diff --git a/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md b/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md index b7734fd8b..2d8186720 100644 --- a/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md +++ b/.claude/skills/morphic-changing-the-ir/references/ir-lessons.md @@ -80,7 +80,7 @@ design. `TestAppendTypeIDs_ReadsWhatTheTypeGraphReads` holds `appendTypeIDs` to `ir.TypeEdges` for a type definition's fields, and nothing holds it for a position only an operation holds. - **Why.** `appendTypeIDs` reads an operation by reflection, so such a position becomes a GraphQL - root and the check on field arguments goes silent on its type, which classifying the position + root and the check on field arguments reports nothing on its type, which classifying the position does not show (#1223). - **Probe.** `git grep -nE 'TypeFor\[(ir\.)?TypeID\]' -- '*.go' ':!*_test.go'` lists the code readers (documents: `references/ir-lessons.md#reference-lists-in-documents`). @@ -299,12 +299,12 @@ design. (`references/ir-lessons.md#disjoint-declarations-take-the-flattening`), while what the member renders as is the taken one. - **Why.** A redaction an overridden declaration asked for was dropped (#1211). On #1700, tag - inference read only the taken declaration, so a body redeclaring the tag as a plain string hid - each variant's pin, and the mapping was keyed by component names (#1704). + inference read only the taken declaration, so a declaration redeclaring the tag as a plain string + hid each variant's pin, and the mapping was keyed by component names (#1704). - **Probe.** Compile a composition that redeclares the member more loosely than what it composes, and read the reader's result. -## Disjoint member declarations take the flattening's winner +## Disjoint member declarations take the flattening's choice `disjoint-declarations-take-the-flattening` - **Rule.** What a flattened member's instance carries conjoins its declarations where they admit a diff --git a/.claude/skills/morphic-checking-style/references/departures.md b/.claude/skills/morphic-checking-style/references/departures.md index 7e9c910a5..621786eec 100644 --- a/.claude/skills/morphic-checking-style/references/departures.md +++ b/.claude/skills/morphic-checking-style/references/departures.md @@ -86,7 +86,7 @@ the rule here rather than reading it across. `ir-shapes-stand` - **Rule.** Rule 5.27 avoids embedding in a public struct. `docs/ir` is normative for - `ir` and stands where the two differ: each type kind embeds `TypeCommon`, and `Header` embeds + `ir` and governs where the two differ: each type kind embeds `TypeCommon`, and `Header` embeds `Property` so the two encode flat as one object. - **Why.** A header's shape was weighed against fields on `Property`, and chosen so that the type states the rule and no check has to (#1144). @@ -108,9 +108,9 @@ the rule here rather than reading it across. - **Rule.** Rule 6.4 bars a project helper that takes `*testing.T` and fails the test itself, test double setup excepted, and rule 6.3 asks `t.Helper()` of every helper. Here a helper asserting - through testify stands and starts with `t.Helper()`, and one a table runs as a case's body needs - no such call: it is the case, and its failure reports its own line (`CONTRIBUTING.md`, "A test is - named for what it tests"). Another assertion library stays barred. + through testify is allowed and starts with `t.Helper()`, and one a table runs as a case's body + needs no such call: it is the case, and its failure reports its own line (`CONTRIBUTING.md`, "A + test is named for what it tests"). Another assertion library stays barred. - **Why.** The rule's concerns are a lost caller's line and a stop at the first failure, which `t.Helper()` and `assert` answer, so rewriting the helpers would add no correctness (#1173). `thelper` reads a signature, so it reported 298 functions and none was a breach (#1178). @@ -120,7 +120,7 @@ the rule here rather than reading it across. `assert-equal-on-plain-values` - **Rule.** Rule 6.16 takes `cmp` for structs, slices, maps and interfaces and bars - `reflect.DeepEqual`, which `assert.Equal` calls. Here `assert.Equal` or `require.Equal` stands on + `reflect.DeepEqual`, which `assert.Equal` calls. Here `assert.Equal` or `require.Equal` applies to a value with no unexported field or `Equal` method, which `cmp` alone calls; any other takes `cmp.Diff` with a direction key (rule 6.15), and no test calls `reflect.DeepEqual`. - **Why.** Such a value lacks the rule's reasons: the two agree on nil against empty, order and NaN, @@ -135,8 +135,8 @@ the rule here rather than reading it across. ## Alias a type to name it at a boundary or to shorten it `type-aliases-that-stand` -- **Rule.** Rule 5.9 keeps type aliases for migration. Three kinds stand here: a public face naming - a type an internal package declares, which no caller outside could name otherwise, as +- **Rule.** Rule 5.9 keeps type aliases for migration. Three kinds are kept here: a public face + naming a type an internal package declares, which no caller outside could name otherwise, as `compilers/openapi/options.go` does; a shape `docs/ir` gives, as `ir.Lifecycle`; and a package's private shorthand for a long type, as `schemaRef`. Any other alias is held to the rule. - **Why.** A defined type in the public face would restate a vocabulary, and two declarations of one diff --git a/.claude/skills/morphic-curating-skills/SKILL.md b/.claude/skills/morphic-curating-skills/SKILL.md index 7d544b72d..bcd1cd551 100644 --- a/.claude/skills/morphic-curating-skills/SKILL.md +++ b/.claude/skills/morphic-curating-skills/SKILL.md @@ -21,7 +21,7 @@ next changes (`references/recorded-lessons.md#recorded-lesson-goes-to-the-skills the lesson applies. If none does, widen a description or add a skill: a rule no trigger reaches is never read. 4. **Not in the repository.** A fact about one machine or person stays out; a shell's documented - default may stand where a command needs it. + default may stay where a command needs it. List the skills with `grep -h '^description:' .claude/skills/*/SKILL.md`, not a hand list. diff --git a/.claude/skills/morphic-curating-skills/scripts/skills_lint.py b/.claude/skills/morphic-curating-skills/scripts/skills_lint.py index fe539d84b..11662bcb5 100755 --- a/.claude/skills/morphic-curating-skills/scripts/skills_lint.py +++ b/.claude/skills/morphic-curating-skills/scripts/skills_lint.py @@ -192,8 +192,8 @@ def go_sources(root: Path) -> Path | None: def path_word(word: str) -> str: """Return what a word of a code span spells, for the checks a one-word span and a command's words share. A double quote, which leaves $GOROOT to expand, is no part of a path wherever it - stands, so "$(go env GOROOT)"/src/... names the toolchain's src; a single quote and a shell's - punctuation around the word are none either. Any other variable keeps its $, which + is written, so "$(go env GOROOT)"/src/... names the toolchain's src; a single quote and a + shell's punctuation around the word are none either. Any other variable keeps its $, which NOT_A_PATH reads: $PWD/ir names no path in the tree.""" word = word.replace('"', "").strip("'();,") return word if word.startswith("$") and not GOROOT_VAR.match(word) else word.strip("$") diff --git a/.claude/skills/morphic-designing-code/SKILL.md b/.claude/skills/morphic-designing-code/SKILL.md index 030b56f4b..79d9c5de5 100644 --- a/.claude/skills/morphic-designing-code/SKILL.md +++ b/.claude/skills/morphic-designing-code/SKILL.md @@ -1,6 +1,6 @@ --- name: morphic-designing-code -description: Use when writing or restructuring production Go code in this repository (a new type, method, package, helper or interface, a walk, index or lookup over a document, a value with a format or a state meaning none, a limit, or code in a shared layer), or before adding or growing a script, prescribed command, CI step, Makefile target or custom check. +description: Use when writing or restructuring production Go code in this repository (a new type, method, package, helper or interface, a walk, index or lookup over a document, a value with a format or a state meaning none, a limit, or code in a shared layer), defining or using a term in a document or comment, or before adding or growing a script, prescribed command, CI step, Makefile target or custom check. --- # Designing morphic code @@ -22,8 +22,8 @@ Each row names a rule and code to copy. | any function | ask what would make it wrong, and refuse that at entry (`CLAUDE.md`, "Assert aggressively") | `Classify` in `compilers/openapi/internal/value/scalar.go` | | work on a path every input takes | ask what it costs before writing it (`.claude/skills/morphic-reviewing-prs/references/performance.md#price-common-path`) | `TestWalkValues_StructsAndMapsCostNoAllocation` | | a lowering, check, pass or helper | `references/design-rules.md#functional-core` | `Read` in `compilers/openapi/internal/annotation/annotation.go` | -| a name | `references/design-rules.md#name-what-it-holds` | `HasFilename` in `ir/operation.go` | -| state every walk of a run must share | `references/design-rules.md#shared-run-state` | `readings` in `compilers/openapi/internal/lowering/lowering.go` | +| a name or a term | `references/design-rules.md#name-what-it-holds`, `references/design-rules.md#one-sense-per-word` | `HasFilename` in `ir/operation.go` | +| state every walk of a run must share | `references/design-rules.md#shared-run-state` | `answerMemos` in `compilers/openapi/internal/lowering/lowering.go` | | a walk, index, lookup or cache over a document | `references/design-rules.md#read-once-per-run`, pruned by `references/design-rules.md#prune-a-visitor-to-its-carriers` | `checkInferred` in `ir/irverify/inferred.go` | | a struct, or a field on one | `references/design-rules.md#fields-in-optimal-size-order` | `HTTPBinding` in `ir/bindings.go` | | a value with a format, or a state meaning none | `references/design-rules.md#type-the-form` | `Limit` in `compilers/openapi/internal/budget/limit.go` | diff --git a/.claude/skills/morphic-designing-code/references/deciding-once.md b/.claude/skills/morphic-designing-code/references/deciding-once.md index 10523dfc6..4d6bb46d8 100644 --- a/.claude/skills/morphic-designing-code/references/deciding-once.md +++ b/.claude/skills/morphic-designing-code/references/deciding-once.md @@ -57,8 +57,8 @@ and how several declarations of one thing fold into it. set before the registry at every later step, and register once after the last step, so only the final node is registered and one no later step keeps never is. - **Why.** A ring of three models each redeclaring `id` as another enum, folded pairwise with each - step registered, ended in `compile/registry-refused` and kept the first fold's `b, c, d` where all - three meet at `c, d` (#2370). + step registered, ended in `compile/registry-refused` and kept the first fold's `b, c, d` where the + intersection of all three is `c, d` (#2370). - **Probe.** `references/deciding-once.md#fold-the-whole-set`'s triple sweep compiles with no `compile/registry-refused` and to one registry; with a plant registering each step's node, it reports that code. diff --git a/.claude/skills/morphic-designing-code/references/design-rules.md b/.claude/skills/morphic-designing-code/references/design-rules.md index 9a0dd478c..43e63ce9e 100644 --- a/.claude/skills/morphic-designing-code/references/design-rules.md +++ b/.claude/skills/morphic-designing-code/references/design-rules.md @@ -139,18 +139,32 @@ and stays simple. Each rule is a cost a later refactor or performance change had `name-what-it-holds` - **Rule.** A name is long, literal and plain: the specification's term where it has one - (`foldingAllOfEntries`, not `voicesAmong`), the kind of thing it declares (`Measurements`, not - an `Index` that indexes nothing), a question for a bool (`HasFilename`), and its type's noun for a + (`allOfEntryFoldingOf`, not `voicesAmong`), the kind it declares (`Measurements`, not an + `Index` that indexes nothing), a question for a bool (`HasFilename`), and its type's noun for a parameter (`schema`, not `s`). One letter names only a loop counter, a receiver, a comparison pair or a standard-library convention (`t *testing.T`). A figurative word, an abbreviation or a - noun another package uses otherwise is renamed, not explained in a doc comment, but a normative - document's term stays, figurative or not - (`references/design-rules.md#normative-term-outranks-figurative`). + noun another package uses otherwise is renamed, not explained in a doc comment + (`references/design-rules.md#one-sense-per-word`), but a normative document's term stays, + figurative or not (`references/design-rules.md#normative-term-outranks-figurative`). - **Why.** Names that needed their comments, and comments that needed other coined names, left the code and the compiled IR unreadable to their owner (#2130). - **Probe.** `references/design-rules.md#one-letter-names-by-kind` lists a change's one-letter names, and `references/design-rules.md#read-each-declared-name` reads the rest. +## Keep each defined word to the one sense its glossary gives it +`one-sense-per-word` + +- **Rule.** A word that `docs/ir/README.md#words`, or the table of words the rules use opening + `docs/compilers/openapi.md`, defines keeps that sense in code, comments and documents. A change + needing a new term adds it to the table in the same change. A word the table retires is not + written again, bar a diagnostic code, rule key or code name that keeps it. +- **Why.** At 7ac4686c7 (#2354), `docs/compilers/openapi.md` wrote *entry* for an `allOf` element + and for an Unmodeled entry and *stand* in several senses, and the schema code's comments coined + *voice* and *ledger*, which no document defined. +- **Probe.** This lists a change's added lines writing a retired word, each read for a code name + or key: + `git diff origin/main -U0 | grep -E '^\+[^+]' | grep -iwE 'stand(s|ing)?|voices?|claims?|ledgers?|elect(s|ed|ion)?|beats?|winners?|losers?|keepers?|meets?|joins?|silent|inert|verdicts?'`. + ## Read each name a change declares against what it holds `read-each-declared-name` @@ -290,13 +304,13 @@ and stays simple. Each rule is a cost a later refactor or performance change had (`.claude/skills/morphic-checking-style/references/departures.md#bounded-recursion-stands`); whether the pin covers other packages is #1525. -## Hold each part of a charge to the cost it stands for +## Hold each part of a charge to the cost it represents `charge-each-part-to-its-cost` - **Rule.** For each part of what a bound's charge weighs, grow that part alone, on `main` and on the branch. A charge growing while the cost stays flat refuses a valid document for nothing, and a cost growing while the charge stays flat is a copy left unbounded. Read a survey of cost per - unit of charge at both ends: the low end is a charge standing for almost no cost. + unit of charge at both ends: the low end is a charge representing almost no cost. - **Why.** A `$ref` budget's first revision charged at every use a response's inline schema, which lowers once, refusing 400 `$ref`s `main` compiles, and charged nothing for an alias's own fields, which copy at every use, through four rounds reading the survey's high end (#1430). @@ -339,12 +353,12 @@ and stays simple. Each rule is a cost a later refactor or performance change had it does not read) was chosen for, and the caller's. Where the fallback is unsafe for the caller, the reader reports that it fell back, as `Budget.Exhausted` reports a cut, and the caller takes its own safe answer. -- **Why.** `conjunctTypes` answers `anyInstance` for what it skips, keeping - `allof-disjoint-conjuncts` silent. #1656 reused it as `Merger.Untyped` (now `Walk.Untyped`), where - `anyInstance` let `{allOf: [{$ref: NotStr}], properties: …}` beside `{type: string}` lower to a - bare string past three rounds (#1673). +- **Why.** `conjunctTypes` answers `anyInstance` for what it skips, so + `allof-disjoint-conjuncts` reports nothing. #1656 reused it as `Merger.Untyped` (now + `Walk.Untyped`), where `anyInstance` let `{allOf: [{$ref: NotStr}], properties: …}` beside + `{type: string}` lower to a bare string past three rounds (#1673). - **Probe.** Through the new caller, compile one input per construct the reader does not read - (`references/design-rules.md#reused-reader-past-its-bound`), checking each verdict against the + (`references/design-rules.md#reused-reader-past-its-bound`), checking each answer against the source. ## Probe a reused reader past every bound it holds @@ -355,7 +369,7 @@ and stays simple. Each rule is a cost a later refactor or performance change had - **Why.** On #1977, reusing the 64-type composition walk missed a 65-level hierarchy taking the base's description over the leaf's through eight review rounds (#1983). - **Probe.** Through the new caller, compile inputs at N and N+1 of each bound the reader holds and - check each verdict against the source. + check each answer against the source. ## Keep code that needs no morphic concept apart from the domain `domain-free-code-lives-apart` diff --git a/.claude/skills/morphic-measuring-performance/references/finding-cost.md b/.claude/skills/morphic-measuring-performance/references/finding-cost.md index d3290b5da..5d2af7397 100644 --- a/.claude/skills/morphic-measuring-performance/references/finding-cost.md +++ b/.claude/skills/morphic-measuring-performance/references/finding-cost.md @@ -112,8 +112,8 @@ Reading the code shows neither a quadratic loop nor an escape. These rules say w input measures one arm. Generate an input per arm, quote the range rather than one figure, and name any arm left out with the reason: reading does not find the dear one. - **Why.** A PR read every enum member through a switch on primitive kind, and one figure, 2.1%, - stood for every format. Measured per format, `uuid` added 0.15% and `double` 35.45%, by rebuilding - a constant on each call (#1191, #1205). + was taken for every format. Measured per format, `uuid` added 0.15% and `double` 35.45%, by + rebuilding a constant on each call (#1191, #1205). - **Probe.** List each arm with the input that reached it, and take each arm's instructions on both builds (`references/reading-a-run.md#instructions-not-wall-clock`). diff --git a/.claude/skills/morphic-measuring-performance/references/reading-a-run.md b/.claude/skills/morphic-measuring-performance/references/reading-a-run.md index 2b01b341e..3b6793ae7 100644 --- a/.claude/skills/morphic-measuring-performance/references/reading-a-run.md +++ b/.claude/skills/morphic-measuring-performance/references/reading-a-run.md @@ -79,7 +79,7 @@ which of them to keep. `references/finding-cost.md` says where to look for the c - **Rule.** On a host with neither `/usr/bin/time -l` nor `perf`, run base and head alternately and compare the user plus sys seconds of `bash -c 'time -p compile '`, saying that is what - was measured. A benchmark is no stand-in for a claim about a spec: `go test -bench` reports wall + was measured. A benchmark is no substitute for a claim about a spec: `go test -bench` reports wall clock, which load skews, and each one reads the fixtures it names. - **Why.** A Linux host with no `perf` left a review of a cost claim no instrument (#1162). - **Probe.** `command -v perf`, then each side's range from the alternated runs against the gap. @@ -148,7 +148,7 @@ which of them to keep. `references/finding-cost.md` says where to look for the c to 39 M above their later runs (#2360), and binaries unused twelve minutes at load 85, under 100 MB free, 69 to 70 M (#2379). - **Probe.** Copy the binary with `cp`, then run the measuring command three times on the copy: the - first count stands out. + first count is well above the rest. ## Keep a collector-off reading only from a run that held its allocation `collector-off-run-held` diff --git a/.claude/skills/morphic-openapi-compiler/references/lossless-and-diagnostics.md b/.claude/skills/morphic-openapi-compiler/references/lossless-and-diagnostics.md index 0a66bd9ef..e2e4384e6 100644 --- a/.claude/skills/morphic-openapi-compiler/references/lossless-and-diagnostics.md +++ b/.claude/skills/morphic-openapi-compiler/references/lossless-and-diagnostics.md @@ -66,8 +66,8 @@ and every diagnostic is true, located, and decided from what actually happened. byte-identical IR with or without them, breaking lossless-by-default with a clean exit (#345, #348); a rebuilt check flagged nothing while `Sources` held each text's hash (#1217). - **Probe.** For each keyword in the vocabulary, compile two specs differing only in it and diff the - IR, `Sources` cleared, and diagnostics; byte-identical output is a silent drop, which `$comment`, - dropped by rule, must show. Enumerate the keywords from the source schema. + IR, `Sources` cleared, and diagnostics; byte-identical output is an unreported drop, which + `$comment`, dropped by rule, must show. Enumerate the keywords from the source schema. ## Compile each draft spelling beside its 2020-12 twin at every position `draft-spelling-beside-its-twin` @@ -125,13 +125,13 @@ and every diagnostic is true, located, and decided from what actually happened. map, needs an explicit rule for every field of the struct; never keep one side wholesale, never assign a zero value over another source's value, and never skip a shared-map write because some other construct already holds the key. -- **Why.** Reconciliation kept the first allOf branch's constraints and visibility wholesale, so the +- **Why.** Reconciliation took the first allOf branch's constraints and visibility wholesale, so the result depended on branch order and later branches' keywords vanished with no diagnostic (#8, #92). - **Probe.** List the struct's fields beside the merge and point at the rule for each; then compile complementary keys from each side in both declaration orders and cmp.Diff the documents. -## Pair every new check with must-stay-silent fixtures for valid input +## Pair every new check with must-report-nothing fixtures for valid input `check-stays-silent-on-valid-input` - **Rule.** A conflict detector, refusal or structural guard must flag only what it can prove wrong: @@ -142,9 +142,9 @@ and every diagnostic is true, located, and decided from what actually happened. - **Why.** New checks rejected legal multipart bodies and valid 3.0 boolean bounds, and warned on allOf narrowings that are satisfiable (#149, #92). A sniff of a bounded prefix refused a longer flow-style spec (#341). -- **Probe.** For each check write a must-fire and a must-stay-silent fixture, including alias/$ref - indirection, every valid spec-version spelling and a valid input past each shortcut's bound, then - run morphic-harness over testdata and require no new diagnostics. +- **Probe.** For each check write a must-fire and a must-report-nothing fixture, including + alias/$ref indirection, every valid spec-version spelling and a valid input past each shortcut's + bound, then run morphic-harness over testdata and require no new diagnostics. ## Decode into a pointer when a guard must tell null from a value `null-decodes-to-zero` @@ -296,9 +296,9 @@ and every diagnostic is true, located, and decided from what actually happened. `keyword-placement-path-independent` - **Rule.** When the same keyword or annotation can reach the IR through several lowerings or past a - dedup guard, its placement must not depend on the path; a guard deciding to skip residue may only - run after confirming the data has a home elsewhere. -- **Why.** Visibility residue was dropped exactly for parameters whose schema owns a node, and a + dedup guard, its placement must not depend on the path; a guard deciding to skip what is left over + may only run after confirming the data has a home elsewhere. +- **Why.** Leftover visibility was dropped exactly for parameters whose schema owns a node, and a constraint beside allOf went to Unmodeled while beside properties it went to Constraints, defeating lossless capture (#149, #363). - **Probe.** Compile the keyword beside every container shape (properties, allOf, $ref, parameter diff --git a/.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md b/.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md index c50b49024..4d632a30c 100644 --- a/.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md +++ b/.claude/skills/morphic-openapi-compiler/references/openapi-lessons.md @@ -82,7 +82,7 @@ canary. A behaviour found that the page lacks is added there. resolver makes its call. - **Why.** Each miss of a reach check was a re-derived reading (#563). `View` and the resolver disagree on a duplicate key (#763, `docs/parser-library.md#duplicate-key`). #1278 widened an - allowlist for `yml`, no rule saying whether a wrapper should stand instead. + allowlist for `yml`, no rule saying whether a wrapper should be used instead. - **Probe.** Generate documents with percent-encoding, a second `#`, `.` and `..`, aliases and `<<`, and run each through the raw resolver in a bounded subprocess. @@ -361,8 +361,9 @@ canary. A behaviour found that the page lacks is added there. it in its statement's `Schema.Ref`, outside its `Entries`, so a walk reading `Entries` alone stops at `R: {$ref: T}` and never reaches `T`. Until the schema cases write the chain (#2404), test it beside its one-hop twin (`references/lossless-and-diagnostics.md#reference-chain-beside-its-twin`). -- **Why.** An unevaluated keyword's reach walked `Entries` alone, so `allOf: [$ref: R]`, with `R` - only a `$ref` to a schema writing `if`, lowered closed while its one-hop twin was kept (#2372). +- **Why.** The walk finding the keyword scope of an unevaluated keyword read `Entries` alone, so + `allOf: [$ref: R]`, with `R` only a `$ref` to a schema writing `if`, lowered closed while its + one-hop twin was kept (#2372). - **Probe.** Compile #2372's `OneHop` and `TwoHop` schemas and compare their `additional` and `unmodeled` members. diff --git a/.claude/skills/morphic-planning-work/references/large-changes.md b/.claude/skills/morphic-planning-work/references/large-changes.md index 02fe1dcea..c082acdf0 100644 --- a/.claude/skills/morphic-planning-work/references/large-changes.md +++ b/.claude/skills/morphic-planning-work/references/large-changes.md @@ -184,7 +184,7 @@ ones. - **Rule.** Before pull requests in neighbouring areas start, the plan names one owner for each field, diagnostic code, option and file two of them read or write; the others build on the owner's branch or wait for its merge, and none copies the owner's file. -- **Why.** Pull requests in neighbouring areas settled shared questions apart, each defect silent +- **Why.** Pull requests in neighbouring areas settled shared questions apart, each defect hidden until both were built, and #1809 and #1819 each copied a file from #1813 byte for byte (#1918, #1809). - **Probe.** For each pair of the plan's open pull requests, `git diff --name-only origin/main...` @@ -212,9 +212,9 @@ ones. - **Rule.** Pull requests that read or write one fact are reviewed on their trial merge before either lands, or become one: reviewed apart, a defect only their merged build shows passes both. -- **Why.** A review of eleven open pull requests found defects only their merged build showed, silent - in another merge order (#1809, #1810, #1813), and the merge train found more (#1840 with #1819, - #1846 with #1833). +- **Why.** A review of eleven open pull requests found defects only their merged build showed, + hidden in another merge order (#1809, #1810, #1813), and the merge train found more (#1840 with + #1819, #1846 with #1833). - **Probe.** For each pair of the plan's open pull requests reading or writing one fact, the angles run on a worktree of their trial merge, confirmed by `.claude/skills/morphic-shipping-prs/references/merging-main.md#trial-merge-happened` and built by diff --git a/.claude/skills/morphic-reviewing-prs/SKILL.md b/.claude/skills/morphic-reviewing-prs/SKILL.md index 59d183bb2..c2e7c5f87 100644 --- a/.claude/skills/morphic-reviewing-prs/SKILL.md +++ b/.claude/skills/morphic-reviewing-prs/SKILL.md @@ -42,7 +42,7 @@ a line saying why. (`references/rounds.md#first-round-finds-everything`), then what moved (`references/later-rounds.md#later-rounds-read-what-moved`, `references/later-rounds.md#nit-round-checks-its-fixes`). -4. **Standing reviews**, after the first round's angles +4. **Posted reviews**, after the first round's angles (`references/rounds.md#read-standing-reviews`). 5. **Fixes**, when the review fixes (its own PR, or asked): each designed first (`references/rounds.md#design-the-fix-first`) and reviewed before it leaves diff --git a/.claude/skills/morphic-reviewing-prs/references/design.md b/.claude/skills/morphic-reviewing-prs/references/design.md index b4b039169..d44c42639 100644 --- a/.claude/skills/morphic-reviewing-prs/references/design.md +++ b/.claude/skills/morphic-reviewing-prs/references/design.md @@ -96,7 +96,7 @@ the run measuring it. replaces this repository's module with the tree under review. Run both programs over compiled specs, a plant showing each reacts, and read each item they disagree on against the document. - **Why.** Rerunning the author's program reproduced its count, and one written from the document - did not (#1356). A flattening written by hand kept a member's first declaration and counted 2,039 + did not (#1356). A flattening written by hand took a member's first declaration and counted 2,039 enveloped bodies leaving `result` optional or nullable, where `ir.FlattenedProperties` gives 1,418 (#1356). - **Probe.** The report names each item the programs disagree on, or says they agree on every one. diff --git a/.claude/skills/morphic-reviewing-prs/references/determinism.md b/.claude/skills/morphic-reviewing-prs/references/determinism.md index f2d07a4c2..0f7be829f 100644 --- a/.claude/skills/morphic-reviewing-prs/references/determinism.md +++ b/.claude/skills/morphic-reviewing-prs/references/determinism.md @@ -78,7 +78,7 @@ The matrix is each construct and fact by order and limit, with the diff each pro model's mixins or a union's variants, a two-order fixture gives that sequence at least two elements, ordered differently in the inputs, and the probe reads the result's order in both declaration orders. -- **Why.** #1656 builds the enum two meeting enums share, in the order the winner lists its +- **Why.** #1656 builds the enum two intersecting enums share, in the order the chosen one lists its members. Its two-order checks met `[a, b]` beside `[b, c]`, which give `[b]` either way, so `[a, b, c]` beside `[c, b, d]` giving `[b, c]` or `[c, b]` by branch order passed those checks and the order oracle, which then reversed mappings only (#1666, #1674). diff --git a/.claude/skills/morphic-reviewing-prs/references/reuse.md b/.claude/skills/morphic-reviewing-prs/references/reuse.md index 79317fc34..6e72a074e 100644 --- a/.claude/skills/morphic-reviewing-prs/references/reuse.md +++ b/.claude/skills/morphic-reviewing-prs/references/reuse.md @@ -56,7 +56,7 @@ each addition with what each search returned. codec or a file write, look for a maintained library owning it: the standard library, `golang.org/x`, `go.mod`'s modules, then a new one. Adopt one a probe shows doing the job on every input the piece meets, whose license and upkeep fit, and which the layering admits (`ir/` - imports the standard library alone). Pin each behaviour relied on with a test, as + imports only standard-library and Layer-0 packages). Pin each behaviour relied on with a test, as `docs/parser-library.md` pins the parser library. - **Why.** Hand-written pointer decoding gave way to `jsontext.Pointer` (#834) and file replacement to `renameio` (#1009), while the parser library's unbounded `$ref` recursion came back into the diff --git a/.claude/skills/morphic-reviewing-prs/references/robustness.md b/.claude/skills/morphic-reviewing-prs/references/robustness.md index 26d5b6178..251b0f2a7 100644 --- a/.claude/skills/morphic-reviewing-prs/references/robustness.md +++ b/.claude/skills/morphic-reviewing-prs/references/robustness.md @@ -8,7 +8,7 @@ allows. It loads `morphic-designing-code` and `morphic-measuring-performance`. 1. Name the limit on each loop, recursion, queue, buffer and retry the change adds, in code or in a rule a design document states, and what the work grows with under it (`.claude/skills/morphic-designing-code/references/design-rules.md#bound-the-product`), each part - of its charge held to the cost it stands for + of its charge held to the cost it represents (`.claude/skills/morphic-designing-code/references/design-rules.md#charge-each-part-to-its-cost`). In the OpenAPI compiler a count held to a limit counts through `compilers/openapi/internal/budget` (`CLAUDE.md`, "Bounded everything"), and its outcome comes diff --git a/.claude/skills/morphic-reviewing-prs/references/rounds.md b/.claude/skills/morphic-reviewing-prs/references/rounds.md index 1939c53c2..feec16dfe 100644 --- a/.claude/skills/morphic-reviewing-prs/references/rounds.md +++ b/.claude/skills/morphic-reviewing-prs/references/rounds.md @@ -246,7 +246,7 @@ narrowed: , , , , '` for each PR the merge brought in. diff --git a/.claude/skills/morphic-verifying-changes/references/assertions-and-reach.md b/.claude/skills/morphic-verifying-changes/references/assertions-and-reach.md index eeaab3d2a..4346019cc 100644 --- a/.claude/skills/morphic-verifying-changes/references/assertions-and-reach.md +++ b/.claude/skills/morphic-verifying-changes/references/assertions-and-reach.md @@ -55,10 +55,10 @@ it. `test-guards-fail-closed` - **Rule.** A guard over declarations, a self-check, a glob, a fixture path or an oracle that can - decline fails on input it cannot classify or find: no silent skip of unparsed spellings or - aliases, no log-only self-check, no glob matching nothing, no `t.Skip` on a missing fixture in a - gate run, no oracle returning ok without comparing, no case expecting failure that does not - first assert its fixture exists. + decline fails on input it cannot classify or find: no skip that reports nothing of unparsed + spellings or aliases, no log-only self-check, no glob matching nothing, no `t.Skip` on a missing + fixture in a gate run, no oracle returning ok without comparing, no case expecting failure that + does not first assert its fixture exists. - **Why.** Const-block guards skipped conversions and aliases, a benchmark read a missing path and exited 0, the order oracle returned ok without comparing on anchor-bearing specs, and a misspelt fixture satisfied a "fails" case (#111, #344, #381). @@ -69,7 +69,7 @@ it. `compile-through-a-verifying-helper` - **Rule.** An end-to-end lowering test compiles through a helper that holds the document to - `irverify` (`compileVerified`, `requireVerifies` in `compilers/openapi/e2e`). This rule stands + `irverify` (`compileVerified`, `requireVerifies` in `compilers/openapi/e2e`). This rule holds until #2288's check lands. - **Why.** At #1937's `32bda46d9`, six helpers returned `Compile` output without verification, letting a lowering test pass on a document `irverify` rejects (#1966). @@ -81,11 +81,11 @@ it. - **Rule.** A check telling two things apart by a property matters only where what it compares depends on that property, as text does on a base only through a relative reference. Compile a - fixture with the dependent deleted, moved outside what it compares, and made inert (an absolute - `$ref`), on `origin/main` and the branch: documents and diagnostics match unless the change says - why not. The probe matches `main` by design, so its control is a build whose check fires without - the dependency, which must differ (`references/differentials.md#planted-control`). Test rows - pin each form. + fixture with the dependent deleted, moved outside what it compares, and made irrelevant (an + absolute `$ref`), on `origin/main` and the branch: documents and diagnostics match unless the + change says why not. The probe matches `main` by design, so its control is a build whose check + fires without the dependency, which must differ (`references/differentials.md#planted-control`). + Test rows pin each form. - **Why.** #1406's checks at a4dda68a fired on text under another `$id`, and every spec testing them wrote a `$ref`: types lost the `minLength` of an `allOf` branch writing none, and the `description` of one whose `$ref` sat in `properties` or, at 1855a63f9, was absolute. @@ -124,8 +124,8 @@ it. only Len, digest length, the entry's existence, that nothing panicked, that the outcome is not X, or count-plus-membership (each expected key exactly once), and never a compiled value discarded with _ =. A proxy that a wrong value also satisfies asserts nothing. -- **Why.** Wrong example values, dangling derived keys, path-derived hashes and empty stand-ins for - skipped refs all passed tests that checked only count, existence, length or no-panic (#222). +- **Why.** Wrong example values, dangling derived keys, path-derived hashes and empty substitutes + for skipped refs all passed tests that checked only count, existence, length or no-panic (#222). - **Probe.** For each assertion, plant a mutant that keeps the proxy true but changes the value (wrong example, different key, fresh hash, duplicate at one key and none at another) and confirm the test reddens; grep tests for `_ = ` on compiled results. diff --git a/.claude/skills/morphic-verifying-changes/references/checkers.md b/.claude/skills/morphic-verifying-changes/references/checkers.md index 1956c5516..61ebd6cbb 100644 --- a/.claude/skills/morphic-verifying-changes/references/checkers.md +++ b/.claude/skills/morphic-verifying-changes/references/checkers.md @@ -24,7 +24,7 @@ own verifier and codecs are in - **Rule.** Cross each form `references/checkers.md#source-scanners-match-every-form` lists with each route the check follows to it: directly, through an alias, and inside another form, as a - walk can stop early. Plant every sibling a branch lists, not one standing for the rest. Key on + walk can stop early. Plant every sibling a branch lists, not one taken for the rest. Key on go/types over selectors. Where the plants may stop is `references/mutation.md#plants-stop-at-a-held-grid`. - **Why.** A fixture planted `delete`, `clear`, `copy` and `append` directly and only `delete` diff --git a/.claude/skills/morphic-verifying-changes/references/claims.md b/.claude/skills/morphic-verifying-changes/references/claims.md index af8e57ed5..dafafc3e5 100644 --- a/.claude/skills/morphic-verifying-changes/references/claims.md +++ b/.claude/skills/morphic-verifying-changes/references/claims.md @@ -13,7 +13,7 @@ to read — and to execute outside the case its author measured. `references/claims.md#set-claims-diff-the-set`. - **Why.** "Read by nothing" was written while `constraints.go` read the field, and "never reports a spec-level problem" over paths that do (#111, #190). A body's "a change that adds one now fails a - test" held for no union whose branches stand alone (#1514, #1594). + test" held for no union whose branches are self-contained (#1514, #1594). - **Probe.** List the sites mechanically (writers by `git grep`, callers, return statements, composition positions) and compile one input per site, reading every diagnostic. @@ -163,8 +163,8 @@ to read — and to execute outside the case its author measured. fixed point or a sort is stable is checked in each direction it can fail: lost, won and unknown; equal keys; each gate condition of the source. A derived gate reuses the source's result rather than a copied test. -- **Why.** A family winning an election was dropped silently, `sort.Slice` broke a promised stable - order, and a copied memo gate dropped a condition (#270, #379). +- **Why.** A family chosen over the others was dropped silently, `sort.Slice` broke a promised + stable order, and a copied memo gate dropped a condition (#270, #379). - **Probe.** Write one case per direction; for neutrality, run old and new over the corpus and diff the IR, and where a report moved, its order (`.claude/skills/morphic-reviewing-prs/references/correctness.md#moved-report-order`). @@ -249,7 +249,7 @@ to read — and to execute outside the case its author measured. - **Rule.** When a comment says something propagates automatically, that a measurement proves a property, that a check deliberately stops at a boundary, or that a known-wrong answer is left - standing, add a test that fails if that statement stops being true (pin the known-wrong answer in + in place, add a test that fails if that statement stops being true (pin the known-wrong answer in a row naming its issue). - **Why.** Unenforced claims rot silently: widening a check's scope or breaking the described wiring leaves every test green, and a benchmark no CI job runs checks nothing (#111, #361). diff --git a/.claude/skills/morphic-verifying-changes/references/mutation.md b/.claude/skills/morphic-verifying-changes/references/mutation.md index 35301d30e..b30c72247 100644 --- a/.claude/skills/morphic-verifying-changes/references/mutation.md +++ b/.claude/skills/morphic-verifying-changes/references/mutation.md @@ -240,7 +240,7 @@ yourself. These rules are the ways that reading still lies. - **Why.** Six at once took 48 to 121 s a plant on a loaded machine (#1216), and a `//nolint` line and a new `TypeKind` each passed through an overlay and failed on disk (#1216). - **Probe.** Plant `//nolint:errcheck` above `package pass` in `pass/doc.go` through an overlay: - `TestSuppressions_NoDirectiveStandsInTheSource` passes, and fails with the same line on disk. + `TestSuppressions_NoDirectiveRemainsInTheSource` passes, and fails with the same line on disk. ## Plant, swap or add through an overlay before a copy `overlay-before-a-copy` diff --git a/.claude/skills/morphic-verifying-changes/references/tests-that-bite.md b/.claude/skills/morphic-verifying-changes/references/tests-that-bite.md index 90c1042fc..b5c537a73 100644 --- a/.claude/skills/morphic-verifying-changes/references/tests-that-bite.md +++ b/.claude/skills/morphic-verifying-changes/references/tests-that-bite.md @@ -159,7 +159,7 @@ is not behaviour held. - **Rule.** A test of what follows a time limit raises the limit's outcome itself, through a seam or a patched call, and leaves a real limit to a test asserting only that the limit fired. A real limit raced against a child starting passes or fails by the machine's load. -- **Why.** A test giving a stand-in one second to start, print and sleep passed alone and failed +- **Why.** A test giving a stub one second to start, print and sleep passed alone and failed seven of eight runs with copies of the suite running beside it (#1210). - **Probe.** Run the suite in six concurrent copies; each passes. @@ -214,16 +214,16 @@ is not behaviour held. killed all three (#1145). - **Probe.** The plant, run against the random test alone. -## Test an API not built yet against a stand-in that builds +## Test an API not built yet against a stub that builds `test-first-against-a-stand-in` -- **Rule.** Declare the planned signature first, as a stand-in that builds and returns zero values +- **Rule.** Declare the planned signature first, as a stub that builds and returns zero values or an error saying it is not built, so the tests' red is `--- FAIL` naming each, not a build failure (`references/mutation.md#read-the-kill-in-the-output`). Until its caller lands, it takes - an `apiRoots` entry (`CONTRIBUTING.md`'s "Code only tests call is test code"). The stand-in and + an `apiRoots` entry (`CONTRIBUTING.md`'s "Code only tests call is test code"). The stub and its tests may be one commit that builds and vets with only those tests failing, pushed only with the commit filling it, never merged unfilled. - **Why.** A builder given a plan naming an unbuilt API settled alone where its tests live, what they build against and what counts as red (#2364). -- **Probe.** At the stand-in's commit, `go vet` passes and `go test -run ''` prints +- **Probe.** At the stub's commit, `go vet` passes and `go test -run ''` prints `--- FAIL` for each, no `[build failed]`; at the fill's, they pass. diff --git a/.claude/skills/morphic-verifying-changes/scripts/sweep.py b/.claude/skills/morphic-verifying-changes/scripts/sweep.py index 38b105042..603967e04 100755 --- a/.claude/skills/morphic-verifying-changes/scripts/sweep.py +++ b/.claude/skills/morphic-verifying-changes/scripts/sweep.py @@ -177,7 +177,7 @@ def one(item): unkept = keep(out / "runs" / str(n), b, h) if what not in ("", STAMP_ALONE) else "" return Result(n, spec, (b.code, h.code), (len(b.ir), len(h.ir)), what, stamps, unkept) - # A number names another spec once the corpus changes, so no earlier run's pair may stand. + # A number names another spec once the corpus changes, so no earlier run's pair may be kept. shutil.rmtree(out / "runs", ignore_errors=True) with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: return list(pool.map(one, enumerate(specs, 1))) diff --git a/.claude/skills/morphic-verifying-changes/scripts/test_sweep.py b/.claude/skills/morphic-verifying-changes/scripts/test_sweep.py index c38843105..1f45a60e2 100644 --- a/.claude/skills/morphic-verifying-changes/scripts/test_sweep.py +++ b/.claude/skills/morphic-verifying-changes/scripts/test_sweep.py @@ -19,7 +19,7 @@ HERE = Path(__file__).resolve().parent -# A stand-in for cmd/morphic: prints IR naming its side, and differs or hangs where told to. +# A stub for cmd/morphic: prints IR naming its side, and differs or hangs where told to. FAKE = """#!{python} import sys, time spec = open(sys.argv[-1]).read() @@ -276,7 +276,7 @@ def test_a_table_that_cannot_be_written_leaves_what_was_found(self): self.assertIn(" 1 corpus/changed.yaml: ir\n", text) -# A stand-in that opens its document with a version of its own, as cmd/morphic does: "moved" changes +# A stub that opens its document with a version of its own, as cmd/morphic does: "moved" changes # the head's IR, "diag" its diagnostics, "late" puts the version past the first member, "gone" has # the head write nothing, and "failed" has neither side write a document. STAMPED = """#!{python} @@ -384,7 +384,7 @@ def test_an_empty_stamp_still_differs_from_another(self): self.assertEqual(sweep.difference(empty, stamped), (sweep.STAMP_ALONE, ("", "1"))) -# A go that fails every build, and one whose build writes a stand-in for cmd/morphic that prints +# A go that fails every build, and one whose build writes a stub for cmd/morphic that prints # the same IR for every spec. FAILING_GO = "#!/bin/sh\necho 'no build here' >&2\nexit 1\n" BUILDING_GO = ('#!/bin/sh\nwhile [ "$1" != "-o" ]; do shift; done\n' diff --git a/.github/workflows/gate.yml b/.github/workflows/gate.yml index dcb98e927..0a6d5e84f 100644 --- a/.github/workflows/gate.yml +++ b/.github/workflows/gate.yml @@ -128,7 +128,7 @@ jobs: name: race detector if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest - timeout-minutes: 80 + timeout-minutes: 120 permissions: actions: read contents: read @@ -182,7 +182,7 @@ jobs: - name: cases id: cases if: ${{ !cancelled() && steps.moved.outputs.run == 'true' && steps.build.outcome == 'success' }} - timeout-minutes: 20 + timeout-minutes: 45 shell: bash run: make cases 2>&1 | tee cases.log # A failed cases step is reported under its own title, and every other diff --git a/CLAUDE.md b/CLAUDE.md index 8321f0375..9a253c9d4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -176,10 +176,16 @@ scratchstate/ map both checkers empty between collections. Imports ONLY the stdlib. pathfold/ Layer 0 — the fold a file system compares paths by, and what makes a path segment portable. Imports golang.org/x/text only. -ir/ Layer 0 — IR nodes, IDs, traversal, editing, JSON round-trip. Imports ONLY the stdlib. +stronglyconnected/ + Layer 0 — Tarjan's search for a directed graph's strongly connected components, + on stacks of its own. Imports ONLY the stdlib. +rfc3339/ Layer 0 — the RFC 3339 time and date-time texts, read by their grammar. Imports + ONLY the stdlib. +ir/ Layer 0 — IR nodes, IDs, traversal, editing, JSON round-trip. Imports the stdlib, + stronglyconnected and rfc3339 only. irfacts/ Layer 0 — what a Document implies and does not state (subtypes, exposed properties, usage, recursion, correlation keys), derived on demand and never stored. Imports - ir only. + ir and stronglyconnected only. irverify/ Layer 0 — structural-invariant checks over a compiled Document. Imports ir and scratchstate. irtest/ Layer 0 — golden-file helper (`-update` rewrites) and fixture helpers. Imports ir + go-cmp. compilers/ Layer 1 — the Compiler contract and the format-keyed registry. Imports ir and barrier. @@ -324,15 +330,24 @@ These all exist already — extend them rather than building a parallel mechanis separate from `ir.Diagnostic`, which reports problems in the source spec. - **Case oracles**: `internal/harness/openapicases` writes the OpenAPI compiler's schema cases, one document per case, as products of axes its `Axes` names: version, target schema, construct (each - keyword of the rule table at two values), a second construct (`none` at the core, outside it a - keyword written in one unit with the first), position and spelling, and the JSON Schema Test - Suite's groups written as defaults. `internal/harness`'s case - oracles judge each case, the first two against a neighbour: spelling (a use spelt another way - lowers alike, up to decorators), presence (a keyword changes what compiles, and again when its + keyword of the rule table at two values), a second construct (`none` at the core, outside it + another keyword written with the first), position and spelling, and the JSON Schema Test Suite's + groups written as defaults. Most spellings write a use of the target `T` with the case's keywords + moved as one unit, as `{$ref: T, K}` or `{allOf: [{$ref: T}, {K}]}`. The body-split spellings + write the target's own keywords split across `allOf` entries, and must lower as those keywords + written flat do. + The apart spellings, outside the core, put the construct and the second construct apart, one + beside the `allOf` and one on an entry, and must lower as the two written together do. + Its `spellings.go` lists them all. Leaving the construct out can leave a case of another + spelling, as it does for an apart spelling, and the presence oracle then compares the two + relocated, as the spelling oracle compares a spelling with its partner + (`CaseDocument.RelocateAbsent`). `internal/harness`'s case oracles judge each case, + the first two against a neighbour: spelling (a use spelt another way lowers alike, up to + decorators), presence (a keyword changes what compiles, and again when its value changes, unless it says why nothing carries it) and instance (the suite's valid instances - are admitted, except that an instance of another kind than a node the compiler marked - `kind-inference` is excused: that policy, on by default, narrows a schema naming no kind to one, - and the suite's groups compile under it). The gate checks the core cases, each axis value whose + are admitted; the validate pass leaves alone a value of another kind than a node a heuristic + shaped, at any depth, as the `kind-inference` policy, on by default, narrows a schema naming no + kind to one, and the suite's groups compile under it). The gate checks the core cases, each axis value whose `Like` is empty, in `go test ./internal/harness/openapicases`; `make cases` checks every case, as the nightly job does, and `go run ./cmd/morphic-harness -cases full -case-index N` reproduces one by index. A case is written to compile: an oracle declining one for an error diagnostic, the spelling oracle where @@ -397,24 +412,35 @@ assertion shapes: alone. The sequence-order oracle beside it reverses each `allOf` and `required` sequence that `reverseSequences` in `internal/harness/sequence.go` may, and forgives what the order oracle does and what `canonicalForm` in `canon.go` lists, and a tie the compiler states: a member that a - report carrying a pair (`ir.RelatedKept`, `ir.RelatedDecided`) decides in each order, the two + report carrying a pair (`ir.RelatedChosen`, `ir.RelatedDecided`) decides in each order, the two places the other way round and the two reports alike but for them (`tiedBy` in `ties.go`), each - member settled from one, each node a tied member's fold mints where it stands or at a position - beneath it the fold builds a member at (`minted` in `canon.go`), each anonymous node present in + member settled from one, a model's own member overriding a tied declaration among them, as one + composing a tied member's model does (the tie's cascade through composition, `settledFrom` in + `sequenceorder.go`), each node a tied member's fold mints by its composed key, at the + member's pointer or at the fold's key, or at a position beneath either the fold builds a member at + (`minted` in `canon.go`), each anonymous node present in only one order that is reachable through anonymous types from a tied member (`prunedByTie` in - `sequenceorder.go`), and all at or beneath a report the reversal moves that carries no pair. Of a + `sequenceorder.go`), and a report carrying no pair, the reversal moving it or not, only where + it is about a member a tie decided or a model holding one, or sits at or beneath such a member's + pointer (`untied`): it forgives itself alone, nothing at or beneath it. Of a tied member it compares what its fold settles from every declaration alike: whether it is required or secret and where it is visible, and its deprecation, docs, name and XML hints where - a stated tie alone decided it (`statedAlone`). So a - dependence of a member settled from a tied one that the tie does not explain passes, #2099's - among them where it lands on such a member, though #2099's own documents are found. Of a - member no tie decided, a report's kept place is compared by the node its - declaration names, since of agreeing declarations of one node it names the one written last, - while copies at distinct nodes keep the declaration of the node sorting first in either order, - and not where the compile reads no declaration there; where the member takes a node the fold - minted, it is compared by that node, since of declarations that meet the later wins, so a report - there naming as kept a declaration the fold dropped passes. A tied member taking in each order the type - its report says lost is found; one taking the same type in both orders passes. + conflicts alone tied it (`tiedByConflictsAlone` in `ties.go`) and it overrides no declaration a + tie decided (`statedAlone`), since a tie any other report carrying a pair states, a + docs report among them, decides what the member folds over every declaration. So a + dependence of a member settled from a tied one that the tie does not explain passes, but for a + member naming in each order another of two nodes saying the same: that is found unless the + cascade explains it, a declaration the member overrides naming another type reversed only where + a tied or settled member is declared (`alikeByOrder` and `cascaded` in `ties.go`). Of a + member no tie decided, a report's kept place is compared as it stands, erased, since of + agreeing declarations it names the first written, whichever the order; where the member takes a + node the fold minted, it is compared by that node, since of declarations that meet the later + wins, so a report there naming as kept a declaration the fold dropped passes. A tied member + taking in each order the type its report says lost is found; one taking the same type in both + orders passes. + No report's message is read, and it alone says what the declarations disagree over, so a tie + over a bound and one over a type at the same places are one, and a tie over one detail decides + every detail a member folds (#2340). Both compile at the default limits, so an order dependence among a listed collection's elements, in any other sequence or another order of one, or in a verdict at another limit (#1519) needs its own two-order diff. A targeted case still earns its place when it pins one lowering, because the @@ -478,7 +504,9 @@ departs from it, with what holds each difference. in the specification's words, a normative document's term even if figurative: no other figurative or abbreviated name, and one letter only for a loop counter, a receiver, a comparison pair or a standard-library convention such as `t *testing.T` - (`.claude/skills/morphic-designing-code/references/design-rules.md#name-what-it-holds`). + (`.claude/skills/morphic-designing-code/references/design-rules.md#name-what-it-holds`). A word + defined in `docs/ir/README.md#words`, or in the table of words the rules use that opens + `docs/compilers/openapi.md`, keeps that one sense in code, comments and documents. - **Testing:** table-driven and flat; `TestFunc_Scenario` names; `testify/require` for preconditions, `assert` for values; compare with `cmp.Diff`, or `assert.Equal` on a value holding no unexported field or `Equal` method, never `reflect.DeepEqual`; golden files for complex diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b7642ae07..48a781397 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -246,8 +246,31 @@ A lowering rule says how one OpenAPI construct reaches the IR: the field it fill `TestModelHolders_NoOtherPackageHoldsAParserSchema` for a package outside its list that holds the model's schema type, whether it imports the library or not, `TestModelReads_HeldToTheBaseline` for a read of the model beside the statement, `TestMethodsPerType_StayUnderTheCap`, - `TestDocComments_StayUnderTheCap`, `TestSuppressions_NoDirectiveStandsInTheSource`, + `TestDocComments_StayUnderTheCap`, `TestSuppressions_NoDirectiveRemainsInTheSource`, `TestCallShape_HeldToTheBaseline`. Nothing fails for code in the wrong file of its package. + + A schema rule shares three readings with every other rule, and goes through each rather than + reading for itself: + + - **What a node keeps.** Record each keyword the rule keeps as a pending keep on the node's + `annotation.PendingKeeps`, through `schema`'s `pendingkeeps.go`. Where each is kept is decided + once, when the node settles. Never write a node's `Unmodeled` yourself: a keyword two writers + keep would then be kept twice, or under the wrong writer's key. + *Fails if missed:* `schema.TestEntryKeptOnce_EveryKeywordOfAGridIsKeptOnce`, for a keyword its + grid writes. Nothing fails for a keyword the grid does not write, so add it to the grid's + shapes. + - **Whether a schema admits null.** Ask `nullAnswerReadingsOf` in `schema`'s `nullverdictstore.go`, which + reads each schema once a run, across its references and its `allOf`, under the + nullable-inference policy. Never read `nullable`, or a `null` in a `type` list, yourself. + *Fails if missed:* `TestCore_SpellingsHoldTheRecord` and + `TestCore_EveryKeywordIsCarriedEverywhere` in `internal/harness/openapicases`, for a reading + that differs at a case the core writes. + - **Which union a position lowers.** `readConjunction` in `schema`'s `unionbesidestructure.go` lists the + `oneOf`s and `anyOf`s a position and its inline `allOf` entries write, and chooses the one the + position lowers. Never list them, or choose among them, yourself. + *Fails if missed:* `e2e.TestUnionBesideBody_EverySpellingLowersAlike` and + `schema.TestConjunction_UnionsNoChoicePicksAreKept`, for a reading that changes with where a + union is written. 4. **Add a conformance case and a unit test.** Write a minimal spec at `testdata/conformance/openapi/.yaml` that exercises the rule, add an entry to `conformanceCases()` in `compilers/openapi/e2e/conformance_test.go` naming its assertion, list it @@ -296,7 +319,7 @@ A lowering rule says how one OpenAPI construct reaches the IR: the field it fill ``` A line the diff adds is a finding the change made, written as `unclassified`, which fails until - the compiler is fixed or the line is given the reason, a key of `Reasons`, of the issue it stands + the compiler is fixed or the line is given the reason, a key of `Reasons`, of the issue it sits under, which every key of `Reasons` cites. A line whose finding changed keeps its reason, so check the reason still holds. @@ -434,12 +457,14 @@ A compiler lowers one source format into an IR document ([`architecture.md`](doc and canonical names with `compilers/compile`, declare in `Document.IDSpaces` every namespace an ID lives in, source-addressed as well as minted (`docs/ir/identity.md`), and stamp `ir.IRVersion`. Once the last lowering returns, take the registry from `compile.Types.Finish` and - report the diagnostics it returns beside it, as the OpenAPI compiler's `run` does: they carry a - `compile/registry-refused` error for each entry the registry refused. Take the `*compile.Types` - as a parameter, as `run` does, so a test can drive the refusal no source provokes. Name each - source in `Document.Sources` with the format it was recognized as and `ir.SourceHash` of its - bytes, in `SourceTable`'s order, and after them each document a reference read through - `compilers.Options.Reader`. + report the diagnostics it returns beside it, as the OpenAPI compiler's `run` does. They carry a + `compile/alias-base-rewritten` error for each alias a settlement changed, itself or the node its + `Base` names, in what a reader of the alias chain takes from it, and a + `compile/registry-refused` error for each entry the registry refused. Take + the `*compile.Types` as a parameter, as `run` does, so a test can drive the refusal no source + provokes. Name each source in `Document.Sources` with the format it was recognized as and + `ir.SourceHash` of its bytes, in `SourceTable`'s order, and after them each document a reference + read through `compilers.Options.Reader`. *Fails if missed:* the `namechannels`, `idderivations` and `registrywrites` rules in `internal/lintrules` (`make vet`) for the framework; `irverify`, in step 5's tests, for the namespaces, the version, the services and a malformed source table, with `irtest.SpacesUsed` diff --git a/Makefile b/Makefile index 461a800ca..1140a3cb7 100644 --- a/Makefile +++ b/Makefile @@ -176,7 +176,7 @@ race: # a line of testdata/full naming none, one test log line each; -full -update # rewrites testdata/full. cases: - $(GO) test ./internal/harness/openapicases -run 'TestFull_' -full -count=1 -timeout 15m + $(GO) test ./internal/harness/openapicases -run 'TestFull_' -full -count=1 -timeout 40m fuzz: ./scripts/fuzz.sh $(FUZZTIME) diff --git a/barrier/text.go b/barrier/text.go index a2a3b4ada..d9e08e4fd 100644 --- a/barrier/text.go +++ b/barrier/text.go @@ -21,8 +21,8 @@ const maxText = 4 << 10 // bounded by what is kept and not by what the value wrote. const scanLimit = 4 * maxText -// noText stands in for a value whose text is empty or only white space, so a -// message quoting it still says something. +// noText takes the place of a value whose text is empty or only white space, so +// a message quoting it still says something. const noText = "(no text)" // elidedMarker ends a text the bound cut. It carries no count: a count would diff --git a/cmd/morphic-vet/main_test.go b/cmd/morphic-vet/main_test.go index 467f7c051..0a8cb9c6f 100644 --- a/cmd/morphic-vet/main_test.go +++ b/cmd/morphic-vet/main_test.go @@ -47,8 +47,8 @@ func TestMain_HandsGoVetTheRules(t *testing.T) { []string{"fragmentreadings", "idderivations", "namechannels", "registrywrites", "servicetreewrites"}) } -// TestMain_RunsTheToolOnTheRules runs main in this process, with vet standing -// in for unitchecker, and holds it to handing the tool every rule lintrules +// TestMain_RunsTheToolOnTheRules runs main in this process, with vet taking the +// place of unitchecker, and holds it to handing the tool every rule lintrules // has. A child's coverage is discarded, so this is what covers main. func TestMain_RunsTheToolOnTheRules(t *testing.T) { orig := vet diff --git a/cmd/morphic/dashes.go b/cmd/morphic/dashes.go index c033d627b..fe512d5aa 100644 --- a/cmd/morphic/dashes.go +++ b/cmd/morphic/dashes.go @@ -43,7 +43,7 @@ func misreadDashes(root *cobra.Command, args []string) error { i++ case endsFlags, refused: return nil - case argumentStandsAlone: + case argumentIsAlone: } } return nil @@ -107,10 +107,10 @@ func dropsAsGoTestFlag(fs *pflag.FlagSet, shorts string) bool { type pflagArgumentReading int const ( - argumentStandsAlone pflagArgumentReading = iota // an operand, or flags with every value they need - wantsValue // a flag whose value is the next argument - endsFlags // the "--" after which every argument is an operand - refused // an argument the parse fails on + argumentIsAlone pflagArgumentReading = iota // an operand, or flags with every value they need + wantsValue // a flag whose value is the next argument + endsFlags // the "--" after which every argument is an operand + refused // an argument the parse fails on ) // readAlone asks pflag how it reads tok, so that which argument is a flag's @@ -130,6 +130,6 @@ func readAlone(probe *pflag.FlagSet, tok string) pflagArgumentReading { case probe.ArgsLenAtDash() >= 0: return endsFlags default: - return argumentStandsAlone + return argumentIsAlone } } diff --git a/cmd/morphic/main_explain_test.go b/cmd/morphic/main_explain_test.go index a97306874..bfc251bbe 100644 --- a/cmd/morphic/main_explain_test.go +++ b/cmd/morphic/main_explain_test.go @@ -44,8 +44,8 @@ func TestRun_ExplainReportsTheNodeAtACoordinate(t *testing.T) { // TestRun_ExplainListsWhatIsKeptWhereNoNodeIs pins the answer --explain gives // for a construct the compiler keeps verbatim rather than models: where no type -// node stands, each entry kept there is listed with the node keeping it and -// why, a path item's once on each operation it rides on. +// node is, each Unmodeled entry kept there is listed with the node keeping it +// and why, a path item's once on each operation it rides on. func TestRun_ExplainListsWhatIsKeptWhereNoNodeIs(t *testing.T) { t.Parallel() spec := writeFile(t, "spec.yaml", `openapi: 3.1.0 diff --git a/cmd/morphic/resolve.go b/cmd/morphic/resolve.go index 00df591e1..5c97f6315 100644 --- a/cmd/morphic/resolve.go +++ b/cmd/morphic/resolve.go @@ -82,10 +82,10 @@ type argumentsBeforeCommandName int const ( onlyFlags argumentsBeforeCommandName = iota // flags and their values, the word none of them unknownFlag // an argument the command's flags refuse - notCommand // no word naming it stands free of an operand, a "--" or a flag + notCommand // no word naming it is free of an operand, a "--" or a flag ) -// firstWord returns where c's word first stands in args, read by c's flags as +// firstWord returns where c's word first sits in args, read by c's flags as // pflag will read them, and how what comes before it reads. The reading is one // pass, ending at the first argument that decides it: an operand or a "--", // after which no word is c's, or a flag c refuses, after which the next word @@ -103,7 +103,7 @@ func firstWord(c *cobra.Command, args []string, read func(*pflag.FlagSet, string return 0, notCommand case refused: return nextNaming(c, args, i+1) - case argumentStandsAlone: + case argumentIsAlone: if isOperand(args[i]) { return 0, notCommand } @@ -112,7 +112,7 @@ func firstWord(c *cobra.Command, args []string, read func(*pflag.FlagSet, string return 0, notCommand } -// nextNaming returns where the first word naming c stands in args at or after +// nextNaming returns where the first word naming c sits in args at or after // from, read past a flag c refuses, or notCommand when none does. func nextNaming(c *cobra.Command, args []string, from int) (int, argumentsBeforeCommandName) { for i := from; i < len(args); i++ { @@ -123,9 +123,9 @@ func nextNaming(c *cobra.Command, args []string, from int) (int, argumentsBefore return 0, notCommand } -// isOperand reports whether pflag reads tok, standing alone, as an operand -// rather than a flag: an empty argument, a lone dash, or one that does not -// start with a dash. +// isOperand reports whether pflag reads tok, on its own, as an operand rather +// than a flag: an empty argument, a lone dash, or one that does not start with +// a dash. func isOperand(tok string) bool { return len(tok) < 2 || tok[0] != '-' } diff --git a/cmd/morphic/resolve_test.go b/cmd/morphic/resolve_test.go index 0500c62a9..e1741bcef 100644 --- a/cmd/morphic/resolve_test.go +++ b/cmd/morphic/resolve_test.go @@ -80,10 +80,10 @@ func TestRun_AFlagBeforeItsCommandIsReadAsTheCommandReadsIt(t *testing.T) { } } -// TestRun_TheSpecOperandTakesNoStandIn pins the operands a spec-taking command -// reads as a file named so, and none as standard input: a lone dash and an -// empty argument are paths like any other. -func TestRun_TheSpecOperandTakesNoStandIn(t *testing.T) { +// TestRun_TheSpecOperandTakesNoSubstitute pins the operands a spec-taking +// command reads as a file named so, and none as standard input: a lone dash and +// an empty argument are paths like any other. +func TestRun_TheSpecOperandTakesNoSubstitute(t *testing.T) { t.Chdir(t.TempDir()) for operand, reason := range map[string]string{ "-": `read spec "-": open -: no such file or directory`, @@ -207,7 +207,7 @@ func TestNextCommand_ReadsTheArgumentsOncePerCommand(t *testing.T) { // TestNextCommand_TheFirstWordReadCleanWins pins the choice between commands // whose flags read the same argument differently: x takes --f as a switch and // so its own name next, y takes that name as --f's value and its own after it. -// The word standing first is the command's, whichever command lists first. +// The word that comes first is the command's, whichever command lists first. func TestNextCommand_TheFirstWordReadCleanWins(t *testing.T) { t.Parallel() for _, order := range [][]string{{"x", "y"}, {"y", "x"}} { diff --git a/compilers/compile/aliasbase.go b/compilers/compile/aliasbase.go new file mode 100644 index 000000000..afe53ea8a --- /dev/null +++ b/compilers/compile/aliasbase.go @@ -0,0 +1,93 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package compile + +import ( + "crypto/sha256" + "encoding/json/v2" + "maps" + "slices" + + "github.com/dexpace/morphic/ir" +) + +// aliasDigests holds the digest of what a reading of an alias chain takes from +// each alias scalar and the node it names, as they were when the settlements +// began or the settlement registering the alias returned. The settlements +// share one alias index, whose memos read each chain once, so none may change +// what a reading took. +type aliasDigests struct { + // baseNamed holds, for each alias, the ID its Base named when it was copied. + baseNamed map[ir.TypeID]ir.TypeID + // digestOf holds the digest of the reading of each alias and of each node + // an alias names. + digestOf map[ir.TypeID][sha256.Size]byte +} + +// digestAliases copies each alias scalar of reg that ids names and the node it +// names, unless one is copied already. +func (digests *aliasDigests) digestAliases(reg ir.TypeRegistry, ids []ir.TypeID) { + for _, id := range ids { + base, alias := ir.AliasBase(reg, id) + if _, copied := digests.baseNamed[id]; !alias || copied { + continue + } + digests.baseNamed[id] = base + for _, node := range [2]ir.TypeID{id, base} { + if _, encoded := digests.digestOf[node]; !encoded { + digests.digestOf[node] = chainReadingDigest(reg[node]) + } + } + } +} + +// rewrittenAliases returns, in sorted order, each alias whose reading differs from +// its copy, or whose node named reads otherwise than that node's copy. +func (digests *aliasDigests) rewrittenAliases(reg ir.TypeRegistry) []ir.TypeID { + changed := make(map[ir.TypeID]bool, len(digests.digestOf)) + for id, encoded := range digests.digestOf { + changed[id] = chainReadingDigest(reg[id]) != encoded + } + var out []ir.TypeID + for _, alias := range slices.Sorted(maps.Keys(digests.baseNamed)) { + if changed[alias] || changed[digests.baseNamed[alias]] { + out = append(out, alias) + } + } + return out +} + +// chainReadingDigest is the SHA-256 digest of what a reading of an alias chain +// may take from typeDef: the whole of an alias, and of a chain's end its kind +// and ID and the fields a scalar's or a primitive's values are read by. A +// model's members, which settlements fold, are left out, as no reading takes +// them through a chain. +func chainReadingDigest(typeDef ir.TypeDef) [sha256.Size]byte { + if ir.IsNilTypeDef(typeDef) { + return sha256.Sum256([]byte("absent")) + } + switch node := typeDef.(type) { + case *ir.Scalar: + if node.Base != nil { + return nodeDigest(node) + } + return nodeDigest(&ir.Scalar{ID: node.ID, Constraints: node.Constraints, Encoding: node.Encoding}) + case *ir.Primitive: + return nodeDigest(&ir.Primitive{ID: node.ID, PrimitiveKind: node.PrimitiveKind}) + default: + return sha256.Sum256([]byte(string(node.Kind()) + " " + string(node.Common().ID))) + } +} + +// nodeDigest is the digest of typeDef's encoding, which tags its kind, or of +// the error refusing it. The encoding streams into the digest, so no copy of +// an alias, whose examples may be large, is held, and allocation does not turn +// on whether a collection emptied the encoder's pooled buffer. +func nodeDigest(typeDef ir.TypeDef) [sha256.Size]byte { + digest := sha256.New() + if err := json.MarshalWrite(digest, typeDef, json.Deterministic(true)); err != nil { + return sha256.Sum256([]byte("unencodable: " + err.Error())) + } + return [sha256.Size]byte(digest.Sum(nil)) +} diff --git a/compilers/compile/aliasbase_test.go b/compilers/compile/aliasbase_test.go new file mode 100644 index 000000000..dbfdcadae --- /dev/null +++ b/compilers/compile/aliasbase_test.go @@ -0,0 +1,336 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package compile_test + +import ( + "encoding/json/v2" + "math" + "runtime" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/ir" +) + +// aliasOverModel stores the model type/end, the alias type/alias naming it, +// and the model type/other no alias names, as lowerings leave them before +// Finish takes the settlements. +func aliasOverModel() *compile.Types { + types := compile.NewTypes() + types.Intern("/end", "type/end", func() ir.TypeDef { return &ir.Model{ID: "type/end"} }) + types.Intern("/alias", "type/alias", func() ir.TypeDef { + return &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/end"}} + }) + types.Intern("/other", "type/other", func() ir.TypeDef { return &ir.Model{ID: "type/other"} }) + return types +} + +// aliasesOverEachEnd is aliasOverModel with the opaque scalar type/opaque, +// bounded and encoded, beside the alias type/overOpaque naming it, and the +// primitive type/string beside the alias type/overPrimitive naming it. +func aliasesOverEachEnd() *compile.Types { + types := aliasOverModel() + types.Intern("/opaque", "type/opaque", func() ir.TypeDef { + return &ir.Scalar{ID: "type/opaque", Constraints: &ir.Constraints{Pattern: "^a"}, Encoding: &ir.Encoding{Name: "rfc3339"}} + }) + types.Intern("/overOpaque", "type/overOpaque", func() ir.TypeDef { + return &ir.Scalar{ID: "type/overOpaque", Base: &ir.TypeRef{Target: "type/opaque"}} + }) + types.Intern("/string", "type/string", func() ir.TypeDef { + return &ir.Primitive{ID: "type/string", PrimitiveKind: ir.PrimitiveString} + }) + types.Intern("/overPrimitive", "type/overPrimitive", func() ir.TypeDef { + return &ir.Scalar{ID: "type/overPrimitive", Base: &ir.TypeRef{Target: "type/string"}} + }) + return types +} + +// rewrittenAliases returns the alias-base-rewritten errors among diags. +func rewrittenAliases(t *testing.T, diags []ir.Diagnostic) []ir.Diagnostic { + t.Helper() + var out []ir.Diagnostic + for _, diagnostic := range diags { + if diagnostic.Code != compile.AliasBaseRewritten { + continue + } + assert.Equal(t, ir.SeverityError, diagnostic.Severity, "an internal invariant") + assert.Equal(t, ir.Provenance{Source: ir.NoSource}, diagnostic.Provenance, "a compiler bug locates nothing in a source") + out = append(out, diagnostic) + } + return out +} + +// TestTypes_FinishReportsAnAliasASettlementRewrote pins the check that makes +// the alias index sound: each alias and the node it names are copied as a +// reading of the chain takes them when the settlements begin, and Finish +// reports one a settlement left otherwise, a completion's rewrite among them, +// once, naming the alias: any field of the alias, and the kind and ID of the +// node it names, and a scalar's Base, Constraints and Encoding or a +// primitive's PrimitiveKind. +func TestTypes_FinishReportsAnAliasASettlementRewrote(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + rewrite func(reg ir.TypeRegistry) + alias string + complete bool + }{ + "its Base retargeted": {alias: "type/alias", rewrite: func(reg ir.TypeRegistry) { + reg["type/alias"].(*ir.Scalar).Base.Target = "type/other" + }}, + "its Base made nullable": {alias: "type/alias", rewrite: func(reg ir.TypeRegistry) { + reg["type/alias"].(*ir.Scalar).Base.Nullable = true + }}, + "its bounds": {alias: "type/alias", rewrite: func(reg ir.TypeRegistry) { + reg["type/alias"].(*ir.Scalar).Constraints = &ir.Constraints{Pattern: "^a"} + }}, + "its encoding": {alias: "type/alias", rewrite: func(reg ir.TypeRegistry) { + reg["type/alias"].(*ir.Scalar).Encoding = &ir.Encoding{Name: "rfc3339"} + }}, + "its docs": {alias: "type/alias", rewrite: func(reg ir.TypeRegistry) { + reg["type/alias"].Common().Docs.Description = "settled" + }}, + "its Base, in a completion": {alias: "type/alias", complete: true, rewrite: func(reg ir.TypeRegistry) { + reg["type/alias"].(*ir.Scalar).Base.Target = "type/other" + }}, + "the model it names, swapped for a node of another kind": {alias: "type/alias", rewrite: func(reg ir.TypeRegistry) { + reg["type/end"] = &ir.Enum{ID: "type/end"} + }}, + "the model it names, given another ID": {alias: "type/alias", rewrite: func(reg ir.TypeRegistry) { + reg["type/end"].Common().ID = "type/elsewhere" + }}, + "the scalar it names, given a Base": {alias: "type/overOpaque", rewrite: func(reg ir.TypeRegistry) { + reg["type/opaque"].(*ir.Scalar).Base = &ir.TypeRef{Target: "type/string"} + }}, + "the scalar it names, its bounds": {alias: "type/overOpaque", rewrite: func(reg ir.TypeRegistry) { + reg["type/opaque"].(*ir.Scalar).Constraints = &ir.Constraints{Pattern: "^b"} + }}, + "the scalar it names, its encoding": {alias: "type/overOpaque", rewrite: func(reg ir.TypeRegistry) { + reg["type/opaque"].(*ir.Scalar).Encoding = &ir.Encoding{Name: "date"} + }}, + "the scalar it names, given another ID": {alias: "type/overOpaque", rewrite: func(reg ir.TypeRegistry) { + reg["type/opaque"].Common().ID = "type/elsewhere" + }}, + "the primitive it names, its kind": {alias: "type/overPrimitive", rewrite: func(reg ir.TypeRegistry) { + reg["type/string"].(*ir.Primitive).PrimitiveKind = ir.PrimitiveInteger + }}, + "the primitive it names, given another ID": {alias: "type/overPrimitive", rewrite: func(reg ir.TypeRegistry) { + reg["type/string"].Common().ID = "type/elsewhere" + }}, + } { + types := aliasesOverEachEnd() + settlement := settleFunc(func(reg ir.TypeRegistry) []ir.Diagnostic { tc.rewrite(reg); return nil }) + if tc.complete { + types.QueueSettlementBeforeDeferredOnes(settlement) + } else { + types.Defer(settlement) + } + + _, diags := types.Finish(t.Context()) + + rewritten := rewrittenAliases(t, diags) + require.Len(t, rewritten, 1, "%s: %+v", name, diags) + assert.Contains(t, rewritten[0].Message, tc.alias+",", name) + } +} + +// TestTypes_FinishLeavesAnAliasNoSettlementChanged pins what the check +// forgives: a settlement rewriting a node no alias names, one rewriting +// nothing, one storing an alias's equal copy, since the copies are compared by +// their encoding, and one rewriting what no reading of a chain takes from the +// node at its end: a model's members, which settlements fold, and any end's +// docs. +func TestTypes_FinishLeavesAnAliasNoSettlementChanged(t *testing.T) { + t.Parallel() + for name, rewrite := range map[string]func(reg ir.TypeRegistry){ + "nothing rewritten": func(ir.TypeRegistry) {}, + "a node no alias names": func(reg ir.TypeRegistry) { + reg["type/other"].Common().Docs.Description = "settled" + }, + "an equal copy stored": func(reg ir.TypeRegistry) { + reg["type/alias"] = &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/end"}} + }, + "the members of the model it names": func(reg ir.TypeRegistry) { + model := reg["type/end"].(*ir.Model) + model.Properties = append(model.Properties, ir.Property{WireName: "children", Type: ir.TypeRef{Target: "type/string"}}) + model.Requires = []string{"x"} + }, + "the model it names, swapped for one of other members": func(reg ir.TypeRegistry) { + reg["type/end"] = &ir.Model{ID: "type/end", Requires: []string{"x"}} + }, + "the docs of the model it names": func(reg ir.TypeRegistry) { + reg["type/end"].Common().Docs.Description = "settled" + }, + "the docs of the scalar it names": func(reg ir.TypeRegistry) { + reg["type/opaque"].Common().Docs.Description = "settled" + }, + "the docs of the primitive it names": func(reg ir.TypeRegistry) { + reg["type/string"].Common().Docs.Description = "settled" + }, + } { + types := aliasesOverEachEnd() + types.Defer(settleFunc(func(reg ir.TypeRegistry) []ir.Diagnostic { rewrite(reg); return nil })) + + _, diags := types.Finish(t.Context()) + + assert.Empty(t, rewrittenAliases(t, diags), "%s: %+v", name, diags) + assert.Empty(t, types.Violations(), name) + } +} + +// TestTypes_FinishReportsAnAliasASettlementRegisteredAndALaterOneRewrote pins +// the copy taken of an alias Register stores during a settlement, and of the +// node it names: a later settlement rewriting either as a reading of the chain +// takes it is reported, and one leaving both so is not. +func TestTypes_FinishReportsAnAliasASettlementRegisteredAndALaterOneRewrote(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + rewrite func(reg ir.TypeRegistry) + reports int + }{ + "left alone": {func(ir.TypeRegistry) {}, 0}, + "its Base retargeted": {func(reg ir.TypeRegistry) { + reg["type/minted"].(*ir.Scalar).Base.Target = "type/end" + }, 1}, + "the node it names, swapped for a node of another kind": {func(reg ir.TypeRegistry) { + reg["type/other"] = &ir.Enum{ID: "type/other"} + }, 1}, + "the docs of the node it names": {func(reg ir.TypeRegistry) { + reg["type/other"].Common().Docs.Description = "settled" + }, 0}, + } { + types := aliasOverModel() + types.Defer(settleFunc(func(ir.TypeRegistry) []ir.Diagnostic { + types.Register("type/minted", &ir.Scalar{ID: "type/minted", Base: &ir.TypeRef{Target: "type/other"}}) + return nil + })) + types.Defer(settleFunc(func(reg ir.TypeRegistry) []ir.Diagnostic { tc.rewrite(reg); return nil })) + + _, diags := types.Finish(t.Context()) + + rewritten := rewrittenAliases(t, diags) + require.Len(t, rewritten, tc.reports, "%s: %+v", name, diags) + if tc.reports > 0 { + assert.Contains(t, rewritten[0].Message, "type/minted", name) + } + } +} + +// TestTypes_FinishCopiesTheAliasesOnceEveryNodeIsBuilt pins when the copies +// are taken: after the promised nodes are built, so an alias a promise builds +// is checked like one a lowering interned, and a promise's own writes, made +// before the settlements, are no rewrite. +func TestTypes_FinishCopiesTheAliasesOnceEveryNodeIsBuilt(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + rewrite func(reg ir.TypeRegistry) + reports int + }{ + "left alone": {func(ir.TypeRegistry) {}, 0}, + "rewritten by a settlement": {func(reg ir.TypeRegistry) { + reg["type/promised"].(*ir.Scalar).Base.Target = "type/other" + }, 1}, + } { + types := aliasOverModel() + types.ReserveNodeAtCoordinate("/promised", func() []ir.Diagnostic { + types.Intern("/promised", "type/promised", func() ir.TypeDef { + return &ir.Scalar{ID: "type/promised", Base: &ir.TypeRef{Target: "type/end"}} + }) + return nil + }) + types.Defer(settleFunc(func(reg ir.TypeRegistry) []ir.Diagnostic { tc.rewrite(reg); return nil })) + + _, diags := types.Finish(t.Context()) + + require.Len(t, rewrittenAliases(t, diags), tc.reports, "%s: %+v", name, diags) + } +} + +// TestTypes_FinishComparesWhatNoEncodingSpells pins the copies of nodes with no +// encoding of their own: a Base naming no node and an alias that does not +// encode, left alone, are no rewrite; a node a settlement stores where a Base +// named none is one, and so is an alias rewritten to one that does not encode, +// and a node two aliases name swapped for another kind, for each of them. +func TestTypes_FinishComparesWhatNoEncodingSpells(t *testing.T) { + t.Parallel() + unencodable := ir.Unmodeled{"openapi:x": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue(`{`)}} + for name, tc := range map[string]struct { + rewrite func(reg ir.TypeRegistry) + reports int + }{ + "no encoding to read, left alone": {func(ir.TypeRegistry) {}, 0}, + "a node stored where it names none": {func(reg ir.TypeRegistry) { + reg["type/ghost"] = &ir.Model{ID: "type/ghost"} + }, 1}, + "an alias rewritten to one that does not encode": {func(reg ir.TypeRegistry) { + reg["type/alias"].Common().Unmodeled = unencodable + }, 1}, + "the node two aliases name, swapped for a node of another kind": {func(reg ir.TypeRegistry) { + reg["type/end"] = &ir.Enum{ID: "type/end"} + }, 2}, + } { + types := compile.NewTypes() + types.Intern("/end", "type/end", func() ir.TypeDef { return &ir.Model{ID: "type/end"} }) + types.Intern("/alias", "type/alias", func() ir.TypeDef { + return &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/end"}} + }) + types.Intern("/dangling", "type/dangling", func() ir.TypeDef { + return &ir.Scalar{ID: "type/dangling", Base: &ir.TypeRef{Target: "type/ghost"}} + }) + types.Intern("/odd", "type/odd", func() ir.TypeDef { + return &ir.Scalar{ID: "type/odd", Unmodeled: unencodable, Base: &ir.TypeRef{Target: "type/end"}} + }) + types.Defer(settleFunc(func(reg ir.TypeRegistry) []ir.Diagnostic { tc.rewrite(reg); return nil })) + + _, diags := types.Finish(t.Context()) + + assert.Len(t, rewrittenAliases(t, diags), tc.reports, "%s: %+v", name, diags) + } +} + +// finishBytes returns the fewest bytes Finish allocates in three runs over an +// alias whose one example lists entries numbers, and the length of that +// alias's encoding. +func finishBytes(t *testing.T, entries int) (allocated, encoded int) { + t.Helper() + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) + list := ir.Value{Kind: ir.ValueList, List: slices.Repeat([]ir.Value{{Kind: ir.ValueNumber, Number: "12345"}}, entries)} + alias := func() ir.TypeDef { + scalar := &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/end"}} + scalar.Examples = []ir.Example{{Value: &list}} + return scalar + } + raw, err := json.Marshal(alias(), json.Deterministic(true)) + require.NoError(t, err) + allocated = math.MaxInt + for range 3 { + types := compile.NewTypes() + types.Intern("/end", "type/end", func() ir.TypeDef { return &ir.Model{ID: "type/end"} }) + types.Intern("/alias", "type/alias", alias) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, diags := types.Finish(t.Context()) + runtime.ReadMemStats(&after) + require.Empty(t, diags) + allocated = min(allocated, int(after.TotalAlloc-before.TotalAlloc)) + } + return allocated, len(raw) +} + +// TestTypes_FinishHoldsNoCopyOfAnAliasEncoding pins what the copies of an +// alias cost: what Finish allocates more for an alias whose example lists a +// hundred times more entries is under a tenth of what its encoding grows by, +// as each copy is a digest the encoding streams into, where a copy of the +// encoding grows with it. It does not run in parallel, since the count is +// process-wide. +func TestTypes_FinishHoldsNoCopyOfAnAliasEncoding(t *testing.T) { + small, smallEncoded := finishBytes(t, 100) + large, largeEncoded := finishBytes(t, 10_000) + + assert.Less(t, large-small, (largeEncoded-smallEncoded)/10, + "Finish allocated %d bytes for an encoding of %d, and %d for one of %d", small, smallEncoded, large, largeEncoded) +} diff --git a/compilers/compile/ids_test.go b/compilers/compile/ids_test.go index 73e5ea26e..2c6c534f8 100644 --- a/compilers/compile/ids_test.go +++ b/compilers/compile/ids_test.go @@ -100,7 +100,7 @@ func TestSpace_QualifiedNamesTheDocumentInOneSegment(t *testing.T) { // and asserts it is refused whichever order the two arrive in. // // Both orders are asserted because that is the failure's whole character: the -// document is well-formed either way and only the winner of the collision +// document is well-formed either way and only the node the collision takes // changes, so a single-order test passes on a compiler that is already wrong. func TestTypes_MintingIntoASourceSpaceIsRefused(t *testing.T) { t.Parallel() @@ -129,10 +129,10 @@ func TestTypes_MintingIntoASourceSpaceIsRefused(t *testing.T) { } } -// TestTypes_SeparateSpacesAreNotRefused is the negative control: the arrangement -// the OpenAPI compiler actually uses — coordinates in openapi and anon, minted -// variants in composed — must stay silent, or the check above would be reporting -// on every compile. +// TestTypes_SeparateSpacesAreNotRefused is the negative control: the +// arrangement the OpenAPI compiler actually uses — coordinates in openapi and +// anon, minted variants in composed — must report nothing, or the check above +// would be reporting on every compile. func TestTypes_SeparateSpacesAreNotRefused(t *testing.T) { t.Parallel() types := compile.NewTypes() diff --git a/compilers/compile/naming.go b/compilers/compile/naming.go index e45e6f9ea..33712cb68 100644 --- a/compilers/compile/naming.go +++ b/compilers/compile/naming.go @@ -46,13 +46,13 @@ func SubHints(parent string, suffixes ...string) string { if len(suffixes) == 0 { return parent } - var b strings.Builder - b.WriteString(neutralHint(parent)) - for _, s := range suffixes { - b.WriteByte('_') - b.WriteString(neutralHint(s)) + var builder strings.Builder + builder.WriteString(neutralHint(parent)) + for _, suffix := range suffixes { + builder.WriteByte('_') + builder.WriteString(neutralHint(suffix)) } - return b.String() + return builder.String() } // neutralHint returns the neutral word sequence of hint, or the minted name when diff --git a/compilers/compile/settle.go b/compilers/compile/settle.go index 1f1e6e1f0..4d0505a3b 100644 --- a/compilers/compile/settle.go +++ b/compilers/compile/settle.go @@ -5,6 +5,8 @@ package compile import ( "context" + "crypto/sha256" + "maps" "slices" "github.com/dexpace/morphic/ir" @@ -16,12 +18,12 @@ import ( // whole. // // Settle may rewrite nodes already in reg. It must not remove one, which would -// leave every reference to it dangling, and it adds one only through Register, -// which holds a node it mints to a namespace of its own. One settling many -// nodes asks ctx between them and returns once it is done, as Finish does -// between settlements. +// leave every reference to it dangling, and adds one only through Register, +// which holds a minted node to a namespace of its own, or PrimitiveRef. +// aliases indexes reg's alias chains, one index for every settlement. One +// settling many nodes asks ctx between them and returns once it is done. type Settlement interface { - Settle(ctx context.Context, reg ir.TypeRegistry) []ir.Diagnostic + Settle(ctx context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic } // Defer queues settlement for Finish to settle. A nil settlement cannot be @@ -53,30 +55,40 @@ func (t *Types) queue(settlements *[]Settlement, verb string, settlement Settlem } // settle takes every Settlement once, those QueueSettlementBeforeDeferredOnes -// queued before those Defer queued, each kind in the order queued, and returns -// their diagnostics; Finish calls it once every promised node is built. It -// checks ctx before each settlement and stops once it is done, leaving a -// registry the caller must not assemble. A settlement leaving the registry any -// size but the one its Register calls account for is refused and left standing, -// a compiler bug, not a recovery. A swap of one node for another keeps the -// count, so the references it leaves dangling are left to pass.Validate and -// irverify. +// queued first, each kind in the order queued, and returns their diagnostics, +// then an AliasBaseRewritten error for each alias a settlement changed +// (aliasDigests): the check that lets one alias index serve every settlement. +// It stops once ctx is done. A settlement changing the registry's size +// otherwise than Register and PrimitiveRef do is refused, a compiler bug; a +// swap of one node for another leaves its dangling references to +// pass.Validate and irverify. func (t *Types) settle(ctx context.Context) []ir.Diagnostic { t.settled = true pending := slices.Concat(t.completing, t.pending) t.completing, t.pending = nil, nil diags := make([]ir.Diagnostic, 0, len(pending)) + digests := aliasDigests{baseNamed: map[ir.TypeID]ir.TypeID{}, digestOf: map[ir.TypeID][sha256.Size]byte{}} + digests.digestAliases(t.reg, slices.Collect(maps.Keys(t.reg))) + aliases := ir.NewAliasChainIndex(t.reg.Lookup) for _, settlement := range pending { if ctx.Err() != nil { return diags } before, minted := len(t.reg), t.minted - diags = append(diags, settlement.Settle(ctx, t.reg)...) + diags = append(diags, settlement.Settle(ctx, t.reg, aliases)...) if after := len(t.reg); after != before+t.minted-minted { t.refuse("settlement %T changed the registry from %d to %d nodes, having registered %d; "+ - "a settlement rewrites nodes the registry holds, and adds one only through Register", + "a settlement rewrites nodes the registry holds, and adds one only through Register or PrimitiveRef", settlement, before, after, t.minted-minted) } + digests.digestAliases(t.reg, t.registered) + t.registered = t.registered[:0] + } + for _, alias := range digests.rewrittenAliases(t.reg) { + diags = append(diags, ir.NewDiagnostic(ir.SeverityError, AliasBaseRewritten, + "internal: a settlement rewrote the alias "+string(alias)+", or what a reading of its chain takes from "+ + "the node its Base names, which every reader of an alias chain reads once for the settlements", + ir.Provenance{Source: ir.NoSource})) } return diags } diff --git a/compilers/compile/settle_test.go b/compilers/compile/settle_test.go index 18da7ae78..3df17a905 100644 --- a/compilers/compile/settle_test.go +++ b/compilers/compile/settle_test.go @@ -17,7 +17,54 @@ import ( // settleFunc adapts a function to compile.Settlement. type settleFunc func(reg ir.TypeRegistry) []ir.Diagnostic -func (f settleFunc) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { return f(reg) } +func (f settleFunc) Settle(_ context.Context, reg ir.TypeRegistry, _ *ir.AliasChainIndex) []ir.Diagnostic { + return f(reg) +} + +// aliasesRead adapts to compile.Settlement a function reading the alias index +// a settlement is handed. +type aliasesRead func(reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic + +func (f aliasesRead) Settle(_ context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + return f(reg, aliases) +} + +// TestTypes_SettleHandsEverySettlementOneAliasIndex pins the index the +// settlements share: completions and deferred ones are each handed the same +// one, which reads the registry they are handed as it is when asked, an +// alias an earlier settlement registered included. +func TestTypes_SettleHandsEverySettlementOneAliasIndex(t *testing.T) { + t.Parallel() + types := compile.NewTypes() + types.Intern("/a", "type/source/a", func() ir.TypeDef { + return &ir.Scalar{ID: "type/source/a", Base: &ir.TypeRef{Target: "type/source/b"}} + }) + types.Intern("/b", "type/source/b", func() ir.TypeDef { return &ir.Model{ID: "type/source/b"} }) + var handed []*ir.AliasChainIndex + var ends []ir.TypeID + types.QueueSettlementBeforeDeferredOnes(aliasesRead(func(_ ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + handed = append(handed, aliases) + types.Register("type/minted/c", &ir.Scalar{ID: "type/minted/c", Base: &ir.TypeRef{Target: "type/source/a"}}) + return nil + })) + types.Defer(aliasesRead(func(_ ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + handed = append(handed, aliases) + for _, id := range []ir.TypeID{"type/source/a", "type/minted/c"} { + end, cyclic := aliases.End(id) + require.False(t, cyclic, "%s", id) + ends = append(ends, end) + } + return nil + })) + + assert.Empty(t, types.Settle(t.Context())) + + require.Len(t, handed, 2) + require.NotNil(t, handed[0]) + assert.Same(t, handed[0], handed[1], "one index for the run's settlements") + assert.Equal(t, []ir.TypeID{"type/source/b", "type/source/b"}, ends, "the index reads the registry the settlements write") + assert.Empty(t, types.Violations()) +} // TestTypes_SettleTakesEachDeferredSettlementOnceInOrder pins what a compiler // relies on: every settlement it deferred runs, once, against the live @@ -41,9 +88,9 @@ func TestTypes_SettleTakesEachDeferredSettlementOnceInOrder(t *testing.T) { require.Len(t, diags, 2) assert.Equal(t, "first", diags[0].Code) assert.Equal(t, "second", diags[1].Code) - td, ok := types.Node("type/x") + typeDef, ok := types.Node("type/x") require.True(t, ok) - assert.Equal(t, "firstsecond", td.Common().Docs.Description, "a settlement rewrites the registry the document holds") + assert.Equal(t, "firstsecond", typeDef.Common().Docs.Description, "a settlement rewrites the registry the document holds") assert.Empty(t, types.Settle(t.Context()), "a settlement taken is not taken again") assert.Empty(t, types.Violations()) } @@ -213,10 +260,10 @@ func TestTypes_FinishBuildsPromisesBeforeSettling(t *testing.T) { assert.Equal(t, []ir.Diagnostic{{Code: "built"}, {Code: "settled"}}, diags) } -// TestTypes_SettlementMayRegisterWhatItMints pins the one way a settlement adds -// a node: through Register, which holds it to a minted namespace. A node -// registered twice counts once, and one more written past Register is still -// refused beside it. +// TestTypes_SettlementMayRegisterWhatItMints pins the ways a settlement adds a +// node: through Register, which holds it to a minted namespace, and through +// PrimitiveRef, which interns a primitive once. A node registered twice counts +// once, and one more written past Register is still refused beside it. func TestTypes_SettlementMayRegisterWhatItMints(t *testing.T) { t.Parallel() for _, c := range []struct { @@ -235,6 +282,11 @@ func TestTypes_SettlementMayRegisterWhatItMints(t *testing.T) { types.Register("type/minted/a", &ir.Model{ID: "type/minted/a"}) reg["type/minted/b"] = &ir.Model{ID: "type/minted/b"} }, 1}, + {"registered, and a primitive interned", func(types *compile.Types, _ ir.TypeRegistry) { + types.Register("type/minted/a", &ir.Model{ID: "type/minted/a"}) + types.PrimitiveRef(ir.PrimitiveUUID) + types.PrimitiveRef(ir.PrimitiveUUID) + }, 0}, } { t.Run(c.name, func(t *testing.T) { t.Parallel() @@ -249,7 +301,7 @@ func TestTypes_SettlementMayRegisterWhatItMints(t *testing.T) { assert.Len(t, types.Violations(), c.refused) _, ok := types.Node("type/minted/a") - assert.True(t, ok, "the registered node stands") + assert.True(t, ok, "the registered node remains") }) } } @@ -257,7 +309,7 @@ func TestTypes_SettlementMayRegisterWhatItMints(t *testing.T) { // TestTypes_SettlementThatAddsOrRemovesANodeIsRefused pins the writes a // settlement may not make. Nothing lowers after Settle, so a node written past // Register is one no lowering produced, and a removed one leaves its references -// dangling. Either is reported as a breach, and left standing. +// dangling. Either is reported as a breach, and left in place. func TestTypes_SettlementThatAddsOrRemovesANodeIsRefused(t *testing.T) { t.Parallel() cases := []struct { @@ -288,7 +340,7 @@ func TestTypes_SettlementThatAddsOrRemovesANodeIsRefused(t *testing.T) { require.Len(t, types.Violations(), 1) assert.Contains(t, types.Violations()[0], c.want) _, present := types.Node("type/other") - assert.Equal(t, c.present, present, "what the settlement did is left standing") + assert.Equal(t, c.present, present, "what the settlement did is left in place") }) } } diff --git a/compilers/compile/types.go b/compilers/compile/types.go index 48f8f28d4..8ebb1c289 100644 --- a/compilers/compile/types.go +++ b/compilers/compile/types.go @@ -41,9 +41,12 @@ type Types struct { pending []Settlement // reported counts the entries of refused that Finish has reported. reported int - // minted counts the nodes Register added, so settle can tell them from a - // node a settlement wrote past it. + // minted counts the nodes Register and PrimitiveRef added, so settle can + // tell them from a node a settlement wrote past both. minted int + // registered holds the IDs Register stores while a settlement runs, whose + // aliases settle copies once it returns. + registered []ir.TypeID // fulfilled records that Finish has built the promises, and settled that // it has taken the settlements. fulfilled bool @@ -64,13 +67,21 @@ func (t *Types) refuse(format string, args ...any) { // locates nothing in a source. const RegistryRefused = "compile/registry-refused" +// AliasBaseRewritten is the code of the error Finish reports for an alias +// scalar a settlement changed, itself or what a chain reading takes of the +// node its Base names (chainReadingDigest), since the settlements began or the +// settlement registering it returned. Every reader of an alias chain during +// the settlements relies on none of that changing, so it names a compiler bug, +// reported as RegistryRefused is. +const AliasBaseRewritten = "compile/alias-base-rewritten" + // Finish ends a compile's use of t, after its last lowering. It builds each // promised node no lowering built (ReserveNodeAtCoordinate), takes every -// deferred Settlement, then hands over the Document's registry and the -// diagnostics to report: what building and settling reported, then a -// RegistryRefused error for each entry t refused, in order. The refusals ride -// in the list a compiler reports anyway, so it cannot take the registry and -// lose them. +// deferred Settlement, then hands over the registry and the diagnostics to +// report: what building and settling reported, an AliasBaseRewritten error for +// each alias whose chain reading a settlement changed, then a RegistryRefused +// error for each entry t refused, in order, in the list a compiler reports +// anyway. // // Each refusal is reported once, and one made after Finish only by a later // call. A cancelled ctx stops it between steps, leaving a registry the caller @@ -153,6 +164,20 @@ func (t *Types) claimSpace(id ir.TypeID, minted bool) { // so a caller must not rely on build running — it is the interning table, not a // constructor. func (t *Types) Intern(pointer string, id ir.TypeID, build func() ir.TypeDef) ir.TypeID { + return t.intern(pointer, id, build, false) +} + +// InternMinted is Intern for a node a lowering mints at coordinate, a key no +// source pointer spells, in a namespace of minted nodes: a position lowered +// in place of another, which sits where that one would but holds no source +// coordinate of its own. +func (t *Types) InternMinted(coordinate string, id ir.TypeID, build func() ir.TypeDef) ir.TypeID { + return t.intern(coordinate, id, build, true) +} + +// intern is Intern and InternMinted, minted saying which namespace id claims +// (claimSpace). +func (t *Types) intern(pointer string, id ir.TypeID, build func() ir.TypeDef, minted bool) ir.TypeID { if existing, ok := t.byPointer[pointer]; ok { return existing } @@ -161,11 +186,11 @@ func (t *Types) Intern(pointer string, id ir.TypeID, build func() ir.TypeDef) ir return id } - t.claimSpace(id, false) + t.claimSpace(id, minted) t.claimID(id, pointer) t.byPointer[pointer] = id - td := build() // may recurse; a self-reference hits byPointer above - if ir.IsNilTypeDef(td) { + typeDef := build() // may recurse; a self-reference hits byPointer above + if ir.IsNilTypeDef(typeDef) { // Leaving the coordinate mapped would be the one state NodeAt's contract // rules out: a pointer that resolves to an ID holding no node. delete(t.byPointer, pointer) @@ -173,11 +198,11 @@ func (t *Types) Intern(pointer string, id ir.TypeID, build func() ir.TypeDef) ir t.refuse("intern rejected: build returned a nil type definition for id=%q at %q", id, pointer) return id } - t.reg[id] = td + t.reg[id] = typeDef return id } -// Register records td under id, a node a lowering or a Settlement mints rather +// Register records typeDef under id, a node a lowering or a Settlement mints rather // than finds, with no source coordinate: a composed union variant's denotes the // branch schema it was built from, so interning it there would race for one // pointer. @@ -185,14 +210,14 @@ func (t *Types) Intern(pointer string, id ir.TypeID, build func() ir.TypeDef) ir // Prefer Intern for a node with a source coordinate: it enforces one node per // coordinate and terminates recursion. A colliding ID must be one node minted // alike twice, as a distributed union's variants mint a composed field. Any -// other is a minting bug, refused with the held node standing. claimSpace +// other is a minting bug, refused with the held node left in place. claimSpace // checks the namespace. -func (t *Types) Register(id ir.TypeID, td ir.TypeDef) { +func (t *Types) Register(id ir.TypeID, typeDef ir.TypeDef) { if id == "" { t.refuse("register rejected: empty type id") return } - if ir.IsNilTypeDef(td) { + if ir.IsNilTypeDef(typeDef) { t.refuse("register rejected: nil type definition for id=%q", id) return } @@ -201,13 +226,16 @@ func (t *Types) Register(id ir.TypeID, td ir.TypeDef) { // a second symptom of the same bug, further from its source. t.claimSpace(id, true) if held, ok := t.reg[id]; ok { - if !reflect.DeepEqual(held, td) { + if !reflect.DeepEqual(held, typeDef) { t.refuse("register rejected: id=%q already holds a different node", id) } return } t.minted++ - t.reg[id] = td + t.reg[id] = typeDef + if t.settled { + t.registered = append(t.registered, id) + } } // Lookup returns the ID interned at pointer, if any. @@ -228,14 +256,14 @@ func (t *Types) NodeAt(pointer string) (ir.TypeDef, bool) { if !ok { return nil, false } - td, built := t.reg[id] - return td, built + typeDef, built := t.reg[id] + return typeDef, built } // Node returns the type definition registered under id, if any. func (t *Types) Node(id ir.TypeID) (ir.TypeDef, bool) { - td, ok := t.reg[id] - return td, ok + typeDef, ok := t.reg[id] + return typeDef, ok } // Building reports whether Intern is still building the node id names: the ID @@ -268,6 +296,7 @@ func (t *Types) Building(id ir.TypeID) bool { func (t *Types) PrimitiveRef(primitiveKind ir.PrimitiveKind) ir.TypeRef { id := ir.PrimitiveTypeID(primitiveKind) if _, ok := t.reg[id]; !ok { + t.minted++ t.reg[id] = &ir.Primitive{ ID: id, Provenance: ir.Provenance{Source: ir.NoSource}, diff --git a/compilers/compile/types_test.go b/compilers/compile/types_test.go index 422301ee0..df04ffad2 100644 --- a/compilers/compile/types_test.go +++ b/compilers/compile/types_test.go @@ -53,9 +53,9 @@ func TestTypes_NodeAtResolvesCoordinateAndNodeTogether(t *testing.T) { types := compile.NewTypes() types.Intern("/p", "type/x", func() ir.TypeDef { return &ir.Model{ID: "type/x"} }) - td, ok := types.NodeAt("/p") + typeDef, ok := types.NodeAt("/p") require.True(t, ok, "an interned coordinate resolves to its node in one step") - assert.Equal(t, ir.TypeID("type/x"), td.Common().ID) + assert.Equal(t, ir.TypeID("type/x"), typeDef.Common().ID) _, ok = types.NodeAt("/never-interned") assert.False(t, ok, "and an uninterned coordinate reports the miss") @@ -110,9 +110,9 @@ func TestTypes_RegisterTakesNoCoordinate(t *testing.T) { types := compile.NewTypes() types.Register("type/composed", &ir.Model{ID: "type/composed"}) - td, ok := types.Node("type/composed") + typeDef, ok := types.Node("type/composed") require.True(t, ok) - assert.Equal(t, ir.TypeID("type/composed"), td.Common().ID) + assert.Equal(t, ir.TypeID("type/composed"), typeDef.Common().ID) _, coordinated := types.Lookup("type/composed") assert.False(t, coordinated, "a minted node claims no coordinate") @@ -131,9 +131,9 @@ func TestTypes_PrimitiveRefInternsOnceAndNamesNoSource(t *testing.T) { assert.Equal(t, first.Target, types.PrimitiveID(ir.PrimitiveString), "a second reach is the same ID") assert.Equal(t, 1, types.Len(), "and interns nothing further") - td, ok := types.Node(first.Target) + typeDef, ok := types.Node(first.Target) require.True(t, ok) - assert.Equal(t, ir.Provenance{Source: ir.NoSource}, td.Common().Provenance) + assert.Equal(t, ir.Provenance{Source: ir.NoSource}, typeDef.Common().Provenance) _, coordinated := types.Lookup(string(first.Target)) assert.False(t, coordinated, "primitives are leaves and hold no coordinate") } @@ -276,10 +276,10 @@ func TestTypes_RefusesANamespaceUsedBothWays(t *testing.T) { } } -// TestTypes_RegisterRefusesADifferentNodeUnderOneID pins what a colliding ID may -// be. One node minted alike twice is registered once, while a different node is -// a minting bug: an overwrite would change what every reference to the ID means, -// silently, so it is refused and the held node stands. +// TestTypes_RegisterRefusesADifferentNodeUnderOneID pins what a colliding ID +// may be. One node minted alike twice is registered once, while a different +// node is a minting bug: an overwrite would change what every reference to the +// ID means, silently, so it is refused and the held node remains. func TestTypes_RegisterRefusesADifferentNodeUnderOneID(t *testing.T) { t.Parallel() first, other := ir.TypeRef{Target: "type/first"}, ir.TypeRef{Target: "type/other"} @@ -304,3 +304,25 @@ func TestTypes_RegisterRefusesADifferentNodeUnderOneID(t *testing.T) { assert.Same(t, held, got, tc.name) } } + +// TestTypes_InternMintedClaimsAMintedNamespace holds a node interned at a +// minted coordinate to what Intern holds a source one to, a revisit returning +// the first ID, while its namespace is one minted nodes share: a node +// registered there beside it is no refusal, and a source-addressed one is. +func TestTypes_InternMintedClaimsAMintedNamespace(t *testing.T) { + t.Parallel() + types := compile.NewTypes() + id := types.InternMinted("minted:/p", "type/composed/p", func() ir.TypeDef { return &ir.Scalar{ID: "type/composed/p"} }) + assert.Equal(t, ir.TypeID("type/composed/p"), id) + again := types.InternMinted("minted:/p", "type/composed/q", func() ir.TypeDef { return &ir.Any{} }) + assert.Equal(t, id, again, "a revisit returns the first ID") + types.Register("type/composed/r", &ir.Scalar{ID: "type/composed/r"}) + _, diags := types.Finish(t.Context()) + assert.Empty(t, diags, "minted nodes share their namespace") + + mixed := compile.NewTypes() + mixed.InternMinted("minted:/p", "type/composed/p", func() ir.TypeDef { return &ir.Scalar{ID: "type/composed/p"} }) + mixed.Intern("/p", "type/composed/s", func() ir.TypeDef { return &ir.Scalar{ID: "type/composed/s"} }) + _, diags = mixed.Finish(t.Context()) + assert.Len(t, diags, 1, "a source-addressed node in a minted namespace is refused") +} diff --git a/compilers/compilers.go b/compilers/compilers.go index 48dec67a8..e4980f9da 100644 --- a/compilers/compilers.go +++ b/compilers/compilers.go @@ -119,9 +119,9 @@ type Compiler interface { // them. // // diags is read only when ok is false. Declining another format's bytes - // within SourceLimit is silent; for this compiler's own source, unreadable - // or one opts forbid reading, diags holds an error saying why, naming src as - // Source 0, or no source. + // within SourceLimit reports nothing; for this compiler's own source, + // unreadable or one opts forbid reading, diags holds an error saying why, + // naming src as Source 0, or no source. Detect(ctx context.Context, src Source, opts Options) (rec Recognition, diags []ir.Diagnostic, ok bool) // DecodeOptions turns textual settings into the value this compiler expects // in Options.FormatOptions. An empty set yields defaults. An unknown key or diff --git a/compilers/compilers_cancel_test.go b/compilers/compilers_cancel_test.go index 05f91c91d..0e33a0ebb 100644 --- a/compilers/compilers_cancel_test.go +++ b/compilers/compilers_cancel_test.go @@ -17,8 +17,8 @@ import ( // cancellingDetect is a compiler whose Detect cancels the run and then answers // in a way that would mislead were it judged: a claim naming no format, which -// the registry would refuse as a breach, or, when declines is set, a silent -// decline, which would report a source no compiler takes. +// the registry would refuse as a breach, or, when declines is set, a +// decline reporting nothing, which would report a source no compiler takes. type cancellingDetect struct { stubCompiler cancel context.CancelFunc diff --git a/compilers/compilers_sourcelimit_test.go b/compilers/compilers_sourcelimit_test.go index e93ef7d34..229a737d5 100644 --- a/compilers/compilers_sourcelimit_test.go +++ b/compilers/compilers_sourcelimit_test.go @@ -95,7 +95,7 @@ func TestRegistry_SourceLimitRefusesACompilerThatPanics(t *testing.T) { // TestRegistry_DetectHoldsEachAnswerToTheCompilersLimit pins the duty a source // cut at the limits rests on: past its own SourceLimit a compiler declines, // saying why, so the first bytes of a source are never taken for the whole of -// one. Within the limit, and under no limit, any answer stands. The limit is +// one. Within the limit, and under no limit, any answer holds. The limit is // the one the compiler reports under the options it was asked with. func TestRegistry_DetectHoldsEachAnswerToTheCompilersLimit(t *testing.T) { t.Parallel() @@ -116,7 +116,7 @@ func TestRegistry_DetectHoldsEachAnswerToTheCompilersLimit(t *testing.T) { {name: "a decline past the limit, saying why", data: "nothing!", limit: 5, declines: refusal}, {name: "a decline past the limit, saying nothing", data: "nothing!", limit: 5, wantErr: "detect by alpha@1: declined a source of 8 bytes, past its limit of 5, saying nothing"}, - {name: "a silent decline within the limit", data: "none", limit: 5}, + {name: "a decline reporting nothing within the limit", data: "none", limit: 5}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { diff --git a/compilers/compilers_test.go b/compilers/compilers_test.go index 2e623f1ff..b517ec6ae 100644 --- a/compilers/compilers_test.go +++ b/compilers/compilers_test.go @@ -27,7 +27,7 @@ type stubCompiler struct { // declines is what this compiler says when it does not take a source, which // the registry is meant to carry out for the caller to report. declines []ir.Diagnostic - // parsed stands in for what this compiler made of a source while + // parsed takes the place of what this compiler made of a source while // recognizing it, which the registry carries to its own Compile and to no // other compiler's. parsed any diff --git a/compilers/openapi/budgets_internal_test.go b/compilers/openapi/budgets_internal_test.go index fda60fa33..0ceee4483 100644 --- a/compilers/openapi/budgets_internal_test.go +++ b/compilers/openapi/budgets_internal_test.go @@ -231,7 +231,7 @@ func TestCompile_AliasBudgetIsTheCallersToSet(t *testing.T) { } // TestCompile_AnUnboundedAliasBudgetStillRefusesABomb pins what turning the -// budget off leaves standing: a document expanding to many times its own size +// budget off leaves in place: a document expanding to many times its own size // is a bomb, which no budget admits. func TestCompile_AnUnboundedAliasBudgetStillRefusesABomb(t *testing.T) { t.Parallel() @@ -429,18 +429,19 @@ components: return ctx.Calls, diags, err } moved := func(diags []ir.Diagnostic) bool { - return openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Pet/discriminator") + return openapitest.HasDiagCodeAt(diags, diag.UnhomedConstruct, "/components/schemas/Pet/discriminator/mapping/cat") } - // Uncancelled, Pet's settlement moves the discriminator; cancelling right + // Uncancelled, Pet's settlement sets the entry routing to Cat, no subtype, + // aside; cancelling right // before it skips the settlement and stops at the boundary after Finish, // while one call later lets the settlement run and still stops at that // boundary before target attachment and pruning. calls, diags, err := runUntil(math.MaxInt) require.NoError(t, err) - require.True(t, moved(diags), "uncancelled, the settlement moves the discriminator") + require.True(t, moved(diags), "uncancelled, the settlement sets the entry aside") // Find the exact call index where the settlement runs: the last live count - // where the discriminator has not moved yet is the settling's own check. + // where the entry is not set aside yet is the settling's own check. settleAt := -1 for live := range calls { _, tryDiags, tryErr := runUntil(live) diff --git a/compilers/openapi/detect.go b/compilers/openapi/detect.go index f5dfad021..d31e6171f 100644 --- a/compilers/openapi/detect.go +++ b/compilers/openapi/detect.go @@ -20,9 +20,9 @@ import ( // It parses all of src, handing Compile the parse in Recognition.Parsed. Three // sources are declined with an error whatever their format: one past // SourceLimit or the node budget, with Compile's refusal, and one whose root -// merges deeper than detection reads, its own keys leaving the version open. Any -// other decline is silent unless src declares a version under a discriminating -// key and is unreadable. +// merges deeper than detection reads, its own keys leaving the version open. +// Any other decline reports nothing unless src declares a version under a +// discriminating key and is unreadable. func (*Compiler) Detect(ctx context.Context, src compilers.Source, opts compilers.Options) (compilers.Recognition, []ir.Diagnostic, bool) { // Source 0 is src: the one source detection is handed is the whole of the // table a declined diagnostic can index (compilers.Compiler.Detect). diff --git a/compilers/openapi/e2e/absent_value_test.go b/compilers/openapi/e2e/absent_value_test.go new file mode 100644 index 000000000..05a5ff5bd --- /dev/null +++ b/compilers/openapi/e2e/absent_value_test.go @@ -0,0 +1,65 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// entryDialect is a dialect whose `required` must hold an entry: the +// document's version and the jsonSchemaDialect it names ("" for its default). +type entryDialect struct{ name, version, dialect string } + +// entryDialects are OpenAPI 3.0's dialect and draft 4's. +var entryDialects = []entryDialect{ + {"3.0", "3.0.3", ""}, + {"draft-04", "3.1.0", "http://json-schema.org/draft-04/schema#"}, +} + +// inDialect returns src, a document, naming dialect as its jsonSchemaDialect, +// or src itself for "". +func inDialect(src, dialect string) string { + if dialect == "" { + return src + } + head, rest, found := strings.Cut(src, "\n") + if !found { + return src + } + return head + "\njsonSchemaDialect: '" + dialect + "'\n" + rest +} + +// TestAbsentValue_AnEmptyRequiredIsRefusedWhereTheDialectRequiresAnEntry holds +// the edge of the reading: OpenAPI 3.0 and draft 4 require `required` to hold +// an entry, so an empty one is no absent value there but the document's error, +// at the keyword, under either spelling of the dialect. +func TestAbsentValue_AnEmptyRequiredIsRefusedWhereTheDialectRequiresAnEntry(t *testing.T) { + t.Parallel() + for _, family := range entryDialects { + _, diags := parseFull(t, inDialect(admissionSpec(family.version, "", "R: {type: object, required: []}"), + family.dialect)) + assert.Equal(t, []ir.Severity{ir.SeverityError}, + diagsAt(diags, "openapi/validation/validation-entry-count", "/components/schemas/R/required"), family.name) + } +} + +// TestAbsentValue_AnyOtherValueSaysSomething holds the limit of the reading: +// an applicator at its default, a nullable where the dialect defines no such +// keyword, an empty format, whose value is collected, and a floor above 0 each +// say something beside the $ref, so the position holds a node of its own. +func TestAbsentValue_AnyOtherValueSaysSomething(t *testing.T) { + t.Parallel() + obj := "Obj: {type: object, properties: {a: {type: string}}}" + for _, keyword := range []string{"additionalProperties: true", "nullable: false", "format: ''", "minProperties: 1"} { + doc, _ := parseVerified(t, conjunctionSpec("3.1.0", "{allOf: [{$ref: '#/components/schemas/Obj'}], "+keyword+"}", obj)) + for _, at := range conjunctionPositions { + assert.NotEqual(t, componentID("Obj"), usedAt(t, doc, at), "%s says something at %s", keyword, at) + } + } +} diff --git a/compilers/openapi/e2e/admission_caps_test.go b/compilers/openapi/e2e/admission_caps_test.go index 97bdbc468..488bcba9a 100644 --- a/compilers/openapi/e2e/admission_caps_test.go +++ b/compilers/openapi/e2e/admission_caps_test.go @@ -5,6 +5,7 @@ package e2e_test import ( "fmt" + "regexp" "slices" "strings" "testing" @@ -82,7 +83,7 @@ func TestCompile_AReadPastTheAdmissionCapsKeepsItsKinds(t *testing.T) { schemas := slices.Concat(capNeighbours, capTarget(tc.kind, n)) inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, diags := compileAnnotationSpec(t, "caps", admissionSpec("3.1.0", "", schemas...)) - requireKindsRead(t, doc, diags) + requireKindsRead(t, doc, diags, capWords(tc.kind)) if schemas[0] != capNeighbours[0] { return } @@ -100,9 +101,11 @@ func TestCompile_AReadPastTheAdmissionCapsKeepsItsKinds(t *testing.T) { } // requireKindsRead holds doc and diags to the lowering of capNeighbours over a -// T of strings: every branch over T dead, every entry over T kept and its -// conjunction reported, O the Base wherever an entry names it. -func requireKindsRead(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { +// T of strings: every branch over T dead, and every object beside an entry +// over T the closed bottom, the conjuncts sharing no kind: no Base, each of +// its own keywords under its plain key and each $ref entry kept, O's too, +// with the conjunction reported. +func requireKindsRead(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, words string) { t.Helper() for name, dead := range map[string]string{"PU": "anyOf/0", "PUr": "anyOf/1"} { union, ok := typeByName(doc, name).(*ir.Union) @@ -110,23 +113,29 @@ func requireKindsRead(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { assert.Len(t, union.Variants, 1, "%s: the branch over T is no variant", name) assert.Contains(t, union.Unmodeled, "openapi:"+dead, name) } - for name, base := range map[string]ir.TypeID{"PA": "", "PA2": componentID("O"), "PA2r": componentID("O")} { + for name, refs := range map[string]int{"PA": 1, "PA2": 2, "PA2r": 2} { model, ok := typeByName(doc, name).(*ir.Model) require.True(t, ok, name) - got := ir.TypeID("") - if model.Base != nil { - got = model.Base.Target - } - assert.Equal(t, base, got, name) + assert.Nil(t, model.Base, "%s: the bottom composes nothing", name) assert.Empty(t, model.Mixins, name) - assert.Contains(t, model.Unmodeled, "openapi:$ref", "%s: the entry over T is kept", name) + assert.Empty(t, model.Properties, name) + kept := 0 + for key := range model.Unmodeled { + if strings.HasPrefix(key, "openapi:$ref") { + kept++ + } + } + assert.Equal(t, refs, kept, "%s: each $ref entry is kept", name) + for _, key := range []string{"openapi:type", "openapi:properties"} { + assert.Contains(t, model.Unmodeled, key, "%s: its own keyword under its plain key", name) + } } requireErrorsAndWarnings(t, diags, []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/PU", contains: []string{"anyOf/0: string"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/PUr", contains: []string{"anyOf/1: string"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/PA", contains: []string{"share no value", "allOf/0: string"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/PA2", contains: []string{"share no value", "allOf/0: string"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/PA2r", contains: []string{"share no value", "allOf/1: string"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/PU", contains: []string{"anyOf/0: " + words}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/PUr", contains: []string{"anyOf/1: " + words}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/PA", contains: []string{"no value satisfies", "allOf/0: " + words}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/PA2", contains: []string{"no value satisfies", "allOf/0: " + words}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/PA2r", contains: []string{"no value satisfies", "allOf/1: " + words}}, }) } @@ -152,12 +161,27 @@ func neighbourhoodOf(doc *ir.Document, diags []ir.Diagnostic) capNeighbourhood { } for _, diagnostic := range diags { if owned(string(diagnostic.Provenance.Pointer)) { + // A report names the first members of a set and counts the + // rest, which is the size, and so the count, that differs. + diagnostic.Message = moreMembers.ReplaceAllString(diagnostic.Message, "… more") out.diags = append(out.diags, diagnostic) } } return out } +// moreMembers matches the count of the members a report leaves unnamed. +var moreMembers = regexp.MustCompile(`… [0-9]+ more`) + +// capWords is how a report names what T, the capTarget of kind, admits: a +// string, or its enum by its first members. +func capWords(kind string) string { + if kind == "enum" { + return `enum ["v0", "v1", "v2", "v3", "v4", … ` + } + return "string" +} + // TestCompile_ABranchPastTheAdmissionCapsBesideANullableBodyLives holds the one // question a read past the caps leaves open: beside a body that may admit // null, whether the branch admits null is not read, so a branch over strings @@ -180,7 +204,7 @@ func TestCompile_ABranchPastTheAdmissionCapsBesideANullableBodyLives(t *testing. if tc.within { assert.Len(t, union.Variants, 1) requireErrorsAndWarnings(t, diags, []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/PN", contains: []string{"anyOf/0: string"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/PN", contains: []string{"anyOf/0: " + capWords(tc.kind)}}, }) return } diff --git a/compilers/openapi/e2e/admission_caps_use_test.go b/compilers/openapi/e2e/admission_caps_use_test.go index 2d398fb37..afa5e613a 100644 --- a/compilers/openapi/e2e/admission_caps_use_test.go +++ b/compilers/openapi/e2e/admission_caps_use_test.go @@ -20,7 +20,7 @@ import ( ) // capUseKeywords are what a use of one target writes beside its $ref and the -// election weighs nothing of: a note, what binds a use, a bound, a structural +// choice weighs nothing of: a note, what binds a use, a bound, a structural // keyword and, where the dialect reads it so, the null the nullable-inference // policy reads as widening the reference. func capUseKeywords(version string) map[string]string { @@ -119,12 +119,12 @@ func useLoweringOf(doc *ir.Document, diags []ir.Diagnostic) useLowering { } // TestCompile_AUseOfOneRefLowersAlikeWhateverItsTargetsSize holds a use of one -// target the election weighs alone, `{$ref: T, K}`, `{allOf: [{$ref: T}], K}` -// and `{allOf: [{$ref: T}, K]}` for K a note, a use's binding, a bound or a +// target the choice weighs alone, `{$ref: T, K}`, `{allOf: [{$ref: T}], K}` and +// `{allOf: [{$ref: T}, K]}` for K a note, a use's binding, a bound or a // structural keyword, at a component, a property, a parameter and a response, // over T and over a $ref to it, to what it lowers to within the caps of // docs/compilers/openapi.md#allof-refinement, past them and in either order: -// the caps stop only what an election compares, and it compares nothing here. +// the caps stop only what a choice compares, and it compares nothing here. func TestCompile_AUseOfOneRefLowersAlikeWhateverItsTargetsSize(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -157,8 +157,8 @@ func TestCompile_AUseOfOneRefLowersAlikeWhateverItsTargetsSize(t *testing.T) { // TestCompile_AUseOfATargetAdmittingNoKindLowersAlikePastTheCaps holds a use // of a target whose conjuncts share no kind to what it lowers to within the // caps, where its read finds no value, past them, where its kinds alone say -// so: `{$ref: N, description: d}` stays the composition the conjuncts sharing -// no value leave, and `{allOf: [{$ref: N}]}`, saying nothing more, the +// so: `{$ref: N, description: d}` is the alias to the bottom N lowers to, +// carrying the note, and `{allOf: [{$ref: N}]}`, saying nothing more, the // reference (docs/compilers/openapi.md#allof-refinement). func TestCompile_AUseOfATargetAdmittingNoKindLowersAlikePastTheCaps(t *testing.T) { t.Parallel() @@ -169,8 +169,11 @@ func TestCompile_AUseOfATargetAdmittingNoKindLowersAlikePastTheCaps(t *testing.T "U_note: {$ref: '#/components/schemas/C', description: d}", "U_one: {allOf: [{$ref: '#/components/schemas/C'}]}"}, capTarget("union", n)...) doc, diags := compileAnnotationSpec(t, "none", admissionSpec("3.1.0", "", schemas...)) - _, model := typeByName(doc, "U_note").(*ir.Model) - assert.True(t, model, "size %d: the note's use composes", n) + note, ok := typeByName(doc, "U_note").(*ir.Scalar) + require.True(t, ok, "size %d: the note's use is an alias, got %T", n, typeByName(doc, "U_note")) + require.NotNil(t, note.Base) + assert.Equal(t, componentID("C"), note.Base.Target, "size %d: the alias to the bottom", n) + assert.Equal(t, "d", note.Docs.Description, "size %d: carrying the note", n) one, ok := typeByName(doc, "U_one").(*ir.Scalar) require.True(t, ok, "size %d: the use saying nothing more is the reference", n) assert.Equal(t, componentID("C"), one.Base.Target) diff --git a/compilers/openapi/e2e/admission_empty_test.go b/compilers/openapi/e2e/admission_empty_test.go index ac2b6a5e3..4031c2ed3 100644 --- a/compilers/openapi/e2e/admission_empty_test.go +++ b/compilers/openapi/e2e/admission_empty_test.go @@ -9,12 +9,16 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" ) // emptyConjunct is a schema C composing a conjunct that admits no value, with -// the errors and warnings the document draws. A pointer holding "{n}" names -// C's allOf entry written n-th in the case, wherever the order puts it. +// the errors and warnings the document draws. A pointer or message holding +// "{n}" names C's allOf entry written n-th in the case, wherever the order +// puts it. type emptyConjunct struct { name string versions []string @@ -24,52 +28,57 @@ type emptyConjunct struct { } // emptyConjuncts are the conjuncts admitting no value an allOf may compose: -// inline, where nothing but the allOf's report says so, and through a $ref or -// as `false`, where the schema or the entry says so itself. +// inline, where nothing but the allOf's report says so, and through a $ref, +// where the schema says so itself. C draws its own warning wherever it is a +// bottom, which a target's report does not settle: it says nothing of C. var emptyConjuncts = []emptyConjunct{ {"an inline type beside a value set of another", bothVersions, nil, []string{"{type: string, enum: [1]}", "{type: object}"}, []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/C", contains: []string{disjoint, "/type: string", "/enum: integer", "object"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/C/allOf/{0}/enum/0", contains: []string{"no instance matches"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C", contains: []string{disjoint, "/type: string", "/enum: [1]", "object"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C/allOf/{0}/enum/0", contains: []string{"no instance matches"}}, }}, {"an inline empty enum", bothVersions, nil, []string{"{enum: []}", "{type: string}", "{type: integer}"}, - []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/C", contains: []string{disjoint, ": no value", "string", "integer"}}}}, + []wantFinding{{code: diag.EmptyEnum, pointer: "/components/schemas/C/allOf/{0}"}}}, {"a lone inline conjunct", bothVersions, nil, []string{"{type: string, enum: [1]}"}, []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/C", contains: []string{disjoint, "allOf/0/type: string", "allOf/0/enum: integer"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/C/allOf/0/enum/0", contains: []string{"no instance matches"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C", contains: []string{disjoint, "allOf/0/type: string", "allOf/0/enum: [1]"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C/allOf/0/enum/0", contains: []string{"no instance matches"}}, }}, {"a target its union beside a scalar reports", bothVersions, []string{"X: {type: string, anyOf: [{type: integer}, {type: boolean}]}"}, []string{"{$ref: '#/components/schemas/X'}", "{type: string}"}, []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/X", contains: []string{"share no value", "anyOf: integer or boolean"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/C/allOf/{1}", contains: []string{"declares a type that is not an object"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/X", contains: []string{"no value satisfies", "anyOf: integer or boolean"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C"}, }}, {"a target its dead union reports", bothVersions, []string{"X: {type: object, anyOf: [{type: string}, {type: integer}]}"}, []string{"{$ref: '#/components/schemas/X'}", "{type: object}"}, - []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/X", contains: []string{"none of its 2 branches"}}}}, + []wantFinding{ + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/X", contains: []string{"no value satisfies", "anyOf: string or integer"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C", contains: []string{disjoint, "allOf/{0}: no value", "object"}}, + }}, {"a target its value set reports", bothVersions, []string{"S: {type: string, enum: [1]}"}, []string{"{$ref: '#/components/schemas/S'}", "{type: object}"}, - []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/S/enum/0", contains: []string{"no instance matches"}}}}, + []wantFinding{ + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/S/enum/0", contains: []string{"no instance matches"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C", contains: []string{disjoint, "allOf/{0}: no value", "object"}}, + }}, {"an alias of a target its value set reports", bothVersions, []string{"S: {type: string, enum: [1]}", "A: {$ref: '#/components/schemas/S'}"}, []string{"{$ref: '#/components/schemas/A'}", "{type: object}"}, - []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/S/enum/0", contains: []string{"no instance matches"}}}}, + []wantFinding{ + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/S/enum/0", contains: []string{"no instance matches"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C", contains: []string{disjoint, "allOf/{0}: no value", "object"}}, + }}, + // The string and the integer share no kind, so C is the bottom, which draws + // its own warning beside the target's though the target admits nothing. {"a target its empty enum reports", bothVersions, []string{"E: {enum: []}"}, []string{"{$ref: '#/components/schemas/E'}", "{type: string}", "{type: integer}"}, []wantFinding{ {code: diag.EmptyEnum, pointer: "/components/schemas/E"}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/C/allOf/{1}", contains: []string{"not an object"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/C/allOf/{2}", contains: []string{"not an object"}}, - }}, - {"a false entry", []string{"3.1.0"}, nil, - []string{"false", "{type: string}", "{type: integer}"}, - []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/C/allOf/{1}", contains: []string{"not an object"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/C/allOf/{2}", contains: []string{"not an object"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C"}, }}, } @@ -77,13 +86,13 @@ var emptyConjuncts = []emptyConjunct{ var bothVersions = []string{"3.0.3", "3.1.0"} // TestCompile_AnEmptyConjunctIsReportedWhereNothingElseSaysSo holds that an -// allOf one of whose conjuncts admits no value is reported at the schema, -// naming it "no value", where nothing else says so: an inline empty enum, and -// a $ref to a schema whose type and union share nothing. An inline value set -// outside its own type lowers the position, so the report names its type and -// its set, as beside the allOf. A `false` entry, or a $ref to a schema whose -// value set or empty enum is reported, says so itself, and the allOf draws -// nothing more. Each holds at both versions, in every order. +// allOf one of whose conjuncts admits no value is reported once at each schema +// nothing else speaks for: a $ref to a schema whose type and union share +// nothing at the schema, an inline empty enum by its own warning where +// written, and an inline value set outside its own type by a report naming +// both. A `false` entry says so itself. A target's report speaks for the +// target alone, so C, a bottom over it, draws its own warning naming the +// target as admitting no value. Each holds at both versions, in every order. func TestCompile_AnEmptyConjunctIsReportedWhereNothingElseSaysSo(t *testing.T) { t.Parallel() for _, tc := range emptyConjuncts { @@ -102,8 +111,13 @@ func TestCompile_AnEmptyConjunctIsReportedWhereNothingElseSaysSo(t *testing.T) { } want := slices.Clone(tc.want) for i := range want { + want[i].contains = slices.Clone(want[i].contains) for at, n := range order { - want[i].pointer = strings.ReplaceAll(want[i].pointer, fmt.Sprintf("{%d}", n), fmt.Sprint(at)) + entry := strings.NewReplacer(fmt.Sprintf("{%d}", n), fmt.Sprint(at)) + want[i].pointer = entry.Replace(want[i].pointer) + for w := range want[i].contains { + want[i].contains[w] = entry.Replace(want[i].contains[w]) + } } } schemas := append([]string{"C: {allOf: [" + strings.Join(written, ", ") + "]}"}, tc.others...) @@ -118,3 +132,17 @@ func TestCompile_AnEmptyConjunctIsReportedWhereNothingElseSaysSo(t *testing.T) { } } } + +// TestCompile_AFalseEntryMakesItsSchemaABottomOfItsOwn holds an allOf writing +// a `false` entry beside a string and an integer, in both orders of the +// entries: the entry reports that it matches nothing, and C, which admits +// nothing, draws its own warning at the position beside it. +func TestCompile_AFalseEntryMakesItsSchemaABottomOfItsOwn(t *testing.T) { + t.Parallel() + for at, entries := range []string{"false, {type: string}, {type: integer}", "{type: integer}, {type: string}, false"} { + _, diags := compileAnnotationSpec(t, "empty", admissionSpec("3.1.0", "", "C: {allOf: ["+entries+"]}")) + falseAt := fmt.Sprintf("/components/schemas/C/allOf/%d", 2*at) + assert.NotEmpty(t, diagsAt(diags, diag.FalseSchema, falseAt), "the entry reports itself: %+v", diags) + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/C"), "%+v", diags) + } +} diff --git a/compilers/openapi/e2e/admission_holders_test.go b/compilers/openapi/e2e/admission_holders_test.go index fddaf54ce..ecc6be576 100644 --- a/compilers/openapi/e2e/admission_holders_test.go +++ b/compilers/openapi/e2e/admission_holders_test.go @@ -11,40 +11,44 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) -// TestCompile_AVariantIsReadWithEverySchemaHoldingItsUnion holds that a field -// declared as a list, a nullable list or a string beside one whose union of an -// object, an array and a string sits in an allOf entry of an object, one or -// two entries deep, beside a typed entry, under a null or beside a null branch, -// is judged against what the object admits: no variant is an array or a -// string, so the merge does not compare the two and keeps the later with its -// own null, in both entry and component orders, at 3.0 and 3.1. The holder -// warns of its dead branches. +// TestCompile_AVariantIsReadWithEverySchemaHoldingItsUnion holds that a list, +// a nullable list or a string beside a union of an object, an array and a +// string on an allOf entry of an object, one or two entries deep, beside a +// typed entry, under a null or beside a null branch, is judged against what the +// object admits: no variant is an array or a string, so the merge keeps the +// later with its own null, in both orders, at 3.0 and 3.1. A union admitting no +// null takes the null beside it away, which the policy keeps at 3.0, marked +// inferred. The holder warns of dead branches. func TestCompile_AVariantIsReadWithEverySchemaHoldingItsUnion(t *testing.T) { t.Parallel() const union = "{anyOf: [{type: object}, {type: array, items: {}}, {type: string}]}" for _, version := range []string{"3.0.3", "3.1.0"} { nullObject, nullList := "type: [object, 'null']", "{type: [array, 'null'], items: {}}" + underNull := ir.TypeRef{} if version == "3.0.3" { nullObject, nullList = "type: object, nullable: true", "{type: array, items: {}, nullable: true}" + underNull = ir.TypeRef{Nullable: true, Inferred: openapi.NullableInferenceHeuristic} } - holders := map[string]struct { - schema string - nullable bool - }{ - "in an entry": {"{type: object, allOf: [" + union + "]}", false}, - "beside a typed entry": {"{allOf: [{type: object}, " + union + "]}", false}, - "two entries deep": {"{type: object, allOf: [{allOf: [" + union + "]}]}", false}, - "under a null": {"{" + nullObject + ", allOf: [" + union + "]}", true}, + type holderNull = struct { + schema string + null ir.TypeRef + } + holders := map[string]holderNull{ + "in an entry": {"{type: object, allOf: [" + union + "]}", ir.TypeRef{}}, + "beside a typed entry": {"{allOf: [{type: object}, " + union + "]}", ir.TypeRef{}}, + "two entries deep": {"{type: object, allOf: [{allOf: [" + union + "]}]}", ir.TypeRef{}}, + "under a null": {"{" + nullObject + ", allOf: [" + union + "]}", underNull}, } if version == "3.1.0" { - holders["beside a null branch"] = struct { - schema string - nullable bool - }{"{type: [object, 'null'], allOf: [{anyOf: [{type: object}, {type: array, items: {}}, {type: string}, {type: 'null'}]}]}", true} + holders["beside a null branch"] = holderNull{ + "{type: [object, 'null'], allOf: [{anyOf: [{type: object}, {type: array, items: {}}, {type: string}, {type: 'null'}]}]}", + ir.TypeRef{Nullable: true}, + } } seconds := map[string]struct { schema, target string @@ -65,7 +69,7 @@ func TestCompile_AVariantIsReadWithEverySchemaHoldingItsUnion(t *testing.T) { t.Parallel() inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, diags := compileAnnotationSpec(t, "holders", admissionSpec(version, "", schemas...)) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/Common/properties/r", contains: []string{"/anyOf/1: array", "/anyOf/2: string"}}}) var uncompared []string for _, diagnostic := range diags { @@ -73,7 +77,7 @@ func TestCompile_AVariantIsReadWithEverySchemaHoldingItsUnion(t *testing.T) { uncompared = append(uncompared, string(diagnostic.Provenance.Pointer)) } } - assert.ElementsMatch(t, []string{"/components/schemas/Coll1/allOf/0", "/components/schemas/Coll2/allOf/0/properties/r"}, + assert.ElementsMatch(t, []string{"/components/schemas/Common/properties/r", "/components/schemas/Coll2/allOf/0/properties/r"}, uncompared, "each order reports the two types the merge does not compare") target := second.target if target == "" { @@ -81,8 +85,9 @@ func TestCompile_AVariantIsReadWithEverySchemaHoldingItsUnion(t *testing.T) { } assert.Equal(t, ir.TypeRef{Target: ir.TypeID(target), Nullable: second.nullable}, typeOfR(t, doc, "Coll1"), "Coll1 keeps its later declaration, with its null") - assert.Equal(t, ir.TypeRef{Target: "type/anonymous/components/schemas/Common/properties/r", Nullable: holder.nullable}, - typeOfR(t, doc, "Coll2"), "Coll2 keeps Common's union, with its null") + want := holder.null + want.Target = "type/anonymous/components/schemas/Common/properties/r" + assert.Equal(t, want, typeOfR(t, doc, "Coll2"), "Coll2 keeps Common's union, with its null") }) }) } diff --git a/compilers/openapi/e2e/admission_test.go b/compilers/openapi/e2e/admission_test.go index c86cdb057..0b1d0378a 100644 --- a/compilers/openapi/e2e/admission_test.go +++ b/compilers/openapi/e2e/admission_test.go @@ -116,11 +116,12 @@ func comparableDocument(t *testing.T, doc *ir.Document) string { return string(raw) + "\n" + strings.Join(findings, "\n") } -// TestCompile_AnEmptyConjunctIsItsOwnSchemasToReport holds that an allOf whose -// conjunct admits nothing by itself draws no report of its own: the conjunct -// that contradicts itself is reported where it is written and the allOf -// naming it draws nothing more, in both orders of the components and of the -// conjuncts. +// TestCompile_AnEmptyConjunctIsItsOwnSchemasToReport holds that a conjunct +// admitting nothing by itself is its own schema's to report: A's contradiction +// is reported where A writes it, and B, the allOf composing it, does not +// repeat it. B admits nothing either, so as a bottom of its own B draws its +// own warning, naming A as admitting no value, for a reader of B alone. Each +// holds in both orders of the components and of the conjuncts. func TestCompile_AnEmptyConjunctIsItsOwnSchemasToReport(t *testing.T) { t.Parallel() for _, swapped := range []bool{false, true} { @@ -139,9 +140,10 @@ func TestCompile_AnEmptyConjunctIsItsOwnSchemasToReport(t *testing.T) { t.Parallel() inBothOrders(t, schemas, func(t *testing.T, schemas []string) { _, diags := compileAnnotationSpec(t, "empty", admissionSpec("3.1.0", "", schemas...)) - requireErrorsAndWarnings(t, diags, []wantFinding{{ - code: diag.DegradedConstruct, pointer: "/components/schemas/A", contains: []string{disjoint, "string", "object"}, - }}) + requireErrorsAndWarnings(t, diags, []wantFinding{ + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/A", contains: []string{disjoint, "string", "object"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/B", contains: []string{disjoint, ": no value", "integer"}}, + }) }) }) } @@ -149,9 +151,9 @@ func TestCompile_AnEmptyConjunctIsItsOwnSchemasToReport(t *testing.T) { // TestCompile_AnAllOfCycleBesideABoundIsReadAlikeFromEveryEntry holds that two // schemas each reaching the other through an allOf, one writing a bound, give -// the same nodes for both whichever is declared first and whichever a -// property enters the cycle through, and the same findings: a read met inside -// an open cycle is no verdict to remember for the schema it started from. +// the same nodes for both whichever is declared first and whichever a property +// enters the cycle through, and the same findings: a read met inside an open +// cycle is no answer to remember for the schema it started from. func TestCompile_AnAllOfCycleBesideABoundIsReadAlikeFromEveryEntry(t *testing.T) { t.Parallel() cycle := []string{ @@ -359,8 +361,8 @@ func TestCompile_ABoundBesideAWideAllOfOfStringsIsDecidedAtEverySize(t *testing. // TestCompile_AUnionConjunctSharingNoKindWithTheOtherIsReported holds that an // allOf of a union of a string and an array and of an object is reported once, // at the schema, naming what each conjunct admits, whichever order the -// components and the conjuncts are written in: a union is read as the join of -// its branches' kinds, not passed over. +// components and the conjuncts are written in: a union is read as the +// combination of its branches' kinds, not passed over. func TestCompile_AUnionConjunctSharingNoKindWithTheOtherIsReported(t *testing.T) { t.Parallel() for _, swapped := range []bool{false, true} { @@ -378,7 +380,7 @@ func TestCompile_AUnionConjunctSharingNoKindWithTheOtherIsReported(t *testing.T) inBothOrders(t, schemas, func(t *testing.T, schemas []string) { _, diags := compileAnnotationSpec(t, "union", admissionSpec("3.1.0", "", schemas...)) requireErrorsAndWarnings(t, diags, []wantFinding{{ - code: diag.DegradedConstruct, pointer: "/components/schemas/UnionAndObject", + code: diag.UnsatisfiableSchema, pointer: "/components/schemas/UnionAndObject", contains: []string{disjoint, "array or string", "object"}, }}) }) @@ -401,8 +403,8 @@ func TestCompile_ANullAliasConjunctIsReadAsTheNullItAliases(t *testing.T) { inBothOrders(t, schemas, func(t *testing.T, schemas []string) { _, diags := compileAnnotationSpec(t, "nil", admissionSpec("3.1.0", "", schemas...)) requireErrorsAndWarnings(t, diags, []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/NullAndString", contains: []string{disjoint, "null", "string"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/NullAliasAndString", contains: []string{disjoint, "null", "string"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/NullAndString", contains: []string{disjoint, "null", "string"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/NullAliasAndString", contains: []string{disjoint, "null", "string"}}, }) var texts []string for _, diagnostic := range diags { @@ -424,7 +426,7 @@ func TestCompile_AnEnumAndATypeSharingNoKindAreReportedAtTheSchema(t *testing.T) inBothOrders(t, []string{"E1: {allOf: [{enum: [1, 2]}, {type: string}]}"}, func(t *testing.T, schemas []string) { _, diags := compileAnnotationSpec(t, "enum", admissionSpec("3.1.0", "", schemas...)) requireErrorsAndWarnings(t, diags, []wantFinding{{ - code: diag.DegradedConstruct, pointer: "/components/schemas/E1", contains: []string{disjoint, "integer", "string"}, + code: diag.UnsatisfiableSchema, pointer: "/components/schemas/E1", contains: []string{disjoint, "enum [1, 2]", "string"}, }}) assert.Equal(t, 1, infosAt(diags, diag.DegradedConstruct, "/components/schemas/E1/allOf/1", ""), "the entry writing the type is an info") @@ -434,7 +436,7 @@ func TestCompile_AnEnumAndATypeSharingNoKindAreReportedAtTheSchema(t *testing.T) _, diags := compileAnnotationSpec(t, "enum", admissionSpec("3.1.0", "", "E1: {allOf: [{type: string}, {enum: [1, 2]}]}")) requireErrorsAndWarnings(t, diags, []wantFinding{{ - code: diag.DegradedConstruct, pointer: "/components/schemas/E1", contains: []string{disjoint}, + code: diag.UnsatisfiableSchema, pointer: "/components/schemas/E1", contains: []string{disjoint}, }}) }) } @@ -457,8 +459,8 @@ func TestCompile_AKeywordBesideARefIsReadByTheDisjointReportAtEveryVersion(t *te inBothOrders(t, schemas, func(t *testing.T, schemas []string) { _, diags := compileAnnotationSpec(t, "beside", admissionSpec(version, "", schemas...)) want := []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/S", contains: []string{disjoint}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/T", contains: []string{disjoint}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/S", contains: []string{disjoint}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/T", contains: []string{disjoint}}, } if version == "3.0.3" { want = append(want, @@ -495,8 +497,9 @@ func redeclaredField(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, id, // TestCompile_AFieldRedeclaredAsAStructureAdmittingItsKindIsNotAConflict holds // that a field declared integer in one allOf entry and in the other as a // structure over a schema stating no type, which admits every integer, keeps -// integer with nothing reported, in both entry orders, while a structure -// refusing only strings through a not stays reported as before. +// integer with nothing reported, in both entry orders, and so does a structure +// refusing only strings through a not of a type, which the read follows +// (GitHub #1671). func TestCompile_AFieldRedeclaredAsAStructureAdmittingItsKindIsNotAConflict(t *testing.T) { t.Parallel() const ( @@ -522,7 +525,7 @@ func TestCompile_AFieldRedeclaredAsAStructureAdmittingItsKindIsNotAConflict(t *t assert.Empty(t, keptEntries(t, doc, "openapi:conflicting-redeclaration/components/schemas/U/allOf/0/properties/f")) _, conflicts = redeclaredField(t, doc, diags, "type/openapi/components/schemas/T", "f", "/components/schemas/T") - assert.Equal(t, 1, conflicts, "T keeps its one conflict: a not refuses what the read cannot follow") + assert.Zero(t, conflicts, "no conflict is reported for T: its not refuses strings alone") }) }) } @@ -633,5 +636,5 @@ const ( stringRef = "{$ref: '#/components/schemas/Str'}" objRef = "{$ref: '#/components/schemas/Obj'}" intRef = "{$ref: '#/components/schemas/Int'}" - disjoint = "share no value" + disjoint = "no value satisfies" ) diff --git a/compilers/openapi/e2e/admission_words_test.go b/compilers/openapi/e2e/admission_words_test.go index df6402bdb..69383e2a2 100644 --- a/compilers/openapi/e2e/admission_words_test.go +++ b/compilers/openapi/e2e/admission_words_test.go @@ -19,8 +19,8 @@ func TestCompile_ADisjointReportNamesAFraction(t *testing.T) { for _, tc := range []struct { fraction, other, fractionWords, otherWords string }{ - {"{enum: [1.5]}", "{type: integer}", "number that is no integer", "integer"}, - {"{enum: [1.5, a]}", "{type: boolean}", "string or number that is no integer", "boolean"}, + {"{enum: [1.5]}", "{type: integer}", "enum [1.5]", "integer"}, + {"{enum: [1.5, a]}", "{type: boolean}", `enum [1.5, "a"]`, "boolean"}, } { for _, version := range bothVersions { for _, swapped := range []bool{false, true} { @@ -32,7 +32,7 @@ func TestCompile_ADisjointReportNamesAFraction(t *testing.T) { t.Parallel() _, diags := compileAnnotationSpec(t, "words", admissionSpec(version, "", "C: {allOf: ["+entries+"]}")) requireErrorsAndWarnings(t, diags, []wantFinding{{ - code: diag.DegradedConstruct, pointer: "/components/schemas/C", + code: diag.UnsatisfiableSchema, pointer: "/components/schemas/C", contains: []string{named(at[0], tc.fractionWords), named(at[1], tc.otherWords)}, }}) }) diff --git a/compilers/openapi/e2e/admits_whole_test.go b/compilers/openapi/e2e/admits_whole_test.go index 8bd9f6539..050e75f79 100644 --- a/compilers/openapi/e2e/admits_whole_test.go +++ b/compilers/openapi/e2e/admits_whole_test.go @@ -124,8 +124,9 @@ var typedTargets = []struct { // a T admitting no object alone is no structure but a use of T keeping its // `properties`, so beside the kind in the other allOf entry it folds as the // $ref to T does, the field the same node as D's, which writes the $ref: -// nothing conflicts, and T's narrowing reaches the field, at 3.0 and 3.1, in -// both orders of the components and of the entries. +// nothing conflicts, and T's narrowing reaches the field, as does its +// `properties`, on the field or in the declaration a fold dropping it keeps, +// at 3.0 and 3.1, in both orders of the components and of the entries. func TestCompile_AnAllOfOverATypedTargetFoldsAsItsRef(t *testing.T) { t.Parallel() for _, tc := range typedTargets { @@ -147,7 +148,7 @@ func TestCompile_AnAllOfOverATypedTargetFoldsAsItsRef(t *testing.T) { refTarget, _ := redeclaredField(t, doc, diags, "type/openapi/components/schemas/D", "p", "/components/schemas/D") assert.Equal(t, refTarget, target, "the field is what the $ref spelling gives") requireHeld(t, fieldClosure(t, doc, "type/openapi/components/schemas/C", "p"), - [][]string{{tc.fact}, {`"openapi:properties"`}}) + [][]string{{tc.fact}, {`"openapi:properties"`, `"properties":{"a":{"type":"string"}}`}}) }) }) } @@ -155,15 +156,16 @@ func TestCompile_AnAllOfOverATypedTargetFoldsAsItsRef(t *testing.T) { } } -// TestCompile_AStructureAdmittingPartOfAKindConflictsWithIt holds that a field +// TestCompile_AStructureAdmittingPartOfAKindSharesItsValues holds that a field // declared as a kind in one allOf entry and, in the other, as a structure // whose source admits that kind but refuses some instance of it, through a -// bound or a format a target declaring no kind writes, or a bound beside it, is -// reported as a conflict: the later declaration's type is the field's and the +// bound or a format a target declaring no kind writes, or a bound beside it, +// shares the instances it admits with the kind, which holds every one: it is +// reported as an overlap, the later declaration's type is the field's and the // earlier is kept verbatim, so every keyword either writes stays in the // document, at 3.0 and 3.1, in both orders of the components and of the // entries. -func TestCompile_AStructureAdmittingPartOfAKindConflictsWithIt(t *testing.T) { +func TestCompile_AStructureAdmittingPartOfAKindSharesItsValues(t *testing.T) { t.Parallel() for _, tc := range partlyAdmitted { for _, version := range []string{"3.0.3", "3.1.0"} { @@ -179,10 +181,8 @@ func TestCompile_AStructureAdmittingPartOfAKindConflictsWithIt(t *testing.T) { t.Parallel() inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, diags := compileAnnotationSpec(t, "partly", admissionSpec(version, "", schemas...)) - requireErrorsAndWarnings(t, diags, []wantFinding{{ - code: diag.ConflictingRedecl, pointer: "/components/schemas/C/allOf/0/properties/p", - contains: []string{"incompatible types"}, - }}) + requireErrorsAndWarnings(t, diags, nil) + assert.Equal(t, 1, infosAt(diags, diag.DegradedConstruct, "/components/schemas/C/allOf/0/properties/p", "whose values overlap")) kept := "openapi:conflicting-redeclaration/components/schemas/C/allOf/0/properties/p" assert.Equal(t, []string{"/components/schemas/C/allOf/0/properties/p"}, keptEntries(t, doc, kept)) target, _ := redeclaredField(t, doc, diags, "type/openapi/components/schemas/C", "p", "/components/schemas/C") diff --git a/compilers/openapi/e2e/alias_end_settled_test.go b/compilers/openapi/e2e/alias_end_settled_test.go new file mode 100644 index 000000000..8f7e7abeb --- /dev/null +++ b/compilers/openapi/e2e/alias_end_settled_test.go @@ -0,0 +1,62 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestAliasBaseRewritten_AModelAnAliasNamesSettlesItsMembersUnreported holds +// the alias a lone allOf of a model admitting null lowers to, composed beside +// a schema redeclaring that model's member: the member settles, which no +// reading of the alias's chain takes, so no alias is reported rewritten, +// whatever the composer is named, and the redeclaration is reported once, +// naming the type the member settled to, minted at the fold's key, whose +// source no read places, so nothing shows it shares a string or none. +func TestAliasBaseRewritten_AModelAnAliasNamesSettlesItsMembersUnreported(t *testing.T) { + t.Parallel() + for _, composer := range []string{"Alpha", "Zulu"} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Root: + type: [object, "null"] + properties: {children: {type: array, items: {type: string}}} + Zed: + type: [object, "null"] + allOf: [{$ref: '#/components/schemas/Root'}] + properties: {children: {type: array, maxItems: 3}} + Wrap: {allOf: [{$ref: '#/components/schemas/Zed'}]} + `+composer+`: + allOf: + - $ref: '#/components/schemas/Wrap' + - {type: object, properties: {children: {type: string}}} +`)) + + assert.NotContains(t, codesOf(diags), compile.AliasBaseRewritten, composer) + openapitest.RequireNoErrorDiags(t, diags) + alias, isAlias := typeByName(doc, "Wrap").(*ir.Scalar) + require.True(t, isAlias, "%s: the lone allOf lowers to an alias: %T", composer, typeByName(doc, "Wrap")) + require.NotNil(t, alias.Base, composer) + assert.Equal(t, componentID("Zed"), alias.Base.Target, composer) + redeclared := fieldComparisonReports(diags) + require.Len(t, redeclared, 1, "%s: %+v", composer, diags) + assert.Equal(t, diag.DegradedConstruct+" /components/schemas/Zed/allOf/properties/children", redeclared[0], composer) + messages := make([]string, 0, 1) + for _, diagnostic := range diags { + if diagnostic.Provenance.Pointer == "/components/schemas/Zed/allOf/properties/children" { + messages = append(messages, diagnostic.Message) + } + } + assert.Equal(t, []string{`field "children" of /components/schemas/` + + composer + ": /components/schemas/" + composer + "/allOf/1/properties/children and " + + "/components/schemas/Zed/allOf/properties/children give types string and a list that the merge cannot show to share a value " + + "or to share none; chose the type the first gives; the second stays declared on its model"}, messages, composer) + } +} diff --git a/compilers/openapi/e2e/kept_entry_keyword_test.go b/compilers/openapi/e2e/allof_entry_kept_keyword_test.go similarity index 80% rename from compilers/openapi/e2e/kept_entry_keyword_test.go rename to compilers/openapi/e2e/allof_entry_kept_keyword_test.go index aab8a9aa3..574684978 100644 --- a/compilers/openapi/e2e/kept_entry_keyword_test.go +++ b/compilers/openapi/e2e/allof_entry_kept_keyword_test.go @@ -18,7 +18,7 @@ import ( "github.com/dexpace/morphic/ir" ) -func TestKeptEntryKeyword_AValueKeywordThatLosesTheElectionIsKeptUnderItsOwnKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_AValueKeywordPassedOverIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "enum-beside-const", principal: "{type: string}", keyword: "enum: [a, b], const: a", versions: keptOnly31, @@ -27,7 +27,7 @@ func TestKeptEntryKeyword_AValueKeywordThatLosesTheElectionIsKeptUnderItsOwnKey( }}) } -func TestKeptEntryKeyword_AClosureTheEntryCannotTypeKeepsTheEntryWhole(t *testing.T) { +func TestAllOfEntryKeptKeyword_AClosureTheEntryCannotTypeKeepsTheEntryWhole(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{ { @@ -36,12 +36,14 @@ func TestKeptEntryKeyword_AClosureTheEntryCannotTypeKeepsTheEntryWhole(t *testin finds: []keptFinding{keptDegraded("/allOf/{i}", "additionalProperties")}, }, { - // The principal declares a member inline: a $ref's target declares none - // the closure reads (docs/compilers/openapi.md#additional-properties). + // The principal declares a member inline, which the closure also + // applies to: it types the model, kept verbatim with one info naming + // the member, and the entry is not kept whole + // (docs/compilers/openapi.md#additional-properties). name: "closure-where-two-conjuncts-declare-members", principal: "{type: object, properties: {a: {type: string}}}", - keyword: "properties: {b: {type: string}}, additionalProperties: false", whole: true, - want: degradedKept("openapi:allOf/{i}"), - finds: []keptFinding{keptDegraded("/allOf/{i}", "additionalProperties")}, + keyword: "properties: {b: {type: string}}, additionalProperties: false", + want: degradedKept("openapi:additionalProperties"), + finds: []keptFinding{keptDegraded("/allOf/{i}/additionalProperties", "additionalProperties", "a")}, }, { // The entry takes the reason the keyword has beside the allOf. @@ -60,7 +62,7 @@ func TestKeptEntryKeyword_AClosureTheEntryCannotTypeKeepsTheEntryWhole(t *testin }) } -func TestKeptEntryKeyword_ARelativeReferenceMergedInPlaceKeepsTheEntryApart(t *testing.T) { +func TestAllOfEntryKeptKeyword_ARelativeReferenceMergedInPlaceKeepsTheEntryApart(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "merged-member", principal: keptObj, versions: keptOnly31, @@ -78,7 +80,7 @@ func TestKeptEntryKeyword_ARelativeReferenceMergedInPlaceKeepsTheEntryApart(t *t }}) } -func TestKeptEntryKeyword_AValidationOnlyKeywordIsKeptUnderItsOwnKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_AValidationOnlyKeywordIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() vo := func(key string) map[string]ir.UnmodeledReason { return map[string]ir.UnmodeledReason{key: ir.ReasonValidationOnly} @@ -111,7 +113,7 @@ func TestKeptEntryKeyword_AValidationOnlyKeywordIsKeptUnderItsOwnKey(t *testing. }) } -func TestKeptEntryKeyword_ANoteWithNoFieldIsKeptUnderItsOwnKeyAndTheRestAreTyped(t *testing.T) { +func TestAllOfEntryKeptKeyword_ANoteWithNoFieldIsKeptUnderItsOwnKeyAndTheRestAreTyped(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "docs-and-visibility", principal: keptString, twin: true, @@ -125,7 +127,7 @@ func TestKeptEntryKeyword_ANoteWithNoFieldIsKeptUnderItsOwnKeyAndTheRestAreTyped }}) } -func TestKeptEntryKeyword_AVendorExtensionIsKeptUnderItsOwnKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_AVendorExtensionIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "vendor-extension", principal: keptString, keyword: "x-a: 1", twin: true, @@ -133,7 +135,7 @@ func TestKeptEntryKeyword_AVendorExtensionIsKeptUnderItsOwnKey(t *testing.T) { }}) } -func TestKeptEntryKeyword_ABoundTheTypeTakesIsTypedAndKeptNowhere(t *testing.T) { +func TestAllOfEntryKeptKeyword_ABoundTheTypeTakesIsTypedAndKeptNowhere(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "string-bound-on-a-string", principal: keptString, keyword: "minLength: 2", twin: true, @@ -148,7 +150,7 @@ func TestKeptEntryKeyword_ABoundTheTypeTakesIsTypedAndKeptNowhere(t *testing.T) }}) } -func TestKeptEntryKeyword_AnEntryDisagreeingWithAnotherIsKeptWholeInEveryOrder(t *testing.T) { +func TestAllOfEntryKeptKeyword_AnEntryDisagreeingWithAnotherIsKeptWholeInEveryOrder(t *testing.T) { t.Parallel() for _, version := range keptKeywordVersions { t.Run(version, func(t *testing.T) { @@ -172,7 +174,7 @@ func TestKeptEntryKeyword_AnEntryDisagreeingWithAnotherIsKeptWholeInEveryOrder(t } } -func TestKeptEntryKeyword_ANullableNoPolicyAppliesIsKeptOutOfScopeUnderBothPolicies(t *testing.T) { +func TestAllOfEntryKeptKeyword_ANullableNoPolicyAppliesIsKeptOutOfScopeUnderBothPolicies(t *testing.T) { t.Parallel() runKeptNullableCases(t, func(t *testing.T, doc *ir.Document) { t.Helper() @@ -181,7 +183,7 @@ func TestKeptEntryKeyword_ANullableNoPolicyAppliesIsKeptOutOfScopeUnderBothPolic }) } -func TestKeptEntryKeyword_AKindKeywordIsKeptUnderItsOwnKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_AKindKeywordIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "type-narrowing-a-number", principal: keptNumber, keyword: "type: integer", twin: true, @@ -190,7 +192,7 @@ func TestKeptEntryKeyword_AKindKeywordIsKeptUnderItsOwnKey(t *testing.T) { }}) } -func TestKeptEntryKeyword_APerKindBoundNoHomeTakesIsKeptUnderItsOwnKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_APerKindBoundNoHomeTakesIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{ { @@ -221,7 +223,11 @@ func TestKeptEntryKeyword_APerKindBoundNoHomeTakesIsKeptUnderItsOwnKey(t *testin }) } -func TestKeptEntryKeyword_AFormatNoTypePairsWithIsKeptUnderItsOwnKey(t *testing.T) { +// TestAllOfEntryKeptKeyword_AFormatNoTypePairsWithIsKeptUnderItsOwnKey holds a +// format beside a use of an object, which no type of it pairs with, kept under +// its own key with one report. One beside a use of a string restricts it with +// an Encoding instead (TestKeywordScope_AFormatBesideARefToAScalarReadsAsItsFlatTwin). +func TestAllOfEntryKeptKeyword_AFormatNoTypePairsWithIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{ { @@ -229,24 +235,24 @@ func TestKeptEntryKeyword_AFormatNoTypePairsWithIsKeptUnderItsOwnKey(t *testing. want: degradedKept("openapi:format"), finds: []keptFinding{keptDegraded("/allOf/{i}", "format")}, }, - { - name: "unknown-format-on-a-string", principal: keptString, keyword: "format: unknownfmt", twin: true, - want: degradedKept("openapi:format"), - finds: []keptFinding{keptDegraded("/allOf/{i}", "format")}, - }, }) } -func TestKeptEntryKeyword_ContentVocabularyIsKeptUnderItsOwnKeyAndReportedAtTheKey(t *testing.T) { +// TestAllOfEntryKeptKeyword_ContentVocabularyIsKeptUnderItsOwnKeyAndReportedAtTheKey +// holds the content vocabulary beside a use of an object, which holds no +// Encoding, kept under its own key and reported at the keyword. Beside a use +// of a string it restricts the reference instead +// (TestKeywordScope_TheContentVocabularyBesideARefToAStringRestrictsIt). +func TestAllOfEntryKeptKeyword_ContentVocabularyIsKeptUnderItsOwnKeyAndReportedAtTheKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ - name: "media-type", principal: keptString, keyword: "contentMediaType: text/html", versions: keptOnly31, twin: true, + name: "media-type", principal: keptObj, keyword: "contentMediaType: text/html", versions: keptOnly31, twin: true, want: map[string]ir.UnmodeledReason{"openapi:contentMediaType": ir.ReasonNoIRHome}, finds: []keptFinding{keptDegraded("/allOf/{i}/contentMediaType", "contentMediaType")}, }}) } -func TestKeptEntryKeyword_AShapeKeywordOnAUseOfAStringIsKeptUnderItsOwnKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_AShapeKeywordOnAUseOfAStringIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{ { @@ -262,7 +268,7 @@ func TestKeptEntryKeyword_AShapeKeywordOnAUseOfAStringIsKeptUnderItsOwnKey(t *te }) } -func TestKeptEntryKeyword_AChoiceIsKeptUnderItsKeywordWithItsReason(t *testing.T) { +func TestAllOfEntryKeptKeyword_AChoiceIsKeptUnderItsKeywordWithItsReason(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{ { @@ -271,24 +277,28 @@ func TestKeptEntryKeyword_AChoiceIsKeptUnderItsKeywordWithItsReason(t *testing.T finds: []keptFinding{keptValidationOnly("anyOf")}, }, { + // Its boolean branch shares no kind with the string, so the union is + // kept whole, its dead branch reported at the union. name: "one-of-saying-more-than-a-string", principal: keptString, twin: true, keyword: "oneOf: [{type: string, maxLength: 5}, {type: boolean}]", want: degradedKept("openapi:oneOf"), - finds: []keptFinding{keptDegraded("/allOf/{i}", "oneOf")}, + finds: []keptFinding{keptDegraded("/allOf/{i}", "oneOf"), + {severity: ir.SeverityWarning, code: diag.UnsatisfiableSchema, at: "/allOf/{i}/oneOf", words: []string{"oneOf/1: boolean"}}}, }, { name: "one-of-sharing-no-kind-with-an-object", principal: keptObj, twin: true, keyword: "oneOf: [{type: string}, {type: boolean}]", want: degradedKept("openapi:oneOf"), + // The one warning says the position keeps the oneOf, which draws + // no info of its own. finds: []keptFinding{ - {severity: ir.SeverityWarning, code: diag.DegradedConstruct, at: "", words: []string{disjoint}}, - keptDegraded("/allOf/{i}", "oneOf"), + {severity: ir.SeverityWarning, code: diag.UnsatisfiableSchema, at: "", words: []string{disjoint, "oneOf kept verbatim under Unmodeled"}}, }, }, }) } -func TestKeptEntryKeyword_ADynamicReferenceOnAnEntryOfAnItemIsKeptUnderItsOwnKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_ADynamicReferenceOnAnEntryOfAnItemIsKeptUnderItsOwnKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "dynamic-ref-at-items", principal: keptString, keyword: "$dynamicRef: '#m'", versions: keptOnly31, @@ -298,7 +308,7 @@ func TestKeptEntryKeyword_ADynamicReferenceOnAnEntryOfAnItemIsKeptUnderItsOwnKey }}) } -func TestKeptEntryKeyword_AScopedKeywordIsKeptOutOfScopeAndAConsumedOneNowhere(t *testing.T) { +func TestAllOfEntryKeptKeyword_AScopedKeywordIsKeptOutOfScopeAndAConsumedOneNowhere(t *testing.T) { t.Parallel() const commentText = "kept-comment-text" oos := func(key string) map[string]ir.UnmodeledReason { @@ -347,7 +357,7 @@ func TestKeptEntryKeyword_AScopedKeywordIsKeptOutOfScopeAndAConsumedOneNowhere(t }) } -func TestKeptEntryKeyword_AnUnknownKeywordIsKeptOutOfScopeAndReportedAtTheKey(t *testing.T) { +func TestAllOfEntryKeptKeyword_AnUnknownKeywordIsKeptOutOfScopeAndReportedAtTheKey(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{ { @@ -358,7 +368,7 @@ func TestKeptEntryKeyword_AnUnknownKeywordIsKeptOutOfScopeAndReportedAtTheKey(t }) } -func TestKeptEntryKeyword_AnEntryWritingSeveralKeywordsKeepsEachUnderItsOwnReason(t *testing.T) { +func TestAllOfEntryKeptKeyword_AnEntryWritingSeveralKeywordsKeepsEachUnderItsOwnReason(t *testing.T) { t.Parallel() runKeptCases(t, []keptKeywordCase{{ name: "mixed", principal: keptString, twin: true, @@ -383,12 +393,12 @@ func TestKeptEntryKeyword_AnEntryWritingSeveralKeywordsKeepsEachUnderItsOwnReaso // keptEntryBuilder is a closed object whose members the two entries of its // allOf each ask one of to be present, each entry a union declaring no shape: -// the two disagree on anyOf, so neither is folded. +// the two disagree on anyOf, so neither is flattened. const keptEntryBuilder = `Builder: {type: object, additionalProperties: false, properties: {to: {type: string}, cc: {type: string}, text: {type: string}, html: {type: string}}, allOf: [%s, %s]}` -func TestKeptEntryKeyword_TwoUnionsDeclaringNoShapeAreKeptWholeAsValidationOnly(t *testing.T) { +func TestAllOfEntryKeptKeyword_TwoUnionsDeclaringNoShapeAreKeptWholeAsValidationOnly(t *testing.T) { t.Parallel() first := "{anyOf: [{required: [to], type: object}, {required: [cc], type: object}]}" second := "{anyOf: [{required: [text], type: object}, {required: [html], type: object}]}" @@ -418,7 +428,7 @@ func TestKeptEntryKeyword_TwoUnionsDeclaringNoShapeAreKeptWholeAsValidationOnly( } } -func TestKeptEntryKeyword_AnEntryDisagreeingWithAnotherKeepsItsKeywordsReasonWhenKeptWhole(t *testing.T) { +func TestAllOfEntryKeptKeyword_AnEntryDisagreeingWithAnotherKeepsItsKeywordsReasonWhenKeptWhole(t *testing.T) { t.Parallel() for _, version := range keptKeywordVersions { t.Run(version, func(t *testing.T) { @@ -445,7 +455,7 @@ func TestKeptEntryKeyword_AnEntryDisagreeingWithAnotherKeepsItsKeywordsReasonWhe } } -func TestKeptEntryKeyword_TwoWritersOfOneKeywordAndValueKeepOneEntryAtThePosition(t *testing.T) { +func TestAllOfEntryKeptKeyword_TwoConjunctsOfOneKeywordAndValueKeepOneEntryAtThePosition(t *testing.T) { t.Parallel() for _, version := range keptKeywordVersions { t.Run(version, func(t *testing.T) { @@ -472,11 +482,11 @@ func TestKeptEntryKeyword_TwoWritersOfOneKeywordAndValueKeepOneEntryAtThePositio } } -// TestKeptEntryKeyword_AKeywordWrittenAlikeBesideTheAllOfIsKeptAsThere holds a +// TestAllOfEntryKeptKeyword_AKeywordWrittenAlikeBesideTheAllOfIsKeptAsThere holds a // keyword an entry writes as the keywords beside its allOf write it to what // those keep: one entry, at the keyword beside the allOf, with that keyword's // report alone, in both orders of the components. -func TestKeptEntryKeyword_AKeywordWrittenAlikeBesideTheAllOfIsKeptAsThere(t *testing.T) { +func TestAllOfEntryKeptKeyword_AKeywordWrittenAlikeBesideTheAllOfIsKeptAsThere(t *testing.T) { t.Parallel() cases := []struct { name, keyword, key string @@ -518,7 +528,12 @@ func keptEntryIssueSchemas(schemas ...string) []string { }, schemas) } -func TestKeptEntryKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndReason(t *testing.T) { +// TestAllOfEntryKeptKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndReason +// holds each spelling of a keyword beside a use of a string to one reading: an +// unknown keyword is kept under one key and reason, reported once, and the +// content vocabulary restricts the reference with the Encoding it reads as, +// keeping nothing (docs/compilers/openapi.md#content-vocabulary). +func TestAllOfEntryKeptKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndReason(t *testing.T) { t.Parallel() const text = "{$ref: '#/components/schemas/Text'}" schemas := keptEntryIssueSchemas( @@ -529,7 +544,6 @@ func TestKeptEntryKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndR "EntryUnknown: {allOf: ["+text+", {unknownKeyword: 1}]}", "EntryMixed: {allOf: ["+text+", {unknownKeyword: 1, minLength: 2, description: d}]}", ) - media := map[string]ir.UnmodeledReason{"openapi:contentMediaType": ir.ReasonNoIRHome} unknown := map[string]ir.UnmodeledReason{"openapi:unknownKeyword": ir.ReasonOutOfScope} inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, diags := compileAnnotationSpec(t, "spellings", admissionSpec("3.1.0", "", schemas...)) @@ -539,15 +553,18 @@ func TestKeptEntryKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndR require.NotNil(t, scalar.Base, name) assert.Equal(t, componentID("Text"), scalar.Base.Target, name) } + for _, name := range []string{"Beside", "Wrapped", "Entry"} { + scalar, ok := kindNode(t, doc, componentID(name)).(*ir.Scalar) + require.True(t, ok, name) + assert.Equal(t, &ir.Encoding{MediaType: "text/html"}, scalar.Encoding, "%s restricts the reference", name) + assert.Empty(t, keptKeywordsOf(doc, name), name) + keptFindingsUnder(t, diags, name, nil) + } entryAt := func(name string) string { return "/components/schemas/" + name + "/allOf/1" } - requireKeptKeywords(t, "Beside", keptKeywordsOf(doc, "Beside"), media, "/components/schemas/Beside", false) - requireKeptKeywords(t, "Wrapped", keptKeywordsOf(doc, "Wrapped"), media, "/components/schemas/Wrapped", false) - requireKeptKeywords(t, "Entry", keptKeywordsOf(doc, "Entry"), media, entryAt("Entry"), false) requireKeptKeywords(t, "BesideUnknown", keptKeywordsOf(doc, "BesideUnknown"), unknown, "/components/schemas/BesideUnknown", false) requireKeptKeywords(t, "EntryUnknown", keptKeywordsOf(doc, "EntryUnknown"), unknown, entryAt("EntryUnknown"), false) requireKeptKeywords(t, "EntryMixed", keptKeywordsOf(doc, "EntryMixed"), unknown, entryAt("EntryMixed"), false) - keptFindingsUnder(t, diags, "Entry", []keptFinding{keptDegraded("/allOf/1/contentMediaType", "contentMediaType")}) keptFindingsUnder(t, diags, "EntryUnknown", []keptFinding{ keptInfo(diag.UnknownSchemaKeyword, "/allOf/1/unknownKeyword", "unknownKeyword"), }) @@ -563,7 +580,7 @@ func TestKeptEntryKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndR }) } -func TestKeptEntryKeyword_ACommentAnchorOrDefsOnAnEntryReachesNoNode(t *testing.T) { +func TestAllOfEntryKeptKeyword_ACommentAnchorOrDefsOnAnEntryReachesNoNode(t *testing.T) { t.Parallel() const obj = "{$ref: '#/components/schemas/Obj'}" schemas := keptEntryIssueSchemas( @@ -586,7 +603,7 @@ func TestKeptEntryKeyword_ACommentAnchorOrDefsOnAnEntryReachesNoNode(t *testing. assert.NotContains(t, string(raw), "kept-comment-text", "a $comment no emitter may see reaches no node") } -func TestKeptEntryKeyword_ANullableOnAnEntryNoPolicyAppliesIsKeptOutOfScopeUnderBothPolicies(t *testing.T) { +func TestAllOfEntryKeptKeyword_ANullableOnAnEntryNoPolicyAppliesIsKeptOutOfScopeUnderBothPolicies(t *testing.T) { t.Parallel() runKeptNullableCases(t, func(t *testing.T, doc *ir.Document) { t.Helper() @@ -595,7 +612,11 @@ func TestKeptEntryKeyword_ANullableOnAnEntryNoPolicyAppliesIsKeptOutOfScopeUnder }) } -func TestKeptEntryKeyword_TwoEntriesKeepingOneKeywordAlikeKeepOneEntryAtThePosition(t *testing.T) { +// TestAllOfEntryKeptKeyword_TwoEntriesKeepingOneKeywordAlikeKeepOneEntryAtThePosition +// holds two entries writing one keyword alike beside a principal: one value +// is one writing, so it is kept once, at the position's pointer since neither +// entry is the same writer in every order, under one report. +func TestAllOfEntryKeptKeyword_TwoEntriesKeepingOneKeywordAlikeKeepOneEntryAtThePosition(t *testing.T) { t.Parallel() for _, version := range keptKeywordVersions { t.Run(version, func(t *testing.T) { @@ -613,14 +634,14 @@ func TestKeptEntryKeyword_TwoEntriesKeepingOneKeywordAlikeKeepOneEntryAtThePosit require.Len(t, got["openapi:minimum"], 1, name) assert.Equal(t, "/components/schemas/"+name, got["openapi:minimum"][0].pointer, "%s: two entries keeping it alike leave one entry at the position", name) - assert.Equal(t, 2, degradedInfosAt(diags, name), "%s: each entry reports what it writes", name) + assert.Equal(t, 1, degradedInfosAt(diags, name), "%s: one value is one report", name) } }) }) } } -func TestKeptEntryKeyword_AValueSetPrincipalsEntryKeepsWhatTheBesideSpellingKeeps(t *testing.T) { +func TestAllOfEntryKeptKeyword_AValueSetPrincipalsEntryKeepsWhatTheBesideSpellingKeeps(t *testing.T) { t.Parallel() for _, version := range keptKeywordVersions { t.Run(version, func(t *testing.T) { @@ -633,12 +654,13 @@ func TestKeptEntryKeyword_AValueSetPrincipalsEntryKeepsWhatTheBesideSpellingKeep inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, diags := compileAnnotationSpec(t, "valueset", admissionSpec(version, "", schemas...)) want := map[string]ir.UnmodeledReason{ - "openapi:$ref": ir.ReasonDegradedLowering, "openapi:pattern": ir.ReasonDegradedLowering, + "openapi:$ref": ir.ReasonDegradedLowering, "openapi:x-note": ir.ReasonVendorExtension, "openapi:fancy": ir.ReasonOutOfScope, } for _, name := range []string{"Entry", "Beside"} { - _, ok := kindNode(t, doc, componentID(name)).(*ir.Enum) + enum, ok := kindNode(t, doc, componentID(name)).(*ir.Enum) require.True(t, ok, "%s is the value set", name) + assert.Equal(t, &ir.Constraints{Pattern: "^a"}, enum.Constraints, "%s holds the pattern of its kind (GitHub #2004)", name) got := keptKeywordsOf(doc, name) assert.Equal(t, want, keptKeywordReasons(got), name) for key, entries := range got { @@ -646,11 +668,11 @@ func TestKeptEntryKeyword_AValueSetPrincipalsEntryKeepsWhatTheBesideSpellingKeep } } keptFindingsUnder(t, diags, "Entry", []keptFinding{ - keptDegraded("", "pattern"), keptDegraded("/allOf/0", "$ref"), + keptDegraded("/allOf/0", "$ref"), keptInfo(diag.UnknownSchemaKeyword, "/allOf/1/fancy", "fancy"), }) keptFindingsUnder(t, diags, "Beside", []keptFinding{ - keptDegraded("", "pattern"), keptDegraded("/allOf/0", "$ref"), + keptDegraded("/allOf/0", "$ref"), keptInfo(diag.UnknownSchemaKeyword, "/fancy", "fancy"), }) }) diff --git a/compilers/openapi/e2e/allof_flatten_depth_test.go b/compilers/openapi/e2e/allof_flatten_depth_test.go index c9d9381ad..213cf336f 100644 --- a/compilers/openapi/e2e/allof_flatten_depth_test.go +++ b/compilers/openapi/e2e/allof_flatten_depth_test.go @@ -15,12 +15,13 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestAllOf_ACollisionPastTheFlatteningDepthIsRefused pins the one way two folds -// reach one naming declaration with different sets: a wrapper reads a declaration -// nested just past the depth a model enclosing it flattens to. The key cannot -// tell them apart, so the registry refuses it rather than let one replace the -// other, and one level shallower both read it and share the node. -func TestAllOf_ACollisionPastTheFlatteningDepthIsRefused(t *testing.T) { +// TestAllOf_PastTheFlatteningDepthOnlyTheWrapperFolds pins a wrapper reading a +// declaration nested just past the depth the position enclosing it flattens +// to. Past that depth the position's kinds are cut, so it is the top type +// keeping its allOf whole and folds nothing: the wrapper is the one fold of +// the declaration, and nothing is refused, as one level shallower, where both +// read it and share the node. +func TestAllOf_PastTheFlatteningDepthOnlyTheWrapperFolds(t *testing.T) { t.Parallel() spec := func(depth int) string { entry := "{type: object, properties: {data: {$ref: '#/components/schemas/C'}}}" @@ -54,9 +55,13 @@ func TestAllOf_ACollisionPastTheFlatteningDepthIsRefused(t *testing.T) { want int }{ {"within the depth of both", statement.MaxFlattenDepth - 1, 0}, - {"past the model's depth, within the wrapper's", statement.MaxFlattenDepth, 1}, + {"past the position's depth, within the wrapper's", statement.MaxFlattenDepth, 0}, } { - _, diags := parseFull(t, spec(tc.depth)) + doc, diags := parseFull(t, spec(tc.depth)) assert.Equal(t, tc.want, refused(diags), tc.name) + if tc.depth == statement.MaxFlattenDepth { + outer := requireComponentScalar(t, doc, "Outer", ir.PrimitiveTypeID(ir.PrimitiveAny)) + assert.Contains(t, outer.Unmodeled, "openapi:allOf", "the position keeps its allOf whole") + } } } diff --git a/compilers/openapi/e2e/allof_fold_order_test.go b/compilers/openapi/e2e/allof_fold_order_test.go index 7853d9c1b..75599784e 100644 --- a/compilers/openapi/e2e/allof_fold_order_test.go +++ b/compilers/openapi/e2e/allof_fold_order_test.go @@ -71,15 +71,15 @@ func TestAllOfFold_AnEncodedFormatIsJudgedAsByteIsBesideBinary(t *testing.T) { for _, tc := range []struct { a, b string code string // "" where the fold narrows to one type, which wins - winner string // the type the field takes where code is "" + chosen string // the type the field takes where code is "" }{ - {a: "{type: string, format: binary}", b: "{type: string, format: byte}", winner: bytesB64}, - {a: "{type: string, format: date-time}", b: "{type: string, format: http-date}", winner: httpDate}, - {a: "{type: string}", b: "{type: string, format: http-date}", winner: httpDate}, - {a: "{type: string, format: date-time}", b: "{type: string, format: unixtime}", winner: secondsText}, - {a: "{type: string, format: binary}", b: "{type: string, format: base64url}", winner: bytesB64URL}, - {a: "{type: integer}", b: "{type: integer, format: unixtime}", winner: seconds}, - {a: "{type: number}", b: "{type: integer, format: unixtime}", winner: seconds}, + {a: "{type: string, format: binary}", b: "{type: string, format: byte}", chosen: bytesB64}, + {a: "{type: string, format: date-time}", b: "{type: string, format: http-date}", chosen: httpDate}, + {a: "{type: string}", b: "{type: string, format: http-date}", chosen: httpDate}, + {a: "{type: string, format: date-time}", b: "{type: string, format: unixtime}", chosen: secondsText}, + {a: "{type: string, format: binary}", b: "{type: string, format: base64url}", chosen: bytesB64URL}, + {a: "{type: integer}", b: "{type: integer, format: unixtime}", chosen: seconds}, + {a: "{type: number}", b: "{type: integer, format: unixtime}", chosen: seconds}, {a: "{type: integer, format: int64}", b: "{type: integer, format: unixtime}", code: diag.DegradedConstruct}, {a: "{type: string, format: byte}", b: "{type: string, format: base64url}", code: diag.DegradedConstruct}, {a: "{type: string, format: http-date}", b: "{type: string, format: unixtime}", code: diag.DegradedConstruct}, @@ -96,7 +96,7 @@ func TestAllOfFold_AnEncodedFormatIsJudgedAsByteIsBesideBinary(t *testing.T) { field, codes := foldedField(t, order[0], order[1]) if tc.code == "" { assert.Empty(t, codes, "%v: the narrower type wins with no report", order) - assert.Equal(t, tc.winner, field, "%v: the field takes the narrower type", order) + assert.Equal(t, tc.chosen, field, "%v: the field takes the narrower type", order) continue } assert.Equal(t, []string{tc.code}, codes, "%v: the first declaration is reported", order) diff --git a/compilers/openapi/e2e/amplification_test.go b/compilers/openapi/e2e/amplification_test.go index c93760378..e42cc42af 100644 --- a/compilers/openapi/e2e/amplification_test.go +++ b/compilers/openapi/e2e/amplification_test.go @@ -48,14 +48,15 @@ func TestCompile_AliasBombDoesNotExhaustMemory(t *testing.T) { } } -// TestCompile_SharedCompositionAncestorsDoNotAmplify pins the visited set in the -// discriminator ancestor walk (compilers/openapi/internal/schema/discriminator.go) on -// an acyclic shape: a chain of diamonds, each allOf naming one parent twice. +// TestCompile_SharedCompositionAncestorsDoNotAmplify pins the visited set in +// the discriminator ancestor walk +// (compilers/openapi/internal/schema/discriminator.go) on an acyclic shape: a +// chain of diamonds, each allOf naming one parent twice. // TestAllOf_DiscriminatorValueCyclicComposition covers the cyclic half, but a -// walk that never returns fails there as a silent package-wide timeout; this -// fails in seconds and names the cause. Branching, not a cycle, is what +// walk that never returns fails there as an unreported package-wide timeout; +// this fails in seconds and names the cause. Branching, not a cycle, is what // multiplies the frontier here. It asserts a bound because the defect is work: -// one visit per level with the dedup, 2^level without it. Electing each level's +// one visit per level with the dedup, 2^level without it. Choosing each level's // Base walks the same ancestors, so it is held to the bound too. func TestCompile_SharedCompositionAncestorsDoNotAmplify(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/e2e/anchors_test.go b/compilers/openapi/e2e/anchors_test.go index f4466aaa0..7ed43d5bb 100644 --- a/compilers/openapi/e2e/anchors_test.go +++ b/compilers/openapi/e2e/anchors_test.go @@ -254,8 +254,8 @@ func compileSource(t *testing.T, path, src string) *ir.Document { return out } -// TestCompile_ARecursiveAnchorInAnExternalDocumentIsRefused pins GitHub #536. -// A recursive anchor in an external document, on a folded entry or in a +// TestCompile_ARecursiveAnchorInAnExternalDocumentIsRefused pins GitHub #536. A +// recursive anchor in an external document, on a flattened entry or in a // self-referencing schema, would build its model without end. Both are refused // as the failure of the reference that named the document. That the compile // returns at all, not only the diagnostic, is what the test proves. @@ -263,7 +263,7 @@ func TestCompile_ARecursiveAnchorInAnExternalDocumentIsRefused(t *testing.T) { t.Parallel() cases := []struct{ name, ext, root string }{ { - name: "a folded entry", + name: "a flattened entry", ext: "openapi: 3.1.0\ninfo: {title: O, version: \"1\"}\npaths:\n /x:\n" + " get: &g\n operationId: getX\n responses: {\"200\": {description: ok}}\n" + " callbacks:\n onEvent:\n \"{$request.body#/url}\":\n get: *g\n", @@ -372,12 +372,12 @@ func TestCompile_AnExternalDocumentIsParsedAsItWasJudged(t *testing.T) { assert.True(t, lowered, "what was judged is what /b mounts") } -// TestCompile_AnAliasStillStandsForAReleasedAnchorInAnExternalDocument is the -// external analogue of TestCompile_AnAliasStillStandsForAReleasedAnchor: a twin +// TestCompile_AnAliasStillReadsAsAReleasedAnchorInAnExternalDocument is the +// external analogue of TestCompile_AnAliasStillReadsAsAReleasedAnchor: a twin // comparison has no alias to resolve, so this pins the half it cannot reach. // Two operations in the external document share one anchored 404 through *nf, // and the root mounts the path holding both by reference. -func TestCompile_AnAliasStillStandsForAReleasedAnchorInAnExternalDocument(t *testing.T) { +func TestCompile_AnAliasStillReadsAsAReleasedAnchorInAnExternalDocument(t *testing.T) { t.Parallel() ext := "openapi: 3.1.0\ninfo: {title: O, version: \"1\"}\npaths:\n /x:\n" + " get:\n operationId: getX\n responses:\n \"200\": {description: ok}\n" + @@ -396,12 +396,12 @@ func TestCompile_AnAliasStillStandsForAReleasedAnchorInAnExternalDocument(t *tes } } -// TestCompile_AnAliasStillStandsForAReleasedAnchor pins the half the twin +// TestCompile_AnAliasStillReadsAsAReleasedAnchor pins the half the twin // comparison cannot: a twin has no alias to resolve. The anchor's name is // cleared before the model is built, and an alias reaches its target through -// the pointer the YAML parser resolved it to, so the alias still stands for the +// the pointer the YAML parser resolved it to, so the alias still names the // anchored response — here, both operations carry the one 404 it names. -func TestCompile_AnAliasStillStandsForAReleasedAnchor(t *testing.T) { +func TestCompile_AnAliasStillReadsAsAReleasedAnchor(t *testing.T) { t.Parallel() doc, diags := parseFull(t, anchorFixtureHead+`paths: /a: diff --git a/compilers/openapi/e2e/annotations_carrier_test.go b/compilers/openapi/e2e/annotations_carrier_test.go index 07889bd00..ce473b575 100644 --- a/compilers/openapi/e2e/annotations_carrier_test.go +++ b/compilers/openapi/e2e/annotations_carrier_test.go @@ -5,7 +5,7 @@ // position whose annotations land on an ir.Property or an ir.Parameter rather // than on a type node, and until the matrix grew an axis for it the grid could // not express a cell there at all — so two dropped-annotation defects at a -// parameter lived in a position the matrix was structurally silent about, while +// parameter lived in a position the matrix was structurally blind to, while // looking complete (GitHub #142). package e2e_test @@ -339,10 +339,10 @@ func validationOnlyParameterCase() retentionCase { } // TestAnnotationRetention_CarriersDifferWhereTheirFieldsDo states the reason -// the two carriers are separate rows rather than one, as a claim rather than an -// arrangement: the same declaration reaches a field on one and Unmodeled on the -// other. A single "carrier" kind would have had to pick one of these answers, -// and covering either would have read as covering both. +// the two carriers are separate rows rather than one, as an assertion rather +// than an arrangement: the same declaration reaches a field on one and +// Unmodeled on the other. A single "carrier" kind would have had to pick one of +// these answers, and covering either would have read as covering both. func TestAnnotationRetention_CarriersDifferWhereTheirFieldsDo(t *testing.T) { t.Parallel() const body = `{type: string, xml: {name: AtCarrier}, readOnly: true}` diff --git a/compilers/openapi/e2e/annotations_test.go b/compilers/openapi/e2e/annotations_test.go index 6559c9e85..856410a7d 100644 --- a/compilers/openapi/e2e/annotations_test.go +++ b/compilers/openapi/e2e/annotations_test.go @@ -23,12 +23,11 @@ import ( ) // minGapReasonLen is the shortest a knownGap reason may be, and -// minGapReasonWords the fewest space-separated words it must contain. -// Neither check reads the reason for sense — that is left to review — but -// together they are cheap insurance against a placeholder like "todo", or a -// run of repeated characters long enough to clear minGapReasonLen alone, -// standing in for the required explanation of why the compiler drops an -// annotation. +// minGapReasonWords the fewest space-separated words it must contain. Neither +// check reads the reason for sense — that is left to review — but together they +// are cheap insurance against a placeholder like "todo", or a run of repeated +// characters long enough to clear minGapReasonLen alone, taking the place of +// the required explanation of why the compiler drops an annotation. const ( minGapReasonLen = 20 minGapReasonWords = 4 @@ -484,10 +483,10 @@ components: require.True(t, ok, "S owns a Model node") assert.NotContains(t, marshalToMap(t, model), "default", "a default binds a use of the type, so it gets no field on the type node") - assertResidueKept(t, model.Unmodeled, "openapi:default", `{"f":"x"}`) + assertKeywordsKept(t, model.Unmodeled, "openapi:default", `{"f":"x"}`) }, assertDiags: func(t *testing.T, diags []ir.Diagnostic) { - assertResidueDiag(t, diags, "/components/schemas/S/default") + assertKeptKeywordDiag(t, diags, "/components/schemas/S/default") }, } } @@ -507,13 +506,13 @@ components: require.True(t, ok, "a bare scalar component owns a Scalar node") assert.NotContains(t, marshalToMap(t, sc), "default", "a default binds a use of the type, so it gets no field on the type node") - assertResidueKept(t, sc.Unmodeled, "openapi:default", `7`) + assertKeywordsKept(t, sc.Unmodeled, "openapi:default", `7`) _, leaked := primitiveNode(t, doc, ir.TypeID("type/primitive/integer")).Common().Unmodeled["openapi:default"] assert.False(t, leaked, "a default on the declaration must not leak onto the shared primitive") }, assertDiags: func(t *testing.T, diags []ir.Diagnostic) { - assertResidueDiag(t, diags, "/components/schemas/S/default") + assertKeptKeywordDiag(t, diags, "/components/schemas/S/default") }, } } @@ -575,10 +574,10 @@ components: require.True(t, ok, "S owns a Model node") assert.NotContains(t, marshalToMap(t, model), "visibility", "readOnly binds a use of the type, so it gets no field on the type node") - assertResidueKept(t, model.Unmodeled, "openapi:readOnly", `true`) + assertKeywordsKept(t, model.Unmodeled, "openapi:readOnly", `true`) }, assertDiags: func(t *testing.T, diags []ir.Diagnostic) { - assertResidueDiag(t, diags, "/components/schemas/S/readOnly") + assertKeptKeywordDiag(t, diags, "/components/schemas/S/readOnly") }, } } @@ -598,13 +597,13 @@ components: require.True(t, ok, "a bare scalar component owns a Scalar node") assert.NotContains(t, marshalToMap(t, sc), "visibility", "readOnly binds a use of the type, so it gets no field on the type node") - assertResidueKept(t, sc.Unmodeled, "openapi:readOnly", `true`) + assertKeywordsKept(t, sc.Unmodeled, "openapi:readOnly", `true`) _, leaked := primitiveNode(t, doc, ir.TypeID("type/primitive/string")).Common().Unmodeled["openapi:readOnly"] assert.False(t, leaked, "a readOnly on the declaration must not leak onto the shared primitive") }, assertDiags: func(t *testing.T, diags []ir.Diagnostic) { - assertResidueDiag(t, diags, "/components/schemas/S/readOnly") + assertKeptKeywordDiag(t, diags, "/components/schemas/S/readOnly") }, } } @@ -1130,7 +1129,7 @@ func TestAnnotationRetention_OtherDeclarationShapes(t *testing.T) { require.True(t, ok, "component S must own a node") require.Equal(t, shape.kind, td.Kind(), "this shape must reach its own lower() destination") assertDeclaredAnnotationsKept(t, td) - assertDeclarationResidueKept(t, td, shape) + assertDeclarationKeywordsKept(t, td, shape) }) } } @@ -1160,10 +1159,10 @@ func assertDeclaredAnnotationsKept(t *testing.T, td ir.TypeDef) { assert.NotEqual(t, ir.Value{}, *typeCommon.Examples[0].Value, "the example converted to a typed value") } -// assertResidueDiag requires one info diagnostic reported at the preserved +// assertKeptKeywordDiag requires one info diagnostic reported at the preserved // keyword's own pointer. The code alone would not say which keyword it was // reported for, and openapi/degraded-construct is emitted for several things. -func assertResidueDiag(t *testing.T, diags []ir.Diagnostic, pointerSuffix string) { +func assertKeptKeywordDiag(t *testing.T, diags []ir.Diagnostic, pointerSuffix string) { t.Helper() for _, diagnostic := range diags { if diagnostic.Code == "openapi/degraded-construct" && diagnostic.Severity == ir.SeverityInfo && @@ -1171,14 +1170,14 @@ func assertResidueDiag(t *testing.T, diags []ir.Diagnostic, pointerSuffix string return } } - assert.Fail(t, "missing residue diagnostic", + assert.Fail(t, "missing kept keyword diagnostic", "no info degraded-construct at a pointer ending %q; got %+v", pointerSuffix, diags) } -// assertResidueKept checks that a keyword binding a use of the type — which +// assertKeywordsKept checks that a keyword binding a use of the type — which // therefore gets no field on the type node — is still on the declaring node // verbatim, under the reason that says the IR models it nowhere else. -func assertResidueKept(t *testing.T, unmodeled ir.Unmodeled, key, wantJSON string) { +func assertKeywordsKept(t *testing.T, unmodeled ir.Unmodeled, key, wantJSON string) { t.Helper() entry, ok := unmodeled[key] require.True(t, ok, "%s must be kept verbatim under Unmodeled", key) @@ -1186,10 +1185,10 @@ func assertResidueKept(t *testing.T, unmodeled ir.Unmodeled, key, wantJSON strin assert.Equal(t, ir.ReasonNoIRHome, entry.Reason) } -// assertDeclarationResidueKept checks the two annotations that bind a use of +// assertDeclarationKeywordsKept checks the two annotations that bind a use of // the type rather than the type, for a declaration shape the SiteKind axis does // not name individually. Only constraints varies by shape. -func assertDeclarationResidueKept(t *testing.T, td ir.TypeDef, shape declShape) { +func assertDeclarationKeywordsKept(t *testing.T, td ir.TypeDef, shape declShape) { t.Helper() node := marshalToMap(t, td) assert.NotContains(t, node, "default", @@ -1197,8 +1196,8 @@ func assertDeclarationResidueKept(t *testing.T, td ir.TypeDef, shape declShape) assert.NotContains(t, node, "visibility", "readOnly has no field on a type node regardless of declaration shape") typeCommon := td.Common() - assertResidueKept(t, typeCommon.Unmodeled, "openapi:readOnly", `true`) - assertResidueKept(t, typeCommon.Unmodeled, "openapi:default", jsonLiteral(shape.value)) + assertKeywordsKept(t, typeCommon.Unmodeled, "openapi:readOnly", `true`) + assertKeywordsKept(t, typeCommon.Unmodeled, "openapi:default", jsonLiteral(shape.value)) if shape.constraintKept { assert.Contains(t, node, "constraints", @@ -1218,13 +1217,13 @@ func jsonLiteral(value string) string { return `"` + value + `"` } -// TestAnnotationRetention_EveryCellCovered requires every cell in the -// harness's annotation-by-site-kind grid to have a case here, gap or not. A -// cell can also be excused instead of cased: an excuse is a claim about what -// OpenAPI itself can express, not about what this compiler currently does -// with it (retentionCase.knownGap is for the latter) — e.g. a SiteKind this -// format has no syntax for at all. No cell currently needs one, so there is -// no excusedCells list here; add one back if a future cell does. +// TestAnnotationRetention_EveryCellCovered requires every cell in the harness's +// annotation-by-site-kind grid to have a case here, gap or not. A cell can also +// be excused instead of cased: an excuse is an assertion about what OpenAPI +// itself can express, not about what this compiler currently does with it +// (retentionCase.knownGap is for the latter) — e.g. a SiteKind this format has +// no syntax for at all. No cell currently needs one, so there is no +// excusedCells list here; add one back if a future cell does. func TestAnnotationRetention_EveryCellCovered(t *testing.T) { t.Parallel() cases := retentionCases() diff --git a/compilers/openapi/e2e/bound_home_corpus_test.go b/compilers/openapi/e2e/bound_home_corpus_test.go index 693fa3ec5..2b268f0df 100644 --- a/compilers/openapi/e2e/bound_home_corpus_test.go +++ b/compilers/openapi/e2e/bound_home_corpus_test.go @@ -83,10 +83,10 @@ func restatedBounds(doc *ir.Document) (restated map[string][]string, owning int) // TestCorpus_NoCarrierRestatesABoundItsOwnNodeHolds sweeps every committed spec // and holds each property, header and parameter to stating no bound the // anonymous node it names states too, so a consumer joining a carrier's bounds -// with its type's meets each once (docs/ir/annotations.md). A field the +// with its type's intersections each once (docs/ir/annotations.md). A field the // redeclared-property fold composes passes, as the model it names holds none. -// The claim stops at a field folded from a declaration owning its node and one -// owning none that write one bound alike: it keeps the second's on the +// The assertion stops at a field folded from a declaration owning its node and +// one owning none that write one bound alike: it keeps the second's on the // property beside the first's node, and no committed spec writes one. func TestCorpus_NoCarrierRestatesABoundItsOwnNodeHolds(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/e2e/bound_home_test.go b/compilers/openapi/e2e/bound_home_test.go index 25f32122a..fa0dba601 100644 --- a/compilers/openapi/e2e/bound_home_test.go +++ b/compilers/openapi/e2e/bound_home_test.go @@ -207,9 +207,11 @@ var keepRows = []homeRow{ name: "prim", schema: "{type: string, maxLength: 9}", kind: "primitive", carrier: map[string]any{"maxLength": 9.0}, node: map[string]any{}, }, + // A length of a uuid's text is no bound of the uuid, so the carrier keeps it + // verbatim rather than holding it (TestTextBounds_ACarrierOverASharedPrimitiveKeepsItsOwn). { name: "uuid", schema: "{type: string, format: uuid, maxLength: 36}", kind: "primitive", - carrier: map[string]any{"maxLength": 36.0}, node: map[string]any{}, + carrier: map[string]any{}, node: map[string]any{}, }, } @@ -240,8 +242,8 @@ func TestCompile_ACarrierOverAReferenceOrASharedPrimitiveKeepsItsBound(t *testin // TestCompile_ABoundBesideAReferenceToAModelIsHeldOnce holds that a property // count written beside a $ref to a model is held once, by the carrier or by a -// node standing for the use, never by both and never lost: a reader asking for -// the effective bound reads each home once. +// node for the use, never by both and never lost: a reader asking for the +// effective bound reads each home once. func TestCompile_ABoundBesideAReferenceToAModelIsHeldOnce(t *testing.T) { t.Parallel() row := homeRow{name: "beside", schema: "{$ref: '#/components/schemas/Obj', minProperties: 2}", sibling: "minProperties"} @@ -368,9 +370,11 @@ var ownedRows = []homeRow{ name: "entry", schema: "{allOf: [{$ref: '#/components/schemas/Obj'}, {maxProperties: 3}]}", kind: "model", carrier: map[string]any{}, node: map[string]any{"maxProperties": 3.0}, }, + // A length of base64 text is no bound of the bytes, so the node keeps it + // verbatim rather than holding it (TestTextBounds_AKeywordOfTheTextBindsOnlyText). { name: "scalar", schema: "{type: string, format: byte, maxLength: 5}", - kind: "scalar", carrier: map[string]any{}, node: map[string]any{"maxLength": 5.0}, + kind: "scalar", carrier: map[string]any{}, node: map[string]any{}, }, { name: "union", schema: "{oneOf: [{type: string}, {type: integer}], minLength: 1}", diff --git a/compilers/openapi/e2e/cases_groups_test.go b/compilers/openapi/e2e/cases_groups_test.go new file mode 100644 index 000000000..6e87c7009 --- /dev/null +++ b/compilers/openapi/e2e/cases_groups_test.go @@ -0,0 +1,57 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/internal/harness/openapicases" +) + +// TestCases_GroupAnchorsAreTheReachTables holds the schema cases' own group +// list to the rule table's reach: at each version the cases are written at, +// every keyword the Schema Object defines there that moves with a group is +// listed with the anchors the table names for it, those the Schema Object +// defines there, and the list names no other keyword. A split the cases write +// then never parts a keyword from its anchor by the table's own reading. +func TestCases_GroupAnchorsAreTheReachTables(t *testing.T) { + t.Parallel() + schema, ok := specrules.Table().Object(specrules.Schema) + require.True(t, ok) + for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { + minor, ok := specrules.ParseMinor(version) + require.True(t, ok, version) + schemaRules, unread := specrules.Table().SchemaRules(version, "") + require.False(t, unread, version) + defined := map[string]bool{} + for _, field := range schema.Fields { + if field.Defined.Holds(minor) { + defined[field.Name] = true + } + } + want := map[string][]string{} + for name := range defined { + if schemaRules.KeywordScopeOf(name) != specrules.KeywordScopeWithGroup { + continue + } + anchors := slices.DeleteFunc(slices.Clone(schemaRules.GroupAnchorKeywords(name)), func(anchor string) bool { + return !defined[anchor] + }) + if len(anchors) > 0 { + want[name] = slices.Sorted(slices.Values(anchors)) + } + } + got := map[string][]string{} + for name, anchors := range openapicases.GroupAnchorKeywords(version) { + got[name] = slices.Sorted(slices.Values(anchors)) + } + require.NotEmpty(t, want, "%s: the table moves some keyword with a group", version) + assert.Equal(t, want, got, "%s: the cases' group list is the table's", version) + } +} diff --git a/compilers/openapi/e2e/election_reports_test.go b/compilers/openapi/e2e/choice_reports_test.go similarity index 78% rename from compilers/openapi/e2e/election_reports_test.go rename to compilers/openapi/e2e/choice_reports_test.go index 20d4aa232..5fdf52b5f 100644 --- a/compilers/openapi/e2e/election_reports_test.go +++ b/compilers/openapi/e2e/choice_reports_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) @@ -38,7 +39,7 @@ func TestAllOfRefine_ARefBesideANullOnlyTypeIsKeptAsTheInlineSpellingIs(t *testi } // TestAllOfRefine_ASetAsideRefIsReportedTrulyWhereNoKindIsDeclared holds that -// the info a $ref set aside draws claims no declared kind where none is: two +// the info a $ref set aside draws names no declared kind where none is: two // $refs the policy reads as an array and an object, and a $ref admitting every // kind beside a union whose branches name none. func TestAllOfRefine_ASetAsideRefIsReportedTrulyWhereNoKindIsDeclared(t *testing.T) { @@ -60,11 +61,12 @@ func TestAllOfRefine_ASetAsideRefIsReportedTrulyWhereNoKindIsDeclared(t *testing }) } -// TestElection_AnAllOfElectingNoEntryIsReportedAsElectingNone holds that the -// info an entry draws where no entry is elected says so, rather than that the -// allOf lowered to a use of one of its conjuncts: two unions of one keyword, -// and two formats neither of which narrows the other, with nothing beside. -func TestElection_AnAllOfElectingNoEntryIsReportedAsElectingNone(t *testing.T) { +// TestChoice_AnAllOfChoosingNoEntryIsReportedAsChoosingNone holds that the info +// an entry draws where no entry is chosen says so, rather than that the allOf +// lowered to a use of one of its conjuncts: two unions of one keyword, each +// naming at its keyword the branch the other leaves dead, and two formats +// neither of which narrows the other, with nothing beside. +func TestChoice_AnAllOfChoosingNoEntryIsReportedAsChoosingNone(t *testing.T) { t.Parallel() schemas := []string{ "Unions: {allOf: [{oneOf: [{type: string}, {type: integer}]}, {oneOf: [{type: string}, {type: boolean}]}]}", @@ -72,7 +74,10 @@ func TestElection_AnAllOfElectingNoEntryIsReportedAsElectingNone(t *testing.T) { } inBothOrders(t, schemas, func(t *testing.T, schemas []string) { _, diags := compileAnnotationSpec(t, "none", admissionSpec("3.1.0", "", schemas...)) - requireErrorsAndWarnings(t, diags, nil) + requireErrorsAndWarnings(t, diags, []wantFinding{ + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/Unions/allOf/0/oneOf", contains: []string{"oneOf/1: integer"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/Unions/allOf/1/oneOf", contains: []string{"oneOf/1: boolean"}}, + }) for _, name := range []string{"Unions", "Formats"} { for _, entry := range []string{"/allOf/0", "/allOf/1"} { at := "/components/schemas/" + name + entry diff --git a/compilers/openapi/e2e/closure_composed_members_test.go b/compilers/openapi/e2e/closure_composed_members_test.go new file mode 100644 index 000000000..6bacf3bcb --- /dev/null +++ b/compilers/openapi/e2e/closure_composed_members_test.go @@ -0,0 +1,201 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// composedMembersShared are the objects the closure cases compose, each +// member named so a message naming it is told from one that does not. +var composedMembersShared = []string{ + "Usr: {type: object, properties: {usrMember: {type: string}}}", + "Req: {type: object, properties: {reqMember: {type: string}}, required: [reqMember]}", +} + +// composedClosure is a closure written over members its own object does not +// declare, where the keyword sits, and what it does not read. +type composedClosure struct { + name, schema, keyword string + unread []string + check func(t *testing.T, model *ir.Model, at jsontext.Pointer) +} + +// requireClosedModel holds a model to be closed with no catch-all. +func requireClosedModel(t *testing.T, model *ir.Model, at jsontext.Pointer) { + t.Helper() + assert.Equal(t, ir.AdditionalClosed, model.Additional, "closed at %s", at) + assert.Nil(t, model.AdditionalProperties, "no catch-all at %s", at) +} + +// requireBooleanCatchAll holds a model to hold a catch-all of booleans. +func requireBooleanCatchAll(t *testing.T, model *ir.Model, at jsontext.Pointer) { + t.Helper() + require.NotNil(t, model.AdditionalProperties, "a catch-all at %s", at) + require.NotNil(t, model.AdditionalProperties.Value, at) + assert.Equal(t, primitive(ir.PrimitiveBool), model.AdditionalProperties.Value.Target, at) +} + +// TestAdditionalProperties_AClosureOverComposedMembersIsTypedKeptAndSaid holds +// that an additionalProperties closure, or its typed catch-all, over a model +// holding members its own object does not declare (a $ref target's, an +// entry's) stays typed, is also kept verbatim as degraded_lowering, and draws +// one info at the keyword naming the members it did not read: beside an allOf +// and on an entry, at every position, at 3.0 and 3.1, in both orders of the +// components (GitHub #2047). +func TestAdditionalProperties_AClosureOverComposedMembersIsTypedKeptAndSaid(t *testing.T) { + t.Parallel() + usr := "{$ref: '#/components/schemas/Usr'}" + for _, tc := range []composedClosure{ + {"beside a $ref", "{allOf: [" + usr + "], additionalProperties: false}", "/additionalProperties", + []string{"usrMember"}, requireClosedModel}, + {"on an entry", "{allOf: [" + usr + ", {additionalProperties: false}]}", "/allOf/1/additionalProperties", + []string{"usrMember"}, requireClosedModel}, + {"a catch-all beside a $ref", "{allOf: [" + usr + "], additionalProperties: {type: boolean}}", "/additionalProperties", + []string{"usrMember"}, requireBooleanCatchAll}, + {"beside an inline entry", "{allOf: [{properties: {inlineMember: {type: string}}}], additionalProperties: false}", + "/additionalProperties", []string{"inlineMember"}, requireClosedModel}, + {"beside its own members and a $ref", "{properties: {ownMember: {type: string}}, allOf: [" + usr + "], additionalProperties: false}", + "/additionalProperties", []string{"usrMember"}, requireClosedModel}, + } { + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version+"/"+tc.name, func(t *testing.T) { + t.Parallel() + inBothMappingOrders(t, conjunctionSpec(version, tc.schema, composedMembersShared...), func(t *testing.T, spec string) { + doc, diags := compileAnnotationSpec(t, "closure", spec) + requireErrorsAndWarnings(t, diags, nil) + for _, at := range conjunctionPositions { + model := closureModelAt(t, doc, at) + tc.check(t, model, at) + kept := unmodeledEntry(t, model.Unmodeled, "openapi:additionalProperties") + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason, "the closure is kept at %s", at) + keyword := string(at) + tc.keyword + messages := messagesBeneath(diags, diag.DegradedConstruct, keyword) + require.Len(t, messages, 1, "one info at %s", keyword) + for _, member := range tc.unread { + assert.Contains(t, messages[0], member, "the info names what the closure did not read") + } + assert.NotContains(t, messages[0], "ownMember", "a member of its own object it reads") + } + }) + }) + } + } +} + +// TestAdditionalProperties_AClosureOverItsOwnMembersOrRefusingNothingSaysNothing +// holds the controls: a closure over the members its own object declares, +// and additionalProperties true or {} beside a $ref, which refuse nothing +// another object declares, keep nothing and draw nothing (GitHub #2047). +func TestAdditionalProperties_AClosureOverItsOwnMembersOrRefusingNothingSaysNothing(t *testing.T) { + t.Parallel() + for name, schema := range map[string]string{ + "its own members": "{type: object, properties: {usrMember: {type: string}}, additionalProperties: false}", + "true": "{allOf: [{$ref: '#/components/schemas/Usr'}], additionalProperties: true}", + "an empty schema": "{allOf: [{$ref: '#/components/schemas/Usr'}], additionalProperties: {}}", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := compileAnnotationSpec(t, "says-nothing", conjunctionSpec("3.1.0", schema, composedMembersShared...)) + requireErrorsAndWarnings(t, diags, nil) + for _, at := range conjunctionPositions { + model := closureModelAt(t, doc, at) + assert.NotContains(t, model.Unmodeled, "openapi:additionalProperties", "nothing is kept at %s", at) + assert.Empty(t, messagesBeneath(diags, diag.DegradedConstruct, string(at)+"/additionalProperties"), at) + } + }) + } +} + +// TestAdditionalProperties_AClosureRefusingARequiredMemberIsUnsatisfiable +// holds that a closure refusing a member another conjunct requires admits no +// instance: one unsatisfiable-schema finding at the keyword, in place of the +// info; and that where every branch of a union beside it requires such a +// member, every branch is dead and the position is the closed model the rest +// gives, keeping the union, with the one finding at the schema (GitHub #2047). +func TestAdditionalProperties_AClosureRefusingARequiredMemberIsUnsatisfiable(t *testing.T) { + t.Parallel() + const branches = "oneOf: [{properties: {x: {type: string}}, required: [x]}, {properties: {y: {type: string}}, required: [y]}]" + refd := "oneOf: [{$ref: '#/components/schemas/Req'}, {properties: {y: {type: string}}, required: [y]}]" + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + doc, diags := compileAnnotationSpec(t, "refuses", admissionSpec(version, "", append(composedMembersShared, + "Required: {type: object, allOf: [{$ref: '#/components/schemas/Req'}], additionalProperties: false}", + "Plain: {type: object, additionalProperties: false, "+branches+"}", + "Refd: {type: object, additionalProperties: false, "+refd+"}")...)) + const keyword = "/components/schemas/Required/additionalProperties" + assert.Equal(t, 1, unsatisfiableAt(diags, keyword), "the closure admits no instance") + assert.Empty(t, messagesBeneath(diags, diag.DegradedConstruct, keyword), "no info beside the finding") + for _, name := range []string{"Plain", "Refd"} { + model, ok := kindNode(t, doc, componentID(name)).(*ir.Model) + require.True(t, ok, "%s is the model the rest gives", name) + assert.Equal(t, ir.AdditionalClosed, model.Additional, name) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(model)["openapi:oneOf"], name) + assert.Equal(t, 1, countBeneath(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/"+name), name) + assert.Equal(t, 1, unsatisfiableAt(diags, "/components/schemas/"+name), "%s: at the schema", name) + } + }) + } +} + +// TestAdditionalProperties_AClosedModelComposedBesideARequiredMemberIsReported +// holds the golden spec's three positions: an allOf of a $ref to a model its +// own closure closes, beside an entry requiring a member that model refuses, +// admits no instance, and draws one unsatisfiable-schema finding at the +// position, at a component and at a list's items, at 3.0 and 3.1, in both +// orders of the components. An entry declaring the member without requiring +// it, and a closed model declaring it, draw none (GitHub #2047). +func TestAdditionalProperties_AClosedModelComposedBesideARequiredMemberIsReported(t *testing.T) { + t.Parallel() + closed := []string{ + "Update: {type: object, properties: {pattern: {type: string}}, additionalProperties: false, minProperties: 1}", + "Create: {type: object, properties: {pattern: {type: string}}, additionalProperties: false, required: [pattern]}", + "Interrupt: {type: object, properties: {reboot: {type: object}}, additionalProperties: false, maxProperties: 1}", + "Declares: {type: object, properties: {id: {type: string}}, additionalProperties: false}", + } + compose := func(target, entry string) string { + return "{allOf: [{$ref: '#/components/schemas/" + target + "'}, " + entry + "]}" + } + const requiresID = "{properties: {id: {type: string}}, required: [id], type: object}" + const declaresID = "{properties: {id: {type: string}}, type: object}" + reported := map[string]string{ + "Patches": compose("Update", requiresID), "Puts": compose("Create", requiresID), + "Result": "{type: object, allOf: [{$ref: '#/components/schemas/Interrupt'}, " + + "{properties: {submitted_at: {type: string}}, required: [submitted_at], type: object}]}", + } + saysNothing := map[string]string{"Optional": compose("Create", declaresID), "Declared": compose("Declares", requiresID)} + for _, version := range []string{"3.0.3", "3.1.0"} { + for _, reversed := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%t", version, reversed), func(t *testing.T) { + t.Parallel() + schemas := append([]string{}, closed...) + for name, schema := range reported { + schemas = append(schemas, name+": "+schema, "List"+name+": {type: array, items: "+schema+"}") + } + for name, schema := range saysNothing { + schemas = append(schemas, name+": "+schema) + } + _, diags := compileAnnotationSpec(t, "golden", bothKeywordsDoc(version, "", reversed, schemas...)) + for name := range reported { + for _, at := range []string{"/components/schemas/" + name, "/components/schemas/List" + name + "/items"} { + assert.Equal(t, 1, unsatisfiableAt(diags, at), "one finding at %s", at) + assert.Equal(t, 1, countBeneath(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, at), "and no other at %s", at) + } + } + for name := range saysNothing { + assert.Zero(t, countBeneath(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/"+name), name) + } + }) + } + } +} diff --git a/compilers/openapi/e2e/closure_conjuncts_test.go b/compilers/openapi/e2e/closure_conjuncts_test.go index c01cf53d8..5190f2583 100644 --- a/compilers/openapi/e2e/closure_conjuncts_test.go +++ b/compilers/openapi/e2e/closure_conjuncts_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) @@ -19,8 +20,9 @@ import ( // holds that patternProperties written beside an allOf types the model's // catch-all though an entry declares members: a pattern applies to every // member name it matches and reads no properties keyword (JSON Schema 2020-12 -// §10.3.2.2), so the members an entry declares change nothing it says. Nothing -// is kept and nothing reported, in every order of the entries. +// §10.3.2.2), so the members an entry declares change nothing it says. Where +// no declared member matches the pattern, the catch-all is exact: nothing is +// kept and nothing reported, in every order of the entries (GitHub #2047). func TestEntryClosure_APatternBesideTheAllOfIsTypedWhateverItsEntriesDeclare(t *testing.T) { t.Parallel() for _, order := range closureOrders("{properties: {b: {type: string}}}", closureRef) { @@ -44,11 +46,64 @@ func TestEntryClosure_APatternBesideTheAllOfIsTypedWhateverItsEntriesDeclare(t * } } +// TestEntryClosure_APatternMatchingADeclaredMemberIsKeptAndSaid holds that a +// patternProperties catch-all is inexact only where a member the model +// declares, its own object's or another conjunct's, matches a pattern, which +// the pattern constrains too and the model's catch-all does not: there it is +// typed, also kept verbatim as degraded_lowering, and one info at the keyword +// names the member; where none matches it is typed and says nothing. The flat +// spelling with its own member matching is kept and reported too, which the +// compiler did not do before (GitHub #2047). +func TestEntryClosure_APatternMatchingADeclaredMemberIsKeptAndSaid(t *testing.T) { + t.Parallel() + const pattern = "patternProperties: {'^x-': {type: string}}" + for _, tc := range []struct { + name, schema, keyword string + matches bool + }{ + {"a composed member matching", "{allOf: [" + closureRef + ", {properties: {x-a: {type: string}}}], " + pattern + "}", + "/patternProperties", true}, + {"its own member matching", "{type: object, properties: {x-a: {type: string}}, " + pattern + "}", "/patternProperties", true}, + {"an entry's pattern, a composed member matching", "{allOf: [{properties: {x-a: {type: string}}}, {" + pattern + "}]}", + "/allOf/1/patternProperties", true}, + {"its own member not matching", "{type: object, properties: {b: {type: string}}, " + pattern + "}", "/patternProperties", false}, + {"an entry's pattern, no member matching", "{allOf: [" + closureRef + ", {properties: {b: {type: string}}}, {" + pattern + "}]}", + "/allOf/2/patternProperties", false}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + inBothMappingOrders(t, conjunctionSpec("3.1.0", tc.schema, closureUser), func(t *testing.T, spec string) { + doc, diags := compileAnnotationSpec(t, "pattern", spec) + requireErrorsAndWarnings(t, diags, nil) + for _, at := range conjunctionPositions { + model := closureModelAt(t, doc, at) + requireClosurePatterns(t, model, string(at)) + keyword := string(at) + tc.keyword + if !tc.matches { + assert.Empty(t, keptUnder(doc, at), "nothing is kept at %s", at) + assert.Empty(t, degradedUnder(diags, at), "nothing is reported at %s", at) + continue + } + kept := map[string]ir.UnmodeledReason{} + for key, entry := range model.Unmodeled { + kept[relocatedKey(key)] = entry.Reason + } + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:patternProperties": ir.ReasonDegradedLowering}, kept, at) + messages := messagesBeneath(diags, diag.DegradedConstruct, keyword) + require.Len(t, messages, 1, "one info at %s", keyword) + assert.Contains(t, messages[0], "x-a", "the info names the member the pattern matches") + } + }) + }) + } +} + // TestEntryClosure_TheClosureBesideTheAllOfIsTheModelsBeforeAnEntrys holds -// that where no conjunct declares a member, a closure beside the allOf types -// the model and one an entry writes is kept whole, as before: the model's -// catch-all has one source, the position, whichever index the entry is -// written at. +// that a closure beside the allOf types the model and one an entry writes is +// kept whole under its entry key, as degraded_lowering, with its info: the +// model's catch-all has one source, the position, whichever index the entry +// is written at. The position's catch-all, over the members of the $ref it +// does not declare, is also kept and reported at its keyword (GitHub #2047). func TestEntryClosure_TheClosureBesideTheAllOfIsTheModelsBeforeAnEntrys(t *testing.T) { t.Parallel() for _, order := range closureOrders("{additionalProperties: false}", closureRef) { @@ -62,8 +117,10 @@ func TestEntryClosure_TheClosureBesideTheAllOfIsTheModelsBeforeAnEntrys(t *testi entry := at + jsontext.Pointer(fmt.Sprintf("/allOf/%d", order.at)) model := closureModelAt(t, doc, at) requireClosureValues(t, model, string(at)) - assert.Equal(t, entryKept(fmt.Sprintf("openapi:allOf/%d", order.at)), keptOn(model), "the entry at %s", at) - assert.Equal(t, []jsontext.Pointer{entry}, degradedUnder(diags, at), "one info at %s", at) + assert.Equal(t, entryKept(fmt.Sprintf("openapi:allOf/%d", order.at), "openapi:additionalProperties"), keptOn(model), + "the entry and the position's catch-all at %s", at) + assert.ElementsMatch(t, []jsontext.Pointer{entry, at + "/additionalProperties"}, degradedUnder(diags, at), + "one info each at %s", at) } }) }) @@ -96,16 +153,21 @@ func TestEntryClosure_TwoEntriesWritingAClosureTypeNeither(t *testing.T) { } // TestEntryClosure_AFalseEntryKeepsTheCatchAllAnEntryTypes holds that a false -// entry closing the model keeps the catch-all value the entry closing it typed, -// since a closed model holds none: kept under its own key at the keyword, the -// false kept beside it, in both orders of the entries. +// entry makes the position a bottom, which draws its own warning, and keeps +// the catch-all value the entry beside it typed, since a closed model holds +// none: kept under its own key at the keyword, the false kept beside it, in +// both orders of the entries. func TestEntryClosure_AFalseEntryKeepsTheCatchAllAnEntryTypes(t *testing.T) { t.Parallel() for _, order := range closureOrders("{additionalProperties: {type: string}}", "false") { t.Run(fmt.Sprintf("at-%d", order.at), func(t *testing.T) { t.Parallel() doc, diags := compileAnnotationSpec(t, "false", conjunctionSpec("3.1.0", "{allOf: "+order.list+"}")) - requireErrorsAndWarnings(t, diags, nil) + bottoms := make([]wantFinding, 0, len(conjunctionPositions)) + for _, at := range conjunctionPositions { + bottoms = append(bottoms, wantFinding{code: diag.UnsatisfiableSchema, pointer: string(at), contains: []string{"no value"}}) + } + requireErrorsAndWarnings(t, diags, bottoms) for _, at := range conjunctionPositions { model := closureModelAt(t, doc, at) requireClosureClosed(t, model, string(at)) @@ -121,11 +183,12 @@ func TestEntryClosure_AFalseEntryKeepsTheCatchAllAnEntryTypes(t *testing.T) { // TestEntryClosure_UnevaluatedPropertiesBesideTheClosingEntry holds what an // unevaluatedProperties: false beside the allOf does where an entry closes the -// model. A catch-all the entry writes evaluates every member, so the keyword is -// inert: the model takes the entry's openness and keeps the keyword as +// model. A catch-all the entry writes evaluates every member, so the keyword +// says nothing: the model takes the entry's openness and keeps the keyword as // validation logic. A pattern alone leaves other members to it, so it closes -// the model after composition. Beside a closure kept for an entry's members, it -// is inert beside that closure, and both are kept. +// the model after composition. Beside a closure over members its own object +// does not declare, which types the model and is also kept, it says nothing +// beside that closure, and both are kept (GitHub #2047). func TestEntryClosure_UnevaluatedPropertiesBesideTheClosingEntry(t *testing.T) { t.Parallel() const up = ", unevaluatedProperties: false}" @@ -158,7 +221,9 @@ func TestEntryClosure_UnevaluatedPropertiesBesideTheClosingEntry(t *testing.T) { for _, at := range conjunctionPositions { model := closureModelAt(t, doc, at) requireClosureClosed(t, model, string(at)) - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:unevaluated": ir.ReasonValidationOnly}, keptOn(model), at) + assert.Equal(t, map[string]ir.UnmodeledReason{ + "openapi:additionalProperties": ir.ReasonDegradedLowering, "openapi:unevaluated": ir.ReasonValidationOnly, + }, keptOn(model), at) } doc, diags = compileAnnotationSpec(t, "kept", conjunctionSpec("3.1.0", @@ -166,22 +231,21 @@ func TestEntryClosure_UnevaluatedPropertiesBesideTheClosingEntry(t *testing.T) { requireErrorsAndWarnings(t, diags, nil) for _, at := range conjunctionPositions { model := closureModelAt(t, doc, at) - assert.Equal(t, ir.AdditionalUnspecified, model.Additional, at) - assert.Nil(t, model.AdditionalProperties, at) + requireCatchAllOfIntegers(t, model, string(at)) assert.Equal(t, map[string]ir.UnmodeledReason{ "openapi:additionalProperties": ir.ReasonDegradedLowering, "openapi:unevaluated": ir.ReasonValidationOnly, }, keptOn(model), at) assert.JSONEq(t, `{"additionalProperties":{"type":"integer"},"unevaluatedProperties":false}`, - string(model.Unmodeled["openapi:unevaluated"].Value), "inert beside the closure at %s", at) + string(model.Unmodeled["openapi:unevaluated"].Value), "saying nothing beside the closure at %s", at) } } // TestEntryClosure_ARefEntrysOwnMembersAreDeclaredBesideTheClosure holds that // properties written beside a $ref entry are members another schema object of -// the conjunction declares, which a closure beside the allOf does not read, so -// it is kept; the members the $ref names are the target's, and a closure -// beside them types the model. +// the conjunction declares, which a closure beside the allOf does not read: +// the closure types the model, the closed subtype its author means, and is +// also kept and reported at the keyword (GitHub #2047). func TestEntryClosure_ARefEntrysOwnMembersAreDeclaredBesideTheClosure(t *testing.T) { t.Parallel() const entry = "{$ref: '#/components/schemas/User', properties: {b: {type: string}}}" @@ -190,16 +254,17 @@ func TestEntryClosure_ARefEntrysOwnMembersAreDeclaredBesideTheClosure(t *testing requireErrorsAndWarnings(t, diags, nil) for _, at := range conjunctionPositions { model := closureModelAt(t, doc, at) - assert.Equal(t, ir.AdditionalUnspecified, model.Additional, "open at %s", at) - assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, model.Unmodeled, "openapi:additionalProperties").Reason, at) - assert.Contains(t, degradedUnder(diags, at), at, "reported at the schema writing it at %s", at) + requireClosureClosed(t, model, string(at)) + requireClosureKeptAndSaid(t, model, diags, at+"/additionalProperties", "b") } } // TestEntryClosure_AClosureBesideAUnionReadsTheAllOfAlike holds that the body a // union distributes into reads a closure as the allOf it writes says: an entry -// closing the model closes every variant, and a closure beside entries -// declaring members closes none, kept on each and reported once. +// closing the model and a closure beside entries declaring members each close +// every variant, over members the closure's own object does not declare, so +// each is kept once, on the Union and on no variant, and reported once +// (GitHub #2047, #2054). func TestEntryClosure_AClosureBesideAUnionReadsTheAllOfAlike(t *testing.T) { t.Parallel() const union = "oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]" @@ -208,15 +273,9 @@ func TestEntryClosure_AClosureBesideAUnionReadsTheAllOfAlike(t *testing.T) { "A: {type: object, properties: {a: {type: string}}}", "B: {type: object, properties: {b: {type: string}}}", } - for _, tc := range []struct { - name, schema string - closed bool - kept map[string]ir.UnmodeledReason - infos int - }{ - {"an entry closing", "{allOf: [" + closureRef + ", {additionalProperties: false}], " + union + "}", true, map[string]ir.UnmodeledReason{}, 0}, - {"a closure kept", "{allOf: [{properties: {c: {type: string}}}], additionalProperties: false, " + union + "}", false, - entryKept("openapi:additionalProperties"), 1}, + for _, tc := range []struct{ name, schema string }{ + {"an entry closing", "{allOf: [" + closureRef + ", {additionalProperties: false}], " + union + "}"}, + {"a closure kept", "{allOf: [{properties: {c: {type: string}}}], additionalProperties: false, " + union + "}"}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() @@ -229,10 +288,16 @@ func TestEntryClosure_AClosureBesideAUnionReadsTheAllOfAlike(t *testing.T) { for _, irVariant := range union.Variants { variant, ok := kindNode(t, doc, irVariant.Type.Target).(*ir.Model) require.True(t, ok, "a composed variant at %s", at) - assert.Equal(t, tc.closed, variant.Additional == ir.AdditionalClosed, "closed at %s", at) - assert.Equal(t, tc.kept, keptOn(variant), at) + assert.Equal(t, ir.AdditionalClosed, variant.Additional, "closed at %s", at) + assert.Empty(t, keptOn(variant), "no variant keeps the closure at %s", at) } - assert.Len(t, degradedUnder(diags, at), tc.infos, at) + kept := map[string]ir.UnmodeledReason{} + for key, entry := range union.Unmodeled { + kept[relocatedKey(key)] = entry.Reason + } + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:additionalProperties": ir.ReasonDegradedLowering}, kept, + "the Union keeps the closure once at %s", at) + assert.Len(t, degradedUnder(diags, at), 1, at) } }) } @@ -243,7 +308,7 @@ func TestEntryClosure_AClosureBesideAUnionReadsTheAllOfAlike(t *testing.T) { // entries are written in, diagnostics included, but for the pointers of the // entries: whether an entry closes the model, is kept whole, or leaves the // closure beside the allOf kept is read from what the conjuncts declare, never -// from where they stand. +// from where they sit. func TestEntryClosure_TheEntryOrderLeavesTheDocumentAlone(t *testing.T) { t.Parallel() const union = ", oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]" @@ -272,3 +337,11 @@ func TestEntryClosure_TheEntryOrderLeavesTheDocumentAlone(t *testing.T) { }) } } + +// requireCatchAllOfIntegers holds a model to hold a catch-all of integers. +func requireCatchAllOfIntegers(t *testing.T, model *ir.Model, at string) { + t.Helper() + require.NotNil(t, model.AdditionalProperties, "a catch-all at %s", at) + require.NotNil(t, model.AdditionalProperties.Value, at) + assert.Equal(t, primitive(ir.PrimitiveInteger), model.AdditionalProperties.Value.Target, at) +} diff --git a/compilers/openapi/e2e/closure_union_test.go b/compilers/openapi/e2e/closure_union_test.go index 64a73ddc5..7d5a17380 100644 --- a/compilers/openapi/e2e/closure_union_test.go +++ b/compilers/openapi/e2e/closure_union_test.go @@ -8,8 +8,8 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) @@ -18,39 +18,36 @@ import ( const closureUnion = "oneOf: [{properties: {x: {type: string}}, required: [x]}, " + "{properties: {y: {type: string}}, required: [y]}]" -// TestEntryClosure_AClosureBesideAUnionsOwnMembersIsKept holds that an entry's -// additionalProperties does not close the variants a union distributes into -// where the union's inline branches declare members: the keyword reads its own -// object's properties alone, so it applies to those members too, as it does to -// an entry's, and the same conjunction written out keeps the entry. Each -// variant stays open and keeps the closing entry, beside the allOf's union and -// on an entry's, in both orders of the entries. -func TestEntryClosure_AClosureBesideAUnionsOwnMembersIsKept(t *testing.T) { +// TestEntryClosure_AClosureRefusingEveryBranchsMemberLeavesTheRest holds that +// an entry's additionalProperties refusing the member each inline branch of a +// union beside it requires leaves every branch dead: the union is no choice +// among shapes, so the position is the closed model the rest of the +// conjunction gives, keeping the union as degraded_lowering, with one +// unsatisfiable-schema finding at the schema, beside the allOf's union and on +// an entry's, in both orders of the entries (GitHub #2047). +func TestEntryClosure_AClosureRefusingEveryBranchsMemberLeavesTheRest(t *testing.T) { t.Parallel() - for _, tc := range []struct { - name, schema, key string - }{ - {"beside", "{allOf: [" + closureRef + ", {additionalProperties: false}], " + closureUnion + "}", "openapi:allOf/1"}, - {"beside-reversed", "{allOf: [{additionalProperties: false}, " + closureRef + "], " + closureUnion + "}", "openapi:allOf/0"}, - {"another-entry", "{allOf: [{" + closureUnion + "}, {additionalProperties: false}]}", "openapi:allOf/1"}, - {"another-entry-reversed", "{allOf: [{additionalProperties: false}, {" + closureUnion + "}]}", "openapi:allOf/0"}, - {"the-closing-entry", "{allOf: [{type: object, additionalProperties: false, " + closureUnion + "}, " + closureRef + "]}", "openapi:allOf/0"}, + for _, tc := range []struct{ name, schema string }{ + {"beside", "{allOf: [" + closureRef + ", {additionalProperties: false}], " + closureUnion + "}"}, + {"beside-reversed", "{allOf: [{additionalProperties: false}, " + closureRef + "], " + closureUnion + "}"}, + {"another-entry", "{allOf: [{" + closureUnion + "}, {additionalProperties: false}]}"}, + {"another-entry-reversed", "{allOf: [{additionalProperties: false}, {" + closureUnion + "}]}"}, + {"the-closing-entry", "{allOf: [{type: object, additionalProperties: false, " + closureUnion + "}, " + closureRef + "]}"}, } { for _, version := range []string{"3.0.3", "3.1.0"} { t.Run(fmt.Sprintf("%s/%s", tc.name, version), func(t *testing.T) { t.Parallel() doc, diags := compileAnnotationSpec(t, "union", conjunctionSpec(version, tc.schema, closureUser)) - requireErrorsAndWarnings(t, diags, nil) for _, at := range conjunctionPositions { - union, ok := kindNode(t, doc, usedAt(t, doc, at)).(*ir.Union) - require.True(t, ok, "a union at %s", at) - require.Len(t, union.Variants, 2, at) - for _, irVariant := range union.Variants { - variant, ok := kindNode(t, doc, irVariant.Type.Target).(*ir.Model) - require.True(t, ok, "a composed variant at %s", at) - assert.Equal(t, ir.AdditionalUnspecified, variant.Additional, "open at %s", at) - assert.Equal(t, ir.ReasonDegradedLowering, keptOn(variant)[tc.key], "the closing entry kept at %s", at) + model := closureModelAt(t, doc, at) + assert.Equal(t, ir.AdditionalClosed, model.Additional, "closed at %s", at) + kept := map[string]ir.UnmodeledReason{} + for key, entry := range model.Unmodeled { + kept[relocatedKey(key)] = entry.Reason } + assert.Equal(t, ir.ReasonDegradedLowering, kept["openapi:oneOf"], "the union kept at %s", at) + assert.Equal(t, 1, unsatisfiableAt(diags, string(at)), "one finding at %s", at) + assert.Equal(t, 1, countBeneath(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, string(at)), "and no other at %s", at) } }) } diff --git a/compilers/openapi/e2e/compose_only_objects_helpers_test.go b/compilers/openapi/e2e/compose_only_objects_helpers_test.go index 4410b63bb..22c00a220 100644 --- a/compilers/openapi/e2e/compose_only_objects_helpers_test.go +++ b/compilers/openapi/e2e/compose_only_objects_helpers_test.go @@ -114,6 +114,6 @@ func degradedInfosAt(diags []ir.Diagnostic, name string) int { // where no instance satisfies them. func disjointFinding(name string) wantFinding { return wantFinding{ - code: diag.DegradedConstruct, pointer: "/components/schemas/" + name, contains: []string{disjoint}, + code: diag.UnsatisfiableSchema, pointer: "/components/schemas/" + name, contains: []string{disjoint}, } } diff --git a/compilers/openapi/e2e/compose_only_objects_test.go b/compilers/openapi/e2e/compose_only_objects_test.go index 249a5026e..a2dd93ded 100644 --- a/compilers/openapi/e2e/compose_only_objects_test.go +++ b/compilers/openapi/e2e/compose_only_objects_test.go @@ -82,23 +82,24 @@ func TestAllOfCompose_ObjectsAloneStayAModel(t *testing.T) { } } -// TestAllOfCompose_ASelfReferenceStaysACompositionWithItsCycleFinding holds -// that an allOf whose only conjunct is the schema itself, which no read of its -// kinds ends, is the composition and is reported as one by the pass that -// finds composition cycles. -func TestAllOfCompose_ASelfReferenceStaysACompositionWithItsCycleFinding(t *testing.T) { +// TestAllOfCompose_ASelfReferenceIsAReferenceLoop holds that an allOf whose +// only conjunct is a $ref to the schema itself, writing nothing else, is a hop +// of the reference chain, so the chain is the loop a bare $ref to itself is: +// one cyclic-ref error, and the position the top type keeping what the bare +// loop keeps (docs/compilers/openapi.md#reference-cycles). No Model composes +// it, so no composition cycle is reported. +func TestAllOfCompose_ASelfReferenceIsAReferenceLoop(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { t.Run(version, func(t *testing.T) { t.Parallel() schemas := []string{"C1: {allOf: [{$ref: '#/components/schemas/C1'}]}"} doc, diags := parseVerified(t, admissionSpec(version, "", schemas...)) - requireErrorsAndWarnings(t, diags, []wantFinding{{ - code: "pass/composition-cycle", pointer: "/components/schemas/C1", - }}) - model := requireModelOf(t, doc, "C1") - require.NotNil(t, model.Base) - assert.Equal(t, componentID("C1"), model.Base.Target) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.CyclicRef, pointer: "/components/schemas/C1"}}) + top := requireComponentScalar(t, doc, "C1", ir.PrimitiveTypeID(ir.PrimitiveAny)) + bareDoc, _ := parseVerified(t, admissionSpec(version, "", "C1: {$ref: '#/components/schemas/C1'}")) + bare := requireComponentScalar(t, bareDoc, "C1", ir.PrimitiveTypeID(ir.PrimitiveAny)) + assert.Equal(t, keptOn(bare), keptOn(top), "the loop keeps what a bare one keeps") }) } } @@ -106,9 +107,9 @@ func TestAllOfCompose_ASelfReferenceStaysACompositionWithItsCycleFinding(t *test // TestAllOfRefine_AKeywordOfAnotherKindIsKeptOnWhatTheTargetDeclares holds // three refinements that already say what the step asks of the others: a // model's keyword beside a $ref to a string is kept under its own key, one in -// an entry beside a string $ref under the entry's index, and an inferred -// object claim never beats a declared string. Each is a use of the string with -// one info. +// an entry beside a string $ref under the entry's index, and an inferred object +// claim never outranks a declared string. Each is a use of the string with one +// info. func TestAllOfRefine_AKeywordOfAnotherKindIsKeptOnWhatTheTargetDeclares(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -459,12 +460,15 @@ func TestAllOfCompose_AModelKeywordOnAKindThatIsNoObjectIsKept(t *testing.T) { // whose keywords speak of an object and of an array do not compose a model: // with no type declared, the position is the top type keeping each entry's // keyword; beside a type list naming both, it is the union of an object and an -// array, the keywords kept. Nothing is reported as unsatisfiable. +// array, the array variant reading the entry's `items` as written beside the +// list, since a node reads the `items` group off whichever conjunct writes it, +// and the object variant composing the entry's `properties` as its flat twin +// does. Nothing is reported as unsatisfiable. func TestAllOfCompose_EntriesClaimingTwoKindsAreNotAModel(t *testing.T) { t.Parallel() for _, version := range composeVersions { for _, swapped := range []bool{false, true} { - list, propertiesAt, itemsAt := composeEntries(swapped, "{properties: {a: {type: string}}}", "{items: {type: string}}") + list, propertiesAt, _ := composeEntries(swapped, "{properties: {a: {type: string}}}", "{items: {type: string}}") schemas := []string{"TwoKinds: {allOf: " + list + "}"} if version == "3.1.0" { schemas = append(schemas, "Listed: {type: [object, array], allOf: "+list+"}") @@ -487,13 +491,14 @@ func TestAllOfCompose_EntriesClaimingTwoKindsAreNotAModel(t *testing.T) { union, ok := kindNode(t, doc, componentID("Listed")).(*ir.Union) require.True(t, ok, "the type list's union") require.Len(t, union.Variants, 2) - assert.Equal(t, ir.KindModel, kindNode(t, doc, union.Variants[0].Type.Target).Kind()) - assert.Equal(t, ir.KindList, kindNode(t, doc, union.Variants[1].Type.Target).Kind()) - kept := []string{ - string(entryPointer("Listed", propertiesAt)) + "/properties", string(entryPointer("Listed", itemsAt)) + "/items", - } - slices.Sort(kept) - assert.Equal(t, kept, keptPointersUnder(doc, "Listed"), "each entry's keyword is kept") + model, isModel := kindNode(t, doc, union.Variants[0].Type.Target).(*ir.Model) + require.True(t, isModel, "the object variant is a model") + require.Len(t, model.Properties, 1, "the entry's properties are the object variant's") + assert.Equal(t, ir.PropertyID("property/openapi"+string(entryPointer("Listed", propertiesAt))+"/properties/a"), model.Properties[0].ID) + list, isList := kindNode(t, doc, union.Variants[1].Type.Target).(*ir.List) + require.True(t, isList, "the array variant is a list") + assert.Equal(t, primitive(ir.PrimitiveString), list.ElementType.Target, "the entry's items types the list") + assert.Empty(t, keptPointersUnder(doc, "Listed"), "each entry's keyword is its kind's variant's") }) }) } @@ -738,7 +743,7 @@ func TestAllOfUnion_AUnionSharingNoKindWithTheRestIsKeptNotDistributed(t *testin integer := requireScalarOver(t, doc, "IntExcl", componentID("Int")) assert.Equal(t, degradedKept("openapi:anyOf"), keptOn(integer)) for _, name := range []string{"WrapDisj", "StrExcl", "IntExcl"} { - assert.Equal(t, 1, degradedInfosAt(diags, name), name) + assert.Zero(t, degradedInfosAt(diags, name), "%s: its one warning says what it keeps", name) } }) }) @@ -1012,8 +1017,10 @@ func findingsUnder(diags []ir.Diagnostic, prefix string) []string { // TestAllOfRefine_ATargetInferredNarrowerThanTheDeclaredKindsIsNoPrincipal // holds that a $ref whose target the kind-inference policy reads as an object // alone is no principal beside a type list or a union declaring a string too: -// the position is the union its own keywords declare, as the inline spelling -// is, and the $ref is kept with one info. +// beside the type list the position is the union its own keywords declare, as +// the inline spelling is, and the $ref is kept with one info; beside the +// union of an object and a string, the body distributes by kind, the object +// variant composing the target and the string variant the branch's node. func TestAllOfRefine_ATargetInferredNarrowerThanTheDeclaredKindsIsNoPrincipal(t *testing.T) { t.Parallel() schemas := []string{ @@ -1032,10 +1039,19 @@ func TestAllOfRefine_ATargetInferredNarrowerThanTheDeclaredKindsIsNoPrincipal(t assert.True(t, slices.ContainsFunc(union.Variants, func(variant ir.Variant) bool { return variant.Type.Target == ir.TypeID("type/primitive/string") }), "%s admits the string it declares", name) - assert.Equal(t, degradedKept("openapi:$ref"), keptOn(union), name) - assert.Equal(t, entryPointer(name, 0), union.Unmodeled["openapi:$ref"].Provenance.Pointer, name) - assert.Equal(t, 1, degradedInfosUnder(diags, "/components/schemas/"+name+"/allOf/0"), name) } + listUnion, ok := kindNode(t, doc, componentID("TypeListRef")).(*ir.Union) + require.True(t, ok) + assert.Equal(t, degradedKept("openapi:$ref"), keptOn(listUnion)) + assert.Equal(t, entryPointer("TypeListRef", 0), listUnion.Unmodeled["openapi:$ref"].Provenance.Pointer) + assert.Equal(t, 1, degradedInfosUnder(diags, "/components/schemas/TypeListRef/allOf/0")) + byKind, ok := kindNode(t, doc, componentID("UnionRef")).(*ir.Union) + require.True(t, ok) + assert.Empty(t, keptOn(byKind), "the target is composed, not kept") + object := requireModelNode(t, doc, byKind.Variants[0].Type.Target) + require.NotNil(t, object.Base) + assert.Equal(t, componentID("Unt"), object.Base.Target, "the object variant composes the target") + assert.Zero(t, degradedInfosUnder(diags, "/components/schemas/UnionRef")) }) } diff --git a/compilers/openapi/e2e/compose_type_list_object_test.go b/compilers/openapi/e2e/compose_type_list_object_test.go index bc7ccae9c..81d632d83 100644 --- a/compilers/openapi/e2e/compose_type_list_object_test.go +++ b/compilers/openapi/e2e/compose_type_list_object_test.go @@ -118,19 +118,24 @@ func TestAllOfCompose_OnlyATypeListsObjectVariantIsComposed(t *testing.T) { overPetN := requireModelOf(t, doc, "OverPetN") require.NotNil(t, overPetN.Base) assert.Equal(t, componentID("PetN"), overPetN.Base.Target, "an object and null is an object") - for _, name := range []string{"OverSI", "OverU"} { - model := requireModelOf(t, doc, name) - assert.Empty(t, parentsOf(model), name) - assert.Equal(t, degradedKept("openapi:$ref"), keptOn(model), "%s: the $ref kept as a refinement keeps one", name) - assert.Equal(t, 1, degradedInfosAt(diags, name), name) - } + overU := requireModelOf(t, doc, "OverU") + assert.Empty(t, parentsOf(overU)) + assert.Equal(t, degradedKept("openapi:$ref"), keptOn(overU), "OverU: the $ref kept as a refinement keeps one") + assert.Equal(t, 1, degradedInfosAt(diags, "OverU")) + // An object beside a type list naming none shares no kind with it: the + // closed bottom keeps its own keywords under their plain keys and the + // $ref entry under its own. + overSI := requireModelOf(t, doc, "OverSI") + assert.Empty(t, parentsOf(overSI)) + assert.Empty(t, overSI.Properties, "the bottom has no member") + assert.Equal(t, degradedKept("openapi:$ref", "openapi:properties", "openapi:type"), keptOn(overSI)) }) } // TestAllOfCompose_TheObjectVariantIsTheOneTheUnionHolds holds that a subtype // composes the object variant the type list's union itself holds wherever the -// list writes its object, null among the others included, so a list whose -// null stands before the object names no node the document lacks. +// list writes its object, null among the others included, so a list whose null +// placed before the object names no node the document lacks. func TestAllOfCompose_TheObjectVariantIsTheOneTheUnionHolds(t *testing.T) { t.Parallel() for _, types := range []string{ diff --git a/compilers/openapi/e2e/composed_variant_key_test.go b/compilers/openapi/e2e/composed_variant_key_test.go new file mode 100644 index 000000000..446dbfe69 --- /dev/null +++ b/compilers/openapi/e2e/composed_variant_key_test.go @@ -0,0 +1,171 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "fmt" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// composedKeyShared are the components the composed-key cases compose. +var composedKeyShared = []string{ + "A: {type: object, properties: {x: {type: string}}}", + "B: {type: object, properties: {y: {type: string}}}", + "T: {type: object, properties: {t: {type: string}}}", +} + +// compileComposedKeys compiles schemas beside composedKeyShared at version, +// in reverse where reversed, requiring no error and no warning of the +// registry. +func compileComposedKeys(t *testing.T, version string, reversed bool, schemas ...string) *ir.Document { + t.Helper() + all := append(slices.Clone(composedKeyShared), schemas...) + if reversed { + slices.Reverse(all) + } + doc, diags := compileAnnotationSpec(t, "keys", admissionSpec(version, "", all...)) + for _, diagnostic := range diags { + require.NotEqual(t, ir.SeverityError, diagnostic.Severity, "%s %s: %s", + diagnostic.Code, diagnostic.Provenance.Pointer, diagnostic.Message) + } + return doc +} + +// unionVariantTargets is the target of each variant of the Union stored at id. +func unionVariantTargets(t *testing.T, doc *ir.Document, id ir.TypeID) []ir.TypeID { + t.Helper() + union, ok := kindNode(t, doc, id).(*ir.Union) + require.True(t, ok, "%s is a Union", id) + targets := make([]ir.TypeID, 0, len(union.Variants)) + for _, variant := range union.Variants { + targets = append(targets, variant.Type.Target) + } + return targets +} + +// composedKeys is the composed key of each branch beneath distributing, +// written after it as at, with the branch indices given. +func composedKeys(distributing, at string, indices ...int) []ir.TypeID { + keys := make([]ir.TypeID, 0, len(indices)) + for _, index := range indices { + keys = append(keys, ir.TypeID(fmt.Sprintf("type/composed%s%s/%d", distributing, at, index))) + } + return keys +} + +// TestComposedVariantKey_AnEntryDistributedVariantIsKeyedApart holds that a +// union written on an inline allOf entry and distributed at the position +// holding the allOf keys each composed variant at the position, the entry +// after the "-" marker, while a $ref to the entry, a position of its own +// distributing the same union over the entry alone, keys its variants at the +// branch: the document compiles, at 3.0 and 3.1, in either order of the +// components (GitHub #2101). +func TestComposedVariantKey_AnEntryDistributedVariantIsKeyedApart(t *testing.T) { + t.Parallel() + refs := "oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]" + for _, version := range []string{"3.0.3", "3.1.0"} { + for _, reversed := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%t", version, reversed), func(t *testing.T) { + t.Parallel() + doc := compileComposedKeys(t, version, reversed, + "X: {allOf: [{$ref: '#/components/schemas/T'}, {properties: {p: {type: string}}, "+refs+"}]}", + "R: {$ref: '#/components/schemas/X/allOf/1'}", + "N: {allOf: [{type: object, properties: {p: {type: string}}, allOf: [{"+refs+"}]}, "+ + "{properties: {q: {type: string}}}]}", + "RN: {$ref: '#/components/schemas/N/allOf/0'}") + assert.Equal(t, composedKeys("/components/schemas/X", "/allOf/-/1/oneOf", 0, 1), + unionVariantTargets(t, doc, componentID("X"))) + assert.Equal(t, composedKeys("/components/schemas/X/allOf/1", "/oneOf", 0, 1), + unionVariantTargets(t, doc, "type/anonymous/components/schemas/X/allOf/1")) + assert.Equal(t, composedKeys("/components/schemas/N", "/allOf/-/0/allOf/0/oneOf", 0, 1), + unionVariantTargets(t, doc, componentID("N"))) + assert.Equal(t, composedKeys("/components/schemas/N/allOf/0", "/allOf/-/0/oneOf", 0, 1), + unionVariantTargets(t, doc, "type/anonymous/components/schemas/N/allOf/0")) + }) + } + } +} + +// TestComposedVariantKey_TheVariantIsPlacedAtItsBranch holds that a variant +// keyed at a minted pointer names that pointer as its provenance, as an ID and +// its provenance agree, and takes its name and source position from the +// branch it composes, as the variant a $ref to the entry keys at the branch +// does (GitHub #2101). +func TestComposedVariantKey_TheVariantIsPlacedAtItsBranch(t *testing.T) { + t.Parallel() + doc := compileComposedKeys(t, "3.1.0", false, + "X: {allOf: [{$ref: '#/components/schemas/T'}, {properties: {p: {type: string}}, "+ + "oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}]}", + "R: {$ref: '#/components/schemas/X/allOf/1'}") + for i := range 2 { + minted := kindNode(t, doc, ir.TypeID(fmt.Sprintf("type/composed/components/schemas/X/allOf/-/1/oneOf/%d", i))).Common() + atBranch := kindNode(t, doc, ir.TypeID(fmt.Sprintf("type/composed/components/schemas/X/allOf/1/oneOf/%d", i))).Common() + assert.Equal(t, jsontext.Pointer(fmt.Sprintf("/components/schemas/X/allOf/-/1/oneOf/%d", i)), minted.Provenance.Pointer, + "variant %d names its key's path", i) + assert.Equal(t, atBranch.Provenance.Position, minted.Provenance.Position, "variant %d sits where its branch is written", i) + assert.Equal(t, atBranch.Name, minted.Name, "variant %d is named by its branch", i) + } +} + +// TestComposedVariantKey_EveryEntryAndPositionKeysApart holds the key to each +// entry a union may sit on, first, middle and last, each beside a $ref to it, +// to a union written at the position itself, whose key is the branch's, and to +// a property's position, every key distinct and the document compiling in +// either order (GitHub #2101). +func TestComposedVariantKey_EveryEntryAndPositionKeysApart(t *testing.T) { + t.Parallel() + union := "{properties: {p: {type: string}}, oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}" + note := "{properties: {n: {type: string}}}" + schemas := make([]string, 0, 8) + for entry := range 3 { + entries := []string{note, note, note} + entries[entry] = union + name := fmt.Sprintf("E%d", entry) + schemas = append(schemas, name+": {allOf: ["+strings.Join(entries, ", ")+"]}", + fmt.Sprintf("R%d: {$ref: '#/components/schemas/%s/allOf/%d'}", entry, name, entry)) + } + schemas = append(schemas, + "At: {allOf: [{$ref: '#/components/schemas/T'}], properties: {p: {type: string}}, "+ + "oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}", + "H: {type: object, properties: {h: {allOf: [{$ref: '#/components/schemas/T'}, "+union+"]}}}") + for _, reversed := range []bool{false, true} { + t.Run(fmt.Sprint(reversed), func(t *testing.T) { + t.Parallel() + doc := compileComposedKeys(t, "3.1.0", reversed, schemas...) + for entry := range 3 { + name := fmt.Sprintf("/components/schemas/E%d", entry) + assert.Equal(t, composedKeys(name, fmt.Sprintf("/allOf/-/%d/oneOf", entry), 0, 1), + unionVariantTargets(t, doc, componentID(fmt.Sprintf("E%d", entry))), "entry %d", entry) + assert.Equal(t, composedKeys(fmt.Sprintf("%s/allOf/%d", name, entry), "/oneOf", 0, 1), + unionVariantTargets(t, doc, ir.TypeID(fmt.Sprintf("type/anonymous%s/allOf/%d", name, entry))), + "the $ref to entry %d", entry) + } + assert.Equal(t, composedKeys("/components/schemas/At", "/oneOf", 0, 1), unionVariantTargets(t, doc, componentID("At")), + "a union written at the position keys at its branch") + assert.Equal(t, composedKeys("/components/schemas/H/properties/h", "/allOf/-/1/oneOf", 0, 1), + unionVariantTargets(t, doc, "type/anonymous/components/schemas/H/properties/h")) + }) + } +} + +// TestComposedVariantKey_TheIssuesDocumentCompiles holds the document the +// defect was found on, an array entry writing an allOf of a union and a $ref +// to that entry, to a compile with no error (GitHub #2101). +func TestComposedVariantKey_TheIssuesDocumentCompiles(t *testing.T) { + t.Parallel() + for _, reversed := range []bool{false, true} { + compileComposedKeys(t, "3.1.0", reversed, + "S: {type: string}", + "X: {allOf: [{type: array, allOf: [{oneOf: [{$ref: '#/components/schemas/S'}, {type: integer}]}]}]}", + "R: {$ref: '#/components/schemas/X/allOf/0'}") + } +} diff --git a/compilers/openapi/e2e/conflict_once_test.go b/compilers/openapi/e2e/conflict_once_test.go index 4551f6ebe..68ecf64cf 100644 --- a/compilers/openapi/e2e/conflict_once_test.go +++ b/compilers/openapi/e2e/conflict_once_test.go @@ -63,12 +63,12 @@ func composing(names ...string) string { // TestConflictOnce_IsReportedOncePerPairOfDeclarations pins how often a // conflict between two declarations is reported (GitHub #2059): once, however -// many models compose both, where the declaration that lost is written, -// saying how many models compose them and naming no member, or naming the -// member where one model does. Each distinct conflict stays: two pairs, one -// pair over two members, one member between two pairs, and one pair two models -// fold to opposite outcomes. Each report lists where the declaration it kept -// is written and the member every model composing the pair decided, in order. +// many models compose both, where the declaration passed over is written, +// naming each model composing them, and naming no node beside its place however +// many do. Each distinct conflict stays: two pairs, one pair over two members, +// one member between two pairs, and one pair two models fold to opposite +// outcomes. Each report lists where the declaration it kept is written and the +// member every model composing the pair decided, in order. func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { t.Parallel() const ( @@ -76,12 +76,16 @@ func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { failure = "/components/schemas/Failure/properties/success" ) type report struct { - at, node, says, kept string - decided []string + at, says, kept string + decided []string } member := func(model int, field string) string { - return fmt.Sprintf("property/composed/components/schemas/M%d/allOf/properties/%s", model, field) + return fmt.Sprintf("/components/schemas/M%d property/composed/components/schemas/M%d/allOf/properties/%s", model, model, field) } + const ( + commonFailure = ": " + failure + " and " + common + stays = "; chose what the first says; the second stays declared on its model" + ) for name, tc := range map[string]struct { models []string want []report @@ -90,15 +94,16 @@ func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { models: []string{composing("Common", "Failure"), composing("Common", "Failure"), composing("Common", "Failure")}, want: []report{{ at: common + "success", kept: failure, - says: "over the one at " + common + "success, which stays declared on its model; the same holds at each of 3 models composing both", + says: `field "success" of /components/schemas/M0, /components/schemas/M1 and /components/schemas/M2` + commonFailure + + "success disagree: incompatible types an enum and an enum" + stays, decided: []string{member(0, "success"), member(1, "success"), member(2, "success")}, }}, }, "one model": { models: []string{composing("Common", "Failure")}, want: []report{{ - at: common + "success", node: member(0, "success"), kept: failure, - says: "over the one at " + common + "success, which stays declared on its model", + at: common + "success", kept: failure, + says: `field "success" of /components/schemas/M0` + commonFailure + "success disagree: incompatible types an enum and an enum" + stays, decided: []string{member(0, "success")}, }}, }, @@ -107,12 +112,13 @@ func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { want: []report{ { at: common + "success", kept: failure, - says: "kept what the declaration at " + failure + " says over the one at " + common + "success, which stays declared on its model; the same holds at each of 2 models", + says: `field "success" of /components/schemas/M0 and /components/schemas/M2` + commonFailure + "success disagree", decided: []string{member(0, "success"), member(2, "success")}, }, { at: common + "success", kept: "/components/schemas/Other/properties/success", - says: "kept what the declaration at /components/schemas/Other/properties/success says over the one at " + common + "success, which stays declared on its model; the same holds at each of 2 models", + says: `field "success" of /components/schemas/M1 and /components/schemas/M3: ` + + "/components/schemas/Other/properties/success and " + common + "success disagree", decided: []string{member(1, "success"), member(3, "success")}, }, }, @@ -121,11 +127,11 @@ func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { models: []string{composing("Common", "Mixed"), composing("Common", "Mixed")}, want: []report{ { - at: common + "code", kept: "/components/schemas/Mixed/properties/code", says: "field \"code\" disagree", + at: common + "code", kept: "/components/schemas/Mixed/properties/code", says: `field "code" of /components/schemas/M0 and /components/schemas/M1`, decided: []string{member(0, "code"), member(1, "code")}, }, { - at: common + "success", kept: "/components/schemas/Mixed/properties/success", says: "field \"success\" disagree", + at: common + "success", kept: "/components/schemas/Mixed/properties/success", says: `field "success" of /components/schemas/M0 and /components/schemas/M1`, decided: []string{member(0, "success"), member(1, "success")}, }, }, @@ -134,12 +140,13 @@ func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { models: []string{composing("Common", "Failure"), composing("Failure", "Common")}, want: []report{ { - at: common + "success", node: member(0, "success"), kept: failure, - says: "kept what the declaration at " + failure + " says", decided: []string{member(0, "success")}, + at: common + "success", kept: failure, + says: `field "success" of /components/schemas/M0` + commonFailure + "success disagree", decided: []string{member(0, "success")}, }, { - at: failure, node: member(1, "success"), kept: common + "success", - says: "kept what the declaration at " + common + "success says", decided: []string{member(1, "success")}, + at: failure, kept: common + "success", + says: `field "success" of /components/schemas/M1: ` + common + "success and " + failure + " disagree", + decided: []string{member(1, "success")}, }, }, }, @@ -155,7 +162,7 @@ func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { require.Len(t, got, len(tc.want), "%s: %+v", name, got) for i, report := range tc.want { assert.Equal(t, report.at, string(got[i].Provenance.Pointer), name) - assert.Equal(t, report.node, got[i].Provenance.Node, name) + assert.Empty(t, got[i].Provenance.Node, name) assert.Contains(t, got[i].Message, report.says, name) kept, decided := concerns(t, got[i]) assert.Equal(t, ir.Provenance{Pointer: jsontext.Pointer(report.kept)}, kept, name) @@ -166,15 +173,16 @@ func TestConflictOnce_IsReportedOncePerPairOfDeclarations(t *testing.T) { // concerns reads what a conflict report concerns besides its place: where the // declaration it kept is written, first, and then the members it decided, -// each named on no source. +// each at the place of the model declaring it, read as that pointer and the +// member's ID. func concerns(t *testing.T, diagnostic ir.Diagnostic) (kept ir.Provenance, decided []string) { t.Helper() require.NotEmpty(t, diagnostic.Related) - require.Equal(t, ir.RelatedKept, diagnostic.Related[0].Role) + require.Equal(t, ir.RelatedChosen, diagnostic.Related[0].Role) for _, related := range diagnostic.Related[1:] { require.Equal(t, ir.RelatedDecided, related.Role) - require.Equal(t, ir.Provenance{Source: ir.NoSource, Node: related.Provenance.Node}, related.Provenance) - decided = append(decided, related.Provenance.Node) + require.Equal(t, ir.Provenance{Pointer: related.Provenance.Pointer, Node: related.Provenance.Node}, related.Provenance) + decided = append(decided, string(related.Provenance.Pointer)+" "+related.Provenance.Node) } return diagnostic.Related[0].Provenance, decided } @@ -197,7 +205,7 @@ func TestConflictOnce_AModelsOwnDeclarationsListTheMember(t *testing.T) { assert.Equal(t, ir.Provenance{Pointer: "/components/schemas/M/allOf/0/properties/p"}, got[0].Provenance) kept, decided := concerns(t, got[0]) assert.Equal(t, ir.Provenance{Pointer: "/components/schemas/M/allOf/1/properties/p"}, kept) - assert.Equal(t, []string{"property/openapi/components/schemas/M/allOf/0/properties/p"}, decided) + assert.Equal(t, []string{"/components/schemas/M property/openapi/components/schemas/M/allOf/0/properties/p"}, decided) } // TestConflictOnce_InlineCompositionsAtOperationsAreOneReport pins the shape @@ -227,7 +235,11 @@ func TestConflictOnce_InlineCompositionsAtOperationsAreOneReport(t *testing.T) { require.Len(t, got, 1, "%+v", diags) assert.Equal(t, "/components/schemas/Common/properties/success", string(got[0].Provenance.Pointer)) assert.Empty(t, got[0].Provenance.Node) - assert.True(t, strings.HasSuffix(got[0].Message, "; the same holds at each of 3 models composing both"), got[0].Message) + schema := func(path string) string { + return "/paths/~1" + path + "/get/responses/400/content/application~1json/schema" + } + assert.True(t, strings.HasPrefix(got[0].Message, `field "success" of `+schema("a")+", "+schema("b")+" and "+schema("c")+": "), + got[0].Message) for name, swapped := range map[string]string{ "the components swapped": spec(paths, []string{components[1], components[0]}), diff --git a/compilers/openapi/e2e/conformance_body_alias_test.go b/compilers/openapi/e2e/conformance_body_alias_test.go index 807cfa4d2..c2159717c 100644 --- a/compilers/openapi/e2e/conformance_body_alias_test.go +++ b/compilers/openapi/e2e/conformance_body_alias_test.go @@ -33,7 +33,7 @@ func assertBodyAlias(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { assert.Equal(t, pets.ID, link.Operation) require.Len(t, link.Params, 1) assert.Equal(t, ir.LinkValue{Kind: ir.LinkResponse, Response: nextCursor}, link.Params[0].Value, - "the cursor reads the member of the model the alias stands for") + "the cursor reads the member of the model the alias names") for key := range pets.Responses[0].Unmodeled { assert.False(t, strings.HasPrefix(key, "openapi:links"), "the link is kept nowhere verbatim: %s", key) } @@ -58,7 +58,7 @@ func assertBodyAlias(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { } // TestBodyAlias_ReadsTheSameInEitherOrder compiles body-alias with every -// mapping's entries reversed, the aliases declared after the model they stand +// mapping's entries reversed, the aliases declared after the model they refer // for and the operation that reads one after the operation that reads another, // and holds it to the same facts. func TestBodyAlias_ReadsTheSameInEitherOrder(t *testing.T) { diff --git a/compilers/openapi/e2e/conformance_composition_test.go b/compilers/openapi/e2e/conformance_composition_test.go index 6b66443d3..d129d4063 100644 --- a/compilers/openapi/e2e/conformance_composition_test.go +++ b/compilers/openapi/e2e/conformance_composition_test.go @@ -66,9 +66,9 @@ func assertAllOfInlineMerge(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { // assertAllOfNestedInline pins the flattening of // docs/compilers/openapi.md#allof-classification: a nested spelling classifies // as the flat one does and keeps each property's own pointer. A wrapper writing -// nothing else is kept nowhere, and one that also writes a closure reading -// every member the conjunction declares closes the model and is kept nowhere -// either. +// nothing else is kept nowhere, and one that also writes a closure closes the +// model, the closure also kept, with one info, as it applies to members its +// own object does not declare (docs/compilers/openapi.md#additional-properties). func assertAllOfNestedInline(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { model, ok := doc.Types[componentID("M")].(*ir.Model) require.True(t, ok) @@ -110,8 +110,13 @@ func assertAllOfNestedInline(t *testing.T, doc *ir.Document, diags []ir.Diagnost require.Len(t, described.Mixins, 2, "the wrapper's refs compose despite its description") assert.Equal(t, componentID("A"), described.Mixins[0].Target) assert.Equal(t, componentID("B"), described.Mixins[1].Target) - assert.Equal(t, ir.AdditionalClosed, described.Additional, "the wrapper's closure, reading no member, closes the model") - assert.Empty(t, described.Unmodeled, "nothing of the wrapper is kept") + assert.Equal(t, ir.AdditionalClosed, described.Additional, "the wrapper's closure closes the model") + // The closure applies to a and b, which A and B bring and the wrapper's + // own object does not declare, so it is also kept, with one info. + closure := unmodeledEntry(t, described.Unmodeled, "openapi:additionalProperties") + assert.Equal(t, ir.ReasonDegradedLowering, closure.Reason) + assert.Equal(t, jsontext.Pointer("/components/schemas/Described/allOf/0/additionalProperties"), closure.Provenance.Pointer) + assert.Len(t, described.Unmodeled, 1, "nothing else of the wrapper is kept") assert.Equal(t, "grouped", described.Docs.Description, "and what it says of the position lands there") for _, id := range []ir.TypeID{"type/composed/components/schemas/U/oneOf/0", "type/composed/components/schemas/U/oneOf/1"} { @@ -125,6 +130,10 @@ func assertAllOfNestedInline(t *testing.T, doc *ir.Document, diags []ir.Diagnost } for _, diagnostic := range diags { + if diagnostic.Provenance.Pointer == "/components/schemas/Described/allOf/0/additionalProperties" { + assert.Equal(t, ir.SeverityInfo, diagnostic.Severity, "the closure's reach is said once") + continue + } assert.NotEqual(t, diag.DegradedConstruct, diagnostic.Code, "flattening is exact: %+v", diagnostic) } } @@ -280,42 +289,46 @@ func assertInlineBranchHint(t *testing.T, doc *ir.Document) { "the outside reference resolves to that same node rather than hoisting a second") } -// assertAllOfDisjointConjuncts pins docs/compilers/openapi.md#allof-disjoint-conjuncts: -// an allOf whose conjuncts share no value draws one warning at the schema -// however the contradiction is spelled, a `type` beside the allOf against a -// $ref, two $refs, or an inline entry against a $ref. The inline entry keeps -// its residue as an info, so one contradiction is one warning; a pair that -// shares a null draws nothing; and no lowering changes, since the report is all -// the case adds. +// assertAllOfDisjointConjuncts pins +// docs/compilers/openapi.md#allof-disjoint-conjuncts: an allOf whose conjuncts +// share no value draws one warning at the schema however the contradiction is +// spelled, a `type` beside the allOf against a $ref, two $refs, or an inline +// entry against a $ref. The inline entry keeps its kept keywords as an info, so +// one contradiction is one warning; a pair that shares null alone is the null +// type, drawing no such warning; and no lowering changes, since the report is +// all the case adds. func assertAllOfDisjointConjuncts(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { for _, name := range []string{"OwnType", "TwoRefs", "Inline"} { assert.Equal(t, []ir.Severity{ir.SeverityWarning}, - diagsAt(diags, diag.DegradedConstruct, "/components/schemas/"+name), + diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name), "%s: conjuncts sharing no value are reported once, at the schema", name) } - assert.Equal(t, []ir.Severity{ir.SeverityInfo}, - diagsAt(diags, diag.DegradedConstruct, "/components/schemas/Inline/allOf/1"), - "the inline entry's residue is an info, since the schema carries the warning") - assert.Empty(t, diagsAt(diags, diag.DegradedConstruct, "/components/schemas/SharedNull"), + assert.Empty(t, diagsAt(diags, diag.DegradedConstruct, "/components/schemas/Inline/allOf/1"), + "the bottom keeps the inline entry whole, and the schema's warning is its one report") + assert.Empty(t, diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/SharedNull"), "a null both conjuncts admit is a value they share") + sharedNull, ok := doc.Types[componentID("SharedNull")].(*ir.Enum) + require.True(t, ok, "null alone together is the null type") + assert.Empty(t, sharedNull.Members) ownType, ok := doc.Types[componentID("OwnType")].(*ir.Model) require.True(t, ok, "the conjuncts share no value, so the allOf composes") assert.Nil(t, ownType.Base, "a model composes no list") assert.Contains(t, ownType.Unmodeled, "openapi:$ref", "the $ref to the list is kept") + // A $ref to an object beside one to a string share no kind: the closed + // bottom composes neither and keeps both. twoRefs, ok := doc.Types[componentID("TwoRefs")].(*ir.Model) require.True(t, ok) - require.NotNil(t, twoRefs.Base, "the one $ref to an object is the Base") - assert.Equal(t, componentID("Obj"), twoRefs.Base.Target) + assert.Nil(t, twoRefs.Base, "the bottom composes nothing") assert.Empty(t, twoRefs.Mixins) - assert.Contains(t, twoRefs.Unmodeled, "openapi:$ref", "the $ref to the string is kept") + assert.ElementsMatch(t, []string{"openapi:$ref/0", "openapi:$ref/1"}, slices.Collect(maps.Keys(twoRefs.Unmodeled))) inline, ok := doc.Types[componentID("Inline")].(*ir.Model) require.True(t, ok) - require.NotNil(t, inline.Base, "the sole $ref is the Base") - assert.Equal(t, componentID("Obj"), inline.Base.Target) - assert.Contains(t, inline.Unmodeled, "openapi:type", "and the inline entry's type is still kept, under its own key") + assert.Nil(t, inline.Base, "the bottom composes nothing") + assert.ElementsMatch(t, []string{"openapi:$ref", "openapi:allOf/1"}, slices.Collect(maps.Keys(inline.Unmodeled)), + "the $ref and the inline entry, each under its own key") } // assertAllOfPositionConstraints pins GitHub #407: a value constraint written @@ -348,16 +361,18 @@ func assertAllOfPositionConstraints(t *testing.T, doc *ir.Document, diags []ir.D // every kind of position, and one that can stays a composition. func assertAllOfRefinement(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { needle, ok := doc.Types[componentID("Needle")].(*ir.Scalar) - require.True(t, ok, "a union conjunct leaves the meet, not a model") + require.True(t, ok, "a union conjunct leaves the intersection, not a model") assert.Equal(t, &ir.TypeRef{Target: "type/primitive/string"}, needle.Base) require.NotNil(t, needle.Constraints) assert.Equal(t, new(int64(1000)), needle.Constraints.MaxLength) - assert.Empty(t, needle.Unmodeled, "the anyOf says nothing the string does not") + // Its number and boolean branches share no value with the string, so the + // anyOf is kept whole, warned of at the keyword. + assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, needle.Unmodeled, "openapi:anyOf").Reason) beside, ok := doc.Types[componentID("NeedleBeside")].(*ir.Scalar) require.True(t, ok, "a union beside the allOf is a conjunct too; got %T", doc.Types[componentID("NeedleBeside")]) assert.Equal(t, needle.Base, beside.Base) assert.Equal(t, needle.Constraints, beside.Constraints) - assert.Empty(t, beside.Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, beside.Unmodeled, "openapi:anyOf").Reason) zone, ok := doc.Types[componentID("Zone")].(*ir.Model) require.True(t, ok) @@ -388,14 +403,15 @@ func assertAllOfRefinement(t *testing.T, doc *ir.Document, diags []ir.Diagnostic mode := properties["mode"] narrowed, ok := doc.Types[mode.Type.Target].(*ir.Enum) require.True(t, ok, "the enum is the value set") - assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Zone/properties/mode"), narrowed.ID, "standing at the property") + assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Zone/properties/mode"), narrowed.ID, "at the property") assert.Len(t, narrowed.Members, 1) assert.Equal(t, "What to do", narrowed.Docs.Description, "and the $ref it narrows still speaks") assert.Empty(t, mode.Unmodeled, "the node the property owns keeps the $ref") unmodeledEntry(t, narrowed.Unmodeled, "openapi:$ref") - assert.Equal(t, componentID("Port"), properties["width"].Type.Target, "a $ref beats a narrower inline type") - unmodeledEntry(t, properties["width"].Unmodeled, "openapi:format") + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInt32), properties["width"].Type.Target, + "a format narrowing the primitive the $ref is rooted at chooses its conjunct") + unmodeledEntry(t, properties["width"].Unmodeled, "openapi:$ref") scan := properties["scan"] assert.Equal(t, "A scan", scan.Docs.Description) @@ -403,11 +419,13 @@ func assertAllOfRefinement(t *testing.T, doc *ir.Document, diags []ir.Diagnostic assertRefinedOperation(t, doc) assertRefinedNodes(t, doc) - assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning), - "only Disjoint is contradicted, and its conjuncts are reported once") - assert.Equal(t, []jsontext.Pointer{"/components/schemas/Disjoint", "/components/schemas/Port80/allOf/1/const", + assert.Equal(t, 3, openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning), + "Disjoint is contradicted, its conjuncts reported once, and each Needle's anyOf has dead branches") + assert.Equal(t, []jsontext.Pointer{"/components/schemas/Disjoint", "/components/schemas/Needle/allOf/0/anyOf", + "/components/schemas/NeedleBeside/anyOf", "/components/schemas/Port80/allOf/1/const", "/components/schemas/Zone/properties/owner/allOf/1/nullable"}, warningPointers(diags), - "and a const, which 3.1 added, and a nullable on an entry writing no type, which 3.0 gives no effect") + "and each anyOf of a Needle at its branches sharing no value with the string, a const, which 3.1 "+ + "added, and a nullable on an entry writing no type, which 3.0 gives no effect") } // assertRefinedOperation covers the positions an operation holds. @@ -581,7 +599,8 @@ func assertDiscriminatorInlineSubtype(t *testing.T, doc *ir.Document, _ []ir.Dia pet, ok := doc.Types[componentID("Pet")].(*ir.Model) require.True(t, ok, "the base is a Model") require.NotNil(t, pet.Discriminator) - assert.Empty(t, pet.Discriminator.Mapping, "every tag in this document is implicit") + assert.Equal(t, map[string]ir.TypeID{"Pet": componentID("Pet"), "Dog": componentID("Dog")}, pet.Discriminator.Mapping, + "every tag in this document is implicit, and a name routes only a component") for _, tc := range []struct { id ir.TypeID @@ -644,27 +663,31 @@ func assertDiscriminatorTransitive(t *testing.T, doc *ir.Document, _ []ir.Diagno } // assertDiscriminatorAliasMapping covers a mapping that spells two keys for one -// subtype (GitHub #410). Model.DiscriminatorValue holds one value and a mapping -// is unordered, so the subtype takes the smallest key in byte order whichever -// was written first — the fixture writes the larger first — while the base's -// mapping keeps both, and the election is reported at the subtype as -// information since nothing is lost. A key naming a component that is only a -// $ref routes to what it names, on the base and on a union, whose value naming -// a schema by its $id resolves too (docs/compilers/openapi.md#discriminator). +// subtype (GitHub #410). DiscriminatorValue holds one value and a mapping is +// unordered, so the subtype takes the smallest key in byte order whichever was +// written first, while the base's mapping keeps both, the choice reported at +// the subtype as information. A key naming a component that is only a $ref +// routes to what it names, on the base and on a union, a value naming a schema +// by its $id resolving too (docs/compilers/openapi.md#discriminator); such a +// component composes what it names, so the base routes it by its name. func assertDiscriminatorAliasMapping(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { pet, ok := doc.Types[componentID("Pet")].(*ir.Model) require.True(t, ok, "the base is a Model") require.NotNil(t, pet.Discriminator) dogID, catID := componentID("Dog"), componentID("Cat") - assert.Equal(t, map[string]ir.TypeID{"alpha": dogID, "zulu": dogID, "cat": catID, "kitten": catID}, - pet.Discriminator.Mapping, "the base keeps every key, a component that is a $ref read through") + assert.Equal(t, map[string]ir.TypeID{"alpha": dogID, "zulu": dogID, "cat": catID, "kitten": catID, + "Pet": componentID("Pet"), "CatAlias": componentID("CatAlias"), "CatNote": componentID("CatNote")}, + pet.Discriminator.Mapping, "the base keeps every key, a component that is a $ref read through, and routes itself "+ + "and each component composing it by its name") + assert.Equal(t, map[string]ir.TypeID{"Dog": dogID, "Cat": catID}, pet.Discriminator.DecodeOnlyRoutes, + "the names of the subtypes the keys route are decode-only") for name, tag := range map[string]string{"Dog": "alpha", "Cat": "cat"} { sub, ok := doc.Types[componentID(name)].(*ir.Model) require.True(t, ok, "%s composes as a Model", name) assert.Equal(t, tag, sub.DiscriminatorValue, "%s: the smallest key in byte order, not the first written", name) assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/"+name), - "the election is reported at the subtype: %+v", diags) + "the choice is reported at the subtype: %+v", diags) } pets, ok := doc.Types[componentID("Pets")].(*ir.Union) @@ -694,11 +717,34 @@ func assertDiscriminatorDefaultMapping(t *testing.T, doc *ir.Document, diags []i "and it is read separately from the mapping") } +// assertDiscriminatorDecodeOnly covers Discriminator.DecodeOnlyRoutes: each +// route the source gives that Mapping leaves out, a name an entry routes under +// another key, or one a subtype's pinned tag refuses, on a union and on a +// hierarchy alike, so no tag has two routes. +func assertDiscriminatorDecodeOnly(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { + require.Len(t, diags, 1, "%+v", diags) + assert.Equal(t, diag.InferredDiscriminator, diags[0].Code, "the one report reads Hound's tag off its pin") + pets, ok := doc.Types[componentID("Pets")].(*ir.Union) + require.True(t, ok, "Pets is a union") + require.NotNil(t, pets.Discriminator) + assert.Equal(t, map[string]ir.TypeID{"dog": componentID("Dog"), "Cat": componentID("Cat")}, pets.Discriminator.Mapping) + assert.Equal(t, map[string]ir.TypeID{"Dog": componentID("Dog")}, pets.Discriminator.DecodeOnlyRoutes, + "the name an entry routes under another key is decode-only") + + pet, ok := doc.Types[componentID("Pet")].(*ir.Model) + require.True(t, ok, "Pet is a model") + require.NotNil(t, pet.Discriminator) + assert.Equal(t, map[string]ir.TypeID{"Pet": componentID("Pet"), "lab": componentID("Labrador"), "hound": componentID("Hound")}, + pet.Discriminator.Mapping, "the base's whole route table") + assert.Equal(t, map[string]ir.TypeID{"Labrador": componentID("Labrador"), "Hound": componentID("Hound")}, + pet.Discriminator.DecodeOnlyRoutes, "an entry's subtype and a subtype pinning another tag are routed by their names for a decoder") +} + // assertDiscriminatedUnionBesideModel pins where a discriminator goes when its -// union is kept verbatim beside a model. Pet's routes are not subtypes of it, -// so pass.Validate would reject the discriminator on the model; it moves whole -// to Unmodeled beside the union. Vehicle, a type array, keeps it on the union -// its types lower to, whose object variant holds none. Shape's and Animal's +// union is kept verbatim beside a model. Pet's branches are no subtypes of it, +// so Pet is their union. Mixed keeps its discriminator, the entry routing to +// Cat, no subtype of it, kept alone verbatim. Vehicle, a type array, lowers to +// the union its one object branch leaves, which the discriminator routes. Shape's and Animal's // routes are true allOf subtypes, Bird composing its union as a mixin rather // than distributing it, so each model keeps it, and the document validates // clean. @@ -717,12 +763,13 @@ func assertDiscriminatedUnionBesideModel(t *testing.T, doc *ir.Document, diags [ mixed, ok := doc.Types[componentID("Mixed")].(*ir.Model) require.True(t, ok, "Kitten composes Mixed, so Mixed stays a model") - assert.Nil(t, mixed.Discriminator, "Mixed routes to a non-subtype, so the model does not carry it") - entry, ok := mixed.Unmodeled["openapi:discriminator"] - require.True(t, ok, "Mixed keeps it verbatim instead") - assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) + require.NotNil(t, mixed.Discriminator, "Mixed keeps the routes to itself and its subtype") + assert.Equal(t, map[string]ir.TypeID{"Kitten": componentID("Kitten"), "Mixed": componentID("Mixed")}, mixed.Discriminator.Mapping) + assert.NotContains(t, mixed.Unmodeled, "openapi:discriminator", "the discriminator is not kept whole") assert.Contains(t, mixed.Unmodeled, "openapi:oneOf", "beside the union it routes through") - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Mixed/discriminator")) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnhomedConstruct, "/components/schemas/Mixed/discriminator/mapping/cat"), + "the entry routing to Cat, no subtype, is kept alone and reported") + assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Mixed/discriminator")) bird, ok := doc.Types[componentID("Bird")].(*ir.Model) require.True(t, ok, "Bird writes allOf to Animal, whose route keeps it a subtype") @@ -737,11 +784,13 @@ func assertDiscriminatedUnionBesideModel(t *testing.T, doc *ir.Document, diags [ assert.Equal(t, componentID("Bird"), animal.Discriminator.Mapping["bird"]) vehicle, ok := doc.Types[componentID("Vehicle")].(*ir.Union) - require.True(t, ok, "a multi-typed body lowers to a union") - assert.Contains(t, vehicle.Unmodeled, "openapi:discriminator", "kept beside the union it was written for") - variant, ok := doc.Types["type/anonymous/components/schemas/Vehicle/type/0"].(*ir.Model) - require.True(t, ok) - assert.Nil(t, variant.Discriminator, "the object variant does not carry it") + require.True(t, ok, "Vehicle lowers to the union of its oneOf") + require.Len(t, vehicle.Variants, 1, "no string is a Car, so the oneOf leaves only an object") + composedCar := ir.TypeID("type/composed/components/schemas/Vehicle/oneOf/0") + assert.Equal(t, composedCar, vehicle.Variants[0].Type.Target) + require.NotNil(t, vehicle.Discriminator, "the discriminator stays with the union it was written for") + assert.Equal(t, composedCar, vehicle.Discriminator.Mapping["car"]) + assert.Empty(t, vehicle.Unmodeled, "it keeps nothing verbatim") shape, ok := doc.Types[componentID("Shape")].(*ir.Model) require.True(t, ok) @@ -793,11 +842,16 @@ func assertDiscriminatedUnionDistributed(t *testing.T, doc *ir.Document, diags [ // the union redeclaring the tag as a string included; none where the names are // them; a discriminator for an undeclared union whose variants each require a // property pinned to a distinct string; and none where a pinned value is no -// string or no variant need carry the property. +// string or no variant need carry the property. A union it leaves to the +// document, its inline variants named by nothing, has each noted as unrouted. func assertDiscriminatorInferred(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { found, err := pass.Validate(t.Context(), doc) require.NoError(t, err) - assert.Empty(t, found) + require.Len(t, found, 2, "%v", found) + for _, finding := range found { + assert.Equal(t, "pass/discriminator-unrouted-variant", finding.Code) + assert.Equal(t, string(componentID("Overlapping")), finding.Provenance.Node) + } format := unionNamed(t, doc, "Format") require.NotNil(t, format.Discriminator) @@ -950,8 +1004,9 @@ func assertNegationNot(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { // the one that writes only `required`: one Model with the union kept under // validation_only, reported as that and not as a degradation. Branches saying // more than a model body distribute it, and more than one that is no model -// degrade, but where each says its type, as a bare `items` says an array under -// the kind-inference policy (docs/compilers/openapi.md#union-beside-structure). +// conjoin with it, a format a Union of the encodings, as a bare `items` says +// an array under the kind-inference policy +// (docs/compilers/openapi.md#union-beside-structure). func assertUnionRestatedBranches(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { for name, keyword := range map[string]string{ "RenderBare": "openapi:oneOf", "Render": "openapi:oneOf", "RenderDocumented": "openapi:anyOf", @@ -963,9 +1018,9 @@ func assertUnionRestatedBranches(t *testing.T, doc *ir.Document, diags []ir.Diag assert.Len(t, model.Properties, 2, "%s", name) assert.Equal(t, ir.ReasonValidationOnly, unmodeledEntry(t, model.Unmodeled, keyword).Reason, "%s", name) } - joint, ok := doc.Types[componentID("RenderJoint")].(*ir.Model) + renderJoint, ok := doc.Types[componentID("RenderJoint")].(*ir.Model) require.True(t, ok, "RenderJoint lowers to its body") - assert.Equal(t, ir.ReasonValidationOnly, unmodeledEntry(t, joint.Unmodeled, "openapi:oneOf").Reason) + assert.Equal(t, ir.ReasonValidationOnly, unmodeledEntry(t, renderJoint.Unmodeled, "openapi:oneOf").Reason) composed, ok := doc.Types[componentID("RenderComposed")].(*ir.Model) require.True(t, ok, "RenderComposed lowers to its body") require.NotNil(t, composed.Base) @@ -980,16 +1035,29 @@ func assertUnionRestatedBranches(t *testing.T, doc *ir.Document, diags []ir.Diag _, isList := doc.Types[variant.Type.Target].(*ir.List) assert.True(t, isList, "each branch is the list its items imply") } - formats, ok := doc.Types[componentID("RenderFormats")] - require.True(t, ok, "RenderFormats lowers") - assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, formats.Common().Unmodeled, "openapi:oneOf").Reason) + formats, ok := doc.Types[componentID("RenderFormats")].(*ir.Union) + require.True(t, ok, "RenderFormats' branches conjoin with the string, a Union of the encodings") + encodings := make([]ir.TypeID, 0, len(formats.Variants)) + for _, variant := range formats.Variants { + encodings = append(encodings, variant.Type.Target) + } + assert.Equal(t, []ir.TypeID{ir.PrimitiveTypeID(ir.PrimitiveDate), ir.PrimitiveTypeID(ir.PrimitiveURL)}, encodings) + assert.Empty(t, formats.Unmodeled, "nothing of the union is left unread") var degraded []string for _, diagnostic := range diags { if diagnostic.Code == diag.DegradedConstruct { degraded = append(degraded, string(diagnostic.Provenance.Pointer)) } } - assert.ElementsMatch(t, []string{"/components/schemas/RenderFormats"}, degraded) + assert.Empty(t, degraded, "a self-reference is composed, not kept, and the formats conjoin with the string") + // The kinds beside a loop of references are read outside every union, so + // RenderSelf composes itself as it does without its oneOf. + self, ok := doc.Types[componentID("RenderSelf")].(*ir.Model) + require.True(t, ok) + require.NotNil(t, self.Base) + assert.Equal(t, componentID("RenderSelf"), self.Base.Target) + assert.NotContains(t, self.Unmodeled, "openapi:$ref") + assert.Equal(t, ir.Inferred("kind-inference"), self.Provenance.Inferred) } // assertUnionRestatedType pins a union beside keywords its branches all say, @@ -1070,7 +1138,19 @@ func assertUnionInlineBranches(t *testing.T, doc *ir.Document, diags []ir.Diagno func assertAllOfUnionBranch(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { found, err := pass.Validate(t.Context(), doc) require.NoError(t, err) - assert.Empty(t, found) + notes := make([]string, 0, len(found)) + for _, finding := range found { + notes = append(notes, finding.Code+" "+finding.Message) + } + // Kennel's resident composes Pet and distributes its union, so each of its + // variants is a subtype of Pet no route names, which validation notes. + const residentVariant = "type/composed/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/" + require.Len(t, notes, 2, "%v", notes) + slices.Sort(notes) + for i, note := range notes { + assert.True(t, strings.HasPrefix(note, "pass/discriminator-unrouted-variant "), note) + assert.Contains(t, note, residentVariant+[]string{"0", "1"}[i], note) + } for name, bases := range map[string][]ir.TypeID{ "Record": {componentID("WithoutData"), componentID("WithData")}, @@ -1093,9 +1173,10 @@ func assertAllOfUnionBranch(t *testing.T, doc *ir.Document, diags []ir.Diagnosti } request, ok := doc.Types[componentID("AppRequest")].(*ir.Union) require.True(t, ok) + assert.Equal(t, ir.ReasonValidationOnly, unmodeledEntry(t, request.Unmodeled, "openapi:anyOf").Reason, + "the union that only narrows is kept once, on the Union, as validation logic") for _, variant := range request.Variants { - assert.Equal(t, ir.ReasonValidationOnly, unmodeledEntry(t, doc.Types[variant.Type.Target].Common().Unmodeled, "openapi:anyOf").Reason, - "the union that only narrows is kept on every variant as validation logic") + assert.NotContains(t, doc.Types[variant.Type.Target].Common().Unmodeled, "openapi:anyOf", "no variant keeps it") } upload := openapitest.FirstOperation(t, doc.Services[0]).Request.Contents[0] @@ -1134,16 +1215,17 @@ func assertAllOfUnionBranch(t *testing.T, doc *ir.Document, diags []ir.Diagnosti } // assertAllOfValueSetBesideEntry holds allof-value-set-beside-entry to -// docs/compilers/openapi.md#competing-keywords: where no value set is elected +// docs/compilers/openapi.md#competing-keywords: where no value set is chosen // before the composition, the allOf an inline entry is written on is passed // over and kept whole, each beside the value set the position lowers as, and a -// $ref written beside them with it. The sets share a member, so the document -// is no refusal of an empty intersection. +// $ref written beside them with it. A type every member of the set is a value +// of restates the union of literals, so it is kept nowhere. The sets share a +// member, so the document is no refusal of an empty intersection. func assertAllOfValueSetBesideEntry(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { entry := `[{"enum":[{"a":1},{"c":3}]}]` for name, want := range map[string]map[string]string{ "Beside": {"openapi:allOf": entry}, - "BesideTyped": {"openapi:allOf": `[{"enum":[{"a":1},{"c":3}],"type":"object"}]`, "openapi:type": `"object"`}, + "BesideTyped": {"openapi:allOf": `[{"enum":[{"a":1},{"c":3}],"type":"object"}]`}, "BesideTwo": {"openapi:allOf": `[{"enum":[{"a":1},{"c":3}]},{"required":["a"]}]`}, "BesideRef": {"openapi:allOf": entry, "openapi:$ref": `"#/components/schemas/Target"`}, } { diff --git a/compilers/openapi/e2e/conformance_docs_test.go b/compilers/openapi/e2e/conformance_docs_test.go index dba7f6625..6c1ff3f9f 100644 --- a/compilers/openapi/e2e/conformance_docs_test.go +++ b/compilers/openapi/e2e/conformance_docs_test.go @@ -259,7 +259,7 @@ func assertAliasHopDocs(t *testing.T, doc *ir.Document) { require.Len(t, sprocket.Responses[0].Payload.Contents[0].Examples, 1) example := sprocket.Responses[0].Payload.Contents[0].Examples[0] assert.Equal(t, "The alias's own summary", example.Summary) - assert.Equal(t, "Declared description", example.Description, "the field the alias omits stands") + assert.Equal(t, "Declared description", example.Description, "the field the alias omits is kept") require.Len(t, sprocket.Errors, 1) assert.Equal(t, "The alias's own response description.", sprocket.Errors[0].Docs.Description) } diff --git a/compilers/openapi/e2e/conformance_kind_inference_test.go b/compilers/openapi/e2e/conformance_kind_inference_test.go index 8e9668c15..3ba8a24a8 100644 --- a/compilers/openapi/e2e/conformance_kind_inference_test.go +++ b/compilers/openapi/e2e/conformance_kind_inference_test.go @@ -5,6 +5,7 @@ package e2e_test import ( "encoding/json/jsontext" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -77,3 +78,34 @@ func assertRefUseBoundKeywords(t *testing.T, doc *ir.Document, _ []ir.Diagnostic assert.Equal(t, filter, component.Base.Target) assert.Contains(t, component.Unmodeled, "openapi:readOnly") } + +// assertApplicatorSayingNothing holds silent-applicator: each applicator +// holding a schema that writes only a comment lowers as its twin holding `{}` +// does, the same kind over the same base, keeping the same keys under the same +// reasons, marked by no policy and reported where its twin is; and one holding +// a note stays a list. +func assertApplicatorSayingNothing(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { + reportedUnder := func(name string) []string { + var out []string + for _, pointer := range degradedInfoPointers(diags) { + rest, ok := strings.CutPrefix(string(pointer), "/components/schemas/"+name) + if ok && (rest == "" || strings.HasPrefix(rest, "/")) { + out = append(out, rest) + } + } + return out + } + for saysNothing, empty := range map[string]string{"Comment": "Empty", "MapComment": "MapEmpty", "EntryComment": "EntryEmpty"} { + got, want := kindNode(t, doc, componentID(saysNothing)), kindNode(t, doc, componentID(empty)) + assert.Equal(t, want.Kind(), got.Kind(), "%s lowers as %s", saysNothing, empty) + if wantScalar, ok := want.(*ir.Scalar); ok { + gotScalar, ok := got.(*ir.Scalar) + require.True(t, ok, saysNothing) + assert.Equal(t, wantScalar.Base, gotScalar.Base, saysNothing) + } + assert.Equal(t, keptOn(want), keptOn(got), saysNothing) + assert.False(t, markedKindInference(got), "%s infers no kind from a comment", saysNothing) + assert.Equal(t, reportedUnder(empty), reportedUnder(saysNothing), "%s is reported where %s is", saysNothing, empty) + } + assert.Equal(t, ir.KindList, kindNode(t, doc, componentID("Described")).Kind(), "a note types the elements") +} diff --git a/compilers/openapi/e2e/conformance_nullability_test.go b/compilers/openapi/e2e/conformance_nullability_test.go index a581a4452..7cb35e16a 100644 --- a/compilers/openapi/e2e/conformance_nullability_test.go +++ b/compilers/openapi/e2e/conformance_nullability_test.go @@ -104,7 +104,7 @@ func assertEnumNullMember(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) require.Len(t, narrowed.Members, 1) assert.Equal(t, "a", narrowed.Members[0].Value.String) assert.Equal(t, []ir.Severity{ir.SeverityWarning}, - diagsAt(diags, "openapi/degraded-construct", "/components/schemas/Narrowed/enum/1"), + diagsAt(diags, "openapi/unsatisfiable-schema", "/components/schemas/Narrowed/enum/1"), "the null its type excludes is reported at it") holder, ok := doc.Types[componentID("Holder")].(*ir.Model) diff --git a/compilers/openapi/e2e/conformance_operations_test.go b/compilers/openapi/e2e/conformance_operations_test.go index f5d44ceb2..115cdf0aa 100644 --- a/compilers/openapi/e2e/conformance_operations_test.go +++ b/compilers/openapi/e2e/conformance_operations_test.go @@ -280,9 +280,9 @@ func assertPaginationInferred(t *testing.T, doc *ir.Document, diags []ir.Diagnos // assertIdempotencyInference pins the idempotency policy on each operation of // its case: a POST's Idempotency-Key header and a PUT's, through a $ref and in // lower case, are their tokens, marked; a GET, safe by its method, a PATCH -// whose key is a query parameter, and a DELETE carrying the header twice in -// two letter cases keep the idempotency the document leaves unknown, the -// DELETE alone reported, as the one whose reading met its trigger and stopped. +// whose key is a query parameter, and a DELETE carrying the header twice in two +// letter cases keep the idempotency the document leaves unknown, the DELETE +// alone reported, as the one whose reading reached its trigger and stopped. func assertIdempotencyInference(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { assert.Equal(t, []jsontext.Pointer{"/paths/~1payments~1{id}/delete"}, openapitest.PointersOf(diags, "openapi/undecided-idempotency")) diff --git a/compilers/openapi/e2e/conformance_params_test.go b/compilers/openapi/e2e/conformance_params_test.go index 897577cd0..e21ba2c50 100644 --- a/compilers/openapi/e2e/conformance_params_test.go +++ b/compilers/openapi/e2e/conformance_params_test.go @@ -37,7 +37,7 @@ func assertParamStyles(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { // keyword belongs to before 3.2 — so a declaration of it, which the // assertion above pins, is not the off-query case the warning reports. assert.Zero(t, openapitest.CountDiagsAt(diags, diag.InapplicableLocationKeyword, ir.SeverityWarning), - "a 3.1 query declaration of allowReserved stays silent") + "a 3.1 query declaration of allowReserved reports nothing") assertAllowEmptyValueLowers(t, operation) @@ -353,8 +353,8 @@ func assertQuerystringForbiddenKeywords(t *testing.T, doc *ir.Document, diags [] // assertParamAllowReservedLocations pins diag.InapplicableLocationKeyword // through the whole compile: OpenAPI 3.1 applies allowReserved to in: query // alone, so a path, header or cookie declaration is reported at the keyword's -// own pointer, a declared false among them, while a query declaration stays -// silent. Every declared value still lowers as declared. +// own pointer, a declared false among them, while a query declaration reports +// nothing. Every declared value still lowers as declared. func assertParamAllowReservedLocations(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { operation, ok := operationByName(doc, "report") require.True(t, ok) @@ -389,8 +389,8 @@ func assertParamAllowReservedLocations(t *testing.T, doc *ir.Document, diags []i // assertParamRefInheritance pins the rule // docs/compilers/openapi.md#ref-use-site at a parameter whose schema is a $ref: -// docs, deprecation and default come from the referent when the use site is -// silent, and from the use site when it is not. Constraints inherit at neither +// docs, deprecation and default come from the referent when the use site says +// nothing, and from the use site when it is not. Constraints inherit at neither // carrier, so the identical property is asserted beside it (GitHub #131). The // bound the use site declares beside the $ref is asserted at both carriers // against the referent's own: use-site precedence would publish 100 as the @@ -412,7 +412,7 @@ func assertParamRefInheritance(t *testing.T, doc *ir.Document, _ []ir.Diagnostic assert.Equal(t, "Cursor for this endpoint only.", override.Docs.Description, "a description beside the $ref wins over the referent's") assert.Equal(t, "Cursor", override.Docs.Summary, - "...and a keyword the use site is silent about still inherits") + "...and a keyword the use site says nothing of still inherits") require.NotNil(t, override.Default) assert.Equal(t, "9", override.Default.String) require.NotNil(t, override.Constraints, "a bound beside the $ref lands on the carrier") @@ -509,11 +509,11 @@ func assertHeaderStyleAndExplodeLower(t *testing.T, headers []ir.Header) { assert.Nil(t, plain.Explode) } -// assertParamContentFields pins GitHub #611: electing a parameter's or header's +// assertParamContentFields pins GitHub #611: choosing a parameter's or header's // `content` spelling reads the whole Media Type Object rather than only its -// schema, so the object's examples reach the carrier and what the carrier has no -// home for is kept verbatim under the content entry's own scope. The schema -// spelling beside them elects no media type and records none of it. +// schema, so the object's examples reach the carrier and what the carrier has +// no home for is kept verbatim under the content entry's own scope. The schema +// spelling beside them chooses no media type and records none of it. func assertParamContentFields(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { operation, ok := operationByName(doc, "search") require.True(t, ok) @@ -531,7 +531,7 @@ func assertParamContentFields(t *testing.T, doc *ir.Document, diags []ir.Diagnos plain, ok := openapitest.ParamBySource(operation, "plain") require.True(t, ok) - assert.Empty(t, plain.Examples, "the schema spelling elects no media type to take examples from") + assert.Empty(t, plain.Examples, "the schema spelling chooses no media type to take examples from") assert.Empty(t, plain.Unmodeled, "nor any content-scoped entry") require.Len(t, operation.Responses, 1) diff --git a/compilers/openapi/e2e/conformance_parts_test.go b/compilers/openapi/e2e/conformance_parts_test.go index 4c7e1abca..a3039a164 100644 --- a/compilers/openapi/e2e/conformance_parts_test.go +++ b/compilers/openapi/e2e/conformance_parts_test.go @@ -48,12 +48,12 @@ const ( jsonType = "application/json" ) -// assertMultipartDefaults31 pins the content type a 3.1 part no Encoding -// Object configures takes by the value it applies to: JSON for an object or a -// map, text for a string, a number or a boolean, octet-stream for raw bytes, a +// assertMultipartDefaults31 pins the content type a 3.1 part no Encoding Object +// configures takes by the value it applies to: JSON for an object or a map, +// text for a string, a number or a boolean, octet-stream for raw bytes, a // contentEncoding string and an untyped value, text for format byte, which 3.1 // gives no effect, and each item's row for an array, none where two values' -// rows differ. A declared content type stands, and a style replaces the +// rows differ. A declared content type is kept, and a style replaces the // content type in a multipart/form-data part as in a form body. No part of a // form body is a file. func assertMultipartDefaults31(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { diff --git a/compilers/openapi/e2e/conformance_promotion_test.go b/compilers/openapi/e2e/conformance_promotion_test.go index 72b4ebbee..451734422 100644 --- a/compilers/openapi/e2e/conformance_promotion_test.go +++ b/compilers/openapi/e2e/conformance_promotion_test.go @@ -160,17 +160,17 @@ func assertExtensionRedaction(t *testing.T, doc *ir.Document, diags []ir.Diagnos assert.Len(t, diags, 2, "false states nothing, and a key read reports nothing: %+v", diags) } -// assertEveryRedactionLanded is the join of the entries and the fields, with no -// list of positions to go stale: every node of the encoded document keeping a -// true x-sensitive entry has to say so in a field, so a carrier a promotion does -// not reach fails here. It returns how many it met. +// assertEveryRedactionLanded is the combination of the entries and the fields, +// with no list of positions to go stale: every node of the encoded document +// keeping a true x-sensitive entry has to say so in a field, so a carrier a +// promotion does not reach fails here. It returns how many it found. func assertEveryRedactionLanded(t *testing.T, doc *ir.Document) int { t.Helper() raw, err := json.Marshal(doc) require.NoError(t, err) var tree any require.NoError(t, json.Unmarshal(raw, &tree)) - met := 0 + redacted := 0 pending := []any{tree} for len(pending) > 0 { node := pending[len(pending)-1] @@ -182,12 +182,12 @@ func assertEveryRedactionLanded(t *testing.T, doc *ir.Document) int { pending = slices.AppendSeq(pending, maps.Values(n)) entry, kept := redactionEntry(n) if kept && entry["value"] == true { - met++ + redacted++ assert.True(t, n["secret"] == true || n["sensitive"] == true, "%v", n["id"]) } } } - return met + return redacted } // redactionEntry returns the x-sensitive entry an encoded node keeps. diff --git a/compilers/openapi/e2e/conformance_responses_test.go b/compilers/openapi/e2e/conformance_responses_test.go index 51478ad2b..24120bb49 100644 --- a/compilers/openapi/e2e/conformance_responses_test.go +++ b/compilers/openapi/e2e/conformance_responses_test.go @@ -67,7 +67,7 @@ func assertErrorCaseIsAResponse(t *testing.T, byRange map[ir.StatusRange]ir.Erro throttled, ok := byRange[ir.StatusRange{From: 429, To: 429}] require.True(t, ok) require.NotNil(t, throttled.Payload) - require.Len(t, throttled.Payload.Contents, 2, "every media type is kept, none elected") + require.Len(t, throttled.Payload.Contents, 2, "every media type is kept, none chosen") assert.Equal(t, "type/openapi/components/schemas/Problem", string(throttled.Payload.Contents[1].Type.Target), "the second media type keeps its own schema rather than the first's") diff --git a/compilers/openapi/e2e/conformance_scalars_test.go b/compilers/openapi/e2e/conformance_scalars_test.go index 9aa2af64a..c5e7d4473 100644 --- a/compilers/openapi/e2e/conformance_scalars_test.go +++ b/compilers/openapi/e2e/conformance_scalars_test.go @@ -37,6 +37,30 @@ func assertEnumString(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { assert.Equal(t, "only", pinned.Members[0].Value.String) } +// assertEnumBounds pins where a bound beside an enum lands: an Enum holds the +// bounds of its value kind in its Constraints, closed or open, the Union of +// literals a mixed enum lowers to holds them in its own, and a bound of +// another kind stays kept verbatim (docs/ir/enums.md#bounds). +func assertEnumBounds(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { + for name, want := range map[string]*ir.Constraints{ + "Mode": {MaxLength: new(int64(8))}, + "Region": {MinLength: new(int64(2)), Pattern: "^[a-z]+$"}, + "Port": {Min: new(ir.BigVal("1")), Max: new(ir.BigVal("65535"))}, + "Tags": nil, + } { + enum, ok := doc.Types[componentID(name)].(*ir.Enum) + require.True(t, ok, "%s is an enum; got %T", name, doc.Types[componentID(name)]) + assert.Equal(t, want, enum.Constraints, name) + } + tags, ok := doc.Types[componentID("Tags")].(*ir.Enum) + require.True(t, ok) + assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, tags.Unmodeled, "openapi:maxItems").Reason) + mixed, ok := doc.Types[componentID("Mixed")].(*ir.Union) + require.True(t, ok, "a mixed enum is a union of literals; got %T", doc.Types[componentID("Mixed")]) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(4))}, mixed.Constraints) + assert.NotContains(t, mixed.Unmodeled, "openapi:maxLength") +} + // assertStringConstUnion pins what the compiler keeps of a union of string // values for pass.ConstUnions to normalize (docs/compilers/openapi.md#string-const-union): // the union, its variants naming the types each branch lowers to, a const's @@ -114,8 +138,9 @@ func assertTypeArrayNumeric(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { // assertTypeArrayBounds pins each value bound beside a type array on the variant // whose type it applies to, a Scalar of its own at /type/, none // on the variant it does not, a format paired with one listed type on that -// variant alone, one no listed type takes kept on the union, and nothing on the -// property carrying one, a bound on an entry beside it included. +// variant alone, a length of the text it is written as kept verbatim there, +// one no listed type takes kept on the union, and nothing on the property +// carrying one, a bound on an entry beside it included. func assertTypeArrayBounds(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { variantOf := func(name string, i int) ir.TypeDef { union, ok := doc.Types[componentID(name)].(*ir.Union) @@ -135,17 +160,19 @@ func assertTypeArrayBounds(t *testing.T, doc *ir.Document, diags []ir.Diagnostic assert.Equal(t, &ir.Constraints{Min: &two}, held("Mixed", 0)) assert.Equal(t, &ir.Constraints{MaxLength: new(int64(3))}, held("Mixed", 1)) assert.Equal(t, &ir.Constraints{MaxLength: new(int64(2))}, held("OnBranch", 1)) - assert.Empty(t, doc.Types[componentID("OnBranch")].Common().Unmodeled, "the entry folded") + assert.Empty(t, doc.Types[componentID("OnBranch")].Common().Unmodeled, "the entry flattened") assert.Equal(t, ir.PrimitiveInteger, primitiveOf(t, variantOf("Dated", 0))) - assert.Equal(t, &ir.Constraints{MinLength: new(int64(10))}, held("Dated", 1)) + assert.Nil(t, held("Dated", 1), "a length of a date's text bounds no date") dated, ok := variantOf("Dated", 1).(*ir.Scalar) require.True(t, ok) assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveDate), dated.Base.Target, "the string variant takes the date") + assert.Equal(t, ir.ReasonNoIRHome, unmodeledEntry(t, dated.Unmodeled, "openapi:minLength").Reason, "and keeps the length verbatim") + assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/unhomed-construct", "/components/schemas/Dated/minLength")) untaken := doc.Types[componentID("Untaken")] assert.Equal(t, ir.RawValue("1"), unmodeledEntry(t, untaken.Common().Unmodeled, "openapi:minProperties").Value) assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/Untaken")) - assert.Len(t, diags, 1, "%+v", diags) + assert.Len(t, diags, 2, "%+v", diags) holder, ok := doc.Types[componentID("Holder")].(*ir.Model) require.True(t, ok) @@ -188,14 +215,13 @@ func assertEmptyEnum(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { "%s is reported once, since nobody writes an empty member list on purpose", name) } - // An Enum has no home for a property set or a composition, so what the empty - // enum is written beside stays verbatim rather than being traded for it. + // An Enum has no home for a property set, so what the empty enum is written + // beside stays verbatim rather than being traded for it; a $ref to a schema + // the empty enum lies within says its own, so nothing of it is kept. properties := unmodeledEntry(t, doc.Types[componentID("BesideProperties")].Common().Unmodeled, "openapi:properties") assert.Equal(t, ir.ReasonDegradedLowering, properties.Reason) assert.JSONEq(t, `{"x":{"type":"string"}}`, string(properties.Value)) - composed := unmodeledEntry(t, doc.Types[componentID("BesideAllOf")].Common().Unmodeled, "openapi:$ref") - assert.Equal(t, ir.ReasonDegradedLowering, composed.Reason) - assert.JSONEq(t, `"#/components/schemas/Base"`, string(composed.Value)) + assert.Empty(t, doc.Types[componentID("BesideAllOf")].Common().Unmodeled) holder, ok := doc.Types[componentID("Holder")].(*ir.Model) require.True(t, ok) @@ -339,8 +365,18 @@ func assertEncodedFormats(t *testing.T, doc *ir.Document, model *ir.Model) { require.True(t, ok) sc, ok := doc.Types[modified.Type.Target].(*ir.Scalar) require.True(t, ok) - require.NotNil(t, sc.Constraints, "the bound beside the format stays on its Scalar") - assert.Equal(t, new(int64(29)), sc.Constraints.MinLength) + assert.Nil(t, sc.Constraints, "a length of the text an instant is written as bounds no instant") + minLength := unmodeledEntry(t, sc.Unmodeled, "openapi:minLength") + assert.Equal(t, ir.ReasonNoIRHome, minLength.Reason, "the Scalar keeps it verbatim") + assert.Equal(t, ir.RawValue("29"), minLength.Value) + resetAt, ok := propertyByWire(model, "resetAt") + require.True(t, ok) + seconds, ok := doc.Types[resetAt.Type.Target].(*ir.Scalar) + require.True(t, ok) + assert.Nil(t, seconds.Constraints, "a minimum of the seconds an instant is written as bounds no instant") + minimum := unmodeledEntry(t, seconds.Unmodeled, "openapi:minimum") + assert.Equal(t, ir.ReasonNoIRHome, minimum.Reason, "the Scalar keeps it verbatim") + assert.Equal(t, ir.RawValue("0"), minimum.Value) } // assertSelectedPrimitives pins the table's pairings this spec writes: each @@ -608,12 +644,15 @@ func assertEncodingByte(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { // A scalar that hoists a node because of its format must keep the bounds it // wrote beside it: owning the pointer is what stops the shared alias path - // attaching them afterwards (GitHub #147). - require.NotNil(t, sc.Constraints, "the hoisted byte scalar carries its own bounds") - require.NotNil(t, sc.Constraints.MinLength) - assert.Equal(t, int64(5), *sc.Constraints.MinLength) - require.NotNil(t, sc.Constraints.MaxLength) - assert.Equal(t, int64(9), *sc.Constraints.MaxLength) + // attaching them afterwards (GitHub #147). A length of the base64 text is + // no bound of the bytes, so it keeps them verbatim + // (docs/ir/constraints.md#constraints). + assert.Nil(t, sc.Constraints, "the bytes' Constraints hold no length of their text") + for keyword, want := range map[string]string{"minLength": "5", "maxLength": "9"} { + kept := unmodeledEntry(t, sc.Unmodeled, "openapi:"+keyword) + assert.Equal(t, ir.RawValue(want), kept.Value, "the hoisted byte scalar keeps its own bounds") + assert.Equal(t, ir.ReasonNoIRHome, kept.Reason, keyword) + } } // assertXMLNodeType32 pins GitHub #615's xml.nodeType: ir.XMLHints.NodeType diff --git a/compilers/openapi/e2e/conformance_test.go b/compilers/openapi/e2e/conformance_test.go index bccaec3c1..f3d9ea09a 100644 --- a/compilers/openapi/e2e/conformance_test.go +++ b/compilers/openapi/e2e/conformance_test.go @@ -182,7 +182,7 @@ func conformanceCases() []conformanceCase { {"required-members", assertRequiredMembers}, {"allof-oneof-cooccurrence", assertAllOfOneOfCooccurrence}, {"allof-union-branch", assertAllOfUnionBranch}, - {"allof-inline-residue", assertAllOfInlineResidue}, + {"allof-inline-residue", assertAllOfInlineKeptKeywords}, {"allof-nested-inline", assertAllOfNestedInline}, {"allof-ref-branch-siblings", assertAllOfRefBranchSiblings}, {"allof-boolean-branch", assertAllOfBooleanBranch}, @@ -194,15 +194,17 @@ func conformanceCases() []conformanceCase { {"allof-position-constraints", assertAllOfPositionConstraints}, {"allof-refinement", assertAllOfRefinement}, {"allof-entry-infers-array", assertAllOfEntryInfersArray}, + {"silent-applicator", assertApplicatorSayingNothing}, {"ref-use-bound-keywords", assertRefUseBoundKeywords}, {"allof-value-set-beside-entry", assertAllOfValueSetBesideEntry}, - {"union-joined-value-sets", assertUnionJoinedValueSets}, + {"union-joined-value-sets", assertUnionCombinedValueSets}, {"kept-ref-unrenderable", assertKeptRefUnrenderable}, {"oneof-discriminated", assertOneOfDiscriminated}, {"anyof-discriminated", assertAnyOfDiscriminated}, {"discriminator-inheritance", assertDiscriminatorInheritance}, {"discriminator-inline-subtype", assertDiscriminatorInlineSubtype}, {"discriminator-default-mapping", assertDiscriminatorDefaultMapping}, + {"discriminator-decode-only", assertDiscriminatorDecodeOnly}, {"discriminator-transitive", assertDiscriminatorTransitive}, {"discriminator-alias-mapping", assertDiscriminatorAliasMapping}, {"discriminated-union-beside-model", assertDiscriminatedUnionBesideModel}, @@ -235,6 +237,7 @@ func conformanceCases() []conformanceCase { {"type-array-bounds", assertTypeArrayBounds}, {"type-array-discriminator", assertTypeArrayDiscriminator}, {"enum-string", assertEnumString}, + {"enum-bounds", assertEnumBounds}, {"enum-numeric", assertEnumNumeric}, {"string-const-union", assertStringConstUnion}, {"empty-enum", assertEmptyEnum}, @@ -280,7 +283,7 @@ func conformanceCases() []conformanceCase { {"querystring-forbidden-keywords", assertQuerystringForbiddenKeywords}, {"param-allowreserved-locations", assertParamAllowReservedLocations}, {laterVersionCase, assertLaterVersionConstructs}, - {"param-xml-residue", assertParamXMLResidue}, + {"param-xml-residue", assertParamXMLKeptKeywords}, {"param-ref-inheritance", assertParamRefInheritance}, {"header-content-schema", assertHeaderContentSchema}, {"header-name-case", assertHeaderNameCase}, @@ -347,7 +350,7 @@ func conformanceCases() []conformanceCase { {"self-uri", assertSelfURI}, {"extensions-x", assertExtensionsX}, {"inline-annotations", assertInlineAnnotations}, - {"inline-residue", assertInlineResidue}, + {"inline-residue", assertInlineKeptKeywords}, {"servers-variables", assertServersVariables}, {"security-schemes", assertSecuritySchemes}, {"oauth2-no-flow", assertOAuth2NoFlow}, diff --git a/compilers/openapi/e2e/conformance_types_test.go b/compilers/openapi/e2e/conformance_types_test.go index e0926aaad..e4636b56e 100644 --- a/compilers/openapi/e2e/conformance_types_test.go +++ b/compilers/openapi/e2e/conformance_types_test.go @@ -335,10 +335,10 @@ func inlinePropertyTarget(t *testing.T, doc *ir.Document, id ir.TypeID, wire str // assertSharedResponseAcrossStatus reads the one shape that puts lowerResponse // and lowerErrorCase on the same declaration: a components/responses entry // mounted at both a success and an error status. Both intern the body type at -// the component's pointer, so the two mints race for it and the loser's naming -// hint is discarded, which the order-invariance oracle reports as an -// order-dependent registry. The hint derives from the declaration pointer, the -// same whichever side reaches it first. No other corpus spec reaches one +// the component's pointer, so the two mints race for it and the passed-over +// one's naming hint is discarded, which the order-invariance oracle reports as +// an order-dependent registry. The hint derives from the declaration pointer, +// the same whichever side reaches it first. No other corpus spec reaches one // response component from both sides, so the oracle needs this one to ask. func assertSharedResponseAcrossStatus(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { operation := operationAt(t, doc, "GET", "/widgets") @@ -435,7 +435,7 @@ func assertReadOnlyWriteOnly(t *testing.T, doc *ir.Document, diags []ir.Diagnost decl, ok := doc.Types[componentID("DeclaredReadOnly")].(*ir.Scalar) require.True(t, ok) entry, ok := decl.Unmodeled["openapi:readOnly"] - require.True(t, ok, "the declaration's own readOnly is kept as residue") + require.True(t, ok, "the declaration's own readOnly is kept") assert.Equal(t, ir.ReasonNoIRHome, entry.Reason) assert.JSONEq(t, `true`, string(entry.Value)) @@ -473,8 +473,8 @@ func assertRecursive(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { // type and entry bounds, and a catch-all beside anything else is a Model's // AdditionalProperties. An explicit `true` types the catch-all as the top type // in either. `unevaluatedProperties: false` closes the object once composition -// is resolved only where no additionalProperties leaves it inert, and beside -// patterns alone nothing types a key they miss. +// is resolved only where no additionalProperties leaves it saying nothing, and +// beside patterns alone nothing types a key they miss. func assertMaps(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { i64 := func(v int64) *int64 { return &v } for name, want := range map[string]*ir.MapT{ @@ -518,26 +518,27 @@ func assertMaps(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { require.NotNil(t, cp.AdditionalProperties) assert.Nil(t, cp.AdditionalProperties.Value, "the source types no key the patterns miss") assert.Len(t, cp.AdditionalProperties.Patterns, 1) - assertInertClosures(t, doc) + assertClosuresSayingNothing(t, doc) } -// assertInertClosures pins the maps' objects writing an unevaluatedProperties -// that additionalProperties beside it leaves inert: additionalProperties alone -// says what each admits, and the keyword is kept with it. -func assertInertClosures(t *testing.T, doc *ir.Document) { +// assertClosuresSayingNothing pins the maps' objects writing an +// unevaluatedProperties that additionalProperties beside it leaves saying +// nothing: additionalProperties alone says what each admits, and the keyword is +// kept with it. +func assertClosuresSayingNothing(t *testing.T, doc *ir.Document) { t.Helper() - inert := map[string]string{ + sayingNothing := map[string]string{ "InertBesideAMap": `{"additionalProperties":{"type":"integer"},"unevaluatedProperties":false}`, "InertBesideARecord": `{"additionalProperties":true,"unevaluatedProperties":{"type":"string"}}`, "ClosedTwice": `{"additionalProperties":false,"unevaluatedProperties":false}`, } - for name, want := range inert { + for name, want := range sayingNothing { entry := unmodeledEntry(t, typeByName(doc, name).Common().Unmodeled, "openapi:unevaluated") assert.Equal(t, ir.ReasonValidationOnly, entry.Reason, name) assert.Equal(t, want, string(entry.Value), name) } mt, ok := typeByName(doc, "InertBesideAMap").(*ir.MapT) - require.True(t, ok, "an inert closure leaves a map a map; got %T", typeByName(doc, "InertBesideAMap")) + require.True(t, ok, "a closure saying nothing leaves a map a map; got %T", typeByName(doc, "InertBesideAMap")) assert.Equal(t, ir.TypeRef{Target: "type/primitive/integer"}, mt.Value) rec, ok := typeByName(doc, "InertBesideARecord").(*ir.Model) require.True(t, ok) @@ -546,15 +547,17 @@ func assertInertClosures(t *testing.T, doc *ir.Document) { assert.Equal(t, &ir.TypeRef{Target: "type/primitive/any"}, rec.AdditionalProperties.Value) twice, ok := typeByName(doc, "ClosedTwice").(*ir.Model) require.True(t, ok) - assert.Equal(t, ir.AdditionalClosed, twice.Additional, "the stronger closure stands") + assert.Equal(t, ir.AdditionalClosed, twice.Additional, "the stronger closure is kept") } // assertTuples pins what each prefixItems tuple admits past its elements and -// the bounds beside them (GitHub #597). Only `items: false` closes a tuple, and -// a typed rest is lowered into the type graph as a List's items is, at the same +// the bounds beside them (GitHub #597). `items: false` closes a tuple, and so +// does an unevaluatedItems false nothing else evaluates past the head, and a +// typed rest is lowered into the type graph as a List's items is, at the same // pointer and under the same hint. All of it is modeled, so no tuple keeps -// anything beside itself or reports a degradation. An unevaluatedItems beside -// them is kept, with the items that leaves it inert. +// anything beside itself or reports a degradation. An unevaluatedItems an items +// leaves saying nothing, or one beside contains, is kept, the first with that +// items. func assertTuples(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { i64 := func(v int64) *int64 { return &v } pair := []ir.TypeRef{{Target: "type/primitive/string"}, {Target: "type/primitive/integer"}} @@ -592,7 +595,6 @@ func assertTuples(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { for name, want := range map[string]string{ "InertPair": `{"items":true,"unevaluatedItems":false}`, - "LivePair": `{"unevaluatedItems":false}`, "InertList": `{"items":{"type":"string"},"unevaluatedItems":{"type":"integer"}}`, "LiveList": `{"unevaluatedItems":false}`, } { @@ -602,13 +604,18 @@ func assertTuples(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { assert.Contains(t, diagsAt(diags, "openapi/validation-only-keyword", "/components/schemas/"+name), ir.SeverityInfo, name) } - for _, name := range []string{"InertPair", "LivePair"} { - tup, ok := typeByName(doc, name).(*ir.Tuple) - require.True(t, ok, name) - if assert.NotNil(t, tup.Rest, name) { - assert.Equal(t, ir.TypeID("type/primitive/any"), tup.Rest.Target, "%s: the entry, not Rest, says what may follow", name) - } + sayingNothing, ok := typeByName(doc, "InertPair").(*ir.Tuple) + require.True(t, ok) + if assert.NotNil(t, sayingNothing.Rest) { + assert.Equal(t, ir.TypeID("type/primitive/any"), sayingNothing.Rest.Target, "items, not the entry saying nothing, says what may follow") } + // Nothing beside a live unevaluatedItems false evaluates an element past + // the head, so it is typed as items false is, and kept nowhere (GitHub + // #1883); beside contains, which the IR does not type, it stays kept. + live, ok := typeByName(doc, "LivePair").(*ir.Tuple) + require.True(t, ok) + assert.Nil(t, live.Rest, "no element follows the head") + assert.NotContains(t, live.Unmodeled, "openapi:unevaluated") } func assertLiteralConst(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { @@ -623,7 +630,7 @@ func assertLiteralConst(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { assert.True(t, ok, "an unconvertible const hoists the top type; got %T", doc.Types[componentID("Opaque")]) assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/Opaque"), - "degrading a declared value is a warning, not silent") + "degrading a declared value is a warning, not left unreported") } // assertUnreferencedComponents pins GitHub #616: every component entry no diff --git a/compilers/openapi/e2e/conformance_unmodeled_test.go b/compilers/openapi/e2e/conformance_unmodeled_test.go index 7c2068100..86e592ed2 100644 --- a/compilers/openapi/e2e/conformance_unmodeled_test.go +++ b/compilers/openapi/e2e/conformance_unmodeled_test.go @@ -115,15 +115,18 @@ func assertUnhomedKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic // where it did not run at all (GitHub #283). $ref is an ordinary 2020-12 // keyword, so the keywords beside it are a conjunct of the position, lowered as // they are beside an allOf of the $ref: each typed on the node the position -// lowers to, or kept on it once, with an info where something is kept. +// lowers to, or kept on it once, with an info where something is kept. A +// format selecting no primitive restricts the reference with its Encoding, at +// a carrier on a node of the position's own. func assertRefSiteKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { t.Helper() format, ok := doc.Types[componentID("RefFormat")].(*ir.Scalar) - require.True(t, ok, "a format beside a $ref to a string is a use of it") + require.True(t, ok, "a format beside a $ref to a string is a restriction of it") require.NotNil(t, format.Base) assert.Equal(t, componentID("RefTargetStr"), format.Base.Target) - assert.JSONEq(t, `"email"`, string(unmodeledEntry(t, format.Unmodeled, "openapi:format").Value)) - assert.Len(t, format.Unmodeled, 1) + assert.Equal(t, &ir.Encoding{Name: "email"}, format.Encoding) + assert.Empty(t, format.Unmodeled) + assert.Empty(t, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/RefFormat")) for name, kind := range map[string]ir.TypeKind{"RefEnum": ir.KindEnum, "RefConst": ir.KindLiteral} { td := kindNode(t, doc, componentID(name)) @@ -133,7 +136,7 @@ func assertRefSiteKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic assert.JSONEq(t, `"#/components/schemas/RefTargetStr"`, string(entry.Value), name) assert.Len(t, td.Common().Unmodeled, 1, name) } - for _, name := range []string{"RefFormat", "RefEnum", "RefConst"} { + for _, name := range []string{"RefEnum", "RefConst"} { assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/"+name), name) } @@ -149,8 +152,17 @@ func assertRefSiteKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic for name, model := range map[string]*ir.Model{"RefRequired": required, "RefAdditionalProperties": closed, "RefDiscriminator": discriminated} { require.NotNil(t, model.Base, name) assert.Equal(t, componentID("RefTargetObj"), model.Base.Target, name) - assert.Empty(t, model.Unmodeled, name) assert.Empty(t, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/"+name), name) + if name == "RefAdditionalProperties" { + // The closure applies to the member the target brings, which its + // own object does not declare, so it is also kept, with one info. + assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, model.Unmodeled, "openapi:additionalProperties").Reason) + assert.Len(t, model.Unmodeled, 1, name) + assert.Equal(t, []ir.Severity{ir.SeverityInfo}, + diagsAt(diags, "openapi/degraded-construct", "/components/schemas/"+name+"/additionalProperties"), name) + continue + } + assert.Empty(t, model.Unmodeled, name) } ctl, ok := doc.Types[componentID("RefConstrained")].(*ir.Scalar) @@ -164,10 +176,12 @@ func assertRefSiteKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic require.True(t, ok) property, ok := propertyByWire(carrier, "p") require.True(t, ok) - assert.Equal(t, componentID("RefTargetStr"), property.Type.Target, - "a carrier hoists no node, so it still resolves straight to the target") - assert.JSONEq(t, `"email"`, string(unmodeledEntry(t, property.Unmodeled, "openapi:format").Value), - "and keeps the keyword on itself instead") + restricted, ok := doc.Types[property.Type.Target].(*ir.Scalar) + require.True(t, ok, "the restriction sits on a node of the property's own, as the flat spelling's Scalar does") + require.NotNil(t, restricted.Base) + assert.Equal(t, componentID("RefTargetStr"), restricted.Base.Target) + assert.Equal(t, &ir.Encoding{Name: "email"}, restricted.Encoding) + assert.Empty(t, property.Unmodeled, "and the carrier keeps nothing") } // assertUnionBesideRef pins oneOf/anyOf and allOf co-declared beside a $ref at @@ -178,11 +192,20 @@ func assertRefSiteKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic // beside it are one conjunction, the union and the allOf among them, lowered // as the allOf of the two is (docs/compilers/openapi.md#ref-use-site). func assertUnionBesideRef(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { - // A union or an allOf beside a $ref joins the conjunction the $ref is one - // conjunct of: beside a $ref to an object a string or an integer shares no - // value with it, so each is the model over Base keeping what shares none, - // with the warning that the conjuncts share no value. - for name, key := range map[string]string{"G": "openapi:oneOf", "H": "openapi:anyOf", "I": "openapi:type"} { + // A union or an allOf beside a $ref is added to the conjunction the $ref is + // one conjunct of: beside a $ref to an object a string or an integer shares + // no value with it, so each is the model over Base keeping what shares + // none, with the warning that the conjuncts share no value. A string beside + // the $ref to an object shares no kind with it, so I is the closed bottom: + // no Base, its own $ref under its plain key and the entry under its entry + // key. + bottom, ok := doc.Types[componentID("I")].(*ir.Model) + require.True(t, ok, "I") + assert.Nil(t, bottom.Base, "I composes nothing") + assert.ElementsMatch(t, []string{"openapi:$ref", "openapi:allOf/0"}, slices.Collect(maps.Keys(bottom.Unmodeled))) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, "openapi/unsatisfiable-schema", ir.SeverityWarning, + "/components/schemas/I"), "no value satisfies") + for name, key := range map[string]string{"G": "openapi:oneOf", "H": "openapi:anyOf"} { model, ok := doc.Types[componentID(name)].(*ir.Model) require.True(t, ok, name) require.NotNil(t, model.Base, name) @@ -190,8 +213,8 @@ func assertUnionBesideRef(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, model.Unmodeled, key).Reason, name) assert.Len(t, model.Unmodeled, 1, "%s keeps what shares no value once", name) assert.Contains(t, - openapitest.DiagMessageAt(t, diags, "openapi/degraded-construct", ir.SeverityWarning, "/components/schemas/"+name), - "share no value", name) + openapitest.DiagMessageAt(t, diags, "openapi/unsatisfiable-schema", ir.SeverityWarning, "/components/schemas/"+name), + "no value satisfies", name) } // At a property the conjunction is a node of the use's own over Base, // keeping the oneOf there, once. @@ -206,8 +229,8 @@ func assertUnionBesideRef(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) assert.Len(t, use.Unmodeled, 1) assert.Empty(t, property.Unmodeled, "the property keeps nothing the node holds") assert.Contains(t, - openapitest.DiagMessageAt(t, diags, "openapi/degraded-construct", ir.SeverityWarning, - "/components/schemas/Carrier/properties/p"), "share no value") + openapitest.DiagMessageAt(t, diags, "openapi/unsatisfiable-schema", ir.SeverityWarning, + "/components/schemas/Carrier/properties/p"), "no value satisfies") } // assertPickedLoweringKeywords pins the keywords the *winning* family's @@ -239,7 +262,7 @@ func assertPickedLoweringKeywords(t *testing.T, doc *ir.Document, diags []ir.Dia } // assertAllOfBooleanBranch pins the lowering of a boolean allOf entry, which -// declares no keywords and so has no residue to rescue (GitHub #154). +// declares no keywords and so has no kept keywords to rescue (GitHub #154). // // The claim is that `false` lowers the same way wherever it appears. The rule // docs/compilers/openapi.md#whole-schema-fallbacks fixes a bare `false` schema @@ -295,15 +318,15 @@ func assertAllOfBooleanBranch(t *testing.T, doc *ir.Document, diags []ir.Diagnos "a false schema and a closed empty model are no longer the same node") } -// assertAllOfInlineResidue pins the residue of an inline allOf entry: what no -// reader consumes survives beside the composed model rather than vanishing into -// it (GitHub #123), and what the position reads lands as it would beside the -// allOf (GitHub #660). +// assertAllOfInlineKeptKeywords pins the kept keywords of an inline allOf +// entry: what no reader consumes survives beside the composed model rather than +// vanishing into it (GitHub #123), and what the position reads lands as it +// would beside the allOf (GitHub #660). // // The severity split is the point. An entry declaring a type that cannot be an // object contradicts the ir.Model the composition produced, so it is a warning; // an entry that only narrows the model further is info. -func assertAllOfInlineResidue(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { +func assertAllOfInlineKeptKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { narrowed, ok := doc.Types[componentID("Narrowed")].(*ir.Model) require.True(t, ok) require.NotNil(t, narrowed.Base, "the $ref entry still becomes Base") @@ -321,13 +344,14 @@ func assertAllOfInlineResidue(t *testing.T, doc *ir.Document, diags []ir.Diagnos diagsAt(diags, "openapi/validation-only-keyword", "/components/schemas/Narrowed/allOf/1"), "an entry that only narrows the model is info") - contradicted, ok := doc.Types[componentID("Contradicted")].(*ir.Model) - require.True(t, ok) - entry = unmodeledEntry(t, contradicted.Unmodeled, "openapi:allOf/1") + contradicted, ok := doc.Types[componentID("Contradicted")].(*ir.Enum) + require.True(t, ok, "entries sharing only null are the null type") + entry = unmodeledEntry(t, contradicted.Unmodeled, "openapi:maxLength") assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assert.Equal(t, []ir.Severity{ir.SeverityWarning}, + assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/Contradicted/allOf/1"), - "an entry excluding object contradicts the composed model and is a warning") + "what the entry keeps is reported where written") + assert.Empty(t, diagsAt(diags, "openapi/unsatisfiable-schema", "/components/schemas/Contradicted/allOf/1")) rebased, ok := doc.Types[componentID("Rebased")].(*ir.Model) require.True(t, ok) @@ -342,10 +366,11 @@ func assertAllOfInlineResidue(t *testing.T, doc *ir.Document, diags []ir.Diagnos // assertAllOfConflictingType pins what an unsatisfiable redeclaration leaves in // the document. A field one allOf entry types `uri` and another `integer` has // no IR combinator, so the merge keeps the later declaration and, under -// docs/compilers/openapi.md#allof-redeclared-property, the loser verbatim -// (GitHub #424). The entry holds the declaration as written, not the dropped IR -// value, because docs/ir/unmodeled.md defines an Unmodeled value as the source -// construct; that keeps the nullable bit a target ID would lose (GitHub #445). +// docs/compilers/openapi.md#allof-redeclared-property, the passed-over +// declaration verbatim (GitHub #424). The entry holds the declaration as +// written, not the dropped IR value, because docs/ir/unmodeled.md defines an +// Unmodeled value as the source construct; that keeps the nullable bit a target +// ID would lose (GitHub #445). // // Described is the same event where the types agree but both entries fill the // fold's one default slot: the first declaration is kept whole and the @@ -382,7 +407,7 @@ func assertAllOfConflictingType(t *testing.T, doc *ir.Document, diags []ir.Diagn require.True(t, ok) did, ok := propertyByWire(described, "id") require.True(t, ok) - assert.Equal(t, &ir.Value{Kind: ir.ValueNumber, Number: "2"}, did.Default, "the later declaration's default stands") + assert.Equal(t, &ir.Value{Kind: ir.ValueNumber, Number: "2"}, did.Default, "the later declaration's default is kept") assert.Equal(t, "second", did.Docs.Description) const describedPtr = "/components/schemas/Described/allOf/0/properties/id" assertKeptRaw(t, did.Unmodeled, "openapi:conflicting-redeclaration"+describedPtr, @@ -398,7 +423,7 @@ func assertAllOfConflictingType(t *testing.T, doc *ir.Document, diags []ir.Diagn require.True(t, ok) property, ok := propertyByWire(overlapping, "n") require.True(t, ok) - assert.Equal(t, ir.TypeID("type/primitive/uint32"), property.Type.Target, "the later declaration stands") + assert.Equal(t, ir.TypeID("type/primitive/uint32"), property.Type.Target, "the later declaration is chosen") const overlapPtr = "/components/schemas/Overlapping/allOf/0/properties/n" assertKeptRaw(t, property.Unmodeled, "openapi:conflicting-redeclaration"+overlapPtr, `{"type":"integer","format":"int32"}`) assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/degraded-construct", overlapPtr), @@ -408,9 +433,9 @@ func assertAllOfConflictingType(t *testing.T, doc *ir.Document, diags []ir.Diagn // assertAllOfRedeclaredModels pins that a field declared as several models names // one minted model composing each declaration, in either entry order, with -// nothing kept but the one value no declaration's own type can answer for. The -// composition sits at the declaration naming the field in the composed space, -// and the conjuncts stay the nodes the source wrote. +// nothing kept: a value the composition admits is adopted. The +// composition sits at the fold's key, /allOf/properties/, in the +// composed space, and the conjuncts stay the nodes the source wrote. func assertAllOfRedeclaredModels(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { const schemas = "/components/schemas/" meeting, recording := ir.TypeID("type/openapi"+schemas+"Meeting"), ir.TypeID("type/openapi"+schemas+"Recording") @@ -419,21 +444,20 @@ func assertAllOfRedeclaredModels(t *testing.T, doc *ir.Document, diags []ir.Diag } for _, tc := range []struct { model, field string - naming string // the allOf entry of the declaration naming the field base ir.TypeID mixins []ir.TypeID nullable bool }{ - {model: "RefFirst", field: "data", naming: "1", base: meeting, mixins: []ir.TypeID{anonymous("RefFirst", "1")}}, - {model: "InlineFirst", field: "data", naming: "1", base: meeting, mixins: []ir.TypeID{anonymous("InlineFirst", "0")}}, - {model: "TwoInline", field: "data", naming: "1", mixins: []ir.TypeID{anonymous("TwoInline", "0"), anonymous("TwoInline", "2")}}, - {model: "TwoComponents", field: "data", naming: "1", mixins: []ir.TypeID{meeting, recording}, nullable: true}, - {model: "DiscriminatedBase", field: "pet", naming: "1", base: "type/openapi" + schemas + "Pet", mixins: []ir.TypeID{recording}}, - {model: "DiscriminatedFirst", field: "pet", naming: "1", base: "type/openapi" + schemas + "Pet", mixins: []ir.TypeID{recording}}, + {model: "RefFirst", field: "data", base: meeting, mixins: []ir.TypeID{anonymous("RefFirst", "1")}}, + {model: "InlineFirst", field: "data", base: meeting, mixins: []ir.TypeID{anonymous("InlineFirst", "0")}}, + {model: "TwoInline", field: "data", mixins: []ir.TypeID{anonymous("TwoInline", "0"), anonymous("TwoInline", "2")}}, + {model: "TwoComponents", field: "data", mixins: []ir.TypeID{meeting, recording}, nullable: true}, + {model: "DiscriminatedBase", field: "pet", base: "type/openapi" + schemas + "Pet", mixins: []ir.TypeID{recording}}, + {model: "DiscriminatedFirst", field: "pet", base: "type/openapi" + schemas + "Pet", mixins: []ir.TypeID{recording}}, // The default beside the first declaration's $ref binds that use, which // a property carries, so the declaration is the reference, as one writing // nothing beside its $ref is: the field composes the two components. - {model: "KeptDefault", field: "data", naming: "1", mixins: []ir.TypeID{meeting, recording}}, + {model: "KeptDefault", field: "data", mixins: []ir.TypeID{meeting, recording}}, } { owner, ok := doc.Types[ir.TypeID("type/openapi"+schemas+tc.model)].(*ir.Model) require.True(t, ok, tc.model) @@ -441,7 +465,7 @@ func assertAllOfRedeclaredModels(t *testing.T, doc *ir.Document, diags []ir.Diag property := owner.Properties[0] assert.Equal(t, tc.field, property.WireName, tc.model) assert.Equal(t, tc.nullable, property.Type.Nullable, tc.model) - want := ir.TypeID("type/composed" + schemas + tc.model + "/allOf/" + tc.naming + "/properties/" + tc.field) + want := ir.TypeID("type/composed" + schemas + tc.model + "/allOf/properties/" + tc.field) require.Equal(t, want, property.Type.Target, tc.model) model, ok := doc.Types[want].(*ir.Model) require.True(t, ok, tc.model) @@ -479,10 +503,10 @@ func assertAllOfRedeclaredModels(t *testing.T, doc *ir.Document, diags []ir.Diag require.True(t, ok) kept, ok := propertyByWire(owner, "data") require.True(t, ok) - assert.Nil(t, kept.Default, "a value is not adopted as the composition's") - assert.Contains(t, kept.Unmodeled, "openapi:conflicting-redeclaration"+schemas+"KeptDefault/allOf/0/properties/data") - require.Len(t, diags, 1, "only the kept default is reported") - assert.Equal(t, schemas+"KeptDefault/allOf/0/properties/data", string(diags[0].Provenance.Pointer)) + require.NotNil(t, kept.Default, "a value the composition admits is adopted") + assert.Equal(t, ir.ValueObject, kept.Default.Kind) + assert.Empty(t, kept.Unmodeled, "and nothing is kept") + assert.Empty(t, diags, "or reported") } // assertAllOfNarrowingRedeclaration pins that a redeclaration narrowing a bare @@ -537,13 +561,13 @@ func assertAllOfNarrowingRedeclaration(t *testing.T, doc *ir.Document, diags []i assertInadmissibleDefault(t, doc, diags) assertNarrowingChainsAndScalars(t, doc, diags) assertRefusedLateDefault(t, doc, diags) - assertEnumsAndAliasesMeet(t, doc, diags) + assertEnumsAndAliasesIntersect(t, doc, diags) } -// assertEnumsAndAliasesMeet holds the enums of different value types and the -// aliases beside a node they meet: each field is the enum or the list holding -// what every declaration says, in either order, with no diagnostic. -func assertEnumsAndAliasesMeet(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { +// assertEnumsAndAliasesIntersect holds the enums of different value types and +// the aliases beside a node they intersect: each field is the enum or the list +// holding what every declaration says, in either order, with no diagnostic. +func assertEnumsAndAliasesIntersect(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { t.Helper() enumOf := func(model string) *ir.Enum { property := narrowedProperty(t, doc, model) @@ -660,14 +684,13 @@ func assertInadmissibleDefault(t *testing.T, doc *ir.Document, diags []ir.Diagno } } -// narrowedProperty returns property property of the named component model. // assertAllOfRedeclaredBounds pins what a field keeps of the bounds its // declarations write, each order a model of its own, since the order oracle never // swaps a sequence. The fixture declares the looser bound first as well as last: // the first declaration's bound used to be kept, so a tighter one declared first // shows nothing. A bound the field implies draws no report and leaves no entry, a -// pattern stays kept and reported, and a default another declaration's bound -// refuses stays off the field while one its own bound refuses stands. +// pattern stays kept and reported, and a default a bound refuses stays off the +// field, whether another declaration wrote the bound or its own did. func assertAllOfRedeclaredBounds(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { lo, hi, step := new(int64(2)), new(int64(10)), new(ir.BigVal("12")) for _, tc := range []struct { @@ -719,7 +742,7 @@ func assertAllOfRedeclaredBounds(t *testing.T, doc *ir.Document, diags []ir.Diag } { property := narrowedProperty(t, doc, tc.model) lost := "/components/schemas/" + tc.model + "/" + tc.lost + "/properties/p" - assert.Equal(t, tc.pattern, property.Constraints.Pattern, "%s: the later stands", tc.model) + assert.Equal(t, tc.pattern, property.Constraints.Pattern, "%s: the later is chosen", tc.model) assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+lost, tc.model) assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, "openapi/conflicting-redeclaration", lost), tc.model) } @@ -727,6 +750,8 @@ func assertAllOfRedeclaredBounds(t *testing.T, doc *ir.Document, diags []ir.Diag for _, tc := range []struct{ model, wrote string }{ {"DefaultPastAnotherBoundDefaultFirst", "allOf/0"}, {"DefaultPastAnotherBoundBoundFirst", "allOf/1"}, + {"DefaultPastItsOwnBoundFirst", "allOf/0"}, + {"DefaultPastItsOwnBoundLast", "allOf/1"}, } { property := narrowedProperty(t, doc, tc.model) wrote := "/components/schemas/" + tc.model + "/" + tc.wrote + "/properties/p" @@ -734,11 +759,9 @@ func assertAllOfRedeclaredBounds(t *testing.T, doc *ir.Document, diags []ir.Diag assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+wrote, tc.model) assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/degraded-construct", wrote), tc.model) } - own := narrowedProperty(t, doc, "DefaultPastItsOwnBound") - require.NotNil(t, own.Default, "a default its own bound refuses is its own to answer for") - assert.Equal(t, "hello", own.Default.String) } +// narrowedProperty returns property p of the named component model. func narrowedProperty(t *testing.T, doc *ir.Document, model string) ir.Property { t.Helper() irModel, ok := doc.Types[componentID(model)].(*ir.Model) @@ -778,14 +801,12 @@ func assertAllOfRefBranchSiblings(t *testing.T, doc *ir.Document, diags []ir.Dia // are conjuncts of the composition, as an inline entry's are: here they share // no value with Base, so the composition warns that no instance satisfies it, // still composes Base, and keeps what Base cannot hold, once, under its own -// key, as an inline entry's keyword is kept. +// key, as an inline entry's keyword is kept, which the warning says, the +// entry drawing no info of its own. func assertAllOfRefBranchUnion(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { t.Helper() for name, want := range map[string]struct{ key, raw, at string }{ "UnionBranch": {"openapi:oneOf", `[{"type":"string"},{"type":"integer"}]`, "/allOf/0"}, - // Its type disagrees with the one the composition writes, so the entry - // is kept whole. - "NestedAllOfBranch": {"openapi:allOf/0/allOf/0", `{"type":"string"}`, "/allOf/0/allOf/0"}, } { model := requireModelNode(t, doc, componentID(name)) require.NotNil(t, model.Base, name) @@ -796,10 +817,24 @@ func assertAllOfRefBranchUnion(t *testing.T, doc *ir.Document, diags []ir.Diagno assert.JSONEq(t, want.raw, string(entry.Value), name) assert.Len(t, model.Unmodeled, 1, name) assert.Contains(t, - openapitest.DiagMessageAt(t, diags, "openapi/degraded-construct", ir.SeverityWarning, - "/components/schemas/"+name), "share no value", name) - assert.Equal(t, []ir.Severity{ir.SeverityInfo}, - diagsAt(diags, "openapi/degraded-construct", "/components/schemas/"+name+want.at), name) + openapitest.DiagMessageAt(t, diags, "openapi/unsatisfiable-schema", ir.SeverityWarning, + "/components/schemas/"+name), "its allOf/0/oneOf kept verbatim under Unmodeled", name) + assert.Empty(t, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/"+name+want.at), name) + } + // A string nested beside the entry's $ref to an object shares no kind with + // it: the closed bottom keeps its own type and properties under their plain + // keys and the entry whole, $ref inside, under its entry key, with the one + // warning and no report of what has no home. + nested := requireModelNode(t, doc, componentID("NestedAllOfBranch")) + assert.Nil(t, nested.Base, "the bottom composes nothing") + assert.ElementsMatch(t, []string{"openapi:allOf/0", "openapi:properties", "openapi:type"}, + slices.Collect(maps.Keys(nested.Unmodeled))) + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, + diagsAt(diags, "openapi/unsatisfiable-schema", "/components/schemas/NestedAllOfBranch")) + for _, d := range diags { + if strings.HasPrefix(string(d.Provenance.Pointer), "/components/schemas/NestedAllOfBranch") { + assert.NotContains(t, d.Message, "no home for properties, type") + } } } @@ -823,11 +858,12 @@ func assertAllOfRefBranchShapes(t *testing.T, doc *ir.Document) { assert.Empty(t, anonymousNodesAt(doc, "/components/schemas/Bare")) } -// assertParamXMLResidue pins a parameter schema's xml hints: ir.Parameter is the -// one annotation carrier with no XML field, and the hint is not inert here — a -// content-style parameter can bind application/xml (GitHub #124). Both parameter -// shapes are covered because they read the schema from different places. -func assertParamXMLResidue(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { +// assertParamXMLKeptKeywords pins a parameter schema's xml hints: ir.Parameter +// is the one annotation carrier with no XML field, and the hint says something +// here — a content-style parameter can bind application/xml (GitHub #124). Both +// parameter shapes are covered because they read the schema from different +// places. +func assertParamXMLKeptKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { operation, ok := operationByName(doc, "findDocs") require.True(t, ok) require.Len(t, operation.Params, 2) @@ -1122,10 +1158,8 @@ func assertDynamicRef(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { children, ok := doc.Types[ir.TypeID("type/anonymous/components/schemas/Recursive/properties/children")].(*ir.List) require.True(t, ok) - element, ok := doc.Types[children.ElementType.Target].(*ir.Scalar) - require.True(t, ok) - require.NotNil(t, element.Base) - assert.Equal(t, componentID("Recursive"), element.Base.Target, "a $recursiveRef names its resource's root") + assert.Equal(t, componentID("Recursive"), children.ElementType.Target, + "a $recursiveRef names its resource's root, as a $ref there would, with no alias between") assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/dynamic-ref-expanded", "/components/schemas/Recursive/properties/children/items/$recursiveRef")) @@ -1160,7 +1194,7 @@ func assertDynamicRefAcrossAnEmptyName(t *testing.T, doc *ir.Document, diags []i }), "%+v", kept) } -// assertInlineResidue pins the other half of the rule +// assertInlineKeptKeywords pins the other half of the rule // docs/compilers/openapi.md#use-bound-annotations: a keyword that binds a *use* // of a type reaches referencing properties, and an inline position that owns a // node has no referencing property at all, so what a declaration there wrote @@ -1168,14 +1202,14 @@ func assertDynamicRefAcrossAnEmptyName(t *testing.T, doc *ir.Document, diags []i // // The carrier case is asserted too, because it is what stops the fix from // double-recording: a property lands all three in its own fields, so neither it -// nor the node its own shape owns may keep residue. -func assertInlineResidue(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { +// nor the node its own shape owns may keep them. +func assertInlineKeptKeywords(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { operation, ok := operationByName(doc, "getThing") require.True(t, ok) bodyID := openapitest.BodyTarget(t, operation.Responses[0].Payload) body, ok := doc.Types[bodyID] require.True(t, ok, "the response body owns a node") - assertResidue(t, body.Common().Unmodeled, map[string]string{ + assertKeptKeywords(t, body.Common().Unmodeled, map[string]string{ "openapi:default": `"x"`, "openapi:readOnly": `true`, }) @@ -1183,7 +1217,7 @@ func assertInlineResidue(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { require.True(t, ok) element, ok := doc.Types[batch.ElementType.Target] require.True(t, ok, "the annotated element owns a node") - assertResidue(t, element.Common().Unmodeled, map[string]string{ + assertKeptKeywords(t, element.Common().Unmodeled, map[string]string{ "openapi:default": `7`, "openapi:writeOnly": `true`, }) @@ -1197,19 +1231,19 @@ func assertInlineResidue(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { "a carrier lands the default in its own field") assert.Equal(t, []ir.Lifecycle{ir.LifecycleRead, ir.LifecycleDelete, ir.LifecycleQuery}, property.Visibility.Only) - assert.Empty(t, property.Unmodeled, "a carrier records no residue for what it already holds") + assert.Empty(t, property.Unmodeled, "a carrier keeps no keyword for what it already holds") // The carrier's array shape interns a node at the property's own pointer, // which is where a recorder that stopped distinguishing the two homes would - // put the residue. + // put them. pNode, ok := doc.Types[property.Type.Target].(*ir.List) require.True(t, ok, "the carrier's array shape owns a node") assert.Empty(t, pNode.Unmodeled, "nor on the node that shape owns") } -// assertResidue requires unmodeled to hold exactly the given keys, each under +// assertKeptKeywords requires unmodeled to hold exactly the given keys, each under // ReasonNoIRHome with the given JSON value. -func assertResidue(t *testing.T, unmodeled ir.Unmodeled, want map[string]string) { +func assertKeptKeywords(t *testing.T, unmodeled ir.Unmodeled, want map[string]string) { t.Helper() assert.Len(t, unmodeled, len(want)) for key, value := range want { @@ -1357,16 +1391,20 @@ func assertCoDeclaredKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnos anyOf := `[{"type":"number"},{"type":"boolean"}]` both, ok := doc.Types[componentID("BothCombinators")].(*ir.Union) require.True(t, ok, "oneOf becomes the union") - assert.Len(t, both.Variants, 2, "with a variant per oneOf branch") + require.Len(t, both.Variants, 1, "a variant per oneOf branch sharing a value with the anyOf") + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInteger), both.Variants[0].Type.Target) assertKeptRaw(t, both.Unmodeled, "openapi:anyOf", anyOf) + assertKeptRaw(t, both.Unmodeled, "openapi:oneOf", `[{"type":"string"},{"type":"integer"}]`) + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, + diagsAt(diags, "openapi/unsatisfiable-schema", "/components/schemas/BothCombinators/oneOf"), + "BothCombinators warns of its string branch at the oneOf") - // Suppressing the {X, null} collapse is what gives this one a node of its - // own: collapsing would resolve the position to the shared string primitive, - // which must never carry one declaration's keywords. - nullable, ok := doc.Types[componentID("NullableWithCombinators")].(*ir.Union) - require.True(t, ok, "a co-declared anyOf stops the {X, null} collapse") - assert.Len(t, nullable.Variants, 1, "the null branch still lifts off the variant list") - assertKeptRaw(t, nullable.Unmodeled, "openapi:anyOf", anyOf) + // No branch of the oneOf shares a value with the anyOf, so the position + // is the top type, keeping both unions. + nullable := doc.Types[componentID("NullableWithCombinators")] + require.NotNil(t, nullable) + assertKeptRaw(t, nullable.Common().Unmodeled, "openapi:anyOf", anyOf) + assertKeptRaw(t, nullable.Common().Unmodeled, "openapi:oneOf", `[{"type":"string"},{"type":"null"}]`) for _, at := range []string{ "NarrowedEnum/allOf/0", "NarrowedConst/allOf/0", "ConstWithinEnum", "BothCombinators", @@ -1376,10 +1414,13 @@ func assertCoDeclaredKeywords(t *testing.T, doc *ir.Document, diags []ir.Diagnos "%s announces the keyword it passed over", at) } // No string or null is a number or a boolean, so no instance satisfies the - // two unions together, which the position warns of beside the announcement. - assert.Equal(t, []ir.Severity{ir.SeverityInfo, ir.SeverityWarning}, - diagsAt(diags, "openapi/degraded-construct", "/components/schemas/NullableWithCombinators"), - "NullableWithCombinators announces the keyword it passed over and that its unions share no value") + // two unions together, which the position's one warning says, with what it + // keeps of them, and no announcement beside it. + assert.Empty(t, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/NullableWithCombinators"), + "NullableWithCombinators's warning says what it keeps") + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, + diagsAt(diags, "openapi/unsatisfiable-schema", "/components/schemas/NullableWithCombinators"), + "NullableWithCombinators says its unions share no value") } // assertKeptRaw requires unmodeled to hold key under ReasonDegradedLowering @@ -1393,7 +1434,7 @@ func assertKeptRaw(t *testing.T, unmodeled ir.Unmodeled, key, want string) { // assertNullOnlyUnion covers a oneOf/anyOf whose only branches admit null // alone: one branch, two, either combinator, the other spellings of the null, -// and both combinators declared at once with the elected one null-only. With no +// and both combinators declared at once with the chosen one null-only. With no // other branch to collapse onto, buildUnion would strip every branch and intern // a Union with no variants, which irverify rejects as ir/union-no-variants // (GitHub #416). Such a set admits only null, as `{type: null}` does, so it @@ -1419,12 +1460,12 @@ func assertNullOnlyUnion(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) } // BothNull declares oneOf and anyOf at once, each with its own null-only - // branch. unionBranches elects oneOf, so lowerNullOnlyUnion is reached the - // same way as the single-combinator cases above, but buildUnion is never - // called at all here — which is what sidesteps preserveUnusedCombinator, - // the union path's usual way of keeping a passed-over combinator. Both - // keywords must therefore come from preserveBranchSets's own loop over - // both, not from that mechanism. + // branch. loweredKeyword chooses oneOf, so lowerNullOnlyUnion is reached + // the same way as the single-combinator cases above, but buildUnion is + // never called at all here — which is what sidesteps + // keepUnusedCombinatorReports, the union path's usual way of keeping a + // passed-over combinator. Both keywords must therefore come from + // keepBranchSets's own loop over both, not from that mechanism. both := assertNullOnlyEnum(t, doc, "BothNull") assertKeptRaw(t, both.Unmodeled, "openapi:oneOf", `[{"type":"null"}]`) assertKeptRaw(t, both.Unmodeled, "openapi:anyOf", `[{"type":"null"}]`) @@ -1453,12 +1494,12 @@ func assertNullOnlyEnum(t *testing.T, doc *ir.Document, name string) *ir.Enum { return enum } -// assertCoDeclaredSchemaContent covers the election at the other pair of +// assertCoDeclaredSchemaContent covers the choice at the other pair of // positions: a parameter and a header may state their type as `schema` or as -// `content`, and OpenAPI forbids both. `content` is elected at both — it names a +// `content`, and OpenAPI forbids both. `content` is chosen at both — it names a // media type the IR models, which the schema spelling has none of — and the -// passed-over schema is kept verbatim rather than dropped, which is what the two -// positions each did in silence, in opposite directions (GitHub #320). +// passed-over schema is kept verbatim rather than dropped, which is what the +// two positions each did in silence, in opposite directions (GitHub #320). func assertCoDeclaredSchemaContent(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { operation, ok := operationByName(doc, "getX") require.True(t, ok) @@ -1470,7 +1511,7 @@ func assertCoDeclaredSchemaContent(t *testing.T, doc *ir.Document, diags []ir.Di param, found := openapitest.ParamBySource(operation, name) require.True(t, found, "parameter %s", name) assert.Equal(t, ir.TypeID("type/primitive/string"), param.Type.Target, - "parameter %s takes its type from the elected content entry, not from the schema", name) + "parameter %s takes its type from the chosen content entry, not from the schema", name) assert.Equal(t, "application/json", binding[name].ContentType, "and the media type that entry names reaches the binding") assertKeptRaw(t, param.Unmodeled, "openapi:schema", `{"type":"integer"}`) @@ -1483,7 +1524,7 @@ func assertCoDeclaredSchemaContent(t *testing.T, doc *ir.Document, diags []ir.Di header, ok := headerByWire(operation.Responses[0].Headers, "X-H") require.True(t, ok) assert.Equal(t, ir.TypeID("type/primitive/string"), header.Type.Target, - "the header elects content too: one order, not one per position") + "the header chooses content too: one order, not one per position") require.NotNil(t, header.Encoding) assert.Equal(t, "application/json", header.Encoding.MediaType) assertKeptRaw(t, header.Unmodeled, "openapi:schema", `{"type":"integer"}`) @@ -1492,9 +1533,9 @@ func assertCoDeclaredSchemaContent(t *testing.T, doc *ir.Document, diags []ir.Di } // assertContentSeveralEntries pins how a parameter and a header holding several -// content entries lower: each elects the lowest key, though the spec declares it -// last, keeps every other entry whole on the Document under its own coordinate, -// and names them in one warning at the map, sorted. +// content entries lower: each chooses the lowest key, though the spec declares +// it last, keeps every other entry whole on the Document under its own +// coordinate, and names them in one warning at the map, sorted. func assertContentSeveralEntries(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { operation, ok := operationByName(doc, "getX") require.True(t, ok) @@ -1547,18 +1588,25 @@ func indexByParam(bindings []ir.HTTPParamBinding) map[string]ir.HTTPParamBinding func assertMergeDepthBound(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { const code = "openapi/degraded-construct" for _, name := range []string{"Str", "Int", "Arr", "Obj", "Doc", "Enum", "Log", "Disc"} { - assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, code, "/components/schemas/"+name), - "%s: one warning, at the schema", name) + // Log's oneOf, an integer branch of which shares no kind with its + // string body, is kept by the body's node with an info of its own. + warnings := slices.DeleteFunc(diagsAt(diags, code, "/components/schemas/"+name), func(severity ir.Severity) bool { + return severity != ir.SeverityWarning + }) + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, warnings, "%s: one warning, at the schema", name) } assert.Len(t, diagsAt(diags, code, ""), 1, "the document's own warning names no position") + // Str's bytes are written as base64, whose text its bounds bind, so the + // Scalar keeps them verbatim as written (docs/ir/constraints.md#constraints). stringType, ok := typeByName(doc, "Str").(*ir.Scalar) require.True(t, ok) - require.NotNil(t, stringType.Constraints.MinLength) - require.NotNil(t, stringType.Constraints.MaxLength) - assert.Equal(t, [2]int64{1, 9}, [2]int64{*stringType.Constraints.MinLength, *stringType.Constraints.MaxLength}, - "a keyword merged in within the bound is read as written") - assert.Equal(t, "^a", stringType.Constraints.Pattern) + assert.Nil(t, stringType.Constraints) + for keyword, want := range map[string]string{"minLength": "1", "maxLength": "9", "pattern": `"^a"`} { + kept := unmodeledEntry(t, stringType.Unmodeled, "openapi:"+keyword) + assert.Equal(t, ir.RawValue(want), kept.Value, "a keyword merged in within the bound is read as written") + assert.Equal(t, ir.ReasonNoIRHome, kept.Reason, keyword) + } literal, ok := typeByName(doc, "Doc").(*ir.Literal) require.True(t, ok) @@ -1691,11 +1739,10 @@ func assertKeywordsAtEveryOutcome(t *testing.T, doc *ir.Document, diags []ir.Dia }{ {"Bare", typeByName(doc, "Bare"), []string{"format"}, `a node of kind "union"`}, {"Dist", typeByName(doc, "Dist"), []string{"format", "maxItems"}, "a union of models"}, - {"Dyn", typeByName(doc, "Dyn"), []string{"discriminator", "format"}, "$dynamicRef expands to"}, + {"Dyn", typeByName(doc, "Dyn"), []string{"format"}, `a node of kind "model"`}, {"NoObjectVariant", typeByName(doc, "NoObjectVariant"), []string{"properties"}, `a node of kind "union"`}, {"NoArrayVariant", typeByName(doc, "NoArrayVariant"), []string{"items", "maxItems"}, `a node of kind "union"`}, {"NoRouting", typeByName(doc, "NoRouting"), []string{"discriminator"}, `a node of kind "union"`}, - {"NoBound", typeByName(doc, "NoBound"), []string{"pattern"}, `a node of kind "union"`}, } for _, tc := range kept { t.Run(tc.name, func(t *testing.T) { @@ -1721,22 +1768,29 @@ func assertKeywordsAtEveryOutcome(t *testing.T, doc *ir.Document, diags []ir.Dia require.True(t, ok) assert.Equal(t, &ir.Constraints{MinLength: new(int64(3))}, bare.Constraints, "a union holds the bound beside it") + // An empty pattern matches every string, so it says nothing: the union + // keeps none of it and nothing reports it. + noBound, ok := typeByName(doc, "NoBound").(*ir.Union) + require.True(t, ok) + assert.Empty(t, noBound.Unmodeled, "an empty pattern is the keyword left out") + assert.Empty(t, diagsAt(diags, "openapi/degraded-construct", "/components/schemas/NoBound")) + carrier, ok := typeByName(doc, "Carrier").(*ir.Model) require.True(t, ok) dyn, ok := propertyByWire(carrier, "dyn") require.True(t, ok) assert.Equal(t, componentID("Node"), dyn.Type.Target, "a carrier keeps the reference, not an alias") assert.Nil(t, dyn.Constraints, "the anchor is no array, so no collection bound is held") - assert.ElementsMatch(t, []string{"openapi:maxItems", "openapi:uniqueItems"}, slices.Collect(maps.Keys(dyn.Unmodeled))) + assert.ElementsMatch(t, []string{"openapi:maxItems"}, slices.Collect(maps.Keys(dyn.Unmodeled)), + "a false uniqueItems says nothing, so only the bound is kept") assertKept(t, dyn.Unmodeled, []keptEntry{ {"openapi:maxItems", "2", "/components/schemas/Carrier/properties/dyn/maxItems"}, - {"openapi:uniqueItems", "false", "/components/schemas/Carrier/properties/dyn/uniqueItems"}, }) - for _, key := range []string{"openapi:maxItems", "openapi:uniqueItems"} { - assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, dyn.Unmodeled, key).Reason, key) - } - assert.Contains(t, openapitest.DiagMessageAt(t, diags, "openapi/degraded-construct", ir.SeverityInfo, - "/components/schemas/Carrier/properties/dyn"), "maxItems, uniqueItems") + assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, dyn.Unmodeled, "openapi:maxItems").Reason) + said := openapitest.DiagMessageAt(t, diags, "openapi/degraded-construct", ir.SeverityInfo, + "/components/schemas/Carrier/properties/dyn") + assert.Contains(t, said, "no home for maxItems declared") + assert.NotContains(t, said, "uniqueItems") beside := typeByName(doc, "BesideAUnion").Common().Unmodeled assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, beside, "openapi:oneOf").Reason) @@ -1749,9 +1803,10 @@ func assertKeywordsAtEveryOutcome(t *testing.T, doc *ir.Document, diags []ir.Dia // assertUnevaluatedAtEveryOutcome pins where `unevaluatedProperties: false` // reaches the IR: a model's openness where the position built one closed after -// composition, itself or as a variant of a union it built, and otherwise -// verbatim under openapi:unevaluated, once, on the node or carrier the position -// owns, at a component, a property, an items schema and a parameter's schema. +// composition, itself or as a variant of a union it built whose branches +// require disjoint tags, and otherwise verbatim under openapi:unevaluated, +// once, on the node or carrier the position owns, at a component, a property, +// an items schema and a parameter's schema. // No matrix row: the case is a preservation claim. func assertUnevaluatedAtEveryOutcome(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { for _, name := range []string{"Closed", "ObjectVariant", "Distributed"} { @@ -1759,7 +1814,7 @@ func assertUnevaluatedAtEveryOutcome(t *testing.T, doc *ir.Document, diags []ir. } kept := map[string]ir.Unmodeled{} for _, name := range []string{"Scalar", "Enumerated", "Constant", "Listed", "Paired", "Alias", "PlainUnion", - "NoObjectVariant", "Anything", "ClosedByABranch"} { + "NoObjectVariant", "Anything", "ClosedByABranch", "Overlapping"} { kept["/components/schemas/"+name] = typeByName(doc, name).Common().Unmodeled } holder, ok := typeByName(doc, "Holder").(*ir.Model) diff --git a/compilers/openapi/e2e/conformance_values_test.go b/compilers/openapi/e2e/conformance_values_test.go index 7616a544a..c5dfcc2f4 100644 --- a/compilers/openapi/e2e/conformance_values_test.go +++ b/compilers/openapi/e2e/conformance_values_test.go @@ -35,7 +35,7 @@ func assertDefaults(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { decl, ok := doc.Types[componentID("DeclaredDefault")].(*ir.Scalar) require.True(t, ok) entry, ok := decl.Unmodeled["openapi:default"] - require.True(t, ok, "the declaration's own default is kept as residue") + require.True(t, ok, "the declaration's own default is kept") assert.Equal(t, ir.ReasonNoIRHome, entry.Reason) assert.JSONEq(t, `41`, string(entry.Value)) @@ -155,14 +155,15 @@ func assertRawPreservedDates(t *testing.T, doc *ir.Document) { } // assertRefCollectionBounds holds each position to the one home a collection -// bound written for one use of a shared list has, and the one bound kept -// unread, verbatim, to the one report the whole document draws. +// bound written for one use of a shared list has. A uniqueItems written false +// equals the keyword left out, so it says nothing beside the $ref: that +// property is the bare reference, and the document draws no report. func assertRefCollectionBounds(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { holder, ok := doc.Types[componentID("Holder")].(*ir.Model) require.True(t, ok) minOne, maxThree := &ir.Constraints{MinItems: new(int64(1))}, &ir.Constraints{MaxItems: new(int64(3))} - for wire, want := range map[string]*ir.Constraints{"plain": nil, "beside": minOne, "nullable": maxThree} { + for wire, want := range map[string]*ir.Constraints{"plain": nil, "beside": minOne, "nullable": maxThree, "unstated": nil} { property, found := propertyByWire(holder, wire) require.True(t, found, wire) assert.Equal(t, want, property.Constraints, wire) @@ -170,8 +171,7 @@ func assertRefCollectionBounds(t *testing.T, doc *ir.Document, diags []ir.Diagno } unstated, found := propertyByWire(holder, "unstated") require.True(t, found) - assert.Nil(t, unstated.Constraints) - assert.Equal(t, ir.ReasonDegradedLowering, unstated.Unmodeled["openapi:uniqueItems"].Reason) + assert.Equal(t, ir.TypeRef{Target: componentID("Tags")}, unstated.Type, "a false uniqueItems lowers as the keyword left out") element, ok := doc.Types[componentID("Element")].(*ir.List) require.True(t, ok) @@ -194,7 +194,7 @@ func assertRefCollectionBounds(t *testing.T, doc *ir.Document, diags []ir.Diagno require.True(t, ok) assert.Equal(t, &ir.Constraints{UniqueItems: true}, body.Constraints) - assert.Len(t, diags, 1, "only the bound left verbatim is reported: %+v", diags) + assert.Empty(t, diags, "nothing is left verbatim, so nothing is reported") } func assertConstraints(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { @@ -524,7 +524,7 @@ func assertReferenceBounds(t *testing.T, doc *ir.Document, diags []ir.Diagnostic inline, found := propertyByWire(holder, "inline") require.True(t, found) assert.Nil(t, inline.Constraints) - assert.Empty(t, inline.Unmodeled, "the list the entry builds stands at the property and keeps the bound") + assert.Empty(t, inline.Unmodeled, "the list the entry builds sits at the property and keeps the bound") list, ok := doc.Types[inline.Type.Target].(*ir.List) require.True(t, ok, "%T", doc.Types[inline.Type.Target]) assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Failure/properties/inline"), list.ID) @@ -570,13 +570,14 @@ func assertReferenceBounds(t *testing.T, doc *ir.Document, diags []ir.Diagnostic assert.Contains(t, header.Unmodeled, "openapi:schema/pattern") } -// assertUnionJoinedValueSets holds union-joined-value-sets to -// docs/compilers/openapi.md#allof-refinement: the value sets of a union's -// branches are one set to the conjunct beside them, whether the branches share -// members, nest, or number more than a set joins beside its first. A set lying -// within what the union admits is the position's, and the union is kept; one -// that does not leaves the union the position's node, with the set kept. -func assertUnionJoinedValueSets(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { +// assertUnionCombinedValueSets holds union-joined-value-sets to +// docs/compilers/openapi.md#allof-refinement: a union of value sets is one set +// to the conjunct beside it, the members of its branches, whether they share +// members, nest, or number more than a set combines beside its first. Where +// every member of the set beside it lies within the union, the union says +// nothing, neither kept nor reported; else the position is the Enum of what the +// two share, the union kept once only where a branch shares none, named dead. +func assertUnionCombinedValueSets(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { memberStrings := func(enum *ir.Enum) []string { out := make([]string, 0, len(enum.Members)) for _, enumMember := range enum.Members { @@ -588,17 +589,27 @@ func assertUnionJoinedValueSets(t *testing.T, doc *ir.Document, diags []ir.Diagn nested, ok := typeByName(doc, "Nested").(*ir.Enum) require.True(t, ok, "a set within the nested union's members is the position") assert.Equal(t, []string{"s1", "p"}, memberStrings(nested)) - assertKeptRaw(t, nested.Unmodeled, "openapi:anyOf", `[{"enum":["s1","s2","s3","s4","s5"]},{"anyOf":[{"enum":["p","q"]},{"enum":["s1"]}]}]`) + assert.Empty(t, nested.Unmodeled, "the union says nothing, so nothing is kept") - shared, ok := typeByName(doc, "Shared").(*ir.Union) - require.True(t, ok, "a set outside what the union admits leaves the union the position's") - assert.Len(t, shared.Variants, 2) + shared, ok := typeByName(doc, "Shared").(*ir.Enum) + require.True(t, ok, "the members the set and the union share are the position") + assert.Equal(t, []string{"b"}, memberStrings(shared)) assertKeptRaw(t, shared.Unmodeled, "openapi:enum", `["b","x"]`) + assert.NotContains(t, shared.Unmodeled, "openapi:anyOf", "the node holds the union whole") - many, ok := typeByName(doc, "Many").(*ir.Union) - require.True(t, ok, "the ten branches are the union the position is") - assert.Len(t, many.Variants, 10) + many, ok := typeByName(doc, "Many").(*ir.Enum) + require.True(t, ok, "the one branch the set shares a member with gives the position") + assert.Equal(t, []string{"v3"}, memberStrings(many)) assertKeptRaw(t, many.Unmodeled, "openapi:enum", `["v3","zz"]`) + assert.Contains(t, many.Unmodeled, "openapi:oneOf", "the union is kept once") + var dead []string + for _, diagnostic := range diags { + if diagnostic.Code == diag.UnsatisfiableSchema { + dead = append(dead, string(diagnostic.Provenance.Pointer)+": "+diagnostic.Message) + } + } + require.Len(t, dead, 1, "the dead branches are named once") + assert.Contains(t, dead[0], "/components/schemas/Many/allOf/0/oneOf: 9 of the 10 branches") assertNoErrorDiags(t, diags) } diff --git a/compilers/openapi/e2e/const_union_test.go b/compilers/openapi/e2e/const_union_test.go index 30a6e132b..b15423c61 100644 --- a/compilers/openapi/e2e/const_union_test.go +++ b/compilers/openapi/e2e/const_union_test.go @@ -7,8 +7,6 @@ package e2e_test import ( - "maps" - "slices" "strings" "testing" @@ -77,38 +75,42 @@ func TestStringConstUnion_NormalizesToItsEnumSpelling(t *testing.T) { } } -// TestStringConstUnion_ABoundBesideTheSetKeepsTheUnion pins a bound written -// beside a union of string consts: the Union holds it, which an Enum has no -// field for, so pass.ConstUnions leaves the union, while the enum spelling's -// Enum keeps the bound verbatim. Neither carrier holds it, each leaving it to -// the node it names (docs/compilers/openapi.md#string-const-union, GitHub -// #1924, #1988). -func TestStringConstUnion_ABoundBesideTheSetKeepsTheUnion(t *testing.T) { +// TestStringConstUnion_ABoundBesideTheSetFoldsIntoTheEnum pins a bound written +// beside a union of string consts: the union is one value-set conjunct with +// the bound, so the compiled node is the Enum of the consts the bound admits, +// holding the bound in its Constraints, as the enum spelling's Enum holds it, +// and the union whole, keeping nothing, which pass.ConstUnions leaves as it +// is. Neither carrier holds the bound, each leaving it to the node it +// names (docs/compilers/openapi.md#string-const-union, GitHub #1924, #1988). +func TestStringConstUnion_ABoundBesideTheSetFoldsIntoTheEnum(t *testing.T) { t.Parallel() doc := compileComponentSpec(t, openapitest.ComponentSpec(` - Union: {oneOf: [{const: a}, {const: bb}], maxLength: 1} - Enum: {type: string, enum: [a, bb], maxLength: 1} + Union: {oneOf: [{const: a}, {const: b}], maxLength: 1} + Enum: {type: string, enum: [a, b], maxLength: 1} H: type: object properties: - u: {oneOf: [{const: a}, {const: bb}], maxLength: 1} - e: {type: string, enum: [a, bb], maxLength: 1} + u: {oneOf: [{const: a}, {const: b}], maxLength: 1} + e: {type: string, enum: [a, b], maxLength: 1} `)) got, diags := pass.ConstUnions{}.Run(t.Context(), doc) require.Empty(t, diags) - want := &ir.Constraints{MaxLength: new(int64(1))} for _, id := range []ir.TypeID{componentID("Union"), "type/anonymous/components/schemas/H/properties/u"} { - union, ok := got.Types[id].(*ir.Union) - require.True(t, ok, "%s stays a union, got %T", id, got.Types[id]) - assert.Same(t, doc.Types[id], got.Types[id], id) - assert.Equal(t, want, union.Constraints, id) - assert.Empty(t, union.Unmodeled, id) + enum, ok := doc.Types[id].(*ir.Enum) + require.True(t, ok, "%s compiles to an enum, got %T", id, doc.Types[id]) + assert.Same(t, enum, got.Types[id], "%s: the pass leaves it", id) + assert.Equal(t, ir.PrimitiveString, enum.ValueType, id) + require.Len(t, enum.Members, 2, id) + assert.Equal(t, []string{"a", "b"}, []string{enum.Members[0].Value.String, enum.Members[1].Value.String}, id) + assert.Equal(t, want, enum.Constraints, id) + assert.Empty(t, enum.Unmodeled, "%s holds the union whole", id) } for _, id := range []ir.TypeID{componentID("Enum"), "type/anonymous/components/schemas/H/properties/e"} { enum, ok := got.Types[id].(*ir.Enum) require.True(t, ok, "%s is an enum, got %T", id, got.Types[id]) - assert.Equal(t, []string{"openapi:maxLength"}, slices.Sorted(maps.Keys(enum.Unmodeled)), id) + assert.Equal(t, want, enum.Constraints, id) + assert.Empty(t, enum.Unmodeled, id) } model, ok := typeByName(got, "H").(*ir.Model) require.True(t, ok) diff --git a/compilers/openapi/e2e/constraints_test.go b/compilers/openapi/e2e/constraints_test.go index 9a43b268c..c37e3905e 100644 --- a/compilers/openapi/e2e/constraints_test.go +++ b/compilers/openapi/e2e/constraints_test.go @@ -81,7 +81,7 @@ func TestCompile_ANumericFieldIsReadPastARationalsRange(t *testing.T) { }{ {"an integer length past a rational", "{type: string, maxLength: 1e1000001}}}", nil, ""}, {"an integer length past what a BigVal holds", "{type: string, maxLength: 1e1000000000000000000}}}", - []string{"openapi/unpreservable-construct"}, "/schemas/N"}, + []string{"openapi/unpreservable-construct"}, "/schemas/N/maxLength"}, {"a negative step past a rational", "{type: number, multipleOf: -1e1000001}}}", []string{mismatch}, "/multipleOf"}, {"a bound past a binary float", "{type: number, minimum: 1e2000000000}}}", nil, ""}, {"a bound past what a BigVal holds", "{type: number, minimum: 1e1000000000000000000}}}", []string{invalid}, "/schemas/N/minimum"}, diff --git a/compilers/openapi/e2e/content_encoding_text_test.go b/compilers/openapi/e2e/content_encoding_text_test.go new file mode 100644 index 000000000..442602802 --- /dev/null +++ b/compilers/openapi/e2e/content_encoding_text_test.go @@ -0,0 +1,173 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// unhomedConstruct is the code of an info reporting a keyword kept verbatim +// because its position has no field for it. +const unhomedConstruct = "openapi/unhomed-construct" + +// formatsBesideAnEncoding are the string formats a contentEncoding of another +// name passes over: those read from the text, each selecting a primitive of +// its own on a bare string, which beside the encoding names the text inside it +// rather than the decoded bytes, and iban, which names an encoding alone. +var formatsBesideAnEncoding = []string{ + "date-time", "date-time-local", "date", "time-local", "duration", "uuid", "uri", + "http-date", "unixtime", "int64", "decimal", "iban", +} + +// TestContentEncoding_AFormatReadFromTheTextIsKeptAndTheBaseStaysString holds +// GitHub #1908's reproduction to one reading for every format read from the +// text: beside a contentEncoding the base is string with no WireType, as +// contentEncoding alone lowers, the format kept verbatim under no_ir_home with +// one openapi/unhomed-construct info at it, at a component and at a property +// alike, a format naming an encoding alone as one read from the text. +func TestContentEncoding_AFormatReadFromTheTextIsKeptAndTheBaseStaysString(t *testing.T) { + t.Parallel() + for _, format := range formatsBesideAnEncoding { + t.Run(format, func(t *testing.T) { + t.Parallel() + schema := "{type: string, format: " + format + ", contentEncoding: base64}" + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", + "C: "+schema, "H: {type: object, properties: {p: "+schema+"}}")) + for _, at := range []struct{ id, pointer string }{ + {string(componentID("C")), "/components/schemas/C"}, + {"type/anonymous/components/schemas/H/properties/p", "/components/schemas/H/properties/p"}, + } { + scalar, ok := kindNode(t, doc, ir.TypeID(at.id)).(*ir.Scalar) + require.True(t, ok, "%s is a scalar", at.id) + require.NotNil(t, scalar.Base, at.id) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), scalar.Base.Target, "%s: the base is the text", at.id) + assert.Equal(t, &ir.Encoding{Name: "base64"}, scalar.Encoding, "%s: contentEncoding names the encoding, with no WireType", at.id) + entry, kept := scalar.Unmodeled["openapi:format"] + require.True(t, kept, "%s keeps the format", at.id) + assert.Equal(t, ir.ReasonNoIRHome, entry.Reason, at.id) + assert.JSONEq(t, `"`+format+`"`, string(entry.Value), at.id) + assert.Equal(t, []string{unhomedConstruct}, infoCodesAt(diags, at.pointer+"/format"), "%s: one info for the kept format", at.id) + } + requireErrorsAndWarnings(t, diags, nil) + }) + } +} + +// TestContentEncoding_ABytesFormatKeepsBytes holds the other half of the +// reading: a format whose base is bytes keeps it beside a contentEncoding, and +// so does an integer, which takes no content vocabulary, keep its format's +// primitive. A bytes format beside an encoding of another name is kept as +// every passed-over format is. +func TestContentEncoding_ABytesFormatKeepsBytes(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", + "Byte: {type: string, format: byte, contentEncoding: base64}", + "Bin: {type: string, format: binary, contentEncoding: base64}", + "Url: {type: string, format: base64url, contentEncoding: base64url}", + "Stamp: {type: integer, format: unixtime, contentEncoding: base64}", + "Other: {type: string, format: byte, contentEncoding: base64url}", + )) + requireErrorsAndWarnings(t, diags, nil) + for name, base := range map[string]ir.PrimitiveKind{ + "Byte": ir.PrimitiveBytes, "Bin": ir.PrimitiveBytes, "Url": ir.PrimitiveBytes, "Stamp": ir.PrimitiveDatetimeOffset, + } { + scalar := requireComponentScalar(t, doc, name, ir.PrimitiveTypeID(base)) + assert.NotContains(t, scalar.Unmodeled, "openapi:format", name) + } + other := requireComponentScalar(t, doc, "Other", ir.PrimitiveTypeID(ir.PrimitiveBytes)) + assert.Equal(t, ir.ReasonNoIRHome, other.Unmodeled["openapi:format"].Reason) + assert.Equal(t, []string{unhomedConstruct}, infoCodesAt(diags, "/components/schemas/Other/format")) +} + +// TestContentEncoding_BesideAReferenceToATextReadScalarLowersAsItsFlatTwin +// holds the content vocabulary written beside a $ref to a scalar rooted at a +// primitive read from the text: the position lowers as its flat twin does, +// string under the encoding, and the reference is kept as a beaten $ref with +// one info, at the position where it is written beside the keyword or at the +// entry writing it, in either order of the components. +// +// It turns on the reading of the content vocabulary beside a $ref (over a +// string referent, a Scalar over the reference carrying the Encoding), which +// lands with the keyword-scope decisions. +func TestContentEncoding_BesideAReferenceToATextReadScalarLowersAsItsFlatTwin(t *testing.T) { + t.Parallel() + schemas := []string{ + "T: {type: string, format: date-time}", + "Beside: {$ref: '#/components/schemas/T', contentEncoding: base64}", + "Entry: {allOf: [{$ref: '#/components/schemas/T'}], contentEncoding: base64}", + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + requireErrorsAndWarnings(t, diags, nil) + for name, refAt := range map[string]string{ + "Beside": "/components/schemas/Beside", "Entry": "/components/schemas/Entry/allOf/0", + } { + scalar := requireComponentScalar(t, doc, name, ir.PrimitiveTypeID(ir.PrimitiveString)) + assert.Equal(t, &ir.Encoding{Name: "base64"}, scalar.Encoding, name) + assert.Equal(t, degradedKept("openapi:$ref"), keptOn(scalar), "%s keeps the beaten $ref alone", name) + assert.Equal(t, []string{diag.DegradedConstruct}, infoCodesAt(diags, refAt), "%s: one info for the kept $ref", name) + } + }) +} + +// infoCodesAt returns the code of every info at the pointer, sorted. +func infoCodesAt(diags []ir.Diagnostic, pointer string) []string { + var out []string + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityInfo && string(diagnostic.Provenance.Pointer) == pointer { + out = append(out, diagnostic.Code) + } + } + return out +} + +// TestContentEncoding_OnAnotherConjunctReadsTheFormatAsFlat holds a format and +// a contentEncoding written on different conjuncts of an allOf to the schema +// writing both flat, in every order and at every site: the string is the +// encoding's text, the format kept verbatim where it is written with its +// info, the bounds those of the text, and nothing else kept or reported. +func TestContentEncoding_OnAnotherConjunctReadsTheFormatAsFlat(t *testing.T) { + t.Parallel() + assertLowersAsFlat(t, []flatTwin{ + {"a format read from the text", "{type: string, format: date-time, contentEncoding: base64}", onlyDialect, []string{ + "{allOf: [{type: string, format: date-time}, {contentEncoding: base64}]}", + "{allOf: [{contentEncoding: base64}, {type: string, format: date-time}]}", + "{allOf: [{type: string, format: date-time}], contentEncoding: base64}", + "{allOf: [{type: string, contentEncoding: base64}, {format: date-time}]}", + }}, + {"a format naming an encoding", "{type: string, format: x-fmt, contentEncoding: base64}", onlyDialect, []string{ + "{allOf: [{type: string, format: x-fmt}, {contentEncoding: base64}]}", + "{allOf: [{type: string, contentEncoding: base64}, {format: x-fmt}]}", + }}, + {"a number as text and its bounds", "{type: string, format: int64, contentEncoding: base64, maxLength: 3}", onlyDialect, []string{ + "{allOf: [{type: string, format: int64, maxLength: 3}, {contentEncoding: base64}]}", + "{allOf: [{type: string, format: int64, maxLength: 3}], contentEncoding: base64}", + }}, + {"a type list's text variant", "{type: [string, boolean], format: int64, contentEncoding: base64, maxLength: 3}", onlyDialect, []string{ + "{allOf: [{type: [string, boolean], format: int64, maxLength: 3}, {contentEncoding: base64}]}", + }}, + }, reachSites()) +} + +// TestContentEncoding_SplitAcrossConjunctsNamingOneTypeLowersAsFlat holds the +// content vocabulary split across conjuncts that each write the same type to +// the schema writing it flat, at every site and in either order: no conjunct +// is the one the position lowers from, the vocabulary reaches any conjunct, +// and the type each writes the string node restates, so it is neither kept +// nor reported. +func TestContentEncoding_SplitAcrossConjunctsNamingOneTypeLowersAsFlat(t *testing.T) { + t.Parallel() + assertLowersAsFlat(t, []flatTwin{ + {"the vocabulary split", "{type: string, contentEncoding: base64, contentMediaType: text/plain}", onlyDialect, []string{ + "{allOf: [{type: string, contentEncoding: base64}, {type: string, contentMediaType: text/plain}]}", + "{allOf: [{type: string, contentMediaType: text/plain}, {type: string, contentEncoding: base64}]}", + }}, + }, reachSites()) +} diff --git a/compilers/openapi/e2e/core_scalars_test.go b/compilers/openapi/e2e/core_scalars_test.go index 4f8ef6517..8975065f0 100644 --- a/compilers/openapi/e2e/core_scalars_test.go +++ b/compilers/openapi/e2e/core_scalars_test.go @@ -93,7 +93,8 @@ func TestCompile_ADiscriminatorMappingKeepsItsNumberLikeKeys(t *testing.T) { require.NotNil(t, doc) assert.Empty(t, diags) - assert.True(t, containsJSON(t, doc, `"mapping":{"01":"type/openapi/components/schemas/A","02":"type/openapi/components/schemas/B"}`)) + assert.True(t, containsJSON(t, doc, `"mapping":{"01":"type/openapi/components/schemas/A","02":"type/openapi/components/schemas/B",`+ + `"P":"type/openapi/components/schemas/P"}`), "the keys kept as written, beside the base's own name") } // TestCompile_ACoreScalarReadsTheSameWrittenQuotedOrAsItsTwin holds each diff --git a/compilers/openapi/e2e/count_report_once_test.go b/compilers/openapi/e2e/count_report_once_test.go new file mode 100644 index 000000000..e7c3a2c1a --- /dev/null +++ b/compilers/openapi/e2e/count_report_once_test.go @@ -0,0 +1,60 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// TestCount_AKeptOrRefusedCountIsReportedOnce holds GitHub #1895's +// reproduction: a count no Constraints field states is kept or refused once, +// with one report naming it, whichever reader attempts it first. N, a number +// carried as text, keeps a count past 64 bits once under no_ir_home with its +// info; N2, the same with a count past what a BigVal holds, and S, such a count +// on a node its position owns, each draw the one unpreservable error, at the +// count, and keep nothing. +func TestCount_AKeptOrRefusedCountIsReportedOnce(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name, schema string + kept ir.UnmodeledReason + severity ir.Severity + code string + }{ + {"N", "{type: string, format: int64, maxLength: 100000000000000000000000}", ir.ReasonNoIRHome, ir.SeverityInfo, ""}, + {"N2", "{type: string, format: int64, maxLength: 1e1000000000000000000}", "", ir.SeverityError, diag.UnpreservableConstruct}, + {"S", "{type: string, format: x-f, maxLength: 1e1000000000000000000}", "", ir.SeverityError, diag.UnpreservableConstruct}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + doc, diags := compileAnnotationSpec(t, "count", admissionSpec("3.1.0", "", tc.name+": "+tc.schema)) + var reports []ir.Diagnostic + for _, diagnostic := range diags { + if strings.Contains(diagnostic.Message, "maxLength") { + reports = append(reports, diagnostic) + } + } + if !assert.Len(t, reports, 1, "one report names the count: %v", reports) { + return + } + assert.Equal(t, tc.severity, reports[0].Severity) + if tc.code != "" { + assert.Equal(t, tc.code, reports[0].Code) + assert.Equal(t, "/components/schemas/"+tc.name+"/maxLength", string(reports[0].Provenance.Pointer), "refused at the count") + } + kept := keptUnderKey(doc, "openapi:maxLength") + if tc.kept == "" { + assert.Empty(t, kept, "a refused count is kept nowhere") + return + } + assert.Equal(t, []ir.UnmodeledReason{tc.kept}, kept, "the count is kept once, under the reason its report names") + }) + } +} diff --git a/compilers/openapi/e2e/cycle_flat_differential_test.go b/compilers/openapi/e2e/cycle_flat_differential_test.go new file mode 100644 index 000000000..efc76dee0 --- /dev/null +++ b/compilers/openapi/e2e/cycle_flat_differential_test.go @@ -0,0 +1,188 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "maps" + "regexp" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// foldOutcome is what one fold of id's declarations settles, spelled so a +// cycle's and a model's fold compare: the member's type, the keys it keeps +// verbatim, and each report at a declaration, by where it sits. +type foldOutcome struct { + Type ir.TypeRef + Kept []string + Reports map[string]string +} + +// mintedID matches a node a fold mints, which a cycle and a model key apart. +var mintedID = regexp.MustCompile(`type/composed/[^\s;,()"]*`) + +// holdingModels matches the models a report said once names after the field +// it opens with, which a cycle's members and one model name apart. +var holdingModels = regexp.MustCompile(`^(field "[^"]*") of .*?(: )`) + +// cycleDeclarationNames is the name of each of n ring members, written in that +// order. +func cycleDeclarationNames(n int) []string { + names := make([]string, n) + for i := range n { + names[i] = string(rune('A' + i)) + } + return names +} + +// asFlatDeclaration rewrites text, which names the declaration a ring member +// writes at /components/schemas//properties/id, as naming the one M's +// allOf entry at the member's place writes, and names every node a fold mints +// alike. +func asFlatDeclaration(text string, names []string) string { + for i, name := range names { + text = strings.ReplaceAll(text, "/components/schemas/"+name+"/properties/id", + fmt.Sprintf("/components/schemas/M/allOf/%d/properties/id", i)) + } + return mintedID.ReplaceAllString(text, "type/composed/*") +} + +// outcomeOf reads the outcome of model's fold of id from doc and diags, each +// place and name spelled by spell, the models a report names left out. +func outcomeOf(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, model string, spell func(string) string) foldOutcome { + t.Helper() + declares, isModel := typeByName(doc, model).(*ir.Model) + require.True(t, isModel, "%s is a model", model) + property, ok := propertyByWire(declares, "id") + require.True(t, ok, "%s declares id", model) + outcome := foldOutcome{Type: property.Type, Reports: map[string]string{}} + outcome.Type.Target = ir.TypeID(spell(string(outcome.Type.Target))) + for _, key := range slices.Sorted(maps.Keys(property.Unmodeled)) { + outcome.Kept = append(outcome.Kept, spell(key)) + } + for _, diagnostic := range diags { + at := spell(string(diagnostic.Provenance.Pointer)) + if !strings.HasPrefix(at, "/components/schemas/M/allOf/") { + continue + } + message := holdingModels.ReplaceAllString(diagnostic.Message, "$1$2") + assert.NotContains(t, outcome.Reports, at, "one report at %s", at) + outcome.Reports[at] = diagnostic.Code + ": " + spell(message) + } + return outcome +} + +// assertCycleFoldsFlat holds a ring of declarations, each a schema id is +// redeclared as and written in the order given, to M composing an allOf entry +// for each in that order: in every order the ring is written in, each member +// settles as M's one flat fold does. +func assertCycleFoldsFlat(t *testing.T, declarations []string) { + t.Helper() + names := cycleDeclarationNames(len(declarations)) + var flat strings.Builder + flat.WriteString(" M:\n allOf:\n") + byName := make(map[string]string, len(names)) + for i, name := range names { + flat.WriteString(" - {properties: {id: " + declarations[i] + "}}\n") + byName[name] = declarations[i] + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", flat.String())) + want := outcomeOf(t, doc, diags, "M", func(text string) string { return mintedID.ReplaceAllString(text, "type/composed/*") }) + schemas := ringOf(byName) + for _, order := range everyOrder(len(schemas)) { + var written strings.Builder + for _, at := range order { + written.WriteString(schemas[at]) + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + for _, name := range names { + got := outcomeOf(t, doc, diags, name, func(text string) string { return asFlatDeclaration(text, names) }) + assert.Equal(t, want, got, "%q written %v: %s", declarations, order, name) + } + } +} + +// TestCompile_ACycleFoldsAsAFlatFoldOfItsDeclarations holds a cycle whose +// declarations of a member fit one fold to the flat fold of the same +// declarations a model's allOf writes: the member's type, what it keeps +// verbatim and each report, in every order the cycle is written in. The rings +// are written by hand, where a later declaration is chosen over an earlier one, +// where the field meets one a later one passed over, and where a member +// restates the declaration of the member it composes, and every set of three, +// and of four, the pools below hold, and every three of one pool repeating one. +func TestCompile_ACycleFoldsAsAFlatFoldOfItsDeclarations(t *testing.T) { + t.Parallel() + rings := [][]string{ + {"{type: string}", "{type: integer}", "{type: boolean}", "{type: number}"}, + {"{type: integer}", "{type: number}", "{type: string}"}, + {"{type: object, properties: {a: {type: string}}}", "{type: string}", "{type: object, properties: {c: {type: string}}}"}, + {"{type: string, pattern: '^a'}", "{type: string, pattern: '^b'}", "{type: string, pattern: '^c'}"}, + {"{type: string, description: a}", "{type: string, description: b}", "{type: string, description: c}"}, + {"{type: integer}", "{type: string, enum: [b, c]}", "{type: string, enum: [c, d]}"}, + {"{type: integer}", "{type: integer}", "{type: string}"}, + {"{type: integer}", "{type: string}", "{type: integer}", "{type: string}"}, + {"{type: string}", "{type: integer}", "{type: integer}", "{type: integer}"}, + } + threes := []string{ + "{type: string}", "{type: integer}", "{type: number}", "{type: boolean}", "{type: string, maxLength: 3}", + "{type: string, pattern: '^a'}", "{type: string, enum: [a, b]}", "{type: object, properties: {a: {type: string}}}", + } + fours := []string{"{type: string}", "{type: integer}", "{type: number}", "{type: boolean}", "{type: string, minLength: 2}", "{type: integer, maximum: 5}"} + sets := slices.Concat(rings, subsetsOf(threes, 3), subsetsOf(fours, 4), repeatingOne(threes[:5], 3)) + for _, declarations := range sets { + t.Run(strings.Join(declarations, " "), func(t *testing.T) { + t.Parallel() + assertCycleFoldsFlat(t, declarations) + }) + } +} + +// subsetsOf returns every subset of pool of size items, each in pool's order. +func subsetsOf(pool []string, size int) [][]string { + if size == 0 { + return [][]string{{}} + } + var out [][]string + for i := range len(pool) - size + 1 { + for _, rest := range subsetsOf(pool[i+1:], size-1) { + out = append(out, slices.Concat([]string{pool[i]}, rest)) + } + } + return out +} + +// repeatingOne returns every multiset of size items of pool holding one item +// more than once, each in pool's order. +func repeatingOne(pool []string, size int) [][]string { + var out [][]string + for _, multiset := range multisetsOf(pool, size) { + if len(slices.Compact(slices.Clone(multiset))) < size { + out = append(out, multiset) + } + } + return out +} + +// multisetsOf returns every multiset of size items of pool, each in pool's +// order. +func multisetsOf(pool []string, size int) [][]string { + if size == 0 { + return [][]string{{}} + } + var out [][]string + for i := range pool { + for _, rest := range multisetsOf(pool[i:], size-1) { + out = append(out, slices.Concat([]string{pool[i]}, rest)) + } + } + return out +} diff --git a/compilers/openapi/e2e/cycle_fold_order_test.go b/compilers/openapi/e2e/cycle_fold_order_test.go new file mode 100644 index 000000000..39ba910eb --- /dev/null +++ b/compilers/openapi/e2e/cycle_fold_order_test.go @@ -0,0 +1,335 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/v2" + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/internal/harness" + "github.com/dexpace/morphic/ir" +) + +// TestCompile_AThreeModelCycleIntersectsItsEnumsInEveryOrder holds a ring of +// three models each redeclaring id as an enum, written in each of the six +// orders. The cycle's fold mints at the least member's key, so each order +// compiles with no error, every model takes the enum all three intersect to, +// every harness oracle passes, the order-invariance one asking, and the six +// documents are one. +func TestCompile_AThreeModelCycleIntersectsItsEnumsInEveryOrder(t *testing.T) { + t.Parallel() + schemas := []string{ + " A: {allOf: [{$ref: '#/components/schemas/B'}], properties: {id: {type: string, enum: [a, b, c, d]}}}\n", + " B: {allOf: [{$ref: '#/components/schemas/C'}], properties: {id: {type: string, enum: [b, c, d, e]}}}\n", + " C: {allOf: [{$ref: '#/components/schemas/A'}], properties: {id: {type: string, enum: [c, d, e, f]}}}\n", + } + minted := ir.TypeID("type/composed/components/schemas/A/allOf/properties/id") + orders := [][]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} + types := make([]string, 0, len(orders)) + for _, order := range orders { + spec := openapitest.ComponentSpecVer("3.1.0", schemas[order[0]]+schemas[order[1]]+schemas[order[2]]) + + result := harness.Check(t.Context(), "spec.yaml", []byte(spec)) + require.Equal(t, harness.OutcomeOK, result.Outcome, "%v: %s", order, result.Detail) + at := slices.IndexFunc(result.Verdicts, func(verdict harness.Verdict) bool { return verdict.Oracle == harness.OracleOrder }) + require.GreaterOrEqual(t, at, 0, "%v", order) + assert.True(t, result.Verdicts[at].Asked(), "%v: the order oracle asks: %s", order, result.Verdicts[at].Declined) + + doc, diags := parseFull(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + assert.NotContains(t, codesOf(diags), compile.RegistryRefused, "%v", order) + for _, name := range []string{"A", "B", "C"} { + model, isModel := typeByName(doc, name).(*ir.Model) + require.True(t, isModel, "%v: %s", order, name) + require.Len(t, model.Properties, 1, "%v: %s", order, name) + assert.Equal(t, minted, model.Properties[0].Type.Target, "%v: %s", order, name) + } + enum, isEnum := doc.Types[minted].(*ir.Enum) + require.True(t, isEnum, "%v: %s", order, minted) + values := make([]string, 0, len(enum.Members)) + for _, member := range enum.Members { + values = append(values, member.Value.String) + } + assert.Equal(t, []string{"c", "d"}, values, "%v", order) + raw, err := json.Marshal(doc.Types, json.Deterministic(true)) + require.NoError(t, err) + types = append(types, string(raw)) + } + assert.Len(t, slices.Compact(types), 1, "the six orders compile to one registry") +} + +// everyOrder returns every order of n items, each a permutation of 0 to n-1. +func everyOrder(n int) [][]int { + if n == 0 { + return [][]int{{}} + } + var out [][]int + for _, shorter := range everyOrder(n - 1) { + for at := range n { + order := slices.Insert(slices.Clone(shorter), at, n-1) + out = append(out, order) + } + } + return out +} + +// ringOf is a ring of the named components, each composing the next and +// redeclaring id as its own declaration, which is the name. +func ringOf(declarations map[string]string) []string { + names := slices.Sorted(maps.Keys(declarations)) + schemas := make([]string, len(names)) + for i, name := range names { + next := names[(i+1)%len(names)] + schemas[i] = " " + name + ": {allOf: [{$ref: '#/components/schemas/" + next + "'}], properties: {id: " + declarations[name] + "}}\n" + } + return schemas +} + +// TestCompile_ARingOfObjectsComposesEveryDeclarationInEveryOrder holds rings +// whose members each redeclare id as an object, written in every order: each +// order compiles with no error, every harness oracle passes, the +// order-invariance one asking, the documents are one, and the model at each +// key composes every member's declaration there, as written, at every depth. +func TestCompile_ARingOfObjectsComposesEveryDeclarationInEveryOrder(t *testing.T) { + t.Parallel() + object := func(name string) string { return "{type: object, properties: {" + name + ": {type: string}}}" } + minted := "type/composed/components/schemas/A/allOf/properties/id" + for name, tc := range map[string]struct { + declarations map[string]string + composes map[string][]string + }{ + "three objects": { + declarations: map[string]string{"A": object("a"), "B": object("b"), "C": object("c")}, + composes: map[string][]string{minted: {"A/properties/id", "B/properties/id", "C/properties/id"}}, + }, + "four objects": { + declarations: map[string]string{"A": object("a"), "B": object("b"), "C": object("c"), "D": object("d")}, + composes: map[string][]string{minted: {"A/properties/id", "B/properties/id", "C/properties/id", "D/properties/id"}}, + }, + "objects a level down": { + declarations: map[string]string{ + "A": "{type: object, properties: {sub: " + object("a") + "}}", "B": "{type: object, properties: {sub: " + object("b") + "}}", + "C": "{type: object, properties: {sub: " + object("c") + "}}", + }, + composes: map[string][]string{ + minted: {"A/properties/id", "B/properties/id", "C/properties/id"}, + minted + "/allOf/allOf/properties/sub": {"A/properties/id/properties/sub", "B/properties/id/properties/sub", "C/properties/id/properties/sub"}, + }, + }, + "objects listed": { + declarations: map[string]string{ + "A": "{type: array, items: " + object("a") + "}", "B": "{type: array, items: " + object("b") + "}", "C": "{type: array, items: " + object("c") + "}", + }, + composes: map[string][]string{minted + "/items": {"A/properties/id/items", "B/properties/id/items", "C/properties/id/items"}}, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + schemas := ringOf(tc.declarations) + var types []string + for _, order := range everyOrder(len(schemas)) { + var written strings.Builder + for _, at := range order { + written.WriteString(schemas[at]) + } + spec := openapitest.ComponentSpecVer("3.1.0", written.String()) + types = append(types, compiledRing(t, spec, order, tc.composes)) + } + assert.Len(t, slices.Compact(types), 1, "every order compiles to one registry") + }) + } +} + +// compiledRing compiles spec, a ring written in order, holds it to every +// harness oracle and to no error, holds each model composes names to the +// declarations it lists, and returns its registry encoded. +func compiledRing(t *testing.T, spec string, order []int, composes map[string][]string) string { + t.Helper() + result := harness.Check(t.Context(), "spec.yaml", []byte(spec)) + require.Equal(t, harness.OutcomeOK, result.Outcome, "%v: %s", order, result.Detail) + at := slices.IndexFunc(result.Verdicts, func(verdict harness.Verdict) bool { return verdict.Oracle == harness.OracleOrder }) + require.GreaterOrEqual(t, at, 0, "%v", order) + assert.True(t, result.Verdicts[at].Asked(), "%v: the order oracle asks: %s", order, result.Verdicts[at].Declined) + + doc, diags := parseFull(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + for id, parts := range composes { + model, isModel := doc.Types[ir.TypeID(id)].(*ir.Model) + require.True(t, isModel, "%v: %s is a model", order, id) + var got []string + for _, part := range ir.ComposedOf(model) { + got = append(got, strings.TrimPrefix(string(part), "type/anonymous/components/schemas/")) + } + assert.Equal(t, parts, got, "%v: %s composes every declaration, as written", order, id) + } + raw, err := json.Marshal(doc.Types, json.Deterministic(true)) + require.NoError(t, err) + return string(raw) +} + +// TestCompile_ARingKeepsEveryLosingDeclarationVerbatim holds rings whose +// members redeclare id as types no one value holds, scalars and objects among +// them, written in every order: each member's own declaration the fold does not +// carry is kept verbatim on every member's id and reported once, as a flat fold +// keeps and reports each it loses, and no report says a member's declaration +// stays declared on its model. A declaration the field intersects, as the +// integer intersects the number, is not passed over. +func TestCompile_ARingKeepsEveryLosingDeclarationVerbatim(t *testing.T) { + t.Parallel() + object := func(name string) string { return "{type: object, properties: {" + name + ": {type: string}}}" } + for name, tc := range map[string]struct { + declarations map[string]string + lost []string + }{ + "three kinds": {map[string]string{"A": "{type: string}", "B": "{type: integer}", "C": "{type: boolean}"}, []string{"A", "B"}}, + "four kinds": {map[string]string{"A": "{type: string}", "B": "{type: integer}", "C": "{type: boolean}", "D": "{type: number}"}, []string{"A", "C"}}, + "three with objects": {map[string]string{"A": object("a"), "B": "{type: string}", "C": object("c")}, []string{"A", "B"}}, + "four with objects": {map[string]string{"A": object("a"), "B": "{type: string}", "C": object("c"), "D": "{type: integer}"}, []string{"A", "B", "C"}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + schemas := ringOf(tc.declarations) + for _, order := range everyOrder(len(schemas)) { + var written strings.Builder + for _, at := range order { + written.WriteString(schemas[at]) + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + want := make([]string, len(tc.lost)) + for i, lost := range tc.lost { + want[i] = "/components/schemas/" + lost + "/properties/id" + } + for member := range tc.declarations { + model, isModel := typeByName(doc, member).(*ir.Model) + require.True(t, isModel, "%v: %s", order, member) + require.Len(t, model.Properties, 1, "%v: %s", order, member) + var kept []string + for key, entry := range model.Properties[0].Unmodeled { + assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason, "%v: %s keeps %s", order, member, key) + kept = append(kept, string(entry.Provenance.Pointer)) + } + slices.Sort(kept) + assert.Equal(t, want, kept, "%v: %s keeps every losing declaration verbatim", order, member) + } + for _, diagnostic := range diags { + assert.NotContains(t, diagnostic.Message, "stays declared on its model", "%v: %s", order, diagnostic.Code) + } + var reported []string + for _, diagnostic := range diags { + if diagnostic.Code == "openapi/conflicting-redeclaration" || diagnostic.Code == "openapi/degraded-construct" { + assert.Contains(t, diagnostic.Message, "; the second is kept verbatim under Unmodeled", "%v", order) + reported = append(reported, string(diagnostic.Provenance.Pointer)) + } + } + slices.Sort(reported) + assert.Equal(t, want, reported, "%v: one report at each losing declaration", order) + } + }) + } +} + +// TestCompile_ARingSaysEachLossAgainstWhatItsFieldKeeps holds rings each of +// whose later declarations are chosen over an earlier one, written in every +// order. Each losing declaration is reported once, where it is written, naming +// the declaration whose say the field keeps and that say, as a flat fold of the +// same declarations reports it: no report names a declaration a later one +// passed over. Where two enums intersect in a node the fold mints, the report +// names the last, whose type the field keeps. +func TestCompile_ARingSaysEachLossAgainstWhatItsFieldKeeps(t *testing.T) { + t.Parallel() + at := func(name string) string { return "/components/schemas/" + name + "/properties/id" } + disagree := func(detail, kept, lost string) string { + return ": " + at(kept) + " and " + at(lost) + " disagree: " + detail + "; chose what the first says; the second is kept " + + "verbatim under Unmodeled" + } + described := func(kept, lost string) string { + return ": " + at(kept) + " and " + at(lost) + " give its description differently; chose the one the first gives; the " + + "second is kept verbatim under Unmodeled" + } + for name, tc := range map[string]struct { + declarations map[string]string + want map[string]string + }{ + "three kinds": { + declarations: map[string]string{"A": "{type: string}", "B": "{type: integer}", "C": "{type: boolean}"}, + want: map[string]string{ + at("A"): disagree("incompatible types bool and string", "C", "A"), + at("B"): disagree("incompatible types bool and integer", "C", "B"), + }, + }, + "four kinds": { + declarations: map[string]string{ + "A": "{type: string}", "B": "{type: integer}", "C": "{type: boolean}", "D": "{type: array, items: {type: string}}", + }, + want: map[string]string{ + at("A"): disagree("incompatible types a list and string", "D", "A"), + at("B"): disagree("incompatible types a list and integer", "D", "B"), + at("C"): disagree("incompatible types a list and bool", "D", "C"), + }, + }, + "three kinds, two enums meeting": { + declarations: map[string]string{ + "A": "{type: integer}", "B": "{type: string, enum: [b, c]}", "C": "{type: string, enum: [c, d]}", + }, + want: map[string]string{ + at("A"): disagree("incompatible types an enum and integer", "C", "A"), + }, + }, + "three patterns": { + declarations: map[string]string{ + "A": "{type: string, pattern: '^a'}", "B": "{type: string, pattern: '^b'}", "C": "{type: string, pattern: '^c'}", + }, + want: map[string]string{ + at("A"): disagree(`conflicting pattern ("^c" and "^a")`, "C", "A"), + at("B"): disagree(`conflicting pattern ("^c" and "^b")`, "C", "B"), + }, + }, + "four descriptions": { + declarations: map[string]string{ + "A": "{type: string, description: a}", "B": "{type: string, description: b}", + "C": "{type: string, description: c}", "D": "{type: string, description: d}", + }, + want: map[string]string{at("A"): described("D", "A"), at("B"): described("D", "B"), at("C"): described("D", "C")}, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + schemas := ringOf(tc.declarations) + members := slices.Sorted(maps.Keys(tc.declarations)) + for i, member := range members { + members[i] = "/components/schemas/" + member + } + once := `field "id" of ` + strings.Join(members[:len(members)-1], ", ") + " and " + members[len(members)-1] + want := make(map[string]string, len(tc.want)) + for pointer, message := range tc.want { + want[pointer] = once + message + } + for _, order := range everyOrder(len(schemas)) { + var written strings.Builder + for _, at := range order { + written.WriteString(schemas[at]) + } + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + got := map[string]string{} + for _, diagnostic := range diags { + if diagnostic.Code == "openapi/conflicting-redeclaration" || diagnostic.Code == "openapi/degraded-construct" { + assert.NotContains(t, got, string(diagnostic.Provenance.Pointer), "%v: one report at each loss", order) + got[string(diagnostic.Provenance.Pointer)] = diagnostic.Message + } + } + assert.Equal(t, want, got, "%v", order) + } + }) + } +} diff --git a/compilers/openapi/e2e/cycles_test.go b/compilers/openapi/e2e/cycles_test.go index 6ef66832e..4abfde00f 100644 --- a/compilers/openapi/e2e/cycles_test.go +++ b/compilers/openapi/e2e/cycles_test.go @@ -215,8 +215,9 @@ func TestCompile_SchemaRefNamingNothingIsUnresolvedNotCyclic(t *testing.T) { // TestCompile_CycleIsReportedAtItsLeastMemberInEitherOrder pins where a loop is // reported: once per loop, at the loop's member with the least pointer, never // at a $ref that only leads into it, and wherever the members are declared -// (GitHub #912). A member of a loop lowers to any, and what only leads into -// one stays an alias to it. +// (GitHub #912). A member of a loop lowers to any, and what only leads into one +// stays an alias to it. An allOf of one $ref writing nothing else is a hop of +// the chain, as a bare $ref is. func TestCompile_CycleIsReportedAtItsLeastMemberInEitherOrder(t *testing.T) { t.Parallel() const head = "openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" @@ -241,6 +242,10 @@ func TestCompile_CycleIsReportedAtItsLeastMemberInEitherOrder(t *testing.T) { " B: {$ref: '#/components/schemas/C'}\n", " A: {$ref: '#/components/schemas/B'}\n", }, []string{"/components/schemas/A"}, []string{"A", "B", "C"}, "", ""}, + {"a loop of two allOf links", []string{ + " B: {allOf: [{$ref: '#/components/schemas/A'}]}\n", + " A: {allOf: [{$ref: '#/components/schemas/B'}]}\n", + }, []string{"/components/schemas/A"}, []string{"A", "B"}, "", ""}, } for _, tc := range tests { for _, reversed := range []bool{false, true} { @@ -275,16 +280,16 @@ func TestCompile_CycleIsReportedAtItsLeastMemberInEitherOrder(t *testing.T) { } } -// TestCompile_ABranchOnALoopIsReportedOnlyAsTheLoop pins the gates that keep an -// allOf entry or union branch on a loop the compiler reads from being reported -// twice: removing the gate in fillRefEntry, diagUnresolvedBranches or -// refTypeRef adds an unresolved-ref beside the cyclic-ref. Where load -// reports the loop at the branch, its least member, withoutRereported drops that -// error, so each gate, and fillRefEntry's two routes through a distributed -// union, has a row whose loop runs through L, which sorts first. A loop past -// the merge bound goes unread (#1570). A union beside structural +// TestCompile_ABranchOnALoopIsReportedOnlyAsTheLoop pins the gates keeping an +// allOf entry or union branch on a loop from a second report: removing the one +// in fillRefEntry, diagUnresolvedBranches or refTypeRef adds an unresolved-ref +// beside the cyclic-ref. Load reports the loop at its least member, so each +// gate, and fillRefEntry's two routes through a distributed union, has a row +// whose loop runs through L, which sorts first. A union beside structural // keywords reaches diagUnresolvedBranches only as case 2 of -// docs/compilers/openapi.md#union-beside-structure, which the why field checks. +// docs/compilers/openapi.md#union-beside-structure, which why checks. A loop +// admits every kind, so an entry on one beside a body keeps its $ref, with the +// info saying so. func TestCompile_ABranchOnALoopIsReportedOnlyAsTheLoop(t *testing.T) { t.Parallel() const namesNoReferent = "a branch's $ref names no referent this compilation resolves" @@ -368,6 +373,7 @@ func TestCompile_ABranchOnALoopIsReportedOnlyAsTheLoop(t *testing.T) { B: {type: object, properties: {b: {type: string}}} `, "", []report{ {diag.CyclicRef, ir.SeverityError, "/components/schemas/L"}, + {diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Y/allOf/0"}, {diag.CompositionLowering, ir.SeverityInfo, "/components/schemas/Y"}, }}, {"allOf entry beside a distributed union on a sibling branch on a loop through a component", ` Y: @@ -384,6 +390,7 @@ func TestCompile_ABranchOnALoopIsReportedOnlyAsTheLoop(t *testing.T) { B: {type: object, properties: {b: {type: string}}} `, "", []report{ {diag.CyclicRef, ir.SeverityError, "/components/schemas/L"}, + {diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Y/allOf/0"}, {diag.CompositionLowering, ir.SeverityInfo, "/components/schemas/Y"}, }}, {"union branch with no keyword beside it on a loop through a component", ` Z: @@ -669,14 +676,6 @@ components: info: {title: t, version: '1'} paths: {} x-foo: {a: {$ref: '#/x-foo/b'}, b: {$ref: '#/x-foo/a'}} -`}, - {"allof-wrapped-cycle", `openapi: 3.1.0 -info: {title: t, version: '1'} -paths: {} -components: - schemas: - A: {allOf: [{$ref: '#/components/schemas/B'}]} - B: {allOf: [{$ref: '#/components/schemas/A'}]} `}, // The four cases below are the negative controls for GitHub #26: each uses // the same alias/merge/contentSchema shapes as the crashing reproducers, but @@ -747,7 +746,7 @@ func scanIndex(t *testing.T, src string) sourcetreestats.Measurements { } // TestCompile_SchemaEmptyPointerSegmentIsUnresolved pins where reading the -// empty token changes a verdict. Reading '/A/' as stopping at A made this shape +// empty token changes an answer. Reading '/A/' as stopping at A made this shape // a cycle. The token names the key "" of A, which A does not hold, so the // reference is reported unresolved where it is written and no cycle is. func TestCompile_SchemaEmptyPointerSegmentIsUnresolved(t *testing.T) { diff --git a/compilers/openapi/e2e/dead_branch_null_test.go b/compilers/openapi/e2e/dead_branch_null_test.go index 59af3b612..e327efe28 100644 --- a/compilers/openapi/e2e/dead_branch_null_test.go +++ b/compilers/openapi/e2e/dead_branch_null_test.go @@ -131,7 +131,7 @@ func requireDeadAsTheNullsSay(t *testing.T, doc *ir.Document, diags []ir.Diagnos assert.Equal(t, dead, union.Unmodeled["openapi:"+at].Value != nil, "%s: the branch over T is dead", name) var warning []string for _, diagnostic := range diags { - if diagnostic.Code == diag.DegradedConstruct && diagnostic.Severity == ir.SeverityWarning && + if diagnostic.Code == diag.UnsatisfiableSchema && diagnostic.Severity == ir.SeverityWarning && string(diagnostic.Provenance.Pointer) == "/components/schemas/"+name { warning = append(warning, diagnostic.Message) } @@ -149,19 +149,18 @@ func requireDeadAsTheNullsSay(t *testing.T, doc *ir.Document, diags []ir.Diagnos } } -// TestCompile_ABodyWhoseNullTheWalkCannotFinishMayAdmitIt holds the bound of -// the null reading beside a union (docs/compilers/openapi.md#union-beside-structure): -// a body whose allOf chain the walk reads to its end keeps out the null its -// end keeps out, so a branch over T, which admits null, is dead; one the walk -// cannot finish may admit null, so the branch lives; and one whose own type -// keeps null out does so however deep its chain. -func TestCompile_ABodyWhoseNullTheWalkCannotFinishMayAdmitIt(t *testing.T) { +// TestCompile_ABodyKeepsOutTheNullItsChainKeepsOutAtAnyDepth holds the null +// reading beside a union to the end of a body's allOf chain, which no depth +// cuts (docs/compilers/openapi.md#union-beside-structure): a body whose chain +// ends on an object keeps null out, so a branch over T, which admits null, is +// dead at every length; and one whose own type keeps null out does so too. +func TestCompile_ABodyKeepsOutTheNullItsChainKeepsOutAtAnyDepth(t *testing.T) { t.Parallel() for _, tc := range []struct { own string depth int dead bool - }{{"", 127, true}, {"", 128, false}, {"", 300, false}, {"type: object, ", 300, true}} { + }{{"", 127, true}, {"", 128, true}, {"", 300, true}, {"type: object, ", 300, true}} { t.Run(fmt.Sprintf("%sdepth %d", tc.own, tc.depth), func(t *testing.T) { t.Parallel() schemas := []string{"S0: {type: string}", "NUL: {type: 'null'}", "O: {type: object, properties: {o: {type: string}}}", @@ -180,7 +179,7 @@ func TestCompile_ABodyWhoseNullTheWalkCannotFinishMayAdmitIt(t *testing.T) { union, ok := typeByName(doc, "P").(*ir.Union) require.True(t, ok, "%T", typeByName(doc, "P")) assert.Equal(t, tc.dead, union.Unmodeled["openapi:anyOf/0"].Value != nil, "depth %d: the branch over T is dead", tc.depth) - assert.Equal(t, tc.dead, countFindings(diags, diag.DegradedConstruct, ir.SeverityWarning, "/components/schemas/P") == 1) + assert.Equal(t, tc.dead, countFindings(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/P") == 1) }) } } diff --git a/compilers/openapi/e2e/declaration_answers_test.go b/compilers/openapi/e2e/declaration_answers_test.go index 3dedc7c91..2641cc67b 100644 --- a/compilers/openapi/e2e/declaration_answers_test.go +++ b/compilers/openapi/e2e/declaration_answers_test.go @@ -26,8 +26,8 @@ const ( "W: {$ref: '" + trustedPet + "'}\n" ) -// trusted starts the server that stands for trusted.example: it serves docs, -// and the reader that routes the host's URLs to it. +// trusted starts the server that serves as trusted.example: it serves docs, and +// the reader that routes the host's URLs to it. func trusted(t *testing.T, docs map[string]string) (*servedDocs, *recordingReader) { t.Helper() srv := serveDocs(t, docs) diff --git a/compilers/openapi/e2e/doc_test.go b/compilers/openapi/e2e/doc_test.go index ef36f52de..03921581e 100644 --- a/compilers/openapi/e2e/doc_test.go +++ b/compilers/openapi/e2e/doc_test.go @@ -9,5 +9,5 @@ // // It is a package of its own because coverage counts only a package's own // tests. Nothing here is covered by them, so the code they reach still needs -// the unit tests beside it, and a case here never stands in for one. +// the unit tests beside it, and a case here never takes the place of one. package e2e_test diff --git a/compilers/openapi/e2e/document_dialect_test.go b/compilers/openapi/e2e/document_dialect_test.go index c6b607035..695c6ccc1 100644 --- a/compilers/openapi/e2e/document_dialect_test.go +++ b/compilers/openapi/e2e/document_dialect_test.go @@ -299,26 +299,28 @@ func TestDocumentDialect_ASchemaIsReadInItsOwnDocumentsDialect(t *testing.T) { // allOf in a 3.1 document lowers to one node whether or not a 3.0 document // also names it. Its decision is remembered once a run, so it is read in its // own document's dialect, never in that of the document whose reader asks -// first, where `nullable: true` would admit the null the other conjunct is. +// first. In its own, the null the nullable-inference policy reads on +// `nullable: true` is read as a dialect's nullable reads it, so the allOf +// lowers as its twin admitting that null in a type list does. func TestDocumentDialect_AnAllOfIsDecidedInItsOwnDocumentsDialect(t *testing.T) { t.Parallel() - const other = "openapi: 3.1.0\ninfo: {title: T, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + - " Holder: {type: object, properties: {h: {$ref: '#/components/schemas/W'}}}\n" + - " W: {allOf: [{type: string, nullable: true}, {type: 'null'}]}\n" + const head = "openapi: 3.1.0\ninfo: {title: T, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + + " Holder: {type: object, properties: {h: {$ref: '#/components/schemas/W'}}}\n" const root = "openapi: 3.0.3\ninfo: {title: T, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + " B: {type: object, properties: {y: {$ref: './other.yaml#/components/schemas/Holder'}}}\n" - w := func(t *testing.T, more string) ir.TypeDef { + w := func(t *testing.T, spelling, more string) ir.TypeDef { t.Helper() dir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(dir, "other.yaml"), []byte(other), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "other.yaml"), []byte(head+" W: "+spelling+"\n"), 0o600)) doc := compileSource(t, filepath.Join(dir, "root.yaml"), root+more) node, ok := doc.Types[ir.TypeID("type/openapi@other.yaml/components/schemas/W")] require.True(t, ok) return node } - alone := w(t, "") - _, composes := alone.(*ir.Model) - require.True(t, composes, "a string and a null share no value at 3.1, so W composes") - named := w(t, " A: {type: object, properties: {x: {$ref: './other.yaml#/components/schemas/W'}}}\n") + const policy = "{allOf: [{type: string, nullable: true}, {type: 'null'}]}" + alone := w(t, policy, "") + twin := w(t, "{allOf: [{type: [string, 'null']}, {type: 'null'}]}", "") + assert.Empty(t, cmp.Diff(twin, alone), "the policy's null is read as the type list's is") + named := w(t, policy, " A: {type: object, properties: {x: {$ref: './other.yaml#/components/schemas/W'}}}\n") assert.Empty(t, cmp.Diff(alone, named), "a 3.0 document naming W changes nothing of it") } diff --git a/compilers/openapi/e2e/document_minor_test.go b/compilers/openapi/e2e/document_minor_test.go index f8119b6af..8b7e68708 100644 --- a/compilers/openapi/e2e/document_minor_test.go +++ b/compilers/openapi/e2e/document_minor_test.go @@ -97,13 +97,13 @@ func extBounds(doc *ir.Document) map[jsontext.Pointer]ir.BigVal { return out } -// TestDocumentMinor_EachDocumentIsReadAtTheMinorItDeclares pins GitHub #839: -// a document a reference reaches is read at the minor it declares, its schemas -// in that minor's dialect, its objects held to that minor's table and its +// TestDocumentMinor_EachDocumentIsReadAtTheMinorItDeclares pins GitHub #839: a +// document a reference reaches is read at the minor it declares, its schemas in +// that minor's dialect, its objects held to that minor's table and its // Document.Sources entry naming it, in either direction between two minors, a // version of two parts drawing no finding. A document declaring no version, or // one the compiler does not read, is read at the source's, and the compile -// still stands. +// still compiles. func TestDocumentMinor_EachDocumentIsReadAtTheMinorItDeclares(t *testing.T) { t.Parallel() const exclusive30 = " S: {type: integer, minimum: 5, exclusiveMinimum: true}\n" diff --git a/compilers/openapi/e2e/dynamic_anchor_reach_test.go b/compilers/openapi/e2e/dynamic_anchor_reach_test.go index 94f43316c..58a5add63 100644 --- a/compilers/openapi/e2e/dynamic_anchor_reach_test.go +++ b/compilers/openapi/e2e/dynamic_anchor_reach_test.go @@ -21,8 +21,10 @@ import ( const dynListOther = "List:\n $id: https://example.com/list\n type: array\n items: {$dynamicRef: '#items'}\n" + " $defs:\n items:\n $dynamicAnchor: items\n type: integer\n" -// dynListItems is where that reference is, and the anchor it expands to. +// dynList is that List, dynListItems where its reference is, and the anchor it +// expands to. const ( + dynList = ir.TypeID("type/anonymous@other.yaml/List") dynListItems = ir.TypeID("type/anonymous@other.yaml/List/items") dynListAnchor = ir.TypeID("type/anonymous@other.yaml/List/$defs/items") dynListPoint = "/List/items/$dynamicRef" @@ -92,11 +94,11 @@ func TestCompile_ADynamicRefNoOtherDocumentDeclaresTheNameExpands(t *testing.T) require.NotNil(t, doc, name) require.Empty(t, byCode(diags, "openapi/unresolved-ref"), "%s: %+v", name, diags) - items, ok := doc.Types[dynListItems].(*ir.Scalar) + _, hoisted := doc.Types[dynListItems] + assert.False(t, hoisted, "%s: the expansion is the items' type, as a $ref's would be", name) + list, ok := doc.Types[dynList].(*ir.List) require.True(t, ok, name) - require.NotNil(t, items.Base, name) - assert.Equal(t, dynListAnchor, items.Base.Target, name) - assert.Empty(t, items.Unmodeled, name) + assert.Equal(t, dynListAnchor, list.ElementType.Target, name) assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAtSource(diags, "openapi/dynamic-ref-expanded", dynListPoint, 1), name) assert.Empty(t, dynKeptIn(diags, 1), name) } @@ -150,7 +152,7 @@ func TestCompile_ADynamicRefNamesTooManyForTheReachWalkAreKept(t *testing.T) { kept++ } } - assert.Equal(t, 100, kept, "every reference is kept with the verdict for a name another document declares") + assert.Equal(t, 100, kept, "every reference is kept with the answer for a name another document declares") if testing.Short() { t.Skip("the budget case binds to its limit") diff --git a/compilers/openapi/e2e/dynamic_ref_as_ref_test.go b/compilers/openapi/e2e/dynamic_ref_as_ref_test.go index 042936140..a4dccea0b 100644 --- a/compilers/openapi/e2e/dynamic_ref_as_ref_test.go +++ b/compilers/openapi/e2e/dynamic_ref_as_ref_test.go @@ -136,7 +136,7 @@ func TestCompile_ADynamicRefResolvingNowhereIsAnUnresolvedRef(t *testing.T) { sc := dynScalar(t, doc, "Miss") require.NotNil(t, sc.Base) assert.Equal(t, ir.TypeID("type/primitive/any"), sc.Base.Target) - assert.Empty(t, sc.Unmodeled, "the binding's error stands alone") + assert.Empty(t, sc.Unmodeled, "the binding's error is the only one") for _, diagnostic := range diags { assert.NotEqual(t, "openapi/dynamic-ref-expanded", diagnostic.Code) if diagnostic.Code == "openapi/degraded-construct" { diff --git a/compilers/openapi/e2e/entry_closure_test.go b/compilers/openapi/e2e/entry_closure_test.go index 60d89481f..86a9352ec 100644 --- a/compilers/openapi/e2e/entry_closure_test.go +++ b/compilers/openapi/e2e/entry_closure_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) @@ -51,76 +52,27 @@ func closureModelAt(t *testing.T, doc *ir.Document, at jsontext.Pointer) *ir.Mod return model } -// requireClosureKeptWhole holds that the entry of the allOf at at written at -// index is kept whole, for want of a home, as the one thing kept under at and -// the one thing reported there, and that the model it was lowered into is -// open: it carries neither the closure nor a catch-all. -func requireClosureKeptWhole(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, at jsontext.Pointer, index int) { +// requireClosureKeptAndSaid holds that model, which an additionalProperties +// types over members its own object does not declare, also keeps the keyword +// verbatim under its own key, its entries left out, as degraded_lowering, and +// that one info is drawn at keyword, naming unread, a member it did not read. +func requireClosureKeptAndSaid(t *testing.T, model *ir.Model, diags []ir.Diagnostic, keyword jsontext.Pointer, unread string) { t.Helper() - entry := at + jsontext.Pointer(fmt.Sprintf("/allOf/%d", index)) - assert.Equal(t, map[jsontext.Pointer]ir.UnmodeledReason{entry: ir.ReasonDegradedLowering}, - keptUnder(doc, at), "what is kept at %s", at) - assert.Equal(t, []jsontext.Pointer{entry}, degradedUnder(diags, at), "what is reported at %s", at) - model := closureModelAt(t, doc, at) - assert.Equal(t, entryKept(fmt.Sprintf("openapi:allOf/%d", index)), keptOn(model), "what the model at %s keeps", at) - assert.Equal(t, ir.AdditionalUnspecified, model.Additional, "the model at %s is open", at) - assert.Nil(t, model.AdditionalProperties, "the model at %s has no catch-all", at) -} - -// TestEntryClosure_AClosureThatIsNotTheOnlyDeclarationOfMembersIsKeptWhole -// holds that an entry writing additionalProperties or patternProperties is -// kept whole, under its index and for want of a home, where another conjunct -// declares the members it would read against: another entry, whichever side -// of it the entry is written on, or the position's own properties. The model -// holds the members of every conjunct and is open, in every order the entries -// are written in. -func TestEntryClosure_AClosureThatIsNotTheOnlyDeclarationOfMembersIsKeptWhole(t *testing.T) { - t.Parallel() - const properties = "{properties: {b: {type: string}}}" - cases := []struct { - name string - closure string - others []string - own string // what the position writes beside its allOf - only31 bool - }{ - {name: "closure beside another entry's properties", closure: "{additionalProperties: false}", others: []string{closureRef, properties}}, - {name: "closure beside a typed entry's properties", closure: "{additionalProperties: false}", - others: []string{"{type: object, properties: {b: {type: string}}, required: [b]}"}}, - {name: "a catch-all beside another entry's properties", closure: "{type: object, additionalProperties: {type: string}}", - others: []string{"{type: object, properties: {b: {type: number}}, required: [b]}"}}, - {name: "closure beside the position's own properties", closure: "{additionalProperties: false}", - others: []string{closureRef}, own: "properties: {b: {type: string}}, "}, - {name: "patterns beside another entry's properties", closure: "{patternProperties: {'^x-': {type: string}}}", - others: []string{closureRef, properties}, only31: true}, - } - for _, tc := range cases { - for _, version := range []string{"3.0.3", "3.1.0"} { - if tc.only31 && version != "3.1.0" { - continue - } - for _, order := range closureOrders(tc.closure, tc.others...) { - t.Run(fmt.Sprintf("%s/%s/at-%d", version, tc.name, order.at), func(t *testing.T) { - t.Parallel() - schema := "{" + tc.own + "allOf: " + order.list + "}" - inBothMappingOrders(t, conjunctionSpec(version, schema, closureUser), func(t *testing.T, spec string) { - doc, diags := compileAnnotationSpec(t, "kept", spec) - requireErrorsAndWarnings(t, diags, nil) - for _, at := range conjunctionPositions { - requireClosureKeptWhole(t, doc, diags, at, order.at) - } - }) - }) - } - } + kept := map[string]ir.UnmodeledReason{} + for name, entry := range model.Unmodeled { + kept[relocatedKey(name)] = entry.Reason } + assert.Equal(t, ir.ReasonDegradedLowering, kept["openapi:additionalProperties"], "the closure is kept at %s", keyword) + messages := messagesBeneath(diags, diag.DegradedConstruct, string(keyword)) + require.Len(t, messages, 1, "one info at %s", keyword) + assert.Contains(t, messages[0], unread, "the info names the member the closure did not read") } -// TestEntryClosure_AClosureBesideTheAllOfOfAnObjectWritingItIsTyped holds the -// control the cases that move a closure are read against: the closure written -// beside an allOf of a $ref, and the closure written beside the position's own -// properties, close the model, since the object writing it declares the -// members, whether the allOf names a $ref or not. +// TestEntryClosure_AClosureBesideTheAllOfOfAnObjectWritingItIsTyped holds that +// the closure written beside an allOf of a $ref, and the closure written +// beside the position's own properties, close the model, and, since the model +// holds the $ref target's members, which the object writing the closure does +// not declare, keep it verbatim and say so once at the keyword (GitHub #2047). func TestEntryClosure_AClosureBesideTheAllOfOfAnObjectWritingItIsTyped(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -137,8 +89,7 @@ func TestEntryClosure_AClosureBesideTheAllOfOfAnObjectWritingItIsTyped(t *testin assert.Equal(t, ir.AdditionalClosed, model.Additional, "%s at %s", name, at) require.NotNil(t, model.Base, "%s at %s", name, at) assert.Equal(t, componentID("User"), model.Base.Target, "%s at %s", name, at) - assert.Empty(t, keptUnder(doc, at), "%s at %s", name, at) - assert.Empty(t, degradedUnder(diags, at), "%s at %s", name, at) + requireClosureKeptAndSaid(t, model, diags, at+"/additionalProperties", "id") } } }) @@ -193,6 +144,15 @@ func requireClosurePatterns(t *testing.T, model *ir.Model, at string) { assert.Equal(t, primitive(ir.PrimitiveString), model.AdditionalProperties.Patterns[0].Value.Target, at) } +// requireCatchAllOfStrings holds a model to hold a catch-all of strings, +// whatever its openness. +func requireCatchAllOfStrings(t *testing.T, model *ir.Model, at string) { + t.Helper() + require.NotNil(t, model.AdditionalProperties, "a catch-all at %s", at) + require.NotNil(t, model.AdditionalProperties.Value, at) + assert.Equal(t, primitive(ir.PrimitiveString), model.AdditionalProperties.Value.Target, at) +} + // requireClosureValues holds a model to hold a catch-all of strings. func requireClosureValues(t *testing.T, model *ir.Model, at string) { t.Helper() @@ -202,8 +162,10 @@ func requireClosureValues(t *testing.T, model *ir.Model, at string) { assert.Equal(t, primitive(ir.PrimitiveString), model.AdditionalProperties.Value.Target, at) } -// closureTypedCases are the entries that type the closure they write. -func closureTypedCases() []closureTyped { +// closureOverRefCases are the entries whose additionalProperties is typed over +// the members of the $ref beside them, which their own object does not +// declare, so each is also kept and reported (GitHub #2047). +func closureOverRefCases() []closureTyped { return []closureTyped{ {name: "a closure, no member declared", closure: "{additionalProperties: false}", others: []string{closureRef}, base: true, check: requireClosureClosed}, {name: "a closure of an object, no member declared", closure: "{type: object, additionalProperties: false}", others: []string{closureRef}, base: true, check: requireClosureClosed}, @@ -211,8 +173,52 @@ func closureTypedCases() []closureTyped { name: "a closure declaring its own members", closure: "{properties: {b: {type: string}}, additionalProperties: false}", others: []string{closureRef}, base: true, properties: []string{"b"}, check: requireClosureClosed, }, - {name: "a closure of no $ref, no member declared", closure: "{type: object, additionalProperties: false}", others: []string{"{required: [a]}"}, check: requireClosureClosed}, {name: "a catch-all, no member declared", closure: "{additionalProperties: {type: string}}", others: []string{closureRef}, base: true, check: requireClosureValues}, + } +} + +// TestEntryClosure_AnEntrysClosureOverARefsMembersIsTypedKeptAndSaid holds that +// an entry writing additionalProperties beside a $ref closes the model or +// takes the catch-all, as beside the allOf, and, since the model holds the +// target's members, keeps the keyword verbatim with one info at it naming +// them, at every position, in both versions and in every order of the entries; +// and that a closure beside an entry requiring a member it refuses admits no +// instance, one unsatisfiable-schema finding at the keyword (GitHub #2047). +func TestEntryClosure_AnEntrysClosureOverARefsMembersIsTypedKeptAndSaid(t *testing.T) { + t.Parallel() + for _, tc := range closureOverRefCases() { + for _, version := range []string{"3.0.3", "3.1.0"} { + for _, order := range closureOrders(tc.closure, tc.others...) { + t.Run(fmt.Sprintf("%s/%s/at-%d", version, tc.name, order.at), func(t *testing.T) { + t.Parallel() + inBothMappingOrders(t, conjunctionSpec(version, "{allOf: "+order.list+"}", closureUser), func(t *testing.T, spec string) { + doc, diags := compileAnnotationSpec(t, "typed", spec) + requireErrorsAndWarnings(t, diags, nil) + for _, at := range conjunctionPositions { + model := closureModelAt(t, doc, at) + tc.check(t, model, string(at)) + require.NotNil(t, model.Base, "the base at %s", at) + assert.Equal(t, componentID("User"), model.Base.Target, at) + keyword := at + jsontext.Pointer(fmt.Sprintf("/allOf/%d/additionalProperties", order.at)) + requireClosureKeptAndSaid(t, model, diags, keyword, "id") + } + }) + }) + } + } + } + for _, order := range closureOrders("{type: object, additionalProperties: false}", "{required: [a]}") { + _, diags := compileAnnotationSpec(t, "refused", conjunctionSpec("3.1.0", "{allOf: "+order.list+"}")) + for _, at := range conjunctionPositions { + keyword := at + jsontext.Pointer(fmt.Sprintf("/allOf/%d/additionalProperties", order.at)) + assert.Equal(t, 1, unsatisfiableAt(diags, string(keyword)), "a required member refused at %s", keyword) + } + } +} + +// closureTypedCases are the entries that type the closure they write. +func closureTypedCases() []closureTyped { + return []closureTyped{ { name: "patterns, no member declared", closure: "{patternProperties: {'^x-': {type: string}}}", others: []string{closureRef}, base: true, only31: true, check: requireClosurePatterns, @@ -225,8 +231,8 @@ func closureTypedCases() []closureTyped { } // TestEntryClosure_AClosureOfTheOnlyEntryDeclaringMembersIsTyped holds that an -// entry writing additionalProperties or patternProperties types it where it is -// the only conjunct declaring properties or patternProperties, or none does: +// entry writing patternProperties types it where it is the only conjunct +// declaring properties or patternProperties, or none does: // the model closes, or takes the catch-all, as it does where the keyword is // written beside the allOf, with nothing kept and nothing reported, at every // position, in both versions the keyword exists in and in every order of the @@ -302,13 +308,13 @@ func TestEntryClosure_TheEntryAndTheBesideSpellingsAreOneModel(t *testing.T) { } } -// TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsKept holds -// that a closure written beside an allOf whose entries declare the members, -// the position declaring none of its own, is kept under its own key for want -// of a home: it reads against the position's own properties, as it does on an -// entry, so it does not close the members the entries declare. The model is -// open, the keyword is kept once on it and reported once. -func TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsKept(t *testing.T) { +// TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsTypedAndKept +// holds that a closure written beside an allOf whose entries declare the +// members, the position declaring none of its own, types the model, the +// closed subtype its author means, and, since it reads against the position's +// own properties alone, is also kept once under its own key and reported once +// (GitHub #2047). +func TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsTypedAndKept(t *testing.T) { t.Parallel() const properties = "{properties: {b: {type: string}}}" for _, tc := range []struct { @@ -318,6 +324,10 @@ func TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsKept(t *test {"closure", "additionalProperties: false", "openapi:additionalProperties", false}, {"catch-all", "additionalProperties: {type: string}", "openapi:additionalProperties", false}, } { + typed := requireClosureClosed + if tc.name == "catch-all" { + typed = requireCatchAllOfStrings + } for _, version := range []string{"3.0.3", "3.1.0"} { if tc.only31 && version != "3.1.0" { continue @@ -335,8 +345,7 @@ func TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsKept(t *test requireErrorsAndWarnings(t, diags, nil) for _, at := range conjunctionPositions { model := closureModelAt(t, doc, at) - assert.Equal(t, ir.AdditionalUnspecified, model.Additional, "open at %s", at) - assert.Nil(t, model.AdditionalProperties, "no catch-all at %s", at) + typed(t, model, string(at)) assert.Equal(t, entryKept(tc.key), keptOn(model), "what the model keeps at %s", at) assert.Len(t, entryKeptUnder(doc, at), 1, "nothing else is kept at %s", at) assert.Len(t, degradedUnder(diags, at), 1, "one info at %s", at) diff --git a/compilers/openapi/e2e/entry_value_set_apart_test.go b/compilers/openapi/e2e/entry_value_set_apart_test.go index 50c4b0718..8e4042f6f 100644 --- a/compilers/openapi/e2e/entry_value_set_apart_test.go +++ b/compilers/openapi/e2e/entry_value_set_apart_test.go @@ -10,9 +10,10 @@ import ( ) // disjointNamesAnywhere matches what a disjoint report names, each conjunct by -// where it is written, which the spellings and orders of a case part on, and -// which the cases assert apart (entryWarnings). -var disjointNamesAnywhere = regexp.MustCompile(`share no value \([^)]*\)`) +// where it is written, and the one of them it asks to correct, which the +// spellings and orders of a case part on, and which the cases assert apart +// (entryWarnings). +var disjointNamesAnywhere = regexp.MustCompile(`no value satisfies [^;]*;|remove or correct one (entry|of them)`) // entryWarnings is the one warning each position draws whose value set shares // no member with its target's, that its conjuncts share no value, and none @@ -23,8 +24,8 @@ func entryWarnings(vs entryValueSet) []wantFinding { } out := make([]wantFinding, 0, len(conjunctionPositions)) for _, at := range conjunctionPositions { - out = append(out, wantFinding{code: string(diag.DegradedConstruct), pointer: string(at), - contains: []string{"share no value (", ": 1 value", ": 2 values", "the enum it lowered as"}}) + out = append(out, wantFinding{code: diag.UnsatisfiableSchema, pointer: string(at), + contains: []string{"no value satisfies ", ": enum [", "; lowered as "}}) } return out } diff --git a/compilers/openapi/e2e/entry_value_set_beside_test.go b/compilers/openapi/e2e/entry_value_set_beside_test.go index 8a929695e..41634fb03 100644 --- a/compilers/openapi/e2e/entry_value_set_beside_test.go +++ b/compilers/openapi/e2e/entry_value_set_beside_test.go @@ -10,16 +10,19 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" ) // TestEntryValueSet_AKeywordBesideTheAllOfLandsAsTheWrapLandsIt holds that a // keyword a position writes beside an allOf whose entry's value set the -// position lowers to lands as it does where the value set is written beside -// the allOf: kept on the node standing at the position, with the info naming -// that node's kind. A bound the value set's kind takes is among them: no -// carrier holds a bound of a use owning its node. +// position lowers to lands as it does where the value set is written beside the +// allOf: a bound of the kind the enum lists in the Enum's Constraints (GitHub +// #2004), and any other keyword kept on the node at the position, with the info +// naming that node's kind. No carrier holds a bound of a use owning its node. func TestEntryValueSet_AKeywordBesideTheAllOfLandsAsTheWrapLandsIt(t *testing.T) { t.Parallel() + held := map[string]*ir.Constraints{"pattern": {Pattern: "^a"}, "maxLength": {MaxLength: new(int64(0))}} for _, beside := range []string{"pattern: '^a'", "maxLength: 0", "minItems: 2", "format: date"} { keyword, _, _ := strings.Cut(beside, ":") for _, version := range []string{"3.0.3", "3.1.0"} { @@ -32,6 +35,13 @@ func TestEntryValueSet_AKeywordBesideTheAllOfLandsAsTheWrapLandsIt(t *testing.T) for _, at := range conjunctionPositions { node := kindNode(t, entryDoc, usedAt(t, entryDoc, at)) _, kept := node.Common().Unmodeled["openapi:"+keyword] + if bounds, isHeld := held[keyword]; isHeld { + enum, isEnum := node.(*ir.Enum) + require.True(t, isEnum, "the node at %s is the Enum", at) + assert.Equal(t, bounds, enum.Constraints, "the Enum at %s holds %s", at, keyword) + assert.False(t, kept, "the node at %s keeps no %s", at, keyword) + continue + } require.True(t, kept, "the node at %s keeps %s", at, keyword) } assert.Equal(t, entryTree(t, wrapDoc), entryTree(t, entryDoc), "the spelling decided the document") diff --git a/compilers/openapi/e2e/entry_value_set_beside_warns_test.go b/compilers/openapi/e2e/entry_value_set_beside_warns_test.go index 647d2de9c..ac0179829 100644 --- a/compilers/openapi/e2e/entry_value_set_beside_warns_test.go +++ b/compilers/openapi/e2e/entry_value_set_beside_warns_test.go @@ -14,11 +14,11 @@ import ( ) // TestEntryValueSet_AValueSetSharingNoKindWithItsRefWarnsInEverySpelling holds -// that a value set elected over a $ref whose instance types it shares none of +// that a value set chosen over a $ref whose instance types it shares none of // draws the warning naming what the position lowered as wherever the set is // written, beside the allOf as on an entry -// (docs/compilers/openapi.md#allof-refinement). The warning names each -// conjunct where it is written, so its text is the one difference. +// (docs/compilers/openapi.md#allof-refinement). The warning names each conjunct +// where it is written, so its text is the one difference. func TestEntryValueSet_AValueSetSharingNoKindWithItsRefWarnsInEverySpelling(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -31,11 +31,11 @@ func TestEntryValueSet_AValueSetSharingNoKindWithItsRefWarnsInEverySpelling(t *t for _, at := range conjunctionPositions { messages := entryMessagesAt(wrapDiags, at) require.Len(t, messages, 1, "one report at %s", at) - assert.Contains(t, messages[0], "which the enum it lowered as cannot state", at) + assert.Contains(t, messages[0], "; lowered as its enum — ", at) } for _, doc := range []*ir.Document{wrapDoc, entryDoc} { for i := range doc.Diagnostics { - if strings.Contains(doc.Diagnostics[i].Message, "share no value (") { + if strings.Contains(doc.Diagnostics[i].Message, "no value satisfies ") { doc.Diagnostics[i].Message = "" } } diff --git a/compilers/openapi/e2e/entry_value_set_helpers_test.go b/compilers/openapi/e2e/entry_value_set_helpers_test.go index 3d9241627..a88666862 100644 --- a/compilers/openapi/e2e/entry_value_set_helpers_test.go +++ b/compilers/openapi/e2e/entry_value_set_helpers_test.go @@ -23,12 +23,12 @@ import ( var entryIndexed = regexp.MustCompile(`/allOf/[0-9]+$`) // requireNoEntryIndexedType holds that no type of doc has an ID or a source -// pointer ending at an entry of an allOf, so none stands at an entry where it -// is the position that owns the node. +// pointer ending at an entry of an allOf, so none sits at an entry where it is +// the position that owns the node. func requireNoEntryIndexedType(t *testing.T, doc *ir.Document) { t.Helper() for _, id := range slices.Sorted(maps.Keys(doc.Types)) { - assert.False(t, entryIndexed.MatchString(string(id)), "%s stands at an entry of an allOf", id) + assert.False(t, entryIndexed.MatchString(string(id)), "%s sits at an entry of an allOf", id) at := string(doc.Types[id].Common().Provenance.Pointer) assert.False(t, entryIndexed.MatchString(at), "%s is lowered from the entry at %s", id, at) } @@ -48,6 +48,35 @@ func entryKeptUnder(doc *ir.Document, at jsontext.Pointer) []string { return keys } +// entryKeyOnly matches the key an allOf entry kept whole is kept under. +var entryKeyOnly = regexp.MustCompile(`^openapi:allOf/[0-9]+$`) + +// keptSetAsBeside rewrites, on every node of doc, an allOf entry kept whole +// that writes keyword alone as the keyword kept where it is written beside the +// allOf: under its own key, its value unwrapped, at its own pointer. A closed +// empty Enum keeps the value set it chooses under the key it is written at, so +// two spellings of one conjunction differ by that key alone. +func keptSetAsBeside(t *testing.T, doc *ir.Document, keyword string) { + t.Helper() + require.NotEmpty(t, keyword) + for _, td := range doc.Types { + kept := td.Common().Unmodeled + for _, key := range slices.Sorted(maps.Keys(kept)) { + var members map[string]jsontext.Value + if !entryKeyOnly.MatchString(key) || json.Unmarshal(kept[key].Value, &members) != nil || + len(members) != 1 || members[keyword] == nil { + continue + } + entry := kept[key] + delete(kept, key) + require.NotContains(t, kept, "openapi:"+keyword, "the keyword is kept once") + entry.Value = members[keyword] + entry.Provenance.Pointer += jsontext.Pointer("/" + keyword) + kept["openapi:"+keyword] = entry + } + } +} + // entryKept is the Unmodeled entries a node is expected to hold, each kept // for want of a home, keyed as the node keeps them. func entryKept(keys ...string) map[string]ir.UnmodeledReason { diff --git a/compilers/openapi/e2e/entry_value_set_position_test.go b/compilers/openapi/e2e/entry_value_set_position_test.go index 5fd71fc30..9ff2b876a 100644 --- a/compilers/openapi/e2e/entry_value_set_position_test.go +++ b/compilers/openapi/e2e/entry_value_set_position_test.go @@ -33,8 +33,9 @@ type entryValueSet struct { } // entryValueSets are the value sets the cases write: a string enum and const -// over a string target, an enum outside the values its target holds, and an -// enum and a const of objects over an object target. +// over a string target, an enum outside the values its target holds, which +// shares no member with the target's and so is the closed empty Enum keeping +// both, and an enum and a const of objects over an object target. func entryValueSets() []entryValueSet { stringSchema := "T: {type: string}" obj := "T: {type: object, properties: {a: {type: string}}}" @@ -43,7 +44,7 @@ func entryValueSets() []entryValueSet { {name: "const", target: stringSchema, keyword: "const: a", only31: true, kind: ir.KindLiteral, check: requireEntryLiteral("a")}, { name: "enum outside the target", target: "T: {type: string, enum: [low, mid]}", keyword: "enum: [other]", - apart: true, kind: ir.KindEnum, check: requireEntryEnum("other"), + apart: true, kind: ir.KindEnum, check: requireEmptyEnumKeeping(`["other"]`), }, {name: "object enum", target: obj, keyword: "enum: [{a: x}]", kind: ir.KindUnion, check: requireEntryObjectUnion}, {name: "object const", target: obj, keyword: "const: {a: x}", only31: true, kind: ir.KindLiteral, check: requireEntryObjectLiteral}, @@ -62,6 +63,31 @@ func requireEntryEnum(member string) func(t *testing.T, doc *ir.Document, node i } } +// requireEmptyEnumKeeping holds a node to be the closed empty Enum of strings +// that value sets sharing no member give, keeping the written set, as JSON, +// verbatim, alone or inside its entry, beside the $ref it narrows. +func requireEmptyEnumKeeping(set string) func(t *testing.T, doc *ir.Document, node ir.TypeDef) { + return func(t *testing.T, _ *ir.Document, node ir.TypeDef) { + t.Helper() + enum, ok := node.(*ir.Enum) + require.True(t, ok, "an enum") + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Equal(t, ir.PrimitiveString, enum.ValueType) + var sets, refs int + for key, entry := range enum.Unmodeled { + if strings.HasPrefix(key, "openapi:$ref") { + refs++ + } + if strings.Contains(string(entry.Value), strings.Trim(set, "[]")) { + sets++ + } + } + assert.Equal(t, 1, sets, "the written set is kept once: %v", enum.Unmodeled) + assert.Equal(t, 1, refs, "the $ref is kept: %v", enum.Unmodeled) + } +} + // requireEntryLiteral holds a node to be a literal of the string given. func requireEntryLiteral(value string) func(t *testing.T, doc *ir.Document, node ir.TypeDef) { return func(t *testing.T, _ *ir.Document, node ir.TypeDef) { @@ -113,11 +139,11 @@ func entryPositionID(at jsontext.Pointer) ir.TypeID { // entryTree is doc as its JSON encodes it, without the hash of its source and // with each finding rendered as a line, sorted, and every pointer in a value -// written as if no allOf entry stood on it: two documents compiled from one +// written as if no allOf entry sat on it: two documents compiled from one // conjunction spelt another way then compare equal where they hold the same // facts. A node keeps the pointer it is written at beneath an entry, so a key -// loses the entries it passes through, but one ending at an entry is left as -// it is, and a node standing at an entry still differs. +// loses the entries it passes through, but one ending at an entry is left as it +// is, and a node sitting at an entry still differs. func entryTree(t *testing.T, doc *ir.Document) string { t.Helper() tree, ok := documentTree(t, doc).(map[string]any) @@ -126,7 +152,7 @@ func entryTree(t *testing.T, doc *ir.Document) string { var findings []string if list, ok := tree["diagnostics"].([]any); ok { for _, d := range list { - findings = append(findings, disjointNamesAnywhere.ReplaceAllString(fmt.Sprint(entryIndexless(d)), "share no value")) + findings = append(findings, disjointNamesAnywhere.ReplaceAllString(fmt.Sprint(entryIndexless(d)), "named apart")) } } slices.Sort(findings) @@ -194,6 +220,24 @@ func entrySpellings(keyword string) []entrySpelling { } } +// besideKey is the key a value set written as keyword, one YAML member, is +// kept under where it is written beside the allOf or the $ref. +func besideKey(keyword string) string { + name, _, _ := strings.Cut(keyword, ":") + return "openapi:" + name +} + +// entryKeptFor is what the node at a position keeps: the $ref the value set +// narrows and, where the value set shares no member with its target's, the set +// the closed empty Enum chooses, under its keyword in every spelling, as no +// other writer writes that keyword. +func entryKeptFor(vs entryValueSet) map[string]ir.UnmodeledReason { + if vs.apart { + return entryKept("openapi:$ref", besideKey(vs.keyword)) + } + return entryKept("openapi:$ref") +} + // entryVersions are the versions of the cases, a 3.1 keyword's among them // where the case names one. func entryVersions(vs entryValueSet) []string { @@ -204,46 +248,53 @@ func entryVersions(vs entryValueSet) []string { } // requireEntryNodeAt holds what a position writing a value set over a $ref -// lowers to, where its schema is written at at: the one node the carrier -// names stands at the position, holds the value set, and holds the $ref the -// set narrows under openapi:$ref, which no other node holds and one info -// reports at the entry writing it. -func requireEntryNodeAt(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, at jsontext.Pointer, vs entryValueSet, ref int) { +// lowers to, where its schema is written at positionPointer: the one node the +// carrier names sits at the position, holds the value set, and holds the $ref +// the set narrows under openapi:$ref, which no other node holds and one info +// reports at the entry writing it. A value set sharing no member with its +// target's is kept too, under its keyword (entryKeptFor). +func requireEntryNodeAt(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, positionPointer jsontext.Pointer, vs entryValueSet, ref int) { t.Helper() - id := usedAt(t, doc, at) - require.Equal(t, entryPositionID(at), id, "the node the position names stands at the position") + id := usedAt(t, doc, positionPointer) + require.Equal(t, entryPositionID(positionPointer), id, "the node the position names sits at the position") node := kindNode(t, doc, id) - assert.Equal(t, vs.kind, node.Kind(), at) - assert.Equal(t, at, node.Common().Provenance.Pointer, "the node is lowered from the position") + assert.Equal(t, vs.kind, node.Kind(), positionPointer) + assert.Equal(t, positionPointer, node.Common().Provenance.Pointer, "the node is lowered from the position") vs.check(t, doc, node) - assert.Equal(t, entryKept("openapi:$ref"), keptOn(node), "what the node keeps at %s", at) + want := entryKeptFor(vs) + assert.Equal(t, want, keptOn(node), "what the node keeps at %s", positionPointer) entry, held := node.Common().Unmodeled["openapi:$ref"] - require.True(t, held, at) + require.True(t, held, positionPointer) assert.JSONEq(t, `"#/components/schemas/T"`, string(entry.Value), "the reference's text") - assert.Len(t, entryKeptUnder(doc, at), 1, "no other node holds what the position keeps at %s", at) + assert.Len(t, entryKeptUnder(doc, positionPointer), len(want), "no other node holds what the position keeps at %s", positionPointer) if ref < 0 { return } - refAt := at + jsontext.Pointer(fmt.Sprintf("/allOf/%d", ref)) + refAt := positionPointer + jsontext.Pointer(fmt.Sprintf("/allOf/%d", ref)) assert.Equal(t, refAt, entry.Provenance.Pointer, "the entry kept is the one writing the $ref") n := 0 - for _, pointer := range degradedUnder(diags, at) { + for _, pointer := range degradedUnder(diags, positionPointer) { if pointer == refAt { n++ } } - assert.Equal(t, 1, n, "one info at the $ref the value set narrows, at %s", at) + infos := 1 + if vs.apart { + // Sets sharing no member draw the one warning, and no entry's info. + infos = 0 + } + assert.Equal(t, infos, n, "the infos at the $ref the value set narrows, at %s", positionPointer) } -// TestEntryValueSet_TheNodeStandsAtThePositionInEverySpelling holds that where -// a value set narrows a $ref, the enum or literal is the position's own node, -// whether the value set is written beside the allOf or in an entry ahead of -// the $ref, after it or behind another: at a component, a property, a list's +// TestEntryValueSet_TheNodeIsAtThePositionInEverySpelling holds that where a +// value set narrows a $ref, the enum or literal is the position's own node, +// whether the value set is written beside the allOf or in an entry ahead of the +// $ref, after it or behind another: at a component, a property, a list's // element and a parameter's schema its ID and its pointer are the position's, -// the kept $ref is on it and on no other node, and no type of the document -// stands at an entry of an allOf. -func TestEntryValueSet_TheNodeStandsAtThePositionInEverySpelling(t *testing.T) { +// the kept $ref is on it and on no other node, and no type of the document sits +// at an entry of an allOf. +func TestEntryValueSet_TheNodeIsAtThePositionInEverySpelling(t *testing.T) { t.Parallel() for _, vs := range entryValueSets() { for _, version := range entryVersions(vs) { @@ -251,7 +302,7 @@ func TestEntryValueSet_TheNodeStandsAtThePositionInEverySpelling(t *testing.T) { t.Run(fmt.Sprintf("%s/%s/%s", version, vs.name, sp.name), func(t *testing.T) { t.Parallel() inBothMappingOrders(t, conjunctionSpec(version, sp.schema, vs.target), func(t *testing.T, spec string) { - doc, diags := compileAnnotationSpec(t, "stands", spec) + doc, diags := compileAnnotationSpec(t, "sits", spec) requireErrorsAndWarnings(t, diags, entryWarnings(vs)) requireNoEntryIndexedType(t, doc) for _, at := range conjunctionPositions { @@ -267,7 +318,8 @@ func TestEntryValueSet_TheNodeStandsAtThePositionInEverySpelling(t *testing.T) { // TestEntryValueSet_TheEntryOrderLeavesTheDocumentAlone holds that the same // value set and $ref written in the one order and in the other compile to one // document but for the index each entry is written at: the nodes keep their -// IDs, since none stands at an entry, and what is kept is keyed by what it is. +// IDs, since none sits at an entry, and what is kept is keyed by what it is, a +// value set sharing no member with its target's under its keyword. func TestEntryValueSet_TheEntryOrderLeavesTheDocumentAlone(t *testing.T) { t.Parallel() for _, vs := range entryValueSets() { @@ -286,7 +338,8 @@ func TestEntryValueSet_TheEntryOrderLeavesTheDocumentAlone(t *testing.T) { // TestEntryValueSet_TheWrapAndTheEntrySpellingsCompileAlike holds that a value // set written beside an allOf over a $ref and one written in an entry after -// the $ref compile to one document, since both are the one conjunction. +// the $ref compile to one document, since both are the one conjunction, a +// value set sharing no member with its target's kept under its keyword in both. func TestEntryValueSet_TheWrapAndTheEntrySpellingsCompileAlike(t *testing.T) { t.Parallel() for _, vs := range entryValueSets() { @@ -304,8 +357,8 @@ func TestEntryValueSet_TheWrapAndTheEntrySpellingsCompileAlike(t *testing.T) { // TestEntryValueSet_AReferenceToThePositionReadsItsNode holds that a $ref to // the pointer of a position holding a narrowing, and a $ref to the component -// holding one, name the enum standing at that position, as a use does, in -// either order of the components. +// holding one, name the enum at that position, as a use does, in either order +// of the components. func TestEntryValueSet_AReferenceToThePositionReadsItsNode(t *testing.T) { t.Parallel() const at = "/components/schemas/Holder/properties/p" @@ -426,12 +479,12 @@ func TestEntryValueSet_SeveralRefsAreKeptByTheirReferenceText(t *testing.T) { } } -// TestEntryValueSet_AnObjectValueSetIsElectedBeforeTheComposition holds that +// TestEntryValueSet_AnObjectValueSetIsChosenBeforeTheComposition holds that // a position whose $ref names an object and whose value set is of objects // lowers to the value set in every spelling: a union of literals for an enum // and a literal for a const at the position, never a model whose base is the // target, the $ref kept under openapi:$ref as for a scalar. -func TestEntryValueSet_AnObjectValueSetIsElectedBeforeTheComposition(t *testing.T) { +func TestEntryValueSet_AnObjectValueSetIsChosenBeforeTheComposition(t *testing.T) { t.Parallel() for _, vs := range entryValueSets() { if vs.target != entryValueSets()[3].target { @@ -457,9 +510,11 @@ func TestEntryValueSet_AnObjectValueSetIsElectedBeforeTheComposition(t *testing. // TestEntryValueSet_AValueSetWrittenTwiceIsOneNodeInEveryOrder holds that a // value set two entries write alike beside a $ref is one conjunct whose node -// stands at the position: written ahead of the $ref, after it or around it, -// the documents are one but for the index each entry is written at, where the -// node stood at whichever copy came first. +// sits at the position: written ahead of the $ref, after it or around it, the +// documents are one but for the index each entry is written at, where the node +// sat at whichever copy came first. A value set sharing no member with its +// target's is one value its two writers write alike, so it is kept once, under +// its keyword. func TestEntryValueSet_AValueSetWrittenTwiceIsOneNodeInEveryOrder(t *testing.T) { t.Parallel() for _, vs := range entryValueSets() { @@ -468,14 +523,17 @@ func TestEntryValueSet_AValueSetWrittenTwiceIsOneNodeInEveryOrder(t *testing.T) t.Parallel() set := "{" + vs.keyword + "}" var trees []string - for _, entries := range []string{entryRef + ", " + set + ", " + set, set + ", " + entryRef + ", " + set, - set + ", " + set + ", " + entryRef} { + for _, entries := range []string{ + entryRef + ", " + set + ", " + set, + set + ", " + entryRef + ", " + set, + set + ", " + set + ", " + entryRef, + } { doc, diags := compileAnnotationSpec(t, "twice", conjunctionSpec(version, "{allOf: ["+entries+"]}", vs.target)) requireErrorsAndWarnings(t, diags, entryWarnings(vs)) requireNoEntryIndexedType(t, doc) node := kindNode(t, doc, componentID("Pos")) vs.check(t, doc, node) - assert.Equal(t, entryKept("openapi:$ref"), keptOn(node), entries) + assert.Equal(t, entryKeptFor(vs), keptOn(node), entries) trees = append(trees, entryTree(t, doc)) } assert.Equal(t, trees[0], trees[1], "the order decided the document") diff --git a/compilers/openapi/e2e/entry_value_set_ref_test.go b/compilers/openapi/e2e/entry_value_set_ref_test.go index 19b76caa7..26df64cc3 100644 --- a/compilers/openapi/e2e/entry_value_set_ref_test.go +++ b/compilers/openapi/e2e/entry_value_set_ref_test.go @@ -7,10 +7,11 @@ import ( "testing" ) -// TestEntryValueSet_ARefWithTheValueSetBesideItIsTheSameNode holds that at -// 3.1, where a keyword beside a $ref applies, the value set written on the -// $ref's own object stands at the position and keeps the $ref as the -// spellings with an allOf do. +// TestEntryValueSet_ARefWithTheValueSetBesideItIsTheSameNode holds that at 3.1, +// where a keyword beside a $ref applies, the value set written on the $ref's +// own object sits at the position and keeps the $ref as the spellings with an +// allOf do, and a value set sharing no member with its target's under its own +// key, as beside the allOf. // // It waits on a $ref and the keywords beside it lowering as one conjunction, // as the allOf spellings do (docs/compilers/openapi.md#ref-use-site): until diff --git a/compilers/openapi/e2e/entry_value_set_test.go b/compilers/openapi/e2e/entry_value_set_test.go index 5fad96423..a11034a29 100644 --- a/compilers/openapi/e2e/entry_value_set_test.go +++ b/compilers/openapi/e2e/entry_value_set_test.go @@ -10,13 +10,13 @@ import ( "github.com/stretchr/testify/assert" ) -// TestEntryValueSet_AValueSetTheTargetAlreadySaysStandsNowhere holds the -// control the cases that move a node are read against: an entry whose value -// set is no narrower than the one its $ref target holds, or that names the -// target's own type, is consumed by the target, so the position is a use of -// the target, nothing stands at the entry, nothing is kept and nothing is -// reported, whichever order the entries and the components are written in. -func TestEntryValueSet_AValueSetTheTargetAlreadySaysStandsNowhere(t *testing.T) { +// TestEntryValueSet_AValueSetTheTargetAlreadySaysIsPlacedNowhere holds the +// control the cases that move a node are read against: an entry whose value set +// is no narrower than the one its $ref target holds, or that names the target's +// own type, is consumed by the target, so the position is a use of the target, +// nothing sits at the entry, nothing is kept and nothing is reported, whichever +// order the entries and the components are written in. +func TestEntryValueSet_AValueSetTheTargetAlreadySaysIsPlacedNowhere(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Level'}" for _, version := range []string{"3.0.3", "3.1.0"} { diff --git a/compilers/openapi/e2e/entry_value_set_written_test.go b/compilers/openapi/e2e/entry_value_set_written_test.go index b23171d99..c7b814aaf 100644 --- a/compilers/openapi/e2e/entry_value_set_written_test.go +++ b/compilers/openapi/e2e/entry_value_set_written_test.go @@ -26,10 +26,10 @@ func entryMessagesAt(diags []ir.Diagnostic, at jsontext.Pointer) []string { } // TestEntryValueSet_WhatTheSetWritesStaysWhereItIsWritten holds that where an -// entry's value set stands at the position, what lies beneath it does not: -// the reports on its members are at the members as the entry writes them, -// and the literals an enum of objects lowers to, with the info saying so, -// stand at the entry, at every position. +// entry's value set sits at the position, what lies beneath it does not: the +// reports on its members are at the members as the entry writes them, and the +// literals an enum of objects lowers to, with the info saying so, sit at the +// entry, at every position. func TestEntryValueSet_WhatTheSetWritesStaysWhereItIsWritten(t *testing.T) { t.Parallel() t.Run("members", func(t *testing.T) { @@ -57,7 +57,7 @@ func TestEntryValueSet_WhatTheSetWritesStaysWhereItIsWritten(t *testing.T) { require.Len(t, union.Variants, 2, at) for i, variant := range union.Variants { want := entry + jsontext.Pointer("/enum/"+strconv.Itoa(i)) - assert.Equal(t, ir.TypeID("type/anonymous"+string(want)), variant.Type.Target, "the literal stands at the entry") + assert.Equal(t, ir.TypeID("type/anonymous"+string(want)), variant.Type.Target, "the literal sits at the entry") assert.Equal(t, want, kindNode(t, doc, variant.Type.Target).Common().Provenance.Pointer, at) } assert.Equal(t, []string{"heterogeneous or non-scalar enum lowered as a union of literals"}, diff --git a/compilers/openapi/e2e/enum_bounds_test.go b/compilers/openapi/e2e/enum_bounds_test.go new file mode 100644 index 000000000..180accbeb --- /dev/null +++ b/compilers/openapi/e2e/enum_bounds_test.go @@ -0,0 +1,235 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/pass" +) + +// enumBoundsHolder is GitHub #2004's reproduction with a component and a +// numeric enum beside it: an open, a mixed and a closed enum writing a length, +// each at a property, and the same closed enum as a component. +var enumBoundsHolder = []string{ + "Holder: {type: object, properties: {" + + "open: {type: string, enum: [a, bb], x-extensible-enum: [a, bb], maxLength: 8}, " + + "mixed: {enum: [a, 1], x-extensible-enum: true, maxLength: 8}, " + + "closed: {type: string, enum: [a, bb], maxLength: 8}, " + + "pattern: {type: string, enum: [a, ab], pattern: '^a'}, " + + "number: {type: integer, enum: [1, 2], minimum: 1, maximum: 5}}}", + "Top: {type: string, enum: [a, bb], minLength: 1, maxLength: 8}", +} + +// TestEnumBounds_AnEnumHoldsTheBoundsOfItsValueKind holds GitHub #2004's +// reproduction to one reading: an Enum's Constraints hold the bounds of its +// value kind its schema writes, closed or open, and the Union of literals a +// mixed enum lowers to holds them in its own Constraints, so none is kept or +// reported, and no carrier holds a copy, its position owning the node, in +// either order of the components. +func TestEnumBounds_AnEnumHoldsTheBoundsOfItsValueKind(t *testing.T) { + t.Parallel() + maxEight := &ir.Constraints{MaxLength: new(int64(8))} + want := map[string]*ir.Constraints{ + "Holder/properties/open": maxEight, + "Holder/properties/closed": maxEight, + "Holder/properties/mixed": maxEight, + "Holder/properties/pattern": {Pattern: "^a"}, + "Holder/properties/number": {Min: new(ir.BigVal("1")), Max: new(ir.BigVal("5"))}, + "Top": {MinLength: new(int64(1)), MaxLength: new(int64(8))}, + } + inBothOrders(t, enumBoundsHolder, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + requireErrorsAndWarnings(t, diags, nil) + for at, bounds := range want { + id := ir.TypeID("type/anonymous/components/schemas/" + at) + if at == "Top" { + id = componentID(at) + } + node := kindNode(t, doc, id) + assert.Equal(t, bounds, heldBoundsOf(node), "%s holds its bounds", at) + for _, key := range []string{"openapi:maxLength", "openapi:minLength", "openapi:pattern", "openapi:minimum", "openapi:maximum"} { + assert.NotContains(t, node.Common().Unmodeled, key, "%s keeps no bound", at) + } + assert.Empty(t, boundInfosAt(diags, "/components/schemas/"+at), "%s reports no kept bound", at) + } + holder := requireModelOf(t, doc, "Holder") + for _, property := range holder.Properties { + assert.Nil(t, property.Constraints, "the carrier %s holds no copy", property.WireName) + } + }) +} + +// TestEnumBounds_ABoundOfAnotherKindIsKeptAsAtTheBase holds the other half: a +// bound no value of the enum's kind is subject to stays kept degraded_lowering +// with one info, since a closed enum's members say nothing of it, and a carrier +// that owns no node, a $ref beside a bound, holds it as a use does. +func TestEnumBounds_ABoundOfAnotherKindIsKeptAsAtTheBase(t *testing.T) { + t.Parallel() + schemas := []string{ + "Items: {type: string, enum: [a, bb], maxItems: 3}", + "Unique: {type: string, enum: [revoke], uniqueItems: true}", + "Length: {type: integer, enum: [1, 2], maxLength: 5}", + "Mixed: {enum: [a, 1], minProperties: 1}", + "Comp: {type: string, enum: [a, bb]}", + "Use: {type: object, properties: {p: {$ref: '#/components/schemas/Comp', maxLength: 4}}}", + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + requireErrorsAndWarnings(t, diags, nil) + for name, key := range map[string]string{ + "Items": "openapi:maxItems", "Unique": "openapi:uniqueItems", "Length": "openapi:maxLength", "Mixed": "openapi:minProperties", + } { + node := kindNode(t, doc, componentID(name)) + assert.Nil(t, heldBoundsOf(node), "%s holds no bound of another kind", name) + assert.Equal(t, ir.ReasonDegradedLowering, node.Common().Unmodeled[key].Reason, "%s keeps %s", name, key) + assert.Len(t, boundInfosAt(diags, "/components/schemas/"+name), 1, "%s reports it once", name) + } + assert.Nil(t, heldBoundsOf(kindNode(t, doc, componentID("Comp")))) + property, ok := propertyByWire(requireModelOf(t, doc, "Use"), "p") + require.True(t, ok) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(4))}, property.Constraints, "a use's carrier holds what it writes") + }) +} + +// TestEnumBounds_TheGoldenModeTwinHoldsItsLength pins the golden spec's one +// enum whose bound of its kind moves: a string enum written with no type and a +// maxLength holds the length in its Constraints, so pass names the member the +// length refuses, while its two string enums writing a count keep it, as at +// the base. +func TestEnumBounds_TheGoldenModeTwinHoldsItsLength(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", + "firewall_components-schemas-mode: {description: The action to apply to a matched request., example: js_challenge, "+ + "enum: [block, challenge, js_challenge, managed_challenge], maxLength: 12}", + "traffic_exclusions: {type: array, items: {enum: [security_events], maxItems: 1, type: string}}", + "waitingroom_enabled_origin_commands: {type: array, items: {enum: [revoke], type: string, uniqueItems: true}, default: []}", + )) + requireErrorsAndWarnings(t, diags, nil) + mode, ok := kindNode(t, doc, componentID("firewall_components-schemas-mode")).(*ir.Enum) + require.True(t, ok) + assert.Equal(t, ir.PrimitiveString, mode.ValueType) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(12))}, mode.Constraints) + assert.NotContains(t, mode.Unmodeled, "openapi:maxLength") + found, err := pass.Validate(t.Context(), doc) + require.NoError(t, err) + requireErrorsAndWarnings(t, found, []wantFinding{{code: "pass/enum-member-outside-bounds", + pointer: "/components/schemas/firewall_components-schemas-mode", contains: []string{`"managed_challenge" by its maxLength`}}}) + for name, key := range map[string]string{ + "traffic_exclusions/items": "openapi:maxItems", "waitingroom_enabled_origin_commands/items": "openapi:uniqueItems", + } { + enum, ok := kindNode(t, doc, ir.TypeID("type/anonymous/components/schemas/"+name)).(*ir.Enum) + require.True(t, ok, name) + assert.Nil(t, enum.Constraints, name) + assert.Equal(t, ir.ReasonDegradedLowering, enum.Unmodeled[key].Reason, name) + } +} + +// TestEnumBounds_ValidateReadsAnEnumsBounds holds pass.Validate to the bounds +// an enum holds: an enum, closed or open, whose bounds cross admits no value; +// a default an open enum does not list is judged against its bounds, refused +// only past them; and a closed enum still refuses one it does not list. +func TestEnumBounds_ValidateReadsAnEnumsBounds(t *testing.T) { + t.Parallel() + doc, _ := compileUnrefused(t, admissionSpec("3.1.0", "", + "Open: {type: string, enum: [a, bb], x-extensible-enum: [a, bb], maxLength: 4}", + "Bare: {type: string, enum: [a, bb], x-extensible-enum: [a, bb]}", + "Closed: {type: string, enum: [a, bb], maxLength: 4}", + "Number: {type: integer, enum: [1, 2], x-extensible-enum: [1, 2], maximum: 5}", + "OpenCrossed: {type: string, enum: [a, bb], x-extensible-enum: [a, bb], minLength: 3, maxLength: 1}", + "ClosedCrossed: {type: string, enum: [a, bb], minLength: 3, maxLength: 1}", + "Holder: {type: object, properties: {"+ + "listed: {$ref: '#/components/schemas/Open', default: bb}, "+ + "within: {$ref: '#/components/schemas/Open', default: ccc}, "+ + "beyond: {$ref: '#/components/schemas/Open', default: ccccc}, "+ + "bare: {$ref: '#/components/schemas/Bare', default: anything}, "+ + "closedOut: {$ref: '#/components/schemas/Closed', default: ccc}, "+ + "numberWithin: {$ref: '#/components/schemas/Number', default: 3}, "+ + "numberBeyond: {$ref: '#/components/schemas/Number', default: 9}}}", + )) + found, err := pass.Validate(t.Context(), doc) + require.NoError(t, err) + const at = "/components/schemas/" + requireErrorsAndWarnings(t, found, []wantFinding{ + {code: "pass/bounds-admit-no-value", pointer: at + "OpenCrossed", contains: []string{"at least 3 characters and at most 1"}}, + {code: "pass/bounds-admit-no-value", pointer: at + "ClosedCrossed", contains: []string{"at least 3 characters and at most 1"}}, + {code: "pass/default-outside-type", pointer: at + "Holder/properties/beyond", contains: []string{"outside the bounds"}}, + {code: "pass/default-outside-type", pointer: at + "Holder/properties/numberBeyond", contains: []string{"outside the bounds"}}, + {code: "pass/default-outside-type", pointer: at + "Holder/properties/closedOut", contains: []string{"not a member"}}, + }) +} + +// TestEnumBounds_ValidateReadsAUnionOfLiteralsBounds holds pass.Validate to +// the bounds the union of literals a mixed enum lowers to holds, as its text +// twin's enum holds them: a default past the length draws +// pass/default-outside-type at a property naming either, written beside the +// $ref, on the component or inline, while a default within it, and a number, +// which no length judges, draw nothing. Each text twin's enum lists a member +// its length refuses, which draws pass/enum-member-outside-bounds. +func TestEnumBounds_ValidateReadsAUnionOfLiteralsBounds(t *testing.T) { + t.Parallel() + doc, _ := compileUnrefused(t, admissionSpec("3.1.0", "", + "Mixed: {enum: [ab, abc, 1], maxLength: 2}", + "Text: {type: string, enum: [ab, abc], maxLength: 2}", + "MixedDefaulted: {enum: [ab, abc, 1], maxLength: 2, default: abc}", + "TextDefaulted: {type: string, enum: [ab, abc], maxLength: 2, default: abc}", + "Holder: {type: object, properties: {"+ + "mixedPast: {$ref: '#/components/schemas/Mixed', default: abc}, "+ + "textPast: {$ref: '#/components/schemas/Text', default: abc}, "+ + "mixedWithin: {$ref: '#/components/schemas/Mixed', default: ab}, "+ + "mixedNumber: {$ref: '#/components/schemas/Mixed', default: 1}, "+ + "inlinePast: {enum: [ab, abc, 1], maxLength: 2, default: abc}, "+ + "inlineNumber: {enum: [ab, abc, 1], maxLength: 2, default: 1}, "+ + "mixedDefaulted: {$ref: '#/components/schemas/MixedDefaulted'}, "+ + "textDefaulted: {$ref: '#/components/schemas/TextDefaulted'}}}", + )) + _, isUnion := doc.Types["type/openapi/components/schemas/Mixed"].(*ir.Union) + require.True(t, isUnion, "the mixed enum lowers to a union of literals") + found, err := pass.Validate(t.Context(), doc) + require.NoError(t, err) + const at = "/components/schemas/Holder/properties/" + requireErrorsAndWarnings(t, found, []wantFinding{ + {code: "pass/enum-member-outside-bounds", pointer: "/components/schemas/Text", contains: []string{`"abc" by its maxLength`}}, + {code: "pass/enum-member-outside-bounds", pointer: "/components/schemas/TextDefaulted", contains: []string{`"abc" by its maxLength`}}, + {code: "pass/default-outside-type", pointer: at + "mixedPast"}, + {code: "pass/default-outside-type", pointer: at + "textPast", contains: []string{"outside the bounds"}}, + {code: "pass/default-outside-type", pointer: at + "inlinePast"}, + {code: "pass/default-outside-type", pointer: at + "mixedDefaulted"}, + {code: "pass/default-outside-type", pointer: at + "textDefaulted", contains: []string{"outside the bounds"}}, + }) +} + +// heldBoundsOf returns the Constraints node holds, for a kind that has the +// field, and nil for any other. +func heldBoundsOf(node ir.TypeDef) *ir.Constraints { + switch typed := node.(type) { + case *ir.Enum: + return typed.Constraints + case *ir.Union: + return typed.Constraints + case *ir.Scalar: + return typed.Constraints + default: + return nil + } +} + +// boundInfosAt returns the infos at pointer saying a position had no home for +// a keyword beside it. +func boundInfosAt(diags []ir.Diagnostic, pointer string) []string { + var out []string + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityInfo && diagnostic.Code == diag.DegradedConstruct && + string(diagnostic.Provenance.Pointer) == pointer && strings.Contains(diagnostic.Message, "no home for") { + out = append(out, diagnostic.Message) + } + } + return out +} diff --git a/compilers/openapi/e2e/external_content_test.go b/compilers/openapi/e2e/external_content_test.go index b3f9ba040..323d6252c 100644 --- a/compilers/openapi/e2e/external_content_test.go +++ b/compilers/openapi/e2e/external_content_test.go @@ -250,12 +250,19 @@ components: // a pointer names a position in that document, as such a $ref does, and so does // a defaultMapping. One that is a component's name is an implicit connection, // which the specification recommends resolving against the entry document, so -// it names the source's component. +// it names the source's component. Each target composes the discriminated +// schema, a subtype its routes keep typed. func TestExternalContent_AMappingNamesAsTheSpecificationSays(t *testing.T) { t.Parallel() + const d = "components/responses/D/content/application~1json/schema" dir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(dir, "ext.yaml"), []byte(foreignContent), 0o600)) - root := foreignRoot(" /op:\n get:\n responses: {\"200\": {$ref: './ext.yaml#/components/responses/D'}}\n") + // Each Thing composes the discriminated schema, so every route stays typed. + ext := strings.Replace(foreignContent, "Thing: {type: object, properties: {theirs: {type: string}}}", + "Thing: {allOf: [{$ref: '#/"+d+"'}], properties: {theirs: {type: string}}}", 1) + require.NoError(t, os.WriteFile(filepath.Join(dir, "ext.yaml"), []byte(ext), 0o600)) + root := strings.Replace(foreignRoot(" /op:\n get:\n responses: {\"200\": {$ref: './ext.yaml#/components/responses/D'}}\n"), + "Thing: {type: object, properties: {ours: {type: integer}}}", + "Thing: {allOf: [{$ref: './ext.yaml#/"+d+"'}], properties: {ours: {type: integer}}}", 1) doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: filepath.Join(dir, "root.yaml"), Data: []byte(root)}}, compilers.Options{Reader: reader.Disk{}, FormatOptions: openapi.Options{AllowExternalRefs: true}}) @@ -264,13 +271,14 @@ func TestExternalContent_AMappingNamesAsTheSpecificationSays(t *testing.T) { assert.False(t, slices.ContainsFunc(diags, func(diagnostic ir.Diagnostic) bool { return diagnostic.Code == "openapi/unresolved-ref" }), "every mapping value resolves: %+v", diags) - ext := ids.In("ext.yaml") - model, ok := doc.Types[ext.AnonymousType("/components/responses/D/content/application~1json/schema")].(*ir.Model) + model, ok := doc.Types[ids.In("ext.yaml").AnonymousType("/"+d)].(*ir.Model) require.True(t, ok, "the response's schema is lowered as a model, where ext.yaml declares it") require.NotNil(t, model.Discriminator) - theirs := ext.NamedType("/components/schemas/Thing") - assert.Equal(t, map[string]ir.TypeID{"byName": "type/openapi/components/schemas/Thing", "byRef": theirs}, - model.Discriminator.Mapping) + theirs := ids.In("ext.yaml").NamedType("/components/schemas/Thing") + ours := ir.TypeID("type/openapi/components/schemas/Thing") + assert.Equal(t, map[string]ir.TypeID{"byName": ours, "byRef": theirs}, model.Discriminator.Mapping) + assert.Equal(t, map[string]ir.TypeID{"Thing": ours}, model.Discriminator.DecodeOnlyRoutes, + "the entry document's Thing an entry routes is routed by its name too") assert.Equal(t, theirs, model.Discriminator.Default) } @@ -304,13 +312,15 @@ const sourceNamer = `paths: func TestExternalContent_ASourcePositionItNamesIsTheSources(t *testing.T) { t.Parallel() const ( - obj = "/paths/~1b/get/responses/200/content/application~1json/schema" - ref = "/paths/~1c/get/responses/200/content/application~1json/schema" + obj = "/paths/~1b/get/responses/200/content/application~1json/schema" + ref = "/paths/~1c/get/responses/200/content/application~1json/schema" + mapped = "/paths/~1x/get/responses/200/content/application~1json/schema" ) items := map[string]string{ "a": " /a: {$ref: './ext.yaml#/paths/~1x'}\n", "b": " /b:\n get:\n responses:\n \"200\":\n description: ok\n" + - " content: {application/json: {schema: {type: object, properties: {t: {$ref: '#/components/schemas/Thing'}}}}}\n", + " content: {application/json: {schema: {allOf: [{$ref: './ext.yaml#" + mapped + "'}], " + + "type: object, properties: {t: {$ref: '#/components/schemas/Thing'}}}}}\n", "c": " /c:\n get:\n responses:\n \"200\":\n description: ok\n" + " content: {application/json: {schema: {$ref: '#/components/schemas/Thing'}}}\n", } @@ -323,7 +333,10 @@ func TestExternalContent_ASourcePositionItNamesIsTheSources(t *testing.T) { } dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "ext.yaml"), []byte(sourceNamer), 0o600)) - root := foreignRoot(paths.String()) + // The object and the source's Thing compose the discriminated schema, + // so each route stays typed. + root := strings.Replace(foreignRoot(paths.String()), "Thing: {type: object, properties: {ours: {type: integer}}}", + "Thing: {allOf: [{$ref: './ext.yaml#"+mapped+"'}], properties: {ours: {type: integer}}}", 1) doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: filepath.Join(dir, "root.yaml"), Data: []byte(root)}}, compilers.Options{Reader: reader.Disk{}, FormatOptions: openapi.Options{AllowExternalRefs: true}}) @@ -413,16 +426,21 @@ func TestExternalContent_APointerPastItsRefNamesItsContent(t *testing.T) { assert.Equal(t, target, property.Type.Target, name) } } + // The mapping's row has ext.yaml's Pet compose the discriminated schema, a + // subtype its route keeps typed. + petUnderD := strings.Replace(passedContent, "Pet: {type: object, properties: {theirs: {type: string}}}", + "Pet: {allOf: [{$ref: 'root.yaml#/paths/~1d/get/responses/200/content/application~1json/schema'}], "+ + "properties: {theirs: {type: string}}}", 1) for _, c := range []struct { - name, item string - check func(t *testing.T, doc *ir.Document) + name, item, ext string + check func(t *testing.T, doc *ir.Document) }{ - {"an entry", " /b: {get: {responses: {\"200\": {$ref: '#/paths/~1a/get/responses/200'}}}}\n", objectReadsTheirs}, + {"an entry", " /b: {get: {responses: {\"200\": {$ref: '#/paths/~1a/get/responses/200'}}}}\n", passedContent, objectReadsTheirs}, {"a schema $ref", " /c: {get: {responses: {\"200\": {description: ok, content: " + - "{application/json: {schema: {$ref: '#" + object + "'}}}}}}}\n", objectReadsTheirs}, + "{application/json: {schema: {$ref: '#" + object + "'}}}}}}}\n", passedContent, objectReadsTheirs}, {"a mapping's read-through", " /d: {get: {responses: {\"200\": {description: ok, content: {application/json: " + "{schema: {type: object, properties: {k: {type: string}}, discriminator: {propertyName: k, " + - "mapping: {x: '#" + alias + "'}}}}}}}}}\n", func(t *testing.T, doc *ir.Document) { + "mapping: {x: '#" + alias + "'}}}}}}}}}\n", petUnderD, func(t *testing.T, doc *ir.Document) { t.Helper() model, ok := doc.Types[ir.TypeID("type/anonymous/paths/~1d/get/responses/200/content/application~1json/schema")].(*ir.Model) require.True(t, ok, "the mapping's schema is lowered as a model") @@ -438,7 +456,7 @@ func TestExternalContent_APointerPastItsRefNamesItsContent(t *testing.T) { // One directory for both orders, so that the reports naming ext.yaml // compare alike. dir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(dir, "ext.yaml"), []byte(passedContent), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "ext.yaml"), []byte(c.ext), 0o600)) for _, paths := range []string{c.item + a, a + c.item} { root := passingRoot(paths) doc, diags, err := openapi.New().Compile(t.Context(), @@ -697,7 +715,8 @@ func TestExternalContent_AnAliasedRefNamingTheSourceKeepsWhatItNames(t *testing. // #765), and a response schema under /paths a schema $ref names (GitHub #766). // Each resolved only where the source's own path item lowered it first, and // was reported unresolved otherwise; bound by position, each resolves in -// either declaration order, to the same document. +// either declaration order, to the same document. The raw YAML composes the +// discriminated schema, a subtype its route keeps typed. func TestExternalContent_ASourcePositionItNamesByFileResolvesInEitherOrder(t *testing.T) { t.Parallel() const schema = "/get/responses/200/content/application~1json/schema" @@ -718,7 +737,7 @@ func TestExternalContent_ASourcePositionItNamesByFileResolvesInEitherOrder(t *te type: object properties: {kind: {type: string}} discriminator: {propertyName: kind, mapping: {cat: 'root.yaml#/x-lib/Cat'}} -`, "x-lib:\n Cat: {type: object, properties: {meow: {type: string}}}\n", []string{ +`, "x-lib:\n Cat: {allOf: [{$ref: './ext.yaml#/paths/~1b" + schema + "'}], properties: {meow: {type: string}}}\n", []string{ " /b: {$ref: './ext.yaml#/paths/~1b'}\n", " /a:\n get:\n responses:\n \"200\":\n description: ok\n" + " content: {application/json: {schema: {$ref: '#/x-lib/Cat'}}}\n", @@ -905,13 +924,13 @@ components: } } -// TestExternalContent_APartFlagReadsTheFoldedType pins the order Finish +// TestExternalContent_APartFlagReadsTheTypeTheFoldSettlesOn pins the order Finish // settles in. A form body another document declares is built only once every // lowering has returned, after its part keys were queued, and its part `file` // is redeclared over a node built later still, so the fold waits too. The // part's HasFilename is read off the type that fold settles on, bytes; read // before it, the first declaration's string would leave the part unflagged. -func TestExternalContent_APartFlagReadsTheFoldedType(t *testing.T) { +func TestExternalContent_APartFlagReadsTheTypeTheFoldSettlesOn(t *testing.T) { t.Parallel() dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "lib.yaml"), []byte(`Form: @@ -985,42 +1004,45 @@ components: } } -// TestExternalContent_ARefinementReadsACopyInAnotherDocumentApart pins that a -// refinement's entry written as its target in another document writes it is -// no restatement, though it writes no $ref: what another document says is read -// in that document, whose dialect may differ -// (docs/compilers/openapi.md#openapi-versions). In the source, the same entry -// restates its target and is consumed. -func TestExternalContent_ARefinementReadsACopyInAnotherDocumentApart(t *testing.T) { +// TestExternalContent_ARefinementReadsACopyInAnotherDocumentInItsOwn pins that a +// refinement's entry written as its target in another document writes it, with +// no $ref, restates it where the two documents read schemas by one dialect, as +// in the source, and is consumed, but not where the other document is 3.0, +// whose dialect reads it otherwise (docs/compilers/openapi.md#openapi-versions), +// and then it is kept. +func TestExternalContent_ARefinementReadsACopyInAnotherDocumentInItsOwn(t *testing.T) { t.Parallel() - dir := t.TempDir() const words = "{type: array, items: {type: string, minLength: 1}}" - require.NoError(t, os.WriteFile(filepath.Join(dir, "other.yaml"), []byte( - "openapi: 3.1.0\ninfo: {title: O, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n W: "+words+"\n"), 0o600)) - root := "openapi: 3.1.0\ninfo: {title: T, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n W: " + words + "\n" + - " H:\n type: object\n properties:\n" + - " there: {allOf: [{$ref: './other.yaml#/components/schemas/W'}, " + words + "]}\n" + - " here: {allOf: [{$ref: '#/components/schemas/W'}, " + words + "]}\n" - path := filepath.Join(dir, "root.yaml") - require.NoError(t, os.WriteFile(path, []byte(root), 0o600)) + for version, keptThere := range map[string]bool{"3.1.0": false, "3.0.3": true} { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "other.yaml"), []byte( + "openapi: "+version+"\ninfo: {title: O, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n W: "+words+"\n"), 0o600)) + root := "openapi: 3.1.0\ninfo: {title: T, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n W: " + words + "\n" + + " H:\n type: object\n properties:\n" + + " there: {allOf: [{$ref: './other.yaml#/components/schemas/W'}, " + words + "]}\n" + + " here: {allOf: [{$ref: '#/components/schemas/W'}, " + words + "]}\n" + path := filepath.Join(dir, "root.yaml") + require.NoError(t, os.WriteFile(path, []byte(root), 0o600)) - doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: path, Data: []byte(root)}}, - compilers.Options{Reader: reader.Disk{}, FormatOptions: openapi.Options{AllowExternalRefs: true}}) + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: path, Data: []byte(root)}}, + compilers.Options{Reader: reader.Disk{}, FormatOptions: openapi.Options{AllowExternalRefs: true}}) - require.NoError(t, err) - openapitest.RequireNoErrorDiags(t, diags) - model, ok := doc.Types["type/openapi/components/schemas/H"].(*ir.Model) - require.True(t, ok) - properties := openapitest.PropertiesByWire(model.Properties) - assert.Contains(t, properties["there"].Unmodeled, "openapi:items", "the copy in another document is kept") - assert.Empty(t, properties["here"].Unmodeled, "the copy in the source restates its target") + require.NoError(t, err) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := doc.Types["type/openapi/components/schemas/H"].(*ir.Model) + require.True(t, ok) + properties := openapitest.PropertiesByWire(model.Properties) + _, kept := properties["there"].Unmodeled["openapi:items"] + assert.Equal(t, keptThere, kept, "%s: the copy in another document is kept", version) + assert.Empty(t, properties["here"].Unmodeled, "%s: the copy in the source restates its target", version) + } } // TestExternalContent_ACopyOfAnotherDocumentsComponentStaysApart pins a -// declaration written as the component in another document another -// declaration names: `#/components/schemas/A` names that document's A there -// and the source's here, so the copy is kept and reported. The source declares -// a schema at E's pointer too, which must not stand in for E's base. +// declaration written as the component in another document another declaration +// names: `#/components/schemas/A` names that document's A there and the +// source's here, so the copy is kept and reported. The source declares a schema +// at E's pointer too, which must not take the place of E's base. func TestExternalContent_ACopyOfAnotherDocumentsComponentStaysApart(t *testing.T) { t.Parallel() dir := t.TempDir() @@ -1048,7 +1070,7 @@ func TestExternalContent_ACopyOfAnotherDocumentsComponentStaysApart(t *testing.T // TestExternalContent_AMemberAnotherDocumentBringsIsNamedWithIt pins the report // on a member a $ref entry brings from another document: it sits where the -// declaration that lost is written, in that document, so it names that one by +// declaration passed over is written, in that document, so it names that one by // its pointer alone and the kept one, in the source, by its pointer and its // document, since the pointer alone would name a place in the report's. func TestExternalContent_AMemberAnotherDocumentBringsIsNamedWithIt(t *testing.T) { @@ -1072,8 +1094,8 @@ func TestExternalContent_AMemberAnotherDocumentBringsIsNamedWithIt(t *testing.T) assert.Equal(t, "openapi/conflicting-redeclaration", found[0].Code) require.Less(t, found[0].Provenance.Source, len(doc.Sources)) assert.Equal(t, "other.yaml", filepath.Base(doc.Sources[found[0].Provenance.Source].Path)) - assert.Regexp(t, `kept what the declaration at /components/schemas/R/allOf/1/properties/p in \S*root\.yaml `+ - `says over the one at /components/schemas/Base/properties/p,`, found[0].Message) + assert.Regexp(t, `: /components/schemas/R/allOf/1/properties/p in \S*root\.yaml and /components/schemas/Base/properties/p `+ + `disagree: incompatible types string and integer; chose what the first says;`, found[0].Message) } // TestExternalContent_ACopyInAnotherDocumentIsJudgedThere pins that the copy @@ -1157,10 +1179,10 @@ components: require.NoError(t, err) assert.Empty(t, diags) for _, tc := range []struct{ model, composed, mixin ir.TypeID }{ - {"type/openapi/components/schemas/F", "type/composed/components/schemas/F/allOf/1/properties/p", "type/openapi/components/schemas/A"}, + {"type/openapi/components/schemas/F", "type/composed/components/schemas/F/allOf/properties/p", "type/openapi/components/schemas/A"}, { "type/openapi@other.yaml/components/schemas/F", - "type/composed@other.yaml/components/schemas/F/allOf/1/properties/p", + "type/composed@other.yaml/components/schemas/F/allOf/properties/p", "type/openapi@other.yaml/components/schemas/A", }, } { @@ -1218,7 +1240,7 @@ components: want ir.PropertyID }{ {"type/openapi/components/schemas/F", "property/openapi/components/schemas/F/allOf/0/properties/p"}, - {"type/openapi@other.yaml/components/schemas/F", "property/composed@other.yaml/components/schemas/F/allOf/1/properties/p"}, + {"type/openapi@other.yaml/components/schemas/F", "property/composed@other.yaml/components/schemas/F/allOf/properties/p"}, } { model, ok := doc.Types[tc.model].(*ir.Model) require.True(t, ok, tc.model) diff --git a/compilers/openapi/e2e/fetched_reach_test.go b/compilers/openapi/e2e/fetched_reach_test.go index cb3863597..b4a2fa96e 100644 --- a/compilers/openapi/e2e/fetched_reach_test.go +++ b/compilers/openapi/e2e/fetched_reach_test.go @@ -24,7 +24,7 @@ const ( reachEvil = "https://pub.example/evil.yaml" reachSecret = "http://10.0.0.5/secret.yaml" - // reachRefusalPrivate is the verdict on a private address named by a + // reachRefusalPrivate is the answer on a private address named by a // document read from a public one. reachRefusalPrivate = "external document http://10.0.0.5/secret.yaml refused: it is at a private address, " + "which a reference in a document read from a public one does not reach" @@ -170,7 +170,7 @@ func TestCompile_APublicChainOfFetchedDocumentsReachesAsFarAsItGoes(t *testing.T }} doc, diags := compileFetched(t, reads, reachSource(" A: {$ref: 'https://pub.example/a.yaml#/X'}\n"), "") assert.Empty(t, diags) - assert.NotEmpty(t, fetchedTypeNamed(doc, "c.yaml/Z"), "every link resolves") + assert.NotEmpty(t, fetchedTypeNamed(doc, "c.yaml/Z"), "every hop resolves") assert.Equal(t, []compilers.AddressSpace{compilers.SpaceUnstated}, reads.servedAt("https://pub.example/a.yaml")) assert.Equal(t, []compilers.AddressSpace{compilers.SpacePublic}, reads.servedAt("https://pub.example/b.yaml")) assert.Equal(t, []compilers.AddressSpace{compilers.SpacePublic}, reads.servedAt("https://pub.example/c.yaml")) diff --git a/compilers/openapi/e2e/fold_identity_test.go b/compilers/openapi/e2e/fold_identity_test.go new file mode 100644 index 000000000..1656dde89 --- /dev/null +++ b/compilers/openapi/e2e/fold_identity_test.go @@ -0,0 +1,225 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/internal/harness" + "github.com/dexpace/morphic/ir" +) + +// requireSequenceOrderPasses holds spec to a sequence-order oracle that asked +// its question and found nothing: every allOf and required reversed, the +// document and its findings compare as the oracle compares them. +func requireSequenceOrderPasses(t *testing.T, spec string) { + t.Helper() + result := harness.Check(t.Context(), "spec.yaml", []byte(spec)) + for _, verdict := range result.Verdicts { + if verdict.Oracle != harness.OracleSequenceOrder { + continue + } + require.True(t, verdict.Asked(), "the oracle asked: %s", verdict.Declined) + assert.Equal(t, harness.OutcomeOK, verdict.Outcome, verdict.Detail) + return + } + require.Fail(t, "the sequence-order oracle gave no verdict") +} + +// TestFoldIdentity_AMintedNodeIsKeyedOnTheSchemaHoldingItsDeclarations holds +// GitHub #1992's reproduction: a node a fold of a model's own declarations +// mints sits at the narrowest schema holding them, then allOf/properties and +// the field's name, and what it settles and what it holds beneath it keep their +// suffixes, so one ID names one node whichever order the entries take. +func TestFoldIdentity_AMintedNodeIsKeyedOnTheSchemaHoldingItsDeclarations(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "Meeting: {type: object, properties: {id: {type: string}}}", + "S: {allOf: [{type: object, properties: {r: {type: object, properties: {a: {type: string}, x: {type: integer}}}}}, "+ + "{type: object, properties: {r: {type: object, properties: {b: {type: string}, x: {type: integer}}}}}]}", + "L: {allOf: [{type: object, properties: {data: {type: array, items: {$ref: '#/components/schemas/Meeting'}}}}, "+ + "{type: object, properties: {data: {type: array, items: {type: object, properties: {at: {type: string}}}}}}]}") + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, _ := compiledAndValidated(t, spec) + const minted = "type/composed/components/schemas/S/allOf/properties/r" + require.Equal(t, ir.TypeID(minted), componentMemberOf(t, doc, "S", "r").Type.Target) + model, ok := doc.Types[minted].(*ir.Model) + require.True(t, ok) + settled := make([]ir.PropertyID, 0, len(model.Properties)) + for _, property := range model.Properties { + settled = append(settled, property.ID) + } + assert.Equal(t, []ir.PropertyID{"property/composed/components/schemas/S/allOf/properties/r/allOf/allOf/properties/x"}, settled) + + const list = "type/composed/components/schemas/L/allOf/properties/data" + require.Equal(t, ir.TypeID(list), componentMemberOf(t, doc, "L", "data").Type.Target) + listNode, ok := doc.Types[list].(*ir.List) + require.True(t, ok) + assert.Equal(t, ir.TypeID(list+"/items"), listNode.ElementType.Target) + for id := range doc.Types { + assert.NotRegexp(t, `^type/composed/components/schemas/[SL]/allOf/[0-9]`, string(id), "no node carries an entry's index") + } + }) + requireSequenceOrderPasses(t, spec) +} + +// TestFoldIdentity_AMintedNodeTakesTheFieldsHint holds GitHub #1921's +// reproduction, the conformance case's TitledAndModel: a node for a field's +// declarations takes the field's name as its hint, never a declaration's title, +// and one minted beneath it the field's with its position's suffix, in either +// order of the entries. +func TestFoldIdentity_AMintedNodeTakesTheFieldsHint(t *testing.T) { + t.Parallel() + data, err := os.ReadFile(filepath.Join("..", "..", "..", "testdata", "conformance", "openapi", "allof-redeclared-models.yaml")) + require.NoError(t, err) + inBothAllOfOrders(t, string(data), func(t *testing.T, spec string) { + doc, _ := compiledAndValidated(t, spec) + for model, hints := range map[string]map[string]string{ + "TitledAndModel": {"": "data"}, + "ListsOfModels": {"": "data", "/items": "data_item"}, + "MapsOfModels": {"": "data", "/additionalProperties": "data_value"}, + } { + field := componentMemberOf(t, doc, model, "data").Type.Target + for suffix, hint := range hints { + node := doc.Types[field+ir.TypeID(suffix)] + require.NotNil(t, node, "%s.data%s", model, suffix) + assert.Equal(t, hint, node.Common().Name.Hint, "%s.data%s", model, suffix) + } + } + }) +} + +// TestFoldIdentity_APropertyKeepsAnOrderFreeIdentity holds GitHub #1931's +// reproduction: of a fold's declarations the property keeps the ID of the one +// whose pointer, its allOf indices erased, is shortest, here the declaration +// written directly in an entry, in either order. And it holds #2125's +// reproduction, recorded under #1931, to the sequence-order oracle. +func TestFoldIdentity_APropertyKeepsAnOrderFreeIdentity(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "X: {allOf: [{allOf: [{type: object, properties: {z: {type: string}}}, {type: object, properties: {q: {type: string}}}]}, "+ + "{type: object, properties: {q: {type: string}}}]}") + for spelling, want := range map[string]ir.PropertyID{ + spec: "property/openapi/components/schemas/X/allOf/1/properties/q", + allOfReversed(t, spec): "property/openapi/components/schemas/X/allOf/0/properties/q", + } { + doc, diags := compiledAndValidated(t, spelling) + assert.Equal(t, want, componentMemberOf(t, doc, "X", "q").ID) + assert.Empty(t, fieldComparisonReports(diags)) + } + + recorded := admissionSpec("3.0.3", "", + "D0: {type: object, properties: {p: {type: array, maxItems: 5, items: {type: string, maxLength: 3}, deprecated: true}}}", + "D1: {type: object, properties: {p: {type: array, maxItems: 5, items: {type: string, maxLength: 3}}}}", + "D3: {type: object, properties: {p: {type: array, minItems: 1, items: {type: string}}}}", + "D4: {type: object, properties: {p: {type: array, minItems: 1, items: {type: string}, description: da}}}", + "M0: {allOf: [{$ref: '#/components/schemas/D3'}, {$ref: '#/components/schemas/D4'}, "+ + "{$ref: '#/components/schemas/D1'}, {$ref: '#/components/schemas/D0'}]}") + var docs []ir.Docs + inBothAllOfOrders(t, recorded, func(t *testing.T, spec string) { + doc, _ := compiledAndValidated(t, spec) + docs = append(docs, doc.Types[componentMemberOf(t, doc, "M0", "p").Type.Target].Common().Docs) + }) + require.Len(t, docs, 2) + assert.Equal(t, docs[0], docs[1], "the member's node says the same in either order") + requireSequenceOrderPasses(t, recorded) +} + +// TestFoldSelection_AnIntersectionReusesAnyMemberItEquals holds GitHub #1866's +// reproduction: a list of the top type beside a list of a nullable alias +// intersects at the second, which holds everything the first says, so the field +// names that declaration's own list and nothing is minted, in either order. +func TestFoldSelection_AnIntersectionReusesAnyMemberItEquals(t *testing.T) { + t.Parallel() + for _, top := range []string{"{}", "{$ref: '#/components/schemas/Top'}"} { + spec := admissionSpec("3.1.0", "", + "Top: {}", + "E1: {type: string, enum: [a, b, c]}", + "NE1: {anyOf: [{$ref: '#/components/schemas/E1'}, {type: 'null'}]}", + "TopFirst: {allOf: [{type: object, properties: {v: {type: array, items: "+top+"}}}, "+ + "{type: object, properties: {v: {type: array, items: {$ref: '#/components/schemas/NE1'}}}}]}") + for spelling, at := range map[string]string{spec: "1", allOfReversed(t, spec): "0"} { + doc, diags := compiledAndValidated(t, spelling) + assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/TopFirst/allOf/"+at+"/properties/v"), + componentMemberOf(t, doc, "TopFirst", "v").Type.Target, "items %s", top) + for id := range doc.Types { + assert.NotContains(t, string(id), "type/composed/", "items %s: nothing is minted", top) + } + assert.Empty(t, fieldComparisonReports(diags), "items %s", top) + } + } +} + +// TestFoldSelection_ComposedModelsCompareTheirPartsAsASet holds GitHub #2123's +// reproduction: two models the merge composed of one set of parts are copies +// whatever order they list them in, so a third composing both takes the +// least of their nodes and mints nothing of its own, in either order and +// wherever the member reaches the composed models. +func TestFoldSelection_ComposedModelsCompareTheirPartsAsASet(t *testing.T) { + t.Parallel() + for name, reach := range map[string][2]string{ + "items": {"{type: array, minItems: 1, items: ", "}"}, + "additionalProperties": {"{type: object, additionalProperties: ", "}"}, + "a reference": {"", ""}, + } { + at := func(target string) string { + return reach[0] + "{$ref: '#/components/schemas/" + target + "'}" + reach[1] + } + spec := admissionSpec("3.0.3", "", + "X0: {type: object, properties: {s: {type: integer}}}", + "X1: {type: object, properties: {s: {type: string}}}", + "D0: {type: object, properties: {p: "+at("X1")+"}}", + "D1: {type: object, properties: {p: "+at("X0")+"}}", + "D2: {type: object, properties: {p: "+at("X0")+"}}", + "M0: {allOf: [{$ref: '#/components/schemas/D2'}, {$ref: '#/components/schemas/D0'}, {$ref: '#/components/schemas/D1'}]}", + "M1: {allOf: [{type: object, properties: {p: "+at("X0")+", s: {type: string, writeOnly: true}}}, {$ref: '#/components/schemas/D0'}]}", + "N: {allOf: [{$ref: '#/components/schemas/M0'}, {$ref: '#/components/schemas/M1'}]}") + t.Run(name, func(t *testing.T) { + t.Parallel() + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, _ := compiledAndValidated(t, spec) + assert.Equal(t, ir.TypeID("type/composed/components/schemas/M0/allOf/properties/p"), componentMemberOf(t, doc, "N", "p").Type.Target) + for id := range doc.Types { + assert.False(t, strings.HasPrefix(string(id), "type/composed/components/schemas/N/"), "%s: N mints nothing", id) + } + }) + requireSequenceOrderPasses(t, spec) + }) + } +} + +// TestSequenceOrder_ForgivesANodeAFoldMintsByItsKey holds GitHub #2124's two +// shapes to the sequence-order oracle: a node a tied member's fold mints by its +// composed key is forgiven wherever it sits relative to the member's pointer, +// whether it exists in one order only or holds in each what a reported tie +// decides, so a document whose differences all follow a reported tie passes. +func TestSequenceOrder_ForgivesANodeAFoldMintsByItsKey(t *testing.T) { + t.Parallel() + for name, spec := range map[string]string{ + "a node in one order only": admissionSpec("3.0.3", "", + "D0: {type: object, properties: {p: {type: string, format: uuid}}}", + "D2: {type: object, properties: {p: {type: string, format: uuid, deprecated: true}}}", + "D3: {type: object, properties: {p: {type: string, enum: [a, b, c], example: 7}}}", + "M0: {allOf: [{$ref: '#/components/schemas/D0'}, {$ref: '#/components/schemas/D2'}, "+ + "{type: object, properties: {p: {type: string, enum: [b, c, d], example: 7}, s: {type: string, minLength: 1}}}, "+ + "{$ref: '#/components/schemas/D3'}], properties: {p: {type: string, maxLength: 4, example: 7}}}"), + "a node holding what a tie decides": admissionSpec("3.0.3", "", + "X1: {type: object, required: [s, q, r]}", + "D0: {type: object, properties: {p: {type: array, minItems: 1, items: {type: object, properties: {q: {type: string, readOnly: true}}}, description: da}}}", + "M0: {allOf: [{$ref: '#/components/schemas/D0'}, "+ + "{type: object, properties: {p: {type: array, minItems: 1, items: {type: object, properties: {q: {type: string, description: two}}}, title: tb}}}], "+ + "properties: {p: {type: array, minItems: 1, items: {$ref: '#/components/schemas/X1'}}}}"), + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + requireSequenceOrderPasses(t, spec) + }) + } +} diff --git a/compilers/openapi/e2e/fold_judgment_test.go b/compilers/openapi/e2e/fold_judgment_test.go new file mode 100644 index 000000000..8bd320c03 --- /dev/null +++ b/compilers/openapi/e2e/fold_judgment_test.go @@ -0,0 +1,780 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "maps" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers" + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/engine/reader" + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/pass" +) + +// allOfReversed is spec with every allOf's entries in the opposite order, the +// one change JSON Schema gives no meaning to. +func allOfReversed(t *testing.T, spec string) string { + t.Helper() + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(spec), &root)) + stack := []*yaml.Node{&root} + for len(stack) > 0 { + node := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if node.Kind == yaml.MappingNode { + for i := 0; i+1 < len(node.Content); i += 2 { + if node.Content[i].Value == "allOf" && node.Content[i+1].Kind == yaml.SequenceNode { + slices.Reverse(node.Content[i+1].Content) + } + } + } + stack = append(stack, node.Content...) + } + out, err := yaml.Marshal(&root) + require.NoError(t, err) + return string(out) +} + +// inBothAllOfOrders runs check over spec as written and with every allOf +// reversed. +func inBothAllOfOrders(t *testing.T, spec string, check func(t *testing.T, spec string)) { + t.Helper() + t.Run("as written", func(t *testing.T) { check(t, spec) }) + t.Run("allOf reversed", func(t *testing.T) { check(t, allOfReversed(t, spec)) }) +} + +// compiledAndValidated is spec compiled, written to compile, and the findings +// of the compile and of pass.Validate over the document, as morphic compile +// reports both. +func compiledAndValidated(t *testing.T, spec string) (*ir.Document, []ir.Diagnostic) { + t.Helper() + doc, diags := compileUnrefused(t, spec) + validated, err := pass.Validate(t.Context(), doc) + require.NoError(t, err) + return doc, append(slices.Clone(diags), validated...) +} + +// componentMemberOf is the property of the model the component name declares +// whose wire name is wire. +func componentMemberOf(t *testing.T, doc *ir.Document, name, wire string) ir.Property { + t.Helper() + model, ok := doc.Types[ir.TypeID("type/openapi/components/schemas/"+name)].(*ir.Model) + require.True(t, ok, "%s is a model", name) + for _, property := range model.Properties { + if property.WireName == wire { + return property + } + } + require.Failf(t, "no member", "%s declares no %s", name, wire) + return ir.Property{} +} + +// fieldComparisonReports lists the findings of diags saying how declarations +// of a field compare, each as its code and pointer: a report about two, which +// lists the place whose say it kept, or a refusal of a value one gives. +func fieldComparisonReports(diags []ir.Diagnostic) []string { + var out []string + for _, diagnostic := range diags { + aboutTwo := slices.ContainsFunc(diagnostic.Related, func(related ir.Related) bool { return related.Role == ir.RelatedChosen }) + if aboutTwo || strings.Contains(diagnostic.Message, "the merge cannot show that the type its declarations merge to") { + out = append(out, diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + } + return out +} + +// chainEnd is the primitive kind the alias chain from ref ends at, and false +// where it ends at a node of another kind. +func chainEnd(doc *ir.Document, ref ir.TypeRef) (ir.PrimitiveKind, bool) { + for range len(doc.Types) + 1 { + switch node := doc.Types[ref.Target].(type) { + case *ir.Primitive: + return node.PrimitiveKind, true + case *ir.Scalar: + if node.Base == nil { + return "", false + } + ref = *node.Base + default: + return "", false + } + } + return "", false +} + +// TestFoldJudgment_NullAloneIsNarrowerThanAnythingAdmittingNull holds GitHub +// #1857's reproduction and its counterpart: a declaration admitting null +// alone, enum or const, is narrower than one admitting null, so the member +// takes its type with nothing reported in either order, and disjoint from one +// admitting no null, a conflict whose member takes the later declaration's +// type. +func TestFoldJudgment_NullAloneIsNarrowerThanAnythingAdmittingNull(t *testing.T) { + t.Parallel() + for _, nullOnly := range []string{"{enum: [null]}", "{const: null}"} { + spec := admissionSpec("3.1.0", "", + "A: {type: object, properties: {r: "+nullOnly+"}}", + `D: {allOf: [{$ref: '#/components/schemas/A'}, {type: object, properties: {r: {type: [string, "null"]}}}]}`, + `E: {allOf: [{type: object, properties: {r: {type: [string, "null"]}}}, {$ref: '#/components/schemas/A'}]}`, + "H: {allOf: [{$ref: '#/components/schemas/A'}, {type: object, properties: {r: {}}}]}", + "J: {allOf: [{$ref: '#/components/schemas/A'}, {type: object, properties: {r: {type: string}}}]}", + "K: {allOf: [{type: object, properties: {r: {type: string}}}, {$ref: '#/components/schemas/A'}]}") + doc, diags := compiledAndValidated(t, spec) + nullType := componentMemberOf(t, doc, "A", "r").Type + require.True(t, nullType.Nullable, "%s: a null-only declaration admits null through its reference", nullOnly) + for _, name := range []string{"D", "E", "H"} { + assert.Equal(t, nullType, componentMemberOf(t, doc, name, "r").Type, "%s: %s.r admits null alone", nullOnly, name) + } + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), componentMemberOf(t, doc, "J", "r").Type.Target, "%s: J.r, the later's", nullOnly) + assert.Equal(t, nullType, componentMemberOf(t, doc, "K", "r").Type, "%s: K.r, the later's", nullOnly) + var conflicts []string + for _, diagnostic := range diags { + if diagnostic.Code != diag.ConflictingRedecl { + continue + } + for _, related := range diagnostic.Related { + if related.Role == ir.RelatedDecided { + conflicts = append(conflicts, related.Provenance.Node) + } + } + } + slices.Sort(conflicts) + assert.Equal(t, []string{"property/openapi/components/schemas/J/allOf/1/properties/r", string(componentMemberOf(t, doc, "K", "r").ID)}, + conflicts, "%s: one conflict for each disjoint pair, none for a narrower one", nullOnly) + } +} + +// TestFoldJudgment_TwoValueSetsSharingOnlyNullIntersectAtNull holds GitHub +// #1894's reproduction: two declarations each admitting null beside a member +// the other does not list intersect at null alone, a closed enum of no member +// keyed on the declarations, behind a nullable reference, with nothing +// reported, in either order and at 3.0 too. +func TestFoldJudgment_TwoValueSetsSharingOnlyNullIntersectAtNull(t *testing.T) { + t.Parallel() + for version, sets := range map[string][2]string{ + "3.1.0": {"{enum: [a, null]}", "{enum: [b, null]}"}, + "3.0.3": {"{type: string, enum: [a], nullable: true}", "{type: string, enum: [b], nullable: true}"}, + } { + spec := admissionSpec(version, "", + "F: {allOf: [{type: object, properties: {f: "+sets[0]+"}}, {type: object, properties: {f: "+sets[1]+"}}]}") + t.Run(version, func(t *testing.T) { + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + member := componentMemberOf(t, doc, "F", "f") + assert.Equal(t, ir.TypeID("type/composed/components/schemas/F/allOf/properties/f"), member.Type.Target, version) + assert.True(t, member.Type.Nullable, version) + enum, ok := doc.Types[member.Type.Target].(*ir.Enum) + require.True(t, ok, "%s: the intersection is an enum", version) + assert.Empty(t, enum.Members, version) + assert.True(t, enum.Closed, version) + assert.Empty(t, fieldComparisonReports(diags), version) + for _, entry := range []string{"allOf/0/properties/f", "allOf/1/properties/f"} { + kept, held := enum.Unmodeled["openapi:"+entry] + if assert.True(t, held, "%s: the set at %s is kept on the enum", version, entry) { + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason, version) + assert.Equal(t, jsontext.Pointer("/components/schemas/F/"+entry), kept.Provenance.Pointer, version) + } + } + assert.Len(t, codedPointers(diags, diag.DegradedConstruct), 2, "%s: one info for each set kept", version) + }) + }) + } +} + +// TestFoldJudgment_NotesAndKeywordsSayingNothingDecideNothing holds GitHub +// #1889's, #2005's and #2040's reproductions, and two aliases of one type +// differing in their examples: the judgment compares what two declarations +// admit, so a note, a use-bound keyword or a keyword applying to none of the +// other side's kinds says nothing, one applying to the narrower kind intersects +// with it, and the member takes the same type in either order with no report. +func TestFoldJudgment_NotesAndKeywordsSayingNothingDecideNothing(t *testing.T) { + t.Parallel() + text, integer, uuid := ir.PrimitiveString, ir.PrimitiveInteger, ir.PrimitiveUUID + for _, tc := range []struct { + name, first, second string + want ir.PrimitiveKind + }{ + {"two strings keeping a minimum", "{type: string, minimum: 1}", "{type: string, minimum: 2}", text}, + {"a string and a bare items", "{type: string}", "{items: {type: string}}", text}, + {"a string and a bare prefixItems", "{type: string}", "{prefixItems: [{type: string}]}", text}, + {"an integer and a bare items", "{type: integer}", "{items: {type: string}}", integer}, + {"a string and a bare format of text", "{type: string}", "{format: uuid}", uuid}, + {"an integer and a union bounding only text", "{type: integer}", "{anyOf: [{type: string}, {type: integer}], maxLength: 5}", integer}, + } { + spec := admissionSpec("3.1.0", "", + "T: {allOf: [{type: object, properties: {p: "+tc.first+"}}, {type: object, properties: {p: "+tc.second+"}}]}") + t.Run(tc.name, func(t *testing.T) { + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + kind, ok := chainEnd(doc, componentMemberOf(t, doc, "T", "p").Type) + assert.True(t, ok, tc.name) + assert.Equal(t, tc.want, kind, tc.name) + assert.Empty(t, fieldComparisonReports(diags), tc.name) + }) + }) + } +} + +// TestFoldJudgment_AliasesDifferingInExamplesAreOneType holds the two folds of +// the golden spec's firewall_anomaly_package: aliases of string differing only +// in their examples are one type, the field taking the least target, with no +// overlap reported, in either order. +func TestFoldJudgment_AliasesDifferingInExamplesAreOneType(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "AName: {type: string, example: x, readOnly: true, description: the name}", + "Name: {type: string, example: y, readOnly: true, description: the name}", + "Def: {type: object, properties: {name: {$ref: '#/components/schemas/Name'}}}", + "Pkg: {allOf: [{$ref: '#/components/schemas/Def'}, {type: object, properties: {name: {$ref: '#/components/schemas/AName'}}}]}") + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/AName"), componentMemberOf(t, doc, "Pkg", "name").Type.Target) + assert.Empty(t, fieldComparisonReports(diags)) + }) +} + +// TestFoldJudgment_AlikeNodesDeclaredApartNameTheOneWrittenFirst holds which +// of two nodes alike, declared apart, a fold names: the one whose pointer +// sorts first token by token (provenance.ComparePointers), in either order of +// the declarations, not the one whose ID sorts first: an index-like name is +// read as a number, and a component written before the schema holding a +// node another declaration reaches is named over it. +func TestFoldJudgment_AlikeNodesDeclaredApartNameTheOneWrittenFirst(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name, first, second string + want ir.TypeID + }{ + {"two components named by numbers", "'#/components/schemas/10'", "'#/components/schemas/9'", + "type/openapi/components/schemas/9"}, + {"a component and a node within another", "'#/components/schemas/A'", "'#/components/schemas/B/properties/p'", + "type/openapi/components/schemas/A"}, + } { + spec := admissionSpec("3.1.0", "", + "'10': {type: string, maxLength: 3}", "'9': {type: string, maxLength: 3}", + "A: {type: string, maxLength: 3}", "B: {type: object, properties: {p: {type: string, maxLength: 3}}}", + "T: {allOf: [{type: object, properties: {f: {$ref: "+tc.first+"}}}, {type: object, properties: {f: {$ref: "+tc.second+"}}}]}") + t.Run(tc.name, func(t *testing.T) { + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + member := componentMemberOf(t, doc, "T", "f") + assert.Equal(t, tc.want, member.Type.Target) + assert.Len(t, member.Unmodeled, 1, "the other declaration is kept") + assert.Empty(t, fieldComparisonReports(diags)) + }) + }) + } +} + +// TestFoldJudgment_AlikeNodesIntersectingAnotherKeepTheOneNotNamed holds a +// declaration naming a node declared apart that admits what the node the field +// names does, beside a third declaration both intersect: the intersection names +// the one written first of the two, and keeps the other's declaration verbatim +// with one info, in every order of the three, whichever declaration's type is +// chosen. +func TestFoldJudgment_AlikeNodesIntersectingAnotherKeepTheOneNotNamed(t *testing.T) { + t.Parallel() + entries := map[string]string{ + "top": "{type: object, properties: {v: {type: array, items: {}}}}", + "10": "{type: object, properties: {v: {$ref: '#/components/schemas/10'}}}", + "9": "{type: object, properties: {v: {$ref: '#/components/schemas/9'}}}", + } + for _, order := range [][3]string{{"top", "10", "9"}, {"top", "9", "10"}, {"10", "top", "9"}, {"10", "9", "top"}, + {"9", "top", "10"}, {"9", "10", "top"}} { + spec := admissionSpec("3.1.0", "", + "E1: {type: string, enum: [a, b, c]}", + "NE1: {anyOf: [{$ref: '#/components/schemas/E1'}, {type: 'null'}]}", + "'10': {type: array, items: {$ref: '#/components/schemas/NE1'}}", + "'9': {type: array, items: {$ref: '#/components/schemas/NE1'}}", + "T: {allOf: ["+entries[order[0]]+", "+entries[order[1]]+", "+entries[order[2]]+"]}") + doc, diags := compiledAndValidated(t, spec) + member := componentMemberOf(t, doc, "T", "v") + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/9"), member.Type.Target, "%v", order) + kept := "allOf/" + strconv.Itoa(slices.Index(order[:], "10")) + "/properties/v" + assert.Equal(t, []string{"openapi:" + kept}, slices.Collect(maps.Keys(member.Unmodeled)), "%v: the declaration naming 10 is kept", order) + assert.Equal(t, []string{"/components/schemas/T/" + kept}, codedPointers(diags, diag.DegradedConstruct), "%v", order) + } +} + +// TestFoldJudgment_AlikeComponentsUnderTwoBasesOverlap holds the limit of that +// reading: two components written alike, each keeping a not whose $ref reads +// against its own document's base, may name two schemas, so nothing shows +// they admit the same values and they overlap as at the base, in either +// order: the field keeps the later and the earlier declaration is kept and +// reported. +func TestFoldJudgment_AlikeComponentsUnderTwoBasesOverlap(t *testing.T) { + t.Parallel() + dir := t.TempDir() + const written = "{type: string, not: {$ref: '#/components/schemas/A'}}" + require.NoError(t, os.WriteFile(filepath.Join(dir, "other.yaml"), []byte("openapi: 3.1.0\ninfo: {title: O, version: \"1\"}\n"+ + "paths: {}\ncomponents:\n schemas:\n A: {type: string, maxLength: 1}\n N: "+written+"\n"), 0o600)) + local, other := "{$ref: '#/components/schemas/N'}", "{$ref: './other.yaml#/components/schemas/N'}" + for _, order := range [][2]string{{local, other}, {other, local}} { + root := "openapi: 3.1.0\ninfo: {title: T, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n" + + " A: {type: string, minLength: 5}\n N: " + written + "\n S:\n allOf:\n" + + " - {type: object, properties: {x: " + order[0] + "}}\n" + + " - {type: object, properties: {x: " + order[1] + "}}\n" + path := filepath.Join(dir, "root.yaml") + require.NoError(t, os.WriteFile(path, []byte(root), 0o600)) + + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: path, Data: []byte(root)}}, + compilers.Options{Reader: reader.Disk{}, FormatOptions: openapi.Options{AllowExternalRefs: true}}) + + require.NoError(t, err) + openapitest.RequireNoErrorDiags(t, diags) + later := ir.TypeID("type/openapi/components/schemas/N") + if order[1] == other { + later = "type/openapi@other.yaml/components/schemas/N" + } + got := componentMemberOf(t, doc, "S", "x") + assert.Equal(t, later, got.Type.Target, "%v: the later", order) + assert.Contains(t, got.Unmodeled, "openapi:conflicting-redeclaration/components/schemas/S/allOf/0/properties/x", "%v", order) + assert.Equal(t, []string{"openapi/degraded-construct /components/schemas/S/allOf/0/properties/x"}, fieldComparisonReports(diags), "%v", order) + } +} + +// TestFoldJudgment_TwoUnionsAlikeIntersectTheirBounds holds GitHub #2041's +// reproduction: two declarations of one union, each with a bound beside it, are +// one type holding the intersection of both bounds, as two scalars of one base +// are, in either order, with nothing reported. +func TestFoldJudgment_TwoUnionsAlikeIntersectTheirBounds(t *testing.T) { + t.Parallel() + union := "{oneOf: [{type: string}, {type: integer}]" + for _, tc := range []struct { + name string + first, second string + want *ir.Constraints + }{ + {"a minimum and a maximum", union + ", minLength: 2}", union + ", maxLength: 8}", &ir.Constraints{MinLength: new(int64(2)), MaxLength: new(int64(8))}}, + {"two minimums", union + ", minLength: 4}", union + ", minLength: 2}", &ir.Constraints{MinLength: new(int64(4))}}, + {"one bounded", union + ", minLength: 2}", union + "}", &ir.Constraints{MinLength: new(int64(2))}}, + } { + spec := admissionSpec("3.1.0", "", + "T: {allOf: [{type: object, properties: {p: "+tc.first+"}}, {type: object, properties: {p: "+tc.second+"}}]}") + t.Run(tc.name, func(t *testing.T) { + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + node, ok := doc.Types[componentMemberOf(t, doc, "T", "p").Type.Target].(*ir.Union) + require.True(t, ok, "%s: the member is the union", tc.name) + assert.Equal(t, tc.want, node.Constraints, tc.name) + assert.Empty(t, fieldComparisonReports(diags), tc.name) + }) + }) + } +} + +// TestFoldJudgment_ReadsNotAndIfAsTheKindsTheyAdmit holds GitHub #1671's +// reproduction: a structure refusing some kinds only through a not of a type, +// a union or an if, read through its allOf, beside an integer declaration, in +// either order. One admitting every integer makes the integer narrower, with +// nothing reported; one admitting none is a conflict; one admitting some, an +// overlap. An if is read per kind: one holding for every integer sends each to +// its then, one holding for none to its else, and one holding for some to +// either. +func TestFoldJudgment_ReadsNotAndIfAsTheKindsTheyAdmit(t *testing.T) { + t.Parallel() + const narrower = "" + rows := []struct{ holder, source, written, want string }{ + {"T", "NotStr", "{not: {type: string}}", narrower}, + {"U", "ObjOrInt", "{anyOf: [{type: object}, {type: integer}]}", narrower}, + {"V", "ObjElseInt", "{if: {required: [k]}, then: {type: object}, else: {type: integer}}", diag.ConflictingRedecl}, + {"W", "NotInt", "{not: {type: integer}}", diag.ConflictingRedecl}, + {"X", "IntUnderThree", "{if: {minimum: 3}, then: {type: object}, else: {type: integer}}", diag.DegradedConstruct}, + {"Y", "StrElseInt", "{if: {type: string}, then: {type: string}, else: {type: integer}}", narrower}, + {"Z", "ObjUnlessStr", "{if: {type: string}, then: {type: integer}, else: {type: object}}", diag.ConflictingRedecl}, + } + schemas := make([]string, 0, 2*len(rows)) + want := make([]string, 0, len(rows)) + for _, row := range rows { + structure := "{allOf: [{$ref: '#/components/schemas/" + row.source + "'}], properties: {a: {type: string}}}" + schemas = append(schemas, row.source+": "+row.written, + row.holder+": {allOf: [{properties: {f: {type: integer}}}, {properties: {f: "+structure+"}}]}") + if row.want != narrower { + want = append(want, row.want+" /components/schemas/"+row.holder+"/allOf/0/properties/f") + } + } + inBothAllOfOrders(t, admissionSpec("3.1.0", "", schemas...), func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + for _, row := range rows { + if row.want == narrower { + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInteger), componentMemberOf(t, doc, row.holder, "f").Type.Target, row.holder) + } + } + assert.Equal(t, want, fieldComparisonReports(diags)) + }) +} + +// TestFoldJudgment_AFieldsCompositionChoosesItsBaseAsAWrittenAllOfDoes holds +// GitHub #1901's reproduction: a member redeclared as two models composes them +// as a written allOf of them does, its Base the one whose source takes part in +// a discriminator hierarchy, though that one lowers to a union holding no +// discriminator, in either order. +func TestFoldJudgment_AFieldsCompositionChoosesItsBaseAsAWrittenAllOfDoes(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "A: {type: object, required: [kind], properties: {kind: {type: string}, a: {type: string}}}", + "B: {type: object, required: [kind], properties: {kind: {type: string}, b: {type: string}}}", + "S: {type: object, properties: {s: {type: string}}}", + "T: {type: object, properties: {t: {type: string}}}", + "URoot: {oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}], discriminator: {propertyName: kind}}", + "Y: {allOf: [{$ref: '#/components/schemas/URoot'}], oneOf: [{$ref: '#/components/schemas/S'}, {$ref: '#/components/schemas/T'}]}", + "Other: {type: object, properties: {x: {type: string}}}", + "Written: {allOf: [{$ref: '#/components/schemas/Other'}, {$ref: '#/components/schemas/Y'}]}", + "Holder: {allOf: [{type: object, properties: {p: {$ref: '#/components/schemas/Other'}}}, {type: object, properties: {p: {$ref: '#/components/schemas/Y'}}}]}") + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, _ := compiledAndValidated(t, spec) + written, ok := doc.Types["type/openapi/components/schemas/Written"].(*ir.Model) + require.True(t, ok) + require.NotNil(t, written.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Y"), written.Base.Target) + minted, ok := doc.Types[componentMemberOf(t, doc, "Holder", "p").Type.Target].(*ir.Model) + require.True(t, ok, "the member is a model composing both") + require.NotNil(t, minted.Base, "it chooses a Base as Written does") + assert.Equal(t, written.Base.Target, minted.Base.Target) + assert.Equal(t, []ir.TypeRef{{Target: "type/openapi/components/schemas/Other"}}, minted.Mixins) + }) +} + +// TestValueAdmission_PassJudgesAPositionByItsTypeAndItsOwnBounds holds pass +// to the value admission reader at a position: the default an int32 range, a +// date's grammar, a step, uniqueItems, an element type or a minimum refuses +// is reported at its property, each judged against the type and the bounds +// written beside it, and the nearest one each admits is not. +func TestValueAdmission_PassJudgesAPositionByItsTypeAndItsOwnBounds(t *testing.T) { + t.Parallel() + refused := map[string]string{ + "i32": "{type: integer, format: int32, default: 3000000000}", + "step": "{type: integer, multipleOf: 2, default: 3}", + "date": "{type: string, format: date, default: '2020-13-45'}", + "uniq": "{type: array, items: {type: integer}, uniqueItems: true, default: [1, 1]}", + "items": "{type: array, items: {type: integer}, default: [a]}", + "min": "{type: integer, minimum: 0, default: -1}", + } + admitted := map[string]string{ + "i32": "{type: integer, format: int32, default: 2147483647}", + "step": "{type: integer, multipleOf: 2, default: 4}", + "date": "{type: string, format: date, default: '2020-12-31'}", + "uniq": "{type: array, items: {type: integer}, uniqueItems: true, default: [1, 2]}", + "items": "{type: array, items: {type: integer}, default: [1]}", + "min": "{type: integer, minimum: 0, default: 0}", + } + members := func(properties map[string]string) string { + written := make([]string, 0, len(properties)) + for _, name := range slices.Sorted(maps.Keys(properties)) { + written = append(written, name+": "+properties[name]) + } + return "{type: object, properties: {" + strings.Join(written, ", ") + "}}" + } + _, diags := compiledAndValidated(t, admissionSpec("3.1.0", "", "Refused: "+members(refused), "Admitted: "+members(admitted))) + want := make([]string, 0, len(refused)) + for _, name := range slices.Sorted(maps.Keys(refused)) { + want = append(want, "/components/schemas/Refused/properties/"+name) + } + got := codedPointers(diags, "pass/default-outside-type") + slices.Sort(got) + assert.Equal(t, want, got) +} + +// TestValueAdmission_ACycleOfUnionsJudgesAlikeWhereverItIsEntered holds the +// union cycle A anyOf [B, C], B anyOf [A, integer], C anyOf [B, string]: a +// default judged through A and through C draws the same answer, and the two +// orders of a union over A and C do too. +func TestValueAdmission_ACycleOfUnionsJudgesAlikeWhereverItIsEntered(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "A: {anyOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/C'}]}", + "B: {anyOf: [{$ref: '#/components/schemas/A'}, {type: integer}]}", + "C: {anyOf: [{$ref: '#/components/schemas/B'}, {type: string}]}", + "P: {type: object, properties: {"+strings.Join([]string{ + "viaA: {$ref: '#/components/schemas/A', default: x}", + "viaC: {$ref: '#/components/schemas/C', default: x}", + "ac: {anyOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/C'}], default: true}", + "ca: {anyOf: [{$ref: '#/components/schemas/C'}, {$ref: '#/components/schemas/A'}], default: true}", + }, ", ")+"}}") + _, diags := compiledAndValidated(t, spec) + refused := map[string]bool{} + for _, diagnostic := range diags { + if diagnostic.Code == "pass/default-outside-type" { + refused[strings.TrimPrefix(diagnostic.Provenance.Node, "property/openapi/components/schemas/P/properties/")] = true + } + } + assert.Equal(t, refused["viaA"], refused["viaC"], "entered at A or at C: %v", refused) + assert.Equal(t, refused["ac"], refused["ca"], "either variant order: %v", refused) + assert.Empty(t, refused, "each member of a cycle answers unknown, so nothing is refused") +} + +// TestFoldJudgment_AHierarchyIsReadInTheDeclarationsOwnDocument holds GitHub +// #1901's shape with the declarations another document writes: whether a +// declaration takes part in a discriminator hierarchy is read where it is +// written, so the field composes as in one document, its Base the union the +// source composes a hierarchy through, in either order of the entries. +func TestFoldJudgment_AHierarchyIsReadInTheDeclarationsOwnDocument(t *testing.T) { + t.Parallel() + const other = `openapi: 3.1.0 +info: {title: o, version: "1"} +paths: {} +components: + schemas: + A: {type: object, required: [kind], properties: {kind: {type: string}, a: {type: string}}} + B: {type: object, required: [kind], properties: {kind: {type: string}, b: {type: string}}} + S: {type: object, properties: {s: {type: string}}} + T: {type: object, properties: {t: {type: string}}} + URoot: {oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}], discriminator: {propertyName: kind}} + Y: {allOf: [{$ref: '#/components/schemas/URoot'}], oneOf: [{$ref: '#/components/schemas/S'}, {$ref: '#/components/schemas/T'}]} + Other: {type: object, properties: {x: {type: string}}} + HOther: {type: object, properties: {p: {$ref: '#/components/schemas/Other'}}} + HY: {type: object, properties: {p: {$ref: '#/components/schemas/Y'}}} +` + main := admissionSpec("3.1.0", "", + "Holder: {allOf: [{$ref: './other.yaml#/components/schemas/HOther'}, {$ref: './other.yaml#/components/schemas/HY'}]}") + inBothAllOfOrders(t, main, func(t *testing.T, spec string) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "other.yaml"), []byte(other), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.yaml"), []byte(spec), 0o600)) + doc, diags := compileDir(t, dir, openapi.Options{}) + openapitest.RequireNoErrorDiags(t, diags) + minted, ok := doc.Types[componentMemberOf(t, doc, "Holder", "p").Type.Target].(*ir.Model) + require.True(t, ok, "the member is a model composing both") + require.NotNil(t, minted.Base, "it chooses a Base as one document does") + assert.Equal(t, ir.TypeID("type/openapi@other.yaml/components/schemas/Y"), minted.Base.Target) + assert.Equal(t, []ir.TypeRef{{Target: "type/openapi@other.yaml/components/schemas/Other"}}, minted.Mixins) + }) +} + +// TestFoldJudgment_AKeptEntryIsJudgedByTheFoldsSourceFormat holds the fold's +// source format over what the base judged typed: a length kept beside a +// uuid is read by its keyword, a default it admits adopted and one it refuses +// reported and kept, and a kept pattern, which it cannot read, refuses +// nothing, in either order of the entries. +func TestFoldJudgment_AKeptEntryIsJudgedByTheFoldsSourceFormat(t *testing.T) { + t.Parallel() + const id = "'00000000-0000-0000-0000-000000000000'" + field := func(name, kept string) string { + return name + ": {allOf: [{type: object, properties: {p: {type: string, format: uuid, " + kept + "}}}, " + + "{type: object, properties: {p: {type: string, format: uuid, default: " + id + "}}}]}" + } + spec := admissionSpec("3.1.0", "", + field("LengthMet", "maxLength: 40"), + field("LengthBroken", "minLength: 37"), + field("Pattern", "pattern: '^0'")) + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + for name, adopted := range map[string]bool{"LengthMet": true, "LengthBroken": false, "Pattern": true} { + member := componentMemberOf(t, doc, name, "p") + assert.Equal(t, adopted, member.Default != nil, "%s: the default is adopted", name) + assert.Equal(t, map[bool]int{true: 0, false: 1}[adopted], + infosAt(diags, diag.DegradedConstruct, "/components/schemas/"+name, "admits the default"), "%s: and reported where not", name) + } + }) +} + +// TestFoldJudgment_ADefaultItsFieldsEnumBoundRefusesIsNotAdopted holds the +// fold to the value admission reader on a member another declaration types +// with an enum whose own bound refuses one of its members: the default 2 a +// declaration writes alone is not adopted, and is reported and kept, in +// either order of the entries, so pass finds no default to report. +func TestFoldJudgment_ADefaultItsFieldsEnumBoundRefusesIsNotAdopted(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "E: {type: integer, enum: [1, 2], maximum: 1}", + "X: {allOf: [{properties: {p: {$ref: '#/components/schemas/E'}}}, {properties: {p: {default: 2}}}]}") + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + member := componentMemberOf(t, doc, "X", "p") + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/E"), member.Type.Target) + assert.Nil(t, member.Default, "the default the enum's bound refuses") + assert.Equal(t, 1, infosAt(diags, diag.DegradedConstruct, "/components/schemas/X", "admits the default")) + assert.Empty(t, codedPointers(diags, "pass/default-outside-type")) + }) +} + +// TestFoldJudgment_AValueItsOwnTypeRefusesIsNotAdopted holds the fold to the +// value admission reader where a declaration writes a value beside the type +// the field keeps: a default the enum's own bound or a pattern the reader reads +// refuses is not adopted, and is reported and kept, while one only a pattern +// the reader cannot read might refuse is adopted, in either order of the +// entries. +func TestFoldJudgment_AValueItsOwnTypeRefusesIsNotAdopted(t *testing.T) { + t.Parallel() + field := func(name, target, value string) string { + ref := "$ref: '#/components/schemas/" + target + "'" + return name + ": {allOf: [{properties: {p: {" + ref + ", default: " + value + "}}}, {properties: {p: {" + ref + "}}}]}" + } + spec := admissionSpec("3.1.0", "", + "E: {type: integer, enum: [1, 2], maximum: 1}", + "S: {type: string, pattern: '^(?=a)'}", + "P: {type: string, pattern: '^a'}", + field("Refused", "E", "2"), + field("PatternRefused", "P", "b"), + field("Unjudged", "S", "b")) + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + refused := componentMemberOf(t, doc, "Refused", "p") + assert.Nil(t, refused.Default, "the default the enum's bound refuses") + assert.Equal(t, 1, infosAt(diags, diag.DegradedConstruct, "/components/schemas/Refused", "admits the default")) + assert.Len(t, refused.Unmodeled, 1, "the declaration writing it is kept") + patternRefused := componentMemberOf(t, doc, "PatternRefused", "p") + assert.Nil(t, patternRefused.Default, "the default a pattern the reader reads refuses") + assert.Equal(t, 1, infosAt(diags, diag.DegradedConstruct, "/components/schemas/PatternRefused", "admits the default")) + assert.Len(t, patternRefused.Unmodeled, 1, "the declaration writing it is kept") + unjudged := componentMemberOf(t, doc, "Unjudged", "p") + assert.Equal(t, &ir.Value{Kind: ir.ValueString, String: "b"}, unjudged.Default, "a default only a pattern might refuse") + assert.Zero(t, infosAt(diags, diag.DegradedConstruct, "/components/schemas/Unjudged", "admits the default")) + assert.Empty(t, codedPointers(diags, "pass/default-outside-type")) + }) +} + +// TestFoldJudgment_ABroaderDeclarationsOwnBoundJudgesItsValue holds a value a +// declaration broader than the field's type writes to the bound it states on its +// property as to the same bound on its own node, in either order of the entries. +// On the node the bound makes that type the narrower, so the field keeps it; on +// the property the field keeps the other's type. Either way a length or a +// pattern refusing the value keeps it off the field, reported at the +// declaration, and a pattern outside the subset the reader reads does not. +func TestFoldJudgment_ABroaderDeclarationsOwnBoundJudgesItsValue(t *testing.T) { + t.Parallel() + field := func(name, valued string) string { + return name + ": {allOf: [{properties: {p: {$ref: '#/components/schemas/Host'}}}, {properties: {p: {" + valued + ", default: abc}}}]}" + } + spec := admissionSpec("3.1.0", "", + "Host: {type: string, description: a host name}", + "ShortText: {type: string, maxLength: 2}", + "PrefixedText: {type: string, pattern: '^x'}", + "LookaheadText: {type: string, pattern: '^(?=x)'}", + field("LengthOnNode", "$ref: '#/components/schemas/ShortText'"), + field("LengthOnProperty", "type: string, maxLength: 2"), + field("PatternOnNode", "$ref: '#/components/schemas/PrefixedText'"), + field("PatternOnProperty", "type: string, pattern: '^x'"), + field("UnreadOnNode", "$ref: '#/components/schemas/LookaheadText'"), + field("UnreadOnProperty", "type: string, pattern: '^(?=x)'")) + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + host := ir.TypeID("type/openapi/components/schemas/Host") + assert.Equal(t, host, componentMemberOf(t, doc, "LengthOnProperty", "p").Type.Target, "the field keeps the narrower type") + assert.Equal(t, host, componentMemberOf(t, doc, "PatternOnProperty", "p").Type.Target, "the field keeps the narrower type") + assert.Equal(t, host, componentMemberOf(t, doc, "UnreadOnProperty", "p").Type.Target, "the field keeps the narrower type") + for name, taken := range map[string]*ir.Value{ + "LengthOnNode": nil, "LengthOnProperty": nil, + "PatternOnNode": nil, "PatternOnProperty": nil, + "UnreadOnNode": {Kind: ir.ValueString, String: "abc"}, "UnreadOnProperty": {Kind: ir.ValueString, String: "abc"}, + } { + assert.Equal(t, taken, componentMemberOf(t, doc, name, "p").Default, name) + refusals := 0 + if taken == nil { + refusals = 1 + } + assert.Equal(t, refusals, infosAt(diags, diag.DegradedConstruct, "/components/schemas/"+name, "admits the default"), name) + } + assert.Empty(t, codedPointers(diags, "pass/default-outside-type")) + }) +} + +// TestFoldJudgment_AValueInAUnionIsCountedAcrossItsVariants holds a default +// written beside a union to each variant's own bounds, those a variant writes +// beside its $ref included, counted across the variants, in either order of +// the entries: a oneOf refuses a value two variants admit or none does, and +// takes one exactly one admits while every other refuses it; one a variant's +// pattern leaves unknown is not refused; an anyOf takes a value any variant +// admits. +func TestFoldJudgment_AValueInAUnionIsCountedAcrossItsVariants(t *testing.T) { + t.Parallel() + ref := func(target string) string { return "$ref: '#/components/schemas/" + target + "'" } + field := func(name, union, value string) string { + return name + ": {allOf: [{properties: {p: {" + ref(union) + ", default: " + value + "}}}, {properties: {p: {" + ref(union) + "}}}]}" + } + spec := admissionSpec("3.1.0", "", + "Text: {type: string, description: text}", + "One: {oneOf: [{"+ref("Text")+", maxLength: 5}, {"+ref("Text")+", minLength: 3}]}", + "Any: {anyOf: [{"+ref("Text")+", maxLength: 5}, {"+ref("Text")+", minLength: 3}]}", + "OnePattern: {oneOf: [{type: string, pattern: '^a'}, {type: integer}]}", + field("OneTwoAdmit", "One", "abcd"), + field("OneOneAdmits", "One", "ab"), + field("AnyTwoAdmit", "Any", "abcd"), + field("OneNoneAdmits", "OnePattern", "true"), + field("OneUnknown", "OnePattern", "abc")) + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + for name, taken := range map[string]*ir.Value{ + "OneTwoAdmit": nil, + "OneOneAdmits": {Kind: ir.ValueString, String: "ab"}, + "AnyTwoAdmit": {Kind: ir.ValueString, String: "abcd"}, + "OneNoneAdmits": nil, + "OneUnknown": {Kind: ir.ValueString, String: "abc"}, + } { + assert.Equal(t, taken, componentMemberOf(t, doc, name, "p").Default, name) + refusals := 0 + if taken == nil { + refusals = 1 + } + assert.Equal(t, refusals, infosAt(diags, diag.DegradedConstruct, "/components/schemas/"+name, "admits the default"), name) + } + }) +} + +// TestFoldJudgment_ABroaderValueTheReaderCannotJudgeIsAdopted holds a value a +// declaration broader than the field's type writes to a refusal only where the +// value admission reader says no, in either order of the entries: a default a +// lookahead pattern on the narrower node leaves unjudged is adopted, and one +// the node's length refuses is reported and kept. +func TestFoldJudgment_ABroaderValueTheReaderCannotJudgeIsAdopted(t *testing.T) { + t.Parallel() + field := func(name, narrower string) string { + return name + ": {allOf: [{properties: {p: {type: string, default: abc}}}, " + + "{properties: {p: {$ref: '#/components/schemas/" + narrower + "'}}}]}" + } + spec := admissionSpec("3.1.0", "", + "Lookahead: {type: string, pattern: '^(?=a)', description: starts with a}", + "Short: {type: string, maxLength: 2, description: two at most}", + field("Unjudged", "Lookahead"), + field("Refused", "Short")) + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + unjudged := componentMemberOf(t, doc, "Unjudged", "p") + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Lookahead"), unjudged.Type.Target, "the narrower type") + assert.Equal(t, &ir.Value{Kind: ir.ValueString, String: "abc"}, unjudged.Default) + assert.Zero(t, infosAt(diags, diag.DegradedConstruct, "/components/schemas/Unjudged", "admits the default")) + refused := componentMemberOf(t, doc, "Refused", "p") + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Short"), refused.Type.Target, "the narrower type") + assert.Nil(t, refused.Default) + assert.Equal(t, 1, infosAt(diags, diag.DegradedConstruct, "/components/schemas/Refused", "admits the default")) + }) +} + +// TestFoldJudgment_ValueSetsSharingNullAloneKeepEachDeclarationOnce holds the +// enum of no member two value sets sharing null alone intersect in: each +// declaration is kept whole under its own key, which a keyword the two keep +// apart writes nothing more under, with one info each. +func TestFoldJudgment_ValueSetsSharingNullAloneKeepEachDeclarationOnce(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "F: {allOf: [{type: object, properties: {f: {type: [string, 'null'], enum: [a, null], minimum: 1}}}, "+ + "{type: object, properties: {f: {type: [string, 'null'], enum: [b, null], minimum: 2}}}]}") + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + member := componentMemberOf(t, doc, "F", "f") + enum, ok := doc.Types[member.Type.Target].(*ir.Enum) + require.True(t, ok, "the intersection is an enum") + assert.Empty(t, enum.Members) + assert.ElementsMatch(t, []string{"openapi:allOf/0/properties/f", "openapi:allOf/1/properties/f"}, slices.Collect(maps.Keys(enum.Unmodeled))) + for key, entry := range enum.Unmodeled { + assert.Contains(t, string(entry.Value), `"enum"`, "%s keeps the declaration whole", key) + } + for _, diagnostic := range diags { + assert.False(t, strings.HasPrefix(diagnostic.Message, `field "f": the other declarations write `), diagnostic.Message) + } + }) +} diff --git a/compilers/openapi/e2e/identifiers_test.go b/compilers/openapi/e2e/identifiers_test.go index f0740a688..7c3c44fbe 100644 --- a/compilers/openapi/e2e/identifiers_test.go +++ b/compilers/openapi/e2e/identifiers_test.go @@ -120,7 +120,8 @@ func TestCompile_ADocumentNothingReachedIsNoSource(t *testing.T) { // TestCompile_ADynamicRefExpandsInTheDocumentItIsWrittenIn pins the reference // another document writes: it expands to the type that document's component -// lowers to, in that document's namespace, whichever component lowers first. +// lowers to, in that document's namespace, whichever component lowers first, +// and the list names that type as its element. func TestCompile_ADynamicRefExpandsInTheDocumentItIsWrittenIn(t *testing.T) { t.Parallel() const other = `openapi: 3.1.0 @@ -147,11 +148,9 @@ components: in := ids.In("other.yaml") target := in.ForPointer("/components/schemas/Tree") - items := in.ForPointer("/components/schemas/Tree/properties/children/items") - alias, ok := doc.Types[items].(*ir.Scalar) + children, ok := doc.Types[in.ForPointer("/components/schemas/Tree/properties/children")].(*ir.List) require.True(t, ok, "%+v", diags) - assert.Equal(t, target, alias.Base.Target) - assert.Empty(t, alias.Unmodeled, "an expanded reference is not kept as well") + assert.Equal(t, target, children.ElementType.Target, "the expansion is the items' type, as a $ref's would be") assert.Equal(t, 1, countCode(diags, "openapi/dynamic-ref-expanded", "/components/schemas/Tree/properties/children/items/$dynamicRef")) } assert.Empty(t, cmp.Diff(docs[0].Types, docs[1].Types), "the declaration order decides nothing") diff --git a/compilers/openapi/e2e/ill_typed_reference_test.go b/compilers/openapi/e2e/ill_typed_reference_test.go index b62ad8993..2c56c18ee 100644 --- a/compilers/openapi/e2e/ill_typed_reference_test.go +++ b/compilers/openapi/e2e/ill_typed_reference_test.go @@ -228,8 +228,7 @@ func TestCompile_ANullRefOfAReferenceObjectLeavesTheEntryOut(t *testing.T) { // TestCompile_AParameterBesideANullRefLowers holds the row as the issue writes // it, the neighbour written after the entry whose $ref is null: the document is -// read, the one finding stands at the $ref, and the operation holds the -// neighbour. +// read, the one finding is at the $ref, and the operation holds the neighbour. func TestCompile_AParameterBesideANullRefLowers(t *testing.T) { t.Parallel() const spec = "openapi: 3.1.0\ninfo: {title: t, version: \"1\"}\npaths:\n /a:\n get:\n parameters:\n" + @@ -396,7 +395,7 @@ const reachedItem = "item:\n get:\n parameters:\n - {$ref: ~}\n - // the model faults on where only a $ref reaches it, raw YAML under an x- key or // another document, to the lowering the same item gets under paths (GitHub // #1928): what the reference lands on is judged before it is built, so the -// table's one error at the shape stands, the shape is read as left out, and +// table's one error at the shape is kept, the shape is read as left out, and // the path item reaching it lowers what else it writes. func TestCompile_AReachedObjectTheModelFaultsOnLowersAsUnderPaths(t *testing.T) { t.Parallel() @@ -460,7 +459,7 @@ func TestCompile_AReachedObjectTheModelFaultsOnLowersAsUnderPaths(t *testing.T) // Reference Object whose $ref a `<<` merge key writes, null, a list or a // mapping, to the entry left out with the one error at the $ref, as the same // $ref written in the mapping itself is: the model reads a reference by the -// keys a mapping writes itself, so the merged one stands in for it. +// keys a mapping writes itself, so the merged one takes its place. func TestCompile_ARefAMergeKeyWritesThatIsNoStringLeavesTheEntryOut(t *testing.T) { t.Parallel() for _, spelling := range []string{"~", "[a]", "{}"} { diff --git a/compilers/openapi/e2e/ill_typed_value_test.go b/compilers/openapi/e2e/ill_typed_value_test.go index b7988fad0..66f3e7ac4 100644 --- a/compilers/openapi/e2e/ill_typed_value_test.go +++ b/compilers/openapi/e2e/ill_typed_value_test.go @@ -488,9 +488,9 @@ func TestCompile_ARefusedValueIsReadAlikeWhetherADocumentMayNameADialect(t *test // TestCompile_ANodeASchemaAcceptsIsKeptInADocumentThatMayNameADialect holds a // scalar a parameter's required refuses and its schema's title and pattern -// accept, in a document whose schemas are judged once the bindings are read, -// to being kept as written: the pattern and title stand, and the one finding -// is the required's error. +// accept, in a document whose schemas are judged once the bindings are read, to +// being kept as written: the pattern and title are kept, and the one finding is +// the required's error. func TestCompile_ANodeASchemaAcceptsIsKeptInADocumentThatMayNameADialect(t *testing.T) { t.Parallel() for namer, line := range dialectNamers { @@ -537,8 +537,8 @@ func strippedTree(t *testing.T, doc *ir.Document) any { } // TestCompile_AVerbatimCopyShowsWhatTheSourceWrote holds a construct kept -// verbatim beside a refused value in it to the text written: the error stands -// at the node, and the copy renders the string, not the null it is read as. +// verbatim beside a refused value in it to the text written: the error is at +// the node, and the copy renders the string, not the null it is read as. func TestCompile_AVerbatimCopyShowsWhatTheSourceWrote(t *testing.T) { t.Parallel() spec := head31 + "paths: {}\ncomponents:\n schemas:\n S: {type: string, not: {maxLength: hello}}\n" diff --git a/compilers/openapi/e2e/inline_principal_discriminator_test.go b/compilers/openapi/e2e/inline_principal_discriminator_test.go index 46747c142..86d2ed411 100644 --- a/compilers/openapi/e2e/inline_principal_discriminator_test.go +++ b/compilers/openapi/e2e/inline_principal_discriminator_test.go @@ -13,13 +13,13 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestInlinePrincipal_AUnionStandingKeepsItsDiscriminatorsKeys holds the -// discriminator an allOf entry writes beside the union standing at the -// position (docs/compilers/openapi.md#allof-refinement) to keep what it -// declares that no IR field holds, an extension and a key the specification -// does not define, on the node, as the same discriminator written at the -// position does, each at the entry writing it. -func TestInlinePrincipal_AUnionStandingKeepsItsDiscriminatorsKeys(t *testing.T) { +// TestInlinePrincipal_AUnionAtThePositionKeepsItsDiscriminatorsKeys holds the +// discriminator an allOf entry writes beside the union at the position +// (docs/compilers/openapi.md#allof-refinement) to keep what it declares that no +// IR field holds, an extension and a key the specification does not define, on +// the node, as the same discriminator written at the position does, each at the +// entry writing it. +func TestInlinePrincipal_AUnionAtThePositionKeepsItsDiscriminatorsKeys(t *testing.T) { t.Parallel() const ( disc = "discriminator: {propertyName: k, x-b: 5, mapped: D}" diff --git a/compilers/openapi/e2e/inline_principal_position_test.go b/compilers/openapi/e2e/inline_principal_position_test.go index 3e8d05ffd..17eb07fa0 100644 --- a/compilers/openapi/e2e/inline_principal_position_test.go +++ b/compilers/openapi/e2e/inline_principal_position_test.go @@ -28,7 +28,7 @@ type inlinePrincipal struct { // inlinePrincipals are the principals that build a node: a list, a tuple, a // type list, a union, a hoisted scalar, a list the kind-inference policy reads, // a union of null alone, a union of value sets, and a map, which composes and -// stood at its position before; each bound beside it where it takes one. +// sat at its position before; each bound beside it where it takes one. var inlinePrincipals = []inlinePrincipal{ {name: "list", keywords: "type: array, items: {type: string}", other: "description: d", kind: ir.KindList}, {name: "list bounded apart", keywords: "type: array, items: {type: string}", other: "minItems: 1", kind: ir.KindList}, @@ -76,23 +76,23 @@ func principalVersions(inlinePrincipalValue inlinePrincipal) []string { return []string{"3.0.3", "3.1.0", "3.2.0"} } -// standingWritten is a document as the cases compare it: its tree without -// sources and findings, every pointer an entry index stands on left out +// positionWritten is a document as the cases compare it: its tree without +// sources and findings, every pointer an entry index sits on left out // (entryIndexless), and the findings as severity, code and pointer, sorted. -type standingWritten struct { +type positionWritten struct { doc string findings []string } -// writtenStanding compiles spec and reads it as standingWritten. -func writtenStanding(t *testing.T, spec string) (standingWritten, *ir.Document) { +// writtenAtPosition compiles spec and reads it as positionWritten. +func writtenAtPosition(t *testing.T, spec string) (positionWritten, *ir.Document) { t.Helper() doc, diags := compileUnrefused(t, spec) tree, ok := documentTree(t, doc).(map[string]any) require.True(t, ok, "a document encodes as an object") delete(tree, "sources") delete(tree, "diagnostics") - got := standingWritten{doc: fmt.Sprint(entryIndexless(tree))} + got := positionWritten{doc: fmt.Sprint(entryIndexless(tree))} for _, diagnostic := range diags { got.findings = append(got.findings, fmt.Sprintf("%s %s %s", diagnostic.Severity, diagnostic.Code, entryIndexless(string(diagnostic.Provenance.Pointer)))) } @@ -100,16 +100,16 @@ func writtenStanding(t *testing.T, spec string) (standingWritten, *ir.Document) return got, doc } -// atAnEntry matches a type ID standing at an allOf entry's own pointer. +// atAnEntry matches a type ID at an allOf entry's own pointer. var atAnEntry = regexp.MustCompile(`/allOf/[0-9]+$`) -// TestInlinePrincipal_TheNodeStandsAtThePositionInEverySpelling holds every +// TestInlinePrincipal_TheNodeIsAtThePositionInEverySpelling holds every // principal that builds a node, at every site, in each version that spells it, -// with and without a $ref entry it beats, written on an entry first, last or -// alone to the document its keywords beside each other compile to, up to the +// with and without a $ref entry it takes over, written on an entry first, last +// or alone to the document its keywords beside each other compile to, up to the // entries' indices in its children's pointers and in its findings: the node at // the position's ID, of the principal's kind, and no type at an entry. -func TestInlinePrincipal_TheNodeStandsAtThePositionInEverySpelling(t *testing.T) { +func TestInlinePrincipal_TheNodeIsAtThePositionInEverySpelling(t *testing.T) { t.Parallel() for _, inlinePrincipal := range inlinePrincipals { t.Run(inlinePrincipal.name, func(t *testing.T) { @@ -118,7 +118,7 @@ func TestInlinePrincipal_TheNodeStandsAtThePositionInEverySpelling(t *testing.T) for _, ref := range []string{"", "{" + refTo("T") + "}"} { spellings := principalSpellings(inlinePrincipal, ref) for _, site := range conjSites { - requireStandsAtPosition(t, inlinePrincipal, version, site, spellings) + requireNodeAtPosition(t, inlinePrincipal, version, site, spellings) } } } @@ -126,19 +126,19 @@ func TestInlinePrincipal_TheNodeStandsAtThePositionInEverySpelling(t *testing.T) } } -// requireStandsAtPosition is one site and version of -// TestInlinePrincipal_TheNodeStandsAtThePositionInEverySpelling. -func requireStandsAtPosition(t *testing.T, inlinePrincipalValue inlinePrincipal, version string, site conjSite, spellings map[string]string) { +// requireNodeAtPosition is one site and version of +// TestInlinePrincipal_TheNodeIsAtThePositionInEverySpelling. +func requireNodeAtPosition(t *testing.T, inlinePrincipalValue inlinePrincipal, version string, site conjSite, spellings map[string]string) { t.Helper() others := []string{"S: {type: string}", "T: {}"} - want, _ := writtenStanding(t, site.write(version, spellings["beside"], others...)) + want, _ := writtenAtPosition(t, site.write(version, spellings["beside"], others...)) for name, schema := range spellings { - got, doc := writtenStanding(t, site.write(version, schema, others...)) + got, doc := writtenAtPosition(t, site.write(version, schema, others...)) at := fmt.Sprintf("%s at the %s in %s, %s", inlinePrincipalValue.name, site.name, version, schema) node := kindNode(t, doc, entryPositionID(jsontext.Pointer(site.pointer))) assert.Equal(t, inlinePrincipalValue.kind, node.Kind(), "%s: the node at the position", at) for id := range doc.Types { - assert.False(t, atAnEntry.MatchString(string(id)), "%s: %s stands at an entry", at, id) + assert.False(t, atAnEntry.MatchString(string(id)), "%s: %s sits at an entry", at, id) } if name == "beside" { continue @@ -268,7 +268,7 @@ func TestInlinePrincipal_AReferenceToTheEntryNamesTheEntryAlone(t *testing.T) { // inline principal holds beneath it to the pointer it is written at: a list's // element at the entry's items, the position's own items kept and no element, // and a union's branch at the entry's oneOf. A type list's variant, written at -// no pointer, stands under the position's, as its flat spelling's does. +// no pointer, sits under the position's, as its flat spelling's does. func TestInlinePrincipal_ChildrenKeepThePointerTheyAreWrittenAt(t *testing.T) { t.Parallel() spec := admissionSpec("3.1.0", "", @@ -316,7 +316,7 @@ func TestInlinePrincipal_AWrapperHoldsEachBoundOnce(t *testing.T) { property := requireModelOf(t, doc, "H").Properties[0] assert.Nil(t, property.Constraints, "%s: the carrier holds no bound", schema) for id := range doc.Types { - assert.NotContains(t, string(id), "/allOf/", "%s: %s stands at an entry", schema, id) + assert.NotContains(t, string(id), "/allOf/", "%s: %s sits at an entry", schema, id) } } } diff --git a/compilers/openapi/e2e/inline_principal_variant_test.go b/compilers/openapi/e2e/inline_principal_variant_test.go index ae913ff11..3e79bd4ca 100644 --- a/compilers/openapi/e2e/inline_principal_variant_test.go +++ b/compilers/openapi/e2e/inline_principal_variant_test.go @@ -126,15 +126,18 @@ var flatTwins = []struct{ conjunction, flat string }{ // TestInlinePrincipal_AVariantEntryLowersAsItsFlatSpelling holds a position // lowering a Union of variants from an allOf entry to the document the same // keywords written flat at that position compile to, at every site a schema is -// written: the variants and what stands beneath them under the position's -// pointer, each holding what the flat spelling's does, and the same findings. +// written: the variants under the position's pointer and what sits beneath them +// where it is written (docs/compilers/openapi.md#type-arrays), the entry's +// pointer read as the position's, each holding what the flat spelling's does, +// and the same findings. func TestInlinePrincipal_AVariantEntryLowersAsItsFlatSpelling(t *testing.T) { t.Parallel() for _, twin := range flatTwins { for _, site := range conjSites { want, _ := compileUnrefused(t, site.write("3.1.0", twin.flat, "S: {type: string}")) got, _ := compileUnrefused(t, site.write("3.1.0", twin.conjunction, "S: {type: string}")) - assert.Empty(t, cmp.Diff(comparableDocument(t, want), comparableDocument(t, got)), + relocate := relocater(site.pointer) + assert.Empty(t, cmp.Diff(comparableDocument(t, want), relocate(comparableDocument(t, got))), "%s at the %s lowers as %s", twin.conjunction, site.name, twin.flat) } } @@ -186,16 +189,16 @@ type unionShapedBound struct { } // unionShapedBounds are a type list's array variant and the kind-inference -// policy's taking a collection bound, as the flat spelling's do, and the bounds -// no node of the position takes kept on the Union: one a oneOf with an array -// branch writes beside it, as flat, and an object bound of a folded entry, -// which no object variant reads (#2062). +// policy's taking a collection bound, as the flat spelling's do, the object +// variant of either taking an object bound, as a variant reads the list's +// conjuncts, and the bound no node of the position takes kept on the Union: one +// a oneOf with an array branch writes beside it, as flat. var unionShapedBounds = []unionShapedBound{ {"type list's array", "type: [string, array], items: {type: string}", "minItems", "minItems", "13", "/type/1", false, true}, {"inferred array", "items: {type: string}, properties: {a: {type: string}}", "minItems", "minItems", "13", "/type/1", false, true}, {"union's array branch", "oneOf: [{type: array, items: {type: string}}, {type: string}]", "minItems", "minItems", "13", "", true, true}, - {"type list's object", "type: [string, object]", "minProperties", "minProperties", "19", "", true, false}, - {"inferred object", "items: {type: string}, properties: {a: {type: string}}", "minProperties", "minProperties", "19", "", true, false}, + {"type list's object", "type: [string, object]", "minProperties", "minProperties", "19", "/type/1", false, true}, + {"inferred object", "items: {type: string}, properties: {a: {type: string}}", "minProperties", "minProperties", "19", "/type/0", false, true}, } // TestInlinePrincipal_ABoundBesideAUnionShapedPrincipalLandsOnce holds a diff --git a/compilers/openapi/e2e/kept_failed_ref_test.go b/compilers/openapi/e2e/kept_failed_ref_test.go index 472e4a291..7a0d5de7d 100644 --- a/compilers/openapi/e2e/kept_failed_ref_test.go +++ b/compilers/openapi/e2e/kept_failed_ref_test.go @@ -107,43 +107,11 @@ func keptUnresolved(at, target string) keptFinding { return keptFinding{severity: ir.SeverityError, code: diag.UnresolvedRef, at: at, words: []string{target}} } -// requireKeptFailedRef holds the schema named to keep, under the entry at -// entry, the $ref that failed and each keyword written beside it, once each, -// and to draw the error of the failure and one info naming the keywords the -// $ref's neighbours were kept as. -func requireKeptFailedRef(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, version, name, entry, target string) { - t.Helper() - at := "/components/schemas/" + name + entry - got := keptKeywordsUnder(doc, at) - kept := got["openapi:$ref"] - require.Len(t, kept, 1, "%s: the $ref that failed is kept once", name) - assert.Equal(t, `"`+target+`"`, kept[0].value, "%s: the reference as written", name) - assert.Equal(t, ir.ReasonDegradedLowering, kept[0].reason, name) - for key, want := range map[string]string{"openapi:properties": `{"a":{"type":"string"}}`, "openapi:minLength": "2"} { - entries := got[key] - require.Len(t, entries, 1, "%s: %s is kept once", name, key) - assert.Equal(t, ir.ReasonDegradedLowering, entries[0].reason, "%s: %s", name, key) - assert.Equal(t, want, entries[0].value, "%s: %s", name, key) - assert.True(t, underPointer(entries[0].pointer, at), "%s: %s is written in the conjunct", name, key) - } - var described bool - if entries, ok := got["openapi:description"]; ok { - require.Len(t, entries, 1, "%s: the description is kept once", name) - described = true - } - described = described || kindNode(t, doc, componentID(name)).Common().Docs.Description == "why" - assert.True(t, described, "%s: the description beside the failed $ref reaches the document", name) - for key := range got { - assert.Contains(t, []string{"openapi:$ref", "openapi:properties", "openapi:minLength", "openapi:description"}, key, - "%s: nothing else is kept", name) - } - want := append([]keptFinding{ - keptUnresolved(entry, target), - keptDegraded(entry, "properties", "minLength"), - }, keptBesideARef(version, entry, "description", "properties", "minLength")...) - keptFindingsUnder(t, diags, name, want) -} - +// TestKeptFailedRef_EveryKeyBesideAFailedRefIsKeptAndTheFailureReportedOnce +// holds a $ref naming nothing beside keywords on an entry, in either order of +// the entries and alone: it admits every kind and cuts nothing, so each +// position lowers as the same entry without the $ref, the reference kept once +// and its failure reported once. func TestKeptFailedRef_EveryKeyBesideAFailedRefIsKeptAndTheFailureReportedOnce(t *testing.T) { t.Parallel() const ghost = "{$ref: '#/components/schemas/Ghost', description: why, properties: {a: {type: string}}, minLength: 2}" @@ -156,11 +124,7 @@ func TestKeptFailedRef_EveryKeyBesideAFailedRefIsKeptAndTheFailureReportedOnce(t "YAlone: {allOf: [" + ghost + "]}", } inBothOrders(t, schemas, func(t *testing.T, schemas []string) { - doc, diags := compileAnnotationSpec(t, "failed", admissionSpec(version, "", schemas...)) - const target = "#/components/schemas/Ghost" - requireKeptFailedRef(t, doc, diags, version, "Y", "/allOf/0", target) - requireKeptFailedRef(t, doc, diags, version, "YRev", "/allOf/1", target) - requireKeptFailedRef(t, doc, diags, version, "YAlone", "/allOf/0", target) + doc := requireLowersWithoutRefs(t, version, schemas, []string{"$ref: '#/components/schemas/Ghost', "}, 3) for _, name := range []string{"Y", "YRev"} { _, ok := propertyByWire(requireModelOf(t, doc, name), "b") assert.True(t, ok, "%s: the member the other conjunct declares is typed", name) @@ -198,6 +162,9 @@ func TestKeptFailedRef_SeveralFailedRefsAreKeptByAscendingReferenceText(t *testi } } +// TestKeptFailedRef_ARefInsideAnEntryOrAtAnItemIsKept holds a $ref naming +// nothing inside a wrapper entry and at a list's element: each lowers as the +// same schema without the $ref, the reference kept once. func TestKeptFailedRef_ARefInsideAnEntryOrAtAnItemIsKept(t *testing.T) { t.Parallel() const ghost = "{$ref: '#/components/schemas/Ghost', minLength: 2}" @@ -209,14 +176,7 @@ func TestKeptFailedRef_ARefInsideAnEntryOrAtAnItemIsKept(t *testing.T) { "Items: {type: array, items: {allOf: [" + ghost + "]}}", } inBothOrders(t, schemas, func(t *testing.T, schemas []string) { - doc, diags := compileAnnotationSpec(t, "nested", admissionSpec(version, "", schemas...)) - for name, entry := range map[string]string{"Nest": "/allOf/0/allOf/0", "Items": "/items/allOf/0"} { - got := keptKeywordsUnder(doc, "/components/schemas/"+name+entry) - require.Equal(t, degradedKept("openapi:$ref", "openapi:minLength"), keptKeywordReasons(got), name) - keptFindingsUnder(t, diags, name, append([]keptFinding{ - keptUnresolved(entry, "Ghost"), keptDegraded(entry, "minLength"), - }, keptBesideARef(version, entry, "minLength")...)) - } + requireLowersWithoutRefs(t, version, schemas, []string{"$ref: '#/components/schemas/Ghost', "}, 2) }) }) } @@ -228,8 +188,9 @@ func TestKeptFailedRef_ARefOnALoopIsKeptLikeOneThatNamesNothing(t *testing.T) { t.Run(version, func(t *testing.T) { t.Parallel() // Self's first entry names itself: the chain of $refs it starts leads - // back to it, and lands on no schema. Into's entry names a schema that - // is on a loop, which is itself declared and so resolves. + // back to it, and lands on no schema. Into's entry names a schema on a + // loop, which admits every kind, so Into lowers as over a schema + // writing nothing: the $ref and its bound kept, no Base. schemas := []string{ "LA: {$ref: '#/components/schemas/LB'}", "LB: {$ref: '#/components/schemas/LA'}", @@ -241,8 +202,10 @@ func TestKeptFailedRef_ARefOnALoopIsKeptLikeOneThatNamesNothing(t *testing.T) { got := keptKeywordsOf(doc, "Self") require.Equal(t, degradedKept("openapi:$ref", "openapi:minLength"), keptKeywordReasons(got), "Self") assert.Equal(t, `"#/components/schemas/Self/allOf/0"`, got["openapi:$ref"][0].value) - assert.Empty(t, keptKeywordsOf(doc, "Into"), "Into: a $ref to a declared schema is lowered, not kept") - assert.NotNil(t, requireModelOf(t, doc, "Into").Base, "Into: the reference is its base") + into := keptKeywordsOf(doc, "Into") + assert.Contains(t, into, "openapi:$ref", "Into: the reference is kept") + assert.Contains(t, into, "openapi:minLength", "Into: the bound beside it is kept") + assert.Nil(t, requireModelOf(t, doc, "Into").Base, "Into: the loop is no base") var cycles int for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityError { diff --git a/compilers/openapi/e2e/kept_keyword_helpers_test.go b/compilers/openapi/e2e/kept_keyword_helpers_test.go index 247c3369d..3f4d5627b 100644 --- a/compilers/openapi/e2e/kept_keyword_helpers_test.go +++ b/compilers/openapi/e2e/kept_keyword_helpers_test.go @@ -44,9 +44,9 @@ type keptKeywordEntry struct { } // keptKeywordsOf returns every Unmodeled entry of doc whose provenance names a -// pointer at or under the component named, by key. It walks the whole -// document, so a keyword kept on a node that moved, a carrier or an alias is -// found where it stands, and a key kept on two nodes shows as two entries. +// pointer at or under the component named, by key. It walks the whole document, +// so a keyword kept on a node that moved, a carrier or an alias is found where +// it sits, and a key kept on two nodes shows as two entries. func keptKeywordsOf(doc *ir.Document, name string) map[string][]keptKeywordEntry { return keptKeywordsUnder(doc, "/components/schemas/"+name) } @@ -213,8 +213,8 @@ type keptKeywordCase struct { wrap, pos string // extra are components the case needs beside the common ones. extra []string - // want is each key kept with its reason, "{i}" standing for the entry's - // index in the allOf; an empty reason accepts any. + // want is each key kept with its reason, "{i}" naming the entry's index in + // the allOf; an empty reason accepts any. want map[string]ir.UnmodeledReason // whole marks a keyword whose entry is kept whole, so the key's provenance // is the entry's own pointer. diff --git a/compilers/openapi/e2e/kept_ref_landings_test.go b/compilers/openapi/e2e/kept_ref_landings_test.go index 345ae8ecc..9200489bb 100644 --- a/compilers/openapi/e2e/kept_ref_landings_test.go +++ b/compilers/openapi/e2e/kept_ref_landings_test.go @@ -5,8 +5,10 @@ package e2e_test import ( "encoding/json/jsontext" + "maps" "os" "path/filepath" + "slices" "testing" "github.com/google/go-cmp/cmp" @@ -83,3 +85,39 @@ func TestCompile_KeptRefLandingsAreLoweredOnceInEitherOrder(t *testing.T) { } } } + +// TestCompile_AFieldNarrowsAStructureKeepingAnyReferenceAlike holds a field +// redeclared beside a structure that keeps verbatim a reference naming no +// schema, one on a loop of references, to the same fold whatever keyword +// writes the reference: the structure admits every string, as the reference +// narrows nothing, so the field is the string and keeps the reference, with +// no report that the declarations disagree. +func TestCompile_AFieldNarrowsAStructureKeepingAnyReferenceAlike(t *testing.T) { + t.Parallel() + for _, keyword := range []string{"$ref", "$dynamicRef"} { + src := `openapi: 3.1.0 +info: {title: t, version: '1'} +paths: {} +components: + schemas: + L1: {$ref: '#/components/schemas/L2'} + L2: {$ref: '#/components/schemas/L1'} + S: + allOf: + - type: object + properties: + p: {properties: {a: {type: string}}, ` + keyword + `: '#/components/schemas/L1'} + - type: object + properties: + p: {type: string} +` + doc, diags := compileLandings(t, "spec.yaml", []byte(src)) + model, ok := doc.Types["type/openapi/components/schemas/S"].(*ir.Model) + require.True(t, ok, keyword) + require.Len(t, model.Properties, 1, keyword) + field := model.Properties[0] + assert.Equal(t, ir.TypeID("type/primitive/string"), field.Type.Target, keyword) + assert.Equal(t, []string{"openapi:" + keyword}, slices.Sorted(maps.Keys(field.Unmodeled)), keyword) + assert.Empty(t, fieldComparisonReports(diags), "%s: %+v", keyword, diags) + } +} diff --git a/compilers/openapi/e2e/keyword_scope_decisions_test.go b/compilers/openapi/e2e/keyword_scope_decisions_test.go new file mode 100644 index 000000000..1ff2b552e --- /dev/null +++ b/compilers/openapi/e2e/keyword_scope_decisions_test.go @@ -0,0 +1,567 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "fmt" + "regexp" + "slices" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestKeywordScope_AMissingItemsIsJudgedPerConjunction holds GitHub #2048's +// reproduction to one reading: at 3.0 an array draws one missing-items warning, +// at its position, where no conjunct writes `items`, a $ref's target included, +// and none where any conjunct does, in either order of the entries and of the +// components (docs/compilers/openapi.md#missing-array-items). +func TestKeywordScope_AMissingItemsIsJudgedPerConjunction(t *testing.T) { + t.Parallel() + schemas := []string{ + "X: {type: array, items: {type: string}}", + "Y: {type: array}", + "Ref: {allOf: [{$ref: '#/components/schemas/X'}, {type: array}]}", + "RefLast: {allOf: [{type: array}, {$ref: '#/components/schemas/X'}]}", + "RefY: {allOf: [{$ref: '#/components/schemas/Y'}, {type: array}]}", + "H: {allOf: [{type: array}, {items: {type: string}}]}", + "HLast: {allOf: [{items: {type: string}}, {type: array}]}", + "J: {allOf: [{type: array}, {type: array, items: {type: string}}]}", + "K: {allOf: [{type: array, items: {type: string}}, {type: array}]}", + "B: {allOf: [{type: array}, {type: array}]}", + "A: {allOf: [{type: array}, {type: array}, {items: {type: string}}]}", + "AFirst: {allOf: [{items: {type: string}}, {type: array}, {type: array}]}", + "M: {allOf: [{type: array}, {type: array, minItems: 1}]}", + "MLast: {allOf: [{type: array, minItems: 1}, {type: array}]}", + "Beside: {type: array, allOf: [{type: array}]}", + "BesideItems: {type: array, allOf: [{items: {type: string}}]}", + } + missing := func(names ...string) []wantFinding { + out := make([]wantFinding, 0, len(names)) + for _, name := range names { + out = append(out, wantFinding{code: diag.MissingArrayItems, pointer: "/components/schemas/" + name}) + } + return out + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + _, diags := compileUnrefused(t, admissionSpec("3.0.3", "", schemas...)) + requireErrorsAndWarnings(t, diags, missing("Y", "RefY", "B", "M", "MLast", "Beside")) + }) +} + +// TestKeywordScope_EntriesAgreeingOnAKeywordFoldItApartFromAnother holds GitHub +// #2049's reproduction: a bound every conjunct writing it states alike folds +// onto the node though the conjuncts disagree on a description, and each entry +// writing what they disagree on stays kept whole, with one report, in either +// order of the entries (docs/compilers/openapi.md#allof-inline-residue). +func TestKeywordScope_EntriesAgreeingOnAKeywordFoldItApartFromAnother(t *testing.T) { + t.Parallel() + const ( + a = "{type: string, minLength: 2, description: a}" + b = "{type: string, minLength: 2, description: b}" + ) + for _, version := range bothVersions { + for _, swapped := range []bool{false, true} { + list, _, _ := composeEntries(swapped, a, b) + schemas := []string{ + "Agree: {allOf: [" + a + ", " + a + "]}", + "Differ: {allOf: " + list + "}", + "Beside: {allOf: [" + a + "], description: b}", + "BesideNone: {allOf: [{type: string, minLength: 2}], description: b}", + } + t.Run(fmt.Sprintf("%s/swapped=%t", version, swapped), func(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, admissionSpec(version, "", schemas...)) + requireErrorsAndWarnings(t, diags, nil) + for name, want := range map[string]struct { + description string + kept []string + }{ + "Agree": {"a", nil}, + "Differ": {"", []string{"openapi:allOf/0", "openapi:allOf/1"}}, + "Beside": {"b", []string{"openapi:allOf/0"}}, + "BesideNone": {"b", nil}, + } { + scalar := requireComponentScalar(t, doc, name, ir.PrimitiveTypeID(ir.PrimitiveString)) + require.NotNil(t, scalar.Constraints, "%s: the bound every conjunct states folds", name) + assert.Equal(t, new(int64(2)), scalar.Constraints.MinLength, name) + assert.Equal(t, want.description, scalar.Docs.Description, name) + assert.Equal(t, degradedKept(want.kept...), keptOn(scalar), "%s: an entry is kept whole for what disagreed", name) + assert.Equal(t, len(want.kept), degradedInfosAt(diags, name), name) + } + }) + } + } +} + +// saysNothingNodeShape is what a test of an applicator saying nothing compares of a +// node: its kind and base, what it keeps, under which reason, and the heuristic +// that chose its kind, if any. +type saysNothingNodeShape struct { + Kind ir.TypeKind + Base ir.TypeID + Kept map[string]ir.UnmodeledReason + Inferred ir.Inferred + Diags []string +} + +// saysNothingShapeOf compiles schema as the component Use and reads its node. +func saysNothingShapeOf(t *testing.T, schema string) saysNothingNodeShape { + t.Helper() + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", "Use: "+schema)) + td := kindNode(t, doc, componentID("Use")) + shape := saysNothingNodeShape{Kind: td.Kind(), Kept: keptOn(td), Inferred: td.Common().Provenance.Inferred} + if scalar, ok := td.(*ir.Scalar); ok && scalar.Base != nil { + shape.Base = scalar.Base.Target + } + for _, diagnostic := range diags { + shape.Diags = append(shape.Diags, fmt.Sprintf("%s %s %s", diagnostic.Severity, diagnostic.Code, diagnostic.Provenance.Pointer)) + } + slices.Sort(shape.Diags) + return shape +} + +// TestKeywordScope_AnApplicatorHoldingOnlyIdentifiersSaysNothing holds GitHub +// #2082's reproduction: `items` or `additionalProperties` holding a schema +// that writes only identifier and meta keywords lowers as it does holding `{}`, +// in the allOf spelling too, while one holding a note, an extension or an +// unevaluated keyword still types its instances +// (docs/compilers/openapi.md#shape-applicator). +func TestKeywordScope_AnApplicatorHoldingOnlyIdentifiersSaysNothing(t *testing.T) { + t.Parallel() + for saysNothing, empty := range map[string]string{ + "{items: {$comment: c}}": "{items: {}}", + "{items: {$anchor: a}}": "{items: {}}", + "{items: {$defs: {Z: {type: string}}}}": "{items: {}}", + "{items: {$comment: c, $anchor: a}}": "{items: {}}", + "{additionalProperties: {$comment: c}}": "{additionalProperties: {}}", + "{allOf: [{items: {$comment: c}}]}": "{allOf: [{items: {}}]}", + "{allOf: [{additionalProperties: {$anchor: a}}]}": "{allOf: [{additionalProperties: {}}]}", + } { + assert.Equal(t, saysNothingShapeOf(t, empty), saysNothingShapeOf(t, saysNothing), "%s lowers as %s", saysNothing, empty) + } + for _, typed := range []string{ + "{items: {description: d}}", + "{items: {title: t}}", + "{items: {x-a: 1}}", + "{items: {unevaluatedProperties: false}}", + "{items: {$comment: c, description: d}}", + } { + assert.Equal(t, ir.KindList, saysNothingShapeOf(t, typed).Kind, "%s stays a list", typed) + } +} + +// TestKeywordScope_ACommentStaysInItsOwnObject holds `$comment` to the schema +// object writing it: conjuncts writing different comments, beside the allOf or +// on entries, do not disagree, so no entry is kept and nothing reports one, in +// either declaration order (docs/compilers/openapi.md#allof-inline-residue). +func TestKeywordScope_ACommentStaysInItsOwnObject(t *testing.T) { + t.Parallel() + schemas := []string{ + "Entries: {type: string, allOf: [{$comment: c}, {$comment: d}]}", + "Members: {allOf: [{type: object, properties: {a: {type: string}}, $comment: c}, {type: object, $comment: d}]}", + "Beside: {$comment: k, allOf: [{type: string, $comment: c}]}", + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", schemas...)) + assert.Empty(t, diags, "no comment draws a report") + for _, name := range []string{"Entries", "Members", "Beside"} { + assert.Empty(t, keptOn(kindNode(t, doc, componentID(name))), "%s keeps no entry", name) + } + }) +} + +// TestKeywordScope_AnItemsMovesWithItsPrefixItems holds 2020-12's `items` to +// the `prefixItems` its own object writes: written apart from them it holds +// every element, the prefix's too, so it disagrees with an `items` written +// beside them, and a `prefixItems` written apart from an `items` disagrees with +// the group writing both, each entry kept whole with the info saying so, in +// either declaration order (docs/compilers/openapi.md#allof-inline-residue). +func TestKeywordScope_AnItemsMovesWithItsPrefixItems(t *testing.T) { + t.Parallel() + schemas := []string{ + "Apart: {type: array, prefixItems: [{type: string}], allOf: [{items: {type: integer}}]}", + "Group: {allOf: [{type: array, prefixItems: [{type: string}], items: {type: integer}}, {type: array, prefixItems: [{type: string}]}]}", + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", schemas...)) + for name, kept := range map[string]string{"Apart": "openapi:allOf/0", "Group": "openapi:allOf/1"} { + assert.Equal(t, degradedKept(kept), keptOn(kindNode(t, doc, componentID(name))), name) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, + "/components/schemas/"+name+"/"+strings.TrimPrefix(kept, "openapi:")), "disagree", name) + } + }) +} + +// TestKeywordScope_ALoneDynamicRefEntryExpandsInPlace holds GitHub #2056's +// reproduction: a $dynamicRef on the only entry of an allOf expands as written +// at the schema, with the same report, while one beside another conjunct is +// still kept with the report saying so. +func TestKeywordScope_ALoneDynamicRefEntryExpandsInPlace(t *testing.T) { + t.Parallel() + const anchored = "M: {$dynamicAnchor: m, type: object, properties: {m: {type: string}}}" + bare := spelledAt(t, "3.1.0", conjSites[0], "{$dynamicRef: '#m'}", anchored) + lone := spelledAt(t, "3.1.0", conjSites[0], "{allOf: [{$dynamicRef: '#m'}]}", anchored) + assert.Empty(t, cmp.Diff(bare, lone, cmp.AllowUnexported(entryWritten{})), "a lone entry's $dynamicRef expands as written bare") + + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", anchored, + "Beside: {allOf: [{$ref: '#/components/schemas/M'}, {$dynamicRef: '#m'}]}")) + beside := requireModelOf(t, doc, "Beside") + assert.Equal(t, degradedKept("openapi:$dynamicRef"), keptOn(beside)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, + "/components/schemas/Beside/allOf/1/$dynamicRef"), "beside another conjunct") +} + +// TestKeywordScope_AnEntrysDynamicRefIsReadAsTheCompositionListsIt holds an +// entry's $dynamicRef to the composition listing it, whatever reads it. Beside +// a $ref and a oneOf it is kept and masks no kind, so the union's branches are +// judged against the $ref's array as where the keyword is written beside the +// allOf, and so where the union and the keyword are entries of an entry. On the +// one entry of a lone entry it takes its place twice over and expands as on a +// lone entry, and through such a wrapper beside a $ref it is kept as on an +// entry there, the position composing the $ref. +func TestKeywordScope_AnEntrysDynamicRefIsReadAsTheCompositionListsIt(t *testing.T) { + t.Parallel() + const anchored = "M: {$dynamicAnchor: m, type: string}" + const union = "oneOf: [{type: array, maxItems: 5}, {type: boolean}]" + doc, _ := compileUnrefused(t, admissionSpec("3.1.0", "", anchored, + "T: {type: array, items: {type: string}}", + "O: {type: object, properties: {a: {type: string}}}", + "OnEntry: {allOf: [{$ref: '#/components/schemas/T'}, {$dynamicRef: '#m'}], "+union+"}", + "Beside: {allOf: [{$ref: '#/components/schemas/T'}], $dynamicRef: '#m', "+union+"}", + "Wrapped: {allOf: [{allOf: [{$dynamicRef: '#m'}]}, {$ref: '#/components/schemas/O'}]}", + "Entry: {allOf: [{$dynamicRef: '#m'}, {$ref: '#/components/schemas/O'}]}", + "Nested: {allOf: [{allOf: [{"+union+"}, {$dynamicRef: '#m'}, {$ref: '#/components/schemas/T'}]}]}")) + for _, name := range []string{"OnEntry", "Beside", "Nested"} { + assert.Equal(t, degradedKept("openapi:$dynamicRef", "openapi:oneOf"), keptOn(kindNode(t, doc, componentID(name))), + "%s: the union declares shape beside the array", name) + } + wrapped, entry := requireModelOf(t, doc, "Wrapped"), requireModelOf(t, doc, "Entry") + assert.Equal(t, entry.Base, wrapped.Base, "the wrapper's entry is kept beside the $ref, which the model composes") + assert.Equal(t, keptOn(entry), keptOn(wrapped)) + + relocate := relocater(conjSites[0].pointer) + nested := spelledAt(t, "3.1.0", conjSites[0], "{allOf: [{allOf: [{$dynamicRef: '#m'}]}]}", anchored) + nested.doc = relocate(nested.doc) + for i := range nested.diags { + nested.diags[i] = relocate(nested.diags[i]) + } + slices.Sort(nested.diags) + lone := spelledAt(t, "3.1.0", conjSites[0], "{allOf: [{$dynamicRef: '#m'}]}", anchored) + assert.Empty(t, cmp.Diff(lone, nested, cmp.AllowUnexported(entryWritten{})), "a lone entry of a lone entry expands as one does") +} + +// TestKeywordScope_ARefNamingAnEntryReadsTheEntryAlone holds GitHub #2058's +// reproduction: a $ref naming an allOf entry that writes a $dynamicRef reads +// that entry's schema alone, expanded, so a conjunction of it with an object +// shares no value, as the same conjunction naming the anchored string does, in +// either declaration order. The keyword draws one report per fact, each naming +// the context reading it: Q keeps it, read as its entry beside another +// conjunct, and the entry read alone as the $ref's target expands it. +func TestKeywordScope_ARefNamingAnEntryReadsTheEntryAlone(t *testing.T) { + t.Parallel() + schemas := []string{ + "M: {$dynamicAnchor: m, type: string}", + "Q: {allOf: [{type: object, properties: {a: {type: string}}}, {$dynamicRef: '#m'}]}", + "ViaEntry: {allOf: [{$ref: '#/components/schemas/Q/allOf/1'}, {type: object, properties: {b: {type: string}}}]}", + "ViaM: {allOf: [{$ref: '#/components/schemas/M'}, {type: object, properties: {b: {type: string}}}]}", + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + requireErrorsAndWarnings(t, diags, []wantFinding{disjointFinding("ViaEntry"), disjointFinding("ViaM")}) + viaEntry, viaM := kindNode(t, doc, componentID("ViaEntry")), kindNode(t, doc, componentID("ViaM")) + assert.Equal(t, viaM.Kind(), viaEntry.Kind()) + assert.Equal(t, keptOn(viaM), keptOn(viaEntry), "the entry reached by the $ref is read as M is") + var facts []string + for _, diagnostic := range diags { + if diagnostic.Provenance.Pointer == "/components/schemas/Q/allOf/1/$dynamicRef" { + facts = append(facts, diagnostic.Code) + if diagnostic.Code == diag.DegradedConstruct { + assert.Contains(t, diagnostic.Message, "read as an entry of this allOf, was not expanded because it is written beside another conjunct", + "Q keeps the keyword, read as its entry") + } else { + assert.Contains(t, diagnostic.Message, `read alone as the target of the $ref at "/components/schemas/ViaEntry/allOf/0", expanded to`, + "the entry read alone expands it") + } + } + } + slices.Sort(facts) + assert.Equal(t, []string{diag.DegradedConstruct, diag.DynamicRefExpanded}, facts, + "one report that Q keeps the keyword, one that the entry read alone expands it") + }) +} + +// TestKeywordScope_AnEntryReadAloneByAMappingNamesNoRef holds the report on an +// allOf entry's $dynamicRef read alone where no $ref lands on the entry, a +// discriminator's mapping naming it: the expansion is read as the target of a +// reference, and the composition's report as its entry, so neither contradicts +// the other (docs/compilers/openapi.md#allof-refinement). +func TestKeywordScope_AnEntryReadAloneByAMappingNamesNoRef(t *testing.T) { + t.Parallel() + _, diags := compileUnrefused(t, admissionSpec("3.1.0", "", + "M: {$dynamicAnchor: m, type: object, properties: {k: {type: string}}}", + "Q: {allOf: [{type: object, properties: {a: {type: string}}}, {$dynamicRef: '#m'}]}", + "U: {type: object, properties: {k: {type: string}}, discriminator: {propertyName: k, mapping: {x: '#/components/schemas/Q/allOf/1'}}}")) + at := "/components/schemas/Q/allOf/1/$dynamicRef" + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DynamicRefExpanded, ir.SeverityInfo, at), + "read alone as the target of a reference, expanded to") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), "read as an entry of this allOf") +} + +// entryOfLink relocates an allOf's first entry to the schema writing it, so a +// loop spelt through single-entry allOfs compares with its bare spelling. +var entryOfLink = regexp.MustCompile(`(/components/schemas/[A-Za-z]+)/allOf/0\b`) + +// loopWritten compiles schemas, its passes run, and reads them as the loop twins +// compare them: the document without its sources and the findings, by severity, code and +// pointer, each entry's pointer read as its schema's. +func loopWritten(t *testing.T, version string, schemas []string) entryWritten { + t.Helper() + doc, diags := parseVerified(t, admissionSpec(version, "", schemas...)) + relocate := func(s string) string { return entryOfLink.ReplaceAllString(s, "$1") } + got := entryWritten{doc: relocate(withoutVersion(t, doc))} + for _, diagnostic := range diags { + got.diags = append(got.diags, fmt.Sprintf("%s %s %s", diagnostic.Severity, diagnostic.Code, + relocate(string(diagnostic.Provenance.Pointer)))) + } + slices.Sort(got.diags) + return got +} + +// TestKeywordScope_AnEntryWritingBesideItsRefIsNoHop holds an allOf entry +// writing what says something beside its $ref, as 3.0 applies it too, to the +// reading of the same keyword beside the allOf: no hop of a reference chain, so +// a loop through it is a composition read to its fixpoint, `KA` the `string` +// keeping its $ref and `WA`, `WB` the composition cycle, in either declaration +// order (docs/compilers/openapi.md#reference-cycles). +func TestKeywordScope_AnEntryWritingBesideItsRefIsNoHop(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "$ref: '#/components/schemas/" + name + "'" } + member := "properties: {p: {type: string}}" + for _, version := range bothVersions { + for _, spelling := range []struct{ name, kind, member string }{ + {"entry", "KA: {allOf: [{" + ref("KB") + ", type: string}]}", "WA: {allOf: [{" + ref("WB") + ", " + member + "}]}"}, + {"beside", "KA: {allOf: [{" + ref("KB") + "}], type: string}", "WA: {allOf: [{" + ref("WB") + "}], " + member + "}"}, + } { + t.Run(version+"/"+spelling.name, func(t *testing.T) { + t.Parallel() + schemas := []string{spelling.kind, "KB: {allOf: [{" + ref("KA") + "}]}", spelling.member, "WB: {allOf: [{" + ref("WA") + "}]}"} + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := parseVerified(t, admissionSpec(version, "", schemas...)) + var found []string + for _, diagnostic := range diags { + if diagnostic.Code != diag.LaterVersionConstruct && diagnostic.Severity != ir.SeverityInfo { + found = append(found, diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + } + slices.Sort(found) + assert.Equal(t, []string{"pass/composition-cycle /components/schemas/WA", "pass/composition-cycle /components/schemas/WB"}, found) + ka := requireComponentScalar(t, doc, "KA", ir.PrimitiveTypeID(ir.PrimitiveString)) + require.Contains(t, ka.Unmodeled, "openapi:$ref") + assert.Equal(t, ir.ReasonDegradedLowering, ka.Unmodeled["openapi:$ref"].Reason) + assert.Equal(t, componentID("KA"), requireComponentScalar(t, doc, "KB", componentID("KA")).Base.Target, + "KB is a use of KA") + wa := requireModelOf(t, doc, "WA") + require.NotNil(t, wa.Base) + assert.Equal(t, componentID("WB"), wa.Base.Target) + require.Len(t, wa.Properties, 1) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/KA/allOf/0"), + "so what its other conjuncts say decides", "KA lowers by what it writes") + }) + }) + } + } +} + +// TestKeywordScope_ABareRefWritingBesideItOnAHopLoopKeepsWhatItWrites holds a +// $ref writing a kind beside it on a loop a pure hop closes, the hop spelt +// alone or beside an entry saying nothing, to its bare twin: the loop is +// reported once, and the member lowers from the keywords beside its $ref, +// keeping the $ref, as the same member on a loop of bare $refs does +// (docs/compilers/openapi.md#reference-cycles). +func TestKeywordScope_ABareRefWritingBesideItOnAHopLoopKeepsWhatItWrites(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "$ref: '#/components/schemas/" + name + "'" } + for _, tc := range []struct { + version, link string + }{ + {"3.0.3", "KB: {allOf: [{" + ref("KA") + "}]}"}, + {"3.1.0", "KB: {allOf: [{" + ref("KA") + "}]}"}, + {"3.1.0", "KB: {allOf: [{" + ref("KA") + "}, true]}"}, + } { + t.Run(tc.version+"/"+tc.link, func(t *testing.T) { + t.Parallel() + inBothOrders(t, []string{"KA: {" + ref("KB") + ", type: string}", tc.link}, func(t *testing.T, links []string) { + bare := []string{"KA: {" + ref("KB") + ", type: string}", "KB: {" + ref("KA") + "}"} + if links[0] != bare[0] { + slices.Reverse(bare) + } + assert.Empty(t, cmp.Diff(loopWritten(t, tc.version, bare), loopWritten(t, tc.version, links), cmp.AllowUnexported(entryWritten{})), + "the link lowers as the bare loop does") + doc, _ := parseVerified(t, admissionSpec(tc.version, "", links...)) + assert.Contains(t, requireComponentScalar(t, doc, "KA", ir.PrimitiveTypeID(ir.PrimitiveString)).Unmodeled, "openapi:$ref") + }) + }) + } +} + +// TestKeywordScope_ALoopThroughAHopIsReadByKind holds a loop closing through a +// hop, spelt alone, beside an entry saying nothing or a note, or nested, while +// the other member writes a kind beside the allOf or on an entry: no pure hop +// loop, so no openapi/cyclic-ref, and read to its greatest fixpoint by kind, NA +// is the string keeping its $ref and NB sits over NA, no kind lost, in either +// declaration order (docs/compilers/openapi.md#reference-cycles). +func TestKeywordScope_ALoopThroughAHopIsReadByKind(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "$ref: '#/components/schemas/" + name + "'" } + kinds := map[string]string{ + "beside": "NA: {allOf: [{" + ref("NB") + "}], type: string}", + "on entry": "NA: {allOf: [{" + ref("NB") + "}, {type: string}]}", + } + links := []struct { + name, link string + versions []string + }{ + {"alone", "NB: {allOf: [{" + ref("NA") + "}]}", bothVersions}, + {"beside a note entry", "NB: {allOf: [{" + ref("NA") + "}, {description: d}]}", bothVersions}, + {"beside a note", "NB: {allOf: [{" + ref("NA") + "}], description: d}", bothVersions}, + {"nested", "NB: {allOf: [{allOf: [{" + ref("NA") + "}]}]}", bothVersions}, + {"beside true", "NB: {allOf: [{" + ref("NA") + "}, true]}", onlyDialect}, + {"beside a comment entry", "NB: {allOf: [{" + ref("NA") + "}, {$comment: c}]}", onlyDialect}, + } + for kindName, kind := range kinds { + for _, link := range links { + for _, version := range link.versions { + t.Run(version+"/"+kindName+"/"+link.name, func(t *testing.T) { + t.Parallel() + inBothOrders(t, []string{kind, link.link}, func(t *testing.T, schemas []string) { + doc, diags := parseVerified(t, admissionSpec(version, "", schemas...)) + requireErrorsAndWarnings(t, diags, nil) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/NA/allOf/0"}, degradedInfoPointers(diags)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, + "/components/schemas/NA/allOf/0"), "which admits every kind there, so what its other conjuncts say decides") + na := requireComponentScalar(t, doc, "NA", ir.PrimitiveTypeID(ir.PrimitiveString)) + assert.Equal(t, degradedKept("openapi:$ref"), keptOn(na), "NA keeps its $ref") + assert.Empty(t, keptOn(requireComponentScalar(t, doc, "NB", componentID("NA"))), "NB sits over NA") + }) + }) + } + } + } +} + +// TestKeywordScope_AHopEveryEntryOfWhichIsOnTheCycleIsAHop holds the second +// form of a pure hop: an allOf every entry of which lies on the cycle closes it +// as one, so the chain is a reference loop, each member the top type keeping +// none of its $refs and each finding the loop's error, the same in either +// declaration order. +func TestKeywordScope_AHopEveryEntryOfWhichIsOnTheCycleIsAHop(t *testing.T) { + t.Parallel() + schemas := []string{ + "A: {allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}", + "B: {allOf: [{$ref: '#/components/schemas/A'}]}", + } + var sites [][]string + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", schemas...)) + var errors []string + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityError || diagnostic.Severity == ir.SeverityWarning { + assert.Equal(t, diag.CyclicRef, diagnostic.Code, "every finding is the loop's: %s", diagnostic.Message) + errors = append(errors, string(diagnostic.Provenance.Pointer)) + } + } + require.NotEmpty(t, errors, "the loop is reported") + slices.Sort(errors) + sites = append(sites, errors) + for _, name := range []string{"A", "B"} { + assert.Empty(t, requireComponentScalar(t, doc, name, ir.PrimitiveTypeID(ir.PrimitiveAny)).Unmodeled, + "%s keeps none of its $refs, as a bare $ref on the loop keeps none", name) + } + }) + if assert.Len(t, sites, 2) { + assert.Equal(t, sites[0], sites[1], "the declaration order moves no report") + } +} + +// TestKeywordScope_ACycleComposingAReferenceOffItStaysAComposition holds the +// other half of GitHub #2042's decision: a cycle through a schema composing a +// reference off the cycle, or writing what says something, is no reference loop +// but a composition read to its fixpoint, `A` composing `O`, reported by the +// composition-cycle pass as at the base, in either order of the entries and of +// the components (docs/ir/models.md#composition). +func TestKeywordScope_ACycleComposingAReferenceOffItStaysAComposition(t *testing.T) { + t.Parallel() + for _, swapped := range []bool{false, true} { + list, _, _ := composeEntries(swapped, "{$ref: '#/components/schemas/B'}", "{$ref: '#/components/schemas/O'}") + schemas := []string{ + "A: {allOf: " + list + "}", + "B: {allOf: [{$ref: '#/components/schemas/A'}]}", + "O: {type: object, properties: {o: {type: string}}}", + "C: {allOf: [{$ref: '#/components/schemas/C'}], properties: {a: {type: string}}}", + } + t.Run(fmt.Sprintf("swapped=%t", swapped), func(t *testing.T) { + t.Parallel() + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", schemas...)) + requireErrorsAndWarnings(t, diags, []wantFinding{ + {code: "pass/composition-cycle", pointer: "/components/schemas/A"}, + {code: "pass/composition-cycle", pointer: "/components/schemas/B"}, + {code: "pass/composition-cycle", pointer: "/components/schemas/C"}, + }) + a := requireModelOf(t, doc, "A") + parents := slices.Clone(a.Mixins) + if a.Base != nil { + parents = append(parents, *a.Base) + } + assert.True(t, slices.ContainsFunc(parents, func(parent ir.TypeRef) bool { + return parent.Target == componentID("O") + }), "A composes O: %v", parents) + c := requireModelOf(t, doc, "C") + require.NotNil(t, c.Base) + assert.Equal(t, componentID("C"), c.Base.Target, "a link writing a member stays a composition") + }) + }) + } +} + +// TestKeywordScope_ATypeListOnAnEntryIsReadAsBesideTheAllOf holds GitHub +// #2039's comment: a type list naming an object, null aside, on an inline +// entry of a composition restates the composed Model as the same list beside +// the allOf does, so neither keeps it, in either declaration order, and the +// null it admits is read alike, a use of either admitting null where every +// conjunct does (docs/compilers/openapi.md#allof-inline-residue). +func TestKeywordScope_ATypeListOnAnEntryIsReadAsBesideTheAllOf(t *testing.T) { + t.Parallel() + schemas := []string{ + "T: {type: object, properties: {a: {type: string}}}", + "Wrap: {allOf: [{$ref: '#/components/schemas/T'}], type: [object, 'null']}", + "Entry: {allOf: [{$ref: '#/components/schemas/T'}, {type: [object, 'null']}]}", + "H: {type: object, properties: {n: {allOf: [{properties: {a: {type: string}}}, {type: [object, 'null']}]}, " + + "w: {allOf: [{properties: {a: {type: string}}}], type: [object, 'null']}}}", + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + for _, name := range []string{"Wrap", "Entry"} { + model := requireModelOf(t, doc, name) + require.NotNil(t, model.Base, name) + assert.Equal(t, componentID("T"), model.Base.Target, name) + assert.Empty(t, keptOn(model), "%s keeps nothing", name) + assert.Zero(t, degradedInfosAt(diags, name), name) + } + holder := requireModelOf(t, doc, "H") + require.Len(t, holder.Properties, 2) + for _, property := range holder.Properties { + assert.True(t, property.Type.Nullable, "%s admits null", property.Name.Source) + } + }) +} diff --git a/compilers/openapi/e2e/keyword_scope_ref_test.go b/compilers/openapi/e2e/keyword_scope_ref_test.go new file mode 100644 index 000000000..0f1ed2079 --- /dev/null +++ b/compilers/openapi/e2e/keyword_scope_ref_test.go @@ -0,0 +1,559 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "maps" + "slices" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// scalarTargets are the named scalars a format or a content keyword is +// written beside a $ref to: plain primitives, a string carrying an encoding of +// its own, and format primitives. +var scalarTargets = []string{ + "S: {type: string, maxLength: 36}", + "I: {type: integer}", + "SX: {type: string, format: x-other}", + "SU: {type: string, format: uuid}", + "I64: {type: integer, format: int64}", + "I32: {type: integer, format: int32}", + "D: {type: string, format: date}", +} + +// besideRefOutcome is how a use beside a $ref to a scalar lowers: as a +// restriction of the reference carrying the keyword's Encoding, rooted at the +// primitive the keyword selects with the reference kept, as the reference +// alone, or as at the base, keeping the keyword. +type besideRefOutcome int + +const ( + restrictsTheReference besideRefOutcome = iota + choosesTheKeyword + saysNothing + keepsTheKeyword +) + +// besideRefCase is one use, what its keyword reads as written flat over the +// target's JSON type, the component it names, the outcome, and where its one +// report is drawn when it draws one. +type besideRefCase struct { + name, use, twin, target string + outcome besideRefOutcome + reportAt string +} + +// assertBesideRef compiles each case's use and twin beside the scalar targets, +// in version and in both declaration orders, and holds the use to its outcome. +func assertBesideRef(t *testing.T, version string, cases []besideRefCase) { + t.Helper() + for _, tc := range cases { + schemas := append(slices.Clone(scalarTargets), "Use: "+tc.use, "Twin: "+tc.twin) + t.Run(tc.name, func(t *testing.T) { + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec(version, "", schemas...)) + use, ok := kindNode(t, doc, componentID("Use")).(*ir.Scalar) + require.True(t, ok, "%s: a use of a scalar is a scalar", tc.name) + require.NotNil(t, use.Base, tc.name) + twin, ok := kindNode(t, doc, componentID("Twin")).(*ir.Scalar) + require.True(t, ok, "%s: the twin is a scalar", tc.name) + require.NotNil(t, twin.Base, tc.name) + assertBesideRefOutcome(t, tc, use, twin, diags) + }) + }) + } +} + +// assertBesideRefOutcome holds use to the outcome tc names, against twin, the +// keyword written flat over the target's JSON type. +func assertBesideRefOutcome(t *testing.T, tc besideRefCase, use, twin *ir.Scalar, diags []ir.Diagnostic) { + t.Helper() + reports := degradedInfoPointers(diags) + var under []string + for _, pointer := range reports { + if strings.HasPrefix(string(pointer), "/components/schemas/Use") { + under = append(under, string(pointer)) + } + } + switch tc.outcome { + case restrictsTheReference: + assert.Equal(t, componentID(tc.target), use.Base.Target, "%s: a restriction of the reference", tc.name) + assert.Equal(t, twinEncodingAt(twin.Encoding, "Use"), use.Encoding, "%s: carrying the Encoding the keyword reads as flat", tc.name) + assert.Empty(t, keptOn(use), tc.name) + assert.Empty(t, under, tc.name) + case choosesTheKeyword: + assert.Equal(t, twin.Base.Target, use.Base.Target, "%s: rooted at the primitive the keyword selects", tc.name) + assert.Equal(t, twin.Encoding, use.Encoding, tc.name) + assert.Equal(t, degradedKept("openapi:$ref"), keptOn(use), "%s: the reference kept as a beaten conjunct", tc.name) + assert.Equal(t, []string{tc.reportAt}, under, "%s: one report, where the $ref is written", tc.name) + case saysNothing: + assert.Equal(t, componentID(tc.target), use.Base.Target, "%s: the reference alone", tc.name) + assert.Nil(t, use.Encoding, tc.name) + assert.Empty(t, keptOn(use), tc.name) + assert.Empty(t, under, tc.name) + case keepsTheKeyword: + assertKeptBesideRef(t, tc, use, diags, under) + default: + t.Fatalf("%s: no outcome %d", tc.name, tc.outcome) + } +} + +// twinEncodingAt returns enc, the twin's Encoding, as written at the component +// named: a content schema it holds is a node of the position writing it, so the +// use's sits at its own pointer where the twin's sits at the twin's. +func twinEncodingAt(enc *ir.Encoding, name string) *ir.Encoding { + if enc == nil || enc.Schema == nil { + return enc + } + out, schema := *enc, *enc.Schema + schema.Target = ir.TypeID(strings.Replace(string(schema.Target), "/components/schemas/Twin/", "/components/schemas/"+name+"/", 1)) + out.Schema = &schema + return &out +} + +// assertKeptBesideRef holds use to a use of the reference keeping the one +// keyword written beside it, for want of a home, with one report saying so in +// the words a kept format draws: the shape is a Scalar, so no report says it +// has no Encoding field. +func assertKeptBesideRef(t *testing.T, tc besideRefCase, use *ir.Scalar, diags []ir.Diagnostic, under []string) { + t.Helper() + assert.Equal(t, componentID(tc.target), use.Base.Target, "%s: a use of the reference", tc.name) + assert.Nil(t, use.Encoding, tc.name) + kept := keptOn(use) + require.Len(t, kept, 1, "%s: the keyword kept", tc.name) + for key, reason := range kept { + assert.Equal(t, ir.ReasonDegradedLowering, reason, "%s: %s is kept for want of a home", tc.name, key) + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, tc.reportAt) + assert.Contains(t, message, "no home for "+strings.TrimPrefix(key, "openapi:"), tc.name) + assert.NotContains(t, message, "no Encoding field", "%s: the shape is a Scalar", tc.name) + } + assert.Equal(t, []string{tc.reportAt}, under, tc.name) +} + +// TestKeywordScope_AFormatBesideARefToAScalarReadsAsItsFlatTwin holds a format +// on a conjunct beside a $ref to a scalar to what its flat twin, the format +// over the target's JSON type, reads: a format selecting no primitive of its +// own restricts the reference with its Encoding unless the target carries +// another; one selecting another primitive over a plain one, or a narrower +// format primitive, is chosen and the reference kept as a passed-over conjunct; +// one the target's primitive already is, or a wider one, says nothing; and one +// neither within nor wider than the target's is kept as at the base +// (docs/compilers/openapi.md#allof-refinement). +func TestKeywordScope_AFormatBesideARefToAScalarReadsAsItsFlatTwin(t *testing.T) { + t.Parallel() + entry := func(target, format string) string { + return "{allOf: [{$ref: '#/components/schemas/" + target + "'}, {format: " + format + "}]}" + } + first := func(target, format string) string { + return "{allOf: [{format: " + format + "}, {$ref: '#/components/schemas/" + target + "'}]}" + } + at := func(i int) string { return fmt.Sprintf("/components/schemas/Use/allOf/%d", i) } + cases := []besideRefCase{ + {"an encoding name over an integer", entry("I", "uuid"), "{type: integer, format: uuid}", "I", restrictsTheReference, ""}, + {"an unknown format over a string", entry("S", "x-fmt"), "{type: string, format: x-fmt}", "S", restrictsTheReference, ""}, + {"an encoding of another name", entry("SX", "x-fmt"), "{type: string, format: x-fmt}", "SX", keepsTheKeyword, at(1)}, + {"uuid over a string", entry("S", "uuid"), "{type: string, format: uuid}", "S", choosesTheKeyword, at(0)}, + {"uuid over a string, the $ref last", first("S", "uuid"), "{type: string, format: uuid}", "S", choosesTheKeyword, at(1)}, + {"int32 over an integer", entry("I", "int32"), "{type: integer, format: int32}", "I", choosesTheKeyword, at(0)}, + {"an int64 as text over a string", entry("S", "int64"), "{type: string, format: int64}", "S", choosesTheKeyword, at(0)}, + {"a restated primitive", entry("SU", "uuid"), "{type: string, format: uuid}", "SU", saysNothing, ""}, + {"a narrower format primitive", entry("I64", "int32"), "{type: integer, format: int32}", "I64", choosesTheKeyword, at(0)}, + {"a wider format primitive", entry("I32", "int64"), "{type: integer, format: int64}", "I32", saysNothing, ""}, + {"a format primitive neither within nor wider", entry("D", "date-time"), "{type: string, format: date-time}", "D", + keepsTheKeyword, at(1)}, + } + for _, version := range bothVersions { + t.Run(version, func(t *testing.T) { + t.Parallel() + assertBesideRef(t, version, cases) + }) + } + t.Run("beside the $ref", func(t *testing.T) { + t.Parallel() + beside := func(target, format string) string { + return "{$ref: '#/components/schemas/" + target + "', format: " + format + "}" + } + assertBesideRef(t, "3.1.0", []besideRefCase{ + {"an encoding name over an integer", beside("I", "uuid"), "{type: integer, format: uuid}", "I", restrictsTheReference, ""}, + {"uuid over a string", beside("S", "uuid"), "{type: string, format: uuid}", "S", choosesTheKeyword, + "/components/schemas/Use"}, + }) + }) +} + +// TestKeywordScope_TheContentVocabularyBesideARefToAStringRestrictsIt holds +// `contentEncoding`, `contentMediaType` and `contentSchema` beside a $ref to a +// string, or beside an allOf of one, to a restriction of the reference +// carrying the Encoding they read as flat over a string, with nothing kept, +// where the base keeps them under no_ir_home as written on a shape with no +// Encoding field (GitHub #2326); beside a target carrying an encoding of +// another name they are kept for want of a home, reported as a format there +// is. +func TestKeywordScope_TheContentVocabularyBesideARefToAStringRestrictsIt(t *testing.T) { + t.Parallel() + const ref = "$ref: '#/components/schemas/" + assertBesideRef(t, "3.1.0", []besideRefCase{ + {"contentEncoding", "{" + ref + "S', contentEncoding: base64}", "{type: string, contentEncoding: base64}", "S", + restrictsTheReference, ""}, + {"contentEncoding beside an allOf", "{allOf: [{" + ref + "S'}], contentEncoding: base64}", + "{type: string, contentEncoding: base64}", "S", restrictsTheReference, ""}, + {"contentMediaType", "{" + ref + "S', contentMediaType: text/plain}", "{type: string, contentMediaType: text/plain}", "S", + restrictsTheReference, ""}, + {"contentSchema", "{" + ref + "S', contentMediaType: application/json, contentSchema: {type: object}}", + "{type: string, contentMediaType: application/json, contentSchema: {type: object}}", "S", restrictsTheReference, ""}, + {"an encoding of another name", "{" + ref + "SX', contentEncoding: base64}", "{type: string, contentEncoding: base64}", "SX", + keepsTheKeyword, "/components/schemas/Use"}, + {"an encoding of another name beside an allOf", "{allOf: [{" + ref + "SX'}], contentEncoding: base64}", + "{type: string, contentEncoding: base64}", "SX", keepsTheKeyword, "/components/schemas/Use"}, + {"an encoding of another name on an entry", "{allOf: [{" + ref + "SX'}, {contentEncoding: base64}]}", + "{type: string, contentEncoding: base64}", "SX", keepsTheKeyword, "/components/schemas/Use/allOf/1"}, + }) +} + +// TestKeywordScope_AUUIDBesideARefToAStringIsAUUID holds GitHub #2107's +// minimal form of the golden spec's three sites: a property whose allOf +// conjoins a $ref to a string with an entry writing `format: uuid` is a uuid, +// the reference kept once as a beaten conjunct with one report at its entry, +// where the base keeps the format. +func TestKeywordScope_AUUIDBesideARefToAStringIsAUUID(t *testing.T) { + t.Parallel() + const property = "{type: string, allOf: [{$ref: '#/components/schemas/U'}, {format: uuid, readOnly: true, type: string}]}" + schemas := []string{ + "U: {type: string, maxLength: 36}", + "P: {type: object, properties: {id: " + property + "}}", + "F: {type: object, properties: {id: {type: string, maxLength: 36, format: uuid}}}", + } + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.0.3", "", schemas...)) + requireErrorsAndWarnings(t, diags, nil) + p, f := modelPropertyType(t, doc, "P", "id"), modelPropertyType(t, doc, "F", "id") + assert.Equal(t, rootPrimitive(t, doc, f), rootPrimitive(t, doc, p), "P's id is the uuid F's is") + var refs []unmodeledSite + for _, site := range unmodeledSites(doc) { + if strings.Contains(site.path, "components/schemas/P") && site.key == "openapi:$ref" { + refs = append(refs, site) + } + } + require.Len(t, refs, 1, "the reference is kept once") + assert.Equal(t, ir.ReasonDegradedLowering, refs[0].entry.Reason) + assert.Contains(t, string(refs[0].entry.Value), "#/components/schemas/U") + assert.Empty(t, cmp.Diff([]string{"/components/schemas/P/properties/id/allOf/0"}, pointerTexts(degradedInfoPointers(diags)))) + }) +} + +// modelPropertyType returns the type the property wire of the model named +// refers to. +func modelPropertyType(t *testing.T, doc *ir.Document, model, wire string) ir.TypeID { + t.Helper() + holder, ok := kindNode(t, doc, componentID(model)).(*ir.Model) + require.True(t, ok, "%s is a model", model) + for _, property := range holder.Properties { + if property.WireName == wire { + return property.Type.Target + } + } + require.Failf(t, "no property", "%s declares no %s", model, wire) + return "" +} + +// rootPrimitive follows id through the Bases of scalars to the node no scalar +// restricts, bounded by the document's size. +func rootPrimitive(t *testing.T, doc *ir.Document, id ir.TypeID) ir.TypeID { + t.Helper() + seen := map[ir.TypeID]bool{} + for !seen[id] { + seen[id] = true + scalar, ok := doc.Types[id].(*ir.Scalar) + if !ok || scalar.Base == nil { + return id + } + id = scalar.Base.Target + } + require.Failf(t, "a loop of bases", "%s", slices.Sorted(maps.Keys(seen))) + return "" +} + +// pointerTexts renders pointers for a comparison with literals. +func pointerTexts[P ~string](pointers []P) []string { + out := make([]string, 0, len(pointers)) + for _, pointer := range pointers { + out = append(out, string(pointer)) + } + return out +} + +// TestKeywordScope_ARestrictionOfAReferenceIsAtEveryPosition holds a +// format selecting no primitive, and the content vocabulary, beside a $ref to +// a scalar, in both spellings, to the node the flat spelling builds at every +// place a use is written: a Scalar of the position's own over the reference, +// carrying the Encoding, a carrier keeping nothing of it. A carrier holds what +// else the position declares, so the node is hoisted for the Encoding alone. +func TestKeywordScope_ARestrictionOfAReferenceIsAtEveryPosition(t *testing.T) { + t.Parallel() + const target = "I: {type: integer}" + const text = "S: {type: string}" + for _, tc := range []struct { + use, target string + want ir.Encoding + }{ + {"{" + refTo("I") + ", format: uuid}", target, ir.Encoding{Name: "uuid"}}, + {"{allOf: [{" + refTo("I") + "}, {format: uuid}]}", target, ir.Encoding{Name: "uuid"}}, + {"{" + refTo("S") + ", contentEncoding: base64}", text, ir.Encoding{Name: "base64"}}, + {"{allOf: [{" + refTo("S") + "}], contentMediaType: text/plain}", text, ir.Encoding{MediaType: "text/plain"}}, + } { + for _, site := range conjSites { + doc, diags := compileUnrefused(t, site.write("3.1.0", tc.use, tc.target)) + var restriction *ir.Scalar + for _, td := range doc.Types { + if scalar, ok := td.(*ir.Scalar); ok && string(scalar.Provenance.Pointer) == site.pointer { + restriction = scalar + } + } + require.NotNil(t, restriction, "%s at %s: a node of the position's own", tc.use, site.name) + require.NotNil(t, restriction.Base, "%s at %s", tc.use, site.name) + assert.Equal(t, componentID(strings.SplitN(tc.target, ":", 2)[0]), restriction.Base.Target, "%s at %s", tc.use, site.name) + assert.Equal(t, &tc.want, restriction.Encoding, "%s at %s", tc.use, site.name) + assert.Empty(t, restriction.Unmodeled, "%s at %s", tc.use, site.name) + assert.Empty(t, degradedInfoPointers(diags), "%s at %s: nothing is kept", tc.use, site.name) + } + } +} + +// enumTargets are the enums a format is written beside a $ref to: a string's +// and an integer's, one writing a format of its own, and a link restricting +// the string's. +var enumTargets = []string{ + "E: {type: string, enum: [a, b]}", + "IE: {type: integer, enum: [1, 2]}", + "EF: {type: string, enum: [a, b], format: date}", + "L: {allOf: [{$ref: '#/components/schemas/E'}, {format: email}]}", +} + +// TestKeywordScope_AFormatBesideARefToAnEnumRestrictsIt holds a format +// selecting no primitive, on a conjunct beside a $ref to an enum, to a +// restriction of the reference carrying an Encoding naming the format, with +// nothing kept: the members stay the enum's, and the document holds no Enum the +// targets do not write. One selecting a primitive is kept, and so, through a +// link restricting the enum, is one of another name, while one of the link's +// name says nothing; beside an enum writing a format of its own one is kept, as +// at any use (docs/compilers/openapi.md#allof-refinement). +func TestKeywordScope_AFormatBesideARefToAnEnumRestrictsIt(t *testing.T) { + t.Parallel() + entry := func(target, beside string) string { + return "{allOf: [{$ref: '#/components/schemas/" + target + "'}, " + beside + "]}" + } + cases := []struct { + name, use, target string + encoding *ir.Encoding + kept bool + }{ + {"email on an entry", entry("E", "{format: email}"), "E", &ir.Encoding{Name: "email"}, false}, + {"email, the $ref last", "{allOf: [{format: email}, {$ref: '#/components/schemas/E'}]}", "E", &ir.Encoding{Name: "email"}, false}, + {"beside a type naming the enum's", entry("E", "{type: string, format: email}"), "E", &ir.Encoding{Name: "email"}, false}, + {"an unknown format", entry("E", "{format: x-fmt}"), "E", &ir.Encoding{Name: "x-fmt"}, false}, + {"an unknown format over an integer enum", entry("IE", "{format: x-int}"), "IE", &ir.Encoding{Name: "x-int"}, false}, + {"uuid on an entry", entry("E", "{format: uuid}"), "E", nil, true}, + {"int64 over an integer enum", entry("IE", "{format: int64}"), "IE", nil, true}, + {"the name a link carries", entry("L", "{format: email}"), "L", nil, false}, + {"another name than a link carries", entry("L", "{format: hostname}"), "L", nil, true}, + {"beside an enum writing a format", entry("EF", "{format: uuid}"), "EF", nil, true}, + } + for _, version := range bothVersions { + for _, tc := range cases { + t.Run(version+"/"+tc.name, func(t *testing.T) { + t.Parallel() + inBothOrders(t, append(slices.Clone(enumTargets), "Use: "+tc.use), func(t *testing.T, schemas []string) { + doc, diags := parseVerified(t, admissionSpec(version, "", schemas...)) + openapitest.RequireNoErrorDiags(t, diags) + link := requireComponentScalar(t, doc, "L", componentID("E")) + assert.Equal(t, &ir.Encoding{Name: "email"}, link.Encoding, "the link restricts the enum") + use := requireComponentScalar(t, doc, "Use", componentID(tc.target)) + assert.Equal(t, tc.encoding, use.Encoding) + if tc.kept { + assert.Equal(t, degradedKept("openapi:format"), keptOn(use), "the format kept, as at any use") + } else { + assert.Empty(t, keptOn(use)) + } + assertEnumsAre(t, doc, "E", "IE", "EF") + }) + }) + } + } +} + +// TestKeywordScope_AFormatBesideARefToAnEnumRestrictsItAtACarrier holds the +// restriction where the $ref is written beside the format, and at a property, +// whose carrier holds what else it declares: the node of the position's own, +// a Scalar over the enum carrying the Encoding, as at a component. +func TestKeywordScope_AFormatBesideARefToAnEnumRestrictsItAtACarrier(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", append(slices.Clone(enumTargets), + "Beside: {$ref: '#/components/schemas/E', format: email}", + "Holder: {type: object, properties: {p: {allOf: [{$ref: '#/components/schemas/E'}, {format: email}]}}}")...)) + openapitest.RequireNoErrorDiags(t, diags) + beside := requireComponentScalar(t, doc, "Beside", componentID("E")) + assert.Equal(t, &ir.Encoding{Name: "email"}, beside.Encoding) + assert.Empty(t, keptOn(beside)) + holder, ok := kindNode(t, doc, componentID("Holder")).(*ir.Model) + require.True(t, ok) + require.Len(t, holder.Properties, 1) + property, ok := kindNode(t, doc, holder.Properties[0].Type.Target).(*ir.Scalar) + require.True(t, ok, "the property names a node of its own") + require.NotNil(t, property.Base) + assert.Equal(t, componentID("E"), property.Base.Target) + assert.Equal(t, &ir.Encoding{Name: "email"}, property.Encoding) + assertEnumsAre(t, doc, "E", "IE", "EF") +} + +// TestKeywordScope_AFormatSelectingAPrimitiveBesideARefToAnEnumIsKept holds a +// format the compiler gives a primitive of its own, one of each kind, beside a +// $ref to an enum of its type, flat, on an entry or beside the allOf: no +// Encoding is named after it, and the enum's members are not rooted at it, so +// the position is the use of the enum keeping the format, degraded_lowering, +// with one info worded as a kept format's is +// (docs/compilers/openapi.md#allof-refinement). +func TestKeywordScope_AFormatSelectingAPrimitiveBesideARefToAnEnumIsKept(t *testing.T) { + t.Parallel() + targets := []string{"E: {type: string, enum: [a, b]}", "IE: {type: integer, enum: [1, 2]}", "NE: {type: number, enum: [1.5, 2]}"} + formats := map[string][]string{ + "E": {"uuid", "uri", "date-time", "date", "time-local", "duration", "binary", "byte", "http-date", "int64"}, + "IE": {"int32", "int64", "uint8", "unixtime"}, + "NE": {"float", "double", "decimal", "int32"}, + } + spellings := map[string]func(target, format string) (use, writer string){ + "flat": func(target, format string) (string, string) { + return "{$ref: '#/components/schemas/" + target + "', format: " + format + "}", "/components/schemas/Use" + }, + "entry": func(target, format string) (string, string) { + return "{allOf: [{$ref: '#/components/schemas/" + target + "'}, {format: " + format + "}]}", "/components/schemas/Use/allOf/1" + }, + "beside": func(target, format string) (string, string) { + return "{allOf: [{$ref: '#/components/schemas/" + target + "'}], format: " + format + "}", "/components/schemas/Use" + }, + } + for _, version := range bothVersions { + for spellingName, spell := range spellings { + for target, written := range formats { + for _, format := range written { + t.Run(version+"/"+spellingName+"/"+target+"/"+format, func(t *testing.T) { + t.Parallel() + use, writer := spell(target, format) + doc, diags := parseVerified(t, admissionSpec(version, "", append(slices.Clone(targets), "Use: "+use)...)) + openapitest.RequireNoErrorDiags(t, diags) + scalar := requireComponentScalar(t, doc, "Use", componentID(target)) + assert.Nil(t, scalar.Encoding, "no Encoding is named after a recognized format") + assert.Equal(t, degradedKept("openapi:format"), keptOn(scalar)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, writer), + "has no home for format") + assertEnumsAre(t, doc, "E", "IE", "NE") + }) + } + } + } + } +} + +// TestKeywordScope_AFormatBesideARefReadsKindsWithNullAside holds a format +// beside a $ref whose target, conjunct or position writes a type list naming +// null to the reading its 3.0 twin, `nullable: true`, gets, and one whose +// target is spelt through an allOf holding no $ref to its flat twin's: a format +// selecting no primitive restricts the reference, and uuid chooses its +// conjunct, keeping the $ref, flat, on an entry or beside the allOf +// (docs/compilers/openapi.md#allof-refinement). +func TestKeywordScope_AFormatBesideARefReadsKindsWithNullAside(t *testing.T) { + t.Parallel() + nullable := map[string]string{"3.0.3": "type: string, nullable: true", "3.1.0": "type: [string, 'null']"} + ref := func(target string) string { return "$ref: '#/components/schemas/" + target + "'" } + for _, version := range bothVersions { + targets := []string{"S: {type: string}", "SN: {" + nullable[version] + "}", "TA: {allOf: [{type: string}, {maxLength: 3}]}"} + for _, tc := range []struct { + name, use, target string + chosen bool + }{ + {"a nullable target, flat", "{" + ref("SN") + ", format: email}", "SN", false}, + {"a nullable target, on an entry", "{allOf: [{" + ref("SN") + "}, {format: email}]}", "SN", false}, + {"a nullable target, beside", "{allOf: [{" + ref("SN") + "}], format: email}", "SN", false}, + {"a nullable target choosing uuid", "{allOf: [{" + ref("SN") + "}, {format: uuid}]}", "SN", true}, + {"a nullable conjunct", "{allOf: [{" + ref("S") + "}, {" + nullable[version] + ", format: email}]}", "S", false}, + {"a nullable conjunct choosing uuid", "{allOf: [{" + ref("S") + "}, {" + nullable[version] + ", format: uuid}]}", "S", true}, + {"a nullable position", "{allOf: [{" + ref("S") + "}, {format: email}], " + nullable[version] + "}", "S", false}, + {"a target spelt through allOf, flat", "{" + ref("TA") + ", format: email}", "TA", false}, + {"a target spelt through allOf, on an entry", "{allOf: [{" + ref("TA") + "}, {format: email}]}", "TA", false}, + {"a target spelt through allOf, beside", "{allOf: [{" + ref("TA") + "}], format: email}", "TA", false}, + {"a target spelt through allOf choosing uuid", "{allOf: [{" + ref("TA") + "}, {format: uuid}]}", "TA", true}, + } { + t.Run(version+"/"+tc.name, func(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec(version, "", append(slices.Clone(targets), "Use: "+tc.use)...)) + openapitest.RequireNoErrorDiags(t, diags) + if tc.chosen { + scalar := requireComponentScalar(t, doc, "Use", ir.PrimitiveTypeID(ir.PrimitiveUUID)) + assert.Equal(t, degradedKept("openapi:$ref"), keptOn(scalar), "the $ref is kept") + return + } + scalar := requireComponentScalar(t, doc, "Use", componentID(tc.target)) + assert.Equal(t, &ir.Encoding{Name: "email"}, scalar.Encoding, "the format restricts the reference") + assert.Empty(t, keptOn(scalar)) + }) + } + } +} + +// assertEnumsAre holds the Enums doc holds to the components named. +func assertEnumsAre(t *testing.T, doc *ir.Document, names ...string) { + t.Helper() + var got []ir.TypeID + for id, td := range doc.Types { + if _, ok := td.(*ir.Enum); ok { + got = append(got, id) + } + } + want := make([]ir.TypeID, 0, len(names)) + for _, name := range names { + want = append(want, componentID(name)) + } + slices.Sort(got) + slices.Sort(want) + assert.Equal(t, want, got, "no member is copied") +} + +// TestKeywordScope_TheContentVocabularyBesideARefToAnEnumLowersAsItsTwin +// holds contentEncoding and contentMediaType beside a $ref to an enum, on an +// entry or beside the $ref, to their flat twin, the keyword on the enum: an +// Enum has no Encoding field, so the twin keeps it verbatim, and the use keeps +// it under the same key and reason, carrying no Encoding +// (docs/compilers/openapi.md#allof-refinement). +func TestKeywordScope_TheContentVocabularyBesideARefToAnEnumLowersAsItsTwin(t *testing.T) { + t.Parallel() + for name, written := range map[string]string{"contentEncoding": "contentEncoding: base64", "contentMediaType": "contentMediaType: text/plain"} { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", "E: {type: string, enum: [a, b]}", + "Twin: {type: string, enum: [a, b], "+written+"}", + "Entry: {allOf: [{$ref: '#/components/schemas/E'}, {"+written+"}]}", + "Beside: {$ref: '#/components/schemas/E', "+written+"}")) + openapitest.RequireNoErrorDiags(t, diags) + twin, ok := kindNode(t, doc, componentID("Twin")).(*ir.Enum) + require.True(t, ok, "the twin is an Enum") + want := keptOn(twin) + require.Equal(t, map[string]ir.UnmodeledReason{"openapi:" + name: ir.ReasonNoIRHome}, want, "the twin keeps the keyword") + for _, use := range []string{"Entry", "Beside"} { + scalar := requireComponentScalar(t, doc, use, componentID("E")) + assert.Nil(t, scalar.Encoding, "%s carries no Encoding", use) + assert.Equal(t, want, keptOn(scalar), "%s keeps what its twin keeps", use) + } + assertEnumsAre(t, doc, "E", "Twin") + }) + } +} diff --git a/compilers/openapi/e2e/keyword_scope_spelling_test.go b/compilers/openapi/e2e/keyword_scope_spelling_test.go new file mode 100644 index 000000000..1990c50a5 --- /dev/null +++ b/compilers/openapi/e2e/keyword_scope_spelling_test.go @@ -0,0 +1,175 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "slices" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// reachSites are the positions a spelling is held to its flat twin at: a +// component, a property, a parameter and an items, each of which builds or +// carries its node differently. +func reachSites() []conjSite { + return []conjSite{conjSites[0], conjSites[1], conjSites[2], conjSites[4]} +} + +// spelledAt compiles schema at site in version, beside others, and reads it as +// the entry grid does: each entry's pointer under the site read as the site's, +// and a whole entry's key without its index. +func spelledAt(t *testing.T, version string, site conjSite, schema string, others ...string) entryWritten { + t.Helper() + doc, diags := compileUnrefused(t, site.write(version, schema, others...)) + relocate := relocater(site.pointer) + got := entryWritten{doc: relocate(withoutVersion(t, doc))} + for _, diagnostic := range diags { + got.diags = append(got.diags, fmt.Sprintf("%s %s %s", diagnostic.Severity, diagnostic.Code, + relocate(string(diagnostic.Provenance.Pointer)))) + } + slices.Sort(got.diags) + return got +} + +// flatTwin is a schema written flat, the versions it is written at, and the +// spellings that write its keywords across an allOf and lower as it does. +type flatTwin struct { + name, flat string + versions []string + spellings []string +} + +// assertLowersAsFlat holds each spelling of each twin, at each site and +// version, to the document and findings its flat twin compiles to there. +func assertLowersAsFlat(t *testing.T, twins []flatTwin, sites []conjSite) { + t.Helper() + for _, twin := range twins { + for _, version := range twin.versions { + for _, site := range sites { + want := spelledAt(t, version, site, twin.flat) + for _, spelling := range twin.spellings { + got := spelledAt(t, version, site, spelling) + assert.Empty(t, cmp.Diff(want, got, cmp.AllowUnexported(entryWritten{})), + "%s at %s in %s: %s lowers as %s", twin.name, site.name, version, spelling, twin.flat) + } + } + } + } +} + +// onlyDialect is the version a twin writing a keyword only JSON Schema 2020-12 +// defines is written at; one 3.0 defines too is written at bothVersions. +var onlyDialect = []string{"3.1.0"} + +// TestKeywordScope_AnEntrysObjectBoundReachesTheObjectVariant holds GitHub +// #2062's reproduction: an object bound on an entry beside a type list is the +// object variant's, as written beside the list, and a string bound the string +// variant's, with nothing kept on the union. +func TestKeywordScope_AnEntrysObjectBoundReachesTheObjectVariant(t *testing.T) { + t.Parallel() + assertLowersAsFlat(t, []flatTwin{ + {"Entry", "{type: [object, string], minProperties: 2, minLength: 2}", onlyDialect, []string{ + "{type: [object, string], allOf: [{minProperties: 2, minLength: 2}]}", + "{minProperties: 2, minLength: 2, allOf: [{type: [object, string]}]}", + "{allOf: [{type: [object, string]}, {minProperties: 2, minLength: 2}]}", + "{allOf: [{minProperties: 2, minLength: 2}, {type: [object, string]}]}", + }}, + }, reachSites()) +} + +// TestKeywordScope_ABoundBesideAPrimitivePrincipalReachesTheFlatNode holds +// GitHub #2116's reproduction: a bound the primitive does not take, written +// beside an allOf whose inline principal is that primitive or on another entry, +// reaches the node the flat spelling hoists at a property or a parameter, +// rather than the carrier, as at a component and an items. +func TestKeywordScope_ABoundBesideAPrimitivePrincipalReachesTheFlatNode(t *testing.T) { + t.Parallel() + assertLowersAsFlat(t, []flatTwin{ + {"E and B", "{type: string, minimum: 1}", bothVersions, []string{ + "{allOf: [{type: string}, {minimum: 1}]}", + "{allOf: [{minimum: 1}, {type: string}]}", + "{allOf: [{type: string}], minimum: 1}", + }}, + {"a text bound beside an integer", "{type: integer, minLength: 1}", bothVersions, []string{ + "{allOf: [{type: integer}], minLength: 1}", + "{allOf: [{type: integer}, {minLength: 1}]}", + }}, + }, reachSites()) +} + +// TestKeywordScope_ABoundBesideANumberAsTextIsTheTextVariants holds GitHub +// #2117's reproduction: a value bound beside an allOf whose inline principal is +// a type list carrying a number as text, or on another entry, is kept on the +// text variant as written flat, not on the union. Two conjuncts writing one +// bound, the list among them, intersect as the fold intersects any bound's, and +// the variant keeps the value they intersect in, as written flat. A list +// written beside the allOf keeps the bound once, on the variant, the union +// keeping none of it. +func TestKeywordScope_ABoundBesideANumberAsTextIsTheTextVariants(t *testing.T) { + t.Parallel() + assertLowersAsFlat(t, []flatTwin{ + {"a list beside the allOf", "{type: [string, object], format: int64, maximum: 9}", onlyDialect, []string{ + "{type: [string, object], format: int64, allOf: [{maximum: 9}]}", + "{allOf: [{type: [string, object], format: int64}], maximum: 9}", + "{allOf: [{type: [string, object], format: int64}, {maximum: 9}]}", + }}, + {"Beside and Entry", "{type: [string, boolean], format: int64, minimum: 31}", onlyDialect, []string{ + "{allOf: [{type: [string, boolean], format: int64}], minimum: 31}", + "{allOf: [{type: [string, boolean], format: int64}, {minimum: 31}]}", + "{allOf: [{minimum: 31}, {type: [string, boolean], format: int64}]}", + }}, + {"two writers", "{type: [string, boolean], format: int64, minimum: 40, maxLength: 5}", onlyDialect, []string{ + "{allOf: [{type: [string, boolean], format: int64}, {minimum: 31, maxLength: 5}, {minimum: 40, maxLength: 9}]}", + "{allOf: [{type: [string, boolean], format: int64}, {minimum: 40, maxLength: 9}], minimum: 31, maxLength: 5}", + "{allOf: [{type: [string, boolean], format: int64, minimum: 31, maxLength: 5}, {minimum: 40, maxLength: 9}]}", + }}, + }, reachSites()) +} + +// TestKeywordScope_TwoBoundsBesideANumberAsTextNoValueHoldsPart holds two +// conjuncts writing a bound on a type list's variant carrying a number as text +// that intersect in no one value, two patterns, as the fold holds conjuncts +// that part: the variant keeps neither, and each entry is kept whole where the +// position keeps it, with the info that the conjuncts disagree, under +// no_ir_home, as a node carrying a number as text holds none of its bounds. +func TestKeywordScope_TwoBoundsBesideANumberAsTextNoValueHoldsPart(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", + "P: {allOf: [{type: [string, boolean], format: int64}, {pattern: a}, {pattern: b}]}")) + union := kindNode(t, doc, componentID("P")) + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:allOf/1": ir.ReasonNoIRHome, "openapi:allOf/2": ir.ReasonNoIRHome}, keptOn(union)) + for _, td := range doc.Types { + if scalar, ok := td.(*ir.Scalar); ok && strings.HasPrefix(string(scalar.ID), "type/anonymous/components/schemas/P/") { + assert.Empty(t, scalar.Unmodeled, "%s keeps no pattern", scalar.ID) + } + } + for _, at := range []string{"/components/schemas/P/allOf/1", "/components/schemas/P/allOf/2"} { + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at) + assert.Contains(t, message, "disagree", at) + } +} + +// TestKeywordScope_AFormatBesideAnInlinePrincipalEncodesItsScalars holds the +// inline half of GitHub #2107's reproduction: a format beside an allOf whose +// inline principal is a scalar or a type list, or on another entry, gives each +// scalar its Encoding as written flat, where the base keeps it on the node. +func TestKeywordScope_AFormatBesideAnInlinePrincipalEncodesItsScalars(t *testing.T) { + t.Parallel() + assertLowersAsFlat(t, []flatTwin{ + {"Beside and Entry", "{type: [string, integer], format: x-fmt}", onlyDialect, []string{ + "{allOf: [{type: [string, integer]}], format: x-fmt}", + "{allOf: [{type: [string, integer]}, {format: x-fmt}]}", + "{allOf: [{format: x-fmt}, {type: [string, integer]}]}", + }}, + {"SBeside", "{type: string, format: x-fmt}", onlyDialect, []string{"{allOf: [{type: string}], format: x-fmt}"}}, + }, reachSites()) +} diff --git a/compilers/openapi/e2e/kind_inference_conjunction_test.go b/compilers/openapi/e2e/kind_inference_conjunction_test.go index 8b9b95f2d..684224a83 100644 --- a/compilers/openapi/e2e/kind_inference_conjunction_test.go +++ b/compilers/openapi/e2e/kind_inference_conjunction_test.go @@ -91,7 +91,7 @@ func keptUnder(doc *ir.Document, at jsontext.Pointer) map[jsontext.Pointer]ir.Un // openapi/degraded-construct is drawn at, once per info. func degradedUnder(diags []ir.Diagnostic, at jsontext.Pointer) []jsontext.Pointer { return slices.DeleteFunc(degradedInfoPointers(diags), func(pointer jsontext.Pointer) bool { - return pointer != at && !strings.HasPrefix(string(pointer), string(at)+"/") + return !underPointer(string(pointer), string(at)) }) } @@ -262,10 +262,10 @@ func assertOutvotedRef(t *testing.T, spec, target string, refAt int) { // $ref names a schema the policy reads as a list: nothing beside it declares // another kind, so the position is a use of the list, holding the bound // written beside it and keeping nothing, a `type: array` beside it among what -// the list already says. With the policy off the target is the top type: the +// the list says. With the policy off the target is the top type: the // position is a use of it holding the bound, and beside a declared array the // list the entry declaring it builds, keeping the $ref, which says nothing of -// the kind. +// the kind. At 3.0 the target's `items` keeps any warning off. func TestKindInference_AUseOfAnInferredKindIsAnAliasOfIt(t *testing.T) { t.Parallel() ref := "{$ref: '#/components/schemas/E'}" @@ -302,7 +302,7 @@ func TestKindInference_AUseOfAnInferredKindIsAnAliasOfIt(t *testing.T) { assert.Empty(t, degradedUnder(onDiags, conjunctionPositions[0])) assertMinItems(t, alias.Constraints, tc.minItems) off, offDiags := compileKindInference(t, "use", spec, true) - requireErrorsAndWarnings(t, offDiags, missingItemsOf(version, tc.offKept, entries, tc.b)) + requireErrorsAndWarnings(t, offDiags, nil) assert.Equal(t, tc.off, kindNode(t, off, componentID("Pos")).Kind()) assert.Equal(t, tc.offKept, len(keptUnder(off, conjunctionPositions[0])) == 1) }) @@ -312,17 +312,6 @@ func TestKindInference_AUseOfAnInferredKindIsAnAliasOfIt(t *testing.T) { } } -// missingItemsOf is the warning a 3.0 array writing no items draws where the -// entry typed, written among entries, is what the position is a use of, the -// $ref beside it kept. -func missingItemsOf(version string, kept bool, entries []string, typed string) []wantFinding { - if version != "3.0.3" || !kept { - return nil - } - return []wantFinding{{code: diag.MissingArrayItems, pointer: fmt.Sprintf("/components/schemas/Pos/allOf/%d", - slices.Index(entries, typed))}} -} - // assertMinItems holds constraints to a minItems of want, and to none where // want is 0. func assertMinItems(t *testing.T, constraints *ir.Constraints, want int) { @@ -453,13 +442,14 @@ func TestKindInference_AFormBodyKeysNoPartItsModelLacks(t *testing.T) { const restatingObjects = "oneOf: [{type: object, required: [a]}, {type: object, required: [b]}]}" // TestKindInference_WhatAPositionSaysIsReadOffWhatItLowersTo holds the readers -// asking whether a position already says what a keyword does to the node what -// it compares to lowers to: a property set the policy reads as an object, as a -// property or an allOf entry of a body, restates `type: object`, a branch -// writing `items` admits no string beside a string the allOf lowers to, and -// branches the policy reads as objects take a bare `required`; with the policy -// off, each is the top type. Keywords beside branches each declaring an object -// are that object under either policy, as beside `type: object`. +// asking whether a position says what a keyword does to what it compares to +// lowers to: a property set the policy reads as an object +// restates `type: object`, and branches it reads as objects take a bare +// `required`; with the policy off, each is the top type. A branch writing +// `items` beside a string declares shape, so the branches conjoin with it. +// Keywords beside branches declaring an object are that object; where they +// close it, every branch requires a member the closure refuses, so the +// position is the closed model keeping the union, with one warning. func TestKindInference_WhatAPositionSaysIsReadOffWhatItLowersTo(t *testing.T) { t.Parallel() schemas := []string{ @@ -481,14 +471,14 @@ func TestKindInference_WhatAPositionSaysIsReadOffWhatItLowersTo(t *testing.T) { want := map[bool]map[string]outcome{ false: { "Nested": {ir.KindModel, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}}, - "HeldUnion": {ir.KindScalar, map[string]ir.UnmodeledReason{}}, + "HeldUnion": {ir.KindUnion, map[string]ir.UnmodeledReason{}}, "BareRequired": {ir.KindUnion, map[string]ir.UnmodeledReason{}}, "Entry": {ir.KindModel, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}}, "RefEntry": {ir.KindModel, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}}, }, true: { "Nested": {ir.KindUnion, map[string]ir.UnmodeledReason{}}, - "HeldUnion": {ir.KindScalar, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonDegradedLowering}}, + "HeldUnion": {ir.KindUnion, map[string]ir.UnmodeledReason{}}, "BareRequired": {ir.KindScalar, map[string]ir.UnmodeledReason{ "openapi:oneOf": ir.ReasonDegradedLowering, "openapi:required": ir.ReasonDegradedLowering}}, "Entry": {ir.KindUnion, map[string]ir.UnmodeledReason{}}, @@ -496,9 +486,10 @@ func TestKindInference_WhatAPositionSaysIsReadOffWhatItLowersTo(t *testing.T) { }, } for _, off := range []bool{false, true} { - for _, name := range []string{"Closed", "Required", "Typed"} { + for _, name := range []string{"Required", "Typed"} { want[off][name] = outcome{ir.KindModel, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}} } + want[off]["Closed"] = outcome{ir.KindModel, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonDegradedLowering}} } for _, version := range []string{"3.0.3", "3.1.0"} { t.Run(version, func(t *testing.T) { @@ -506,7 +497,8 @@ func TestKindInference_WhatAPositionSaysIsReadOffWhatItLowersTo(t *testing.T) { inBothOrders(t, schemas, func(t *testing.T, schemas []string) { for _, off := range []bool{false, true} { doc, diags := compileKindInference(t, "says", admissionSpec(version, "", schemas...), off) - requireErrorsAndWarnings(t, diags, nil) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, + pointer: "/components/schemas/Closed", contains: []string{"oneOf/0: a", "oneOf/1: b"}}}) for name, outcome := range want[off] { td := kindNode(t, doc, componentID(name)) assert.Equal(t, outcome.kind, td.Kind(), "%s off=%t", name, off) diff --git a/compilers/openapi/e2e/kind_inference_distribution_test.go b/compilers/openapi/e2e/kind_inference_distribution_test.go index 115f20c81..c4f682172 100644 --- a/compilers/openapi/e2e/kind_inference_distribution_test.go +++ b/compilers/openapi/e2e/kind_inference_distribution_test.go @@ -5,7 +5,6 @@ package e2e_test import ( "encoding/json/jsontext" - "encoding/json/v2" "fmt" "maps" "slices" @@ -15,6 +14,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) @@ -50,31 +50,16 @@ func distributedOver(t *testing.T, doc *ir.Document, id ir.TypeID) map[ir.TypeID return out } -// unionAsWritten is the union at id with each variant's node in place of its -// reference, encoded less the IDs, names and provenance a twin written at -// another component cannot share. -func unionAsWritten(t *testing.T, doc *ir.Document, id ir.TypeID) string { - t.Helper() - union, ok := kindNode(t, doc, id).(*ir.Union) - require.True(t, ok, "%s is a union", id) - tree := nodeWithoutNames(t, doc, id) - variants := make([]any, 0, len(union.Variants)) - for _, variant := range union.Variants { - variants = append(variants, nodeWithoutNames(t, doc, variant.Type.Target)) - } - tree["variants"] = variants - raw, err := json.Marshal(tree, json.Deterministic(true)) - require.NoError(t, err) - return string(raw) -} - -// TestKindInference_AClosureBesideAUnionOfObjectsDistributes holds a closure -// written beside a union of objects with no type: the branches declare the -// object, so it is the schema writing `type: object` beside them, a union of -// closed models over each branch, keeping nothing, under either policy and in -// both branch orders, a `nullable: true` beside it included, which at 3.0 has -// no effect beside no type and draws the load's warning. -func TestKindInference_AClosureBesideAUnionOfObjectsDistributes(t *testing.T) { +// TestKindInference_AClosureRefusingWhatEveryBranchRequiresAdmitsNothing holds +// a closure written beside a union of objects each requiring a member the +// closure's own object does not declare: the closure refuses that member, so +// no branch lives, and the position is the closed model keeping the union, +// with one warning naming each branch's member, as with `type: object` beside +// them, under either kind policy and in both branch orders. A `nullable: true` +// beside it, of no effect at 3.0 beside no type and warned of, the +// nullable-inference policy reads as null for the whole conjunction, which the +// position then admits alone, the refused branches reported at the union. +func TestKindInference_AClosureRefusingWhatEveryBranchRequiresAdmitsNothing(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { for _, order := range [][]string{{"A", "B"}, {"B", "A"}} { @@ -88,25 +73,27 @@ func TestKindInference_AClosureBesideAUnionOfObjectsDistributes(t *testing.T) { for _, off := range []bool{false, true} { inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, diags := compileKindInference(t, "closure", admissionSpec(version, "", schemas...), off) + closed := []string{"Closed", "Typed"} + requirePolicyNullAlone(t, doc) var findings []wantFinding + for _, name := range closed { + findings = append(findings, wantFinding{code: diag.UnsatisfiableSchema, + pointer: "/components/schemas/" + name, contains: []string{"a", "b", "additionalProperties"}}) + } + // The refused branches alone are reported, at the union: the position admits the policy's null. + findings = append(findings, wantFinding{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/Nullable/oneOf", + contains: []string{"a", "b", "additionalProperties", "so no instance satisfies them"}}) if version == "3.0.3" { - findings = []wantFinding{{code: "openapi/validation/validation-no-effect", pointer: "/components/schemas/Nullable/nullable"}} + findings = append(findings, wantFinding{code: "openapi/validation/validation-no-effect", pointer: "/components/schemas/Nullable/nullable"}) } requireErrorsAndWarnings(t, diags, findings) - for _, name := range []string{"Closed", "Nullable", "Typed"} { - variants := distributedOver(t, doc, componentID(name)) - assert.ElementsMatch(t, []ir.TypeID{componentID("A"), componentID("B")}, - slices.Collect(maps.Keys(variants)), name) - for base, model := range variants { - assert.Equal(t, ir.AdditionalClosed, model.Additional, "%s over %s", name, base) - assert.Empty(t, model.Properties, "%s over %s", name, base) - assert.False(t, markedKindInference(model), "%s over %s: the branch declares the object", name, base) - } - assert.Empty(t, keptUnder(doc, jsontext.Pointer("/components/schemas/"+name)), name) + for _, name := range closed { + model, ok := kindNode(t, doc, componentID(name)).(*ir.Model) + require.True(t, ok, "%s is its closed body", name) + assert.Equal(t, ir.AdditionalClosed, model.Additional, name) + assert.Empty(t, model.Properties, name) + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonDegradedLowering}, keptOn(model), name) } - assert.Equal(t, unionAsWritten(t, doc, componentID("Typed")), - strings.ReplaceAll(unionAsWritten(t, doc, componentID("Closed")), "/Closed/", "/Typed/"), - "the closure lowers as the same schema writing type: object") }) } }) @@ -114,9 +101,22 @@ func TestKindInference_AClosureBesideAUnionOfObjectsDistributes(t *testing.T) { } } +// requirePolicyNullAlone holds Nullable, whose `nullable: true` the policy +// reads as null for the whole conjunction no branch of which lives, to that +// null alone: the closed Enum with no member keeping the union. +func requirePolicyNullAlone(t *testing.T, doc *ir.Document) { + t.Helper() + enum, ok := kindNode(t, doc, componentID("Nullable")).(*ir.Enum) + require.True(t, ok, "Nullable admits the policy's null alone") + assert.True(t, enum.Closed) + assert.Empty(t, enum.Members) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(enum)["openapi:oneOf"]) +} + // TestKindInference_ACatchAllBesideAUnionOfObjectsDistributes holds a catch-all // beside a union of objects with no type: a union of two models over its -// branches, each holding the catch-all's value type. +// branches, each holding the catch-all's value type, which also applies to +// the members the branches bring, so it is kept once, with one info. func TestKindInference_ACatchAllBesideAUnionOfObjectsDistributes(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -135,7 +135,10 @@ func TestKindInference_ACatchAllBesideAUnionOfObjectsDistributes(t *testing.T) { require.NotNil(t, model.AdditionalProperties.Value, base) assert.Equal(t, primitive(ir.PrimitiveString), model.AdditionalProperties.Value.Target, base) } - assert.Empty(t, keptUnder(doc, "/components/schemas/Open")) + assert.Equal(t, map[jsontext.Pointer]ir.UnmodeledReason{"/components/schemas/Open/additionalProperties": ir.ReasonDegradedLowering}, + keptUnder(doc, "/components/schemas/Open")) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/Open/additionalProperties"}, + degradedUnder(diags, "/components/schemas/Open"), "one info, at the keyword") }) } }) diff --git a/compilers/openapi/e2e/kind_inference_entry_test.go b/compilers/openapi/e2e/kind_inference_entry_test.go index 4a60e59fa..1170c342f 100644 --- a/compilers/openapi/e2e/kind_inference_entry_test.go +++ b/compilers/openapi/e2e/kind_inference_entry_test.go @@ -35,10 +35,10 @@ func withoutKindInference(t *testing.T, doc *ir.Document) string { return strings.ReplaceAll(comparableDocument(t, doc), `"inferred":"kind-inference",`, "") } -// TestKindInference_AnEntryClaimingThePositionsKindIsItsPrincipal holds that -// an allOf entry whose keywords claim every kind the position lowers to by the +// TestKindInference_AnEntryClaimingThePositionsKindIsItsPrincipal holds that an +// allOf entry whose keywords claim every kind the position lowers to by the // policy says what the position is, as one writing that type does: at every -// position `{allOf: [{K}]}` is the node its entry builds, standing at the +// position `{allOf: [{K}]}` is the node its entry builds, sitting at the // position, marked, keeping nothing and reporting nothing, and compiles to what // `{allOf: [{type: array, K}]}` compiles to but for the marker, as `{K}` does // beside `{type: array, K}`. With the policy off it is the top type keeping K. @@ -53,7 +53,7 @@ func TestKindInference_AnEntryClaimingThePositionsKindIsItsPrincipal(t *testing. requireErrorsAndWarnings(t, diags, nil) for _, at := range conjunctionPositions { used := usedAt(t, doc, at) - assert.Equal(t, entryPositionID(at), used, "the node standing at %s", at) + assert.Equal(t, entryPositionID(at), used, "the node at %s", at) node := kindNode(t, doc, used) assert.Equal(t, tc.kind, node.Kind(), at) assert.True(t, markedKindInference(node), "the entry's node is the policy's reading at %s", at) @@ -83,9 +83,9 @@ func TestKindInference_AnEntryClaimingThePositionsKindIsItsPrincipal(t *testing. } } -// entryClaimOrders are allOf entries the election picks among, each written in -// both orders: an entry claiming an array beside one bounding it, beside a -// $ref to a schema admitting every kind, and beside a copy of itself. +// entryClaimOrders are allOf entries the choice picks among, each written in +// both orders: an entry claiming an array beside one bounding it, beside a $ref +// to a schema admitting every kind, and beside a copy of itself. var entryClaimOrders = []struct { name string first string @@ -99,8 +99,8 @@ var entryClaimOrders = []struct { // TestKindInference_AnEntryClaimingTheKindIsPickedInEitherOrder holds that the // entry claiming the position's kind is its principal whichever order the // entries are written in: the two orders compile to one document but for the -// entries' indices, the position the list the claiming entry builds (the -// first copy of one written twice), standing at the position. +// entries' indices, the position the list the claiming entry builds (the first +// copy of one written twice), sitting at the position. func TestKindInference_AnEntryClaimingTheKindIsPickedInEitherOrder(t *testing.T) { t.Parallel() for _, tc := range entryClaimOrders { diff --git a/compilers/openapi/e2e/kind_inference_keywords_test.go b/compilers/openapi/e2e/kind_inference_keywords_test.go index 36568694c..ab0a585e8 100644 --- a/compilers/openapi/e2e/kind_inference_keywords_test.go +++ b/compilers/openapi/e2e/kind_inference_keywords_test.go @@ -110,8 +110,8 @@ func TestKindInference_AnInferredCollectionKeepsItsMemberTypes(t *testing.T) { } // TestKindInference_AnInlineCollectionIsMarkedAtItsPosition holds that the -// marker stands on the list or map an inline schema owns at a property, for -// the keywords other than `properties`. +// marker sits on the list or map an inline schema owns at a property, for the +// keywords other than `properties`. func TestKindInference_AnInlineCollectionIsMarkedAtItsPosition(t *testing.T) { t.Parallel() holder := "Holder: {type: object, properties: {it: {items: {type: string}}, " + @@ -286,27 +286,33 @@ func TestKindInference_AKindAConjunctNamesIsDeclared(t *testing.T) { t.Parallel() inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, _ := compileKindInference(t, "declared", admissionSpec("3.1.0", "", schemas...), off) - // The oneOf distributes across the body, the anyOf kept on each variant. + // The oneOf distributes across the body, the Union keeping the + // anyOf once, and the closure over the member Obj brings. closed, ok := kindNode(t, doc, componentID("Closed")).(*ir.Union) require.True(t, ok, "the branches declare an object") assert.False(t, markedKindInference(closed), "the document declared the kind") + assert.Equal(t, map[string]ir.UnmodeledReason{ + "openapi:anyOf": ir.ReasonDegradedLowering, "openapi:additionalProperties": ir.ReasonDegradedLowering, + }, keptOn(closed)) require.Len(t, closed.Variants, 1) variant := kindNode(t, doc, closed.Variants[0].Type.Target) assert.Equal(t, ir.KindModel, variant.Kind()) assert.False(t, markedKindInference(variant)) - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": ir.ReasonDegradedLowering}, keptOn(variant)) + assert.Empty(t, keptOn(variant), "a variant keeps nothing of its own") assertUntypedOutcome(t, doc, "Scalars", topKeeping("items", "oneOf")) }) }) } } -// TestKindInference_KeywordsNarrowingAKeptUnionNameNoKind holds a schema -// writing no type beside a union kept whole whose branches admit a kind its -// shape keywords do not speak of: the keywords would narrow what the document -// declares, so under either policy the node is the top type keeping them, and -// no instance the union admits is outside it. -func TestKindInference_KeywordsNarrowingAKeptUnionNameNoKind(t *testing.T) { +// TestKindInference_ObjectKeywordsBesideAnObjectAndAStringDistributeByKind +// holds a schema writing no type beside a union of an object and a string: a +// `required` and a closure distribute by kind under either policy, into the +// object branch's variant alone, the string branch being its own node; a +// branch the policy alone reads as an object distributes so with it on and is +// kept by the top type with it off; and `items` beside an array and a string, +// no object among them, is the top type keeping both. +func TestKindInference_ObjectKeywordsBesideAnObjectAndAStringDistributeByKind(t *testing.T) { t.Parallel() schemas := []string{ "Obj: {type: object, properties: {a: {type: string}}}", @@ -315,30 +321,49 @@ func TestKindInference_KeywordsNarrowingAKeptUnionNameNoKind(t *testing.T) { "Elements: {oneOf: [{type: array, items: {type: integer}}, {type: string}], items: {type: string}}", "ThroughABranch: {oneOf: [{properties: {u: {type: string}}}, {type: string}], required: [a]}", } - want := map[string]untypedOutcome{ - "Required": topKeeping("oneOf", "required"), - "Closed": topKeeping("anyOf", "additionalProperties"), - "Elements": topKeeping("oneOf", "items"), - "ThroughABranch": topKeeping("oneOf", "required"), - } for _, off := range []bool{false, true} { t.Run(fmt.Sprintf("off=%t", off), func(t *testing.T) { t.Parallel() inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, _ := compileKindInference(t, "narrowing", admissionSpec("3.1.0", "", schemas...), off) - for name, outcome := range want { - assertUntypedOutcome(t, doc, name, outcome) + requireObjectAndString(t, doc, "Required", false, nil) + requireObjectAndString(t, doc, "Closed", false, []string{"additionalProperties"}) + assertUntypedOutcome(t, doc, "Elements", topKeeping("oneOf", "items")) + if off { + assertUntypedOutcome(t, doc, "ThroughABranch", topKeeping("oneOf", "required")) + return } + requireObjectAndString(t, doc, "ThroughABranch", true, nil) }) }) } } -// TestKindInference_APropertySetBesideAUnionOfOtherKindsIsTheTopType holds a -// `properties` with no type beside a union naming an object and a string: the -// kinds the position lowers to are what the branches declare, not an object -// alone, so under either policy no model composes and the top type keeps both. -func TestKindInference_APropertySetBesideAUnionOfOtherKindsIsTheTopType(t *testing.T) { +// requireObjectAndString holds the component name to a Union of two variants, +// a Model over its object branch, marked where marked says, and the string +// primitive, the Union keeping kept degraded. +func requireObjectAndString(t *testing.T, doc *ir.Document, name string, marked bool, kept []string) { + t.Helper() + union, ok := kindNode(t, doc, componentID(name)).(*ir.Union) + require.True(t, ok, "%s distributes by kind", name) + require.Len(t, union.Variants, 2, name) + model, ok := kindNode(t, doc, union.Variants[0].Type.Target).(*ir.Model) + require.True(t, ok, "%s: the object branch's variant is a model", name) + assert.Equal(t, marked, markedKindInference(model), "%s: marked where the policy read the object", name) + assert.Equal(t, primitive(ir.PrimitiveString), union.Variants[1].Type.Target, "%s: the string branch is its own node", name) + want := map[string]ir.UnmodeledReason{} + for _, keyword := range kept { + want["openapi:"+keyword] = ir.ReasonDegradedLowering + } + assert.Equal(t, want, keptOn(union), name) +} + +// TestKindInference_APropertySetBesideAUnionOfOtherKindsDistributesByKind holds +// a `properties` with no type beside a union naming an object and a string: +// under either policy the body distributes by kind, the object branch's +// variant composing the member, the string branch's its own node, as no body +// keyword applies to a string. +func TestKindInference_APropertySetBesideAUnionOfOtherKindsDistributesByKind(t *testing.T) { t.Parallel() schemas := []string{ "Obj: {type: object, properties: {a: {type: string}}}", @@ -347,7 +372,15 @@ func TestKindInference_APropertySetBesideAUnionOfOtherKindsIsTheTopType(t *testi inBothOrders(t, schemas, func(t *testing.T, schemas []string) { for _, off := range []bool{false, true} { doc, _ := compileKindInference(t, "other-kinds", admissionSpec("3.1.0", "", schemas...), off) - assertUntypedOutcome(t, doc, "Item", topKeeping("oneOf", "properties")) + union, ok := kindNode(t, doc, componentID("Item")).(*ir.Union) + require.True(t, ok, "Item distributes by kind, policy off %t", off) + require.Len(t, union.Variants, 2) + model, ok := kindNode(t, doc, union.Variants[0].Type.Target).(*ir.Model) + require.True(t, ok, "the object branch's variant is a model") + assert.Equal(t, []string{"q"}, propertyNames(model), "it composes the member") + assert.Equal(t, componentID("Obj"), model.Base.Target, "over the branch's target") + assert.Equal(t, primitive(ir.PrimitiveString), union.Variants[1].Type.Target, "the string branch is its own node") + assert.Empty(t, keptOn(union), "nothing is kept") } }) } @@ -394,8 +427,9 @@ func TestKindInference_AKindReadThroughAnInferredBranchIsMarked(t *testing.T) { // variants a union distributes an untyped property set into: one composed over // a branch declaring an object is a model by that branch and unmarked, and one // over a branch that is an object only as the policy reads it is a model by the -// policy's reading of the property set and names it, as does one over a branch -// whose read a cycle cuts short, which the policy off composes nothing over. A +// policy's reading of the property set and names it. A branch declaring an +// object beside a cycle is that declared object, as a loop cuts no read, so +// its variant is unmarked. A // body writing `type: object` marks none, a variant over a branch that may be // a string among them. func TestKindInference_AVariantComposedOverAnInferredBodyIsMarked(t *testing.T) { @@ -407,7 +441,7 @@ func TestKindInference_AVariantComposedOverAnInferredBodyIsMarked(t *testing.T) "Cycle: {allOf: [{$ref: '#/components/schemas/Cycle'}]}", "CutShort: {properties: {x: {type: string}}, oneOf: [{type: object, allOf: [{$ref: '#/components/schemas/Cycle'}]}]}", } - want := map[string][]bool{"Untyped": {false, true}, "Typed": {false, false, false}, "CutShort": {true}} + want := map[string][]bool{"Untyped": {false, true}, "Typed": {false, false, false}, "CutShort": {false}} inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, _ := compileKindInference(t, "variants", admissionSpec("3.1.0", "", schemas...), false) for name, marked := range want { diff --git a/compilers/openapi/e2e/kind_inference_policy_test.go b/compilers/openapi/e2e/kind_inference_policy_test.go index e4bf06bd5..cb9a19c7c 100644 --- a/compilers/openapi/e2e/kind_inference_policy_test.go +++ b/compilers/openapi/e2e/kind_inference_policy_test.go @@ -131,7 +131,7 @@ func TestKindInference_ANullableWithNoTypeStillInfersTheKind(t *testing.T) { } // TestKindInference_AnInlineSchemaIsMarkedAtEachPositionOwningANode holds that -// the marker stands on the node an inline schema owns at a property, a list +// the marker sits on the node an inline schema owns at a property, a list // element, a union variant and a request body, as it does on a component. func TestKindInference_AnInlineSchemaIsMarkedAtEachPositionOwningANode(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/e2e/kind_inference_width_test.go b/compilers/openapi/e2e/kind_inference_width_test.go index c1fdb2d37..31f46a57b 100644 --- a/compilers/openapi/e2e/kind_inference_width_test.go +++ b/compilers/openapi/e2e/kind_inference_width_test.go @@ -134,9 +134,9 @@ func assertWidthOutcome(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, a // TestKindInference_AKeywordTypingNothingStillSpeaksOfItsKind holds that a // keyword inferring no kind still speaks of the one it applies to beside // conjuncts that declare kinds: a bare `required` beside a union of objects -// distributes across it, beside a union naming a string too it is the top -// type keeping both, and a union of two bare `required`s is a union of two top -// types, each keeping its own, under either policy. +// distributes across it, beside a union naming a string too it distributes +// by kind, into the object branch alone, and a union of two bare `required`s +// is a union of two top types, each keeping its own, under either policy. func TestKindInference_AKeywordTypingNothingStillSpeaksOfItsKind(t *testing.T) { t.Parallel() schemas := []string{ @@ -161,7 +161,13 @@ func TestKindInference_AKeywordTypingNothingStillSpeaksOfItsKind(t *testing.T) { assert.Equal(t, []string{"a"}, variant.Requires) assert.False(t, markedKindInference(variant), "the branches declare the object") } - assertUntypedOutcome(t, doc, "Mixed", topKeeping("oneOf", "required")) + mixed, ok := kindNode(t, doc, componentID("Mixed")).(*ir.Union) + require.True(t, ok, "a bare required distributes by kind") + require.Len(t, mixed.Variants, 2) + object, isModel := kindNode(t, doc, mixed.Variants[0].Type.Target).(*ir.Model) + require.True(t, isModel) + assert.Equal(t, []string{"a"}, object.Requires, "the object branch takes the required") + assert.Equal(t, primitive(ir.PrimitiveString), mixed.Variants[1].Type.Target, "the string branch is its own node") narrowings, ok := kindNode(t, doc, componentID("Narrowings")).(*ir.Union) require.True(t, ok) require.Len(t, narrowings.Variants, 2) diff --git a/compilers/openapi/e2e/literal_union_type_test.go b/compilers/openapi/e2e/literal_union_type_test.go new file mode 100644 index 000000000..39eb5b09d --- /dev/null +++ b/compilers/openapi/e2e/literal_union_type_test.go @@ -0,0 +1,48 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// TestLiteralUnion_ATypeAMemberLacksIsKept holds a type beside an enum +// lowering to a union of literals one member of which is no value of it: the +// type says what the union does not, so it is kept verbatim with its info. +func TestLiteralUnion_ATypeAMemberLacksIsKept(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", "Count: {type: integer, enum: [1, two]}")) + union, ok := kindNode(t, doc, componentID("Count")).(*ir.Union) + require.True(t, ok) + assert.Equal(t, degradedKept("openapi:type"), keptOn(union)) + assert.Contains(t, infoCodesAt(diags, "/components/schemas/Count"), diag.DegradedConstruct) +} + +// TestLiteralUnion_ANullableTypeAt30LowersAsItsTypeListAt31 holds a 3.0 type +// beside nullable: true and an enum lowering to a union of literals, a null +// among its members, to its 3.1 twin, the type list naming null: nullable +// admits the null member, so the type restates the union there too and is +// kept nowhere, the union and its nullable use alike in both. +func TestLiteralUnion_ANullableTypeAt30LowersAsItsTypeListAt31(t *testing.T) { + t.Parallel() + unions := map[string]*ir.Union{} + for version, schema := range map[string]string{ + "3.0.3": "{type: array, nullable: true, enum: [[1], null]}", + "3.1.0": "{type: [array, 'null'], enum: [[1], null]}", + } { + doc, _ := compileUnrefused(t, admissionSpec(version, "", "N: "+schema)) + union, ok := kindNode(t, doc, componentID("N")).(*ir.Union) + require.True(t, ok, version) + assert.Empty(t, keptOn(union), "%s keeps no type", version) + unions[version] = union + } + assert.Empty(t, cmp.Diff(unions["3.1.0"], unions["3.0.3"]), "the 3.0 union is its 3.1 twin's") +} diff --git a/compilers/openapi/e2e/load_test.go b/compilers/openapi/e2e/load_test.go index bbb4a160c..c4e10e979 100644 --- a/compilers/openapi/e2e/load_test.go +++ b/compilers/openapi/e2e/load_test.go @@ -138,7 +138,7 @@ func TestCompile_AResolutionFailureIsReportedOnceAtItsRef(t *testing.T) { // (GitHub #1044): one unresolved-ref error at the $ref whose own hop lands // there, naming the kind as a schema $ref to a position holding no schema is // worded, in whichever document writes it, and none at a reference whose chain -// passes that one. No finding stands beside it at the target, and it does not +// passes that one. No finding sits beside it at the target, and it does not // depend on which $ref reaches the target first. A target with findings of its // own still reports them. func TestCompile_AReferenceObjectToANonObjectIsReportedOnce(t *testing.T) { @@ -520,13 +520,13 @@ func TestCompile_AnUnusableDocumentIsReportedAlikeOnEitherRoute(t *testing.T) { } } -// TestCompile_AURLNoReaderReadsIsRefusedUnread pins that a $ref whose -// document part is a URL with a scheme other than http, https or file fails -// unread with the reason, in a schema and in a parameter, with external -// references allowed or not, and whatever the working directory: a reader -// would read "foo:b.yaml" as a path against it. A file whose name holds a -// colon, written "./foo:b.yaml", is read, the spec named relatively too, -// where the parser library's join would make it that same "foo:b.yaml" +// TestCompile_AURLNoReaderReadsIsRefusedUnread pins that a $ref whose document +// part is a URL with a scheme other than http, https or file fails unread with +// the reason, in a schema and in a parameter, with external references allowed +// or not, and whatever the working directory: a reader would read "foo:b.yaml" +// as a path against it. A file whose name holds a colon, written +// "./foo:b.yaml", is read, the spec named relatively too, where the parser +// library's path join would make it that same "foo:b.yaml" // (componentlookup.Locate keeps the "./"). Both routes word the refusal alike. func TestCompile_AURLNoReaderReadsIsRefusedUnread(t *testing.T) { dir, err := filepath.EvalSymlinks(t.TempDir()) diff --git a/compilers/openapi/e2e/lowering_spec_test.go b/compilers/openapi/e2e/lowering_spec_test.go index 7f231839a..bd78ffe02 100644 --- a/compilers/openapi/e2e/lowering_spec_test.go +++ b/compilers/openapi/e2e/lowering_spec_test.go @@ -326,13 +326,16 @@ func testProblems(rules []rule, funcsOf func(pkg string) (map[string]bool, error return problems } -// packageDir returns the directory, from the repository root, of the package -// a test name's prefix stands for: the compiler itself, this package, the -// harness's schema cases, or one under the compiler's internal directory. +// packageDir returns the directory, from the repository root, of the package a +// test name's prefix names: the compiler itself, this package, the harness's +// schema cases, the IR, whose readers a lowering asks, or one under the +// compiler's internal directory. func packageDir(pkg string) string { switch pkg { case "openapi": return "compilers/openapi" + case "ir": + return "ir" case "e2e": return "compilers/openapi/e2e" case "openapicases": diff --git a/compilers/openapi/e2e/mapping_lowered_test.go b/compilers/openapi/e2e/mapping_lowered_test.go index 539392441..262b04e28 100644 --- a/compilers/openapi/e2e/mapping_lowered_test.go +++ b/compilers/openapi/e2e/mapping_lowered_test.go @@ -111,9 +111,9 @@ func schemaKeywordCases(t *testing.T) []readCase { return cases } -// structureCases are the places a discriminator stands that a keyword alone -// does not decide: a component, a definition, what a $ref reaches or stands -// beside, an election's loser, and what the operation walk lowers. +// structureCases are the places a discriminator sits that a keyword alone does +// not decide: a component, a definition, what a $ref reaches or sits beside, a +// choice's passed-over declaration, and what the operation walk lowers. func structureCases() []readCase { response := "{description: x, content: {application/json: {schema: " + namesT + "}}}" return []readCase{ @@ -186,8 +186,8 @@ func structureCases() []readCase { // TestMappingTargets_TheLoadPhaseResolvesEveryEntryItReaches holds the load // phase's resolution of mapping targets to what the lowering reads: wherever a -// discriminator stands that the model or a $ref's chain reaches, the finding in -// a target is reported, as a $ref's is. The lowering reads some of those +// discriminator sits that the model or a $ref's chain reaches, the finding in a +// target is reported, as a $ref's is. The lowering reads some of those // positions and not others, as each row's answer shows, and what it reads is // never left to what it lowered first (GitHub #757). The keyword rows come from // the parser's model, so a keyword it comes to read reddens a row. @@ -352,7 +352,8 @@ func TestMappingTargets_ARawPositionACopyReachesResolvesInEitherOrder(t *testing // discriminator inside a path item or a callback that a reference reaches: its // mapping is bound at the discriminator's own position under the object the // reference names, where the lowering looks it up, so the entry names T and -// nothing reports it unresolved. A position read with an empty segment before +// nothing reports it unresolved. T is no subtype, so the discriminator is kept +// whole, its entry's target T. A position read with an empty segment before // the method or the expression matched no lookup (GitHub #886). func TestMappingTargets_ADiscriminatorAReferenceReachesIsBoundWhereItSits(t *testing.T) { t.Parallel() @@ -369,8 +370,15 @@ func TestMappingTargets_ADiscriminatorAReferenceReachesIsBoundWhereItSits(t *tes require.NotNil(t, doc, readCaseValue.name) var mapped []ir.TypeID for _, def := range doc.Types { - if model, ok := def.(*ir.Model); ok && model.Discriminator != nil { - mapped = append(mapped, model.Discriminator.Mapping["x"]) + model, ok := def.(*ir.Model) + if !ok { + continue + } + // T is no subtype and the position has no name of its own, so no + // route stays typed: the discriminator is kept whole, its route to + // T among its targets. + if kept, whole := model.Unmodeled["openapi:discriminator"]; whole { + mapped = append(mapped, kept.Targets["/mapping/x"]) } } assert.Equal(t, []ir.TypeID{"type/anonymous/x-lib/T"}, mapped, readCaseValue.name) diff --git a/compilers/openapi/e2e/model_bounds_intersection_test.go b/compilers/openapi/e2e/model_bounds_intersection_test.go new file mode 100644 index 000000000..4eb9147dd --- /dev/null +++ b/compilers/openapi/e2e/model_bounds_intersection_test.go @@ -0,0 +1,75 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/pass" +) + +// modelBoundsSchemas is GitHub #2043's reproduction with a mixin beside it: +// Obj requires two members, B composes it under at most five and Empty under +// at most one, Both composes it beside a model capping one, and Flat is B +// written flat. +var modelBoundsSchemas = []string{ + "Obj: {type: object, properties: {a: {type: string}}, minProperties: 2}", + "Cap: {type: object, properties: {c: {type: string}}, maxProperties: 1}", + "Flat: {type: object, properties: {a: {type: string}, b: {type: string}}, minProperties: 2}", + "B: {allOf: [{$ref: '#/components/schemas/Obj'}, {type: object, properties: {b: {type: string}}, maxProperties: 5}]}", + "Empty: {allOf: [{$ref: '#/components/schemas/Obj'}, {type: object, properties: {c: {type: string}}, maxProperties: 1}]}", + "Both: {allOf: [{$ref: '#/components/schemas/Obj'}, {$ref: '#/components/schemas/Cap'}]}", + "Direct: {type: object, properties: {a: {type: string}}, minProperties: 3, maxProperties: 1}", + "Holder: {type: object, properties: {" + + "own: {$ref: '#/components/schemas/Obj', default: {a: x}}, " + + "viaBase: {$ref: '#/components/schemas/B', default: {b: x}}, " + + "viaBaseWithin: {$ref: '#/components/schemas/B', default: {a: x, b: y}}, " + + "flat: {$ref: '#/components/schemas/Flat', default: {a: x}}}}", +} + +// TestModelBounds_ValidateIntersectsTheBoundsOfWhatAModelComposes holds +// pass.Validate to an instance meeting the bounds of every model it composes +// along Base and Mixins: a composition whose joined bounds cross admits no +// object, as a model writing them crossed does, and a default under the +// composed minimum lies outside the bounds, as under its flat twin's, in either +// order of the components. +func TestModelBounds_ValidateIntersectsTheBoundsOfWhatAModelComposes(t *testing.T) { + t.Parallel() + const at = "/components/schemas/" + inBothOrders(t, modelBoundsSchemas, func(t *testing.T, schemas []string) { + doc, _ := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + found, err := pass.Validate(t.Context(), doc) + require.NoError(t, err) + requireErrorsAndWarnings(t, found, []wantFinding{ + {code: "pass/bounds-admit-no-value", pointer: at + "Direct", contains: []string{"at least 3 members and at most 1"}}, + {code: "pass/bounds-admit-no-value", pointer: at + "Empty", contains: []string{"at least 2 members and at most 1"}}, + {code: "pass/bounds-admit-no-value", pointer: at + "Both", contains: []string{"at least 2 members and at most 1"}}, + {code: "pass/default-outside-type", pointer: at + "Holder/properties/own", contains: []string{"outside the bounds"}}, + {code: "pass/default-outside-type", pointer: at + "Holder/properties/viaBase", contains: []string{"outside the bounds"}}, + {code: "pass/default-outside-type", pointer: at + "Holder/properties/flat", contains: []string{"outside the bounds"}}, + }) + }) +} + +// TestModelBounds_EachModelStatesItsOwn holds the compiler to writing each +// model's own bounds: a reader intersects them, so a model composing another +// holds only those its own schema writes, and the one it composes keeps its +// own. +func TestModelBounds_EachModelStatesItsOwn(t *testing.T) { + t.Parallel() + doc, _ := compileUnrefused(t, admissionSpec("3.1.0", "", modelBoundsSchemas...)) + for name, want := range map[string]*ir.Constraints{ + "Obj": {MinProperties: new(int64(2))}, + "Cap": {MaxProperties: new(int64(1))}, + "B": {MaxProperties: new(int64(5))}, + "Empty": {MaxProperties: new(int64(1))}, + "Both": nil, + } { + assert.Equal(t, want, requireModelOf(t, doc, name).Constraints, name) + } +} diff --git a/compilers/openapi/e2e/model_only_object_rows_test.go b/compilers/openapi/e2e/model_only_object_rows_test.go new file mode 100644 index 000000000..3388c5389 --- /dev/null +++ b/compilers/openapi/e2e/model_only_object_rows_test.go @@ -0,0 +1,159 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// TestModelOnlyObject_TheBottomKeepsEachKeywordUnderItsOwnKey holds the +// closed Model with no member that kinds sharing none lower to: each keyword +// the position writes is kept under its plain key and each entry under its +// entry key, reported as admitting no instance. +func TestModelOnlyObject_TheBottomKeepsEachKeywordUnderItsOwnKey(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, admissionSpec("3.1.0", "", + "B3: {type: object, properties: {b: {type: string}}, allOf: [{type: string, maxLength: 2}]}")) + bottom := requireModelOf(t, doc, "B3") + assert.Empty(t, bottom.Properties, "no member") + assert.Equal(t, ir.AdditionalClosed, bottom.Additional) + for _, key := range []string{"openapi:type", "openapi:properties", "openapi:allOf/0"} { + assert.Contains(t, bottom.Unmodeled, key) + } + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/B3")) +} + +// TestModelOnlyObject_ACutReadOfAnArrayIsAList holds an allOf of more array +// entries than the choice compares, each saying more than its kind: the kinds, +// read whole, are an array alone, so the position is a List keeping each +// conjunct verbatim, with one report at the position. +func TestModelOnlyObject_ACutReadOfAnArrayIsAList(t *testing.T) { + t.Parallel() + entries := strings.TrimSuffix(strings.Repeat("{type: array, minItems: 1}, ", 65), ", ") + doc, diags := parseFull(t, admissionSpec("3.1.0", "", "L: {allOf: ["+entries+"]}")) + list, ok := typeByName(doc, "L").(*ir.List) + require.True(t, ok, "got %T", typeByName(doc, "L")) + assert.Len(t, list.Unmodeled, 65, "each conjunct is kept") + for key, entry := range list.Unmodeled { + assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason, key) + } + assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, diag.DegradedConstruct, "/components/schemas/L")) +} + +// petHierarchy is a discriminator hierarchy whose members compose its union: +// a cycle through oneOf. +const petHierarchy = `openapi: 3.1.0 +info: {title: t, version: "1"} +paths: {} +components: + schemas: + Pet: + oneOf: [{$ref: '#/components/schemas/Cat'}, {$ref: '#/components/schemas/Dog'}] + discriminator: {propertyName: kind} + Cat: {allOf: [{$ref: '#/components/schemas/Pet'}, {properties: {kind: {type: string}, purrs: {type: boolean}}}]} + Dog: {allOf: [{$ref: '#/components/schemas/Pet'}, {properties: {kind: {type: string}, barks: {type: boolean}}}]} +` + +// TestModelOnlyObject_ACycleThroughAUnionComposesAsThePolicyReads holds the +// members of a discriminator hierarchy, each an allOf of the union and of +// properties naming no type: their kinds are those the kind-inference policy +// reads off the properties, an object, so under the default policy each +// composes a Model, and with the policy off, which reads no kind, neither is. +func TestModelOnlyObject_ACycleThroughAUnionComposesAsThePolicyReads(t *testing.T) { + t.Parallel() + on, _ := compileKindInference(t, "pets", petHierarchy, false) + off, _ := compileKindInference(t, "pets", petHierarchy, true) + for _, name := range []string{"Cat", "Dog"} { + _, composed := typeByName(on, name).(*ir.Model) + assert.True(t, composed, "%s composes under the default policy: got %T", name, typeByName(on, name)) + _, composedOff := typeByName(off, name).(*ir.Model) + assert.False(t, composedOff, "%s is no Model with the policy off", name) + } +} + +// TestModelOnlyObject_AnUnreadableConstInATargetReadsAsTheTopType holds a $ref +// to a schema whose const no reading converts: the const is no conjunct of +// the reading, so the reference reads as the top type's kinds and the other +// conjunct decides, a string a use of the string and an object a Model. +func TestModelOnlyObject_AnUnreadableConstInATargetReadsAsTheTopType(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, admissionSpec("3.1.0", "", + "T: {const: .nan}", + "S: {allOf: [{$ref: '#/components/schemas/T'}, {type: string, maxLength: 3}]}", + "O: {allOf: [{$ref: '#/components/schemas/T'}, {type: object, properties: {a: {type: string}}}]}", + )) + requireComponentScalar(t, doc, "S", ir.PrimitiveTypeID(ir.PrimitiveString)) + _, composed := typeByName(doc, "O").(*ir.Model) + assert.True(t, composed, "the object decides: got %T", typeByName(doc, "O")) +} + +// TestModelOnlyObject_AReferenceNamingNothingBesideAnIDKeepsTheID holds a +// $ref, a $dynamicRef and a $recursiveRef that lead nowhere, each beside an +// $id and a bound: each lowers as its twin without the reference does, the +// $id kept alike, the reference kept beside it. +func TestModelOnlyObject_AReferenceNamingNothingBesideAnIDKeepsTheID(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, "openapi: 3.1.0\njsonSchemaDialect: 'https://json-schema.org/draft/2019-09/schema'\n"+ + strings.TrimPrefix(admissionSpec("3.1.0", "", + "Twin: {$id: 'https://x.example/twin', minLength: 2}", + "Ref: {$id: 'https://x.example/ref', $ref: '#/components/schemas/Ghost', minLength: 2}", + "Dynamic: {$id: 'https://x.example/dynamic', $dynamicRef: '#nothing', minLength: 2}", + "Recursive: {$id: 'https://x.example/recursive', $recursiveRef: '#', minLength: 2}", + ), "openapi: 3.1.0\n")) + twin := requireComponentScalar(t, doc, "Twin", ir.PrimitiveTypeID(ir.PrimitiveAny)) + want := unmodeledEntry(t, twin.Common().Unmodeled, "openapi:$id") + for _, name := range []string{"Ref", "Dynamic", "Recursive"} { + got := requireComponentScalar(t, doc, name, ir.PrimitiveTypeID(ir.PrimitiveAny)) + assert.Equal(t, twin.Constraints, got.Constraints, name) + id := unmodeledEntry(t, got.Unmodeled, "openapi:$id") + assert.Equal(t, want.Reason, id.Reason, name) + assert.JSONEq(t, `"https://x.example/`+strings.ToLower(name)+`"`, string(id.Value), name) + assert.Len(t, got.Unmodeled, 2, "%s keeps the $id and its reference: %v", name, got.Unmodeled) + } +} + +// TestModelOnlyObject_ValueSetsSharingNoMemberAdmitNothing holds two value sets +// the read shows share no member, in either order of the entries and with one +// beside the allOf: of one value type, the closed empty Enum of that type; of +// two, the closed Model with no member. Each is reported as admitting no +// instance. +func TestModelOnlyObject_ValueSetsSharingNoMemberAdmitNothing(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + a, b string + enum bool + }{{"[a]", "[b]", true}, {"[a]", "[1]", false}} { + for _, spelling := range []string{ + "{allOf: [{enum: " + tc.a + "}, {enum: " + tc.b + "}]}", + "{allOf: [{enum: " + tc.b + "}, {enum: " + tc.a + "}]}", + "{enum: " + tc.a + ", allOf: [{enum: " + tc.b + "}]}", + "{enum: " + tc.b + ", allOf: [{enum: " + tc.a + "}]}", + } { + doc, diags := parseFull(t, admissionSpec("3.1.0", "", "V: "+spelling)) + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, + diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/V"), spelling) + if tc.enum { + enum, ok := typeByName(doc, "V").(*ir.Enum) + if assert.True(t, ok, "%s: got %T", spelling, typeByName(doc, "V")) { + assert.Empty(t, enum.Members, spelling) + assert.True(t, enum.Closed, spelling) + assert.Equal(t, ir.PrimitiveString, enum.ValueType, spelling) + } + continue + } + model, ok := typeByName(doc, "V").(*ir.Model) + if assert.True(t, ok, "%s: got %T", spelling, typeByName(doc, "V")) { + assert.Empty(t, model.Properties, spelling) + assert.Equal(t, ir.AdditionalClosed, model.Additional, spelling) + } + } + } +} diff --git a/compilers/openapi/e2e/model_only_object_test.go b/compilers/openapi/e2e/model_only_object_test.go new file mode 100644 index 000000000..6990bc535 --- /dev/null +++ b/compilers/openapi/e2e/model_only_object_test.go @@ -0,0 +1,423 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "encoding/json/v2" + "fmt" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// stringEntries is an allOf's entries: n schemas `{type: string}`, then extra. +func stringEntries(n int, extra ...string) string { + entries := slices.Repeat([]string{"{type: string}"}, n) + return "[" + strings.Join(append(entries, extra...), ", ") + "]" +} + +// bigEnum is a component Big, a string whose enum lists n members. +func bigEnum(n int) string { + members := make([]string, 0, n) + for i := range n { + members = append(members, fmt.Sprintf("v%d", i)) + } + return "Big: {type: string, enum: [" + strings.Join(members, ", ") + "]}" +} + +// requireComponentScalar requires the component name's own node to be a +// Scalar whose base is target, and returns it. +func requireComponentScalar(t *testing.T, doc *ir.Document, name string, target ir.TypeID) *ir.Scalar { + t.Helper() + scalar, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s is a scalar: got %T", name, typeByName(doc, name)) + require.NotNil(t, scalar.Base, name) + assert.Equal(t, target, scalar.Base.Target, name) + return scalar +} + +// TestModelOnlyObject_PastTheConjunctBoundTheConjunctsDecide holds an allOf of +// more string entries than the choice compares: an entry writing nothing past +// its kind says nothing, so 65 such entries are the string 64 are, with no +// report, and one more bound among them is held by that string. +func TestModelOnlyObject_PastTheConjunctBoundTheConjunctsDecide(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", + "Within: {allOf: "+stringEntries(64)+"}", + "Past: {allOf: "+stringEntries(65)+"}", + "Bounded: {allOf: "+stringEntries(64, "{type: string, maxLength: 3}")+"}", + )) + stringType := ir.PrimitiveTypeID(ir.PrimitiveString) + requireComponentScalar(t, doc, "Within", stringType) + requireComponentScalar(t, doc, "Past", stringType) + assert.Empty(t, diagsUnder(diags, "/components/schemas/Past"), "no report") + bounded := requireComponentScalar(t, doc, "Bounded", stringType) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(3))}, bounded.Constraints) +} + +// TestModelOnlyObject_PastTheFlatteningDepthIsTheTopTypeKeepingTheAllOf holds +// a string nested in allOfs past the flattening depth, whose kinds the read +// cannot reach: the position is the top type keeping its allOf whole beside +// the bound's own report, never a Model, while one level less is the string. +func TestModelOnlyObject_PastTheFlatteningDepthIsTheTopTypeKeepingTheAllOf(t *testing.T) { + t.Parallel() + nested := func(depth int) string { + body := "{type: string}" + for range depth { + body = "{allOf: [" + body + "]}" + } + return body + } + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", "Within: "+nested(33), "Past: "+nested(34))) + requireComponentScalar(t, doc, "Within", ir.PrimitiveTypeID(ir.PrimitiveString)) + past := requireComponentScalar(t, doc, "Past", ir.PrimitiveTypeID(ir.PrimitiveAny)) + assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, past.Unmodeled, "openapi:allOf").Reason) + assert.NotEmpty(t, diagsUnder(diags, "/components/schemas/Past/allOf/0/"), "the bound's own report remains") +} + +// TestModelOnlyObject_AnUnreadableConstIsNoConjunct holds a const no reading +// converts, kept and reported as before: it is no conjunct of the reading, so +// an allOf of it alone is the top type, not a Model. +func TestModelOnlyObject_AnUnreadableConstIsNoConjunct(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, admissionSpec("3.1.0", "", "S: {allOf: [{const: .nan}]}")) + requireComponentScalar(t, doc, "S", ir.PrimitiveTypeID(ir.PrimitiveAny)) +} + +// TestModelOnlyObject_PastTheMemberBoundWhatIsLeftDecides holds a $ref whose +// target's members pass the read's bound: beside an entry saying nothing past +// its kind it is the reference alone, and beside a format a restriction of it +// carrying the format's Encoding, never a Model. The members stay the target's: +// the document holds one Enum, and nothing is kept. +func TestModelOnlyObject_PastTheMemberBoundWhatIsLeftDecides(t *testing.T) { + t.Parallel() + const members = 4097 + doc, _ := parseVerified(t, admissionSpec("3.1.0", "", bigEnum(members), + "S: {allOf: [{$ref: '#/components/schemas/Big'}, {type: string}]}", + "F: {allOf: [{$ref: '#/components/schemas/Big'}, {format: email}]}", + )) + requireComponentScalar(t, doc, "S", componentID("Big")) + f := requireComponentScalar(t, doc, "F", componentID("Big")) + assert.Equal(t, &ir.Encoding{Name: "email"}, f.Encoding, "F carries the format's Encoding") + assert.Empty(t, f.Unmodeled, "F keeps nothing") + var enums []ir.TypeID + for id, td := range doc.Types { + if enum, ok := td.(*ir.Enum); ok { + enums = append(enums, id) + assert.Len(t, enum.Members, members, "%s holds every member", id) + } + } + assert.Equal(t, []ir.TypeID{componentID("Big")}, enums, "no member is copied") +} + +// TestModelOnlyObject_AChainOfRefsBesideNotesIsAliases holds a chain of 299 +// links, each a $ref to the next beside a description, ending in a null: a +// position whose one conjunct is a $ref, with notes beside it, is the +// reference, so each link is an alias of the next however far from the end, +// and none is a Model. +func TestModelOnlyObject_AChainOfRefsBesideNotesIsAliases(t *testing.T) { + t.Parallel() + const links = 299 + schemas := make([]string, 0, links+1) + for i := range links { + schemas = append(schemas, fmt.Sprintf("C%d: {$ref: '#/components/schemas/C%d', description: d}", i, i+1)) + } + schemas = append(schemas, fmt.Sprintf("C%d: {type: 'null'}", links)) + doc, _ := parseFull(t, admissionSpec("3.1.0", "", schemas...)) + for i := range links { + link, ok := typeByName(doc, fmt.Sprintf("C%d", i)).(*ir.Scalar) + if assert.True(t, ok, "C%d is an alias: got %T", i, typeByName(doc, fmt.Sprintf("C%d", i))) && + assert.NotNil(t, link.Base, "C%d", i) { + assert.Equal(t, componentID(fmt.Sprintf("C%d", i+1)), link.Base.Target, "C%d", i) + } + } +} + +// TestModelOnlyObject_ALoopBesideAStringIsTheString holds a self-reference +// beside a string's bound: a loop admits every kind, so the kinds are the +// other conjunct's, and the position is the string holding the bound, the +// self-reference kept verbatim with one report at its entry. +func TestModelOnlyObject_ALoopBesideAStringIsTheString(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, admissionSpec("3.1.0", "", + "CY: {allOf: [{$ref: '#/components/schemas/CY'}, {type: string, maxLength: 3}]}")) + loop := requireComponentScalar(t, doc, "CY", ir.PrimitiveTypeID(ir.PrimitiveString)) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(3))}, loop.Constraints) + assert.Equal(t, ir.ReasonDegradedLowering, unmodeledEntry(t, loop.Unmodeled, "openapi:$ref").Reason) + assert.Equal(t, []ir.Severity{ir.SeverityInfo}, + diagsAt(diags, diag.DegradedConstruct, "/components/schemas/CY/allOf/0")) +} + +// ghostTwins are schemas writing a $ref naming nothing, each with the same +// schema without it. +var ghostTwins = []struct{ name, with, without string }{ + {"G1", "{$ref: '#/components/schemas/Ghost', minLength: 2}", "{minLength: 2}"}, + {"G2", "{allOf: [{$ref: '#/components/schemas/Ghost'}], minLength: 2}", "{minLength: 2}"}, + {"G3", "{$ref: '#/components/schemas/Ghost', description: d}", "{description: d}"}, + {"G4", "{$ref: '#/components/schemas/Ghost', type: string, minLength: 2}", "{type: string, minLength: 2}"}, + {"GC", "{allOf: [{$ref: '#/components/schemas/Ghost'}, {const: a}]}", "{const: a}"}, + {"H", "{type: object, properties: {p: {$ref: '#/components/schemas/Ghost', minLength: 2}}}", + "{type: object, properties: {p: {minLength: 2}}}"}, +} + +// TestModelOnlyObject_ARefNamingNothingLowersAsItsSchemaWithoutIt holds a $ref +// landing on no schema, which admits every kind and cuts nothing: the position +// lowers as the same schema without the $ref, which it keeps verbatim beside +// the one unresolved-reference error, at 3.1 and at 3.0, where the warning that +// 3.0 ignores the keywords beside a $ref also applies. +func TestModelOnlyObject_ARefNamingNothingLowersAsItsSchemaWithoutIt(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.1.0", "3.0.3"} { + for _, tc := range ghostTwins { + t.Run(version+"/"+tc.name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, admissionSpec(version, "", "S: "+tc.with)) + twin, _ := parseFull(t, admissionSpec(version, "", "S: "+tc.without)) + got, want := typeByName(doc, "S"), typeByName(twin, "S") + require.NotNil(t, got) + require.NotNil(t, want) + assert.Equal(t, want.Kind(), got.Kind()) + unmodeled := ir.Unmodeled{} + for key, entry := range got.Common().Unmodeled { + if strings.HasPrefix(key, "openapi:$ref") || key == "openapi:allOf/0" { + assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason, key) + continue + } + unmodeled[key] = entry + } + if wantKept := want.Common().Unmodeled; len(wantKept) == 0 { + assert.Empty(t, unmodeled, "nothing but the $ref is kept") + } else { + assert.Equal(t, wantKept, unmodeled, "nothing but the $ref is kept") + } + scalar, isScalar := got.(*ir.Scalar) + if wantScalar, wantsScalar := want.(*ir.Scalar); isScalar && wantsScalar { + assert.Equal(t, wantScalar.Base, scalar.Base) + assert.Equal(t, wantScalar.Constraints, scalar.Constraints) + } + model, isModel := got.(*ir.Model) + if wantModel, wantsModel := want.(*ir.Model); isModel && wantsModel { + gotP, _ := propertyByWire(model, "p") + wantP, _ := propertyByWire(wantModel, "p") + assert.Equal(t, wantP.Type, gotP.Type, "the property's type") + assert.Equal(t, wantP.Constraints, gotP.Constraints, "the property's bound") + } + var others []string + for _, d := range diags { + if d.Code != diag.UnresolvedRef && d.Code != diag.LaterVersionConstruct { + others = append(others, d.Code+" "+string(d.Provenance.Pointer)) + } + } + assert.Empty(t, others, "no other report") + assert.Len(t, byCode(diags, diag.UnresolvedRef), 1) + }) + } + } +} + +// TestModelOnlyObject_AValueSetIsChosenBeforeACutRead holds a value set beside +// a $ref naming nothing, and an empty one beside a $ref naming a schema: each +// is chosen by its keyword before any read, in every spelling, so the entry +// spelling lowers as the value set does beside the allOf, the Enum keeping the +// $ref, and an empty one is the closed empty Enum with its warning, drawn where +// the enum is written. +func TestModelOnlyObject_AValueSetIsChosenBeforeACutRead(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, admissionSpec("3.1.0", "", + "O: {type: object, properties: {a: {type: string}}}", + "Str: {type: string}", + "Beside: {$ref: '#/components/schemas/Missing', enum: [a]}", + "Wrap: {allOf: [{$ref: '#/components/schemas/Missing'}], enum: [a]}", + "Entry: {allOf: [{$ref: '#/components/schemas/Missing'}, {enum: [a]}]}", + "EntryObj: {allOf: [{$ref: '#/components/schemas/O'}, {enum: []}]}", + "WrapObj: {allOf: [{$ref: '#/components/schemas/O'}], enum: []}", + "EntryStr: {allOf: [{$ref: '#/components/schemas/Str'}, {enum: []}]}", + "WrapStr: {allOf: [{$ref: '#/components/schemas/Str'}], enum: []}", + )) + for _, name := range []string{"Beside", "Wrap", "Entry"} { + enum, ok := typeByName(doc, name).(*ir.Enum) + if assert.True(t, ok, "%s is the value set: got %T", name, typeByName(doc, name)) { + assert.Len(t, enum.Members, 1, name) + assert.Contains(t, enum.Unmodeled, "openapi:$ref", name) + } + } + for name, written := range map[string]string{"EntryObj": "/allOf/1", "WrapObj": "", "EntryStr": "/allOf/1", "WrapStr": ""} { + enum, ok := typeByName(doc, name).(*ir.Enum) + if assert.True(t, ok, "%s is the empty value set: got %T", name, typeByName(doc, name)) { + assert.Empty(t, enum.Members, name) + assert.True(t, enum.Closed, name) + } + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, + diagsAt(diags, diag.EmptyEnum, "/components/schemas/"+name+written), "%s: where the enum is written", name) + } +} + +// TestModelOnlyObject_AValueSetPastTheMemberBoundIsTheSameInEveryOrder holds +// an inline value set beside a $ref whose members pass the read's bound: in +// either order of the entries and beside the allOf it is the Enum of the +// inline set keeping the $ref, with no report that the conjuncts share +// nothing. Within the bound, where the read shows they share nothing, each +// spelling is the closed empty Enum, reported as admitting no instance. +func TestModelOnlyObject_AValueSetPastTheMemberBoundIsTheSameInEveryOrder(t *testing.T) { + t.Parallel() + const big, small = "{$ref: '#/components/schemas/Big'}", "{enum: [zz]}" + spellings := []string{ + "T: {allOf: [" + big + ", " + small + "]}", + "T: {allOf: [" + small + ", " + big + "]}", + "T: {allOf: [" + big + "], enum: [zz]}", + } + for _, members := range []int{4095, 4096} { + for _, spelling := range spellings { + t.Run(fmt.Sprintf("%d/%s", members, spelling), func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, admissionSpec("3.1.0", "", bigEnum(members), spelling)) + enum, ok := typeByName(doc, "T").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "T")) + assert.Contains(t, enum.Unmodeled, "openapi:$ref") + unsatisfiable := diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/T") + if members == 4096 { + assert.Len(t, enum.Members, 1, "the inline set past the bound") + assert.Empty(t, unsatisfiable, "no report past the bound") + return + } + assert.Empty(t, enum.Members, "the read shows the sets share nothing") + assert.True(t, enum.Closed) + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, unsatisfiable) + }) + } + } +} + +// TestModelOnlyObject_KindsSharingNoneAreTheBottom holds conjuncts whose kinds, +// or whose value sets' value types, share none: the closed Model with no +// member keeping each conjunct verbatim, reported as admitting no instance. +// Value sets of one value type sharing no member are the closed empty Enum of +// that type, beside or on entries alike. +func TestModelOnlyObject_KindsSharingNoneAreTheBottom(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, admissionSpec("3.1.0", "", + "Str: {type: string}", + "Int: {type: integer}", + "Kinds: {allOf: [{type: string}, {type: integer}]}", + "KindRefs: {allOf: [{$ref: '#/components/schemas/Str'}, {$ref: '#/components/schemas/Int'}]}", + "Types: {allOf: [{enum: [a]}, {enum: [1]}]}", + "EnumEntries: {allOf: [{enum: [a, b]}, {enum: [c, d]}]}", + "EnumBeside: {enum: [a, b], allOf: [{enum: [c, d]}]}", + )) + for _, name := range []string{"Kinds", "KindRefs", "Types"} { + model, ok := typeByName(doc, name).(*ir.Model) + if assert.True(t, ok, "%s is the bottom: got %T", name, typeByName(doc, name)) { + assert.Empty(t, model.Properties, name) + assert.Equal(t, ir.AdditionalClosed, model.Additional, name) + assert.Len(t, model.Unmodeled, 2, "%s keeps each conjunct: %v", name, model.Unmodeled) + } + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name), name) + } + for _, name := range []string{"EnumEntries", "EnumBeside"} { + enum, ok := typeByName(doc, name).(*ir.Enum) + if assert.True(t, ok, "%s is the empty value set: got %T", name, typeByName(doc, name)) { + assert.Empty(t, enum.Members, name) + assert.True(t, enum.Closed, name) + assert.Equal(t, ir.PrimitiveString, enum.ValueType, name) + } + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name), name) + } +} + +// TestModelOnlyObject_ACycleWritingObjectKeywordsComposesAsThePolicyReads holds +// a member of a cycle of allOfs writing object keywords and no type: its kinds +// are those the kind-inference policy reads, so it composes as one outside a +// cycle does, marked as the policy marks it. +func TestModelOnlyObject_ACycleWritingObjectKeywordsComposesAsThePolicyReads(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, admissionSpec("3.1.0", "", + "N: {properties: {x: {type: string}}, allOf: [{$ref: '#/components/schemas/N2'}]}", + "N2: {allOf: [{$ref: '#/components/schemas/N'}]}", + "M: {properties: {x: {type: string}}, allOf: [{$ref: '#/components/schemas/M2'}]}", + "M2: {properties: {y: {type: string}}}", + )) + for _, name := range []string{"N", "M"} { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s composes: got %T", name, typeByName(doc, name)) + assert.True(t, markedKindInference(model), "%s names the kind-inference policy", name) + } +} + +// withoutRefs is doc as its types' JSON encodes it, each kept $ref taken out +// of every node's and member's Unmodeled entries, alone or inside an entry's +// object, then diags but the unresolved references' and the later-version +// warnings of keywords beside one, by severity, code and pointer, sorted; and +// how many references it took out. +func withoutRefs(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) (string, int) { + t.Helper() + refs := 0 + strip := func(kept ir.Unmodeled) { + for key, entry := range kept { + if strings.HasPrefix(key, "openapi:$ref") { + refs++ + delete(kept, key) + continue + } + var members map[string]jsontext.Value + if json.Unmarshal(entry.Value, &members) != nil || members["$ref"] == nil { + continue + } + refs++ + delete(members, "$ref") + raw, err := json.Marshal(members, json.Deterministic(true)) + require.NoError(t, err) + entry.Value = raw + kept[key] = entry + } + } + for _, td := range doc.Types { + strip(td.Common().Unmodeled) + if model, isModel := td.(*ir.Model); isModel { + for _, property := range model.Properties { + strip(property.Unmodeled) + } + } + } + raw, err := json.Marshal(doc.Types, json.Deterministic(true)) + require.NoError(t, err) + var findings []string + for _, d := range diags { + if d.Code != diag.UnresolvedRef && d.Code != diag.LaterVersionConstruct { + findings = append(findings, string(d.Severity)+" "+d.Code+" "+string(d.Provenance.Pointer)) + } + } + slices.Sort(findings) + return string(raw) + "\n" + strings.Join(findings, "\n"), refs +} + +// requireLowersWithoutRefs requires the document of version writing schemas +// to lower as the same document with each of refs, a $ref and the separator +// after it as written, taken out, keeping the references it took out, n of +// them, and drawing an unresolved-reference error; it returns the document +// as compiled, its references kept. +func requireLowersWithoutRefs(t *testing.T, version string, schemas, refs []string, n int) *ir.Document { + t.Helper() + twinSchemas := slices.Clone(schemas) + for i := range twinSchemas { + for _, ref := range refs { + twinSchemas[i] = strings.ReplaceAll(twinSchemas[i], ref, "") + } + } + stripped, diags := parseFull(t, admissionSpec(version, "", schemas...)) + twin, twinDiags := parseFull(t, admissionSpec(version, "", twinSchemas...)) + assert.NotEmpty(t, byCode(diags, diag.UnresolvedRef), "each $ref naming nothing draws its error") + got, kept := withoutRefs(t, stripped, diags) + want, _ := withoutRefs(t, twin, twinDiags) + assert.Equal(t, want, got, "lowers as %v", twinSchemas) + assert.Equal(t, n, kept, "each reference kept once") + doc, _ := parseFull(t, admissionSpec(version, "", schemas...)) + return doc +} diff --git a/compilers/openapi/e2e/non_scalar_key_test.go b/compilers/openapi/e2e/non_scalar_key_test.go index 6a6390387..052ed3f3f 100644 --- a/compilers/openapi/e2e/non_scalar_key_test.go +++ b/compilers/openapi/e2e/non_scalar_key_test.go @@ -86,7 +86,7 @@ func TestCompile_AKeyWrittenAsTheEmptyStringStillDrawsEachRule(t *testing.T) { // TestCompile_TwoKeysThatAreNoScalarAreEachReportedInEitherOrder holds two such // keys of one mapping to one answer in both declaration orders: neither is read -// as a key "", so no entry stands for which order would decide, each is +// as a key "", so no entry exists for which order would decide, each is // reported at its own line, and nothing is said of a key written twice. func TestCompile_TwoKeysThatAreNoScalarAreEachReportedInEitherOrder(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/e2e/null_answer_chain_test.go b/compilers/openapi/e2e/null_answer_chain_test.go new file mode 100644 index 000000000..8f201d28e --- /dev/null +++ b/compilers/openapi/e2e/null_answer_chain_test.go @@ -0,0 +1,129 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "slices" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// answerChainSpec writes schemaCount component schemas C0 to C(schemaCount-1), +// each but the last written by hop over the name of the next and the last as +// last, beside Holder, whose property p names C0, declared in that order or +// reversed. +func answerChainSpec(schemaCount int, hop func(next string) string, last string, reversed bool) string { + declarations := make([]string, 0, schemaCount+1) + for i := range schemaCount - 1 { + declarations = append(declarations, fmt.Sprintf(" C%d: %s\n", i, hop(fmt.Sprintf("C%d", i+1)))) + } + declarations = append(declarations, fmt.Sprintf(" C%d: %s\n", schemaCount-1, last), + " Holder: {type: object, properties: {p: "+capRef("C0")+"}}\n") + if reversed { + slices.Reverse(declarations) + } + return openapitest.ComponentSpec(strings.Join(declarations, "")) +} + +// answerAllOfHop is a hop naming the next through an allOf entry, and +// answerNestedHop one naming it through an allOf entry nested in another +// (#2121's two forms). +func answerAllOfHop(next string) string { return "{allOf: [" + capRef(next) + "]}" } + +func answerNestedHop(next string) string { return "{allOf: [{allOf: [" + capRef(next) + "]}]}" } + +// answerChainNulls returns, for each schema of a chain but the last, whether +// the reference its Scalar takes to the next is nullable, and whether Holder's +// property naming C0 is. +func answerChainNulls(t *testing.T, doc *ir.Document, schemaCount int) ([]bool, bool) { + t.Helper() + out := make([]bool, 0, schemaCount-1) + for i := range schemaCount - 1 { + scalar, ok := doc.Types[componentID(fmt.Sprintf("C%d", i))].(*ir.Scalar) + require.True(t, ok, "C%d lowers to an alias of the next schema", i) + require.NotNil(t, scalar.Base, "C%d", i) + require.Equal(t, componentID(fmt.Sprintf("C%d", i+1)), scalar.Base.Target, "C%d", i) + out = append(out, scalar.Base.Nullable) + } + return out, holderProperties(t, doc)["p"].Type.Nullable +} + +// everyAnswerHop is schemaCount-1 answers of true. +func everyAnswerHop(schemaCount int) []bool { + out := make([]bool, schemaCount-1) + for i := range out { + out[i] = true + } + return out +} + +// TestNullAnswer_AChainOfAllOfReferencesToNullAdmitsItAtEveryLink pins GitHub +// #2121: a chain of schemas each naming the next through an allOf, the last +// admitting null alone, admits null at every alias, at a length past any walk's +// budget and in either declaration order, with no finding. The answer of each +// schema is read once per run in dependency order, so the order the components +// lower in decides nothing. +func TestNullAnswer_AChainOfAllOfReferencesToNullAdmitsItAtEveryLink(t *testing.T) { + t.Parallel() + for _, form := range []struct { + name string + hop func(next string) string + }{{"allOf", answerAllOfHop}, {"nested allOf", answerNestedHop}} { + for _, schemaCount := range []int{130, 300} { + t.Run(fmt.Sprintf("%s of %d", form.name, schemaCount), func(t *testing.T) { + t.Parallel() + forward, forwardDiags := parseVerified(t, answerChainSpec(schemaCount, form.hop, "{type: 'null'}", false)) + reversed, reversedDiags := parseVerified(t, answerChainSpec(schemaCount, form.hop, "{type: 'null'}", true)) + assert.Empty(t, forwardDiags, "a chain to null is no defect") + assert.Empty(t, reversedDiags, "a chain to null is no defect") + for name, doc := range map[string]*ir.Document{"declared first to last": forward, "declared last to first": reversed} { + bases, holder := answerChainNulls(t, doc, schemaCount) + assert.Equal(t, everyAnswerHop(schemaCount), bases, "%s: every schema admits the null its next does", name) + assert.True(t, holder, "%s: the reference naming the chain admits null", name) + } + assert.Empty(t, cmp.Diff(forward.Types, reversed.Types), "the declaration order decides nothing") + }) + } + } +} + +// TestNullAnswer_ACycleKeepsTheNullItAdmits pins a cycle's answer, settled as +// one component whichever of its schemas the walk enters: an allOf naming a +// union one of whose branches names the allOf back and another is null admits +// null at both, as JSON Schema reads it, written as two schemas or as a cycle +// of 300 (GitHub #2121), in either declaration order; a cycle saying nothing of +// null admits none. +func TestNullAnswer_ACycleKeepsTheNullItAdmits(t *testing.T) { + t.Parallel() + const closing = "{anyOf: [" + "{$ref: '#/components/schemas/C0'}" + ", {type: 'null'}]}" + for _, schemaCount := range []int{2, 300} { + t.Run(fmt.Sprintf("through a union holder, %d schemas", schemaCount), func(t *testing.T) { + t.Parallel() + forward, forwardDiags := parseVerified(t, answerChainSpec(schemaCount, answerAllOfHop, closing, false)) + reversed, reversedDiags := parseVerified(t, answerChainSpec(schemaCount, answerAllOfHop, closing, true)) + assert.Equal(t, lines(forwardDiags), lines(reversedDiags)) + for name, doc := range map[string]*ir.Document{"declared first to last": forward, "declared last to first": reversed} { + bases, holder := answerChainNulls(t, doc, schemaCount) + assert.Equal(t, everyAnswerHop(schemaCount), bases, "%s: every allOf of the cycle admits the union's null", name) + assert.True(t, holder, "%s", name) + } + assert.Empty(t, cmp.Diff(forward.Types, reversed.Types), "the declaration order decides nothing") + }) + } + t.Run("saying nothing of null", func(t *testing.T) { + t.Parallel() + for _, reversed := range []bool{false, true} { + doc, _ := parseVerified(t, answerChainSpec(3, answerAllOfHop, answerAllOfHop("C0"), reversed)) + assert.False(t, holderProperties(t, doc)["p"].Type.Nullable, "reversed %t: no schema of the cycle admits null", reversed) + } + }) +} diff --git a/compilers/openapi/e2e/null_answer_collapse_test.go b/compilers/openapi/e2e/null_answer_collapse_test.go new file mode 100644 index 000000000..eb12afa8f --- /dev/null +++ b/compilers/openapi/e2e/null_answer_collapse_test.go @@ -0,0 +1,89 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestNullAnswer_ACollapsedUnionsNullIsInferredWhereThePolicyAloneReadsIt holds +// the null of a union collapsing to the nullable reference to its one non-null +// branch to the position's answer in every spelling, on the component's Base +// and on a $ref to it: declared where that branch declares null, though another +// branch is null only by the nullable-inference policy, and inferred where only +// the policy reads it in, as beside an enum keeping null out, with the one info +// at the nullable the policy reads +// (docs/compilers/openapi.md#union-null-variant). +func TestNullAnswer_ACollapsedUnionsNullIsInferredWhereThePolicyAloneReadsIt(t *testing.T) { + t.Parallel() + for _, row := range []struct { + name, version, body, union string + want refNull + }{ + {"a branch declaring null", "3.1.0", "", + "anyOf: [{type: object, enum: [null], nullable: true}, {type: [string, 'null']}]", refNull{Nullable: true}}, + {"a set keeping null out", "3.0.3", "type: string, enum: [a], nullable: true", + "anyOf: [{type: object, enum: [null], nullable: true}, {format: uuid}]", inferredNull}, + } { + t.Run(row.name, func(t *testing.T) { + t.Parallel() + spellings := openapitest.Spellings(row.body, row.union) + names := slices.Sorted(maps.Keys(spellings)) + var schemas, properties strings.Builder + for _, name := range names { + schemas.WriteString(" " + name + ": " + spellings[name] + "\n") + properties.WriteString(" p" + name + ": {$ref: '#/components/schemas/" + name + "'}\n") + } + doc, diags := compileNullableVerified(t, openapitest.ComponentSpecVer(row.version, + schemas.String()+" Holder:\n type: object\n properties:\n"+properties.String()), false) + holder, ok := doc.Types[componentID("Holder")].(*ir.Model) + require.True(t, ok) + references := openapitest.PropertiesByWire(holder.Properties) + for _, name := range names { + assert.Equal(t, row.want, nullOf(references["p"+name].Type), "%s: a $ref to it", name) + scalar, isScalar := doc.Types[componentID(name)].(*ir.Scalar) + require.True(t, isScalar, "%s is the Scalar over its one non-null branch", name) + assert.Equal(t, row.want, nullOf(*scalar.Base), "%s: its Base", name) + assert.Equal(t, 1, countBeneath(diags, diag.InferredNullable, ir.SeverityInfo, "/components/schemas/"+name), + "%s: the nullable the policy reads is reported once", name) + } + }) + } +} + +// TestNullAnswer_AUnionOfSeveralVariantsKeepsAVariantsNullOffItsReference +// holds that a variant's declared null stays on the variant: the reference to +// a union of two variants, one admitting null, admits none under either +// policy, and the reference to one lifting a branch only the +// nullable-inference policy reads admits that null inferred, the variant's +// declared null not reaching it (docs/compilers/openapi.md#union-null-variant). +func TestNullAnswer_AUnionOfSeveralVariantsKeepsAVariantsNullOffItsReference(t *testing.T) { + t.Parallel() + src := openapitest.ComponentSpecVer("3.1.0", ` Two: {oneOf: [{type: [string, 'null']}, {type: integer}]} + Lifting: {oneOf: [{type: [string, 'null']}, {type: integer}, {type: object, enum: [null], nullable: true}]} + Holder: {type: object, properties: {two: {$ref: '#/components/schemas/Two'}, lifting: {$ref: '#/components/schemas/Lifting'}}} +`) + for _, off := range []bool{false, true} { + doc, _ := compileNullableVerified(t, src, off) + holder, ok := doc.Types[componentID("Holder")].(*ir.Model) + require.True(t, ok) + references := openapitest.PropertiesByWire(holder.Properties) + assert.Equal(t, refNull{}, nullOf(references["two"].Type), "policy off %t: the variant holds its null", off) + lifting := inferredNull + if off { + lifting = refNull{} + } + assert.Equal(t, lifting, nullOf(references["lifting"].Type), "policy off %t: the lifted null is the policy's", off) + } +} diff --git a/compilers/openapi/e2e/null_answer_enum_test.go b/compilers/openapi/e2e/null_answer_enum_test.go new file mode 100644 index 000000000..906844126 --- /dev/null +++ b/compilers/openapi/e2e/null_answer_enum_test.go @@ -0,0 +1,57 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// repeatedNullSpec writes a null repeated in an enum: alone, beside a member, +// in a union of literals, at a property, on an allOf entry, at 3.0's +// nullable, and beside a type excluding null; and a repeated member as a +// control. +const repeatedNullSpec = ` E: {enum: [null, null]} + F: {enum: [a, null, null]} + Literals: {enum: [a, 1, null, null]} + Entry: {allOf: [{enum: [b, null, null]}]} + Excl: {type: string, enum: [a, null, null]} + Same: {enum: [a, a]} + Holder: {type: object, properties: {r: {enum: [null, null]}}} +` + +// TestNullAnswer_ARepeatedNullIsReportedAsWhatHoldsIt pins GitHub #1903: a +// null repeated in an enum is reported as the reference admitting null once, +// not as an occurrence kept, at every position and at 3.0; where a keyword +// excludes null only the drop is reported; a repeated member is still kept. +func TestNullAnswer_ARepeatedNullIsReportedAsWhatHoldsIt(t *testing.T) { + t.Parallel() + _, diags := parseVerified(t, openapitest.ComponentSpec(repeatedNullSpec)) + _, diags30 := parseVerified(t, openapitest.ComponentSpecVer("3.0.3", + " N: {type: string, nullable: true, enum: [a, null, null]}\n")) + for _, tc := range []struct { + findings []ir.Diagnostic + pointer string + }{ + {diags, "/components/schemas/E/enum/1"}, {diags, "/components/schemas/F/enum/2"}, + {diags, "/components/schemas/Literals/enum/3"}, {diags, "/components/schemas/Entry/allOf/0/enum/2"}, + {diags, "/components/schemas/Holder/properties/r/enum/1"}, {diags30, "/components/schemas/N/enum/2"}, + } { + message := openapitest.DiagMessageAt(t, tc.findings, diag.DuplicateEnumValue, ir.SeverityWarning, tc.pointer) + assert.Contains(t, message, "admits null once", tc.pointer) + assert.NotContains(t, message, "kept", tc.pointer) + } + assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DuplicateEnumValue, "/components/schemas/Excl/enum/2"), + "a null the type excludes is reported dropped alone") + for _, pointer := range []string{"/components/schemas/Excl/enum/1", "/components/schemas/Excl/enum/2"} { + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, pointer), "%s is dropped", pointer) + } + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DuplicateEnumValue, ir.SeverityWarning, + "/components/schemas/Same/enum/1"), "every occurrence is kept", "a repeated member is kept") +} diff --git a/compilers/openapi/e2e/null_answer_idiom_test.go b/compilers/openapi/e2e/null_answer_idiom_test.go new file mode 100644 index 000000000..a64def300 --- /dev/null +++ b/compilers/openapi/e2e/null_answer_idiom_test.go @@ -0,0 +1,85 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// idiomSchemas are the targets and the positions writing a value keyword of +// null beside one reference: a conjunct keeping null out beside it, a target +// already admitting null, and a dynamic reference to a target admitting none. +const idiomSchemas = ` T: {type: integer} + TN: {type: [integer, 'null']} + NM: {$dynamicAnchor: nm, type: integer} + KeptOut: {$ref: '#/components/schemas/T', const: null, allOf: [{type: integer}]} + KeptOutAllOf: {allOf: [{$ref: '#/components/schemas/T'}, {type: integer}], const: null} + NarrowsConst: {$ref: '#/components/schemas/TN', const: null} + NarrowsEnum: {$ref: '#/components/schemas/TN', enum: [null]} + NarrowsType: {$ref: '#/components/schemas/TN', type: 'null'} + DynamicType: {$dynamicRef: '#nm', type: 'null'} + DynamicConst: {$dynamicRef: '#nm', const: null} + Holder: + type: object + properties: + p: {type: string} +` + +// TestNullAnswer_TheIdiomIsTheAnswersWidening pins the idiom to the reading the +// null answer widens by, under either policy: a conjunct keeping null out +// beside the one reference leaves a value keyword of null conjoined, the closed +// empty Enum reporting the conjuncts sharing no value; beside a target +// admitting null the keyword narrows it to the null type, keeping the +// reference; and a dynamic reference reads the keyword as a $ref does, with the +// policy the nullable reference, without it not expanded. +func TestNullAnswer_TheIdiomIsTheAnswersWidening(t *testing.T) { + t.Parallel() + for _, off := range []bool{false, true} { + doc, diags := compileNullableVerified(t, openapitest.ComponentSpecVer("3.1.0", idiomSchemas), off) + for _, name := range []string{"KeptOut", "KeptOutAllOf"} { + requireClosedEmptyEnum(t, doc, name, "openapi:$ref") + assert.NotEmpty(t, byCode(diagsBeneath(diags, "/components/schemas/"+name), diag.UnsatisfiableSchema), "policy off %t: %s", off, name) + } + for _, name := range []string{"NarrowsConst", "NarrowsEnum", "NarrowsType"} { + requireClosedEmptyEnum(t, doc, name, "openapi:$ref") + assert.Empty(t, byCode(diagsBeneath(diags, "/components/schemas/"+name), diag.UnsatisfiableSchema), "policy off %t: %s", off, name) + } + for _, name := range []string{"DynamicType", "DynamicConst"} { + if off { + requireClosedEmptyEnum(t, doc, name, "openapi:$dynamicRef") + continue + } + alias, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s is the nullable reference to NM; got %T", name, typeByName(doc, name)) + assert.Equal(t, inferred(componentID("NM")), *alias.Base, name) + assert.Empty(t, alias.Unmodeled, "%s: the reference says the null", name) + } + } +} + +// requireClosedEmptyEnum holds the component name of doc to the closed Enum +// with no member, keeping kept. +func requireClosedEmptyEnum(t *testing.T, doc *ir.Document, name, kept string) { + t.Helper() + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s is the closed empty Enum; got %T", name, typeByName(doc, name)) + assert.True(t, enum.Closed, name) + assert.Empty(t, enum.Members, name) + assert.Contains(t, keptOn(enum), kept, name) +} + +// diagsBeneath returns those of diags at pointer or beneath it. +func diagsBeneath(diags []ir.Diagnostic, pointer string) []ir.Diagnostic { + return slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return !underPointer(string(diagnostic.Provenance.Pointer), pointer) + }) +} diff --git a/compilers/openapi/e2e/null_answer_reads_test.go b/compilers/openapi/e2e/null_answer_reads_test.go new file mode 100644 index 000000000..1655ef846 --- /dev/null +++ b/compilers/openapi/e2e/null_answer_reads_test.go @@ -0,0 +1,170 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// dynamicNullSpec names Name, an anchored schema admitting null, by an +// expanding $dynamicRef and by a $ref, at a property, a parameter and a union +// member. +const dynamicNullSpec = `openapi: 3.1.0 +info: {title: t, version: "1"} +paths: + /p: + get: + parameters: + - {name: viaDynamic, in: query, schema: {$dynamicRef: '#nm'}} + - {name: viaRef, in: query, schema: {$ref: '#nm'}} + responses: {'200': {description: ok}} +components: + schemas: + Name: {$dynamicAnchor: nm, type: [string, 'null'], maxLength: 5} + O: {type: object, properties: {o: {type: string}}} + UnionDynamic: {oneOf: [{$ref: '#/components/schemas/O'}, {$dynamicRef: '#nm'}]} + UnionRef: {oneOf: [{$ref: '#/components/schemas/O'}, {$ref: '#nm'}]} + Holder: + type: object + properties: + viaDynamic: {$dynamicRef: '#nm'} + viaRef: {$ref: '#nm'} +` + +// TestNullAnswer_AnExpandedDynamicRefReadsItsTargetsNull pins GitHub #1967: +// a $dynamicRef expanding to the one anchor of its document reads the null +// its target admits as a $ref to it does, at a property, a parameter and a +// union member, and so does a $recursiveRef expanding to its resource's root. +func TestNullAnswer_AnExpandedDynamicRefReadsItsTargetsNull(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, dynamicNullSpec) + openapitest.RequireNoErrorDiags(t, diags) + name := componentID("Name") + nullable := ir.TypeRef{Target: name, Nullable: true} + + properties := holderProperties(t, doc) + assert.Equal(t, nullable, properties["viaRef"].Type) + assert.Equal(t, properties["viaRef"].Type, properties["viaDynamic"].Type, "at a property") + + operation := openapitest.FirstOperation(t, doc.Services[0]) + viaRef, ok := openapitest.ParamBySource(operation, "viaRef") + require.True(t, ok) + viaDynamic, ok := openapitest.ParamBySource(operation, "viaDynamic") + require.True(t, ok) + assert.Equal(t, nullable, viaRef.Type) + assert.Equal(t, viaRef.Type, viaDynamic.Type, "at a parameter") + + unionRef, ok := doc.Types[componentID("UnionRef")].(*ir.Union) + require.True(t, ok) + unionDynamic, ok := doc.Types[componentID("UnionDynamic")].(*ir.Union) + require.True(t, ok) + require.Len(t, unionRef.Variants, 2) + require.Len(t, unionDynamic.Variants, 2) + assert.Equal(t, nullable, unionRef.Variants[1].Type) + assert.Equal(t, unionRef.Variants[1].Type, unionDynamic.Variants[1].Type, "at a union member") + + recursive, recursiveDiags := parseVerified(t, "openapi: 3.1.0\ninfo: {title: t, version: '1'}\n"+ + "jsonSchemaDialect: 'https://json-schema.org/draft/2019-09/schema'\npaths: {}\ncomponents:\n schemas:\n"+ + " Holder: {$id: 'https://example.com/n', $recursiveAnchor: true, type: [object, 'null'], "+ + "properties: {viaRecursive: {$recursiveRef: '#'}, viaRef: {$ref: '#'}}}\n") + openapitest.RequireNoErrorDiags(t, recursiveDiags) + recursiveProperties := holderProperties(t, recursive) + assert.Equal(t, ir.TypeRef{Target: componentID("Holder"), Nullable: true}, recursiveProperties["viaRef"].Type) + assert.Equal(t, recursiveProperties["viaRef"].Type, recursiveProperties["viaRecursive"].Type, "a $recursiveRef alike") +} + +// dialectUnionExt is ext.yaml at version: a union of X and a branch whose +// null rests on `nullable`, which 3.0 adds to the branch's type and 3.1 does +// not define, and V, naming the union from within the document. +func dialectUnionExt(version string) string { + return "openapi: " + version + "\ninfo: {title: e, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + + " X: {type: object, properties: {a: {type: string}}}\n" + + " U: {oneOf: [{$ref: '#/components/schemas/X'}, {type: object, enum: [null], nullable: true}]}\n" + + " V: {type: object, properties: {u: {$ref: '#/components/schemas/U'}}}\n" +} + +// dialectUnionRoot is a root at version whose Holder names ext.yaml's U and +// V, in that order or the other. +func dialectUnionRoot(version string, reversed bool) string { + sites := []string{" p: {$ref: 'ext.yaml#/components/schemas/U'}\n", " v: {$ref: 'ext.yaml#/components/schemas/V'}\n"} + if reversed { + sites[0], sites[1] = sites[1], sites[0] + } + return "openapi: " + version + "\ninfo: {title: r, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + + " Holder:\n type: object\n properties:\n" + strings.Join(sites, "") +} + +// dialectUnionNulls compiles root beside ext and returns what the root's +// reference to U, and V's within ext.yaml, say of null. +func dialectUnionNulls(t *testing.T, root, ext string, off bool) [2]refNull { + t.Helper() + doc, diags := compileMinors(t, root, ext, openapi.NullableInference{Disabled: off}) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := doc.Types["type/openapi@ext.yaml/components/schemas/V"].(*ir.Model) + require.True(t, ok, "V lowers to a model") + return [2]refNull{nullOf(holderProperties(t, doc)["p"].Type), nullOf(openapitest.PropertiesByWire(model.Properties)["u"].Type)} +} + +// TestNullAnswer_EachSchemasNullableIsReadInItsOwnDocumentsDialect pins that a +// schema's answer reads its `nullable` by the dialect of the document holding +// it, never the asking one's, in either order of the sites naming it: a 3.0 +// root naming a 3.1 union reads it as 3.1 does, its null resting on the policy, +// and a 3.1 root naming a 3.0 union reads it as 3.0 does, its null declared. +func TestNullAnswer_EachSchemasNullableIsReadInItsOwnDocumentsDialect(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name, root, ext string + on, off refNull + }{ + {"a 3.0 root naming a 3.1 schema", "3.0.3", "3.1.0", inferredNull, refNull{}}, + {"a 3.1 root naming a 3.0 schema", "3.1.0", "3.0.3", refNull{Nullable: true}, refNull{Nullable: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + for _, reversed := range []bool{false, true} { + root := dialectUnionRoot(tc.root, reversed) + assert.Equal(t, [2]refNull{tc.on, tc.on}, dialectUnionNulls(t, root, dialectUnionExt(tc.ext), false), + "reversed %t, policy on", reversed) + assert.Equal(t, [2]refNull{tc.off, tc.off}, dialectUnionNulls(t, root, dialectUnionExt(tc.ext), true), + "reversed %t, policy off", reversed) + } + }) + } +} + +// TestNullAnswer_AUsesBitDecides pins GitHub #2090's decision, which changes +// no output: a use of an alias whose Base admits null states its position's +// null alone, so a use excluding the null is the alias at false, in each +// spelling, and the alias's Base keeps what its own schema admits. +func TestNullAnswer_AUsesBitDecides(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.1.0", "3.0.3"} { + an := "{type: [string, 'null']}" + if version == "3.0.3" { + an = "{type: string, nullable: true}" + } + doc, diags := parseVerified(t, openapitest.ComponentSpecVer(version, " AN: "+an+"\n ZS: {type: string}\n"+ + " Holder:\n type: object\n properties:\n"+ + " an: {$ref: '#/components/schemas/AN'}\n"+ + " refinl: {allOf: [{$ref: '#/components/schemas/AN'}, {type: string}]}\n"+ + " both: {allOf: [{$ref: '#/components/schemas/AN'}, {$ref: '#/components/schemas/ZS'}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + alias, ok := doc.Types[componentID("AN")].(*ir.Scalar) + require.True(t, ok, version) + require.NotNil(t, alias.Base, version) + assert.True(t, alias.Base.Nullable, "%s: the alias's Base is what its own schema admits", version) + properties := holderProperties(t, doc) + assert.Equal(t, ir.TypeRef{Target: componentID("AN"), Nullable: true}, properties["an"].Type, version) + assert.Equal(t, ir.TypeRef{Target: componentID("AN")}, properties["refinl"].Type, version) + assert.Equal(t, ir.TypeRef{Target: componentID("AN")}, properties["both"].Type, version) + } +} diff --git a/compilers/openapi/e2e/null_answer_scalar_base_test.go b/compilers/openapi/e2e/null_answer_scalar_base_test.go new file mode 100644 index 000000000..ad6ab44fc --- /dev/null +++ b/compilers/openapi/e2e/null_answer_scalar_base_test.go @@ -0,0 +1,92 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestNullAnswer_AScalarsBaseIsWhatItsSchemaAdmitsInEverySpelling pins that +// the Base of the Scalar a component builds admits null where the component's +// schema does: an alias over the node its body lowered to, whatever it keeps +// (a union beside a scalar body, flat or apart across allOf entries, a keyword +// the body does not read), and a restriction its format names, each row's +// spellings alike. +func TestNullAnswer_AScalarsBaseIsWhatItsSchemaAdmitsInEverySpelling(t *testing.T) { + t.Parallel() + const branches = "[{type: string, maxLength: 5}, {type: boolean}]" + for _, tc := range []struct { + name, version string + spellings []string + want refNull + }{ + {"a oneOf a nullable sits beside", "3.0.3", []string{ + "{type: string, nullable: true, oneOf: " + branches + "}", + "{oneOf: " + branches + ", allOf: [{type: string, nullable: true}]}", + "{type: string, nullable: true, allOf: [{oneOf: " + branches + "}]}", + }, inferredNull}, + {"an anyOf a nullable sits beside", "3.0.3", []string{ + "{type: string, nullable: true, anyOf: " + branches + "}", + "{anyOf: " + branches + ", allOf: [{type: string, nullable: true}]}", + "{type: string, nullable: true, allOf: [{anyOf: " + branches + "}]}", + }, inferredNull}, + {"a union admitting null", "3.1.0", []string{ + "{type: [string, 'null'], oneOf: [{type: string, maxLength: 5}, {type: boolean}, {type: 'null'}]}", + "{allOf: [{type: [string, 'null']}], oneOf: [{type: string, maxLength: 5}, {type: boolean}, {type: 'null'}]}", + }, refNull{Nullable: true}}, + {"a keyword the body does not read", "3.0.3", []string{ + "{type: string, nullable: true}", + "{type: string, nullable: true, minItems: 1}", + "{type: string, nullable: true, items: {type: string}}", + "{allOf: [{type: string, nullable: true}], minItems: 1}", + }, refNull{Nullable: true}}, + {"an entry taking the place of an allOf excluding null", "3.1.0", []string{ + "{type: [string, 'null'], minItems: 1, allOf: [{type: string}]}", + "{allOf: [{type: [string, 'null'], minItems: 1}, {type: string}]}", + "{type: [string, 'null'], oneOf: [{maxLength: 3}, {type: boolean}], allOf: [{type: string}]}", + "{allOf: [{type: [string, 'null'], oneOf: [{maxLength: 3}, {type: boolean}]}, {type: string}]}", + }, refNull{}}, + {"a restriction its format names", "3.0.3", []string{ + "{type: string, format: byte, nullable: true}", + "{allOf: [{type: string, format: byte, nullable: true}], description: d}", + "{type: string, nullable: true, allOf: [{format: byte}]}", + "{format: byte, allOf: [{type: string, nullable: true}]}", + "{type: string, format: unknown, nullable: true}", + "{allOf: [{type: string, format: unknown, nullable: true}], description: d}", + }, refNull{Nullable: true}}, + {"a restriction a type list admits null beside", "3.1.0", []string{ + "{type: [string, 'null'], format: byte}", + "{allOf: [{type: [string, 'null'], format: byte}], description: d}", + }, refNull{Nullable: true}}, + {"a restriction a nullable sits beside a union with", "3.0.3", []string{ + "{type: string, format: byte, nullable: true, oneOf: " + branches + "}", + "{oneOf: " + branches + ", allOf: [{type: string, format: byte, nullable: true}]}", + "{type: string, format: byte, nullable: true, allOf: [{oneOf: " + branches + "}]}", + }, inferredNull}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + var schemas strings.Builder + for i, spelling := range tc.spellings { + schemas.WriteString(" S" + strconv.Itoa(i) + ": " + spelling + "\n") + } + doc, diags := parseVerified(t, openapitest.ComponentSpecVer(tc.version, schemas.String())) + openapitest.RequireNoErrorDiags(t, diags) + for i, spelling := range tc.spellings { + alias, ok := doc.Types[componentID("S"+strconv.Itoa(i))].(*ir.Scalar) + require.True(t, ok, spelling) + require.NotNil(t, alias.Base, spelling) + assert.Equal(t, tc.want, nullOf(*alias.Base), "%s: the Scalar's Base is what its own schema admits", spelling) + } + }) + } +} diff --git a/compilers/openapi/e2e/null_answer_union_test.go b/compilers/openapi/e2e/null_answer_union_test.go new file mode 100644 index 000000000..74adb1884 --- /dev/null +++ b/compilers/openapi/e2e/null_answer_union_test.go @@ -0,0 +1,234 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// refNull is what a reference says of null: its bit and the heuristic its +// null rests on, apart from the node it names. +type refNull struct { + Nullable bool + Inferred ir.Inferred +} + +// nullOf is typeRef's refNull. +func nullOf(typeRef ir.TypeRef) refNull { + return refNull{Nullable: typeRef.Nullable, Inferred: typeRef.Inferred} +} + +// inferredNull is a reference whose null only the nullable-inference policy +// admits. +var inferredNull = refNull{Nullable: true, Inferred: openapi.NullableInferenceHeuristic} + +// compileNullableVerified is compileNullable, holding the document and its +// findings to irverify's invariants. +func compileNullableVerified(t *testing.T, src string, off bool) (*ir.Document, []ir.Diagnostic) { + t.Helper() + doc, diags := compileNullable(t, src, off) + requireVerifies(t, doc, diags) + return doc, diags +} + +// oneUnionSpec is GitHub #2120's document, with the sites beside it: a type +// list admitting null beside one union none of whose branches does, flat, +// beside an allOf of the list and on an entry (whose node the conjunction +// decision builds; only the reference's null is held here), an anyOf, a pair, +// an allOf and an enum keeping it out, a union of two branches, a $ref +// branch, and a control whose branch admits null. +const oneUnionSpec = `openapi: 3.1.0 +info: {title: t, version: "1"} +paths: {} +components: + schemas: + S: {type: string} + Flat: {type: [string, 'null'], oneOf: [{type: string, minLength: 1}]} + Beside: {allOf: [{type: [string, 'null']}], oneOf: [{type: string, minLength: 1}]} + Entry: {allOf: [{type: [string, 'null']}, {oneOf: [{type: string, minLength: 1}]}]} + Any: {type: [string, 'null'], anyOf: [{type: string, minLength: 1}]} + Pair: {type: [string, 'null'], oneOf: [{type: string, minLength: 1}], anyOf: [{type: string}]} + Plain: {type: [string, 'null'], allOf: [{type: string}]} + En: {type: [string, 'null'], enum: [a, b]} + Two: {type: [string, 'null'], oneOf: [{type: string, minLength: 1}, {type: string, maxLength: 0}]} + RefBranch: {type: [string, 'null'], anyOf: [{$ref: '#/components/schemas/S'}]} + Control: {type: [string, 'null'], oneOf: [{type: [string, 'null'], minLength: 1}]} + H: + type: object + properties: + f: {$ref: '#/components/schemas/Flat'} + b: {$ref: '#/components/schemas/Beside'} + e: {$ref: '#/components/schemas/Entry'} + an: {$ref: '#/components/schemas/Any'} + pr: {$ref: '#/components/schemas/Pair'} + p: {$ref: '#/components/schemas/Plain'} + en: {$ref: '#/components/schemas/En'} + two: {$ref: '#/components/schemas/Two'} + rb: {$ref: '#/components/schemas/RefBranch'} + ctrl: {$ref: '#/components/schemas/Control'} +` + +// TestNullAnswer_OneUnionAdmittingNoNullTakesItAway pins GitHub #2120: a +// union none of whose branches admits null is a conjunct forbidding it, as an +// allOf entry and a pair of unions are, so a type list's null beside it is +// taken away in every spelling, under either policy, with nothing read in; +// a union one of whose branches admits null keeps it. +func TestNullAnswer_OneUnionAdmittingNoNullTakesItAway(t *testing.T) { + t.Parallel() + for _, off := range []bool{false, true} { + doc, diags := compileNullableVerified(t, oneUnionSpec, off) + model, ok := doc.Types[componentID("H")].(*ir.Model) + require.True(t, ok) + properties := openapitest.PropertiesByWire(model.Properties) + for _, name := range []string{"f", "b", "e", "an", "pr", "p", "en", "two", "rb"} { + assert.Equal(t, refNull{}, nullOf(properties[name].Type), "policy off %t: %s admits no null", off, name) + } + assert.Equal(t, refNull{Nullable: true}, nullOf(properties["ctrl"].Type), "policy off %t: a branch admitting null keeps it", off) + assert.Empty(t, openapitest.PointersOf(diags, diag.InferredNullable), "policy off %t: nothing is read in", off) + } +} + +// besideUnion30Spec writes OpenAPI 3.0's `nullable: true` beside a type and a +// union none of whose branches admits null, at the positions and in the shapes +// the golden spec writes it: a component of a string, one of an integer over +// two integer branches, an inline property, an object over two $ref branches +// and an inline one, an anyOf on an allOf entry's property, and a parameter +// over one $ref branch; and a control whose branch writes `nullable: true` +// beside its own type. +const besideUnion30Spec = `openapi: 3.0.3 +info: {title: t, version: "1"} +paths: + /s: + get: + parameters: + - {name: q, in: query, schema: {type: string, nullable: true, oneOf: [{$ref: '#/components/schemas/Kind'}]}} + responses: {'200': {description: ok}} +components: + schemas: + Kind: {type: string, enum: [a, b]} + Idiom: {type: string, nullable: true, oneOf: [{type: string, minLength: 1}]} + Bytes: {type: integer, nullable: true, oneOf: [{enum: [0], type: integer}, {maximum: 10, minimum: 5, type: integer}]} + A: {type: object, properties: {a: {type: string}}} + B: {type: object, properties: {b: {type: string}}} + Holder: + type: object + properties: + idiom: {$ref: '#/components/schemas/Idiom'} + bytes: {$ref: '#/components/schemas/Bytes'} + inl: {type: string, nullable: true, oneOf: [{type: string, minLength: 1}]} + config: {type: object, nullable: true, oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}, {type: object, additionalProperties: false}]} + ctrl: {type: string, nullable: true, oneOf: [{type: string, nullable: true, minLength: 1}]} + Resp: + allOf: + - {type: object, properties: {x: {type: string}}} + - {type: object, properties: {result: {type: object, anyOf: [{type: object}, {type: string}], nullable: true}}} +` + +// besideUnion30Nulls returns what each reference besideUnion30Spec holds says +// of null, by property or parameter name. +func besideUnion30Nulls(t *testing.T, doc *ir.Document) map[string]refNull { + t.Helper() + out := map[string]refNull{} + for name, property := range holderProperties(t, doc) { + out[name] = nullOf(property.Type) + } + resp, ok := doc.Types[componentID("Resp")].(*ir.Model) + require.True(t, ok, "Resp lowers to a model") + out["result"] = nullOf(openapitest.PropertiesByWire(resp.Properties)["result"].Type) + parameter, ok := openapitest.ParamBySource(openapitest.FirstOperation(t, doc.Services[0]), "q") + require.True(t, ok) + out["q"] = nullOf(parameter.Type) + return out +} + +// TestNullAnswer_ANullableBesideAUnionAdmittingNoNullIsInferred pins the 3.0 +// idiom GitHub #2120 keeps: the union takes the declared null away, and the +// nullable-inference policy keeps the bit, marked inferred, with one info at +// each `nullable` naming the union the schema writes and no allOf, which it +// does not write. The golden spec's eight such sites take the same shapes. +// Policy off, no reference admits null and nothing is reported. +func TestNullAnswer_ANullableBesideAUnionAdmittingNoNullIsInferred(t *testing.T) { + t.Parallel() + sites := map[jsontext.Pointer]string{ + "/components/schemas/Idiom/nullable": "oneOf", + "/components/schemas/Bytes/nullable": "oneOf", + "/components/schemas/Holder/properties/inl/nullable": "oneOf", + "/components/schemas/Holder/properties/config/nullable": "oneOf", + "/components/schemas/Resp/allOf/1/properties/result/nullable": "anyOf", + "/paths/~1s/get/parameters/0/schema/nullable": "oneOf", + } + doc, diags := compileNullableVerified(t, besideUnion30Spec, false) + nulls := besideUnion30Nulls(t, doc) + for _, name := range []string{"idiom", "bytes", "inl", "config", "result", "q"} { + assert.Equal(t, inferredNull, nulls[name], "%s: the policy keeps the null the union takes away", name) + } + assert.Equal(t, refNull{Nullable: true}, nulls["ctrl"], "a branch admitting null keeps the declared null") + + var reported []jsontext.Pointer + for _, finding := range byCode(diags, diag.InferredNullable) { + reported = append(reported, finding.Provenance.Pointer) + assert.Equal(t, ir.SeverityInfo, finding.Severity) + union, ok := sites[finding.Provenance.Pointer] + if !ok { + continue + } + assert.Contains(t, finding.Message, union, "%s names the union it writes", finding.Provenance.Pointer) + assert.NotContains(t, finding.Message, "allOf", "%s names no allOf, which it does not write", finding.Provenance.Pointer) + } + assert.ElementsMatch(t, []jsontext.Pointer{ + "/components/schemas/Idiom/nullable", "/components/schemas/Bytes/nullable", + "/components/schemas/Holder/properties/inl/nullable", "/components/schemas/Holder/properties/config/nullable", + "/components/schemas/Resp/allOf/1/properties/result/nullable", "/paths/~1s/get/parameters/0/schema/nullable", + }, reported, "one info at each nullable the policy reads in") + + off, offDiags := compileNullableVerified(t, besideUnion30Spec, true) + for name, null := range besideUnion30Nulls(t, off) { + if name == "ctrl" { + assert.Equal(t, refNull{Nullable: true}, null, "policy off: the control's branch admits null") + continue + } + assert.False(t, null.Nullable, "policy off: %s admits no null", name) + } + assert.Empty(t, openapitest.PointersOf(offDiags, diag.InferredNullable)) +} + +// unionPairNullSpec is a oneOf whose first branch admits null only by the +// policy's reading of `nullable`, which 3.1 does not define, beside an anyOf +// with a null branch, so the two share null only under that reading. Its +// node is the conjunction decision's; the reference's null is held here. +const unionPairNullSpec = `openapi: 3.1.0 +info: {title: t, version: "1"} +paths: {} +components: + schemas: + P1: {oneOf: [{type: object, nullable: true, enum: [null]}, {type: string}], anyOf: [{type: 'null'}, {type: integer}]} + Holder: {type: object, properties: {p1: {$ref: '#/components/schemas/P1'}}} +` + +// TestNullAnswer_AUnionPairCarriesBothHalves pins that a pair of unions +// keeps the declared half of null apart from the lenient one: policy on, the +// reference admits the null the two share only by the policy's reading, +// marked inferred, and the pair is not reported as sharing no value; policy +// off, it admits none, and the pair shares no value. +func TestNullAnswer_AUnionPairCarriesBothHalves(t *testing.T) { + t.Parallel() + doc, diags := compileNullableVerified(t, unionPairNullSpec, false) + assert.Equal(t, inferredNull, nullOf(holderProperties(t, doc)["p1"].Type)) + assert.False(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/P1"), + "under the policy the pair shares null") + + off, offDiags := compileNullableVerified(t, unionPairNullSpec, true) + assert.Equal(t, refNull{}, nullOf(holderProperties(t, off)["p1"].Type)) + assert.True(t, openapitest.HasDiagCodeAt(offDiags, diag.UnsatisfiableSchema, "/components/schemas/P1"), + "as its version reads it the pair shares no value") +} diff --git a/compilers/openapi/e2e/null_answer_widening_test.go b/compilers/openapi/e2e/null_answer_widening_test.go new file mode 100644 index 000000000..63ce0d812 --- /dev/null +++ b/compilers/openapi/e2e/null_answer_widening_test.go @@ -0,0 +1,191 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// widenedSpellings writes K, the keywords stating a null, beside one $ref to T +// in each spelling of one conjunction (openapitest.Spellings). +func widenedSpellings(keywords string) map[string]string { + return openapitest.Spellings(refTo("T"), keywords) +} + +// widenedHolder writes, at version, the object T and Holder, whose properties +// are the spellings by name. +func widenedHolder(version string, spellings map[string]string) string { + var b strings.Builder + b.WriteString(" T: {type: object, properties: {a: {type: string}}}\n" + + " U: {type: object, properties: {u: {type: string}}}\n Holder:\n type: object\n properties:\n") + for name, spelling := range spellings { + b.WriteString(" " + name + ": " + spelling + "\n") + } + return openapitest.ComponentSpecVer(version, b.String()) +} + +// widenedNulls compiles spellings at version, policy on, and returns what +// each property's reference says of null, by spelling. +func widenedNulls(t *testing.T, version string, spellings map[string]string) (map[string]refNull, []ir.Diagnostic) { + t.Helper() + doc, diags := compileNullableVerified(t, widenedHolder(version, spellings), false) + out := map[string]refNull{} + properties := holderProperties(t, doc) + for name := range spellings { + property, ok := properties[name] + require.True(t, ok, name) + out[name] = nullOf(property.Type) + } + return out, diags +} + +// TestNullAnswer_ThePolicyWidensAReferenceAlikeInEverySpelling pins GitHub +// #2109's decision: the nullable-inference policy widens the one reference of +// a conjunction to "or null" where `nullable: true` or a value keyword admitting +// null states it, whichever object of the conjunction writes it, so the four +// spellings of one conjunction lower alike, notes, extensions, use-bound +// keywords and bounds beside it stopping nothing, each null read in reported. +// What states the null is said by the reference, kept nowhere. +func TestNullAnswer_ThePolicyWidensAReferenceAlikeInEverySpelling(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ version, keywords string }{ + {"3.1.0", "type: [object, 'null']"}, + {"3.1.0", "type: [object, 'null'], description: d, x-e: 1, readOnly: true, minProperties: 1"}, + {"3.0.3", "type: object, nullable: true"}, + {"3.1.0", "type: 'null'"}, + {"3.1.0", "const: null"}, + {"3.1.0", "enum: [null]"}, + } { + t.Run(tc.version+" "+tc.keywords, func(t *testing.T) { + t.Parallel() + spellings := widenedSpellings(tc.keywords) + doc, diags := compileNullableVerified(t, widenedHolder(tc.version, spellings), false) + properties := holderProperties(t, doc) + for spelling := range spellings { + property, ok := properties[spelling] + require.True(t, ok, spelling) + assert.Equal(t, inferredNull, nullOf(property.Type), spelling) + assert.Empty(t, property.Unmodeled, "%s: the reference says the null", spelling) + } + assert.Len(t, openapitest.PointersOf(diags, diag.InferredNullable), len(spellings), "one info per spelling read in") + }) + } +} + +// TestNullAnswer_AValueKeywordOfNullAloneBesideAReferenceIsTheNullableReference +// pins the idiom in each of its spellings: `type: 'null'`, `const: null` and +// `enum: [null]` beside a $ref, flat or beside an allOf of it, are each the +// nullable reference to its target, marked inferred, the keyword consumed. +func TestNullAnswer_AValueKeywordOfNullAloneBesideAReferenceIsTheNullableReference(t *testing.T) { + t.Parallel() + spellings := map[string]string{} + for _, keyword := range []string{"type: 'null'", "const: null", "enum: [null]"} { + name := strings.TrimSuffix(strings.Fields(keyword)[0], ":") + spellings["flat "+name] = "{" + refTo("T") + ", " + keyword + "}" + spellings["beside an allOf "+name] = "{allOf: [" + capRef("T") + "], " + keyword + "}" + } + doc, diags := compileNullableVerified(t, widenedHolder("3.1.0", spellings), false) + properties := holderProperties(t, doc) + for name := range spellings { + property := properties[name] + assert.Equal(t, inferred(componentID("T")), property.Type, "%s is the nullable reference to T", name) + assert.Empty(t, property.Unmodeled, "%s: the keyword is consumed", name) + } + assert.False(t, openapitest.HasDiag(diags, diag.UnsatisfiableSchema), "the idiom is satisfiable under the policy") + assert.Len(t, openapitest.PointersOf(diags, diag.InferredNullable), len(spellings), "one info per spelling read in") +} + +// TestNullAnswer_WithThePolicyOffANullAloneBesideAReferenceIsWhatItWrites pins +// the idiom with the policy off, where it is no reading and each form falls +// under the rule of what it writes, T admitting no null: a const or enum of +// null is the closed Enum with no member keeping the $ref, behind a reference +// that is not nullable, and a type of null alone is a closed Model with no +// member keeping each conjunct; each draws one unsatisfiable-schema warning. +func TestNullAnswer_WithThePolicyOffANullAloneBesideAReferenceIsWhatItWrites(t *testing.T) { + t.Parallel() + spellings := map[string]string{ + "const": "{" + refTo("T") + ", const: null}", + "enum": "{" + refTo("T") + ", enum: [null]}", + "type": "{" + refTo("T") + ", type: 'null'}", + } + doc, diags := compileNullableVerified(t, widenedHolder("3.1.0", spellings), true) + properties := holderProperties(t, doc) + for _, name := range []string{"const", "enum"} { + typeRef := properties[name].Type + assert.False(t, typeRef.Nullable, name) + enum, ok := doc.Types[typeRef.Target].(*ir.Enum) + require.True(t, ok, "%s lowers to an Enum", name) + assert.True(t, enum.Closed, name) + assert.Empty(t, enum.Members, name) + assert.Contains(t, enum.Unmodeled, "openapi:$ref", name) + } + typed := properties["type"].Type + assert.False(t, typed.Nullable) + model, ok := doc.Types[typed.Target].(*ir.Model) + require.True(t, ok, "a type of null beside an object is the bottom Model") + assert.NotEqual(t, componentID("T"), typed.Target) + assert.Empty(t, model.Properties) + assert.Nil(t, model.Base) + for _, name := range []string{"const", "enum", "type"} { + unsatisfiable := byCode(diagsBeneath(diags, "/components/schemas/Holder/properties/"+name), diag.UnsatisfiableSchema) + assert.Len(t, unsatisfiable, 1, "%s draws one finding", name) + } + assert.Empty(t, openapitest.PointersOf(diags, diag.InferredNullable)) +} + +// TestNullAnswer_ThePolicyWidensNothingBesideAUnionOrStructure pins where the +// policy does not widen, the null then conjoined as JSON Schema conjoins it: +// beside a union, which conjoins (GitHub #2109's two spellings among them, +// alike), beside a conjunct writing properties, the position's own among +// them, and where the conjunction holds two references. None is reported as +// read in. +func TestNullAnswer_ThePolicyWidensNothingBesideAUnionOrStructure(t *testing.T) { + t.Parallel() + const union = "anyOf: [{type: object, properties: {y: {type: string}}}, {type: 'null'}]" + const pair = "oneOf: [{type: object, properties: {x: {type: string}}}, {type: 'null'}], anyOf: [{type: object}, {type: 'null'}]" + spellings := map[string]string{ + "union flat": "{" + refTo("T") + ", " + union + "}", + "union beside an allOf": "{allOf: [" + capRef("T") + "], " + union + "}", + "pair flat": "{" + refTo("T") + ", " + pair + "}", + "pair beside an allOf": "{allOf: [" + capRef("T") + "], " + pair + "}", + "type beside a union": "{" + refTo("T") + ", type: [object, 'null'], oneOf: [{required: [a]}, {required: [b]}]}", + "type beside properties": "{allOf: [" + capRef("T") + ", {properties: {z: {type: string}}}], type: [object, 'null']}", + "two references": "{allOf: [" + capRef("T") + ", " + capRef("U") + "], type: [object, 'null']}", + "type beside its own properties": "{" + refTo("T") + ", type: [object, 'null'], properties: {z: {type: string}}}", + } + nulls, diags := widenedNulls(t, "3.1.0", spellings) + for spelling, null := range nulls { + assert.Equal(t, refNull{}, null, spelling) + } + assert.Empty(t, openapitest.PointersOf(diags, diag.InferredNullable), "nothing is read in") +} + +// TestNullAnswer_ANullableBesideAReferenceAndAUnionIsNotWidened pins that, at +// 3.0, `nullable: true` beside a $ref and a union none of whose branches admits +// null widens nothing: the union is a conjunct rejecting null, so the +// reference admits none, under either policy, and no null is read in. +func TestNullAnswer_ANullableBesideAReferenceAndAUnionIsNotWidened(t *testing.T) { + t.Parallel() + const union = "oneOf: [{type: object, required: [a]}, {type: object, required: [b]}]" + spellings := map[string]string{ + "flat": "{" + refTo("T") + ", nullable: true, " + union + "}", + "beside an allOf": "{allOf: [" + capRef("T") + "], nullable: true, " + union + "}", + } + for _, off := range []bool{false, true} { + doc, diags := compileNullableVerified(t, widenedHolder("3.0.3", spellings), off) + properties := holderProperties(t, doc) + for name := range spellings { + assert.Equal(t, refNull{}, nullOf(properties[name].Type), "policy off %t: %s", off, name) + } + assert.Empty(t, openapitest.PointersOf(diags, diag.InferredNullable), "policy off %t: nothing is read in", off) + } +} diff --git a/compilers/openapi/e2e/null_keywords_test.go b/compilers/openapi/e2e/null_keywords_test.go index a1c25bd1f..b1f59180a 100644 --- a/compilers/openapi/e2e/null_keywords_test.go +++ b/compilers/openapi/e2e/null_keywords_test.go @@ -24,11 +24,11 @@ import ( // TestCompile_ANullKeywordLowersAsTheKeywordLeftOut holds every keyword the // table gives a Schema Object to one reading of a null: the document lowers -// exactly as it does with the key removed, whatever node the keyword sits on and -// wherever the schema is written, and the load phase's warning for it is the -// only report. It reads the keywords off the table, so one the table gains is -// held too. An allOf entry is asked only where nothing else makes it residue, -// since residue keeps the whole entry as written, the null included. +// exactly as it does with the key removed, whatever node the keyword sits on +// and wherever the schema is written, and the load phase's warning for it is +// the only report. It reads the keywords off the table, so one the table gains +// is held too. An allOf entry is asked only where nothing else keeps it whole, +// since an entry kept whole keeps it as written, the null included. func TestCompile_ANullKeywordLowersAsTheKeywordLeftOut(t *testing.T) { t.Parallel() const noPaths = "paths: {}\n" diff --git a/compilers/openapi/e2e/nullable_inference_test.go b/compilers/openapi/e2e/nullable_inference_test.go index a77c7f1e2..473774a92 100644 --- a/compilers/openapi/e2e/nullable_inference_test.go +++ b/compilers/openapi/e2e/nullable_inference_test.go @@ -90,6 +90,9 @@ func assertNullableKeyword30(t *testing.T, doc *ir.Document, diags []ir.Diagnost assert.Equal(t, openapi.NullableInferenceHeuristic, properties[name].Type.Inferred, name) assert.True(t, properties[name].Type.Nullable, name) } + assert.Equal(t, inferred(componentID("Pet")), properties["composed"].Type, "the nullable reference") + assert.Equal(t, properties["composed"].Type, properties["typedComposed"].Type, + "a type naming the kind its $ref's target admits restates it, so it lowers as the schema writing no type") assert.True(t, properties["listed"].Type.Nullable) assert.Empty(t, properties["listed"].Type.Inferred, "an enum listing null agrees with the type nullable widens") @@ -182,14 +185,19 @@ func TestSchemaRefSiblings_ApplyAsIn31(t *testing.T) { // 3.0 $ref, applied as 3.1 applies it, is read as 3.0 defines it: its nullable // adds null to the type beside it, under either policy, and its // exclusiveMinimum is a boolean modifying the bound beside it, which the -// warning says. The 3.1 control reads its nullable as no keyword at all. +// warning says. The 3.1 control reads its nullable as no keyword at all. A +// type naming the kind the $ref's target admits restates it and says nothing, +// so each spelling lowers as its twin writing no type does. func TestSchemaRefSiblings_ReadInTheDeclaredDialect(t *testing.T) { t.Parallel() const at = "/components/schemas/Holder/properties/p" - // The keywords beside the $ref are a conjunct of the use, so p names the - // model over Maybe they make, as the allOf of the two does. + // With the policy off, the nullable beside the $ref is a conjunct of the + // use, so p names the model over Maybe it makes, as the allOf of the two + // does. With it on, the nullable the policy reads is the null Maybe + // admits, and p is the nullable reference. model := ir.TypeID("type/anonymous" + at) maybe := ir.TypeRef{Target: model, Nullable: true} + reference := ir.TypeRef{Target: componentID("Maybe"), Nullable: true} for _, tc := range []struct { name, version, p, rest string off bool @@ -198,8 +206,12 @@ func TestSchemaRefSiblings_ReadInTheDeclaredDialect(t *testing.T) { }{ {"3.0 off", "3.0.3", "{$ref: '#/components/schemas/Maybe', type: object, nullable: true}", " Maybe: {type: object, nullable: true}\n", true, maybe, nil}, + {"3.0 off, its twin writing no type", "3.0.3", "{$ref: '#/components/schemas/Maybe', nullable: true}", + " Maybe: {type: object, nullable: true}\n", true, maybe, nil}, {"3.0 on", "3.0.3", "{$ref: '#/components/schemas/Maybe', type: object, nullable: true}", - " Maybe: {type: object, nullable: true}\n", false, maybe, nil}, + " Maybe: {type: object, nullable: true}\n", false, reference, nil}, + {"3.0 on, its twin writing no type", "3.0.3", "{$ref: '#/components/schemas/Maybe', nullable: true}", + " Maybe: {type: object, nullable: true}\n", false, reference, nil}, {"3.1 off", "3.1.0", "{$ref: '#/components/schemas/Maybe', type: object, nullable: true}", " Maybe: {type: [object, \"null\"]}\n", true, ir.TypeRef{Target: model}, []jsontext.Pointer{at + "/nullable"}}, diff --git a/compilers/openapi/e2e/nullable_unread_test.go b/compilers/openapi/e2e/nullable_unread_test.go index 2a0fa75bf..24b47dadd 100644 --- a/compilers/openapi/e2e/nullable_unread_test.go +++ b/compilers/openapi/e2e/nullable_unread_test.go @@ -19,22 +19,21 @@ import ( ) // nullableValues are the values a `nullable` is written with, as YAML, each with -// the JSON the document holds, whether the nullable-inference policy reads it -// as admitting null (only the boolean true), and whether it is a null, which -// is the keyword left out. +// the JSON the document holds and whether the nullable-inference policy reads +// it as admitting null (only the boolean true). A null is among them: where no +// dialect defines the keyword, its null is a value like any other. var nullableValues = []struct { yaml, json string read bool - leftOut bool }{ - {"true", "true", true, false}, - {"false", "false", false, false}, - {`"true"`, `"true"`, false, false}, - {"1", "1", false, false}, - {"[true]", "[true]", false, false}, - {"{a: 1}", `{"a":1}`, false, false}, - {`"yes"`, `"yes"`, false, false}, - {"null", "null", false, true}, + {"true", "true", true}, + {"false", "false", false}, + {`"true"`, `"true"`, false}, + {"1", "1", false}, + {"[true]", "[true]", false}, + {"{a: 1}", `{"a":1}`, false}, + {`"yes"`, `"yes"`, false}, + {"null", "null", false}, } // nullableSchemas writes each value of nullableValues at four positions: on a @@ -65,17 +64,15 @@ type nullableFacts struct { // factsOfNullable returns what the value at index i leaves: the keyword is kept // beside its position when no one reads it, and with it an info of the dialect // not defining it, on an allOf entry as beside it. A value that is read leaves -// one info, of the null read in, and a null is the keyword left out. +// one info, of the null read in. A null is kept as any other value is: it is +// the keyword left out only where a dialect defines the keyword. func factsOfNullable(i int, policyOn bool) nullableFacts { v := nullableValues[i] nullableFactsValue := nullableFacts{kept: map[string]string{}, infos: map[string][]jsontext.Pointer{}, reasons: map[string]ir.UnmodeledReason{}} at := func(name string) jsontext.Pointer { return jsontext.Pointer(fmt.Sprintf("/components/schemas/%s%d", name, i)) } - switch { - case v.leftOut: - return nullableFactsValue - case policyOn && v.read: + if policyOn && v.read { nullableFactsValue.infos[diag.InferredNullable] = []jsontext.Pointer{ at("A") + "/allOf/1/nullable", at("C") + "/nullable", at("P") + "/properties/p/nullable", at("R") + "/properties/r/nullable", } @@ -120,8 +117,9 @@ func nullableEntries(t *testing.T, doc *ir.Document, i int) map[string]ir.Unmode // schema beside a $ref and an allOf entry), that at 3.1 and 3.2, where no // dialect defines the keyword, the policy takes out the boolean true it reads // and nothing else: every other value is kept verbatim as an unknown keyword -// under either setting, a null being the keyword left out. With the policy off -// the true is kept as well. +// under either setting, a null among them, since a null reads as the keyword +// left out only where a dialect defines it. With the policy off the true is +// kept as well. func TestNullable_AValueThePolicyDoesNotReadIsKeptAtOpenAPI31(t *testing.T) { t.Parallel() for _, version := range []string{"3.1.0", "3.2.0"} { diff --git a/compilers/openapi/e2e/number_text_beside_test.go b/compilers/openapi/e2e/number_text_beside_test.go index a4fed11ed..213c14bae 100644 --- a/compilers/openapi/e2e/number_text_beside_test.go +++ b/compilers/openapi/e2e/number_text_beside_test.go @@ -49,12 +49,12 @@ type textCell struct { } // TestNumberText_ABoundBesideAPrincipalIsKeptAsFlat pins each value bound -// written beside an allOf principal carrying a number as text, on another -// entry in either order or on the principal's own entry, at a component and a +// written beside an allOf principal carrying a number as text, on another entry +// in either order or on the principal's own entry, at a component and a // property, in both declaration orders: kept once, under no_ir_home with the -// number-as-text info, on the node the flat spelling keeps it on, a type -// list's text variant where its own entry writes it and else the Union -// (docs/compilers/openapi.md#string-formats). +// number-as-text info, on the node the flat spelling keeps it on, a type list's +// text variant wherever one conjunct alone writes it, as its node reads the +// list's conjuncts (docs/compilers/openapi.md#string-formats). func TestNumberText_ABoundBesideAPrincipalIsKeptAsFlat(t *testing.T) { t.Parallel() n := len(numberTextPrincipals) * len(textBounds) * len(textSpellings) * 2 @@ -91,16 +91,7 @@ func TestNumberText_ABoundBesideAPrincipalIsKeptAsFlat(t *testing.T) { assert.Equal(t, got, backward[cell.component], "the declaration order decides nothing") flat := forward[strings.Replace(cell.component, strings.ReplaceAll(cell.spelling, " ", ""), "flat", 1)] require.Len(t, flat.kept, 1, "the flat spelling keeps it once") - if cell.principal == 1 && cell.spelling != "own" { - // The type list's text variant holds what its own entry writes, so - // one written elsewhere is kept on the Union, where a second - // writer of the keyword cannot overwrite it. - owner := "document.Types[type/openapi/components/schemas/X].Unmodeled" - if cell.property { - owner = "document.Types[type/anonymous/components/schemas/X/properties/p].Unmodeled" - } - flat.kept = []string{owner + " " + string(ir.ReasonNoIRHome)} - } + assert.True(t, flat.reported, "and reports it under openapi/unhomed-construct") assert.Equal(t, flat, got, "kept and reported as the flat spelling is") }) } @@ -133,7 +124,7 @@ func textBoundsKept(t *testing.T, lines []string, cells []textCell) map[string]k } } for _, diagnostic := range diags { - if diagnostic.Code == diag.DegradedConstruct && strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"+cell.component+"/") && + if diagnostic.Code == diag.UnhomedConstruct && strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"+cell.component+"/") && strings.HasPrefix(diagnostic.Message, cell.keyword+" bounds no number written as text") { keptTextValue.reported = true } @@ -143,27 +134,75 @@ func textBoundsKept(t *testing.T, lines []string, cells []textCell) map[string]k return out } -// TestNumberText_TwoWritersOfABoundKeepBoth pins a bound two conjuncts write +// TestNumberText_TwoConjunctsOfABoundIntersect pins a bound two conjuncts write // apart from the principal carrying a number as text, beside the allOf and on -// an entry, or on two entries, and one a type list's own entry and the -// position both write: each value is kept once, none overwriting another. -func TestNumberText_TwoWritersOfABoundKeepBoth(t *testing.T) { +// an entry, on two entries, on the principal and an entry, on a type list's own +// entry and the position, and on a position's own string and its entry: the +// conjuncts intersect as any bound's do, and the node keeps the value they +// intersect in once, the writing it replaces nowhere. +func TestNumberText_TwoConjunctsOfABoundIntersect(t *testing.T) { t.Parallel() const text = "type: string, format: double" doc, diags := parseFull(t, openapitest.ComponentSpec( " E: {allOf: [{"+text+", minimum: 11}, {minimum: 12}]}\n"+ " T: {allOf: [{"+text+"}, {minimum: 21}, {minimum: 22}]}\n"+ " B: {allOf: [{"+text+"}, {minimum: 31}], minimum: 32}\n"+ - " L: {allOf: [{type: [string, boolean], format: int64, minimum: 41}], minimum: 42}\n")) + " L: {allOf: [{type: [string, boolean], format: int64, minimum: 41}], minimum: 42}\n"+ + " O: {"+text+", minimum: 51, allOf: [{minimum: 52}]}\n"+ + " M: {allOf: [{"+text+", maximum: 69}, {maximum: 61}]}\n")) openapitest.RequireNoErrorDiags(t, diags) sites := unmodeledSites(doc) - for _, want := range []string{"11", "12", "21", "22", "31", "32", "41", "42"} { + for want, times := range map[string]int{ + "11": 0, "12": 1, "21": 0, "22": 1, "31": 0, "32": 1, "41": 0, "42": 1, "51": 0, "52": 1, "69": 0, "61": 1, + } { var held int for _, site := range sites { - if strings.Contains(string(site.entry.Value), `"minimum":`+want) || string(site.entry.Value) == want { + if strings.Contains(string(site.entry.Value), "imum\":"+want) || string(site.entry.Value) == want { held++ } } - assert.Equal(t, 1, held, "minimum %s is kept once", want) + assert.Equal(t, times, held, "the bound %s is kept %d times", want, times) + } + for _, name := range []string{"E", "T", "B", "O", "M"} { + for _, diagnostic := range diags { + if strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"+name+"/") { + assert.NotContains(t, diagnostic.Message, "keeps otherwise", "%s: no writer is kept apart", name) + } + } + } +} + +// TestNumberText_TwoConjunctsIntersectingInAValueNoneWritesKeepIt pins two +// steps on a number as text, whose common multiple neither writes: the node +// keeps that multiple, its report naming it, on a string principal, a +// position's own string and a type list's variant; and two patterns, which +// intersect in no value, kept on their entries with the report that the +// conjuncts disagree. +func TestNumberText_TwoConjunctsIntersectingInAValueNoneWritesKeepIt(t *testing.T) { + t.Parallel() + const text = "type: string, format: double" + doc, diags := parseFull(t, openapitest.ComponentSpec( + " S: {allOf: [{"+text+"}, {multipleOf: 2}, {multipleOf: 3}]}\n"+ + " O: {"+text+", multipleOf: 2, allOf: [{multipleOf: 3}]}\n"+ + " L: {allOf: [{type: [string, boolean], format: int64}, {multipleOf: 2}, {multipleOf: 3}]}\n"+ + " P: {allOf: [{"+text+"}, {pattern: a}, {pattern: b}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + for name, node := range map[string]ir.TypeID{ + "S": componentID("S"), "O": componentID("O"), "L": "type/anonymous/components/schemas/L/type/0", + } { + td, ok := doc.Types[node] + require.True(t, ok, name) + kept := td.Common().Unmodeled + assert.Equal(t, "6", string(unmodeledEntry(t, kept, "openapi:multipleOf").Value), "%s keeps the multiple", name) + assert.Equal(t, ir.ReasonNoIRHome, kept["openapi:multipleOf"].Reason, name) + assert.Len(t, kept, 1, "%s keeps no conjunct apart", name) + message := openapitest.DiagMessageAt(t, diags, diag.UnhomedConstruct, ir.SeverityInfo, string(kept["openapi:multipleOf"].Provenance.Pointer)) + assert.Contains(t, message, "meet in 6", name) + } + pattern := typeByName(doc, "P") + require.NotNil(t, pattern) + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:allOf/1": ir.ReasonNoIRHome, "openapi:allOf/2": ir.ReasonNoIRHome}, keptOn(pattern)) + for _, at := range []string{"/components/schemas/P/allOf/1", "/components/schemas/P/allOf/2"} { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), "disagree", at) } } diff --git a/compilers/openapi/e2e/older_drafts_test.go b/compilers/openapi/e2e/older_drafts_test.go index 80f84b954..7f48563fd 100644 --- a/compilers/openapi/e2e/older_drafts_test.go +++ b/compilers/openapi/e2e/older_drafts_test.go @@ -154,11 +154,12 @@ func TestOlderDrafts_ATypeListsArrayVariantIsTheTupleWritten(t *testing.T) { } // TestOlderDrafts_ATupleIsReadInTheDialectWhereItIsWritten pins a draft's tuple -// beneath a type list's array variant, which stands at a pointer of its own, to -// the dialect of the resource it is written in: the variant's items, a draft 7 -// resource of its own, is the Tuple it is under a type array, and so is the -// variant of a type list a draft 7 allOf entry writes, which stands under the -// position's pointer, though the document reads 2020-12. +// beneath a type list's array variant to the dialect of the resource it is +// written in: the variant's items, a draft 7 resource of its own, is the Tuple +// it is under a type array, at the pointer where it is written rather than +// beneath the variant's (GitHub #1888), and so is the variant of a type list a +// draft 7 allOf entry writes, which sits under the position's pointer, though +// the document reads 2020-12. func TestOlderDrafts_ATupleIsReadInTheDialectWhereItIsWritten(t *testing.T) { t.Parallel() const items = "items: {$id: 'https://example.com/%s', $schema: " + draft07 + ", type: array, items: [{type: string}]}" @@ -169,7 +170,7 @@ func TestOlderDrafts_ATupleIsReadInTheDialectWhereItIsWritten(t *testing.T) { ", type: [string, array], items: [{type: string}]}, {description: d}]}\n")) openapitest.RequireNoErrorDiags(t, diags) for _, id := range []ir.TypeID{ - "type/anonymous/components/schemas/Variant/type/1/items", "type/anonymous/components/schemas/Array/items", "type/anonymous/components/schemas/Entry/type/1", + "type/anonymous/components/schemas/Variant/items", "type/anonymous/components/schemas/Array/items", "type/anonymous/components/schemas/Entry/type/1", } { tuple, ok := doc.Types[id].(*ir.Tuple) require.True(t, ok, "%s is the tuple its resource writes", id) diff --git a/compilers/openapi/e2e/overlay_refusal_test.go b/compilers/openapi/e2e/overlay_refusal_test.go index c1dbf2d5a..ec5e7f300 100644 --- a/compilers/openapi/e2e/overlay_refusal_test.go +++ b/compilers/openapi/e2e/overlay_refusal_test.go @@ -58,14 +58,14 @@ paths: ` // TestCompile_AnOverlayKeepsWhatTheSourceIsRefusedFor holds each finding above -// info the source alone draws for a mapping, a key or a merge to standing at -// its pointer, an error still failing the compile, under an overlay writing -// into the mapping, writing or removing a member, writing inside one, or -// copying the mapping, merging or not. The rows are written by hand from what +// info the source alone draws for a mapping, a key or a merge to being at its +// pointer, an error still failing the compile, under an overlay writing into +// the mapping, writing or removing a member, writing inside one, or copying the +// mapping, merging or not. The rows are written by hand from what // specrules.CheckFormat, specrules.CheckRepeatedKeys and the load phase's // tagged-mapping and anchor-cycle refusals report of a mapping's YAML, so a // report added there needs its row. A key's text is judged on the overlaid -// tree, so four rules of it stand for the rest. +// tree, so four rules of it represent the rest. func TestCompile_AnOverlayKeepsWhatTheSourceIsRefusedFor(t *testing.T) { t.Parallel() const s, h = "$.components.schemas.S", "$.paths['/a'].get.responses['200'].headers" diff --git a/compilers/openapi/e2e/overlay_test.go b/compilers/openapi/e2e/overlay_test.go index a0db40ac9..97299e98b 100644 --- a/compilers/openapi/e2e/overlay_test.go +++ b/compilers/openapi/e2e/overlay_test.go @@ -72,7 +72,7 @@ func compileWith(t *testing.T, opts openapi.Options) (*ir.Document, []ir.Diagnos // the bytes on disk. Each repeat is reported at itself, naming the first // holder, and credited to the document that wrote that entry, as any finding at // a pointer is: the overlay for an entry it appended, the base for the ones it -// wrote, though an overlay renaming an earlier entry joins them. +// wrote, though an overlay renaming an earlier entry combines them. func TestCompile_OverlayServerNameRepeatsAreCreditedToTheirWriter(t *testing.T) { t.Parallel() type report struct { @@ -234,8 +234,8 @@ func TestCompile_OverlayAppliesBeforeLowering(t *testing.T) { // TestCompile_OverlayWorkAnAliasMountsStaysWhereItWasWritten pins where the // overlay's writes land when the source shares the node it writes. The overlay // wrote the anchor's own position, so that one is credited to it, and the -// positions an alias and a `<<` merge key stand at keep the value they stood -// for, which the overlay never wrote: they hold no property it added. +// positions an alias and a `<<` merge key sit at keep the value they +// represented, which the overlay never wrote: they hold no property it added. func TestCompile_OverlayWorkAnAliasMountsStaysWhereItWasWritten(t *testing.T) { t.Parallel() const spec = `openapi: 3.1.0 @@ -729,8 +729,9 @@ actions: } } want := []ir.Diagnostic{{Severity: ir.SeverityError, Code: diag.CyclicRef, - Message: "cyclic $ref: the chain of $refs through #/components/schemas/A, #/components/schemas/B " + - "comes back to where it started and never reaches a schema", + Message: "cyclic $ref: #/components/schemas/A, #/components/schemas/B refer only to each other, by $ref or by an " + + "allOf of one $ref, so none of them constrains a value; give one of them a type, properties or " + + "another constraint", Provenance: ir.Provenance{Pointer: "/components/schemas/A"}}} assert.Empty(t, cmp.Diff(want, errs)) // A, on the loop, lowers to the top type; B writes a type beside its $ref, @@ -1039,15 +1040,15 @@ func TestCompile_OverlayIsCreditedWithTheKeysItAdds(t *testing.T) { {"combined entry the overlay writes in full (contains + minContains)", "openapi:contains", 1}, {"combined entry on an array schema (unevaluatedItems alone)", "openapi:unevaluated", 1}, {"dialect keyword the overlay adds", "openapi:$id", 1}, - {"unknown schema keyword the overlay adds (preserve.go PreserveUnknownKeywords)", "openapi:frobnicate", 1}, + {"unknown schema keyword the overlay adds (keep.go KeepUnknownKeywords)", "openapi:frobnicate", 1}, {"property extension (property.go fillPropertyAnnotations)", "openapi:x-prop", 1}, {"false allOf entry (allof.go applyFalseEntries)", "openapi:allOf/1", 1}, - {"validation-only oneOf beside a model (union.go preserveBranchSets)", "openapi:oneOf", 1}, + {"validation-only oneOf beside a model (union.go keepBranchSets)", "openapi:oneOf", 1}, {"operation extension (operations.go applyOperationAnnotations)", "openapi:x-op", 1}, {"operation unknown key (operations.go applyOperationAnnotations)", "openapi:opBogus", 1}, {"externalDocs unknown key (operations.go applyOperationAnnotations)", "openapi:externalDocs/edBogus", 1}, - {"response unknown key (responses.go preserveResponseExtras)", "openapi:bogus", 1}, - {"response extension (responses.go preserveResponseExtras)", "openapi:x-resp", 1}, + {"response unknown key (responses.go keepResponseExtras)", "openapi:bogus", 1}, + {"response extension (responses.go keepResponseExtras)", "openapi:x-resp", 1}, {"media type unknown key (content.go lowerContent)", "openapi:mediaBogus", 1}, {"header unknown key (headers.go applyHeaderAnnotations)", "openapi:headerBogus", 1}, {"example unknown key (examples.go appendPluralExample)", "openapi:exBogus", 1}, @@ -1057,7 +1058,7 @@ func TestCompile_OverlayIsCreditedWithTheKeysItAdds(t *testing.T) { {"parameter schema extension (params.go fillParamSchemaAnnotations)", "openapi:schema/x-ps", 1}, {"security scheme extension (schemes.go applySchemeAnnotations)", "openapi:x-scheme", 1}, {"security scheme unknown key (schemes.go lowerSecurityScheme)", "openapi:schemeBogus", 1}, - {"field the scheme's type leaves unread (schemes.go preserveUnreadFields)", "openapi:bearerFormat", 1}, + {"field the scheme's type leaves unread (schemes.go keepUnreadFields)", "openapi:bearerFormat", 1}, {"OAuth flows extension (schemes.go applySchemeAnnotations)", "openapi:flows/x-flows", 1}, {"OAuth flows unknown key (schemes.go applySchemeAnnotations)", "openapi:flows/flowsBogus", 1}, {"OAuth flow extension (flows.go applyFlowAnnotations)", "openapi:x-flow", 1}, @@ -1148,10 +1149,11 @@ func TestCompile_OverlayIsCreditedWithTheKeysItAdds(t *testing.T) { // call paths provenanceSpec cannot reach. annotation.Constraints keeps a 3.0 // exclusiveMinimum or exclusiveMaximum that has no bound beside it to modify, // which only a 3.0 document reads as a modifier: for a component schema -// (declaration.go hoistDeclarationHome) and for a parameter's schema (params.go +// (declaration.go homeDeclaration) and for a parameter's schema (params.go // fillParamSchema), each through schema.ConstraintsOf. And a oneOf that will -// not render is reported rather than kept (union.go preserveBranchSets), which -// is an error a clean fixture cannot carry. +// not render, its one branch declaring no shape against the string, is +// reported rather than kept (union.go keepBranchSets), which is an error a +// clean fixture cannot carry. func TestCompile_OverlayIsCreditedWithAKeptModifierAndAnUnkeptBranchSet(t *testing.T) { t.Parallel() const spec = `openapi: 3.0.3 @@ -1182,7 +1184,7 @@ actions: exclusiveMaximum: true - target: $.components.schemas.Str update: - oneOf: [{enum: [.nan]}] + oneOf: [{example: .nan}] ` doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: "spec.yaml", Data: []byte(spec)}}, @@ -1198,7 +1200,7 @@ actions: entries := unmodeledEntriesByPath(doc) assert.Equal(t, ir.Provenance{Source: 0, Pointer: "/components/schemas/Num/exclusiveMinimum", WrittenBy: 1}, entryKeyed(t, entries, "openapi:exclusiveMinimum").Provenance, - "a component schema's kept modifier (declaration.go hoistDeclarationHome)") + "a component schema's kept modifier (declaration.go homeDeclaration)") assert.Equal(t, ir.Provenance{Source: 0, Pointer: "/paths/~1n/get/parameters/0/schema/exclusiveMaximum", WrittenBy: 1}, entryKeyed(t, entries, "openapi:schema/exclusiveMaximum").Provenance, "a parameter schema's kept modifier (params.go fillParamSchema)") @@ -1206,7 +1208,7 @@ actions: unkept := diagnosticsByCodeAndPointer(diags)[diagKey{diag.UnpreservableConstruct, "/components/schemas/Str/oneOf"}] require.Len(t, unkept, 1, "the oneOf that will not render is reported: %+v", diags) assert.Equal(t, 1, unkept[0].Provenance.WrittenBy, - "a branch set the overlay added is reported as the overlay's (union.go preserveBranchSets)") + "a branch set the overlay added is reported as the overlay's (union.go keepBranchSets)") } // TestCompile_OverlayIsCreditedWithAnUnkeptCombinedEntry is the failure half of @@ -1383,3 +1385,39 @@ func TestCompile_OverlayWritingAnIDTwiceIsAConflictNotARemount(t *testing.T) { }) } } + +// TestCompile_AnExtensionAnOverlayAddsIsCreditedAsWhatHoldsIt holds the +// warning of an extension no JSON holds, which an overlay adds into a schema +// the source writes, to one placement and one writer whichever keeping drops +// it: the keyword kept flat beside a type, and the entry of an allOf whose +// conjuncts disagree on it, kept whole. The overlay only added into what holds +// the extension, so the warning is credited as that is, to the source. +func TestCompile_AnExtensionAnOverlayAddsIsCreditedAsWhatHoldsIt(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct{ schema, target, at string }{ + "kept flat": { + schema: " type: object\n not: {type: string}\n", + target: "$.components.schemas.S.not", at: "/components/schemas/S/not", + }, + "kept whole": { + schema: " allOf:\n - {type: object, not: {type: string}}\n - {type: object, not: {type: integer}}\n", + target: "$.components.schemas.S.allOf[0].not", at: "/components/schemas/S/allOf/0/not", + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + spec := "openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n schemas:\n S:\n" + tc.schema + patch := "overlay: 1.0.0\ninfo: {title: p, version: '1'}\nactions:\n - target: " + tc.target + "\n update: {x-bad: .nan}\n" + _, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: "spec.yaml", Data: []byte(spec)}}, + compilers.Options{FormatOptions: openapi.Options{Overlay: &openapi.Overlay{Path: "patch.yaml", Data: []byte(patch)}}}) + require.NoError(t, err) + var warned []ir.Provenance + for _, diagnostic := range diags { + if diagnostic.Message == `extension "x-bad" could not be serialized` { + warned = append(warned, diagnostic.Provenance) + } + } + assert.Equal(t, []ir.Provenance{{Pointer: jsontext.Pointer(tc.at)}}, warned, "one warning, the source's: %+v", diags) + }) + } +} diff --git a/compilers/openapi/e2e/overlay_value_test.go b/compilers/openapi/e2e/overlay_value_test.go index 8678fac59..0ac2d80a6 100644 --- a/compilers/openapi/e2e/overlay_value_test.go +++ b/compilers/openapi/e2e/overlay_value_test.go @@ -69,7 +69,7 @@ func TestCompile_AnOverlayDescribesOneSchemaOfASharedNode(t *testing.T) { assert.Empty(t, diags, "no warning for what the source shares") assert.Equal(t, "only A", schemaDescription(t, shared, "A")) - assert.Empty(t, schemaDescription(t, shared, "B"), "the alias keeps the value it stood for") + assert.Empty(t, schemaDescription(t, shared, "B"), "the alias keeps the value it represented") assert.Equal(t, "c", schemaDescription(t, shared, "C"), "and so does the merge, with what it wrote") for _, name := range []string{"A", "B", "C"} { model, ok := typeByName(shared, name).(*ir.Model) diff --git a/compilers/openapi/e2e/pending_keeps_test.go b/compilers/openapi/e2e/pending_keeps_test.go new file mode 100644 index 000000000..3b35d08d1 --- /dev/null +++ b/compilers/openapi/e2e/pending_keeps_test.go @@ -0,0 +1,372 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "encoding/json/v2" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// keptValuesOf returns, for each Unmodeled entry of unmodeled, the value it +// holds for keyword: the entry's own under the plain key, or the member of an +// entry holding a whole schema. A value is its JSON text. +func keptValuesOf(t *testing.T, unmodeled ir.Unmodeled, keyword string) []string { + t.Helper() + var out []string + for key, entry := range unmodeled { + if key == "openapi:"+keyword || strings.HasSuffix(key, "/"+keyword) && !strings.Contains(key, "allOf/") { + out = append(out, string(entry.Value)) + continue + } + var members map[string]jsontext.Value + if json.Unmarshal(entry.Value, &members) == nil { + if value, held := members[keyword]; held { + out = append(out, string(value)) + } + } + } + slices.Sort(out) + return out +} + +// reportsNaming returns the findings of diags drawn at or under at whose +// message names keyword. +func reportsNaming(diags []ir.Diagnostic, at jsontext.Pointer, keyword string) []ir.Diagnostic { + var out []ir.Diagnostic + for _, d := range diags { + under := underPointer(string(d.Provenance.Pointer), string(at)) + if under && slices.Contains(strings.FieldsFunc(d.Message, func(r rune) bool { + return !strings.ContainsRune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-$", r) + }), keyword) { + out = append(out, d) + } + } + return out +} + +// TestPendingKeeps_TheRecordedDoubleKeepsHold holds the three places a value is +// kept twice on purpose: an entry kept whole holds every key it writes, so +// one the position writes alike is kept there and at the position; an +// extension the promotion policy reads is kept at each writer; and an entry +// inside a flattened entry kept whole is kept inside its copy and under its +// own path. +func TestPendingKeeps_TheRecordedDoubleKeepsHold(t *testing.T) { + t.Parallel() + doc, _ := parseVerified(t, admissionSpec("3.1.0", "", + "A: {type: object, allOf: [{foo: 1, x-k: 1}, {x-k: 2}], foo: 1}", + "B: {allOf: [{type: string, x-deprecated-reason: r, x-k: 1}, {x-k: 2}], x-deprecated-reason: r}", + "C: {type: object, allOf: [{allOf: [false], x-k: 1}, {x-k: 2}]}", + )) + a := typeByName(doc, "A").Common().Unmodeled + assert.Equal(t, []string{"1", "1"}, keptValuesOf(t, a, "foo"), "inside the whole entry and at the position") + assert.Contains(t, a, "openapi:foo") + b := typeByName(doc, "B").Common().Unmodeled + assert.Equal(t, []string{`"r"`, `"r"`}, keptValuesOf(t, b, "x-deprecated-reason"), "at each writer") + assert.Contains(t, b, "openapi:x-deprecated-reason") + c := typeByName(doc, "C").Common().Unmodeled + assert.Equal(t, "false", string(unmodeledEntry(t, c, "openapi:allOf/0/allOf/0").Value), "under its own path") + var flattened map[string]any + require.NoError(t, json.Unmarshal(unmodeledEntry(t, c, "openapi:allOf/0").Value, &flattened)) + assert.Equal(t, []any{false}, flattened["allOf"], "and inside the flattened entry's copy") +} + +// TestPendingKeeps_AnEntryKeptWholeIsReportedOnceNamingWhatItHolds holds an entry +// kept whole for one keyword that also writes a validation-only one: one +// Unmodeled entry holds both, and one report at the entry names both. +func TestPendingKeeps_AnEntryKeptWholeIsReportedOnceNamingWhatItHolds(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", + "T: {type: object, properties: {a: {type: string}}}", + "Entry: {allOf: [{$ref: '#/components/schemas/T'}, {unevaluatedProperties: false, not: {required: [a]}}]}", + )) + kept := typeByName(doc, "Entry").Common().Unmodeled + require.Len(t, kept, 1, "one entry: %v", kept) + var whole map[string]any + require.NoError(t, json.Unmarshal(unmodeledEntry(t, kept, "openapi:allOf/1").Value, &whole)) + assert.Contains(t, whole, "unevaluatedProperties") + assert.Contains(t, whole, "not") + reports := diagsUnder(diags, "/components/schemas/Entry") + require.Len(t, reports, 1, "one report for the one entry: %+v", reports) + assert.Equal(t, jsontext.Pointer("/components/schemas/Entry/allOf/1"), reports[0].Provenance.Pointer) + assert.Contains(t, reports[0].Message, "unevaluatedProperties") + assert.Contains(t, reports[0].Message, "not") +} + +// TestPendingKeeps_AKeywordIsReportedAsItsFlatSpellingReportsIt holds one report +// per keyword kept, worded as the flat spelling words it: a union kept beside +// a value set is explained alike on an entry and beside the allOf, its dead +// branch and the member of the set it refuses too, and an entry's unknown +// keywords draw one report each, at the keyword, as written flat. +func TestPendingKeeps_AKeywordIsReportedAsItsFlatSpellingReportsIt(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", + "T: {type: string}", + "Beside: {allOf: [{$ref: '#/components/schemas/T'}], enum: [a, b], oneOf: [{enum: [a]}, {type: integer}]}", + "Entry: {allOf: [{$ref: '#/components/schemas/T'}, {enum: [a, b], oneOf: [{enum: [a]}, {type: integer}]}]}", + "Flat: {type: object, k0a: 1, k0b: 1, k0c: 1}", + "Split: {type: object, allOf: [{k0a: 1, k0b: 1, k0c: 1}, {k1a: 1, k1b: 1, k1c: 1}]}", + )) + assert.Equal(t, unmodeledKeySet(typeByName(doc, "Beside").Common().Unmodeled), + unmodeledKeySet(typeByName(doc, "Entry").Common().Unmodeled)) + beside := reportsNaming(diags, "/components/schemas/Beside", "oneOf") + entry := reportsNaming(diags, "/components/schemas/Entry", "oneOf") + messages := func(reports []ir.Diagnostic) []string { + out := make([]string, 0, len(reports)) + for _, report := range reports { + out = append(out, report.Message) + } + slices.Sort(out) + return out + } + assert.Len(t, beside, 3, "the union's keep, its dead branch and the member it refuses") + assert.Equal(t, messages(beside), messages(entry), "one sentence for one reason") + + flat := diagsAt(diags, diag.UnknownSchemaKeyword, "/components/schemas/Flat/k0a") + for _, entry := range []string{"allOf/0/k0", "allOf/1/k1"} { + for _, suffix := range []string{"a", "b", "c"} { + at := "/components/schemas/Split/" + entry + suffix + assert.Equal(t, flat, diagsAt(diags, diag.UnknownSchemaKeyword, at), at) + } + } + assert.Len(t, diagsUnder(diags, "/components/schemas/Split"), 6, "one report per keyword kept") +} + +// unmodeledKeySet lists unmodeled's keys, sorted. +func unmodeledKeySet(unmodeled ir.Unmodeled) []string { + keys := make([]string, 0, len(unmodeled)) + for key := range unmodeled { + keys = append(keys, key) + } + slices.Sort(keys) + return keys +} + +// TestPendingKeeps_AValueABuildKeepsIsReportedOnceUnderOneKey holds what an inline +// principal's build keeps, which an entry around it writes alike while the +// keywords beside the outer allOf write it otherwise: kept once with one +// report, as a passed-over union as a kept format, each under a key of the +// same shape, the position's own under the plain key. +func TestPendingKeeps_AValueABuildKeepsIsReportedOnceUnderOneKey(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", + "Build: {allOf: [{allOf: [{oneOf: [{type: string}, {type: integer}], anyOf: [{type: string}, {type: boolean}]}], "+ + "anyOf: [{type: string}, {type: boolean}]}], anyOf: [{type: string}, {type: number}]}", + "Fmt: {allOf: [{allOf: [{type: string, format: byte, contentEncoding: base64url}], format: byte}], format: uuid}", + )) + keyOf := func(name, keyword, inner string) string { + t.Helper() + var key string + for k, entry := range typeByName(doc, name).Common().Unmodeled { + if k != "openapi:"+keyword && strings.Contains(string(entry.Value), inner) { + assert.Empty(t, key, "%s keeps the inner %s once", name, keyword) + key = k + } + } + return key + } + build, format := keyOf("Build", "anyOf", "boolean"), keyOf("Fmt", "format", "byte") + assert.NotEmpty(t, build) + assert.Equal(t, format, build, "one key shape whichever keyword the build keeps") + assert.Len(t, reportsNaming(diags, "/components/schemas/Build/allOf/0", "anyOf"), 1, "one report for the one writing") + assert.Len(t, reportsNaming(diags, "/components/schemas/Fmt/allOf/0", "format"), 1) + assert.JSONEq(t, `[{"type":"string"},{"type":"number"}]`, + string(unmodeledEntry(t, typeByName(doc, "Build").Common().Unmodeled, "openapi:anyOf").Value)) +} + +// TestPendingKeeps_AnEntryKeptWholeTakesItsKeywordsReason holds an entry kept +// whole for a keyword another writer gives otherwise to the reason that keyword +// is kept under alone, on that entry or beside the allOf; on a number as text, +// two patterns, which intersect in no value. +func TestPendingKeeps_AnEntryKeptWholeTakesItsKeywordsReason(t *testing.T) { + t.Parallel() + paths := "paths:\n /a:\n get:\n parameters:\n" + + " - {name: r, in: query, schema: {allOf: [{type: string}, {xml: {name: a}}], xml: {name: b}}}\n" + + " - {name: x, in: query, schema: {type: string, xml: {name: b}}}\n" + + " responses: {'200': {description: ok}}\n" + doc, _ := parseVerified(t, admissionSpec("3.1.0", paths, + "P: {allOf: [{type: string, dependentRequired: {a: [z]}}], dependentRequired: {b: [z]}}", + "E: {allOf: [{type: string}, {dependentRequired: {a: [z]}}], dependentRequired: {b: [z]}}", + "E1: {allOf: [{type: string}, {dependentRequired: {a: [z]}}]}", + "PD: {allOf: [{type: string, default: a}], default: b}", + "ED: {allOf: [{type: string}, {default: a}], default: b}", + "D1: {allOf: [{type: string}, {default: a}]}", + "ET: {allOf: [{type: string, format: int64}, {pattern: a}], pattern: b}", + "T1: {allOf: [{type: string, format: int64}, {pattern: a}]}", + )) + alone := func(name, key string) ir.UnmodeledReason { + t.Helper() + return unmodeledEntry(t, typeByName(doc, name).Common().Unmodeled, key).Reason + } + for name, tc := range map[string]struct{ key, twin, twinKey string }{ + "P": {"openapi:allOf/0", "E1", "openapi:dependentRequired"}, + "E": {"openapi:allOf/1", "E1", "openapi:dependentRequired"}, + "PD": {"openapi:allOf/0", "D1", "openapi:default"}, + "ED": {"openapi:allOf/1", "D1", "openapi:default"}, + "ET": {"openapi:allOf/1", "T1", "openapi:pattern"}, + } { + assert.Equal(t, alone(tc.twin, tc.twinKey), alone(name, tc.key), name) + } + operation := operationAt(t, doc, "GET", "/a") + require.Len(t, operation.Params, 2) + byName := map[string]ir.Unmodeled{} + for _, param := range operation.Params { + byName[param.Name.Source] = param.Unmodeled + } + assert.Equal(t, unmodeledEntry(t, byName["x"], "openapi:schema/xml").Reason, + unmodeledEntry(t, byName["r"], "openapi:schema/allOf/1").Reason, "a parameter's xml") +} + +// TestPendingKeeps_AKeywordWrittenAlikeIsKeptAndReportedOnce holds one writing of +// a keyword two writers of one node give alike to one keep and one report: +// at a property, a parameter and a header as at a component, where the +// principal is kept whole for an extension the conjuncts give otherwise; a +// 3.0 exclusive flag with no bound; and a default two entries write. +func TestPendingKeeps_AKeywordWrittenAlikeIsKeptAndReportedOnce(t *testing.T) { + t.Parallel() + const ev, nt, xm = "{allOf: [{type: string, x-v: 1, x-k: 1}, {x-k: 2}], x-v: 1}", + "{allOf: [{type: string, not: {minLength: 1}, x-k: 1}, {x-k: 2}], not: {minLength: 1}}", + "{allOf: [{type: string, xml: {name: a}, x-k: 1}, {x-k: 2}], xml: {name: a}}" + paths := "paths:\n /a:\n get:\n parameters:\n" + + " - {name: q, in: query, schema: " + ev + "}\n" + + " - {name: r, in: query, schema: " + nt + "}\n" + + " - {name: s, in: query, schema: " + xm + "}\n" + + " responses:\n '200':\n description: ok\n headers:\n" + + " H: {schema: " + ev + "}\n" + doc, diags := parseVerified(t, admissionSpec("3.1.0", paths, + "TOP: "+ev, "PR: {type: object, properties: {p: "+ev+", n: "+nt+"}}")) + operation := operationAt(t, doc, "GET", "/a") + require.Len(t, operation.Params, 3) + params := map[string]ir.Unmodeled{} + for _, param := range operation.Params { + params[param.Name.Source] = param.Unmodeled + } + holder := requireModelOf(t, doc, "PR") + p, ok := propertyByWire(holder, "p") + require.True(t, ok) + n, ok := propertyByWire(holder, "n") + require.True(t, ok) + require.Len(t, operation.Responses, 1) + require.Len(t, operation.Responses[0].Headers, 1) + for _, tc := range []struct { + name, keyword string + kept ir.Unmodeled + at jsontext.Pointer + }{ + {"component", "x-v", typeByName(doc, "TOP").Common().Unmodeled, "/components/schemas/TOP"}, + {"property", "x-v", p.Unmodeled, "/components/schemas/PR/properties/p"}, + {"parameter", "x-v", params["q"], "/paths/~1a/get/parameters/0/schema"}, + {"header", "x-v", operation.Responses[0].Headers[0].Unmodeled, "/paths/~1a/get/responses/200/headers/H/schema"}, + {"property's not", "not", n.Unmodeled, "/components/schemas/PR/properties/n"}, + {"parameter's not", "not", params["r"], "/paths/~1a/get/parameters/1/schema"}, + {"parameter's xml", "xml", params["s"], "/paths/~1a/get/parameters/2/schema"}, + } { + assert.Len(t, keptValuesOf(t, tc.kept, tc.keyword), 1, "%s keeps %s once: %v", tc.name, tc.keyword, tc.kept) + assert.LessOrEqual(t, len(reportsNaming(diags, tc.at, tc.keyword)), 1, "%s reports %s at most once", tc.name, tc.keyword) + } + + doc, diags = parseVerified(t, admissionSpec("3.0.3", "", + "X: {allOf: [{type: number, exclusiveMinimum: true}], exclusiveMinimum: true}", + "XM: {allOf: [{type: number, exclusiveMaximum: true}], exclusiveMaximum: true}", + )) + for name, keyword := range map[string]string{"X": "exclusiveMinimum", "XM": "exclusiveMaximum"} { + assert.Len(t, keptValuesOf(t, typeByName(doc, name).Common().Unmodeled, keyword), 1, name) + assert.Len(t, reportsNaming(diags, jsontext.Pointer("/components/schemas/"+name), keyword), 1, "%s is warned of once", name) + } + + doc, diags = parseVerified(t, admissionSpec("3.1.0", "", "EE: {allOf: [{type: string}, {default: a}, {default: a}]}")) + assert.Equal(t, []string{`"a"`}, keptValuesOf(t, typeByName(doc, "EE").Common().Unmodeled, "default")) + assert.Len(t, reportsNaming(diags, "/components/schemas/EE", "default"), 1, "reported once") +} + +// TestPendingKeeps_AnEnumAConstPassesOverIsKeptAtEachConjunct holds the enum an inline +// principal's const passes over where another writer writes the const or an +// enum: kept, as written alone, at the plain key where it is the only enum, +// and beside the position's own under the principal's entry key. +func TestPendingKeeps_AnEnumAConstPassesOverIsKeptAtEachConjunct(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", + "Alone: {allOf: [{type: string, const: a, enum: [a, b]}]}", + "Both: {allOf: [{type: string, const: a, enum: [a, b]}], const: a, enum: [a, c]}", + "Const: {allOf: [{type: string, const: a, enum: [a, b]}], const: a}", + "Enum: {allOf: [{type: string, const: a, enum: [a, b]}], enum: [a, c]}", + "Entry: {allOf: [{type: string}, {const: a, enum: [a, b]}], const: a}", + "Prop: {type: object, properties: {p: {allOf: [{type: string, const: a, enum: [a, b]}], const: a}}}", + )) + alone := reportsNaming(diags, "/components/schemas/Alone", "enum") + require.Len(t, alone, 1) + for _, name := range []string{"Const", "Entry"} { + kept := typeByName(doc, name).Common().Unmodeled + assert.JSONEq(t, `["a","b"]`, string(unmodeledEntry(t, kept, "openapi:enum").Value), name) + reports := reportsNaming(diags, jsontext.Pointer("/components/schemas/"+name), "enum") + if assert.Len(t, reports, 1, name) { + assert.Equal(t, alone[0].Message, reports[0].Message, name) + } + } + holder := requireModelOf(t, doc, "Prop") + p, ok := propertyByWire(holder, "p") + require.True(t, ok) + held := p.Unmodeled + if literal, isNode := doc.Types[p.Type.Target]; isNode && len(literal.Common().Unmodeled) > 0 { + held = literal.Common().Unmodeled + } + assert.Equal(t, []string{`["a","b"]`}, keptValuesOf(t, held, "enum"), "at a property") + for name, position := range map[string]string{"Both": `["a","c"]`, "Enum": `["a","c"]`} { + kept := typeByName(doc, name).Common().Unmodeled + assert.JSONEq(t, position, string(unmodeledEntry(t, kept, "openapi:enum").Value), "%s: the position's", name) + var principal map[string]any + require.NoError(t, json.Unmarshal(unmodeledEntry(t, kept, "openapi:allOf/0").Value, &principal), name) + assert.Equal(t, []any{"a", "b"}, principal["enum"], "%s: the principal's", name) + } +} + +// TestPendingKeeps_ANullOnAKeyNoDialectDefinesIsAValue holds a null written on a key +// no dialect defines as a value another writer's collides with, in either +// order of two entries and at a property: no internal error, each value kept +// once, the position's under the plain key and an entry's under its entry key, +// and two entries' each under its own, with one report per value kept. +func TestPendingKeeps_ANullOnAKeyNoDialectDefinesIsAValue(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.1.0", "", + "Z1: {allOf: [{type: string, foo: null}], foo: 1}", + "ZF: {allOf: [{type: string, foo: 2}], foo: null}", + "ZE: {allOf: [{type: string, foo: null}, {foo: 2}]}", + "ZER: {allOf: [{type: string, foo: 2}, {foo: null}]}", + "ZP: {type: object, properties: {p: {allOf: [{type: string, foo: null}], foo: 1}}}", + )) + assertNoErrorDiags(t, diags) + holder := requireModelOf(t, doc, "ZP") + p, ok := propertyByWire(holder, "p") + require.True(t, ok) + for _, tc := range []struct { + name, plain string + values []string + kept ir.Unmodeled + at jsontext.Pointer + }{ + {"Z1", "1", []string{"1", "null"}, typeByName(doc, "Z1").Common().Unmodeled, "/components/schemas/Z1"}, + {"ZF", "null", []string{"2", "null"}, typeByName(doc, "ZF").Common().Unmodeled, "/components/schemas/ZF"}, + {"ZE", "", []string{"2", "null"}, typeByName(doc, "ZE").Common().Unmodeled, "/components/schemas/ZE"}, + {"ZER", "", []string{"2", "null"}, typeByName(doc, "ZER").Common().Unmodeled, "/components/schemas/ZER"}, + {"ZP.p", "1", []string{"1", "null"}, p.Unmodeled, "/components/schemas/ZP/properties/p"}, + } { + values := keptValuesOf(t, tc.kept, "foo") + assert.Equal(t, tc.values, values, "%s keeps each value once", tc.name) + plain, hasPlain := tc.kept["openapi:foo"] + if tc.plain == "" { + assert.False(t, hasPlain, "%s: no writer is outermost, so no plain key", tc.name) + } else if assert.True(t, hasPlain, tc.name) { + assert.Equal(t, tc.plain, string(plain.Value), "%s: the plain key holds the position's", tc.name) + } + assert.Len(t, reportsNaming(diags, tc.at, "foo"), len(values), "%s: one report per value kept", tc.name) + } +} diff --git a/compilers/openapi/e2e/pointer_spelled_test.go b/compilers/openapi/e2e/pointer_spelled_test.go index 6452cb59d..5051f4429 100644 --- a/compilers/openapi/e2e/pointer_spelled_test.go +++ b/compilers/openapi/e2e/pointer_spelled_test.go @@ -6,11 +6,14 @@ package e2e_test import ( "cmp" "maps" + "os" "runtime" + "runtime/debug" "slices" "strconv" "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -20,6 +23,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/compilers/openapi/internal/reftable" "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/internal/exectest" ) // spelledHop is one step from an object of the rule table to an object it @@ -149,8 +153,8 @@ func spelledShapes(shape specrules.Shape, all bool) map[string]string { } // spelledLeaves lists values a raw value holds many of, by name: the first -// three wherever one stands, the rest too where all is set. Each is one a -// reader could place a finding at, or read otherwise than as written. +// three wherever one is, the rest too where all is set. Each is one a reader +// could place a finding at, or read otherwise than as written. func spelledLeaves(all bool) map[string]string { leaves := map[string]string{"a key written twice": "{a: 1, a: 2}", "a merge": "{<<: {a: 1}, a: 2}", "a mapping": "{a: 1, b: 2}"} if !all { @@ -262,16 +266,34 @@ const ( // last the one whose cases are widened. var spelledMinors = []string{"3.0.3", "3.1.1", "3.2.0"} +// spelledGCPercent is the pace the child collects at (debug.SetGCPercent). +const spelledGCPercent = 400 + +// spelledAlone names the variable telling a run of this test binary that it is +// the child TestCompile_SpellsNoPointerTheNamedTotalLeavesOut starts. +const spelledAlone = "MORPHIC_E2E_SPELLED_ALONE" + // TestCompile_SpellsNoPointerTheNamedTotalLeavesOut holds a whole compile to // the total the pointer bound's second weighing takes // (docs/compilers/openapi.md#source-budgets): for each case spelledCases // lists, what a compile allocates more for a longer key is within a constant // of what the total grows by, so no walk spells a pointer at each entry of a // value the total counts by its root. A short run holds the last minor alone. -// It does not run in parallel, since the count is process-wide. +// The count is process-wide, so the cases run in a child running nothing else, +// and the test runs in parallel with the rest of the package. func TestCompile_SpellsNoPointerTheNamedTotalLeavesOut(t *testing.T) { + if os.Getenv(spelledAlone) == "" { + t.Parallel() + runAloneInChild(t, spelledAlone) + return + } previous := runtime.GOMAXPROCS(1) t.Cleanup(func() { runtime.GOMAXPROCS(previous) }) + // The count is of bytes allocated, which collecting less often moves only + // by what a collection empties, as a pool, alike for both compiles of a + // case. The child's heap stays small, so it collects at a fourth the pace. + previousPercent := debug.SetGCPercent(spelledGCPercent) + t.Cleanup(func() { debug.SetGCPercent(previousPercent) }) for i, version := range spelledMinors { last := i == len(spelledMinors)-1 if last || !testing.Short() { @@ -280,6 +302,24 @@ func TestCompile_SpellsNoPointerTheNamedTotalLeavesOut(t *testing.T) { } } +// runAloneInChild runs t's test in a child, a run of this test binary told by +// the variable named alone that it is the child, and fails t where the child +// does not report the test passed. The child takes -test.short from this run, +// and times out where this run does, with its own stacks. +func runAloneInChild(t *testing.T, alone string) { + t.Helper() + var timeout time.Duration // none, as this run has none + if deadline, bounded := t.Deadline(); bounded { + timeout = time.Until(deadline) + } + args := []string{"-test.run=^" + t.Name() + "$", "-test.v", "-test.short=" + strconv.FormatBool(testing.Short()), + "-test.timeout=" + timeout.String()} + out, err := exectest.Command(t.Context(), t, []string{alone + "=1"}, os.Args[0], args...).CombinedOutput() + require.NoError(t, err, "the child running %s failed:\n%s", t.Name(), out) + // A pattern naming no test passes too, having run nothing. + require.Contains(t, string(out), "--- PASS: "+t.Name()+" ", "the child ran %s:\n%s", t.Name(), out) +} + // spellsWithinTheTotal holds each of cases to what its total grows by, the // fewest of three compiles where one is past. A case whose total is not taken // is left to the first total. diff --git a/compilers/openapi/e2e/pointer_tokens_test.go b/compilers/openapi/e2e/pointer_tokens_test.go index e3adfdeb6..33c17e5a9 100644 --- a/compilers/openapi/e2e/pointer_tokens_test.go +++ b/compilers/openapi/e2e/pointer_tokens_test.go @@ -57,7 +57,7 @@ components: } // assertAliases asserts the component schema name lowered to an alias over -// target: what the position's $ref came to stand for. +// target: what the position's $ref came to name. func assertAliases(t *testing.T, doc *ir.Document, name string, target ir.TypeID, message string) { t.Helper() assert.Equal(t, target, useTarget(t, doc, name), message) diff --git a/compilers/openapi/e2e/standing_shape_test.go b/compilers/openapi/e2e/position_shape_test.go similarity index 86% rename from compilers/openapi/e2e/standing_shape_test.go rename to compilers/openapi/e2e/position_shape_test.go index 11b75e43e..c1b00d5be 100644 --- a/compilers/openapi/e2e/standing_shape_test.go +++ b/compilers/openapi/e2e/position_shape_test.go @@ -43,13 +43,13 @@ var shapeCases = []shapeCase{ {"$ref on an entry", "{allOf: [{$ref: '#/components/schemas/L'}, {minLength: 1}]}", "/allOf/1", ""}, } -// TestStandingShape_AReportNamesWhatAnInlinePrincipalLoweredTo pins the report +// TestPositionShape_AReportNamesWhatAnInlinePrincipalLoweredTo pins the report // of a keyword kept beside an inline allOf principal, at a component and a // property, in both declaration orders: it names what the position lowered // to as the same schema written flat does, and only a $ref principal's says // the position lowered to a use of one of its conjuncts // (docs/compilers/openapi.md#allof-refinement). -func TestStandingShape_AReportNamesWhatAnInlinePrincipalLoweredTo(t *testing.T) { +func TestPositionShape_AReportNamesWhatAnInlinePrincipalLoweredTo(t *testing.T) { t.Parallel() lines := []string{" S: {type: string}", " L: {type: array, items: {type: string}}"} for i, tc := range shapeCases { @@ -102,26 +102,27 @@ func shapesReported(t *testing.T, lines []string) map[string]string { return out } -// TestStandingShape_ConjunctsSharingNoValueNameWhatThePositionLoweredTo pins -// the warning of a union beside an allOf sharing no kind with its principal: -// it names the node an inline principal stands as at the position, and a -// use of one of its conjuncts only for a $ref principal +// TestPositionShape_ConjunctsSharingNoValueNameWhatThePositionLoweredTo pins +// the warning of a union beside an allOf sharing no kind with its principal: it +// names the node an inline principal lowers as at the position, and a use of +// one of its conjuncts only for a $ref principal // (docs/compilers/openapi.md#allof-disjoint-conjuncts). -func TestStandingShape_ConjunctsSharingNoValueNameWhatThePositionLoweredTo(t *testing.T) { +func TestPositionShape_ConjunctsSharingNoValueNameWhatThePositionLoweredTo(t *testing.T) { t.Parallel() const union = "oneOf: [{type: integer}, {type: boolean}]" _, diags := parseFull(t, openapitest.ComponentSpec(" S: {type: string}\n"+ " L: {allOf: [{type: array, items: {type: string}}], "+union+"}\n"+ " R: {allOf: [{$ref: '#/components/schemas/S'}], "+union+"}\n")) want := map[string]string{ - "/components/schemas/L": `which a node of kind "list" cannot state`, - "/components/schemas/R": "which a use of one of its allOf conjuncts cannot state", + "/components/schemas/L": `a node of kind "list", its oneOf kept verbatim under Unmodeled`, + "/components/schemas/R": "a use of one of its allOf conjuncts, its oneOf kept verbatim under Unmodeled", } got := map[string]string{} for _, diagnostic := range diags { - if diagnostic.Code == diag.DegradedConstruct && strings.Contains(diagnostic.Message, "share no value") { - _, tail, _ := strings.Cut(diagnostic.Message, "so no instance satisfies this schema, ") - got[string(diagnostic.Provenance.Pointer)] = tail + if diagnostic.Code == diag.UnsatisfiableSchema && strings.Contains(diagnostic.Message, "no value satisfies") { + _, tail, _ := strings.Cut(diagnostic.Message, "; lowered as ") + shape, _, _ := strings.Cut(tail, " — ") + got[string(diagnostic.Provenance.Pointer)] = shape } } assert.Equal(t, want, got) diff --git a/compilers/openapi/e2e/principal_apart_test.go b/compilers/openapi/e2e/principal_apart_test.go index ef2156ef0..b1d5902e4 100644 --- a/compilers/openapi/e2e/principal_apart_test.go +++ b/compilers/openapi/e2e/principal_apart_test.go @@ -35,8 +35,10 @@ type apartCase struct { var apartCases = []apartCase{ {"one keyword", "X1: {allOf: [{type: string, minimum: 1}], minimum: 2}", componentID("X1"), map[string]string{"minimum": "2"}, "openapi:allOf/0", map[string]any{"minimum": 1.0}, "/components/schemas/X1/allOf/0"}, + // A number as text holds its bounds verbatim, and the two conjuncts + // intersect, so the node keeps the value they intersect in alone. {"a number as text", "X2: {allOf: [{type: string, format: double, minimum: 1}], minimum: 2}", componentID("X2"), - map[string]string{"minimum": "2"}, "openapi:allOf/0", map[string]any{"minimum": 1.0}, "/components/schemas/X2/allOf/0"}, + map[string]string{"minimum": "2"}, "", nil, ""}, {"two keywords", "X3: {allOf: [{type: string, minimum: 1, maximum: 5}], minimum: 2, maximum: 6}", componentID("X3"), map[string]string{"minimum": "2", "maximum": "6"}, "openapi:allOf/0", map[string]any{"minimum": 1.0, "maximum": 5.0}, "/components/schemas/X3/allOf/0"}, @@ -58,10 +60,12 @@ var apartCases = []apartCase{ {"an array's items", "I: {type: array, items: {allOf: [{type: string, minimum: 1}], minimum: 2}}", "type/anonymous/components/schemas/I/items", map[string]string{"minimum": "2"}, "openapi:allOf/0", map[string]any{"minimum": 1.0}, "/components/schemas/I/items/allOf/0"}, + // A draft's exclusive flag written false equals the keyword left out, so + // the principal's false is no value colliding with the position's true. {"a draft's exclusive flag", "D: {$id: 'https://example.com/d', $schema: " + draft04 + - ", allOf: [{type: string, minimum: 1, exclusiveMinimum: true}], minimum: 2, exclusiveMinimum: false}", componentID("D"), - map[string]string{"minimum": "2", "exclusiveMinimum": "false"}, "openapi:allOf/0", - map[string]any{"minimum": 1.0, "exclusiveMinimum": true}, "/components/schemas/D/allOf/0"}, + ", allOf: [{type: string, minimum: 1, exclusiveMinimum: false}], minimum: 2, exclusiveMinimum: true}", componentID("D"), + map[string]string{"minimum": "2", "exclusiveMinimum": "true"}, "openapi:allOf/0", + map[string]any{"minimum": 1.0}, "/components/schemas/D/allOf/0"}, } // TestPrincipalApart_AKeywordThePrincipalAndThePositionKeepHoldsBoth pins a @@ -131,8 +135,52 @@ func TestPrincipalApart_AKeywordThePrincipalAndThePositionKeepHoldsBoth(t *testi } } +// TestPrincipalApart_AnExclusiveFlagSettlesWithItsBound pins a boolean +// exclusive flag, at 3.0 and under draft 4, which modifies the bound beside +// it: the principal's true is kept with its own bound, apart from the outer +// bound, so the plain keys read alone state the position's inclusive bound, +// and the position's false says nothing, beside a principal or alone. Under +// which entry key the pair is kept is not pinned here. +func TestPrincipalApart_AnExclusiveFlagSettlesWithItsBound(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ name, version, dialect, bound, flag string }{ + {"3.0 minimum", "3.0.3", "", "minimum", "exclusiveMinimum"}, + {"3.0 maximum", "3.0.3", "", "maximum", "exclusiveMaximum"}, + {"draft-04 minimum", "3.1.0", "http://json-schema.org/draft-04/schema#", "minimum", "exclusiveMinimum"}, + {"draft-04 maximum", "3.1.0", "http://json-schema.org/draft-04/schema#", "maximum", "exclusiveMaximum"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, inDialect(admissionSpec(tc.version, "", + "D: {allOf: [{type: string, "+tc.bound+": 1, "+tc.flag+": true}], "+tc.bound+": 2, "+tc.flag+": false}", + "L: {type: string, "+tc.bound+": 2, "+tc.flag+": false}", + ), tc.dialect)) + openapitest.RequireNoErrorDiags(t, diags) + held := typeByName(doc, "D").Common().Unmodeled + assert.Equal(t, "2", string(unmodeledEntry(t, held, "openapi:"+tc.bound).Value), "the plain key holds the outer bound") + assert.NotContains(t, held, "openapi:"+tc.flag, "no flag beside the outer bound: the plain keys mean the inclusive 2") + pairs := 0 + for key, entry := range held { + var whole map[string]any + if key == "openapi:"+tc.bound || json.Unmarshal(entry.Value, &whole) != nil { + continue + } + assert.NotEqual(t, false, whole[tc.flag], "%s holds no false", key) + if whole[tc.flag] == true { + assert.Equal(t, 1.0, whole[tc.bound], "%s keeps the true with its own bound", key) + pairs++ + } + } + assert.Equal(t, 1, pairs, "the principal's pair is kept once, whole: %v", held) + lone := typeByName(doc, "L").Common().Unmodeled + assert.NotContains(t, lone, "openapi:"+tc.flag, "a lone false says nothing") + assert.Equal(t, "2", string(unmodeledEntry(t, lone, "openapi:"+tc.bound).Value)) + }) + } +} + // TestPrincipalApart_AParameterSchemaHoldsBoth pins the rule at a parameter's -// schema, whose node stands for the parameter. +// schema, whose node represents the parameter. func TestPrincipalApart_AParameterSchemaHoldsBoth(t *testing.T) { t.Parallel() doc, diags := parseFull(t, "openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths:\n /a:\n get:\n"+ @@ -144,14 +192,17 @@ func TestPrincipalApart_AParameterSchemaHoldsBoth(t *testing.T) { assert.JSONEq(t, `{"minimum":1}`, string(unmodeledEntry(t, held, "openapi:allOf/0").Value)) } -// TestPrincipalApart_AReportNamesTheEntryWhereACarrierKeepsIt pins the report of -// a principal's keyword kept under its entry's key where the position owns no -// node: the parameter keeps it beneath its schema's scope, so the report names -// the entry's path, which that key ends in, and no key the parameter lacks. +// TestPrincipalApart_AReportNamesTheEntryWhereACarrierKeepsIt pins the report +// of a principal's keyword kept under its entry's key where the position owns +// no node: the parameter keeps it beneath its schema's scope, so the report +// names the entry's path, which that key ends in, and no key the parameter +// lacks. The keyword is one no dialect defines, which folds nowhere, so the +// node's pending keeps settle the two conjuncts' values; a keyword that folds +// is compared by its conjuncts. func TestPrincipalApart_AReportNamesTheEntryWhereACarrierKeepsIt(t *testing.T) { t.Parallel() doc, diags := parseFull(t, "openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths:\n /a:\n get:\n"+ - " parameters:\n - {name: q, in: query, schema: {allOf: [{type: integer, contentEncoding: a}], contentEncoding: b}}\n"+ + " parameters:\n - {name: q, in: query, schema: {allOf: [{type: integer, foo: a}], foo: b}}\n"+ " responses: {'204': {description: ok}}\n") openapitest.RequireNoErrorDiags(t, diags) raw, err := json.Marshal(doc, json.Deterministic(true)) diff --git a/compilers/openapi/e2e/promotion_test.go b/compilers/openapi/e2e/promotion_test.go index e6f22eb52..abb523755 100644 --- a/compilers/openapi/e2e/promotion_test.go +++ b/compilers/openapi/e2e/promotion_test.go @@ -164,7 +164,7 @@ func assertMemberKeys(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) { assert.Equal(t, info, diagsAt(diags, "openapi/degraded-construct", "/paths/~1members/patch/x-forge-sunset/date"), "located at the member") assert.Equal(t, info, diagsAt(diags, "openapi/degraded-construct", - "/paths/~1members/delete/x-stainless-deprecation-message"), "the key that lost") + "/paths/~1members/delete/x-stainless-deprecation-message"), "the key passed over") } // assertEnumOpenness is the corpus row for GitHub #427 and the matrix's @@ -536,9 +536,9 @@ paths: ` alpha, zulu := openapi.ExtensionSource{Key: "x-alpha-msg"}, openapi.ExtensionSource{Key: "x-zulu-msg"} for _, tc := range []struct { - order []openapi.ExtensionSource - want string - loser string + order []openapi.ExtensionSource + want string + passedOver string }{ {[]openapi.ExtensionSource{alpha, zulu}, "FROM-ALPHA", "/paths/~1x/get/x-zulu-msg"}, {[]openapi.ExtensionSource{zulu, alpha}, "FROM-ZULU", "/paths/~1x/get/x-alpha-msg"}, @@ -557,7 +557,7 @@ paths: require.True(t, ok) require.NotNil(t, operation.Deprecation) assert.Equal(t, tc.want, operation.Deprecation.Message) - assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/degraded-construct", tc.loser)) + assert.Equal(t, []ir.Severity{ir.SeverityInfo}, diagsAt(diags, "openapi/degraded-construct", tc.passedOver)) assert.Len(t, diags, 1) }) } diff --git a/compilers/openapi/e2e/promotion_usesite_test.go b/compilers/openapi/e2e/promotion_usesite_test.go index 27c6430fc..263bd7b00 100644 --- a/compilers/openapi/e2e/promotion_usesite_test.go +++ b/compilers/openapi/e2e/promotion_usesite_test.go @@ -1,13 +1,13 @@ // Copyright (c) 2026 dexpace. // Licensed under the MIT License. See LICENSE in the repository root for details. -// This file covers what a promotion reads through a $ref. Annotations merge from -// a $ref's target onto the property, parameter or header naming it, field by -// field and by one rule at every carrier, so a fact a key states on the target -// reaches the use site as the keyword's fact does. The reading happens at three -// construction sites, which is why each case below runs at all three, and a -// parameter and a header elect their schema from two spellings, which is why it -// runs at both of those too. +// This file covers what a promotion reads through a $ref. Annotations merge +// from a $ref's target onto the property, parameter or header naming it, field +// by field and by one rule at every carrier, so a fact a key states on the +// target reaches the use site as the keyword's fact does. The reading happens +// at three construction sites, which is why each case below runs at all three, +// and a parameter and a header choose their schema from two spellings, which is +// why it runs at both of those too. package e2e_test // external test package — exercises only the public API import ( @@ -309,7 +309,7 @@ const decoratedComponents = ` OldObject: {type: object, deprecated: true, x-d DatedObject: {type: object, x-sunset: "2032-01-01"} ` -// TestPromotion_ADecoratorMatchesTheRefItStandsFor pins the two spellings of one +// TestPromotion_ADecoratorMatchesTheRefItWraps pins the two spellings of one // use to one answer. A 3.0 document annotates a use by wrapping the $ref in an // allOf. Over a target admitting no object that is a refinement, whose carriers // read the target as the $ref's do. Over an object it is a decorator, which an @@ -317,7 +317,7 @@ const decoratedComponents = ` OldObject: {type: object, deprecated: true, x-d // $ref, the same conjunction, lowers to the same decorator, which holds the // deprecation, its mark and the kept member key in both spellings (GitHub // #1220, #1258, #2024). -func TestPromotion_ADecoratorMatchesTheRefItStandsFor(t *testing.T) { +func TestPromotion_ADecoratorMatchesTheRefItWraps(t *testing.T) { t.Parallel() for _, tc := range []struct { name, target, annotation string @@ -492,19 +492,19 @@ func assertPromotionsAgree(t *testing.T, a, b *ir.Document) { } } -// TestPromotion_AContentCarrierReadsTheEntryItElects ties what a carrier's +// TestPromotion_AContentCarrierReadsTheEntryItChooses ties what a carrier's // promotion reads to the entry docs/compilers/openapi.md#content-parameters -// elects from a content map holding several: the lowest key, not the first +// chooses from a content map holding several: the lowest key, not the first // declared. Such a map is invalid and draws an error, but the carrier still // lowers one entry's type, and its promoted facts must come from that entry. -func TestPromotion_AContentCarrierReadsTheEntryItElects(t *testing.T) { +func TestPromotion_AContentCarrierReadsTheEntryItChooses(t *testing.T) { t.Parallel() cases := []struct { name string plain, json string secret bool }{ - {name: "the elected entry names the target", plain: "Plain", json: "Tok", secret: true}, + {name: "the chosen entry names the target", plain: "Plain", json: "Tok", secret: true}, {name: "the other entry names the target", plain: "Tok", json: "Plain", secret: false}, } for _, tc := range cases { diff --git a/compilers/openapi/e2e/recursive_scope_reach_test.go b/compilers/openapi/e2e/recursive_scope_reach_test.go index 15188e52a..deef6d14c 100644 --- a/compilers/openapi/e2e/recursive_scope_reach_test.go +++ b/compilers/openapi/e2e/recursive_scope_reach_test.go @@ -17,7 +17,7 @@ import ( const recDialect = " $schema: 'https://json-schema.org/draft/2019-09/schema'\n" // recTree and recChain are the two anchored resources of a document no -// reference joins: each $recursiveRef can only come back to its own. +// reference connects: each $recursiveRef can only come back to its own. const ( recTree = " Tree:\n" + recDialect + " $id: 'https://example.com/tree'\n $recursiveAnchor: true\n type: object\n" + @@ -29,7 +29,7 @@ const ( recTreePointer = "/components/schemas/Tree/properties/children/items/$recursiveRef" recChainPointer = "/components/schemas/Chain/items/$recursiveRef" - // recReaches is the verdict for a reference another anchored resource + // recReaches is the answer for a reference another anchored resource // reaches the target of. recReaches = "is also declared in a schema resource that reaches this one, so the target depends on the evaluation path" ) @@ -46,22 +46,18 @@ func recKept(diags []ir.Diagnostic, pointer string) []ir.Diagnostic { return out } -// recElementBase returns the type the scalar at id, a list's element, is based -// on. -func recElementBase(t *testing.T, doc *ir.Document, list ir.TypeID) ir.TypeID { +// recElement returns the type the list at id names as its element. +func recElement(t *testing.T, doc *ir.Document, list ir.TypeID) ir.TypeID { t.Helper() irList, ok := doc.Types[list].(*ir.List) require.True(t, ok, "%s is a list, not %T", list, doc.Types[list]) - element, ok := doc.Types[irList.ElementType.Target].(*ir.Scalar) - require.True(t, ok, "its element is a scalar, not %T", doc.Types[irList.ElementType.Target]) - require.NotNil(t, element.Base) - return element.Base.Target + return irList.ElementType.Target } // TestCompile_ARecursiveRefNoOtherAnchoredResourceReachesExpands pins that two // anchored resources neither of which reaches the other each expand their own // reference, as either does alone: no path can make a target of one of them -// the other. +// the other. Each list names its expansion as its element, as one of a $ref. func TestCompile_ARecursiveRefNoOtherAnchoredResourceReachesExpands(t *testing.T) { t.Parallel() for name, schemas := range map[string]string{"Tree first": recTree + recChain, "Chain first": recChain + recTree} { @@ -73,14 +69,8 @@ func TestCompile_ARecursiveRefNoOtherAnchoredResourceReachesExpands(t *testing.T assert.Empty(t, recKept(diags, recTreePointer), name) assert.Empty(t, recKept(diags, recChainPointer), name) assert.Equal(t, componentID("Tree"), - recElementBase(t, doc, "type/anonymous/components/schemas/Tree/properties/children"), name) - - chain, ok := doc.Types[componentID("Chain")].(*ir.List) - require.True(t, ok, name) - element, ok := doc.Types[chain.ElementType.Target].(*ir.Scalar) - require.True(t, ok, name) - require.NotNil(t, element.Base, name) - assert.Equal(t, componentID("Chain"), element.Base.Target, name) + recElement(t, doc, "type/anonymous/components/schemas/Tree/properties/children"), name) + assert.Equal(t, componentID("Chain"), recElement(t, doc, componentID("Chain")), name) } } @@ -112,8 +102,8 @@ func TestCompile_ARecursiveRefAnotherAnchoredResourceReachesIsKept(t *testing.T) } // TestCompile_ARecursiveRefAnotherDocumentsAnchoredResourceReachesIsKept pins -// the same verdict where the reaching resource is in another document, which -// is read only because the source names it: with that reference removed the +// the same answer where the reaching resource is in another document, which is +// read only because the source names it: with that reference removed the // document is not read and the reference expands. func TestCompile_ARecursiveRefAnotherDocumentsAnchoredResourceReachesIsKept(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/e2e/ref_conjunction_disjoint_set_test.go b/compilers/openapi/e2e/ref_conjunction_disjoint_set_test.go index b23a68969..b8c6d9696 100644 --- a/compilers/openapi/e2e/ref_conjunction_disjoint_set_test.go +++ b/compilers/openapi/e2e/ref_conjunction_disjoint_set_test.go @@ -4,70 +4,122 @@ package e2e_test import ( + "strings" "testing" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) -// fourSpellings are the four ways a schema writes keywords k beside a $ref to -// T: beside it, beside an allOf of it, on its allOf entry, and on an entry of -// their own. -func fourSpellings(k string) map[string]string { - ref := "$ref: '#/components/schemas/T'" - return map[string]string{ - "beside the $ref": "{" + ref + ", " + k + "}", - "beside an allOf": "{allOf: [{" + ref + "}], " + k + "}", - "on its entry": "{allOf: [{" + ref + ", " + k + "}]}", - "on an entry next": "{allOf: [{" + ref + "}, {" + k + "}]}", - } -} +// besideRefSpellings are the ways a schema writes keywords k beside a $ref to +// T, in every placement openapitest.Spellings gives. +func besideRefSpellings(k string) map[string]string { return openapitest.Spellings(refTo("T"), k) } -// requireOneDocument holds the four spellings of k beside a $ref to the -// target, at each of the sites given, to one document up to the entries' -// pointers. -func requireOneDocument(t *testing.T, sites []conjSite, target, k string) { +// requireOneDocument holds the four spellings of k beside a $ref to the target, +// at each of the sites given, to one document up to the entries' pointers and, +// where chosen names a keyword, up to the key the value set it writes is kept +// under: its own beside the $ref or the allOf, its entry's on an entry. +func requireOneDocument(t *testing.T, sites []conjSite, target, k, chosen string) { t.Helper() - spellings := fourSpellings(k) + spellings := besideRefSpellings(k) + written := func(site conjSite, schema string) entryWritten { + doc, diags := compileAnnotationSpec(t, "conjunction", site.write("3.1.0", schema, target)) + require.NotNil(t, doc) + if chosen != "" { + keptSetAsBeside(t, doc, chosen) + } + return writtenOf(t, site, doc, diags) + } for _, site := range sites { - want := writtenAnyway(t, site, target, spellings["beside the $ref"]) + want := written(site, spellings["Flat"]) for name, schema := range spellings { - got := writtenAnyway(t, site, target, schema) + got := written(site, schema) assert.Empty(t, cmp.Diff(want, got, cmp.AllowUnexported(entryWritten{})), "%s, %s", site.name, name) } } } -// disjointSets are value keywords that leave their conjunction with a $ref to -// T no value, each beside the target it is written over. -var disjointSets = map[string]struct{ target, keywords string }{ - "a const and an enum sharing no value": {"T: {type: string}", "const: z, enum: [a]"}, - "a const outside its type": {"T: {type: string}", "type: integer, const: z"}, - "an enum outside its type": {"T: {type: string}", "type: integer, enum: [a]"}, - "two enums sharing no member": {"T: {type: string, enum: [a]}", "enum: [b]"}, - "a const and an enum over an object": {"T: {type: object}", "const: z, enum: [a]"}, - "a const and an enum over a union": {"T: {oneOf: [{type: string}, {type: integer}]}", "const: 1, enum: [a]"}, +// disjointSets are value keywords that leave their conjunction with a $ref to T +// no value, each beside the target it is written over. Where the keywords' +// value sets share no member, chosen names the one the closed empty Enum +// chooses, which it keeps beside every other set; bottom says they are a const +// and an enum of two value types, which no Enum types. +var disjointSets = map[string]struct { + target, keywords, chosen string + bottom bool +}{ + "a const and an enum sharing no value": {"T: {type: string}", "const: z, enum: [a]", "const", false}, + "a const outside its type": {"T: {type: string}", "type: integer, const: z", "", false}, + "an enum outside its type": {"T: {type: string}", "type: integer, enum: [a]", "", false}, + "two enums sharing no member": {"T: {type: string, enum: [a]}", "enum: [b]", "enum", false}, + "a const and an enum over an object": {"T: {type: object}", "const: z, enum: [a]", "", false}, + "a const and an enum over a union": {"T: {oneOf: [{type: string}, {type: integer}]}", "const: 1, enum: [a]", "", true}, "a const beside a union of another kind": {"T: {oneOf: [{type: string}, {type: integer}]}", - "const: 1, oneOf: [{type: string}, {type: boolean}]"}, + "const: 1, oneOf: [{type: string}, {type: boolean}]", "", false}, "an enum beside a union of another kind": {"T: {oneOf: [{type: string}, {type: integer}]}", - "enum: [1], oneOf: [{type: string}, {type: boolean}]"}, + "enum: [1], oneOf: [{type: string}, {type: boolean}]", "", false}, +} + +// requireTheBottomInEverySpelling holds each of the four spellings of keywords +// beside a $ref to target to the bottom: a closed Model with no member keeping +// the const and the enum once each, with the one warning at the position. +func requireTheBottomInEverySpelling(t *testing.T, name, target, keywords string) { + t.Helper() + for spelling, schema := range besideRefSpellings(keywords) { + doc, diags := compileUnrefused(t, conjSites[0].write("3.1.0", schema, target)) + model, ok := kindNode(t, doc, componentID("Use")).(*ir.Model) + if !assert.True(t, ok, "%s, %s: the bottom", name, spelling) { + continue + } + assert.Empty(t, model.Properties, "%s, %s", name, spelling) + assert.Equal(t, ir.AdditionalClosed, model.Additional, "%s, %s", name, spelling) + for _, keyword := range []string{"const", "enum"} { + assert.Equal(t, 1, keptNaming(doc, keyword), "%s, %s: %s is kept once", name, spelling, keyword) + } + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, diagsAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Use"), + "%s, %s", name, spelling) + } } // TestRefConjunction_AnEntrysValueSetLowersAsBesideItsRef holds the four -// spellings of value keywords leaving the conjunction no value beside a $ref -// to one document at every site: the value set the dispatch among competing -// keywords picks, never a Model, the rest kept and reported alike. +// spellings of value keywords leaving the conjunction no value beside a $ref to +// one document at every site: the value set the dispatch among competing +// keywords picks, never a Model, the rest kept and reported alike. Value sets +// sharing no member are the closed empty Enum keeping each set once, the chosen +// one under the key it is written at, so the spellings differ by that key +// alone. A const and an enum of two value types are the bottom, which keeps +// each keyword where it is written. func TestRefConjunction_AnEntrysValueSetLowersAsBesideItsRef(t *testing.T) { t.Parallel() for name, tc := range disjointSets { - requireOneDocument(t, conjSites, tc.target, tc.keywords) - doc, _ := compileUnrefused(t, conjSites[0].write("3.1.0", fourSpellings(tc.keywords)["on an entry next"], tc.target)) - switch node := kindNode(t, doc, componentID("Use")).(type) { - case *ir.Literal, *ir.Enum: - default: - t.Errorf("%s: the entry lowers to %T, not the value set elected", name, node) + if tc.bottom { + requireTheBottomInEverySpelling(t, name, tc.target, tc.keywords) + continue + } + requireOneDocument(t, conjSites, tc.target, tc.keywords, tc.chosen) + for spelling, schema := range besideRefSpellings(tc.keywords) { + doc, _ := compileUnrefused(t, conjSites[0].write("3.1.0", schema, tc.target)) + switch node := kindNode(t, doc, componentID("Use")).(type) { + case *ir.Enum: + if tc.chosen != "" { + assert.Empty(t, node.Members, "%s, %s: the sets share no member", name, spelling) + assert.True(t, node.Closed, "%s, %s", name, spelling) + for _, keyword := range []string{"const", "enum"} { + if strings.Contains(tc.keywords, keyword+":") { + assert.Equal(t, 1, keptNaming(doc, keyword), "%s, %s: %s is kept once", name, spelling, keyword) + } + } + } + case *ir.Literal: + assert.Empty(t, tc.chosen, "%s, %s: sets sharing no member are no Literal", name, spelling) + default: + t.Errorf("%s, %s: the entry lowers to %T, not the value set chosen", name, spelling, node) + } } } } diff --git a/compilers/openapi/e2e/ref_conjunction_entry_test.go b/compilers/openapi/e2e/ref_conjunction_entry_test.go index b97745bc6..2f5adf5ba 100644 --- a/compilers/openapi/e2e/ref_conjunction_entry_test.go +++ b/compilers/openapi/e2e/ref_conjunction_entry_test.go @@ -46,11 +46,6 @@ var entryGridTargets = map[string]string{ "union": "T: {oneOf: [{type: string}, {type: integer}]}", } -// saidByTarget are the cells whose keyword the target already says: a string -// conjoined with a oneOf of a string and an integer admits what the string -// does, so the use is the reference, as written alone. -var saidByTarget = map[[2]string]bool{{"string", "oneOf"}: true} - // refEntrySpellings are the four ways an allOf writes a $ref and keywords k as // its conjuncts: on one entry, the $ref first or last, and on two, the $ref's // entry first or last. @@ -73,12 +68,17 @@ type entryWritten struct { diags []string } +// maxRelocatedAllOfDepth is how many allOfs one inside another relocater reads. +const maxRelocatedAllOfDepth = 8 + // relocater reads an entry's pointer under the use at pointer as the use's, -// and a whole entry's key without its index: one conjunct is written at -// /allOf/0 or /allOf/1 by the spelling alone. +// at any depth of allOf up to maxRelocatedAllOfDepth, and a whole entry's key +// without its index: one conjunct is written at /allOf/0 or /allOf/1 by the +// spelling alone. func relocater(pointer string) func(string) string { - entry := regexp.MustCompile(regexp.QuoteMeta(pointer+"/allOf/") + `[01]\b`) - key := regexp.MustCompile(`openapi:allOf/[01]\b`) + nested := fmt.Sprintf(`(?:/allOf/[01]){1,%d}\b`, maxRelocatedAllOfDepth) + entry := regexp.MustCompile(regexp.QuoteMeta(pointer) + nested) + key := regexp.MustCompile(fmt.Sprintf(`openapi:allOf/[01](?:/allOf/[01]){0,%d}\b`, maxRelocatedAllOfDepth-1)) return func(s string) string { return key.ReplaceAllString(entry.ReplaceAllString(s, pointer), "openapi:allOf") } @@ -126,11 +126,10 @@ func namesTarget(t *testing.T, doc *ir.Document) bool { // TestRefConjunction_AnEntrysRefAndKeywordsLowerAsTwoEntries holds an allOf // entry writing a $ref beside a keyword to the composition listing the two on // entries of their own, for ten keyword families over six targets, at a -// component and at a property, each in both orders: one document, up to the +// component and at a property, in both orders: one document, up to the // entries' pointers and a whole entry's index, and one diagnostic list up to -// message text. In each, the $ref is either the node a use names or kept, on -// one node, and the keyword is kept at most once, else changes what compiles -// or is one the target says already. +// message text. The $ref is the node a use names or kept on one node, and the +// keyword is kept at most once, else changes what compiles. func TestRefConjunction_AnEntrysRefAndKeywordsLowerAsTwoEntries(t *testing.T) { t.Parallel() for _, site := range []conjSite{conjSites[0], conjSites[1]} { @@ -149,9 +148,7 @@ func TestRefConjunction_AnEntrysRefAndKeywordsLowerAsTwoEntries(t *testing.T) { assert.NotEqual(t, refs == 1, namesTarget(t, doc), "%s, %s: the $ref is named or kept", name, spelling) kept := keptNaming(doc, keyword) assert.LessOrEqual(t, kept, 1, "%s, %s: %s is kept once", name, spelling, keyword) - if saidByTarget[[2]string{tname, kname}] { - assert.Equal(t, bare.doc, got.doc, "%s, %s: the use is the reference", name, spelling) - } else if kept == 0 { + if kept == 0 { assert.NotEqual(t, bare.doc, got.doc, "%s, %s: %s, kept nowhere, is typed", name, spelling, keyword) } } @@ -196,9 +193,9 @@ func TestRefConjunction_AValueSetBesideAnEntrysRefIsReportedOnce(t *testing.T) { } } -// TestRefConjunction_AnEntrysRefIsKeptOnOneNode holds that a $ref an -// election passes over is kept on one node of the document, whether a union -// is written beside it or beside its entry. +// TestRefConjunction_AnEntrysRefIsKeptOnOneNode holds that a $ref a choice +// passes over is kept on one node of the document, whether a union is written +// beside it or beside its entry. func TestRefConjunction_AnEntrysRefIsKeptOnOneNode(t *testing.T) { t.Parallel() union := "oneOf: [{type: string}, {type: integer}]" diff --git a/compilers/openapi/e2e/ref_conjunction_grid_test.go b/compilers/openapi/e2e/ref_conjunction_grid_test.go index 6eeda7961..cc9be3076 100644 --- a/compilers/openapi/e2e/ref_conjunction_grid_test.go +++ b/compilers/openapi/e2e/ref_conjunction_grid_test.go @@ -16,6 +16,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) @@ -248,12 +249,11 @@ func TestRefConjunction_APromotedFactAndItsMarkSitOnOneNodeInEverySpelling(t *te } } -// TestRefConjunction_AnAllOfOfOneRefHoistsNoNode holds that an allOf whose -// only entry is a $ref to a string or an object, writing nothing beside it, -// is a use of the target: no anonymous node stands at its position or names -// the target as its base, and the position names the target, but at a -// component, which owns a node: a model over an object, a scalar over any -// other target. +// TestRefConjunction_AnAllOfOfOneRefHoistsNoNode holds that an allOf whose only +// entry is a $ref to a string or an object, writing nothing beside it, is a use +// of the target: no anonymous node sits at its position or names the target as +// its base, and the position names the target, but at a component, which owns a +// node: a model over an object, a scalar over any other target. func TestRefConjunction_AnAllOfOfOneRefHoistsNoNode(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -430,19 +430,24 @@ func TestRefConjunction_AStructuralKeywordBesideARefIsComposedOverItsTarget(t *t // TestRefConjunction_AValueSetBesideARefNarrowsItsTargetInEverySpelling holds // that an enum or a const written beside a $ref and beside an allOf of it -// lowers alike (a value set on an entry of that allOf is a case of the node -// standing at the position, which these do not hold): the property names the enum or the +// lowers alike (a value set on an entry of that allOf is a case of the node at +// the position, which these do not hold): the property names the enum or the // literal, which keeps the $ref, with one report, and an enum or type the -// target already says is a use of the target keeping nothing. +// target already says is a use of the target keeping nothing. An enum sharing +// no member with the target's is the closed empty Enum keeping it, the one +// warning alone reporting it. func TestRefConjunction_AValueSetBesideARefNarrowsItsTargetInEverySpelling(t *testing.T) { t.Parallel() levels := []string{"Level: {type: string, enum: [low, mid, high]}", "Port: {type: integer}"} - uses := []struct{ name, target, keywords, kind string }{ - {"enum", "Level", "enum: [low]", "enum"}, - {"const", "Level", "const: low", "literal"}, - {"out", "Level", "enum: [other]", "enum"}, - {"portEnum", "Port", "enum: [1, 2]", "enum"}, - {"type", "Port", "type: integer", ""}, + uses := []struct { + name, target, keywords, kind string + kept []string // what the node keeps but its $ref + }{ + {"enum", "Level", "enum: [low]", "enum", nil}, + {"const", "Level", "const: low", "literal", nil}, + {"out", "Level", "enum: [other]", "enum", []string{"openapi:enum"}}, + {"portEnum", "Port", "enum: [1, 2]", "enum", nil}, + {"type", "Port", "type: integer", "", nil}, } for _, version := range []string{"3.1.0"} { t.Run(version, func(t *testing.T) { @@ -468,12 +473,18 @@ func TestRefConjunction_AValueSetBesideARefNarrowsItsTargetInEverySpelling(t *te } assert.Equal(t, ir.TypeKind(u.kind), node.Kind(), "what %s names", u.name) kept := keptOn(node) - require.Len(t, kept, 1, u.name) + require.Len(t, kept, 1+len(u.kept), u.name) for key, reason := range kept { - assert.Regexp(t, `^openapi:(allOf/\d+|\$ref)$`, key, u.name) + if !slices.Contains(u.kept, key) { + assert.Regexp(t, `^openapi:(allOf/\d+|\$ref)$`, key, u.name) + } assert.Equal(t, ir.ReasonDegradedLowering, reason, u.name) } - assert.Equal(t, 1, degradedInfosUnder(diags, pointer), "the one report of %s", u.name) + infos := 1 + if u.kept != nil { + infos = 0 // the sets share no member, which the one warning reports + } + assert.Equal(t, infos, degradedInfosUnder(diags, pointer), "the one report of %s", u.name) } }) } @@ -550,8 +561,9 @@ func TestRefConjunction_AKeywordOnlyAModelHoldsBesideARefAtAParameterIsKeptOnThe // TestRefConjunction_AUnionBesideARefLowersAsBesideAnAllOfOfIt holds that a // oneOf or an anyOf written beside a $ref is read as the allOf spelling reads -// it: consumed where the principal already says it (a string and a union of a -// string and a boolean), kept as validation logic where its branches declare +// it: kept whole by the target's node where a branch shares no kind with the +// target (a string and a union of a string and a boolean), its dead branch +// reported at the union, kept as validation logic where its branches declare // no shape, and distributed over an object where they declare one. func TestRefConjunction_AUnionBesideARefLowersAsBesideAnAllOfOfIt(t *testing.T) { t.Parallel() @@ -568,12 +580,17 @@ func TestRefConjunction_AUnionBesideARefLowersAsBesideAnAllOfOfIt(t *testing.T) } }) requireSpellingsEqual(t, beside, wrapped, "a union beside a $ref") - requireOnlyFindings(t, filterCodes(diags, "openapi/validation-only-keyword", "openapi/composition-lowering"), - "a union beside a $ref", "openapi/later-version-construct") + requireOnlyFindings(t, filterCodes(diags, "openapi/validation-only-keyword", "openapi/composition-lowering", + diag.DegradedConstruct, diag.UnsatisfiableSchema), "a union beside a $ref", "openapi/later-version-construct") stringType := requireScalarOver(t, beside, "UnionStr", componentID("Str")) - assert.Empty(t, keptOn(stringType), "a union the principal says is consumed") - assert.Zero(t, degradedInfosAt(diags, "UnionStr")) + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonDegradedLowering}, keptOn(stringType), + "a union holding a dead branch is kept whole") + assert.Equal(t, 1, unsatisfiableAt(diags, "/components/schemas/UnionStr/oneOf"), "its dead branch is reported at the union") + assert.Equal(t, 1, degradedInfosAt(diags, "UnionStr"), "and the keep once") + assert.Len(t, slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code != diag.UnsatisfiableSchema && diagnostic.Code != diag.DegradedConstruct + }), 2, "nothing else is reported") req := kindNode(t, beside, componentID("UnionReq")) assert.Equal(t, ir.ReasonValidationOnly, keptOn(req)["openapi:anyOf"], "a union declaring no shape is validation logic") @@ -599,7 +616,7 @@ func filterCodes(diags []ir.Diagnostic, drop ...string) []ir.Diagnostic { // TestRefConjunction_TwoUnionsOnOneSchemaLowerAsOnTwoEntries holds that a oneOf // and an anyOf written on one schema beside a body lower as the same two on // two entries beside the same body do: a union of the models, the oneOf -// distributed and the anyOf kept on each variant. +// distributed and the anyOf kept once, on the Union. func TestRefConjunction_TwoUnionsOnOneSchemaLowerAsOnTwoEntries(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -688,11 +705,11 @@ func TestRefConjunction_ADynamicRefBesideARefIsKeptOnTheUseInEverySpelling(t *te } } -// TestRefConjunction_TwoBasesInADiscriminatorHierarchyElectTheLeastReference +// TestRefConjunction_TwoBasesInADiscriminatorHierarchyChooseTheLeastReference // holds that of two $refs to schemas each declaring a discriminator, neither // of which routes to the composing schema, the base is the one whose reference // text is the least, whichever is written first, and the other is a mixin. -func TestRefConjunction_TwoBasesInADiscriminatorHierarchyElectTheLeastReference(t *testing.T) { +func TestRefConjunction_TwoBasesInADiscriminatorHierarchyChooseTheLeastReference(t *testing.T) { t.Parallel() base := "{type: object, required: [kind], properties: {kind: {type: string}}, discriminator: {propertyName: kind}}" body := "{type: object, properties: {c: {type: string}}}" @@ -753,10 +770,11 @@ var entryNumbers = regexp.MustCompile(`openapi:allOf/\d+|/allOf/\d+`) // table, no position, no provenance pointer, the findings as a multiset of // severity and code, and no entry of an allOf numbered, in an ID, a pointer or // an Unmodeled key, since a spelling that writes a $ref as an entry and one -// that writes it beside has no other name for the entry. later-version-construct, -// the warning a 3.0 document draws for a keyword beside a $ref, is left out of -// the findings, and so is the validation-no-effect it stands in for at a -// `nullable` (docs/compilers/openapi.md#nullable). +// that writes it beside has no other name for the entry. +// later-version-construct, the warning a 3.0 document draws for a keyword +// beside a $ref, is left out of the findings, and so is the +// validation-no-effect it takes the place of at a `nullable` +// (docs/compilers/openapi.md#nullable). func spellingView(t *testing.T, doc *ir.Document) map[string]any { t.Helper() raw, err := json.Marshal(doc) @@ -784,8 +802,8 @@ func spellingView(t *testing.T, doc *ir.Document) map[string]any { } // statedBesideARef reports whether the diagnostic d is one a spelling states -// for a keyword beside a $ref at 3.0: the later-version warning, or the -// warning that a `nullable` has no effect, which it stands in for. +// for a keyword beside a $ref at 3.0: the later-version warning, or the warning +// that a `nullable` has no effect, which it takes the place of. func statedBesideARef(d any) bool { code := valueAtPath(d, "code") pointer := fmt.Sprint(valueAtPath(d, "provenance", "pointer")) diff --git a/compilers/openapi/e2e/ref_conjunction_helpers_test.go b/compilers/openapi/e2e/ref_conjunction_helpers_test.go index d6c2e35e2..6f3472f87 100644 --- a/compilers/openapi/e2e/ref_conjunction_helpers_test.go +++ b/compilers/openapi/e2e/ref_conjunction_helpers_test.go @@ -143,7 +143,7 @@ func requireNothingHoisted(t *testing.T, version, target string, site conjSite, assert.Equal(t, id, scalar.Base.Target) return } - assert.Empty(t, anonymousNodesAt(doc, site.pointer), "no node stands at %s", site.pointer) + assert.Empty(t, anonymousNodesAt(doc, site.pointer), "no node sits at %s", site.pointer) assert.Empty(t, anonymousOver(doc, id), "no node names %s as its base", target) } @@ -181,20 +181,21 @@ var twoUnionShapes = func() map[string]string { // requireOneOfDistributed holds the component Use to the union of the oneOf // of twoUnionShapes: exclusive, a model for each branch carrying the body, and -// the anyOf kept on each of them under its keyword. +// the anyOf kept once, on the Union, under its keyword. func requireOneOfDistributed(t *testing.T, doc *ir.Document) { t.Helper() union, ok := kindNode(t, doc, componentID("Use")).(*ir.Union) require.True(t, ok, "the oneOf distributes") assert.True(t, union.Exclusive) + // Its branches declare no shape against the body, so it is validation + // logic, as the anyOf beside a body alone is. + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": ir.ReasonValidationOnly}, keptOn(union), + "the anyOf is kept once, on the Union") require.Len(t, union.Variants, 2) for _, irVariant := range union.Variants { variant := requireModelNode(t, doc, irVariant.Type.Target) assert.Equal(t, []string{"x", "y"}, propertyNames(variant), "each variant carries the body") - // Its branches declare no shape against the body, so it is validation - // logic, as the anyOf beside a body alone is. - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": ir.ReasonValidationOnly}, keptOn(variant), - "the anyOf is kept on each variant") + assert.Empty(t, keptOn(variant), "a variant keeps nothing of its own") } } diff --git a/compilers/openapi/e2e/ref_conjunction_nothing_test.go b/compilers/openapi/e2e/ref_conjunction_nothing_test.go index 1d5b6d8ff..ae83a620e 100644 --- a/compilers/openapi/e2e/ref_conjunction_nothing_test.go +++ b/compilers/openapi/e2e/ref_conjunction_nothing_test.go @@ -31,6 +31,13 @@ func writtenAnyway(t *testing.T, site conjSite, target, schema string) entryWrit t.Helper() doc, diags := compileAnnotationSpec(t, "conjunction", site.write("3.1.0", schema, target)) require.NotNil(t, doc) + return writtenOf(t, site, doc, diags) +} + +// writtenOf reads doc and diags, compiled with the schema written at site, as +// entryWritten. +func writtenOf(t *testing.T, site conjSite, doc *ir.Document, diags []ir.Diagnostic) entryWritten { + t.Helper() relocate := relocater(site.pointer) got := entryWritten{doc: relocate(withoutVersion(t, doc))} for _, diagnostic := range diags { diff --git a/compilers/openapi/e2e/ref_conjunction_silent_test.go b/compilers/openapi/e2e/ref_conjunction_says_nothing_test.go similarity index 88% rename from compilers/openapi/e2e/ref_conjunction_silent_test.go rename to compilers/openapi/e2e/ref_conjunction_says_nothing_test.go index 37b68611b..a7124ac58 100644 --- a/compilers/openapi/e2e/ref_conjunction_silent_test.go +++ b/compilers/openapi/e2e/ref_conjunction_says_nothing_test.go @@ -12,11 +12,11 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestRefConjunction_SilentKeysBesideARefLeaveItTheReference holds that a key +// TestRefConjunction_KeysSayingNothingBesideARefLeaveItTheReference holds that a key // saying nothing of the instance, a comment, an anchor or the schemas a // reference reaches, makes no conjunction beside a $ref: a property names the // target as a bare $ref does, and a component over a string is its alias. -func TestRefConjunction_SilentKeysBesideARefLeaveItTheReference(t *testing.T) { +func TestRefConjunction_KeysSayingNothingBesideARefLeaveItTheReference(t *testing.T) { t.Parallel() for _, key := range []string{"$comment: c", "$anchor: a", "$defs: {D: {type: string}}"} { spec := admissionSpec("3.1.0", "", "Obj: {type: object, properties: {a: {type: string}}}", diff --git a/compilers/openapi/e2e/ref_conjunction_spelling_pending_test.go b/compilers/openapi/e2e/ref_conjunction_spelling_pending_test.go index 0d1a61e70..24c6edd26 100644 --- a/compilers/openapi/e2e/ref_conjunction_spelling_pending_test.go +++ b/compilers/openapi/e2e/ref_conjunction_spelling_pending_test.go @@ -8,31 +8,12 @@ package e2e_test import ( "testing" - "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dexpace/morphic/ir" ) -// TestRefConjunction_AValueSetBesideAFailedRefLowersAsBesideItsRef holds an -// enum beside a $ref naming no schema to one document in each spelling but an -// entry writing both, which is read whole. Pending (GitHub #2064): an enum on -// an entry of its own next to the $ref composes a Model, where beside the $ref -// or the allOf it lowers as the enum keeping the $ref. -func TestRefConjunction_AValueSetBesideAFailedRefLowersAsBesideItsRef(t *testing.T) { - t.Parallel() - const target, k = "Other: {type: string}", "enum: [a]" - spellings := fourSpellings(k) - for _, site := range conjSites { - want := writtenAnyway(t, site, target, spellings["beside the $ref"]) - for _, name := range []string{"beside an allOf", "on an entry next"} { - got := writtenAnyway(t, site, target, spellings[name]) - assert.Empty(t, cmp.Diff(want, got, cmp.AllowUnexported(entryWritten{})), "%s, %s", site.name, name) - } - } -} - // TestRefConjunction_AComponentOverADiscriminatedBaseIsTaggedInEverySpelling // holds the tag a component over a discriminated schema carries to one value // in every spelling of a use saying nothing more of it. Pending (GitHub @@ -43,14 +24,14 @@ func TestRefConjunction_AComponentOverADiscriminatedBaseIsTaggedInEverySpelling( t.Parallel() disc := "T: {type: object, required: [kind], properties: {kind: {type: string}}, discriminator: {propertyName: kind}}" tags := map[string]string{} - for name, schema := range fourSpellings("$comment: c") { + for name, schema := range besideRefSpellings("$comment: c") { doc, _ := compileUnrefused(t, conjSites[0].write("3.1.0", schema, disc)) m, ok := kindNode(t, doc, componentID("Use")).(*ir.Model) require.True(t, ok, name) tags[name] = m.DiscriminatorValue } for name, tag := range tags { - assert.Equal(t, tags["beside the $ref"], tag, name) + assert.Equal(t, tags["Flat"], tag, name) } } @@ -62,7 +43,7 @@ func TestRefConjunction_AComponentOverADiscriminatedBaseIsTaggedInEverySpelling( // string it is the carrier's Secret. func TestRefConjunction_ARedactionBesideARefToAnObjectIsTheCarriersInEverySpelling(t *testing.T) { t.Parallel() - for name, schema := range fourSpellings("format: password") { + for name, schema := range besideRefSpellings("format: password") { doc, _ := compileUnrefused(t, conjSites[1].write("3.1.0", schema, "T: {type: object, properties: {a: {type: string}}}")) holder, ok := kindNode(t, doc, componentID("Holder")).(*ir.Model) require.True(t, ok, name) diff --git a/compilers/openapi/e2e/ref_conjunction_spelling_test.go b/compilers/openapi/e2e/ref_conjunction_spelling_test.go index 912f8b8a1..6f773fbf6 100644 --- a/compilers/openapi/e2e/ref_conjunction_spelling_test.go +++ b/compilers/openapi/e2e/ref_conjunction_spelling_test.go @@ -3,15 +3,39 @@ package e2e_test -import "testing" +import ( + "testing" -// TestRefConjunction_AUnionBesideARefToTheTopTypeStandsAtThePosition holds + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" +) + +// TestRefConjunction_AUnionBesideARefToTheTopTypeSitsAtThePosition holds // the four spellings of a union beside a $ref to a schema admitting every // kind to one document, the union the node the position owns // (docs/compilers/openapi.md#allof-refinement). -func TestRefConjunction_AUnionBesideARefToTheTopTypeStandsAtThePosition(t *testing.T) { +func TestRefConjunction_AUnionBesideARefToTheTopTypeSitsAtThePosition(t *testing.T) { t.Parallel() for _, target := range []string{"T: {}", "T: true", "T: {properties: {a: {type: string}}}"} { - requireOneDocument(t, conjSites, target, "oneOf: [{type: string}, {type: integer}]") + requireOneDocument(t, conjSites, target, "oneOf: [{type: string}, {type: integer}]", "") + } +} + +// TestRefConjunction_AValueSetBesideAFailedRefLowersAsBesideItsRef holds an +// enum beside a $ref naming no schema to one document in each spelling but an +// entry writing both, which is read whole: on an entry of its own next to the +// $ref, beside the $ref or beside the allOf, the value set is chosen by its +// keyword before any read, so the position is the enum keeping the $ref +// (docs/compilers/openapi.md#allof-refinement). +func TestRefConjunction_AValueSetBesideAFailedRefLowersAsBesideItsRef(t *testing.T) { + t.Parallel() + const target, k = "Other: {type: string}", "enum: [a]" + spellings := besideRefSpellings(k) + for _, site := range conjSites { + want := writtenAnyway(t, site, target, spellings["Flat"]) + for _, name := range []string{"Beside", "Entry"} { + got := writtenAnyway(t, site, target, spellings[name]) + assert.Empty(t, cmp.Diff(want, got, cmp.AllowUnexported(entryWritten{})), "%s, %s", site.name, name) + } } } diff --git a/compilers/openapi/e2e/ref_conjunction_test.go b/compilers/openapi/e2e/ref_conjunction_test.go index e47b6494c..62feae430 100644 --- a/compilers/openapi/e2e/ref_conjunction_test.go +++ b/compilers/openapi/e2e/ref_conjunction_test.go @@ -12,14 +12,13 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) // TestRefConjunction_ABareRefHoistsNoNode holds that a $ref to a string or an -// object writing nothing beside it is a use of the target at every position: -// no anonymous node stands there or names the target as its base, and a -// component over a string is the alias that owns it. +// object writing nothing beside it is a use of the target at every position: no +// anonymous node sits there or names the target as its base, and a component +// over a string is the alias that owns it. func TestRefConjunction_ABareRefHoistsNoNode(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -39,7 +38,7 @@ func TestRefConjunction_ABareRefHoistsNoNode(t *testing.T) { // TestRefConjunction_TwoUnionsOnEntriesLowerTheOneOfWhicheverEntryWritesIt holds // that a oneOf and an anyOf on two entries beside a body, in either order of the -// entries, distribute the oneOf and keep the anyOf whole on each variant. +// entries, distribute the oneOf and keep the anyOf whole once, on the Union. func TestRefConjunction_TwoUnionsOnEntriesLowerTheOneOfWhicheverEntryWritesIt(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0"} { @@ -56,8 +55,9 @@ func TestRefConjunction_TwoUnionsOnEntriesLowerTheOneOfWhicheverEntryWritesIt(t // TestRefConjunction_KeywordsAnOverlayWritesBesideARefConjoinAsWritten holds // that an overlay's update writing keywords beside a $ref makes the same // conjunction the source would: a bound and a description beside a $ref to a -// string are the alias's own, and a oneOf of bounds beside one at a property -// is validation logic, kept once on the property. +// string are the alias's own, and a oneOf of bounds beside one at a property is +// validation logic, kept once on the node over the target at the property, as +// the body's node keeps such a union at a property in every spelling. func TestRefConjunction_KeywordsAnOverlayWritesBesideARefConjoinAsWritten(t *testing.T) { t.Parallel() doc, diags := compileWithPatch(t, `openapi: 3.1.0 @@ -90,15 +90,19 @@ actions: model := requireModelNode(t, doc, componentID("H")) property, ok := propertyByWire(model, "p") require.True(t, ok) - assert.Equal(t, componentID("T"), property.Type.Target, "a carrier hoists no node") - assert.Equal(t, "e", property.Docs.Description) - assert.Equal(t, ir.ReasonValidationOnly, unmodeledEntry(t, property.Unmodeled, "openapi:oneOf").Reason) - assert.Len(t, property.Unmodeled, 1) + node, ok := kindNode(t, doc, property.Type.Target).(*ir.Scalar) + require.True(t, ok, "the property names a node of its own") + require.NotNil(t, node.Base) + assert.Equal(t, componentID("T"), node.Base.Target, "over the target") + assert.Equal(t, "e", node.Docs.Description) + assert.Equal(t, ir.ReasonValidationOnly, unmodeledEntry(t, node.Unmodeled, "openapi:oneOf").Reason) + assert.Len(t, node.Unmodeled, 1) + assert.Empty(t, property.Unmodeled, "the property keeps nothing of its own") } // TestRefConjunction_ACarrierOfAnAllOfOfOneRefReadsItsTargetsDocs holds that a // property or a parameter whose schema is an allOf of one $ref saying nothing -// is the use of the target a bare $ref is: no node stands between them, and the +// is the use of the target a bare $ref is: no node sits between them, and the // carrier reads the target's description as it does through the bare $ref. func TestRefConjunction_ACarrierOfAnAllOfOfOneRefReadsItsTargetsDocs(t *testing.T) { t.Parallel() @@ -122,12 +126,14 @@ func TestRefConjunction_ACarrierOfAnAllOfOfOneRefReadsItsTargetsDocs(t *testing. assert.Equal(t, params[0].Docs, params[1].Docs, "the parameter reads the docs alike in either spelling") } -// TestRefConjunction_AKeywordBesideAValueSetIsKeptOnceOnItsNode holds that a -// keyword no Enum holds, written beside a value set narrowing a $ref, is kept -// once on the Enum the position lowers to, whether the value set is written -// beside the $ref, beside an allOf of it or on an entry of that allOf, at a -// component and at a property. -func TestRefConjunction_AKeywordBesideAValueSetIsKeptOnceOnItsNode(t *testing.T) { +// TestRefConjunction_ABoundBesideAValueSetIsHeldOnItsNode holds that a bound of +// the value kind, written beside a value set narrowing a $ref, is held once in +// the Constraints of the Enum the position lowers to (GitHub #2004), and the +// beaten $ref kept once on it, whether the value set is written beside the +// $ref, beside an allOf of it or on an entry of that allOf, at a component and +// at a property. Where the $ref is read beside a value set turns on the +// keyword-scope decisions. +func TestRefConjunction_ABoundBesideAValueSetIsHeldOnItsNode(t *testing.T) { t.Parallel() for name, schema := range map[string]string{ "beside the $ref": "{" + refTo("Str") + ", enum: [a, b], pattern: '^a'}", @@ -143,53 +149,70 @@ func TestRefConjunction_AKeywordBesideAValueSetIsKeptOnceOnItsNode(t *testing.T) } enum, ok := kindNode(t, doc, id).(*ir.Enum) require.True(t, ok, at) - assert.ElementsMatch(t, []string{"openapi:$ref", "openapi:pattern"}, slices.Collect(maps.Keys(enum.Unmodeled)), at) - assert.JSONEq(t, `"^a"`, string(enum.Unmodeled["openapi:pattern"].Value), at) - assert.Equal(t, 2, degradedInfosUnder(diags, site.pointer), "%s: one report for each keyword kept", at) + assert.ElementsMatch(t, []string{"openapi:$ref"}, slices.Collect(maps.Keys(enum.Unmodeled)), at) + assert.Equal(t, &ir.Constraints{Pattern: "^a"}, enum.Constraints, at) + assert.Equal(t, 1, degradedInfosUnder(diags, site.pointer), "%s: one report, for the $ref kept", at) } } } // TestRefConjunction_AKeptRefsSiblingsAreKeptEachUnderItsOwnKey holds that a -// $ref a composition or a value set passes over is kept under openapi:$ref as -// the reference alone, and that each keyword written beside it, beside the -// $ref or beside it on an allOf entry, is a conjunct kept under its own key -// with its own reason: a note is the node's, a bound and a format no node -// holds degraded, an unknown keyword out of scope, an extension a vendor's. +// $ref a value set passes over is kept under openapi:$ref alone, and each +// keyword beside it, beside the $ref or on its entry, under its own key and +// reason: a note is the node's, a format degraded, an unknown keyword out of +// scope, an extension a vendor's, while a bound of the kind the enum lists is +// held in the Enum's Constraints (GitHub #2004). Beside an object, which the +// string shares no kind with, the bottom keeps each keyword the position +// writes under its plain key and each entry, its $ref inside, under its +// entry key. func TestRefConjunction_AKeptRefsSiblingsAreKeptEachUnderItsOwnKey(t *testing.T) { t.Parallel() const siblings = "description: d, maxLength: 9, format: email, foo: bar, x-v: 1" ref := refTo("Str") object := "{type: object, properties: {p: {type: string}}}" - for name, schema := range map[string]string{ - "a value set, beside the $ref": "{" + ref + ", " + siblings + ", enum: [a]}", - "a value set, on an entry": "{allOf: [{" + ref + ", " + siblings + "}], enum: [a]}", - "a composition, beside the $ref": "{" + ref + ", " + siblings + ", allOf: [" + object + "]}", - "a composition, on an entry": "{allOf: [{" + ref + ", " + siblings + "}, " + object + "]}", + ownKeys := map[string]ir.UnmodeledReason{ + "openapi:$ref": ir.ReasonDegradedLowering, + "openapi:format": ir.ReasonDegradedLowering, "openapi:foo": ir.ReasonOutOfScope, + "openapi:x-v": ir.ReasonVendorExtension, + } + for name, tc := range map[string]struct { + schema string + want []string + }{ + "a value set, beside the $ref": {"{" + ref + ", " + siblings + ", enum: [a]}", nil}, + "a value set, on an entry": {"{allOf: [{" + ref + ", " + siblings + "}], enum: [a]}", nil}, + "a composition, beside the $ref": {"{" + ref + ", " + siblings + ", allOf: [" + object + "]}", []string{"openapi:$ref", "openapi:allOf/0", "openapi:foo", "openapi:format", "openapi:maxLength", "openapi:x-v"}}, + "a composition, on an entry": {"{allOf: [{" + ref + ", " + siblings + "}, " + object + "]}", []string{"openapi:allOf/0", "openapi:allOf/1"}}, } { - doc, _ := compileAnnotationSpec(t, "kept", admissionSpec("3.1.0", "", conjTargets["Str"], "Use: "+schema)) + doc, _ := compileAnnotationSpec(t, "kept", admissionSpec("3.1.0", "", conjTargets["Str"], "Use: "+tc.schema)) node := kindNode(t, doc, componentID("Use")) kept := node.Common().Unmodeled - want := map[string]ir.UnmodeledReason{ - "openapi:$ref": ir.ReasonDegradedLowering, "openapi:maxLength": ir.ReasonDegradedLowering, - "openapi:format": ir.ReasonDegradedLowering, "openapi:foo": ir.ReasonOutOfScope, - "openapi:x-v": ir.ReasonVendorExtension, + if tc.want != nil { + assert.ElementsMatch(t, tc.want, slices.Collect(maps.Keys(kept)), "%s: the bottom's keys", name) + if entry, ok := kept["openapi:allOf/0"]; ok && name == "a composition, on an entry" { + assert.Contains(t, string(entry.Value), "#/components/schemas/Str", "%s: the entry holds its $ref", name) + } + continue } got := map[string]ir.UnmodeledReason{} for key, entry := range kept { got[key] = entry.Reason } - assert.Equal(t, want, got, name) + assert.Equal(t, ownKeys, got, name) assert.JSONEq(t, `"#/components/schemas/Str"`, string(kept["openapi:$ref"].Value), "%s: the reference's text alone", name) assert.Equal(t, "d", node.Common().Docs.Description, "%s: the note is the node's", name) + enum, isEnum := node.(*ir.Enum) + require.True(t, isEnum, name) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(9))}, enum.Constraints, "%s: the bound is the Enum's", name) } } // TestRefConjunction_AFailedRefBesideKeywordsIsKeptAsBesideAnAllOfOfIt holds // that a $ref naming nothing written beside keywords is the conjunction -// `{allOf: [{$ref: …}], …}` writes: the reference's text kept under -// openapi:$ref at the position, each keyword the position's own, the note on -// the node and the rest kept under its own key, in both spellings alike. +// `{allOf: [{$ref: …}], …}` writes, which admits every kind and cuts nothing: +// in both spellings the position lowers as the keywords alone do, its note +// and bound on the node, the reference's text kept under openapi:$ref, and the +// failure reported once. func TestRefConjunction_AFailedRefBesideKeywordsIsKeptAsBesideAnAllOfOfIt(t *testing.T) { t.Parallel() const keywords = "description: why, minLength: 2, x-a: 1" @@ -199,23 +222,13 @@ func TestRefConjunction_AFailedRefBesideKeywordsIsKeptAsBesideAnAllOfOfIt(t *tes "beside an allOf": "{allOf: [{$ref: '#/components/schemas/Ghost'}], " + keywords + "}", } { at := version + ", " + name - doc, diags := compileAnnotationSpec(t, "failed", admissionSpec(version, "", "Use: "+schema)) - use := requireModelNode(t, doc, componentID("Use")) + doc := requireLowersWithoutRefs(t, version, []string{"Use: " + schema}, + []string{"$ref: '#/components/schemas/Ghost', ", "allOf: [{$ref: '#/components/schemas/Ghost'}], "}, 1) + use, ok := doc.Types[componentID("Use")].(*ir.Scalar) + require.True(t, ok, "%s: the keywords alone are a scalar, got %T", at, doc.Types[componentID("Use")]) assert.Equal(t, "why", use.Docs.Description, at) - got := map[string]ir.UnmodeledReason{} - for key, entry := range use.Unmodeled { - got[key] = entry.Reason - } - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:$ref": ir.ReasonDegradedLowering, - "openapi:minLength": ir.ReasonDegradedLowering, "openapi:x-a": ir.ReasonVendorExtension}, got, at) + assert.Equal(t, &ir.Constraints{MinLength: new(int64(2))}, use.Constraints, at) assert.JSONEq(t, `"#/components/schemas/Ghost"`, string(use.Unmodeled["openapi:$ref"].Value), at) - errs := 0 - for _, diagnostic := range diags { - if diagnostic.Code == diag.UnresolvedRef { - errs++ - } - } - assert.Equal(t, 1, errs, "%s: the failure is reported once", at) } } } diff --git a/compilers/openapi/e2e/ref_use_bound_test.go b/compilers/openapi/e2e/ref_use_bound_test.go index 983d2ff83..b9bfe3ef4 100644 --- a/compilers/openapi/e2e/ref_use_bound_test.go +++ b/compilers/openapi/e2e/ref_use_bound_test.go @@ -48,11 +48,11 @@ var useBoundSpellings = map[string]string{ } // TestRefUseBound_ACarriedUseIsTheReference holds that a use whose keywords -// beside its one $ref to an object only bind the use is that reference where -// a property or a parameter carries it, in both spellings and at both -// versions: the carrier names Obj and holds the keyword, and no node stands at -// the position. A component and a list's element own their node, the Model -// over Obj, as before. +// beside its one $ref to an object only bind the use is that reference where a +// property or a parameter carries it, in both spellings and at both versions: +// the carrier names Obj and holds the keyword, and no node sits at the +// position. A component and a list's element own their node, the Model over +// Obj, as before. func TestRefUseBound_ACarriedUseIsTheReference(t *testing.T) { t.Parallel() for _, kw := range useBoundKeywords { @@ -74,7 +74,7 @@ func TestRefUseBound_ACarriedUseIsTheReference(t *testing.T) { require.Len(t, operation.Params, 1) assert.Equal(t, componentID("Obj"), operation.Params[0].Type.Target, "the parameter names the reference") for _, at := range []string{"/components/schemas/Holder/properties/p", "/paths/~1x/get/parameters/0/schema"} { - assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous"+at), "no node stands at %s", at) + assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous"+at), "no node sits at %s", at) } for _, id := range []ir.TypeID{componentID("Pos"), "type/anonymous/components/schemas/Els/items"} { model, ok := kindNode(t, doc, id).(*ir.Model) @@ -140,7 +140,7 @@ func TestRefUseBound_AReferenceToACarriedPositionReadsItInEitherOrder(t *testing assert.Equal(t, ir.TypeID("type/anonymous"+at), property.Type.Target) assert.NotEmpty(t, property.Visibility.Only, "the user reads the readOnly through its $ref") node, ok := kindNode(t, doc, property.Type.Target).(*ir.Model) - require.True(t, ok, "no Scalar stands over a model") + require.True(t, ok, "no Scalar sits over a model") assert.Contains(t, node.Unmodeled, "openapi:readOnly") assert.Contains(t, degradedInfoPointers(diags), jsontext.Pointer(at+"/readOnly")) }) diff --git a/compilers/openapi/e2e/reference_objects_test.go b/compilers/openapi/e2e/reference_objects_test.go index ecad7063d..015c70feb 100644 --- a/compilers/openapi/e2e/reference_objects_test.go +++ b/compilers/openapi/e2e/reference_objects_test.go @@ -347,15 +347,17 @@ components: t.Helper() const cyclic = "error " + diag.CyclicRef + " /components/" assert.Equal(t, []string{ - cyclic + "requestBodies/RA: cyclic $ref: the chain of $refs through #/components/requestBodies/RA, " + - "#/components/requestBodies/RB comes back to where it started and never reaches a request body", - cyclic + "responses/Self: cyclic $ref: the chain of $refs through #/components/responses/Self comes back " + - "to where it started and never reaches a response", - cyclic + "responses/T1: cyclic $ref: the chain of $refs through #/components/responses/T1, " + - "#/components/responses/T2, #/components/responses/T3 comes back to where it started and never " + - "reaches a response", - cyclic + "schemas/S1: cyclic $ref: the chain of $refs through #/components/schemas/S1, " + - "#/components/schemas/S2 comes back to where it started and never reaches a schema", + cyclic + "requestBodies/RA: cyclic $ref: #/components/requestBodies/RA, #/components/requestBodies/RB, " + + "each a request body, refer only to each other by $ref, so none of them defines one; give one of " + + "them a definition of its own", + cyclic + "responses/Self: cyclic $ref: #/components/responses/Self, a response, refers only to itself " + + "by $ref, so it defines none; give it a definition of its own", + cyclic + "responses/T1: cyclic $ref: #/components/responses/T1, #/components/responses/T2, " + + "#/components/responses/T3, each a response, refer only to each other by $ref, so none of them " + + "defines one; give one of them a definition of its own", + cyclic + "schemas/S1: cyclic $ref: #/components/schemas/S1, #/components/schemas/S2 refer only to " + + "each other, by $ref or by an allOf of one $ref, so none of them constrains a value; give one of " + + "them a type, properties or another constraint", }, placedFindings(diags)) }) } diff --git a/compilers/openapi/e2e/restated_conjunct_test.go b/compilers/openapi/e2e/restated_conjunct_test.go new file mode 100644 index 000000000..dcd552196 --- /dev/null +++ b/compilers/openapi/e2e/restated_conjunct_test.go @@ -0,0 +1,61 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/jsontext" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestRestatedConjunct_ATypeSayingMoreIsAConjunct holds the limit of that +// reading: a type naming null beside the referent's kinds, and one naming a +// kind a referent admits only by the kind-inference policy, each say something, +// so the position composes a Model of its own. That Model holds nothing but its +// Base, so it exists only where a carrier holds the position, whose own node +// the carrier's keywords never fill, or where the use admits null, as the +// nullable-inference policy reads the type naming null beside the one +// reference, and elsewhere the position lowers as its bare $ref does +// (docs/compilers/openapi.md#allof-classification). +func TestRestatedConjunct_ATypeSayingMoreIsAConjunct(t *testing.T) { + t.Parallel() + targets := []string{"Obj: {type: object, properties: {a: {type: string}}}", "Untyped: {properties: {a: {type: string}}}"} + for referent, schema := range map[string]string{ + "Obj": "{allOf: [{$ref: '#/components/schemas/Obj'}], type: [object, 'null']}", + "Untyped": "{allOf: [{$ref: '#/components/schemas/Untyped'}], type: object}", + } { + doc, _ := parseVerified(t, conjunctionSpec("3.1.0", schema, targets...)) + for _, at := range conjunctionPositions[1:] { + carried := strings.Contains(string(at), "/properties/") || strings.Contains(string(at), "/parameters/") + widened := referent == "Obj" + assert.Equal(t, !carried && !widened, componentID(referent) == usedAt(t, doc, at), "%s at %s", schema, at) + } + } +} + +// TestRestatedConjunct_AnEntryKeywordRestatingTheReferentsSaysNothing holds +// that an entry's keyword beside a $ref principal restating the referent's +// same keyword, its own $ref there resolved once, says nothing: every key it +// writes the referent's writes alike, and the referent's others are notes or +// extensions. So it is neither kept nor reported, while one writing what the +// referent's does not is kept (docs/compilers/openapi.md#allof-refinement). +func TestRestatedConjunct_AnEntryKeywordRestatingTheReferentsSaysNothing(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, admissionSpec("3.0.3", "", + "Flag: {description: d, type: string, example: a, x-auditable: true}", + "Flags: {type: array, items: {$ref: '#/components/schemas/Flag'}}", + "Same: {type: object, properties: {p: {allOf: [{$ref: '#/components/schemas/Flags'}, "+ + "{type: array, items: {type: string, x-auditable: true}}]}}}", + "More: {type: object, properties: {p: {allOf: [{$ref: '#/components/schemas/Flags'}, "+ + "{type: array, items: {type: string, minLength: 1}}]}}}", + )) + same, more := keptUnder(doc, "/components/schemas/Same"), keptUnder(doc, "/components/schemas/More") + assert.Empty(t, same, "a restated items is kept nowhere") + assert.Contains(t, more, jsontext.Pointer("/components/schemas/More/properties/p/allOf/1/items"), "an items saying more is kept") + for _, d := range diags { + assert.False(t, strings.HasPrefix(string(d.Provenance.Pointer), "/components/schemas/Same/"), "Same reports nothing: %s", d.Message) + } +} diff --git a/compilers/openapi/e2e/security_requirement_uri_test.go b/compilers/openapi/e2e/security_requirement_uri_test.go index 8d125adaa..3dd7a7bfc 100644 --- a/compilers/openapi/e2e/security_requirement_uri_test.go +++ b/compilers/openapi/e2e/security_requirement_uri_test.go @@ -100,7 +100,7 @@ func TestCompile_ASecurityRequirementKeyThatIsAURIIsBoundToItsScheme(t *testing. doc, diags := compileRequirements(t, requirementEntry, requirementSchemes) assert.Empty(t, diags) - require.Len(t, doc.Auth, 2, "the two schemes, and no scheme standing for a key") + require.Len(t, doc.Auth, 2, "the two schemes, and no scheme taking the place of a key") require.Contains(t, doc.Auth, extraScheme) assert.Equal(t, ir.AuthKindHTTPBearer, doc.Auth[extraScheme].Kind) require.Contains(t, doc.Auth, sharedScheme) diff --git a/compilers/openapi/e2e/settlement_alias_chains_test.go b/compilers/openapi/e2e/settlement_alias_chains_test.go new file mode 100644 index 000000000..fafcebaa4 --- /dev/null +++ b/compilers/openapi/e2e/settlement_alias_chains_test.go @@ -0,0 +1,227 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// componentsSpec is a 3.1 document with no paths whose component schemas are +// schemas, each line indented under schemas. +func componentsSpec(schemas string) string { + return "openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + schemas +} + +// modelNamed returns the component schema name, lowered to a model. +func modelNamed(t *testing.T, doc *ir.Document, name string) *ir.Model { + t.Helper() + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s lowers to a model", name) + return model +} + +// memberOf returns model's member wire. +func memberOf(t *testing.T, model *ir.Model, wire string) ir.Property { + t.Helper() + property, ok := propertyByWire(model, wire) + require.True(t, ok, "%s declares %s", model.ID, wire) + return property +} + +// manyUsesOfOneChain is n aliases of integer, each with a description of its +// own, and one model per alias folding a field typed by it beside one typed +// number: each fold reads its alias's chain. +func manyUsesOfOneChain(n int) string { + var b strings.Builder + b.WriteString(" I0: {type: integer, description: alias 0}\n") + for i := 1; i < n; i++ { + fmt.Fprintf(&b, " I%d: {$ref: '#/components/schemas/I%d', description: alias %d}\n", i, i-1, i) + } + for i := range n { + fmt.Fprintf(&b, " W%d: {allOf: [{type: object, properties: {f: {$ref: '#/components/schemas/I%d'}}}, "+ + "{type: object, properties: {f: {type: number}}}]}\n", i, i) + } + return componentsSpec(b.String()) +} + +// TestAliasChains_ManyUsesOfOneChainFoldAlikePastSixtyFour pins a fold over an +// alias chain of any length: each of 70 models keeps the alias its field names +// over number, as those within 63 aliases do, where the 64th and later kept +// number and reported types the merge does not compare. +func TestAliasChains_ManyUsesOfOneChainFoldAlikePastSixtyFour(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, manyUsesOfOneChain(70)) + + assertNoErrorDiags(t, diags) + for i := range 70 { + field := memberOf(t, modelNamed(t, doc, fmt.Sprintf("W%d", i)), "f") + assert.Equal(t, componentID(fmt.Sprintf("I%d", i)), field.Type.Target, "W%d keeps its alias", i) + assert.Zero(t, countCode(diags, "openapi/degraded-construct", fmt.Sprintf("/components/schemas/W%d/allOf/0/properties/f", i)), + "W%d reports no types the merge does not compare", i) + } +} + +// multipartThroughRefs is a multipart request body whose schema is a chain of +// hops $refs to an object declaring n, with an encoding entry naming no +// property. +func multipartThroughRefs(hops int) string { + var b strings.Builder + b.WriteString(`openapi: 3.1.0 +info: {title: t, version: "1"} +paths: + /u: + post: + requestBody: + content: + multipart/form-data: + schema: {$ref: "#/components/schemas/L0"} + encoding: {ghost: {contentType: text/plain}} + responses: {"204": {description: ok}} +components: + schemas: +`) + for i := range hops { + fmt.Fprintf(&b, " L%d: {$ref: \"#/components/schemas/L%d\"}\n", i, i+1) + } + fmt.Fprintf(&b, " L%d:\n type: object\n properties:\n n: {type: string}\n", hops) + return b.String() +} + +// TestAliasChains_AnEncodingKeyNamingNoPartIsFoundThroughAnyChain pins the +// part walk's $ref chain: an encoding key naming no property draws +// openapi/unknown-encoding-key with the body reached through 64 or 200 $refs, +// as through 3, where past 63 the cut walk took the body to declare what it +// did not read. +func TestAliasChains_AnEncodingKeyNamingNoPartIsFoundThroughAnyChain(t *testing.T) { + t.Parallel() + for _, hops := range []int{3, 63, 64, 200} { + _, diags := parseVerified(t, multipartThroughRefs(hops)) + + assert.Equal(t, 1, countCode(diags, "openapi/unknown-encoding-key", + "/paths/~1u/post/requestBody/content/multipart~1form-data/encoding/ghost"), "%d $refs", hops) + } +} + +// lastModifiedThroughAliases is a response header Last-Modified whose schema +// reaches a date-time string through n aliases, each with a description. +func lastModifiedThroughAliases(n int) string { + var b strings.Builder + b.WriteString(`openapi: 3.1.0 +info: {title: t, version: "1"} +paths: + /x: + get: + operationId: getX + responses: + "200": + description: ok + headers: + Last-Modified: {schema: {$ref: '#/components/schemas/C0'}} +components: + schemas: +`) + for i := range n { + fmt.Fprintf(&b, " C%d: {$ref: '#/components/schemas/C%d', description: d%d}\n", i, i+1, i) + } + fmt.Fprintf(&b, " C%d: {type: string, format: date-time}\n", n) + return b.String() +} + +// TestAliasChains_AnHTTPDateIsInferredThroughAnyChain pins the convention's +// chain: a Last-Modified header reaching a date-time through 63 or 200 +// aliases draws openapi/inferred-http-date, as one through 62 does, where the +// walk cut at 64 hops drew none. +func TestAliasChains_AnHTTPDateIsInferredThroughAnyChain(t *testing.T) { + t.Parallel() + for _, n := range []int{62, 63, 200} { + _, diags := parseVerified(t, lastModifiedThroughAliases(n)) + + assert.Equal(t, 1, countCode(diags, "openapi/inferred-http-date", "/paths/~1x/get/responses/200/headers/Last-Modified"), + "%d aliases", n) + } +} + +// defaultOverAFarBound is a field typed by the head of n aliases of a string +// at most 2 long, with a default of 7 characters. +func defaultOverAFarBound(n int) string { + var b strings.Builder + b.WriteString(" I0: {type: string, maxLength: 2, description: alias 0}\n") + for i := 1; i < n; i++ { + fmt.Fprintf(&b, " I%d: {$ref: '#/components/schemas/I%d', description: alias %d}\n", i, i-1, i) + } + fmt.Fprintf(&b, " M: {type: object, properties: {f: {$ref: '#/components/schemas/I%d', default: toolong}}}\n", n-1) + return componentsSpec(b.String()) +} + +// TestAliasChains_ADefaultOutsideAFarBoundIsFoundThroughAnyChain pins the +// pass's chain: a default the far alias's bound refuses draws +// pass/default-outside-type over 70 and 200 aliases, as over 60, where the +// pass's walk cut at 64 hops drew nothing. +func TestAliasChains_ADefaultOutsideAFarBoundIsFoundThroughAnyChain(t *testing.T) { + t.Parallel() + for _, n := range []int{60, 70, 200} { + _, diags := parseVerified(t, defaultOverAFarBound(n)) + + assert.Equal(t, 1, countCode(diags, "pass/default-outside-type", "/components/schemas/M/properties/f"), "%d aliases", n) + } +} + +// sharedAliasPastSixtyFour is a chain of n aliases of integer and, beside its +// head, an alias K of its alias I(far), each a field of W folded against the +// other: the fold reads where the two chains meet and what each adds there. +func sharedAliasPastSixtyFour(n, far int) string { + var b strings.Builder + b.WriteString(" I0: {type: integer, description: alias 0}\n") + for i := 1; i < n; i++ { + fmt.Fprintf(&b, " I%d: {$ref: '#/components/schemas/I%d', description: alias %d}\n", i, i-1, i) + } + fmt.Fprintf(&b, " K: {$ref: '#/components/schemas/I%d', description: k}\n", far) + fmt.Fprintf(&b, " W: {allOf: [{type: object, properties: {f: {$ref: '#/components/schemas/I%d'}}}, "+ + "{type: object, properties: {f: {$ref: '#/components/schemas/K'}}}]}\n", n-1) + return componentsSpec(b.String()) +} + +// foldReports returns, sorted, the messages of the reports at pointer, each +// spelling head as , so chains of two lengths report comparably. +func foldReports(diags []ir.Diagnostic, pointer string, head ir.TypeID) []string { + var out []string + for _, diagnostic := range diags { + if string(diagnostic.Provenance.Pointer) == pointer { + out = append(out, diagnostic.Code+": "+strings.ReplaceAll(diagnostic.Message, string(head), "")) + } + } + slices.Sort(out) + return out +} + +// TestAliasChains_ASharedAliasIsReadAtAnyDepth pins sharedAlias and +// relateAliasChainTo on a long chain: the fold of a chain's head beside an +// alias of its far end gives the same field, the head, alike to the alias and +// the least, and the same reports at 70 and 200 aliases as at 60, where past 64 +// the cut chain read as no alias of that node, so the fold reported types it +// does not compare. +func TestAliasChains_ASharedAliasIsReadAtAnyDepth(t *testing.T) { + t.Parallel() + const at = "/components/schemas/W/allOf/0/properties/f" + control, controlDiags := parseVerified(t, sharedAliasPastSixtyFour(60, 0)) + want := memberOf(t, modelNamed(t, control, "W"), "f") + require.Equal(t, componentID("I59"), want.Type.Target, "the head at 60 aliases") + wantReports := foldReports(controlDiags, at, componentID("I59")) + require.NotEmpty(t, wantReports, "the fold reports at 60 aliases") + for _, n := range []int{70, 200} { + doc, diags := parseVerified(t, sharedAliasPastSixtyFour(n, 0)) + + head := componentID(fmt.Sprintf("I%d", n-1)) + assert.Equal(t, head, memberOf(t, modelNamed(t, doc, "W"), "f").Type.Target, "%d aliases take the head, as 60 do", n) + assert.Equal(t, wantReports, foldReports(diags, at, head), "%d aliases report what 60 do", n) + } +} diff --git a/compilers/openapi/e2e/settlement_composition_test.go b/compilers/openapi/e2e/settlement_composition_test.go new file mode 100644 index 000000000..0cda91398 --- /dev/null +++ b/compilers/openapi/e2e/settlement_composition_test.go @@ -0,0 +1,224 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// deepComposition is a hierarchy C0 to Cn, each level composing the one below +// and adding a member, and W folding f declared as Cn beside f declared as C0. +func deepComposition(n int) string { + var b strings.Builder + b.WriteString(" C0: {type: object, properties: {a: {type: string}}}\n") + for i := 1; i <= n; i++ { + fmt.Fprintf(&b, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}], properties: {a%d: {type: string}}}\n", i, i-1, i) + } + fmt.Fprintf(&b, " W: {allOf: [{type: object, properties: {f: {$ref: '#/components/schemas/C%d'}}}, "+ + "{type: object, properties: {f: {$ref: '#/components/schemas/C0'}}}]}\n", n) + return componentsSpec(b.String()) +} + +// TestComposition_AFieldFoldsToTheDeeperModelAtAnyDepth pins the fold's +// question whether one model composes another, answered from the reach +// index the settlement builds: a field redeclared as C70 and C0 over a 70-level hierarchy +// folds to C70, as at 60 levels, where past the walk's cap of 64 it minted a +// node composing both. +func TestComposition_AFieldFoldsToTheDeeperModelAtAnyDepth(t *testing.T) { + t.Parallel() + for _, n := range []int{60, 70, 200} { + doc, diags := parseVerified(t, deepComposition(n)) + + assertNoErrorDiags(t, diags) + field := memberOf(t, modelNamed(t, doc, "W"), "f") + assert.Equal(t, componentID(fmt.Sprintf("C%d", n)), field.Type.Target, "%d levels", n) + } +} + +// twoModelCycle is A and B composing each other, A declaring id as first and +// B as second. +func twoModelCycle(first, second string) string { + return componentsSpec(fmt.Sprintf(` A: + allOf: [{$ref: '#/components/schemas/B'}] + properties: {id: {type: %s}} + B: + allOf: [{$ref: '#/components/schemas/A'}] + properties: {id: {type: %s}} +`, first, second)) +} + +// TestComposition_ACycleGivesEveryModelTheLastDeclarationsType pins a +// two-model cycle redeclaring id apart: both models take the type of the +// declaration written last, B's, and the conflict is reported once, where each +// kept its own and each reported the other. +func TestComposition_ACycleGivesEveryModelTheLastDeclarationsType(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ first, second string }{{"integer", "string"}, {"string", "integer"}} { + doc, diags := parseVerified(t, twoModelCycle(tc.first, tc.second)) + + want := ir.PrimitiveTypeID(ir.PrimitiveKind(tc.second)) + for _, name := range []string{"A", "B"} { + assert.Equal(t, want, memberOf(t, modelNamed(t, doc, name), "id").Type.Target, "%v: %s", tc, name) + } + var conflicts int + for _, diagnostic := range diags { + if diagnostic.Code == "openapi/conflicting-redeclaration" { + conflicts++ + } + } + assert.Equal(t, 1, conflicts, "%v: said once", tc) + } +} + +// threeModelCycle is three models composing one another in a ring, in the order +// names gives, declaring id with a minimum of 1, a maximum of 9 and a minimum +// of 3. +func threeModelCycle(names [3]string) string { + var b strings.Builder + for i, bound := range []string{"minimum: 1", "maximum: 9", "minimum: 3"} { + fmt.Fprintf(&b, " %s:\n allOf: [{$ref: '#/components/schemas/%s'}]\n properties: {id: {type: integer, %s}}\n", + names[i], names[(i+1)%3], bound) + } + return componentsSpec(b.String()) +} + +// holdsBounds reports whether property holds the bounds minimum and maximum +// and no other. +func holdsBounds(property ir.Property, minimum, maximum string) bool { + constraints := property.Constraints + return constraints != nil && constraints.Min != nil && constraints.Max != nil && + string(*constraints.Min) == minimum && string(*constraints.Max) == maximum && + *constraints == ir.Constraints{Min: constraints.Min, Max: constraints.Max} +} + +// TestComposition_AThreeModelCycleSettlesToItsFixpoint pins a cycle read to +// its fixpoint: each of three models composing one another in a ring holds +// {min 3, max 9} under both namings, where the model settled first was left +// one short. +func TestComposition_AThreeModelCycleSettlesToItsFixpoint(t *testing.T) { + t.Parallel() + for _, names := range [][3]string{{"A", "B", "C"}, {"B", "C", "A"}} { + doc, diags := parseVerified(t, threeModelCycle(names)) + + assertNoErrorDiags(t, diags) + for _, name := range names { + id := memberOf(t, modelNamed(t, doc, name), "id") + assert.True(t, holdsBounds(id, "3", "9"), "named %v: %s holds %+v", names, name, id.Constraints) + } + } +} + +// longCycle is n models prefix0 to prefix(n-1), each composing the next and +// the last the first, each declaring id with a rising minimum or a falling +// maximum; first names the first model where it is not empty. +func longCycle(n int, prefix, first string) (string, []string) { + names := make([]string, n) + for i := range names { + names[i] = fmt.Sprintf("%s%d", prefix, i) + } + if first != "" { + names[0] = first + } + var b strings.Builder + for i, name := range names { + bound := fmt.Sprintf("maximum: %d", 1000-i) + if i%2 == 0 { + bound = fmt.Sprintf("minimum: %d", i) + } + fmt.Fprintf(&b, " %s: {allOf: [{$ref: '#/components/schemas/%s'}], properties: {id: {type: integer, %s}}}\n", + name, names[(i+1)%n], bound) + } + return componentsSpec(b.String()), names +} + +// TestComposition_ALongCycleFoldsAsAModelsFoldPastTheBound pins a 250-model +// cycle under two namings, the second sorting its first model last: the cycle +// folds as a model's fold does, judging the 64 declarations written first and +// reporting once that the rest are unjudged, so every model holds the bounds +// those 64 intersect to, the largest minimum and the smallest maximum among +// them. +func TestComposition_ALongCycleFoldsAsAModelsFoldPastTheBound(t *testing.T) { + t.Parallel() + const judged = 64 + for _, naming := range [][2]string{{"C", ""}, {"Z", "ZZ0"}} { + spec, names := longCycle(250, naming[0], naming[1]) + doc, diags := parseVerified(t, spec) + + var budget []ir.Diagnostic + for _, diagnostic := range diags { + if diagnostic.Code == "openapi/budget-exceeded" { + budget = append(budget, diagnostic) + } + } + require.Len(t, budget, 1, "named %v: %+v", naming, budget) + written := slices.Sorted(slices.Values(names)) + minimum, maximum := 0, 1000 + for _, name := range written[:judged] { + i := slices.Index(names, name) + if i%2 == 0 { + minimum = max(minimum, i) + } else { + maximum = min(maximum, 1000-i) + } + } + assert.Equal(t, "/components/schemas/"+written[judged]+"/properties/id", string(budget[0].Provenance.Pointer), "named %v", naming) + var short []string + for _, name := range names { + if id := memberOf(t, modelNamed(t, doc, name), "id"); !holdsBounds(id, fmt.Sprint(minimum), fmt.Sprint(maximum)) { + short = append(short, name) + } + } + assert.Empty(t, short, "named %v: the models holding another member", naming) + } +} + +// TestComposition_TwoCyclesFoldingOneNameMintTwoNodes pins where a cycle's fold +// mints: at its least member's brought form, so A and B take the node at +// A/allOf/properties/id and C and D the node at C/allOf/properties/id, each +// the values its own cycle's enums share. +func TestComposition_TwoCyclesFoldingOneNameMintTwoNodes(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, componentsSpec(` A: + allOf: [{$ref: '#/components/schemas/B'}] + properties: {id: {type: string, enum: [a, b, c]}} + B: + allOf: [{$ref: '#/components/schemas/A'}] + properties: {id: {type: string, enum: [b, c, d]}} + C: + allOf: [{$ref: '#/components/schemas/D'}] + properties: {id: {type: string, enum: [x, y, z]}} + D: + allOf: [{$ref: '#/components/schemas/C'}] + properties: {id: {type: string, enum: [y, z, w]}} +`)) + + assertNoErrorDiags(t, diags) + for _, tc := range []struct { + models []string + minted ir.TypeID + values []string + }{ + {[]string{"A", "B"}, "type/composed/components/schemas/A/allOf/properties/id", []string{"b", "c"}}, + {[]string{"C", "D"}, "type/composed/components/schemas/C/allOf/properties/id", []string{"y", "z"}}, + } { + for _, name := range tc.models { + assert.Equal(t, tc.minted, memberOf(t, modelNamed(t, doc, name), "id").Type.Target, name) + } + enum, ok := doc.Types[tc.minted].(*ir.Enum) + require.True(t, ok, "%s is minted, an enum", tc.minted) + var values []string + for _, member := range enum.Members { + values = append(values, member.Value.String) + } + assert.Equal(t, tc.values, values, "%s", tc.minted) + } +} diff --git a/compilers/openapi/e2e/settlement_own_document_test.go b/compilers/openapi/e2e/settlement_own_document_test.go new file mode 100644 index 000000000..06b5c982e --- /dev/null +++ b/compilers/openapi/e2e/settlement_own_document_test.go @@ -0,0 +1,125 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "maps" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// composingS writes a 3.1 M composing S, named by ref, and an object declaring +// a as aSchema, S's entry first where sFirst is set and the object's +// otherwise. +func composingS(ref, aSchema string, sFirst bool) string { + entries := []string{" - $ref: '" + ref + "'\n", " - type: object\n properties:\n a: " + aSchema + "\n"} + if !sFirst { + slices.Reverse(entries) + } + return "openapi: 3.1.0\ninfo: {title: m, version: '1'}\npaths: {}\ncomponents:\n schemas:\n M:\n allOf:\n" + + strings.Join(entries, "") +} + +// foldAcrossDocuments compiles main beside other.yaml, which declares S, and +// returns M's member a and every finding. +func foldAcrossDocuments(t *testing.T, main, other string) (ir.Property, []ir.Diagnostic) { + t.Helper() + dir := t.TempDir() + layout(t, dir, map[string]string{"main.yaml": main, "other.yaml": other}) + doc, diags := compileOnDisk(t, filepath.Join(dir, "main.yaml"), main, false) + return memberOf(t, modelNamed(t, doc, "M"), "a"), diags +} + +// foldInOneDocument compiles main with S declared beside M, and returns M's +// member a and every finding. +func foldInOneDocument(t *testing.T, main, sDeclaration string) (ir.Property, []ir.Diagnostic) { + t.Helper() + dir := t.TempDir() + source := main + " S:\n" + sDeclaration + doc, diags := compileOnDisk(t, filepath.Join(dir, "main.yaml"), source, false) + return memberOf(t, modelNamed(t, doc, "M"), "a"), diags +} + +// sortedCodesOf is the codes of diags, sorted. +func sortedCodesOf(diags []ir.Diagnostic) []string { + return slices.Sorted(slices.Values(codesOf(diags))) +} + +// sDeclaringAnObjectA is S declaring a as an object with a member x. +const sDeclaringAnObjectA = " type: object\n properties:\n a:\n properties:\n x: {}\n" + +// TestOwnDocument_AMemberRedeclaredAcrossTwoDocumentsFoldsAsInOne pins a site +// read in its own document: a member M declares a string and S, in another +// document, declares an object folds, in both orders, as the same two +// declarations in one document fold, with nothing reported, where the walk +// read the other document's site as unplaced and so disjoint, and reported a +// conflict. +func TestOwnDocument_AMemberRedeclaredAcrossTwoDocumentsFoldsAsInOne(t *testing.T) { + t.Parallel() + other := "openapi: 3.1.0\ninfo: {title: o, version: '1'}\npaths: {}\ncomponents:\n schemas:\n S:\n" + sDeclaringAnObjectA + for _, sFirst := range []bool{true, false} { + want, wantDiags := foldInOneDocument(t, composingS("#/components/schemas/S", "{type: string}", sFirst), sDeclaringAnObjectA) + got, diags := foldAcrossDocuments(t, composingS("other.yaml#/components/schemas/S", "{type: string}", sFirst), other) + + assert.Equal(t, want.Type.Target, got.Type.Target, "S first %v", sFirst) + assert.Equal(t, sortedCodesOf(wantDiags), sortedCodesOf(diags), "S first %v", sFirst) + assert.Zero(t, countCode(diags, "openapi/conflicting-redeclaration", "/components/schemas/M/allOf/0/properties/a"), "S first %v", sFirst) + assert.Empty(t, got.Unmodeled, "S first %v: nothing kept", sFirst) + } +} + +// TestOwnDocument_TwoReferencesInAnotherDocumentReadAlike pins DeclarationsAdmitAlike read in +// the sites' own document: two declarations in another document whose not +// writes one $ref read it against one base, so the member keeps one entry and +// the fold reports nothing, as in one document, where the fold reported the +// entries given differently. +func TestOwnDocument_TwoReferencesInAnotherDocumentReadAlike(t *testing.T) { + t.Parallel() + declarations := " X: {type: string, const: bad}\n" + + " S:\n type: object\n properties:\n a: {type: string, not: {$ref: '#/components/schemas/X'}}\n" + + " T:\n type: object\n properties:\n a: {type: string, not: {$ref: '#/components/schemas/X'}}\n" + composing := func(prefix string) string { + return "openapi: 3.1.0\ninfo: {title: m, version: '1'}\npaths: {}\ncomponents:\n schemas:\n M:\n allOf:\n" + + " - $ref: '" + prefix + "#/components/schemas/S'\n - $ref: '" + prefix + "#/components/schemas/T'\n" + } + dir := t.TempDir() + other := "openapi: 3.1.0\ninfo: {title: o, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + declarations + layout(t, dir, map[string]string{"other.yaml": other}) + single, singleDiags := compileOnDisk(t, filepath.Join(dir, "single.yaml"), composing("")+declarations, false) + across, diags := compileOnDisk(t, filepath.Join(dir, "main.yaml"), composing("other.yaml"), false) + + assert.Equal(t, sortedCodesOf(singleDiags), sortedCodesOf(diags)) + assert.Zero(t, countCode(diags, "openapi/degraded-construct", "/components/schemas/M/allOf/0"), "no entries given differently") + want, got := memberOf(t, modelNamed(t, single, "M"), "a"), memberOf(t, modelNamed(t, across, "M"), "a") + require.Contains(t, got.Unmodeled, "openapi:not") + assert.Equal(t, slices.Sorted(maps.Keys(want.Unmodeled)), slices.Sorted(maps.Keys(got.Unmodeled))) +} + +// TestOwnDocument_AFalseNullableInA30DocumentReadsByItsOwnDialect pins a site +// read by its own document's dialect: a member one declaration of which, in a +// 3.0 document, writes nullable: false beside a 3.1 declaration writing +// nothing of null folds, in both orders, as two declarations writing nothing +// of null do. M's declaration narrows S's, so M declares the member and the +// fold reads both. +func TestOwnDocument_AFalseNullableInA30DocumentReadsByItsOwnDialect(t *testing.T) { + t.Parallel() + other := "openapi: 3.0.3\ninfo: {title: o, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + + " S:\n type: object\n properties:\n a: {type: string, nullable: false}\n" + for _, sFirst := range []bool{true, false} { + want, wantDiags := foldInOneDocument(t, composingS("#/components/schemas/S", "{type: string, maxLength: 5}", sFirst), + " type: object\n properties:\n a: {type: string}\n") + got, diags := foldAcrossDocuments(t, composingS("other.yaml#/components/schemas/S", "{type: string, maxLength: 5}", sFirst), other) + + assert.Equal(t, want.Type, got.Type, "S first %v", sFirst) + assert.Equal(t, sortedCodesOf(wantDiags), sortedCodesOf(diags), "S first %v", sFirst) + assert.Empty(t, got.Unmodeled, "S first %v: nothing kept", sFirst) + } +} diff --git a/compilers/openapi/e2e/settlement_steps_test.go b/compilers/openapi/e2e/settlement_steps_test.go new file mode 100644 index 000000000..0dd1571a4 --- /dev/null +++ b/compilers/openapi/e2e/settlement_steps_test.go @@ -0,0 +1,168 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// stepOrders is every order of three distinct multipleOf steps whose least +// common multiple, 60, none of them writes. +var stepOrders = [][3]string{{"4", "6", "10"}, {"4", "10", "6"}, {"6", "4", "10"}, {"6", "10", "4"}, {"10", "4", "6"}, {"10", "6", "4"}} + +// threeStepsEachWay writes steps three ways: in one schema, beside its allOf +// entries; as three declarations of one field; and as two alias chains of one +// integer, I2 over I1 and J1, whose views the fold intersects. +func threeStepsEachWay(steps [3]string) string { + a, b, c := steps[0], steps[1], steps[2] + return componentsSpec(fmt.Sprintf(` Flat: {type: integer, multipleOf: %[1]s, allOf: [{multipleOf: %[2]s}, {multipleOf: %[3]s}]} + Fold: + allOf: + - {type: object, properties: {n: {type: integer, multipleOf: %[1]s}}} + - {type: object, properties: {n: {type: integer, multipleOf: %[2]s}}} + - {type: object, properties: {n: {type: integer, multipleOf: %[3]s}}} + I0: {type: integer} + I1: {$ref: '#/components/schemas/I0', multipleOf: %[1]s} + I2: {$ref: '#/components/schemas/I1', multipleOf: %[2]s} + J1: {$ref: '#/components/schemas/I0', multipleOf: %[3]s} + Chain: + allOf: + - {type: object, properties: {n: {$ref: '#/components/schemas/I2'}}} + - {type: object, properties: {n: {$ref: '#/components/schemas/J1'}}} +`, a, b, c)) +} + +// stepOf returns the multipleOf a constraint set holds, "" for none. +func stepOf(constraints *ir.Constraints) string { + if constraints == nil || constraints.MultipleOf == nil { + return "" + } + return string(*constraints.MultipleOf) +} + +// TestSteps_ThreeStepsIntersectAlikeInEveryOrder pins the one intersection the +// schema, the fold and the view intersect through: three distinct steps +// intersect to 60 in each of their six orders, written in one schema, as three +// declarations of a field, or along two alias chains the fold reads the views +// of. +func TestSteps_ThreeStepsIntersectAlikeInEveryOrder(t *testing.T) { + t.Parallel() + for _, steps := range stepOrders { + doc, diags := parseVerified(t, threeStepsEachWay(steps)) + + assertNoErrorDiags(t, diags) + flat, ok := typeByName(doc, "Flat").(*ir.Scalar) + require.True(t, ok, "%v: Flat lowers to a scalar", steps) + assert.Equal(t, "60", stepOf(flat.Constraints), "%v: in one schema", steps) + assert.Equal(t, "60", stepOf(memberOf(t, modelNamed(t, doc, "Fold"), "n").Constraints), "%v: as three declarations", steps) + chained := memberOf(t, modelNamed(t, doc, "Chain"), "n") + minted, ok := doc.Types[chained.Type.Target].(*ir.Scalar) + require.True(t, ok, "%v: the fold of two chains is a scalar", steps) + assert.Equal(t, "60", stepOf(minted.Constraints), "%v: along two chains", steps) + } +} + +// stepPair writes steps x and y in one schema beside its allOf entry, and as +// two models' declarations of a field another model composes both of. +func stepPair(x, y string) string { + return componentsSpec(fmt.Sprintf(` Flat: {type: number, multipleOf: %[1]s, allOf: [{multipleOf: %[2]s}]} + A: {type: object, properties: {n: {type: number, multipleOf: %[1]s}}} + B: {type: object, properties: {n: {type: number, multipleOf: %[2]s}}} + AB: {allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]} +`, x, y)) +} + +// TestSteps_TwoLongStepsOneTwiceTheOtherIntersectToTheLarger pins the +// intersection's bound at each step's numerator: two 600-digit steps, one twice +// the other, intersect to the larger in one schema and in a fold, with nothing +// reported or kept, where a bound on the digits between them refused the pair. +func TestSteps_TwoLongStepsOneTwiceTheOtherIntersectToTheLarger(t *testing.T) { + t.Parallel() + ones, twos := strings.Repeat("1", 600), strings.Repeat("2", 600) + doc, diags := parseVerified(t, stepPair(ones, twos)) + + assert.Zero(t, countCode(diags, "openapi/degraded-construct", "/components/schemas/Flat/allOf/0")) + assert.Zero(t, countCode(diags, "openapi/conflicting-redeclaration", "/components/schemas/A/properties/n")) + flat, ok := typeByName(doc, "Flat").(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, twos, stepOf(flat.Constraints)) + assert.Empty(t, flat.Unmodeled, "no entry is kept") + assert.Equal(t, twos, stepOf(memberOf(t, modelNamed(t, doc, "AB"), "n").Constraints)) +} + +// TestSteps_AStepWhoseNumeratorPassesTheBoundIsRefused pins the refusal the +// numerator bound adds: 1e2000 beside 3e2000, whose numerators pass 1,024 +// digits, is refused in one schema, the entry kept and reported, and in a fold, +// which reports the conflict and keeps the last declaration's step, where a +// bound on the digits written intersected them to 3e2000. +func TestSteps_AStepWhoseNumeratorPassesTheBoundIsRefused(t *testing.T) { + t.Parallel() + doc, diags := parseVerified(t, stepPair("1e2000", "3e2000")) + + assert.Equal(t, 1, countCode(diags, "openapi/degraded-construct", "/components/schemas/Flat/allOf/0")) + assert.Equal(t, 1, countCode(diags, "openapi/conflicting-redeclaration", "/components/schemas/A/properties/n")) + flat, ok := typeByName(doc, "Flat").(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, "1e2000", stepOf(flat.Constraints), "the schema's own step") + assert.Contains(t, flat.Unmodeled, "openapi:allOf/0", "the entry it cannot intersect, kept") + assert.Equal(t, "3e2000", stepOf(memberOf(t, modelNamed(t, doc, "AB"), "n").Constraints), "the last declaration's step") +} + +// TestSteps_AConflictingPatternLeavesTheLengthsJudged pins the pass's settle +// over an intersection: two patterns no one value holds conflict, and the +// lengths beside them are still judged, so a minimum of 5 under a maximum of 2 +// draws pass/bounds-admit-no-value with the patterns apart and alike. +func TestSteps_AConflictingPatternLeavesTheLengthsJudged(t *testing.T) { + t.Parallel() + _, diags := parseVerified(t, componentsSpec(` A: {type: string, pattern: '^a', maxLength: 2} + B: {allOf: [{$ref: '#/components/schemas/A'}], pattern: '^b', minLength: 5} + C: {allOf: [{$ref: '#/components/schemas/A'}], minLength: 5} +`)) + + for _, name := range []string{"B", "C"} { + assert.Equal(t, 1, countCode(diags, "pass/bounds-admit-no-value", "/components/schemas/"+name), name) + } +} + +// defaultUnderAStep is a field declared a multiple of 7 in one entry and given +// value as its default in another. +func defaultUnderAStep(value string) string { + return componentsSpec(fmt.Sprintf(` M: + allOf: + - {type: object, properties: {n: {type: integer, multipleOf: 7}}} + - {type: object, properties: {n: {type: integer, default: %s}}} +`, value)) +} + +// TestSteps_ADefaultPastTheJudgmentsBoundIsAdoptedUnjudged pins the +// multiple-of judgment's bound in the fold: under a step of 7, a default of +// 1,023 digits, 1,024 between them, is judged, a multiple adopted and one off +// the step refused, while one of 1,024 digits, which the judgment reads no +// further, is adopted unjudged, since what it cannot read refuses nothing. +func TestSteps_ADefaultPastTheJudgmentsBoundIsAdoptedUnjudged(t *testing.T) { + t.Parallel() + for value, adopted := range map[string]bool{ + strings.Repeat("7", 1023): true, + strings.Repeat("7", 1022) + "8": false, + strings.Repeat("7", 1023) + "8": true, + } { + doc, diags := parseVerified(t, defaultUnderAStep(value)) + + assertNoErrorDiags(t, diags) + field := memberOf(t, modelNamed(t, doc, "M"), "n") + if !adopted { + assert.Nil(t, field.Default, "%d digits: not adopted", len(value)) + continue + } + require.NotNil(t, field.Default, "%d digits: adopted", len(value)) + assert.Equal(t, ir.BigVal(value), field.Default.Number) + } +} diff --git a/compilers/openapi/e2e/streaming_test.go b/compilers/openapi/e2e/streaming_test.go index d46a5e075..662ca3c93 100644 --- a/compilers/openapi/e2e/streaming_test.go +++ b/compilers/openapi/e2e/streaming_test.go @@ -131,11 +131,11 @@ func assertStreamingMedia30(t *testing.T, doc *ir.Document, _ []ir.Diagnostic) { assert.Equal(t, ir.Inferred("streaming-inference"), operation.Provenance.Inferred) } -// assertStreamingMedia31 is the corpus row for what assertStreamingMedia30 leaves -// out, which a 3.0 document lowers alike: a request that streams beside its -// response, one that streams alone, a response whose two streaming contents name -// different element types, where none is elected, one whose two name the same, -// where it is, and a plain body beside a stream (assertTailMetrics). +// assertStreamingMedia31 is the corpus row for what assertStreamingMedia30 +// leaves out, which a 3.0 document lowers alike: a request that streams beside +// its response, one that streams alone, a response whose two streaming contents +// name different element types, where none is chosen, one whose two name the +// same, where it is, and a plain body beside a stream (assertTailMetrics). // // The two responses streaming twice say what the refusal is for. Refusing on // the count alone would pass the first and fail the second, and content @@ -165,7 +165,7 @@ func assertStreamingMedia31(t *testing.T, doc *ir.Document, diags []ir.Diagnosti require.True(t, ok) assert.Equal(t, ir.StreamingServer, either.Streaming) require.NotNil(t, either.ResponseStream) - assert.Nil(t, either.ResponseStream.Events, "two streaming contents elect no element type") + assert.Nil(t, either.ResponseStream.Events, "two streaming contents choose no element type") require.NotNil(t, either.Responses[0].Payload) assert.Len(t, either.Responses[0].Payload.Contents, 2, "both contents are still kept") assert.True(t, openapitest.HasDiag(diags, "openapi/degraded-construct"), @@ -185,7 +185,7 @@ func assertStreamingMedia31(t *testing.T, doc *ir.Document, diags []ir.Diagnosti assert.Equal(t, ir.StreamingServer, negotiated.Streaming) require.NotNil(t, negotiated.ResponseStream) require.NotNil(t, negotiated.ResponseStream.Events, - "two contents naming one element type elect it: there is nothing to choose between") + "two contents naming one element type choose it: there is nothing to choose between") assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Frame"), negotiated.ResponseStream.Events.Target) require.NotNil(t, negotiated.Responses[0].Payload) @@ -226,6 +226,6 @@ func assertTailMetrics(t *testing.T, doc *ir.Document) { assert.Equal(t, guessed, failure.Contents[0].Stream, "an error's content streams too") assert.Equal(t, ir.StreamingServer, metrics.Streaming) require.NotNil(t, metrics.ResponseStream) - require.NotNil(t, metrics.ResponseStream.Events, "only the success response's stream is elected from") + require.NotNil(t, metrics.ResponseStream.Events, "only the success response's stream is chosen from") assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Frame"), metrics.ResponseStream.Events.Target) } diff --git a/compilers/openapi/e2e/text_bounds_reach_test.go b/compilers/openapi/e2e/text_bounds_reach_test.go new file mode 100644 index 000000000..46795f2bd --- /dev/null +++ b/compilers/openapi/e2e/text_bounds_reach_test.go @@ -0,0 +1,120 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// referenceTextSchemas write a length, a pattern or a numeric bound beside a +// reference to a number carried as text and to an instant: beside the $ref, +// beside an allOf over it, on an inline entry of one, and at a property, where +// also beside an inline uuid on another entry, the type on one entry and the +// format on another. +var referenceTextSchemas = []string{ + "N: {type: string, format: int64}", + "I: {type: string, format: date-time}", + "Beside: {allOf: [{$ref: '#/components/schemas/N'}], minLength: 2}", + "Ref: {$ref: '#/components/schemas/N', minimum: 5, maxLength: 9}", + "Entry: {allOf: [{$ref: '#/components/schemas/N'}, {minLength: 2}]}", + "EntryMin: {allOf: [{$ref: '#/components/schemas/N'}, {minimum: 5}]}", + "RefI: {$ref: '#/components/schemas/I', maxLength: 9, minimum: 1}", + "EntryI: {allOf: [{$ref: '#/components/schemas/I'}, {maxLength: 9}]}", + "Loose: {format: date-time}", + "ByLoose: {$ref: '#/components/schemas/Loose', maxLength: 9}", + "Holder: {type: object, properties: {viaEntry: {allOf: [{$ref: '#/components/schemas/N'}, {minLength: 2}]}, " + + "viaRef: {$ref: '#/components/schemas/I', maxLength: 9}, " + + "viaPrincipal: {allOf: [{type: string, format: uuid}, {maxLength: 9}]}, " + + "viaKind: {allOf: [{type: string}, {format: uuid, maxLength: 9}]}}}", +} + +// TestTextBounds_AReferenceToTextOfAnotherKindKeepsItsBounds holds a bound +// written beside a reference whose referent's value is text of another kind +// to what the referent keeps flat, and one beside a format no type selects +// to the top type's Constraints: the alias or the carrier keeps a length, +// a pattern and, beside a number carried as text, a numeric bound verbatim +// with no IR home and one info at it, holds none, and a numeric bound beside +// an instant applies to none of its kinds, degraded as at the base. It holds +// in both declaration orders, the referent built before its use or after. +func TestTextBounds_AReferenceToTextOfAnotherKindKeepsItsBounds(t *testing.T) { + t.Parallel() + inBothOrders(t, referenceTextSchemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + for name, kept := range map[string][]string{ + "Beside": {"openapi:minLength"}, "Ref": {"openapi:maxLength", "openapi:minimum"}, + "Entry": {"openapi:minLength"}, "EntryMin": {"openapi:minimum"}, + "RefI": {"openapi:maxLength"}, "EntryI": {"openapi:maxLength"}, + } { + node := doc.Types[ir.TypeID("type/openapi/components/schemas/"+name)] + require.NotNil(t, node, name) + assert.Nil(t, heldConstraints(node), "%s holds no bound of the text", name) + assert.Equal(t, kept, keptNoHome(node.Common().Unmodeled), "%s keeps", name) + assert.Equal(t, len(kept), infosAt(diags, diag.UnhomedConstruct, "/components/schemas/"+name, ""), "%s reports each once", name) + } + byLoose, ok := doc.Types["type/openapi/components/schemas/ByLoose"].(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, []string{"maxLength"}, heldMembers(t, byLoose.Constraints), "a format beside no type selects nothing: the top type's text") + refI, ok := doc.Types["type/openapi/components/schemas/RefI"].(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, ir.ReasonDegradedLowering, refI.Unmodeled["openapi:minimum"].Reason, "a bound of no kind an instant takes, as at the base") + for wire, keyword := range map[string]string{ + "viaEntry": "openapi:minLength", "viaRef": "openapi:maxLength", + "viaPrincipal": "openapi:maxLength", "viaKind": "openapi:maxLength", + } { + property := componentMemberOf(t, doc, "Holder", wire) + assert.Nil(t, property.Constraints, wire) + assert.Equal(t, []string{keyword}, keptNoHome(property.Unmodeled), wire) + requireNoNodeAt(t, doc, "/components/schemas/Holder/properties/"+wire) + } + }) +} + +// TestTextBounds_AnEnumOrATypeListOfAnotherKindsTextKeepsIt holds an Enum +// whose ValueType is a uuid to keeping a length of its members' text verbatim, +// the uuid written flat, on another conjunct or beside an allOf over the enum, +// where an Enum of strings holds it; and a type list's date variant to keeping +// one written beside the list on a Scalar hoisted for it, the Union keeping +// none. +func TestTextBounds_AnEnumOrATypeListOfAnotherKindsTextKeepsIt(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", + "EU: {type: string, format: uuid, enum: ['123e4567-e89b-12d3-a456-426614174000'], maxLength: 36}", + "EV: {allOf: [{type: string, format: uuid, enum: ['123e4567-e89b-12d3-a456-426614174000']}, {maxLength: 36}]}", + "EC: {allOf: [{type: string, format: uuid}, {enum: ['123e4567-e89b-12d3-a456-426614174000']}, {maxLength: 36}]}", + "EB: {allOf: [{type: string, format: uuid, enum: ['123e4567-e89b-12d3-a456-426614174000']}], maxLength: 36}", + "EP: {allOf: [{type: string, format: uuid, enum: ['123e4567-e89b-12d3-a456-426614174000'], minLength: 1}], maxLength: 36}", + "ES: {type: string, enum: [a, b], maxLength: 3}", + "TL: {type: [string, integer], format: date, maxLength: 5}")) + for name, kept := range map[string]bool{"EU": true, "EV": true, "EC": true, "EB": true, "ES": false} { + enum, ok := doc.Types[ir.TypeID("type/openapi/components/schemas/"+name)].(*ir.Enum) + require.True(t, ok, name) + if !kept { + require.NotNil(t, enum.Constraints, name) + assert.NotNil(t, enum.Constraints.MaxLength, "%s holds the length of its strings", name) + continue + } + assert.Equal(t, ir.PrimitiveUUID, enum.ValueType, name) + assert.Nil(t, enum.Constraints, name) + assert.Equal(t, []string{"openapi:maxLength"}, keptNoHome(enum.Unmodeled), name) + assert.Equal(t, 1, infosAt(diags, diag.UnhomedConstruct, "/components/schemas/"+name, ""), name) + } + both, ok := doc.Types["type/openapi/components/schemas/EP"].(*ir.Enum) + require.True(t, ok) + assert.Equal(t, []string{"openapi:maxLength", "openapi:minLength"}, keptNoHome(both.Unmodeled), "the position's and the principal's") + assert.Equal(t, 2, infosAt(diags, diag.UnhomedConstruct, "/components/schemas/EP", "")) + union, ok := doc.Types["type/openapi/components/schemas/TL"].(*ir.Union) + require.True(t, ok) + assert.Empty(t, union.Unmodeled) + require.Len(t, union.Variants, 2) + variant, ok := doc.Types[union.Variants[0].Type.Target].(*ir.Scalar) + require.True(t, ok, "the date variant is hoisted to keep the length") + assert.Nil(t, variant.Constraints) + assert.Equal(t, []string{"openapi:maxLength"}, keptNoHome(variant.Unmodeled)) +} diff --git a/compilers/openapi/e2e/text_bounds_test.go b/compilers/openapi/e2e/text_bounds_test.go new file mode 100644 index 000000000..ae7efb5cf --- /dev/null +++ b/compilers/openapi/e2e/text_bounds_test.go @@ -0,0 +1,153 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// textBoundsSpec writes a length, a pattern or a numeric bound beside each kind +// of value: an instant, a uuid, a url, base64 text, octets, a number carried +// as text, a string, the top type, an integer, and unions holding text, a +// number or an instant beside an integer, with a carrier over a shared uuid. +func textBoundsSpec() string { + return admissionSpec("3.1.0", "", + "Instant: {type: string, format: date-time, maxLength: 5}", + "Id: {type: string, format: uuid, minLength: 36, pattern: '^[0-9a-f-]+$'}", + "Link: {type: string, format: uri, maxLength: 9}", + "Blob: {type: string, format: byte, minLength: 4, maxLength: 20}", + "Bin: {type: string, format: binary, maxLength: 20}", + "Num: {type: string, format: int64, maxLength: 3}", + "NumMin: {type: string, format: int64, minimum: 3}", + "Plain: {type: string, maxLength: 3}", + "TopLength: {minLength: 2}", + "TopMinimum: {minimum: 2}", + "IntLength: {type: integer, maxLength: 3}", + "Port: {anyOf: [{type: integer}, {type: string}], minimum: 1, maximum: 65535}", + "TextOrInt: {anyOf: [{type: string}, {type: integer}], maxLength: 5}", + "InstantOrInt: {anyOf: [{type: string, format: date-time}, {type: integer}], maxLength: 5}", + "Holder: {type: object, properties: {wm: {type: string, format: uuid, maxLength: 36, minLength: 1}}}") +} + +// textBoundRow is where one schema's bounds land: the keywords its node, or +// its carrier, keeps verbatim with no IR home, and the bounds its Constraints +// hold, by JSON member. +type textBoundRow struct { + name string + kept []string + held []string +} + +// heldMembers lists the JSON members constraints sets, uniqueItems aside. +func heldMembers(t *testing.T, constraints *ir.Constraints) []string { + t.Helper() + if constraints == nil { + return nil + } + var out []string + for member := range marshalToMap(t, constraints) { + if member != "uniqueItems" { + out = append(out, member) + } + } + slices.Sort(out) + return out +} + +// keptNoHome lists the keywords unmodeled keeps with no IR home. +func keptNoHome(unmodeled ir.Unmodeled) []string { + var out []string + for key, entry := range unmodeled { + if entry.Reason == ir.ReasonNoIRHome { + out = append(out, key) + } + } + slices.Sort(out) + return out +} + +// TestTextBounds_AKeywordOfTheTextBindsOnlyText holds a length, pattern or +// text format to a node whose value is that text, a string, the top type, +// octets, or a union whose text variants are strings: written of another +// kind's text, an instant, a uuid, a url, base64 or a number carried as text, +// it is kept verbatim with no IR home and one info at the keyword. A numeric +// bound binds a number carried as a number alone, and a bound applying to +// none of a node's kinds stays degraded, as at the base. +func TestTextBounds_AKeywordOfTheTextBindsOnlyText(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, textBoundsSpec()) + for _, row := range []textBoundRow{ + {"Instant", []string{"openapi:maxLength"}, nil}, + {"Id", []string{"openapi:minLength", "openapi:pattern"}, nil}, + {"Link", []string{"openapi:maxLength"}, nil}, + {"Blob", []string{"openapi:maxLength", "openapi:minLength"}, nil}, + {"Bin", nil, []string{"maxLength"}}, + {"Num", []string{"openapi:maxLength"}, nil}, + {"NumMin", []string{"openapi:minimum"}, nil}, + {"Plain", nil, []string{"maxLength"}}, + {"TopLength", nil, []string{"minLength"}}, + {"TopMinimum", nil, []string{"min"}}, + {"IntLength", nil, nil}, + {"Port", nil, []string{"max", "min"}}, + {"TextOrInt", nil, []string{"maxLength"}}, + {"InstantOrInt", []string{"openapi:maxLength"}, nil}, + } { + node := doc.Types[ir.TypeID("type/openapi/components/schemas/"+row.name)] + require.NotNil(t, node, row.name) + assert.Equal(t, row.kept, keptNoHome(node.Common().Unmodeled), "%s keeps", row.name) + assert.Equal(t, row.held, heldMembers(t, heldConstraints(node)), "%s holds", row.name) + for _, key := range row.kept { + pointer := "/components/schemas/" + row.name + "/" + key[len("openapi:"):] + assert.Equal(t, 1, infosAt(diags, diag.UnhomedConstruct, pointer, ""), "one info at %s", pointer) + assert.Zero(t, infosAt(diags, diag.DegradedConstruct, pointer, ""), "under the unhomed code at %s", pointer) + } + } + intLength, ok := doc.Types["type/openapi/components/schemas/IntLength"].(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, ir.ReasonDegradedLowering, intLength.Unmodeled["openapi:maxLength"].Reason, "a bound of no kind the node takes, as at the base") +} + +// TestTextBounds_ACarrierOverASharedPrimitiveKeepsItsOwn holds a property over +// the shared uuid primitive writing two lengths: the carrier keeps both in its +// own Unmodeled with an info each, holds no Constraints, and no node is +// hoisted for it, as the golden spec's watermark ID is written. +func TestTextBounds_ACarrierOverASharedPrimitiveKeepsItsOwn(t *testing.T) { + t.Parallel() + doc, diags := compileUnrefused(t, textBoundsSpec()) + wm := componentMemberOf(t, doc, "Holder", "wm") + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveUUID), wm.Type.Target) + assert.Nil(t, wm.Constraints) + assert.Equal(t, []string{"openapi:maxLength", "openapi:minLength"}, keptNoHome(wm.Unmodeled)) + for _, keyword := range []string{"maxLength", "minLength"} { + assert.Equal(t, 1, infosAt(diags, diag.UnhomedConstruct, "/components/schemas/Holder/properties/wm/"+keyword, ""), keyword) + } + requireNoNodeAt(t, doc, "/components/schemas/Holder/properties/wm") +} + +// TestTextBounds_TheFoldStillRefusesAnOverlongInstant holds what moving a +// length off an instant leaves: the fold reads the kept length through its +// source format, so it still refuses an over-long default another +// declaration writes, while pass, holding no source format, no longer +// reports the same default written beside its bound at one use. +func TestTextBounds_TheFoldStillRefusesAnOverlongInstant(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", + "F: {allOf: [{type: object, properties: {t: {type: string, format: date-time, maxLength: 5}}}, "+ + "{type: object, properties: {t: {type: string, format: date-time, default: '2024-01-01T00:00:00Z'}}}]}", + "H: {type: object, properties: {at: {type: string, format: date-time, maxLength: 5, default: '2024-01-01T00:00:00Z'}}}") + inBothAllOfOrders(t, spec, func(t *testing.T, spec string) { + doc, diags := compiledAndValidated(t, spec) + assert.Nil(t, componentMemberOf(t, doc, "F", "t").Default, "the fold refuses the default by the kept length") + assert.Equal(t, 1, infosAt(diags, diag.DegradedConstruct, "", "admits the default"), "and says so once") + assert.NotNil(t, componentMemberOf(t, doc, "H", "at").Default, "a use keeps its own default") + assert.Empty(t, codedPointers(diags, "pass/default-outside-type"), "which pass no longer reads the kept length against") + }) +} diff --git a/compilers/openapi/e2e/type_list_variants_test.go b/compilers/openapi/e2e/type_list_variants_test.go new file mode 100644 index 000000000..0066fd777 --- /dev/null +++ b/compilers/openapi/e2e/type_list_variants_test.go @@ -0,0 +1,57 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// draft07Items is the items of a type list's array variant, a draft 7 resource +// of its own, named by its $id's last segment. +func draft07Items(name, body string) string { + return "items: {$id: 'https://example.com/" + name + "', $schema: 'http://json-schema.org/draft-07/schema#', " + body + "}" +} + +// typeListVariantSchemas are GitHub #1888's and #2103's reproductions: a type +// list's object, scalar and array variants, one a kind inference infers, one a +// subtype composes, and one a $ref to its entry reads beside its own. +var typeListVariantSchemas = []string{ + "Obj: {type: [string, object], properties: {a: {type: string}}, minProperties: 99999999999999999999}", + "Enc: {type: [string, integer], format: x-mine, contentSchema: {type: object, properties: {a: {type: string}}}, contentMediaType: application/json}", + "R: {$ref: '#/components/schemas/Enc/contentSchema'}", + "Inf: {items: {type: string}, properties: {a: {type: string}}, minProperties: 99999999999999999999}", + "Cat: {allOf: [{$ref: '#/components/schemas/Pet'}, {type: object, properties: {meow: {type: boolean}}}]}", + "Pet: {type: [string, 'null', object], properties: {kind: {type: string}, name: {type: string}}, required: [kind], " + + "discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}}", + "Listed: {type: [string, array], " + draft07Items("a", "type: array, items: [{type: string}]") + "}", + "VDep: {type: [string, array], " + draft07Items("vd", "type: object, properties: {a: {type: string}}, dependencies: {a: [b]}") + "}", + "PDep: {type: array, " + draft07Items("pd", "type: object, properties: {a: {type: string}}, dependencies: {a: [b]}") + "}", + "X: {allOf: [{type: [string, object], properties: {a: {type: string}}, minLength: 2}], description: d}", + "RX: {$ref: '#/components/schemas/X/allOf/0'}", +} + +// TestTypeList_TwoVariantsOfOneSchemaShareItsDeclarations holds two variants +// reading one schema object, a type list on an allOf entry and a $ref to that +// entry, to one declaration: each model holds the property the schema writes, +// under the one ID its written pointer names, as a model and its entry's +// model share one at the base. +func TestTypeList_TwoVariantsOfOneSchemaShareItsDeclarations(t *testing.T) { + t.Parallel() + inBothOrders(t, typeListVariantSchemas, func(t *testing.T, schemas []string) { + doc, _ := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + const declaration = "property/openapi/components/schemas/X/allOf/0/properties/a" + for _, id := range []ir.TypeID{"type/anonymous/components/schemas/X/type/1", "type/anonymous/components/schemas/X/allOf/0/type/1"} { + model, ok := kindNode(t, doc, id).(*ir.Model) + require.True(t, ok, "%s is the object variant", id) + require.Len(t, model.Properties, 1, id) + assert.Equal(t, ir.PropertyID(declaration), model.Properties[0].ID, id) + assert.Equal(t, "/components/schemas/X/allOf/0/properties/a", string(model.Properties[0].Provenance.Pointer), id) + } + }) +} diff --git a/compilers/openapi/e2e/unevaluated_scope_test.go b/compilers/openapi/e2e/unevaluated_scope_test.go new file mode 100644 index 000000000..10212f10d --- /dev/null +++ b/compilers/openapi/e2e/unevaluated_scope_test.go @@ -0,0 +1,157 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// unevaluatedTargets are the components the unevaluated rows compose or +// reference. +var unevaluatedTargets = []string{ + "B: {type: object, properties: {a: {type: integer}}, additionalProperties: {type: string}}", + "BC: {type: object, additionalProperties: {type: integer}}", + "BU: {type: object, properties: {a: {type: integer}}, unevaluatedProperties: false}", + "T: {type: object, properties: {a: {type: integer}}, if: {required: [a]}, then: {properties: {k: {type: integer}}}}", + "AItems: {type: array, items: {type: string}}", + "APrefix: {type: array, prefixItems: [{type: string}]}", + "P: {type: object, properties: {x: {type: integer}}}", + "Q: {type: object, properties: {y: {type: integer}}}", + "U: {oneOf: [{$ref: '#/components/schemas/P'}, {$ref: '#/components/schemas/Q'}]}", + "A: {type: object, properties: {t: {type: string}, a: {type: integer}}}", + "AB: {type: object, properties: {t: {type: string}, b: {type: integer}}}", + "TA: {type: object, properties: {t: {const: a}, a: {type: integer}}, required: [t]}", + "TB: {type: object, properties: {t: {const: b}, b: {type: integer}}, required: [t]}", + "EA: {type: object, properties: {t: {enum: [a, c]}, a: {type: integer}}, required: [t]}", + "EB: {type: object, properties: {t: {enum: [b]}, b: {type: integer}}, required: [t]}", +} + +// unevaluatedRef is a $ref to the component named, as a one-line YAML +// mapping. +func unevaluatedRef(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } + +// TestUnevaluated_AnUntypedEvaluatorKeepsTheKeyword holds #1904's other half: +// where the evaluation reaches an evaluator the IR does not type into the node +// the closure reads over, beside the keyword or in a schema a $ref brings, the +// keyword is kept verbatim under openapi:unevaluated, once, on the node, a +// distributed union's on the Union, and no model is closed after composition. A distributed oneOf whose branches may both match, with a +// discriminator or without, and a distributed anyOf are such evaluators; one +// whose branches require disjoint const or enum tags is not, and closes. +func TestUnevaluated_AnUntypedEvaluatorKeepsTheKeyword(t *testing.T) { + t.Parallel() + const body = "type: object, properties: {c: {type: string}}, " + schemas := append(slices.Clone(unevaluatedTargets), + "Conditional: {type: object, properties: {a: {type: string}}, if: {required: [a]}, then: {properties: {b: {type: string}}}, unevaluatedProperties: false}", + "Dependent: {type: object, properties: {a: {type: string}}, dependentSchemas: {a: {properties: {b: {type: string}}}}, unevaluatedProperties: false}", + "S: {allOf: ["+unevaluatedRef("T")+"], unevaluatedProperties: false}", + "Disc: {"+body+"oneOf: ["+unevaluatedRef("A")+", "+unevaluatedRef("AB")+"], discriminator: {propertyName: t}, unevaluatedProperties: false}", + "Plain: {"+body+"oneOf: ["+unevaluatedRef("A")+", "+unevaluatedRef("AB")+"], unevaluatedProperties: false}", + "Any: {"+body+"anyOf: ["+unevaluatedRef("TA")+", "+unevaluatedRef("TB")+"], unevaluatedProperties: false}", + "Tagged: {"+body+"oneOf: ["+unevaluatedRef("TA")+", "+unevaluatedRef("TB")+"], discriminator: {propertyName: t}, unevaluatedProperties: false}", + "EnumTagged: {"+body+"oneOf: ["+unevaluatedRef("EA")+", "+unevaluatedRef("EB")+"], unevaluatedProperties: false}", + "Contains: {type: array, prefixItems: [{type: string}], contains: {type: integer}, unevaluatedItems: false}", + ) + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, _ := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + for _, name := range []string{"Conditional", "Dependent", "S", "Disc", "Plain", "Any", "Contains"} { + assert.Equal(t, []ir.UnmodeledReason{ir.ReasonValidationOnly}, keptReasonsOf(doc, name, "openapi:unevaluated"), + "%s keeps the keyword once", name) + assert.Equal(t, ir.ReasonValidationOnly, keptOn(kindNode(t, doc, componentID(name)))["openapi:unevaluated"], + "%s: on its own node, a distributed union's on the Union", name) + assert.Empty(t, closedAfterCompositionUnder(doc, name), "%s closes no model", name) + } + for _, name := range []string{"Tagged", "EnumTagged"} { + assert.NotContains(t, keptKeywordsOf(doc, name), "openapi:unevaluated", name) + assert.Len(t, closedAfterCompositionUnder(doc, name), 2, "%s: each variant closes after composition", name) + } + }) +} + +// TestUnevaluated_AKeywordSayingNothingOrComposedScopeIsKeptAsAtTheBase holds what the rule +// leaves as the base lowers it: a keyword reaching an items or a catch-all +// beside it or through an inline entry evaluates nothing and is kept, the +// entry's spelling alone; one reaching a catch-all through a $ref is +// closed_after_composition over it; an array's reaching an items or a prefix +// through a $ref is kept on the alias; and an unevaluatedProperties S reaching +// a composed catch-all, a composed model closed after composition or a +// composed union is kept, not typed. #1904's inline catch-all and pattern rows +// stay as they are. +func TestUnevaluated_AKeywordSayingNothingOrComposedScopeIsKeptAsAtTheBase(t *testing.T) { + t.Parallel() + schemas := append(slices.Clone(unevaluatedTargets), + "ItemsBeside: {type: array, items: {type: string}, unevaluatedItems: false}", + "ItemsEntry: {allOf: [{items: {type: string}}], unevaluatedItems: false}", + "CatchEntry: {allOf: [{type: object, additionalProperties: {type: string}}], unevaluatedProperties: false}", + "CB: {allOf: ["+unevaluatedRef("B")+"], unevaluatedProperties: false}", + "RefItems: {allOf: ["+unevaluatedRef("AItems")+"], unevaluatedItems: false}", + "RefPrefix: {allOf: ["+unevaluatedRef("APrefix")+"], unevaluatedItems: false}", + "X: {allOf: ["+unevaluatedRef("BU")+"], properties: {b: {type: integer}}, unevaluatedProperties: {type: string}}", + "CS: {allOf: ["+unevaluatedRef("BC")+"], unevaluatedProperties: {type: string}}", + "RefUnionS: {allOf: ["+unevaluatedRef("U")+"], unevaluatedProperties: {type: string}}", + "BranchCatchAll: {type: object, allOf: [{additionalProperties: {type: integer}}], unevaluatedProperties: false}", + "BranchPatterns: {type: object, allOf: [{patternProperties: {'^x-': {type: string}}}], unevaluatedProperties: false}", + ) + inBothOrders(t, schemas, func(t *testing.T, schemas []string) { + doc, diags := compileUnrefused(t, admissionSpec("3.1.0", "", schemas...)) + for _, name := range []string{"ItemsBeside", "ItemsEntry", "CatchEntry", "RefItems", "RefPrefix", "X", "CS", "RefUnionS", "BranchCatchAll"} { + assert.Equal(t, []ir.UnmodeledReason{ir.ReasonValidationOnly}, keptReasonsOf(doc, name, "openapi:unevaluated"), + "%s keeps the keyword once", name) + assert.Len(t, byCode(diagsBeneath(diags, "/components/schemas/"+name), diag.ValidationOnlyKeyword), 1, "%s reports it once", name) + } + for name, elem := range map[string]ir.TypeID{"ItemsBeside": "type/primitive/string", "ItemsEntry": "type/primitive/string"} { + list, ok := kindNode(t, doc, componentID(name)).(*ir.List) + require.True(t, ok, "%s is the list of its items", name) + assert.Equal(t, elem, list.ElementType.Target, name) + } + catchEntry, ok := kindNode(t, doc, componentID("CatchEntry")).(*ir.MapT) + require.True(t, ok, "CatchEntry is the map of its catch-all") + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), catchEntry.Value.Target) + for name, base := range map[string]string{"CB": "B", "X": "BU", "CS": "BC"} { + model := requireModelOf(t, doc, name) + require.NotNil(t, model.Base, name) + assert.Equal(t, componentID(base), model.Base.Target, name) + } + assert.Equal(t, ir.AdditionalClosedAfterComposition, requireModelOf(t, doc, "CB").Additional) + assert.Nil(t, requireModelOf(t, doc, "CS").AdditionalProperties, "CS takes no catch-all of its own") + assert.Nil(t, requireModelOf(t, doc, "X").AdditionalProperties, "X takes no catch-all of its own") + assert.Equal(t, ir.AdditionalClosedAfterComposition, requireModelOf(t, doc, "BranchPatterns").Additional) + }) +} + +// keptReasonsOf lists the reason of each entry under key that the component +// named, or a node beneath it, keeps. +func keptReasonsOf(doc *ir.Document, name, key string) []ir.UnmodeledReason { + entries := keptKeywordsOf(doc, name)[key] + out := make([]ir.UnmodeledReason, 0, len(entries)) + for _, entry := range entries { + out = append(out, entry.reason) + } + return out +} + +// closedAfterCompositionUnder lists the models at or beneath the component +// named, its distributed variants among them, closed after composition. +func closedAfterCompositionUnder(doc *ir.Document, name string) []ir.TypeID { + var out []ir.TypeID + for id, td := range doc.Types { + model, ok := td.(*ir.Model) + if !ok || model.Additional != ir.AdditionalClosedAfterComposition { + continue + } + at := "/components/schemas/" + name + if s := string(id); strings.HasSuffix(s, at) || strings.Contains(s, at+"/") { + out = append(out, id) + } + } + slices.Sort(out) + return out +} diff --git a/compilers/openapi/e2e/unheld_twins_test.go b/compilers/openapi/e2e/unheld_twins_test.go index 1a9b17e85..fb29d200d 100644 --- a/compilers/openapi/e2e/unheld_twins_test.go +++ b/compilers/openapi/e2e/unheld_twins_test.go @@ -535,9 +535,9 @@ func bindAnswers(table *reftable.ReferenceTargetTable) []string { chain := func(chain reftable.Chain) string { return fmt.Sprintf("chain %s %s %d", chain.Status, at(chain.End), chain.Hops) } - lines := make([]string, 0, len(table.Entries())+len(table.Landings())+len(table.References())+ + lines := make([]string, 0, len(table.ReferenceSites())+len(table.Landings())+len(table.References())+ len(table.ObjectLandings())) - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { lines = append(lines, "entry "+at(referenceSite.Site)+": "+hop(referenceSite.Hop)+chain(referenceSite.Chain)) } for _, landing := range table.Landings() { diff --git a/compilers/openapi/e2e/union_alone_entry_test.go b/compilers/openapi/e2e/union_alone_entry_test.go index a79167bee..1a59eaa90 100644 --- a/compilers/openapi/e2e/union_alone_entry_test.go +++ b/compilers/openapi/e2e/union_alone_entry_test.go @@ -271,12 +271,12 @@ func TestUnionAlone_OnAnEntryLowersAsWrittenAtThePosition(t *testing.T) { } // aloneBodies are conjuncts beside a union on an allOf entry that keep it from -// standing alone: a property set, a $ref and a `type` the null branch does not -// say, each paired with the schema writing the same keywords beside the union; -// a discriminator beside the allOf or on another entry, paired with itself, as -// the union with the discriminator written beside it stands alone; and an -// allOf the union's own entry composes beside it, paired with the same allOf -// beside the union. +// being alone: a property set, a $ref and a `type` the null branch does not +// say, each paired with the schema writing the same keywords beside the union. +// An allOf of notes beside the union is no body +// (TestUnionBesideBody_NotesBesideAUnionAreNoBody), and a discriminator +// wherever written stays with the union +// (TestUnionBesideBody_ADiscriminatorStaysWithItsUnion). var aloneBodies = []struct { name, entry, flat string }{ @@ -290,19 +290,13 @@ var aloneBodies = []struct { "{type: object, oneOf: [" + aloneRef("X") + ", {type: 'null'}]}"}, {"type object beside the allOf", "{type: object, allOf: [{oneOf: [" + aloneRef("X") + ", {type: 'null'}]}]}", "{type: object, oneOf: [" + aloneRef("X") + ", {type: 'null'}]}"}, - {"a discriminator beside the allOf", "{discriminator: {propertyName: id}, allOf: [{oneOf: [" + aloneRef("X") + ", {type: 'null'}]}]}", - "{discriminator: {propertyName: id}, allOf: [{oneOf: [" + aloneRef("X") + ", {type: 'null'}]}]}"}, - {"a discriminator on another entry", "{allOf: [{discriminator: {propertyName: id}}, {oneOf: [" + aloneRef("X") + ", {type: 'null'}]}]}", - "{allOf: [{discriminator: {propertyName: id}}, {oneOf: [" + aloneRef("X") + ", {type: 'null'}]}]}"}, - {"an allOf on its entry", "{allOf: [{oneOf: [" + aloneRef("X") + ", {type: 'null'}], allOf: [{description: d}]}]}", - "{oneOf: [" + aloneRef("X") + ", {type: 'null'}], allOf: [{description: d}]}"}, } // TestUnionAlone_ABodyBesideItStillDistributes holds a union written on an -// allOf entry beside a conjunct that keeps it from standing alone to stay -// distributed, one variant included (docs/compilers/openapi.md#union-beside-structure): -// at a component and a property both spellings of each row of aloneBodies are -// a Union of one model composed over X. +// allOf entry beside a conjunct that keeps it from being alone to stay distributed, +// one variant included (docs/compilers/openapi.md#union-beside-structure): at a +// component and a property both spellings of each row of aloneBodies are a +// Union of one model composed over X. func TestUnionAlone_ABodyBesideItStillDistributes(t *testing.T) { t.Parallel() for _, siteName := range []string{"component", "property"} { diff --git a/compilers/openapi/e2e/union_apart_body_test.go b/compilers/openapi/e2e/union_apart_body_test.go index 726fafdea..dbcc06681 100644 --- a/compilers/openapi/e2e/union_apart_body_test.go +++ b/compilers/openapi/e2e/union_apart_body_test.go @@ -11,16 +11,17 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) -// TestElection_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody +// TestChoice_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody // holds that a oneOf or an anyOf of objects, which shares no kind with a // string, a string or null, an integer or an array body, lowers as the body // keeping the union, with the one warning that the conjuncts share no value: // beside the body's keywords, beside an allOf of it and on an entry in either // order, at a component, in either order of the components. -func TestElection_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody(t *testing.T) { +func TestChoice_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody(t *testing.T) { t.Parallel() bodies := []struct { body string @@ -54,7 +55,7 @@ func TestElection_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody(t *te } } require.Len(t, warned, 1) - assert.Contains(t, warned[0], "share no value") + assert.Contains(t, warned[0], "no value satisfies") }) } } @@ -63,30 +64,35 @@ func TestElection_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody(t *te } } -// TestElection_AUnionSharingAKindWithAScalarBodyLowersAsBefore pins a oneOf of -// a string beside a string body, which #2108 decides: the body's Scalar -// keeping it as validation logic beside the body's keywords, a Union of the -// branch beside an allOf of it and on an entry, keeping nothing, none warned. -func TestElection_AUnionSharingAKindWithAScalarBodyLowersAsBefore(t *testing.T) { +// TestChoice_AUnionRestatingAScalarBodyIsKeptByTheBody holds that a oneOf +// of a string beside a string body, a union declaring no shape the body does +// not, is the body's Scalar keeping it as validation logic in every spelling: +// beside the body's keywords, beside an allOf of it and on an entry, with one +// validation-only finding each and none warned (GitHub #2108). +func TestChoice_AUnionRestatingAScalarBodyIsKeptByTheBody(t *testing.T) { t.Parallel() doc, diags := compileAnnotationSpec(t, "shared", bothKeywordsDoc("3.1.0", "", false, "Flat: {type: string, oneOf: [{type: string}]}", "Beside: {allOf: [{type: string}], oneOf: [{type: string}]}", "Entry: {allOf: [{type: string}, {oneOf: [{type: string}]}]}")) requireErrorsAndWarnings(t, diags, nil) - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}, keptOn(kindNode(t, doc, componentID("Flat")))) - assert.Equal(t, ir.KindScalar, kindNode(t, doc, componentID("Flat")).Kind()) - assert.Equal(t, ir.KindUnion, kindNode(t, doc, componentID("Beside")).Kind()) - entry := kindNode(t, doc, componentID("Entry")) - assert.Equal(t, ir.KindUnion, entry.Kind()) - assert.Empty(t, keptOn(entry)) + for _, name := range []string{"Flat", "Beside", "Entry"} { + td := kindNode(t, doc, componentID(name)) + assert.Equal(t, ir.KindScalar, td.Kind(), name) + kept := map[string]ir.UnmodeledReason{} + for key, reason := range keptOn(td) { + kept[entryNodes.ReplaceAllString(key, "")] = reason + } + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}, kept, name) + assert.Equal(t, 1, countBeneath(diags, diag.ValidationOnlyKeyword, ir.SeverityInfo, "/components/schemas/"+name), name) + } } -// TestElection_AnEntryTypeSharingNoKindWithItsUnionLowersAsBesideTheAllOf +// TestChoice_AnEntryTypeSharingNoKindWithItsUnionLowersAsBesideTheAllOf // holds that a type and a oneOf sharing no kind, beside a $ref, beside an // allOf of it and on an inline entry of that allOf, in either order of the // components, are each a use of the $ref's target keeping both keywords, with // the one warning that the conjuncts share no value (GitHub #2063). -func TestElection_AnEntryTypeSharingNoKindWithItsUnionLowersAsBesideTheAllOf(t *testing.T) { +func TestChoice_AnEntryTypeSharingNoKindWithItsUnionLowersAsBesideTheAllOf(t *testing.T) { t.Parallel() for _, reversed := range []bool{false, true} { t.Run(fmt.Sprint(reversed), func(t *testing.T) { @@ -116,14 +122,14 @@ func TestElection_AnEntryTypeSharingNoKindWithItsUnionLowersAsBesideTheAllOf(t * } } -// TestElection_ANullBranchIsDeadWhereTheUnionPassedOverKeepsNullOut holds -// that the anyOf an object or null elects over a oneOf of an object, its -// branch a $ref to null alone, leaves that branch dead, the oneOf keeping null -// out: the Union of the object branch keeping the null branch, with the one -// warning, beside the body's keywords, beside an allOf of it, on one entry and -// on two, in either order of the components, whether or not the body declares -// a property. -func TestElection_ANullBranchIsDeadWhereTheUnionPassedOverKeepsNullOut(t *testing.T) { +// TestChoice_ANullBranchIsDeadWhereTheUnionPassedOverKeepsNullOut holds that +// the anyOf an object or null chooses over a oneOf of an object, its branch a +// $ref to null alone, leaves that branch dead, the oneOf keeping null out: the +// Union of the object branch keeping the null branch, with the one warning, +// beside the body's keywords, beside an allOf of it, on one entry and on two, +// in either order of the components, whether or not the body declares a +// property. +func TestChoice_ANullBranchIsDeadWhereTheUnionPassedOverKeepsNullOut(t *testing.T) { t.Parallel() const one, anyOf = "oneOf: [{type: object}]", "anyOf: [{type: object, properties: {x: {type: string}}}, {$ref: '#/components/schemas/Null'}]" for _, body := range []string{"type: [object, 'null']", "type: [object, 'null'], properties: {a: {type: string}}"} { diff --git a/compilers/openapi/e2e/union_beside_body_helpers_test.go b/compilers/openapi/e2e/union_beside_body_helpers_test.go new file mode 100644 index 000000000..bd7d9a933 --- /dev/null +++ b/compilers/openapi/e2e/union_beside_body_helpers_test.go @@ -0,0 +1,441 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "encoding/json/v2" + "fmt" + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers" + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// bodyView is what a reader of a position is given, with every pointer the +// spelling oracle relocates left out: what its reference names (a primitive, a +// named component, or a node the position owns, by namespace and facts), +// whether it admits null, the node's facts down to a bounded depth, and at a +// property what the property keeps. +type bodyView struct { + Ref string + Space string + Nullable bool + Kind ir.TypeKind + Base *bodyView + Mixins []bodyView + Properties []string + PropertyTypes []bodyView + Requires []string + Additional ir.AdditionalMode + CatchAll *bodyView + Encoding string + Constraints string + ValueType ir.PrimitiveKind + Members []string + Variants []bodyView + Exclusive bool + Closed bool + Discriminator string + Kept map[string]ir.UnmodeledReason + PropertyKept map[string]ir.UnmodeledReason +} + +// maxReportedDifferences is how many differing spellings of one comparison +// print their difference, each cut after maxDifferenceLines lines: the rest are +// counted, as a bounded report is read. +const ( + maxReportedDifferences = 1 + maxDifferenceLines = 40 + // maxNamedDifferences is how many differing spellings a report names. + maxNamedDifferences = 12 +) + +// bodyViewDepth bounds how deep a view reads nested nodes: a variant's base's +// property is as deep as any row below asks. +const bodyViewDepth = 4 + +// relocatedKey is key, an Unmodeled key, with each allOf entry it names left +// out, as the spelling oracle relocates it. +func relocatedKey(key string) string { + return strings.Replace(entryNodes.ReplaceAllString(key, ""), "openapi:/", "openapi:", 1) +} + +// viewOfRef describes what ref names in doc, components and primitives by name. +func viewOfRef(doc *ir.Document, ref ir.TypeRef, depth int) bodyView { + target := string(ref.Target) + view := bodyView{Nullable: ref.Nullable} + if primitive, ok := strings.CutPrefix(target, "type/primitive/"); ok { + view.Ref = primitive + return view + } + if name, ok := strings.CutPrefix(target, "type/openapi/components/schemas/"); ok && !strings.Contains(name, "/") { + view.Ref = "component " + name + return view + } + space, _, _ := strings.Cut(strings.TrimPrefix(target, "type/"), "/") + view.Space = space + node := doc.Types[ref.Target] + if node == nil || depth >= bodyViewDepth { + return view + } + describeNode(doc, node, depth, &view) + return view +} + +// viewOfComponent describes the component name's own node in doc, its +// reference read from holder's property of that name, which admits null where +// a reader of the component is given null. +func viewOfComponent(doc *ir.Document, name, holder string) bodyView { + view := bodyView{Space: "openapi"} + if model, ok := doc.Types[componentID(holder)].(*ir.Model); ok { + if property, found := propertyByWire(model, name); found { + view.Nullable = property.Type.Nullable + } + } + if node := doc.Types[componentID(name)]; node != nil { + describeNode(doc, node, 0, &view) + } + return view +} + +// viewOfProperty describes the type of holder's property wire in doc, and +// what the property itself keeps. +func viewOfProperty(doc *ir.Document, holder, wire string) bodyView { + model, ok := doc.Types[componentID(holder)].(*ir.Model) + if !ok { + return bodyView{Ref: "no holder"} + } + property, found := propertyByWire(model, wire) + if !found { + return bodyView{Ref: "no property"} + } + view := viewOfRef(doc, property.Type, 0) + view.PropertyKept = map[string]ir.UnmodeledReason{} + for key, entry := range property.Unmodeled { + view.PropertyKept[relocatedKey(key)] = entry.Reason + } + return view +} + +// describeNode fills view with node's facts. +func describeNode(doc *ir.Document, node ir.TypeDef, depth int, view *bodyView) { + view.Kind = node.Kind() + view.Kept = map[string]ir.UnmodeledReason{} + for key, entry := range node.Common().Unmodeled { + view.Kept[relocatedKey(key)] = entry.Reason + } + nested := func(ref ir.TypeRef) bodyView { return viewOfRef(doc, ref, depth+1) } + switch typed := node.(type) { + case *ir.Scalar: + view.Base = refView(typed.Base, nested) + view.Constraints = constraintsText(typed.Constraints) + view.Encoding = encodingName(typed.Encoding) + case *ir.List: + element := nested(typed.ElementType) + view.Base = &element + view.Constraints = constraintsText(typed.Constraints) + case *ir.Enum: + for _, member := range typed.Members { + view.Members = append(view.Members, fmt.Sprint(member.Value)) + } + view.ValueType = typed.ValueType + view.Closed = typed.Closed + view.Constraints = constraintsText(typed.Constraints) + case *ir.Union: + for _, variant := range typed.Variants { + view.Variants = append(view.Variants, nested(variant.Type)) + } + view.Exclusive = typed.Exclusive + view.Constraints = constraintsText(typed.Constraints) + if typed.Discriminator != nil { + view.Discriminator = typed.Discriminator.PropertyName + } + case *ir.Model: + describeModel(typed, nested, view) + case *ir.Literal: + view.Members = []string{fmt.Sprint(typed.Value)} + view.ValueType = typed.ValueType + } +} + +// describeModel fills view with model's facts. +func describeModel(model *ir.Model, nested func(ir.TypeRef) bodyView, view *bodyView) { + view.Base = refView(model.Base, nested) + for _, mixin := range model.Mixins { + view.Mixins = append(view.Mixins, nested(mixin)) + } + for _, property := range model.Properties { + name := property.Name.Source + if property.Required { + name += " required" + } + view.Properties = append(view.Properties, name) + view.PropertyTypes = append(view.PropertyTypes, nested(property.Type)) + } + view.Requires = slices.Clone(model.Requires) + view.Additional = model.Additional + if model.AdditionalProperties != nil { + view.CatchAll = refView(model.AdditionalProperties.Value, nested) + } + view.Constraints = constraintsText(model.Constraints) + if model.Discriminator != nil { + view.Discriminator = model.Discriminator.PropertyName + } +} + +// refView is the view of ref, nil where there is none. +func refView(ref *ir.TypeRef, nested func(ir.TypeRef) bodyView) *bodyView { + if ref == nil { + return nil + } + view := nested(*ref) + return &view +} + +// constraintsText is constraints as its JSON, empty where there are none. +func constraintsText(constraints *ir.Constraints) string { + if constraints == nil { + return "" + } + text, err := json.Marshal(constraints, json.Deterministic(true)) + if err != nil { + return "unencodable: " + err.Error() + } + return string(text) +} + +// encodingName is encoding's name, empty where there is none. +func encodingName(encoding *ir.Encoding) string { + if encoding == nil { + return "" + } + return encoding.Name +} + +// findingsBeneath lists the severity and code of each finding at pointer or beneath +// it, an info once however often it is drawn, warnings and errors each time. +func findingsBeneath(diags []ir.Diagnostic, pointer string) []string { + infos := map[string]bool{} + var others []string + for _, diagnostic := range diagsBeneath(diags, pointer) { + finding := string(diagnostic.Severity) + " " + diagnostic.Code + if diagnostic.Severity == ir.SeverityInfo { + infos[finding] = true + continue + } + others = append(others, finding) + } + slices.Sort(others) + return slices.Concat(slices.Sorted(maps.Keys(infos)), others) +} + +// countBeneath is how many findings of code and severity lie at pointer or beneath it. +func countBeneath(diags []ir.Diagnostic, code string, severity ir.Severity, pointer string) int { + count := 0 + for _, diagnostic := range byCode(diagsBeneath(diags, pointer), code) { + if diagnostic.Severity == severity { + count++ + } + } + return count +} + +// messagesBeneath lists the messages of the findings of code at pointer or beneath it. +func messagesBeneath(diags []ir.Diagnostic, code, pointer string) []string { + found := byCode(diagsBeneath(diags, pointer), code) + out := make([]string, 0, len(found)) + for _, diagnostic := range found { + out = append(out, diagnostic.Message) + } + return out +} + +// spelledPosition is one spelling of a schema at one position: the view of +// what it lowers to and the findings at it. +type spelledPosition struct { + View bodyView + Findings []string +} + +// bodyHolder is the component whose properties hold a reference to each +// component a spelling row declares, so the reference's null is read. +const bodyHolder = "Holder" + +// compileSpellingRows is compileSpellingRowsWith at 3.1 and the default +// options. +func compileSpellingRows( + t *testing.T, shared []string, rows []openapitest.Row, +) openapitest.Readings[spelledPosition] { + t.Helper() + return compileSpellingRowsWith(t, openapi.Options{}, "3.1.0", shared, rows) +} + +// compileSpellingRowsWith compiles every spelling of every row at version +// beside shared, under options, as components and as properties of a holder +// of its own, and returns each spelling's component and property readings, by +// row, spelling and position, in both orders of the components. +func compileSpellingRowsWith( + t *testing.T, options openapi.Options, version string, shared []string, rows []openapitest.Row, +) openapitest.Readings[spelledPosition] { + t.Helper() + var schemas, references, properties []string + for _, row := range rows { + for _, spelling := range slices.Sorted(maps.Keys(row.Spellings)) { + name := row.Name + "_" + spelling + schemas = append(schemas, name+": "+row.Spellings[spelling]) + references = append(references, name+": {$ref: '#/components/schemas/"+name+"'}") + properties = append(properties, name+": "+row.Spellings[spelling]) + } + } + schemas = append(schemas, shared...) + schemas = append(schemas, + bodyHolder+": {type: object, properties: {"+strings.Join(references, ", ")+"}}", + "Props: {type: object, properties: {"+strings.Join(properties, ", ")+"}}") + out := openapitest.Readings[spelledPosition]{} + for _, reversed := range []bool{false, true} { + ordered := slices.Clone(schemas) + if reversed { + slices.Reverse(ordered) + } + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{ + {Path: "spellings.yaml", Data: []byte(admissionSpec(version, "", ordered...))}, + }, compilers.Options{FormatOptions: options}) + require.NoError(t, err) + requireVerifies(t, doc, diags) + out[reversed] = readSpellingRows(doc, diags, rows) + } + return out +} + +// readSpellingRows reads each spelling of rows in doc at its component and +// at its property of Props. +func readSpellingRows( + doc *ir.Document, diags []ir.Diagnostic, rows []openapitest.Row, +) map[string]map[string]map[string]spelledPosition { + out := map[string]map[string]map[string]spelledPosition{} + for _, row := range rows { + out[row.Name] = map[string]map[string]spelledPosition{} + for spelling := range row.Spellings { + name := row.Name + "_" + spelling + out[row.Name][spelling] = map[string]spelledPosition{ + "component": { + View: viewOfComponent(doc, name, bodyHolder), + Findings: findingsBeneath(diags, "/components/schemas/"+name), + }, + "property": { + View: viewOfProperty(doc, "Props", name), + Findings: findingsBeneath(diags, "/components/schemas/Props/properties/"+name), + }, + } + } + } + return out +} + +// only is the spellings named of spellings. +func only(spellings map[string]string, names ...string) map[string]string { + out := map[string]string{} + for _, name := range names { + out[name] = spellings[name] + } + return out +} + +// alsoSpelt is spellings and, under prefix, each of more: one row written +// with a body that is itself what the row is held to, as a $ref to a schema +// stating nothing is. +func alsoSpelt(spellings map[string]string, prefix string, more map[string]string) map[string]string { + out := maps.Clone(spellings) + for name, text := range more { + out[prefix+name] = text + } + return out +} + +// forgiveness is what one kind of spelling alone draws, taken out of its +// reading so the spelling can be held to its row's first. The reading is +// required to hold it: a rule that finds nothing to take has stopped reaching. +type forgiveness struct { + // applies reports whether the spelling written as text is one the rule reads. + applies func(text string) bool + // take returns reading without what applies' spellings alone draw, and + // whether it held it; first is the row's first spelling's reading there. + take func(reading, first spelledPosition) (spelledPosition, bool) +} + +// forgive applies rule to every spelling of rows it reads, in every position +// and order of the components, and fails t where one holds nothing to take. +// first names the spelling a row is held to, whose reading take is given. +func forgive(t *testing.T, readings openapitest.Readings[spelledPosition], rows []openapitest.Row, first string, rule forgiveness) { + t.Helper() + for _, row := range rows { + for spelling, text := range row.Spellings { + if !rule.applies(text) { + continue + } + for reversed := range readings { + for position, reading := range readings[reversed][row.Name][spelling] { + firstReading := readings[reversed][row.Name][first][position] + taken, held := rule.take(reading, firstReading) + if !assert.True(t, held, "%s %s at the %s holds what its rule forgives", row.Name, spelling, position) { + continue + } + readings[reversed][row.Name][spelling][position] = taken + } + } + } + } +} + +// forgiveLaterVersion forgives, in a 3.0 document, the warning that a $ref's +// siblings are a later version's construct, which every spelling writing a +// keyword beside a $ref draws and the others do not. +func forgiveLaterVersion(t *testing.T, version string, readings openapitest.Readings[spelledPosition], rows []openapitest.Row) { + t.Helper() + if !strings.HasPrefix(version, "3.0") { + return + } + const later = "warning openapi/later-version-construct" + forgive(t, readings, rows, "Flat", forgiveness{ + applies: openapitest.WritesBesideRef, + take: func(reading, _ spelledPosition) (spelledPosition, bool) { + held := slices.Contains(reading.Findings, later) + reading.Findings = slices.DeleteFunc(slices.Clone(reading.Findings), func(finding string) bool { return finding == later }) + return reading, held + }, + }) +} + +// forgiveKeptRef forgives, for the spellings writing ref, a $ref kept +// verbatim, as one to a schema stating nothing, which is no body, is, and the +// one info it draws, which stays where the row's first spelling draws one of +// its own. +func forgiveKeptRef(t *testing.T, readings openapitest.Readings[spelledPosition], rows []openapitest.Row, ref string) { + t.Helper() + const info = "info " + diag.DegradedConstruct + forgive(t, readings, rows, "Flat", forgiveness{ + applies: func(text string) bool { return strings.Contains(text, ref) }, + take: func(reading, first spelledPosition) (spelledPosition, bool) { + at := slices.Index(reading.Findings, info) + if reading.View.Kept["openapi:$ref"] != ir.ReasonDegradedLowering || at < 0 { + return reading, false + } + reading.View.Kept = maps.Clone(reading.View.Kept) + delete(reading.View.Kept, "openapi:$ref") + if !slices.Contains(first.Findings, info) { + reading.Findings = slices.Concat(reading.Findings[:at], reading.Findings[at+1:]) + } + return reading, true + }, + }) +} diff --git a/compilers/openapi/e2e/union_beside_body_test.go b/compilers/openapi/e2e/union_beside_body_test.go new file mode 100644 index 000000000..c3032eeda --- /dev/null +++ b/compilers/openapi/e2e/union_beside_body_test.go @@ -0,0 +1,586 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// unionBodies are the bodies a union is written beside, by version: an object, +// a string with and without a bound, a string or null, an array, an object or +// null, an object or a string, a $ref to an object, and notes alone. +func unionBodies(version string) map[string]string { + bodies := map[string]string{ + "obj": "type: object, properties: {a: {type: string}}", "str": "type: string", + "strB": "type: string, maxLength: 9", "strN": "type: [string, 'null']", + "arr": "type: array, items: {type: string}", "objN": "type: [object, 'null'], properties: {a: {type: string}}", + "objS": "type: [object, string]", "ref": "$ref: '#/components/schemas/O'", "notes": "description: d", + } + if version == "3.0.3" { + bodies["strN"] = "type: string, nullable: true" + bodies["objN"] = "type: object, nullable: true, properties: {a: {type: string}}" + delete(bodies, "objS") + } + return bodies +} + +// besideUnions are the unions written beside each body, by version: one +// restating a string, formats alone, a string or an object, two objects, two +// narrowings, null alone, an object or null, and a oneOf with an anyOf. +func besideUnions(version string) map[string]string { + null := "{type: 'null'}" + if version == "3.0.3" { + null = "{type: object, enum: [null], nullable: true}" + } + return map[string]string{ + "restate": "oneOf: [{type: string}]", "formats": "oneOf: [{format: uuid}, {format: email}]", + "strObj": "oneOf: [{type: string}, {$ref: '#/components/schemas/A'}]", + "objs": "oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]", + "narrow": "oneOf: [{required: [a]}, {required: [b]}]", "null1": "oneOf: [" + null + "]", + "refNull": "oneOf: [{$ref: '#/components/schemas/A'}, " + null + "]", + "pair": "oneOf: [{type: string}, {type: integer}], anyOf: [{type: integer}, {type: boolean}]", + } +} + +// besideShared are the components the bodies and unions above name. +var besideShared = []string{ + "A: {type: object, properties: {x: {type: string}}}", + "B: {type: object, properties: {y: {type: string}}}", + "O: {type: object, properties: {a: {type: string}}}", +} + +// TestUnionBesideBody_EverySpellingLowersAlike holds that a union, or a oneOf +// with an anyOf, beside each body above lowers to one result in every +// spelling: flat, beside an allOf of the body, on an entry after or before +// it, one allOf deeper, split or one beside the allOf; at a component and a +// property, in either component order, at 3.0, 3.1 and 3.2. A 3.0 $ref's +// siblings read as at 3.1, the flat spelling alone warning of a later +// version. The nullable-inference policy is off: where it widens a $ref +// beside a union is its own question (GitHub #2109), which the rows below +// read with it on. +func TestUnionBesideBody_EverySpellingLowersAlike(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + bodies, unions := unionBodies(version), besideUnions(version) + cases := map[string][2]string{} + for body := range bodies { + for union := range unions { + cases[body+"_"+union] = [2]string{bodies[body], unions[union]} + } + } + rows := openapitest.Rows(cases) + off := openapi.Options{NullableInference: openapi.NullableInference{Disabled: true}} + readings := compileSpellingRowsWith(t, off, version, besideShared, rows) + forgiveLaterVersion(t, version, readings, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + }) + } +} + +// requireOneUnsatisfiable holds the findings beneath schema to one +// openapi/unsatisfiable-schema, drawn at union, the pointer of the union +// keyword, whose message names each of names. +func requireOneUnsatisfiable(t *testing.T, diags []ir.Diagnostic, schema, union string, names ...string) { + t.Helper() + messages := messagesBeneath(diags, diag.UnsatisfiableSchema, schema) + require.Len(t, messages, 1, "one report that no instance satisfies %s", schema) + assert.Equal(t, 1, unsatisfiableAt(diags, union), "the report is at the union keyword") + for _, name := range names { + assert.Contains(t, messages[0], name, "the report at %s names %s", union, name) + } +} + +// TestUnionBesideBody_AUnionDeclaringNoShapeIsKeptByAScalarBody holds that a +// union whose branches restate, bound or pattern a string or an array body, +// in every spelling, is the body's node keeping the union as validation logic, +// with one validation-only finding and no warning, at a property as at a +// component: the property is not the union's home (GitHub #2108). +func TestUnionBesideBody_AUnionDeclaringNoShapeIsKeptByAScalarBody(t *testing.T) { + t.Parallel() + rows := openapitest.Rows(map[string][2]string{ + "Restate": {"type: string", "oneOf: [{type: string}]"}, + "Bounds": {"type: string", "oneOf: [{maxLength: 3}, {minLength: 10}]"}, + "Patterns": {"type: string", "anyOf: [{pattern: '^a'}, {pattern: '^b'}]"}, + "Array": {"type: array, items: {type: string}", "oneOf: [{minItems: 1}, {maxItems: 3}]"}, + }) + readings := compileSpellingRows(t, nil, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for row, kind := range map[string]ir.TypeKind{ + "Restate": ir.KindScalar, "Bounds": ir.KindScalar, "Patterns": ir.KindScalar, "Array": ir.KindList, + } { + flat := readings[false][row]["Flat"]["component"] + assert.Equal(t, kind, flat.View.Kind, row) + keyword := "openapi:oneOf" + if row == "Patterns" { + keyword = "openapi:anyOf" + } + assert.Equal(t, map[string]ir.UnmodeledReason{keyword: ir.ReasonValidationOnly}, flat.View.Kept, row) + assert.Equal(t, []string{"info " + diag.ValidationOnlyKeyword}, flat.Findings, row) + for spelling := range openapitest.RowNamed(t, rows, row).Spellings { + property := readings[false][row][spelling]["property"].View + assert.Equal(t, kind, property.Kind, "%s %s: the body's node sits at the property", row, spelling) + assert.Equal(t, ir.ReasonValidationOnly, property.Kept[keyword], "%s %s: and keeps the union", row, spelling) + assert.Empty(t, property.PropertyKept, "%s %s: the property is no home for it", row, spelling) + } + } +} + +// TestUnionBesideBody_ADeadBranchBesideAScalarBodyIsReported holds that a +// branch sharing no kind with a string or an array body is dead in every +// spelling: the body's node keeps the whole union once as degraded_lowering, +// with one report at the union keyword naming each dead branch. The first two +// are the golden spec's: a flat oneOf of a string, a number and a boolean +// beside a string, and an anyOf of the same on an entry before a bounded +// string (GitHub #2108, #2089). +func TestUnionBesideBody_ADeadBranchBesideAScalarBodyIsReported(t *testing.T) { + t.Parallel() + scalarBranches := "[{type: string}, {type: number}, {type: boolean}]" + rows := openapitest.Rows(map[string][2]string{ + "Value": {"description: v, type: string, example: x", "oneOf: " + scalarBranches}, + "Needle": {"maxLength: 1000, type: string", "anyOf: " + scalarBranches}, + "Array": {"type: array, items: {type: string}", "oneOf: [{minItems: 1}, {type: string}]"}, + }) + readings := compileSpellingRows(t, nil, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for row, want := range map[string]struct { + kind ir.TypeKind + keyword string + dead []string + }{ + "Value": {ir.KindScalar, "openapi:oneOf", []string{"oneOf/1", "oneOf/2"}}, + "Needle": {ir.KindScalar, "openapi:anyOf", []string{"anyOf/1", "anyOf/2"}}, + "Array": {ir.KindList, "openapi:oneOf", []string{"oneOf/1"}}, + } { + flat := readings[false][row]["Flat"]["component"] + assert.Equal(t, want.kind, flat.View.Kind, row) + assert.Equal(t, map[string]ir.UnmodeledReason{want.keyword: ir.ReasonDegradedLowering}, flat.View.Kept, row) + assert.Contains(t, flat.Findings, "warning "+diag.UnsatisfiableSchema, row) + } + unions := map[string]string{"Flat": "", "EntryRev": "/allOf/0"} + for spelling, entry := range unions { + for row, keyword := range map[string]string{"Value": "oneOf", "Needle": "anyOf"} { + doc, diags := compileAnnotationSpec(t, "dead", admissionSpec("3.1.0", "", row+": "+openapitest.RowNamed(t, rows, row).Spellings[spelling])) + require.NotNil(t, doc) + schema := "/components/schemas/" + row + requireOneUnsatisfiable(t, diags, schema, schema+entry+"/"+keyword, keyword+"/1", keyword+"/2") + } + } +} + +// TestUnionBesideBody_ABranchDeclaringShapeBesideAStringMakesAUnion holds that +// live branches of which one writes a format or a $ref beside a string body +// make a Union of the branches conjoined with the body, alike in every +// spelling: formats alone as with the type written, the golden spec's +// references to strings and to formatted strings, and two encodings; the +// body's length, which binds no uuid's or date's text, is kept on the Union +// (GitHub #2108). +func TestUnionBesideBody_ABranchDeclaringShapeBesideAStringMakesAUnion(t *testing.T) { + t.Parallel() + shared := []string{ + "C1: {type: string, description: one}", "C2: {type: string, description: two}", + "V4: {type: string, format: ipv4}", "V6: {type: string, format: ipv6}", + } + rows := openapitest.Rows(map[string][2]string{ + "Formats": {"type: string", "oneOf: [{format: uuid}, {format: date}]"}, + "TypedFormats": {"type: string", "oneOf: [{type: string, format: uuid}, {type: string, format: date}]"}, + "Bounded": {"type: string, maxLength: 9", "oneOf: [{format: uuid}, {format: date}]"}, + "Codes": {"type: string", "anyOf: [{$ref: '#/components/schemas/C1'}, {$ref: '#/components/schemas/C2'}]"}, + "Addresses": {"type: string", "anyOf: [{$ref: '#/components/schemas/V4'}, {$ref: '#/components/schemas/V6'}]"}, + "Encodings": {"type: string", "anyOf: [{format: ipv4}, {format: ipv6}]"}, + }) + readings := compileSpellingRows(t, shared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + view := func(row string) bodyView { return readings[false][row]["Flat"]["component"].View } + for _, row := range []string{"Formats", "TypedFormats", "Bounded", "Codes", "Addresses", "Encodings"} { + assert.Equal(t, ir.KindUnion, view(row).Kind, row) + assert.Len(t, view(row).Variants, 2, row) + } + assert.Equal(t, view("TypedFormats").Variants, view("Formats").Variants, "a format alone is its flat twin") + assert.Empty(t, view("Bounded").Constraints, "the body's length binds no variant's value") + assert.Equal(t, ir.ReasonNoIRHome, view("Bounded").Kept["openapi:maxLength"], "the Union keeps the body's length") + assert.Equal(t, []string{"component C1", "component C2"}, refsOf(view("Codes").Variants)) + assert.Equal(t, []string{"component V4", "component V6"}, refsOf(view("Addresses").Variants)) + encodings := make([]string, 0, len(view("Encodings").Variants)) + for _, variant := range view("Encodings").Variants { + encodings = append(encodings, variant.Encoding) + } + assert.Equal(t, []string{"ipv4", "ipv6"}, encodings) +} + +// refsOf lists what each of views names. +func refsOf(views []bodyView) []string { + out := make([]string, 0, len(views)) + for _, view := range views { + out = append(out, view.Ref) + } + return out +} + +// TestUnionBesideBody_EveryBranchDeadLowersAsTheRest holds that a union no +// branch of which shares a kind with a string body lowers, in every spelling, +// as the body, keeping the union as degraded_lowering, with the one report at +// the schema that its conjuncts share no value. +func TestUnionBesideBody_EveryBranchDeadLowersAsTheRest(t *testing.T) { + t.Parallel() + rows := openapitest.Rows(map[string][2]string{ + "Scalars": {"type: string", "oneOf: [{type: integer}, {type: boolean}]"}, + "Objects": {"type: string", "anyOf: [{$ref: '#/components/schemas/A'}, {type: object}]"}, + }) + readings := compileSpellingRows(t, besideShared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range []string{"Scalars", "Objects"} { + flat := readings[false][row]["Flat"]["component"] + assert.Equal(t, ir.KindScalar, flat.View.Kind, row) + require.NotNil(t, flat.View.Base, row) + assert.Equal(t, "string", flat.View.Base.Ref, row) + assert.Len(t, flat.View.Kept, 1, row) + for _, reason := range flat.View.Kept { + assert.Equal(t, ir.ReasonDegradedLowering, reason, row) + } + } + for _, row := range rows { + for spelling, schema := range row.Spellings { + _, diags := compileAnnotationSpec(t, "dead", admissionSpec("3.1.0", "", append(slices.Clone(besideShared), "P: "+schema)...)) + messages := messagesBeneath(diags, diag.UnsatisfiableSchema, "/components/schemas/P") + require.Len(t, messages, 1, "%s %s", row.Name, spelling) + assert.Equal(t, 1, unsatisfiableAt(diags, "/components/schemas/P"), + "%s %s: the report is at the schema", row.Name, spelling) + } + } +} + +// unsatisfiableAt is how many unsatisfiable-schema findings are drawn at +// pointer itself. +func unsatisfiableAt(diags []ir.Diagnostic, pointer string) int { + count := 0 + for _, diagnostic := range diags { + if diagnostic.Code == diag.UnsatisfiableSchema && string(diagnostic.Provenance.Pointer) == pointer { + count++ + } + } + return count +} + +// TestUnionBesideBody_TwoUnionsAreReadTogether holds that a oneOf and an anyOf +// conjoin wherever each is written: the chosen union's branch sharing no kind +// with the other is dead, and where only null survives the position is the +// closed empty Enum behind a nullable reference (GitHub #2115), and one written +// beside an allOf whose entry writes the other lowers as the two on one schema, +// whichever is beside the allOf (GitHub #2110). +func TestUnionBesideBody_TwoUnionsAreReadTogether(t *testing.T) { + t.Parallel() + shared := []string{ + "T: {type: object, properties: {a: {type: string}}}", + "TN: {type: [object, 'null'], properties: {a: {type: string}}}", + } + rows := openapitest.Rows(map[string][2]string{ + "V": {"", "oneOf: [{type: string}, {type: integer}], anyOf: [{type: integer}, {type: boolean}]"}, + "NullAlone": {"", "oneOf: [{type: string}, {type: 'null'}], anyOf: [{type: integer}, {type: 'null'}]"}, + "Beside": {"$ref: '#/components/schemas/TN'", + "oneOf: [{type: object, properties: {x: {type: string}}}, {type: 'null'}], anyOf: [{type: string}, {type: 'null'}]"}, + "Mixed": {"type: object, properties: {a: {type: string}}", + "oneOf: [{required: [a]}], anyOf: [{properties: {x: {type: string}}}, {properties: {y: {type: string}}}]"}, + }) + readings := compileSpellingRows(t, shared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + + v := readings[false]["V"]["Flat"]["component"] + assert.Equal(t, ir.KindUnion, v.View.Kind) + assert.Equal(t, []string{"integer"}, refsOf(v.View.Variants), "integers alone are admitted") + assert.Equal(t, map[string]ir.UnmodeledReason{ + "openapi:oneOf": ir.ReasonDegradedLowering, "openapi:anyOf": ir.ReasonDegradedLowering, + }, v.View.Kept, "the union holding a dead branch and the one passed over, each kept once") + _, diags := compileAnnotationSpec(t, "pair", admissionSpec("3.1.0", "", "V: "+openapitest.RowNamed(t, rows, "V").Spellings["Flat"])) + requireOneUnsatisfiable(t, diags, "/components/schemas/V", "/components/schemas/V/oneOf", "oneOf/0") + for _, row := range []string{"NullAlone", "Beside"} { + flat := readings[false][row]["Flat"]["component"] + assert.Equal(t, ir.KindEnum, flat.View.Kind, row) + assert.Empty(t, flat.View.Members, row) + assert.True(t, flat.View.Closed, row) + assert.True(t, flat.View.Nullable, "%s: the reference admits null", row) + assert.Equal(t, ir.ReasonDegradedLowering, flat.View.Kept["openapi:oneOf"], row) + assert.Equal(t, ir.ReasonDegradedLowering, flat.View.Kept["openapi:anyOf"], row) + } +} + +// TestUnionBesideBody_NullAloneIsTheClosedEmptyEnum holds that a union +// sharing null alone with a type list holding an object, or with a null type, +// is in every spelling the closed empty Enum behind a nullable reference, +// keeping the union as degraded_lowering with one degraded-construct info +// (GitHub #2111, #2106). +func TestUnionBesideBody_NullAloneIsTheClosedEmptyEnum(t *testing.T) { + t.Parallel() + shared := []string{"Null: {type: 'null'}"} + objectOrNull := "type: [object, 'null'], properties: {a: {type: string}}" + rows := openapitest.Rows(map[string][2]string{ + "ListNull": {objectOrNull, "anyOf: [{type: 'null'}]"}, + "ListRefNull": {objectOrNull, "oneOf: [{$ref: '#/components/schemas/Null'}]"}, + "ListShared": {objectOrNull, "anyOf: [{type: string}, {type: 'null'}]"}, + "TypedNull": {"type: ['null']", "oneOf: [{type: 'null'}]"}, + "TypedEnum": {"type: ['null']", "oneOf: [{enum: [null]}]"}, + "TypedRefNull": {"type: ['null']", "oneOf: [{$ref: '#/components/schemas/Null'}]"}, + }) + readings := compileSpellingRows(t, shared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range rows { + flat := readings[false][row.Name]["Flat"]["component"] + assert.Equal(t, ir.KindEnum, flat.View.Kind, row.Name) + assert.Empty(t, flat.View.Members, row.Name) + assert.True(t, flat.View.Closed, row.Name) + assert.True(t, flat.View.Nullable, "%s: the reference admits null", row.Name) + keyword := "openapi:oneOf" + if strings.Contains(row.Spellings["Flat"], "anyOf") { + keyword = "openapi:anyOf" + } + assert.Equal(t, ir.ReasonDegradedLowering, flat.View.Kept[keyword], row.Name) + assert.Contains(t, flat.Findings, "info "+diag.DegradedConstruct, row.Name) + assert.NotContains(t, flat.Findings, "info "+diag.ValidationOnlyKeyword, row.Name) + } +} + +// TestUnionBesideBody_ADiscriminatorStaysWithItsUnion holds that a union +// alone on an allOf entry, its discriminator written beside it, beside the +// allOf or on another entry, lowers as the union written with it at the +// schema: a Union of the branches routed by the discriminator, with a null +// branch the nullable reference to the other, and so with a oneOf and an +// anyOf, the discriminator on either (GitHub #2104). +func TestUnionBesideBody_ADiscriminatorStaysWithItsUnion(t *testing.T) { + t.Parallel() + shared := []string{ + "X: {type: object, properties: {id: {type: string}}}", + "Y: {type: object, properties: {id: {type: string}}}", + } + const disc = "discriminator: {propertyName: id}" + refs := "oneOf: [{$ref: '#/components/schemas/X'}, {$ref: '#/components/schemas/Y'}]" + withNull := "oneOf: [{$ref: '#/components/schemas/X'}, {type: 'null'}]" + const required = "anyOf: [{required: [id]}]" + rows := []openapitest.Row{ + {Name: "Refs", Spellings: openapitest.Spellings(refs, disc)}, + {Name: "WithNull", Spellings: openapitest.Except(openapitest.Spellings(withNull, disc), + "a discriminator on an entry beside a union with a null branch is kept apart from the union, as beside a distributing allOf", + "UnionEntry")}, + {Name: "Pair", Spellings: pairWithDiscriminator(refs, required, disc)}, + } + readings := compileSpellingRows(t, shared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range []string{"Refs", "Pair"} { + flat := readings[false][row]["Flat"]["component"].View + assert.Equal(t, ir.KindUnion, flat.Kind, row) + assert.Equal(t, []string{"component X", "component Y"}, refsOf(flat.Variants), row) + assert.Equal(t, "id", flat.Discriminator, row) + } +} + +// pairWithDiscriminator writes the chosen union, the one passed over and a +// discriminator in every placement Spellings gives three parts, and on the +// entry of the one or the other, which no placement of parts alone names: a +// discriminator stays with the union it routes on whichever entry holds it. +func pairWithDiscriminator(chosen, passed, discriminator string) map[string]string { + spellings := openapitest.Spellings("", chosen, passed, discriminator) + spellings["OnPassed"] = "{allOf: [{" + chosen + "}, {" + passed + ", " + discriminator + "}]}" + spellings["OnChosen"] = "{allOf: [{" + chosen + ", " + discriminator + "}, {" + passed + "}]}" + return spellings +} + +// TestUnionBesideBody_NotesBesideAUnionAreNoBody holds that an allOf of notes +// alone, or of nothing, beside a union or holding it is no body to distribute: +// each spelling lowers as the union with the notes written beside it (GitHub +// #2105). A $ref to a schema stating nothing is no body either, but nothing +// reads it, so it is kept verbatim, with its one info, beside that lowering. +func TestUnionBesideBody_NotesBesideAUnionAreNoBody(t *testing.T) { + t.Parallel() + shared := []string{ + "X: {type: object, properties: {id: {type: string}}}", + "A: {type: object, properties: {x: {type: string}}}", + "B: {type: object, properties: {y: {type: integer}}}", + "E: {}", + } + nullable := "oneOf: [{$ref: '#/components/schemas/X'}, {type: 'null'}]" + pair := "oneOf: [{type: string}], anyOf: [{type: integer}]" + objects := "oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]" + const ref = "$ref: '#/components/schemas/E'" + rows := []openapitest.Row{ + {Name: "Nullable", Spellings: openapitest.Spellings(nullable, "description: d")}, + {Name: "Pair", Spellings: openapitest.Spellings("description: d", openapitest.SplitKeywords(pair)...)}, + {Name: "PairEmpty", Spellings: alsoSpelt(openapitest.Spellings("{}", openapitest.SplitKeywords(pair)...), + "Ref", only(openapitest.Spellings(ref, openapitest.SplitKeywords(pair)...), "Beside"))}, + {Name: "Typed", Spellings: alsoSpelt(openapitest.Spellings("type: object", objects), + "UnionFirst", only(openapitest.Spellings(objects, "type: object"), "UnionEntry"))}, + } + readings := compileSpellingRows(t, shared, rows) + forgiveKeptRef(t, readings, rows, ref) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range []string{"Pair", "PairEmpty"} { + assert.Contains(t, readings[false][row]["Flat"]["component"].Findings, "warning "+diag.UnsatisfiableSchema, + "%s: the pair shares no value", row) + } +} + +// TestUnionBesideBody_ATypeListOnAnEntryIsReadAsBesideTheUnion holds that a +// type list holding an object and null, beside a union or on an entry beside +// it, is read alike: no variant keeps the list (GitHub #2112). +func TestUnionBesideBody_ATypeListOnAnEntryIsReadAsBesideTheUnion(t *testing.T) { + t.Parallel() + shared := []string{"Null: {type: 'null'}"} + rows := openapitest.Rows(map[string][2]string{ + "Members": {"type: [object, 'null'], properties: {a: {type: string}}", + "oneOf: [{type: object, properties: {x: {type: string}}}]"}, + "Pair": {"type: [object, 'null']", "oneOf: [{type: object}], anyOf: [{type: object, properties: {p: " + + "{type: string}}}, {$ref: '#/components/schemas/Null'}]"}, + }) + readings := compileSpellingRows(t, shared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range []string{"Members", "Pair"} { + for _, variant := range readings[false][row]["Flat"]["component"].View.Variants { + assert.NotContains(t, variant.Kept, "openapi:type", "%s: no variant keeps the list", row) + } + } +} + +// TestUnionBesideBody_ADeadBranchIsReadAgainstAnyRest holds that a branch +// sharing no kind with a rest admitting an object and a string is dead, as +// beside a rest of objects alone: no variant, the branch kept under its own +// key, one report at the schema, as a body holding an object keeps a dead +// branch; that a string or null beside an object or null leaves null alone; +// and that two unions sharing no value are reported (GitHub #2089). +func TestUnionBesideBody_ADeadBranchIsReadAgainstAnyRest(t *testing.T) { + t.Parallel() + rows := openapitest.Rows(map[string][2]string{ + "ObjectOrString": {"type: [object, string]", "oneOf: [{$ref: '#/components/schemas/A'}, {type: boolean}]"}, + "StringOrNull": {"type: [string, 'null']", "oneOf: [{$ref: '#/components/schemas/A'}, {type: 'null'}]"}, + }) + readings := compileSpellingRows(t, besideShared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + objectOrString := readings[false]["ObjectOrString"]["Flat"]["component"] + assert.Equal(t, ir.KindUnion, objectOrString.View.Kind) + assert.Len(t, objectOrString.View.Variants, 1, "the boolean branch is no variant") + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf/1": ir.ReasonDegradedLowering}, objectOrString.View.Kept, + "the dead branch is kept under its own key") + assert.Equal(t, []string{"warning " + diag.UnsatisfiableSchema}, notInfos(objectOrString.Findings)) + _, flatDiags := compileAnnotationSpec(t, "rest", admissionSpec("3.1.0", "", append(slices.Clone(besideShared), + "P: "+openapitest.RowNamed(t, rows, "ObjectOrString").Spellings["Flat"])...)) + requireOneUnsatisfiable(t, flatDiags, "/components/schemas/P", "/components/schemas/P", "oneOf/1") + stringOrNull := readings[false]["StringOrNull"]["Flat"]["component"] + assert.Equal(t, ir.KindEnum, stringOrNull.View.Kind, "null alone is admitted") + assert.True(t, stringOrNull.View.Nullable) + + _, diags := compileAnnotationSpec(t, "two", admissionSpec("3.1.0", "", + "Two: {allOf: [{oneOf: [{type: string}, {type: integer}]}, {oneOf: [{type: boolean}, {type: 'null'}]}]}")) + assert.Equal(t, 1, countBeneath(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/Two"), + "two unions sharing no value draw one report") +} + +// TestUnionBesideBody_ADeadBranchBesideObjectsAndStringsIsNamedSo holds a +// boolean branch beside a rest admitting an object or a string, the union on +// an entry, beside an allOf and flat, to no variant, kept, with one warning +// whose words say what the rest admits, never objects alone, as beside an +// object; and two unions sharing no value to one warning (GitHub #2089). +func TestUnionBesideBody_ADeadBranchBesideObjectsAndStringsIsNamedSo(t *testing.T) { + t.Parallel() + const union = "oneOf: [{$ref: '#/components/schemas/A'}, {type: boolean}]" + doc, diags := compileAnnotationSpec(t, "rest", admissionSpec("3.1.0", "", + "A: {type: object, properties: {a: {type: string}}}", + "ObjEntry: {allOf: [{type: object}, {"+union+"}]}", + "OSEntry: {allOf: [{type: [object, string]}, {"+union+"}]}", + "OSBeside: {allOf: [{type: [object, string]}], "+union+"}", + "OSFlat: {type: [object, string], "+union+"}", + "ObjFlat: {type: object, "+union+"}", + "Two: {allOf: [{oneOf: [{type: string}, {type: integer}]}, {oneOf: [{type: boolean}, {type: 'null'}]}]}")) + for _, name := range []string{"ObjEntry", "OSEntry", "OSBeside", "OSFlat", "ObjFlat"} { + union, ok := kindNode(t, doc, componentID(name)).(*ir.Union) + require.True(t, ok, name) + assert.Len(t, union.Variants, 1, "%s: the boolean branch is no variant", name) + assert.Contains(t, union.Unmodeled, "openapi:oneOf/1", name) + messages := messagesBeneath(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name) + require.Len(t, messages, 1, name) + assert.Contains(t, messages[0], "boolean", name) + if strings.HasPrefix(name, "OS") { + assert.NotContains(t, messages[0], "objects alone", "%s: the rest admits a string too", name) + } + } + for _, name := range []string{"OSBeside", "OSFlat"} { + assert.Contains(t, messagesBeneath(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name)[0], "object or string", name) + } + assert.Contains(t, messagesBeneath(diags, diag.UnsatisfiableSchema, "/components/schemas/ObjFlat")[0], "admits objects alone") + assert.Equal(t, 1, countBeneath(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/Two"), + "two unions sharing no value draw one report") +} + +// notInfos is the findings of findings that are not infos. +func notInfos(findings []string) []string { + return slices.DeleteFunc(slices.Clone(findings), isInfo) +} + +// TestUnionBesideBody_AnEntryKeepsWhatItCannotHoldOnceOnTheUnion holds that a +// keyword the IR has no home for, written beside a union on an allOf entry, is +// kept once on the Union as beside the allOf, no variant copying it (GitHub +// #2054). +func TestUnionBesideBody_AnEntryKeepsWhatItCannotHoldOnceOnTheUnion(t *testing.T) { + t.Parallel() + shared := []string{ + "T: {type: object, properties: {a: {type: string}}}", + "M: {$dynamicAnchor: m, type: object, properties: {m: {type: string}}}", + } + union := "oneOf: [{type: object, properties: {b: {type: string}}}, {type: object, properties: {c: {type: string}}}]" + for keyword, written := range map[string]string{ + "$vocabulary": "$vocabulary: {'https://json-schema.org/draft/2020-12/vocab/core': true}", + "$dynamicRef": "$dynamicRef: '#m'", + } { + t.Run(keyword, func(t *testing.T) { + t.Parallel() + rows := []openapitest.Row{{Name: "Kept", Spellings: openapitest.Spellings("$ref: '#/components/schemas/T'", written, union)}} + readings := compileSpellingRows(t, shared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Beside") + entry := readings[false]["Kept"]["Entry"]["component"].View + assert.Equal(t, ir.KindUnion, entry.Kind) + assert.Contains(t, entry.Kept, "openapi:"+keyword, "the Union keeps the keyword") + for i, variant := range entry.Variants { + assert.Empty(t, variant.Kept, "variant %d keeps nothing", i) + } + }) + } +} + +// TestUnionBesideBody_ResourceKeywordsInABranchDeclareNoShape holds that a +// branch narrowing an object body and writing $schema, $vocabulary or an $id +// with no relative reference beneath it declares no shape, as one writing an +// $anchor: the body's Model keeps the union as validation logic, with one +// validation-only finding; an $id over a relative reference does declare +// shape (GitHub #1859). +func TestUnionBesideBody_ResourceKeywordsInABranchDeclareNoShape(t *testing.T) { + t.Parallel() + body := "type: object, properties: {a: {type: string}, b: {type: string}}" + branch := func(keyword string) string { return "oneOf: [{required: [a], " + keyword + "}, {required: [b]}]" } + rows := openapitest.Rows(map[string][2]string{ + "Anchor": {body, branch("$anchor: first")}, + "Schema": {body, branch("$schema: 'https://json-schema.org/draft/2020-12/schema'")}, + "Vocabulary": {body, branch("$vocabulary: {'https://json-schema.org/draft/2020-12/vocab/core': true}")}, + "Identifier": {body, branch("$id: 'https://example.com/first.json'")}, + }) + readings := compileSpellingRows(t, nil, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range rows { + flat := readings[false][row.Name]["Flat"]["component"] + assert.Equal(t, ir.KindModel, flat.View.Kind, row.Name) + assert.Equal(t, ir.ReasonValidationOnly, flat.View.Kept["openapi:oneOf"], row.Name) + assert.Equal(t, []string{"info " + diag.ValidationOnlyKeyword}, flat.Findings, row.Name) + } + + doc, _ := compileAnnotationSpec(t, "relative", admissionSpec("3.1.0", "", + "Target: {$id: 'https://example.com/target.json', type: object, properties: {t: {type: string}}}", + "S: {"+body+", oneOf: [{required: [a], $id: 'https://example.com/first.json', properties: {a: {$ref: 'target.json'}}}, {required: [b]}]}")) + assert.Equal(t, ir.KindUnion, kindNode(t, doc, componentID("S")).Kind(), "an $id over a relative reference declares shape") +} diff --git a/compilers/openapi/e2e/union_body_by_kind_test.go b/compilers/openapi/e2e/union_body_by_kind_test.go new file mode 100644 index 000000000..1b44e0d0d --- /dev/null +++ b/compilers/openapi/e2e/union_body_by_kind_test.go @@ -0,0 +1,65 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// byKindShared are the components the by-kind cases name. +var byKindShared = []string{"A: {type: object, properties: {a: {type: string}}}"} + +// TestUnionBesideBody_ABodyDistributesByKind holds that a body beside a union +// of an object and another kind splits by kind, in every spelling: the object +// branch's variant composes the body's object keywords over the branch, a +// string branch's is a Scalar over the branch holding the body's string +// bounds, a branch no body keyword applies to is the branch's own node, and a +// branch admitting two kinds is the Union of its kinds, each holding the +// body's keywords of its kind (GitHub #2046). +func TestUnionBesideBody_ABodyDistributesByKind(t *testing.T) { + t.Parallel() + const members = "properties: {c: {type: string}}, minProperties: 1" + ref := "{$ref: '#/components/schemas/A'}" + rows := openapitest.Rows(map[string][2]string{ + "Split": {members + ", minLength: 2", "oneOf: [" + ref + ", {type: string}]"}, + "OwnNode": {members, "oneOf: [" + ref + ", {type: integer}]"}, + "TwoKinds": {members + ", minLength: 2", "oneOf: [" + ref + ", {type: [string, integer]}]"}, + }) + readings := compileSpellingRows(t, byKindShared, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + view := func(row string) bodyView { return readings[false][row]["Flat"]["component"].View } + + for _, row := range []string{"Split", "OwnNode", "TwoKinds"} { + require.Equal(t, ir.KindUnion, view(row).Kind, row) + require.Len(t, view(row).Variants, 2, row) + object := view(row).Variants[0] + assert.Equal(t, ir.KindModel, object.Kind, "%s: the object branch composes the body", row) + require.NotNil(t, object.Base, row) + assert.Equal(t, "component A", object.Base.Ref, row) + assert.Equal(t, []string{"c"}, object.Properties, row) + assert.Contains(t, object.Constraints, `"minProperties":1`, row) + assert.NotContains(t, object.Constraints, "minLength", "%s: no string bound on the object", row) + assert.Empty(t, view(row).Kept, "%s: nothing is kept", row) + } + text := view("Split").Variants[1] + assert.Equal(t, ir.KindScalar, text.Kind, "the string branch is a Scalar") + require.NotNil(t, text.Base) + assert.Equal(t, "string", text.Base.Ref) + assert.Contains(t, text.Constraints, `"minLength":2`) + assert.NotContains(t, text.Constraints, "minProps") + + assert.Equal(t, "integer", view("OwnNode").Variants[1].Ref, "no body keyword applies to an integer") + + kinds := view("TwoKinds").Variants[1] + require.Equal(t, ir.KindUnion, kinds.Kind, "a type list is the Union of its kinds") + require.Len(t, kinds.Variants, 2) + assert.Contains(t, kinds.Variants[0].Constraints, `"minLength":2`, "the string kind holds the string bound") + assert.Equal(t, "integer", kinds.Variants[1].Ref, "the integer kind holds nothing") +} diff --git a/compilers/openapi/e2e/union_election_bound_test.go b/compilers/openapi/e2e/union_choice_bound_test.go similarity index 72% rename from compilers/openapi/e2e/union_election_bound_test.go rename to compilers/openapi/e2e/union_choice_bound_test.go index dc797b823..7b3faf3c7 100644 --- a/compilers/openapi/e2e/union_election_bound_test.go +++ b/compilers/openapi/e2e/union_choice_bound_test.go @@ -12,14 +12,14 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestElection_AUnionAndTheWordsItTiesWithAreTheUnionHoldingTheBound holds -// that an allOf of a union and an entry refining it lowers to the union, -// standing at the position whichever is written first: the branch's bound is -// held once, in Union.Constraints, at a property and at a component, no entry -// is kept and nothing is reported (docs/compilers/openapi.md#allof-refinement). -func TestElection_AUnionAndTheWordsItTiesWithAreTheUnionHoldingTheBound(t *testing.T) { +// TestChoice_AUnionAndTheWordsItTiesWithAreTheUnionHoldingTheBound holds that +// an allOf of a union and an entry refining it lowers to the union, at the +// position whichever is written first: the branch's bound is held once, in +// Union.Constraints, at a property and at a component, no entry is kept and +// nothing is reported (docs/compilers/openapi.md#allof-refinement). +func TestChoice_AUnionAndTheWordsItTiesWithAreTheUnionHoldingTheBound(t *testing.T) { t.Parallel() - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -36,7 +36,7 @@ func TestElection_AUnionAndTheWordsItTiesWithAreTheUnionHoldingTheBound(t *testi assert.Zero(t, degradedInfosAt(diags, "C")) property := requireModelOf(t, doc, "N").Properties[0] - assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/N/properties/p"), property.Type.Target, "the union stands at the property") + assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/N/properties/p"), property.Type.Target, "the union sits at the property") for _, id := range []ir.TypeID{property.Type.Target, componentID("C")} { union, ok := kindNode(t, doc, id).(*ir.Union) require.True(t, ok, "%s is the union, not the string beside it", id) diff --git a/compilers/openapi/e2e/union_election_entry_test.go b/compilers/openapi/e2e/union_choice_entry_test.go similarity index 63% rename from compilers/openapi/e2e/union_election_entry_test.go rename to compilers/openapi/e2e/union_choice_entry_test.go index a7b3281b9..336072ea7 100644 --- a/compilers/openapi/e2e/union_election_entry_test.go +++ b/compilers/openapi/e2e/union_choice_entry_test.go @@ -16,11 +16,12 @@ import ( "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) -// bothKeywordsSite is a position a schema writing a oneOf and an anyOf stands -// at: the pointer it is written at, and the document holding it beside the +// bothKeywordsSite is a position a schema writing a oneOf and an anyOf sits at: +// the pointer it is written at, and the document holding it beside the // component T, the components declared in the order given. type bothKeywordsSite struct { name string @@ -69,34 +70,33 @@ func bothKeywordsSpellings(body, anyOf string) map[string]string { return unionPairSpellings(body, bothKeywordsOneOf, anyOf) } -// unionPairSpellings is bothKeywordsSpellings for the oneOf one. +// unionPairSpellings is bothKeywordsSpellings for the oneOf one: the oneOf and +// the anyOf in every placement openapitest.Spellings gives a body and two +// keywords. Entry is the one each other is compared to. func unionPairSpellings(body, one, anyOf string) map[string]string { - spellings := map[string]string{ - "one entry": "{allOf: [" + body + ", {oneOf: " + one + ", anyOf: " + anyOf + "}]}", - "one entry, the anyOf first": "{allOf: [" + body + ", {anyOf: " + anyOf + ", oneOf: " + one + "}]}", - "one entry, before the body": "{allOf: [{oneOf: " + one + ", anyOf: " + anyOf + "}, " + body + "]}", - "beside the allOf": "{allOf: [" + body + "], oneOf: " + one + ", anyOf: " + anyOf + "}", - "two entries": "{allOf: [" + body + ", {oneOf: " + one + "}, {anyOf: " + anyOf + "}]}", - "two entries, the anyOf first": "{allOf: [" + body + ", {anyOf: " + anyOf + "}, {oneOf: " + one + "}]}", - "two entries, before the body": "{allOf: [{anyOf: " + anyOf + "}, {oneOf: " + one + "}, " + body + "]}", - "two entries one allOf deeper": "{allOf: [" + body + ", {allOf: [{oneOf: " + one + "}, {anyOf: " + anyOf + "}]}]}", - "one entry one allOf deeper": "{allOf: [" + body + ", {allOf: [{oneOf: " + one + ", anyOf: " + anyOf + "}]}]}", - } - if inline, ok := strings.CutPrefix(body, "{type: object, "); ok { - spellings["beside the body"] = "{type: object, oneOf: " + one + ", anyOf: " + anyOf + ", " + inline + return pairPlacements(body, "oneOf: "+one, "anyOf: "+anyOf) +} + +// pairPlacements is openapitest.Spellings of body and the parts, less, for a +// $ref body, the placements writing the parts beside the $ref itself. +func pairPlacements(body string, parts ...string) map[string]string { + spellings := openapitest.Spellings(body, parts...) + if !strings.Contains(body, "$ref") { + return spellings } - return spellings + return openapitest.Except(spellings, "a $ref beside keywords is the use of its target, not an entry the choice reads", + "Flat", "FlatPartsRev", "UnionEntry", "OneEntry", "OneEntryUnionEntry") } -// TestElection_BothKeywordsOnOneEntryDistributeTheOneOf holds that a oneOf -// and an anyOf written on one inline allOf entry lower as the same two do -// beside the allOf, on two entries and beside the body's own keywords: at every -// version, at a component, a property, items and a parameter, over an inline -// body and a $ref, in either order of the entries, of the keywords and of the -// components. The position is a Union of the oneOf keeping neither union, -// each variant composing the body and its branch and keeping the anyOf, as -// validation logic where its branches declare no shape against the position. -func TestElection_BothKeywordsOnOneEntryDistributeTheOneOf(t *testing.T) { +// TestChoice_BothKeywordsOnOneEntryDistributeTheOneOf holds that a oneOf +// and an anyOf on one inline allOf entry lower as the same two do beside the +// allOf, on two entries and beside the body's own keywords: at every version, +// at a component, a property, items and a parameter, over an inline body and +// a $ref, in either order of the entries, keywords and components. The +// position is a Union of the oneOf keeping the anyOf once, as validation logic +// where its branches declare no shape, each variant composing the body and +// its branch and keeping nothing. +func TestChoice_BothKeywordsOnOneEntryDistributeTheOneOf(t *testing.T) { t.Parallel() bodies := []struct{ name, schema string }{ {"inline", "{type: object, properties: {a: {type: string}}}"}, @@ -130,47 +130,57 @@ func TestElection_BothKeywordsOnOneEntryDistributeTheOneOf(t *testing.T) { // compileSpellingsAlike compiles each spelling at site, its components in both // orders, and holds every document equal to the one entry's with the components // as declared, read with no allOf entry's index, and returns that document. An -// info is drawn at each entry a union is kept on (GitHub #2057), so infos are -// compared as a set. +// info is drawn at each entry a union is kept on, which the spellings place +// apart (docs/compilers/openapi.md#allof-inline-residue), so infos are compared +// as a set. func compileSpellingsAlike( t *testing.T, site bothKeywordsSite, version string, spellings map[string]string, ) (*ir.Document, []ir.Diagnostic) { t.Helper() noEntry := func(text string) string { return entryNodes.ReplaceAllString(text, "") } view := func(doc *ir.Document) any { - v, ok := electionView(t, doc, noEntry).(map[string]any) + v, ok := choiceView(t, doc, noEntry).(map[string]any) require.True(t, ok) v["findings"] = infosOnce(v["findings"]) return v } - doc, diags := compileAnnotationSpec(t, "both", site.doc(version, spellings["one entry"], false)) + doc, diags := compileAnnotationSpec(t, "both", site.doc(version, spellings["Entry"], false)) want := view(doc) + var differing []string for _, name := range slices.Sorted(maps.Keys(spellings)) { for _, reversed := range []bool{false, true} { got, _ := compileAnnotationSpec(t, "both", site.doc(version, spellings[name], reversed)) - if diff := cmp.Diff(want, view(got)); diff != "" { - t.Errorf("%s, reversed %t, differs from one entry (-one entry +%s):\n%s", name, reversed, name, diff) + diff := cmp.Diff(want, view(got)) + if diff == "" { + continue + } + if differing = append(differing, fmt.Sprintf("%s, reversed %t", name, reversed)); len(differing) <= maxReportedDifferences { + t.Errorf("%s, reversed %t, differs from Entry (-Entry +%s):\n%s", name, reversed, name, openapitest.Excerpt(diff, maxDifferenceLines)) } } } + if len(differing) > maxReportedDifferences { + t.Errorf("and %d more spellings differ from Entry, none printed: %s", len(differing)-maxReportedDifferences, + strings.Join(differing[maxReportedDifferences:min(len(differing), maxNamedDifferences)], "; ")) + } return doc, diags } // requireDistributedOneOf holds the node at the position at to a Union of the -// oneOf written on its allOf's entry 1, keeping neither union, whose variants -// each compose the body, T where ref says so, and the branch, and keep the -// anyOf for reason. +// oneOf written on its allOf's entry 1, keeping the anyOf once for reason, +// whose variants each compose the body, T where ref says so, and the branch, +// and keep nothing. func requireDistributedOneOf(t *testing.T, doc *ir.Document, at jsontext.Pointer, ref bool, reason ir.UnmodeledReason) { t.Helper() union, ok := kindNode(t, doc, entryPositionID(at)).(*ir.Union) require.True(t, ok, "the oneOf distributes") assert.True(t, union.Exclusive) - assert.Empty(t, keptOn(union), "the Union keeps neither union") + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": reason}, keptOn(union), "the Union keeps the anyOf once") require.Len(t, union.Variants, 2) for i, irVariant := range union.Variants { variant, isModel := kindNode(t, doc, irVariant.Type.Target).(*ir.Model) require.True(t, isModel, "variant %d is a model", i) - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": reason}, keptOn(variant), "variant %d keeps the anyOf", i) + assert.Empty(t, keptOn(variant), "variant %d keeps nothing", i) composed := slices.Clone(variant.Mixins) if variant.Base != nil { composed = append(composed, *variant.Base) @@ -188,14 +198,14 @@ func requireDistributedOneOf(t *testing.T, doc *ir.Document, at jsontext.Pointer } } -// TestElection_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf holds that +// TestChoice_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf holds that // an entry writing a oneOf and an anyOf over a $ref lowers as the same keywords // beside the allOf where the oneOf is not distributed or is routed: every // branch admitting no object keeps both unions on a model of the $ref, with a // warning; a $ref branch naming nothing keeps both, with its error; a // discriminator written with them routes the distributed variants. The // findings named are the one entry's. -func TestElection_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf(t *testing.T) { +func TestChoice_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf(t *testing.T) { t.Parallel() objects := "[{type: object, properties: {d: {type: string}}}, {type: object, properties: {e: {type: string}}}]" cases := []struct { @@ -204,7 +214,7 @@ func TestElection_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf(t *testin union bool }{ {"no branch admits an object", "", "[{type: string}, {type: array}]", objects, - []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/P"}}, false}, + []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P"}}, false}, {"a branch names nothing", "", "[{$ref: '#/components/schemas/Missing'}, {type: object}]", objects, []wantFinding{{code: diag.UnresolvedRef, pointer: "/components/schemas/P/allOf/1/oneOf/0"}}, false}, {"a discriminator routes them", "discriminator: {propertyName: a}, ", bothKeywordsOneOf, @@ -215,14 +225,8 @@ func TestElection_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf(t *testin for _, tc := range cases { t.Run(version+"/"+tc.name, func(t *testing.T) { t.Parallel() - oneFirst := tc.extra + "oneOf: " + tc.oneOf + ", anyOf: " + tc.anyOf - anyFirst := tc.extra + "anyOf: " + tc.anyOf + ", oneOf: " + tc.oneOf - doc, diags := compileSpellingsAlike(t, site, version, map[string]string{ - "one entry": "{allOf: [" + entryRef + ", {" + oneFirst + "}]}", - "one entry, the anyOf first": "{allOf: [" + entryRef + ", {" + anyFirst + "}]}", - "one entry, before the body": "{allOf: [{" + oneFirst + "}, " + entryRef + "]}", - "beside the allOf": "{allOf: [" + entryRef + "], " + oneFirst + "}", - }) + doc, diags := compileSpellingsAlike(t, site, version, + pairPlacements(entryRef, tc.extra+"oneOf: "+tc.oneOf, "anyOf: "+tc.anyOf)) requireErrorsAndWarnings(t, diags, slices.Clone(tc.want)) node := kindNode(t, doc, componentID("P")) if tc.union { @@ -241,16 +245,16 @@ func TestElection_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf(t *testin } } -// TestElection_AnEntryWritingBothBesideAnotherOneOfDistributesNeither holds -// that an entry writing a oneOf and an anyOf, beside another writing a oneOf -// and a body, distributes neither oneOf, in both orders of the entries and of -// the components: two unions of one keyword elect none, whatever else an entry +// TestChoice_AnEntryWritingBothBesideAnotherOneOfDistributesNeither holds that +// an entry writing a oneOf and an anyOf, beside another writing a oneOf and a +// body, distributes neither oneOf, in both orders of the entries and of the +// components: two unions of one keyword choose none, whatever else an entry // writes. Both entries are kept whole, each reported. -func TestElection_AnEntryWritingBothBesideAnotherOneOfDistributesNeither(t *testing.T) { +func TestChoice_AnEntryWritingBothBesideAnotherOneOfDistributesNeither(t *testing.T) { t.Parallel() both := "{" + oneObjBranches + ", " + anyObjBranches + "}" other := "{oneOf: [{type: object, properties: {f: {type: string}}}, {type: object, properties: {g: {type: string}}}]}" - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -258,19 +262,22 @@ func TestElection_AnEntryWritingBothBesideAnotherOneOfDistributesNeither(t *test }) requireErrorsAndWarnings(t, diags, nil) - assert.Empty(t, unionsUnder(doc, "BothOne"), "neither oneOf stands for the position") + assert.Empty(t, unionsUnder(doc, "BothOne"), "neither oneOf is the position's") requireKeptEntries(t, kindNode(t, doc, componentID("BothOne")), "both entries", 0, 1) requireOneInfoAtEach(t, diags, "BothOne", "both entries", 0, 1) }) } } -// TestElection_BothKeywordsOnOneEntryOfARoutedSubtypeKeepTheAnyOfAsBeside holds +// TestChoice_BothKeywordsOnOneEntryOfARoutedSubtypeKeepTheAnyOfAsBeside holds // that a subtype a discriminator routes to, writing a oneOf and an anyOf on one // entry of its allOf, composes the oneOf as a mixin keeping the anyOf as the -// same keywords beside the allOf do: as validation logic where its branches -// restate what the position declares, though they say more than the entry. -func TestElection_BothKeywordsOnOneEntryOfARoutedSubtypeKeepTheAnyOfAsBeside(t *testing.T) { +// same keywords beside the allOf do, and so does every spelling, the two on +// entries of their own or one beside the allOf among them: the Union keeps the +// anyOf, as validation logic where its branches restate what the position +// declares, though they say more than the entry, and degraded where they +// declare shape, and the Model keeps nothing of either. +func TestChoice_BothKeywordsOnOneEntryOfARoutedSubtypeKeepTheAnyOfAsBeside(t *testing.T) { t.Parallel() base := "Base: {type: object, properties: {kind: {type: string}}, required: [kind], " + "discriminator: {propertyName: kind, mapping: {p: '#/components/schemas/P'}}}" @@ -278,33 +285,42 @@ func TestElection_BothKeywordsOnOneEntryOfARoutedSubtypeKeepTheAnyOfAsBeside(t * return bothKeywordsDoc(version, "", reversed, base, "P: "+schema) }} ref := "{$ref: '#/components/schemas/Base'}" - keywords := "oneOf: " + bothKeywordsOneOf + ", anyOf: [{type: object}, {properties: {kind: {type: string}}}]" + anyOfs := []struct { + name, schema string + reason ir.UnmodeledReason + }{ + {"restating the body", "[{type: object}, {properties: {kind: {type: string}}}]", ir.ReasonValidationOnly}, + {"declaring shape", "[{type: object, properties: {d: {type: string}}}, {type: object, properties: {e: {type: string}}}]", + ir.ReasonDegradedLowering}, + } for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { - t.Run(version, func(t *testing.T) { - t.Parallel() - doc, diags := compileSpellingsAlike(t, site, version, map[string]string{ - "one entry": "{allOf: [" + ref + ", {" + keywords + "}]}", - "beside the allOf": "{allOf: [" + ref + "], " + keywords + "}", + for _, anyOf := range anyOfs { + t.Run(version+"/"+anyOf.name, func(t *testing.T) { + t.Parallel() + spellings := pairPlacements(ref, "oneOf: "+bothKeywordsOneOf, "anyOf: "+anyOf.schema) + doc, diags := compileSpellingsAlike(t, site, version, spellings) + requireErrorsAndWarnings(t, diags, nil) + model, ok := kindNode(t, doc, componentID("P")).(*ir.Model) + require.True(t, ok, "the subtype stays a model") + assert.Empty(t, keptOn(model), "the model keeps nothing of either union") + require.Len(t, model.Mixins, 1) + union, isUnion := kindNode(t, doc, model.Mixins[0].Target).(*ir.Union) + require.True(t, isUnion, "the model composes the oneOf") + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": anyOf.reason}, keptOn(union)) }) - requireErrorsAndWarnings(t, diags, nil) - model, ok := kindNode(t, doc, componentID("P")).(*ir.Model) - require.True(t, ok, "the subtype stays a model") - require.Len(t, model.Mixins, 1) - union, isUnion := kindNode(t, doc, model.Mixins[0].Target).(*ir.Union) - require.True(t, isUnion, "the model composes the oneOf") - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": ir.ReasonValidationOnly}, keptOn(union)) - }) + } } } -// TestElection_TwoUnionsOverABodyLowerAlikeWhereverWritten holds that a oneOf -// and an anyOf over a body lower alike beside the allOf, on one entry or on two, -// at every version and position, where the anyOf alone declares shape, where -// it admits objects alone beside a oneOf branch of another kind, and where it -// shares no kind with the body: the union declaring shape is elected, and the -// other is a conjunct of the rest wherever it is written, which keeps both on -// the body's Model where it shares no kind with the body. -func TestElection_TwoUnionsOverABodyLowerAlikeWhereverWritten(t *testing.T) { +// TestChoice_TwoUnionsOverABodyLowerAlikeWhereverWritten holds that a oneOf and +// an anyOf over a body lower alike beside the allOf, on one entry or on two, at +// every version and position, where the anyOf alone declares shape, where it +// admits objects alone beside a oneOf branch of another kind, and where it +// shares no kind with the body: the union declaring shape is chosen, and the +// other is a conjunct of the rest wherever it is written, kept once on the +// Union, which keeps both on the body's Model where it shares no kind with the +// body. +func TestChoice_TwoUnionsOverABodyLowerAlikeWhereverWritten(t *testing.T) { t.Parallel() objects := "[{type: object, properties: {d: {type: string}}}, {type: object, properties: {e: {type: string}}}]" shapes := []struct { @@ -318,26 +334,28 @@ func TestElection_TwoUnionsOverABodyLowerAlikeWhereverWritten(t *testing.T) { t.Helper() requireErrorsAndWarnings(t, diags, nil) union := requireUnionOf(t, doc, at, 2) - assert.False(t, union.Exclusive, "the anyOf is elected") + assert.False(t, union.Exclusive, "the anyOf is chosen") + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}, keptOn(union), + "the Union keeps the oneOf once") for _, variant := range union.Variants { - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}, - keptOn(kindNode(t, doc, variant.Type.Target)), "each variant keeps the oneOf") + assert.Empty(t, keptOn(kindNode(t, doc, variant.Type.Target)), "no variant keeps it") } }}, {"the anyOf refuses a oneOf branch", "[{type: object, properties: {b: {type: string}}}, {type: array}]", "[{type: object}]", []string{"{properties: {a: {type: string}}}"}, func(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, at jsontext.Pointer) { t.Helper() - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: string(at)}}) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: string(at)}}) union := requireUnionOf(t, doc, at, 1) - assert.Equal(t, degradedKept("openapi:oneOf/1"), keptOn(union), "the dead branch is kept on the Union") + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf/1": ir.ReasonDegradedLowering, "openapi:anyOf": ir.ReasonValidationOnly}, + keptOn(union), "the dead branch and the anyOf are kept on the Union") }}, {"the anyOf shares no kind with the body", bothKeywordsOneOf, "[{type: string}, {type: integer}]", []string{"{type: object, properties: {a: {type: string}}}", entryRef}, func(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, at jsontext.Pointer) { t.Helper() - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: string(at), - contains: []string{"share no value", "string or integer"}}}) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: string(at), + contains: []string{"no value satisfies", "string or integer"}}}) model, ok := kindNode(t, doc, entryPositionID(at)).(*ir.Model) require.True(t, ok, "no instance satisfies the two, so the position is the Model its body gives") assert.Equal(t, map[string]ir.UnmodeledReason{ @@ -369,14 +387,14 @@ func requireUnionOf(t *testing.T, doc *ir.Document, at jsontext.Pointer, n int) return union } -// TestElection_AnEntryHoldingBothIsJudgedWithoutThemAtAnyDepth holds that an +// TestChoice_AnEntryHoldingBothIsJudgedWithoutThemAtAnyDepth holds that an // entry writing a oneOf and an anyOf lowers as one directly on the allOf where // it is nested in an allOf entry, and from 3.1 where it writes them beside a -// $ref to the body: each union is judged against the rest of the position -// read without the entry's own two, wherever the entry is listed. Read with -// them, the rest admits nothing, so a oneOf of strings and integers restated it -// and the anyOf was elected, or an anyOf of them was kept as validation logic. -func TestElection_AnEntryHoldingBothIsJudgedWithoutThemAtAnyDepth(t *testing.T) { +// $ref to the body: each union is judged against the rest of the position read +// without the entry's own two, wherever the entry is listed. Read with them, +// the rest admits nothing, so a oneOf of strings and integers restated it and +// the anyOf was chosen, or an anyOf of them was kept as validation logic. +func TestChoice_AnEntryHoldingBothIsJudgedWithoutThemAtAnyDepth(t *testing.T) { t.Parallel() objects := "[{type: object, properties: {d: {type: string}}}, {type: object, properties: {e: {type: string}}}]" apart := "[{type: string}, {type: integer}]" @@ -389,14 +407,10 @@ func TestElection_AnEntryHoldingBothIsJudgedWithoutThemAtAnyDepth(t *testing.T) for _, pair := range pairs { t.Run(fmt.Sprintf("%s/%s/%s", version, site.name, pair.name), func(t *testing.T) { t.Parallel() - both := "oneOf: " + pair.oneOf + ", anyOf: " + pair.anyOf - spellings := map[string]string{ - "one entry": "{allOf: [" + entryRef + ", {" + both + "}]}", - "one entry, in an allOf": "{allOf: [" + entryRef + ", {allOf: [{" + both + "}]}]}", - "one entry, two allOfs in": "{allOf: [" + entryRef + ", {allOf: [{allOf: [{" + both + "}]}]}]}", - } - if version != "3.0.3" { - spellings["one entry, beside the $ref"] = "{allOf: [{$ref: '#/components/schemas/T', " + both + "}]}" + spellings := openapitest.Spellings(entryRef, "oneOf: "+pair.oneOf, "anyOf: "+pair.anyOf) + if version == "3.0.3" { + spellings = openapitest.Except(spellings, "a $ref beside keywords is a later version's construct", + "Flat", "FlatPartsRev", "UnionEntry", "OneEntry", "OneEntryUnionEntry") } compileSpellingsAlike(t, site, version, spellings) }) diff --git a/compilers/openapi/e2e/union_election_helpers_test.go b/compilers/openapi/e2e/union_choice_helpers_test.go similarity index 86% rename from compilers/openapi/e2e/union_election_helpers_test.go rename to compilers/openapi/e2e/union_choice_helpers_test.go index 91ba93210..db74aeef4 100644 --- a/compilers/openapi/e2e/union_election_helpers_test.go +++ b/compilers/openapi/e2e/union_choice_helpers_test.go @@ -18,13 +18,15 @@ import ( "github.com/dexpace/morphic/ir" ) -// electionVersions are the OpenAPI versions every election case is written at. -var electionVersions = []string{"3.0.3", "3.1.0"} +// choiceVersions are the OpenAPI versions every choice case is written at. +var choiceVersions = []string{"3.0.3", "3.1.0"} // swapEntryIndices names, in a document's JSON, entry 0 of an allOf as entry 1 // and the other way round, so the document compiled from an allOf's entries in -// one order reads in the coordinates of the other. -var swapEntryIndices = strings.NewReplacer("allOf/0", "allOf/1", "allOf/1", "allOf/0") +// one order reads in the coordinates of the other; a key minted from an entry +// (allOf/-/k) names its entry alike. +var swapEntryIndices = strings.NewReplacer("allOf/0", "allOf/1", "allOf/1", "allOf/0", + "allOf/-/0", "allOf/-/1", "allOf/-/1", "allOf/-/0") // positionKey is the members of a node that say where its source lies in the // file, which two spellings of one document never share. @@ -53,12 +55,12 @@ func withoutPositions(tree any) any { } } -// electionView is doc as the comparison of two entry orders reads it: its +// choiceView is doc as the comparison of two entry orders reads it: its // JSON, renamed by rename into the first order's coordinates, with // no sources table and no position, and its findings as a sorted multiset of // severity, code and pointer, which leaves out the words of a message. The // findings sit beside the document under "findings". -func electionView(t *testing.T, doc *ir.Document, rename func(string) string) any { +func choiceView(t *testing.T, doc *ir.Document, rename func(string) string) any { t.Helper() raw, err := json.Marshal(doc) require.NoError(t, err) @@ -98,14 +100,14 @@ func compileInEveryOrder( }) } -// entryNodes names no allOf entry in a document's JSON: the node that stands -// at an entry, whichever entry it is, and the key an entry is kept under, are -// read without the index. -var entryNodes = regexp.MustCompile(`/?allOf/\d+`) +// entryNodes names no allOf entry in a document's JSON: the node that sits at +// an entry, whichever entry it is, and the key an entry is kept under, are read +// without the index. +var entryNodes = regexp.MustCompile(`/?allOf/(-/)?\d+`) -// withoutEntryIndices is compileInEveryOrder for a tie whose pick shows only -// in the entry a node stands at: the two orders compare equal once no entry -// has an index, which is all a tie among alike entries may change. +// withoutEntryIndices is compileInEveryOrder for a tie whose pick shows only in +// the entry a node sits at: the two orders compare equal once no entry has an +// index, which is all a tie among alike entries may change. func withoutEntryIndices( t *testing.T, version string, build func(swapped bool) []string, ) (*ir.Document, []ir.Diagnostic) { @@ -134,8 +136,8 @@ func compileInEveryOrderRenamed( slices.Reverse(schemas) } name := fmt.Sprintf("swapped-%t-reversed-%t", swapped, reversed) - got, found := compileAnnotationSpec(t, "election", admissionSpec(version, "", schemas...)) - view := electionView(t, got, func(text string) string { return rename(text, swapped) }) + got, found := compileAnnotationSpec(t, "choice", admissionSpec(version, "", schemas...)) + view := choiceView(t, got, func(text string) string { return rename(text, swapped) }) if first == nil { first, doc, diags, anchor = view, got, found, name continue @@ -185,7 +187,7 @@ func requireOneInfoAtEach(t *testing.T, diags []ir.Diagnostic, name, what string assert.Equal(t, len(indices), degradedInfosAt(diags, name), "%s: the reports of %s", what, name) } -// The entries the election cases write, each a union naming its kinds. +// The entries the choice cases write, each a union naming its kinds. const ( oneStringInt = "{oneOf: [{type: string}, {type: integer}]}" oneIntBool = "{oneOf: [{type: integer}, {type: boolean}]}" diff --git a/compilers/openapi/e2e/union_election_test.go b/compilers/openapi/e2e/union_choice_test.go similarity index 63% rename from compilers/openapi/e2e/union_election_test.go rename to compilers/openapi/e2e/union_choice_test.go index b034a193c..37c779989 100644 --- a/compilers/openapi/e2e/union_election_test.go +++ b/compilers/openapi/e2e/union_choice_test.go @@ -6,6 +6,7 @@ package e2e_test import ( "fmt" "regexp" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -15,15 +16,15 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestElection_TwoAnyOfUnionsBesideABodyDistributeNeither holds that two anyOf +// TestChoice_TwoAnyOfUnionsBesideABodyDistributeNeither holds that two anyOf // unions whose branches declare objects, beside a body, distribute neither: // the position is the model of the body keeping both entries whole under // their indices, each reported, in both orders. -func TestElection_TwoAnyOfUnionsBesideABodyDistributeNeither(t *testing.T) { +func TestChoice_TwoAnyOfUnionsBesideABodyDistributeNeither(t *testing.T) { t.Parallel() first := "{anyOf: [{type: object, properties: {a: {type: string}}}, {type: object, properties: {b: {type: string}}}]}" second := "{anyOf: [{type: object, properties: {c: {type: string}}}, {type: object, properties: {d: {type: string}}}]}" - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -40,16 +41,16 @@ func TestElection_TwoAnyOfUnionsBesideABodyDistributeNeither(t *testing.T) { } } -// TestElection_TwoAnyOfEntriesThatDeclareNoShapeAreKeptWhole holds an allOf of -// two anyOf entries and nothing else, each only naming required members, as -// the golden spec writes beside an object it composes: written alone it -// refines, two unions of one keyword elect neither, and one key cannot hold -// both, so both are kept whole under their indices as the validation logic -// each is, and reported as that, in both orders of the entries and of the -// components, and no union stands for the position. -func TestElection_TwoAnyOfEntriesThatDeclareNoShapeAreKeptWhole(t *testing.T) { +// TestChoice_TwoAnyOfEntriesThatDeclareNoShapeAreKeptWhole holds an allOf of +// two anyOf entries and nothing else, each only naming required members, as the +// golden spec writes beside an object it composes: written alone it refines, +// two unions of one keyword choose neither, and one key cannot hold both, so +// both are kept whole under their indices as the validation logic each is, and +// reported as that, in both orders of the entries and of the components, and no +// union is the position's. +func TestChoice_TwoAnyOfEntriesThatDeclareNoShapeAreKeptWhole(t *testing.T) { t.Parallel() - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -72,13 +73,14 @@ func TestElection_TwoAnyOfEntriesThatDeclareNoShapeAreKeptWhole(t *testing.T) { } } -// TestElection_ARefIsThePrincipalOverAUnionWhichSaysNothingMoreOfIt holds that +// TestChoice_ARefIsThePrincipalOverAUnionWhichSaysNothingMoreOfIt holds that // an allOf of a $ref to a string and a union of a string and an integer is a -// use of the $ref, nothing kept and nothing reported, whichever is written -// first. -func TestElection_ARefIsThePrincipalOverAUnionWhichSaysNothingMoreOfIt(t *testing.T) { +// use of the $ref, whichever is written first: the integer branch shares no +// kind with the $ref and is dead, reported once at the union, and the union, +// whose other branch restates the $ref, is kept whole (GitHub #2108). +func TestChoice_ARefIsThePrincipalOverAUnionWhichSaysNothingMoreOfIt(t *testing.T) { t.Parallel() - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -86,22 +88,22 @@ func TestElection_ARefIsThePrincipalOverAUnionWhichSaysNothingMoreOfIt(t *testin "{$ref: '#/components/schemas/Zed'}", oneStringInt, "", "Zed: {type: string}") return schemas }) - requireErrorsAndWarnings(t, diags, nil) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, + pointer: "/components/schemas/RefAndUnion/allOf/1/oneOf", contains: []string{"oneOf/1: integer"}}}) use := requireScalarOver(t, doc, "RefAndUnion", componentID("Zed")) - assert.Empty(t, keptOn(use)) - assert.Zero(t, degradedInfosAt(diags, "RefAndUnion")) + assert.Equal(t, degradedKept("openapi:oneOf"), keptOn(use)) }) } } -// TestElection_TwoInlineEntriesTieOnTheOneWritingItems holds that of two array +// TestChoice_TwoInlineEntriesTieOnTheOneWritingItems holds that of two array // entries the one writing `items` is the principal whichever is written first, -// and that two writing the same items are one: the list stands at the position +// and that two writing the same items are one: the list sits at the position // and holds the string, nothing is kept or reported, and the two orders differ -// in no entry's index, the entry a child stands under being all a tie among -// alike entries may move. -func TestElection_TwoInlineEntriesTieOnTheOneWritingItems(t *testing.T) { +// in no entry's index, the entry a child sits under being all a tie among alike +// entries may move. +func TestChoice_TwoInlineEntriesTieOnTheOneWritingItems(t *testing.T) { t.Parallel() cases := []struct { name, a, b string @@ -110,7 +112,7 @@ func TestElection_TwoInlineEntriesTieOnTheOneWritingItems(t *testing.T) { {"OneWritesItems", "{type: array}", "{type: array, items: {type: string}}", compileInEveryOrder}, {"BothAgree", "{type: array, items: {type: string}}", "{type: array, items: {type: string}}", withoutEntryIndices}, } - for _, version := range electionVersions { + for _, version := range choiceVersions { for _, tc := range cases { t.Run(fmt.Sprintf("%s/%s", version, tc.name), func(t *testing.T) { t.Parallel() @@ -130,43 +132,48 @@ func TestElection_TwoInlineEntriesTieOnTheOneWritingItems(t *testing.T) { } } -// TestElection_BothKeywordsElectTheOneOfWhicheverIsWrittenFirst holds that an +// TestChoice_BothKeywordsChooseTheOneOfWhicheverIsWrittenFirst holds that an // allOf of a oneOf and an anyOf, each naming its kinds, lowers to the oneOf // whichever entry writes it, in both orders of the entries and of the -// components: the position is a use of the exclusive union, and the anyOf is -// kept under its own entry's index with one info there. -func TestElection_BothKeywordsElectTheOneOfWhicheverIsWrittenFirst(t *testing.T) { +// components: the position is a use of the exclusive union, its string branch +// dead against the anyOf and reported at the union, which is kept whole, and +// the anyOf is kept under its own entry's index with one info there (GitHub +// #2115). +func TestChoice_BothKeywordsChooseTheOneOfWhicheverIsWrittenFirst(t *testing.T) { t.Parallel() - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { schemas := pairSchemas(swapped, "OneAny", anyNumberBool, oneStringInt, "") return schemas }) - requireErrorsAndWarnings(t, diags, nil) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, + pointer: "/components/schemas/OneAny/allOf/1/oneOf", contains: []string{"oneOf/0: string"}}}) - union := electedUnion(doc, "OneAny") - require.NotNil(t, union, "the oneOf is elected, though the anyOf is written first") + union := chosenUnion(doc, "OneAny") + require.NotNil(t, union, "the oneOf is chosen, though the anyOf is written first") assert.True(t, union.Exclusive) - assert.Equal(t, []ir.TypeID{primitive(ir.PrimitiveString), primitive(ir.PrimitiveInteger)}, variantTargets(union)) - requireKeptKeys(t, kindNode(t, doc, componentID("OneAny")), "the anyOf, written first", "openapi:anyOf") + assert.Equal(t, []ir.TypeID{primitive(ir.PrimitiveInteger)}, variantTargets(union)) + requireKeptKeys(t, kindNode(t, doc, componentID("OneAny")), "the anyOf, written first, and the oneOf whole", + "openapi:anyOf", "openapi:oneOf") requireOneInfoAtEach(t, diags, "OneAny", "the anyOf is reported where it is written", 0) }) } } -// TestElection_TwoUnionsOfOneKeywordElectNeither holds that an allOf of two -// oneOf entries, or of two anyOf entries, none beside it, elects neither: no -// union stands for the position, both entries are kept whole under their own -// index and each is reported, and the two orders give one document. -func TestElection_TwoUnionsOfOneKeywordElectNeither(t *testing.T) { +// TestChoice_TwoUnionsOfOneKeywordChooseNeither holds that an allOf of two +// oneOf entries, or of two anyOf entries, none beside it, chooses neither: no +// union is the position's, both entries are kept whole under their own index +// and each is reported, each naming at its keyword the branch the other leaves +// dead, and the two orders give one document. +func TestChoice_TwoUnionsOfOneKeywordChooseNeither(t *testing.T) { t.Parallel() cases := []struct{ name, a, b string }{ {"OneOne", oneStringInt, oneIntBool}, {"AnyAny", anyNumberBool, anyStringInt}, } - for _, version := range electionVersions { + for _, version := range choiceVersions { for _, tc := range cases { t.Run(fmt.Sprintf("%s/%s", version, tc.name), func(t *testing.T) { t.Parallel() @@ -174,10 +181,14 @@ func TestElection_TwoUnionsOfOneKeywordElectNeither(t *testing.T) { schemas := pairSchemas(swapped, tc.name, tc.a, tc.b, "") return schemas }) - requireErrorsAndWarnings(t, diags, nil) + keyword := tc.a[1:strings.Index(tc.a, ":")] + requireErrorsAndWarnings(t, diags, []wantFinding{ + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/" + tc.name + "/allOf/0/" + keyword}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/" + tc.name + "/allOf/1/" + keyword}, + }) - assert.Empty(t, unionsUnder(doc, tc.name), "neither union stands for the position") - assert.Nil(t, electedUnion(doc, tc.name)) + assert.Empty(t, unionsUnder(doc, tc.name), "neither union is the position's") + assert.Nil(t, chosenUnion(doc, tc.name)) requireKeptEntries(t, kindNode(t, doc, componentID(tc.name)), "both entries", 0, 1) requireOneInfoAtEach(t, diags, tc.name, "both entries", 0, 1) }) @@ -185,13 +196,13 @@ func TestElection_TwoUnionsOfOneKeywordElectNeither(t *testing.T) { } } -// TestElection_TwoUnionsBesideABodyDistributeTheOneOf holds that a oneOf and an +// TestChoice_TwoUnionsBesideABodyDistributeTheOneOf holds that a oneOf and an // anyOf whose branches declare objects, each on an entry beside a body, lower -// to the union of the oneOf whichever is written first, each variant keeping -// the anyOf under its entry's index. -func TestElection_TwoUnionsBesideABodyDistributeTheOneOf(t *testing.T) { +// to the union of the oneOf whichever is written first, keeping the anyOf +// once, no variant keeping it. +func TestChoice_TwoUnionsBesideABodyDistributeTheOneOf(t *testing.T) { t.Parallel() - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -204,42 +215,43 @@ func TestElection_TwoUnionsBesideABodyDistributeTheOneOf(t *testing.T) { require.True(t, ok, "the oneOf distributes") assert.True(t, union.Exclusive) require.Len(t, union.Variants, 2) + assert.Equal(t, degradedKept("openapi:anyOf"), keptOn(union), "the anyOf, written first, once on the Union") for _, irVariant := range union.Variants { variant := kindNode(t, doc, irVariant.Type.Target) assert.Equal(t, ir.KindModel, variant.Kind()) - assert.Equal(t, degradedKept("openapi:anyOf"), keptOn(variant), "the anyOf, written first, on each variant") + assert.Empty(t, keptOn(variant), "no variant keeps it") } }) } } -// TestElection_ARefTieGoesByReferenceText holds that of two $refs neither of +// TestChoice_ARefTieGoesByReferenceText holds that of two $refs neither of // which lies within the other, or which are equal, the principal is the one // whose reference text is the least, whichever is written first: the // position is a use of it, and the other is kept under its entry's index with // one info. -func TestElection_ARefTieGoesByReferenceText(t *testing.T) { +func TestChoice_ARefTieGoesByReferenceText(t *testing.T) { t.Parallel() cases := []struct { - name, written, elected, kept string - schemas []string + name, written, chosen, kept string + schemas []string }{ {"EqualStrings", "Zed", "Amy", "Zed", []string{"Amy: {type: string}", "Zed: {type: string}"}}, {"Neither", "Lo", "Hi", "Lo", []string{"Lo: {type: string, minLength: 1}", "Hi: {type: string, maxLength: 9}"}}, } - for _, version := range electionVersions { + for _, version := range choiceVersions { for _, tc := range cases { t.Run(fmt.Sprintf("%s/%s", version, tc.name), func(t *testing.T) { t.Parallel() ref := func(n string) string { return "{$ref: '#/components/schemas/" + n + "'}" } doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { - schemas := pairSchemas(swapped, "Both", ref(tc.written), ref(tc.elected), "", tc.schemas...) + schemas := pairSchemas(swapped, "Both", ref(tc.written), ref(tc.chosen), "", tc.schemas...) return schemas }) requireErrorsAndWarnings(t, diags, nil) requireModelsNameModels(t, doc) - use := requireScalarOver(t, doc, "Both", componentID(tc.elected)) + use := requireScalarOver(t, doc, "Both", componentID(tc.chosen)) kept := keptOn(use) require.Len(t, kept, 1, "the other $ref is kept") for key, reason := range kept { @@ -252,12 +264,12 @@ func TestElection_ARefTieGoesByReferenceText(t *testing.T) { } } -// TestElection_TwoInlineEntriesThatDisagreeOnItemsElectNeither holds that two -// array entries writing different items elect neither, in both orders: both +// TestChoice_TwoInlineEntriesThatDisagreeOnItemsChooseNeither holds that two +// array entries writing different items choose neither, in both orders: both // are kept whole and reported, where the first written used to be the list. -func TestElection_TwoInlineEntriesThatDisagreeOnItemsElectNeither(t *testing.T) { +func TestChoice_TwoInlineEntriesThatDisagreeOnItemsChooseNeither(t *testing.T) { t.Parallel() - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -272,10 +284,10 @@ func TestElection_TwoInlineEntriesThatDisagreeOnItemsElectNeither(t *testing.T) } } -// electedUnion returns the union the component named is a use of, or is: the +// chosenUnion returns the union the component named is a use of, or is: the // node itself where it is a union, the node it names as its Base where it is a // scalar over one, and nil for anything else. -func electedUnion(doc *ir.Document, name string) *ir.Union { +func chosenUnion(doc *ir.Document, name string) *ir.Union { td := doc.Types[componentID(name)] if union, ok := td.(*ir.Union); ok { return union diff --git a/compilers/openapi/e2e/union_election_ties_test.go b/compilers/openapi/e2e/union_choice_ties_test.go similarity index 75% rename from compilers/openapi/e2e/union_election_ties_test.go rename to compilers/openapi/e2e/union_choice_ties_test.go index d8ff25d9a..c4c93e5a1 100644 --- a/compilers/openapi/e2e/union_election_ties_test.go +++ b/compilers/openapi/e2e/union_choice_ties_test.go @@ -13,16 +13,16 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestElection_AUnionTyingWithTheWordsIsThePrincipal holds that an allOf of a +// TestChoice_AUnionTyingWithTheWordsIsThePrincipal holds that an allOf of a // union and words admitting what it does is the union, whichever is written -// first: the bound the words write lands on the union, standing at the -// property, nothing is kept and nothing reported. Words beside the allOf tie -// the same way, and the union is the principal there too. -func TestElection_AUnionTyingWithTheWordsIsThePrincipal(t *testing.T) { +// first: the bound the words write lands on the union, at the property, nothing +// is kept and nothing reported. Words beside the allOf tie the same way, and +// the union is the principal there too. +func TestChoice_AUnionTyingWithTheWordsIsThePrincipal(t *testing.T) { t.Parallel() const simple = "SimpleString: {type: string}" const union = "{oneOf: [{$ref: '#/components/schemas/SimpleString'}]}" - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -34,7 +34,7 @@ func TestElection_AUnionTyingWithTheWordsIsThePrincipal(t *testing.T) { property := requireModelOf(t, doc, "N").Properties[0] irUnion, ok := kindNode(t, doc, property.Type.Target).(*ir.Union) require.True(t, ok, "the property names the union") - assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/N/properties/p"), property.Type.Target, "standing at the property") + assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/N/properties/p"), property.Type.Target, "at the property") require.NotNil(t, irUnion.Constraints) require.NotNil(t, irUnion.Constraints.MinLength) assert.EqualValues(t, 1, *irUnion.Constraints.MinLength) @@ -54,14 +54,14 @@ func TestElection_AUnionTyingWithTheWordsIsThePrincipal(t *testing.T) { } } -// TestElection_ASchemaWrittenTwiceIsOneConjunct holds that two entries written +// TestChoice_ASchemaWrittenTwiceIsOneConjunct holds that two entries written // alike, a $ref or a union, are one conjunct: the position is a use of it, // keeping nothing and reporting nothing, in both orders. Which copy's node a -// union stands at is all the two orders may differ in. -func TestElection_ASchemaWrittenTwiceIsOneConjunct(t *testing.T) { +// union sits at is all the two orders may differ in. +func TestChoice_ASchemaWrittenTwiceIsOneConjunct(t *testing.T) { t.Parallel() const amy = "{$ref: '#/components/schemas/Amy'}" - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -75,20 +75,20 @@ func TestElection_ASchemaWrittenTwiceIsOneConjunct(t *testing.T) { return pairSchemas(swapped, "Unions", oneStringInt, oneStringInt, "") }) requireErrorsAndWarnings(t, diags, nil) - union := electedUnion(doc, "Unions") - require.NotNil(t, union, "the union stands for the position") + union := chosenUnion(doc, "Unions") + require.NotNil(t, union, "the union is the position's") assert.Empty(t, keptOn(kindNode(t, doc, componentID("Unions")))) assert.Zero(t, degradedInfosAt(diags, "Unions")) }) } } -// TestElection_TwoRefsWrittenAlikeGoByTheirEntries holds that two $refs naming +// TestChoice_TwoRefsWrittenAlikeGoByTheirEntries holds that two $refs naming // one target, one entry writing more beside it, are one $ref written twice: // what the entry writes beside its $ref is a conjunct of its own, so the // position is the use of the target, the description its own, nothing kept, // whichever is written first. -func TestElection_TwoRefsWrittenAlikeGoByTheirEntries(t *testing.T) { +func TestChoice_TwoRefsWrittenAlikeGoByTheirEntries(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, "3.1.0", func(swapped bool) []string { return pairSchemas(swapped, "Refs", "{$ref: '#/components/schemas/Amy', description: d}", @@ -101,38 +101,36 @@ func TestElection_TwoRefsWrittenAlikeGoByTheirEntries(t *testing.T) { assert.Zero(t, degradedInfosAt(diags, "Refs")) } -// TestElection_WordsAdmittingAlikePartOnWhatTheirNodeReads holds that of two -// entries admitting alike, the pick turns on the keywords a node reads from -// its principal alone, whichever is written first: the one writing all the -// other does and more is the principal, standing at the position, keeping -// nothing of its own, and two -// writing them otherwise, or writing one keyword with values that differ, -// elect neither, the position the string both admit, or the top type where -// they admit an array, keeping what each writes under its own key, a type both -// write alike once, or both whole where they write one keyword apart. -func TestElection_WordsAdmittingAlikePartOnWhatTheirNodeReads(t *testing.T) { +// TestChoice_WordsAdmittingAlikePartOnWhatTheirNodeReads holds that of two +// entries admitting alike, the pick turns on the keywords a node reads from its +// principal alone, whichever is written first: one writing all the other does +// and more is the principal, keeping nothing, and two writing them otherwise, +// or one keyword with values that differ, choose neither, the position the +// string both admit, or the top type where they admit an array, keeping no type +// naming the string it is, or both whole where they write one keyword apart. +// The node reads the content either writes; a group written otherwise keeps one +// entry whole. +func TestChoice_WordsAdmittingAlikePartOnWhatTheirNodeReads(t *testing.T) { t.Parallel() cases := []struct { name, a, b string - elected ir.TypeKind + chosen ir.TypeKind kept map[string]ir.UnmodeledReason - // primitive is the primitive a position electing neither is, where - // elected is a primitive. + // primitive is the primitive a position choosing neither is, where + // chosen is a primitive. primitive ir.PrimitiveKind }{ {"Content", "{type: string}", "{type: string, contentEncoding: base64}", ir.KindScalar, nil, ""}, {"Tuple", "{type: array}", "{type: array, prefixItems: [{type: string}]}", ir.KindTuple, nil, ""}, {"MoreContent", "{type: string, contentMediaType: application/json}", "{type: string, contentMediaType: application/json, contentSchema: {type: object}}", ir.KindScalar, - map[string]ir.UnmodeledReason{"openapi:contentMediaType": ir.ReasonNoIRHome}, ""}, + map[string]ir.UnmodeledReason{entryKey(0): ir.ReasonNoIRHome}, ""}, {"OtherContent", "{type: string, contentEncoding: base64}", - "{type: string, contentMediaType: application/json}", ir.KindPrimitive, map[string]ir.UnmodeledReason{ - "openapi:contentEncoding": ir.ReasonNoIRHome, "openapi:contentMediaType": ir.ReasonNoIRHome, - "openapi:type": ir.ReasonDegradedLowering, - }, ir.PrimitiveString}, + "{type: string, contentMediaType: application/json}", ir.KindPrimitive, nil, ir.PrimitiveString}, {"DisagreeingContent", "{type: string, contentMediaType: application/json}", - "{type: string, contentMediaType: text/plain}", ir.KindPrimitive, degradedKept(entryKey(0), entryKey(1)), - ir.PrimitiveString}, + "{type: string, contentMediaType: text/plain}", ir.KindPrimitive, map[string]ir.UnmodeledReason{ + entryKey(0): ir.ReasonNoIRHome, entryKey(1): ir.ReasonNoIRHome, + }, ir.PrimitiveString}, {"DisagreeingTuple", "{type: array, prefixItems: [{type: string}]}", "{type: array, prefixItems: [{type: integer}]}", ir.KindPrimitive, degradedKept(entryKey(0), entryKey(1)), ir.PrimitiveAny}, @@ -145,13 +143,13 @@ func TestElection_WordsAdmittingAlikePartOnWhatTheirNodeReads(t *testing.T) { }) requireErrorsAndWarnings(t, diags, nil) use := kindNode(t, doc, componentID(tc.name)) - if tc.elected == ir.KindPrimitive { + if tc.chosen == ir.KindPrimitive { alias, ok := use.(*ir.Scalar) require.True(t, ok) require.NotNil(t, alias.Base) - assert.Equal(t, primitive(tc.primitive), alias.Base.Target, "neither is elected") + assert.Equal(t, primitive(tc.primitive), alias.Base.Target, "neither is chosen") } else { - assert.Equal(t, tc.elected, use.Kind(), "the principal's node is the position's") + assert.Equal(t, tc.chosen, use.Kind(), "the principal's node is the position's") } kept := tc.kept if kept == nil { @@ -162,12 +160,12 @@ func TestElection_WordsAdmittingAlikePartOnWhatTheirNodeReads(t *testing.T) { } } -// TestElection_ValueSetsAlikeGoByTheirText holds that two equal value sets, -// written differently, elect the one whose text is the least, whichever is +// TestChoice_ValueSetsAlikeGoByTheirText holds that two equal value sets, +// written differently, choose the one whose text is the least, whichever is // written first: the enum keeps that entry's order of members. -func TestElection_ValueSetsAlikeGoByTheirText(t *testing.T) { +func TestChoice_ValueSetsAlikeGoByTheirText(t *testing.T) { t.Parallel() - for _, version := range electionVersions { + for _, version := range choiceVersions { t.Run(version, func(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, version, func(swapped bool) []string { @@ -175,7 +173,7 @@ func TestElection_ValueSetsAlikeGoByTheirText(t *testing.T) { }) requireErrorsAndWarnings(t, diags, nil) enum, ok := kindNode(t, doc, componentID("Sets")).(*ir.Enum) - require.True(t, ok, "the value set stands at the position") + require.True(t, ok, "the value set sits at the position") require.Len(t, enum.Members, 2) assert.Equal(t, "b", enum.Members[0].Value.String, "the entry writing the description is the least text") assert.Zero(t, degradedInfosAt(diags, "Sets")) @@ -183,10 +181,10 @@ func TestElection_ValueSetsAlikeGoByTheirText(t *testing.T) { } } -// TestElection_TwoOneOfUnionsBesideABodyDistributeNeither holds that two oneOf +// TestChoice_TwoOneOfUnionsBesideABodyDistributeNeither holds that two oneOf // unions whose branches declare objects, beside a body, distribute neither: // the position is the model of the body keeping both entries, in both orders. -func TestElection_TwoOneOfUnionsBesideABodyDistributeNeither(t *testing.T) { +func TestChoice_TwoOneOfUnionsBesideABodyDistributeNeither(t *testing.T) { t.Parallel() doc, diags := compileInEveryOrder(t, "3.1.0", func(swapped bool) []string { return pairSchemas(swapped, "OneOneObj", "{"+oneObjBranches+"}", @@ -198,10 +196,10 @@ func TestElection_TwoOneOfUnionsBesideABodyDistributeNeither(t *testing.T) { assert.Empty(t, unionsUnder(doc, "OneOneObj"), "neither union distributes") } -// TestElection_APositionUsedTwiceElectsAsOnce holds that each tie the election +// TestChoice_APositionUsedTwiceChoosesAsOnce holds that each tie the choice // breaks gives the nodes and findings of a position used once when a response, // a parameter and two properties use it. -func TestElection_APositionUsedTwiceElectsAsOnce(t *testing.T) { +func TestChoice_APositionUsedTwiceChoosesAsOnce(t *testing.T) { t.Parallel() const stringReference = "{$ref: '#/components/schemas/Str'}" rows := []string{ @@ -228,7 +226,7 @@ func TestElection_APositionUsedTwiceElectsAsOnce(t *testing.T) { return admissionSpec(version, paths, "Str: {type: string}", "X: "+row, holder) + " responses:\n R:\n description: d\n content: {application/json: {schema: " + row + "}}\n" } - for _, version := range electionVersions { + for _, version := range choiceVersions { for _, row := range rows { t.Run(version+"/"+row, func(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/e2e/union_conjunction_twins_test.go b/compilers/openapi/e2e/union_conjunction_twins_test.go new file mode 100644 index 000000000..d3a595a68 --- /dev/null +++ b/compilers/openapi/e2e/union_conjunction_twins_test.go @@ -0,0 +1,320 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "maps" + "slices" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers" + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// policies are the nullable-inference policy on and off, by name. +var policies = map[string]openapi.Options{ + "on": {}, + "off": {NullableInference: openapi.NullableInference{Disabled: true}}, +} + +// stringOrNull is a string admitting null as version spells it. +func stringOrNull(version string) string { + if version == "3.0.3" { + return "type: string, nullable: true" + } + return "type: [string, 'null']" +} + +// nullBranch is a branch admitting null alone as version spells it. +func nullBranch(version string) string { + if version == "3.0.3" { + return "type: object, enum: [null], nullable: true" + } + return "type: 'null'" +} + +// TestUnionBesideBody_ALoneNullBranchLiftsOntoTheObject holds that a union of +// null branches alone beside an object keeping null out lowers, in every +// spelling and at 3.0 and 3.1, with the nullable-inference policy on, to the +// object's Model behind a reference admitting null that the policy marks, its +// members staying members, the union said and the branch's info at it, with no +// warning; what a branch writes beside its null, and a union passed over, are +// kept on the Model. With the policy off the null branch is dead: the Model +// keeps the union, and the schema draws the warning that no instance +// satisfies it. +func TestUnionBesideBody_ALoneNullBranchLiftsOntoTheObject(t *testing.T) { + t.Parallel() + const object = "type: object, properties: {a: {type: string}}" + for _, version := range []string{"3.0.3", "3.1.0"} { + null := nullBranch(version) + rows := openapitest.Rows(map[string][2]string{ + "Lone": {object, "oneOf: [{" + null + "}]"}, + "Described": {object, "oneOf: [{" + null + ", description: none}]"}, + "PassedOver": {object, "oneOf: [{" + null + "}], anyOf: [{" + null + "}, {type: object, required: [a]}]"}, + }) + for policy, options := range policies { + t.Run(version+"/"+policy, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, options, version, nil, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range []string{"Lone", "Described", "PassedOver"} { + flat := readings[false][row]["Flat"]["component"] + require.Equal(t, ir.KindModel, flat.View.Kind, "%s is its object", row) + assert.Equal(t, []string{"a"}, flat.View.Properties, "%s: its members stay members", row) + if policy == "off" { + assert.False(t, flat.View.Nullable, row) + assert.Equal(t, ir.ReasonDegradedLowering, flat.View.Kept["openapi:oneOf"], "%s keeps its union", row) + assert.Contains(t, flat.Findings, "warning "+diag.UnsatisfiableSchema, row) + continue + } + assert.True(t, flat.View.Nullable, "%s admits the lifted null", row) + assert.NotContains(t, flat.View.Kept, "openapi:oneOf", "%s: the lifted union is said", row) + assert.Contains(t, flat.Findings, "info "+diag.InferredNullable, row) + assert.NotContains(t, flat.Findings, "warning "+diag.UnsatisfiableSchema, row) + } + if policy == "on" { + described := readings[false]["Described"]["Flat"]["component"].View + assert.Equal(t, ir.ReasonNoIRHome, described.Kept["openapi:oneOf/0"], "the branch's description is kept") + passed := readings[false]["PassedOver"]["Flat"]["component"].View + assert.Contains(t, passed.Kept, "openapi:anyOf", "the union passed over is kept") + } + }) + } + } +} + +// TestUnionBesideBody_ATypeListBranchIsSplitByKind holds that a branch listing +// several types beside a body split by kind is distributed over its kinds in +// every spelling, at 3.1 and 3.2, where a type list is written, and under +// either policy: its variant is a Union of one node per type, the object's a +// model composing the body's object keywords, a string's holding the body's +// string bounds over the branch's own string node, which keeps what the +// branch writes of strings, and a null listed is the variant's. No string the +// source admits is left without a variant admitting it. +func TestUnionBesideBody_ATypeListBranchIsSplitByKind(t *testing.T) { + t.Parallel() + const body = "properties: {a: {type: string}}, minLength: 3" + rows := openapitest.Rows(map[string][2]string{ + "ObjectString": {body, "oneOf: [{type: [object, string]}, {type: integer}]"}, + "OwnBound": {body, "oneOf: [{type: [string, integer], maxLength: 5, description: d}, {type: object}]"}, + "Null": {body, "oneOf: [{type: [object, string, 'null']}, {type: integer}]"}, + }) + for _, version := range []string{"3.1.0", "3.2.0"} { + for policy, options := range policies { + t.Run(version+"/"+policy, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, options, version, nil, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range []string{"ObjectString", "Null"} { + union := readings[false][row]["Flat"]["component"].View + require.Equal(t, ir.KindUnion, union.Kind, row) + require.Len(t, union.Variants, 2, row) + assert.Equal(t, "integer", union.Variants[1].Ref, row) + listed := union.Variants[0] + assert.Equal(t, row == "Null", listed.Nullable, "%s: the listed null is the variant's", row) + require.Equal(t, ir.KindUnion, listed.Kind, "%s: the list is split by its kinds", row) + require.Len(t, listed.Variants, 2, row) + assert.Equal(t, ir.KindModel, listed.Variants[0].Kind, row) + assert.Equal(t, []string{"a"}, listed.Variants[0].Properties, "%s: the object composes the body's members", row) + assert.Equal(t, ir.KindScalar, listed.Variants[1].Kind, row) + assert.JSONEq(t, `{"minLength":3,"uniqueItems":false}`, listed.Variants[1].Constraints, "%s: the string holds the body's bound", row) + assert.Empty(t, union.Kept, "%s keeps nothing: every keyword has its kind", row) + } + own := readings[false]["OwnBound"]["Flat"]["component"].View.Variants[0] + require.Equal(t, ir.KindUnion, own.Kind) + require.Len(t, own.Variants, 2) + assert.Equal(t, "integer", own.Variants[1].Ref) + require.NotNil(t, own.Variants[0].Base, "the string variant is over the branch's own string") + assert.JSONEq(t, `{"maxLength":5,"uniqueItems":false}`, own.Variants[0].Base.Constraints, "the branch's own bound is kept") + }) + } + } +} + +// refBodyShared are the components the $ref-body rows name: the body's +// scalar, a uuid and a patterned string a branch names, and the allOf of the +// body and each branch, whose lowering each variant is. +var refBodyShared = []string{ + "B: {type: string, maxLength: 40}", + "U: {type: string, format: uuid}", + "C: {type: string, pattern: '^c'}", + "TwinUuid: {allOf: [{$ref: '#/components/schemas/B'}, {format: uuid}]}", + "TwinFoo: {allOf: [{$ref: '#/components/schemas/B'}, {format: foo}]}", + "TwinU: {allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/U'}]}", + "TwinC: {allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/C'}]}", + "TwinDate: {allOf: [{$ref: '#/components/schemas/B'}, {format: date}]}", + "TwinTypedUuid: {allOf: [{$ref: '#/components/schemas/B'}, {type: string}, {format: uuid}]}", + "TwinTypedShort: {allOf: [{$ref: '#/components/schemas/B'}, {type: string}, {minLength: 2}]}", + "TwinDescribedC: {allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/C', description: c}]}", + "TwinBoundedU: {allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/U', maxLength: 3}]}", +} + +// refBodyTwins names, for each $ref-body row, the twin of each of its +// branches: the allOf of the body and that branch, written as a component. +var refBodyTwins = map[string][]string{ + "Formats": {"TwinUuid", "TwinFoo"}, "Refs": {"TwinU", "TwinC"}, "Bounded": {"TwinUuid", "TwinDate"}, + "Typed": {"TwinTypedUuid", "TwinTypedShort"}, "RefSiblings": {"TwinDescribedC", "TwinBoundedU"}, +} + +// sameNode holds got, a variant's view, to want, the view of the node its allOf +// twin lowers to, in all but where each sits. +func sameNode(t *testing.T, want, got bodyView, label string) { + t.Helper() + want.Space, got.Space, want.Nullable, got.Nullable = "", "", false, false + assert.Equal(t, want, got, "%s lowers as its allOf twin", label) +} + +// TestUnionBesideBody_ARefBodyConjoinsEachBranchAsItsAllOf holds that a union +// beside a body holding one $ref to a scalar is a Union of the branches, each +// lowered as the allOf of the body and the branch lowers, in every spelling, at +// 3.0 and 3.1: a recognized format the primitive it chooses with the $ref kept, +// an unrecognized one restricting the target, a $ref branch, one writing beside +// its $ref too, the one of the two $refs the choice keeps, and a type beside +// the body's $ref in each variant. The target's bounds stay its own; the Union +// keeps the body's length, which binds no uuid's text. +func TestUnionBesideBody_ARefBodyConjoinsEachBranchAsItsAllOf(t *testing.T) { + t.Parallel() + const body = "$ref: '#/components/schemas/B'" + rows := openapitest.Rows(map[string][2]string{ + "Formats": {body, "oneOf: [{format: uuid}, {format: foo}]"}, + "Refs": {body, "anyOf: [{$ref: '#/components/schemas/U'}, {$ref: '#/components/schemas/C'}]"}, + "Bounded": {body + ", maxLength: 5", "oneOf: [{format: uuid}, {format: date}]"}, + "Typed": {body + ", type: string", "anyOf: [{format: uuid}, {minLength: 2}]"}, + "RefSiblings": {body, "oneOf: [{$ref: '#/components/schemas/C', description: c}, {$ref: '#/components/schemas/U', maxLength: 3}]"}, + }) + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, openapi.Options{}, version, refBodyShared, rows) + forgiveLaterVersion(t, version, readings, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + doc := compileRefTwins(t, version) + for row, names := range refBodyTwins { + union := readings[false][row]["Flat"]["component"].View + require.Equal(t, ir.KindUnion, union.Kind, row) + require.Len(t, union.Variants, len(names), row) + assert.Empty(t, union.Constraints, "%s: the target's bounds stay its own, the body's bind no variant's value", row) + if row == "Bounded" { + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:maxLength": ir.ReasonNoIRHome}, union.Kept, "%s: the Union keeps the body's length", row) + } else { + assert.Empty(t, union.Kept, "%s: each variant conjoins the body", row) + } + for i, name := range names { + sameNode(t, viewOfComponent(doc, name, ""), union.Variants[i], row+" "+name) + } + } + }) + } +} + +// TestUnionBesideBody_ARefBodyConjoinsWhereverItsConjunctsNest holds that a +// union beside a body holding one $ref to a scalar lowers as written flat +// wherever the body's conjuncts stay, at 3.0 and 3.1: on the one entry writing +// the $ref, a type, a note and a bound beside the union, with the bound in an +// allOf of the union's own entry, and with the $ref there. +func TestUnionBesideBody_ARefBodyConjoinsWhereverItsConjunctsNest(t *testing.T) { + t.Parallel() + const ref, union = "$ref: '#/components/schemas/B'", "oneOf: [{format: uuid}, {format: date}]" + rows := []openapitest.Row{{Name: "Nested", Spellings: map[string]string{ + "Flat": "{" + ref + ", type: string, description: d, " + union + ", maxLength: 5}", + "OneEntry": "{allOf: [{" + ref + ", type: string, description: d, " + union + ", maxLength: 5}]}", + "BoundInEntry": "{allOf: [{" + ref + "}, {type: string, description: d, " + union + ", allOf: [{maxLength: 5}]}]}", + "RefInEntry": "{allOf: [{type: string, description: d, " + union + ", allOf: [{" + ref + "}]}], maxLength: 5}", + }}} + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, openapi.Options{}, version, refBodyShared, rows) + forgiveLaterVersion(t, version, readings, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + union := readings[false]["Nested"]["Flat"]["component"].View + require.Equal(t, ir.KindUnion, union.Kind) + assert.Len(t, union.Variants, 2) + }) + } +} + +// compileRefTwins compiles refBodyShared at version. +func compileRefTwins(t *testing.T, version string) *ir.Document { + t.Helper() + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{ + {Path: "twins.yaml", Data: []byte(admissionSpec(version, "", refBodyShared...))}, + }, compilers.Options{}) + require.NoError(t, err) + requireVerifies(t, doc, diags) + return doc +} + +// flatEnumRows are the unions of value sets beside a body whose members span +// two kinds or hold null, under a oneOf and an anyOf, each a body, a union and +// the members a flat enum beside that body lists for them, in every spelling +// (conjunctionSpellings), and each one's flat twin, a row of its own. +func flatEnumRows(version string) (rows, twins []openapitest.Row) { + null := stringOrNull(version) + cases := map[string][3]string{ + "MixedOneOf": {"maxLength: 3", "oneOf: [{enum: [a]}, {enum: [1]}]", "[a, 1]"}, + "MixedAnyOf": {"maxLength: 3", "anyOf: [{enum: [a, 1]}, {enum: [b, 1]}]", "[a, 1, b]"}, + "NullOneOf": {null, "oneOf: [{enum: [a]}, {enum: [null]}]", "[a, null]"}, + "NullAnyOf": {null, "anyOf: [{enum: [a, null]}, {enum: [b]}]", "[a, null, b]"}, + "BothOneOf": {"maxLength: 3", "oneOf: [{enum: [a, null]}, {enum: [1]}]", "[a, null, 1]"}, + "BothAnyOf": {"maxLength: 3", "anyOf: [{enum: [a]}, {enum: [1, null]}]", "[a, 1, null]"}, + } + for _, name := range slices.Sorted(maps.Keys(cases)) { + written := cases[name] + rows = append(rows, openapitest.Row{Name: name, Spellings: openapitest.Spellings(written[0], openapitest.SplitKeywords(written[1])...)}) + twins = append(twins, openapitest.Row{Name: "Twin" + name, Spellings: map[string]string{"Flat": "{" + written[0] + ", enum: " + written[2] + "}"}}) + } + return rows, twins +} + +// asFlatTwin is view as its flat twin's is compared: the union it keeps aside, +// and each variant's namespace, a Literal minted for a union's member where an +// enum's own is hoisted. +func asFlatTwin(view bodyView) bodyView { + view.Kept = nil + view.Variants = slices.Clone(view.Variants) + for i := range view.Variants { + view.Variants[i].Space = "" + } + return view +} + +// TestUnionBesideBody_AUnionOfValueSetsLowersAsItsFlatEnum holds that a union +// whose branches are all value sets, beside a body, lowers as the flat enum of +// the members the body admits lowers, in every spelling, at 3.0 and 3.1 under +// either policy, members spanning a string and a number or holding null: +// two kinds make the Union of literals a mixed enum does, and a null is the +// reference's as beside an enum listing it. The node holds the union whole, +// which is kept nowhere, the findings alike. +func TestUnionBesideBody_AUnionOfValueSetsLowersAsItsFlatEnum(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.0.3", "3.1.0"} { + rows, twins := flatEnumRows(version) + for policy, options := range policies { + t.Run(version+"/"+policy, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, options, version, nil, slices.Concat(rows, twins)) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for _, row := range rows { + for _, position := range []string{"component", "property"} { + got := readings[false][row.Name]["Flat"][position] + want := readings[false]["Twin"+row.Name]["Flat"][position] + if diff := cmp.Diff(asFlatTwin(want.View), asFlatTwin(got.View)); diff != "" { + t.Errorf("%s at the %s lowers as its flat enum (-twin +union):\n%s", row.Name, position, diff) + } + assert.Equal(t, want.Findings, got.Findings, "%s at the %s draws its flat enum's findings", row.Name, position) + assert.Empty(t, got.View.Kept, "%s keeps no union the node holds whole", row.Name) + } + } + }) + } + } +} diff --git a/compilers/openapi/e2e/union_dead_null_branch_test.go b/compilers/openapi/e2e/union_dead_null_branch_test.go index e5d9f6961..c7e85ab81 100644 --- a/compilers/openapi/e2e/union_dead_null_branch_test.go +++ b/compilers/openapi/e2e/union_dead_null_branch_test.go @@ -28,14 +28,14 @@ var nullListSites = []bothKeywordsSite{ }}, } -// TestElection_ANullBranchIsReadAgainstTheUnionPassedOver holds that a branch -// of null alone of the union a position elects is read against the union it +// TestChoice_ANullBranchIsReadAgainstTheUnionPassedOver holds that a branch of +// null alone of the union a position chooses is read against the union it // passes over too, wherever the two are written: beside a body admitting an -// object or null, a oneOf admitting objects alone leaves the elected anyOf's -// branch naming null no value, so every spelling, the reference's own -// keywords beside the two included, is a Union of the anyOf's object branch -// keeping the null one, with one warning naming it (GitHub #2011). -func TestElection_ANullBranchIsReadAgainstTheUnionPassedOver(t *testing.T) { +// object or null, a oneOf admitting objects alone leaves the chosen anyOf's +// branch naming null no value, so every spelling, the reference's own keywords +// beside the two included, is a Union of the anyOf's object branch keeping the +// null one, with one warning naming it (GitHub #2011). +func TestChoice_ANullBranchIsReadAgainstTheUnionPassedOver(t *testing.T) { t.Parallel() const inline = "{type: [object, 'null'], properties: {a: {type: string}}}" for _, version := range []string{"3.1.0", "3.2.0"} { @@ -56,7 +56,7 @@ func TestElection_ANullBranchIsReadAgainstTheUnionPassedOver(t *testing.T) { spellings["beside the body"] = strings.TrimSuffix(body, "}") + ", oneOf: " + one + ", anyOf: " + anyOf + "}" } doc, diags := compileSpellingsAlike(t, site, version, spellings) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: string(site.at), + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: string(site.at), contains: []string{"so no instance satisfies it"}}}) union, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Union) require.True(t, ok, "the anyOf distributes") diff --git a/compilers/openapi/e2e/union_null_alone_beside_test.go b/compilers/openapi/e2e/union_null_alone_beside_test.go index 76737c770..c5102a6d6 100644 --- a/compilers/openapi/e2e/union_null_alone_beside_test.go +++ b/compilers/openapi/e2e/union_null_alone_beside_test.go @@ -4,6 +4,7 @@ package e2e_test import ( + "encoding/json/jsontext" "fmt" "strings" "testing" @@ -31,25 +32,29 @@ var nullAloneSites = []bothKeywordsSite{ // nullAlonePairs are a oneOf and an anyOf over an object body that share // no value, the null of one or of both being all they admit beside what the -// body does not. -var nullAlonePairs = []struct{ name, oneOf, anyOf string }{ - {"an object or null beside a string or null", "[{type: object}, {type: 'null'}]", "[{type: string}, {type: 'null'}]"}, +// body does not, and whether the anyOf writes a branch keeping null out. +var nullAlonePairs = []struct { + name, oneOf, anyOf string + anyOfKeepsNullOut bool +}{ + {"an object or null beside a string or null", "[{type: object}, {type: 'null'}]", "[{type: string}, {type: 'null'}]", true}, {"a string or null beside objects or null", "[{type: string}, {type: 'null'}]", - "[{type: object, properties: {x: {type: string}}}, " + nullRef + "]"}, - {"an array or a named null beside an object or null", "[{type: array}, " + nullRef + "]", "[{type: object}, {type: 'null'}]"}, - {"a named null beside a union declaring no shape", "[" + nullRef + "]", "[{required: [a]}]"}, - {"null and a named null beside a union admitting all", "[{type: 'null'}, " + nullRef + "]", "[{}]"}, - {"a union declaring no shape beside a named null", "[{required: [a]}]", "[" + nullRef + "]"}, + "[{type: object, properties: {x: {type: string}}}, " + nullRef + "]", true}, + {"an array or a named null beside an object or null", "[{type: array}, " + nullRef + "]", "[{type: object}, {type: 'null'}]", true}, + {"a named null beside a union declaring no shape", "[" + nullRef + "]", "[{required: [a]}]", false}, + {"null and a named null beside a union admitting all", "[{type: 'null'}, " + nullRef + "]", "[{}]", false}, + {"a union declaring no shape beside a named null", "[{required: [a]}]", "[" + nullRef + "]", false}, } -// TestElection_UnionsSharingNullAloneWithEachOtherDrawOneWarning holds that a -// oneOf and an anyOf over an object body sharing no value with it, null -// being all either admits beside the kinds the other or the body lacks, lower -// alike beside the body, beside its allOf, on one entry and two, in either -// order of the entries, the branches and the components: the Model the body -// gives keeping both unions, with one warning that no instance satisfies it, -// as a schema draws one of the two at most (GitHub #2011). -func TestElection_UnionsSharingNullAloneWithEachOtherDrawOneWarning(t *testing.T) { +// TestChoice_UnionsSharingNullAloneWithEachOtherDrawOneWarning holds that a +// oneOf and an anyOf over an object body sharing no value with it, null being +// all either admits beside what the other or the body lacks, lower alike in +// every spelling and order: the Model the body gives keeping both unions, with +// one warning that no instance satisfies it (GitHub #2011). Where the chosen +// union writes an inline null branch, the nullable-inference policy lifts its +// null, so the position is null alone, warned of at that union and at the one +// passed over keeping null out. +func TestChoice_UnionsSharingNullAloneWithEachOtherDrawOneWarning(t *testing.T) { t.Parallel() for _, version := range []string{"3.1.0", "3.2.0"} { for _, site := range nullAloneSites { @@ -62,6 +67,10 @@ func TestElection_UnionsSharingNullAloneWithEachOtherDrawOneWarning(t *testing.T if reversed { one, anyOf = reversedBranches(t, one), reversedBranches(t, anyOf) } + if strings.Contains(one, "{type: 'null'}") { + checkLiftedPair(t, site, version, unionPairSpellings(body, one, anyOf), pair.anyOfKeepsNullOut) + return + } checkUnsatisfiedPair(t, site, version, unionPairSpellings(body, one, anyOf)) }) } @@ -71,13 +80,41 @@ func TestElection_UnionsSharingNullAloneWithEachOtherDrawOneWarning(t *testing.T } } -// TestElection_AUnionOfNullAloneBesideAnAllOfDrawsOneWarning holds that a +// checkLiftedPair compiles each spelling at site as checkUnsatisfiedPair does +// and holds the one it compares to to null alone, the closed empty Enum keeping +// both unions, with one warning at the oneOf it chooses naming its dead +// branches, and, where passedDead says the anyOf it passes over keeps null out +// in a branch, one there naming that branch. +func checkLiftedPair(t *testing.T, site bothKeywordsSite, version string, spellings map[string]string, passedDead bool) { + t.Helper() + doc, diags := compileSpellingsAlike(t, site, version, spellings) + var warned []jsontext.Pointer + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityWarning || diagnostic.Severity == ir.SeverityError { + warned = append(warned, diagnostic.Provenance.Pointer) + } + } + want := []jsontext.Pointer{site.at + "/allOf/1/oneOf"} + if passedDead { + want = append(want, site.at+"/allOf/1/anyOf") + } + assert.ElementsMatch(t, want, warned) + enum, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Enum) + require.True(t, ok, "the position is null alone") + assert.Empty(t, enum.Members) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(enum)["openapi:oneOf"]) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(enum)["openapi:anyOf"]) +} + +// TestChoice_AUnionOfNullAloneBesideAnAllOfDrawsOneWarning holds that a // union whose every branch admits null alone, one of them naming a schema of // null, lowers alike beside an allOf of an object body, on an entry of it, // before the body or after it, one allOf deeper and beside the body's own // keywords: the Model the body gives keeping the union as degraded_lowering, -// with one warning naming it. -func TestElection_AUnionOfNullAloneBesideAnAllOfDrawsOneWarning(t *testing.T) { +// with one warning naming it. Where an inline branch is null, the +// nullable-inference policy lifts its null, so the position is null alone, the +// branch naming the schema of null warned of at the union. +func TestChoice_AUnionOfNullAloneBesideAnAllOfDrawsOneWarning(t *testing.T) { t.Parallel() for _, version := range []string{"3.1.0", "3.2.0"} { for _, site := range nullAloneSites { @@ -101,7 +138,7 @@ func TestElection_AUnionOfNullAloneBesideAnAllOfDrawsOneWarning(t *testing.T) { func requireNullAloneUnion(t *testing.T, site bothKeywordsSite, version, keyword, u, body string) { t.Helper() spellings := map[string]string{ - "one entry": "{allOf: [" + body + ", {" + u + "}]}", + "Entry": "{allOf: [" + body + ", {" + u + "}]}", "before the body": "{allOf: [{" + u + "}, " + body + "]}", "beside the allOf": "{allOf: [" + body + "], " + u + "}", "one allOf deeper": "{allOf: [" + body + ", {allOf: [{" + u + "}]}]}", @@ -110,21 +147,30 @@ func requireNullAloneUnion(t *testing.T, site bothKeywordsSite, version, keyword spellings["beside the keywords"] = "{type: object, " + u + ", " + inline } doc, diags := compileSpellingsAlike(t, site, version, spellings) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: string(site.at), - contains: []string{"share no value", "so no instance satisfies this schema"}}}) + if strings.Contains(u, "{type: 'null'}") { + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: string(site.at) + "/allOf/1/" + keyword, + contains: []string{"1 of the 2 branches of this " + keyword}}}) + enum, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Enum) + require.True(t, ok, "the position is null alone") + assert.Empty(t, enum.Members) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(enum)["openapi:"+keyword]) + return + } + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: string(site.at), + contains: []string{"no value satisfies", "; lowered as "}}}) model, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Model) require.True(t, ok, "the position is the Model its body gives") assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:" + keyword: ir.ReasonDegradedLowering}, keptOn(model)) } -// TestElection_TwoUnionsKeptBesideABodyAdmittingNullKeepTheirReasonEverywhere +// TestChoice_TwoUnionsKeptBesideABodyAdmittingNullKeepTheirReasonEverywhere // holds that a oneOf of an object and null and an anyOf of null alone over a // $ref to an object or null, which admit null alone together, lower alike // beside the allOf, on one entry, on two in either order and one allOf deeper, -// in either order of the branches and the components: a use of the body -// keeping both unions as degraded_lowering, as beside the allOf, the oneOf -// declaring shape for the two. -func TestElection_TwoUnionsKeptBesideABodyAdmittingNullKeepTheirReasonEverywhere(t *testing.T) { +// in either order of the branches and the components: the position admits +// null alone, the closed empty Enum behind a nullable reference keeping both +// unions as degraded_lowering, as beside the allOf (GitHub #2111, #2115). +func TestChoice_TwoUnionsKeptBesideABodyAdmittingNullKeepTheirReasonEverywhere(t *testing.T) { t.Parallel() const body = "{$ref: '#/components/schemas/TN'}" sites := []bothKeywordsSite{ @@ -146,17 +192,36 @@ func TestElection_TwoUnionsKeptBesideABodyAdmittingNullKeepTheirReasonEverywhere one = reversedBranches(t, one) } doc, _ := compileSpellingsAlike(t, site, version, unionPairSpellings(body, one, anyOf)) - assert.Equal(t, map[string]ir.UnmodeledReason{ - "openapi:oneOf": ir.ReasonDegradedLowering, "openapi:anyOf": ir.ReasonDegradedLowering, - }, keptAtUse(t, doc, site), "the position keeps both unions") + requireNullAloneKeepingBoth(t, doc, site) }) } } } } +// requireNullAloneKeepingBoth holds the position at site to the closed empty +// Enum of null alone behind a nullable reference, keeping a oneOf and an anyOf +// as degraded_lowering. +func requireNullAloneKeepingBoth(t *testing.T, doc *ir.Document, site bothKeywordsSite) { + t.Helper() + ref := ir.TypeRef{Target: entryPositionID(site.at)} + if site.name == "property" { + model, ok := kindNode(t, doc, componentID("C")).(*ir.Model) + require.True(t, ok) + require.Len(t, model.Properties, 1) + ref = model.Properties[0].Type + } + enum, ok := kindNode(t, doc, ref.Target).(*ir.Enum) + require.True(t, ok, "the position admits null alone") + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + kept := keptOn(enum) + assert.Equal(t, ir.ReasonDegradedLowering, kept["openapi:oneOf"], "the Enum keeps the oneOf") + assert.Equal(t, ir.ReasonDegradedLowering, kept["openapi:anyOf"], "the Enum keeps the anyOf") +} + // keptAtUse is what the use of the body at site keeps by reason: the node a -// component stands at, or the property a model's carrier holds, a use of a +// component sits at, or the property a model's carrier holds, a use of a // component keeping on its carrier what no node of its own holds. func keptAtUse(t *testing.T, doc *ir.Document, site bothKeywordsSite) map[string]ir.UnmodeledReason { t.Helper() diff --git a/compilers/openapi/e2e/union_null_distribution_test.go b/compilers/openapi/e2e/union_null_distribution_test.go index 485f328af..1c9626c31 100644 --- a/compilers/openapi/e2e/union_null_distribution_test.go +++ b/compilers/openapi/e2e/union_null_distribution_test.go @@ -22,14 +22,16 @@ var nullSpellings = []string{"{type: 'null'}", "{enum: [null]}", "{const: null}" // distributedBodies are bodies beside a union of two objects and a null // branch, each with whether the reference to the position admits null: a body // writing `type: object` forbids it, one listing null in its type admits it, -// and one writing no type says nothing of it, so the null branch decides. +// and one writing no type says nothing of it, so the null branch decides. A +// closure would refuse the members the branches require, leaving no object +// branch (TestKindInference_AClosureRefusingWhatEveryBranchRequiresAdmitsNothing). var distributedBodies = []struct { name, body string nullable bool }{ {"Typed", "type: object, properties: {p: {type: string}}", false}, {"TypedNull", "type: [object, 'null'], properties: {p: {type: string}}", true}, - {"Closed", "additionalProperties: false", true}, + {"Untyped", "properties: {p: {type: string}}", true}, } // TestUnionNullVariant_ADistributedUnionLiftsItsNullBranch holds a union with a @@ -111,7 +113,7 @@ func TestUnionNullVariant_AUnionAloneOnAnEntryIsTheReferenceItsBareSpellingIs(t assert.Equal(t, ir.TypeRef{Target: componentID("X"), Nullable: true}, irProperty.Type, "the bare union is X, nullable") assert.Equal(t, irProperty.Type, property.Type, "the union on an entry is what the bare union is") for id := range doc.Types { - assert.NotContains(t, string(id), "/properties/p", "no node stands for p or beneath it") + assert.NotContains(t, string(id), "/properties/p", "no node exists for p or beneath it") } assert.Empty(t, keptUnder(doc, "/components/schemas/H/properties/p"), "nothing is kept") assert.Empty(t, property.Unmodeled, "the property keeps nothing") diff --git a/compilers/openapi/e2e/union_null_shared_test.go b/compilers/openapi/e2e/union_null_shared_test.go index 5ddd6df96..4e9a3f7ce 100644 --- a/compilers/openapi/e2e/union_null_shared_test.go +++ b/compilers/openapi/e2e/union_null_shared_test.go @@ -51,12 +51,12 @@ var nullSharedBranches = []struct { // TestCompile_AUnionAndARestShareNullOnlyWhereBothAdmitIt holds that a union // sharing no kind with the rest of its allOf shares a null with it only where -// both admit null: a union no branch of which admits null, beside a rest -// admitting it, draws once the warning that no instance satisfies the schema, -// the Model the rest gives keeping the union, and one with a branch admitting -// null draws none. At both versions, for a oneOf and an anyOf, beside the -// allOf, on an entry and beside a $ref, the rest inline and a $ref, in both -// orders of the branches and of the components (GitHub #2055). +// both admit null: with none, one warning that no instance satisfies the +// schema, the rest's Model keeping the union; with one, the position is null +// alone, the closed empty Enum keeping it, in every spelling, order and +// version (GitHub #2055). The nullable-inference policy reads in a 3.0 inline +// rest's `nullable: true` for the whole conjunction, and lifts a null branch +// beside a rest keeping null out, so the union shares that null. func TestCompile_AUnionAndARestShareNullOnlyWhereBothAdmitIt(t *testing.T) { t.Parallel() for _, version := range bothVersions { @@ -71,8 +71,10 @@ func TestCompile_AUnionAndARestShareNullOnlyWhereBothAdmitIt(t *testing.T) { name := fmt.Sprintf("%s/%s/%s/%s/ref=%t/%s", version, rest.name, branch.name, keyword, ref, spelling) t.Run(name, func(t *testing.T) { t.Parallel() + widened := rest.null && version == "3.0.3" && !ref + lifted := !rest.null && branch.name == "null alone" checkNullShared(t, version, keyword, rest.schema[version], branch.schema[version], ref, spelling, - rest.null && branch.null) + rest.null && branch.null || widened || lifted, widened || lifted) }) } } @@ -86,8 +88,10 @@ func TestCompile_AUnionAndARestShareNullOnlyWhereBothAdmitIt(t *testing.T) { // written as spelling says: beside an allOf of rest, on an entry beside it, or // beside the $ref to it, the rest a $ref where ref says, in both orders of the // branches and of the components, and holds what P lowers to to shared, -// whether the two share a value: only null can be one. -func checkNullShared(t *testing.T, version, keyword, rest, branch string, ref bool, spelling string, shared bool) { +// whether the two share a value: only null can be one. Where policyNull says +// the nullable-inference policy reads that null in, the branches of another +// kind are still reported dead, once, at the union. +func checkNullShared(t *testing.T, version, keyword, rest, branch string, ref bool, spelling string, shared, policyNull bool) { t.Helper() for _, branches := range []string{"{$ref: '#/components/schemas/Str'}, " + branch, branch + ", {$ref: '#/components/schemas/Str'}"} { restAt := rest @@ -107,8 +111,8 @@ func checkNullShared(t *testing.T, version, keyword, rest, branch string, ref bo inBothOrders(t, schemas, func(t *testing.T, schemas []string) { doc, diags := compileAnnotationSpec(t, "null-shared", admissionSpec(version, "", schemas...)) if !shared { - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/P", - contains: []string{"share no value", "so no instance satisfies this schema"}}}) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", + contains: []string{"no value satisfies", "; lowered as "}}}) model, ok := typeByName(doc, "P").(*ir.Model) require.True(t, ok, "the schema is the Model the rest of its allOf gives") kept, ok := model.Unmodeled["openapi:"+keyword] @@ -117,15 +121,18 @@ func checkNullShared(t *testing.T, version, keyword, rest, branch string, ref bo return } for _, diagnostic := range diags { - assert.NotContains(t, diagnostic.Message, "so no instance satisfies this schema", "null is a value the two share") + assert.NotContains(t, diagnostic.Message, "no value satisfies", "null is a value the two share") } - if union, ok := typeByName(doc, "P").(*ir.Union); ok { - assert.Len(t, union.Variants, 1, "the branch admitting null is the one variant") - return + if policyNull { + at := map[string]string{"beside": "/" + keyword, "entry": "/allOf/1/" + keyword, "beside the $ref": "/" + keyword}[spelling] + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P" + at, + contains: []string{"no value with the rest of the schema", "so no instance satisfies"}}}) } - irModel, ok := typeByName(doc, "P").(*ir.Model) - require.True(t, ok, "a union whose null branch alone lives keeps it on the Model") - assert.Contains(t, keptOn(irModel), "openapi:"+keyword) + enum, ok := typeByName(doc, "P").(*ir.Enum) + require.True(t, ok, "the position admits null alone") + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(enum)["openapi:"+keyword], "and keeps the union") }) } } diff --git a/compilers/openapi/e2e/union_pair_alone_test.go b/compilers/openapi/e2e/union_pair_alone_test.go index 5922fac44..2426e42f9 100644 --- a/compilers/openapi/e2e/union_pair_alone_test.go +++ b/compilers/openapi/e2e/union_pair_alone_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) @@ -21,62 +22,57 @@ import ( const pairAloneObjects = "[{type: object, properties: {p: {type: string}}, required: [p]}, " + "{type: object, properties: {q: {type: string}}, required: [q]}]" -// unionPairsAlone are a oneOf and an anyOf written with nothing beside them, by -// the kinds of their branches, each with what the position lowers to: the -// union elected, its variant count, the reason the other is kept under, and -// whether the two share no value, a null shared only where both admit it. -// A union of null alone -// elected is an Enum keeping both, and a null branch saying more is kept at -// its index, its oneOf's second branch where saysMore. +// unionPairsAlone are a oneOf and an anyOf with nothing beside them, by the +// kinds of their branches, with what the position lowers to: the union chosen, +// its variant count and the reason the other is kept under. The chosen union's +// branches are read against the other: one sharing no value with it is dead. +// Where only null survives the position is an Enum keeping both ("null"); where +// no branch does, the top type keeping both ("none"), with one warning +// (unsatisfied). A dead branch is kept under its index beside objects (deadAt), +// else the union whole, reported at it (deadWhole). var unionPairsAlone = []struct { - name, oneOf, anyOf, elected string - variants int - kept ir.UnmodeledReason - unsatisfied, null, saysMore bool + name, oneOf, anyOf, chosen, deadAt string + variants int + kept ir.UnmodeledReason + unsatisfied, null, deadWhole bool + // deadBeside names the oneOf branch the anyOf leaves dead where null + // alone survives, reported at the oneOf. + deadBeside string }{ {name: "an anyOf each oneOf branch satisfies", oneOf: pairAloneObjects, anyOf: "[{type: object}]", - elected: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering}, + chosen: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering}, {name: "a oneOf of null alone", oneOf: "[{type: 'null'}]", anyOf: "[{required: [a]}]", - elected: "null", kept: ir.ReasonDegradedLowering, null: true}, - {name: "both of objects", oneOf: pairAloneObjects, elected: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering, + chosen: "null", kept: ir.ReasonDegradedLowering, null: true}, + {name: "both of objects", oneOf: pairAloneObjects, chosen: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering, anyOf: "[{type: object, properties: {x: {type: string}}, required: [x]}, {type: object, properties: {y: {type: string}}}]"}, {name: "an anyOf declaring no shape", oneOf: pairAloneObjects, anyOf: "[{required: [x]}, {required: [y]}]", - elected: "oneOf", variants: 2, kept: ir.ReasonValidationOnly}, + chosen: "oneOf", variants: 2, kept: ir.ReasonValidationOnly}, {name: "a oneOf declaring no shape", oneOf: "[{required: [x]}, {}]", anyOf: pairAloneObjects, - elected: "anyOf", variants: 2, kept: ir.ReasonValidationOnly}, + chosen: "anyOf", variants: 2, kept: ir.ReasonValidationOnly}, {name: "a oneOf with a null branch", oneOf: "[" + entryRef + ", {type: 'null'}]", anyOf: pairAloneObjects, - elected: "oneOf", variants: 1, kept: ir.ReasonDegradedLowering, null: true}, + chosen: "oneOf", variants: 1, kept: ir.ReasonDegradedLowering, null: true, deadAt: "1"}, {name: "a oneOf with a null branch saying more", oneOf: "[" + entryRef + ", {type: 'null', description: none}]", - anyOf: pairAloneObjects, elected: "oneOf", variants: 1, kept: ir.ReasonDegradedLowering, null: true, saysMore: true}, + anyOf: pairAloneObjects, chosen: "oneOf", variants: 1, kept: ir.ReasonDegradedLowering, null: true, deadAt: "1"}, {name: "scalars sharing a kind", oneOf: "[{type: string}, {type: integer}]", - anyOf: "[{type: string, maxLength: 3}, {type: boolean}]", elected: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering}, + anyOf: "[{type: string, maxLength: 3}, {type: boolean}]", chosen: "oneOf", variants: 1, kept: ir.ReasonDegradedLowering, deadWhole: true}, {name: "scalars sharing a null alone", oneOf: "[{type: string}, {type: 'null'}]", - anyOf: "[{type: integer}, {type: 'null'}]", elected: "oneOf", variants: 1, kept: ir.ReasonDegradedLowering, null: true}, + anyOf: "[{type: integer}, {type: 'null'}]", chosen: "null", kept: ir.ReasonDegradedLowering, null: true, deadBeside: "string"}, {name: "objects beside scalars", oneOf: pairAloneObjects, anyOf: "[{type: string}, {type: integer}]", - elected: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering, unsatisfied: true}, + chosen: "none", kept: ir.ReasonDegradedLowering, unsatisfied: true}, {name: "scalars beside objects", oneOf: "[{type: string}, {type: integer}]", anyOf: pairAloneObjects, - elected: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering, unsatisfied: true}, + chosen: "none", kept: ir.ReasonDegradedLowering, unsatisfied: true}, {name: "scalars sharing no kind", oneOf: "[{type: string}, {type: integer}]", anyOf: "[{type: boolean}]", - elected: "oneOf", variants: 2, kept: ir.ReasonDegradedLowering, unsatisfied: true}, + chosen: "none", kept: ir.ReasonDegradedLowering, unsatisfied: true}, {name: "objects beside a null alone", oneOf: pairAloneObjects, anyOf: "[{type: 'null'}]", - elected: "oneOf", variants: 2, kept: ir.ReasonValidationOnly, unsatisfied: true, null: true}, + chosen: "none", kept: ir.ReasonDegradedLowering, unsatisfied: true, null: true}, } // unionPairAloneSpellings are the ways to write the oneOf one and the anyOf -// with nothing beside them: on one schema, on one inline allOf entry and on -// two, each in either order, and one allOf deeper. The one-entry spelling is -// the one each other is compared to. +// with nothing beside them: every placement of two keywords with no body +// (openapitest.Spellings). Entry, the oneOf and the anyOf on one entry, is the +// one each other is compared to. func unionPairAloneSpellings(one, anyOf string) map[string]string { - return map[string]string{ - "one entry": "{allOf: [{oneOf: " + one + ", anyOf: " + anyOf + "}]}", - "one entry, the anyOf first": "{allOf: [{anyOf: " + anyOf + ", oneOf: " + one + "}]}", - "one schema": "{oneOf: " + one + ", anyOf: " + anyOf + "}", - "one schema, the anyOf first": "{anyOf: " + anyOf + ", oneOf: " + one + "}", - "two entries": "{allOf: [{oneOf: " + one + "}, {anyOf: " + anyOf + "}]}", - "two entries, the anyOf first": "{allOf: [{anyOf: " + anyOf + "}, {oneOf: " + one + "}]}", - "two entries one allOf deeper": "{allOf: [{allOf: [{oneOf: " + one + "}, {anyOf: " + anyOf + "}]}]}", - "one entry one allOf deeper": "{allOf: [{allOf: [{oneOf: " + one + ", anyOf: " + anyOf + "}]}]}", - } + return openapitest.Spellings("", "oneOf: "+one, "anyOf: "+anyOf) } // reversedBranches is the branch list written as a YAML flow sequence of @@ -105,15 +101,15 @@ func reversedBranches(t *testing.T, list string) string { return "[" + strings.Join(branches, ", ") + "]" } -// TestElection_TwoUnionsAloneLowerAsOneSchemaWritingBoth holds that a oneOf and +// TestChoice_TwoUnionsAloneLowerAsOneSchemaWritingBoth holds that a oneOf and // an anyOf with nothing beside them lower alike on one schema, on one allOf // entry and on two, in either order of the entries, the keywords, the branches // and the components, and one allOf deeper, at every version and position, by // every kind of pair: the position is a Union of the union competing keywords -// elects, keeping the other under its keyword, as validation logic where its -// branches declare no shape, and draws one warning where the two share no -// value, as two conjuncts sharing none do (GitHub #2011). -func TestElection_TwoUnionsAloneLowerAsOneSchemaWritingBoth(t *testing.T) { +// chooses, its branches read against the other union, keeping the other under +// its keyword, as validation logic where its branches declare no shape, and +// draws one warning where the two share no value (GitHub #2011, #2115). +func TestChoice_TwoUnionsAloneLowerAsOneSchemaWritingBoth(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { for _, site := range bothKeywordsSites { @@ -130,16 +126,27 @@ func TestElection_TwoUnionsAloneLowerAsOneSchemaWritingBoth(t *testing.T) { } doc, diags := compileSpellingsAlike(t, site, version, unionPairAloneSpellings(one, anyOf)) var want []wantFinding - if pair.unsatisfied { - want = append(want, wantFinding{code: diag.DegradedConstruct, pointer: string(site.at), - contains: []string{"share no value", "so no instance satisfies this schema, which the union it lowered as"}}) - } - requireErrorsAndWarnings(t, diags, want) kept := map[string]ir.UnmodeledReason{} - if pair.saysMore { - kept[fmt.Sprintf("openapi:oneOf/%d", map[bool]int{false: 1, true: 0}[reversed])] = ir.ReasonNoIRHome + switch { + case pair.unsatisfied: + want = append(want, wantFinding{code: diag.UnsatisfiableSchema, pointer: string(site.at), + contains: []string{"no value satisfies", "; lowered as "}}) + case pair.deadAt != "": + index := map[bool]int{false: 1, true: 0}[reversed] + kept[fmt.Sprintf("openapi:oneOf/%d", index)] = ir.ReasonDegradedLowering + want = append(want, wantFinding{code: diag.UnsatisfiableSchema, pointer: string(site.at), + contains: []string{fmt.Sprintf("oneOf/%d", index)}}) + case pair.deadWhole: + kept["openapi:oneOf"] = ir.ReasonDegradedLowering + want = append(want, wantFinding{code: diag.UnsatisfiableSchema, pointer: string(site.at) + "/allOf/0/oneOf", + contains: []string{"no value with the rest of the schema"}}) + case pair.deadBeside != "": + index := map[bool]int{false: 0, true: 1}[reversed] + want = append(want, wantFinding{code: diag.UnsatisfiableSchema, pointer: string(site.at) + "/allOf/0/oneOf", + contains: []string{fmt.Sprintf("oneOf/%d: %s", index, pair.deadBeside)}}) } - requirePairAlone(t, kindNode(t, doc, entryPositionID(site.at)), pair.elected, pair.variants, pair.kept, kept) + requireErrorsAndWarnings(t, diags, want) + requirePairAlone(t, kindNode(t, doc, entryPositionID(site.at)), pair.chosen, pair.variants, pair.kept, kept) }) } } @@ -148,27 +155,34 @@ func TestElection_TwoUnionsAloneLowerAsOneSchemaWritingBoth(t *testing.T) { } // requirePairAlone holds node, what a oneOf and an anyOf alone lowered to, to a -// Union of variants variants of the union elected, keeping the other for -// reason beside what more holds, or, where elected is "null", to the Enum of -// null alone keeping both. -func requirePairAlone(t *testing.T, node ir.TypeDef, elected string, variants int, reason ir.UnmodeledReason, +// Union of variants variants of the union chosen, keeping the other for reason +// beside what more holds, or, where chosen is "null", to the Enum of null alone +// keeping both, or, where it is "none", to the top type keeping both. +func requirePairAlone(t *testing.T, node ir.TypeDef, chosen string, variants int, reason ir.UnmodeledReason, more map[string]ir.UnmodeledReason, ) { t.Helper() - if elected == "null" { + switch chosen { + case "null": enum, ok := node.(*ir.Enum) require.True(t, ok, "the position is null alone") assert.Empty(t, enum.Members) assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": reason, "openapi:anyOf": reason}, keptOn(enum), "the Enum keeps both unions") return + case "none": + scalar, ok := node.(*ir.Scalar) + require.True(t, ok, "no branch lives, so the position is the top type") + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": reason, "openapi:anyOf": reason}, + keptOn(scalar), "the top type keeps both unions") + return } union, ok := node.(*ir.Union) - require.True(t, ok, "the position is a Union of the union elected") + require.True(t, ok, "the position is a Union of the union chosen") assert.Len(t, union.Variants, variants) - assert.Equal(t, elected == "oneOf", union.Exclusive, "the union elected") + assert.Equal(t, chosen == "oneOf", union.Exclusive, "the union chosen") other := "oneOf" - if elected == "oneOf" { + if chosen == "oneOf" { other = "anyOf" } more["openapi:"+other] = reason diff --git a/compilers/openapi/e2e/union_pair_disjoint_test.go b/compilers/openapi/e2e/union_pair_disjoint_test.go index b8d49ec48..d8f7bb3a8 100644 --- a/compilers/openapi/e2e/union_pair_disjoint_test.go +++ b/compilers/openapi/e2e/union_pair_disjoint_test.go @@ -11,13 +11,13 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/diag" ) -// TestElection_TwoUnionsSharingNoValueWarnOnceBesideAnyBody holds that a +// TestChoice_TwoUnionsSharingNoValueWarnOnceBesideAnyBody holds that a // oneOf and an anyOf sharing no value, a null shared only where both admit // it, lower alike beside a string, a string or null, an array, an object or // null and an object, on one schema, beside an allOf, on one entry or two, in // either order: as the schema writing them beside its body lowers, with the // one warning that the conjuncts share no value (GitHub #2011). -func TestElection_TwoUnionsSharingNoValueWarnOnceBesideAnyBody(t *testing.T) { +func TestChoice_TwoUnionsSharingNoValueWarnOnceBesideAnyBody(t *testing.T) { t.Parallel() bodies := []string{"{type: string}", "{type: [string, 'null']}", "{type: array, items: {type: string}}", "{type: [object, 'null'], properties: {a: {type: string}}}", "{type: object, properties: {a: {type: string}}}"} @@ -43,8 +43,8 @@ func TestElection_TwoUnionsSharingNoValueWarnOnceBesideAnyBody(t *testing.T) { spellings["beside the body"] = strings.TrimSuffix(body, "}") + ", oneOf: " + one + ", anyOf: " + anyOf + "}" } _, diags := compileSpellingsAlike(t, bothKeywordsSites[0], "3.1.0", spellings) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/P", - contains: []string{"share no value", "so no instance satisfies this schema"}}}) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", + contains: []string{"no value satisfies", "; lowered as "}}}) }) } } diff --git a/compilers/openapi/e2e/union_pair_scalar_test.go b/compilers/openapi/e2e/union_pair_scalar_test.go index 3d3d72777..c6728f503 100644 --- a/compilers/openapi/e2e/union_pair_scalar_test.go +++ b/compilers/openapi/e2e/union_pair_scalar_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) @@ -31,12 +32,12 @@ var stringOrNullBodies = map[string]string{ "3.2.0": "{type: [string, 'null']}", } -// TestElection_TwoUnionsOfNullAloneBesideABodyKeepTheirReasonEverywhere holds +// TestChoice_TwoUnionsOfNullAloneBesideABodyKeepTheirReasonEverywhere holds // that a oneOf and an anyOf each of null alone, beside a string or null, lower // alike beside the allOf, on one entry, on two in either order and one allOf // deeper, in either order of the components: null alone, keeping both unions // as degraded_lowering, as beside the allOf (GitHub #2011). -func TestElection_TwoUnionsOfNullAloneBesideABodyKeepTheirReasonEverywhere(t *testing.T) { +func TestChoice_TwoUnionsOfNullAloneBesideABodyKeepTheirReasonEverywhere(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { for _, site := range scalarPairSites { @@ -55,14 +56,15 @@ func TestElection_TwoUnionsOfNullAloneBesideABodyKeepTheirReasonEverywhere(t *te } } -// TestElection_APrincipalUnionBesideAPairAndABodyCollapsesAsBesideTheAllOf -// holds that an anyOf of null and a $ref to a string, elected over a oneOf -// declaring no shape, beside a string or null, lowers alike beside the allOf, -// on one entry, on two in either order and one allOf deeper, in either order of -// the branches and the components: a Union of the one string, as beside the -// allOf, not collapsed to a reference on two entries, keeping the oneOf as -// validation_only (GitHub #2011). -func TestElection_APrincipalUnionBesideAPairAndABodyCollapsesAsBesideTheAllOf(t *testing.T) { +// TestChoice_APrincipalUnionBesideAPairAndABodyCollapsesAsBesideTheAllOf holds +// that an anyOf of null and a $ref to a string, chosen over a oneOf declaring +// no shape, beside a string or null, lowers alike beside the allOf, on one +// entry, on two in either order and one allOf deeper, in either order of the +// branches and the components: the one live branch, the string, is the +// position's node, as beside the allOf, not collapsed to a reference on two +// entries, keeping the oneOf as validation_only (GitHub #2011), its Base +// admitting the null every conjunct admits, as the Scalar's own schema does. +func TestChoice_APrincipalUnionBesideAPairAndABodyCollapsesAsBesideTheAllOf(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { for _, site := range scalarPairSites { @@ -76,26 +78,27 @@ func TestElection_APrincipalUnionBesideAPairAndABodyCollapsesAsBesideTheAllOf(t if reversed { anyOf = reversedBranches(t, anyOf) } - doc, _ := compileSpellingsAlike(t, site, version, - unionPairSpellings(stringOrNullBodies[version], "[{required: [a]}]", anyOf)) - union, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Union) - require.True(t, ok, "the position is a Union") - require.Len(t, union.Variants, 1) - assert.Equal(t, componentID("Kstr"), union.Variants[0].Type.Target) - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}, keptOn(union)) + doc, _ := compileSpellingsAlike(t, site, version, unionPairSpellings(stringOrNullBodies[version], "[{required: [a]}]", anyOf)) + node, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Scalar) + require.True(t, ok, "the position is its one live branch's node") + assert.Equal(t, componentID("Kstr"), node.Base.Target) + assert.True(t, node.Base.Nullable, "null satisfies the body, the oneOf's one branch and the anyOf's null") + assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}, keptOn(node)) }) } } } } -// TestElection_TwoUnionEntriesElectByCompetingKeywords holds that a oneOf of -// an object and a $ref to a string and an anyOf of that $ref alone, beside a +// TestChoice_TwoUnionEntriesChooseByCompetingKeywords holds that a oneOf of an +// object and a $ref to a string and an anyOf of that $ref alone, beside a // string, lower alike beside the allOf, on one entry, on two in either order -// and one allOf deeper, in either order of the branches and the components: -// the oneOf is elected, both declaring shape, though the anyOf's kinds are the -// body's, and the anyOf is kept as degraded_lowering (GitHub #2011). -func TestElection_TwoUnionEntriesElectByCompetingKeywords(t *testing.T) { +// and one allOf deeper, in either order of the branches and the components: the +// oneOf is chosen, both declaring shape, though the anyOf's kinds are the +// body's; its object branch, sharing no kind with the rest, is dead, so the one +// live branch, the $ref, is the position's node keeping the oneOf whole, and +// the anyOf is kept as degraded_lowering (GitHub #2011, #2115). +func TestChoice_TwoUnionEntriesChooseByCompetingKeywords(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { for _, site := range scalarPairSites { @@ -106,45 +109,48 @@ func TestElection_TwoUnionEntriesElectByCompetingKeywords(t *testing.T) { if reversed { one = reversedBranches(t, one) } - doc, _ := compileSpellingsAlike(t, site, version, + doc, diags := compileSpellingsAlike(t, site, version, unionPairSpellings("{type: string}", one, "[{$ref: '#/components/schemas/Kstr'}]")) - union, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Union) - require.True(t, ok, "the position is a Union") - assert.True(t, union.Exclusive, "the oneOf is elected") - assert.Len(t, union.Variants, 2) - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:anyOf": ir.ReasonDegradedLowering}, keptOn(union)) + node, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Scalar) + require.True(t, ok, "the position is its one live branch's node") + assert.Equal(t, &ir.TypeRef{Target: componentID("Kstr")}, node.Base) + assert.Positive(t, countBeneath(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, string(site.at)), + "the oneOf is chosen, its object branch dead") + assert.Equal(t, map[string]ir.UnmodeledReason{ + "openapi:oneOf": ir.ReasonDegradedLowering, "openapi:anyOf": ir.ReasonDegradedLowering, + }, keptOn(node)) }) } } } } -// TestElection_AnEntryWritingBothElectsAgainstThePosition holds that a oneOf -// and an anyOf beside a string or null lower alike beside the allOf, on one -// entry, on two in either order and one allOf deeper, in either order of the -// branches and the components, each union judged against all the position -// conjoins, whichever entry writes it (GitHub #2011): an anyOf with an object -// branch is elected over a oneOf restating the body, its null branch included, -// which is kept whole as validation_only, and a oneOf of null alone over an -// anyOf restating the body, the position null alone keeping both. -func TestElection_AnEntryWritingBothElectsAgainstThePosition(t *testing.T) { +// TestChoice_AnEntryWritingBothChoosesAgainstThePosition holds that a oneOf and +// an anyOf beside a string or null lower alike beside the allOf, on one entry, +// on two in either order and one allOf deeper, in either order of the branches +// and components, each judged against all the position conjoins (GitHub #2011): +// an anyOf with an object branch is chosen over a oneOf restating the body; +// that branch is dead and the other restates the body, so the body's node keeps +// both as degraded_lowering (GitHub #2108, #2115); a oneOf of null alone over +// an anyOf restating the body leaves null alone. +func TestChoice_AnEntryWritingBothChoosesAgainstThePosition(t *testing.T) { t.Parallel() - anyOfElected := func(t *testing.T, td ir.TypeDef) { + anyOfChosen := func(t *testing.T, td ir.TypeDef) { t.Helper() - union, ok := td.(*ir.Union) - require.True(t, ok, "the position is a Union") - assert.False(t, union.Exclusive, "the anyOf is elected") - assert.Len(t, union.Variants, 2) - assert.Equal(t, map[string]ir.UnmodeledReason{"openapi:oneOf": ir.ReasonValidationOnly}, keptOn(union)) + scalar, ok := td.(*ir.Scalar) + require.True(t, ok, "the body's node sits at the position") + assert.Equal(t, map[string]ir.UnmodeledReason{ + "openapi:oneOf": ir.ReasonDegradedLowering, "openapi:anyOf": ir.ReasonDegradedLowering, + }, keptOn(scalar)) } cases := []struct { name, oneOf, anyOf string want func(*testing.T, ir.TypeDef) }{ {"an anyOf declaring shape", "[{type: string}]", "[{type: object, properties: {x: {type: string}}}, {type: string}]", - anyOfElected}, + anyOfChosen}, {"a oneOf with a null branch saying more", "[{type: 'null', title: n}, {type: string}]", - "[{type: object, properties: {x: {type: string}}}, {type: string}]", anyOfElected}, + "[{type: object, properties: {x: {type: string}}}, {type: string}]", anyOfChosen}, {"a oneOf of null alone", "[{type: 'null'}]", "[{type: 'null'}, {type: string}]", func(t *testing.T, td ir.TypeDef) { t.Helper() _, ok := td.(*ir.Enum) @@ -173,14 +179,16 @@ func TestElection_AnEntryWritingBothElectsAgainstThePosition(t *testing.T) { } } -// TestElection_TwoUnionsSharingNullAloneBesideABodyAdmittingNullAreKept holds +// TestChoice_TwoUnionsSharingNullAloneBesideABodyAdmittingNullAreKept holds // that a oneOf of an object and null and an anyOf of a string and null, which // share null alone, beside a $ref to an object or null, lower alike beside the // allOf, on one entry, on two in either order and one allOf deeper, in either -// order of the branches and the components: a use of the body keeping both -// unions as degraded_lowering, distributing neither, with no warning, as null -// is a value every conjunct admits (GitHub #2011). -func TestElection_TwoUnionsSharingNullAloneBesideABodyAdmittingNullAreKept(t *testing.T) { +// order of the branches and the components: the position admits null alone, +// the closed empty Enum behind a nullable reference keeping both unions as +// degraded_lowering, as null is a value every conjunct admits, the one warning +// naming at the oneOf its object branch, which the rest leaves dead (GitHub +// #2011, #2111). +func TestChoice_TwoUnionsSharingNullAloneBesideABodyAdmittingNullAreKept(t *testing.T) { t.Parallel() const body = "{$ref: '#/components/schemas/TN'}" const tn = "TN: {type: [object, 'null'], properties: {a: {type: string}}}" @@ -202,10 +210,10 @@ func TestElection_TwoUnionsSharingNullAloneBesideABodyAdmittingNullAreKept(t *te one, anyOf = reversedBranches(t, one), reversedBranches(t, anyOf) } doc, diags := compileSpellingsAlike(t, site, version, unionPairSpellings(body, one, anyOf)) - requireErrorsAndWarnings(t, diags, nil) - assert.Equal(t, map[string]ir.UnmodeledReason{ - "openapi:oneOf": ir.ReasonDegradedLowering, "openapi:anyOf": ir.ReasonDegradedLowering, - }, keptAtUse(t, doc, site), "the position keeps both unions") + index := map[bool]int{false: 0, true: 1}[reversed] + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, + pointer: string(site.at) + "/allOf/1/oneOf", contains: []string{fmt.Sprintf("oneOf/%d: object", index)}}}) + requireNullAloneKeepingBoth(t, doc, site) }) } } diff --git a/compilers/openapi/e2e/union_pair_shapeless_reason_test.go b/compilers/openapi/e2e/union_pair_shapeless_reason_test.go index 07dc497c7..1015c58cf 100644 --- a/compilers/openapi/e2e/union_pair_shapeless_reason_test.go +++ b/compilers/openapi/e2e/union_pair_shapeless_reason_test.go @@ -12,12 +12,12 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestElection_TwoShapelessUnionsBesideAScalarKeepBesidesReasonOnEntries holds +// TestChoice_TwoShapelessUnionsBesideAScalarKeepBesidesReasonOnEntries holds // that a oneOf of null alone and an anyOf restating a scalar body, neither -// declaring shape against it and sharing no value, are kept as validation -// logic on the allOf's entries, as beside the allOf, in either order -// (GitHub #2011). -func TestElection_TwoShapelessUnionsBesideAScalarKeepBesidesReasonOnEntries(t *testing.T) { +// declaring shape against it and sharing no value, leave no branch of the oneOf +// live, so both are kept as degraded_lowering on the allOf's entries, as beside +// the allOf, in either order (GitHub #2011, #2115). +func TestChoice_TwoShapelessUnionsBesideAScalarKeepBesidesReasonOnEntries(t *testing.T) { t.Parallel() for _, body := range []string{"{type: string}", "{type: integer}"} { for _, reversed := range []bool{false, true} { @@ -26,8 +26,8 @@ func TestElection_TwoShapelessUnionsBesideAScalarKeepBesidesReasonOnEntries(t *t site := bothKeywordsSites[0] doc, _ := compileSpellingsAlike(t, site, "3.1.0", unionPairSpellings(body, "[{type: 'null'}]", "["+body+"]")) assert.Equal(t, map[string]ir.UnmodeledReason{ - "openapi:oneOf": ir.ReasonValidationOnly, "openapi:anyOf": ir.ReasonValidationOnly, - }, keptAtUse(t, doc, site), "the position keeps both unions as validation logic") + "openapi:oneOf": ir.ReasonDegradedLowering, "openapi:anyOf": ir.ReasonDegradedLowering, + }, keptAtUse(t, doc, site), "the position keeps both unions, no branch of the oneOf living") }) } } diff --git a/compilers/openapi/e2e/union_pair_shapeless_test.go b/compilers/openapi/e2e/union_pair_shapeless_test.go index 08fa846b2..d7516a51d 100644 --- a/compilers/openapi/e2e/union_pair_shapeless_test.go +++ b/compilers/openapi/e2e/union_pair_shapeless_test.go @@ -13,12 +13,12 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/diag" ) -// TestElection_TwoShapelessUnionsSharingNoValueWarnBesideTheirBody holds that +// TestChoice_TwoShapelessUnionsSharingNoValueWarnBesideTheirBody holds that // a oneOf and an anyOf sharing no value, neither declaring shape against the // body beside them, draw the one warning that the conjuncts share no value // where they are written beside the body's own keywords, as beside an allOf of // the body and on its entries (GitHub #2011). -func TestElection_TwoShapelessUnionsSharingNoValueWarnBesideTheirBody(t *testing.T) { +func TestChoice_TwoShapelessUnionsSharingNoValueWarnBesideTheirBody(t *testing.T) { t.Parallel() cases := []struct{ body, oneOf, anyOf string }{ {"{type: string}", "[{type: 'null'}]", "[{type: string}]"}, @@ -32,19 +32,19 @@ func TestElection_TwoShapelessUnionsSharingNoValueWarnBesideTheirBody(t *testing t.Run(fmt.Sprintf("%s/%s/%t", tc.body, name, reversed), func(t *testing.T) { t.Parallel() _, diags := compileAnnotationSpec(t, "shapeless", bothKeywordsSites[0].doc("3.1.0", schema, reversed)) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/P", - contains: []string{"share no value", "so no instance satisfies this schema"}}}) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", + contains: []string{"no value satisfies", "; lowered as "}}}) }) } } } } -// TestElection_TwoShapelessUnionsSharingNullBesideABodyAreNotNamedApart holds +// TestChoice_TwoShapelessUnionsSharingNullBesideABodyAreNotNamedApart holds // that a oneOf and an anyOf sharing null, written beside a body admitting no // null, are not reported as sharing no value with each other: they share the // null, which the body keeps out. -func TestElection_TwoShapelessUnionsSharingNullBesideABodyAreNotNamedApart(t *testing.T) { +func TestChoice_TwoShapelessUnionsSharingNullBesideABodyAreNotNamedApart(t *testing.T) { t.Parallel() _, diags := compileAnnotationSpec(t, "shared", bothKeywordsSites[0].doc("3.1.0", "{type: string, oneOf: [{type: 'null'}], anyOf: [{type: 'null'}]}", false)) diff --git a/compilers/openapi/e2e/union_pair_spellings_test.go b/compilers/openapi/e2e/union_pair_spellings_test.go index 7cbb215e2..76f0ffdf0 100644 --- a/compilers/openapi/e2e/union_pair_spellings_test.go +++ b/compilers/openapi/e2e/union_pair_spellings_test.go @@ -6,13 +6,13 @@ package e2e_test import ( "fmt" "maps" - "regexp" "slices" "strings" "testing" "github.com/google/go-cmp/cmp" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) @@ -79,40 +79,14 @@ func pairUnion(names string, reversed bool) string { return "[" + strings.Join(branches, ", ") + "]" } -// pairSpellings writes a oneOf and an anyOf beside body in the flat spelling, -// beside an allOf of the body, on one entry and on two in either order, and -// each one allOf deeper; reversed reverses the entries and the keywords. +// pairSpellings writes a oneOf and an anyOf beside body in every placement +// openapitest.Spellings gives, or, where reversed, in the order openapitest.Reversed does: +// the entries and the keywords the other way about. func pairSpellings(body, oneOf, anyOf string, reversed bool) map[string]string { - unions := []string{"oneOf: " + oneOf, "anyOf: " + anyOf} + spellings := openapitest.Spellings(body, "oneOf: "+oneOf, "anyOf: "+anyOf) if reversed { - slices.Reverse(unions) + spellings = openapitest.Reversed(body, "oneOf: "+oneOf, "anyOf: "+anyOf) } - both := strings.Join(unions, ", ") - order := func(entries ...string) string { - if reversed { - slices.Reverse(entries) - } - return "{allOf: [" + strings.Join(entries, ", ") + "]}" - } - withBody := func(entries ...string) string { - if body == "" { - return order(entries...) - } - return order(append([]string{"{" + body + "}"}, entries...)...) - } - spellings := map[string]string{ - "one": withBody("{" + both + "}"), - "nest": withBody("{allOf: [{" + both + "}]}"), - "two": withBody("{oneOf: "+oneOf+"}", "{anyOf: "+anyOf+"}"), - "tworev": withBody("{anyOf: "+anyOf+"}", "{oneOf: "+oneOf+"}"), - "deep": withBody(order("{oneOf: "+oneOf+"}", "{anyOf: "+anyOf+"}")), - } - if body == "" { - spellings["flat"] = "{" + both + "}" - return spellings - } - spellings["flat"] = "{" + body + ", " + both + "}" - spellings["beside"] = "{allOf: [{" + body + "}], " + both + "}" return spellings } @@ -220,213 +194,58 @@ func viewOfPair(doc *ir.Document, diags []ir.Diagnostic, name string) pairView { // isInfo reports whether finding, a severity and a code, is an info. func isInfo(finding string) bool { return strings.HasPrefix(finding, string(ir.SeverityInfo)+" ") } -// infosOf is the infos of pairViewValue's findings. -func infosOf(pairViewValue pairView) []string { - return slices.DeleteFunc(slices.Clone(pairViewValue.Findings), func(f string) bool { return !isInfo(f) }) -} - -// facets names the facets of two views that differ, the warnings and errors -// apart from the infos, a view with no finding left in either alike with one -// whose findings are infos alone. -func facets(a, b pairView) []string { - var out []string - for _, f := range []struct { - name string - same bool - }{ - {"kind", a.Kind == b.Kind}, {"variants", cmp.Equal(a.Variants, b.Variants)}, - {"kept", cmp.Equal(a.Kept, b.Kept)}, {"infos", slices.Equal(infosOf(a), infosOf(b))}, - {"warnings", slices.Equal(slices.DeleteFunc(slices.Clone(a.Findings), isInfo), slices.DeleteFunc(slices.Clone(b.Findings), isInfo))}, - } { - if !f.same { - out = append(out, f.name) - } - } - return out -} - -// pairExcused are the bodies beside which a union written alone lowers apart -// in its own spellings, each naming that mechanism and the open issue holding -// it (pairIssues). A pair beside one of them is excused where its split is -// one of its unions' (singleExplains); each body must still excuse one, so a -// fix elsewhere names it stale. -var pairExcused = map[string]string{ - "object or null": "#2111, #2112: a union of null alone beside a type list holding an object is its Model, an " + - "Enum of null beside an allOf of the list (#2111), and the list on an allOf entry is kept where beside the " + - "union it is read (#2112)", - "string or null": "#2108: a union beside a scalar body is the body's Scalar beside its keywords, a Union beside an allOf", - "string": "#2108: a union beside a scalar body is the body's Scalar beside its keywords, a Union beside an allOf", -} - -// pairIssues matches the reason of an excuse or an open group: the open issues -// holding the mechanism, each a question #2011 leaves to another, then why. -var pairIssues = regexp.MustCompile(`^#(2108|2109|2111|2112)(, #(2108|2109|2111|2112))*: `) - -// pairOpen are the groups, by body and pair, whose spellings split where -// neither union alone does, each by a mechanism an open issue holds for one -// union too: a pair beside a scalar body, whose node #2108 decides, and a -// pair's null beside a $ref, which the nullable-inference policy widens -// beside the $ref alone (#2109). Each cites its issue and must still split. -var pairOpen = map[[2]string]string{ - {"ref to an object", "null through a ref and inline"}: "#2109: the flat spelling's $ref is widened to admit null, the others' not", - {"string", "refs on both"}: "#2108: the flat spelling is the body's Scalar, the others a Union of the oneOf", - {"string or null", "refs on both"}: "#2108: the flat spelling is the body's Scalar, the others a Union of the oneOf", - {"string or null", "null and a ref"}: "#2108: the flat spelling is the body's Scalar, the others a Union of the $ref", - {"string", "null and a ref"}: "#2108: the flat spelling is the body's Scalar, the others a Union of the $ref", - {"string", "a branch that is a union"}: "#2108: the flat spelling is the body's Scalar, the others a Union of the union", - {"string or null", "a branch that is a union"}: "#2108: the flat spelling is the body's Scalar, the others a Union " + - "of the union", -} - -// singleSpellings are the spellings a union written alone has. -var singleSpellings = []string{"flat", "beside", "one", "nest"} - -// pairSingles writes each union of a pair alone beside body in the spellings -// singleSpellings names, keyed by keyword initial and spelling. -func pairSingles(body, oneOf, anyOf string) map[string]string { - out := map[string]string{} - for keyword, union := range map[string]string{"O": "oneOf: " + oneOf, "A": "anyOf: " + anyOf} { - out[keyword+"flat"] = "{" + body + ", " + union + "}" - out[keyword+"beside"] = "{allOf: [{" + body + "}], " + union + "}" - out[keyword+"one"] = "{allOf: [{" + body + "}, {" + union + "}]}" - out[keyword+"nest"] = "{allOf: [{" + body + "}, {allOf: [{" + union + "}]}]}" - } - return out -} - -// pairPartition groups spellings by the view each gives. -func pairPartition(spellings []string, view func(string) pairView) [][]string { - var classes [][]string - for _, spelling := range spellings { - at := slices.IndexFunc(classes, func(c []string) bool { return cmp.Equal(view(c[0]), view(spelling)) }) - if at < 0 { - classes = append(classes, []string{spelling}) - continue - } - classes[at] = append(classes[at], spelling) - } - return classes -} - -// within reports whether every class of fine lies within one class of coarse. -func within(fine, coarse [][]string) bool { - return !slices.ContainsFunc(fine, func(f []string) bool { - return !slices.ContainsFunc(coarse, func(c []string) bool { - return !slices.ContainsFunc(f, func(s string) bool { return !slices.Contains(c, s) }) - }) - }) -} - -// singleExplains reports whether the split of pair i is one of its unions': -// the two-entry spellings lower as one entry does, and over the spellings a -// union alone has, the pair splits as one of its unions alone does, or -// coarser, each spelling apart from the flat one differing from it only in -// facets that union's same spelling differs from its flat one in. -func singleExplains(view func(int, string) pairView, i int) bool { - for _, spelling := range []string{"two", "tworev", "deep"} { - if !cmp.Equal(view(i, "one"), view(i, spelling)) { - return false - } - } - pair := pairPartition(singleSpellings, func(s string) pairView { return view(i, s) }) - for _, keyword := range []string{"O", "A"} { - single := pairPartition(singleSpellings, func(s string) pairView { return view(i, keyword+s) }) - if len(single) > 1 && within(single, pair) && sameFacets(view, i, keyword) { - return true - } - } - return false -} - -// sameFacets reports whether each spelling of pair i differs from its flat -// one only in facets the union keyword alone differs in at that spelling. -func sameFacets(view func(int, string) pairView, i int, keyword string) bool { - for _, spelling := range singleSpellings[1:] { - single := facets(view(i, keyword+"flat"), view(i, keyword+spelling)) - for _, f := range facets(view(i, "flat"), view(i, spelling)) { - if !slices.Contains(single, f) { - return false - } - } - } - return true -} - -// TestElection_AUnionPairLowersAlikeInEverySpelling holds that a oneOf and an -// anyOf, of each pair above, beside each body above or none, lower alike in -// the flat spelling and the six allOf spellings, in either order of the -// entries, the branches, the keywords and the components: the same kind of -// node, the same variants, each as what it is, the same keys kept with the -// same reasons and the same findings, wherever each stands (GitHub #2011). -// A spelling writing one union flat and the other on an entry is #2110's. -func TestElection_AUnionPairLowersAlikeInEverySpelling(t *testing.T) { +// TestChoice_AUnionPairLowersAlikeInEverySpelling holds that a oneOf and an +// anyOf, of each pair above, beside each body above or none, lower alike in the +// flat spelling and the six allOf spellings, in either order of the entries, +// the branches, the keywords and the components: the same kind of node, the +// same variants, each as what it is, the same keys kept with the same reasons +// and the same findings, wherever each sits (GitHub #2011, #2108, #2109, #2111, +// #2112). A spelling writing one union flat and the other on an entry is held +// in union_beside_body_test.go. +func TestChoice_AUnionPairLowersAlikeInEverySpelling(t *testing.T) { t.Parallel() - for group, why := range pairOpen { - if !pairIssues.MatchString(why) { - t.Errorf("%v is open for no question an open issue holds: %s", group, why) - } - } - for body, why := range pairExcused { - if !pairIssues.MatchString(why) { - t.Errorf("%s is excused by no mechanism an open issue holds: %s", body, why) - } - } for _, body := range pairBodies { t.Run(body.name, func(t *testing.T) { t.Parallel() - excuses := 0 for _, reversed := range []bool{false, true} { - excuses += pairGroupsAlike(t, body.name, body.body, reversed) - } - if why, ok := pairExcused[body.name]; ok && excuses == 0 { - t.Errorf("excused (%s) but no pair needs it: stale", why) + pairGroupsAlike(t, body.body, reversed) } }) } } -// pairGroupsAlike compiles every pair beside body in every spelling, holds -// each spelling to the flat one, and returns how many pairs the body's excuse -// explains. -func pairGroupsAlike(t *testing.T, name, body string, reversed bool) int { +// pairGroupsAlike compiles every pair beside body in every spelling and holds +// each spelling to the flat one. +func pairGroupsAlike(t *testing.T, body string, reversed bool) { t.Helper() schemas := []string{"TN: {type: [object, 'null'], properties: {a: {type: string}}}", "Kstr: {type: string}", "Knul: {type: 'null'}", "Kuni: {oneOf: [{type: string}, {type: integer}]}"} for i, pair := range unionPairs { oneOf, anyOf := pairUnion(pair.oneOf, reversed), pairUnion(pair.anyOf, reversed) spellings := pairSpellings(body, oneOf, anyOf, reversed) - if body != "" { - maps.Copy(spellings, pairSingles(body, oneOf, anyOf)) - } for _, spelling := range slices.Sorted(maps.Keys(spellings)) { schemas = append(schemas, fmt.Sprintf("P%d%s: %s", i, spelling, spellings[spelling])) } } doc, diags := compileAnnotationSpec(t, "pairs", bothKeywordsDoc("3.1.0", "", reversed, schemas...)) - view := func(i int, spelling string) pairView { - return viewOfPair(doc, diags, fmt.Sprintf("P%d%s", i, spelling)) - } - excused := 0 + var differing []string + firstDiff, firstAt := "", "" for i, pair := range unionPairs { - apart := map[string]string{} for _, spelling := range slices.Sorted(maps.Keys(pairSpellings(body, "[]", "[]", false))) { - if diff := cmp.Diff(view(i, "flat"), view(i, spelling)); diff != "" { - apart[spelling] = diff + flat := viewOfPair(doc, diags, fmt.Sprintf("P%dFlat", i)) + diff := cmp.Diff(flat, viewOfPair(doc, diags, fmt.Sprintf("P%d%s", i, spelling))) + if diff == "" { + continue } + if len(differing) == 0 { + firstDiff, firstAt = diff, pair.name+" "+spelling + } + differing = append(differing, pair.name+" "+spelling) } - why, open := pairOpen[[2]string{name, pair.name}] - switch { - case open && len(apart) == 0: - t.Errorf("%s, reversed %t: open (%s) but lowers alike: stale", pair.name, reversed, why) - continue - case open, len(apart) == 0: - continue - } - if _, ok := pairExcused[name]; ok && singleExplains(view, i) { - excused++ - continue - } - t.Errorf("%s, reversed %t: spellings differ from the flat (-flat +spelling): %v", pair.name, reversed, apart) } - return excused + if len(differing) > 0 { + t.Errorf("reversed %t: %d of the spellings differ from the flat: %s\nthe first, %s (-flat +spelling):\n%s", + reversed, len(differing), strings.Join(differing[:min(len(differing), maxNamedDifferences)], "; "), firstAt, + openapitest.Excerpt(firstDiff, maxDifferenceLines)) + } } diff --git a/compilers/openapi/e2e/union_pair_unsatisfied_test.go b/compilers/openapi/e2e/union_pair_unsatisfied_test.go index ad222dbeb..92f318921 100644 --- a/compilers/openapi/e2e/union_pair_unsatisfied_test.go +++ b/compilers/openapi/e2e/union_pair_unsatisfied_test.go @@ -34,14 +34,14 @@ var unsatisfiedPairs = []struct{ name, oneOf, anyOf string }{ {"neither admits an object or a kind of the other", "[{type: string}]", "[{type: boolean}]"}, } -// TestElection_TwoUnionsNoInstanceSatisfiesLowerAlikeWhereverWritten holds that -// a oneOf and an anyOf no instance of the body satisfies together lower alike -// beside the body, beside its allOf, on one entry and on two, in either order of -// the entries, the keywords and the components, at every version and position, -// over an inline body and a $ref: the position is the Model the body gives, -// keeping both unions as degraded_lowering, and draws one warning that no -// instance satisfies it, whichever union is elected (GitHub #2011). -func TestElection_TwoUnionsNoInstanceSatisfiesLowerAlikeWhereverWritten(t *testing.T) { +// TestChoice_TwoUnionsNoInstanceSatisfiesLowerAlikeWhereverWritten holds that a +// oneOf and an anyOf no instance of the body satisfies together lower alike +// beside the body, beside its allOf, on one entry and on two, in either order +// of the entries, the keywords and the components, at every version and +// position, over an inline body and a $ref: the position is the Model the body +// gives, keeping both unions as degraded_lowering, and draws one warning that +// no instance satisfies it, whichever union is chosen (GitHub #2011). +func TestChoice_TwoUnionsNoInstanceSatisfiesLowerAlikeWhereverWritten(t *testing.T) { t.Parallel() for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { for _, site := range bothKeywordsSites { @@ -63,8 +63,8 @@ func TestElection_TwoUnionsNoInstanceSatisfiesLowerAlikeWhereverWritten(t *testi func checkUnsatisfiedPair(t *testing.T, site bothKeywordsSite, version string, spellings map[string]string) { t.Helper() doc, diags := compileSpellingsAlike(t, site, version, spellings) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: string(site.at), - contains: []string{"so no instance satisfies this schema"}}}) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: string(site.at), + contains: []string{"no value satisfies", "; lowered as "}}}) model, ok := kindNode(t, doc, entryPositionID(site.at)).(*ir.Model) require.True(t, ok, "the position is the Model its body gives") assert.Equal(t, map[string]ir.UnmodeledReason{ @@ -72,7 +72,7 @@ func checkUnsatisfiedPair(t *testing.T, site bothKeywordsSite, version string, s }, keptOn(model), "it keeps both unions") } -// infosOnce is the findings of an election view with each info listed once. +// infosOnce is the findings of an choice view with each info listed once. func infosOnce(findings any) []string { list, _ := findings.([]string) var out []string @@ -84,12 +84,12 @@ func infosOnce(findings any) []string { return out } -// TestElection_AUnionOfNullAloneBesideObjectsLowersAsTheOtherUnsatisfiedPairs +// TestChoice_AUnionOfNullAloneBesideObjectsLowersAsTheOtherUnsatisfiedPairs // holds that a union of null alone and a union of objects over an object body, // which admits no null, lower as the unsatisfied pairs do wherever written: // the Model the body gives, keeping both unions, with one warning, whichever // keyword writes the null (GitHub #2011). -func TestElection_AUnionOfNullAloneBesideObjectsLowersAsTheOtherUnsatisfiedPairs(t *testing.T) { +func TestChoice_AUnionOfNullAloneBesideObjectsLowersAsTheOtherUnsatisfiedPairs(t *testing.T) { t.Parallel() const null = "[{type: 'null'}]" pairs := []struct{ name, oneOf, anyOf string }{ diff --git a/compilers/openapi/e2e/union_passed_over_kept_test.go b/compilers/openapi/e2e/union_passed_over_kept_test.go index d2aed5720..9adae4445 100644 --- a/compilers/openapi/e2e/union_passed_over_kept_test.go +++ b/compilers/openapi/e2e/union_passed_over_kept_test.go @@ -48,14 +48,14 @@ func unmodeledValues(t *testing.T, raw []byte) []string { return out } -// TestElection_AUnionPassedOverThatSaysNothingIsKeptEverywhere holds that a +// TestChoice_AUnionPassedOverThatSaysNothingIsKeptEverywhere holds that a // oneOf or an anyOf whose branches declare nothing, passed over for the other // declaring shape, is kept wherever the two are written, beside a string, a // string or null, an array and an object, on one schema, beside an allOf, on // one entry or two, in either order: a refinement folds neither union of a // pair into its principal as said, as one schema writing both keeps the one it // passes over (GitHub #2011). -func TestElection_AUnionPassedOverThatSaysNothingIsKeptEverywhere(t *testing.T) { +func TestChoice_AUnionPassedOverThatSaysNothingIsKeptEverywhere(t *testing.T) { t.Parallel() const shaped = "[{type: object, properties: {x: {type: string}}}, {type: string}]" bodies := []string{"{type: string}", "{type: [string, 'null']}", "{type: array, items: {type: string}}", diff --git a/compilers/openapi/e2e/union_typed_value_set_test.go b/compilers/openapi/e2e/union_typed_value_set_test.go new file mode 100644 index 000000000..20bf83369 --- /dev/null +++ b/compilers/openapi/e2e/union_typed_value_set_test.go @@ -0,0 +1,509 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers" + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// typedSetSpellings writes the value set set beside the union union in the +// spellings a value set and a union of typed branches have: flat beside a +// string type, bare, beside an allOf of a $ref to a string, and on an entry of +// that allOf. They are spellings of a body, a string written three ways, where +// openapitest.Spellings writes one body in many places, and each is held to the +// result its row says, not to the first, so they stay apart from it. +func typedSetSpellings(set, union string) map[string]string { + return map[string]string{ + "Flat": "{type: string, " + set + ", " + union + "}", + "Bare": "{" + set + ", " + union + "}", + "Beside": "{allOf: [{$ref: '#/components/schemas/T'}], " + set + ", " + union + "}", + "Entry": "{allOf: [{$ref: '#/components/schemas/T'}, {" + set + ", " + union + "}]}", + } +} + +// typedSetEntry is the pointer below a spelling of typedSetSpellings at which +// its value set and its union are written. +func typedSetEntry(spelling string) string { + if spelling == "Entry" { + return "/allOf/1" + } + return "" +} + +// typedSetRows writes each named value set and union in every spelling +// typedSetSpellings gives. +func typedSetRows(cases map[string][2]string) []openapitest.Row { + rows := make([]openapitest.Row, 0, len(cases)) + for _, name := range slices.Sorted(maps.Keys(cases)) { + rows = append(rows, openapitest.Row{Name: name, Spellings: typedSetSpellings(cases[name][0], cases[name][1])}) + } + return rows +} + +// stringMembers is each of values as an Enum member's string value prints. +func stringMembers(values ...string) []string { + out := make([]string, 0, len(values)) + for _, v := range values { + out = append(out, fmt.Sprint(ir.Value{Kind: ir.ValueString, String: v})) + } + return out +} + +// TestUnionBesideValueSet_TypedBranchesEveryMemberSatisfiesSayNothing holds +// that a oneOf or an anyOf of typed branches beside an enum, every member of +// which satisfies it, says nothing, in every spelling, at 3.0 and 3.1, at a +// component and at a property: the position is the enum as written, and the +// union is neither kept nor reported, nor are its branches no member is. +// Under an anyOf, a member two branches admit satisfies it. +func TestUnionBesideValueSet_TypedBranchesEveryMemberSatisfiesSayNothing(t *testing.T) { + t.Parallel() + rows := typedSetRows(map[string][2]string{ + "OneOf": {"enum: [a, b]", "oneOf: [{type: string}, {type: integer}]"}, + "AnyOf": {"enum: [a, b]", "anyOf: [{type: string}, {type: integer}]"}, + "AnyOfTwice": {"enum: [a, b]", "anyOf: [{type: string}, {enum: [a, c]}]"}, + "OneOfByBounds": {"enum: [a, bb]", "oneOf: [{maxLength: 1, type: string}, {minLength: 2, type: string}]"}, + }) + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, openapi.Options{}, version, []string{"T: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + for _, row := range rows { + want := stringMembers("a", "b") + if row.Name == "OneOfByBounds" { + want = stringMembers("a", "bb") + } + for spelling := range row.Spellings { + for _, position := range []string{"component", "property"} { + at := readings[false][row.Name][spelling][position] + label := fmt.Sprintf("%s %s at the %s", row.Name, spelling, position) + require.Equal(t, ir.KindEnum, at.View.Kind, label) + assert.Equal(t, want, at.View.Members, label) + assert.NotContains(t, at.View.Kept, "openapi:oneOf", label) + assert.NotContains(t, at.View.Kept, "openapi:anyOf", label) + assert.NotContains(t, at.View.Kept, "openapi:enum", label) + assert.NotContains(t, at.Findings, "warning "+diag.UnsatisfiableSchema, label) + } + } + } + }) + } +} + +// TestUnionBesideValueSet_ABranchSayingMoreThanTheSetIsKept holds that a +// union every member of the enum beside it satisfies is kept where a branch +// writes what the set does not say, a note, an example or an extension, in +// every spelling at 3.0 and 3.1: the position is the enum as written, keeping +// the union once and not the enum, and no member is reported. +func TestUnionBesideValueSet_ABranchSayingMoreThanTheSetIsKept(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.0.3", "3.1.0"} { + example := "example: zz" + if version == "3.1.0" { + example = "examples: [zz]" + } + rows := typedSetRows(map[string][2]string{ + "Description": {"enum: [a, b]", "oneOf: [{type: string, description: d}, {type: integer}]"}, + "Extension": {"enum: [a, b]", "anyOf: [{type: string}, {type: integer, x-bar: 2}]"}, + "Example": {"enum: [a, b]", "oneOf: [{type: string, " + example + "}, {type: integer}]"}, + }) + t.Run(version, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, openapi.Options{}, version, []string{"T: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + diags := compileTypedSetRows(t, version, rows) + for _, row := range rows { + keyword := "openapi:oneOf" + if row.Name == "Extension" { + keyword = "openapi:anyOf" + } + for spelling := range row.Spellings { + at := readings[false][row.Name][spelling]["component"] + label := row.Name + " " + spelling + " at " + version + require.Equal(t, ir.KindEnum, at.View.Kind, label) + assert.Equal(t, stringMembers("a", "b"), at.View.Members, label) + assert.Contains(t, at.View.Kept, keyword, label) + assert.NotContains(t, at.View.Kept, "openapi:enum", label) + assert.Empty(t, setReportsBeneath(diags, "/components/schemas/"+row.Name+"_"+spelling), label) + } + } + }) + } +} + +// TestUnionBesideValueSet_AConstSatisfyingTheUnionSaysNothing holds the same +// of a const, at 3.1, which defines it: the position is its Literal, keeping +// nothing. +func TestUnionBesideValueSet_AConstSatisfyingTheUnionSaysNothing(t *testing.T) { + t.Parallel() + rows := typedSetRows(map[string][2]string{ + "OneOf": {"const: a", "oneOf: [{type: string}, {type: integer}]"}, + "AnyOf": {"const: a", "anyOf: [{type: string}, {const: a}]"}, + }) + readings := compileSpellingRowsWith(t, openapi.Options{}, "3.1.0", []string{"T: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + for _, row := range rows { + for spelling := range row.Spellings { + at := readings[false][row.Name][spelling]["component"] + label := row.Name + " " + spelling + require.Equal(t, ir.KindLiteral, at.View.Kind, label) + assert.NotContains(t, at.View.Kept, "openapi:oneOf", label) + assert.NotContains(t, at.View.Kept, "openapi:anyOf", label) + assert.NotContains(t, at.Findings, "warning "+diag.UnsatisfiableSchema, label) + } + } +} + +// TestUnionBesideValueSet_TypedBranchesRefusingSomeMembersNarrowTheEnum holds +// that a union of typed branches some members of the enum beside it satisfy +// and others do not narrows the position to the Enum of those that do, in +// every spelling, at 3.0 and 3.1, at a component and at a property: the enum +// is kept as validation_only, holding the members refused, and the union as +// the rule keeps one beside a body that is no object, and the refused member +// draws one warning at the position, none where it is written. A oneOf +// refuses a member two of its branches admit, which its anyOf twin admits. +func TestUnionBesideValueSet_TypedBranchesRefusingSomeMembersNarrowTheEnum(t *testing.T) { + t.Parallel() + cases := map[string]struct { + set, union string + members []string + kept ir.UnmodeledReason + refused string + }{ + "NoBranch": {"enum: [a, b]", "oneOf: [{enum: [a]}, {type: integer}]", stringMembers("a"), ir.ReasonDegradedLowering, `"b"`}, + "NoBranchAny": {"enum: [a, b]", "anyOf: [{enum: [a]}, {type: integer}]", stringMembers("a"), ir.ReasonDegradedLowering, `"b"`}, + "TwoBranches": {"enum: [a, b]", "oneOf: [{type: string}, {enum: [a]}]", stringMembers("b"), ir.ReasonDegradedLowering, `"a"`}, + "Bounds": {"enum: [a, bb, ccc]", "oneOf: [{type: string, maxLength: 1}, {type: string, minLength: 3}]", + stringMembers("a", "ccc"), ir.ReasonValidationOnly, `"bb"`}, + } + rows := make([]openapitest.Row, 0, len(cases)) + for _, name := range slices.Sorted(maps.Keys(cases)) { + rows = append(rows, openapitest.Row{Name: name, Spellings: typedSetSpellings(cases[name].set, cases[name].union)}) + } + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, openapi.Options{}, version, []string{"T: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + diags := compileTypedSetRows(t, version, rows) + for _, row := range rows { + expected := cases[row.Name] + keyword, _, _ := strings.Cut(expected.union, ":") + for spelling := range row.Spellings { + for position, prefix := range map[string]string{ + "component": "/components/schemas/" + row.Name + "_" + spelling, + "property": "/components/schemas/Props/properties/" + row.Name + "_" + spelling, + } { + at := readings[false][row.Name][spelling][position] + label := fmt.Sprintf("%s %s at the %s", row.Name, spelling, position) + require.Equal(t, ir.KindEnum, at.View.Kind, label) + assert.Equal(t, expected.members, at.View.Members, label) + assert.Equal(t, expected.kept, at.View.Kept["openapi:"+keyword], label) + assert.Equal(t, ir.ReasonValidationOnly, at.View.Kept["openapi:enum"], label) + requireOneReportNaming(t, diags, prefix, label, "the "+keyword+" beside it", expected.refused) + } + } + } + }) + } +} + +// TestUnionBesideValueSet_AMemberTheReaderCannotJudgeLeavesTheUnion holds +// that a union beside an enum refusing no member, some of which the value +// reader cannot judge against it, by a pattern outside the subset it reads, a +// format, a branch writing a +// keyword it does not read, a $ref beside a keyword, or one whose kinds the +// kind-inference policy read, lowers as it does with no judgment, in every +// spelling: no member is dropped or reported, and the node holds or keeps +// both the union and the enum, an Enum holding every member. +func TestUnionBesideValueSet_AMemberTheReaderCannotJudgeLeavesTheUnion(t *testing.T) { + t.Parallel() + rows := typedSetRows(map[string][2]string{ + "Pattern": {"enum: [a, b]", "oneOf: [{pattern: '^(?=a)'}, {type: integer}]"}, + "Unread": {"enum: [a, b]", "oneOf: [{type: string, not: {const: b}}, {type: integer}]"}, + "Inferred": {"enum: [a, b]", "oneOf: [{properties: {p: {type: string}}}, {type: string}]"}, + "Format": {"enum: [a, b]", "anyOf: [{type: string, format: uuid}, {type: integer}]"}, + "Sibling": {"enum: [a, b]", "anyOf: [{$ref: '#/components/schemas/Int', maxLength: 1}, {type: string, maxLength: 0}]"}, + }) + readings := compileSpellingRowsWith(t, openapi.Options{}, "3.1.0", []string{"T: {type: string}", "Int: {type: integer}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + diags := compileTypedSetRows(t, "3.1.0", rows) + for _, row := range rows { + keyword := "openapi:oneOf" + if row.Name == "Format" || row.Name == "Sibling" { + keyword = "openapi:anyOf" + } + for spelling := range row.Spellings { + at := readings[false][row.Name][spelling]["component"] + label := row.Name + " " + spelling + _, unionKept := at.View.Kept[keyword] + _, enumKept := at.View.Kept["openapi:enum"] + assert.True(t, unionKept || at.View.Kind == ir.KindUnion, "%s holds or keeps the union", label) + assert.True(t, enumKept || at.View.Kind == ir.KindEnum, "%s holds or keeps the enum", label) + if at.View.Kind == ir.KindEnum { + assert.Equal(t, stringMembers("a", "b"), at.View.Members, label) + } + for _, member := range []string{"/enum/0", "/enum/1"} { + assert.Zero(t, unsatisfiableAt(diags, + "/components/schemas/"+row.Name+"_"+spelling+typedSetEntry(spelling)+member), "%s %s", label, member) + } + } + } +} + +// TestUnionBesideValueSet_EachBranchIsCountedThreeWays holds that a member is +// judged branch by branch, each saying yes, no or unknown, in every spelling +// at 3.0 and 3.1: a oneOf refuses a member two branches admit or every one +// refuses, and admits one exactly one admits beside no unknown; an anyOf +// admits a member one admits and refuses one every one refuses. A member left +// unknown stays in the Enum, and the refused one draws one warning at the +// position. +func TestUnionBesideValueSet_EachBranchIsCountedThreeWays(t *testing.T) { + t.Parallel() + cases := map[string]struct { + set, union string + members []string + refused []string + }{ + "OneOfTwiceBesideUnknown": {"enum: [ab, abcd]", "oneOf: [{maxLength: 3}, {maxLength: 4}, {pattern: '^(?=a)'}]", + stringMembers("abcd"), []string{`"ab"`}}, + "OneOfNoneOrOnce": {"enum: [abcd, abcde, abcdef]", "oneOf: [{maxLength: 3}, {maxLength: 4}, {minLength: 6, pattern: '^a'}]", + stringMembers("abcd", "abcdef"), []string{`"abcde"`}}, + "AnyOf": {"enum: [a, ab, abc]", "anyOf: [{maxLength: 1}, {minLength: 3, pattern: '^a'}]", + stringMembers("a", "abc"), []string{`"ab"`}}, + } + rows := make([]openapitest.Row, 0, len(cases)) + for _, name := range slices.Sorted(maps.Keys(cases)) { + rows = append(rows, openapitest.Row{Name: name, Spellings: typedSetSpellings(cases[name].set, cases[name].union)}) + } + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, openapi.Options{}, version, []string{"T: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + diags := compileTypedSetRows(t, version, rows) + for _, row := range rows { + expected := cases[row.Name] + for spelling := range row.Spellings { + at := readings[false][row.Name][spelling]["component"] + prefix := "/components/schemas/" + row.Name + "_" + spelling + label := row.Name + " " + spelling + " at " + version + require.Equal(t, ir.KindEnum, at.View.Kind, label) + assert.Equal(t, expected.members, at.View.Members, label) + assert.Equal(t, ir.ReasonValidationOnly, at.View.Kept["openapi:enum"], label) + keyword, _, _ := strings.Cut(expected.union, ":") + requireOneReportNaming(t, diags, prefix, label, "the "+keyword+" beside it", expected.refused...) + } + } + }) + } +} + +// TestUnionBesideValueSet_TypedBranchesRefusingEveryMemberLeaveNoValue holds +// that a union of typed branches refusing every member of the enum beside it +// narrows the position to the closed Enum with no member, in every spelling, +// at 3.0 and 3.1, at a component and at a property: the enum is kept as +// validation_only, holding every member, the union as the rule keeps one +// beside a body that is no object, and one warning at the position names each +// member and the union, none drawn where a member is written. A oneOf refuses +// members two of its branches admit. +func TestUnionBesideValueSet_TypedBranchesRefusingEveryMemberLeaveNoValue(t *testing.T) { + t.Parallel() + cases := map[string]struct { + set, union string + kept ir.UnmodeledReason + named []string + }{ + "NoBranch": {"enum: [a, b]", "oneOf: [{enum: [c]}, {type: integer}]", ir.ReasonDegradedLowering, []string{`"a"`, `"b"`}}, + "NoBranchAny": {"enum: [a, b]", "anyOf: [{enum: [c]}, {type: integer}]", ir.ReasonDegradedLowering, []string{`"a"`, `"b"`}}, + "TwoBranches": {"enum: [a, b]", "oneOf: [{type: string}, {maxLength: 3}]", ir.ReasonValidationOnly, []string{`"a"`, `"b"`}}, + "Bounds": {"enum: [aaaa, bbbb]", "anyOf: [{type: string, maxLength: 3}, {type: integer}]", ir.ReasonDegradedLowering, + []string{`"aaaa"`, `"bbbb"`}}, + } + rows := make([]openapitest.Row, 0, len(cases)) + for _, name := range slices.Sorted(maps.Keys(cases)) { + rows = append(rows, openapitest.Row{Name: name, Spellings: typedSetSpellings(cases[name].set, cases[name].union)}) + } + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version, func(t *testing.T) { + t.Parallel() + readings := compileSpellingRowsWith(t, openapi.Options{}, version, []string{"T: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + diags := compileTypedSetRows(t, version, rows) + for _, row := range rows { + expected := cases[row.Name] + keyword, _, _ := strings.Cut(expected.union, ":") + for spelling := range row.Spellings { + for position, prefix := range map[string]string{ + "component": "/components/schemas/" + row.Name + "_" + spelling, + "property": "/components/schemas/Props/properties/" + row.Name + "_" + spelling, + } { + at := readings[false][row.Name][spelling][position] + label := fmt.Sprintf("%s %s at the %s", row.Name, spelling, position) + require.Equal(t, ir.KindEnum, at.View.Kind, label) + assert.Empty(t, at.View.Members, label) + assert.True(t, at.View.Closed, label) + assert.Equal(t, expected.kept, at.View.Kept["openapi:"+keyword], label) + assert.Equal(t, ir.ReasonValidationOnly, at.View.Kept["openapi:enum"], label) + requireOneReportNaming(t, diags, prefix, label, "the "+keyword+" beside it", expected.named...) + } + } + } + }) + } +} + +// TestUnionBesideValueSet_TypedBranchesRefusingTheConstLeaveNoValue holds the +// same of a const, at 3.1, which defines it: the position is the closed Enum +// with no member, keeping the const as validation_only, and one warning at the +// position names the const's value and the union, none drawn at the const. +func TestUnionBesideValueSet_TypedBranchesRefusingTheConstLeaveNoValue(t *testing.T) { + t.Parallel() + cases := map[string][2]string{ + "OneOf": {"const: a", "oneOf: [{type: string, minLength: 2}, {type: integer}]"}, + "AnyOf": {"const: a", "anyOf: [{type: string, minLength: 2}, {type: integer}]"}, + } + rows := typedSetRows(cases) + readings := compileSpellingRowsWith(t, openapi.Options{}, "3.1.0", []string{"T: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "") + diags := compileTypedSetRows(t, "3.1.0", rows) + for _, row := range rows { + keyword, _, _ := strings.Cut(cases[row.Name][1], ":") + for spelling := range row.Spellings { + at := readings[false][row.Name][spelling]["component"] + label := row.Name + " " + spelling + require.Equal(t, ir.KindEnum, at.View.Kind, label) + assert.Empty(t, at.View.Members, label) + assert.Equal(t, ir.ReasonValidationOnly, at.View.Kept["openapi:const"], label) + assert.Equal(t, ir.ReasonDegradedLowering, at.View.Kept["openapi:"+keyword], label) + prefix := "/components/schemas/" + row.Name + "_" + spelling + requireOneReportNaming(t, diags, prefix, label, "the "+keyword+" beside it", `"a"`) + } + } +} + +// TestUnionBesideValueSet_AMixedSetIsJudgedMemberByMember holds that the +// members of an enum of several value types are judged against a oneOf or an +// anyOf of typed branches beside it, in every placement openapitest.Spellings +// gives the enum and the union, each held to the flat one: the position is +// the Union of the literals of those it does not refuse, a member the reader +// cannot judge among them, or, where it refuses every one, the untyped closed +// Enum with no member; either way one warning at the position names the +// refused members. The enum and the union are kept. +func TestUnionBesideValueSet_AMixedSetIsJudgedMemberByMember(t *testing.T) { + t.Parallel() + stringAndOne := []string{fmt.Sprint(ir.Value{Kind: ir.ValueString, String: "a"}), fmt.Sprint(ir.Value{Kind: ir.ValueNumber, Number: "1"})} + cases := map[string]struct { + set, branches string + kept []string + refused []string + }{ + "OneRefused": {"enum: [a, 1, true]", "[{type: string}, {type: integer}]", stringAndOne, []string{"true"}}, + "EveryRefused": {"enum: [a, 1]", "[{type: string, minLength: 2}, {type: integer, minimum: 5}]", nil, []string{`"a"`, "1"}}, + "Unknown": {"enum: [a, 1, true]", "[{type: string, pattern: '^(?=a)'}, {type: integer}]", stringAndOne, []string{"true"}}, + } + written := map[string][2]string{} + for name, row := range cases { + for _, keyword := range []string{"oneOf", "anyOf"} { + written[name+"_"+keyword] = [2]string{row.set, keyword + ": " + row.branches} + } + } + rows := openapitest.Rows(written) + readings := compileSpellingRowsWith(t, openapi.Options{}, "3.1.0", nil, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + diags := compileTypedSetRows(t, "3.1.0", rows) + for _, row := range rows { + name, keyword, _ := strings.Cut(row.Name, "_") + expected := cases[name] + for spelling := range row.Spellings { + at := readings[false][row.Name][spelling]["component"] + label := row.Name + " " + spelling + assert.Equal(t, ir.ReasonValidationOnly, at.View.Kept["openapi:enum"], label) + assert.Contains(t, at.View.Kept, "openapi:"+keyword, label) + if expected.kept == nil { + require.Equal(t, ir.KindEnum, at.View.Kind, label) + assert.Empty(t, at.View.Members, label) + assert.True(t, at.View.Closed, label) + assert.Equal(t, ir.PrimitiveAny, at.View.ValueType, label) + } else { + require.Equal(t, ir.KindUnion, at.View.Kind, label) + assert.Equal(t, expected.kept, variantMembers(at.View), label) + } + requireOneReportNaming(t, diags, "/components/schemas/"+row.Name+"_"+spelling, label, "the "+keyword+" beside it", + expected.refused...) + } + } +} + +// variantMembers is the value of each Literal the Union view holds, in order. +func variantMembers(view bodyView) []string { + var out []string + for _, variant := range view.Variants { + out = append(out, variant.Members...) + } + return out +} + +// setReportsBeneath is the unsatisfiable-schema warnings at or beneath +// pointer that report members of a value set a union refuses. +func setReportsBeneath(diags []ir.Diagnostic, pointer string) []ir.Diagnostic { + var out []ir.Diagnostic + for _, diagnostic := range diags { + at := string(diagnostic.Provenance.Pointer) + if diagnostic.Code == diag.UnsatisfiableSchema && (at == pointer || strings.HasPrefix(at, pointer+"/")) && + strings.Contains(diagnostic.Message, "value set") { + out = append(out, diagnostic) + } + } + return out +} + +// requireOneReportNaming holds the reports of a value set's refused members +// at or beneath pointer to one, at pointer itself, whose message names union, +// the union refusing the set, and each of members, however the spelling +// placed the set and the union. +func requireOneReportNaming(t *testing.T, diags []ir.Diagnostic, pointer, label, union string, members ...string) { + t.Helper() + reports := setReportsBeneath(diags, pointer) + require.Len(t, reports, 1, "%s draws one report", label) + assert.Equal(t, pointer, string(reports[0].Provenance.Pointer), "%s reports at the position", label) + assert.Contains(t, reports[0].Message, union, label) + for _, member := range members { + assert.Contains(t, reports[0].Message, member+" satisfies", label) + } +} + +// compileTypedSetRows compiles rows at version beside a string T, as +// compileSpellingRowsWith writes them, and returns the diagnostics. +func compileTypedSetRows(t *testing.T, version string, rows []openapitest.Row) []ir.Diagnostic { + t.Helper() + schemas := []string{"T: {type: string}", "Int: {type: integer}"} + var properties []string + for _, row := range rows { + for _, spelling := range slices.Sorted(maps.Keys(row.Spellings)) { + schemas = append(schemas, row.Name+"_"+spelling+": "+row.Spellings[spelling]) + properties = append(properties, row.Name+"_"+spelling+": "+row.Spellings[spelling]) + } + } + schemas = append(schemas, "Props: {type: object, properties: {"+strings.Join(properties, ", ")+"}}") + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{ + {Path: "typed.yaml", Data: []byte(admissionSpec(version, "", schemas...))}, + }, compilers.Options{}) + require.NoError(t, err) + requireVerifies(t, doc, diags) + return diags +} diff --git a/compilers/openapi/e2e/union_value_set_entry_test.go b/compilers/openapi/e2e/union_value_set_entry_test.go new file mode 100644 index 000000000..4e1795145 --- /dev/null +++ b/compilers/openapi/e2e/union_value_set_entry_test.go @@ -0,0 +1,53 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "testing" + + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" +) + +// TestUnionBesideBody_AValueSetBesideThePositionsUnionLowersAsFlat holds that +// a value set, type, format or content keyword beside the union the position +// is lowers as written flat in every spelling, at 3.0 and 3.1, at a component +// and a property, in either order of the components: read by the closed +// empty Enum of a union leaving null alone, kept by the Union of formats, and +// kept beside a union collapsing to the nullable reference to its one +// non-null branch where that reference has no home for it +// (docs/compilers/openapi.md#allof-inline-residue). +func TestUnionBesideBody_AValueSetBesideThePositionsUnionLowersAsFlat(t *testing.T) { + t.Parallel() + const kstr = "{$ref: '#/components/schemas/Kstr'}" + cases := map[string]map[string][2]string{ + "3.0.3": { + "NullBody": {"type: object, enum: [null], nullable: true", "anyOf: [{type: string}, {type: integer}]"}, + "NullBranch": {"type: object, enum: [null], nullable: true", "oneOf: [{type: object, enum: [null], nullable: true}, {type: integer}]"}, + "NullableSet": {"type: string, enum: [a], nullable: true", "oneOf: [{type: integer}, {type: boolean}]"}, + "SetOfFormats": {"type: string, enum: [a, b], nullable: true", "oneOf: [{format: uuid}, {format: date}]"}, + }, + "3.1.0": { + "NullType": {"type: 'null'", "anyOf: [{type: string}, {type: 'null'}]"}, + "NullEnum": {"enum: [null]", "anyOf: [{type: string}, {type: 'null'}]"}, + "NullConst": {"const: null", "anyOf: [{type: string}, {const: null}]"}, + "SetOfFormats": {"type: string, enum: [a, b], maxLength: 3", "oneOf: [{format: uuid}, {format: date}]"}, + "CollapsedSet": {"type: [string, 'null'], enum: [a, null]", "anyOf: [{type: 'null'}, {format: uuid}]"}, + "CollapsedType": {"description: d, type: [string, 'null'], minLength: 1", "anyOf: [{type: 'null'}, {format: uuid}]"}, + "CollapsedFormat": {"type: [string, 'null'], format: email", "anyOf: [{type: 'null'}, " + kstr + "]"}, + "CollapsedItems": {"type: [string, 'null'], items: {type: string}", "anyOf: [{type: 'null'}, " + kstr + "]"}, + "TypedSet": {"type: string, enum: [a, b]", "oneOf: [{type: string, format: uuid}, {type: string, format: email}]"}, + "TypedContent": {"type: string, contentMediaType: application/zip", "oneOf: [{type: string, format: uuid}, {type: string, format: email}]"}, + "SetSaysUnion": {"type: string, format: email, enum: [a]", "anyOf: [{type: 'null'}, " + kstr + "]"}, + }, + } + for version, written := range cases { + t.Run(version, func(t *testing.T) { + t.Parallel() + rows := openapitest.Rows(written) + readings := compileSpellingRowsWith(t, openapi.Options{}, version, []string{"Kstr: {type: string}"}, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + }) + } +} diff --git a/compilers/openapi/e2e/unknownkeys_table_test.go b/compilers/openapi/e2e/unknownkeys_table_test.go index 871d21898..4f473f5df 100644 --- a/compilers/openapi/e2e/unknownkeys_table_test.go +++ b/compilers/openapi/e2e/unknownkeys_table_test.go @@ -20,7 +20,6 @@ import ( "github.com/dexpace/morphic/compilers" "github.com/dexpace/morphic/compilers/openapi" - "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/engine/reader" "github.com/dexpace/morphic/ir" @@ -575,37 +574,3 @@ func TestUnknownKeys_EveryKeptKeyIsReported(t *testing.T) { } require.Positive(t, swept, "the sweep compiled no OpenAPI spec") } - -// TestKeywordLists_AMutatedCopyChangesNoReader is #1316's reader-side half: -// the list a caller collects from the seam is its own, so overwriting it -// leaves the lowering still keeping each dialect keyword and the census still -// leaving each decided keyword alone. -func TestKeywordLists_AMutatedCopyChangesNoReader(t *testing.T) { - t.Parallel() - mine := slices.Collect(annotation.DialectKeywords()) - require.NotEmpty(t, mine) - for i := range mine { - mine[i] = "x-overwritten" - } - - doc, diags := compileAnnotationSpec(t, "dialect", `openapi: 3.1.0 -info: {title: T, version: "1"} -paths: {} -components: - schemas: - A: - $id: 'urn:example:a' - $schema: 'https://json-schema.org/draft/2020-12/schema' - $vocabulary: {'https://json-schema.org/draft/2020-12/vocab/core': true} - $comment: not for end users - type: string -`) - requireNoErrorDiagnostics(t, diags) - got := typeByName(doc, "A").Common().Unmodeled - for _, keyword := range []string{"$id", "$schema", "$vocabulary"} { - entry := unmodeledEntry(t, got, "openapi:"+keyword) - assert.Equal(t, ir.ReasonOutOfScope, entry.Reason, keyword) - } - assert.NotContains(t, got, "openapi:$comment", "a decided keyword is left to its own reader") - assert.Len(t, slices.Collect(annotation.DialectKeywords()), 3) -} diff --git a/compilers/openapi/e2e/unknownkeys_test.go b/compilers/openapi/e2e/unknownkeys_test.go index 1c9620425..27dbddf7e 100644 --- a/compilers/openapi/e2e/unknownkeys_test.go +++ b/compilers/openapi/e2e/unknownkeys_test.go @@ -297,9 +297,8 @@ components: // TestUnknownKeys_SubObjectKeyMergedPastTheBoundIsReported holds the census of // a schema's xml, discriminator and externalDocs objects, and of the -// discriminator an allOf entry writes for its union, distributed over a body -// or standing alone at the position, to every key their models name no field -// for, as +// discriminator an allOf entry writes for its union, distributed over a body or +// alone at the position, to every key their models name no field for, as // annotation.TestUnknownKeywordsIn_AKeywordMergedPastTheBoundIsUnreachable // holds the schema's own: one merged in through `<<` from past // nodeview.MergeDepthLimit, which the compiler reads no pair for, is reported @@ -342,8 +341,8 @@ components: // TestUnknownKeys_ExtensionMergedPastTheBoundIsKept holds the extensions a // schema, its xml, discriminator and externalDocs objects, and the -// discriminator an allOf entry writes for its union, distributed over a body -// or standing alone at the position, merge in through `<<` from past +// discriminator an allOf entry writes for its union, distributed over a body or +// alone at the position, merge in through `<<` from past // nodeview.MergeDepthLimit to what the parser's model holds: each is kept on // the node holding the object, as one written in place is, though the compiler // reads no pair for it. diff --git a/compilers/openapi/e2e/unpreservable_test.go b/compilers/openapi/e2e/unpreservable_test.go index 60409e281..377a50de9 100644 --- a/compilers/openapi/e2e/unpreservable_test.go +++ b/compilers/openapi/e2e/unpreservable_test.go @@ -5,8 +5,12 @@ package e2e_test import ( "encoding/json/jsontext" + "slices" + "strings" "testing" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -27,6 +31,12 @@ import ( // positions. const unpreservableValue = ".nan" +// unpreservableKey is a member no OpenAPI object or JSON Schema dialect +// defines, holding unpreservableValue. It is no vendor extension, since one of +// those whose value no JSON holds is left out wherever it is kept, and what +// held it kept without it (TestUnpreservable_AnExtensionIsLeftOutWhereverItIsKept). +const unpreservableKey = "foo: " + unpreservableValue + // TestUnpreservable_AnnouncementNeverOutrunsTheEntry is the regression test for // GitHub #144: a diagnostic stating a construct was "kept verbatim under // Unmodeled" must not be emitted when nothing was written. @@ -50,19 +60,21 @@ func TestUnpreservable_AnnouncementNeverOutrunsTheEntry(t *testing.T) { at string }{ { - name: "unmerged allOf entry", + // An entry with no cause to be kept whole keeps keyword by keyword, + // so the value is refused at its keyword. + name: "keyword of an allOf entry", spec: openapitest.ComponentSpec(" M:\n allOf:\n" + - " - {additionalProperties: false, x-t: " + unpreservableValue + "}\n"), - at: "/components/schemas/M/allOf/0", + " - {" + unpreservableKey + "}\n"), + at: "/components/schemas/M/allOf/0/foo", }, { name: "response links", spec: openapitest.PathsSpec(" /x:\n get:\n responses:\n \"200\":\n" + - " description: ok\n links: {l: {operationId: g, x-t: " + unpreservableValue + "}}\n"), + " description: ok\n links: {l: {operationId: g, parameters: {p: " + unpreservableValue + "}}}\n"), at: "/paths/~1x/get/responses/200/links/l", }, { - name: "residue keyword on a declaration", + name: "use-bound keyword on a declaration", spec: openapitest.ComponentSpec(" R:\n type: object\n" + " default: " + unpreservableValue + "\n" + " properties: {a: {type: string}}\n"), @@ -76,7 +88,7 @@ func TestUnpreservable_AnnouncementNeverOutrunsTheEntry(t *testing.T) { assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, tc.at), "the case must reach the site it is named for: %+v", diags) - assert.Empty(t, openapitest.PreservationClaims(diags), + assert.Empty(t, openapitest.MessagesSayingKept(diags), "nothing was written under Unmodeled, so nothing may announce that it was") }) } @@ -99,12 +111,12 @@ func TestUnpreservable_SchemaKeywordSites(t *testing.T) { }{ { name: "contains combination", - body: " type: array\n contains: {x-t: " + unpreservableValue + "}\n", + body: " type: array\n contains: {" + unpreservableKey + "}\n", at: "/components/schemas/S", }, { name: "unevaluated combination", - body: " type: object\n unevaluatedProperties: {x-t: " + unpreservableValue + "}\n", + body: " type: object\n unevaluatedProperties: {" + unpreservableKey + "}\n", at: "/components/schemas/S", }, { @@ -112,13 +124,13 @@ func TestUnpreservable_SchemaKeywordSites(t *testing.T) { // legitimately preserved construct to account for — the sibling is kept // verbatim when it converts, and a claim about it would be sound. name: "union beside a structural sibling", - body: " items: {type: string, x-t: " + unpreservableValue + "}\n" + - " oneOf: [{type: string, x-t: " + unpreservableValue + "}, {type: integer}]\n", + body: " items: {type: string, " + unpreservableKey + "}\n" + + " oneOf: [{type: string, " + unpreservableKey + "}, {type: integer}]\n", at: "/components/schemas/S/oneOf", }, { name: "applicator with no home on its node", - body: " enum: [a]\n properties: {p: {type: integer, x-t: " + unpreservableValue + "}}\n", + body: " enum: [a]\n properties: {p: {type: integer, " + unpreservableKey + "}}\n", at: "/components/schemas/S/properties", }, } @@ -128,7 +140,7 @@ func TestUnpreservable_SchemaKeywordSites(t *testing.T) { _, diags := parseFull(t, openapitest.ComponentSpec(" S:\n"+tc.body)) assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, tc.at), "the case must reach the site it is named for: %+v", diags) - assert.Empty(t, openapitest.PreservationClaims(diags), + assert.Empty(t, openapitest.MessagesSayingKept(diags), "nothing was written under Unmodeled, so nothing may announce that it was") }) } @@ -141,22 +153,74 @@ func TestUnpreservable_SchemaKeywordSites(t *testing.T) { func TestUnpreservable_ReportsTheFailureItself(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(" M:\n allOf:\n" + - " - {additionalProperties: false, x-t: " + unpreservableValue + "}\n") + " - {additionalProperties: false, " + unpreservableKey + "}\n") _, diags := parseFull(t, spec) diagnostic, ok := openapitest.FirstDiag(diags, diag.UnpreservableConstruct) require.True(t, ok, "the unconvertible construct is reported: %+v", diags) assert.Equal(t, ir.SeverityError, diagnostic.Severity, "a construct that reached the IR in no form at all is a losslessness failure, not a degradation") - assert.Equal(t, jsontext.Pointer("/components/schemas/M/allOf/0"), diagnostic.Provenance.Pointer, + assert.Equal(t, jsontext.Pointer("/components/schemas/M/allOf/0/foo"), diagnostic.Provenance.Pointer, "the diagnostic locates the construct that was lost, not its owner") assert.Contains(t, diagnostic.Message, "no form at all") } -// TestUnpreservable_AbsentConstructIsSilent is the control for the two tests -// above: the same code path must stay silent when there is simply nothing to -// preserve, or the new error would fire on every well-formed document. -func TestUnpreservable_AbsentConstructIsSilent(t *testing.T) { +// TestUnpreservable_AnExtensionIsLeftOutWhereverItIsKept holds each site above +// writing a vendor extension whose value no JSON holds, which the extension +// reader leaves out where it is written: wherever an entry or a keyword is +// kept, the extension alone is left out with its own warning, and what held it +// is kept and reported as its twin without the extension is, with no error. +func TestUnpreservable_AnExtensionIsLeftOutWhereverItIsKept(t *testing.T) { + t.Parallel() + const extension = ", x-t: " + unpreservableValue + const schemas = "/components/schemas/S" + for name, tc := range map[string]struct { + spec string + at []string + }{ + "allOf entry": {openapitest.ComponentSpec(" S:\n allOf:\n - {additionalProperties: false" + extension + "}\n"), + []string{schemas + "/allOf/0"}}, + "response links": {openapitest.PathsSpec(" /x:\n get:\n responses:\n \"200\":\n" + + " description: ok\n links: {l: {operationId: g" + extension + "}}\n"), + []string{"/paths/~1x/get/responses/200/links/l"}}, + "contains combination": {openapitest.ComponentSpec(" S:\n type: array\n contains: {type: string" + extension + "}\n"), + []string{schemas + "/contains"}}, + "unevaluated combination": {openapitest.ComponentSpec(" S:\n type: object\n" + + " unevaluatedProperties: {type: string" + extension + "}\n"), []string{schemas + "/unevaluatedProperties"}}, + "if/then/else combination": {openapitest.ComponentSpec(" S:\n type: object\n if: {required: [a]}\n" + + " then: {required: [c]" + extension + "}\n else: {required: [b]}\n"), []string{schemas + "/then"}}, + "union beside a structural sibling": {openapitest.ComponentSpec(" S:\n items: {type: string" + extension + "}\n" + + " oneOf: [{type: string" + extension + "}, {type: integer}]\n"), []string{schemas + "/items", schemas + "/oneOf/0"}}, + "applicator with no home on its node": {openapitest.ComponentSpec(" S:\n enum: [a]\n" + + " properties: {p: {type: integer" + extension + "}}\n"), []string{schemas + "/properties/p"}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + require.Equal(t, len(tc.at), strings.Count(tc.spec, extension), "the spec writes the extension once at each site") + doc, diags := parseFull(t, tc.spec) + twin, twinDiags := parseFull(t, strings.ReplaceAll(tc.spec, extension, "")) + + _, refused := openapitest.FirstDiag(diags, diag.UnpreservableConstruct) + assert.False(t, refused, "nothing is refused: %+v", diags) + for _, at := range tc.at { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, at), + `extension "x-t" could not be serialized`, "the extension reports itself at %s", at) + } + others := slices.DeleteFunc(slices.Clone(diags), func(d ir.Diagnostic) bool { + return d.Severity == ir.SeverityWarning && strings.Contains(d.Message, "could not be serialized") + }) + assert.Empty(t, cmp.Diff(twinDiags, others, cmpopts.EquateEmpty()), "what holds it is reported as without the extension") + assert.Empty(t, cmp.Diff(twin.Types, doc.Types, cmpopts.EquateEmpty()), "what holds it is kept as without the extension") + assert.Empty(t, cmp.Diff(twin.Services, doc.Services, cmpopts.EquateEmpty()), "an operation's keeps too") + }) + } +} + +// TestUnpreservable_AbsentConstructReportsNothing is the control for the two +// tests above: the same code path must report nothing when there is simply +// nothing to preserve, or the new error would fire on every well-formed +// document. +func TestUnpreservable_AbsentConstructReportsNothing(t *testing.T) { t.Parallel() _, diags := parseFull(t, openapitest.ComponentSpec(" T:\n type: array\n items: {type: string}\n")) _, ok := openapitest.FirstDiag(diags, diag.UnpreservableConstruct) @@ -171,7 +235,7 @@ func TestUnpreservable_CompositeFailsWhole(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(" C:\n type: object\n" + " if: {required: [a]}\n" + - " then: {x-t: " + unpreservableValue + "}\n" + + " then: {" + unpreservableKey + "}\n" + " else: {required: [b]}\n") doc, diags := parseFull(t, spec) @@ -191,7 +255,7 @@ func typeUnmodeled(t *testing.T, doc *ir.Document, id ir.TypeID) ir.Unmodeled { return td.Common().Unmodeled } -// TestPreserve_AllReasonsReachable pins that every UnmodeledReason an OpenAPI +// TestKeep_AllReasonsReachable pins that every UnmodeledReason an OpenAPI // document can provoke is produced by some lowering here, so a consumer // switching on the enum meets no value this compiler can never emit. There is no // longer an exception: ReasonOutOfScope was once only the Smithy and TypeSpec @@ -202,7 +266,7 @@ func typeUnmodeled(t *testing.T, doc *ir.Document, id ir.TypeID) ir.Unmodeled { // The reach is per reason, not per entry: an entry left at the zero reason is // invisible here, and is irverify's "ir/empty-unmodeled-reason" to catch across // the whole corpus rather than this one document's. -func TestPreserve_AllReasonsReachable(t *testing.T) { +func TestKeep_AllReasonsReachable(t *testing.T) { t.Parallel() spec := `openapi: 3.1.0 info: {title: T, version: "1"} @@ -238,9 +302,9 @@ paths: svc := doc.Services[0] // S witnesses vendor_extension, validation_only (its constraint-only union - // joins `not` there) and out_of_scope (its $schema); T's items, which its - // Model has no home for, is the only degraded_lowering witness here, so it - // must not be folded into another case. + // combines `not` there) and out_of_scope (its $schema); T's items, which + // its Model has no home for, is the only degraded_lowering witness here, so + // it must not be folded into another case. seen := map[ir.UnmodeledReason]bool{} for _, name := range []string{"S", "T"} { for _, entry := range doc.Types[componentID(name)].Common().Unmodeled { diff --git a/compilers/openapi/e2e/unreferenced_types_test.go b/compilers/openapi/e2e/unreferenced_types_test.go index 4c3e4cd25..3319b2787 100644 --- a/compilers/openapi/e2e/unreferenced_types_test.go +++ b/compilers/openapi/e2e/unreferenced_types_test.go @@ -7,8 +7,11 @@ import ( "encoding/json/jsontext" "os" "path/filepath" + "strings" "testing" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -332,9 +335,10 @@ components: // TestCompile_PromisedLandingsResolveAfterPruning guards against over-pruning: // after full compilation and pruning, every kept $ref landing, kept -// discriminator route, composed loser, direct $ref to a loser, and empty-named -// root component schema remains in Document.Types, is recorded on the owning -// UnmodeledEntry.Targets where kept verbatim, and passes irverify.Verify. +// discriminator route, composed passed-over declaration, direct $ref to a +// passed-over declaration, and empty-named root component schema remains in +// Document.Types, is recorded on the owning UnmodeledEntry.Targets where kept +// verbatim, and passes irverify.Verify. func TestCompile_PromisedLandingsResolveAfterPruning(t *testing.T) { t.Parallel() spec := `openapi: 3.2.0 @@ -789,13 +793,16 @@ components: } switch d.Provenance.Pointer { case "/components/schemas/LiveInlineLoser/allOf/0/properties/result": - assert.Contains(t, d.Message, string(liveLoserID), "live directly referenced losing inline node keeps its TypeID") + assert.Contains(t, d.Message, "incompatible types string and an object", "live directly referenced losing inline node, by its kind") + assert.NotContains(t, d.Message, string(liveLoserID), "a report names no type ID") sawLiveLoserDiag = true case "/components/schemas/LiveEntryRefLoser/allOf/0/properties/result": - assert.Contains(t, d.Message, string(liveEntryLoserID), "live entry-referenced losing inline node keeps its TypeID") + assert.Contains(t, d.Message, "incompatible types string and an object", "live entry-referenced losing inline node, by its kind") + assert.NotContains(t, d.Message, string(liveEntryLoserID), "a report names no type ID") sawLiveEntryLoserDiag = true case "/components/schemas/PrunedInlineLoser/allOf/0/properties/result": - assert.NotContains(t, d.Message, string(prunedLoserID), "actually pruned losing inline node omits its pruned TypeID") + assert.Contains(t, d.Message, "incompatible types string and an object", "actually pruned losing inline node, by its kind") + assert.NotContains(t, d.Message, string(prunedLoserID), "a report names no type ID") sawPrunedLoserDiag = true } } @@ -805,8 +812,10 @@ components: assert.Empty(t, doc.Types["type/openapi/components/schemas/LiteralMappingNoFalseTarget"].Common().Unmodeled["openapi:if-then-else"].Targets) assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/mapping/a": "type/openapi/components/schemas/Cat"}, doc.Types["type/openapi/components/schemas/CollapsedDiscBesideSibling"].Common().Unmodeled["openapi:discriminator"].Targets) - assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/mapping/sub": "type/anonymous/components/schemas/BesideKeptUnionDisc/$defs/Sub"}, - doc.Types["type/openapi/components/schemas/BesideKeptUnionDisc"].Common().Unmodeled["openapi:discriminator"].Targets) + // BesideKeptUnionDisc routes itself by its name, so only the entry naming + // no subtype is kept, apart, naming what it lowered to. + assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/sub": "type/anonymous/components/schemas/BesideKeptUnionDisc/$defs/Sub"}, + doc.Types["type/openapi/components/schemas/BesideKeptUnionDisc"].Common().Unmodeled["openapi:discriminator/mapping"].Targets) assert.Contains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/TransitiveHoistedDisc/$defs/Deep")) assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/$ref": "type/anonymous/components/schemas/TransitiveHoistedDisc/$defs/Deep"}, doc.Types["type/anonymous/components/schemas/TransitiveHoistedDisc/$defs/Mapped"].Common().Unmodeled["openapi:not"].Targets) @@ -890,9 +899,13 @@ components: // payloads (.inf) beside $refs or kept discriminators report // openapi/unpreservable-construct without leaving unreferenced anonymous types // behind, and that a surviving sibling itemEncoding beside an unpreservable -// prefixEncoding still reserves and attaches its $ref targets. +// prefixEncoding still reserves and attaches its $ref targets. Each payload is +// under a key no object defines: a vendor extension whose value no JSON holds +// is left out wherever it is kept, so the same constructs writing one compile +// as their twins without it, every target kept. func TestCompile_UnpreservableConstructsStayVerified(t *testing.T) { t.Parallel() + const unpreservable = "foo: .inf" spec := `openapi: 3.2.0 info: {title: t, version: "1"} paths: @@ -905,7 +918,7 @@ paths: itemSchema: {type: string} prefixEncoding: - contentType: text/plain - x-bad: .inf + ` + unpreservable + ` itemEncoding: contentType: application/json headers: @@ -923,7 +936,7 @@ paths: - contentType: text/plain itemEncoding: contentType: application/json - x-bad: .inf + ` + unpreservable + ` headers: X-Item: {schema: {$ref: '#/components/schemas/Holder/$defs/DroppedItem'}} responses: @@ -932,7 +945,7 @@ paths: parameters: - name: p in: query - x-bad: .inf + ` + unpreservable + ` schema: {$ref: '#/components/schemas/Holder/$defs/DroppedParam'} components: schemas: @@ -951,18 +964,18 @@ components: type: object not: $ref: '#/components/schemas/Holder/$defs/DroppedNot' - x-bad: .inf + ` + unpreservable + ` UnpreservableIf: type: object if: $ref: '#/components/schemas/Holder/$defs/DroppedIf' - x-bad: .inf + ` + unpreservable + ` then: {required: [a]} UnpreservableUnknown: type: object additionalItems: $ref: '#/components/schemas/Holder/$defs/DroppedUnknown' - x-bad: .inf + ` + unpreservable + ` PreservableNot: type: object not: @@ -971,15 +984,24 @@ components: type: string discriminator: propertyName: kind - x-bad: .inf + ` + unpreservable + ` mapping: m: '#/components/schemas/Holder/$defs/DroppedDisc' ` - doc, _, err := openapi.New().Compile(t.Context(), - []compilers.Source{{Path: "spec.yaml", Data: []byte(spec)}}, compilers.Options{}) - require.NoError(t, err) - require.NotNil(t, doc) - assert.Empty(t, irverify.Verify(doc)) + compile := func(spec string) *ir.Document { + doc, _, err := openapi.New().Compile(t.Context(), + []compilers.Source{{Path: "spec.yaml", Data: []byte(spec)}}, compilers.Options{}) + require.NoError(t, err) + require.NotNil(t, doc) + assert.Empty(t, irverify.Verify(doc)) + return doc + } + doc := compile(spec) + + extension := compile(strings.ReplaceAll(spec, unpreservable, "x-bad: .inf")) + twin := compile(strings.ReplaceAll(spec, unpreservable, "")) + assert.Empty(t, cmp.Diff(twin.Types, extension.Types, cmpopts.EquateEmpty()), "an extension no JSON holds is left out") + assert.Contains(t, extension.Types, ir.TypeID("type/anonymous/components/schemas/Holder/$defs/DroppedNot"), "and its construct kept") assert.Contains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/Holder/$defs/KeptItem")) assert.Contains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/Holder/$defs/KeptNot")) @@ -1039,76 +1061,3 @@ components: } assert.True(t, sawCollision, "declaring \"\" beside Empty must draw pass/name-collision; got %+v", diags) } - -// TestCompile_RefBroughtAllOfFoldRewritesPrunedLoserDiagnostic pins that when -// an allOf mixes an inline schema with a $ref-brought declaration (so -// settlement stamps Provenance.Node onto each fold diagnostic), post-pruning -// diagnostic rewriting still matches and removes every pruned anonymous TypeID -// from both degraded-construct and conflicting-redeclaration messages. -func TestCompile_RefBroughtAllOfFoldRewritesPrunedLoserDiagnostic(t *testing.T) { - t.Parallel() - const spec = `openapi: 3.1.0 -info: {title: t, version: "1"} -paths: - /a: - delete: - operationId: delA - responses: - "200": - description: ok - content: - application/json: - schema: - allOf: - - type: object - properties: - result: - type: array - items: {type: string} - conflict: - type: object - properties: - c: {type: string} - - $ref: '#/components/schemas/Failure' -components: - schemas: - Failure: - type: object - properties: - result: - type: array - items: {type: integer} - conflict: - type: string -` - doc, diags := parseVerified(t, spec) - assert.Empty(t, irverify.Verify(doc)) - - const ( - prunedOverlap ir.TypeID = "type/anonymous/paths/~1a/delete/responses/200/content/application~1json/schema/allOf/0/properties/result" - prunedConflict ir.TypeID = "type/anonymous/paths/~1a/delete/responses/200/content/application~1json/schema/allOf/0/properties/conflict" - keptOverlap ir.TypeID = "type/anonymous/components/schemas/Failure/properties/result" - ) - assert.NotContains(t, doc.Types, prunedOverlap) - assert.NotContains(t, doc.Types, prunedConflict) - assert.Contains(t, doc.Types, keptOverlap) - - var sawOverlap, sawConflict bool - for _, d := range diags { - assert.NotContains(t, d.Message, string(prunedOverlap), "pruned type ID must not appear in diagnostic: %+v", d) - assert.NotContains(t, d.Message, string(prunedConflict), "pruned type ID must not appear in diagnostic: %+v", d) - if d.Code == "openapi/degraded-construct" && d.Provenance.Pointer == "/paths/~1a/delete/responses/200/content/application~1json/schema/allOf/0/properties/result" { - assert.Contains(t, d.Message, string(keptOverlap)) - assert.Contains(t, d.Message, "over the declaration at") - assert.NotEmpty(t, d.Provenance.Node, "brought allOf fold must still stamp Provenance.Node") - sawOverlap = true - } - if d.Code == "openapi/conflicting-redeclaration" && d.Provenance.Pointer == "/paths/~1a/delete/responses/200/content/application~1json/schema/allOf/0/properties/conflict" { - assert.Contains(t, d.Message, "incompatible types (") - assert.NotEmpty(t, d.Provenance.Node, "brought allOf fold must still stamp Provenance.Node") - sawConflict = true - } - } - assert.True(t, sawOverlap, "expected rewritten degraded-construct diagnostic for result; got %+v", diags) - assert.True(t, sawConflict, "expected rewritten conflicting-redeclaration diagnostic for conflict; got %+v", diags) -} diff --git a/compilers/openapi/e2e/unresolved_ref_once_test.go b/compilers/openapi/e2e/unresolved_ref_once_test.go new file mode 100644 index 000000000..fcfc64aea --- /dev/null +++ b/compilers/openapi/e2e/unresolved_ref_once_test.go @@ -0,0 +1,90 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" +) + +// pastMergeBoundSpec is a 3.1 document whose x-m64 is a mapping merging +// through 64 levels of `<<` a $ref to target, which the compiler does not +// expand, beside the schemas given, each one line of YAML. +func pastMergeBoundSpec(target string, schemas ...string) string { + var b strings.Builder + b.WriteString("openapi: 3.1.0\ninfo: {title: t, version: \"1\"}\npaths: {}\n") + fmt.Fprintf(&b, "x-m0: &m0 {$ref: '%s'}\n", target) + for i := 1; i <= 64; i++ { + fmt.Fprintf(&b, "x-m%d: &m%d\n <<: *m%d\n", i, i, i-1) + } + b.WriteString("components:\n schemas:\n Ok: {type: string}\n") + for _, schema := range schemas { + b.WriteString(" " + schema + "\n") + } + return b.String() +} + +// TestUnresolvedRef_ABranchPastTheMergeBoundIsReportedOnce holds GitHub +// #1570's reproduction to one writer per unresolved $ref: a branch whose $ref +// lies past the merge bound draws one openapi/unresolved-ref, at the branch +// and naming its $ref, however many other $refs name the branch and whichever +// composition holds it. The report kept is the first drawn: the union branch +// reader's beside structure, and the $ref's own elsewhere. +func TestUnresolvedRef_ABranchPastTheMergeBoundIsReportedOnce(t *testing.T) { + t.Parallel() + const ok = "#/components/schemas/Ok" + const branchFirst = "union branch $ref" + for _, tc := range []struct { + name, target, at string + schemas []string + // first are words of the report drawn first, the one kept; empty + // names the $ref's own report. + first string + }{ + {"an allOf entry", ok, "allOf/0", []string{"Y: {allOf: [{<<: *m64}]}"}, ""}, + {"an allOf entry another entry names", ok, "allOf/0", + []string{"Y: {allOf: [{<<: *m64}, {$ref: '#/components/schemas/Y/allOf/0'}]}"}, ""}, + {"an allOf entry a property names", ok, "allOf/0", + []string{"Y: {allOf: [{<<: *m64}]}", "H: {type: object, properties: {p: {$ref: '#/components/schemas/Y/allOf/0'}}}"}, ""}, + {"an allOf entry a component names", ok, "allOf/0", + []string{"Y: {allOf: [{<<: *m64}]}", "Z: {$ref: '#/components/schemas/Y/allOf/0'}"}, ""}, + {"a loop past the bound", "#/components/schemas/Y/allOf/1", "allOf/0", + []string{"Y: {allOf: [{<<: *m64}, {$ref: '#/components/schemas/Y/allOf/0'}]}"}, ""}, + {"a oneOf branch beside structure a property names", ok, "oneOf/0", + []string{"Y: {type: object, oneOf: [{<<: *m64}], properties: {p: {$ref: '#/components/schemas/Y/oneOf/0'}}}"}, branchFirst}, + {"a oneOf branch beside structure a component names", ok, "oneOf/0", + []string{"Y: {type: object, oneOf: [{<<: *m64}]}", "Z: {$ref: '#/components/schemas/Y/oneOf/0'}"}, branchFirst}, + {"an anyOf branch beside structure a property names", ok, "anyOf/0", + []string{"Y: {type: object, anyOf: [{<<: *m64}], properties: {p: {$ref: '#/components/schemas/Y/anyOf/0'}}}"}, branchFirst}, + {"a oneOf branch beside structure", ok, "oneOf/0", []string{"Y: {type: object, oneOf: [{<<: *m64}, {type: object}]}"}, branchFirst}, + {"a plain oneOf branch another names", ok, "oneOf/0", + []string{"Y: {oneOf: [{<<: *m64}, {$ref: '#/components/schemas/Y/oneOf/0'}]}"}, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + _, diags := compileAnnotationSpec(t, "merge", pastMergeBoundSpec(tc.target, tc.schemas...)) + var reports []string + for _, diagnostic := range diags { + if diagnostic.Code == diag.UnresolvedRef { + reports = append(reports, string(diagnostic.Provenance.Pointer)+": "+diagnostic.Message) + } + } + if !assert.Len(t, reports, 1, "one report: %v", reports) { + return + } + assert.True(t, strings.HasPrefix(reports[0], "/components/schemas/Y/"+tc.at+": "), "at the branch: %s", reports[0]) + assert.Contains(t, reports[0], `$ref "`+tc.target+`"`) + first := tc.first + if first == "" { + first = "unresolved $ref" + } + assert.Contains(t, reports[0], ": "+first, "the report kept is the first drawn") + }) + } +} diff --git a/compilers/openapi/e2e/use_sites_order_test.go b/compilers/openapi/e2e/use_sites_order_test.go index a171c4f42..78fc02ca3 100644 --- a/compilers/openapi/e2e/use_sites_order_test.go +++ b/compilers/openapi/e2e/use_sites_order_test.go @@ -135,9 +135,9 @@ func TestUseSites_APathItemLandingMountsAlikeInEitherOrder(t *testing.T) { } } -// TestUseSites_AUsesChargeHoldsInEitherOrder pins the reference-expansion charge -// of uses writing keys beside their $ref and of an alias between: the verdict at -// the exact weight, and one below it, is the same in either order. +// TestUseSites_AUsesChargeHoldsInEitherOrder pins the reference-expansion +// charge of uses writing keys beside their $ref and of an alias between: the +// answer at the exact weight, and one below it, is the same in either order. func TestUseSites_AUsesChargeHoldsInEitherOrder(t *testing.T) { t.Parallel() // P weighs 25 as paramP does; A, an alias of P, weighs 1 + description (12) diff --git a/compilers/openapi/e2e/usesites_carried_test.go b/compilers/openapi/e2e/usesites_carried_test.go index cb3533c8e..51fef3490 100644 --- a/compilers/openapi/e2e/usesites_carried_test.go +++ b/compilers/openapi/e2e/usesites_carried_test.go @@ -151,12 +151,13 @@ func TestCarriedKeys_DeclarationOrderChangesNothing(t *testing.T) { // TestParameter_SchemaAndObjectSpellOneKeyEndToEnd compiles the spec writing // one key on a parameter and on its schema, verified: each is kept, and the -// collision finding is gone. +// collision finding is gone. A format beside the schema's $ref to a string, +// selecting no primitive, restricts the reference with its Encoding, so only +// the parameter's own key is kept. func TestParameter_SchemaAndObjectSpellOneKeyEndToEnd(t *testing.T) { t.Parallel() doc, diags := compileNamedVerified(t, "p.yaml", testdataSpec(t, "param_schema_keys_apart")) assert.Equal(t, []string{ - "openapi/degraded-construct info /paths/~1a/get/parameters/1/schema", "openapi/unknown-object-key warning /paths/~1a/get/parameters/0/divisibleBy", "openapi/unknown-object-key warning /paths/~1a/get/parameters/1/format", "openapi/unknown-object-key warning /paths/~1a/get/responses/200/headers/X-H/divisibleBy", @@ -165,11 +166,16 @@ func TestParameter_SchemaAndObjectSpellOneKeyEndToEnd(t *testing.T) { }, findings(diags)) p := namedItem(t, valueAtPath(operationTree(t, doc, "a"), "params"), "p") assert.Contains(t, keptValues(valueAtPath(p, "unmodeled")), "openapi:schema/divisibleBy") + restricted, ok := doc.Types["type/anonymous/paths/~1a/get/parameters/1/schema"].(*ir.Scalar) + require.True(t, ok, "r's schema restricts its reference") + assert.Equal(t, &ir.Encoding{Name: "FROM_SCHEMA_BESIDE_REF"}, restricted.Encoding) } // TestParameter_XMLAndBranchKeptOnceEndToEnd compiles the two specs in which a // parameter's schema keeps a declaration whole beside a key read from inside -// it, and requires the declaration alone. +// it, and requires the declaration alone. The entry writing `format: uuid` +// beside a $ref to a string is the uuid the parameter is, so what it keeps is +// the $ref it took over and the readOnly no parameter holds. func TestParameter_XMLAndBranchKeptOnceEndToEnd(t *testing.T) { t.Parallel() doc, diags := compileNamedVerified(t, "x.yaml", testdataSpec(t, "param_xml_kept_once")) @@ -180,10 +186,10 @@ func TestParameter_XMLAndBranchKeptOnceEndToEnd(t *testing.T) { doc, diags = compileNamedVerified(t, "x.yaml", testdataSpec(t, "param_branch_kept_once")) g := operationTree(t, doc, "g") id := namedItem(t, valueAtPath(g, "params"), "schema_id") - assert.Equal(t, []string{"openapi:schema/format", "openapi:schema/readOnly"}, sortedKeys(keptValues(valueAtPath(id, "unmodeled"))), - "each keyword the entry keeps is kept once, under its own key") + assert.Equal(t, []string{"openapi:schema/$ref", "openapi:schema/readOnly"}, sortedKeys(keptValues(valueAtPath(id, "unmodeled"))), + "each keyword the position keeps is kept once, under its own key") assert.Equal(t, []string{ - "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/1", + "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/0", "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/1/readOnly", "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/1/schema/xml", }, findings(diags)) @@ -191,7 +197,7 @@ func TestParameter_XMLAndBranchKeptOnceEndToEnd(t *testing.T) { // TestParameter_RedactionIsSingleSidedEndToEnd compiles the spec stating // redaction on a schema and withdrawing it on the parameter: the schema's -// statement stands, as it does when it sits behind a $ref. +// statement is kept, as it is when it sits behind a $ref. func TestParameter_RedactionIsSingleSidedEndToEnd(t *testing.T) { t.Parallel() doc, diags := compileNamedVerified(t, "x.yaml", testdataSpec(t, "param_redaction_single_sided")) @@ -221,7 +227,7 @@ func TestTags_KeysOnTheTagAndTierOnItsGroupEndToEnd(t *testing.T) { } // TestTags_ARepeatedNameKeepsEachDeclaration compiles two tags of one name: the -// load's duplicate-key error stands and the document is still built, each tag +// load's duplicate-key error is kept and the document is still built, each tag // keeping its own keys, and the group taking the first declaration's. func TestTags_ARepeatedNameKeepsEachDeclaration(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/e2e/value_set_bounds_test.go b/compilers/openapi/e2e/value_set_bounds_test.go new file mode 100644 index 000000000..caf14246c --- /dev/null +++ b/compilers/openapi/e2e/value_set_bounds_test.go @@ -0,0 +1,36 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package e2e_test + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestValueAdmission_AValueSetsTextBoundJudgesItsTextMembers holds a default +// to the length bound a value set writes, a mixed enum as its string twin: +// {enum: [ab, abc, 1], maxLength: 2} refuses the default abc, as +// {type: string, enum: [ab, abc], maxLength: 2} does, and the bound judges no +// member of another kind, so the default 1 is admitted. +func TestValueAdmission_AValueSetsTextBoundJudgesItsTextMembers(t *testing.T) { + t.Parallel() + spec := admissionSpec("3.1.0", "", "H: {type: object, properties: {"+strings.Join([]string{ + "mixed: {enum: [ab, abc, 1], maxLength: 2, default: abc}", + "text: {type: string, enum: [ab, abc], maxLength: 2, default: abc}", + "mixedNumber: {enum: [ab, abc, 1], maxLength: 2, default: 1}", + "mixedShort: {enum: [ab, abc, 1], maxLength: 2, default: ab}", + }, ", ")+"}}") + _, diags := compiledAndValidated(t, spec) + var refused []string + for _, diagnostic := range diags { + if diagnostic.Code == "pass/default-outside-type" { + refused = append(refused, strings.TrimPrefix(diagnostic.Provenance.Node, "property/openapi/components/schemas/H/properties/")) + } + } + slices.Sort(refused) + assert.Equal(t, []string{"mixed", "text"}, refused) +} diff --git a/compilers/openapi/e2e/variant_bounds_pending_test.go b/compilers/openapi/e2e/variant_bounds_by_kind_test.go similarity index 92% rename from compilers/openapi/e2e/variant_bounds_pending_test.go rename to compilers/openapi/e2e/variant_bounds_by_kind_test.go index 13c214142..0164450e2 100644 --- a/compilers/openapi/e2e/variant_bounds_pending_test.go +++ b/compilers/openapi/e2e/variant_bounds_by_kind_test.go @@ -1,8 +1,6 @@ // Copyright (c) 2026 dexpace. // Licensed under the MIT License. See LICENSE in the repository root for details. -//go:build pending - package e2e_test import ( @@ -20,6 +18,8 @@ import ( // keeping the union and the members (GitHub #2046). func TestVariantBounds_AStringBoundBesideAnArrayAndAStringBranchGoesToTheString(t *testing.T) { t.Parallel() + t.Skip("a body split by kind across a union holding no object branch is not decided: " + + "the object keywords beside it would reach no variant") for _, version := range []string{"3.0.3", "3.1.0"} { for _, order := range [][]string{{"Arr", "Str"}, {"Str", "Arr"}} { t.Run(fmt.Sprintf("%s/%v", version, order), func(t *testing.T) { diff --git a/compilers/openapi/e2e/variant_bounds_test.go b/compilers/openapi/e2e/variant_bounds_test.go index 739437ffc..19b8e5128 100644 --- a/compilers/openapi/e2e/variant_bounds_test.go +++ b/compilers/openapi/e2e/variant_bounds_test.go @@ -179,8 +179,10 @@ func TestVariantBounds_ABoundNoVariantTakesIsKeptOnceOnTheUnion(t *testing.T) { assert.Equal(t, entryKept(kept...), keptOn(union), "what the union keeps at %s", at) assert.Equal(t, 1, countFindings(diags, diag.DegradedConstruct, ir.SeverityInfo, at), "one info for the bounds kept at %s", at) - assert.Len(t, degradedUnder(diags, at), 2+keptBranches(live), - "that, the warning, and one at each branch a variant keeps at %s", at) + assert.Len(t, degradedUnder(diags, at), 1+keptBranches(live), + "that, and one at each branch a variant keeps at %s", at) + assert.Equal(t, 1, countFindings(diags, diag.UnsatisfiableSchema, ir.SeverityWarning, at), + "the warning at %s", at) for j, b := range live { held := variantConstraints(t, doc, union.Variants[j].Type.Target) for _, bound := range variantBounds { diff --git a/compilers/openapi/e2e/variant_dead_entry_test.go b/compilers/openapi/e2e/variant_dead_entry_test.go index 251e89545..22c54b542 100644 --- a/compilers/openapi/e2e/variant_dead_entry_test.go +++ b/compilers/openapi/e2e/variant_dead_entry_test.go @@ -4,6 +4,7 @@ package e2e_test import ( + "encoding/json/jsontext" "fmt" "strings" "testing" @@ -37,8 +38,8 @@ func TestCompile_AnEntryUnionNoBranchOfWhichLivesIsKeptOnTheEntry(t *testing.T) res := harness.Check(t.Context(), "spec.yaml", []byte(spec)) require.Equal(t, harness.OutcomeOK, res.Outcome, res.Detail) doc, diags := compileAnnotationSpec(t, "entry", spec) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, - pointer: "/components/schemas/P", contains: []string{"share no value"}}}) + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, + pointer: "/components/schemas/P", contains: []string{"no value satisfies"}}}) model, ok := typeByName(doc, "P").(*ir.Model) require.True(t, ok, "the schema is the Model its other entry gives") require.NotNil(t, model.Base) @@ -56,22 +57,30 @@ func TestCompile_AnEntryUnionNoBranchOfWhichLivesIsKeptOnTheEntry(t *testing.T) } } -// TestCompile_ABodyBesideANullBranchAndNoLiveOneAdmitsNull holds that the -// reports of a union none of whose branches but its null one an object -// satisfies, beside a body admitting null, say what is true: null satisfies -// the schema, and the union has as many branches as it writes. +// TestCompile_ABodyBesideANullBranchAndNoLiveOneAdmitsNull holds that a union +// none of whose branches but its null one an object satisfies, beside a body +// admitting null, leaves the position null alone: the closed empty Enum behind +// a nullable reference, keeping the union, whose report says what is true, +// that null satisfies the schema and that a branch shares no value with it. func TestCompile_ABodyBesideANullBranchAndNoLiveOneAdmitsNull(t *testing.T) { t.Parallel() spec := admissionSpec("3.1.0", "", "S: {type: [object, 'null'], properties: {p: {type: string}}, oneOf: [{type: 'null'}, {type: integer}]}") - _, diags := compileAnnotationSpec(t, "nullbranch", spec) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/S", - contains: []string{"none of its 2 branches but a null one", "no instance but null satisfies this schema"}}}) + doc, diags := compileAnnotationSpec(t, "nullbranch", spec) + requireErrorsAndWarnings(t, diags, nil) + enum, ok := kindNode(t, doc, componentID("S")).(*ir.Enum) + require.True(t, ok, "the position admits null alone") + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(enum)["openapi:oneOf"]) + var said []string for _, diagnostic := range diags { - if diagnostic.Provenance.Pointer == "/components/schemas/S" { - assert.NotContains(t, diagnostic.Message, "no instance satisfies", "null satisfies it: %s", diagnostic.Message) + if diagnostic.Provenance.Pointer == "/components/schemas/S" && strings.Contains(diagnostic.Message, "oneOf kept") { + said = append(said, diagnostic.Message) } } + require.Len(t, said, 1, "the union's keep is reported once") + assert.Contains(t, said[0], "no branch shares a value with the rest of this schema but null") } // TestCompile_AnEntryUnionBesideARestAdmittingNullIsKeptAndWarns holds that a @@ -100,10 +109,10 @@ func TestCompile_AnEntryUnionBesideARestAdmittingNullIsKeptAndWarns(t *testing.T res := harness.Check(t.Context(), "spec.yaml", []byte(spec)) require.Equal(t, harness.OutcomeOK, res.Outcome, res.Detail) doc, diags := compileAnnotationSpec(t, "entry-null", spec) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", contains: []string{ - "the conjuncts of this allOf share no value (allOf/0: object, allOf/1: string or boolean)", - "so no instance satisfies this schema"}}}) + "no value satisfies every allOf entry (allOf/0: object, allOf/1: string or boolean)", + "; lowered as "}}}) model, ok := typeByName(doc, "P").(*ir.Model) require.True(t, ok, "the schema is the Model the rest of its allOf gives") require.NotNil(t, model.Base) @@ -118,14 +127,26 @@ func TestCompile_AnEntryUnionBesideARestAdmittingNullIsKeptAndWarns(t *testing.T } } -// TestCompile_AnEntryUnionWhoseNullBranchAloneLivesSaysWhatNullMeets holds the -// warning of a union on an allOf entry whose only branch not dead is its null -// one to the null the rest of the allOf admits: beside a rest admitting null, -// null alone satisfies the schema; beside one keeping it out, nothing does, -// which the report of conjuncts sharing no value says, and says too in either -// order where a cycle cuts short the read of another conjunct's null, as the -// object read on its own keeps null out. -func TestCompile_AnEntryUnionWhoseNullBranchAloneLivesSaysWhatNullMeets(t *testing.T) { +// countMessagesAt counts the findings at pointer whose message holds text. +func countMessagesAt(diags []ir.Diagnostic, pointer jsontext.Pointer, text string) int { + count := 0 + for _, diagnostic := range diags { + if diagnostic.Provenance.Pointer == pointer && strings.Contains(diagnostic.Message, text) { + count++ + } + } + return count +} + +// TestCompile_AnEntryUnionWhoseNullBranchAloneLivesSaysWhatNullIntersects holds a +// union on an allOf entry whose only branch not dead is its null one to the +// null the rest admits: beside a rest admitting null, null alone satisfies the +// schema, the closed empty Enum behind a nullable reference, saying why; +// beside one keeping it out, the nullable-inference policy lifts that null, so +// the position is null alone too, the dead branch named at the union; where a +// cycle cuts short the read of another conjunct's null, the report of +// conjuncts sharing no value says nothing satisfies it. +func TestCompile_AnEntryUnionWhoseNullBranchAloneLivesSaysWhatNullIntersects(t *testing.T) { t.Parallel() branches := "{oneOf: [{type: 'null'}, {$ref: '#/components/schemas/Str'}]}" spec := admissionSpec("3.1.0", "", "Obj: {type: object, properties: {a: {type: string}}}", @@ -134,14 +155,20 @@ func TestCompile_AnEntryUnionWhoseNullBranchAloneLivesSaysWhatNullMeets(t *testi "Admits: {allOf: [{$ref: '#/components/schemas/ON'}, "+branches+"]}", "Refuses: {allOf: [{$ref: '#/components/schemas/Obj'}, "+branches+"]}", "Unknown: {allOf: [{$ref: '#/components/schemas/Obj'}, {$ref: '#/components/schemas/Cyc'}, "+branches+"]}") - _, diags := compileAnnotationSpec(t, "entry-null-branch", spec) + doc, diags := compileAnnotationSpec(t, "entry-null-branch", spec) + admits, ok := kindNode(t, doc, componentID("Admits")).(*ir.Enum) + require.True(t, ok, "beside a rest admitting null the position admits null alone") + assert.Empty(t, admits.Members) + assert.Equal(t, ir.ReasonDegradedLowering, keptOn(admits)["openapi:oneOf"]) + assert.Equal(t, 1, countMessagesAt(diags, "/components/schemas/Admits/allOf/1", + "no branch shares a value with the rest of this schema but null"), "and says why, once") + refuses, ok := kindNode(t, doc, componentID("Refuses")).(*ir.Enum) + require.True(t, ok, "beside a rest keeping null out the policy leaves the position null alone") + assert.Empty(t, refuses.Members) requireErrorsAndWarnings(t, diags, []wantFinding{ - {code: diag.DegradedConstruct, pointer: "/components/schemas/Admits", contains: []string{ - "none of the 2 branches of the oneOf on allOf/1 but a null one admits a value the rest", - "(allOf/1/oneOf/1: string)", "so no instance but null satisfies this schema"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/Refuses", contains: []string{ - "the conjuncts of this allOf share no value (allOf/0: object, allOf/1: string)"}}, - {code: diag.DegradedConstruct, pointer: "/components/schemas/Unknown", contains: []string{ - "the conjuncts of this allOf share no value (allOf/0: object, allOf/2: string)"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/Refuses/allOf/1/oneOf", contains: []string{ + "1 of the 2 branches of this oneOf shares no value with the rest of the schema (oneOf/1: string)"}}, + {code: diag.UnsatisfiableSchema, pointer: "/components/schemas/Unknown", contains: []string{ + "no value satisfies every allOf entry (allOf/0: object, allOf/2: string)"}}, }) } diff --git a/compilers/openapi/e2e/variant_dead_grid_test.go b/compilers/openapi/e2e/variant_dead_grid_test.go index 51eae89b9..93dc92d1f 100644 --- a/compilers/openapi/e2e/variant_dead_grid_test.go +++ b/compilers/openapi/e2e/variant_dead_grid_test.go @@ -13,14 +13,15 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestCompile_AUnionBesideAnyRestDrawsOneWarningAtMost holds every schema of a -// grid, a rest of the allOf (a $ref to a string, to an object, an enum, a -// union, a $ref naming no schema, the top type, `type: object`) beside a union -// of two branches (a string, a boolean, a $ref to an object, null), written -// beside the allOf and on an entry, as a oneOf and an anyOf, to one warning at -// its own pointer at most, and a dead-branch warning to a rest admitting -// objects alone (docs/compilers/openapi.md#union-beside-structure). -func TestCompile_AUnionBesideAnyRestDrawsOneWarningAtMost(t *testing.T) { +// TestCompile_AUnionBesideAnyRestDrawsOneWarningPerUnionAtMost holds every schema of a +// grid, a rest of the allOf beside a union of two branches (a string, a +// boolean, a $ref to an object, null), written beside the allOf and on an +// entry, as a oneOf and an anyOf, to one warning per union at most, a rest +// that is a union being one, each at its own pointer: a dead branch's at +// the schema beside a rest admitting objects alone, else at the union keyword, +// as where the nullable-inference policy lifts the null of a union no branch +// of which lives (docs/compilers/openapi.md#union-beside-structure). +func TestCompile_AUnionBesideAnyRestDrawsOneWarningPerUnionAtMost(t *testing.T) { t.Parallel() rests := map[string]string{ "str": "{$ref: '#/components/schemas/Str'}", "obj": "{$ref: '#/components/schemas/Obj'}", @@ -39,27 +40,39 @@ func TestCompile_AUnionBesideAnyRestDrawsOneWarningAtMost(t *testing.T) { entry := fmt.Sprintf("G%s%d%d%sEntry", rest, i, j, keyword) schemas = append(schemas, beside+": {allOf: ["+written+"], "+union+"}", entry+": {allOf: ["+written+", {"+union+"}]}") - objects[beside] = rest == "obj" || rest == "objtype" + // The null branch is the last; beside an object it is lifted + // where the other branch, no $ref to an object, is dead. + lifted := j == len(branches)-1 && i != 2 + objects[beside] = (rest == "obj" || rest == "objtype") && !lifted objects[entry] = objects[beside] } } } } _, diags := compileAnnotationSpec(t, "grid", admissionSpec("3.1.0", "", schemas...)) - warned := map[string][]string{} + warned, warnedAt := map[string][]string{}, map[string]map[string]bool{} for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityWarning { - name := strings.TrimPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/") + at := strings.TrimPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/") + name, union, _ := strings.Cut(at, "/") warned[name] = append(warned[name], diagnostic.Message) + if warnedAt[name] == nil { + warnedAt[name] = map[string]bool{} + } + warnedAt[name][at] = true + if strings.Contains(diagnostic.Message, "branches") && !strings.HasPrefix(name, "Gunion") { + assert.Equal(t, objects[name], union == "", "%s: a dead branch is reported at the schema beside objects alone, "+ + "else at its union: %s", at, diagnostic.Message) + } } } for name, messages := range warned { - assert.LessOrEqual(t, len(messages), 1, "%s: %q", name, messages) - for _, m := range messages { - if strings.Contains(m, "branches") { - assert.True(t, objects[name] || strings.HasPrefix(name, "Gunion"), "%s: a dead branch beside a rest of another kind: %s", name, m) - } + unions := 1 + if strings.HasPrefix(name, "Gunion") { + unions = 2 } + assert.LessOrEqual(t, len(messages), unions, "%s: %q", name, messages) + assert.Len(t, warnedAt[name], len(messages), "%s: each warning at its own union: %q", name, messages) } assert.NotEmpty(t, warned, "the grid reaches the reports") } diff --git a/compilers/openapi/e2e/variant_dead_helpers_test.go b/compilers/openapi/e2e/variant_dead_helpers_test.go index e69da7155..bfffe3de2 100644 --- a/compilers/openapi/e2e/variant_dead_helpers_test.go +++ b/compilers/openapi/e2e/variant_dead_helpers_test.go @@ -12,7 +12,7 @@ import ( ) // liveBranches returns the branches of a union distributed over an object body -// that some instance satisfies, in order: the ones its variants stand for. +// that some instance satisfies, in order: the ones its variants stay for. func liveBranches(branches []variantBranch) []variantBranch { var out []variantBranch for _, b := range branches { @@ -49,7 +49,7 @@ func deadWarnings(keyword string, branches []variantBranch) []wantFinding { } out := make([]wantFinding, 0, len(conjunctionPositions)) for _, at := range conjunctionPositions { - out = append(out, wantFinding{code: diag.DegradedConstruct, pointer: string(at), contains: named}) + out = append(out, wantFinding{code: diag.UnsatisfiableSchema, pointer: string(at), contains: named}) } return out } diff --git a/compilers/openapi/e2e/variant_dead_rest_test.go b/compilers/openapi/e2e/variant_dead_rest_test.go index 86ca9b41c..68a10168f 100644 --- a/compilers/openapi/e2e/variant_dead_rest_test.go +++ b/compilers/openapi/e2e/variant_dead_rest_test.go @@ -23,7 +23,7 @@ func TestCompile_ADeadBranchIsReadAgainstWhatTheRestAdmits(t *testing.T) { }{ {"a string rest beside an object branch", "P: {allOf: [{$ref: '#/components/schemas/Str'}, {oneOf: [{type: boolean}, {$ref: '#/components/schemas/Obj'}]}]}", - []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/P", contains: []string{"share no value"}}}}, + []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", contains: []string{"no value satisfies"}}}}, {"a rest naming no schema", "P: {allOf: [{$ref: '#/components/schemas/Nowhere'}, {oneOf: [{type: string}, {type: integer}]}]}", []wantFinding{{code: diag.UnresolvedRef, pointer: "/components/schemas/P/allOf/0"}}}, diff --git a/compilers/openapi/e2e/variant_dead_route_test.go b/compilers/openapi/e2e/variant_dead_route_test.go index 28112e074..28c8a2fb5 100644 --- a/compilers/openapi/e2e/variant_dead_route_test.go +++ b/compilers/openapi/e2e/variant_dead_route_test.go @@ -15,7 +15,7 @@ import ( "github.com/dexpace/morphic/ir" ) -// deadRouteSpelling is one place a discriminator stands with a union holding a +// deadRouteSpelling is one place a discriminator stays with a union holding a // dead branch: the schema it is written in, what the dead branch's mapping // entry is kept under on the Union, and where that entry is written. type deadRouteSpelling struct { @@ -69,7 +69,7 @@ func TestCompile_AMappingToADeadBranchIsNoRoute(t *testing.T) { res := harness.Check(t.Context(), "spec.yaml", []byte(spec)) require.Equal(t, harness.OutcomeOK, res.Outcome, res.Detail) doc, diags := parseVerified(t, spec) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", contains: []string{ `no tag of the discriminator routes to it (mapping "s", the name "Str")`, "the routes it writes kept verbatim under Unmodeled"}}}) @@ -85,7 +85,7 @@ func TestCompile_AMappingToADeadBranchIsNoRoute(t *testing.T) { assert.JSONEq(t, `"#/components/schemas/Str"`, string(kept.Value)) assert.Equal(t, sp.at, string(kept.Provenance.Pointer)) compiled, compiledDiags := compileAnnotationSpec(t, "route", spec) - requireErrorsAndWarnings(t, compiledDiags, []wantFinding{{code: diag.DegradedConstruct, + requireErrorsAndWarnings(t, compiledDiags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P"}}) assert.Equal(t, union, compiled.Types[componentID("P")], "the passes change nothing here") }) @@ -113,7 +113,7 @@ func TestCompile_TheNameOfADeadBranchIsNoRoute(t *testing.T) { t.Run(strings.Join([]string{version, sp.name, order}, "/"), func(t *testing.T) { t.Parallel() doc, diags := parseVerified(t, spec) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", contains: []string{ `no tag of the discriminator routes to it (the name "Str")`}}}) for _, diagnostic := range diags { @@ -147,7 +147,7 @@ func TestCompile_ADefaultMappingToADeadBranchIsNoRoute(t *testing.T) { t.Run(order, func(t *testing.T) { t.Parallel() doc, diags := parseVerified(t, spec) - requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.DegradedConstruct, + requireErrorsAndWarnings(t, diags, []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", contains: []string{ `no tag of the discriminator routes to it (defaultMapping, the name "Str")`}}}) union, ok := kindNode(t, doc, componentID("P")).(*ir.Union) @@ -162,12 +162,12 @@ func TestCompile_ADefaultMappingToADeadBranchIsNoRoute(t *testing.T) { } } -// TestCompile_ADiscriminatorBesideAUnionNoBranchOfWhichLivesIsKeptWhole holds -// that where every branch is dead, so the union is kept whole, the -// discriminator standing with it routes nothing and is kept whole too, as the -// tree keeps one beside a union it cannot route: on the Model beside the body -// or the allOf, and with its entry on an entry, with no error. -func TestCompile_ADiscriminatorBesideAUnionNoBranchOfWhichLivesIsKeptWhole(t *testing.T) { +// TestCompile_ADiscriminatorBesideAUnionNoBranchOfWhichLivesKeepsItsOwnRoute +// holds that where every branch is dead, so the union is kept whole, the +// discriminator beside it routes no branch: on an entry it is kept with its +// entry, and on the Model beside the body or the allOf it routes the model by +// its own name, its entry naming no subtype kept verbatim apart, with no error. +func TestCompile_ADiscriminatorBesideAUnionNoBranchOfWhichLivesKeepsItsOwnRoute(t *testing.T) { t.Parallel() mapping := ", mapping: {s: '#/components/schemas/Str'}" for _, version := range bothVersions { @@ -183,10 +183,19 @@ func TestCompile_ADiscriminatorBesideAUnionNoBranchOfWhichLivesIsKeptWhole(t *te } model, ok := kindNode(t, doc, componentID("P")).(*ir.Model) require.True(t, ok) - assert.Nil(t, model.Discriminator, "the discriminator routes nothing") - kept, ok := model.Unmodeled["openapi:discriminator"] - require.True(t, ok, "it is kept whole: %v", keptOn(model)) - assert.Equal(t, strings.TrimSuffix(sp.at, "/mapping/s"), string(kept.Provenance.Pointer)) + if sp.name == "entry" { + assert.Nil(t, model.Discriminator, "the discriminator routes nothing") + kept, ok := model.Unmodeled["openapi:discriminator"] + require.True(t, ok, "it is kept whole: %v", keptOn(model)) + assert.Equal(t, strings.TrimSuffix(sp.at, "/mapping/s"), string(kept.Provenance.Pointer)) + return + } + require.NotNil(t, model.Discriminator, "P routes itself by its name") + assert.Equal(t, map[string]ir.TypeID{"P": componentID("P")}, model.Discriminator.Mapping) + kept, ok := model.Unmodeled["openapi:discriminator/mapping"] + require.True(t, ok, "the entry is kept apart: %v", keptOn(model)) + assert.JSONEq(t, `{"s": "#/components/schemas/Str"}`, string(kept.Value)) + assert.Equal(t, strings.TrimSuffix(sp.at, "/s"), string(kept.Provenance.Pointer)) }) } } diff --git a/compilers/openapi/e2e/variant_dead_test.go b/compilers/openapi/e2e/variant_dead_test.go index 4516d7253..d857e1612 100644 --- a/compilers/openapi/e2e/variant_dead_test.go +++ b/compilers/openapi/e2e/variant_dead_test.go @@ -4,6 +4,7 @@ package e2e_test import ( + "encoding/json/jsontext" "fmt" "slices" "strings" @@ -109,7 +110,8 @@ func deadSchema(deadCaseValue deadCase, keyword string, branches []deadBranch) s // its path and the schema draws one warning naming every such branch, at 3.0.3 // and 3.1.0, under oneOf and anyOf, in both orders of the branches and of the // components, with every harness oracle passing. Where none lives, the -// position lowers as its body, keeping the union whole. +// position lowers as its body, keeping the union whole, and the warning +// names the union as one conjunct of the schema. func TestCompile_ABranchNoObjectSatisfiesIsNoVariant(t *testing.T) { t.Parallel() for _, deadCase := range deadCases { @@ -138,14 +140,16 @@ func TestCompile_ABranchNoObjectSatisfiesIsNoVariant(t *testing.T) { } // requireDeadBranches holds the component P, whose union keyword lists -// branches, to the shape a union with those branches dead takes. +// branches, to the shape a union with those branches dead takes. A variant over +// an entry's branch sits at its composed key, P/allOf/-/1/..., which names the +// entry the union is written on. func requireDeadBranches(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, entry bool, keyword string, branches []deadBranch, ) { t.Helper() - path := keyword + path, variantPath := keyword, keyword if entry { - path = "allOf/1/" + keyword + path, variantPath = "allOf/1/"+keyword, "allOf/-/1/"+keyword } var named []string live := 0 @@ -157,9 +161,13 @@ func requireDeadBranches(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, live++ } } + if live == 0 && len(named) > 0 { + // No branch lives: the one report reads the union as a conjunct. + named = []string{keyword + ": "} + } var want []wantFinding if len(named) > 0 { - want = []wantFinding{{code: diag.DegradedConstruct, pointer: "/components/schemas/P", contains: named}} + want = []wantFinding{{code: diag.UnsatisfiableSchema, pointer: "/components/schemas/P", contains: named}} } requireErrorsAndWarnings(t, diags, want) node := kindNode(t, doc, componentID("P")) @@ -185,13 +193,14 @@ func requireDeadBranches(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, if b.dead || b.null { continue } - assert.Equal(t, at, string(kindNode(t, doc, union.Variants[v].Type.Target).Common().Provenance.Pointer), - "variant %d stands for %s", v, at) + variantAt := fmt.Sprintf("/components/schemas/P/%s/%d", variantPath, i) + assert.Equal(t, variantAt, string(kindNode(t, doc, union.Variants[v].Type.Target).Common().Provenance.Pointer), + "variant %d represents %s", v, at) v++ } } -// requireNothingAt holds that no node and no finding stands at or under at. +// requireNothingAt holds that no node and no finding sits at or under at. func requireNothingAt(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, at string) { t.Helper() for id := range doc.Types { @@ -217,12 +226,13 @@ func TestCompile_AnUntypedBranchLivesWithKindInferenceOff(t *testing.T) { []deadBranch{{schema: "{$ref: '#/components/schemas/A'}"}, {schema: "{minLength: 1}"}}) } -// TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureKept holds that -// a union whose one member-declaring inline branch is dead still leaves an -// entry's additionalProperties kept on each variant rather than closing it: -// which object closes the model reads the branches as written, not which of -// them are variants (docs/compilers/openapi.md#additional-properties). -func TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureKept(t *testing.T) { +// TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureTyped holds that +// an entry's additionalProperties beside a union whose one member-declaring +// inline branch is dead closes the live variant, which holds members the +// closure's own object does not declare, and is also kept once, on the Union, +// and reported once at the keyword +// (docs/compilers/openapi.md#additional-properties, GitHub #2047, #2054). +func TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureTyped(t *testing.T) { t.Parallel() schema := "{allOf: [" + closureRef + ", {additionalProperties: false}], " + "oneOf: [{$ref: '#/components/schemas/A'}, {type: string, properties: {z: {type: string}}}]}" @@ -236,8 +246,12 @@ func TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureKept(t *testing assert.Equal(t, ir.ReasonDegradedLowering, keptOn(union)["openapi:oneOf/1"], "the dead branch kept at %s", at) variant, ok := kindNode(t, doc, union.Variants[0].Type.Target).(*ir.Model) require.True(t, ok, at) - assert.Equal(t, ir.AdditionalUnspecified, variant.Additional, "open at %s", at) - assert.Equal(t, ir.ReasonDegradedLowering, keptOn(variant)["openapi:allOf/1"], "the closing entry kept at %s", at) + assert.Equal(t, ir.AdditionalClosed, variant.Additional, "closed at %s", at) + keyword := string(at) + "/allOf/1/additionalProperties" + assert.Len(t, messagesBeneath(diags, diag.DegradedConstruct, keyword), 1, "one info at %s", keyword) + assert.NotEmpty(t, keptUnder(doc, jsontext.Pointer(keyword)), "the closure kept at %s", keyword) + assert.NotContains(t, keptOn(variant), "openapi:allOf/1", "the variant keeps no closure at %s", at) + assert.NotContains(t, keptOn(variant), "openapi:additionalProperties", "the variant keeps no closure at %s", at) } }) } @@ -247,7 +261,8 @@ func TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureKept(t *testing // branches a distributed union on an allOf entry keeps, on a variant, on the // Union or as its null, are keyed by their keyword and index, the provenance // naming the entry, and that no key collides with another entry's union, which -// is kept whole under its own keyword: a position distributes one union. +// is kept whole under its own keyword, once, on the Union: a position +// distributes one union. func TestCompile_TwoUnionsOnEntriesKeepTheirBranchesApart(t *testing.T) { t.Parallel() spec := admissionSpec("3.1.0", "", append([]string{"P: {allOf: [{$ref: '#/components/schemas/A'}, " + @@ -263,9 +278,12 @@ func TestCompile_TwoUnionsOnEntriesKeepTheirBranchesApart(t *testing.T) { require.Len(t, union.Variants, 2) const entry = "/components/schemas/P/allOf/" want := map[ir.TypeID]map[string]string{ - union.ID: {"openapi:oneOf/2": entry + "1/oneOf/2", "openapi:oneOf/3": entry + "1/oneOf/3"}, - union.Variants[0].Type.Target: {"openapi:anyOf": entry + "2/anyOf"}, - union.Variants[1].Type.Target: {"openapi:anyOf": entry + "2/anyOf", "openapi:oneOf/1": entry + "1/oneOf/1"}, + union.ID: { + "openapi:oneOf/2": entry + "1/oneOf/2", "openapi:oneOf/3": entry + "1/oneOf/3", + "openapi:anyOf": entry + "2/anyOf", + }, + union.Variants[0].Type.Target: {}, + union.Variants[1].Type.Target: {"openapi:oneOf/1": entry + "1/oneOf/1"}, } for id, keys := range want { got := map[string]string{} diff --git a/compilers/openapi/e2e/variant_kept_once_test.go b/compilers/openapi/e2e/variant_kept_once_test.go index 3f774d37f..a0d90f920 100644 --- a/compilers/openapi/e2e/variant_kept_once_test.go +++ b/compilers/openapi/e2e/variant_kept_once_test.go @@ -42,10 +42,10 @@ var keptOnceCases = []struct { } // TestCompile_ABranchAVariantKeepsLowersNowhereElse holds that a branch a -// distributed variant keeps verbatim is held there alone: no node stands at -// or under its pointer, the target of a $ref it writes stays a node of its -// own, the variant's reference admits null where the branch and the body both -// do, and the branch draws one info and no other finding. Every harness oracle +// distributed variant keeps verbatim is held there alone: no node sits at or +// under its pointer, the target of a $ref it writes stays a node of its own, +// the variant's reference admits null where the branch and the body both do, +// and the branch draws one info and no other finding. Every harness oracle // passes, and the components lower alike in either order. func TestCompile_ABranchAVariantKeepsLowersNowhereElse(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/export_test.go b/compilers/openapi/export_test.go index f4f530b8d..f0b7daaa4 100644 --- a/compilers/openapi/export_test.go +++ b/compilers/openapi/export_test.go @@ -34,7 +34,3 @@ var AttachUnmodeledTargetsWith = attachUnmodeledTargetsWith // SeedDiscardedLandings is seedDiscardedLandings, for the external tests. var SeedDiscardedLandings = seedDiscardedLandings - -// RewritePrunedFoldDiagnostics is rewritePrunedFoldDiagnostics, for the -// external tests. -var RewritePrunedFoldDiagnostics = rewritePrunedFoldDiagnostics diff --git a/compilers/openapi/foldreports_test.go b/compilers/openapi/foldreports_test.go new file mode 100644 index 000000000..ea91510e3 --- /dev/null +++ b/compilers/openapi/foldreports_test.go @@ -0,0 +1,621 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package openapi_test + +import ( + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers" + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// foldReport is what a test reads of a report of the member fold: its +// severity, code and site, the node it names beside its place, and each entry +// of what it concerns, by role, place and node, and its message. +type foldReport struct { + Severity ir.Severity + Code string + At string + Node string + Related []string + Message string +} + +// foldReportsOf compiles src and returns its reports of the member fold about +// a pair of declarations, each listing the place it kept, under the two codes +// the fold reports a pair under, sorted by site and then message. +func foldReportsOf(t *testing.T, src string) []foldReport { + t.Helper() + _, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + var out []foldReport + for _, diagnostic := range diags { + if diagnostic.Code != "openapi/degraded-construct" && diagnostic.Code != "openapi/conflicting-redeclaration" { + continue + } + if !slices.ContainsFunc(diagnostic.Related, func(related ir.Related) bool { return related.Role == ir.RelatedChosen }) { + continue + } + report := foldReport{Severity: diagnostic.Severity, Code: diagnostic.Code, At: string(diagnostic.Provenance.Pointer), + Node: diagnostic.Provenance.Node, Message: diagnostic.Message} + for _, related := range diagnostic.Related { + report.Related = append(report.Related, strings.TrimSpace(string(related.Role)+" "+string(related.Provenance.Pointer)+" "+related.Provenance.Node)) + } + out = append(out, report) + } + slices.SortFunc(out, func(a, b foldReport) int { return strings.Compare(a.At+a.Message, b.At+b.Message) }) + return out +} + +// foldSpec is a 3.1 document declaring schemas. +func foldSpec(schemas ...string) string { + return openapitest.ComponentSpec(" " + strings.Join(schemas, "\n ") + "\n") +} + +// TestFoldReports_AStepNamesOneDeclarationInEitherOrder pins what a fold of +// steps reports, its entries in either order. A step too long to intersect any +// other, beside 5 and 2, which intersect in 10, names the first written of +// those two as chosen and the 10 chosen, in one message, though the entries +// intersect them in another order. Two spellings of one long step are one +// value, no conflict, spelled as the first written. +func TestFoldReports_AStepNamesOneDeclarationInEitherOrder(t *testing.T) { + t.Parallel() + long := "1" + strings.Repeat("3", 512) + stepSchema := func(name, step string) string { + return name + ": {type: object, properties: {f: {type: number, multipleOf: " + step + "}}}" + } + model := func(entries ...string) string { + refs := make([]string, len(entries)) + for i, entry := range entries { + refs[i] = "{$ref: '#/components/schemas/" + entry + "'}" + } + return "M: {allOf: [" + strings.Join(refs, ", ") + "]}" + } + // tooLong's numerator passes the 1,024 digits a step intersection reads. + tooLong := "1" + strings.Repeat("0", 1024) + "7" + for _, tc := range []struct { + name string + schemas []string + entries []string + at, kept string + says string + step ir.BigVal + }{ + {name: "a step intersected after the conflict", entries: []string{"D0", "D1", "D2"}, at: "/components/schemas/D1/properties/f", + kept: "chosen /components/schemas/D0/properties/f", says: "conflicting multipleOf (10 and " + tooLong + ")", step: "10", + schemas: []string{stepSchema("D0", "5"), stepSchema("D1", tooLong), stepSchema("D2", "2")}}, + {name: "one long step spelled two ways", entries: []string{"D1", "D2"}, step: ir.BigVal(long), + schemas: []string{stepSchema("D1", long), stepSchema("D2", long+".0")}}, + } { + said := map[bool][]string{} + for _, reversed := range []bool{false, true} { + entries := slices.Clone(tc.entries) + if reversed { + slices.Reverse(entries) + } + src := foldSpec(append(slices.Clone(tc.schemas), model(entries...))...) + doc, _, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + + reports := foldReportsOf(t, src) + sites := make([]string, 0, len(reports)) + for _, report := range reports { + sites = append(sites, report.At+" "+report.Related[0]) + said[reversed] = append(said[reversed], report.Message) + assert.Contains(t, report.Message, tc.says, "%s, reversed %v", tc.name, reversed) + } + if tc.at == "" { + assert.Empty(t, sites, "%s, reversed %v", tc.name, reversed) + } else { + assert.Equal(t, []string{tc.at + " " + tc.kept}, sites, "%s, reversed %v", tc.name, reversed) + } + composed, isModel := doc.Types["type/openapi/components/schemas/M"].(*ir.Model) + require.True(t, isModel, tc.name) + require.Len(t, composed.Properties, 1, tc.name) + require.NotNil(t, composed.Properties[0].Constraints, tc.name) + assert.Equal(t, tc.step, *composed.Properties[0].Constraints.MultipleOf, "%s, reversed %v", tc.name, reversed) + } + assert.Equal(t, said[false], said[true], "%s: the reports say the same in either order", tc.name) + } +} + +// TestFoldReports_DisjointVisibilitySitsAtTheFirstWrittenRestriction pins the +// report of a member its declarations restrict to disjoint lifecycles: it sits +// at the first written, by source position and not by allOf order, of the +// declarations writing readOnly or writeOnly true, and its message names them +// in that order, so either order of the entries draws the same report. +func TestFoldReports_DisjointVisibilitySitsAtTheFirstWrittenRestriction(t *testing.T) { + t.Parallel() + restricted := func(name, keyword string) string { + return name + ": {type: object, properties: {p: {type: string, " + keyword + ": true}}}" + } + pointer := func(name string) string { return "/components/schemas/" + name + "/properties/p" } + for _, tc := range []struct { + name string + schemas []string + entries []string // M0's allOf as written + restricting []string // in the order they are written + }{ + {name: "two declarations", schemas: []string{restricted("D0", "readOnly"), restricted("D1", "writeOnly")}, + entries: []string{"D0", "D1"}, restricting: []string{"D0", "D1"}}, + {name: "three declarations, composed out of written order", + schemas: []string{restricted("D0", "readOnly"), restricted("D1", "readOnly"), restricted("D2", "writeOnly")}, + entries: []string{"D2", "D0", "D1"}, restricting: []string{"D0", "D1", "D2"}}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + reversed := slices.Clone(tc.entries) + slices.Reverse(reversed) + messages := make([]string, 0, 2) + for _, entries := range [][]string{tc.entries, reversed} { + refs := make([]string, len(entries)) + for i, entry := range entries { + refs[i] = "{$ref: '#/components/schemas/" + entry + "'}" + } + src := foldSpec(append(slices.Clone(tc.schemas), "M0: {allOf: ["+strings.Join(refs, ", ")+"]}")...) + _, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + reports := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code != "openapi/disjoint-visibility" + }) + require.Len(t, reports, 1, "the member must be reported once, with entries %v", entries) + assert.Equal(t, pointer(tc.restricting[0]), string(reports[0].Provenance.Pointer), "the site, with entries %v", entries) + positions := make([]int, len(tc.restricting)) + for i, name := range tc.restricting { + assert.Contains(t, reports[0].Message, pointer(name), "the message must name each restriction, with entries %v", entries) + positions[i] = strings.Index(reports[0].Message, pointer(name)) + } + assert.IsIncreasing(t, positions, "the message must name the restrictions as written, with entries %v", entries) + messages = append(messages, reports[0].Message) + } + assert.Equal(t, messages[0], messages[1], "the message must not follow the order of the entries") + }) + } +} + +// budgetCutDeclaration declares p a string, the first of 66 alone describing +// it, so whether that one is judged shows in p's docs. +func budgetCutDeclaration(i int) string { + description := "" + if i == 0 { + description = ", description: zero" + } + return "{type: object, properties: {p: {type: string" + description + "}}}" +} + +// budgetCutComponents writes D00 to D65, each a budgetCutDeclaration, and the +// references naming them in the order they are written. +func budgetCutComponents() (schemas, targets []string) { + for i := range 66 { + name := fmt.Sprintf("D%02d", i) + schemas = append(schemas, name+": "+budgetCutDeclaration(i)) + targets = append(targets, "#/components/schemas/"+name) + } + return schemas, targets +} + +// budgetCutPrefixItems writes H, whose prefixItems are 66 budgetCutDeclaration +// items, and the references naming them in the order they are written, each +// by its index. +func budgetCutPrefixItems() (schemas, targets []string) { + items := make([]string, 66) + for i := range items { + items[i] = budgetCutDeclaration(i) + targets = append(targets, "#/components/schemas/H/prefixItems/"+strconv.Itoa(i)) + } + return []string{"H: {type: array, prefixItems: [" + strings.Join(items, ", ") + "]}"}, targets +} + +// TestFoldReports_TheBudgetCutFollowsTheSource pins which declarations of a +// member declared past the fold's budget are judged: the first 64 written, by +// source position and not by allOf order, an index compared as a number, the +// budget report sitting where the first one left unjudged is written, so +// either order of the entries judges the same declarations and reports alike. +func TestFoldReports_TheBudgetCutFollowsTheSource(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + declarations func() (schemas, targets []string) + site string + }{ + {name: "components D00 to D65", declarations: budgetCutComponents, site: "/components/schemas/D64/properties/p"}, + {name: "items of a holder's prefixItems", declarations: budgetCutPrefixItems, + site: "/components/schemas/H/prefixItems/64/properties/p"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + schemas, targets := tc.declarations() + reversed := slices.Clone(targets) + slices.Reverse(reversed) + members := make([][]ir.Property, 0, 2) + for _, entries := range [][]string{targets, reversed} { + refs := make([]string, len(entries)) + for i, entry := range entries { + refs[i] = "{$ref: '" + entry + "'}" + } + src := foldSpec(append(slices.Clone(schemas), "M0: {allOf: ["+strings.Join(refs, ", ")+"]}")...) + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + reports := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code != "openapi/budget-exceeded" + }) + require.Len(t, reports, 1, "the cut must be reported once, with M0's allOf from %s", entries[0]) + assert.Equal(t, tc.site, string(reports[0].Provenance.Pointer), "the site, with M0's allOf from %s", entries[0]) + model, isModel := doc.Types["type/openapi/components/schemas/M0"].(*ir.Model) + require.True(t, isModel, "M0 must lower to a model") + require.Len(t, model.Properties, 1, "M0 must fold its declarations to one member") + members = append(members, model.Properties) + } + assert.Equal(t, "zero", members[0][0].Docs.Description, "the first written declaration must be judged") + if diff := cmp.Diff(members[0], members[1]); diff != "" { + t.Errorf("the member depends on the order of M0's allOf (-as written +reversed):\n%s", diff) + } + }) + } +} + +// TestFoldReports_AMemberRestrictedBothWaysIsReportedByItsReader pins that a +// declaration writing readOnly and writeOnly true is reported where it is +// written, with nothing composed: the reader of the schema reports it, so the +// report decides no member of a fold. +func TestFoldReports_AMemberRestrictedBothWaysIsReportedByItsReader(t *testing.T) { + t.Parallel() + src := foldSpec("C: {type: object, properties: {p: {type: string, readOnly: true, writeOnly: true}}}") + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + reports := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code != "openapi/disjoint-visibility" + }) + require.Len(t, reports, 1, "the declaration must be reported once") + assert.Equal(t, "/components/schemas/C/properties/p", string(reports[0].Provenance.Pointer)) + assert.Empty(t, reports[0].Related, "the report must decide no member of a fold") + model, isModel := doc.Types["type/openapi/components/schemas/C"].(*ir.Model) + require.True(t, isModel, "C must lower to a model") + require.Len(t, model.Properties, 1) + assert.Equal(t, ir.Visibility{InvisibleInEveryLifecycle: true}, model.Properties[0].Visibility) +} + +// TestFoldReports_ADeclarationRestrictedBothWaysLeavesTheFoldNothingToReport +// pins that a fold reports disjoint lifecycles only where no declaration +// empties them alone: C, restricted both ways, draws its reader's report, and +// composing it with A and B, each restricted one way, draws no report of the +// fold in either order of the entries. +func TestFoldReports_ADeclarationRestrictedBothWaysLeavesTheFoldNothingToReport(t *testing.T) { + t.Parallel() + schemas := []string{"A: {type: object, properties: {p: {type: string, readOnly: true}}}", + "B: {type: object, properties: {p: {type: string, writeOnly: true}}}", + "C: {type: object, properties: {p: {type: string, readOnly: true, writeOnly: true}}}"} + for _, entries := range []string{"A, B, C", "C, B, A"} { + t.Run(entries, func(t *testing.T) { + t.Parallel() + refs := strings.Split(entries, ", ") + for i, entry := range refs { + refs[i] = "{$ref: '#/components/schemas/" + entry + "'}" + } + src := foldSpec(append(slices.Clone(schemas), "M0: {allOf: ["+strings.Join(refs, ", ")+"]}")...) + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + reports := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code != "openapi/disjoint-visibility" + }) + require.Len(t, reports, 1, "C's own report alone must be drawn") + assert.Equal(t, "/components/schemas/C/properties/p", string(reports[0].Provenance.Pointer)) + assert.Empty(t, reports[0].Related, "the report must decide no member of a fold") + model, isModel := doc.Types["type/openapi/components/schemas/M0"].(*ir.Model) + require.True(t, isModel, "M0 must lower to a model") + require.Len(t, model.Properties, 1, "M0 must fold its declarations to one member") + assert.Equal(t, ir.Visibility{InvisibleInEveryLifecycle: true}, model.Properties[0].Visibility) + }) + } +} + +// TestFoldReports_ABudgetErrorOutlivesThePruningOfItsMember pins that pruning +// removes no error: Both's allOf holds false, so the member its +// additionalProperties model folds from 66 declarations is pruned, and the +// budget error at that fold stays, listing no member the document no longer +// holds. +func TestFoldReports_ABudgetErrorOutlivesThePruningOfItsMember(t *testing.T) { + t.Parallel() + entries := make([]string, 66) + for i := range entries { + entries[i] = "{properties: {f: {type: string, description: d" + strconv.Itoa(i) + "}}}" + } + src := foldSpec("Both: {allOf: [{type: object, additionalProperties: {type: object, allOf: [" + strings.Join(entries, ", ") + "]}}, false]}") + doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + held := map[ir.PropertyID]bool{} + for _, typeDef := range doc.Types { + if model, isModel := typeDef.(*ir.Model); isModel { + for _, property := range model.Properties { + held[property.ID] = true + } + } + } + reports := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code != "openapi/budget-exceeded" + }) + require.Len(t, reports, 1, "the budget error must outlive pruning: %+v", diags) + assert.Equal(t, ir.SeverityError, reports[0].Severity) + for _, related := range reports[0].Related { + if related.Role == ir.RelatedDecided { + assert.True(t, held[ir.PropertyID(related.Provenance.Node)], "a decided entry names %s, which pruning removed", related.Provenance.Node) + } + } +} + +// TestFoldReports_AReportSitsWhereThePassedOverValueIsDeclared pins where a +// report about a detail a field gives up sits, and names: at the declaration +// passed over for it where that declaration is written, even when its value +// comes through its $ref, and where the value is written only for a member a +// part's composition settles, which is written nowhere. The kept place it names +// writes the value kept. A place writes a value it holds or one its $ref +// reaches holds. +func TestFoldReports_AReportSitsWhereThePassedOverValueIsDeclared(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + schemas []string + sites []string + }{ + { + // A and B each compose C, which writes no description, with one of + // their own, and M both with one of its own: each member A and B + // settle is reported where its description is written, and C, + // which writes none, draws no report. + name: "a member a part's composition settles", + schemas: []string{"C: {type: object, properties: {f: {type: string, maxLength: 5}}}", + "A: {allOf: [{$ref: '#/components/schemas/C'}, {properties: {f: {description: a}}}]}", + "B: {allOf: [{$ref: '#/components/schemas/C'}, {properties: {f: {description: b}}}]}", + "M: {allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}, {properties: {f: {type: string, description: m}}}]}"}, + sites: []string{"/components/schemas/A/allOf/1/properties/f", "/components/schemas/B/allOf/1/properties/f"}, + }, + { + // P's domain takes its description from Dom, which its $ref names: + // the report sits at the property, not at Dom. + name: "a property describing itself through its $ref", + schemas: []string{"Dom: {type: string, description: dom}", + "P: {type: object, properties: {domain: {$ref: '#/components/schemas/Dom'}}}", + "Q: {type: object, properties: {domain: {type: string, description: q}}}", + "M: {allOf: [{$ref: '#/components/schemas/P'}, {$ref: '#/components/schemas/Q'}]}"}, + sites: []string{"/components/schemas/P/properties/domain"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + src := foldSpec(tc.schemas...) + writesDescription := describedAt(t, src) + + reports := foldReportsOf(t, src) + + sites := make([]string, 0, len(reports)) + for _, report := range reports { + sites = append(sites, report.At) + assert.Contains(t, report.Message, "description", "the report speaks of the description") + assert.Contains(t, report.Message, " and "+report.At+" give", "the report names where it sits as the place passed over") + assert.True(t, writesDescription(report.At), "%s writes no description", report.At) + for _, related := range report.Related { + if chosen, isChosen := strings.CutPrefix(related, "chosen "); isChosen { + assert.True(t, writesDescription(chosen), "the chosen place %s writes no description", chosen) + } + } + } + assert.Equal(t, tc.sites, sites) + }) + } +} + +// TestFoldReports_ARefusalSitsWhereEachValueIsWritten pins where a refusal of +// a member a part settled sits, and what it names: P's member takes its +// default from one declaration and its examples from one, and Q's enum admits +// neither, so each value is refused where it is written, in one report where +// one declaration writes both and in one each where two do. +func TestFoldReports_ARefusalSitsWhereEachValueIsWritten(t *testing.T) { + t.Parallel() + const ( + q = "Q: {type: object, properties: {id: {type: string, enum: [z]}}}" + m = "M: {allOf: [{$ref: '#/components/schemas/P'}, {$ref: '#/components/schemas/Q'}]}" + p = "P: {allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}" + refusal = `: the merge cannot show that the type its declarations merge to admits the ` + suffix = ` gives; not adopted, and that declaration stays declared on its model` + ) + refused := func(what, at string) string { + return at + `: field "id" of /components/schemas/M` + refusal + what + " " + at + suffix + } + for _, tc := range []struct { + name string + schemas []string + want []string + }{ + {name: "two declarations writing them", schemas: []string{"A: {type: object, properties: {id: {default: aa}}}", + "B: {type: object, properties: {id: {examples: [bb]}}}", p, q, m}, + want: []string{refused("default", "/components/schemas/A/properties/id"), refused("examples", "/components/schemas/B/properties/id")}}, + {name: "one declaration writing both", schemas: []string{"A: {type: object, properties: {id: {default: aa, examples: [bb]}}}", + "B: {type: object, properties: {id: {description: b}}}", p, q, m}, + want: []string{refused("default and examples", "/components/schemas/A/properties/id")}}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + _, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(foldSpec(tc.schemas...))}, compilers.Options{}) + require.NoError(t, err) + var got []string + for _, diagnostic := range diags { + if strings.Contains(diagnostic.Message, refusal) { + got = append(got, string(diagnostic.Provenance.Pointer)+": "+diagnostic.Message) + } + } + slices.Sort(got) + assert.Equal(t, tc.want, got, "%+v", diags) + }) + } +} + +// describedAt reads src and returns whether the schema at a pointer into it +// writes a description, itself or through the $ref it writes, read a bounded +// number of hops. +func describedAt(t *testing.T, src string) func(pointer string) bool { + t.Helper() + var source any + require.NoError(t, yaml.Unmarshal([]byte(src), &source)) + at := func(pointer string) map[string]any { + node := source + for token := range strings.SplitSeq(strings.TrimPrefix(pointer, "/"), "/") { + switch value := node.(type) { + case map[string]any: + node = value[token] + case []any: + index, err := strconv.Atoi(token) + if err != nil || index >= len(value) { + return nil + } + node = value[index] + default: + return nil + } + } + schema, _ := node.(map[string]any) + return schema + } + return func(pointer string) bool { + for range 8 { + schema := at(pointer) + if _, writes := schema["description"]; writes { + return true + } + ref, isRef := schema["$ref"].(string) + if !isRef { + return false + } + pointer = strings.TrimPrefix(ref, "#") + } + return false + } +} + +// TestFoldReports_AMemberWrittenNowhereIsNamedWhereItsFieldIsWritten pins the +// place a report names for a member W's composition settled from components +// alone, which no schema writes: a field the member takes from one +// declaration where that declaration writes it, and a field several give +// jointly at the one place the member's type is written. Each place a report +// names, its site among them, writes what the report speaks of. +func TestFoldReports_AMemberWrittenNowhereIsNamedWhereItsFieldIsWritten(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } + for _, tc := range []struct { + name, code string + schemas []string + site string + named []string + writes []string + }{ + { + // W takes its description from D alone, and is passed over for M's + // own. + name: "a field taken from one declaration", code: "openapi/degraded-construct", + schemas: []string{"C: {type: object, properties: {f: {type: string, maxLength: 5}}}", + "D: {type: object, properties: {f: {type: string, description: d}}}", + "W: {allOf: [" + ref("C") + ", " + ref("D") + "]}", + "M: {allOf: [" + ref("W") + ", {properties: {f: {type: string, description: m}}}]}"}, + site: "/components/schemas/D/properties/f", + named: []string{"/components/schemas/M/allOf/1/properties/f", "/components/schemas/D/properties/f"}, + writes: []string{"description"}, + }, + { + // T and V both make W's f read-only, and T alone writes its type. + name: "a field several declarations give jointly", code: "openapi/disjoint-visibility", + schemas: []string{"T: {type: object, properties: {f: {type: string, readOnly: true}}}", + "V: {type: object, properties: {f: {readOnly: true, maxLength: 5}}}", + "W: {allOf: [" + ref("T") + ", " + ref("V") + "]}", + "A: {type: object, properties: {f: {type: string, writeOnly: true}}}", + "M: {allOf: [" + ref("W") + ", " + ref("A") + "]}"}, + site: "/components/schemas/A/properties/f", + named: []string{"/components/schemas/A/properties/f", "/components/schemas/T/properties/f"}, + writes: []string{"readOnly", "writeOnly"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + src := foldSpec(tc.schemas...) + _, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(src)}, compilers.Options{}) + require.NoError(t, err) + reports := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { return diagnostic.Code != tc.code }) + require.Len(t, reports, 1, "%+v", diags) + report := reports[0] + writes := writtenAt(t, src) + + assert.Equal(t, tc.site, string(report.Provenance.Pointer)) + for _, named := range tc.named { + assert.True(t, namesPlace(report.Message, named), "the report names %s: %s", named, report.Message) + assert.True(t, writes(named, tc.writes...), "%s writes none of %v", named, tc.writes) + } + assert.False(t, namesPlace(report.Message, "/components/schemas/W"), "the report names W, which writes none: %s", report.Message) + for _, related := range report.Related { + if related.Role == ir.RelatedChosen { + assert.True(t, writes(string(related.Provenance.Pointer), tc.writes...), "the kept place writes none of %v", tc.writes) + } + } + }) + } +} + +// namesPlace reports whether message names the declaration at pointer, and not +// one beneath or beside it: after the field it opens with, the models holding +// it and the parts composing them, which name no declaration. +func namesPlace(message, pointer string) bool { + _, said, _ := strings.Cut(message, ": ") + return regexp.MustCompile(`(^|\s)` + regexp.QuoteMeta(pointer) + `([^/\w]|$)`).MatchString(said) +} + +// writtenAt reads src and returns whether the schema at a pointer into it +// writes any of keywords, itself or through the $ref it writes, read a bounded +// number of hops. +func writtenAt(t *testing.T, src string) func(pointer string, keywords ...string) bool { + t.Helper() + var source any + require.NoError(t, yaml.Unmarshal([]byte(src), &source)) + at := func(pointer string) map[string]any { + node := source + for token := range strings.SplitSeq(strings.TrimPrefix(pointer, "/"), "/") { + switch value := node.(type) { + case map[string]any: + node = value[token] + case []any: + index, err := strconv.Atoi(token) + if err != nil || index >= len(value) { + return nil + } + node = value[index] + default: + return nil + } + } + schema, _ := node.(map[string]any) + return schema + } + return func(pointer string, keywords ...string) bool { + for range 8 { + schema := at(pointer) + if slices.ContainsFunc(keywords, func(keyword string) bool { _, writes := schema[keyword]; return writes }) { + return true + } + ref, isRef := schema["$ref"].(string) + if !isRef { + return false + } + pointer = strings.TrimPrefix(ref, "#") + } + return false + } +} diff --git a/compilers/openapi/internal/annotation/annotation.go b/compilers/openapi/internal/annotation/annotation.go index 8fdfaac4f..fa21f5dd4 100644 --- a/compilers/openapi/internal/annotation/annotation.go +++ b/compilers/openapi/internal/annotation/annotation.go @@ -6,10 +6,8 @@ package annotation import ( "encoding/json/jsontext" "fmt" - "iter" "slices" "strconv" - "strings" yaml "go.yaml.in/yaml/v3" @@ -65,11 +63,11 @@ func EffectiveVisibility(chain []*statement.Schema) (ir.Visibility, bool) { // occurrence is true, and false the same as absent. func anyFlag(chain []*statement.Schema, accessor func(*statement.Notes) *bool) bool { return slices.ContainsFunc(chain, func(schema *statement.Schema) bool { - v := (*bool)(nil) + flag := (*bool)(nil) if notes := notesIn(schema); notes != nil { - v = accessor(notes) + flag = accessor(notes) } - return v != nil && *v + return flag != nil && *flag }) } @@ -163,9 +161,21 @@ const ( // references another type and may carry annotations of its own. type Kind int +// SchemaRole is the part a schema plays in a position's conjunction: the +// schema written at the position, or one of its allOf entries. A reader takes +// some keywords from one part and not the other. +type SchemaRole int + +const ( + // PositionSchema is the schema written at the position, beside its allOf. + PositionSchema SchemaRole = iota + // AllOfEntrySchema is an allOf entry of the schema written at the position. + AllOfEntrySchema +) + // SchemaPositionAnnotationSources is what a schema position declares: Node is -// the schema written there, FoldedAllOfEntries the inline allOf entries read as -// written beside it, and Referents, honoured only for a reference site, what a +// the schema written there, FlattenedAllOfEntries the inline allOf entries read +// as written beside it, and Referents, honoured only for a reference site, what a // use site's annotations fall back to, nearest first. // // A SchemaPositionAnnotationSources At builds carries none of either: a @@ -177,21 +187,29 @@ type Kind int type SchemaPositionAnnotationSources struct { Kind Kind Node *statement.Schema - // FoldedAllOfEntries are the entries read as written at Node + // FlattenedAllOfEntries are the entries read as written at Node // (docs/compilers/openapi.md#allof-inline-residue). - FoldedAllOfEntries []FoldedAllOfEntry + FlattenedAllOfEntries []FlattenedAllOfEntry // Referents is empty when Kind is Reference but the $ref's chain ends on no // schema; refTypeRef is what diagnoses that, not this. Referents []*statement.Schema // Dialect is what the dialect Node is read in spells otherwise than 2020-12. Dialect Dialect - // Closure says the node Node lowered to holds its `unevaluatedProperties: - // false` as its openness, so no entry keeps it. The zero value keeps it. + // Typed says which unevaluated keywords of Node the node it lowered to + // holds, so no entry keeps them. The zero value keeps each. + Typed Typed +} + +// Typed says which unevaluated keywords of a schema the node it lowered to +// holds (docs/compilers/openapi.md#validation-only). +type Typed struct { + // Closure says the node holds `unevaluatedProperties: false` as its + // openness. Closure bool - // Leaves names the keywords Node writes that Read keeps no entry of: an - // inline allOf entry the position keeps whole writes them alike, and that - // entry holds the one writing (docs/compilers/openapi.md#allof-refinement). - Leaves []string + // CatchAll says it holds an unevaluatedProperties schema as its catch-all. + CatchAll bool + // Items says it holds unevaluatedItems as its elements or its rest. + Items bool } // Dialect is what a schema's dialect spells otherwise than JSON Schema @@ -209,22 +227,17 @@ type Dialect struct { ListedTuple bool } -// FoldedAllOfEntry is an inline allOf entry and where it is written, so what it -// declares is read, and reported, at its own pointer, in its own dialect. -type FoldedAllOfEntry struct { +// FlattenedAllOfEntry is an inline allOf entry and where it is written, so what +// it declares is read, and reported, at its own pointer, in its own dialect. +type FlattenedAllOfEntry struct { Node *statement.Schema At jsontext.Pointer // Dependencies says the dialect Node is written in defines `dependencies` // (Dialect.Dependencies), which an entry naming its own may, whatever the // position's. Dependencies bool - // KeptWhole says the position keeps the entry whole, an Unmodeled entry - // holding what it writes, so it writes no Unmodeled entry Read keeps beside - // it but one no other voice writes - // (docs/compilers/openapi.md#allof-inline-residue). - KeptWhole bool // Beside says Node is the position's own schema, read beside the inline - // allOf entry its node is built from: what it writes stands before that + // allOf entry its node is built from: what it writes comes before that // entry's, as the keywords beside an allOf do before an entry's. Beside bool } @@ -232,9 +245,9 @@ type FoldedAllOfEntry struct { // Chain returns what speaks for the site, nearest first: its own schema, its // folded entries, then the referents a reference site falls back to. func (st SchemaPositionAnnotationSources) Chain() []*statement.Schema { - chain := make([]*statement.Schema, 0, 1+len(st.FoldedAllOfEntries)+len(st.Referents)) + chain := make([]*statement.Schema, 0, 1+len(st.FlattenedAllOfEntries)+len(st.Referents)) chain = append(chain, st.Node) - for _, foldedAllOfEntry := range st.FoldedAllOfEntries { + for _, foldedAllOfEntry := range st.FlattenedAllOfEntries { chain = append(chain, foldedAllOfEntry.Node) } if st.Kind == Declaration { @@ -285,11 +298,14 @@ type Set struct { // Sensitive is a redaction the site or its referent asks for // (DeclaresRedaction). A type node holds it as Sensitive, and a property or // a parameter as Secret. - Sensitive bool - XML *ir.XMLHints - Examples []ir.Example - Unmodeled ir.Unmodeled - Unpreserved []ir.Provenance + Sensitive bool + XML *ir.XMLHints + Examples []ir.Example + Unmodeled ir.Unmodeled + // FlattenedEntries are what each flattened entry keeps, apart from what the + // site's own schema keeps (Unmodeled). + FlattenedEntries []FlattenedEntryKept + Unkept []ir.Provenance } // redactionFormat is the one format OpenAPI defines that names no shape: its @@ -306,102 +322,67 @@ func DeclaresRedaction(schema *statement.Schema) bool { } // Read reads every site-local annotation at st: what its schema writes at -// pointer, then what each voice writes at its own. A voice agrees with what -// spoke before it wherever both write a keyword (schema.foldingAllOfEntries), -// so an entry is kept once: the site's own, else, where several voices kept -// apart write it, at pointer, no one writer's (underlay). A voice's unevaluated -// keywords fold nowhere (schema.foldEntry): its entry, kept whole, is their one -// record. +// pointer, and what each flattened entry writes at its own +// (Set.FlattenedEntries), each keeping what its schema writes as written flat +// for the node's pending keeps to settle (PendingKeeps). A flattened entry's +// unevaluated keywords fold nowhere +// (schema.foldKey): the entry, kept whole, is their one record. // // This is the one place the site-versus-referent choice is made, so no // position attaching annotations makes it apart. -func Read(st SchemaPositionAnnotationSources, pointer jsontext.Pointer, doc provenance.Doc) (Set, []ir.Diagnostic) { - out, diags := readLocal(st.Node, pointer, doc, true, st.Dialect, st.Closure) - for _, key := range leftEntries(st) { - if _, kept := out.Unmodeled[key]; kept { - delete(out.Unmodeled, key) - diags = lessNote(diags, doc.At(pointer), key) - } - } - var underlayValue underlay - if len(st.FoldedAllOfEntries) > 0 { - underlayValue.own = make(map[string]bool, len(out.Unmodeled)) - for key := range out.Unmodeled { - underlayValue.own[key] = true - } - } - for _, foldedAllOfEntry := range st.FoldedAllOfEntries { - foldedEntry, foldedEntryDiags := readLocal(foldedAllOfEntry.Node, foldedAllOfEntry.At, doc, false, Dialect{Dependencies: foldedAllOfEntry.Dependencies}, false) - for key := range foldedEntry.Unmodeled { - if underlayValue.own[key] { - // The site keeps the one writing, and its report says so. - foldedEntryDiags = lessNote(foldedEntryDiags, doc.At(foldedAllOfEntry.At), key) - } - } - diags = append(diags, foldedEntryDiags...) - out.Unpreserved = append(out.Unpreserved, foldedEntry.Unpreserved...) +func Read(st SchemaPositionAnnotationSources, pointer jsontext.Pointer, doc provenance.Doc) (Set, KeptReports) { + out, reports := readLocal(st.Node, pointer, doc, PositionSchema, st.Dialect, st.Typed) + for _, foldedAllOfEntry := range st.FlattenedAllOfEntries { + foldedEntry, foldedEntryReports := readLocal(foldedAllOfEntry.Node, foldedAllOfEntry.At, doc, AllOfEntrySchema, Dialect{Dependencies: foldedAllOfEntry.Dependencies}, Typed{}) + out.Unkept = append(out.Unkept, foldedEntry.Unkept...) if out.XML == nil { out.XML = foldedEntry.XML } if len(out.Examples) == 0 { out.Examples = foldedEntry.Examples } - out.Unmodeled = underlayValue.add(out.Unmodeled, foldedEntry.Unmodeled, foldedAllOfEntry.KeptWhole, doc.At(pointer)) + out.FlattenedEntries = append(out.FlattenedEntries, FlattenedEntryKept{At: foldedAllOfEntry.At, Unmodeled: foldedEntry.Unmodeled, Reports: foldedEntryReports}) } chain := st.Chain() FillCarrierDocs(&out.Docs, chain) out.Deprecated = EffectiveDeprecated(chain) out.Sensitive = slices.ContainsFunc(chain, DeclaresRedaction) - return out, diags + return out, reports } -// leftEntries returns the entries Read keeps none of for st.Leaves: the one -// each keyword is kept under, and the one several keywords fold into, if, then -// and else or contains and its counts, where the site leaves every one of -// them it writes. -func leftEntries(st SchemaPositionAnnotationSources) []string { - if len(st.Leaves) == 0 { - return nil - } - out := make([]string, 0, len(st.Leaves)+2) - for _, keyword := range st.Leaves { - out = append(out, EntryKey("", keyword)) - } - left := func(keyword string) bool { return slices.Contains(st.Leaves, keyword) } - if _, written, _ := IfThenElseRaw(st.Node); len(written) > 0 && !slices.ContainsFunc(written, func(k string) bool { return !left(k) }) { - out = append(out, "openapi:if-then-else") +// ReadKeeps reports whether Read, reading schema as a declaration's own schema +// in dialect, with no folded entry, referent or closure, keeps anything of it +// that only a node holds. A false answer where the node would hold something +// drops it, while a true one where it holds nothing costs only a build, so XML +// hints count however empty. +func ReadKeeps(schema *statement.Schema, dialect Dialect) bool { + set, _ := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: schema, Dialect: dialect}, "", provenance.Doc{}) + if set.Deprecated || set.Sensitive || set.XML != nil { + return true } - if _, written, _ := ContainsRaw(st.Node); len(written) > 0 && !slices.ContainsFunc(written, func(k string) bool { return !left(k) }) { - out = append(out, "openapi:contains") + if set.Docs.Summary != "" || set.Docs.Description != "" || len(set.Docs.ExternalDocs) > 0 { + return true } - return out + return len(set.Examples) > 0 || len(set.Unmodeled) > 0 } -// lessNote returns diags less the report validationOnlyAt drew at at for the -// validation-only entry under key, which its caller keeps no entry of: another -// writer keeps the one writing, and reports it. An entry of another reason -// drew none. -func lessNote(diags []ir.Diagnostic, at ir.Provenance, key string) []ir.Diagnostic { - label := strings.TrimPrefix(key, EntryKey("", "")) - switch label { - case "if-then-else": - label = "if/then/else" - default: - } - message := validationOnlyMessage(label) - return slices.DeleteFunc(diags, func(diagnostic ir.Diagnostic) bool { - return diagnostic.Code == diag.ValidationOnlyKeyword && diagnostic.Provenance.Pointer == at.Pointer && diagnostic.Message == message - }) +// FlattenedEntryKept is what one flattened entry of a site keeps verbatim, +// written at At, and the reports of its reading, each paired with the key of +// the entry it reports. +type FlattenedEntryKept struct { + At jsontext.Pointer + Unmodeled ir.Unmodeled + Reports KeptReports } // readLocal reads what schema, written at pointer, says of the position alone: -// the annotations no use inherits. own says schema is the schema written at the -// position, rather than a folded entry, whose dialect keywords, discriminator -// and unevaluated keywords no fold reads and whose residue keeps them, dialect -// is what its dialect spells otherwise -// (SchemaPositionAnnotationSources.Dialect), and closure is -// SchemaPositionAnnotationSources.Closure. -func readLocal(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, own bool, dialect Dialect, closure bool) (Set, []ir.Diagnostic) { +// the annotations no use inherits. role says whether schema is the schema +// written at the position or a flattened allOf entry, whose dialect keywords, +// discriminator and unevaluated keywords no fold reads and the entry keeps, +// dialect is what its dialect spells otherwise +// (SchemaPositionAnnotationSources.Dialect), and typed is +// SchemaPositionAnnotationSources.Typed. +func readLocal(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, role SchemaRole, dialect Dialect, typed Typed) (Set, KeptReports) { var out Set out.XML = XMLHints(schema.XML()) @@ -409,18 +390,13 @@ func readLocal(schema *statement.Schema, pointer jsontext.Pointer, doc provenanc out.Examples = examples ext, extDiags := SchemaExtensions(extensionsIn(schema), doc, pointer, "") - sub, subDiags := subObjectKeys(schema, out.XML, pointer, doc, own) - kept, unpreserved, keptDiags := unmodeledAt(schema, pointer, doc, own, dialect, closure) - - diags := make([]ir.Diagnostic, 0, len(exDiags)+len(extDiags)+len(subDiags)+len(keptDiags)) - diags = append(diags, exDiags...) - diags = append(diags, extDiags...) - diags = append(diags, subDiags...) - diags = append(diags, keptDiags...) + sub, subReports := subObjectKeys(schema, out.XML, pointer, doc, role == PositionSchema) + kept, unpreserved, keptReports := unmodeledAt(schema, pointer, doc, role, dialect, typed) + reports := slices.Concat(ReportsOf("", exDiags...), ReportsOf("", extDiags...), subReports, keptReports) out.Unmodeled = MergeUnmodeled(MergeUnmodeled(ext, sub), kept) - out.Unpreserved = unpreserved - return out, diags + out.Unkept = unpreserved + return out, reports } // subObjectKeys collects what a schema's xml, discriminator and externalDocs @@ -432,45 +408,45 @@ func readLocal(schema *statement.Schema, pointer jsontext.Pointer, doc provenanc // (applyNodeType). discriminator says whether schema's discriminator is read. // An object schema does not write is not asked, so a schema writing none costs // nothing. -func subObjectKeys(schema *statement.Schema, hints *ir.XMLHints, pointer jsontext.Pointer, doc provenance.Doc, discriminator bool) (ir.Unmodeled, []ir.Diagnostic) { +func subObjectKeys(schema *statement.Schema, hints *ir.XMLHints, pointer jsontext.Pointer, doc provenance.Doc, discriminator bool) (ir.Unmodeled, KeptReports) { var out ir.Unmodeled - var diags []ir.Diagnostic + var reports KeptReports keep := func(keyword string, unknown []string, node *yaml.Node, ext []statement.Extension, taken []string) { owner := pointer + ids.Ptr(keyword) kept, extDiags := SchemaExtensions(ext, doc, owner, keyword) out = MergeUnmodeled(out, kept) - diags = append(diags, extDiags...) - diags = append(diags, UnknownKeysNamed(&out, unknown, node, doc, owner, keyword, taken...)...) + reports = append(reports, ReportsOf("", extDiags...)...) + reports = append(reports, UnknownKeysNamed(&out, unknown, node, doc, owner, keyword, taken...)...) } if xml := schema.XML(); xml != nil { - taken, xmlDiags := applyNodeType(&out, hints, xml, doc, pointer+ids.Ptr("xml")) - diags = append(diags, xmlDiags...) + taken, xmlReports := applyNodeType(&out, hints, xml, doc, pointer+ids.Ptr("xml")) + reports = append(reports, xmlReports...) keep("xml", xml.Unknown, xml.Node, xml.Extensions, taken) } if discriminator { - kept, keptDiags := DiscriminatorKeys(schema, pointer, doc) + kept, keptReports := DiscriminatorKeys(schema, pointer, doc) out = MergeUnmodeled(out, kept) - diags = append(diags, keptDiags...) + reports = append(reports, keptReports...) } if externalDocs := schema.ExternalDocs(); externalDocs != nil { keep("externalDocs", externalDocs.Unknown, externalDocs.Node, externalDocs.Extensions, nil) } - return out, diags + return out, reports } // DiscriminatorKeys returns what the discriminator schema writes, at pointer, // declares that reaches no IR field, as Read keeps a site's own schema's: the // x-* it carries and the keys the specification does not define for it. A node // holding the discriminator of a schema written elsewhere, an allOf entry whose -// union stands at the entry's position, keeps them so. -func DiscriminatorKeys(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc) (ir.Unmodeled, []ir.Diagnostic) { +// union sits at the entry's position, keeps them so. +func DiscriminatorKeys(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc) (ir.Unmodeled, KeptReports) { discriminator := schema.Discriminator() if discriminator == nil { return nil, nil } owner := pointer + ids.Ptr("discriminator") out, diags := SchemaExtensions(discriminator.Extensions, doc, owner, "discriminator") - return out, append(diags, UnknownKeysNamed(&out, discriminator.Unknown, discriminator.Node, doc, owner, "discriminator")...) + return out, append(ReportsOf("", diags...), UnknownKeysNamed(&out, discriminator.Unknown, discriminator.Node, doc, owner, "discriminator")...) } // applyNodeType places the nodeType the XML object xml writes on hints, which @@ -481,31 +457,32 @@ func DiscriminatorKeys(schema *statement.Schema, pointer jsontext.Pointer, doc p // instead, as nothing else may fill XMLHints.NodeType. An attribute flag the // nodeType contradicts, which 3.2 forbids writing beside it, is kept verbatim // on unmodeled rather than placed, so the hints never name two kinds of node. -func applyNodeType(unmodeled *ir.Unmodeled, hints *ir.XMLHints, xml *statement.XML, doc provenance.Doc, owner jsontext.Pointer) ([]string, []ir.Diagnostic) { +func applyNodeType(unmodeled *ir.Unmodeled, hints *ir.XMLHints, xml *statement.XML, doc provenance.Doc, owner jsontext.Pointer) ([]string, KeptReports) { nodeType, read, diags := TakeString(unmodeled, xml.Node, "nodeType", definedNodeType, doc, owner, "xml") + reports := ReportsOf(EntryKey("xml", "nodeType"), diags...) if !read { - return nil, diags + return nil, reports } if nodeType == "" { - return []string{"nodeType"}, diags + return []string{"nodeType"}, reports } if xml.Attribute != nil && *xml.Attribute != (nodeType == "attribute") { hints.Attribute = nil at := doc.At(owner + ids.Ptr("attribute")) - PreserveInto(unmodeled, "openapi:xml/attribute", ir.RawValue(strconv.FormatBool(*xml.Attribute)), - ir.ReasonDegradedLowering, at) - diags = append(diags, diag.Newf(ir.SeverityWarning, diag.DegradedConstruct, at, + key := EntryKey("xml", "attribute") + KeepInto(unmodeled, key, ir.RawValue(strconv.FormatBool(*xml.Attribute)), ir.ReasonDegradedLowering, at) + reports = append(reports, ReportsOf(key, diag.Newf(ir.SeverityWarning, diag.DegradedConstruct, at, "attribute contradicts nodeType %q, which replaces it; nodeType is placed and attribute "+ - "kept verbatim under Unmodeled", nodeType)) + "kept verbatim under Unmodeled", nodeType))...) } hints.NodeType = nodeType - return []string{"nodeType"}, diags + return []string{"nodeType"}, reports } -// definedNodeType reports whether v is a node type OpenAPI 3.2 defines, the -// domain ir.XMLHints.NodeType holds. -func definedNodeType(v string) bool { - switch v { +// definedNodeType reports whether typeName is a node type OpenAPI 3.2 +// defines, the domain ir.XMLHints.NodeType holds. +func definedNodeType(typeName string) bool { + switch typeName { case "element", "attribute", "text", "cdata", "none": return true } @@ -516,7 +493,7 @@ func definedNodeType(v string) bool { // instead of modelling, each under the reason saying which it is // (docs/ir/unmodeled.md#reasons): validation logic the IR draws a boundary // against (docs/ir/boundaries.md#validation-only-constructs), and JSON Schema -// resource/dialect metadata the IR excludes on purpose. own and closure are +// resource/dialect metadata the IR excludes on purpose. role and typed are // readLocal's. // // The content vocabulary is not read here even though it is data with an IR @@ -524,15 +501,15 @@ func definedNodeType(v string) bool { // ir.Encoding depends on what the position lowered to, which only the schema // package can answer — schema.recordUnplacedContent asks the node that was // built rather than the keyword that was written. -func unmodeledAt(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, own bool, dialect Dialect, - closure bool, -) (ir.Unmodeled, []ir.Provenance, []ir.Diagnostic) { - vOnly, unpreserved, diags := validationOnlyAt(schema, pointer, doc, dialect, own, closure) - if !own { - return vOnly, unpreserved, diags - } - kept, dDiags := dialectAt(schema, pointer, doc, dialect) - return MergeUnmodeled(vOnly, kept), unpreserved, append(diags, dDiags...) +func unmodeledAt(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, role SchemaRole, dialect Dialect, + typed Typed, +) (ir.Unmodeled, []ir.Provenance, KeptReports) { + vOnly, unpreserved, reports := validationOnlyAt(schema, pointer, doc, dialect, role, typed) + if role != PositionSchema { + return vOnly, unpreserved, reports + } + kept, dialectReports := dialectAt(schema, pointer, doc, dialect) + return MergeUnmodeled(vOnly, kept), unpreserved, append(reports, dialectReports...) } // dialectKeywords are the JSON Schema resource and dialect keywords the IR @@ -547,15 +524,11 @@ func unmodeledAt(schema *statement.Schema, pointer jsontext.Pointer, doc provena // `$schema` as the dialect a schema it roots is read in. var dialectKeywords = [...]string{"$id", "$schema", "$vocabulary"} -// DialectKeywords yields the JSON Schema resource and dialect keywords the IR -// keeps out of scope (dialectKeywords). Each reader ranges over its own -// sequence, so none can change what another reads. -func DialectKeywords() iter.Seq[string] { return slices.Values(dialectKeywords[:]) } - -// DialectKeyword reports whether keyword is one of DialectKeywords. +// DialectKeyword reports whether keyword is one of the JSON Schema resource and +// dialect keywords the IR keeps out of scope (dialectKeywords). func DialectKeyword(keyword string) bool { return slices.Contains(dialectKeywords[:], keyword) } -// dialectRead is what keyword, one of DialectKeywords or draft 4's `id`, is +// dialectRead is what keyword, one of dialectKeywords or draft 4's `id`, is // read for beyond being kept, its schema's dialect reading its identifier as // dialect says: an identifier for reference resolution alone, and for nothing // where the dialect ignores it, or spells it `id` and keyword is `$id`; @@ -581,28 +554,28 @@ func dialectRead(keyword string, dialect Dialect) string { // dialectAt keeps each dialect keyword schema declares verbatim and announces // it, so the exclusion is visible in the output rather than only in this -// comment: those DialectKeywords names, and draft 4's `id` where dialect says +// comment: those dialectKeywords names, and draft 4's `id` where dialect says // schema is read in a dialect spelling its identifier so. -func dialectAt(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, dialect Dialect) (ir.Unmodeled, []ir.Diagnostic) { +func dialectAt(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, dialect Dialect) (ir.Unmodeled, KeptReports) { var unmodeled ir.Unmodeled - var diags []ir.Diagnostic + var reports KeptReports if dialect.Identifier == "id" { - diags = append(diags, KeepDialectKeyword(&unmodeled, schema, "id", pointer, doc, dialect)...) + reports = append(reports, ReportsOf(EntryKey("", "id"), KeepDialectKeyword(&unmodeled, schema, "id", pointer, doc, dialect)...)...) } for _, keyword := range dialectKeywords { - diags = append(diags, KeepDialectKeyword(&unmodeled, schema, keyword, pointer, doc, dialect)...) + reports = append(reports, ReportsOf(EntryKey("", keyword), KeepDialectKeyword(&unmodeled, schema, keyword, pointer, doc, dialect)...)...) } - return unmodeled, diags + return unmodeled, reports } -// KeepDialectKeyword keeps keyword, one of DialectKeywords or draft 4's `id`, +// KeepDialectKeyword keeps keyword, one of dialectKeywords or draft 4's `id`, // verbatim on unmodeled where schema, the schema at pointer, writes it, out of // scope, and announces it at the keyword, as dialectAt does for each one a site // writes. func KeepDialectKeyword(unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, pointer jsontext.Pointer, doc provenance.Doc, dialect Dialect, ) []ir.Diagnostic { - kept, diags := PreserveSchemaKeyword(unmodeled, schema, keyword, ir.ReasonOutOfScope, pointer, doc) + kept, diags := KeepSchemaKeyword(unmodeled, schema, keyword, ir.ReasonOutOfScope, pointer, doc) if !kept { return diags } @@ -640,18 +613,18 @@ func schemaExamplesAt(schema *statement.Schema, pointer jsontext.Pointer, doc pr // AppendExample converts node into proto's value and appends the result to out. // An unconvertible node is skipped and yields a warning diagnostic for the // caller to record: an example is an annotation, not a structural hole, so -// losing it is fine as long as it is not silent. proto carries the annotations +// losing it is fine as long as a diagnostic reports it. proto carries the annotations // around the value (name, summary, description); base and seg locate the node, // joined into a pointer only on the failure path. func AppendExample(out []ir.Example, proto ir.Example, node *yaml.Node, doc provenance.Doc, base jsontext.Pointer, seg ...string, ) ([]ir.Example, []ir.Diagnostic) { - irValue, err := value.FromNode(node) + result, err := value.FromNode(node) if err != nil { return out, []ir.Diagnostic{diag.Newf(ir.SeverityWarning, diag.DegradedConstruct, doc.At(base+ids.Ptr(seg...)), "example: %s", err.Error())} } - proto.Value = &irValue + proto.Value = &result return append(out, proto), nil } @@ -668,7 +641,8 @@ func (k Kind) String() string { } } -// notesIn returns what schema says of itself, nil for none. +// notesIn returns what schema says of itself, nil for none or a nil schema. It +// is no method of statement.Schema, to keep that type under the method cap. func notesIn(schema *statement.Schema) *statement.Notes { if schema == nil { return nil @@ -676,7 +650,8 @@ func notesIn(schema *statement.Schema) *statement.Notes { return schema.Notes } -// extensionsIn returns the extensions schema writes, nil for none. +// extensionsIn returns the extensions schema writes, nil for none or a nil +// schema; a function for notesIn's reason. func extensionsIn(schema *statement.Schema) []statement.Extension { if schema == nil { return nil diff --git a/compilers/openapi/internal/annotation/annotation_internal_test.go b/compilers/openapi/internal/annotation/annotation_internal_test.go index 37489b37b..267bfe5dd 100644 --- a/compilers/openapi/internal/annotation/annotation_internal_test.go +++ b/compilers/openapi/internal/annotation/annotation_internal_test.go @@ -5,7 +5,6 @@ package annotation import ( "encoding/json/jsontext" - "slices" "strings" "testing" @@ -26,13 +25,14 @@ import ( // TestAnnotations_SiteOverridesReferent pins the precedence rule of // docs/compilers/openapi.md#ref-use-site at the one place it is now decided. An // annotation written beside a $ref describes the position; the target's is the -// fallback, not the winner. +// fallback, not the one chosen. func TestAnnotations_SiteOverridesReferent(t *testing.T) { t.Parallel() ref := &oas3.Schema{Description: new("SiteDesc")} tgt := &oas3.Schema{Description: new("TargetDesc"), Deprecated: new(true)} - got, diags := Read(SchemaPositionAnnotationSources{Kind: Reference, Node: standaloneSchema(ref), Referents: []*statement.Schema{standaloneSchema(tgt)}}, "/p", sourced(0)) + got, diagsReports := Read(SchemaPositionAnnotationSources{Kind: Reference, Node: standaloneSchema(ref), Referents: []*statement.Schema{standaloneSchema(tgt)}}, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, diags) assert.Equal(t, "SiteDesc", got.Docs.Description, "the site's own description wins") @@ -55,59 +55,13 @@ func TestAnnotations_DeclarationIgnoresAnyReferent(t *testing.T) { assert.False(t, got.Deprecated) } -// TestAnnotations_AFoldedEntryReadsAsTheSiteDoes pins what a foldedEntry -// lends a site: each annotation it writes, read at its own pointer, under what -// the site writes itself, and over its referents. -func TestAnnotations_AFoldedEntryReadsAsTheSiteDoes(t *testing.T) { - t.Parallel() - node := schemaFromYAML(t, "description: site\nx-site: 1\n") - foldedEntry := FoldedAllOfEntry{At: "/p/allOf/1", Node: standaloneSchema(schemaFromYAML(t, `description: voice -title: voice -deprecated: true -format: password -xml: {name: voiced} -example: 1 -x-kept: 1 -x-site: 1 -not: {type: string} -`))} - second := FoldedAllOfEntry{At: "/p/allOf/2", Node: standaloneSchema(schemaFromYAML(t, `example: 2 -xml: {name: other} -x-kept: 2 -$id: 'https://example.com/s' -discriminator: {propertyName: kind, x-d: 1} -`))} - referent := schemaFromYAML(t, "title: referent\nexternalDocs: {url: 'https://x'}\n") - - got, _ := Read(SchemaPositionAnnotationSources{Kind: Reference, Node: standaloneSchema(node), FoldedAllOfEntries: []FoldedAllOfEntry{foldedEntry, second}, - Referents: []*statement.Schema{standaloneSchema(referent)}}, "/p", sourced(0)) - - assert.Equal(t, "site", got.Docs.Description, "the site writes one") - assert.Equal(t, "voice", got.Docs.Summary, "a voice is nearer than a referent") - assert.Len(t, got.Docs.ExternalDocs, 1, "and a referent speaks where neither does") - assert.True(t, got.Deprecated) - assert.True(t, got.Sensitive) - require.NotNil(t, got.XML) - assert.Equal(t, "voiced", got.XML.Name, "the first to write it") - require.Len(t, got.Examples, 1, "the first to write them") - assert.Equal(t, jsontext.Pointer("/p"), got.Unmodeled["openapi:x-kept"].Provenance.Pointer, - "two voices write it, so it is the site's, at the site's pointer") - assert.Equal(t, jsontext.Pointer("/p/allOf/1/not"), got.Unmodeled["openapi:not"].Provenance.Pointer, - "one voice writes it, at the pointer it is written at") - assert.Equal(t, jsontext.Pointer("/p/x-site"), got.Unmodeled["openapi:x-site"].Provenance.Pointer, - "the site writes it too, so it stays the site's own") - assert.Contains(t, got.Unmodeled, "openapi:not") - assert.NotContains(t, got.Unmodeled, "openapi:$id", "a voice's residue keeps what no fold reads") - assert.NotContains(t, got.Unmodeled, "openapi:discriminator/x-d") -} - // TestSchemaPositionAnnotationSources_ChainIsNearestFirst pins the order // everything a site falls back to is read in, and that a declaration has no // referent in it. func TestSchemaPositionAnnotationSources_ChainIsNearestFirst(t *testing.T) { t.Parallel() node, foldedEntry, referent := standaloneSchema(&oas3.Schema{}), standaloneSchema(&oas3.Schema{}), standaloneSchema(&oas3.Schema{}) - st := SchemaPositionAnnotationSources{Kind: Reference, Node: node, FoldedAllOfEntries: []FoldedAllOfEntry{{Node: foldedEntry}}, Referents: []*statement.Schema{referent}} + st := SchemaPositionAnnotationSources{Kind: Reference, Node: node, FlattenedAllOfEntries: []FlattenedAllOfEntry{{Node: foldedEntry}}, Referents: []*statement.Schema{referent}} assertSameSchemas(t, []*statement.Schema{node, foldedEntry, referent}, st.Chain()) st.Kind = Declaration assertSameSchemas(t, []*statement.Schema{node, foldedEntry}, st.Chain()) @@ -143,7 +97,8 @@ func TestAnnotations_RedactionFromTheSiteOrItsReferent(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - got, diags := Read(tc.site, "/p", sourced(0)) + got, diagsReports := Read(tc.site, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, diags) assert.Equal(t, tc.want, got.Sensitive) }) @@ -158,7 +113,8 @@ func TestAnnotations_ReadsEverySiteLocalAspect(t *testing.T) { XML: &oas3.XML{Name: new("Q")}, Example: openapitest.YAMLNode(t, "hello"), } - got, diags := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(node)}, "/components/schemas/S", sourced(0)) + got, diagsReports := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(node)}, "/components/schemas/S", sourced(0)) + diags := diagsReports.Diagnostics() assert.Equal(t, "D", got.Docs.Description) require.NotNil(t, got.XML) @@ -188,9 +144,10 @@ func TestSchemaExamplesAt_UnconvertibleValueIsReportedNotDropped(t *testing.T) { // "the field is missing for now". func TestDialectAt_KeepsEachKeywordOutOfScope(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "$id: 'urn:example:a'\n$schema: 'https://example.com/dialect'\ntype: string\n") + schema := schemaFromYAML(t, "$id: 'urn:example:a'\n$schema: 'https://example.com/dialect'\ntype: string\n") - got, diags := dialectAt(standaloneSchema(s), "/components/schemas/S", sourced(0), Dialect{}) + got, diagsReports := dialectAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), Dialect{}) + diags := diagsReports.Diagnostics() require.Len(t, got, 2, "one entry per keyword written") for _, keyword := range []string{"$id", "$schema"} { @@ -199,10 +156,8 @@ func TestDialectAt_KeepsEachKeywordOutOfScope(t *testing.T) { assert.Equal(t, ir.ReasonOutOfScope, entry.Reason) } assert.Len(t, diags, 2, "each exclusion is announced where it was written") - assert.True(t, slices.ContainsFunc(slices.Collect(DialectKeywords()), func(keyword string) bool { - _, read := standaloneSchema(s).Key(keyword) - return read - }), "and the keys the hoist gate reads agree a node is needed to hold them") + assert.ElementsMatch(t, []string{"$id", "$schema", "$vocabulary"}, dialectKeywords[:], + "a keyword joining or leaving the exclusion must be decided here too") } // TestDialectAt_SaysWhatEachKeywordIsReadFor pins what the info at each kept @@ -211,9 +166,10 @@ func TestDialectAt_KeepsEachKeywordOutOfScope(t *testing.T) { // for nothing (docs/compilers/openapi.md#dialect-keywords). func TestDialectAt_SaysWhatEachKeywordIsReadFor(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "$id: 'urn:example:a'\n$schema: 'https://example.com/dialect'\n"+ + schema := schemaFromYAML(t, "$id: 'urn:example:a'\n$schema: 'https://example.com/dialect'\n"+ "$vocabulary: {'https://example.com/v': true}\ntype: string\n") - _, diags := dialectAt(standaloneSchema(s), "/components/schemas/S", sourced(0), Dialect{}) + _, diagsReports := dialectAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), Dialect{}) + diags := diagsReports.Diagnostics() require.Len(t, diags, 3) said := map[jsontext.Pointer]string{} for _, diagnostic := range diags { @@ -232,9 +188,10 @@ func TestDialectAt_SaysWhatEachKeywordIsReadFor(t *testing.T) { // of. func TestDialectAt_ReadsTheIdentifierTheDialectSpells(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "id: 'urn:example:a'\n$id: 'urn:example:b'\ntype: string\n") + schema := schemaFromYAML(t, "id: 'urn:example:a'\n$id: 'urn:example:b'\ntype: string\n") saidOf := func(dialect Dialect) (ir.Unmodeled, map[jsontext.Pointer]string) { - got, diags := dialectAt(standaloneSchema(s), "/components/schemas/S", sourced(0), dialect) + got, diagsReports := dialectAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), dialect) + diags := diagsReports.Diagnostics() said := map[jsontext.Pointer]string{} for _, diagnostic := range diags { said[diagnostic.Provenance.Pointer] = diagnostic.Message @@ -250,7 +207,7 @@ func TestDialectAt_ReadsTheIdentifierTheDialectSpells(t *testing.T) { _, said = saidOf(Dialect{Identifier: "id", IdentifierIgnored: true}) assert.Contains(t, said["/components/schemas/S/id"], "is read for nothing, as this schema's dialect ignores") assert.Contains(t, said["/components/schemas/S/$id"], "spells an identifier id") - plain, _ := dialectAt(standaloneSchema(s), "/components/schemas/S", sourced(0), Dialect{}) + plain, _ := dialectAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), Dialect{}) assert.NotContains(t, plain, "openapi:id", "where `$id` is the identifier, `id` is an unknown keyword's to keep") } @@ -260,9 +217,10 @@ func TestDialectAt_ReadsTheIdentifierTheDialectSpells(t *testing.T) { // at its own pointer rather than at the schema's. func TestDialectAt_AttributesTheKeywordRatherThanTheSchema(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "$id: 'urn:example:a'\ntype: string\n") + schema := schemaFromYAML(t, "$id: 'urn:example:a'\ntype: string\n") - got, diags := dialectAt(standaloneSchema(s), "/components/schemas/S", overlaid("/components/schemas/S/$id"), Dialect{}) + got, diagsReports := dialectAt(standaloneSchema(schema), "/components/schemas/S", overlaid("/components/schemas/S/$id"), Dialect{}) + diags := diagsReports.Diagnostics() entry, ok := got["openapi:$id"] require.True(t, ok) @@ -290,9 +248,9 @@ func schemaFromYAML(t *testing.T, body string) *oas3.Schema { valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader(body), &js) require.NoError(t, err) require.Empty(t, valErrs, "the fixture parses cleanly") - s := js.GetSchema() - require.NotNil(t, s, "the fixture is a schema, not a bare boolean") - return s + schema := js.GetSchema() + require.NotNil(t, schema, "the fixture is a schema, not a bare boolean") + return schema } // TestKind_String covers both named values and the default case, so an @@ -312,9 +270,10 @@ func TestKind_String(t *testing.T) { // told the key was read, so it is not announced as undefined. func TestRead_NodeTypeIsReadFromTheRawXMLObject(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nxml:\n name: q\n nodeType: attribute\n") + schema := schemaFromYAML(t, "type: string\nxml:\n name: q\n nodeType: attribute\n") - got, diags := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(s)}, "/components/schemas/S", sourced(0)) + got, diagsReports := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(schema)}, "/components/schemas/S", sourced(0)) + diags := diagsReports.Diagnostics() require.NotNil(t, got.XML) assert.Equal(t, "q", got.XML.Name, "the modelled fields still come from the model") @@ -328,9 +287,10 @@ func TestRead_NodeTypeIsReadFromTheRawXMLObject(t *testing.T) { // to carry it. func TestRead_NodeTypeWithNoXMLObjectHasNothingToFill(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\n") + schema := schemaFromYAML(t, "type: string\n") - got, diags := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(s)}, "/components/schemas/S", sourced(0)) + got, diagsReports := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(schema)}, "/components/schemas/S", sourced(0)) + diags := diagsReports.Diagnostics() assert.Nil(t, got.XML) assert.Empty(t, diags) @@ -368,8 +328,9 @@ func TestRead_NodeTypeOnlyADefinedValueIsPlaced(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nxml: "+tc.xml+"\n") - got, diags := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(s)}, "/components/schemas/S", sourced(0)) + schema := schemaFromYAML(t, "type: string\nxml: "+tc.xml+"\n") + got, diagsReports := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(schema)}, "/components/schemas/S", sourced(0)) + diags := diagsReports.Diagnostics() require.NotNil(t, got.XML) assert.Equal(t, tc.nodeType, got.XML.NodeType) assert.Equal(t, tc.attr, got.XML.Attribute, "the attribute flag, placed only where no nodeType contradicts it") @@ -394,9 +355,10 @@ func TestRead_NodeTypeOnlyADefinedValueIsPlaced(t *testing.T) { // under, and left for the rule table to report, as an OpenAPI object's is. func TestRead_SubObjectsKeepTheKeysTheirModelsLeaveOut(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\nxml: {name: s, a: 1}\n"+ + schema := schemaFromYAML(t, "type: object\nxml: {name: s, a: 1}\n"+ "discriminator: {propertyName: k, b: 2}\nexternalDocs: {url: 'https://x', c: 3}\n") - got, diags := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(s)}, "/S", sourced(0)) + got, diagsReports := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: standaloneSchema(schema)}, "/S", sourced(0)) + diags := diagsReports.Diagnostics() for key, want := range map[string]string{ "openapi:xml/a": "1", "openapi:discriminator/b": "2", "openapi:externalDocs/c": "3", } { @@ -450,7 +412,8 @@ func TestAt_ClassifiesEveryPositionShape(t *testing.T) { assert.Equal(t, Declaration, got.Kind) assert.Nil(t, statement.Parsed(got.Node)) assert.Nil(t, got.Referents) - set, diags := Read(got, "/p", sourced(0)) + set, diagsReports := Read(got, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, set.Unmodeled, "and reads as declaring nothing") assert.Empty(t, diags) }) @@ -563,11 +526,11 @@ func TestEffectiveDeprecated_AnySchemaDeprecates(t *testing.T) { // $ref that hoists it — must not end up with two copies of its externalDocs. func TestFillTypeDocs_AssignsRatherThanAccumulates(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "title: T\ndescription: D\nexternalDocs: {url: 'https://x', description: E}\n") + schema := schemaFromYAML(t, "title: T\ndescription: D\nexternalDocs: {url: 'https://x', description: E}\n") var docs ir.Docs - FillTypeDocs(&docs, standaloneSchema(s)) - FillTypeDocs(&docs, standaloneSchema(s)) + FillTypeDocs(&docs, standaloneSchema(schema)) + FillTypeDocs(&docs, standaloneSchema(schema)) assert.Equal(t, "T", docs.Summary) assert.Equal(t, "D", docs.Description) @@ -575,7 +538,7 @@ func TestFillTypeDocs_AssignsRatherThanAccumulates(t *testing.T) { } // TestFillTypeDocs_AnAbsentFieldOverwritesNothing pins the other half: a schema -// that writes no title must leave one already read from a referent standing, +// that writes no title must leave one already read from a referent in place, // which is what makes the field-by-field merge in FillCarrierDocs work. func TestFillTypeDocs_AnAbsentFieldOverwritesNothing(t *testing.T) { t.Parallel() @@ -611,9 +574,9 @@ func TestXMLHints_ReadsEveryFieldDirectly(t *testing.T) { t.Parallel() assert.Nil(t, XMLHints(nil)) - s := schemaFromYAML(t, "type: string\nxml: {name: n, namespace: ns, prefix: p, wrapped: true, attribute: true}\n") + schema := schemaFromYAML(t, "type: string\nxml: {name: n, namespace: ns, prefix: p, wrapped: true, attribute: true}\n") assert.Equal(t, &ir.XMLHints{Name: "n", Namespace: "ns", Prefix: "p", Wrapped: new(true), Attribute: new(true)}, - XMLHints(standaloneSchema(s).XML())) + XMLHints(standaloneSchema(schema).XML())) bare := schemaFromYAML(t, "type: string\nxml: {}\n") assert.Equal(t, &ir.XMLHints{}, XMLHints(standaloneSchema(bare).XML()), "an empty xml object invents nothing") @@ -632,9 +595,9 @@ func TestXMLHints_ReadsEveryFieldDirectly(t *testing.T) { // are separate keywords rather than aliases. func TestSchemaExamplesAt_ReadsBothKeywordsInOrder(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nexample: one\nexamples: [two, three]\n") + schema := schemaFromYAML(t, "type: string\nexample: one\nexamples: [two, three]\n") - got, diags := schemaExamplesAt(standaloneSchema(s), "/components/schemas/S", sourced(0)) + got, diags := schemaExamplesAt(standaloneSchema(schema), "/components/schemas/S", sourced(0)) assert.Empty(t, diags) require.Len(t, got, 3) @@ -650,9 +613,9 @@ func TestSchemaExamplesAt_ReadsBothKeywordsInOrder(t *testing.T) { // because the diagnostic is located at the example's own pointer. func TestSchemaExamplesAt_AttributesAnUnconvertibleExampleAtItsPointer(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: number\nexample: .nan\n") + schema := schemaFromYAML(t, "type: number\nexample: .nan\n") - got, diags := schemaExamplesAt(standaloneSchema(s), "/S", overlaid("/S/example")) + got, diags := schemaExamplesAt(standaloneSchema(schema), "/S", overlaid("/S/example")) assert.Empty(t, got, "an unconvertible example yields no value") require.Len(t, diags, 1) @@ -680,7 +643,7 @@ func TestAppendExample_ConvertsAndAppends(t *testing.T) { // TestAppendExample_UnconvertibleValueIsReported pins the other half: a node // that cannot become a value adds nothing to the list, and the pointer it is // reported at is built from the base and the segments — which is the only path -// that joins them, so a wrong join shows up nowhere else. +// that combines them, so a wrong combination shows up nowhere else. func TestAppendExample_UnconvertibleValueIsReported(t *testing.T) { t.Parallel() nan := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!float", Value: ".nan"} @@ -721,45 +684,36 @@ func standalone(js *oas3.JSONSchema[oas3.Referenceable]) *statement.Statement { // standaloneSchema is standalone for a schema object decoded alone, nil for a // nil s. -func standaloneSchema(s *oas3.Schema) *statement.Schema { - if s == nil { +func standaloneSchema(schema *oas3.Schema) *statement.Schema { + if schema == nil { return nil } - return standalone(oas3.NewJSONSchemaFromSchema[oas3.Referenceable](s)).Schema + return standalone(oas3.NewJSONSchemaFromSchema[oas3.Referenceable](schema)).Schema } -// TestRead_AKeywordWrittenAlikeIsKeptAndReportedOnce pins one writing two -// schemas of a site write: an entry the site keeps is the site's alone, so a -// voice writing it draws no second report, a keyword of several folded in one -// entry among them; and a keyword the site leaves to an allOf entry its position -// keeps whole (SchemaPositionAnnotationSources.Leaves) is kept and reported by -// neither reading here. -func TestRead_AKeywordWrittenAlikeIsKeptAndReportedOnce(t *testing.T) { +// TestReadKeeps_AsksWhatReadKeepsOfTheSchemaAlone pins ReadKeeps to each kind +// of thing Read keeps of a schema written at a declaration, and to false for +// one writing only what Read reads none of. +func TestReadKeeps_AsksWhatReadKeepsOfTheSchemaAlone(t *testing.T) { t.Parallel() - const written = "not: {type: string}\nif: {type: string}\nthen: {minLength: 1}\nx-a: 1\n" - site := standaloneSchema(schemaFromYAML(t, written)) - foldedEntry := FoldedAllOfEntry{At: "/p/allOf/0", Node: standaloneSchema(schemaFromYAML(t, written+"propertyNames: {maxLength: 3}\n"))} - - got, diags := Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: site, FoldedAllOfEntries: []FoldedAllOfEntry{foldedEntry}}, "/p", sourced(0)) - assert.Contains(t, got.Unmodeled, "openapi:not") - assert.Contains(t, got.Unmodeled, "openapi:if-then-else") - assert.Equal(t, jsontext.Pointer("/p/allOf/0/propertyNames"), got.Unmodeled["openapi:propertyNames"].Provenance.Pointer) - at := map[jsontext.Pointer]int{} - for _, diagnostic := range diags { - at[diagnostic.Provenance.Pointer]++ + for _, tc := range []struct { + name, body string + want bool + }{ + {"a bound, which Read reads none of", "type: string\nminLength: 1\n", false}, + {"a title", "title: Named\n", true}, + {"external docs", "externalDocs: {url: 'https://example.com'}\n", true}, + {"a deprecation", "deprecated: true\n", true}, + {"a redaction", "type: string\nformat: password\n", true}, + {"XML hints", "xml: {name: n}\n", true}, + {"an example", "example: 1\n", true}, + {"an extension", "x-acme: 1\n", true}, + {"a validation-only keyword", "not: {type: string}\n", true}, + {"a dialect keyword", "$id: 'urn:example:a'\n", true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, ReadKeeps(standaloneSchema(schemaFromYAML(t, tc.body)), Dialect{})) + }) } - assert.Equal(t, map[jsontext.Pointer]int{"/p": 2, "/p/allOf/0": 1}, at, "the site reports its two, the voice the one it alone writes") - - got, diags = Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: site, Leaves: []string{"not", "x-a", "title", "if"}}, "/p", sourced(0)) - assert.NotContains(t, got.Unmodeled, "openapi:not") - assert.NotContains(t, got.Unmodeled, "openapi:x-a") - assert.Contains(t, got.Unmodeled, "openapi:if-then-else", "an entry of several keywords is kept while it leaves but one") - assert.Len(t, diags, 1) - - both := standaloneSchema(schemaFromYAML(t, written+"contains: {type: string}\nminContains: 2\n")) - got, diags = Read(SchemaPositionAnnotationSources{Kind: Declaration, Node: both, Leaves: []string{"if", "then", "contains", "minContains"}}, "/p", sourced(0)) - assert.NotContains(t, got.Unmodeled, "openapi:if-then-else", "and left where it leaves every one it writes") - assert.NotContains(t, got.Unmodeled, "openapi:contains") - assert.Contains(t, got.Unmodeled, "openapi:not") - assert.Len(t, diags, 1) } diff --git a/compilers/openapi/internal/annotation/constraints.go b/compilers/openapi/internal/annotation/constraints.go index 67c27e205..20e48dcb8 100644 --- a/compilers/openapi/internal/annotation/constraints.go +++ b/compilers/openapi/internal/annotation/constraints.go @@ -51,19 +51,19 @@ const ( // BigVal holds, an exclusive bound in the other form than exclusiveBoolean // selects, or a count the model misreads (ExactCount) is skipped, for the rule // table's check to report (docs/compilers/openapi.md#constraints) or the caller -// to keep. The second return holds a 3.0 exclusive modifier with no bound -// beside it (applyExclusiveFlag), placed by pointer and doc. -func Constraints(schema *statement.Schema, take Bounds, exclusiveBoolean bool, pointer jsontext.Pointer, doc provenance.Doc) (*ir.Constraints, ir.Unmodeled, []ir.Diagnostic) { +// to keep. It keeps, placed by pointer and doc and reported under its key, a +// 3.0 exclusive modifier with no bound beside it (applyExclusiveFlag). +func Constraints(schema *statement.Schema, take Bounds, exclusiveBoolean bool, pointer jsontext.Pointer, doc provenance.Doc) (*ir.Constraints, ir.Unmodeled, KeptReports) { if schema == nil || schema.Truth != statement.Stated { return nil, nil, nil } constraints := &ir.Constraints{} - residue := boundResidue{pointer: pointer, doc: doc} - var diags []ir.Diagnostic + keeping := keptBounds{pointer: pointer, doc: doc} + var diags KeptReports if take&NumberBounds != 0 { numericBounds(constraints, schema) - diags = applyExclusive(constraints, schema, minBound, &residue, exclusiveBoolean) - diags = append(diags, applyExclusive(constraints, schema, maxBound, &residue, exclusiveBoolean)...) + diags = applyExclusive(constraints, schema, minBound, &keeping, exclusiveBoolean) + diags = append(diags, applyExclusive(constraints, schema, maxBound, &keeping, exclusiveBoolean)...) } if take&StringBounds != 0 && schema.Text != nil { constraints.MinLength = ExactCount(schema, "minLength", schema.Text.MinLength) @@ -75,9 +75,9 @@ func Constraints(schema *statement.Schema, take Bounds, exclusiveBoolean bool, p constraints.MaxProperties = ExactCount(schema, "maxProperties", schema.Object.MaxProperties) } if emptyConstraints(constraints) { - return nil, residue.kept, diags + return nil, keeping.kept, diags } - return constraints, residue.kept, diags + return constraints, keeping.kept, diags } // ExactCount returns the count the integer keyword schema writes states, where the @@ -102,15 +102,15 @@ func ExactCount(schema *statement.Schema, keyword string, count *int64) *int64 { return nil } // Within int64, the digits and the zeros the exponent adds are at most 19. - var v int64 + var spelled int64 zeros := max(int(stated.Exponent())+1-len(stated.Digits()), 0) - for _, d := range stated.Digits() + strings.Repeat("0", zeros) { - v = v*10 + int64(d-'0') + for _, digit := range stated.Digits() + strings.Repeat("0", zeros) { + spelled = spelled*10 + int64(digit-'0') } - if v == *count { + if spelled == *count { return count } - return &v + return &spelled } // CountIsExact reports whether the integer keyword schema writes states a @@ -119,17 +119,17 @@ func CountIsExact(schema *statement.Schema, keyword string, count *int64) bool { return ExactCount(schema, keyword, count) != nil } -// boundResidue is where a schema's bounds were written, and what became of a +// keptBounds is where a schema's bounds were written, and what became of a // bound keyword that reached no field of ir.Constraints. // -// One value serves both sides, so a schema leaving residue on each leaves two +// One value serves both sides, so a schema leaving a kept bound on each leaves two // entries and each keyword survives; writing the map rather than adding to it // would keep whichever side ran second. // // The keyword is recorded here, not handed back, so the diagnostic naming it is // written at the statement that keeps it. Announcing a preservation elsewhere -// is how a message comes to claim one that never happened (GitHub #144). -type boundResidue struct { +// is how a message comes to assert one that never happened (GitHub #144). +type keptBounds struct { pointer jsontext.Pointer doc provenance.Doc kept ir.Unmodeled @@ -141,8 +141,8 @@ type boundResidue struct { // The literal is the boolean the keyword was written as, which is the whole of // what it said; there is no numeric bound here to write back, because the // absence of one is the reason it is being kept at all. -func (b *boundResidue) keepUnmodifiable(inclProperty, exclProperty string) ir.Diagnostic { - PreserveInto(&b.kept, "openapi:"+exclProperty, ir.RawValue("true"), +func (b *keptBounds) keepUnmodifiable(inclProperty, exclProperty string) ir.Diagnostic { + KeepInto(&b.kept, EntryKey("", exclProperty), ir.RawValue("true"), ir.ReasonDegradedLowering, b.doc.At(b.pointer+ids.Ptr(exclProperty))) return unmodifiableExclusiveDiag(inclProperty, exclProperty) } @@ -159,13 +159,13 @@ func numericBounds(constraints *ir.Constraints, schema *statement.Schema) { {"maximum", &constraints.Max}, {"multipleOf", &constraints.MultipleOf}, } - for _, b := range bounds { - node := keyNode(schema, b.property) + for _, bound := range bounds { + node := keyNode(schema, bound.property) if node == nil { continue } if bigVal, err := value.NumericLiteral(node); err == nil { - *b.dst = &bigVal + *bound.dst = &bigVal } } } @@ -178,7 +178,7 @@ func numericBounds(constraints *ir.Constraints, schema *statement.Schema) { // exclusiveBoolean is true for 3.0's dialect and draft 4's. A value in the // wrong form for the dialect, or a literal no decimal spells, is dropped, and // the rule table's check reports it (Constraints). -func applyExclusive(constraints *ir.Constraints, schema *statement.Schema, side boundSide, residue *boundResidue, exclusiveBoolean bool) []ir.Diagnostic { +func applyExclusive(constraints *ir.Constraints, schema *statement.Schema, side boundSide, keeping *keptBounds, exclusiveBoolean bool) KeptReports { form := exclusiveForm(schema, side) _, property := boundProperties(side) node := keyNode(schema, property) @@ -190,7 +190,7 @@ func applyExclusive(constraints *ir.Constraints, schema *statement.Schema, side return nil } if flag { - return applyExclusiveFlag(constraints, schema, side, residue, form == statement.ExclusiveTrue) + return applyExclusiveFlag(constraints, schema, side, keeping, form == statement.ExclusiveTrue) } if bigVal, err := value.NumericLiteral(node); err == nil { setExclusiveBound(constraints, side, &bigVal) @@ -221,13 +221,13 @@ func exclusiveForm(schema *statement.Schema, side boundSide) statement.Exclusive // Absence is read off the raw node, because the parsed slot is also nil for a // bound numericBounds could not read. That bound has drawn its own error, and // its modifier is dropped silently. -func applyExclusiveFlag(constraints *ir.Constraints, schema *statement.Schema, side boundSide, residue *boundResidue, flag bool) []ir.Diagnostic { +func applyExclusiveFlag(constraints *ir.Constraints, schema *statement.Schema, side boundSide, keeping *keptBounds, flag bool) KeptReports { if !flag { return nil } inclProperty, exclProperty := boundProperties(side) if keyNode(schema, inclProperty) == nil { - return []ir.Diagnostic{residue.keepUnmodifiable(inclProperty, exclProperty)} + return ReportsOf(EntryKey("", exclProperty), keeping.keepUnmodifiable(inclProperty, exclProperty)) } incl := inclusiveBound(constraints, side) if *incl == nil { diff --git a/compilers/openapi/internal/annotation/constraints_internal_test.go b/compilers/openapi/internal/annotation/constraints_internal_test.go index bdb0b47bb..668f98db7 100644 --- a/compilers/openapi/internal/annotation/constraints_internal_test.go +++ b/compilers/openapi/internal/annotation/constraints_internal_test.go @@ -21,7 +21,8 @@ import ( func TestConstraints_NilSchema(t *testing.T) { t.Parallel() - constraints, kept, diags := Constraints(nil, AllBounds, false, "/p", sourced(0)) + constraints, kept, diagsReports := Constraints(nil, AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Nil(t, constraints) assert.Nil(t, kept) assert.Nil(t, diags) @@ -49,13 +50,13 @@ func TestCountIsExact(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - s := schemaFromYAMLUnvalidated(t, "minItems: "+tc.literal) - assert.Equal(t, tc.exact, CountIsExact(standaloneSchema(s), "minItems", &tc.count)) + schema := schemaFromYAMLUnvalidated(t, "minItems: "+tc.literal) + assert.Equal(t, tc.exact, CountIsExact(standaloneSchema(schema), "minItems", &tc.count)) }) } } -// TestCountIsExact_NeedsBothReadings pins the two halves that each stand for a +// TestCountIsExact_NeedsBothReadings pins the two halves that each hold for a // keyword not written: no count from the model, and no node to hold it to. func TestCountIsExact_NeedsBothReadings(t *testing.T) { t.Parallel() @@ -65,15 +66,16 @@ func TestCountIsExact_NeedsBothReadings(t *testing.T) { func TestApplyExclusive_NumericWithoutRootNode(t *testing.T) { t.Parallel() - s := &oas3.Schema{ExclusiveMinimum: &values.EitherValue[bool, bool, float64, float64]{Right: new(5.0)}} + schema := &oas3.Schema{ExclusiveMinimum: &values.EitherValue[bool, bool, float64, float64]{Right: new(5.0)}} constraints := &ir.Constraints{} - residue := boundResidue{pointer: "/p"} - diags := applyExclusive(constraints, standaloneSchema(s), minBound, &residue, false) + keeping := keptBounds{pointer: "/p"} + diagsReports := applyExclusive(constraints, standaloneSchema(schema), minBound, &keeping, false) + diags := diagsReports.Diagnostics() // The numeric arm is taken (2020-12 dialect, numeric value) but there is no raw // node to read the exact literal from, so nothing is set and no diagnostic. assert.Nil(t, diags) assert.Nil(t, constraints.ExclusiveMin) - assert.Empty(t, residue.kept) + assert.Empty(t, keeping.kept) } // schemaFromYAMLUnvalidated parses body like schemaFromYAML but keeps the @@ -89,9 +91,9 @@ func schemaFromYAMLUnvalidated(t *testing.T, body string) *oas3.Schema { var js oas3.JSONSchema[oas3.Referenceable] _, err := marshaller.Unmarshal(t.Context(), strings.NewReader(body), &js) require.NoError(t, err) - s := js.GetSchema() - require.NotNil(t, s, "the fixture is a schema, not a bare boolean") - return s + schema := js.GetSchema() + require.NotNil(t, schema, "the fixture is a schema, not a bare boolean") + return schema } // TestConstraints_ReadsEveryScalarKeyword pins the whole scalar set in one @@ -100,10 +102,11 @@ func schemaFromYAMLUnvalidated(t *testing.T, body string) *oas3.Schema { // check below can only be right if this list and that one agree. func TestConstraints_ReadsEveryScalarKeyword(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nminimum: 1\nmaximum: 9\nmultipleOf: 3\n"+ + schema := schemaFromYAML(t, "type: string\nminimum: 1\nmaximum: 9\nmultipleOf: 3\n"+ "minLength: 2\nmaxLength: 8\npattern: '^a'\nminProperties: 1\nmaxProperties: 4\n") - got, _, diags := Constraints(standaloneSchema(s), AllBounds, false, "/p", sourced(0)) + got, _, diagsReports := Constraints(standaloneSchema(schema), AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() require.Empty(t, diags) require.NotNil(t, got) @@ -123,13 +126,14 @@ func TestConstraints_ReadsEveryScalarKeyword(t *testing.T) { // wrote. func TestConstraints_NothingDeclaredIsNilNotEmpty(t *testing.T) { t.Parallel() - got, _, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: string\n")), AllBounds, false, "/p", sourced(0)) + got, _, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: string\n")), AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Nil(t, got) assert.Empty(t, diags) - got, _, diags = Constraints(nil, AllBounds, false, "/p", sourced(0)) + got, _, diagsReports = Constraints(nil, AllBounds, false, "/p", sourced(0)) assert.Nil(t, got) - assert.Nil(t, diags) + assert.Nil(t, diagsReports) } // TestConstraints_KeepsTheExactLiteral pins the no-float64 invariant at the one @@ -137,9 +141,10 @@ func TestConstraints_NothingDeclaredIsNilNotEmpty(t *testing.T) { // float64 and a decimal float64 cannot represent both survive as written. func TestConstraints_KeepsTheExactLiteral(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: number\nminimum: 9007199254740993\nmaximum: 0.30000000000000004\n") + schema := schemaFromYAML(t, "type: number\nminimum: 9007199254740993\nmaximum: 0.30000000000000004\n") - got, _, diags := Constraints(standaloneSchema(s), AllBounds, false, "/p", sourced(0)) + got, _, diagsReports := Constraints(standaloneSchema(schema), AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() require.Empty(t, diags) require.NotNil(t, got) @@ -156,7 +161,8 @@ func TestNumericBounds_AMalformedLiteralIsDropped(t *testing.T) { for _, keyword := range []string{"minimum", "maximum", "multipleOf"} { t.Run(keyword, func(t *testing.T) { t.Parallel() - got, _, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+keyword+": .inf\n")), AllBounds, false, "/p", sourced(0)) + got, _, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+keyword+": .inf\n")), AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, diags) assert.Nil(t, got, "the bound is dropped rather than half-read") @@ -201,7 +207,8 @@ func TestApplyExclusive_BothDialects(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - got, _, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, tc.exclusiveBoolean, "/p", sourced(0)) + got, _, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, tc.exclusiveBoolean, "/p", sourced(0)) + diags := diagsReports.Diagnostics() require.Empty(t, diags) require.NotNil(t, got) @@ -236,7 +243,8 @@ func TestApplyExclusive_TheWrongFormForTheDialectIsDropped(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - got, _, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, tc.exclusiveBoolean, "/p", sourced(0)) + got, _, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, tc.exclusiveBoolean, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, diags) require.NotNil(t, got, "the sibling minimum is still read") @@ -252,7 +260,8 @@ func TestApplyExclusive_TheWrongFormForTheDialectIsDropped(t *testing.T) { // reports it (docs/compilers/openapi.md#constraints). func TestApplyExclusive_AMalformedNumericBoundIsDropped(t *testing.T) { t.Parallel() - got, _, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\nexclusiveMaximum: .inf\n")), AllBounds, false, "/p", sourced(0)) + got, _, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\nexclusiveMaximum: .inf\n")), AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, diags) assert.Nil(t, got) @@ -268,7 +277,7 @@ func TestApplyExclusive_AMalformedNumericBoundIsDropped(t *testing.T) { // change, and a revision moving only the looser keyword as none (GitHub #425). // // Nothing is kept verbatim or reported: with both keywords present there is no -// residue and no degradation. +// kept bound and no degradation. func TestConstraints_CoDeclaredBoundsBothReachAField(t *testing.T) { t.Parallel() tests := []struct { @@ -323,7 +332,8 @@ func TestConstraints_CoDeclaredBoundsBothReachAField(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - got, kept, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, false, "/p", sourced(3)) + got, kept, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, false, "/p", sourced(3)) + diags := diagsReports.Diagnostics() require.NotNil(t, got) if diff := cmp.Diff(tc.want, *got); diff != "" { @@ -342,9 +352,10 @@ func TestConstraints_CoDeclaredBoundsBothReachAField(t *testing.T) { // round or fail; ir.NewBigVal keeps the text, and both keywords keep their own. func TestConstraints_ABoundNoFloatHoldsIsCarriedVerbatim(t *testing.T) { t.Parallel() - got, kept, diags := Constraints(standaloneSchema(schemaFromYAMLUnvalidated(t, + got, kept, diagsReports := Constraints(standaloneSchema(schemaFromYAMLUnvalidated(t, "type: number\nminimum: 1.0e2000000\nexclusiveMinimum: 5\nmaximum: 1e-1000001\nexclusiveMaximum: 5\n")), AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() require.NotNil(t, got) want := ir.Constraints{ @@ -371,7 +382,8 @@ func TestConstraints_OneKeywordPerSideKeepsNothing(t *testing.T) { } { t.Run(body, func(t *testing.T) { t.Parallel() - got, kept, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+body)), AllBounds, false, "/p", sourced(0)) + got, kept, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+body)), AllBounds, false, "/p", sourced(0)) + diags := diagsReports.Diagnostics() require.NotNil(t, got) assert.Empty(t, diags) @@ -415,7 +427,8 @@ func TestApplyExclusiveFlag_ThreeZeroModifierMovesTheBound(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - got, kept, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, true, "/p", sourced(0)) + got, kept, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\n"+tc.body)), AllBounds, true, "/p", sourced(0)) + diags := diagsReports.Diagnostics() require.NotNil(t, got) if diff := cmp.Diff(tc.want, *got); diff != "" { @@ -433,12 +446,13 @@ func TestApplyExclusiveFlag_ThreeZeroModifierMovesTheBound(t *testing.T) { // so dropping one would lose a declared keyword silently. It is kept verbatim // at its own pointer and reported instead. // -// Both sides are declared because they share one boundResidue: a schema leaving -// residue on each must keep both entries. +// Both sides are declared because they share one keptBounds: a schema leaving a +// kept bound on each must keep both entries. func TestApplyExclusiveFlag_AModifierWithNoBoundIsKeptAndReported(t *testing.T) { t.Parallel() - got, kept, diags := Constraints(standaloneSchema(schemaFromYAML(t, + got, kept, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\nexclusiveMinimum: true\nexclusiveMaximum: true\n")), AllBounds, true, "/p", sourced(3)) + diags := diagsReports.Diagnostics() assert.Nil(t, got, "a modifier that bounds nothing leaves no constraint behind") require.Len(t, kept, 2, "each side keeps its own modifier; got %v", kept) @@ -467,13 +481,14 @@ func TestApplyExclusiveFlag_AModifierWithNoBoundIsKeptAndReported(t *testing.T) } // TestConstraints_AttributesAKeptModifierAtItsKeyword pins GitHub #522: a 3.0 -// exclusiveMinimum modifier kept as residue (because no minimum stands beside +// exclusiveMinimum modifier kept (because no minimum sits beside // it to make exclusive) is located at its own keyword, so an overlay that // rewrote just that keyword is who the kept entry names. func TestConstraints_AttributesAKeptModifierAtItsKeyword(t *testing.T) { t.Parallel() - _, kept, diags := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\nexclusiveMinimum: true\n")), + _, kept, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\nexclusiveMinimum: true\n")), AllBounds, true, "/p", overlaid("/p/exclusiveMinimum")) + diags := diagsReports.Diagnostics() entry, ok := kept["openapi:exclusiveMinimum"] require.True(t, ok) @@ -490,17 +505,18 @@ func TestConstraints_AttributesAKeptModifierAtItsKeyword(t *testing.T) { // to report (docs/compilers/openapi.md#constraints), so nothing is said here. func TestApplyExclusiveFlag_AnUnreadableBoundIsNotAMissingOne(t *testing.T) { t.Parallel() - got, kept, diags := Constraints(standaloneSchema(schemaFromYAML(t, + got, kept, diagsReports := Constraints(standaloneSchema(schemaFromYAML(t, "type: number\nminimum: .inf\nexclusiveMinimum: true\n")), AllBounds, true, "/p", sourced(3)) + diags := diagsReports.Diagnostics() assert.Nil(t, got, "an unreadable bound leaves no constraint behind") assert.Empty(t, kept, "the modifier modifies a bound that was written; it is no orphan") assert.Empty(t, diags, "the bad literal is the whole complaint, and it is load's") } -// TestExactCount_StatesOnlyAnExactCount pins what a reader of a count takes from -// the model: its reading where the literal states it, and none where it does -// not, so no bound stands for a number the source does not write. +// TestExactCount_StatesOnlyAnExactCount pins what a reader of a count takes +// from the model: its reading where the literal states it, and none where it +// does not, so no bound names a number the source does not write. func TestExactCount_StatesOnlyAnExactCount(t *testing.T) { t.Parallel() exact := new(int64(3)) diff --git a/compilers/openapi/internal/annotation/count_internal_test.go b/compilers/openapi/internal/annotation/count_internal_test.go index 4ca49be48..32f8a6d78 100644 --- a/compilers/openapi/internal/annotation/count_internal_test.go +++ b/compilers/openapi/internal/annotation/count_internal_test.go @@ -30,10 +30,10 @@ func TestExactCount_TakesTheCountFromItsLiteral(t *testing.T) { func TestExactCount_AFractionCostsNoMoreForAWiderExponent(t *testing.T) { // AllocsPerRun counts the whole process, so the test runs alone. allocs := func(exp string) float64 { - s := schemaFromYAMLUnvalidated(t, "minItems: 1e-"+exp) + schema := schemaFromYAMLUnvalidated(t, "minItems: 1e-"+exp) count := new(int64(0)) return testing.AllocsPerRun(3, func() { - assert.Nil(t, ExactCount(standaloneSchema(s), "minItems", count)) + assert.Nil(t, ExactCount(standaloneSchema(schema), "minItems", count)) }) } diff --git a/compilers/openapi/internal/annotation/dropped_internal_test.go b/compilers/openapi/internal/annotation/dropped_internal_test.go new file mode 100644 index 000000000..f8b97387b --- /dev/null +++ b/compilers/openapi/internal/annotation/dropped_internal_test.go @@ -0,0 +1,208 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package annotation + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ynode" + "github.com/dexpace/morphic/ir" +) + +// TestRenderDroppingExtensions_LeavesOutOnlyAnExtensionNoJSONHolds holds a +// construct kept whole to its rendering with each vendor extension whose value +// no JSON holds left out, at any depth, and that extension's pointer from the +// construct noted, an extension JSON holds and every other key kept. +func TestRenderDroppingExtensions_LeavesOutOnlyAnExtensionNoJSONHolds(t *testing.T) { + t.Parallel() + node := ynode.Map( + ynode.Scalar("b"), ynode.Scalar("1"), + ynode.Scalar("x-bad"), nanNode(), + ynode.Scalar("n"), ynode.Map(ynode.Scalar("x-deep"), nanNode(), ynode.Scalar("k"), ynode.Scalar("v")), + ynode.Scalar("x-ok"), ynode.Scalar("2"), + ) + raw, dropped, err := RenderDroppingExtensions(node) + require.NoError(t, err) + assert.JSONEq(t, `{"b":1,"n":{"k":"v"},"x-ok":2}`, string(raw)) + assert.Equal(t, []jsontext.Pointer{"/n/x-deep", "/x-bad"}, dropped) + + only, dropped, err := RenderDroppingExtensions(ynode.Map(ynode.Scalar("x-bad"), nanNode())) + require.NoError(t, err) + assert.Equal(t, "{}", string(only), "an object of nothing else is empty") + assert.Equal(t, []jsontext.Pointer{"/x-bad"}, dropped) +} + +// nanNode is a YAML float no JSON holds. +func nanNode() *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!float", Value: ".nan"} } + +// TestRenderDroppingExtensions_RefusesAnExtensionNameNoJSONHolds holds an +// extension whose value converts but whose name is no UTF-8 to a refusal of +// the whole construct, naming the key. +func TestRenderDroppingExtensions_RefusesAnExtensionNameNoJSONHolds(t *testing.T) { + t.Parallel() + raw, dropped, err := RenderDroppingExtensions(ynode.Map(ynode.Scalar("x-\xff"), ynode.Scalar("1"))) + require.Error(t, err) + assert.Contains(t, err.Error(), "mapping key") + assert.Nil(t, raw) + assert.Nil(t, dropped) +} + +// TestExtensionDroppedDiag_IsTheExtensionReadersWarningAtItsObject holds the +// report of an extension left out to the extension reader's own: a warning at +// the object holding it, naming the extension. +func TestExtensionDroppedDiag_IsTheExtensionReadersWarningAtItsObject(t *testing.T) { + t.Parallel() + got := ExtensionDroppedDiag(ir.Provenance{Source: 2, Pointer: "/components/schemas/S/x-t"}) + assert.Equal(t, ir.SeverityWarning, got.Severity) + assert.Equal(t, diag.DegradedConstruct, got.Code) + assert.Equal(t, ir.Provenance{Source: 2, Pointer: "/components/schemas/S"}, got.Provenance) + assert.Equal(t, `extension "x-t" could not be serialized`, got.Message) +} + +// TestKeepNodeInto_KeepsAConstructLessAnExtensionNoJSONHolds holds a +// construct written with an extension no JSON holds to being kept without it, +// the extension reported where it is written. +func TestKeepNodeInto_KeepsAConstructLessAnExtensionNoJSONHolds(t *testing.T) { + t.Parallel() + unmodeled := ir.Unmodeled{} + prov := ir.Provenance{Pointer: "/components/schemas/S/not"} + kept, diags := KeepNodeInto(&unmodeled, "openapi:not", ynode.Map(ynode.Scalar("type"), ynode.Scalar("string"), + ynode.Scalar("x-bad"), nanNode()), ir.ReasonValidationOnly, prov) + assert.True(t, kept) + assert.JSONEq(t, `{"type":"string"}`, string(unmodeled["openapi:not"].Value)) + require.Len(t, diags, 1) + assert.Equal(t, ExtensionDroppedDiag(ir.Provenance{Pointer: "/components/schemas/S/not/x-bad"}), diags[0]) +} + +// TestKeepSchemaKeyword_LeavesOutAnExtensionNoJSONHolds holds an extension +// keyword whose value no JSON holds to being kept nowhere, with the extension +// reader's warning, while one JSON holds is kept; ExtensionNoJSONHolds tells +// the two apart, and holds no other keyword to be such an extension. +func TestKeepSchemaKeyword_LeavesOutAnExtensionNoJSONHolds(t *testing.T) { + t.Parallel() + schema := standaloneSchema(schemaFromYAML(t, "type: string\nx-bad: .nan\nx-ok: 1\nminLength: 1\n")) + unmodeled := ir.Unmodeled{} + kept, diags := KeepSchemaKeyword(&unmodeled, schema, "x-bad", ir.ReasonVendorExtension, "/S", sourced(0)) + assert.False(t, kept) + assert.Empty(t, unmodeled) + assert.Equal(t, []ir.Diagnostic{ExtensionDroppedDiag(ir.Provenance{Pointer: "/S/x-bad"})}, diags) + + assert.True(t, ExtensionNoJSONHolds(schema, "x-bad")) + for _, keyword := range []string{"x-ok", "minLength", "x-absent"} { + assert.False(t, ExtensionNoJSONHolds(schema, keyword), keyword) + } +} + +// TestValidationOnlyOf_KeepsOnlyTheKeywordsNamed holds what an entry's +// validation-only keywords keep to those the kept keywords name: an entry +// several keywords combine into where it holds one of them, each with its +// report, and none of another, whose report goes with it. An extension no JSON +// holds inside a kept keyword is left out with its own warning. +func TestValidationOnlyOf_KeepsOnlyTheKeywordsNamed(t *testing.T) { + t.Parallel() + schema := standaloneSchema(schemaFromYAML(t, "type: array\nnot: {type: string}\nif: {minItems: 1}\nthen: {maxItems: 3}\n"+ + "contains: {type: string, x-t: .nan}\nminContains: 1\nunevaluatedItems: false\n")) + kept, unpreserved, diagsReports := ValidationOnlyOf(schema, []string{"not", "minContains", "unevaluatedItems"}, "/S", sourced(0), Dialect{}) + diags := diagsReports.Diagnostics() + + assert.Equal(t, map[string]string{ + "openapi:not": `{"type":"string"}`, + "openapi:contains": `{"contains":{"type":"string"},"minContains":1}`, + "openapi:unevaluated": `{"unevaluatedItems":false}`, + }, stringsOfKept(kept)) + assert.Empty(t, unpreserved) + var notes []string + for _, diagnostic := range diags { + if diagnostic.Code == diag.ValidationOnlyKeyword { + notes = append(notes, diagnostic.Message) + } + } + assert.ElementsMatch(t, []string{validationOnlyMessage("not"), validationOnlyMessage("contains"), validationOnlyMessage("unevaluated")}, notes, + "the note of if/then/else goes with its entry") + assert.Contains(t, diags, ExtensionDroppedDiag(ir.Provenance{Pointer: "/S/contains/x-t"})) +} + +// stringsOfKept is kept with each entry's value as a string. +func stringsOfKept(kept ir.Unmodeled) map[string]string { + out := make(map[string]string, len(kept)) + for key, entry := range kept { + out[key] = string(entry.Value) + } + return out +} + +// TestValidationOnlyKeywordsOf_NamesTheKeywordsAnEntryCombines holds each +// validation-only entry key to the keywords it holds, and an allOf entry kept +// whole to none. +func TestValidationOnlyKeywordsOf_NamesTheKeywordsAnEntryCombines(t *testing.T) { + t.Parallel() + for key, want := range map[string][]string{ + "openapi:if-then-else": {"if", "then", "else"}, + "openapi:contains": {"contains", "minContains", "maxContains"}, + "openapi:unevaluated": {"unevaluatedProperties", "unevaluatedItems"}, + "openapi:not": {"not"}, + "openapi:allOf/1": nil, + } { + assert.Equal(t, want, ValidationOnlyKeywordsOf(key), key) + } +} + +// TestEntryKeyword_NamesTheKeywordAKeyIsKeptFor holds the one reader of an +// Unmodeled key to the schema keyword its entry is kept for: its own key's, +// past an allOf entry's path, and the keyword a sub-object's key is written +// under, unescaped; and to none for an entry kept whole or another reader's key. +func TestEntryKeyword_NamesTheKeywordAKeyIsKeptFor(t *testing.T) { + t.Parallel() + for key, want := range map[string]string{ + "openapi:not": "not", + "openapi:if-then-else": "if-then-else", + "openapi:allOf/0/maxLength": "maxLength", + "openapi:allOf/1/allOf/0/minimum": "minimum", + "openapi:discriminator/x-k": "discriminator", + "openapi:$ref/1": "$ref", + "openapi:a~1b": "a/b", + "openapi:allOf/x": "allOf", + "openapi:allOf": "allOf", + "openapi:allOf/1": "", + "openapi:allOf/0/allOf/2": "", + "openapi:": "", + "vendor:not": "", + } { + got, named := EntryKeyword(key) + assert.Equal(t, want, got, key) + assert.Equal(t, want != "", named, key) + } +} + +// TestRead_AFlattenedEntryReadsAsAConjunctOfItsOwn holds what Read takes of an +// inline entry flattened into the position: its validation-only keywords kept +// apart as its own conjunct at its pointer, its xml and examples where the +// position writes none, and what it could not keep among the position's. +func TestRead_AFlattenedEntryReadsAsAConjunctOfItsOwn(t *testing.T) { + t.Parallel() + node := standaloneSchema(schemaFromYAML(t, "description: D\n")) + entry := standaloneSchema(schemaFromYAML(t, "xml: {name: Q}\nexample: 3\nnot: {type: string}\nif: {const: .nan}\nthen: {minLength: 1}\n")) + got, diagsReports := Read(SchemaPositionAnnotationSources{ + Kind: Declaration, Node: node, + FlattenedAllOfEntries: []FlattenedAllOfEntry{{Node: entry, At: "/components/schemas/S/allOf/0"}}, + }, "/components/schemas/S", sourced(0)) + diags := diagsReports.Diagnostics() + + assert.Equal(t, "D", got.Docs.Description) + require.NotNil(t, got.XML, "the entry's xml where the position writes none") + assert.Equal(t, "Q", got.XML.Name) + assert.Len(t, got.Examples, 1, "the entry's example where the position writes none") + require.Len(t, got.FlattenedEntries, 1) + assert.Equal(t, jsontext.Pointer("/components/schemas/S/allOf/0"), got.FlattenedEntries[0].At) + assert.Contains(t, got.FlattenedEntries[0].Unmodeled, "openapi:not", "the entry keeps its own") + assert.NotContains(t, got.Unmodeled, "openapi:not", "apart from what the position keeps") + assert.NotEmpty(t, got.Unkept, "what the entry could not keep is held with the position's") + assert.Empty(t, diags) +} diff --git a/compilers/openapi/internal/annotation/extensions_internal_test.go b/compilers/openapi/internal/annotation/extensions_internal_test.go index d5db3efb3..1697dc86e 100644 --- a/compilers/openapi/internal/annotation/extensions_internal_test.go +++ b/compilers/openapi/internal/annotation/extensions_internal_test.go @@ -18,9 +18,9 @@ import ( // the format assigns it no semantics. func TestExtensionsFrom_KeepsEachAndLocatesItAtItsOwnKey(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nx-a: 1\nx-b: {k: v}\n") + schema := schemaFromYAML(t, "type: string\nx-a: 1\nx-b: {k: v}\n") - got, diags := ExtensionsFrom(s.GetExtensions(), sourced(3), "/components/schemas/S") + got, diags := ExtensionsFrom(schema.GetExtensions(), sourced(3), "/components/schemas/S") assert.Empty(t, diags) require.Len(t, got, 2) @@ -51,14 +51,14 @@ func TestExtensionsFrom_NothingWrittenIsNotAnEmptyMap(t *testing.T) { // nil map and not an empty one a carrier would have to tell apart. func TestExtensionsNamed_ReadsOnlyWhatItIsAsked(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nx-a: 1\nx-b: {k: v}\n") + schema := schemaFromYAML(t, "type: string\nx-a: 1\nx-b: {k: v}\n") - got := ExtensionsNamed(s.GetExtensions(), slices.Values([]string{"x-a", "x-absent"})) + got := ExtensionsNamed(schema.GetExtensions(), slices.Values([]string{"x-a", "x-absent"})) require.Len(t, got, 1) assert.Equal(t, ir.RawValue("1"), got["openapi:x-a"].Value) assert.Equal(t, ir.ReasonVendorExtension, got["openapi:x-a"].Reason) - assert.Nil(t, ExtensionsNamed(s.GetExtensions(), slices.Values([]string{"x-absent"}))) + assert.Nil(t, ExtensionsNamed(schema.GetExtensions(), slices.Values([]string{"x-absent"}))) assert.Nil(t, ExtensionsNamed(nil, slices.Values([]string{"x-a"}))) assert.Nil(t, ExtensionsNamed(schemaFromYAML(t, "type: string\n").GetExtensions(), slices.Values([]string{"x-a"}))) @@ -77,9 +77,9 @@ func TestExtensionsNamed_ReadsOnlyWhatItIsAsked(t *testing.T) { // a nil map rather than an empty one, with the warning still reported. func TestExtensionsFrom_UnserializableIsWarnedNotKept(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nx-bad: .nan\n") + schema := schemaFromYAML(t, "type: string\nx-bad: .nan\n") - got, diags := ExtensionsFrom(s.GetExtensions(), sourced(0), "/x") + got, diags := ExtensionsFrom(schema.GetExtensions(), sourced(0), "/x") assert.Nil(t, got, "nothing was kept, so there is no map to emit") require.Len(t, diags, 1) @@ -93,9 +93,9 @@ func TestExtensionsFrom_UnserializableIsWarnedNotKept(t *testing.T) { // extension itself. func TestExtensionsUnder_KeysBeneathTheScope(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nx-a: 1\n") + schema := schemaFromYAML(t, "type: string\nx-a: 1\n") - got, diags := ExtensionsUnder(s.GetExtensions(), sourced(2), "/info/contact", "info/contact") + got, diags := ExtensionsUnder(schema.GetExtensions(), sourced(2), "/info/contact", "info/contact") assert.Empty(t, diags) require.Len(t, got, 1) @@ -110,9 +110,9 @@ func TestExtensionsUnder_KeysBeneathTheScope(t *testing.T) { // entries are located through the same owner pointer plus their own key. func TestExtensionsUnder_AttributesEachEntryAtItsOwnKey(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nx-a: 1\nx-b: 2\n") + schema := schemaFromYAML(t, "type: string\nx-a: 1\nx-b: 2\n") - got, diags := ExtensionsUnder(s.GetExtensions(), overlaid("/o/x-b"), "/o", "") + got, diags := ExtensionsUnder(schema.GetExtensions(), overlaid("/o/x-b"), "/o", "") assert.Empty(t, diags) require.Len(t, got, 2) diff --git a/compilers/openapi/internal/annotation/preserve.go b/compilers/openapi/internal/annotation/keep.go similarity index 68% rename from compilers/openapi/internal/annotation/preserve.go rename to compilers/openapi/internal/annotation/keep.go index 8f45b06c9..2ff5bcfa7 100644 --- a/compilers/openapi/internal/annotation/preserve.go +++ b/compilers/openapi/internal/annotation/keep.go @@ -8,6 +8,7 @@ import ( "fmt" "maps" "slices" + "strings" yaml "go.yaml.in/yaml/v3" @@ -18,13 +19,13 @@ import ( "github.com/dexpace/morphic/ir" ) -// PreserveInto records raw under key in unmodeled, located at prov, or records +// KeepInto records raw under key in unmodeled, located at prov, or records // nothing when there are no bytes to record. // // len rather than a nil comparison: nil and a zero-length slice are distinct // states, and an empty payload is the worse of the two. It preserves no // construct, and it fails the encoding of the whole document that carries it. -func PreserveInto(unmodeled *ir.Unmodeled, key string, raw ir.RawValue, +func KeepInto(unmodeled *ir.Unmodeled, key string, raw ir.RawValue, reason ir.UnmodeledReason, prov ir.Provenance, ) { if len(raw) == 0 { @@ -40,7 +41,7 @@ func PreserveInto(unmodeled *ir.Unmodeled, key string, raw ir.RawValue, } } -// PreserveNodeInto converts node and records it under key, reporting a +// KeepNodeInto converts node and records it under key, reporting a // construct that reached the IR in no form at all rather than leaving its // caller to announce a preservation that did not happen (GitHub #144). // @@ -49,50 +50,83 @@ func PreserveInto(unmodeled *ir.Unmodeled, key string, raw ir.RawValue, // point: an absent node writes nothing and says nothing, because there was no // construct; a converted one writes the entry; an unconvertible one writes // nothing and yields the diagnostic that says so. -func PreserveNodeInto(unmodeled *ir.Unmodeled, key string, node *yaml.Node, +func KeepNodeInto(unmodeled *ir.Unmodeled, key string, node *yaml.Node, reason ir.UnmodeledReason, prov ir.Provenance, ) (bool, []ir.Diagnostic) { - raw, err := RawFromNode(node) + raw, dropped, err := RenderDroppingExtensions(node) if err != nil { return false, []ir.Diagnostic{unpreservableDiag(key, prov, err)} } + diags := DroppedExtensionDiags(prov, dropped) if len(raw) == 0 { - return false, nil + return false, diags + } + KeepInto(unmodeled, key, raw, reason, prov) + return true, diags +} + +// DroppedExtensionDiags reports each vendor extension of dropped, pointers +// from the construct at prov, left out of what kept it (ExtensionDroppedDiag): +// every keeping that leaves an extension out reports it here. +func DroppedExtensionDiags(prov ir.Provenance, dropped []jsontext.Pointer) []ir.Diagnostic { + diags := make([]ir.Diagnostic, 0, len(dropped)) + for _, at := range dropped { + place := prov + place.Pointer += at + diags = append(diags, ExtensionDroppedDiag(place)) } - PreserveInto(unmodeled, key, raw, reason, prov) - return true, nil + return diags } -// PreserveSchemaKeyword is PreserveNodeInto addressed by keyword: it keeps what +// KeepSchemaKeyword is KeepNodeInto addressed by keyword: it keeps what // schema, the schema at pointer, writes under keyword, keyed by EntryKey and // located at the keyword itself. Those are the key and the position the census // checks before keeping a keyword on its own (unrecorded). Deriving both here // leaves no caller a way to have the census keep the keyword again under // another key, or report a collision with this entry. // -// An absent keyword is no construct: it keeps and places nothing. -func PreserveSchemaKeyword(unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, +// An absent keyword is no construct: it keeps and places nothing, and nor +// does one written as it left out (WritesKeywordLeftOut), which says nothing. +func KeepSchemaKeyword(unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, reason ir.UnmodeledReason, pointer jsontext.Pointer, doc provenance.Doc, ) (bool, []ir.Diagnostic) { node := keyNode(schema, keyword) - if node == nil { + if node == nil || WritesKeywordLeftOut(schema, keyword) { return false, nil } - return PreserveNodeInto(unmodeled, EntryKey("", keyword), node, reason, doc.At(pointer+ids.Ptr(keyword))) + at := doc.At(pointer + ids.Ptr(keyword)) + if ExtensionNoJSONHolds(schema, keyword) { + // A vendor extension no JSON holds is left out wherever it is kept, as + // the extension reader leaves it out where written. + return false, []ir.Diagnostic{ExtensionDroppedDiag(at)} + } + return KeepNodeInto(unmodeled, EntryKey("", keyword), node, reason, at) +} + +// ExtensionNoJSONHolds reports whether keyword, written on schema, is a +// vendor extension whose value no JSON holds: one a keeping leaves out, +// reporting it as ExtensionDroppedDiag says. +func ExtensionNoJSONHolds(schema *statement.Schema, keyword string) bool { + node := keyNode(schema, keyword) + if !strings.HasPrefix(keyword, "x-") || node == nil { + return false + } + _, err := RawFromNode(node) + return err != nil } -// PreserveValidationOnlyKeyword is PreserveSchemaKeyword for a validation-only +// KeepValidationOnlyKeyword is KeepSchemaKeyword for a validation-only // keyword: it keeps the keyword under ReasonValidationOnly, at its own node, // which is what a validation emitter reports against, and announces it at -// pointer, the schema that wrote it. What PreserveSchemaKeyword keeps nothing +// pointer, the schema that wrote it. What KeepSchemaKeyword keeps nothing // of, it announces nothing of, reporting whether the entry was written. A // validation-only entry combining several keywords has no such node and is not // kept here but by Read, which attributes it by the keywords it holds // (GitHub #534). -func PreserveValidationOnlyKeyword(unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, +func KeepValidationOnlyKeyword(unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, pointer jsontext.Pointer, doc provenance.Doc, ) (bool, []ir.Diagnostic) { - kept, diags := PreserveSchemaKeyword(unmodeled, schema, keyword, ir.ReasonValidationOnly, pointer, doc) + kept, diags := KeepSchemaKeyword(unmodeled, schema, keyword, ir.ReasonValidationOnly, pointer, doc) if !kept { return false, diags } @@ -109,7 +143,7 @@ func PreserveValidationOnlyKeyword(unmodeled *ir.Unmodeled, schema *statement.Sc // // The vendor-extension reader (ExtensionsFrom) reports the same conversion // failure as a warning and is deliberately left alone: it already branches on the -// error and never claimed to have kept anything, so it is not the defect this +// error and never says it kept anything, so it is not the defect this // code exists for. func unpreservableDiag(key string, prov ir.Provenance, err error) ir.Diagnostic { return diag.Newf(ir.SeverityError, diag.UnpreservableConstruct, prov, @@ -117,23 +151,23 @@ func unpreservableDiag(key string, prov ir.Provenance, err error) ir.Diagnostic "in no form at all: %s", key, err.Error()) } -// preserveValidationOnlyInto records a validation-only payload at entry and +// keepValidationOnlyInto records a validation-only payload at entry and // returns the one diagnostic announcing it at note, the schema that wrote it, // saying message. An absent payload records nothing and announces nothing; an // unconvertible one never reaches here, because its caller reports it through // unpreservableDiag first. -func preserveValidationOnlyInto(unmodeled *ir.Unmodeled, key string, raw ir.RawValue, +func keepValidationOnlyInto(unmodeled *ir.Unmodeled, key string, raw ir.RawValue, entry, note ir.Provenance, message string, ) []ir.Diagnostic { if len(raw) == 0 { return nil } - PreserveInto(unmodeled, key, raw, ir.ReasonValidationOnly, entry) + KeepInto(unmodeled, key, raw, ir.ReasonValidationOnly, entry) return []ir.Diagnostic{diag.Newf(ir.SeverityInfo, diag.ValidationOnlyKeyword, note, "%s", message)} } // validationOnlyNote announces the validation-only entry named label at note, -// the schema that wrote it: one info per entry kept, whichever keeper kept it. +// the schema that wrote it: one info per entry kept, whichever reader kept it. func validationOnlyNote(note ir.Provenance, label string) ir.Diagnostic { return diag.Newf(ir.SeverityInfo, diag.ValidationOnlyKeyword, note, "%s", validationOnlyMessage(label)) } @@ -176,8 +210,8 @@ func CopyEntriesInto(unmodeled *ir.Unmodeled, src ir.Unmodeled) []ir.Diagnostic } // refusedCopyDiag reports an entry CopyEntriesInto left off a carrier that -// already holds its key. Unlike occupiedEntryDiag it claims no loss from the IR, -// since the other carriers the entry is copied onto may hold it. +// already holds its key. Unlike occupiedEntryDiag it states no loss from the +// IR, since the other carriers the entry is copied onto may hold it. func refusedCopyDiag(entry string, at ir.Provenance, held jsontext.Pointer) ir.Diagnostic { return diag.Newf(ir.SeverityWarning, diag.UnknownKeyEntryAlreadyClaimed, at, "%s is already held by the construct at %q, so the node holding that construct keeps no copy of this one", @@ -195,49 +229,3 @@ func MergeUnmodeled(dst, src ir.Unmodeled) ir.Unmodeled { maps.Copy(dst, src) return dst } - -// underlay is what Read knows of the entries it merged: those the site's own -// schema keeps (own), and those only a folded entry kept whole wrote (filled). -type underlay struct { - own, filled map[string]bool -} - -// add adds to dst each entry of src, one voice's, it lacks, walking src alone: -// overlaying the site's map on each voice would cost it all those before it. -// An entry own keeps stays its. A voice kept whole is no writer of what it -// folds, which its entry holds: it fills a key no other voice writes, which -// the first voice kept apart writing it takes. One two voices kept apart write, -// alike, as voices agree, is no one writer's, so it takes site, and no order of -// the voices decides where it points -// (docs/compilers/openapi.md#allof-inline-residue). -func (u *underlay) add(dst, src ir.Unmodeled, whole bool, site ir.Provenance) ir.Unmodeled { - if dst == nil && len(src) > 0 { - dst = make(ir.Unmodeled, len(src)) - } - for keyword, entry := range src { - held, written := dst[keyword] - switch { - case !written: - dst[keyword] = entry - if whole { - u.fill(keyword) - } - case whole || u.own[keyword]: - case u.filled[keyword]: - dst[keyword] = entry - delete(u.filled, keyword) - default: - held.Provenance = site - dst[keyword] = held - } - } - return dst -} - -// fill marks keyword as written by a folded entry kept whole alone. -func (u *underlay) fill(keyword string) { - if u.filled == nil { - u.filled = map[string]bool{} - } - u.filled[keyword] = true -} diff --git a/compilers/openapi/internal/annotation/preserve_internal_test.go b/compilers/openapi/internal/annotation/keep_internal_test.go similarity index 58% rename from compilers/openapi/internal/annotation/preserve_internal_test.go rename to compilers/openapi/internal/annotation/keep_internal_test.go index 582e4504c..84bfb4efe 100644 --- a/compilers/openapi/internal/annotation/preserve_internal_test.go +++ b/compilers/openapi/internal/annotation/keep_internal_test.go @@ -16,60 +16,60 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestPreserveInto_RecordsOnlyRealBytes pins the len check rather than a nil +// TestKeepInto_RecordsOnlyRealBytes pins the len check rather than a nil // comparison: an empty payload preserves no construct, and it fails the encoding // of the whole document that carries it. -func TestPreserveInto_RecordsOnlyRealBytes(t *testing.T) { +func TestKeepInto_RecordsOnlyRealBytes(t *testing.T) { t.Parallel() var unmodeled ir.Unmodeled - PreserveInto(&unmodeled, "openapi:x", nil, ir.ReasonOutOfScope, sourced(0).At("/x")) + KeepInto(&unmodeled, "openapi:x", nil, ir.ReasonOutOfScope, sourced(0).At("/x")) assert.Nil(t, unmodeled, "an absent payload allocates nothing") - PreserveInto(&unmodeled, "openapi:x", ir.RawValue(""), ir.ReasonOutOfScope, sourced(0).At("/x")) + KeepInto(&unmodeled, "openapi:x", ir.RawValue(""), ir.ReasonOutOfScope, sourced(0).At("/x")) assert.Nil(t, unmodeled, "nor does an empty one") - PreserveInto(&unmodeled, "openapi:x", ir.RawValue("1"), ir.ReasonOutOfScope, sourced(7).At("/x")) + KeepInto(&unmodeled, "openapi:x", ir.RawValue("1"), ir.ReasonOutOfScope, sourced(7).At("/x")) assert.Equal(t, ir.Unmodeled{"openapi:x": { Reason: ir.ReasonOutOfScope, Value: ir.RawValue("1"), Provenance: ir.Provenance{Source: 7, Pointer: "/x"}, }}, unmodeled) } -// TestPreserveNodeInto_ReportsWhichOfThreeOutcomesHappened pins the bool its +// TestKeepNodeInto_ReportsWhichOfThreeOutcomesHappened pins the bool its // callers gate their announcement on. An absent node must report false with no // diagnostic, and an unconvertible one false with the diagnostic that says // nothing reached the IR. -func TestPreserveNodeInto_ReportsWhichOfThreeOutcomesHappened(t *testing.T) { +func TestKeepNodeInto_ReportsWhichOfThreeOutcomesHappened(t *testing.T) { t.Parallel() var unmodeled ir.Unmodeled - kept, diags := PreserveNodeInto(&unmodeled, "openapi:x", nil, ir.ReasonNoIRHome, sourced(0).At("/x")) + kept, diags := KeepNodeInto(&unmodeled, "openapi:x", nil, ir.ReasonNoIRHome, sourced(0).At("/x")) assert.False(t, kept) assert.Empty(t, diags) assert.Nil(t, unmodeled) - kept, diags = PreserveNodeInto(&unmodeled, "openapi:x", openapitest.YAMLNode(t, ".nan"), ir.ReasonNoIRHome, sourced(0).At("/x")) + kept, diags = KeepNodeInto(&unmodeled, "openapi:x", openapitest.YAMLNode(t, ".nan"), ir.ReasonNoIRHome, sourced(0).At("/x")) assert.False(t, kept) require.Len(t, diags, 1) assert.Equal(t, ir.SeverityError, diags[0].Severity) assert.Nil(t, unmodeled, "an unconvertible node writes no entry") - kept, diags = PreserveNodeInto(&unmodeled, "openapi:x", openapitest.YAMLNode(t, "{a: 1}"), ir.ReasonNoIRHome, sourced(0).At("/x")) + kept, diags = KeepNodeInto(&unmodeled, "openapi:x", openapitest.YAMLNode(t, "{a: 1}"), ir.ReasonNoIRHome, sourced(0).At("/x")) assert.True(t, kept) assert.Empty(t, diags) assert.JSONEq(t, `{"a":1}`, string(unmodeled["openapi:x"].Value)) } -// TestPreserveSchemaKeyword_KeysAndLocatesTheEntryAtTheKeyword pins what the +// TestKeepSchemaKeyword_KeysAndLocatesTheEntryAtTheKeyword pins what the // function derives rather than takes: the census key, and the keyword's own // node beneath the schema's pointer. The overlay supplied that node and not the // schema, so placing the entry at the schema shows. -func TestPreserveSchemaKeyword_KeysAndLocatesTheEntryAtTheKeyword(t *testing.T) { +func TestKeepSchemaKeyword_KeysAndLocatesTheEntryAtTheKeyword(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nformat: password\n") + schema := schemaFromYAML(t, "type: string\nformat: password\n") var unmodeled ir.Unmodeled - kept, diags := PreserveSchemaKeyword(&unmodeled, standaloneSchema(s), "format", ir.ReasonNoIRHome, "/S", overlaid("/S/format")) + kept, diags := KeepSchemaKeyword(&unmodeled, standaloneSchema(schema), "format", ir.ReasonNoIRHome, "/S", overlaid("/S/format")) assert.True(t, kept) assert.Empty(t, diags) @@ -79,20 +79,20 @@ func TestPreserveSchemaKeyword_KeysAndLocatesTheEntryAtTheKeyword(t *testing.T) }}, unmodeled) } -// TestPreserveSchemaKeyword_ReportsAnUnkeptKeywordAtItsNode pins the other two -// outcomes PreserveNodeInto distinguishes, as this function reaches them: an +// TestKeepSchemaKeyword_ReportsAnUnkeptKeywordAtItsNode pins the other two +// outcomes KeepNodeInto distinguishes, as this function reaches them: an // absent keyword keeps and says nothing, and an unconvertible one keeps nothing // and is reported at the keyword's node. -func TestPreserveSchemaKeyword_ReportsAnUnkeptKeywordAtItsNode(t *testing.T) { +func TestKeepSchemaKeyword_ReportsAnUnkeptKeywordAtItsNode(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: number\ndefault: .nan\n") + schema := schemaFromYAML(t, "type: number\ndefault: .nan\n") var unmodeled ir.Unmodeled - kept, diags := PreserveSchemaKeyword(&unmodeled, standaloneSchema(s), "format", ir.ReasonNoIRHome, "/S", sourced(0)) + kept, diags := KeepSchemaKeyword(&unmodeled, standaloneSchema(schema), "format", ir.ReasonNoIRHome, "/S", sourced(0)) assert.False(t, kept) assert.Empty(t, diags, "an absent keyword is no construct") - kept, diags = PreserveSchemaKeyword(&unmodeled, standaloneSchema(s), "default", ir.ReasonNoIRHome, "/S", overlaid("/S/default")) + kept, diags = KeepSchemaKeyword(&unmodeled, standaloneSchema(schema), "default", ir.ReasonNoIRHome, "/S", overlaid("/S/default")) assert.False(t, kept) assert.Nil(t, unmodeled, "an unconvertible keyword writes no entry") require.Len(t, diags, 1) @@ -100,37 +100,38 @@ func TestPreserveSchemaKeyword_ReportsAnUnkeptKeywordAtItsNode(t *testing.T) { assert.Equal(t, ir.Provenance{Pointer: "/S/default", WrittenBy: 1}, diags[0].Provenance) } -// TestPreserveSchemaKeyword_TheCensusLeavesItsEntryAlone holds the function to +// TestKeepSchemaKeyword_TheCensusLeavesItsEntryAlone holds the function to // the reason it derives its key and position: the census, run after it as the // schema lowering runs it, finds the entry it wrote and adds nothing. A key it // does not recognise would be kept a second time, and a position it does not // recognise reported as a collision. -func TestPreserveSchemaKeyword_TheCensusLeavesItsEntryAlone(t *testing.T) { +func TestKeepSchemaKeyword_TheCensusLeavesItsEntryAlone(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nnullable: true\n") + schema := schemaFromYAML(t, "type: string\nnullable: true\n") var unmodeled ir.Unmodeled - kept, diags := PreserveSchemaKeyword(&unmodeled, standaloneSchema(s), "nullable", ir.ReasonDegradedLowering, "/S", sourced(0)) + kept, diags := KeepSchemaKeyword(&unmodeled, standaloneSchema(schema), "nullable", ir.ReasonDegradedLowering, "/S", sourced(0)) require.True(t, kept) require.Empty(t, diags) - census := UndefinedKeywordsIn(&unmodeled, standaloneSchema(s), []string{"nullable"}, "/S", sourced(0)) + censusReports := UndefinedKeywordsIn(&unmodeled, standaloneSchema(schema), []string{"nullable"}, "/S", sourced(0)) + census := censusReports.Diagnostics() assert.Empty(t, census, "the census announces nothing it did not keep") require.Len(t, unmodeled, 1, "and keeps no second entry") assert.Equal(t, ir.ReasonDegradedLowering, unmodeled[EntryKey("", "nullable")].Reason, "nor rewrites this one") } -// TestPreserveValidationOnlyKeyword_SplitsTheEntryFromItsAnnouncement pins the +// TestKeepValidationOnlyKeyword_SplitsTheEntryFromItsAnnouncement pins the // two positions it derives: the entry at the keyword's own node, which a // validation emitter reports against, and the announcement at the schema that // wrote it. The overlay supplied the keyword and not the schema, so swapping // them shows. -func TestPreserveValidationOnlyKeyword_SplitsTheEntryFromItsAnnouncement(t *testing.T) { +func TestKeepValidationOnlyKeyword_SplitsTheEntryFromItsAnnouncement(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nnot: {const: x}\n") + schema := schemaFromYAML(t, "type: string\nnot: {const: x}\n") var unmodeled ir.Unmodeled - kept, diags := PreserveValidationOnlyKeyword(&unmodeled, standaloneSchema(s), "not", "/S", overlaid("/S/not")) + kept, diags := KeepValidationOnlyKeyword(&unmodeled, standaloneSchema(schema), "not", "/S", overlaid("/S/not")) assert.True(t, kept) assert.Equal(t, ir.Unmodeled{EntryKey("", "not"): { @@ -142,19 +143,19 @@ func TestPreserveValidationOnlyKeyword_SplitsTheEntryFromItsAnnouncement(t *test assert.Equal(t, ir.Provenance{Source: 0, Pointer: "/S"}, diags[0].Provenance) } -// TestPreserveValidationOnlyKeyword_ReportsAnUnkeptKeywordAtItsNode pins that a +// TestKeepValidationOnlyKeyword_ReportsAnUnkeptKeywordAtItsNode pins that a // keyword which cannot be converted is reported where its entry would have // been, and that an absent one announces nothing. -func TestPreserveValidationOnlyKeyword_ReportsAnUnkeptKeywordAtItsNode(t *testing.T) { +func TestKeepValidationOnlyKeyword_ReportsAnUnkeptKeywordAtItsNode(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\ndependentRequired: {a: [.nan]}\n") + schema := schemaFromYAML(t, "type: object\ndependentRequired: {a: [.nan]}\n") var unmodeled ir.Unmodeled - kept, absentDiags := PreserveValidationOnlyKeyword(&unmodeled, standaloneSchema(s), "not", "/S", sourced(0)) + kept, absentDiags := KeepValidationOnlyKeyword(&unmodeled, standaloneSchema(schema), "not", "/S", sourced(0)) assert.False(t, kept) assert.Empty(t, absentDiags, "an absent keyword is no construct") - kept, diags := PreserveValidationOnlyKeyword(&unmodeled, standaloneSchema(s), "dependentRequired", "/S", overlaid("/S/dependentRequired")) + kept, diags := KeepValidationOnlyKeyword(&unmodeled, standaloneSchema(schema), "dependentRequired", "/S", overlaid("/S/dependentRequired")) assert.False(t, kept) assert.Nil(t, unmodeled, "an unconvertible keyword writes no entry") require.Len(t, diags, 1) @@ -177,16 +178,16 @@ func TestUnpreservableDiag_IsAnErrorNotADegradation(t *testing.T) { assert.Contains(t, got.Message, "in no form at all") } -// TestPreserveValidationOnlyInto_EmptyPayloadRecordsAndAnnouncesNothing pins the +// TestKeepValidationOnlyInto_EmptyPayloadRecordsAndAnnouncesNothing pins the // recorder's len check: a nil and a zero-length payload both keep no entry, so // neither may be announced as kept. -func TestPreserveValidationOnlyInto_EmptyPayloadRecordsAndAnnouncesNothing(t *testing.T) { +func TestKeepValidationOnlyInto_EmptyPayloadRecordsAndAnnouncesNothing(t *testing.T) { t.Parallel() for name, raw := range map[string]ir.RawValue{"nil": nil, "empty non-nil": {}} { t.Run(name, func(t *testing.T) { t.Parallel() var unmodeled ir.Unmodeled - diags := preserveValidationOnlyInto(&unmodeled, "openapi:not", raw, sourced(0).At("/p/not"), sourced(0).At("/p"), "not") + diags := keepValidationOnlyInto(&unmodeled, "openapi:not", raw, sourced(0).At("/p/not"), sourced(0).At("/p"), "not") assert.Nil(t, unmodeled) assert.Empty(t, diags, "nothing was kept, so nothing is announced") }) @@ -210,56 +211,6 @@ func TestMergeUnmodeled_AllocatesOnlyOnFirstWrite(t *testing.T) { }, MergeUnmodeled(dst, src)) } -// TestUnderlayAdd_TheSiteOwnsWhatSeveralWrite pins what a folded entry may -// add: an entry the site does not hold. One the site's own schema holds stays -// the site's, its provenance with it; one another folded entry wrote takes the -// site's provenance, so no order of the folded entries names a writer. -func TestUnderlayAdd_TheSiteOwnsWhatSeveralWrite(t *testing.T) { - t.Parallel() - site := ir.Provenance{Pointer: "/site"} - near := ir.UnmodeledEntry{Reason: ir.ReasonVendorExtension, Provenance: ir.Provenance{Pointer: "/near"}} - far := ir.UnmodeledEntry{Reason: ir.ReasonVendorExtension, Provenance: ir.Provenance{Pointer: "/far"}} - atSite := ir.UnmodeledEntry{Reason: ir.ReasonVendorExtension, Provenance: site} - - own := underlay{own: map[string]bool{"x-a": true}} - got := own.add(ir.Unmodeled{"x-a": near}, ir.Unmodeled{"x-a": far, "x-b": far}, false, site) - assert.Equal(t, ir.Unmodeled{"x-a": near, "x-b": far}, got, "the site's own entry stands") - - var underlayValue underlay - got = underlayValue.add(ir.Unmodeled{"x-a": near}, ir.Unmodeled{"x-a": far}, false, site) - assert.Equal(t, ir.Unmodeled{"x-a": atSite}, got, "an entry two voices write is the site's") - - assert.Equal(t, ir.Unmodeled{"x-b": far}, underlayValue.add(nil, ir.Unmodeled{"x-b": far}, false, site)) - assert.Nil(t, underlayValue.add(nil, nil, false, site), "nothing to add allocates nothing") -} - -// TestUnderlayAdd_AFoldedEntryKeptWholeWritesForNoOne pins that a voice kept -// whole, whose entry holds what it folds, counts as no writer: it fills a key -// alone, gives it up to a voice kept apart in either order, and leaves one two -// voices kept apart write at the site. -func TestUnderlayAdd_AFoldedEntryKeptWholeWritesForNoOne(t *testing.T) { - t.Parallel() - site := ir.Provenance{Pointer: "/site"} - whole := ir.UnmodeledEntry{Reason: ir.ReasonVendorExtension, Provenance: ir.Provenance{Pointer: "/allOf/1/x-a"}} - apart := ir.UnmodeledEntry{Reason: ir.ReasonVendorExtension, Provenance: ir.Provenance{Pointer: "/allOf/2/x-a"}} - atSite := ir.UnmodeledEntry{Reason: ir.ReasonVendorExtension, Provenance: site} - - var first underlay - got := first.add(nil, ir.Unmodeled{"x-a": whole}, true, site) - assert.Equal(t, ir.Unmodeled{"x-a": whole}, got, "a voice kept whole fills a key alone") - got = first.add(got, ir.Unmodeled{"x-a": whole}, true, site) - assert.Equal(t, ir.Unmodeled{"x-a": whole}, got, "a second voice kept whole writes nothing") - got = first.add(got, ir.Unmodeled{"x-a": apart}, false, site) - assert.Equal(t, ir.Unmodeled{"x-a": apart}, got, "a voice kept apart takes the key") - got = first.add(got, ir.Unmodeled{"x-a": apart}, false, site) - assert.Equal(t, ir.Unmodeled{"x-a": atSite}, got, "two voices kept apart leave it at the site") - - var last underlay - got = last.add(nil, ir.Unmodeled{"x-a": apart}, false, site) - got = last.add(got, ir.Unmodeled{"x-a": whole}, true, site) - assert.Equal(t, ir.Unmodeled{"x-a": apart}, got, "a voice kept whole after it writes nothing") -} - // TestCopyEntriesInto_KeepsWhatTheCarrierHolds pins that a copied entry never // replaces one the carrier already holds: the held one stays, the copy is // reported missing from that carrier, and every other entry lands with bytes of diff --git a/compilers/openapi/internal/annotation/keptreports.go b/compilers/openapi/internal/annotation/keptreports.go new file mode 100644 index 000000000..14db9c65b --- /dev/null +++ b/compilers/openapi/internal/annotation/keptreports.go @@ -0,0 +1,40 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package annotation + +import "github.com/dexpace/morphic/ir" + +// KeptReport is one report a keeping draws, paired with the Unmodeled key of +// the entry it reports, so PendingKeeps draws it where that entry's pending +// keep settles. A report keyed "" or by a key the keeping holds no entry under +// is left where it is drawn. +type KeptReport struct { + Key string + Diagnostic ir.Diagnostic +} + +// KeptReports is what keepings report, in the order drawn. +type KeptReports []KeptReport + +// ReportsOf pairs each of diags, the reports of what one keeping keeps under +// key, with key, in order. +func ReportsOf(key string, diags ...ir.Diagnostic) KeptReports { + out := make(KeptReports, len(diags)) + for i, diagnostic := range diags { + out[i] = KeptReport{Key: key, Diagnostic: diagnostic} + } + return out +} + +// Diagnostics returns the reports, in the order drawn, nil for none. +func (reports KeptReports) Diagnostics() []ir.Diagnostic { + if len(reports) == 0 { + return nil + } + out := make([]ir.Diagnostic, len(reports)) + for i, report := range reports { + out[i] = report.Diagnostic + } + return out +} diff --git a/compilers/openapi/internal/annotation/keywordlists_test.go b/compilers/openapi/internal/annotation/keywordlists_test.go index dfa3546ce..0cfb8a4a7 100644 --- a/compilers/openapi/internal/annotation/keywordlists_test.go +++ b/compilers/openapi/internal/annotation/keywordlists_test.go @@ -4,95 +4,13 @@ package annotation_test import ( - "io/fs" - "os" - "path/filepath" - "regexp" - "slices" - "strings" "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" ) -// moduleRoot is the repository root, which is four directories above this -// package. -const moduleRoot = "../../../.." - -// exportedListVar matches the declaration the keyword lists used to take: an -// exported package-level slice or map, which any importer can mutate and every -// other importer then reads. -var exportedListVar = regexp.MustCompile(`^var [A-Z][A-Za-z0-9]* = (\[\]|map\[)`) - -// TestKeywordLists_AreNotExported holds the module to no exported package-level -// slice or map in a production file. A list a package exports is one value -// every importer shares, so a caller that sorts or appends to it changes what -// every other reader sees (GitHub #1316). -func TestKeywordLists_AreNotExported(t *testing.T) { - t.Parallel() - var found []string - var scanned int - err := filepath.WalkDir(moduleRoot, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - if d.IsDir() { - switch d.Name() { - case ".git", "testdata", "node_modules", ".claude": - return fs.SkipDir - } - return nil - } - if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { - return nil - } - data, err := os.ReadFile(path) - if err != nil { - return err - } - scanned++ - for line := range strings.SplitSeq(string(data), "\n") { - if exportedListVar.MatchString(line) { - found = append(found, filepath.ToSlash(path)+": "+line) - } - } - return nil - }) - require.NoError(t, err) - require.Greater(t, scanned, 100, "the walk reached the module's production files") - - assert.Empty(t, found, "a package exposes its list through a function, not a shared variable") -} - -// TestDialectKeywords_YieldsTheDialectKeywords pins the members the seam gives -// out, so a mutation test below has something to mutate. -func TestDialectKeywords_YieldsTheDialectKeywords(t *testing.T) { - t.Parallel() - assert.ElementsMatch(t, []string{"$id", "$schema", "$vocabulary"}, - slices.Collect(annotation.DialectKeywords())) -} - -// TestDialectKeywords_EachReaderGetsItsOwnCopy mutates through one reader's -// result and holds another's to what it was: the seam yields values, so no -// reader holds the list another one can change. -func TestDialectKeywords_EachReaderGetsItsOwnCopy(t *testing.T) { - t.Parallel() - first := slices.Collect(annotation.DialectKeywords()) - want := slices.Clone(first) - - slices.Sort(first) - slices.Reverse(first) - first[0] = "mutated" - first = append(first[:1], "appended") - - assert.Equal(t, want, slices.Collect(annotation.DialectKeywords()), - "a second reader sees the list as the package declared it") - assert.NotEqual(t, first, slices.Collect(annotation.DialectKeywords())) -} - // TestDialectKeyword_IsMembership holds the predicate a reader outside the // package asks in place of searching the list: the dialect's keywords are // members, and another keyword is not. diff --git a/compilers/openapi/internal/annotation/pendingkeeps.go b/compilers/openapi/internal/annotation/pendingkeeps.go new file mode 100644 index 000000000..f2e33e797 --- /dev/null +++ b/compilers/openapi/internal/annotation/pendingkeeps.go @@ -0,0 +1,1080 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package annotation + +import ( + "cmp" + "encoding/json/jsontext" + "fmt" + "slices" + "strings" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/ir" +) + +// ConjunctRole is how one conjunct writing a node relates to the position the +// node lowers (docs/compilers/openapi.md#allof-inline-residue). +type ConjunctRole uint8 + +const ( + // WritesAtPosition is the schema written at the position, or the carrier + // holding it: the outermost conjunct of every node. + WritesAtPosition ConjunctRole = iota + // WritesLoweredFrom is an inline allOf entry the position lowers from: its + // inline principal, or a wrapper out of whose allOf the principal is + // flattened, each around the entries written inside it. + WritesLoweredFrom + // WritesBeside is any other allOf entry: one the position composes or + // refines beside its principal, or a $ref entry naming nothing. + WritesBeside +) + +// ConjunctIndex is where a conjunct site is among the conjuncts of the allOf +// its position writes: its entry's index among the allOf's entries as +// flattened, the lowest being the nearest, else BesideAllOf or UnlistedEntry. +type ConjunctIndex int + +const ( + // BesideAllOf is the place of the keywords written beside the allOf: the + // position's own. + BesideAllOf ConjunctIndex = -1 + // UnlistedEntry is the place of an allOf entry the flattened entries do + // not list. It names no index, and sorts before every place that does. + UnlistedEntry ConjunctIndex = -2 +) + +// Entry returns the index of the entry place names among the allOf's entries +// as flattened, and whether it names one: BesideAllOf and UnlistedEntry name +// none. +func (place ConjunctIndex) Entry() (int, bool) { + return int(place), place >= 0 +} + +// ConjunctSite is one conjunct writing a node: where it is written, which no +// other conjunct of the node shares, how it relates to the position (Role), +// the key what it keeps apart from another conjunct is held under (EntryKey, +// "" for the position) and where it is among the allOf's conjuncts (Order). +type ConjunctSite struct { + Pointer jsontext.Pointer + EntryKey string + Role ConjunctRole + Order ConjunctIndex +} + +// contains reports whether s lies around other: the position around every +// conjunct, and an entry the position lowers from around each written inside +// it. +func (s ConjunctSite) contains(other ConjunctSite) bool { + switch s.Role { + case WritesAtPosition: + return true + case WritesLoweredFrom: + return s.Pointer.Contains(other.Pointer) + default: + return s.Pointer == other.Pointer + } +} + +// KeptKeywordKeeping is one reading of one conjunct that keeps several keywords +// and reports them together: Keep writes each of keys, the keywords it keeps +// once the node settles, onto unmodeled as written flat, and returns their +// reports. KeepAtPosition is Keep for keys the node reports at its position, as +// several entries keep them alike, worded as the same keys written beside the +// allOf are, nil where Keep's reports read alike there. Pending keeps share a +// keeping by pointing at one. +type KeptKeywordKeeping struct { + Keep func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic + KeepAtPosition func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic +} + +// pendingKeeping keys the keywords a keeping keeps plain, apart from those +// it keeps for the position to report (KeptKeywordKeeping.KeepAtPosition). +type pendingKeeping struct { + keeping *KeptKeywordKeeping + atPosition bool +} + +// KeptKeywordSource is where a pending keep comes from, which says how the +// node settling it places and reports its value. The zero value is +// KeptByReader. +type KeptKeywordSource uint8 + +const ( + // KeptByReader is a reader's keep of a keyword: its own report draws it + // where the value is kept under its own key, and the report of the allOf + // entry writing it names it where that entry holds it apart or whole. + KeptByReader KeptKeywordSource = iota + // KeptByBuild is what the build of the node kept on it: the report the + // build drew is drawn wherever the value is kept, apart or whole too, so no + // report of the allOf entry writing it names it again. + KeptByBuild + // KeptByFold is a folded allOf entry's keep, of a value read as written + // beside the allOf: the entry kept whole holds it and names it, and reads + // no reason from it, since what the entry folds is typed as any entry's is. + KeptByFold + // ConsumedIntoNode is no keep but a value read into the node, which holds + // its key's one value: a value written otherwise is kept apart, and this + // one is written nowhere. + ConsumedIntoNode +) + +// PendingKeep is what one conjunct writing a node keeps of one key, until the +// node settles (PendingKeeps): kept as written where the conjunct is the +// node's only one, and otherwise as the settlement places it, under its own +// key, apart under its conjunct's entry key, or in its conjunct's entry kept +// whole. +type PendingKeep struct { + // Key is the Unmodeled key the value is kept under where kept as written + // (EntryKey). + Key string + // Keyword is the keyword the value is written under. + Keyword string + // Modifies is the key of the bound a boolean exclusive flag modifies, with + // whose pending keeps it settles as one, and empty for any other value. + Modifies string + // Value is the value as the conjunct keeps it written flat, empty where + // Written alone holds it. + Value jsontext.Value + // Written is the node the value is written as, nil where unknown: the + // settlement renders it into an empty Value, and warns of each vendor + // extension it leaves out where the value is kept apart. + Written *yaml.Node + // Reason is why the value is kept. + Reason ir.UnmodeledReason + // Report is what the conjunct reports of the value kept as written, unless + // KeptBy reports it. + Report []ir.Diagnostic + // Source is where the value comes from, which says how the settlement + // places and reports it. + Source KeptKeywordSource + // KeptBy is the keeping that writes the value and reports it with the + // others it keeps, nil where the value is kept under Key as written. + KeptBy *KeptKeywordKeeping + // Provenance is where the value is written, which the entry keeping it + // carries. + Provenance ir.Provenance + // WrittenBy is the conjunct of the node that keeps the value. + WrittenBy ConjunctSite + // KeptAtEveryConjunctSite says the value is kept wherever a conjunct + // writes it, never dropped because another conjunct's entry, kept whole or + // lying around it, holds the same value: a promotion reads its key at each. + KeptAtEveryConjunctSite bool + // reading names the one reading the pending keep is reported with where kept + // apart (AsOneReading), nil for its keeping's own. + reading *reading + // muted holds the reports another report takes the place of (DropReports). + muted func(ir.Diagnostic) bool +} + +// reading is one reading of one conjunct, the pending keeps of which are +// reported together where kept apart. +type reading struct{ _ byte } + +// AsOneReading marks every pending keep in pendingKeeps as one reading of its +// conjunct, reported together where kept apart. +func (pendingKeeps *PendingKeeps) AsOneReading() { + one := &reading{} + for i := range pendingKeeps.pendingKeeps { + pendingKeeps.pendingKeeps[i].reading = one + } +} + +// KeptAllOfEntry is an allOf entry writing to a node: the entry as written +// (Whole, nil where no JSON holds it), kept whole under its site's key where +// KeptWhole says a cause read before lowering does or a keyword it keeps +// collides with another conjunct's, only one another conjunct keeps where +// AgainstKept says so, and the reports of what its key holds, whole or apart. +// Dropped lists the vendor extensions Whole leaves out that no reading of the +// entry reports, pointers from it, each warned of where the entry is kept +// whole. +type KeptAllOfEntry struct { + Site ConjunctSite + Whole jsontext.Value + Dropped []jsontext.Pointer + Provenance ir.Provenance + KeptWhole bool + AgainstKept bool + ReportWhole func(held []string, reason ir.UnmodeledReason) []ir.Diagnostic + ReportApart func(apart []string) []ir.Diagnostic + // muted holds the reports another report takes the place of (DropReports). + muted func(ir.Diagnostic) bool +} + +// PendingKeeps is a node's pending keeps: what each of its conjuncts keeps, +// settled once into the node's Unmodeled and the reports of what it holds +// (docs/compilers/openapi.md#allof-inline-residue). The zero value is empty. +// It settles once: Add and AddEntry record nothing after Settle. +type PendingKeeps struct { + pendingKeeps []PendingKeep + entries []KeptAllOfEntry + settled bool +} + +// Add records pendingKeep. A pending keep with no value keeps nothing and is +// refused, and so is every pending keep once pendingKeeps has settled. +func (pendingKeeps *PendingKeeps) Add(pendingKeep PendingKeep) { + if pendingKeeps.settled || len(pendingKeep.Value) == 0 && pendingKeep.Written == nil || pendingKeep.Key == "" { + return + } + pendingKeeps.pendingKeeps = append(pendingKeeps.pendingKeeps, pendingKeep) +} + +// AddEntry records entry, unless pendingKeeps has settled. Records of one site +// merge once, when the pending keeps settle (completeEntry), since a scan of +// the entries per record would be quadratic in them. +func (pendingKeeps *PendingKeeps) AddEntry(entry KeptAllOfEntry) { + if pendingKeeps.settled { + return + } + pendingKeeps.entries = append(pendingKeeps.entries, entry) +} + +// completeEntry is held, a record of one site, completed by entry, a later +// one: kept whole where either says, with the reports the later one gives. +func completeEntry(held, entry KeptAllOfEntry) KeptAllOfEntry { + held.KeptWhole = held.KeptWhole || entry.KeptWhole + held.AgainstKept = held.AgainstKept || entry.AgainstKept + if len(held.Whole) == 0 { + held.Whole = entry.Whole + } + if len(entry.Dropped) > 0 { + held.Dropped = entry.Dropped + } + if entry.ReportWhole != nil { + held.ReportWhole = entry.ReportWhole + } + if entry.ReportApart != nil { + held.ReportApart = entry.ReportApart + } + if entry.muted != nil { + held.muted = entry.muted + } + return held +} + +// AddAll records what other holds after what pendingKeeps holds, in order: +// each of its entries as AddEntry records one, and each of its pending keeps as +// Add does. +func (pendingKeeps *PendingKeeps) AddAll(other PendingKeeps) { + for _, entry := range other.entries { + pendingKeeps.AddEntry(entry) + } + for _, pendingKeep := range other.pendingKeeps { + pendingKeeps.Add(pendingKeep) + } +} + +// DropReports drops each report drop holds of what pendingKeeps would report +// once settled, for a conjunct whose reports another report takes the place of. +func (pendingKeeps *PendingKeeps) DropReports(drop func(ir.Diagnostic) bool) { + for i := range pendingKeeps.pendingKeeps { + pendingKeeps.pendingKeeps[i].muted = drop + } + for i := range pendingKeeps.entries { + pendingKeeps.entries[i].muted = drop + } +} + +// unmuted returns diags less what muted, a conjunct's dropped reports +// (DropReports), holds. +func unmuted(diags []ir.Diagnostic, muted func(ir.Diagnostic) bool) []ir.Diagnostic { + if muted == nil { + return diags + } + return slices.DeleteFunc(slices.Clone(diags), muted) +} + +// Keywords returns the keywords pendingKeeps keeps, by its conjuncts' pending +// keeps, each once, in the order first added. +func (pendingKeeps *PendingKeeps) Keywords() []string { + var out []string + seen := map[string]bool{} + for _, pendingKeep := range pendingKeeps.pendingKeeps { + if pendingKeep.Source != ConsumedIntoNode && !seen[pendingKeep.Keyword] { + seen[pendingKeep.Keyword] = true + out = append(out, pendingKeep.Keyword) + } + } + return out +} + +// KeptUnderOwnKeyAt returns the keywords pendingKeeps holds written on the +// schema at pointer and kept there under their own key, each once, in the order +// first pending: a conjunct's own reading of a keyword is no keep. +func (pendingKeeps *PendingKeeps) KeptUnderOwnKeyAt(pointer jsontext.Pointer) []string { + var out []string + for _, pendingKeep := range pendingKeeps.pendingKeeps { + if pendingKeep.Source != ConsumedIntoNode && pendingKeep.Key == EntryKey("", pendingKeep.Keyword) && pendingKeep.Provenance.Pointer == pointer+ids.Ptr(pendingKeep.Keyword) && + !slices.Contains(out, pendingKeep.Keyword) { + out = append(out, pendingKeep.Keyword) + } + } + return out +} + +// keepPlain keeps pendingKeep under its key, as written, or by its keeping with +// the others it keeps, which pending holds until kept, and returns the +// reports drawn: at position where it is not nil, as the node reports there a +// value several entries keep alike (settlement.settleAlike). +func keepPlain(out *ir.Unmodeled, pendingKeep PendingKeep, pending map[pendingKeeping][]string, position *ir.Provenance) []ir.Diagnostic { + if pendingKeep.KeptBy == nil { + KeepInto(out, pendingKeep.Key, pendingKeep.Value, pendingKeep.Reason, pendingKeep.Provenance) + return reportedAt(unmuted(pendingKeep.Report, pendingKeep.muted), position) + } + key := pendingKeeping{keeping: pendingKeep.KeptBy, atPosition: position != nil} + keys, waiting := pending[key] + if !waiting { + return nil + } + delete(pending, key) + keep := pendingKeep.KeptBy.Keep + if position != nil && pendingKeep.KeptBy.KeepAtPosition != nil { + keep = pendingKeep.KeptBy.KeepAtPosition + } + return reportedAt(unmuted(keep(out, keys), pendingKeep.muted), position) +} + +// reportedAt returns diags drawn at position, a copy, or diags where position +// is nil. +func reportedAt(diags []ir.Diagnostic, position *ir.Provenance) []ir.Diagnostic { + if position == nil { + return diags + } + out := slices.Clone(diags) + for i := range out { + out[i].Provenance = *position + } + return out +} + +// Empty reports whether pendingKeeps holds nothing. +func (pendingKeeps *PendingKeeps) Empty() bool { + return len(pendingKeeps.pendingKeeps) == 0 && len(pendingKeeps.entries) == 0 +} + +// Settle groups the pending keeps by key, a bound with its boolean flag as one +// unit, and compares the conjuncts' values by rendering, member order aside. +// One value is one entry, the outermost conjunct's, at position where no +// conjunct surrounds the others; several are the outermost's under the plain +// key and each other conjunct's under its entry key, whole for an entry nothing +// lowers from. It returns the Unmodeled entries and the reports of what they +// hold, and leaves pendingKeeps settled, refusing what is added to it after. +func (pendingKeeps *PendingKeeps) Settle(position ir.Provenance) (ir.Unmodeled, []ir.Diagnostic) { + pendingKeeps.settled = true + if pendingKeeps.Empty() { + return nil, nil + } + keepSettlement := newSettlement(pendingKeeps, position) + keepSettlement.markWhole() + for _, unit := range keepSettlement.units { + keepSettlement.settleUnit(unit) + } + return keepSettlement.write() +} + +// settlement is one Settle's working state, each unit's parts in the order +// first added, and settled indexed as pendingKeeps. +type settlement struct { + pendingKeeps []PendingKeep + entries map[jsontext.Pointer]KeptAllOfEntry + order []jsontext.Pointer + units [][]*conjunctPart + bySite map[jsontext.Pointer][]int + whole map[jsontext.Pointer]bool + collided map[jsontext.Pointer]bool + wholeLowered []ConjunctSite + settled []pendingKeepSettlement + apartBy map[jsontext.Pointer][]int + // wholeRendering is each entry's Whole as rendered for comparison, by + // its site's pointer, rendered where first compared (renderedWhole). + wholeRendering map[jsontext.Pointer]string + position ir.Provenance +} + +// pendingKeepSettlement is what one pending keep settled as: its placement, +// the pointer of the entry whose key holds it where placed apart, whether its +// reports are drawn at the position (reportAtPosition) and its entry placed +// there (relocate), whether no JSON holds its value, and the vendor extensions +// its value, rendered from the node it is written as, leaves out. +type pendingKeepSettlement struct { + apartAt jsontext.Pointer + dropped []jsontext.Pointer + placed placement + atPosition bool + relocated bool + unrendered bool +} + +// conjunctPart is what one conjunct writes of one unit: the pending keeps, by +// index, and their rendering, member order aside. +type conjunctPart struct { + site ConjunctSite + members []int + render string + every bool + consumed bool +} + +// placement is what a pending keep settled as. +type placement uint8 + +const ( + // placedNowhere is a pending keep dropped as one part of a value kept + // elsewhere. + placedNowhere placement = iota + // placedPlain is a pending keep kept under its own key. + placedPlain + // placedApart is a pending keep kept under its conjunct's entry key. + placedApart + // placedWhole is a pending keep its conjunct's entry holds, kept whole. + placedWhole +) + +// unitSite keys the part of one unit by one conjunct. +type unitSite struct { + unit string + site jsontext.Pointer +} + +// newSettlement groups pending keeps into parts by unit and conjunct. +func newSettlement(pendingKeeps *PendingKeeps, position ir.Provenance) *settlement { + keepSettlement := &settlement{ + pendingKeeps: pendingKeeps.pendingKeeps, + entries: make(map[jsontext.Pointer]KeptAllOfEntry, len(pendingKeeps.entries)), + bySite: map[jsontext.Pointer][]int{}, + whole: map[jsontext.Pointer]bool{}, + collided: map[jsontext.Pointer]bool{}, + settled: make([]pendingKeepSettlement, len(pendingKeeps.pendingKeeps)), + wholeRendering: map[jsontext.Pointer]string{}, + position: position, + } + for _, entry := range pendingKeeps.entries { + if held, seen := keepSettlement.entries[entry.Site.Pointer]; seen { + keepSettlement.entries[entry.Site.Pointer] = completeEntry(held, entry) + continue + } + keepSettlement.entries[entry.Site.Pointer] = entry + keepSettlement.order = append(keepSettlement.order, entry.Site.Pointer) + } + byUnit := map[string]int{} + parts := map[unitSite]*conjunctPart{} + for i, pendingKeep := range pendingKeeps.pendingKeeps { + keepSettlement.bySite[pendingKeep.WrittenBy.Pointer] = append(keepSettlement.bySite[pendingKeep.WrittenBy.Pointer], i) + keepSettlement.settled[i].apartAt = pendingKeep.WrittenBy.Pointer + unit := cmp.Or(pendingKeep.Modifies, pendingKeep.Key) + at, seen := byUnit[unit] + if !seen { + at = len(keepSettlement.units) + byUnit[unit] = at + keepSettlement.units = append(keepSettlement.units, nil) + } + key := unitSite{unit: unit, site: pendingKeep.WrittenBy.Pointer} + if part, held := parts[key]; held { + keepSettlement.addTo(part, i) + continue + } + part := &conjunctPart{site: pendingKeep.WrittenBy, members: []int{i}, every: pendingKeep.KeptAtEveryConjunctSite, consumed: pendingKeep.Source == ConsumedIntoNode} + parts[key] = part + keepSettlement.units[at] = append(keepSettlement.units[at], part) + } + for i, pendingKeep := range keepSettlement.pendingKeeps { + if pendingKeep.Written == nil { + continue + } + raw, dropped, err := RenderDroppingExtensions(pendingKeep.Written) + keepSettlement.settled[i].dropped = dropped + if len(pendingKeep.Value) == 0 { + keepSettlement.pendingKeeps[i].Value, keepSettlement.settled[i].unrendered = raw, err != nil || len(raw) == 0 + } + } + for _, unit := range keepSettlement.units { + for _, part := range unit { + part.render = keepSettlement.renderOf(part) + } + } + return keepSettlement +} + +// addTo adds the pending keep at index i to part, its conjunct's part of the +// pending keep's unit: what a conjunct keeps of a key takes the place of what +// it reads of it, and a second reading of a key it holds already adds nothing. +func (keepSettlement *settlement) addTo(part *conjunctPart, i int) { + pendingKeep := keepSettlement.pendingKeeps[i] + at := slices.IndexFunc(part.members, func(j int) bool { return keepSettlement.pendingKeeps[j].Key == pendingKeep.Key }) + switch { + case at < 0: + part.members = append(part.members, i) + part.every = part.every && pendingKeep.KeptAtEveryConjunctSite + part.consumed = part.consumed && pendingKeep.Source == ConsumedIntoNode + case keepSettlement.pendingKeeps[part.members[at]].Source == ConsumedIntoNode && pendingKeep.Source != ConsumedIntoNode: + part.members[at] = i + part.consumed = !slices.ContainsFunc(part.members, func(j int) bool { return keepSettlement.pendingKeeps[j].Source != ConsumedIntoNode }) + default: + } +} + +// renderOf renders part's members, each as key and canonical value, in one +// order whatever the order they were added in. +func (keepSettlement *settlement) renderOf(part *conjunctPart) string { + if len(part.members) == 1 { + pendingKeep := keepSettlement.pendingKeeps[part.members[0]] + return pendingKeep.Key + "=" + CanonicalRendering(pendingKeep.Value) + } + parts := make([]string, 0, len(part.members)) + for _, i := range part.members { + pendingKeep := keepSettlement.pendingKeeps[i] + parts = append(parts, pendingKeep.Key+"="+CanonicalRendering(pendingKeep.Value)) + } + slices.Sort(parts) + return strings.Join(parts, "\x00") +} + +// markWhole marks each entry kept whole: for a cause read before lowering, or +// as an entry nothing lowers from keeping a unit another conjunct writes +// otherwise, where JSON holds it whole. An entry kept whole writes no keyword +// for anyone else, and one folding writes what every conjunct agrees on. +func (keepSettlement *settlement) markWhole() { + for _, pointer := range keepSettlement.order { + if entry := keepSettlement.entries[pointer]; entry.KeptWhole && len(entry.Whole) > 0 { + keepSettlement.whole[pointer] = true + } + } + keepSettlement.noteWholeLowered() + var collided []jsontext.Pointer + for _, unit := range keepSettlement.units { + live := slices.DeleteFunc(slices.Clone(unit), func(part *conjunctPart) bool { return keepSettlement.heldWhole(part.site) }) + if distinctRenders(live) < 2 { + continue + } + kept := slices.DeleteFunc(slices.Clone(live), func(part *conjunctPart) bool { return part.consumed }) + for _, part := range kept { + entry, ok := keepSettlement.entries[part.site.Pointer] + if !ok || part.site.Role != WritesBeside || len(entry.Whole) == 0 || foldedOnly(keepSettlement.pendingKeeps, part) || entry.AgainstKept && distinctRenders(kept) < 2 { + continue + } + collided = append(collided, part.site.Pointer) + } + } + for _, pointer := range collided { + keepSettlement.whole[pointer] = true + keepSettlement.collided[pointer] = true + } + keepSettlement.noteWholeLowered() +} + +// noteWholeLowered lists the entries kept whole the position lowers from, each +// holding what is written inside it. +func (keepSettlement *settlement) noteWholeLowered() { + keepSettlement.wholeLowered = keepSettlement.wholeLowered[:0] + for _, pointer := range keepSettlement.order { + if entry := keepSettlement.entries[pointer]; keepSettlement.whole[pointer] && entry.Site.Role == WritesLoweredFrom { + keepSettlement.wholeLowered = append(keepSettlement.wholeLowered, entry.Site) + } + } +} + +// foldedOnly reports whether every pending keep of part is its conjunct's +// fold's (KeptByFold). +func foldedOnly(pendingKeeps []PendingKeep, part *conjunctPart) bool { + return !slices.ContainsFunc(part.members, func(i int) bool { return pendingKeeps[i].Source != KeptByFold }) +} + +// distinctRenders counts the values the parts of unit write. +func distinctRenders(unit []*conjunctPart) int { + if len(unit) < 2 { + return len(unit) + } + seen := make(map[string]bool, len(unit)) + for _, part := range unit { + seen[part.render] = true + } + return len(seen) +} + +// heldWhole reports whether what site writes is held by an entry kept whole: +// its own, or one it lowers from that surrounds it. +func (keepSettlement *settlement) heldWhole(site ConjunctSite) bool { + if keepSettlement.whole[site.Pointer] { + return true + } + return slices.ContainsFunc(keepSettlement.wholeLowered, func(around ConjunctSite) bool { return around.contains(site) }) +} + +// settleUnit places each part of unit (Settle). +func (keepSettlement *settlement) settleUnit(unit []*conjunctPart) { + var live, held []*conjunctPart + for _, part := range unit { + if slices.ContainsFunc(part.members, func(i int) bool { return keepSettlement.settled[i].unrendered }) { + // A value no JSON holds is alike to nothing: its chosen part + // refuses it as written flat. + keepSettlement.place(part, placedPlain) + continue + } + if keepSettlement.heldWhole(part.site) && !part.every { + held = append(held, part) + keepSettlement.place(part, placedWhole) + continue + } + live = append(live, part) + } + live = keepSettlement.leftAround(keepSettlement.unheld(live), held) + if len(live) == 0 { + return + } + // An entry kept whole for what it writes otherwise still writes it; one + // kept whole for another cause writes it for no one else. + conjuncts := slices.Concat(live, slices.DeleteFunc(slices.Clone(held), func(part *conjunctPart) bool { return !keepSettlement.collided[part.site.Pointer] })) + if distinctRenders(conjuncts) == 1 { + keepSettlement.settleAlike(live) + return + } + outer := outermost(conjuncts) + for _, group := range groupByRender(live) { + chosenPart := outermost(group) + switch { + case chosenPart == nil: + // No conjunct of the value surrounds the others, so none holds + // another's part: each keeps its own. + for _, part := range group { + keepSettlement.placeFor(part, []*conjunctPart{part}, placedApart) + } + case outer != nil && chosenPart.site.Pointer == outer.site.Pointer, chosenPart.site.Role == WritesAtPosition: + keepSettlement.placeFor(chosenPart, group, placedPlain) + default: + keepSettlement.placeFor(chosenPart, group, placedApart) + } + } +} + +// placeFor settles chosenPart, the part group keeps its one value by, as where: +// where chosenPart reads the value into the node, by the first part of group +// keeping it, under chosenPart's key, so a value a field holds is written +// nowhere and one written alike by a conjunct that reads it is kept where that +// conjunct is. +func (keepSettlement *settlement) placeFor(chosenPart *conjunctPart, group []*conjunctPart, where placement) { + if !chosenPart.consumed { + keepSettlement.place(chosenPart, where) + return + } + at := slices.IndexFunc(group, func(part *conjunctPart) bool { return !part.consumed }) + if at < 0 { + return + } + keepSettlement.place(group[at], where) + for _, i := range group[at].members { + keepSettlement.settled[i].apartAt = chosenPart.site.Pointer + } +} + +// unheld returns live less what a conjunct kept whole writes, kept at every +// conjunct, where another conjunct writes the unit too: an entry kept whole is +// no conjunct writing what it folds, which it holds, but a key no other +// conjunct writes. +func (keepSettlement *settlement) unheld(live []*conjunctPart) []*conjunctPart { + whole := func(part *conjunctPart) bool { return keepSettlement.heldWhole(part.site) } + if !slices.ContainsFunc(live, whole) || !slices.ContainsFunc(live, func(part *conjunctPart) bool { return !whole(part) }) { + return live + } + return slices.DeleteFunc(live, whole) +} + +// leftAround returns live less each part an entry it surrounds, one the +// position lowers from, holds kept whole alike, but a key kept at every +// conjunct: that entry holds the one part +// (docs/compilers/openapi.md#allof-refinement). +func (keepSettlement *settlement) leftAround(live, held []*conjunctPart) []*conjunctPart { + if len(keepSettlement.wholeLowered) == 0 { + return live + } + inside := map[string][]ConjunctSite{} + for _, heldPart := range held { + if heldPart.site.Role == WritesLoweredFrom { + inside[heldPart.render] = append(inside[heldPart.render], heldPart.site) + } + } + if len(inside) == 0 { + return live + } + return slices.DeleteFunc(live, func(part *conjunctPart) bool { + return !part.every && !part.consumed && slices.ContainsFunc(inside[part.render], func(conjunctSite ConjunctSite) bool { return part.site.contains(conjunctSite) }) + }) +} + +// settleAlike places live, parts of one value, as one entry: the outermost +// conjunct's, else, written by entries none of which surrounds another, the +// nearest's for a keyword binding a use and the first's at the position for any +// other. Its one report is the chosen part's, at the position where nothing but +// order tells the chosen part from another conjunct: it binds a use, or another +// entry is written alike. +func (keepSettlement *settlement) settleAlike(live []*conjunctPart) { + if chosenPart := outermost(live); chosenPart != nil { + keepSettlement.placeFor(chosenPart, live, placedPlain) + return + } + live = slices.DeleteFunc(slices.Clone(live), func(part *conjunctPart) bool { return part.consumed }) + if len(live) == 0 { + return + } + chosenPart := live[0] + if useBinding(keepSettlement.pendingKeeps[chosenPart.members[0]].Keyword) { + for _, part := range live { + if part.site.Order < chosenPart.site.Order { + chosenPart = part + } + } + keepSettlement.place(chosenPart, placedPlain) + reportAtPosition(keepSettlement.settled, chosenPart, len(live) > 1) + return + } + // Which of several alike reports the one part turns on the entries as + // written, and where two are written alike, on the position. + chosenPart = slices.MinFunc(live, func(a, b *conjunctPart) int { + return cmp.Or(strings.Compare(keepSettlement.renderedWhole(a.site.Pointer), keepSettlement.renderedWhole(b.site.Pointer)), + strings.Compare(string(a.site.Pointer), string(b.site.Pointer))) + }) + keepSettlement.place(chosenPart, placedPlain) + for _, i := range chosenPart.members { + keepSettlement.settled[i].relocated = true + } + whole := keepSettlement.renderedWhole(chosenPart.site.Pointer) + reportAtPosition(keepSettlement.settled, chosenPart, slices.ContainsFunc(live, func(part *conjunctPart) bool { + return part != chosenPart && keepSettlement.renderedWhole(part.site.Pointer) == whole + })) +} + +// reportAtPosition says in settled, by pending keep, that chosenPart's pending +// keeps report at the position where tied says nothing but order tells +// chosenPart from another conjunct of its value. +func reportAtPosition(settled []pendingKeepSettlement, chosenPart *conjunctPart, tied bool) { + for _, i := range chosenPart.members { + settled[i].atPosition = tied + } +} + +// renderedWhole is the Whole of the entry written at pointer as rendered for +// comparison (CanonicalRendering), rendered once per settlement. +func (keepSettlement *settlement) renderedWhole(pointer jsontext.Pointer) string { + if rendered, seen := keepSettlement.wholeRendering[pointer]; seen { + return rendered + } + rendered := CanonicalRendering(keepSettlement.entries[pointer].Whole) + keepSettlement.wholeRendering[pointer] = rendered + return rendered +} + +// useBinding reports whether keyword binds a use, kept at the nearest entry +// writing it where several write it alike: a use-bound keyword, and the xml a +// parameter, which holds no XML field, keeps beside it. +func useBinding(keyword string) bool { + return keyword == "default" || keyword == "readOnly" || keyword == "writeOnly" || keyword == "xml" +} + +// outermost returns the part of parts whose conjunct surrounds every other, nil +// where none does: the position's, else the one nearest the position of +// conjuncts each surrounding those below it. +func outermost(parts []*conjunctPart) *conjunctPart { + if len(parts) == 1 { + return parts[0] + } + var candidate *conjunctPart + for _, part := range parts { + switch { + case part.site.Role == WritesAtPosition: + return part + case candidate == nil || len(part.site.Pointer) < len(candidate.site.Pointer): + candidate = part + } + } + if slices.ContainsFunc(parts, func(other *conjunctPart) bool { return !candidate.site.contains(other.site) }) { + return nil + } + return candidate +} + +// groupByRender groups parts by the value each writes, in the order first met. +func groupByRender(parts []*conjunctPart) [][]*conjunctPart { + var out [][]*conjunctPart + at := make(map[string]int, len(parts)) + for _, part := range parts { + i, seen := at[part.render] + if !seen { + at[part.render] = len(out) + out = append(out, []*conjunctPart{part}) + continue + } + out[i] = append(out[i], part) + } + return out +} + +// place settles each pending keep of part as where. +func (keepSettlement *settlement) place(part *conjunctPart, where placement) { + for _, i := range part.members { + keepSettlement.settled[i].placed = where + } +} + +// write writes what settled and draws its reports, in the order added: each +// pending keep kept plain under its key with its reports, or by its keeping +// with the others it keeps, and each entry kept whole or apart under its entry +// key with its own. +func (keepSettlement *settlement) write() (ir.Unmodeled, []ir.Diagnostic) { + out := ir.Unmodeled{} + pending := keepSettlement.index() + written := map[jsontext.Pointer]bool{} + var diags []ir.Diagnostic + for i := range keepSettlement.pendingKeeps { + diags = append(diags, keepSettlement.writePendingKeep(&out, i, pending, written)...) + } + for _, pointer := range keepSettlement.order { + if keepSettlement.whole[pointer] && !written[pointer] { + diags = append(diags, keepSettlement.writeEntry(&out, keepSettlement.entries[pointer].Site)...) + } + } + relocate(out, keepSettlement.pendingKeeps, keepSettlement.settled, keepSettlement.position) + return out, diags +} + +// index settles what a reading pending keeps as nowhere, lists the pending +// keeps kept apart by the entry key holding them, and returns the keywords each +// keeping keeps plain. +func (keepSettlement *settlement) index() map[pendingKeeping][]string { + pending := map[pendingKeeping][]string{} + keepSettlement.apartBy = map[jsontext.Pointer][]int{} + for i, pendingKeep := range keepSettlement.pendingKeeps { + if pendingKeep.Source == ConsumedIntoNode { + keepSettlement.settled[i].placed = placedNowhere + } + switch { + case keepSettlement.settled[i].placed == placedApart: + keepSettlement.apartBy[keepSettlement.settled[i].apartAt] = append(keepSettlement.apartBy[keepSettlement.settled[i].apartAt], i) + case keepSettlement.settled[i].placed == placedPlain && pendingKeep.KeptBy != nil: + key := pendingKeeping{keeping: pendingKeep.KeptBy, atPosition: keepSettlement.settled[i].atPosition} + pending[key] = appendNew(pending[key], pendingKeep.Keyword) + default: + } + } + return pending +} + +// writePendingKeep writes the pending keep at index i as it settled: plain +// (keepPlain), or with the entry its key holds, which written says is written +// already. A conjunct held by an entry around it kept whole writes nothing of +// its own. +func (keepSettlement *settlement) writePendingKeep(out *ir.Unmodeled, i int, pending map[pendingKeeping][]string, written map[jsontext.Pointer]bool) []ir.Diagnostic { + pendingKeep := keepSettlement.pendingKeeps[i] + switch keepSettlement.settled[i].placed { + case placedPlain: + var position *ir.Provenance + if keepSettlement.settled[i].atPosition { + position = &keepSettlement.position + } + return keepPlain(out, pendingKeep, pending, position) + case placedApart, placedWhole: + var diags []ir.Diagnostic + site := pendingKeep.WrittenBy + if keepSettlement.settled[i].placed == placedApart { + site = ConjunctSite{Pointer: keepSettlement.settled[i].apartAt} + if entry, known := keepSettlement.entries[site.Pointer]; known { + site = entry.Site + } + } + if own := keepSettlement.settled[i].placed == placedApart || keepSettlement.whole[site.Pointer]; own && !written[site.Pointer] { + written[site.Pointer] = true + diags = keepSettlement.writeEntry(out, site) + } + if pendingKeep.Source == KeptByBuild { + diags = append(diags, unmuted(pendingKeep.Report, pendingKeep.muted)...) + } + return diags + default: + return nil + } +} + +// relocate places at position each entry of out a pending keep settled +// relocated writes, one written alike by entries none of which surrounds +// another, as no one conjunct's (settleAlike). +func relocate(out ir.Unmodeled, pendingKeeps []PendingKeep, settled []pendingKeepSettlement, position ir.Provenance) { + for i, pendingKeep := range pendingKeeps { + if entry, ok := out[pendingKeep.Key]; ok && settled[i].relocated { + entry.Provenance = position + out[pendingKeep.Key] = entry + } + } +} + +// appendNew appends keyword to keywords where it is not there already. +func appendNew(keywords []string, keyword string) []string { + if slices.Contains(keywords, keyword) { + return keywords + } + return append(keywords, keyword) +} + +// writeEntry writes under site's entry key what its entry holds: the entry +// whole where kept so, else the keywords it keeps apart, and draws the report +// of that one part. +func (keepSettlement *settlement) writeEntry(out *ir.Unmodeled, site ConjunctSite) []ir.Diagnostic { + entry, known := keepSettlement.entries[site.Pointer] + if !known { + return []ir.Diagnostic{diag.Newf(ir.SeverityError, diag.InternalInvariant, keepSettlement.position, + "internal: a keyword kept apart from %s names no entry the node holds", site.Pointer)} + } + if keepSettlement.whole[site.Pointer] { + _, held, reason := keepSettlement.keywordsOf(site, placedWhole) + held = append(held, readAt(keepSettlement.pendingKeeps, keepSettlement.bySite[site.Pointer], held)...) + KeepInto(out, site.EntryKey, entry.Whole, reason, entry.Provenance) + var diags []ir.Diagnostic + if entry.ReportWhole != nil { + written, _ := wholeMembers(entry.Whole) + diags = unmuted(entry.ReportWhole(orderedBy(held, written), reason), entry.muted) + } + return append(diags, DroppedExtensionDiags(entry.Provenance, entry.Dropped)...) + } + apart, _, reason := keepSettlement.keywordsOf(site, placedApart) + members, err := keepSettlement.apartObject(site, apart, entry.Whole) + if err != nil { + return []ir.Diagnostic{unpreservableDiag(site.EntryKey, entry.Provenance, err)} + } + KeepInto(out, site.EntryKey, members, reason, entry.Provenance) + diags := droppedApart(keepSettlement, site, entry.Provenance) + if entry.ReportApart == nil { + return diags + } + written, _ := wholeMembers(entry.Whole) + var reports []ir.Diagnostic + for _, keys := range keepSettlement.apartReadings(site) { + reports = append(reports, entry.ReportApart(orderedBy(keys, written))...) + } + return append(diags, unmuted(reports, entry.muted)...) +} + +// droppedApart warns of each vendor extension that a pending keep in +// pendingKeeps keeps apart under site's key leaves out of the value written +// (pendingKeepSettlement.dropped), at the keyword its conjunct writes, credited +// as the entry kept at held, the entry it settled under, is. +func droppedApart(keepSettlement *settlement, site ConjunctSite, held ir.Provenance) []ir.Diagnostic { + apart := keepSettlement.pendingKeepsAt(site, placedApart) + diags := make([]ir.Diagnostic, 0, len(apart)) + for _, i := range apart { + pendingKeep := keepSettlement.pendingKeeps[i] + at := held + at.Pointer = pendingKeep.WrittenBy.Pointer + ids.Ptr(pendingKeep.Keyword) + diags = append(diags, DroppedExtensionDiags(at, keepSettlement.settled[i].dropped)...) + } + return diags +} + +// apartReadings returns the keywords site keeps apart that no chosen part +// reported where kept, by the reading keeping them, in the order added: each +// keeping's own, and the rest as one. +func (keepSettlement *settlement) apartReadings(site ConjunctSite) [][]string { + var out [][]string + at := map[any]int{} + for _, i := range keepSettlement.pendingKeepsAt(site, placedApart) { + pendingKeep := keepSettlement.pendingKeeps[i] + if keepSettlement.settled[i].placed != placedApart || pendingKeep.Source == KeptByBuild { + continue + } + var group any = pendingKeep.KeptBy + if pendingKeep.reading != nil { + group = pendingKeep.reading + } + order, seen := at[group] + if !seen { + order = len(out) + at[group] = order + out = append(out, nil) + } + out[order] = appendNew(out[order], pendingKeep.Keyword) + } + return out +} + +// keywordsOf returns the keywords of the pending keeps site settled as where, +// in the order pending, all of them and those no chosen part reported where +// kept, and the reason they share, else degraded_lowering: of an entry kept +// whole, the reason what it leaves unread shares, what its fold keeps typed as +// any entry's is. +func (keepSettlement *settlement) keywordsOf(site ConjunctSite, where placement) (all, unreported []string, reason ir.UnmodeledReason) { + counted := 0 + for _, i := range keepSettlement.pendingKeepsAt(site, where) { + pendingKeep := keepSettlement.pendingKeeps[i] + if keepSettlement.settled[i].placed != where { + continue + } + all = appendNew(all, pendingKeep.Keyword) + if pendingKeep.Source != KeptByBuild { + unreported = appendNew(unreported, pendingKeep.Keyword) + } + if where == placedWhole && pendingKeep.Source == KeptByFold { + continue + } + switch { + case counted == 0: + reason = pendingKeep.Reason + case reason != pendingKeep.Reason: + reason = ir.ReasonDegradedLowering + } + counted++ + } + if counted == 0 { + reason = ir.ReasonDegradedLowering + } + return all, unreported, reason +} + +// readAt returns the keywords the pending keeps at, indices into pending keeps +// of one conjunct's, read into the node, but those of named: the conjunct's +// entry kept whole holds them too, so its report names them. +func readAt(pendingKeeps []PendingKeep, at []int, named []string) []string { + var out []string + for _, i := range at { + if keyword := pendingKeeps[i].Keyword; pendingKeeps[i].Source == ConsumedIntoNode && !slices.Contains(named, keyword) { + out = appendNew(out, keyword) + } + } + return out +} + +// pendingKeepsAt returns the indices of the pending keeps site holds as where: +// its own kept whole, or those kept apart under its key, its own and another +// conjunct's it takes the place of (placeFor). +func (keepSettlement *settlement) pendingKeepsAt(site ConjunctSite, where placement) []int { + if where != placedApart { + return keepSettlement.bySite[site.Pointer] + } + return keepSettlement.apartBy[site.Pointer] +} + +// apartObject renders the keywords apart that site keeps as one object, each +// member spelled as whole, the entry as written, holds it, though another +// conjunct's alike reading takes the place of it there (placeFor), else as +// pending, in the order whole writes them. +func (keepSettlement *settlement) apartObject(site ConjunctSite, apart []string, whole jsontext.Value) (jsontext.Value, error) { + written, members := wholeMembers(whole) + for _, i := range keepSettlement.pendingKeepsAt(site, placedApart) { + pendingKeep := keepSettlement.pendingKeeps[i] + if _, held := members[pendingKeep.Keyword]; !held { + members[pendingKeep.Keyword] = pendingKeep.Value + } + } + buf := []byte{'{'} + for index, keyword := range orderedBy(apart, written) { + name, err := jsontext.AppendQuote(nil, keyword) + if err != nil { + return nil, fmt.Errorf("render kept keyword %q: %w", keyword, err) + } + if index > 0 { + buf = append(buf, ',') + } + buf = append(append(append(buf, name...), ':'), members[keyword]...) + } + return jsontext.Value(append(buf, '}')), nil +} diff --git a/compilers/openapi/internal/annotation/pendingkeeps_internal_test.go b/compilers/openapi/internal/annotation/pendingkeeps_internal_test.go new file mode 100644 index 000000000..c3773e74e --- /dev/null +++ b/compilers/openapi/internal/annotation/pendingkeeps_internal_test.go @@ -0,0 +1,1158 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package annotation + +import ( + "encoding/json/jsontext" + "fmt" + "maps" + "slices" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ynode" + "github.com/dexpace/morphic/ir" +) + +// fixturePositionPointer is the schema whose node each pending keeps here settles. +const fixturePositionPointer jsontext.Pointer = "/components/schemas/Pet" + +// fixturePlace is the provenance of what is written at pointer. +func fixturePlace(pointer jsontext.Pointer) ir.Provenance { + return ir.Provenance{Pointer: pointer} +} + +// fixturePositionSite is the site of the conjunct writing the schema at the +// position. +func fixturePositionSite() ConjunctSite { + return ConjunctSite{Pointer: fixturePositionPointer, Role: WritesAtPosition, Order: BesideAllOf} +} + +// fixtureEntrySite is the site of the conjunct writing the allOf entry at path +// below the position, related to it as role says, order its index as flattened. +func fixtureEntrySite(path string, role ConjunctRole, order int) ConjunctSite { + return ConjunctSite{ + Pointer: fixturePositionPointer + jsontext.Pointer("/"+path), EntryKey: "openapi:" + path, Role: role, Order: ConjunctIndex(order), + } +} + +// fixtureWrapperSite is a wrapper at allOf/0 the position lowers from. +func fixtureWrapperSite() ConjunctSite { return fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) } + +// fixtureNestedPrincipalSite is the principal flattened out of the wrapper's +// allOf, which the position lowers from too. +func fixtureNestedPrincipalSite() ConjunctSite { + return fixtureEntrySite("allOf/0/allOf/0", WritesLoweredFrom, 1) +} + +// fixtureKeywordPointer is where site writes keyword. +func fixtureKeywordPointer(site ConjunctSite, keyword string) jsontext.Pointer { + return site.Pointer + "/" + jsontext.Pointer(keyword) +} + +// fixturePendingKeep is site keeping value, as JSON, of keyword under the keyword's +// own key, located at the keyword and reported by fixturePendingKeepReport. +func fixturePendingKeep(site ConjunctSite, keyword, value string) PendingKeep { + return PendingKeep{ + Key: "openapi:" + keyword, Keyword: keyword, Value: jsontext.Value(value), Reason: ir.ReasonDegradedLowering, + Report: []ir.Diagnostic{fixturePendingKeepReport(site, keyword)}, + Provenance: fixturePlace(fixtureKeywordPointer(site, keyword)), WrittenBy: site, + } +} + +// fixtureRead is fixturePendingKeep read into the node rather than kept. +func fixtureRead(site ConjunctSite, keyword, value string) PendingKeep { + pendingKeep := fixturePendingKeep(site, keyword, value) + pendingKeep.Source = ConsumedIntoNode + return pendingKeep +} + +// fixturePendingKeepReport is the report the chosen part of keyword at site +// draws. +func fixturePendingKeepReport(site ConjunctSite, keyword string) ir.Diagnostic { + return diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, fixturePlace(fixtureKeywordPointer(site, keyword)), "%s kept", keyword) +} + +// fixtureJSON is text as JSON, nil for "", which no JSON holds. +func fixtureJSON(text string) jsontext.Value { + if text == "" { + return nil + } + return jsontext.Value(text) +} + +// fixtureEntry records the entry site writes, whole as JSON, "" where no JSON +// holds it, drawing fixtureWholeReport and fixtureApartReport. +func fixtureEntry(site ConjunctSite, whole string) KeptAllOfEntry { + return KeptAllOfEntry{ + Site: site, Whole: fixtureJSON(whole), Provenance: fixturePlace(site.Pointer), + ReportWhole: func(held []string, reason ir.UnmodeledReason) []ir.Diagnostic { + return []ir.Diagnostic{fixtureWholeReport(site, held, reason)} + }, + ReportApart: func(apart []string) []ir.Diagnostic { + return []ir.Diagnostic{fixtureApartReport(site, apart)} + }, + } +} + +// fixtureWholeReport is the report of site's entry kept whole as reason, +// naming held. +func fixtureWholeReport(site ConjunctSite, held []string, reason ir.UnmodeledReason) ir.Diagnostic { + return diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, fixturePlace(site.Pointer), "kept whole as %s, naming %q", reason, held) +} + +// fixtureApartReport is the report of what site's entry keeps apart, naming +// apart. +func fixtureApartReport(site ConjunctSite, apart []string) ir.Diagnostic { + return diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, fixturePlace(site.Pointer), "kept apart, naming %q", apart) +} + +// fixtureKeeping keeps each keyword it is handed under the keyword's own key +// at the position, as values writes it, nothing where values writes none, and +// reports them in one fixtureKeepingReport. +func fixtureKeeping(values map[string]string) *KeptKeywordKeeping { + return &KeptKeywordKeeping{Keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + for _, key := range keys { + KeepInto(unmodeled, "openapi:"+key, fixtureJSON(values[key]), ir.ReasonOutOfScope, fixturePlace(fixturePositionPointer)) + } + return []ir.Diagnostic{fixtureKeepingReport(keys)} + }} +} + +// fixtureKeepingReport is the one report of a fixtureKeeping handed keys. +func fixtureKeepingReport(keys []string) ir.Diagnostic { + return diag.Newf(ir.SeverityInfo, diag.UnknownSchemaKeyword, fixturePlace(fixturePositionPointer), "kept together: %q", keys) +} + +// fixtureKeptByKeeping is what a fixtureKeeping writes of value. +func fixtureKeptByKeeping(value string) ir.UnmodeledEntry { + return ir.UnmodeledEntry{Reason: ir.ReasonOutOfScope, Value: jsontext.Value(value), Provenance: fixturePlace(fixturePositionPointer)} +} + +// fixtureKeptPlain is pending keep kept under its own key, as pending. +func fixtureKeptPlain(pendingKeep PendingKeep) ir.UnmodeledEntry { + return ir.UnmodeledEntry{Reason: pendingKeep.Reason, Value: pendingKeep.Value, Provenance: pendingKeep.Provenance} +} + +// fixtureKeptAt is value, as JSON, kept under entry's key as reason, located at +// the entry. +func fixtureKeptAt(entry KeptAllOfEntry, value string, reason ir.UnmodeledReason) ir.UnmodeledEntry { + return ir.UnmodeledEntry{Reason: reason, Value: jsontext.Value(value), Provenance: entry.Provenance} +} + +// fixtureKeptWhole is entry kept whole under its key as reason. +func fixtureKeptWhole(entry KeptAllOfEntry, reason ir.UnmodeledReason) ir.UnmodeledEntry { + return fixtureKeptAt(entry, string(entry.Whole), reason) +} + +// fixtureReportedAtPosition is reports drawn at the position, as the node draws +// the report of a value only order tells its conjuncts of apart. +func fixtureReportedAtPosition(reports ...ir.Diagnostic) []ir.Diagnostic { + out := slices.Clone(reports) + for i := range out { + out[i].Provenance = fixturePlace(fixturePositionPointer) + } + return out +} + +// fixturePendingKeeps is a pending keeps recording entries, then pending keeps, in the order given. +func fixturePendingKeeps(entries []KeptAllOfEntry, pendingKeeps ...PendingKeep) *PendingKeeps { + var keepSettlement PendingKeeps + for _, entry := range entries { + keepSettlement.AddEntry(entry) + } + for _, pendingKeep := range pendingKeeps { + keepSettlement.Add(pendingKeep) + } + return &keepSettlement +} + +// fixtureReversed is values in reverse, a copy. +func fixtureReversed[T any](values []T) []T { + out := slices.Clone(values) + slices.Reverse(out) + return out +} + +// fixtureSettleRow is a pending keeps's entries and pending keeps and what the rule says it +// settles as: the Unmodeled entries and the reports, in the order drawn. +type fixtureSettleRow struct { + entries []KeptAllOfEntry + pendingKeeps []PendingKeep + want ir.Unmodeled + reports []ir.Diagnostic +} + +// runPendingKeepSettleRows settles each of rows in a subtest of its own. +func runPendingKeepSettleRows(t *testing.T, rows map[string]fixtureSettleRow) { + t.Helper() + for name, row := range rows { + t.Run(name, func(t *testing.T) { + t.Parallel() + assertPendingKeepsSettle(t, fixturePendingKeeps(row.entries, row.pendingKeeps...), row.want, row.reports) + }) + } +} + +// assertPendingKeepsSettle settles pending keeps at the position and holds what it keeps +// to want and what it reports to reports, an empty collection matching an +// absent one. +func assertPendingKeepsSettle(t *testing.T, keepSettlement *PendingKeeps, want ir.Unmodeled, reports []ir.Diagnostic) { + t.Helper() + gotUnmodeled, gotReports := keepSettlement.Settle(fixturePlace(fixturePositionPointer)) + assert.Empty(t, cmp.Diff(want, gotUnmodeled, cmpopts.EquateEmpty()), "the Unmodeled settled (-want +got)") + assert.Empty(t, cmp.Diff(reports, gotReports, cmpopts.EquateEmpty()), "the reports drawn (-want +got)") +} + +// TestAdd_APendingKeepThatKeepsNothingIsRefused pins Add's refusal: a pending keep with +// neither a value nor a node to render one from keeps nothing, nor does one +// under no key, and either leaves the pending keeps empty, as does any pending keep added +// once the pending keeps has settled, while a pending keep holding a value or a node under +// a key is recorded. +func TestAdd_APendingKeepThatKeepsNothingIsRefused(t *testing.T) { + t.Parallel() + written := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "A"} + for name, tc := range map[string]struct { + pendingKeep PendingKeep + keywords []string + settled bool + }{ + // A pending keep holding nothing to keep is refused. + "no value and no node": {pendingKeep: PendingKeep{Key: "openapi:title", Keyword: "title"}}, + // A pending keep with nowhere to be kept is refused. + "no key": {pendingKeep: PendingKeep{Keyword: "title", Value: jsontext.Value(`"A"`)}}, + // A node is the value it renders to. + "a node and no value": { + pendingKeep: PendingKeep{Key: "openapi:title", Keyword: "title", Written: written}, keywords: []string{"title"}, + }, + // A value under a key is recorded. + "a value under a key": { + pendingKeep: PendingKeep{Key: "openapi:title", Keyword: "title", Value: jsontext.Value(`"A"`)}, + keywords: []string{"title"}, + }, + // A pending keep settles once, so one that has settled records nothing. + "a value under a key, the pending keep settled": { + pendingKeep: PendingKeep{Key: "openapi:title", Keyword: "title", Value: jsontext.Value(`"A"`)}, settled: true, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + var keepSettlement PendingKeeps + if tc.settled { + keepSettlement.Settle(fixturePlace(fixturePositionPointer)) + } + keepSettlement.Add(tc.pendingKeep) + assert.Equal(t, len(tc.keywords) == 0, keepSettlement.Empty()) + assert.Equal(t, tc.keywords, keepSettlement.Keywords()) + }) + } +} + +// TestAddEntry_SettledPendingKeepsRecordNoEntry pins AddEntry's refusal: a +// pending keeps settles once, so an entry recorded after it settled, alone or +// through AddAll, leaves it empty. +func TestAddEntry_SettledPendingKeepsRecordNoEntry(t *testing.T) { + t.Parallel() + entry := fixtureEntry(fixtureEntrySite("allOf/0", WritesBeside, 0), `{}`) + var keepSettlement PendingKeeps + keepSettlement.Settle(fixturePlace(fixturePositionPointer)) + keepSettlement.AddEntry(entry) + assert.True(t, keepSettlement.Empty(), "an entry recorded alone") + keepSettlement.AddAll(*fixturePendingKeeps([]KeptAllOfEntry{entry})) + assert.True(t, keepSettlement.Empty(), "an entry recorded through AddAll") +} + +// TestSettle_NoPendingKeepSettlesNothing pins the settlement of a pending keeps +// holding nothing: no Unmodeled entry and no report. +func TestSettle_NoPendingKeepSettlesNothing(t *testing.T) { + t.Parallel() + var keepSettlement PendingKeeps + unmodeled, reports := keepSettlement.Settle(fixturePlace(fixturePositionPointer)) + assert.Empty(t, unmodeled) + assert.Empty(t, reports) +} + +// TestKeywords_EachKeptKeywordOnceInTheOrderFirstAdded pins Keywords: each +// keyword a conjunct keeps, once, in the order first added, and none a conjunct +// only reads into the node. +func TestKeywords_EachKeptKeywordOnceInTheOrderFirstAdded(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesBeside, 0) + keepSettlement := fixturePendingKeeps(nil, + fixtureRead(position, "description", `"D"`), + fixturePendingKeep(position, "minimum", "1"), + fixturePendingKeep(beside, "title", `"A"`), + fixturePendingKeep(beside, "minimum", "2"), + fixtureRead(beside, "title", `"B"`)) + assert.Equal(t, []string{"minimum", "title"}, keepSettlement.Keywords()) +} + +// TestSettle_ThePositionAloneKeepsEachPendingKeepAsAdded pins the settlement of +// one conjunct: each pending keep kept under its key as pending, and a keeping +// called once, at its first pending keep, with each keyword it keeps once, its +// reports drawn where that pending keep's would be, in the order pending. +func TestSettle_ThePositionAloneKeepsEachPendingKeepAsAdded(t *testing.T) { + t.Parallel() + position := fixturePositionSite() + keeping := fixtureKeeping(map[string]string{"minimum": "1", "maximum": "9"}) + title, description := fixturePendingKeep(position, "title", `"A"`), fixturePendingKeep(position, "description", `"D"`) + minimum, maximum := fixturePendingKeep(position, "minimum", "1"), fixturePendingKeep(position, "maximum", "9") + minimum.KeptBy, maximum.KeptBy = keeping, keeping + // The keeping's second pending keep of maximum hands the keyword over once. + keepSettlement := fixturePendingKeeps(nil, title, minimum, maximum, maximum, description) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{ + "openapi:title": fixtureKeptPlain(title), + "openapi:minimum": fixtureKeptByKeeping("1"), + "openapi:maximum": fixtureKeptByKeeping("9"), + "openapi:description": fixtureKeptPlain(description), + }, []ir.Diagnostic{title.Report[0], fixtureKeepingReport([]string{"minimum", "maximum"}), description.Report[0]}) +} + +// TestSettle_ADroppedReportIsDrawnNowhereAndLeftInItsPendingKeep pins DropReports on +// the position's own pending keeps: the reports it drops, a pending keep's and a keeping's, +// are drawn nowhere, what is kept stays, and the pending keep's own report list is +// left as it was. +func TestSettle_ADroppedReportIsDrawnNowhereAndLeftInItsPendingKeep(t *testing.T) { + t.Parallel() + position := fixturePositionSite() + dropped := diag.Newf(ir.SeverityInfo, diag.UnknownSchemaKeyword, fixturePlace(fixturePositionPointer), "dropped") + title := fixturePendingKeep(position, "title", `"A"`) + title.Report = []ir.Diagnostic{fixturePendingKeepReport(position, "title"), dropped} + held := title.Report + minimum := fixturePendingKeep(position, "minimum", "1") + minimum.KeptBy = fixtureKeeping(map[string]string{"minimum": "1"}) + keepSettlement := fixturePendingKeeps(nil, title, minimum) + keepSettlement.DropReports(func(report ir.Diagnostic) bool { return report.Code == diag.UnknownSchemaKeyword }) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{ + "openapi:title": fixtureKeptPlain(title), "openapi:minimum": fixtureKeptByKeeping("1"), + }, []ir.Diagnostic{fixturePendingKeepReport(position, "title")}) + assert.Equal(t, []ir.Diagnostic{fixturePendingKeepReport(position, "title"), dropped}, held, "the pending keep's own reports") +} + +// TestSettle_ReportsAddedPendingKeepsDropAreDrawnNowhere pins DropReports on a +// pending keeps added into the node's (AddAll): every report its conjuncts +// would draw, an entry's kept whole or apart and a pending keep's reported +// where kept, is drawn nowhere, while what they keep stays and the position's +// own reports remain. +func TestSettle_ReportsAddedPendingKeepsDropAreDrawnNowhere(t *testing.T) { + t.Parallel() + position := fixturePositionSite() + principal, beside := fixtureEntrySite("allOf/0", WritesLoweredFrom, 0), fixtureEntrySite("allOf/1", WritesBeside, 1) + whole := fixtureEntry(beside, `{"title":"B","unevaluatedProperties":false}`) + whole.KeptWhole = true + apart := fixtureEntry(principal, `{"minimum":3,"type":"string"}`) + besideTitle := fixturePendingKeep(beside, "title", `"B"`) + besideTitle.Source = KeptByBuild + joined := fixturePendingKeeps([]KeptAllOfEntry{apart, whole}, fixturePendingKeep(principal, "minimum", "3"), besideTitle) + joined.DropReports(func(ir.Diagnostic) bool { return true }) + ownTitle, ownMinimum := fixturePendingKeep(position, "title", `"A"`), fixturePendingKeep(position, "minimum", "1") + keepSettlement := fixturePendingKeeps(nil, ownTitle, ownMinimum) + keepSettlement.AddAll(*joined) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{ + "openapi:title": fixtureKeptPlain(ownTitle), + "openapi:minimum": fixtureKeptPlain(ownMinimum), + "openapi:allOf/0": fixtureKeptAt(apart, `{"minimum":3}`, ir.ReasonDegradedLowering), + "openapi:allOf/1": fixtureKeptWhole(whole, ir.ReasonDegradedLowering), + }, []ir.Diagnostic{ownTitle.Report[0], ownMinimum.Report[0]}) +} + +// TestSettle_AUseBindingKeywordWrittenAlikeIsKeptAtTheNearestEntry pins the +// keywords that bind a use, default, readOnly, writeOnly and xml: written alike +// by entries none of which surrounds another, each is kept at the nearest entry +// writing it, as it pending keeps it, where a keyword binding no use is the +// position's. Order alone tells the two entries apart, so the one report is +// drawn at the position. +func TestSettle_AUseBindingKeywordWrittenAlikeIsKeptAtTheNearestEntry(t *testing.T) { + t.Parallel() + nearest, farther := fixtureEntrySite("allOf/0", WritesBeside, 0), fixtureEntrySite("allOf/1", WritesBeside, 1) + for keyword, atPosition := range map[string]bool{ + "default": false, "readOnly": false, "writeOnly": false, "xml": false, "title": true, + } { + t.Run(keyword, func(t *testing.T) { + t.Parallel() + whole := `{"` + keyword + `":true}` + kept := fixturePendingKeep(nearest, keyword, "true") + want := fixtureKeptPlain(kept) + if atPosition { + want.Provenance = fixturePlace(fixturePositionPointer) + } + keepSettlement := fixturePendingKeeps([]KeptAllOfEntry{fixtureEntry(farther, whole), fixtureEntry(nearest, whole)}, + fixturePendingKeep(farther, keyword, "true"), kept) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{"openapi:" + keyword: want}, fixtureReportedAtPosition(kept.Report...)) + }) + } +} + +// TestSettle_EntriesWrittenAlikeReportTheirOneValueAtThePosition pins a value +// entries written alike keep, none surrounding another: whichever keeps it is +// told from the other by order alone, so the one report is drawn at the +// position, in either order, by the keeping's own wording for that place where +// it has one, and as drawn otherwise. +func TestSettle_EntriesWrittenAlikeReportTheirOneValueAtThePosition(t *testing.T) { + t.Parallel() + first, second := fixtureEntrySite("allOf/0", WritesBeside, 0), fixtureEntrySite("allOf/1", WritesBeside, 1) + entries := []KeptAllOfEntry{fixtureEntry(first, `{"minimum":1}`), fixtureEntry(second, `{"minimum":1}`)} + beside := diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, fixturePlace(first.Pointer), "kept as written beside the allOf") + worded := fixtureKeeping(map[string]string{"minimum": "1"}) + worded.KeepAtPosition = func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + worded.Keep(unmodeled, keys) + return []ir.Diagnostic{beside} + } + unworded := fixtureKeeping(map[string]string{"minimum": "1"}) + keptBy := func(site ConjunctSite, keeping *KeptKeywordKeeping) PendingKeep { + pendingKeep := fixturePendingKeep(site, "minimum", "1") + pendingKeep.Report, pendingKeep.KeptBy = nil, keeping + return pendingKeep + } + kept := fixtureKeptByKeeping("1") + kept.Provenance = fixturePlace(fixturePositionPointer) + want := ir.Unmodeled{"openapi:minimum": kept} + selfReporting := []PendingKeep{fixturePendingKeep(first, "minimum", "1"), fixturePendingKeep(second, "minimum", "1")} + plain := fixtureKeptPlain(selfReporting[0]) + plain.Provenance = fixturePlace(fixturePositionPointer) + rows := map[string]fixtureSettleRow{} + for order, reverse := range map[string]bool{"in order": false, "in reverse": true} { + arrange := func(pendingKeeps ...PendingKeep) []PendingKeep { + if reverse { + return fixtureReversed(pendingKeeps) + } + return pendingKeeps + } + rows[order+", each pending keep reports itself"] = fixtureSettleRow{entries: entries, pendingKeeps: arrange(selfReporting...), + want: ir.Unmodeled{"openapi:minimum": plain}, reports: fixtureReportedAtPosition(selfReporting[0].Report...)} + rows[order+", worded for the position"] = fixtureSettleRow{entries: entries, pendingKeeps: arrange(keptBy(first, worded), keptBy(second, worded)), + want: want, reports: fixtureReportedAtPosition(beside)} + rows[order+", worded alike there"] = fixtureSettleRow{entries: entries, pendingKeeps: arrange(keptBy(first, unworded), keptBy(second, unworded)), + want: want, reports: fixtureReportedAtPosition(fixtureKeepingReport([]string{"minimum"}))} + } + runPendingKeepSettleRows(t, rows) +} + +// TestSettle_AValueThePositionWritesAlikeIsKeptAsThePositionKeepsIt pins +// values compared by rendering: one an entry writes as the position does, +// member order aside, is the position's, kept as it keeps it, while a number +// spelled two ways is two values, the entry's kept whole for writing it +// otherwise. +func TestSettle_AValueThePositionWritesAlikeIsKeptAsThePositionKeepsIt(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/1", WritesBeside, 1) + entry := func(value string) KeptAllOfEntry { + return fixtureEntry(beside, `{"example":`+value+`,"type":"object"}`) + } + text, object, number := fixturePendingKeep(position, "example", `"A"`), fixturePendingKeep(position, "example", `{"a":1,"b":2}`), + fixturePendingKeep(position, "example", "1") + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // One value spelled alike. + "one spelling": { + entries: []KeptAllOfEntry{entry(`"A"`)}, pendingKeeps: []PendingKeep{text, fixturePendingKeep(beside, "example", `"A"`)}, + want: ir.Unmodeled{"openapi:example": fixtureKeptPlain(text)}, reports: text.Report, + }, + // Two parts alike but for the order of their members. + "members in another order": { + entries: []KeptAllOfEntry{entry(`{"b":2,"a":1}`)}, pendingKeeps: []PendingKeep{object, fixturePendingKeep(beside, "example", `{"b":2,"a":1}`)}, + want: ir.Unmodeled{"openapi:example": fixtureKeptPlain(object)}, reports: object.Report, + }, + // 1 and 1.0 are two values. + "a number spelled two ways": { + entries: []KeptAllOfEntry{entry("1.0")}, pendingKeeps: []PendingKeep{number, fixturePendingKeep(beside, "example", "1.0")}, + want: ir.Unmodeled{ + "openapi:example": fixtureKeptPlain(number), "openapi:allOf/1": fixtureKeptWhole(entry("1.0"), ir.ReasonDegradedLowering), + }, + reports: []ir.Diagnostic{number.Report[0], fixtureWholeReport(beside, []string{"example"}, ir.ReasonDegradedLowering)}, + }, + }) +} + +// TestSettle_AValueEveryConjunctReadsIsWrittenNowhere pins a value read into the +// node and kept by no conjunct: it is written nowhere and reported by none, +// whether the position reads it or entries none of which surrounds another read +// it alike. +func TestSettle_AValueEveryConjunctReadsIsWrittenNowhere(t *testing.T) { + t.Parallel() + position := fixturePositionSite() + first, second := fixtureEntrySite("allOf/0", WritesBeside, 0), fixtureEntrySite("allOf/1", WritesBeside, 1) + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The position alone reads it. + "read by the position": {pendingKeeps: []PendingKeep{fixtureRead(position, "title", `"A"`)}}, + // Two entries read it alike. + "read alike by two entries": { + entries: []KeptAllOfEntry{fixtureEntry(first, `{"title":"A"}`), fixtureEntry(second, `{"title":"A"}`)}, + pendingKeeps: []PendingKeep{fixtureRead(first, "title", `"A"`), fixtureRead(second, "title", `"A"`)}, + }, + }) +} + +// TestSettle_AValueAReaderWritesAlikeIsKeptWhereTheReaderIs pins a value +// one conjunct reads and one inside it keeps alike: it is kept by the one +// keeping it, under the key the reader's place gives, the plain key at the +// position and the reader's entry key at a wrapper. +func TestSettle_AValueAReaderWritesAlikeIsKeptWhereTheReaderIs(t *testing.T) { + t.Parallel() + position, wrapper, nested := fixturePositionSite(), fixtureWrapperSite(), fixtureNestedPrincipalSite() + principal := fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + kept, own := fixturePendingKeep(principal, "minimum", "3"), fixturePendingKeep(position, "example", `{"a":0}`) + wrapperEntry := fixtureEntry(wrapper, `{"allOf":[{"example":{"a":1,"b":2}}],"example":{"a":1,"b":2}}`) + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The position reads what the principal keeps alike. + "the position reading": { + entries: []KeptAllOfEntry{fixtureEntry(principal, `{"minimum":3,"type":"string"}`)}, + pendingKeeps: []PendingKeep{fixtureRead(position, "minimum", "3"), kept}, + want: ir.Unmodeled{"openapi:minimum": fixtureKeptPlain(kept)}, reports: kept.Report, + }, + // A wrapper reads what the principal inside it keeps alike, the position otherwise. + "a wrapper reading": { + entries: []KeptAllOfEntry{wrapperEntry, fixtureEntry(nested, `{"example":{"a":1,"b":2}}`)}, + pendingKeeps: []PendingKeep{ + own, fixtureRead(wrapper, "example", `{"a":1,"b":2}`), fixturePendingKeep(nested, "example", `{"a":1,"b":2}`), + }, + want: ir.Unmodeled{ + "openapi:example": fixtureKeptPlain(own), + "openapi:allOf/0": fixtureKeptAt(wrapperEntry, `{"example":{"a":1,"b":2}}`, ir.ReasonDegradedLowering), + }, + reports: []ir.Diagnostic{own.Report[0], fixtureApartReport(wrapper, []string{"example"})}, + }, + }) +} + +// TestSettle_AValueKeptApartIsSpelledAsTheEntryHoldingItWritesIt pins the +// object an entry key holds apart: each keyword as the entry holding it is +// written, where its JSON writes the keyword, else as pending, for the entry's +// own pending keep and for one it holds for a conjunct inside it. +func TestSettle_AValueKeptApartIsSpelledAsTheEntryHoldingItWritesIt(t *testing.T) { + t.Parallel() + position, principal := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + wrapper, nested := fixtureWrapperSite(), fixtureNestedPrincipalSite() + own := fixturePendingKeep(position, "example", `{"a":0}`) + spelled, unwritten := fixtureEntry(principal, `{"example":{"b":2,"a":1},"type":"string"}`), fixtureEntry(principal, `{"type":"string"}`) + wrapperEntry := fixtureEntry(wrapper, `{"allOf":[{"example":{"a":1,"b":2}}],"example":{"b":2,"a":1}}`) + selfReporting := fixturePendingKeep(principal, "example", `{"a":1,"b":2}`) + ownReports := []ir.Diagnostic{own.Report[0], fixtureApartReport(principal, []string{"example"})} + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The entry's JSON spells the keyword's members in another order. + "the entry writing it": { + entries: []KeptAllOfEntry{spelled}, pendingKeeps: []PendingKeep{own, selfReporting}, + want: ir.Unmodeled{ + "openapi:example": fixtureKeptPlain(own), + "openapi:allOf/0": fixtureKeptAt(spelled, `{"example":{"b":2,"a":1}}`, ir.ReasonDegradedLowering), + }, + reports: ownReports, + }, + // The entry's JSON writes no such keyword. + "the entry writing it not": { + entries: []KeptAllOfEntry{unwritten}, pendingKeeps: []PendingKeep{own, selfReporting}, + want: ir.Unmodeled{ + "openapi:example": fixtureKeptPlain(own), + "openapi:allOf/0": fixtureKeptAt(unwritten, `{"example":{"a":1,"b":2}}`, ir.ReasonDegradedLowering), + }, + reports: ownReports, + }, + // A wrapper reading the keyword holds what the principal inside it keeps alike. + "a wrapper holding it for the principal": { + entries: []KeptAllOfEntry{wrapperEntry, fixtureEntry(nested, `{"example":{"a":1,"b":2}}`)}, + pendingKeeps: []PendingKeep{ + own, fixtureRead(wrapper, "example", `{"b":2,"a":1}`), fixturePendingKeep(nested, "example", `{"a":1,"b":2}`), + }, + want: ir.Unmodeled{ + "openapi:example": fixtureKeptPlain(own), + "openapi:allOf/0": fixtureKeptAt(wrapperEntry, `{"example":{"b":2,"a":1}}`, ir.ReasonDegradedLowering), + }, + reports: []ir.Diagnostic{own.Report[0], fixtureApartReport(wrapper, []string{"example"})}, + }, + }) +} + +// TestSettle_AnEntryBesideNotKeptWholeHoldsWhatItKeepsApart pins the entries +// nothing lowers from that a value otherwise does not keep whole, each held +// keyword by keyword under its entry key: one measured only against what is +// kept, beside a value read; one no JSON holds, even kept whole for a cause; +// and one whose fold writes it. +func TestSettle_AnEntryBesideNotKeptWholeHoldsWhatItKeepsApart(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/1", WritesBeside, 1) + entry, unheld := fixtureEntry(beside, `{"minimum":2,"properties":{"id":{}}}`), fixtureEntry(beside, "") + againstKept, causeUnheld := entry, unheld + againstKept.AgainstKept, causeUnheld.KeptWhole = true, true + kept, besides := fixturePendingKeep(position, "minimum", "1"), fixturePendingKeep(beside, "minimum", "2") + folded := besides + folded.Source = KeptByFold + apart := []ir.Diagnostic{kept.Report[0], fixtureApartReport(beside, []string{"minimum"})} + keptAndApart := func(entry KeptAllOfEntry) ir.Unmodeled { + return ir.Unmodeled{ + "openapi:minimum": fixtureKeptPlain(kept), "openapi:allOf/1": fixtureKeptAt(entry, `{"minimum":2}`, ir.ReasonDegradedLowering), + } + } + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // Measured only against what is kept, beside a value the position reads. + "against kept, a value read otherwise": { + entries: []KeptAllOfEntry{againstKept}, pendingKeeps: []PendingKeep{fixtureRead(position, "minimum", "1"), besides}, + want: ir.Unmodeled{"openapi:allOf/1": fixtureKeptAt(entry, `{"minimum":2}`, ir.ReasonDegradedLowering)}, + reports: apart[1:], + }, + // No JSON holds the entry whole. + "no JSON holding the entry": { + entries: []KeptAllOfEntry{unheld}, pendingKeeps: []PendingKeep{kept, besides}, want: keptAndApart(unheld), reports: apart, + }, + // Kept whole for a cause, but no JSON holds it. + "kept whole for a cause no JSON holds": { + entries: []KeptAllOfEntry{causeUnheld}, pendingKeeps: []PendingKeep{kept, besides}, want: keptAndApart(causeUnheld), reports: apart, + }, + // A folding entry writes what every conjunct agrees on. + "a folding entry": { + entries: []KeptAllOfEntry{entry}, pendingKeeps: []PendingKeep{kept, folded}, want: keptAndApart(entry), reports: apart, + }, + }) +} + +// TestSettle_EntriesNoneAroundAnotherWritingOneValueOtherwiseKeepItEachUnderItsKey +// pins two entries nothing lowers from and no JSON holds, writing one value +// otherwise than the position: each keeps it under its own entry key with its +// report, as Settle says of each conjunct but the outermost. +func TestSettle_EntriesNoneAroundAnotherWritingOneValueOtherwiseKeepItEachUnderItsKey(t *testing.T) { + t.Parallel() + position := fixturePositionSite() + first, second := fixtureEntrySite("allOf/1", WritesBeside, 1), fixtureEntrySite("allOf/2", WritesBeside, 2) + firstEntry, secondEntry := fixtureEntry(first, ""), fixtureEntry(second, "") + kept := fixturePendingKeep(position, "minimum", "1") + keepSettlement := fixturePendingKeeps([]KeptAllOfEntry{firstEntry, secondEntry}, kept, fixturePendingKeep(first, "minimum", "2"), fixturePendingKeep(second, "minimum", "2")) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{ + "openapi:minimum": fixtureKeptPlain(kept), + "openapi:allOf/1": fixtureKeptAt(firstEntry, `{"minimum":2}`, ir.ReasonDegradedLowering), + "openapi:allOf/2": fixtureKeptAt(secondEntry, `{"minimum":2}`, ir.ReasonDegradedLowering), + }, []ir.Diagnostic{ + kept.Report[0], fixtureApartReport(first, []string{"minimum"}), fixtureApartReport(second, []string{"minimum"}), + }) +} + +// TestSettle_APromotedKeyAnEntryKeptWholeWritesIsKeptBesideIt pins a key the +// promotion policy reads, kept at every conjunct: an entry kept whole that +// alone writes it keeps it beside the whole entry too, reasoned apart from it, +// while one another conjunct writes is that conjunct's, the whole entry holding +// its own. +func TestSettle_APromotedKeyAnEntryKeptWholeWritesIsKeptBesideIt(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesBeside, 0) + whole := fixtureEntry(beside, `{"unevaluatedProperties":false,"x-promoted":"a"}`) + whole.KeptWhole = true + unevaluated := fixturePendingKeep(beside, "unevaluatedProperties", "false") + unevaluated.Reason = ir.ReasonValidationOnly + promoted, positions := fixturePendingKeep(beside, "x-promoted", `"a"`), fixturePendingKeep(position, "x-promoted", `"b"`) + promoted.Reason, positions.Reason = ir.ReasonVendorExtension, ir.ReasonVendorExtension + promoted.KeptAtEveryConjunctSite, positions.KeptAtEveryConjunctSite = true, true + keptWhole := fixtureKeptWhole(whole, ir.ReasonValidationOnly) + wholeReport := fixtureWholeReport(beside, []string{"unevaluatedProperties"}, ir.ReasonValidationOnly) + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The entry alone writes the key. + "written by the entry alone": { + entries: []KeptAllOfEntry{whole}, pendingKeeps: []PendingKeep{unevaluated, promoted}, + want: ir.Unmodeled{"openapi:allOf/0": keptWhole, "openapi:x-promoted": fixtureKeptPlain(promoted)}, + reports: []ir.Diagnostic{wholeReport, promoted.Report[0]}, + }, + // The position writes the key otherwise. + "written by the position too": { + entries: []KeptAllOfEntry{whole}, pendingKeeps: []PendingKeep{positions, unevaluated, promoted}, + want: ir.Unmodeled{"openapi:allOf/0": keptWhole, "openapi:x-promoted": fixtureKeptPlain(positions)}, + reports: []ir.Diagnostic{positions.Report[0], wholeReport}, + }, + }) +} + +// TestSettle_APrincipalKeptWholeHoldsTheOnePartOfWhatItWrites pins a +// principal kept whole: what the position writes alike is that one part, kept +// inside the whole entry alone, but a promoted key; what the position writes +// otherwise, or the principal does not write, stays the position's. +func TestSettle_APrincipalKeptWholeHoldsTheOnePartOfWhatItWrites(t *testing.T) { + t.Parallel() + position, principal := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + whole := fixtureEntry(principal, `{"title":"A","type":"string","unevaluatedItems":false}`) + whole.KeptWhole = true + keptWhole := fixtureKeptWhole(whole, ir.ReasonDegradedLowering) + wholeReport := fixtureWholeReport(principal, []string{"title"}, ir.ReasonDegradedLowering) + principals := fixturePendingKeep(principal, "title", `"A"`) + alike, otherwise := fixturePendingKeep(position, "title", `"A"`), fixturePendingKeep(position, "title", `"B"`) + promoted, description := alike, fixturePendingKeep(position, "description", `"D"`) + promoted.KeptAtEveryConjunctSite = true + besideWhole := func(pendingKeep PendingKeep) fixtureSettleRow { + return fixtureSettleRow{ + entries: []KeptAllOfEntry{whole}, pendingKeeps: []PendingKeep{pendingKeep, principals}, + want: ir.Unmodeled{pendingKeep.Key: fixtureKeptPlain(pendingKeep), "openapi:allOf/0": keptWhole}, + reports: []ir.Diagnostic{pendingKeep.Report[0], wholeReport}, + } + } + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The position writes the title alike. + "written alike": { + entries: []KeptAllOfEntry{whole}, pendingKeeps: []PendingKeep{alike, principals}, + want: ir.Unmodeled{"openapi:allOf/0": keptWhole}, reports: []ir.Diagnostic{wholeReport}, + }, + // The position reads the title alike. + "read alike": { + entries: []KeptAllOfEntry{whole}, pendingKeeps: []PendingKeep{fixtureRead(position, "title", `"A"`), principals}, + want: ir.Unmodeled{"openapi:allOf/0": keptWhole}, reports: []ir.Diagnostic{wholeReport}, + }, + // The position writes the title otherwise. + "written otherwise": besideWhole(otherwise), + // The position writes alike a title the promotion policy reads. + "a promoted key written alike": besideWhole(promoted), + // The position writes a keyword the principal does not. + "a keyword the principal writes not": besideWhole(description), + }) +} + +// TestSettle_AnEntryKeptWholeTakesTheReasonItsKeywordsShare pins the reason of +// an entry kept whole: the one its kept keywords share, else +// degraded_lowering, what its fold keeps typed as any entry's is and so +// reading no reason, and its report naming every keyword it holds. +func TestSettle_AnEntryKeptWholeTakesTheReasonItsKeywordsShare(t *testing.T) { + t.Parallel() + beside := fixtureEntrySite("allOf/1", WritesBeside, 1) + entry := fixtureEntry(beside, `{"contentMediaType":"text/plain","if":{},"unevaluatedProperties":false,"x-a":1}`) + entry.KeptWhole = true + withReason := func(keyword, value string, reason ir.UnmodeledReason) PendingKeep { + pendingKeep := fixturePendingKeep(beside, keyword, value) + pendingKeep.Reason = reason + return pendingKeep + } + unevaluated, conditional := withReason("unevaluatedProperties", "false", ir.ReasonValidationOnly), withReason("if", "{}", ir.ReasonValidationOnly) + content, folded := withReason("contentMediaType", `"text/plain"`, ir.ReasonNoIRHome), withReason("x-a", "1", ir.ReasonVendorExtension) + folded.Source = KeptByFold + row := func(reason ir.UnmodeledReason, held []string, pendingKeeps ...PendingKeep) fixtureSettleRow { + return fixtureSettleRow{ + entries: []KeptAllOfEntry{entry}, pendingKeeps: pendingKeeps, want: ir.Unmodeled{"openapi:allOf/1": fixtureKeptWhole(entry, reason)}, + reports: []ir.Diagnostic{fixtureWholeReport(beside, held, reason)}, + } + } + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // Two keywords of one reason, named in the order the entry writes them. + "one reason shared": row(ir.ReasonValidationOnly, []string{"if", "unevaluatedProperties"}, unevaluated, conditional), + // Two keywords of two reasons. + "two reasons": row(ir.ReasonDegradedLowering, []string{"contentMediaType", "unevaluatedProperties"}, unevaluated, content), + // A keyword the entry's fold keeps beside one of a reason. + "a folded keyword beside": row(ir.ReasonValidationOnly, []string{"unevaluatedProperties", "x-a"}, unevaluated, folded), + // Only a keyword the entry's fold keeps. + "only a folded keyword": row(ir.ReasonDegradedLowering, []string{"x-a"}, folded), + // No keyword pending at all. + "no keyword": row(ir.ReasonDegradedLowering, nil), + }) +} + +// TestSettle_AKeywordReportedWhereKeptIsNamedByItsOwnReport pins a pending keep +// whose chosen part reports it wherever it is kept: its report is drawn there, +// after the entry's, which names it neither kept whole nor kept apart, while +// its reason counts as any kept keyword's. +func TestSettle_AKeywordReportedWhereKeptIsNamedByItsOwnReport(t *testing.T) { + t.Parallel() + position := fixturePositionSite() + beside, principal := fixtureEntrySite("allOf/1", WritesBeside, 1), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + whole := fixtureEntry(beside, `{"contentMediaType":"text/plain","unevaluatedProperties":false}`) + whole.KeptWhole = true + apart := fixtureEntry(principal, `{"contentMediaType":"text/plain","type":"string","x-a":1}`) + unevaluated := fixturePendingKeep(beside, "unevaluatedProperties", "false") + unevaluated.Reason = ir.ReasonValidationOnly + wholeContent, apartContent := fixturePendingKeep(beside, "contentMediaType", `"text/plain"`), fixturePendingKeep(principal, "contentMediaType", `"text/plain"`) + wholeContent.Source, apartContent.Source = KeptByBuild, KeptByBuild + ownContent, ownExtension := fixturePendingKeep(position, "contentMediaType", `"text/html"`), fixturePendingKeep(position, "x-a", "2") + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // Kept inside an entry kept whole. + "kept whole": { + entries: []KeptAllOfEntry{whole}, pendingKeeps: []PendingKeep{unevaluated, wholeContent}, + want: ir.Unmodeled{"openapi:allOf/1": fixtureKeptWhole(whole, ir.ReasonDegradedLowering)}, + reports: []ir.Diagnostic{ + fixtureWholeReport(beside, []string{"unevaluatedProperties"}, ir.ReasonDegradedLowering), wholeContent.Report[0], + }, + }, + // Kept apart under the principal's entry key. + "kept apart": { + entries: []KeptAllOfEntry{apart}, + pendingKeeps: []PendingKeep{ownContent, ownExtension, apartContent, fixturePendingKeep(principal, "x-a", "1")}, + want: ir.Unmodeled{ + "openapi:contentMediaType": fixtureKeptPlain(ownContent), "openapi:x-a": fixtureKeptPlain(ownExtension), + "openapi:allOf/0": fixtureKeptAt(apart, `{"contentMediaType":"text/plain","x-a":1}`, ir.ReasonDegradedLowering), + }, + reports: []ir.Diagnostic{ + ownContent.Report[0], ownExtension.Report[0], fixtureApartReport(principal, []string{"x-a"}), apartContent.Report[0], + }, + }, + }) +} + +// TestSettle_EachReadingOfAnEntryNamesWhatItKeepsApartInOneReport pins the +// reports of what an entry keeps apart: one per reading, in the order first +// pending, each keeping's keywords together, a reading marked as one +// together, the rest as one, and none naming a keyword reported where kept. +func TestSettle_EachReadingOfAnEntryNamesWhatItKeepsApartInOneReport(t *testing.T) { + t.Parallel() + position, principal := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + written := `{"x-f":1,"x-e":1,"x-d":1,"x-c":1,"x-b":1,"x-a":1,"type":"string"}` + entry := fixtureEntry(principal, written) + keepSettlement := fixturePendingKeeps([]KeptAllOfEntry{entry}) + keywords := []string{"x-a", "x-b", "x-c", "x-d", "x-e", "x-f"} + reports := make([]ir.Diagnostic, 0, len(keywords)+4) + for _, keyword := range keywords { + keepSettlement.Add(fixturePendingKeep(position, keyword, "0")) + reports = append(reports, fixturePendingKeepReport(position, keyword)) + } + keeping := fixtureKeeping(nil) + kept, keptToo := fixturePendingKeep(principal, "x-b", "1"), fixturePendingKeep(principal, "x-c", "1") + kept.KeptBy, keptToo.KeptBy = keeping, keeping + reportedWhereKept := fixturePendingKeep(principal, "x-f", "1") + reportedWhereKept.Source = KeptByBuild + for _, pendingKeep := range []PendingKeep{fixturePendingKeep(principal, "x-a", "1"), kept, keptToo, fixturePendingKeep(principal, "x-e", "1"), reportedWhereKept} { + keepSettlement.Add(pendingKeep) + } + var reading PendingKeeps + reading.Add(fixturePendingKeep(principal, "x-d", "1")) + reading.AsOneReading() + keepSettlement.AddAll(reading) + want := ir.Unmodeled{"openapi:allOf/0": fixtureKeptAt(entry, `{"x-f":1,"x-e":1,"x-d":1,"x-c":1,"x-b":1,"x-a":1}`, ir.ReasonDegradedLowering)} + for _, keyword := range keywords { + want["openapi:"+keyword] = fixtureKeptPlain(fixturePendingKeep(position, keyword, "0")) + } + reports = append(reports, + fixtureApartReport(principal, []string{"x-e", "x-a"}), fixtureApartReport(principal, []string{"x-c", "x-b"}), + fixtureApartReport(principal, []string{"x-d"}), reportedWhereKept.Report[0]) + assertPendingKeepsSettle(t, keepSettlement, want, reports) +} + +// fixtureReportsAs is the record of the entry site writes, whole as JSON, +// whose reports, kept whole or apart, name label and what they hold. +func fixtureReportsAs(site ConjunctSite, whole, label string) KeptAllOfEntry { + entry := fixtureEntry(site, whole) + entry.ReportWhole = func(held []string, _ ir.UnmodeledReason) []ir.Diagnostic { + return []ir.Diagnostic{fixtureLabelledReport(site, label+" whole", held)} + } + entry.ReportApart = func(apart []string) []ir.Diagnostic { + return []ir.Diagnostic{fixtureLabelledReport(site, label+" apart", apart)} + } + return entry +} + +// fixtureLabelledReport is the report fixtureReportsAs draws at site. +func fixtureLabelledReport(site ConjunctSite, label string, keywords []string) ir.Diagnostic { + return diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, fixturePlace(site.Pointer), "%s: %q", label, keywords) +} + +// TestSettle_ALaterRecordOfAnEntryCompletesTheFirst pins two records of one +// entry: the later completes the earlier, kept whole and measured only against +// what is kept where either says, its JSON where the earlier holds none, and +// each report it gives replacing the earlier's. +func TestSettle_ALaterRecordOfAnEntryCompletesTheFirst(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/1", WritesBeside, 1) + written, other := `{"title":"A","type":"object"}`, `{"title":"A","type":"string"}` + bare := KeptAllOfEntry{Site: beside, Provenance: fixturePlace(beside.Pointer)} + cause, later, laterWhole, against := fixtureReportsAs(beside, written, "first"), fixtureReportsAs(beside, written, "second"), bare, bare + cause.KeptWhole, later.KeptWhole, laterWhole.Whole, against.AgainstKept = true, true, fixtureJSON(other), true + unheld, unheldLater := fixtureReportsAs(beside, "", "first"), fixtureReportsAs(beside, "", "second") + title, ownTitle := fixturePendingKeep(beside, "title", `"A"`), fixturePendingKeep(position, "title", `"B"`) + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The later record holds the JSON and the cause, and gives the report. + "kept whole where the later says": { + entries: []KeptAllOfEntry{unheld, later}, pendingKeeps: []PendingKeep{title}, + want: ir.Unmodeled{"openapi:allOf/1": fixtureKeptWhole(later, ir.ReasonDegradedLowering)}, + reports: []ir.Diagnostic{fixtureLabelledReport(beside, "second whole", []string{"title"})}, + }, + // The earlier record holds the JSON, the cause and the report. + "the earlier JSON and report kept": { + entries: []KeptAllOfEntry{cause, laterWhole}, pendingKeeps: []PendingKeep{title}, + want: ir.Unmodeled{"openapi:allOf/1": fixtureKeptWhole(cause, ir.ReasonDegradedLowering)}, + reports: []ir.Diagnostic{fixtureLabelledReport(beside, "first whole", []string{"title"})}, + }, + // The later record says the entry is measured only against what is kept. + "against kept where the later says": { + entries: []KeptAllOfEntry{fixtureReportsAs(beside, written, "first"), against}, + pendingKeeps: []PendingKeep{fixtureRead(position, "title", `"B"`), title}, + want: ir.Unmodeled{"openapi:allOf/1": fixtureKeptAt(cause, `{"title":"A"}`, ir.ReasonDegradedLowering)}, + reports: []ir.Diagnostic{fixtureLabelledReport(beside, "first apart", []string{"title"})}, + }, + // Both records give a report of what the entry keeps apart. + "the later apart report": { + entries: []KeptAllOfEntry{unheld, unheldLater}, pendingKeeps: []PendingKeep{ownTitle, title}, + want: ir.Unmodeled{ + "openapi:title": fixtureKeptPlain(ownTitle), "openapi:allOf/1": fixtureKeptAt(unheld, `{"title":"A"}`, ir.ReasonDegradedLowering), + }, + reports: []ir.Diagnostic{ownTitle.Report[0], fixtureLabelledReport(beside, "second apart", []string{"title"})}, + }, + }) +} + +// TestSettle_ALaterRecordsDroppedReportsAreTheEntrys pins a later record of +// one entry made in a pending keeps whose reports are dropped: the entry takes the +// later record's dropping, so what it keeps apart is reported by no one. +func TestSettle_ALaterRecordsDroppedReportsAreTheEntrys(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/1", WritesBeside, 1) + earlier := fixtureReportsAs(beside, "", "first") + ownTitle := fixturePendingKeep(position, "title", `"B"`) + keepSettlement := fixturePendingKeeps([]KeptAllOfEntry{earlier}, ownTitle, fixturePendingKeep(beside, "title", `"A"`)) + later := fixturePendingKeeps([]KeptAllOfEntry{fixtureReportsAs(beside, "", "second")}) + later.DropReports(func(ir.Diagnostic) bool { return true }) + keepSettlement.AddAll(*later) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{ + "openapi:title": fixtureKeptPlain(ownTitle), "openapi:allOf/1": fixtureKeptAt(earlier, `{"title":"A"}`, ir.ReasonDegradedLowering), + }, ownTitle.Report) +} + +// TestSettle_AValueNoJSONHoldsIsRefusedAsWrittenFlat pins a pending keep +// written as a node no JSON holds: it is kept nowhere, refused as written flat, +// by its chosen part where a keeping keeps it, its reports drawn where they +// would be, and alike to nothing, so another entry's value is kept under the +// key. +func TestSettle_AValueNoJSONHoldsIsRefusedAsWrittenFlat(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/1", WritesBeside, 1) + invalid := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "\xff"} + refused := PendingKeep{ + Key: "openapi:title", Keyword: "title", Written: invalid, Reason: ir.ReasonDegradedLowering, + Report: []ir.Diagnostic{fixturePendingKeepReport(position, "title")}, Provenance: fixturePlace(fixtureKeywordPointer(position, "title")), + WrittenBy: position, + } + keptBy := refused + keptBy.KeptBy = fixtureKeeping(nil) + besides := fixturePendingKeep(beside, "title", `"A"`) + entries := []KeptAllOfEntry{fixtureEntry(beside, "")} + want := ir.Unmodeled{"openapi:title": fixtureKeptPlain(besides)} + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // A pending keep no keeping keeps. + "kept as written": { + entries: entries, pendingKeeps: []PendingKeep{refused, besides}, want: want, + reports: []ir.Diagnostic{refused.Report[0], besides.Report[0]}, + }, + // A pending keep a keeping keeps. + "kept by a keeping": { + entries: entries, pendingKeeps: []PendingKeep{keptBy, besides}, want: want, + reports: []ir.Diagnostic{fixtureKeepingReport([]string{"title"}), besides.Report[0]}, + }, + }) +} + +// fixtureFlag is site's boolean exclusiveMinimum, value as JSON, which modifies +// the minimum it settles with. +func fixtureFlag(site ConjunctSite, value string) PendingKeep { + pendingKeep := fixturePendingKeep(site, "exclusiveMinimum", value) + pendingKeep.Modifies = "openapi:minimum" + return pendingKeep +} + +// TestSettle_ABoundAndItsFlagSettleAsOneUnit pins a boolean exclusive flag +// settling with the bound it modifies: a flag otherwise parts the bound +// written alike, both kept apart in the order the entry writes them; one +// alike keeps nothing apart; and a bound the entry reads is written nowhere. +func TestSettle_ABoundAndItsFlagSettleAsOneUnit(t *testing.T) { + t.Parallel() + position, principal := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + minimum, flag := fixturePendingKeep(position, "minimum", "1"), fixtureFlag(position, "true") + own := ir.Unmodeled{"openapi:minimum": fixtureKeptPlain(minimum), "openapi:exclusiveMinimum": fixtureKeptPlain(flag)} + otherwise := fixtureEntry(principal, `{"exclusiveMinimum":false,"minimum":1,"type":"number"}`) + withApart := func(value string) ir.Unmodeled { + out := ir.Unmodeled{"openapi:allOf/0": fixtureKeptAt(otherwise, value, ir.ReasonDegradedLowering)} + maps.Copy(out, own) + return out + } + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The principal writes the bound alike and the flag otherwise. + "a flag otherwise": { + entries: []KeptAllOfEntry{otherwise}, + pendingKeeps: []PendingKeep{minimum, flag, fixturePendingKeep(principal, "minimum", "1"), fixtureFlag(principal, "false")}, + want: withApart(`{"exclusiveMinimum":false,"minimum":1}`), + reports: []ir.Diagnostic{minimum.Report[0], flag.Report[0], fixtureApartReport(principal, []string{"exclusiveMinimum", "minimum"})}, + }, + // The principal writes both alike. + "a flag alike": { + entries: []KeptAllOfEntry{fixtureEntry(principal, `{"exclusiveMinimum":true,"minimum":1,"type":"number"}`)}, + pendingKeeps: []PendingKeep{minimum, flag, fixturePendingKeep(principal, "minimum", "1"), fixtureFlag(principal, "true")}, + want: own, reports: []ir.Diagnostic{minimum.Report[0], flag.Report[0]}, + }, + // The principal reads its bound and keeps its flag otherwise. + "a bound read": { + entries: []KeptAllOfEntry{otherwise}, + pendingKeeps: []PendingKeep{minimum, flag, fixtureRead(principal, "minimum", "3"), fixtureFlag(principal, "false")}, + want: withApart(`{"exclusiveMinimum":false}`), + reports: []ir.Diagnostic{minimum.Report[0], flag.Report[0], fixtureApartReport(principal, []string{"exclusiveMinimum"})}, + }, + }) +} + +// TestSettle_AConjunctReadingAndKeepingOneKeyKeepsIt pins one conjunct reading +// and keeping one key, in either order: what it keeps takes the place of what +// it reads, so its value otherwise is kept apart, and its second pending keep +// of the key adds nothing. +func TestSettle_AConjunctReadingAndKeepingOneKeyKeepsIt(t *testing.T) { + t.Parallel() + position, principal := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + entry := fixtureEntry(principal, `{"minimum":3,"type":"string"}`) + own, read, kept := fixturePendingKeep(position, "minimum", "1"), fixtureRead(principal, "minimum", "3"), fixturePendingKeep(principal, "minimum", "3") + want := ir.Unmodeled{ + "openapi:minimum": fixtureKeptPlain(own), "openapi:allOf/0": fixtureKeptAt(entry, `{"minimum":3}`, ir.ReasonDegradedLowering), + } + reports := []ir.Diagnostic{own.Report[0], fixtureApartReport(principal, []string{"minimum"})} + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // The conjunct reads the key, then keeps it. + "read, then kept": {entries: []KeptAllOfEntry{entry}, pendingKeeps: []PendingKeep{own, read, kept}, want: want, reports: reports}, + // The conjunct keeps the key, then reads it. + "kept, then read": {entries: []KeptAllOfEntry{entry}, pendingKeeps: []PendingKeep{own, kept, read}, want: want, reports: reports}, + }) +} + +// TestSettle_AKeywordKeptApartByAConjunctNoEntryRecordsIsAnInternalError pins a +// keyword kept apart by a conjunct the pending keeps records no entry of: +// nothing is kept for it, and an internal-invariant error at the position names +// the conjunct whose keyword has no entry to be kept under. +func TestSettle_AKeywordKeptApartByAConjunctNoEntryRecordsIsAnInternalError(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/1", WritesBeside, 1) + own := fixturePendingKeep(position, "minimum", "1") + keepSettlement := fixturePendingKeeps(nil, own, fixturePendingKeep(beside, "minimum", "2")) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{"openapi:minimum": fixtureKeptPlain(own)}, []ir.Diagnostic{ + own.Report[0], + diag.Newf(ir.SeverityError, diag.InternalInvariant, fixturePlace(fixturePositionPointer), + "internal: a keyword kept apart from %s names no entry the node holds", beside.Pointer), + }) +} + +// TestSettle_AKeywordNoJSONNamesRefusesTheObjectKeptApart pins a keyword kept +// apart whose name no JSON string holds: the entry key keeps nothing, and an +// unpreservable-construct error at the entry says so, in place of the entry's +// report. +func TestSettle_AKeywordNoJSONNamesRefusesTheObjectKeptApart(t *testing.T) { + t.Parallel() + position, beside := fixturePositionSite(), fixtureEntrySite("allOf/1", WritesBeside, 1) + entry := fixtureEntry(beside, "") + own := fixturePendingKeep(position, "\xff", "1") + keepSettlement := fixturePendingKeeps([]KeptAllOfEntry{entry}, own, fixturePendingKeep(beside, "\xff", "2")) + _, quoteErr := jsontext.AppendQuote(nil, "\xff") + require.Error(t, quoteErr, "the keyword is no JSON string") + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{"openapi:\xff": fixtureKeptPlain(own)}, []ir.Diagnostic{ + own.Report[0], + unpreservableDiag("openapi:allOf/1", entry.Provenance, fmt.Errorf("render kept keyword %q: %w", "\xff", quoteErr)), + }) +} + +// TestSettle_AnEntryRecordedWithNoReportDrawsNone pins an entry recorded with +// no report of what its key holds: kept whole or apart, it is kept as any +// entry is and draws no report of its own. +func TestSettle_AnEntryRecordedWithNoReportDrawsNone(t *testing.T) { + t.Parallel() + position := fixturePositionSite() + beside, principal := fixtureEntrySite("allOf/1", WritesBeside, 1), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + whole := KeptAllOfEntry{Site: beside, Whole: fixtureJSON(`{"title":"A","unevaluatedProperties":false}`), Provenance: fixturePlace(beside.Pointer), KeptWhole: true} + apart := KeptAllOfEntry{Site: principal, Whole: fixtureJSON(`{"minimum":3,"type":"string"}`), Provenance: fixturePlace(principal.Pointer)} + own := fixturePendingKeep(position, "minimum", "1") + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + // An entry kept whole. + "kept whole": { + entries: []KeptAllOfEntry{whole}, pendingKeeps: []PendingKeep{fixturePendingKeep(beside, "title", `"A"`)}, + want: ir.Unmodeled{"openapi:allOf/1": fixtureKeptWhole(whole, ir.ReasonDegradedLowering)}, + }, + // An entry keeping a keyword apart. + "kept apart": { + entries: []KeptAllOfEntry{apart}, pendingKeeps: []PendingKeep{own, fixturePendingKeep(principal, "minimum", "3")}, + want: ir.Unmodeled{ + "openapi:minimum": fixtureKeptPlain(own), "openapi:allOf/0": fixtureKeptAt(apart, `{"minimum":3}`, ir.ReasonDegradedLowering), + }, + reports: own.Report, + }, + }) +} + +// TestKeptUnderOwnKeyAt_NamesWhatTheSchemaAtAPointerKeepsUnderItsOwnKey holds +// the keywords the position keeps plain to those its own conjuncts pending +// keep: a keyword it only reads, one an entry writes and one kept under an +// entry key are none of them, and a keyword pending twice is named once. +func TestKeptUnderOwnKeyAt_NamesWhatTheSchemaAtAPointerKeepsUnderItsOwnKey(t *testing.T) { + t.Parallel() + position, entry := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesBeside, 0) + underEntryKey := fixturePendingKeep(position, "y", "2") + underEntryKey.Key = "openapi:allOf/0" + var pendingKeeps PendingKeeps + for _, pendingKeep := range []PendingKeep{ + fixturePendingKeep(position, "x", "1"), fixtureRead(position, "r", "1"), fixturePendingKeep(entry, "z", "1"), + underEntryKey, fixturePendingKeep(position, "x", "1"), + } { + pendingKeeps.Add(pendingKeep) + } + assert.Equal(t, []string{"x"}, pendingKeeps.KeptUnderOwnKeyAt(fixturePositionPointer)) + assert.Empty(t, pendingKeeps.KeptUnderOwnKeyAt(fixturePositionPointer+"/other"), "nothing is written there") +} + +// TestSettle_AnEntryKeptWholeNamesWhatItsConjunctReads pins the report of an +// entry kept whole whose conjunct reads a keyword into the node beside one it +// keeps: the entry holds both, so its report names both, in the order the entry +// writes them. +func TestSettle_AnEntryKeptWholeNamesWhatItsConjunctReads(t *testing.T) { + t.Parallel() + first := fixtureEntrySite("allOf/0", WritesBeside, 0) + entry := fixtureEntry(first, `{"x-k":1,"enum":["a"]}`) + entry.KeptWhole = true + keepSettlement := fixturePendingKeeps([]KeptAllOfEntry{entry}, fixturePendingKeep(first, "x-k", "1"), fixtureRead(first, "enum", `["a"]`)) + assertPendingKeepsSettle(t, keepSettlement, ir.Unmodeled{"openapi:allOf/0": fixtureKeptWhole(entry, ir.ReasonDegradedLowering)}, + []ir.Diagnostic{fixtureWholeReport(first, []string{"x-k", "enum"}, ir.ReasonDegradedLowering)}) +} + +// TestSettle_AValueKeptApartWarnsOfTheExtensionsItLeavesOut holds a keyword +// kept apart, whose node writes a vendor extension no JSON holds, to the +// extension's own warning, at the keyword its conjunct writes and credited as +// the entry it settled under is, beside the entry's report: kept as the chosen +// part's value with the node it renders from or as the node alone. +func TestSettle_AValueKeptApartWarnsOfTheExtensionsItLeavesOut(t *testing.T) { + t.Parallel() + position, principal := fixturePositionSite(), fixtureEntrySite("allOf/0", WritesLoweredFrom, 0) + apart := fixtureEntry(principal, `{"foo":{"a":1},"type":"string"}`) + apart.Provenance.WrittenBy = 1 + node := ynode.Map(ynode.Scalar("a"), ynode.Scalar("1"), ynode.Scalar("x-bad"), nanNode()) + own := fixturePendingKeep(position, "foo", `{"a":2}`) + warning := ExtensionDroppedDiag(ir.Provenance{Pointer: fixtureKeywordPointer(principal, "foo") + "/x-bad", WrittenBy: 1}) + kept := ir.Unmodeled{"openapi:foo": fixtureKeptPlain(own), "openapi:allOf/0": fixtureKeptAt(apart, `{"foo":{"a":1}}`, ir.ReasonDegradedLowering)} + with := fixturePendingKeep(principal, "foo", `{"a":1}`) + with.Written = node + asNode := with + asNode.Value = nil + runPendingKeepSettleRows(t, map[string]fixtureSettleRow{ + "a value with the node it renders from": { + entries: []KeptAllOfEntry{apart}, pendingKeeps: []PendingKeep{own, with}, want: kept, + reports: []ir.Diagnostic{own.Report[0], warning, fixtureApartReport(principal, []string{"foo"})}, + }, + "the node alone": { + entries: []KeptAllOfEntry{apart}, pendingKeeps: []PendingKeep{own, asNode}, want: kept, + reports: []ir.Diagnostic{own.Report[0], warning, fixtureApartReport(principal, []string{"foo"})}, + }, + }) +} + +// TestSettle_AnEntryKeptWholeWarnsOfTheExtensionsItLeavesOut holds an entry +// kept whole that leaves out a vendor extension no JSON holds to the +// extension's warning, after the entry's report, credited as the entry is, +// whichever record of the entry names it. +func TestSettle_AnEntryKeptWholeWarnsOfTheExtensionsItLeavesOut(t *testing.T) { + t.Parallel() + beside := fixtureEntrySite("allOf/1", WritesBeside, 1) + first := fixtureEntry(beside, `{"title":"A","unevaluatedProperties":false}`) + first.KeptWhole, first.Provenance.WrittenBy = true, 1 + later := first + later.Dropped = []jsontext.Pointer{"/x-bad"} + warning := ExtensionDroppedDiag(ir.Provenance{Pointer: beside.Pointer + "/x-bad", WrittenBy: 1}) + for name, entries := range map[string][]KeptAllOfEntry{"one record": {later}, "a later record": {first, later}} { + t.Run(name, func(t *testing.T) { + t.Parallel() + assertPendingKeepsSettle(t, fixturePendingKeeps(entries, fixturePendingKeep(beside, "title", `"A"`)), + ir.Unmodeled{"openapi:allOf/1": fixtureKeptWhole(later, ir.ReasonDegradedLowering)}, + []ir.Diagnostic{fixtureWholeReport(beside, []string{"title"}, ir.ReasonDegradedLowering), warning}) + }) + } +} + +// TestAppendNew_AppendsAKeywordOnce pins appendNew, through which the +// settlement lists the keywords a keeping or an entry names: a keyword the +// list holds already leaves it as it is, and another is appended last. +func TestAppendNew_AppendsAKeywordOnce(t *testing.T) { + t.Parallel() + keywords := []string{"minimum", "maximum"} + assert.Equal(t, []string{"minimum", "maximum"}, appendNew(keywords, "minimum"), "a keyword held already") + assert.Equal(t, []string{"minimum", "maximum", "title"}, appendNew(keywords, "title"), "a keyword not held") +} diff --git a/compilers/openapi/internal/annotation/pendingkeeps_test.go b/compilers/openapi/internal/annotation/pendingkeeps_test.go new file mode 100644 index 000000000..0fb33da0d --- /dev/null +++ b/compilers/openapi/internal/annotation/pendingkeeps_test.go @@ -0,0 +1,40 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package annotation_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" +) + +// TestConjunctIndex_EntryNamesOnlyAListedEntry pins Entry's comma-ok form: an +// index among the allOf's entries names that entry, the first among them, +// and neither the keywords beside the allOf nor an entry the flattened +// entries do not list names one. +func TestConjunctIndex_EntryNamesOnlyAListedEntry(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + place annotation.ConjunctIndex + want int + listed bool + }{ + "the first entry": {place: 0, want: 0, listed: true}, + "a later entry": {place: 3, want: 3, listed: true}, + "beside the allOf": {place: annotation.BesideAllOf}, + "an entry not listed": {place: annotation.UnlistedEntry}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + index, listed := tc.place.Entry() + assert.Equal(t, tc.listed, listed) + if tc.listed { + assert.Equal(t, tc.want, index) + } + }) + } + assert.NotEqual(t, annotation.BesideAllOf, annotation.UnlistedEntry, "the keywords beside the allOf and an unlisted entry are told apart") +} diff --git a/compilers/openapi/internal/annotation/rawjson.go b/compilers/openapi/internal/annotation/rawjson.go index 6d142ed7c..c34a4dc3d 100644 --- a/compilers/openapi/internal/annotation/rawjson.go +++ b/compilers/openapi/internal/annotation/rawjson.go @@ -14,6 +14,7 @@ import ( yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" "github.com/dexpace/morphic/compilers/openapi/internal/value" "github.com/dexpace/morphic/ir" @@ -67,6 +68,37 @@ const ( type rawConv struct { nodes budget.Budget view *nodeview.View + // drop says a vendor extension whose value no JSON holds is left out, its + // pointer from the rendered node noted in dropped, path being where the + // walk is. + drop bool + path []string + dropped []jsontext.Pointer +} + +// RenderDroppingExtensions is RawFromNode for a construct kept whole, leaving +// out each vendor extension whose value no JSON holds, as the extension reader +// leaves one out where written: it returns those extensions' pointers from +// node, for their warnings (ExtensionDroppedDiag). +func RenderDroppingExtensions(node *yaml.Node) (ir.RawValue, []jsontext.Pointer, error) { + if node == nil { + return nil, nil, nil + } + conv := newRawConv() + conv.drop = true + data, err := conv.node(nil, node, 0) + if err != nil { + return nil, nil, fmt.Errorf("render yaml node as json: %w", err) + } + return data, conv.dropped, nil +} + +// ExtensionDroppedDiag reports the vendor extension at, which no JSON holds, +// left out of what kept it, as the extension reader reports one where written. +func ExtensionDroppedDiag(at ir.Provenance) ir.Diagnostic { + name := at.Pointer.LastToken() + at.Pointer = at.Pointer.Parent() + return diag.Newf(ir.SeverityWarning, diag.DegradedConstruct, at, "extension %q could not be serialized", name) } // newRawConv returns a conversion with the whole of maxRawNodes to spend. @@ -159,13 +191,65 @@ func (c *rawConv) sequence(dst jsontext.Value, node *yaml.Node, depth int) (json dst = append(dst, ',') } var err error - if dst, err = c.node(dst, child, depth+1); err != nil { + c.enter(strconv.Itoa(i)) + dst, err = c.node(dst, child, depth+1) + c.leave() + if err != nil { return nil, err } } return append(dst, ']'), nil } +// enter steps the walk into token, where it notes what it drops. +func (c *rawConv) enter(token string) { + if c.drop { + c.path = append(c.path, token) + } +} + +// leave steps the walk out of the token it entered last. +func (c *rawConv) leave() { + if c.drop { + c.path = c.path[:len(c.path)-1] + } +} + +// member renders pair, a mapping's member, onto dst: a vendor extension whose +// value no JSON holds is left out where c drops one, reporting whether it +// wrote. +func (c *rawConv) member(dst jsontext.Value, pair nodeview.Pair, depth int) (jsontext.Value, bool, error) { + c.enter(pair.Key) + defer c.leave() + if !c.drop || !strings.HasPrefix(pair.Key, "x-") { + out, err := c.member1(dst, pair, depth) + return out, true, err + } + rendered, err := c.node(nil, pair.Val, depth+1) + if err != nil { + var at jsontext.Pointer + for _, token := range c.path { + at = at.AppendToken(token) + } + c.dropped = append(c.dropped, at) + return dst, false, nil + } + if dst, err = appendString(dst, pair.Key); err != nil { + return nil, false, fmt.Errorf("mapping key: %w", err) + } + return append(append(dst, ':'), rendered...), true, nil +} + +// member1 renders pair, key and value, onto dst. +func (c *rawConv) member1(dst jsontext.Value, pair nodeview.Pair, depth int) (jsontext.Value, error) { + var err error + if dst, err = appendString(dst, pair.Key); err != nil { + return nil, fmt.Errorf("mapping key: %w", err) + } + dst = append(dst, ':') + return c.node(dst, pair.Val, depth+1) +} + // mapping appends a YAML mapping to dst as a JSON object of the members the // parser reads, each key once (MappingPairs), in the byte order of their keys, // as the IR's determinism invariant asks of every map it serializes. Of several @@ -185,30 +269,33 @@ func (c *rawConv) mapping(dst jsontext.Value, node *yaml.Node, depth int) (jsont }) dst = append(dst, '{') - for i, pair := range sorted { - if i > 0 { + wrote := false + for _, pair := range sorted { + mark := len(dst) + if wrote { dst = append(dst, ',') } - var err error - if dst, err = appendString(dst, pair.Key); err != nil { - return nil, fmt.Errorf("mapping key: %w", err) - } - dst = append(dst, ':') - if dst, err = c.node(dst, pair.Val, depth+1); err != nil { + out, written, err := c.member(dst, pair, depth) + if err != nil { return nil, err } + if !written { + dst = dst[:mark] + continue + } + dst, wrote = out, true } return append(dst, '}'), nil } -// appendString appends s to dst as a JSON string with RFC 8785's minimal +// appendString appends text to dst as a JSON string with RFC 8785's minimal // escaping, matching the IR's canonical form. Text that is not valid UTF-8 // fails the conversion rather than reaching the IR as U+FFFD, which a source // could also have written itself. -func appendString(dst jsontext.Value, s string) (jsontext.Value, error) { - b, err := jsontext.AppendQuote(dst, s) +func appendString(dst jsontext.Value, text string) (jsontext.Value, error) { + quoted, err := jsontext.AppendQuote(dst, text) if err != nil { - return nil, fmt.Errorf("string %q: %w", s, err) + return nil, fmt.Errorf("string %q: %w", text, err) } - return b, nil + return quoted, nil } diff --git a/compilers/openapi/internal/annotation/rawjson_internal_test.go b/compilers/openapi/internal/annotation/rawjson_internal_test.go index 114c51dd4..fad70de69 100644 --- a/compilers/openapi/internal/annotation/rawjson_internal_test.go +++ b/compilers/openapi/internal/annotation/rawjson_internal_test.go @@ -172,7 +172,7 @@ func TestRawFromNode_RendersEveryScalarTag(t *testing.T) { // TestRawFromNode_PreservesMergeAndOrderingSemantics pins the mapping rules a // payload is read by, which are the parser's (nodeview.View.MappingPairs). -// Losing any of them would be a silent regression: the construct still +// Losing any of them would be an unreported regression: the construct still // converts, just to something else. func TestRawFromNode_PreservesMergeAndOrderingSemantics(t *testing.T) { t.Parallel() @@ -180,8 +180,8 @@ func TestRawFromNode_PreservesMergeAndOrderingSemantics(t *testing.T) { {"keys sort", "{z: 1, a: 2, m: 3}", `{"a":2,"m":3,"z":1}`}, {"sequence keeps source order", "[3, 1, 2]", `[3,1,2]`}, {"merge key expands", "{<<: {p: 1}, q: 2}", `{"p":1,"q":2}`}, - {"own key beats merged key", "{<<: {p: 1}, p: 2}", `{"p":2}`}, - {"earlier merge source wins", "{<<: [{p: 1}, {p: 2}]}", `{"p":1}`}, + {"own key is chosen over merged key", "{<<: {p: 1}, p: 2}", `{"p":2}`}, + {"earlier merge source is chosen", "{<<: [{p: 1}, {p: 2}]}", `{"p":1}`}, {"merge through an alias", "a: &m {p: 1}\nb: {<<: *m, q: 2}", `{"a":{"p":1},"b":{"p":1,"q":2}}`}, {"nested merge inside a merged map", "a: &m {<<: {deep: 1}, p: 2}\nb: {<<: *m}", `{"a":{"deep":1,"p":2},"b":{"deep":1,"p":2}}`}, {"alias to a scalar", "a: &n 5\nb: *n", `{"a":5,"b":5}`}, @@ -499,7 +499,7 @@ var rawDivergences = map[string]struct{ old, want string }{ // v1's encoding/json changed which spelling it wrote between Go 1.26 and // 1.27; decodeAndMarshal no longer goes through v1 at all, so it is v2's // AllowInvalidUTF8 spelling that this row and the one below now pin, and - // whichever change moves off it owns rewriting both — the claim they make + // whichever change moves off it owns rewriting both — the pending keep they make // is that the old conversion lost the byte, not that any particular encoder // spells the loss one way. `!!binary /w==`: {"\"\ufffd\"", `"/w=="`}, @@ -542,7 +542,7 @@ var rawEquivalenceCorpus = []string{ "|\n line1\n line2", ">\n folded text", "a: &s {x: 1}\nb: *s\nc: *s", `{"": 1}`, `{"a\nb": 1}`, "{a: }", "{a: null, b: ~}", // Refused by the old conversion, preserved by the walk. They carry no - // equality claim, and are here so the asymmetry is visible in a -v run + // equality pending keep, and are here so the asymmetry is visible in a -v run // rather than asserted in a comment. "!!int 12345678901234567890123", "!!float 1e400", } @@ -553,7 +553,7 @@ var rawEquivalenceCorpus = []string{ // back can, because rounding is the only transformation the old one applied to // a row rawDivergences does not name. // -// A row the old conversion refused carries no claim — the new walk is allowed +// A row the old conversion refused carries no pending keep — the new walk is allowed // to be strictly more capable, and on `!!int 12345678901234567890123` and on a // block-form `!!binary` it is. func TestRawFromNode_DiffersFromTheOldDecodeOnlyWhereRecorded(t *testing.T) { diff --git a/compilers/openapi/internal/annotation/references.go b/compilers/openapi/internal/annotation/references.go index 1764fbb20..113757261 100644 --- a/compilers/openapi/internal/annotation/references.go +++ b/compilers/openapi/internal/annotation/references.go @@ -6,9 +6,11 @@ package annotation import ( "bytes" "encoding/json/jsontext" + "encoding/json/v2" "errors" "io" "slices" + "strings" "github.com/dexpace/morphic/compilers/openapi/internal/fragment" "github.com/dexpace/morphic/ir" @@ -19,6 +21,18 @@ import ( // more often errs safely. var referenceKeywords = []string{"$ref", "$dynamicRef", "$recursiveRef"} +// KeptReferenceKey reports whether key keeps verbatim a reference naming no +// schema, as a lowering keeps one it reads no target through: under the key +// of the keyword it is written with, openapi:$ref, openapi:$dynamicRef or +// openapi:$recursiveRef, or, where several are kept, under that key and its +// rank, as openapi:$ref/1. Such an entry admits every kind and narrows +// nothing. +func KeptReferenceKey(key string) bool { + rest, ours := strings.CutPrefix(key, entryPrefix) + keyword, rank, ranked := strings.Cut(rest, "/") + return ours && slices.Contains(referenceKeywords, keyword) && (!ranked || entryIndex(rank)) +} + // WritesReference reports whether raw, a schema or keyword value rendered as // JSON, names a member referenceKeywords lists at any depth whose value is no // absolute URI (fragment.Absolute), so that what it says turns on the base it @@ -34,8 +48,8 @@ func WritesReference(raw ir.RawValue) bool { return !errors.Is(err, io.EOF) } // In an object a name is each odd token, its value each even one. - kind, n := dec.StackIndex(dec.StackDepth()) - if tok.Kind() != '"' || kind != '{' || n%2 != 1 || !slices.Contains(referenceKeywords, tok.String()) { + kind, index := dec.StackIndex(dec.StackDepth()) + if tok.Kind() != '"' || kind != '{' || index%2 != 1 || !slices.Contains(referenceKeywords, tok.String()) { continue } value, err := dec.ReadToken() @@ -44,3 +58,46 @@ func WritesReference(raw ir.RawValue) bool { } } } + +// ReferenceSites returns where raw writes each member referenceKeywords lists +// whose value is no absolute URI (WritesReference): the pointer, from raw's +// root, of the object writing it, in the order written. It is false where raw +// does not decode or such a value is no string, which no site names. Every +// token read consumes input, so the walk is bounded by raw's length. +func ReferenceSites(raw ir.RawValue) ([]jsontext.Pointer, bool) { + dec := jsontext.NewDecoder(bytes.NewReader(raw)) + var sites []jsontext.Pointer + for { + tok, err := dec.ReadToken() + if err != nil { + return sites, errors.Is(err, io.EOF) + } + kind, index := dec.StackIndex(dec.StackDepth()) + if tok.Kind() != '"' || kind != '{' || index%2 != 1 || !slices.Contains(referenceKeywords, tok.String()) { + continue + } + at := dec.StackPointer().Parent() + value, err := dec.ReadToken() + if err != nil || value.Kind() != '"' { + return nil, false + } + if !fragment.Absolute(value.String()) { + sites = append(sites, at) + } + } +} + +// ReferenceAlone reports whether raw is an object writing one member, a +// reference keyword referenceKeywords lists whose value is a string: what it +// says is what that reference names, however a dialect reads other keywords. +func ReferenceAlone(raw ir.RawValue) bool { + var members map[string]jsontext.Value + if json.Unmarshal(raw, &members) != nil || len(members) != 1 { + return false + } + alone := false + for keyword, value := range members { + alone = slices.Contains(referenceKeywords, keyword) && value.Kind() == '"' + } + return alone +} diff --git a/compilers/openapi/internal/annotation/references_test.go b/compilers/openapi/internal/annotation/references_test.go index 22f286b40..cc2888c4e 100644 --- a/compilers/openapi/internal/annotation/references_test.go +++ b/compilers/openapi/internal/annotation/references_test.go @@ -4,6 +4,7 @@ package annotation_test import ( + "encoding/json/jsontext" "testing" "github.com/stretchr/testify/assert" @@ -43,3 +44,75 @@ func TestWritesReference_FindsAReferenceMemberAtAnyDepth(t *testing.T) { assert.Equal(t, tc.want, annotation.WritesReference(ir.RawValue(tc.raw)), tc.raw) } } + +// TestReferenceSites_NamesEachObjectWritingARelativeReference pins where a +// text writes what a base resolves: the pointer of each object naming a +// reference member whose value is no absolute URI, in the order written, from +// the text's root. A value that is no string, and text that does not decode, +// name no site, so are false. +func TestReferenceSites_NamesEachObjectWritingARelativeReference(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + raw string + sites []jsontext.Pointer + read bool + }{ + {`{"$ref":"n.json"}`, []jsontext.Pointer{""}, true}, + {`{"not":{"anyOf":[{"type":"string"},{"$ref":"#/$defs/a"}]},"items":{"$dynamicRef":"#node"}}`, + []jsontext.Pointer{"/not/anyOf/1", "/items"}, true}, + {`{"properties":{"a~b/c":{"$ref":"x.yaml"}}}`, []jsontext.Pointer{"/properties/a~0b~1c"}, true}, + {`{"$ref":"https://ex.test/n.json","minLength":1}`, nil, true}, + {`{"const":"$ref"}`, nil, true}, + {``, nil, true}, + {`{"$ref":{"a":1}}`, nil, false}, + {`{"$ref":`, nil, false}, + {`{"a":`, nil, false}, + } { + sites, read := annotation.ReferenceSites(ir.RawValue(tc.raw)) + assert.Equal(t, tc.read, read, tc.raw) + assert.Equal(t, tc.sites, sites, tc.raw) + } +} + +// TestReferenceAlone_IsAnObjectWritingOneReference pins what reads alike in +// every dialect: an object writing one reference keyword with a string value, +// and nothing else; a reference beside another keyword, one whose value is no +// string, another keyword alone, and text that is no object are not. +func TestReferenceAlone_IsAnObjectWritingOneReference(t *testing.T) { + t.Parallel() + for raw, want := range map[string]bool{ + `{"$ref":"#/x"}`: true, + `{"$dynamicRef":"#node"}`: true, + `{"$ref":"#/x","maxLength":3}`: false, + `{"$ref":{"a":1}}`: false, + `{"type":"string"}`: false, + `"#/x"`: false, + `{}`: false, + } { + assert.Equal(t, want, annotation.ReferenceAlone(ir.RawValue(raw)), raw) + } +} + +// TestKeptReferenceKey_ReadsEveryReferenceKeywordsKey holds the one reader of +// the key a reference naming no schema is kept under to every keyword a +// schema resolves against its base, ranked or not: a $dynamicRef kept so is +// as much a reference naming nothing as a $ref is. A key of another keyword, +// a rank that is no index and a key kept under an allOf entry's path are none. +func TestKeptReferenceKey_ReadsEveryReferenceKeywordsKey(t *testing.T) { + t.Parallel() + for key, want := range map[string]bool{ + "openapi:$ref": true, + "openapi:$ref/1": true, + "openapi:$dynamicRef": true, + "openapi:$dynamicRef/0": true, + "openapi:$recursiveRef": true, + "openapi:$refs": false, + "openapi:$ref/a": false, + "openapi:$ref/": false, + "openapi:allOf/0/$ref": false, + "openapi:not": false, + "vendor:$ref": false, + } { + assert.Equal(t, want, annotation.KeptReferenceKey(key), key) + } +} diff --git a/compilers/openapi/internal/annotation/rendering.go b/compilers/openapi/internal/annotation/rendering.go new file mode 100644 index 000000000..1a7fd12f1 --- /dev/null +++ b/compilers/openapi/internal/annotation/rendering.go @@ -0,0 +1,207 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package annotation + +import ( + "bytes" + "encoding/json/jsontext" + "slices" + "strings" +) + +// maxRenderingDepth is the nesting CanonicalRendering reads, the depth +// RawFromNode renders to: the decoder refuses a value nested past it, as +// jsontext's own limit. +const maxRenderingDepth = maxRawDepth + +// CanonicalRendering is value as two written values of one keyword are +// compared: its JSON with each object's members ordered by their names' bytes +// as written, every other token as written, so `1` and `1.0` stay two values. +// A value that is no JSON renders as itself behind a NUL, alike only to the +// same bytes. +func CanonicalRendering(value jsontext.Value) string { + nodes, err := readRendering(value) + if err != nil { + return "\x00" + string(value) + } + var out strings.Builder + out.Grow(len(value)) + writeRendering(&out, value, nodes) + return out.String() +} + +// RenderedAlike reports whether a and b render alike (CanonicalRendering), as +// two written values of one keyword are compared. +func RenderedAlike(a, b jsontext.Value) bool { + return CanonicalRendering(a) == CanonicalRendering(b) +} + +// renderingNode is one value a rendering reads: a scalar's bytes in the +// input, or a container's members, an object's in name order, each member of +// an object with its name's bytes. +type renderingNode struct { + members []int + value [2]int + name [2]int + kind jsontext.Kind +} + +// readRendering reads the one JSON value value starts with into nodes, the +// value first, each container's members after it, the decoder refusing one +// nested past maxRenderingDepth. +func readRendering(value jsontext.Value) ([]renderingNode, error) { + dec := jsontext.NewDecoder(bytes.NewReader(value)) + var nodes []renderingNode + var open []int + for { + if kind := dec.PeekKind(); kind == '}' || kind == ']' { + if _, err := dec.ReadToken(); err != nil { + return nil, err + } + sortMembers(value, nodes, open[len(open)-1]) + open = open[:len(open)-1] + if len(open) == 0 { + return nodes, nil + } + continue + } + node, err := readRenderingNode(dec, nodes, open) + if err != nil { + return nil, err + } + at := len(nodes) + if len(open) > 0 { + parent := open[len(open)-1] + nodes[parent].members = append(nodes[parent].members, at) + } + nodes = append(nodes, node) + if node.kind == '{' || node.kind == '[' { + open = append(open, at) + continue + } + if len(open) == 0 { + return nodes, nil + } + } +} + +// readRenderingNode reads the value dec reads next, the member of the +// innermost container open names, with its name where that is an object: a +// container's opening token, or a scalar's bytes. +func readRenderingNode(dec *jsontext.Decoder, nodes []renderingNode, open []int) (renderingNode, error) { + var node renderingNode + if len(open) > 0 && nodes[open[len(open)-1]].kind == '{' { + name, err := dec.ReadValue() + if err != nil { + return renderingNode{}, err + } + node.name = spanOf(dec, name) + } + node.kind = dec.PeekKind() + if node.kind == '{' || node.kind == '[' { + _, err := dec.ReadToken() + return node, err + } + raw, err := dec.ReadValue() + node.value = spanOf(dec, raw) + return node, err +} + +// spanOf is the place in its input of raw, the bytes dec read last. +func spanOf(dec *jsontext.Decoder, raw jsontext.Value) [2]int { + end := int(dec.InputOffset()) + return [2]int{end - len(raw), end} +} + +// sortMembers puts the members of the node at index at in name order where +// it is an object. +func sortMembers(value jsontext.Value, nodes []renderingNode, at int) { + if nodes[at].kind != '{' { + return + } + slices.SortStableFunc(nodes[at].members, func(a, b int) int { + return bytes.Compare(value[nodes[a].name[0]:nodes[a].name[1]], value[nodes[b].name[0]:nodes[b].name[1]]) + }) +} + +// writeRendering writes nodes, read from value, to out: each container's +// members in their order, an object member's name before it. +func writeRendering(out *strings.Builder, value jsontext.Value, nodes []renderingNode) { + type frame struct{ node, next int } + var stack []frame + enter := func(at int) { + node := nodes[at] + if node.name[1] > 0 { + out.Write(value[node.name[0]:node.name[1]]) + out.WriteByte(':') + } + if node.kind != '{' && node.kind != '[' { + out.Write(value[node.value[0]:node.value[1]]) + return + } + out.WriteByte(byte(node.kind)) + stack = append(stack, frame{node: at}) + } + enter(0) + for len(stack) > 0 { + top := &stack[len(stack)-1] + members := nodes[top.node].members + if top.next == len(members) { + out.WriteByte(byte(nodes[top.node].kind) + 2) + stack = stack[:len(stack)-1] + continue + } + if top.next > 0 { + out.WriteByte(',') + } + top.next++ + enter(members[top.next-1]) + } +} + +// wholeMembers returns the member names of whole, a JSON object, as written, +// and its members by name, each as written; none where whole is no object. +func wholeMembers(whole jsontext.Value) ([]string, map[string]jsontext.Value) { + members := map[string]jsontext.Value{} + if len(whole) == 0 { + return nil, members + } + dec := jsontext.NewDecoder(bytes.NewReader(whole)) + if tok, err := dec.ReadToken(); err != nil || tok.Kind() != '{' { + return nil, members + } + var names []string + for dec.PeekKind() == '"' { + token, err := dec.ReadToken() + if err != nil { + return names, members + } + name := token.String() + names = append(names, name) + value, err := dec.ReadValue() + if err != nil { + return names, members + } + members[name] = value.Clone() + } + return names, members +} + +// orderedBy returns keywords in the order written names them, those it names +// none of last, as given. +func orderedBy(keywords, written []string) []string { + out := slices.Clone(keywords) + slices.SortStableFunc(out, func(a, b string) int { + return rank(written, a) - rank(written, b) + }) + return out +} + +// rank is keyword's index in names, past every one where it is none of them. +func rank(names []string, keyword string) int { + if i := slices.Index(names, keyword); i >= 0 { + return i + } + return len(names) +} diff --git a/compilers/openapi/internal/annotation/rendering_internal_test.go b/compilers/openapi/internal/annotation/rendering_internal_test.go new file mode 100644 index 000000000..4d6e31920 --- /dev/null +++ b/compilers/openapi/internal/annotation/rendering_internal_test.go @@ -0,0 +1,151 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package annotation + +import ( + "encoding/json/jsontext" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestCanonicalRendering_SortsMembersAndKeepsEveryOtherToken holds what a +// rendering writes: each object's members in name order at every level, names +// compared as their written bytes, and every other token as written, so `1` +// and `1.0` stay two values and an array keeps its order. +func TestCanonicalRendering_SortsMembersAndKeepsEveryOtherToken(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct{ value, want string }{ + "members in name order": {`{"b":1,"a":2}`, `{"a":2,"b":1}`}, + "nested objects sorted": {`{"z":{"d":[{"y":1,"x":2}],"c":3},"a":null}`, `{"a":null,"z":{"c":3,"d":[{"x":2,"y":1}]}}`}, + "an array keeps its order": {`[3,1,2]`, `[3,1,2]`}, + "a number as written": {`1.0`, `1.0`}, + "an escaped name as written": {`{"b":1,"a":2}`, `{"a":2,"b":1}`}, + "a name read right": {`{"example":null}`, `{"example":null}`}, + "names read right in order": {`{"example":null,"description":"d"}`, `{"description":"d","example":null}`}, + "a scalar": {`"text"`, `"text"`}, + "an empty object": {`{}`, `{}`}, + "an empty array": {`[]`, `[]`}, + "whitespace dropped": {"{ \"b\" : [ 1 , 2 ] ,\n\"a\": true }", `{"a":true,"b":[1,2]}`}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, CanonicalRendering(jsontext.Value(tc.value))) + }) + } +} + +// TestCanonicalRendering_ANonJSONValueRendersAsItself holds a value that is no +// JSON, one nested past maxRenderingDepth among them, to rendering as its own +// bytes behind a NUL, alike only to the same bytes, and a value nested to the +// depth itself to rendering as JSON. +func TestCanonicalRendering_ANonJSONValueRendersAsItself(t *testing.T) { + t.Parallel() + nested := func(depth int) string { return strings.Repeat("[", depth) + "1" + strings.Repeat("]", depth) } + for name, value := range map[string]string{ + "empty": "", + "an unclosed object": `{"a":`, + "a name that is no string": `{1:2}`, + "a mismatched close": `[}`, + "a member with no value": `{"a"}`, + "an unclosed nested object": `[{`, + "a duplicate name": `{"a":1,"a":2}`, + "past the rendering depth": nested(maxRenderingDepth + 1), + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, "\x00"+value, CanonicalRendering(jsontext.Value(value))) + }) + } + assert.Equal(t, nested(maxRenderingDepth), CanonicalRendering(jsontext.Value(nested(maxRenderingDepth))), "the depth itself is read") +} + +// TestRenderedAlike_ComparesValuesMemberOrderAside holds two written values +// alike where they differ in member order and whitespace alone, and apart where +// a number, an array's order or a name differs. +func TestRenderedAlike_ComparesValuesMemberOrderAside(t *testing.T) { + t.Parallel() + assert.True(t, RenderedAlike(jsontext.Value(`{"a":1,"b":[1,2]}`), jsontext.Value(`{"b": [1,2], "a": 1}`))) + for _, pair := range [][2]string{{`1`, `1.0`}, {`[1,2]`, `[2,1]`}, {`{"a":1}`, `{"b":1}`}, {`{"a":`, `{"a":1}`}} { + assert.False(t, RenderedAlike(jsontext.Value(pair[0]), jsontext.Value(pair[1])), "%s and %s", pair[0], pair[1]) + } +} + +// TestWholeMembers_ReadsAnObjectsMembersAsWritten holds the members and names +// read off a whole entry: each member as written, by name, the names in the +// order written, and none for what is no object. +func TestWholeMembers_ReadsAnObjectsMembersAsWritten(t *testing.T) { + t.Parallel() + whole := jsontext.Value(`{"type":"string","enum":[ "a" ],"x-k":{"b":1}}`) + names, members := wholeMembers(whole) + assert.Equal(t, map[string]string{"type": `"string"`, "enum": `[ "a" ]`, "x-k": `{"b":1}`}, stringsOf(members)) + assert.Equal(t, []string{"type", "enum", "x-k"}, names) + assert.Equal(t, []string{"enum", "type", "minimum"}, orderedBy([]string{"minimum", "type", "enum"}, []string{"enum", "type"}), + "in the order written, those it writes none of last") + for name, value := range map[string]string{"empty": "", "an array": `[1]`, "a scalar": `"s"`} { + names, members := wholeMembers(jsontext.Value(value)) + assert.Empty(t, members, name) + assert.Empty(t, names, name) + } + for name, value := range map[string]string{ + "a name with no value": `{"a"`, "an unclosed value": `{"a":[`, "a name that is no string": `{"a":1,2:3}`, + "a name that is no UTF-8": "{\"a\":1,\"\xff\":2}", + } { + names, members := wholeMembers(jsontext.Value(value)) + assert.NotContains(t, members, "b", name) + assert.LessOrEqual(t, len(names), 1, name) + } +} + +// stringsOf is members with each value as a string. +func stringsOf(members map[string]jsontext.Value) map[string]string { + out := make(map[string]string, len(members)) + for name, value := range members { + out[name] = string(value) + } + return out +} + +// nestedRenderingValue is d objects each nested in the one above it, each +// writing a member before its nested one that sorts after it, so that every +// level reorders. +func nestedRenderingValue(d int) jsontext.Value { + return jsontext.Value(strings.Repeat(`{"b":0,"a":`, d) + "1" + strings.Repeat("}", d)) +} + +// renderingBytes returns the fewest bytes one CanonicalRendering of a value d +// levels deep allocates, of three runs. +func renderingBytes(t *testing.T, d int) float64 { + t.Helper() + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) + value := nestedRenderingValue(d) + fewest := -1.0 + for range 3 { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + rendered := CanonicalRendering(value) + runtime.ReadMemStats(&after) + require.NotEqual(t, byte(0), rendered[0], "the value renders as JSON") + if spent := float64(after.TotalAlloc - before.TotalAlloc); fewest < 0 || spent < fewest { + fewest = spent + } + } + return fewest +} + +// TestCanonicalRendering_AllocatesLinearlyInTheDepth holds what rendering a +// deep value allocates to linear growth in its depth: from 2000 levels to 4000 +// it grows at most 2.5 times what it grows from 1000 to 2000. A level copying +// what the levels below it rendered grows four times. It does not run in +// parallel, since the count is process-wide. +func TestCanonicalRendering_AllocatesLinearlyInTheDepth(t *testing.T) { + var bytes [3]float64 + for k, d := range []int{1000, 2000, 4000} { + bytes[k] = renderingBytes(t, d) + } + assert.LessOrEqual(t, bytes[2]-bytes[1], 2.5*(bytes[1]-bytes[0]), "bytes at 1000, 2000, 4000 levels: %v", bytes) +} diff --git a/compilers/openapi/internal/annotation/scalar_internal_test.go b/compilers/openapi/internal/annotation/scalar_internal_test.go index 6d1092812..169b165cc 100644 --- a/compilers/openapi/internal/annotation/scalar_internal_test.go +++ b/compilers/openapi/internal/annotation/scalar_internal_test.go @@ -37,7 +37,7 @@ func TestScalarRenderers_AgreeOnKind(t *testing.T) { t.Run(src, func(t *testing.T) { t.Parallel() node := openapitest.YAMLNode(t, src) - irValue, valueErr := value.FromNode(node) + result, valueErr := value.FromNode(node) raw, rawErr := RawFromNode(node) scalar, classErr := value.Classify(node) @@ -50,26 +50,26 @@ func TestScalarRenderers_AgreeOnKind(t *testing.T) { switch scalar.Kind { case value.ScalarBinary: require.NoError(t, valueErr) - assert.Equal(t, ir.ValueBytes, irValue.Kind) + assert.Equal(t, ir.ValueBytes, result.Kind) assert.Equal(t, jsontext.Kind('"'), raw.Kind(), "a payload keeps the source text") case value.ScalarTagged: require.Error(t, valueErr, "no ir.Value holds a document's own tag") assert.Equal(t, jsontext.Kind('"'), raw.Kind(), "a payload keeps the text") default: require.NoError(t, valueErr) - assert.Equal(t, jsonKindOf(irValue), raw.Kind(), "the two renderers read one kind") + assert.Equal(t, jsonKindOf(result), raw.Kind(), "the two renderers read one kind") } }) } } // jsonKindOf is the JSON kind the scalar ir.Value irValue is written as. -func jsonKindOf(irValue ir.Value) jsontext.Kind { - switch irValue.Kind { +func jsonKindOf(scalar ir.Value) jsontext.Kind { + switch scalar.Kind { case ir.ValueNull: return 'n' case ir.ValueBool: - if irValue.Bool { + if scalar.Bool { return 't' } return 'f' diff --git a/compilers/openapi/internal/annotation/unknown.go b/compilers/openapi/internal/annotation/unknown.go index a91802c8f..69165aa96 100644 --- a/compilers/openapi/internal/annotation/unknown.go +++ b/compilers/openapi/internal/annotation/unknown.go @@ -65,7 +65,7 @@ const MaxUnknownKeys = 64 // decidedKeywords are the JSON Schema keywords the schema model names no field // for (docs/parser-library.md#unmodeled-keywords) and this compiler has already -// decided about, so the census must not claim them as unread. The schema walk's +// decided about, so the census must not treat them as unread. The schema walk's // 2020-12 vocabulary test fails if one starts being carried: // // - $comment: 2020-12 §8.3 forbids presenting it to end users, so it is @@ -95,7 +95,7 @@ var modellessKeywords = []string{"$vocabulary", "dependentRequired"} // and `dependentRequired` have readers of their own. A keyword no reader // leaves a trace of is named in decidedKeywords, or in taken where only the // caller knows a reader took it. -func UnknownKeywordsIn(unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, taken ...string) ([]ir.Provenance, []ir.Diagnostic) { +func UnknownKeywordsIn(unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, taken ...string) ([]ir.Provenance, KeptReports) { keys, root := unknownSchemaKeys(schema) keys = slices.DeleteFunc(keys, func(key string) bool { return slices.Contains(taken, key) }) return census(unmodeled, keys, root, doc, pointer, "", keyClass{ @@ -107,11 +107,11 @@ func UnknownKeywordsIn(unmodeled *ir.Unmodeled, schema *statement.Schema, pointe } // WritesUnknownKeyword reports whether schema writes a keyword -// UnknownKeywordsIn would consider keeping, so a position can tell whether it +// UnknownKeywordsIn keeps when handed taken, so a position can tell whether it // needs a node of its own for one to land on. -func WritesUnknownKeyword(schema *statement.Schema) bool { +func WritesUnknownKeyword(schema *statement.Schema, taken ...string) bool { keys, _ := unknownSchemaKeys(schema) - return len(keys) > 0 + return slices.ContainsFunc(keys, func(key string) bool { return !slices.Contains(taken, key) }) } // UnknownKeyword reports whether key, a key schema writes, is one @@ -142,17 +142,21 @@ func WritesEmptyDependencyMap(schema *statement.Schema, key string) bool { return node != nil && node.Kind == yaml.MappingNode && len(node.Content) == 0 } -// WritesKeywordLeftOut reports whether schema writes key as a null that reads -// as the keyword left out (statement.Schema.Key), or key as an empty dependency -// map (WritesEmptyDependencyMap), for a reader that lists the keys schema -// writes rather than asking for one. A null is a value in an extension, and in -// a key the census keeps. +// WritesKeywordLeftOut reports whether schema writes key as a value that reads +// as the keyword left out (statement.Schema.Key): one its keyword equates with +// its absence, or a null, or key as an empty dependency map +// (WritesEmptyDependencyMap), for a reader that lists the keys schema writes +// rather than asking for one. A null is a value in a key no dialect defines, an +// extension among them, and in a key the census keeps. func WritesKeywordLeftOut(schema *statement.Schema, key string) bool { if WritesEmptyDependencyMap(schema, key) { return true } statementKey, read := schema.Key(key) - if !statementKey.Null || read || strings.HasPrefix(key, "x-") { + if statementKey.EquatesToAbsence() { + return true + } + if !statementKey.WritesNull() || read { return false } keys, _ := unknownSchemaKeys(schema) @@ -173,7 +177,7 @@ func unknownSchemaKeys(schema *statement.Schema) ([]string, *yaml.Node) { } return slices.DeleteFunc(slices.Clone(schema.Unknown), func(key string) bool { statementKey, _ := schema.Key(key) - return DecidedKeyword(key) || slices.Contains(modellessKeywords, key) && statementKey.Null || + return DecidedKeyword(key) || slices.Contains(modellessKeywords, key) && statementKey.WritesNull() || WritesEmptyDependencyMap(schema, key) }), schema.Node } @@ -184,17 +188,17 @@ func unknownSchemaKeys(schema *statement.Schema) ([]string, *yaml.Node) { // keyword the model does not name: JSON Schema 2020-12 ignores the two alike. // The caller says which keywords those are, since only it knows the dialect and // the policies. -func UndefinedKeywordsIn(unmodeled *ir.Unmodeled, schema *statement.Schema, keys []string, pointer jsontext.Pointer, doc provenance.Doc) []ir.Diagnostic { +func UndefinedKeywordsIn(unmodeled *ir.Unmodeled, schema *statement.Schema, keys []string, pointer jsontext.Pointer, doc provenance.Doc) KeptReports { if len(keys) == 0 { return nil } - _, diags := census(unmodeled, keys, schema.Node, doc, pointer, "", keyClass{ + _, reports := census(unmodeled, keys, schema.Node, doc, pointer, "", keyClass{ code: diag.UnknownSchemaKeyword, severity: ir.SeverityInfo, message: "keyword %q is not defined by the dialect this schema is read in, and no policy reads it " + "here; kept verbatim under Unmodeled", }) - return diags + return reports } // UnknownKeysIn records on unmodeled the keys an OpenAPI object writes that the @@ -220,7 +224,7 @@ func UnknownKeysIn(unmodeled *ir.Unmodeled, model any, doc provenance.Doc, owner // lowering ran last. taken lists keys a reader placed in a field (TakeString). func UnknownKeysUnder(unmodeled *ir.Unmodeled, model any, doc provenance.Doc, owner jsontext.Pointer, scope string, taken ...string) []ir.Diagnostic { keys, root := undeclaredKeys(model) - return UnknownKeysNamed(unmodeled, keys, root, doc, owner, scope, taken...) + return UnknownKeysNamed(unmodeled, keys, root, doc, owner, scope, taken...).Diagnostics() } // UnknownKeysNamed is UnknownKeysUnder for an object whose model keeps no @@ -232,12 +236,12 @@ func UnknownKeysUnder(unmodeled *ir.Unmodeled, model any, doc provenance.Doc, ow // rather than recording it as undeclared, so the object's census is empty // however much the document wrote (docs/parser-library.md#embedded-map-keys). // Its leftovers are graded as any undeclared key is, because UnknownKeysUnder -// delegates here. +// delegates here. Each report is paired with the key of the entry it reports. func UnknownKeysNamed(unmodeled *ir.Unmodeled, keys []string, root *yaml.Node, doc provenance.Doc, owner jsontext.Pointer, scope string, taken ...string, -) []ir.Diagnostic { - _, diags := census(unmodeled, keys, root, doc, owner, scope, keyClass{skip: taken}) - return diags +) KeptReports { + _, reports := census(unmodeled, keys, root, doc, owner, scope, keyClass{skip: taken}) + return reports } // TakeString reads a string field the parser's model names no member for, @@ -261,7 +265,7 @@ func TakeString(unmodeled *ir.Unmodeled, root *yaml.Node, key string, valid func return value, true, nil } at := doc.At(owner + ids.Ptr(key)) - kept, diags := PreserveNodeInto(unmodeled, EntryKey(scope, key), node, ir.ReasonDegradedLowering, at) + kept, diags := KeepNodeInto(unmodeled, EntryKey(scope, key), node, ir.ReasonDegradedLowering, at) if !kept { return "", true, diags } @@ -317,7 +321,7 @@ type keyClass struct { // unrecorded). That happens before the bound applies (see MaxUnknownKeys). func census(unmodeled *ir.Unmodeled, keys []string, root *yaml.Node, doc provenance.Doc, owner jsontext.Pointer, scope string, cl keyClass, -) ([]ir.Provenance, []ir.Diagnostic) { +) ([]ir.Provenance, KeptReports) { if len(keys) == 0 { return nil, nil // the common case: most objects write no key their model misses } @@ -326,40 +330,42 @@ func census(unmodeled *ir.Unmodeled, keys []string, root *yaml.Node, return nil, nil } var unpreserved []ir.Provenance - var diags []ir.Diagnostic + var reports KeptReports if len(fresh) > MaxUnknownKeys { - diags = append(diags, budgetDiag(len(fresh), doc.At(owner))) + reports = append(reports, ReportsOf("", budgetDiag(len(fresh), doc.At(owner)))...) fresh = fresh[:MaxUnknownKeys] } for _, key := range fresh { - keyDiags, failed := keep(unmodeled, root, key, doc, owner, scope, cl) + keyReports, failed := keep(unmodeled, root, key, doc, owner, scope, cl) if failed { unpreserved = append(unpreserved, doc.At(owner+ids.Ptr(key))) } - diags = append(diags, keyDiags...) + reports = append(reports, keyReports...) } - return unpreserved, diags + return unpreserved, reports } // keep writes one key's value under its entry and announces it, or says why it -// could not, reporting whether raw conversion failed. -func keep(unmodeled *ir.Unmodeled, root *yaml.Node, key string, doc provenance.Doc, owner jsontext.Pointer, scope string, cl keyClass) ([]ir.Diagnostic, bool) { +// could not, reporting whether raw conversion failed. What it draws of the +// entry it writes is paired with the entry's key, and a report of an entry +// another construct holds with none. +func keep(unmodeled *ir.Unmodeled, root *yaml.Node, key string, doc provenance.Doc, owner jsontext.Pointer, scope string, cl keyClass) (KeptReports, bool) { entry, at := EntryKey(scope, key), doc.At(owner+ids.Ptr(key)) if taken, occupied := (*unmodeled)[entry]; occupied { - return []ir.Diagnostic{occupiedEntryDiag(entry, at, taken.Provenance.Pointer)}, false + return ReportsOf("", occupiedEntryDiag(entry, at, taken.Provenance.Pointer)), false } node := nodeview.Child(root, key) if node == nil { - return []ir.Diagnostic{unreachableKeyDiag(entry, at)}, false + return ReportsOf("", unreachableKeyDiag(entry, at)), false } - kept, diags := PreserveNodeInto(unmodeled, entry, node, ir.ReasonOutOfScope, at) + kept, diags := KeepNodeInto(unmodeled, entry, node, ir.ReasonOutOfScope, at) if !kept { - return diags, len(diags) > 0 + return ReportsOf(entry, diags...), len(diags) > 0 } if cl.code == "" { - return diags, false + return ReportsOf(entry, diags...), false } - return append(diags, diag.Newf(cl.severity, cl.code, at, cl.message, key)), false + return ReportsOf(entry, append(diags, diag.Newf(cl.severity, cl.code, at, cl.message, key))...), false } // unrecorded returns the keys this census has to answer for: those not in skip, @@ -392,6 +398,32 @@ func EntryKey(scope, key string) string { return entryPrefix + scoped(scope, key) } +// EntryKeyword returns the schema keyword the entry under key is kept for: +// the first segment past the path of an allOf entry the key is kept under, if +// any, as openapi:allOf/0/maxLength keeps maxLength and +// openapi:discriminator/x-k what the discriminator writes. It is false for a +// key another reader spells and for one keeping an allOf entry whole, such as +// openapi:allOf/1. +func EntryKeyword(key string) (string, bool) { + rest, ours := strings.CutPrefix(key, entryPrefix) + if !ours { + return "", false + } + segments := strings.Split(rest, "/") + for len(segments) > 1 && segments[0] == "allOf" && entryIndex(segments[1]) { + segments = segments[2:] + } + if len(segments) == 0 || segments[0] == "" { + return "", false + } + return jsontext.Pointer("/" + segments[0]).LastToken(), true +} + +// entryIndex reports whether segment is an index among an allOf's entries. +func entryIndex(segment string) bool { + return segment != "" && !strings.ContainsFunc(segment, func(character rune) bool { return character < '0' || character > '9' }) +} + // scoped spells one entry's key on the carrier holding it. // // The key is escaped as one segment while scope is a path of literals already @@ -441,8 +473,8 @@ type unknownReporter interface{ GetUnknownProperties() []string } // legitimate entry. A Path Item's keys go to UnknownKeysNamed instead, and // another such object would go quiet here. func undeclaredKeys(model any) ([]string, *yaml.Node) { - v := reflect.ValueOf(model) - if v.Kind() == reflect.Pointer && v.IsNil() { + modelValue := reflect.ValueOf(model) + if modelValue.Kind() == reflect.Pointer && modelValue.IsNil() { return nil, nil } obj, ok := model.(parsedObject) diff --git a/compilers/openapi/internal/annotation/unknown_internal_test.go b/compilers/openapi/internal/annotation/unknown_internal_test.go index b61c23853..28fad4301 100644 --- a/compilers/openapi/internal/annotation/unknown_internal_test.go +++ b/compilers/openapi/internal/annotation/unknown_internal_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "github.com/speakeasy-api/openapi/jsonschema/oas3" soa "github.com/speakeasy-api/openapi/openapi" soavalidation "github.com/speakeasy-api/openapi/validation" "github.com/stretchr/testify/assert" @@ -18,7 +19,9 @@ import ( yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/dialect" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) @@ -28,10 +31,11 @@ import ( // own key, located at itself, and is announced at info. func TestUnknownKeywordsIn_KeepsWhatTheModelDoesNotName(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nx-ray: kept\nnotAKeyword: 7\n") + schema := schemaFromYAML(t, "type: string\nx-ray: kept\nnotAKeyword: 7\n") var got ir.Unmodeled - unpreserved, diags := UnknownKeywordsIn(&got, standaloneSchema(s), "/components/schemas/A", sourced(3)) + unpreserved, diagsReports := UnknownKeywordsIn(&got, standaloneSchema(schema), "/components/schemas/A", sourced(3)) + diags := diagsReports.Diagnostics() assert.Empty(t, unpreserved) require.Len(t, got, 1, "the x-* is the extension reader's, not the census's; got %v", got) @@ -52,10 +56,11 @@ func TestUnknownKeywordsIn_KeepsWhatTheModelDoesNotName(t *testing.T) { // keyword, whatever its value, and naming none keeps nothing. func TestUndefinedKeywordsIn_KeepsWhatTheCallerNames(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nnullable: false\n") + schema := schemaFromYAML(t, "type: string\nnullable: false\n") var got ir.Unmodeled - diags := UndefinedKeywordsIn(&got, standaloneSchema(s), []string{"nullable"}, "/components/schemas/A", sourced(2)) + diagsReports := UndefinedKeywordsIn(&got, standaloneSchema(schema), []string{"nullable"}, "/components/schemas/A", sourced(2)) + diags := diagsReports.Diagnostics() require.Len(t, got, 1) entry := got["openapi:nullable"] @@ -68,13 +73,13 @@ func TestUndefinedKeywordsIn_KeepsWhatTheCallerNames(t *testing.T) { assert.Contains(t, diags[0].Message, `"nullable" is not defined by the dialect`) var none ir.Unmodeled - assert.Empty(t, UndefinedKeywordsIn(&none, standaloneSchema(s), nil, "/components/schemas/A", sourced(2))) + assert.Empty(t, UndefinedKeywordsIn(&none, standaloneSchema(schema), nil, "/components/schemas/A", sourced(2))) assert.Empty(t, none) } // TestUnknownKeywordsIn_DecidedKeywordsAreLeftAlone holds the census to the // decisions already recorded elsewhere. Each of these has no field in the schema -// model, so the census would otherwise claim all three and overrule a +// model, so the census would otherwise pending keep all three and overrule a // deliberate drop — or, for an expanded $dynamicRef, say the compiler ignored a // reference it resolved. func TestUnknownKeywordsIn_DecidedKeywordsAreLeftAlone(t *testing.T) { @@ -87,10 +92,11 @@ func TestUnknownKeywordsIn_DecidedKeywordsAreLeftAlone(t *testing.T) { for _, keyword := range DecidedKeywordList() { body.WriteString(keyword + ": v\n") } - s := schemaFromYAML(t, body.String()) + schema := schemaFromYAML(t, body.String()) var got ir.Unmodeled - unpreserved, diags := UnknownKeywordsIn(&got, standaloneSchema(s), "/components/schemas/A", sourced(0)) + unpreserved, diagsReports := UnknownKeywordsIn(&got, standaloneSchema(schema), "/components/schemas/A", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, unpreserved) assert.Empty(t, got, "each is decided about elsewhere, so the census keeps none of them") @@ -104,7 +110,7 @@ func TestUnknownKeywordsIn_DecidedKeywordsAreLeftAlone(t *testing.T) { // twice. func TestUnknownKeywordsIn_AlreadyRecordedKeyIsLeftAlone(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\ndependentRequired: {a: [b]}\n") + schema := schemaFromYAML(t, "type: object\ndependentRequired: {a: [b]}\n") already := ir.UnmodeledEntry{ Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{"a":["b"]}`), @@ -112,7 +118,8 @@ func TestUnknownKeywordsIn_AlreadyRecordedKeyIsLeftAlone(t *testing.T) { } got := ir.Unmodeled{"openapi:dependentRequired": already} - unpreserved, diags := UnknownKeywordsIn(&got, standaloneSchema(s), "/A", sourced(0)) + unpreserved, diagsReports := UnknownKeywordsIn(&got, standaloneSchema(schema), "/A", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, unpreserved) assert.Equal(t, ir.Unmodeled{"openapi:dependentRequired": already}, got) @@ -124,10 +131,11 @@ func TestUnknownKeywordsIn_AlreadyRecordedKeyIsLeftAlone(t *testing.T) { // says so, rather than announcing a preservation that did not happen. func TestUnknownKeywordsIn_UnpreservableValueIsReportedNotKept(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: string\nnotAKeyword: .nan\n") + schema := schemaFromYAML(t, "type: string\nnotAKeyword: .nan\n") var got ir.Unmodeled - unpreserved, diags := UnknownKeywordsIn(&got, standaloneSchema(s), "/A", sourced(0)) + unpreserved, diagsReports := UnknownKeywordsIn(&got, standaloneSchema(schema), "/A", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, got) assert.Equal(t, []ir.Provenance{{Source: 0, Pointer: "/A/notAKeyword"}}, unpreserved) @@ -148,7 +156,8 @@ func TestUnknownKeywordsIn_AKeywordMergedPastTheBoundIsUnreachable(t *testing.T) require.False(t, listed, "the statement's keys stop at the bound") var got ir.Unmodeled - unpreserved, diags := UnknownKeywordsIn(&got, schema, "/A", sourced(0)) + unpreserved, diagsReports := UnknownKeywordsIn(&got, schema, "/A", sourced(0)) + diags := diagsReports.Diagnostics() assert.Empty(t, unpreserved) assert.Empty(t, got, "no node of it is reached") @@ -204,10 +213,10 @@ func TestUnknownKeysIn_AttributesEachKeyAtItsOwnPointer(t *testing.T) { assert.Empty(t, diags, "the rule table reports an unknown object key, so the census only keeps it") } -// TestUnknownKeysIn_BudgetBoundsWhatOneObjectContributes exercises the bound. An -// object writing more undeclared keys than MaxUnknownKeys keeps exactly that +// TestUnknownKeysIn_BudgetBoundsWhatOneObjectContributes exercises the bound. +// An object writing more undeclared keys than MaxUnknownKeys keeps exactly that // many and reports the remainder, which is what stops the discarded tail from -// being the silent loss this census exists to end. +// being the unreported loss this census exists to end. func TestUnknownKeysIn_BudgetBoundsWhatOneObjectContributes(t *testing.T) { t.Parallel() const over = MaxUnknownKeys + 3 @@ -234,14 +243,15 @@ func TestUnknownKeysIn_BudgetBoundsWhatOneObjectContributes(t *testing.T) { } // TestUnknownKeysIn_KeyWithNoSourceNodeIsReported covers the one outcome -// PreserveNodeInto's contract does not: a key whose value node is not in the +// KeepNodeInto's contract does not: a key whose value node is not in the // mapping. // -// Everywhere else an absent node means the construct was never written, which is -// why it records nothing and says nothing. Here the parser has already reported -// the key as present, so an absent node means this reader could not reach one -// the document does write — a merged-in key, in practice — and passing over it -// would be the silent loss this census exists to end (GitHub #395). +// Everywhere else an absent node means the construct was never written, which +// is why it records nothing and says nothing. Here the parser has already +// reported the key as present, so an absent node means this reader could not +// reach one the document does write — a merged-in key, in practice — and +// passing over it would be the unreported loss this census exists to end +// (GitHub #395). func TestUnknownKeysIn_KeyWithNoSourceNodeIsReported(t *testing.T) { t.Parallel() obj := fakeObject{core: &fakeCore{keys: []string{"absent"}}, root: openapitest.YAMLDocument(t, "present: 1\n")} @@ -360,9 +370,9 @@ func TestUnknownKeysNamed_DelegatesTheSameGrading(t *testing.T) { assert.Empty(t, diags, "the rule table reports the key, so the census only keeps it") } -// fakeObject is a parsed model standing in for the library's, so the census can -// be driven at shapes no real document produces — an unsorted census, one past -// the bound, and a core that keeps none. +// fakeObject is a parsed model taking the place of the library's, so the census +// can be driven at shapes no real document produces — an unsorted census, one +// past the bound, and a core that keeps none. type fakeObject struct { core any root *yaml.Node @@ -399,18 +409,18 @@ func TestTakeString_UnkeepableValueIsReportedAndRead(t *testing.T) { } // parserString returns what the parser makes of value written as the optional -// string field info.summary, which the model names where TakeString reads one it -// does not: the string it decodes, empty where the field is null or unset, and -// whether it decodes the value as a string at all. The anchor x stands behind an -// alias. +// string field info.summary, which the model names where TakeString reads one +// it does not: the string it decodes, empty where the field is null or unset, +// and whether it decodes the value as a string at all. The anchor x sits behind +// an alias. func parserString(t *testing.T, value string) (string, bool) { t.Helper() src := "openapi: 3.1.0\nx-a: &x hello\ninfo:\n title: T\n version: '1'\n summary: " + value + "\npaths: {}\n" parsed, findings, err := soa.Unmarshal(t.Context(), strings.NewReader(src)) require.NoError(t, err) - for _, e := range findings { + for _, finding := range findings { var ve *soavalidation.Error - if errors.As(e, &ve) && ve.Rule == soavalidation.RuleValidationTypeMismatch { + if errors.As(finding, &ve) && ve.Rule == soavalidation.RuleValidationTypeMismatch { return "", false } } @@ -543,31 +553,65 @@ func TestWritesUnknownKeyword_AsksWhatTheCensusWouldKeep(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, tc.schema) - assert.Equal(t, tc.want, WritesUnknownKeyword(standaloneSchema(s))) - assert.Equal(t, tc.want, slices.ContainsFunc(standaloneSchema(s).Keys, func(key statement.Key) bool { - return UnknownKeyword(standaloneSchema(s), key.Name) + schema := schemaFromYAML(t, tc.schema) + assert.Equal(t, tc.want, WritesUnknownKeyword(standaloneSchema(schema))) + assert.Equal(t, tc.want, slices.ContainsFunc(standaloneSchema(schema).Keys, func(key statement.Key) bool { + return UnknownKeyword(standaloneSchema(schema), key.Name) }), "a keyword of it answers alike") var kept ir.Unmodeled - _, _ = UnknownKeywordsIn(&kept, standaloneSchema(s), "/s", sourced(0)) + _, _ = UnknownKeywordsIn(&kept, standaloneSchema(schema), "/s", sourced(0)) assert.Equal(t, tc.want, len(kept) > 0) }) } assert.False(t, WritesUnknownKeyword(nil), "a position with no schema object writes none") } -// TestWritesKeywordLeftOut_TellsANullThatStatesNothing pins what a reader -// listing a schema's keys asks of each: a null for a keyword of the dialect is -// the keyword left out, while one that is a value stays written, as an -// instance's, an extension's, and that of a key the census keeps. -func TestWritesKeywordLeftOut_TellsANullThatStatesNothing(t *testing.T) { +// TestWritesUnknownKeyword_LeavesWhatIsTaken pins the question's taken keys to +// UnknownKeywordsIn's: a keyword another reader takes is none it keeps, so a +// position writing only that one needs no node for it, and one writing another +// beside it still does. +func TestWritesUnknownKeyword_LeavesWhatIsTaken(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "{title: t, description: null, dependentRequired: ~, const: null, x-e: null, k: null}\n") + for _, tc := range []struct { + name, schema string + want bool + }{ + {"only a taken keyword", "{type: string, k: 1}\n", false}, + {"another beside it", "{type: string, k: 1, j: 2}\n", true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + s := standaloneSchema(schemaFromYAML(t, tc.schema)) + assert.Equal(t, tc.want, WritesUnknownKeyword(s, "k")) + var kept ir.Unmodeled + _, _ = UnknownKeywordsIn(&kept, s, "/s", sourced(0), "k") + assert.Equal(t, tc.want, len(kept) > 0, "UnknownKeywordsIn keeps alike") + }) + } +} + +// TestWritesKeywordLeftOut_TellsAValueThatStatesNothing pins what a reader +// listing a schema's keys asks of each, read in a dialect: a null for a +// keyword it defines is the keyword left out, and so is the value a keyword +// equates with its absence, while any other value stays written, as an +// instance's null, an extension's, and that of a key no dialect defines, the +// 3.1 `nullable` among them. +func TestWritesKeywordLeftOut_TellsAValueThatStatesNothing(t *testing.T) { + t.Parallel() + rules, unread := specrules.Table().SchemaRules("3.1.0", "") + require.False(t, unread) + schema := schemaFromYAML(t, "{title: t, description: null, dependentRequired: ~, const: null, x-e: null, k: null, "+ + "nullable: null, readOnly: false, writeOnly: true, uniqueItems: false, minLength: 0, minItems: 1, "+ + "required: [], pattern: '', format: '', additionalProperties: true}\n") + read := statement.NewTable(statement.Source{Rules: dialect.NewBuilder(rules).Table()}). + Of(oas3.NewJSONSchemaFromSchema[oas3.Referenceable](schema)).Schema for key, want := range map[string]bool{ "description": true, "dependentRequired": true, - "const": false, "x-e": false, "k": false, "title": false, "absent": false, + "readOnly": true, "uniqueItems": true, "minLength": true, "required": true, "pattern": true, + "const": false, "x-e": false, "k": false, "nullable": false, "title": false, "absent": false, + "writeOnly": false, "minItems": false, "format": false, "additionalProperties": false, } { - assert.Equal(t, want, WritesKeywordLeftOut(standaloneSchema(s), key), key) + assert.Equal(t, want, WritesKeywordLeftOut(read, key), key) } } @@ -578,14 +622,14 @@ func TestWritesKeywordLeftOut_TellsANullThatStatesNothing(t *testing.T) { // keyword and kept whatever it holds. func TestWritesEmptyDependencyMap_TellsAnEmptyMapFromAnEntry(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "{dependentSchemas: {}, dependentRequired: {}, dependencies: {}, definitions: {}, "+ + schema := schemaFromYAML(t, "{dependentSchemas: {}, dependentRequired: {}, dependencies: {}, definitions: {}, "+ "properties: {}, title: t}\n") for key, want := range map[string]bool{ "dependentSchemas": true, "dependentRequired": true, "dependencies": false, "definitions": false, "properties": false, "title": false, "absent": false, } { - assert.Equal(t, want, WritesEmptyDependencyMap(standaloneSchema(s), key), key) - assert.Equal(t, want, WritesKeywordLeftOut(standaloneSchema(s), key), key) + assert.Equal(t, want, WritesEmptyDependencyMap(standaloneSchema(schema), key), key) + assert.Equal(t, want, WritesKeywordLeftOut(standaloneSchema(schema), key), key) } filled := schemaFromYAML(t, "{dependentSchemas: {a: {required: [b]}}, dependentRequired: [a]}\n") assert.False(t, WritesEmptyDependencyMap(standaloneSchema(filled), "dependentSchemas")) diff --git a/compilers/openapi/internal/annotation/validationonly.go b/compilers/openapi/internal/annotation/validationonly.go index 737ed126f..aa983a7ec 100644 --- a/compilers/openapi/internal/annotation/validationonly.go +++ b/compilers/openapi/internal/annotation/validationonly.go @@ -6,6 +6,7 @@ package annotation import ( "encoding/json/jsontext" "fmt" + "slices" "strings" yaml "go.yaml.in/yaml/v3" @@ -19,96 +20,106 @@ import ( // IfThenElseRaw combines the present if/then/else arms into one raw JSON // object, and names the arms it combines. func IfThenElseRaw(schema *statement.Schema) (ir.RawValue, []string, error) { - return combine(schema, "if", "then", "else") + return CombinedRaw(schema, "if", "then", "else") } // ContainsRaw combines contains/minContains/maxContains into one raw JSON // object, and names the keywords it combines. func ContainsRaw(schema *statement.Schema) (ir.RawValue, []string, error) { + raw, keys, _, err := containsCombined(schema, renderAsWritten) + return raw, keys, err +} + +// containsCombined is ContainsRaw rendering each member by render +// (combineKept). +func containsCombined(schema *statement.Schema, render memberRendering) (ir.RawValue, []string, []jsontext.Pointer, error) { if schema == nil || schema.Array == nil { - return nil, nil, nil + return nil, nil, nil, nil } - if a := schema.Array; a.Contains == (statement.Subschema{}) && a.MinContains == nil && a.MaxContains == nil { - return nil, nil, nil + if array := schema.Array; array.Contains == (statement.Subschema{}) && array.MinContains == nil && array.MaxContains == nil { + return nil, nil, nil, nil } - return combine(schema, "contains", "minContains", "maxContains") + keywords, _ := combinedKeywords(containsLabel) + return combineKept(schema, render, keywords...) } // ExamplesRaw combines example and examples into one raw JSON object, and names // the keywords it combines: Set.Examples holds the two as one list. func ExamplesRaw(schema *statement.Schema) (ir.RawValue, []string, error) { - return combine(schema, "example", "examples") + return CombinedRaw(schema, "example", "examples") } -// ClosesAfterComposition reports whether schema closes its model once -// composition is resolved: it writes `unevaluatedProperties: false` and no -// additionalProperties, which would evaluate every property the keyword could -// apply to (JSON Schema 2020-12 §11.3). It reads the adjacent keyword alone, so -// an applicator kept verbatim that evaluates a member leaves the closure typed -// (GitHub #1904). +// ClosesAfterComposition reports whether schema's closure after composition is +// live: it writes `unevaluatedProperties: false` and no additionalProperties, +// which would evaluate every property the keyword could apply to (JSON Schema +// 2020-12 §11.3). It reads the adjacent keyword alone; whether every evaluator +// the keyword reaches is one the IR types, as a closed model needs, is the +// schema package's to read. func ClosesAfterComposition(schema *statement.Schema) bool { - return schema.ObjectKeywords().UnevaluatedProperties.SchemaValueForm().ReadsFalse() && inertBeside(schema, "unevaluatedProperties", Dialect{}) == "" + return schema.ObjectKeywords().UnevaluatedProperties.SchemaValueForm().ReadsFalse() && saysNothingBeside(schema, "unevaluatedProperties", Dialect{}) == "" } -// unevaluatedRaw renders the entry holding kept, each inert keyword beside the -// keyword written next to it that leaves it nothing to apply to (inertBeside), -// and names its unevaluated keywords alone, which are what its provenance is -// asked about: the keyword beside an inert one is context the entry holds -// whoever wrote it. -func unevaluatedRaw(schema *statement.Schema, kept []keptUnevaluated) (ir.RawValue, []string, error) { +// unevaluatedRaw renders the entry holding kept, each keyword that says nothing +// beside the keyword written next to it that leaves it nothing to apply to +// (saysNothingBeside), and names its unevaluated keywords alone, which are what +// its provenance is asked about: the keyword beside one that says nothing is +// context the entry holds whoever wrote it. It leaves out each vendor extension +// no JSON holds, as a keep does (RenderDroppingExtensions), returning those +// extensions' pointers. +func unevaluatedRaw(schema *statement.Schema, kept []keptUnevaluated) (ir.RawValue, []string, []jsontext.Pointer, error) { if len(kept) == 0 { - return nil, nil, nil + return nil, nil, nil, nil } - raw, _, err := combine(schema, unevaluatedMembers(kept)...) + raw, _, dropped, err := combineKept(schema, RenderDroppingExtensions, unevaluatedMembers(kept)...) names := make([]string, 0, len(kept)) for _, keptUnevaluated := range kept { names = append(names, keptUnevaluated.keyword) } - return raw, names, err + return raw, names, dropped, err } // keptUnevaluated is one unevaluated keyword an entry keeps, and the keyword -// written beside it that leaves it inert, "" for a live one. +// written beside it that leaves it saying nothing, "" for a live one. type keptUnevaluated struct { - keyword string - inertBy string + keyword string + saysNothingBy string } // unevaluatedKept returns the unevaluated keywords schema writes that an entry -// keeps, in keyword order. closure says the node took -// `unevaluatedProperties: false` as its openness, so that form is left out, and -// dialect says where schema's dialect reads the elements past a prefix. It asks -// the typed values first, so a schema writing neither, nearly every one, costs -// no read of its node. -func unevaluatedKept(schema *statement.Schema, closure bool, dialect Dialect) []keptUnevaluated { +// keeps, in keyword order. typed says which of them the node holds, which are +// left out, and dialect says where schema's dialect reads the elements past a +// prefix. It asks the typed values first, so a schema writing neither, nearly +// every one, costs no read of its node. +func unevaluatedKept(schema *statement.Schema, typed Typed, dialect Dialect) []keptUnevaluated { var out []keptUnevaluated keep := func(keyword string) { - out = append(out, keptUnevaluated{keyword: keyword, inertBy: inertBeside(schema, keyword, dialect)}) + out = append(out, keptUnevaluated{keyword: keyword, saysNothingBy: saysNothingBeside(schema, keyword, dialect)}) } - if up := schema.ObjectKeywords().UnevaluatedProperties.SchemaValueForm(); up != statement.Unwritten && (!closure || !up.ReadsFalse()) { + if up := schema.ObjectKeywords().UnevaluatedProperties.SchemaValueForm(); up != statement.Unwritten && (up.ReadsFalse() && !typed.Closure || !up.ReadsFalse() && !typed.CatchAll) { keep("unevaluatedProperties") } - if schema.ArrayKeywords().UnevaluatedItems.SchemaValueForm() != statement.Unwritten { + if schema.ArrayKeywords().UnevaluatedItems.SchemaValueForm() != statement.Unwritten && !typed.Items { keep("unevaluatedItems") } return out } // unevaluatedMembers returns the members an entry holding kept writes, each -// inert keyword after the keyword that leaves it so, which a consumer reading -// the entry beside what its position types then reads as the source does. +// keyword that says nothing after the keyword that leaves it so, which a +// consumer reading the entry beside what its position types then reads as the +// source does. func unevaluatedMembers(kept []keptUnevaluated) []string { out := make([]string, 0, 2*len(kept)) for _, keptUnevaluated := range kept { - if keptUnevaluated.inertBy != "" { - out = append(out, keptUnevaluated.inertBy) + if keptUnevaluated.saysNothingBy != "" { + out = append(out, keptUnevaluated.saysNothingBy) } out = append(out, keptUnevaluated.keyword) } return out } -// inertBeside returns the keyword schema writes beside keyword, an unevaluated +// saysNothingBeside returns the keyword schema writes beside keyword, an unevaluated // one, that evaluates every location keyword could apply to, and "" where // schema writes none. Beside unevaluatedProperties that is an // additionalProperties of any value (JSON Schema 2020-12 §10.3.2.3). Beside @@ -116,7 +127,7 @@ func unevaluatedMembers(kept []keptUnevaluated) []string { // an `items` list as a tuple, the additionalItems written beside it (2019-09 // §9.3.1.2). An `items` list any other dialect reads is no schema, and // evaluates nothing. -func inertBeside(schema *statement.Schema, keyword string, dialect Dialect) string { +func saysNothingBeside(schema *statement.Schema, keyword string, dialect Dialect) string { if keyword == "unevaluatedProperties" { if schema.ObjectKeywords().AdditionalProperties.SchemaValueForm() != statement.Unwritten { return "additionalProperties" @@ -135,13 +146,13 @@ func inertBeside(schema *statement.Schema, keyword string, dialect Dialect) stri return "" } -// unevaluatedNote words the report of an unevaluated entry holding kept: as -// any validation-only entry's, but naming each inert keyword and the keyword -// that leaves it so, which the entry holds beside it. +// unevaluatedNote words the report of an unevaluated entry holding kept: as any +// validation-only entry's, but naming each keyword that says nothing and the +// keyword that leaves it so, which the entry holds beside it. func unevaluatedNote(kept []keptUnevaluated) string { var clauses []string for _, keptUnevaluated := range kept { - if keptUnevaluated.inertBy == "" { + if keptUnevaluated.saysNothingBy == "" { continue } unit := "property" @@ -149,7 +160,7 @@ func unevaluatedNote(kept []keptUnevaluated) string { unit = "element" } clauses = append(clauses, fmt.Sprintf("%s beside %s applies to no %s, since %s evaluates each one it would", - keptUnevaluated.keyword, keptUnevaluated.inertBy, unit, keptUnevaluated.inertBy)) + keptUnevaluated.keyword, keptUnevaluated.saysNothingBy, unit, keptUnevaluated.saysNothingBy)) } switch { case len(clauses) == 0: @@ -161,34 +172,42 @@ func unevaluatedNote(kept []keptUnevaluated) string { } } -// combine renders the keys schema writes, of those given, as one raw JSON +// CombinedRaw renders the keys schema writes, of those given, as one raw JSON // object, and names the keys written; nothing written yields no object rather // than an empty one. The entry built from it has no position of its own, so // those keys are what its provenance is asked about (GitHub #534). They are -// named beside a conversion error as well, because the report that stands in -// for an entry that could not be kept is attributed as the entry would have -// been. -func combine(schema *statement.Schema, keys ...string) (ir.RawValue, []string, error) { - members, written, err := presentMembers(schema, keys...) +// named beside a conversion error as well, because the report that takes the +// place of an entry that could not be kept is attributed as the entry would +// have been. +func CombinedRaw(schema *statement.Schema, keys ...string) (ir.RawValue, []string, error) { + raw, written, _, err := combineKept(schema, renderAsWritten, keys...) + return raw, written, err +} + +// combineKept is CombinedRaw rendering each member by render, and returns, from +// schema, the pointer of each part of a member that render left out. +func combineKept(schema *statement.Schema, render memberRendering, keys ...string) (ir.RawValue, []string, []jsontext.Pointer, error) { + members, written, dropped, err := presentMembers(schema, render, keys...) if err != nil || len(members) == 0 { - return nil, written, err + return nil, written, dropped, err } raw, err := jsonObject(members) - return raw, written, err + return raw, written, dropped, err } -// presentMembers collects the given keywords that are present on schema as raw -// JSON members, preserving the requested order, and names the keywords present. -// A keyword written as `null` states nothing, so it is read as left out. +// presentMembers renders each of the given keywords schema writes by render, as +// a raw JSON member in the order given, and names them. A keyword written as +// `null` states nothing, so it is read as left out. // // A member that cannot be converted fails the whole combination rather than // being skipped: the entry is presented as the verbatim source, so dropping a // member would restate GitHub #144 in miniature. The error names the first such // member, and the keywords present are returned in full even then, since the // report of the failure is attributed by all of them. -func presentMembers(schema *statement.Schema, keys ...string) ([]rawMember, []string, error) { +func presentMembers(schema *statement.Schema, render memberRendering, keys ...string) ([]rawMember, []string, []jsontext.Pointer, error) { var members []rawMember var present []string + var dropped []jsontext.Pointer var failed error for _, k := range keys { node := keyNode(schema, k) @@ -196,7 +215,10 @@ func presentMembers(schema *statement.Schema, keys ...string) ([]rawMember, []st continue } present = append(present, k) - raw, err := RawFromNode(node) + raw, left, err := render(node) + for _, at := range left { + dropped = append(dropped, ids.Ptr(k)+at) + } switch { case err == nil: members = append(members, rawMember{key: k, val: raw}) @@ -205,9 +227,21 @@ func presentMembers(schema *statement.Schema, keys ...string) ([]rawMember, []st } } if failed != nil { - return nil, present, failed + return nil, present, nil, failed } - return members, present, nil + return members, present, dropped, nil +} + +// memberRendering renders the YAML node of one member of a combined object as +// the JSON the object holds, and returns the pointer, from node, of each part +// it left out. +type memberRendering func(node *yaml.Node) (ir.RawValue, []jsontext.Pointer, error) + +// renderAsWritten is RawFromNode as a memberRendering: it leaves out nothing, +// so a vendor extension no JSON holds fails the rendering. +func renderAsWritten(node *yaml.Node) (ir.RawValue, []jsontext.Pointer, error) { + raw, err := RawFromNode(node) + return raw, nil, err } // rawMember is one key/raw-JSON pair of a combined validation-only object. @@ -221,55 +255,58 @@ type rawMember struct { // is the caller's — a fixed handful of JSON Schema keywords in keyword order — // and is preserved rather than sorted. func jsonObject(members []rawMember) (ir.RawValue, error) { - var b strings.Builder - b.WriteByte('{') + var builder strings.Builder + builder.WriteByte('{') for i, rawMember := range members { if i > 0 { - b.WriteByte(',') + builder.WriteByte(',') } key, err := jsontext.AppendQuote(nil, rawMember.key) if err != nil { return nil, fmt.Errorf("member %q: %w", rawMember.key, err) } - b.Write(key) - b.WriteByte(':') - b.Write(rawMember.val) + builder.Write(key) + builder.WriteByte(':') + builder.Write(rawMember.val) } - b.WriteByte('}') - return ir.RawValue(b.String()), nil + builder.WriteByte('}') + return ir.RawValue(builder.String()), nil } // validationOnlyAt collects the validation-only keywords // (docs/ir/boundaries.md#validation-only-constructs) a schema declares that the // IR does not model, keeping each verbatim and announcing it, `dependencies` -// among them where dialect defines it. own says s is the schema written at the -// position rather than a voice, whose unevaluated keywords stay with its entry -// (schema.foldEntry), and closure is unevaluatedKept's. +// among them where dialect defines it. role says whether schema is the schema +// written at the position or a folded allOf entry, whose unevaluated keywords +// stay with the entry (schema.foldKey), and typed is unevaluatedKept's. // // Site-only: these constrain the value at the position that wrote them. -func validationOnlyAt(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, dialect Dialect, own, closure bool) (ir.Unmodeled, []ir.Provenance, []ir.Diagnostic) { +func validationOnlyAt(schema *statement.Schema, pointer jsontext.Pointer, doc provenance.Doc, dialect Dialect, role SchemaRole, typed Typed) (ir.Unmodeled, []ir.Provenance, KeptReports) { var unmodeled ir.Unmodeled var unpreserved []ir.Provenance - var diags []ir.Diagnostic + var reports KeptReports - // A keyword kept at its own node goes through PreserveValidationOnlyKeyword. + // A keyword kept at its own node goes through KeepValidationOnlyKeyword. // The entries combining several keywords into one object — if/then/else, // contains, unevaluated — go through keepCombinedValidationOnly, because no // single keyword names those. keepKeyword := func(keyword string) { - kept, kwDiags := PreserveValidationOnlyKeyword(&unmodeled, schema, keyword, pointer, doc) + kept, kwDiags := KeepValidationOnlyKeyword(&unmodeled, schema, keyword, pointer, doc) if !kept && len(kwDiags) > 0 { unpreserved = append(unpreserved, doc.At(pointer+ids.Ptr(keyword))) } - diags = append(diags, kwDiags...) + reports = append(reports, ReportsOf(EntryKey("", keyword), kwDiags...)...) } if schema.LogicKeywords().Not.SchemaValueForm() != statement.Unwritten { keepKeyword("not") } - if ite, iteKeys, iteErr := IfThenElseRaw(schema); ite != nil || iteErr != nil { - diags = append(diags, keepCombinedValidationOnly(&unmodeled, &unpreserved, pointer, doc, - "openapi:if-then-else", ite, iteErr, validationOnlyMessage("if/then/else"), iteKeys...)...) + ifThenElse, _ := combinedKeywords(ifThenElseLabel) + if ite, iteKeys, iteDropped, iteErr := combineKept(schema, RenderDroppingExtensions, ifThenElse...); ite != nil || iteErr != nil { + key := EntryKey("", ifThenElseLabel) + reports = append(reports, ReportsOf(key, DroppedExtensionDiags(doc.At(pointer), iteDropped)...)...) + reports = append(reports, keepCombinedValidationOnly(&unmodeled, &unpreserved, pointer, doc, + key, ite, iteErr, validationOnlyMessage("if/then/else"), iteKeys...)...) } // An empty dependency map is the keyword left out, and keeps nothing // (docs/compilers/openapi.md#validation-only). @@ -291,19 +328,79 @@ func validationOnlyAt(schema *statement.Schema, pointer jsontext.Pointer, doc pr if schema.ObjectKeywords().PropertyNames.SchemaValueForm() != statement.Unwritten { keepKeyword("propertyNames") } - if craw, cKeys, cErr := ContainsRaw(schema); craw != nil || cErr != nil { - diags = append(diags, keepCombinedValidationOnly(&unmodeled, &unpreserved, pointer, doc, - "openapi:contains", craw, cErr, validationOnlyMessage("contains"), cKeys...)...) + if craw, cKeys, cDropped, cErr := containsCombined(schema, RenderDroppingExtensions); craw != nil || cErr != nil { + key := EntryKey("", containsLabel) + reports = append(reports, ReportsOf(key, DroppedExtensionDiags(doc.At(pointer), cDropped)...)...) + reports = append(reports, keepCombinedValidationOnly(&unmodeled, &unpreserved, pointer, doc, + key, craw, cErr, validationOnlyMessage(containsLabel), cKeys...)...) + } + if role != PositionSchema { + return unmodeled, unpreserved, reports + } + kept := unevaluatedKept(schema, typed, dialect) + if unevaluated, uKeys, uDropped, uErr := unevaluatedRaw(schema, kept); unevaluated != nil || uErr != nil { + key := EntryKey("", unevaluatedLabel) + reports = append(reports, ReportsOf(key, DroppedExtensionDiags(doc.At(pointer), uDropped)...)...) + reports = append(reports, keepCombinedValidationOnly(&unmodeled, &unpreserved, pointer, doc, + key, unevaluated, uErr, unevaluatedNote(kept), uKeys...)...) } - if !own { - return unmodeled, unpreserved, diags + return unmodeled, unpreserved, reports +} + +// ValidationOnlyOf keeps what validationOnlyAt keeps of schema, written at +// pointer in dialect as the schema at a position, of the kept keywords the +// caller names: an entry several keywords combine into where it holds one of +// them (ValidationOnlyKeywordsOf), each reported as written beside an allOf. +// What it keeps no entry of, it reports nothing of. An unevaluated keyword on +// an entry is always unread, so none is dropped. +func ValidationOnlyOf(schema *statement.Schema, keptKeywords []string, pointer jsontext.Pointer, doc provenance.Doc, dialect Dialect, +) (ir.Unmodeled, []ir.Provenance, KeptReports) { + kept, unpreserved, reports := validationOnlyAt(schema, pointer, doc, dialect, PositionSchema, Typed{}) + for key := range kept { + if !slices.ContainsFunc(ValidationOnlyKeywordsOf(key), func(keyword string) bool { return slices.Contains(keptKeywords, keyword) }) { + delete(kept, key) + reports = slices.DeleteFunc(reports, func(report KeptReport) bool { return report.Key == key }) + } + } + return kept, unpreserved, reports +} + +// The labels the key of a validation-only entry several keywords combine into +// ends in, which combinedKeywords maps to those keywords. +const ( + ifThenElseLabel = "if-then-else" + containsLabel = "contains" + unevaluatedLabel = "unevaluated" +) + +// combinedKeywords returns the keywords the validation-only entry whose key +// ends in label holds, in the order its object writes them, and false for a +// label naming one keyword alone. +func combinedKeywords(label string) ([]string, bool) { + switch label { + case ifThenElseLabel: + return []string{"if", "then", "else"}, true + case containsLabel: + return []string{"contains", "minContains", "maxContains"}, true + case unevaluatedLabel: + return []string{"unevaluatedProperties", "unevaluatedItems"}, true + default: + return nil, false + } +} + +// ValidationOnlyKeywordsOf returns the keywords the validation-only entry under +// key holds: those it combines, else the one it is kept under, and none for a +// key naming no keyword (EntryKeyword). +func ValidationOnlyKeywordsOf(key string) []string { + label, named := EntryKeyword(key) + if !named { + return nil } - kept := unevaluatedKept(schema, closure, dialect) - if u, uKeys, uErr := unevaluatedRaw(schema, kept); u != nil || uErr != nil { - diags = append(diags, keepCombinedValidationOnly(&unmodeled, &unpreserved, pointer, doc, - "openapi:unevaluated", u, uErr, unevaluatedNote(kept), uKeys...)...) + if combined, ok := combinedKeywords(label); ok { + return combined } - return unmodeled, unpreserved, diags + return []string{label} } // keepCombinedValidationOnly takes the conversion's error alongside its payload @@ -311,12 +408,12 @@ func validationOnlyAt(schema *statement.Schema, pointer jsontext.Pointer, doc pr // an absent one — the two were indistinguishable here before GitHub #144. // // The entry is located at pointer and attributed by combined, the keywords it -// folds together, and so is the report that stands in for it when it cannot be +// folds together, and so is the report that takes the place of it when it cannot be // kept (with each failed keyword's provenance appended to unpreserved). note is // what the report of one kept says. func keepCombinedValidationOnly(unmodeled *ir.Unmodeled, unpreserved *[]ir.Provenance, pointer jsontext.Pointer, doc provenance.Doc, key string, raw ir.RawValue, err error, note string, combined ...string, -) []ir.Diagnostic { +) KeptReports { from := make([]jsontext.Pointer, 0, len(combined)) for _, keyword := range combined { from = append(from, pointer+ids.Ptr(keyword)) @@ -326,7 +423,7 @@ func keepCombinedValidationOnly(unmodeled *ir.Unmodeled, unpreserved *[]ir.Prove for _, at := range from { *unpreserved = append(*unpreserved, doc.At(at)) } - return []ir.Diagnostic{unpreservableDiag(key, entry, err)} + return ReportsOf(key, unpreservableDiag(key, entry, err)) } - return preserveValidationOnlyInto(unmodeled, key, raw, entry, doc.At(pointer), note) + return ReportsOf(key, keepValidationOnlyInto(unmodeled, key, raw, entry, doc.At(pointer), note)...) } diff --git a/compilers/openapi/internal/annotation/validationonly_internal_test.go b/compilers/openapi/internal/annotation/validationonly_internal_test.go index 8780f18ad..d2d5b462a 100644 --- a/compilers/openapi/internal/annotation/validationonly_internal_test.go +++ b/compilers/openapi/internal/annotation/validationonly_internal_test.go @@ -19,12 +19,12 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestCombinedRaw_JoinsOnlyWhatIsWritten pins the three combining readers. Each -// keyword present goes into one object in the requested order, and a +// TestCombinedRaw_CombinesOnlyWhatIsWritten pins the three combining readers. +// Each keyword present goes into one object in the requested order, and a // combination with nothing written yields nothing rather than an empty object. -// The keywords returned beside it are exactly the ones it holds, since those are -// what the entry's provenance is asked about (GitHub #534). -func TestCombinedRaw_JoinsOnlyWhatIsWritten(t *testing.T) { +// The keywords returned beside it are exactly the ones it holds, since those +// are what the entry's provenance is asked about (GitHub #534). +func TestCombinedRaw_CombinesOnlyWhatIsWritten(t *testing.T) { t.Parallel() tests := []struct { name string @@ -80,12 +80,12 @@ func TestCombinedRaw_JoinsOnlyWhatIsWritten(t *testing.T) { } } -// TestCombinedRaw_AnUnconvertibleMemberFailsTheWhole pins the rule presentMembers -// exists for: an object labelled verbatim that silently omits one of its -// keywords would restate GitHub #144 in miniature, so the combination errors -// instead. The error names the first member that failed, and every keyword -// written is still returned beside it, since the report that stands in for the -// entry is attributed by them (GitHub #534). +// TestCombinedRaw_AnUnconvertibleMemberFailsTheWhole pins the rule +// presentMembers exists for: an object labelled verbatim that silently omits +// one of its keywords would restate GitHub #144 in miniature, so the +// combination errors instead. The error names the first member that failed, and +// every keyword written is still returned beside it, since the report that +// takes the place of the entry is attributed by them (GitHub #534). func TestCombinedRaw_AnUnconvertibleMemberFailsTheWhole(t *testing.T) { t.Parallel() tests := []struct { @@ -111,7 +111,7 @@ func TestCombinedRaw_AnUnconvertibleMemberFailsTheWhole(t *testing.T) { failed: "unevaluatedItems", keys: []string{"unevaluatedProperties", "unevaluatedItems"}, }, { - name: "unevaluated, the keyword leaving it inert failing, which names only the unevaluated one", + name: "unevaluated, the keyword leaving it saying nothing failing, which names only the unevaluated one", read: unevaluatedClosed, body: "additionalProperties: {const: .nan}\nunevaluatedProperties: {type: string}\n", failed: "additionalProperties", keys: []string{"unevaluatedProperties"}, @@ -135,13 +135,13 @@ func TestCombinedRaw_AnUnconvertibleMemberFailsTheWhole(t *testing.T) { } } -// TestUnevaluatedRaw_KeepsAnInertKeywordBesideWhatLeavesItInert pins the +// TestUnevaluatedRaw_KeepsAKeywordSayingNothingBesideWhatLeavesItSo pins the // unevaluated entry's members: a keyword the keyword written beside it leaves // nothing to apply to is kept with that keyword, just before it, so the entry // read at its position means what the source means, and a live keyword is kept // alone. Only the unevaluated keywords are named, since the entry's provenance // asks after them alone. -func TestUnevaluatedRaw_KeepsAnInertKeywordBesideWhatLeavesItInert(t *testing.T) { +func TestUnevaluatedRaw_KeepsAKeywordSayingNothingBesideWhatLeavesItSo(t *testing.T) { t.Parallel() const ( upFalse = "unevaluatedProperties: false\n" @@ -186,7 +186,7 @@ func TestUnevaluatedRaw_KeepsAnInertKeywordBesideWhatLeavesItInert(t *testing.T) `{"items":{"type":"string"},"unevaluatedItems":false}`, []string{"unevaluatedItems"}}, {"a list of items no tuple in this dialect", "items: [{}]\nadditionalItems: {type: string}\n" + uiFalse, false, false, `{"unevaluatedItems":false}`, []string{"unevaluatedItems"}}, - {"both, one inert", "additionalProperties: true\n" + upFalse + uiFalse, false, false, + {"both, one saying nothing", "additionalProperties: true\n" + upFalse + uiFalse, false, false, `{"additionalProperties":true,"unevaluatedProperties":false,"unevaluatedItems":false}`, []string{"unevaluatedProperties", "unevaluatedItems"}}, {"a closure the node holds is left out", upFalse + uiFalse, true, false, @@ -197,19 +197,19 @@ func TestUnevaluatedRaw_KeepsAnInertKeywordBesideWhatLeavesItInert(t *testing.T) for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - s := schemaFromYAMLUnvalidated(t, tc.body) - got, keys, err := unevaluatedRaw(standaloneSchema(s), unevaluatedKept(standaloneSchema(s), tc.closure, Dialect{ListedTuple: tc.listed})) + schema := schemaFromYAMLUnvalidated(t, tc.body) + got, keys, _, err := unevaluatedRaw(standaloneSchema(schema), unevaluatedKept(standaloneSchema(schema), Typed{Closure: tc.closure}, Dialect{ListedTuple: tc.listed})) require.NoError(t, err) - assert.Equal(t, tc.want, string(got), "each inert keyword just after what leaves it inert") + assert.Equal(t, tc.want, string(got), "each keyword saying nothing just after what leaves it so") assert.Equal(t, tc.keys, keys) }) } } -// TestClosesAfterComposition_OnlyWhereNoAdditionalPropertiesStandsBeside pins +// TestClosesAfterComposition_OnlyWhereNoAdditionalPropertiesSitsBeside pins // the one definition of a live closure: `unevaluatedProperties: false` with no // additionalProperties written beside it, a null one being none. -func TestClosesAfterComposition_OnlyWhereNoAdditionalPropertiesStandsBeside(t *testing.T) { +func TestClosesAfterComposition_OnlyWhereNoAdditionalPropertiesSitsBeside(t *testing.T) { t.Parallel() for body, want := range map[string]bool{ "unevaluatedProperties: false\n": true, @@ -228,11 +228,11 @@ func TestClosesAfterComposition_OnlyWhereNoAdditionalPropertiesStandsBeside(t *t } } -// TestValidationOnlyAt_AnInertUnevaluatedKeywordNamesWhatLeavesItInert pins the -// entry's report: one per entry, its wording naming each inert keyword and its sibling, -// and ending as every validation-only report does where the entry holds -// anything else. -func TestValidationOnlyAt_AnInertUnevaluatedKeywordNamesWhatLeavesItInert(t *testing.T) { +// TestValidationOnlyAt_AnUnevaluatedKeywordSayingNothingNamesWhatLeavesItSo pins the +// entry's report: one per entry, its wording naming each keyword saying nothing +// and its sibling, and ending as every validation-only report does where the +// entry holds anything else. +func TestValidationOnlyAt_AnUnevaluatedKeywordSayingNothingNamesWhatLeavesItSo(t *testing.T) { t.Parallel() const ( properties = "unevaluatedProperties beside additionalProperties applies to no property, " + @@ -250,24 +250,26 @@ func TestValidationOnlyAt_AnInertUnevaluatedKeywordNamesWhatLeavesItInert(t *tes "unevaluatedProperties: false\nitems: true\nunevaluatedItems: false\n": items + "; " + plain, "additionalProperties: {}\nunevaluatedProperties: {}\nitems: {}\nunevaluatedItems: {}\n": properties + "; " + items + "; " + plain, } { - got, _, diags := validationOnlyAt(standaloneSchema(schemaFromYAML(t, body)), "/S", sourced(0), Dialect{}, true, false) + got, _, diagsReports := validationOnlyAt(standaloneSchema(schemaFromYAML(t, body)), "/S", sourced(0), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() require.Contains(t, got, "openapi:unevaluated", "%s", body) // contains is an entry of its own, reported first. diags = slices.DeleteFunc(diags, func(diagnostic ir.Diagnostic) bool { return strings.Contains(diagnostic.Message, `"contains"`) }) require.Len(t, diags, 1, "one report for the one entry: %s", body) assert.Equal(t, diag.ValidationOnlyKeyword, diags[0].Code) - assert.Equal(t, ir.SeverityInfo, diags[0].Severity, "an inert keyword is valid JSON Schema") + assert.Equal(t, ir.SeverityInfo, diags[0].Severity, "a keyword saying nothing is valid JSON Schema") assert.Equal(t, want, diags[0].Message, "%s", body) } } -// TestValidationOnlyAt_AttributesAnInertEntryByItsUnevaluatedKeyword pins the -// entry's provenance once it holds the keyword leaving one inert: that keyword -// is context the entry holds whoever wrote it, so an overlay is the entry's -// writer where it wrote the unevaluated keyword, whoever wrote the other. -func TestValidationOnlyAt_AttributesAnInertEntryByItsUnevaluatedKeyword(t *testing.T) { +// TestValidationOnlyAt_AttributesAnEntrySayingNothingByItsUnevaluatedKeyword pins the +// entry's provenance once it holds the keyword leaving one saying nothing: that +// keyword is context the entry holds whoever wrote it, so an overlay is the +// entry's writer where it wrote the unevaluated keyword, whoever wrote the +// other. +func TestValidationOnlyAt_AttributesAnEntrySayingNothingByItsUnevaluatedKeyword(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "additionalProperties: true\nunevaluatedProperties: false\n") + schema := schemaFromYAML(t, "additionalProperties: true\nunevaluatedProperties: false\n") for name, tc := range map[string]struct { wrote []jsontext.Pointer want int @@ -276,7 +278,7 @@ func TestValidationOnlyAt_AttributesAnInertEntryByItsUnevaluatedKeyword(t *testi "the unevaluated keyword": {[]jsontext.Pointer{"/S/unevaluatedProperties"}, 1}, "the other": {[]jsontext.Pointer{"/S/additionalProperties"}, 0}, } { - got, _, _ := validationOnlyAt(standaloneSchema(s), "/S", overlaid(tc.wrote...), Dialect{}, true, false) + got, _, _ := validationOnlyAt(standaloneSchema(schema), "/S", overlaid(tc.wrote...), Dialect{}, PositionSchema, Typed{}) require.Contains(t, got, "openapi:unevaluated", name) assert.Equal(t, ir.Provenance{Pointer: "/S", WrittenBy: tc.want}, got["openapi:unevaluated"].Provenance, name) } @@ -285,7 +287,8 @@ func TestValidationOnlyAt_AttributesAnInertEntryByItsUnevaluatedKeyword(t *testi // unevaluatedClosed is unevaluatedRaw for a 2020-12 schema whose node holds a // false unevaluatedProperties as its closure, as a combining reader takes one. func unevaluatedClosed(schema *statement.Schema) (ir.RawValue, []string, error) { - return unevaluatedRaw(schema, unevaluatedKept(schema, true, Dialect{})) + raw, keys, _, err := unevaluatedRaw(schema, unevaluatedKept(schema, Typed{Closure: true}, Dialect{})) + return raw, keys, err } // TestJSONObject_PropagatesAQuoteFailure covers jsonObject's one failure mode: @@ -304,14 +307,14 @@ func TestJSONObject_PropagatesAQuoteFailure(t *testing.T) { assert.Contains(t, err.Error(), "invalid UTF-8") } -// TestValidationOnlyAt_KeepsEveryKeywordItClaims pins the validation-only +// TestValidationOnlyAt_KeepsEveryKeywordOfTheFamily pins the validation-only // family as a set. A keyword missing from this list is one the IR neither -// models nor keeps, which is the silent-drop class of defect the family exists -// to prevent. Each entry is announced once, by the name it was kept under, -// whichever keeper kept it. -func TestValidationOnlyAt_KeepsEveryKeywordItClaims(t *testing.T) { +// models nor keeps, which is the unreported-drop class of defect the family +// exists to prevent. Each entry is announced once, by the name it was kept +// under, whichever conjunct kept it. +func TestValidationOnlyAt_KeepsEveryKeywordOfTheFamily(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\n"+ + schema := schemaFromYAML(t, "type: object\n"+ "not: {type: string}\n"+ "if: {type: object}\nthen: {required: [a]}\n"+ "dependentSchemas: {a: {required: [b]}}\n"+ @@ -320,7 +323,8 @@ func TestValidationOnlyAt_KeepsEveryKeywordItClaims(t *testing.T) { "contains: {type: string}\nminContains: 1\n"+ "unevaluatedProperties: {type: string}\n") - got, _, diags := validationOnlyAt(standaloneSchema(s), "/components/schemas/S", sourced(0), Dialect{}, true, false) + got, _, diagsReports := validationOnlyAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() for _, key := range []string{ "openapi:not", "openapi:if-then-else", "openapi:dependentSchemas", @@ -353,15 +357,16 @@ func TestValidationOnlyAt_KeepsEveryKeywordItClaims(t *testing.T) { // schema's dialect defines it, and left to the unknown keywords otherwise. func TestValidationOnlyAt_KeepsADraftsDependenciesWhereItsDialectDefinesThem(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\ndependencies: {a: [b], c: {required: [d]}}\n") - got, _, diags := validationOnlyAt(standaloneSchema(s), "/components/schemas/S", sourced(0), Dialect{Dependencies: true}, true, false) + schema := schemaFromYAML(t, "type: object\ndependencies: {a: [b], c: {required: [d]}}\n") + got, _, diagsReports := validationOnlyAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), Dialect{Dependencies: true}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() require.Contains(t, got, "openapi:dependencies") assert.Equal(t, ir.ReasonValidationOnly, got["openapi:dependencies"].Reason) require.Len(t, diags, 1) assert.Equal(t, `validation-only keyword "dependencies" kept verbatim under Unmodeled`, diags[0].Message) - got, _, diags = validationOnlyAt(standaloneSchema(s), "/components/schemas/S", sourced(0), Dialect{}, true, false) + got, _, diagsReports = validationOnlyAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), Dialect{}, PositionSchema, Typed{}) assert.Empty(t, got) - assert.Empty(t, diags) + assert.Empty(t, diagsReports) } // TestValidationOnlyAt_AnUnconvertibleKeywordIsReportedNotKept pins the error @@ -369,9 +374,10 @@ func TestValidationOnlyAt_KeepsADraftsDependenciesWhereItsDialectDefinesThem(t * // and no entry, rather than an entry announcing a preservation that failed. func TestValidationOnlyAt_AnUnconvertibleKeywordIsReportedNotKept(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\nnot: {const: .nan}\ncontains: {const: .nan}\n") + schema := schemaFromYAML(t, "type: object\nnot: {const: .nan}\ncontains: {const: .nan}\n") - got, unpreserved, diags := validationOnlyAt(standaloneSchema(s), "/components/schemas/S", sourced(0), Dialect{}, true, false) + got, unpreserved, diagsReports := validationOnlyAt(standaloneSchema(schema), "/components/schemas/S", sourced(0), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() assert.NotContains(t, got, "openapi:not") assert.NotContains(t, got, "openapi:contains") @@ -393,9 +399,10 @@ func TestValidationOnlyAt_AnUnconvertibleKeywordIsReportedNotKept(t *testing.T) // keyword's own text. func TestValidationOnlyAt_AttributesTheEntryAtItsKeyword(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\nnot: {type: integer}\n") + schema := schemaFromYAML(t, "type: object\nnot: {type: integer}\n") - got, _, diags := validationOnlyAt(standaloneSchema(s), "/components/schemas/S", overlaid("/components/schemas/S/not"), Dialect{}, true, false) + got, _, diagsReports := validationOnlyAt(standaloneSchema(schema), "/components/schemas/S", overlaid("/components/schemas/S/not"), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() entry, ok := got["openapi:not"] require.True(t, ok) @@ -413,9 +420,10 @@ func TestValidationOnlyAt_AttributesTheEntryAtItsKeyword(t *testing.T) { // at the keyword, so it names the overlay. func TestValidationOnlyAt_AttributesAnUnconvertibleKeywordAtItsPointer(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\nnot: {const: .nan}\n") + schema := schemaFromYAML(t, "type: object\nnot: {const: .nan}\n") - got, unpreserved, diags := validationOnlyAt(standaloneSchema(s), "/components/schemas/S", overlaid("/components/schemas/S/not"), Dialect{}, true, false) + got, unpreserved, diagsReports := validationOnlyAt(standaloneSchema(schema), "/components/schemas/S", overlaid("/components/schemas/S/not"), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() assert.NotContains(t, got, "openapi:not", "a keyword that will not render is not kept") assert.Equal(t, []ir.Provenance{{Pointer: "/components/schemas/S/not", WrittenBy: 1}}, unpreserved) @@ -436,7 +444,7 @@ func TestValidationOnlyAt_AttributesAnUnconvertibleKeywordAtItsPointer(t *testin // names the wrong writer in some row. func TestValidationOnlyAt_AttributesACombinedEntryByItsKeywords(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\n"+ + schema := schemaFromYAML(t, "type: object\n"+ "not: {type: integer}\n"+ "if: {required: [name]}\nthen: {required: [tag]}\n"+ "contains: {type: string}\nminContains: 1\n"+ @@ -452,7 +460,8 @@ func TestValidationOnlyAt_AttributesACombinedEntryByItsKeywords(t *testing.T) { "if, contains and unevaluatedItems": {[]jsontext.Pointer{"/S/if", "/S/contains", "/S/unevaluatedItems"}, 0, 0, 1}, "then and minContains": {[]jsontext.Pointer{"/S/then", "/S/minContains"}, 0, 0, 0}, } { - got, _, diags := validationOnlyAt(standaloneSchema(s), "/S", overlaid(tc.wrote...), Dialect{}, true, true) + got, _, diagsReports := validationOnlyAt(standaloneSchema(schema), "/S", overlaid(tc.wrote...), Dialect{}, PositionSchema, Typed{Closure: true}) + diags := diagsReports.Diagnostics() for key, want := range map[string]ir.Provenance{ "openapi:not": {Source: 0, Pointer: "/S/not"}, @@ -479,7 +488,7 @@ func TestValidationOnlyAt_AttributesACombinedEntryByItsKeywords(t *testing.T) { // rows split the keywords as that test's do. func TestValidationOnlyAt_AttributesAnUnkeptCombinedEntryByItsKeywords(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\n"+ + schema := schemaFromYAML(t, "type: object\n"+ "if: {required: [name]}\nthen: {const: .nan}\n"+ "contains: {const: .nan}\nminContains: 1\n") for name, tc := range map[string]struct { @@ -490,7 +499,8 @@ func TestValidationOnlyAt_AttributesAnUnkeptCombinedEntryByItsKeywords(t *testin "if and contains": {[]jsontext.Pointer{"/S/if", "/S/contains"}, 0}, "then and minContains": {[]jsontext.Pointer{"/S/then", "/S/minContains"}, 0}, } { - got, _, diags := validationOnlyAt(standaloneSchema(s), "/S", overlaid(tc.wrote...), Dialect{}, true, false) + got, _, diagsReports := validationOnlyAt(standaloneSchema(schema), "/S", overlaid(tc.wrote...), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() assert.Empty(t, got, "%s: an entry that will not render is not kept", name) require.Len(t, diags, 2, name) @@ -511,21 +521,23 @@ func TestValidationOnlyAt_NeedsTheRawNode(t *testing.T) { t.Parallel() built := &oas3.Schema{Not: oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{})} - got, _, diags := validationOnlyAt(standaloneSchema(built), "/p", sourced(0), Dialect{}, true, false) + got, _, diagsReports := validationOnlyAt(standaloneSchema(built), "/p", sourced(0), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() assert.Nil(t, got, "no raw bytes to keep, so nothing is kept") assert.Empty(t, diags, "and nothing is announced for a keyword that was not kept") } -// TestValidationOnlyAt_DependentRequiredJoinsItsSiblings pins the keyword the -// validation-only family was missing. dependentRequired is pure validation +// TestValidationOnlyAt_DependentRequiredCombinesItsSiblings pins the keyword +// the validation-only family was missing. dependentRequired is pure validation // logic exactly as dependentSchemas is, and oas3.Schema has no field for it, // which is the whole reason it was dropped where its sibling was kept. -func TestValidationOnlyAt_DependentRequiredJoinsItsSiblings(t *testing.T) { +func TestValidationOnlyAt_DependentRequiredCombinesItsSiblings(t *testing.T) { t.Parallel() - s := schemaFromYAML(t, "type: object\ndependentRequired:\n a: [b]\n") + schema := schemaFromYAML(t, "type: object\ndependentRequired:\n a: [b]\n") - got, _, diags := validationOnlyAt(standaloneSchema(s), "/components/schemas/S", sourced(7), Dialect{}, true, false) + got, _, diagsReports := validationOnlyAt(standaloneSchema(schema), "/components/schemas/S", sourced(7), Dialect{}, PositionSchema, Typed{}) + diags := diagsReports.Diagnostics() entry, ok := got["openapi:dependentRequired"] require.True(t, ok, "dependentRequired must be kept verbatim") diff --git a/compilers/openapi/internal/auth/flows.go b/compilers/openapi/internal/auth/flows.go index 0fc01f940..ceee530d3 100644 --- a/compilers/openapi/internal/auth/flows.go +++ b/compilers/openapi/internal/auth/flows.go @@ -62,7 +62,7 @@ func oauthFlows(flows *soa.OAuthFlows) []ir.OAuthFlow { } // oauthFlow lowers one OAuth2 flow, reading only the fields of flowFields its -// kind defines; preserveUndefinedFlowFields keeps the rest. The device flow's +// kind defines; keepUndefinedFlowFields keeps the rest. The device flow's // deviceAuthorizationUrl rides OAuthFlow.AuthorizationURL (docs/ir/auth.md). func oauthFlow(sourceFlowValue sourceFlow) ir.OAuthFlow { fl := ir.OAuthFlow{ @@ -142,7 +142,7 @@ func tokenless(scheme ir.AuthScheme) bool { // flowsMissing reports whether ss writes no flows object: flows absent, null, // or a value that is no mapping, which the parser models as no object. The rule // table reports each, as a REQUIRED field missing or a value of the wrong type, -// wherever the scheme is written (GitHub #872), so the lowering stands aside. A +// wherever the scheme is written (GitHub #872), so the lowering steps aside. A // mapping lowering no flow, one whose only flow is null included, is the // lowering's to report. func flowsMissing(ss *soa.SecurityScheme) bool { @@ -175,7 +175,7 @@ func applyFlowAnnotations(serviceContext service.Ctx, lowered []ir.OAuthFlow, fl ext, extDiags := annotation.ExtensionsFrom(sourceFlow.src.GetExtensions(), serviceContext.Place(), fptr) lowered[i].Unmodeled = annotation.MergeUnmodeled(lowered[i].Unmodeled, ext) diags = append(diags, extDiags...) - diags = append(diags, preserveUndefinedFlowFields(serviceContext, &lowered[i], sourceFlow, fptr)...) + diags = append(diags, keepUndefinedFlowFields(serviceContext, &lowered[i], sourceFlow, fptr)...) diags = append(diags, annotation.UnknownKeysIn(&lowered[i].Unmodeled, sourceFlow.src, serviceContext.Place(), fptr)...) methods, promoted := promotion.TokenEndpointAuthMethods(serviceContext.Promoter(), lowered[i].Unmodeled, &lowered[i].Inferred) lowered[i].TokenEndpointAuthMethods = methods @@ -184,16 +184,16 @@ func applyFlowAnnotations(serviceContext service.Ctx, lowered []ir.OAuthFlow, fl return diags } -// preserveUndefinedFlowFields keeps each field of flowFields the flow wrote but +// keepUndefinedFlowFields keeps each field of flowFields the flow wrote but // its kind does not define verbatim under the flow's Unmodeled (GitHub #865), -// as preserveUnreadFields does for a scheme. oauthFlow lowered none of them, so +// as keepUnreadFields does for a scheme. oauthFlow lowered none of them, so // without this they would be lost: the parser models every field on every flow, // and the unknown-key census never sees one. // // It reads the flow's mapping as the parser does, as every preservation site // does, so a field merged in through a `<<` key is kept as a written one is // (GitHub #384). -func preserveUndefinedFlowFields(serviceContext service.Ctx, fl *ir.OAuthFlow, sourceFlowValue sourceFlow, fptr jsontext.Pointer) []ir.Diagnostic { +func keepUndefinedFlowFields(serviceContext service.Ctx, fl *ir.OAuthFlow, sourceFlowValue sourceFlow, fptr jsontext.Pointer) []ir.Diagnostic { defined := flowFieldsDefinedBy(sourceFlowValue.keyword) var diags []ir.Diagnostic for _, field := range flowFields() { @@ -201,7 +201,7 @@ func preserveUndefinedFlowFields(serviceContext service.Ctx, fl *ir.OAuthFlow, s continue } at := fptr + ids.Ptr(field.name) - kept, keptDiags := annotation.PreserveNodeInto(&fl.Unmodeled, "openapi:"+field.name, + kept, keptDiags := annotation.KeepNodeInto(&fl.Unmodeled, "openapi:"+field.name, nodeview.Child(sourceFlowValue.src.GetRootNode(), field.name), ir.ReasonDegradedLowering, serviceContext.Place().At(at)) diags = append(diags, keptDiags...) if !kept { diff --git a/compilers/openapi/internal/auth/flows_test.go b/compilers/openapi/internal/auth/flows_test.go index c29771233..f4490ba08 100644 --- a/compilers/openapi/internal/auth/flows_test.go +++ b/compilers/openapi/internal/auth/flows_test.go @@ -205,7 +205,7 @@ components: // the loader's report of a missing `flows` is placed when the declaration is // reached through aliases first (GitHub #803): once, at the target, with the // position of its text, and never at an alias, which holds no flows either way. -// The lowering stands aside, so no no-flow warning appears anywhere. +// The lowering steps aside, so no no-flow warning appears anywhere. func TestLowerSecuritySchemes_AnAbsentFlowsIsReportedAtTheDeclaration(t *testing.T) { t.Parallel() doc, _, diags := serviceSpec(t, `openapi: 3.1.0 diff --git a/compilers/openapi/internal/auth/requirements_test.go b/compilers/openapi/internal/auth/requirements_test.go index 2e15b77e7..068b78753 100644 --- a/compilers/openapi/internal/auth/requirements_test.go +++ b/compilers/openapi/internal/auth/requirements_test.go @@ -108,12 +108,12 @@ components: } } -// TestSecurityRequirement_AScalarTheModelDoesNotDecodeIsAScope pins that a scope -// is the text a list writes. A plain date, which the load phase tags a string, -// is a scope. A list holding an item under a tag outside YAML's JSON schema -// ruleset, which the model decodes nothing of +// TestSecurityRequirement_AScalarTheModelDoesNotDecodeIsAScope pins that a +// scope is the text a list writes. A plain date, which the load phase tags a +// string, is a scope. A list holding an item under a tag outside YAML's JSON +// schema ruleset, which the model decodes nothing of // (docs/parser-library.md#undecoded-scalar), is the rule table's error, and is -// read as left out: the name stands, listing no scopes. +// read as left out: the name remains, listing no scopes. func TestSecurityRequirement_AScalarTheModelDoesNotDecodeIsAScope(t *testing.T) { t.Parallel() for written, want := range map[string][]string{ @@ -187,7 +187,7 @@ components: securitySchemes: ghost: {$ref: '#/components/securitySchemes/Missing'} `) - require.Len(t, svc.Auth, 1, "the requirement stands, though the scheme it names resolves to nothing") + require.Len(t, svc.Auth, 1, "the requirement remains, though the scheme it names resolves to nothing") assert.Equal(t, []ir.AuthID{ids.UnresolvedAuth("ghost")}, schemeUses(svc.Auth[0])) entry := messagesAtPointer(diags, "/components/securitySchemes/ghost") @@ -214,7 +214,7 @@ security: - missing: [] paths: {} `) - require.Len(t, svc.Auth, 1, "the list stands") + require.Len(t, svc.Auth, 1, "the list remains") assert.Equal(t, []ir.AuthID{ids.UnresolvedAuth("missing")}, schemeUses(svc.Auth[0])) assert.Len(t, doc.Auth, 1, "the name is the one scheme the document holds") @@ -729,8 +729,8 @@ func TestSecurityRequirements_AnEmptyListIsNotAnAbsentOne(t *testing.T) { // option would pass the malformed rows while deleting that encoding. // // Each malformed row pins that the loader's report survives, since the drop is -// otherwise silent. The aliased rows catch a drop that tests the entry's node -// kind, which would lose the `{}` reached through an alias. +// otherwise unreported. The aliased rows catch a drop that tests the entry's +// node kind, which would lose the `{}` reached through an alias. func TestSecurityRequirement_ANonObjectEntryIsNotTheEmptyOption(t *testing.T) { t.Parallel() cases := []struct { @@ -999,7 +999,7 @@ func TestSecurityRequirement_AMergeNamingNoMappingIsNoOption(t *testing.T) { {`{<<: {}}`, empty, ""}, {`{<<: &empty {}}`, empty, ""}, {`{<<: *e}`, empty, ""}, {`{<<: []}`, empty, ""}, {`{<<: 5, key: []}`, []ir.AuthRequirement{key, key}, ""}, // JSON has no merge key: the quoted key is a name, which reaches no - // scheme, and the option stands. + // scheme, and the option remains. {`{"<<": 5}`, []ir.AuthRequirement{key, {Schemes: []ir.SchemeUse{{Scheme: ids.UnresolvedAuth("<<")}}}}, ""}, } for _, tc := range cases { diff --git a/compilers/openapi/internal/auth/schemes.go b/compilers/openapi/internal/auth/schemes.go index f6efbf46f..358067a68 100644 --- a/compilers/openapi/internal/auth/schemes.go +++ b/compilers/openapi/internal/auth/schemes.go @@ -79,7 +79,7 @@ func unresolvableScheme(serviceContext service.Ctx, name string, rs *soa.Referen return scheme, nil } scheme.Docs = docsBeside(rs) - _, keptDiags := annotation.PreserveNodeInto(&scheme.Unmodeled, "openapi:$ref", rs.GetCore().Reference.ValueNode, + _, keptDiags := annotation.KeepNodeInto(&scheme.Unmodeled, "openapi:$ref", rs.GetCore().Reference.ValueNode, ir.ReasonDegradedLowering, serviceContext.Place().At(entry+ids.Ptr("$ref"))) return scheme, keptDiags } @@ -129,9 +129,9 @@ func lowerSecurityScheme(serviceContext, dc service.Ctx, name string, ss *soa.Se // Reported rather than refused; see oauthNoFlowDiag. diags = append(diags, oauthNoFlowDiag(dc, decl)) } - diags = append(diags, preserveUnreadFields(dc, &scheme, ss, decl)...) + diags = append(diags, keepUnreadFields(dc, &scheme, ss, decl)...) diags = append(diags, applySchemeAnnotations(dc, &scheme, ss, decl)...) - // Distinct from preserveUnreadFields above it: that keeps the fields OpenAPI + // Distinct from keepUnreadFields above it: that keeps the fields OpenAPI // defines for a securityScheme which this entry's own mechanism gives no // meaning to, while this keeps the keys OpenAPI defines for no securityScheme // at all. @@ -149,7 +149,7 @@ func lowerSecurityScheme(serviceContext, dc service.Ctx, name string, ss *soa.Se // at all, so its entries are kept on the scheme under the keyword. // // Only oauth2 reads inside `flows`: on any other type the whole node is kept -// verbatim by preserveUnreadFields, extensions and all, and no ir.OAuthFlow was +// verbatim by keepUnreadFields, extensions and all, and no ir.OAuthFlow was // lowered for a flow's own to land on. func applySchemeAnnotations(serviceContext service.Ctx, scheme *ir.AuthScheme, ss *soa.SecurityScheme, decl jsontext.Pointer) []ir.Diagnostic { ext, diags := annotation.ExtensionsFrom(ss.GetExtensions(), serviceContext.Place(), decl) @@ -172,9 +172,9 @@ func applySchemeAnnotations(serviceContext service.Ctx, scheme *ir.AuthScheme, s // Custom is no home for it: AuthKindCustom means a mechanism the IR does not // model, and an entry naming none would assert that the API is authenticated by // nothing in particular, which no emitter can implement (#294). So it takes the -// kind that says the compiler holds no mechanism, with what it wrote kept beside -// that, and a requirement naming it stands. An error: what the entry means is -// missing, and OpenAPI requires both fields. +// kind that says the compiler holds no mechanism, with what it wrote kept +// beside that, and a requirement naming it remains. An error: what the entry +// means is missing, and OpenAPI requires both fields. func noMechanismDiag(serviceContext service.Ctx, name, missing string, entry jsontext.Pointer) ir.Diagnostic { // "has no", not "declares no": a $ref entry declares only the reference, yet // alias and target are each reported at their own entry, so the wording must @@ -246,7 +246,7 @@ func fillHTTPScheme(scheme *ir.AuthScheme, ss *soa.SecurityScheme) (missing stri } // mechanismFieldNames are the securityScheme fields only some types define, -// sorted — which is both the order preserveUnreadFields walks them in and what +// sorted — which is both the order keepUnreadFields walks them in and what // makes the list comparable to the source model it must keep pace with. // // type, description, deprecated and the x-* extensions are absent because every @@ -283,7 +283,7 @@ func fieldsDefinedBy(t soa.SecuritySchemaType) []string { } } -// preserveUnreadFields keeps verbatim under Unmodeled every mechanism field the +// keepUnreadFields keeps verbatim under Unmodeled every mechanism field the // entry declared that its own type gives no meaning to (#294). An entry naming no // mechanism keeps all of them, with its type, which no kind can say. // @@ -293,7 +293,7 @@ func fieldsDefinedBy(t soa.SecuritySchemaType) []string { // nothing; an explicit `in: ""` is recorded as written. // // decl is where the fields are written, the declaration for a $ref entry (#107). -func preserveUnreadFields(serviceContext service.Ctx, scheme *ir.AuthScheme, ss *soa.SecurityScheme, +func keepUnreadFields(serviceContext service.Ctx, scheme *ir.AuthScheme, ss *soa.SecurityScheme, decl jsontext.Pointer, ) []ir.Diagnostic { unresolved := scheme.Kind == ir.AuthKindUnresolved @@ -307,7 +307,7 @@ func preserveUnreadFields(serviceContext service.Ctx, scheme *ir.AuthScheme, ss continue } at := decl + ids.Ptr(field) - kept, keptDiags := annotation.PreserveNodeInto(&scheme.Unmodeled, "openapi:"+field, + kept, keptDiags := annotation.KeepNodeInto(&scheme.Unmodeled, "openapi:"+field, nodeview.Child(ss.GetRootNode(), field), ir.ReasonDegradedLowering, serviceContext.Place().At(at)) diags = append(diags, keptDiags...) if !kept { diff --git a/compilers/openapi/internal/auth/schemes_test.go b/compilers/openapi/internal/auth/schemes_test.go index af467cf8b..b703a477d 100644 --- a/compilers/openapi/internal/auth/schemes_test.go +++ b/compilers/openapi/internal/auth/schemes_test.go @@ -210,9 +210,9 @@ components: } // TestLowerSecuritySchemes_ARequirementNamingAnEntryWithNoMechanismKeepsIt pins -// the downstream half: the requirement stands, naming the scheme the entry -// lowered to rather than one minted over it, and is reported like any other that -// resolved to no mechanism. +// the downstream half: the requirement remains, naming the scheme the entry +// lowered to rather than one minted over it, and is reported like any other +// that resolved to no mechanism. func TestLowerSecuritySchemes_ARequirementNamingAnEntryWithNoMechanismKeepsIt(t *testing.T) { t.Parallel() doc, svc, diags := serviceSpec(t, `openapi: 3.1.0 @@ -359,7 +359,7 @@ components: } // TestLowerSecuritySchemes_ABrokenRefKeepsTheDocsBesideIt pins that the text a -// Reference Object writes survives the $ref it stands beside (GitHub #610), +// Reference Object writes survives the $ref it sits beside (GitHub #610), // whichever way that string $ref failed: where the model could not read it, // the model holds neither field (docs/parser-library.md#undecoded-scalar). A // $ref that is no string names nothing, and the entry is read as left out. @@ -607,7 +607,7 @@ components: // writers of a scheme's Unmodeled map do not overwrite each other. The x-* // extensions used to be the only one and were assigned over the whole map, so a // preserved field written before them would vanish without trace — the same -// silent drop this all exists to close, one layer up. +// unreported drop this all exists to close, one layer up. func TestLowerSecuritySchemes_KeptFieldsAndExtensionsShareOneMap(t *testing.T) { t.Parallel() doc, _, _ := serviceSpec(t, `openapi: 3.1.0 @@ -687,11 +687,11 @@ components: } // TestLowerSecuritySchemes_AnUnkeepableFieldIsReportedNotDropped pins the third -// outcome of keeping a field: one whose value JSON cannot hold reaches the IR in -// no form at all, so it is reported as the losslessness failure it is rather +// outcome of keeping a field: one whose value JSON cannot hold reaches the IR +// in no form at all, so it is reported as the losslessness failure it is rather // than announced as kept (GitHub #144). `.nan` is such a value, and a scheme // declaring it is enough to reach this: the loader parses the entry, warns that -// a number stands where a string belongs, and hands it here intact. +// a number sits where a string belongs, and hands it here intact. func TestLowerSecuritySchemes_AnUnkeepableFieldIsReportedNotDropped(t *testing.T) { t.Parallel() doc, _, diags := serviceSpec(t, `openapi: 3.1.0 diff --git a/compilers/openapi/internal/canary/decoding_test.go b/compilers/openapi/internal/canary/decoding_test.go index 17e0425b9..e131ee57e 100644 --- a/compilers/openapi/internal/canary/decoding_test.go +++ b/compilers/openapi/internal/canary/decoding_test.go @@ -695,7 +695,7 @@ func mergeKeyPredicate(t *testing.T) { } // mergeKeySpellings decodes a `<<` written four ways: a quoted `<<` and an -// alias standing for one name a property, and a plain one and a `!!merge` +// alias naming one name a property, and a plain one and a `!!merge` // tagged one merge their source. It skips validation, which reports a quoted // `<<` key's schema, so the properties are read as decoded. func mergeKeySpellings(t *testing.T) { diff --git a/compilers/openapi/internal/canary/json_test.go b/compilers/openapi/internal/canary/json_test.go index a93c31e7b..5ecaf6364 100644 --- a/compilers/openapi/internal/canary/json_test.go +++ b/compilers/openapi/internal/canary/json_test.go @@ -25,7 +25,7 @@ func jsonWith(text, path string) string { func u(hex string) string { return `\u` + hex } // jsonAsYAML pins json-as-yaml: the YAML parser refuses a JSON text that writes -// a surrogate pair, a solidus escape, a key whose colon stands more than 1,024 +// a surrogate pair, a solidus escape, a key whose colon sits more than 1,024 // characters past its start, a raw DEL, U+FFFE, U+FFFF or a C1 control other // than U+0085, or a tab before the root or on a line after the one it ends on, // with a message that names no position of the escape, and reads a raw NEL as diff --git a/compilers/openapi/internal/canary/oracle_test.go b/compilers/openapi/internal/canary/oracle_test.go index ba12cc30c..f96b57c45 100644 --- a/compilers/openapi/internal/canary/oracle_test.go +++ b/compilers/openapi/internal/canary/oracle_test.go @@ -229,7 +229,7 @@ func binderAnswers(t *testing.T, spec string) (map[jsontext.Pointer]string, bool // table reads as the $ref it spells is no $ref the library reads. func sourceChains(table *reftable.ReferenceTargetTable) map[jsontext.Pointer]reftable.Chain { out := map[jsontext.Pointer]reftable.Chain{} - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { if referenceSite.Site.Doc == reftable.Source && referenceSite.Keyword == "$ref" { out[referenceSite.Site.Pointer] = referenceSite.Chain } diff --git a/compilers/openapi/internal/canary/record_test.go b/compilers/openapi/internal/canary/record_test.go index 7b558b4ce..da48d931d 100644 --- a/compilers/openapi/internal/canary/record_test.go +++ b/compilers/openapi/internal/canary/record_test.go @@ -265,7 +265,7 @@ func citesEntry(text, key string) bool { return false } -// importPath returns the import path a symbol's package name stands for: the +// importPath returns the import path a symbol's package name names: the // compiler itself, or one of its internal packages. func importPath(pkg string) string { if pkg == "openapi" { diff --git a/compilers/openapi/internal/canary/testdata/validation_disagreements.txt b/compilers/openapi/internal/canary/testdata/validation_disagreements.txt index b31460302..4b9c222f2 100644 --- a/compilers/openapi/internal/canary/testdata/validation_disagreements.txt +++ b/compilers/openapi/internal/canary/testdata/validation_disagreements.txt @@ -180,7 +180,7 @@ compilers/openapi/internal/canary/testdata/validation/L04-unknown-key_info.bogus compilers/openapi/internal/canary/testdata/validation/L05-unknown-key_operation.bogus__3.1.0.yaml 5:37 unknown-object-key compiler undefined-key compilers/openapi/internal/canary/testdata/validation/L06-unknown-key_top-level.bogus__3.1.0.yaml 3:8 unknown-object-key compiler undefined-key testdata/conformance/openapi/allof-refinement.yaml 46:26 validation-no-effect compiler nullable-type -testdata/conformance/openapi/allof-refinement.yaml 122:19 later-version-construct compiler version-gate +testdata/conformance/openapi/allof-refinement.yaml 123:19 later-version-construct compiler version-gate testdata/conformance/openapi/codeclared-schema-content.yaml 17:11 validation-mutually-exclusive-fields compiler library-silent testdata/conformance/openapi/codeclared-schema-content.yaml 25:11 validation-mutually-exclusive-fields compiler library-silent testdata/conformance/openapi/codeclared-schema-content.yaml 35:15 validation-mutually-exclusive-fields compiler library-silent diff --git a/compilers/openapi/internal/compileddoc/compileddoc.go b/compilers/openapi/internal/compileddoc/compileddoc.go index be8117c58..6a5755405 100644 --- a/compilers/openapi/internal/compileddoc/compileddoc.go +++ b/compilers/openapi/internal/compileddoc/compileddoc.go @@ -9,11 +9,6 @@ import ( "github.com/dexpace/morphic/ir" ) -// MaxAliasHops bounds how many alias scalars Stands reads a type through -// (styleguide bounded-everything rule), as the schema walk bounds a tag's. A -// longer chain, or a loop, stands for no type a step reads. -const MaxAliasHops = 64 - // ResponseList is the field of an ir.Operation a response sits in. type ResponseList int @@ -59,6 +54,9 @@ type CompiledDocumentView struct { // flatten is ir.FlattenedProperties, which this package's tests count // through. flatten func(ir.TypeRegistry, ir.TypeID) ir.Flattening + // aliases is the index of the document's alias chains every step reads + // through (AliasChains), each chain read once for the run. + aliases *ir.AliasChainIndex } // memberKey is one member Member is asked for: a type, and a wire name. @@ -80,33 +78,34 @@ func New(doc *ir.Document) *CompiledDocumentView { headers: map[ResponseKey]map[string][]ir.PropertyID{}, flatten: ir.FlattenedProperties, } + compiledDocumentView.aliases = ir.NewAliasChainIndex(compiledDocumentView.Types.Lookup) for i := range doc.Services { compiledDocumentView.Operations = append(compiledDocumentView.Operations, operations(&doc.Services[i])...) } return compiledDocumentView } -// Stands returns the type id stands for, read through at most MaxAliasHops -// alias scalars, and nil past them or where the registry holds none, a typed -// nil included, so a caller's comma-ok assertion holds a node. -func (w *CompiledDocumentView) Stands(id ir.TypeID) ir.TypeDef { - for range MaxAliasHops { - base, alias := ir.AliasBase(w.Types, id) - if !alias { - break - } - id = base - } - td := w.Types[id] - if _, alias := ir.AliasBase(w.Types, id); alias || ir.IsNilTypeDef(td) { +// ChainEndNode returns the node id's alias chain ends on, read through its +// alias scalars however many there are (AliasChains), and nil for a cycle of +// them or where the registry holds none, a typed nil included, so a caller's +// comma-ok assertion holds a node. +func (w *CompiledDocumentView) ChainEndNode(id ir.TypeID) ir.TypeDef { + end, cyclic := w.aliases.End(id) + typeDef := w.Types[end] + if cyclic || ir.IsNilTypeDef(typeDef) { return nil } - return td + return typeDef } -// Member returns the declaration the flattening of the model id stands for -// (Stands) takes for the wire name wire (ir.MemberReader), and false where id -// stands for no model or the model holds no such member, so it reads a chain +// AliasChains returns the index of the document's alias chains, each read +// once for the run, as the registry is when first asked. Like the view, it is +// not safe for concurrent use. +func (w *CompiledDocumentView) AliasChains() *ir.AliasChainIndex { return w.aliases } + +// Member returns the declaration the flattening of the model id's chain ends +// on (ChainEndNode) takes for the wire name wire (ir.MemberReader), and false +// where id's chain ends on no model or the model holds no such member, so it reads a chain // of alias scalars as Members does. Each answer is read once, by a walk of // the model's composition, so a model read for n names costs n walks (#1955). func (w *CompiledDocumentView) Member(id ir.TypeID, wire string) (*ir.Property, bool) { @@ -115,7 +114,7 @@ func (w *CompiledDocumentView) Member(id ir.TypeID, wire string) (*ir.Property, return property, property != nil } var irProperty *ir.Property - if model, ok := w.Stands(id).(*ir.Model); ok { + if model, ok := w.ChainEndNode(id).(*ir.Model); ok { if decl, held := w.names.Member(model.ID, wire); held { irProperty = decl.Property } @@ -141,12 +140,13 @@ func (w *CompiledDocumentView) Walk(root ir.TypeID, tokens []string) ([]ir.Prope return segments, true } -// Members returns the members of the model id stands for (Stands), in layout -// order (ir.FlattenedProperties), and none for any other type. It flattens -// each model once, however many aliases name it, for a step that reads every -// member; one asking for a name reads it with Member, which flattens nothing. +// Members returns the members of the model id's chain ends on +// (ChainEndNode), in layout order (ir.FlattenedProperties), and none for any +// other type. It flattens each model once, however many aliases name it, for a +// step that reads every member; one asking for a name reads it with Member, +// which flattens nothing. func (w *CompiledDocumentView) Members(id ir.TypeID) []*ir.Property { - model, ok := w.Stands(id).(*ir.Model) + model, ok := w.ChainEndNode(id).(*ir.Model) if !ok { return nil } diff --git a/compilers/openapi/internal/compileddoc/compileddoc_test.go b/compilers/openapi/internal/compileddoc/compileddoc_test.go index 06354e1cd..1367f38c3 100644 --- a/compilers/openapi/internal/compileddoc/compileddoc_test.go +++ b/compilers/openapi/internal/compileddoc/compileddoc_test.go @@ -124,13 +124,14 @@ type bodyShape struct { // taken is the declaration the root takes for a wire name where more than // one model declares it. taken map[string]ir.PropertyID - // none is set where the root stands for no model: a union, which has no - // member of its own, or the head of more alias scalars than Stands reads. + // none is set where the root's chain ends on no model: a union, which has + // no member of its own, or the head of more alias scalars than ChainEndNode + // reads. none bool } // aliasChain is length alias scalars, named name and a number from 000, each -// standing for the next and the last for to. +// naming the next and the last for to. func aliasChain(name string, length int, to ir.TypeID) []ir.TypeDef { at := func(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("%s%03d", name, i)) } defs := make([]ir.TypeDef, 0, length) @@ -193,18 +194,17 @@ func bodyShapes() map[string]bodyShape { model("m", nil, property("m.n", "n", "string"))).Types, root: "u", none: true, }, - "an alias chain to the cap": {types: chained(compileddoc.MaxAliasHops), root: "body000"}, - "an alias chain past the cap": { - types: chained(compileddoc.MaxAliasHops + 1), root: "body000", none: true, - }, + "an alias chain of 64": {types: chained(64), root: "body000"}, + "an alias chain of 65": {types: chained(65), root: "body000"}, + "an alias chain of 200": {types: chained(200), root: "body000"}, } } // TestDocument_MemberAgreesWithMembers holds Member to the flattening Members // reads, for each shape of body: every wire name of the flattening names the -// property Members lists, a name outside it names none, and a body standing -// for no model, a union or a chain of aliases past the cap, has no member -// whatever the types it names declare. +// property Members lists, a name outside it names none, and a body naming +// for no model or a union has no member whatever the types it names declare, +// and a chain of aliases of any length has its end's. func TestDocument_MemberAgreesWithMembers(t *testing.T) { t.Parallel() for name, shape := range bodyShapes() { @@ -216,7 +216,7 @@ func TestDocument_MemberAgreesWithMembers(t *testing.T) { assert.Empty(t, members) for _, wire := range []string{"n", "a", "absent"} { _, ok := compiledDocumentView.Member(shape.root, wire) - assert.False(t, ok, "a body standing for no model has no member %q", wire) + assert.False(t, ok, "a body naming no model has no member %q", wire) } return } @@ -240,7 +240,7 @@ func TestDocument_MemberAgreesWithMembers(t *testing.T) { // TestDocument_WalkNamesEachMemberFromTheRoot pins a walk to the declaration of // each token's member, through the type of the member before it, and to nothing // where a step names no member or reaches no model, however an alias scalar -// stands between the steps. +// sits between the steps. func TestDocument_WalkNamesEachMemberFromTheRoot(t *testing.T) { t.Parallel() types := irtest.DocOf( @@ -278,12 +278,12 @@ func TestDocument_WalkNamesEachMemberFromTheRoot(t *testing.T) { } } -// TestDocument_StandsReadsThroughAliasScalarsToTheCap pins Stands to the type -// an alias scalar stands for: the same type for one that is none, the model at -// the end of as many as compileddoc.MaxAliasHops alias scalars, and nothing -// past that, for a cycle of them, or for an alias of a type the registry lacks -// or holds as a typed nil. -func TestDocument_StandsReadsThroughAliasScalarsToTheCap(t *testing.T) { +// TestDocument_ChainEndNodeReadsThroughAliasScalarsToTheEnd pins ChainEndNode +// to the chain end of an alias scalar: the same type for one that is none, the model at +// the end of a chain of any length, past the 64 aliases a walk once stopped +// at, and nothing for a cycle of them, or for an alias of a type the registry +// lacks or holds as a typed nil. +func TestDocument_ChainEndNodeReadsThroughAliasScalarsToTheEnd(t *testing.T) { t.Parallel() defs := slices.Concat( []ir.TypeDef{ @@ -291,21 +291,21 @@ func TestDocument_StandsReadsThroughAliasScalarsToTheCap(t *testing.T) { irtest.ScalarOf("loop1", "loop2"), irtest.ScalarOf("loop2", "loop1"), irtest.ScalarOf("dangling", "gone"), irtest.ScalarOf("toNil", "nil"), }, - aliasChain("ok", compileddoc.MaxAliasHops, "m"), - aliasChain("long", compileddoc.MaxAliasHops+1, "m"), + aliasChain("ok", 64, "m"), + aliasChain("long", 200, "m"), ) compiledDocumentView := compileddoc.New(&ir.Document{Types: irtest.DocOf(defs...).Types}) compiledDocumentView.Types["nil"] = (*ir.Model)(nil) // noType is no type at all, which a typed nil is not: assert.Nil accepts both. var noType ir.TypeDef - assert.Equal(t, compiledDocumentView.Types["m"], compiledDocumentView.Stands("m"), "a model stands for itself") - assert.Equal(t, compiledDocumentView.Types["m"], compiledDocumentView.Stands("ok000"), "the head of as many alias scalars as the cap allows") - assert.Equal(t, noType, compiledDocumentView.Stands("long000"), "the head of one more") - assert.Equal(t, noType, compiledDocumentView.Stands("loop1"), "a cycle of aliases") - assert.Equal(t, noType, compiledDocumentView.Stands("dangling"), "an alias of no type") - assert.Equal(t, noType, compiledDocumentView.Stands("toNil"), "an alias of a typed nil") - assert.Equal(t, noType, compiledDocumentView.Stands("gone"), "a type the registry lacks") + assert.Equal(t, compiledDocumentView.Types["m"], compiledDocumentView.ChainEndNode("m"), "a model names itself") + assert.Equal(t, compiledDocumentView.Types["m"], compiledDocumentView.ChainEndNode("ok000"), "the head of 64 alias scalars") + assert.Equal(t, compiledDocumentView.Types["m"], compiledDocumentView.ChainEndNode("long000"), "the head of 200") + assert.Equal(t, noType, compiledDocumentView.ChainEndNode("loop1"), "a cycle of aliases") + assert.Equal(t, noType, compiledDocumentView.ChainEndNode("dangling"), "an alias of no type") + assert.Equal(t, noType, compiledDocumentView.ChainEndNode("toNil"), "an alias of a typed nil") + assert.Equal(t, noType, compiledDocumentView.ChainEndNode("gone"), "a type the registry lacks") } // TestDocument_HeaderMatchesTheNameWithoutCase pins a header to its wire name as @@ -437,3 +437,18 @@ func TestDocument_MembersFlattensAModelOnceWhateverNamesIt(t *testing.T) { } assert.Equal(t, 1, *flattenings, "the model is flattened once") } + +// TestDocument_AliasChainsIsOneIndexReadLive pins the index a view's steps +// read alias chains through, reading the registry as it is when a chain is +// first asked, so a node added after the view is built is read. +func TestDocument_AliasChainsIsOneIndexReadLive(t *testing.T) { + t.Parallel() + compiledDocumentView := compileddoc.New(&ir.Document{Types: irtest.DocOf(aliasChain("late", 3, "n")...).Types}) + compiledDocumentView.Types["n"] = irtest.ModelOf("n", func(*ir.Model) {}) + + end, cyclic := compiledDocumentView.AliasChains().End("late000") + + assert.Equal(t, ir.TypeID("n"), end) + assert.False(t, cyclic) + assert.Equal(t, compiledDocumentView.Types["n"], compiledDocumentView.ChainEndNode("late000")) +} diff --git a/compilers/openapi/internal/compileddoc/doc.go b/compilers/openapi/internal/compileddoc/doc.go index 838afdb74..0c74d1acb 100644 --- a/compilers/openapi/internal/compileddoc/doc.go +++ b/compilers/openapi/internal/compileddoc/doc.go @@ -5,5 +5,5 @@ // that run after the lowerings: it lists the operations and indexes the // members, parameters and headers those steps name (CompiledDocumentView). It // imports ir alone, so it holds what the document states and nothing of a -// source's context, a policy or a step's verdict. +// source's context, a policy or a step's answer. package compileddoc diff --git a/compilers/openapi/internal/compileddoc/params.go b/compilers/openapi/internal/compileddoc/params.go index 90e45465f..e323cd0d7 100644 --- a/compilers/openapi/internal/compileddoc/params.go +++ b/compilers/openapi/internal/compileddoc/params.go @@ -59,8 +59,8 @@ func indexParams(operation *ir.Operation) ParamIndex { names[operation.Params[i].ID] = operation.Params[i].Name.Source } ix := ParamIndex{at: map[paramKey][]ir.ParameterID{}, placed: map[ir.ParameterID][]Placement{}} - for _, b := range operation.Bindings.HTTP { - for _, pb := range b.ParamBindings { + for _, binding := range operation.Bindings.HTTP { + for _, pb := range binding.ParamBindings { if pb.Location == ir.HTTPLocationHost { continue } diff --git a/compilers/openapi/internal/componentlookup/componentlookup_test.go b/compilers/openapi/internal/componentlookup/componentlookup_test.go index 4b4777bb1..b67eed592 100644 --- a/compilers/openapi/internal/componentlookup/componentlookup_test.go +++ b/compilers/openapi/internal/componentlookup/componentlookup_test.go @@ -23,9 +23,9 @@ import ( func TestScope_InDocument_ReadsTheDocumentItNames(t *testing.T) { t.Parallel() path := externalDocument(t) - b := loadBound(t, path, openapitest.ComponentSpec(" Other: {$ref: 'ext.yaml#/components/schemas/E'}\n"), + bound := loadBound(t, path, openapitest.ComponentSpec(" Other: {$ref: 'ext.yaml#/components/schemas/E'}\n"), load.Options{Reader: reader.Disk{}}) - foreign := b.scope + foreign := bound.scope foreign.Foreign, foreign.Holder = true, "elsewhere.yaml" home := foreign.InDocument(reftable.Source) @@ -33,10 +33,10 @@ func TestScope_InDocument_ReadsTheDocumentItNames(t *testing.T) { assert.Empty(t, home.Holder) assert.True(t, foreign.Foreign, "the scope it was asked from is left as it was") - referenceSite, ok := b.doc.Bindings.Entry(b.component(t, "Other")) + referenceSite, ok := bound.doc.Bindings.ReferenceSiteAt(bound.component(t, "Other")) require.True(t, ok && referenceSite.Lands(), "Other's $ref lands in ext.yaml") - there := b.scope.InDocument(referenceSite.Hop.Target.Doc) + there := bound.scope.InDocument(referenceSite.Hop.Target.Doc) assert.True(t, there.Foreign, "ext.yaml holds E") assert.Equal(t, filepath.Join(filepath.Dir(path), "ext.yaml"), there.Holder) - assert.False(t, b.scope.Foreign, "the scope it was asked from is left as it was") + assert.False(t, bound.scope.Foreign, "the scope it was asked from is left as it was") } diff --git a/compilers/openapi/internal/componentlookup/doc.go b/compilers/openapi/internal/componentlookup/doc.go index c1e247b30..20ce99594 100644 --- a/compilers/openapi/internal/componentlookup/doc.go +++ b/compilers/openapi/internal/componentlookup/doc.go @@ -4,7 +4,7 @@ // Package componentlookup answers what a $ref names: the same-document pointer // it addresses and the type interned there, and, for components that are not // schemas, the concrete value and declaration site a reference-or-inline entry -// stands for. +// names. // // It is only that. Following a reference far enough to lower its target // recurses into the schema walk, so it stays with the walk. What is here needs diff --git a/compilers/openapi/internal/componentlookup/documents.go b/compilers/openapi/internal/componentlookup/documents.go index 3cd8c9d6a..2277011c7 100644 --- a/compilers/openapi/internal/componentlookup/documents.go +++ b/compilers/openapi/internal/componentlookup/documents.go @@ -37,9 +37,9 @@ func documentOf(ref references.Reference, base string) (string, bool) { // URL of any scheme but file is spelled one way (normalURL). func Locate(uri, base string) (string, bool) { uri = strings.TrimSpace(uri) - if b, ok := networkURL(base); ok && uri != "" { - if u, err := url.Parse(uri); err == nil && u.Scheme == "" { - return reftable.NormalURI(b.ResolveReference(u)), true + if network, ok := networkURL(base); ok && uri != "" { + if parsed, err := url.Parse(uri); err == nil && parsed.Scheme == "" { + return reftable.NormalURI(network.ResolveReference(parsed)), true } } part := FilePart(uri) @@ -58,11 +58,11 @@ func Locate(uri, base string) (string, bool) { // where it is an absolute URL of a scheme other than file, which names a path, // so every spelling of one URL locates one document, and as it is otherwise. func normalURL(located string) string { - u, err := url.Parse(located) - if err != nil || !IsURL(located) || strings.EqualFold(u.Scheme, "file") { + parsed, err := url.Parse(located) + if err != nil || !IsURL(located) || strings.EqualFold(parsed.Scheme, "file") { return located } - return reftable.NormalURI(u) + return reftable.NormalURI(parsed) } // networkURL returns base parsed as an http or https URL @@ -71,8 +71,8 @@ func networkURL(base string) (*url.URL, bool) { if !reftable.OverNetwork(base) { return nil, false } - u, err := url.Parse(base) - return u, err == nil + parsed, err := url.Parse(base) + return parsed, err == nil } // FilePart returns uri, a reference's document part, as the file it names @@ -181,11 +181,11 @@ func (p *Places) FileOf(name string) (string, bool) { if !IsURL(name) { return p.File(name), true } - u, err := url.Parse(name) - if err != nil || !strings.EqualFold(u.Scheme, "file") { + parsed, err := url.Parse(name) + if err != nil || !strings.EqualFold(parsed.Scheme, "file") { return "", false } - path, err := compilers.FilePath(u, runtime.GOOS == "windows") + path, err := compilers.FilePath(parsed, runtime.GOOS == "windows") if err != nil { return "", false } diff --git a/compilers/openapi/internal/componentlookup/documents_internal_test.go b/compilers/openapi/internal/componentlookup/documents_internal_test.go index efccd988f..4a115ab18 100644 --- a/compilers/openapi/internal/componentlookup/documents_internal_test.go +++ b/compilers/openapi/internal/componentlookup/documents_internal_test.go @@ -190,8 +190,8 @@ func (r *linkReader) LocateDirectory(dir string) string { // through the link, as its target or by a file URI is one document. func TestPlaces_PlacesAFileWhereItsDirectoryLies(t *testing.T) { t.Parallel() - linkReaderValue := &linkReader{from: "/link", to: "/real", asked: map[string]int{}} - places := NewPlaces(linkReaderValue) + linkReader := &linkReader{from: "/link", to: "/real", asked: map[string]int{}} + places := NewPlaces(linkReader) require.NotNil(t, places) assert.Equal(t, "/real/a.yaml", places.File("/link/a.yaml")) @@ -200,7 +200,7 @@ func TestPlaces_PlacesAFileWhereItsDirectoryLies(t *testing.T) { assert.Equal(t, "link/a.yaml", places.File("link/a.yaml"), "a relative path, kept as spelled") assert.Equal(t, "/real", places.Directory("/link")) assert.Equal(t, "link", places.Directory("link")) - assert.Equal(t, 1, linkReaderValue.asked["/link"], "a directory is asked once") + assert.Equal(t, 1, linkReader.asked["/link"], "a directory is asked once") file, ok := places.FileOf("file:///link/a.yaml") assert.True(t, ok) assert.Equal(t, "/real/a.yaml", file) diff --git a/compilers/openapi/internal/componentlookup/entry.go b/compilers/openapi/internal/componentlookup/entry.go index 743ea91f9..dba2573c1 100644 --- a/compilers/openapi/internal/componentlookup/entry.go +++ b/compilers/openapi/internal/componentlookup/entry.go @@ -17,7 +17,7 @@ type Referenced[T any] interface { GetObject() *T } -// Object returns what the reference-or-inline wrapper ref stands for: the +// Object returns what the reference-or-inline wrapper ref names: the // object the chain of the Reference Object written where ref was read ends on, // in whichever document, or ref's own object where the table reads no $ref // there. It is nil for a nil ref and for a chain that does not resolve. The *S @@ -25,28 +25,31 @@ type Referenced[T any] interface { func Object[T, S any, R interface { *S Referenced[T] -}](b *typed.Bindings, ref R) *T { - obj, _ := objectAt[T, S](b, ref) +}](bindings *typed.Bindings, ref R) *T { + obj, _ := objectAt[T, S](bindings, ref) return obj } // ObjectAt is Object with the position declaring what it returns, and use for -// an inline entry, which declares its own object where it is written. It notes -// in scope.Reached each position of the source the chain passes, its end -// included: the declarations the IR carries through their uses. +// an inline entry, which declares its own object where it is written, and the +// chain's hops (Hops), read once for a caller that reads them too: none for an +// inline entry or one that resolves to nothing. It notes in scope.Reached each +// position of the source the chain passes, its end included: the declarations +// the IR carries through their uses. func ObjectAt[T, S any, R interface { *S Referenced[T] -}](scope Scope, ref R, use reftable.DocumentPointer) (*T, reftable.DocumentPointer) { +}](scope Scope, ref R, use reftable.DocumentPointer) (*T, reftable.DocumentPointer, []Hop[R]) { obj, reference := objectAt[T, S](scope.Bindings, ref) if obj == nil || reference == nil { - return obj, use + return obj, use, nil } - for _, hop := range Hops[T, S](scope.Bindings, ref) { + hops := Hops[T, S](scope.Bindings, ref) + for _, hop := range hops { scope.Reached.noteSource(hop.At) } scope.Reached.noteSource(reference.Chain.End) - return obj, reference.Chain.End + return obj, reference.Chain.End, hops } // objectAt is Object with the table's entry for ref's Reference Object, or nil @@ -54,18 +57,18 @@ func ObjectAt[T, S any, R interface { func objectAt[T, S any, R interface { *S Referenced[T] -}](b *typed.Bindings, ref R) (*T, *reftable.Reference) { +}](bindings *typed.Bindings, ref R) (*T, *reftable.Reference) { if ref == nil { return nil, nil } - reference, ok := b.Reference(ref) + reference, ok := bindings.Reference(ref) if !ok { return ref.GetObject(), nil } if reference.Chain.Status != reftable.Resolved { return nil, &reference } - end, ok := b.ObjectAt(reference.Chain.End, reference.Kind).(R) + end, ok := bindings.ObjectAt(reference.Chain.End, reference.Kind).(R) if !ok { return nil, &reference } diff --git a/compilers/openapi/internal/componentlookup/entry_test.go b/compilers/openapi/internal/componentlookup/entry_test.go index d0eeba853..eb07a1b4a 100644 --- a/compilers/openapi/internal/componentlookup/entry_test.go +++ b/compilers/openapi/internal/componentlookup/entry_test.go @@ -271,9 +271,9 @@ func assertCrossDocumentDeclarations(t *testing.T, doc *ir.Document) { assert.Empty(t, cmp.Diff(want, got), "the types in the registry") for id, pointer := range map[ir.TypeID]jsontext.Pointer{wantParamID: paramPtr + "/schema", wantRespID: respPtr} { - td, ok := doc.Types[id] + typeDef, ok := doc.Types[id] require.True(t, ok, "%s is in the registry", id) - assert.Equal(t, ir.Provenance{Source: 1, Pointer: pointer}, td.Common().Provenance, "where %s is declared", id) + assert.Equal(t, ir.Provenance{Source: 1, Pointer: pointer}, typeDef.Common().Provenance, "where %s is declared", id) } operation := openapitest.FindOperation(t, doc, "a") @@ -341,7 +341,8 @@ components: // TestObjectAt_NotesEachPositionOfTheSourceItsChainPasses pins what ObjectAt // records in its scope's Reached: each alias its chain passes and the // declaration it ends at, in the source, and nothing for an inline entry, a -// chain that fails or a scope recording nothing. +// chain that fails or a scope recording nothing. The hops it returns are the +// chain's (Hops), and none where it notes none. func TestObjectAt_NotesEachPositionOfTheSourceItsChainPasses(t *testing.T) { t.Parallel() doc := loaded(t, chainedAliasSpec(2)+" Missing: {$ref: '#/components/parameters/Nope'}\n") @@ -350,22 +351,26 @@ func TestObjectAt_NotesEachPositionOfTheSourceItsChainPasses(t *testing.T) { scope := componentlookup.Scope{SelfPath: doc.Location, Bindings: doc.Bindings, Reached: reached} use := reftable.DocumentPointer{Pointer: "/use"} - obj, at := componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("P0"), use) + obj, at, hops := componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("P0"), use) require.NotNil(t, obj) assert.Equal(t, reftable.DocumentPointer{Pointer: "/components/parameters/P2"}, at) + require.Len(t, hops, 1) + assert.Equal(t, componentlookup.Hops[soa.Parameter](doc.Bindings, params.GetOrZero("P0")), hops) for _, pointer := range []jsontext.Pointer{"/components/parameters/P1", "/components/parameters/P2"} { assert.True(t, reached.Has(pointer), pointer) } assert.False(t, reached.Has("/components/parameters/P0"), "the use site is no position the chain reaches") - obj, at = componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("P2"), use) + obj, at, hops = componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("P2"), use) assert.NotNil(t, obj) assert.Equal(t, use, at, "an inline entry declares its object where it is written") - obj, at = componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("Missing"), use) + assert.Empty(t, hops) + obj, at, hops = componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("Missing"), use) assert.Nil(t, obj) assert.Equal(t, use, at) + assert.Empty(t, hops) scope.Reached = nil - obj, _ = componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("P0"), use) + obj, _, _ = componentlookup.ObjectAt[soa.Parameter](scope, params.GetOrZero("P0"), use) assert.NotNil(t, obj, "a scope recording nothing still answers") } @@ -416,7 +421,7 @@ components: require.True(t, ok) scope := componentlookup.Scope{SelfPath: doc.Location, Bindings: doc.Bindings} - obj, at := componentlookup.ObjectAt[soa.PathItem](scope, rp, reftable.DocumentPointer{Pointer: "/paths/~1hop"}) + obj, at, _ := componentlookup.ObjectAt[soa.PathItem](scope, rp, reftable.DocumentPointer{Pointer: "/paths/~1hop"}) require.NotNil(t, obj) assert.Equal(t, reftable.DocumentPointer{Pointer: "/components/pathItems/P"}, at) assert.Same(t, doc.Doc.Components.GetPathItems().GetOrZero("P").GetObject(), obj, "the source's own model") diff --git a/compilers/openapi/internal/componentlookup/hops.go b/compilers/openapi/internal/componentlookup/hops.go index 623215eec..9914a9040 100644 --- a/compilers/openapi/internal/componentlookup/hops.go +++ b/compilers/openapi/internal/componentlookup/hops.go @@ -24,16 +24,16 @@ type Hop[R any] struct { func Hops[T, S any, R interface { *S Referenced[T] -}](b *typed.Bindings, ref R) []Hop[R] { - reference, ok := b.Reference(ref) +}](bindings *typed.Bindings, ref R) []Hop[R] { + reference, ok := bindings.Reference(ref) if !ok || reference.Chain.Status != reftable.Resolved { return nil } - var hops []Hop[R] + hops := make([]Hop[R], 0, max(reference.Chain.Hops-1, 0)) for range reference.Chain.Hops - 1 { at := reference.Hop.Target - next, ok := b.Table().Reference(at, reference.Kind) - wrapper, held := b.ObjectAt(at, reference.Kind).(R) + next, ok := bindings.Table().Reference(at, reference.Kind) + wrapper, held := bindings.ObjectAt(at, reference.Kind).(R) if !ok || !held { break } diff --git a/compilers/openapi/internal/componentlookup/hops_test.go b/compilers/openapi/internal/componentlookup/hops_test.go index 77839a42e..6f91f5a77 100644 --- a/compilers/openapi/internal/componentlookup/hops_test.go +++ b/compilers/openapi/internal/componentlookup/hops_test.go @@ -119,9 +119,9 @@ components: C: {name: c, in: query} `), &tree)) bd := typed.NewBuilder(reftable.Bind(t.Context(), &tree, reftable.Config{Self: "spec.yaml"})) - a := &soa.ReferencedParameter{} - bd.Object(a, reftable.RefParameter, reftable.DocumentPointer{Pointer: "/components/parameters/A"}) + referencedParameter := &soa.ReferencedParameter{} + bd.Object(referencedParameter, reftable.RefParameter, reftable.DocumentPointer{Pointer: "/components/parameters/A"}) - assert.Empty(t, componentlookup.Hops[soa.Parameter](bd.Bindings(), a), "no wrapper is held at B") - assert.Nil(t, componentlookup.Object[soa.Parameter](bd.Bindings(), a), "nor at C, where the chain ends") + assert.Empty(t, componentlookup.Hops[soa.Parameter](bd.Bindings(), referencedParameter), "no wrapper is held at B") + assert.Nil(t, componentlookup.Object[soa.Parameter](bd.Bindings(), referencedParameter), "nor at C, where the chain ends") } diff --git a/compilers/openapi/internal/componentlookup/placement_test.go b/compilers/openapi/internal/componentlookup/placement_test.go index c9b4c9729..2f7c2d670 100644 --- a/compilers/openapi/internal/componentlookup/placement_test.go +++ b/compilers/openapi/internal/componentlookup/placement_test.go @@ -42,19 +42,19 @@ func TestScope_MappingTarget_WhereTheCompilerResolvedTheValue(t *testing.T) { missing: '#/$defs/missing' bare: Cat ` - b := loadBound(t, externalDocument(t), openapitest.ComponentSpec(schemas), load.Options{Reader: reader.Disk{}}) - require.NotNil(t, b.component(t, "Pet").GetSchema().GetDiscriminator()) + bound := loadBound(t, externalDocument(t), openapitest.ComponentSpec(schemas), load.Options{Reader: reader.Disk{}}) + require.NotNil(t, bound.component(t, "Pet").GetSchema().GetDiscriminator()) documentPointer := reftable.DocumentPointer{Pointer: "/components/schemas/Pet/discriminator"} for value, want := range map[string]string{ "#/components/schemas/Cat": "/components/schemas/Cat", "#/$defs/dog": "/components/schemas/Pet/$defs/dog", } { - got, ok := b.scope.MappingTarget(documentPointer, value) + got, ok := bound.scope.MappingTarget(documentPointer, value) assert.True(t, ok, value) assert.Equal(t, reftable.DocumentPointer{Pointer: jsontext.Pointer(want)}, got, value) } - other, ok := b.scope.MappingTarget(documentPointer, "ext.yaml#/components/schemas/E") + other, ok := bound.scope.MappingTarget(documentPointer, "ext.yaml#/components/schemas/E") require.True(t, ok, "a value into another document lands there") assert.NotEqual(t, reftable.Source, other.Doc) assert.Equal(t, jsontext.Pointer("/components/schemas/E"), other.Pointer) @@ -65,12 +65,12 @@ func TestScope_MappingTarget_WhereTheCompilerResolvedTheValue(t *testing.T) { "Cat": "a bare name is a component's name, read as no $ref", "#/components/schemas/Unwritten": "the table read no such value", } { - got, ok := b.scope.MappingTarget(documentPointer, value) + got, ok := bound.scope.MappingTarget(documentPointer, value) assert.False(t, ok, "%s: %s", value, why) assert.Zero(t, got, value) } - _, ok = b.scope.MappingTarget(reftable.DocumentPointer{}, "#/components/schemas/Cat") + _, ok = bound.scope.MappingTarget(reftable.DocumentPointer{}, "#/components/schemas/Cat") assert.False(t, ok, "the position of a schema the bindings do not know") _, ok = componentlookup.Scope{}.MappingTarget(documentPointer, "#/components/schemas/Cat") assert.False(t, ok, "no bindings, no target") diff --git a/compilers/openapi/internal/componentlookup/usedocs.go b/compilers/openapi/internal/componentlookup/usedocs.go index c746012cb..21705365e 100644 --- a/compilers/openapi/internal/componentlookup/usedocs.go +++ b/compilers/openapi/internal/componentlookup/usedocs.go @@ -15,21 +15,22 @@ import ( // UseDocs folds the summary and description written beside each `$ref` of ref's // chain over docs, the declaration's, from it outward, field by field, so the -// use site's own win, an alias's beat what it names, and a field a hop omits, -// or writes empty or null, leaves the one beneath standing (GitHub #610). Each -// is read off the mapping writing the $ref, as the model reads it, a `<<` -// included. OpenAPI gives such a sibling "no effect" where the object allows -// none, but the IR has a docs field at each position this serves +// use site's own take precedence, an alias's over what it names, and a field a +// hop omits, or writes empty or null, leaves the one beneath in place (GitHub +// #610). Each is read off the mapping writing the $ref, as the model reads it, +// a `<<` included. OpenAPI gives such a sibling "no effect" where the object +// allows none, but the IR has a docs field at each position this serves // (docs/compilers/openapi.md#reference-object-siblings). func UseDocs[T, S any, R interface { *S Referenced[T] -}](b *typed.Bindings, ref R, docs ir.Docs) ir.Docs { - if _, ok := b.Reference(ref); !ok { +}](bindings *typed.Bindings, ref R, docs ir.Docs) ir.Docs { + if _, ok := bindings.Reference(ref); !ok { return docs } - written := []*yaml.Node{writtenAs(ref)} - for _, hop := range Hops[T, S](b, ref) { + hops := Hops[T, S](bindings, ref) + written := append(make([]*yaml.Node, 0, 1+len(hops)), writtenAs(ref)) + for _, hop := range hops { written = append(written, writtenAs(hop.Ref)) } for _, node := range slices.Backward(written) { diff --git a/compilers/openapi/internal/componentlookup/usedocs_test.go b/compilers/openapi/internal/componentlookup/usedocs_test.go index 243475803..146a32fd5 100644 --- a/compilers/openapi/internal/componentlookup/usedocs_test.go +++ b/compilers/openapi/internal/componentlookup/usedocs_test.go @@ -9,6 +9,7 @@ import ( "github.com/google/go-cmp/cmp" soa "github.com/speakeasy-api/openapi/openapi" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/componentlookup" "github.com/dexpace/morphic/ir" @@ -18,7 +19,7 @@ import ( // chain: a summary or description written beside a $ref wins field by field // over what it names, the use site's over an alias's and an alias's over the // declaration's, and one an entry omits, or writes empty or null, leaves the -// one beneath it standing. One beside a $ref a `<<` merges in counts, as the +// one beneath it in place. One beside a $ref a `<<` merges in counts, as the // table reads that $ref, and an inline entry, a nil one and one the bindings // never read fold nothing. func TestUseDocs_UseSiteSiblingsOverrideTheDeclaration(t *testing.T) { @@ -51,3 +52,19 @@ components: assert.Equal(t, declared, componentlookup.UseDocs[soa.Parameter](doc.Bindings, (*soa.ReferencedParameter)(nil), declared)) assert.Equal(t, declared, componentlookup.UseDocs[soa.Parameter](doc.Bindings, &soa.ReferencedParameter{}, declared)) } + +// TestUseDocs_AllocatesAlikeWhateverTheChainsLength pins that a use folds its +// chain's docs from one slice of its count: a use through sixteen times the +// aliases makes as many allocations, which growing the slice a hop at a time +// would not. Not parallel: AllocsPerRun measures the process. +func TestUseDocs_AllocatesAlikeWhateverTheChainsLength(t *testing.T) { + allocations := func(hops int) float64 { + doc := loaded(t, chainedAliasSpec(hops)) + use := doc.Doc.Components.GetParameters().GetOrZero("P0") + require.NotNil(t, use) + return testing.AllocsPerRun(20, func() { + _ = componentlookup.UseDocs[soa.Parameter](doc.Bindings, use, ir.Docs{}) + }) + } + assert.Equal(t, allocations(16), allocations(256)) +} diff --git a/compilers/openapi/internal/convention/convention.go b/compilers/openapi/internal/convention/convention.go index 999d941ab..932be923c 100644 --- a/compilers/openapi/internal/convention/convention.go +++ b/compilers/openapi/internal/convention/convention.go @@ -17,8 +17,9 @@ import ( // run's promoter, whose keys a reading defers to, and compiledDocumentView the // document its lowerings built, whose service tree and registry are whole. func Apply(policy Policy, promoter promotion.Promoter, compiledDocumentView *compileddoc.CompiledDocumentView) (diags []ir.Diagnostic) { + chains := newChainAnswerMemo(promoter, compiledDocumentView) for _, irOperation := range compiledDocumentView.Operations { - diags = append(diags, operation(policy, promoter, compiledDocumentView, irOperation)...) + diags = append(diags, operation(policy, promoter, chains, compiledDocumentView, irOperation)...) } // Each member is read alone and none is reported, so the registry's order, // which no sort fixes here, decides nothing. @@ -28,7 +29,7 @@ func Apply(policy Policy, promoter promotion.Promoter, compiledDocumentView *com continue } for i := range model.Properties { - redact(policy.Secret, promoter, compiledDocumentView.Types, &model.Properties[i]) + redact(policy.Secret, promoter, chains, &model.Properties[i]) } } return diags @@ -37,23 +38,24 @@ func Apply(policy Policy, promoter promotion.Promoter, compiledDocumentView *com // operation fills what irOperation's names imply: its idempotency token, the // redaction of its parameters and of every header it declares, and the text of // each of its header parameters and its responses' headers. -func operation(policy Policy, promoter promotion.Promoter, compiledDocumentView *compileddoc.CompiledDocumentView, irOperation *ir.Operation) []ir.Diagnostic { - reg := compiledDocumentView.Types +func operation(policy Policy, promoter promotion.Promoter, chains *chainAnswerMemo, compiledDocumentView *compileddoc.CompiledDocumentView, + irOperation *ir.Operation, +) []ir.Diagnostic { diags := idempotency(policy.Idempotency, compiledDocumentView, irOperation) for i := range irOperation.Params { param := &irOperation.Params[i] - redactUse(policy.Secret, promoter, reg, param.Name, param.Type, param.Unmodeled, ¶m.Secret, ¶m.Provenance) + redactUse(policy.Secret, promoter, chains, param.Name, param.Type, param.Unmodeled, ¶m.Secret, ¶m.Provenance) } - diags = append(diags, httpDateParam(policy.HTTPDate, promoter, compiledDocumentView, irOperation)...) + diags = append(diags, httpDateParam(policy.HTTPDate, chains, compiledDocumentView, irOperation)...) for _, hs := range responseHeaders(irOperation) { for i := range hs { - redact(policy.Secret, promoter, reg, &hs[i].Property) - diags = append(diags, httpDate(policy.HTTPDate, promoter, reg, &hs[i])...) + redact(policy.Secret, promoter, chains, &hs[i].Property) + diags = append(diags, httpDate(policy.HTTPDate, chains, &hs[i])...) } } for _, hs := range partHeaders(irOperation) { for i := range hs { - redact(policy.Secret, promoter, reg, &hs[i].Property) + redact(policy.Secret, promoter, chains, &hs[i].Property) } } return diags @@ -109,13 +111,7 @@ func partHeaders(operation *ir.Operation) [][]ir.Header { return lists } -// maxScalarHops bounds the scalars a type chain is read through. The IR -// permits a chain of any length, a cycle among them, and a document nests -// aliases a few deep, so a chain longer than this is read as ending at no -// primitive. -const maxScalarHops = 64 - -// chain is what the scalars from a type stand over: the primitive at the end of +// chain is what the scalars from a type lead to: the primitive at the end of // the chain, and whether a node along it names an encoding, asks for // redaction, or writes a key the policy reads redaction from. type chain struct { @@ -125,32 +121,47 @@ type chain struct { spoken bool } -// readChain reads the chain from id through each scalar's Base, to -// maxScalarHops of them, and reports false where it ends at a type that is no -// primitive, at a type the registry does not hold, or past the bound. -func readChain(promoter promotion.Promoter, reg ir.TypeRegistry, id ir.TypeID) (chain, bool) { - var ch chain - for range maxScalarHops { - td := reg[id] - if ir.IsNilTypeDef(td) { - return chain{}, false +// chainAnswerMemo remembers what each alias chain of a document leads to, once +// for the run, through the document's AliasChains index. Like that index, it +// is not safe for concurrent use. +type chainAnswerMemo struct { + answers *ir.AliasChainAnswers[chainAnswer] +} + +// chainAnswer is what one chain leads to, and whether it ends at a primitive. +type chainAnswer struct { + chain + ok bool +} + +// newChainAnswerMemo returns the memo of the answers for compiledDocumentView's +// chains, a redaction key read as promoter reads it. +func newChainAnswerMemo(promoter promotion.Promoter, compiledDocumentView *compileddoc.CompiledDocumentView) *chainAnswerMemo { + atEnd := func(_ ir.TypeID, td ir.TypeDef) chainAnswer { + primitive, ok := td.(*ir.Primitive) + if !ok { + return chainAnswer{} } - common := td.Common() - ch.sensitive = ch.sensitive || common.Sensitive - ch.spoken = ch.spoken || promoter.Writes(common.Unmodeled, promotion.TargetRedaction) - switch n := td.(type) { - case *ir.Primitive: - ch.primitive = n.PrimitiveKind - return ch, true - case *ir.Scalar: - ch.encoded = ch.encoded || n.Encoding != nil && n.Encoding.Name != "" - if n.Base == nil { - return chain{}, false - } - id = n.Base.Target - default: - return chain{}, false + common := primitive.Common() + return chainAnswer{primitive: primitive.PrimitiveKind, sensitive: common.Sensitive, + spoken: promoter.Writes(common.Unmodeled, promotion.TargetRedaction), ok: true} + } + fromNext := func(scalar *ir.Scalar, next chainAnswer) chainAnswer { + if !next.ok { + return next } + next.encoded = next.encoded || scalar.Encoding.Encodes() + next.sensitive = next.sensitive || scalar.Sensitive + next.spoken = next.spoken || promoter.Writes(scalar.Unmodeled, promotion.TargetRedaction) + return next } - return chain{}, false + return &chainAnswerMemo{answers: ir.NewAliasChainAnswers(compiledDocumentView.AliasChains(), atEnd, fromNext)} +} + +// read returns what the chain from id leads to, through each scalar's Base +// however many there are, and false where it ends at a type that is no +// primitive, at a type the registry does not hold, or meets a scalar twice. +func (memo *chainAnswerMemo) read(id ir.TypeID) (chain, bool) { + answer, read := memo.answers.AnswerFor(id) + return answer.chain, read && answer.ok } diff --git a/compilers/openapi/internal/convention/httpdate.go b/compilers/openapi/internal/convention/httpdate.go index 4c59b17a3..e8d1793a1 100644 --- a/compilers/openapi/internal/convention/httpdate.go +++ b/compilers/openapi/internal/convention/httpdate.go @@ -8,7 +8,6 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/compileddoc" "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/promotion" "github.com/dexpace/morphic/ir" ) @@ -23,12 +22,12 @@ const httpDateEncoding = "http-date" // datetime_offset none of them names an encoding for. It reports each such // header, whose format says RFC 3339's text. The rule is // docs/compilers/openapi.md#http-date-inference. -func httpDate(policy HTTPDateInference, promoter promotion.Promoter, reg ir.TypeRegistry, header *ir.Header) []ir.Diagnostic { +func httpDate(policy HTTPDateInference, chains *chainAnswerMemo, header *ir.Header) []ir.Diagnostic { if !policy.Honours() || header.Encoding != nil || header.Prefix != nil || !httpDateField(header.EffectiveWireName()) { return nil } - if !instant(promoter, reg, header.Type.Target) { + if !instant(chains, header.Type.Target) { return nil } header.Encoding = &ir.Encoding{Name: httpDateEncoding} @@ -46,7 +45,7 @@ func httpDate(policy HTTPDateInference, promoter promotion.Promoter, reg ir.Type // its own, and its type reads as an instant: on the parameter itself, as its // type may be one a $ref shares. A parameter in any other location is not read, // whatever its name. The rule is docs/compilers/openapi.md#http-date-inference. -func httpDateParam(policy HTTPDateInference, promoter promotion.Promoter, compiledDocumentView *compileddoc.CompiledDocumentView, +func httpDateParam(policy HTTPDateInference, chains *chainAnswerMemo, compiledDocumentView *compileddoc.CompiledDocumentView, operation *ir.Operation, ) []ir.Diagnostic { if !policy.Honours() || len(operation.Params) == 0 { @@ -57,7 +56,7 @@ func httpDateParam(policy HTTPDateInference, promoter promotion.Promoter, compil for i := range operation.Params { parameter := &operation.Params[i] name, bound := headerName(ix, parameter) - if !bound || parameter.Encoding != nil || !httpDateField(name) || !instant(promoter, compiledDocumentView.Types, parameter.Type.Target) { + if !bound || parameter.Encoding != nil || !httpDateField(name) || !instant(chains, parameter.Type.Target) { continue } parameter.Encoding = &ir.Encoding{Name: httpDateEncoding} @@ -84,8 +83,8 @@ func headerName(ix compileddoc.ParamIndex, parameter *ir.Parameter) (string, boo // instant reports whether id reads, through its scalars, as a datetime_offset // none of them names an encoding for. -func instant(promoter promotion.Promoter, reg ir.TypeRegistry, id ir.TypeID) bool { - ch, ok := readChain(promoter, reg, id) +func instant(chains *chainAnswerMemo, id ir.TypeID) bool { + ch, ok := chains.read(id) return ok && !ch.encoded && ch.primitive == ir.PrimitiveDatetimeOffset } diff --git a/compilers/openapi/internal/convention/secret.go b/compilers/openapi/internal/convention/secret.go index 7172a1f77..f7f548b62 100644 --- a/compilers/openapi/internal/convention/secret.go +++ b/compilers/openapi/internal/convention/secret.go @@ -12,8 +12,8 @@ import ( // redact asks for property's redaction where its name says it holds a // credential (redactUse): a model's member or a header. -func redact(policy SecretInference, promoter promotion.Promoter, reg ir.TypeRegistry, property *ir.Property) { - redactUse(policy, promoter, reg, property.Name, property.Type, property.Unmodeled, &property.Secret, &property.Provenance) +func redact(policy SecretInference, promoter promotion.Promoter, chains *chainAnswerMemo, property *ir.Property) { + redactUse(policy, promoter, chains, property.Name, property.Type, property.Unmodeled, &property.Secret, &property.Provenance) } // redactUse sets *secret, and marks prov, under the secret policy, on a use @@ -24,7 +24,7 @@ func redact(policy SecretInference, promoter promotion.Promoter, reg ir.TypeRegi // redaction from, at the use or along its type, whatever the key says: the // document has spoken there. The rule is // docs/compilers/openapi.md#secret-inference. -func redactUse(policy SecretInference, promoter promotion.Promoter, reg ir.TypeRegistry, name ir.Naming, +func redactUse(policy SecretInference, promoter promotion.Promoter, chains *chainAnswerMemo, name ir.Naming, typeRef ir.TypeRef, own ir.Unmodeled, secret *bool, prov *ir.Provenance, ) { if !policy.Honours() || *secret || !credentialName(name.Canonical) { @@ -33,7 +33,7 @@ func redactUse(policy SecretInference, promoter promotion.Promoter, reg ir.TypeR if promoter.Writes(own, promotion.TargetRedaction) { return } - ch, ok := readChain(promoter, reg, typeRef.Target) + ch, ok := chains.read(typeRef.Target) if !ok || ch.sensitive || ch.spoken || ch.primitive != ir.PrimitiveString && ch.primitive != ir.PrimitiveBytes { return } diff --git a/compilers/openapi/internal/convention/secret_test.go b/compilers/openapi/internal/convention/secret_test.go index 2219d7ad5..67801f770 100644 --- a/compilers/openapi/internal/convention/secret_test.go +++ b/compilers/openapi/internal/convention/secret_test.go @@ -84,9 +84,9 @@ func TestRedact_ReadsTheNamesTail(t *testing.T) { } // TestRedact_ReadsTheValuesType pins which values a credential's name redacts: -// text and bytes, read through the scalars a schema or a $ref hoists, and no -// other value, nor one whose chain ends at no primitive, loops, or reaches its -// primitive past the bound: 63 scalars and the primitive are 64 types read. +// text and bytes, read through the scalars a schema or a $ref hoists, however +// many, past the 64 types a walk once stopped at, and no other value, nor one +// whose chain ends at no primitive or loops. func TestRedact_ReadsTheValuesType(t *testing.T) { t.Parallel() over := func(id ir.TypeID, base ir.TypeID) *ir.Scalar { @@ -111,8 +111,9 @@ func TestRedact_ReadsTheValuesType(t *testing.T) { {"an opaque scalar", "type/o", ir.TypeRegistry{"type/o": &ir.Scalar{ID: "type/o"}}, false}, {"a type the registry lacks", "type/missing", nil, false}, {"a cycle of scalars", "type/x", ir.TypeRegistry{"type/x": over("type/x", "type/y"), "type/y": over("type/y", "type/x")}, false}, - {"a chain of scalars the bound reads to its primitive", "type/c/0", scalars(63), true}, - {"a chain past the bound", "type/c/0", scalars(64), false}, + {"a chain of 63 scalars", "type/c/0", scalars(63), true}, + {"a chain of 64 scalars", "type/c/0", scalars(64), true}, + {"a chain of 200 scalars", "type/c/0", scalars(200), true}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/detect/declares_test.go b/compilers/openapi/internal/detect/declares_test.go index e61bdccf1..68c439a27 100644 --- a/compilers/openapi/internal/detect/declares_test.go +++ b/compilers/openapi/internal/detect/declares_test.go @@ -49,7 +49,7 @@ func TestDeclaresProbeKey_ScopesTheNameToItsOwnDocument(t *testing.T) { {"flow style, prose for the version", `{"openapi":"is a format",`, false}, {"flow style, nothing after the colon", `{"openapi":`, false}, {"flow style past a byte-order mark", "\xef\xbb\xbf{\"openapi\":\"3.1.0\",", true}, - // What may stand in front of a root flow mapping: comment lines, and up + // What may sit in front of a root flow mapping: comment lines, and up // to two node properties — an anchor and a tag, in either order. {"flow style behind a comment line", "# c\n # d\n{\"openapi\":\"3.1.0\",", true}, {"flow style behind an anchor", "&x {\"openapi\":\"3.1.0\",", true}, diff --git a/compilers/openapi/internal/detect/recognize.go b/compilers/openapi/internal/detect/recognize.go index 858ef5b1a..3f4fecf6a 100644 --- a/compilers/openapi/internal/detect/recognize.go +++ b/compilers/openapi/internal/detect/recognize.go @@ -20,10 +20,10 @@ import ( // it, declining silently. // // Three sources are declined with an error whatever their format: one past -// maxBytes, unread, or past maxNodes, with load.Load's refusal, and one whose root -// merges past the depth the read expands, its own keys leaving the version -// open (settledByOwnPairs). Any other decline is silent unless the source is -// unreadable and declares a version where a document declares one +// maxBytes, unread, or past maxNodes, with load.Load's refusal, and one whose +// root merges past the depth the read expands, its own keys leaving the version +// open (settledByOwnPairs). Any other decline reports nothing unless the source +// is unreadable and declares a version where a document declares one // (declaresProbeKey). func Recognize(ctx context.Context, srcIndex int, data []byte, maxBytes, maxNodes budget.Limit, ) (compilers.Recognition, []ir.Diagnostic, bool) { diff --git a/compilers/openapi/internal/detect/recognize_reading_test.go b/compilers/openapi/internal/detect/recognize_reading_test.go index 3d7224931..e80c4a2cb 100644 --- a/compilers/openapi/internal/detect/recognize_reading_test.go +++ b/compilers/openapi/internal/detect/recognize_reading_test.go @@ -16,7 +16,7 @@ import ( ) // reading is how detection reads a document: it parses, or it does not and -// Recognize says so, or it does not and Recognize is silent. +// Recognize says so, or it does not and Recognize reports nothing. type reading int const ( @@ -138,8 +138,9 @@ func declarations() []declarationRow { {name: "the key inside an open single-quoted scalar", src: "description: 'a\nopenapi: 3.1.0\n'\n"}, {name: "the key inside a single-quoted scalar with an escaped quote", src: "description: 'it''s\nopenapi: 3.1.0\n'\n"}, {name: "the key inside a quoted scalar opened on an indented line", src: "info:\n d: \"a\nopenapi: 3.1.0\n\"\n"}, - // A node property — an anchor, a tag, or both — stands between the colon - // and the opener, and yaml.v3 opens the construct behind it all the same. + // A node property — an anchor, a tag, or both — sits between the colon + // and the opener, and yaml.v3 opens the construct behind it all the + // same. {name: "the key inside a flow mapping behind an anchor", src: "a: &x {\nopenapi: 3.1.0\n}\n"}, {name: "the key inside a flow mapping behind a tag", src: "a: !!map {\nopenapi: 3.1.0\n}\n"}, {name: "the key inside a flow mapping behind a tag and an anchor", src: "a: !!map &x {\nopenapi: 3.1.0\n}\n"}, @@ -309,9 +310,9 @@ func TestRecognize_AVersionThatIsNotServedIsStillADeclaration(t *testing.T) { } // TestRecognize_ABrokenDocumentIsReportedAtAnySize pins what reading one way -// bought. A broken spec that declares a version at column 0 is this -// compiler's own, and saying so needs the whole document read: the byte scan that stood -// in for the parse past 64 KiB could not tell such a spec from another format's +// bought. A broken spec that declares a version at column 0 is this compiler's +// own, and saying so needs the whole document read: the byte scan that took in +// for the parse past 64 KiB could not tell such a spec from another format's // file naming the word, so the same document drew a complaint when small and // silence when large. func TestRecognize_ABrokenDocumentIsReportedAtAnySize(t *testing.T) { diff --git a/compilers/openapi/internal/detect/recognize_test.go b/compilers/openapi/internal/detect/recognize_test.go index a317de993..07e13a77b 100644 --- a/compilers/openapi/internal/detect/recognize_test.go +++ b/compilers/openapi/internal/detect/recognize_test.go @@ -256,9 +256,9 @@ func TestRecognize_KeyOrderDoesNotDecideTheFormat(t *testing.T) { } // bigComponents returns a `components` entry whose value alone runs past -// scanCutover, in flow and in block style. It stands in for the schema catalogue a -// published spec leads with; what matters is only that it is one entry too large -// to read past. +// scanCutover, in flow and in block style. It takes the place of the schema +// catalogue a published spec leads with; what matters is only that it is one +// entry too large to read past. func bigComponents() (flow, block string) { var f, b strings.Builder f.WriteString(`"components":{"schemas":{`) @@ -345,7 +345,7 @@ func TestRecognize_ReadsAVersionKeyThroughAMergeKey(t *testing.T) { {"mapping written out", "<<: {openapi: 3.1.0}\ninfo: {}\n", "3.1"}, {"sequence of aliases", "one: &o\n unrelated: x\ntwo: &t\n openapi: 3.1.0\n<<: [*o, *t]\n", "3.1"}, {"earlier merge wins", "one: &o\n openapi: 3.0.3\ntwo: &t\n openapi: 3.1.0\n<<: [*o, *t]\n", "3.0"}, - {"a written key beats a merged one", "base: &b\n openapi: 3.0.3\n<<: *b\nopenapi: 3.1.0\n", "3.1"}, + {"a written key takes precedence over a merged one", "base: &b\n openapi: 3.0.3\n<<: *b\nopenapi: 3.1.0\n", "3.1"}, {"a quoted << merges nothing", "base: &b\n openapi: 3.1.0\n\"<<\": *b\ninfo: {}\n", ""}, } for _, tc := range cases { diff --git a/compilers/openapi/internal/diag/diag.go b/compilers/openapi/internal/diag/diag.go index a88f64e9a..4aba319e1 100644 --- a/compilers/openapi/internal/diag/diag.go +++ b/compilers/openapi/internal/diag/diag.go @@ -25,7 +25,8 @@ const ( // it, with why (reftable.Hop.Why); a $ref whose chain ends on it reports // nothing of its own (docs/compilers/openapi.md#references). The lowering // reports a $ref it cannot follow at its position too, kept only where the - // load phase reported none there (openapi.withoutRereported). + // load phase reported none there (openapi.withoutRereported), once however + // many of its readers meet it. UnresolvedRef = "openapi/unresolved-ref" // UnresolvedSecurityScheme reports a security requirement naming a scheme // the compiler resolved no mechanism for, at the requirement, from @@ -44,7 +45,7 @@ const ( // ambiguously or breaks the runtime-expression grammar. The link is kept // verbatim (docs/compilers/openapi.md#links). A warning, as a broken rule // the validator finds is: nothing is lost, and the rest of the document - // stands. + // remains. InvalidLink = "openapi/invalid-link" // UntypedLink reports a link, at the link, that reads a value no // ir.LinkValue spells, such as an operation of another document or a member @@ -207,11 +208,11 @@ const ( InvalidStatusKey = "openapi/invalid-status-key" // DuplicateStatusKey reports two responses-map keys on one operation that // resolve to the same status range — "4XX" beside "4xx", or "200" beside a - // second "200" a merge key introduced. The key reaches the IR neutralized, so - // both lower to one hint and one condition, and an ErrorCase carries no ID: - // name and conditions are the whole of what tells two apart. Both are kept, - // because neither key is wrong on its own and dropping one would pick a winner - // on nothing but declaration order. + // second "200" a merge key introduced. The key reaches the IR neutralized, + // so both lower to one hint and one condition, and an ErrorCase carries no + // ID: name and conditions are the whole of what tells two apart. Both are + // kept, because neither key is wrong on its own and dropping one would + // choose one on nothing but declaration order. DuplicateStatusKey = "openapi/duplicate-status-key" // DuplicateParameter reports a parameter list entry repeating the name and // location of an earlier entry in the same list (ids.SlotOf), its $refs @@ -244,16 +245,25 @@ const ( // DegradedConstruct reports a construct the compiler could not lower as // written: kept raw for want of a home or past a bound (callbacks too deep, // operation.operationCallbacks), lowered weaker (a mixed enum as a union, an - // unconvertible value as the top type, a member or const its type rejects as - // written), or dropped (an example, an enum's excluded null). A promotion + // unconvertible value as the top type), or dropped (an example). A promotion // or grouping by extension reports an extension kept but read into no field // or group (promotion.Promoter, operation.extensionPaths). It marks the lossy // lowerings reported, not every one. DegradedConstruct = "openapi/degraded-construct" - // CompositionLowering reports that a schema conjoining a structural body with - // a oneOf/anyOf was lowered by distributing the body across the union - // variants (lowerDistributedUnion), or, for a subtype a discriminator routes - // to, by composing a Union minted for it as a mixin of its model + // UnsatisfiableSchema reports a schema, a branch or a member of it no + // instance satisfies, at the construct saying so: conjuncts sharing no + // value, a union branch the rest beside it leaves no value, an enum member + // or a const its declared type excludes, an enum whose bounds refuse every + // member, or an allOf entry declaring a type no object is beside the model + // it composes. A composition cycle whose member counts admit no object is + // pass.Validate's pass/bounds-admit-no-value. + // + // Warning: the document is valid, and what it describes holds no value. + UnsatisfiableSchema = "openapi/unsatisfiable-schema" + // CompositionLowering reports that a schema writing a structural rest + // beside a oneOf/anyOf was lowered by distributing the rest across the + // union variants (lowerDistributedUnion), or, for a subtype a discriminator + // routes to, by composing a Union minted for it as a mixin of its model // (lowerSubtypeUnion; docs/ir/models.md#composition-beside-a-union, // docs/compilers/openapi.md#union-beside-structure). Nothing is lost, so // this records a decision rather than a degradation: the IR's shape no @@ -270,22 +280,22 @@ const ( DynamicRefExpanded = "openapi/dynamic-ref-expanded" // ConflictingRedecl reports that inline allOf entries redeclare one field // with disagreeing values. The judgment finds the types narrower (no - // diagnostic), overlapping (a DegradedConstruct: shared values the merge does - // not narrow) or disjoint; only disjoint types, a scalar against a structure - // and two structures of different instance types conflict. A constraint - // keyword no one value states, such as two patterns, is usually satisfiable, - // but the merge can keep only a source-order winner. A bound meets, so it - // never reports here. + // diagnostic), overlapping (a DegradedConstruct: shared values the merge + // does not narrow) or disjoint; only disjoint types, a scalar against a + // structure and two structures of different instance types conflict. A + // constraint keyword no one value states, such as two patterns, is usually + // satisfiable, but the merge can keep only the source-order choice. A bound + // intersects, so it never reports here. // - // Either way the losing declaration is kept whole under the merged property's - // Unmodeled (merge.keepLosingDeclaration). + // Either way the passed-over declaration is kept whole under the merged + // property's Unmodeled (merge.keepLosingDeclaration). ConflictingRedecl = "openapi/conflicting-redeclaration" // DisjointVisibility reports one field restricted to lifecycle sets that // share nothing — readOnly against writeOnly — so no lifecycle admits it at // all. Both spellings raise it under this one code: one schema writing both // flags, and inline allOf entries whose intersection is empty. It is // neither of its neighbours: ConflictingRedecl keeps an arbitrary - // source-order winner, and DegradedConstruct lowers to a weaker shape, + // source-order choice, and DegradedConstruct lowers to a weaker shape, // whereas Visibility{None: true} is the exact answer and a shape the // IR already has. It is reported nonetheless, because a field no request or // response can carry is seldom what the document set out to say. @@ -316,8 +326,8 @@ const ( // most: a document's bytes or nodes (an overlay's included), alias nodes, an // enum's members (GitHub #75), external documents, what $refs and path // items copy. Fixed bounds cover load's schema $refs, chains through other - // documents and rule checks, detection's merges, and the declarations of one - // field the allOf merge judges. + // documents and rule checks, detection's merges, one field's declarations + // the allOf merge judges, and a format's $ref chain. // // None is the input's fault, unlike AliasAmplification's bomb. Each is an // error: the document is refused, validation stops, an enum loses its members @@ -354,9 +364,9 @@ const ( // still lowers, and nothing is lost unnamed (GitHub #577). PathItemRefCollision = "openapi/path-item-ref-collision" // IncompleteSecurityScheme reports a securitySchemes entry that omits the - // field naming its mechanism: `type`, or for type http the RFC 7235 `scheme` - // token. It lowers to a scheme of kind unresolved, keeping what it wrote, and - // a requirement naming it stands (GitHub #294). + // field naming its mechanism: `type`, or for type http the RFC 7235 + // `scheme` token. It lowers to a scheme of kind unresolved, keeping what it + // wrote, and a requirement naming it remains (GitHub #294). // // An error: OpenAPI requires both fields, and what the entry means is missing // (docs/compilers/openapi.md#validation), so a reader told only that it was @@ -461,11 +471,15 @@ const ( // UnhomedConstruct reports documentation a use writes beside a $ref where // the position has no docs to hold it, a callback's or a parameter's or // header's content entry's, kept verbatim on the node the use lowers to - // (docs/compilers/openapi.md#reference-object-siblings). Info: nothing is - // lost, and the entry leaves when the field arrives. + // (docs/compilers/openapi.md#reference-object-siblings); a format kept + // beside a contentEncoding naming another encoding, at the format; and a + // bound of the text a value of another kind or a number is written as, + // kept on the node or carrier that wrote it, at the bound + // (docs/compilers/openapi.md#string-formats). Info: nothing is lost, and + // the entry leaves when the field arrives. UnhomedConstruct = "openapi/unhomed-construct" // PartlessFormBody reports a multipart/form-data or url-encoded body whose - // schema stands for no object, so it names no part to send + // schema names no object, so it names no part to send // (docs/compilers/openapi.md#multipart-encoding). A warning: the body // lowers as declared, and the document likely says other than it means. PartlessFormBody = "openapi/partless-form-body" @@ -481,10 +495,11 @@ const ( // name than the compiler keeps, so the ones past the bound reached the IR in no // form at all. // - // Every collection here is bounded, and this one is over a key set the document - // chooses the size of. The bound is far above what any document writes by - // accident, so tripping it is either a generated file or a hostile one; the - // diagnostic is what keeps the discarded remainder from being a silent loss. + // Every collection here is bounded, and this one is over a key set the + // document chooses the size of. The bound is far above what any document + // writes by accident, so tripping it is either a generated file or a + // hostile one; the diagnostic is what keeps the discarded remainder from + // being an unreported loss. UnknownKeyBudget = "openapi/unknown-key-budget" // UnknownKeyUnreachable reports a key the parsed model reported as undeclared // whose value the raw mapping does not present, so nothing of it reached the @@ -564,15 +579,21 @@ const ( // keeps. Matching the expressions to path parameters is #640's. InvalidPathKey = "openapi/invalid-path-key" // InferredNullable reports a null the nullable-inference policy reads in - // where the document's version does not: a `nullable: true` in a 3.1 or 3.2 - // schema, beside a $ref, in a 3.0 schema with no type beside it or a keyword - // that excludes null, or on an allOf entry another conjunct contradicts, at - // the keyword; or keywords beside a $ref that admit null over a target that - // does not, at the schema writing them. Each is reported once, and each - // reference whose null rests on it is marked Inferred + // where the version does not: a `nullable: true` in a 3.1 or 3.2 schema, + // beside one $ref, in a 3.0 schema with no type beside it or a keyword or + // union excluding null, or on an allOf entry another conjunct contradicts, + // at the keyword; or value keywords admitting null beside one $ref over a + // target that does not, at the object writing them. Each is reported once, + // and each reference whose null rests on it is marked Inferred // (docs/compilers/openapi.md#nullable). Info: the reading is the document's // evident intent, and the mark keeps the declared one. InferredNullable = "openapi/inferred-nullable" + // UnwidenedNullable reports, at the keyword, a `nullable: true` beside a + // $ref that the nullable-inference policy leaves unwidened, as a conjunct + // beside it excludes null, naming each such conjunct + // (docs/compilers/openapi.md#nullable). Warning: the null its author wrote + // is on no reference, which changes what the wire admits. + UnwidenedNullable = "openapi/unwidened-nullable" // UnreadDialect reports a `$schema` on a schema resource root, or a // jsonSchemaDialect, naming a JSON Schema dialect the rule table has no // rows for, at it: the schemas it governs are read in the dialect their diff --git a/compilers/openapi/internal/diag/diag_test.go b/compilers/openapi/internal/diag/diag_test.go index b865cb5fe..818b09cfb 100644 --- a/compilers/openapi/internal/diag/diag_test.go +++ b/compilers/openapi/internal/diag/diag_test.go @@ -154,7 +154,7 @@ func codes() []string { diag.ValidationOnlyKeyword, diag.FalseSchema, diag.EmptyEnum, diag.DuplicateEnumValue, diag.RepeatedEntry, diag.NumericPrecision, diag.ExclusiveBoundForm, diag.InvalidStatusKey, diag.DuplicateStatusKey, diag.DuplicateParameter, diag.DuplicateServerName, - diag.InvalidMethodKey, diag.DegradedConstruct, + diag.InvalidMethodKey, diag.DegradedConstruct, diag.UnsatisfiableSchema, diag.CompositionLowering, diag.DynamicRefExpanded, diag.ConflictingRedecl, diag.DisjointVisibility, diag.AliasAmplification, diag.BudgetExceeded, @@ -170,7 +170,7 @@ func codes() []string { diag.UnknownKeyUnreachable, diag.UnknownKeyEntryAlreadyClaimed, diag.InvalidLocationKeyword, diag.InapplicableLocationKeyword, diag.MissingArrayItems, diag.LaterVersionConstruct, diag.ItemSchemaOnDocument, - diag.InvalidPathKey, diag.InferredNullable, diag.UnreadDialect, diag.InvalidItemsList, + diag.InvalidPathKey, diag.InferredNullable, diag.UnwidenedNullable, diag.UnreadDialect, diag.InvalidItemsList, diag.InferredDiscriminator, diag.InferredHTTPDate, diag.UndecidedIdempotency, diag.UndecidedReplacement, diag.UndecidedPagination, diff --git a/compilers/openapi/internal/diag/foreign.go b/compilers/openapi/internal/diag/foreign.go index a9a1ab84f..3224275b1 100644 --- a/compilers/openapi/internal/diag/foreign.go +++ b/compilers/openapi/internal/diag/foreign.go @@ -28,7 +28,7 @@ func OneLine(err error) string { // // It catches what barrier.Catch does and no more. The parser decodes on // goroutines of its own (docs/parser-library.md#goroutine-per-node), where a -// panic ends the process whatever barrier its caller stands behind. +// panic ends the process whatever barrier its caller sits behind. func Catch(f func()) (text string, panicked bool) { err := barrier.Catch(f) if err == nil { diff --git a/compilers/openapi/internal/doctree/json_internal_test.go b/compilers/openapi/internal/doctree/json_internal_test.go index 7fca14bdf..27d7cbc1a 100644 --- a/compilers/openapi/internal/doctree/json_internal_test.go +++ b/compilers/openapi/internal/doctree/json_internal_test.go @@ -291,9 +291,9 @@ func TestReadJSON_ReportsExactlyTheSurrogateEscapesAsHalves(t *testing.T) { } } -// TestReadJSON_ReadsAFaultAfterAnEscapeAsTheFaultAlone holds a string that holds an -// escape of a code unit outside D800 to DFFF, then a fault the decoder gives up -// at, to the verdict of the same string with the escape written as one +// TestReadJSON_ReadsAFaultAfterAnEscapeAsTheFaultAlone holds a string that +// holds an escape of a code unit outside D800 to DFFF, then a fault the decoder +// gives up at, to the answer for the same string with the escape written as one // character: the escape is never the reason, so it is never what Read quotes. func TestReadJSON_ReadsAFaultAfterAnEscapeAsTheFaultAlone(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/doctree/read_test.go b/compilers/openapi/internal/doctree/read_test.go index 02de5eebe..48fec2dd4 100644 --- a/compilers/openapi/internal/doctree/read_test.go +++ b/compilers/openapi/internal/doctree/read_test.go @@ -393,7 +393,7 @@ func TestRead_ACoreScalarIsRetaggedAndNeverRewritten(t *testing.T) { } // TestRead_AMergeKeyStillMergesAndAMergeValueIsText holds the one exception to -// the core schema, a << key, and its mirror: a << where a value stands is a +// the core schema, a << key, and its mirror: a << where a value is written is a // string. func TestRead_AMergeKeyStillMergesAndAMergeValueIsText(t *testing.T) { t.Parallel() @@ -535,9 +535,9 @@ func TestRead_ALineBreakYAML11EndsALineAtIsACharacter(t *testing.T) { assert.Empty(t, cmp.Diff(positions(read(t, twin).Root), positions(doc.Root)), "positions as the twin with a hyphen for each break") } -// TestRead_APlaceholderNeverShowsInATree holds the respelling invisible: whatever -// the text spells, no string of the tree holds a character the compiler chose -// to stand for another. +// TestRead_APlaceholderNeverShowsInATree holds the respelling invisible: +// whatever the text spells, no string of the tree holds a character the +// compiler chose to name another. func TestRead_APlaceholderNeverShowsInATree(t *testing.T) { t.Parallel() const tail = "\n version: \"1\"\n description: 'a" + nel + "b'\npaths: {}\n" diff --git a/compilers/openapi/internal/doctree/respell.go b/compilers/openapi/internal/doctree/respell.go index ee3ea2933..3163fcc97 100644 --- a/compilers/openapi/internal/doctree/respell.go +++ b/compilers/openapi/internal/doctree/respell.go @@ -31,9 +31,9 @@ const ( // respelling is what respell put in place of each trigger it respelled, for // restore to read back. type respelling struct { - breaks [3]rune // what stands for U+0085, U+2028 and U+2029, or 0 - slash rune // what, written twice, stands for an escaped slash, or 0 - pair rune // what stands for each backslash and u of a pair of escapes, or 0 + breaks [3]rune // what names U+0085, U+2028 and U+2029, or 0 + slash rune // what, written twice, names an escaped slash, or 0 + pair rune // what names each backslash and u of a pair of escapes, or 0 } // respell returns text as the parser reads it as YAML 1.2, one character for @@ -74,8 +74,8 @@ func respell(text []byte) ([]byte, respelling, []Directive) { out = replaceSlashes(out, respellingValue.slash) } if paired { - // Found again in out: a placeholder is wider in bytes than a break or an - // escaped slash it stands for, so the offsets text gave have moved. + // Found again in out: a placeholder is wider in bytes than a break or + // an escaped slash it names, so the offsets text gave have moved. respellingValue.pair = take(&free) out = replacePairs(out, pairsIn(out), respellingValue.pair) } @@ -258,8 +258,8 @@ func pairAt(text []byte, i int) bool { // replacePairs returns text with each pair of escapes starting at starts // written as p, the high half's hex digits, p twice, the low half's, and p: -// twelve characters for twelve, so every position after it stands. It returns -// text itself when p is 0. +// twelve characters for twelve, so every position after it is unmoved. It +// returns text itself when p is 0. func replacePairs(text []byte, starts []int, p rune) []byte { if p == 0 { return text @@ -431,9 +431,9 @@ func (r respelling) breakIn(s string) rune { // written as 1.1, padded with spaces to its width, which the parser reads as it // reads any document (docs/parser-library.md#yaml11-lexing), and every %YAML // 1.x directive the stream writes, in order. A line counts as a directive in -// the stream's prologue, where only blank lines, comments and directives stand -// above it, and after a document end marker. A major other than 1 is left for -// the parser to refuse, as YAML 1.2 asks. +// the stream's prologue, where only blank lines, comments and directives may +// appear above it, and after a document end marker. A major other than 1 is +// left for the parser to refuse, as YAML 1.2 asks. func directives(text []byte) ([]Directive, []byte) { if !bytes.Contains(text, []byte("%YAML")) { return nil, text diff --git a/compilers/openapi/internal/doctree/respell_internal_test.go b/compilers/openapi/internal/doctree/respell_internal_test.go index 88517e753..ce53abcba 100644 --- a/compilers/openapi/internal/doctree/respell_internal_test.go +++ b/compilers/openapi/internal/doctree/respell_internal_test.go @@ -427,7 +427,7 @@ func slicesOf(respellingValue respelling) []rune { return out } -// replacePlaceholder returns respellingValue with the placeholder from standing +// replacePlaceholder returns respellingValue with the placeholder from taking // as to. func replacePlaceholder(respellingValue respelling, from, to rune) respelling { for i, p := range respellingValue.breaks { diff --git a/compilers/openapi/internal/doctree/stream.go b/compilers/openapi/internal/doctree/stream.go index f7cecedcc..ca06545d0 100644 --- a/compilers/openapi/internal/doctree/stream.go +++ b/compilers/openapi/internal/doctree/stream.go @@ -25,7 +25,7 @@ const MaxStreamDocuments = 1024 // A stream with no such document yields the first one it holds, a null its // reader refuses, or a node of no kind when it holds none. A decoder error // before content is the input's. The search reads at most MaxStreamDocuments -// documents; past it the first one read stands. +// documents; past it the first one read is taken. func firstWithContent(dec *yaml.Decoder) (*yaml.Node, error) { var first *yaml.Node for range MaxStreamDocuments { diff --git a/compilers/openapi/internal/doctree/surrogate_pair_test.go b/compilers/openapi/internal/doctree/surrogate_pair_test.go index 801fab8c3..b7697da24 100644 --- a/compilers/openapi/internal/doctree/surrogate_pair_test.go +++ b/compilers/openapi/internal/doctree/surrogate_pair_test.go @@ -36,7 +36,7 @@ func TestRead_ASurrogatePairIsTheCharacterOnlyInADoubleQuotedScalar(t *testing.T // TestRead_ASurrogatePairAfterAnotherTriggerIsTheCharacter holds a pair written // after an escaped slash or a line-break character, whose placeholders are -// wider in bytes than what they stand for, to the character, the text before +// wider in bytes than what they name, to the character, the text before // it as written. func TestRead_ASurrogatePairAfterAnotherTriggerIsTheCharacter(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/document/components.go b/compilers/openapi/internal/document/components.go index fa04584bb..fd1c7ebe3 100644 --- a/compilers/openapi/internal/document/components.go +++ b/compilers/openapi/internal/document/components.go @@ -8,6 +8,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" "github.com/dexpace/morphic/compilers/openapi/internal/service" "github.com/dexpace/morphic/ir" ) @@ -42,9 +43,13 @@ func retainUnreferencedComponents(serviceContext service.Ctx) (ir.Unmodeled, []i if serviceContext.Reached(pointer) { continue } - _, keptDiags := annotation.PreserveNodeInto(&out, "openapi:"+ids.Scope("components", section, entry.Key), + kept, keptDiags := annotation.KeepNodeInto(&out, "openapi:"+ids.Scope("components", section, entry.Key), entry.Val, ir.ReasonNoIRHome, serviceContext.Place().At(pointer)) diags = append(diags, keptDiags...) + if kept { + // A discriminator's values are references wherever it is kept. + diags = append(diags, schema.KeepDiscriminatorsWithin(serviceContext.Ctx, nil, pointer)...) + } } } if view.Exhausted() { diff --git a/compilers/openapi/internal/document/dialect.go b/compilers/openapi/internal/document/dialect.go index 4ae10b4dd..2ece8bd11 100644 --- a/compilers/openapi/internal/document/dialect.go +++ b/compilers/openapi/internal/document/dialect.go @@ -15,12 +15,12 @@ import ( // keepJSONSchemaDialect keeps the document's jsonSchemaDialect verbatim on the // document, with an info. It is the default `$schema` of the document's Schema // Objects, and the IR models no dialect, so it is kept as a schema's own -// `$schema` is (annotation.DialectKeywords()): ReasonOutOfScope, read only for +// `$schema` is (annotation.DialectKeyword): ReasonOutOfScope, read only for // the dialect a schema naming none of its own is read in. func keepJSONSchemaDialect(serviceContext service.Ctx, unmodeled *ir.Unmodeled) []ir.Diagnostic { at := ids.Ptr("jsonSchemaDialect") node := nodeview.Child(serviceContext.Doc.GetRootNode(), "jsonSchemaDialect") - kept, diags := annotation.PreserveNodeInto(unmodeled, annotation.EntryKey("", "jsonSchemaDialect"), node, + kept, diags := annotation.KeepNodeInto(unmodeled, annotation.EntryKey("", "jsonSchemaDialect"), node, ir.ReasonOutOfScope, serviceContext.Place().At(at)) if !kept { return diags diff --git a/compilers/openapi/internal/document/sites.go b/compilers/openapi/internal/document/sites.go index 0c71b5f07..17e4d9a35 100644 --- a/compilers/openapi/internal/document/sites.go +++ b/compilers/openapi/internal/document/sites.go @@ -46,7 +46,7 @@ func documentUnknownKeys(serviceContext service.Ctx, unmodeled *ir.Unmodeled) [] // metadataObjectSite is one object around the document metadata that lowers to // no node of its own, so its x-* and its undeclared keys ride on ir.Document, // keyed under scope: the path from the root down to the object, empty for the -// root itself, which ir.Document stands for. A tag's path holds its index +// root itself, which ir.Document names. A tag's path holds its index // rather than its name, which is the pointer it is written at: OpenAPI's // requirement that tag names be unique is the document's to keep, not this // compiler's to rely on, and two tags spelled alike would silently leave one diff --git a/compilers/openapi/internal/ids/ids.go b/compilers/openapi/internal/ids/ids.go index 29eaaa102..1fd19879e 100644 --- a/compilers/openapi/internal/ids/ids.go +++ b/compilers/openapi/internal/ids/ids.go @@ -57,13 +57,14 @@ const ( // ComposedSpace holds what no schema or declaration in the source occupies: // distributed union variants and the Union a routed subtype composes // (docs/ir/models.md#composition-beside-a-union), the node a field's - // declarations compose or meet to, the identity of a field another model - // declares first, and a member its composition settles, beneath allOf at - // properties and its name + // declarations compose or intersect to, the identity of a field another + // model declares first, and a member its composition settles, beneath allOf + // at properties and its name // (docs/compilers/openapi.md#allof-redeclared-property). A variant's path - // ends in oneOf or anyOf and an index, a minted union's in that keyword, and - // a field's in properties and a name, so none meet. ForPointer yields only - // the openapi and anon spaces: no $ref resolves to a composed ID. + // ends in oneOf or anyOf and an index, a minted union's in that keyword, + // and a field's in properties and a name, so none coincide. ForPointer + // yields only the openapi and anon spaces: no $ref resolves to a composed + // ID. ComposedSpace compile.Space = "composed" ) @@ -160,12 +161,37 @@ func Namespaces(others ...DocumentIDNamespace) compile.Namespaces { // so it does. type DocumentIDNamespace struct { label string + // mintAt is the one position whose node is minted at mintKey rather + // than hoisted at it, where mints says so (Minting). + mintAt, mintKey jsontext.Pointer + mints bool } // In returns the document labelled label: its location, as the source's // directory reaches it. The empty label is the source's. func In(label string) DocumentIDNamespace { return DocumentIDNamespace{label: label} } +// Source reports whether d names the source document's IDs. +func (d DocumentIDNamespace) Source() bool { return d.label == "" } + +// Minting returns d where the schema at pointer lowers to a node minted in the +// composed namespace at key (ComposedType), whose coordinate no pointer +// spells, as a union variant conjoining the rest with one branch is. Every +// other pointer derives as in d. +func (d DocumentIDNamespace) Minting(pointer, key jsontext.Pointer) DocumentIDNamespace { + d.mintAt, d.mintKey, d.mints = pointer, key, true + return d +} + +// Minted returns the key the node of the schema at pointer is minted at in d +// (Minting), and false where it is hoisted at pointer. +func (d DocumentIDNamespace) Minted(pointer jsontext.Pointer) (jsontext.Pointer, bool) { + if !d.mints || pointer != d.mintAt { + return "", false + } + return d.mintKey, true +} + // space returns space as d names it: space itself for the source, else // qualified by d. func (d DocumentIDNamespace) space(space compile.Space) compile.Space { @@ -178,8 +204,12 @@ func (d DocumentIDNamespace) space(space compile.Space) compile.Space { // Coordinate returns the key the type registry interns the schema at pointer // in d under: the pointer itself in the source, and the pointer behind d's // qualifier elsewhere, which no pointer spells, so one pointer in two -// documents is two coordinates. +// documents is two coordinates; the minted ID for the position d mints in +// place of (Minting). func (d DocumentIDNamespace) Coordinate(pointer jsontext.Pointer) string { + if key, minted := d.Minted(pointer); minted { + return string(d.ComposedType(key)) + } if d.label == "" { return string(pointer) } @@ -196,11 +226,11 @@ func (d DocumentIDNamespace) AnonymousType(pointer jsontext.Pointer) ir.TypeID { return compile.TypeID(d.space(AnonymousSpace), string(pointer)) } -// ComposedType returns the stable ID of the node synthesized at pointer in d: -// a distributed union variant's branch, the keyword writing the union a routed +// ComposedType returns the stable ID of the node synthesized at pointer in d: a +// distributed union variant's branch, the keyword writing the union a routed // subtype composes (docs/ir/models.md#composition-beside-a-union), or the -// declaration naming a field whose declarations compose or meet to a node none -// of them wrote. +// declaration naming a field whose declarations compose or intersect to a node +// none of them wrote. func (d DocumentIDNamespace) ComposedType(pointer jsontext.Pointer) ir.TypeID { return compile.TypeID(d.space(ComposedSpace), string(pointer)) } @@ -384,8 +414,12 @@ func componentEntryName(pointer jsontext.Pointer) (string, bool) { // ForPointer returns the stable TypeID for a schema hoisted at pointer in d: // the named-component ID for a top-level component schema, the anonymous -// (hoisted-inline) ID otherwise. +// (hoisted-inline) ID otherwise, and the composed one d mints for the +// position it mints in place of (Minting). func (d DocumentIDNamespace) ForPointer(pointer jsontext.Pointer) ir.TypeID { + if key, minted := d.Minted(pointer); minted { + return d.ComposedType(key) + } if schemaSpace(pointer) == OpenAPISpace { return d.NamedType(pointer) } diff --git a/compilers/openapi/internal/ids/ids_test.go b/compilers/openapi/internal/ids/ids_test.go index 8636fd940..bf8099996 100644 --- a/compilers/openapi/internal/ids/ids_test.go +++ b/compilers/openapi/internal/ids/ids_test.go @@ -298,6 +298,34 @@ func TestDocumentIDNamespace_QualifiesEachSpaceByItsLabel(t *testing.T) { assert.NotEqual(t, other.Coordinate(pointer), ids.In("dir").Coordinate(pointer)) } +// TestDocumentIDNamespace_MintsOnePositionInPlace holds a namespace minting +// one position to the composed ID of its key, for that position's node and +// coordinate alone, in the source and another document, every other pointer +// deriving as before, and the document what it was. +func TestDocumentIDNamespace_MintsOnePositionInPlace(t *testing.T) { + t.Parallel() + const at, key = "/components/schemas/P", "/components/schemas/P/oneOf/0" + for _, namespace := range []ids.DocumentIDNamespace{{}, ids.In("dir/a.yaml")} { + minting := namespace.Minting(at, key) + assert.Equal(t, namespace.ComposedType(key), minting.ForPointer(at)) + assert.Equal(t, string(namespace.ComposedType(key)), minting.Coordinate(at), "a coordinate no pointer spells") + minted, ok := minting.Minted(at) + assert.True(t, ok) + assert.Equal(t, jsontext.Pointer(key), minted) + _, ok = minting.Minted(key) + assert.False(t, ok, "the key is no position minted in place") + _, ok = namespace.Minted(at) + assert.False(t, ok, "a namespace minting nothing mints nothing") + for _, pointer := range []jsontext.Pointer{key, "/components/schemas/Q", at + "/properties/a"} { + assert.Equal(t, namespace.ForPointer(pointer), minting.ForPointer(pointer), pointer) + assert.Equal(t, namespace.Coordinate(pointer), minting.Coordinate(pointer), pointer) + } + assert.Equal(t, namespace.Source(), minting.Source()) + } + assert.True(t, ids.DocumentIDNamespace{}.Source()) + assert.False(t, ids.In("dir/a.yaml").Source()) +} + // TestDeclarationHint_PrefersTheComponentName pins why a hint is not taken from // the use site: a $ref'd component lowers once, at its declaration, so a hint // derived from whichever reference lowered first would name the one shared node diff --git a/compilers/openapi/internal/jsonpath/bounds_test.go b/compilers/openapi/internal/jsonpath/bounds_test.go index 90c47a145..3d170dbcd 100644 --- a/compilers/openapi/internal/jsonpath/bounds_test.go +++ b/compilers/openapi/internal/jsonpath/bounds_test.go @@ -62,11 +62,11 @@ func paths(got []jsonpath.Located) []string { return out } -// TestSelect_ReadsAnAliasAndAMergedMemberAsTheValueTheyStandFor pins what the +// TestSelect_ReadsAnAliasAndAMergedMemberAsTheValueTheyName pins what the // evaluator sees of the YAML a source writes: an alias is what it names, a // merged member is a member of the mapping that merges it, and the merge key // itself is no member. Each node is returned once through each path to it. -func TestSelect_ReadsAnAliasAndAMergedMemberAsTheValueTheyStandFor(t *testing.T) { +func TestSelect_ReadsAnAliasAndAMergedMemberAsTheValueTheyName(t *testing.T) { t.Parallel() root := readTree(t, "a: &x {p: 1}\nb: *x\nc: {<<: *x, q: 2}\n") @@ -207,7 +207,7 @@ func TestSelect_DescendsWithoutRecursion(t *testing.T) { } // TestSelect_BuildsAResultsPathsInLinearMemory pins that a result's path is a -// link to its parent's and not a copy: allocations over a chain of 4n are +// pointer to its parent's and not a copy: allocations over a chain of 4n are // about four times those over n, where copied paths would be sixteen times. func TestSelect_BuildsAResultsPathsInLinearMemory(t *testing.T) { query, err := jsonpath.Parse("$..a") diff --git a/compilers/openapi/internal/jsonpath/compliance_test.go b/compilers/openapi/internal/jsonpath/compliance_test.go index 63cac5881..44bc074b6 100644 --- a/compilers/openapi/internal/jsonpath/compliance_test.go +++ b/compilers/openapi/internal/jsonpath/compliance_test.go @@ -179,7 +179,7 @@ func checkCase(t *testing.T, tc ctsCase) error { return fmt.Errorf("no listed answer matches (-want +got), one block per answer:\n%s", strings.Join(diffs, "\n--\n")) } -// jsonTree builds the tree doc stands for as the compiler's reader builds one +// jsonTree builds the tree doc names as the compiler's reader builds one // from a JSON text: mappings and sequences tagged !!map and !!seq, strings // !!str, and numbers, booleans and null by what they are. A name written twice // stays twice, for the evaluator to read as its last. @@ -213,7 +213,7 @@ func jsonTree(t testing.TB, doc []byte) *yaml.Node { return root } -// tokenNode returns the node an opening or a scalar token stands for. +// tokenNode returns the node an opening or a scalar token names. func tokenNode(tok jsontext.Token) *yaml.Node { switch tok.Kind() { case '{': diff --git a/compilers/openapi/internal/jsonpath/doc.go b/compilers/openapi/internal/jsonpath/doc.go index 89dbb211a..8c87cccdb 100644 --- a/compilers/openapi/internal/jsonpath/doc.go +++ b/compilers/openapi/internal/jsonpath/doc.go @@ -2,7 +2,7 @@ // Licensed under the MIT License. See LICENSE in the repository root for details. // Package jsonpath evaluates RFC 9535 queries over the JSON value a YAML tree -// stands for: an alias reads as the node it names, a `<<` merge key's members +// names: an alias reads as the node it names, a `<<` merge key's members // as members of the mapping merging them, and a scalar as the compiler reads // it. It is how the compiler reads an overlay's selectors. // diff --git a/compilers/openapi/internal/jsonpath/eval.go b/compilers/openapi/internal/jsonpath/eval.go index 61119c5a4..9d81fe366 100644 --- a/compilers/openapi/internal/jsonpath/eval.go +++ b/compilers/openapi/internal/jsonpath/eval.go @@ -13,7 +13,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" ) -// reader reads the value a tree stands for within a budget: the view it +// reader reads the value a tree names within a budget: the view it // reads mappings through, the steps it spends and the most nodes a nodelist // holds. It compares values too, which is reading two at once. type reader struct { diff --git a/compilers/openapi/internal/jsonpath/eval_test.go b/compilers/openapi/internal/jsonpath/eval_test.go index 388f5759c..5f5e7eadc 100644 --- a/compilers/openapi/internal/jsonpath/eval_test.go +++ b/compilers/openapi/internal/jsonpath/eval_test.go @@ -283,7 +283,7 @@ func TestSelect_RefusesAMergeChainWhereverItIsRead(t *testing.T) { } // TestSelect_SpendsNoStepPastItsBudget pins that any budget below what a query -// needs is refused with ErrSteps, wherever the evaluation stands when it runs +// needs is refused with ErrSteps, wherever the evaluation is when it runs // out, and that the need itself is enough. Scalars long enough to cost steps // to read and to compare are among the values. func TestSelect_SpendsNoStepPastItsBudget(t *testing.T) { @@ -376,7 +376,7 @@ func TestSelect_HoldsEveryLiveNodelistToOneBound(t *testing.T) { } // TestSelect_ReadsAnAliasNamingNothingAsNoValue pins a tree no parse builds: -// an alias whose anchor is missing is no node, wherever it stands. +// an alias whose anchor is missing is no node, wherever it sits. func TestSelect_ReadsAnAliasNamingNothingAsNoValue(t *testing.T) { t.Parallel() dangling := func() *yaml.Node { return &yaml.Node{Kind: yaml.AliasNode} } diff --git a/compilers/openapi/internal/jsonpath/iregexp.go b/compilers/openapi/internal/jsonpath/iregexp.go index 21e5146a6..7e06fab8f 100644 --- a/compilers/openapi/internal/jsonpath/iregexp.go +++ b/compilers/openapi/internal/jsonpath/iregexp.go @@ -53,7 +53,7 @@ type translation struct { size int } -// Why no string matches a branch in which an anchor stands where Go's engine +// Why no string matches a branch in which an anchor sits where Go's engine // reads it, and the class a writer meaning the character writes instead. const ( endAnchored = "$ anchors the end of the string, and a character must follow it; write [$] to match the character" @@ -323,7 +323,7 @@ func (t *translator) escapeOutside() bool { // escape reads an escape after its backslash: a single character escape, // returned as its character, or a category escape, returned as the Go class -// items it stands for. +// items it names. func (t *translator) escape() (items string, char rune, ok bool) { if t.pos >= len(t.src) { return "", 0, false diff --git a/compilers/openapi/internal/jsonpath/parse.go b/compilers/openapi/internal/jsonpath/parse.go index 28dff9263..83317484e 100644 --- a/compilers/openapi/internal/jsonpath/parse.go +++ b/compilers/openapi/internal/jsonpath/parse.go @@ -229,7 +229,7 @@ func (s *scanner) shorthand() (string, error) { return s.text[start:s.pos], nil } -// isNameChar reports whether r may stand in a member-name-shorthand. +// isNameChar reports whether r may appear in a member-name-shorthand. func isNameChar(r rune) bool { return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r >= 0x80 && r <= 0xD7FF || r >= 0xE000 && r <= 0x10FFFF diff --git a/compilers/openapi/internal/jsonpath/path.go b/compilers/openapi/internal/jsonpath/path.go index 8509fc130..d41d60ddc 100644 --- a/compilers/openapi/internal/jsonpath/path.go +++ b/compilers/openapi/internal/jsonpath/path.go @@ -11,14 +11,14 @@ import ( ) // Path is the location of one node of a result, from the root of the value a -// query read. It is a link to its parent's path, so a nodelist one walk finds -// holds a link a node however deep they lie; walks from several starts each +// query read. It points to its parent's path, so a nodelist one walk finds +// holds one step a node however deep they lie; walks from several starts each // build their own (GitHub #1960). The zero Path is the root's. -type Path struct{ last *link } +type Path struct{ last *pathStep } -// link is one step of a Path and the path to its holder. -type link struct { - parent *link +// pathStep is one step of a Path and the path to its holder. +type pathStep struct { + parent *pathStep name string index int member bool @@ -34,12 +34,12 @@ type Step struct { // child returns the path of the member name of the node at p. func (p Path) child(name string) Path { - return Path{last: &link{parent: p.last, name: name, member: true}} + return Path{last: &pathStep{parent: p.last, name: name, member: true}} } // element returns the path of the element at index i of the array at p. func (p Path) element(i int) Path { - return Path{last: &link{parent: p.last, index: i}} + return Path{last: &pathStep{parent: p.last, index: i}} } // Parent returns the path of the node holding the one at p and the step from @@ -51,8 +51,8 @@ func (p Path) Parent() (Path, Step, bool) { if p.last == nil { return Path{}, Step{}, false } - link := p.last - return Path{last: link.parent}, Step{Name: link.name, Index: link.index, IsObjectMemberStep: link.member}, true + last := p.last + return Path{last: last.parent}, Step{Name: last.name, Index: last.index, IsObjectMemberStep: last.member}, true } // String returns p as RFC 9535 section 2.7 normalizes it: `$`, then each diff --git a/compilers/openapi/internal/jsonpath/query.go b/compilers/openapi/internal/jsonpath/query.go index 765f46bab..977f498d6 100644 --- a/compilers/openapi/internal/jsonpath/query.go +++ b/compilers/openapi/internal/jsonpath/query.go @@ -19,7 +19,7 @@ import ( // the list a segment reads and the one it builds, and those of every query a // filter it is in evaluates. Each node costs a step, so the steps bound them // too, but a step is cheap and a node held is not: this bounds the nodes a -// query holds however deep its filters nest. It does not count the links of +// query holds however deep its filters nest. It does not count the steps of // their paths, which nested descendant segments build in proportion to their // steps, so such a query can hold gigabytes within its budget (GitHub #1960). const MaxResults = 1 << 22 @@ -97,7 +97,7 @@ type Located struct { Node *yaml.Node } -// Select evaluates q over the JSON value root stands for: an alias reads as +// Select evaluates q over the JSON value root names: an alias reads as // what it names and a merged member as a member of the mapping merging it // (view). Every node visited, compared or returned spends a step of steps; // ErrSteps reports them spent, ErrMergeBound a mapping whose merges pass the diff --git a/compilers/openapi/internal/load/aside.go b/compilers/openapi/internal/load/aside.go index c0293286d..f1a858350 100644 --- a/compilers/openapi/internal/load/aside.go +++ b/compilers/openapi/internal/load/aside.go @@ -54,10 +54,10 @@ func (a *aside) spoil(node *yaml.Node) { *node = yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Style: yaml.FlowStyle, Line: node.Line, Column: node.Column} } -// standIn has the mapping node read as a Reference Object whose $ref is an -// empty sequence, as spoil leaves one, until restore. -func (a *aside) standIn(node *yaml.Node) { - a.keep(node, func() { a.standIn(node) }) +// readAsEmptyReference has the mapping node read as a Reference Object whose +// $ref is an empty sequence, as spoil leaves one, until restore. +func (a *aside) readAsEmptyReference(node *yaml.Node) { + a.keep(node, func() { a.readAsEmptyReference(node) }) node.Content = []*yaml.Node{ {Kind: yaml.ScalarNode, Tag: "!!str", Value: "$ref", Line: node.Line, Column: node.Column}, {Kind: yaml.SequenceNode, Tag: "!!seq", Style: yaml.FlowStyle, Line: node.Line, Column: node.Column}, diff --git a/compilers/openapi/internal/load/bindings.go b/compilers/openapi/internal/load/bindings.go index e1313ded0..0eaf0d29e 100644 --- a/compilers/openapi/internal/load/bindings.go +++ b/compilers/openapi/internal/load/bindings.go @@ -204,7 +204,7 @@ func bindingDiags(sites places, table *reftable.ReferenceTargetTable) []ir.Diagn "unresolved $ref %q: %s", reference.Hop.Ref, reference.Hop.Why())) } } - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { if referenceSite.Hop.Status == reftable.Unresolved { diags = append(diags, diag.Newf(ir.SeverityError, diag.UnresolvedRef, sites.position(referenceSite.Site), "unresolved %s %q: %s", referenceSite.Keyword, referenceSite.Hop.Ref, referenceSite.Hop.Why())) @@ -212,8 +212,7 @@ func bindingDiags(sites places, table *reftable.ReferenceTargetTable) []ir.Diagn } for _, loop := range table.Loops() { diags = append(diags, diag.Newf(ir.SeverityError, diag.CyclicRef, sites.position(loop.Site), - "cyclic $ref: the chain of $refs through %s comes back to where it started and never reaches %s", - spellLoop(loop, table), reachesNone(loop.Kind))) + "cyclic $ref: %s", loopAdvice(loop, spellLoop(loop, table)))) } at := sites.position(reftable.DocumentPointer{}) if table.Exhausted() { @@ -230,13 +229,25 @@ func bindingDiags(sites places, table *reftable.ReferenceTargetTable) []ir.Diagn return diags } -// reachesNone names what a loop of $refs read as kind never reaches: a schema, -// for a loop of schema $refs, or an object of that kind. -func reachesNone(kind reftable.RefKind) string { - if kind == 0 { - return "a schema" +// loopAdvice says what is wrong with a loop of $refs whose members are named +// by members, and what to do. +func loopAdvice(loop reftable.Loop, members string) string { + alone := len(loop.Members) == 1 + if loop.Kind == 0 { + if alone { + return members + " refers only to itself, by $ref or by an allOf of one $ref, so it constrains " + + "no value; give it a type, properties or another constraint" + } + return members + " refer only to each other, by $ref or by an allOf of one $ref, so none of them " + + "constrains a value; give one of them a type, properties or another constraint" + } + kind := loop.Kind.String() + if alone { + return members + ", a " + kind + ", refers only to itself by $ref, so it defines none; " + + "give it a definition of its own" } - return "a " + kind.String() + return members + ", each a " + kind + ", refer only to each other by $ref, so none of them defines one; " + + "give one of them a definition of its own" } // buildFailures reports each landing no schema could be built for, and each diff --git a/compilers/openapi/internal/load/bindings_corpus_internal_test.go b/compilers/openapi/internal/load/bindings_corpus_internal_test.go index 84a572a76..788b83e6f 100644 --- a/compilers/openapi/internal/load/bindings_corpus_internal_test.go +++ b/compilers/openapi/internal/load/bindings_corpus_internal_test.go @@ -65,7 +65,7 @@ func assertBound(t *testing.T, b *typed.Bindings, model any, at string) { t.Helper() if js, ok := model.(*schemaRef); ok { if js.IsReference() { - _, bound := b.Entry(js) + _, bound := b.ReferenceSiteAt(js) assert.True(t, bound, "%s: the $ref", at) } return diff --git a/compilers/openapi/internal/load/bindings_internal_test.go b/compilers/openapi/internal/load/bindings_internal_test.go index 46e092fb5..500ff7ad4 100644 --- a/compilers/openapi/internal/load/bindings_internal_test.go +++ b/compilers/openapi/internal/load/bindings_internal_test.go @@ -101,7 +101,7 @@ func TestBindingDiags_ReportsAFailedRefOnceWhereItIsWrittenAtEveryBudget(t *test cfg := reftable.Config{Self: "spec.yaml", Open: func(string, string) (*yaml.Node, error) { return &other, nil }} want := []ir.Diagnostic{diag.Newf(ir.SeverityError, diag.UnresolvedRef, ir.Provenance{Source: 1, Pointer: "/Y"}, `unresolved $ref "#/Missing": it names nothing in the document it points into`)} - reported, silent := 0, 0 + reported, unreported := 0, 0 // Every limit up to the first the reading fits in, which a table so small // reaches well within the cap. for limit, exhausted := 1, true; exhausted; limit++ { @@ -121,14 +121,14 @@ func TestBindingDiags_ReportsAFailedRefOnceWhereItIsWrittenAtEveryBudget(t *test } assert.Equal(t, table.Exhausted(), crossed, "a cut table reports the budget, limit %d", limit) if len(failed) == 0 { - silent++ + unreported++ continue } reported++ assert.Empty(t, cmp.Diff(want, failed), "limit %d", limit) } assert.Positive(t, reported, "some limit cut short of the full table reports the failure") - assert.Positive(t, silent, "and some limit cuts the table before the walk that reads it") + assert.Positive(t, unreported, "and some limit cuts the table before the walk that reads it") } // TestBindingDiags_NamesALoopsMembersByTheirDocument pins how a loop is @@ -157,15 +157,51 @@ func TestBindingDiags_NamesALoopsMembersByTheirDocument(t *testing.T) { got = append(got, fmt.Sprintf("%d%s: %s", diagnostic.Provenance.Source, diagnostic.Provenance.Pointer, diagnostic.Message)) } - const rest = " comes back to where it started and never reaches a schema" + const ( + alone = " refers only to itself, by $ref or by an allOf of one $ref, so it constrains no value; give it a type, properties or another constraint" + together = " refer only to each other, by $ref or by an allOf of one $ref, so none of them constrains a value; give one of them a type, properties or another constraint" + ) assert.Empty(t, cmp.Diff([]string{ - "0/components/schemas/B: cyclic $ref: the chain of $refs through #/components/schemas/B" + rest, - "0/components/schemas/C: cyclic $ref: the chain of $refs through #/components/schemas/C, #/P in other.yaml" + rest, - "1/Q: cyclic $ref: the chain of $refs through #/Q, #/R in third.yaml" + rest, - "1/X: cyclic $ref: the chain of $refs through #/X, #/Y" + rest, + "0/components/schemas/B: cyclic $ref: #/components/schemas/B" + alone, + "0/components/schemas/C: cyclic $ref: #/components/schemas/C, #/P in other.yaml" + together, + "1/Q: cyclic $ref: #/Q, #/R in third.yaml" + together, + "1/X: cyclic $ref: #/X, #/Y" + together, }, got), "in the order of where each is reported") } +// TestLoopAdvice_SaysWhatToDoForEachKindAndSize pins the wording of a loop's +// report for a schema and for another object, alone and with others: it names +// the members, says they refer only to each other, and says what to give one. +func TestLoopAdvice_SaysWhatToDoForEachKindAndSize(t *testing.T) { + t.Parallel() + one := []reftable.DocumentPointer{{Pointer: "/a"}} + two := []reftable.DocumentPointer{{Pointer: "/a"}, {Pointer: "/b"}} + tests := []struct { + name string + loop reftable.Loop + members string + want string + }{ + {"a schema alone", reftable.Loop{Members: one}, "#/a", + "#/a refers only to itself, by $ref or by an allOf of one $ref, so it constrains no value; " + + "give it a type, properties or another constraint"}, + {"schemas together", reftable.Loop{Members: two}, "#/a, #/b", + "#/a, #/b refer only to each other, by $ref or by an allOf of one $ref, so none of them " + + "constrains a value; give one of them a type, properties or another constraint"}, + {"a response alone", reftable.Loop{Kind: reftable.RefResponse, Members: one}, "#/a", + "#/a, a response, refers only to itself by $ref, so it defines none; give it a definition of its own"}, + {"responses together", reftable.Loop{Kind: reftable.RefResponse, Members: two}, "#/a, #/b", + "#/a, #/b, each a response, refer only to each other by $ref, so none of them defines one; " + + "give one of them a definition of its own"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, loopAdvice(tt.loop, tt.members)) + }) + } +} + // TestBindSchemas_AChainEndsInTheDocumentItEndsIn pins where the bindings end a // schema $ref's chain: in the document its last hop lands in, not the one it // first leaves for, on a schema built for the landing where the model holds @@ -189,7 +225,7 @@ func TestBindSchemas_AChainEndsInTheDocumentItEndsIn(t *testing.T) { } { js, ok := doc.Components.Schemas.Get(name) require.True(t, ok, name) - referenceSite, ok := bindings.Entry(js) + referenceSite, ok := bindings.ReferenceSiteAt(js) require.True(t, ok, name) require.Equal(t, reftable.Resolved, referenceSite.Chain.Status, name) assert.Equal(t, want.doc, table.Document(referenceSite.Chain.End.Doc).Name, name) diff --git a/compilers/openapi/internal/load/dialects.go b/compilers/openapi/internal/load/dialects.go index 0251a77f7..7f066f8a8 100644 --- a/compilers/openapi/internal/load/dialects.go +++ b/compilers/openapi/internal/load/dialects.go @@ -155,7 +155,7 @@ func dialectRuleOf(rules specrules.SchemaRules, uri string) reftable.DialectRule rule := reftable.DialectRule{Keyword: rules.Identifier(), Definitions: rules.Takes("definitions", specrules.Map), Dependencies: rules.Defines("dependencies"), Tuples: rules.Takes("items", specrules.List), Recursive: rules.Defines("$recursiveRef"), IgnoresRefFields: rules.IgnoresRefFields(), - NamesNone: !specrules.NamesDialect(uri)} + NamesNone: !specrules.NamesDialect(uri), Schema: rules} rule.Fragments = rule.Keyword != "" && !rules.Defines("$anchor") rule.PlainFragments = rules.Formatted(rule.Keyword, specrules.PlainNameURI) rule.PlainNames = rules.Formatted("$anchor", specrules.PlainName) diff --git a/compilers/openapi/internal/load/dialects_internal_test.go b/compilers/openapi/internal/load/dialects_internal_test.go index a864f30ea..ddaf2360d 100644 --- a/compilers/openapi/internal/load/dialects_internal_test.go +++ b/compilers/openapi/internal/load/dialects_internal_test.go @@ -233,7 +233,7 @@ func TestReadDialects_WarnsOfADocumentReadUnderTwoNamesOnce(t *testing.T) { } // TestReadDialects_ReadsNothingOfADocumentNoSourceEntryHolds pins that a -// document only a pass that did not stand read, which +// document only a pass that did not remain read, which // LoadedOpenAPIDocument.Sources leaves out, draws no warning: its `$schema` // governs nothing the result holds, and no entry would place the finding. func TestReadDialects_ReadsNothingOfADocumentNoSourceEntryHolds(t *testing.T) { diff --git a/compilers/openapi/internal/load/documentbudget_internal_test.go b/compilers/openapi/internal/load/documentbudget_internal_test.go index 615175a3d..ddc8b8f7d 100644 --- a/compilers/openapi/internal/load/documentbudget_internal_test.go +++ b/compilers/openapi/internal/load/documentbudget_internal_test.go @@ -120,7 +120,7 @@ func TestLoad_ASchemaChainIsReadToTheDocumentBudget(t *testing.T) { got, _ := loadExternal(t, t.TempDir(), schemaRoot(srv.URL+"/0.yaml#/x"), Options{MaxExternalDocuments: budget.AtMost(5)}) assert.Equal(t, int32(5), requests.Load(), "exactly the budget is read") - entry, ok := got.Bindings.Table().Entry(reftable.DocumentPointer{Pointer: "/components/schemas/A"}) + entry, ok := got.Bindings.Table().ReferenceSiteAt(reftable.DocumentPointer{Pointer: "/components/schemas/A"}) require.True(t, ok) assert.Equal(t, reftable.Resolved, entry.Hop.Status, "the first document is read") assert.Equal(t, reftable.Unresolved, entry.Chain.Status, "the chain is not followed past the budget") diff --git a/compilers/openapi/internal/load/external.go b/compilers/openapi/internal/load/external.go index c0027f4da..8526f16f0 100644 --- a/compilers/openapi/internal/load/external.go +++ b/compilers/openapi/internal/load/external.go @@ -88,7 +88,7 @@ func (e external) reachOf(from string) compilers.AddressSpace { // the asker's own where no read gave it or its read was bounded no wider. Else // the document is judged as a target, by the most private space its read can // have dialled (answer.bound); where that read stated none, a read wider than -// reach is judged again at reach (verdict), and one no wider is refused, as +// reach is judged again at reach (judgement), and one no wider is refused, as // the reader did not say. func (e external) admits(ctx context.Context, id, location string, a answer, reach compilers.AddressSpace) error { switch { @@ -101,18 +101,18 @@ func (e external) admits(ctx context.Context, id, location string, a answer, rea case !wider(a.reach, reach): return unsaid(id) } - return e.read.verdict(id, reach, func() (compilers.AddressSpace, error) { - return e.verdict(ctx, id, location, reach) + return e.read.judgementAt(id, reach, func() (compilers.AddressSpace, error) { + return e.judgement(ctx, id, location, reach) }) } -// verdict reads the document id at location as an asker bounded by reach +// judgement reads the document id at location as an asker bounded by reach // would, to judge it for that asker alone, and returns the bound the read // stated, or why the asker is refused: its read's own failure among them. // What it reads is dropped, as the document's content, space and place in the // document budget stay its first read's, so the read is not charged; one is -// made per reach a document is judged at (externalReads.verdict). -func (e external) verdict(ctx context.Context, id, location string, reach compilers.AddressSpace) (compilers.AddressSpace, error) { +// made per reach a document is judged at (externalReads.judgementAt). +func (e external) judgement(ctx context.Context, id, location string, reach compilers.AddressSpace) (compilers.AddressSpace, error) { got, err := e.request(ctx, location, reach) if err != nil { return compilers.SpaceUnstated, readFailure(e.opts, id, err, reach) diff --git a/compilers/openapi/internal/load/external_internal_test.go b/compilers/openapi/internal/load/external_internal_test.go index 8f9d64121..2eadd5ca8 100644 --- a/compilers/openapi/internal/load/external_internal_test.go +++ b/compilers/openapi/internal/load/external_internal_test.go @@ -52,7 +52,7 @@ func TestExternal_DocumentOfAMissingFilePassesTheReadersErrorThrough(t *testing. } // TestExternal_DocumentPreparesTheFile pins the success path: the tree a file -// parses to comes back with its anchors released while its alias still stands +// parses to comes back with its anchors released while its alias still holds // for what it named, recorded under the name it was asked for by. func TestExternal_DocumentPreparesTheFile(t *testing.T) { t.Parallel() @@ -63,7 +63,7 @@ func TestExternal_DocumentPreparesTheFile(t *testing.T) { tree, err := ext.document(t.Context(), path, "spec.yaml") require.NoError(t, err) - assertAnchorsReleasedAliasesStand(t, tree) + assertAnchorsReleasedAliasesRemain(t, tree) recorded, ok := ext.read.preparedFor(path) require.True(t, ok) assert.Same(t, tree, recorded) @@ -116,7 +116,7 @@ func TestExternal_DocumentReadsAFileOnce(t *testing.T) { again, err := ext.document(t.Context(), path, "spec.yaml") require.NoError(t, err, "served from the first read, not opened") - assert.Same(t, first, again, "the tree prepared the first time stands") + assert.Same(t, first, again, "the tree prepared the first time remains") } // TestExternal_PrepareRefusesBytesThatDoNotParse pins that bytes which will @@ -246,7 +246,7 @@ func newTestServer(t *testing.T, handler http.HandlerFunc) *httptest.Server { } // TestExternal_DocumentFetchesAURL pins the network half of the success path: -// the tree the body parses to, anchors released and aliases standing, +// the tree the body parses to, anchors released and aliases left in place, // recorded under the request's own URL. func TestExternal_DocumentFetchesAURL(t *testing.T) { t.Parallel() @@ -260,7 +260,7 @@ func TestExternal_DocumentFetchesAURL(t *testing.T) { tree, err := ext.document(t.Context(), key, "spec.yaml") require.NoError(t, err) - assertAnchorsReleasedAliasesStand(t, tree) + assertAnchorsReleasedAliasesRemain(t, tree) _, ok := ext.read.preparedFor(key) assert.True(t, ok, "recorded under the request's own URL") } @@ -378,11 +378,11 @@ func TestExternal_ReadsPastTheDocumentBudgetAreRefusedUnread(t *testing.T) { assert.Equal(t, int32(1), fetches.Load(), "nothing past the budget is fetched") } -// assertAnchorsReleasedAliasesStand walks every node reachable from root and +// assertAnchorsReleasedAliasesRemain walks every node reachable from root and // fails if any carries an anchor name, while requiring at least one alias node // whose Alias still points at its target — the two halves of "released, but an -// alias still stands for what it named" that a prepared tree must show. -func assertAnchorsReleasedAliasesStand(t *testing.T, root *yaml.Node) { +// alias still names what it named" that a prepared tree must show. +func assertAnchorsReleasedAliasesRemain(t *testing.T, root *yaml.Node) { t.Helper() var sawAlias bool stack := []*yaml.Node{root} @@ -392,7 +392,7 @@ func assertAnchorsReleasedAliasesStand(t *testing.T, root *yaml.Node) { assert.Empty(t, node.Anchor, "anchors are released before the tree is recorded") if node.Kind == yaml.AliasNode { sawAlias = true - assert.NotNil(t, node.Alias, "an alias still stands for its target") + assert.NotNil(t, node.Alias, "an alias still names its target") } stack = append(stack, node.Content...) } diff --git a/compilers/openapi/internal/load/json_internal_test.go b/compilers/openapi/internal/load/json_internal_test.go index 511bc2370..be4d4af9b 100644 --- a/compilers/openapi/internal/load/json_internal_test.go +++ b/compilers/openapi/internal/load/json_internal_test.go @@ -95,7 +95,7 @@ func TestDecode_ReturnsALoneSurrogateAsItIs(t *testing.T) { // YAML's to read, so the documents after the first are still reported as // dropped, and a comment still ends a document. A solidus escape, which only // the JSON reader accepts, tells the two reads apart: the source that writes -// one is read when it stands alone and refused as YAML when a comment follows. +// one is read when it is alone and refused as YAML when a comment follows. func TestDecode_AJSONTextBesideAStreamIsReadAsYAML(t *testing.T) { t.Parallel() const first = `{"openapi":"3.1.0","info":{"title":"T","version":"1"},"paths":{}}` diff --git a/compilers/openapi/internal/load/load.go b/compilers/openapi/internal/load/load.go index ae38b7d38..94c19fa34 100644 --- a/compilers/openapi/internal/load/load.go +++ b/compilers/openapi/internal/load/load.go @@ -289,7 +289,7 @@ func sourceChecks(ctx context.Context, sites places, doc *soa.OpenAPI, sibs Sibl } // defaultIndex indexes a decoded tree under the compiler's node bound. It is -// what Options.buildIndex stands in for when a caller leaves it nil, which +// what Options.buildIndex takes the place of when a caller leaves it nil, which // everything outside this package's tests does. func defaultIndex(ctx context.Context, root *yaml.Node) sourcetreestats.Measurements { return sourcetreestats.Build(ctx, root, sourcetreestats.MaxIndexedNodes) diff --git a/compilers/openapi/internal/load/load_rootdefs_internal_test.go b/compilers/openapi/internal/load/load_rootdefs_internal_test.go index 14b696d9a..6b4301abc 100644 --- a/compilers/openapi/internal/load/load_rootdefs_internal_test.go +++ b/compilers/openapi/internal/load/load_rootdefs_internal_test.go @@ -45,7 +45,7 @@ func TestLoad_ARootDefinitionResolvesAsTheResolverReadsIt(t *testing.T) { } { property, ok := a.GetSchema().GetProperties().Get(c.property) require.True(t, ok, c.property) - entry, ok := got.Bindings.Entry(property) + entry, ok := got.Bindings.ReferenceSiteAt(property) require.True(t, ok, "%s is bound", c.property) assert.Equal(t, reftable.Resolved, entry.Hop.Status, c.property) assert.Equal(t, reftable.DocumentPointer{Pointer: jsontext.Pointer(c.lands)}, entry.Hop.Target, "%s lands on the root's definition", c.property) @@ -96,7 +96,7 @@ func TestLoad_ARootDefinitionAnswersBeforeASchemasOwn(t *testing.T) { assert.NotEqual(t, diag.CyclicRef, diagnostic.Code, diagnostic.Message) } root := reftable.DocumentPointer{Pointer: "/$defs/e"} - entry, ok := got.Bindings.Table().Entry(reftable.DocumentPointer{Pointer: "/components/schemas/A"}) + entry, ok := got.Bindings.Table().ReferenceSiteAt(reftable.DocumentPointer{Pointer: "/components/schemas/A"}) require.True(t, ok) assert.Equal(t, reftable.Resolved, entry.Hop.Status) assert.Equal(t, root, entry.Hop.Target, "the root's definition answers, not A's own") @@ -104,7 +104,7 @@ func TestLoad_ARootDefinitionAnswersBeforeASchemasOwn(t *testing.T) { if c.chained == "" { return } - via, ok := got.Bindings.Table().Entry(reftable.DocumentPointer{Pointer: jsontext.Pointer(c.chained)}) + via, ok := got.Bindings.Table().ReferenceSiteAt(reftable.DocumentPointer{Pointer: jsontext.Pointer(c.chained)}) require.True(t, ok) assert.Equal(t, root, via.Chain.End, "a chain through A ends on the root's definition too") }) diff --git a/compilers/openapi/internal/load/nesting_internal_test.go b/compilers/openapi/internal/load/nesting_internal_test.go index bcbe7a21d..235656414 100644 --- a/compilers/openapi/internal/load/nesting_internal_test.go +++ b/compilers/openapi/internal/load/nesting_internal_test.go @@ -288,7 +288,7 @@ func TestNamedWithin_ADocumentBreakingTheFormatRulesIsNotWithin(t *testing.T) { // TestUnreportedRepeats_KeepsARepeatNoReachedCheckReported holds the repeats of // another document to those no reached object's check reported under the same -// code at the same place: that check's wording stands, and every other repeat +// code at the same place: that check's wording remains, and every other repeat // is kept. func TestUnreportedRepeats_KeepsARepeatNoReachedCheckReported(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/load/objects.go b/compilers/openapi/internal/load/objects.go index 02d78f148..c3fc25db0 100644 --- a/compilers/openapi/internal/load/objects.go +++ b/compilers/openapi/internal/load/objects.go @@ -30,7 +30,7 @@ type builtObject struct { var errNothingThere = errors.New("the document holds nothing there") // refKindOf returns the kind of object model, one of the parser's -// reference-or-inline wrappers or a ReferencedMediaType, stands for, and false +// reference-or-inline wrappers or a ReferencedMediaType, names, and false // for any other value, a schema included. It is the one place the load phase // lists the wrappers. func refKindOf(model any) (reftable.RefKind, bool) { @@ -118,7 +118,7 @@ type objectSite struct { kind reftable.RefKind } -// build builds the object objectLanding stands for, unless one is held there or +// build builds the object objectLanding names, unless one is held there or // a build was tried there before, and reports whether the building goes on: // false once ctx is done. func (o *objectBuild) build(ctx context.Context, objectLanding reftable.ObjectLanding) bool { diff --git a/compilers/openapi/internal/load/others_internal_test.go b/compilers/openapi/internal/load/others_internal_test.go index ef55eac02..939536363 100644 --- a/compilers/openapi/internal/load/others_internal_test.go +++ b/compilers/openapi/internal/load/others_internal_test.go @@ -183,9 +183,9 @@ func TestShownPathOf_NamesADocumentAsTheHandedPathNamesTheSource(t *testing.T) { } } -// TestUnreachedKeys_NamesWhatOnlyAPassThatDidNotStandRead pins what leaves +// TestUnreachedKeys_NamesWhatOnlyAPassThatDidNotRemainRead pins what leaves // LoadedOpenAPIDocument.Sources: a document the table holds nothing of. -func TestUnreachedKeys_NamesWhatOnlyAPassThatDidNotStandRead(t *testing.T) { +func TestUnreachedKeys_NamesWhatOnlyAPassThatDidNotRemainRead(t *testing.T) { t.Parallel() docs := map[string]string{ "/a.yaml": "$defs: {T: {type: integer}}\n", diff --git a/compilers/openapi/internal/load/overlay_refusals_internal_test.go b/compilers/openapi/internal/load/overlay_refusals_internal_test.go index a940f3f60..f4971703f 100644 --- a/compilers/openapi/internal/load/overlay_refusals_internal_test.go +++ b/compilers/openapi/internal/load/overlay_refusals_internal_test.go @@ -30,7 +30,7 @@ func overlayOf(doc string) Options { } // updateBomb writes an overlay whose update value defines anchors a0..aL, each -// listing eight aliases to the one before: a few hundred bytes that stand for +// listing eight aliases to the one before: a few hundred bytes that name // 8^L nodes once the aliases are followed. func updateBomb(levels int) string { var b strings.Builder diff --git a/compilers/openapi/internal/load/phases.go b/compilers/openapi/internal/load/phases.go index b54fc4d5b..c035c85a9 100644 --- a/compilers/openapi/internal/load/phases.go +++ b/compilers/openapi/internal/load/phases.go @@ -291,7 +291,7 @@ func (l *loading) readTable(ctx context.Context) (*reftable.ReferenceTargetTable // reread builds again, from the tree a late turn changed (bindRefs), what was // read off it before: the shapes set aside, the parser's model and what it -// leaves out. The anchors are released already, and the version stands as the +// leaves out. The anchors are released already, and the version is as the // first build read it: a value the table refuses there is one the model // decodes nothing from (docs/parser-library.md#undecoded-scalar), which that // build refused. @@ -335,7 +335,7 @@ func (l *loading) reach(context.Context) (bool, error) { // unreportedRepeats returns each key another document writes twice that no // check of an object a reference reached in it reports at the same place, -// under the same code: the object's wording stands (GitHub #1033). +// under the same code: the object's wording remains (GitHub #1033). func unreportedRepeats(repeats, reached []ir.Diagnostic) []ir.Diagnostic { type place struct { code string diff --git a/compilers/openapi/internal/load/reach_order_internal_test.go b/compilers/openapi/internal/load/reach_order_internal_test.go index 3f8f23d71..e5d5aa039 100644 --- a/compilers/openapi/internal/load/reach_order_internal_test.go +++ b/compilers/openapi/internal/load/reach_order_internal_test.go @@ -185,7 +185,7 @@ func TestExternal_AJudgementIsKeptForItsReachAndItsBoundForEvery(t *testing.T) { _, err = passed.document(t.Context(), orderProxied, reachPub) require.NoError(t, err) for _, reach := range []compilers.AddressSpace{compilers.SpacePublic, compilers.SpacePrivate} { - err = passed.read.verdict(orderProxied, reach, func() (compilers.AddressSpace, error) { + err = passed.read.judgementAt(orderProxied, reach, func() (compilers.AddressSpace, error) { t.Errorf("reach %d is judged by the bound a judgement stated, with no read", reach) return compilers.SpaceUnstated, nil }) diff --git a/compilers/openapi/internal/load/reached.go b/compilers/openapi/internal/load/reached.go index 1d1a0ab05..f5fa51390 100644 --- a/compilers/openapi/internal/load/reached.go +++ b/compilers/openapi/internal/load/reached.go @@ -116,7 +116,7 @@ func objectTargets(landings []reftable.ObjectLanding, written func(reftable.Docu } // objectKinds is the rule table's kind of each kind of object a reference can -// stand for. +// name. var objectKinds = map[reftable.RefKind]specrules.Kind{ reftable.RefPathItem: specrules.PathItem, reftable.RefParameter: specrules.Parameter, reftable.RefHeader: specrules.Header, reftable.RefRequestBody: specrules.RequestBody, reftable.RefResponse: specrules.Response, reftable.RefCallback: specrules.Callback, diff --git a/compilers/openapi/internal/load/reached_internal_test.go b/compilers/openapi/internal/load/reached_internal_test.go index 0a54bd3d6..e1d7d05e7 100644 --- a/compilers/openapi/internal/load/reached_internal_test.go +++ b/compilers/openapi/internal/load/reached_internal_test.go @@ -129,7 +129,7 @@ func TestObjectTargets(t *testing.T) { } // TestObjectKinds_NamesTheRuleTablesKindOfEach pins that every kind of object a -// reference object can stand for is held to the rule table as that kind. +// reference object can name is held to the rule table as that kind. func TestObjectKinds_NamesTheRuleTablesKindOfEach(t *testing.T) { t.Parallel() want := map[reftable.RefKind]specrules.Kind{ @@ -222,13 +222,14 @@ func TestReached_CheckAllStopsOnceTheContextIsDone(t *testing.T) { assert.NotEmpty(t, live.seen) } -// comparePositionsForTest orders positions by document, then pointer, as a -// table orders positions of one document. +// comparePositionsForTest orders positions by document, then pointer as it is +// written (provenance.ComparePointers), as a table orders positions of one +// document. func comparePositionsForTest(documentPointer, reftableDocumentPointer reftable.DocumentPointer) int { if c := cmp.Compare(documentPointer.Doc, reftableDocumentPointer.Doc); c != 0 { return c } - return cmp.Compare(documentPointer.Pointer, reftableDocumentPointer.Pointer) + return provenance.ComparePointers(documentPointer.Pointer, reftableDocumentPointer.Pointer) } // TestReached_ASchemaTheSourceWritesUnmodelledIsJudgedInItsRows pins a value diff --git a/compilers/openapi/internal/load/reached_resolve_internal_test.go b/compilers/openapi/internal/load/reached_resolve_internal_test.go index 3a5ea0519..0e1f87eb1 100644 --- a/compilers/openapi/internal/load/reached_resolve_internal_test.go +++ b/compilers/openapi/internal/load/reached_resolve_internal_test.go @@ -822,7 +822,7 @@ func TestResolve_ValidatesOnceUnderAnUpperCasedScheme(t *testing.T) { // inSourceFinding is one finding on a node of the source: the pointer it is // placed at, its code and what it says, and at, the snippet of the fixture the // node starts at, whose line and column it carries beside the pointer. -// "{line}" in text stands for that line. +// "{line}" in text names that line. type inSourceFinding struct { pointer, code, text, at string } diff --git a/compilers/openapi/internal/load/reads.go b/compilers/openapi/internal/load/reads.go index a8431c545..d2d19bbfe 100644 --- a/compilers/openapi/internal/load/reads.go +++ b/compilers/openapi/internal/load/reads.go @@ -45,10 +45,10 @@ func newExternalReads(self sourceDocument, documents budget.Limit) *externalRead } // answer is how a read was answered: the error it failed with, or the body -// read, the spelling the document was prepared under, the address space it -// was read from and the most private one it can have dialled -// (compilers.DocumentRead.MostPrivate), which a judgement at another reach can state where -// the read stated none (externalReads.verdict). +// read, the spelling the document was prepared under, the address space it was +// read from and the most private one it can have dialled +// (compilers.DocumentRead.MostPrivate), which a judgement at another reach can +// state where the read stated none (externalReads.judgementAt). type answer struct { body []byte err error @@ -76,9 +76,9 @@ type reading struct { // words (barredFor). barred error barredAt compilers.AddressSpace - // verdicts holds, once it is read with no bound stated, the judgement of - // it at each reach an asker was judged at (verdict). - verdicts map[compilers.AddressSpace]error + // judgements holds, once it is read with no bound stated, the judgement of + // it at each reach an asker was judged at (judgementAt). + judgements map[compilers.AddressSpace]error } // once returns the answer the document under key got when it was read, as an @@ -130,12 +130,12 @@ func (r *externalReads) reading(key string) *reading { return rd } -// verdict returns the refusal of the document under key, read with no bound +// judgementAt returns the refusal of the document under key, read with no bound // stated, to an asker bounded by reach, or nil, by judge, a read of it at // reach: at most once per reach, a refusal kept for every asker at it. A // judgement that passes states the document's bound, by which every later // asker is judged unread (external.admits). -func (r *externalReads) verdict(key string, reach compilers.AddressSpace, +func (r *externalReads) judgementAt(key string, reach compilers.AddressSpace, judge func() (compilers.AddressSpace, error), ) error { rd := r.reading(key) @@ -144,7 +144,7 @@ func (r *externalReads) verdict(key string, reach compilers.AddressSpace, if rd.answer.bound != compilers.SpaceUnstated { return beyond(key, rd.answer.bound, reach) } - if err, judged := rd.verdicts[reach]; judged { + if err, judged := rd.judgements[reach]; judged { return err } bound, err := judge() @@ -152,10 +152,10 @@ func (r *externalReads) verdict(key string, reach compilers.AddressSpace, rd.answer.bound = bound return nil } - if rd.verdicts == nil { - rd.verdicts = map[compilers.AddressSpace]error{} + if rd.judgements == nil { + rd.judgements = map[compilers.AddressSpace]error{} } - rd.verdicts[reach] = err + rd.judgements[reach] = err return err } diff --git a/compilers/openapi/internal/load/repeats.go b/compilers/openapi/internal/load/repeats.go index fab35e203..7cccea334 100644 --- a/compilers/openapi/internal/load/repeats.go +++ b/compilers/openapi/internal/load/repeats.go @@ -38,7 +38,7 @@ func listRepeats(at func(jsontext.Pointer) ir.Provenance, sibs Siblings, b *type case *soa.OpenAPI: // Placed from "", not site: the library renders the root's location // as "/", the pointer to a key named "". Read from the field, since - // GetServers stands in a server the source never wrote. + // GetServers puts in a server the source never wrote. diags = append(diags, serverRepeats(at, m.Servers, "")...) case *soa.ReferencedPathItem: if item, ok := writtenItem(m, b, sibs, site); ok { diff --git a/compilers/openapi/internal/load/settle.go b/compilers/openapi/internal/load/settle.go index d25ce7c85..fe4920347 100644 --- a/compilers/openapi/internal/load/settle.go +++ b/compilers/openapi/internal/load/settle.go @@ -54,8 +54,8 @@ func setAside(judgmentValue judgment, a *aside) { a.spoil(node) default: // The model reads a Reference Object by the keys the mapping writes - // itself, so one whose $ref a `<<` merges in stands in its place. - a.standIn(ref) + // itself, so one whose $ref a `<<` merges in takes its place. + a.readAsEmptyReference(ref) } } for key := range judgmentValue.seen { diff --git a/compilers/openapi/internal/load/settle_internal_test.go b/compilers/openapi/internal/load/settle_internal_test.go index d8b2c65d8..03fea8b38 100644 --- a/compilers/openapi/internal/load/settle_internal_test.go +++ b/compilers/openapi/internal/load/settle_internal_test.go @@ -230,7 +230,7 @@ func TestBuildObjects_AShapeTheModelFaultsOnIsAFailedBuild(t *testing.T) { // TestLoad_AReachedPathItemsAdditionalOperationsAreSetAside holds a 3.2 path // item only a $ref reaches, under an extension, whose additionalOperations // merges in an entry that is no mapping: the entry is set aside in the mapping -// the merge names, so nothing faults and the table's one error stands; a path +// the merge names, so nothing faults and the table's one error remains; a path // item reached whose own $ref resolves nowhere holds no lists to read; and one // whose operation repeats a parameter is reported where it is written. func TestLoad_AReachedPathItemsAdditionalOperationsAreSetAside(t *testing.T) { diff --git a/compilers/openapi/internal/load/siblings.go b/compilers/openapi/internal/load/siblings.go index ecca2cfa3..5bd2c0f3f 100644 --- a/compilers/openapi/internal/load/siblings.go +++ b/compilers/openapi/internal/load/siblings.go @@ -112,7 +112,7 @@ func isReference(node *yaml.Node) bool { // The doc's walk comes first, then each model's in the order it was found, so // a model found inside another is walked too. Each mapping is modelled once, // so there are no more models than mappings the source holds, which its node -// bound caps. A walk that panics stops the search where it stands; the +// bound caps. A walk that panics stops the search where it is; the // resolution walk meets the same fault at the same model, and reports it. func siblingsFrom(ctx context.Context, items iter.Seq[soa.WalkItem], tree provenance.Tree, build siblingBuild, ) (Siblings, []ir.Diagnostic) { diff --git a/compilers/openapi/internal/load/validate_internal_test.go b/compilers/openapi/internal/load/validate_internal_test.go index 8dc86c5c5..9f9f2dae0 100644 --- a/compilers/openapi/internal/load/validate_internal_test.go +++ b/compilers/openapi/internal/load/validate_internal_test.go @@ -92,7 +92,7 @@ components: } // TestJudgeSource_RecordsTheObjectsItRead pins what the source's check reports -// of what it read, by the mapping and the kind: a $ref standing in an object's +// of what it read, by the mapping and the kind: a $ref sitting in an object's // place is none, and an alias is the mapping it names. func TestJudgeSource_RecordsTheObjectsItRead(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/lowering/lowering.go b/compilers/openapi/internal/lowering/lowering.go index 52c9565ff..1b524cf88 100644 --- a/compilers/openapi/internal/lowering/lowering.go +++ b/compilers/openapi/internal/lowering/lowering.go @@ -91,17 +91,20 @@ type shared struct { // what another reads. documents map[reftable.DocID]BoundDocument dialects dialect.SchemaDialectRows + // bySource is, for each Provenance.Source a document's positions are + // recorded in, the least of the documents recorded there (InDocumentOf). + bySource map[int]reftable.DocID // sources is the compile's input files, in the order Provenance.Source // indexes them (Sources). sources []ir.SourceInfo // reads holds those readings in the scope fields they fill: SelfPath, and // Bindings over every $ref. reads componentlookup.Scope - // readings remembers each answer ReadOncePerRun read, in a map per type of - // key and answer (memo). Copies share it on purpose: an answer reads only - // the documents and their bindings, which no lowering changes, so what one - // copy remembers is what another would read. - readings map[any]any + // answerMemos remembers each answer ReadOncePerRun read, in a map per type + // of key and answer (memo). Copies share it on purpose: an answer reads + // only the documents and their bindings, which no lowering changes, so what + // one copy remembers is what another would read. + answerMemos map[any]any // statements reads each schema the bindings hold into its statement, once // for the run (Statements). Copies share it on purpose: a statement reads // only the documents, their bindings and their rows, which no lowering @@ -161,6 +164,7 @@ type Loaded struct { // lowering can write through the context into the caller's map. func New(in Loaded, policy Policy) Ctx { promoter := promotion.New(policy.Promotions) + statements := statement.NewTable(statement.Source{Bindings: in.Bindings, Rules: in.Rules}) return Ctx{ DocumentPlacement: siteOf(reftable.Source, in.Documents[reftable.Source]), Limits: policy.Limits, @@ -170,15 +174,27 @@ func New(in Loaded, policy Policy) Ctx { DiscriminatorInference: policy.DiscriminatorInference, KindInference: policy.KindInference, - shared: &shared{documents: maps.Clone(in.Documents), dialects: in.Rules, sources: slices.Clone(in.Sources), - names: naming.New(in.Bindings.Table(), policy.TitleNames.Honours()), - reads: componentlookup.Scope{SelfPath: in.Location, Places: in.Places, Bindings: in.Bindings}, - readings: map[any]any{}, settled: map[any]any{}, - statements: statement.NewTable(statement.Source{Bindings: in.Bindings, Rules: in.Rules})}, + shared: &shared{documents: maps.Clone(in.Documents), bySource: bySource(in.Documents), dialects: in.Rules, sources: slices.Clone(in.Sources), + names: naming.New(statements, policy.TitleNames.Honours()), + reads: componentlookup.Scope{SelfPath: in.Location, Places: in.Places, Bindings: in.Bindings}, + answerMemos: map[any]any{}, settled: map[any]any{}, statements: statements}, reached: componentlookup.NewReached(), } } +// bySource returns, for each Provenance.Source one of documents records its +// positions in, the least of the documents recorded there: two names one +// document is read by record it once. +func bySource(documents map[reftable.DocID]BoundDocument) map[int]reftable.DocID { + out := make(map[int]reftable.DocID, len(documents)) + for _, id := range slices.Sorted(maps.Keys(documents)) { + if _, recorded := out[documents[id].Place.Source]; !recorded { + out[documents[id].Place.Source] = id + } + } + return out +} + // siteOf returns the site of document id, which boundDocument is. func siteOf(id reftable.DocID, boundDocument BoundDocument) DocumentPlacement { return DocumentPlacement{place: boundDocument.Place, ids: boundDocument.IDs, doc: id} @@ -229,12 +245,12 @@ func (c Ctx) Statements() *statement.MemoizingSchemaReader { // and answer has a map of its own, so neither is boxed to be found or kept, and // a key read for two types of answer is read once for each. func ReadOncePerRun[K comparable, V any](loweringContext Ctx, key K, read func() V) V { - answers, ok := loweringContext.shared.readings[memo[K, V]{}].(map[K]V) + answers, ok := loweringContext.shared.answerMemos[memo[K, V]{}].(map[K]V) if !ok { // Kept before read runs, so a reading that asks ReadOncePerRun for answers // of the same types keeps them here rather than in a map this one replaces. answers = map[K]V{} - loweringContext.shared.readings[memo[K, V]{}] = answers + loweringContext.shared.answerMemos[memo[K, V]{}] = answers } if answer, seen := answers[key]; seen { return answer @@ -345,6 +361,18 @@ func InDocument(loweringContext Ctx, id reftable.DocID) (Ctx, bool) { return loweringContext, true } +// InDocumentOf returns loweringContext for reading what at names, in the +// document whose positions its Source records (InDocument), so a site is read +// in its own document and dialect whoever asks. It is false, loweringContext +// unchanged, for a Source no document the compile read records. +func InDocumentOf(loweringContext Ctx, at ir.Provenance) (Ctx, bool) { + id, recorded := loweringContext.shared.bySource[at.Source] + if !recorded { + return loweringContext, false + } + return InDocument(loweringContext, id) +} + // DynamicAnchor returns what c's document's declarations of the // $dynamicAnchor name say (reftable.ReferenceTargetTable.DynamicAnchor). func (c Ctx) DynamicAnchor(name string) reftable.DynamicAnchor { diff --git a/compilers/openapi/internal/lowering/lowering_documents_test.go b/compilers/openapi/internal/lowering/lowering_documents_test.go index 403dee8ee..3a921db76 100644 --- a/compilers/openapi/internal/lowering/lowering_documents_test.go +++ b/compilers/openapi/internal/lowering/lowering_documents_test.go @@ -106,6 +106,31 @@ func TestInDocument_PlacesWhatAnotherDocumentDeclares(t *testing.T) { assert.Equal(t, ids.DocumentIDNamespace{}, same.IDs(), "and the context is left as it was") } +// TestMinting_MintsOnePositionUntilAnotherDocumentIsEntered pins a context +// lowering one position to a node minted in place of its own: that position's +// ID and coordinate are the composed ID of its key, placed and named by the +// pointer it is given, every other position is as before, and entering a +// document, the source's own among them, mints nothing. +func TestMinting_MintsOnePositionUntilAnotherDocumentIsEntered(t *testing.T) { + t.Parallel() + loweringContext, _ := loadSplit(t, "X: {type: string}\nP: {name: p, in: query}\n") + const at, key, from = "/components/schemas/A", "/components/schemas/A/oneOf/-/0", "/components/schemas/A/oneOf/0" + minting := lowering.Minting(loweringContext, at, key, from) + assert.Equal(t, ids.DocumentIDNamespace{}.ComposedType(key), minting.IDs().ForPointer(at)) + mintedKey, mintedFrom, minted := minting.MintedAt(at) + require.True(t, minted) + assert.Equal(t, [2]jsontext.Pointer{key, from}, [2]jsontext.Pointer{mintedKey, mintedFrom}) + _, _, minted = minting.MintedAt(from) + assert.False(t, minted, "the pointer placing the node is no position minted in place") + _, _, minted = loweringContext.MintedAt(at) + assert.False(t, minted, "the context minting was made from mints nothing") + back, ok := lowering.InDocument(minting, reftable.Source) + require.True(t, ok) + _, _, minted = back.MintedAt(at) + assert.False(t, minted, "entering a document mints nothing") + assert.Equal(t, ids.DocumentIDNamespace{}, back.IDs()) +} + // TestSchemaRules_FollowTheDocumentTheScopeReads pins which document's rows a // context reads a schema with: that of the document its scope reads, through // InDocument, and back to the source's. Rules().In answers for a document of @@ -253,3 +278,26 @@ func TestNameOfDocument_NamesWhatADocumentsRootDeclares(t *testing.T) { loweringContext, _ := loadSplit(t, "X: {type: string}\n") assert.Equal(t, "ext.yaml", lowering.NameOfDocument(loweringContext, extDoc(t, loweringContext))) } + +// TestInDocumentOf_ReadsAPlaceInItsOwnDocument pins the document a place is +// read in: the one whose BoundDocument.Sources entry its Source names, from a +// context reading any document, and none for a Source no document records. +func TestInDocumentOf_ReadsAPlaceInItsOwnDocument(t *testing.T) { + t.Parallel() + loweringContext, _ := loadSplit(t, "X: {type: string}\nP: {name: p, in: query}\n") + ext := extDoc(t, loweringContext) + fromExt, read := lowering.InDocument(loweringContext, ext) + require.True(t, read) + + for name, from := range map[string]lowering.Ctx{"the source": loweringContext, "ext.yaml": fromExt} { + inExt, placed := lowering.InDocumentOf(from, ir.Provenance{Source: 1, Pointer: "/X"}) + require.True(t, placed, name) + assert.Equal(t, reftable.DocumentPointer{Doc: ext, Pointer: "/X"}, inExt.Position("/X"), "from %s", name) + inSource, placed := lowering.InDocumentOf(from, ir.Provenance{Source: 0, Pointer: "/X"}) + require.True(t, placed, name) + assert.Equal(t, reftable.Source, inSource.Position("/X").Doc, "from %s", name) + } + unplaced, placed := lowering.InDocumentOf(fromExt, ir.Provenance{Source: 7}) + assert.False(t, placed) + assert.Equal(t, ext, unplaced.Position("").Doc, "the context comes back unchanged") +} diff --git a/compilers/openapi/internal/lowering/lowering_test.go b/compilers/openapi/internal/lowering/lowering_test.go index 9291964b2..fa0da2da9 100644 --- a/compilers/openapi/internal/lowering/lowering_test.go +++ b/compilers/openapi/internal/lowering/lowering_test.go @@ -160,7 +160,7 @@ func TestRefScope_CarriesTheBindingsItWasGiven(t *testing.T) { assert.Same(t, loaded.Bindings, carrying.Bindings()) assert.Same(t, loaded.Bindings, carrying.RefScope().Bindings) assert.Same(t, loaded.Bindings, atSource(t, carrying.Ctx).Bindings(), "a copy shares it") - referenceSite, ok := carrying.RefScope().Bindings.Entry(alias) + referenceSite, ok := carrying.RefScope().Bindings.ReferenceSiteAt(alias) require.True(t, ok && referenceSite.Lands(), "its $ref lands where the load phase resolved it") assert.Equal(t, reftable.DocumentPointer{Pointer: "/components/schemas/Target"}, referenceSite.Hop.Target) } diff --git a/compilers/openapi/internal/lowering/site.go b/compilers/openapi/internal/lowering/site.go index 1395e1e52..5fbc94486 100644 --- a/compilers/openapi/internal/lowering/site.go +++ b/compilers/openapi/internal/lowering/site.go @@ -22,6 +22,9 @@ type DocumentPlacement struct { place provenance.Doc ids ids.DocumentIDNamespace doc reftable.DocID + // mintedFrom places and names the node ids mints in place of a + // position's own (Minting). + mintedFrom jsontext.Pointer } // Place returns where the site places a pointer of its document: in another @@ -49,6 +52,29 @@ func (s DocumentPlacement) DiagAt(sev ir.Severity, code string, pointer jsontext // IDs returns how the IDs of what the site's document declares name it. func (s DocumentPlacement) IDs() ids.DocumentIDNamespace { return s.ids } +// Minting returns loweringContext lowering the schema at pointer, of its +// document, to a node minted in the composed namespace at key in place of its +// own (ids.DocumentIDNamespace.Minting), placed and named by from, where the +// source writes what that node names. Every other position lowers as in +// loweringContext, and so does the schema at pointer once another document is +// entered. +func Minting(loweringContext Ctx, pointer, key, from jsontext.Pointer) Ctx { + loweringContext.ids = loweringContext.ids.Minting(pointer, key) + loweringContext.mintedFrom = from + return loweringContext +} + +// MintedAt returns the key the node of the schema at pointer is minted at +// (Minting) and the pointer placing and naming it, and false where that node +// is hoisted at pointer. +func (s DocumentPlacement) MintedAt(pointer jsontext.Pointer) (key, from jsontext.Pointer, minted bool) { + key, minted = s.ids.Minted(pointer) + if !minted { + return "", "", false + } + return key, s.mintedFrom, true +} + // Position returns where pointer of the site's document is in the bindings' // table. func (s DocumentPlacement) Position(pointer jsontext.Pointer) reftable.DocumentPointer { diff --git a/compilers/openapi/internal/merge/admits.go b/compilers/openapi/internal/merge/admits.go index 61da4f419..a32fc3374 100644 --- a/compilers/openapi/internal/merge/admits.go +++ b/compilers/openapi/internal/merge/admits.go @@ -4,163 +4,19 @@ package merge import ( - "strconv" - "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/rfc3339" ) -// Bounds of the fixed-width integers, as the decimal literals inRange compares. -const ( - int8Min ir.BigVal = "-128" - int8Max ir.BigVal = "127" - int16Min ir.BigVal = "-32768" - int16Max ir.BigVal = "32767" - int32Min ir.BigVal = "-2147483648" - int32Max ir.BigVal = "2147483647" - int64Min ir.BigVal = "-9223372036854775808" - int64Max ir.BigVal = "9223372036854775807" - uint8Max ir.BigVal = "255" - uint16Max ir.BigVal = "65535" - uint32Max ir.BigVal = "4294967295" - uint64Max ir.BigVal = "18446744073709551615" -) - -// The IEEE 754 formats Admits judges against: decimal128's digit budget and -// exponent range, and the width of each binary float. -const ( - decimal128Digits = 34 - decimal128MaxMsdExp = 6144 - decimal128MinLowExp = -6176 - float32Bits = 32 - float64Bits = 64 -) - -// Admits reports whether value is a value of the primitive kind primitiveKind, -// judged exactly: a bounded read of a number rather than a conversion, so an -// exponent no machine type holds is refused, not overflowed. A kind with no -// judge admits nothing, which keeps a value off a field it cannot be shown to -// fit. -// -// A null is not judged here: whether null is a value depends on the merged -// field's nullability, not on a kind. -func Admits(primitiveKind ir.PrimitiveKind, value ir.Value) bool { - switch primitiveKind { - case ir.PrimitiveAny: - return true - case ir.PrimitiveBool: - return value.Kind == ir.ValueBool - case ir.PrimitiveString: - return value.Kind == ir.ValueString - case ir.PrimitiveInt8: - return inRange(value, int8Min, int8Max) - case ir.PrimitiveInt16: - return inRange(value, int16Min, int16Max) - case ir.PrimitiveInt32: - return inRange(value, int32Min, int32Max) - case ir.PrimitiveInt64: - return inRange(value, int64Min, int64Max) - case ir.PrimitiveUint8: - return inRange(value, "0", uint8Max) - case ir.PrimitiveUint16: - return inRange(value, "0", uint16Max) - case ir.PrimitiveUint32: - return inRange(value, "0", uint32Max) - case ir.PrimitiveUint64: - return inRange(value, "0", uint64Max) - case ir.PrimitiveInteger: - decimal, ok := decimalOf(value) - return ok && decimal.IsInt() - case ir.PrimitiveNumber, ir.PrimitiveFloat, ir.PrimitiveDecimal: - _, ok := decimalOf(value) - return ok - case ir.PrimitiveDecimal128: - return admitsDecimal128(value) - case ir.PrimitiveFloat32: - return admitsFloat(value, float32Bits) - case ir.PrimitiveFloat64: - return admitsFloat(value, float64Bits) - case ir.PrimitiveDate: - return value.Kind == ir.ValueString && parses("2006-01-02", value.String) - case ir.PrimitiveTime: - return value.Kind == ir.ValueString && parsesRFC3339(value.String, partialTime) - case ir.PrimitiveDatetime: - return value.Kind == ir.ValueString && parsesRFC3339(value.String, localDateTime) - case ir.PrimitiveDatetimeOffset: - return value.Kind == ir.ValueString && parsesRFC3339(value.String, dateTime) - case ir.PrimitiveUUID: - return value.Kind == ir.ValueString && isUUID(value.String) - case ir.PrimitiveURL: - return value.Kind == ir.ValueString && isAbsoluteURI(value.String) - case ir.PrimitiveDuration: - return value.Kind == ir.ValueString && isDuration(value.String) - case ir.PrimitiveBytes: - return false - default: - return false - } -} - // admitsFormat reports whether value is a value of the string format named -// format, and whether the compiler holds that format's grammar at all, which -// the name alone decides. It holds one for a format the table pairs with no -// kind: time, RFC 3339's full-time, whose offset the time kind does not hold -// (docs/ir/primitives.md#offsets). A format the table pairs with a kind is -// judged as that kind, by Admits. +// format, and whether the compiler holds that format's grammar, which it does +// only for a format the table pairs with no kind: time, RFC 3339's full-time, +// whose offset the time kind does not hold (docs/ir/primitives.md#offsets). func admitsFormat(format string, value ir.Value) (admits, held bool) { switch format { case "time": - return value.Kind == ir.ValueString && parsesRFC3339(value.String, fullTime), true + return value.Kind == ir.ValueString && rfc3339.Parses(value.String, rfc3339.FullTime), true default: return false, false } } - -// decimalOf reads value as a number, reporting false for any other kind of -// value and for a number no Decimal holds: reading that as zero would admit it -// everywhere. -func decimalOf(value ir.Value) (ir.Decimal, bool) { - if value.Kind != ir.ValueNumber { - return ir.Decimal{}, false - } - decimal, err := value.Number.Decimal() - return decimal, err == nil -} - -// inRange reports whether value is an integral number from lo to hi inclusive. -// An end that reads as no number admits nothing. -func inRange(value ir.Value, lo, hi ir.BigVal) bool { - decimal, ok := decimalOf(value) - low, lowErr := lo.Decimal() - high, highErr := hi.Decimal() - return ok && lowErr == nil && highErr == nil && decimal.IsInt() && decimal.Cmp(low) >= 0 && decimal.Cmp(high) <= 0 -} - -// admitsDecimal128 reports whether value fits IEEE 754 decimal128: at most 34 -// significant digits, the leading one no higher than 10^6144 and the last no -// lower than 10^-6176. -func admitsDecimal128(value ir.Value) bool { - decimal, ok := decimalOf(value) - if !ok { - return false - } - if decimal.Sign() == 0 { - return true - } - digits := int64(len(decimal.Digits())) - lowest := decimal.Exponent() - (digits - 1) - return digits <= decimal128Digits && decimal.Exponent() <= decimal128MaxMsdExp && lowest >= decimal128MinLowExp -} - -// admitsFloat reports whether value rounds to a finite value of a binary float -// of the given width, which strconv settles exactly: rounding is allowed, as -// OpenAPI floats round, and a magnitude at or past the point where -// round-to-nearest overflows is a range error. The float it returns is not -// kept, so no value passes through one. -func admitsFloat(value ir.Value, bits int) bool { - decimal, ok := decimalOf(value) - if !ok { - return false - } - _, err := strconv.ParseFloat(decimal.String(), bits) - return err == nil -} diff --git a/compilers/openapi/internal/merge/admits_chain_internal_test.go b/compilers/openapi/internal/merge/admits_chain_internal_test.go new file mode 100644 index 000000000..3142539b6 --- /dev/null +++ b/compilers/openapi/internal/merge/admits_chain_internal_test.go @@ -0,0 +1,84 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// boundedChain is a registry holding a chain of aliasCount aliases over +// integer, the far one bounding it by a maximum of 9, and returns the near end. +func boundedChain(aliasCount int) (ir.TypeRegistry, ir.TypeID) { + reg := ir.TypeRegistry{"type/primitive/integer": &ir.Primitive{ID: "type/primitive/integer", PrimitiveKind: ir.PrimitiveInteger}} + base := ir.TypeID("type/primitive/integer") + for i := range aliasCount { + id := ir.TypeID(fmt.Sprintf("type/I%d", i)) + alias := &ir.Scalar{ID: id, Base: &ir.TypeRef{Target: base}} + if i == 0 { + alias.Constraints = &ir.Constraints{Max: new(ir.BigVal("9"))} + } + reg[id], base = alias, id + } + return reg, base +} + +// TestAdmits_ReadsAnAliasChainOfAnyLength pins the value judgment through alias +// scalars, as the fold's value admission reader reads them: each alias's bounds +// hold the value, however many aliases lie before the far one bounding it, so +// 5, 12 and 1,000 aliases admit 5 and refuse 50 alike, and a chain repeating an +// alias admits nothing. +func TestAdmits_ReadsAnAliasChainOfAnyLength(t *testing.T) { + t.Parallel() + reader := func(reg ir.TypeRegistry) *ir.ValueAdmissionReader { + return NewFoldValueAdmissionReader(stubResolve(reg), ir.NewAliasChainIndex(stubResolve(reg))) + } + for _, aliasCount := range []int{5, 12, 1000} { + reg, near := boundedChain(aliasCount) + admission := reader(reg) + assert.Equal(t, ir.AdmitsYes, admission.Admits(ir.TypeRef{Target: near}, number("5")), "%d aliases admit 5", aliasCount) + assert.Equal(t, ir.AdmitsNo, admission.Admits(ir.TypeRef{Target: near}, number("50")), "%d aliases refuse 50", aliasCount) + } + reg := ir.TypeRegistry{ + "type/A": &ir.Scalar{ID: "type/A", Base: &ir.TypeRef{Target: "type/B"}}, + "type/B": &ir.Scalar{ID: "type/B", Base: &ir.TypeRef{Target: "type/A"}}, + } + assert.NotEqual(t, ir.AdmitsYes, reader(reg).Admits(ir.TypeRef{Target: "type/A"}, number("5")), "a cycle admits nothing") +} + +// TestFold_ADefaultOverALongAliasChainIsAdopted pins a default the field's type +// admits through a chain of aliases: a field declared as integer defaulting to +// 5 and as the near end of a chain whose far alias bounds it by 9 takes the +// chain and adopts the default at 5, 12 and 100 aliases alike, and refuses a +// default of 50 at each. +func TestFold_ADefaultOverALongAliasChainIsAdopted(t *testing.T) { + t.Parallel() + for _, aliasCount := range []int{5, 12, 100} { + for value, adopted := range map[string]bool{"5": true, "50": false} { + reg, near := boundedChain(aliasCount) + stubbed, _ := stubMerger(reg) + defaulted := number(value) + declared := []declaration{ + {property: ir.Property{WireName: "p", Type: primitiveRef(ir.PrimitiveInteger), Default: &defaulted, + Provenance: ptrAt(jsontext.Pointer("/allOf/0/properties/p"))}, source: written(`{"type":"integer","default":` + value + `}`)}, + {property: ir.Property{WireName: "p", Type: ir.TypeRef{Target: near}, Provenance: ptrAt("/allOf/1/properties/p")}, source: unread(t)}, + } + + merged := stubbed.fold(declared) + + require.Equal(t, near, merged.Type.Target, "%d aliases", aliasCount) + if adopted { + assert.Equal(t, &defaulted, merged.Default, "%d aliases adopt %s", aliasCount, value) + continue + } + assert.Nil(t, merged.Default, "%d aliases refuse %s", aliasCount, value) + } + } +} diff --git a/compilers/openapi/internal/merge/admits_internal_test.go b/compilers/openapi/internal/merge/admits_internal_test.go index 5cb2b7ab7..f4a6b0220 100644 --- a/compilers/openapi/internal/merge/admits_internal_test.go +++ b/compilers/openapi/internal/merge/admits_internal_test.go @@ -6,7 +6,6 @@ package merge import ( "slices" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -16,210 +15,8 @@ import ( "github.com/dexpace/morphic/ir" ) -func number(s string) ir.Value { return ir.Value{Kind: ir.ValueNumber, Number: ir.BigVal(s)} } -func stringValue(s string) ir.Value { return ir.Value{Kind: ir.ValueString, String: s} } - -// TestAdmits_JudgesEachKindExactly pins the boundary of every judge: the last -// value in and the first value out, and the near misses of each grammar. -func TestAdmits_JudgesEachKindExactly(t *testing.T) { - t.Parallel() - digits35 := "12345678901234567890123456789012345" - for _, tc := range []struct { - name string - kind ir.PrimitiveKind - v ir.Value - want bool - }{ - {"int8 min", ir.PrimitiveInt8, number("-128"), true}, - {"int8 max", ir.PrimitiveInt8, number("127"), true}, - {"int8 above", ir.PrimitiveInt8, number("128"), false}, - {"int8 below", ir.PrimitiveInt8, number("-129"), false}, - {"int8 fraction", ir.PrimitiveInt8, number("1.5"), false}, - {"int8 integral fraction", ir.PrimitiveInt8, number("5.0"), true}, - {"int16 max", ir.PrimitiveInt16, number("32767"), true}, - {"int16 above", ir.PrimitiveInt16, number("32768"), false}, - {"int32 max", ir.PrimitiveInt32, number("2147483647"), true}, - {"int32 above", ir.PrimitiveInt32, number("2147483648"), false}, - {"int32 below", ir.PrimitiveInt32, number("-2147483649"), false}, - {"int64 max", ir.PrimitiveInt64, number("9223372036854775807"), true}, - {"int64 above", ir.PrimitiveInt64, number("9223372036854775808"), false}, - {"int64 huge exponent", ir.PrimitiveInt64, number("1e1000001"), false}, - {"int64 tiny exponent", ir.PrimitiveInt64, number("1e-1000001"), false}, - {"uint8 max", ir.PrimitiveUint8, number("255"), true}, - {"uint8 above", ir.PrimitiveUint8, number("256"), false}, - {"uint8 negative", ir.PrimitiveUint8, number("-1"), false}, - {"uint16 max", ir.PrimitiveUint16, number("65535"), true}, - {"uint16 above", ir.PrimitiveUint16, number("65536"), false}, - {"uint32 max", ir.PrimitiveUint32, number("4294967295"), true}, - {"uint32 above", ir.PrimitiveUint32, number("4294967296"), false}, - {"uint64 max", ir.PrimitiveUint64, number("18446744073709551615"), true}, - {"uint64 above", ir.PrimitiveUint64, number("18446744073709551616"), false}, - {"integer huge", ir.PrimitiveInteger, number("1e1000001"), true}, - {"integer fraction", ir.PrimitiveInteger, number("0.5"), false}, - {"integer zero", ir.PrimitiveInteger, number("0.0"), true}, - {"integer string", ir.PrimitiveInteger, stringValue("1"), false}, - {"number fraction", ir.PrimitiveNumber, number("1.5"), true}, - {"number bool", ir.PrimitiveNumber, ir.Value{Kind: ir.ValueBool}, false}, - {"float any number", ir.PrimitiveFloat, number("1e1000001"), true}, - {"decimal any number", ir.PrimitiveDecimal, number("1e1000001"), true}, - {"float32 in range", ir.PrimitiveFloat32, number("3.4e38"), true}, - {"float32 out of range", ir.PrimitiveFloat32, number("3.5e38"), false}, - {"float32 negative out of range", ir.PrimitiveFloat32, number("-3.5e38"), false}, - {"float32 rounds to max", ir.PrimitiveFloat32, number("3.40282356e38"), true}, - {"float32 huge exponent", ir.PrimitiveFloat32, number("1e1000001"), false}, - {"float32 string", ir.PrimitiveFloat32, stringValue("1"), false}, - {"float64 in range", ir.PrimitiveFloat64, number("1.7e308"), true}, - {"float64 out of range", ir.PrimitiveFloat64, number("1.8e308"), false}, - {"decimal128 34 digits", ir.PrimitiveDecimal128, number(digits35[:34]), true}, - {"decimal128 35 digits", ir.PrimitiveDecimal128, number(digits35), false}, - {"decimal128 zero", ir.PrimitiveDecimal128, number("0"), true}, - {"decimal128 top exponent", ir.PrimitiveDecimal128, number("1e6144"), true}, - {"decimal128 above exponent", ir.PrimitiveDecimal128, number("1e6145"), false}, - {"decimal128 lowest exponent", ir.PrimitiveDecimal128, number("1e-6176"), true}, - {"decimal128 below exponent", ir.PrimitiveDecimal128, number("1e-6177"), false}, - {"decimal128 string", ir.PrimitiveDecimal128, stringValue("1"), false}, - {"decimal128 34 digits ending at the lowest exponent", ir.PrimitiveDecimal128, - number("1.234567890123456789012345678901234e-6143"), true}, - {"decimal128 34 digits ending one below it", ir.PrimitiveDecimal128, - number("1.234567890123456789012345678901234e-6144"), false}, - {"float32 last in", ir.PrimitiveFloat32, number("340282356779733661637539395458142568447"), true}, - {"float32 first out", ir.PrimitiveFloat32, number("340282356779733661637539395458142568448"), false}, - {"float32 negative last in", ir.PrimitiveFloat32, number("-340282356779733661637539395458142568447"), true}, - {"float32 negative first out", ir.PrimitiveFloat32, number("-340282356779733661637539395458142568448"), false}, - {"float64 last in", ir.PrimitiveFloat64, number("179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791"), true}, - {"float64 first out", ir.PrimitiveFloat64, number("179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792"), false}, - {"float64 negative last in", ir.PrimitiveFloat64, number("-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791"), true}, - {"float64 negative first out", ir.PrimitiveFloat64, number("-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792"), false}, - {"float64 zero", ir.PrimitiveFloat64, number("0"), true}, - {"url space", ir.PrimitiveURL, stringValue("mailto:a b"), false}, - {"url space in path", ir.PrimitiveURL, stringValue("http://x/a b"), false}, - {"url braces", ir.PrimitiveURL, stringValue("bytes:{}"), false}, - {"url non ascii", ir.PrimitiveURL, stringValue("http://x/é"), false}, - {"url control byte", ir.PrimitiveURL, stringValue("http://x/a\x01"), false}, - {"url backslash", ir.PrimitiveURL, stringValue("http://x/a\\b"), false}, - {"url percent octet", ir.PrimitiveURL, stringValue("http://x/a%20b"), true}, - {"url bad percent octet", ir.PrimitiveURL, stringValue("http://x/a%2"), false}, - {"url bad percent digit", ir.PrimitiveURL, stringValue("http://x/a%2g"), false}, - {"url delimiters", ir.PrimitiveURL, stringValue("a+b-c.d://u@[::1]:1/p?q=1&r=!$'()*,;~_#f"), true}, - {"url second fragment delimiter", ir.PrimitiveURL, stringValue("http://x/#a#b"), false}, - {"url bracket in path", ir.PrimitiveURL, stringValue("http://x/a[b"), false}, - {"url bracket without authority", ir.PrimitiveURL, stringValue("bytes:a]"), false}, - {"url ip literal host", ir.PrimitiveURL, stringValue("http://[::1]/"), true}, - {"url bracket ends a reg-name host", ir.PrimitiveURL, stringValue("http://x]/"), false}, - {"url bracket ends a host before the port", ir.PrimitiveURL, stringValue("http://x]:80/"), false}, - {"url bracket ends a userinfo host", ir.PrimitiveURL, stringValue("http://u@x]/"), false}, - {"url bracket inside a reg-name host", ir.PrimitiveURL, stringValue("http://a]b/"), false}, - {"url second @ in the authority", ir.PrimitiveURL, stringValue("http://a@b@x/"), false}, - {"url second @ before an IP-literal", ir.PrimitiveURL, stringValue("http://a@b@[::1]/"), false}, - {"url @ after the authority is a path or query byte", ir.PrimitiveURL, stringValue("http://u@x/a@b?c@d"), true}, - {"url @ in a path with no authority", ir.PrimitiveURL, stringValue("mailto:a@b@c"), true}, - {"url @ in a query right after the host", ir.PrimitiveURL, stringValue("http://u@x?a@b"), true}, - {"url @ in a fragment right after the host", ir.PrimitiveURL, stringValue("http://u@x#a@b"), true}, - {"url two closing brackets", ir.PrimitiveURL, stringValue("http://[::1]]/"), false}, - {"url text after the literal", ir.PrimitiveURL, stringValue("http://[::1]a/"), false}, - {"url opening bracket ends a host", ir.PrimitiveURL, stringValue("http://x[/"), false}, - {"url opening bracket in the userinfo", ir.PrimitiveURL, stringValue("http://u[@x/"), false}, - {"url ipvfuture host is refused as url.Parse refuses it", ir.PrimitiveURL, stringValue("http://[v1.x]/"), false}, - {"url ip literal with a port, path, query and fragment", ir.PrimitiveURL, stringValue("http://[::1]:80/a?b#c"), true}, - {"url ip literal with userinfo", ir.PrimitiveURL, stringValue("http://u@[::1]/"), true}, - {"url ip literal without a path", ir.PrimitiveURL, stringValue("bytes://[::1]"), true}, - {"url ip literal with a zone", ir.PrimitiveURL, stringValue("http://[fe80::1%25en0]/"), true}, - {"url query then fragment", ir.PrimitiveURL, stringValue("http://x?a#b"), true}, - {"url empty", ir.PrimitiveURL, stringValue(""), false}, - {"url no colon", ir.PrimitiveURL, stringValue("abc"), false}, - {"url scheme only", ir.PrimitiveURL, stringValue("a:"), true}, - {"url bad scheme byte", ir.PrimitiveURL, stringValue("a_b:c"), false}, - {"time comma fraction", ir.PrimitiveTime, stringValue("23:59:59,5"), false}, - {"time dot fraction", ir.PrimitiveTime, stringValue("23:59:59.5"), true}, - {"time empty fraction", ir.PrimitiveTime, stringValue("23:59:59."), false}, - {"time with a Z offset", ir.PrimitiveTime, stringValue("23:59:59Z"), false}, - {"time with a numeric offset", ir.PrimitiveTime, stringValue("23:59:59.5+01:00"), false}, - {"time short", ir.PrimitiveTime, stringValue("23:59"), false}, - {"time bad separator", ir.PrimitiveTime, stringValue("23-59:59"), false}, - {"time bad digit", ir.PrimitiveTime, stringValue("2a:59:59"), false}, - {"time hour 24", ir.PrimitiveTime, stringValue("24:00:00"), false}, - {"time minute 60", ir.PrimitiveTime, stringValue("23:60:00"), false}, - {"time leap second at any minute", ir.PrimitiveTime, stringValue("12:34:60"), true}, - {"time second 61", ir.PrimitiveTime, stringValue("23:59:61"), false}, - {"time number", ir.PrimitiveTime, number("1"), false}, - {"datetime", ir.PrimitiveDatetime, stringValue("2024-02-29T23:59:59"), true}, - {"datetime dot fraction", ir.PrimitiveDatetime, stringValue("2024-02-29T23:59:59.5"), true}, - {"datetime lower case t", ir.PrimitiveDatetime, stringValue("2024-02-29t23:59:59"), true}, - {"datetime with a Z offset", ir.PrimitiveDatetime, stringValue("2024-02-29T23:59:59Z"), false}, - {"datetime with a numeric offset", ir.PrimitiveDatetime, stringValue("2024-02-29T23:59:59+01:00"), false}, - {"datetime space separator", ir.PrimitiveDatetime, stringValue("2024-01-01 00:00:00"), false}, - {"datetime short", ir.PrimitiveDatetime, stringValue("2024-01-01"), false}, - {"datetime bad calendar", ir.PrimitiveDatetime, stringValue("2023-02-29T00:00:00"), false}, - {"datetime hour 24", ir.PrimitiveDatetime, stringValue("2024-01-01T24:00:00"), false}, - {"datetime leap second at any minute", ir.PrimitiveDatetime, stringValue("2024-01-01T05:29:60"), true}, - {"datetime second 61", ir.PrimitiveDatetime, stringValue("2016-12-31T23:59:61"), false}, - {"datetime number", ir.PrimitiveDatetime, number("1"), false}, - {"datetime offset max", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T23:59:59-23:59"), true}, - {"datetime offset bad digit", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T23:59:59+0a:00"), false}, - {"datetime offset bad sign", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T23:59:59*05:00"), false}, - {"datetime offset no colon", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T23:59:59+0500"), false}, - {"datetime offset empty fraction", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T23:59:59.Z"), false}, - {"datetime offset leap second behind utc", ir.PrimitiveDatetimeOffset, stringValue("2016-12-31T15:59:60-08:00"), true}, - {"datetime offset leap second wrong minute", ir.PrimitiveDatetimeOffset, stringValue("2016-12-31T23:58:60Z"), false}, - {"datetime offset second 61", ir.PrimitiveDatetimeOffset, stringValue("2016-12-31T23:59:61Z"), false}, - {"datetime offset leap second", ir.PrimitiveDatetimeOffset, stringValue("2016-12-31T23:59:60Z"), true}, - {"datetime offset leap second wrong hour", ir.PrimitiveDatetimeOffset, stringValue("2016-12-31T22:59:60Z"), false}, - {"datetime offset comma fraction", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T00:00:00,5Z"), false}, - {"datetime offset dot fraction", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T00:00:00.5Z"), true}, - {"datetime offset hour 24 offset", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T00:00:00+24:00"), false}, - {"datetime offset minute 60 offset", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01T00:00:00+05:60"), false}, - {"datetime offset lower case", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01t00:00:00z"), true}, - {"datetime offset lower case t", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01t00:00:00Z"), true}, - {"datetime offset space separator", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01 00:00:00Z"), false}, - {"datetime offset short", ir.PrimitiveDatetimeOffset, stringValue("2024-01-01"), false}, - {"datetime offset bad calendar", ir.PrimitiveDatetimeOffset, stringValue("2024-02-30T00:00:00Z"), false}, - {"bool", ir.PrimitiveBool, ir.Value{Kind: ir.ValueBool, Bool: true}, true}, - {"bool number", ir.PrimitiveBool, number("1"), false}, - {"string", ir.PrimitiveString, stringValue("x"), true}, - {"string symbol", ir.PrimitiveString, ir.Value{Kind: ir.ValueSymbol, String: "x"}, false}, - {"date", ir.PrimitiveDate, stringValue("2024-02-29"), true}, - {"date invalid calendar", ir.PrimitiveDate, stringValue("2023-02-29"), false}, - {"date short", ir.PrimitiveDate, stringValue("2024-2-9"), false}, - {"time", ir.PrimitiveTime, stringValue("23:59:59"), true}, - {"datetime offset", ir.PrimitiveDatetimeOffset, stringValue("2024-02-29T23:59:59Z"), true}, - {"datetime offset none", ir.PrimitiveDatetimeOffset, stringValue("2024-02-29T23:59:59"), false}, - {"datetime offset hour", ir.PrimitiveDatetimeOffset, stringValue("2024-02-29T24:00:00Z"), false}, - {"uuid", ir.PrimitiveUUID, stringValue("123e4567-e89b-12d3-a456-426614174000"), true}, - {"uuid upper", ir.PrimitiveUUID, stringValue("123E4567-E89B-12D3-A456-426614174000"), true}, - {"uuid short", ir.PrimitiveUUID, stringValue("123e4567-e89b-12d3-a456-42661417400"), false}, - {"uuid no dash", ir.PrimitiveUUID, stringValue("123e4567xe89b-12d3-a456-426614174000"), false}, - {"uuid non hex", ir.PrimitiveUUID, stringValue("123e4567-e89b-12d3-a456-42661417400g"), false}, - {"uuid word", ir.PrimitiveUUID, stringValue("hello"), false}, - {"url", ir.PrimitiveURL, stringValue("https://example.com/a?b=c"), true}, - {"url mailto", ir.PrimitiveURL, stringValue("mailto:a@example.com"), true}, - {"url relative", ir.PrimitiveURL, stringValue("/a/b"), false}, - {"url bad", ir.PrimitiveURL, stringValue("1http://x"), false}, - {"url number", ir.PrimitiveURL, number("1"), false}, - {"duration", ir.PrimitiveDuration, stringValue("P1Y2M3DT4H5M6S"), true}, - {"duration weeks", ir.PrimitiveDuration, stringValue("P2W"), true}, - {"duration time only", ir.PrimitiveDuration, stringValue("PT5M"), true}, - {"duration skipped designator", ir.PrimitiveDuration, stringValue("P1Y3D"), false}, - {"duration date from months", ir.PrimitiveDuration, stringValue("P2M3D"), true}, - {"duration out of order", ir.PrimitiveDuration, stringValue("P3D2M"), false}, - {"duration empty", ir.PrimitiveDuration, stringValue("P"), false}, - {"duration empty time", ir.PrimitiveDuration, stringValue("P1DT"), false}, - {"duration bare T", ir.PrimitiveDuration, stringValue("PT"), false}, - {"duration no prefix", ir.PrimitiveDuration, stringValue("1D"), false}, - {"duration weeks mixed", ir.PrimitiveDuration, stringValue("P1W2D"), false}, - {"duration no digits", ir.PrimitiveDuration, stringValue("PD"), false}, - {"duration trailing digits", ir.PrimitiveDuration, stringValue("P1"), false}, - {"duration repeated", ir.PrimitiveDuration, stringValue("P1D1D"), false}, - {"duration unknown", ir.PrimitiveDuration, stringValue("P1X"), false}, - {"duration date after time", ir.PrimitiveDuration, stringValue("PT1H1D"), false}, - {"date number", ir.PrimitiveDate, number("1"), false}, - {"bytes", ir.PrimitiveBytes, ir.Value{Kind: ir.ValueBytes, Bytes: []byte("x")}, false}, - {"any", ir.PrimitiveAny, ir.Value{Kind: ir.ValueObject}, true}, - {"list against integer", ir.PrimitiveInteger, ir.Value{Kind: ir.ValueList, List: []ir.Value{number("1")}}, false}, - {"unknown kind", ir.PrimitiveKind("nope"), stringValue("x"), false}, - } { - assert.Equal(t, tc.want, Admits(tc.kind, tc.v), "%s: %s of %v", tc.name, tc.kind, tc.v) - } -} +func number(text string) ir.Value { return ir.Value{Kind: ir.ValueNumber, Number: ir.BigVal(text)} } +func stringValue(text string) ir.Value { return ir.Value{Kind: ir.ValueString, String: text} } // TestAdmitsFormat_JudgesTimeAsAFullTime pins the boundary of the one format // judged by name: time, RFC 3339's full-time, which carries the offset the time @@ -283,7 +80,7 @@ func TestAdmitsFormat_SharesNoStringWithAKind(t *testing.T) { all := slices.Clone(times) for primitiveKind, ss := range samples { for _, s := range ss { - require.True(t, Admits(primitiveKind, stringValue(s)), "%q is a value of %s", s, primitiveKind) + require.Equal(t, ir.AdmitsYes, ir.PrimitiveAdmits(primitiveKind, stringValue(s)), "%q is a value of %s", s, primitiveKind) } all = append(all, ss...) } @@ -304,46 +101,7 @@ func TestAdmitsFormat_SharesNoStringWithAKind(t *testing.T) { assert.NotEmpty(t, samples[primitiveKind], "%s refines string and has no sample", primitiveKind) for _, s := range all { inTime, _ := admitsFormat("time", stringValue(s)) - assert.False(t, inTime && Admits(primitiveKind, stringValue(s)), "%q is both a time and a value of %s", s, primitiveKind) + assert.False(t, inTime && ir.PrimitiveAdmits(primitiveKind, stringValue(s)) == ir.AdmitsYes, "%q is both a time and a value of %s", s, primitiveKind) } } } - -// TestAdmits_ReadsAHugeExponentWithoutMaterializingIt pins that a literal no -// machine type holds is refused promptly rather than built. -func TestAdmits_ReadsAHugeExponentWithoutMaterializingIt(t *testing.T) { - t.Parallel() - start := time.Now() - for _, primitiveKind := range []ir.PrimitiveKind{ir.PrimitiveInt64, ir.PrimitiveUint64, ir.PrimitiveFloat32, ir.PrimitiveFloat64, ir.PrimitiveDecimal128} { - assert.False(t, Admits(primitiveKind, number("1e1000001")), "%s", primitiveKind) - assert.False(t, Admits(primitiveKind, number("1e99999999999999999999")), "%s", primitiveKind) - } - assert.Less(t, time.Since(start), 5*time.Second) -} - -// TestDecimalOf_DeclinesWhatIsNoReadableNumber pins that a value with no number -// to read is declined rather than read as zero: a literal outside the grammar, one -// past the exponent range a BigVal holds, and a value that is no number at all. -func TestDecimalOf_DeclinesWhatIsNoReadableNumber(t *testing.T) { - t.Parallel() - for _, value := range []ir.Value{number("1p4"), number("1e1000000000000000000"), stringValue("1")} { - _, ok := decimalOf(value) - - assert.False(t, ok, "%v", value) - } - - decimal, ok := decimalOf(number("1e1000001")) - assert.True(t, ok) - assert.Equal(t, int64(1000001), decimal.Exponent()) -} - -// TestInRange_DeclinesABoundThatReadsAsNoNumber pins the second half of the -// judge: a range whose end is no number admits nothing, where reading it as zero -// would admit everything above it. -func TestInRange_DeclinesABoundThatReadsAsNoNumber(t *testing.T) { - t.Parallel() - assert.True(t, inRange(number("5"), "0", "10")) - assert.False(t, inRange(number("5"), "1p4", "10"), "a low end outside the grammar") - assert.False(t, inRange(number("5"), "0", "1p4"), "a high end outside the grammar") - assert.False(t, inRange(number("-1"), "-5", "1p4"), "a high end that would read as zero, above this value") -} diff --git a/compilers/openapi/internal/merge/admitsconstraints.go b/compilers/openapi/internal/merge/admitsconstraints.go deleted file mode 100644 index a9d3774db..000000000 --- a/compilers/openapi/internal/merge/admitsconstraints.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "unicode/utf8" - - "github.com/dexpace/morphic/ir" -) - -// admitsConstraints reports whether value meets every keyword of constraints -// that applies to a value of its kind, judged exactly. A keyword with no judge, -// a pattern or a decimal precision or scale, refuses every value it applies to, -// so a constrained node admits nothing it cannot be shown to fit. A keyword for -// another kind of value, maxLength on a number, constrains nothing. -func admitsConstraints(constraints *ir.Constraints, value ir.Value, depth int) bool { - if constraints == nil { - return true - } - switch value.Kind { - case ir.ValueNumber: - return admitsNumber(constraints, value.Number) - case ir.ValueString: - return constraints.Pattern == "" && within(int64(utf8.RuneCountInString(value.String)), constraints.MinLength, constraints.MaxLength) - case ir.ValueBytes: - return within(int64(len(value.Bytes)), constraints.MinLength, constraints.MaxLength) - case ir.ValueList: - return within(int64(len(value.List)), constraints.MinItems, constraints.MaxItems) && (!constraints.UniqueItems || distinct(value.List, depth)) - case ir.ValueObject: - return within(int64(len(value.Object)), constraints.MinProperties, constraints.MaxProperties) - case ir.ValueNull, ir.ValueBool, ir.ValueSymbol, ir.ValueRefKind, ir.ValueConstructor, - ir.ValueInfinity, ir.ValueNegativeInfinity, ir.ValueNaN: - // No keyword constrains a null or a bool, and the kind judge refuses the - // rest before any keyword is read; no OpenAPI value is non-finite. - return true - default: - return false - } -} - -// admitsNumber reports whether bigVal meets constraints's numeric keywords: -// each bound, and multipleOf where isMultipleOf can say. A number or a bound -// that reads as no number admits nothing. Precision and scale have no judge -// here. -func admitsNumber(constraints *ir.Constraints, bigVal ir.BigVal) bool { - if constraints.Precision != nil || constraints.Scale != nil { - return false - } - decimal, err := bigVal.Decimal() - if err != nil { - return false - } - bounds := []struct { - bound *ir.BigVal - holds func(order int) bool - }{ - {constraints.Min, func(order int) bool { return order >= 0 }}, - {constraints.ExclusiveMin, func(order int) bool { return order > 0 }}, - {constraints.Max, func(order int) bool { return order <= 0 }}, - {constraints.ExclusiveMax, func(order int) bool { return order < 0 }}, - } - for _, b := range bounds { - if b.bound == nil { - continue - } - bound, err := b.bound.Decimal() - if err != nil || !b.holds(decimal.Cmp(bound)) { - return false - } - } - if constraints.MultipleOf == nil { - return true - } - step, err := constraints.MultipleOf.Decimal() - if err != nil { - return false - } - multiple, ok := isMultipleOf(decimal, step) - return ok && multiple -} - -// within reports whether n lies between the inclusive counts lo and hi, either -// of which may be absent. -func within(n int64, lo, hi *int64) bool { - return (lo == nil || n >= *lo) && (hi == nil || n <= *hi) -} - -// distinct reports whether no two of vs are one JSON value (canonicalValue). A -// value it cannot spell canonically is judged not distinct, since its -// uniqueness cannot be shown. -func distinct(vs []ir.Value, depth int) bool { - seen := make(map[string]bool, len(vs)) - for _, value := range vs { - key, ok := canonicalValue(value, depth+1) - if !ok || seen[key] { - return false - } - seen[key] = true - } - return true -} diff --git a/compilers/openapi/internal/merge/admitsconstraints_internal_test.go b/compilers/openapi/internal/merge/admitsconstraints_internal_test.go deleted file mode 100644 index e2eb5242f..000000000 --- a/compilers/openapi/internal/merge/admitsconstraints_internal_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/dexpace/morphic/ir" -) - -// TestAdmitsConstraints_JudgesEachKeyword pins each constraint keyword at its -// boundary, the last value in and the first out, a keyword that does not apply -// to the value's kind, and the keywords with no judge, which refuse what they -// apply to. -func TestAdmitsConstraints_JudgesEachKeyword(t *testing.T) { - t.Parallel() - n := func(i int64) *int64 { return &i } - b := func(s string) *ir.BigVal { bigVal := ir.BigVal(s); return &bigVal } - list := func(vs ...ir.Value) ir.Value { return ir.Value{Kind: ir.ValueList, List: vs} } - obj := func(fs ...ir.Field) ir.Value { return ir.Value{Kind: ir.ValueObject, Object: fs} } - field := func(name string, value ir.Value) ir.Field { return ir.Field{Name: name, Value: value} } - nested := list(list(list(list(list(list(list(list(list(list()))))))))) - for _, tc := range []struct { - name string - c *ir.Constraints - v ir.Value - want bool - }{ - {"no constraints", nil, stringValue("anything"), true}, - {"minimum, at it", &ir.Constraints{Min: b("5")}, number("5.0"), true}, - {"minimum, below it", &ir.Constraints{Min: b("5")}, number("4.9"), false}, - {"exclusiveMinimum, at it", &ir.Constraints{ExclusiveMin: b("5")}, number("5"), false}, - {"exclusiveMinimum, above it", &ir.Constraints{ExclusiveMin: b("5")}, number("5.01"), true}, - {"maximum, at it", &ir.Constraints{Max: b("1e2")}, number("100"), true}, - {"maximum, above it", &ir.Constraints{Max: b("1e2")}, number("100.5"), false}, - {"exclusiveMaximum, at it", &ir.Constraints{ExclusiveMax: b("10")}, number("10"), false}, - {"exclusiveMaximum, below it", &ir.Constraints{ExclusiveMax: b("10")}, number("9"), true}, - {"a bound outside the grammar", &ir.Constraints{Max: b("1p4")}, number("1"), false}, - {"multipleOf, a multiple", &ir.Constraints{MultipleOf: b("0.1")}, number("0.3"), true}, - {"multipleOf, off the step", &ir.Constraints{MultipleOf: b("0.1")}, number("0.35"), false}, - {"multipleOf, a multiple past what a rational builds", &ir.Constraints{MultipleOf: b("2")}, number("1e5000"), true}, - {"multipleOf, a step far below the value", &ir.Constraints{MultipleOf: b("1e-5000")}, number("1"), true}, - {"multipleOf, a step outside the grammar", &ir.Constraints{MultipleOf: b("2p1")}, number("4"), false}, - {"multipleOf, a value outside the grammar", &ir.Constraints{MultipleOf: b("2")}, number("1p4"), false}, - {"minimum, a bound outside the grammar", &ir.Constraints{Min: b("1p4")}, number("4"), false}, - {"precision, which has no judge", &ir.Constraints{Precision: n(5)}, number("1"), false}, - {"scale, which has no judge", &ir.Constraints{Scale: n(2)}, number("1"), false}, - {"a numeric bound on a string", &ir.Constraints{Max: b("1")}, stringValue("hello"), true}, - {"maxLength in code points, at it", &ir.Constraints{MaxLength: n(3)}, stringValue("héé"), true}, - {"maxLength, past it", &ir.Constraints{MaxLength: n(3)}, stringValue("hello"), false}, - {"minLength, short of it", &ir.Constraints{MinLength: n(2)}, stringValue("a"), false}, - {"a length on a number", &ir.Constraints{MaxLength: n(1)}, number("12345"), true}, - {"a pattern, which has no judge", &ir.Constraints{Pattern: "^a"}, stringValue("a"), false}, - {"a pattern on a number", &ir.Constraints{Pattern: "^a"}, number("1"), true}, - {"maxLength on bytes", &ir.Constraints{MaxLength: n(2)}, ir.Value{Kind: ir.ValueBytes, Bytes: []byte("abc")}, false}, - {"maxItems, at it", &ir.Constraints{MaxItems: n(2)}, list(number("1"), number("2")), true}, - {"maxItems, past it", &ir.Constraints{MaxItems: n(2)}, list(number("1"), number("2"), number("3")), false}, - {"minItems, short of it", &ir.Constraints{MinItems: n(1)}, list(), false}, - {"uniqueItems, distinct", &ir.Constraints{UniqueItems: true}, list(number("1"), stringValue("1"), ir.Value{Kind: ir.ValueNull}), true}, - {"uniqueItems, one number spelled twice", &ir.Constraints{UniqueItems: true}, list(number("1"), number("1.0")), false}, - {"uniqueItems, one object in two member orders", &ir.Constraints{UniqueItems: true}, - list(obj(field("a", number("1")), field("b", ir.Value{Kind: ir.ValueBool, Bool: true})), - obj(field("b", ir.Value{Kind: ir.ValueBool, Bool: true}), field("a", number("1")))), false}, - {"uniqueItems, two lists", &ir.Constraints{UniqueItems: true}, list(list(number("1")), list(number("2"))), true}, - {"uniqueItems, a member no instance holds", &ir.Constraints{UniqueItems: true}, list(ir.Value{Kind: ir.ValueSymbol}), false}, - {"uniqueItems, nesting past the cap", &ir.Constraints{UniqueItems: true}, list(nested), false}, - {"maxProperties, past it", &ir.Constraints{MaxProperties: n(1)}, obj(field("a", number("1")), field("b", number("2"))), false}, - {"minProperties, at it", &ir.Constraints{MinProperties: n(1)}, obj(field("a", number("1"))), true}, - {"a count on a bool", &ir.Constraints{MaxItems: n(0)}, ir.Value{Kind: ir.ValueBool}, true}, - {"a kind the IR does not declare", &ir.Constraints{}, ir.Value{Kind: "unknown"}, false}, - {"uniqueItems, a member of a kind the IR does not declare", &ir.Constraints{UniqueItems: true}, - list(ir.Value{Kind: "unknown"}), false}, - } { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - assert.Equal(t, tc.want, admitsConstraints(tc.c, tc.v, 0)) - }) - } -} diff --git a/compilers/openapi/internal/merge/aliaschain.go b/compilers/openapi/internal/merge/aliaschain.go new file mode 100644 index 000000000..780104071 --- /dev/null +++ b/compilers/openapi/internal/merge/aliaschain.go @@ -0,0 +1,233 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// AliasChainAnswerMemos holds merge's answers about a run's alias chains, each +// chain read once for the run however many models and fields ask. Of a chain's +// end it holds only what compile/alias-base-rewritten guards, its ID and kind +// and a primitive's kind, reading the rest when asked. Like its index, it is +// not safe for concurrent use. +type AliasChainAnswerMemos struct { + node func(ir.TypeID) (ir.TypeDef, bool) + index *ir.AliasChainIndex + // walk is the first asker's, whose Admits reads a site in the site's own + // document, so its answer is a function of the site and the kind alone. + walk FieldDeclarationContext + // endsOnTopType answers whether a chain ends on the top type with every + // alias on it adding nothing; kindsBoundBeside the kinds the bounds an + // alias on a chain holds apply to; aliasesAdd what the aliases between two + // aliases add beyond their Bases. + endsOnTopType *ir.AliasChainAnswers[bool] + kindsBoundBeside *ir.AliasChainAnswers[typeformat.JSONInstanceKinds] + aliasesAdd *aliasRunSummaries[aliasAdds] + // admissionsByKind holds, by kind of instance, what a chain's aliases say of an + // instance of that kind (admissionThrough), each built on first use. + admissionsByKind [InstanceNull + 1]*ir.AliasChainAnswers[instanceAdmission] + // kindWalkEnds answers where the kind walk from each type ends + // (registry.kindOf), and aliasViews summarizes what view reads. + kindWalkEnds *ir.AliasChainAnswers[kindWalkEnd] + aliasViews *aliasRunSummaries[aliasView] +} + +// NewAliasChainAnswerMemos returns the memos of the chains index reads, +// reading every type through node, the lookup index is built over, and asking +// walk whether a site admits an instance of a kind. +func NewAliasChainAnswerMemos(node func(ir.TypeID) (ir.TypeDef, bool), index *ir.AliasChainIndex, walk FieldDeclarationContext) *AliasChainAnswerMemos { + memos := &AliasChainAnswerMemos{node: node, index: index, walk: walk} + memos.endsOnTopType = ir.NewAliasChainAnswers(index, func(_ ir.TypeID, typeDef ir.TypeDef) bool { return isTop(typeDef) }, + func(scalar *ir.Scalar, next bool) bool { return next && aliasAddsNothingBeyondBase(scalar) }) + memos.kindsBoundBeside = ir.NewAliasChainAnswers(index, func(ir.TypeID, ir.TypeDef) typeformat.JSONInstanceKinds { return 0 }, + func(scalar *ir.Scalar, next typeformat.JSONInstanceKinds) typeformat.JSONInstanceKinds { + return next | boundKinds(scalar.Constraints) + }) + memos.aliasesAdd = newAliasRunSummaries(index, node, addsOfAlias, combineAdds) + memos.aliasViews = newAliasRunSummaries(index, node, viewOfAlias, combineViews) + memos.kindWalkEnds = ir.NewAliasChainAnswers(index, kindWalkEndAtChainEnd, func(scalar *ir.Scalar, next kindWalkEnd) kindWalkEnd { + return kindWalkEndFrom(node, scalar, next) + }) + return memos +} + +// aliasAdds is what a run of aliases down a chain adds beyond their Bases: +// whether one admits null in its Base, and whether one says more than its Base +// (aliasAddsNothingBeyondBase). +type aliasAdds struct { + null, saysMore bool +} + +// addsOfAlias is what scalar alone adds. +func addsOfAlias(scalar *ir.Scalar) aliasAdds { + return aliasAdds{null: scalar.Base.Nullable, saysMore: !aliasAddsNothingBeyondBase(scalar)} +} + +// combineAdds is what two adjacent runs add together. +func combineAdds(near, far aliasAdds) aliasAdds { + return aliasAdds{null: near.null || far.null, saysMore: near.saysMore || far.saysMore} +} + +// instanceAdmission is what a chain says of an instance of one kind: whether +// every site of it, its end a structure, admits every instance of the kind, +// and whether each of them says nothing beyond its Base; and whether a site of +// it admits none. +type instanceAdmission struct { + admits, saysNothing, none bool +} + +// admissionOf returns the memos' answers for an instance of kind, read from one +// node on its chain through the aliases after it, built on first use. A chain's +// end answers as admitting and saying nothing here: its own answer is read when +// asked (admissionThrough), since a settlement may rewrite what a model end +// holds. +func (memos *AliasChainAnswerMemos) admissionOf(kind JSONInstanceKind) *ir.AliasChainAnswers[instanceAdmission] { + if answers := memos.admissionsByKind[kind]; answers != nil { + return answers + } + answers := ir.NewAliasChainAnswers(memos.index, + func(ir.TypeID, ir.TypeDef) instanceAdmission { + return instanceAdmission{admits: true, saysNothing: true} + }, + func(scalar *ir.Scalar, next instanceAdmission) instanceAdmission { + admission, _ := sourceAdmission(memos.walk, scalar.Provenance, kind) + out := instanceAdmission{none: next.none || admission == AdmitsNoneOfKind} + if next.admits && admission == AdmitsEveryOfKind { + out.admits, out.saysNothing = true, next.saysNothing && aliasAddsNothingBeyondBase(scalar) + } + return out + }) + memos.admissionsByKind[kind] = answers + return answers +} + +// admissionThrough returns what the chain from id says of an instance of +// kind: what its aliases say, read once a run, and what the node it ends on +// says, read as it is now. It is false where the chain repeats a type or names +// one the registry lacks. +func (memos *AliasChainAnswerMemos) admissionThrough(id ir.TypeID, kind JSONInstanceKind) (instanceAdmission, bool) { + aliases, read := memos.admissionOf(kind).AnswerFor(id) + if !read || !aliases.admits { + return instanceAdmission{none: aliases.none}, read + } + end, _ := memos.index.End(id) + node, held := memos.node(end) + if _, literal := node.(*ir.Literal); literal { + // A literal judged here holds a value of another kind than the one + // asked (classify), so it admits none of it. + return instanceAdmission{none: true}, true + } + if !held || ir.IsNilTypeDef(node) || !isStructural(node) { + return instanceAdmission{}, true + } + switch own, _ := sourceAdmission(memos.walk, node.Common().Provenance, kind); own { + case AdmitsNoneOfKind: + return instanceAdmission{none: true}, true + case AdmitsEveryOfKind: + return instanceAdmission{admits: true, saysNothing: aliases.saysNothing && structureAddsNothingBeyondBase(node, false)}, true + default: + return instanceAdmission{}, true + } +} + +// endOf returns the node the alias scalar represents, the node its chain ends +// on, or scalar where the chain repeats a type or ends naming one the registry +// lacks, which represents itself. +func (memos *AliasChainAnswerMemos) endOf(scalar *ir.Scalar) ir.TypeDef { + end, cyclic := memos.index.End(scalar.Base.Target) + if cyclic { + return scalar + } + node, held := memos.node(end) + if !held || ir.IsNilTypeDef(node) { + return scalar + } + return node +} + +// kindWalkEnd is where the kind walk from one type ends (registry.kindOf): the +// type it ends on, none where it ends in no kind, and the first Encoding met on +// the way, which decides how a primitive's values are read. +type kindWalkEnd struct { + end ir.TypeID + encoding *ir.Encoding +} + +// kindAt returns where the kind walk from id ends (kindWalkEndFrom), each alias +// it passes answered once for the run. A walk reaching a type it passed +// already, a Scalar with no Base, or a type the registry lacks, ends on none. +func (memos *AliasChainAnswerMemos) kindAt(id ir.TypeID) kindWalkEnd { + walkEnd, _ := memos.kindWalkEnds.AnswerFor(id) + return walkEnd +} + +// kindWalkEndAtChainEnd is where the kind walk from typeDef, the type id names +// at a chain's end, ends: on it, but for a Scalar with no Base, which ends in +// no kind. +func kindWalkEndAtChainEnd(id ir.TypeID, typeDef ir.TypeDef) kindWalkEnd { + if _, opaque := typeDef.(*ir.Scalar); opaque { + return kindWalkEnd{} + } + return kindWalkEnd{end: id} +} + +// kindWalkEndFrom is where the kind walk from the alias scalar ends, next where +// it ends from scalar's Base: next, or the type scalar's values travel as +// (travelsAs). +func kindWalkEndFrom(node func(ir.TypeID) (ir.TypeDef, bool), scalar *ir.Scalar, next kindWalkEnd) kindWalkEnd { + if travels := travelsAs(node, scalar); travels != scalar.Base.Target { + next = kindWalkEnd{end: travels} + } + if next.end != "" && scalar.Encoding.Encodes() { + next.encoding = scalar.Encoding + } + return next +} + +// kindWalkEndAtEnd is what a kind walk reads of the type id it ended on, found +// through node as that type is: a primitive's kind, or an enum's value +// type, and false for any other type, or none. +func kindWalkEndAtEnd(node func(ir.TypeID) (ir.TypeDef, bool), id ir.TypeID) endKind { + typeDef, held := node(id) + if !held || ir.IsNilTypeDef(typeDef) { + return endKind{} + } + switch t := typeDef.(type) { + case *ir.Primitive: + return endKind{primitive: t.PrimitiveKind, read: true} + case *ir.Enum: + return endKind{primitive: t.ValueType, isEnum: true, read: true} + default: + return endKind{} + } +} + +// endKind is the primitive kind a kind walk's end gives (kindWalkEndAtEnd), +// whether the end is an enum, whose value type it is, and whether it gives one. +type endKind struct { + primitive ir.PrimitiveKind + isEnum bool + read bool +} + +// travelsAs returns the type the values of scalar are instances of: its Base, +// but for a Base its Encoding's WireType does not spell, whose values then +// travel as that type, as an instant written as its seconds is a number. A Base +// the WireType spells keeps its own kind, as bytes written as a base64 string +// do. +func travelsAs(node func(ir.TypeID) (ir.TypeDef, bool), scalar *ir.Scalar) ir.TypeID { + if scalar.Encoding == nil || scalar.Encoding.WireType == nil { + return scalar.Base.Target + } + base, baseOK := node(scalar.Base.Target) + wire, wireOK := node(scalar.Encoding.WireType.Target) + basePrimitive, baseIsPrimitive := base.(*ir.Primitive) + wirePrimitive, wireIsPrimitive := wire.(*ir.Primitive) + if !baseOK || !wireOK || !baseIsPrimitive || !wireIsPrimitive || spelledIn(basePrimitive.PrimitiveKind, wirePrimitive.PrimitiveKind) { + return scalar.Base.Target + } + return scalar.Encoding.WireType.Target +} diff --git a/compilers/openapi/internal/merge/aliaschain_cost_internal_test.go b/compilers/openapi/internal/merge/aliaschain_cost_internal_test.go new file mode 100644 index 000000000..094bb91fa --- /dev/null +++ b/compilers/openapi/internal/merge/aliaschain_cost_internal_test.go @@ -0,0 +1,165 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" +) + +// chainSizes are the lengths a cost row reads a chain at: each past the 64 +// hops a walk once stopped at, and doubling, so the marginal growth shows a +// quadratic term apart from what every size spends alike. +var chainSizes = [3]int{100, 200, 400} + +// chainAlias is the ID of the alias i steps above integer. +func chainAlias(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("type/I%d", i)) } + +// usesOfOneChain is a registry holding a chain of n aliases of integer, I0 over +// integer and each I(i) over I(i-1), each with a description of its own, and +// the alias K over I0, as a chain of $refs with descriptions lowers. +func usesOfOneChain(count int) ir.TypeRegistry { + reg := ir.TypeRegistry{ + "type/primitive/integer": &ir.Primitive{ID: "type/primitive/integer", PrimitiveKind: ir.PrimitiveInteger}, + "type/primitive/number": &ir.Primitive{ID: "type/primitive/number", PrimitiveKind: ir.PrimitiveNumber}, + "type/K": &ir.Scalar{ID: "type/K", Docs: ir.Docs{Description: "k"}, Base: &ir.TypeRef{Target: chainAlias(0)}}, + } + below := ir.TypeID("type/primitive/integer") + for i := range count { + reg[chainAlias(i)] = &ir.Scalar{ID: chainAlias(i), Docs: ir.Docs{Description: fmt.Sprintf("alias %d", i)}, Base: &ir.TypeRef{Target: below}} + below = chainAlias(i) + } + return reg +} + +// foldPerUse settles one model per alias of reg's chain, each folding f +// declared as that alias in its entry 0 and as other in its entry 1, with a +// default on whichever declaration defaulted names, through one Merger whose +// alias index and memos count their reads, and returns the reads, each +// model's f and the codes each model's folds report. +func foldPerUse(t *testing.T, reg ir.TypeRegistry, count int, other ir.TypeID, defaulted int) (int, []ir.Property, [][]string) { + t.Helper() + reads := 0 + stubbed, _ := stubMergerOver(reg, func(id ir.TypeID) (ir.TypeDef, bool) { + reads++ + typeDef, ok := reg[id] + return typeDef, ok + }) + fields := make([]ir.Property, 0, count) + codes := make([][]string, 0, count) + for i := range count { + at := fmt.Sprintf("/W%d", i) + model := &ir.Model{ID: ir.TypeID("type" + at), Provenance: ptrAt(jsontext.Pointer(at))} + reg[model.ID] = model + idx := NewModelPropertyDeclarations(model) + for entry, target := range []ir.TypeID{chainAlias(i), other} { + property := declared("f", target, fmt.Sprintf("%s/allOf/%d/properties/f", at, entry)) + if entry == defaulted { + property.Default = &ir.Value{Kind: ir.ValueNumber, Number: "1"} + } + idx.MergeProperty(property, written(`{"$ref":"x"}`), "") + } + diags, _ := idx.Settle(stubbed.Merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{"f": true}) + require.Len(t, model.Properties, 1, "W%d folds one f", i) + fields = append(fields, model.Properties[0]) + codes = append(codes, irtest.DiagCodes(diags)) + } + return reads, fields, codes +} + +// assertMarginalGrowth holds three counts taken at n, 2n and 4n to linear +// growth: the third step adds at most two and a half times what the second +// does, where a linear count adds twice and a quadratic one four times. +func assertMarginalGrowth(t *testing.T, counts [3]int, what string) { + t.Helper() + require.Less(t, counts[0], counts[1], "%s grows with the chain: %v", what, counts) + assert.LessOrEqual(t, float64(counts[2]-counts[1]), 2.5*float64(counts[1]-counts[0]), + "%s at %v: %v", what, chainSizes, counts) +} + +// TestAliasChainAnswerMemos_ManyUsesOfOneChainReadItLinearly pins the per-run +// memos over many uses of one chain: a model per alias folding a field typed by +// it beside one typed number keeps the alias at every length, past the 64 +// aliases a walk once read, with nothing reported, and the chain's aliases are +// read a bounded number of times however many fields read them. +func TestAliasChainAnswerMemos_ManyUsesOfOneChainReadItLinearly(t *testing.T) { + t.Parallel() + var reads [3]int + for k, n := range chainSizes { + var fields []ir.Property + var codes [][]string + reads[k], fields, codes = foldPerUse(t, usesOfOneChain(n), n, "type/primitive/number", -1) + + for i, field := range fields { + assert.Equal(t, chainAlias(i), field.Type.Target, "at %d aliases: W%d keeps its alias", n, i) + assert.Empty(t, codes[i], "at %d aliases: W%d reports nothing", n, i) + } + } + assertMarginalGrowth(t, reads, "the reads") +} + +// TestAliasChainAnswerMemos_AViewUpToASharedAliasReadsLinearly pins the range a +// view reads: a model per alias folding a field typed by it beside one typed K, +// an alias of the chain's far end alike to it, reads the aliases between +// linearly in all, with or without a default on each use, where a view reading +// alias by alias reads the square, and every model folds alike, taking its +// alias, the least of the two. +func TestAliasChainAnswerMemos_AViewUpToASharedAliasReadsLinearly(t *testing.T) { + t.Parallel() + for name, defaulted := range map[string]int{"no default": -1, "a default on K": 1, "a default on the chain": 0} { + var reads [3]int + for k, n := range chainSizes { + var fields []ir.Property + var codes [][]string + reads[k], fields, codes = foldPerUse(t, usesOfOneChain(n), n, "type/K", defaulted) + + for i := 1; i < n; i++ { + assert.Equal(t, chainAlias(i), fields[i].Type.Target, "%s at %d aliases: W%d takes its alias", name, n, i) + assert.Equal(t, codes[1], codes[i], "%s at %d aliases: W%d reports as W1 does", name, n, i) + assert.Equal(t, fields[1].Default, fields[i].Default, "%s at %d aliases: W%d's default", name, n, i) + } + } + assertMarginalGrowth(t, reads, name+": the reads") + } +} + +// TestAliasChainAnswerMemos_AreBuiltOncePerRun pins that the memos a run's +// Mergers share are the run's: a second Merger over the same memos reads no +// alias the first read, only a few nodes, the ends of chains among them, which +// a reading reads as it is asked. +func TestAliasChainAnswerMemos_AreBuiltOncePerRun(t *testing.T) { + t.Parallel() + reg := usesOfOneChain(100) + reads := 0 + stubbed, _ := stubMergerOver(reg, func(id ir.TypeID) (ir.TypeDef, bool) { + reads++ + typeDef, ok := reg[id] + return typeDef, ok + }) + settle := func(name string, merger Merger) { + model := &ir.Model{ID: ir.TypeID("type/" + name), Provenance: ptrAt(jsontext.Pointer("/" + name))} + reg[model.ID] = model + idx := NewModelPropertyDeclarations(model) + for entry, target := range []ir.TypeID{chainAlias(99), "type/K"} { + idx.MergeProperty(declared("f", target, fmt.Sprintf("/%s/allOf/%d/properties/f", name, entry)), written(`{"$ref":"x"}`), "") + } + idx.Settle(merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{"f": true}) + } + + settle("first", stubbed.Merger) + first := reads + second := stubbed.Merger + second.Walk = &stubWalk{reg: reg} + settle("second", second) + + require.Greater(t, first, 100, "the first fold reads the chain") + assert.LessOrEqual(t, reads-first, 20, "the second reads a few nodes, not the chain the first settled: %d, then %d", first, reads-first) +} diff --git a/compilers/openapi/internal/merge/aliaschain_internal_test.go b/compilers/openapi/internal/merge/aliaschain_internal_test.go new file mode 100644 index 000000000..9f3c24cde --- /dev/null +++ b/compilers/openapi/internal/merge/aliaschain_internal_test.go @@ -0,0 +1,251 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// TestView_ReadsEveryEndThroughOneCombination pins the view's three readings of +// a chain whose aliases one combination reads: a stop no alias names reads as +// none, so the chain is read to its end; two aliases whose patterns no one +// value states leave the alias representing itself; and an alias over an opaque +// scalar, which names no kind, reads as that scalar holding the bounds both +// say. +func TestView_ReadsEveryEndThroughOneCombination(t *testing.T) { + t.Parallel() + reg := viewRegistry() + reg["type/L-pattern-a"] = &ir.Scalar{ID: "type/L-pattern-a", Base: &ir.TypeRef{Target: "type/L"}, Constraints: &ir.Constraints{Pattern: "^a"}} + reg["type/L-pattern-b"] = &ir.Scalar{ID: "type/L-pattern-b", Base: &ir.TypeRef{Target: "type/L-pattern-a"}, Constraints: &ir.Constraints{Pattern: "^b"}} + reg["type/O"] = &ir.Scalar{ID: "type/O", Constraints: &ir.Constraints{MaxLength: new(int64(3))}} + reg["type/O-min"] = &ir.Scalar{ID: "type/O-min", Base: &ir.TypeRef{Target: "type/O"}, Constraints: &ir.Constraints{MinLength: new(int64(1))}} + registry := registryReader{resolve: stubResolve(reg)} + + list, ok := registry.view(reg["type/L-max-docs"], "type/E").(*ir.List) + require.True(t, ok, "a stop the chain does not name reads as no stop") + assert.Equal(t, &ir.Constraints{MinItems: new(int64(2)), MaxItems: new(int64(3))}, list.Constraints) + assert.Same(t, reg["type/L-pattern-b"], registry.view(reg["type/L-pattern-b"], ""), "patterns no one value states") + opaque, ok := registry.view(reg["type/O-min"], "").(*ir.Scalar) + require.True(t, ok, "an alias of an opaque scalar reads as the scalar") + assert.Equal(t, ir.TypeID("type/O"), opaque.ID) + assert.Nil(t, opaque.Base, "which names no kind") + assert.Equal(t, &ir.Constraints{MinLength: new(int64(1)), MaxLength: new(int64(3))}, opaque.Constraints) +} + +// TestBoundsBeside_ReadsEveryAliasOfTheChain pins where a union read through +// aliases holds bounds of its own applying to a kind: on the union, on the +// alias judged, or on an alias further down, nowhere for a chain of aliases +// saying none, and nowhere for one whose bounds bind another kind. +func TestBoundsBeside_ReadsEveryAliasOfTheChain(t *testing.T) { + t.Parallel() + maxItems := &ir.Constraints{MaxItems: new(int64(3))} + reg := ir.TypeRegistry{ + "type/U": &ir.Union{ID: "type/U"}, + "type/UB": &ir.Union{ID: "type/UB", Constraints: maxItems}, + "type/UU": &ir.Union{ID: "type/UU", Constraints: &ir.Constraints{UniqueItems: true}}, + "type/U-max": &ir.Scalar{ID: "type/U-max", Base: &ir.TypeRef{Target: "type/U"}, Constraints: maxItems}, + "type/U-bare": &ir.Scalar{ID: "type/U-bare", Base: &ir.TypeRef{Target: "type/U"}}, + "type/U-over-max": &ir.Scalar{ID: "type/U-over-max", Base: &ir.TypeRef{Target: "type/U-max"}}, + "type/UB-bare": &ir.Scalar{ID: "type/UB-bare", Base: &ir.TypeRef{Target: "type/UB"}}, + } + stubbed, _ := stubMerger(reg) + for id, want := range map[ir.TypeID]bool{ + "type/U": false, "type/UB": true, "type/UU": true, "type/U-max": true, "type/U-bare": false, "type/U-over-max": true, + "type/UB-bare": true, + } { + assert.Equal(t, want, boundsBeside(stubbed.registryReader(), reg[id], typeformat.InstanceArray), "%s against an array", id) + assert.False(t, boundsBeside(stubbed.registryReader(), reg[id], typeformat.InstanceString|typeformat.InstanceInteger), + "%s against text or an integer", id) + } +} + +// TestAgainstOtherInstance_ReadsAChainOnceAKind pins the structure judgment +// through an alias: the run's memos and a judgment naming none answer alike, a +// second judgment of one kind reads the chain's answers already settled, and an +// alias whose source admits no string leaves the structure disjoint from one. +func TestAgainstOtherInstance_ReadsAChainOnceAKind(t *testing.T) { + t.Parallel() + reg := ir.TypeRegistry{ + "type/obj": &ir.Model{ID: "type/obj", Provenance: ptrAt("/untyped/obj")}, + "type/alias": &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/obj"}, Provenance: ptrAt("/untyped/alias")}, + "type/typed": &ir.Scalar{ID: "type/typed", Base: &ir.TypeRef{Target: "type/obj"}, Provenance: ptrAt("/typed")}, + } + stubbed, _ := stubMerger(reg) + withMemos := stubbed.judgeAt(nil, nil) + for name, judgment := range map[string]typeJudge{"the run's memos": withMemos, "memos of its own": judge(stubbed)} { + for range 2 { + assert.Equal(t, secondTypeIsNarrower, judgment.againstOtherInstance(reg["type/alias"], nil, 1, InstanceString, true), name) + } + assert.Equal(t, relDisjoint, judgment.againstOtherInstance(reg["type/typed"], nil, 1, InstanceString, true), name) + } +} + +// TestSettleCompositionCycle_ReadsWhatPartsOutsideItBring pins what a cycle's +// members read beyond their own declarations, A composing B and O1, B composing +// A and O2: a name a member declares and a part brings folds across both, the +// member declaring it keeping its own identity and the other taking one in the +// composed namespace, required where it requires the name; a name only parts +// bring apart folds once, reported once; and a name one declaration gives, +// carried or a member's own, is in every member's table. +func TestSettleCompositionCycle_ReadsWhatPartsOutsideItBring(t *testing.T) { + t.Parallel() + reg := cycleRegistry() + model := func(id ir.TypeID, at string, properties ...ir.Property) *ir.Model { + reg[id] = &ir.Model{ID: id, Provenance: ptrAt(jsontext.Pointer(at)), Properties: properties} + return reg[id].(*ir.Model) + } + o1 := model("type/O1", "/O1", declared("id", "type/primitive/string", "/O1/properties/id"), + declared("tag", "type/primitive/string", "/O1/properties/tag")) + o2 := model("type/O2", "/O2", declared("tag", "type/primitive/integer", "/O2/properties/tag"), + declared("note", "type/primitive/string", "/O2/properties/note")) + a, b := model("type/A", "/A"), model("type/B", "/B") + a.Base, a.Mixins = &ir.TypeRef{Target: b.ID}, []ir.TypeRef{{Target: o1.ID}} + b.Base, b.Mixins, b.Requires = &ir.TypeRef{Target: a.ID}, []ir.TypeRef{{Target: o2.ID}}, []string{"id"} + aFields, bFields := NewModelPropertyDeclarations(a), NewModelPropertyDeclarations(b) + aFields.Compose(b.ID, "/A/allOf/0") + aFields.Compose(o1.ID, "/A/allOf/1") + aFields.MergeProperty(declared("id", "type/primitive/string", "/A/properties/id"), written(`{"own":true}`), "") + bFields.Compose(a.ID, "/B/allOf/0") + bFields.Compose(o2.ID, "/B/allOf/1") + bFields.MergeProperty(declared("solo", "type/primitive/string", "/B/properties/solo"), written(`{"own":true}`), "") + tables := map[ir.TypeID]RedeclaredWireNameTable{} + for _, part := range []*ir.Model{o1, o2} { + tables[part.ID] = RedeclaredWireNameTable{} + for i := range part.Properties { + tables[part.ID][part.Properties[i].WireName] = DeclaredAt(ir.PropertyDecl{Owner: part.ID, Property: &part.Properties[i]}) + } + } + stubbed, _ := stubMerger(reg) + + diags, settled := SettleCompositionCycle([]*ModelPropertyDeclarations{bFields, aFields}, stubbed.Merger, tables, + map[string]bool{"id": true, "tag": true, "note": true, "solo": true}) + + assert.Equal(t, ir.PropertyID("property/A/properties/id"), idOf(t, reg, a.ID).ID, "A keeps its own declaration's identity") + bID := idOf(t, reg, b.ID) + assert.Equal(t, mintedProperty("/B/allOf/properties/id"), bID.ID, "B, declaring none, takes one in the composed namespace") + assert.True(t, bID.Required, "required, as B requires it") + assert.Empty(t, b.Requires, "which the name leaves") + require.Len(t, diags, 1, "%+v", diags) + assert.ElementsMatch(t, []string{string(mintedProperty("/A/allOf/properties/tag")), string(mintedProperty("/B/allOf/properties/tag"))}, + decidedBy(diags[0]), "the parts' tags fold once, deciding each member's") + for _, member := range []ir.TypeID{a.ID, b.ID} { + assert.Equal(t, o2.ID, settled[member]["note"].Owner, "%s: a name one part brings", member) + assert.Equal(t, b.ID, settled[member]["solo"].Owner, "%s: a name one member declares", member) + } +} + +// TestSettleCompositionCycle_FoldsInTheOrderTheDeclarationsAreWritten pins the +// chain's order where the members' IDs and places disagree: A, written at /Z, +// and B, written at /Y, redeclare id apart, so B's integer is written first and +// A's string last, and both take the string, whichever ID sorts first. +func TestSettleCompositionCycle_FoldsInTheOrderTheDeclarationsAreWritten(t *testing.T) { + t.Parallel() + reg := cycleRegistry() + member := func(id ir.TypeID, at string, next ir.TypeID, target ir.TypeID) *ModelPropertyDeclarations { + model := &ir.Model{ID: id, Base: &ir.TypeRef{Target: next}, Provenance: ptrAt(jsontext.Pointer(at))} + reg[id] = model + fields := NewModelPropertyDeclarations(model) + fields.Compose(next, jsontext.Pointer(at+"/allOf/0")) + fields.MergeProperty(declared("id", target, at+"/properties/id"), written(`{"own":true}`), "") + return fields + } + a := member("type/A", "/Z", "type/B", "type/primitive/string") + b := member("type/B", "/Y", "type/A", "type/primitive/integer") + + settleCycle(reg, []*ModelPropertyDeclarations{a, b}) + + for _, id := range []ir.TypeID{"type/A", "type/B"} { + assert.Equal(t, ir.TypeID("type/primitive/string"), idOf(t, reg, id).Type.Target, "%s takes the one written last", id) + } +} + +// TestAgainstOtherInstance_ReadsAModelEndAsItIsWhenAsked pins what the +// run's memos hold of a model a chain ends on: nothing a settlement may +// rewrite. After a first judgment through the alias, a settlement keeping an +// entry on the model leaves it saying more than a structure, and one moving +// its provenance under a site admitting no string leaves it disjoint; each +// later judgment sees it. +func TestAgainstOtherInstance_ReadsAModelEndAsItIsWhenAsked(t *testing.T) { + t.Parallel() + model := &ir.Model{ID: "type/obj", Provenance: ptrAt("/untyped/obj")} + reg := ir.TypeRegistry{ + "type/obj": model, + "type/alias": &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/obj"}, Provenance: ptrAt("/untyped/alias")}, + } + stubbed, _ := stubMerger(reg) + judgment := stubbed.judgeAt(nil, nil) + assert.Equal(t, secondTypeIsNarrower, judgment.againstOtherInstance(reg["type/alias"], nil, 1, InstanceString, true)) + + model.Unmodeled = ir.Unmodeled{"x-kept": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue(`1`)}} + assert.Equal(t, relOverlap, judgment.againstOtherInstance(reg["type/alias"], nil, 1, InstanceString, true), "an entry kept since") + + model.Provenance = ptrAt("/typed/obj") + assert.Equal(t, relDisjoint, judgment.againstOtherInstance(reg["type/alias"], nil, 1, InstanceString, true), "a site moved since") +} + +// TestAgainstOtherInstance_ReadsWhatAChainShows pins what a structure through +// an alias shares with another instance's type by what the chain shows: an +// alias admitting none of it below one admitting every one, or a chain ending +// on a literal, leaves the two disjoint; a structure admitting some, a chain +// naming a type the registry lacks, or one ending on a node no source read +// judges, shows nothing; and two structures of different instance types neither of which +// shows a shared value or none are undecided, while one showing either +// decides. +func TestAgainstOtherInstance_ReadsWhatAChainShows(t *testing.T) { + t.Parallel() + reg := ir.TypeRegistry{ + "type/obj": &ir.Model{ID: "type/obj", Provenance: ptrAt("/untyped/obj")}, + "type/some-obj": &ir.Model{ID: "type/some-obj", Provenance: ptrAt("/some/obj")}, + "type/lit": &ir.Literal{ID: "type/lit", Value: number("1")}, + "type/typed": &ir.Scalar{ID: "type/typed", Base: &ir.TypeRef{Target: "type/obj"}, Provenance: ptrAt("/typed")}, + "type/outer": &ir.Scalar{ID: "type/outer", Base: &ir.TypeRef{Target: "type/typed"}, Provenance: ptrAt("/untyped/outer")}, + "type/over-some": &ir.Scalar{ID: "type/over-some", Base: &ir.TypeRef{Target: "type/some-obj"}, Provenance: ptrAt("/untyped/over-some")}, + "type/over-lit": &ir.Scalar{ID: "type/over-lit", Base: &ir.TypeRef{Target: "type/lit"}, Provenance: ptrAt("/untyped/over-lit")}, + "type/over-absent": &ir.Scalar{ID: "type/over-absent", Base: &ir.TypeRef{Target: "type/absent"}, Provenance: ptrAt("/untyped/over-absent")}, + "type/over-text": &ir.Scalar{ID: "type/over-text", Base: &ir.TypeRef{Target: "type/primitive/string"}, Provenance: ptrAt("/untyped/over-text")}, + "type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}, + } + stubbed, _ := stubMerger(reg) + for alias, want := range map[ir.TypeID]relation{ + "type/outer": relDisjoint, + "type/over-some": relUndecided, + "type/over-lit": relDisjoint, + "type/over-absent": relUndecided, + "type/over-text": relUndecided, + } { + assert.Equal(t, want, stubbed.judgeAt(nil, nil).againstOtherInstance(reg[alias], nil, 1, InstanceString, true), alias) + } + assert.Equal(t, relUndecided, acrossInstances(relUndecided, relUndecided)) + assert.Equal(t, relDisjoint, acrossInstances(relDisjoint, relDisjoint)) + assert.Equal(t, relOverlap, acrossInstances(relUndecided, secondTypeIsNarrower)) +} + +// TestKindOf_ReadsAnEnumEndAsItIsWhenAsked pins the kind walk's memo: it +// holds where a chain ends, and the enum it ends on is read when asked, so a +// value type set after a first walk is the one a later walk reads. +func TestKindOf_ReadsAnEnumEndAsItIsWhenAsked(t *testing.T) { + t.Parallel() + enum := &ir.Enum{ID: "type/E", ValueType: ir.PrimitiveString} + reg := ir.TypeRegistry{ + "type/E": enum, + "type/E-alias": &ir.Scalar{ID: "type/E-alias", Base: &ir.TypeRef{Target: "type/E"}}, + } + stubbed, _ := stubMerger(reg) + registry := stubbed.registryReader() + kind, ok := registry.kindOf(ir.TypeRef{Target: "type/E-alias"}) + require.True(t, ok) + assert.Equal(t, ir.PrimitiveString, kind.primitive) + + enum.ValueType = ir.PrimitiveInteger + kind, ok = registry.kindOf(ir.TypeRef{Target: "type/E-alias"}) + require.True(t, ok) + assert.Equal(t, ir.PrimitiveInteger, kind.primitive, "the value type set since") +} diff --git a/compilers/openapi/internal/merge/apart.go b/compilers/openapi/internal/merge/apart.go new file mode 100644 index 000000000..0db2ed11e --- /dev/null +++ b/compilers/openapi/internal/merge/apart.go @@ -0,0 +1,93 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// markApart marks each declaration whose member at position is a node +// declared apart from target, the node the position names, yet alike to it +// (alikeApart): nothing there names the member's node, so keepApart keeps +// that declaration verbatim. held says which members the position's node holds. +func markApart(fieldFold *fieldFold, position position, held func(k int) bool, target ir.TypeID, depth int) { + named := position.naming(target) + for k, member := range position.members { + if !held(k) || member.ref.Target == position.members[named].ref.Target || !alikeApart(fieldFold, position, named, k, depth) { + continue + } + fieldFold.apart[member.decl] = true + } +} + +// naming returns the member of p whose type is target, the chosen member where +// it is one or none is: an intersection names the least of the nodes it equals +// (reusedNode), which need not be the chosen member's. +func (p position) naming(target ir.TypeID) int { + if p.members[p.chosen].ref.Target == target { + return p.chosen + } + for k, member := range p.members { + if member.ref.Target == target { + return k + } + } + return p.chosen +} + +// alikeApart reports whether member k of p names a node declared apart from +// member named's (hoistedAt) that admits the same values: the two are one +// type, or would be but for which of the two admits null. +func alikeApart(fieldFold *fieldFold, position position, named, k, depth int) bool { + member, namedMember := position.members[k], position.members[named] + typeDef, ok := fieldFold.g.resolve(member.ref.Target) + if !ok || hoistedAt(typeDef, fieldFold.decls[member.decl].sites()) { + return false + } + switch position.rel[named][k] { + case relSame: + return true + case firstTypeIsNarrower: + namedMember.ref.Nullable = member.ref.Nullable + judge := fieldFold.g.judgeAt(fieldFold.decls[namedMember.decl].sites(), fieldFold.decls[member.decl].sites()) + return judge.relateFrom(namedMember.ref, member.ref, depth) == relSame + default: + return false + } +} + +// keepApart keeps verbatim beside the field, under chosenDeclarationKey and +// with an info, each declaration the model holds alone that markApart marked +// and the fold passed over nothing else of. One another model's declaration +// brings stays declared there, naming its node. +func keepApart(fieldFold *fieldFold) { + for i, declaration := range fieldFold.decls { + if !fieldFold.apart[i] || fieldFold.passedOver[i] || declaration.via != nil { + continue + } + at := declaration.property.Provenance + for _, diagnostic := range fieldFold.g.keepVerbatim(&fieldFold.merged.Unmodeled, chosenDeclarationKey(fieldFold.fieldPointer, at.Pointer), at, declaration.source) { + fieldFold.notes[i] = append(fieldFold.notes[i], note{sev: diagnostic.Severity, code: diagnostic.Code, message: diagnostic.Message, + at: diagnostic.Provenance}) + } + place := fieldPlace(fieldFold.g, declaration, fieldGivenTogether) + fieldFold.note(declarationIndex(i), ir.SeverityInfo, diag.DegradedConstruct, + "field %q names one of two types declared apart that admit the same values; the declaration at %s names "+ + "the other, and is kept verbatim under Unmodeled", fieldFold.merged.WireName, placeName(fieldFold.g.Sources, place, place.Source)) + } +} + +// chosenDeclarationKey is the Unmodeled key a fold keeps the declaration written +// at declarationPointer under: its pointer below the schema fieldPointer, +// /allOf/properties/, names, so no two declarations of the field +// share one. +func chosenDeclarationKey(fieldPointer, declarationPointer jsontext.Pointer) string { + schema := fieldPointer.Parent().Parent().Parent() + return annotation.EntryKey("", "") + strings.TrimPrefix(strings.TrimPrefix(string(declarationPointer), string(schema)), "/") +} diff --git a/compilers/openapi/internal/merge/bounds.go b/compilers/openapi/internal/merge/bounds.go index ee5094bd0..da0998e95 100644 --- a/compilers/openapi/internal/merge/bounds.go +++ b/compilers/openapi/internal/merge/bounds.go @@ -4,27 +4,26 @@ package merge import ( + "cmp" "reflect" "slices" "github.com/dexpace/morphic/ir" ) -// boundsRelation judges two nodes alike in all but the bounds a and b. The node -// whose bounds say all the other's do is narrower, and two that say one thing -// are the same, as two written alike do without a keyword read. Otherwise -// neither holds the other, and the two meet, which is the verdict too on a +// boundsRelation judges two nodes alike in all but the bounds a and b: two +// saying one thing are the same, the node whose bounds say all the other's do +// is narrower, and otherwise the two intersect, which is the answer too on a // keyword no one value states. func boundsRelation(a, b *ir.Constraints) relation { if reflect.DeepEqual(a, b) { return relSame } - if _, _, conflict := constraintsConflict(a, b); conflict { - return relMeet + intersected := ir.ConstraintIntersectionOf(a).Intersect(ir.ConstraintIntersectionOf(b)) + if len(intersected.DisagreeingKeywords()) > 0 { + return relIntersect } - var met ir.Constraints - Constraints(Constraints(&met, a), b) - aHolds, bHolds := sameBounds(&met, a), sameBounds(&met, b) + aHolds, bHolds := sameBounds(intersected.AgreedConstraints(), a), sameBounds(intersected.AgreedConstraints(), b) switch { case aHolds && bHolds: return relSame @@ -33,7 +32,7 @@ func boundsRelation(a, b *ir.Constraints) relation { case bHolds: return secondTypeIsNarrower default: - return relMeet + return relIntersect } } @@ -47,118 +46,209 @@ func sameBounds(a, b *ir.Constraints) bool { if b == nil { b = &none } - return a.UniqueItems == b.UniqueItems && - !slices.ContainsFunc(constraintKeywords, func(kw constraintKeyword) bool { return !kw.same(a, b) }) + if a.UniqueItems != b.UniqueItems { + return false + } + for keyword := range ir.ConstraintKeywords() { + if !ir.SameKeywordValue(a, b, keyword) { + return false + } + } + return true } // boundsBeyond returns what constraints says that own does not: constraints // without each keyword own states at the value constraints holds. It writes to // neither. func boundsBeyond(constraints, own *ir.Constraints) *ir.Constraints { - beyond := *constraints - for _, kw := range constraintKeywords { - if kw.same(constraints, own) { - kw.clear(&beyond) + var said []ir.ConstraintKeyword + for keyword := range ir.ConstraintKeywords() { + if ir.SameKeywordValue(constraints, own, keyword) { + said = append(said, keyword) } } + beyond := constraints.WithoutKeywords(said...) beyond.UniqueItems = constraints.UniqueItems && !own.UniqueItems - return &beyond + return beyond } -// boundsOf returns the constraints td's own node holds. A node of any other kind -// than the four the judgment can meet holds none it reads. -func boundsOf(td ir.TypeDef) *ir.Constraints { - switch n := td.(type) { +// boundsOf returns the constraints typeDef's own node holds. A node of any +// other kind than the five the judgment can intersect holds none it reads. +func boundsOf(typeDef ir.TypeDef) *ir.Constraints { + switch node := typeDef.(type) { + case *ir.Union: + return node.Constraints case *ir.Scalar: - return n.Constraints + return node.Constraints case *ir.List: - return n.Constraints + return node.Constraints case *ir.MapT: - return n.Constraints + return node.Constraints case *ir.Tuple: - return n.Constraints + return node.Constraints default: return nil } } -// withBounds returns a copy of td holding constraints, and td itself where -// boundsOf reads none of its kind. The copy shares the rest of td, which is -// read and never written: an editor clones a node before changing it. -func withBounds(td ir.TypeDef, constraints *ir.Constraints) ir.TypeDef { - switch n := td.(type) { +// withBounds returns a copy of typeDef holding constraints, and typeDef itself +// where boundsOf reads none of its kind. The copy shares the rest of typeDef, +// which is read and never written: an editor clones a node before changing it. +func withBounds(typeDef ir.TypeDef, constraints *ir.Constraints) ir.TypeDef { + switch node := typeDef.(type) { + case *ir.Union: + own := *node + own.Constraints = constraints + return &own case *ir.Scalar: - own := *n + own := *node own.Constraints = constraints return &own case *ir.List: - own := *n + own := *node own.Constraints = constraints return &own case *ir.MapT: - own := *n + own := *node own.Constraints = constraints return &own case *ir.Tuple: - own := *n + own := *node own.Constraints = constraints return &own default: - return td + return typeDef } } -// meetConstraints returns what sets say together, each keyword taking the value -// saying what they all do (Constraints), whatever their order; a nil set says -// nothing. A keyword no one value states keeps the last set's value, where a -// spec writes the specialization, and disagree hears of each earlier set -// pinning it otherwise: that set's index, the index the value was kept from, -// and the difference. No set is written to. -func meetConstraints(sets []*ir.Constraints, disagree func(i, kept int, detail string)) *ir.Constraints { - setBy := make([]int, len(constraintKeywords)) - var kept *ir.Constraints +// intersectConstraints returns what sets say together (Constraints), whatever +// their order, a value two sets spell differently spelled as the first written +// (before) of those giving it. A keyword no one value states keeps the last +// set's value, and disagree hears, once the sets are intersected, of each +// earlier set pinning it otherwise. None is written. +func intersectConstraints(sets []*ir.Constraints, before func(i, j declarationIndex) bool, + disagree func(i, chosenIndex declarationIndex, reportedField, disagreesOver string, agrees func(declarationIndex) bool), +) *ir.Constraints { + var setBy [ir.ConstraintKeywordPatternMessage + 1]declarationIndex + var intersected *ir.Constraints + var conflicts []constraintConflict for i, constraints := range slices.Backward(sets) { if constraints == nil { continue } - if k, detail, conflict := constraintsConflict(kept, constraints); conflict { - disagree(i, setBy[k], detail) + if keyword, detail, conflict := constraintsConflict(intersected, constraints); conflict { + conflicts = append(conflicts, constraintConflict{passedOver: declarationIndex(i), keyword: keyword, detail: detail}) } - for k, kw := range constraintKeywords { - if kw.set(constraints) && (kept == nil || !kw.set(kept)) { - setBy[k] = i + for keyword := range ir.ConstraintKeywords() { + if constraints.SetsKeyword(keyword) && !intersected.SetsKeyword(keyword) { + setBy[keyword] = declarationIndex(i) } } - if kept == nil { + if intersected == nil { own := *constraints - kept = &own + intersected = &own continue } - kept = Constraints(kept, constraints) + intersected = Constraints(intersected, constraints) + } + intersected = spellAsWrittenFirst(intersected, sets, before) + for _, conflict := range conflicts { + by, agrees := intersectionValueGivers(sets, conflict.keyword, intersected, conflict.passedOver, setBy[conflict.keyword]) + name := keywordName(conflict.keyword) + disagree(conflict.passedOver, by, name, differenceFromIntersection(conflict.keyword, intersected, sets[conflict.passedOver], conflict.detail), agrees) + } + return intersected +} + +// differenceFromIntersection is how passedOver differs from intersected, what +// every set says together, over keyword, so no order of the sets changes it, +// or else earlier, how it differs from the sets intersected before it, where +// intersected holds passedOver's value: the intersection is associative, so +// that happens only for a keyword it does not fold. +func differenceFromIntersection(keyword ir.ConstraintKeyword, intersected, passedOver *ir.Constraints, earlier string) string { + detail := "" + if slices.Contains(disagreeingKeywords(intersected, passedOver), keyword) { + detail = keywordDifference(keyword, intersected, passedOver) + } + return cmp.Or(detail, earlier) +} + +// constraintConflict is a set intersectConstraints intersected pinning a keyword otherwise +// than the sets intersected before it: the set's index, the keyword, and the +// difference. +type constraintConflict struct { + detail string + passedOver declarationIndex + keyword ir.ConstraintKeyword +} + +// spellAsWrittenFirst returns intersected with each keyword it states spelled +// as the first written (before) of sets giving its value, so no order of the +// sets picks among spellings of one number. A value no set gives, as a common +// step, keeps the spelling the intersection wrote. Neither intersected nor a +// set is written. +func spellAsWrittenFirst(intersected *ir.Constraints, sets []*ir.Constraints, before func(i, j declarationIndex) bool) *ir.Constraints { + if intersected == nil { + return nil + } + for keyword := range ir.ConstraintKeywords() { + first, found := declarationIndex(0), false + for j, constraints := range sets { + if constraints.SetsKeyword(keyword) && ir.SameKeywordValue(constraints, intersected, keyword) && (!found || before(declarationIndex(j), first)) { + first, found = declarationIndex(j), true + } + } + if found { + intersected = Constraints(intersected.WithoutKeywords(keyword), onlyKeyword(sets[first], keyword)) + } } - return kept + return intersected +} + +// onlyKeyword is constraints less every keyword but keyword, and less +// uniqueItems: a new value, nil for a nil set. +func onlyKeyword(constraints *ir.Constraints, keyword ir.ConstraintKeyword) *ir.Constraints { + var others []ir.ConstraintKeyword + for other := range ir.ConstraintKeywords() { + if other != keyword { + others = append(others, other) + } + } + only := constraints.WithoutKeywords(others...) + if only != nil { + only.UniqueItems = false + } + return only +} + +// intersectionValueGivers is which of sets a conflict of sets[passedOver] +// names as giving keyword the value intersected holds, and one of them: those +// but sets[passedOver] giving that value, or, where none gives it alone, every +// set but sets[passedOver] stating keyword, as sets[setter] does. Each is read +// against what all say, so no order of the sets changes which it holds. +func intersectionValueGivers(sets []*ir.Constraints, keyword ir.ConstraintKeyword, intersected *ir.Constraints, passedOver, setter declarationIndex) (declarationIndex, func(declarationIndex) bool) { + states := func(j declarationIndex) bool { return j != passedOver && sets[j].SetsKeyword(keyword) } + gives := func(j declarationIndex) bool { return states(j) && ir.SameKeywordValue(sets[j], intersected, keyword) } + for j := range declarationIndex(len(sets)) { + if gives(j) { + return j, gives + } + } + return setter, states } // nodeBounds returns the constraints on the node ref names. -func nodeBounds(typeJudgeValue typeJudge, ref ir.TypeRef) *ir.Constraints { - td, ok := typeJudgeValue.resolve(ref.Target) +func nodeBounds(typeJudge typeJudge, ref ir.TypeRef) *ir.Constraints { + typeDef, ok := typeJudge.resolve(ref.Target) if !ok { return nil } - return boundsOf(td) + return boundsOf(typeDef) } // allBounds returns the bounds property holds and those on its type's node // together. -func allBounds(typeJudgeValue typeJudge, property *ir.Property) *ir.Constraints { +func allBounds(typeJudge typeJudge, property *ir.Property) *ir.Constraints { var all ir.Constraints - return Constraints(Constraints(&all, property.Constraints), nodeBounds(typeJudgeValue, property.Type)) -} - -// sameTypeIgnoringBounds reports whether a and b are one type but for the -// bounds their nodes hold: the judgment on the two with those bounds set aside. -func sameTypeIgnoringBounds(typeJudgeValue typeJudge, a, b ir.TypeRef) bool { - at, aok := typeJudgeValue.resolve(a.Target) - bt, bok := typeJudgeValue.resolve(b.Target) - return aok && bok && typeJudgeValue.boundedNodes(withBounds(at, nil), withBounds(bt, nil), 0) == relSame + return Constraints(Constraints(&all, property.Constraints), nodeBounds(typeJudge, property.Type)) } diff --git a/compilers/openapi/internal/merge/bounds_internal_test.go b/compilers/openapi/internal/merge/bounds_internal_test.go index 4869db9f7..da8b3320b 100644 --- a/compilers/openapi/internal/merge/bounds_internal_test.go +++ b/compilers/openapi/internal/merge/bounds_internal_test.go @@ -7,6 +7,7 @@ import ( "encoding/json/jsontext" "fmt" "slices" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -51,7 +52,7 @@ func propertyBounds(t *testing.T, sets ...*ir.Constraints) []declaration { func TestFold_ABoundTakesItsTightestValueInEveryOrder(t *testing.T) { t.Parallel() big := func(v string) *ir.BigVal { return new(ir.BigVal(v)) } - count := func(n int64) *int64 { return new(n) } + count := func(count int64) *int64 { return new(count) } for _, tc := range []struct { name string sets [3]*ir.Constraints @@ -82,14 +83,14 @@ func TestFold_ABoundTakesItsTightestValueInEveryOrder(t *testing.T) { assert.Equal(t, tc.want, got.Constraints) assert.Empty(t, *recorded, "a bound the field implies is no disagreement") - assert.Empty(t, got.Unmodeled, "and nothing of it is lost") + assert.Empty(t, got.Unmodeled, "and nothing of it is passed over") }) }) } } // TestFold_ABoundLeavesTheDeclarationsItFoldsAlone pins that a fold reads the -// constraints it meets: a declaration's are shared with whatever else holds it, +// constraints it intersects: a declaration's are shared with whatever else holds it, // so one tightened in place would change a field the fold never saw. func TestFold_ABoundLeavesTheDeclarationsItFoldsAlone(t *testing.T) { t.Parallel() @@ -104,14 +105,14 @@ func TestFold_ABoundLeavesTheDeclarationsItFoldsAlone(t *testing.T) { assert.Equal(t, &ir.Constraints{MaxLength: new(int64(9))}, loose) } -// TestBoundsRelation_JudgesWhichSaysAllTheOtherDoes pins the verdict on two nodes -// alike but for their bounds, a verdict the fold rests on: narrower is adopted +// TestBoundsRelation_JudgesWhichSaysAllTheOtherDoes pins the answer on two nodes +// alike but for their bounds, a answer the fold rests on: narrower is adopted // silently, so a pair called narrower that is not would lose a bound with no // report. Each row reads in both directions. func TestBoundsRelation_JudgesWhichSaysAllTheOtherDoes(t *testing.T) { t.Parallel() big := func(v string) *ir.BigVal { return new(ir.BigVal(v)) } - count := func(n int64) *int64 { return new(n) } + count := func(count int64) *int64 { return new(count) } for _, tc := range []struct { name string a, b *ir.Constraints @@ -124,17 +125,17 @@ func TestBoundsRelation_JudgesWhichSaysAllTheOtherDoes(t *testing.T) { {"a tighter lower bound", &ir.Constraints{MinItems: count(5)}, &ir.Constraints{MinItems: count(1)}, firstTypeIsNarrower}, {"one number spelled two ways", &ir.Constraints{Min: big("10")}, &ir.Constraints{Min: big("1e1")}, relSame}, {"a step that is a multiple of the other", &ir.Constraints{MultipleOf: big("6")}, &ir.Constraints{MultipleOf: big("2")}, firstTypeIsNarrower}, - {"two steps neither divides", &ir.Constraints{MultipleOf: big("4")}, &ir.Constraints{MultipleOf: big("6")}, relMeet}, + {"two steps neither divides", &ir.Constraints{MultipleOf: big("4")}, &ir.Constraints{MultipleOf: big("6")}, relIntersect}, {"uniqueItems against none", &ir.Constraints{UniqueItems: true}, nil, firstTypeIsNarrower}, - {"each adds a bound", &ir.Constraints{MinItems: count(1)}, &ir.Constraints{MaxItems: count(5)}, relMeet}, - {"one tighter on each keyword", &ir.Constraints{MinItems: count(2), MaxItems: count(9)}, &ir.Constraints{MinItems: count(1), MaxItems: count(5)}, relMeet}, - {"a bound beside an exclusive one", &ir.Constraints{Min: big("5")}, &ir.Constraints{ExclusiveMin: big("5")}, relMeet}, + {"each adds a bound", &ir.Constraints{MinItems: count(1)}, &ir.Constraints{MaxItems: count(5)}, relIntersect}, + {"one tighter on each keyword", &ir.Constraints{MinItems: count(2), MaxItems: count(9)}, &ir.Constraints{MinItems: count(1), MaxItems: count(5)}, relIntersect}, + {"a bound beside an exclusive one", &ir.Constraints{Min: big("5")}, &ir.Constraints{ExclusiveMin: big("5")}, relIntersect}, {"one more keyword and the same bound", &ir.Constraints{Pattern: "^a$", MaxItems: count(5)}, &ir.Constraints{MaxItems: count(5)}, firstTypeIsNarrower}, {"one pattern against none", &ir.Constraints{Pattern: "^a$"}, nil, firstTypeIsNarrower}, - {"two patterns", &ir.Constraints{Pattern: "^a$"}, &ir.Constraints{Pattern: "^b$"}, relMeet}, - {"two precisions", &ir.Constraints{Precision: count(4)}, &ir.Constraints{Precision: count(5)}, relMeet}, - {"a tighter bound against another pattern", &ir.Constraints{Pattern: "^a$", MaxLength: count(1)}, &ir.Constraints{Pattern: "^b$", MaxLength: count(9)}, relMeet}, - {"two literals with no order", &ir.Constraints{Min: big("nan")}, &ir.Constraints{Min: big("other")}, relMeet}, + {"two patterns", &ir.Constraints{Pattern: "^a$"}, &ir.Constraints{Pattern: "^b$"}, relIntersect}, + {"two precisions", &ir.Constraints{Precision: count(4)}, &ir.Constraints{Precision: count(5)}, relIntersect}, + {"a tighter bound against another pattern", &ir.Constraints{Pattern: "^a$", MaxLength: count(1)}, &ir.Constraints{Pattern: "^b$", MaxLength: count(9)}, relIntersect}, + {"two literals with no order", &ir.Constraints{Min: big("nan")}, &ir.Constraints{Min: big("other")}, relIntersect}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() @@ -160,7 +161,7 @@ func TestSameBounds_NothingSaysNothingOnEitherSide(t *testing.T) { } // TestBoundsBeyond_KeepsWhatTheOtherDoesNotStateAtThatValue pins what counts as a -// bound another declaration brought: not one a declaration states itself at the +// bound another declaration carried: not one a declaration states itself at the // value the field keeps, whichever keyword it is, and a looser value it states // does not excuse it. func TestBoundsBeyond_KeepsWhatTheOtherDoesNotStateAtThatValue(t *testing.T) { @@ -180,24 +181,24 @@ func TestBoundsBeyond_KeepsWhatTheOtherDoesNotStateAtThatValue(t *testing.T) { // carry over. func boundedNodeKinds() map[string]func(n int, constraints *ir.Constraints) ir.TypeDef { i32 := primitiveRef(ir.PrimitiveInt32) - site := func(n int) ir.TypeCommon { + site := func(count int) ir.TypeCommon { return ir.TypeCommon{ - ID: ir.TypeID(fmt.Sprintf("type/node/%d", n)), Anonymous: true, Provenance: ptrAt(declaredAt(n)), + ID: ir.TypeID(fmt.Sprintf("type/node/%d", count)), Anonymous: true, Provenance: ptrAt(declaredAt(count)), Docs: ir.Docs{Description: "detail"}, } } return map[string]func(n int, constraints *ir.Constraints) ir.TypeDef{ - "a scalar": func(n int, constraints *ir.Constraints) ir.TypeDef { - return &ir.Scalar{TypeCommon: site(n), Base: &i32, Encoding: &ir.Encoding{Name: "x"}, Constraints: constraints} + "a scalar": func(count int, constraints *ir.Constraints) ir.TypeDef { + return &ir.Scalar{TypeCommon: site(count), Base: &i32, Encoding: &ir.Encoding{Name: "x"}, Constraints: constraints} }, - "a list": func(n int, constraints *ir.Constraints) ir.TypeDef { - return &ir.List{TypeCommon: site(n), ElementType: i32, Constraints: constraints} + "a list": func(count int, constraints *ir.Constraints) ir.TypeDef { + return &ir.List{TypeCommon: site(count), ElementType: i32, Constraints: constraints} }, - "a map": func(n int, constraints *ir.Constraints) ir.TypeDef { - return &ir.MapT{TypeCommon: site(n), Value: i32, Constraints: constraints} + "a map": func(count int, constraints *ir.Constraints) ir.TypeDef { + return &ir.MapT{TypeCommon: site(count), Value: i32, Constraints: constraints} }, - "a tuple": func(n int, constraints *ir.Constraints) ir.TypeDef { - return &ir.Tuple{TypeCommon: site(n), ElementTypes: []ir.TypeRef{i32}, Constraints: constraints} + "a tuple": func(count int, constraints *ir.Constraints) ir.TypeDef { + return &ir.Tuple{TypeCommon: site(count), ElementTypes: []ir.TypeRef{i32}, Constraints: constraints} }, } } @@ -208,20 +209,21 @@ func nodeDecls(t *testing.T, reg map[ir.TypeID]ir.TypeDef, node func(int, *ir.Co t.Helper() decls := make([]declaration, len(sets)) for i, constraints := range sets { - td := node(i, constraints) - reg[td.Common().ID] = td - decls[i] = nthDecl(i, td.Common().ID) + typeDef := node(i, constraints) + reg[typeDef.Common().ID] = typeDef + decls[i] = nthDecl(i, typeDef.Common().ID) decls[i].source = unread(t) } return decls } -// TestFold_NodesThatMeetStandOnAMintedNode pins what a field takes where each of -// two nodes adds a bound the other lacks: no declared node holds both, so the -// merge mints one. It holds both bounds in either order, keeps the detail the two -// share, names the field, and leaves the declared nodes as they were written. -// Neither declaration lost anything, so nothing is reported or kept. -func TestFold_NodesThatMeetStandOnAMintedNode(t *testing.T) { +// TestFold_NodesThatIntersectSitOnAMintedNode pins what a field takes where each +// of two nodes adds a bound the other lacks: no declared node holds both, so +// the merge mints one. It holds both bounds in either order, keeps the detail +// the two share, names the field, and leaves the declared nodes as they were +// written. Neither declaration passed over anything, so nothing is reported or +// kept. +func TestFold_NodesThatIntersectSitOnAMintedNode(t *testing.T) { t.Parallel() lower, upper := &ir.Constraints{MinItems: new(int64(1))}, &ir.Constraints{MaxItems: new(int64(5))} want := &ir.Constraints{MinItems: new(int64(1)), MaxItems: new(int64(5))} @@ -232,11 +234,10 @@ func TestFold_NodesThatMeetStandOnAMintedNode(t *testing.T) { inOrders(t, nodeDecls(t, reg, node, lower, upper), func(t *testing.T, ordered []declaration) { t.Helper() stubbed, recorded := stubMerger(reg) - _, field := fieldSpan(ordered) got := stubbed.fold(ordered) - require.Equal(t, composedAt(field), got.Type.Target, "the node takes the composed namespace") + require.Equal(t, composedAt(foldKey), got.Type.Target, "the node takes the composed key no order moves") minted := reg[got.Type.Target] assert.Equal(t, node(0, nil).Kind(), minted.Kind()) assert.Equal(t, want, boundsOf(minted)) @@ -250,11 +251,12 @@ func TestFold_NodesThatMeetStandOnAMintedNode(t *testing.T) { } } -// TestFold_TheBoundsOfEveryDeclarationMeetInEveryOrder pins the set fold over -// nodes. A winner picked by how many declarations it holds can be any of those -// that meet, so what the minted node holds must not follow which: a chain folding -// pairs would keep the third declaration's bound or lose it by its position. -func TestFold_TheBoundsOfEveryDeclarationMeetInEveryOrder(t *testing.T) { +// TestFold_TheBoundsOfEveryDeclarationIntersectInEveryOrder pins the set fold over +// nodes. A chosen declaration picked by how many declarations it holds can be +// any of those that intersect, so what the minted node holds must not follow +// which: a chain folding pairs would keep the third declaration's bound or lose +// it by its position. +func TestFold_TheBoundsOfEveryDeclarationIntersectInEveryOrder(t *testing.T) { t.Parallel() one, two, five := new(int64(1)), new(int64(2)), new(int64(5)) for _, tc := range []struct { @@ -263,7 +265,7 @@ func TestFold_TheBoundsOfEveryDeclarationMeetInEveryOrder(t *testing.T) { want *ir.Constraints }{ {"one bound tightening another", []*ir.Constraints{{MinItems: one}, {MaxItems: five}, {MinItems: two}}, &ir.Constraints{MinItems: two, MaxItems: five}}, - {"a bare node beside two that meet", []*ir.Constraints{nil, {MinItems: one}, {MaxItems: five}}, &ir.Constraints{MinItems: one, MaxItems: five}}, + {"a bare node beside two that intersect", []*ir.Constraints{nil, {MinItems: one}, {MaxItems: five}}, &ir.Constraints{MinItems: one, MaxItems: five}}, {"three that each add one", []*ir.Constraints{{MinItems: one}, {MaxItems: five}, {UniqueItems: true}}, &ir.Constraints{MinItems: one, MaxItems: five, UniqueItems: true}}, } { t.Run(tc.name, func(t *testing.T) { @@ -283,16 +285,16 @@ func TestFold_TheBoundsOfEveryDeclarationMeetInEveryOrder(t *testing.T) { } } -// TestFold_ADroppedDeclarationsBoundsStayOffAMintedNode pins whose bounds a mint -// reads: only the declarations meeting the winner. A list of strings beside lists -// of int32 loses its type, and its bound went with it, since it describes the -// shape that lost. +// TestFold_ADroppedDeclarationsBoundsStayOffAMintedNode pins whose bounds a +// mint reads: only the declarations intersecting the chosen declaration. A list +// of strings beside lists of int32 loses its type, and its bound went with it, +// since it describes the shape passed over. func TestFold_ADroppedDeclarationsBoundsStayOffAMintedNode(t *testing.T) { t.Parallel() reg := narrowingRegistry() i32 := primitiveRef(ir.PrimitiveInt32) - decls := nodeDecls(t, reg, func(n int, constraints *ir.Constraints) ir.TypeDef { - return &ir.List{ID: ir.TypeID(fmt.Sprintf("type/lists/%d", n)), Anonymous: true, Provenance: ptrAt(declaredAt(n)), ElementType: i32, Constraints: constraints} + decls := nodeDecls(t, reg, func(count int, constraints *ir.Constraints) ir.TypeDef { + return &ir.List{ID: ir.TypeID(fmt.Sprintf("type/lists/%d", count)), Anonymous: true, Provenance: ptrAt(declaredAt(count)), ElementType: i32, Constraints: constraints} }, &ir.Constraints{MinItems: new(int64(1))}, &ir.Constraints{MaxItems: new(int64(5))}) reg["type/strings"] = &ir.List{ID: "type/strings", Anonymous: true, Provenance: ptrAt(declaredAt(2)), ElementType: primitiveRef(ir.PrimitiveString), Constraints: &ir.Constraints{MaxItems: new(int64(2))}} @@ -304,7 +306,7 @@ func TestFold_ADroppedDeclarationsBoundsStayOffAMintedNode(t *testing.T) { got := stubbed.fold(ordered) assert.Equal(t, &ir.Constraints{MinItems: new(int64(1)), MaxItems: new(int64(5))}, boundsOf(reg[got.Type.Target])) - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(2))) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(2))) require.Len(t, *recorded, 1, "only the dropped declaration is reported") assert.Equal(t, declaredAt(2), (*recorded)[0].Provenance.Pointer) }) @@ -344,11 +346,12 @@ func TestFold_ANodeHoldingEveryBoundIsNotMinted(t *testing.T) { } } -// TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheWinner pins two nodes -// that cannot meet on one keyword. The later's pattern stands and the other's -// declaration is reported and kept, as on a property, and one warning stands for -// a keyword a Scalar's position writes on both its node and its property. -func TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheWinner(t *testing.T) { +// TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheChosenDeclaration pins two nodes +// that cannot intersect on one keyword. The later's pattern is chosen and the +// other's declaration is reported and kept, as on a property, and one warning +// represents a keyword a Scalar's position writes on both its node and its +// property. +func TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheChosenDeclaration(t *testing.T) { t.Parallel() node := boundedNodeKinds()["a scalar"] mirrored := func(t *testing.T, reg map[ir.TypeID]ir.TypeDef, sets ...*ir.Constraints) []declaration { @@ -370,11 +373,11 @@ func TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheWinner(t *testing.T got := stubbed.fold(decls) - assert.Equal(t, decls[1].property.Type.Target, got.Type.Target, "the later stands") + assert.Equal(t, decls[1].property.Type.Target, got.Type.Target, "the later is chosen") assert.Len(t, reg, nodes, "and nothing is minted for it") require.Len(t, *recorded, 1, "the keyword is reported once") assert.Equal(t, diag.ConflictingRedecl, (*recorded)[0].Code) - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(0))) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(0))) }) t.Run("one more declaration sets it on the property alone", func(t *testing.T) { @@ -387,11 +390,11 @@ func TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheWinner(t *testing.T stubbed.fold([]declaration{nodes[0], nodes[1], bare}) - require.Len(t, *recorded, 1, "the node and the property each meet the one disagreement, whoever each kept it from") + require.Len(t, *recorded, 1, "the node and the property each draw the one disagreement, whoever each took it from") assert.Equal(t, declaredAt(0), (*recorded)[0].Provenance.Pointer) }) - t.Run("a bound meets beside it", func(t *testing.T) { + t.Run("a bound intersects beside it", func(t *testing.T) { t.Parallel() reg := narrowingRegistry() decls := mirrored(t, reg, @@ -404,20 +407,21 @@ func TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheWinner(t *testing.T assert.Equal(t, &ir.Constraints{Pattern: "^b$", MaxLength: new(int64(3))}, boundsOf(reg[got.Type.Target])) assert.Equal(t, &ir.Constraints{Pattern: "^b$", MaxLength: new(int64(3))}, got.Constraints) require.Len(t, *recorded, 1, "the keyword is reported once") - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(0))) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(0))) }) } -// TestFold_AValueIsHeldToTheBoundsOthersBring pins which bounds judge a value a -// declaration wrote. One another declaration brought does, and a value it refuses -// stays off the field, reported and kept at the declaration, in both orders. One -// the declaration states itself at the value the field keeps does not: that -// disagreement is the declaration's own and stays where it stood. A type's kind -// is never asked here, since both declarations have the field's type. -func TestFold_AValueIsHeldToTheBoundsOthersBring(t *testing.T) { +// TestFold_AValueIsHeldToEveryBoundAtItsPosition pins which bounds judge a +// value a declaration wrote: every one at its position, whether another +// declaration carried it or the declaration states it itself, and a value one +// refuses stays off the field, reported and kept at the declaration, in both +// orders. Both declarations have the field's type, and a value is refused only +// on a definite no: a pattern in the subset ir reads refuses a value it misses +// wherever it is written, and one outside it refuses none. +func TestFold_AValueIsHeldToEveryBoundAtItsPosition(t *testing.T) { t.Parallel() big := func(v string) *ir.BigVal { return new(ir.BigVal(v)) } - count := func(n int64) *int64 { return new(n) } + count := func(count int64) *int64 { return new(count) } hello := stringValue("hello") for _, tc := range []struct { name string @@ -430,11 +434,16 @@ func TestFold_AValueIsHeldToTheBoundsOthersBring(t *testing.T) { {name: "a string within another's maxLength", kind: ir.PrimitiveString, another: &ir.Constraints{MaxLength: count(5)}, value: hello, taken: true}, {name: "a string below another's minLength", kind: ir.PrimitiveString, another: &ir.Constraints{MinLength: count(6)}, value: hello}, {name: "a string past a bound tighter than its own", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(9)}, another: &ir.Constraints{MaxLength: count(3)}, value: hello}, - {name: "a string past its own bound alone", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(3)}, value: hello, taken: true}, - {name: "a string past its own bound, which another restates", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(3)}, another: &ir.Constraints{MaxLength: count(3)}, value: hello, taken: true}, - {name: "a string past its own bound, another's being looser", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(3)}, another: &ir.Constraints{MaxLength: count(9)}, value: hello, taken: true}, - {name: "a string under another's pattern, which nothing evaluates", kind: ir.PrimitiveString, another: &ir.Constraints{Pattern: "^h"}, value: hello}, - {name: "a string under its own pattern", kind: ir.PrimitiveString, own: &ir.Constraints{Pattern: "^x"}, value: hello, taken: true}, + {name: "a string past its own bound alone", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(3)}, value: hello}, + {name: "a string past its own bound, which another restates", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(3)}, another: &ir.Constraints{MaxLength: count(3)}, value: hello}, + {name: "a string past its own bound, another's being looser", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(3)}, another: &ir.Constraints{MaxLength: count(9)}, value: hello}, + {name: "a string within its own bound", kind: ir.PrimitiveString, own: &ir.Constraints{MaxLength: count(5)}, value: hello, taken: true}, + {name: "a number past its own maximum", kind: ir.PrimitiveNumber, own: &ir.Constraints{Max: big("5")}, value: number("9")}, + {name: "a string under another's pattern it matches", kind: ir.PrimitiveString, another: &ir.Constraints{Pattern: "^h"}, value: hello, taken: true}, + {name: "a string under another's pattern it misses", kind: ir.PrimitiveString, another: &ir.Constraints{Pattern: "^x"}, value: hello}, + {name: "a string under another's pattern ir does not read", kind: ir.PrimitiveString, another: &ir.Constraints{Pattern: "^(?=h)"}, value: hello, taken: true}, + {name: "a string under its own pattern it misses", kind: ir.PrimitiveString, own: &ir.Constraints{Pattern: "^x"}, value: hello}, + {name: "a string under its own pattern ir does not read", kind: ir.PrimitiveString, own: &ir.Constraints{Pattern: "^(?=x)"}, value: hello, taken: true}, {name: "a number below another's minimum", kind: ir.PrimitiveNumber, another: &ir.Constraints{Min: big("5")}, value: number("1")}, {name: "a number within another's minimum", kind: ir.PrimitiveNumber, another: &ir.Constraints{Min: big("5")}, value: number("9"), taken: true}, {name: "a number at another's exclusive bound", kind: ir.PrimitiveNumber, another: &ir.Constraints{ExclusiveMax: big("5")}, value: number("5")}, @@ -442,15 +451,15 @@ func TestFold_AValueIsHeldToTheBoundsOthersBring(t *testing.T) { {name: "a number on the step the two make", kind: ir.PrimitiveNumber, own: &ir.Constraints{MultipleOf: big("4")}, another: &ir.Constraints{MultipleOf: big("6")}, value: number("24"), taken: true}, {name: "a bound for another kind of value", kind: ir.PrimitiveNumber, another: &ir.Constraints{MaxLength: count(1)}, value: number("123"), taken: true}, {name: "a list repeating under another's uniqueItems", kind: ir.PrimitiveAny, another: &ir.Constraints{UniqueItems: true}, value: ir.Value{Kind: ir.ValueList, List: []ir.Value{hello, hello}}}, - {name: "a list repeating under its own uniqueItems", kind: ir.PrimitiveAny, own: &ir.Constraints{UniqueItems: true}, another: &ir.Constraints{UniqueItems: true}, value: ir.Value{Kind: ir.ValueList, List: []ir.Value{hello, hello}}, taken: true}, + {name: "a list repeating under its own uniqueItems", kind: ir.PrimitiveAny, own: &ir.Constraints{UniqueItems: true}, another: &ir.Constraints{UniqueItems: true}, value: ir.Value{Kind: ir.ValueList, List: []ir.Value{hello, hello}}}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() const source = `{"written":"value"}` - withValue, other := nthDecl(0, primitiveRef(tc.kind).Target), nthDecl(1, primitiveRef(tc.kind).Target) - withValue.property.Constraints, withValue.property.Default, withValue.source = tc.own, &tc.value, written(source) + with, other := nthDecl(0, primitiveRef(tc.kind).Target), nthDecl(1, primitiveRef(tc.kind).Target) + with.property.Constraints, with.property.Default, with.source = tc.own, &tc.value, written(source) other.property.Constraints = tc.another - for _, order := range [][]declaration{{withValue, other}, {other, withValue}} { + for _, order := range [][]declaration{{with, other}, {other, with}} { stubbed, recorded := stubMerger(narrowingRegistry()) got := stubbed.fold(order) @@ -464,8 +473,8 @@ func TestFold_AValueIsHeldToTheBoundsOthersBring(t *testing.T) { assert.Nil(t, got.Default, "the field does not take it") require.Len(t, *recorded, 1) assert.Equal(t, diag.DegradedConstruct, (*recorded)[0].Code) - assert.Equal(t, withValue.property.Provenance.Pointer, (*recorded)[0].Provenance.Pointer) - assert.Equal(t, ir.RawValue(source), got.Unmodeled[losingDeclarationKey+string(declaredAt(0))].Value) + assert.Equal(t, with.property.Provenance.Pointer, (*recorded)[0].Provenance.Pointer) + assert.Equal(t, ir.RawValue(source), got.Unmodeled[passedOverDeclarationKey+string(declaredAt(0))].Value) } }) } @@ -491,12 +500,18 @@ func TestFold_AnExampleIsHeldToTheBoundsOthersBringAsAWhole(t *testing.T) { // TestFold_ANodesBoundsJudgeAValueWrittenAgainstItsOwnKind pins what a declaration // of a node alike the field's answers for. Its type is the field's but for bounds, -// so an encoding, which admits no value, refuses nothing it wrote; a bound another -// declaration brought to the node does, whether the field took a declared node or -// a minted one. +// so an encoding the value admission reader cannot read refuses nothing it wrote; +// a bound another declaration carried to the node does, whether the field took a +// declared node or a minted one. func TestFold_ANodesBoundsJudgeAValueWrittenAgainstItsOwnKind(t *testing.T) { t.Parallel() - node := boundedNodeKinds()["a scalar"] + text := primitiveRef(ir.PrimitiveString) + node := func(count int, constraints *ir.Constraints) ir.TypeDef { + scalar, isScalar := boundedNodeKinds()["a scalar"](count, constraints).(*ir.Scalar) + require.True(t, isScalar) + scalar.Base = &text + return scalar + } short, long := stringValue("abc"), stringValue("abcdefgh") maxFive := &ir.Constraints{MaxLength: new(int64(5))} for _, tc := range []struct { @@ -572,16 +587,16 @@ func TestTypeJudge_ATupleOfTuplesCostsItsWidthNotItsWidthToTheDepth(t *testing.T reg[leaf] = &ir.Primitive{ID: leaf, PrimitiveKind: ir.PrimitiveString} } reads := 0 - typeJudgeValue := typeJudge{ + typeJudge := typeJudge{ resolve: func(id ir.TypeID) (ir.TypeDef, bool) { reads++ - td, ok := reg[id] - return td, ok + typeDef, ok := reg[id] + return typeDef, ok }, sites: declarationSites{written: [2][]ir.Provenance{sitesAt("/a"), sitesAt("/b")}, walk: &stubWalk{}}, } - rel := typeJudgeValue.relate(ref("type/a/0"), ref("type/b/0")) + rel := typeJudge.relate(ref("type/a/0"), ref("type/b/0")) assert.Equal(t, relUnrelated, rel, "a tuple holding tuples is compared by no position") assert.LessOrEqual(t, reads, 2*width*depth, "the reads grow with the document, not with its width to the depth") @@ -595,10 +610,10 @@ func TestTypeJudge_ATuplesPositionsCompareOnlyAtAFieldsOwnDepth(t *testing.T) { reg := judgeRegistry() reg["type/held-min"] = &ir.List{ID: "type/held-min", ElementType: ref("type/tuple-min")} reg["type/held-bare"] = &ir.List{ID: "type/held-bare", ElementType: ref("type/tuple")} - typeJudgeValue := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{})} + typeJudge := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{})} - assert.Equal(t, firstTypeIsNarrower, typeJudgeValue.relate(ref("type/tuple-min"), ref("type/tuple")), "as a field's own type") - assert.Equal(t, relUnrelated, typeJudgeValue.relate(ref("type/held-min"), ref("type/held-bare")), "as what a list holds") + assert.Equal(t, firstTypeIsNarrower, typeJudge.relate(ref("type/tuple-min"), ref("type/tuple")), "as a field's own type") + assert.Equal(t, relUnrelated, typeJudge.relate(ref("type/held-min"), ref("type/held-bare")), "as what a list holds") } // TestFold_AValueOnAListInAnotherDocumentIsJudgedAsItsOwn pins whose copies a @@ -608,9 +623,9 @@ func TestTypeJudge_ATuplesPositionsCompareOnlyAtAFieldsOwnDepth(t *testing.T) { func TestFold_AValueOnAListInAnotherDocumentIsJudgedAsItsOwn(t *testing.T) { t.Parallel() const elsewhere = 1 - at := func(n int) ir.Provenance { return ir.Provenance{Source: elsewhere, Pointer: declaredAt(n)} } - element := func(id string, n int) *ir.Scalar { - provenance := at(n) + at := func(count int) ir.Provenance { return ir.Provenance{Source: elsewhere, Pointer: declaredAt(count)} } + element := func(id string, count int) *ir.Scalar { + provenance := at(count) provenance.Pointer += "/items" return &ir.Scalar{ID: ir.TypeID(id), Anonymous: true, Provenance: provenance, Base: new(primitiveRef(ir.PrimitiveString)), Encoding: &ir.Encoding{Name: "x"}} } @@ -631,8 +646,9 @@ func TestFold_AValueOnAListInAnotherDocumentIsJudgedAsItsOwn(t *testing.T) { } // TestFold_ATypeTheRegistryDoesNotHoldHoldsNoBounds pins the guard behind a -// dangling reference: it says nothing of its bounds, and a value written against -// it is its declaration's own, as on any type the fold keeps. +// dangling reference: it says nothing of its bounds, and the value admission +// reader cannot judge a value written against it, so the field adopts the value, +// as it does one the reader cannot judge on any type the fold keeps. func TestFold_ATypeTheRegistryDoesNotHoldHoldsNoBounds(t *testing.T) { t.Parallel() value := stringValue("hello") @@ -657,3 +673,133 @@ func TestWithBounds_ReadsOnlyTheKindsThatHoldThem(t *testing.T) { assert.Nil(t, boundsOf(model)) assert.Same(t, model, withBounds(model, &ir.Constraints{})) } + +// TestIntersectConstraints_NamesWhatGivesTheValueIntersected pins which sets a conflict +// names as giving the value it parts from: those giving the step every set +// intersects in, though a set intersected after the conflict moved it, a step +// that one is a multiple of giving another, or, where none gives it alone, as 6 +// follows from 2 and 3, every set but the passed-over one stating multipleOf, +// in any order. +func TestIntersectConstraints_NamesWhatGivesTheValueIntersected(t *testing.T) { + t.Parallel() + // fine's steps intersect a common step another fine one has none with, and + // longest, whose numerator passes the 1,024 digits a step intersect reads, + // intersects none. + fine, longest := "1."+strings.Repeat("0", 598), "1"+strings.Repeat("0", 1024)+"1" + step := func(value string) *ir.Constraints { + multipleOf := ir.BigVal(value) + return &ir.Constraints{MultipleOf: &multipleOf} + } + type heard struct { + passedOver, chosen int + agreeing []int + } + for name, tc := range map[string]struct { + sets []*ir.Constraints + want []heard + }{ + "the set giving the step intersected": {sets: []*ir.Constraints{step("1e-599"), step(fine + "3"), step(fine + "1")}, + want: []heard{{passedOver: 1, chosen: 2, agreeing: []int{2}}}}, + "the same, reversed": {sets: []*ir.Constraints{step(fine + "1"), step(fine + "3"), step("1e-599")}, + want: []heard{{passedOver: 0, chosen: 1, agreeing: []int{1}}}}, + "none giving it alone": {sets: []*ir.Constraints{step(longest), nil, step("2"), step("3")}, + want: []heard{{passedOver: 0, chosen: 3, agreeing: []int{2, 3}}}}, + "a step intersected after the conflict": {sets: []*ir.Constraints{step("5"), step(longest), step("2")}, + want: []heard{{passedOver: 1, chosen: 2, agreeing: []int{0, 2}}}}, + "the same, reversed, meeting the other first": {sets: []*ir.Constraints{step("2"), step(longest), step("5")}, + want: []heard{{passedOver: 1, chosen: 2, agreeing: []int{0, 2}}}}, + } { + var got []heard + intersectConstraints(tc.sets, func(i, j declarationIndex) bool { return i < j }, func(passedOver, chosen declarationIndex, _, _ string, agrees func(declarationIndex) bool) { + said := heard{passedOver: int(passedOver), chosen: int(chosen)} + for j := range declarationIndex(len(tc.sets)) { + if agrees(j) { + said.agreeing = append(said.agreeing, int(j)) + } + } + got = append(got, said) + }) + assert.Equal(t, tc.want, got, name) + } +} + +// TestIntersectConstraints_SpellsAValueAsTheFirstWrittenGivingIt pins the spelling +// a value two sets spell differently takes: the first written's, whatever +// their order, and for two steps of one number too long to intersect as steps, +// with no conflict. +func TestIntersectConstraints_SpellsAValueAsTheFirstWrittenGivingIt(t *testing.T) { + t.Parallel() + long := "1" + strings.Repeat("3", 512) + for name, tc := range map[string]struct { + sets []*ir.Constraints + read func(*ir.Constraints) *ir.BigVal + }{ + "a bound": {sets: []*ir.Constraints{{Min: new(ir.BigVal("1.50"))}, {Min: new(ir.BigVal("1.5"))}}, + read: func(constraints *ir.Constraints) *ir.BigVal { return constraints.Min }}, + "a long step": {sets: []*ir.Constraints{{MultipleOf: new(ir.BigVal(long + ".0"))}, {MultipleOf: new(ir.BigVal(long))}}, + read: func(constraints *ir.Constraints) *ir.BigVal { return constraints.MultipleOf }}, + } { + for _, writtenFirst := range []int{0, 1} { + before := func(i, j declarationIndex) bool { return int(i) == writtenFirst && int(j) != writtenFirst } + conflicts := 0 + + intersected := intersectConstraints(tc.sets, before, func(declarationIndex, declarationIndex, string, string, func(declarationIndex) bool) { conflicts++ }) + + require.NotNil(t, intersected, name) + assert.Equal(t, *tc.read(tc.sets[writtenFirst]), *tc.read(intersected), "%s, set %d written first", name, writtenFirst) + assert.Zero(t, conflicts, name) + } + } +} + +// TestIntersectionValueGivers_NeverNamesThePassedOverSet pins that a conflict names no set +// as giving the intersected value that is the one passed over for it, though +// that set gives the value too. +func TestIntersectionValueGivers_NeverNamesThePassedOverSet(t *testing.T) { + t.Parallel() + step := &ir.Constraints{MultipleOf: new(ir.BigVal("2"))} + sets := []*ir.Constraints{step, step} + by, agrees := intersectionValueGivers(sets, ir.ConstraintKeywordMultipleOf, step, 0, 1) + + assert.Equal(t, declarationIndex(1), by) + assert.False(t, agrees(0), "the passed-over set") + assert.True(t, agrees(1)) +} + +// TestIntersectConstraints_SaysTheDifferenceFromTheIntersection pins the difference a +// conflict says: from the step every set intersects in, whatever their order. A +// step intersected after the conflict only makes that step a multiple of the +// one intersected before, which the passed-over step intersects no more than +// that one, as 5 intersected with 1.25 stays 5. +func TestIntersectConstraints_SaysTheDifferenceFromTheIntersection(t *testing.T) { + t.Parallel() + step := func(value string) *ir.Constraints { + multipleOf := ir.BigVal(value) + return &ir.Constraints{MultipleOf: &multipleOf} + } + // longest's numerator passes the 1,024 digits a step intersect reads, so it + // intersects no other step, and conflicts with every value intersected + // after it too. + longest := "1" + strings.Repeat("0", 1024) + "7" + for name, tc := range map[string]struct { + sets []*ir.Constraints + want string + intersected ir.BigVal + }{ + "the step every set intersects in": {sets: []*ir.Constraints{step("5"), step(longest), step("2")}, + want: "conflicting multipleOf (10 and " + longest + ")", intersected: "10"}, + "the same, reversed": {sets: []*ir.Constraints{step("2"), step(longest), step("5")}, + want: "conflicting multipleOf (10 and " + longest + ")", intersected: "10"}, + "a step intersected after the conflict that no shortening lets it intersect": {sets: []*ir.Constraints{step("5"), step(longest), step("1.25")}, + want: "conflicting multipleOf (5 and " + longest + ")", intersected: "5"}, + } { + var said []string + intersected := intersectConstraints(tc.sets, func(i, j declarationIndex) bool { return i < j }, func(_, _ declarationIndex, _, detail string, _ func(declarationIndex) bool) { + said = append(said, detail) + }) + + assert.Equal(t, []string{tc.want}, said, name) + require.NotNil(t, intersected, name) + assert.Equal(t, tc.intersected, *intersected.MultipleOf, name) + } +} diff --git a/compilers/openapi/internal/merge/canonical.go b/compilers/openapi/internal/merge/canonical.go deleted file mode 100644 index 4f9c1ca9c..000000000 --- a/compilers/openapi/internal/merge/canonical.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "slices" - "strconv" - "strings" - - "github.com/dexpace/morphic/ir" -) - -// canonicalValue spells value so that two JSON-equal values spell alike: a -// number by its value (ir.Decimal.String), an object by its members in name -// order. ok is false for a kind JSON has no instance of, a number no Decimal -// holds, or nesting past maxJudgeDepth. -func canonicalValue(value ir.Value, depth int) (string, bool) { - if depth > maxJudgeDepth { - return "", false - } - switch value.Kind { - case ir.ValueNull: - return "null", true - case ir.ValueBool: - return strconv.FormatBool(value.Bool), true - case ir.ValueString: - return strconv.Quote(value.String), true - case ir.ValueNumber: - decimal, err := value.Number.Decimal() - if err != nil { - return "", false - } - return decimal.String(), true - case ir.ValueList: - return canonicalMembers("[", "]", len(value.List), func(i int) (string, bool) { - return canonicalValue(value.List[i], depth+1) - }) - case ir.ValueObject: - fields := slices.SortedFunc(slices.Values(value.Object), func(a, b ir.Field) int { return strings.Compare(a.Name, b.Name) }) - return canonicalMembers("{", "}", len(fields), func(i int) (string, bool) { - member, ok := canonicalValue(fields[i].Value, depth+1) - return strconv.Quote(fields[i].Name) + ":" + member, ok - }) - case ir.ValueBytes, ir.ValueSymbol, ir.ValueRefKind, ir.ValueConstructor, ir.ValueInfinity, ir.ValueNegativeInfinity, ir.ValueNaN: - return "", false - default: - return "", false - } -} - -// canonicalMembers joins the n spellings member gives between open and close, -// or fails with the first member that cannot be spelled. -func canonicalMembers(open, closing string, n int, member func(i int) (string, bool)) (string, bool) { - parts := make([]string, 0, n) - for i := range n { - part, ok := member(i) - if !ok { - return "", false - } - parts = append(parts, part) - } - return open + strings.Join(parts, ",") + closing, true -} diff --git a/compilers/openapi/internal/merge/canonical_internal_test.go b/compilers/openapi/internal/merge/canonical_internal_test.go deleted file mode 100644 index 25b190875..000000000 --- a/compilers/openapi/internal/merge/canonical_internal_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -// TestCanonicalValue_DeclinesANumberOutsideTheGrammar pins that a number with no -// canonical decimal has no spelling at all. Reading "1p4" as the zero Decimal -// would spell it "0" and make it a duplicate of every zero, so the judge -// reports it unspellable instead. -func TestCanonicalValue_DeclinesANumberOutsideTheGrammar(t *testing.T) { - t.Parallel() - got, ok := canonicalValue(number("1p4"), 0) - - assert.False(t, ok) - assert.Empty(t, got) -} - -// TestCanonicalValue_SpellsANumberByItsValue holds the spelling to the value: -// 1500 is "1.5e3" however it is written, and every zero is "0". -func TestCanonicalValue_SpellsANumberByItsValue(t *testing.T) { - t.Parallel() - for _, tc := range []struct{ in, want string }{ - {"1500", "1.5e3"}, - {"15e2", "1.5e3"}, - {"-0.0", "0"}, - } { - got, ok := canonicalValue(number(tc.in), 0) - - assert.True(t, ok, tc.in) - assert.Equal(t, tc.want, got, tc.in) - } -} diff --git a/compilers/openapi/internal/merge/chainaliases.go b/compilers/openapi/internal/merge/chainaliases.go new file mode 100644 index 000000000..af3787280 --- /dev/null +++ b/compilers/openapi/internal/merge/chainaliases.go @@ -0,0 +1,168 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "math/bits" + "slices" + + "github.com/dexpace/morphic/ir" +) + +// aliasDistance returns how many aliases lie from from itself through the one +// whose Base names to, and false where to is not on from's chain or either +// chain is cyclic. +func aliasDistance(index *ir.AliasChainIndex, from, to ir.TypeID) (int, bool) { + fromDepth, fromAcyclic := index.Depth(from) + toDepth, toAcyclic := index.Depth(to) + distance := fromDepth - toDepth + if !fromAcyclic || !toAcyclic || distance <= 0 { + return 0, false + } + ancestor, _ := index.Ancestor(from, distance) + return distance, ancestor == to +} + +// chainContains reports whether to is on from's chain: a Base target on it, +// the type it ends on among them. A cyclic chain contains none. +func chainContains(index *ir.AliasChainIndex, from, to ir.TypeID) bool { + _, contains := aliasDistance(index, from, to) + return contains +} + +// sharedAliasBelow returns the first node the chains of a and b, two aliases, +// both name below themselves, nearest a, and false where they share none or +// it is a primitive. +func sharedAliasBelow(index *ir.AliasChainIndex, node func(ir.TypeID) (ir.TypeDef, bool), a, b ir.TypeID) (ir.TypeID, bool) { + aDepth, aAcyclic := index.Depth(a) + bDepth, bAcyclic := index.Depth(b) + aEnd, _ := index.End(a) + bEnd, _ := index.End(b) + if !aAcyclic || !bAcyclic || aDepth == 0 || bDepth == 0 || aEnd != bEnd { + return "", false + } + x, _ := index.Ancestor(a, 1) + y, _ := index.Ancestor(b, 1) + shared := lowestCommonAlias(index, x, aDepth-1, y, bDepth-1) + if typeDef, _ := node(shared); isPrimitive(typeDef) { + return "", false + } + return shared, true +} + +// lowestCommonAlias returns the nearest type x and y, at depths xDepth and +// yDepth on chains ending on one acyclic end, both are or lie above: the +// deeper lifted to the other's depth, then both lifted by each power of two, +// greatest first, that leaves them apart. +func lowestCommonAlias(index *ir.AliasChainIndex, x ir.TypeID, xDepth int, y ir.TypeID, yDepth int) ir.TypeID { + if xDepth < yDepth { + x, xDepth, y, yDepth = y, yDepth, x, xDepth + } + x, _ = index.Ancestor(x, xDepth-yDepth) + if x == y { + return x + } + for k := bits.Len(uint(yDepth)) - 1; k >= 0; k-- { + upX, xOK := index.Ancestor(x, 1< 0; k++ { + if distance&1 != 0 { + segment := summaries.segment(at, k) + if first { + combined, first = segment, false + } else { + combined = summaries.combineRuns(combined, segment) + } + at, _ = summaries.index.Ancestor(at, 1<>= 1 + } + return combined, true +} + +// segment returns the combination of the 2^k aliases from the acyclic alias at +// up its chain, summarizing first, from the top, every alias between it and +// the nearest one above it already summarized, so each is built once. +func (summaries *aliasRunSummaries[T]) segment(at ir.TypeID, k int) T { + if segments, built := summaries.segments[at]; built { + return segments[k] + } + var path []ir.TypeID + for cursor := at; ; { + if depth, _ := summaries.index.Depth(cursor); depth == 0 { + break + } + if _, built := summaries.segments[cursor]; built { + break + } + path = append(path, cursor) + cursor, _ = summaries.index.Ancestor(cursor, 1) + } + for _, alias := range slices.Backward(path) { + summaries.summarize(alias) + } + return summaries.segments[at][k] +} + +// summarize builds the segments of the alias at, every alias above it +// summarized already: one for each power of two up to its depth. +func (summaries *aliasRunSummaries[T]) summarize(at ir.TypeID) { + depth, _ := summaries.index.Depth(at) + typeDef, _ := summaries.node(at) + scalar, _ := typeDef.(*ir.Scalar) + segments := make([]T, bits.Len(uint(depth))) + segments[0] = summaries.aliasSummary(scalar) + for k := 1; k < len(segments); k++ { + half, _ := summaries.index.Ancestor(at, 1<<(k-1)) + segments[k] = summaries.combineRuns(segments[k-1], summaries.segments[half][k-1]) + } + summaries.segments[at] = segments +} diff --git a/compilers/openapi/internal/merge/chainaliases_internal_test.go b/compilers/openapi/internal/merge/chainaliases_internal_test.go new file mode 100644 index 000000000..8b0003836 --- /dev/null +++ b/compilers/openapi/internal/merge/chainaliases_internal_test.go @@ -0,0 +1,355 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "fmt" + "math/rand/v2" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" +) + +// integerPrimitive is the primitive the chains of these tests end on. +var integerPrimitive = ir.PrimitiveTypeID(ir.PrimitiveInteger) + +// aliasChainRegistry returns a registry holding the integer primitive and the aliases +// I0 to I(n-1), each over the one below it and I0 over integer, and the model +// type/m, the opaque scalar type/opaque, the cycle type/A ⇄ type/B entered from +// type/X, the self-naming type/self, type/dangling naming no type, and the +// scalars type/P and type/Q over type/m. +func aliasChainRegistry(count int) ir.TypeRegistry { + types := irtest.DocOf( + &ir.Primitive{ID: integerPrimitive, PrimitiveKind: ir.PrimitiveInteger}, + irtest.ModelOf("type/m", nil), + irtest.ScalarOf("type/opaque", ""), + irtest.ScalarOf("type/A", "type/B"), irtest.ScalarOf("type/B", "type/A"), irtest.ScalarOf("type/X", "type/A"), + irtest.ScalarOf("type/self", "type/self"), + irtest.ScalarOf("type/dangling", "type/ghost"), + irtest.ScalarOf("type/P", "type/m"), irtest.ScalarOf("type/Q", "type/m"), + ).Types + below := integerPrimitive + for i := range count { + types[chainAlias(i)] = irtest.ScalarOf(chainAlias(i), below) + below = chainAlias(i) + } + return types +} + +// TestChainContains_ContainsItsAliasesAlone pins chainContains: what a chain +// contains is a Base target on it, the primitive end among them, the alias +// asked not on its own chain, and a cyclic chain contains nothing. +func TestChainContains_ContainsItsAliasesAlone(t *testing.T) { + t.Parallel() + index := ir.NewAliasChainIndex(aliasChainRegistry(200).Lookup) + for _, tc := range []struct { + from, to ir.TypeID + want bool + }{ + {chainAlias(5), chainAlias(4), true}, + {chainAlias(5), chainAlias(3), true}, + {chainAlias(5), chainAlias(0), true}, + {chainAlias(5), integerPrimitive, true}, + {chainAlias(199), chainAlias(0), true}, + {chainAlias(199), chainAlias(198), true}, + {chainAlias(5), chainAlias(5), false}, + {chainAlias(3), chainAlias(5), false}, + {chainAlias(5), "type/m", false}, + {"type/P", "type/m", true}, + {"type/m", "type/m", false}, + {"type/m", chainAlias(0), false}, + {"type/dangling", "type/ghost", true}, + {"type/A", "type/B", false}, + {"type/X", "type/A", false}, + {"type/self", "type/self", false}, + {"type/never", chainAlias(0), false}, + } { + assert.Equal(t, tc.want, chainContains(index, tc.from, tc.to), "%s to %s", tc.from, tc.to) + } +} + +// TestSharedAliasBelow_CountsNoPrimitiveEnd pins the node two chains share +// first below their aliases: I2 for I5 and I3 over I0 and integer, a branch's +// own head where it branches off, a model two scalars name, and none for two scalars +// directly over integer, a type that is no alias, or a cyclic chain. +func TestSharedAliasBelow_CountsNoPrimitiveEnd(t *testing.T) { + t.Parallel() + types := aliasChainRegistry(200) + types["type/branch"] = irtest.ScalarOf("type/branch", chainAlias(3)) + types["type/overInteger"] = irtest.ScalarOf("type/overInteger", integerPrimitive) + index := ir.NewAliasChainIndex(types.Lookup) + for _, tc := range []struct { + a, b ir.TypeID + want ir.TypeID // "" where they share none + }{ + {chainAlias(5), chainAlias(3), chainAlias(2)}, + {chainAlias(3), chainAlias(5), chainAlias(2)}, + {chainAlias(5), chainAlias(5), chainAlias(4)}, + {chainAlias(199), chainAlias(1), chainAlias(0)}, + {"type/branch", chainAlias(5), chainAlias(3)}, + {chainAlias(5), "type/branch", chainAlias(3)}, + {"type/P", "type/Q", "type/m"}, + {chainAlias(0), "type/overInteger", ""}, + {chainAlias(1), chainAlias(0), ""}, + {"type/m", chainAlias(5), ""}, + {chainAlias(5), "type/m", ""}, + {"type/A", "type/B", ""}, + {"type/X", "type/A", ""}, + {"type/never", chainAlias(5), ""}, + } { + got, shared := sharedAliasBelow(index, types.Lookup, tc.a, tc.b) + assert.Equal(t, tc.want != "", shared, "%s and %s", tc.a, tc.b) + assert.Equal(t, tc.want, got, "%s and %s", tc.a, tc.b) + } +} + +// listedSummaries is segment summaries over index that list the aliases they +// cover, nearest first. +func listedSummaries(index *ir.AliasChainIndex, types ir.TypeRegistry) *aliasRunSummaries[[]ir.TypeID] { + return newAliasRunSummaries(index, types.Lookup, + func(scalar *ir.Scalar) []ir.TypeID { return []ir.TypeID{scalar.ID} }, + func(near, far []ir.TypeID) []ir.TypeID { return slices.Concat(near, far) }) +} + +// TestSummaryBetween_CombinesTheAliasesBetweenTwo pins summaryBetween: the +// aliases from the first itself through the one whose Base names the second, +// nearest first, past 64 aliases; none where the second is not on the first's +// chain, the alias itself among them, or the chain is cyclic. +func TestSummaryBetween_CombinesTheAliasesBetweenTwo(t *testing.T) { + t.Parallel() + types := aliasChainRegistry(200) + runSummaries := listedSummaries(ir.NewAliasChainIndex(types.Lookup), types) + + for _, tc := range []struct { + from, to ir.TypeID + want []ir.TypeID + }{ + {chainAlias(5), chainAlias(4), []ir.TypeID{chainAlias(5)}}, + {chainAlias(5), chainAlias(3), []ir.TypeID{chainAlias(5), chainAlias(4)}}, + {chainAlias(5), integerPrimitive, []ir.TypeID{chainAlias(5), chainAlias(4), chainAlias(3), chainAlias(2), chainAlias(1), chainAlias(0)}}, + {"type/P", "type/m", []ir.TypeID{"type/P"}}, + } { + got, ok := runSummaries.summaryBetween(tc.from, tc.to) + assert.True(t, ok, "%s to %s", tc.from, tc.to) + assert.Equal(t, tc.want, got, "%s to %s", tc.from, tc.to) + } + + deep, ok := runSummaries.summaryBetween(chainAlias(199), chainAlias(0)) + require.True(t, ok) + want := make([]ir.TypeID, 0, 199) + for i := 199; i >= 1; i-- { + want = append(want, chainAlias(i)) + } + assert.Equal(t, want, deep, "199 aliases, nearest first, whatever jump aliases group them") + + for _, tc := range [][2]ir.TypeID{ + {chainAlias(5), chainAlias(5)}, {chainAlias(3), chainAlias(5)}, {chainAlias(5), "type/m"}, + {"type/m", chainAlias(0)}, {"type/A", "type/B"}, {"type/X", "type/A"}, {"type/self", "type/self"}, + } { + _, ok := runSummaries.summaryBetween(tc[0], tc[1]) + assert.False(t, ok, "%s to %s", tc[0], tc[1]) + } +} + +// patternChain is aliasChainRegistry(n) with every alias writing a pattern of its own, +// the far one a maxLength of 2 beside it. +func patternChain(t *testing.T, count int) ir.TypeRegistry { + t.Helper() + types := aliasChainRegistry(count) + for i := range count { + scalar, ok := types[chainAlias(i)].(*ir.Scalar) + require.True(t, ok) + scalar.Constraints = &ir.Constraints{Pattern: fmt.Sprintf("^p%d", i)} + } + far, ok := types[chainAlias(0)].(*ir.Scalar) + require.True(t, ok) + far.Constraints.MaxLength = new(int64(2)) + return types +} + +// TestSummaryBetween_IntersectsAChainOfDistinctPatternsToOneDisagreement pins +// the bounds intersection view reads over ConstraintIntersection: a chain each +// alias of which writes its own pattern intersects to one disagreeing keyword +// holding the nearest's pattern, beside the bound its far alias writes. +func TestSummaryBetween_IntersectsAChainOfDistinctPatternsToOneDisagreement(t *testing.T) { + t.Parallel() + types := patternChain(t, 120) + runSummaries := newAliasRunSummaries(ir.NewAliasChainIndex(types.Lookup), types.Lookup, + func(scalar *ir.Scalar) ir.ConstraintIntersection { + return ir.ConstraintIntersectionOf(scalar.Constraints) + }, + ir.ConstraintIntersection.Intersect) + + combined, ok := runSummaries.summaryBetween(chainAlias(119), integerPrimitive) + + require.True(t, ok) + assert.Equal(t, []ir.ConstraintKeyword{ir.ConstraintKeywordPattern}, combined.DisagreeingKeywords()) + constraints := combined.ConstraintsKeepingReceiverOnDisagreement() + require.NotNil(t, constraints) + assert.Equal(t, "^p119", constraints.Pattern, "the nearest alias's") + assert.Equal(t, new(int64(2)), constraints.MaxLength, "the far alias's bound combines beside") +} + +// usesOfAliasChain is aliasChainRegistry(n) with n uses of its head: an alias +// over each alias, as the fields of many models typed by one chain read it. +func usesOfAliasChain(count int) ir.TypeRegistry { + types := aliasChainRegistry(count) + for i := range count { + use := ir.TypeID(fmt.Sprintf("type/use%d", i)) + types[use] = irtest.ScalarOf(use, chainAlias(i)) + } + return types +} + +// countedLookup is types.Lookup, counting each read in reads. +func countedLookup(types ir.TypeRegistry, reads *int) func(ir.TypeID) (ir.TypeDef, bool) { + return func(id ir.TypeID) (ir.TypeDef, bool) { + *reads++ + typeDef, ok := types[id] + return typeDef, ok + } +} + +// TestSummaryBetween_CombinationsGrowAsTheLogarithmPerQuestion pins the +// combinations' cost: the combination between every use of one chain and the +// chain's far alias, as view reads one per field, and the node each shares +// with the head, summarize each alias once and combine O(log n) summaries per +// question, where combining alias by alias is quadratic, and read the +// registry linearly. +func TestSummaryBetween_CombinationsGrowAsTheLogarithmPerQuestion(t *testing.T) { + t.Parallel() + var reads, summaries, combinations [3]int + for k, n := range chainSizes { + types := usesOfAliasChain(n) + lookup := countedLookup(types, &reads[k]) + index := ir.NewAliasChainIndex(lookup) + runSummaries := newAliasRunSummaries(index, lookup, + func(*ir.Scalar) int { summaries[k]++; return 1 }, + func(near, far int) int { combinations[k]++; return near + far }) + for i := range n { + use := ir.TypeID(fmt.Sprintf("type/use%d", i)) + count, ok := runSummaries.summaryBetween(use, integerPrimitive) + require.True(t, ok) + require.Equal(t, i+2, count, "the use and every alias below it") + _, shared := sharedAliasBelow(index, lookup, use, chainAlias(n-1)) + require.True(t, shared, "use%d shares an alias with the head", i) + } + assert.LessOrEqual(t, summaries[k], 2*n, "each of the %d aliases is summarized once", 2*n) + } + assertMarginalGrowth(t, reads, "the lookups") + assertMarginalGrowth(t, combinations, "the combinations") +} + +// walkedBases is the reference reading of id's chain, apart from the index: the +// aliases it walks and the bases they name, each alias's Base target in turn, +// until a type that is no alias or the first ID met twice, and whether it met +// one twice. +func walkedBases(types ir.TypeRegistry, id ir.TypeID) (aliases, bases []ir.TypeID, cyclic bool) { + seen := map[ir.TypeID]bool{} + for { + base, alias := ir.AliasBase(types, id) + if !alias { + return aliases, bases, false + } + if seen[id] { + return aliases, bases, true + } + seen[id] = true + aliases = append(aliases, id) + bases = append(bases, base) + id = base + } +} + +// walkedSharedAlias is the reference sharedAliasBelow: the first alias of a's +// chain that b's chain names too, no primitive counted. +func walkedSharedAlias(types ir.TypeRegistry, a, b ir.TypeID) (ir.TypeID, bool) { + _, basesA, cyclicA := walkedBases(types, a) + _, basesB, cyclicB := walkedBases(types, b) + if cyclicA || cyclicB { + return "", false + } + for _, base := range basesA { + if _, primitive := types[base].(*ir.Primitive); !primitive && slices.Contains(basesB, base) { + return base, true + } + } + return "", false +} + +// aliasForest is a registry of up to sixty aliases over two models, a +// primitive, an opaque scalar and an ID it does not hold, each alias's Base an +// earlier alias or one of those, so its chains branch at every depth, and a few +// aliases naming a later one, which closes cycles. +func aliasForest(rng *rand.Rand) (ir.TypeRegistry, []ir.TypeID) { + types := irtest.DocOf( + &ir.Primitive{ID: integerPrimitive, PrimitiveKind: ir.PrimitiveInteger}, + irtest.ModelOf("type/m1", nil), irtest.ModelOf("type/m2", nil), irtest.ScalarOf("type/opaque", ""), + ).Types + ends := []ir.TypeID{integerPrimitive, "type/m1", "type/m2", "type/opaque", "type/ghost"} + n := 1 + rng.IntN(60) + ids := make([]ir.TypeID, n, n+len(ends)) + for i := range ids { + ids[i] = ir.TypeID(fmt.Sprintf("type/a%02d", i)) + } + for i, id := range ids { + var base ir.TypeID + switch r := rng.IntN(20); { + case r == 0 && i+1 < n: + base = ids[i+1+rng.IntN(n-i-1)] + case r < 4 || i == 0: + base = ends[rng.IntN(len(ends))] + default: + base = ids[rng.IntN(i)] + } + types[id] = irtest.ScalarOf(id, base) + } + return types, append(ids, ends...) +} + +// TestChainAliases_AnswerAsTheReferenceWalkDoes holds chainContains, +// sharedAliasBelow and the combinations to a walk of each chain on random forests of +// aliases, branching at every depth, with cycles, dangling Bases and every +// kind of end, each question asked over a fresh index and over one asked +// everything before. +func TestChainAliases_AnswerAsTheReferenceWalkDoes(t *testing.T) { + t.Parallel() + var shared, branched int + for seed := range uint64(200) { + types, ids := aliasForest(rand.New(rand.NewPCG(seed, seed+7))) + warm := ir.NewAliasChainIndex(types.Lookup) + runSummaries := listedSummaries(warm, types) + for _, a := range ids { + aliases, bases, cyclic := walkedBases(types, a) + for _, b := range ids { + at := fmt.Sprintf("seed %d: %s and %s", seed, a, b) + for _, index := range []*ir.AliasChainIndex{warm, ir.NewAliasChainIndex(types.Lookup)} { + want, wantShared := walkedSharedAlias(types, a, b) + got, gotShared := sharedAliasBelow(index, types.Lookup, a, b) + require.Equal(t, wantShared, gotShared, at) + require.Equal(t, want, got, at) + reaches := !cyclic && slices.Contains(bases, b) + require.Equal(t, reaches, chainContains(index, a, b), at) + if gotShared && len(bases) > 1 && !slices.Contains(bases, b) && got != bases[0] { + branched++ + } + shared += len(want) + } + combined, ok := runSummaries.summaryBetween(a, b) + reaches := !cyclic && slices.Contains(bases, b) + require.Equal(t, reaches, ok, at) + if reaches { + require.Equal(t, aliases[:slices.Index(bases, b)+1], combined, at) + } + } + } + } + require.Positive(t, shared, "no pair shared an alias, so sharedAliasBelow was never asked a real question") + require.Positive(t, branched, "no pair met below two branches") +} diff --git a/compilers/openapi/internal/merge/compose.go b/compilers/openapi/internal/merge/compose.go index b549f2b01..cecded85c 100644 --- a/compilers/openapi/internal/merge/compose.go +++ b/compilers/openapi/internal/merge/compose.go @@ -6,11 +6,12 @@ package merge import ( "encoding/json/jsontext" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) // conjunct is one type a position composes: the member naming it, and the node -// that member's type stands for. +// that member's type represents. type conjunct struct { member node ir.TypeDef @@ -18,13 +19,10 @@ type conjunct struct { // composition returns the types the position composes // (docs/compilers/openapi.md#allof-redeclared-property): those of the members -// no other member's type holds, each once, in declaration order. Two models, -// or a model and a map or a union, say nothing of what they share, but an -// instance satisfies both, so the type there is a model composing them all. -// It returns nothing where fewer than two remain, since one type then holds -// every other, where none is a model, or where one is no model, map or union, -// such as a kind, which leaves the type to the winner. -func (p position) composition(reg registry) []conjunct { +// no other member's type holds, each once, in declaration order, where at +// least two remain, one is a model and each is a model, a map or a union. An +// instance satisfies all of them, so the type there is a model composing them. +func (p position) composition(reg registryReader) []conjunct { var conjuncts []conjunct model := false for i, member := range p.members { @@ -46,45 +44,78 @@ func (p position) composition(reg registry) []conjunct { } // heldByAnother reports whether some other member's type already says all -// member i's does: one narrower, or the same one standing for it (stands). +// member i's does: one narrower, or the same one representing it (represents). func (p position) heldByAnother(i int) bool { for j := range p.members { - if p.rel[j][i] == firstTypeIsNarrower || (p.rel[j][i] == relSame && p.stands(j, i)) { + if p.rel[j][i] == firstTypeIsNarrower || (p.rel[j][i] == relSame && p.represents(j, i)) { return true } } return false } -// compose returns the model that composes cs, minted at pointer, as a written -// allOf of them composes: SelectBase picks its Base among those written as a -// $ref, and the rest are Mixins in declaration order, so the model's own -// members settle in that order too. Only the target is carried. A conjunct says -// nothing of null, which the reference to the model says (position.null). The -// pointer is the declaration last to widen the field (fieldSpan), so swapping -// two entries renames the model, and moves a report on a member it settles +// compose returns the model that composes cs' parts, minted at pointer, as a +// written allOf of them composes: SelectBase picks its Base among those +// written as a $ref, and the rest are Mixins in declaration order. The pointer +// is the declaration last to widen the field (fieldSpan), so swapping two +// entries renames the model, and moves a report on a member it settles // (GitHub #1921, #1992). func (b *builder) compose(cs []conjunct, pointer jsontext.Pointer) ir.TypeID { + parts := b.composedParts(cs) var refs []int - for k, conjunct := range cs { - if !hoistedAt(conjunct.node, b.f.decls[conjunct.decl].sites()) { + for k, part := range parts { + if part.ref { refs = append(refs, k) } } - base, hasBase := SelectBase(refs, func(k int) bool { return inHierarchy(b.f.g.Reg, cs[k].node) }) + base, hasBase := SelectBase(refs, func(k int) bool { return b.f.g.Walk.InDiscriminatorHierarchy(parts[k].place) }) composed := &ir.Model{} - var brought []jsontext.Pointer - for k, conjunct := range cs { - ref := ir.TypeRef{Target: conjunct.ref.Target} + var partPointers []jsontext.Pointer + for k, part := range parts { + ref := ir.TypeRef{Target: part.target} if hasBase && k == base { composed.Base = &ref - brought = append([]jsontext.Pointer{b.f.decls[conjunct.decl].reportAt()}, brought...) + partPointers = append([]jsontext.Pointer{part.writtenAt}, partPointers...) continue } composed.Mixins = append(composed.Mixins, ref) - brought = append(brought, b.f.decls[conjunct.decl].reportAt()) + partPointers = append(partPointers, part.writtenAt) } - return b.mint(pointer, composed, brought) + return b.mint(pointer, composed, partPointers) +} + +// composedPart is one part of a model a fold composes: its type, the node the +// judgment read it as, where the model writes it (carried), where its +// declaration is written, and whether that writes it as a $ref, which may make +// it the Base. +type composedPart struct { + node ir.TypeDef + target ir.TypeID + writtenAt jsontext.Pointer + place ir.Provenance + ref bool +} + +// composedParts returns the parts the model composing cs composes, one for +// each conjunct, in declaration order. A conjunct handed in before one it +// follows is an internal error, noted at its declaration outside a dry run, +// and composed where it sits. +func (b *builder) composedParts(cs []conjunct) []composedPart { + parts := make([]composedPart, 0, len(cs)) + for k, conjunct := range cs { + declaration := b.f.decls[conjunct.decl] + if k > 0 && conjunct.decl < cs[k-1].decl && !b.dry { + at := fieldPlace(b.f.g, declaration, fieldGivenTogether) + b.f.note(conjunct.decl, ir.SeverityError, diag.InternalInvariant, + "internal: field %q composes the declaration at %s after a later one", b.f.merged.WireName, + placeName(b.f.g.Sources, at, at.Source)) + } + parts = append(parts, composedPart{ + node: conjunct.node, target: conjunct.ref.Target, writtenAt: declaration.assemblyPointer(), + place: fieldPlace(b.f.g, declaration, fieldGivenTogether), ref: !hoistedAt(conjunct.node, declaration.sites()), + }) + } + return parts } // SelectBase returns which entry of a composition becomes Model.Base, given @@ -104,59 +135,14 @@ func SelectBase(refs []int, takesPart func(i int) bool) (int, bool) { return 0, false } -// inHierarchy reports whether node takes part in a discriminator hierarchy: a -// Model or Union holding a discriminator its source declares, or a Model one of -// whose supertypes does at any depth (ir.Supertypes), as a composition the -// source writes elects its Base. A visited set ends the walk on a cyclic -// hierarchy. A member lowering to a Union that holds no discriminator reads as -// none here, though the election over the source counts it (GitHub #1901). -func inHierarchy(reg ir.TypeRegistry, node ir.TypeDef) bool { - doc := &ir.Document{Types: reg} - seen := map[ir.TypeID]bool{} - queue := []ir.TypeDef{node} - for len(queue) > 0 { - td := queue[len(queue)-1] - queue = queue[:len(queue)-1] - if !ir.IsNilTypeDef(td) && declaresDiscriminator(td) { - return true - } - model, ok := td.(*ir.Model) - if !ok || model == nil || seen[model.ID] { - continue - } - seen[model.ID] = true - for _, id := range ir.Supertypes(doc, model.ID) { - queue = append(queue, reg[id]) - } - } - return false -} - -// declaresDiscriminator reports whether td, which is not nil, holds a -// discriminator its source declares: a Model's, or a Union's, as a union written -// with structure holds the one written with it. One a policy inferred is no -// source's, so it makes no hierarchy, as the election over the source reads none. -func declaresDiscriminator(td ir.TypeDef) bool { - var discriminator *ir.Discriminator - switch n := td.(type) { - case *ir.Model: - discriminator = n.Discriminator - case *ir.Union: - discriminator = n.Discriminator - default: - return false - } - return discriminator != nil && !discriminator.Inferred -} - // composable returns the node ref names, directly or through aliases, where // it is a Model, a MapT or a Union, and false where it names anything else. -func (r registry) composable(ref ir.TypeRef) (ir.TypeDef, bool) { - td, ok := r.resolve(ref.Target) +func (r registryReader) composable(ref ir.TypeRef) (ir.TypeDef, bool) { + typeDef, ok := r.resolve(ref.Target) if !ok { return nil, false } - switch node := r.unaliased(td).(type) { + switch node := r.unaliased(typeDef).(type) { case *ir.Model, *ir.MapT, *ir.Union: return node, true default: diff --git a/compilers/openapi/internal/merge/compose_internal_test.go b/compilers/openapi/internal/merge/compose_internal_test.go index cee3943fb..0edd20495 100644 --- a/compilers/openapi/internal/merge/compose_internal_test.go +++ b/compilers/openapi/internal/merge/compose_internal_test.go @@ -63,15 +63,20 @@ func composeRegistry() map[ir.TypeID]ir.TypeDef { } // declaredAt is where the nth declaration of a field is written, each in an -// allOf entry of one schema, so the second names the field (fieldSpan). -func declaredAt(n int) jsontext.Pointer { - return jsontext.Pointer(fmt.Sprintf("/s/allOf/%d/properties/data", n)) +// allOf entry of one schema. +func declaredAt(count int) jsontext.Pointer { + return jsontext.Pointer(fmt.Sprintf("/s/allOf/%d/properties/data", count)) } +// foldKey is where a fold of declarations at declaredAt mints its node: the +// narrowest schema holding them, then allOf/properties and the field's name, +// which no order of the declarations moves. +const foldKey jsontext.Pointer = "/s/allOf/properties/data" + // nthDecl is the nth declaration of a field, of target. -func nthDecl(n int, target ir.TypeID) declaration { +func nthDecl(count int, target ir.TypeID) declaration { return declaration{ - property: ir.Property{WireName: "data", Type: ir.TypeRef{Target: target}, Provenance: ptrAt(declaredAt(n))}, + property: ir.Property{WireName: "data", Type: ir.TypeRef{Target: target}, Provenance: ptrAt(declaredAt(count))}, source: written(`{}`), } } @@ -85,17 +90,19 @@ func declsOf(targets ...ir.TypeID) []declaration { return out } -// TestFold_RedeclaredModelsCompose pins what a field declared as several models, -// or as a model beside a map or a union, takes: a model the fold mints, -// composing each once as a written allOf of them does, its Base the first taking -// part in a discriminator hierarchy at any depth. Nothing is lost, so -// nothing is kept and nothing reported, and a bare `{}` beside the models adds -// no conjunct. +// TestFold_RedeclaredModelsCompose pins what a field declared as several +// models, or as a model beside a map or a union, takes: a model the fold mints, +// composing each once as a written allOf of them does, its Base the first +// declaration the walk places in a discriminator hierarchy, reading the source +// as the written allOf's choice does, whatever the registry holds. Nothing is +// lost, so nothing is kept and nothing reported, and a bare `{}` beside the +// models adds no conjunct. func TestFold_RedeclaredModelsCompose(t *testing.T) { t.Parallel() for _, tc := range []struct { name string targets []ir.TypeID + placed []int base ir.TypeID mixins []ir.TypeID }{ @@ -103,14 +110,15 @@ func TestFold_RedeclaredModelsCompose(t *testing.T) { {name: "an inline object, then a component", targets: []ir.TypeID{"type/in0", "type/B"}, base: "type/B", mixins: []ir.TypeID{"type/in0"}}, {name: "two inline objects stay mixins", targets: []ir.TypeID{"type/in0", "type/in1"}, mixins: []ir.TypeID{"type/in0", "type/in1"}}, {name: "two components stay mixins, in order", targets: []ir.TypeID{"type/B", "type/A"}, mixins: []ir.TypeID{"type/B", "type/A"}}, - {name: "a discriminated component is the base", targets: []ir.TypeID{"type/A", "type/Pet"}, base: "type/Pet", mixins: []ir.TypeID{"type/A"}}, - {name: "the first discriminated component is", targets: []ir.TypeID{"type/Dog", "type/A", "type/Pet"}, base: "type/Dog", mixins: []ir.TypeID{"type/A", "type/Pet"}}, - {name: "a subtype of a discriminated component is", targets: []ir.TypeID{"type/A", "type/Mid"}, base: "type/Mid", mixins: []ir.TypeID{"type/A"}}, - {name: "a deeper one, through an alias", targets: []ir.TypeID{"type/A", "type/Low"}, base: "type/Low", mixins: []ir.TypeID{"type/A"}}, - {name: "a cycle of subtypes declaring none is not", targets: []ir.TypeID{"type/A", "type/loopA"}, mixins: []ir.TypeID{"type/A", "type/loopA"}}, - {name: "a union holding a declared discriminator is", targets: []ir.TypeID{"type/A", "type/tagged"}, base: "type/tagged", mixins: []ir.TypeID{"type/A"}}, - {name: "a model under one is", targets: []ir.TypeID{"type/A", "type/byTag"}, base: "type/byTag", mixins: []ir.TypeID{"type/A"}}, - {name: "a union holding an inferred one is not", targets: []ir.TypeID{"type/A", "type/guessed"}, mixins: []ir.TypeID{"type/A", "type/guessed"}}, + {name: "a declaration the walk places is the base", targets: []ir.TypeID{"type/A", "type/Pet"}, placed: []int{1}, base: "type/Pet", mixins: []ir.TypeID{"type/A"}}, + {name: "the first it places is", targets: []ir.TypeID{"type/Dog", "type/A", "type/Pet"}, placed: []int{0, 2}, base: "type/Dog", mixins: []ir.TypeID{"type/A", "type/Pet"}}, + {name: "one placed though its type holds no discriminator", targets: []ir.TypeID{"type/A", "type/B"}, placed: []int{1}, base: "type/B", mixins: []ir.TypeID{"type/A"}}, + {name: "a union placed though it holds no discriminator", targets: []ir.TypeID{"type/apart", "type/A"}, placed: []int{0}, base: "type/apart", mixins: []ir.TypeID{"type/A"}}, + {name: "a discriminated component the walk does not place is not", targets: []ir.TypeID{"type/A", "type/Pet"}, mixins: []ir.TypeID{"type/A", "type/Pet"}}, + {name: "nor a subtype of one", targets: []ir.TypeID{"type/A", "type/Mid"}, mixins: []ir.TypeID{"type/A", "type/Mid"}}, + {name: "nor a deeper one, through an alias", targets: []ir.TypeID{"type/A", "type/Low"}, mixins: []ir.TypeID{"type/A", "type/Low"}}, + {name: "nor a union holding a declared discriminator", targets: []ir.TypeID{"type/A", "type/tagged"}, mixins: []ir.TypeID{"type/A", "type/tagged"}}, + {name: "nor a model under one", targets: []ir.TypeID{"type/A", "type/byTag"}, mixins: []ir.TypeID{"type/A", "type/byTag"}}, {name: "one type declared twice composes once, where the later is", targets: []ir.TypeID{"type/A", "type/B", "type/A"}, mixins: []ir.TypeID{"type/B", "type/A"}}, {name: "`{}` adds no conjunct", targets: []ir.TypeID{"type/top", "type/A", "type/in2"}, base: "type/A", mixins: []ir.TypeID{"type/in2"}}, {name: "an alias of `{}` saying nothing of its values adds none", targets: []ir.TypeID{"type/A", "type/B", "type/topDoc"}, mixins: []ir.TypeID{"type/A", "type/B"}}, @@ -127,10 +135,13 @@ func TestFold_RedeclaredModelsCompose(t *testing.T) { t.Parallel() reg := composeRegistry() stubbed, recorded := stubMerger(reg) + for _, i := range tc.placed { + stubbed.walk.hierarchy = append(stubbed.walk.hierarchy, declaredAt(i)) + } got := stubbed.fold(declsOf(tc.targets...)) - require.Equal(t, composedAt(declaredAt(1)), got.Type.Target, "the field takes the minted model") + require.Equal(t, composedAt(foldKey), got.Type.Target, "the field takes the minted model") model, ok := reg[got.Type.Target].(*ir.Model) require.True(t, ok, "the minted model is registered") assert.Empty(t, cmp.Diff(tc.mixins, targetsOf(model.Mixins)), "mixins") @@ -156,10 +167,10 @@ func targetsOf(refs []ir.TypeRef) []ir.TypeID { return out } -// TestFold_OnlyTwoOrMoreModelsCompose pins where the type stays the winner's: -// one type holds every other, a declaration that remains is no model, map or -// union, or none is a model, so the fold keeps the type it would keep without -// composing, of a tie the later's, and mints nothing. +// TestFold_OnlyTwoOrMoreModelsCompose pins where the type stays the chosen +// declaration's: one type holds every other, a declaration that remains is no +// model, map or union, or none is a model, so the fold keeps the type it would +// keep without composing, of a tie the later's, and mints nothing. func TestFold_OnlyTwoOrMoreModelsCompose(t *testing.T) { t.Parallel() for _, tc := range []struct { @@ -195,7 +206,7 @@ func TestFold_OnlyTwoOrMoreModelsCompose(t *testing.T) { assert.Len(t, reg, count, "nothing is minted") want := make([]string, 0, len(tc.dropped)) for _, pointer := range tc.dropped { - want = append(want, losingDeclarationKey+string(pointer)) + want = append(want, passedOverDeclarationKey+string(pointer)) } assert.ElementsMatch(t, want, slices.Collect(maps.Keys(got.Unmodeled)), "each drop is kept") }) @@ -252,15 +263,15 @@ func TestFold_AComposedFieldKeepsEveryDeclarationsDetail(t *testing.T) { assert.Equal(t, "^b$", got.Constraints.Pattern, "the last to set a keyword with no order keeps it") require.Len(t, *recorded, 1) assert.Equal(t, diag.ConflictingRedecl, (*recorded)[0].Code) - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(0))) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(0))) } // TestFold_AComposedFieldHoldsTheBoundsOfEachDeclarationsOwnNode pins the // bounds of a field the fold composes: a declaration owning its node leaves its -// bounds there, its property holding none, so the field takes those of each node -// hoisted at a declaration (ownBounds), met with those a property holds. A -// component's bounds stay its own, which the composition reaches through its -// reference, and the composed model holds none. +// bounds there, its property holding none, so the field takes those of each +// node hoisted at a declaration (ownBounds), intersected with those a property +// holds. A component's bounds stay its own, which the composition reaches +// through its reference, and the composed model holds none. func TestFold_AComposedFieldHoldsTheBoundsOfEachDeclarationsOwnNode(t *testing.T) { t.Parallel() reg := composeRegistry() @@ -305,16 +316,17 @@ func TestOwnBounds_ReadsTheNodeADeclarationOwns(t *testing.T) { "type/model": bound, "type/map": bound, "type/scalar": length, "type/union": length, "type/list": nil, "type/named": nil, "type/missing": nil, } { - foldingValue := &folding{g: &stubbed.Merger, decls: declsOf(target)} - assert.Equal(t, want, foldingValue.ownBounds(0), target) + folding := &fieldFold{g: &stubbed.Merger, decls: declsOf(target)} + assert.Equal(t, want, folding.ownBounds(0), target) } } -// TestFold_AliasesOfOneModelComposeThoughTheirBoundsMeet pins which node a field -// takes where both could stand. Two aliases of one model each say more than the -// model, so they compose as any two aliases do, and the composition holds both -// bounds on the aliases it names: no node is minted for the bounds beside it. -func TestFold_AliasesOfOneModelComposeThoughTheirBoundsMeet(t *testing.T) { +// TestFold_AliasesOfOneModelComposeThoughTheirBoundsIntersect pins which node a +// field takes where both could be taken. Two aliases of one model each say more +// than the model, so they compose as any two aliases do, and the composition +// holds both bounds on the aliases it names: no node is minted for the bounds +// beside it. +func TestFold_AliasesOfOneModelComposeThoughTheirBoundsIntersect(t *testing.T) { t.Parallel() reg := composeRegistry() reg["type/min"] = &ir.Scalar{ID: "type/min", Base: &ir.TypeRef{Target: "type/B"}, Constraints: &ir.Constraints{MinProperties: new(int64(1))}} @@ -330,14 +342,20 @@ func TestFold_AliasesOfOneModelComposeThoughTheirBoundsMeet(t *testing.T) { assert.Empty(t, *recorded) } -// TestFold_AComposedFieldAdoptsOnlyANull pins what a composed field takes of the -// values its declarations write. A null follows the field's null admission. Any -// other value describes one conjunct, and nothing judges it against a model, so -// it is reported and kept rather than adopted as the whole field's, whichever -// declaration wrote it. -func TestFold_AComposedFieldAdoptsOnlyANull(t *testing.T) { +// TestFold_AComposedFieldAdoptsWhatItsCompositionAdmits pins what a composed +// field takes of the values its declarations write: a value every model it +// composes admits, a null where the field admits null, and nothing either +// model refuses, which is reported and kept, whichever declaration wrote it. +func TestFold_AComposedFieldAdoptsWhatItsCompositionAdmits(t *testing.T) { t.Parallel() - object := ir.Value{Kind: ir.ValueObject} + text := func(text string) ir.Value { return ir.Value{Kind: ir.ValueString, String: text} } + object := func(names ...string) ir.Value { + value := ir.Value{Kind: ir.ValueObject} + for _, name := range names { + value.Object = append(value.Object, ir.Field{Name: name, Value: text("s")}) + } + return value + } null := ir.Value{Kind: ir.ValueNull} for _, tc := range []struct { name string @@ -346,15 +364,23 @@ func TestFold_AComposedFieldAdoptsOnlyANull(t *testing.T) { nullable bool adopted bool }{ - {name: "an object the first declaration writes", at: 0, value: object}, - {name: "an object the second declaration writes", at: 1, value: object}, + {name: "an object both models admit, the first declaration writes", at: 0, value: object("y"), adopted: true}, + {name: "the same object, the second writes", at: 1, value: object("y"), adopted: true}, + {name: "an object missing what the inline model requires", at: 0, value: object()}, + {name: "an object whose member the component refuses", at: 1, value: object("x", "y")}, {name: "a null where the field admits null", at: 1, value: null, nullable: true, adopted: true}, {name: "a null where it does not", at: 0, value: null}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - stubbed, recorded := stubMerger(composeRegistry()) - decls := declsOf("type/A", "type/in1") + reg := composeRegistry() + maps.Copy(reg, narrowingRegistry()) + reg["type/typed"] = &ir.Model{ID: "type/typed", Provenance: ptrAt("/components/schemas/Typed"), + Properties: []ir.Property{{WireName: "x", Type: primitiveRef(ir.PrimitiveInteger)}}} + reg["type/typedIn1"] = &ir.Model{ID: "type/typedIn1", Anonymous: true, Provenance: ptrAt(declaredAt(1)), + Properties: []ir.Property{{WireName: "y", Type: primitiveRef(ir.PrimitiveString), Required: true}}} + stubbed, recorded := stubMerger(reg) + decls := declsOf("type/typed", "type/typedIn1") decls[0].property.Type.Nullable, decls[1].property.Type.Nullable = tc.nullable, tc.nullable decls[tc.at].property.Default = &tc.value @@ -368,8 +394,8 @@ func TestFold_AComposedFieldAdoptsOnlyANull(t *testing.T) { assert.Nil(t, got.Default) require.Len(t, *recorded, 1) assert.Equal(t, diag.DegradedConstruct, (*recorded)[0].Code) - assert.Contains(t, (*recorded)[0].Message, "admits the default the declaration at "+string(declaredAt(tc.at))+" gives") - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(tc.at))) + assert.Contains(t, (*recorded)[0].Message, "admits the default "+string(declaredAt(tc.at))+" gives") + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(tc.at))) }) } } @@ -392,10 +418,10 @@ func TestFold_ComposesOnlyTheDeclarationsItJudges(t *testing.T) { model, ok := reg[got.Type.Target].(*ir.Model) require.True(t, ok) assert.Empty(t, cmp.Diff([]ir.TypeID{"type/B", "type/A"}, targetsOf(model.Mixins)), - "the declaration past the bound composes nothing, and the last of one type stands for it") + "the declaration past the bound composes nothing, and the last of one type is the one it takes") require.Len(t, *recorded, 1) assert.Equal(t, diag.BudgetExceeded, (*recorded)[0].Code) - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(2))) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(2))) } // TestSelectBase_ChoosesAsTheRuleSays pins the rule both readers take: the only @@ -423,3 +449,37 @@ func TestSelectBase_ChoosesAsTheRuleSays(t *testing.T) { assert.Equal(t, tc.want, got, tc.name) } } + +// TestComposedParts_AConjunctOutOfDeclarationOrderIsAnError pins the +// assertion on the order composition hands its conjuncts in: one handed +// before a declaration it follows is an internal error noted at its own +// declaration, outside a dry run alone, and every conjunct is still a part, in +// the order handed. +func TestComposedParts_AConjunctOutOfDeclarationOrderIsAnError(t *testing.T) { + t.Parallel() + for _, dry := range []bool{false, true} { + stubbed, _ := stubMerger(narrowingRegistry()) + f := &fieldFold{g: &stubbed.Merger, decls: declsOf("type/a", "type/b"), fieldPointer: foldKey, notes: make([][]note, 2)} + b := builder{f: f, dry: dry} + conjuncts := []conjunct{ + {member{ref: ir.TypeRef{Target: "type/b"}, decl: 1}, &ir.Model{ID: "type/b"}}, + {member{ref: ir.TypeRef{Target: "type/a"}, decl: 0}, &ir.Model{ID: "type/a"}}, + } + + parts := b.composedParts(conjuncts) + + targets := make([]ir.TypeID, len(parts)) + for i, part := range parts { + targets[i] = part.target + } + assert.Equal(t, []ir.TypeID{"type/b", "type/a"}, targets, "dry %t", dry) + assert.Empty(t, f.notes[1], "dry %t", dry) + if dry { + assert.Empty(t, f.notes[0], "a dry run notes nothing") + continue + } + require.Len(t, f.notes[0], 1) + assert.Equal(t, diag.InternalInvariant, f.notes[0][0].code) + assert.Contains(t, f.notes[0][0].message, "after a later one") + } +} diff --git a/compilers/openapi/internal/merge/conflict_internal_test.go b/compilers/openapi/internal/merge/conflict_internal_test.go index 8322a6242..e21853dce 100644 --- a/compilers/openapi/internal/merge/conflict_internal_test.go +++ b/compilers/openapi/internal/merge/conflict_internal_test.go @@ -45,11 +45,25 @@ func TestKindOf_CyclicBaseChainTerminates(t *testing.T) { assert.False(t, ok, "a cyclic base chain terminates without resolving") } -func TestTypeJudge_IsAnyTypeDanglingTargetIsNotAny(t *testing.T) { +// TestKindOf_ReadsTheFirstEncodingThatEncodes pins the encoding a kind walk +// reads a primitive under: the nearest alias's whose Encoding names a scheme +// (ir.Encoding.Encodes), so one stating only a media type, which says what the +// value holds and not how it is written, leaves a farther alias's format in +// force, and the chain reads as the held format alone. +func TestKindOf_ReadsTheFirstEncodingThatEncodes(t *testing.T) { t.Parallel() - stubbed, _ := stubMerger(nil) - assert.False(t, judge(stubbed).isAnyType(ir.TypeRef{Target: "type/missing"}), - "an unresolvable target is not classified as the top type") + str := ir.TypeRef{Target: "type/primitive/string"} + formatted := ir.TypeRef{Target: "type/formatted"} + stubbed, _ := stubMerger(map[ir.TypeID]ir.TypeDef{ + "type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}, + "type/formatted": &ir.Scalar{ID: "type/formatted", Base: &str, Encoding: &ir.Encoding{Name: "time"}}, + "type/media": &ir.Scalar{ID: "type/media", Base: &formatted, Encoding: &ir.Encoding{MediaType: "text/plain"}}, + }) + for _, id := range []ir.TypeID{"type/formatted", "type/media"} { + kind, ok := judge(stubbed).kindOf(ir.TypeRef{Target: id}) + require.True(t, ok, "%s", id) + assert.Equal(t, valueKind{primitive: ir.PrimitiveString, format: "time"}, kind, "%s", id) + } } func TestClassify_AnUnresolvableTargetIsUnrelated(t *testing.T) { @@ -109,30 +123,27 @@ func TestLargerAndSmallerNumber_OrderMagnitudesAtAnyScale(t *testing.T) { require.NoError(t, err, "%q is a literal a schema may write", tc.b) for _, pair := range [][2]ir.BigVal{{a, b}, {b, a}} { - larger, ok := largerNumber(pair[0], pair[1]) - require.True(t, ok, "%s and %s have an order", pair[0], pair[1]) - assert.Equal(t, ir.BigVal(tc.larger), larger, "larger of %s and %s", pair[0], pair[1]) + require.True(t, IntersectsWithoutDisagreement(&ir.Constraints{Min: &pair[0]}, &ir.Constraints{Min: &pair[1]}), "%s and %s have an order", pair[0], pair[1]) + larger := Constraints(&ir.Constraints{Min: &pair[0]}, &ir.Constraints{Min: &pair[1]}).Min + assert.Equal(t, ir.BigVal(tc.larger), *larger, "larger of %s and %s", pair[0], pair[1]) - smaller, ok := smallerNumber(pair[0], pair[1]) - require.True(t, ok, "%s and %s have an order", pair[0], pair[1]) - assert.Equal(t, ir.BigVal(tc.smaller), smaller, "smaller of %s and %s", pair[0], pair[1]) + smaller := Constraints(&ir.Constraints{Max: &pair[0]}, &ir.Constraints{Max: &pair[1]}).Max + assert.Equal(t, ir.BigVal(tc.smaller), *smaller, "smaller of %s and %s", pair[0], pair[1]) } }) } } // TestLargerAndSmallerNumber_KeepTheFirstSpellingOfOneNumber pins that one number -// written twice meets to the first spelling, as a default written twice does: no +// written twice intersects to the first spelling, as a default written twice does: no // magnitude is decided by which came first. func TestLargerAndSmallerNumber_KeepTheFirstSpellingOfOneNumber(t *testing.T) { t.Parallel() - for _, meet := range []func(bigVal, irBigVal ir.BigVal) (ir.BigVal, bool){largerNumber, smallerNumber} { - got, ok := meet("10", "1e1") - require.True(t, ok) - assert.Equal(t, ir.BigVal("10"), got) - got, ok = meet("1e1", "10") - require.True(t, ok) - assert.Equal(t, ir.BigVal("1e1"), got) + for _, pair := range [][2]ir.BigVal{{"10", "1e1"}, {"1e1", "10"}} { + lower := Constraints(&ir.Constraints{Min: &pair[0]}, &ir.Constraints{Min: &pair[1]}) + assert.Equal(t, pair[0], *lower.Min) + upper := Constraints(&ir.Constraints{Max: &pair[0]}, &ir.Constraints{Max: &pair[1]}) + assert.Equal(t, pair[0], *upper.Max) } } @@ -228,7 +239,7 @@ func TestConstraints_AdoptsEveryUnsetKeyword(t *testing.T) { t.Parallel() // Every keyword ir.Constraints carries: dst leaves each one unset, so the // merge must adopt all of them from src, not just the ones exercised by - // the spec-driven table tests in the compiler package. + // the spec-driven table tests in the compiler package, writing neither. five, ten := int64(5), int64(10) minVal, maxVal, multipleOf := ir.BigVal("1"), ir.BigVal("9"), ir.BigVal("2") exclMin, exclMax := ir.BigVal("0"), ir.BigVal("10") @@ -250,29 +261,15 @@ func TestConstraints_AdoptsEveryUnsetKeyword(t *testing.T) { } merged := Constraints(&ir.Constraints{}, src) require.NotNil(t, merged) - assert.Same(t, src.Min, merged.Min) - assert.Same(t, src.ExclusiveMin, merged.ExclusiveMin) - assert.Same(t, src.Max, merged.Max) - assert.Same(t, src.ExclusiveMax, merged.ExclusiveMax) - assert.Same(t, src.MultipleOf, merged.MultipleOf) - assert.Same(t, src.Precision, merged.Precision) - assert.Same(t, src.Scale, merged.Scale) - assert.Same(t, src.MinLength, merged.MinLength) - assert.Same(t, src.MaxLength, merged.MaxLength) - assert.Equal(t, src.Pattern, merged.Pattern) - assert.Equal(t, src.PatternMessage, merged.PatternMessage) - assert.Same(t, src.MinItems, merged.MinItems) - assert.Same(t, src.MaxItems, merged.MaxItems) - assert.Equal(t, src.UniqueItems, merged.UniqueItems) - assert.Same(t, src.MinProperties, merged.MinProperties) - assert.Same(t, src.MaxProperties, merged.MaxProperties) + assert.Equal(t, src, merged, "every keyword is adopted") + assert.NotSame(t, src.Min, merged.Min, "an intersection shares no pointer with what it intersects") } func TestConstraints_ABoundTakesItsTighterValue(t *testing.T) { t.Parallel() // Under allOf every bound holds, so each keyword both sides set takes the - // value admitting fewer, whichever side wrote it. Both orders are folded, - // so a merge keeping one side would fail one of them. + // value admitting fewer, whichever side wrote it. Both orders are taken + // into one, so a merge keeping one side would fail one of them. loose := &ir.Constraints{ Min: new(ir.BigVal("1")), ExclusiveMin: new(ir.BigVal("2")), Max: new(ir.BigVal("9")), ExclusiveMax: new(ir.BigVal("8")), MinLength: new(int64(3)), MaxLength: new(int64(7)), MinItems: new(int64(3)), MaxItems: new(int64(7)), @@ -297,10 +294,10 @@ func TestConstraints_AKeywordWithNoOrderKeepsTheFirst(t *testing.T) { assert.Equal(t, a, Constraints(&merged, b)) } -func TestConstraints_APairWithNoMeetKeepsTheFirst(t *testing.T) { +func TestConstraints_APairWithNoIntersectionKeepsTheFirst(t *testing.T) { t.Parallel() // A pair no one value states is reported by constraintsConflict, and the - // field keeps the first of it: a failed meet writes nothing, since what it + // field keeps the first of it: a failed intersect writes nothing, since what it // returns is no value. a := &ir.Constraints{MultipleOf: new(ir.BigVal("3")), Min: new(ir.BigVal("1"))} b := &ir.Constraints{MultipleOf: new(ir.BigVal("nan")), Min: new(ir.BigVal("nan"))} @@ -333,8 +330,9 @@ func TestConstraintsConflict_DeterministicKeywordOrder(t *testing.T) { // TestClassify_ALiteralOverlapsWhatHoldsValues pins that a literal against a // type with a primitive kind no held format narrows is an overlap, never -// silent, while a literal against another of a different value, or a scalar -// literal against a structure, conflicts, and a dangling target stays silent. +// reported as nothing, while a literal against another of a different value, or +// a scalar literal against a structure, conflicts, and a dangling target is +// reported as nothing. func TestClassify_ALiteralOverlapsWhatHoldsValues(t *testing.T) { t.Parallel() stubbed, _ := stubMerger(judgeRegistry()) @@ -347,13 +345,14 @@ func TestClassify_ALiteralOverlapsWhatHoldsValues(t *testing.T) { assert.Equal(t, relUnrelated, judge(stubbed).relate(ref("type/primitive/string"), ref("type/absent"))) } -// TestMeets_ANoOrderPairIsNoMeet pins what Meets asks of constraintsConflict: two -// ordered bounds always meet, and two values of a keyword with no order meet only +// TestIntersectsWithoutDisagreement_ANoOrderPairDisagrees pins what +// IntersectsWithoutDisagreement asks of constraintsConflict: two ordered bounds +// always intersect, and two values of a keyword with no order intersect only // where they are one. -func TestMeets_ANoOrderPairIsNoMeet(t *testing.T) { +func TestIntersectsWithoutDisagreement_ANoOrderPairDisagrees(t *testing.T) { t.Parallel() - assert.True(t, Meets(&ir.Constraints{MaxLength: new(int64(3))}, &ir.Constraints{MaxLength: new(int64(5))})) - assert.True(t, Meets(&ir.Constraints{Pattern: "a"}, &ir.Constraints{Pattern: "a"})) - assert.False(t, Meets(&ir.Constraints{Pattern: "a"}, &ir.Constraints{Pattern: "b"})) - assert.True(t, Meets(nil, &ir.Constraints{Pattern: "b"}), "nothing conflicts with nothing") + assert.True(t, IntersectsWithoutDisagreement(&ir.Constraints{MaxLength: new(int64(3))}, &ir.Constraints{MaxLength: new(int64(5))})) + assert.True(t, IntersectsWithoutDisagreement(&ir.Constraints{Pattern: "a"}, &ir.Constraints{Pattern: "a"})) + assert.False(t, IntersectsWithoutDisagreement(&ir.Constraints{Pattern: "a"}, &ir.Constraints{Pattern: "b"})) + assert.True(t, IntersectsWithoutDisagreement(nil, &ir.Constraints{Pattern: "b"}), "nothing conflicts with nothing") } diff --git a/compilers/openapi/internal/merge/constraints.go b/compilers/openapi/internal/merge/constraints.go index 8dc81da31..fcb4b6a7b 100644 --- a/compilers/openapi/internal/merge/constraints.go +++ b/compilers/openapi/internal/merge/constraints.go @@ -4,21 +4,15 @@ package merge import ( - "cmp" "fmt" "github.com/dexpace/morphic/ir" ) -// Constraints folds src's constraint keywords into dst under allOf -// intersection semantics: each keyword takes the value that says what both -// sides say (constraintKeyword.meet), so a keyword only one side sets is adopted -// and a bound both set takes the tighter value. -// -// The four numeric bounds are separate keywords, so each meets on its own: an -// entry declaring only exclusiveMinimum contributes it beside a minimum from -// elsewhere, and both apply. UniqueItems has no absent state, but under -// intersection a true from either side always holds. +// Constraints returns dst and src intersected as ir.ConstraintIntersection +// intersects them, a keyword no one value states keeping dst's. A nil side +// says nothing, so the other is returned as it is; two that intersect in +// nothing give an empty set. Neither is written. func Constraints(dst, src *ir.Constraints) *ir.Constraints { if dst == nil { return src @@ -26,200 +20,78 @@ func Constraints(dst, src *ir.Constraints) *ir.Constraints { if src == nil { return dst } - for _, kw := range constraintKeywords { - kw.meet(dst, src) + if intersected := ir.ConstraintIntersectionOf(dst).Intersect(ir.ConstraintIntersectionOf(src)).ConstraintsKeepingReceiverOnDisagreement(); intersected != nil { + return intersected } - dst.UniqueItems = dst.UniqueItems || src.UniqueItems - return dst + return &ir.Constraints{} } -// constraintKeyword is one constraint keyword the merge folds across -// declarations. -type constraintKeyword struct { - // set reports whether a constraint set states the keyword. - set func(constraints *ir.Constraints) bool - // same reports whether two sets say one thing of it: neither states it, or - // both state one value. - same func(a, b *ir.Constraints) bool - // meet writes to dst the value saying what dst and src say, and leaves dst's - // where no one value does. - meet func(dst, src *ir.Constraints) - // differ describes two sets no one value holds, as "conflicting pattern - // ("a" and "b")". - differ func(a, b *ir.Constraints) (string, bool) - // clear removes the keyword from a set. - clear func(constraints *ir.Constraints) -} - -// constraintKeywords lists the keywords the merge folds, in the fixed order -// constraintsConflict tries them, so the one named when several conflict is -// deterministic. A bound takes its tighter value, a step the common multiple of -// both (commonStep), and a keyword with no order keeps one value and conflicts -// with any other. UniqueItems is absent: a plain bool cannot tell false from -// unset, and under intersection a true from either side always holds. It is -// built once, as every judgment of two nodes' bounds reads it several times. -var constraintKeywords = []constraintKeyword{ - numberKeyword("minimum", func(constraints *ir.Constraints) **ir.BigVal { return &constraints.Min }, largerNumber), - numberKeyword("exclusiveMinimum", func(constraints *ir.Constraints) **ir.BigVal { return &constraints.ExclusiveMin }, largerNumber), - numberKeyword("maximum", func(constraints *ir.Constraints) **ir.BigVal { return &constraints.Max }, smallerNumber), - numberKeyword("exclusiveMaximum", func(constraints *ir.Constraints) **ir.BigVal { return &constraints.ExclusiveMax }, smallerNumber), - numberKeyword("multipleOf", func(constraints *ir.Constraints) **ir.BigVal { return &constraints.MultipleOf }, commonStep), - intKeyword("precision", func(constraints *ir.Constraints) **int64 { return &constraints.Precision }, onlyEqual), - intKeyword("scale", func(constraints *ir.Constraints) **int64 { return &constraints.Scale }, onlyEqual), - intKeyword("minLength", func(constraints *ir.Constraints) **int64 { return &constraints.MinLength }, largerCount), - intKeyword("maxLength", func(constraints *ir.Constraints) **int64 { return &constraints.MaxLength }, smallerCount), - intKeyword("minItems", func(constraints *ir.Constraints) **int64 { return &constraints.MinItems }, largerCount), - intKeyword("maxItems", func(constraints *ir.Constraints) **int64 { return &constraints.MaxItems }, smallerCount), - intKeyword("minProperties", func(constraints *ir.Constraints) **int64 { return &constraints.MinProperties }, largerCount), - intKeyword("maxProperties", func(constraints *ir.Constraints) **int64 { return &constraints.MaxProperties }, smallerCount), - stringKeyword("pattern", func(constraints *ir.Constraints) *string { return &constraints.Pattern }), - stringKeyword("patternMessage", func(constraints *ir.Constraints) *string { return &constraints.PatternMessage }), -} - -// numberKeyword is the arbitrary-precision keyword name, stored at slot, which -// meet folds. Two spellings of one number are one value (sameNumber). -func numberKeyword(name string, slot func(*ir.Constraints) **ir.BigVal, meet func(bigVal, irBigVal ir.BigVal) (ir.BigVal, bool)) constraintKeyword { - return slotKeyword(name, slot, sameNumber, meet) -} - -// intKeyword is the integer keyword name, stored at slot, which meet folds. -func intKeyword(name string, slot func(*ir.Constraints) **int64, meet func(x, y int64) (int64, bool)) constraintKeyword { - return slotKeyword(name, slot, func(x, y int64) bool { return x == y }, meet) -} - -// slotKeyword is the keyword name stored as a pointer at slot, nil where unset. -// same says whether two values are one, and meet returns the value saying what -// two say, and false where no one value does. -func slotKeyword[T any](name string, slot func(*ir.Constraints) **T, same func(x, y T) bool, meet func(x, y T) (T, bool)) constraintKeyword { - return constraintKeyword{ - set: func(constraints *ir.Constraints) bool { return *slot(constraints) != nil }, - same: func(a, b *ir.Constraints) bool { - x, y := *slot(a), *slot(b) - if x == nil || y == nil { - return x == y - } - return same(*x, *y) - }, - meet: func(dst, src *ir.Constraints) { - x, y := *slot(dst), *slot(src) - if x == nil { - *slot(dst) = y - return - } - if y == nil { - return - } - if met, ok := meet(*x, *y); ok { - *slot(dst) = &met - } - }, - differ: func(a, b *ir.Constraints) (string, bool) { - x, y := *slot(a), *slot(b) - if x == nil || y == nil { - return "", false - } - if _, ok := meet(*x, *y); ok { - return "", false - } - return fmt.Sprintf("conflicting %s (%v and %v)", name, *x, *y), true - }, - clear: func(constraints *ir.Constraints) { *slot(constraints) = nil }, +// SameConstraints reports whether a and b say one thing of every keyword +// (sameBounds); nil is the same as nil alone. +func SameConstraints(a, b *ir.Constraints) bool { + if a == nil || b == nil { + return a == b } + return sameBounds(a, b) } -// stringKeyword is the string keyword name, stored at slot, "" where unset. Two -// values of it have no order and no form saying both, so it keeps the first. -func stringKeyword(name string, slot func(*ir.Constraints) *string) constraintKeyword { - return constraintKeyword{ - set: func(constraints *ir.Constraints) bool { return *slot(constraints) != "" }, - same: func(a, b *ir.Constraints) bool { return *slot(a) == *slot(b) }, - meet: func(dst, src *ir.Constraints) { *slot(dst) = cmp.Or(*slot(dst), *slot(src)) }, - differ: func(a, b *ir.Constraints) (string, bool) { - x, y := *slot(a), *slot(b) - if x == "" || y == "" || x == y { - return "", false - } - return fmt.Sprintf("conflicting %s (%q and %q)", name, x, y), true - }, - clear: func(constraints *ir.Constraints) { *slot(constraints) = "" }, - } +// IntersectsWithoutDisagreement reports whether one set of constraints says +// what a and b both do: no keyword both give values no one value of it states +// (constraintsConflict), so Constraints folds them losing nothing. +func IntersectsWithoutDisagreement(a, b *ir.Constraints) bool { + return len(disagreeingKeywords(a, b)) == 0 } -// Meets reports whether one set of constraints says what a and b both do: no -// keyword both pin to values no one value holds (constraintsConflict), so -// Constraints folds them losing nothing. -func Meets(a, b *ir.Constraints) bool { - _, _, conflict := constraintsConflict(a, b) - return !conflict +// disagreeingKeywords returns the keywords a and b give values no one value of +// the keyword states, in ir.ConstraintKeyword order. +func disagreeingKeywords(a, b *ir.Constraints) []ir.ConstraintKeyword { + return ir.ConstraintIntersectionOf(a).Intersect(ir.ConstraintIntersectionOf(b)).DisagreeingKeywords() } -// constraintsConflict reports the first keyword of constraintKeywords that two -// constraint sets pin to values no one value holds: its index and the -// disagreement. A keyword set on one side only is no conflict, and neither is a -// bound both set, since Constraints takes what holds both. -func constraintsConflict(a, b *ir.Constraints) (keyword int, detail string, conflict bool) { - if a == nil || b == nil { +// constraintsConflict reports the first keyword, in ir.ConstraintKeyword +// order, that two constraint sets pin to values no one value holds, and the +// disagreement (keywordDifference). A keyword set on one side only is no +// conflict, and neither is a bound both set, since Constraints takes what +// holds both. +func constraintsConflict(a, b *ir.Constraints) (keyword ir.ConstraintKeyword, detail string, conflict bool) { + conflicting := disagreeingKeywords(a, b) + if len(conflicting) == 0 { return 0, "", false } - for i, kw := range constraintKeywords { - if detail, conflict := kw.differ(a, b); conflict { - return i, detail, true - } - } - return 0, "", false -} - -// largerCount returns the larger of x and y. -func largerCount(x, y int64) (int64, bool) { return max(x, y), true } - -// smallerCount returns the smaller of x and y. -func smallerCount(x, y int64) (int64, bool) { return min(x, y), true } - -// onlyEqual returns x where y is the same, and false otherwise: a keyword with -// no order. -func onlyEqual(x, y int64) (int64, bool) { return x, x == y } - -// largerNumber returns the larger of bigVal and irBigVal, and false where they -// have no order (compareNumbers). It keeps bigVal's spelling of one number -// written twice. -func largerNumber(bigVal, irBigVal ir.BigVal) (ir.BigVal, bool) { - order, ok := compareNumbers(bigVal, irBigVal) - if order < 0 { - return irBigVal, ok - } - return bigVal, ok + return conflicting[0], keywordDifference(conflicting[0], a, b), true } -// smallerNumber returns the smaller of bigVal and irBigVal, and false where -// they have no order (compareNumbers). It keeps bigVal's spelling of one number -// written twice. -func smallerNumber(bigVal, irBigVal ir.BigVal) (ir.BigVal, bool) { - order, ok := compareNumbers(bigVal, irBigVal) - if order > 0 { - return irBigVal, ok +// keywordDifference describes two sets pinning keyword to values no one value +// holds, as "conflicting pattern ("a" and "b")": a number or a count as +// written, a text quoted. +func keywordDifference(keyword ir.ConstraintKeyword, a, b *ir.Constraints) string { + name := keywordName(keyword) + first, isText := a.KeywordText(keyword) + second, _ := b.KeywordText(keyword) + if isText { + return fmt.Sprintf("conflicting %s (%q and %q)", name, first, second) } - return bigVal, ok + return fmt.Sprintf("conflicting %s (%s and %s)", name, first, second) } -// compareNumbers orders a and b by magnitude, and returns false where either is -// a literal no Decimal holds, unless they are one text. Reading such a literal -// as zero would fold two bounds into one the source never wrote. -func compareNumbers(a, b ir.BigVal) (int, bool) { - if a == b { - return 0, true - } - da, errA := a.Decimal() - db, errB := b.Decimal() - if errA != nil || errB != nil { - return 0, false +// keywordName returns the name a report gives keyword, the JSON Schema +// keyword it lowers from, and "keyword N" for a value no constant names. +func keywordName(keyword ir.ConstraintKeyword) string { + switch keyword { + case ir.ConstraintKeywordMin: + return "minimum" + case ir.ConstraintKeywordExclusiveMin: + return "exclusiveMinimum" + case ir.ConstraintKeywordMax: + return "maximum" + case ir.ConstraintKeywordExclusiveMax: + return "exclusiveMaximum" + case ir.ConstraintKeywordMultipleOf, ir.ConstraintKeywordPrecision, ir.ConstraintKeywordScale, + ir.ConstraintKeywordMinLength, ir.ConstraintKeywordMaxLength, ir.ConstraintKeywordMinItems, + ir.ConstraintKeywordMaxItems, ir.ConstraintKeywordMinProperties, ir.ConstraintKeywordMaxProperties, + ir.ConstraintKeywordPattern, ir.ConstraintKeywordPatternMessage: + return keyword.String() + default: + return fmt.Sprintf("keyword %d", keyword) } - return da.Cmp(db), true -} - -// sameNumber reports whether a and b denote the same value, so one magnitude -// spelled two ways, 10, 10.0 and 1e1, is one value. A pair with a literal no -// Decimal holds is judged by its text alone. -func sameNumber(a, b ir.BigVal) bool { - order, ok := compareNumbers(a, b) - return ok && order == 0 } diff --git a/compilers/openapi/internal/merge/constraints_internal_test.go b/compilers/openapi/internal/merge/constraints_internal_test.go index 72aa5b6e4..3814243fd 100644 --- a/compilers/openapi/internal/merge/constraints_internal_test.go +++ b/compilers/openapi/internal/merge/constraints_internal_test.go @@ -30,7 +30,7 @@ func TestMerger_MergeConstraintsKeepsBothSidesBounds(t *testing.T) { // TestConstraintsConflict_ComparesByMagnitude pins the comparison every // arbitrary-precision keyword goes through. Equal magnitudes spelled differently // are one value, so reporting them would invent a disagreement the source never -// wrote. Two numbers that have an order meet, and a literal no Decimal holds has +// wrote. Two numbers that have an order intersect, and a literal no Decimal holds has // none, so the merge keeps one and reports the other. func TestConstraintsConflict_ComparesByMagnitude(t *testing.T) { t.Parallel() @@ -64,12 +64,12 @@ func TestConstraintsConflict_ComparesByMagnitude(t *testing.T) { } // TestSameNumber_SeparatesOneValueFromTwo pins what the allOf redeclaration -// merge asks of this comparison: one value written two ways stays one value at +// merge asks of ir.SameKeywordValue: one value written two ways stays one value at // any magnitude, and two values stay two. // // The rows past a rational's range carry the test, since math/big will not // build 1e1000001. A pair outside the decimal grammar is judged by its text -// alone: identical text is one literal, and differing text is never folded into +// alone: identical text is one literal, and differing text is never taken into // one value. Both directions are asserted, so an answer right one way round is // not mistaken for a comparison. func TestSameNumber_SeparatesOneValueFromTwo(t *testing.T) { @@ -81,7 +81,7 @@ func TestSameNumber_SeparatesOneValueFromTwo(t *testing.T) { want bool }{ {name: "one literal against itself", a: "1e1000001", b: "1e1000001", want: true}, - {name: "an exponent against the digits it stands for", a: "1e2", b: "100", want: true}, + {name: "an exponent against the digits it spells", a: "1e2", b: "100", want: true}, {name: "a digit the exponent moved, past a rational", a: "1e1000001", b: "10e1000000", want: true}, {name: "a magnitude too small for a rational", a: "1e-1000001", b: "10e-1000002", want: true}, {name: "zero however it is written", a: "0", b: "-0.0", want: true}, @@ -100,8 +100,51 @@ func TestSameNumber_SeparatesOneValueFromTwo(t *testing.T) { _, errB := tc.b.Decimal() require.Equal(t, tc.outside, errA != nil || errB != nil, "the row says whether a literal is outside the grammar") - assert.Equal(t, tc.want, sameNumber(tc.a, tc.b), "%s against %s", tc.a, tc.b) - assert.Equal(t, tc.want, sameNumber(tc.b, tc.a), "%s against %s", tc.b, tc.a) + a, b := &ir.Constraints{Min: &tc.a}, &ir.Constraints{Min: &tc.b} + assert.Equal(t, tc.want, ir.SameKeywordValue(a, b, ir.ConstraintKeywordMin), "%s against %s", tc.a, tc.b) + assert.Equal(t, tc.want, ir.SameKeywordValue(b, a, ir.ConstraintKeywordMin), "%s against %s", tc.b, tc.a) }) } } + +// TestKeywordName_NamesEachKeywordByTheOneItLowersFrom holds the name a +// report gives each keyword ir.ConstraintKeywords yields to the JSON Schema +// keyword it lowers from, so a keyword ir adds is not reported unnamed, and +// names the zero value, which no keyword is, by its number. +func TestKeywordName_NamesEachKeywordByTheOneItLowersFrom(t *testing.T) { + t.Parallel() + var names []string + for keyword := range ir.ConstraintKeywords() { + names = append(names, keywordName(keyword)) + } + assert.Equal(t, []string{ + "minimum", "exclusiveMinimum", "maximum", "exclusiveMaximum", "multipleOf", "precision", "scale", + "minLength", "maxLength", "minItems", "maxItems", "minProperties", "maxProperties", "pattern", "patternMessage", + }, names) + assert.Equal(t, "keyword 0", keywordName(0), "the zero value, which names no keyword") +} + +// TestSameConstraints_SaysOneThingOfEveryKeyword pins SameConstraints: two +// sets saying one value of every keyword, two spellings of one number +// included, are the same; a value one sets and the other does not, a +// different value, or a uniqueItems one holds are not, and nil is the same as +// nil alone. +func TestSameConstraints_SaysOneThingOfEveryKeyword(t *testing.T) { + t.Parallel() + forty, fortyPointZero, fortyOne := ir.BigVal("40"), ir.BigVal("40.0"), ir.BigVal("41") + for name, tc := range map[string]struct { + a, b *ir.Constraints + same bool + }{ + "both nil": {nil, nil, true}, + "one nil": {&ir.Constraints{}, nil, false}, + "one number, two ways": {&ir.Constraints{Min: &forty}, &ir.Constraints{Min: &fortyPointZero}, true}, + "two numbers": {&ir.Constraints{Min: &forty}, &ir.Constraints{Min: &fortyOne}, false}, + "set on one side": {&ir.Constraints{Min: &forty}, &ir.Constraints{}, false}, + "two patterns": {&ir.Constraints{Pattern: "a"}, &ir.Constraints{Pattern: "b"}, false}, + "uniqueItems on one": {&ir.Constraints{UniqueItems: true}, &ir.Constraints{}, false}, + "alike": {&ir.Constraints{MaxLength: new(int64(3)), Pattern: "a"}, &ir.Constraints{MaxLength: new(int64(3)), Pattern: "a"}, true}, + } { + assert.Equal(t, tc.same, SameConstraints(tc.a, tc.b), name) + } +} diff --git a/compilers/openapi/internal/merge/cycle.go b/compilers/openapi/internal/merge/cycle.go new file mode 100644 index 000000000..1b7dbab7d --- /dev/null +++ b/compilers/openapi/internal/merge/cycle.go @@ -0,0 +1,193 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "cmp" + "encoding/json/jsontext" + "maps" + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// SettleCompositionCycle settles the members of a cyclic composition component +// as one unit: one fold per wire name over every member's declarations, own and +// carried, each member taking its result. tables holds the settled table of +// each type a member composes outside the component. It returns each member's +// table. +// +// merger is built for the member of least type ID, and a fold mints at that +// member's carried form, /allOf/properties/ (composedMember): one +// model belongs to one component. +func SettleCompositionCycle(cycleModels []*ModelPropertyDeclarations, merger Merger, + tables map[ir.TypeID]RedeclaredWireNameTable, shared map[string]bool, +) ([]ir.Diagnostic, map[ir.TypeID]RedeclaredWireNameTable) { + cycleModels = slices.SortedFunc(slices.Values(cycleModels), func(a, b *ModelPropertyDeclarations) int { return cmp.Compare(a.m.ID, b.m.ID) }) + inCycle := make(map[ir.TypeID]bool, len(cycleModels)) + for _, member := range cycleModels { + inCycle[member.m.ID] = true + } + entryDeclarations, inherited, diags := cycleEntryDeclarations(cycleModels, merger, tables, inCycle) + own := cycleOwnDeclarations(cycleModels) + for _, wire := range slices.Sorted(maps.Keys(own)) { + diags = append(diags, settleAcross(cycleModels, merger, slices.Concat(own[wire], entryDeclarations[wire]))...) + delete(entryDeclarations, wire) + } + for _, wire := range slices.Sorted(maps.Keys(entryDeclarations)) { + diags = append(diags, settleAcross(cycleModels, merger, entryDeclarations[wire])...) + } + return diags, cycleTables(cycleModels, own, inherited, shared) +} + +// cycleEntryDeclarations returns, by wire name, the declarations the parts of +// the component's members outside it bring, each carried once through the +// entry naming its part, and the one declaration each name its parts leave one +// of. A part outside the component bringing a member's declaration is an +// internal error, since a part composing a member is in the component. +func cycleEntryDeclarations(cycleModels []*ModelPropertyDeclarations, merger Merger, tables map[ir.TypeID]RedeclaredWireNameTable, + inCycle map[ir.TypeID]bool, +) (map[string][]declaration, RedeclaredWireNameTable, []ir.Diagnostic) { + type entryCandidate struct { + candidate + parts []composedEntry + } + byWire := map[string][]entryCandidate{} + var diags []ir.Diagnostic + for _, member := range cycleModels { + parts := member.parts() + for i, part := range parts { + for _, wire := range slices.Sorted(maps.Keys(tables[part.target])) { + declared := tables[part.target][wire] + if inCycle[declared.Owner] { + diags = append(diags, diag.Newf(ir.SeverityError, diag.InternalInvariant, merger.Doc.At(part.at), + "internal: %s, outside a cycle of compositions, brings %q as %s declares it, a model of the cycle", part.target, + wire, declared.Owner)) + continue + } + byWire[wire] = append(byWire[wire], entryCandidate{decl: declared, part: i, parts: parts}) + } + } + } + out, inherited := map[string][]declaration{}, RedeclaredWireNameTable{} + for _, wire := range slices.Sorted(maps.Keys(byWire)) { + candidates := make([]candidate, len(byWire[wire])) + for i, brought := range byWire[wire] { + candidates[i] = brought.candidate + candidates[i].listed = i + } + left := candidatesNotReadElsewhere(merger.Walk, candidates) + for _, left := range left { + from := byWire[wire][left.listed] + out[wire] = append(out[wire], declarationFromEntry(left.decl, &from.parts[from.part])) + } + if len(left) == 1 { + inherited[wire] = left[0].decl + } + } + return out, inherited, diags +} + +// cycleOwnDeclarations returns, by wire name, every declaration the component's +// members make themselves, the first of each member's read off its model, each +// naming the member as its owner. +func cycleOwnDeclarations(cycleModels []*ModelPropertyDeclarations) map[string][]declaration { + out := map[string][]declaration{} + for _, member := range cycleModels { + for _, field := range member.byWire { + decls := slices.Clone(field.decls) + decls[0].property = member.m.Properties[field.pos] + for i := range decls { + decls[i].owner = member.m.ID + } + wire := decls[0].property.WireName + out[wire] = append(out[wire], decls...) + } + } + return out +} + +// settleAcross folds decls, every declaration of one wire name the component +// holds, where at least two are, in one flat fold in the order they are +// written, every member taking the result at an identity of its own +// (adoptSettled) and each report listing every member's field as decided. +func settleAcross(cycleModels []*ModelPropertyDeclarations, merger Merger, decls []declaration) []ir.Diagnostic { + if len(decls) < 2 { + return nil + } + written := inWrittenOrder(&merger, decls) + wire := written[0].property.WireName + fieldPointer := composedMember(merger.IDs, cycleModels[0].m, wire) + merged, valueWrittenAt, diags := merger.foldAt(written, fieldPointer, assembledFrom(written)) + merger.discardDropped(written, merged) + assembled, typeSites := assembledFrom(written), merger.typeSites(merged, written) + for _, member := range cycleModels { + id := member.adoptSettled(merger, merged, assembled) + member.typeAt[wire], member.valueWrittenAt[wire] = typeSites, valueWrittenAt + diags = deciding(diags, id, member.m.Provenance) + } + return diags +} + +// inWrittenOrder returns decls in the order they are written (writtenOrder). +func inWrittenOrder(merger *Merger, decls []declaration) []declaration { + out := make([]declaration, len(decls)) + for i, at := range writtenOrder(merger, decls) { + out[i] = decls[at] + } + return out +} + +// adoptSettled places merged, the member a component's fold settled, on the +// model at the identity its own declarations give it, and returns that +// identity. +func (idx *ModelPropertyDeclarations) adoptSettled(merger Merger, merged ir.Property, assembled []jsontext.Pointer) ir.PropertyID { + wire := merged.WireName + pos := -1 + var own []declaration + if field, declares := idx.byWire[wire]; declares { + pos, own = field.pos, field.decls + } + inferred := merged.Provenance.Inferred + var chosenIdentity ir.Property + if len(own) > 0 { + judged, _ := judgedFirst(&merger, own) + chosenIdentity = identityDeclaration(judged).property + } + if len(own) > 0 && idx.heldAlone(merger, chosenIdentity) { + merged.ID, merged.Provenance = chosenIdentity.ID, chosenIdentity.Provenance + } else { + fieldPointer := composedMember(merger.IDs, idx.m, wire) + merged.ID, merged.Provenance = merger.IDs.ComposedProperty(fieldPointer), merger.Doc.At(fieldPointer, assembled...) + } + merged.Provenance.Inferred = inferred + if i := slices.Index(idx.m.Requires, wire); i >= 0 { + idx.m.Requires = slices.Delete(idx.m.Requires, i, i+1) + merged.Required = true + } + idx.place(pos, merged) + return merged.ID +} + +// cycleTables returns each member's table once the component settled: every +// shared name a member declares, at its own, and every other the component +// holds one declaration of, the one a member declares or a part brings. +func cycleTables(cycleModels []*ModelPropertyDeclarations, own map[string][]declaration, inherited RedeclaredWireNameTable, + shared map[string]bool, +) map[ir.TypeID]RedeclaredWireNameTable { + single := maps.Clone(inherited) + for _, member := range cycleModels { + for wire, decls := range own { + if field, declares := member.byWire[wire]; declares && len(decls) == 1 && shared[wire] { + single[wire] = DeclaredAt(ir.PropertyDecl{Owner: member.m.ID, Property: &member.m.Properties[field.pos]}) + } + } + } + out := make(map[ir.TypeID]RedeclaredWireNameTable, len(cycleModels)) + for _, member := range cycleModels { + out[member.m.ID] = member.members(shared, single) + } + return out +} diff --git a/compilers/openapi/internal/merge/cycle_internal_test.go b/compilers/openapi/internal/merge/cycle_internal_test.go new file mode 100644 index 000000000..07d556cc3 --- /dev/null +++ b/compilers/openapi/internal/merge/cycle_internal_test.go @@ -0,0 +1,440 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "fmt" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// cycleMember is one model of a composition cycle: its name, the model its +// Base composes, and its own declaration of id. +type cycleMember struct { + name, next string + target ir.TypeID + bounds *ir.Constraints +} + +// cycleOf builds each member in reg as compose does, composing next as its +// allOf entry 0 and declaring id at //properties/id, and returns their +// declarations in the order given. +func cycleOf(reg ir.TypeRegistry, members ...cycleMember) []*ModelPropertyDeclarations { + out := make([]*ModelPropertyDeclarations, 0, len(members)) + for _, member := range members { + id := ir.TypeID("type/" + member.name) + model := &ir.Model{ID: id, Base: &ir.TypeRef{Target: ir.TypeID("type/" + member.next)}, Provenance: ptrAt(jsontext.Pointer("/" + member.name))} + reg[id] = model + idx := NewModelPropertyDeclarations(model) + idx.Compose(model.Base.Target, jsontext.Pointer("/"+member.name+"/allOf/0")) + property := declared("id", member.target, "/"+member.name+"/properties/id") + property.Constraints = member.bounds + idx.MergeProperty(property, written(`{"own":true}`), "") + out = append(out, idx) + } + return out +} + +// cycleRegistry holds the primitives a cycle's members declare id as. +func cycleRegistry() ir.TypeRegistry { + return ir.TypeRegistry{ + "type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}, + "type/primitive/integer": &ir.Primitive{ID: "type/primitive/integer", PrimitiveKind: ir.PrimitiveInteger}, + } +} + +// settleCycle settles members as one component through a stub Merger over +// reg, every name shared, and returns what it reports and its tables. +func settleCycle(reg ir.TypeRegistry, members []*ModelPropertyDeclarations) ([]ir.Diagnostic, map[ir.TypeID]RedeclaredWireNameTable) { + stubbed, _ := stubMerger(reg) + return SettleCompositionCycle(members, stubbed.Merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{"id": true}) +} + +// idOf returns the member id the model id declares. +func idOf(t *testing.T, reg ir.TypeRegistry, id ir.TypeID) ir.Property { + t.Helper() + model, ok := reg[id].(*ir.Model) + require.True(t, ok, "%s is a model", id) + for _, property := range model.Properties { + if property.WireName == "id" { + return property + } + } + require.Failf(t, "no member", "%s declares no id", id) + return ir.Property{} +} + +// decidedBy returns the nodes a report names as decided. +func decidedBy(diagnostic ir.Diagnostic) []string { + var out []string + for _, related := range diagnostic.Related { + if related.Role == ir.RelatedDecided { + out = append(out, related.Provenance.Node) + } + } + return out +} + +// TestSettleCompositionCycle_EveryMemberTakesTheLastDeclarationsType pins a +// two-model cycle redeclaring id apart: one fold over both declarations, both +// models taking the type of the one written last, whichever order the members +// are handed in and whichever model declares it, and one report, naming each +// model's member as decided. +func TestSettleCompositionCycle_EveryMemberTakesTheLastDeclarationsType(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + first, second ir.TypeID // what A and B declare id as + }{ + "A an integer, B a string": {"type/primitive/integer", "type/primitive/string"}, + "A a string, B an integer": {"type/primitive/string", "type/primitive/integer"}, + } { + for _, swap := range []bool{false, true} { + reg := cycleRegistry() + members := cycleOf(reg, cycleMember{name: "A", next: "B", target: tc.first}, cycleMember{name: "B", next: "A", target: tc.second}) + if swap { + slices.Reverse(members) + } + at := fmt.Sprintf("%s, handed in reversed %v", name, swap) + + diags, tables := settleCycle(reg, members) + + a, b := idOf(t, reg, "type/A"), idOf(t, reg, "type/B") + assert.Equal(t, tc.second, a.Type.Target, "%s: A takes B's, written last", at) + assert.Equal(t, tc.second, b.Type.Target, "%s: B keeps its own", at) + var conflicts []ir.Diagnostic + for _, diagnostic := range diags { + if diagnostic.Code == diag.ConflictingRedecl { + conflicts = append(conflicts, diagnostic) + } + } + require.Len(t, conflicts, 1, "%s: said once: %+v", at, diags) + assert.ElementsMatch(t, []string{string(a.ID), string(b.ID)}, decidedBy(conflicts[0]), at) + assert.Contains(t, tables, ir.TypeID("type/A"), at) + assert.Contains(t, tables, ir.TypeID("type/B"), at) + } + } +} + +// TestSettleCompositionCycle_AThreeModelCycleSettlesToItsFixpoint pins the +// fixpoint where the base settled one model short: A, B and C composing one +// another in a ring, declaring a minimum of 1, a maximum of 9 and a minimum of 3, +// each take {3, 9} under both namings, with nothing reported. +func TestSettleCompositionCycle_AThreeModelCycleSettlesToItsFixpoint(t *testing.T) { + t.Parallel() + integer := ir.TypeID("type/primitive/integer") + bound := func(minimum, maximum string) *ir.Constraints { + out := &ir.Constraints{} + if minimum != "" { + out.Min = new(ir.BigVal(minimum)) + } + if maximum != "" { + out.Max = new(ir.BigVal(maximum)) + } + return out + } + for name, members := range map[string][]cycleMember{ + "named A, B, C": { + {"A", "B", integer, bound("1", "")}, {"B", "C", integer, bound("", "9")}, {"C", "A", integer, bound("3", "")}, + }, + "rotated": { + {"B", "C", integer, bound("1", "")}, {"C", "A", integer, bound("", "9")}, {"A", "B", integer, bound("3", "")}, + }, + } { + reg := cycleRegistry() + + diags, _ := settleCycle(reg, cycleOf(reg, members...)) + + assert.Empty(t, diags, name) + for _, id := range []ir.TypeID{"type/A", "type/B", "type/C"} { + got := idOf(t, reg, id).Constraints + require.NotNil(t, got, "%s: %s", name, id) + assert.True(t, sameBounds(bound("3", "9"), got), "%s: %s holds %+v", name, id, got) + } + } +} + +// TestSettleCompositionCycle_ALongCycleFoldsAsAModelsFoldPastTheBound pins a +// cycle of 250 models alternating a rising minimum and a falling maximum: the +// cycle folds as a model's fold does, judging the first maxFoldDeclarations +// written and reporting once, at the first left unjudged, that the rest are +// kept verbatim, so every model takes the member those first ones intersect to, +// {62, 937}, beside the rest. +func TestSettleCompositionCycle_ALongCycleFoldsAsAModelsFoldPastTheBound(t *testing.T) { + t.Parallel() + const n = 250 + members := make([]cycleMember, n) + for i := range members { + bounds := &ir.Constraints{Max: new(ir.BigVal(fmt.Sprint(1000 - i)))} + if i%2 == 0 { + bounds = &ir.Constraints{Min: new(ir.BigVal(fmt.Sprint(i)))} + } + members[i] = cycleMember{fmt.Sprintf("C%03d", i), fmt.Sprintf("C%03d", (i+1)%n), "type/primitive/integer", bounds} + } + reg := cycleRegistry() + + diags, _ := settleCycle(reg, cycleOf(reg, members...)) + + require.Len(t, diags, 1, "%+v", diags) + assert.Equal(t, diag.BudgetExceeded, diags[0].Code) + assert.Equal(t, jsontext.Pointer(fmt.Sprintf("/C%03d/properties/id", maxFoldDeclarations)), diags[0].Provenance.Pointer) + assert.Len(t, decidedBy(diags[0]), n, "the report decides every model's member") + want := &ir.Constraints{Min: new(ir.BigVal("62")), Max: new(ir.BigVal("937"))} + var short []string + for _, member := range members { + property := idOf(t, reg, ir.TypeID("type/"+member.name)) + if !sameBounds(want, property.Constraints) || len(property.Unmodeled) != n-maxFoldDeclarations { + short = append(short, fmt.Sprintf("%s %v..%v keeping %d", member.name, property.Constraints.Min, + property.Constraints.Max, len(property.Unmodeled))) + } + } + assert.Empty(t, short, "the models holding another member") +} + +// TestSettleCompositionCycle_MintsAtItsLeastMembersBroughtForm pins where a +// cycle's fold mints a node: at /allOf/properties/, so two +// cycles folding one name, each settled as its own component, mint two nodes, +// each member of a cycle taking its own cycle's. +func TestSettleCompositionCycle_MintsAtItsLeastMembersBroughtForm(t *testing.T) { + t.Parallel() + reg := cycleRegistry() + enum := func(id ir.TypeID, values ...string) ir.TypeID { + members := make([]ir.EnumMember, len(values)) + for i, value := range values { + members[i] = ir.EnumMember{Value: stringValue(value)} + } + reg[id] = &ir.Enum{ID: id, ValueType: ir.PrimitiveString, Members: members} + return id + } + first := cycleOf(reg, + cycleMember{name: "B", next: "A", target: enum("type/enum/B", "b", "c", "d")}, + cycleMember{name: "A", next: "B", target: enum("type/enum/A", "a", "b", "c")}) + second := cycleOf(reg, + cycleMember{name: "D", next: "C", target: enum("type/enum/D", "y", "z", "w")}, + cycleMember{name: "C", next: "D", target: enum("type/enum/C", "x", "y", "z")}) + stubbed, _ := stubMerger(reg) + for _, members := range [][]*ModelPropertyDeclarations{first, second} { + SettleCompositionCycle(members, stubbed.Merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{"id": true}) + } + + for _, tc := range []struct { + models []ir.TypeID + minted ir.TypeID + values []string + }{ + {[]ir.TypeID{"type/A", "type/B"}, composedAt("/A/allOf/properties/id"), []string{"b", "c"}}, + {[]ir.TypeID{"type/C", "type/D"}, composedAt("/C/allOf/properties/id"), []string{"y", "z"}}, + } { + for _, id := range tc.models { + assert.Equal(t, tc.minted, idOf(t, reg, id).Type.Target, "%s", id) + } + minted, ok := reg[tc.minted].(*ir.Enum) + require.True(t, ok, "%s is minted, an enum", tc.minted) + var values []string + for _, member := range minted.Members { + values = append(values, member.Value.String) + } + assert.Equal(t, tc.values, values, "%s", tc.minted) + } +} + +// modelRing builds a ring of models in reg named names, each declaring id as a +// model of its own, type/m/, and returns their declarations. +func modelRing(reg ir.TypeRegistry, names ...string) []*ModelPropertyDeclarations { + members := make([]cycleMember, len(names)) + for i, name := range names { + id := ir.TypeID("type/m/" + name) + reg[id] = &ir.Model{ID: id, Properties: []ir.Property{declared(name, "type/primitive/string", "/m/"+name+"/properties/"+name)}} + members[i] = cycleMember{name: name, next: names[(i+1)%len(names)], target: id} + } + return cycleOf(reg, members...) +} + +// TestSettleCompositionCycle_ARingOfModelsComposesEveryDeclaration pins a +// ring each member of which redeclares id as a model of its own: the cycle's +// one fold mints one model composing every member's model, in the order they +// are written, whatever order the members are handed in, and nothing is +// reported. +func TestSettleCompositionCycle_ARingOfModelsComposesEveryDeclaration(t *testing.T) { + t.Parallel() + for name, names := range map[string][]string{ + "three": {"A", "B", "C"}, "three rotated": {"C", "A", "B"}, "four": {"D", "B", "A", "C"}, + } { + reg := cycleRegistry() + members := modelRing(reg, names...) + stubbed, _ := stubMerger(reg) + + diags, _ := SettleCompositionCycle(members, stubbed.Merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{"id": true}) + + assert.Empty(t, diags, name) + assert.Equal(t, 1, stubbed.walk.minted, "%s: one model is registered", name) + minted := composedAt("/A/allOf/properties/id") + model, ok := reg[minted].(*ir.Model) + require.True(t, ok, "%s: %s is a model", name, minted) + written := slices.Sorted(slices.Values(names)) + want := make([]ir.TypeID, len(written)) + for i, member := range written { + want[i] = ir.TypeID("type/m/" + member) + } + assert.Equal(t, want, ir.ComposedOf(model), "%s: every declaration, as written", name) + for _, member := range names { + assert.Equal(t, minted, idOf(t, reg, ir.TypeID("type/"+member)).Type.Target, "%s: %s", name, member) + } + } +} + +// countingWalk is a stubWalk counting what a fold asks of it. +type countingWalk struct { + *stubWalk + asked int +} + +func (w *countingWalk) Mint(pointer jsontext.Pointer, node ir.TypeDef, partPointers, assembled []jsontext.Pointer) ir.TypeID { + w.asked++ + return w.stubWalk.Mint(pointer, node, partPointers, assembled) +} + +func (w *countingWalk) Interned(at ir.Provenance) bool { + w.asked++ + return w.stubWalk.Interned(at) +} + +func (w *countingWalk) IsComposedOf(id, target ir.TypeID) bool { + w.asked++ + return w.stubWalk.IsComposedOf(id, target) +} + +func (w *countingWalk) DeclarationsAdmitAlike(a, b ir.Provenance) bool { + w.asked++ + return w.stubWalk.DeclarationsAdmitAlike(a, b) +} + +func (w *countingWalk) NodesAdmitAlike(a, b ir.TypeID) bool { + w.asked++ + return w.stubWalk.NodesAdmitAlike(a, b) +} + +func (w *countingWalk) AnnotationsCarried(kept, other ir.TypeID) AnnotationCarriage { + w.asked++ + return w.stubWalk.AnnotationsCarried(kept, other) +} + +func (w *countingWalk) Admits(at ir.Provenance, kind JSONInstanceKind) (admits KindAdmission, exact bool) { + w.asked++ + return w.stubWalk.Admits(at, kind) +} + +// closingRangeCycle builds a ring of n models in reg, each declaring id as an +// alias of integer, those at an even place raising a minimum to it and the +// rest lowering a maximum to 10n less it, so no two types hold one another and +// the fold mints their intersect. +func closingRangeCycle(reg ir.TypeRegistry, count int) []*ModelPropertyDeclarations { + members := make([]cycleMember, count) + for i := range members { + alias := ir.TypeID(fmt.Sprintf("type/bound/%d", i)) + bounds := &ir.Constraints{Max: new(ir.BigVal(fmt.Sprint(10*count - i)))} + if i%2 == 0 { + bounds = &ir.Constraints{Min: new(ir.BigVal(fmt.Sprint(i)))} + } + reg[alias] = &ir.Scalar{ID: alias, Base: &ir.TypeRef{Target: "type/primitive/integer"}, Constraints: bounds} + members[i] = cycleMember{name: fmt.Sprintf("C%04d", i), next: fmt.Sprintf("C%04d", (i+1)%count), target: alias} + } + return cycleOf(reg, members...) +} + +// TestSettleCompositionCycle_ALongCycleCostsOneFoldPastTheBound pins the cost +// of a cycle past one fold's bound: at 250, 500 and 1,000 models, what the +// fold asks of the walk and reads of the registry stays as it is, since it +// judges the first maxFoldDeclarations written and keeps the rest unread; the +// walk registers one node, every model takes it, and the one report is the +// cut. +func TestSettleCompositionCycle_ALongCycleCostsOneFoldPastTheBound(t *testing.T) { + t.Parallel() + var counts [3]int + for i, n := range []int{250, 500, 1000} { + reg := cycleRegistry() + members := closingRangeCycle(reg, n) + reads := 0 + stubbed, _ := stubMergerOver(reg, func(id ir.TypeID) (ir.TypeDef, bool) { + reads++ + typeDef, ok := reg[id] + return typeDef, ok + }) + walk := &countingWalk{stubWalk: stubbed.walk} + stubbed.Walk = walk + + diags, _ := SettleCompositionCycle(members, stubbed.Merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{"id": true}) + + require.Len(t, diags, 1, "%d models: %+v", n, diags) + require.Equal(t, diag.BudgetExceeded, diags[0].Code, "%d models", n) + minted := composedAt("/C0000/allOf/properties/id") + require.Equal(t, 1, stubbed.walk.minted, "%d models", n) + node, ok := reg[minted].(*ir.Scalar) + require.True(t, ok, "%d models: %s is a scalar", n, minted) + want := &ir.Constraints{Min: new(ir.BigVal("62")), Max: new(ir.BigVal(fmt.Sprint(10*n - 63)))} + assert.True(t, sameBounds(want, node.Constraints), "%d models: %+v", n, node.Constraints) + for _, member := range members { + require.Equal(t, minted, idOf(t, reg, member.m.ID).Type.Target, "%d models: %s", n, member.m.ID) + } + counts[i] = walk.asked + reads + } + assert.Equal(t, [3]int{counts[0], counts[0], counts[0]}, counts, "what a cycle of 250, 500 and 1,000 models asks and reads") +} + +// TestSettleCompositionCycle_APartBringingAMembersDeclarationIsAnError pins +// the component's boundary: a part outside it composes no member, since one +// that did would be in it, so a part's table naming a member's own +// declaration is an internal error, and that declaration is not carried again +// beside the member's own. +func TestSettleCompositionCycle_APartBringingAMembersDeclarationIsAnError(t *testing.T) { + t.Parallel() + reg := cycleRegistry() + members := cycleOf(reg, + cycleMember{name: "A", next: "B", target: "type/primitive/string"}, + cycleMember{name: "B", next: "A", target: "type/primitive/string"}) + reg["type/O"] = &ir.Model{ID: "type/O"} + a := reg["type/A"].(*ir.Model) + a.Mixins = append(a.Mixins, ir.TypeRef{Target: "type/O"}) + members[0].Compose("type/O", "/A/allOf/1") + bID := reg["type/B"].(*ir.Model) + tables := map[ir.TypeID]RedeclaredWireNameTable{ + "type/O": {"id": DeclaredAt(ir.PropertyDecl{Owner: "type/B", Property: &bID.Properties[0]})}, + } + stubbed, _ := stubMerger(reg) + + diags, _ := SettleCompositionCycle(members, stubbed.Merger, tables, map[string]bool{"id": true}) + + require.Len(t, diags, 1, "%+v", diags) + assert.Equal(t, diag.InternalInvariant, diags[0].Code) + assert.Equal(t, jsontext.Pointer("/A/allOf/1"), diags[0].Provenance.Pointer) + assert.Contains(t, diags[0].Message, `brings "id" as type/B declares it`) +} + +// TestSettleCompositionCycle_ATableNamesOnlySharedNames pins the tables a cycle +// settles: a name one member alone declares is in every member's table only +// where another model declares it too, as a member's own names are only where +// shared. +func TestSettleCompositionCycle_ATableNamesOnlySharedNames(t *testing.T) { + t.Parallel() + for _, shared := range []bool{true, false} { + reg := cycleRegistry() + members := cycleOf(reg, + cycleMember{name: "A", next: "B", target: "type/primitive/string"}, + cycleMember{name: "B", next: "A", target: "type/primitive/string"}) + members[0].MergeProperty(declared("solo", "type/primitive/string", "/A/properties/solo"), written(`{"own":true}`), "") + stubbed, _ := stubMerger(reg) + + _, tables := SettleCompositionCycle(members, stubbed.Merger, map[ir.TypeID]RedeclaredWireNameTable{}, + map[string]bool{"id": true, "solo": shared}) + + _, named := tables["type/B"]["solo"] + assert.Equal(t, shared, named, "solo shared %t", shared) + } +} diff --git a/compilers/openapi/internal/merge/detail.go b/compilers/openapi/internal/merge/detail.go index c7d000471..3703d90b3 100644 --- a/compilers/openapi/internal/merge/detail.go +++ b/compilers/openapi/internal/merge/detail.go @@ -9,197 +9,211 @@ import ( "slices" "strings" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/ir" ) -// holding is which of two nodes says all the other does of one part of them: +// subsumption is which of two nodes says all the other does of one part of them: // both where they say the same, neither where each says what the other lacks. -type holding struct{ a, b bool } +type subsumption struct{ a, b bool } -// bothNodesHoldPart is the holding of a part two nodes say alike. -var bothNodesHoldPart = holding{a: true, b: true} +// bothSubsume is the holding of a part two nodes say alike. +var bothSubsume = subsumption{a: true, b: true} // and is the holding of two parts together. -func (h holding) and(holdingValue holding) holding { - return holding{a: h.a && holdingValue.a, b: h.b && holdingValue.b} +func (h subsumption) and(combined subsumption) subsumption { + return subsumption{a: h.a && combined.a, b: h.b && combined.b} } -// holdingOf reads a verdict on two parts as a holding: the narrower says all -// the broader does, and two that meet each say what the other lacks. Any other -// verdict is no holding, since nothing builds a part saying both. -func holdingOf(rel relation) (holding, bool) { +// subsumptionOf reads an answer on two parts as a holding: the narrower says +// all the broader does, and two that intersect each say what the other lacks. +// Any other answer is no holding, since nothing builds a part saying both. +func subsumptionOf(rel relation) (subsumption, bool) { switch rel { case relSame: - return bothNodesHoldPart, true + return bothSubsume, true case firstTypeIsNarrower: - return holding{a: true}, true + return subsumption{a: true}, true case secondTypeIsNarrower: - return holding{b: true}, true - case relMeet: - return holding{}, true + return subsumption{b: true}, true + case relIntersect: + return subsumption{}, true default: - return holding{}, false + return subsumption{}, false } } -// nullHolding is the holding of two references' null admission: the one +// nullSubsumption is the holding of two references' null admission: the one // admitting no null the other refuses says all the other does of null. -func nullHolding(a, b ir.TypeRef) holding { - return holding{a: !a.Nullable || b.Nullable, b: !b.Nullable || a.Nullable} +func nullSubsumption(a, b ir.TypeRef) subsumption { + return subsumption{a: !a.Nullable || b.Nullable, b: !b.Nullable || a.Nullable} } -// verdict judges two nodes of one kind by what they say of their values and -// what else they say. Two saying one set of values are the same type where they -// say the rest alike, and otherwise two types the source declared apart, which -// overlap. Otherwise the one saying all the other does, in both, is narrower, -// and two each saying what the other lacks meet in a node the fold builds, -// where one can hold all they say (adoptable), and overlap where none can. -func verdict(values, detail holding, adoptable bool) relation { +// relationOfValues judges two nodes of one kind by what they say of their +// values and else (nodeDetail). Two each saying what the other lacks intersect +// where one node can hold both (adoptable); where none can, one whose values +// the other holds overlaps it, and two neither holding the other's values, as +// two patterns, are undecided. +func relationOfValues(values subsumption, detail nodeDetail) relation { if values.a && values.b { - if detail.a && detail.b { + if detail.besideNotes == bothSubsume { return relSame } return relOverlap } - holdingValue := values.and(detail) + combined := values.and(detail.subsumption) switch { - case holdingValue.a: + case combined.a: return firstTypeIsNarrower - case holdingValue.b: + case combined.b: return secondTypeIsNarrower - case adoptable: - return relMeet - default: + case detail.adoptable: + return relIntersect + case values.a || values.b: return relOverlap + default: + return relUndecided } } +// nodeDetail is what two nodes say beside their values, as detailOf judges it: +// the holding of all of it, the holding of all but their notes (judgedEntries, +// unjudged), and whether one node could say all both do. +type nodeDetail struct { + subsumption subsumption + besideNotes subsumption + adoptable bool +} + // detailOf judges what two nodes say beside their values: their encoding and -// their TypeCommon but where each was declared (siteless). A field one sets -// and the other leaves empty is said by the first alone, and one both set -// differently by neither. adoptable reports whether one node could say all -// both do: no field set differently, and no examples only one gives, since -// nothing shows the node built of the two admits them. -func (j typeJudge) detailOf(a, b extras) (holding, bool) { - holdingValue, adoptable := fieldHolding(reflect.ValueOf(a.Encoding), reflect.ValueOf(b.Encoding)) - um, umOK := unmodeledHolding(a.Common.Unmodeled, b.Common.Unmodeled, j.sites.walk) - ex, exOK := fieldHolding(reflect.ValueOf(a.Common.Examples), reflect.ValueOf(b.Common.Examples)) - holdingValue, adoptable = holdingValue.and(um).and(ex), adoptable && umOK && exOK && ex == bothNodesHoldPart +// their TypeCommon but where each was declared (siteless). One node can say +// all both do where no field is set differently and no examples only one +// gives, since nothing shows the node built of the two admits them. +func (j typeJudge) detailOf(a, b extras) nodeDetail { + combined, adoptable := fieldSubsumption(reflect.ValueOf(a.Encoding), reflect.ValueOf(b.Encoding)) + um, umOK := unmodeledSubsumption(a.Common.Unmodeled, b.Common.Unmodeled, j.sites.walk) + judgedUm, _ := unmodeledSubsumption(judgedAgainst(a.Common.Unmodeled, b.Kinds), judgedAgainst(b.Common.Unmodeled, a.Kinds), j.sites.walk) + ex, exOK := fieldSubsumption(reflect.ValueOf(a.Common.Examples), reflect.ValueOf(b.Common.Examples)) + besideNotes := combined.and(judgedUm) + combined, adoptable = combined.and(um).and(ex), adoptable && umOK && exOK && ex == bothSubsume ac, bc := siteless(a.Common), siteless(b.Common) ac.Unmodeled, bc.Unmodeled, ac.Examples, bc.Examples = nil, nil, nil, nil av, bv := reflect.ValueOf(ac), reflect.ValueOf(bc) for i := range av.NumField() { - fh, ok := fieldHolding(av.Field(i), bv.Field(i)) - holdingValue, adoptable = holdingValue.and(fh), adoptable && ok + fh, ok := fieldSubsumption(av.Field(i), bv.Field(i)) + combined, adoptable = combined.and(fh), adoptable && ok + if av.Type().Field(i).Name != "Docs" { + besideNotes = besideNotes.and(fh) + } } - return holdingValue, adoptable + return nodeDetail{subsumption: combined, besideNotes: besideNotes, adoptable: adoptable} } -// fieldHolding is the holding of one field two nodes may set, and false where +// judgedEntries returns the entries of unmodeled an answer on values reads: +// every one but a kept readOnly or writeOnly, which binds a use of the type and +// says nothing of what it admits. It writes to no map it was given. +func judgedEntries(unmodeled ir.Unmodeled) ir.Unmodeled { + readOnly, writeOnly := annotation.EntryKey("", "readOnly"), annotation.EntryKey("", "writeOnly") + _, hasReadOnly := unmodeled[readOnly] + _, hasWriteOnly := unmodeled[writeOnly] + if !hasReadOnly && !hasWriteOnly { + return unmodeled + } + out := maps.Clone(unmodeled) + delete(out, readOnly) + delete(out, writeOnly) + return out +} + +// fieldSubsumption is the holding of one field two nodes may set, and false where // both set it differently. -func fieldHolding(a, b reflect.Value) (holding, bool) { +func fieldSubsumption(a, b reflect.Value) (subsumption, bool) { switch { case reflect.DeepEqual(a.Interface(), b.Interface()): - return bothNodesHoldPart, true + return bothSubsume, true case b.IsZero(): - return holding{a: true}, true + return subsumption{a: true}, true case a.IsZero(): - return holding{b: true}, true + return subsumption{b: true}, true default: - return holding{}, false + return subsumption{}, false } } -// unmodeledHolding is the holding of what two nodes keep under Unmodeled, key +// unmodeledSubsumption is the holding of what two nodes keep under Unmodeled, key // by key as fieldHolding reads a field, and false where both keep a key // differently, as sameEntry reads two entries through walk. -func unmodeledHolding(a, b ir.Unmodeled, walk FieldDeclarationContext) (holding, bool) { - holdingValue := bothNodesHoldPart +func unmodeledSubsumption(a, b ir.Unmodeled, walk FieldDeclarationContext) (subsumption, bool) { + combined := bothSubsume for _, k := range slices.Sorted(maps.Keys(a)) { other, ok := b[k] if !ok { - holdingValue.b = false + combined.b = false continue } if !sameEntry(walk, a[k], other) { - return holding{}, false + return subsumption{}, false } } for k := range b { if _, ok := a[k]; !ok { - holdingValue.a = false + combined.a = false } } - return holdingValue, true + return combined, true } // adopt returns base holding, beside all it says, each field of others that -// base leaves empty, as a reference to each would read it: the first of others -// to set it gives it, and differ hears of each later one setting it otherwise, -// by its index and the name a document spells the field with. Base keeps its -// site and its examples, which nothing adopts (detailOf). -func adopt(base ir.TypeCommon, others []ir.TypeCommon, walk FieldDeclarationContext, - differ func(k int, field string), +// base leaves empty, the first of others to set it giving it. differ hears of +// each later one setting it otherwise, and of each setting otherwise a field +// base sets, naming each node by its index among base and others, base at 0 +// and others[k] at k+1. Base keeps its site, its examples and its Unmodeled. +func adopt(base ir.TypeCommon, others []ir.TypeCommon, + differ func(passedOver, chosen int, field string, agrees func(k int) bool), ) ir.TypeCommon { said := func(typeCommon ir.TypeCommon) reflect.Value { typeCommon = siteless(typeCommon) typeCommon.Unmodeled, typeCommon.Examples = nil, nil return reflect.ValueOf(typeCommon) } - own, out := said(base), reflect.ValueOf(&base).Elem() - theirs := make([]reflect.Value, len(others)) - for k, typeCommon := range others { - theirs[k] = said(typeCommon) + out := reflect.ValueOf(&base).Elem() + nodes := make([]reflect.Value, 0, len(others)+1) + nodes = append(nodes, said(base)) + for _, typeCommon := range others { + nodes = append(nodes, said(typeCommon)) } for i := range out.NumField() { - if !own.Field(i).IsZero() { - continue - } - set := false - for k := range others { - v := theirs[k].Field(i) - switch { - case v.IsZero(): - case !set: - out.Field(i).Set(v) - set = true - case !reflect.DeepEqual(v.Interface(), out.Field(i).Interface()): - differ(k, jsonName(out.Type().Field(i))) - } - } + adoptField(out.Field(i), nodes, i, jsonName(out.Type().Field(i)), differ) } - base.Unmodeled = adoptUnmodeled(base.Unmodeled, others, walk, differ) return base } -// jsonName is the name a document spells f with, its JSON member's. -func jsonName(f reflect.StructField) string { - name, _, _ := strings.Cut(f.Tag.Get("json"), ",") - return name -} - -// adoptUnmodeled returns own with each key of others' Unmodeled it lacks, the -// first to keep one giving it, its provenance with it. differ hears of a later -// one keeping the key otherwise. It writes to no map it was given. -func adoptUnmodeled(own ir.Unmodeled, others []ir.TypeCommon, walk FieldDeclarationContext, - differ func(k int, field string), -) ir.Unmodeled { - out := maps.Clone(own) - taken := map[string]bool{} - for k, typeCommon := range others { - for _, key := range slices.Sorted(maps.Keys(typeCommon.Unmodeled)) { - entry := typeCommon.Unmodeled[key] - kept, ok := out[key] - switch { - case !ok: - if out == nil { - out = ir.Unmodeled{} - } - out[key], taken[key] = entry, true - case taken[key] && !sameEntry(walk, kept, entry): - differ(k, key) - } +// adoptField settles field i of a node built from nodes[0], which out holds, +// from what each of nodes says, as adopt reads it: the first of them to set +// it gives it, and differ hears of each later one setting another. +func adoptField(out reflect.Value, nodes []reflect.Value, i int, name string, + differ func(passedOver, chosen int, field string, agrees func(k int) bool), +) { + set, setter := false, 0 + gives := func(k int) bool { + field := nodes[k].Field(i) + return !field.IsZero() && reflect.DeepEqual(field.Interface(), out.Interface()) + } + for k := range nodes { + field := nodes[k].Field(i) + switch { + case field.IsZero(): + case !set: + out.Set(field) + set, setter = true, k + case !reflect.DeepEqual(field.Interface(), out.Interface()): + differ(k, setter, name, gives) } } - return out +} + +// jsonName is the name a document spells structField with, its JSON member's. +func jsonName(structField reflect.StructField) string { + name, _, _ := strings.Cut(structField.Tag.Get("json"), ",") + return name } diff --git a/compilers/openapi/internal/merge/enums.go b/compilers/openapi/internal/merge/enums.go index c969a29ff..c66c3f1c8 100644 --- a/compilers/openapi/internal/merge/enums.go +++ b/compilers/openapi/internal/merge/enums.go @@ -12,12 +12,11 @@ import ( // enums relates two enums alike but for their members, value types and // TypeCommon by the values they hold: none shared is disjoint, and otherwise -// verdict judges the values with the value types (valueTypeHolding) beside what -// else each says. Two listing shared values in different orders hold no enum of -// both, whose order would be one's (inOneOrder). Two of value types neither -// within the other, of one set of values of one value type or in different -// orders, or saying a shared value's member differently (sharedMembers) are left -// unrelated, for classify to judge by kind, as is any other pair. +// answer judges the values with the value types (valueTypeSubsumption) beside +// what else each says. Two listing shared values in different orders hold no +// enum of both, whose order would be one's, so they are left unrelated, for +// classify to judge by kind, as are two of value types neither within the +// other or saying a shared value's member differently. func (j typeJudge) enums(a, b *ir.Enum) relation { as, bs := *a, *b as.TypeCommon, bs.TypeCommon, as.Members, bs.Members = ir.TypeCommon{}, ir.TypeCommon{}, nil, nil @@ -28,34 +27,35 @@ func (j typeJudge) enums(a, b *ir.Enum) relation { ai, bi := indexMembers(a.Members), indexMembers(b.Members) aWithin, shared, aok := sharedMembers(a.Members, bi) bWithin, _, bok := sharedMembers(b.Members, ai) - kinds, related := valueTypeHolding(a.ValueType, b.ValueType) + kinds, related := valueTypeSubsumption(a.ValueType, b.ValueType) ordered := inOneOrder(a.Members, bi) switch { case !aok || !bok: return relUnrelated case shared == 0: return relDisjoint - case !related, aWithin && bWithin && (kinds == bothNodesHoldPart || !ordered): + case !related, aWithin && bWithin && (kinds == bothSubsume || !ordered): return relUnrelated } - detail, adoptable := j.detailOf(extras{Common: a.TypeCommon}, extras{Common: b.TypeCommon}) - return verdict(holding{a: aWithin, b: bWithin}.and(kinds), detail, adoptable && ordered) + detail := j.detailOf(extras{Common: a.TypeCommon, Kinds: primitiveKinds(a.ValueType)}, + extras{Common: b.TypeCommon, Kinds: primitiveKinds(b.ValueType)}) + detail.adoptable = detail.adoptable && ordered + return relationOfValues(subsumption{a: aWithin, b: bWithin}.and(kinds), detail) } -// valueTypeHolding is the holding of two enums' value types: the narrower says -// all the other does (typeformat.Relate), and one says all the other does of -// itself. It is false where neither is within the other, since no value type -// says both. -func valueTypeHolding(a, b ir.PrimitiveKind) (holding, bool) { - return holdingOf(fromTypeformat(typeformat.Relate(a, b))) +// valueTypeSubsumption is the holding of two enums' value types: the narrower +// says all the other does (typeformat.Relate). It is false where neither is +// within the other, since no value type says both. +func valueTypeSubsumption(a, b ir.PrimitiveKind) (subsumption, bool) { + return subsumptionOf(fromTypeformat(typeformat.Relate(a, b))) } // narrowestValueType returns the value type within every other of the enums // nodes holds, and false where no one is, or a node is no enum. func narrowestValueType(nodes []ir.TypeDef) (ir.PrimitiveKind, bool) { var narrowest ir.PrimitiveKind - for k, td := range nodes { - enum, ok := td.(*ir.Enum) + for k, typeDef := range nodes { + enum, ok := typeDef.(*ir.Enum) if !ok { return "", false } @@ -114,33 +114,33 @@ func inOneOrder(xs []ir.EnumMember, ys memberIndex) bool { // are scanned. type memberIndex struct { members []ir.EnumMember - // byValue maps each canonical spelling to its first member's position. - byValue map[string]int + // by maps each canonical spelling to its first member's position. + by map[string]int // rest lists, in order, the positions of members no canonical spelling names. rest []int } // indexMembers indexes ms by value. func indexMembers(ms []ir.EnumMember) memberIndex { - memberIndexValue := memberIndex{members: ms, byValue: make(map[string]int, len(ms))} + memberIndex := memberIndex{members: ms, by: make(map[string]int, len(ms))} for i, enumMember := range ms { - key, ok := canonicalValue(enumMember.Value, 0) + key, ok := ir.CanonicalValueSpelling(enumMember.Value) if !ok { - memberIndexValue.rest = append(memberIndexValue.rest, i) + memberIndex.rest = append(memberIndex.rest, i) continue } - if _, seen := memberIndexValue.byValue[key]; !seen { - memberIndexValue.byValue[key] = i + if _, seen := memberIndex.by[key]; !seen { + memberIndex.by[key] = i } } - return memberIndexValue + return memberIndex } // find returns the position of the first member holding value, and false where // none does. func (x memberIndex) find(value ir.Value) (int, bool) { - if key, ok := canonicalValue(value, 0); ok { - i, found := x.byValue[key] + if key, ok := ir.CanonicalValueSpelling(value); ok { + i, found := x.by[key] return i, found } for _, i := range x.rest { @@ -154,8 +154,8 @@ func (x memberIndex) find(value ir.Value) (int, bool) { // literalBesideDetail relates lit, a literal a Scalar node admits, against // that node where it holds more than saysOnlyFormat allows: the literal is // narrower where it says all the node says beside its values too, and the two -// meet where a literal can hold what the node adds (verdict). A node saying more -// of its values than a held format and bounds overlaps the literal, as before. +// intersect where a literal can hold what the node adds. A node saying more of +// its values than a held format and bounds overlaps the literal. func (j typeJudge) literalBesideDetail(lit *ir.Literal, node ir.TypeDef) relation { scalar, ok := node.(*ir.Scalar) if !ok { @@ -166,8 +166,8 @@ func (j typeJudge) literalBesideDetail(lit *ir.Literal, node ir.TypeDef) relatio if !scalarSaysOnlyFormat(&bare) { return relOverlap } - detail, adoptable := j.detailOf(extras{Common: lit.TypeCommon}, extras{Common: scalar.TypeCommon}) - return verdict(holding{a: true}, detail, adoptable) + return relationOfValues(subsumption{a: true}, j.detailOf(extras{Common: lit.TypeCommon, Kinds: typeformat.EveryInstanceKind}, + extras{Common: scalar.TypeCommon, Kinds: typeformat.EveryInstanceKind})) } // bothEnums returns a and b as enums, and false where either is not one. diff --git a/compilers/openapi/internal/merge/enums_internal_test.go b/compilers/openapi/internal/merge/enums_internal_test.go index d7641ea37..ff2ed731d 100644 --- a/compilers/openapi/internal/merge/enums_internal_test.go +++ b/compilers/openapi/internal/merge/enums_internal_test.go @@ -22,21 +22,21 @@ import ( // grow with the square of the width. Not parallel: AllocsPerRun measures the // process. func TestFold_TwoEnumsCostTheirWidth(t *testing.T) { - enum := func(id ir.TypeID, from, n int) *ir.Enum { - ms := make([]ir.EnumMember, n) + enum := func(id ir.TypeID, from, count int) *ir.Enum { + ms := make([]ir.EnumMember, count) for i := range ms { ms[i] = ir.EnumMember{Value: stringValue("v" + strconv.Itoa(from+i))} } return &ir.Enum{ID: id, ValueType: ir.PrimitiveString, Members: ms} } - cost := func(n int) float64 { - reg := map[ir.TypeID]ir.TypeDef{"type/x": enum("type/x", 0, n), "type/y": enum("type/y", n/2, n)} + cost := func(count int) float64 { + reg := map[ir.TypeID]ir.TypeDef{"type/x": enum("type/x", 0, count), "type/y": enum("type/y", count/2, count)} stubbed, recorded := stubMerger(reg) decls := declsOf("type/x", "type/y") got := stubbed.fold(decls) irEnum, ok := reg[got.Type.Target].(*ir.Enum) require.True(t, ok) - require.Len(t, irEnum.Members, n/2, "the two meet in the values they share") + require.Len(t, irEnum.Members, count/2, "the two intersect in the values they share") require.Empty(t, *recorded) least := testing.AllocsPerRun(1, func() { stubbed.fold(decls) }) for range 4 { @@ -107,13 +107,13 @@ func valueTypedRegistry() map[ir.TypeID]ir.TypeDef { // enums in both orders: the one whose values the other holds every one of, of // the narrower value type, is the field's type, with nothing minted, kept or // reported, and two each saying what the other lacks, in their values or their -// value types, meet in an enum of the values they share, of the narrower value +// value types, intersect in an enum of the values they share, of the narrower value // type. func TestFold_EnumsOfDifferentValueTypesAreJudgedByTheirValues(t *testing.T) { t.Parallel() for _, tc := range []struct { a, b ir.TypeID - within ir.TypeID // the field's type, or "" where the two meet + within ir.TypeID // the field's type, or "" where the two intersect values []ir.Value }{ {a: "type/number-1,2", b: "type/integer-1", within: "type/integer-1"}, @@ -135,19 +135,19 @@ func TestFold_EnumsOfDifferentValueTypesAreJudgedByTheirValues(t *testing.T) { } enum, ok := reg[got.Type.Target].(*ir.Enum) require.True(t, ok, "%v", order) - assert.Equal(t, composedAt(declaredAt(1)), got.Type.Target, "%v", order) + assert.Equal(t, composedAt(foldKey), got.Type.Target, "%v", order) assert.Equal(t, ir.PrimitiveInteger, enum.ValueType, "%v: of the narrower value type", order) assert.Equal(t, tc.values, valuesOf(enum), "%v", order) } } } -// TestFold_ThreeEnumsMeetInTheNarrowestValueType pins three enums of value types +// TestFold_ThreeEnumsIntersectInTheNarrowestValueType pins three enums of value types // one within the next, each pair sharing values, in every order: the field is an // enum of the value all three hold, of the narrowest value type. Where no value // type is within both others, no enum holds the three, so the field keeps the -// one meeting both, and each other is reported and kept, in every order. -func TestFold_ThreeEnumsMeetInTheNarrowestValueType(t *testing.T) { +// one intersecting both, and each other is reported and kept, in every order. +func TestFold_ThreeEnumsIntersectInTheNarrowestValueType(t *testing.T) { t.Parallel() for _, tc := range []struct { name string diff --git a/compilers/openapi/internal/merge/fold.go b/compilers/openapi/internal/merge/fold.go index a73e85217..722ddcc12 100644 --- a/compilers/openapi/internal/merge/fold.go +++ b/compilers/openapi/internal/merge/fold.go @@ -5,7 +5,6 @@ package merge import ( "bytes" - "cmp" "encoding/json/jsontext" "fmt" "maps" @@ -14,7 +13,6 @@ import ( "strings" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/budget" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/provenance" @@ -34,16 +32,17 @@ type Merger struct { // Doc places what a fold reports. Doc provenance.Doc // Sources names the documents a declaration's Provenance.Source indexes, - // so a report names the one an entry brought a declaration from (at). + // so a report names the one an entry carried a declaration from + // (placeName). Sources []ir.SourceInfo - // Reads is what remains of the run's reads, which telling whether one part's - // declaration stands within another's composition spends (ownership); nil - // reads without bound. - Reads *budget.Budget - // PrunedDiagnostics, when non-nil, records alternate messages for drop - // diagnostics naming an anonymous losing TypeID so post-settlement pruning - // can substitute them if and only if that TypeID is actually removed. - PrunedDiagnostics *[]PrunedDiagnostic + // AliasChainAnswerMemos holds merge's answers about the run's alias + // chains, through the index the run's settlements are handed: built once a + // run, so a chain many models' folds read is read once. + AliasChainAnswerMemos *AliasChainAnswerMemos + // ValueAdmissionReader judges whether a type admits a value + // (NewFoldValueAdmissionReader), over the registry the run's memos + // read: a fold judges each value a declaration gives with it (adopts). + ValueAdmissionReader *ir.ValueAdmissionReader // Discarded, when non-nil, records every TypeID carried by a declaration // that a fold superseded or dropped so post-settlement pruning can remove // it if nothing else reaches it. @@ -59,42 +58,100 @@ type Merger struct { // FieldDeclarationContext is what a fold asks of the walk that declared the // field. type FieldDeclarationContext interface { - // Mint registers node, which stands for the declarations of the field - // pointer names (fieldSpan), or for what their types hold at a position - // below it, and returns the ID it is registered under. It fills what in - // node's TypeCommon names and places the node, and an enum's member IDs: - // the lowering's to derive. The fold reads what it mints, so it registers - // at once. brought holds where each part of a model composing the - // declarations' types, Base first (ComposedOf), was brought, and assembled - // what a node no schema is written at is assembled from - // (folding.assembled); each is nil otherwise. + // Mint registers node, which represents the declarations of the field + // pointer names (fieldSpan), or what their types hold at a position below + // it, and returns its ID, filling what in node's TypeCommon names and + // places it and an enum's member IDs. The fold reads what it mints, so it + // registers at once. brought holds where each part of a model composing + // the declarations' types, Base first, was carried, and assembled what a + // node no schema is written at is assembled from; each is nil otherwise. Mint(pointer jsontext.Pointer, node ir.TypeDef, brought, assembled []jsontext.Pointer) ir.TypeID - // Interned reports whether a node stands at pointer, which only the - // finished registry can answer. - Interned(pointer jsontext.Pointer) bool - // Alike reports whether what is written at a and at b reads each $ref it - // writes against one base, so the same text there says the same: under an - // $id naming another URI, a $ref spelled alike names another schema. The - // fold asks it only of text writing one (annotation.WritesReference). - Alike(a, b ir.Provenance) bool - // Admits reports whether the schema written at a node's provenance admits - // every instance of kind, so the structure it lowered to admits each value - // of another type of that kind: `properties` alone constrains objects and - // admits a string (docs/compilers/openapi.md#allof-redeclared-property), - // while a bound or a value set beside it refuses some integers, so it - // admits integers but not every one. It is exact where the read follows all - // the source writes; one it cannot place, or one writing what the read does - // not follow but which could refuse a value of some kind, is not, and - // decides nothing. - Admits(at ir.Provenance, kind JSONInstanceKind) (admits, exact bool) + // Primitive returns the ID of the primitive of kind, registering it where + // no lowering has: a node the fold builds may name a primitive no + // declaration's type names, as the intersection of a format and a bare + // kind does. + Primitive(kind ir.PrimitiveKind) ir.TypeID + // Interned reports whether a node sits at the pointer at names, read in + // at's own document, which only the finished registry can answer. + Interned(at ir.Provenance) bool + // InDiscriminatorHierarchy reports whether the declaration written at + // place, read in its own document, writes a $ref landing on a schema that + // takes part in a discriminator hierarchy, as a written allOf's choice + // reads one: the fold chooses the Base of a field's composition alike. + InDiscriminatorHierarchy(place ir.Provenance) bool + // IsComposedOf reports whether id is composed of target: a path of one + // edge or more along ir.ComposedOf leads from one to the other, at any + // depth. + IsComposedOf(id, target ir.TypeID) bool + // DeclarationsAdmitAlike reports whether the declarations at a and at b + // admit exactly the same values, each read in its own document and + // dialect: under an $id naming another URI, or in another document, a + // $ref spelled alike may name another schema. Where that cannot be shown + // they are not alike. The fold asks it only of declarations keeping a + // reference (annotation.WritesReference). + DeclarationsAdmitAlike(a, b ir.Provenance) bool + // NodesAdmitAlike reports whether the nodes a and b admit exactly the same + // values, each read where it was written, an alias adding nothing read as + // the end of its chain; where that cannot be shown, they do not. + NodesAdmitAlike(a, b ir.TypeID) bool + // AnnotationsCarried reports whether the nodes kept and other admit + // alike, as NodesAdmitAlike reads them, and, where they do, whether kept's + // nodes give every annotation other's give: each title, description, + // external link and deprecation, at the same place, or for one an alias + // says, anywhere on the chain. + AnnotationsCarried(kept, other ir.TypeID) AnnotationCarriage + // Admits reports what the schema written at a node's provenance, read in + // its own document and dialect, admits of the instances of kind: every + // one, as `properties` alone admits a string + // (docs/compilers/openapi.md#allof-redeclared-property); none, as `not` + // of a type refuses that type's; or some, as a bound refuses some + // integers. It is exact where the read follows all the source writes; one + // it cannot place, or one writing what the read does not follow but which + // could refuse a value of some kind, is not, and decides nothing. + Admits(at ir.Provenance, kind JSONInstanceKind) (admits KindAdmission, exact bool) } +// AnnotationCarriage is what a type chosen for another carries of it +// (FieldDeclarationContext.AnnotationsCarried). +type AnnotationCarriage uint8 + +// What a type chosen for another carries of it. +const ( + // TypesAdmitApart is two types not shown to admit alike, whose + // annotations are read for nothing. + TypesAdmitApart AnnotationCarriage = iota + // AlikeAnnotatedApart is two types admitting alike, the chosen one's nodes + // dropping an annotation the other's give. + AlikeAnnotatedApart + // AlikeAnnotationsCarried is two types admitting alike, the chosen one's + // nodes giving every annotation the other's give. + AlikeAnnotationsCarried +) + +// KindAdmission is what a schema's source admits of the instances of one +// kind (FieldDeclarationContext.Admits). +type KindAdmission uint8 + +// What a schema's source admits of one kind's instances. +const ( + // AdmitsSomeOfKind is a source admitting some instances of the kind and + // refusing others, or one whose read cannot tell. + AdmitsSomeOfKind KindAdmission = iota + // AdmitsEveryOfKind is a source admitting every instance of the kind. + AdmitsEveryOfKind + // AdmitsNoneOfKind is a source refusing every instance of the kind. + AdmitsNoneOfKind +) + // JSONInstanceKind is a kind of JSON instance, which every value of a type a // structure is judged against is (FieldDeclarationContext.Admits). type JSONInstanceKind uint8 -// The kinds of JSON instance. An integer is a number with no fraction, which -// a schema may admit apart from the others. +// The kinds of JSON instance, one for each `type` word. An integer is a number +// with no fraction, which a schema may admit apart from the others, and +// InstanceNumber is any number, as `type: number` admits, where the applies-to +// reading's typeformat.InstanceNumber is a number with a fraction alone +// (instanceKindsOf). const ( InstanceString JSONInstanceKind = iota + 1 InstanceInteger @@ -107,16 +164,27 @@ const ( // resolve looks the type id names up in the registry. func (g *Merger) resolve(id ir.TypeID) (ir.TypeDef, bool) { - td, ok := g.Reg[id] - return td, ok + typeDef, ok := g.Reg[id] + return typeDef, ok } // judgeAt is the judgment over g's registry of two declarations whose types // are written at a and b (declaration.sites). func (g *Merger) judgeAt(a, b []ir.Provenance) typeJudge { - return typeJudge{resolve: g.resolve, sites: declarationSites{walk: g.Walk, written: [2][]ir.Provenance{a, b}}} + return typeJudge{registryReader: g.registryReader(), sites: declarationSites{walk: g.Walk, written: [2][]ir.Provenance{a, b}}} } +// registryReader is what g's judgments read of the registryReader and its alias chains. +func (g *Merger) registryReader() registryReader { + return registryReader{resolve: g.resolve, answerMemos: g.AliasChainAnswerMemos, admission: g.ValueAdmissionReader} +} + +// declarationIndex is where a declaration sits among the declarations of one +// field a fold judges, in declaration order. A member's index among its +// position's members is a plain int, since a position nested below the field +// holds fewer members than the field has declarations. +type declarationIndex int + // declaration is one declaration of a field, as the walk lowered it, and how // to render it verbatim. type declaration struct { @@ -137,10 +205,14 @@ type declaration struct { // may be written (Declared.TypeAt), and owner the model declaring it. typeAt []ir.Provenance owner ir.TypeID + // valueWrittenAt is, for a settled member an entry brings, where the value of + // each field its fold took from one declaration is written + // (Declared.ValueAt), by the field's name in a report. + valueWrittenAt map[string]ir.Provenance } // sites is where the nodes of d's type may be written, which tells one -// hoisted at its declaration from one a $ref brought there (hoistedAt): where +// hoisted at its declaration from one a $ref carried there (hoistedAt): where // d is written, or, for a declaration an entry brings, where its part says, // since a member a part settled keeps its first declaration's identity // whichever gave its type. @@ -151,9 +223,11 @@ func (d declaration) sites() []ir.Provenance { return []ir.Provenance{d.property.Provenance} } -// reportAt is where what a fold says of d sits: the entry bringing it, or where -// it is written. -func (d declaration) reportAt() jsontext.Pointer { +// assemblyPointer is where the model writes d, the entry bringing it or d +// itself, which places a node the fold assembles from d or mints for it +// (assembledFrom, builder.compose). A report about d sits where d is written +// (fieldPlace). +func (d declaration) assemblyPointer() jsontext.Pointer { if d.via != nil { return d.via.at } @@ -171,43 +245,45 @@ func (d declaration) keptAs() string { } // fold returns the property decls make together under allOf intersection -// (docs/compilers/openapi.md#allof-redeclared-property), and what it reports. -// decls is every declaration of one wire name, at least two, in declaration -// order; the field keeps the first one's identity unless another model carries -// that declaration (identify). Declaration order decides only a tie, reported, -// which goes to the later declaration as the flattening's override does. What -// a declaration says that the field does not carry is reported at that -// declaration, which is kept verbatim beside the field. -// -// A fold judges every pair of declarations, so it judges at most -// maxFoldDeclarations of them (keepUnjudged). -func (g *Merger) fold(decls []declaration) (ir.Property, []ir.Diagnostic) { - judged := decls[:min(len(decls), maxFoldDeclarations)] - schema, field := fieldSpan(judged) - merged, diags := g.foldAt(decls, field, nil) - g.identify(&merged, schema, field) - return merged, diags +// (docs/compilers/openapi.md#allof-redeclared-property), its value sites, and +// what it reports. decls is every declaration of one wire name, at least two, +// in declaration order. Declaration order decides only a tie, reported, going +// to the later as the flattening's override does. What a declaration says +// that the field does not carry is reported there and kept verbatim. It +// judges every pair, so it judges at most maxFoldDeclarations declarations. +func (g *Merger) fold(decls []declaration) (ir.Property, map[string]ir.Provenance, []ir.Diagnostic) { + judged, _ := judgedFirst(g, decls) + schema, key := fieldSpan(judged) + merged, valueWrittenAt, diags := g.foldAt(decls, key, nil) + g.identify(&merged, judged, schema, key) + return merged, valueWrittenAt, diags } // foldAt is fold with no identity of its own, minting what it must under -// field, placed by assembled where no declaration names field -// (folding.assembled). -func (g *Merger) foldAt(decls []declaration, field jsontext.Pointer, assembled []jsontext.Pointer) (ir.Property, []ir.Diagnostic) { - judged, past := decls, []declaration(nil) - if len(decls) > maxFoldDeclarations { - judged, past = decls[:maxFoldDeclarations], decls[maxFoldDeclarations:] - } - folding := newFolding(g, judged, field) +// fieldPointer, placed by assembled where no declaration names the field. +func (g *Merger) foldAt(decls []declaration, fieldPointer jsontext.Pointer, assembled []jsontext.Pointer) (ir.Property, map[string]ir.Provenance, []ir.Diagnostic) { + folding, past := g.runFold(decls, fieldPointer, assembled) + merged, diags := folding.finish() + return merged, folding.valueWrittenAt, append(diags, g.keepUnjudged(&merged, past)...) +} + +// runFold runs the fold of decls but those past maxFoldDeclarations, which it +// returns, to its last setting, its reports noted and not yet said +// (fieldFold.finish). +func (g *Merger) runFold(decls []declaration, field jsontext.Pointer, assembled []jsontext.Pointer) (*fieldFold, []declaration) { + judged, past := judgedFirst(g, decls) + folding := newFieldFold(g.withFoldReader(), judged, field) folding.assembled = assembled folding.foldType() + keepAnnotatedCopies(folding) folding.foldConstraints() folding.foldValues() folding.foldUse() folding.foldDocs() folding.foldAnnotations() folding.foldUnmodeled() - merged, diags := folding.finish() - return merged, append(diags, g.keepUnjudged(&merged, past)...) + keepApart(folding) + return folding, past } // maxFoldDeclarations bounds the declarations of one field a fold judges @@ -217,62 +293,91 @@ func (g *Merger) foldAt(decls []declaration, field jsontext.Pointer, assembled [ // times. const maxFoldDeclarations = 64 +// judgedFirst splits decls, in declaration order, into the declarations a +// fold judges, the first maxFoldDeclarations written (compareSourceOrder), +// still in declaration order, and the rest, the first written first, so no +// order of the declarations decides which are cut. +func judgedFirst(merger *Merger, decls []declaration) (judged, past []declaration) { + if len(decls) <= maxFoldDeclarations { + return decls, nil + } + order := writtenOrder(merger, decls) + cut := make([]bool, len(decls)) + for _, i := range order[maxFoldDeclarations:] { + cut[i] = true + past = append(past, decls[i]) + } + for i, declaration := range decls { + if !cut[i] { + judged = append(judged, declaration) + } + } + return judged, past +} + // keepUnjudged keeps each declaration past the bound that the model declares // verbatim beside merged, leaves each another model holds declared there, and -// reports at the first of them that the fold judged none: what they say is -// kept, not folded. +// reports at the first of them written, where it is written (fieldPlace), that +// the fold judged none: what they say is kept, not taken into the field. func (g *Merger) keepUnjudged(merged *ir.Property, past []declaration) []ir.Diagnostic { if len(past) == 0 { return nil } - diags := []ir.Diagnostic{diag.Newf(ir.SeverityError, diag.BudgetExceeded, g.Doc.At(past[0].reportAt()), - "field %q is declared %d times, past the %d declarations one fold judges; the %d after them are "+ + diags := []ir.Diagnostic{diag.Newf(ir.SeverityError, diag.BudgetExceeded, fieldPlace(g, past[0], fieldGivenTogether), + "field %q is declared %d times, past the %d declarations one fold judges; the %d written after them are "+ "unjudged, and each the model declares is kept verbatim under Unmodeled", merged.WireName, maxFoldDeclarations+len(past), maxFoldDeclarations, len(past))} for _, declaration := range past { if declaration.via == nil { - diags = append(diags, g.keepLosingDeclaration(merged, declaration.property.Provenance, declaration.source)...) + diags = append(diags, g.keepPassedOverDeclaration(merged, declaration.property.Provenance, declaration.source)...) } } return diags } -// folding is one fold in progress. -type folding struct { +// fieldFold is one fold in progress. +type fieldFold struct { g *Merger decls []declaration - // field is the pointer the nodes the fold mints are named for: the + // fieldPointer is the pointer the nodes the fold mints are named for: the // declaration naming the field (fieldSpan), or the member a composing model // declares, which no schema is written at, so assembled holds the positions // it is assembled from, which place what it mints // (FieldDeclarationContext.Mint); nil where a declaration names the field. - field jsontext.Pointer - assembled []jsontext.Pointer - // pos is the declarations' types judged against each other, and rel, winner + fieldPointer jsontext.Pointer + assembled []jsontext.Pointer + // pos is the declarations' types judged against each other, and rel, chosen declaration // and conjuncts what it holds. pos position // rel[i][j] is the judgment of decls[i]'s type against decls[j]'s. rel [][]relation - // winner is the declaration whose type the field takes, and cone marks - // each declaration whose type is the same as the winner's, broader, or - // meets it: the field's type holds every one of them, so it adopts their - // shape detail. A meeting no node holds takes its declarations out of the - // cone (meetField). - winner int + // chosen is the declaration whose type the field takes, and cone marks + // each declaration whose type is the same as the chosen's, broader, or + // intersects it: the field's type holds every one of them, so it adopts + // their shape detail. An intersection no node holds takes its declarations + // out of the cone. + chosen declarationIndex cone []bool // conjuncts lists the types the field composes, which puts every - // declaration in the cone, or nothing where the winner's type is the field's + // declaration in the cone, or nothing where the chosen declaration's type is the field's // (composition). conjuncts []conjunct merged ir.Property // typeAt is where the nodes of the field's type may be written // (Merger.typeSites), once foldType has settled it: a node the fold built - // holds members of declarations other than the winner. + // holds members of declarations other than the chosen declaration. typeAt []ir.Provenance // notes holds what the fold reports at each declaration, in order, and - // lost marks each declaration something of which the field does not carry. - notes [][]note - lost []bool + // passedOver marks each declaration something of which the field does not + // carry. + notes [][]note + passedOver []bool + // apart marks each declaration naming, at some position, a node alike to + // the one there but declared apart (markApart), kept verbatim (keepApart). + apart []bool + // valueWrittenAt is where the value of each field the fold takes from one + // declaration is written (singleSource), nil until it takes one. + valueWrittenAt map[string]ir.Provenance } // note is one diagnostic the fold reports at a declaration. @@ -280,243 +385,346 @@ type note struct { sev ir.Severity code string message string - // detail is what a disagreement is over, and empty on any other note. - detail string - // at is where the note sits: where the declaration is reported - // (declaration.reportAt), or, for a disagreement, where it is written. + // disagreesOver is what a disagreement is over, and empty on any other note. + disagreesOver string + // heldField is, for a note that a declaration gives a field of a type the + // field holds otherwise (builder.differ), the name a document spells that + // field with, and empty on any other note. + heldField string + // at is where the note sits: where the declaration it is about is written + // (fieldPlace). at ir.Provenance - // kept is, for a disagreement, where the declaration whose say the field - // kept is written (ir.RelatedKept). - kept *ir.Provenance + // chosenAt is, for a note about a pair, where the declaration whose say the + // field took is written (ir.RelatedChosen), and nil on one about a single + // declaration. + chosenAt *ir.Provenance } -// newFolding judges every pair of decls once, picks the winner (widestCone) or +// newFieldFold judges every pair of decls once, picks the chosen declaration (widestCone) or // the types to compose (composition), and starts the field from the first // declaration, marked by no heuristic: the field names one only for a fact it // keeps that one promoted (foldUse, foldAnnotations). -func newFolding(merger *Merger, decls []declaration, field jsontext.Pointer) *folding { - n := len(decls) - ms := make([]member, n) +func newFieldFold(merger *Merger, decls []declaration, field jsontext.Pointer) *fieldFold { + declarationCount := len(decls) + ms := make([]member, declarationCount) for i, declaration := range decls { - ms[i] = member{ref: declaration.property.Type, decl: i} + ms[i] = member{ref: declaration.property.Type, decl: declarationIndex(i)} } position := merger.judgePosition(decls, ms, 0) - foldingValue := &folding{ - g: merger, decls: decls, field: field, pos: position, rel: position.rel, winner: position.winner, conjuncts: position.conjuncts, - cone: make([]bool, n), notes: make([][]note, n), lost: make([]bool, n), merged: decls[0].property, + folding := &fieldFold{ + g: merger, decls: decls, fieldPointer: field, pos: position, rel: position.rel, chosen: declarationIndex(position.chosen), conjuncts: position.conjuncts, + cone: make([]bool, declarationCount), notes: make([][]note, declarationCount), passedOver: make([]bool, declarationCount), apart: make([]bool, declarationCount), merged: decls[0].property, } - foldingValue.merged.Provenance.Inferred = "" - for i := range n { - foldingValue.cone[i] = len(foldingValue.conjuncts) > 0 || position.holds(foldingValue.winner, i) + folding.merged.Provenance.Inferred = "" + for i := range declarationCount { + folding.cone[i] = len(folding.conjuncts) > 0 || position.subsumes(int(folding.chosen), i) } - return foldingValue + return folding } // foldType settles the field's type: the model composing the conjuncts, or the -// node the winner and the declarations meeting it stand on (meetField), admitting +// node the chosen declaration and the declarations intersecting it rest on (intersectionField), admitting // null as position.null reads the cone. Every declaration outside the cone loses // its type (drop). -func (f *folding) foldType() { - target := f.meetField() - f.merged.Type = f.pos.null(registry{f.g.resolve}, func(i int) bool { return f.cone[i] }, 0) +func (f *fieldFold) foldType() { + target := f.intersectionField() + f.merged.Type = f.pos.null(f.g.registryReader(), func(i int) bool { return f.cone[i] }, 0) f.merged.Type.Target = target - for i := range f.decls { + for i := range declarationIndex(len(f.decls)) { if !f.cone[i] { f.drop(i) } } + if len(f.conjuncts) == 0 { + markApart(f, f.pos, func(i int) bool { return f.cone[i] }, target, 0) + } f.typeAt = f.g.typeSites(f.merged, f.decls) } -// meetField returns the field's target: the model the conjuncts compose, or the -// node the winner and the declarations meeting it stand on (builder). A dry run -// first, so a field whose meeting no node holds registers nothing: it keeps the -// winner's type, and each declaration meeting it leaves the cone, to be dropped -// and reported as an overlap. -func (f *folding) meetField() ir.TypeID { - b := builder{f: f} +// intersectionField returns the field's target: the model the conjuncts +// compose, or the node the chosen declaration and the declarations +// intersecting it rest on. A dry run comes first, so a field whose +// intersection no node holds registers nothing: it keeps the chosen +// declaration's type, and each declaration intersecting it leaves the cone, to +// be dropped and reported as an overlap. +func (f *fieldFold) intersectionField() ir.TypeID { + nodeBuilder := builder{f: f} if len(f.conjuncts) > 0 { - return b.compose(f.conjuncts, f.field) + return nodeBuilder.compose(f.conjuncts, f.fieldPointer) } cone := func(i int) bool { return f.cone[i] } - base, partners := f.pos.meeting(cone) + base, partners := f.pos.intersecting(cone, unheldCopy(f, f.pos)) dry := builder{f: f, dry: true} - dry.meetNode(base, partners, f.field, 0) + dry.intersectionNode(base, partners, f.fieldPointer, 0) if dry.failed { for _, member := range partners { f.cone[member.decl] = false } return base.ref.Target } - return b.meetNode(base, partners, f.field, 0) + return nodeBuilder.intersectionNode(base, partners, f.fieldPointer, 0) } -// PrunedDiagnostic pairs a drop diagnostic's full message (naming an anonymous -// losing TypeID) with the replacement message to substitute after -// post-settlement pruning if Loser is actually removed from Document.Types. -type PrunedDiagnostic struct { - Code string - Provenance ir.Provenance - Full string - Pruned string - Loser ir.TypeID +// unheldCopy reports, of the members of position, whether member k is written +// by a declaration the model holds alone, at a node hoisted there: nothing but +// this field holds that node, so what it says the node the field takes must +// hold. A node another model's declaration brings stays there, and one +// declared apart sits where it was declared. +func unheldCopy(fieldFold *fieldFold, position position) func(k int) bool { + return func(k int) bool { + declaration := fieldFold.decls[position.members[k].decl] + typeDef, ok := fieldFold.g.resolve(position.members[k].ref.Target) + chosenNode, held := fieldFold.g.resolve(position.members[position.chosen].ref.Target) + _, model := chosenNode.(*ir.Model) + return declaration.via == nil && ok && hoistedAt(typeDef, declaration.sites()) && + (!held || !model || !reflect.DeepEqual(siteless(*typeDef.Common()), siteless(*chosenNode.Common()))) + } } // drop reports how decls[i]'s type, which the field does not hold, relates to -// the winner's (typeJudge.relateFrom), even where nothing says how, since the type -// the field keeps then follows declaration order; and it marks the declaration -// lost. A type narrower than the winner that still lost shares its values. Its -// default, constraints and examples go with its type: they describe the shape -// that lost, and nothing downstream compares a Value's kind to its property's -// type, so adopting them would leave one field asserting two contradictory -// things. -func (f *folding) drop(i int) { - f.lost[i] = true - kept, loser := f.merged.Type.Target, f.decls[i].property.Type.Target - anonLoser := isAnonymousType(f, loser) - switch f.rel[f.winner][i] { +// the chosen declaration's, even where nothing says how, since the type the +// field keeps then follows declaration order; and it marks the declaration +// passed over. Its default, constraints and examples go with its type: they +// describe the shape passed over, and adopting them would leave one field +// asserting two contradictory things. +func (f *fieldFold) drop(i declarationIndex) { + f.passedOver[i] = true + chosenType, passedOverType := f.merged.Type.Target, f.decls[i].property.Type.Target + switch f.rel[f.chosen][i] { case relDisjoint: - fullDetail := fmt.Sprintf("incompatible types %s and %s", kept, loser) - f.disagree(i, f.winner, fullDetail) - if anonLoser { - prunedDetail := fmt.Sprintf("incompatible types (%s vs the declaration at %s)", kept, f.at(i)) - last := f.notes[i][len(f.notes[i])-1] - recordPrunedDiagnostic(f, last.code, last.at, last.message, - strings.Replace(last.message, fullDetail, prunedDetail, 1), loser) - } - case relOverlap, secondTypeIsNarrower, relMeet: - dropDegraded(f, i, kept, loser, anonLoser, "whose values overlap but that the merge does not narrow to one") + registry := f.g.registryReader() + disagreesOver := fmt.Sprintf("incompatible types %s and %s", typeNamed(registry, chosenType), typeNamed(registry, passedOverType)) + f.disagree(i, f.chosen, fieldGivenTogether, disagreesOver, typedAs(f, f.chosen)) + case relOverlap, secondTypeIsNarrower, relIntersect: + reportPassedOver(f, i, f.chosen, chosenType, passedOverType, "whose values overlap but that the merge does not narrow to one") + case relUndecided: + reportPassedOver(f, i, f.chosen, chosenType, passedOverType, "that the merge cannot show to share a value or to share none") default: - dropDegraded(f, i, kept, loser, anonLoser, "that the merge does not compare") + reportPassedOver(f, i, f.chosen, chosenType, passedOverType, "that the merge does not compare") } } -// isAnonymousType reports whether id resolves in fold's registry to an -// anonymous type. -func isAnonymousType(fold *folding, id ir.TypeID) bool { - td, ok := fold.g.resolve(id) - return ok && td.Common().Anonymous +// keepAnnotatedCopies marks passed over each declaration of the cone whose type +// the field does not take but one it takes admits alike, where none of those +// carries every annotation its type gives (annotatedApart): choosing one of two +// copies documented apart would drop the other's docs. A declaration so passed +// over is kept verbatim, its annotations with it (keepPassedOver). +func keepAnnotatedCopies(fieldFold *fieldFold) { + for i := range declarationIndex(len(fieldFold.decls)) { + if !fieldFold.cone[i] { + continue + } + chosenIndex, apart := annotatedApart(fieldFold, i) + if !apart { + continue + } + fieldFold.passedOver[i] = true + chosenType := fieldFold.merged.Type.Target + if len(fieldFold.conjuncts) > 0 { + chosenType = fieldFold.decls[chosenIndex].property.Type.Target + } + relation := "that admit the same values but are annotated apart" + if held := annotationsHeldApart(fieldFold, i); len(held) > 0 { + relation += " in the " + strings.Join(held, " and ") + " of a type it holds" + } + reportPassedOver(fieldFold, i, chosenIndex, chosenType, fieldFold.decls[i].property.Type.Target, relation) + } } -// dropDegraded records a degraded-construct drop diagnostic naming both kept -// and loser, and registers the alternate location-based message to substitute -// if post-settlement pruning removes an anonymous loser. -func dropDegraded(fold *folding, i int, kept, loser ir.TypeID, anonLoser bool, relation string) { - full := fmt.Sprintf("declarations of field %q give types %s and %s %s; kept the type the declaration at %s gives over the one at %s, which %s", - fold.merged.WireName, kept, loser, relation, fold.at(fold.winner), fold.at(i), fold.decls[i].keptAs()) - fold.note(i, ir.SeverityInfo, diag.DegradedConstruct, "%s", full) - if anonLoser { - last := fold.notes[i][len(fold.notes[i])-1] - pruned := fmt.Sprintf("declarations of field %q give types %s; kept %s (from %s) over the declaration at %s, which %s", - fold.merged.WireName, relation, kept, fold.at(fold.winner), fold.at(i), fold.decls[i].keptAs()) - recordPrunedDiagnostic(fold, last.code, last.at, full, pruned, loser) - } +// annotationFields are the names a document spells the fields of a type's +// TypeCommon with that give its annotations, as AnnotationsCarried reads them: +// its docs and its deprecation. +var annotationFields = []string{"deprecation", "docs"} + +// annotationsHeldApart takes from decls[i]'s notes each saying it gives an +// annotation of a type the field holds otherwise (builder.differ), which +// states the loss the report of a copy annotated apart states, and returns +// the annotations they name, sorted, each once, for that one report to name. +func annotationsHeldApart(fieldFold *fieldFold, i declarationIndex) []string { + var held []string + fieldFold.notes[i] = slices.DeleteFunc(fieldFold.notes[i], func(note note) bool { + if !slices.Contains(annotationFields, note.heldField) { + return false + } + held = append(held, note.heldField) + return true + }) + slices.Sort(held) + return slices.Compact(held) } -// recordPrunedDiagnostic appends an alternate post-pruning message to fold's -// Merger.PrunedDiagnostics slice when the caller collects them. -func recordPrunedDiagnostic(fold *folding, code string, at ir.Provenance, full, pruned string, loser ir.TypeID) { - if fold.g.PrunedDiagnostics == nil { - return +// annotatedApart returns the declaration whose type, one the field takes, +// admits what decls[i]'s does, and true where none such carries every +// annotation decls[i]'s gives (FieldDeclarationContext.AnnotationsCarried). +func annotatedApart(fieldFold *fieldFold, i declarationIndex) (declarationIndex, bool) { + chosenIndexes := []declarationIndex{fieldFold.chosen} + if len(fieldFold.conjuncts) > 0 { + chosenIndexes = chosenIndexes[:0] + for _, conjunct := range fieldFold.conjuncts { + chosenIndexes = append(chosenIndexes, conjunct.decl) + } } - *fold.g.PrunedDiagnostics = append(*fold.g.PrunedDiagnostics, PrunedDiagnostic{ - Code: code, - Provenance: at, - Full: full, - Pruned: pruned, - Loser: loser, - }) + other := fieldFold.decls[i].property.Type.Target + found, apart := declarationIndex(0), false + for _, chosenIndex := range chosenIndexes { + target := fieldFold.decls[chosenIndex].property.Type.Target + if target == other { + return chosenIndex, false + } + switch fieldFold.g.Walk.AnnotationsCarried(target, other) { + case AlikeAnnotationsCarried: + return chosenIndex, false + case AlikeAnnotatedApart: + if !apart { + found, apart = chosenIndex, true + } + default: // TypesAdmitApart: no copy of other. + } + } + return found, apart +} + +// reportPassedOver notes at decls[i] that its type, passedOverType, which the +// field does not take, and chosenType, the type decls[chosenIndex] gives, +// relate as relation says, naming as chosen the first written of the +// declarations giving chosenType (chosenDeclaration). +func reportPassedOver(fold *fieldFold, i, chosenIndex declarationIndex, chosenType, passedOverType ir.TypeID, relation string) { + chosenFirst := chosenDeclaration(fold, chosenIndex, typedAs(fold, chosenIndex), fieldGivenTogether) + passedOverAt, chosenPlace := fieldPlace(fold.g, fold.decls[i], fieldGivenTogether), fieldPlace(fold.g, fold.decls[chosenFirst], fieldGivenTogether) + registry := fold.g.registryReader() + gives := fmt.Sprintf("give types %s and %s %s", typeNamed(registry, chosenType), typeNamed(registry, passedOverType), relation) + fold.notes[i] = append(fold.notes[i], note{sev: ir.SeverityInfo, code: diag.DegradedConstruct, at: passedOverAt, chosenAt: &chosenPlace, + message: aboutPair(fold, i, passedOverAt, chosenPlace, gives, "the type the first gives")}) } // disagree notes the conflicting-redeclaration warning at decls[i], which says -// something of the field, detail, that decls[kept] says otherwise, and marks it -// lost. Warning, not info: the two cannot both hold, or no one value states -// them. It says "declarations", since one can sit beside allOf, not in an -// entry. A keyword a position writes on its node and its property is met -// twice, and said once. It sits where decls[i] is written, not at the entry -// bringing it, so every model composing the two says it alike (ReportOnce), -// and it carries where decls[kept] is written, the place its message names. -func (f *folding) disagree(i, kept int, detail string) { - f.lost[i] = true - if slices.ContainsFunc(f.notes[i], func(noteValue note) bool { return noteValue.detail == detail }) { +// something of reportedField, disagreesOver, that decls[chosenIndex] says +// otherwise, and marks it passed over. Warning, not info: the two cannot both +// hold, or no one value states them. It names as chosen the first written of +// the declarations agreeing with decls[chosenIndex], agrees saying which. +func (f *fieldFold) disagree(i, chosenIndex declarationIndex, reportedField, disagreesOver string, agrees func(declarationIndex) bool) { + f.passedOver[i] = true + if slices.ContainsFunc(f.notes[i], func(note note) bool { return note.disagreesOver == disagreesOver }) { return } - at, keptAt := f.place(i), f.place(kept) - f.notes[i] = append(f.notes[i], note{sev: ir.SeverityWarning, code: diag.ConflictingRedecl, detail: detail, at: at, - kept: &keptAt, - message: fmt.Sprintf("declarations of field %q disagree: %s; kept what the declaration at %s says over the one "+ - "at %s, which %s", f.merged.WireName, detail, f.named(keptAt, at.Source), f.named(at, at.Source), - f.decls[i].keptAs())}) + chosenFirst := chosenDeclaration(f, chosenIndex, agrees, reportedField) + passedOverAt, chosenPlace := fieldPlace(f.g, f.decls[i], reportedField), fieldPlace(f.g, f.decls[chosenFirst], reportedField) + f.notes[i] = append(f.notes[i], note{sev: ir.SeverityWarning, code: diag.ConflictingRedecl, disagreesOver: disagreesOver, at: passedOverAt, chosenAt: &chosenPlace, + message: aboutPair(f, i, passedOverAt, chosenPlace, "disagree: "+disagreesOver, "what the first says")}) } -// at is how a report the fold makes at a declaration (note), which stands in -// the composing model's document, names where decls[i] was written (place). -func (f *folding) at(i int) string { - return f.named(f.place(i), f.g.Doc.Source) +// fieldPlace is where declaration writes field, the field a report about it is +// about, in its own document: for a settled member whose fold took field from +// one declaration, where that one writes it; else, as for fieldGivenTogether, +// where it is written, or, written nowhere, at the model settling it. A place +// in the composing model's document, or in none in range, reads as g.Doc +// places it. +func fieldPlace(merger *Merger, declaration declaration, field string) ir.Provenance { + written, single := declaration.valueWrittenAt[field] + if !single { + written = declaration.property.Provenance + if declaration.via != nil && len(declaration.typeAt) == 1 { + written = declaration.typeAt[0] + } + if written.Pointer == declaration.property.Provenance.Pointer { + if owner, unwritten := unwrittenOwner(merger, declaration); unwritten { + written = owner.Provenance + } + } + } + if written.Source == merger.Doc.Source || written.Source < 0 || written.Source >= len(merger.Sources) { + return merger.Doc.At(written.Pointer) + } + return ir.Provenance{Source: written.Source, Pointer: written.Pointer, WrittenBy: written.WrittenBy} } -// named is how a report standing in the document in names irProvenance, a -// place: its pointer, followed by its document's name where that is another -// document, in which the pointer alone would read as one in the report's. -func (f *folding) named(irProvenance ir.Provenance, in int) string { - if irProvenance.Source == in { - return string(irProvenance.Pointer) +// placeName is how a report written in the document in names place: its +// pointer, followed by the name sources gives its document where that is +// another, in which the pointer alone would read as one in the report's; a +// document's root, which the empty pointer names, by that name alone, or as +// the document root in the report's own. A source out of range is the +// report's. +func placeName(sources []ir.SourceInfo, place ir.Provenance, in int) string { + another := place.Source != in && place.Source >= 0 && place.Source < len(sources) + switch { + case !another && place.Pointer == "": + return "the document root" + case !another: + return string(place.Pointer) + case place.Pointer == "": + return sources[place.Source].Path + default: + return string(place.Pointer) + " in " + sources[place.Source].Path } - return string(irProvenance.Pointer) + " in " + f.g.Sources[irProvenance.Source].Path } -// place is where decls[i] was written, in its own document, as a declaration -// an entry brings may be written in another. A member an entry brings settled -// names its first declaration, which need not say what the member does, so -// its place is the one place its type is written, or, where that is the -// member's own and no schema is written there (unwritten), the entry bringing -// it. A source out of range reads as the composing model's document. -func (f *folding) place(i int) ir.Provenance { - declaration := f.decls[i] - irProvenance := declaration.property.Provenance - if declaration.via != nil && len(declaration.typeAt) == 1 { - irProvenance = declaration.typeAt[0] - } - if irProvenance.Pointer == declaration.property.Provenance.Pointer && f.unwritten(declaration) { - return f.g.Doc.At(declaration.via.at) +// chosenDeclaration is the declaration a report about a pair names as chosen: +// the first written (writtenBefore) of decls[chosenIndex] and the declarations +// agrees says give what it gives, so no order of the declarations decides which +// of several agreeing ones a report names. Each declaration is placed where it +// writes field, the field the report is about (fieldPlace). +func chosenDeclaration(fieldFold *fieldFold, chosenIndex declarationIndex, agrees func(declarationIndex) bool, reportedField string) declarationIndex { + out := chosenIndex + for j := range declarationIndex(len(fieldFold.decls)) { + if j != out && agrees(j) && writtenBefore(fieldPlace(fieldFold.g, fieldFold.decls[j], reportedField), fieldPlace(fieldFold.g, fieldFold.decls[out], reportedField)) { + out = j + } } - if irProvenance.Source == f.g.Doc.Source || irProvenance.Source < 0 || irProvenance.Source >= len(f.g.Sources) { - return f.g.Doc.At(irProvenance.Pointer) + return out +} + +// writtenFirst orders two of f's declarations, by index, as a report about +// what they give together places them (fieldPlace): whether the first is written +// before the second. +func writtenFirst(fieldFold *fieldFold) func(i, j declarationIndex) bool { + return func(i, j declarationIndex) bool { + return writtenBefore(fieldPlace(fieldFold.g, fieldFold.decls[i], fieldGivenTogether), fieldPlace(fieldFold.g, fieldFold.decls[j], fieldGivenTogether)) } - return ir.Provenance{Source: irProvenance.Source, Pointer: irProvenance.Pointer, WrittenBy: irProvenance.WrittenBy} } -// unwritten reports whether declarationValue is a member an entry brings that -// its model's composition settled where no schema is written (settledAt). -func (f *folding) unwritten(declarationValue declaration) bool { - if declarationValue.via == nil { - return false +// fieldGivenTogether names no field one declaration gives: a report about the type, +// its bounds or its visibility, which several declarations give jointly. +const fieldGivenTogether = "" + +// typedAs is the agreement of a type drop: a declaration agrees with +// decls[chosenIndex] where it names the type that one does. +func typedAs(fieldFold *fieldFold, chosenIndex declarationIndex) func(declarationIndex) bool { + target := fieldFold.decls[chosenIndex].property.Type.Target + return func(j declarationIndex) bool { return fieldFold.decls[j].property.Type.Target == target } +} + +// unwrittenOwner returns the model declaring declaration, and whether that is +// a member an entry brings that the model's composition settled where no +// schema is written (settledAt). +func unwrittenOwner(merger *Merger, declaration declaration) (*ir.Model, bool) { + if declaration.via == nil { + return nil, false } - td, _ := f.g.resolve(declarationValue.owner) - model, isModel := td.(*ir.Model) + typeDef, _ := merger.resolve(declaration.owner) + model, isModel := typeDef.(*ir.Model) if !isModel { - return false + return nil, false } - at, wire := declarationValue.property.Provenance.Pointer, declarationValue.property.WireName - return at == settledAt(model, wire, false) || at == settledAt(model, wire, true) + at, wire := declaration.property.Provenance.Pointer, declaration.property.WireName + return model, at == settledAt(model, wire, false) || at == settledAt(model, wire, true) } -// foldConstraints meets the constraints the cone writes on the property. Where +// foldConstraints intersects the constraints the cone writes on the property. Where // the fold composes the field's model, which holds no bound, the bounds of each -// declaration's own node meet there too (ownBounds): its property leaves them to -// that node, which the composed model does not stand for. -func (f *folding) foldConstraints() { +// declaration's own node intersect there too (ownBounds): its property leaves them to +// that node, which the composed model does not represent. +func (f *fieldFold) foldConstraints() { sets := make([]*ir.Constraints, len(f.decls)) for i, declaration := range f.decls { switch { case !f.cone[i]: case len(f.conjuncts) > 0: - sets[i] = metOrNil(declaration.property.Constraints, f.ownBounds(i)) + sets[i] = intersectedOrNil(declaration.property.Constraints, f.ownBounds(declarationIndex(i))) default: sets[i] = declaration.property.Constraints } } - f.merged.Constraints = meetConstraints(sets, f.disagree) + f.merged.Constraints = intersectConstraints(sets, writtenFirst(f), f.disagree) } // ownBounds returns the value bounds held by the node decls[i]'s type names @@ -524,43 +732,42 @@ func (f *folding) foldConstraints() { // otherwise: a property owning its node leaves those bounds to it // (docs/compilers/openapi.md#constraints). A List's or a Tuple's are read by // no property, which never held them. -func (f *folding) ownBounds(i int) *ir.Constraints { +func (f *fieldFold) ownBounds(i declarationIndex) *ir.Constraints { declaration := f.decls[i] - td, ok := f.g.resolve(declaration.property.Type.Target) - if !ok || !hoistedAt(td, declaration.sites()) { + typeDef, ok := f.g.resolve(declaration.property.Type.Target) + if !ok || !hoistedAt(typeDef, declaration.sites()) { return nil } - switch n := td.(type) { + switch node := typeDef.(type) { case *ir.Model: - return n.Constraints + return node.Constraints case *ir.MapT: - return n.Constraints + return node.Constraints case *ir.Scalar: - return n.Constraints + return node.Constraints case *ir.Union: - return n.Constraints + return node.Constraints default: return nil } } -// metOrNil returns a copy of a and b met (Constraints), writing to neither, or -// nil where both are. -func metOrNil(a, b *ir.Constraints) *ir.Constraints { +// intersectedOrNil returns a copy of a and b intersected (Constraints), writing +// to neither, or nil where both are. +func intersectedOrNil(a, b *ir.Constraints) *ir.Constraints { if a == nil && b == nil { return nil } - var met ir.Constraints - return Constraints(Constraints(&met, a), b) + var intersected ir.Constraints + return Constraints(Constraints(&intersected, a), b) } // foldValues settles the default and the examples from the cone. A value the // field does not take (takes) is refused, reported and kept at the declaration -// that wrote it; of the rest, the last written is kept, and a declaration +// that wrote it; of the rest, the last written is chosen, and a declaration // writing another is reported and kept. Refusing first means a value the field -// takes is kept whichever order the declarations come in. -func (f *folding) foldValues() { - nullable := f.merged.Type.Nullable || registry{f.g.resolve}.isAnyType(f.merged.Type) +// takes is chosen whichever order the declarations come in. +func (f *fieldFold) foldValues() { takesDefault := make([]bool, len(f.decls)) takesExamples := make([]bool, len(f.decls)) for i, declaration := range f.decls { @@ -568,37 +775,51 @@ func (f *folding) foldValues() { continue } var refused []string - takesDefault[i] = declaration.property.Default == nil || f.takes(i, *declaration.property.Default, nullable) + takesDefault[i] = declaration.property.Default == nil || f.adopts(declarationIndex(i), *declaration.property.Default) if !takesDefault[i] { refused = append(refused, "default") } takesExamples[i] = !slices.ContainsFunc(declaration.property.Examples, func(example ir.Example) bool { - return example.Value != nil && !f.takes(i, *example.Value, nullable) + return example.Value != nil && !f.adopts(declarationIndex(i), *example.Value) }) if !takesExamples[i] { refused = append(refused, "examples") } if len(refused) > 0 { - f.lost[i] = true - f.refuse(i, refused) + f.passedOver[i] = true + f.refuse(declarationIndex(i), refused) } } - f.merged.Default = lastWritten(f, "default", func(i int, property *ir.Property) (*ir.Value, bool) { + f.merged.Default = lastWritten(f, "default", func(i declarationIndex, property *ir.Property) (*ir.Value, bool) { return property.Default, takesDefault[i] && property.Default != nil }, func(a, b *ir.Value) bool { return sameValue(*a, *b) }) - f.merged.Examples = lastWritten(f, "examples", func(i int, property *ir.Property) ([]ir.Example, bool) { + f.merged.Examples = lastWritten(f, "examples", func(i declarationIndex, property *ir.Property) ([]ir.Example, bool) { return property.Examples, takesExamples[i] && len(property.Examples) > 0 }, sameExamples) } // refuse notes at decls[i] that the field does not adopt the values it gives, // what, its default, its examples or both, which the merged type is not shown -// to admit. -func (f *folding) refuse(i int, what []string) { - f.note(i, ir.SeverityInfo, diag.DegradedConstruct, - "the merge cannot show that the type the declarations of field %q merge to admits the %s the "+ - "declaration at %s gives; not adopted, and that declaration %s", - f.merged.WireName, strings.Join(what, " and "), f.at(i), f.decls[i].keptAs()) +// to admit: both in one note where one place writes them, and each in its own +// at its place where a settled member took them from two (fieldPlace). +func (f *fieldFold) refuse(i declarationIndex, what []string) { + if len(what) > 1 && fieldPlace(f.g, f.decls[i], what[0]) != fieldPlace(f.g, f.decls[i], what[1]) { + for _, field := range what { + noteRefusal(f, i, []string{field}) + } + return + } + noteRefusal(f, i, what) +} + +// noteRefusal notes at decls[i] that the field does not adopt what it gives, +// values one place writes, there and naming it. +func noteRefusal(fieldFold *fieldFold, i declarationIndex, what []string) { + at := fieldPlace(fieldFold.g, fieldFold.decls[i], what[0]) + fieldFold.notes[i] = append(fieldFold.notes[i], note{sev: ir.SeverityInfo, code: diag.DegradedConstruct, at: at, message: fmt.Sprintf( + "field %q: the merge cannot show that the type its declarations merge to admits the %s %s gives; not adopted, "+ + "and that declaration %s", fieldFold.merged.WireName, strings.Join(what, " and "), placeName(fieldFold.g.Sources, at, at.Source), + fieldFold.decls[i].keptAs())}) } // sameExamples reports whether two example lists say the same, each example's @@ -614,80 +835,118 @@ func sameExamples(a, b []ir.Example) bool { }) } -// takes reports whether the field takes value, which decls[i] wrote: a null -// where the field admits null, which the top type always does (nullable), and -// any other value every bound another declaration brought admits, where -// decls[i]'s own type is the field's, but for those bounds (ownType), or the -// field's type admits it. A value a declaration writes against its own type and -// bounds is that declaration's to answer for, and a composed field has no -// declaration whose type it is. The field's type is read where its nodes are -// written (typeAt), not at the winner alone. -func (f *folding) takes(i int, value ir.Value, nullable bool) bool { - if value.Kind == ir.ValueNull { - return nullable - } +// adopts reports whether the field adopts value, which decls[i] wrote: unless +// something shows the value outside what the field admits. It is refused only +// where a bound another declaration carried, an entry another kept verbatim, +// or the run's value admission reader, judging it against the field's type +// and the bounds decls[i]'s property states, says no; a fact none of them can +// read, as a pattern it cannot evaluate, refuses nothing. +func (f *fieldFold) adopts(i declarationIndex, value ir.Value) bool { own := &f.decls[i].property judge := f.g.judgeAt(f.typeAt, f.decls[i].sites()) - if !admitsConstraints(boundsBeyond(allBounds(judge, &f.merged), allBounds(judge, own)), value, 0) { - return false - } - if len(f.conjuncts) == 0 && f.ownType(judge, i) { - return true + beyond := boundsBeyond(allBounds(judge, &f.merged), allBounds(judge, own)) + return ir.ConstraintsAdmit(beyond, value) != ir.AdmitsNo && othersEntriesAdmit(f, i, value) && + valueAdmission(f.g.registryReader()).AdmitsAtPosition(f.merged.Type, own.Constraints, value) != ir.AdmitsNo +} + +// othersEntriesAdmit reports whether each keyword a declaration of the cone +// but decls[i] keeps verbatim with no IR home on its carrier, and decls[i] +// does not keep alike, admits value as OpenAPI, the source format, reads it +// (carriedEntriesAdmit): a text bound kept beside a type that does not take it +// binds the field's value as one typed would. +func othersEntriesAdmit(fieldFold *fieldFold, i declarationIndex, value ir.Value) bool { + own := fieldFold.decls[i].property.Unmodeled + for j, declaration := range fieldFold.decls { + if declarationIndex(j) == i || !fieldFold.cone[j] { + continue + } + fromEntries := maps.Clone(declaration.property.Unmodeled) + maps.DeleteFunc(fromEntries, func(key string, entry ir.UnmodeledEntry) bool { + mine, held := own[key] + return held && bytes.Equal(mine.Value, entry.Value) + }) + if !carriedEntriesAdmit(fromEntries, value) { + return false + } } - ref := f.merged.Type - ref.Nullable = nullable - return judge.admits(ref, value) + return true } -// ownType reports whether decls[i]'s type is the field's but for bounds: the -// same as the winner's or alike it, where the field keeps the winner's node, -// and alike the node the merge built for the field otherwise, which can hold -// members or values the winner's does not (builder). -func (f *folding) ownType(judge typeJudge, i int) bool { - winner, own := f.decls[f.winner].property.Type, f.decls[i].property.Type - if f.merged.Type.Target == winner.Target { - return f.rel[f.winner][i] == relSame || sameTypeIgnoringBounds(judge, winner, own) +// carriedEntriesAdmit reports whether no keyword a field keeps verbatim with no +// IR home, a text bound its type does not take among them, refuses value as +// OpenAPI, the source format, reads it (sourceFormatAdmissions). +func carriedEntriesAdmit(unmodeled ir.Unmodeled, value ir.Value) bool { + for key, entry := range unmodeled { + if entry.Reason == ir.ReasonNoIRHome && (sourceFormatAdmissions{}).AdmitsUnderUnmodeledEntry(key, entry, value) == ir.AdmitsNo { + return false + } } - return sameTypeIgnoringBounds(judge, f.merged.Type, own) + return true } // foldUse settles who sends the field and sees it: required and secret where -// any declaration says so, and visible only in the lifecycles every declaration -// admits (mergeVisibility). A promoted redaction brings its marker (secretBy) -// in either order, and a declared one brings none, whatever else that -// declaration's marker covers. Declarations that empty a set none had emptied -// on its own are reported where the last of them is written; nothing is -// discarded, so nothing is kept. -func (f *folding) foldUse() { +// any declaration says so, and visible only in the lifecycles every +// declaration admits. A promoted redaction brings its marker in either order, +// and a declared one brings none. Declarations that empty a set none empties +// on its own are reported once (reportDisjointVisibility); one that does is +// its own reader's to report. +func (f *fieldFold) foldUse() { for i, declaration := range f.decls { f.merged.Required = f.merged.Required || declaration.property.Required f.merged.Secret = f.merged.Secret || declaration.property.Secret f.merged.Provenance.Inferred = ir.JoinInferred(f.merged.Provenance.Inferred, declaration.secretBy) - if i == 0 { - continue + if i > 0 { + f.merged.Visibility = mergeVisibility(f.merged.Visibility, declaration.property.Visibility) } - visibility := mergeVisibility(f.merged.Visibility, declaration.property.Visibility) - if visibility.InvisibleInEveryLifecycle && !f.merged.Visibility.InvisibleInEveryLifecycle && !declaration.property.Visibility.InvisibleInEveryLifecycle { - f.note(i, ir.SeverityWarning, diag.DisjointVisibility, - "allOf entries restrict field %q to disjoint lifecycles; the merged field is visible in none", - f.merged.WireName) + } + emptiedAlone := slices.ContainsFunc(f.decls, func(declaration declaration) bool { + return declaration.property.Visibility.InvisibleInEveryLifecycle + }) + if f.merged.Visibility.InvisibleInEveryLifecycle && !emptiedAlone { + reportDisjointVisibility(f) + } +} + +// reportDisjointVisibility reports that the declarations restricting the +// field's lifecycles, each writing readOnly or writeOnly, leave it visible in +// none: at the first of them written (writtenBefore), naming each in that +// order, so no order of the declarations decides where it sits or what it says. +// foldUse calls it only where no declaration is visible in none alone, so each +// restricting one names the lifecycles it keeps (ir.Visibility.Only). +func reportDisjointVisibility(fieldFold *fieldFold) { + var restricting []declarationIndex + for i, declaration := range fieldFold.decls { + if len(declaration.property.Visibility.Only) > 0 { + restricting = append(restricting, declarationIndex(i)) } - f.merged.Visibility = visibility } + places := make([]ir.Provenance, len(fieldFold.decls)) + for _, i := range restricting { + places[i] = fieldPlace(fieldFold.g, fieldFold.decls[i], fieldGivenTogether) + } + slices.SortStableFunc(restricting, func(a, b declarationIndex) int { return compareSourceOrder(places[a], places[b]) }) + first := restricting[0] + named := make([]string, len(restricting)) + for k, i := range restricting { + named[k] = placeName(fieldFold.g.Sources, places[i], places[first].Source) + " (" + listed(fieldFold.decls[i].property.Visibility.Only) + ")" + } + fieldFold.note(first, ir.SeverityWarning, diag.DisjointVisibility, + "field %q: its declarations restrict it to disjoint lifecycles, %s; the merged field is visible in none", + fieldFold.merged.WireName, listed(slices.Compact(named))) } // foldDocs settles the field's title, description and external links, each the // last declaration's to give one (lastWritten), from every declaration: docs // describe the field, not a shape, so a dropped declaration's count too. -func (f *folding) foldDocs() { +func (f *fieldFold) foldDocs() { same := func(a, b string) bool { return a == b } - f.merged.Docs.Summary = lastWritten(f, "title", func(_ int, property *ir.Property) (string, bool) { + f.merged.Docs.Summary = lastWritten(f, "title", func(_ declarationIndex, property *ir.Property) (string, bool) { return property.Docs.Summary, property.Docs.Summary != "" }, same) - f.merged.Docs.Description = lastWritten(f, "description", func(_ int, property *ir.Property) (string, bool) { + f.merged.Docs.Description = lastWritten(f, "description", func(_ declarationIndex, property *ir.Property) (string, bool) { return property.Docs.Description, property.Docs.Description != "" }, same) - f.merged.Docs.ExternalDocs = lastWritten(f, "external docs", func(_ int, property *ir.Property) ([]ir.Link, bool) { + f.merged.Docs.ExternalDocs = lastWritten(f, "external docs", func(_ declarationIndex, property *ir.Property) ([]ir.Link, bool) { return property.Docs.ExternalDocs, len(property.Docs.ExternalDocs) > 0 }, slices.Equal[[]ir.Link]) } @@ -705,8 +964,8 @@ func sameDeprecation(a, b *ir.Deprecation) bool { // declaration it read (promotion.Promoter.Deprecation), so the field takes the // marker of the declaration whose deprecation it keeps, whichever declaration // that is. -func (f *folding) foldAnnotations() { - f.merged.Deprecation = lastWritten(f, "deprecation", func(_ int, property *ir.Property) (*ir.Deprecation, bool) { +func (f *fieldFold) foldAnnotations() { + f.merged.Deprecation = lastWritten(f, "deprecation", func(_ declarationIndex, property *ir.Property) (*ir.Deprecation, bool) { return property.Deprecation, property.Deprecation != nil }, sameDeprecation) for _, declaration := range slices.Backward(f.decls) { @@ -716,65 +975,88 @@ func (f *folding) foldAnnotations() { } } // XMLHints.Wrapped is a pointer, which == would compare by address. - f.merged.XML = lastWritten(f, "xml", func(_ int, property *ir.Property) (*ir.XMLHints, bool) { + f.merged.XML = lastWritten(f, "xml", func(_ declarationIndex, property *ir.Property) (*ir.XMLHints, bool) { return property.XML, property.XML != nil }, func(a, b *ir.XMLHints) bool { return reflect.DeepEqual(a, b) }) } -// lastWritten returns the last value of detail a declaration gives (of), or the -// zero value when none gives one: a later declaration is where a spec writes -// the specialization. An earlier one giving a value that is not the same is -// reported and kept: the field has one slot for it. +// lastWritten returns the last value of reportedField a declaration gives +// (of), or the zero value when none gives one: a later declaration is where a +// spec writes the specialization. An earlier one giving a value that is not +// the same is reported and kept: the field has one slot for it. // // Each caller says what is the same. A Value or an example list compares // deeply, which tells a nil slice from an empty one, but every declaration was // lowered by the same code, so two spellings the source wrote alike cannot land // on opposite sides. -func lastWritten[T any](foldingValue *folding, detail string, of func(i int, property *ir.Property) (T, bool), same func(a, b T) bool) T { - var kept T - at := -1 - for i := len(foldingValue.decls) - 1; i >= 0; i-- { - v, gives := of(i, &foldingValue.decls[i].property) +func lastWritten[T any](folding *fieldFold, reportedField string, of func(i declarationIndex, property *ir.Property) (T, bool), same func(a, b T) bool) T { + var chosen T + at, found := declarationIndex(0), false + givesKept := func(j declarationIndex) bool { + otherValue, givesToo := of(j, &folding.decls[j].property) + return givesToo && same(chosen, otherValue) + } + for i := declarationIndex(len(folding.decls)) - 1; i >= 0; i-- { + declaredValue, gives := of(i, &folding.decls[i].property) switch { case !gives: - case at < 0: - kept, at = v, i - case !same(kept, v): - foldingValue.lost[i] = true - foldingValue.note(i, ir.SeverityInfo, diag.DegradedConstruct, - "declarations of field %q give its %s differently; kept the one the declaration at %s gives "+ - "over the one at %s, which %s", - foldingValue.merged.WireName, detail, foldingValue.at(at), foldingValue.at(i), foldingValue.decls[i].keptAs()) + case !found: + chosen, at, found = declaredValue, i, true + case !same(chosen, declaredValue): + folding.passedOver[i] = true + chosenFirst := chosenDeclaration(folding, at, givesKept, reportedField) + passedOverAt, chosenPlace := fieldPlace(folding.g, folding.decls[i], reportedField), fieldPlace(folding.g, folding.decls[chosenFirst], reportedField) + folding.notes[i] = append(folding.notes[i], note{sev: ir.SeverityInfo, code: diag.DegradedConstruct, at: passedOverAt, chosenAt: &chosenPlace, + message: aboutPair(folding, i, passedOverAt, chosenPlace, "give its "+reportedField+" differently", "the one the first gives")}) } } - return kept + if found { + singleSource(folding, reportedField, at, givesKept) + } + return chosen } -// note records a diagnostic for decls[i], reported when the fold finishes. -func (f *folding) note(i int, sev ir.Severity, code, format string, args ...any) { - f.notes[i] = append(f.notes[i], note{sev: sev, code: code, message: fmt.Sprintf(format, args...), - at: f.g.Doc.At(f.decls[i].reportAt())}) +// singleSource records that field's value is the one decls[chosenIndex] and +// those agrees names give, and so is written where the first written of them +// writes it (fieldFold.valueWrittenAt). +func singleSource(fieldFold *fieldFold, reportedField string, chosenIndex declarationIndex, agrees func(declarationIndex) bool) { + if fieldFold.valueWrittenAt == nil { + fieldFold.valueWrittenAt = map[string]ir.Provenance{} + } + fieldFold.valueWrittenAt[reportedField] = fieldPlace(fieldFold.g, fieldFold.decls[chosenDeclaration(fieldFold, chosenIndex, agrees, reportedField)], reportedField) } -// foldUnmodeled unions every declaration's Unmodeled into the field's. The keys -// are namespaced, so each entry lands; a key two declarations give is the last -// one's, and an earlier one keeping another construct under it is reported and -// kept, as lastWritten keeps a detail. Of two keeping one construct, the one -// written first in the documents' order (writtenBefore) is kept, so no order -// of the declarations decides where the field says it was written. Keys are -// read in order, so the reports are. -func (f *folding) foldUnmodeled() { +// note records a diagnostic about decls[i] alone, reported when the fold +// finishes where that declaration is written (fieldPlace). +func (f *fieldFold) note(i declarationIndex, sev ir.Severity, code, format string, args ...any) { + f.notes[i] = append(f.notes[i], note{sev: sev, code: code, message: fmt.Sprintf(format, args...), at: fieldPlace(f.g, f.decls[i], fieldGivenTogether)}) +} + +// foldUnmodeled unions every declaration's Unmodeled into the field's: a key +// two declarations give is the last one's, and an earlier one keeping another +// construct under it is reported and kept. Of two keeping one construct, the +// first written is chosen, so no order of the declarations decides where the +// field says it was written. A structure the field's type narrows gives the +// $ref it keeps verbatim with the rest (keptReferences). +func (f *fieldFold) foldUnmodeled() { var merged ir.Unmodeled - from := map[string]int{} - for i := len(f.decls) - 1; i >= 0; i-- { + from := map[string]declarationIndex{} + for i := declarationIndex(len(f.decls)) - 1; i >= 0; i-- { declaration := f.decls[i] - for _, key := range slices.Sorted(maps.Keys(declaration.property.Unmodeled)) { - entry := declaration.property.Unmodeled[key] + given := declaration.property.Unmodeled + if f.cone[i] && declaration.property.Type.Target != f.merged.Type.Target { + given = withNarrowedStructureReferences(f.g.registryReader(), declaration.property.Type.Target, given) + } + if !f.cone[i] { + given = withoutShapeEntries(declaration.property.Provenance, given) + } + for _, key := range slices.Sorted(maps.Keys(given)) { + entry := given[key] at, seen := from[key] switch { case !seen: if merged == nil { - merged = make(ir.Unmodeled, len(declaration.property.Unmodeled)) + merged = make(ir.Unmodeled, len(given)) } merged[key], from[key] = entry, i case sameEntry(f.g.Walk, merged[key], entry): @@ -782,49 +1064,88 @@ func (f *folding) foldUnmodeled() { merged[key] = entry } default: - f.lost[i] = true - f.note(i, ir.SeverityInfo, diag.DegradedConstruct, - "declarations of field %q give its %s differently; kept the one the declaration at %s gives "+ - "over the one at %s, which %s", - f.merged.WireName, key, f.at(at), f.at(i), f.decls[i].keptAs()) + f.passedOver[i] = true + chosenFirst := chosenDeclaration(f, at, keepsEntry(f, merged, key), key) + passedOverAt, chosenPlace := fieldPlace(f.g, f.decls[i], key), fieldPlace(f.g, f.decls[chosenFirst], key) + f.notes[i] = append(f.notes[i], note{sev: ir.SeverityInfo, code: diag.DegradedConstruct, at: passedOverAt, chosenAt: &chosenPlace, + message: aboutPair(f, i, passedOverAt, chosenPlace, "give its "+key+" differently", "the one the first gives")}) } } } + for _, key := range slices.Sorted(maps.Keys(from)) { + singleSource(f, key, from[key], keepsEntry(f, merged, key)) + } f.merged.Unmodeled = merged } -// writtenBefore reports whether a is written before b: in a document listed -// before b's, which the load phase orders by name, not as declarations reach -// it, or in one document at a pointer sorting first. Two files each holding -// one schema write the same pointers. -func writtenBefore(a, b ir.Provenance) bool { - return cmp.Or(cmp.Compare(a.Source, b.Source), cmp.Compare(a.Pointer, b.Pointer)) < 0 +// withNarrowedStructureReferences returns given, what a declaration whose type is target +// keeps, with the references a structure target represents keeps verbatim +// (keptReferences): the field's type narrows the structure, which no node +// then holds. +func withNarrowedStructureReferences(reg registryReader, target ir.TypeID, given ir.Unmodeled) ir.Unmodeled { + typeDef, ok := reg.resolve(target) + if !ok { + return given + } + end := reg.unaliased(typeDef) + references := keptReferences(end.Common().Unmodeled) + if !isStructural(end) || len(references) == 0 { + return given + } + out := maps.Clone(references) + maps.Copy(out, given) + return out +} + +// keepsEntry is which declarations give key the entry merged keeps under it. +func keepsEntry(fieldFold *fieldFold, merged ir.Unmodeled, key string) func(declarationIndex) bool { + return func(j declarationIndex) bool { + other, holds := fieldFold.decls[j].property.Unmodeled[key] + return holds && sameEntry(fieldFold.g.Walk, merged[key], other) + } } // sameEntry reports whether a and b, the entry two declarations give one key, -// are one: written alike, and read against one base where they write a -// reference (FieldDeclarationContext.Alike), which the same text under another -// base may read as another schema. +// are one: written alike, and, where they write a reference, admitting alike +// where each is written (FieldDeclarationContext.DeclarationsAdmitAlike), as the same text may +// name another schema under another base. func sameEntry(walk FieldDeclarationContext, a, b ir.UnmodeledEntry) bool { - return bytes.Equal(a.Value, b.Value) && (!annotation.WritesReference(a.Value) || walk.Alike(a.Provenance, b.Provenance)) + return bytes.Equal(a.Value, b.Value) && (!annotation.WritesReference(a.Value) || walk.DeclarationsAdmitAlike(a.Provenance, b.Provenance)) } -// finish returns the field and, declaration by declaration, what the fold -// noted there (note.at), keeping each declaration the model declares that it -// lost something of verbatim (keepLosingDeclaration). -func (f *folding) finish() (ir.Property, []ir.Diagnostic) { +// finish returns the field and, declaration by declaration, what the fold noted +// there (note.at), keeping each declaration the model declares that it passed +// over something of verbatim (keepPassedOver). +func (f *fieldFold) finish() (ir.Property, []ir.Diagnostic) { var diags []ir.Diagnostic - for i, declaration := range f.decls { - for _, note := range f.notes[i] { - diagnostic := diag.Newf(note.sev, note.code, note.at, "%s", note.message) - if note.kept != nil { - diagnostic.Related = []ir.Related{{Role: ir.RelatedKept, Provenance: *note.kept}} - } - diags = append(diags, diagnostic) - } - if f.lost[i] && declaration.via == nil { - diags = append(diags, f.g.keepLosingDeclaration(&f.merged, declaration.property.Provenance, declaration.source)...) - } + for i := range declarationIndex(len(f.decls)) { + diags = appendNoteDiagnostics(diags, f.notes[i]...) + diags = append(diags, f.keepPassedOver(i)...) } return f.merged, diags } + +// keepPassedOver keeps decls[i] verbatim beside the field where the fold passed +// over something of it and the model declares it (keepPassedOverDeclaration), +// and returns what keeping it reports. +func (f *fieldFold) keepPassedOver(i declarationIndex) []ir.Diagnostic { + declaration := f.decls[i] + if !f.passedOver[i] || declaration.via != nil { + return nil + } + return f.g.keepPassedOverDeclaration(&f.merged, declaration.property.Provenance, declaration.source) +} + +// appendNoteDiagnostics appends to diags what notes say, each where it sits +// (note.at), naming where the declaration it chose is written where it is +// about a pair (ir.RelatedChosen). +func appendNoteDiagnostics(diags []ir.Diagnostic, notes ...note) []ir.Diagnostic { + for _, note := range notes { + diagnostic := diag.Newf(note.sev, note.code, note.at, "%s", note.message) + if note.chosenAt != nil { + diagnostic.Related = []ir.Related{{Role: ir.RelatedChosen, Provenance: *note.chosenAt}} + } + diags = append(diags, diagnostic) + } + return diags +} diff --git a/compilers/openapi/internal/merge/fold_annotations_internal_test.go b/compilers/openapi/internal/merge/fold_annotations_internal_test.go new file mode 100644 index 000000000..cf9c5a82a --- /dev/null +++ b/compilers/openapi/internal/merge/fold_annotations_internal_test.go @@ -0,0 +1,119 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "reflect" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestFold_ACopyAnnotatedApartIsKeptVerbatim pins the fold of declarations +// whose types the walk shows admit alike (FieldDeclarationContext.AnnotationsCarried), +// in either order: a copy the field's type does not carry, its description +// apart, is reported once and kept verbatim, and so is one a part of a +// composition holds; one whose description the field's type gives, or one +// that does not admit alike, is not. +func TestFold_ACopyAnnotatedApartIsKeptVerbatim(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + targets []ir.TypeID + description string + alike [][2]ir.TypeID + kept ir.TypeID + }{ + "two copies apart": {[]ir.TypeID{"type/copy0", "type/copy1"}, "two", [][2]ir.TypeID{{"type/copy0", "type/copy1"}}, "type/copy1"}, + "a copy carried": {[]ir.TypeID{"type/copy0", "type/copy1"}, "", [][2]ir.TypeID{{"type/copy0", "type/copy1"}}, ""}, + "two copies not alike": {[]ir.TypeID{"type/copy0", "type/copy1"}, "two", nil, ""}, + "a copy of a part": {[]ir.TypeID{"type/Owner", "type/copy1", "type/Addr"}, "two", + [][2]ir.TypeID{{"type/Owner", "type/copy1"}}, "type/copy1"}, + } { + for _, order := range permutationsOf(len(tc.targets)) { + reg := alikeRegistry() + reg["type/copy0"] = &ir.Scalar{ID: "type/copy0", Anonymous: true, Docs: ir.Docs{Description: "one"}, + Provenance: ptrAt(declaredAt(0)), Base: &ir.TypeRef{Target: "type/primitive/string"}} + if tc.targets[0] == "type/copy0" { + reg["type/copy1"] = &ir.Scalar{ID: "type/copy1", Anonymous: true, Docs: ir.Docs{Description: tc.description}, + Provenance: ptrAt(declaredAt(1)), Base: &ir.TypeRef{Target: "type/primitive/string"}} + } else { + reg["type/copy1"].Common().Docs.Description = tc.description + } + stubbed, recorded := stubMerger(reg) + stubbed.walk.alike = map[[2]ir.TypeID]bool{} + for _, pair := range tc.alike { + stubbed.walk.alike[pair], stubbed.walk.alike[[2]ir.TypeID{pair[1], pair[0]}] = true, true + } + decls := make([]declaration, len(order)) + for k, at := range order { + decls[k] = nthDecl(at, tc.targets[at]) + } + + merged := stubbed.fold(decls) + + reports := slices.DeleteFunc(slices.Clone(*recorded), func(diagnostic ir.Diagnostic) bool { + return !strings.Contains(diagnostic.Message, "annotated apart") + }) + if tc.kept == "" { + assert.Empty(t, reports, "%s %v", name, order) + continue + } + if assert.Len(t, reports, 1, "%s %v", name, order) { + assert.Equal(t, declaredAt(slices.Index(tc.targets, tc.kept)), reports[0].Provenance.Pointer, "%s %v", name, order) + } + assert.Contains(t, merged.Unmodeled, passedOverDeclarationKey+string(declaredAt(slices.Index(tc.targets, tc.kept))), "%s %v", name, order) + } + } +} + +// permutationsOf returns every order of 0..n-1. +func permutationsOf(count int) [][]int { + if count == 1 { + return [][]int{{0}} + } + var out [][]int + for _, rest := range permutationsOf(count - 1) { + for at := range count { + out = append(out, slices.Insert(slices.Clone(rest), at, count-1)) + } + } + return out +} + +// TestAnnotationsHeldApart_TakesTheNotesOnAHeldTypesAnnotations pins what a +// copy annotated apart folds into its one report: each note that it gives the +// docs or the deprecation of a type the field holds otherwise, named once and +// sorted, while a note on any other field of a held type, and any other note, +// stays its own. +func TestAnnotationsHeldApart_TakesTheNotesOnAHeldTypesAnnotations(t *testing.T) { + t.Parallel() + f := &fieldFold{notes: [][]note{{ + {message: "docs", heldField: "docs"}, {message: "examples", heldField: "examples"}, + {message: "deprecation", heldField: "deprecation"}, {message: "docs again", heldField: "docs"}, {message: "plain"}, + }}} + + held := annotationsHeldApart(f, 0) + + assert.Equal(t, []string{"deprecation", "docs"}, held) + left := make([]string, 0, len(f.notes[0])) + for _, note := range f.notes[0] { + left = append(left, note.message) + } + assert.Equal(t, []string{"examples", "plain"}, left) +} + +// TestAnnotationFields_NameTheAnnotationsOfATypeCommon holds annotationFields +// to the names a document spells the TypeCommon fields giving a type's +// annotations with, its Docs and its Deprecation (jsonName). +func TestAnnotationFields_NameTheAnnotationsOfATypeCommon(t *testing.T) { + t.Parallel() + common := reflect.TypeFor[ir.TypeCommon]() + docs, _ := common.FieldByName("Docs") + deprecation, _ := common.FieldByName("Deprecation") + assert.ElementsMatch(t, []string{jsonName(docs), jsonName(deprecation)}, annotationFields) +} diff --git a/compilers/openapi/internal/merge/fold_cases_internal_test.go b/compilers/openapi/internal/merge/fold_cases_internal_test.go index 4cfa05429..6e87464f8 100644 --- a/compilers/openapi/internal/merge/fold_cases_internal_test.go +++ b/compilers/openapi/internal/merge/fold_cases_internal_test.go @@ -73,14 +73,14 @@ func TestKindOf_EnumResolvesThroughItsValueType(t *testing.T) { assert.Empty(t, kind.format) } -// TestFold_ALosingDetailIsKeptAndReported sweeps the fold's -// adopt-if-absent fields. Each of them once took one declaration's value and -// dropped a present, different value from the other with nothing said and -// nothing kept — a consumer diffing two revisions that change the losing -// entry's default saw no change. Now the merge keeps the later declaration's -// value, says which detail disagreed, and keeps the losing declaration -// verbatim, under the same key a losing type is kept under, since it is the -// same event: a declaration the merge could not fold whole. +// TestFold_ALosingDetailIsKeptAndReported sweeps the fold's adopt-if-absent +// fields. Each of them once took one declaration's value and dropped a present, +// different value from the other with nothing said and nothing kept — a +// consumer diffing two revisions that change the passed-over entry's default +// saw no change. Now the merge keeps the later declaration's value, says which +// detail disagreed, and keeps the passed-over declaration verbatim, under the +// same key a passed-over type is kept under, since it is the same event: a +// declaration the merge could not fold whole. func TestFold_ALosingDetailIsKeptAndReported(t *testing.T) { t.Parallel() one, two := &ir.Value{Kind: ir.ValueNumber, Number: "1"}, &ir.Value{Kind: ir.ValueNumber, Number: "2"} @@ -122,7 +122,7 @@ func TestFold_ALosingDetailIsKeptAndReported(t *testing.T) { assert.Contains(t, diagnostic.Message, `"id"`) assert.Contains(t, diagnostic.Message, tc.detail, "the message names the detail that disagreed") assert.Equal(t, ir.Unmodeled{ - losingDeclarationKey + "/allOf/0/properties/id": { + passedOverDeclarationKey + "/allOf/0/properties/id": { Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(firstSource), Provenance: ir.Provenance{Source: 1, Pointer: "/allOf/0/properties/id"}, @@ -159,29 +159,29 @@ func TestFold_AnIdenticalDetailIsNotADisagreement(t *testing.T) { assert.Empty(t, dst.Unmodeled) } -// TestFold_AnUnrenderableLoserIsAnError pins the one way keeping +// TestFold_AnUnrenderablePassedOverDeclarationIsAnError pins the one way keeping // the declaration can fail. The merge has already said the redeclaration is // kept, so a source that will not render is reported as an error — the // construct reached the IR in no form — rather than left to the announcement. -func TestFold_AnUnrenderableLoserIsAnError(t *testing.T) { +func TestFold_AnUnrenderablePassedOverDeclarationIsAnError(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(map[ir.TypeID]ir.TypeDef{ "type/str": &ir.Primitive{ID: "type/str", PrimitiveKind: ir.PrimitiveString}, "type/int": &ir.Primitive{ID: "type/int", PrimitiveKind: ir.PrimitiveInt32}, }) - loser := ir.Property{WireName: "id", Type: ir.TypeRef{Target: "type/str"}, Provenance: ptrAt("/a")} - winner := ir.Property{WireName: "id", Type: ir.TypeRef{Target: "type/int"}, Provenance: ptrAt("/b")} + passedOver := ir.Property{WireName: "id", Type: ir.TypeRef{Target: "type/str"}, Provenance: ptrAt("/a")} + chosen := ir.Property{WireName: "id", Type: ir.TypeRef{Target: "type/int"}, Provenance: ptrAt("/b")} dst := stubbed.fold([]declaration{ - {property: loser, source: func() (ir.RawValue, error) { return nil, errors.New("no such node") }}, - {property: winner, source: unread(t)}, + {property: passedOver, source: func() (ir.RawValue, error) { return nil, errors.New("no such node") }}, + {property: chosen, source: unread(t)}, }) require.Len(t, *recorded, 2, "the conflict, and then the failure to keep it; got %v", *recorded) assert.Equal(t, diag.ConflictingRedecl, (*recorded)[0].Code) assert.Equal(t, diag.UnpreservableConstruct, (*recorded)[1].Code) assert.Equal(t, ir.SeverityError, (*recorded)[1].Severity) - assert.Empty(t, dst.Unmodeled, "nothing claims a preservation that did not happen") + assert.Empty(t, dst.Unmodeled, "nothing reports a preservation that did not happen") } // narrowingRegistry holds one bare primitive per kind the narrowing tests pair. @@ -202,14 +202,14 @@ func primitiveRef(primitiveKind ir.PrimitiveKind) ir.TypeRef { return ir.TypeRef{Target: ir.TypeID("type/primitive/" + string(primitiveKind))} } -// TestFold_AnInadmissibleValueIsKeptNotAdopted pins that no -// declaration of a fold lands a default or example the merged field does not -// admit: the field carries no such value, and one info and one Unmodeled entry -// sit at each declaration that wrote it, identical whichever comes first. The -// table holds the broad side's kind refusals (a fractional default, an -// out-of-range default, a non-UUID example) and a null the merged field no -// longer admits; the helpers add every writer, late writers, and a null on -// either side of a fold. +// TestFold_AnInadmissibleValueIsKeptNotAdopted pins that no declaration of a +// fold lands a default or example the merged field does not admit: the field +// carries no such value, and one info and one Unmodeled entry sit at each +// declaration that wrote it, identical whichever comes first. The table holds +// the broad side's kind refusals (a fractional default, an out-of-range +// default, a non-UUID example) and a null the merged field no longer admits; +// the helpers add every declaration writing it, late ones, and a null on either +// side of a fold. func TestFold_AnInadmissibleValueIsKeptNotAdopted(t *testing.T) { t.Parallel() const broadPtr, narrowPtr = "/allOf/0/properties/p", "/allOf/1/properties/p" @@ -296,8 +296,8 @@ func TestFold_AnInadmissibleValueIsKeptNotAdopted(t *testing.T) { // assertANullTheMergedFieldRefusesIsKeptAtItsWriter holds that a null default // is judged on the declaration that wrote it, whichever side of the fold that // is and whether the fold narrowed or kept one target: the field ends -// non-nullable with no default, and one info and one entry sit at the writer -// alone, in every order of the declarations. +// non-nullable with no default, and one info and one entry sit at the +// declaration writing it alone, in every order of the declarations. func assertANullTheMergedFieldRefusesIsKeptAtItsWriter(t *testing.T) { t.Helper() null := ir.Value{Kind: ir.ValueNull} @@ -308,7 +308,7 @@ func assertANullTheMergedFieldRefusesIsKeptAtItsWriter(t *testing.T) { nullIntEx := decl{kind: ir.PrimitiveInteger, nullable: true, examples: []ir.Value{null}, raw: `{"type":["integer","null"],"examples":[null]}`} for _, tc := range []struct { name string - decls []decl // the null writer is first + decls []decl // the declaration writing null is first }{ {"a null example, narrow against a number", []decl{nullIntEx, plainNumber}}, {"a null example, the same target", []decl{nullIntEx, plainInt}}, @@ -319,12 +319,12 @@ func assertANullTheMergedFieldRefusesIsKeptAtItsWriter(t *testing.T) { } { for _, order := range permutations(len(tc.decls)) { placed := make([]decl, len(order)) - var writer decl + var nullDeclaration decl for pos, which := range order { placed[pos] = tc.decls[which] placed[pos].ptr = jsontext.Pointer("/allOf/" + string(rune('0'+pos))) if which == 0 { - writer = placed[pos] + nullDeclaration = placed[pos] } } label := fmt.Sprintf("%s %v", tc.name, order) @@ -333,10 +333,10 @@ func assertANullTheMergedFieldRefusesIsKeptAtItsWriter(t *testing.T) { assert.False(t, got.Type.Nullable, label) assert.Nil(t, got.Default, label) assert.Empty(t, got.Examples, label) - assert.Equal(t, entry(writer), got.Unmodeled, "%s: kept at the null writer alone", label) + assert.Equal(t, entry(nullDeclaration), got.Unmodeled, "%s: kept at the declaration writing null alone", label) require.Len(t, diags, 1, "%s: one info", label) assert.Equal(t, ir.SeverityInfo, diags[0].Severity, label) - assert.Equal(t, writer.ptr, diags[0].Provenance.Pointer, "%s: at the writer", label) + assert.Equal(t, nullDeclaration.ptr, diags[0].Provenance.Pointer, "%s: at the declaration writing null", label) } } } @@ -348,16 +348,16 @@ func assertTheTopTypeKeepsANull(t *testing.T) { t.Helper() null := ir.Value{Kind: ir.ValueNull} plain := decl{kind: ir.PrimitiveAny, raw: `{"description":"x"}`} - for _, writer := range []decl{ + for _, valueDeclaration := range []decl{ {kind: ir.PrimitiveAny, def: &null, raw: `{"default":null}`}, {kind: ir.PrimitiveAny, examples: []ir.Value{null}, raw: `{"examples":[null]}`}, } { - for _, order := range [][]decl{{writer, plain}, {plain, writer}} { + for _, order := range [][]decl{{valueDeclaration, plain}, {plain, valueDeclaration}} { label := fmt.Sprintf("%s first", order[0].raw) order[0].ptr, order[1].ptr = "/allOf/0", "/allOf/1" got, diags := mergeDecls(t, order...) - assert.Equal(t, writer.def, got.Default, label) - assert.Len(t, got.Examples, len(writer.examples), label) + assert.Equal(t, valueDeclaration.def, got.Default, label) + assert.Len(t, got.Examples, len(valueDeclaration.examples), label) assert.Empty(t, got.Unmodeled, label) assert.Empty(t, diags, label) } @@ -365,9 +365,9 @@ func assertTheTopTypeKeepsANull(t *testing.T) { } // permutations returns every ordering of 0..n-1. -func permutations(n int) [][]int { +func permutations(count int) [][]int { all := [][]int{{}} - for k := range n { + for k := range count { next := make([][]int, 0, len(all)*(k+1)) for _, rest := range all { for at := 0; at <= len(rest); at++ { @@ -412,9 +412,9 @@ func mergeDecls(t *testing.T, decls ...decl) (ir.Property, []ir.Diagnostic) { } // entry is the Unmodeled entry a kept declaration lands as. -func entry(declValue decl) ir.Unmodeled { - return ir.Unmodeled{losingDeclarationKey + string(declValue.ptr): { - Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(declValue.raw), Provenance: ptrAt(declValue.ptr), +func entry(decl decl) ir.Unmodeled { + return ir.Unmodeled{passedOverDeclarationKey + string(decl.ptr): { + Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(decl.raw), Provenance: ptrAt(decl.ptr), }} } @@ -428,9 +428,9 @@ func assertThreeDeclarationsKeepTheWritingOne(t *testing.T) { wide := decl{ptr: "/allOf/0", kind: ir.PrimitiveNumber, raw: `{"type":"number"}`} narrow := decl{ptr: "/allOf/2", kind: ir.PrimitiveInteger, raw: `{"type":"integer"}`} for _, tc := range []struct { - name string - writer decl - keyword string + name string + valueDeclaration decl + keyword string }{ {"default", decl{ptr: "/allOf/1", kind: ir.PrimitiveNumber, def: &half, raw: `{"type":"number","default":1.5}`}, "default"}, @@ -438,16 +438,16 @@ func assertThreeDeclarationsKeepTheWritingOne(t *testing.T) { raw: `{"type":"number","examples":[2.5]}`}, "examples"}, } { for name, order := range map[string][]decl{ - "abc": {wide, tc.writer, narrow}, "cab": {narrow, wide, tc.writer}, "bca": {tc.writer, narrow, wide}, + "abc": {wide, tc.valueDeclaration, narrow}, "cab": {narrow, wide, tc.valueDeclaration}, "bca": {tc.valueDeclaration, narrow, wide}, } { got, diags := mergeDecls(t, order...) label := tc.name + " " + name assert.Equal(t, primitiveRef(ir.PrimitiveInteger).Target, got.Type.Target, label) assert.Nil(t, got.Default, label) assert.Empty(t, got.Examples, label) - assert.Equal(t, entry(tc.writer), got.Unmodeled, "%s: kept at the declaration that wrote it", label) + assert.Equal(t, entry(tc.valueDeclaration), got.Unmodeled, "%s: kept at the declaration that wrote it", label) require.Len(t, diags, 1, label) - assert.Equal(t, tc.writer.ptr, diags[0].Provenance.Pointer, "%s: the info names it", label) + assert.Equal(t, tc.valueDeclaration.ptr, diags[0].Provenance.Pointer, "%s: the info names it", label) assert.Contains(t, diags[0].Message, tc.keyword, label) } } @@ -459,17 +459,17 @@ func assertThreeDeclarationsKeepTheWritingOne(t *testing.T) { func assertEveryWriterOfARefusedValueIsKept(t *testing.T) { t.Helper() half, two := number("1.5"), number("2.5") - for _, kw := range []string{"default", "examples"} { - writer := func(name string) decl { - declValue := decl{kind: ir.PrimitiveNumber, raw: `{"writer":"` + name + `"}`} - if kw == "default" { - declValue.def = &half + for _, keyword := range []string{"default", "examples"} { + valueDeclaration := func(name string) decl { + decl := decl{kind: ir.PrimitiveNumber, raw: `{"writer":"` + name + `"}`} + if keyword == "default" { + decl.def = &half } else { - declValue.examples = []ir.Value{two} + decl.examples = []ir.Value{two} } - return declValue + return decl } - decls := map[string]decl{"a": writer("a"), "b": writer("b"), "c": {kind: ir.PrimitiveInteger, raw: `{"type":"integer"}`}} + decls := map[string]decl{"a": valueDeclaration("a"), "b": valueDeclaration("b"), "c": {kind: ir.PrimitiveInteger, raw: `{"type":"integer"}`}} for _, order := range []string{"abc", "acb", "bac", "bca", "cab", "cba"} { placed := make([]decl, 0, len(order)) want := ir.Unmodeled{} @@ -479,20 +479,20 @@ func assertEveryWriterOfARefusedValueIsKept(t *testing.T) { decl.ptr = jsontext.Pointer("/allOf/" + string(rune('0'+i))) placed = append(placed, decl) if name != 'c' { - want[losingDeclarationKey+string(decl.ptr)] = entry(decl)[losingDeclarationKey+string(decl.ptr)] + want[passedOverDeclarationKey+string(decl.ptr)] = entry(decl)[passedOverDeclarationKey+string(decl.ptr)] wantPtrs = append(wantPtrs, decl.ptr) } } - label := kw + " " + order + label := keyword + " " + order got, diags := mergeDecls(t, placed...) assert.Equal(t, primitiveRef(ir.PrimitiveInteger).Target, got.Type.Target, label) assert.Nil(t, got.Default, label) assert.Empty(t, got.Examples, label) - assert.Equal(t, want, got.Unmodeled, "%s: both writers are kept, and only they", label) + assert.Equal(t, want, got.Unmodeled, "%s: both declarations writing it are kept, and only they", label) gotPtrs := make([]jsontext.Pointer, 0, len(diags)) for _, diagnostic := range diags { gotPtrs = append(gotPtrs, diagnostic.Provenance.Pointer) - assert.Contains(t, diagnostic.Message, kw, label) + assert.Contains(t, diagnostic.Message, keyword, label) } assert.ElementsMatch(t, wantPtrs, gotPtrs, "%s: and both are reported", label) } @@ -513,8 +513,8 @@ func assertRefusedValuesAreKeptAtTheirOwnDeclarations(t *testing.T) { got, diags := mergeDecls(t, defaulted, exampled, narrow) assert.Equal(t, ir.Unmodeled{ - losingDeclarationKey + "/allOf/0": entry(defaulted)[losingDeclarationKey+"/allOf/0"], - losingDeclarationKey + "/allOf/1": entry(exampled)[losingDeclarationKey+"/allOf/1"], + passedOverDeclarationKey + "/allOf/0": entry(defaulted)[passedOverDeclarationKey+"/allOf/0"], + passedOverDeclarationKey + "/allOf/1": entry(exampled)[passedOverDeclarationKey+"/allOf/1"], }, got.Unmodeled, "a default and examples from different declarations are two entries") require.Len(t, diags, 2, "and two infos") assert.Equal(t, jsontext.Pointer("/allOf/0"), diags[0].Provenance.Pointer) @@ -533,8 +533,8 @@ func assertRefusedValuesAreKeptAtTheirOwnDeclarations(t *testing.T) { last := decl{ptr: "/allOf/2", kind: ir.PrimitiveInt32, raw: `{"last":1}`} got, diags = mergeDecls(t, defaulted, late, last) assert.Equal(t, ir.Unmodeled{ - losingDeclarationKey + "/allOf/0": entry(defaulted)[losingDeclarationKey+"/allOf/0"], - losingDeclarationKey + "/allOf/1": entry(late)[losingDeclarationKey+"/allOf/1"], + passedOverDeclarationKey + "/allOf/0": entry(defaulted)[passedOverDeclarationKey+"/allOf/0"], + passedOverDeclarationKey + "/allOf/1": entry(late)[passedOverDeclarationKey+"/allOf/1"], }, got.Unmodeled, "a value adopted after a refusal is kept at the declaration that wrote it") require.Len(t, diags, 2) assert.Equal(t, jsontext.Pointer("/allOf/0"), diags[0].Provenance.Pointer) diff --git a/compilers/openapi/internal/merge/fold_docs_internal_test.go b/compilers/openapi/internal/merge/fold_docs_internal_test.go index 6fe70eadb..1106d9007 100644 --- a/compilers/openapi/internal/merge/fold_docs_internal_test.go +++ b/compilers/openapi/internal/merge/fold_docs_internal_test.go @@ -15,10 +15,11 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestFold_DifferingDescriptionsKeepTheLater pins a merge outcome -// that is reported without being a conflict: two entries describing the same -// field differently cannot both be kept, so the later wins, the loss is -// announced rather than silent, and the losing declaration is kept whole. +// TestFold_DifferingDescriptionsKeepTheLater pins a merge outcome that is +// reported without being a conflict: two entries describing the same field +// differently cannot both be kept, so the later is chosen, the loss is +// announced rather than left unreported, and the passed-over declaration is +// kept whole. func TestFold_DifferingDescriptionsKeepTheLater(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(nil) @@ -31,10 +32,10 @@ func TestFold_DifferingDescriptionsKeepTheLater(t *testing.T) { require.Len(t, *recorded, 1) assert.Equal(t, ir.SeverityInfo, (*recorded)[0].Severity) assert.Equal(t, diag.DegradedConstruct, (*recorded)[0].Code) - assert.Equal(t, jsontext.Pointer("/first"), (*recorded)[0].Provenance.Pointer, "at the declaration that lost") + assert.Equal(t, jsontext.Pointer("/first"), (*recorded)[0].Provenance.Pointer, "at the declaration passed over") assert.Contains(t, (*recorded)[0].Message, `"id"`) assert.Contains(t, (*recorded)[0].Message, "description") - assert.Equal(t, ir.RawValue(firstSource), dst.Unmodeled[losingDeclarationKey+"/first"].Value) + assert.Equal(t, ir.RawValue(firstSource), dst.Unmodeled[passedOverDeclarationKey+"/first"].Value) } // TestFold_AnIdenticalDescriptionIsNotADisagreement pins the other @@ -60,14 +61,14 @@ func TestFold_TitleAndExternalDocsFoldLikeDescription(t *testing.T) { t.Parallel() linkA := []ir.Link{{URL: "https://a.example"}} linkB := []ir.Link{{URL: "https://b.example"}} - summary := func(s string) ir.Docs { return ir.Docs{Summary: s} } + summary := func(text string) ir.Docs { return ir.Docs{Summary: text} } links := func(links []ir.Link) ir.Docs { return ir.Docs{ExternalDocs: links} } tests := []struct { name string dst, src ir.Docs want ir.Docs - detail string // empty when nothing is lost + detail string // empty when nothing is passed over }{ {"summary, dst empty", summary(""), summary("B"), summary("B"), ""}, {"summary, src empty", summary("A"), summary(""), summary("A"), ""}, @@ -102,7 +103,7 @@ func TestFold_TitleAndExternalDocsFoldLikeDescription(t *testing.T) { assert.Contains(t, (*recorded)[0].Message, `"id"`) assert.Contains(t, (*recorded)[0].Message, tt.detail) require.Len(t, dst.Unmodeled, 1) - entry, ok := dst.Unmodeled[losingDeclarationKey+"/first"] + entry, ok := dst.Unmodeled[passedOverDeclarationKey+"/first"] require.True(t, ok) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) assert.Equal(t, ir.RawValue(firstSource), entry.Value) @@ -130,5 +131,5 @@ func TestFold_EveryDocsDisagreementIsReported(t *testing.T) { assert.Contains(t, (*recorded)[i].Message, detail) } require.Len(t, dst.Unmodeled, 1) - assert.Equal(t, ir.RawValue(firstSource), dst.Unmodeled[losingDeclarationKey+"/first"].Value) + assert.Equal(t, ir.RawValue(firstSource), dst.Unmodeled[passedOverDeclarationKey+"/first"].Value) } diff --git a/compilers/openapi/internal/merge/fold_internal_test.go b/compilers/openapi/internal/merge/fold_internal_test.go index 6e9346acc..a52b7e776 100644 --- a/compilers/openapi/internal/merge/fold_internal_test.go +++ b/compilers/openapi/internal/merge/fold_internal_test.go @@ -71,7 +71,7 @@ func foldInEveryOrder(t *testing.T, decls ...declaration) []foldOutcome { // TestFold_TheSetDecidesWhateverTheOrder pins the fold over the whole set: a // type that holds every other declaration's is the field's in every order, and // where none does, the type that loses the fewest declarations is, each it -// loses being reported. A chain folded pair by pair kept int32 over uint32, +// loses being reported. A chain taken pair by pair kept int32 over uint32, // reporting the overlap and keeping uint32, then narrowed to uint16 anyway, // while the same declarations in another order drew nothing. func TestFold_TheSetDecidesWhateverTheOrder(t *testing.T) { @@ -89,7 +89,7 @@ func TestFold_TheSetDecidesWhateverTheOrder(t *testing.T) { kindDecl(ir.PrimitiveNumber, nil), kindDecl(ir.PrimitiveString, nil), kindDecl(ir.PrimitiveInt32, nil), }, foldOutcome{ typ: primitiveRef(ir.PrimitiveInt32), - kept: []string{losingDeclarationKey + "/k/string"}, + kept: []string{passedOverDeclarationKey + "/k/string"}, diags: []string{diag.ConflictingRedecl + " /k/string"}, }}, {"a value the field takes, from any declaration", []declaration{ @@ -97,7 +97,7 @@ func TestFold_TheSetDecidesWhateverTheOrder(t *testing.T) { }, foldOutcome{ typ: primitiveRef(ir.PrimitiveInteger), def: &two, - kept: []string{losingDeclarationKey + "/k/number"}, + kept: []string{passedOverDeclarationKey + "/k/number"}, diags: []string{diag.DegradedConstruct + " /k/number"}, }}, } { @@ -120,56 +120,67 @@ func TestFold_ATieGoesToTheLaterAndIsReported(t *testing.T) { assert.Equal(t, primitiveRef(order[1]), got.Type) require.Len(t, *recorded, 1) assert.Equal(t, diag.DegradedConstruct, (*recorded)[0].Code, "an overlap is an info") - assert.Contains(t, got.Unmodeled, losingDeclarationKey+"/k/"+string(order[0])) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+"/k/"+string(order[0])) } } // TestFold_ADroppedFirstDeclarationIsKept pins that the declaration whose -// identity the field keeps can lose its type like any other: it is reported -// and kept verbatim at its own pointer. +// identity the field keeps, the one written at the shortest pointer +// (identityDeclaration), can lose its type like any other: it is reported and +// kept verbatim at its own pointer. func TestFold_ADroppedFirstDeclarationIsKept(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(narrowingRegistry()) - first := kindDecl(ir.PrimitiveString, nil) + chosenIdentity := kindDecl(ir.PrimitiveString, nil) + chosenIdentity.property.Provenance = ptrAt("/k/s") - got := stubbed.fold([]declaration{first, kindDecl(ir.PrimitiveInt32, nil), kindDecl(ir.PrimitiveNumber, nil)}) + got := stubbed.fold([]declaration{chosenIdentity, kindDecl(ir.PrimitiveInt32, nil), kindDecl(ir.PrimitiveNumber, nil)}) assert.Equal(t, primitiveRef(ir.PrimitiveInt32), got.Type) - assert.Equal(t, first.property.Provenance, got.Provenance, "the field keeps the first declaration's identity") + assert.Equal(t, chosenIdentity.property.Provenance, got.Provenance, "the field keeps the chosen declaration's identity") require.Len(t, *recorded, 1) assert.Equal(t, diag.ConflictingRedecl, (*recorded)[0].Code) - assert.Equal(t, jsontext.Pointer("/k/string"), (*recorded)[0].Provenance.Pointer) - assert.Equal(t, ir.RawValue(`{"k":"string"}`), got.Unmodeled[losingDeclarationKey+"/k/string"].Value) + assert.Equal(t, jsontext.Pointer("/k/s"), (*recorded)[0].Provenance.Pointer) + assert.Equal(t, ir.RawValue(`{"k":"string"}`), got.Unmodeled[passedOverDeclarationKey+"/k/s"].Value) } // TestFold_AConstraintConflictNamesTheDeclarationKeptFrom pins where a -// constraint conflict points: at the declaration that wrote the value kept, -// which is not the last declaration where that one sets none. +// constraint conflict points +// (docs/compilers/openapi.md#allof-redeclared-property): at the declaration +// passed over, naming as chosen the first written of the declarations giving +// the value kept, never the last declaration where that one sets none, and the +// same one in either order of those agreeing. func TestFold_AConstraintConflictNamesTheDeclarationKeptFrom(t *testing.T) { t.Parallel() - stubbed, recorded := stubMerger(narrowingRegistry()) - pattern := func(p string) *ir.Constraints { return &ir.Constraints{Pattern: p} } + pattern := func(path string) *ir.Constraints { return &ir.Constraints{Pattern: path} } d := func(at string, constraints *ir.Constraints) declaration { return declaration{ property: ir.Property{WireName: "p", Type: primitiveRef(ir.PrimitiveString), Constraints: constraints, Provenance: ptrAt(jsontext.Pointer(at))}, source: written(`{}`), } } + for name, decls := range map[string][]declaration{ + "as written": {d("/a", pattern("^y$")), d("/b", pattern("^x$")), d("/c", pattern("^x$")), d("/d", nil)}, + "reversed": {d("/a", pattern("^y$")), d("/c", pattern("^x$")), d("/b", pattern("^x$")), d("/d", nil)}, + } { + stubbed, recorded := stubMerger(narrowingRegistry()) - got := stubbed.fold([]declaration{d("/a", pattern("^y$")), d("/b", pattern("^x$")), d("/c", pattern("^x$")), d("/d", nil)}) + got := stubbed.fold(decls) - require.NotNil(t, got.Constraints) - assert.Equal(t, "^x$", got.Constraints.Pattern) - require.Len(t, *recorded, 1, "an agreeing declaration is no conflict") - assert.Equal(t, jsontext.Pointer("/a"), (*recorded)[0].Provenance.Pointer) - assert.Contains(t, (*recorded)[0].Message, "kept what the declaration at /c says over the one at /a", - "the last to write the kept value is named, not one agreeing with it") + require.NotNil(t, got.Constraints, name) + assert.Equal(t, "^x$", got.Constraints.Pattern, name) + require.Len(t, *recorded, 1, "%s: an agreeing declaration is no conflict", name) + assert.Equal(t, jsontext.Pointer("/a"), (*recorded)[0].Provenance.Pointer, name) + assert.Contains(t, (*recorded)[0].Message, `field "p": /b and /a disagree: conflicting pattern ("^x$" and "^y$"); chose what the first says`, name) + require.Len(t, (*recorded)[0].Related, 1, name) + assert.Equal(t, ir.Related{Role: ir.RelatedChosen, Provenance: ptrAt("/b")}, (*recorded)[0].Related[0], name) + } } // TestFold_ADroppedDeclarationStillSaysWhatIsNotShape pins what a declaration // whose type the field drops still contributes: whether the field is required -// or secret, and its docs where no declaration after it gives any. None of -// them describes the shape that lost. +// or secret, and its docs where no declaration after it gives any. None of them +// describes the shape passed over. func TestFold_ADroppedDeclarationStillSaysWhatIsNotShape(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(narrowingRegistry()) @@ -186,7 +197,7 @@ func TestFold_ADroppedDeclarationStillSaysWhatIsNotShape(t *testing.T) { assert.Equal(t, "a count", got.Docs.Description) require.Len(t, *recorded, 1) assert.Equal(t, diag.ConflictingRedecl, (*recorded)[0].Code) - assert.Contains(t, got.Unmodeled, losingDeclarationKey+"/k/integer") + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+"/k/integer") } // stringAt returns a declaration of field p typed string, written at pointer, @@ -221,13 +232,13 @@ func TestFold_UnmodeledKeepsTheLastOfAKeyAndReportsAnother(t *testing.T) { got := stubbed.fold(order) - assert.Equal(t, kept.property.Unmodeled["x-shared"], got.Unmodeled["x-shared"], "the later declaration's value stands") + assert.Equal(t, kept.property.Unmodeled["x-shared"], got.Unmodeled["x-shared"], "the later declaration's value is kept") for _, key := range []string{"x-a", "x-b", "x-alike"} { assert.Contains(t, got.Unmodeled, key) } assert.Equal(t, jsontext.Pointer("/allOf/0/x-alike"), got.Unmodeled["x-alike"].Provenance.Pointer, "of two alike, the one written at the pointer sorting first, in either order") - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(other.property.Provenance.Pointer), "the other is kept verbatim") + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(other.property.Provenance.Pointer), "the other is kept verbatim") require.Len(t, *recorded, 1, "only the key given differently is reported") assert.Equal(t, diag.DegradedConstruct, (*recorded)[0].Code) assert.Equal(t, other.property.Provenance.Pointer, (*recorded)[0].Provenance.Pointer) @@ -275,21 +286,21 @@ func TestFold_AValueSpelledTwoWaysIsOneValue(t *testing.T) { assert.Empty(t, got.Unmodeled) }) } - stubbedValue, recorded := stubMerger(narrowingRegistry()) + stubbed, recorded := stubMerger(narrowingRegistry()) one, two := number("1"), number("2") first := declaration{property: ir.Property{WireName: "p", Type: primitiveRef(ir.PrimitiveAny), Default: &one, Provenance: ptrAt("/a")}, source: written(`{}`)} second := declaration{property: ir.Property{WireName: "p", Type: primitiveRef(ir.PrimitiveAny), Default: &two, Provenance: ptrAt("/b")}, source: written(`{}`)} - stubbedValue.fold([]declaration{first, second}) + stubbed.fold([]declaration{first, second}) require.Len(t, *recorded, 1, "two values are still two") } // TestFold_ThePromotionMarkerFollowsTheSecretTaken is the marker pin for the // other annotation a promotion writes on a declaration. Secret folds by OR, so // the field takes it from a later declaration as readily as from the first, and -// the field keeps the first's provenance: without the join, a redaction a -// heuristic read would carry no trace of it. A declaration lends no marker for a -// redaction it declared or does not ask for, whatever else was inferred of it, -// and the answer is the same in either order. +// the field keeps the first's provenance: without the combination, a redaction +// a heuristic read would carry no trace of it. A declaration lends no marker +// for a redaction it declared or does not ask for, whatever else was inferred +// of it, and the answer is the same in either order. func TestFold_ThePromotionMarkerFollowsTheSecretTaken(t *testing.T) { t.Parallel() const marker ir.Inferred = "extension-promotion" @@ -355,8 +366,8 @@ func TestFold_ThePromotionMarkerFollowsTheDeprecationKept(t *testing.T) { assert.Empty(t, *recorded) } - stubbedValue, recorded := stubMerger(narrowingRegistry()) - got := stubbedValue.fold([]declaration{plain, promoted, declared}) + stubbed, recorded := stubMerger(narrowingRegistry()) + got := stubbed.fold([]declaration{plain, promoted, declared}) assert.Equal(t, &ir.Deprecation{Message: "gone"}, got.Deprecation, "the last deprecation written is kept") assert.Empty(t, got.Provenance.Inferred, "a declared deprecation kept carries no heuristic's name") require.Len(t, *recorded, 1) @@ -388,14 +399,14 @@ func TestFold_DeclarationsPastTheBoundAreKeptUnjudged(t *testing.T) { assert.Equal(t, diag.BudgetExceeded, (*recorded)[0].Code) assert.Equal(t, at(maxFoldDeclarations), (*recorded)[0].Provenance.Pointer) assert.Contains(t, (*recorded)[0].Message, "declared 66 times, past the 64") - assert.Equal(t, []string{losingDeclarationKey + string(at(maxFoldDeclarations)), losingDeclarationKey + string(at(maxFoldDeclarations+1))}, + assert.Equal(t, []string{passedOverDeclarationKey + string(at(maxFoldDeclarations)), passedOverDeclarationKey + string(at(maxFoldDeclarations+1))}, slices.Sorted(maps.Keys(got.Unmodeled)), "each is kept") } // TestFold_AnUnjudgedDeclarationThatWillNotRenderIsReported pins that a -// declaration past the bound is kept as one the fold judged and lost is: one -// with no source to render is reported unkeepable beside the budget error, not -// dropped in silence. +// declaration past the bound is kept as one the fold judged and passed over is: +// one with no source to render is reported unkeepable beside the budget error, +// not dropped in silence. func TestFold_AnUnjudgedDeclarationThatWillNotRenderIsReported(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(narrowingRegistry()) @@ -420,87 +431,24 @@ func TestFold_AnUnjudgedDeclarationThatWillNotRenderIsReported(t *testing.T) { } // TestFold_ANarrowerTypeThatLosesIsAnOverlap pins how the fold reports a type -// narrower than the winner's that still lost. The judgment's narrowing is -// transitive, so such a type holds every type the winner holds and wins; were -// it ever to lose, it shares the winner's values, and is reported as an -// overlap, never as a pair the merge does not compare. +// narrower than the chosen declaration's that is still passed over. The +// judgment's narrowing is transitive, so such a type holds every type the +// chosen declaration holds and wins; were it ever to lose, it shares the chosen +// declaration's values, and is reported as an overlap, never as a pair the +// merge does not compare. func TestFold_ANarrowerTypeThatLosesIsAnOverlap(t *testing.T) { t.Parallel() stubbed, _ := stubMerger(narrowingRegistry()) decls := []declaration{stringAt("/allOf/0/properties/p", `{}`), stringAt("/allOf/1/properties/p", `{}`)} _, field := fieldSpan(decls) - folding := newFolding(&stubbed.Merger, decls, field) - folding.rel[folding.winner][1] = secondTypeIsNarrower + folding := newFieldFold(&stubbed.Merger, decls, field) + folding.rel[folding.chosen][1] = secondTypeIsNarrower folding.drop(1) require.Len(t, folding.notes[1], 1) assert.Contains(t, folding.notes[1][0].message, "whose values overlap") - assert.True(t, folding.lost[1]) -} - -// TestFold_DropRecordsAlternateMessageForAnonymousLoser pins that -// (*folding).drop always emits the full message naming both type IDs and -// records an alternate location-based message in Merger.PrunedDiagnostics if -// and only if the losing type is anonymous (with a nil slice safely ignored). -func TestFold_DropRecordsAlternateMessageForAnonymousLoser(t *testing.T) { - t.Parallel() - const ( - inlineAnon ir.TypeID = "type/anonymous/allOf/1/properties/p" - primLoser ir.TypeID = "type/primitive/integer" - ) - reg := narrowingRegistry() - reg[inlineAnon] = &ir.Model{ID: inlineAnon, Anonymous: true, Provenance: ptrAt("/allOf/1/properties/p")} - - for _, tc := range []struct { - name string - rel relation - loser ir.TypeID - collect bool - wantFullSub string - wantPrunedSub string - wantPrunedGone string - }{ - {"disjoint anonymous records alternate", relDisjoint, inlineAnon, true, string(inlineAnon), "/allOf/1/properties/p", string(inlineAnon)}, - {"disjoint anonymous nil sink", relDisjoint, inlineAnon, false, string(inlineAnon), "", ""}, - {"disjoint primitive records nothing", relDisjoint, primLoser, true, string(primLoser), "", ""}, - {"overlap anonymous records alternate", relOverlap, inlineAnon, true, "give types type/primitive/string and " + string(inlineAnon), "whose values overlap", string(inlineAnon)}, - {"overlap primitive records nothing", relOverlap, primLoser, true, "give types type/primitive/string and " + string(primLoser), "", ""}, - {"uncompared anonymous records alternate", relUnrelated, inlineAnon, true, "give types type/primitive/string and " + string(inlineAnon), "that the merge does not compare", string(inlineAnon)}, - {"uncompared primitive records nothing", relUnrelated, primLoser, true, "give types type/primitive/string and " + string(primLoser), "", ""}, - } { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - stubbed, _ := stubMerger(reg) - var recorded []PrunedDiagnostic - if tc.collect { - stubbed.PrunedDiagnostics = &recorded - } - d0 := stringAt("/allOf/0/properties/p", `{}`) - d1 := declaration{ - property: ir.Property{WireName: "p", Type: ir.TypeRef{Target: tc.loser}, Provenance: ptrAt("/allOf/1/properties/p")}, - source: written(`{}`), - } - decls := []declaration{d0, d1} - _, field := fieldSpan(decls) - folding := newFolding(&stubbed.Merger, decls, field) - folding.rel[folding.winner][1] = tc.rel - - folding.drop(1) - - require.Len(t, folding.notes[1], 1) - assert.Contains(t, folding.notes[1][0].message, tc.wantFullSub) - if tc.wantPrunedSub == "" { - assert.Empty(t, recorded) - return - } - require.Len(t, recorded, 1) - assert.Equal(t, tc.loser, recorded[0].Loser) - assert.Equal(t, folding.notes[1][0].message, recorded[0].Full) - assert.Contains(t, recorded[0].Pruned, tc.wantPrunedSub) - assert.NotContains(t, recorded[0].Pruned, tc.wantPrunedGone) - }) - } + assert.True(t, folding.passedOver[1]) } // TestSameExamples_ComparesEachExampleWhole pins that two example lists agree @@ -546,15 +494,15 @@ func TestFold_ExamplesAreJudgedAsOneKeyword(t *testing.T) { } assert.Nil(t, got.Examples, "%s: refused whole", tc.name) require.Len(t, *recorded, 1, tc.name) - assert.Contains(t, (*recorded)[0].Message, "admits the examples the declaration at /b gives", tc.name) - assert.Contains(t, got.Unmodeled, losingDeclarationKey+"/b", "%s: the writer is kept", tc.name) + assert.Contains(t, (*recorded)[0].Message, "admits the examples /b gives", tc.name) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+"/b", "%s: the declaration is kept", tc.name) } } -// TestMerger_ReconcileReportsDisagreementAndKeepsAWinner pins the documented +// TestMerger_ReconcileReportsDisagreementAndKeepsTheChosenDeclaration pins the documented // policy: an unsatisfiable redeclaration is surfaced rather than silently // resolved, and the merge still yields one property. -func TestMerger_ReconcileReportsDisagreementAndKeepsAWinner(t *testing.T) { +func TestMerger_ReconcileReportsDisagreementAndKeepsTheChosenDeclaration(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(map[ir.TypeID]ir.TypeDef{ "type/str": &ir.Primitive{ID: "type/str", PrimitiveKind: ir.PrimitiveString}, @@ -590,7 +538,7 @@ func TestKindOf_ReportsUnresolvableTargets(t *testing.T) { // TestFold_UnmodeledAlikeUnderAnotherBaseIsKept pins that an entry two // declarations write alike, writing a reference, is one only where -// FieldDeclarationContext.Alike says they read it against one base: elsewhere +// FieldDeclarationContext.DeclarationsAdmitAlike says they read it against one base: elsewhere // the same text may name another schema, so the earlier one is reported and // kept as one given differently is. An entry writing no reference is one under // any base. @@ -601,7 +549,7 @@ func TestFold_UnmodeledAlikeUnderAnotherBaseIsKept(t *testing.T) { wantKeys []string reports int }{ - {`{"$ref":"n.json"}`, []string{"openapi:not", losingDeclarationKey + "/allOf/0/properties/p"}, 1}, + {`{"$ref":"n.json"}`, []string{"openapi:not", passedOverDeclarationKey + "/allOf/0/properties/p"}, 1}, {`{"const":"n.json"}`, []string{"openapi:not"}, 0}, {`{"$ref":"https://ex.test/n.json"}`, []string{"openapi:not"}, 0}, } { diff --git a/compilers/openapi/internal/merge/fold_narrowing_internal_test.go b/compilers/openapi/internal/merge/fold_narrowing_internal_test.go index c7ad6ba34..35524b242 100644 --- a/compilers/openapi/internal/merge/fold_narrowing_internal_test.go +++ b/compilers/openapi/internal/merge/fold_narrowing_internal_test.go @@ -110,11 +110,11 @@ func TestFold_ANarrowingIntersectsNullability(t *testing.T) { } } -// TestFold_ADroppedTargetKeepsTheWinnersNullAdmission pins a drop: -// an unrelated declaration's type is lost whole, so the merged field keeps the -// winner's null admission, not the conjunction a same-referent or narrowing -// pair takes. -func TestFold_ADroppedTargetKeepsTheWinnersNullAdmission(t *testing.T) { +// TestFold_ADroppedTargetKeepsTheChosenDeclarationsNullAdmission pins a drop: an unrelated +// declaration's type is passed over whole, so the merged field keeps the chosen +// declaration's null admission, not the conjunction a same-referent or +// narrowing pair takes. +func TestFold_ADroppedTargetKeepsTheChosenDeclarationsNullAdmission(t *testing.T) { t.Parallel() for _, firstNull := range []bool{true, false} { t.Run(fmt.Sprintf("firstNullable=%v", firstNull), func(t *testing.T) { @@ -135,9 +135,9 @@ func TestFold_ADroppedTargetKeepsTheWinnersNullAdmission(t *testing.T) { } } -// TestFold_ANarrowingAdoptsTheBroaderDeclarationsDetail pins that -// nothing is dropped, so the broader declaration's constraints and default are -// folded as for any agreeing pair. +// TestFold_ANarrowingAdoptsTheBroaderDeclarationsDetail pins that nothing is +// dropped, so the broader declaration's constraints and default are taken into +// one as for any agreeing pair. func TestFold_ANarrowingAdoptsTheBroaderDeclarationsDetail(t *testing.T) { t.Parallel() for _, broadFirst := range []bool{true, false} { @@ -189,8 +189,9 @@ func TestFold_ANarrowingIsNoDrop(t *testing.T) { // TestFold_ANarrowingCarriesTheNullMarkers pins TypeRef.Inferred through a // narrowing: the field's null rests on a heuristic wherever either side's did -// (intersectNull), whichever side wins, except where the loser is the top -// type, whose null bit and marker say nothing, so the winner's stand alone. +// (intersectNull), whichever side is chosen, except where the passed-over +// declaration is the top type, whose null bit and marker say nothing, so the +// chosen declaration's are taken alone. func TestFold_ANarrowingCarriesTheNullMarkers(t *testing.T) { t.Parallel() nullRef := func(primitiveKind ir.PrimitiveKind, nullable bool, inferred ir.Inferred) ir.TypeRef { diff --git a/compilers/openapi/internal/merge/fold_types_internal_test.go b/compilers/openapi/internal/merge/fold_types_internal_test.go index d04de06aa..fad92b4dc 100644 --- a/compilers/openapi/internal/merge/fold_types_internal_test.go +++ b/compilers/openapi/internal/merge/fold_types_internal_test.go @@ -14,14 +14,15 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestFold_AConflictingTypeTakesNothingWithIt pins that a -// discarded declaration is discarded whole. The type conflict is diagnosed and -// the loser's type kept under Unmodeled, but the fold below it used to run to -// completion regardless, adopting the loser's default, constraints and examples -// onto the winner. That leaves the document asserting two contradictory things -// about one field — an integer carrying a string default — and nothing in -// pass/validate or irverify compares a Value's kind to its property's type, so -// an emitter renders it into non-compiling code. +// TestFold_AConflictingTypeTakesNothingWithIt pins that a discarded declaration +// is discarded whole. The type conflict is diagnosed and the passed-over +// declaration's type kept under Unmodeled, but the fold below it used to run to +// completion regardless, adopting the passed-over declaration's default, +// constraints and examples onto the chosen declaration. That leaves the +// document asserting two contradictory things about one field — an integer +// carrying a string default — and nothing in pass/validate or irverify compares +// a Value's kind to its property's type, so an emitter renders it into +// non-compiling code. func TestFold_AConflictingTypeTakesNothingWithIt(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(map[ir.TypeID]ir.TypeDef{ @@ -82,15 +83,15 @@ func TestFold_NullabilityIntersectsWhenTargetsAgree(t *testing.T) { } } -// TestFold_ADroppedTypeIsKeptEvenWhenItDoesNotConflict pins the -// gap between what the merge drops and what it calls a conflict. The judgment -// does not guess about two composites of one kind or an opaque scalar, but the -// fold keeps the winner's type regardless, so the losing declaration once -// vanished with neither a diagnostic nor an entry: #424's own failure, a -// consumer diffing two versions seeing no change. It is kept, and reported as a -// pair the merge does not compare, an info rather than a conflict: the field -// keeps the later declaration's type, which follows declaration order, and only -// the report says so. +// TestFold_ADroppedTypeIsKeptEvenWhenItDoesNotConflict pins the gap between +// what the merge drops and what it calls a conflict. The judgment does not +// guess about two composites of one kind or an opaque scalar, but the fold +// keeps the chosen declaration's type regardless, so the passed-over +// declaration once vanished with neither a diagnostic nor an entry: #424's own +// failure, a consumer diffing two versions seeing no change. It is kept, and +// reported as a pair the merge does not compare, an info rather than a +// conflict: the field keeps the later declaration's type, which follows +// declaration order, and only the report says so. func TestFold_ADroppedTypeIsKeptEvenWhenItDoesNotConflict(t *testing.T) { t.Parallel() reg := map[ir.TypeID]ir.TypeDef{ @@ -126,7 +127,7 @@ func TestFold_ADroppedTypeIsKeptEvenWhenItDoesNotConflict(t *testing.T) { assert.Equal(t, ir.SeverityInfo, (*recorded)[0].Severity, "a drop not called a conflict is no warning") assert.Equal(t, diag.DegradedConstruct, (*recorded)[0].Code) assert.Contains(t, (*recorded)[0].Message, "that the merge does not compare") - entry, ok := dst.Unmodeled[losingDeclarationKey+"/p/allOf/0/properties/id"] + entry, ok := dst.Unmodeled[passedOverDeclarationKey+"/p/allOf/0/properties/id"] require.True(t, ok, "the dropped declaration is kept; got %v", dst.Unmodeled) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) }) @@ -134,12 +135,13 @@ func TestFold_ADroppedTypeIsKeptEvenWhenItDoesNotConflict(t *testing.T) { } // TestFold_ADroppedTypeTakesNothingWithItEvenUnjudged is -// TestFold_AConflictingTypeTakesNothingWithIt for the drops -// the judgment declines to classify. The skip was keyed on the conflict -// diagnostic rather than on the drop, so a pair never called a conflict still -// folded the loser's default and constraints onto a winner whose type could -// not hold them, beside an entry saying that type was dropped: the -// contradiction the skip exists to prevent, on the one path it did not cover. +// TestFold_AConflictingTypeTakesNothingWithIt for the drops the judgment +// declines to classify. The skip was keyed on the conflict diagnostic rather +// than on the drop, so a pair never called a conflict still folded the +// passed-over declaration's default and constraints onto a chosen declaration +// whose type could not hold them, beside an entry saying that type was dropped: +// the contradiction the skip exists to prevent, on the one path it did not +// cover. func TestFold_ADroppedTypeTakesNothingWithItEvenUnjudged(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(map[ir.TypeID]ir.TypeDef{ @@ -163,15 +165,16 @@ func TestFold_ADroppedTypeTakesNothingWithItEvenUnjudged(t *testing.T) { assert.Nil(t, dst.Default, "the default describes the shape that was dropped") assert.Nil(t, dst.Constraints, "so does minProperties") assert.Empty(t, dst.Examples, "and so do the examples") - assert.Contains(t, dst.Unmodeled, losingDeclarationKey+"/allOf/0/properties/x", "the whole declaration is kept instead") + assert.Contains(t, dst.Unmodeled, passedOverDeclarationKey+"/allOf/0/properties/x", "the whole declaration is kept instead") } -// TestFold_TheJudgmentsVerdictIsWhatIsReported pins the three +// TestFold_TheJudgmentsAnswerIsWhatIsReported pins the three // paths of the fold: a disjoint pair warns, an overlapping pair draws an info, -// and one target declared twice judges null alone and adopts a default. -func TestFold_TheJudgmentsVerdictIsWhatIsReported(t *testing.T) { +// and one target declared twice judges null alone and adopts a default its type +// admits. +func TestFold_TheJudgmentsAnswerIsWhatIsReported(t *testing.T) { t.Parallel() - value := stringValue("x") + value := number("1") for _, tc := range []struct { name string a, b ir.TypeID @@ -201,7 +204,7 @@ func TestFold_TheJudgmentsVerdictIsWhatIsReported(t *testing.T) { require.Len(t, *recorded, 1, "%s (order %d)", tc.name, i) assert.Equal(t, tc.severity, (*recorded)[0].Severity, "%s (order %d)", tc.name, i) assert.Equal(t, tc.code, (*recorded)[0].Code, "%s (order %d)", tc.name, i) - assert.Contains(t, dst.Unmodeled, losingDeclarationKey+"/allOf/0/properties/x", + assert.Contains(t, dst.Unmodeled, passedOverDeclarationKey+"/allOf/0/properties/x", "the earlier declaration is kept: %s (order %d)", tc.name, i) continue } @@ -212,6 +215,59 @@ func TestFold_TheJudgmentsVerdictIsWhatIsReported(t *testing.T) { } } +// TestFold_AdoptsAValueWhereTheValueAdmissionReaderSaysYes holds the fold's +// adoption of a default to the value admission reader's answer for the +// field's type, on the types where a reading of merge's own once parted from +// it, in both orders: beside a declaration of the top type, which the field +// takes the type's node over, and beside one of the same type, except where +// that type refuses its own declaration's value, which the fold leaves to +// that declaration. +func TestFold_AdoptsAValueWhereTheValueAdmissionReaderSaysYes(t *testing.T) { + t.Parallel() + reg := judgeRegistry() + reg["type/enum-capped"] = &ir.Enum{ID: "type/enum-capped", ValueType: ir.PrimitiveInteger, Closed: true, + Members: []ir.EnumMember{{Value: number("1")}, {Value: number("2")}}, Constraints: &ir.Constraints{Max: new(ir.BigVal("1"))}} + reg["type/enum-open"] = &ir.Enum{ID: "type/enum-open", ValueType: ir.PrimitiveInteger, + Members: []ir.EnumMember{{Value: number("1")}, {Value: number("2")}}} + reg["type/tuple-i32"] = &ir.Tuple{ID: "type/tuple-i32", ElementTypes: []ir.TypeRef{primitiveRef(ir.PrimitiveInt32)}} + reg["type/union-i32-string"] = &ir.Union{ID: "type/union-i32-string", Closed: true, + Variants: []ir.Variant{{Type: primitiveRef(ir.PrimitiveInt32)}, {Type: primitiveRef(ir.PrimitiveString)}}} + top := ir.TypeID("type/primitive/any") + for _, tc := range []struct { + name string + typ ir.TypeID + value ir.Value + want ir.Admission + besides []ir.TypeID + }{ + {"a closed enum's member its bound refuses", "type/enum-capped", number("2"), ir.AdmitsNo, []ir.TypeID{top}}, + {"a value an open enum does not list", "type/enum-open", number("3"), ir.AdmitsYes, []ir.TypeID{top, "type/enum-open"}}, + {"null at a degraded top type", "type/any", ir.Value{Kind: ir.ValueNull}, ir.AdmitsYes, []ir.TypeID{"type/any"}}, + {"a tuple's one position", "type/tuple-i32", ir.Value{Kind: ir.ValueList, List: []ir.Value{number("1")}}, ir.AdmitsYes, + []ir.TypeID{top, "type/tuple-i32"}}, + {"a union's second variant", "type/union-i32-string", stringValue("a"), ir.AdmitsYes, []ir.TypeID{top, "type/union-i32-string"}}, + } { + stubbed, _ := stubMerger(reg) + require.Equal(t, tc.want, stubbed.ValueAdmissionReader.Admits(ref(tc.typ), tc.value), tc.name) + for _, beside := range tc.besides { + for order := range 2 { + stubbed, _ := stubMerger(reg) + typed := ir.Property{WireName: "x", Type: ref(tc.typ), Provenance: ptrAt("/allOf/0/properties/x")} + valued := ir.Property{WireName: "x", Type: ref(beside), Default: &tc.value, Provenance: ptrAt("/allOf/1/properties/x")} + if order == 1 { + typed.Provenance, valued.Provenance = valued.Provenance, typed.Provenance + typed, valued = valued, typed + } + + dst := foldTwo(stubbed, typed, valued, written(`{"type":"x"}`)) + + assert.Equal(t, ref(tc.typ).Target, dst.Type.Target, "%s beside %s, order %d", tc.name, beside, order) + assert.Equal(t, tc.want == ir.AdmitsYes, dst.Default != nil, "%s beside %s, order %d", tc.name, beside, order) + } + } + } +} + // reconcileBothOrders reconciles kinds a and b in both declaration orders and // returns what each order recorded and merged. func reconcileBothOrders(t *testing.T, a, b ir.PrimitiveKind) (dsts [2]ir.Property, diags [2][]ir.Diagnostic) { @@ -250,7 +306,7 @@ func TestFold_OverlappingKindsAreKeptAndReportedAsInfo(t *testing.T) { require.Len(t, diags[i], 1, "exactly one diagnostic (order %d)", i) assert.Equal(t, diag.DegradedConstruct, diags[i][0].Code, "order %d", i) assert.Equal(t, ir.SeverityInfo, diags[i][0].Severity, "order %d", i) - assert.Contains(t, dsts[i].Unmodeled, losingDeclarationKey+"/allOf/0/properties/x", + assert.Contains(t, dsts[i].Unmodeled, passedOverDeclarationKey+"/allOf/0/properties/x", "the earlier declaration is kept (order %d)", i) } }) @@ -278,15 +334,15 @@ func TestFold_DisjointKindsStillWarn(t *testing.T) { require.Len(t, diags[i], 1, "exactly one diagnostic (order %d)", i) assert.Equal(t, diag.ConflictingRedecl, diags[i][0].Code, "order %d", i) assert.Equal(t, ir.SeverityWarning, diags[i][0].Severity, "order %d", i) - assert.Contains(t, dsts[i].Unmodeled, losingDeclarationKey+"/allOf/0/properties/x", "order %d", i) + assert.Contains(t, dsts[i].Unmodeled, passedOverDeclarationKey+"/allOf/0/properties/x", "order %d", i) } }) } } -// enumRegistry adds two integer enums and two string enums to narrowingRegistry, -// each with a member the pairs below judge, and the uuid and bytes Scalar nodes -// that stand for a kind the same way a bare reference does. +// enumRegistry adds two integer enums and two string enums to +// narrowingRegistry, each with a member the pairs below judge, and the uuid and +// bytes Scalar nodes that represent a kind the same way a bare reference does. func enumRegistry() map[ir.TypeID]ir.TypeDef { reg := narrowingRegistry() reg["type/enum/a"] = &ir.Enum{ID: "type/enum/a", ValueType: ir.PrimitiveString, Members: []ir.EnumMember{{Value: stringValue("a")}}} @@ -312,7 +368,7 @@ func TestFold_EnumPairsAreJudgedByKind(t *testing.T) { name string a, b ir.TypeRef want ir.Severity // "" = none - winner ir.TypeID // "" = the later declaration's + chosen ir.TypeID // "" = the later declaration's }{ {"enum of string and uuid", enum("type/enum/a"), primitiveRef(ir.PrimitiveUUID), ir.SeverityWarning, ""}, {"enum of integer and int32", enum("type/enum/big"), primitiveRef(ir.PrimitiveInt32), ir.SeverityWarning, ""}, @@ -336,8 +392,8 @@ func TestFold_EnumPairsAreJudgedByKind(t *testing.T) { dst = foldTwo(stubbed, dst, src, written(`{"type":"x"}`)) wantTarget := order[1].Target - if tc.winner != "" { - wantTarget = tc.winner + if tc.chosen != "" { + wantTarget = tc.chosen } assert.Equal(t, wantTarget, dst.Type.Target, "the winning target (order %d)", i) if tc.want == "" { @@ -346,7 +402,7 @@ func TestFold_EnumPairsAreJudgedByKind(t *testing.T) { } require.Len(t, *recorded, 1, "exactly one diagnostic (order %d)", i) assert.Equal(t, tc.want, (*recorded)[0].Severity, "order %d", i) - assert.Contains(t, dst.Unmodeled, losingDeclarationKey+"/allOf/0/properties/x", + assert.Contains(t, dst.Unmodeled, passedOverDeclarationKey+"/allOf/0/properties/x", "the earlier declaration is kept (order %d)", i) } }) @@ -397,10 +453,10 @@ func twinRegistry() map[ir.TypeID]ir.TypeDef { reg["type/hex/1"] = &ir.Scalar{ID: "type/hex/1", Base: &stringType} reg["type/hex/2"] = &ir.Scalar{ID: "type/hex/2", Base: &stringType} reg["type/hex/min"] = &ir.Scalar{ID: "type/hex/min", Base: &stringType, Constraints: &ir.Constraints{MinLength: &minLen}} - for _, td := range reg { - switch td.(type) { + for _, typeDef := range reg { + switch typeDef.(type) { case *ir.Enum, *ir.Literal, *ir.Scalar: - td.Common().Anonymous = true + typeDef.Common().Anonymous = true } } reg["type/enum/x-named"] = enum("type/enum/x-named", members("xn/", "a", "b"), "") @@ -409,27 +465,29 @@ func twinRegistry() map[ir.TypeID]ir.TypeDef { } // TestFold_IdenticalNodesAreOneType pins, in both orders, that two -// hoisted Enum, Literal or Scalar nodes equal but for what names their site are -// one type, the one whose ID sorts first standing for both: no diagnostic and -// nothing kept aside. A named node wins over a hoisted copy of itself, and two -// named ones, or a pair that differs in a field, member order included, are an -// overlap reported as info, the later kept. +// hoisted Enum, Literal or Scalar nodes equal but for what names their site and +// their notes are one type, the one written first representing both, each +// hoisted at its own declaration, or the one holding every note: no diagnostic +// and nothing kept aside (GitHub #1889). A +// named node wins over a hoisted copy of itself, and two named ones, or a pair +// that differs in a field, member order included, are an overlap reported as +// info, the later kept. func TestFold_IdenticalNodesAreOneType(t *testing.T) { t.Parallel() for _, tc := range []struct { - name string - a, b ir.TypeID - same bool - win ir.TypeID // the type that stands in both orders, or "" for the rule's + name string + a, b ir.TypeID + same bool + chosenType ir.TypeID // the type chosen in both orders, or "" for the rule's }{ {"two identical enums", "type/enum/x1", "type/enum/x2", true, ""}, {"two identical literals", "type/lit/1", "type/lit/2", true, ""}, {"two identical scalars", "type/hex/1", "type/hex/2", true, ""}, {"enums that differ in the provenance of an extension", "type/enum/x-ext1", "type/enum/x-ext2", true, ""}, {"a named enum against a hoisted copy", "type/enum/x-named", "type/enum/x1", true, "type/enum/x-named"}, - {"two named enums declared alike", "type/enum/x-named", "type/enum/x-named2", false, ""}, + {"two named enums declared alike", "type/enum/x-named", "type/enum/x-named2", false, "type/enum/x-named"}, {"enums that differ in an extension's value", "type/enum/x-ext1", "type/enum/x-ext-valued", false, ""}, - {"enums that differ in a description", "type/enum/x1", "type/enum/x-described", false, ""}, + {"enums that differ in a description", "type/enum/x1", "type/enum/x-described", true, "type/enum/x-described"}, {"enums that differ in member order", "type/enum/x1", "type/enum/x-reordered", false, ""}, {"scalars that differ in a constraint", "type/hex/1", "type/hex/min", true, "type/hex/min"}, } { @@ -448,15 +506,15 @@ func TestFold_IdenticalNodesAreOneType(t *testing.T) { dst = foldTwo(stubbed, dst, src, written(`{"type":"x"}`)) - want := tc.win + want := tc.chosenType switch { case want != "": case tc.same: - want = min(tc.a, tc.b) + want = order[0] default: want = order[1] } - assert.Equal(t, want, dst.Type.Target, "the type that stands (order %d)", i) + assert.Equal(t, want, dst.Type.Target, "the type chosen (order %d)", i) if tc.same { assert.Empty(t, *recorded, "no diagnostic (order %d)", i) assert.Empty(t, dst.Unmodeled, "nothing is kept (order %d)", i) diff --git a/compilers/openapi/internal/merge/foldreader_internal_test.go b/compilers/openapi/internal/merge/foldreader_internal_test.go new file mode 100644 index 000000000..344d8baee --- /dev/null +++ b/compilers/openapi/internal/merge/foldreader_internal_test.go @@ -0,0 +1,75 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// settleDefaulted settles the model at id, whose field f is declared twice +// as target, the second declaration giving value as its default, through +// merger, and returns the default the field takes. +func settleDefaulted(t *testing.T, merger Merger, reg ir.TypeRegistry, id ir.TypeID, target ir.TypeID, value ir.Value) *ir.Value { + t.Helper() + model := &ir.Model{ID: id} + reg[id] = model + idx := NewModelPropertyDeclarations(model) + at := "/components/schemas/" + string(id) + idx.MergeProperty(declared("f", target, at+"/allOf/0/properties/f"), written(`{"$ref":"x"}`), "") + defaulted := declared("f", target, at+"/allOf/1/properties/f") + defaulted.Default = &value + idx.MergeProperty(defaulted, written(`{"$ref":"x","default":{}}`), "") + idx.Settle(merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{}) + require.Len(t, model.Properties, 1, "%s folds one f", id) + return model.Properties[0].Default +} + +// TestFold_AReadingDoesNotOutliveTheSettlementAfterIt pins each fold's value +// admission reader to that fold: a fold before a model's settlement adopts a +// default the model then admits, and a fold after it, through the same +// Merger, refuses that default once the settlement has placed a member +// required by one declaration of it, which a reading held from the first +// fold would not see. +func TestFold_AReadingDoesNotOutliveTheSettlementAfterIt(t *testing.T) { + t.Parallel() + reg := judgeRegistry() + settling := &ir.Model{ID: "type/settling"} + reg[settling.ID] = settling + members := NewModelPropertyDeclarations(settling) + text := ir.TypeID("type/primitive/string") + members.MergeProperty(declared("a", text, "/components/schemas/settling/properties/a"), written(`{"type":"string"}`), "") + members.MergeProperty(declared("b", text, "/components/schemas/settling/allOf/0/properties/b"), written(`{"type":"string"}`), "") + required := declared("b", text, "/components/schemas/settling/allOf/1/properties/b") + required.Required = true + members.MergeProperty(required, written(`{"type":"string"}`), "") + stubbed, _ := stubMerger(reg) + value := ir.Value{Kind: ir.ValueObject, Object: []ir.Field{{Name: "a", Value: stringValue("x")}}} + + require.NotNil(t, settleDefaulted(t, stubbed.Merger, reg, "type/before", settling.ID, value), + "before the settlement, b is not required") + members.Settle(stubbed.Merger, map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{}) + require.True(t, ir.FlattenedProperties(reg, settling.ID).Properties[1].Required, "the settlement requires b") + assert.Nil(t, settleDefaulted(t, stubbed.Merger, reg, "type/after", settling.ID, value), + "after it, the model is read as it is") +} + +// TestMerger_WithFoldReaderLeavesTheRunsReader pins withFoldReader: a fold +// reads through a reader of its own, leaving the Merger's as it was, and a +// Merger holding none folds through one each judgment builds (valueAdmission). +func TestMerger_WithFoldReaderLeavesTheRunsReader(t *testing.T) { + t.Parallel() + stubbed, _ := stubMerger(judgeRegistry()) + run := stubbed.ValueAdmissionReader + fold := stubbed.withFoldReader() + require.NotNil(t, fold.ValueAdmissionReader) + assert.NotSame(t, run, fold.ValueAdmissionReader, "a fold reads through its own") + assert.Same(t, run, stubbed.ValueAdmissionReader, "the Merger keeps the run's") + bare := &Merger{} + assert.Same(t, bare, bare.withFoldReader(), "a Merger holding none is left as it is") +} diff --git a/compilers/openapi/internal/merge/formatadmissions.go b/compilers/openapi/internal/merge/formatadmissions.go new file mode 100644 index 000000000..4afdcb66f --- /dev/null +++ b/compilers/openapi/internal/merge/formatadmissions.go @@ -0,0 +1,172 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/v2" + "strings" + "unicode/utf8" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// NewFoldValueAdmissionReader returns the value admission reader a fold asks +// whether a type admits a value, over the types node finds and their alias +// chains, index, reading what ir cannot as OpenAPI reads it. A run builds one +// and sets it on each Merger. +func NewFoldValueAdmissionReader(node func(ir.TypeID) (ir.TypeDef, bool), index *ir.AliasChainIndex) *ir.ValueAdmissionReader { + return ir.NewValueAdmissionReader(node, index, sourceFormatAdmissions{}) +} + +// withFoldReader returns g with a value admission reader of one fold's own +// (ir.ValueAdmissionReader.Fresh): a settlement places a model's members +// between two folds, so no reading outlives the fold that took it. +func (g *Merger) withFoldReader() *Merger { + if g.ValueAdmissionReader == nil { + return g + } + fold := *g + fold.ValueAdmissionReader = g.ValueAdmissionReader.Fresh() + return &fold +} + +// sourceFormatAdmissions judges a value against what the IR keeps of the +// OpenAPI source but does not read (ir.SourceFormatAdmissions): a +// format the compiler holds the grammar of and no kind holds, and a keyword +// kept verbatim with no IR home. +type sourceFormatAdmissions struct{} + +// AdmitsUnderEncoding judges value against encoding where it names a format +// whose grammar the compiler holds (heldFormat), and answers unknown for any +// other. +func (sourceFormatAdmissions) AdmitsUnderEncoding(encoding *ir.Encoding, value ir.Value) ir.Admission { + format, held := heldFormat(encoding) + if !held { + return ir.AdmitsUnknown + } + admits, _ := admitsFormat(format, value) + return ir.AdmissionOf(admits) +} + +// AdmitsUnderUnmodeledEntry judges value against the keyword entry keeps, by the +// keyword its key names: a value of no kind the keyword applies to is +// admitted, a length and a numeric bound are read, a keyword asserting nothing +// of a value admits it, and any other answers unknown, as does a value of no +// JSON kind. +func (sourceFormatAdmissions) AdmitsUnderUnmodeledEntry(key string, entry ir.UnmodeledEntry, value ir.Value) ir.Admission { + keyword := keptEntryKeyword(key) + kinds, isInstance := typeformat.KindsOfValue(value) + switch { + case !isInstance: + return ir.AdmitsUnknown + case typeformat.InstanceKindsKeywordAppliesTo(keyword, entry.Value)&kinds == 0: + return ir.AdmitsYes + } + switch keyword { + case "minLength", "maxLength": + return lengthAdmission(keyword, entry.Value, value) + case "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf": + return numberAdmission(keyword, entry.Value, value) + case "default", "example", "examples", "contentMediaType", "contentEncoding", "contentSchema": + return ir.AdmitsYes + default: + if fieldNoteKeyword(keyword) { + return ir.AdmitsYes + } + return ir.AdmitsUnknown + } +} + +// fieldNoteKeyword reports whether keyword says something of a field rather +// than of its values: a note, a use-bound keyword or an extension. +func fieldNoteKeyword(keyword string) bool { + switch keyword { + case "$comment", "title", "description", "readOnly", "writeOnly", "deprecated", "externalDocs", "xml": + return true + default: + return strings.HasPrefix(keyword, "x-") + } +} + +// withoutShapeEntries returns given, what the declaration written at declared, +// one the field drops, keeps on its property, less each entry the declaration +// writes itself that describes the type passed over, which goes with it as +// its constraints do (docs/compilers/openapi.md#allof-redeclared-property). An +// entry saying something of the field (fieldNoteKeyword) stays. It writes to +// no map it was given. +func withoutShapeEntries(declared ir.Provenance, given ir.Unmodeled) ir.Unmodeled { + var out ir.Unmodeled + for key, entry := range given { + keyword, ok := strings.CutPrefix(key, annotation.EntryKey("", "")) + shape := ok && !strings.Contains(keyword, "/") && !fieldNoteKeyword(keyword) && writtenAtOrUnder(entry.Provenance, declared) + if shape { + continue + } + if out == nil { + out = ir.Unmodeled{} + } + out[key] = entry + } + return out +} + +// writtenAtOrUnder reports whether at is declared or a place within it, in its +// document. +func writtenAtOrUnder(at, declared ir.Provenance) bool { + return at.Source == declared.Source && declared.Pointer.Contains(at.Pointer) +} + +// keptEntryKeyword is the keyword an Unmodeled key of the OpenAPI compiler +// names: what follows its prefix, up to the first path separator. +func keptEntryKeyword(key string) string { + keyword, ok := strings.CutPrefix(key, annotation.EntryKey("", "")) + if !ok { + return "" + } + keyword, _, _ = strings.Cut(keyword, "/") + return keyword +} + +// lengthAdmission judges value, a string, against a kept length, keyword +// holding the count written: by its code points, and a count that is no whole +// number unknown. +func lengthAdmission(keyword string, written ir.RawValue, value ir.Value) ir.Admission { + var count int64 + if err := json.Unmarshal(written, &count); err != nil || count < 0 { + return ir.AdmitsUnknown + } + length := int64(utf8.RuneCountInString(value.String)) + if keyword == "minLength" { + return ir.AdmissionOf(length >= count) + } + return ir.AdmissionOf(length <= count) +} + +// numberAdmission judges value, a number, against a kept numeric bound or +// step, and a bound or a value that reads as no number answers unknown. +func numberAdmission(keyword string, written ir.RawValue, value ir.Value) ir.Admission { + bound, err := ir.ParseDecimal(strings.TrimSpace(string(written))) + if err != nil { + return ir.AdmitsUnknown + } + number, err := value.Number.Decimal() + if err != nil { + return ir.AdmitsUnknown + } + order := number.Cmp(bound) + switch keyword { + case "minimum": + return ir.AdmissionOf(order >= 0) + case "maximum": + return ir.AdmissionOf(order <= 0) + case "exclusiveMinimum": + return ir.AdmissionOf(order > 0) + case "exclusiveMaximum": + return ir.AdmissionOf(order < 0) + default: + return ir.MultipleOfAdmits(bound, number) + } +} diff --git a/compilers/openapi/internal/merge/formatadmissions_internal_test.go b/compilers/openapi/internal/merge/formatadmissions_internal_test.go new file mode 100644 index 000000000..079d424f4 --- /dev/null +++ b/compilers/openapi/internal/merge/formatadmissions_internal_test.go @@ -0,0 +1,83 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestSourceFormatAdmissions_ReadsAKeptEntryByItsKeyword pins how the fold +// reads a keyword kept verbatim with no IR home: a value of no kind the +// keyword applies to admitted, a length by a string's code points and a +// numeric bound by a number; a pattern or a format unknown; a note, a +// use-bound keyword, a kept default, the content vocabulary and an extension +// asserting nothing; and a bound that reads as no count or number, a key of +// no keyword, or a value no JSON instance spells, unknown. +func TestSourceFormatAdmissions_ReadsAKeptEntryByItsKeyword(t *testing.T) { + t.Parallel() + kept := func(value string) ir.UnmodeledEntry { + return ir.UnmodeledEntry{Reason: ir.ReasonNoIRHome, Value: ir.RawValue(value)} + } + for _, tc := range []struct { + name, key, value string + judged ir.Value + want ir.Admission + }{ + {"a string within a maxLength", "openapi:maxLength", "3", stringValue("abc"), ir.AdmitsYes}, + {"a string past it", "openapi:maxLength", "3", stringValue("abcd"), ir.AdmitsNo}, + {"code points, not bytes", "openapi:maxLength", "1", stringValue("é"), ir.AdmitsYes}, + {"a string below a minLength", "openapi:minLength", "2", stringValue("a"), ir.AdmitsNo}, + {"a number beside a length", "openapi:maxLength", "1", number("123"), ir.AdmitsYes}, + {"a length that is no count", "openapi:maxLength", `"3"`, stringValue("abcd"), ir.AdmitsUnknown}, + {"a negative length", "openapi:maxLength", "-1", stringValue("a"), ir.AdmitsUnknown}, + {"a number at a minimum", "openapi:minimum", "5", number("5"), ir.AdmitsYes}, + {"a number below it", "openapi:minimum", "5", number("4"), ir.AdmitsNo}, + {"a number above a maximum", "openapi:maximum", "5", number("6"), ir.AdmitsNo}, + {"a number at an exclusive minimum", "openapi:exclusiveMinimum", "5", number("5"), ir.AdmitsNo}, + {"a number at an exclusive maximum", "openapi:exclusiveMaximum", "5", number("5"), ir.AdmitsNo}, + {"a number on a step", "openapi:multipleOf", "3", number("9"), ir.AdmitsYes}, + {"a number off it", "openapi:multipleOf", "3", number("10"), ir.AdmitsNo}, + {"a string beside a numeric bound", "openapi:minimum", "5", stringValue("a"), ir.AdmitsYes}, + {"a bound that reads as no number", "openapi:exclusiveMinimum", "true", number("1"), ir.AdmitsUnknown}, + {"a number that reads as no number", "openapi:minimum", "5", ir.Value{Kind: ir.ValueNumber, Number: "1p4"}, ir.AdmitsUnknown}, + {"a null beside a length", "openapi:maxLength", "1", ir.Value{Kind: ir.ValueNull}, ir.AdmitsYes}, + {"a bool beside a numeric bound", "openapi:maximum", "0", ir.Value{Kind: ir.ValueBool, Bool: true}, ir.AdmitsYes}, + {"an object beside a length", "openapi:minLength", "9", ir.Value{Kind: ir.ValueObject}, ir.AdmitsYes}, + {"a list beside an item count", "openapi:minItems", "9", ir.Value{Kind: ir.ValueList}, ir.AdmitsUnknown}, + {"a fraction beside a step", "openapi:multipleOf", "0.5", number("1.5"), ir.AdmitsYes}, + {"an infinity beside a length", "openapi:maxLength", "1", ir.Value{Kind: ir.ValueInfinity}, ir.AdmitsYes}, + {"a not-a-number beside a maximum", "openapi:maximum", "1", ir.Value{Kind: ir.ValueNaN}, ir.AdmitsUnknown}, + {"bytes beside a numeric bound", "openapi:minimum", "1", ir.Value{Kind: ir.ValueBytes}, ir.AdmitsUnknown}, + {"a value of no kind ir names", "openapi:minimum", "1", ir.Value{Kind: "unnamed"}, ir.AdmitsUnknown}, + {"a number beside a text format", "openapi:format", `"uuid"`, number("1"), ir.AdmitsYes}, + {"a string beside a text format", "openapi:format", `"uuid"`, stringValue("b"), ir.AdmitsUnknown}, + {"a pattern", "openapi:pattern", `"^a"`, stringValue("b"), ir.AdmitsUnknown}, + {"a number beside a pattern", "openapi:pattern", `"^a"`, number("1"), ir.AdmitsYes}, + {"a format", "openapi:format", `"email"`, stringValue("b"), ir.AdmitsUnknown}, + {"a note", "openapi:$comment", `"x"`, stringValue("b"), ir.AdmitsYes}, + {"a use-bound keyword", "openapi:readOnly", "true", stringValue("b"), ir.AdmitsYes}, + {"a kept default", "openapi:default", `"x"`, number("1"), ir.AdmitsYes}, + {"the content vocabulary", "openapi:contentMediaType", `"text/plain"`, number("1"), ir.AdmitsYes}, + {"an extension", "openapi:x-flag", "true", number("1"), ir.AdmitsYes}, + {"a key scoped below its carrier", "openapi:maxLength/inner", "1", stringValue("abc"), ir.AdmitsNo}, + {"a key of another format", "graphql:maxLength", "1", stringValue("abc"), ir.AdmitsUnknown}, + } { + assert.Equal(t, tc.want, sourceFormatAdmissions{}.AdmitsUnderUnmodeledEntry(tc.key, kept(tc.value), tc.judged), tc.name) + } +} + +// TestSourceFormatAdmissions_ReadsAHeldFormatAsItsGrammar pins the one +// encoding the fold reads: a held format by its grammar, and any other +// unknown. +func TestSourceFormatAdmissions_ReadsAHeldFormatAsItsGrammar(t *testing.T) { + t.Parallel() + sourceFormats := sourceFormatAdmissions{} + assert.Equal(t, ir.AdmitsYes, sourceFormats.AdmitsUnderEncoding(&ir.Encoding{Name: "time"}, stringValue("12:00:00Z"))) + assert.Equal(t, ir.AdmitsNo, sourceFormats.AdmitsUnderEncoding(&ir.Encoding{Name: "time"}, stringValue("12:00:00"))) + assert.Equal(t, ir.AdmitsUnknown, sourceFormats.AdmitsUnderEncoding(&ir.Encoding{Name: "email"}, stringValue("a@b.c"))) +} diff --git a/compilers/openapi/internal/merge/formats.go b/compilers/openapi/internal/merge/formats.go deleted file mode 100644 index cfadff264..000000000 --- a/compilers/openapi/internal/merge/formats.go +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "net/url" - "strings" - "time" -) - -// isAbsoluteURI reports whether s is an RFC 3986 URI with a scheme. The bytes -// are scanned first, since url.Parse accepts what the grammar does not (a -// space, a brace, a non-ASCII byte). The scan and ipLiteralPlaced own the -// characters and where brackets sit; url.Parse owns the structure and the -// IP-literal's content. An IPvFuture host ([v1.x]) is refused, since url.Parse -// refuses it; a refused value is kept verbatim, never lost. -func isAbsoluteURI(s string) bool { - if !uriBytesValid(s) { - return false - } - u, err := url.Parse(s) - return err == nil && u.Scheme != "" -} - -// uriBytesValid reports whether s is a scheme, a colon and then a tail -// uriTailValid admits. -func uriBytesValid(s string) bool { - if s == "" || !isLetter(s[0]) { - return false - } - i := 1 - for i < len(s) && (isLetter(s[i]) || isDigit(s[i]) || strings.IndexByte("+-.", s[i]) >= 0) { - i++ - } - if i == len(s) || s[i] != ':' { - return false - } - return uriTailValid(s[i+1:]) -} - -// uriTailValid reports whether rest, what follows a URI's scheme colon, holds -// only bytes RFC 3986 allows: unreserved, a gen-delim, a sub-delim or a -// percent-encoded octet. A bracket is allowed only in the authority (an -// IP-literal host), an "@" at most once there, and a fragment delimiter only -// once. -func uriTailValid(rest string) bool { - authorityEnd := 0 - if strings.HasPrefix(rest, "//") { - authorityEnd = 2 + strings.IndexAny(rest[2:]+"/", "/?#") - } - if !ipLiteralPlaced(rest[:authorityEnd]) || strings.Count(rest[:authorityEnd], "@") > 1 { - return false - } - fragments := 0 - for i := 0; i < len(rest); i++ { - switch c := rest[i]; { - case c == '%': - if i+2 >= len(rest) || !isHex(rest[i+1]) || !isHex(rest[i+2]) { - return false - } - i += 2 - case c == '[' || c == ']': - if i >= authorityEnd { - return false - } - case c == '#': - if fragments++; fragments > 1 { - return false - } - case !isLetter(c) && !isDigit(c) && strings.IndexByte("-._~:/?@!$&'()*+,;=", c) < 0: - return false - } - } - return true -} - -// ipLiteralPlaced reports whether authority's brackets, if it has any, enclose -// its whole host, which RFC 3986 allows only for an IP-literal: one "[" right -// after "//" or the userinfo's "@", and one "]" ending the authority or -// followed by the port's ":". -func ipLiteralPlaced(authority string) bool { - if !strings.ContainsAny(authority, "[]") { - return true - } - host := authority[2:] - if at := strings.LastIndexByte(host, '@'); at >= 0 { - host = host[at+1:] - } - end := strings.IndexByte(host, ']') - return strings.HasPrefix(host, "[") && end > 0 && - strings.Count(authority, "[") == 1 && strings.Count(authority, "]") == 1 && - (end == len(host)-1 || host[end+1] == ':') -} - -// isLetter reports whether c is an ASCII letter. -func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } - -// isDigit reports whether c is an ASCII decimal digit. -func isDigit(c byte) bool { return c >= '0' && c <= '9' } - -// parses reports whether s is a time in layout. Calendar fields are checked, so -// 2024-02-30 is refused. -func parses(layout, s string) bool { - _, err := time.Parse(layout, s) - return err == nil -} - -// rfc3339Form names the RFC 3339 §5.6 production parsesRFC3339 reads: a -// partial-time, or a full-date, T and partial-time, each with or without the -// time-offset after it. -type rfc3339Form int - -// The productions the time kinds and the time format are judged against. -const ( - // partialTime is a time of day with no offset: OpenAPI's time-local. - partialTime rfc3339Form = iota - // fullTime is a time of day with its offset: JSON Schema's time, which no - // kind holds (docs/ir/primitives.md#offsets), judged by admitsFormat. - fullTime - // localDateTime is a date-time with no offset: OpenAPI's date-time-local. - localDateTime - // dateTime is a date-time with its offset. - dateTime -) - -// parsesRFC3339 reports whether s is the production form names: the grammar's -// shape first, since time.Parse accepts a comma fraction and an offset hour -// above 23, then time.Parse for the calendar and range. The T separator and -// the Z offset may be lower case, which time.Parse refuses, so both are -// upper-cased once the shape is known. A second of 60 is a leap second, which -// time.Parse refuses, so it is parsed as 59. With an offset it is admitted -// where the time in UTC is 23:59 (§5.7). Without one, an offset could put -// 23:59 at any minute, so it is admitted at each. -func parsesRFC3339(s string, form rfc3339Form) bool { - layout, clock := "15:04:05", s - if form == localDateTime || form == dateTime { - if len(s) < len("2006-01-02T") || s[10] != 'T' && s[10] != 't' { - return false - } - layout, clock = "2006-01-02T15:04:05", s[11:] - s = s[:10] + "T" + clock - } - offset := form == fullTime || form == dateTime - if !clockShape(clock, offset) { - return false - } - if offset { - layout += "Z07:00" - if last := len(s) - 1; s[last] == 'z' { - s = s[:last] + "Z" - } - } - sec := len(s) - len(clock) + len("15:04:") - leap := s[sec:sec+2] == "60" - if leap { - s = s[:sec] + "59" + s[sec+2:] - } - t, err := time.Parse(layout, s) - return err == nil && (!leap || !offset || t.UTC().Hour() == 23 && t.UTC().Minute() == 59) -} - -// clockShape reports whether s is hh:mm:ss and an optional fraction of a dot -// and at least one digit, then an offset where offset is set and nothing where -// it is not. -func clockShape(s string, offset bool) bool { - const clockLength = len("15:04:05") - if len(s) < clockLength || s[2] != ':' || s[5] != ':' { - return false - } - for _, i := range []int{0, 1, 3, 4, 6, 7} { - if !isDigit(s[i]) { - return false - } - } - rest := s[clockLength:] - if strings.HasPrefix(rest, ".") { - end := 1 - for end < len(rest) && isDigit(rest[end]) { - end++ - } - if end == 1 { - return false - } - rest = rest[end:] - } - if offset { - return isOffset(rest) - } - return rest == "" -} - -// isOffset reports whether s is Z, z or ±hh:mm with hh 00-23 and mm 00-59. -func isOffset(s string) bool { - if s == "Z" || s == "z" { - return true - } - if len(s) != len("+05:30") || s[0] != '+' && s[0] != '-' || s[3] != ':' { - return false - } - hour, hourRead := twoDigits(s[1:3]) - minute, minuteRead := twoDigits(s[4:6]) - return hourRead && minuteRead && hour <= 23 && minute <= 59 -} - -// twoDigits reads s, two bytes, as a number, and false when either is not a -// digit. -func twoDigits(s string) (int, bool) { - if !isDigit(s[0]) || !isDigit(s[1]) { - return 0, false - } - return int(s[0]-'0')*10 + int(s[1]-'0'), true -} - -// uuidLength is the length of the 8-4-4-4-12 form isUUID reads: 32 -// hexadecimal digits and four hyphens. -const uuidLength = 36 - -// isUUID reports whether s is the 8-4-4-4-12 hexadecimal form. -func isUUID(s string) bool { - if len(s) != uuidLength { - return false - } - for i := range len(s) { - switch i { - case 8, 13, 18, 23: - if s[i] != '-' { - return false - } - default: - if !isHex(s[i]) { - return false - } - } - } - return true -} - -// isHex reports whether c is a hexadecimal digit. -func isHex(c byte) bool { - return isDigit(c) || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' -} - -// isDuration reports whether s is an ISO 8601 duration as RFC 3339 Appendix A -// writes it: P, then a week count alone, or a date part and a time part, each -// a run of consecutive designators from years to days and from hours to -// seconds, at least one present. -func isDuration(s string) bool { - rest, ok := strings.CutPrefix(s, "P") - if !ok || rest == "" { - return false - } - if weeks, found := strings.CutSuffix(rest, "W"); found { - return isDigitRun(weeks) - } - datePart, timePart, hasTime := strings.Cut(rest, "T") - if hasTime && timePart == "" || !hasTime && datePart == "" { - return false - } - return consecutiveDesignators(datePart, "YMD") && consecutiveDesignators(timePart, "HMS") -} - -// consecutiveDesignators reports whether s is empty or a run of digit-led -// designators each following the previous in order, starting anywhere. -func consecutiveDesignators(s, order string) bool { - next := 0 - for s != "" { - end := strings.IndexFunc(s, func(r rune) bool { return r < '0' || r > '9' }) - if end <= 0 || end == len(s) { - return false - } - at := strings.IndexByte(order[next:], s[end]) - if at < 0 || (next > 0 && at != 0) { - return false - } - next += at + 1 - s = s[end+1:] - } - return true -} - -// isDigitRun reports whether s is a non-empty run of decimal digits. -func isDigitRun(s string) bool { - return s != "" && strings.IndexFunc(s, func(r rune) bool { return r < '0' || r > '9' }) < 0 -} diff --git a/compilers/openapi/internal/merge/identity.go b/compilers/openapi/internal/merge/identity.go index 737171b16..027a89dde 100644 --- a/compilers/openapi/internal/merge/identity.go +++ b/compilers/openapi/internal/merge/identity.go @@ -4,59 +4,103 @@ package merge import ( + "cmp" "encoding/json/jsontext" + "strconv" + "strings" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/ir" ) // fieldSpan returns the narrowest schema holding every declaration of a field, -// and the declaration that names the field: the last to widen that schema, so -// the first outside the entry holding decls[0]. A model and a wrapper it -// flattens can share a first or a last declaration while folding different sets, -// but not this one: a wrapper's is never its own first, and an enclosing fold's -// is at most the wrapper's first. Folds of one set reach the same declaration. -// Past the flattening depth a model can miss what its wrapper reads, and -// Register refuses that collision. -func fieldSpan(decls []declaration) (schema, field jsontext.Pointer) { - field = decls[0].property.Provenance.Pointer - schema = schemaOf(field) +// and the key the nodes a fold of them mints sit under: +// /allOf/properties/, which no schema is written at, since an +// allOf holds entries by index. Both are functions of the set of declarations, +// so no order of them moves a minted node. A model and a wrapper it flattens +// folding different sets hold them in different schemas, so they key apart. +func fieldSpan(decls []declaration) (schema, key jsontext.Pointer) { + schema = schemaOf(decls[0].property.Provenance.Pointer) for _, declaration := range decls[1:] { - held := declaration.property.Provenance.Pointer - if schema.Contains(held) { - continue - } - for !schema.Contains(held) { + for held := declaration.property.Provenance.Pointer; !schema.Contains(held); { schema = schemaOf(schema) } - field = held } - return schema, field + return schema, schema + ids.Ptr("allOf", "properties", decls[0].property.WireName) } // schemaOf returns the schema a property or an allOf entry at pointer is // written in, two tokens above either. func schemaOf(pointer jsontext.Pointer) jsontext.Pointer { return pointer.Parent().Parent() } -// identify gives merged an identity of its own, named for field, where a model -// holding its first declaration without the others would otherwise share it: a -// $ref to an allOf entry makes one. That is a minted identity, so it takes a -// namespace of its own (docs/ir/identity.md#the-id-grammar). Otherwise the field -// keeps the first declaration's, which the walk has already handed out. schema -// holds every declaration (fieldSpan). -func (g *Merger) identify(merged *ir.Property, schema, field jsontext.Pointer) { - if !g.carriedApart(merged.Provenance.Pointer, schema) { - return +// identityDeclaration returns the declaration of decls whose identity the +// field keeps: the one whose pointer, its allOf indices erased +// (withoutAllOfIndices), is shortest, then least so erased, then least as +// written, then of the least document, so no order of the declarations moves +// the field's ID. +func identityDeclaration(decls []declaration) declaration { + best := decls[0] + for _, candidate := range decls[1:] { + if compareIdentity(candidate.property.Provenance, best.property.Provenance) < 0 { + best = candidate + } + } + return best +} + +// compareIdentity orders two declarations' provenances as identityDeclaration +// reads them. +func compareIdentity(a, b ir.Provenance) int { + erasedA, erasedB := withoutAllOfIndices(a.Pointer), withoutAllOfIndices(b.Pointer) + return cmp.Or(cmp.Compare(len(erasedA), len(erasedB)), strings.Compare(erasedA, erasedB), + strings.Compare(string(a.Pointer), string(b.Pointer)), cmp.Compare(a.Source, b.Source)) +} + +// withoutAllOfIndices returns pointer with the index after each allOf token +// dropped, so a declaration's place among the entries does not count. +func withoutAllOfIndices(pointer jsontext.Pointer) string { + var erased strings.Builder + afterAllOf := false + for token := range pointer.Tokens() { + if _, err := strconv.Atoi(token); afterAllOf && err == nil { + afterAllOf = false + continue + } + afterAllOf = token == "allOf" + erased.WriteString(string(ids.Ptr(token))) + } + return erased.String() +} + +// identify gives merged the identity of the declaration identityDeclaration +// chooses, or one of its own, named and placed at key, where a node sits +// between that declaration and schema (fieldSpan): a model holding it without +// the others would otherwise share it. That is a minted identity, so it takes +// a namespace of its own (docs/ir/identity.md#the-id-grammar). +func (g *Merger) identify(merged *ir.Property, decls []declaration, schema, key jsontext.Pointer) { + chosenIdentity, inferred := identityDeclaration(decls).property, merged.Provenance.Inferred + merged.ID, merged.Provenance = chosenIdentity.ID, chosenIdentity.Provenance + if g.carriedApart(chosenIdentity.Provenance, schema) { + merged.ID, merged.Provenance = g.IDs.ComposedProperty(key), g.Doc.At(key, declarationPointers(decls)...) + } + merged.Provenance.Inferred = inferred +} + +// declarationPointers returns where each of decls is written. +func declarationPointers(decls []declaration) []jsontext.Pointer { + out := make([]jsontext.Pointer, len(decls)) + for i, declaration := range decls { + out[i] = declaration.property.Provenance.Pointer } - merged.ID = g.IDs.ComposedProperty(field) - merged.Provenance.Pointer = field + return out } -// carriedApart reports whether a node stands at a schema inside whole that holds -// the declaration at first. Such a node's field holds fewer declarations than -// one of whole's, so the two are different fields. -func (g *Merger) carriedApart(first, whole jsontext.Pointer) bool { - for schema := schemaOf(first); len(schema) > len(whole); schema = schemaOf(schema) { - if g.Walk.Interned(schema) { +// carriedApart reports whether a node sits at a schema inside whole that holds +// the declaration at first, in first's document. Such a node's field holds +// fewer declarations than one of whole's, so the two are different fields. +func (g *Merger) carriedApart(first ir.Provenance, whole jsontext.Pointer) bool { + for schema := schemaOf(first.Pointer); len(schema) > len(whole); schema = schemaOf(schema) { + if g.Walk.Interned(ir.Provenance{Source: first.Source, Pointer: schema}) { return true } } diff --git a/compilers/openapi/internal/merge/identity_internal_test.go b/compilers/openapi/internal/merge/identity_internal_test.go index 8dd74c6fe..992615b8e 100644 --- a/compilers/openapi/internal/merge/identity_internal_test.go +++ b/compilers/openapi/internal/merge/identity_internal_test.go @@ -5,6 +5,7 @@ package merge import ( "encoding/json/jsontext" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -24,11 +25,12 @@ func declaredIn(pointers ...jsontext.Pointer) []declaration { } // TestFieldSpan_NamesEachSetOfDeclarations pins the one key that tells two folds -// apart. A model and a wrapper it flattens can share a first declaration or a -// last one, so neither names a field: the declaration that last widened the -// schema holding them all does, and it is one the source wrote. Each pair of -// rows sharing a first or a last differs in that. It reads tokens, so an index -// that prefixes another is no ancestor, and a property named allOf is no allOf. +// apart: the narrowest schema holding every declaration, then +// allOf/properties and the name, which no schema is written at. A model and a +// wrapper it flattens hold different sets in different schemas, so their keys +// differ, and the key is a function of the set, so no order of the +// declarations moves it. It reads tokens, so an index that prefixes another is +// no ancestor, and a property named allOf is no allOf. func TestFieldSpan_NamesEachSetOfDeclarations(t *testing.T) { t.Parallel() const ( @@ -43,42 +45,48 @@ func TestFieldSpan_NamesEachSetOfDeclarations(t *testing.T) { name string decls []jsontext.Pointer schema jsontext.Pointer - field jsontext.Pointer }{ - {"two entries", []jsontext.Pointer{a, b}, "/s", b}, - {"an entry and the schema's own", []jsontext.Pointer{a, "/s/properties/p"}, "/s", "/s/properties/p"}, - {"two entries of a wrapper", []jsontext.Pointer{in, on}, "/s/allOf/0", on}, - {"that wrapper, then a later entry", []jsontext.Pointer{in, on, b}, "/s", b}, - {"an entry, then a wrapper", []jsontext.Pointer{a, x, y}, "/s", x}, - {"that wrapper alone", []jsontext.Pointer{x, y}, "/s/allOf/1", y}, - {"two wrappers", []jsontext.Pointer{in, on, x, y}, "/s", x}, - {"a wrapper's own beside its entry", []jsontext.Pointer{in, "/s/allOf/0/properties/p"}, "/s/allOf/0", "/s/allOf/0/properties/p"}, - {"an index prefixing another", []jsontext.Pointer{"/s/allOf/1/properties/p", "/s/allOf/10/properties/p"}, "/s", "/s/allOf/10/properties/p"}, + {"two entries", []jsontext.Pointer{a, b}, "/s"}, + {"an entry and the schema's own", []jsontext.Pointer{a, "/s/properties/p"}, "/s"}, + {"two entries of a wrapper", []jsontext.Pointer{in, on}, "/s/allOf/0"}, + {"that wrapper, then a later entry", []jsontext.Pointer{in, on, b}, "/s"}, + {"an entry, then a wrapper", []jsontext.Pointer{a, x, y}, "/s"}, + {"that wrapper alone", []jsontext.Pointer{x, y}, "/s/allOf/1"}, + {"two wrappers", []jsontext.Pointer{in, on, x, y}, "/s"}, + {"a wrapper's own beside its entry", []jsontext.Pointer{in, "/s/allOf/0/properties/p"}, "/s/allOf/0"}, + {"an index prefixing another", []jsontext.Pointer{"/s/allOf/1/properties/p", "/s/allOf/10/properties/p"}, "/s"}, { "a schema under a property named allOf", []jsontext.Pointer{"/s/properties/allOf/allOf/0/properties/p", "/s/properties/allOf/allOf/1/properties/p"}, - "/s/properties/allOf", "/s/properties/allOf/allOf/1/properties/p", + "/s/properties/allOf", }, - {"a declaration inside what the first spans", []jsontext.Pointer{"/s/properties/p", a}, "/s", "/s/properties/p"}, + {"a declaration inside what the first spans", []jsontext.Pointer{"/s/properties/p", a}, "/s"}, } { - schema, field := fieldSpan(declaredIn(tc.decls...)) - assert.Equal(t, tc.schema, schema, tc.name) - assert.Equal(t, tc.field, field, tc.name) + reversed := slices.Clone(tc.decls) + slices.Reverse(reversed) + for _, decls := range [][]jsontext.Pointer{tc.decls, reversed} { + schema, key := fieldSpan(declaredIn(decls...)) + assert.Equal(t, tc.schema, schema, tc.name) + assert.Equal(t, tc.schema+"/allOf/properties/p", key, tc.name) + } } } // TestFold_AFieldAnotherModelCarriesTakesAnIdentityOfItsOwn pins when a field -// leaves its first declaration's identity: where a node inside the schema -// holding every declaration holds the first, since that model's field is a +// leaves its declarations' identity: where a node inside the schema holding +// every declaration holds the one it would keep, since that model's field is a // different one. A node at that schema, or above it, folds these same -// declarations, so it is this one field. The identity is a minted one, named for -// a declaration the source wrote. +// declarations, so it is this one field. The minted identity is keyed on that +// schema, which no order moves; a kept one is the declaration whose pointer, +// allOf indices erased, is shortest, then least erased, then least as written. func TestFold_AFieldAnotherModelCarriesTakesAnIdentityOfItsOwn(t *testing.T) { t.Parallel() const ( - first = "/s/allOf/0/allOf/0/properties/p" - next = "/s/allOf/0/allOf/1/properties/p" - later = "/s/allOf/1/properties/p" + first = "/s/allOf/0/allOf/0/properties/p" + next = "/s/allOf/0/allOf/1/properties/p" + later = "/s/allOf/1/properties/p" + key = "/s/allOf/properties/p" + wrapperKey = "/s/allOf/0/allOf/properties/p" ) for _, tc := range []struct { name string @@ -87,12 +95,15 @@ func TestFold_AFieldAnotherModelCarriesTakesAnIdentityOfItsOwn(t *testing.T) { id ir.PropertyID pointer jsontext.Pointer }{ - {"no other node", []jsontext.Pointer{first, later}, nil, "property/test" + first, first}, - {"the entry holding the first", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s/allOf/0/allOf/0"}, mintedProperty(later), later}, - {"a wrapper around it", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s/allOf/0"}, mintedProperty(later), later}, - {"the schema holding every declaration", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s"}, "property/test" + first, first}, + {"no other node", []jsontext.Pointer{first, later}, nil, "property/test" + later, later}, + {"the same, written in the other order", []jsontext.Pointer{later, first}, nil, "property/test" + later, later}, + {"the entry holding the kept one", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s/allOf/1"}, mintedProperty(key), key}, + {"an entry holding the other", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s/allOf/0/allOf/0"}, "property/test" + later, later}, + {"a wrapper around the other", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s/allOf/0"}, "property/test" + later, later}, + {"the schema holding every declaration", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s"}, "property/test" + later, later}, {"a wrapper holding every declaration", []jsontext.Pointer{first, next}, []jsontext.Pointer{"/s/allOf/0"}, "property/test" + first, first}, - {"an entry holding only a later one", []jsontext.Pointer{first, later}, []jsontext.Pointer{"/s/allOf/1"}, "property/test" + first, first}, + {"the same, written in the other order", []jsontext.Pointer{next, first}, []jsontext.Pointer{"/s/allOf/0"}, "property/test" + first, first}, + {"an entry inside that wrapper holding the kept one", []jsontext.Pointer{first, next}, []jsontext.Pointer{"/s/allOf/0/allOf/0"}, mintedProperty(wrapperKey), wrapperKey}, } { stubbed, _ := stubMerger(map[ir.TypeID]ir.TypeDef{"type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}}) stubbed.walk.interned = tc.nodes @@ -115,7 +126,7 @@ func TestPropertyIndex_ADiscriminatorFollowsItsFieldToANewIdentity(t *testing.T) names ir.PropertyID want ir.PropertyID }{ - {"the folded field", "property/test" + first, mintedProperty(later)}, + {"the folded field", "property/test" + first, mintedProperty("/s/allOf/properties/p")}, {"another field", "property/test/other", "property/test/other"}, } { stubbed, _ := stubMerger(map[ir.TypeID]ir.TypeDef{"type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}}) diff --git a/compilers/openapi/internal/merge/instancekinds.go b/compilers/openapi/internal/merge/instancekinds.go new file mode 100644 index 000000000..8f3ac1346 --- /dev/null +++ b/compilers/openapi/internal/merge/instancekinds.go @@ -0,0 +1,216 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/v2" + "maps" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// instanceKindsOf is the set of JSON instance kinds a value of kind may be, +// the one conversion between the two readings: a number is an integer or one +// with a fraction, and every other kind, the null among them, is its own. +func instanceKindsOf(kind JSONInstanceKind) typeformat.JSONInstanceKinds { + switch kind { + case InstanceString: + return typeformat.InstanceString + case InstanceInteger: + return typeformat.InstanceInteger + case InstanceNumber: + return typeformat.InstanceInteger | typeformat.InstanceNumber + case InstanceBoolean: + return typeformat.InstanceBoolean + case InstanceArray: + return typeformat.InstanceArray + case InstanceObject: + return typeformat.InstanceObject + default: + return typeformat.InstanceNull + } +} + +// primitiveKinds is the set of JSON instance kinds a value of primitiveKind +// may be (primitiveInstance), every kind for the top type. +func primitiveKinds(primitiveKind ir.PrimitiveKind) typeformat.JSONInstanceKinds { + if primitiveKind == ir.PrimitiveAny { + return typeformat.EveryInstanceKind + } + return instanceKindsOf(primitiveInstance(primitiveKind)) +} + +// scalarKinds is the set of JSON instance kinds the values of scalar are: +// those of the kind they travel as (travelsAs, registry.kindOf), every kind +// where the walk reads none. +func (r registryReader) scalarKinds(scalar *ir.Scalar) typeformat.JSONInstanceKinds { + if scalar.Base == nil { + return typeformat.EveryInstanceKind + } + kind, ok := r.kindOf(ir.TypeRef{Target: travelsAs(r.resolve, scalar)}) + if !ok { + return typeformat.EveryInstanceKind + } + return primitiveKinds(kind.primitive) +} + +// saysNothingBeside reports whether the entry kept under key applies to none of +// kinds, so it is no part of an answer on what a node holding it admits +// against a node of those kinds +// (docs/compilers/openapi.md#allof-redeclared-property). +func saysNothingBeside(key string, entry ir.UnmodeledEntry, kinds typeformat.JSONInstanceKinds) bool { + return typeformat.InstanceKindsKeywordAppliesTo(keptEntryKeyword(key), entry.Value)&kinds == 0 +} + +// judgedAgainst returns the entries of unmodeled judgedEntries reads, less +// each saying nothing beside kinds. It writes to no map it was given. +func judgedAgainst(unmodeled ir.Unmodeled, kinds typeformat.JSONInstanceKinds) ir.Unmodeled { + judged := judgedEntries(unmodeled) + var out ir.Unmodeled + for key, entry := range judged { + if saysNothingBeside(key, entry, kinds) { + if out == nil { + out = maps.Clone(judged) + } + delete(out, key) + } + } + if out == nil { + return judged + } + return out +} + +// formatIntersectionKind returns the primitive typeDef intersects the bare kind +// bareKind at, and false where it intersects none: typeDef is an alias of the +// top type keeping only a format bareKind's JSON type pairs with in the format +// table, so `{format: uuid}` beside `string` intersects at `uuid`. +func formatIntersectionKind(registry registryReader, typeDef ir.TypeDef, bareKind ir.PrimitiveKind) (ir.PrimitiveKind, bool) { + scalar, ok := typeDef.(*ir.Scalar) + if !ok || scalar.Base == nil || scalar.Encoding != nil || scalar.Constraints != nil { + return "", false + } + formatKey := annotation.EntryKey("", "format") + base, held := registry.resolve(scalar.Base.Target) + entry, kept := scalar.Unmodeled[formatKey] + jsonType, typed := bareJSONType(bareKind) + if !held || !isTop(base) || !kept || !typed { + return "", false + } + kinds := primitiveKinds(bareKind) + for key, other := range scalar.Unmodeled { + if key != formatKey && !saysNothingBeside(key, other, kinds) { + return "", false + } + } + var format string + if saysNothingBeside(formatKey, entry, kinds) || json.Unmarshal(entry.Value, &format) != nil { + return "", false + } + return typeformat.Lookup(jsonType + "/" + format) +} + +// bareJSONType returns the JSON type the bare kind primitiveKind is written +// as, the type a format table row pairs a format with, and false for a kind +// no row is written on bare. +func bareJSONType(primitiveKind ir.PrimitiveKind) (string, bool) { + if primitiveKind == ir.PrimitiveString { + return "string", true + } + if primitiveKind == ir.PrimitiveInteger { + return "integer", true + } + if primitiveKind == ir.PrimitiveNumber { + return "number", true + } + return "", false +} + +// formatIntersection returns the node alias, an alias of the top type keeping a +// format, intersects bare at (formatIntersectionKind): alias over the +// primitive the format pairs bare's type with, which then holds the format. +// It is false where the two intersect at none. +func (b *builder) formatIntersection(alias *ir.Scalar, bare *ir.Primitive) (ir.TypeDef, bool) { + intersected, ok := formatIntersectionKind(b.f.g.registryReader(), alias, bare.PrimitiveKind) + if !ok { + return nil, false + } + target := ir.PrimitiveTypeID(intersected) + if !b.dry { + target = b.f.g.Walk.Primitive(intersected) + } + out := *alias + out.Base = &ir.TypeRef{Target: target} + out.Unmodeled = maps.Clone(alias.Unmodeled) + delete(out.Unmodeled, annotation.EntryKey("", "format")) + if len(out.Unmodeled) == 0 { + out.Unmodeled = nil + } + return &out, true +} + +// boundKinds is the set of JSON instance kinds the bounds constraints holds +// apply to, none for nil: those each keyword it sets binds +// (keywordBoundKinds), and an array's for UniqueItems, which is no keyword. +func boundKinds(constraints *ir.Constraints) typeformat.JSONInstanceKinds { + if constraints == nil { + return 0 + } + var kinds typeformat.JSONInstanceKinds + if constraints.UniqueItems { + kinds |= typeformat.InstanceArray + } + for keyword := range ir.ConstraintKeywords() { + if constraints.SetsKeyword(keyword) { + kinds |= keywordBoundKinds(keyword) + } + } + return kinds +} + +// instanceValues holds a value of each JSON instance kind, one integer and one +// number with a fraction among them. +var instanceValues = [...]ir.Value{ + {Kind: ir.ValueString}, {Kind: ir.ValueNumber, Number: "0"}, {Kind: ir.ValueNumber, Number: "0.5"}, + {Kind: ir.ValueBool}, {Kind: ir.ValueList}, {Kind: ir.ValueObject}, {Kind: ir.ValueNull}, +} + +// keywordBoundKinds is the set of JSON instance kinds keyword binds, as +// ir.ConstraintKeyword.Binds reads it: the kind (typeformat.KindsOfValue) of +// each of instanceValues it binds. +func keywordBoundKinds(keyword ir.ConstraintKeyword) typeformat.JSONInstanceKinds { + var kinds typeformat.JSONInstanceKinds + for _, value := range instanceValues { + if keyword.Binds(value.Kind) { + valueKinds, _ := typeformat.KindsOfValue(value) + kinds |= valueKinds + } + } + return kinds +} + +// typeKinds is the set of JSON instance kinds the values of ref, naming +// typeDef, are, every kind for a type it reads no kind of. +func (j typeJudge) typeKinds(ref ir.TypeRef, typeDef ir.TypeDef) typeformat.JSONInstanceKinds { + if kind, ok := j.kindOf(ref); ok { + return primitiveKinds(kind.primitive) + } + end := j.unaliased(typeDef) + if lit, ok := end.(*ir.Literal); ok { + if kinds, isInstance := typeformat.KindsOfValue(lit.Value); isInstance { + return kinds + } + return typeformat.EveryInstanceKind + } + kind := instanceKind(end) + if kind == ir.KindModel { + return typeformat.InstanceObject + } + if kind == ir.KindList { + return typeformat.InstanceArray + } + return typeformat.EveryInstanceKind +} diff --git a/compilers/openapi/internal/merge/instancekinds_internal_test.go b/compilers/openapi/internal/merge/instancekinds_internal_test.go new file mode 100644 index 000000000..962e966c2 --- /dev/null +++ b/compilers/openapi/internal/merge/instancekinds_internal_test.go @@ -0,0 +1,266 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "maps" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// kept is an entry kept verbatim under Unmodeled holding value, as a node keeps +// a keyword its kind takes no home for. +func kept(value string) ir.UnmodeledEntry { + return ir.UnmodeledEntry{Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(value)} +} + +// TestInstanceKinds_ReadEachKindOnce pins the one conversion between merge's +// kinds and the applies-to reading's, and what a primitive's values are. +func TestInstanceKinds_ReadEachKindOnce(t *testing.T) { + t.Parallel() + for kind, want := range map[JSONInstanceKind]typeformat.JSONInstanceKinds{ + InstanceString: typeformat.InstanceString, InstanceInteger: typeformat.InstanceInteger, + InstanceNumber: typeformat.InstanceInteger | typeformat.InstanceNumber, InstanceBoolean: typeformat.InstanceBoolean, + InstanceArray: typeformat.InstanceArray, InstanceObject: typeformat.InstanceObject, InstanceNull: typeformat.InstanceNull, + } { + assert.Equal(t, want, instanceKindsOf(kind), "%d", kind) + } + for primitiveKind, want := range map[ir.PrimitiveKind]typeformat.JSONInstanceKinds{ + ir.PrimitiveAny: typeformat.EveryInstanceKind, ir.PrimitiveUUID: typeformat.InstanceString, + ir.PrimitiveInt32: typeformat.InstanceInteger, ir.PrimitiveFloat64: typeformat.InstanceInteger | typeformat.InstanceNumber, + } { + assert.Equal(t, want, primitiveKinds(primitiveKind), "%s", primitiveKind) + } +} + +// TestBoundKinds_ReadsEachBoundByItsKeyword pins the kinds a node's bounds +// apply to: none for no bounds, each bound the kinds its keyword binds +// (ir.ConstraintKeyword.Binds), a precision and a scale a number's and a +// pattern's message a string's among them, and uniqueItems an array's. +func TestBoundKinds_ReadsEachBoundByItsKeyword(t *testing.T) { + t.Parallel() + number := ir.BigVal("1") + for _, tc := range []struct { + name string + constraints *ir.Constraints + want typeformat.JSONInstanceKinds + }{ + {"no bounds", nil, 0}, + {"no bound set", &ir.Constraints{}, 0}, + {"a length", &ir.Constraints{MaxLength: new(int64(3))}, typeformat.InstanceString}, + {"a minimum and an item count", &ir.Constraints{Min: &number, MinItems: new(int64(1))}, + typeformat.InstanceInteger | typeformat.InstanceNumber | typeformat.InstanceArray}, + {"distinct items", &ir.Constraints{UniqueItems: true}, typeformat.InstanceArray}, + {"a property count", &ir.Constraints{MaxProperties: new(int64(1))}, typeformat.InstanceObject}, + {"a precision and a scale", &ir.Constraints{Precision: new(int64(2)), Scale: new(int64(1))}, + typeformat.InstanceInteger | typeformat.InstanceNumber}, + {"a pattern's message", &ir.Constraints{PatternMessage: "digits"}, typeformat.InstanceString}, + } { + assert.Equal(t, tc.want, boundKinds(tc.constraints), tc.name) + } +} + +// TestTypeKinds_ReadsWhatAValueOfATypeIs pins the kinds a type's values are: +// those of the kind it ends in, an object for a model, an array for a list, a +// literal's own, and every kind for a union or a literal no JSON instance +// spells. +func TestTypeKinds_ReadsWhatAValueOfATypeIs(t *testing.T) { + t.Parallel() + reg := narrowingRegistry() + reg["type/model"] = &ir.Model{ID: "type/model"} + reg["type/list"] = &ir.List{ID: "type/list", ElementType: primitiveRef(ir.PrimitiveString)} + reg["type/union"] = &ir.Union{ID: "type/union"} + reg["type/text"] = &ir.Literal{ID: "type/text", Value: stringValue("a")} + reg["type/symbol"] = &ir.Literal{ID: "type/symbol", Value: ir.Value{Kind: ir.ValueSymbol}} + stubbed, _ := stubMerger(reg) + for id, want := range map[ir.TypeID]typeformat.JSONInstanceKinds{ + primitiveRef(ir.PrimitiveUUID).Target: typeformat.InstanceString, "type/model": typeformat.InstanceObject, + "type/list": typeformat.InstanceArray, "type/union": typeformat.EveryInstanceKind, "type/text": typeformat.InstanceString, + "type/symbol": typeformat.EveryInstanceKind, + } { + assert.Equal(t, want, judge(stubbed).typeKinds(ref(id), reg[id]), "%s", id) + } +} + +// TestTypeJudge_AKeptKeywordOfAnotherKindSaysNothing pins the reading of what two +// nodes keep: a keyword applying to none of the other's kinds, or a use-bound +// one, decides nothing, so two strings keeping minimums apart, or two lists +// keeping lengths apart, are one type, while two strings keeping patterns apart +// are not, nor two opaque scalars, whose kinds nothing reads. +func TestTypeJudge_AKeptKeywordOfAnotherKindSaysNothing(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + scalar := func(id ir.TypeID, count int, key, value string) *ir.Scalar { + return hoisted(count, &ir.Scalar{ID: id, Base: &text, Unmodeled: ir.Unmodeled{key: kept(value)}}) + } + list := func(id ir.TypeID, count int, value string) *ir.List { + return hoisted(count, &ir.List{ID: id, ElementType: text, Unmodeled: ir.Unmodeled{"openapi:maxLength": kept(value)}}) + } + reg := narrowingRegistry() + reg["type/min1"], reg["type/min2"] = scalar("type/min1", 0, "openapi:minimum", "1"), scalar("type/min2", 1, "openapi:minimum", "2") + reg["type/len1"], reg["type/len2"] = scalar("type/len1", 0, "openapi:pattern", `"a"`), scalar("type/len2", 1, "openapi:pattern", `"b"`) + reg["type/ro"], reg["type/wo"] = scalar("type/ro", 0, "openapi:readOnly", "true"), scalar("type/wo", 1, "openapi:readOnly", "false") + reg["type/list1"], reg["type/list2"] = list("type/list1", 0, "1"), list("type/list2", 1, "2") + reg["type/opaque1"] = hoisted(0, &ir.Scalar{ID: "type/opaque1", Unmodeled: ir.Unmodeled{"openapi:minimum": kept("1")}}) + reg["type/opaque2"] = hoisted(1, &ir.Scalar{ID: "type/opaque2", Unmodeled: ir.Unmodeled{"openapi:minimum": kept("2")}}) + stubbed, _ := stubMerger(reg) + for _, tc := range []struct { + name string + a, b ir.TypeID + want relation + }{ + {"two strings keeping minimums apart", "type/min1", "type/min2", relSame}, + {"two strings keeping readOnly apart", "type/ro", "type/wo", relSame}, + {"two lists keeping lengths apart", "type/list1", "type/list2", relSame}, + {"two strings keeping patterns apart", "type/len1", "type/len2", relOverlap}, + {"two opaque scalars keeping minimums apart", "type/opaque1", "type/opaque2", relUnrelated}, + } { + judgeAt := stubbed.judgeAt(sitesAt(declaredAt(0)), sitesAt(declaredAt(1))) + assert.Equal(t, tc.want, judgeAt.relate(ref(tc.a), ref(tc.b)), tc.name) + judgeAt = stubbed.judgeAt(sitesAt(declaredAt(1)), sitesAt(declaredAt(0))) + assert.Equal(t, tc.want.flipped(), judgeAt.relate(ref(tc.b), ref(tc.a)), "%s, swapped", tc.name) + } +} + +// TestTypeJudge_ACopyKeepingWhatAnotherDoesNotIsNoCopy pins two nodes alike but +// for what they keep that says nothing: one type, neither a copy giving way to +// the other, so a node declared elsewhere does not win over one hoisted at its +// declaration; kept alike, the one declared elsewhere wins. +func TestTypeJudge_ACopyKeepingWhatAnotherDoesNotIsNoCopy(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + reg := narrowingRegistry() + reg["type/component"] = &ir.Scalar{ID: "type/component", Base: &text, Unmodeled: ir.Unmodeled{"openapi:minimum": kept("1")}} + reg["type/apart"] = hoisted(1, &ir.Scalar{ID: "type/apart", Base: &text, Unmodeled: ir.Unmodeled{"openapi:minimum": kept("2")}}) + reg["type/copy"] = hoisted(1, &ir.Scalar{ID: "type/copy", Base: &text, Unmodeled: ir.Unmodeled{"openapi:minimum": kept("1")}}) + stubbed, _ := stubMerger(reg) + judgeAt := stubbed.judgeAt(sitesAt(declaredAt(0)), sitesAt(declaredAt(1))) + + assert.Equal(t, relSame, judgeAt.relate(ref("type/component"), ref("type/apart"))) + assert.Equal(t, firstTypeIsNarrower, judgeAt.relate(ref("type/component"), ref("type/copy"))) +} + +// TestFormatIntersectionKind_IntersectsAKindAFormatApplyingToItNarrows pins where an alias +// of the top type keeping a format intersects a bare kind: the format applies to the +// kind and the format table pairs the two, and the alias keeps nothing else +// that applies to it, no encoding and no bound, over the top type itself. +func TestFormatIntersectionKind_IntersectsAKindAFormatApplyingToItNarrows(t *testing.T) { + t.Parallel() + top, text := primitiveRef(ir.PrimitiveAny), primitiveRef(ir.PrimitiveString) + alias := func(base ir.TypeRef, format string, more ir.Unmodeled) *ir.Scalar { + unmodeled := ir.Unmodeled{"openapi:format": kept(format)} + maps.Copy(unmodeled, more) + return &ir.Scalar{ID: "type/alias", Base: &base, Unmodeled: unmodeled} + } + stubbed, _ := stubMerger(narrowingRegistry()) + for _, tc := range []struct { + name string + typeDef ir.TypeDef + kind ir.PrimitiveKind + want ir.PrimitiveKind + }{ + {"a text format beside a string", alias(top, `"uuid"`, nil), ir.PrimitiveString, ir.PrimitiveUUID}, + {"a width beside an integer", alias(top, `"int32"`, nil), ir.PrimitiveInteger, ir.PrimitiveInt32}, + {"a width beside a number", alias(top, `"double"`, nil), ir.PrimitiveNumber, ir.PrimitiveFloat64}, + {"a numeric bound kept beside", alias(top, `"uuid"`, ir.Unmodeled{"openapi:minimum": kept("1")}), ir.PrimitiveString, ir.PrimitiveUUID}, + {"a text format beside an integer", alias(top, `"uuid"`, nil), ir.PrimitiveInteger, ""}, + {"a width beside a string, no row", alias(top, `"int32"`, nil), ir.PrimitiveString, ""}, + {"a format no row lists", alias(top, `"email"`, nil), ir.PrimitiveString, ""}, + {"a format that is no text", alias(top, `7`, nil), ir.PrimitiveString, ""}, + {"a not kept beside", alias(top, `"uuid"`, ir.Unmodeled{"openapi:not": kept(`{}`)}), ir.PrimitiveString, ""}, + {"a bool", alias(top, `"uuid"`, nil), ir.PrimitiveBool, ""}, + {"over a string", alias(text, `"uuid"`, nil), ir.PrimitiveString, ""}, + {"over a type the registry lacks", alias(ref("type/missing"), `"uuid"`, nil), ir.PrimitiveString, ""}, + {"no format", &ir.Scalar{ID: "type/alias", Base: &top}, ir.PrimitiveString, ""}, + {"bounded", &ir.Scalar{ID: "type/alias", Base: &top, Constraints: &ir.Constraints{MaxLength: new(int64(1))}}, ir.PrimitiveString, ""}, + {"encoded", &ir.Scalar{ID: "type/alias", Base: &top, Encoding: &ir.Encoding{Name: "uuid"}}, ir.PrimitiveString, ""}, + {"no alias", &ir.Scalar{ID: "type/alias"}, ir.PrimitiveString, ""}, + {"no scalar", &ir.Model{ID: "type/alias"}, ir.PrimitiveString, ""}, + } { + intersected, ok := formatIntersectionKind(stubbed.registryReader(), tc.typeDef, tc.kind) + assert.Equal(t, tc.want, intersected, tc.name) + assert.Equal(t, tc.want != "", ok, tc.name) + } +} + +// TestFold_AFormatIntersectsTheKindItNarrows pins a field declared as a string and +// as a schema writing a format alone: the two intersect at the format's primitive in +// either order, registered for the fold, with nothing reported; where the +// format's schema says more, the field takes a node over that primitive holding +// it. +func TestFold_AFormatIntersectsTheKindItNarrows(t *testing.T) { + t.Parallel() + top := primitiveRef(ir.PrimitiveAny) + for _, docs := range []ir.Docs{{}, {Description: "an identifier"}} { + for _, swapped := range []bool{false, true} { + reg := narrowingRegistry() + delete(reg, primitiveRef(ir.PrimitiveUUID).Target) + at := 1 + if swapped { + at = 0 + } + reg["type/format"] = hoisted(at, &ir.Scalar{ID: "type/format", Base: &top, Docs: docs, + Unmodeled: ir.Unmodeled{"openapi:format": kept(`"uuid"`)}}) + targets := []ir.TypeID{primitiveRef(ir.PrimitiveString).Target, "type/format"} + if swapped { + targets[0], targets[1] = targets[1], targets[0] + } + stubbed, recorded := stubMerger(reg) + + got := stubbed.fold(declsOf(targets...)) + + assert.Empty(t, *recorded, "%q, swapped %v", docs.Description, swapped) + require.Contains(t, reg, primitiveRef(ir.PrimitiveUUID).Target, "the primitive is registered") + if docs.Description == "" { + assert.Equal(t, primitiveRef(ir.PrimitiveUUID).Target, got.Type.Target, "swapped %v", swapped) + continue + } + intersected, ok := reg[got.Type.Target].(*ir.Scalar) + require.True(t, ok, "swapped %v", swapped) + assert.Equal(t, composedAt(foldKey), intersected.ID) + assert.Equal(t, &ir.TypeRef{Target: primitiveRef(ir.PrimitiveUUID).Target}, intersected.Base) + assert.Equal(t, docs, intersected.Docs) + assert.Empty(t, intersected.Unmodeled, "the format is held by the primitive") + } + } +} + +// TestFormatIntersection_BuildsNoNodeWhereNoFormatIntersects pins the build's guard: an +// alias and a bare kind intersecting at no format's primitive build nothing. +func TestFormatIntersection_BuildsNoNodeWhereNoFormatIntersects(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + stubbed, _ := stubMerger(narrowingRegistry()) + b := builder{f: &fieldFold{g: &stubbed.Merger}} + + built, ok := b.formatIntersection(&ir.Scalar{ID: "type/alias", Base: &text}, &ir.Primitive{PrimitiveKind: ir.PrimitiveString}) + + assert.False(t, ok) + assert.Nil(t, built) +} + +// TestTypeJudge_TwoUnionsAlikeAreCopies pins two untagged unions alike in +// variants and bounds, documented apart: copies, one type where both are +// hoisted at their declarations, and the one declared elsewhere narrower than +// a copy hoisted at its declaration. +func TestTypeJudge_TwoUnionsAlikeAreCopies(t *testing.T) { + t.Parallel() + union := func(id ir.TypeID) *ir.Union { + return &ir.Union{ID: id, Closed: true, Constraints: &ir.Constraints{MaxLength: new(int64(3))}, + Variants: []ir.Variant{{Type: primitiveRef(ir.PrimitiveString)}, {Type: primitiveRef(ir.PrimitiveInteger)}}} + } + reg := narrowingRegistry() + reg["type/u0"], reg["type/u1"], reg["type/component"] = hoisted(0, union("type/u0")), hoisted(1, union("type/u1")), union("type/component") + reg["type/u1"].Common().Docs.Description = "documented apart" + stubbed, _ := stubMerger(reg) + judgeAt := stubbed.judgeAt(sitesAt(declaredAt(0)), sitesAt(declaredAt(1))) + + assert.Equal(t, relSame, judgeAt.relate(ref("type/u0"), ref("type/u1"))) + assert.Equal(t, firstTypeIsNarrower, judgeAt.relate(ref("type/component"), ref("type/u1"))) +} diff --git a/compilers/openapi/internal/merge/intersection.go b/compilers/openapi/internal/merge/intersection.go new file mode 100644 index 000000000..1788d7cb9 --- /dev/null +++ b/compilers/openapi/internal/merge/intersection.go @@ -0,0 +1,413 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "cmp" + "encoding/json/jsontext" + "fmt" + "reflect" + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// builder builds the node the members at one position intersect in +// (docs/compilers/openapi.md#allof-redeclared-property): the chosen member's node +// holding what each member intersecting it adds, its members built the same way a +// level down. A dry run mints and reports nothing, so a fold learns whether +// every position builds before it registers a node; failed says one did not. +type builder struct { + f *fieldFold + dry bool + failed bool +} + +// mint registers node at pointer, its parts carried where carried says and +// placed as the field is (fieldFold.assembled; FieldDeclarationContext.Mint), or +// in a dry run names nothing. +func (b *builder) mint(pointer jsontext.Pointer, node ir.TypeDef, partPointers []jsontext.Pointer) ir.TypeID { + if b.dry { + return "" + } + return b.f.g.Walk.Mint(pointer, node, partPointers, b.f.assembled) +} + +// intersectionNode returns the node base and partners, members that intersect it, rest on: +// base's own where no partner adds anything, and otherwise one minted at +// pointer, built from the node each represents (registry.view). A literal among +// them is the node, since it is within each; a literal intersects only one node, so +// it is built beside one partner alone. +func (b *builder) intersectionNode(base member, partners []member, pointer jsontext.Pointer, depth int) ir.TypeID { + if len(partners) == 0 { + return base.ref.Target + } + all := append([]member{base}, partners...) + nodes, written := make([]ir.TypeDef, len(all)), make([]ir.Provenance, len(all)) + reg := b.f.g.registryReader() + for k, member := range all { + typeDef, ok := reg.resolve(member.ref.Target) + if !ok { + b.failed = true + return base.ref.Target + } + nodes[k], written[k] = typeDef, typeDef.Common().Provenance + } + stop := reg.sharedAlias(nodes...) + for k, typeDef := range nodes { + nodes[k] = reg.view(typeDef, stop) + } + if k := slices.IndexFunc(nodes, isLiteral); k > 0 { + all[0], all[k], nodes[0], nodes[k] = all[k], all[0], nodes[k], nodes[0] + } + if _, bare := nodes[0].(*ir.Primitive); bare && len(nodes) == 2 { + // A bare kind intersects only an alias keeping a format (formatIntersectionKind), + // which the node is built from. + all[0], all[1], nodes[0], nodes[1] = all[1], all[0], nodes[1], nodes[0] + } + built, ok := b.build(all, nodes, pointer, depth) + if !ok { + b.failed = true + return base.ref.Target + } + built = b.adoptInto(built, all, nodes) + if reused, ok := reusedNode(built, all, nodes, written); ok { + return reused + } + if scalar, alias := built.(*ir.Scalar); alias && scalar.Base != nil && aliasAddsNothingBeyondBase(scalar) { + return scalar.Base.Target + } + if enum, ok := built.(*ir.Enum); ok && len(enum.Members) == 0 { + b.keepValueSets(enum, all) + } + return b.mint(pointer, built, nil) +} + +// everyAdmitsNull reports whether every member's reference admits null, so two +// value sets sharing no other member intersect at null alone (typeJudge.nullIntersection). +func everyAdmitsNull(all []member) bool { + return !slices.ContainsFunc(all, func(member member) bool { return !member.ref.Nullable }) +} + +// keepValueSets keeps on enum, the closed enum of no member value sets +// sharing null alone intersect in, the set each declaration the model holds alone +// gives, verbatim, as one position keeps each set its allOf writes: under its +// own key (chosenDeclarationKey), each with an info. A set another model's +// declaration brings stays there. A dry run keeps nothing. +func (b *builder) keepValueSets(enum *ir.Enum, all []member) { + if b.dry { + return + } + for _, member := range all { + declaration := b.f.decls[member.decl] + if declaration.via != nil { + continue + } + at := declaration.property.Provenance + for _, diagnostic := range b.f.g.keepVerbatim(&enum.Unmodeled, chosenDeclarationKey(b.f.fieldPointer, at.Pointer), at, declaration.source) { + b.f.notes[member.decl] = append(b.f.notes[member.decl], note{sev: diagnostic.Severity, code: diagnostic.Code, + message: diagnostic.Message, at: diagnostic.Provenance}) + } + place := fieldPlace(b.f.g, declaration, fieldGivenTogether) + b.f.note(member.decl, ir.SeverityInfo, diag.DegradedConstruct, + "field %q admits null alone, the one value the value sets of its declarations share, as a closed enum "+ + "of no member behind a nullable reference; the set the declaration at %s gives is kept verbatim "+ + "under Unmodeled at that enum", b.f.merged.WireName, placeName(b.f.g.Sources, place, place.Source)) + } +} + +// reusedNode returns the least target (compareWrittenTargets) of the members +// all whose node, of nodes, is built but for where it was declared, and false +// where none is: the intersection names a node a declaration already gives +// rather than minting a copy of it. +func reusedNode(built ir.TypeDef, all []member, nodes []ir.TypeDef, written []ir.Provenance) (ir.TypeID, bool) { + var reused ir.TypeID + var reusedAt ir.Provenance + for k, typeDef := range nodes { + target := all[k].ref.Target + if (reused == "" || compareWrittenTargets(target, written[k], reused, reusedAt) < 0) && sitelessCopy(built, typeDef) { + reused, reusedAt = target, written[k] + } + } + return reused, reused != "" +} + +// sitelessCopy reports whether a and b are nodes of one kind equal but for +// where each was declared (siteless) and their enum members' IDs, notes +// included, so naming one in the other's place loses nothing. +func sitelessCopy(a, b ir.TypeDef) bool { + av, bv := reflect.ValueOf(a), reflect.ValueOf(b) + if av.Type() != bv.Type() { + return false + } + x, y := reflect.New(av.Type().Elem()).Elem(), reflect.New(bv.Type().Elem()).Elem() + x.Set(av.Elem()) + y.Set(bv.Elem()) + x.FieldByName("TypeCommon").Set(reflect.ValueOf(siteless(*a.Common()))) + y.FieldByName("TypeCommon").Set(reflect.ValueOf(siteless(*b.Common()))) + if members := x.FieldByName("Members"); members.IsValid() { + xm, _ := reflect.TypeAssert[[]ir.EnumMember](members) + ym, _ := reflect.TypeAssert[[]ir.EnumMember](y.FieldByName("Members")) + members.Set(reflect.ValueOf(idless(xm))) + y.FieldByName("Members").Set(reflect.ValueOf(idless(ym))) + } + return reflect.DeepEqual(x.Interface(), y.Interface()) +} + +// build returns nodes[0] holding what each of nodes[1:] adds: its members built +// from all the nodes' (settle), its bounds intersected with theirs +// (intersectConstraints), and what else they say adopted (adopt), or false +// where the nodes are of kinds no node holds together. +func (b *builder) build(all []member, nodes []ir.TypeDef, pointer jsontext.Pointer, depth int) (ir.TypeDef, bool) { + switch node := nodes[0].(type) { + case *ir.Literal: + out := *node + return &out, len(nodes) == 2 + case *ir.Scalar: + if bare, ok := nodes[len(nodes)-1].(*ir.Primitive); ok && len(nodes) == 2 { + return b.formatIntersection(node, bare) + } + out := *node + return &out, sameKind[*ir.Scalar](nodes) + case *ir.Union: + // Unions intersect only where their variants are the same (unionsAlike), so + // the node is the first's, holding the bounds every one says. + out := *node + return &out, sameKind[*ir.Union](nodes) + case *ir.Enum: + out := *node + out.Members = sharedBy(node.Members, nodes[1:]) + valueType, narrowest := narrowestValueType(nodes) + out.ValueType = valueType + return &out, narrowest && (len(out.Members) > 0 || everyAdmitsNull(all)) + case *ir.List: + out := *node + out.ElementType = b.settle(membersOf(all, nodes, func(list *ir.List) ir.TypeRef { return list.ElementType }), pointer+"/items", depth) + return &out, sameKind[*ir.List](nodes) + case *ir.MapT: + out := *node + out.Value = b.settle(membersOf(all, nodes, func(mapT *ir.MapT) ir.TypeRef { return mapT.Value }), pointer+"/additionalProperties", depth) + return &out, sameKind[*ir.MapT](nodes) + case *ir.Tuple: + return b.tuple(node, all, nodes, pointer, depth) + default: + return nil, false + } +} + +// tuple is build for a tuple: each position, and what may follow the last, +// built from all the tuples' (settle), which intersect only at one length and one +// presence of what follows (typeJudge.tuples). +func (b *builder) tuple(tuple *ir.Tuple, all []member, nodes []ir.TypeDef, pointer jsontext.Pointer, depth int) (ir.TypeDef, bool) { + if !shapedAs(tuple, nodes) { + return nil, false + } + out := *tuple + out.ElementTypes = make([]ir.TypeRef, len(tuple.ElementTypes)) + for i := range tuple.ElementTypes { + at := pointer + jsontext.Pointer(fmt.Sprintf("/prefixItems/%d", i)) + out.ElementTypes[i] = b.settle(membersOf(all, nodes, func(irTuple *ir.Tuple) ir.TypeRef { return irTuple.ElementTypes[i] }), at, depth) + } + if tuple.Rest != nil { + rest := b.settle(membersOf(all, nodes, func(irTuple *ir.Tuple) ir.TypeRef { return *irTuple.Rest }), pointer+"/items", depth) + out.Rest = &rest + } + return &out, true +} + +// shapedAs reports whether every node is a tuple of tuple's length, and admits +// what follows its last position where tuple does. +func shapedAs(tuple *ir.Tuple, nodes []ir.TypeDef) bool { + for _, typeDef := range nodes { + irTuple, ok := typeDef.(*ir.Tuple) + if !ok || len(irTuple.ElementTypes) != len(tuple.ElementTypes) || (irTuple.Rest == nil) != (tuple.Rest == nil) { + return false + } + } + return true +} + +// sameKind reports whether every node is a T. +func sameKind[T ir.TypeDef](nodes []ir.TypeDef) bool { + return !slices.ContainsFunc(nodes, func(typeDef ir.TypeDef) bool { _, ok := typeDef.(T); return !ok }) +} + +// membersOf returns what each node, a T, holds at one position (of), each the +// member of the declaration whose node it is. +func membersOf[T ir.TypeDef](all []member, nodes []ir.TypeDef, of func(T) ir.TypeRef) []member { + out := make([]member, 0, len(nodes)) + for k, typeDef := range nodes { + if typed, ok := typeDef.(T); ok { + out = append(out, member{ref: of(typed), decl: all[k].decl}) + } + } + return out +} + +// sharedBy returns the members of ms whose value every enum of others holds, +// in ms's order: the values of all the enums at once. A node of others that is +// no enum holds none of them. +func sharedBy(ms []ir.EnumMember, others []ir.TypeDef) []ir.EnumMember { + indexes := make([]memberIndex, len(others)) + for k, typeDef := range others { + enum, ok := typeDef.(*ir.Enum) + if !ok { + return nil + } + indexes[k] = indexMembers(enum.Members) + } + out := make([]ir.EnumMember, 0, len(ms)) + for _, enumMember := range ms { + if heldByAll(indexes, enumMember.Value) { + out = append(out, enumMember) + } + } + if len(out) == len(ms) { + return ms + } + return out +} + +// heldByAll reports whether each enum indexes indexed holds value. +func heldByAll(indexes []memberIndex, value ir.Value) bool { + for _, memberIndex := range indexes { + if _, held := memberIndex.find(value); !held { + return false + } + } + return true +} + +// settle returns the type of one position of the nodes built at depth, its +// members ms: the model they compose, or the node they intersect in built a level +// down, at pointer, admitting null as position.null reads them. A member +// outside the chosen member's cone fails the build, since no node holds it beside the +// rest. ms are judged in declaration order, as a field's own types are, so a +// tie goes to the later and what they compose is listed as they are written. +func (b *builder) settle(ms []member, pointer jsontext.Pointer, depth int) ir.TypeRef { + ms = slices.SortedStableFunc(slices.Values(ms), func(member, otherMember member) int { return cmp.Compare(member.decl, otherMember.decl) }) + position := b.f.g.judgePosition(b.f.decls, ms, depth+1) + all := func(int) bool { return true } + var target ir.TypeID + if len(position.conjuncts) > 0 { + target = b.compose(position.conjuncts, pointer) + } else { + for k := range ms { + if !position.subsumes(position.chosen, k) { + b.failed = true + return ms[position.chosen].ref + } + } + base, partners := position.intersecting(all, unheldCopy(b.f, position)) + target = b.intersectionNode(base, partners, pointer, depth+1) + if !b.dry { + markApart(b.f, position, all, target, depth+1) + } + } + ref := position.null(b.f.g.registryReader(), all, depth+1) + ref.Target = target + return ref +} + +// adoptInto returns built, the node nodes[0] represents with its members built, +// holding the bounds every node says together and what else each of nodes[1:] +// adds. A field two give differently is the first's, and the later one is +// reported and kept verbatim. A literal takes no bounds, since every node +// intersecting it admits its value. +func (b *builder) adoptInto(built ir.TypeDef, all []member, nodes []ir.TypeDef) ir.TypeDef { + sets := make([]*ir.Constraints, len(b.f.decls)) + for k, typeDef := range nodes { + sets[all[k].decl] = boundsOf(typeDef) + } + if !isLiteral(built) { + if intersected := intersectConstraints(sets, writtenFirst(b.f), b.disagree); !sameBounds(intersected, boundsOf(nodes[0])) { + built = withBounds(built, intersected) + } + } + others := make([]ir.TypeCommon, len(nodes)-1) + for k, typeDef := range nodes[1:] { + others[k] = *typeDef.Common() + } + typeCommon := built.Common() + *typeCommon = adopt(*typeCommon, others, func(passedOver, chosen int, field string, agrees func(k int) bool) { + b.differ(all[passedOver].decl, all[chosen].decl, field, agreeingDeclarations(all, agrees)) + }) + enum, isEnum := built.(*ir.Enum) + typeCommon.Unmodeled = b.intersectionEntries(typeCommon.Unmodeled, all, nodes, isEnum && len(enum.Members) == 0, + bindsText(b.f.g.registryReader(), built)) + b.keepExamples(typeCommon.Examples, all, nodes) + if list, ok := built.(*ir.List); ok && list.Encoding == nil { + b.adoptEncoding(list, all, nodes) + } + return built +} + +// keepExamples reports, as adoptInto reports a field, each of nodes[1:] giving +// examples otherwise than the built node keeps, built: no node adopts another's +// examples, which nothing shows it admits, so they are kept verbatim with +// their declaration. +func (b *builder) keepExamples(built []ir.Example, all []member, nodes []ir.TypeDef) { + gives := func(k int) bool { return k == 0 || sameExamples(nodes[k].Common().Examples, built) } + for k, typeDef := range nodes[1:] { + if examples := typeDef.Common().Examples; len(examples) > 0 && !sameExamples(examples, built) { + b.differ(all[k+1].decl, all[0].decl, "examples", agreeingDeclarations(all, gives)) + } + } +} + +// adoptEncoding sets on list, a list giving no encoding, the first one +// nodes[1:] give, reporting each later list giving another as adopt reports a +// field. +func (b *builder) adoptEncoding(list *ir.List, all []member, nodes []ir.TypeDef) { + keptFrom := 0 + encodes := func(k int) bool { + other, ok := nodes[k].(*ir.List) + return ok && other.Encoding != nil && reflect.DeepEqual(other.Encoding, list.Encoding) + } + for k, typeDef := range nodes[1:] { + other, ok := typeDef.(*ir.List) + switch { + case !ok || other.Encoding == nil: + case list.Encoding == nil: + list.Encoding, keptFrom = other.Encoding, k+1 + case !reflect.DeepEqual(list.Encoding, other.Encoding): + b.differ(all[k+1].decl, all[keptFrom].decl, "encoding", agreeingDeclarations(all, encodes)) + } + } +} + +// disagree is fieldFold.disagree, heard only where the build is not a dry run. +func (b *builder) disagree(i, chosenIndex declarationIndex, reportedField, disagreesOver string, agrees func(declarationIndex) bool) { + if !b.dry { + b.f.disagree(i, chosenIndex, reportedField, disagreesOver, agrees) + } +} + +// differ reports at declaration decl that it gives what field names of a type +// the field holds otherwise than the chosen declaration, whose value the type +// keeps, as do the declarations agrees names, and keeps decl verbatim. +func (b *builder) differ(decl, chosenIndex declarationIndex, reportedField string, agrees func(declarationIndex) bool) { + if b.dry { + return + } + b.f.passedOver[decl] = true + chosenFirst := chosenDeclaration(b.f, chosenIndex, agrees, fieldGivenTogether) + passedOverAt, chosenPlace := fieldPlace(b.f.g, b.f.decls[decl], fieldGivenTogether), fieldPlace(b.f.g, b.f.decls[chosenFirst], fieldGivenTogether) + b.f.notes[decl] = append(b.f.notes[decl], note{sev: ir.SeverityInfo, code: diag.DegradedConstruct, at: passedOverAt, chosenAt: &chosenPlace, + heldField: reportedField, message: aboutPair(b.f, decl, passedOverAt, chosenPlace, "give the "+reportedField+" of a type it holds differently", "the one the first gives")}) +} + +// agreeingDeclarations is which declarations agrees, read over the members +// all lists by their index there, names: those a member of all represents. +func agreeingDeclarations(all []member, agrees func(k int) bool) func(declarationIndex) bool { + return func(j declarationIndex) bool { + for k, member := range all { + if member.decl == j && agrees(k) { + return true + } + } + return false + } +} diff --git a/compilers/openapi/internal/merge/meet_internal_test.go b/compilers/openapi/internal/merge/intersection_internal_test.go similarity index 69% rename from compilers/openapi/internal/merge/meet_internal_test.go rename to compilers/openapi/internal/merge/intersection_internal_test.go index 6ce327391..d5c7d34d0 100644 --- a/compilers/openapi/internal/merge/meet_internal_test.go +++ b/compilers/openapi/internal/merge/intersection_internal_test.go @@ -23,17 +23,17 @@ import ( // so none is a copy of another, and the models A and B. func meetRegistry() map[ir.TypeID]ir.TypeDef { reg := narrowingRegistry() - at := func(n int) ir.Provenance { return ptrAt(declaredAt(n)) } - members := func(n int, values ...string) []ir.EnumMember { + at := func(count int) ir.Provenance { return ptrAt(declaredAt(count)) } + members := func(count int, values ...string) []ir.EnumMember { out := make([]ir.EnumMember, len(values)) for i, v := range values { - out[i] = ir.EnumMember{ID: ir.EnumMemberID("enum-member/anonymous" + string(declaredAt(n)) + "/s:" + v), Value: stringValue(v)} + out[i] = ir.EnumMember{ID: ir.EnumMemberID("enum-member/anonymous" + string(declaredAt(count)) + "/s:" + v), Value: stringValue(v)} } return out } - enum := func(id ir.TypeID, n int, values ...string) { - reg[id] = &ir.Enum{ID: id, Anonymous: true, Provenance: at(n), - ValueType: ir.PrimitiveString, Members: members(n, values...)} + enum := func(id ir.TypeID, count int, values ...string) { + reg[id] = &ir.Enum{ID: id, Anonymous: true, Provenance: at(count), Closed: true, + ValueType: ir.PrimitiveString, Members: members(count, values...)} } enum("type/ab", 0, "a", "b") enum("type/a", 1, "a") @@ -47,8 +47,8 @@ func meetRegistry() map[ir.TypeID]ir.TypeDef { enum("type/ba", 1, "b", "a") enum("type/abc-described", 0, "a", "b", "c") reg["type/abc-described"].Common().Docs.Description = "d" - list := func(id ir.TypeID, n int, element ir.TypeRef, typeCommon ir.TypeCommon) { - typeCommon.ID, typeCommon.Anonymous, typeCommon.Provenance = id, true, at(n) + list := func(id ir.TypeID, count int, element ir.TypeRef, typeCommon ir.TypeCommon) { + typeCommon.ID, typeCommon.Anonymous, typeCommon.Provenance = id, true, at(count) reg[id] = &ir.List{TypeCommon: typeCommon, ElementType: element} } described := func(d string) ir.TypeCommon { return ir.TypeCommon{Docs: ir.Docs{Description: d}} } @@ -89,7 +89,7 @@ func foldOf(targets ...ir.TypeID) (ir.Property, map[ir.TypeID]ir.TypeDef, []ir.D // TestFold_EnumsAreJudgedByTheValuesTheyShare pins GitHub #1042's enums in both // orders: the one whose values the other holds every one of is the field's -// type, with nothing minted, kept or reported; two sharing only some meet in an +// type, with nothing minted, kept or reported; two sharing only some intersect in an // enum of those, minted at the field with its members beneath it; and two // sharing none are disjoint, which warns. func TestFold_EnumsAreJudgedByTheValuesTheyShare(t *testing.T) { @@ -102,7 +102,7 @@ func TestFold_EnumsAreJudgedByTheValuesTheyShare(t *testing.T) { } got, reg, recorded := foldOf("type/ab", "type/bc") - require.Equal(t, composedAt(declaredAt(1)), got.Type.Target) + require.Equal(t, composedAt(foldKey), got.Type.Target) enum, ok := reg[got.Type.Target].(*ir.Enum) require.True(t, ok) require.Len(t, enum.Members, 1) @@ -123,7 +123,7 @@ func TestFold_ANarrowerListAdoptsTheBroadersDetail(t *testing.T) { t.Parallel() for _, order := range [][]ir.TypeID{{"type/ints-described", "type/i32s"}, {"type/i32s", "type/ints-described"}} { got, reg, recorded := foldOf(order...) - require.Equal(t, composedAt(declaredAt(1)), got.Type.Target, "%v", order) + require.Equal(t, composedAt(foldKey), got.Type.Target, "%v", order) list, ok := reg[got.Type.Target].(*ir.List) require.True(t, ok, "%v", order) assert.Equal(t, primitiveRef(ir.PrimitiveInt32), list.ElementType, "%v", order) @@ -135,7 +135,7 @@ func TestFold_ANarrowerListAdoptsTheBroadersDetail(t *testing.T) { // TestFold_ANarrowerListAdoptsTheBroadersEncoding pins the encoding a list // holds beside its detail: adopted as its documentation is, in either order, and -// where two declarations meeting the first give it differently, the first's +// where two declarations intersecting the first give it differently, the first's // kept and the other reported and kept. func TestFold_ANarrowerListAdoptsTheBroadersEncoding(t *testing.T) { t.Parallel() @@ -155,27 +155,27 @@ func TestFold_ANarrowerListAdoptsTheBroadersEncoding(t *testing.T) { } reg := meetRegistry() - encoded := func(id ir.TypeID, n int, element ir.PrimitiveKind, enc *ir.Encoding, constraints *ir.Constraints) { - reg[id] = &ir.List{ID: id, Anonymous: true, Provenance: ptrAt(declaredAt(n)), + encoded := func(id ir.TypeID, count int, element ir.PrimitiveKind, enc *ir.Encoding, constraints *ir.Constraints) { + reg[id] = &ir.List{ID: id, Anonymous: true, Provenance: ptrAt(declaredAt(count)), ElementType: primitiveRef(element), Encoding: enc, Constraints: constraints} } encoded("type/ints-min", 0, ir.PrimitiveInteger, nil, &ir.Constraints{MinItems: new(int64(1))}) encoded("type/i32s-csv", 1, ir.PrimitiveInt32, &ir.Encoding{Name: "csv"}, nil) encoded("type/i32s-tsv", 2, ir.PrimitiveInt32, &ir.Encoding{Name: "tsv"}, nil) - stubbedValue, recorded := stubMerger(reg) + stubbed, recorded := stubMerger(reg) - got := stubbedValue.fold(declsOf("type/ints-min", "type/i32s-csv", "type/i32s-tsv")) + got := stubbed.fold(declsOf("type/ints-min", "type/i32s-csv", "type/i32s-tsv")) irList, ok := reg[got.Type.Target].(*ir.List) require.True(t, ok) assert.Equal(t, &ir.Encoding{Name: "tsv"}, irList.Encoding, "the last encoding given is kept") require.Len(t, *recorded, 1, "and the other reported") assert.Equal(t, declaredAt(1), (*recorded)[0].Provenance.Pointer) - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(1))) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(1))) } // TestFold_ContainersOfModelsComposeTheirMembers pins GitHub #1180 in both -// orders: two lists, maps or tuples of different models stand on one minted +// orders: two lists, maps or tuples of different models sit on one minted // container whose member is a model composing both, minted at a position of its // own beneath the field's, with nothing kept or reported. func TestFold_ContainersOfModelsComposeTheirMembers(t *testing.T) { @@ -185,15 +185,15 @@ func TestFold_ContainersOfModelsComposeTheirMembers(t *testing.T) { member func(ir.TypeDef) ir.TypeRef at jsontext.Pointer }{ - {"type/As", "type/Bs", func(td ir.TypeDef) ir.TypeRef { return td.(*ir.List).ElementType }, "/items"}, - {"type/A-map", "type/B-map", func(td ir.TypeDef) ir.TypeRef { return td.(*ir.MapT).Value }, "/additionalProperties"}, - {"type/A-tuple", "type/B-tuple", func(td ir.TypeDef) ir.TypeRef { return td.(*ir.Tuple).ElementTypes[0] }, "/prefixItems/0"}, + {"type/As", "type/Bs", func(typeDef ir.TypeDef) ir.TypeRef { return typeDef.(*ir.List).ElementType }, "/items"}, + {"type/A-map", "type/B-map", func(typeDef ir.TypeDef) ir.TypeRef { return typeDef.(*ir.MapT).Value }, "/additionalProperties"}, + {"type/A-tuple", "type/B-tuple", func(typeDef ir.TypeDef) ir.TypeRef { return typeDef.(*ir.Tuple).ElementTypes[0] }, "/prefixItems/0"}, } { for _, order := range [][]ir.TypeID{{tc.a, tc.b}, {tc.b, tc.a}} { got, reg, recorded := foldOf(order...) - require.Equal(t, composedAt(declaredAt(1)), got.Type.Target, "%v", order) + require.Equal(t, composedAt(foldKey), got.Type.Target, "%v", order) member := tc.member(reg[got.Type.Target]) - require.Equal(t, composedAt(declaredAt(1)+tc.at), member.Target, "%v", order) + require.Equal(t, composedAt(foldKey+tc.at), member.Target, "%v", order) model, ok := reg[member.Target].(*ir.Model) require.True(t, ok, "%v", order) assert.ElementsMatch(t, []ir.TypeID{"type/A", "type/B"}, targetsOf(model.Mixins), "%v", order) @@ -203,10 +203,10 @@ func TestFold_ContainersOfModelsComposeTheirMembers(t *testing.T) { } } -// TestFold_AConstMeetsATimeScalarHoldingDetail pins the const a time scalar +// TestFold_AConstIntersectsATimeScalarHoldingDetail pins the const a time scalar // admits beside one holding a description: the field is the const, minted // holding the description too, in either order. -func TestFold_AConstMeetsATimeScalarHoldingDetail(t *testing.T) { +func TestFold_AConstIntersectsATimeScalarHoldingDetail(t *testing.T) { t.Parallel() for _, order := range [][]ir.TypeID{{"type/time-described", "type/noon"}, {"type/noon", "type/time-described"}} { got, reg, recorded := foldOf(order...) @@ -218,12 +218,12 @@ func TestFold_AConstMeetsATimeScalarHoldingDetail(t *testing.T) { } } -// TestFold_AMeetingNoNodeHoldsKeepsTheWinner pins the fall back to the winner's -// own node: three lists, each of the others meeting the first, whose elements a -// string and a bool share no value, stand on no list, so the field keeps the -// first, and each declaration meeting it is dropped, reported and kept, with -// nothing minted. -func TestFold_AMeetingNoNodeHoldsKeepsTheWinner(t *testing.T) { +// TestFold_AnIntersectionNoNodeHoldsKeepsTheChosenDeclaration pins the fall back to the chosen +// declaration's own node: three lists, each of the others intersecting the +// first, whose elements a string and a bool share no value, sit on no list, so +// the field keeps the first, and each declaration intersecting it is dropped, +// reported and kept, with nothing minted. +func TestFold_AnIntersectionNoNodeHoldsKeepsTheChosenDeclaration(t *testing.T) { t.Parallel() got, reg, recorded := foldOf("type/anys-described", "type/strs", "type/bools") count := len(meetRegistry()) @@ -231,41 +231,73 @@ func TestFold_AMeetingNoNodeHoldsKeepsTheWinner(t *testing.T) { assert.Equal(t, ir.TypeID("type/anys-described"), got.Type.Target) assert.Len(t, reg, count, "nothing is minted") assert.Len(t, recorded, 2) - assert.ElementsMatch(t, []string{losingDeclarationKey + string(declaredAt(1)), losingDeclarationKey + string(declaredAt(2))}, + assert.ElementsMatch(t, []string{passedOverDeclarationKey + string(declaredAt(1)), passedOverDeclarationKey + string(declaredAt(2))}, slices.Collect(maps.Keys(got.Unmodeled))) } -// TestFold_ADetailTwoMeetingDeclarationsGiveDifferentlyIsKept pins a detail two -// declarations meeting the winner each add, differently: the minted node takes -// the later's, and the earlier is reported, naming the detail as a document -// spells it, and kept, its narrower element still adopted. -func TestFold_ADetailTwoMeetingDeclarationsGiveDifferentlyIsKept(t *testing.T) { +// TestFold_ADetailTwoIntersectingDeclarationsGiveDifferentlyIsKept pins a detail two +// declarations intersecting the chosen declaration each add, differently. The +// two are copies differing in a note, so the minted node takes the note of the +// copy written first, whichever declaration that is (GitHub #2099), and the +// other is reported, naming the detail as a document spells it, and kept, its +// narrower element still adopted. The report names as kept the first written of +// the declarations giving the detail kept, so a fourth agreeing with the copy +// "one", written after both, changes nothing. +func TestFold_ADetailTwoIntersectingDeclarationsGiveDifferentlyIsKept(t *testing.T) { t.Parallel() - reg := meetRegistry() - reg["type/ints-min"] = &ir.List{ID: "type/ints-min", Anonymous: true, Provenance: ptrAt(declaredAt(0)), - ElementType: primitiveRef(ir.PrimitiveInteger), Constraints: &ir.Constraints{MinItems: new(int64(1))}} - stubbed, recorded := stubMerger(reg) + for name, targets := range map[string][]ir.TypeID{ + "three declarations": {"type/ints-min", "type/i32s-one", "type/i32s-other"}, + "a fourth agreeing": {"type/ints-min", "type/i32s-one", "type/i32s-other", "type/i32s-one-again"}, + } { + for _, order := range [][]ir.TypeID{targets, {targets[0], targets[2], targets[1]}, append([]ir.TypeID{targets[1], targets[0]}, targets[2:]...)} { + reg := meetRegistry() + reg["type/ints-min"] = &ir.List{ID: "type/ints-min", Anonymous: true, Provenance: ptrAt(declaredAt(0)), + ElementType: primitiveRef(ir.PrimitiveInteger), Constraints: &ir.Constraints{MinItems: new(int64(1))}} + reg["type/i32s-one-again"] = &ir.List{ID: "type/i32s-one-again", Anonymous: true, + Provenance: ptrAt(declaredAt(3)), Docs: ir.Docs{Description: "one"}, ElementType: primitiveRef(ir.PrimitiveInt32)} + placeAtDeclarations(reg, order) + stubbed, recorded := stubMerger(reg) - got := stubbed.fold(declsOf("type/ints-min", "type/i32s-one", "type/i32s-other")) + got := stubbed.fold(declsOf(order...)) - list, ok := reg[got.Type.Target].(*ir.List) - require.True(t, ok) - assert.Equal(t, "other", list.Docs.Description) - assert.Equal(t, primitiveRef(ir.PrimitiveInt32), list.ElementType) - assert.Equal(t, &ir.Constraints{MinItems: new(int64(1))}, list.Constraints) - require.Len(t, *recorded, 1) - assert.Equal(t, declaredAt(1), (*recorded)[0].Provenance.Pointer) - assert.Contains(t, (*recorded)[0].Message, "give the docs of a type", "the detail is named as a document spells it") - assert.Contains(t, got.Unmodeled, losingDeclarationKey+string(declaredAt(1))) + list, ok := reg[got.Type.Target].(*ir.List) + require.True(t, ok, name) + first, second := slices.Index(order, "type/i32s-one"), slices.Index(order, "type/i32s-other") + note := "one" + if second < first { + first, second, note = second, first, "other" + } + assert.Equal(t, note, list.Docs.Description, name) + assert.Equal(t, primitiveRef(ir.PrimitiveInt32), list.ElementType, name) + assert.Equal(t, &ir.Constraints{MinItems: new(int64(1))}, list.Constraints, name) + other := declaredAt(second) + require.Len(t, *recorded, 1, name) + assert.Equal(t, other, (*recorded)[0].Provenance.Pointer, name) + kept := declaredAt(first) + assert.Equal(t, []ir.Related{{Role: ir.RelatedChosen, Provenance: ptrAt(kept)}}, (*recorded)[0].Related, name) + assert.Contains(t, (*recorded)[0].Message, "give the docs of a type", "the detail is named as a document spells it: %s", name) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(other), name) + } + } +} + +// placeAtDeclarations writes each anonymous node of targets at the declaration +// declsOf gives it, so the node is hoisted there. +func placeAtDeclarations(reg map[ir.TypeID]ir.TypeDef, targets []ir.TypeID) { + for i, target := range targets { + if typeCommon := reg[target].Common(); typeCommon.Anonymous { + typeCommon.Provenance = ptrAt(declaredAt(i)) + } + } } -// TestFold_EnumsListingSharedValuesApartKeepTheWinner pins two enums listing +// TestFold_EnumsListingSharedValuesApartKeepTheChosenDeclaration pins two enums listing // the values they share in different orders, in either entry order: an enum of // both would take one declaration's order, so the two overlap, and the field // keeps the later, reports the other and mints nothing, whether each holds a // value the other lacks or one holds only the other's values beside less -// detail. Two listing them in one order meet in an enum of those in that order. -func TestFold_EnumsListingSharedValuesApartKeepTheWinner(t *testing.T) { +// detail. Two listing them in one order intersect in an enum of those in that order. +func TestFold_EnumsListingSharedValuesApartKeepTheChosenDeclaration(t *testing.T) { t.Parallel() for _, pair := range [][2]ir.TypeID{{"type/abc", "type/cbd"}, {"type/abc-described", "type/ba"}} { for _, order := range [][2]ir.TypeID{pair, {pair[1], pair[0]}} { @@ -289,10 +321,10 @@ func TestFold_EnumsListingSharedValuesApartKeepTheWinner(t *testing.T) { } } -// TestFold_EnumsSharingNoValueTogetherKeepTheWinner pins three enums each -// meeting the others in a value no third holds: no value is in all three, so no +// TestFold_EnumsSharingNoValueTogetherKeepTheChosenDeclaration pins three enums each +// intersecting the others in a value no third holds: no value is in all three, so no // enum holds them, and the field keeps the last, each other reported and kept. -func TestFold_EnumsSharingNoValueTogetherKeepTheWinner(t *testing.T) { +func TestFold_EnumsSharingNoValueTogetherKeepTheChosenDeclaration(t *testing.T) { t.Parallel() got, reg, recorded := foldOf("type/ab", "type/ac", "type/bc2") @@ -301,22 +333,23 @@ func TestFold_EnumsSharingNoValueTogetherKeepTheWinner(t *testing.T) { assert.Len(t, recorded, 2) } -// TestFold_AFailedMeetingReportsOnlyItsDrops pins the dry run's silence: two -// tuples meeting the first, whose first positions meet in lists giving a pattern -// differently and whose second hold a string and a bool, stand on no tuple. The -// pattern no list was built with is not reported, only each dropped declaration. -func TestFold_AFailedMeetingReportsOnlyItsDrops(t *testing.T) { +// TestFold_AFailedIntersectionReportsOnlyItsDrops pins the dry run's silence: two +// tuples intersecting the first, whose first positions intersect in lists +// giving a pattern differently and whose second hold a string and a bool, sit +// on no tuple. The pattern no list was built with is not reported, only each +// dropped declaration. +func TestFold_AFailedIntersectionReportsOnlyItsDrops(t *testing.T) { t.Parallel() reg := meetRegistry() - list := func(id ir.TypeID, n int, element ir.TypeRef, constraints *ir.Constraints) { - reg[id] = &ir.List{ID: id, Anonymous: true, Provenance: ptrAt(declaredAt(n) + "/prefixItems/0"), + list := func(id ir.TypeID, count int, element ir.TypeRef, constraints *ir.Constraints) { + reg[id] = &ir.List{ID: id, Anonymous: true, Provenance: ptrAt(declaredAt(count) + "/prefixItems/0"), ElementType: element, Constraints: constraints} } list("type/l0", 0, primitiveRef(ir.PrimitiveAny), &ir.Constraints{Pattern: "^a$"}) list("type/l1", 1, primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^b$"}) list("type/l2", 2, primitiveRef(ir.PrimitiveAny), &ir.Constraints{MaxItems: new(int64(3))}) - tuple := func(id ir.TypeID, n int, first ir.TypeID, second ir.TypeRef) { - reg[id] = &ir.Tuple{ID: id, Anonymous: true, Provenance: ptrAt(declaredAt(n)), + tuple := func(id ir.TypeID, count int, first ir.TypeID, second ir.TypeRef) { + reg[id] = &ir.Tuple{ID: id, Anonymous: true, Provenance: ptrAt(declaredAt(count)), ElementTypes: []ir.TypeRef{ref(first), second}} } tuple("type/t0", 0, "type/l0", primitiveRef(ir.PrimitiveAny)) @@ -358,8 +391,8 @@ func TestFold_AnEnumWithinAnotherAdoptsItsDetail(t *testing.T) { // TestFold_ANarrowerListAdoptsWhatTheBroaderKeeps pins what a node keeps under // Unmodeled: adopted with the provenance it was kept at, in either order, and a -// key two declarations meeting the first keep differently is the first's, the -// other reported and kept. +// key two declarations intersecting the first keep differently kept under each +// one's own key, as an object of what it keeps apart, each reported once. func TestFold_ANarrowerListAdoptsWhatTheBroaderKeeps(t *testing.T) { t.Parallel() kept := func(v string) ir.Unmodeled { @@ -387,19 +420,23 @@ func TestFold_ANarrowerListAdoptsWhatTheBroaderKeeps(t *testing.T) { reg[id] = &ir.List{ID: id, Anonymous: true, Provenance: ptrAt(declaredAt(n + 1)), Unmodeled: kept(v), ElementType: primitiveRef(ir.PrimitiveInt32)} } - stubbedValue, recorded := stubMerger(reg) + stubbed, recorded := stubMerger(reg) - got := stubbedValue.fold(declsOf("type/ints-min", "type/i32s-kept-1", "type/i32s-kept-2")) + got := stubbed.fold(declsOf("type/ints-min", "type/i32s-kept-1", "type/i32s-kept-2")) irList, ok := reg[got.Type.Target].(*ir.List) require.True(t, ok) - assert.Equal(t, kept("2"), irList.Unmodeled) - require.Len(t, *recorded, 1) - assert.Equal(t, declaredAt(1), (*recorded)[0].Provenance.Pointer) + assert.Equal(t, ir.Unmodeled{ + "openapi:allOf/1/properties/data": {Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(`{"x-a":1}`), Provenance: ptrAt(declaredAt(1))}, + "openapi:allOf/2/properties/data": {Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(`{"x-a":2}`), Provenance: ptrAt(declaredAt(2))}, + }, irList.Unmodeled) + require.Len(t, *recorded, 2) + assert.Equal(t, []jsontext.Pointer{declaredAt(1), declaredAt(2)}, []jsontext.Pointer{(*recorded)[0].Provenance.Pointer, (*recorded)[1].Provenance.Pointer}) + assert.Empty(t, got.Unmodeled, "no declaration is kept verbatim beside the field") } // TestFold_TuplesBuildWhatFollowsTheirPositions pins a tuple's rest: two tuples -// of different models with rests of different models stand on one tuple whose +// of different models with rests of different models sit on one tuple whose // position and rest each compose both, the rest minted at its own position. func TestFold_TuplesBuildWhatFollowsTheirPositions(t *testing.T) { t.Parallel() @@ -416,15 +453,15 @@ func TestFold_TuplesBuildWhatFollowsTheirPositions(t *testing.T) { tu, ok := reg[got.Type.Target].(*ir.Tuple) require.True(t, ok) require.NotNil(t, tu.Rest) - assert.Equal(t, composedAt(declaredAt(1)+"/items"), tu.Rest.Target) - assert.Equal(t, composedAt(declaredAt(1)+"/prefixItems/0"), tu.ElementTypes[0].Target) + assert.Equal(t, composedAt(foldKey+"/items"), tu.Rest.Target) + assert.Equal(t, composedAt(foldKey+"/prefixItems/0"), tu.ElementTypes[0].Target) assert.Empty(t, *recorded) } // TestBuilder_RefusesWhatNoNodeHolds pins the build's own guards, which the // judgment keeps every fold from reaching: a partner the registry does not // hold, nodes of a kind no node is built of, tuples of different shapes, and an -// enum beside a node of another kind each fail the build, and a literal meets +// enum beside a node of another kind each fail the build, and a literal intersects // only a Scalar holding more than its format. func TestBuilder_RefusesWhatNoNodeHolds(t *testing.T) { t.Parallel() @@ -434,8 +471,8 @@ func TestBuilder_RefusesWhatNoNodeHolds(t *testing.T) { reg["type/A-rest-tuple"] = &ir.Tuple{ID: "type/A-rest-tuple", Anonymous: true, Provenance: ptrAt(declaredAt(1)), ElementTypes: []ir.TypeRef{ref("type/A")}, Rest: new(ref("type/A"))} stubbed, _ := stubMerger(reg) - folding := newFolding(&stubbed.Merger, declsOf("type/A", "type/B"), declaredAt(1)) - m := func(id ir.TypeID, decl int) member { return member{ref: ref(id), decl: decl} } + folding := newFieldFold(&stubbed.Merger, declsOf("type/A", "type/B"), declaredAt(1)) + m := func(id ir.TypeID, decl declarationIndex) member { return member{ref: ref(id), decl: decl} } for _, tc := range []struct { name string base, partner member @@ -448,7 +485,7 @@ func TestBuilder_RefusesWhatNoNodeHolds(t *testing.T) { {"an enum beside a list", m("type/ab", 0), m("type/i32s", 1)}, } { b := builder{f: folding, dry: true} - b.meetNode(tc.base, []member{tc.partner}, declaredAt(1), 0) + b.intersectionNode(tc.base, []member{tc.partner}, declaredAt(1), 0) assert.True(t, b.failed, tc.name) } @@ -460,8 +497,8 @@ func TestBuilder_RefusesWhatNoNodeHolds(t *testing.T) { // type the merge builds the field's node from: that node can hold members or // values the declaration's own does not, so the value is judged against it, in // either order. A list of integer's default past int32 is refused beside a list -// of int32, and an enum's default the meeting cut is refused beside the enum it -// meets, each reported and kept. +// of int32, and an enum's default the intersecting cut is refused beside the enum it +// intersects, each reported and kept. func TestFold_AValueIsJudgedByTheNodeTheFieldHolds(t *testing.T) { t.Parallel() big := ir.Value{Kind: ir.ValueList, List: []ir.Value{number("5000000000")}} @@ -485,7 +522,7 @@ func TestFold_AValueIsJudgedByTheNodeTheFieldHolds(t *testing.T) { got := stubbed.fold(decls) - assert.Equal(t, composedAt(declaredAt(1)), got.Type.Target, "%s (order %d)", tc.name, i) + assert.Equal(t, composedAt(foldKey), got.Type.Target, "%s (order %d)", tc.name, i) assert.Nil(t, got.Default, "%s (order %d)", tc.name, i) require.Len(t, *recorded, 1, "%s (order %d)", tc.name, i) assert.Equal(t, declaredAt(i), (*recorded)[0].Provenance.Pointer, "%s (order %d)", tc.name, i) @@ -493,12 +530,13 @@ func TestFold_AValueIsJudgedByTheNodeTheFieldHolds(t *testing.T) { } } -// TestFold_AnAliasMeetsAsTheNodeItStandsFor pins GitHub #1672 in both orders: a -// field declared as an alias of an enum or a list and as a node it meets stands -// on the node they meet in, built from the node the alias stands for, holding -// what the alias adds: its bounds and its docs. Two aliases of one node meet in -// an alias of it holding what each adds. Nothing is kept or reported. -func TestFold_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { +// TestFold_AnAliasIntersectsAsTheNodeItRepresents pins GitHub #1672 in both orders: a +// field declared as an alias of an enum or a list and as a node it intersects +// sits on the node they intersect in, built from the node the alias represents, +// holding what the alias adds: its bounds and its docs. Two aliases of one node +// intersect in an alias of it holding what each adds. Nothing is kept or +// reported. +func TestFold_AnAliasIntersectsAsTheNodeItRepresents(t *testing.T) { t.Parallel() reg := meetRegistry() alias := func(id, base ir.TypeID, docs string, constraints *ir.Constraints) { @@ -514,21 +552,21 @@ func TestFold_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { a, b ir.TypeID check func(t *testing.T, td ir.TypeDef, label string) }{ - {"an alias of an enum", "type/ab-alias", "type/bc", func(t *testing.T, td ir.TypeDef, label string) { - enum, ok := td.(*ir.Enum) + {"an alias of an enum", "type/ab-alias", "type/bc", func(t *testing.T, typeDef ir.TypeDef, label string) { + enum, ok := typeDef.(*ir.Enum) require.True(t, ok, label) assert.Equal(t, []ir.Value{stringValue("b")}, valuesOf(enum), label) assert.Equal(t, "alias", enum.Docs.Description, label) }}, - {"an alias of a list", "type/ints-alias", "type/i32s", func(t *testing.T, td ir.TypeDef, label string) { - list, ok := td.(*ir.List) + {"an alias of a list", "type/ints-alias", "type/i32s", func(t *testing.T, typeDef ir.TypeDef, label string) { + list, ok := typeDef.(*ir.List) require.True(t, ok, label) assert.Equal(t, primitiveRef(ir.PrimitiveInt32), list.ElementType, label) assert.Equal(t, "d", list.Docs.Description, "%s: the docs the alias reads from its node", label) assert.Equal(t, &ir.Constraints{MaxItems: new(int64(3))}, list.Constraints, label) }}, - {"two aliases of one list", "type/As-min", "type/As-max", func(t *testing.T, td ir.TypeDef, label string) { - scalar, ok := td.(*ir.Scalar) + {"two aliases of one list", "type/As-min", "type/As-max", func(t *testing.T, typeDef ir.TypeDef, label string) { + scalar, ok := typeDef.(*ir.Scalar) require.True(t, ok, "%s: an alias of the list they share", label) assert.Equal(t, ir.TypeRef{Target: "type/As"}, *scalar.Base, label) assert.Equal(t, &ir.Constraints{MinItems: new(int64(1)), MaxItems: new(int64(3))}, scalar.Constraints, label) @@ -540,7 +578,7 @@ func TestFold_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { got := stubbed.fold(declsOf(order...)) - require.Equal(t, composedAt(declaredAt(1)), got.Type.Target, label) + require.Equal(t, composedAt(foldKey), got.Type.Target, label) tc.check(t, stubbed.Reg[got.Type.Target], label) assert.Empty(t, *recorded, label) assert.Empty(t, got.Unmodeled, label) @@ -548,10 +586,10 @@ func TestFold_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { } } -// TestFold_AnAliasIsWithinTheNodeItStandsFor pins an alias against the node it -// stands for, in either order: the alias says all the node does and may say more, +// TestFold_AnAliasIsWithinTheNodeItRepresents pins an alias against the node it +// represents, in either order: the alias says all the node does and may say more, // so the field takes it, with nothing minted, kept or reported. -func TestFold_AnAliasIsWithinTheNodeItStandsFor(t *testing.T) { +func TestFold_AnAliasIsWithinTheNodeItRepresents(t *testing.T) { t.Parallel() reg := meetRegistry() reg["type/ab-alias"] = &ir.Scalar{ID: "type/ab-alias", Base: &ir.TypeRef{Target: "type/ab"}} diff --git a/compilers/openapi/internal/merge/intersectionentries.go b/compilers/openapi/internal/merge/intersectionentries.go new file mode 100644 index 000000000..617614a7a --- /dev/null +++ b/compilers/openapi/internal/merge/intersectionentries.go @@ -0,0 +1,119 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "encoding/json/v2" + "maps" + "slices" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// intersectionEntries returns what the node built from nodes keeps under +// Unmodeled, own in place of nodes[0]'s, as one position keeps what its +// allOf's entries keep (docs/compilers/openapi.md#allof-redeclared-property): +// a key every holder keeps alike once, and otherwise each declaration's value +// under a key of its own (keepApart), but the narrowest length under its key +// where lengthsBound says the values are text. keepsWhole keeps only what is +// kept alike. +func (b *builder) intersectionEntries(own ir.Unmodeled, all []member, nodes []ir.TypeDef, keepsWhole, lengthsBound bool) ir.Unmodeled { + entriesOf := func(k int) ir.Unmodeled { + if k == 0 { + return own + } + return nodes[k].Common().Unmodeled + } + holders := map[string][]int{} + for k := range nodes { + for key := range entriesOf(k) { + holders[key] = append(holders[key], k) + } + } + var out ir.Unmodeled + apart := map[declarationIndex]map[string]jsontext.Value{} + for _, key := range slices.Sorted(maps.Keys(holders)) { + held := holders[key] + if entry, alike := keptAlike(b.f.g.Walk, key, held, entriesOf); alike { + annotation.KeepInto(&out, key, entry.Value, entry.Reason, entry.Provenance) + continue + } + if keepsWhole { + continue + } + if entry, narrowest, ok := narrowestLength(key, held, entriesOf); ok && lengthsBound { + annotation.KeepInto(&out, key, entry.Value, entry.Reason, entry.Provenance) + held = slices.DeleteFunc(slices.Clone(held), narrowest) + } + b.collectApart(apart, key, held, all, entriesOf) + } + for _, decl := range slices.Sorted(maps.Keys(apart)) { + b.keepApart(&out, decl, apart[decl]) + } + return out +} + +// keptAlike returns the entry under key that the nodes holders indexes keep +// alike (sameEntry), the first written of them, and false where two keep it +// apart. +func keptAlike(walk FieldDeclarationContext, key string, holders []int, entriesOf func(int) ir.Unmodeled) (ir.UnmodeledEntry, bool) { + first := entriesOf(holders[0])[key] + for _, k := range holders[1:] { + entry := entriesOf(k)[key] + if !sameEntry(walk, first, entry) { + return ir.UnmodeledEntry{}, false + } + if writtenBefore(entry.Provenance, first.Provenance) { + first = entry + } + } + return first, true +} + +// collectApart adds, for each node holders indexes, the value it keeps under +// key to what its declaration keeps apart. A declaration another model brings +// keeps its own on its node there. +func (b *builder) collectApart(apart map[declarationIndex]map[string]jsontext.Value, key string, holders []int, all []member, + entriesOf func(int) ir.Unmodeled, +) { + keyword := strings.TrimPrefix(key, annotation.EntryKey("", "")) + for _, k := range holders { + decl := all[k].decl + if b.f.decls[decl].via != nil { + continue + } + if apart[decl] == nil { + apart[decl] = map[string]jsontext.Value{} + } + apart[decl][keyword] = entriesOf(k)[key].Value + } +} + +// keepApart keeps on out, under the key naming the declaration decl, the +// object of the keywords it keeps apart from the other declarations at the +// node, with one info where the build is no dry run. An object that will not +// encode fails the build. +func (b *builder) keepApart(out *ir.Unmodeled, decl declarationIndex, keywords map[string]jsontext.Value) { + at := b.f.decls[decl].property.Provenance + raw, err := json.Marshal(keywords, json.Deterministic(true)) + if err != nil { + b.failed = true + return + } + key := chosenDeclarationKey(b.f.fieldPointer, at.Pointer) + annotation.KeepInto(out, key, raw, ir.ReasonDegradedLowering, at) + if b.dry { + return + } + b.f.note(decl, ir.SeverityInfo, diag.DegradedConstruct, + "field %q: the other declarations write %s differently from this one, and one Unmodeled entry under a "+ + "keyword holds one value; this declaration's are kept verbatim under Unmodeled under the key naming "+ + "it, %s, on the node built as the intersection of the field's declarations, the rest of it folded", + b.f.merged.WireName, strings.Join(slices.Sorted(maps.Keys(keywords)), ", "), + strings.TrimPrefix(key, annotation.EntryKey("", ""))) +} diff --git a/compilers/openapi/internal/merge/intersectionentries_internal_test.go b/compilers/openapi/internal/merge/intersectionentries_internal_test.go new file mode 100644 index 000000000..54c8bb0a1 --- /dev/null +++ b/compilers/openapi/internal/merge/intersectionentries_internal_test.go @@ -0,0 +1,291 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "maps" + "slices" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// entryKeptAt is an entry kept verbatim holding value under reason, written at the +// keyword below the nth declaration declsOf gives. +func entryKeptAt(count int, keyword, value string, reason ir.UnmodeledReason) ir.UnmodeledEntry { + return ir.UnmodeledEntry{Reason: reason, Value: ir.RawValue(value), Provenance: ptrAt(declaredAt(count) + jsontext.Pointer("/"+keyword))} +} + +// entryRow is what a test reads of one entry: its value, reason and where it +// is written. +type entryRow struct { + value string + reason ir.UnmodeledReason + pointer jsontext.Pointer +} + +// rowsOf reads unmodeled as entry rows. +func rowsOf(unmodeled ir.Unmodeled) map[string]entryRow { + out := map[string]entryRow{} + for key, entry := range unmodeled { + out[key] = entryRow{string(entry.Value), entry.Reason, entry.Provenance.Pointer} + } + return out +} + +// foldKeepsReports lists where the fold reported keeping keywords of a +// declaration apart, each its code and pointer. +func foldKeepsReports(diags []ir.Diagnostic) []string { + var out []string + for _, diagnostic := range diags { + if strings.Contains(diagnostic.Message, "the other declarations write") { + out = append(out, diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + } + slices.Sort(out) + return out +} + +// TestFold_NodesKeepingAKeywordApartKeepItUnderEachDeclaration pins what a +// node built of copies keeps of what each keeps verbatim, in both orders of +// the declarations: a keyword one value is written under once, as the first +// written keeps it, under its reason, with no report; a keyword kept apart +// under the key of each declaration writing it, an object of what that one +// keeps apart, under degraded_lowering, with one info at it; and the field +// takes the node, minted at the fold's key. +func TestFold_NodesKeepingAKeywordApartKeepItUnderEachDeclaration(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + for _, reversed := range []bool{false, true} { + // values[n] is the minimum the nth declaration keeps; the first two + // keep one maximum alike, and the rest one readOnly alike, the node + // built from the first. + values := []string{"1", "2", "1"} + if reversed { + slices.Reverse(values) + } + reg := narrowingRegistry() + targets := make([]ir.TypeID, 3) + for n, value := range values { + unmodeled := ir.Unmodeled{"openapi:minimum": entryKeptAt(n, "minimum", value, ir.ReasonDegradedLowering)} + if n < 2 { + unmodeled["openapi:maximum"] = entryKeptAt(n, "maximum", "9", ir.ReasonDegradedLowering) + } + if n > 0 { + unmodeled["openapi:readOnly"] = entryKeptAt(n, "readOnly", "true", ir.ReasonNoIRHome) + } + targets[n] = ir.TypeID("type/s" + string(rune('0'+n))) + reg[targets[n]] = hoisted(n, &ir.Scalar{ID: targets[n], Base: &text, Unmodeled: unmodeled}) + } + stubbed, recorded := stubMerger(reg) + + got := stubbed.fold(declsOf(targets...)) + + require.Equal(t, composedAt(foldKey), got.Type.Target, "reversed %v", reversed) + node, ok := reg[got.Type.Target].(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, map[string]entryRow{ + "openapi:maximum": {"9", ir.ReasonDegradedLowering, declaredAt(0) + "/maximum"}, + "openapi:readOnly": {"true", ir.ReasonNoIRHome, declaredAt(1) + "/readOnly"}, + "openapi:allOf/0/properties/data": {`{"minimum":` + values[0] + `}`, ir.ReasonDegradedLowering, declaredAt(0)}, + "openapi:allOf/1/properties/data": {`{"minimum":` + values[1] + `}`, ir.ReasonDegradedLowering, declaredAt(1)}, + "openapi:allOf/2/properties/data": {`{"minimum":` + values[2] + `}`, ir.ReasonDegradedLowering, declaredAt(2)}, + }, rowsOf(node.Unmodeled), "reversed %v", reversed) + assert.Equal(t, []string{diag.DegradedConstruct + " " + string(declaredAt(0)), diag.DegradedConstruct + " " + string(declaredAt(1)), + diag.DegradedConstruct + " " + string(declaredAt(2))}, foldKeepsReports(*recorded), "reversed %v", reversed) + assert.Len(t, *recorded, 3, "nothing else is reported: %v", *recorded) + assert.Empty(t, got.Unmodeled, "no declaration is kept verbatim beside the field") + } +} + +// TestIntersectionEntries_KeepsNothingAnotherModelBringsOrTheEnumKeepsWhole pins the +// keyword a declaration another model brings keeps apart, which stays on its +// own node, the enum of no member, which keeps each declaration whole and so +// only what is kept alike, and an entry no object can hold, which fails the +// build. +func TestIntersectionEntries_KeepsNothingAnotherModelBringsOrTheEnumKeepsWhole(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + node := func(count int, minimum string) ir.TypeDef { + return &ir.Scalar{Base: &text, Unmodeled: ir.Unmodeled{ + "openapi:minimum": entryKeptAt(count, "minimum", minimum, ir.ReasonDegradedLowering), + "openapi:maximum": entryKeptAt(count, "maximum", "9", ir.ReasonDegradedLowering), + }} + } + stubbed, _ := stubMerger(narrowingRegistry()) + decls := declsOf("type/a", "type/b") + decls[1].via = &composedEntry{target: "type/other", at: "/other"} + f := &fieldFold{g: &stubbed.Merger, decls: decls, fieldPointer: foldKey, notes: make([][]note, 2)} + b := builder{f: f} + all := []member{{decl: 0}, {decl: 1}} + nodes := []ir.TypeDef{node(0, "1"), node(1, "2")} + + assert.Equal(t, []string{"openapi:allOf/0/properties/data", "openapi:maximum"}, + slices.Sorted(maps.Keys(b.intersectionEntries(nodes[0].Common().Unmodeled, all, nodes, false, true))), "one another model brings stays there") + assert.Equal(t, []string{"openapi:maximum"}, slices.Sorted(maps.Keys(b.intersectionEntries(nodes[0].Common().Unmodeled, all, nodes, true, true))), + "an enum keeping each declaration whole keeps only what is kept alike") + assert.False(t, b.failed) + + broken := node(1, "{") + b.intersectionEntries(nodes[0].Common().Unmodeled, []member{{decl: 0}, {decl: 0}}, []ir.TypeDef{nodes[0], broken}, false, true) + assert.True(t, b.failed, "an entry no object holds fails the build") +} + +// TestFold_KeptTextBoundsIntersectByKeyword pins lengths declarations keep +// verbatim with no IR home, as a text bound over a text of another kind is: +// the declarations intersect, the narrowest under the plain key, the least maximum +// and the greatest minimum, as the first written giving it keeps it, and each +// other declaration's under its own key, with one info, in both orders. +func TestFold_KeptTextBoundsIntersectByKeyword(t *testing.T) { + t.Parallel() + uuid := primitiveRef(ir.PrimitiveUUID) + for _, tc := range []struct { + name, keyword string + values [3]string + plain string + }{ + {"maximums", "maxLength", [3]string{"40", "36", "36"}, "36"}, + {"minimums", "minLength", [3]string{"30", "36", "32"}, "36"}, + } { + for _, reversed := range []bool{false, true} { + values := tc.values + if reversed { + values = [3]string{values[2], values[1], values[0]} + } + reg := narrowingRegistry() + targets := make([]ir.TypeID, 3) + for n, value := range values { + targets[n] = ir.TypeID("type/s" + strconv.Itoa(n)) + reg[targets[n]] = hoisted(n, &ir.Scalar{ID: targets[n], Base: &uuid, + Unmodeled: ir.Unmodeled{"openapi:" + tc.keyword: entryKeptAt(n, tc.keyword, value, ir.ReasonNoIRHome)}}) + } + stubbed, recorded := stubMerger(reg) + + got := stubbed.fold(declsOf(targets...)) + + node, ok := reg[got.Type.Target].(*ir.Scalar) + require.True(t, ok, "%s, reversed %v", tc.name, reversed) + from := slices.Index(values[:], tc.plain) + want := map[string]entryRow{"openapi:" + tc.keyword: {tc.plain, ir.ReasonNoIRHome, declaredAt(from) + jsontext.Pointer("/"+tc.keyword)}} + var reports []string + for n, value := range values { + if value != tc.plain { + want["openapi:allOf/"+strconv.Itoa(n)+"/properties/data"] = entryRow{`{"` + tc.keyword + `":` + value + `}`, + ir.ReasonDegradedLowering, declaredAt(n)} + reports = append(reports, diag.DegradedConstruct+" "+string(declaredAt(n))) + } + } + assert.Equal(t, composedAt(foldKey), got.Type.Target, "%s, reversed %v", tc.name, reversed) + assert.Equal(t, want, rowsOf(node.Unmodeled), "%s, reversed %v", tc.name, reversed) + assert.Equal(t, reports, foldKeepsReports(*recorded), "%s, reversed %v", tc.name, reversed) + assert.Len(t, *recorded, len(reports), "%s, reversed %v: nothing else is reported", tc.name, reversed) + } + } +} + +// TestKeptLength_ReadsALengthKeptAsACount pins which entries the fold reads as +// a kept length: minLength or maxLength under its own key, written as a count, +// and no other key, no count that is no whole number at least zero. +func TestKeptLength_ReadsALengthKeptAsACount(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + key, value string + want bool + }{ + {"openapi:maxLength", "3", true}, + {"openapi:minLength", "0", true}, + {"openapi:maxLength/inner", "3", false}, + {"openapi:minimum", "3", false}, + {"openapi:maxLength", "-1", false}, + {"openapi:maxLength", `"3"`, false}, + } { + _, _, ok := keptLength(tc.key, ir.UnmodeledEntry{Value: ir.RawValue(tc.value)}) + assert.Equal(t, tc.want, ok, "%s %s", tc.key, tc.value) + } +} + +// TestTypeJudge_KeptLengthsAreReadAsBounds pins two nodes of a text kind +// keeping lengths: apart, they intersect; one keeping a length the other does +// not is narrower; alike, they are one type; a length that is no count is read +// as any kept entry, and one kept on an integer, saying nothing, decides +// nothing. +func TestTypeJudge_KeptLengthsAreReadAsBounds(t *testing.T) { + t.Parallel() + uuid, integer := primitiveRef(ir.PrimitiveUUID), primitiveRef(ir.PrimitiveInteger) + scalar := func(id ir.TypeID, count int, base ir.TypeRef, unmodeled ir.Unmodeled) *ir.Scalar { + return hoisted(count, &ir.Scalar{ID: id, Base: &base, Unmodeled: unmodeled}) + } + length := func(count int, value string) ir.Unmodeled { + return ir.Unmodeled{"openapi:maxLength": entryKeptAt(count, "maxLength", value, ir.ReasonNoIRHome)} + } + reg := narrowingRegistry() + reg["type/u40"], reg["type/u36"] = scalar("type/u40", 0, uuid, length(0, "40")), scalar("type/u36", 1, uuid, length(1, "36")) + reg["type/u40-again"] = scalar("type/u40-again", 1, uuid, length(1, "40")) + reg["type/u-documented"] = scalar("type/u-documented", 1, uuid, nil) + reg["type/u-documented"].Common().Docs.Description = "documented" + reg["type/u-text"], reg["type/u-text2"] = scalar("type/u-text", 0, uuid, length(0, `"40"`)), scalar("type/u-text2", 1, uuid, length(1, `"36"`)) + reg["type/i40"], reg["type/i36"] = scalar("type/i40", 0, integer, length(0, "40")), scalar("type/i36", 1, integer, length(1, "36")) + stubbed, _ := stubMerger(reg) + judgeAt := stubbed.judgeAt(sitesAt(declaredAt(0)), sitesAt(declaredAt(1))) + for _, tc := range []struct { + name string + a, b ir.TypeID + want relation + }{ + {"lengths apart", "type/u40", "type/u36", relIntersect}, + {"lengths alike", "type/u40", "type/u40-again", relSame}, + {"a length beside docs", "type/u40", "type/u-documented", relIntersect}, + {"docs beside a length", "type/u-documented", "type/u40", relIntersect}, + {"lengths that are no counts", "type/u-text", "type/u-text2", relOverlap}, + {"lengths on integers", "type/i40", "type/i36", relSame}, + } { + assert.Equal(t, tc.want, judgeAt.relate(ref(tc.a), ref(tc.b)), tc.name) + } +} + +// TestIntersectionEntries_ALengthNotEveryHolderKeepsAsACountIsKeptApart pins a +// length two nodes keep apart where one keeps it as no count: no narrowest is +// read, and each declaration keeps its own under its key. +func TestIntersectionEntries_ALengthNotEveryHolderKeepsAsACountIsKeptApart(t *testing.T) { + t.Parallel() + uuid := primitiveRef(ir.PrimitiveUUID) + node := func(count int, value string) ir.TypeDef { + return &ir.Scalar{Base: &uuid, Unmodeled: ir.Unmodeled{"openapi:maxLength": entryKeptAt(count, "maxLength", value, ir.ReasonNoIRHome)}} + } + stubbed, _ := stubMerger(narrowingRegistry()) + b := builder{f: &fieldFold{g: &stubbed.Merger, decls: declsOf("type/a", "type/b"), fieldPointer: foldKey, notes: make([][]note, 2)}} + nodes := []ir.TypeDef{node(0, "3"), node(1, `"4"`)} + + got := b.intersectionEntries(nodes[0].Common().Unmodeled, []member{{decl: 0}, {decl: 1}}, nodes, false, true) + + assert.Equal(t, []string{"openapi:allOf/0/properties/data", "openapi:allOf/1/properties/data"}, slices.Sorted(maps.Keys(got))) +} + +// TestFold_LengthsSayingNothingAreKeptUnderEachDeclaration pins lengths two integer +// declarations keep apart: saying nothing beside an integer's values, they are no +// bound, so each is kept under its declaration's key and none under its own. +func TestFold_LengthsSayingNothingAreKeptUnderEachDeclaration(t *testing.T) { + t.Parallel() + integer := primitiveRef(ir.PrimitiveInteger) + reg := narrowingRegistry() + for n, value := range []string{"3", "4"} { + id := ir.TypeID("type/i" + strconv.Itoa(n)) + reg[id] = hoisted(n, &ir.Scalar{ID: id, Base: &integer, + Unmodeled: ir.Unmodeled{"openapi:maxLength": entryKeptAt(n, "maxLength", value, ir.ReasonDegradedLowering)}}) + } + stubbed, _ := stubMerger(reg) + + got := stubbed.fold(declsOf("type/i0", "type/i1")) + + node, ok := reg[got.Type.Target].(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, []string{"openapi:allOf/0/properties/data", "openapi:allOf/1/properties/data"}, slices.Sorted(maps.Keys(node.Unmodeled))) +} diff --git a/compilers/openapi/internal/merge/judgment_internal_test.go b/compilers/openapi/internal/merge/judgment_internal_test.go new file mode 100644 index 000000000..263d1deda --- /dev/null +++ b/compilers/openapi/internal/merge/judgment_internal_test.go @@ -0,0 +1,297 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/ir" +) + +// hoisted returns node hoisted at the nth declaration declsOf gives. +func hoisted[T ir.TypeDef](count int, node T) T { + common := node.Common() + common.Anonymous, common.Provenance = true, ptrAt(declaredAt(count)) + return node +} + +// TestFold_TwoUnionsAlikeIntersectTheirBoundsWhereTheirVariantsAreOne pins the +// union pair the fold intersects: untagged, of one exclusiveness, variants the +// same type in any order, each holding a bound the other lacks, intersect in a +// union holding both; a tagged one, or one whose variants differ, does not. +func TestFold_TwoUnionsAlikeIntersectTheirBoundsWhereTheirVariantsAreOne(t *testing.T) { + t.Parallel() + union := func(id ir.TypeID, count int, constraints *ir.Constraints, variants ...ir.PrimitiveKind) *ir.Union { + node := &ir.Union{ID: id, Exclusive: true, Closed: true, Constraints: constraints} + for _, kind := range variants { + node.Variants = append(node.Variants, ir.Variant{Type: primitiveRef(kind)}) + } + return hoisted(count, node) + } + minLength, maxLength := &ir.Constraints{MinLength: new(int64(2))}, &ir.Constraints{MaxLength: new(int64(8))} + reg := narrowingRegistry() + reg["type/u-min"] = union("type/u-min", 0, minLength, ir.PrimitiveString, ir.PrimitiveInteger) + reg["type/u-max"] = union("type/u-max", 1, maxLength, ir.PrimitiveInteger, ir.PrimitiveString) + reg["type/u-other"] = union("type/u-other", 1, maxLength, ir.PrimitiveBool, ir.PrimitiveString) + tagged := union("type/u-tagged", 1, maxLength, ir.PrimitiveInteger, ir.PrimitiveString) + tagged.WireTagged = true + reg["type/u-tagged"] = tagged + stubbed, recorded := stubMerger(reg) + + got := stubbed.fold(declsOf("type/u-min", "type/u-max")) + + intersected, ok := reg[got.Type.Target].(*ir.Union) + require.True(t, ok, "the intersection is a union") + assert.Equal(t, &ir.Constraints{MinLength: new(int64(2)), MaxLength: new(int64(8))}, intersected.Constraints) + assert.Empty(t, *recorded) + for _, other := range []ir.TypeID{"type/u-other", "type/u-tagged"} { + assert.NotEqual(t, relSame, judge(stubbed).relate(ref("type/u-min"), ref(other)), "%s is no copy", other) + } +} + +// TestTypeJudge_NullAloneIsJudgedByWhatTheOtherAdmits pins a declaration +// admitting null alone against another, in both orders: within one admitting +// null, disjoint from one refusing it, and unrelated where the reader cannot +// tell. +func TestTypeJudge_NullAloneIsJudgedByWhatTheOtherAdmits(t *testing.T) { + t.Parallel() + reg := narrowingRegistry() + reg["type/null"] = &ir.Enum{ID: "type/null", ValueType: ir.PrimitiveAny, Closed: true} + reg["type/opaque"] = &ir.Scalar{ID: "type/opaque"} + stubbed, _ := stubMerger(reg) + nullOnly := ir.TypeRef{Target: "type/null", Nullable: true} + nullableText := ir.TypeRef{Target: primitiveRef(ir.PrimitiveString).Target, Nullable: true} + for _, tc := range []struct { + name string + other ir.TypeRef + want relation + }{ + {"a string admitting null", nullableText, firstTypeIsNarrower}, + {"a string refusing it", primitiveRef(ir.PrimitiveString), relDisjoint}, + {"a type the reader cannot read", ref("type/opaque"), relUnrelated}, + } { + assert.Equal(t, tc.want, judge(stubbed).relate(nullOnly, tc.other), tc.name) + assert.Equal(t, tc.want.flipped(), judge(stubbed).relate(tc.other, nullOnly), "%s, swapped", tc.name) + } +} + +// TestFold_ValueSetsSharingNullAloneIntersectAtNull pins two enums sharing no +// member, both admitting null: they intersect in a closed enum of no member behind a +// nullable reference, keeping the set each declaration the model holds alone +// gives verbatim, with one info each, and one another model brings not at all; +// a source that will not render is reported. Two kinds sharing no value but +// null stay disjoint. +func TestFold_ValueSetsSharingNullAloneIntersectAtNull(t *testing.T) { + t.Parallel() + enum := func(id ir.TypeID, count int, values ...string) *ir.Enum { + node := &ir.Enum{ID: id, ValueType: ir.PrimitiveString, Closed: true} + for _, v := range values { + node.Members = append(node.Members, ir.EnumMember{ID: ir.EnumMemberID(string(id) + "/" + v), Value: stringValue(v)}) + } + return hoisted(count, node) + } + reg := narrowingRegistry() + reg["type/ab"], reg["type/cd"], reg["type/ef"] = enum("type/ab", 0, "a", "b"), enum("type/cd", 1, "c", "d"), enum("type/ef", 2, "e", "f") + stubbed, recorded := stubMerger(reg) + decls := declsOf("type/ab", "type/cd", "type/ef") + for i := range decls { + decls[i].property.Type.Nullable = true + } + decls[1].source = nil + decls[2].via = &composedEntry{target: "type/other", at: "/other"} + + got := stubbed.fold(decls) + + assert.Equal(t, composedAt(foldKey), got.Type.Target) + assert.True(t, got.Type.Nullable) + intersected, ok := reg[got.Type.Target].(*ir.Enum) + require.True(t, ok) + assert.Empty(t, intersected.Members) + assert.Contains(t, intersected.Unmodeled, "openapi:allOf/0/properties/data", "the set the model holds alone is kept") + assert.NotContains(t, intersected.Unmodeled, "openapi:allOf/2/properties/data", "a set another model brings stays there") + codes := map[string]int{} + for _, diagnostic := range *recorded { + codes[diagnostic.Code]++ + } + assert.Equal(t, map[string]int{diag.DegradedConstruct: 2, diag.UnpreservableConstruct: 1}, codes) + + text, integer := ir.TypeRef{Target: primitiveRef(ir.PrimitiveString).Target, Nullable: true}, ir.TypeRef{Target: primitiveRef(ir.PrimitiveInteger).Target, Nullable: true} + assert.Equal(t, relDisjoint, judge(stubbed).relate(text, integer), "two kinds sharing null alone stay disjoint") +} + +// TestFold_ACopyTheModelHoldsAloneGivesItsNotes pins copies differing in what +// says nothing of their values: one the model holds alone giving examples +// otherwise than the node the field takes is reported and kept, naming as kept +// the first copy agreeing with the node, and the field names the copy written +// first. A copy another model brings stays there, so it gives the node nothing. +func TestFold_ACopyTheModelHoldsAloneGivesItsNotes(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + example := func(v string) []ir.Example { return []ir.Example{{Value: new(stringValue(v))}} } + for name, nodes := range map[string][3]*ir.Scalar{ + "examples": {{ID: "type/s0", Base: &text, Examples: example("a")}, {ID: "type/s1", Base: &text, Examples: example("b")}, + {ID: "type/s2", Base: &text, Examples: example("a")}}, + } { + for _, order := range [][3]int{{0, 1, 2}, {2, 1, 0}} { + reg := narrowingRegistry() + targets := make([]ir.TypeID, 3) + for at, i := range order { + node := *nodes[i] + reg[node.ID], targets[at] = hoisted(at, &node), node.ID + } + stubbed, recorded := stubMerger(reg) + + got := stubbed.fold(declsOf(targets...)) + + assert.Equal(t, targets[0], got.Type.Target, name) + require.Len(t, *recorded, 1, name) + assert.Equal(t, declaredAt(1), (*recorded)[0].Provenance.Pointer, name) + assert.Equal(t, []ir.Related{{Role: ir.RelatedChosen, Provenance: ptrAt(declaredAt(0))}}, (*recorded)[0].Related, + "%s: the first written agreeing with the node is named kept", name) + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(1)), name) + } + } +} + +// TestFold_ACopyKeepingAUseBoundKeywordApartKeepsItUnderItsDeclaration pins +// copies the model holds alone keeping a use-bound keyword apart: the field +// takes a node minted at the fold's key keeping each declaration's under its +// own key, with one info at each, in either order, and keeps no declaration +// verbatim. +func TestFold_ACopyKeepingAUseBoundKeywordApartKeepsItUnderItsDeclaration(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + for _, values := range [][3]string{{"true", "false", "false"}, {"false", "false", "true"}} { + reg := narrowingRegistry() + targets := make([]ir.TypeID, 3) + want := ir.Unmodeled{} + for n, value := range values { + targets[n] = ir.TypeID("type/s" + strconv.Itoa(n)) + reg[targets[n]] = hoisted(n, &ir.Scalar{ID: targets[n], Base: &text, + Unmodeled: ir.Unmodeled{"openapi:readOnly": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue(value)}}}) + want["openapi:allOf/"+strconv.Itoa(n)+"/properties/data"] = ir.UnmodeledEntry{Reason: ir.ReasonDegradedLowering, + Value: ir.RawValue(`{"readOnly":` + value + `}`), Provenance: ptrAt(declaredAt(n))} + } + stubbed, recorded := stubMerger(reg) + + got := stubbed.fold(declsOf(targets...)) + + assert.Equal(t, composedAt(foldKey), got.Type.Target, "%v", values) + node, ok := reg[got.Type.Target].(*ir.Scalar) + require.True(t, ok, "%v", values) + assert.Equal(t, want, node.Unmodeled, "%v", values) + assert.Len(t, *recorded, 3, "%v: one info at each declaration", values) + assert.Empty(t, got.Unmodeled, "%v", values) + } +} + +// TestFold_AValueAnotherDeclarationsKeptEntryRefusesIsNotTaken pins a bound +// kept verbatim on a declaration: a default another declaration writes that +// it refuses is not taken, and one it admits is. +func TestFold_AValueAnotherDeclarationsKeptEntryRefusesIsNotTaken(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + value ir.Value + taken bool + }{{stringValue("abc"), true}, {stringValue("abcd"), false}} { + stubbed, _ := stubMerger(narrowingRegistry()) + decls := declsOf(primitiveRef(ir.PrimitiveString).Target, primitiveRef(ir.PrimitiveString).Target) + decls[0].property.Unmodeled = ir.Unmodeled{"openapi:maxLength": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue("3")}} + decls[1].property.Default = &tc.value + + got := stubbed.fold(decls) + + assert.Equal(t, tc.taken, got.Default != nil, "%v", tc.value) + } +} + +// TestTypeJudge_ModelsComposingOneSetOfPartsAreCopies pins a model's Mixins +// read as a set: two models listing one set in different orders are copies, +// and two listing different sets, or sets of different sizes, are not. +func TestTypeJudge_ModelsComposingOneSetOfPartsAreCopies(t *testing.T) { + t.Parallel() + model := func(id ir.TypeID, count int, mixins ...ir.TypeID) *ir.Model { + node := &ir.Model{ID: id} + for _, mixin := range mixins { + node.Mixins = append(node.Mixins, ref(mixin)) + } + return hoisted(count, node) + } + reg := judgeRegistry() + part := func(id ir.TypeID, member string) *ir.Model { + return &ir.Model{ID: id, Properties: []ir.Property{{WireName: member, Type: primitiveRef(ir.PrimitiveString)}}} + } + reg["type/P"], reg["type/Q"], reg["type/R"] = part("type/P", "p"), part("type/Q", "q"), part("type/R", "r") + reg["type/PQ"], reg["type/QP"] = model("type/PQ", 0, "type/P", "type/Q"), model("type/QP", 1, "type/Q", "type/P") + reg["type/PR"], reg["type/P1"] = model("type/PR", 1, "type/P", "type/R"), model("type/P1", 1, "type/P") + stubbed, _ := stubMerger(reg) + assert.Equal(t, relSame, judge(stubbed).relate(ref("type/PQ"), ref("type/QP"))) + assert.NotEqual(t, relSame, judge(stubbed).relate(ref("type/PQ"), ref("type/PR"))) + assert.NotEqual(t, relSame, judge(stubbed).relate(ref("type/PQ"), ref("type/P1"))) +} + +// TestTypeJudge_RelatesCopiesAndTheirKin pins pairs a judgment reaches past +// the copy rule's first reading: two hoisted lists whose elements are copies at +// two nodes, and two hoisted unions alike, are one type; two scalars alike but +// for a deprecation are unrelated; two object literals of one value, one +// keeping what validates it, overlap; and a literal of a held format lies +// within a scalar of it whose pattern it matches, and is undecided against one +// whose pattern the reader cannot read. +func TestTypeJudge_RelatesCopiesAndTheirKin(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + reg := judgeRegistry() + reg["type/e0"] = hoisted(0, &ir.Scalar{ID: "type/e0", Base: &text, Constraints: &ir.Constraints{MaxLength: new(int64(3))}}) + reg["type/e1"] = hoisted(1, &ir.Scalar{ID: "type/e1", Base: &text, Constraints: &ir.Constraints{MaxLength: new(int64(3))}}) + reg["type/l0"] = hoisted(0, &ir.List{ID: "type/l0", ElementType: ref("type/e0")}) + reg["type/l1"] = hoisted(1, &ir.List{ID: "type/l1", ElementType: ref("type/e1")}) + reg["type/u0"] = hoisted(0, &ir.Union{ID: "type/u0", Closed: true, Variants: []ir.Variant{{Type: text}}}) + reg["type/u1"] = hoisted(1, &ir.Union{ID: "type/u1", Closed: true, Variants: []ir.Variant{{Type: text}}}) + reg["type/s-plain"] = &ir.Scalar{ID: "type/s-plain", Base: &text} + reg["type/s-deprecated"] = &ir.Scalar{ID: "type/s-deprecated", Base: &text, Deprecation: &ir.Deprecation{}} + object := ir.Value{Kind: ir.ValueObject, Object: []ir.Field{{Name: "a", Value: stringValue("x")}}} + reg["type/o0"] = &ir.Literal{ID: "type/o0", Value: object} + reg["type/o1"] = &ir.Literal{ID: "type/o1", Value: object, + Unmodeled: ir.Unmodeled{"openapi:not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{}`)}}} + reg["type/lit-noon"] = &ir.Literal{ID: "type/lit-noon", Value: stringValue("12:00:00Z")} + timePatterned := *reg["type/scalar-time"].(*ir.Scalar) + timePatterned.ID, timePatterned.Constraints = "type/scalar-time-patterned", &ir.Constraints{Pattern: "^1"} + reg["type/scalar-time-patterned"] = &timePatterned + timeUnread := timePatterned + timeUnread.ID, timeUnread.Constraints = "type/scalar-time-unread", &ir.Constraints{Pattern: "^(?=1)"} + reg["type/scalar-time-unread"] = &timeUnread + stubbed, _ := stubMerger(reg) + sites := declarationSites{walk: stubbed.walk, written: [2][]ir.Provenance{{ptrAt(declaredAt(0))}, {ptrAt(declaredAt(1))}}} + copies := typeJudge{resolve: stubbed.resolve, sites: sites} + assert.Equal(t, relSame, copies.relate(ref("type/l0"), ref("type/l1")), "lists of element copies") + assert.Equal(t, relSame, copies.relate(ref("type/u0"), ref("type/u1")), "unions alike") + assert.Equal(t, relUnrelated, judge(stubbed).scalars(reg["type/s-plain"].(*ir.Scalar), reg["type/s-deprecated"].(*ir.Scalar))) + assert.Equal(t, relOverlap, judge(stubbed).relate(ref("type/o0"), ref("type/o1")), "object literals") + assert.Equal(t, firstTypeIsNarrower, judge(stubbed).relate(ref("type/lit-noon"), ref("type/scalar-time-patterned")), "a pattern matched") + assert.Equal(t, relUndecided, judge(stubbed).relate(ref("type/lit-noon"), ref("type/scalar-time-unread")), "a pattern unread") +} + +// TestFold_ACopyAnotherModelBringsGivesNothing pins a copy another model's +// declaration brings, differing in its notes: it stays on that model, so the +// field names the least copy and nothing is reported or kept. +func TestFold_ACopyAnotherModelBringsGivesNothing(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + reg := narrowingRegistry() + reg["type/s0"] = hoisted(0, &ir.Scalar{ID: "type/s0", Base: &text}) + reg["type/s1"] = hoisted(1, &ir.Scalar{ID: "type/s1", Base: &text, Docs: ir.Docs{Description: "d"}}) + stubbed, recorded := stubMerger(reg) + decls := declsOf("type/s0", "type/s1") + decls[1].via, decls[1].typeAt = &composedEntry{target: "type/other", at: "/other"}, []ir.Provenance{ptrAt(declaredAt(1))} + + got := stubbed.fold(decls) + + assert.Equal(t, ir.TypeID("type/s0"), got.Type.Target) + assert.Empty(t, *recorded) +} diff --git a/compilers/openapi/internal/merge/keptlengths.go b/compilers/openapi/internal/merge/keptlengths.go new file mode 100644 index 000000000..8cab54745 --- /dev/null +++ b/compilers/openapi/internal/merge/keptlengths.go @@ -0,0 +1,120 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/v2" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// keptLength reads the count the entry under key keeps verbatim where key +// names minLength or maxLength, as lengthAdmission reads one. It is false for +// any other key and for a count that is no whole number at least zero. +func keptLength(key string, entry ir.UnmodeledEntry) (keyword string, count int64, ok bool) { + keyword = keptEntryKeyword(key) + if key != annotation.EntryKey("", keyword) || keyword != "minLength" && keyword != "maxLength" { + return "", 0, false + } + if err := json.Unmarshal(entry.Value, &count); err != nil || count < 0 { + return "", 0, false + } + return keyword, count, true +} + +// narrower reports whether count is a narrower length of keyword than other: +// a lesser maximum, a greater minimum. +func narrower(keyword string, count, other int64) bool { + if keyword == "maxLength" { + return count < other + } + return count > other +} + +// splitKeptLengths returns the lengths unmodeled keeps verbatim (keptLength) +// and the rest of it, each nil where it holds none. It writes to no map it was +// given. +func splitKeptLengths(unmodeled ir.Unmodeled) (lengths, rest ir.Unmodeled) { + for key, entry := range unmodeled { + if _, _, ok := keptLength(key, entry); ok { + lengths = withEntry(lengths, key, entry) + continue + } + rest = withEntry(rest, key, entry) + } + return lengths, rest +} + +// withEntry returns unmodeled holding entry under key, a new map where it is +// nil. +func withEntry(unmodeled ir.Unmodeled, key string, entry ir.UnmodeledEntry) ir.Unmodeled { + if unmodeled == nil { + unmodeled = ir.Unmodeled{} + } + unmodeled[key] = entry + return unmodeled +} + +// keptLengthsHolding is the holding of the lengths two nodes keep verbatim, +// each a bound on their values: a node keeping one the other does not says +// more, and two keeping one keyword at counts apart each say what the other +// lacks. +func keptLengthsHolding(a, b ir.Unmodeled) subsumption { + out := bothSubsume + for key, entry := range a { + other, ok := b[key] + if !ok { + out.b = false + continue + } + _, count, _ := keptLength(key, entry) + _, otherCount, _ := keptLength(key, other) + if count != otherCount { + out = subsumption{} + } + } + for key := range b { + if _, ok := a[key]; !ok { + out.a = false + } + } + return out +} + +// narrowestLength returns, of the nodes holders indexes each keeping a length +// under key, the first written entry giving the narrowest and which of holders +// give it, and false where key names no length every holder keeps as a count. +func narrowestLength(key string, holders []int, entriesOf func(int) ir.Unmodeled) (ir.UnmodeledEntry, func(int) bool, bool) { + keyword, best, ok := keptLength(key, entriesOf(holders[0])[key]) + if !ok { + return ir.UnmodeledEntry{}, nil, false + } + counts := make(map[int]int64, len(holders)) + for _, k := range holders { + _, count, read := keptLength(key, entriesOf(k)[key]) + if !read { + return ir.UnmodeledEntry{}, nil, false + } + counts[k] = count + if narrower(keyword, count, best) { + best = count + } + } + var kept ir.UnmodeledEntry + for _, k := range holders { + if entry := entriesOf(k)[key]; counts[k] == best && (kept.Value == nil || writtenBefore(entry.Provenance, kept.Provenance)) { + kept = entry + } + } + return kept, func(k int) bool { return counts[k] == best }, true +} + +// bindsText reports whether typeDef is a Scalar whose values are text, so a +// length it keeps verbatim bounds them. +func bindsText(registry registryReader, typeDef ir.TypeDef) bool { + scalar, ok := typeDef.(*ir.Scalar) + return ok && registry.scalarKinds(scalar)&typeformat.InstanceString != 0 +} diff --git a/compilers/openapi/internal/merge/keptref_internal_test.go b/compilers/openapi/internal/merge/keptref_internal_test.go new file mode 100644 index 000000000..dc0dc56cd --- /dev/null +++ b/compilers/openapi/internal/merge/keptref_internal_test.go @@ -0,0 +1,36 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestKeptReferences_AStructureKeepingAGhostRefSaysNothingMore holds a +// structure keeping verbatim a $ref naming no schema, under openapi:$ref or +// openapi:$ref/, to the reading of a structure without it: it adds nothing +// beyond its base, the references alone are what a field narrowing it carries, +// and a key keeping anything else still says more. +func TestKeptReferences_AStructureKeepingAGhostRefSaysNothingMore(t *testing.T) { + t.Parallel() + ref := ir.UnmodeledEntry{Value: ir.RawValue(`"#/components/schemas/Missing"`), Reason: ir.ReasonDegradedLowering} + ghost := &ir.Model{ID: "type/ghost", Unmodeled: ir.Unmodeled{"openapi:$ref": ref, "openapi:$ref/1": ref}} + more := &ir.Model{ID: "type/more", Unmodeled: ir.Unmodeled{"openapi:$ref": ref, "openapi:x-k": ref}} + + assert.True(t, structureAddsNothingBeyondBase(ghost, false), "a kept $ref says nothing") + assert.False(t, structureAddsNothingBeyondBase(more, false), "an extension beside it says more") + assert.Equal(t, ir.Unmodeled{"openapi:x-k": ref}, withoutKeptReferences(more.Unmodeled)) + assert.Equal(t, ir.Unmodeled{"openapi:x-k": ref}, withoutKeptReferences(ir.Unmodeled{"openapi:x-k": ref}), "nothing to leave out") + + reg := registryReader{resolve: stubResolve(map[ir.TypeID]ir.TypeDef{ghost.ID: ghost, "type/scalar": &ir.Scalar{}})} + given := ir.Unmodeled{"openapi:x-own": ref} + assert.Equal(t, ir.Unmodeled{"openapi:$ref": ref, "openapi:$ref/1": ref, "openapi:x-own": ref}, + withNarrowedStructureReferences(reg, ghost.ID, given), "the field carries the structure's references") + assert.Equal(t, given, withNarrowedStructureReferences(reg, "type/unknown", given), "an unresolved target carries nothing") + assert.Equal(t, given, withNarrowedStructureReferences(reg, "type/scalar", given), "no structure carries nothing") +} diff --git a/compilers/openapi/internal/merge/meet.go b/compilers/openapi/internal/merge/meet.go deleted file mode 100644 index 992d19b13..000000000 --- a/compilers/openapi/internal/merge/meet.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "cmp" - "encoding/json/jsontext" - "fmt" - "reflect" - "slices" - - "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/ir" -) - -// builder builds the node the members at one position meet in -// (docs/compilers/openapi.md#allof-redeclared-property): the winner's node -// holding what each member meeting it adds, its members built the same way a -// level down. A dry run mints and reports nothing, so a fold learns whether -// every position builds before it registers a node; failed says one did not. -type builder struct { - f *folding - dry bool - failed bool -} - -// mint registers node at pointer, its parts brought where brought says and -// placed as the field is (folding.assembled; FieldDeclarationContext.Mint), or -// in a dry run names nothing. -func (b *builder) mint(pointer jsontext.Pointer, node ir.TypeDef, brought []jsontext.Pointer) ir.TypeID { - if b.dry { - return "" - } - return b.f.g.Walk.Mint(pointer, node, brought, b.f.assembled) -} - -// meetNode returns the node base and partners, members that meet it, stand on: -// base's own where no partner adds anything, and otherwise one minted at -// pointer, built from the node each stands for (registry.view). A literal among -// them is the node, since it is within each; a literal meets only one node, so -// it is built beside one partner alone. -func (b *builder) meetNode(base member, partners []member, pointer jsontext.Pointer, depth int) ir.TypeID { - if len(partners) == 0 { - return base.ref.Target - } - all := append([]member{base}, partners...) - nodes := make([]ir.TypeDef, len(all)) - reg := registry{b.f.g.resolve} - for k, member := range all { - td, ok := reg.resolve(member.ref.Target) - if !ok { - b.failed = true - return base.ref.Target - } - nodes[k] = td - } - stop := reg.sharedLink(nodes...) - for k, td := range nodes { - nodes[k] = reg.view(td, stop) - } - if k := slices.IndexFunc(nodes, isLiteral); k > 0 { - all[0], all[k], nodes[0], nodes[k] = all[k], all[0], nodes[k], nodes[0] - } - built, ok := b.build(all, nodes, pointer, depth) - if !ok { - b.failed = true - return base.ref.Target - } - built = b.adoptInto(built, all, nodes) - if reflect.DeepEqual(built, nodes[0]) { - return all[0].ref.Target - } - return b.mint(pointer, built, nil) -} - -// build returns nodes[0] holding what each of nodes[1:] adds: its members built -// from all the nodes' (settle), its bounds met with theirs (meetConstraints), -// and what else they say adopted (adopt), or false where the nodes are of -// kinds no node holds together. -func (b *builder) build(all []member, nodes []ir.TypeDef, pointer jsontext.Pointer, depth int) (ir.TypeDef, bool) { - switch n := nodes[0].(type) { - case *ir.Literal: - out := *n - return &out, len(nodes) == 2 - case *ir.Scalar: - out := *n - return &out, sameKind[*ir.Scalar](nodes) - case *ir.Enum: - out := *n - out.Members = sharedBy(n.Members, nodes[1:]) - valueType, narrowest := narrowestValueType(nodes) - out.ValueType = valueType - return &out, narrowest && len(out.Members) > 0 - case *ir.List: - out := *n - out.ElementType = b.settle(membersOf(all, nodes, func(list *ir.List) ir.TypeRef { return list.ElementType }), pointer+"/items", depth) - return &out, sameKind[*ir.List](nodes) - case *ir.MapT: - out := *n - out.Value = b.settle(membersOf(all, nodes, func(mapT *ir.MapT) ir.TypeRef { return mapT.Value }), pointer+"/additionalProperties", depth) - return &out, sameKind[*ir.MapT](nodes) - case *ir.Tuple: - return b.tuple(n, all, nodes, pointer, depth) - default: - return nil, false - } -} - -// tuple is build for a tuple: each position, and what may follow the last, -// built from all the tuples' (settle), which meet only at one length and one -// presence of what follows (typeJudge.tuples). -func (b *builder) tuple(tuple *ir.Tuple, all []member, nodes []ir.TypeDef, pointer jsontext.Pointer, depth int) (ir.TypeDef, bool) { - if !shapedAs(tuple, nodes) { - return nil, false - } - out := *tuple - out.ElementTypes = make([]ir.TypeRef, len(tuple.ElementTypes)) - for i := range tuple.ElementTypes { - at := pointer + jsontext.Pointer(fmt.Sprintf("/prefixItems/%d", i)) - out.ElementTypes[i] = b.settle(membersOf(all, nodes, func(irTuple *ir.Tuple) ir.TypeRef { return irTuple.ElementTypes[i] }), at, depth) - } - if tuple.Rest != nil { - rest := b.settle(membersOf(all, nodes, func(irTuple *ir.Tuple) ir.TypeRef { return *irTuple.Rest }), pointer+"/items", depth) - out.Rest = &rest - } - return &out, true -} - -// shapedAs reports whether every node is a tuple of tuple's length, and admits -// what follows its last position where tuple does. -func shapedAs(tuple *ir.Tuple, nodes []ir.TypeDef) bool { - for _, td := range nodes { - irTuple, ok := td.(*ir.Tuple) - if !ok || len(irTuple.ElementTypes) != len(tuple.ElementTypes) || (irTuple.Rest == nil) != (tuple.Rest == nil) { - return false - } - } - return true -} - -// sameKind reports whether every node is a T. -func sameKind[T ir.TypeDef](nodes []ir.TypeDef) bool { - return !slices.ContainsFunc(nodes, func(td ir.TypeDef) bool { _, ok := td.(T); return !ok }) -} - -// membersOf returns what each node, a T, holds at one position (of), each the -// member of the declaration whose node it is. -func membersOf[T ir.TypeDef](all []member, nodes []ir.TypeDef, of func(T) ir.TypeRef) []member { - out := make([]member, 0, len(nodes)) - for k, td := range nodes { - if n, ok := td.(T); ok { - out = append(out, member{ref: of(n), decl: all[k].decl}) - } - } - return out -} - -// sharedBy returns the members of ms whose value every enum of others holds, -// in ms's order: the values of all the enums at once. A node of others that is -// no enum holds none of them. -func sharedBy(ms []ir.EnumMember, others []ir.TypeDef) []ir.EnumMember { - indexes := make([]memberIndex, len(others)) - for k, td := range others { - enum, ok := td.(*ir.Enum) - if !ok { - return nil - } - indexes[k] = indexMembers(enum.Members) - } - out := make([]ir.EnumMember, 0, len(ms)) - for _, enumMember := range ms { - if heldByAll(indexes, enumMember.Value) { - out = append(out, enumMember) - } - } - if len(out) == len(ms) { - return ms - } - return out -} - -// heldByAll reports whether each enum indexes indexed holds value. -func heldByAll(indexes []memberIndex, value ir.Value) bool { - for _, memberIndex := range indexes { - if _, held := memberIndex.find(value); !held { - return false - } - } - return true -} - -// settle returns the type of one position of the nodes built at depth, its -// members ms: the model they compose, or the node they meet in built a level -// down, at pointer, admitting null as position.null reads them. A member -// outside the winner's cone fails the build, since no node holds it beside the -// rest. ms are judged in declaration order, as a field's own types are, so a -// tie goes to the later and what they compose is listed as they are written. -func (b *builder) settle(ms []member, pointer jsontext.Pointer, depth int) ir.TypeRef { - ms = slices.SortedStableFunc(slices.Values(ms), func(memberValue, otherMember member) int { return cmp.Compare(memberValue.decl, otherMember.decl) }) - position := b.f.g.judgePosition(b.f.decls, ms, depth+1) - all := func(int) bool { return true } - var target ir.TypeID - if len(position.conjuncts) > 0 { - target = b.compose(position.conjuncts, pointer) - } else { - for k := range ms { - if !position.holds(position.winner, k) { - b.failed = true - return ms[position.winner].ref - } - } - base, partners := position.meeting(all) - target = b.meetNode(base, partners, pointer, depth+1) - } - ref := position.null(registry{b.f.g.resolve}, all, depth+1) - ref.Target = target - return ref -} - -// adoptInto returns built, the node nodes[0] stands for with its members built, -// holding the bounds every node says together and what else each of nodes[1:] -// adds: all a reference to each would read. A keyword or a field two give -// differently is the first's, and the later one is reported where its -// declaration is written and kept verbatim, as foldDocs keeps a property's. A -// literal takes no bounds, since every node meeting it admits its value. -func (b *builder) adoptInto(built ir.TypeDef, all []member, nodes []ir.TypeDef) ir.TypeDef { - sets := make([]*ir.Constraints, len(b.f.decls)) - for k, td := range nodes { - sets[all[k].decl] = boundsOf(td) - } - if !isLiteral(built) { - if met := meetConstraints(sets, b.disagree); !sameBounds(met, boundsOf(nodes[0])) { - built = withBounds(built, met) - } - } - others := make([]ir.TypeCommon, len(nodes)-1) - for k, td := range nodes[1:] { - others[k] = *td.Common() - } - typeCommon := built.Common() - *typeCommon = adopt(*typeCommon, others, b.f.g.Walk, func(k int, field string) { b.differ(all[k+1].decl, field) }) - if list, ok := built.(*ir.List); ok && list.Encoding == nil { - b.adoptEncoding(list, all, nodes) - } - return built -} - -// adoptEncoding sets on list, a list giving no encoding, the first one -// nodes[1:] give, reporting each later list giving another as adopt reports a -// field. -func (b *builder) adoptEncoding(list *ir.List, all []member, nodes []ir.TypeDef) { - for k, td := range nodes[1:] { - other, ok := td.(*ir.List) - switch { - case !ok || other.Encoding == nil: - case list.Encoding == nil: - list.Encoding = other.Encoding - case !reflect.DeepEqual(list.Encoding, other.Encoding): - b.differ(all[k+1].decl, "encoding") - } - } -} - -// disagree is folding.disagree, heard only where the build is not a dry run. -func (b *builder) disagree(i, kept int, detail string) { - if !b.dry { - b.f.disagree(i, kept, detail) - } -} - -// differ reports at declaration decl that it gives what field names of a type -// the field holds otherwise than one before it, keeping it verbatim. -func (b *builder) differ(decl int, field string) { - if b.dry { - return - } - b.f.lost[decl] = true - b.f.note(decl, ir.SeverityInfo, diag.DegradedConstruct, - "declarations of field %q give the %s of a type it holds differently; kept the one a later "+ - "declaration gives over the one at %s, which %s", b.f.merged.WireName, field, b.f.at(decl), b.f.decls[decl].keptAs()) -} diff --git a/compilers/openapi/internal/merge/members.go b/compilers/openapi/internal/merge/members.go index 2eb987ca1..003f0baac 100644 --- a/compilers/openapi/internal/merge/members.go +++ b/compilers/openapi/internal/merge/members.go @@ -9,17 +9,15 @@ import ( "maps" "slices" - "github.com/dexpace/morphic/compilers/openapi/internal/budget" - "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/ir" ) // RedeclaredWireNameTable is what a model's composition says of the wire names // more than one model declares: for each, the declaration its flattening takes -// (ir.FlattenedProperties), which a model settled before holds folded from -// every other its composition gives the name. A name one model alone declares -// never decides a member twice, so a settlement reads none. +// (ir.FlattenedProperties), which a model settled before holds taken into one +// from every other its composition gives the name. A name one model alone +// declares never decides a member twice, so a settlement reads none. type RedeclaredWireNameTable map[string]Declared // Declared is the declaration a flattening takes for one name, and where the @@ -30,6 +28,10 @@ type RedeclaredWireNameTable map[string]Declared type Declared struct { ir.PropertyDecl TypeAt []ir.Provenance + // ValueAt is, for a settled member, where the value of each field its + // fold took from one declaration is written, by the field's name in a + // report (singleSource). + ValueAt map[string]ir.Provenance } // DeclaredAt is propertyDecl as a model's flattening takes it unsettled: its @@ -40,33 +42,31 @@ func DeclaredAt(propertyDecl ir.PropertyDecl) Declared { // Settle folds each member of the model more than one declaration decides, // its own and those its entries bring -// (docs/compilers/openapi.md#allof-redeclared-property), which the flattening -// would take one of by where it reads it, judging none. Each fold reads them in -// the order the walk met them, an entry's where it met the entry, so a $ref -// and the schema it names written inline fold alike, but for a tie the entry -// settled. tables holds the RedeclaredWireNameTable of each type the model -// composes (ComposedOf), settled first, and shared the names more than one +// (docs/compilers/openapi.md#allof-redeclared-property), in the order the walk +// met them, so a $ref and the schema it names written inline fold alike, but +// for a tie the entry settled. tables holds the RedeclaredWireNameTable of each +// type the model composes, settled first, and shared the names more than one // model declares. It returns the model's RedeclaredWireNameTable. func (idx *ModelPropertyDeclarations) Settle(merger Merger, tables map[ir.TypeID]RedeclaredWireNameTable, shared map[string]bool) ([]ir.Diagnostic, RedeclaredWireNameTable) { - brought, inherited := idx.brought(merger, tables) + entryDeclarations, inherited := idx.entryDeclarations(merger, tables) diags := make([]ir.Diagnostic, 0, len(idx.byWire)) - for _, fieldValue := range slices.SortedFunc(maps.Values(idx.byWire), func(a, b *field) int { return cmp.Compare(a.pos, b.pos) }) { - decls := slices.Clone(fieldValue.decls) - decls[0].property = idx.m.Properties[fieldValue.pos] + for _, field := range slices.SortedFunc(maps.Values(idx.byWire), func(a, b *field) int { return cmp.Compare(a.pos, b.pos) }) { + decls := slices.Clone(field.decls) + decls[0].property = idx.m.Properties[field.pos] wire := decls[0].property.WireName - decls = inOrder(decls, brought[wire]) - delete(brought, wire) - diags = append(diags, idx.settle(merger, fieldValue.pos, decls)...) + decls = inOrder(decls, entryDeclarations[wire]) + delete(entryDeclarations, wire) + diags = append(diags, idx.settle(merger, field.pos, decls)...) } - for _, wire := range slices.Sorted(maps.Keys(brought)) { - diags = append(diags, idx.settle(merger, -1, brought[wire])...) + for _, wire := range slices.Sorted(maps.Keys(entryDeclarations)) { + diags = append(diags, idx.settle(merger, -1, entryDeclarations[wire])...) } return diags, idx.members(shared, inherited) } // members returns the model's RedeclaredWireNameTable once settled: each name // its parts leave one declaration of, and each shared one it declares itself, -// which stands over theirs, its type written where its fold says +// which takes precedence over theirs, its type written where its fold says // (Merger.typeSites) or, where one declaration alone decides it, there. func (idx *ModelPropertyDeclarations) members(shared map[string]bool, inherited RedeclaredWireNameTable) RedeclaredWireNameTable { out := make(RedeclaredWireNameTable, len(inherited)) @@ -78,7 +78,7 @@ func (idx *ModelPropertyDeclarations) members(shared map[string]bool, inherited } declared := DeclaredAt(ir.PropertyDecl{Owner: idx.m.ID, Property: property}) if at, settled := idx.typeAt[property.WireName]; settled { - declared.TypeAt = at + declared.TypeAt, declared.ValueAt = at, idx.valueWrittenAt[property.WireName] } out[property.WireName] = declared } @@ -87,41 +87,44 @@ func (idx *ModelPropertyDeclarations) members(shared map[string]bool, inherited // settle folds decls, one member's declarations, where at least two are, into // the model's property at pos, or appends one where pos is -1. A member only -// the model declares keeps its identity (Merger.fold), and so does one it -// declares beside an entry's where no other model holds the own declaration -// the walk met first (heldAlone), so two at different depths follow their -// order (GitHub #1931). Any other takes an identity in the composed namespace -// (composedMember), placed by where its declarations are written -// (assembledFrom). Where an entry brings a declaration, each report names the -// member (naming). +// the model declares keeps its identity, as does one whose own declaration no +// other model holds (heldAlone), so no order of them moves it (GitHub #1931); +// any other takes an identity in the composed namespace, placed by where its +// declarations are written. func (idx *ModelPropertyDeclarations) settle(merger Merger, pos int, decls []declaration) []ir.Diagnostic { if len(decls) < 2 { return nil } - if !slices.ContainsFunc(decls, isBrought) { - merged, diags := merger.fold(decls) + if !slices.ContainsFunc(decls, isFromEntry) { + merged, valueWrittenAt, diags := merger.fold(decls) merger.discardDropped(decls, merged) idx.place(pos, merged) - idx.typeAt[merged.WireName] = merger.typeSites(merged, decls) - return deciding(diags, merged.ID) + idx.typeAt[merged.WireName], idx.valueWrittenAt[merged.WireName] = merger.typeSites(merged, decls), valueWrittenAt + return deciding(diags, merged.ID, idx.m.Provenance) } - own := slices.DeleteFunc(slices.Clone(decls), isBrought) - field := composedMember(merger.IDs, idx.m, decls[0].property.WireName) - kept := len(own) > 0 && idx.heldAlone(merger, own[0]) - if kept { - _, field = fieldSpan(own[:min(len(own), maxFoldDeclarations)]) + own := slices.DeleteFunc(slices.Clone(decls), isFromEntry) + var fieldPointer jsontext.Pointer + var chosenIdentity ir.Property + if len(own) > 0 { + judged, _ := judgedFirst(&merger, own) + chosenIdentity = identityDeclaration(judged).property + _, fieldPointer = fieldSpan(judged) + } + identityKept := len(own) > 0 && idx.heldAlone(merger, chosenIdentity) + if !identityKept { + fieldPointer = composedMember(merger.IDs, idx.m, decls[0].property.WireName) } var assembled []jsontext.Pointer - if !kept { + if !identityKept { assembled = assembledFrom(decls) } - merged, diags := merger.foldAt(decls, field, assembled) + merged, valueWrittenAt, diags := merger.foldAt(decls, fieldPointer, assembled) merger.discardDropped(decls, merged) inferred := merged.Provenance.Inferred - if kept { - merged.ID, merged.Provenance = own[0].property.ID, own[0].property.Provenance + if identityKept { + merged.ID, merged.Provenance = chosenIdentity.ID, chosenIdentity.Provenance } else { - merged.ID, merged.Provenance = merger.IDs.ComposedProperty(field), merger.Doc.At(field, assembled...) + merged.ID, merged.Provenance = merger.IDs.ComposedProperty(fieldPointer), merger.Doc.At(fieldPointer, assembled...) } merged.Provenance.Inferred = inferred if i := slices.Index(idx.m.Requires, merged.WireName); i >= 0 { @@ -129,8 +132,8 @@ func (idx *ModelPropertyDeclarations) settle(merger Merger, pos int, decls []dec merged.Required = true } idx.place(pos, merged) - idx.typeAt[merged.WireName] = merger.typeSites(merged, decls) - return deciding(naming(diags, merged.ID), merged.ID) + idx.typeAt[merged.WireName], idx.valueWrittenAt[merged.WireName] = merger.typeSites(merged, decls), valueWrittenAt + return deciding(diags, merged.ID, idx.m.Provenance) } // discardDropped records any TypeID a declaration in decls carried that merged @@ -140,9 +143,9 @@ func (g *Merger) discardDropped(decls []declaration, merged ir.Property) { if g.Discarded == nil { return } - for _, d := range decls { - if d.property.Type.Target != merged.Type.Target { - g.Discarded[d.property.Type.Target] = true + for _, declared := range decls { + if declared.property.Type.Target != merged.Type.Target { + g.Discarded[declared.property.Type.Target] = true } } } @@ -165,34 +168,33 @@ func (g *Merger) typeSites(merged ir.Property, decls []declaration) []ir.Provena naming = append(naming, declaration.sites()) } } - td, registered := g.resolve(merged.Type.Target) + typeDef, registered := g.resolve(merged.Type.Target) switch { case len(naming) == 1: return naming[0] - case !registered || !td.Common().Anonymous: + case !registered || !typeDef.Common().Anonymous: return nil case len(naming) > 1: - at := slices.IndexFunc(naming, func(sites []ir.Provenance) bool { return hoistedAt(td, sites) }) + at := slices.IndexFunc(naming, func(sites []ir.Provenance) bool { return hoistedAt(typeDef, sites) }) return naming[max(at, 0)] default: - return g.builtSites(td, decls) + return g.builtSites(typeDef, decls) } } -// builtSites returns where the nodes of td, which a fold of decls built, are -// written: where td stands, and, for each node it holds (heldTypes), the first +// builtSites returns where the nodes of typeDef, which a fold of decls built, +// are written: where typeDef sits, and, for each node it holds, the first // place a declaration says that holds it. A node none holds was reached by a -// $ref, and so was what it holds. A hierarchy building a node at every level -// so records what each node holds, not its depth. It reads each node once, -// maxTypeSites of them at most. -func (g *Merger) builtSites(td ir.TypeDef, decls []declaration) []ir.Provenance { +// $ref, and so was what it holds. It reads each node once, maxTypeSites of +// them at most. +func (g *Merger) builtSites(typeDef ir.TypeDef, decls []declaration) []ir.Provenance { places := make([][]ir.Provenance, len(decls)) for i, declaration := range decls { places[i] = declaration.sites() } - out := []ir.Provenance{td.Common().Provenance} + out := []ir.Provenance{typeDef.Common().Provenance} seen := map[ir.TypeID]bool{} - queue := heldTypes(td) + queue := heldTypes(typeDef) for len(queue) > 0 && len(seen) < maxTypeSites { id := queue[0] queue = queue[1:] @@ -227,11 +229,11 @@ func writtenAt(node ir.TypeDef, places [][]ir.Provenance) (ir.Provenance, bool) return ir.Provenance{}, false } -// heldTypes returns the types td holds values of: a list's element, a map's +// heldTypes returns the types typeDef holds values of: a list's element, a map's // value, a tuple's positions and what follows them, and what a model or an -// alias composes (ComposedOf). -func heldTypes(td ir.TypeDef) []ir.TypeID { - switch t := td.(type) { +// alias composes (ir.ComposedOf). +func heldTypes(typeDef ir.TypeDef) []ir.TypeID { + switch t := typeDef.(type) { case *ir.List: return []ir.TypeID{t.ElementType.Target} case *ir.MapT: @@ -246,7 +248,7 @@ func heldTypes(td ir.TypeDef) []ir.TypeID { } return held default: - return ComposedOf(td) + return ir.ComposedOf(typeDef) } } @@ -276,23 +278,23 @@ func settledAt(model *ir.Model, wire string, deeper bool) jsontext.Pointer { func assembledFrom(decls []declaration) []jsontext.Pointer { out := make([]jsontext.Pointer, len(decls)) for i, declaration := range decls { - out[i] = declaration.reportAt() + out[i] = declaration.assemblyPointer() } return out } -// isBrought reports whether declarationValue is a declaration an entry brings, +// isFromEntry reports whether declaration is one an entry brings, // which another model holds. -func isBrought(declarationValue declaration) bool { return declarationValue.via != nil } - -// heldAlone reports whether no model but this one holds declarationValue, its -// own declaration, so the member it decides may keep declarationValue's -// identity: declarationValue is written inside the model's schema, as the body -// a distributed variant shares with its siblings is not, and no schema between -// the two stands as a node of its own (Merger.carriedApart). -func (idx *ModelPropertyDeclarations) heldAlone(merger Merger, declarationValue declaration) bool { - model, at := idx.m.Provenance.Pointer, declarationValue.property.Provenance.Pointer - return model.Contains(at) && !merger.carriedApart(at, model) +func isFromEntry(declaration declaration) bool { return declaration.via != nil } + +// heldAlone reports whether no model but this one holds declared, its own +// declaration, so the member it decides may keep declared's identity: declared +// is written inside the model's schema, as the body a distributed variant +// shares with its siblings is not, and no schema between the two serves as a +// node of its own (Merger.carriedApart). +func (idx *ModelPropertyDeclarations) heldAlone(merger Merger, declared ir.Property) bool { + model, at := idx.m.Provenance.Pointer, declared.Provenance + return model.Contains(at.Pointer) && !merger.carriedApart(at, model) } // place writes property as the model's property at pos, or appends it where pos @@ -315,28 +317,14 @@ func (idx *ModelPropertyDeclarations) place(pos int, property ir.Property) { idx.m.Properties[pos] = property } -// naming returns diags, each naming id, the property the fold decided, as the -// node it locates (ir.Provenance.Node): a report about an entry's declaration -// sits where the model writes the entry, which is not where the property is. -func naming(diags []ir.Diagnostic, id ir.PropertyID) []ir.Diagnostic { - for i := range diags { - diags[i].Provenance.Node = string(id) - } - return diags -} - -// deciding returns diags, each conflict between two declarations listing id, -// the property the fold decided, among what it concerns (ir.RelatedDecided): -// every model composing the two draws the report, and the run says it once -// for all of them (ReportOnce), where one node named beside its place could -// not say which. -func deciding(diags []ir.Diagnostic, id ir.PropertyID) []ir.Diagnostic { +// deciding returns diags, each listing id, the property the fold decided, as +// ir.RelatedDecided at model, the place of the model declaring it: every model +// composing the declarations a report is about draws it alike, and the run +// says it once for all of them, naming each (ReportOnce). +func deciding(diags []ir.Diagnostic, id ir.PropertyID, model ir.Provenance) []ir.Diagnostic { for i := range diags { - if diags[i].Code != diag.ConflictingRedecl { - continue - } diags[i].Related = append(diags[i].Related, ir.Related{ - Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: string(id)}, + Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: model.Source, Pointer: model.Pointer, Node: string(id)}, }) } return diags @@ -346,17 +334,18 @@ func deciding(diags []ir.Diagnostic, id ir.PropertyID) []ir.Diagnostic { type candidate struct { decl Declared part int + // listed is where the candidate sits in the list its caller hands + // candidatesNotReadElsewhere, so the caller reads what it knows of each candidate left. + listed int } -// brought returns, by wire name, the declarations the model's parts bring, as -// tables holds them, each read where the walk met the entry naming its part -// (parts), and the one declaration each name its parts leave one of. A -// declaration two parts bring is read once, at the first, and one within -// another's composition is left out: the model composing it narrows it there -// already. A part on a cycle may hold the model's own declaration, which the -// model reads as its own, not brought. Names are read in order, as their walks -// spend the run's reads (ownership). -func (idx *ModelPropertyDeclarations) brought(merger Merger, tables map[ir.TypeID]RedeclaredWireNameTable) (map[string][]declaration, RedeclaredWireNameTable) { +// entryDeclarations returns, by wire name, the declarations the model's parts +// bring, each read where the walk met the entry naming its part, and the one +// declaration each name its parts leave one of. A declaration two parts bring +// is read once, and one within another's composition is left out, as the +// model composing it narrows it there already. A part on a cycle may hold the +// model's own declaration, which the model reads as its own. +func (idx *ModelPropertyDeclarations) entryDeclarations(merger Merger, tables map[ir.TypeID]RedeclaredWireNameTable) (map[string][]declaration, RedeclaredWireNameTable) { parts := idx.parts() byWire := map[string][]candidate{} for i, part := range parts { @@ -366,12 +355,11 @@ func (idx *ModelPropertyDeclarations) brought(merger Merger, tables map[ir.TypeI } } } - owners := newOwnership(registry{merger.resolve}, merger.Reads) out, inherited := map[string][]declaration{}, RedeclaredWireNameTable{} for _, wire := range slices.Sorted(maps.Keys(byWire)) { - left := owners.left(byWire[wire]) + left := candidatesNotReadElsewhere(merger.Walk, byWire[wire]) for _, cd := range left { - out[wire] = append(out[wire], broughtDeclaration(cd.decl, &parts[cd.part])) + out[wire] = append(out[wire], declarationFromEntry(cd.decl, &parts[cd.part])) } if len(left) == 1 { inherited[wire] = left[0].decl @@ -380,137 +368,48 @@ func (idx *ModelPropertyDeclarations) brought(merger Merger, tables map[ir.TypeI return out, inherited } -// ownership is what one settlement reads of the models its parts' declarations -// come from: how far each one's composition reaches (reaching), through alias -// scalars, Base and Mixins, read once per model however many names and -// candidates ask of it, and only as far as a question needs. Each type it -// reads is charged to reads, the run's, so no fixed depth decides an answer: a -// walk the reads cut short leaves a candidate in, and the settlement reports -// the cut. -type ownership struct { - r registry - reads *budget.Budget - walks map[ir.TypeID]*ownerWalk -} - -// newOwnership returns the ownership one settlement reads through -// registryValue, charging reads, which nil leaves without bound, as a Merger -// naming none does. -func newOwnership(registryValue registry, reads *budget.Budget) ownership { - if reads == nil { - reads = new(budget.Budget) - } - return ownership{r: registryValue, reads: reads, walks: map[ir.TypeID]*ownerWalk{}} -} - -// ownerWalk is how far one model's composition has been read breadth first: -// the types it reaches, those queued once, and those whose parts are yet to -// read. -type ownerWalk struct { - reached, queued map[ir.TypeID]bool - queue []ir.TypeID -} - -// reaching returns the types owner's composition reaches, read until it -// reaches each of owners but owner, ends, or the reads run out. A hierarchy -// composing a shared base at every level answers at its first level; one -// composing at every level a model redeclaring a name it holds reads its whole -// depth at each, its depth squared, until the reads run out (GitHub #1993). -func (o ownership) reaching(owner ir.TypeID, owners map[ir.TypeID]bool) map[ir.TypeID]bool { - ownerWalkValue, read := o.walks[owner] - if !read { - ownerWalkValue = &ownerWalk{reached: map[ir.TypeID]bool{}, queued: map[ir.TypeID]bool{owner: true}, queue: []ir.TypeID{owner}} - o.walks[owner] = ownerWalkValue - } - missing := len(owners) - 1 - len(reachedOthers(ownerWalkValue.reached, owners, owner)) - for len(ownerWalkValue.queue) > 0 && missing > 0 { - td, ok := o.r.resolve(ownerWalkValue.queue[0]) - ownerWalkValue.queue = ownerWalkValue.queue[1:] - if !ok { - continue - } - parts := ComposedOf(td) - if !o.reads.Spend(1 + len(parts)) { - ownerWalkValue.queue = nil - break - } - for _, part := range parts { - if !ownerWalkValue.reached[part] && part != owner && owners[part] { - missing-- - } - ownerWalkValue.reached[part] = true - if !ownerWalkValue.queued[part] { - ownerWalkValue.queued[part] = true - ownerWalkValue.queue = append(ownerWalkValue.queue, part) - } - } - } - return ownerWalkValue.reached -} - -// reachedOthers returns the members of owners but owner that reached holds, -// reading the smaller of the two. -func reachedOthers(reached, owners map[ir.TypeID]bool, owner ir.TypeID) []ir.TypeID { - small, large := reached, owners - if len(owners) < len(reached) { - small, large = owners, reached - } - var out []ir.TypeID - for id := range small { - if id != owner && large[id] { - out = append(out, id) - } - } - return out -} - -// left returns cs, one name's candidates in part order, but those it reads -// elsewhere: one an earlier part brings, or one whose model another -// candidate's composes without being composed by it in turn, as two models on -// a cycle each compose the other. Each model's composition is read once, in -// the order of their IDs, so the candidates cost their number, not its square, -// and the reads run out at the same model in every run. -func (o ownership) left(cs []candidate) []candidate { +// candidatesNotReadElsewhere returns cs, one name's candidates in part order, +// but those read elsewhere: one an earlier part brings, or one whose model +// another candidate's composes without being composed by it in turn, as two +// models on a cycle each compose the other. The walk answers what composes +// what at any depth, so no cut decides which candidates remain. +func candidatesNotReadElsewhere(walk FieldDeclarationContext, cs []candidate) []candidate { type key struct { owner ir.TypeID id ir.PropertyID } - owners, brought := map[ir.TypeID]bool{}, map[key]bool{} + var owners []ir.TypeID for _, cd := range cs { - owners[cd.decl.Owner] = true - } - reach, composers := map[ir.TypeID]map[ir.TypeID]bool{}, map[ir.TypeID][]ir.TypeID{} - if len(owners) > 1 { - for _, owner := range slices.Sorted(maps.Keys(owners)) { - reach[owner] = o.reaching(owner, owners) - for _, part := range reachedOthers(reach[owner], owners, owner) { - composers[part] = append(composers[part], owner) - } + if !slices.Contains(owners, cd.decl.Owner) { + owners = append(owners, cd.decl.Owner) } } + entryDeclarations := map[key]bool{} var out []candidate for _, cd := range cs { - keyValue := key{owner: cd.decl.Owner, id: cd.decl.Property.ID} - if brought[keyValue] { + key := key{owner: cd.decl.Owner, id: cd.decl.Property.ID} + if entryDeclarations[key] { continue } - brought[keyValue] = true - within := func(by ir.TypeID) bool { return !reach[cd.decl.Owner][by] } - if !slices.ContainsFunc(composers[cd.decl.Owner], within) { + entryDeclarations[key] = true + within := func(by ir.TypeID) bool { + return by != cd.decl.Owner && walk.IsComposedOf(by, cd.decl.Owner) && !walk.IsComposedOf(cd.decl.Owner, by) + } + if !slices.ContainsFunc(owners, within) { out = append(out, cd) } } return out } -// parts returns the types the model composes (ComposedOf), each with the +// parts returns the types the model composes (ir.ComposedOf), each with the // entry naming it: the first the walk met, or one at the model, read first, // where none does. A type written twice brings its declarations once -// (ownership.left). +// (candidatesNotReadElsewhere). func (idx *ModelPropertyDeclarations) parts() []composedEntry { var out []composedEntry - for _, target := range ComposedOf(idx.m) { - at := slices.IndexFunc(idx.entries, func(composedEntryValue composedEntry) bool { return composedEntryValue.target == target }) + for _, target := range ir.ComposedOf(idx.m) { + at := slices.IndexFunc(idx.entries, func(composedEntry composedEntry) bool { return composedEntry.target == target }) if at < 0 { out = append(out, composedEntry{target: target, at: idx.m.Provenance.Pointer}) continue @@ -522,7 +421,7 @@ func (idx *ModelPropertyDeclarations) parts() []composedEntry { // TakenOutside returns the declaration of member a flattening takes but those of // from: a composition on a cycle reaches from in turn, whose declarations from -// holds already, so the one taken before them stands in. It is false where +// holds already, so the one taken before them is used instead. It is false where // every declaration is from's. func TakenOutside(member ir.FlatProperty, from ir.TypeID) (ir.PropertyDecl, bool) { if member.Owner != from { @@ -536,23 +435,24 @@ func TakenOutside(member ir.FlatProperty, from ir.TypeID) (ir.PropertyDecl, bool return ir.PropertyDecl{}, false } -// broughtDeclaration is from, which another model declares, as an entry, via, +// declarationFromEntry is from, which another model declares, as an entry, via, // brings it, its type judged where it may be written (Declared.TypeAt). The // registry does not say which heuristic set its Secret, so where it is secret // its marker is read as covering that too (declaration.secretBy), as // foldAnnotations reads one covering a deprecation. -func broughtDeclaration(from Declared, via *composedEntry) declaration { - declarationValue := declaration{property: *from.Property, order: via.order, via: via, typeAt: from.TypeAt, owner: from.Owner} - if declarationValue.property.Secret { - declarationValue.secretBy = declarationValue.property.Provenance.Inferred +func declarationFromEntry(from Declared, via *composedEntry) declaration { + declaration := declaration{property: *from.Property, order: via.order, via: via, typeAt: from.TypeAt, owner: from.Owner, + valueWrittenAt: from.ValueAt} + if declaration.property.Secret { + declaration.secretBy = declaration.property.Provenance.Inferred } - return declarationValue + return declaration } -// inOrder returns own and brought, the declarations of one member, in the +// inOrder returns own and carried, the declarations of one member, in the // order the walk met them. -func inOrder(own, brought []declaration) []declaration { - out := slices.Concat(own, brought) +func inOrder(own, entryDeclarations []declaration) []declaration { + out := slices.Concat(own, entryDeclarations) slices.SortStableFunc(out, func(a, b declaration) int { return cmp.Compare(a.order, b.order) }) return out } diff --git a/compilers/openapi/internal/merge/members_internal_test.go b/compilers/openapi/internal/merge/members_internal_test.go index 77f88d3d2..de9441b12 100644 --- a/compilers/openapi/internal/merge/members_internal_test.go +++ b/compilers/openapi/internal/merge/members_internal_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/dexpace/morphic/compilers/openapi/internal/budget" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/ir" @@ -28,7 +27,7 @@ func declared(wire string, target ir.TypeID, pointer string) ir.Property { // its own, and C and D declaring z and y apart. func membersRegistry() ir.TypeRegistry { model := func(id ir.TypeID, base *ir.TypeRef, properties ...ir.Property) *ir.Model { - return &ir.Model{ID: id, Base: base, Properties: properties} + return &ir.Model{ID: id, Base: base, Properties: properties, Provenance: ptrAt(jsontext.Pointer(strings.TrimPrefix(string(id), "type")))} } return ir.TypeRegistry{ "type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}, @@ -56,11 +55,11 @@ func settled(t *testing.T, reg ir.TypeRegistry, steps ...func(idx *ModelProperty } // settleFlat settles idx's model against reg, reading each part as its -// flattening stands and every name as shared, as a run reads a part it has +// flattening reads them and every name as shared, as a run reads a part it has // not settled. -func settleFlat(stubbedValue *stubbed, idx *ModelPropertyDeclarations, reg ir.TypeRegistry) []ir.Diagnostic { +func settleFlat(stubbed *stubbed, idx *ModelPropertyDeclarations, reg ir.TypeRegistry) []ir.Diagnostic { parts, shared := map[ir.TypeID]RedeclaredWireNameTable{}, map[string]bool{} - for _, target := range ComposedOf(idx.m) { + for _, target := range ir.ComposedOf(idx.m) { parts[target] = RedeclaredWireNameTable{} for _, member := range ir.FlattenedProperties(reg, target).Properties { if propertyDecl, ok := TakenOutside(member, idx.m.ID); ok { @@ -68,14 +67,14 @@ func settleFlat(stubbedValue *stubbed, idx *ModelPropertyDeclarations, reg ir.Ty } } } - for _, td := range reg { - if model, ok := td.(*ir.Model); ok { + for _, typeDef := range reg { + if model, ok := typeDef.(*ir.Model); ok { for _, property := range model.Properties { shared[property.WireName] = true } } } - diags, _ := idx.Settle(stubbedValue.Merger, parts, shared) + diags, _ := idx.Settle(stubbed.Merger, parts, shared) return diags } @@ -97,15 +96,16 @@ func own(wire string, target ir.TypeID, n string) func(idx *ModelPropertyDeclara // TestPropertyIndex_SettlesAMemberItsEntriesDeclareApart pins a member two // entries declare apart, in either entry order: the model declares the later's // at /allOf/properties/ in the composed namespace, reports where -// the one that lost is written, naming the property, and keeps nothing, the -// loser staying declared on its model. +// the one passed over is written, listing the property as what it decided and +// naming no node beside its place, and keeps nothing, the passed-over +// declaration staying declared on its model. func TestPropertyIndex_SettlesAMemberItsEntriesDeclareApart(t *testing.T) { t.Parallel() id := ids.DocumentIDNamespace{}.ComposedProperty("/M/allOf/properties/p") for _, tc := range []struct { first, second ir.TypeID want ir.TypeID - lost jsontext.Pointer + passedOver jsontext.Pointer }{ {"type/A", "type/B", "type/primitive/integer", "/A/p"}, {"type/B", "type/A", "type/primitive/string", "/B/p"}, @@ -119,8 +119,9 @@ func TestPropertyIndex_SettlesAMemberItsEntriesDeclareApart(t *testing.T) { assert.Empty(t, property.Unmodeled) require.Len(t, diags, 1, "%v", tc) assert.Equal(t, diag.ConflictingRedecl, diags[0].Code) - assert.Equal(t, tc.lost, diags[0].Provenance.Pointer) - assert.Equal(t, string(id), diags[0].Provenance.Node) + assert.Equal(t, tc.passedOver, diags[0].Provenance.Pointer) + assert.Empty(t, diags[0].Provenance.Node) + assert.Contains(t, diags[0].Related, ir.Related{Role: ir.RelatedDecided, Provenance: ir.Provenance{Pointer: "/M", Node: string(id)}}) } } @@ -146,16 +147,16 @@ func TestPropertyIndex_AComposedModelDeclaresItsMemberAnAllOfDeeper(t *testing.T } // TestPropertyIndex_ReadsAnOwnDeclarationWhereTheWalkMetIt pins a model's own -// declaration beside an entry's, read where the walk met each: the later wins -// a tie, and the result replaces the own declaration at the composed identity, -// which, losing, is kept verbatim; a name the model requires and declares only -// through an entry is the member's, leaving Requires. +// declaration beside an entry's, read where the walk met each: the later is +// chosen a tie, and the result replaces the own declaration at the composed +// identity, which, passed over, is kept verbatim; a name the model requires and +// declares only through an entry is the member's, leaving Requires. func TestPropertyIndex_ReadsAnOwnDeclarationWhereTheWalkMetIt(t *testing.T) { t.Parallel() model, diags := settled(t, membersRegistry(), own("p", "type/primitive/string", "0"), composes("type/B", "1")) require.Len(t, model.Properties, 1) assert.Equal(t, ir.TypeID("type/primitive/integer"), model.Properties[0].Type.Target) - assert.Contains(t, model.Properties[0].Unmodeled, losingDeclarationKey+"/M/allOf/0/properties/p", "the own declaration is kept") + assert.Contains(t, model.Properties[0].Unmodeled, passedOverDeclarationKey+"/M/allOf/0/properties/p", "the own declaration is kept") require.Len(t, diags, 1) assert.Equal(t, jsontext.Pointer("/M/allOf/0/properties/p"), diags[0].Provenance.Pointer, "where the own one is written") @@ -168,13 +169,12 @@ func TestPropertyIndex_ReadsAnOwnDeclarationWhereTheWalkMetIt(t *testing.T) { assert.Empty(t, model.Requires) } -// TestPropertyIndex_PlacesADeclarationAtTheEntryBringingIt pins where a brought +// TestPropertyIndex_PlacesADeclarationAtTheEntryBringingIt pins where a carried // declaration is read: at the entry naming its owner or a type composing it, // and at the model, read first, where no entry does, a conflict over it sitting -// where it is written either way; an owner -// another entry's composes brings nothing, Sub's p standing within A's, but -// one of two models composing each other does, and a declaration two entries -// bring is read once. +// where it is written either way; an owner another entry's composes brings +// nothing, Sub's p lying within A's, but one of two models composing each other +// does, and a declaration two entries bring is read once. func TestPropertyIndex_PlacesADeclarationAtTheEntryBringingIt(t *testing.T) { t.Parallel() reg := membersRegistry() @@ -191,7 +191,7 @@ func TestPropertyIndex_PlacesADeclarationAtTheEntryBringingIt(t *testing.T) { assert.Equal(t, jsontext.Pointer("/B/p"), diags[0].Provenance.Pointer) model, diags = settled(t, membersRegistry(), composes("type/Sub", "0"), composes("type/A", "1")) - assert.Empty(t, model.Properties, "Sub's p stands within A's, so one declaration decides") + assert.Empty(t, model.Properties, "Sub's p lies within A's, so one declaration decides") assert.Empty(t, diags) reg = membersRegistry() @@ -246,7 +246,7 @@ func TestPropertyIndex_APromotedRedactionBringsItsMarkerInEitherOrder(t *testing // TestTypeJudge_AUnionsVariantIsJudgedAtTheUnionsSite pins the sites a // variant is read at: its union's declaration's, whichever side the union is // on, so a variant and a node hoisted alike at the other declaration are one -// type, and swapping the two flips the verdict and changes nothing else. +// type, and swapping the two flips the answer and changes nothing else. func TestTypeJudge_AUnionsVariantIsJudgedAtTheUnionsSite(t *testing.T) { t.Parallel() enum := func(id ir.TypeID, at jsontext.Pointer) *ir.Enum { @@ -268,7 +268,7 @@ func TestTypeJudge_AUnionsVariantIsJudgedAtTheUnionsSite(t *testing.T) { // TestPropertyIndex_ComposesModelsAsTheirEntriesBringThem pins a member entries // declare as two models: the field composes them in the order the entries are -// written, recording where each part was brought, so the composed model's own +// written, recording where each part was carried, so the composed model's own // members report at those entries and read the later as the specialization. func TestPropertyIndex_ComposesModelsAsTheirEntriesBringThem(t *testing.T) { t.Parallel() @@ -292,29 +292,31 @@ func TestPropertyIndex_ComposesModelsAsTheirEntriesBringThem(t *testing.T) { minted, ok := reg[model.Properties[0].Type.Target].(*ir.Model) require.True(t, ok, "%v", order) assert.Equal(t, []ir.TypeRef{{Target: order[0] + "part"}, {Target: order[1] + "part"}}, minted.Mixins, "%v", order) - assert.Equal(t, []jsontext.Pointer{"/M/allOf/0", "/M/allOf/1"}, stubbed.walk.brought[minted.ID], "%v", order) + assert.Equal(t, []jsontext.Pointer{"/M/allOf/0", "/M/allOf/1"}, stubbed.walk.partPointers[minted.ID], "%v", order) } } // TestFold_ABroughtDeclarationPastTheBoundStaysOnItsModel pins a declaration an -// entry brings past the declarations one fold judges: reported at the entry +// entry brings past the declarations one fold judges, the first that many +// written: B's, written after the 64 at /A/data and carried first, is the one +// left unjudged, reported where it is written rather than at the entry // bringing it, and kept nowhere, as it stays declared on its model. func TestFold_ABroughtDeclarationPastTheBoundStaysOnItsModel(t *testing.T) { t.Parallel() + past := declared("data", "type/primitive/string", "/B/data") decls := make([]declaration, 0, maxFoldDeclarations+1) + decls = append(decls, declaration{property: past, via: &composedEntry{target: "type/B", at: "/M/allOf/0"}}) for range maxFoldDeclarations { - decls = append(decls, nthDecl(0, "type/primitive/string")) + decls = append(decls, declaration{property: declared("data", "type/primitive/string", "/A/data"), source: written(`{}`)}) } - past := declared("data", "type/primitive/string", "/B/data") - decls = append(decls, declaration{property: past, via: &composedEntry{target: "type/B", at: "/M/allOf/9"}}) stubbed, _ := stubMerger(membersRegistry()) - got, diags := stubbed.foldAt(decls, "/M/allOf/properties/data", nil) + got, _, diags := stubbed.foldAt(decls, "/M/allOf/properties/data", nil) require.Len(t, diags, 1) assert.Equal(t, diag.BudgetExceeded, diags[0].Code) - assert.Equal(t, jsontext.Pointer("/M/allOf/9"), diags[0].Provenance.Pointer) - assert.NotContains(t, got.Unmodeled, losingDeclarationKey+"/B/data") + assert.Equal(t, jsontext.Pointer("/B/data"), diags[0].Provenance.Pointer) + assert.NotContains(t, got.Unmodeled, passedOverDeclarationKey+"/B/data") } // TestPropertyIndex_KeepsTheIdentityOfTheDeclarationItHoldsAlone pins the @@ -323,7 +325,8 @@ func TestFold_ABroughtDeclarationPastTheBoundStaysOnItsModel(t *testing.T) { // declaration too, as a node interned at the allOf entry writing it does, or it // is written outside the model's schema, as the body a distributed variant // shares is; then one in the composed namespace. The conflict over the entry's -// declaration sits where that is written either way, naming the member. +// declaration sits where that is written either way, listing the member as +// what it decided. func TestPropertyIndex_KeepsTheIdentityOfTheDeclarationItHoldsAlone(t *testing.T) { t.Parallel() const composedAt jsontext.Pointer = "/M/allOf/properties/p" @@ -355,7 +358,9 @@ func TestPropertyIndex_KeepsTheIdentityOfTheDeclarationItHoldsAlone(t *testing.T assert.Equal(t, ir.TypeID("type/primitive/string"), property.Type.Target, "%s: the own declaration, written later", name) require.Len(t, diags, 1, name) assert.Equal(t, jsontext.Pointer("/B/p"), diags[0].Provenance.Pointer, name) - assert.Equal(t, string(property.ID), diags[0].Provenance.Node, name) + assert.Empty(t, diags[0].Provenance.Node, name) + assert.Contains(t, diags[0].Related, ir.Related{Role: ir.RelatedDecided, + Provenance: ir.Provenance{Pointer: "/M", Node: string(property.ID)}}, name) } } @@ -377,19 +382,18 @@ func TestFold_NamesADeclarationAnotherDocumentHolds(t *testing.T) { {property: declared("p", "type/primitive/string", "/M/allOf/1/properties/p"), source: written(`{}`), order: 2}, } - _, diags := stubbed.foldAt(decls, "/M/allOf/1/properties/p", nil) + _, _, diags := stubbed.foldAt(decls, "/M/allOf/1/properties/p", nil) require.Len(t, diags, 1) - assert.Contains(t, diags[0].Message, - "kept what the declaration at /M/allOf/1/properties/p in root.yaml says over the one at /B/p,") + assert.Contains(t, diags[0].Message, `field "p": /M/allOf/1/properties/p in root.yaml and /B/p disagree:`) assert.Equal(t, ir.Provenance{Source: 1, Pointer: "/B/p", WrittenBy: 2}, diags[0].Provenance) } // TestFold_NamesEachPlaceAgainstTheDocumentTheReportIsIn pins how a conflict -// names the two declarations: against the document it stands in, the losing +// names the two declarations: against the document it is in, the passed-over // declaration's, so that one is named by its pointer alone and the one kept // carries its document's name where it is in another, wherever the composing -// model is. The kept place the report lists is the one its message names. +// model is. The chosen place the report lists is the one its message names. func TestFold_NamesEachPlaceAgainstTheDocumentTheReportIsIn(t *testing.T) { t.Parallel() at := func(target ir.TypeID, pointer string, source int) declaration { @@ -398,63 +402,63 @@ func TestFold_NamesEachPlaceAgainstTheDocumentTheReportIsIn(t *testing.T) { return declaration{property: property, via: &composedEntry{target: "type/E", at: "/M/allOf/0", order: 1}} } for name, tc := range map[string]struct { - sources []string - lost, kept declaration - message string - lostIn int - keptIn int - keptNamesIn bool + sources []string + passedOver, chosen declaration + message string + passedOverIn int + chosenIn int + chosenNamesIn bool }{ - "the loser in another document": { - sources: []string{"root.yaml", "other.yaml"}, - lost: at("type/primitive/integer", "/B/p", 1), kept: at("type/primitive/string", "/A/p", 0), - message: "kept what the declaration at /A/p in root.yaml says over the one at /B/p,", lostIn: 1, keptIn: 0, keptNamesIn: true, + "the passed-over declaration in another document": { + sources: []string{"root.yaml", "other.yaml"}, + passedOver: at("type/primitive/integer", "/B/p", 1), chosen: at("type/primitive/string", "/A/p", 0), + message: "/A/p in root.yaml and /B/p disagree:", passedOverIn: 1, chosenIn: 0, chosenNamesIn: true, }, - "the winner in another document": { - sources: []string{"root.yaml", "other.yaml"}, - lost: at("type/primitive/integer", "/A/p", 0), kept: at("type/primitive/string", "/B/p", 1), - message: "kept what the declaration at /B/p in other.yaml says over the one at /A/p,", lostIn: 0, keptIn: 1, keptNamesIn: true, + "the chosen declaration in another document": { + sources: []string{"root.yaml", "other.yaml"}, + passedOver: at("type/primitive/integer", "/A/p", 0), chosen: at("type/primitive/string", "/B/p", 1), + message: "/B/p in other.yaml and /A/p disagree:", passedOverIn: 0, chosenIn: 1, chosenNamesIn: true, }, "both in the model's document": { - sources: []string{"root.yaml"}, - lost: at("type/primitive/integer", "/A/p", 0), kept: at("type/primitive/string", "/B/p", 0), - message: "kept what the declaration at /B/p says over the one at /A/p,", lostIn: 0, keptIn: 0, + sources: []string{"root.yaml"}, + passedOver: at("type/primitive/integer", "/A/p", 0), chosen: at("type/primitive/string", "/B/p", 0), + message: "/B/p and /A/p disagree:", passedOverIn: 0, chosenIn: 0, }, "each in a document of its own": { - sources: []string{"root.yaml", "a.yaml", "b.yaml"}, - lost: at("type/primitive/integer", "/A/p", 1), kept: at("type/primitive/string", "/B/p", 2), - message: "kept what the declaration at /B/p in b.yaml says over the one at /A/p,", lostIn: 1, keptIn: 2, keptNamesIn: true, + sources: []string{"root.yaml", "a.yaml", "b.yaml"}, + passedOver: at("type/primitive/integer", "/A/p", 1), chosen: at("type/primitive/string", "/B/p", 2), + message: "/B/p in b.yaml and /A/p disagree:", passedOverIn: 1, chosenIn: 2, chosenNamesIn: true, }, } { stubbed, _ := stubMerger(membersRegistry()) for _, path := range tc.sources { stubbed.Sources = append(stubbed.Sources, ir.SourceInfo{Path: path}) } - lost, kept := tc.lost, tc.kept - lost.order, kept.order = 1, 2 + passedOver, chosen := tc.passedOver, tc.chosen + passedOver.order, chosen.order = 1, 2 - _, diags := stubbed.foldAt([]declaration{lost, kept}, "/M/allOf/properties/p", nil) + _, _, diags := stubbed.foldAt([]declaration{passedOver, chosen}, "/M/allOf/properties/p", nil) require.Len(t, diags, 1, name) assert.Contains(t, diags[0].Message, tc.message, name) - assert.Equal(t, tc.lostIn, diags[0].Provenance.Source, "%s: the report stands in the losing declaration's document", name) + assert.Equal(t, tc.passedOverIn, diags[0].Provenance.Source, "%s: the report is in the passed-over declaration's document", name) require.Len(t, diags[0].Related, 1, name) listed := diags[0].Related[0].Provenance - assert.Equal(t, ir.Provenance{Source: tc.keptIn, Pointer: kept.property.Provenance.Pointer}, listed, name) - assert.Equal(t, tc.keptNamesIn, listed.Source != diags[0].Provenance.Source, "%s: the message names a document where the entry lists another", name) - assert.Equal(t, tc.keptNamesIn, strings.Contains(diags[0].Message, string(listed.Pointer)+" in "+tc.sources[listed.Source]), name) + assert.Equal(t, ir.Provenance{Source: tc.chosenIn, Pointer: chosen.property.Provenance.Pointer}, listed, name) + assert.Equal(t, tc.chosenNamesIn, listed.Source != diags[0].Provenance.Source, "%s: the message names a document where the entry lists another", name) + assert.Equal(t, tc.chosenNamesIn, strings.Contains(diags[0].Message, string(listed.Pointer)+" in "+tc.sources[listed.Source]), name) } } -// TestTypeSites_NamesWhereAFoldedTypesNodesAreWritten pins where a settled +// TestTypeSites_NamesWhereAFieldTypesNodesAreWritten pins where a settled // member says the nodes of its type are written: where the one declaration -// naming its node says, as that declaration's own list; nowhere for a -// primitive several name, or a node the registry lacks; for a hoisted node -// several name, where the first holding it says, else the first. For a node -// the fold built: where it stands and where each node it holds is written, -// through a node built beneath it or one holding itself, however many places -// a declaration brings, but for a node a $ref reached and what that holds. -func TestTypeSites_NamesWhereAFoldedTypesNodesAreWritten(t *testing.T) { +// naming its node says, as that declaration's own list; nowhere for a primitive +// several name, or a node the registry lacks; for a hoisted node several name, +// where the first holding it says, else the first. For a node the fold built: +// where it is and where each node it holds is written, through a node built +// beneath it or one holding itself, however many places a declaration brings, +// but for a node a $ref reached and what that holds. +func TestTypeSites_NamesWhereAFieldTypesNodesAreWritten(t *testing.T) { t.Parallel() hoisted := func(id ir.TypeID, at jsontext.Pointer) ir.TypeCommon { return ir.TypeCommon{ID: id, Anonymous: true, Provenance: ptrAt(at)} @@ -479,15 +483,15 @@ func TestTypeSites_NamesWhereAFoldedTypesNodesAreWritten(t *testing.T) { for i := range maxTypeSites { partSites = append(partSites, ptrAt(jsontext.Pointer(fmt.Sprintf("/part/deeper/%d", i)))) } - brought := declaration{property: declared("p", "type/primitive/string", "/part/allOf/0/p"), via: part, typeAt: partSites} + fromEntries := declaration{property: declared("p", "type/primitive/string", "/part/allOf/0/p"), via: part, typeAt: partSites} own := declaration{property: declared("p", "type/primitive/integer", "/M/p")} twin := declaration{property: declared("p", "type/primitive/string", "/M/q")} field := func(target ir.TypeID) ir.Property { return declared("p", target, "/M/p") } - kept := stubbed.typeSites(field("type/primitive/string"), []declaration{own, brought}) + kept := stubbed.typeSites(field("type/primitive/string"), []declaration{own, fromEntries}) assert.Equal(t, partSites, kept) assert.Same(t, &partSites[0], &kept[0], "one declaration's list is the member's, uncopied") - assert.Nil(t, stubbed.typeSites(field("type/primitive/string"), []declaration{brought, own, twin}), "no declaration writes a primitive") + assert.Nil(t, stubbed.typeSites(field("type/primitive/string"), []declaration{fromEntries, own, twin}), "no declaration writes a primitive") assert.Nil(t, stubbed.typeSites(field("type/unregistered"), []declaration{own})) named := func(pointer string) declaration { return declaration{property: declared("p", "type/enum", pointer)} } @@ -498,7 +502,7 @@ func TestTypeSites_NamesWhereAFoldedTypesNodesAreWritten(t *testing.T) { for _, built := range []ir.TypeID{"type/built", "type/built-list", "type/built-map", "type/built-rest", "type/built-model", "type/built-nested", "type/built-cycle"} { assert.Equal(t, []ir.Provenance{ptrAt("/M/p"), ptrAt("/part/allOf/1/p")}, - stubbed.typeSites(field(built), []declaration{own, brought}), "%s: where it stands, then where what it holds is written", built) + stubbed.typeSites(field(built), []declaration{own, fromEntries}), "%s: where it is, then where what it holds is written", built) } } @@ -532,12 +536,14 @@ func TestBuiltSites_ReadsNoMoreNodesThanItsBound(t *testing.T) { } // TestFold_NamesABroughtDeclarationWhereItSaysWhatItDoes pins how a report -// names a declaration an entry brings. One a part settled names its first -// declaration whichever gave its type, so the report names the one place its -// type is written; where its type is written at several places or none, the -// member's own place; and where the place it would name is the member's own -// and its model's composition settled it there, at either depth, the entry -// bringing it, since no schema is written there. +// about what several declarations give together, the type among them, names +// a declaration an entry brings: at the one place its type is written, as +// every report names a place writing what it speaks of, and so not at the +// member's own declaration when another gave its type +// (docs/compilers/openapi.md#allof-redeclared-property); where its type is +// written at several places or none, where the member is; and for a member +// its model's composition settled, at either depth, written nowhere, at that +// model's place, which no entry composing it moves. func TestFold_NamesABroughtDeclarationWhereItSaysWhatItDoes(t *testing.T) { t.Parallel() reg := membersRegistry() @@ -545,25 +551,26 @@ func TestFold_NamesABroughtDeclarationWhereItSaysWhatItDoes(t *testing.T) { stubbed, _ := stubMerger(reg) entry := &composedEntry{target: "type/part", at: "/M/allOf/0"} built := []ir.Provenance{ptrAt("/part/p"), ptrAt("/part/allOf/0/p"), ptrAt("/part/allOf/1/p")} - brought := func(owner ir.TypeID, pointer string, typeAt []ir.Provenance) declaration { + fromEntries := func(owner ir.TypeID, pointer string, typeAt []ir.Provenance) declaration { property := declared("p", "type/primitive/string", pointer) - return broughtDeclaration(Declared{Owner: owner, Property: &property, TypeAt: typeAt}, entry) - } - foldingValue := &folding{g: &stubbed.Merger, decls: []declaration{ - brought("type/part", "/part/allOf/0/p", sitesAt("/part/allOf/1/p")), - brought("type/part", "/part/allOf/0/p", built), - brought("type/part", "/part/allOf/properties/p", built), - brought("type/part", "/part/allOf/allOf/properties/p", built), - brought("type/part", "/part/allOf/properties/p", sitesAt("/part/allOf/1/p")), - brought("type/part", "/part/allOf/properties/p", sitesAt("/part/allOf/properties/p")), - brought("type/part", "/part/allOf/0/p", nil), - brought("type/primitive/string", "/part/allOf/properties/p", built), + return declarationFromEntry(Declared{Owner: owner, Property: &property, TypeAt: typeAt}, entry) + } + folding := &fieldFold{g: &stubbed.Merger, decls: []declaration{ + fromEntries("type/part", "/part/allOf/0/p", sitesAt("/part/allOf/1/p")), + fromEntries("type/part", "/part/allOf/0/p", built), + fromEntries("type/part", "/part/allOf/properties/p", built), + fromEntries("type/part", "/part/allOf/allOf/properties/p", built), + fromEntries("type/part", "/part/allOf/properties/p", sitesAt("/part/allOf/1/p")), + fromEntries("type/part", "/part/allOf/properties/p", sitesAt("/part/allOf/properties/p")), + fromEntries("type/part", "/part/allOf/0/p", nil), + fromEntries("type/primitive/string", "/part/allOf/properties/p", built), {property: declared("p", "type/primitive/string", "/M/allOf/properties/p")}, }} - for i, want := range []string{"/part/allOf/1/p", "/part/allOf/0/p", "/M/allOf/0", "/M/allOf/0", "/part/allOf/1/p", - "/M/allOf/0", "/part/allOf/0/p", "/part/allOf/properties/p", "/M/allOf/properties/p"} { - assert.Equal(t, want, foldingValue.at(i), "declaration %d", i) + for i, want := range []string{"/part/allOf/1/p", "/part/allOf/0/p", "/part", "/part", "/part/allOf/1/p", + "/part", "/part/allOf/0/p", "/part/allOf/properties/p", "/M/allOf/properties/p"} { + place := fieldPlace(folding.g, folding.decls[i], fieldGivenTogether) + assert.Equal(t, want, placeName(folding.g.Sources, place, place.Source), "declaration %d", i) } } @@ -593,60 +600,24 @@ func TestHoistedAt_ReadsEachPlaceADeclarationHoldsItsType(t *testing.T) { // field says wrote it. func TestFold_AnEntryAlikeInTwoDocumentsKeepsOneWhateverTheOrder(t *testing.T) { t.Parallel() - brought := func(source, order int) declaration { + fromEntries := func(source, order int) declaration { property := declared("p", "type/primitive/string", "/properties/p") property.Provenance.Source = source at := ir.Provenance{Source: source, Pointer: "/properties/p/x-tag"} property.Unmodeled = ir.Unmodeled{"openapi:x-tag": {Value: ir.RawValue(`"same"`), Provenance: at}} entry := &composedEntry{target: "type/part", at: "/M/allOf/0", order: order} - return broughtDeclaration(DeclaredAt(ir.PropertyDecl{Owner: "type/part", Property: &property}), entry) + return declarationFromEntry(DeclaredAt(ir.PropertyDecl{Owner: "type/part", Property: &property}), entry) } for _, sources := range [][2]int{{1, 2}, {2, 1}} { stubbed, _ := stubMerger(membersRegistry()) - got, diags := stubbed.foldAt([]declaration{brought(sources[0], 1), brought(sources[1], 2)}, "/M/allOf/properties/p", nil) + got, _, diags := stubbed.foldAt([]declaration{fromEntries(sources[0], 1), fromEntries(sources[1], 2)}, "/M/allOf/properties/p", nil) assert.Empty(t, diags, "entries written alike say one thing") assert.Equal(t, 1, got.Unmodeled["openapi:x-tag"].Provenance.Source, "entries from %v", sources) } } -// TestOwnership_ReadsEachModelsCompositionOnce pins what sorting one name's -// candidates costs: each model's composition is read once, however many other -// candidates ask whether it composes theirs, so the reads grow with the -// candidates, not their square. Each candidate's model composes a chain as -// deep as the judge's walk reads, and none composes another, so every one is -// left. -func TestOwnership_ReadsEachModelsCompositionOnce(t *testing.T) { - t.Parallel() - reads := func(n int) int { - reg := map[ir.TypeID]ir.TypeDef{"type/link-0": declaring("type/link-0")} - for i := 1; i <= maxComposedParts; i++ { - id := ir.TypeID(fmt.Sprintf("type/link-%d", i)) - reg[id] = &ir.Model{ID: id, Base: &ir.TypeRef{Target: ir.TypeID(fmt.Sprintf("type/link-%d", i-1))}} - } - cs := make([]candidate, n) - for i := range cs { - owner := ir.TypeID(fmt.Sprintf("type/owner-%d", i)) - property := declared("p", "type/primitive/string", "/"+string(owner)+"/p") - last := ir.TypeID(fmt.Sprintf("type/link-%d", maxComposedParts)) - reg[owner] = &ir.Model{ID: owner, Base: &ir.TypeRef{Target: last}, Properties: []ir.Property{property}} - cs[i] = candidate{decl: DeclaredAt(ir.PropertyDecl{Owner: owner, Property: &property}), part: i} - } - count := 0 - ownership := newOwnership(registry{resolve: func(id ir.TypeID) (ir.TypeDef, bool) { - count++ - td, ok := reg[id] - return td, ok - }}, nil) - - require.Len(t, ownership.left(cs), n, "no model composes another") - return count - } - a, b := reads(50), reads(100) - assert.LessOrEqual(t, float64(b), 2.5*float64(a), "reads at 50 and 100 candidates: %d, %d", a, b) -} - // chainTo returns reg with a chain of depth models above base, each composing // the one below it, and the top one's ID. func chainTo(reg map[ir.TypeID]ir.TypeDef, base ir.TypeID, depth int) ir.TypeID { @@ -659,128 +630,27 @@ func chainTo(reg map[ir.TypeID]ir.TypeDef, base ir.TypeID, depth int) ir.TypeID return below } -// countingRegistry returns a registry reading reg, and the count of its reads. -func countingRegistry(reg map[ir.TypeID]ir.TypeDef) (registry, *int) { - count := new(int) - return registry{resolve: func(id ir.TypeID) (ir.TypeDef, bool) { - *count++ - td, ok := reg[id] - return td, ok - }}, count -} - -// leafOver returns a registry holding t/Base declaring p and t/Leaf -// redeclaring it, which composes t/Base through a chain of depth models and, -// where direct, as a mixin too, and a candidate of each, Leaf's part first. -func leafOver(depth int, direct bool) (map[ir.TypeID]ir.TypeDef, []candidate) { - reg := map[ir.TypeID]ir.TypeDef{} - baseP := declared("p", "type/primitive/integer", "/Base/p") - reg["type/Base"] = &ir.Model{ID: "type/Base", Properties: []ir.Property{baseP}} - top := chainTo(reg, "type/Base", depth) - leafP := declared("p", "type/primitive/integer", "/Leaf/p") - leaf := &ir.Model{ID: "type/Leaf", Base: &ir.TypeRef{Target: top}, Properties: []ir.Property{leafP}} - if direct { - leaf.Mixins = []ir.TypeRef{{Target: "type/Base"}} - } - reg["type/Leaf"] = leaf - return reg, []candidate{ - {decl: DeclaredAt(ir.PropertyDecl{Owner: "type/Leaf", Property: &leafP}), part: 0}, - {decl: DeclaredAt(ir.PropertyDecl{Owner: "type/Base", Property: &baseP}), part: 1}, - } -} - -// TestOwnership_LeavesOutADeclarationAnotherComposesAtAnyDepth pins that a -// declaration another candidate's model composes stands within it however deep -// that model's hierarchy nests, past the judge's walk too: a model composing a -// hierarchy and its base again folds the hierarchy's declaration alone. -func TestOwnership_LeavesOutADeclarationAnotherComposesAtAnyDepth(t *testing.T) { - t.Parallel() - for _, depth := range []int{1, maxComposedParts, 4 * maxComposedParts} { - reg, cs := leafOver(depth, false) - registry, _ := countingRegistry(reg) - - left := newOwnership(registry, nil).left(cs) - - require.Len(t, left, 1, "at depth %d", depth) - assert.Equal(t, ir.TypeID("type/Leaf"), left[0].decl.Owner, "at depth %d", depth) - } -} - -// TestOwnership_ReadsPastAPartNamingNoType pins a composition one of whose -// parts names no type, as a reference left dangling does: the walk reads past -// it to the rest, so the base it reaches beside it is still found. -func TestOwnership_ReadsPastAPartNamingNoType(t *testing.T) { +// TestSettle_LeavesOutADeclarationAnotherPartComposesAtAnyDepth pins that a +// declaration one part brings lies within another part's composition however +// deep the hierarchy between them nests, past the 64 levels a walk once read: a +// model composing a hierarchy and its base again folds nothing, the hierarchy's +// own declaration narrowing the base's there already. +func TestSettle_LeavesOutADeclarationAnotherPartComposesAtAnyDepth(t *testing.T) { t.Parallel() - reg, cs := leafOver(3, false) - leaf, ok := reg["type/Leaf"].(*ir.Model) - require.True(t, ok) - leaf.Mixins = []ir.TypeRef{*leaf.Base} - leaf.Base = &ir.TypeRef{Target: "type/missing"} - registry, _ := countingRegistry(reg) - - left := newOwnership(registry, nil).left(cs) - - require.Len(t, left, 1) - assert.Equal(t, ir.TypeID("type/Leaf"), left[0].decl.Owner) -} - -// TestOwnership_AWalkReturningToItsModelReadsOnToTheOthers pins a walk whose -// model's composition leads back to the model: it is none of the others the -// walk reads on for, so the walk passes it and reaches a candidate's model -// read after it, whose declaration then stands within the walk's own. -func TestOwnership_AWalkReturningToItsModelReadsOnToTheOthers(t *testing.T) { - t.Parallel() - reg := map[ir.TypeID]ir.TypeDef{} - declaring := func(id ir.TypeID, parts ...ir.TypeID) candidate { - model := &ir.Model{ID: id, Properties: []ir.Property{declared("p", "type/primitive/string", "/"+string(id)+"/p")}} - for _, part := range parts { - model.Mixins = append(model.Mixins, ir.TypeRef{Target: part}) - } - reg[id] = model - return candidate{decl: DeclaredAt(ir.PropertyDecl{Owner: id, Property: &model.Properties[0]})} - } - top := declaring("type/top", "type/loop") - reg["type/loop"] = &ir.Model{ID: "type/loop", Mixins: []ir.TypeRef{{Target: "type/top"}, {Target: "type/near"}, {Target: "type/mid"}}} - reg["type/mid"] = &ir.Model{ID: "type/mid", Base: &ir.TypeRef{Target: "type/far"}} - near, far := declaring("type/near"), declaring("type/far") - near.part, far.part = 1, 2 - - left := newOwnership(registry{resolve: stubResolve(reg)}, nil).left([]candidate{top, near, far}) - - require.Len(t, left, 1, "each other declaration stands within the first's composition") - assert.Equal(t, ir.TypeID("type/top"), left[0].decl.Owner) -} + for _, depth := range []int{1, 64, 65, 256} { + reg := membersRegistry() + top := chainTo(reg, "type/B", depth) + near, ok := reg["type/level-1"].(*ir.Model) + require.True(t, ok) + near.Properties = []ir.Property{declared("p", "type/primitive/string", "/level-1/p")} -// TestOwnership_StopsOnceItReachesEveryOtherModel pins what telling one -// candidate from another costs where one model composes the other directly -// beside a deep hierarchy: the walk stops at the first level, so a hierarchy -// composing a shared base at every level costs its size, not its depth squared. -func TestOwnership_StopsOnceItReachesEveryOtherModel(t *testing.T) { - t.Parallel() - reads := func(depth int) int { - reg, cs := leafOver(depth, true) - registry, count := countingRegistry(reg) + diags := settledModel(t, reg, "type/M", "/M", partAt(top, "0"), partAt("type/B", "1")) - require.Len(t, newOwnership(registry, nil).left(cs), 1, "at depth %d", depth) - return *count + assert.Empty(t, diags, "depth %d: the base's declaration lies within the hierarchy", depth) + model, ok := reg["type/M"].(*ir.Model) + require.True(t, ok) + assert.Empty(t, model.Properties, "depth %d: nothing taken into one", depth) } - assert.Equal(t, reads(10), reads(1000), "reads at depth 10 and 1,000") -} - -// TestOwnership_ChargesWhatItReadsAndLeavesInWhatACutWalkMisses pins the -// run's reads as the walk's bound: each type it reads is charged, and a walk -// they cut short tells nothing, so both candidates are left and the reads say -// they ran out, which the settlement reports. -func TestOwnership_ChargesWhatItReadsAndLeavesInWhatACutWalkMisses(t *testing.T) { - t.Parallel() - reg, cs := leafOver(100, false) - registry, _ := countingRegistry(reg) - reads := budget.New(budget.AtMost(50)) - - left := newOwnership(registry, &reads).left(cs) - - assert.Len(t, left, 2, "a cut walk shows no candidate within another") - assert.True(t, reads.Exhausted(), "the walk charged its reads") } // TestPropertyIndex_ADiscriminatorNamingAnAppendedMemberNamesItsID pins the @@ -804,7 +674,7 @@ func TestPropertyIndex_ADiscriminatorNamingAnAppendedMemberNamesItsID(t *testing } // TestTakenOutside_LeavesOutTheComposingModelsOwn pins the declaration a part's -// flattening stands for: the one it takes, or, where that is the composing +// flattening represents: the one it takes, or, where that is the composing // model's own, as a cycle reaches it, the last other it reads, and none where // every declaration is the model's. func TestTakenOutside_LeavesOutTheComposingModelsOwn(t *testing.T) { diff --git a/compilers/openapi/internal/merge/merge.go b/compilers/openapi/internal/merge/merge.go index 2a0d3bf6a..b8a1abe78 100644 --- a/compilers/openapi/internal/merge/merge.go +++ b/compilers/openapi/internal/merge/merge.go @@ -45,6 +45,10 @@ type ModelPropertyDeclarations struct { // typeAt is where the nodes of the type of each member Settle folded may // be written, by wire name (Merger.typeSites). typeAt map[string][]ir.Provenance + // valueWrittenAt is, for each member Settle folded, where the value of each + // field its fold took from one declaration is written, by wire name + // (Declared.ValueAt). + valueWrittenAt map[string]map[string]ir.Provenance } // field is one wire name the model declares: where its property sits, and @@ -66,31 +70,33 @@ type composedEntry struct { // NewModelPropertyDeclarations returns an empty index of model's properties; // model holds none yet, so every property reaches it through MergeProperty. func NewModelPropertyDeclarations(model *ir.Model) *ModelPropertyDeclarations { - return &ModelPropertyDeclarations{m: model, byWire: map[string]*field{}, typeAt: map[string][]ir.Provenance{}} + return &ModelPropertyDeclarations{m: model, byWire: map[string]*field{}, typeAt: map[string][]ir.Provenance{}, + valueWrittenAt: map[string]map[string]ir.Provenance{}} } -// MergeProperty appends p to the model, or records it as one more declaration -// of the field that already carries its wire name: overlapping allOf entries -// (and properties co-declared alongside allOf) redeclare one logical field -// under allOf's intersection semantics +// MergeProperty appends property to the model, or records it as one more +// declaration of the field that already carries its wire name: overlapping +// allOf entries (and properties co-declared alongside allOf) redeclare one +// logical field under allOf's intersection semantics // (docs/compilers/openapi.md#allof-redeclared-property). Callers must set -// p.WireName (fillModelProperties always does); it keys idx directly. +// property.WireName (fillModelProperties always does); it keys idx directly. // -// p.Provenance alone locates the declaration, so no second copy can disagree. -// secretBy names the heuristics that set p.Secret, empty where a keyword -// declared it (folding.foldUse). It reports whether p is the model's first -// redeclaration, from which the model has members to settle. +// property.Provenance alone locates the declaration, so no second copy can +// disagree. secretBy names the heuristics that set property.Secret, empty +// where a keyword declared it (fieldFold.foldUse). It reports whether property +// is the model's first redeclaration, from which the model has members to +// settle. func (idx *ModelPropertyDeclarations) MergeProperty(property ir.Property, source DeclarationConstructRenderer, secretBy ir.Inferred) (firstRedeclaration bool) { - declarationValue := declaration{property: property, source: source, secretBy: secretBy, order: idx.next()} - fieldValue, ok := idx.byWire[property.WireName] + added := declaration{property: property, source: source, secretBy: secretBy, order: idx.next()} + existing, ok := idx.byWire[property.WireName] if !ok { - idx.byWire[property.WireName] = &field{pos: len(idx.m.Properties), decls: []declaration{declarationValue}} + idx.byWire[property.WireName] = &field{pos: len(idx.m.Properties), decls: []declaration{added}} idx.m.Properties = append(idx.m.Properties, property) return false } first := !idx.redeclared idx.redeclared = true - fieldValue.decls = append(fieldValue.decls, declarationValue) + existing.decls = append(existing.decls, added) return first } diff --git a/compilers/openapi/internal/merge/merge_internal_test.go b/compilers/openapi/internal/merge/merge_internal_test.go index 043267ea8..719230f07 100644 --- a/compilers/openapi/internal/merge/merge_internal_test.go +++ b/compilers/openapi/internal/merge/merge_internal_test.go @@ -6,6 +6,7 @@ package merge import ( "encoding/json/jsontext" "maps" + "reflect" "slices" "strings" "testing" @@ -25,11 +26,11 @@ func ptrAt(pointer jsontext.Pointer) ir.Provenance { return ir.Provenance{Pointe // unread is the source of a redeclaration the merge has no reason to keep: it // fails the test if rendered, which is how a case asserts that nothing of the -// redeclaration was lost. +// redeclaration was passed over. func unread(t *testing.T) func() (ir.RawValue, error) { return func() (ir.RawValue, error) { t.Helper() - t.Fatal("the redeclaration's source was rendered, so the merge believes it lost something") + t.Fatal("the redeclaration's source was rendered, so the merge believes it passed something over") return nil, nil } } @@ -58,8 +59,8 @@ func atRoot(walk FieldDeclarationContext) declarationSites { // judge is the type judgment over the registry stubbedValue reads, its // declarations read against one base. -func judge(stubbedValue *stubbed) typeJudge { - return typeJudge{resolve: stubbedValue.resolve, sites: atRoot(stubbedValue.walk)} +func judge(stubbed *stubbed) typeJudge { + return typeJudge{resolve: stubbed.resolve, sites: atRoot(stubbed.walk)} } // untypedAt reports whether a node of a registry is written under /untyped, @@ -79,55 +80,175 @@ type stubbed struct { // fold is Merger.fold, recording what it reports. func (s *stubbed) fold(decls []declaration) ir.Property { - merged, diags := s.Merger.fold(decls) + merged, _, diags := s.Merger.fold(decls) *s.recorded = append(*s.recorded, diags...) return merged } -// stubMerger returns a stubbed Merger over reg, and what its folds report. +// stubMerger returns a stubbed Merger over reg, and what its folds report. Its +// alias index and memos read reg live, as a run's read the registry its +// settlement receives. func stubMerger(reg map[ir.TypeID]ir.TypeDef) (*stubbed, *[]ir.Diagnostic) { + return stubMergerOver(reg, stubResolve(reg)) +} + +// stubMergerOver is stubMerger with its alias index and memos built over +// lookup, which a cost test counts. +func stubMergerOver(reg map[ir.TypeID]ir.TypeDef, lookup func(ir.TypeID) (ir.TypeDef, bool)) (*stubbed, *[]ir.Diagnostic) { walk := &stubWalk{reg: reg} recorded := &[]ir.Diagnostic{} - return &stubbed{Reg: reg, Walk: walk, walk: walk, recorded: recorded}, recorded + index := ir.NewAliasChainIndex(lookup) + merger := Merger{Reg: reg, Walk: walk, AliasChainAnswerMemos: NewAliasChainAnswerMemos(lookup, index, walk), + ValueAdmissionReader: NewFoldValueAdmissionReader(lookup, index)} + return &stubbed{Merger: merger, walk: walk, recorded: recorded}, recorded } // stubWalk is the walk a test folds under. Mint registers a node in reg under // composedAt's ID and counts it in minted, Interned answers for the schemas -// interned lists, Alike reads every two sites against one base unless apart -// says they are read apart, and Admits answers untypedAt, exactly. +// interned lists, DeclarationsAdmitAlike reads every two sites against one base unless apart +// says they are read apart, NodesAdmitAlike reads two nodes alike where they encode +// alike but for their sites, Admits answers untypedAt, exactly, IsComposedOf +// answers composedOf where set and reg's composition otherwise, and +// InDiscriminatorHierarchy answers for the declarations hierarchy lists. type stubWalk struct { - reg map[ir.TypeID]ir.TypeDef - interned []jsontext.Pointer - apart bool - minted int - brought map[ir.TypeID][]jsontext.Pointer + reg map[ir.TypeID]ir.TypeDef + composedOf func(id, target ir.TypeID) bool + interned []jsontext.Pointer + hierarchy []jsontext.Pointer + apart bool + // apartAt lists the places a declaration is written apart from every + // other, as apart does everywhere. + apartAt []jsontext.Pointer + alike map[[2]ir.TypeID]bool + minted int + partPointers map[ir.TypeID][]jsontext.Pointer } // Mint is FieldDeclarationContext.Mint. -func (w *stubWalk) Mint(pointer jsontext.Pointer, node ir.TypeDef, brought, _ []jsontext.Pointer) ir.TypeID { +func (w *stubWalk) Mint(pointer jsontext.Pointer, node ir.TypeDef, partPointers, _ []jsontext.Pointer) ir.TypeID { common := node.Common() common.ID = composedAt(pointer) w.reg[common.ID] = node w.minted++ - if w.brought == nil { - w.brought = map[ir.TypeID][]jsontext.Pointer{} + if w.partPointers == nil { + w.partPointers = map[ir.TypeID][]jsontext.Pointer{} } - w.brought[common.ID] = brought + w.partPointers[common.ID] = partPointers return common.ID } +// Primitive is FieldDeclarationContext.Primitive: the primitive of kind, +// registered where the stub holds none. +func (w *stubWalk) Primitive(kind ir.PrimitiveKind) ir.TypeID { + id := ir.PrimitiveTypeID(kind) + if _, held := w.reg[id]; !held { + w.reg[id] = &ir.Primitive{ID: id, PrimitiveKind: kind} + } + return id +} + // Interned is FieldDeclarationContext.Interned. -func (w *stubWalk) Interned(pointer jsontext.Pointer) bool { - return slices.Contains(w.interned, pointer) +func (w *stubWalk) Interned(at ir.Provenance) bool { + return slices.Contains(w.interned, at.Pointer) +} + +// IsComposedOf is FieldDeclarationContext.IsComposedOf: composedOf's answer +// where set, and otherwise whether a path along ir.ComposedOf leads from id to +// target in reg, read to its end. +func (w *stubWalk) IsComposedOf(id, target ir.TypeID) bool { + if w.composedOf != nil { + return w.composedOf(id, target) + } + seen := map[ir.TypeID]bool{id: true} + queue := []ir.TypeID{id} + for len(queue) > 0 { + typeDef, ok := w.reg[queue[len(queue)-1]] + queue = queue[:len(queue)-1] + if !ok { + continue + } + for _, part := range ir.ComposedOf(typeDef) { + if part == target { + return true + } + if !seen[part] { + seen[part] = true + queue = append(queue, part) + } + } + } + return false +} + +// DeclarationsAdmitAlike is FieldDeclarationContext.DeclarationsAdmitAlike: everywhere but where apart or apartAt +// says otherwise. +func (w *stubWalk) DeclarationsAdmitAlike(a, b ir.Provenance) bool { + return !w.apart && !slices.Contains(w.apartAt, a.Pointer) && !slices.Contains(w.apartAt, b.Pointer) } -// Alike is FieldDeclarationContext.Alike. -func (w *stubWalk) Alike(ir.Provenance, ir.Provenance) bool { return !w.apart } +// NodesAdmitAlike is FieldDeclarationContext.NodesAdmitAlike: two nodes reg holds +// encoded alike but for their sites (siteless), or a pair alike lists. +func (w *stubWalk) NodesAdmitAlike(a, b ir.TypeID) bool { + nodeA, heldA := w.reg[a] + nodeB, heldB := w.reg[b] + return w.alike[[2]ir.TypeID{a, b}] || heldA && heldB && reflect.DeepEqual(sitelessNode(nodeA), sitelessNode(nodeB)) +} + +// AnnotationsCarried is FieldDeclarationContext.AnnotationsCarried: kept and +// other admit alike (NodesAdmitAlike), and other's own docs and deprecation say +// nothing or what kept's say. +func (w *stubWalk) AnnotationsCarried(kept, other ir.TypeID) AnnotationCarriage { + type annotations struct { + docs ir.Docs + deprecation *ir.Deprecation + } + of := func(id ir.TypeID) annotations { + node, held := w.reg[id] + if !held { + return annotations{} + } + return annotations{node.Common().Docs, node.Common().Deprecation} + } + others := of(other) + switch { + case !w.NodesAdmitAlike(kept, other): + return TypesAdmitApart + case reflect.DeepEqual(others, annotations{}) || reflect.DeepEqual(of(kept), others): + return AlikeAnnotationsCarried + default: + return AlikeAnnotatedApart + } +} + +// sitelessNode is a copy of node with its TypeCommon siteless. +func sitelessNode(node ir.TypeDef) any { + copied := reflect.New(reflect.TypeOf(node).Elem()) + copied.Elem().Set(reflect.ValueOf(node).Elem()) + typeDef, _ := reflect.TypeAssert[ir.TypeDef](copied) + *typeDef.Common() = siteless(*typeDef.Common()) + return typeDef +} + +// Admits is FieldDeclarationContext.Admits: every instance under /untyped and +// some under /some, exactly, every one inexactly under /loose, and none +// elsewhere, as a structure stating its instance type admits none of another. +func (w *stubWalk) Admits(at ir.Provenance, _ JSONInstanceKind) (admits KindAdmission, exact bool) { + switch { + case untypedAt(at): + return AdmitsEveryOfKind, true + case strings.HasPrefix(string(at.Pointer), "/loose/"): + return AdmitsEveryOfKind, false + case strings.HasPrefix(string(at.Pointer), "/some/"): + return AdmitsSomeOfKind, true + default: + return AdmitsNoneOfKind, true + } +} -// Admits is FieldDeclarationContext.Admits: every kind, exactly, under -// /untyped. -func (w *stubWalk) Admits(at ir.Provenance, _ JSONInstanceKind) (admits, exact bool) { - return untypedAt(at), true +// InDiscriminatorHierarchy is FieldDeclarationContext.InDiscriminatorHierarchy: +// the declarations hierarchy lists take part, and no other. +func (w *stubWalk) InDiscriminatorHierarchy(at ir.Provenance) bool { + return slices.Contains(w.hierarchy, at.Pointer) } // composedAt is the ID stubMerger mints a composition under, for the field the @@ -143,8 +264,8 @@ func mintedProperty(pointer jsontext.Pointer) ir.PropertyID { // foldTwo folds src, rendered by source, into dst, a first declaration // rendered as firstSource: the pair the walk hands over for one redeclared // field. -func foldTwo(stubbedValue *stubbed, dst, src ir.Property, source DeclarationConstructRenderer) ir.Property { - return stubbedValue.fold([]declaration{{property: dst, source: written(firstSource)}, {property: src, source: source}}) +func foldTwo(stubbed *stubbed, dst, src ir.Property, source DeclarationConstructRenderer) ir.Property { + return stubbed.fold([]declaration{{property: dst, source: written(firstSource)}, {property: src, source: source}}) } // firstSource is how foldTwo renders its first declaration. @@ -153,10 +274,10 @@ const firstSource = `{"declared":"first"}` // indexOver returns an index filling model, and settle, which folds what the // index queued through stubbedValue, recording what they report, as Finish // takes the compiler's completions once every lowering has returned. -func indexOver(model *ir.Model, stubbedValue *stubbed) (idx *ModelPropertyDeclarations, settle func()) { +func indexOver(model *ir.Model, stubbed *stubbed) (idx *ModelPropertyDeclarations, settle func()) { idx = NewModelPropertyDeclarations(model) return idx, func() { - *stubbedValue.recorded = append(*stubbedValue.recorded, settleFlat(stubbedValue, idx, stubbedValue.Reg)...) + *stubbed.recorded = append(*stubbed.recorded, settleFlat(stubbed, idx, stubbed.Reg)...) } } @@ -189,7 +310,7 @@ func TestPropertyIndex_ARedeclarationFoldsOnceTheRegistryIsWhole(t *testing.T) { assert.Equal(t, []bool{false, false, true, false, false}, firsts, "one settlement per model, at its first redeclaration, however many fields are redeclared") require.Len(t, model.Properties, 2, "a redeclaration adds no property") - assert.Equal(t, ir.TypeID("type/str"), model.Properties[0].Type.Target, "nothing is folded before the settlement runs") + assert.Equal(t, ir.TypeID("type/str"), model.Properties[0].Type.Target, "nothing is taken into one before the settlement runs") assert.Empty(t, model.Properties[0].Unmodeled) reg["type/uri"] = &ir.Primitive{ID: "type/uri", PrimitiveKind: ir.PrimitiveURL} @@ -202,8 +323,8 @@ func TestPropertyIndex_ARedeclarationFoldsOnceTheRegistryIsWhole(t *testing.T) { require.Len(t, settled, 1) assert.Equal(t, diag.ConflictingRedecl, settled[0].Code) assert.Equal(t, ptrAt("/allOf/2/properties/v").Pointer, settled[0].Provenance.Pointer) - assert.Equal(t, []string{losingDeclarationKey + "/allOf/2/properties/v"}, slices.Sorted(maps.Keys(model.Properties[0].Unmodeled)), - "the losing declaration is kept, and only it") + assert.Equal(t, []string{passedOverDeclarationKey + "/allOf/2/properties/v"}, slices.Sorted(maps.Keys(model.Properties[0].Unmodeled)), + "the passed-over declaration is kept, and only it") assert.Equal(t, ir.TypeID("type/str"), model.Properties[1].Type.Target, "a field declared once is left as declared") } @@ -238,8 +359,8 @@ func TestWireNameIndex_KeysEveryPropertyByItsWireName(t *testing.T) { // TestMergeProperty_AppendsThenFolds pins the two outcomes the entry point // chooses between: a wire name not yet present is appended and indexed, and one -// already present is folded into the property that holds it rather than -// appended beside it. +// already present is taken into the property that holds it rather than appended +// beside it. func TestMergeProperty_AppendsThenFolds(t *testing.T) { t.Parallel() stubbed, recorded := stubMerger(nil) diff --git a/compilers/openapi/internal/merge/models.go b/compilers/openapi/internal/merge/models.go index 1f6163681..ace8810c5 100644 --- a/compilers/openapi/internal/merge/models.go +++ b/compilers/openapi/internal/merge/models.go @@ -20,16 +20,15 @@ const maxModelPairs = 64 // modelPairs is a fresh budget for the model pairs one judgment compares. func modelPairs() *budget.Budget { - b := budget.New(budget.AtMost(maxModelPairs)) - return &b + pairBudget := budget.New(budget.AtMost(maxModelPairs)) + return &pairBudget } // models relates two models alike in everything but where they and the nodes -// they name were declared (modelSkeleton), as the copy rule relates identical -// nodes (sameNodes): where every type one names relates to the other's as the -// same type, or as that rule relates the two models, the one it picks loses -// nothing of the other. Two models declared apart overlap, and so compose. Any -// other pair is unrelated here, as is one past the judgment's budget. +// they name were declared, as the copy rule relates identical nodes, where +// every type one names relates to the other's as the same type or as that rule +// relates the two models. Any other pair is unrelated here, as is one past the +// judgment's budget. func (j typeJudge) models(a ir.TypeRef, am *ir.Model, b ir.TypeRef, bm *ir.Model, depth int) relation { if j.modelPairs == nil || !j.modelPairs.Spend(1) { return relUnrelated @@ -39,36 +38,67 @@ func (j typeJudge) models(a ir.TypeRef, am *ir.Model, b ir.TypeRef, bm *ir.Model if !aok || !bok || as.tag != bs.tag || len(as.refs) != len(bs.refs) || !reflect.DeepEqual(as.model, bs.model) { return relUnrelated } - if (membersKeepReference(am) || membersKeepReference(bm)) && !j.sites.walk.Alike(am.Provenance, bm.Provenance) { + if (membersKeepReference(am) || membersKeepReference(bm)) && !j.sites.walk.DeclarationsAdmitAlike(am.Provenance, bm.Provenance) { return relUnrelated } outer := j.sites.copies(a, am, b, bm) + holds := func(rel relation) bool { return rel == relSame || rel == outer && outer != relUndecided } for i := range as.refs { - rel := j.relateAt(as.refs[i], bs.refs[i], depth+1) - if rel != relSame && (rel != outer || outer == relOverlap) { + if !holds(j.relateAt(as.refs[i], bs.refs[i], depth+1)) { return relUnrelated } } + if !sameSet(j, as.mixins, bs.mixins, holds, depth) { + return relUnrelated + } return outer } +// sameSet reports whether each of as pairs with a distinct one of bs, of one +// null admission, the two related as holds accepts: a model's Mixins compose +// it whatever order they are listed in, so two models composing one set of +// parts are alike (GitHub #2123). The pairing is greedy, which finds one where +// holds reads copies of copies alike. +func sameSet(j typeJudge, as, bs []ir.TypeRef, holds func(relation) bool, depth int) bool { + if len(as) != len(bs) { + return false + } + paired := make([]bool, len(bs)) + for _, a := range as { + k := -1 + for candidate, b := range bs { + if !paired[candidate] && a.Nullable == b.Nullable && holds(j.relateAt(a, b, depth+1)) { + k = candidate + break + } + } + if k < 0 { + return false + } + paired[k] = true + } + return true +} + // skeleton is a model with what names where it and its members were declared // cleared, as siteless clears a node's: its own site, each property's ID and // provenance and those of what it keeps under Unmodeled. Each type it names is -// set apart in refs, in order, with only its target cleared in model, and the -// discriminator's property is read as its position, tag, or -1 where it has -// none. +// set apart in refs, in order, with only its target cleared in model, but its +// Mixins, set apart in mixins and cleared in model, which compose it as a set; +// and the discriminator's property is read as its position, tag, or -1 where +// it has none. type skeleton struct { - model ir.Model - refs []ir.TypeRef - tag int + model ir.Model + refs []ir.TypeRef + mixins []ir.TypeRef + tag int } // modelSkeleton returns model's skeleton, and false where its discriminator // names no property of model. func modelSkeleton(model *ir.Model) (skeleton, bool) { sk := skeleton{model: *model, tag: -1} - take := func(typeRef ir.TypeRef) ir.TypeRef { + extractTarget := func(typeRef ir.TypeRef) ir.TypeRef { sk.refs = append(sk.refs, typeRef) typeRef.Target = "" return typeRef @@ -77,16 +107,16 @@ func modelSkeleton(model *ir.Model) (skeleton, bool) { sk.model.Properties = make([]ir.Property, len(model.Properties)) for i, property := range model.Properties { property.ID, property.Provenance, property.Unmodeled = "", ir.Provenance{}, sitelessUnmodeled(property.Unmodeled) - property.Type = take(property.Type) + property.Type = extractTarget(property.Type) sk.model.Properties[i] = property } if model.Base != nil { - sk.model.Base = new(take(*model.Base)) + sk.model.Base = new(extractTarget(*model.Base)) } - sk.model.Implements = takeAll(model.Implements, take) - sk.model.Mixins = takeAll(model.Mixins, take) + sk.model.Implements = extractTargets(model.Implements, extractTarget) + sk.mixins, sk.model.Mixins = model.Mixins, nil if model.AdditionalProperties != nil { - sk.model.AdditionalProperties = additionalSkeleton(*model.AdditionalProperties, take) + sk.model.AdditionalProperties = additionalSkeleton(*model.AdditionalProperties, extractTarget) } if discriminator := model.Discriminator; discriminator != nil && discriminator.Property != "" { sk.tag = slices.IndexFunc(model.Properties, func(property ir.Property) bool { return property.ID == discriminator.Property }) @@ -100,33 +130,34 @@ func modelSkeleton(model *ir.Model) (skeleton, bool) { return sk, true } -// takeAll applies take to each of refs, in order, into a new slice. -func takeAll(refs []ir.TypeRef, take func(ir.TypeRef) ir.TypeRef) []ir.TypeRef { +// extractTargets applies take to each of refs, in order, into a new slice. +func extractTargets(refs []ir.TypeRef, extractTarget func(ir.TypeRef) ir.TypeRef) []ir.TypeRef { if refs == nil { return nil } out := make([]ir.TypeRef, len(refs)) for i, typeRef := range refs { - out[i] = take(typeRef) + out[i] = extractTarget(typeRef) } return out } // additionalSkeleton is modelSkeleton's reading of a catch-all: each type it -// names, value, key and each pattern's value in that order, taken by take. -func additionalSkeleton(ap ir.AdditionalProperties, take func(ir.TypeRef) ir.TypeRef) *ir.AdditionalProperties { - if ap.Value != nil { - ap.Value = new(take(*ap.Value)) +// names, value, key and each pattern's value in that order, taken by +// extractTarget. +func additionalSkeleton(additional ir.AdditionalProperties, extractTarget func(ir.TypeRef) ir.TypeRef) *ir.AdditionalProperties { + if additional.Value != nil { + additional.Value = new(extractTarget(*additional.Value)) } - if ap.Key != nil { - ap.Key = new(take(*ap.Key)) + if additional.Key != nil { + additional.Key = new(extractTarget(*additional.Key)) } - patterns := slices.Clone(ap.Patterns) + patterns := slices.Clone(additional.Patterns) for i := range patterns { - patterns[i].Value = take(patterns[i].Value) + patterns[i].Value = extractTarget(patterns[i].Value) } - ap.Patterns = patterns - return &ap + additional.Patterns = patterns + return &additional } // sitelessUnmodeled copies um with each entry's provenance cleared, as siteless @@ -136,8 +167,8 @@ func sitelessUnmodeled(um ir.Unmodeled) ir.Unmodeled { } // membersKeepReference reports whether a property of model keeps a reference -// under Unmodeled (keepsReference), which reads as the same text only against -// one base. +// under Unmodeled (keepsReference), which says the same only where what it +// lands on admits alike (FieldDeclarationContext.DeclarationsAdmitAlike). func membersKeepReference(model *ir.Model) bool { return slices.ContainsFunc(model.Properties, func(property ir.Property) bool { return keepsReference(&ir.Scalar{Unmodeled: property.Unmodeled}) diff --git a/compilers/openapi/internal/merge/models_internal_test.go b/compilers/openapi/internal/merge/models_internal_test.go index 347649f7b..334bdfd1f 100644 --- a/compilers/openapi/internal/merge/models_internal_test.go +++ b/compilers/openapi/internal/merge/models_internal_test.go @@ -12,7 +12,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" ) // alikeRegistry holds a component Owner, inline copies of it written at the @@ -89,13 +91,13 @@ func alikeRegistry() map[ir.TypeID]ir.TypeDef { return reg } -// TestTypeJudge_ModelsAlikeAreCopies pins GitHub #1083's verdicts, each in both +// TestTypeJudge_ModelsAlikeAreCopies pins GitHub #1083's answers, each in both // orders: two models alike in every member are judged as two identical nodes // are, a component winning over an inline copy of itself and two inline copies // being one type, where each type they name, a nested object included, is // judged the same way. A model differing in a member, or naming a type that -// relates otherwise, is unrelated, and two components alike overlap where what -// they name is one type, so either composes as two models do. +// relates otherwise, is unrelated, and two components alike are one type too, +// declared apart, where what they name is one type, nested objects included. func TestTypeJudge_ModelsAlikeAreCopies(t *testing.T) { t.Parallel() reg := alikeRegistry() @@ -107,8 +109,8 @@ func TestTypeJudge_ModelsAlikeAreCopies(t *testing.T) { {"a component, then an inline copy", "type/Owner", "type/copy1", firstTypeIsNarrower}, {"an inline copy, then a component", "type/copy0", "type/Owner", secondTypeIsNarrower}, {"two inline copies", "type/copy0", "type/copy1", relSame}, - {"two components alike, naming one nested type", "type/Home", "type/House", relOverlap}, - {"two components alike, each nesting its own object", "type/Owner", "type/Twin", relUnrelated}, + {"two components alike, naming one nested type", "type/Home", "type/House", relSame}, + {"two components alike, each nesting its own object", "type/Owner", "type/Twin", relSame}, {"a copy naming a component where the other names a copy", "type/copy0", "type/copy1-addr", relUnrelated}, {"a copy with one more property", "type/copy0", "type/copy1-more", relUnrelated}, {"a copy requiring a property the other does not", "type/copy0", "type/copy1-required", relUnrelated}, @@ -122,13 +124,13 @@ func TestTypeJudge_ModelsAlikeAreCopies(t *testing.T) { {"two copies whose catch-alls differ", "type/copy0-open", "type/copy1-open-other", relUnrelated}, } { for i, order := range [][2]ir.TypeID{{tc.a, tc.b}, {tc.b, tc.a}} { - typeJudgeValue := typeJudge{resolve: stubResolve(reg), sites: declarationSites{ + typeJudge := typeJudge{resolve: stubResolve(reg), sites: declarationSites{ walk: &stubWalk{}, written: [2][]ir.Provenance{sitesAt(declaredAt(i)), sitesAt(declaredAt(1 - i))}}} want := tc.want if i == 1 { want = want.flipped() } - assert.Equal(t, want, typeJudgeValue.relate(ref(order[0]), ref(order[1])), "%s (order %d)", tc.name, i) + assert.Equal(t, want, typeJudge.relate(ref(order[0]), ref(order[1])), "%s (order %d)", tc.name, i) } } } @@ -147,16 +149,18 @@ func TestTypeJudge_ModelsKeepingAReferenceAreAlikeUnderOneBase(t *testing.T) { {false, relSame}, {true, relUnrelated}, } { - typeJudgeValue := typeJudge{resolve: stubResolve(reg), sites: declarationSites{ + typeJudge := typeJudge{resolve: stubResolve(reg), sites: declarationSites{ walk: &stubWalk{apart: tc.apart}, written: [2][]ir.Provenance{sitesAt(declaredAt(0)), sitesAt(declaredAt(1))}}} - assert.Equal(t, tc.want, typeJudgeValue.relate(ref("type/copy0-ref"), ref("type/copy1-ref"))) + assert.Equal(t, tc.want, typeJudge.relate(ref("type/copy0-ref"), ref("type/copy1-ref"))) } } // TestFold_ModelsAlikeAreOneType pins what a field declared as alike models // takes: the component over an inline copy of it, whichever comes first, and the -// first of two inline copies, with nothing kept or reported. Two components -// alike still compose. +// first of two inline copies, with nothing kept or reported. Of two components +// alike it takes the least, whichever comes first, and keeps the declaration +// naming the other verbatim with an info, one whose source will not render +// reported as such, and one another model brings left declared there. func TestFold_ModelsAlikeAreOneType(t *testing.T) { t.Parallel() for _, tc := range []struct { @@ -167,7 +171,6 @@ func TestFold_ModelsAlikeAreOneType(t *testing.T) { {"a component, then a copy", []ir.TypeID{"type/Owner", "type/copy1"}, "type/Owner"}, {"a copy, then a component", []ir.TypeID{"type/copy0", "type/Owner"}, "type/Owner"}, {"two copies", []ir.TypeID{"type/copy0", "type/copy1"}, "type/copy0"}, - {"two components", []ir.TypeID{"type/Owner", "type/Twin"}, composedAt(declaredAt(1))}, } { reg := alikeRegistry() stubbed, recorded := stubMerger(reg) @@ -182,6 +185,36 @@ func TestFold_ModelsAlikeAreOneType(t *testing.T) { assert.Empty(t, *recorded, tc.name) assert.Empty(t, got.Unmodeled, tc.name) } + + for _, tc := range []struct { + name string + targets []ir.TypeID + set func(twin *declaration) + codes []string + kept int + }{ + {"the least first", []ir.TypeID{"type/Owner", "type/Twin"}, nil, []string{diag.DegradedConstruct}, 1}, + {"the least last", []ir.TypeID{"type/Twin", "type/Owner"}, nil, []string{diag.DegradedConstruct}, 1}, + {"a source that will not render", []ir.TypeID{"type/Owner", "type/Twin"}, func(twin *declaration) { twin.source = nil }, + []string{diag.UnpreservableConstruct, diag.DegradedConstruct}, 0}, + {"another model's declaration", []ir.TypeID{"type/Owner", "type/Twin"}, + func(twin *declaration) { twin.via = &composedEntry{target: "type/other", at: "/other"} }, []string{}, 0}, + } { + stubbed, recorded := stubMerger(alikeRegistry()) + decls := declsOf(tc.targets...) + for i := range decls { + decls[i].source = written(`{"$ref":"t"}`) + if tc.targets[i] == "type/Twin" && tc.set != nil { + tc.set(&decls[i]) + } + } + + got := stubbed.fold(decls) + + assert.Equal(t, ir.TypeID("type/Owner"), got.Type.Target, "%s: two components alike are one type, the least", tc.name) + assert.Equal(t, tc.codes, irtest.DiagCodes(*recorded), tc.name) + assert.Len(t, got.Unmodeled, tc.kept, "%s: the declaration naming Twin is kept verbatim", tc.name) + } } // TestTypeJudge_ModelPairsStopAtTheirBudget pins maxModelPairs from both sides: @@ -203,14 +236,14 @@ func TestTypeJudge_ModelPairsStopAtTheirBudget(t *testing.T) { } reg[outer.ID] = outer } - typeJudgeValue := typeJudge{resolve: stubResolve(reg), sites: declarationSites{ + typeJudge := typeJudge{resolve: stubResolve(reg), sites: declarationSites{ walk: &stubWalk{}, written: [2][]ir.Provenance{sitesAt(declaredAt(0)), sitesAt(declaredAt(1))}}} want := relSame if nested == maxModelPairs { want = relUnrelated } - assert.Equal(t, want, typeJudgeValue.relate(ref("type/0"), ref("type/1")), "%d nested pairs", nested) + assert.Equal(t, want, typeJudge.relate(ref("type/0"), ref("type/1")), "%d nested pairs", nested) } } @@ -236,17 +269,37 @@ func TestTypeJudge_NestedModelsCostTheirBudgetNotTheirWidthToTheDepth(t *testing reg[leaf] = &ir.Primitive{ID: leaf, PrimitiveKind: ir.PrimitiveString} } reads := 0 - typeJudgeValue := typeJudge{ + typeJudge := typeJudge{ resolve: func(id ir.TypeID) (ir.TypeDef, bool) { reads++ - td, ok := reg[id] - return td, ok + typeDef, ok := reg[id] + return typeDef, ok }, sites: declarationSites{written: [2][]ir.Provenance{sitesAt(declaredAt(0)), sitesAt(declaredAt(1))}, walk: &stubWalk{}}, } - rel := typeJudgeValue.relate(ref("type/0/0"), ref("type/1/0")) + rel := typeJudge.relate(ref("type/0/0"), ref("type/1/0")) require.Equal(t, relUnrelated, rel, "past the budget the two are unrelated") assert.LessOrEqual(t, reads, 4*maxModelPairs*width, "the reads grow with the budget, not with the width to the depth") } + +// TestTypeJudge_NodesTheWalkShowsAlikeAreCopies pins the judgment's last +// resort: two nodes no rule relates, a copy and one with one more property, +// are copies, by the rule sameNodes states, where the walk shows the two +// admit alike (FieldDeclarationContext.NodesAdmitAlike), here two inline copies, +// one type; where it does not, they stay unrelated. +func TestTypeJudge_NodesTheWalkShowsAlikeAreCopies(t *testing.T) { + t.Parallel() + reg := alikeRegistry() + for alike, want := range map[bool]relation{true: relSame, false: relUnrelated} { + walk := &stubWalk{alike: map[[2]ir.TypeID]bool{}} + if alike { + walk.alike[[2]ir.TypeID{"type/copy0", "type/copy1-more"}] = true + } + typeJudge := typeJudge{resolve: stubResolve(reg), sites: declarationSites{ + walk: walk, written: [2][]ir.Provenance{sitesAt(declaredAt(0)), sitesAt(declaredAt(1))}}} + + assert.Equal(t, want, typeJudge.relate(ir.TypeRef{Target: "type/copy0"}, ir.TypeRef{Target: "type/copy1-more"}), "alike %t", alike) + } +} diff --git a/compilers/openapi/internal/merge/multiple.go b/compilers/openapi/internal/merge/multiple.go deleted file mode 100644 index 6aeba8ee3..000000000 --- a/compilers/openapi/internal/merge/multiple.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "math/big" - "strconv" - - "github.com/dexpace/morphic/ir" -) - -// stepFactorsPerDigit bounds the powers of two and of five in a step's -// coefficient: a number of n decimal digits has fewer than 4n of either. -const stepFactorsPerDigit = 4 - -// isMultipleOf reports whether decimal is an integral multiple of irDecimal, -// exactly. Read decimal as vc·10^vl and irDecimal as mc·10^ml: the coefficients -// are the digits, and vl and ml the exponents of their last digits. -// -// If vl < ml, decimal is never a multiple, since mc·10^(ml−vl) divides vc only -// if 10 divides vc, and it does not. Otherwise decimal is a multiple iff mc -// divides vc·10^k, with k = min(vl−ml, 4·len(irDecimal.Digits())): mc's powers -// of 2 and 5 are each below 4 per digit, and the cofactor coprime to 10 is -// unaffected by the shift. ok is false only for a zero step, which divides -// nothing. -func isMultipleOf(decimal, irDecimal ir.Decimal) (multiple, ok bool) { - if irDecimal.Sign() == 0 { - return false, false - } - if decimal.Sign() == 0 { - return true, true - } - shift := lowestExponent(decimal) - lowestExponent(irDecimal) - if shift < 0 { - return false, true - } - k := min(shift, int64(stepFactorsPerDigit*len(irDecimal.Digits()))) - return new(big.Int).Rem(scaled(decimal, k), coefficient(irDecimal)).Sign() == 0, true -} - -// maxStepDigits bounds the significant digits of the two steps commonStep folds -// (styleguide bounded-everything rule): the cost of their common multiple grows -// with the square of them, and a step of this many digits is no step a document -// means. Past it the two are reported and kept, as a keyword with no order is. -const maxStepDigits = 1024 - -// commonStep returns the step whose multiples are exactly the multiples of both -// bigVal and irBigVal: one literal written twice, whichever of them is a -// multiple of the other, or else their least common multiple, a number neither -// wrote. It returns false where no such step can be read: a literal no Decimal -// holds, a step that is not positive, a pair past maxStepDigits, or a multiple -// past what a Decimal holds. -func commonStep(bigVal, irBigVal ir.BigVal) (ir.BigVal, bool) { - if bigVal == irBigVal { - return bigVal, true - } - a, errA := bigVal.Decimal() - b, errB := irBigVal.Decimal() - if errA != nil || errB != nil || a.Sign() <= 0 || b.Sign() <= 0 || len(a.Digits())+len(b.Digits()) > maxStepDigits { - return "", false - } - if multiple, ok := isMultipleOf(a, b); ok && multiple { - return bigVal, true - } - if multiple, ok := isMultipleOf(b, a); ok && multiple { - return irBigVal, true - } - lcm, err := ir.NewBigVal(leastCommonMultiple(a, b)) - return lcm, err == nil -} - -// leastCommonMultiple spells the least common multiple of two positive numbers. -// Read each as a coefficient and the exponent of its last digit, and count both -// in units of the lower exponent: a's coefficient grows by 10^shift. Past the -// powers of 2 and 5 in b's coefficient, fewer than 4 per digit, a further power -// of ten only scales the result, so k of them are multiplied out and the other -// shift-k stay in the exponent, which keeps a wide shift from being built. -func leastCommonMultiple(a, b ir.Decimal) string { - if lowestExponent(a) < lowestExponent(b) { - a, b = b, a - } - shift := lowestExponent(a) - lowestExponent(b) - k := min(shift, int64(stepFactorsPerDigit*len(b.Digits()))) - x, y := scaled(a, k), coefficient(b) - gcd := new(big.Int).GCD(nil, nil, x, y) - lcm := x.Mul(x.Quo(x, gcd), y).String() - if exp := lowestExponent(a) - k; exp != 0 { - lcm += "e" + strconv.FormatInt(exp, 10) - } - return lcm -} - -// scaled returns decimal's coefficient times 10^k. -func scaled(decimal ir.Decimal, k int64) *big.Int { - c := coefficient(decimal) - return c.Mul(c, new(big.Int).Exp(big.NewInt(10), big.NewInt(k), nil)) -} - -// coefficient returns decimal's significant digits as an integer. -func coefficient(decimal ir.Decimal) *big.Int { - c, _ := new(big.Int).SetString(decimal.Digits(), 10) // Digits is a digit run, by Decimal's invariant - return c -} - -// lowestExponent returns the power of ten decimal's last significant digit -// carries. decimal is not zero, and the result stays inside int64 because -// Decimal bounds the leading digit's exponent by ir.MaxDecimalExp. -func lowestExponent(decimal ir.Decimal) int64 { - return decimal.Exponent() - int64(len(decimal.Digits())) + 1 -} diff --git a/compilers/openapi/internal/merge/multiple_internal_test.go b/compilers/openapi/internal/merge/multiple_internal_test.go deleted file mode 100644 index 0b7692712..000000000 --- a/compilers/openapi/internal/merge/multiple_internal_test.go +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package merge - -import ( - "fmt" - "math/big" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/dexpace/morphic/ir" -) - -// TestIsMultipleOf_JudgesExactly pins the multipleOf judgment the merge holds a -// value to. Each row is one a float division gets wrong, or one where no answer -// is claimed: a decimal step float64 cannot hold, values far apart in scale, -// magnitudes no rational builds, steps whose powers of two and five outrun the -// shift, and the one pair ok refuses, a zero step. -func TestIsMultipleOf_JudgesExactly(t *testing.T) { - t.Parallel() - tests := []struct { - name string - v, m string - multiple, ok bool - }{ - {"an integer multiple", "10", "5", true, true}, - {"an integer that is not one", "7", "2", false, true}, - {"a decimal step float64 cannot hold", "0.3", "0.1", true, true}, - {"a last digit finer than the step's", "0.35", "0.1", false, true}, - {"a fraction against an integral step", "2.5", "2", false, true}, - {"a fraction against a fractional step", "2.5", "0.5", true, true}, - {"zero, a multiple of anything", "0", "3", true, true}, - {"a negative multiple", "-6", "3", true, true}, - {"the step's sign does not matter", "6", "-3", true, true}, - {"a step larger than the value", "2", "5", false, true}, - {"magnitudes far apart", "1e100", "5", true, true}, - {"a step far below the value", "1", "1e-100", true, true}, - {"magnitudes past what a rational builds", "1e5000", "2", true, true}, - {"a value far above a step it is not a multiple of", "1e1000001", "3", false, true}, - {"a value at the top of the range", "1e999999999999999999", "2", true, true}, - {"a value and step at the bottom of the range", "3e-999999999999999999", "1e-999999999999999999", true, true}, - {"a value below its step's lowest digit", "1e-999999999999999999", "1", false, true}, - {"a power of two the shift covers", "1e3", "8", true, true}, - {"a power of two the shift falls short of", "1e2", "8", false, true}, - {"a coefficient's own powers of two and five", "5e10", "1024", true, true}, - {"one power of two short", "5e9", "1024", false, true}, - {"a shift past the cap", "1e100", "1125899906842624", true, true}, - {"a shift under the cap, one power short", "1e49", "1125899906842624", false, true}, - {"a zero step, which divides nothing", "4", "0", false, false}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - decimal, err := ir.ParseDecimal(tc.v) - require.NoError(t, err, "%q is a decimal in range", tc.v) - irDecimal, err := ir.ParseDecimal(tc.m) - require.NoError(t, err, "%q is a decimal in range", tc.m) - - multiple, ok := isMultipleOf(decimal, irDecimal) - - assert.Equal(t, tc.ok, ok) - assert.Equal(t, tc.multiple, multiple) - }) - } -} - -// TestCommonStep_HoldsTheMultiplesOfBoth pins the step two multipleOf keywords -// make together. A step that is a multiple of the other is that step, as written. -// Otherwise it is their least common multiple, which the rows check by magnitude -// in both orders, some of them at scales no rational builds, where the fold must -// not multiply the shift out. -func TestCommonStep_HoldsTheMultiplesOfBoth(t *testing.T) { - t.Parallel() - tests := []struct { - name string - x, y ir.BigVal - want ir.BigVal - }{ - {"one step", "3", "3", "3"}, - {"one step spelled two ways", "10", "1e1", "10"}, - {"a multiple of the other", "6", "2", "6"}, - {"a decimal multiple of the other", "0.25", "0.01", "0.25"}, - {"two primes", "3", "5", "15"}, - {"sharing a factor", "4", "6", "12"}, - {"two decimals", "0.4", "0.6", "1.2"}, - {"a decimal beside an integer", "0.4", "3", "6"}, - {"trailing zeros on one side", "30", "4", "60"}, - {"a shift past the cap", "3e100", "7", "21e100"}, - {"a shift past the cap, with powers of two to cover", "3e100", "7168", "21e100"}, - {"a shift past what a rational builds", "3e1000001", "7", "21e1000001"}, - {"far below one", "3e-1000001", "7e-1000002", "21e-1000001"}, - {"far apart around one", "3e1000001", "7e-1000001", "21e1000001"}, - {"at the bottom of the range", "3e-999999999999999999", "7e-999999999999999999", "21e-999999999999999999"}, - {"a shift no integer could hold", "3e999999999999999998", "7e-999999999999999999", "21e999999999999999998"}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - for _, pair := range [][2]ir.BigVal{{tc.x, tc.y}, {tc.y, tc.x}} { - got, ok := commonStep(pair[0], pair[1]) - require.True(t, ok, "%s and %s", pair[0], pair[1]) - assert.True(t, sameNumber(tc.want, got), "%s and %s make %s, not %s", pair[0], pair[1], tc.want, got) - } - }) - } -} - -// TestCommonStep_KeepsTheStepItChoseAsWritten pins that a step the other divides -// is the literal a declaration wrote, so only a number no declaration wrote is -// spelled by the merge. -func TestCommonStep_KeepsTheStepItChoseAsWritten(t *testing.T) { - t.Parallel() - for _, pair := range [][2]ir.BigVal{{"6.0", "2"}, {"2", "6.0"}} { - got, ok := commonStep(pair[0], pair[1]) - require.True(t, ok) - assert.Equal(t, ir.BigVal("6.0"), got) - } -} - -// TestCommonStep_MatchesTheIntegerLeastCommonMultiple holds the decimal reading -// to integers it can be computed from: every pair of small coefficients at every -// pair of small scales, multiplied up to integers and compared with math/big. -func TestCommonStep_MatchesTheIntegerLeastCommonMultiple(t *testing.T) { - t.Parallel() - for a := int64(1); a <= 36; a++ { - for b := int64(1); b <= 36; b++ { - for _, scale := range [][2]int{{0, 0}, {0, 2}, {2, 0}, {-2, 1}, {1, -2}, {-1, -1}} { - bigVal := ir.BigVal(fmt.Sprintf("%de%d", a, scale[0])) - irBigVal := ir.BigVal(fmt.Sprintf("%de%d", b, scale[1])) - want := wholeMultiple(a, scale[0], b, scale[1]) - - got, ok := commonStep(bigVal, irBigVal) - - require.True(t, ok, "%s and %s", bigVal, irBigVal) - assert.True(t, sameNumber(want, got), "%s and %s make %s, not %s", bigVal, irBigVal, want, got) - } - } - } -} - -// wholeMultiple is the least common multiple of a·10^ae and b·10^be, computed -// over integers scaled up past both exponents. -func wholeMultiple(a int64, ae int, b int64, be int) ir.BigVal { - const unit = 3 // past every scale the caller uses - scaleUp := func(v int64, e int) *big.Int { - return new(big.Int).Mul(big.NewInt(v), new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(e+unit)), nil)) - } - x, y := scaleUp(a, ae), scaleUp(b, be) - gcd := new(big.Int).GCD(nil, nil, x, y) - lcm := new(big.Int).Mul(new(big.Int).Quo(x, gcd), y) - return ir.BigVal(fmt.Sprintf("%se-%d", lcm, unit)) -} - -// TestCommonStep_RefusesWhatItCannotRead pins each pair that has no common step -// to report: the merge keeps the first and reports the other, rather than folding -// two values into one the source never wrote. The digit bound is held at the -// limit and one past it. -func TestCommonStep_RefusesWhatItCannotRead(t *testing.T) { - t.Parallel() - digits := func(n int) ir.BigVal { return ir.BigVal(strings.Repeat("3", n)) } - for _, tc := range []struct { - name string - x, y ir.BigVal - ok bool - }{ - {name: "one literal twice, though no Decimal holds it", x: "nan", y: "nan", ok: true}, - {name: "a literal no Decimal holds", x: "nan", y: "2"}, - {name: "a zero step", x: "0", y: "2"}, - {name: "a negative step", x: "-3", y: "2"}, - {name: "digits at the bound", x: digits(maxStepDigits - 1), y: "7", ok: true}, - {name: "digits past the bound", x: digits(maxStepDigits), y: "7"}, - {name: "a multiple past what a Decimal holds", x: "9e999999999999999999", y: "7"}, - } { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - for _, pair := range [][2]ir.BigVal{{tc.x, tc.y}, {tc.y, tc.x}} { - _, ok := commonStep(pair[0], pair[1]) - assert.Equal(t, tc.ok, ok, "%.40s and %.40s", pair[0], pair[1]) - } - }) - } -} diff --git a/compilers/openapi/internal/merge/once.go b/compilers/openapi/internal/merge/once.go index d02e00695..a5b9bcb04 100644 --- a/compilers/openapi/internal/merge/once.go +++ b/compilers/openapi/internal/merge/once.go @@ -8,70 +8,109 @@ import ( "slices" "strings" - "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) -// ReportOnce returns diags, a run's settlement reports, with each conflict -// between two declarations said once, where it is first. Every model composing -// both draws it alike, at the declaration that lost (folding.disagree), but for -// the member each decided (naming, deciding). One said for several models -// names how many and no member beside its place, as it decided one at each, -// and lists them all among what it concerns, in ascending order of their IDs, -// so no order the models settled in shows. Every other report stays, in order. -// It reuses diags' array. -func ReportOnce(diags []ir.Diagnostic) []ir.Diagnostic { - said := map[ir.DiagnosticKey]*conflict{} - for _, diagnostic := range diags { - if diagnostic.Code != diag.ConflictingRedecl { - continue - } - key := unnamed(diagnostic).Key() - conflictValue := said[key] - if conflictValue == nil { - conflictValue = &conflict{} - said[key] = conflictValue - } - conflictValue.models++ - conflictValue.decided = append(conflictValue.decided, decided(diagnostic)...) - } - if len(said) == 0 { - return diags - } +// ReportOnce returns diags, a run's findings after pruning, with each member +// fold report, one listing a member it decided (ir.RelatedDecided), held to +// types, the pruned registry, and said once. A decided entry naming a member +// no model holds goes, and so does a report left deciding none, unless an +// error. Reports alike but for what they decided are one, where the first is, +// naming every model holding the field and listing every member by ascending +// ID, so no order the models settled in shows. It reuses diags' array. +func ReportOnce(diags []ir.Diagnostic, types ir.TypeRegistry, sources []ir.SourceInfo) []ir.Diagnostic { + var held map[string]string + said := map[ir.DiagnosticKey]*foldReport{} out := diags[:0] for _, diagnostic := range diags { - if diagnostic.Code != diag.ConflictingRedecl { + if !slices.ContainsFunc(diagnostic.Related, isDecided) { out = append(out, diagnostic) continue } - bare := unnamed(diagnostic) - conflict, first := said[bare.Key()] - if !first { + if held == nil { + held = heldMembers(types) + } + members := slices.DeleteFunc(decided(diagnostic), func(related ir.Related) bool { + _, isHeld := held[related.Provenance.Node] + return !isHeld + }) + if len(members) == 0 && diagnostic.Severity != ir.SeverityError { continue } - delete(said, bare.Key()) - if conflict.models > 1 { - diagnostic = bare - diagnostic.Message += fmt.Sprintf("; the same holds at each of %d models composing both", conflict.models) - slices.SortFunc(conflict.decided, func(a, b ir.Related) int { return strings.Compare(a.Provenance.Node, b.Provenance.Node) }) - diagnostic.Related = append(diagnostic.Related, conflict.decided...) + bare := undecided(diagnostic) + if report, seen := said[bare.Key()]; seen { + report.decided = append(report.decided, members...) + continue } - out = append(out, diagnostic) + said[bare.Key()] = &foldReport{at: len(out), decided: members} + out = append(out, bare) + } + for _, report := range said { + out[report.at] = report.withMembersListed(out[report.at], held, sources) } return out } -// conflict is one conflict as every model composing its two declarations -// draws it: how many did, and the member each decided. -type conflict struct { - models int +// foldReport is one report of the member fold as every model drawing it says +// it: where it sits in the reports kept, and each member it decided. +type foldReport struct { + at int decided []ir.Related } -// unnamed is diagnostic naming no member, beside its place or among what it -// concerns: what every model composing the two declarations says alike. -func unnamed(diagnostic ir.Diagnostic) ir.Diagnostic { - diagnostic.Provenance.Node = "" +// withMembersListed is bare, a report deciding none, listing each member report +// decided once, sorted by ID, and naming the field as "field %q of" each model +// holding one. A fold report opens with the field, which the models follow; +// one that does not, as an error keeping a declaration verbatim, follows them. +func (report *foldReport) withMembersListed(bare ir.Diagnostic, held map[string]string, sources []ir.SourceInfo) ir.Diagnostic { + slices.SortFunc(report.decided, func(a, b ir.Related) int { return strings.Compare(a.Provenance.Node, b.Provenance.Node) }) + report.decided = slices.CompactFunc(report.decided, func(a, b ir.Related) bool { return a.Provenance.Node == b.Provenance.Node }) + if len(report.decided) > 0 { + subject := fmt.Sprintf("field %q", held[report.decided[0].Provenance.Node]) + rest, opens := strings.CutPrefix(bare.Message, subject) + if !opens { + rest = ": " + bare.Message + } + bare.Message = subject + " of " + modelsNamed(report.decided, bare.Provenance.Source, sources) + rest + } + bare.Related = append(bare.Related, report.decided...) + return bare +} + +// modelsNamed names the model each of decided says declares its member, by +// its place, as a report written in the document in names it. Each is named +// once, in written order, so no order the models settled in shows. +func modelsNamed(decided []ir.Related, in int, sources []ir.SourceInfo) string { + places := make([]ir.Provenance, len(decided)) + for i, related := range decided { + places[i] = ir.Provenance{Source: related.Provenance.Source, Pointer: related.Provenance.Pointer} + } + slices.SortFunc(places, compareSourceOrder) + places = slices.Compact(places) + names := make([]string, len(places)) + for i, place := range places { + names[i] = placeName(sources, place, in) + } + return listed(names) +} + +// heldMembers is the wire name of each member the models of types declare, +// by ID. +func heldMembers(types ir.TypeRegistry) map[string]string { + held := map[string]string{} + for _, typeDef := range types { + if model, isModel := typeDef.(*ir.Model); isModel && model != nil { + for _, property := range model.Properties { + held[string(property.ID)] = property.WireName + } + } + } + return held +} + +// undecided is diagnostic listing no member it decided: what every model +// drawing it says alike. +func undecided(diagnostic ir.Diagnostic) ir.Diagnostic { diagnostic.Related = slices.DeleteFunc(slices.Clone(diagnostic.Related), isDecided) return diagnostic } diff --git a/compilers/openapi/internal/merge/once_internal_test.go b/compilers/openapi/internal/merge/once_internal_test.go index 9334d4f7c..75658a315 100644 --- a/compilers/openapi/internal/merge/once_internal_test.go +++ b/compilers/openapi/internal/merge/once_internal_test.go @@ -5,78 +5,196 @@ package merge import ( "encoding/json/jsontext" + "path" + "slices" + "strconv" + "strings" "testing" "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/ir" ) -// TestReportOnce_SaysEachConflictOnce pins what a run's settlement reports: -// a conflict drawn alike at several models, but for the member each names, -// is said once, where it is first, with how many and no member; one drawn at -// one model keeps its member; two differing in what they say or where they -// sit are two; and every other report stays as it is, in order, repeats too. -// A report said for several lists the member each decided, in ascending order -// whatever order the models came in, after what all of them kept, and two -// keeping different declarations are two. -func TestReportOnce_SaysEachConflictOnce(t *testing.T) { +// TestReportOnce_SaysEachFoldReportOnce pins what a run's member fold reports +// once pruning is done: reports alike but for the members they decided are +// said once, where the first is, naming the field and each model holding a +// member, and listing every member once, in ascending order; two differing in +// what they say, where they sit or what they kept are two; a decided entry +// naming no member held goes, and so does a report left deciding none, but an +// error, kept naming no model; and every report deciding nothing stays, in +// order. +func TestReportOnce_SaysEachFoldReportOnce(t *testing.T) { t.Parallel() - conflict := func(source int, node, message string) ir.Diagnostic { + types := ir.TypeRegistry{"type/M": &ir.Model{ID: "type/M", Properties: []ir.Property{{ID: "property/M", WireName: "p"}, {ID: "property/N", WireName: "p"}}}, + "type/O": &ir.Model{ID: "type/O", Properties: []ir.Property{{ID: "property/O", WireName: "p"}}}, "type/S": &ir.Scalar{ID: "type/S"}} + const ( + x = `: /K and /C/properties/p disagree: conflicting maximum (1 and 2)` + y = `: /K and /C/properties/p give its default differently` + r = `: the merge cannot show that the type its declarations merge to admits the default /C/properties/p gives` + ) + field := func(models, rest string) string { return `field "p"` + models + rest } + conflict := func(source int, message string) ir.Diagnostic { return ir.Diagnostic{Severity: ir.SeverityWarning, Code: diag.ConflictingRedecl, Message: message, - Provenance: ir.Provenance{Source: source, Pointer: "/C/properties/p", Node: node}} + Provenance: ir.Provenance{Source: source, Pointer: "/C/properties/p"}} } other := ir.Diagnostic{Severity: ir.SeverityInfo, Code: diag.DegradedConstruct, Message: "o", Provenance: ir.Provenance{Pointer: "/M/allOf/0", Node: "property/M"}} + refusal := func(message string, decided ...string) ir.Diagnostic { + diagnostic := concerning(ir.Diagnostic{Severity: ir.SeverityInfo, Code: diag.DegradedConstruct, Message: message, + Provenance: ir.Provenance{Pointer: "/C/properties/p"}}, "", decided...) + diagnostic.Related = diagnostic.Related[1:] + return diagnostic + } + budgetError := func(message string, decided ...string) ir.Diagnostic { + diagnostic := concerning(ir.Diagnostic{Severity: ir.SeverityError, Code: diag.BudgetExceeded, Message: message, + Provenance: ir.Provenance{Pointer: "/C/properties/p"}}, "", decided...) + diagnostic.Related = diagnostic.Related[1:] + return diagnostic + } for name, tc := range map[string]struct{ in, want []ir.Diagnostic }{ "none": {in: []ir.Diagnostic{other, other}, want: []ir.Diagnostic{other, other}}, "one model": { - in: []ir.Diagnostic{conflict(0, "property/M", "x")}, - want: []ir.Diagnostic{conflict(0, "property/M", "x")}, + in: []ir.Diagnostic{concerning(conflict(0, field("", x)), "/K", "property/M")}, + want: []ir.Diagnostic{concerning(conflict(0, field(" of /M", x)), "/K", "property/M")}, }, - "three models": { - in: []ir.Diagnostic{other, conflict(0, "property/M", "x"), other, conflict(0, "property/N", "x"), conflict(0, "property/O", "x")}, - want: []ir.Diagnostic{other, conflict(0, "", "x; the same holds at each of 3 models composing both"), - other}, + "three models, listed in order": { + in: []ir.Diagnostic{other, concerning(conflict(0, field("", x)), "/K", "property/O"), other, + concerning(conflict(0, field("", x)), "/K", "property/M"), concerning(conflict(0, field("", x)), "/K", "property/N")}, + want: []ir.Diagnostic{other, concerning(conflict(0, field(" of /M, /N and /O", x)), "/K", + "property/M", "property/N", "property/O"), other}, }, "what they say differs": { - in: []ir.Diagnostic{conflict(0, "property/M", "x"), conflict(0, "property/N", "y")}, - want: []ir.Diagnostic{conflict(0, "property/M", "x"), conflict(0, "property/N", "y")}, + in: []ir.Diagnostic{concerning(conflict(0, field("", x)), "/K", "property/M"), concerning(conflict(0, field("", y)), "/K", "property/N")}, + want: []ir.Diagnostic{concerning(conflict(0, field(" of /M", x)), "/K", "property/M"), + concerning(conflict(0, field(" of /N", y)), "/K", "property/N")}, }, "where they sit differs": { - in: []ir.Diagnostic{conflict(0, "property/M", "x"), conflict(1, "property/N", "x")}, - want: []ir.Diagnostic{conflict(0, "property/M", "x"), conflict(1, "property/N", "x")}, + in: []ir.Diagnostic{concerning(conflict(0, field("", x)), "/K", "property/M"), concerning(conflict(1, field("", x)), "/K", "property/N")}, + want: []ir.Diagnostic{concerning(conflict(0, field(" of /M", x)), "/K", "property/M"), + concerning(conflict(1, field(" of /N in a.yaml", x)), "/K", "property/N")}, }, - "the members each decided are listed in order": { - in: []ir.Diagnostic{ - concerning(conflict(0, "property/N", "x"), "/K", "property/N"), other, concerning(conflict(0, "property/M", "x"), "/K", "property/M"), - }, - want: []ir.Diagnostic{ - concerning(conflict(0, "", "x; the same holds at each of 2 models composing both"), "/K", "property/M", "property/N"), other, - }, + "what they kept differs": { + in: []ir.Diagnostic{concerning(conflict(0, field("", x)), "/K", "property/M"), concerning(conflict(0, field("", x)), "/L", "property/N")}, + want: []ir.Diagnostic{concerning(conflict(0, field(" of /M", x)), "/K", "property/M"), + concerning(conflict(0, field(" of /N", x)), "/L", "property/N")}, }, - "one model keeps the member it lists": { - in: []ir.Diagnostic{concerning(conflict(0, "property/M", "x"), "/K", "property/M")}, - want: []ir.Diagnostic{concerning(conflict(0, "property/M", "x"), "/K", "property/M")}, + "one member decided twice": { + in: []ir.Diagnostic{concerning(conflict(0, field("", x)), "/K", "property/M"), concerning(conflict(0, field("", x)), "/K", "property/M")}, + want: []ir.Diagnostic{concerning(conflict(0, field(" of /M", x)), "/K", "property/M")}, }, - "what they kept differs": { - in: []ir.Diagnostic{concerning(conflict(0, "property/M", "x"), "/K", "property/M"), concerning(conflict(0, "property/N", "x"), "/L", "property/N")}, - want: []ir.Diagnostic{concerning(conflict(0, "property/M", "x"), "/K", "property/M"), concerning(conflict(0, "property/N", "x"), "/L", "property/N")}, + "a member pruning removed": { + in: []ir.Diagnostic{concerning(conflict(0, field("", x)), "/K", "property/Gone"), concerning(conflict(0, field("", x)), "/K", "property/M"), + concerning(conflict(0, field("", x)), "/K", "property/N")}, + want: []ir.Diagnostic{concerning(conflict(0, field(" of /M and /N", x)), "/K", "property/M", "property/N")}, + }, + "a report deciding only what no model holds": { + in: []ir.Diagnostic{concerning(conflict(0, field("", x)), "/K", "property/Gone", "type/S"), other}, + want: []ir.Diagnostic{other}, + }, + "an error deciding only what no model holds": { + in: []ir.Diagnostic{budgetError("b", "property/Gone", "type/S"), other}, + want: []ir.Diagnostic{budgetError("b"), other}, + }, + "a report not opening with the field": { + in: []ir.Diagnostic{budgetError("b", "property/N"), budgetError("b", "property/M")}, + want: []ir.Diagnostic{budgetError(field(" of /M and /N", ": b"), "property/M", "property/N")}, + }, + "a report about one declaration": { + in: []ir.Diagnostic{refusal(field("", r), "property/N"), refusal(field("", r), "property/M")}, + want: []ir.Diagnostic{refusal(field(" of /M and /N", r), "property/M", "property/N")}, }, } { - if diff := cmp.Diff(tc.want, ReportOnce(tc.in)); diff != "" { + if diff := cmp.Diff(tc.want, ReportOnce(tc.in, types, []ir.SourceInfo{{Path: "a.yaml"}, {Path: "b.yaml"}})); diff != "" { t.Errorf("%s (-want +got):\n%s", name, diff) } } } +// TestReportOnce_NamesEachModelOnceByItsPlace pins how a report said once names +// the models holding its members: by their places, in the documents' order and +// then the pointers', whatever order their IDs list them in, each place once, +// though two models sit at it, and one in another document than the report's +// with that document's name. +func TestReportOnce_NamesEachModelOnceByItsPlace(t *testing.T) { + t.Parallel() + types := ir.TypeRegistry{"type/M": &ir.Model{ID: "type/M", Properties: []ir.Property{ + {ID: "property/A", WireName: "p"}, {ID: "property/B", WireName: "p"}, {ID: "property/C", WireName: "p"}, {ID: "property/D", WireName: "p"}, + }}} + report := ir.Diagnostic{Severity: ir.SeverityWarning, Code: diag.ConflictingRedecl, Message: `field "p": x`, + Provenance: ir.Provenance{Source: 0, Pointer: "/C/properties/p"}} + decided := func(node string, source int, pointer jsontext.Pointer) ir.Diagnostic { + diagnostic := report + diagnostic.Related = []ir.Related{{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: source, Pointer: pointer, Node: node}}} + return diagnostic + } + + got := ReportOnce([]ir.Diagnostic{decided("property/A", 1, "/Y"), decided("property/B", 0, "/Z"), decided("property/C", 0, "/Y"), + decided("property/D", 0, "/Y")}, types, []ir.SourceInfo{{Path: "a.yaml"}, {Path: "b.yaml"}}) + + require.Len(t, got, 1) + assert.Equal(t, `field "p" of /Y, /Z and /Y in b.yaml: x`, got[0].Message) +} + // concerning is diagnostic concerning the declaration kept at kept and the -// members decided, in the order a fold and ReportOnce list them. +// members decided, in the order a fold and ReportOnce list them, each at the +// place of a model named for it, property/M's at /M. func concerning(diagnostic ir.Diagnostic, kept jsontext.Pointer, decided ...string) ir.Diagnostic { - diagnostic.Related = []ir.Related{{Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: kept}}} + diagnostic.Related = []ir.Related{{Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: kept}}} for _, node := range decided { - diagnostic.Related = append(diagnostic.Related, ir.Related{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: node}}) + model := jsontext.Pointer("/" + path.Base(node)) + diagnostic.Related = append(diagnostic.Related, ir.Related{Role: ir.RelatedDecided, Provenance: ir.Provenance{Pointer: model, Node: node}}) } return diagnostic } + +// TestReportOnce_NamesTheFieldAMergedReportIsAbout pins how a report said once +// for two models names what they compose: by the field and the two models, +// whatever number of declarations it is about, so a budget report leaving one +// declaration unjudged, one leaving two and a disjoint-visibility report +// naming two all open alike. Each report is the fold's own, listed as deciding +// a member of each model. +func TestReportOnce_NamesTheFieldAMergedReportIsAbout(t *testing.T) { + t.Parallel() + types := ir.TypeRegistry{"type/M": &ir.Model{ID: "type/M", Properties: []ir.Property{{ID: "property/M", WireName: "data"}, {ID: "property/N", WireName: "data"}}}} + pastTheBound := func(unjudged int) []declaration { + decls := make([]declaration, 0, maxFoldDeclarations+unjudged) + for range maxFoldDeclarations { + decls = append(decls, declaration{property: declared("data", "type/primitive/string", "/A/data"), source: written(`{}`)}) + } + for i := range unjudged { + at := "/U" + strconv.Itoa(i) + "/data" + decls = append(decls, declaration{property: declared("data", "type/primitive/string", at), source: written(`{}`)}) + } + return decls + } + restricted := func(at string, lifecycle ir.Lifecycle) declaration { + property := declared("data", "type/primitive/string", at) + property.Visibility = ir.Visibility{Only: []ir.Lifecycle{lifecycle}} + return declaration{property: property, source: written(`{}`)} + } + for name, tc := range map[string]struct { + decls []declaration + code string + }{ + "a budget report leaving one declaration unjudged": {decls: pastTheBound(1), code: diag.BudgetExceeded}, + "a budget report leaving two unjudged": {decls: pastTheBound(2), code: diag.BudgetExceeded}, + "a disjoint-visibility report naming two declarations": {decls: []declaration{restricted("/A/data", ir.LifecycleRead), + restricted("/B/data", ir.LifecycleCreate)}, code: diag.DisjointVisibility}, + } { + stubbed, _ := stubMerger(membersRegistry()) + _, _, diags := stubbed.foldAt(tc.decls, "/M/allOf/properties/data", nil) + reports := slices.DeleteFunc(diags, func(diagnostic ir.Diagnostic) bool { return diagnostic.Code != tc.code }) + require.Len(t, reports, 1, name) + reports[0].Related = slices.Clip(reports[0].Related) + + got := ReportOnce(slices.Concat(deciding(slices.Clone(reports), "property/M", ptrAt("/M")), + deciding(slices.Clone(reports), "property/N", ptrAt("/N"))), types, nil) + + require.Len(t, got, 1, name) + assert.True(t, strings.HasPrefix(got[0].Message, `field "data" of /M and /N`), "%s: %s", name, got[0].Message) + } +} diff --git a/compilers/openapi/internal/merge/losers.go b/compilers/openapi/internal/merge/passedover.go similarity index 66% rename from compilers/openapi/internal/merge/losers.go rename to compilers/openapi/internal/merge/passedover.go index 3936f2876..f80ead3c8 100644 --- a/compilers/openapi/internal/merge/losers.go +++ b/compilers/openapi/internal/merge/passedover.go @@ -11,35 +11,41 @@ import ( "github.com/dexpace/morphic/ir" ) -// losingDeclarationKey prefixes the Unmodeled entry a redeclaration the merge could not +// passedOverDeclarationKey prefixes the Unmodeled entry a redeclaration the merge could not // fold whole is kept under. The "openapi:" namespace is what keeps two source // formats' keys from colliding on one node (docs/ir/unmodeled.md#keys); the // redeclaration's own pointer completes it, the way an allOf entry's index // completes the composition's keys. -const losingDeclarationKey = "openapi:conflicting-redeclaration" +const passedOverDeclarationKey = "openapi:conflicting-redeclaration" // errNoSource is why a declaration that must be kept verbatim cannot be: no // Source was recorded for it. var errNoSource = errors.New("no source was recorded for the declaration") -// keepLosingDeclaration keeps the declaration at loser verbatim under +// keepPassedOverDeclaration keeps the declaration at passedOver verbatim under // Unmodeled beside the merged property, so a document consumer sees what the // merge did not carry (GitHub #424). // // The value is the construct source renders, not the dropped IR values (GitHub // #445): Unmodeled holds what the document wrote (docs/ir/unmodeled.md), and a -// TypeID in a byte slice is invisible to irverify. The key ends in loser's +// TypeID in a byte slice is invisible to irverify. The key ends in passedOver's // pointer, so each declaration keeps its own entry. // -// A declaration with no pointer is skipped, since PreserveInto overwrites a +// A declaration with no pointer is skipped, since KeepInto overwrites a // collapsed key; no production path produces one. A source that will not // render is reported as an error (GitHub #144). -func (g *Merger) keepLosingDeclaration(dst *ir.Property, loser ir.Provenance, source DeclarationConstructRenderer) []ir.Diagnostic { - pointer := loser.Pointer - if pointer == "" { +func (g *Merger) keepPassedOverDeclaration(dst *ir.Property, passedOver ir.Provenance, source DeclarationConstructRenderer) []ir.Diagnostic { + if passedOver.Pointer == "" { return nil } - key := losingDeclarationKey + string(pointer) + return g.keepVerbatim(&dst.Unmodeled, passedOverDeclarationKey+string(passedOver.Pointer), passedOver, source) +} + +// keepVerbatim keeps the declaration at passedOver, rendered by source, +// verbatim under key in dst, and reports, as an error, a source that will not +// render (keepPassedOverDeclaration). +func (g *Merger) keepVerbatim(dst *ir.Unmodeled, key string, passedOver ir.Provenance, source DeclarationConstructRenderer) []ir.Diagnostic { + pointer := passedOver.Pointer raw, err := render(source) if err != nil { at := g.Doc.At(pointer) @@ -53,8 +59,7 @@ func (g *Merger) keepLosingDeclaration(dst *ir.Property, loser ir.Provenance, so // Degraded lowering (docs/ir/boundaries.md#degraded-constructs, // docs/compilers/openapi.md#allof-redeclared-property): the IR has no // combinator for two shapes or two defaults at one position. - annotation.PreserveInto(&dst.Unmodeled, key, raw, - ir.ReasonDegradedLowering, loser) + annotation.KeepInto(dst, key, raw, ir.ReasonDegradedLowering, passedOver) return nil } diff --git a/compilers/openapi/internal/merge/losers_internal_test.go b/compilers/openapi/internal/merge/passedover_internal_test.go similarity index 84% rename from compilers/openapi/internal/merge/losers_internal_test.go rename to compilers/openapi/internal/merge/passedover_internal_test.go index 7af8fb32c..f826d1e6d 100644 --- a/compilers/openapi/internal/merge/losers_internal_test.go +++ b/compilers/openapi/internal/merge/passedover_internal_test.go @@ -13,10 +13,10 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestKeepLosingDeclaration_RecordsTheDiscardedDeclaration pins what the fix for -// GitHub #424 adds: the redeclaration whose type loses is kept verbatim beside -// the winner, so a consumer reading the document — not the diagnostic stream — -// still sees what the second declaration said. +// TestKeepLosingDeclaration_RecordsTheDiscardedDeclaration pins what the fix +// for GitHub #424 adds: the redeclaration whose type loses is kept verbatim +// beside the chosen declaration, so a consumer reading the document — not the +// diagnostic stream — still sees what the second declaration said. // // The reference is asserted whole rather than by its target alone: Nullable is // half of what a redeclaration says about a field, and an entry that kept only @@ -27,37 +27,37 @@ func TestKeepLosingDeclaration_RecordsTheDiscardedDeclaration(t *testing.T) { "type/str": &ir.Primitive{ID: "type/str", PrimitiveKind: ir.PrimitiveString}, "type/int": &ir.Primitive{ID: "type/int", PrimitiveKind: ir.PrimitiveInt32}, }) - loser := ir.Property{ + passedOver := ir.Property{ WireName: "id", Type: ir.TypeRef{Target: "type/int", Nullable: true}, Provenance: ir.Provenance{Source: 2, Pointer: "/components/schemas/S/allOf/0/properties/id"}, } - winner := ir.Property{ + chosen := ir.Property{ WireName: "id", Type: ir.TypeRef{Target: "type/str"}, Provenance: ir.Provenance{Source: 2, Pointer: "/components/schemas/S/allOf/1/properties/id"}, } - dst := stubbed.fold([]declaration{{property: loser, source: written(`{"type":"integer","nullable":true}`)}, {property: winner, source: unread(t)}}) + dst := stubbed.fold([]declaration{{property: passedOver, source: written(`{"type":"integer","nullable":true}`)}, {property: chosen, source: unread(t)}}) require.Len(t, *recorded, 1, "the conflict is still diagnosed") assert.Equal(t, ir.TypeID("type/str"), dst.Type.Target, "the later declaration wins the shape") key := "openapi:conflicting-redeclaration/components/schemas/S/allOf/0/properties/id" entry, ok := dst.Unmodeled[key] - require.True(t, ok, "the losing declaration is kept under a pointer-namespaced key; got %v", dst.Unmodeled) + require.True(t, ok, "the passed-over declaration is kept under a pointer-namespaced key; got %v", dst.Unmodeled) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) assert.JSONEq(t, `{"type":"integer","nullable":true}`, string(entry.Value), "the declaration is kept as the document wrote it, nullability included") assert.Equal(t, ir.Provenance{Source: 2, Pointer: "/components/schemas/S/allOf/0/properties/id"}, - entry.Provenance, "the entry locates the losing declaration, not the merged property") + entry.Provenance, "the entry locates the passed-over declaration, not the merged property") } -// TestKeepLosingDeclaration_EveryLoserSurvivesItsSiblings pins the key's namespacing. -// A field three entries type three incompatible ways discards two -// declarations, and a fixed key would leave only whichever entry ran last — -// the same silent overwrite the entry exists to prevent. -func TestKeepLosingDeclaration_EveryLoserSurvivesItsSiblings(t *testing.T) { +// TestKeepPassedOverDeclaration_EveryPassedOverDeclarationSurvivesItsSiblings pins the key's +// namespacing. A field three entries type three incompatible ways discards two +// declarations, and a fixed key would leave only whichever entry ran last — the +// same unreported overwrite the entry exists to prevent. +func TestKeepPassedOverDeclaration_EveryPassedOverDeclarationSurvivesItsSiblings(t *testing.T) { t.Parallel() reg := map[ir.TypeID]ir.TypeDef{ "type/str": &ir.Primitive{ID: "type/str", PrimitiveKind: ir.PrimitiveString}, diff --git a/compilers/openapi/internal/merge/position.go b/compilers/openapi/internal/merge/position.go index 28d7c84a2..0d912e281 100644 --- a/compilers/openapi/internal/merge/position.go +++ b/compilers/openapi/internal/merge/position.go @@ -13,112 +13,145 @@ import ( // type, or what a container that declaration's type names holds there. type member struct { ref ir.TypeRef - decl int + decl declarationIndex } // position is the members at one position of a field, every pair judged once: -// the one holding the most (winner) and those the field composes, judged alike +// the one holding the most (chosen member) and those the field composes, judged alike // for the field's own types and for what their containers hold. type position struct { members []member // rel[i][j] is the judgment of members[i]'s type against members[j]'s. rel [][]relation - // winner is the member whose type holds the most members' types. - winner int + // written is where each member's target node is written, the zero + // provenance for one the registry does not hold (compareTargets). + written []ir.Provenance + // chosen is the member whose type holds the most members' types. + chosen int // conjuncts are the members the position composes (composition), or none. conjuncts []conjunct } // judgePosition judges ms, members of decls at depth, against each other, each -// pair at the sites its two declarations were written, and picks the winner +// pair at the sites its two declarations were written, and picks the chosen member // (widestCone) and the conjuncts (composition). func (g *Merger) judgePosition(decls []declaration, ms []member, depth int) position { - n := len(ms) - positionValue := position{members: ms, rel: make([][]relation, n)} - for i := range n { - positionValue.rel[i] = make([]relation, n) - positionValue.rel[i][i] = relSame + memberCount := len(ms) + position := position{members: ms, rel: make([][]relation, memberCount), written: make([]ir.Provenance, memberCount)} + for i := range memberCount { + position.rel[i] = make([]relation, memberCount) + position.rel[i][i] = relSame + if typeDef, ok := g.resolve(ms[i].ref.Target); ok { + position.written[i] = typeDef.Common().Provenance + } } sites := make([][]ir.Provenance, len(decls)) for _, member := range ms { sites[member.decl] = decls[member.decl].sites() } - for i := range n { - for j := i + 1; j < n; j++ { + for i := range memberCount { + for j := i + 1; j < memberCount; j++ { judge := g.judgeAt(sites[ms[i].decl], sites[ms[j].decl]) rel := judge.relateFrom(ms[i].ref, ms[j].ref, depth) - positionValue.rel[i][j], positionValue.rel[j][i] = rel, rel.flipped() + position.rel[i][j], position.rel[j][i] = rel, rel.flipped() } } - positionValue.winner = positionValue.widestCone() - positionValue.conjuncts = positionValue.composition(registry{g.resolve}) - return positionValue + position.chosen = position.widestCone() + position.conjuncts = position.composition(g.registryReader()) + return position } -// holds reports whether member i's type is the same as member j's or narrower, -// or meets it: a type of member i's, with what a meeting adds, loses nothing -// member j says of its type. -func (p position) holds(i, j int) bool { - return p.rel[i][j] == relSame || p.rel[i][j] == firstTypeIsNarrower || p.rel[i][j] == relMeet +// subsumes reports whether member i's type is the same as member j's, +// narrower, or intersects it, so a type of member i's, with what an +// intersection adds, loses nothing member j says of its type. +func (p position) subsumes(i, j int) bool { + return p.rel[i][j] == relSame || p.rel[i][j] == firstTypeIsNarrower || p.rel[i][j] == relIntersect } // widestCone returns the member whose type holds the most members' types: of -// those holding as many, the one standing for its type (stands), and of -// different types the last, where a spec writes the specialization. Where one -// type is within every other, it is the intersection and wins whatever the -// order; where types meet, each holds the other, and the winner's node takes -// what each it meets adds (builder). Otherwise the position keeps the type that -// loses the fewest members, and each it loses is reported. +// those holding as many, the one representing its type (represents), and of +// different types the last, where a spec writes the specialization. Of the +// chosen member's copies the least wins (leastOfItsCopies), so no order of +// them decides which node the field names. func (p position) widestCone() int { best, widest := 0, 0 for i := range p.members { width := 0 for j := range p.members { - if p.holds(i, j) { + if p.subsumes(i, j) { width++ } } - if width > widest || (width == widest && (p.rel[i][best] != relSame || p.stands(i, best))) { + if width > widest || (width == widest && (p.rel[i][best] != relSame || p.represents(i, best))) { best, widest = i, width } } + return p.leastOfItsCopies(best) +} + +// leastOfItsCopies returns, of member chosen and every member whose type is +// the same as its, the one representing the rest (represents), which a tie in +// widestCone may have passed over where a copy came before a member of another +// type it then lost to. +func (p position) leastOfItsCopies(chosen int) int { + best := chosen + for k := range p.members { + if p.rel[chosen][k] == relSame && p.compareTargets(k, best) < 0 { + best = k + } + } return best } -// stands reports whether member i stands for member j, the two of one type: the -// one whose target sorts first, so no declaration order decides which node the -// field names, else the later. -func (p position) stands(i, j int) bool { - if a, b := p.members[i].ref.Target, p.members[j].ref.Target; a != b { - return a < b +// represents reports whether member i is the one member j, of one type with +// it, is read as: the one whose target is the least (compareTargets), so no +// declaration order decides which node the field names, else the later. +func (p position) represents(i, j int) bool { + if order := p.compareTargets(i, j); order != 0 { + return order < 0 } return i > j } -// meeting returns the winner and each other member of the cone whose type -// meets its (relMeet), the members a node holding them all is built of, the -// later first: what two give differently is the first's (builder.adoptInto). -func (p position) meeting(cone func(k int) bool) (member, []member) { +// compareTargets orders the targets of members i and j as a fold names the +// least of nodes alike (compareWrittenTargets), zero where they name one. +func (p position) compareTargets(i, j int) int { + a, b := p.members[i].ref.Target, p.members[j].ref.Target + if a == b { + return 0 + } + return compareWrittenTargets(a, p.written[i], b, p.written[j]) +} + +// intersecting returns the chosen member and each other member of the cone +// whose type intersects its, or is a copy of it whose node nothing else holds +// (unheldCopy), the later first: the members a node holding them all is built +// of. A copy differing in its notes alone gives them to that node, so no note +// is lost. +func (p position) intersecting(cone, unheldCopy func(k int) bool) (member, []member) { var partners []member for k, member := range slices.Backward(p.members) { - if k != p.winner && cone(k) && p.rel[p.winner][k] == relMeet { + if k == p.chosen || !cone(k) { + continue + } + if rel := p.rel[p.chosen][k]; rel == relIntersect || rel == relSame && member.ref.Target != p.members[p.chosen].ref.Target && unheldCopy(k) { partners = append(partners, member) } } - return p.members[p.winner], partners + return p.members[p.chosen], partners } // null is what null the type of the members cone keeps admits: where every one -// of them does (intersectNull), as foldNullVerdicts states for a single schema. -// The top type admits null whatever its bit says, so a member of it below a -// winner of another type says nothing of null. -func (p position) null(reg registry, cone func(k int) bool, depth int) ir.TypeRef { +// of them does (intersectNull). The top type admits null whatever its bit +// says, so a member of it below a chosen member of another type says nothing +// of null. +func (p position) null(reg registryReader, cone func(k int) bool, depth int) ir.TypeRef { var merged ir.TypeRef seeded := false for k, member := range p.members { switch { case !cone(k): - case p.rel[p.winner][k] != relSame && targetsTop(reg, member.ref, depth): + case p.rel[p.chosen][k] != relSame && targetsTop(reg, member.ref, depth): case !seeded: merged, seeded = member.ref, true default: @@ -130,7 +163,7 @@ func (p position) null(reg registry, cone func(k int) bool, depth int) ir.TypeRe // targetsTop reports whether ref, a member's type at depth, targets the // schemaless top type as the judgment reads one (registry.topAt). -func targetsTop(reg registry, ref ir.TypeRef, depth int) bool { - td, ok := reg.resolve(ref.Target) - return ok && reg.topAt(td, depth) +func targetsTop(reg registryReader, ref ir.TypeRef, depth int) bool { + typeDef, ok := reg.resolve(ref.Target) + return ok && reg.topAt(typeDef, depth) } diff --git a/compilers/openapi/internal/merge/related_internal_test.go b/compilers/openapi/internal/merge/related_internal_test.go index 924181b33..e956b5478 100644 --- a/compilers/openapi/internal/merge/related_internal_test.go +++ b/compilers/openapi/internal/merge/related_internal_test.go @@ -44,14 +44,15 @@ func ownAt(wire string, target ir.TypeID, n string) func(idx *ModelPropertyDecla } } -// TestReportOnce_AConflictListsWhatItKeptAndThenWhatItDecided holds the order +// TestReportOnce_AConflictListsWhatItChoseAndThenWhatItDecided holds the order // this compiler gives a conflict report's related entries, which the IR leaves -// to the producer (docs/ir/provenance.md#related-places): exactly one kept -// place, first, then every member the report decided, ascending by ID, however -// the declarations meet: two or three, a $ref chain, a model's own declaration -// against an entry's, one model or five settled out of order, two members of -// one pair, and a model composing one that settled the pair. -func TestReportOnce_AConflictListsWhatItKeptAndThenWhatItDecided(t *testing.T) { +// to the producer (docs/ir/provenance.md#related-places): exactly one chosen +// place, first, then every member the report decided, ascending by ID, each at +// the place of the model declaring it, however the declarations intersect: two or +// three, a $ref chain, a model's own declaration against an entry's, one model +// or five settled out of order, two members of one pair, and a model composing +// one that settled the pair. +func TestReportOnce_AConflictListsWhatItChoseAndThenWhatItDecided(t *testing.T) { t.Parallel() registry := func() ir.TypeRegistry { reg := membersRegistry() @@ -112,19 +113,23 @@ func TestReportOnce_AConflictListsWhatItKeptAndThenWhatItDecided(t *testing.T) { reports: 2, decided: []int{1, 1}, }, } { - got := ReportOnce(tc.settle(registry())) + reg := registry() + got := ReportOnce(tc.settle(reg), reg, nil) var counts []int for _, diagnostic := range got { require.Equal(t, diag.ConflictingRedecl, diagnostic.Code, name) require.NotEmpty(t, diagnostic.Related, name) - assert.Equal(t, ir.RelatedKept, diagnostic.Related[0].Role, "%s: the kept place comes first", name) + assert.Equal(t, ir.RelatedChosen, diagnostic.Related[0].Role, "%s: the kept place comes first", name) assert.NotEmpty(t, diagnostic.Related[0].Provenance.Pointer, "%s: the kept place is a declaration's", name) decided := diagnostic.Related[1:] nodes := make([]string, len(decided)) for i, related := range decided { assert.Equal(t, ir.RelatedDecided, related.Role, "%s: one kept place, then the members decided", name) - assert.Equal(t, ir.Provenance{Source: ir.NoSource, Node: related.Provenance.Node}, related.Provenance, name) + model := declaringModel(reg, related.Provenance.Node) + require.NotNil(t, model, "%s: %s is a member a model declares", name, related.Provenance.Node) + assert.Equal(t, ir.Provenance{Source: model.Provenance.Source, Pointer: model.Provenance.Pointer, Node: related.Provenance.Node}, + related.Provenance, name) nodes[i] = related.Provenance.Node } assert.True(t, slices.IsSorted(nodes), "%s: the members ascend by ID: %v", name, nodes) @@ -135,3 +140,14 @@ func TestReportOnce_AConflictListsWhatItKeptAndThenWhatItDecided(t *testing.T) { assert.Equal(t, tc.decided, counts, name) } } + +// declaringModel is the model of reg declaring the member node names, or nil. +func declaringModel(reg ir.TypeRegistry, node string) *ir.Model { + for _, typeDef := range reg { + model, isModel := typeDef.(*ir.Model) + if isModel && slices.ContainsFunc(model.Properties, func(property ir.Property) bool { return string(property.ID) == node }) { + return model + } + } + return nil +} diff --git a/compilers/openapi/internal/merge/reportwords.go b/compilers/openapi/internal/merge/reportwords.go new file mode 100644 index 000000000..f4d12745b --- /dev/null +++ b/compilers/openapi/internal/merge/reportwords.go @@ -0,0 +1,90 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "fmt" + "strconv" + "strings" + + "github.com/dexpace/morphic/ir" +) + +// aboutPair is the message of a report at decls[passedOver], written at +// passedOverAt, about a field it and the declaration written at chosenPlace +// give otherwise. It names no model: every model composing the two draws it +// alike, and the run names them as it says it once (ReportOnce). +func aboutPair(fieldFold *fieldFold, passedOver declarationIndex, passedOverAt, chosenPlace ir.Provenance, gives, chosenWhat string) string { + return fmt.Sprintf("field %q: %s and %s %s; chose %s; the second %s", fieldFold.merged.WireName, + placeName(fieldFold.g.Sources, chosenPlace, passedOverAt.Source), placeName(fieldFold.g.Sources, passedOverAt, passedOverAt.Source), gives, chosenWhat, + fieldFold.decls[passedOver].keptAs()) +} + +// listed joins names as a sentence lists them: "A", "A and B", "A, B and C". +func listed(names []string) string { + if len(names) < 2 { + return strings.Join(names, "") + } + return strings.Join(names[:len(names)-1], ", ") + " and " + names[len(names)-1] +} + +// typeNamed is how a report names the type id refers to, as an author wrote +// it, never by its ID, which no author wrote and pruning may remove: by its +// source name, or else by that of its alias chain's end, or else by that end's +// kind in words. +func typeNamed(reg registryReader, id ir.TypeID) string { + typeDef, held := reg.resolve(id) + if !held || ir.IsNilTypeDef(typeDef) { + return "a type" + } + if name, named := sourceNamed(typeDef); named { + return name + } + end := reg.unaliased(typeDef) + if name, named := sourceNamed(end); named { + return name + } + return kindInWords(end) +} + +// sourceNamed returns the name a report gives typeDef where it has one: a +// primitive's kind, as `string`, or, quoted, the name the source gives a type +// it declares. An anonymous type has none. +func sourceNamed(typeDef ir.TypeDef) (string, bool) { + if primitive, isPrimitive := typeDef.(*ir.Primitive); isPrimitive { + return string(primitive.PrimitiveKind), true + } + typeCommon := typeDef.Common() + if typeCommon.Anonymous || typeCommon.Name.Source == "" { + return "", false + } + return strconv.Quote(typeCommon.Name.Source), true +} + +// kindInWords names an anonymous type by its kind, as a reader of the schema +// would. +func kindInWords(typeDef ir.TypeDef) string { + switch typeDef.(type) { + case *ir.Model: + return "an object" + case *ir.MapT: + return "a map" + case *ir.List: + return "a list" + case *ir.Tuple: + return "a tuple" + case *ir.Union: + return "a union" + case *ir.Enum: + return "an enum" + case *ir.Literal: + return "a constant" + case *ir.External: + return "an external type" + case *ir.Any: + return "any value" + default: + return "a scalar" + } +} diff --git a/compilers/openapi/internal/merge/reportwords_internal_test.go b/compilers/openapi/internal/merge/reportwords_internal_test.go new file mode 100644 index 000000000..ba24f07a8 --- /dev/null +++ b/compilers/openapi/internal/merge/reportwords_internal_test.go @@ -0,0 +1,85 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestTypeNamed_NamesATypeAsItsAuthorWroteIt pins how a report names a type: +// by the name its source gives it, quoted; a primitive by its kind; an alias +// by what its chain ends in; any other anonymous type, or one whose source +// gives no name, by its kind in words; and one the registry does not hold as +// a type, never by an ID. +func TestTypeNamed_NamesATypeAsItsAuthorWroteIt(t *testing.T) { + t.Parallel() + anonymous := ir.TypeCommon{Anonymous: true} + reg := ir.TypeRegistry{ + "type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}, + "type/pet": &ir.Model{ID: "type/pet", Name: ir.Naming{Source: "Pet"}}, + "type/unnamed": &ir.Model{ID: "type/unnamed"}, + "type/object": &ir.Model{TypeCommon: anonymous}, + "type/map": &ir.MapT{TypeCommon: anonymous}, + "type/list": &ir.List{TypeCommon: anonymous}, + "type/tuple": &ir.Tuple{TypeCommon: anonymous}, + "type/union": &ir.Union{TypeCommon: anonymous}, + "type/enum": &ir.Enum{TypeCommon: anonymous}, + "type/literal": &ir.Literal{TypeCommon: anonymous}, + "type/external": &ir.External{TypeCommon: anonymous}, + "type/any": &ir.Any{TypeCommon: anonymous}, + "type/opaque": &ir.Scalar{TypeCommon: anonymous}, + "type/to-pet": &ir.Scalar{ID: "type/to-pet", Anonymous: true, Base: &ir.TypeRef{Target: "type/pet"}}, + "type/short": &ir.Scalar{ID: "type/short", Anonymous: true, Base: &ir.TypeRef{Target: "type/primitive/string"}}, + "type/to-list": &ir.Scalar{ID: "type/to-list", Anonymous: true, Base: &ir.TypeRef{Target: "type/list"}}, + } + stubbed, _ := stubMerger(reg) + for id, want := range map[ir.TypeID]string{ + "type/primitive/string": "string", + "type/pet": `"Pet"`, + "type/unnamed": "an object", + "type/object": "an object", + "type/map": "a map", + "type/list": "a list", + "type/tuple": "a tuple", + "type/union": "a union", + "type/enum": "an enum", + "type/literal": "a constant", + "type/external": "an external type", + "type/any": "any value", + "type/opaque": "a scalar", + "type/to-pet": `"Pet"`, + "type/short": "string", + "type/to-list": "a list", + "type/missing": "a type", + } { + assert.Equal(t, want, typeNamed(stubbed.registryReader(), id), "%s", id) + } +} + +// TestPlaceName_NamesADocumentsRootByTheDocument pins how a report names a +// place: by its pointer where it is in the report's document or in none the +// sources list, followed by its document's name where it is in another, and a +// document's root, which the empty pointer names, by that name alone, or as +// the document root in the report's own. +func TestPlaceName_NamesADocumentsRootByTheDocument(t *testing.T) { + t.Parallel() + sources := []ir.SourceInfo{{Path: "root.yaml"}, {Path: "pet.yaml"}} + for _, tc := range []struct { + place ir.Provenance + want string + }{ + {ir.Provenance{Source: 0, Pointer: "/components/schemas/B"}, "/components/schemas/B"}, + {ir.Provenance{Source: 1, Pointer: "/components/schemas/B"}, "/components/schemas/B in pet.yaml"}, + {ir.Provenance{Source: 0}, "the document root"}, + {ir.Provenance{Source: 1}, "pet.yaml"}, + {ir.Provenance{Source: 5, Pointer: "/B"}, "/B"}, + {ir.Provenance{Source: ir.NoSource}, "the document root"}, + } { + assert.Equal(t, tc.want, placeName(sources, tc.place, 0), "%+v", tc.place) + } +} diff --git a/compilers/openapi/internal/merge/topalias.go b/compilers/openapi/internal/merge/topalias.go new file mode 100644 index 000000000..0f82a43d1 --- /dev/null +++ b/compilers/openapi/internal/merge/topalias.go @@ -0,0 +1,56 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "github.com/dexpace/morphic/ir" +) + +// topAliasAgainstKind relates typeDef, written at sites and read as tdKind, to +// a type whose values are instances of kind, where typeDef is an alias of the +// top type: by what its source and each alias below it admit +// (instanceRelation), otherWhole saying the other type holds every instance of +// kind. It reads nothing for another typeDef. +func topAliasAgainstKind(j typeJudge, typeDef ir.TypeDef, tdKind valueKind, sites []ir.Provenance, depth int, + kind JSONInstanceKind, otherWhole bool, +) (relation, bool) { + scalar, alias := typeDef.(*ir.Scalar) + if !alias || scalar.Base == nil || tdKind.primitive != ir.PrimitiveAny { + return relUnrelated, false + } + below, read := j.registryReader.chainAnswerMemos(j.sites.walk).admissionOf(kind).AnswerFor(scalar.Base.Target) + if !read { + return relUnrelated, false + } + own, exact := sourceAdmission(j.sites.walk, scalar.Provenance, kind) + saysNothing := below.saysNothing && replacedLosesNothing(scalar, depth == 0 && !hoistedAt(typeDef, sites)) + return instanceRelation(own, exact, below, saysNothing, otherWhole), true +} + +// topAliasAgainstKindNode relates at and bt, two types ending in kinds, ak and +// bk, one of them the top type (classify), as topAliasAgainstKind judges the +// alias of it against the other's kind; unrelated where it reads nothing. +func topAliasAgainstKindNode(j typeJudge, at ir.TypeDef, ak valueKind, aSites []ir.Provenance, bt ir.TypeDef, bk valueKind, + bSites []ir.Provenance, depth int, +) relation { + if ak.primitive == ir.PrimitiveAny { + rel, _ := topAliasAgainstKind(j, at, ak, aSites, depth, primitiveInstance(bk.primitive), coversItsInstanceKind(bt)) + return rel + } + rel, _ := topAliasAgainstKind(j, bt, bk, bSites, depth, primitiveInstance(ak.primitive), coversItsInstanceKind(at)) + return rel.flipped() +} + +// replacedLosesNothing reports whether a type replacing scalar, an alias of the +// top type whose source admits every value of that type, loses nothing it +// says. What a node declared apart keeps verbatim, which the walk read whole, +// it keeps where it sits. +func replacedLosesNothing(scalar *ir.Scalar, carried bool) bool { + if !scalar.Anonymous { + bare := *scalar + bare.Unmodeled = nil + scalar = &bare + } + return aliasAddsNothingBeyondBase(scalar) || carried && aliasAddsNothingBeyondItsUse(scalar) +} diff --git a/compilers/openapi/internal/merge/topalias_internal_test.go b/compilers/openapi/internal/merge/topalias_internal_test.go new file mode 100644 index 000000000..a08705a56 --- /dev/null +++ b/compilers/openapi/internal/merge/topalias_internal_test.go @@ -0,0 +1,119 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestTypeJudge_AnAliasOfTheTopTypeIsJudgedByWhatItsSourceAdmits pins an +// alias of the top type saying something of its values against a kind, in +// either order: disjoint where its source, or an alias below, admits no +// instance of the kind; the kind narrower where every source admits every one +// and a type replacing the alias loses nothing, what a node declared apart +// keeps aside; and an overlap where a source admits some, is read inexactly, +// or the alias, hoisted where it is declared, keeps what a replacement loses. +// An alias keeping an `if` is judged as any other, by what its source admits. +func TestTypeJudge_AnAliasOfTheTopTypeIsJudgedByWhatItsSourceAdmits(t *testing.T) { + t.Parallel() + top := primitiveRef(ir.PrimitiveAny) + not, condition := ir.Unmodeled{"openapi:not": kept(`{"type":"string"}`)}, ir.Unmodeled{"openapi:if-then-else": kept(`{}`)} + alias := func(id ir.TypeID, at jsontext.Pointer, base ir.TypeRef, unmodeled ir.Unmodeled) *ir.Scalar { + return &ir.Scalar{ID: id, Base: &base, Unmodeled: unmodeled, Provenance: ptrAt(at)} + } + reg := narrowingRegistry() + reg["type/admitting"] = alias("type/admitting", "/untyped/admitting", top, not) + reg["type/refusing"] = alias("type/refusing", "/refusing/x", top, not) + reg["type/some"] = alias("type/some", "/some/x", top, not) + reg["type/loose"] = alias("type/loose", "/loose/x", top, not) + reg["type/other-top"] = alias("type/other-top", "/untyped/other-top", top, ir.Unmodeled{"openapi:not": kept(`{"type":"integer"}`)}) + reg["type/conditional"] = alias("type/conditional", "/untyped/conditional", top, condition) + reg["type/conditional-refusing"] = alias("type/conditional-refusing", "/refusing/conditional", top, condition) + reg["type/over-refusing"] = alias("type/over-refusing", "/untyped/over-refusing", ref("type/refusing"), nil) + reg["type/over-conditional"] = alias("type/over-conditional", "/untyped/over-conditional", ref("type/conditional"), nil) + reg["type/over-admitting"] = alias("type/over-admitting", "/untyped/over-admitting", ref("type/admitting"), nil) + hoistedAlias := alias("type/hoisted", "/untyped/hoisted", top, not) + hoistedAlias.Anonymous = true + reg["type/hoisted"] = hoistedAlias + documented := alias("type/documented", "/untyped/documented", top, nil) + documented.Docs = ir.Docs{Description: "carried"} + reg["type/documented"] = documented + reg["type/described-integer"] = &ir.Scalar{ID: "type/described-integer", Base: new(primitiveRef(ir.PrimitiveInteger)), + Docs: ir.Docs{Description: "an integer"}} + stubbed, _ := stubMerger(reg) + integer := primitiveRef(ir.PrimitiveInteger) + for _, tc := range []struct { + name string + alias ir.TypeID + kind ir.TypeRef + want relation + }{ + {"a source admitting every integer", "type/admitting", integer, secondTypeIsNarrower}, + {"a source admitting no integer", "type/refusing", integer, relDisjoint}, + {"a source admitting some integers", "type/some", integer, relOverlap}, + {"a source admitting some integers beside int32", "type/some", primitiveRef(ir.PrimitiveInt32), relUndecided}, + {"a source read inexactly", "type/loose", integer, relUndecided}, + {"an if whose source admits every integer", "type/conditional", integer, secondTypeIsNarrower}, + {"an if beside a source admitting none", "type/conditional-refusing", integer, relDisjoint}, + {"an alias over one admitting none", "type/over-refusing", integer, relDisjoint}, + {"an alias over one keeping an if", "type/over-conditional", integer, relOverlap}, + {"an alias over one saying more", "type/over-admitting", integer, relOverlap}, + {"one hoisted where it is declared", "type/hoisted", integer, relOverlap}, + {"one documented, carried down", "type/documented", integer, secondTypeIsNarrower}, + {"a kind saying more", "type/admitting", ref("type/described-integer"), secondTypeIsNarrower}, + {"an alias of the top type beside another", "type/admitting", ref("type/other-top"), relUnrelated}, + } { + assert.Equal(t, tc.want, judge(stubbed).relate(ref(tc.alias), tc.kind), tc.name) + assert.Equal(t, tc.want.flipped(), judge(stubbed).relate(tc.kind, ref(tc.alias)), "%s, swapped", tc.name) + } +} + +// TestFold_ADroppedDeclarationsShapeGoesWithIt pins what a declaration the +// field drops gives it of what its property keeps: not a keyword it writes +// itself for want of a home on its type, which the declaration kept verbatim +// holds, but a note, a use-bound keyword, an extension, an entry written +// elsewhere, what a fold kept of another declaration, and an entry of another +// vocabulary. +func TestFold_ADroppedDeclarationsShapeGoesWithIt(t *testing.T) { + t.Parallel() + stubbed, _ := stubMerger(narrowingRegistry()) + decls := declsOf(primitiveRef(ir.PrimitiveInteger).Target, primitiveRef(ir.PrimitiveString).Target) + under := func(suffix jsontext.Pointer) ir.Provenance { return ptrAt(declaredAt(0) + "/" + suffix) } + decls[0].property.Unmodeled = ir.Unmodeled{ + "openapi:properties": {Value: ir.RawValue(`{}`), Provenance: under("properties")}, + "openapi:readOnly": {Value: ir.RawValue(`true`), Provenance: under("readOnly")}, + "openapi:x-tag": {Value: ir.RawValue(`1`), Provenance: under("x-tag")}, + "openapi:maxLength": {Value: ir.RawValue(`1`), Provenance: ptrAt("/elsewhere/maxLength")}, + "openapi:conflicting-redeclaration/elsewhere": {Value: ir.RawValue(`{}`), Provenance: ptrAt("/elsewhere")}, + "graphql:shape": {Value: ir.RawValue(`{}`), Provenance: under("shape")}, + } + + got := stubbed.fold(decls) + + assert.Equal(t, primitiveRef(ir.PrimitiveString).Target, got.Type.Target) + for _, key := range []string{"openapi:readOnly", "openapi:x-tag", "openapi:maxLength", + "openapi:conflicting-redeclaration/elsewhere", "graphql:shape"} { + assert.Contains(t, got.Unmodeled, key) + } + assert.NotContains(t, got.Unmodeled, "openapi:properties", "the shape passed over goes with it") + assert.Contains(t, got.Unmodeled, passedOverDeclarationKey+string(declaredAt(0)), "the declaration is kept verbatim") +} + +// TestTopAliasAgainstKind_ReadsNothingOfAChainItCannotRead pins the judgment's +// guard: an alias of the top type over a type the registry lacks reads +// nothing. +func TestTopAliasAgainstKind_ReadsNothingOfAChainItCannotRead(t *testing.T) { + t.Parallel() + stubbed, _ := stubMerger(narrowingRegistry()) + typeDef := &ir.Scalar{ID: "type/alias", Base: new(ref("type/missing")), Provenance: ptrAt("/untyped/alias")} + + _, read := topAliasAgainstKind(judge(stubbed), typeDef, valueKind{primitive: ir.PrimitiveAny}, nil, 0, InstanceInteger, true) + + assert.False(t, read) +} diff --git a/compilers/openapi/internal/merge/typejudge.go b/compilers/openapi/internal/merge/typejudge.go index 2f194d68c..847479902 100644 --- a/compilers/openapi/internal/merge/typejudge.go +++ b/compilers/openapi/internal/merge/typejudge.go @@ -6,7 +6,6 @@ package merge import ( "reflect" "slices" - "strings" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/budget" @@ -14,7 +13,7 @@ import ( "github.com/dexpace/morphic/ir" ) -// relation is the verdict of comparing the types of one field declared twice +// relation is the answer of comparing the types of one field declared twice // under allOf (docs/compilers/openapi.md#allof-redeclared-property). type relation int @@ -39,10 +38,15 @@ const ( firstTypeIsNarrower // secondTypeIsNarrower says the second type is within the first. secondTypeIsNarrower - // relMeet is a pair of nodes each saying what the other lacks, in their - // bounds, members or what else they say (verdict): a value of both is one of + // relIntersect is a pair of nodes each saying what the other lacks, in their + // bounds, members or what else they say (answer): a value of both is one of // a node holding both, so each folds into the field (builder). - relMeet + relIntersect + // relUndecided is a pair the judgment cannot show to share a value or to + // share none: a source read it does not follow, a value the value admission + // reader cannot judge, or two nodes keeping references not shown alike. The + // fold lowers it as an overlap and says only that it cannot tell. + relUndecided ) // flipped is the relation seen from the other side. @@ -56,15 +60,16 @@ func (r relation) flipped() relation { return r } -// maxJudgeDepth bounds the nesting of containers the judgment compares and of -// the values it judges, so a deep or cyclic registry cannot recurse without end. +// maxJudgeDepth bounds the nesting of containers the judgment compares, so a +// deep or cyclic registry cannot recurse without end. A value is judged and +// spelled by ir, to ir's own bound. const maxJudgeDepth = 8 // typeJudge compares two types of one field, and judges whether a value is one // of a type's. It is a type of its own, not methods on Merger, so that the // conflict lattice's size stays the lattice's. type typeJudge struct { - registry + registryReader // modelPairs is what remains of the model pairs a judgment compares // (maxModelPairs), shared by its every depth; relate starts it, and nil // compares none. @@ -76,13 +81,28 @@ type typeJudge struct { sites declarationSites } -// registry reads what the registry says of one type, whichever declarations a -// judgment compares: what an alias stands for, the kind its values are read as, +// registryReader reads what the registryReader says of one type, whichever declarations a +// judgment compares: what an alias represents, the kind its values are read as, // what it composes, and which values it admits. -type registry struct { +type registryReader struct { // resolve looks a type up in the registry: Merger.resolve, which a test // counts the reads of. resolve func(ir.TypeID) (ir.TypeDef, bool) + // answerMemos are the run's memos of answers along its alias chains, which every alias + // walk reads through (Merger.AliasChainAnswerMemos). + answerMemos *AliasChainAnswerMemos + // admission is the fold's value admission reader + // (Merger.ValueAdmissionReader). + admission *ir.ValueAdmissionReader +} + +// valueAdmission returns the value admission reader r judges values through: +// the fold's, or, for a registry naming none, one of its own over resolve. +func valueAdmission(registry registryReader) *ir.ValueAdmissionReader { + if registry.admission != nil { + return registry.admission + } + return NewFoldValueAdmissionReader(registry.resolve, ir.NewAliasChainIndex(registry.resolve)) } // declarationSites is where the two declarations a judgment compares were @@ -95,20 +115,16 @@ type declarationSites struct { // at or under one of them, in the same document; one a $ref reached // elsewhere was declared apart. written [2][]ir.Provenance - // walk is Merger.Walk, whose Alike says two nodes held alike keeping a - // reference are one type only where they read it against one base, and - // whose Admits says whether a node's source admits a kind of instance. + // walk is Merger.Walk, whose DeclarationsAdmitAlike says two nodes held alike keeping a + // reference are one type only where they admit alike, and whose Admits + // says whether a node's source admits a kind of instance. walk FieldDeclarationContext } // relateFrom compares a with b, two types at depth: a field's own at 0, a -// container's members a level down, with budgets of its own. The winner never -// depends on which is which: swapping the arguments, and written's two pointers -// with them, flips a narrowing and leaves any other verdict as it was. The arms, -// in order: the same target; a degraded Any node, unrelated to every type; the -// top type, or an alias read as it (topAt), losing to anything but another; -// then arms, a union's variants (unionArms) and classify, each where those -// before find nothing, read for null (heldNull). +// container's members a level down, with budgets of its own. The chosen member +// never depends on which is which: swapping the arguments flips a narrowing +// and leaves any other answer as it was. func (j typeJudge) relateFrom(a, b ir.TypeRef, depth int) relation { j.modelPairs = modelPairs() variants := budget.New(budget.AtMost(maxVariantReads)) @@ -141,6 +157,9 @@ func (j typeJudge) relateAt(a, b ir.TypeRef, depth int) relation { case bTop: return firstTypeIsNarrower } + if rel, decided := nullAlone(j, a, at, b, bt); decided { + return rel + } rel := j.arms(a, at, b, bt, depth) if rel == relUnrelated { rel = unionArms(j, a, at, b, bt, depth) @@ -148,50 +167,80 @@ func (j typeJudge) relateAt(a, b ir.TypeRef, depth int) relation { if rel == relUnrelated { rel = j.classify(a, at, b, bt, depth) } - return j.heldNull(a, at, b, bt, rel) + return nullIntersection(j, a, at, b, bt, rel) } -// heldNull returns rel but where it puts a type admitting null through its alias -// chain (nullThroughChain) within one whose reference admits none: a field -// holding that type would admit null the other refuses, whatever the field's -// reference says, so the two overlap. -func (j typeJudge) heldNull(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef, rel relation) relation { - switch { - case rel == firstTypeIsNarrower && !b.Nullable && j.nullThroughChain(at): - return relOverlap - case rel == secondTypeIsNarrower && !a.Nullable && j.nullThroughChain(bt): - return relOverlap - default: +// nullAlone relates a type admitting null alone, a nullable reference to a +// closed enum of no member (admitsNullAlone), to another: within it where the +// value admission reader says the other admits null, disjoint where it says it +// does not, and unrelated where it cannot tell (GitHub #1857). It decides +// nothing where neither or both admit null alone. +func nullAlone(j typeJudge, a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef) (relation, bool) { + aAlone, bAlone := admitsNullAlone(j, a, at), admitsNullAlone(j, b, bt) + if aAlone == bAlone { + return relUnrelated, false + } + other, flip := b, false + if bAlone { + other, flip = a, true + } + rel := relUnrelated + switch valueAdmission(j.registryReader).Admits(other, ir.Value{Kind: ir.ValueNull}) { + case ir.AdmitsYes: + rel = firstTypeIsNarrower + case ir.AdmitsNo: + rel = relDisjoint + case ir.AdmitsUnknown: + } + if flip { + return rel.flipped(), true + } + return rel, true +} + +// admitsNullAlone reports whether ref, naming typeDef, admits null and +// nothing else: it admits null, and typeDef represents a closed enum of no +// member. +func admitsNullAlone(j typeJudge, ref ir.TypeRef, typeDef ir.TypeDef) bool { + enum, ok := j.unaliased(typeDef).(*ir.Enum) + return ref.Nullable && ok && enum.Closed && len(enum.Members) == 0 +} + +// nullIntersection returns rel, but where two value sets sharing no member both admit +// null through their references: they share null, so they intersect at null alone, +// in a closed enum of no member behind a nullable reference (GitHub #1894). +func nullIntersection(j typeJudge, a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef, rel relation) relation { + if rel != relDisjoint || !a.Nullable || !b.Nullable { + return rel + } + _, _, both := bothEnums(j.unaliased(at), j.unaliased(bt)) + if !both { return rel } + return relIntersect } // arms relates two resolved types, neither the top type nor degraded, that it -// can narrow: two bare primitives (typeformat.Relate); a Scalar, Enum or -// Literal against a bare primitive; an alias against the type it stands for, by -// what it adds (standsFor); then each as the node it stands for (view): two -// identical such nodes; two literals of different values, disjoint; two enums -// (enums); two models alike (models); two nodes holding bounds (boundedNodes), -// two alike in every member and detail taking the copy rule (sameNodes); and a -// structure against one it says it is (structures). Any other pair is unrelated -// here. +// can narrow: two bare primitives, a node against a bare primitive, an alias +// against the type it represents, and then each as the node it represents +// (view). Any other pair is unrelated here. func (j typeJudge) arms(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef, depth int) relation { - ap, aBare := at.(*ir.Primitive) - bp, bBare := bt.(*ir.Primitive) - aFor, bFor := j.standsFor(at, b.Target), j.standsFor(bt, a.Target).flipped() + aPrimitive, aBare := at.(*ir.Primitive) + bPrimitive, bBare := bt.(*ir.Primitive) + aFor, bFor := j.relateAliasChainTo(at, b.Target, a.Nullable), j.relateAliasChainTo(bt, a.Target, b.Nullable).flipped() switch { case aBare && bBare: - return fromTypeformat(typeformat.Relate(ap.PrimitiveKind, bp.PrimitiveKind)) + return fromTypeformat(typeformat.Relate(aPrimitive.PrimitiveKind, bPrimitive.PrimitiveKind)) case bBare: - return j.nodeAgainstBare(a, at, b, bp.PrimitiveKind) + return j.nodeAgainstBare(a, at, j.sites.written[0], depth, b, bPrimitive.PrimitiveKind) case aBare: - return j.nodeAgainstBare(b, bt, a, ap.PrimitiveKind).flipped() + return j.nodeAgainstBare(b, bt, j.sites.written[1], depth, a, aPrimitive.PrimitiveKind).flipped() case aFor != relUnrelated && bFor == relUnrelated: return aFor case bFor != relUnrelated && aFor == relUnrelated: return bFor } - stop := j.sharedLink(at, bt) + stop := j.sharedAlias(at, bt) at, bt = j.view(at, stop), j.view(bt, stop) switch { case sameNode(at, bt): @@ -213,10 +262,23 @@ func (j typeJudge) arms(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef if rel == relSame { // Two distinct nodes alike in member and detail: copies, by the rule // sameNodes states for the others. - return j.sites.copies(a, at, b, bt) + return j.sites.alikeInValues(a, at, b, bt) } if rel == relUnrelated { - return j.structures(a, at, b, bt) + return unrelatedNodes(j, a, at, b, bt) + } + return rel +} + +// unrelatedNodes relates two nodes j found no relation between in their +// bounds: by what one says of the other (structures), and where that says +// nothing either, as copies (sameNodes) where the walk shows the types a and b +// name admit exactly the same values, as an alias of a model and an inline +// copy of that model do. +func unrelatedNodes(j typeJudge, a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef) relation { + rel := j.structures(a, at, b, bt) + if rel == relUnrelated && at.Kind() == bt.Kind() && j.sites.walk.NodesAdmitAlike(a.Target, b.Target) { + return j.sites.copies(a, at, b, bt) } return rel } @@ -239,65 +301,13 @@ func (j typeJudge) structures(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.T } // within reports whether every value of a is a value of b, a structure: a is -// composed of b (composes), or b says nothing but object and a describes one. An +// composed of b (FieldDeclarationContext.IsComposedOf), or b says nothing but object and a describes one. An // alias of such a model does not count, since it may say more than the model. func (j typeJudge) within(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef) bool { if !isStructural(j.unaliased(bt)) { return false } - return j.composes(a.Target, b.Target) || (saysOnlyObject(bt) && instanceKind(j.unaliased(at)) == ir.KindModel) -} - -// maxComposedParts bounds the types composes reads for one question. Stopping -// early only misses a narrowing, which leaves two types for the field to -// compose, and that loses nothing. -const maxComposedParts = 64 - -// composes reports whether id is composed of target: a chain of alias scalars, -// Base and Mixins leads from one to the other, and every value of the first is -// a value of what it composes. A folded field names no such link, so the answer -// follows no fold. The walk reads at most maxComposedParts types. -func (r registry) composes(id, target ir.TypeID) bool { - seen := map[ir.TypeID]bool{id: true} - queue := []ir.TypeID{id} - for len(queue) > 0 && len(seen) <= maxComposedParts { - td, ok := r.resolve(queue[len(queue)-1]) - queue = queue[:len(queue)-1] - if !ok { - continue - } - for _, part := range ComposedOf(td) { - if part == target { - return true - } - if !seen[part] { - seen[part] = true - queue = append(queue, part) - } - } - } - return false -} - -// ComposedOf returns the types td says its values are also values of: an -// alias scalar's Base, and a model's Base and Mixins. -func ComposedOf(td ir.TypeDef) []ir.TypeID { - var parts []ir.TypeID - switch t := td.(type) { - case *ir.Scalar: - if t.Base != nil { - parts = append(parts, t.Base.Target) - } - case *ir.Model: - if t.Base != nil { - parts = append(parts, t.Base.Target) - } - for _, typeRef := range t.Mixins { - parts = append(parts, typeRef.Target) - } - default: - } - return parts + return j.sites.walk.IsComposedOf(a.Target, b.Target) || (saysOnlyObject(bt) && instanceKind(j.unaliased(at)) == ir.KindModel) } // bothModels returns a and b as models, and false where either is not one. @@ -307,13 +317,13 @@ func bothModels(a, b ir.TypeDef) (*ir.Model, *ir.Model, bool) { return am, bm, aok && bok } -// saysOnlyObject reports whether td is a model saying nothing but that its +// saysOnlyObject reports whether typeDef is a model saying nothing but that its // values are objects, as a bare `type: object` lowers, however it is named // (siteless). A type that composes another still reaches it, but one narrowing // this model does not, so a title or an example here would be lost with it. It // compares the whole model, so a field added to it counts. -func saysOnlyObject(td ir.TypeDef) bool { - model, ok := td.(*ir.Model) +func saysOnlyObject(typeDef ir.TypeDef) bool { + model, ok := typeDef.(*ir.Model) if !ok { return false } @@ -323,20 +333,19 @@ func saysOnlyObject(td ir.TypeDef) bool { } // classify judges a pair arms cannot narrow by what each type holds, an alias -// as the type it stands for. Two ending in kinds go through relateKinds: disjoint -// kinds, or an enum none of whose members the other kind admits, are disjoint, -// and any other pair overlaps. A literal against a type ending in a kind is -// judged by againstKind, and against a literal of its value overlaps. A value -// type against a structure, or two structures of different instance types -// (saysItsValues), are judged by what each structure's source states -// (againstOtherInstance). Anything else is unrelated: nothing says what they -// share. +// as the type it represents: two ending in kinds by relateKinds, a literal +// against a kind by againstKind, and a value type against a structure, or two +// structures of different instance types, by what each structure's source +// states (againstOtherInstance). Anything else is unrelated: nothing says what +// they share. func (j typeJudge) classify(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef, depth int) relation { ak, aok := j.kindOf(a) bk, bok := j.kindOf(b) au, bu := j.unaliased(at), j.unaliased(bt) aSites, bSites := j.sites.written[0], j.sites.written[1] switch { + case aok && bok && (ak.primitive == ir.PrimitiveAny) != (bk.primitive == ir.PrimitiveAny): + return topAliasAgainstKindNode(j, at, ak, aSites, bt, bk, bSites, depth) case aok && ak.primitive == ir.PrimitiveAny, bok && bk.primitive == ir.PrimitiveAny: return relUnrelated case aok && bok: @@ -345,9 +354,9 @@ func (j typeJudge) classify(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.Typ } return relOverlap case aok && isStructural(bu): - return j.againstOtherInstance(bt, bSites, depth, primitiveInstance(ak.primitive)).flipped() + return j.againstOtherInstance(bt, bSites, depth, primitiveInstance(ak.primitive), coversItsInstanceKind(at)).flipped() case bok && isStructural(au): - return j.againstOtherInstance(at, aSites, depth, primitiveInstance(bk.primitive)) + return j.againstOtherInstance(at, aSites, depth, primitiveInstance(bk.primitive), coversItsInstanceKind(bt)) case aok: return j.againstKind(j.view(bt, ""), a, j.view(at, ""), ak).flipped() case bok: @@ -355,51 +364,109 @@ func (j typeJudge) classify(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.Typ case isLiteral(au) && isLiteral(bu): return relOverlap case saysItsValues(au) && saysItsValues(bu) && instanceKind(au) != instanceKind(bu): - return acrossInstances(j.againstOtherInstance(at, aSites, depth, nodeInstance(bu)), - j.againstOtherInstance(bt, bSites, depth, nodeInstance(au))) + return acrossInstances(j.againstOtherInstance(at, aSites, depth, nodeInstance(bu), false), + j.againstOtherInstance(bt, bSites, depth, nodeInstance(au), false)) default: return relUnrelated } } -// againstOtherInstance is the verdict on td, a structure through any aliases, -// against a type whose values are of the kind other, from td's side. Where td's -// source and each alias's admit every instance of that kind, exactly -// (FieldDeclarationContext.Admits), td admits every value of the other type, so -// that one is narrower: `properties` alone constrains objects and admits a -// string. A node saying more than that, such as examples, overlaps instead, as -// topAt reads an alias of `{}`, since a type replacing it would lose it. Any -// other structure is disjoint from the other type. -func (j typeJudge) againstOtherInstance(td ir.TypeDef, sites []ir.Provenance, depth int, other JSONInstanceKind) relation { - chain, end := j.aliasChain(td) - if !isStructural(end) || !sourceAdmits(j.sites.walk, end.Common().Provenance, other) { - return relDisjoint - } +// againstOtherInstance is the answer on typeDef, a structure through any +// aliases, against a type whose values are of the kind other, every one of +// them where otherWhole, from typeDef's side, by what its source and each +// alias's admit of that kind: `properties` alone constrains objects and admits +// every string, so a string is narrower. A literal of another kind is disjoint +// from the other type. +func (j typeJudge) againstOtherInstance(typeDef ir.TypeDef, sites []ir.Provenance, depth int, other JSONInstanceKind, otherWhole bool) relation { // A $ref carries the docs, deprecation and redaction of what it reaches // down to the property, so a field's own type the declaration written at // sites reached through one may hold them; one written there keeps them on // itself alone (docs/ir/annotations.md#what-a-reference-carries-down). - carried := depth == 0 && !hoistedAt(td, sites) - saysNothing := structureAddsNothingBeyondBase(end, carried && len(chain) == 0) - for k, scalar := range chain { - if !sourceAdmits(j.sites.walk, scalar.Provenance, other) { + carried := depth == 0 && !hoistedAt(typeDef, sites) + scalar, alias := typeDef.(*ir.Scalar) + if !alias || scalar.Base == nil { + if !isStructural(typeDef) { return relDisjoint } - saysNothing = saysNothing && aliasAddsNothingBeyondBase(scalar, carried && k == 0) + own, exact := sourceAdmission(j.sites.walk, typeDef.Common().Provenance, other) + return instanceRelation(own, exact, instanceAdmission{admits: true}, structureAddsNothingBeyondBase(typeDef, carried), otherWhole) + } + below, read := j.registryReader.chainAnswerMemos(j.sites.walk).admissionThrough(scalar.Base.Target, other) + if !read { + return relUndecided + } + own, exact := sourceAdmission(j.sites.walk, scalar.Provenance, other) + addsNothing := aliasAddsNothingBeyondBase(scalar) || carried && aliasAddsNothingBeyondItsUse(scalar) + return instanceRelation(own, exact, below, below.saysNothing && addsNothing, otherWhole) +} + +// instanceRelation is the other type's answer against a source admitting own +// of the other's kind, by a read exact or not, below a chain admitting below of +// it, and saying nothing more where saysNothing: disjoint where either admits +// no instance of the kind; narrower, or overlapping where the source says +// more, where both admit every one; overlapping where they admit some and the +// other type holds every instance (otherWhole); and undecided where nothing +// shows a shared value or none. +func instanceRelation(own KindAdmission, exact bool, below instanceAdmission, saysNothing, otherWhole bool) relation { + switch { + case own == AdmitsNoneOfKind || below.none: + return relDisjoint + case !exact || !below.admits: + return relUndecided + case own == AdmitsEveryOfKind: + return narrowerUnlessSaid(saysNothing) + case otherWhole: + return relOverlap + default: + return relUndecided } +} + +// coversItsInstanceKind reports whether typeDef is a bare primitive whose +// values are every instance of the JSON kind they are (wholeInstanceKind). +func coversItsInstanceKind(typeDef ir.TypeDef) bool { + primitive, ok := typeDef.(*ir.Primitive) + return ok && wholeInstanceKind(primitive.PrimitiveKind) +} + +// wholeInstanceKind reports whether a value of kind may be any instance of the +// JSON kind it is (primitiveInstance): a string, an integer, a number or a +// boolean, which no format narrows. +func wholeInstanceKind(kind ir.PrimitiveKind) bool { + return kind == ir.PrimitiveString || kind == ir.PrimitiveInteger || kind == ir.PrimitiveNumber || kind == ir.PrimitiveBool +} + +// narrowerUnlessSaid is the other type's answer against a structure admitting +// every instance of its kind: narrower where the structure says nothing else, +// and overlapping where it says more, which a type replacing it would lose. +func narrowerUnlessSaid(saysNothing bool) relation { if !saysNothing { return relOverlap } return secondTypeIsNarrower } -// sourceAdmits reports whether the source written at at admits every instance -// of kind, by a read of walk's that follows all it writes -// (FieldDeclarationContext.Admits): one that does not decides nothing, and the -// structure stays disjoint from the other type. -func sourceAdmits(walk FieldDeclarationContext, at ir.Provenance, kind JSONInstanceKind) bool { - admits, exact := walk.Admits(at, kind) - return admits && exact +// chainAnswerMemos returns the memos r reads alias chains through: the +// run's, or, for a registry naming none, memos of its own over resolve, +// which read each chain afresh, asking walk whether a site admits an instance +// of a kind, nil where no question asks it. +func (r registryReader) chainAnswerMemos(walk FieldDeclarationContext) *AliasChainAnswerMemos { + if r.answerMemos != nil { + return r.answerMemos + } + return NewAliasChainAnswerMemos(r.resolve, ir.NewAliasChainIndex(r.resolve), walk) +} + +// sourceAdmission is what the source written at place admits of the instances +// of kind, by a read of walk's (FieldDeclarationContext.Admits), and whether +// that read follows all the source writes: one that does not decides nothing, +// read as admitting some. +func sourceAdmission(walk FieldDeclarationContext, place ir.Provenance, kind JSONInstanceKind) (admission KindAdmission, exact bool) { + admission, exact = walk.Admits(place, kind) + if !exact { + return AdmitsSomeOfKind, false + } + return admission, true } // primitiveInstance returns the kind of JSON instance a value of primitiveKind @@ -418,12 +485,13 @@ func primitiveInstance(primitiveKind ir.PrimitiveKind) JSONInstanceKind { } } -// nodeInstance returns the kind of JSON instance td's values are, td being a -// literal or a structure (saysItsValues): an object for a model or a map, an -// array for a list or a tuple, and a literal's value's own. -func nodeInstance(td ir.TypeDef) JSONInstanceKind { - kind := instanceKind(td) - lit, isLit := td.(*ir.Literal) +// nodeInstance returns the kind of JSON instance typeDef's values are, typeDef +// being a literal or a structure (saysItsValues): an object for a model or a +// map, an array for a list or a tuple, and a literal's value's own +// (valueInstance). +func nodeInstance(typeDef ir.TypeDef) JSONInstanceKind { + kind := instanceKind(typeDef) + lit, isLit := typeDef.(*ir.Literal) switch { case kind == ir.KindModel: return InstanceObject @@ -431,39 +499,89 @@ func nodeInstance(td ir.TypeDef) JSONInstanceKind { return InstanceArray case !isLit: return 0 - case lit.Value.Kind == ir.ValueBool: - return InstanceBoolean - case lit.Value.Kind == ir.ValueNull: - return InstanceNull - case lit.Value.Kind == ir.ValueNumber && strings.ContainsAny(string(lit.Value.Number), ".eE"): - return InstanceNumber - case lit.Value.Kind == ir.ValueNumber: - return InstanceInteger default: + return valueInstance(lit.Value) + } +} + +// valueInstance returns the kind of JSON instance value is, as +// typeformat.KindsOfValue reads it: the first of merge's kinds whose instances +// it may be (instanceKindsOf), so an integer is an integer and any other +// number a number. A value no JSON instance spells is asked as a string, the +// text a symbol or bytes is written as. +func valueInstance(value ir.Value) JSONInstanceKind { + kinds, isInstance := typeformat.KindsOfValue(value) + if !isInstance { return InstanceString } + kind := InstanceString + for kind < InstanceNull && instanceKindsOf(kind)&kinds == 0 { + kind++ + } + return kind } -// structureAddsNothingBeyondBase reports whether td holds nothing in its +// structureAddsNothingBeyondBase reports whether typeDef holds nothing in its // TypeCommon but where it was declared, and, where carried, what a reference -// carries down to its use, as aliasAddsNothingBeyondBase reads an alias. What -// else a structure holds constrains only values of its own instance type. -func structureAddsNothingBeyondBase(td ir.TypeDef, carried bool) bool { - typeCommon := siteless(*td.Common()) +// carries down to its use. What else a structure holds constrains only values +// of its own instance type. A $ref it keeps verbatim, naming no schema, says +// nothing here; the field narrowing the structure carries it (keptReferences). +func structureAddsNothingBeyondBase(typeDef ir.TypeDef, carried bool) bool { + typeCommon := siteless(*typeDef.Common()) + typeCommon.Unmodeled = withoutKeptReferences(typeCommon.Unmodeled) if carried { typeCommon.Docs, typeCommon.Deprecation, typeCommon.Sensitive = ir.Docs{}, nil, false } return reflect.DeepEqual(typeCommon, ir.TypeCommon{}) } -// acrossInstances joins the verdicts againstOtherInstance gives two structures -// of different instance types, a's against b and b's against a, each from its -// own side. Where both admit every value of the other's type they share every -// value of a third, so they overlap. +// keptReferences returns the entries of unmodeled keeping a reference verbatim, +// one naming no schema, which lowers as the schema written without it does +// (annotation.KeptReferenceKey): a $ref's, or a $dynamicRef's resolving as the +// $ref it spells. +func keptReferences(unmodeled ir.Unmodeled) ir.Unmodeled { + var out ir.Unmodeled + for key, entry := range unmodeled { + if annotation.KeptReferenceKey(key) { + if out == nil { + out = ir.Unmodeled{} + } + out[key] = entry + } + } + return out +} + +// withoutKeptReferences returns unmodeled less its kept references +// (keptReferences), nil where nothing else is left. +func withoutKeptReferences(unmodeled ir.Unmodeled) ir.Unmodeled { + kept := keptReferences(unmodeled) + if len(kept) == 0 { + return unmodeled + } + var out ir.Unmodeled + for key, entry := range unmodeled { + if _, reference := kept[key]; !reference { + if out == nil { + out = ir.Unmodeled{} + } + out[key] = entry + } + } + return out +} + +// acrossInstances combines the answers againstOtherInstance gives two +// structures of different instance types, a's against b and b's against a, each +// from its own side. Where both admit every value of the other's type they +// share every value of a third, so they overlap; where neither answer shows a +// shared value or none, nothing does. func acrossInstances(a, b relation) relation { switch { case a == relDisjoint && b == relDisjoint: return relDisjoint + case a == relUndecided && b == relUndecided: + return relUndecided case a == relDisjoint: return b.flipped() case b == relDisjoint: @@ -473,70 +591,56 @@ func acrossInstances(a, b relation) relation { } } -// saysItsValues reports whether td is a literal or a structure, which classify -// can compare by kind. Nothing else that reaches it can be: a union or an -// external may hold a value of any kind, and an opaque scalar says nothing. -func saysItsValues(td ir.TypeDef) bool { return isLiteral(td) || isStructural(td) } +// saysItsValues reports whether typeDef is a literal or a structure, which +// classify can compare by kind. Nothing else that reaches it can be: a union or +// an external may hold a value of any kind, and an opaque scalar says nothing. +func saysItsValues(typeDef ir.TypeDef) bool { return isLiteral(typeDef) || isStructural(typeDef) } -// unaliased returns the type td stands for: td itself, or what a chain of alias -// scalars ends in (aliasChain). -func (r registry) unaliased(td ir.TypeDef) ir.TypeDef { - _, end := r.aliasChain(td) - return end +// unaliased returns the type typeDef represents: typeDef itself, or what a +// chain of alias scalars ends in (docs/ir/scalars.md#aliases), typeDef where +// the chain repeats a type or names one the registry lacks. +func (r registryReader) unaliased(typeDef ir.TypeDef) ir.TypeDef { + scalar, alias := typeDef.(*ir.Scalar) + if !alias || scalar.Base == nil { + return typeDef + } + return r.chainAnswerMemos(nil).endOf(scalar) } -// aliasChain returns the alias scalars a chain from td leads through, in order, -// and the type it ends in: td itself where td is no alias -// (docs/ir/scalars.md#aliases). The chain is bounded against a malformed -// registry, as kindOf's is. -func (r registry) aliasChain(td ir.TypeDef) ([]*ir.Scalar, ir.TypeDef) { - var chain []*ir.Scalar - for range maxTypeResolveDepth { - scalar, alias := td.(*ir.Scalar) - if !alias || scalar.Base == nil { - return chain, td - } - next, ok := r.resolve(scalar.Base.Target) - if !ok { - return chain, td - } - chain, td = append(chain, scalar), next - } - return chain, td -} - -// againstKind judges td, which ends in no primitive kind and is no structure -// (classify judges those), against kindRef, a type that ends in valueKindValue -// and resolves to kindNode, from td's side. Anything but a literal, such as a -// union, is unrelated to it. A literal overlaps it, since which values meet is -// not decided here, unless a held format narrows valueKindValue. Then the -// literal is disjoint where kindRef refuses its value, as against a kind with a -// judge, narrower where kindRef admits it and says nothing more -// (saysOnlyFormat), and otherwise judged by what else kindNode says -// (literalBesideDetail). -func (j typeJudge) againstKind(td ir.TypeDef, kindRef ir.TypeRef, kindNode ir.TypeDef, valueKindValue valueKind) relation { - lit, ok := td.(*ir.Literal) - switch { - case !ok: +// againstKind judges typeDef, which ends in no primitive kind and is no +// structure, against kindRef, a type that ends in valueKind and resolves to +// kindNode, from typeDef's side. Anything but a literal is unrelated to it. A +// literal is disjoint where the value admission reader says kindRef refuses +// its value, undecided where it cannot tell, and overlapping where it admits +// it, unless a held format narrows valueKind: then it is narrower where kindRef +// says nothing more (saysOnlyFormat), and otherwise judged by what else +// kindNode says (literalBesideDetail). +func (j typeJudge) againstKind(typeDef ir.TypeDef, kindRef ir.TypeRef, kindNode ir.TypeDef, valueKind valueKind) relation { + lit, ok := typeDef.(*ir.Literal) + if !ok { return relUnrelated - case valueKindValue.format == "": - return relOverlap - case !j.admits(kindRef, lit.Value): + } + switch valueAdmission(j.registryReader).Admits(kindRef, lit.Value) { + case ir.AdmitsNo: return relDisjoint - case saysOnlyFormat(kindNode): + case ir.AdmitsUnknown: + return relUndecided + case ir.AdmitsYes: + } + if valueKind.format == "" { + return relOverlap + } + if saysOnlyFormat(kindNode) { return firstTypeIsNarrower - default: - return j.literalBesideDetail(lit, kindNode) } + return j.literalBesideDetail(lit, kindNode) } -// saysOnlyFormat reports whether td is a Scalar saying nothing but its base, a -// held format and bounds: no documentation, example, deprecation, XML hint, -// Unmodeled entry or anything else, as saysOnlyObject reads a model. A -// narrower type replacing it loses none of it, since a value it admits meets -// the format and the bounds. -func saysOnlyFormat(td ir.TypeDef) bool { - scalar, ok := td.(*ir.Scalar) +// saysOnlyFormat reports whether typeDef is a Scalar saying nothing but its +// base, a held format and bounds. A narrower type replacing it loses none of +// it, since a value it admits intersects the format and the bounds. +func saysOnlyFormat(typeDef ir.TypeDef) bool { + scalar, ok := typeDef.(*ir.Scalar) return ok && scalarSaysOnlyFormat(scalar) } @@ -548,18 +652,18 @@ func scalarSaysOnlyFormat(scalar *ir.Scalar) bool { return held && reflect.DeepEqual(bare, ir.Scalar{}) } -// isLiteral reports whether td is a Literal. -func isLiteral(td ir.TypeDef) bool { - _, ok := td.(*ir.Literal) +// isLiteral reports whether typeDef is a Literal. +func isLiteral(typeDef ir.TypeDef) bool { + _, ok := typeDef.(*ir.Literal) return ok } -// isStructural reports whether td can never be a value type under allOf +// isStructural reports whether typeDef can never be a value type under allOf // intersection: a model, list, map or tuple. An Enum, Union or External is // not, since a member or variant can itself be a value of the kind against it, // nor is a base-less opaque scalar, which says nothing of its values. -func isStructural(td ir.TypeDef) bool { - switch td.(type) { +func isStructural(typeDef ir.TypeDef) bool { + switch typeDef.(type) { case *ir.Model, *ir.List, *ir.MapT, *ir.Tuple: return true default: @@ -567,20 +671,20 @@ func isStructural(td ir.TypeDef) bool { } } -// instanceKind folds td's kind onto the JSON instance type it describes: a MapT -// or an object literal into the Model kind, and a Tuple or a list literal into -// the List kind. One instance can satisfy a map and a struct at once, or a list -// and a tuple. Which of the two a position lowers to depends on what else it -// declares about its members (docs/ir/containers.md), not on a shape that could -// contradict the other. -func instanceKind(td ir.TypeDef) ir.TypeKind { - if lit, ok := td.(*ir.Literal); ok && lit.Value.Kind == ir.ValueObject { +// instanceKind folds typeDef's kind onto the JSON instance type it describes: a +// MapT or an object literal into the Model kind, and a Tuple or a list literal +// into the List kind. One instance can satisfy a map and a struct at once, or a +// list and a tuple. Which of the two a position lowers to depends on what else +// it declares about its members (docs/ir/containers.md), not on a shape that +// could contradict the other. +func instanceKind(typeDef ir.TypeDef) ir.TypeKind { + if lit, ok := typeDef.(*ir.Literal); ok && lit.Value.Kind == ir.ValueObject { return ir.KindModel } - if lit, ok := td.(*ir.Literal); ok && lit.Value.Kind == ir.ValueList { + if lit, ok := typeDef.(*ir.Literal); ok && lit.Value.Kind == ir.ValueList { return ir.KindList } - typeKind := td.Kind() + typeKind := typeDef.Kind() if typeKind == ir.KindMap { return ir.KindModel } @@ -590,57 +694,62 @@ func instanceKind(td ir.TypeDef) ir.TypeKind { return typeKind } -// isAnyType reports whether ref targets a type that admits every value: the -// schemaless top type, bare or an alias over it, or an Any node a degraded -// lowering minted. It follows the Base chain, since a position writing -// something only a node can hold gets an alias over the top type. -func (r registry) isAnyType(ref ir.TypeRef) bool { - if valueKind, ok := r.kindOf(ref); ok { - return valueKind.primitive == ir.PrimitiveAny - } - td, ok := r.resolve(ref.Target) - return ok && td.Kind() == ir.KindAny -} - -// hoistedAt reports whether td is a hoisted node written at or under one of -// sites, where the declaration that holds it is written (declaration.sites): +// hoistedAt reports whether typeDef is a hoisted node written at or under one +// of sites, where the declaration that holds it is written (declaration.sites): // in its document, at or below its pointer. A hoisted node a $ref reached from // elsewhere, another schema's property, a parameter's schema or a position of // another document that happens to share the pointer, was declared apart. -func hoistedAt(td ir.TypeDef, sites []ir.Provenance) bool { - typeCommon := td.Common() +func hoistedAt(typeDef ir.TypeDef, sites []ir.Provenance) bool { + typeCommon := typeDef.Common() return slices.ContainsFunc(sites, func(at ir.Provenance) bool { return hoistedUnder(typeCommon, at) }) } // hoistedUnder reports whether the node typeCommon describes is a hoisted one // written at or under at, in at's document. func hoistedUnder(typeCommon *ir.TypeCommon, at ir.Provenance) bool { - pointer := typeCommon.Provenance.Pointer return typeCommon.Anonymous && typeCommon.Provenance.Source == at.Source && - (pointer == at.Pointer || strings.HasPrefix(string(pointer), string(at.Pointer)+"/")) + at.Pointer.Contains(typeCommon.Provenance.Pointer) } // copies relates a and b, two nodes held alike, by sameNodes, each a copy -// where it was hoisted at its own declaration. A copy keeping a reference is -// one type with the other node only where the two read it against one base, -// each where it is written: elsewhere a $ref spelled alike names another -// schema, so the two were declared apart, whether the other is a copy or a -// node declared elsewhere. +// where it was hoisted at its own declaration. Two nodes keeping a reference, +// a copy or two declared apart, are one type, or one gives way to the other, +// only where the two admit alike, each read where it is written +// (FieldDeclarationContext.DeclarationsAdmitAlike): elsewhere a $ref spelled alike may name +// another schema, so nothing shows whether they share a value. func (d declarationSites) copies(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef) relation { - aHoisted, bHoisted := hoistedAt(at, d.written[0]), hoistedAt(bt, d.written[1]) - keeps := (aHoisted || bHoisted) && (keepsReference(at) || keepsReference(bt)) - if keeps && !d.walk.Alike(at.Common().Provenance, bt.Common().Provenance) { - return relOverlap + keeps := keepsReference(at) || keepsReference(bt) + if keeps && !d.walk.DeclarationsAdmitAlike(at.Common().Provenance, bt.Common().Provenance) { + return relUndecided } - return sameNodes(a, b, aHoisted, bHoisted) + return sameNodes(a, b, hoistedAt(at, d.written[0]), hoistedAt(bt, d.written[1])) } -// keepsReference reports whether td keeps a reference under Unmodeled +// alikeInValues relates a and b, two nodes an answer on their values and +// detail holds the same: copies, but where the two keep entries apart, each +// saying nothing beside the other (judgedAgainst), one type neither a copy of +// the other, so a node built of both holds what each keeps. +func (d declarationSites) alikeInValues(a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef) relation { + rel := d.copies(a, at, b, bt) + if rel == relUndecided || sameKeptEntries(at, bt) { + return rel + } + return byNull(a, b) +} + +// sameKeptEntries reports whether a and b keep alike what a answer on values +// reads under Unmodeled (judgedEntries), wherever each was written. +func sameKeptEntries(a, b ir.TypeDef) bool { + ac, bc := siteless(*a.Common()), siteless(*b.Common()) + return reflect.DeepEqual(judgedEntries(ac.Unmodeled), judgedEntries(bc.Unmodeled)) +} + +// keepsReference reports whether typeDef keeps a reference under Unmodeled // (annotation.WritesReference), the one text of a node a base reads: what else // it holds names nodes by ID, each resolved where it was written, and the nodes // it names are judged as copies in turn. -func keepsReference(td ir.TypeDef) bool { - for _, entry := range td.Common().Unmodeled { +func keepsReference(typeDef ir.TypeDef) bool { + for _, entry := range typeDef.Common().Unmodeled { if annotation.WritesReference(entry.Value) { return true } @@ -648,45 +757,32 @@ func keepsReference(td ir.TypeDef) bool { return false } -// sameNodes judges two nodes sameNode holds equal. Two hoisted copies are one -// type. A node declared elsewhere, a component or one a $ref reached, wins over -// a hoisted copy of itself in either order. Two such nodes are two types the -// source declared apart, so neither is dropped unreported: they overlap. +// sameNodes judges two nodes sameNode holds equal, so admitting the same +// values. A node declared elsewhere, a component or one a $ref reached, wins +// over a hoisted copy of itself in either order. Two hoisted copies are one +// type, and so are two such nodes declared apart: the field names the least +// (position.represents), and a declaration naming the other is kept verbatim +// (fieldFold.apart). func sameNodes(a, b ir.TypeRef, aHoisted, bHoisted bool) relation { switch { - case aHoisted && bHoisted: + case aHoisted == bHoisted: return byNull(a, b) case bHoisted: return firstTypeIsNarrower - case aHoisted: - return secondTypeIsNarrower default: - return relOverlap + return secondTypeIsNarrower } } -// sameNode reports whether a and b are two Literal, Enum or Scalar nodes equal -// but for what names their site (the ID, the naming, whether it was hoisted, -// and the provenance of the node and of what it keeps under Unmodeled) and -// their members' IDs: one declaration written twice, hoisted to two nodes. +// sameNode reports whether a and b are two Literal, Enum, Scalar, List or +// MapT nodes equal but for what names their site and what says nothing of +// their values (unjudgedCommon), and their members' IDs: one declaration +// written twice, hoisted to two nodes, or two declarations saying one thing of +// their values. func sameNode(a, b ir.TypeDef) bool { switch x := a.(type) { - case *ir.Literal: - literal, ok := b.(*ir.Literal) - if !ok { - return false - } - x2, y2 := *x, *literal - x2.TypeCommon, y2.TypeCommon = siteless(x.TypeCommon), siteless(literal.TypeCommon) - return reflect.DeepEqual(x2, y2) - case *ir.Scalar: - scalar, ok := b.(*ir.Scalar) - if !ok { - return false - } - x2, y2 := *x, *scalar - x2.TypeCommon, y2.TypeCommon = siteless(x.TypeCommon), siteless(scalar.TypeCommon) - return reflect.DeepEqual(x2, y2) + case *ir.Literal, *ir.Scalar, *ir.List, *ir.MapT: + return sameBesideCommon(x, b) case *ir.Enum: enum, ok := b.(*ir.Enum) return ok && sameEnum(*x, *enum) @@ -695,13 +791,38 @@ func sameNode(a, b ir.TypeDef) bool { } } +// sameBesideCommon reports whether a and b are nodes of one kind equal but for +// what their TypeCommon says beside their values (unjudgedCommon). It reads +// copies, writing to neither node. +func sameBesideCommon(a, b ir.TypeDef) bool { + av, bv := reflect.ValueOf(a), reflect.ValueOf(b) + if av.Type() != bv.Type() { + return false + } + x, y := reflect.New(av.Type().Elem()).Elem(), reflect.New(bv.Type().Elem()).Elem() + x.Set(av.Elem()) + y.Set(bv.Elem()) + x.FieldByName("TypeCommon").Set(reflect.ValueOf(unjudgedCommon(*a.Common()))) + y.FieldByName("TypeCommon").Set(reflect.ValueOf(unjudgedCommon(*b.Common()))) + return reflect.DeepEqual(x.Interface(), y.Interface()) +} + // sameEnum compares two enums as sameNode does, members by position. func sameEnum(enum, irEnum ir.Enum) bool { - enum.TypeCommon, irEnum.TypeCommon = siteless(enum.TypeCommon), siteless(irEnum.TypeCommon) + enum.TypeCommon, irEnum.TypeCommon = unjudgedCommon(enum.TypeCommon), unjudgedCommon(irEnum.TypeCommon) enum.Members, irEnum.Members = idless(enum.Members), idless(irEnum.Members) return reflect.DeepEqual(enum, irEnum) } +// unjudgedCommon returns typeCommon as a answer on values reads it: siteless, +// with its notes and examples cleared and its kept use-bound keywords dropped +// (judgedEntries), none of which says anything of what the node admits. +func unjudgedCommon(typeCommon ir.TypeCommon) ir.TypeCommon { + typeCommon = siteless(typeCommon) + typeCommon.Docs, typeCommon.Examples, typeCommon.Unmodeled = ir.Docs{}, nil, judgedEntries(typeCommon.Unmodeled) + return typeCommon +} + // siteless returns typeCommon with what names where its node was declared // zeroed: ID, Name, Anonymous, Provenance and the Provenance of each Unmodeled // entry. It copies the Unmodeled map, which belongs to the registry. @@ -729,7 +850,7 @@ func idless(ms []ir.EnumMember) []ir.EnumMember { return out } -// fromTypeformat maps typeformat's verdict on two kinds to a relation. +// fromTypeformat maps typeformat's answer on two kinds to a relation. func fromTypeformat(typeformatRelation typeformat.Relation) relation { if typeformatRelation == typeformat.Same { return relSame @@ -746,89 +867,98 @@ func fromTypeformat(typeformatRelation typeformat.Relation) relation { return relDisjoint } -// isTop reports whether td is the schemaless top type, a bare PrimitiveAny. An -// *ir.Any node is not: this compiler mints one only for a degraded lowering (an -// enum past its member budget, an unconvertible const), which stands for a -// narrower declaration. -func isTop(td ir.TypeDef) bool { - primitive, ok := td.(*ir.Primitive) +// isTop reports whether typeDef is the schemaless top type, a bare +// PrimitiveAny. An *ir.Any node is not: this compiler mints one only for a +// degraded lowering (an enum past its member budget, an unconvertible const), +// which represents a narrower declaration. +func isTop(typeDef ir.TypeDef) bool { + primitive, ok := typeDef.(*ir.Primitive) return ok && primitive.PrimitiveKind == ir.PrimitiveAny } -// topAt reports whether a type a judgment at depth reads as td stands for the -// top type: td is (isTop), or is a chain of alias scalars ending in it that -// says nothing of its values. The chain's first alias may hold docs, a -// deprecation and redaction where it is a field's own type, since a reference -// carries those down to the property using it -// (docs/ir/annotations.md#what-a-reference-carries-down), and a property -// keeps what is written beside its $ref itself. Any other alias holds nothing -// but where it was declared, so no type replacing it loses anything. -func (r registry) topAt(td ir.TypeDef, depth int) bool { - carried := depth == 0 - for range maxTypeResolveDepth { - scalar, alias := td.(*ir.Scalar) - if !alias { - return isTop(td) - } - if scalar.Base == nil || !aliasAddsNothingBeyondBase(scalar, carried) { - return false - } - next, ok := r.resolve(scalar.Base.Target) - if !ok { - return false - } - td, carried = next, false +// topAt reports whether a type a judgment at depth reads as typeDef +// represents the top type: typeDef is (isTop), or is a chain of alias scalars +// ending in it that says nothing of its values. The chain's first alias may +// hold docs, a deprecation and redaction where it is a field's own type, since +// a reference carries those down to the property using it +// (docs/ir/annotations.md#what-a-reference-carries-down). +func (r registryReader) topAt(typeDef ir.TypeDef, depth int) bool { + scalar, alias := typeDef.(*ir.Scalar) + if !alias { + return isTop(typeDef) } - return false + if scalar.Base == nil || !aliasAddsNothingBeyondBase(scalar) && (depth != 0 || !aliasAddsNothingBeyondItsUse(scalar)) { + return false + } + top, read := r.chainAnswerMemos(nil).endsOnTopType.AnswerFor(scalar.Base.Target) + return read && top } // aliasAddsNothingBeyondBase reports whether the alias scalar holds nothing but -// its base and where it was declared, and, where carried, what a reference -// carries down to its use. -func aliasAddsNothingBeyondBase(scalar *ir.Scalar, carried bool) bool { +// its base and where it was declared. +func aliasAddsNothingBeyondBase(scalar *ir.Scalar) bool { + return reflect.DeepEqual(bareAlias(scalar), ir.Scalar{}) +} + +// aliasAddsNothingBeyondItsUse reports whether the alias scalar holds nothing +// but its base, where it was declared, and what a reference carries down to +// the use naming it, its docs, deprecation and redaction +// (docs/ir/annotations.md#what-a-reference-carries-down): an alias that is a +// field's own type adds nothing a type replacing it there loses. +func aliasAddsNothingBeyondItsUse(scalar *ir.Scalar) bool { + bare := bareAlias(scalar) + bare.Docs, bare.Deprecation, bare.Sensitive = ir.Docs{}, nil, false + return reflect.DeepEqual(bare, ir.Scalar{}) +} + +// bareAlias is a copy of scalar with no Base, and siteless. +func bareAlias(scalar *ir.Scalar) ir.Scalar { bare := *scalar bare.TypeCommon, bare.Base = siteless(scalar.TypeCommon), nil - if carried { - bare.Docs, bare.Deprecation, bare.Sensitive = ir.Docs{}, nil, false - } - return reflect.DeepEqual(bare, ir.Scalar{}) + return bare } -// isDegraded reports whether td is an Any node. This compiler mints one only -// for a degraded lowering, so it stands for a declaration the judgment cannot -// see: it is related to nothing, and a drop against it is kept. -func isDegraded(td ir.TypeDef) bool { - _, ok := td.(*ir.Any) +// isDegraded reports whether typeDef is an Any node. This compiler mints one +// only for a degraded lowering, so it represents a declaration the judgment +// cannot see: it is related to nothing, and a drop against it is kept. +func isDegraded(typeDef ir.TypeDef) bool { + _, ok := typeDef.(*ir.Any) return ok } -// nodeAgainstBare compares a Scalar, Enum or Literal (ref, resolved to td) -// against the bare primitive ref bare, of kind bareKind, from the node's side, -// a Scalar by its kind and held format (kindOf, relateKinds). Any other node is -// unrelated. Where an Enum's kind and the bare kind overlap, the pair is -// disjoint when the bare kind refuses every member, as literalAgainst judges one -// value, so an enum with no members is disjoint from any such kind. An enum or a -// literal behind aliases is judged by its members or its value, which the -// aliases can only narrow. -func (j typeJudge) nodeAgainstBare(ref ir.TypeRef, td ir.TypeDef, bare ir.TypeRef, bareKind ir.PrimitiveKind) relation { - end := j.unaliased(td) +// nodeAgainstBare compares a Scalar, Enum or Literal (ref, resolved to +// typeDef, written at sites, judged at depth) against the bare primitive ref +// bare, of kind bareKind, from the node's side. An Enum overlapping the kind is +// disjoint from it where the kind refuses every member, as with no members. An +// enum or a literal behind aliases is judged by its members or its value, +// which the aliases only narrow. +func (j typeJudge) nodeAgainstBare(ref ir.TypeRef, typeDef ir.TypeDef, sites []ir.Provenance, depth int, bare ir.TypeRef, + bareKind ir.PrimitiveKind, +) relation { + end := j.unaliased(typeDef) if lit, ok := end.(*ir.Literal); ok { return literalAgainst(lit.Value, valueKind{primitive: bareKind}, bare.Nullable) } - if _, ok := td.(*ir.Scalar); !ok { - if _, ok = td.(*ir.Enum); !ok { + if _, ok := typeDef.(*ir.Scalar); !ok { + if _, ok = typeDef.(*ir.Enum); !ok { return relUnrelated } } - valueKindValue, ok := j.kindOf(ref) + kind, ok := j.kindOf(ref) if !ok { return relUnrelated } bareK := valueKind{primitive: bareKind} - rel := relateKinds(valueKindValue, bareK) + rel := relateKinds(kind, bareK) if rel == relSame { return firstTypeIsNarrower } + if _, intersects := formatIntersectionKind(j.registryReader, typeDef, bareKind); intersects { + return relIntersect + } + if rel, read := topAliasAgainstKind(j, typeDef, kind, sites, depth, primitiveInstance(bareKind), wholeInstanceKind(bareKind)); read { + return rel + } if rel == secondTypeIsNarrower { rel = relOverlap } @@ -839,23 +969,25 @@ func (j typeJudge) nodeAgainstBare(ref ir.TypeRef, td ir.TypeDef, bare ir.TypeRe } // literalAgainst compares a literal's value with a kind: the literal is -// narrower when the kind admits it. When it does not, the pair is disjoint -// where the kind has a judge, and an overlap where it has none (judged), as -// bytes has none. A null is judged against the kind's side's nullability, not -// its kind: narrower where the side admits null, disjoint where it does not. +// narrower where the kind admits it, the pair disjoint where the kind refuses +// it, and undecided where the kind has no judge (valueKind.admits), as bytes +// has none. A null is judged against the kind's side's nullability, not its +// kind: narrower where the side admits null, disjoint where it does not. func literalAgainst(value ir.Value, kind valueKind, nullable bool) relation { - switch { - case value.Kind == ir.ValueNull && nullable: - return firstTypeIsNarrower - case value.Kind == ir.ValueNull: + if value.Kind == ir.ValueNull { + if nullable { + return firstTypeIsNarrower + } return relDisjoint - case kind.admits(value): + } + switch kind.admits(value) { + case ir.AdmitsYes: return firstTypeIsNarrower - case !kind.judged(): - return relOverlap - default: + case ir.AdmitsNo: return relDisjoint + case ir.AdmitsUnknown: } + return relUndecided } // noMemberMeets reports whether kind refuses every member of en, each judged @@ -870,22 +1002,25 @@ func noMemberMeets(en *ir.Enum, kind valueKind, nullable bool) bool { return true } -// enumMisses reports whether td is an Enum no member of which kind admits, +// enumMisses reports whether typeDef is an Enum no member of which kind admits, // judging each member as literalAgainst does: an enum with no members is // vacuously disjoint, and a kind with no judge refuses nothing. -func enumMisses(td ir.TypeDef, kind valueKind, nullable bool) bool { - en, isEnum := td.(*ir.Enum) +func enumMisses(typeDef ir.TypeDef, kind valueKind, nullable bool) bool { + en, isEnum := typeDef.(*ir.Enum) return isEnum && noMemberMeets(en, kind, nullable) } -// extras is what a list, map or tuple node holds beyond its members: its bounds, -// its encoding, and its TypeCommon, which detailOf reads but where it was -// declared. A node kept for two then loses nothing either holds, a deprecation -// or XML hints included. +// extras is what a list, map or tuple node holds beyond its members: its +// bounds, its encoding, and its TypeCommon, which detailOf reads but where it +// was declared. A node chosen for two then loses nothing either holds, a +// deprecation or XML hints included. Kinds is the JSON instance kinds the +// node's values are, beside which what the other node keeps may say nothing +// (judgedAgainst). type extras struct { Constraints *ir.Constraints Encoding *ir.Encoding Common ir.TypeCommon + Kinds typeformat.JSONInstanceKinds } // boundedNodes compares two nodes of a kind that holds bounds: two Scalars of one @@ -908,15 +1043,15 @@ func (j typeJudge) boundedNodes(at, bt ir.TypeDef, depth int) relation { if !ok { return relUnrelated } - return j.contained(a.ElementType, b.ElementType, extras{a.Constraints, a.Encoding, a.TypeCommon}, - extras{b.Constraints, b.Encoding, b.TypeCommon}, depth) + return j.contained(a.ElementType, b.ElementType, extras{a.Constraints, a.Encoding, a.TypeCommon, typeformat.InstanceArray}, + extras{b.Constraints, b.Encoding, b.TypeCommon, typeformat.InstanceArray}, depth) case *ir.MapT: b, ok := bt.(*ir.MapT) if !ok || !reflect.DeepEqual(a.Key, b.Key) { return relUnrelated } - return j.contained(a.Value, b.Value, extras{a.Constraints, nil, a.TypeCommon}, - extras{b.Constraints, nil, b.TypeCommon}, depth) + return j.contained(a.Value, b.Value, extras{a.Constraints, nil, a.TypeCommon, typeformat.InstanceObject}, + extras{b.Constraints, nil, b.TypeCommon, typeformat.InstanceObject}, depth) case *ir.Tuple: b, ok := bt.(*ir.Tuple) if !ok || depth > 0 { @@ -929,84 +1064,92 @@ func (j typeJudge) boundedNodes(at, bt ir.TypeDef, depth int) relation { } // scalars relates two Scalars of one base and encoding by their bounds and what -// else they say (verdict). Two of one set of values that say the rest +// else they say (answer). Two of one set of values that say the rest // differently are left unrelated, for classify to judge by their kinds, as are // two of different bases or encodings. func (j typeJudge) scalars(a, b *ir.Scalar) relation { if !reflect.DeepEqual(a.Base, b.Base) || !reflect.DeepEqual(a.Encoding, b.Encoding) { return relUnrelated } - values := boundsHolding(a.Constraints, b.Constraints) - detail, adoptable := j.detailOf(extras{Common: a.TypeCommon}, extras{Common: b.TypeCommon}) - if values == bothNodesHoldPart && detail != bothNodesHoldPart { + values := boundsSubsumption(a.Constraints, b.Constraints) + kinds := j.scalarKinds(a) + ac, bc := a.TypeCommon, b.TypeCommon + if kinds&typeformat.InstanceString != 0 { + var aLengths, bLengths ir.Unmodeled + aLengths, ac.Unmodeled = splitKeptLengths(a.Unmodeled) + bLengths, bc.Unmodeled = splitKeptLengths(b.Unmodeled) + values = values.and(keptLengthsHolding(aLengths, bLengths)) + } + detail := j.detailOf(extras{Common: ac, Kinds: kinds}, extras{Common: bc, Kinds: kinds}) + if values == bothSubsume && detail.besideNotes != bothSubsume { return relUnrelated } - return verdict(values, detail, adoptable) + return relationOfValues(values, detail) } -// boundsHolding is the holding of two nodes' bounds (boundsRelation). -func boundsHolding(a, b *ir.Constraints) holding { - holdingValue, _ := holdingOf(boundsRelation(a, b)) - return holdingValue +// boundsSubsumption is the holding of two nodes' bounds (boundsRelation). +func boundsSubsumption(a, b *ir.Constraints) subsumption { + combined, _ := subsumptionOf(boundsRelation(a, b)) + return combined } // tuples compares two tuples position by position, and what may follow the // last, as contained compares two lists' elements: unrelated where their // lengths differ, one alone admits more, or a position holds neither of the -// other's, and otherwise by verdict over every position, their bounds and what +// other's, and otherwise by answer over every position, their bounds and what // else they say. func (j typeJudge) tuples(a, b *ir.Tuple, depth int) relation { if len(a.ElementTypes) != len(b.ElementTypes) || (a.Rest == nil) != (b.Rest == nil) { return relUnrelated } - values := boundsHolding(a.Constraints, b.Constraints) + values := boundsSubsumption(a.Constraints, b.Constraints) for i := range a.ElementTypes { - holding, ok := j.memberHolding(a.ElementTypes[i], b.ElementTypes[i], j.relateAt(a.ElementTypes[i], b.ElementTypes[i], depth+1)) + subsumption, ok := j.memberSubsumption(a.ElementTypes[i], b.ElementTypes[i], j.relateAt(a.ElementTypes[i], b.ElementTypes[i], depth+1)) if !ok { return relUnrelated } - values = values.and(holding) + values = values.and(subsumption) } if a.Rest != nil { - holding, ok := j.memberHolding(*a.Rest, *b.Rest, j.relateAt(*a.Rest, *b.Rest, depth+1)) + subsumption, ok := j.memberSubsumption(*a.Rest, *b.Rest, j.relateAt(*a.Rest, *b.Rest, depth+1)) if !ok { return relUnrelated } - values = values.and(holding) + values = values.and(subsumption) } - detail, adoptable := j.detailOf(extras{Common: a.TypeCommon}, extras{Common: b.TypeCommon}) - return verdict(values, detail, adoptable) + return relationOfValues(values, j.detailOf(extras{Common: a.TypeCommon, Kinds: typeformat.InstanceArray}, + extras{Common: b.TypeCommon, Kinds: typeformat.InstanceArray})) } -// memberHolding is the holding of typeRef and irTypeRef, two members of +// memberSubsumption is the holding of typeRef and irTypeRef, two members of // containers judged rel against each other, null included, and false where // neither holds the other and the fold builds no member of the two: two members -// that meet are built into one, and two that compose, as two models or a model +// that intersect are built into one, and two that compose, as two models or a model // beside a map or a union do (composedBeside), are composed. -func (j typeJudge) memberHolding(typeRef, irTypeRef ir.TypeRef, rel relation) (holding, bool) { - holdingValue, ok := holdingOf(rel) +func (j typeJudge) memberSubsumption(typeRef, irTypeRef ir.TypeRef, rel relation) (subsumption, bool) { + combined, ok := subsumptionOf(rel) if !ok && j.composedBeside(typeRef, irTypeRef) { - holdingValue, ok = holding{}, true + combined, ok = subsumption{}, true } - return holdingValue.and(nullHolding(typeRef, irTypeRef)), ok + return combined.and(nullSubsumption(typeRef, irTypeRef)), ok } // composedBeside reports whether the fold composes typeRef and irTypeRef beside // each other: each a model, a map or a union, and one of them a model // (position.composition). -func (j typeJudge) composedBeside(typeRef, irTypeRef ir.TypeRef) bool { - xn, xok := j.composable(typeRef) - yn, yok := j.composable(irTypeRef) +func (r registryReader) composedBeside(typeRef, irTypeRef ir.TypeRef) bool { + xn, xok := r.composable(typeRef) + yn, yok := r.composable(irTypeRef) _, xModel := xn.(*ir.Model) _, yModel := yn.(*ir.Model) return xok && yok && (xModel || yModel) } -// contained is the verdict on two containers whose members are ae and be: -// verdict over their members, null included, their bounds and what else they +// contained is the answer on two containers whose members are ae and be: +// answer over their members, null included, their bounds and what else they // say. Disjoint members still overlap in a shared value: the empty container, or // a null both members admit. Members neither holding the other nor built into -// one keep the verdict on them. +// one keep the answer on them. func (j typeJudge) contained(ae, be ir.TypeRef, ax, bx extras, depth int) relation { rel := j.relateAt(ae, be, depth+1) if rel == relDisjoint && (ae.Nullable && be.Nullable || admitsEmpty(ax) && admitsEmpty(bx)) { @@ -1014,20 +1157,19 @@ func (j typeJudge) contained(ae, be ir.TypeRef, ax, bx extras, depth int) relati // value of both, so disjoint members overlap. return relOverlap } - member, ok := j.memberHolding(ae, be, rel) + member, ok := j.memberSubsumption(ae, be, rel) if !ok { return rel } - values := member.and(boundsHolding(ax.Constraints, bx.Constraints)) - detail, adoptable := j.detailOf(ax, bx) - return verdict(values, detail, adoptable) + values := member.and(boundsSubsumption(ax.Constraints, bx.Constraints)) + return relationOfValues(values, j.detailOf(ax, bx)) } -// admitsEmpty reports whether a container with extrasValue admits the empty -// one: true when extrasValue.Constraints is nil or holds neither MinItems nor +// admitsEmpty reports whether a container with extras admits the empty +// one: true when extras.Constraints is nil or holds neither MinItems nor // MinProperties above zero. -func admitsEmpty(extrasValue extras) bool { - constraints := extrasValue.Constraints +func admitsEmpty(extras extras) bool { + constraints := extras.Constraints if constraints == nil { return true } @@ -1047,12 +1189,6 @@ func byNull(a, b ir.TypeRef) relation { } } -// maxTypeResolveDepth bounds the Base chain kindOf follows (styleguide -// bounded-recursion rule). A scalar Base chain is far shorter than this in a -// well-formed document, so the cap only guards a pathological or malformed -// registry. -const maxTypeResolveDepth = 64 - // valueKind is what the judgment reads a type's values as: the primitive kind // the type ends in, and the held format that narrows it, if any. A held format // is one a Scalar names whose grammar the compiler holds (heldFormat); it is a @@ -1068,25 +1204,22 @@ type valueKind struct { unjudged bool } -// admits reports whether value is a value of k: of its held format where it has -// one, which narrows string (kindOf), of nothing where k is unjudged, and -// otherwise of its primitive kind. -func (k valueKind) admits(value ir.Value) bool { +// admits judges whether value is a value of k: of its held format where it has +// one, which narrows string (kindOf), and otherwise of its primitive kind +// (ir.PrimitiveAdmits). It answers unknown where k has no judge: bytes has +// none, and neither has a kind an encoding leaves unjudged. +func (k valueKind) admits(value ir.Value) ir.Admission { switch { case k.unjudged: - return false + return ir.AdmitsUnknown case k.format == "": - return Admits(k.primitive, value) + return ir.PrimitiveAdmits(k.primitive, value) default: inFormat, _ := admitsFormat(k.format, value) - return inFormat + return ir.AdmissionOf(inFormat) } } -// judged reports whether k has a judge that can refuse a value: bytes has -// none, and neither has a kind an encoding leaves unjudged. -func (k valueKind) judged() bool { return k.primitive != ir.PrimitiveBytes && !k.unjudged } - // heldFormat returns the format enc names where the compiler holds its grammar // (admitsFormat) and enc says nothing else. An Encoding that also gives a wire // type, a media type or a decoded schema says more of the value than the @@ -1114,19 +1247,19 @@ func relateKinds(a, b valueKind) relation { } } -// formatAgainst relates the held format f to the kind valueKindValue, from f's -// side, as typeformat.Relate relates one string format to another kind: the -// same as itself, within string and the top, an overlap with bytes, which -// octets may spell, and disjoint from any other kind, a string format or +// formatAgainst relates format, a held format, to the kind valueKind, from +// format's side, as typeformat.Relate relates one string format to another +// kind: the same as itself, within string and the top, an overlap with bytes, +// which octets may spell, and disjoint from any other kind, a string format or // another family, since no string satisfies two formats' grammars // (TestAdmitsFormat_SharesNoStringWithAKind). -func formatAgainst(f string, valueKindValue valueKind) relation { +func formatAgainst(format string, valueKind valueKind) relation { switch { - case valueKindValue.format == f: + case valueKind.format == format: return relSame - case valueKindValue.format == "" && (valueKindValue.primitive == ir.PrimitiveString || valueKindValue.primitive == ir.PrimitiveAny): + case valueKind.format == "" && (valueKind.primitive == ir.PrimitiveString || valueKind.primitive == ir.PrimitiveAny): return firstTypeIsNarrower - case valueKindValue.format == "" && valueKindValue.primitive == ir.PrimitiveBytes: + case valueKind.format == "" && valueKind.primitive == ir.PrimitiveBytes: return relOverlap default: return relDisjoint @@ -1137,57 +1270,21 @@ func formatAgainst(f string, valueKindValue valueKind) relation { // (valueKind), reporting false when the target does not end in a single // primitive kind (a model, union, list, tuple, literal, external, or a // base-less opaque scalar). A Scalar leads to the type its values travel as -// (travelsAs), and the first Encoding met decides how the kind reached is read -// (kindUnder). The chain is bounded against a malformed registry. -// -// An Enum resolves via its ValueType (docs/ir/enums.md). A Literal is left -// unresolved: a ValueNumber literal spans integer, number, float and decimal, -// so no one kind stands for it. -func (r registry) kindOf(ref ir.TypeRef) (valueKind, bool) { - id := ref.Target - var first *ir.Encoding - for range maxTypeResolveDepth { - td, ok := r.resolve(id) - if !ok { - return valueKind{}, false - } - switch t := td.(type) { - case *ir.Primitive: - return kindUnder(first, t.PrimitiveKind), true - case *ir.Enum: - return valueKind{primitive: t.ValueType}, true - case *ir.Scalar: - if t.Base == nil { - return valueKind{}, false - } - if first == nil { - first = t.Encoding - } - id = r.travelsAs(t) - default: - return valueKind{}, false - } - } - return valueKind{}, false -} - -// travelsAs returns the type the values of scalar are instances of: its Base, -// but for a Base its Encoding's WireType does not spell, whose values then -// travel as that type, as an instant written as its seconds is a number. A Base -// the WireType spells keeps its own kind, as bytes written as a base64 string -// do. -func (r registry) travelsAs(scalar *ir.Scalar) ir.TypeID { - if scalar.Encoding == nil || scalar.Encoding.WireType == nil { - return scalar.Base.Target - } - base, baseOK := r.resolve(scalar.Base.Target) - wire, wireOK := r.resolve(scalar.Encoding.WireType.Target) - bp, baseIsPrimitive := base.(*ir.Primitive) - wp, wireIsPrimitive := wire.(*ir.Primitive) - if !baseOK || !wireOK || !baseIsPrimitive || !wireIsPrimitive || spelledIn(bp.PrimitiveKind, wp.PrimitiveKind) { - return scalar.Base.Target +// (travelsAs), and the first Encoding met decides how the kind reached is +// read. Each type a walk passes is read once a run. An Enum resolves via its +// ValueType (docs/ir/enums.md); a Literal is left unresolved, as a ValueNumber +// literal spans integer, number, float and decimal. +func (r registryReader) kindOf(ref ir.TypeRef) (valueKind, bool) { + walkEnd := r.chainAnswerMemos(nil).kindAt(ref.Target) + end := kindWalkEndAtEnd(r.resolve, walkEnd.end) + switch { + case !end.read: + return valueKind{}, false + case end.isEnum: + return valueKind{primitive: end.primitive}, true + default: + return kindUnder(walkEnd.encoding, end.primitive), true } - return scalar.Encoding.WireType.Target } // spelledIn reports whether JSON writes a value of primitiveKind as an instance @@ -1219,89 +1316,13 @@ func rewritesText(enc *ir.Encoding, primitiveKind ir.PrimitiveKind) bool { return enc != nil && enc.Name != "" && typeformat.Relate(primitiveKind, ir.PrimitiveString) == typeformat.ANarrower } -// admits reports whether value is a value of the type ref names. A null is -// judged against ref.Nullable, or the top type; any other value against the -// type: a bare primitive by its kind, an Enum by its members, a Literal by its -// value, a Scalar by its base and its Encoding (encodingAdmits), and a list or -// map by each member. A Scalar, list or map also holds value to its Constraints -// (admitsConstraints). Nesting past maxJudgeDepth is refused. -func (r registry) admits(ref ir.TypeRef, value ir.Value) bool { return r.admitsAt(ref, value, 0) } - -func (r registry) admitsAt(ref ir.TypeRef, value ir.Value, depth int) bool { - td, ok := r.resolve(ref.Target) - if !ok || depth > maxJudgeDepth { - return false - } - if value.Kind == ir.ValueNull { - return ref.Nullable || isTop(td) - } - switch t := td.(type) { - case *ir.Primitive: - return Admits(t.PrimitiveKind, value) - case *ir.Any: - return true - case *ir.Enum: - for _, enumMember := range t.Members { - if sameValue(enumMember.Value, value) { - return true - } - } - return false - case *ir.Literal: - return sameValue(t.Value, value) - case *ir.Scalar: - return t.Base != nil && encodingAdmits(t.Encoding, value) && admitsConstraints(t.Constraints, value, depth) && - r.admitsAt(*t.Base, value, depth+1) - case *ir.List: - return value.Kind == ir.ValueList && admitsConstraints(t.Constraints, value, depth) && r.admitsAll(t.ElementType, value.List, depth) - case *ir.MapT: - return value.Kind == ir.ValueObject && admitsConstraints(t.Constraints, value, depth) && - r.admitsFields(t.Value, value.Object, depth) - default: - return false - } -} - -// encodingAdmits reports whether a Scalar with the Encoding enc lets value -// through: any value where it has none, and otherwise only one its held format -// admits (heldFormat), since any other encoding's wire form need not be the -// value's. -func encodingAdmits(enc *ir.Encoding, value ir.Value) bool { - if enc == nil { - return true - } - format, held := heldFormat(enc) - inFormat, _ := admitsFormat(format, value) - return held && inFormat -} - -// admitsAll reports whether every element of vs is a value of element. -func (r registry) admitsAll(element ir.TypeRef, vs []ir.Value, depth int) bool { - for _, value := range vs { - if !r.admitsAt(element, value, depth+1) { - return false - } - } - return true -} - -// admitsFields reports whether every member of fs is a value of element. -func (r registry) admitsFields(element ir.TypeRef, fs []ir.Field, depth int) bool { - for _, field := range fs { - if !r.admitsAt(element, field.Value, depth+1) { - return false - } - } - return true -} - -// sameValue reports whether a and b are one JSON value: canonicalValue spells -// them alike, so a number compares by magnitude, 1 and 1.0 being one, and an -// object by its members whatever their order. A value canonicalValue cannot -// spell compares deeply. +// sameValue reports whether a and b are one JSON value: ir spells them alike +// (ir.CanonicalValueSpelling), so a number compares by magnitude, 1 and 1.0 +// being one, and an object by its members whatever their order. A value ir +// cannot spell compares deeply. func sameValue(a, b ir.Value) bool { - ak, aok := canonicalValue(a, 0) - bk, bok := canonicalValue(b, 0) + ak, aok := ir.CanonicalValueSpelling(a) + bk, bok := ir.CanonicalValueSpelling(b) if aok && bok { return ak == bk } diff --git a/compilers/openapi/internal/merge/typejudge_internal_test.go b/compilers/openapi/internal/merge/typejudge_internal_test.go index d98c6fc10..d2633f557 100644 --- a/compilers/openapi/internal/merge/typejudge_internal_test.go +++ b/compilers/openapi/internal/merge/typejudge_internal_test.go @@ -16,7 +16,7 @@ import ( ) func stubResolve(reg map[ir.TypeID]ir.TypeDef) func(ir.TypeID) (ir.TypeDef, bool) { - return func(id ir.TypeID) (ir.TypeDef, bool) { td, ok := reg[id]; return td, ok } + return func(id ir.TypeID) (ir.TypeDef, bool) { typeDef, ok := reg[id]; return typeDef, ok } } // judgeRegistry is narrowingRegistry plus one node of every kind the arms @@ -56,15 +56,15 @@ func judgeRegistry() map[ir.TypeID]ir.TypeDef { reg["type/scalar-any-doc"] = &ir.Scalar{Base: &ir.TypeRef{Target: "type/primitive/any"}, ID: "type/scalar-any-doc", Docs: ir.Docs{Description: "d"}, Deprecation: &ir.Deprecation{}, Sensitive: true} reg["type/scalar-any-ex"] = &ir.Scalar{Base: &ir.TypeRef{Target: "type/primitive/any"}, - ID: "type/scalar-any-ex", Examples: []ir.Example{{Value: new(number("1"))}}} + ID: "type/scalar-any-ex", Examples: []ir.Example{{Value: new(number("1"))}}, Provenance: ptrAt("/untyped/scalar-any-ex")} reg["type/alias-scalar-any-doc"] = &ir.Scalar{ID: "type/alias-scalar-any-doc", Base: &ir.TypeRef{Target: "type/scalar-any-doc"}} reg["type/alias-doc-scalar-any"] = &ir.Scalar{Base: &ir.TypeRef{Target: "type/scalar-any"}, ID: "type/alias-doc-scalar-any", Docs: ir.Docs{Description: "d"}} reg["type/list-scalar-any"] = &ir.List{ID: "type/list-scalar-any", ElementType: ir.TypeRef{Target: "type/scalar-any"}} - untyped := func(id ir.TypeID, td ir.TypeDef) { - typeCommon := td.Common() + untyped := func(id ir.TypeID, typeDef ir.TypeDef) { + typeCommon := typeDef.Common() typeCommon.ID, typeCommon.Provenance = id, ir.Provenance{Pointer: "/untyped/" + jsontext.Pointer(id)} - reg[id] = td + reg[id] = typeDef } untyped("type/model-untyped", &ir.Model{Properties: []ir.Property{{WireName: "own"}}}) untyped("type/model-untyped-doc", &ir.Model{Properties: []ir.Property{{WireName: "own"}}, @@ -204,7 +204,7 @@ func judgeRegistry() map[ir.TypeID]ir.TypeDef { } // valueTypedEnums adds enums whose value types differ: t/enum--, -// their values joined. +// their values combined. func valueTypedEnums(reg map[ir.TypeID]ir.TypeDef) { for _, e := range []struct { kind ir.PrimitiveKind @@ -226,7 +226,7 @@ func valueTypedEnums(reg map[ir.TypeID]ir.TypeDef) { } // aliasesOverNodes adds aliases over the registry's enums, consts, scalars and -// lists, and the nodes they meet. +// lists, and the nodes they intersect. func aliasesOverNodes(reg map[ir.TypeID]ir.TypeDef) { alias := func(id, base ir.TypeID, bounds *ir.Constraints) { reg[id] = &ir.Scalar{ID: id, Base: &ir.TypeRef{Target: base}, Constraints: bounds} @@ -244,6 +244,8 @@ func aliasesOverNodes(reg map[ir.TypeID]ir.TypeDef) { reg["type/alias-time-ref"].Common().Unmodeled = ir.Unmodeled{"openapi:not": {Value: ir.RawValue(`{"$ref":"n.json"}`)}} reg["type/alias-enum-str-null"] = &ir.Scalar{ID: "type/alias-enum-str-null", Base: &ir.TypeRef{Target: "type/enum-str", Nullable: true}} + reg["type/alias-enum-str-null-doc"] = &ir.Scalar{ID: "type/alias-enum-str-null-doc", Docs: ir.Docs{Description: "d"}, + Base: &ir.TypeRef{Target: "type/enum-str", Nullable: true}} reg["type/enum-str-closed"] = &ir.Enum{ID: "type/enum-str-closed", ValueType: ir.PrimitiveString, Closed: true, Members: []ir.EnumMember{{Value: stringValue("a")}}} reg["type/alias-list-i32-min-doc"].Common().Docs = ir.Docs{Description: "d"} @@ -261,7 +263,7 @@ func (j typeJudge) relate(a, b ir.TypeRef) relation { return j.relateFrom(a, b, func TestTypeJudge_RelateArms(t *testing.T) { t.Parallel() - typeJudgeValue := typeJudge{resolve: stubResolve(judgeRegistry()), sites: atRoot(&stubWalk{})} + typeJudge := typeJudge{resolve: stubResolve(judgeRegistry()), sites: atRoot(&stubWalk{})} primitive := func(primitiveKind ir.PrimitiveKind) ir.TypeID { return primitiveRef(primitiveKind).Target } for _, tc := range []struct { @@ -285,7 +287,7 @@ func TestTypeJudge_RelateArms(t *testing.T) { {"bare int32 against an enum none of whose members it admits", primitive(ir.PrimitiveInt32), "type/enum-big", relDisjoint}, {"an enum with no members against an overlapping kind", "type/enum-none", primitive(ir.PrimitiveInt32), relDisjoint}, {"an enum against a kind with no judge", "type/enum-str", primitive(ir.PrimitiveBytes), relOverlap}, - {"an enum of bytes against a format no member meets", "type/enum-bytes", primitive(ir.PrimitiveUUID), relDisjoint}, + {"an enum of bytes against a format no member intersects", "type/enum-bytes", primitive(ir.PrimitiveUUID), relDisjoint}, {"an enum of string over bare string", "type/enum-str", primitive(ir.PrimitiveString), firstTypeIsNarrower}, {"bare string under an enum of string", primitive(ir.PrimitiveString), "type/enum-str", secondTypeIsNarrower}, {"an enum against another family", "type/enum-str", primitive(ir.PrimitiveInteger), relDisjoint}, @@ -303,7 +305,7 @@ func TestTypeJudge_RelateArms(t *testing.T) { {"a literal the kind admits", "type/lit-1", primitive(ir.PrimitiveInteger), firstTypeIsNarrower}, {"a literal string against integer", "type/lit-a", primitive(ir.PrimitiveInteger), relDisjoint}, {"a literal 1.5 against integer", "type/lit-1.5", primitive(ir.PrimitiveInteger), relDisjoint}, - {"a literal against a kind with no judge", "type/lit-x", primitive(ir.PrimitiveBytes), relOverlap}, + {"a literal against a kind with no judge", "type/lit-x", primitive(ir.PrimitiveBytes), relUndecided}, {"a literal the local date-time kind admits", "type/lit-local", primitive(ir.PrimitiveDatetime), firstTypeIsNarrower}, {"a literal the local date-time kind refuses", "type/lit-x", primitive(ir.PrimitiveDatetime), relDisjoint}, {"a time scalar within string", "type/scalar-time", primitive(ir.PrimitiveString), firstTypeIsNarrower}, @@ -318,13 +320,13 @@ func TestTypeJudge_RelateArms(t *testing.T) { {"a string a time scalar refuses", "type/lit-x", "type/scalar-time", relDisjoint}, {"a time a time scalar's bound refuses", "type/lit-time", "type/scalar-time-max", relDisjoint}, {"a time a time scalar's bound admits", "type/lit-time", "type/scalar-time-roomy", firstTypeIsNarrower}, - {"a literal against an alias of a kind it is not", "type/lit-a", "type/scalar-int", relOverlap}, - {"a time against a time scalar holding detail", "type/lit-time", "type/scalar-time-doc", relMeet}, + {"a literal against an alias of a kind it is not", "type/lit-a", "type/scalar-int", relDisjoint}, + {"a time against a time scalar holding detail", "type/lit-time", "type/scalar-time-doc", relIntersect}, {"a time against an alias of a time scalar", "type/lit-time", "type/alias-time", firstTypeIsNarrower}, - {"a time against a format with no grammar here", "type/lit-time", "type/scalar-email", relOverlap}, + {"a time against a format with no grammar here", "type/lit-time", "type/scalar-email", relUndecided}, {"an enum no member of which is a time", "type/enum-str", "type/scalar-time", relDisjoint}, {"an enum with a time member", "type/enum-time", "type/scalar-time", relOverlap}, - {"two time scalars declared apart", "type/scalar-time", "type/scalar-time-doc", relOverlap}, + {"two time scalars declared apart, one type", "type/scalar-time", "type/scalar-time-doc", relSame}, {"a time scalar against an alias of a date-time", "type/scalar-time", "type/alias-offset", relDisjoint}, {"a time scalar against a format with no grammar here", "type/scalar-time", "type/scalar-email", relOverlap}, {"a null literal against a bare integer", "type/lit-null", primitive(ir.PrimitiveInteger), relDisjoint}, @@ -351,50 +353,52 @@ func TestTypeJudge_RelateArms(t *testing.T) { {"two different literals", "type/lit-a", "type/lit-x", relDisjoint}, {"two identical hoisted literals", "type/lit-a-h1", "type/lit-a-h2", relSame}, {"a named enum against a hoisted copy", "type/enum-str", "type/enum-str-h", firstTypeIsNarrower}, - {"two identical named literals", "type/lit-a", "type/lit-a-twin", relOverlap}, - {"two identical named enums", "type/enum-str", "type/enum-str-twin", relOverlap}, - {"two identical named scalars", "type/scalar-str", "type/scalar-str-twin", relOverlap}, + {"two identical named literals", "type/lit-a", "type/lit-a-twin", relSame}, + {"two identical named enums", "type/enum-str", "type/enum-str-twin", relSame}, + {"two identical named scalars", "type/scalar-str", "type/scalar-str-twin", relSame}, {"a literal against an enum", "type/lit-a", "type/enum-str", relOverlap}, {"a scalar against an enum", "type/scalar-str", "type/enum-str", relOverlap}, {"a scalar against a literal", "type/scalar-str", "type/lit-a", relOverlap}, {"a narrower element", "type/list-int-null", "type/list-i32", secondTypeIsNarrower}, {"a narrower element, the other way", "type/list-i32", "type/list-int-null", firstTypeIsNarrower}, - {"a narrower element that admits null the broader does not", "type/list-int", "type/list-i32-null", relMeet}, + {"a narrower element that admits null the broader does not", "type/list-int", "type/list-i32-null", relIntersect}, {"one element admitting null and the other not", "type/list-i32-null", "type/list-i32", secondTypeIsNarrower}, - {"a loser-only constraint", "type/list-int-min", "type/list-i32", relMeet}, - {"a winner-only constraint", "type/list-int", "type/list-i32-min", secondTypeIsNarrower}, + {"a passed-over-only constraint", "type/list-int-min", "type/list-i32", relIntersect}, + {"a chosen-only constraint", "type/list-int", "type/list-i32-min", secondTypeIsNarrower}, {"the same constraint on both", "type/list-int-min", "type/list-i32-min", secondTypeIsNarrower}, - {"two lists alike, declared apart", "type/list-i32", "type/list-i32-twin", relOverlap}, + {"two lists alike, declared apart", "type/list-i32", "type/list-i32-twin", relSame}, {"two hoisted copies of one list", "type/list-i32-h1", "type/list-i32-h2", relSame}, {"a list declared apart against a hoisted copy", "type/list-i32", "type/list-i32-h1", firstTypeIsNarrower}, {"a map declared apart against a hoisted copy", "type/map-int", "type/map-int-h", firstTypeIsNarrower}, {"a list another document hoists at the declaration's pointer", "type/list-i32-other", "type/list-i32-h1", firstTypeIsNarrower}, {"two lists of one element, one constrained", "type/list-i32-min", "type/list-i32", firstTypeIsNarrower}, {"two lists of one element, one bound tighter", "type/list-i32-min2", "type/list-i32-min", firstTypeIsNarrower}, - {"two lists of one element, each adding a bound", "type/list-i32-min", "type/list-i32-max", relMeet}, + {"two lists of one element, each adding a bound", "type/list-i32-min", "type/list-i32-max", relIntersect}, {"a narrower element and bounds that say all the other's do", "type/list-i32-min2", "type/list-int-min1", firstTypeIsNarrower}, - {"a narrower element and looser bounds", "type/list-i32-min", "type/list-int-min2", relMeet}, - {"a narrower element and a bound only the broader says", "type/list-i32-min", "type/list-int-max", relMeet}, - {"two lists of one element differing beside a bound", "type/list-i32-described", "type/list-i32-max", relMeet}, + {"a narrower element and looser bounds", "type/list-i32-min", "type/list-int-min2", relIntersect}, + {"a narrower element and a bound only the broader says", "type/list-i32-min", "type/list-int-max", relIntersect}, + {"two lists of one element differing beside a bound", "type/list-i32-described", "type/list-i32-max", relIntersect}, {"a narrower element holding detail the broader lacks", "type/list-i32-described", "type/list-int", firstTypeIsNarrower}, {"a narrower element holding the detail the broader holds", "type/list-i32-described", "type/list-int-described", firstTypeIsNarrower}, - {"a narrower element lacking detail the broader holds", "type/list-i32", "type/list-int-described", relMeet}, + {"a narrower element lacking detail the broader holds", "type/list-i32", "type/list-int-described", relIntersect}, {"a narrower element lacking examples the broader gives", "type/list-i32", "type/list-int-exampled", relOverlap}, - {"two lists of one element, one described", "type/list-i32", "type/list-i32-described", relOverlap}, - {"two hoisted lists of one element, one described", "type/list-i32-h1", "type/list-i32-h-described", relOverlap}, - {"a narrower element lacking what the broader keeps", "type/list-i32", "type/list-int-kept", relMeet}, - {"two opaque scalars, one described", "type/scalar-opaque", "type/scalar-opaque-doc", relUnrelated}, + {"two lists of one element, one described", "type/list-i32", "type/list-i32-described", relSame}, + // A description says nothing of a value (GitHub #1889), so two nodes + // differing in one are one type, hoisted or declared apart. + {"two hoisted lists of one element, one described", "type/list-i32-h1", "type/list-i32-h-described", relSame}, + {"a narrower element lacking what the broader keeps", "type/list-i32", "type/list-int-kept", relIntersect}, + {"two opaque scalars, one described", "type/scalar-opaque", "type/scalar-opaque-doc", relSame}, {"an enum within another", "type/enum-str", "type/enum-ab", firstTypeIsNarrower}, {"an enum within another saying its shared member otherwise", "type/enum-str", "type/enum-ab-doc", relOverlap}, - {"two lists of lists whose elements meet", "type/lists-min", "type/lists-max", relMeet}, + {"two lists of lists whose elements intersect", "type/lists-min", "type/lists-max", relIntersect}, {"two lists of lists, one element tighter", "type/lists-min2", "type/lists-min", firstTypeIsNarrower}, - {"two maps of one value, each adding a bound", "type/map-min", "type/map-max", relMeet}, + {"two maps of one value, each adding a bound", "type/map-min", "type/map-max", relIntersect}, {"two maps of one value, one constrained", "type/map-min", "type/map-bare", firstTypeIsNarrower}, {"two scalars alike but for a bound", "type/scalar-enc-min", "type/scalar-enc", firstTypeIsNarrower}, - {"two scalars, each adding a bound", "type/scalar-enc-min", "type/scalar-enc-max", relMeet}, - {"two scalars differing in a keyword with no order", "type/scalar-enc-a", "type/scalar-enc-b", relMeet}, + {"two scalars, each adding a bound", "type/scalar-enc-min", "type/scalar-enc-max", relIntersect}, + {"two scalars differing in a keyword with no order", "type/scalar-enc-a", "type/scalar-enc-b", relIntersect}, {"two scalars differing beside their bounds", "type/scalar-enc-min", "type/scalar-int", relOverlap}, - {"two tuples, each adding a bound", "type/tuple-min", "type/tuple-max", relMeet}, + {"two tuples, each adding a bound", "type/tuple-min", "type/tuple-max", relIntersect}, {"two tuples, one constrained", "type/tuple-min", "type/tuple", firstTypeIsNarrower}, {"two tuples of different lengths", "type/tuple", "type/tuple-long", relUnrelated}, {"two tuples, one position narrower", "type/tuple", "type/tuple-int", firstTypeIsNarrower}, @@ -402,7 +406,7 @@ func TestTypeJudge_RelateArms(t *testing.T) { {"a tuple with a rest against one with none", "type/tuple", "type/tuple-rest", relUnrelated}, {"two tuples, one rest narrower", "type/tuple-rest", "type/tuple-rest-int", firstTypeIsNarrower}, {"two tuples whose rests share no value", "type/tuple-rest", "type/tuple-rest-str", relUnrelated}, - {"two literals of one value, one described", "type/lit-a", "type/lit-a-doc", relOverlap}, + {"two literals of one value, one described", "type/lit-a", "type/lit-a-doc", relSame}, {"a narrower element keeping a key the broader keeps otherwise", "type/list-i32-kept-other", "type/list-int-kept", relOverlap}, {"a tuple against a list", "type/tuple", "type/list-i32", relUnrelated}, {"disjoint elements overlap in the empty list", "type/list-str", "type/list-i32", relOverlap}, @@ -421,51 +425,75 @@ func TestTypeJudge_RelateArms(t *testing.T) { {"an enum within another of a broader value type", "type/enum-integer-1", "type/enum-number-12", firstTypeIsNarrower}, {"one set of values of a narrower value type", "type/enum-integer-12", "type/enum-number-12", firstTypeIsNarrower}, {"one set of values of another type in another order", "type/enum-integer-12", "type/enum-number-21", relOverlap}, - {"an enum within another of a narrower value type", "type/enum-number-1", "type/enum-integer-12", relMeet}, - {"enums of different value types sharing some values", "type/enum-number-12.5", "type/enum-integer-13", relMeet}, + {"an enum within another of a narrower value type", "type/enum-number-1", "type/enum-integer-12", relIntersect}, + {"enums of different value types sharing some values", "type/enum-number-12.5", "type/enum-integer-13", relIntersect}, {"enums of different value types sharing none", "type/enum-number-2.5", "type/enum-integer-13", relDisjoint}, {"enums of overlapping value types sharing values", "type/enum-int32-12", "type/enum-uint32-12", relOverlap}, {"enums of overlapping value types sharing none", "type/enum-int32-1", "type/enum-uint32-2", relDisjoint}, {"an alias of an enum no member of which a kind admits", "type/alias-enum-str-max", primitive(ir.PrimitiveUUID), relDisjoint}, {"an alias of a const a kind refuses", "type/alias-lit-a-max", primitive(ir.PrimitiveInteger), relDisjoint}, {"an alias of a const a kind admits", "type/alias-lit-a-max", primitive(ir.PrimitiveString), firstTypeIsNarrower}, - {"an alias of an enum against a node of a kind no member meets", "type/alias-enum-big-max", "type/scalar-i32-doc", relDisjoint}, + {"an alias of an enum against a node of a kind no member intersects", "type/alias-enum-big-max", "type/scalar-i32-doc", relDisjoint}, {"an alias of an enum against the enum", "type/alias-enum-ab", "type/enum-ab", firstTypeIsNarrower}, - {"an alias of an enum against one it meets", "type/alias-enum-ab", "type/enum-bc", relMeet}, - {"an alias of a list against one it meets", "type/alias-list-i32-min", "type/list-i32-max", relMeet}, - {"an alias of a time scalar holding a bound a time meets", "type/lit-time", "type/alias-scalar-time", firstTypeIsNarrower}, + {"an alias of an enum against one it intersects", "type/alias-enum-ab", "type/enum-bc", relIntersect}, + {"an alias of a list against one it intersects", "type/alias-list-i32-min", "type/list-i32-max", relIntersect}, + {"an alias of a time scalar holding a bound a time intersects", "type/lit-time", "type/alias-scalar-time", firstTypeIsNarrower}, {"an alias of a time holding docs a time scalar gives otherwise", "type/alias-lit-time-doc", "type/scalar-time-doc", relOverlap}, - {"two aliases of one list saying it otherwise, judged as two scalars", "type/alias-list-i32-min", "type/alias-list-i32-min-doc", relUnrelated}, + {"two aliases of one list saying it otherwise, judged as two scalars", "type/alias-list-i32-min", "type/alias-list-i32-min-doc", relSame}, {"a time against an alias of a time scalar the view cannot read", "type/lit-time", "type/alias-time-ref", relOverlap}, {"two enums differing in closedness", "type/enum-str", "type/enum-str-closed", relOverlap}, - {"an alias of the top type against the top it stands for", "type/alias-doc-scalar-any", "type/scalar-any", firstTypeIsNarrower}, - {"an alias adding null to an enum against the enum", "type/alias-enum-str-null", "type/enum-str", secondTypeIsNarrower}, - {"an alias adding null to an enum against a kind holding it", "type/alias-enum-str-null", primitive(ir.PrimitiveString), relOverlap}, + {"an alias of the top type against the top it represents", "type/alias-doc-scalar-any", "type/scalar-any", firstTypeIsNarrower}, + // The alias's null is the use's to say, so it is the enum. + {"an alias adding null to an enum against the enum", "type/alias-enum-str-null", "type/enum-str", firstTypeIsNarrower}, + {"an alias adding null to an enum against a kind holding it", "type/alias-enum-str-null", primitive(ir.PrimitiveString), firstTypeIsNarrower}, + {"an alias adding null and docs to an enum against its twin", "type/alias-enum-str-null-doc", "type/enum-str-twin", relSame}, } { want := tc.want - assert.Equal(t, want, typeJudgeValue.relate(ref(tc.a), ref(tc.b)), tc.name) - assert.Equal(t, want.flipped(), typeJudgeValue.relate(ref(tc.b), ref(tc.a)), "%s, swapped", tc.name) + assert.Equal(t, want, typeJudge.relate(ref(tc.a), ref(tc.b)), tc.name) + assert.Equal(t, want.flipped(), typeJudge.relate(ref(tc.b), ref(tc.a)), "%s, swapped", tc.name) + } + + // A use admitting null reads the null an alias on the chain adds, so the + // alias holds the enum it adds null alone to, whoever's use admits null. + // Against a kind holding the enum, whose use admits none, the alias is + // within it: the field admits null only where both uses do (intersectNull), + // so that null reaches no intersect. + nullableUse := ref("type/alias-enum-str-null") + nullableUse.Nullable = true + nullableEnum := ref("type/enum-str") + nullableEnum.Nullable = true + for _, tc := range []struct { + name string + other ir.TypeRef + want relation + }{ + {"the enum", ref("type/enum-str"), secondTypeIsNarrower}, + {"the enum admitting null", nullableEnum, secondTypeIsNarrower}, + {"a kind holding it", ref(primitive(ir.PrimitiveString)), firstTypeIsNarrower}, + } { + assert.Equal(t, tc.want, typeJudge.relate(nullableUse, tc.other), "a nullable use of an alias adding null, against %s", tc.name) + assert.Equal(t, tc.want.flipped(), typeJudge.relate(tc.other, nullableUse), "%s, swapped", tc.name) } nullTwin := ref("type/lit-a-h2") nullTwin.Nullable = true - assert.Equal(t, secondTypeIsNarrower, typeJudgeValue.relate(nullTwin, ref("type/lit-a-h1")), "identical hoisted nodes order by null") - assert.Equal(t, firstTypeIsNarrower, typeJudgeValue.relate(ref("type/lit-a-h1"), nullTwin), "in either order") + assert.Equal(t, secondTypeIsNarrower, typeJudge.relate(nullTwin, ref("type/lit-a-h1")), "identical hoisted nodes order by null") + assert.Equal(t, firstTypeIsNarrower, typeJudge.relate(ref("type/lit-a-h1"), nullTwin), "in either order") nullInt := primitiveRef(ir.PrimitiveInteger) nullInt.Nullable = true - assert.Equal(t, firstTypeIsNarrower, typeJudgeValue.relate(ref("type/lit-null"), nullInt), "a null literal against a nullable integer") - assert.Equal(t, secondTypeIsNarrower, typeJudgeValue.relate(nullInt, ref("type/lit-null")), "a nullable integer against a null literal") + assert.Equal(t, firstTypeIsNarrower, typeJudge.relate(ref("type/lit-null"), nullInt), "a null literal against a nullable integer") + assert.Equal(t, secondTypeIsNarrower, typeJudge.relate(nullInt, ref("type/lit-null")), "a nullable integer against a null literal") nullString := primitiveRef(ir.PrimitiveString) nullString.Nullable = true - assert.Equal(t, firstTypeIsNarrower, typeJudgeValue.relate(ref("type/alias-enum-str-null"), nullString), + assert.Equal(t, firstTypeIsNarrower, typeJudge.relate(ref("type/alias-enum-str-null"), nullString), "an alias admitting null within a kind whose reference admits null too") nullTime := ref("type/scalar-time") nullTime.Nullable = true - assert.Equal(t, firstTypeIsNarrower, typeJudgeValue.relate(ref("type/lit-null"), nullTime), "a null literal against a time scalar admitting null") - assert.Equal(t, relDisjoint, typeJudgeValue.relate(ref("type/lit-null"), ref("type/scalar-time")), "and against one that does not") + assert.Equal(t, firstTypeIsNarrower, typeJudge.relate(ref("type/lit-null"), nullTime), "a null literal against a time scalar admitting null") + assert.Equal(t, relDisjoint, typeJudge.relate(ref("type/lit-null"), ref("type/scalar-time")), "and against one that does not") } // TestRelateKinds_ReadsAHeldFormatAsAStringFormat pins formatAgainst on the @@ -496,7 +524,7 @@ func TestRelateKinds_ReadsAHeldFormatAsAStringFormat(t *testing.T) { // kind, holds none. func TestKindOf_TheFirstEncodingDecidesTheFormat(t *testing.T) { t.Parallel() - typeJudgeValue := typeJudge{resolve: stubResolve(judgeRegistry()), sites: atRoot(&stubWalk{})} + typeJudge := typeJudge{resolve: stubResolve(judgeRegistry()), sites: atRoot(&stubWalk{})} for _, tc := range []struct { id ir.TypeID want valueKind @@ -510,7 +538,7 @@ func TestKindOf_TheFirstEncodingDecidesTheFormat(t *testing.T) { {"type/scalar-time-schema", valueKind{primitive: ir.PrimitiveString}}, {"type/scalar-email", valueKind{primitive: ir.PrimitiveString}}, } { - got, ok := typeJudgeValue.kindOf(ref(tc.id)) + got, ok := typeJudge.kindOf(ref(tc.id)) require.True(t, ok, "%s", tc.id) assert.Equal(t, tc.want.primitive, got.primitive, "%s", tc.id) assert.Equal(t, tc.want.format, got.format, "%s: the held format", tc.id) @@ -564,7 +592,7 @@ func encodedRegistry() map[ir.TypeID]ir.TypeDef { // A WireType or base that is no primitive leaves the base read as it is. func TestKindOf_AnEncodedScalarIsReadAsItsValuesTravel(t *testing.T) { t.Parallel() - typeJudgeValue := typeJudge{resolve: stubResolve(encodedRegistry()), sites: atRoot(&stubWalk{})} + typeJudge := typeJudge{resolve: stubResolve(encodedRegistry()), sites: atRoot(&stubWalk{})} for id, want := range map[ir.TypeID]valueKind{ "type/unixtime-int": {primitive: ir.PrimitiveInteger}, "type/alias-unixtime-int": {primitive: ir.PrimitiveInteger}, @@ -582,7 +610,7 @@ func TestKindOf_AnEncodedScalarIsReadAsItsValuesTravel(t *testing.T) { "type/wire-node": {primitive: ir.PrimitiveDatetimeOffset, unjudged: true}, "type/alias-wired": {primitive: ir.PrimitiveDatetimeOffset, unjudged: true}, } { - got, ok := typeJudgeValue.kindOf(ref(id)) + got, ok := typeJudge.kindOf(ref(id)) require.True(t, ok, "%s", id) assert.Equal(t, want, got, "%s", id) } @@ -596,7 +624,7 @@ func TestKindOf_AnEncodedScalarIsReadAsItsValuesTravel(t *testing.T) { // would refuse the text, while a bare datetime_offset still refuses it. func TestTypeJudge_AnEncodedScalarRelatesAsItsValues(t *testing.T) { t.Parallel() - typeJudgeValue := typeJudge{resolve: stubResolve(encodedRegistry()), sites: atRoot(&stubWalk{})} + typeJudge := typeJudge{resolve: stubResolve(encodedRegistry()), sites: atRoot(&stubWalk{})} primitive := func(primitiveKind ir.PrimitiveKind) ir.TypeID { return primitiveRef(primitiveKind).Target } for _, tc := range []struct { a, b ir.TypeID @@ -621,24 +649,24 @@ func TestTypeJudge_AnEncodedScalarRelatesAsItsValues(t *testing.T) { {"type/byte", "type/base64url", relOverlap}, {"type/enum-http-date", primitive(ir.PrimitiveDatetimeOffset), relDisjoint}, } { - assert.Equal(t, tc.want, typeJudgeValue.relate(ref(tc.a), ref(tc.b)), "%s against %s", tc.a, tc.b) - assert.Equal(t, tc.want.flipped(), typeJudgeValue.relate(ref(tc.b), ref(tc.a)), "%s against %s", tc.b, tc.a) + assert.Equal(t, tc.want, typeJudge.relate(ref(tc.a), ref(tc.b)), "%s against %s", tc.a, tc.b) + assert.Equal(t, tc.want.flipped(), typeJudge.relate(ref(tc.b), ref(tc.a)), "%s against %s", tc.b, tc.a) } } -// TestValueKind_AnUnjudgedKindAdmitsNothing pins admits and literalAgainst on -// a kind an encoding leaves unjudged: no value is shown to be one of it, an -// RFC 3339 text no more than any, so a literal overlaps it rather than being -// narrower or disjoint, as against bytes. -func TestValueKind_AnUnjudgedKindAdmitsNothing(t *testing.T) { +// TestValueKind_AnUnjudgedKindAnswersUnknown pins admits and literalAgainst +// on a kind an encoding leaves unjudged: no value is shown to be one of it or +// not, an RFC 3339 text no more than any, so a literal is undecided against it +// rather than narrower, overlapping or disjoint, as against bytes. +func TestValueKind_AnUnjudgedKindAnswersUnknown(t *testing.T) { t.Parallel() offset := valueKind{primitive: ir.PrimitiveDatetimeOffset} unjudged := valueKind{primitive: ir.PrimitiveDatetimeOffset, unjudged: true} for _, value := range []ir.Value{stringValue("2020-01-01T00:00:00Z"), stringValue("Sun, 06 Nov 1994 08:49:37 GMT"), number("1")} { - assert.False(t, unjudged.admits(value), "%v", value) - assert.Equal(t, relOverlap, literalAgainst(value, unjudged, false), "%v", value) + assert.Equal(t, ir.AdmitsUnknown, unjudged.admits(value), "%v", value) + assert.Equal(t, relUndecided, literalAgainst(value, unjudged, false), "%v", value) } - assert.True(t, offset.admits(stringValue("2020-01-01T00:00:00Z")), "the judged kind reads its own text") + assert.Equal(t, ir.AdmitsYes, offset.admits(stringValue("2020-01-01T00:00:00Z")), "the judged kind reads its own text") assert.Equal(t, relDisjoint, literalAgainst(stringValue("Sun, 06 Nov 1994 08:49:37 GMT"), offset, false)) } @@ -662,26 +690,30 @@ func TestKindOf_ANumberAsTextIsAString(t *testing.T) { reg["type/alias-num-text"] = &ir.Scalar{ID: "type/alias-num-text", Base: &ir.TypeRef{Target: "type/num-text"}} reg["type/num"] = &ir.Scalar{ID: "type/num", Base: &i64, Encoding: &ir.Encoding{Name: "string"}} reg["type/bytes-b64"] = &ir.Scalar{ID: "type/bytes-b64", Base: &b, Encoding: wire()} - typeJudgeValue := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{})} + typeJudge := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{})} for id, want := range map[ir.TypeID]valueKind{ "type/num-text": {primitive: ir.PrimitiveString}, "type/alias-num-text": {primitive: ir.PrimitiveString}, "type/num": {primitive: ir.PrimitiveInt64}, "type/bytes-b64": {primitive: ir.PrimitiveBytes, unjudged: true}, } { - got, ok := typeJudgeValue.kindOf(ref(id)) + got, ok := typeJudge.kindOf(ref(id)) require.True(t, ok, "%s", id) assert.Equal(t, want, got, "%s", id) } - stringValue, _ := typeJudgeValue.kindOf(primitiveRef(ir.PrimitiveString)) - number, _ := typeJudgeValue.kindOf(primitiveRef(ir.PrimitiveInt64)) - text, _ := typeJudgeValue.kindOf(ref("type/num-text")) - assert.Equal(t, relSame, relateKinds(stringValue, text), "a string and a number as text share their instances") + stringKind, _ := typeJudge.kindOf(primitiveRef(ir.PrimitiveString)) + number, _ := typeJudge.kindOf(primitiveRef(ir.PrimitiveInt64)) + text, _ := typeJudge.kindOf(ref("type/num-text")) + assert.Equal(t, relSame, relateKinds(stringKind, text), "a string and a number as text share their instances") assert.Equal(t, relDisjoint, relateKinds(number, text), "a JSON number is no string") } -func TestTypeJudge_AdmitsPerNode(t *testing.T) { +// TestFoldValueAdmissionReader_AdmitsPerNode pins the fold's value admission +// reader (NewFoldValueAdmissionReader) over the nodes a fold intersects, a held +// format's grammar among them (sourceFormatAdmissions): a value is adopted +// only where it says yes. +func TestFoldValueAdmissionReader_AdmitsPerNode(t *testing.T) { t.Parallel() reg := judgeRegistry() - reg["type/enum-1"] = &ir.Enum{ID: "type/enum-1", ValueType: ir.PrimitiveInteger, + reg["type/enum-1"] = &ir.Enum{ID: "type/enum-1", ValueType: ir.PrimitiveInteger, Closed: true, Members: []ir.EnumMember{{Value: number("1")}, {Value: number("2")}}} reg["type/list-1"] = &ir.List{ID: "type/list-1", ElementType: ref("type/enum-1")} reg["type/map-1"] = &ir.MapT{ID: "type/map-1", Value: ref("type/enum-1")} @@ -690,69 +722,79 @@ func TestTypeJudge_AdmitsPerNode(t *testing.T) { Constraints: &ir.Constraints{MaxLength: &short}} reg["type/list-pair"] = &ir.List{ID: "type/list-pair", ElementType: ref("type/enum-1"), Constraints: &ir.Constraints{MaxItems: &two}} reg["type/map-pair"] = &ir.MapT{ID: "type/map-pair", Value: ref("type/enum-1"), Constraints: &ir.Constraints{MaxProperties: &two}} - typeJudgeValue := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{})} + reader := NewFoldValueAdmissionReader(stubResolve(reg), ir.NewAliasChainIndex(stubResolve(reg))) + admits := func(typeRef ir.TypeRef, value ir.Value) bool { return reader.Admits(typeRef, value) == ir.AdmitsYes } list := func(vs ...ir.Value) ir.Value { return ir.Value{Kind: ir.ValueList, List: vs} } obj := func(value ir.Value) ir.Value { return ir.Value{Kind: ir.ValueObject, Object: []ir.Field{{Name: "k", Value: value}}} } - assert.True(t, typeJudgeValue.admits(ref("type/enum-1"), number("1.0")), "an enum member by magnitude") - assert.False(t, typeJudgeValue.admits(ref("type/enum-1"), number("3"))) - assert.True(t, typeJudgeValue.admits(ref("type/lit-a"), stringValue("a"))) - assert.False(t, typeJudgeValue.admits(ref("type/lit-a"), stringValue("b"))) - assert.True(t, typeJudgeValue.admits(ref("type/scalar-int"), number("3"))) - assert.False(t, typeJudgeValue.admits(ref("type/scalar-enc"), number("3")), "an encoded scalar admits nothing") - assert.False(t, typeJudgeValue.admits(ref("type/scalar-opaque"), number("3")), "an opaque scalar admits nothing") - assert.True(t, typeJudgeValue.admits(ref("type/scalar-time"), stringValue("12:00:00Z")), "a held format admits what its grammar does") - assert.False(t, typeJudgeValue.admits(ref("type/scalar-time"), stringValue("12:00:00")), "and refuses what it does not") - assert.False(t, typeJudgeValue.admits(ref("type/scalar-time-max"), stringValue("12:00:00Z")), "a held format's bounds are judged too") - assert.True(t, typeJudgeValue.admits(ref("type/alias-time"), stringValue("12:00:00Z")), "an alias of it admits what it does") - assert.False(t, typeJudgeValue.admits(ref("type/scalar-time-media"), stringValue("12:00:00Z")), "an encoding saying more admits nothing") - assert.False(t, typeJudgeValue.admits(ref("type/scalar-email"), stringValue("a@b.c")), "a format with no grammar here admits nothing") - assert.False(t, typeJudgeValue.admits(ref("type/scalar-time-int"), stringValue("12:00:00Z")), "nor does a time format over an integer") - assert.True(t, typeJudgeValue.admits(ref("type/any"), stringValue("a"))) - assert.False(t, typeJudgeValue.admits(ref("type/model"), stringValue("a"))) - assert.False(t, typeJudgeValue.admits(ref("type/absent"), stringValue("a"))) - assert.True(t, typeJudgeValue.admits(ref("type/list-1"), list(number("1"), number("2")))) - assert.False(t, typeJudgeValue.admits(ref("type/list-1"), list(number("1"), number("3")))) - assert.False(t, typeJudgeValue.admits(ref("type/list-1"), stringValue("a"))) - assert.True(t, typeJudgeValue.admits(ref("type/map-1"), obj(number("2")))) - assert.False(t, typeJudgeValue.admits(ref("type/map-1"), obj(number("3")))) - assert.False(t, typeJudgeValue.admits(ref("type/map-1"), list(number("1")))) - assert.True(t, typeJudgeValue.admits(ref("type/scalar-short"), stringValue("abc")), "a scalar's constraints admit what meets them") - assert.False(t, typeJudgeValue.admits(ref("type/scalar-short"), stringValue("abcd")), "and refuse what does not") - assert.False(t, typeJudgeValue.admits(ref("type/list-pair"), list(number("1"), number("2"), number("1"))), "a list's constraints are judged") + assert.True(t, admits(ref("type/enum-1"), number("1.0")), "an enum member by magnitude") + assert.False(t, admits(ref("type/enum-1"), number("3"))) + assert.True(t, admits(ref("type/lit-a"), stringValue("a"))) + assert.False(t, admits(ref("type/lit-a"), stringValue("b"))) + assert.True(t, admits(ref("type/scalar-int"), number("3"))) + assert.False(t, admits(ref("type/scalar-enc"), number("3")), "an encoded scalar admits nothing") + assert.False(t, admits(ref("type/scalar-opaque"), number("3")), "an opaque scalar admits nothing") + assert.True(t, admits(ref("type/scalar-time"), stringValue("12:00:00Z")), "a held format admits what its grammar does") + assert.False(t, admits(ref("type/scalar-time"), stringValue("12:00:00")), "and refuses what it does not") + assert.False(t, admits(ref("type/scalar-time-max"), stringValue("12:00:00Z")), "a held format's bounds are judged too") + assert.True(t, admits(ref("type/alias-time"), stringValue("12:00:00Z")), "an alias of it admits what it does") + assert.False(t, admits(ref("type/scalar-time-media"), stringValue("12:00:00Z")), "an encoding saying more admits nothing") + assert.False(t, admits(ref("type/scalar-email"), stringValue("a@b.c")), "a format with no grammar here admits nothing") + assert.False(t, admits(ref("type/scalar-time-int"), stringValue("12:00:00Z")), "nor does a time format over an integer") + assert.True(t, admits(ref("type/any"), stringValue("a"))) + assert.False(t, admits(ref("type/model"), stringValue("a"))) + assert.False(t, admits(ref("type/absent"), stringValue("a"))) + assert.True(t, admits(ref("type/list-1"), list(number("1"), number("2")))) + assert.False(t, admits(ref("type/list-1"), list(number("1"), number("3")))) + assert.False(t, admits(ref("type/list-1"), stringValue("a"))) + assert.True(t, admits(ref("type/map-1"), obj(number("2")))) + assert.False(t, admits(ref("type/map-1"), obj(number("3")))) + assert.False(t, admits(ref("type/map-1"), list(number("1")))) + assert.True(t, admits(ref("type/scalar-short"), stringValue("abc")), "a scalar's constraints admit what intersects them") + assert.False(t, admits(ref("type/scalar-short"), stringValue("abcd")), "and refuse what does not") + assert.False(t, admits(ref("type/list-pair"), list(number("1"), number("2"), number("1"))), "a list's constraints are judged") pairs := ir.Value{Kind: ir.ValueObject, Object: []ir.Field{{Name: "a", Value: number("1")}, {Name: "b", Value: number("1")}, {Name: "c", Value: number("2")}}} - assert.False(t, typeJudgeValue.admits(ref("type/map-pair"), pairs), "and so are a map's") - assert.False(t, typeJudgeValue.admits(ref("type/cycle"), list(list(list(list(list(list(list(list(list(list())))))))))), - "a list nested past the cap is refused") + assert.False(t, admits(ref("type/map-pair"), pairs), "and so are a map's") + nested := list() + for range 70 { + nested = list(nested) + } + assert.True(t, admits(ref("type/cycle"), list(list(list(list(list(list(list(list(list(list())))))))))), + "a list nested within the reader's bound is judged") + assert.False(t, admits(ref("type/cycle"), nested), "one nested well past it is not admitted") } func TestRelation_Flipped(t *testing.T) { t.Parallel() - for _, relationValue := range []relation{relUnrelated, relDisjoint, relOverlap, relSame, relMeet} { - assert.Equal(t, relationValue, relationValue.flipped()) + for _, relation := range []relation{relUnrelated, relDisjoint, relOverlap, relSame, relIntersect} { + assert.Equal(t, relation, relation.flipped()) } assert.Equal(t, secondTypeIsNarrower, firstTypeIsNarrower.flipped()) assert.Equal(t, firstTypeIsNarrower, secondTypeIsNarrower.flipped()) } -func TestTypeJudge_NullIsJudgedByNullability(t *testing.T) { +// TestFoldValueAdmissionReader_JudgesNullByTheReference pins null as the +// fold's reader reads it: by the reference's bit, and always for the top type. +func TestFoldValueAdmissionReader_JudgesNullByTheReference(t *testing.T) { t.Parallel() null := ir.Value{Kind: ir.ValueNull} - typeJudgeValue := typeJudge{resolve: stubResolve(narrowingRegistry()), sites: atRoot(&stubWalk{})} + lookup := stubResolve(narrowingRegistry()) + reader := NewFoldValueAdmissionReader(lookup, ir.NewAliasChainIndex(lookup)) + admits := func(typeRef ir.TypeRef, value ir.Value) bool { return reader.Admits(typeRef, value) == ir.AdmitsYes } nullable := func(primitiveKind ir.PrimitiveKind) ir.TypeRef { typeRef := primitiveRef(primitiveKind) typeRef.Nullable = true return typeRef } - assert.True(t, typeJudgeValue.admits(nullable(ir.PrimitiveInteger), null)) - assert.False(t, typeJudgeValue.admits(primitiveRef(ir.PrimitiveInteger), null)) - assert.False(t, typeJudgeValue.admits(nullable(ir.PrimitiveInteger), stringValue("x"))) - assert.True(t, typeJudgeValue.admits(primitiveRef(ir.PrimitiveInteger), number("1"))) - assert.True(t, typeJudgeValue.admits(primitiveRef(ir.PrimitiveAny), null), "the top type admits null whatever the bit says") + assert.True(t, admits(nullable(ir.PrimitiveInteger), null)) + assert.False(t, admits(primitiveRef(ir.PrimitiveInteger), null)) + assert.False(t, admits(nullable(ir.PrimitiveInteger), stringValue("x"))) + assert.True(t, admits(primitiveRef(ir.PrimitiveInteger), number("1"))) + assert.True(t, admits(primitiveRef(ir.PrimitiveAny), null), "the top type admits null whatever the bit says") } // TestClassify_ComparesResolvedKinds pins the last-resort comparison classify @@ -761,7 +803,7 @@ func TestTypeJudge_NullIsJudgedByNullability(t *testing.T) { // a union or an opaque scalar, which say nothing of their values: only two // structures of different instance types are disjoint. A list and a tuple are // one instance type, as a model and a map are, a literal holding an object or a -// list is that instance type, and an alias is judged as the type it stands for. +// list is that instance type, and an alias is judged as the type it represents. func TestClassify_ComparesResolvedKinds(t *testing.T) { t.Parallel() stubbed, _ := stubMerger(map[ir.TypeID]ir.TypeDef{ @@ -798,7 +840,9 @@ func TestClassify_ComparesResolvedKinds(t *testing.T) { "type/bounded": &ir.Union{ID: "type/bounded", Variants: variantsOf("type/list", "type/model"), Constraints: &ir.Constraints{MinProperties: new(int64(1))}}, "type/bounded-of-models": &ir.Union{ID: "type/bounded-of-models", Closed: true, Variants: variantsOf("type/model", "type/derived"), Constraints: &ir.Constraints{MinProperties: new(int64(1))}}, - "type/holds-alias": &ir.Scalar{ID: "type/holds-alias", Base: &ir.TypeRef{Target: "type/holds"}, Constraints: &ir.Constraints{MinItems: new(int64(1))}}, + "type/holds-alias": &ir.Scalar{ID: "type/holds-alias", Base: &ir.TypeRef{Target: "type/holds"}, Constraints: &ir.Constraints{MinProperties: new(int64(1))}}, + "type/holds-alias-items": &ir.Scalar{ID: "type/holds-alias-items", Base: &ir.TypeRef{Target: "type/holds"}, + Constraints: &ir.Constraints{MinItems: new(int64(1))}}, "type/plain-alias": &ir.Scalar{ID: "type/plain-alias", Base: &ir.TypeRef{Target: "type/holds"}}, "type/external": &ir.External{ID: "type/external"}, "type/opaque": &ir.Scalar{ID: "type/opaque"}, @@ -840,6 +884,7 @@ func TestClassify_ComparesResolvedKinds(t *testing.T) { {"a union of no variant", "type/union", "type/bare", relUnrelated}, {"a model and a union one variant of which holds it, bounded beside", "type/model", "type/bounded", relUnrelated}, {"a model and a bounded alias of a union holding it", "type/model", "type/holds-alias", relUnrelated}, + {"a model and an alias of a union holding it, bounding only arrays", "type/model", "type/holds-alias-items", firstTypeIsNarrower}, {"a model and an alias of a union holding it", "type/model", "type/plain-alias", firstTypeIsNarrower}, {"a bounded union every variant of which is within a bare object", "type/bounded-of-models", "type/bare", firstTypeIsNarrower}, {"a list and a union", "type/list", "type/union", relUnrelated}, @@ -862,11 +907,11 @@ func TestClassify_ComparesResolvedKinds(t *testing.T) { {"a model and its Base", "type/derived", "type/model", firstTypeIsNarrower}, {"a model and its Base's Base", "type/grandchild", "type/model", firstTypeIsNarrower}, {"a model and a mixin", "type/mixed", "type/model", firstTypeIsNarrower}, - {"a model and the model an alias Base stands for", "type/via-alias", "type/model", firstTypeIsNarrower}, + {"a model and the model an alias Base represents", "type/via-alias", "type/model", firstTypeIsNarrower}, {"a Base the registry does not hold", "type/dangling", "type/model", relUnrelated}, {"a part the registry does not hold beside one that leads there", "type/partly-gone", "type/model", firstTypeIsNarrower}, - {"an alias of a scalar is within the scalar it stands for", "type/scalar-on", "type/scalar", firstTypeIsNarrower}, - {"models composing each other", "type/cycle-a", "type/cycle-b", relOverlap}, + {"an alias of a scalar is within the scalar it represents", "type/scalar-on", "type/scalar", firstTypeIsNarrower}, + {"models composing each other", "type/cycle-a", "type/cycle-b", relSame}, {"a model and a bare object", "type/model", "type/bare", firstTypeIsNarrower}, {"a map and a bare object", "type/map", "type/bare", firstTypeIsNarrower}, {"an object literal and a bare object", "type/lit-object", "type/bare", firstTypeIsNarrower}, @@ -874,7 +919,7 @@ func TestClassify_ComparesResolvedKinds(t *testing.T) { {"a list and a bare object", "type/list", "type/bare", relDisjoint}, {"a list literal and a bare object", "type/lit-list", "type/bare", relDisjoint}, {"a union and a bare object", "type/union", "type/bare", relUnrelated}, - {"two bare objects declared apart", "type/bare", "type/bare-twin", relOverlap}, + {"two bare objects declared apart", "type/bare", "type/bare-twin", relSame}, {"an alias of a bare object and that object", "type/alias-bare", "type/bare", firstTypeIsNarrower}, {"a model and an alias of a bare object, which may say more", "type/model", "type/alias-bare", relUnrelated}, {"a model and an object with a title", "type/model", "type/bare-titled", relUnrelated}, @@ -894,25 +939,18 @@ func TestClassify_ComparesResolvedKinds(t *testing.T) { gone, ok := stubbed.resolve("type/alias-gone") require.True(t, ok) - assert.Equal(t, gone, judge(stubbed).unaliased(gone), "an alias with nothing at its end stands for itself, never for no type") + assert.Equal(t, gone, judge(stubbed).unaliased(gone), "an alias with nothing at its end represents itself, never no type") } -// TestUnaliased_ReadsAChainUpToItsBound pins maxTypeResolveDepth on an alias -// chain: that many aliases are read to the type they stand for, and one more -// stops at an alias, so a chain too long to read is judged as an opaque scalar. -func TestUnaliased_ReadsAChainUpToItsBound(t *testing.T) { +// TestUnaliased_ReadsAChainToItsEnd pins that an alias chain is read to the +// type it represents however long it is: past the 64 aliases a walk once +// stopped at, where a chain too long to read was judged as an opaque scalar. +func TestUnaliased_ReadsAChainToItsEnd(t *testing.T) { t.Parallel() - for _, tc := range []struct { - name string - aliases int - wantModel bool - }{ - {"at the bound", maxTypeResolveDepth, true}, - {"past the bound", maxTypeResolveDepth + 1, false}, - } { + for _, aliases := range []int{64, 65, 200} { reg := map[ir.TypeID]ir.TypeDef{"type/end": declaring("type/end")} next := ir.TypeID("type/end") - for i := range tc.aliases { + for i := range aliases { id := ir.TypeID(fmt.Sprintf("type/alias-%d", i)) reg[id] = &ir.Scalar{ID: id, Base: &ir.TypeRef{Target: next}} next = id @@ -921,34 +959,44 @@ func TestUnaliased_ReadsAChainUpToItsBound(t *testing.T) { _, isModel := judge(stubbed).unaliased(reg[next]).(*ir.Model) - assert.Equal(t, tc.wantModel, isModel, tc.name) + assert.True(t, isModel, "%d aliases", aliases) } } -// TestComposes_ReadsAChainUpToItsBound pins maxComposedParts: a part that many -// links away is found, and one more is not, so a hierarchy too deep to read -// stays two types the field composes. -func TestComposes_ReadsAChainUpToItsBound(t *testing.T) { +// TestComposes_AsksTheWalk pins where composition reach is answered: by the +// walk's IsComposedOf, which a run answers from its settlement's reach index, so a +// hierarchy is read to any depth, past the 64 types a walk once stopped at, +// and the judgment reads no composition of the registry's own. +func TestComposes_AsksTheWalk(t *testing.T) { t.Parallel() - for _, tc := range []struct { - name string - links int - want bool - }{ - {"at the bound", maxComposedParts, true}, - {"past the bound", maxComposedParts + 1, false}, - } { + for _, aliasCount := range []int{64, 65, 200} { reg := map[ir.TypeID]ir.TypeDef{"type/end": declaring("type/end")} next := ir.TypeID("type/end") - for i := range tc.links { + for i := range aliasCount { id := ir.TypeID(fmt.Sprintf("type/link-%d", i)) reg[id] = &ir.Model{ID: id, Base: &ir.TypeRef{Target: next}} next = id } stubbed, _ := stubMerger(reg) - assert.Equal(t, tc.want, judge(stubbed).composes(next, "type/end"), tc.name) + assert.True(t, judge(stubbed).sites.walk.IsComposedOf(next, "type/end"), "%d aliases", aliasCount) + } + + reg := map[ir.TypeID]ir.TypeDef{ + "type/linked": &ir.Model{ID: "type/linked", Base: &ir.TypeRef{Target: "type/base"}}, + "type/base": declaring("type/base"), + "type/unlinked": declaring("type/unlinked"), } + stubbed, _ := stubMerger(reg) + var asked [][2]ir.TypeID + stubbed.walk.composedOf = func(id, target ir.TypeID) bool { + asked = append(asked, [2]ir.TypeID{id, target}) + return id == "type/unlinked" + } + + assert.True(t, judge(stubbed).sites.walk.IsComposedOf("type/unlinked", "type/base"), "the walk's yes, which no alias of the registry gives") + assert.False(t, judge(stubbed).sites.walk.IsComposedOf("type/linked", "type/base"), "the walk's no, though the registry links them") + assert.Equal(t, [][2]ir.TypeID{{"type/unlinked", "type/base"}, {"type/linked", "type/base"}}, asked) } // TestComposes_ReadsEachPartOnce pins that a diamond and a cycle both end: a @@ -963,8 +1011,8 @@ func TestComposes_ReadsEachPartOnce(t *testing.T) { "type/alone": declaring("type/alone"), }) - assert.True(t, judge(stubbed).composes("type/root", "type/shared")) - assert.False(t, judge(stubbed).composes("type/root", "type/alone")) + assert.True(t, judge(stubbed).sites.walk.IsComposedOf("type/root", "type/shared")) + assert.False(t, judge(stubbed).sites.walk.IsComposedOf("type/root", "type/alone")) } // TestSaysOnlyObject_ReadsEveryFieldThatSaysSomething pins what a bare object is: @@ -975,9 +1023,9 @@ func TestSaysOnlyObject_ReadsEveryFieldThatSaysSomething(t *testing.T) { t.Parallel() ref := &ir.TypeRef{Target: "type/x"} for _, tc := range []struct { - name string - td ir.TypeDef - want bool + name string + typeDef ir.TypeDef + want bool }{ {"nothing at all", &ir.Model{}, true}, {"where it was declared", &ir.Model{ @@ -999,7 +1047,7 @@ func TestSaysOnlyObject_ReadsEveryFieldThatSaysSomething(t *testing.T) { {"something kept verbatim", &ir.Model{Unmodeled: ir.Unmodeled{"k": {}}}, false}, {"no model", &ir.MapT{}, false}, } { - assert.Equal(t, tc.want, saysOnlyObject(tc.td), tc.name) + assert.Equal(t, tc.want, saysOnlyObject(tc.typeDef), tc.name) } } @@ -1023,7 +1071,7 @@ func TestTypeJudge_UnrelatedPrimitivesAreDisjoint(t *testing.T) { func TestSameValue_ComparesJSONValues(t *testing.T) { t.Parallel() obj := func(fs ...ir.Field) ir.Value { return ir.Value{Kind: ir.ValueObject, Object: fs} } - sym := func(s string) ir.Value { return ir.Value{Kind: ir.ValueSymbol, String: s} } + sym := func(text string) ir.Value { return ir.Value{Kind: ir.ValueSymbol, String: text} } for _, tc := range []struct { name string a, b ir.Value @@ -1063,16 +1111,17 @@ func TestTypeJudge_ComparesReferentsNotReferences(t *testing.T) { assert.Equal(t, relDisjoint, judge(stubbed).relate(ref("type/a"), ref("type/i")), "string and integer cannot both be satisfied") assert.Equal(t, relUnrelated, judge(stubbed).relate(ref("type/any"), ref("type/i")), - "a degraded node stands for a declaration the judgment cannot see") + "a degraded node represents a declaration the judgment cannot see") assert.Equal(t, relDisjoint, judge(stubbed).relate(ref("type/m"), ref("type/a")), "a structural type and a primitive are different kinds") } // TestTypeJudge_CopiesUnderAnotherBaseOverlap pins that a hoisted copy keeping // a reference is one type with a node held alike only where the two read it -// against one base (FieldDeclarationContext.Alike): elsewhere they are two -// types declared apart, which overlap, whether the other is a copy or a node -// declared elsewhere. Copies keeping none say the same under any base. +// against one base (FieldDeclarationContext.DeclarationsAdmitAlike): elsewhere they are two +// types declared apart, which nothing shows share a value or share none, +// whether the other is a copy or a node declared elsewhere. Copies keeping +// none say the same under any base. func TestTypeJudge_CopiesUnderAnotherBaseOverlap(t *testing.T) { t.Parallel() reg := judgeRegistry() @@ -1085,12 +1134,12 @@ func TestTypeJudge_CopiesUnderAnotherBaseOverlap(t *testing.T) { for _, id := range []ir.TypeID{"type/lit-a-abs1", "type/lit-a-abs2"} { reg[id] = &ir.Literal{ID: id, Anonymous: true, Value: stringValue("a"), Unmodeled: absolute} } - typeJudgeValue := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{apart: true})} - assert.Equal(t, relOverlap, typeJudgeValue.relate(ref("type/lit-a-ref1"), ref("type/lit-a-ref2"))) - assert.Equal(t, relOverlap, typeJudgeValue.relate(ref("type/lit-a-ref"), ref("type/lit-a-ref1")), "a node declared apart") - assert.Equal(t, relSame, typeJudgeValue.relate(ref("type/lit-a-h1"), ref("type/lit-a-h2")), "copies keeping no reference") - assert.Equal(t, relSame, typeJudgeValue.relate(ref("type/lit-a-abs1"), ref("type/lit-a-abs2")), "copies keeping an absolute one") - assert.Equal(t, firstTypeIsNarrower, typeJudgeValue.relate(ref("type/enum-str"), ref("type/enum-str-h")), + typeJudge := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{apart: true})} + assert.Equal(t, relUndecided, typeJudge.relate(ref("type/lit-a-ref1"), ref("type/lit-a-ref2"))) + assert.Equal(t, relUndecided, typeJudge.relate(ref("type/lit-a-ref"), ref("type/lit-a-ref1")), "a node declared apart") + assert.Equal(t, relSame, typeJudge.relate(ref("type/lit-a-h1"), ref("type/lit-a-h2")), "copies keeping no reference") + assert.Equal(t, relSame, typeJudge.relate(ref("type/lit-a-abs1"), ref("type/lit-a-abs2")), "copies keeping an absolute one") + assert.Equal(t, firstTypeIsNarrower, typeJudge.relate(ref("type/enum-str"), ref("type/enum-str-h")), "a node declared apart still wins over a hoisted copy") } @@ -1166,8 +1215,8 @@ func TestJSONInstanceKind_NamesTheKindOfAValue(t *testing.T) { assert.Equal(t, want, primitiveInstance(primitiveKind), primitiveKind) } for _, tc := range []struct { - td ir.TypeDef - want JSONInstanceKind + typeDef ir.TypeDef + want JSONInstanceKind }{ {&ir.Model{}, InstanceObject}, {&ir.MapT{}, InstanceObject}, @@ -1179,10 +1228,71 @@ func TestJSONInstanceKind_NamesTheKindOfAValue(t *testing.T) { {&ir.Literal{Value: ir.Value{Kind: ir.ValueNull}}, InstanceNull}, {&ir.Literal{Value: ir.Value{Kind: ir.ValueNumber, Number: "2"}}, InstanceInteger}, {&ir.Literal{Value: ir.Value{Kind: ir.ValueNumber, Number: "2.5"}}, InstanceNumber}, - {&ir.Literal{Value: ir.Value{Kind: ir.ValueNumber, Number: "1e3"}}, InstanceNumber}, + // 1.0 and 1e3 are integers to a JSON Schema validator (`type: integer`). + {&ir.Literal{Value: ir.Value{Kind: ir.ValueNumber, Number: "1.0"}}, InstanceInteger}, + {&ir.Literal{Value: ir.Value{Kind: ir.ValueNumber, Number: "1e3"}}, InstanceInteger}, + {&ir.Literal{Value: ir.Value{Kind: ir.ValueNumber, Number: "1e-3"}}, InstanceNumber}, {&ir.Literal{Value: ir.Value{Kind: ir.ValueString, String: "a"}}, InstanceString}, + // An infinity is a number, as typeformat.KindsOfValue reads it, and a + // symbol the text it is written as. + {&ir.Literal{Value: ir.Value{Kind: ir.ValueInfinity}}, InstanceNumber}, + {&ir.Literal{Value: ir.Value{Kind: ir.ValueSymbol, String: "a"}}, InstanceString}, {&ir.Enum{}, 0}, } { - assert.Equal(t, tc.want, nodeInstance(tc.td), "%T %+v", tc.td, tc.td) + assert.Equal(t, tc.want, nodeInstance(tc.typeDef), "%T %+v", tc.typeDef, tc.typeDef) + } +} + +// TestTypeJudge_ModelsApartInTheirReferencesHoldNoUndecidedMember pins the +// guard on two models alike in skeleton whose own kept references are not +// shown to land alike, an undecided answer: a member pair the judgment cannot +// decide either, as two documented strings under different patterns, is no member the +// two hold alike, so the models are unrelated, composed rather than one kept +// over the other as undecided. +func TestTypeJudge_ModelsApartInTheirReferencesHoldNoUndecidedMember(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + not := ir.Unmodeled{"openapi:not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{"$ref":"n.json"}`)}} + model := func(id, member ir.TypeID) *ir.Model { + return &ir.Model{ID: id, Unmodeled: not, Properties: []ir.Property{{WireName: "n", Type: ir.TypeRef{Target: member}}}} + } + reg := ir.TypeRegistry{ + "type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}, + "type/starts-a": &ir.Scalar{ID: "type/starts-a", Base: &text, Constraints: &ir.Constraints{Pattern: "^a"}, + Docs: ir.Docs{Description: "starts with a"}}, + "type/starts-b": &ir.Scalar{ID: "type/starts-b", Base: &text, Constraints: &ir.Constraints{Pattern: "^b"}, + Docs: ir.Docs{Description: "starts with b"}}, + "type/model-a": model("type/model-a", "type/starts-a"), + "type/model-b": model("type/model-b", "type/starts-b"), } + judgment := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{apart: true})} + + require.Equal(t, relUndecided, judgment.relate(ref("type/starts-a"), ref("type/starts-b")), "the members") + assert.Equal(t, relUnrelated, judgment.relate(ref("type/model-a"), ref("type/model-b"))) +} + +// TestTypeJudge_CopiesNotShownAlikeStayUndecided pins the guard on two nodes a +// answer holds alike in values and detail whose kept references the walk +// shows alike entry by entry but not node by node, as two declarations written +// apart: one keeps a length, which says nothing of an integer, so they keep +// different entries, and still they are not one type, but undecided. +func TestTypeJudge_CopiesNotShownAlikeStayUndecided(t *testing.T) { + t.Parallel() + integer := primitiveRef(ir.PrimitiveInteger) + kept := func(at jsontext.Pointer, length bool) ir.Unmodeled { + entries := ir.Unmodeled{"openapi:not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{"$ref":"n.json"}`), + Provenance: ptrAt(at + "/not")}} + if length { + entries["openapi:minLength"] = ir.UnmodeledEntry{Reason: ir.ReasonNoIRHome, Value: ir.RawValue(`3`), Provenance: ptrAt(at + "/minLength")} + } + return entries + } + reg := ir.TypeRegistry{ + "type/primitive/integer": &ir.Primitive{ID: "type/primitive/integer", PrimitiveKind: ir.PrimitiveInteger}, + "type/count-a": &ir.Scalar{ID: "type/count-a", Base: &integer, Unmodeled: kept("/a", false), Provenance: ptrAt("/a")}, + "type/count-b": &ir.Scalar{ID: "type/count-b", Base: &integer, Unmodeled: kept("/b", true), Provenance: ptrAt("/b")}, + } + judgment := typeJudge{resolve: stubResolve(reg), sites: atRoot(&stubWalk{apartAt: []jsontext.Pointer{"/a", "/b"}})} + + assert.Equal(t, relUndecided, judgment.relate(ref("type/count-a"), ref("type/count-b"))) } diff --git a/compilers/openapi/internal/merge/unions.go b/compilers/openapi/internal/merge/unions.go index 8b99985d9..600237053 100644 --- a/compilers/openapi/internal/merge/unions.go +++ b/compilers/openapi/internal/merge/unions.go @@ -4,8 +4,7 @@ package merge import ( - "slices" - + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" "github.com/dexpace/morphic/ir" ) @@ -17,48 +16,84 @@ const maxVariantReads = 64 // unionArms relates a type to an untagged union, each read through aliases, by // the union's variants: the type is within the union where it is within one -// variant (withinUnion) and nothing on the way bounds the union's values -// (boundsBeside), and a closed union within the type where every variant is -// (unionWithin). Two unions, a tagged union, or a type neither holds, are -// unrelated here. A variant is judged on its union's side, against the site -// that union was declared at (declarationSites), so swapping a and b flips the -// verdict and changes nothing else. -func unionArms(typeJudgeValue typeJudge, a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef, depth int) relation { - au, aUnion := typeJudgeValue.unaliased(at).(*ir.Union) - bu, bUnion := typeJudgeValue.unaliased(bt).(*ir.Union) +// variant and nothing on the way bounds the union's values of its kinds +// (boundsBeside), and a closed union within the type where every variant is. +// Any other pair is unrelated here. A variant is judged against the site its +// union was declared at, so swapping a and b flips the answer and changes +// nothing else. +func unionArms(typeJudge typeJudge, a ir.TypeRef, at ir.TypeDef, b ir.TypeRef, bt ir.TypeDef, depth int) relation { + au, aUnion := typeJudge.unaliased(at).(*ir.Union) + bu, bUnion := typeJudge.unaliased(bt).(*ir.Union) + if aUnion && bUnion { + return unionsAlike(typeJudge, a, au, b, bu, depth) + } if aUnion == bUnion { return relUnrelated } if bUnion { - against := func(typeRef ir.TypeRef) relation { return typeJudgeValue.relateAt(a, typeRef, depth+1) } - return byVariants(typeJudgeValue, against, bu, !boundsBeside(typeJudgeValue.registry, bt)) + against := func(typeRef ir.TypeRef) relation { return typeJudge.relateAt(a, typeRef, depth+1) } + return byVariants(typeJudge, against, bu, !boundsBeside(typeJudge.registryReader, bt, typeJudge.typeKinds(a, at))) + } + against := func(typeRef ir.TypeRef) relation { return typeJudge.relateAt(typeRef, b, depth+1).flipped() } + return byVariants(typeJudge, against, au, !boundsBeside(typeJudge.registryReader, at, typeJudge.typeKinds(b, bt))).flipped() +} + +// unionsAlike relates two untagged unions of one exclusiveness and closedness +// whose variants pair off as the same type (sameSet), so the two admit the +// same values but for the bounds each holds beside them, which decide with +// what else each says (GitHub #2041). Any other pair is unrelated here. +func unionsAlike(j typeJudge, a ir.TypeRef, au *ir.Union, b ir.TypeRef, bu *ir.Union, depth int) relation { + if tagged(au) || tagged(bu) || au.Exclusive != bu.Exclusive || au.Closed != bu.Closed || + j.variants == nil || !j.variants.Spend(len(au.Variants)) { + return relUnrelated + } + same := func(rel relation) bool { return rel == relSame } + if !sameSet(j, variantTypes(au), variantTypes(bu), same, depth) { + return relUnrelated + } + rel := relationOfValues(boundsSubsumption(au.Constraints, bu.Constraints), j.detailOf(extras{Common: au.TypeCommon, Kinds: typeformat.EveryInstanceKind}, + extras{Common: bu.TypeCommon, Kinds: typeformat.EveryInstanceKind})) + if rel == relSame { + return j.sites.alikeInValues(a, au, b, bu) } - against := func(typeRef ir.TypeRef) relation { return typeJudgeValue.relateAt(typeRef, b, depth+1).flipped() } - return byVariants(typeJudgeValue, against, au, !boundsBeside(typeJudgeValue.registry, at)).flipped() + return rel } -// boundsBeside reports whether td, a union read through aliases, or an alias -// on the way holds bounds of its own. Each bounds the values of its kind -// whichever variant holds them (docs/ir/unions.md#bounds-beside-a-union), -// which the variants do not say, so a type within one of them is not shown to -// be within td, and a field taking it would lose them. -func boundsBeside(registryValue registry, td ir.TypeDef) bool { - chain, end := registryValue.aliasChain(td) - if union, ok := end.(*ir.Union); ok && union.Constraints != nil { +// variantTypes lists the type of each of union's variants, in order. +func variantTypes(union *ir.Union) []ir.TypeRef { + out := make([]ir.TypeRef, len(union.Variants)) + for i, variant := range union.Variants { + out[i] = variant.Type + } + return out +} + +// boundsBeside reports whether typeDef, a union read through aliases, or an +// alias on the way holds a bound of its own applying to kinds. Such a bound +// bounds the values of its kind whichever variant holds them +// (docs/ir/unions.md#bounds-beside-a-union), so a type of those kinds within +// one variant is not shown to be within typeDef. +func boundsBeside(registry registryReader, typeDef ir.TypeDef, kinds typeformat.JSONInstanceKinds) bool { + if union, ok := registry.unaliased(typeDef).(*ir.Union); ok && boundKinds(union.Constraints)&kinds != 0 { return true } - return slices.ContainsFunc(chain, func(scalar *ir.Scalar) bool { return scalar.Constraints != nil }) + scalar, alias := typeDef.(*ir.Scalar) + if !alias || scalar.Base == nil { + return false + } + bounded, _ := registry.chainAnswerMemos(nil).kindsBoundBeside.AnswerFor(scalar.Base.Target) + return (boundKinds(scalar.Constraints)|bounded)&kinds != 0 } // byVariants relates a type to union, an untagged union, where against is the // type judged against one of union's variants: narrower where it is within // union, which holds says it may be, broader where union is within it, and // unrelated otherwise. -func byVariants(typeJudgeValue typeJudge, against func(typeRef ir.TypeRef) relation, union *ir.Union, holds bool) relation { +func byVariants(typeJudge typeJudge, against func(typeRef ir.TypeRef) relation, union *ir.Union, holds bool) relation { switch { - case holds && withinUnion(typeJudgeValue, against, union): + case holds && withinUnion(typeJudge, against, union): return firstTypeIsNarrower - case unionWithin(typeJudgeValue, against, union): + case unionWithin(typeJudge, against, union): return secondTypeIsNarrower default: return relUnrelated @@ -74,12 +109,12 @@ func tagged(union *ir.Union) bool { return union.WireTagged || union.Discriminat // value of the type against judges: union is closed and has a variant, and each // is within that type. An open union admits a variant it does not list, which // nothing holds within the type. A read past the judgment's budget is no proof. -func unionWithin(typeJudgeValue typeJudge, against func(typeRef ir.TypeRef) relation, union *ir.Union) bool { +func unionWithin(typeJudge typeJudge, against func(typeRef ir.TypeRef) relation, union *ir.Union) bool { if tagged(union) || !union.Closed || len(union.Variants) == 0 { return false } for _, variant := range union.Variants { - if typeJudgeValue.variants == nil || !typeJudgeValue.variants.Spend(1) { + if typeJudge.variants == nil || !typeJudge.variants.Spend(1) { return false } if rel := against(variant.Type); rel != relSame && rel != secondTypeIsNarrower { @@ -94,13 +129,13 @@ func unionWithin(typeJudgeValue typeJudge, against func(typeRef ir.TypeRef) rela // one, which admits what any variant does, or within exactly one variant of an // exclusive one and disjoint from every other, as one admits no value two // variants share. A read past the judgment's budget is no proof. -func withinUnion(typeJudgeValue typeJudge, against func(typeRef ir.TypeRef) relation, union *ir.Union) bool { +func withinUnion(typeJudge typeJudge, against func(typeRef ir.TypeRef) relation, union *ir.Union) bool { if tagged(union) { return false } within := 0 for _, variant := range union.Variants { - if typeJudgeValue.variants == nil || !typeJudgeValue.variants.Spend(1) { + if typeJudge.variants == nil || !typeJudge.variants.Spend(1) { return false } switch rel := against(variant.Type); { diff --git a/compilers/openapi/internal/merge/valuesites_internal_test.go b/compilers/openapi/internal/merge/valuesites_internal_test.go new file mode 100644 index 000000000..1b09b937d --- /dev/null +++ b/compilers/openapi/internal/merge/valuesites_internal_test.go @@ -0,0 +1,90 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// TestFold_RecordsWhereAFieldsOneSourceWritesIt pins the value sites a fold +// returns for a member written nowhere: for each field it takes from one +// declaration, the place of the first written of those giving the value kept, +// and nothing for a field none gives. A fold taking no field from one +// declaration returns none. +func TestFold_RecordsWhereAFieldsOneSourceWritesIt(t *testing.T) { + t.Parallel() + described := func(pointer, description string) declaration { + property := declared("p", "type/primitive/string", pointer) + property.Docs.Description = description + return declaration{property: property, source: written(`{}`)} + } + decls := []declaration{described("/D/p", "other"), described("/A/p", "kept"), described("/B/p", "kept")} + + stubbed, _ := stubMerger(membersRegistry()) + _, valueWrittenAt, _ := stubbed.foldAt(decls, "/M/allOf/properties/p", nil) + + require.Contains(t, valueWrittenAt, "description") + assert.Equal(t, "/A/p", string(valueWrittenAt["description"].Pointer), "the first written of the two giving it, not the last, which the field keeps") + assert.NotContains(t, valueWrittenAt, "title", "a field no declaration gives") + + plain := []declaration{described("/A/p", ""), described("/B/p", "")} + _, none, _ := stubbed.foldAt(plain, "/M/allOf/properties/p", nil) + assert.Nil(t, none, "a fold taking no field from one declaration") +} + +// TestFold_PlacesAFieldWhereItsOneSourceWritesIt pins where a report about a +// field of a member written nowhere sits: where the declaration it took that +// field from writes it, and, for a field it records no place of, a shared one, +// as any report about the member sits. +func TestFold_PlacesAFieldWhereItsOneSourceWritesIt(t *testing.T) { + t.Parallel() + stubbed, _ := stubMerger(membersRegistry()) + member := declared("p", "type/primitive/string", "/M/p") + fromEntries := declaration{property: member, typeAt: sitesAt("/T/p"), valueWrittenAt: map[string]ir.Provenance{"description": ptrAt("/A/p")}, + via: &composedEntry{target: "type/A", at: "/N/allOf/0"}} + description := fieldPlace(&stubbed.Merger, fromEntries, "description") + + assert.Equal(t, "/A/p", string(description.Pointer)) + assert.Equal(t, "/T/p", string(fieldPlace(&stubbed.Merger, fromEntries, fieldGivenTogether).Pointer)) + assert.Equal(t, "/A/p", placeName(stubbed.Sources, description, description.Source)) +} + +// TestFold_RefusesEachValueWhereItIsWritten pins where a refusal of a member +// written nowhere sits: its default and examples in one note where one place +// writes both, and each in a note of its own, at and naming its place, where +// the member took them from two. +func TestFold_RefusesEachValueWhereItIsWritten(t *testing.T) { + t.Parallel() + stubbed, _ := stubMerger(membersRegistry()) + for name, tc := range map[string]struct { + examplesAt jsontext.Pointer + want map[string]string + }{ + "one place writing both": {examplesAt: "/A/p", want: map[string]string{"/A/p": "default and examples /A/p gives"}}, + "two places": {examplesAt: "/B/p", want: map[string]string{"/A/p": "default /A/p gives", + "/B/p": "examples /B/p gives"}}, + } { + fromEntries := declaration{property: declared("p", "type/primitive/string", "/M/p"), typeAt: sitesAt("/T/p"), + valueWrittenAt: map[string]ir.Provenance{"default": ptrAt("/A/p"), "examples": ptrAt(tc.examplesAt)}, + via: &composedEntry{target: "type/A", at: "/N/allOf/0"}} + folding := &fieldFold{g: &stubbed.Merger, decls: []declaration{fromEntries}, notes: make([][]note, 1)} + + folding.refuse(0, []string{"default", "examples"}) + + got := map[string]string{} + for _, note := range folding.notes[0] { + got[string(note.at.Pointer)] = note.message + } + require.Len(t, got, len(tc.want), name) + for at, says := range tc.want { + assert.Contains(t, got[at], "admits the "+says+";", name) + } + } +} diff --git a/compilers/openapi/internal/merge/view.go b/compilers/openapi/internal/merge/view.go index 932bd785b..eabbd07ef 100644 --- a/compilers/openapi/internal/merge/view.go +++ b/compilers/openapi/internal/merge/view.go @@ -12,155 +12,248 @@ import ( ) // view returns the node the judgment compares, and the builder builds from, for -// td (docs/compilers/openapi.md#allof-redeclared-property): td itself, or, where -// td is a chain of aliases ending in an enum, a const, a Scalar, a list, a map or -// a tuple, a copy of that node holding what the chain adds (chainBounds, -// chainCommon), read down to stop, where the alias naming stop is the node. A -// chain giving an encoding or bounds no one value states, or keeping a reference -// under Unmodeled, which reads against where it is written, is td. -func (r registry) view(td ir.TypeDef, stop ir.TypeID) ir.TypeDef { - chain, end := r.aliasedNode(td, stop) - if len(chain) == 0 || keepsReference(end) { - return td +// typeDef (docs/compilers/openapi.md#allof-redeclared-property): typeDef, or, +// for a chain of aliases ending in an enum, a const, a Scalar, a list, a map +// or a tuple, a copy of that node holding what the chain adds, read down to +// stop, where the alias naming stop is the node. A chain giving an encoding or +// bounds no one value states, or keeping a reference under Unmodeled, is +// typeDef. What the aliases add costs a logarithm of the chain to combine. +func (r registryReader) view(typeDef ir.TypeDef, stop ir.TypeID) ir.TypeDef { + scalar, alias := typeDef.(*ir.Scalar) + if !alias || scalar.Base == nil { + return typeDef } - for _, scalar := range chain { - if scalar.Encoding != nil || keepsReference(scalar) { - return td + memos := r.chainAnswerMemos(nil) + if stop != "" { + if out, read := memos.viewDownTo(scalar, stop); read { + return out } } - bounds, ok := chainBounds(chain, end) - if !ok { - return td - } - if typeDef, ok := viewOf(end, chain, bounds); ok { - return typeDef + if end := memos.primitiveEnd(scalar); end != "" { + out, _ := memos.viewDownTo(scalar, end) + return out } - return td + return memos.viewToEnd(scalar) } -// aliasedNode returns the aliases a chain from td leads through, td first, and -// the node it ends in: the alias naming stop, the first node that is no alias, -// or a Scalar over a kind, whose Base says what its values are rather than naming -// another node. It returns no chain where a link names nothing the registry -// holds or the chain runs past maxTypeResolveDepth aliases. -func (r registry) aliasedNode(td ir.TypeDef, stop ir.TypeID) ([]*ir.Scalar, ir.TypeDef) { - var chain []*ir.Scalar - for range maxTypeResolveDepth + 1 { - scalar, alias := td.(*ir.Scalar) - if !alias || scalar.Base == nil || scalar.Base.Target == stop { - return chain, td - } - next, ok := r.resolve(scalar.Base.Target) - if !ok { - return nil, td - } - if _, kind := next.(*ir.Primitive); kind { - return chain, td - } - chain, td = append(chain, scalar), next +// primitiveEnd returns the primitive scalar's chain ends on, and "" where it +// ends on any other type, repeats one or names one the registry lacks. +func (memos *AliasChainAnswerMemos) primitiveEnd(scalar *ir.Scalar) ir.TypeID { + end, cyclic := memos.index.End(scalar.Base.Target) + if cyclic { + return "" } - return nil, td + node, held := memos.node(end) + if _, primitive := node.(*ir.Primitive); !held || !primitive { + return "" + } + return end } -// sharedLink returns the first node every alias chain from tds names, and "" -// where no node is named by all of them. Each chain is a path one Base at a time, -// so where two meet they share the rest, and the first node they share is where -// aliases of one node stop being read through: what each adds to it is judged -// against what the others add, and a node built of them stays an alias of it. -func (r registry) sharedLink(tds ...ir.TypeDef) ir.TypeID { - first := r.links(tds[0]) - if len(first) == 0 { - return "" +// viewDownTo is the view of scalar read down to stop: the alias naming stop, +// holding what every alias from scalar to it adds, that one among them, but for +// the encoding of the alias naming stop, which the node itself holds. It is +// false where stop is no node on scalar's chain, which reads as no stop. +func (memos *AliasChainAnswerMemos) viewDownTo(scalar *ir.Scalar, stop ir.TypeID) (ir.TypeDef, bool) { + if scalar.Base.Target == stop { + return scalar, true } - rest := make([][]ir.TypeID, len(tds)-1) - for k, td := range tds[1:] { - if rest[k] = r.links(td); len(rest[k]) == 0 { - return "" - } + below, reaches := memos.aliasViews.summaryBetween(scalar.Base.Target, stop) + if !reaches { + return nil, false } - for _, id := range first { - if !slices.ContainsFunc(rest, func(ids []ir.TypeID) bool { return !slices.Contains(ids, id) }) { - return id - } + combined := combineViews(viewOfAlias(scalar), below) + if combined.references || combined.encodedBefore { + return scalar, true + } + bounds := combined.lastBounds.Intersect(combined.bounds) + if len(bounds.DisagreeingKeywords()) > 0 { + return scalar, true } - return "" + out := *combined.last + out.TypeCommon, out.Constraints = viewCommon(combined.common, scalar, out.ID), bounds.AgreedConstraints() + return &out, true } -// links returns the nodes an alias chain from td names, nearest first, down to -// the node it ends in (aliasedNode). -func (r registry) links(td ir.TypeDef) []ir.TypeID { - chain, _ := r.aliasedNode(td, "") - ids := make([]ir.TypeID, len(chain)) - for k, scalar := range chain { - ids[k] = scalar.Base.Target +// viewToEnd is the view of scalar read to the end of its chain, a node of no +// primitive kind: a copy of it holding what every alias of the chain adds, +// beside what it holds itself. +func (memos *AliasChainAnswerMemos) viewToEnd(scalar *ir.Scalar) ir.TypeDef { + end, cyclic := memos.index.End(scalar.Base.Target) + node, held := memos.node(end) + if cyclic || !held || ir.IsNilTypeDef(node) || keepsReference(node) { + return scalar } - return ids + combined := viewOfAlias(scalar) + if scalar.Base.Target != end { + // The end of an acyclic chain is a node on it, so the combination + // reads. + below, _ := memos.aliasViews.summaryBetween(scalar.Base.Target, end) + combined = combineViews(combined, below) + } + if combined.references || combined.encodedBefore || combined.encodedLast { + return scalar + } + intersected := ir.ConstraintIntersectionOf(boundsOf(node)).Intersect(combined.bounds.Intersect(combined.lastBounds)) + if len(intersected.DisagreeingKeywords()) > 0 { + return scalar + } + bounds, ok := endBounds(node, intersected.AgreedConstraints()) + if !ok { + return scalar + } + common := viewCommon(nearerCommon(combined.common, *node.Common()), scalar, node.Common().ID) + if typeDef, ok := viewOf(node, common, bounds); ok { + return typeDef + } + return scalar } -// chainBounds returns the bounds end and every alias of chain say together, and -// false where two say a keyword no one value states. A closed enum or a const -// holds none: bounds every value it lists meets say nothing of it, and false is -// returned where they cut a value or have no judge (admitsConstraints), since -// the node they leave lists values none of its declarations do. An open enum's -// bounds also constrain the values it does not list, which no node of its kind -// holds, so false is returned for any. -func chainBounds(chain []*ir.Scalar, end ir.TypeDef) (*ir.Constraints, bool) { - bounds := boundsOf(end) - for _, scalar := range chain { - if sameBounds(scalar.Constraints, nil) { - continue - } - if !Meets(bounds, scalar.Constraints) { - return nil, false - } - var met ir.Constraints - bounds = Constraints(Constraints(&met, bounds), scalar.Constraints) +// aliasView is what a run of aliases down a chain adds, nearest first, as view +// reads it: the bounds of all but the last and the last's own, which view +// intersects after the end's or the stop's; the TypeCommon a reference to the +// first reads; whether any keeps a reference under Unmodeled; whether any but +// the last, and the last, gives an encoding; and the last alias itself. +type aliasView struct { + bounds, lastBounds ir.ConstraintIntersection + common ir.TypeCommon + last *ir.Scalar + references bool + encodedBefore, encodedLast bool +} + +// viewOfAlias is what scalar alone adds. +func viewOfAlias(scalar *ir.Scalar) aliasView { + return aliasView{lastBounds: ir.ConstraintIntersectionOf(scalar.Constraints), common: scalar.TypeCommon, last: scalar, + references: keepsReference(scalar), encodedLast: scalar.Encoding != nil} +} + +// combineViews is what near and the run below it, far, add together: a +// combination associative in every field, so a range combines alike in every +// grouping. +func combineViews(near, far aliasView) aliasView { + return aliasView{ + bounds: near.bounds.Intersect(near.lastBounds).Intersect(far.bounds), + lastBounds: far.lastBounds, + common: nearerCommon(near.common, far.common), + last: far.last, + references: near.references || far.references, + encodedBefore: near.encodedBefore || near.encodedLast || far.encodedBefore, + encodedLast: far.encodedLast, } - switch n := end.(type) { +} + +// endBounds returns the bounds a view of end holds, bounds being what end and +// every alias of its chain say together, and false where none can exist. A +// closed enum or a const holds none: bounds every value it lists intersects say +// nothing of it, and false is returned where they cut a value or have no judge +// (ir.ConstraintsAdmit), since the node they leave lists values none of its +// declarations do. An open enum's bounds also constrain the values it does not +// list, which no node of its kind holds, so false is returned for any. +func endBounds(end ir.TypeDef, bounds *ir.Constraints) (*ir.Constraints, bool) { + switch node := end.(type) { case *ir.Enum: - if !n.Closed && !sameBounds(bounds, nil) { + if !node.Closed && !sameBounds(bounds, nil) { return nil, false } - return nil, !slices.ContainsFunc(n.Members, func(enumMember ir.EnumMember) bool { - return !admitsConstraints(bounds, enumMember.Value, 0) + return nil, !slices.ContainsFunc(node.Members, func(enumMember ir.EnumMember) bool { + return ir.ConstraintsAdmit(bounds, enumMember.Value) != ir.AdmitsYes }) case *ir.Literal: - return nil, admitsConstraints(bounds, n.Value, 0) + return nil, ir.ConstraintsAdmit(bounds, node.Value) == ir.AdmitsYes default: return bounds, true } } -// chainCommon returns the TypeCommon a reference to chain's first alias reads: -// each field the nearest of chain and end sets, the documentation field by field -// (nearerDocs), a redaction where any asks for it, and every Unmodeled key, the -// nearest keeping it giving it. It holds the first alias's site but for the ID, -// end's, beneath which an enum's members are named, and writes to no node. -func chainCommon(chain []*ir.Scalar, end ir.TypeDef) ir.TypeCommon { - typeCommon := *end.Common() - id := typeCommon.ID - typeCommon.Unmodeled = maps.Clone(typeCommon.Unmodeled) - out := reflect.ValueOf(&typeCommon).Elem() - for _, scalar := range slices.Backward(chain) { - near := scalar.TypeCommon - kept, docs := typeCommon.Unmodeled, nearerDocs(typeCommon.Docs, near.Docs) - said := reflect.ValueOf(near) - for i := range out.NumField() { - if f := said.Field(i); !f.IsZero() { - out.Field(i).Set(f) - } +// sharedAlias returns the first node every alias chain from tds names, and "" +// where none is. There aliases of one node stop being read through: what each +// adds to it is judged against what the others add, and a node built of them +// stays an alias of it. No primitive counts, and each pair costs the logarithm +// of the chains' lengths. +func (r registryReader) sharedAlias(tds ...ir.TypeDef) ir.TypeID { + first, alias := tds[0].(*ir.Scalar) + if !alias || first.Base == nil { + return "" + } + memos := r.chainAnswerMemos(nil) + var shared ir.TypeID + for k, typeDef := range tds[1:] { + scalar, alias := typeDef.(*ir.Scalar) + if !alias || scalar.Base == nil { + return "" } - typeCommon.Unmodeled, typeCommon.Docs = kept, docs - for key, entry := range near.Unmodeled { - if typeCommon.Unmodeled == nil { - typeCommon.Unmodeled = ir.Unmodeled{} - } - typeCommon.Unmodeled[key] = entry + sharedAlias, ok := memos.nearestSharedAlias(first, scalar) + switch { + case !ok: + return "" + case k == 0 || chainContains(memos.index, shared, sharedAlias): + shared = sharedAlias + } + } + return shared +} + +// nearestSharedAlias returns the first alias the chains of a and b both name, +// nearest a, and false where they share none: a's Base where b's chain names +// it, b's where a's names it, and otherwise the first both name below them +// (sharedAliasBelow), no primitive counted. +func (memos *AliasChainAnswerMemos) nearestSharedAlias(a, b *ir.Scalar) (ir.TypeID, bool) { + x, y := a.Base.Target, b.Base.Target + switch { + case x == y || chainContains(memos.index, y, x): + return memos.noPrimitive(x) + case chainContains(memos.index, x, y): + return memos.noPrimitive(y) + default: + return sharedAliasBelow(memos.index, memos.node, x, y) + } +} + +// noPrimitive returns id where it names a node of the registry that is no +// primitive, and false otherwise. +func (memos *AliasChainAnswerMemos) noPrimitive(id ir.TypeID) (ir.TypeID, bool) { + node, held := memos.node(id) + if _, primitive := node.(*ir.Primitive); primitive || !held { + return "", false + } + return id, true +} + +// nearerCommon returns the TypeCommon a reference to near's node reads where it +// is an alias over far's: each field near sets in place of far's, the +// documentation field by field (nearerDocs), and every Unmodeled key either +// keeps, near's entry where both do. It writes to neither side's map, so the +// combinations of a range share them. +func nearerCommon(near, far ir.TypeCommon) ir.TypeCommon { + out := far + unmodeled, docs := far.Unmodeled, nearerDocs(far.Docs, near.Docs) + fields, said := reflect.ValueOf(&out).Elem(), reflect.ValueOf(near) + for i := range fields.NumField() { + if setField := said.Field(i); !setField.IsZero() { + fields.Field(i).Set(setField) } } - site := chain[0].TypeCommon - typeCommon.ID, typeCommon.Name, typeCommon.Anonymous, typeCommon.Provenance = id, site.Name, site.Anonymous, site.Provenance - return typeCommon + out.Docs, out.Unmodeled = docs, unmodeled + switch { + case len(near.Unmodeled) == 0: + case len(unmodeled) == 0: + out.Unmodeled = near.Unmodeled + default: + out.Unmodeled = maps.Clone(unmodeled) + maps.Copy(out.Unmodeled, near.Unmodeled) + } + return out +} + +// viewCommon returns combined, what a reference to first reads, at first's site +// but for the ID, id, the node's beneath which an enum's members are named, +// holding a map of its own, as it writes to no node. +func viewCommon(combined ir.TypeCommon, first *ir.Scalar, id ir.TypeID) ir.TypeCommon { + site := first.TypeCommon + combined.ID, combined.Name, combined.Anonymous, combined.Provenance = id, site.Name, site.Anonymous, site.Provenance + combined.Unmodeled = maps.Clone(combined.Unmodeled) + return combined } // nearerDocs returns far with each field near sets in its place, a description @@ -179,86 +272,75 @@ func nearerDocs(far, near ir.Docs) ir.Docs { return far } -// viewOf returns a copy of end holding what a reference to chain's first alias -// reads (chainCommon) and, where its kind holds them, bounds, and false where end -// is of a kind the merge builds no node of: a model, a union or what the -// judgment reads otherwise. -func viewOf(end ir.TypeDef, chain []*ir.Scalar, bounds *ir.Constraints) (ir.TypeDef, bool) { - switch n := end.(type) { +// viewOf returns a copy of end holding typeCommon, what a reference to the +// chain's first alias reads (nearerCommon), and, where its kind holds them, +// bounds, and false where end is of a kind the merge builds no node of: a model, +// a union or what the judgment reads otherwise. +func viewOf(end ir.TypeDef, typeCommon ir.TypeCommon, bounds *ir.Constraints) (ir.TypeDef, bool) { + switch node := end.(type) { case *ir.Enum: - out := *n - out.TypeCommon = chainCommon(chain, n) + out := *node + out.TypeCommon = typeCommon return &out, true case *ir.Literal: - out := *n - out.TypeCommon = chainCommon(chain, n) + out := *node + out.TypeCommon = typeCommon return &out, true case *ir.Scalar: - out := *n - out.TypeCommon, out.Constraints = chainCommon(chain, n), bounds + out := *node + out.TypeCommon, out.Constraints = typeCommon, bounds return &out, true case *ir.List: - out := *n - out.TypeCommon, out.Constraints = chainCommon(chain, n), bounds + out := *node + out.TypeCommon, out.Constraints = typeCommon, bounds return &out, true case *ir.MapT: - out := *n - out.TypeCommon, out.Constraints = chainCommon(chain, n), bounds + out := *node + out.TypeCommon, out.Constraints = typeCommon, bounds return &out, true case *ir.Tuple: - out := *n - out.TypeCommon, out.Constraints = chainCommon(chain, n), bounds + out := *node + out.TypeCommon, out.Constraints = typeCommon, bounds return &out, true default: return nil, false } } -// standsFor relates td to the type id names where td is an alias whose chain -// reaches id: a reference to td reads all id says, and td may say more, so td -// is within it (firstTypeIsNarrower), unless a link admits null, which id -// lacks. Such a chain whose every alias says nothing else -// (aliasAddsNothingBeyondBase), docs included, adds only null, so id is within -// td (secondTypeIsNarrower). Any other is relUnrelated, for the view to judge, -// as is a td whose chain does not reach id. Docs count, as a use of td reads -// them (docs/compilers/openapi.md#ref-use-site). -func (r registry) standsFor(td ir.TypeDef, id ir.TypeID) relation { - null, says := false, false - for range maxTypeResolveDepth { - scalar, alias := td.(*ir.Scalar) - if !alias || scalar.Base == nil { - return relUnrelated - } - null, says = null || scalar.Base.Nullable, says || !aliasAddsNothingBeyondBase(scalar, false) - if scalar.Base.Target == id { - return addsNull(null, says) - } - next, ok := r.resolve(scalar.Base.Target) - if !ok { - return relUnrelated - } - td = next +// relateAliasChainTo relates typeDef, named by a use admitting null where +// useNullable, to the type id names where typeDef is an alias whose chain +// reaches id: typeDef reads all id says and may say more, so it is within id, +// unless an alias on the chain admits null the use admits too +// (docs/ir/scalars.md#aliases). A chain whose every alias says nothing else, +// docs counting (docs/compilers/openapi.md#ref-use-site), adds only null, so id +// is within typeDef. Any other is relUnrelated, as is a typeDef whose chain +// does not reach id or repeats a type. +func (r registryReader) relateAliasChainTo(typeDef ir.TypeDef, id ir.TypeID, useNullable bool) relation { + scalar, alias := typeDef.(*ir.Scalar) + if !alias || scalar.Base == nil { + return relUnrelated + } + adds := aliasAdds{null: useNullable && scalar.Base.Nullable, saysMore: !aliasAddsNothingBeyondBase(scalar)} + if scalar.Base.Target == id { + return relationOf(adds) } - return relUnrelated + below, reaches := r.chainAnswerMemos(nil).aliasesAdd.summaryBetween(scalar.Base.Target, id) + if !reaches { + return relUnrelated + } + return relationOf(aliasAdds{null: adds.null || useNullable && below.null, saysMore: adds.saysMore || below.saysMore}) } -// addsNull relates an alias chain to the type it reaches by what it adds: one -// admitting no null is within the type, one adding null alone holds it, and one -// adding null and more is related to it by neither. -func addsNull(null, says bool) relation { +// relationOf relates an alias chain to the type it reaches by what it adds: +// one admitting no null is within the type, one adding null alone holds it, +// and one adding null and more is related to it by neither. +func relationOf(adds aliasAdds) relation { switch { - case !null: + case !adds.null: return firstTypeIsNarrower - case !says: + case !adds.saysMore: return secondTypeIsNarrower default: return relUnrelated } } - -// nullThroughChain reports whether a link of td's alias chain admits null, so -// td's values hold null whatever a reference to it says. -func (r registry) nullThroughChain(td ir.TypeDef) bool { - chain, _ := r.aliasChain(td) - return slices.ContainsFunc(chain, func(scalar *ir.Scalar) bool { return scalar.Base.Nullable }) -} diff --git a/compilers/openapi/internal/merge/view_internal_test.go b/compilers/openapi/internal/merge/view_internal_test.go index 2185c698f..2277c6783 100644 --- a/compilers/openapi/internal/merge/view_internal_test.go +++ b/compilers/openapi/internal/merge/view_internal_test.go @@ -50,6 +50,8 @@ func viewRegistry() map[ir.TypeID]ir.TypeDef { alias("type/C-docs", "type/C", described("near"), nil) alias("type/C-max", "type/C", ir.TypeCommon{}, &ir.Constraints{MaxLength: new(int64(3))}) alias("type/C-cut", "type/C", ir.TypeCommon{}, &ir.Constraints{MaxLength: new(int64(2))}) + alias("type/C-pattern", "type/C", ir.TypeCommon{}, &ir.Constraints{Pattern: "^(?=a)"}) + alias("type/C-pattern-met", "type/C", ir.TypeCommon{}, &ir.Constraints{Pattern: "^a"}) alias("type/S-min", "type/S", ir.TypeCommon{}, &ir.Constraints{MinLength: new(int64(2))}) alias("type/S-pattern", "type/S", ir.TypeCommon{}, &ir.Constraints{Pattern: "^a"}) alias("type/S-pattern-b", "type/S-pattern", ir.TypeCommon{}, &ir.Constraints{Pattern: "^b"}) @@ -67,18 +69,18 @@ func viewRegistry() map[ir.TypeID]ir.TypeDef { return reg } -// TestView_ReadsAnAliasAsTheNodeItStandsFor pins what the judgment reads an +// TestView_ReadsAnAliasAsTheNodeItRepresents pins what the judgment reads an // alias chain as: the node it ends in, holding the bounds the chain and the node // say together and, field by field, the detail the nearest node sets, at the // first alias's site but for the ID, the end's, beneath which an enum's members -// are named. A chain the view cannot read so stands for itself. -func TestView_ReadsAnAliasAsTheNodeItStandsFor(t *testing.T) { +// are named. A chain the view cannot read so represents itself. +func TestView_ReadsAnAliasAsTheNodeItRepresents(t *testing.T) { t.Parallel() - registryValue := registry{resolve: stubResolve(viewRegistry())} + registry := registryReader{resolve: stubResolve(viewRegistry())} read := func(id ir.TypeID) ir.TypeDef { - td, ok := registryValue.resolve(id) + typeDef, ok := registry.resolve(id) require.True(t, ok, id) - return registryValue.view(td, "") + return registry.view(typeDef, "") } enum, ok := read("type/E-docs").(*ir.Enum) @@ -106,20 +108,23 @@ func TestView_ReadsAnAliasAsTheNodeItStandsFor(t *testing.T) { assert.True(t, ok, "an open enum's alias bounding nothing reads as the enum") _, ok = read("type/E-max").(*ir.Enum) - assert.True(t, ok, "bounds every member meets say nothing of an enum") + assert.True(t, ok, "bounds every member intersects say nothing of an enum") lit, ok := read("type/C-max").(*ir.Literal) - require.True(t, ok, "nor of a const its value meets") + require.True(t, ok, "nor of a const its value intersects") + assert.Equal(t, stringValue("abc"), lit.Value) + lit, ok = read("type/C-pattern-met").(*ir.Literal) + require.True(t, ok, "nor does a pattern its value intersects") assert.Equal(t, stringValue("abc"), lit.Value) assert.Equal(t, "near", read("type/C-docs").Common().Docs.Description) scalar, ok := read("type/S-min").(*ir.Scalar) require.True(t, ok) - assert.Equal(t, &ir.Constraints{MinLength: new(int64(2)), MaxLength: new(int64(5))}, scalar.Constraints, "bounds meet") + assert.Equal(t, &ir.Constraints{MinLength: new(int64(2)), MaxLength: new(int64(5))}, scalar.Constraints, "bounds intersect") assert.Equal(t, ir.TypeRef{Target: "type/primitive/string"}, *scalar.Base, "an alias of a scalar reads as the scalar over its kind") list, ok := read("type/L-max-docs").(*ir.List) require.True(t, ok) assert.Equal(t, &ir.Constraints{MinItems: new(int64(2)), MaxItems: new(int64(3))}, list.Constraints, - "bounds meet down the chain") + "bounds intersect down the chain") assert.Equal(t, "near", list.Docs.Description) assert.Equal(t, ir.Unmodeled{"openapi:x-k": {Value: ir.RawValue("1")}}, read("type/L-kept").Common().Unmodeled, "a key only the alias keeps") @@ -131,11 +136,11 @@ func TestView_ReadsAnAliasAsTheNodeItStandsFor(t *testing.T) { assert.Nil(t, tuple.Constraints, "a chain bounding nothing adds no bounds") for _, id := range []ir.TypeID{ - "type/E-cut", "type/E-pattern", "type/OE-max", "type/C-cut", "type/S-pattern-b", "type/L-encoded", "type/L-ref", "type/Ref-docs", + "type/E-cut", "type/E-pattern", "type/OE-max", "type/C-cut", "type/C-pattern", "type/S-pattern-b", "type/L-encoded", "type/L-ref", "type/Ref-docs", "type/Model-docs", "type/gone", "type/gone-deep", "type/S", "type/E", "type/primitive/string", } { - td, _ := registryValue.resolve(id) - assert.Same(t, td, read(id), "%s stands for itself", id) + typeDef, _ := registry.resolve(id) + assert.Same(t, typeDef, read(id), "%s represents itself", id) } } @@ -143,25 +148,25 @@ func TestView_ReadsAnAliasAsTheNodeItStandsFor(t *testing.T) { // an alias naming it is the node, and a chain past it reads to its own end. func TestView_StopsAtTheNodeTheChainsShare(t *testing.T) { t.Parallel() - registryValue := registry{resolve: stubResolve(viewRegistry())} - maxDocs, _ := registryValue.resolve("type/L-max-docs") - maxOnly, _ := registryValue.resolve("type/L-max") + registry := registryReader{resolve: stubResolve(viewRegistry())} + maxDocs, _ := registry.resolve("type/L-max-docs") + maxOnly, _ := registry.resolve("type/L-max") - assert.Same(t, maxOnly, registryValue.view(maxOnly, "type/L"), "an alias naming the stop is the node") - scalar, ok := registryValue.view(maxDocs, "type/L").(*ir.Scalar) + assert.Same(t, maxOnly, registry.view(maxOnly, "type/L"), "an alias naming the stop is the node") + scalar, ok := registry.view(maxDocs, "type/L").(*ir.Scalar) require.True(t, ok, "a chain read down to the stop is an alias of it") assert.Equal(t, ir.TypeRef{Target: "type/L"}, *scalar.Base) assert.Equal(t, &ir.Constraints{MinItems: new(int64(2)), MaxItems: new(int64(3))}, scalar.Constraints) assert.Equal(t, "near", scalar.Docs.Description) } -// TestSharedLink_NamesTheFirstNodeEveryChainNames pins where aliases stop being +// TestSharedAlias_NamesTheFirstNodeEveryChainNames pins where aliases stop being // read through: at the first node every chain names, and nowhere where one names // none, or no node all of them name. -func TestSharedLink_NamesTheFirstNodeEveryChainNames(t *testing.T) { +func TestSharedAlias_NamesTheFirstNodeEveryChainNames(t *testing.T) { t.Parallel() - registryValue := registry{resolve: stubResolve(viewRegistry())} - node := func(id ir.TypeID) ir.TypeDef { td, _ := registryValue.resolve(id); return td } + registry := registryReader{resolve: stubResolve(viewRegistry())} + node := func(id ir.TypeID) ir.TypeDef { typeDef, _ := registry.resolve(id); return typeDef } for _, tc := range []struct { name string ids []ir.TypeID @@ -169,7 +174,7 @@ func TestSharedLink_NamesTheFirstNodeEveryChainNames(t *testing.T) { }{ {"two aliases of one list", []ir.TypeID{"type/L-max", "type/L-ref"}, "type/L"}, {"a chain and an alias of its end", []ir.TypeID{"type/L-max-docs", "type/L-ref"}, "type/L"}, - {"a chain and an alias of its link", []ir.TypeID{"type/L-max-docs", "type/L-max-docs"}, "type/L-max"}, + {"a chain and an alias of its alias", []ir.TypeID{"type/L-max-docs", "type/L-max-docs"}, "type/L-max"}, {"three aliases of one enum", []ir.TypeID{"type/E-docs", "type/E-max", "type/E-over-docs"}, "type/E"}, {"one alias among three of another node", []ir.TypeID{"type/E-docs", "type/E-max", "type/L-max"}, ""}, {"aliases of two nodes", []ir.TypeID{"type/E-docs", "type/L-max"}, ""}, @@ -180,72 +185,67 @@ func TestSharedLink_NamesTheFirstNodeEveryChainNames(t *testing.T) { for k, id := range tc.ids { tds[k] = node(id) } - assert.Equal(t, tc.want, registryValue.sharedLink(tds...), tc.name) + assert.Equal(t, tc.want, registry.sharedAlias(tds...), tc.name) } } -// TestAliasedNode_ReadsAChainUpToItsBound pins maxTypeResolveDepth on the view: -// a chain of that many aliases is read to the node it ends in, and one more -// reads as no chain, so the alias stands for itself. -func TestAliasedNode_ReadsAChainUpToItsBound(t *testing.T) { +// TestAliasedNode_ReadsAChainToItsEnd pins the view and relateAliasChainTo on a long +// chain: one of any length is read to the node it ends in, past the 64 +// aliases a walk once stopped at, where one more read as no chain. +func TestAliasedNode_ReadsAChainToItsEnd(t *testing.T) { t.Parallel() - for _, tc := range []struct { - name string - aliases int - read bool - }{ - {"at the bound", maxTypeResolveDepth, true}, - {"past the bound", maxTypeResolveDepth + 1, false}, - } { + for _, aliases := range []int{64, 65, 200} { reg := viewRegistry() next := ir.TypeID("type/L") - for i := range tc.aliases { + for i := range aliases { id := ir.TypeID(fmt.Sprintf("type/link-%d", i)) reg[id] = &ir.Scalar{ID: id, Base: &ir.TypeRef{Target: next}} next = id } - registryValue := registry{resolve: stubResolve(reg)} + registry := registryReader{resolve: stubResolve(reg)} - _, isList := registryValue.view(reg[next], "").(*ir.List) + _, isList := registry.view(reg[next], "").(*ir.List) - assert.Equal(t, tc.read, isList, tc.name) - assert.Equal(t, tc.read, registryValue.standsFor(reg[next], "type/L") == firstTypeIsNarrower, "%s: standsFor reads as far", tc.name) + assert.True(t, isList, "%d aliases", aliases) + assert.Equal(t, firstTypeIsNarrower, registry.relateAliasChainTo(reg[next], "type/L", false), "%d aliases: relateAliasChainTo reads as far", aliases) } } -// TestStandsFor_ReadsOnlyAnAliasChain pins which types an alias stands for: each -// node its chain names, within it, but through a link admitting null, which -// adds null to it alone or more, docs counted; and nothing for a node that is -// no alias, a chain naming nothing the registry holds, or a type the chain does -// not name. -func TestStandsFor_ReadsOnlyAnAliasChain(t *testing.T) { +// TestRepresents_ReadsOnlyAnAliasChain pins which types an alias represents: +// each node its chain names, within it, but through an alias admitting null a +// use admitting null names, which adds null to it alone or more, docs counted; +// a alias's null going no further than the use's bit +// (docs/ir/scalars.md#aliases); and nothing for a node that is no alias, a +// chain naming nothing the registry holds, or a type the chain does not name. +func TestRepresents_ReadsOnlyAnAliasChain(t *testing.T) { t.Parallel() reg := nullableAliases(viewRegistry()) - registryValue := registry{resolve: stubResolve(reg)} + registry := registryReader{resolve: stubResolve(reg)} for _, tc := range []struct { - td ir.TypeID - id ir.TypeID - want relation + typeDef ir.TypeID + id ir.TypeID + useNullable bool + want relation }{ - {"type/L-max-docs", "type/L-max", firstTypeIsNarrower}, - {"type/L-max-docs", "type/L", firstTypeIsNarrower}, - {"type/L-max", "type/L-max-docs", relUnrelated}, - {"type/L", "type/L", relUnrelated}, - {"type/gone", "type/L", relUnrelated}, - {"type/S", "type/primitive/string", firstTypeIsNarrower}, - {"type/L-null", "type/L", secondTypeIsNarrower}, - {"type/L-null-docs", "type/L", relUnrelated}, - {"type/L-null-max", "type/L", relUnrelated}, - {"type/L-over-null", "type/L", relUnrelated}, - {"type/L-over-null", "type/L-null", firstTypeIsNarrower}, - {"type/L-over-null-docs", "type/L", relUnrelated}, - {"type/L-over-null-bare", "type/L", secondTypeIsNarrower}, + {"type/L-max-docs", "type/L-max", true, firstTypeIsNarrower}, + {"type/L-max-docs", "type/L", true, firstTypeIsNarrower}, + {"type/L-max", "type/L-max-docs", true, relUnrelated}, + {"type/L", "type/L", true, relUnrelated}, + {"type/gone", "type/L", true, relUnrelated}, + {"type/S", "type/primitive/string", true, firstTypeIsNarrower}, + {"type/L-null", "type/L", true, secondTypeIsNarrower}, + {"type/L-null-docs", "type/L", true, relUnrelated}, + {"type/L-null-max", "type/L", true, relUnrelated}, + {"type/L-over-null", "type/L", true, relUnrelated}, + {"type/L-over-null", "type/L-null", true, firstTypeIsNarrower}, + {"type/L-over-null-docs", "type/L", true, relUnrelated}, + {"type/L-over-null-bare", "type/L", true, secondTypeIsNarrower}, + {"type/L-null", "type/L", false, firstTypeIsNarrower}, + {"type/L-null-docs", "type/L", false, firstTypeIsNarrower}, + {"type/L-over-null-bare", "type/L", false, firstTypeIsNarrower}, } { - assert.Equal(t, tc.want, registryValue.standsFor(reg[tc.td], tc.id), "%s for %s", tc.td, tc.id) + assert.Equal(t, tc.want, registry.relateAliasChainTo(reg[tc.typeDef], tc.id, tc.useNullable), "%s for %s, use nullable %t", tc.typeDef, tc.id, tc.useNullable) } - assert.True(t, registryValue.nullThroughChain(reg["type/L-over-null"]), "a link past the first admits null") - assert.False(t, registryValue.nullThroughChain(reg["type/L-max-docs"])) - assert.False(t, registryValue.nullThroughChain(reg["type/L"]), "no alias") assert.Empty(t, cmp.Diff(nullableAliases(viewRegistry()), reg), "reading writes to no node") } diff --git a/compilers/openapi/internal/merge/visibility.go b/compilers/openapi/internal/merge/visibility.go index 87bca2602..2b7ed3a64 100644 --- a/compilers/openapi/internal/merge/visibility.go +++ b/compilers/openapi/internal/merge/visibility.go @@ -52,13 +52,13 @@ func intersectLifecycles(a, b []ir.Lifecycle) []ir.Lifecycle { a, b = b, a } inB := make(map[ir.Lifecycle]bool, len(b)) - for _, l := range b { - inB[l] = true + for _, lifecycle := range b { + inB[lifecycle] = true } var out []ir.Lifecycle - for _, l := range a { - if inB[l] { - out = append(out, l) + for _, lifecycle := range a { + if inB[lifecycle] { + out = append(out, lifecycle) } } return out diff --git a/compilers/openapi/internal/merge/written.go b/compilers/openapi/internal/merge/written.go new file mode 100644 index 000000000..486680102 --- /dev/null +++ b/compilers/openapi/internal/merge/written.go @@ -0,0 +1,45 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "cmp" + "slices" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" + "github.com/dexpace/morphic/ir" +) + +// writtenBefore reports whether a is written before b (compareSourceOrder). +func writtenBefore(a, b ir.Provenance) bool { + return compareSourceOrder(a, b) < 0 +} + +// writtenOrder returns the indices of decls in the order their places are +// written, two at one place as decls holds them: the one order a fold's cut +// and a cycle's fold read declarations in. +func writtenOrder(merger *Merger, decls []declaration) []int { + places, order := make([]ir.Provenance, len(decls)), make([]int, len(decls)) + for i, declaration := range decls { + places[i], order[i] = fieldPlace(merger, declaration, fieldGivenTogether), i + } + slices.SortStableFunc(order, func(a, b int) int { return compareSourceOrder(places[a], places[b]) }) + return order +} + +// compareSourceOrder orders two places as a document set is written: by the +// document listed first, which the load phase orders by name, not as +// declarations reach it, then by pointer (provenance.ComparePointers). Two +// files each holding one schema write the same pointers. +func compareSourceOrder(a, b ir.Provenance) int { + return cmp.Or(cmp.Compare(a.Source, b.Source), provenance.ComparePointers(a.Pointer, b.Pointer)) +} + +// compareWrittenTargets orders two nodes, a written at aAt and b at bAt, as a +// fold names the least of nodes alike: by where each is written +// (compareSourceOrder), then by ID, which orders two written at one place. +func compareWrittenTargets(a ir.TypeID, aAt ir.Provenance, b ir.TypeID, bAt ir.Provenance) int { + return cmp.Or(compareSourceOrder(aAt, bAt), strings.Compare(string(a), string(b))) +} diff --git a/compilers/openapi/internal/merge/written_internal_test.go b/compilers/openapi/internal/merge/written_internal_test.go new file mode 100644 index 000000000..86e2bb5a0 --- /dev/null +++ b/compilers/openapi/internal/merge/written_internal_test.go @@ -0,0 +1,22 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package merge + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestWrittenBefore_ReadsTheDocumentThenThePointer pins the order of two +// places: a document listed first before any place of another, then the +// pointer written first, an array index by its number. +func TestWrittenBefore_ReadsTheDocumentThenThePointer(t *testing.T) { + t.Parallel() + assert.True(t, writtenBefore(ir.Provenance{Source: 0, Pointer: "/Z"}, ir.Provenance{Source: 1, Pointer: "/A"}), "the document listed first") + assert.True(t, writtenBefore(ir.Provenance{Pointer: "/M/allOf/9"}, ir.Provenance{Pointer: "/M/allOf/10"})) + assert.False(t, writtenBefore(ir.Provenance{Pointer: "/M/allOf/10"}, ir.Provenance{Pointer: "/M/allOf/9"})) +} diff --git a/compilers/openapi/internal/naming/naming.go b/compilers/openapi/internal/naming/naming.go index 5897a4f80..68e1286cf 100644 --- a/compilers/openapi/internal/naming/naming.go +++ b/compilers/openapi/internal/naming/naming.go @@ -26,21 +26,26 @@ const MaxHops = 64 // alone, so the memo answers as a fresh Namer would. A Namer must not outlive // the trees its table holds, and is not safe for concurrent use. type Namer struct { - table *reftable.ReferenceTargetTable - views map[reftable.DocID]*nodeview.View - memo map[reftable.DocumentPointer]string + table *reftable.ReferenceTargetTable + statements *statement.MemoizingSchemaReader + views map[reftable.DocID]*nodeview.View + memo map[reftable.DocumentPointer]string // titles reads the title a schema names its node by, and is nil where // titles name nothing. titles *titles } -// New returns a Namer over the documents table read, naming a schema by its -// title where byTitle holds (titles.at), and by its position where it does -// not. A nil table reads none, and names each position by its pointer alone. -func New(table *reftable.ReferenceTargetTable, byTitle bool) *Namer { - namer := &Namer{table: table, views: map[reftable.DocID]*nodeview.View{}, memo: map[reftable.DocumentPointer]string{}} +// New returns a Namer over the documents statements reads, each schema as its +// statement says (statement.MemoizingSchemaReader), naming one by its title +// where byTitle holds (titles.at), and by its position where it does not. A nil +// statements reads none, and names each position by its pointer alone. +func New(statements *statement.MemoizingSchemaReader, byTitle bool) *Namer { + table := statements.ReferenceTargets() + namer := &Namer{table: table, statements: statements, views: map[reftable.DocID]*nodeview.View{}, + memo: map[reftable.DocumentPointer]string{}} if byTitle { - namer.titles = &titles{table: table, read: map[*yaml.Node]string{}, lists: map[reftable.DocumentPointer]map[string]int{}} + namer.titles = &titles{table: table, statements: statements, read: map[reftable.DocumentPointer]string{}, + lists: map[reftable.DocumentPointer]map[string]int{}} } return namer } @@ -71,21 +76,13 @@ func (n *Namer) at(documentPointer reftable.DocumentPointer, hops int) string { } // conjoined reports whether the schema at documentPointer writes a key beside -// its reference that it reads (statement.ReadBeside), which makes it the -// conjunction of the two, a node of the position's own, named by its position -// as any other (docs/compilers/openapi.md#naming); a reference alone is named -// after what it names. +// its reference that it reads, which its statement lists as a conjunct of its +// own (statement.Schema.BesideRef): the conjunction of the two is a node of the +// position's own, named by its position as any other +// (docs/compilers/openapi.md#naming), and a reference alone is named after what +// it names. func (n *Namer) conjoined(documentPointer reftable.DocumentPointer) bool { - if n.table == nil { - return false - } - referenceSite, ok := n.table.Entry(documentPointer) - if !ok { - return false - } - return slices.ContainsFunc(n.view(documentPointer.Doc).MappingPairs(n.node(documentPointer.Doc, documentPointer.Pointer)), func(kv nodeview.Pair) bool { - return statement.ReadBeside(kv.Key, kv.Val, referenceSite.Keyword) - }) + return n.statements != nil && n.statements.At(documentPointer).BesideRef != nil } // walk names documentPointer from its owner down the structure to it (steps), @@ -98,8 +95,11 @@ func (n *Namer) walk(documentPointer reftable.DocumentPointer) (hint string, bra start, owner := n.owner(documentPointer, tokens, reading.kinds) var title titler if n.titles != nil { + spelled, ends := prefixEnds(documentPointer.Pointer, tokens) title = func(consumed int, union bool) string { - return n.titles.at(documentPointer.Doc, tokens[:start+consumed], reading, union) + tokensWalked := start + consumed + position := reftable.DocumentPointer{Doc: documentPointer.Doc, Pointer: spelled[:ends[tokensWalked]]} + return n.titles.at(position, tokens[:tokensWalked], reading, union) } } return steps(owner, tokens[start:], title) @@ -125,7 +125,7 @@ func (n *Namer) through(documentPointer reftable.DocumentPointer, hops int) stri if n.table == nil || hops >= MaxHops { return "" } - referenceSite, ok := n.table.Entry(documentPointer) + referenceSite, ok := n.table.ReferenceSiteAt(documentPointer) switch { case !ok: return "" diff --git a/compilers/openapi/internal/naming/naming_internal_test.go b/compilers/openapi/internal/naming/naming_internal_test.go index 8faa6dbe6..81f8538f1 100644 --- a/compilers/openapi/internal/naming/naming_internal_test.go +++ b/compilers/openapi/internal/naming/naming_internal_test.go @@ -10,17 +10,19 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers" "github.com/dexpace/morphic/compilers/openapi/internal/load" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/engine/reader" ) -// loaded returns the table a load of spec binds. -func loaded(t *testing.T, spec string) *reftable.ReferenceTargetTable { +// loaded returns the statement table over what a load of spec binds. +func loaded(t *testing.T, spec string) *statement.MemoizingSchemaReader { t.Helper() dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "root.yaml"), []byte(spec), 0o600)) @@ -28,7 +30,18 @@ func loaded(t *testing.T, spec string) *reftable.ReferenceTargetTable { Data: []byte(spec)}, load.Options{Reader: reader.Disk{}}) require.NoError(t, err) require.NotNil(t, doc) - return doc.Bindings.Table() + return statement.NewTable(statement.Source{Bindings: doc.Bindings, Rules: doc.Dialects}) +} + +// TestItems_ReadsASequenceAlone pins that a list's items are those of a +// sequence alone: a list written as a mapping, which load reports, and no node +// have none to read. +func TestItems_ReadsASequenceAlone(t *testing.T) { + t.Parallel() + sequence := &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{{Kind: yaml.ScalarNode, Value: "a"}}} + assert.Equal(t, sequence.Content, items(sequence)) + assert.Nil(t, items(&yaml.Node{Kind: yaml.MappingNode})) + assert.Nil(t, items(nil)) } // TestNode_ReadsNothingTheTableDoesNotHold pins that node reads only a @@ -39,7 +52,7 @@ func TestNode_ReadsNothingTheTableDoesNotHold(t *testing.T) { namer := New(tb, true) require.NotNil(t, namer.node(reftable.Source, "/components/schemas/A"), "sanity: the source holds A") assert.Nil(t, namer.node(-1, "/components/schemas/A")) - assert.Nil(t, namer.node(reftable.DocID(tb.Documents()), "/components/schemas/A")) + assert.Nil(t, namer.node(reftable.DocID(tb.ReferenceTargets().Documents()), "/components/schemas/A")) assert.Nil(t, New(nil, true).node(reftable.Source, "/components/schemas/A")) } diff --git a/compilers/openapi/internal/naming/naming_test.go b/compilers/openapi/internal/naming/naming_test.go index 981d8c4e2..3e2b8457a 100644 --- a/compilers/openapi/internal/naming/naming_test.go +++ b/compilers/openapi/internal/naming/naming_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "strconv" "strings" "testing" @@ -20,6 +21,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/load" "github.com/dexpace/morphic/compilers/openapi/internal/naming" "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/engine/reader" ) @@ -27,8 +29,8 @@ import ( const head = "openapi: 3.1.0\ninfo: {title: T, version: \"1\"}\n" // table loads spec as root.yaml beside others, each written to disk under its -// name, and returns the table the load bound. -func table(t *testing.T, spec string, others map[string]string) *reftable.ReferenceTargetTable { +// name, and returns the statement table over what the load bound. +func table(t *testing.T, spec string, others map[string]string) *statement.MemoizingSchemaReader { t.Helper() dir := t.TempDir() for name, body := range others { @@ -38,7 +40,7 @@ func table(t *testing.T, spec string, others map[string]string) *reftable.Refere Data: []byte(spec)}, load.Options{Reader: reader.Disk{}}) require.NoError(t, err) require.NotNil(t, doc) - return doc.Bindings.Table() + return statement.NewTable(statement.Source{Bindings: doc.Bindings, Rules: doc.Dialects}) } // documentPointerAt is the source's position at pointer. @@ -47,8 +49,9 @@ func documentPointerAt(pointer string) reftable.DocumentPointer { } // docNamed returns the number of the document the table read as name. -func docNamed(t *testing.T, tb *reftable.ReferenceTargetTable, name string) reftable.DocID { +func docNamed(t *testing.T, statements *statement.MemoizingSchemaReader, name string) reftable.DocID { t.Helper() + tb := statements.ReferenceTargets() for id := range tb.Documents() { if strings.HasSuffix(tb.Document(reftable.DocID(id)).Name, "/"+name) { return reftable.DocID(id) @@ -67,7 +70,7 @@ func docNamed(t *testing.T, tb *reftable.ReferenceTargetTable, name string) reft // since the owner is the component. func TestAt_NamesASchemaByItsStructure(t *testing.T) { t.Parallel() - tb := table(t, head+"paths: {}\ncomponents: {schemas: {Foo: {type: object}}}\n", nil) + const spec = head + "paths: {}\ncomponents: {schemas: {Foo: {type: object}}}\n" tests := []struct { name, pointer, want string }{ @@ -130,7 +133,7 @@ func TestAt_NamesASchemaByItsStructure(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - assert.Equal(t, tc.want, naming.New(tb, true).At(documentPointerAt(tc.pointer)), "read") + assert.Equal(t, tc.want, naming.New(table(t, spec, nil), true).At(documentPointerAt(tc.pointer)), "read") assert.Equal(t, tc.want, naming.New(nil, true).At(documentPointerAt(tc.pointer)), "by pointer alone") }) } @@ -205,7 +208,6 @@ components: // callback, a webhook or a component path item. func TestAt_NamesASchemaAfterItsOwner(t *testing.T) { t.Parallel() - tb := table(t, ownersSpec, nil) const operation = "/paths/~1a/post" const json = "/content/application~1json/schema" tests := []struct { @@ -249,7 +251,7 @@ func TestAt_NamesASchemaAfterItsOwner(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - assert.Equal(t, tc.want, naming.New(tb, true).At(documentPointerAt(tc.pointer))) + assert.Equal(t, tc.want, naming.New(table(t, ownersSpec, nil), true).At(documentPointerAt(tc.pointer))) }) } } @@ -566,6 +568,10 @@ components: referenced: {allOf: [{$ref: '#/components/schemas/Pet', title: Beside A Ref}]} dynamic: {allOf: [{$dynamicRef: '#/components/schemas/Pet', title: Beside A Dynamic Ref}]} nested: {allOf: [{allOf: [{title: Deep, type: object}]}]} + failed: + allOf: + - {$ref: '#/components/schemas/Missing', allOf: [{title: Deep Title}]} + - {type: object, properties: {a: {type: string}}} mapped: {allOf: {a: {title: Mapped Title, type: object}}} $defs: Local: {title: Not This, type: object} @@ -602,11 +608,10 @@ components: // A title is read as the parser reads a string. func TestAt_NamesASchemaByItsTitle(t *testing.T) { t.Parallel() - tb := table(t, titlesSpec, nil) for _, tc := range titleRows { t.Run(tc.name, func(t *testing.T) { t.Parallel() - assert.Equal(t, tc.want, naming.New(tb, true).At(documentPointerAt(tc.pointer))) + assert.Equal(t, tc.want, naming.New(table(t, titlesSpec, nil), true).At(documentPointerAt(tc.pointer))) }) } } @@ -646,6 +651,9 @@ var titleRows = func() []struct{ name, pointer, want string } { {"a title beside a $ref in an allOf", keyed + "/properties/referenced", "beside_a_ref"}, {"a title beside a $dynamicRef in an allOf", keyed + "/properties/dynamic", "beside_a_dynamic_ref"}, {"a title an allOf entry nests", keyed + "/properties/nested", "deep"}, + // The reference names nothing, so the entry is read as it is without it, + // an entry naming no kind whose allOf the flattening reaches. + {"a title nested in an entry whose $ref names nothing, read as without it", keyed + "/properties/failed", "deep_title"}, {"a title under an allOf written as a mapping", keyed + "/properties/mapped", "mapped"}, {"a title a branch's allOf writes is its siblings' too", "/components/schemas/Conjoined/anyOf/0", "variant_0"}, {"a $defs entry keeps its key", keyed + "/$defs/Local", "Local"}, @@ -722,6 +730,28 @@ func TestTitle_IsTheNameATitleGives(t *testing.T) { assert.Empty(t, title) } +// TestTitle_ReadsAnInvalidPointerByItsTokens pins that a pointer spelt as no +// valid one is, here without its leading '/', reads the titles on the way to +// it as the valid pointer spelling the same tokens does. +func TestTitle_ReadsAnInvalidPointerByItsTokens(t *testing.T) { + t.Parallel() + valid := naming.New(table(t, titlesSpec, nil), true) + invalid := naming.New(table(t, titlesSpec, nil), true) + titled := 0 + for _, tc := range titleRows { + spelt := documentPointerAt(strings.TrimPrefix(tc.pointer, "/")) + require.False(t, spelt.Pointer.IsValid(), tc.name) + wantTitle, wantTitled := valid.Title(documentPointerAt(tc.pointer)) + title, ok := invalid.Title(spelt) + assert.Equal(t, wantTitle, title, tc.name) + assert.Equal(t, wantTitled, ok, tc.name) + if ok { + titled++ + } + } + assert.Positive(t, titled, "the rows name some position by its title") +} + // TestAt_ATitleNamesAlikeInEitherOrder pins that the names two branches titled // alike fall back to, and a lone title, are the same whichever branch is asked // first and whichever the list writes first. @@ -773,6 +803,49 @@ components: "a title another document's component is named by") } +// TestAt_ATitleNamesEachDocumentsSchemaByItsOwn pins that where two documents +// write a schema at one pointer, titled apart, each is named by its own +// document's title, and each branch of a oneOf both write at one pointer by +// the titles its own list writes, whichever document is asked first. +func TestAt_ATitleNamesEachDocumentsSchemaByItsOwn(t *testing.T) { + t.Parallel() + tb := table(t, head+`paths: {} +components: + schemas: + A: {type: object, properties: {p: {title: Root Title, type: object}}} + U: {oneOf: [{title: Same, type: object}, {title: Same, type: object}]} + B: {$ref: 'other.yaml#/components/schemas/A'} + V: {$ref: 'other.yaml#/components/schemas/U'} +`, map[string]string{ + "other.yaml": `components: + schemas: + A: {type: object, properties: {p: {title: Other Title, type: object}}} + U: {oneOf: [{title: Same, type: object}, {title: Lone, type: object}]} +`, + }) + other := docNamed(t, tb, "other.yaml") + type named struct { + at reftable.DocumentPointer + want string + } + forward := []named{ + {documentPointerAt("/components/schemas/A/properties/p"), "root_title"}, + {documentPointerAt("/components/schemas/U/oneOf/0"), "variant_0"}, + {documentPointerAt("/components/schemas/U/oneOf/1"), "variant_1"}, + {reftable.DocumentPointer{Doc: other, Pointer: "/components/schemas/A/properties/p"}, "other_title"}, + {reftable.DocumentPointer{Doc: other, Pointer: "/components/schemas/U/oneOf/0"}, "same"}, + {reftable.DocumentPointer{Doc: other, Pointer: "/components/schemas/U/oneOf/1"}, "lone"}, + } + backward := slices.Clone(forward) + slices.Reverse(backward) + for order, asked := range map[string][]named{"the source first": forward, "the other document first": backward} { + read := naming.New(tb, true) + for _, row := range asked { + assert.Equal(t, row.want, read.At(row.at), "%s: %v", order, row.at) + } + } +} + // TestAt_NamesAHeaderAnEncodingNests pins that a schema under a header of an // Encoding Object another nests, through 3.2's encoding, prefixEncoding or // itemEncoding, is named by the header's key, its content's and its diff --git a/compilers/openapi/internal/naming/owners_internal_test.go b/compilers/openapi/internal/naming/owners_internal_test.go index 3b223adfc..fdceb52db 100644 --- a/compilers/openapi/internal/naming/owners_internal_test.go +++ b/compilers/openapi/internal/naming/owners_internal_test.go @@ -15,7 +15,7 @@ import ( // type's owner. The grammar reads a media type only as a components/mediaTypes // entry or an entry of a content map, whose holder is a request body, a // response, a parameter or a header, so neither guard is reached through At; -// each stands for a grammar that grows a media type anywhere else, which must +// each names a grammar that grows a media type anywhere else, which must // name it nothing rather than read past the pointer's start. func TestOwnerOf_NamesOnlyAMediaTypeAContentMapHolds(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/naming/steps.go b/compilers/openapi/internal/naming/steps.go index 01860d238..9bdc01940 100644 --- a/compilers/openapi/internal/naming/steps.go +++ b/compilers/openapi/internal/naming/steps.go @@ -15,12 +15,12 @@ import ( // steps composes the hint of the position the schema keywords in rest lead to // from enclosing, the hint of the position they start at. It reports whether -// that position is a composition branch, which Namer.branch names further, -// and whether its own title named it. title names the position consumed -// tokens of rest lead to by its title (titles.at), asked of each but one a -// step names by the document's own key, and a name it gives stands in for the -// one composed so far, so the positions beneath compose from it. Each step -// consumes a token, bounding the walk. +// that position is a composition branch, which Namer.branch names further, and +// whether its own title named it. title names the position consumed tokens of +// rest lead to by its title (titles.at), asked of each but one a step names by +// the document's own key, and a name it gives takes the place of the one +// composed so far, so the positions beneath compose from it. Each step consumes +// a token, bounding the walk. func steps(enclosing string, rest []string, title titler) (hint string, branch, titled bool) { chainValue := chain{base: enclosing} if t := title.at(0, false); t != "" { @@ -37,7 +37,7 @@ func steps(enclosing string, rest []string, title titler) (hint string, branch, chainValue, branch, titled = chain{base: t}, false, true } } - return compile.SubHints(chainValue.base, chainValue.parts...), branch, titled + return compile.SubHints(chainValue.baseName(), chainValue.parts...), branch, titled } // titler returns the name the title of the position consumed tokens of a walk @@ -55,10 +55,22 @@ func (t titler) at(consumed int, union bool) string { // chain is a hint being composed: base, then each part compile.SubHint would // append to it, joined once (compile.SubHints) rather than at every step, so a -// position n roles deep costs n parts rather than n² bytes. +// position n roles deep costs n parts rather than n² bytes. A chain starting at +// a composition branch holds its index, and baseName builds the name only when +// joined, so a branch a walk passes, or a title renames, builds none. type chain struct { - base string - parts []string + base string + branch string + parts []string +} + +// baseName returns the name c starts from: its base, or its branch's +// positional name (positionalBranch) where it starts at a branch. +func (c chain) baseName() string { + if c.branch != "" { + return positionalBranch(c.branch) + } + return c.base } // then is c with part composed onto it. steps keeps only the chain a step @@ -112,7 +124,7 @@ func stepOf(enclosing chain, rest []string) step { // there is that schema's, and named as it is. return step{hint: enclosing, tokens: 2, branch: true, keyed: true} case compositionKeywords[keyword] && isDecimalIndex(child): - return step{hint: chain{base: positionalBranch(child)}, tokens: 2, branch: true, union: true} + return step{hint: chain{branch: child}, tokens: 2, branch: true, union: true} case keyword == "type" && isDecimalIndex(child): // One variant of a multi-typed schema, built from that schema itself, // so it is named as the schema is. diff --git a/compilers/openapi/internal/naming/titles.go b/compilers/openapi/internal/naming/titles.go index 362499aad..6db5d3bc4 100644 --- a/compilers/openapi/internal/naming/titles.go +++ b/compilers/openapi/internal/naming/titles.go @@ -4,6 +4,7 @@ package naming import ( + "encoding/json/jsontext" "strconv" "strings" @@ -57,68 +58,92 @@ func (n *Namer) Title(documentPointer reftable.DocumentPointer) (string, bool) { // documents. type titles struct { table *reftable.ReferenceTargetTable - read map[*yaml.Node]string + statements *statement.MemoizingSchemaReader + read map[reftable.DocumentPointer]string lists map[reftable.DocumentPointer]map[string]int components map[string]bool } -// at returns the words of the title the schema tokens leads to in doc writes, -// as readingValue reads the way there, where they name the node built there; -// union marks a oneOf or anyOf branch. They name none where the grammar reads -// no schema there or the document holds no node; at a component schema, which -// its key names; where the title has no word; and where its words are a -// component schema's name, or another branch's of the list a branch is in -// (collides). The position then keeps the name it has without a title. -func (t *titles) at(doc reftable.DocID, tokens []string, readingValue reading, union bool) string { +// at returns the words of the title the schema at position writes, whose +// pointer spells tokens as pointerOf does, as readingValue reads the way there, +// where they name the node built there; union marks a oneOf or anyOf branch. +// They name none where the grammar reads no schema there or the document holds +// no node; at a component schema, which its key names; where the title has no +// word; and where its words are a component schema's name, or another branch's +// of the list a branch is in (collides). The position then keeps the name it +// has without a title. +func (t *titles) at(position reftable.DocumentPointer, tokens []string, readingValue reading, union bool) string { k := len(tokens) if k >= len(readingValue.path) || k >= len(readingValue.kinds) || readingValue.kinds[k] != reftable.KindSchema || componentRoot(tokens) { return "" } - words := t.words(readingValue.path[k]) + words := t.words(position, readingValue.path[k]) if words == "" || t.componentNames()[words] { return "" } - if union && t.collides(doc, tokens, readingValue.path[k-1], words) { + if union && t.collides(position, readingValue.path[k-1], words) { return "" } return words } +// prefixEnds returns pointer, whose tokens are tokens, spelt as pointerOf +// spells them, and ends[k], where its first k tokens end, so the pointer to +// each position on the way is a slice of one spelling rather than joined anew +// at every step. A valid pointer is that spelling already, as each '/' in it +// begins a token; one that is not is spelt anew. +func prefixEnds(pointer jsontext.Pointer, tokens []string) (spelled jsontext.Pointer, ends []int) { + spelled = pointer + if !spelled.IsValid() { + spelled = pointerOf(tokens) + } + ends = make([]int, 0, len(tokens)+1) + for i := range len(spelled) { + if spelled[i] == '/' { + ends = append(ends, i) + } + } + return spelled, append(ends, len(spelled)) +} + // componentRoot reports whether tokens leads to a component schema, which its // key names however its title reads (ids.ComponentSchema). func componentRoot(tokens []string) bool { return len(tokens) == componentSchemaTokens && tokens[0] == "components" && tokens[1] == "schemas" } -// collides reports whether words, the title of the branch tokens leads to in -// doc, of the list written as list, would name it as another branch of the -// list is named: a title two branches write names neither, whichever comes -// first, and one spelling a branch's positional name (positionalBranch) is -// that branch's, its own included, which the title would name as its position -// does. -func (t *titles) collides(doc reftable.DocID, tokens []string, list *yaml.Node, words string) bool { - if t.listed(doc, tokens[:len(tokens)-1], list)[words] > 1 { +// collides reports whether words, the title of the branch at position, of the +// list written as list, would name it as another branch of the list is named: +// a title two branches write names neither, whichever comes first, and one +// spelling a branch's positional name (positionalBranch) is that branch's, its +// own included, which the title would name as its position does. +func (t *titles) collides(position reftable.DocumentPointer, list *yaml.Node, words string) bool { + holder := reftable.DocumentPointer{Doc: position.Doc, Pointer: position.Pointer.Parent()} + if t.listed(holder, list)[words] > 1 { return true } index, positional := strings.CutPrefix(words, positionalBranch("")) + if !positional { + return false + } j, err := strconv.Atoi(index) - return positional && err == nil && strconv.Itoa(j) == index && j < len(items(list)) + return err == nil && strconv.Itoa(j) == index && j < len(items(list)) } -// listed returns how many branches of the list written as list at holder in -// doc write a title of each set of words, read once per list. -func (t *titles) listed(doc reftable.DocID, holder []string, list *yaml.Node) map[string]int { - at := reftable.DocumentPointer{Doc: doc, Pointer: pointerOf(holder)} - if counted, ok := t.lists[at]; ok { +// listed returns how many branches of the list written as list at holder +// write a title of each set of words, read once per list. +func (t *titles) listed(holder reftable.DocumentPointer, list *yaml.Node) map[string]int { + if counted, ok := t.lists[holder]; ok { return counted } counted := map[string]int{} - for _, item := range items(list) { - if words := t.words(nodeview.Deref(item)); words != "" { + for i, item := range items(list) { + branch := reftable.DocumentPointer{Doc: holder.Doc, Pointer: holder.Pointer + "/" + jsontext.Pointer(strconv.Itoa(i))} + if words := t.words(branch, nodeview.Deref(item)); words != "" { counted[words]++ } } - t.lists[at] = counted + t.lists[holder] = counted return counted } @@ -141,7 +166,7 @@ func (t *titles) componentNames() map[string]bool { return t.components } -// items returns the items of the sequence node stands for, none where it is no +// items returns the items of the sequence node names, none where it is no // sequence: a oneOf or an allOf written as a mapping, which load reports, has // no branches to read. func items(node *yaml.Node) []*yaml.Node { @@ -152,51 +177,37 @@ func items(node *yaml.Node) []*yaml.Node { return node.Content } -// words returns titleWords of node, read once per node. -func (t *titles) words(node *yaml.Node) string { - if words, ok := t.read[node]; ok { +// words returns titleWords of node, the schema written at documentPointer, read +// once per position. +func (t *titles) words(documentPointer reftable.DocumentPointer, node *yaml.Node) string { + if words, ok := t.read[documentPointer]; ok { return words } - words := titleWords(node) - t.read[node] = words + words := titleWords(node, t.statements.At(documentPointer)) + t.read[documentPointer] = words return words } // titleWords returns the words of the title the schema written as node holds: -// its own, else the one its inline conjuncts write between them, read through -// the flattening docs/compilers/openapi.md#allof-classification gives, since a -// conjunct describes the instance the schema does. A title written beside an -// entry's $ref is that entry's conjunct's; the schema a $ref names lends none. -// It is "" where none writes one with a word, and where they write two. It -// walks an explicit stack of at most statement.MaxFlattenDepth+1 lists. -func titleWords(node *yaml.Node) string { +// its own, else the one the inline conjuncts its statement st lists write +// between them, as the flattening docs/compilers/openapi.md#allof-classification +// gives, since a conjunct describes the instance the schema does. A title +// written beside an entry's $ref is that entry's conjunct's, whether or not the +// $ref names a schema; the schema a $ref names lends none. It is "" where none +// writes one with a word, and where they write two. +func titleWords(node *yaml.Node, st *statement.Statement) string { if words := ownTitle(node); words != "" { return words } - type list struct { - entries []*yaml.Node - next int - } found := "" - stack := []list{{entries: items(nodeview.Child(node, "allOf"))}} - for len(stack) > 0 { - top := &stack[len(stack)-1] - if top.next == len(top.entries) { - stack = stack[:len(stack)-1] - continue - } - entry := nodeview.Deref(top.entries[top.next]) - top.next++ - switch words := ownTitle(entry); { + for _, conjunct := range st.Entries { + switch words := ownTitle(conjunct.Node); { case words == "": case found != "" && words != found: return "" default: found = words } - if nested := items(nodeview.Child(entry, "allOf")); len(nested) > 0 && len(stack) <= statement.MaxFlattenDepth { - stack = append(stack, list{entries: nested}) - } } return found } diff --git a/compilers/openapi/internal/naming/titles_cost_test.go b/compilers/openapi/internal/naming/titles_cost_test.go new file mode 100644 index 000000000..74b2eeeef --- /dev/null +++ b/compilers/openapi/internal/naming/titles_cost_test.go @@ -0,0 +1,151 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package naming_test + +import ( + "encoding/json/jsontext" + "math" + "runtime" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/naming" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" +) + +// nesting is how a document nests schemas depth deep in its one component S: +// the document, the position of each schema, the outermost first, and the +// name each takes. +type nesting func(depth int) (spec string, positions []reftable.DocumentPointer, names []string) + +// nestedProperties nests each schema as the property p of the one around it, +// which its key names. +func nestedProperties(depth int) (string, []reftable.DocumentPointer, []string) { + spec := head + "paths: {}\ncomponents:\n schemas:\n S: " + + strings.Repeat("{type: object, properties: {p: ", depth) + "{type: string}" + strings.Repeat("}}", depth) + "\n" + return spec, nestedPositions(depth, "properties", "p"), slices.Repeat([]string{"p"}, depth) +} + +// nestedBranches nests each schema as the first branch of a oneOf the one +// around it writes, each titled Level and so named, as the other branch of +// its list writes no title. +func nestedBranches(depth int) (string, []reftable.DocumentPointer, []string) { + spec := head + "paths: {}\ncomponents:\n schemas:\n S: {oneOf: [" + + strings.Repeat("{title: Level, oneOf: [", depth-1) + "{title: Level, type: string}" + + strings.Repeat(", {type: integer}]}", depth-1) + ", {type: integer}]}\n" + return spec, nestedPositions(depth, "oneOf", "0"), slices.Repeat([]string{"level"}, depth) +} + +// nestedPositions returns the position of each schema of a nesting depth deep +// in S, each the tokens of step below the one around it. +func nestedPositions(depth int, step ...string) []reftable.DocumentPointer { + positions := make([]reftable.DocumentPointer, depth) + pointer := jsontext.Pointer("/components/schemas/S") + for i := range positions { + for _, token := range step { + pointer = pointer.AppendToken(token) + } + positions[i] = reftable.DocumentPointer{Doc: reftable.Source, Pointer: pointer} + } + return positions +} + +// namingAllocations returns the fewest objects naming every position of shape +// depth deep allocates in three runs, the outermost first as a lowering asks, +// each run by a Namer of its own over a table loaded before the measured +// window. +func namingAllocations(t *testing.T, shape nesting, depth int) float64 { + t.Helper() + spec, positions, want := shape(depth) + fewest := math.Inf(1) + for range 3 { + namer := naming.New(table(t, spec, nil), true) + names := make([]string, len(positions)) + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + for i, position := range positions { + names[i] = namer.At(position) + } + runtime.ReadMemStats(&after) + require.Equal(t, want, names, "the name each position takes") + fewest = min(fewest, float64(after.Mallocs-before.Mallocs)) + } + return fewest +} + +// deepestLookupAllocations returns the fewest objects naming the deepest +// position of shape depth deep allocates in three runs, each by a Namer of its +// own that named every position above it before the measured window. +func deepestLookupAllocations(t *testing.T, shape nesting, depth int) float64 { + t.Helper() + spec, positions, want := shape(depth) + deepest := len(positions) - 1 + fewest := math.Inf(1) + for range 3 { + namer := naming.New(table(t, spec, nil), true) + for _, position := range positions[:deepest] { + namer.At(position) + } + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + name := namer.At(positions[deepest]) + runtime.ReadMemStats(&after) + require.Equal(t, want[deepest], name, "the name the deepest position takes") + fewest = min(fewest, float64(after.Mallocs-before.Mallocs)) + } + return fewest +} + +// TestAt_NamesANestingInAllocationsLinearInItsDepth holds what naming every +// position of a nesting of properties allocates to linear growth in its depth: +// from 2n levels to 4n it grows at most 2.5 times what it grows from n to 2n. +// A lookup that builds again the pointer of each schema above its position, +// token by token, to find the title read there grows with the cube. Not +// parallel: the count is process-wide. +func TestAt_NamesANestingInAllocationsLinearInItsDepth(t *testing.T) { + previous := runtime.GOMAXPROCS(1) + t.Cleanup(func() { runtime.GOMAXPROCS(previous) }) + const n = 16 + one, two, four := namingAllocations(t, nestedProperties, n), namingAllocations(t, nestedProperties, 2*n), + namingAllocations(t, nestedProperties, 4*n) + assert.LessOrEqual(t, four-two, 2.5*(two-one), "allocations at depths %d, %d and %d: %v, %v and %v", + n, 2*n, 4*n, one, two, four) +} + +// TestAt_NamesABranchBeneathTitledBranchesInAllocationsLinearInItsDepth holds +// what naming the deepest of a nesting of titled oneOf branches allocates, +// once those above it are named, to linear growth in its depth, by the rule +// above: the walk names each branch it passes by its position before its +// title. A lookup that builds again the pointer of each list above its +// position, token by token, to count the titles its branches write grows +// with the square. Not parallel: the count is process-wide. +func TestAt_NamesABranchBeneathTitledBranchesInAllocationsLinearInItsDepth(t *testing.T) { + previous := runtime.GOMAXPROCS(1) + t.Cleanup(func() { runtime.GOMAXPROCS(previous) }) + const n = 16 + one, two, four := deepestLookupAllocations(t, nestedBranches, n), deepestLookupAllocations(t, nestedBranches, 2*n), + deepestLookupAllocations(t, nestedBranches, 4*n) + assert.LessOrEqual(t, four-two, 2.5*(two-one), "allocations at depths %d, %d and %d: %v, %v and %v", + n, 2*n, 4*n, one, two, four) +} + +// TestAt_NamesANestingOfTitledBranchesInAllocationsLinearInItsDepth holds what +// naming every branch of a nesting of titled oneOf branches allocates, the +// outermost first, to linear growth in its depth, by the rule above. A walk +// that allocates at each branch it passes on the way down, to name it by its +// position or to ask whether its title spells a position's name, grows with +// the square. Not parallel: the count is process-wide. +func TestAt_NamesANestingOfTitledBranchesInAllocationsLinearInItsDepth(t *testing.T) { + previous := runtime.GOMAXPROCS(1) + t.Cleanup(func() { runtime.GOMAXPROCS(previous) }) + const n = 16 + one, two, four := namingAllocations(t, nestedBranches, n), namingAllocations(t, nestedBranches, 2*n), + namingAllocations(t, nestedBranches, 4*n) + assert.LessOrEqual(t, four-two, 2.5*(two-one), "allocations at depths %d, %d and %d: %v, %v and %v", + n, 2*n, 4*n, one, two, four) +} diff --git a/compilers/openapi/internal/nodeview/lookup.go b/compilers/openapi/internal/nodeview/lookup.go index 9094d01df..a7772c066 100644 --- a/compilers/openapi/internal/nodeview/lookup.go +++ b/compilers/openapi/internal/nodeview/lookup.go @@ -16,7 +16,7 @@ func Pairs(node *yaml.Node) []Pair { return New().MappingPairs(DocumentRoot(node)) } -// Child returns the value the parser reads under key in the mapping node stands +// Child returns the value the parser reads under key in the mapping node names // for, its alias followed, or nil where it reads none: the value MappingPairs // pairs key with, found without building the pairs // (docs/parser-library.md#merge-keys, docs/parser-library.md#duplicate-key). diff --git a/compilers/openapi/internal/nodeview/lookup_test.go b/compilers/openapi/internal/nodeview/lookup_test.go index 39d10a2f5..4e333d80e 100644 --- a/compilers/openapi/internal/nodeview/lookup_test.go +++ b/compilers/openapi/internal/nodeview/lookup_test.go @@ -49,7 +49,7 @@ func TestStrings_ReadsAListOfScalarsByItsText(t *testing.T) { // TestChild_ReadsOnlyWhatAMappingHolds pins the inputs Child answers nil for // and the shapes its one pass serves without a view: a node that is no -// mapping, a key nothing writes, a document node or an alias standing for the +// mapping, a key nothing writes, a document node or an alias naming the // mapping, and a value written as an alias, which it hands back followed. func TestChild_ReadsOnlyWhatAMappingHolds(t *testing.T) { t.Parallel() @@ -63,7 +63,7 @@ func TestChild_ReadsOnlyWhatAMappingHolds(t *testing.T) { "a document node is unwrapped") assert.Nil(t, nodeview.Child(mapping, "absent")) assert.Same(t, value, nodeview.Child(mapping, "k"), "the value's alias is followed") - assert.Same(t, value, nodeview.Child(ynode.Alias(mapping), "k"), "an alias standing for the mapping is followed") + assert.Same(t, value, nodeview.Child(ynode.Alias(mapping), "k"), "an alias for the mapping is followed") } // TestChild_AnswersAsMappingPairs holds Child to the pair MappingPairs gives @@ -124,7 +124,7 @@ func TestPairs_IsAFreshViewsReading(t *testing.T) { // TestWrittenChildren_ReadsTheTextNotThroughIt pins the reading that answers // where a node is written: a mapping's own pairs, each value as written, an // alias left an alias, nothing a `<<` merges in, each key as KeyOf names it at -// its last copy, and nothing for a node that is no mapping, an alias standing +// its last copy, and nothing for a node that is no mapping, an alias // for one included. func TestWrittenChildren_ReadsTheTextNotThroughIt(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/nodeview/nodeview.go b/compilers/openapi/internal/nodeview/nodeview.go index 404dae070..104b762d3 100644 --- a/compilers/openapi/internal/nodeview/nodeview.go +++ b/compilers/openapi/internal/nodeview/nodeview.go @@ -155,7 +155,7 @@ func (e expansion) asSource() []Pair { // the mapping writes itself, then its own, a key written twice at its last // copy. // -// node is dereferenced, so an alias standing in for a whole mapping can be +// node is dereferenced, so an alias taking the place of a whole mapping can be // passed directly; a non-mapping node (including nil) yields no pairs. The // returned slice is the view's own memo — callers must treat it as read-only. func (v *View) MappingPairs(node *yaml.Node) []Pair { @@ -211,7 +211,7 @@ func (v *View) expand(node *yaml.Node, depth int) expansion { // chain still fits under the bound; from deeper than that a fresh read would // truncate, and the memo must not hide the truncation. An incomplete entry was // kept only because it was an entry point, and an entry point is the one read -// it can stand in for. +// it can take the place of. func (v *View) serves(expansionValue expansion, depth int) bool { if !expansionValue.complete { return v.isEntryPoint(depth) @@ -257,9 +257,10 @@ func (v *View) expandContent(node *yaml.Node, depth int) expansion { for i := 0; i+1 < len(node.Content); i += 2 { raw, val := node.Content[i], Deref(node.Content[i+1]) // The library's own predicate, so the view and the unmarshaller cannot - // disagree about which key merges. It is handed the key unresolved, as the - // library hands it: an alias standing in for `<<` is an ordinary key. Every - // `<<` merges, not only the last as in yaml.v3's decoder. + // disagree about which key merges. It is handed the key unresolved, as + // the library hands it: an alias taking the place of `<<` is an + // ordinary key. Every `<<` merges, not only the last as in yaml.v3's + // decoder. if IsMergeKey(raw) { got := v.mergeSource(val, depth+1) merged = append(merged, got.pairs...) @@ -368,7 +369,7 @@ func keepCopy(pairs []Pair, written map[string]int, rule copyRule) []Pair { // IsMergeKey reports whether raw, a mapping key node as written, is a `<<` // merge key: a scalar `<<` the YAML reader tags `!!merge`, which a quoted `<<` -// or an alias standing for one is not (docs/parser-library.md#merge-keys). Every +// or an alias naming one is not (docs/parser-library.md#merge-keys). Every // reader of the parser's reading of a mapping asks this or KeyOf, never a test // of its own. func IsMergeKey(raw *yaml.Node) bool { @@ -429,7 +430,7 @@ func RepeatedKeys(node *yaml.Node) []string { // specrules.CheckFormat reports it. // // The height of a sequence is its tallest element's: the elements are -// alternatives at one level, not links in a chain. +// alternatives at one level, not hops in a chain. func (v *View) mergeSource(val *yaml.Node, depth int) expansion { if val == nil || val.Kind != yaml.SequenceNode { got := v.expand(val, depth) @@ -638,7 +639,7 @@ func (v *View) keyIndex(node *yaml.Node, pairs []Pair) map[string]*yaml.Node { return index } -// Deref follows AliasNode links to the anchored node, bounded against an alias +// Deref follows AliasNode hops to the anchored node, bounded against an alias // chain that loops (the anchor-cycle detector reports those separately). func Deref(node *yaml.Node) *yaml.Node { for i := 0; node != nil && node.Kind == yaml.AliasNode && i <= maxAliasChain; i++ { diff --git a/compilers/openapi/internal/nodeview/nodeview_internal_test.go b/compilers/openapi/internal/nodeview/nodeview_internal_test.go index 29a4bcaa2..607c7347b 100644 --- a/compilers/openapi/internal/nodeview/nodeview_internal_test.go +++ b/compilers/openapi/internal/nodeview/nodeview_internal_test.go @@ -396,8 +396,8 @@ func selfReferentialMergeNode() *yaml.Node { // see a $ref a merge contributes. // // The precedence rules are the resolver's, and they differ by position: an -// explicit key beats any merged one, and among the elements of a merge sequence -// the earlier source wins. +// explicit key takes precedence over any merged one, and among the elements of +// a merge sequence the earlier source wins. func TestMappingPairs_MergeKeySources(t *testing.T) { t.Parallel() tests := []struct { @@ -411,7 +411,7 @@ func TestMappingPairs_MergeKeySources(t *testing.T) { want: map[string]string{"a": "1", "b": "2", "c": "3"}, }, { - name: "an explicit key beats the merged one", + name: "an explicit key takes precedence over the merged one", src: "base: &b {a: 1}\nuse:\n <<: *b\n a: 2\n", want: map[string]string{"a": "2"}, }, @@ -473,7 +473,7 @@ func TestMappingPairs_MergeKeySpellings(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - // m anchors a merge key for the alias case to stand in for. + // m anchors a merge key for the alias case to take the place of. src := fmt.Sprintf("b: &b {k: v}\nm: {&m <<: *b}\nuse:\n %s : *b\n", tc.key) use := New().ChildByToken(YAMLDoc(t, src), "use") require.NotNil(t, use, "the fixture declares a `use` mapping") @@ -602,8 +602,8 @@ func TestDocumentPath_AnEmptyTokenNamesTheEmptyKey(t *testing.T) { // TestDocumentPath_SegmentCapStopsTheWalk pins the cap at its edge. A mapping // whose only key is "a" and whose value is itself cannot be built from parsed -// YAML, but an alias can stand in: the walk follows "a" as long as tokens last, -// so only the cap can end it. +// YAML, but an alias can take its place: the walk follows "a" as long as tokens +// last, so only the cap can end it. func TestDocumentPath_SegmentCapStopsTheWalk(t *testing.T) { t.Parallel() root := ynode.Map(ynode.Scalar("a"), nil) @@ -652,7 +652,7 @@ func TestChildByToken_IndexAgreesWithTheScanItReplaces(t *testing.T) { n: wideMap(ynode.Merge(), ynode.Alias(base), ynode.Scalar("c"), ynode.Scalar("3")), }, { - name: "explicit beats merged", + name: "explicit takes precedence over merged", n: wideMap(ynode.Merge(), ynode.Alias(base), ynode.Scalar("a"), ynode.Scalar("9")), }, {name: "an aliased value", n: wideMap(ynode.Scalar("a"), ynode.Alias(ynode.Scalar("1")))}, @@ -787,8 +787,8 @@ func TestDocumentPath_ReachesTheIndexOnAWideMapping(t *testing.T) { func TestNodeView_SharedViewAnswersAsAFreshOne(t *testing.T) { t.Parallel() - // head -> ... -> leaf, two links past the bound: a read from head truncates. - // inner sits ten links down, where a read from it fits inside the bound. + // head -> ... -> leaf, two hops past the bound: a read from head truncates. + // inner sits ten hops down, where a read from it fits inside the bound. head := ynode.MergeChain(MergeDepthLimit + 2) inner := head for range 10 { @@ -827,7 +827,7 @@ func TestNodeView_SharedViewAnswersAsAFreshOne(t *testing.T) { _ = view.MappingPairs(inner) retained := view.cached.Spent() - // Two links above inner: inner is reached at depth 2, and its own chain + // Two hops above inner: inner is reached at depth 2, and its own chain // fits under the bound from there, so the memo answers the read. assert.Equal(t, map[string]string{"leaf": "v"}, pairMap(view.MappingPairs(linksAbove(inner, 2)))) assert.False(t, view.Exhausted()) @@ -835,12 +835,12 @@ func TestNodeView_SharedViewAnswersAsAFreshOne(t *testing.T) { "only the two new mappings were memoized; nothing beneath inner was recomputed") }) - // inner's chain is MergeDepthLimit-8 links, so from 8 links above it the whole - // chain is exactly the bound and fits; from 9 it is one past and truncates. - // Both readings must agree with a fresh view's, and the fitting one must be - // the memo answering: refusing it recomputes the same pairs, so only the memo - // count can see a bound drawn one short, where the answer sees one drawn one - // long. Together they fix the bound's meaning. + // inner's chain is MergeDepthLimit-8 hops, so from 8 hops above it the + // whole chain is exactly the bound and fits; from 9 it is one past and + // truncates. Both readings must agree with a fresh view's, and the fitting + // one must be the memo answering: refusing it recomputes the same pairs, so + // only the memo count can see a bound drawn one short, where the answer + // sees one drawn one long. Together they fix the bound's meaning. t.Run("the budget is exact at the bound", func(t *testing.T) { t.Parallel() for _, tc := range []struct { @@ -878,7 +878,7 @@ func linksAbove(node *yaml.Node, links int) *yaml.Node { } // pairSource is a document whose components/responses section holds the one -// mapping pair written as pair. Its anchors stand behind the aliases the pairs +// mapping pair written as pair. Its anchors sit behind the aliases the pairs // use, each named differently from what it anchors so that an alias left // unfollowed reads differently from one followed. func pairSource(pair string) string { @@ -904,13 +904,13 @@ func pairRead(t *testing.T, pair string) ([]string, *yaml.Node) { return slices.Collect(parsed.Components.Responses.Keys()), section.Content[0] } -// TestKeyOf_KeysAPairAsTheParserDoes holds the key KeyOf gives a raw pair key to -// the parser's: each pair is written into a section the parser reads, and the -// keys it gives that section's entries are the one KeyOf names, or none where -// KeyOf says the pair names none. A `<<` merge key names none, here a merge -// of nothing; a scalar tagged !!merge with any other value, a quoted `<<` and -// an alias standing in for `<<` are ordinary keys; an alias key names the -// scalar it stands for. The key and own columns pin today's parser. +// TestKeyOf_KeysAPairAsTheParserDoes holds the key KeyOf gives a raw pair key +// to the parser's: each pair is written into a section the parser reads, and +// the keys it gives that section's entries are the one KeyOf names, or none +// where KeyOf says the pair names none. A `<<` merge key names none, here a +// merge of nothing; a scalar tagged !!merge with any other value, a quoted `<<` +// and an alias taking the place of `<<` are ordinary keys; an alias key names +// the scalar it names. The key and own columns pin today's parser. func TestKeyOf_KeysAPairAsTheParserDoes(t *testing.T) { t.Parallel() tests := []struct { @@ -923,7 +923,7 @@ func TestKeyOf_KeysAPairAsTheParserDoes(t *testing.T) { {"a quoted <<", "'<<': {description: x}", "<<", true}, {"a key tagged !!merge that is not <<", "!!merge tagged: {description: x}", "tagged", true}, {"an alias key", "*scalar : {description: x}", "named", true}, - {"an alias standing in for <<", "*merge : {description: x}", "<<", true}, + {"an alias taking the place of <<", "*merge : {description: x}", "<<", true}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -946,7 +946,7 @@ func TestKeyOf_KeysAPairAsTheParserDoes(t *testing.T) { // TestKeyOf_ANameForAKeyThatIsNoScalarIsNone holds KeyOf to naming no key for a // pair whose key is no scalar, aliased or not, though the parser keys it with // the empty string (docs/parser-library.md#non-scalar-key): the entry is left -// out of the view, which is what keeps one pointer from standing for every such +// out of the view, which is what keeps one pointer from naming every such // key. No node at all names no key either. func TestKeyOf_ANameForAKeyThatIsNoScalarIsNone(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/nodeview/nodeview_test.go b/compilers/openapi/internal/nodeview/nodeview_test.go index 372abf854..538b13b07 100644 --- a/compilers/openapi/internal/nodeview/nodeview_test.go +++ b/compilers/openapi/internal/nodeview/nodeview_test.go @@ -19,7 +19,7 @@ func TestIsMergeKey_IsTheLibrarysPredicate(t *testing.T) { t.Parallel() assert.True(t, nodeview.IsMergeKey(ynode.Merge())) assert.False(t, nodeview.IsMergeKey(ynode.Scalar("<<")), "untagged, it is an ordinary key") - assert.False(t, nodeview.IsMergeKey(ynode.Alias(ynode.Merge())), "an alias standing for it is an ordinary key") + assert.False(t, nodeview.IsMergeKey(ynode.Alias(ynode.Merge())), "an alias for it is an ordinary key") assert.False(t, nodeview.IsMergeKey(nil)) } diff --git a/compilers/openapi/internal/nodeview/unread_test.go b/compilers/openapi/internal/nodeview/unread_test.go index 706831d32..835a594dd 100644 --- a/compilers/openapi/internal/nodeview/unread_test.go +++ b/compilers/openapi/internal/nodeview/unread_test.go @@ -192,7 +192,7 @@ func TestKeyOf_AKeyThatIsNoScalarNamesNoKey(t *testing.T) { names = append(names, pair.Key) } assert.Equal(t, []string{"k", "z"}, names, "the entries with such keys are left out") - assert.Nil(t, nodeview.Child(root, ""), "and no entry stands for the key \"\"") + assert.Nil(t, nodeview.Child(root, ""), "and no entry for the key \"\"") assert.Empty(t, nodeview.RepeatedKeys(root), "two such keys are not one key written twice") } diff --git a/compilers/openapi/internal/nodeview/walk.go b/compilers/openapi/internal/nodeview/walk.go index c1040811f..44c3a70bb 100644 --- a/compilers/openapi/internal/nodeview/walk.go +++ b/compilers/openapi/internal/nodeview/walk.go @@ -39,10 +39,10 @@ const ( // Walk is a bounded, iterative walk over a raw YAML tree as written, through // Content and in document order, visiting each node before its children. A // reader that visits every node written runs one rather than keeping a stack -// and a bound of its own, so a cut short walk is reported rather than silent -// wherever one runs. A walk addressing positions as the parser reads them, -// where a merged pair's value is no child of the mapping merging it, keeps a -// frame per position instead. +// and a bound of its own, so a cut short walk is reported +// wherever one runs. A walk addressing positions as the parser reads +// them, where a merged pair's value is no child of the mapping merging it, +// keeps a frame per position instead. type Walk struct { // Nodes bounds how many nodes the walk visits. A walk that would visit // more stops there and reports itself Cut; a bound below one visits none. @@ -54,7 +54,7 @@ type Walk struct { // depth zero: a node deeper is not visited, and the walk is Cut. Nodes // bounds the depth either way. Depth int - // Aliases says what an alias stands for. + // Aliases says what an alias names. Aliases Aliases // Visit is handed each node and its depth, and says whether to descend. // Unset, the walk descends everywhere, which counts a tree's nodes. @@ -140,7 +140,7 @@ func (w Walk) step(node *yaml.Node, depth int) Step { } // node returns what the walk visits for node: node itself, or the node an alias -// names where aliases stand for their targets. +// names where aliases name their targets. func (w Walk) node(node *yaml.Node) *yaml.Node { if w.Aliases != AliasTarget { return node diff --git a/compilers/openapi/internal/nodeview/walk_test.go b/compilers/openapi/internal/nodeview/walk_test.go index 9754d38ce..057ee2fb7 100644 --- a/compilers/openapi/internal/nodeview/walk_test.go +++ b/compilers/openapi/internal/nodeview/walk_test.go @@ -84,11 +84,11 @@ func TestWalk_PruneAndStop(t *testing.T) { assert.Equal(t, nodeview.Outcome{Visited: 1, Stopped: true}, out) } -// TestWalk_BoundsAreReportedNotSilent pins the two bounds: a tree of exactly +// TestWalk_BoundsAreReported pins the two bounds: a tree of exactly // Nodes nodes is walked whole, one node more is Cut there, and a bound below // one visits none; a node past Depth is not visited, its siblings are, and the // walk says it was Cut. -func TestWalk_BoundsAreReportedNotSilent(t *testing.T) { +func TestWalk_BoundsAreReported(t *testing.T) { t.Parallel() root := ynode.Seq(ynode.Seq(ynode.Scalar("deep")), ynode.Scalar("shallow")) @@ -103,7 +103,7 @@ func TestWalk_BoundsAreReportedNotSilent(t *testing.T) { } // TestWalk_AnAliasIsALeafOrItsTarget pins the alias rule: as a leaf, an alias -// is visited as itself and what it names only where that is written; standing +// is visited as itself and what it names only where that is written; naming // for its target, the target is visited in its place each time, and an alias // naming nothing is visited as itself. func TestWalk_AnAliasIsALeafOrItsTarget(t *testing.T) { diff --git a/compilers/openapi/internal/openapitest/result.go b/compilers/openapi/internal/openapitest/result.go index dcbbb24e7..f052b1c81 100644 --- a/compilers/openapi/internal/openapitest/result.go +++ b/compilers/openapi/internal/openapitest/result.go @@ -173,11 +173,11 @@ func PointersOf(diags []ir.Diagnostic, code string) []jsontext.Pointer { return out } -// PreservationClaims returns the messages announcing that something was kept +// MessagesSayingKept returns the messages announcing that something was kept // under Unmodeled. The unpreservable report is excluded by code rather than by // wording: it says a construct "could not be kept verbatim under Unmodeled", // which contains the phrase and is the opposite of a claim. -func PreservationClaims(diags []ir.Diagnostic) []string { +func MessagesSayingKept(diags []ir.Diagnostic) []string { var out []string for _, diagnostic := range diags { if strings.Contains(diagnostic.Message, "under Unmodeled") && diagnostic.Code != diag.UnpreservableConstruct { diff --git a/compilers/openapi/internal/openapitest/result_test.go b/compilers/openapi/internal/openapitest/result_test.go index 7b00b6044..b51ddb953 100644 --- a/compilers/openapi/internal/openapitest/result_test.go +++ b/compilers/openapi/internal/openapitest/result_test.go @@ -116,7 +116,7 @@ func TestIndexBy_KeysEveryItem(t *testing.T) { } // TestBodyTarget_RequiresExactlyOneMediaType pins that a second media type is a -// failure rather than a silent pick of the first. +// failure rather than an unreported pick of the first. // // The recorder can drive this case and not the two that would leave the helper // nothing to index, a nil payload or a payload with no media type: its FailNow @@ -219,10 +219,10 @@ func TestPointersOf_SortsThePointersOfOneCode(t *testing.T) { assert.Empty(t, openapitest.PointersOf(diags, "c")) } -// TestPreservationClaims_ExcludesTheUnpreservableReport pins both halves: a +// TestMessagesSayingKept_ExcludesTheUnpreservableReport pins both halves: a // message claiming a keep is listed whatever its code, and the report that a // construct could not be kept is not, though its wording holds the phrase. -func TestPreservationClaims_ExcludesTheUnpreservableReport(t *testing.T) { +func TestMessagesSayingKept_ExcludesTheUnpreservableReport(t *testing.T) { t.Parallel() diags := []ir.Diagnostic{ {Code: "a", Message: "x kept under Unmodeled"}, @@ -230,7 +230,7 @@ func TestPreservationClaims_ExcludesTheUnpreservableReport(t *testing.T) { {Code: "b", Message: "z reported"}, {Code: "c", Message: "w kept under Unmodeled"}, } - assert.Equal(t, []string{"x kept under Unmodeled", "w kept under Unmodeled"}, openapitest.PreservationClaims(diags)) + assert.Equal(t, []string{"x kept under Unmodeled", "w kept under Unmodeled"}, openapitest.MessagesSayingKept(diags)) } // TestDiagMessageAt_ReturnsTheSingleMatchingMessage pins that the message is diff --git a/compilers/openapi/internal/openapitest/rows.go b/compilers/openapi/internal/openapitest/rows.go new file mode 100644 index 000000000..1499dcb6c --- /dev/null +++ b/compilers/openapi/internal/openapitest/rows.go @@ -0,0 +1,159 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package openapitest + +import ( + "cmp" + "fmt" + "maps" + "slices" + "strings" + + gocmp "github.com/google/go-cmp/cmp" +) + +// Readings is what each spelling of each row read as, by whether the +// components were declared in reverse, row, spelling and position. +type Readings[R any] map[bool]map[string]map[string]map[string]R + +// Subtests is the subset of *testing.T RequireRowsAlike needs: TB and +// subtests, whose own type is B. +type Subtests[B TB] interface { + TB + Run(name string, body func(B)) bool +} + +const ( + // maxDetailedRows is how many failing rows of one call print a difference. + maxDetailedRows = 3 + // maxDetailedSpellings is how many failing spellings of a row print one. + maxDetailedSpellings = 2 + // maxCellsNamed is how many differing cells of a spelling are named. + maxCellsNamed = 4 +) + +// RequireRowsAlike holds, in a subtest of its own for each of rows, every +// spelling of the row, at each position and in each order of the components, +// to the reading of the one named first in the first order. An empty first +// holds each spelling to its own first-order reading. A failure prints a +// bounded report: the spellings that differ and where, the first few +// differences, and a count of the rest. A row alone runs by name. +func RequireRowsAlike[B TB, R any](t Subtests[B], readings Readings[R], rows []Row, first string) { + t.Helper() + detailed := 0 + for _, row := range rows { + t.Run(row.Name, func(sub B) { + sub.Helper() + if first != "" && len(readings[false][row.Name][first]) == 0 { + sub.Errorf("%s has no reading of its spelling %s to hold the others to", row.Name, first) + return + } + report := rowDifferences(readings, row, first, detailed < maxDetailedRows) + if report == "" { + return + } + detailed++ + sub.Errorf("%s", report) + }) + } +} + +// rowDifferences reports how the spellings of row read unlike its first. Where +// detail, it names the first few and where each differs, with the first +// difference of each, and lists the rest; otherwise it names them in one line. +// It is empty where they read alike. +func rowDifferences[R any](readings Readings[R], row Row, first string, detail bool) string { + var report strings.Builder + var unlike []string + for _, spelling := range slices.Sorted(maps.Keys(row.Spellings)) { + held := cmp.Or(first, spelling) + cells := differingCells(readings, row, held, spelling) + if len(cells) == 0 { + continue + } + unlike = append(unlike, spelling) + if detail && len(unlike) <= maxDetailedSpellings { + fmt.Fprintf(&report, "%s: %s differs from %s in %s\nfirst difference (-%s +%s):\n%s\n", + row.Name, spelling, held, describeCells(cells), held, spelling, strings.TrimRight(cells[0].diff, "\n")) + } + } + if len(unlike) == 0 { + return "" + } + shown := shownSpellings(detail) + if rest := unlike[min(len(unlike), shown):]; len(rest) > 0 { + more := "" + if shown > 0 { + more = " more" + } + fmt.Fprintf(&report, "%s: %d%s spellings read unlike %s: %s\n", + row.Name, len(rest), more, cmp.Or(first, "themselves"), strings.Join(rest, ", ")) + } + return strings.TrimRight(report.String(), "\n") +} + +// shownSpellings is how many differing spellings of a row print a difference. +func shownSpellings(detail bool) int { + if detail { + return maxDetailedSpellings + } + return 0 +} + +// cell is one reading that differs: where it was read and how it differs. +type cell struct { + position string + reversed bool + diff string +} + +// differingCells are the cells of spelling that read unlike first's, in each +// position first has and each order of the components the readings hold. +func differingCells[R any](readings Readings[R], row Row, first, spelling string) []cell { + var out []cell + for _, reversed := range []bool{false, true} { + for _, position := range slices.Sorted(maps.Keys(readings[false][row.Name][first])) { + want := readings[false][row.Name][first][position] + if diff := gocmp.Diff(want, readings[reversed][row.Name][spelling][position]); diff != "" { + out = append(out, cell{position: position, reversed: reversed, diff: diff}) + } + } + } + return out +} + +// describeCells names the first few of cells and counts the rest. +func describeCells(cells []cell) string { + named := make([]string, 0, maxCellsNamed) + for _, c := range cells[:min(len(cells), maxCellsNamed)] { + named = append(named, fmt.Sprintf("the %s, components reversed %t", c.position, c.reversed)) + } + text := fmt.Sprintf("%d cells: %s", len(cells), strings.Join(named, "; ")) + if more := len(cells) - len(named); more > 0 { + text += fmt.Sprintf("; and %d more", more) + } + return text +} + +// RowNamed returns the row of rows called name, and fails tb where there is +// none. +func RowNamed(tb TB, rows []Row, name string) Row { + tb.Helper() + at := slices.IndexFunc(rows, func(row Row) bool { return row.Name == name }) + if at < 0 { + tb.Fatalf("no row %q among %d", name, len(rows)) + return Row{} + } + return rows[at] +} + +// Excerpt is the first lines lines of text, with a count of the rest, so a +// difference of two documents prints as much of itself as a reader takes in. +func Excerpt(text string, lines int) string { + all := strings.Split(strings.TrimRight(text, "\n"), "\n") + if len(all) <= lines { + return strings.Join(all, "\n") + } + return fmt.Sprintf("%s\n... and %d more lines", strings.Join(all[:lines], "\n"), len(all)-lines) +} diff --git a/compilers/openapi/internal/openapitest/rows_test.go b/compilers/openapi/internal/openapitest/rows_test.go new file mode 100644 index 000000000..963b33a49 --- /dev/null +++ b/compilers/openapi/internal/openapitest/rows_test.go @@ -0,0 +1,216 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package openapitest_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" +) + +// subRecorder is a recorder that runs its subtests at once and keeps each by +// name, so a test reads what each row said. +type subRecorder struct { + recorder + children map[string]*subRecorder + order []string +} + +func (r *subRecorder) Run(name string, body func(*subRecorder)) bool { + if r.children == nil { + r.children = map[string]*subRecorder{} + } + child := &subRecorder{} + r.children[name] = child + r.order = append(r.order, name) + body(child) + return !child.failed() +} + +// reading is a placeholder for what a position reads as. +type reading struct { + Kind string + Notes map[string]int +} + +// readingsOf holds one reading for each of spellings in both orders of the +// components, at the component and the property, all alike unless a test +// changes one. +func readingsOf(row string, spellings ...string) openapitest.Readings[reading] { + out := openapitest.Readings[reading]{} + for _, reversed := range []bool{false, true} { + out[reversed] = map[string]map[string]map[string]reading{row: {}} + for _, spelling := range spellings { + out[reversed][row][spelling] = map[string]reading{ + "component": {Kind: "union"}, + "property": {Kind: "union"}, + } + } + } + return out +} + +// TestRequireRowsAlike_PassesRowsThatReadAlike holds rows whose spellings read +// alike to draw nothing, each row in a subtest of its own named for it. +func TestRequireRowsAlike_PassesRowsThatReadAlike(t *testing.T) { + t.Parallel() + rec := &subRecorder{} + rows := []openapitest.Row{{Name: "One", Spellings: map[string]string{"Flat": "{}", "Entry": "{}"}}} + openapitest.RequireRowsAlike(rec, readingsOf("One", "Flat", "Entry"), rows, "Flat") + assert.False(t, rec.failed()) + assert.Equal(t, []string{"One"}, rec.order) + assert.False(t, rec.children["One"].failed()) +} + +// TestRequireRowsAlike_ReportsAMisreadSpellingBounded holds a spelling that reads +// unlike the first, in every position and order, to a report naming where, with +// the first difference only and a count of the rest, and the row beside it to +// pass. +func TestRequireRowsAlike_ReportsAMisreadSpellingBounded(t *testing.T) { + t.Parallel() + readings := readingsOf("Bad", "Flat", "Entry") + long := map[string]int{} + for i := range 200 { + long[fmt.Sprintf("note %d", i)] = i + } + for _, reversed := range []bool{false, true} { + for _, position := range []string{"component", "property"} { + readings[reversed]["Bad"]["Entry"][position] = reading{Kind: "scalar", Notes: long} + } + } + for row, spellings := range map[string][]string{"Good": {"Flat", "Entry"}} { + for reversed, byRow := range readingsOf(row, spellings...) { + readings[reversed][row] = byRow[row] + } + } + rows := []openapitest.Row{ + {Name: "Bad", Spellings: map[string]string{"Flat": "{}", "Entry": "{}"}}, + {Name: "Good", Spellings: map[string]string{"Flat": "{}", "Entry": "{}"}}, + } + rec := &subRecorder{} + openapitest.RequireRowsAlike(rec, readings, rows, "Flat") + assert.True(t, rec.children["Bad"].failed()) + assert.False(t, rec.children["Good"].failed(), "a row that reads alike passes beside one that does not") + require.Len(t, rec.children["Bad"].errorf, 1) + report := rec.children["Bad"].errorf[0] + assert.Contains(t, report, "Bad: Entry differs from Flat in 4 cells") + assert.Contains(t, report, "the component, components reversed false") + assert.Contains(t, report, "first difference (-Flat +Entry)") + assert.NotContains(t, report, "spellings read unlike") + assert.Less(t, len(strings.Split(report, "\n")), 40, "a report is a screen, however much differs") +} + +// TestRequireRowsAlike_NamesFewCellsAndCountsTheRest holds a report of many +// differing cells to name the first few and count the rest. +func TestRequireRowsAlike_NamesFewCellsAndCountsTheRest(t *testing.T) { + t.Parallel() + positions := []string{"a", "b", "c", "d", "e", "f"} + readings := openapitest.Readings[reading]{} + for _, reversed := range []bool{false, true} { + readings[reversed] = map[string]map[string]map[string]reading{"Row": {"Flat": {}, "Entry": {}}} + for _, position := range positions { + readings[reversed]["Row"]["Flat"][position] = reading{Kind: "union"} + readings[reversed]["Row"]["Entry"][position] = reading{Kind: "scalar"} + } + } + rows := []openapitest.Row{{Name: "Row", Spellings: map[string]string{"Flat": "{}", "Entry": "{}"}}} + rec := &subRecorder{} + openapitest.RequireRowsAlike(rec, readings, rows, "Flat") + report := rec.children["Row"].errorf[0] + assert.Contains(t, report, "12 cells") + assert.Contains(t, report, "and 8 more") +} + +// TestRequireRowsAlike_PrintsADifferenceForFewRowsAndSpellings holds the detail +// of a failure to the first few rows and the first few spellings of a row, every +// other one named in a line of its row. +func TestRequireRowsAlike_PrintsADifferenceForFewRowsAndSpellings(t *testing.T) { + t.Parallel() + const rowCount, spellingCount = 6, 5 + readings := openapitest.Readings[reading]{false: {}, true: {}} + rows := make([]openapitest.Row, 0, rowCount) + for i := range rowCount { + name := fmt.Sprintf("Row%d", i) + row := openapitest.Row{Name: name, Spellings: map[string]string{"Flat": "{}"}} + for _, reversed := range []bool{false, true} { + readings[reversed][name] = map[string]map[string]reading{"Flat": {"component": {Kind: "union"}}} + } + for j := range spellingCount { + spelling := fmt.Sprintf("S%d", j) + row.Spellings[spelling] = "{}" + for _, reversed := range []bool{false, true} { + readings[reversed][name][spelling] = map[string]reading{"component": {Kind: "scalar"}} + } + } + rows = append(rows, row) + } + rec := &subRecorder{} + openapitest.RequireRowsAlike(rec, readings, rows, "Flat") + detailed := 0 + for _, name := range rec.order { + report := rec.children[name].errorf[0] + if strings.Contains(report, "first difference") { + detailed++ + assert.Equal(t, 2, strings.Count(report, "first difference"), "%s: two spellings are detailed", name) + assert.Contains(t, report, "3 more spellings read unlike Flat: S2, S3, S4", name) + continue + } + assert.Equal(t, name+": 5 spellings read unlike Flat: S0, S1, S2, S3, S4", report) + } + assert.Equal(t, 3, detailed, "three rows print a difference") +} + +// TestRequireRowsAlike_HoldsEachSpellingToItselfWhereNoneIsFirst holds an empty +// first to compare each spelling's first-order reading with its reading in the +// other order. +func TestRequireRowsAlike_HoldsEachSpellingToItselfWhereNoneIsFirst(t *testing.T) { + t.Parallel() + readings := readingsOf("Row", "Flat", "Entry") + readings[true]["Row"]["Entry"]["component"] = reading{Kind: "scalar"} + rows := []openapitest.Row{{Name: "Row", Spellings: map[string]string{"Flat": "{}", "Entry": "{}"}}} + rec := &subRecorder{} + openapitest.RequireRowsAlike(rec, readings, rows, "") + require.True(t, rec.children["Row"].failed()) + report := rec.children["Row"].errorf[0] + assert.Contains(t, report, "Row: Entry differs from Entry in 1 cells: the component, components reversed true") + assert.NotContains(t, report, "Flat differs") +} + +// TestRequireRowsAlike_FailsARowWithNoReadingOfItsFirst holds a row the readings +// hold none of its first spelling for to fail, not to pass with nothing to +// compare. +func TestRequireRowsAlike_FailsARowWithNoReadingOfItsFirst(t *testing.T) { + t.Parallel() + rows := []openapitest.Row{{Name: "Row", Spellings: map[string]string{"Flat": "{}"}}} + rec := &subRecorder{} + openapitest.RequireRowsAlike(rec, readingsOf("Other", "Flat"), rows, "Flat") + require.True(t, rec.children["Row"].failed()) + assert.Contains(t, rec.children["Row"].errorf[0], "no reading of its spelling Flat") +} + +// TestRowNamed_FindsARowOrFails holds a row to be found by its name and a name +// no row has to fail the test asking. +func TestRowNamed_FindsARowOrFails(t *testing.T) { + t.Parallel() + rows := []openapitest.Row{{Name: "A"}, {Name: "B", Spellings: map[string]string{"Flat": "{}"}}} + rec := &recorder{} + assert.Equal(t, "B", openapitest.RowNamed(rec, rows, "B").Name) + assert.False(t, rec.failed()) + assert.Empty(t, openapitest.RowNamed(rec, rows, "C").Name) + require.Len(t, rec.fatalf, 1) + assert.Contains(t, rec.fatalf[0], `no row "C" among 2`) +} + +// TestExcerpt_CutsATextAfterItsFirstLines holds a short text to come back whole +// and a long one to come back cut, with a count of the lines left out. +func TestExcerpt_CutsATextAfterItsFirstLines(t *testing.T) { + t.Parallel() + assert.Equal(t, "a\nb", openapitest.Excerpt("a\nb\n", 2)) + assert.Equal(t, "a\nb\n... and 2 more lines", openapitest.Excerpt("a\nb\nc\nd", 2)) +} diff --git a/compilers/openapi/internal/openapitest/spellings.go b/compilers/openapi/internal/openapitest/spellings.go new file mode 100644 index 000000000..9d9263389 --- /dev/null +++ b/compilers/openapi/internal/openapitest/spellings.go @@ -0,0 +1,313 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package openapitest + +import ( + "maps" + "slices" + "strings" + + yaml "go.yaml.in/yaml/v3" +) + +// Row is one schema written in several spellings, each a component's text. +type Row struct { + Name string + Spellings map[string]string +} + +// writing is what a placement writes: the keywords of the rest, and parts, +// each a group of keywords a placement may keep together or put apart. +type writing struct { + rest string + parts []string + // hasRest says a rest is written in every placement, an empty one among + // them. + hasRest bool + // reverse writes every list of parts and of entries in the other order, + // the rest's entry last. + reverse bool +} + +// placement is one way to write a writing: where its rest and its parts +// sit relative to an allOf. A placement is added here and every family +// built on Spellings reads it. +type placement struct { + name string + // needsRest and needsPair say the placement writes nothing new without a + // rest, or without two parts to put apart. + needsRest, needsPair bool + // partOnEntry says the parts sit on an entry of an allOf, not in the + // mapping that holds the allOf. + partOnEntry bool + // at is where the parts written together sit in a schema with a rest, + // as a pointer from the schema, empty where beside the rest or apart. + at string + write func(w writing) string +} + +// placements are the spellings in the order each name is claimed: where +// several write one schema, the first of them names it. Families that spell +// something else keep their own, for that reason: a principal beside a group +// (inline_principal_position_test.go), the body kinds of a typed value set +// (union_typed_value_set_test.go), the key a discriminator's mapping is kept +// under (variant_dead_route_test.go), and an entry held to its own pointer +// (ref_conjunction_entry_test.go, entry_value_set_position_test.go, +// union_alone_entry_test.go). +var placements = []placement{ + {name: "Flat", write: func(w writing) string { return mapping(w.rest, w.unit()) }}, + {name: "Entry", partOnEntry: true, at: "/allOf/1", write: func(w writing) string { return w.allOf(w.restThen(braced(w.unit()))...) }}, + {name: "UnionEntry", partOnEntry: true, at: "/allOf/0", write: func(w writing) string { return mapping(w.rest, "allOf: ["+braced(w.unit())+"]") }}, + {name: "OneEntry", partOnEntry: true, at: "/allOf/0", write: func(w writing) string { return w.allOf(mapping(w.rest, w.unit())) }}, + {name: "Beside", needsRest: true, write: func(w writing) string { return mapping("allOf: ["+braced(w.rest)+"]", w.unit()) }}, + {name: "EntryRev", needsRest: true, partOnEntry: true, at: "/allOf/0", write: func(w writing) string { return w.allOf(braced(w.unit()), braced(w.rest)) }}, + {name: "Deep", partOnEntry: true, at: "/allOf/1/allOf/0", write: func(w writing) string { return w.allOf(w.restThen("{allOf: [" + braced(w.unit()) + "]}")...) }}, + {name: "OneEntryUnionEntry", partOnEntry: true, at: "/allOf/0/allOf/0", write: func(w writing) string { + return w.allOf(mapping(w.rest, "allOf: ["+braced(w.unit())+"]")) + }}, + {name: "Split", needsPair: true, partOnEntry: true, write: func(w writing) string { return w.allOf(w.restThen(w.entries()...)...) }}, + {name: "SplitRev", needsPair: true, partOnEntry: true, write: func(w writing) string { + r := w.reversed() + return r.allOf(w.restThen(r.entries()...)...) + }}, + {name: "SplitRevBefore", needsPair: true, partOnEntry: true, write: func(w writing) string { + return w.allOf(append(w.reversed().entries(), w.restThen()...)...) + }}, + {name: "DeepTwice", partOnEntry: true, at: "/allOf/1/allOf/0/allOf/0", write: func(w writing) string { + return w.allOf(w.restThen("{allOf: [{allOf: [" + braced(w.unit()) + "]}]}")...) + }}, + {name: "SplitDeep", needsPair: true, partOnEntry: true, write: func(w writing) string { + return w.allOf(w.restThen(w.allOf(w.entries()...))...) + }}, + {name: "EntryPartsRev", needsPair: true, partOnEntry: true, write: func(w writing) string { + return w.allOf(w.restThen(braced(w.reversed().unit()))...) + }}, + {name: "FlatPartsRev", needsPair: true, write: func(w writing) string { return mapping(w.rest, w.reversed().unit()) }}, + {name: "Mixed", needsPair: true, write: func(w writing) string { return w.besideOne(w.parts[0], w.parts[1:]) }}, + {name: "MixedRev", needsPair: true, write: func(w writing) string { + return w.besideOne(w.parts[len(w.parts)-1], w.parts[:len(w.parts)-1]) + }}, +} + +// Spellings writes rest and parts in every placement, by name: flat, on entries +// of an allOf in either order, beside an allOf holding the other, one allOf +// deeper, and, where there are two parts or more, each part apart. rest is the +// keywords of one schema, none for parts alone and "{}" for a rest that says +// nothing; one written in braces is taken as written. A text a placement shares +// with an earlier one is written under the first name alone. +func Spellings(rest string, parts ...string) map[string]string { + return dedupe(rest, parts, false) +} + +// Reversed is Spellings with every list of parts and of entries in the other +// order, the rest's entry last, which a family reads in both orders to hold +// that the order of what is written decides nothing. +func Reversed(rest string, parts ...string) map[string]string { + return dedupe(rest, parts, true) +} + +// dedupe writes rest and parts in each placement, a text once. +func dedupe(rest string, parts []string, reverse bool) map[string]string { + out := map[string]string{} + seen := map[string]bool{} + for _, p := range placements { + text, ok := p.written(rest, parts, reverse) + if !ok || seen[text] { + continue + } + seen[text] = true + out[p.name] = text + } + return out +} + +// Placements is Spellings with a text two placements share written under +// each of their names, so what one writes with parts and what it writes with +// none can be held side by side by name. +func Placements(rest string, parts ...string) map[string]string { + out := map[string]string{} + for _, p := range placements { + if text, ok := p.written(rest, parts, false); ok { + out[p.name] = text + } + } + return out +} + +// written is the placement's text for rest and parts, and false where it +// writes nothing new for them. +func (p placement) written(rest string, parts []string, reverse bool) (string, bool) { + w := writing{rest: unbraced(rest), parts: slices.Clone(parts), hasRest: rest != "", reverse: reverse} + if (p.needsRest && !w.hasRest) || (p.needsPair && len(w.parts) < 2) { + return "", false + } + return p.write(w), true +} + +// PartsOnEntry reports whether the placement named writes the parts on an +// entry of an allOf rather than beside it, so where a keyword is kept or +// reported is on that entry. Mixed and MixedRev write one part each way, and +// a name no placement has is none. +func PartsOnEntry(name string) bool { + at := slices.IndexFunc(placements, func(p placement) bool { return p.name == name }) + return at >= 0 && placements[at].partOnEntry +} + +// PartsAt is where the parts of the placement named sit, written together, +// as a pointer from the schema, in a schema with a rest or without one: empty +// where they sit in the schema itself, and for a placement that puts them +// apart or that no placement has. +func PartsAt(name string, hasRest bool) string { + at := slices.IndexFunc(placements, func(p placement) bool { return p.name == name }) + if at < 0 { + return "" + } + pointer := placements[at].at + if !hasRest { + return strings.Replace(pointer, "/allOf/1", "/allOf/0", 1) + } + return pointer +} + +// Except is spellings without the placements named, which the family calling +// it does not hold to the first, and for the reason it states: a placement +// is excused where it is, so the next placement added reaches the family +// unless the family says otherwise, and the reason can be read there. +func Except(spellings map[string]string, reason string, names ...string) map[string]string { + if reason == "" { + panic("openapitest: a placement excused for no reason") + } + out := maps.Clone(spellings) + for _, name := range names { + delete(out, name) + } + return out +} + +// Rows writes each named case, a rest and its union keywords, in every +// spelling Spellings gives. A union written as a oneOf then an anyOf is two +// parts, which Spellings puts apart. +func Rows(cases map[string][2]string) []Row { + rows := make([]Row, 0, len(cases)) + for name, written := range cases { + rows = append(rows, Row{Name: name, Spellings: Spellings(written[0], SplitKeywords(written[1])...)}) + } + slices.SortFunc(rows, func(a, b Row) int { return strings.Compare(a.Name, b.Name) }) + return rows +} + +// ExceptRows is rows with each row's spellings less those named, as Except +// leaves them. +func ExceptRows(rows []Row, reason string, names ...string) []Row { + out := make([]Row, 0, len(rows)) + for _, row := range rows { + out = append(out, Row{Name: row.Name, Spellings: Except(row.Spellings, reason, names...)}) + } + return out +} + +// SplitKeywords splits union, the text of the keywords oneOf and anyOf written +// "oneOf: [...], anyOf: [...]", at the second keyword, and returns union alone +// where it does not write both in that order. +func SplitKeywords(union string) []string { + at := strings.Index(union, "], anyOf: ") + if !strings.HasPrefix(union, "oneOf: ") || at < 0 { + return []string{union} + } + return []string{union[:at+1], union[at+3:]} +} + +// WritesBesideRef reports whether spelling, a schema's text, writes a $ref +// beside another keyword in one mapping, which a 3.0 document reads as a later +// version's construct. +func WritesBesideRef(spelling string) bool { + var root yaml.Node + if yaml.Unmarshal([]byte(spelling), &root) != nil { + return false + } + pending := []*yaml.Node{&root} + for len(pending) > 0 { + node := pending[len(pending)-1] + pending = pending[:len(pending)-1] + pending = append(pending, node.Content...) + if node.Kind != yaml.MappingNode || len(node.Content) < 4 { + continue + } + for i := 0; i < len(node.Content); i += 2 { + if node.Content[i].Value == "$ref" { + return true + } + } + } + return false +} + +// unit is every part, written together. +func (w writing) unit() string { + if w.reverse { + return strings.Join(w.reversed().parts, ", ") + } + return strings.Join(w.parts, ", ") +} + +// reversed is the writing with its parts in the other order. +func (w writing) reversed() writing { + parts := slices.Clone(w.parts) + slices.Reverse(parts) + return writing{rest: w.rest, parts: parts, hasRest: w.hasRest, reverse: w.reverse} +} + +// entries is each part on an entry of its own. +func (w writing) entries() []string { + out := make([]string, 0, len(w.parts)) + for _, part := range w.parts { + out = append(out, braced(part)) + } + return out +} + +// restThen is the rest's entry, if there is a rest, then entries. +func (w writing) restThen(entries ...string) []string { + if !w.hasRest { + return entries + } + return append([]string{braced(w.rest)}, entries...) +} + +// allOf is an allOf of entries, alone in its mapping. +func (w writing) allOf(entries ...string) string { + return "{" + w.allOfKeyword(entries...) + "}" +} + +// allOfKeyword is the allOf keyword of entries, in reverse where w is. +func (w writing) allOfKeyword(entries ...string) string { + if w.reverse { + entries = slices.Clone(entries) + slices.Reverse(entries) + } + return "allOf: [" + strings.Join(entries, ", ") + "]" +} + +// besideOne writes first beside an allOf of the body and each of rest on an +// entry. +func (w writing) besideOne(first string, rest []string) string { + moved := writing{rest: w.rest, parts: rest, hasRest: w.hasRest, reverse: w.reverse} + return mapping(moved.allOfKeyword(moved.restThen(moved.entries()...)...), first) +} + +// mapping is the keywords given, none of them empty, in one mapping. +func mapping(keywords ...string) string { + return "{" + strings.Join(slices.DeleteFunc(slices.Clone(keywords), func(k string) bool { return k == "" }), ", ") + "}" +} + +// braced is keywords as the mapping of one schema. +func braced(keywords string) string { return "{" + keywords + "}" } + +// unbraced is keywords without the braces of the mapping holding them. +func unbraced(keywords string) string { + if inner, ok := strings.CutPrefix(keywords, "{"); ok { + return strings.TrimSuffix(inner, "}") + } + return keywords +} diff --git a/compilers/openapi/internal/openapitest/spellings_test.go b/compilers/openapi/internal/openapitest/spellings_test.go new file mode 100644 index 000000000..8595a045c --- /dev/null +++ b/compilers/openapi/internal/openapitest/spellings_test.go @@ -0,0 +1,174 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package openapitest_test + +import ( + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" +) + +// TestSpellings_ABracedBodyIsTakenAsWritten holds a body in braces to read as +// the same schema as the one without. +func TestSpellings_ABracedBodyIsTakenAsWritten(t *testing.T) { + t.Parallel() + assert.Equal(t, openapitest.Spellings("type: object", "a: 1"), openapitest.Spellings("{type: object}", "a: 1")) +} + +// TestExcept_LeavesOutTheNamedPlacements holds a family's excuse to drop what +// it names and no more, and to need a reason. +func TestExcept_LeavesOutTheNamedPlacements(t *testing.T) { + t.Parallel() + all := openapitest.Spellings("type: object", "a: 1") + got := openapitest.Except(all, "a reason", "Deep", "Beside", "NoSuchPlacement") + assert.NotContains(t, got, "Deep") + assert.NotContains(t, got, "Beside") + assert.Len(t, got, len(all)-2) + assert.Contains(t, all, "Deep", "the spellings given are left as they were") + assert.PanicsWithValue(t, "openapitest: a placement excused for no reason", func() { openapitest.Except(all, "", "Deep") }) +} + +// TestRows_WriteEachCaseInEverySpelling holds rows to come in the order of +// their names, a union of two keywords put apart, and a row excused of a +// placement to lose it alone. +func TestRows_WriteEachCaseInEverySpelling(t *testing.T) { + t.Parallel() + rows := openapitest.Rows(map[string][2]string{ + "B": {"type: object", "oneOf: [a]"}, + "A": {"type: object", "oneOf: [a], anyOf: [b]"}, + }) + require.Len(t, rows, 2) + assert.Equal(t, "A", rows[0].Name) + assert.Equal(t, "B", rows[1].Name) + assert.Contains(t, rows[0].Spellings, "Split", "two union keywords are put apart") + assert.NotContains(t, rows[1].Spellings, "Split") + + excused := openapitest.ExceptRows(rows, "a reason", "Split") + assert.NotContains(t, excused[0].Spellings, "Split") + assert.Contains(t, rows[0].Spellings, "Split", "the rows given are left as they were") + assert.Equal(t, rows[1].Spellings, excused[1].Spellings) +} + +// TestSplitKeywords_SplitsAOneOfThenAnAnyOf holds the split to the two keywords +// in that order and to leave any other text whole. +func TestSplitKeywords_SplitsAOneOfThenAnAnyOf(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + union string + want []string + }{ + {"oneOf: [a], anyOf: [b]", []string{"oneOf: [a]", "anyOf: [b]"}}, + {"oneOf: [a]", []string{"oneOf: [a]"}}, + {"anyOf: [a], oneOf: [b]", []string{"anyOf: [a], oneOf: [b]"}}, + {"oneOf: [a]], anyOf", []string{"oneOf: [a]], anyOf"}}, + } { + assert.Equal(t, tc.want, openapitest.SplitKeywords(tc.union), tc.union) + } +} + +// TestWritesBesideRef_ReadsAMappingHoldingARefAndAnotherKey holds the reading +// to the mapping a $ref sits in, at any depth, and to nothing else. +func TestWritesBesideRef_ReadsAMappingHoldingARefAndAnotherKey(t *testing.T) { + t.Parallel() + for text, want := range map[string]bool{ + "{$ref: '#/a', maxLength: 5}": true, + "{allOf: [{$ref: '#/a', description: d}]}": true, + "{allOf: [{$ref: '#/a'}], description: d}": false, + "{allOf: [{$ref: '#/a'}, {description: d}]}": false, + "{type: string}": false, + "{oneOf: [{$ref: '#/a'}, {$ref: '#/b'}]}": false, + "[unterminated": false, + } { + assert.Equal(t, want, openapitest.WritesBesideRef(text), text) + } +} + +// TestSpellings_NamesAreOneWord holds every placement name to a plain word, so +// a row's subtest name needs no escaping and -run can name it. +func TestSpellings_NamesAreOneWord(t *testing.T) { + t.Parallel() + for name := range openapitest.Spellings("type: object", "a: 1", "b: 2") { + assert.Equal(t, strings.TrimSpace(name), name) + assert.NotContains(t, name, " ", "placement %q", name) + } +} + +// TestPartsOnEntry_NamesWhereAPlacementWritesTheParts holds the placements that +// write the parts in an allOf's entry to say so, and the rest, and a name no +// placement has, to say they do not. +func TestPartsOnEntry_NamesWhereAPlacementWritesTheParts(t *testing.T) { + t.Parallel() + for name, want := range map[string]bool{ + "Flat": false, "Beside": false, "Mixed": false, "MixedRev": false, "NoSuchPlacement": false, + "Entry": true, "UnionEntry": true, "OneEntry": true, "EntryRev": true, "Deep": true, + "OneEntryUnionEntry": true, "DeepTwice": true, "Split": true, "SplitRev": true, "SplitRevBefore": true, "SplitDeep": true, + "EntryPartsRev": true, "FlatPartsRev": false, + } { + assert.Equal(t, want, openapitest.PartsOnEntry(name), name) + } +} + +// TestPartsAt_PointsAtWhereAPlacementWritesTheParts holds the pointer of the +// parts written together in each placement, with a rest and without one, and +// none for a placement that puts them apart or that no placement has. +func TestPartsAt_PointsAtWhereAPlacementWritesTheParts(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + withRest, bare string + }{ + {"Flat", "", ""}, + {"Beside", "", ""}, + {"Entry", "/allOf/1", "/allOf/0"}, + {"UnionEntry", "/allOf/0", "/allOf/0"}, + {"OneEntry", "/allOf/0", "/allOf/0"}, + {"EntryRev", "/allOf/0", "/allOf/0"}, + {"Deep", "/allOf/1/allOf/0", "/allOf/0/allOf/0"}, + {"DeepTwice", "/allOf/1/allOf/0/allOf/0", "/allOf/0/allOf/0/allOf/0"}, + {"OneEntryUnionEntry", "/allOf/0/allOf/0", "/allOf/0/allOf/0"}, + {"Split", "", ""}, + {"NoSuchPlacement", "", ""}, + } { + assert.Equal(t, tc.withRest, openapitest.PartsAt(tc.name, true), tc.name) + assert.Equal(t, tc.bare, openapitest.PartsAt(tc.name, false), tc.name) + } +} + +// TestPlacements_WriteATextEachPlacementSharesUnderEveryName holds Placements to +// name what Spellings writes once under each name that writes it, so that the +// same body with no parts has every name its parts have. +func TestPlacements_WriteATextEachPlacementSharesUnderEveryName(t *testing.T) { + t.Parallel() + all := openapitest.Placements("type: object", "a: 1") + assert.Equal(t, all["OneEntry"], "{allOf: [{type: object, a: 1}]}") + assert.Greater(t, len(openapitest.Placements("", "a: 1")), len(openapitest.Spellings("", "a: 1")), "Placements keeps the repeats") + bare := openapitest.Placements("type: object") + assert.Equal(t, "{allOf: [{type: object}]}", bare["OneEntry"]) + assert.Equal(t, "{allOf: [{type: object}]}", bare["Beside"]) + assert.Equal(t, "{allOf: [{type: object}, {}]}", bare["Entry"]) + for name := range all { + assert.Contains(t, bare, name, "a body with no parts is written in every placement it has parts in") + } +} + +// TestReversed_WritesEveryListInTheOtherOrder holds the reversed spellings to +// put the parts and the entries the other way about, the body's entry last, and +// to write the placements the forward ones do. +func TestReversed_WritesEveryListInTheOtherOrder(t *testing.T) { + t.Parallel() + got := openapitest.Reversed("type: object", "a: 1", "b: 2") + assert.Equal(t, "{type: object, b: 2, a: 1}", got["Flat"]) + assert.Equal(t, "{allOf: [{b: 2, a: 1}, {type: object}]}", got["Entry"]) + assert.Equal(t, "{allOf: [{b: 2}, {a: 1}, {type: object}]}", got["Split"]) + assert.Equal(t, "{allOf: [{allOf: [{b: 2}, {a: 1}]}, {type: object}]}", got["SplitDeep"]) + assert.Equal(t, "{allOf: [{b: 2}, {type: object}], a: 1}", got["Mixed"]) + assert.ElementsMatch(t, slices.Collect(maps.Keys(openapitest.Spellings("type: object", "a: 1", "b: 2"))), + slices.Collect(maps.Keys(got))) +} diff --git a/compilers/openapi/internal/operation/callbacks.go b/compilers/openapi/internal/operation/callbacks.go index 22c193f00..1294fd808 100644 --- a/compilers/openapi/internal/operation/callbacks.go +++ b/compilers/openapi/internal/operation/callbacks.go @@ -39,10 +39,10 @@ func operationCallbacks(serviceContext service.Ctx, loweringState operationLower } at := operationCtx.ptrs.decl + ids.Ptr("callbacks") var kept ir.Unmodeled - written, diags := annotation.PreserveNodeInto(&kept, annotation.EntryKey("", "callbacks"), + written, diags := annotation.KeepNodeInto(&kept, annotation.EntryKey("", "callbacks"), nodeview.Child(src.GetRootNode(), "callbacks"), ir.ReasonDegradedLowering, serviceContext.Place().At(at)) if written { - schema.RecordReached(serviceContext.Ctx, at) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, at)...) diags = append(diags, serviceContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, at, "callbacks nested deeper than %d levels are not lowered; they are kept verbatim on the HTTP binding "+ "of the operation declaring them", maxCallbackNesting)) @@ -70,7 +70,7 @@ func lowerCallbacks(serviceContext service.Ctx, loweringState operationLoweringS beside, besideDiags := service.Beside[soa.Callback](serviceContext, rcb, use, false) ext = annotation.MergeUnmodeled(ext, annotation.Under(ids.Scope("callbacks", cbName), beside)) diags = append(diags, besideDiags...) - cb, serviceContextValue, cbDecl := service.Declared[soa.Callback](serviceContext, rcb, use) + cb, serviceContext, cbDecl := service.Declared[soa.Callback](serviceContext, rcb, use) if cb == nil { continue } @@ -78,12 +78,12 @@ func lowerCallbacks(serviceContext service.Ctx, loweringState operationLoweringS // expression's path item, and ir.Callback holds no Unmodeled map. The HTTP // binding does, and is where the callbacks themselves live, so they are kept // there under the name the callback is mapped by. - cbExt, cbExtDiags := annotation.ExtensionsUnder(cb.GetExtensions(), serviceContextValue.Place(), cbDecl, ids.Scope("callbacks", cbName)) + cbExt, cbExtDiags := annotation.ExtensionsUnder(cb.GetExtensions(), serviceContext.Place(), cbDecl, ids.Scope("callbacks", cbName)) ext = annotation.MergeUnmodeled(ext, cbExt) diags = append(diags, cbExtDiags...) for expr, rp := range cb.All() { exprString := string(expr) - layers := pathItemLayers(serviceContextValue, rp, cbDecl+ids.Ptr(exprString)) + layers := pathItemLayers(serviceContext, rp, cbDecl+ids.Ptr(exprString)) if layers == nil { continue } @@ -92,7 +92,7 @@ func lowerCallbacks(serviceContext service.Ctx, loweringState operationLoweringS key: exprString, template: exprString, inbound: ir.HTTPInboundCallback, inferred: parent.inferred, nesting: parent.nesting + 1, } - at := mountSite{ptr: mount, use: serviceContextValue, usePtr: cbDecl + ids.Ptr(exprString)} + at := mountSite{ptr: mount, use: serviceContext, usePtr: cbDecl + ids.Ptr(exprString)} operationIDs, cbOperations, orphan, cbDiags := lowerCallbackOperations(loweringState, layers, at, route) ext = annotation.MergeUnmodeled(ext, orphan) diags = append(diags, cbDiags...) @@ -115,7 +115,7 @@ func lowerCallbacks(serviceContext service.Ctx, loweringState operationLoweringS // parent's HTTP binding. func lowerCallbackOperations(loweringState operationLoweringState, layers []layer, at mountSite, route operationContext) ([]ir.OperationID, []ir.Operation, ir.Unmodeled, []ir.Diagnostic) { var orphan ir.Unmodeled - at.residue = &orphan + at.orphanUnmodeled = &orphan mounted, diags := mountPathItem(loweringState, layers, at, route) operationIDs := make([]ir.OperationID, 0, len(mounted)) operations := make([]ir.Operation, 0, len(mounted)) @@ -148,7 +148,7 @@ func lowerWebhooks(ctx context.Context, serviceContext service.Ctx, loweringStat continue } route := operationContext{key: name, inbound: ir.HTTPInboundWebhook} - at := mountSite{ptr: hookPtr, use: serviceContext, usePtr: hookPtr, residue: &svc.Unmodeled} + at := mountSite{ptr: hookPtr, use: serviceContext, usePtr: hookPtr, orphanUnmodeled: &svc.Unmodeled} mounted, hookDiags := mountPathItem(loweringState, layers, at, route) diags = append(diags, hookDiags...) for _, mountedOperation := range mounted { diff --git a/compilers/openapi/internal/operation/callbacks_test.go b/compilers/openapi/internal/operation/callbacks_test.go index 1e6ae9d0e..1bb5b6a36 100644 --- a/compilers/openapi/internal/operation/callbacks_test.go +++ b/compilers/openapi/internal/operation/callbacks_test.go @@ -71,7 +71,7 @@ components: // callback scope is "callbacks/" and the name is a document-chosen map // key, so a "/" in it must not read as a separator and merge two callbacks into // one key on the HTTP binding. Both sites take their scope from ids.Scope, and -// each needs its own case, since a fix at one can leave the other standing. +// each needs its own case, since a fix at one can leave the other in place. func TestCallbacks_NameWithSlashKeepsItsOwnKey(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.PathsSpec(` /p: diff --git a/compilers/openapi/internal/operation/catchall.go b/compilers/openapi/internal/operation/catchall.go index 204bdfc47..c9d43eea1 100644 --- a/compilers/openapi/internal/operation/catchall.go +++ b/compilers/openapi/internal/operation/catchall.go @@ -17,11 +17,11 @@ import ( // key. A part is read as a declared part with no encoding entry is // (catchAllReading.part), since OpenAPI keys an Encoding Object by a property's name // and a catch-all has none. -func (k partKeys) settleCatchAlls(reg ir.TypeRegistry, node func(ir.TypeID) (ir.TypeDef, bool)) { - holders, _ := memberHolders(node, k.body) +func (k partKeys) settleCatchAlls(reg ir.TypeRegistry, chains *runChains) { + holders, _ := memberHolders(chains, k.body) read := catchAllReading{ unions: partUnionsOf(k.c), - node: node, + chains: chains, multipart: isMultipart(k.mediaType), rules: service.EncodingRules(k.c), encodedBy: readContentEncoding(k.c, k.catchAllValues), @@ -36,12 +36,13 @@ func (k partKeys) settleCatchAlls(reg ir.TypeRegistry, node func(ir.TypeID) (ir. } // catchAllReading is what reading one body's catch-all parts shares: the -// run's reading of the unions parts name, the registry's lookup, the Encoding -// Object's rows at the document's minor, whether the body is multipart, and -// what the catch-alls' value schemas write of contentEncoding. +// run's reading of the unions parts name, the run's readings of its alias +// chains, the Encoding Object's rows at the document's minor, whether the body +// is multipart, and what the catch-alls' value schemas write of +// contentEncoding. type catchAllReading struct { unions *partUnions - node func(ir.TypeID) (ir.TypeDef, bool) + chains *runChains rules specrules.EncodingRules encodedBy contentEncoding multipart bool @@ -51,14 +52,14 @@ type catchAllReading struct { // catch-all, admits: its value's, and each pattern's, each only where it says // something (partEncodingEmpty). says is false where neither does. func (r catchAllReading) parts(holder ir.TypeDef) (parts ir.CatchAllParts, says bool) { - switch h := holder.(type) { + switch typed := holder.(type) { case *ir.MapT: - parts.Value = r.value(h.Value) + parts.Value = r.value(typed.Value) case *ir.Model: - if h.AdditionalProperties.Value != nil { - parts.Value = r.value(*h.AdditionalProperties.Value) + if typed.AdditionalProperties.Value != nil { + parts.Value = r.value(*typed.AdditionalProperties.Value) } - for _, patternProperties := range h.AdditionalProperties.Patterns { + for _, patternProperties := range typed.AdditionalProperties.Patterns { if pe := r.part(patternProperties.Value); !partEncodingEmpty(pe) { if parts.Patterns == nil { parts.Patterns = map[string]ir.PartEncoding{} @@ -88,6 +89,7 @@ func (r catchAllReading) value(ref ir.TypeRef) *ir.PartEncoding { // Headers are the entry's to state, and a catch-all's part has none. func (r catchAllReading) part(ref ir.TypeRef) ir.PartEncoding { var pe ir.PartEncoding - pe.RepeatsPerArrayItem, pe.HasFilename, _ = partTypeFlags(r.unions, r.node, ref, r.multipart) - return withDefaultContentType(r.unions, r.node, r.rules, &ir.Property{Type: ref}, r.encodedBy, pe) + flags := partTypeFlags(r.unions, r.chains, ref, r.multipart) + pe.RepeatsPerArrayItem, pe.HasFilename = flags.multi, flags.file + return withDefaultContentType(r.unions, r.chains, r.rules, &ir.Property{Type: ref}, r.encodedBy, pe) } diff --git a/compilers/openapi/internal/operation/content.go b/compilers/openapi/internal/operation/content.go index 77fc32c20..bf0c16dff 100644 --- a/compilers/openapi/internal/operation/content.go +++ b/compilers/openapi/internal/operation/content.go @@ -53,7 +53,7 @@ func lowerPayload(serviceContext service.Ctx, loweringState operationLoweringSta return payload, diags } -// mediaDecl is the Media Type Object a content entry stands for, with the +// mediaDecl is the Media Type Object a content entry names, with the // context and pointer declaring it: the entry itself, or what the chain of the // $ref the entry is written as, use, ends on. entryCtx and entryPtr are where // the entry itself is written. @@ -67,7 +67,7 @@ type mediaDecl struct { } // declaredMedia returns what the content entry media, written at mediaPtr in -// serviceContext's document, stands for (mediaDecl), and false for one written +// serviceContext's document, names (mediaDecl), and false for one written // as a $ref resolving to nothing, which lowers nothing, as any reference object // does (docs/compilers/openapi.md#references), where the load phase reported // why. The keys beside each $ref of use's chain are the Content's @@ -90,19 +90,19 @@ func declaredMedia(serviceContext service.Ctx, media *soa.MediaType, mediaPtr js return mediaDecl{ctx: dc, media: obj, pointer: decl, use: use, entryCtx: serviceContext, entryPtr: mediaPtr}, true } -// mediaTypeDocs returns the docs of the media type mediaDeclValue declares: its +// mediaTypeDocs returns the docs of the media type mediaDecl declares: its // own description, which OpenAPI 3.2 adds and the parser's model names no field -// for, with the summary and description beside each $ref of mediaDeclValue's +// for, with the summary and description beside each $ref of mediaDecl's // use folded over it (docs/compilers/openapi.md#reference-object-siblings), and // the keys it read for the census to leave alone. It reads the description at // every version, as load reports the key below 3.2 // (diag.LaterVersionConstruct). -func mediaTypeDocs(mediaDeclValue mediaDecl, unmodeled *ir.Unmodeled) (ir.Docs, []string, []ir.Diagnostic) { - description, read, diags := annotation.TakeString(unmodeled, mediaDeclValue.media.GetRootNode(), "description", nil, - mediaDeclValue.ctx.Place(), mediaDeclValue.pointer, "") +func mediaTypeDocs(mediaDecl mediaDecl, unmodeled *ir.Unmodeled) (ir.Docs, []string, []ir.Diagnostic) { + description, read, diags := annotation.TakeString(unmodeled, mediaDecl.media.GetRootNode(), "description", nil, + mediaDecl.ctx.Place(), mediaDecl.pointer, "") docs := ir.Docs{Description: description} - if mediaDeclValue.use != nil { - docs = componentlookup.UseDocs[soa.MediaType](mediaDeclValue.entryCtx.Bindings(), mediaDeclValue.use, docs) + if mediaDecl.use != nil { + docs = componentlookup.UseDocs[soa.MediaType](mediaDecl.entryCtx.Bindings(), mediaDecl.use, docs) } if !read { return docs, nil, diags @@ -112,11 +112,11 @@ func mediaTypeDocs(mediaDeclValue mediaDecl, unmodeled *ir.Unmodeled) (ir.Docs, // lowerContent lowers one media-type view: its type graph, examples, binary/ // form specialization, sequential-media shape, whether it streams, docs and -// extensions, as mediaDeclValue declares them, under mt, the key it is written +// extensions, as mediaDecl declares them, under mt, the key it is written // under. -func lowerContent(mediaDeclValue mediaDecl, loweringState operationLoweringState, mt string) (ir.Content, []ir.Diagnostic) { - serviceContext, media, mediaPtr := mediaDeclValue.ctx, mediaDeclValue.media, mediaDeclValue.pointer - mediaType, diags := schema.Ref(serviceContext.Ctx, loweringState.types, schema.TopLevelDepth, mediaDeclValue.ctx.Statements().Of(media.GetSchema()), mediaPtr+ids.Ptr("schema")) +func lowerContent(mediaDecl mediaDecl, loweringState operationLoweringState, mt string) (ir.Content, []ir.Diagnostic) { + serviceContext, media, mediaPtr := mediaDecl.ctx, mediaDecl.media, mediaDecl.pointer + mediaType, diags := schema.Ref(serviceContext.Ctx, loweringState.types, schema.TopLevelDepth, mediaDecl.ctx.Statements().Of(media.GetSchema()), mediaPtr+ids.Ptr("schema")) content := ir.Content{ MediaType: mt, Type: mediaType, @@ -149,13 +149,13 @@ func lowerContent(mediaDeclValue mediaDecl, loweringState operationLoweringState if len(ext) > 0 { content.Unmodeled = annotation.MergeUnmodeled(content.Unmodeled, ext) } - docs, taken, docDiags := mediaTypeDocs(mediaDeclValue, &content.Unmodeled) + docs, taken, docDiags := mediaTypeDocs(mediaDecl, &content.Unmodeled) content.Docs = docs diags = append(diags, docDiags...) - if mediaDeclValue.use != nil { + if mediaDecl.use != nil { // What the entry's chain writes beside each $ref rides on the Content the // use lowers to, its summary and description folded into Docs above. - beside, besideDiags := service.Beside[soa.MediaType](mediaDeclValue.entryCtx, mediaDeclValue.use, mediaDeclValue.entryPtr, true) + beside, besideDiags := service.Beside[soa.MediaType](mediaDecl.entryCtx, mediaDecl.use, mediaDecl.entryPtr, true) content.Unmodeled = annotation.MergeUnmodeled(content.Unmodeled, beside) diags = append(diags, besideDiags...) } @@ -210,13 +210,13 @@ func schemaOf(refs *typed.Bindings, js *oas3.JSONSchema[oas3.Referenceable]) *oa if js == nil || !js.IsSchema() { return nil } - s := js.GetSchema() + oasSchema := js.GetSchema() if refs.RefSite(js) { if end := refs.End(js); end != nil { return end.GetSchema() } } - return s + return oasSchema } // statementOf is schemaOf read as a statement: the schema whose object diff --git a/compilers/openapi/internal/operation/content_test.go b/compilers/openapi/internal/operation/content_test.go index e537f4efb..67c5230d7 100644 --- a/compilers/openapi/internal/operation/content_test.go +++ b/compilers/openapi/internal/operation/content_test.go @@ -297,9 +297,9 @@ components: } // TestContent_ARefinedBinaryBodyIsAFile pins that wrapping a binary body in an -// allOf changes what a body is no more than a $ref does: a refinement is a use of -// the schema it names, in either spelling, of the narrower of two it names, or -// the value set of the entry an enum beside it narrows to, standing at the +// allOf changes what a body is no more than a $ref does: a refinement is a use +// of the schema it names, in either spelling, of the narrower of two it names, +// or the value set of the entry an enum beside it narrows to, sitting at the // position, and one over no binary schema is a plain body. func TestContent_ARefinedBinaryBodyIsAFile(t *testing.T) { t.Parallel() @@ -469,7 +469,7 @@ func TestContent_OctetAndErrorMulti(t *testing.T) { require.Len(t, raw.Errors, 1) payload := raw.Errors[0].Payload require.NotNil(t, payload) - require.Len(t, payload.Contents, 2, "neither media type is elected over the other") + require.Len(t, payload.Contents, 2, "neither media type is chosen over the other") assert.Equal(t, []string{"application/json", "application/problem+json"}, []string{payload.Contents[0].MediaType, payload.Contents[1].MediaType}) assert.Empty(t, raw.Errors[0].Unmodeled, "nothing is kept verbatim beside the typed payload") @@ -606,9 +606,9 @@ func TestContent_InlineSchemaKeepsItsUseSiteHint(t *testing.T) { `) doc, diags := parseFull(t, spec) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types[ir.TypeID("type/anonymous/paths/~1a/post/requestBody/content/application~1json/schema")] + typeDef, ok := doc.Types[ir.TypeID("type/anonymous/paths/~1a/post/requestBody/content/application~1json/schema")] require.True(t, ok) - assert.Equal(t, "post_a_request", td.Common().Name.Hint) + assert.Equal(t, "post_a_request", typeDef.Common().Name.Hint) } // TestContent_AMediaTypeRefHoldingNoStringLowersNothing pins the content entry @@ -805,9 +805,9 @@ x-headers: assert.Empty(t, cmp.Diff(forward, backward), "the names must not follow the declaration order") var nodes []string - for _, td := range forward { - if td.Common().Provenance.Source != ir.NoSource { - nodes = append(nodes, string(td.Common().ID)+" "+td.Common().Name.Hint) + for _, typeDef := range forward { + if typeDef.Common().Provenance.Source != ir.NoSource { + nodes = append(nodes, string(typeDef.Common().ID)+" "+typeDef.Common().Name.Hint) } } slices.Sort(nodes) diff --git a/compilers/openapi/internal/operation/encoding.go b/compilers/openapi/internal/operation/encoding.go index 8137df964..d05a81a52 100644 --- a/compilers/openapi/internal/operation/encoding.go +++ b/compilers/openapi/internal/operation/encoding.go @@ -88,11 +88,11 @@ func keepIgnoredFields(serviceContext service.Ctx, enc *soa.Encoding, encPtr jso continue } at := encPtr + ids.Ptr(field) - written, keepDiags := annotation.PreserveNodeInto(&kept, annotation.EntryKey(scope, field), + written, keepDiags := annotation.KeepNodeInto(&kept, annotation.EntryKey(scope, field), nodeview.Child(enc.GetRootNode(), field), ir.ReasonNoIRHome, serviceContext.Place().At(at)) diags = append(diags, keepDiags...) if written { - schema.RecordReached(serviceContext.Ctx, at) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, at)...) diags = append(diags, serviceContext.DiagAt(ir.SeverityWarning, specrules.NoEffect, at, "Encoding Object field %q has no effect under %q, where the specification ignores it; kept verbatim under Unmodeled", field, mt)) @@ -138,13 +138,13 @@ func nestedEncodings(serviceContext service.Ctx, out *ir.Unmodeled, enc *soa.Enc var diags []ir.Diagnostic for _, keyword := range nestedEncodingFields { at := encPtr + ids.Ptr(keyword) - kept, keptDiags := annotation.PreserveNodeInto(out, annotation.EntryKey(scope, keyword), + kept, keptDiags := annotation.KeepNodeInto(out, annotation.EntryKey(scope, keyword), nodeview.Child(enc.GetRootNode(), keyword), ir.ReasonNoIRHome, serviceContext.Place().At(at)) diags = append(diags, keptDiags...) if !kept { continue } - schema.RecordReached(serviceContext.Ctx, at) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, at)...) diags = append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, "encoding %s has no ir.PartEncoding home; kept verbatim under Unmodeled", keyword)) } @@ -159,8 +159,8 @@ func splitContentTypes(raw string) []string { } var out []string for part := range strings.SplitSeq(raw, ",") { - if s := strings.TrimSpace(part); s != "" { - out = append(out, s) + if trimmed := strings.TrimSpace(part); trimmed != "" { + out = append(out, trimmed) } } return out diff --git a/compilers/openapi/internal/operation/examples.go b/compilers/openapi/internal/operation/examples.go index 7a2681ee5..e2381317f 100644 --- a/compilers/openapi/internal/operation/examples.go +++ b/compilers/openapi/internal/operation/examples.go @@ -5,7 +5,6 @@ package operation import ( "encoding/json/jsontext" - "slices" soa "github.com/speakeasy-api/openapi/openapi" "github.com/speakeasy-api/openapi/sequencedmap" @@ -89,7 +88,7 @@ func appendPluralExample(serviceContext service.Ctx, out []ir.Example, re *soa.R // there. No key of the Example Object can spell it, as one holding a "/" is // escaped, so an undeclared name key the object writes stays its own entry. func keepEmptyName(serviceContext service.Ctx, ext *ir.Unmodeled, use jsontext.Pointer) []ir.Diagnostic { - annotation.PreserveInto(ext, annotation.EntryKey("examples", "key"), ir.RawValue(`""`), + annotation.KeepInto(ext, annotation.EntryKey("examples", "key"), ir.RawValue(`""`), ir.ReasonDegradedLowering, serviceContext.Place().At(use)) return []ir.Diagnostic{serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, use, "examples entry is keyed by the empty string, which ir.Example.Name reads as no name; the key is kept under Unmodeled")} @@ -149,19 +148,10 @@ func keepExampleSpelling(serviceContext service.Ctx, unmodeled *ir.Unmodeled, no reason ir.UnmodeledReason, decl jsontext.Pointer, why string, ) (bool, []ir.Diagnostic) { at := decl + ids.Ptr(keyword) - kept, diags := annotation.PreserveNodeInto(unmodeled, annotation.EntryKey("", keyword), node, reason, serviceContext.Place().At(at)) + kept, diags := annotation.KeepNodeInto(unmodeled, annotation.EntryKey("", keyword), node, reason, serviceContext.Place().At(at)) if !kept { return false, diags } return true, append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, "%s; kept verbatim under Unmodeled", why)) } - -// positionExamples returns the examples a parameter or header writes for -// itself: its own, then those of the media type its content spelling elected. -// Together they replace the schema's, as OpenAPI says a position's example -// overrides its schema's, but neither replaces the other: OpenAPI orders them -// nowhere, and keeping one would drop the other in silence (GitHub #611). -func positionExamples(own, media []ir.Example) []ir.Example { - return slices.Concat(own, media) -} diff --git a/compilers/openapi/internal/operation/examples_test.go b/compilers/openapi/internal/operation/examples_test.go index c95592b8b..98207a751 100644 --- a/compilers/openapi/internal/operation/examples_test.go +++ b/compilers/openapi/internal/operation/examples_test.go @@ -177,7 +177,7 @@ components: // TestParamContent_OwnAndMediaExamplesAreBothKept pins how a parameter's or a // header's examples combine (GitHub #611): those the object writes itself and -// those its elected media type writes are both kept, its own first, and +// those its chosen media type writes are both kept, its own first, and // together they replace the schema's — neither drops the other. func TestParamContent_OwnAndMediaExamplesAreBothKept(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/operation/filebody.go b/compilers/openapi/internal/operation/filebody.go index 279bd00fc..d6d2edf3d 100644 --- a/compilers/openapi/internal/operation/filebody.go +++ b/compilers/openapi/internal/operation/filebody.go @@ -71,7 +71,7 @@ func readSchema(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Referenceab } // The union holds beside what statementSchema says itself, so a string // statementSchema keeps its branches to strings. - read := lowering.ReadOncePerRun(serviceContext.Ctx, unionFileOf{s: statementSchema, part: branch.part}, func() fileReading { + read := lowering.ReadOncePerRun(serviceContext.Ctx, unionFileKey{s: statementSchema, part: branch.part}, func() fileReading { return readUnion(serviceContext, union, branch.read) }) if own != readsString || read != readsUntyped { @@ -91,12 +91,12 @@ type branchReading struct { part bool } -// unionFileOf is what a union's reading as a file is remembered under +// unionFileKey is what a union's reading as a file is remembered under // (lowering.ReadOncePerRun): s, the schema writing the union, which a $ref // chain ends on, and whether its branches are read as a part's, which reads a // list of bytes through its elements where a body's does not. The reading turns // on nothing else: the documents, and the bindings of their $refs. -type unionFileOf struct { +type unionFileKey struct { s *statement.Schema part bool } @@ -145,7 +145,7 @@ func besideRefsOpen(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Referen // Where none does, decided is false and statementSchema is the schema whose // keywords the caller reads, never nil, as a position holding no schema reads // as a boolean. -func readHead(serviceContext service.Ctx, js *statement.Statement) (statementSchema *statement.Schema, fileReadingValue fileReading, decided bool) { +func readHead(serviceContext service.Ctx, js *statement.Statement) (statementSchema *statement.Schema, fileReading fileReading, decided bool) { end := serviceContext.Statements().Of(refEnd(serviceContext.Bindings(), statement.ParsedAt(js))) switch { case end.Truth.ReadsFalse(): @@ -173,14 +173,14 @@ func refEnd(refs *typed.Bindings, js *oas3.JSONSchema[oas3.Referenceable]) *oas3 return js } -// declaresBinary reports whether s declares raw bytes: format binary on a +// declaresBinary reports whether oasSchema declares raw bytes: format binary on a // schema whose type includes string or is unwritten, and that names no // contentEncoding, which makes the bytes text as the type lowering reads it. -func declaresBinary(s *oas3.Schema) bool { - if s == nil || s.GetFormat() != "binary" || s.GetContentEncoding() != "" { +func declaresBinary(oasSchema *oas3.Schema) bool { + if oasSchema == nil || oasSchema.GetFormat() != "binary" || oasSchema.GetContentEncoding() != "" { return false } - types := s.GetType() + types := oasSchema.GetType() return len(types) == 0 || slices.Contains(types, oas3.SchemaTypeString) } @@ -188,13 +188,13 @@ func declaresBinary(s *oas3.Schema) bool { // untyped or other: other where it writes a keyword no file leaves open // (openKeyword), or a type other than string, alone or with null. func readOpen(serviceContext service.Ctx, statementSchema *statement.Schema, unions bool) fileReading { - m := statement.Parsed(statementSchema) + parsed := statement.Parsed(statementSchema) if !writesOnlyOpenKeywords(serviceContext, statementSchema, unions) { return readsOther } - types := withoutNull(m.GetType()) + types := withoutNull(parsed.GetType()) switch { - case len(m.GetType()) == 0: + case len(parsed.GetType()) == 0: return readsUntyped case len(types) == 1 && types[0] == oas3.SchemaTypeString: return readsString @@ -214,7 +214,7 @@ func writesOnlyOpenKeywords(serviceContext service.Ctx, statementSchema *stateme } // writesOnly reports whether every keyword statementSchema writes is one -// allowed takes, a null standing for a keyword left out passing whatever its +// allowed takes, a null naming a keyword left out passing whatever its // key. The keys are the statement's, so a key it leaves out // (statement.Schema.Truncated) is not read here either. func writesOnly(statementSchema *statement.Schema, allowed func(string) bool) bool { @@ -256,11 +256,11 @@ func readUnion(serviceContext service.Ctx, branches []*oas3.JSONSchema[oas3.Refe }) { return readsOther } - return leastOf(serviceContext, branches, func(serviceContextValue service.Ctx, branch *oas3.JSONSchema[oas3.Referenceable]) fileReading { - if admitsNoBytes(serviceContextValue, branch) { + return leastOf(serviceContext, branches, func(serviceContext service.Ctx, branch *oas3.JSONSchema[oas3.Referenceable]) fileReading { + if admitsNoBytes(serviceContext, branch) { return readsBinary // the top, which leaves the least of the others } - return read(serviceContextValue, branch) + return read(serviceContext, branch) }) } @@ -301,16 +301,16 @@ func withoutNull(types []oas3.SchemaType) []oas3.SchemaType { } // bodyFile returns the FileInfo of a content entry under mt whose schema reads -// as fileReadingValue, or nil where it is no file body: declared where the +// as fileReading, or nil where it is no file body: declared where the // schema declares raw bytes, or where it leaves the media type to say and that // is application/octet-stream, which RFC 2046 defines as arbitrary octets; // marked where it leaves it to a media type the binary policy names. -func bodyFile(serviceContext service.Ctx, mt string, fileReadingValue fileReading) *ir.FileInfo { +func bodyFile(serviceContext service.Ctx, mt string, fileReading fileReading) *ir.FileInfo { file := &ir.FileInfo{IsText: false, ContentTypes: []string{mt}} switch { - case fileReadingValue == readsBinary: + case fileReading == readsBinary: return file - case !fileReadingValue.open(): + case !fileReading.open(): return nil case service.NormalizeMediaType(mt) == octetStream: return file diff --git a/compilers/openapi/internal/operation/filebody_internal_test.go b/compilers/openapi/internal/operation/filebody_internal_test.go index fcd299940..f0c6584c9 100644 --- a/compilers/openapi/internal/operation/filebody_internal_test.go +++ b/compilers/openapi/internal/operation/filebody_internal_test.go @@ -39,9 +39,9 @@ func TestLeastOf_StopsAtOther(t *testing.T) { t.Parallel() reads := 0 serviceContext := servicetest.Context(t, openapitest.EmptySpec, service.Policy{}) - got := leastOf(serviceContext, tc.items, func(_ service.Ctx, fileReadingValue fileReading) fileReading { + got := leastOf(serviceContext, tc.items, func(_ service.Ctx, fileReading fileReading) fileReading { reads++ - return fileReadingValue + return fileReading }) assert.Equal(t, tc.want, got, "least") assert.Equal(t, tc.reads, reads, "items read") @@ -64,15 +64,15 @@ func unionSchemas(branches []string, uses int) string { // readAs reads the component name of the document lowererValue holds as a body, // or as a part when part is set, through the branch reader of that reading, // counting each branch read in reads. -func readAs(t *testing.T, lowererValue *lowerer, name string, part bool, reads *int) fileReading { +func readAs(t *testing.T, lowerer *lowerer, name string, part bool, reads *int) fileReading { t.Helper() - js, ok := lowererValue.ctx.Doc.Components.Schemas.Get(name) + js, ok := lowerer.ctx.Doc.Components.Schemas.Get(name) require.True(t, ok, name) read := readBranch if part { read = readPartBranch } - return readSchema(lowererValue.ctx, js, branchReading{part: part, read: func(serviceContext service.Ctx, branch *oas3.JSONSchema[oas3.Referenceable]) fileReading { + return readSchema(lowerer.ctx, js, branchReading{part: part, read: func(serviceContext service.Ctx, branch *oas3.JSONSchema[oas3.Referenceable]) fileReading { *reads++ return read(serviceContext, branch) }}) diff --git a/compilers/openapi/internal/operation/groups.go b/compilers/openapi/internal/operation/groups.go index e2089e212..a5aa291ab 100644 --- a/compilers/openapi/internal/operation/groups.go +++ b/compilers/openapi/internal/operation/groups.go @@ -155,8 +155,8 @@ func (g *serviceGroups) filingFor(serviceContext service.Ctx, src *soa.Operation filed = filing{levels: extensionLevels(paths[0]), inferred: service.GroupExtensionHeuristic} paths = paths[1:] } - for _, p := range slices.Concat(paths, aliases) { - filed.remounts = append(filed.remounts, extensionLevels(p)) + for _, path := range slices.Concat(paths, aliases) { + filed.remounts = append(filed.remounts, extensionLevels(path)) } filed.diags = diags return filed diff --git a/compilers/openapi/internal/operation/groups_test.go b/compilers/openapi/internal/operation/groups_test.go index 2a774d60f..660c08ce9 100644 --- a/compilers/openapi/internal/operation/groups_test.go +++ b/compilers/openapi/internal/operation/groups_test.go @@ -574,11 +574,11 @@ func placements(t *testing.T, groups []ir.OperationGroup) map[ir.GroupID]groupPl next := stack[len(stack)-1] stack = stack[:len(stack)-1] require.NotContains(t, out, next.group.ID, "two groups share the ID %q", next.group.ID) - groupPlacementValue := groupPlacement{parent: next.parent, name: next.group.Name.Source} + groupPlacement := groupPlacement{parent: next.parent, name: next.group.Name.Source} for _, operation := range next.group.Operations { - groupPlacementValue.operations = append(groupPlacementValue.operations, operation.ID) + groupPlacement.operations = append(groupPlacement.operations, operation.ID) } - out[next.group.ID] = groupPlacementValue + out[next.group.ID] = groupPlacement for _, child := range slices.Backward(next.group.Groups) { stack = append(stack, pending{parent: next.group.ID, group: child}) } @@ -841,7 +841,7 @@ func TestGrouping_ByExtensionMintsAGroupForEachAlias(t *testing.T) { assert.Equal(t, []string{"info at /paths/~1bad/get/x-aliases"}, found) listQueries := svc.Groups[2].Operations[0] require.Equal(t, ir.OperationID("operation/openapi/paths/~1queries/get"), listQueries.ID) - assert.Empty(t, listQueries.Provenance.Inferred, "an alias moves no filing, so the fallback's marker stands") + assert.Empty(t, listQueries.Provenance.Inferred, "an alias moves no filing, so the fallback's marker remains") assert.JSONEq(t, `[{"x-group":"o11y.queries"}]`, string(listQueries.Unmodeled["openapi:x-aliases"].Value), "the aliases stay kept whole") } diff --git a/compilers/openapi/internal/operation/headers.go b/compilers/openapi/internal/operation/headers.go index f6ec033c9..41b8d4d00 100644 --- a/compilers/openapi/internal/operation/headers.go +++ b/compilers/openapi/internal/operation/headers.go @@ -5,6 +5,7 @@ package operation import ( "encoding/json/jsontext" + "slices" soa "github.com/speakeasy-api/openapi/openapi" "github.com/speakeasy-api/openapi/sequencedmap" @@ -30,11 +31,11 @@ func lowerHeaders(serviceContext service.Ctx, loweringState operationLoweringSta out := make([]ir.Header, 0, headers.Len()) for name, rh := range headers.All() { hptr := basePtr + ids.Ptr("headers", name) - h, dc, hdecl := service.Declared[soa.Header](serviceContext, rh, hptr) - if h == nil { + declaredHeader, dc, hdecl := service.Declared[soa.Header](serviceContext, rh, hptr) + if declaredHeader == nil { continue } - lowered, headerDiags := lowerHeader(serviceContext, dc, loweringState, h, name, hptr, hdecl) + lowered, headerDiags := lowerHeader(serviceContext, dc, loweringState, declaredHeader, name, hptr, hdecl) diags = append(diags, headerDiags...) // A summary or description beside a $ref of the entry's chain documents // this header rather than the declaration it names (GitHub #610). @@ -55,45 +56,45 @@ func lowerHeaders(serviceContext service.Ctx, loweringState operationLoweringSta // hold, as declared: undeclared, each stays unset rather than being written as // the default. Written beside content, where they have no effect, they lower // as declared, and load's rule table reports them, as a parameter's. -func lowerHeader(serviceContext, dc service.Ctx, loweringState operationLoweringState, h *soa.Header, name string, hptr, hdecl jsontext.Pointer) (ir.Header, []ir.Diagnostic) { - elected, diags := electTypeSpelling(dc, loweringState, h.GetSchema(), h.GetContent(), h.GetRootNode(), hdecl, +func lowerHeader(serviceContext, dc service.Ctx, loweringState operationLoweringState, header *soa.Header, name string, hptr, hdecl jsontext.Pointer) (ir.Header, []ir.Diagnostic) { + chosen, diags := chooseTypeSpelling(dc, loweringState, header.GetSchema(), header.GetContent(), header.GetRootNode(), hdecl, "header", "ir.Property") // The schema is named after the key the header is declared under, never // this mount's, and lowered in its declaration's document (dc), so every // response mounting one header builds the same nodes beneath it, in // whichever order they lower (GitHub #433). - headerType, headerDiags := schema.CarriedRef(elected.ctx.Ctx, loweringState.types, schema.TopLevelDepth, serviceContext.Statements().Of(elected.js), elected.pointer) + headerType, headerDiags := schema.CarriedRef(chosen.ctx.Ctx, loweringState.types, schema.TopLevelDepth, serviceContext.Statements().Of(chosen.js), chosen.pointer) diags = append(diags, headerDiags...) property := ir.Property{ ID: serviceContext.IDs().Property(hptr), Name: ir.NamingFor(name), WireName: name, Type: headerType, - Required: h.GetRequired(), + Required: header.GetRequired(), Provenance: serviceContext.Place().At(hptr), } - if elected.mediaType != "" { + if chosen.mediaType != "" { // The media type a content-style header serializes its value in, which is // what ir.Encoding.MediaType holds. Nothing else on this path writes // Property.Encoding, so the content spelling loses nothing the schema // spelling keeps. - property.Encoding = &ir.Encoding{MediaType: elected.mediaType} + property.Encoding = &ir.Encoding{MediaType: chosen.mediaType} } // The property holds what the schema writes beside what the header object // writes, so the schema's entries are kept beneath its scope: the two can // spell one key. - diags = append(diags, schema.FillPropertyDetail(elected.ctx.Ctx, loweringState.types, &property, serviceContext.Statements().Of(elected.js), elected.pointer)...) + diags = append(diags, schema.FillPropertyDetail(chosen.ctx.Ctx, loweringState.types, &property, serviceContext.Statements().Of(chosen.js), chosen.pointer)...) promotion.DropContained(dc.Promoter(), &property.Unmodeled) - property.Unmodeled = annotation.MergeUnmodeled(annotation.Under(elected.schemaScope(), property.Unmodeled), elected.unmodeled) - diags = append(diags, applyHeaderAnnotations(dc, &property, h, hdecl, elected.examples)...) - fallbackReferent := dc.Promoter().WithOwnCarriedState(schema.FallbackKeysForCarrier(dc.Ctx, serviceContext.Statements().Of(elected.js), property.Type, elected.pointer), property.Unmodeled, - elected.carries...) - own := promotion.Carried(dc.Promoter(), property.Unmodeled, elected.carries...) + property.Unmodeled = annotation.MergeUnmodeled(annotation.Under(chosen.schemaScope(), property.Unmodeled), chosen.unmodeled) + diags = append(diags, applyHeaderAnnotations(dc, &property, header, hdecl, chosen.examples)...) + fallbackReferent := dc.Promoter().WithOwnCarriedState(schema.FallbackKeysForCarrier(dc.Ctx, serviceContext.Statements().Of(chosen.js), property.Type, chosen.pointer), property.Unmodeled, + chosen.carries...) + own := promotion.Carried(dc.Promoter(), property.Unmodeled, chosen.carries...) diags = append(diags, schema.PromoteUse(dc.Ctx, fallbackReferent, own, &property.Deprecation, &property.Secret, &property.Provenance)...) - diags = append(diags, promoteShadowed(dc, property.Unmodeled, elected.carries...)...) - lowered := ir.Header{Property: property, Explode: h.Explode} - if h.Style != nil { - lowered.Style = string(*h.Style) + diags = append(diags, promoteShadowed(dc, property.Unmodeled, chosen.carries...)...) + lowered := ir.Header{Property: property, Explode: header.Explode} + if header.Style != nil { + lowered.Style = string(*header.Style) } return lowered, diags } @@ -101,21 +102,23 @@ func lowerHeader(serviceContext, dc service.Ctx, loweringState operationLowering // applyHeaderAnnotations overlays the annotations the header object writes on // itself onto property, after its schema's. A header carries both, and the // header's own are the more specific of the two — they describe this header -// rather than the type it happens to be. media is what its elected content +// rather than the type it happens to be. media is what its chosen content // entry wrote. -func applyHeaderAnnotations(serviceContext service.Ctx, property *ir.Property, h *soa.Header, hdecl jsontext.Pointer, media []ir.Example) []ir.Diagnostic { - if d := h.GetDescription(); d != "" { - property.Docs.Description = d +func applyHeaderAnnotations(serviceContext service.Ctx, property *ir.Property, header *soa.Header, hdecl jsontext.Pointer, media []ir.Example) []ir.Diagnostic { + if description := header.GetDescription(); description != "" { + property.Docs.Description = description } - if h.GetDeprecated() { + if header.GetDeprecated() { property.Deprecation = &ir.Deprecation{} } - own, diags := exampleList(serviceContext, h.GetExample(), h.GetExamples(), hdecl) - if ex := positionExamples(own, media); len(ex) > 0 { + own, diags := exampleList(serviceContext, header.GetExample(), header.GetExamples(), hdecl) + // The examples a position writes and its media type writes replace the + // schema's, neither replacing the other (GitHub #611). + if ex := slices.Concat(own, media); len(ex) > 0 { property.Examples = ex } - hExt, extDiags := annotation.ExtensionsFrom(h.GetExtensions(), serviceContext.Place(), hdecl) + hExt, extDiags := annotation.ExtensionsFrom(header.GetExtensions(), serviceContext.Place(), hdecl) diags = append(diags, extDiags...) property.Unmodeled = annotation.MergeUnmodeled(property.Unmodeled, hExt) - return append(diags, annotation.UnknownKeysIn(&property.Unmodeled, h, serviceContext.Place(), hdecl)...) + return append(diags, annotation.UnknownKeysIn(&property.Unmodeled, header, serviceContext.Place(), hdecl)...) } diff --git a/compilers/openapi/internal/operation/helpers_internal_test.go b/compilers/openapi/internal/operation/helpers_internal_test.go index fd058b95f..dfa315c10 100644 --- a/compilers/openapi/internal/operation/helpers_internal_test.go +++ b/compilers/openapi/internal/operation/helpers_internal_test.go @@ -48,9 +48,10 @@ func lowererOver(ctx service.Ctx) *lowerer { } } -// serviceWalk stands in for the walk LowerService hands the lowerings beneath it: -// l's registry, and a kept set and links of its own. It holds no operationId -// claims, servers or schemes: no lowering a test here hands it to reads them. +// serviceWalk takes the place of the walk LowerService hands the lowerings +// beneath it: l's registry, and a kept set and links of its own. It holds no +// operationId claims, servers or schemes: no lowering a test here hands it to +// reads them. func (l *lowerer) serviceWalk() operationLoweringState { return operationLoweringState{types: l.types, kept: newKeptOnce(), links: &Links{}} } @@ -99,16 +100,16 @@ func lowerServiceSpec(t *testing.T, src string) (ir.Service, []ir.Diagnostic) { // diagnostics it returns are load's, and lowererValue holds the rest. func lowerBeforeLinks(t *testing.T, src string) (*lowerer, Lowered, ir.TypeRegistry, []ir.Diagnostic) { t.Helper() - lowererValue, loadDiags := loweredFor(t, src) - lowererValue.diags.AppendAll(schema.LowerComponentSchemas(t.Context(), lowererValue.ctx.Ctx, lowererValue.types, componentStatements(lowererValue.ctx))) - declared, authDiags := auth.LowerSecuritySchemes(lowererValue.ctx) - lowererValue.diags.AppendAll(authDiags) + lowerer, loadDiags := loweredFor(t, src) + lowerer.diags.AppendAll(schema.LowerComponentSchemas(t.Context(), lowerer.ctx.Ctx, lowerer.types, componentStatements(lowerer.ctx))) + declared, authDiags := auth.LowerSecuritySchemes(lowerer.ctx) + lowerer.diags.AppendAll(authDiags) - lowered, svcDiags := LowerService(t.Context(), lowererValue.ctx, lowererValue.types, declared) - lowererValue.diags.AppendAll(svcDiags) - reg, finished := lowererValue.types.Finish(t.Context()) - lowererValue.diags.AppendAll(finished) - return lowererValue, lowered, reg, loadDiags + lowered, svcDiags := LowerService(t.Context(), lowerer.ctx, lowerer.types, declared) + lowerer.diags.AppendAll(svcDiags) + reg, finished := lowerer.types.Finish(t.Context()) + lowerer.diags.AppendAll(finished) + return lowerer, lowered, reg, loadDiags } // componentStatements yields each component schema of serviceContext's document diff --git a/compilers/openapi/internal/operation/keptonce.go b/compilers/openapi/internal/operation/keptonce.go index 41df37baf..a886c23f2 100644 --- a/compilers/openapi/internal/operation/keptonce.go +++ b/compilers/openapi/internal/operation/keptonce.go @@ -10,8 +10,9 @@ import ( ) // keptOnce is what the service walk keeps for the Document rather than a node: -// the declarations read so far, by coordinate, and the entries those reads kept. -// LowerService returns the entries once every lowering of the walk has returned. +// the declarations read so far, by coordinate, and the Unmodeled entries those +// reads kept. LowerService returns the Unmodeled entries once every lowering of +// the walk has returned. type keptOnce struct { read map[string]bool entries ir.Unmodeled diff --git a/compilers/openapi/internal/operation/linkresolve.go b/compilers/openapi/internal/operation/linkresolve.go index 2c8de2aeb..4a867ed61 100644 --- a/compilers/openapi/internal/operation/linkresolve.go +++ b/compilers/openapi/internal/operation/linkresolve.go @@ -41,11 +41,11 @@ func (l *Links) Resolve(serviceContext service.Ctx, compiledDocumentView *compil return diags } -// place lowers pendingLinkValue onto the response of from it sits on, or keeps +// place lowers pendingLink onto the response of from it sits on, or keeps // it verbatim there. -func place(ix operationIndex, compiledDocumentView *compileddoc.CompiledDocumentView, srv *servers.Registry, from *ir.Operation, pendingLinkValue *pendingLink) []ir.Diagnostic { - linkDraft := &pendingLinkValue.draft - at := pendingLinkValue.slot.in(from) +func place(ix operationIndex, compiledDocumentView *compileddoc.CompiledDocumentView, srv *servers.Registry, from *ir.Operation, pendingLink *pendingLink) []ir.Diagnostic { + linkDraft := &pendingLink.draft + at := pendingLink.slot.in(from) link, failed := resolveLink(ix, compiledDocumentView, from, at, linkDraft) if failed != nil { kept, keepDiags := linkDraft.keep(at.unmodeled) @@ -112,19 +112,19 @@ func untyped(format string, args ...any) *linkFailure { return &linkFailure{code: diag.UntypedLink, severity: ir.SeverityInfo, reason: fmt.Sprintf(format, args...)} } -// resolveLink resolves linkDraftValue, which a response of from carries, at. -func resolveLink(ix operationIndex, compiledDocumentView *compileddoc.CompiledDocumentView, from *ir.Operation, at responseView, linkDraftValue *linkDraft) (ir.OperationLink, *linkFailure) { - target, failed := ix.target(linkDraftValue) +// resolveLink resolves linkDraft, which a response of from carries, at. +func resolveLink(ix operationIndex, compiledDocumentView *compileddoc.CompiledDocumentView, from *ir.Operation, at responseView, linkDraft *linkDraft) (ir.OperationLink, *linkFailure) { + target, failed := ix.target(linkDraft) if failed != nil { return ir.OperationLink{}, failed } link := ir.OperationLink{ - Name: ir.NamingFor(linkDraftValue.name), Operation: target.ID, Docs: linkDraftValue.docs, - Provenance: linkDraftValue.c.Place().At(linkDraftValue.ptr), Unmodeled: linkDraftValue.extra, + Name: ir.NamingFor(linkDraft.name), Operation: target.ID, Docs: linkDraft.docs, + Provenance: linkDraft.c.Place().At(linkDraft.ptr), Unmodeled: linkDraft.extra, } ex := exchange{w: compiledDocumentView, from: from, at: at} given := map[ir.ParameterID]string{} - for _, dp := range linkDraftValue.params { + for _, dp := range linkDraft.params { id, failed := targetParam(compiledDocumentView, target, dp.key) if failed != nil { return ir.OperationLink{}, failed @@ -139,8 +139,8 @@ func resolveLink(ix operationIndex, compiledDocumentView *compileddoc.CompiledDo } link.Params = append(link.Params, ir.LinkParam{Param: id, Value: value}) } - if linkDraftValue.body != nil { - body, failed := ex.value(linkDraftValue.body) + if linkDraft.body != nil { + body, failed := ex.value(linkDraft.body) if failed != nil { return ir.OperationLink{}, failed } @@ -181,32 +181,32 @@ func (ix operationIndex) add(operation *ir.Operation, source int) { } } -// target returns the operation linkDraftValue leads to, which it names by +// target returns the operation linkDraft leads to, which it names by // operationId or by operationRef, never both. -func (ix operationIndex) target(linkDraftValue *linkDraft) (*ir.Operation, *linkFailure) { +func (ix operationIndex) target(linkDraft *linkDraft) (*ir.Operation, *linkFailure) { switch { - case linkDraftValue.operationID != nil && linkDraftValue.operationRef != nil: + case linkDraft.operationID != nil && linkDraft.operationRef != nil: return nil, invalid("names its operation by both operationId and operationRef") - case linkDraftValue.operationID != nil: - return one(ix.byName[*linkDraftValue.operationID], "operationId", *linkDraftValue.operationID) - case linkDraftValue.operationRef != nil: - return ix.byReference(linkDraftValue) + case linkDraft.operationID != nil: + return one(ix.byName[*linkDraft.operationID], "operationId", *linkDraft.operationID) + case linkDraft.operationRef != nil: + return ix.byReference(linkDraft) default: return nil, invalid("names no operation") } } -// byReference returns the operation linkDraftValue's operationRef names: the +// byReference returns the operation linkDraft's operationRef names: the // one mounted at the position it points to, else the one declared there. A // reference whose fragment is no JSON pointer, a bare `#` among them, names no // operation; one into another document names an operation this compile does not // lower; and a declaration mounted more than once names several. -func (ix operationIndex) byReference(linkDraftValue *linkDraft) (*ir.Operation, *linkFailure) { - ref := *linkDraftValue.operationRef +func (ix operationIndex) byReference(linkDraft *linkDraft) (*ir.Operation, *linkFailure) { + ref := *linkDraft.operationRef if _, ok := componentlookup.FragmentPointer(ref); !ok { return nil, invalid("names operationRef %q, which is no JSON pointer to an operation", ref) } - pointer, internal := linkDraftValue.c.RefScope().InternalPointer(ref) + pointer, internal := linkDraft.c.RefScope().InternalPointer(ref) if !internal { return nil, untyped("names operation %q, which is not one this document declares", ref) } diff --git a/compilers/openapi/internal/operation/links.go b/compilers/openapi/internal/operation/links.go index 2f521bb44..2d65560d3 100644 --- a/compilers/openapi/internal/operation/links.go +++ b/compilers/openapi/internal/operation/links.go @@ -79,13 +79,13 @@ type draftParam struct { value *yaml.Node } -// draftLinks drafts each link the response r, declared at rptr in serviceContext's +// draftLinks drafts each link response, declared at rptr in serviceContext's // document, names. A $ref the bindings could not follow is the load phase's // finding, and drafts nothing. The summary and description written beside a link's $ref // describe that use of it, so they fold over the declaration's docs // (docs/compilers/openapi.md#reference-object-siblings). -func draftLinks(serviceContext service.Ctx, r *soa.Response, rptr jsontext.Pointer) ([]linkDraft, []ir.Diagnostic) { - links := r.GetLinks() +func draftLinks(serviceContext service.Ctx, response *soa.Response, rptr jsontext.Pointer) ([]linkDraft, []ir.Diagnostic) { + links := response.GetLinks() if links == nil { return nil, nil } @@ -93,11 +93,11 @@ func draftLinks(serviceContext service.Ctx, r *soa.Response, rptr jsontext.Point var diags []ir.Diagnostic for name, rl := range links.All() { use := rptr + ids.Ptr("links", name) - l, lc, lptr := service.Declared[soa.Link](serviceContext, rl, use) - if l == nil { + link, lc, lptr := service.Declared[soa.Link](serviceContext, rl, use) + if link == nil { continue } - linkDraft, draftDiags := draftLink(lc, l, lptr, name) + linkDraft, draftDiags := draftLink(lc, link, lptr, name) linkDraft.docs = componentlookup.UseDocs[soa.Link](serviceContext.Bindings(), rl, linkDraft.docs) beside, besideDiags := service.Beside[soa.Link](serviceContext, rl, use, true) linkDraft.extra = annotation.MergeUnmodeled(linkDraft.extra, beside) @@ -109,23 +109,23 @@ func draftLinks(serviceContext service.Ctx, r *soa.Response, rptr jsontext.Point return drafts, diags } -// draftLink drafts the link l named name, declared at ptr in serviceContext's -// document. It holds l whole, as it resolved, for keep. -func draftLink(serviceContext service.Ctx, l *soa.Link, ptr jsontext.Pointer, name string) (linkDraft, []ir.Diagnostic) { - linkDraftValue := linkDraft{ +// draftLink drafts link, named name, declared at ptr in serviceContext's +// document. It holds link whole, as it resolved, for keep. +func draftLink(serviceContext service.Ctx, link *soa.Link, ptr jsontext.Pointer, name string) (linkDraft, []ir.Diagnostic) { + linkDraft := linkDraft{ c: serviceContext, ptr: ptr, name: name, - operationID: l.OperationID, operationRef: l.OperationRef, - body: l.GetRequestBody(), server: l.GetServer(), - docs: ir.Docs{Description: l.GetDescription()}, node: l.GetRootNode(), + operationID: link.OperationID, operationRef: link.OperationRef, + body: link.GetRequestBody(), server: link.GetServer(), + docs: ir.Docs{Description: link.GetDescription()}, node: link.GetRootNode(), } - if params := l.GetParameters(); params != nil { + if params := link.GetParameters(); params != nil { for key, value := range params.All() { - linkDraftValue.params = append(linkDraftValue.params, draftParam{key: key, value: value}) + linkDraft.params = append(linkDraft.params, draftParam{key: key, value: value}) } } - extra, diags := annotation.ExtensionsFrom(l.GetExtensions(), serviceContext.Place(), ptr) - linkDraftValue.extra = extra - return linkDraftValue, append(diags, annotation.UnknownKeysIn(&linkDraftValue.extra, l, serviceContext.Place(), ptr)...) + extra, diags := annotation.ExtensionsFrom(link.GetExtensions(), serviceContext.Place(), ptr) + linkDraft.extra = extra + return linkDraft, append(diags, annotation.UnknownKeysIn(&linkDraft.extra, link, serviceContext.Place(), ptr)...) } // keep records d verbatim in unmodeled, under openapi:links/, reporting @@ -134,6 +134,6 @@ func draftLink(serviceContext service.Ctx, l *soa.Link, ptr jsontext.Pointer, na // one included; one that lowers is not converted at all, so nothing about its // verbatim form is reported. func (d *linkDraft) keep(unmodeled *ir.Unmodeled) (bool, []ir.Diagnostic) { - return annotation.PreserveNodeInto(unmodeled, "openapi:"+ids.Scope("links", d.name), + return annotation.KeepNodeInto(unmodeled, "openapi:"+ids.Scope("links", d.name), d.node, ir.ReasonNoIRHome, d.c.Place().At(d.ptr)) } diff --git a/compilers/openapi/internal/operation/links_alias_test.go b/compilers/openapi/internal/operation/links_alias_test.go index d1649ae3e..63883b2f8 100644 --- a/compilers/openapi/internal/operation/links_alias_test.go +++ b/compilers/openapi/internal/operation/links_alias_test.go @@ -17,7 +17,7 @@ import ( // aliasLinkSpec is a document whose operation listPets answers with the schema // body, and carries a link whose cursor reads the body's next_cursor member. // The schemas are written as schemas, so a test can put an alias before or -// after the model it stands for. +// after the model it names. func aliasLinkSpec(body, schemas string) string { return `openapi: 3.1.0 info: {title: T, version: "1"} diff --git a/compilers/openapi/internal/operation/links_internal_test.go b/compilers/openapi/internal/operation/links_internal_test.go index 8b0f26bfe..5d5b3b38d 100644 --- a/compilers/openapi/internal/operation/links_internal_test.go +++ b/compilers/openapi/internal/operation/links_internal_test.go @@ -58,9 +58,9 @@ func TestIndexOperations_StopsAtTheGroupDepthBound(t *testing.T) { // membersSpec is a document whose link reads, through n steps along member a, // a member p0 of a model declaring n members besides a, from a body of // contents media types, each holding that model. -func membersSpec(n, contents int) string { +func membersSpec(count, contents int) string { var properties, pointer, media strings.Builder - for i := range n { + for i := range count { fmt.Fprintf(&properties, " p%d: {type: string}\n", i) pointer.WriteString("/a") } @@ -92,9 +92,9 @@ components: // response headers, and whose link gives each parameter, at the operation // itself, the value from names: the same request parameter, or the header of // its index. -func paramsSpec(n int, from string) string { +func paramsSpec(count int, from string) string { var params, headers, values strings.Builder - for i := range n { + for i := range count { fmt.Fprintf(¶ms, " - {name: p%d, in: query, schema: {type: string}}\n", i) fmt.Fprintf(&headers, " h%d: {schema: {type: string}}\n", i) fmt.Fprintf(&values, " p%d: '%s%d'\n", i, from, i) @@ -120,9 +120,9 @@ paths: // linksSpec is a document whose operation declares n query parameters and n // response headers, and whose body is a model of n members, and whose n links // each read one entry of each list: every link reads the same three lists. -func linksSpec(n int) string { +func linksSpec(count int) string { var params, headers, properties, links strings.Builder - for i := range n { + for i := range count { fmt.Fprintf(¶ms, " - {name: p%d, in: query, schema: {type: string}}\n", i) fmt.Fprintf(&headers, " h%d: {schema: {type: string}}\n", i) fmt.Fprintf(&properties, " m%d: {type: string}\n", i) @@ -156,10 +156,10 @@ paths: // operation's parameters, and a response's headers, and the shape whose n links // each read an entry of all three. var linkSpecs = map[string]func(n int) string{ - "members": func(n int) string { return membersSpec(n, 1) }, - "contents": func(n int) string { return membersSpec(n, n) }, - "params": func(n int) string { return paramsSpec(n, "$request.query.p") }, - "headers": func(n int) string { return paramsSpec(n, "$response.header.h") }, + "members": func(count int) string { return membersSpec(count, 1) }, + "contents": func(count int) string { return membersSpec(count, count) }, + "params": func(count int) string { return paramsSpec(count, "$request.query.p") }, + "headers": func(count int) string { return paramsSpec(count, "$response.header.h") }, "links": linksSpec, } diff --git a/compilers/openapi/internal/operation/links_test.go b/compilers/openapi/internal/operation/links_test.go index b20a42512..6e60ac56b 100644 --- a/compilers/openapi/internal/operation/links_test.go +++ b/compilers/openapi/internal/operation/links_test.go @@ -349,7 +349,7 @@ func TestLinks_AHeaderIsReadOffItsOwnResponse(t *testing.T) { // TestLinks_UseSiteDocsFoldOverTheDeclaration pins that the summary and // description written beside a link's $ref describe that use of it, each -// overriding the declaration's field it names and leaving the other standing. +// overriding the declaration's field it names and leaving the other in place. func TestLinks_UseSiteDocsFoldOverTheDeclaration(t *testing.T) { t.Parallel() doc, diags := parseFull(t, `openapi: 3.1.0 diff --git a/compilers/openapi/internal/operation/linkvalues.go b/compilers/openapi/internal/operation/linkvalues.go index b085aa123..1bfcaa2f1 100644 --- a/compilers/openapi/internal/operation/linkvalues.go +++ b/compilers/openapi/internal/operation/linkvalues.go @@ -26,35 +26,35 @@ type exchange struct { // written alone or anywhere within a list or an object: a constant holding one // would pass on its braces as written. func (ex exchange) value(node *yaml.Node) (ir.LinkValue, *linkFailure) { - irValue, err := value.FromNode(node) + parsed, err := value.FromNode(node) if err != nil { return ir.LinkValue{}, untyped("passes a value the IR has no constant for: %v", err) } - if irValue.Kind != ir.ValueString { - if s, ok := substitutedString(&irValue); ok { - return ir.LinkValue{}, untyped("passes a value holding %q, a string an expression is substituted into", s) + if parsed.Kind != ir.ValueString { + if text, ok := substitutedString(&parsed); ok { + return ir.LinkValue{}, untyped("passes a value holding %q, a string an expression is substituted into", text) } - return ir.LinkValue{Kind: ir.LinkConstant, Constant: &irValue}, nil + return ir.LinkValue{Kind: ir.LinkConstant, Constant: &parsed}, nil } - expression, isExpression, err := runtimeexpr.Parse(irValue.String) + expression, isExpression, err := runtimeexpr.Parse(parsed.String) switch { case err != nil: - return ir.LinkValue{}, invalid("passes %q, which breaks the runtime expression grammar", irValue.String) + return ir.LinkValue{}, invalid("passes %q, which breaks the runtime expression grammar", parsed.String) case isExpression: return ex.read(expression) - case runtimeexpr.Embeds(irValue.String): - return ir.LinkValue{}, untyped("passes %q, a string an expression is substituted into", irValue.String) + case runtimeexpr.Embeds(parsed.String): + return ir.LinkValue{}, untyped("passes %q, a string an expression is substituted into", parsed.String) default: - return ir.LinkValue{Kind: ir.LinkConstant, Constant: &irValue}, nil + return ir.LinkValue{Kind: ir.LinkConstant, Constant: &parsed}, nil } } -// substitutedString returns the first string within irValue, in source order, +// substitutedString returns the first string within linkValue, in source order, // that an expression is substituted into, and false for none. It walks with a -// stack of its own rather than recursing, so irValue's depth, which +// stack of its own rather than recursing, so linkValue's depth, which // value.FromNode bounds, bounds no call stack here. -func substitutedString(irValue *ir.Value) (string, bool) { - stack := []*ir.Value{irValue} +func substitutedString(linkValue *ir.Value) (string, bool) { + stack := []*ir.Value{linkValue} for len(stack) > 0 { top := stack[len(stack)-1] stack = stack[:len(stack)-1] diff --git a/compilers/openapi/internal/operation/mediatyperefs_test.go b/compilers/openapi/internal/operation/mediatyperefs_test.go index 2b5108dde..6291fb652 100644 --- a/compilers/openapi/internal/operation/mediatyperefs_test.go +++ b/compilers/openapi/internal/operation/mediatyperefs_test.go @@ -138,16 +138,16 @@ components: openapitest.RequireNoErrorDiags(t, backDiags) assert.Empty(t, cmp.Diff(forward.Types, backward.Types), "the types must not follow the declaration order") - td, ok := forward.Types[ir.TypeID(tc.id)] + typeDef, ok := forward.Types[ir.TypeID(tc.id)] require.True(t, ok, "types: %v", slices.Collect(maps.Keys(forward.Types))) - assert.Equal(t, tc.hint, td.Common().Name.Hint) + assert.Equal(t, tc.hint, typeDef.Common().Name.Hint) post, get := openapitest.FindOperation(t, forward, "postA"), openapitest.FindOperation(t, forward, "getB") for _, target := range []ir.TypeID{post.Request.Contents[0].Type.Target, get.Responses[0].Payload.Contents[0].Type.Target, get.Params[0].Type.Target, get.Responses[0].Headers[0].Type.Target} { assert.Equal(t, ir.TypeID(tc.id), target) } - model, ok := td.(*ir.Model) + model, ok := typeDef.(*ir.Model) require.True(t, ok) require.Len(t, model.Properties, 1) assert.NotEqual(t, ir.PrimitiveTypeID(ir.PrimitiveAny), model.Properties[0].Type.Target, @@ -315,7 +315,7 @@ components: // TestMediaTypeRef_AnUnsetSiblingLeavesTheDeclarationsDocs pins a description // written empty or null beside a content entry's $ref: it reads as unset, as -// the fold reads it, so the declaration's own description stands, in a body's +// the fold reads it, so the declaration's own description remains, in a body's // Content.Docs and in what a parameter keeps alike. func TestMediaTypeRef_AnUnsetSiblingLeavesTheDeclarationsDocs(t *testing.T) { t.Parallel() @@ -516,16 +516,16 @@ components: A2: {$ref: '#/components/mediaTypes/M', x-a: a2} M: {schema: {type: string}, x-a: own} `)) - a := operationTree(t, doc, "a") + operationTree := operationTree(t, doc, "a") for _, payload := range []struct{ name, at string }{ {"request", "/paths/~1a/post/requestBody/content/application~1json"}, {"ok", "/paths/~1a/post/responses/200/content/application~1json"}, {"default", "/paths/~1a/post/responses/default/content/application~1json"}, } { content := map[string]any{ - "request": valueAtPath(a, "request", "contents", "0"), - "ok": valueAtPath(a, "responses", "0", "payload", "contents", "0"), - "default": valueAtPath(a, "default", "payload", "contents", "0"), + "request": valueAtPath(operationTree, "request", "contents", "0"), + "ok": valueAtPath(operationTree, "responses", "0", "payload", "contents", "0"), + "default": valueAtPath(operationTree, "default", "payload", "contents", "0"), }[payload.name] assert.Equal(t, "s", valueAtPath(content, "docs", "summary"), payload.name) assert.Empty(t, cmp.Diff(map[string]string{ diff --git a/compilers/openapi/internal/operation/multipart.go b/compilers/openapi/internal/operation/multipart.go index dffee0002..925206208 100644 --- a/compilers/openapi/internal/operation/multipart.go +++ b/compilers/openapi/internal/operation/multipart.go @@ -102,8 +102,8 @@ func unknownNestedKeys(serviceContext service.Ctx, part bodyPart, entry *yaml.No } declared := map[string]bool{} for _, js := range part.schemas { - if s := schemaOf(serviceContext.Bindings(), js); isArraySchema(s) { - js = s.GetItems() + if oasSchema := schemaOf(serviceContext.Bindings(), js); isArraySchema(oasSchema) { + js = oasSchema.GetItems() } partWalk := walkBodyParts(serviceContext.Ctx, js) if !partWalk.decidesKeys() { @@ -142,7 +142,7 @@ const ( ) // keepUnkeyedEncodings keeps whole each entry of media's encoding map whose key -// names none of the parts partWalkValue found, under Unmodeled at +// names none of the parts partWalk found, under Unmodeled at // annotation.EntryKey("encoding", key), with one info each, which why completes // (docs/compilers/openapi.md#multipart-encoding). Where the walk decides the // key names no property it also warns (unknownEncodingKey), save outside form @@ -150,9 +150,9 @@ const ( // with no parts, has no effect, so is out of scope; one the walk cannot // decide, as a catch-all may take it, has no IR home. An entry that is no // object, which load reports, is skipped. -func keepUnkeyedEncodings(serviceContext service.Ctx, media *soa.MediaType, mediaPtr jsontext.Pointer, partWalkValue partWalk, why string) (ir.Unmodeled, []ir.Diagnostic) { - walked := make(map[string]struct{}, len(partWalkValue.parts)) - for _, part := range partWalkValue.parts { +func keepUnkeyedEncodings(serviceContext service.Ctx, media *soa.MediaType, mediaPtr jsontext.Pointer, partWalk partWalk, why string) (ir.Unmodeled, []ir.Diagnostic) { + walked := make(map[string]struct{}, len(partWalk.parts)) + for _, part := range partWalk.parts { walked[part.name] = struct{}{} } var kept ir.Unmodeled @@ -167,12 +167,12 @@ func keepUnkeyedEncodings(serviceContext service.Ctx, media *soa.MediaType, medi // may take has no IR home yet. Under a media type that is neither // multipart nor form, load reports the whole field as having no effect. reason := ir.ReasonNoIRHome - if partWalkValue.decidesKeys() { + if partWalk.decidesKeys() { reason = ir.ReasonOutOfScope } written, keepDiags := keepEntry(serviceContext, &kept, name, enc.GetRootNode(), at, why, reason) diags = append(diags, keepDiags...) - if written && partWalkValue.decidesKeys() && why != unkeyedOtherEntry { + if written && partWalk.decidesKeys() && why != unkeyedOtherEntry { diags = append(diags, unknownEncodingKey(serviceContext, name, "body", at)) } } @@ -188,12 +188,12 @@ func keepUnkeyedEncodings(serviceContext service.Ctx, media *soa.MediaType, medi func keepEntry(serviceContext service.Ctx, unmodeled *ir.Unmodeled, name string, entry *yaml.Node, at jsontext.Pointer, why string, reason ir.UnmodeledReason, ) (written bool, diags []ir.Diagnostic) { - written, diags = annotation.PreserveNodeInto(unmodeled, annotation.EntryKey("encoding", name), entry, + written, diags = annotation.KeepNodeInto(unmodeled, annotation.EntryKey("encoding", name), entry, reason, serviceContext.Place().At(at)) if !written { return false, diags } - schema.RecordReached(serviceContext.Ctx, at) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, at)...) return true, append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, "encoding entry %q %s, so Content.Encoding has no key for it; kept verbatim under Unmodeled", name, why)) } @@ -249,12 +249,9 @@ const unkeyedPartEntry = "names a part the form body's schema declares, but the // Settle keys each part's encoding, writing no node of reg. It reads each // property a part names as the merge settled it, which Finish has done by then: // a fold is a completion (compile.Types.QueueSettlementBeforeDeferredOnes). -func (k partKeys) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { - node := func(id ir.TypeID) (ir.TypeDef, bool) { - td, ok := reg[id] - return td, ok - } - members, complete, unread := partMembers(reg, k.body) +func (k partKeys) Settle(_ context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + chains := runChainsOf(k.c, reg, aliases) + members, complete, unread := partMembers(chains, k.body) var diags []ir.Diagnostic if !complete { diags = append(diags, k.c.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, k.schema, @@ -274,37 +271,37 @@ func (k partKeys) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic maps.Copy(k.kept, keyedPart.unmodeled) schemas := declarationSchemas(k.c, keyedPart.part, decls) for _, property := range decls { - if pe := k.declared(node, keyedPart, bodyPart{name: keyedPart.part.name, schemas: schemas[property.ID]}, property); !partEncodingEmpty(pe) { + if pe := k.declared(chains, keyedPart, bodyPart{name: keyedPart.part.name, schemas: schemas[property.ID]}, property); !partEncodingEmpty(pe) { k.out[property.ID] = pe } } } - k.settleCatchAlls(reg, node) - return append(diags, k.partless(node)...) + k.settleCatchAlls(reg, chains) + return append(diags, k.partless(chains)...) } // partless reports a multipart/form-data or url-encoded body whose type, read -// through its unions, stands for no model, no map, no object value and not the -// top type, so it names no part to send (docs/compilers/openapi.md#multipart-encoding). A -// union read past its bound, or a type reaching no node, which load reports, -// is not judged. -func (k partKeys) partless(node func(ir.TypeID) (ir.TypeDef, bool)) []ir.Diagnostic { +// through its unions, names no model, no map, no object value and not the top +// type, so it names no part to send +// (docs/compilers/openapi.md#multipart-encoding). A union read past its bound, +// or a type reaching no node, which load reports, is not judged. +func (k partKeys) partless(chains *runChains) []ir.Diagnostic { if k.mediaType != "multipart/form-data" && k.mediaType != "application/x-www-form-urlencoded" { return nil } - holders, complete := memberHolders(node, k.body) - if !complete || slices.ContainsFunc(holders, func(typeID ir.TypeID) bool { return mayHoldParts(bodyNode(node, typeID)) }) { + holders, complete := memberHolders(chains, k.body) + if !complete || slices.ContainsFunc(holders, func(typeID ir.TypeID) bool { return mayHoldParts(bodyNode(chains, typeID)) }) { return nil } return []ir.Diagnostic{k.c.DiagAt(ir.SeverityWarning, diag.PartlessFormBody, k.schema, "form body's schema declares no object, so it names no part to send; lowered as declared")} } -// mayHoldParts reports whether td, a form body's type or a variant of it, may +// mayHoldParts reports whether typeDef, a form body's type or a variant of it, may // hold a part: a model, a map, an object value, whose members name its parts, // or the top type, or no node, which another finding reports. -func mayHoldParts(td ir.TypeDef) bool { - switch t := td.(type) { +func mayHoldParts(typeDef ir.TypeDef) bool { + switch t := typeDef.(type) { case *ir.Model, *ir.MapT, nil: return true case *ir.Literal: @@ -316,21 +313,21 @@ func mayHoldParts(td ir.TypeDef) bool { } } -// declared returns the encoding of keyedPartValue as property, one of the +// declared returns the encoding of keyedPart as property, one of the // declarations the body's type holds of its name, declares it: the entry // written, with the structural flags and the default content type read off // property and part, the schemas declaring it (declarationSchemas), so a part // two variants declare apart reads as each declares it. -func (k partKeys) declared(node func(ir.TypeID) (ir.TypeDef, bool), keyedPartValue keyedPart, part bodyPart, property *ir.Property) ir.PartEncoding { +func (k partKeys) declared(chains *runChains, keyedPart keyedPart, part bodyPart, property *ir.Property) ir.PartEncoding { one := []*ir.Property{property} multipart := isMultipart(k.mediaType) unions := partUnionsOf(k.c) - pe := partFlags(unions, node, k.c.Bindings(), one, part, keyedPartValue.encoding, multipart) - pe = readPartFile(k.c, part, keyedPartValue.encoding.ContentTypes, multipart).apply(pe) - if !keyedPartValue.defaulted { + pe := partFlags(unions, chains, k.c.Bindings(), one, part, keyedPart.encoding, multipart) + pe = readPartFile(k.c, part, keyedPart.encoding.ContentTypes, multipart).apply(pe) + if !keyedPart.defaulted { return pe } - return withDefaultContentType(unions, node, service.EncodingRules(k.c), property, readContentEncoding(k.c, part.schemas), pe) + return withDefaultContentType(unions, chains, service.EncodingRules(k.c), property, readContentEncoding(k.c, part.schemas), pe) } // declarationSchemas returns, for each of decls, the declarations the body's @@ -373,21 +370,21 @@ func declaredProperty(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Refer return dc.IDs().Property(at.Pointer), placed && read } -// keepWhole keeps the entry of keyedPartValue, a part the body's type holds no +// keepWhole keeps the entry of keyedPart, a part the body's type holds no // property for, whole, as keepUnkeyedEncodings keeps one naming no part. Where -// the entry cannot be kept, what its lowering kept of it stands instead, so +// the entry cannot be kept, what its lowering kept of it holds instead, so // what the lowering announced holds. A part with no entry keeps nothing: the // schema lowering kept the properties declaring it, which say what its flags // would. -func (k partKeys) keepWhole(keyedPartValue keyedPart) []ir.Diagnostic { - if keyedPartValue.entry == nil { +func (k partKeys) keepWhole(keyedPart keyedPart) []ir.Diagnostic { + if keyedPart.entry == nil { return nil } - discardPartHeaders(k.c.Ctx, keyedPartValue.encoding.Headers) + discardPartHeaders(k.c.Ctx, keyedPart.encoding.Headers) kept := k.kept // the map partEncodings made, which the content holds - written, diags := keepEntry(k.c, &kept, keyedPartValue.part.name, keyedPartValue.entry, keyedPartValue.at, unkeyedPartEntry, ir.ReasonNoIRHome) + written, diags := keepEntry(k.c, &kept, keyedPart.part.name, keyedPart.entry, keyedPart.at, unkeyedPartEntry, ir.ReasonNoIRHome) if !written { - maps.Copy(k.kept, keyedPartValue.unmodeled) + maps.Copy(k.kept, keyedPart.unmodeled) } return diags } @@ -396,9 +393,9 @@ func (k partKeys) keepWhole(keyedPartValue keyedPart) []ir.Diagnostic { // dropped when a form part's encoding is kept whole rather than keyed on // Content.Encoding. func discardPartHeaders(ctx lowering.Ctx, headers []ir.Header) { - for _, h := range headers { - schema.RecordDiscarded(ctx, h.Type.Target) - for _, entry := range h.Unmodeled { + for _, header := range headers { + schema.RecordDiscarded(ctx, header.Type.Target) + for _, entry := range header.Unmodeled { schema.RecordDiscardedSite(ctx, entry.Provenance) } } @@ -415,11 +412,11 @@ type bodyPart struct { } // maxPartRefHops bounds how many $ref targets and union branches bodyParts -// enters down a composition. Inline allOf wrappers are not counted: -// schema.FlattenedAllOf reads them, with the cap the lowering uses. A target is -// entered again only when a shorter path reaches it, so an allOf cycle (GitHub -// #642) costs one visit, and the bound is reported only for a target no path -// reaches within it. +// enters down a composition. Inline allOf wrappers are not counted: the +// statement flattens them (statement.Statement.Entries), with the cap the +// lowering uses. A target is entered again only when a shorter path reaches it, +// so an allOf cycle (GitHub #642) costs one visit, and the bound is reported +// only for a target no path reaches within it. const maxPartRefHops = 16 // partWalk is what bodyParts found, which bound cut it short, and what keeps @@ -464,11 +461,11 @@ type partVisits struct { catchAllValues *[]*oas3.JSONSchema[oas3.Referenceable] } -// markCapped records the allOf entries of b, an inline entry past the +// markCapped records the allOf entries of oasSchema, an inline entry past the // flattening depth, as targets the walk did not follow. -func (v partVisits) markCapped(b *oas3.Schema) { - for _, c := range b.GetAllOf() { - if cs := schemaOf(v.c.Bindings(), c); cs != nil { +func (v partVisits) markCapped(oasSchema *oas3.Schema) { + for _, entry := range oasSchema.GetAllOf() { + if cs := schemaOf(v.c.Bindings(), entry); cs != nil { v.capped[cs] = true } } @@ -479,7 +476,7 @@ func (v partVisits) markCapped(b *oas3.Schema) { func walkBodyParts(loweringContext lowering.Ctx, js *oas3.JSONSchema[oas3.Referenceable]) partWalk { open := false var catchAllValues []*oas3.JSONSchema[oas3.Referenceable] - partVisitsValue := partVisits{ + partVisits := partVisits{ c: loweringContext, entered: map[*oas3.Schema]int{}, cut: map[*oas3.Schema]bool{}, @@ -487,19 +484,19 @@ func walkBodyParts(loweringContext lowering.Ctx, js *oas3.JSONSchema[oas3.Refere open: &open, catchAllValues: &catchAllValues, } - partWalkValue := bodyParts(js, 0, partVisitsValue) - for s := range partVisitsValue.cut { - if _, ok := partVisitsValue.entered[s]; !ok { - partWalkValue.hopsSpent = true + partWalk := bodyParts(js, 0, partVisits) + for oasSchema := range partVisits.cut { + if _, ok := partVisits.entered[oasSchema]; !ok { + partWalk.hopsSpent = true } } - for s := range partVisitsValue.capped { - if _, ok := partVisitsValue.entered[s]; !ok { - partWalkValue.capped = true + for oasSchema := range partVisits.capped { + if _, ok := partVisits.entered[oasSchema]; !ok { + partWalk.capped = true } } - partWalkValue.open, partWalkValue.catchAllValues = open, catchAllValues - return partWalkValue + partWalk.open, partWalk.catchAllValues = open, catchAllValues + return partWalk } // bodyParts returns the parts a form body declares: the properties written on @@ -507,65 +504,67 @@ func walkBodyParts(loweringContext lowering.Ctx, js *oas3.JSONSchema[oas3.Refere // the schema or an inline allOf entry. A name declared more than once is one // part, at its first declaration's place, with every declaration kept // (dedupeParts). The allOf entries are the lowering's own -// (schema.FlattenedAllOf); a $ref branch and a union branch are followed here, -// up to maxPartRefHops. v records the fewest hops each target was entered at, -// so one met again by no shorter path yields no parts, and the bounds that cut -// the walk. -func bodyParts(js *oas3.JSONSchema[oas3.Referenceable], hops int, partVisitsValue partVisits) partWalk { - s := schemaOf(partVisitsValue.c.Bindings(), js) - if s == nil || hops > maxPartRefHops { - if s != nil { - partVisitsValue.cut[s] = true +// (statement.Statement.Entries); a $ref branch and a union branch are followed +// here, up to maxPartRefHops. partVisits records the fewest hops each target +// was entered at, so one met again by no shorter path yields no parts, and the +// bounds that cut the walk. +func bodyParts(js *oas3.JSONSchema[oas3.Referenceable], hops int, partVisits partVisits) partWalk { + oasSchema := schemaOf(partVisits.c.Bindings(), js) + if oasSchema == nil || hops > maxPartRefHops { + if oasSchema != nil { + partVisits.cut[oasSchema] = true } return partWalk{} } - if prev, ok := partVisitsValue.entered[s]; ok && prev <= hops { + if prev, ok := partVisits.entered[oasSchema]; ok && prev <= hops { return partWalk{} } - partVisitsValue.entered[s] = hops - partVisitsValue.note(js, s) - partWalkValue := partWalk{parts: propertyParts(s)} - branches := []*oas3.Schema{s} - for _, br := range schema.FlattenedAllOf(partVisitsValue.c, statementOf(partVisitsValue.c, js)) { - if br.Ref { - partWalkValue.parts = append(partWalkValue.parts, bodyParts(statement.ParsedAt(br.Schema), hops+1, partVisitsValue).parts...) + partVisits.entered[oasSchema] = hops + partVisits.note(js, oasSchema) + partWalk := partWalk{parts: propertyParts(oasSchema)} + branches := []*oas3.Schema{oasSchema} + statements := partVisits.c.Statements() + for _, br := range statements.Read(statementOf(partVisits.c, js)).Entries { + entry := statement.ParsedAt(statements.Read(br.Schema)) + if br.Ref != nil { + partWalk.parts = append(partWalk.parts, bodyParts(entry, hops+1, partVisits).parts...) continue } - bs := schemaOf(partVisitsValue.c.Bindings(), statement.ParsedAt(br.Schema)) - partVisitsValue.note(statement.ParsedAt(br.Schema), bs) - partWalkValue.parts = append(partWalkValue.parts, propertyParts(bs)...) + bs := schemaOf(partVisits.c.Bindings(), entry) + partVisits.note(entry, bs) + partWalk.parts = append(partWalk.parts, propertyParts(bs)...) branches = append(branches, bs) if br.Capped { - partVisitsValue.markCapped(bs) + partVisits.markCapped(bs) } } - for _, b := range branches { - for _, union := range slices.Concat(b.GetOneOf(), b.GetAnyOf()) { - partWalkValue.parts = append(partWalkValue.parts, bodyParts(union, hops+1, partVisitsValue).parts...) + for _, branch := range branches { + for _, union := range slices.Concat(branch.GetOneOf(), branch.GetAnyOf()) { + partWalk.parts = append(partWalk.parts, bodyParts(union, hops+1, partVisits).parts...) } } - partWalkValue.parts = dedupeParts(partWalkValue.parts) - return partWalkValue + partWalk.parts = dedupeParts(partWalk.parts) + return partWalk } -// note records in v.open that s, the schema js is entered as, leaves a key +// note records in v.open that oasSchema, the schema js is entered as, leaves a key // undecided: it admits members it names no property for (admitsMembers), or js -// or s declares properties where the walk reads none (declaresUnread). It -// collects the value schemas of the catch-alls s holds in v.catchAllValues. -func (v partVisits) note(js *oas3.JSONSchema[oas3.Referenceable], s *oas3.Schema) { - *v.catchAllValues = append(*v.catchAllValues, catchAllValues(v.c.Statements(), s)...) - if s != nil && (admitsMembers(v.c.Statements(), s) || declaresUnread(v.c, js, s)) { +// or oasSchema declares properties where the walk reads none (declaresUnread). It +// collects the value schemas of the catch-alls oasSchema holds in v.catchAllValues. +func (v partVisits) note(js *oas3.JSONSchema[oas3.Referenceable], oasSchema *oas3.Schema) { + *v.catchAllValues = append(*v.catchAllValues, catchAllValues(v.c.Statements(), oasSchema)...) + if oasSchema != nil && (admitsMembers(v.c.Statements(), oasSchema) || declaresUnread(v.c, js, oasSchema)) { *v.open = true } } -// admitsMembers reports whether s holds a catch-all for members it names no +// admitsMembers reports whether oasSchema holds a catch-all for members it names no // property for: an additionalProperties or unevaluatedProperties other than // false, or a patternProperties. A key such a member could have is not shown // to name nothing, though OpenAPI asks a key to name a declared property. -func admitsMembers(memoizingSchemaReader *statement.MemoizingSchemaReader, s *oas3.Schema) bool { - return admitting(memoizingSchemaReader, s.GetAdditionalProperties()) || admitting(memoizingSchemaReader, s.GetUnevaluatedProperties()) || - s.GetPatternProperties().Len() > 0 +func admitsMembers(memoizingSchemaReader *statement.MemoizingSchemaReader, oasSchema *oas3.Schema) bool { + return admitting(memoizingSchemaReader, oasSchema.GetAdditionalProperties()) || admitting(memoizingSchemaReader, oasSchema.GetUnevaluatedProperties()) || + oasSchema.GetPatternProperties().Len() > 0 } // admitting reports whether js, a catch-all's schema as memoizingSchemaReader @@ -575,63 +574,66 @@ func admitting(memoizingSchemaReader *statement.MemoizingSchemaReader, js *oas3. return truth != statement.Unwritten && !truth.ReadsFalse() } -// catchAllValues returns the value schemas of the catch-alls s, which may be +// catchAllValues returns the value schemas of the catch-alls oasSchema, which may be // nil, holds that admit a member (admitting), additionalProperties, // unevaluatedProperties and each patternProperties entry, in that order. -func catchAllValues(memoizingSchemaReader *statement.MemoizingSchemaReader, s *oas3.Schema) []*oas3.JSONSchema[oas3.Referenceable] { +func catchAllValues(memoizingSchemaReader *statement.MemoizingSchemaReader, oasSchema *oas3.Schema) []*oas3.JSONSchema[oas3.Referenceable] { var out []*oas3.JSONSchema[oas3.Referenceable] - for _, js := range []*oas3.JSONSchema[oas3.Referenceable]{s.GetAdditionalProperties(), s.GetUnevaluatedProperties()} { + for _, js := range []*oas3.JSONSchema[oas3.Referenceable]{oasSchema.GetAdditionalProperties(), oasSchema.GetUnevaluatedProperties()} { if admitting(memoizingSchemaReader, js) { out = append(out, js) } } - for _, js := range s.GetPatternProperties().All() { + for _, js := range oasSchema.GetPatternProperties().All() { out = append(out, js) } return out } // declaresUnread reports whether a property can be declared, or a member -// admitted, where the part walk reads none: under what s, the end of the chain +// admitted, where the part walk reads none: under what oasSchema, the end of the chain // of $refs js starts, writes that it does not read (writesUnread), past a $ref // resolving to nothing, and beside a $ref on the chain, which the walk reads -// to its end (schemaOf). -func declaresUnread(loweringContext lowering.Ctx, js *oas3.JSONSchema[oas3.Referenceable], s *oas3.Schema) bool { - if writesUnread(s, "") { +// to its end (schemaOf). A chain returning to a site it read declares what +// none of its sites shows, so it reads as declaring one; the set of sites read +// bounds the walk. +func declaresUnread(loweringContext lowering.Ctx, js *oas3.JSONSchema[oas3.Referenceable], oasSchema *oas3.Schema) bool { + if writesUnread(oasSchema, "") { return true } refs := loweringContext.Bindings() - for range maxBodyAliasHops { + read := map[*oas3.JSONSchema[oas3.Referenceable]]bool{} + for { keyword := refs.RefKeyword(js) if keyword == "" { return false } site := js.GetSchema() - if refs.End(js) == nil || writesUnread(site, keyword) || admitsMembers(loweringContext.Statements(), site) || len(site.GetAllOf()) > 0 || - len(site.GetOneOf()) > 0 || len(site.GetAnyOf()) > 0 || site.GetProperties().Len() > 0 { + if read[js] || refs.End(js) == nil || writesUnread(site, keyword) || admitsMembers(loweringContext.Statements(), site) || + len(site.GetAllOf()) > 0 || len(site.GetOneOf()) > 0 || len(site.GetAnyOf()) > 0 || site.GetProperties().Len() > 0 { return true } + read[js] = true js = refs.Declared(js) } - return true } -// writesUnread reports whether s writes a keyword that can declare a property +// writesUnread reports whether oasSchema writes a keyword that can declare a property // the part walk does not read: if, then, else, dependentSchemas or a -// $dynamicRef, unless that is the reference keyword s is a reference site under +// $dynamicRef, unless that is the reference keyword oasSchema is a reference site under // (typed.Bindings.RefKeyword), which the walk follows. -func writesUnread(s *oas3.Schema, reference string) bool { - return s.GetIf() != nil || s.GetThen() != nil || s.GetElse() != nil || s.GetDependentSchemas().Len() > 0 || - reference != "$dynamicRef" && nodeview.Child(s.GetRootNode(), "$dynamicRef") != nil +func writesUnread(oasSchema *oas3.Schema, reference string) bool { + return oasSchema.GetIf() != nil || oasSchema.GetThen() != nil || oasSchema.GetElse() != nil || oasSchema.GetDependentSchemas().Len() > 0 || + reference != "$dynamicRef" && nodeview.Child(oasSchema.GetRootNode(), "$dynamicRef") != nil } -// propertyParts returns the properties s declares itself, in source order. -func propertyParts(s *oas3.Schema) []bodyPart { - if s == nil || s.GetProperties() == nil { +// propertyParts returns the properties oasSchema declares itself, in source order. +func propertyParts(oasSchema *oas3.Schema) []bodyPart { + if oasSchema == nil || oasSchema.GetProperties() == nil { return nil } var out []bodyPart - for name, pjs := range s.GetProperties().All() { + for name, pjs := range oasSchema.GetProperties().All() { out = append(out, bodyPart{name: name, schemas: []*oas3.JSONSchema[oas3.Referenceable]{pjs}}) } return out @@ -641,14 +643,14 @@ func propertyParts(s *oas3.Schema) []bodyPart { // part past one, which gets no Content.Encoding key and no structural flags, // is not lost without a word; an entry written for it is kept whole // (keepUnkeyedEncodings). -func diagPartWalkCut(serviceContext service.Ctx, partWalkValue partWalk, at jsontext.Pointer) []ir.Diagnostic { +func diagPartWalkCut(serviceContext service.Ctx, partWalk partWalk, at jsontext.Pointer) []ir.Diagnostic { var out []ir.Diagnostic - if partWalkValue.capped { + if partWalk.capped { out = append(out, serviceContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, at, "form body composition is nested past the flattening depth of %d, so a part reached only below it has no Content.Encoding key", statement.MaxFlattenDepth)) } - if partWalkValue.hopsSpent { + if partWalk.hopsSpent { out = append(out, serviceContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, at, "form body composition follows $refs and union branches past %d hops, so a part reached only beyond them has no Content.Encoding key", maxPartRefHops)) @@ -682,12 +684,9 @@ func dedupeParts(parts []bodyPart) []bodyPart { // in that order. complete is false past maxPartUnions unions, where a member // only a union beyond them declares is missing, and unread names each model // whose shapes were not read. -func partMembers(reg ir.TypeRegistry, body ir.TypeID) (members map[string][]*ir.Property, complete bool, unread []unreadNarrowing) { - node := func(id ir.TypeID) (ir.TypeDef, bool) { - td, ok := reg[id] - return td, ok - } - holders, complete := memberHolders(node, body) +func partMembers(chains *runChains, body ir.TypeID) (members map[string][]*ir.Property, complete bool, unread []unreadNarrowing) { + reg := chains.reg + holders, complete := memberHolders(chains, body) members = map[string][]*ir.Property{} for _, holder := range holders { flat := ir.FlattenedProperties(reg, holder) @@ -744,11 +743,11 @@ func shapeFlattenings(reg ir.TypeRegistry, holder ir.TypeID, flat ir.Flattening, } // memberHolders returns the types whose members a body typed body has: body -// itself, or, where it stands for a union, its variants that stand for none, +// itself, or, where it names a union, its variants that name none, // in source order, each union read once, depth first, so a union naming // itself ends. complete is false past maxPartUnions unions. -func memberHolders(node func(ir.TypeID) (ir.TypeDef, bool), body ir.TypeID) (holders []ir.TypeID, complete bool) { - root, ok := bodyNode(node, body).(*ir.Union) +func memberHolders(chains *runChains, body ir.TypeID) (holders []ir.TypeID, complete bool) { + root, ok := bodyNode(chains, body).(*ir.Union) if !ok || root == nil { return []ir.TypeID{body}, true } @@ -762,7 +761,7 @@ func memberHolders(node func(ir.TypeID) (ir.TypeDef, bool), body ir.TypeID) (hol } stack[len(stack)-1] = top[1:] typeID := top[0].Type.Target - union, nested := bodyNode(node, typeID).(*ir.Union) + union, nested := bodyNode(chains, typeID).(*ir.Union) switch { case !nested || union == nil: holders = append(holders, typeID) @@ -785,12 +784,12 @@ func memberHolders(node func(ir.TypeID) (ir.TypeDef, bool), body ir.TypeID) (hol // every schema of part, as refs resolves them (declaredMulti), a reading left // until then since it walks a union's branches. unions is the run's reading of // the unions parts name. -func partFlags(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), refs *typed.Bindings, decls []*ir.Property, part bodyPart, pe ir.PartEncoding, multipart bool) ir.PartEncoding { - multi, file, decided := declarationFlags(unions, node, decls, multipart) - if !decided { - multi = declaredMulti(refs, part.schemas) +func partFlags(unions *partUnions, chains *runChains, refs *typed.Bindings, decls []*ir.Property, part bodyPart, pe ir.PartEncoding, multipart bool) ir.PartEncoding { + flags := declarationFlags(unions, chains, decls, multipart) + if !flags.decided { + flags.multi = declaredMulti(refs, part.schemas) } - pe.RepeatsPerArrayItem, pe.HasFilename = multi, file + pe.RepeatsPerArrayItem, pe.HasFilename = flags.multi, flags.file return pe } @@ -799,13 +798,13 @@ func partFlags(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), refs // multi where any is, and file where every one is, a type partTypeFlags cannot // decide being no file, as a union's member of such a kind is. decided is // false where partTypeFlags cannot decide one of them. -func declarationFlags(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), decls []*ir.Property, multipart bool) (multi, file, decided bool) { - file, decided = multipart && len(decls) > 0, true +func declarationFlags(unions *partUnions, chains *runChains, decls []*ir.Property, multipart bool) structuralFlags { + flags := structuralFlags{file: multipart && len(decls) > 0, decided: true} for _, property := range decls { - declMulti, declFile, ok := partTypeFlags(unions, node, property.Type, multipart) - multi, file, decided = multi || declMulti, file && declFile, decided && ok + declared := partTypeFlags(unions, chains, property.Type, multipart) + flags = structuralFlags{multi: flags.multi || declared.multi, file: flags.file && declared.file, decided: flags.decided && declared.decided} } - return multi, file, decided + return flags } // partTypeFlags reads the structural flags of a part from its type, as @@ -815,13 +814,13 @@ func declarationFlags(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool // list or tuple of them. A member memberFlags cannot answer for is neither. // decided is false where memberFlags cannot answer, or the union's members are // not read. A union's flags are read once a run (partUnions.flagsOf). -func partTypeFlags(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), ref ir.TypeRef, multipart bool) (multi, file, decided bool) { - td, found := node(ref.Target) - union, isUnion := td.(*ir.Union) +func partTypeFlags(unions *partUnions, chains *runChains, ref ir.TypeRef, multipart bool) structuralFlags { + typeDef, found := chains.lookup(ref.Target) + union, isUnion := typeDef.(*ir.Union) if !found || !isUnion { - return memberFlags(node, ref, multipart) + return memberFlags(chains, ref, multipart) } - return unions.flagsOf(node, union, multipart) + return unions.flagsOf(chains, union, multipart) } // maxPartUnions bounds the unions unionMembers and memberHolders read through @@ -833,7 +832,7 @@ const maxPartUnions = 64 // each read once, so a union naming itself ends. ok is false where a variant // names no node or more than maxPartUnions unions are read. A part reads it // through partUnions, once a run. -func unionMembers(node func(ir.TypeID) (ir.TypeDef, bool), union *ir.Union) (members []ir.TypeRef, ok bool) { +func unionMembers(chains *runChains, union *ir.Union) (members []ir.TypeRef, ok bool) { pending := []*ir.Union{union} seen := map[ir.TypeID]bool{} for range maxPartUnions { @@ -843,11 +842,11 @@ func unionMembers(node func(ir.TypeID) (ir.TypeDef, bool), union *ir.Union) (mem next := pending[0] pending = pending[1:] for _, variant := range next.Variants { - td, found := node(variant.Type.Target) + typeDef, found := chains.lookup(variant.Type.Target) if !found { return nil, false } - nested, isUnion := td.(*ir.Union) + nested, isUnion := typeDef.(*ir.Union) switch { case !isUnion: members = append(members, variant.Type) @@ -868,32 +867,24 @@ func unionMembers(node func(ir.TypeID) (ir.TypeDef, bool), union *ir.Union) (mem // scalar re-encodes (rawBytes), following the alias scalars a hoisted position // puts over the primitive, or a list or tuple whose every element is such bytes // (rawTuple). A `format: byte` part is base64 text, and a url-encoded body has -// no file parts. decided is false for a type of a kind it cannot answer for. -// The walk is bounded by maxBodyAliasHops. -func memberFlags(node func(ir.TypeID) (ir.TypeDef, bool), ref ir.TypeRef, multipart bool) (multi, file, decided bool) { - id := ref.Target - for range maxBodyAliasHops { - td, found := node(id) - if !found { - return false, false, false - } - switch t := td.(type) { - case *ir.List: - return true, multipart && rawBytes(node, t.ElementType), true - case *ir.Tuple: - return true, multipart && rawTuple(node, t), true - case *ir.Primitive: - return false, multipart && rawBytes(node, ref), true - case *ir.Scalar: - if t.Base == nil { - return false, false, true - } - id = t.Base.Target - default: - return false, false, false - } +// no file parts. decided is false for a type of a kind it cannot answer for, or +// a chain naming no node, and a cycle of aliases is decided as no file. +func memberFlags(chains *runChains, ref ir.TypeRef, multipart bool) structuralFlags { + end := chains.end(ref.Target) + switch t := end.typeDef.(type) { + case nil: + return structuralFlags{} + case *ir.List: + return structuralFlags{multi: true, file: multipart && rawBytes(chains, t.ElementType), decided: true} + case *ir.Tuple: + return structuralFlags{multi: true, file: multipart && rawTuple(chains, t), decided: true} + case *ir.Primitive: + return structuralFlags{file: multipart && rawBytes(chains, ref), decided: true} + case *ir.Scalar: + return structuralFlags{decided: end.cyclic || t.Base == nil} + default: + return structuralFlags{} } - return false, false, true } // buildPartEncoding assembles the explicit encoding config of the part named @@ -912,54 +903,39 @@ func buildPartEncoding(serviceContext service.Ctx, loweringState operationLoweri // refs resolves them: where any declares an array (declaresArray). func declaredMulti(refs *typed.Bindings, schemas []*oas3.JSONSchema[oas3.Referenceable]) bool { return slices.ContainsFunc(schemas, func(js *oas3.JSONSchema[oas3.Referenceable]) bool { - s := schemaOf(refs, js) - return s != nil && declaresArray(refs, s) + oasSchema := schemaOf(refs, js) + return oasSchema != nil && declaresArray(refs, oasSchema) }) } -// declaresArray reports whether s declares a repeated part: the array type on -// s, or, where s writes no type of its own, which would hold beside every +// declaresArray reports whether oasSchema declares a repeated part: the array type on +// oasSchema, or, where oasSchema writes no type of its own, which would hold beside every // branch, on a branch of a union it writes, a part that may repeat traveling as // repeated parts. -func declaresArray(refs *typed.Bindings, s *oas3.Schema) bool { - if len(withoutNull(s.GetType())) > 0 { - return schemaIsArray(s) +func declaresArray(refs *typed.Bindings, oasSchema *oas3.Schema) bool { + if len(withoutNull(oasSchema.GetType())) > 0 { + return schemaIsArray(oasSchema) } - return slices.ContainsFunc(slices.Concat(s.GetAnyOf(), s.GetOneOf()), func(branch *oas3.JSONSchema[oas3.Referenceable]) bool { + return slices.ContainsFunc(slices.Concat(oasSchema.GetAnyOf(), oasSchema.GetOneOf()), func(branch *oas3.JSONSchema[oas3.Referenceable]) bool { return schemaIsArray(schemaOf(refs, branch)) }) } // schemaIsArray reports whether a schema declares the array type (a repeated // multipart part). -func schemaIsArray(s *oas3.Schema) bool { - return slices.Contains(s.GetType(), oas3.SchemaTypeArray) -} - -// maxBodyAliasHops bounds the alias chains bodyNode, partTypeFlags and the -// default content type follow over the IR (styleguide bounded-everything -// rule), which the IR permits to be cyclic, and the $ref chain declaresUnread -// reads. The composition partMembers reads is ir.FlattenedProperties's to -// bound: it meets each model and alias once. -const maxBodyAliasHops = 64 - -// bodyNode returns the node body stands for past the alias scalars a -// $ref-with-siblings position hoists, nil where the chain reaches no node or -// runs past maxBodyAliasHops. -func bodyNode(node func(ir.TypeID) (ir.TypeDef, bool), body ir.TypeID) ir.TypeDef { - id := body - for range maxBodyAliasHops { - td, found := node(id) - if !found { - return nil - } - scalar, alias := td.(*ir.Scalar) - if !alias || scalar == nil || scalar.Base == nil { - return td - } - id = scalar.Base.Target +func schemaIsArray(oasSchema *oas3.Schema) bool { + return slices.Contains(oasSchema.GetType(), oas3.SchemaTypeArray) +} + +// bodyNode returns the node body names past the alias scalars a +// $ref-with-siblings position hoists, however many, nil where the chain +// reaches no node or meets an alias twice. +func bodyNode(chains *runChains, body ir.TypeID) ir.TypeDef { + end := chains.end(body) + if end.cyclic { + return nil } - return nil + return end.typeDef } // partEncodingEmpty reports whether a PartEncoding carries no information and can diff --git a/compilers/openapi/internal/operation/multipart_internal_test.go b/compilers/openapi/internal/operation/multipart_internal_test.go index 17095fddf..c90096d42 100644 --- a/compilers/openapi/internal/operation/multipart_internal_test.go +++ b/compilers/openapi/internal/operation/multipart_internal_test.go @@ -40,24 +40,24 @@ func TestPartMembers_DeadEnds(t *testing.T) { body ir.TypeID }{ {"an ID no registry entry declares", "type/absent"}, - {"an opaque scalar standing for nothing", "type/opaque"}, + {"an opaque scalar naming nothing", "type/opaque"}, {"a kind that declares no properties", "type/string"}, {"an alias chain that closes on itself", "type/cycle/a"}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - members, complete, _ := partMembers(reg, tc.body) - assert.Empty(t, members, "no property stands behind this body, and none is invented") + members, complete, _ := partMembers(chainsOver(reg), tc.body) + assert.Empty(t, members, "no property sits behind this body, and none is invented") assert.True(t, complete) }) } - members, complete, _ := partMembers(reg, "type/model/cycle") + members, complete, _ := partMembers(chainsOver(reg), "type/model/cycle") require.Len(t, members["file"], 1, "a model whose base closes on itself still has its own members") assert.Equal(t, file.ID, members["file"][0].ID) assert.True(t, complete) } -// TestPartMembers_AUnionBodyHasItsVariantsMembers pins a body standing for a +// TestPartMembers_AUnionBodyHasItsVariantsMembers pins a body naming a // union, as one a composition is distributed across does, through an alias // too: its members are its variants', through a union nested in a variant, // each variant's declaration of a name in source order, and a declaration @@ -88,7 +88,7 @@ func TestPartMembers_AUnionBodyHasItsVariantsMembers(t *testing.T) { return out } for _, body := range []ir.TypeID{"type/u", "type/alias"} { - members, complete, _ := partMembers(reg, body) + members, complete, _ := partMembers(chainsOver(reg), body) assert.True(t, complete, "%s", body) require.Len(t, members, 3, "%s", body) assert.Equal(t, []ir.PropertyID{shared.ID}, ids(members["file"]), "a shared declaration is listed once: %s", body) @@ -96,8 +96,8 @@ func TestPartMembers_AUnionBodyHasItsVariantsMembers(t *testing.T) { "each variant's declaration, in source order, the nested union's in its place: %s", body) assert.Equal(t, []ir.PropertyID{deep.ID}, ids(members["y"]), "a nested union's variant's member: %s", body) } - members, complete, _ := partMembers(reg, "type/nil") - assert.Empty(t, members, "a typed nil union stands for no members") + members, complete, _ := partMembers(chainsOver(reg), "type/nil") + assert.Empty(t, members, "a typed nil union names no members") assert.True(t, complete) } @@ -141,7 +141,7 @@ func narrowingRegistry() ir.TypeRegistry { func TestPartMembers_AModelNarrowingAUnionHasItsShapesMembers(t *testing.T) { t.Parallel() reg := narrowingRegistry() - members, complete, unread := partMembers(reg, "type/n") + members, complete, unread := partMembers(chainsOver(reg), "type/n") assert.True(t, complete) assert.Empty(t, unread) got := map[string][]ir.PropertyID{} @@ -152,7 +152,7 @@ func TestPartMembers_AModelNarrowingAUnionHasItsShapesMembers(t *testing.T) { } assert.Equal(t, map[string][]ir.PropertyID{"note": {"property/n/note"}, "file": {"property/a/file"}, "url": {"property/b/url"}}, got) - members, _, unread = partMembers(reg, "type/two") + members, _, unread = partMembers(chainsOver(reg), "type/two") assert.Empty(t, members) assert.Equal(t, []unreadNarrowing{{model: "type/two", why: "several"}}, unread) } @@ -200,16 +200,13 @@ func TestMemberHolders_StopsPastItsBound(t *testing.T) { } return reg, "type/u/0" } - node := func(reg ir.TypeRegistry) func(ir.TypeID) (ir.TypeDef, bool) { - return func(id ir.TypeID) (ir.TypeDef, bool) { td, ok := reg[id]; return td, ok } - } reg, body := chain(maxPartUnions) - holders, complete := memberHolders(node(reg), body) + holders, complete := memberHolders(chainsOver(reg), body) assert.True(t, complete, "a chain of maxPartUnions unions is read whole") assert.Len(t, holders, maxPartUnions) reg, body = chain(maxPartUnions + 1) - holders, complete = memberHolders(node(reg), body) + holders, complete = memberHolders(chainsOver(reg), body) assert.False(t, complete, "one union more is past the bound") assert.Len(t, holders, maxPartUnions, "the holders the walk reached are kept") } @@ -219,11 +216,11 @@ func TestMemberHolders_StopsPastItsBound(t *testing.T) { func TestBodyParts_RefHopBound(t *testing.T) { t.Parallel() js := oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{}) - partVisitsValue := partVisits{c: newRawLowerer(&soa.OpenAPI{}).ctx.Ctx, entered: map[*oas3.Schema]int{}, cut: map[*oas3.Schema]bool{}} - partWalk := bodyParts(js, maxPartRefHops+1, partVisitsValue) + partVisits := partVisits{c: newRawLowerer(&soa.OpenAPI{}).ctx.Ctx, entered: map[*oas3.Schema]int{}, cut: map[*oas3.Schema]bool{}} + partWalk := bodyParts(js, maxPartRefHops+1, partVisits) assert.Nil(t, partWalk.parts, "past the bound the walk stops rather than descending further") - assert.Len(t, partVisitsValue.cut, 1, "and records the target it stopped at") + assert.Len(t, partVisits.cut, 1, "and records the target it stopped at") } // TestPartTypeFlags_DecidesOnlyTheKindsItReads holds the type walk to what it @@ -259,10 +256,10 @@ func TestPartTypeFlags_DecidesOnlyTheKindsItReads(t *testing.T) { {lowerer.types.PrimitiveID(ir.PrimitiveString), false, true}, } for _, tc := range cases { - multi, file, decided := partTypeFlags(newPartUnions(), lowerer.types.Node, ir.TypeRef{Target: tc.target}, true /* multipart */) - assert.Equal(t, tc.multi, multi, "%s multi", tc.target) - assert.False(t, file, "%s is not bytes", tc.target) - assert.Equal(t, tc.decided, decided, "%s decided", tc.target) + flags := partTypeFlags(newPartUnions(), chainsThrough(nil, lowerer.types.Node), ir.TypeRef{Target: tc.target}, true /* multipart */) + assert.Equal(t, tc.multi, flags.multi, "%s multi", tc.target) + assert.False(t, flags.file, "%s is not bytes", tc.target) + assert.Equal(t, tc.decided, flags.decided, "%s decided", tc.target) } } @@ -308,9 +305,9 @@ func TestPartTypeFlags_AListOrTupleOfRawBytesIsFiles(t *testing.T) { } { id := tc.node.Common().ID lowerer.types.Register(id, tc.node) - multi, file, decided := partTypeFlags(newPartUnions(), lowerer.types.Node, ir.TypeRef{Target: id}, tc.multipart) - assert.True(t, multi && decided, "%s repeats", id) - assert.Equal(t, tc.file, file, "%s file", id) + flags := partTypeFlags(newPartUnions(), chainsThrough(nil, lowerer.types.Node), ir.TypeRef{Target: id}, tc.multipart) + assert.True(t, flags.multi && flags.decided, "%s repeats", id) + assert.Equal(t, tc.file, flags.file, "%s file", id) } } @@ -335,10 +332,10 @@ func TestPartTypeFlags_AUnionReadsThroughItsMembers(t *testing.T) { lowerer.types.Register("type/inner", unionOf("type/inner", bytes, files)) lowerer.types.Register("type/self", unionOf("type/self", bytes, ir.TypeRef{Target: "type/self"})) lowerer.types.Register("type/diamond", unionOf("type/diamond", ir.TypeRef{Target: "type/inner"}, ir.TypeRef{Target: "type/inner"})) - chain := func(id string, n int) ir.TypeID { - for i := n - 1; i >= 0; i-- { + chain := func(id string, count int) ir.TypeID { + for i := count - 1; i >= 0; i-- { variants := []ir.TypeRef{bytes} - if i < n-1 { + if i < count-1 { variants = append(variants, ir.TypeRef{Target: ir.TypeID(fmt.Sprintf("%s/%d", id, i+1))}) } at := ir.TypeID(fmt.Sprintf("%s/%d", id, i)) @@ -374,10 +371,10 @@ func TestPartTypeFlags_AUnionReadsThroughItsMembers(t *testing.T) { {"unions up to the bound", chain("type/chain", maxPartUnions), true, false, true, true}, {"unions past the bound", chain("type/long", maxPartUnions+1), true, false, false, false}, } { - multi, file, decided := partTypeFlags(newPartUnions(), lowerer.types.Node, ir.TypeRef{Target: tc.target}, tc.multipart) - assert.Equal(t, tc.multi, multi, "%s: multi", tc.name) - assert.Equal(t, tc.file, file, "%s: file", tc.name) - assert.Equal(t, tc.decided, decided, "%s: decided", tc.name) + flags := partTypeFlags(newPartUnions(), chainsThrough(nil, lowerer.types.Node), ir.TypeRef{Target: tc.target}, tc.multipart) + assert.Equal(t, tc.multi, flags.multi, "%s: multi", tc.name) + assert.Equal(t, tc.file, flags.file, "%s: file", tc.name) + assert.Equal(t, tc.decided, flags.decided, "%s: decided", tc.name) } } @@ -391,9 +388,9 @@ func unionOf(id ir.TypeID, variants ...ir.TypeRef) *ir.Union { } // registered registers node with lowererValue and returns its ID. -func registered(lowererValue *lowerer, node ir.TypeDef) ir.TypeID { +func registered(lowerer *lowerer, node ir.TypeDef) ir.TypeID { id := node.Common().ID - lowererValue.types.Register(id, node) + lowerer.types.Register(id, node) return id } @@ -506,11 +503,11 @@ func TestPartWalk_DecidesKeysOnlyWhereItReadsEveryDeclaration(t *testing.T) { } } -// TestPartWalk_ReadsARefChainToItsBound holds the $ref chain whose sites the -// walk reads for properties written beside each $ref to maxBodyAliasHops -// sites: a chain of one fewer is read whole and decides a key, and a chain of -// as many leaves a key undecided, as a site past the bound may write one. -func TestPartWalk_ReadsARefChainToItsBound(t *testing.T) { +// TestPartWalk_ReadsARefChainToItsEnd pins the $ref chain a part walk reads +// for properties written beside each $ref: a chain of any length is read whole +// and decides a key, past the 64 sites a walk once stopped at, where a chain +// of as many left a key undecided. +func TestPartWalk_ReadsARefChainToItsEnd(t *testing.T) { t.Parallel() chain := func(sites int) string { var b strings.Builder @@ -520,13 +517,13 @@ func TestPartWalk_ReadsARefChainToItsBound(t *testing.T) { fmt.Fprintf(&b, " L%d: {type: object, properties: {a: {type: string}}}\n", sites) return b.String() } - for sites, decides := range map[int]bool{maxBodyAliasHops - 1: true, maxBodyAliasHops: false} { + for _, sites := range []int{63, 64, 200} { lowerer, _ := loweredFor(t, openapitest.ComponentSpec(chain(sites))) js, ok := lowerer.ctx.Doc.Components.Schemas.Get("L0") require.True(t, ok) partWalk := walkBodyParts(lowerer.ctx.Ctx, js) require.Len(t, partWalk.parts, 1, "the walk reads the chain's end at %d sites", sites) - assert.Equal(t, decides, partWalk.decidesKeys(), "%d sites", sites) + assert.True(t, partWalk.decidesKeys(), "%d sites", sites) } } @@ -537,10 +534,10 @@ func TestPartWalk_ReadsARefChainToItsBound(t *testing.T) { // quadruple it. It is not run in parallel: AllocsPerRun measures the process. func TestDeclarationSchemas_PlacesEachSchemaOnce(t *testing.T) { unplaced := oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{}) - read := func(n int) (map[ir.PropertyID][]*oas3.JSONSchema[oas3.Referenceable], []*ir.Property, float64) { + read := func(count int) (map[ir.PropertyID][]*oas3.JSONSchema[oas3.Referenceable], []*ir.Property, float64) { var b strings.Builder b.WriteString(" U:\n oneOf:\n") - for range n { + for range count { b.WriteString(" - {type: object, properties: {file: {type: string}}}\n") } lowerer, _ := loweredFor(t, openapitest.ComponentSpec(b.String())) @@ -549,10 +546,10 @@ func TestDeclarationSchemas_PlacesEachSchemaOnce(t *testing.T) { partWalk := walkBodyParts(lowerer.ctx.Ctx, js) require.Len(t, partWalk.parts, 1) part := partWalk.parts[0] - require.Len(t, part.schemas, n) - decls := make([]*ir.Property, 0, n) - for _, s := range part.schemas { - id, placed := declaredProperty(lowerer.ctx, s) + require.Len(t, part.schemas, count) + decls := make([]*ir.Property, 0, count) + for _, schema := range part.schemas { + id, placed := declaredProperty(lowerer.ctx, schema) require.True(t, placed) decls = append(decls, &ir.Property{ID: id}) } diff --git a/compilers/openapi/internal/operation/multipart_test.go b/compilers/openapi/internal/operation/multipart_test.go index 4205ce0b9..169ecf5b5 100644 --- a/compilers/openapi/internal/operation/multipart_test.go +++ b/compilers/openapi/internal/operation/multipart_test.go @@ -349,7 +349,7 @@ components: // declares for it (docs/compilers/openapi.md#allof-redeclared-property): one // key whichever the allOf lists last, with the flags read off the type the // member keeps, the later entry's, as no value is both, which is reported -// where the declaration that lost is written. Both are files, so HasFilename +// where the declaration passed over is written. Both are files, so HasFilename // shows nothing either way. func TestPartEncodings_KeyedOnTheMemberTheBodyDeclares(t *testing.T) { t.Parallel() @@ -396,9 +396,9 @@ components: assert.Equal(t, []string{"image/png"}, pe.ContentTypes) assert.Equal(t, tc.multi, pe.RepeatsPerArrayItem, "the flags are read off the type the member keeps") assert.True(t, pe.HasFilename, "a file and a list of files are both files") - lost := ids.Ptr("components", "schemas", tc.first, "properties", "file") - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.ConflictingRedecl, string(lost)), - "no value is both, which is reported where the declaration that lost is written") + passedOver := ids.Ptr("components", "schemas", tc.first, "properties", "file") + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.ConflictingRedecl, string(passedOver)), + "no value is both, which is reported where the declaration passed over is written") }) } } @@ -646,12 +646,12 @@ func TestPartEncodings_ReadsTheFlattenedComposition(t *testing.T) { t.Parallel() const multipart, urlencoded = "multipart/form-data", "application/x-www-form-urlencoded" cases := []struct { - name string - n int - residue bool - shape string - media string - capped bool + name string + n int + keptKeywords bool + shape string + media string + capped bool }{ {"15 wrappers", 15, false, shapeInline, multipart, false}, {"16 wrappers", 16, false, shapeInline, multipart, false}, @@ -662,15 +662,15 @@ func TestPartEncodings_ReadsTheFlattenedComposition(t *testing.T) { {"past the flattening depth, urlencoded", statement.MaxFlattenDepth + 2, false, shapeInline, urlencoded, true}, {"past the flattening depth behind a $ref", statement.MaxFlattenDepth + 2, false, shapeViaRef, multipart, true}, {"a part beside the cut", statement.MaxFlattenDepth + 2, false, shapeBesideNote, multipart, true}, - {"residue wrapper", 1, true, shapeInline, multipart, false}, + {"keptKeywords wrapper", 1, true, shapeInline, multipart, false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() mediaPtr := requestMedia(tc.media) bodyPtr := ids.Ptr("paths", "/u", "post", "requestBody", "content", tc.media, "schema") - forward := nestedPartSpec(tc.n, tc.residue, tc.shape, tc.media, []string{"file", "meta"}, []string{"file", "meta"}) - reversed := nestedPartSpec(tc.n, tc.residue, tc.shape, tc.media, []string{"meta", "file"}, []string{"meta", "file"}) + forward := nestedPartSpec(tc.n, tc.keptKeywords, tc.shape, tc.media, []string{"file", "meta"}, []string{"file", "meta"}) + reversed := nestedPartSpec(tc.n, tc.keptKeywords, tc.shape, tc.media, []string{"meta", "file"}, []string{"meta", "file"}) var got [2]map[ir.PropertyID]ir.PartEncoding for i, src := range []string{forward, reversed} { _, svc, diags := compileService(t, src) @@ -1017,7 +1017,7 @@ components: // nestedPartSpec spells a form body of media type media whose parts sit wrapped // deep inside n inline allOf wrappers, each optionally carrying a description, // with the encoding map and the two parts written in the order given. -func nestedPartSpec(n int, residue bool, shape, media string, parts, encoding []string) string { +func nestedPartSpec(count int, keptKeywords bool, shape, media string, parts, encoding []string) string { partLine := map[string]string{ "file": "file: {type: string, format: binary}", "meta": "meta: {type: string}", @@ -1028,16 +1028,16 @@ func nestedPartSpec(n int, residue bool, shape, media string, parts, encoding [] } properties := make([]string, 0, len(parts)) encs := make([]string, 0, len(encoding)) - for _, p := range parts { - properties = append(properties, partLine[p]) + for _, part := range parts { + properties = append(properties, partLine[part]) } for _, e := range encoding { encs = append(encs, encLine[e]) } schemaSrc := "{type: object, properties: {" + strings.Join(properties, ", ") + "}}" - for range n { + for range count { wrapper := "{allOf: [" + schemaSrc + "]}" - if residue { + if keptKeywords { wrapper = "{description: grouped, allOf: [" + schemaSrc + "]}" } schemaSrc = wrapper @@ -1752,8 +1752,8 @@ func TestPartEncodings_AnUnkeyedEntryLowersNothingItDeclares(t *testing.T) { } typesUnder := func(doc *ir.Document, name string) []ir.TypeID { var out []ir.TypeID - for id, td := range doc.Types { - if strings.HasPrefix(string(td.Common().Provenance.Pointer), media+"/encoding/"+name+"/") { + for id, typeDef := range doc.Types { + if strings.HasPrefix(string(typeDef.Common().Provenance.Pointer), media+"/encoding/"+name+"/") { out = append(out, id) } } @@ -1879,13 +1879,13 @@ func TestPartEncodings_AnEntryThatCannotBeKeptIsReportedNotAnnounced(t *testing. assert.Empty(t, keptEncodingNames(formContent(t, svc, false).Unmodeled), "nothing was written") openapitest.AssertHasCode(t, diags, diag.UnpreservableConstruct, ir.SeverityError) assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, at), "reported at the entry") - assert.Empty(t, openapitest.PreservationClaims(diags), "no announcement says the entry was kept") + assert.Empty(t, openapitest.MessagesSayingKept(diags), "no announcement says the entry was kept") } // TestPartEncodings_AContentTypeWrittenTakesNoDefault holds a part whose entry // writes a contentType naming no media type, which load reports, to no // default content type: the entry wrote one, and a default would read as a -// valid value standing for a malformed one. +// valid value naming a malformed one. func TestPartEncodings_AContentTypeWrittenTakesNoDefault(t *testing.T) { t.Parallel() _, svc, diags := compileService(t, formDoc("", multipartForm, @@ -1908,7 +1908,7 @@ func TestPartEncodings_AnEntryKeptAtSettlementThatCannotBeKeptKeepsItsRecords(t "{const: x, properties: {file: {type: string}}}", "{file: {x-k: 1, contentType: image/png, bogus: .nan}}", "")) content := formContent(t, svc, false) assert.Empty(t, content.Encoding) - assert.Equal(t, []string{"file/x-k"}, keptEncodingNames(content.Unmodeled), "the entry's own records stand") + assert.Equal(t, []string{"file/x-k"}, keptEncodingNames(content.Unmodeled), "the entry's own records remain") assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, media+"/encoding/file"), "the refusal, at the entry") assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, media+"/encoding/file"), "no announcement says the entry was kept whole") diff --git a/compilers/openapi/internal/operation/operationids.go b/compilers/openapi/internal/operation/operationids.go index 481886c6b..c0571e379 100644 --- a/compilers/openapi/internal/operation/operationids.go +++ b/compilers/openapi/internal/operation/operationids.go @@ -17,7 +17,7 @@ import ( "github.com/dexpace/morphic/ir" ) -// operationIDClaims collects the operationId each lowered operation claims, so +// operationIDUses collects the operationId each lowered operation claims, so // that uniqueness is judged once the whole service is lowered rather than as // each claim arrives. Judging on arrival reported whichever claim was lowered // second, so where the finding landed depended on declaration order. @@ -25,51 +25,51 @@ import ( // It owns the rule: the load phase's rule table states it and leaves it here, // since only the lowering sees every operation, and tells an alias's reuse // from a repeat (GitHub #502). -type operationIDClaims struct { - names []string // each operationId, in the order it was first claimed - claims map[string][]operationIDClaim +type operationIDUses struct { + names []string // each operationId, in the order it was first claimed + uses map[string][]operationIDUse } -// operationIDClaim is one operation claiming an operationId: the node declaring +// operationIDUse is one operation claiming an operationId: the node declaring // it and the pointers the operation was lowered with. The node and the // declaration pointer are the two ways a claim names the declaration it mounts. -type operationIDClaim struct { +type operationIDUse struct { node *yaml.Node ptrs operationPointers } -func newOperationIDClaims() *operationIDClaims { - return &operationIDClaims{claims: map[string][]operationIDClaim{}} +func newOperationIDUses() *operationIDUses { + return &operationIDUses{uses: map[string][]operationIDUse{}} } // add records the claim src makes at ptrs. An operation with no operationId // claims nothing: emitters synthesize its name from the method and path. -func (o *operationIDClaims) add(src *soa.Operation, ptrs operationPointers) { +func (o *operationIDUses) add(src *soa.Operation, ptrs operationPointers) { name := src.GetOperationID() if name == "" { return } - if _, seen := o.claims[name]; !seen { + if _, seen := o.uses[name]; !seen { o.names = append(o.names, name) } - o.claims[name] = append(o.claims[name], operationIDClaim{node: declaringNode(src.GetRootNode()), ptrs: ptrs}) + o.uses[name] = append(o.uses[name], operationIDUse{node: declaringNode(src.GetRootNode()), ptrs: ptrs}) } // report judges every operationId claimed more than once, in first-claim order. // The document's text is read only once an id is claimed twice, which most // documents never do. -func (o *operationIDClaims) report(serviceContext service.Ctx) []ir.Diagnostic { +func (o *operationIDUses) report(serviceContext service.Ctx) []ir.Diagnostic { var diags []ir.Diagnostic var written *writtenTree for _, name := range o.names { - claims := o.claims[name] - if len(claims) < 2 { + uses := o.uses[name] + if len(uses) < 2 { continue } if written == nil { written = newWrittenTree(serviceContext.Doc.GetRootNode()) } - diags = append(diags, judge(serviceContext, name, declarations(claims, written))...) + diags = append(diags, judge(serviceContext, name, declarations(uses, written))...) } return diags } @@ -109,11 +109,11 @@ func judge(serviceContext service.Ctx, name string, decls []declaration) []ir.Di return diags } -// declarations sorts claims into the declarations they mount, ordered by the +// declarations sorts uses into the declarations they mount, ordered by the // pointer each is written at: a property of the document rather than of the // order it was lowered in. -func declarations(claims []operationIDClaim, written *writtenTree) []declaration { - groups := byDeclaration(claims) +func declarations(uses []operationIDUse, written *writtenTree) []declaration { + groups := byDeclaration(uses) decls := make([]declaration, 0, len(groups)) for _, group := range groups { decls = append(decls, declare(group, written)) @@ -122,7 +122,7 @@ func declarations(claims []operationIDClaim, written *writtenTree) []declaration return decls } -// byDeclaration partitions claims by the declaration they mount. Claims mount +// byDeclaration partitions uses by the declaration they mount. Uses mount // one when they share the node declaring it (a $ref, YAML alias or merge key // reuse) or resolve to one declaration pointer. A reference naming this // document by its file name does both. One through a directory, like @@ -131,24 +131,24 @@ func declarations(claims []operationIDClaim, written *writtenTree) []declaration // // Neither test can turn a conflict into a reuse, since each identifies one // declaration. -func byDeclaration(claims []operationIDClaim) [][]operationIDClaim { - sets := newDisjointSets(len(claims)) - byNode := make(map[*yaml.Node]int, len(claims)) - byDecl := make(map[jsontext.Pointer]int, len(claims)) - for i, cl := range claims { +func byDeclaration(uses []operationIDUse) [][]operationIDUse { + sets := newDisjointSets(len(uses)) + byNode := make(map[*yaml.Node]int, len(uses)) + byDecl := make(map[jsontext.Pointer]int, len(uses)) + for i, cl := range uses { if cl.node != nil { joinOn(sets, byNode, cl.node, i) } joinOn(sets, byDecl, cl.ptrs.decl, i) } - groups := make([][]operationIDClaim, 0, len(claims)) + groups := make([][]operationIDUse, 0, len(uses)) for _, members := range sets.members { if len(members) == 0 { continue } - group := make([]operationIDClaim, 0, len(members)) + group := make([]operationIDUse, 0, len(members)) for _, i := range members { - group = append(group, claims[i]) + group = append(group, uses[i]) } groups = append(groups, group) } @@ -162,7 +162,7 @@ func byDeclaration(claims []operationIDClaim) [][]operationIDClaim { // declaration is written, and neither is a reference into another document; a // declaration no claim is written at is taken to be at the least of its claims' // declaration pointers. -func declare(group []operationIDClaim, written *writtenTree) declaration { +func declare(group []operationIDUse, written *writtenTree) declaration { var writtenAt, own, reused []jsontext.Pointer for _, cl := range group { switch { @@ -176,7 +176,7 @@ func declare(group []operationIDClaim, written *writtenTree) declaration { reused = append(reused, cl.ptrs.mount) } } - at := slices.MinFunc(group, func(a, b operationIDClaim) int { return cmp.Compare(a.ptrs.decl, b.ptrs.decl) }).ptrs.decl + at := slices.MinFunc(group, func(a, b operationIDUse) int { return cmp.Compare(a.ptrs.decl, b.ptrs.decl) }).ptrs.decl if len(writtenAt) > 0 { at = slices.Min(writtenAt) } @@ -236,12 +236,12 @@ type disjointSets struct { members [][]int // set → its items; empty once merged into another } -func newDisjointSets(n int) *disjointSets { - disjointSetsValue := &disjointSets{set: make([]int, n), members: make([][]int, n)} - for i := range n { - disjointSetsValue.set[i], disjointSetsValue.members[i] = i, []int{i} +func newDisjointSets(count int) *disjointSets { + disjointSets := &disjointSets{set: make([]int, count), members: make([][]int, count)} + for i := range count { + disjointSets.set[i], disjointSets.members[i] = i, []int{i} } - return disjointSetsValue + return disjointSets } // union merges the sets holding items a and b. The smaller set's items move, so diff --git a/compilers/openapi/internal/operation/operationids_internal_test.go b/compilers/openapi/internal/operation/operationids_internal_test.go index cd2dd1436..85060f789 100644 --- a/compilers/openapi/internal/operation/operationids_internal_test.go +++ b/compilers/openapi/internal/operation/operationids_internal_test.go @@ -77,12 +77,12 @@ func TestDeclare_ReadsWhereADeclarationIsWritten(t *testing.T) { root, operation := writtenOperation(t) for _, tc := range []struct { name string - claims []operationIDClaim + claims []operationIDUse want declaration }{ { name: "an alias site sorting first", - claims: []operationIDClaim{ + claims: []operationIDUse{ {node: operation, ptrs: operationPointers{mount: "/paths/~1a/get", decl: "/paths/~1a/get"}}, {node: operation, ptrs: operationPointers{mount: "/paths/~1z/get", decl: "/paths/~1z/get"}}, }, @@ -90,7 +90,7 @@ func TestDeclare_ReadsWhereADeclarationIsWritten(t *testing.T) { }, { name: "a ref sorting first", - claims: []operationIDClaim{ + claims: []operationIDUse{ {node: operation, ptrs: operationPointers{mount: "/paths/~1r/get", decl: "/paths/~1z/get"}}, {node: operation, ptrs: operationPointers{mount: "/paths/~1z/get", decl: "/paths/~1z/get"}}, }, @@ -98,7 +98,7 @@ func TestDeclare_ReadsWhereADeclarationIsWritten(t *testing.T) { }, { name: "written where no claim is mounted", - claims: []operationIDClaim{ + claims: []operationIDUse{ {node: operation, ptrs: operationPointers{mount: "/paths/~1y/get", decl: "/paths/~1z/get"}}, {node: operation, ptrs: operationPointers{mount: "/paths/~1x/get", decl: "/paths/~1z/get"}}, }, @@ -106,7 +106,7 @@ func TestDeclare_ReadsWhereADeclarationIsWritten(t *testing.T) { }, { name: "written nowhere the tree holds", - claims: []operationIDClaim{ + claims: []operationIDUse{ {node: operation, ptrs: operationPointers{mount: "/paths/~1y/get", decl: "/paths/~1y/get"}}, {node: operation, ptrs: operationPointers{mount: "/paths/~1x/get", decl: "/paths/~1x/get"}}, }, @@ -117,7 +117,7 @@ func TestDeclare_ReadsWhereADeclarationIsWritten(t *testing.T) { t.Parallel() reversed := slices.Clone(tc.claims) slices.Reverse(reversed) - for _, claims := range [][]operationIDClaim{tc.claims, reversed} { + for _, claims := range [][]operationIDUse{tc.claims, reversed} { got := declare(claims, newWrittenTree(root)) assert.Empty(t, cmp.Diff(tc.want, got, cmp.AllowUnexported(declaration{}))) } @@ -134,13 +134,13 @@ func TestDeclare_ReadsWhereADeclarationIsWritten(t *testing.T) { func TestByDeclaration_GroupsByNodeOrDeclarationPointer(t *testing.T) { t.Parallel() shared, copied, other := &yaml.Node{}, &yaml.Node{}, &yaml.Node{} - a := operationIDClaim{node: shared, ptrs: operationPointers{mount: "/paths/~1a/get", decl: "/paths/~1a/get"}} - b := operationIDClaim{node: shared, ptrs: operationPointers{mount: "/paths/~1b/get", decl: "/components/pathItems/S/get"}} - operationIDClaimValue := operationIDClaim{node: copied, ptrs: operationPointers{mount: "/paths/~1c/get", decl: "/components/pathItems/S/get"}} - otherOperationIDClaim := operationIDClaim{node: other, ptrs: operationPointers{mount: "/paths/~1d/get", decl: "/paths/~1d/get"}} + a := operationIDUse{node: shared, ptrs: operationPointers{mount: "/paths/~1a/get", decl: "/paths/~1a/get"}} + b := operationIDUse{node: shared, ptrs: operationPointers{mount: "/paths/~1b/get", decl: "/components/pathItems/S/get"}} + use := operationIDUse{node: copied, ptrs: operationPointers{mount: "/paths/~1c/get", decl: "/components/pathItems/S/get"}} + otherOperationIDUse := operationIDUse{node: other, ptrs: operationPointers{mount: "/paths/~1d/get", decl: "/paths/~1d/get"}} want := [][]jsontext.Pointer{{"/paths/~1a/get", "/paths/~1b/get", "/paths/~1c/get"}, {"/paths/~1d/get"}} - for _, claims := range [][]operationIDClaim{{a, b, operationIDClaimValue, otherOperationIDClaim}, {operationIDClaimValue, a, otherOperationIDClaim, b}, {otherOperationIDClaim, operationIDClaimValue, b, a}} { + for _, claims := range [][]operationIDUse{{a, b, use, otherOperationIDUse}, {use, a, otherOperationIDUse, b}, {otherOperationIDUse, use, b, a}} { var got [][]jsontext.Pointer for _, group := range byDeclaration(claims) { var mounts []jsontext.Pointer @@ -150,8 +150,8 @@ func TestByDeclaration_GroupsByNodeOrDeclarationPointer(t *testing.T) { slices.Sort(mounts) got = append(got, mounts) } - slices.SortFunc(got, func(pointers, pointersValue []jsontext.Pointer) int { - return strings.Compare(string(pointers[0]), string(pointersValue[0])) + slices.SortFunc(got, func(pointers, otherPointers []jsontext.Pointer) int { + return strings.Compare(string(pointers[0]), string(otherPointers[0])) }) assert.Empty(t, cmp.Diff(want, got)) } @@ -162,13 +162,13 @@ func TestByDeclaration_GroupsByNodeOrDeclarationPointer(t *testing.T) { // at one declaration pointer, never through the missing node they share. func TestByDeclaration_ANilNodeGroupsByDeclarationPointerAlone(t *testing.T) { t.Parallel() - apart := byDeclaration([]operationIDClaim{ + apart := byDeclaration([]operationIDUse{ {ptrs: operationPointers{mount: "/paths/~1a/get", decl: "/paths/~1a/get"}}, {ptrs: operationPointers{mount: "/paths/~1b/get", decl: "/paths/~1b/get"}}, }) assert.Len(t, apart, 2, "two claims with no node are two declarations") - together := byDeclaration([]operationIDClaim{ + together := byDeclaration([]operationIDUse{ {ptrs: operationPointers{mount: "/paths/~1a/get", decl: "/components/pathItems/S/get"}}, {ptrs: operationPointers{mount: "/paths/~1b/get", decl: "/components/pathItems/S/get"}}, }) @@ -220,7 +220,7 @@ func TestDeclaringNode_FollowsAnAliasOneHop(t *testing.T) { // declared. func TestOperationIDClaims_AddSkipsAnEmptyOperationID(t *testing.T) { t.Parallel() - claims := newOperationIDClaims() + claims := newOperationIDUses() claims.add(&soa.Operation{}, operationPointers{mount: "/paths/~1a/get", decl: "/paths/~1a/get"}) assert.Empty(t, claims.names, "nothing was claimed, so nothing is queued to report") diff --git a/compilers/openapi/internal/operation/operations.go b/compilers/openapi/internal/operation/operations.go index 3bbfe2ffc..25bd18098 100644 --- a/compilers/openapi/internal/operation/operations.go +++ b/compilers/openapi/internal/operation/operations.go @@ -58,14 +58,14 @@ func LowerService(ctx context.Context, serviceContext service.Ctx, ts *compile.T diags = append(diags, pathsDiags...) groups := newServiceGroups(serviceContext.Doc.GetTags()) loweringState := operationLoweringState{ - types: ts, claims: newOperationIDClaims(), servers: reg, schemes: schemes, + types: ts, uses: newOperationIDUses(), servers: reg, schemes: schemes, kept: newKeptOnce(), links: &Links{}, } diags = append(diags, lowerPaths(ctx, serviceContext, loweringState, groups, &svc)...) diags = append(diags, lowerWebhooks(ctx, serviceContext, loweringState, groups, &svc)...) // After both walks: whether an operationId is unique is a question about // every operation the service mounts, callbacks included. - diags = append(diags, loweringState.claims.report(serviceContext)...) + diags = append(diags, loweringState.uses.report(serviceContext)...) groups.markSharedRoutes() svc.Groups = groups.finalize() tagDefs, tagDiags := lowerTagDefs(serviceContext) @@ -103,7 +103,7 @@ type Lowered struct { // and handed down by value, since each field is the shared accumulator itself. type operationLoweringState struct { types *compile.Types - claims *operationIDClaims + uses *operationIDUses servers *servers.Registry schemes *auth.Registry kept *keptOnce @@ -228,7 +228,7 @@ func lowerOperation(serviceContext service.Ctx, loweringState operationLoweringS own, serverDiags := loweringState.servers.Declared(serviceContext, src.GetServers(), decl) operation.Servers = own diags = append(diags, serverDiags...) - loweringState.claims.add(src, operationCtx.ptrs) + loweringState.uses.add(src, operationCtx.ptrs) return operation, extra, diags } diff --git a/compilers/openapi/internal/operation/operations_test.go b/compilers/openapi/internal/operation/operations_test.go index 5d90791c6..077dc815f 100644 --- a/compilers/openapi/internal/operation/operations_test.go +++ b/compilers/openapi/internal/operation/operations_test.go @@ -263,8 +263,8 @@ func TestProvenance_EveryPointerResolvesInSource(t *testing.T) { } checked := 0 - for id, td := range doc.Types { - checked += check("type", string(id), td.Common().Provenance.Pointer) + for id, typeDef := range doc.Types { + checked += check("type", string(id), typeDef.Common().Provenance.Pointer) } require.NotEmpty(t, doc.Services, "the spec lowers to at least one service") for _, irOperation := range operationsOf(doc) { @@ -508,10 +508,11 @@ func TestGhostRefs_AllResolversDegradeGracefully(t *testing.T) { doc, diags := parseFull(t, ghostRefsSpec) require.NotEmpty(t, diags, "unresolved refs reported") - // And the skips themselves are silent: every diagnostic here is the load - // phase's report of a $ref it followed to nothing, at the $ref itself - // (GitHub #385). A skip lowering an empty stand-in instead would report on a - // construct the document never wrote, beside the one report per $ref below. + // And the skips themselves report nothing: every diagnostic here is the + // load phase's report of a $ref it followed to nothing, at the $ref itself + // (GitHub #385). A skip lowering an empty placeholder instead would report + // on a construct the document never wrote, beside the one report per $ref + // below. wantRefs := map[string]string{ "/paths/~1a/parameters/0": "#/components/parameters/GhostParam", "/paths/~1a/get/callbacks/good/{$url}": "#/components/pathItems/GhostInner", @@ -530,11 +531,11 @@ func TestGhostRefs_AllResolversDegradeGracefully(t *testing.T) { assert.Contains(t, message, fmt.Sprintf("unresolved $ref %q", ref), "names the reference that failed") } - // What each skip has to do is contribute nothing — not an empty stand-in. - // Asserting only "no panic" leaves that unheld: lowering an unresolvable path - // item as an empty one, rather than skipping it, passes a no-panic test and - // every other test in this repo, while putting a path the document does not - // declare into the IR. + // What each skip has to do is contribute nothing — not an empty + // placeholder. Asserting only "no panic" leaves that unheld: lowering an + // unresolvable path item as an empty one, rather than skipping it, passes a + // no-panic test and every other test in this repo, while putting a path the + // document does not declare into the IR. require.Len(t, doc.Services[0].Groups, 1, "the ghost webhook adds no group of its own") operations := doc.Services[0].Groups[0].Operations require.Len(t, operations, 1, @@ -825,9 +826,9 @@ func TestOperations_OwnServersSurviveBesideExtensions(t *testing.T) { // TestLowerService_PercentEncodedEntryRefKeepsTheDeclaredCoordinate covers the // same identity defect on the components that are not schemas, where it was -// wholly silent. Their entries resolve through the library, so the value arrived -// intact and no unresolved-ref was ever emitted; only the pointer the entry -// carried stayed encoded, and every ID hoisted beneath it inherited the +// wholly unreported. Their entries resolve through the library, so the value +// arrived intact and no unresolved-ref was ever emitted; only the pointer the +// entry carried stayed encoded, and every ID hoisted beneath it inherited the // encoding — here the response's own content schema. func TestLowerService_PercentEncodedEntryRefKeepsTheDeclaredCoordinate(t *testing.T) { t.Parallel() @@ -858,7 +859,7 @@ components: } // TestLowerService_LeavesTheDeclaredSchemesAsTheyWere pins that the walk adds -// the scheme an unresolved name stands for to a registry of its own, and +// the scheme an unresolved name names to a registry of its own, and // returns it: the map the compiler's run lowered and handed in still holds what // securitySchemes declares, and nothing else. func TestLowerService_LeavesTheDeclaredSchemesAsTheyWere(t *testing.T) { diff --git a/compilers/openapi/internal/operation/params.go b/compilers/openapi/internal/operation/params.go index 3c4cd5834..176ed97b3 100644 --- a/compilers/openapi/internal/operation/params.go +++ b/compilers/openapi/internal/operation/params.go @@ -32,7 +32,7 @@ import ( // target for a referenced entry, else the list entry itself (issue #107). Its // ID is rooted at mount, the operation's mount pointer, not at the declaration // it was copied from; a repeat of one name and location keeps an ID of its own -// (paramLedger). +// (parameterNumbering). func lowerParameters(serviceContext service.Ctx, loweringState operationLoweringState, mount jsontext.Pointer, params []sourcedParam) ([]ir.Parameter, []ir.HTTPParamBinding, []ir.Diagnostic) { if len(params) == 0 { return nil, nil, nil @@ -40,18 +40,18 @@ func lowerParameters(serviceContext service.Ctx, loweringState operationLowering var diags []ir.Diagnostic logical := make([]ir.Parameter, 0, len(params)) bindings := make([]ir.HTTPParamBinding, 0, len(params)) - ledger := newParamLedger(mount) + numbering := newParameterNumbering(mount) for _, sp := range params { pc := serviceContext if sp.in != nil { pc = *sp.in } - p, dc, pptr := service.Declared[soa.Parameter](pc, sp.ref, sp.pointer) - if p == nil { + parameter, dc, pptr := service.Declared[soa.Parameter](pc, sp.ref, sp.pointer) + if parameter == nil { continue } - id := ledger.next(p.GetName(), string(p.GetIn())) - param, binding, paramDiags := lowerParameter(dc, loweringState, id, p, pptr) + id := numbering.next(parameter.GetName(), string(parameter.GetIn())) + param, binding, paramDiags := lowerParameter(dc, loweringState, id, parameter, pptr) diags = append(diags, paramDiags...) // A summary or description beside a $ref of the entry's chain documents // this use of the parameter, over what its declaration says (GitHub #610). @@ -69,61 +69,61 @@ func lowerParameters(serviceContext service.Ctx, loweringState operationLowering // lowerParameter lowers one resolved parameter into its logical Parameter and // HTTP binding, both naming the parameter by id. Path parameters are always // required regardless of the declared flag (OpenAPI requires it). -func lowerParameter(serviceContext service.Ctx, loweringState operationLoweringState, id ir.ParameterID, p *soa.Parameter, pptr jsontext.Pointer) (ir.Parameter, ir.HTTPParamBinding, []ir.Diagnostic) { - name, in := p.GetName(), p.GetIn() +func lowerParameter(serviceContext service.Ctx, loweringState operationLoweringState, id ir.ParameterID, parameter *soa.Parameter, pptr jsontext.Pointer) (ir.Parameter, ir.HTTPParamBinding, []ir.Diagnostic) { + name, in := parameter.GetName(), parameter.GetIn() param := ir.Parameter{ ID: id, Name: ir.NamingFor(name), - Required: p.GetRequired() || in == soa.ParameterInPath, + Required: parameter.GetRequired() || in == soa.ParameterInPath, Provenance: serviceContext.Place().At(pptr), } - style, explode := styleAndExplode(p, in) + style, explode := styleAndExplode(parameter, in) binding := ir.HTTPParamBinding{ Param: id, Location: httpLocation(in), WireName: name, Style: style, Explode: explode, - AllowReserved: p.GetAllowReserved(), + AllowReserved: parameter.GetAllowReserved(), // Read whatever the location, as allowReserved is: the validator refuses // it outside in: query, and warns where the style gives it no effect. - AllowEmptyValue: p.GetAllowEmptyValue(), + AllowEmptyValue: parameter.GetAllowEmptyValue(), } - elected, diags := fillParamType(serviceContext, loweringState, ¶m, &binding, p, pptr) - if elected.mediaType != "" && p.Style == nil { + chosen, diags := fillParamType(serviceContext, loweringState, ¶m, &binding, parameter, pptr) + if chosen.mediaType != "" && parameter.Style == nil { // The media type serializes the value, so no style is stated for it. binding.Style = "" } - diags = append(diags, fillParamDetail(serviceContext, ¶m, p, pptr, elected)...) - if p.AllowReserved != nil { + diags = append(diags, fillParamDetail(serviceContext, ¶m, parameter, pptr, chosen)...) + if parameter.AllowReserved != nil { return param, binding, diags } // Read once the keys are kept, and only where the parameter decides nothing: // its own key, else the nearest object it carries stating one. reserved, promoted := promotion.AllowReserved(serviceContext.Promoter(), - promotion.Carried(serviceContext.Promoter(), param.Unmodeled, elected.carries...), ¶m.Provenance) + promotion.Carried(serviceContext.Promoter(), param.Unmodeled, chosen.carries...), ¶m.Provenance) binding.AllowReserved = reserved return param, binding, append(diags, promoted...) } -// fillParamType lowers a parameter's type from the spelling electTypeSpelling -// elects — its schema, or the single media-type entry of a content-style +// fillParamType lowers a parameter's type from the spelling chooseTypeSpelling +// chooses — its schema, or the single media-type entry of a content-style // parameter, whose media type goes on the binding. Constraints come from that // same schema position; the default comes from it too, falling back to its $ref // target (docs/compilers/openapi.md#ref-use-site). -func fillParamType(serviceContext service.Ctx, loweringState operationLoweringState, param *ir.Parameter, binding *ir.HTTPParamBinding, p *soa.Parameter, pptr jsontext.Pointer) (typeSpelling, []ir.Diagnostic) { - elected, diags := electTypeSpelling(serviceContext, loweringState, p.GetSchema(), p.GetContent(), p.GetRootNode(), pptr, +func fillParamType(serviceContext service.Ctx, loweringState operationLoweringState, param *ir.Parameter, binding *ir.HTTPParamBinding, parameter *soa.Parameter, pptr jsontext.Pointer) (typeSpelling, []ir.Diagnostic) { + chosen, diags := chooseTypeSpelling(serviceContext, loweringState, parameter.GetSchema(), parameter.GetContent(), parameter.GetRootNode(), pptr, "parameter", "ir.Parameter") - paramType, typeDiags := schema.CarriedRef(elected.ctx.Ctx, loweringState.types, schema.TopLevelDepth, serviceContext.Statements().Of(elected.js), elected.pointer) + paramType, typeDiags := schema.CarriedRef(chosen.ctx.Ctx, loweringState.types, schema.TopLevelDepth, serviceContext.Statements().Of(chosen.js), chosen.pointer) diags = append(diags, typeDiags...) param.Type = paramType - binding.ContentType = elected.mediaType + binding.ContentType = chosen.mediaType var written ir.Unmodeled - diags = append(diags, fillParamSchema(elected.ctx, loweringState.types, param, &written, elected.js, elected.pointer)...) + diags = append(diags, fillParamSchema(chosen.ctx, loweringState.types, param, &written, chosen.js, chosen.pointer)...) // What the schema keeps whole it keeps once, its inner keys not again. promotion.DropContained(serviceContext.Promoter(), &written) - param.Unmodeled = annotation.MergeUnmodeled(annotation.Under(elected.schemaScope(), written), elected.unmodeled) - return elected, diags + param.Unmodeled = annotation.MergeUnmodeled(annotation.Under(chosen.schemaScope(), written), chosen.unmodeled) + return chosen, diags } // fillParamSchema reads a parameter schema's default value and scalar @@ -144,8 +144,8 @@ func fillParamSchema(serviceContext service.Ctx, ts *compile.Types, param *ir.Pa if js == nil || !js.IsSchema() { return nil } - s := js.GetSchema() - if s == nil { + oasSchema := js.GetSchema() + if oasSchema == nil { return nil } // schema.UseOf reads the end of a $ref chain, since one hop would take the @@ -155,14 +155,19 @@ func fillParamSchema(serviceContext service.Ctx, ts *compile.Types, param *ir.Pa def, diags := use.Default(serviceContext.Ctx, serviceContext.Statements().Of(js).Schema, pointer) param.Default = def - cons, consDiags := schema.CarrierConstraintsOf(serviceContext.Ctx, written, serviceContext.Statements().Of(js).Schema, use.FoldedAllOfEntries, param.Type, pointer) + cons, consDiags := schema.CarrierConstraintsOf(serviceContext.Ctx, written, serviceContext.Statements().Of(js).Schema, use.FlattenedAllOfEntries, param.Type, pointer) param.Constraints = cons diags = append(diags, consDiags...) - diags = append(diags, fillParamSchemaAnnotations(serviceContext, param, written, serviceContext.Statements().Of(js).Schema, use, pointer)...) + var pendingKeeps annotation.PendingKeeps + diags = append(diags, fillParamSchemaAnnotations(serviceContext, param, &pendingKeeps, serviceContext.Statements().Of(js).Schema, use, pointer)...) // A parameter is the third annotation.HomeCarrier, so the keywords beside a // $ref that the alias it resolves to cannot hold are kept here, exactly as a // property and a header keep them (schema.FillPropertyDetail). - return append(diags, schema.PreserveRefSiteKeywords(serviceContext.Ctx, ts, written, serviceContext.Statements().Of(js), param.Type, pointer)...) + diags = append(diags, schema.KeepRefSiteKeywords(serviceContext.Ctx, ts, &pendingKeeps, serviceContext.Statements().Of(js), param.Type, pointer, + schema.CarrierKeywordKeeps{"xml": func(unmodeled *ir.Unmodeled, statementSchema *statement.Schema, at jsontext.Pointer) []ir.Diagnostic { + return keepParamXML(serviceContext, unmodeled, statementSchema, at) + }})...) + return append(diags, schema.SettleCarrier(serviceContext.Ctx, written, &pendingKeeps, pointer)...) } // fillParamSchemaAnnotations records what a parameter's schema declares on the @@ -175,57 +180,65 @@ func fillParamSchema(serviceContext service.Ctx, ts *compile.Types, param *ir.Pa // win where both are set. Docs, deprecation and redaction read what use falls // back to (docs/compilers/openapi.md#ref-use-site); examples, xml and the // visibility keywords stay with the position, which they describe, and its -// folded entries. What has no field of the parameter goes to written. -func fillParamSchemaAnnotations(serviceContext service.Ctx, param *ir.Parameter, written *ir.Unmodeled, +// flattened entries, each added to pendingKeeps by its conjunct. +func fillParamSchemaAnnotations(serviceContext service.Ctx, param *ir.Parameter, pendingKeeps *annotation.PendingKeeps, statementSchema *statement.Schema, use schema.Use, pointer jsontext.Pointer, ) []ir.Diagnostic { - // Visibility is kept before the own-node guard, not after it. The guard exists - // so an annotation with a home on the node is not also copied to the carrier, - // but readOnly/writeOnly have no home on either: the residue a declaration - // keeps on its node skips this position because a parameter is an - // annotation.HomeCarrier, and ir.Parameter has no Visibility field. Keeping - // them after the guard would drop them for exactly the parameters whose - // schema owns a node — an object, an enum, an array. - var diags []ir.Diagnostic - for _, foldedAllOfEntry := range schema.FoldedEntriesInOverwriteOrder(use.FoldedAllOfEntries) { - diags = append(diags, preserveParamVisibility(serviceContext, written, foldedAllOfEntry.Node, foldedAllOfEntry.At)...) + // Visibility is kept before the own-node guard, not after it. The guard + // exists so an annotation with a home on the node is not also copied to the + // carrier, but readOnly/writeOnly have no home on either: the use-bound + // keywords a declaration keeps on its node skip this position because a + // parameter is an annotation.HomeCarrier, and ir.Parameter has no + // Visibility field. Keeping them after the guard would drop them for + // exactly the parameters whose schema owns a node — an object, an enum, an + // array. + flattenedEntryKeeps := make([]annotation.FlattenedEntryKept, 0, len(use.FlattenedAllOfEntries)) + for _, flattenedEntry := range use.FlattenedAllOfEntries { + var kept ir.Unmodeled + keptReports := keepParamVisibility(serviceContext, &kept, flattenedEntry.Node, flattenedEntry.At) + flattenedEntryKeeps = append(flattenedEntryKeeps, annotation.FlattenedEntryKept{At: flattenedEntry.At, Unmodeled: kept, Reports: keptReports}) } - diags = append(diags, preserveParamVisibility(serviceContext, written, statementSchema, pointer)...) + var own ir.Unmodeled + ownReports := keepParamVisibility(serviceContext, &own, statementSchema, pointer) + diags := schema.AddCarrierPendingKeeps(serviceContext.Ctx, pendingKeeps, statementSchema, pointer, own, flattenedEntryKeeps, ownReports) if schema.LoweredToOwnNode(serviceContext.Ctx, pointer, param.Type) { return diags } - a, readDiags := schema.ReadAnnotations(serviceContext.Ctx, use.SiteAt(serviceContext.Ctx, statementSchema, pointer), pointer) - diags = append(diags, readDiags...) + xmlKey := annotation.EntryKey("", "xml") + annotations, readReports := schema.ReadAnnotations(serviceContext.Ctx, use.SiteAt(serviceContext.Ctx, statementSchema, pointer), pointer) - param.Docs = a.Docs - if a.Deprecated { + param.Docs = annotations.Docs + if annotations.Deprecated { param.Deprecation = &ir.Deprecation{} } - if a.Sensitive { + if annotations.Sensitive { param.Secret = true } - if len(a.Examples) > 0 { - param.Examples = a.Examples + if len(annotations.Examples) > 0 { + param.Examples = annotations.Examples } - for _, foldedAllOfEntry := range slices.Backward(use.FoldedAllOfEntries) { - diags = append(diags, preserveParamXML(serviceContext, written, foldedAllOfEntry.Node, foldedAllOfEntry.At)...) + for _, flattenedEntry := range use.FlattenedAllOfEntries { + var kept ir.Unmodeled + keptDiags := keepParamXML(serviceContext, &kept, flattenedEntry.Node, flattenedEntry.At) + annotations.FlattenedEntries = append(annotations.FlattenedEntries, annotation.FlattenedEntryKept{At: flattenedEntry.At, Unmodeled: kept, Reports: annotation.ReportsOf(xmlKey, keptDiags...)}) } - diags = append(diags, preserveParamXML(serviceContext, written, statementSchema, pointer)...) - *written = annotation.MergeUnmodeled(*written, a.Unmodeled) + kept := annotations.Unmodeled + readReports = append(readReports, annotation.ReportsOf(xmlKey, keepParamXML(serviceContext, &kept, statementSchema, pointer)...)...) // Last, as it keeps only the keywords no reader above it kept, and everything - // annotation.Read recorded is already in written by this line. - return append(diags, schema.PreserveCarriedKeywords(serviceContext.Ctx, written, statementSchema, pointer)...) + // annotation.Read recorded is already in kept by this line. + readReports = append(readReports, schema.KeepCarriedKeywords(serviceContext.Ctx, &kept, statementSchema, pointer)...) + return append(diags, schema.AddCarrierPendingKeeps(serviceContext.Ctx, pendingKeeps, statementSchema, pointer, kept, annotations.FlattenedEntries, readReports)...) } -// preserveParamXML keeps a parameter schema's xml hints instead of dropping +// keepParamXML keeps a parameter schema's xml hints instead of dropping // them: ir.Parameter is the one annotation carrier with no XML field, and the -// hint is not inert at this position — a content-style parameter can bind +// hint has an effect at this position — a content-style parameter can bind // application/xml, the media type OpenAPI §4.8.26 conditions xml on, and the // binding records that content type. ReasonNoIRHome, since the IR can close the // gap by adding the field (GitHub #124). -func preserveParamXML(serviceContext service.Ctx, written *ir.Unmodeled, statementSchema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { +func keepParamXML(serviceContext service.Ctx, written *ir.Unmodeled, statementSchema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { at := pointer + ids.Ptr("xml") - kept, diags := annotation.PreserveSchemaKeyword(written, statementSchema, "xml", ir.ReasonNoIRHome, pointer, serviceContext.Place()) + kept, diags := annotation.KeepSchemaKeyword(written, statementSchema, "xml", ir.ReasonNoIRHome, pointer, serviceContext.Place()) if kept { diags = append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, "parameter schema xml hints have no ir.Parameter home; kept verbatim under Unmodeled")) @@ -233,7 +246,7 @@ func preserveParamXML(serviceContext service.Ctx, written *ir.Unmodeled, stateme return diags } -// preserveParamVisibility keeps the residue keywords a parameter schema writes +// keepParamVisibility keeps the use-bound keywords a parameter schema writes // that ir.Parameter has no field for. The rule // docs/compilers/openapi.md#use-bound-annotations lowers readOnly/writeOnly to // a Visibility, which only ir.Property has (ir/operation.go) — so at a @@ -244,28 +257,29 @@ func preserveParamXML(serviceContext service.Ctx, written *ir.Unmodeled, stateme // The list is asked of the schema package rather than restated here, so a // keyword added there is preserved here too instead of being dropped at this one // carrier. -func preserveParamVisibility(serviceContext service.Ctx, written *ir.Unmodeled, statementSchema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - var diags []ir.Diagnostic - for _, keyword := range schema.ResidueKeywords() { - if paramHoldsResidue(keyword) { +func keepParamVisibility(serviceContext service.Ctx, written *ir.Unmodeled, statementSchema *statement.Schema, pointer jsontext.Pointer) annotation.KeptReports { + var reports annotation.KeptReports + for _, keyword := range schema.UseBoundKeywords() { + if paramHoldsUseBoundKeyword(keyword) { continue } - at := pointer + ids.Ptr(keyword) - kept, keptDiags := annotation.PreserveSchemaKeyword(written, statementSchema, keyword, ir.ReasonNoIRHome, pointer, serviceContext.Place()) - diags = append(diags, keptDiags...) + at, key := pointer+ids.Ptr(keyword), annotation.EntryKey("", keyword) + kept, keptDiags := annotation.KeepSchemaKeyword(written, statementSchema, keyword, ir.ReasonNoIRHome, pointer, serviceContext.Place()) + reports = append(reports, annotation.ReportsOf(key, keptDiags...)...) if !kept { continue } - diags = append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, - "parameter schema %s has no ir.Parameter home; kept verbatim under Unmodeled", keyword)) + reports = append(reports, annotation.ReportsOf(key, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, + "parameter schema %s has no ir.Parameter home; kept verbatim under Unmodeled", keyword))...) } - return diags + return reports } -// paramHoldsResidue reports whether ir.Parameter has a field for a residue -// keyword. Only `default` does — Parameter.Default, which fillParamSchema -// fills — so recording it verbatim as well would give one declaration two homes. -func paramHoldsResidue(keyword string) bool { +// paramHoldsUseBoundKeyword reports whether ir.Parameter has a field for a +// use-bound keyword. Only `default` does — Parameter.Default, which +// fillParamSchema fills — so recording it verbatim as well would give one +// declaration two homes. +func paramHoldsUseBoundKeyword(keyword string) bool { return keyword == "default" } @@ -279,29 +293,31 @@ func paramHoldsResidue(keyword string) bool { // been preserved: a promotion reads the kept Unmodeled entries rather // than the source node, so a parameter whose x-* keys are not in the map yet // has nothing to promote from (GitHub #423). -func fillParamDetail(serviceContext service.Ctx, param *ir.Parameter, p *soa.Parameter, pptr jsontext.Pointer, elected typeSpelling) []ir.Diagnostic { - if d := p.GetDescription(); d != "" { - param.Docs.Description = d +func fillParamDetail(serviceContext service.Ctx, param *ir.Parameter, parameter *soa.Parameter, pptr jsontext.Pointer, chosen typeSpelling) []ir.Diagnostic { + if description := parameter.GetDescription(); description != "" { + param.Docs.Description = description } - if p.GetDeprecated() { + if parameter.GetDeprecated() { param.Deprecation = &ir.Deprecation{} } - own, diags := exampleList(serviceContext, p.GetExample(), p.GetExamples(), pptr) - if ex := positionExamples(own, elected.examples); len(ex) > 0 { + own, diags := exampleList(serviceContext, parameter.GetExample(), parameter.GetExamples(), pptr) + // The examples a position writes and its media type writes replace the + // schema's, neither replacing the other (GitHub #611). + if ex := slices.Concat(own, chosen.examples); len(ex) > 0 { param.Examples = ex } - pExt, extDiags := annotation.ExtensionsFrom(p.GetExtensions(), serviceContext.Place(), pptr) + pExt, extDiags := annotation.ExtensionsFrom(parameter.GetExtensions(), serviceContext.Place(), pptr) diags = append(diags, extDiags...) param.Unmodeled = annotation.MergeUnmodeled(param.Unmodeled, pExt) - diags = append(diags, annotation.UnknownKeysIn(¶m.Unmodeled, p, serviceContext.Place(), pptr)...) + diags = append(diags, annotation.UnknownKeysIn(¶m.Unmodeled, parameter, serviceContext.Place(), pptr)...) // Redaction and deprecation hold where the parameter or an object it carries // states them, as they hold where its schema's $ref target does; a value is // read at the nearest key writing one, and a misfit reported at each. - fallbackReferent := serviceContext.Promoter().WithOwnCarriedState(schema.FallbackKeysForCarrier(serviceContext.Ctx, serviceContext.Statements().Of(elected.js), param.Type, elected.pointer), param.Unmodeled, - elected.carries...) - carried := promotion.Carried(serviceContext.Promoter(), param.Unmodeled, elected.carries...) + fallbackReferent := serviceContext.Promoter().WithOwnCarriedState(schema.FallbackKeysForCarrier(serviceContext.Ctx, serviceContext.Statements().Of(chosen.js), param.Type, chosen.pointer), param.Unmodeled, + chosen.carries...) + carried := promotion.Carried(serviceContext.Promoter(), param.Unmodeled, chosen.carries...) diags = append(diags, schema.PromoteUse(serviceContext.Ctx, fallbackReferent, carried, ¶m.Deprecation, ¶m.Secret, ¶m.Provenance)...) - return append(diags, promoteShadowed(serviceContext, param.Unmodeled, elected.carries...)...) + return append(diags, promoteShadowed(serviceContext, param.Unmodeled, chosen.carries...)...) } // promoteShadowed reads, for its findings alone, the deprecation and redaction @@ -323,23 +339,23 @@ func promoteShadowed(serviceContext service.Ctx, own ir.Unmodeled, scopes ...str // styleAndExplode returns a parameter's serialization style and its explode // flag. The style is the written one, else the location's default, which a // binding states because the location fixes it, unless the parameter's content -// is elected, whose media type serializes the value (lowerParameter). Explode is only what the +// is chosen, whose media type serializes the value (lowerParameter). Explode is only what the // parameter writes and nil otherwise: its default depends on the style, so filling // it in would present the default as a declaration, and a deepObject that writes // none would read as one that wrote false (GitHub #627). -func styleAndExplode(p *soa.Parameter, in soa.ParameterIn) (string, *bool) { +func styleAndExplode(parameter *soa.Parameter, in soa.ParameterIn) (string, *bool) { style := defaultParamStyle(in) - if p.Style != nil { - style = string(*p.Style) + if parameter.Style != nil { + style = string(*parameter.Style) } // A declared explode lowers as declared wherever it is written, for the same // reason a declared style does: 3.2 forbids both at in: querystring, but // dropping content the document states is an emitter's call, not a // compiler's, and this position has an IR field to hold it. - if p.Explode == nil { + if parameter.Explode == nil { return style, nil } - return style, new(*p.Explode) + return style, new(*parameter.Explode) } // defaultParamStyle returns the OpenAPI default serialization style for a @@ -393,17 +409,17 @@ type sourcedParam struct { // position recomputed from the merged slice (issue #36), and a $ref'd path // item's are under its own declaration pointer, not the path it is mounted at // (issue #107). -func mergeParameters(b *typed.Bindings, pathParams []sourcedParam, operationParams []*soa.ReferencedParameter, +func mergeParameters(bindings *typed.Bindings, pathParams []sourcedParam, operationParams []*soa.ReferencedParameter, operationDeclPtr jsontext.Pointer, ) []sourcedParam { merged := make([]sourcedParam, 0, len(operationParams)+len(pathParams)) - merged = appendSourced(b, merged, operationParams, operationDeclPtr, nil, nil) + merged = appendSourced(bindings, merged, operationParams, operationDeclPtr, nil, nil) if len(pathParams) == 0 { return merged } - shadowed := shadowedKeys(b, operationParams) + shadowed := shadowedKeys(bindings, operationParams) for _, sourcedParam := range pathParams { - if key, ok := paramKey(b, sourcedParam.ref); ok && shadowed[key] { + if key, ok := paramKey(bindings, sourcedParam.ref); ok && shadowed[key] { continue } merged = append(merged, sourcedParam) @@ -416,24 +432,24 @@ func mergeParameters(b *typed.Bindings, pathParams []sourcedParam, operationPara // skipping any whose (name, in) key is in shadowed. A nil shadowed map reads as // all-false, which is what the operation side passes: operation parameters are // never shadowed, and are lowered in the operation's own context (a nil in). -func appendSourced(b *typed.Bindings, dst []sourcedParam, params []*soa.ReferencedParameter, base jsontext.Pointer, +func appendSourced(bindings *typed.Bindings, dst []sourcedParam, params []*soa.ReferencedParameter, base jsontext.Pointer, shadowed map[ids.ParamSlot]bool, in *service.Ctx, ) []sourcedParam { - for i, p := range params { - if key, ok := paramKey(b, p); ok && shadowed[key] { + for i, parameter := range params { + if key, ok := paramKey(bindings, parameter); ok && shadowed[key] { continue } - dst = append(dst, sourcedParam{ref: p, pointer: base + ids.Ptr("parameters", strconv.Itoa(i)), in: in}) + dst = append(dst, sourcedParam{ref: parameter, pointer: base + ids.Ptr("parameters", strconv.Itoa(i)), in: in}) } return dst } // shadowedKeys returns the (in, name) identities declared by operationParams, // so a path-item parameter sharing one is left out of the merge as a duplicate. -func shadowedKeys(b *typed.Bindings, operationParams []*soa.ReferencedParameter) map[ids.ParamSlot]bool { +func shadowedKeys(bindings *typed.Bindings, operationParams []*soa.ReferencedParameter) map[ids.ParamSlot]bool { shadowed := make(map[ids.ParamSlot]bool, len(operationParams)) - for _, p := range operationParams { - if key, ok := paramKey(b, p); ok { + for _, parameter := range operationParams { + if key, ok := paramKey(bindings, parameter); ok { shadowed[key] = true } } @@ -441,16 +457,16 @@ func shadowedKeys(b *typed.Bindings, operationParams []*soa.ReferencedParameter) } // paramKey builds the identity a parameter is merged by (ids.SlotOf), read -// through the bindings b, as the lowering reads it. -func paramKey(b *typed.Bindings, rp *soa.ReferencedParameter) (ids.ParamSlot, bool) { - p := componentlookup.Object[soa.Parameter](b, rp) - if p == nil { +// through bindings, as the lowering reads it. +func paramKey(bindings *typed.Bindings, rp *soa.ReferencedParameter) (ids.ParamSlot, bool) { + parameter := componentlookup.Object[soa.Parameter](bindings, rp) + if parameter == nil { return ids.ParamSlot{}, false } - return ids.SlotOf(p.GetName(), string(p.GetIn())), true + return ids.SlotOf(parameter.GetName(), string(parameter.GetIn())), true } -// paramLedger numbers the parameters of one operation, or of a path item +// parameterNumbering numbers the parameters of one operation, or of a path item // mounting none, in list order, and finds each repeat by its slot // (ids.SlotOf). A repeat is numbered among those spelled alike, as an ID is // derived from the name as written (ids.Param), so X-Trace and x-trace keep @@ -458,7 +474,7 @@ func paramKey(b *typed.Bindings, rp *soa.ReferencedParameter) (ids.ParamSlot, bo // // A repeat in any list, in whichever document writes it, is load's to report, // once, where it is written (load.listRepeats). -type paramLedger struct { +type parameterNumbering struct { mount jsontext.Pointer seen map[paramSpelling]int } @@ -469,19 +485,20 @@ type paramSpelling struct { name, in string } -// newParamLedger returns a ledger for the operation mounted at mount. -func newParamLedger(mount jsontext.Pointer) *paramLedger { - return ¶mLedger{mount: mount, seen: map[paramSpelling]int{}} +// newParameterNumbering returns an empty numbering for the operation mounted at +// mount. +func newParameterNumbering(mount jsontext.Pointer) *parameterNumbering { + return ¶meterNumbering{mount: mount, seen: map[paramSpelling]int{}} } // next returns the ID of the parameter holding name in in. -func (l *paramLedger) next(name, in string) ir.ParameterID { +func (l *parameterNumbering) next(name, in string) ir.ParameterID { return ids.Param(l.mount, name, in, l.count(name, in)) } // count records one more holder of name in in, and returns which holder of // that spelling it is, counting from one. -func (l *paramLedger) count(name, in string) int { +func (l *parameterNumbering) count(name, in string) int { spelled := paramSpelling{name: name, in: in} l.seen[spelled]++ return l.seen[spelled] diff --git a/compilers/openapi/internal/operation/params_identity_test.go b/compilers/openapi/internal/operation/params_identity_test.go index c3dae04a5..9b81f01e7 100644 --- a/compilers/openapi/internal/operation/params_identity_test.go +++ b/compilers/openapi/internal/operation/params_identity_test.go @@ -139,8 +139,8 @@ func repeatSpec(pathLevel, operationLevel []string) string { return "" } out := indent + "parameters:\n" - for _, e := range entries { - out += indent + " - " + e + "\n" + for _, entry := range entries { + out += indent + " - " + entry + "\n" } return out } diff --git a/compilers/openapi/internal/operation/params_internal_test.go b/compilers/openapi/internal/operation/params_internal_test.go index 6ee092bc3..559d15e2f 100644 --- a/compilers/openapi/internal/operation/params_internal_test.go +++ b/compilers/openapi/internal/operation/params_internal_test.go @@ -33,20 +33,20 @@ func TestFillParamSchema_EmptyEitherNoOp(t *testing.T) { assert.Empty(t, diags) } -// TestPreserveParamXML_ModelSetWithoutRawSourceRecordsNothing pins the same guard +// TestKeepParamXML_ModelSetWithoutRawSourceRecordsNothing pins the same guard // on the parameter carrier. The hint is kept verbatim, so it is read off the // source node, and a schema whose model reports xml with no bytes behind it must // record nothing rather than announce a preservation it did not make. -func TestPreserveParamXML_ModelSetWithoutRawSourceRecordsNothing(t *testing.T) { +func TestKeepParamXML_ModelSetWithoutRawSourceRecordsNothing(t *testing.T) { t.Parallel() lowerer, _ := loweredFor(t, openapitest.ComponentSpec(" A: {type: string}\n")) - s := &oas3.Schema{XML: &oas3.XML{}} - require.NotNil(t, s.GetXML(), "the model reports the hint as set") - _, backed := standaloneSchema(s).Key("xml") + schema := &oas3.Schema{XML: &oas3.XML{}} + require.NotNil(t, schema.GetXML(), "the model reports the hint as set") + _, backed := standaloneSchema(schema).Key("xml") require.False(t, backed, "and no raw node backs it") var written ir.Unmodeled - diags := preserveParamXML(lowerer.ctx, &written, standaloneSchema(s), "/paths/~1x/get/parameters/0/schema") + diags := keepParamXML(lowerer.ctx, &written, standaloneSchema(schema), "/paths/~1x/get/parameters/0/schema") assert.Nil(t, written, "no entry is recorded when there are no bytes to record") assert.Empty(t, diags, "and nothing is announced, so the two channels agree") @@ -114,9 +114,9 @@ func standalone(js *oas3.JSONSchema[oas3.Referenceable]) *statement.Statement { // standaloneSchema is standalone for a schema object decoded alone, nil for a // nil s. -func standaloneSchema(s *oas3.Schema) *statement.Schema { - if s == nil { +func standaloneSchema(schema *oas3.Schema) *statement.Schema { + if schema == nil { return nil } - return standalone(oas3.NewJSONSchemaFromSchema[oas3.Referenceable](s)).Schema + return standalone(oas3.NewJSONSchemaFromSchema[oas3.Referenceable](schema)).Schema } diff --git a/compilers/openapi/internal/operation/params_querystring_test.go b/compilers/openapi/internal/operation/params_querystring_test.go index 431774d40..a97d88046 100644 --- a/compilers/openapi/internal/operation/params_querystring_test.go +++ b/compilers/openapi/internal/operation/params_querystring_test.go @@ -92,7 +92,7 @@ func TestParams_QueryStringDeclaredStyleIsKeptAndReported(t *testing.T) { // // Suppressing the invented style must not take a declared explode with it. 3.2 // forbids explode at this location as it forbids style, and erasing it would be -// the same silent drop the invented style was, in the other direction. See +// the same unreported drop the invented style was, in the other direction. See // diag.InvalidLocationKeyword's GoDoc for why the report is a warning. func TestParams_QueryStringDeclaredExplodeAloneIsKeptAndReported(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/operation/params_schema_test.go b/compilers/openapi/internal/operation/params_schema_test.go index d96a56e74..5bf708963 100644 --- a/compilers/openapi/internal/operation/params_schema_test.go +++ b/compilers/openapi/internal/operation/params_schema_test.go @@ -274,7 +274,7 @@ paths: // TestParams_SchemaXMLHintsKeptUnderUnmodeled covers the one annotation // ir.Parameter has no field for (GitHub #124), which used to be dropped with no -// diagnostic at all. It is not inert here: the content-style case binds +// diagnostic at all. It has an effect here: the content-style case binds // application/xml, the media type OpenAPI §4.8.26 conditions xml on, and the // binding records that content type. func TestParams_SchemaXMLHintsKeptUnderUnmodeled(t *testing.T) { @@ -416,12 +416,12 @@ paths: responses: {"200": {description: ok}} ` -// TestParams_SchemaVisibilityKeptUnderUnmodeled covers the residue keywords a +// TestParams_SchemaVisibilityKeptUnderUnmodeled covers the use-bound keywords a // parameter has no field for. The rule // docs/compilers/openapi.md#use-bound-annotations lowers readOnly/writeOnly to // a Visibility, which only ir.Property carries, so at a parameter both reached -// no field and were dropped with no diagnostic at all — the silent loss this -// compiler exists to make impossible. +// no field and were dropped with no diagnostic at all — the unreported loss +// this compiler exists to make impossible. func TestParams_SchemaVisibilityKeptUnderUnmodeled(t *testing.T) { t.Parallel() _, svc, diags := compileService(t, paramVisibilitySpec) @@ -449,10 +449,10 @@ func TestParams_SchemaVisibilityKeptUnderUnmodeled(t *testing.T) { } } -// TestParams_KeepWhatAnyCarrierKeeps pins the keepers a parameter shares with a +// TestParams_KeepWhatAnyCarrierKeeps pins the keeps a parameter shares with a // property. A parameter whose schema owns no node once kept neither the content // vocabulary nor a $dynamicRef that did not expand, and reported neither, which -// is the silent loss a property never had, as it called them itself. +// is the unreported loss a property never had, as it called them itself. func TestParams_KeepWhatAnyCarrierKeeps(t *testing.T) { t.Parallel() _, svc, diags := compileService(t, `openapi: 3.1.0 @@ -484,7 +484,7 @@ components: } // TestParams_SchemaDefaultIsNotAlsoKeptVerbatim is the other side of that list: -// `default` is a residue keyword too, but Parameter.Default is a real home for +// `default` is a use-bound keyword too, but Parameter.Default is a real home for // it, so a verbatim copy beside it would give one declaration two homes. func TestParams_SchemaDefaultIsNotAlsoKeptVerbatim(t *testing.T) { t.Parallel() @@ -523,7 +523,7 @@ func TestParams_OwnAnnotationsWinOverTheSchema(t *testing.T) { // TestParams_SchemaVisibilityKeptWhenTheSchemaOwnsANode pins the half of the // parameter-visibility rescue that the own-node guard used to swallow. A // parameter whose schema is an object, an enum or an array hoists a node, and -// neither home held the keywords: the residue a declaration keeps skips the +// neither home held the keywords: the keywords a declaration keeps skips the // position because a parameter is an annotation.HomeCarrier, and ir.Parameter // has no Visibility field, so they were dropped for exactly the shapes that own // a node. @@ -552,11 +552,11 @@ func TestParams_SchemaVisibilityKeptWhenTheSchemaOwnsANode(t *testing.T) { // TestParams_RefSiteKeywordsAreKeptOnTheParameter covers the third // annotation.HomeCarrier position keeping a $ref's unread siblings (GitHub #283). // -// A parameter whose schema is a $ref resolves straight to the target, so the -// keywords written beside that $ref have no node of their own and no field on -// ir.Parameter either — exactly the shape a property and a header are in, and -// they are kept the same way: verbatim on the carrier, announced at the schema -// position that wrote them. +// A parameter whose schema is a $ref resolves straight to the target, so a +// bound written beside that $ref reaches the parameter's own constraints, as +// at a property and a header. A format selecting no primitive restricts the +// reference with its Encoding instead, which needs a node: the parameter's +// type is a Scalar of its own over the target carrying it, and nothing is kept. func TestParams_RefSiteKeywordsAreKeptOnTheParameter(t *testing.T) { t.Parallel() spec := "openapi: 3.1.0\ninfo: {title: T, version: \"1\"}\n" + @@ -565,23 +565,25 @@ func TestParams_RefSiteKeywordsAreKeptOnTheParameter(t *testing.T) { " - {name: r, in: query, schema: {$ref: '#/components/schemas/Base', minLength: 3}}\n" + " responses: {\"200\": {description: ok}}\n" + "components:\n schemas:\n Base: {type: string}\n" - _, svc, diags := compileService(t, spec) + doc, svc, diags := compileService(t, spec) openapitest.RequireNoErrorDiags(t, diags) params := openapitest.IndexBy(openapitest.FirstOperation(t, svc).Params, func(parameter ir.Parameter) string { return parameter.Name.Source }) irParameter, ok := params["q"] require.True(t, ok) - entry, ok := irParameter.Unmodeled["openapi:schema/format"] - require.True(t, ok, "an alias over the target has no Encoding field, so the format is kept") - assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assert.JSONEq(t, `"email"`, string(entry.Value)) - openapitest.AssertInfoDiagAt(t, diags, "/paths/~1x/get/parameters/0/schema") - - parameterValue, ok := params["r"] + assert.Empty(t, irParameter.Unmodeled, "the format is the restriction's") + restricted, ok := doc.Types[irParameter.Type.Target].(*ir.Scalar) + require.True(t, ok, "a restriction of the reference: got %T", doc.Types[irParameter.Type.Target]) + require.NotNil(t, restricted.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Base"), restricted.Base.Target) + assert.Equal(t, &ir.Encoding{Name: "email"}, restricted.Encoding) + assert.Empty(t, openapitest.PointersOf(diags, diag.DegradedConstruct), "nothing is kept") + + parameter, ok := params["r"] require.True(t, ok) - assert.Empty(t, parameterValue.Unmodeled, "a bound at the same position always reached ir.Parameter.Constraints") - require.NotNil(t, parameterValue.Constraints) - assert.Equal(t, int64(3), *parameterValue.Constraints.MinLength) + assert.Empty(t, parameter.Unmodeled, "a bound at the same position always reached ir.Parameter.Constraints") + require.NotNil(t, parameter.Constraints) + assert.Equal(t, int64(3), *parameter.Constraints.MinLength) } // TestParams_CoDeclaredBoundsReachTheParameter covers the parameter carrier for @@ -765,9 +767,9 @@ components: } } -// TestParameter_AnEntrySeveralWriteIsTheNearest pins what a parameter keeps of one -// keyword written twice, as a node's residue does: the schema written at the -// position over its entries, and the first entry over a later one. +// TestParameter_AnEntrySeveralWriteIsTheNearest pins what a parameter keeps of +// one keyword written twice, as a node's kept keywords do: the schema written +// at the position over its entries, and the first entry over a later one. func TestParameter_AnEntrySeveralWriteIsTheNearest(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.PathsSpec(` /p: @@ -808,6 +810,41 @@ components: } } +// TestParameter_AnEntryWritingXMLOtherwiseKeepsItAsTheParameterDoes pins an +// allOf entry of a parameter's schema writing xml otherwise than the schema +// beside it, or than another entry: each entry is kept whole under its own +// key, with the reason the parameter keeps its own xml for, as no field of +// ir.Parameter holds xml hints. +func TestParameter_AnEntryWritingXMLOtherwiseKeepsItAsTheParameterDoes(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.PathsSpec(` /p: + get: + operationId: get + parameters: + - {name: beside, in: query, schema: {allOf: [{$ref: '#/components/schemas/Str'}, {xml: {name: a}}], xml: {name: b}}} + - {name: entries, in: query, schema: {allOf: [{$ref: '#/components/schemas/Str'}, {xml: {name: a}}, {xml: {name: b}}]}} + responses: {"200": {description: ok}} +components: + schemas: + Str: {type: string} +`)) + openapitest.RequireNoErrorDiags(t, diags) + operation := openapitest.FindOperation(t, doc, "get") + for source, want := range map[string]map[string]string{ + "beside": {"openapi:schema/allOf/1": `{"xml":{"name":"a"}}`, "openapi:schema/xml": `{"name":"b"}`}, + "entries": {"openapi:schema/allOf/1": `{"xml":{"name":"a"}}`, "openapi:schema/allOf/2": `{"xml":{"name":"b"}}`}, + } { + param, ok := openapitest.ParamBySource(operation, source) + require.True(t, ok, source) + got := map[string]string{} + for key, entry := range param.Unmodeled { + assert.Equal(t, ir.ReasonNoIRHome, entry.Reason, "%s: %s", source, key) + got[key] = string(entry.Value) + } + assert.Equal(t, want, got, source) + } +} + // TestParameter_ADefaultReadsOnlyWhereTheNarrowingTakesIt pins a parameter's default // across a value set narrowing its $ref, as a property's reads. func TestParameter_ADefaultReadsOnlyWhereTheNarrowingTakesIt(t *testing.T) { diff --git a/compilers/openapi/internal/operation/partdefault.go b/compilers/openapi/internal/operation/partdefault.go index e30e6a9cf..df36bd7ee 100644 --- a/compilers/openapi/internal/operation/partdefault.go +++ b/compilers/openapi/internal/operation/partdefault.go @@ -32,7 +32,8 @@ const ( // readContentEncoding reads whether schemas, a part's declarations, write // contentEncoding, each read through its $ref chain and a refinement to the -// schema deciding it (schema.DecidingSchema), as the type lowering reads it. +// schema deciding it (schema.DecidingSchema), or beside a $ref it restricts +// (schema.RestrictionContentEncoding), as the type lowering reads it. func readContentEncoding(serviceContext service.Ctx, schemas []*oas3.JSONSchema[oas3.Referenceable]) contentEncoding { writes, omits := false, false for _, js := range schemas { @@ -40,7 +41,8 @@ func readContentEncoding(serviceContext service.Ctx, schemas []*oas3.JSONSchema[ if statement.Parsed(statementSchema) == nil { continue } - if statement.Parsed(schema.DecidingSchema(serviceContext.Ctx, statementSchema)).GetContentEncoding() != "" { + if schema.RestrictionContentEncoding(serviceContext.Ctx, serviceContext.Statements().Of(js).Schema) != "" || + statement.Parsed(schema.DecidingSchema(serviceContext.Ctx, statementSchema)).GetContentEncoding() != "" { writes = true } else { omits = true @@ -63,14 +65,14 @@ func readContentEncoding(serviceContext service.Ctx, schemas []*oas3.JSONSchema[ // §4.15.1). ok is false where a union's members are not read. A union's values // are read once a run (partUnions.valuesOf), and a part declared once by a // union takes them as they are, a list it only reads. -func partValues(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), decls []*ir.Property) (values []ir.TypeRef, ok bool) { +func partValues(unions *partUnions, chains *runChains, decls []*ir.Property) (values []ir.TypeRef, ok bool) { for _, property := range decls { - union, isUnion := bodyNode(node, property.Type.Target).(*ir.Union) + union, isUnion := bodyNode(chains, property.Type.Target).(*ir.Union) if !isUnion || union == nil { - values = append(values, itemsOf(node, property.Type)...) + values = append(values, itemsOf(chains, property.Type)...) continue } - held, read := unions.valuesOf(node, union) + held, read := unions.valuesOf(chains, union) switch { case !read: return nil, false @@ -87,26 +89,26 @@ func partValues(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), dec // declarations write of contentEncoding, and decl the one declaration of the // part. The run's store reads it once for every part so declared // (partUnions.partDefault). -func withDefaultContentType(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), rules specrules.EncodingRules, decl *ir.Property, encodedBy contentEncoding, pe ir.PartEncoding) ir.PartEncoding { - if types, ok := unions.partDefault(node, rules, decl, encodedBy); ok { +func withDefaultContentType(unions *partUnions, chains *runChains, rules specrules.EncodingRules, decl *ir.Property, encodedBy contentEncoding, pe ir.PartEncoding) ir.PartEncoding { + if types, ok := unions.partDefault(chains, rules, decl, encodedBy); ok { pe.ContentTypes = slices.Clone(types) } return pe } -// itemsOf returns the element types of ref where it stands for a list or a +// itemsOf returns the element types of ref where it names a list or a // tuple (elementsOf), and ref itself otherwise. -func itemsOf(node func(ir.TypeID) (ir.TypeDef, bool), ref ir.TypeRef) []ir.TypeRef { - if elements, isArray := elementsOf(bodyNode(node, ref.Target)); isArray { +func itemsOf(chains *runChains, ref ir.TypeRef) []ir.TypeRef { + if elements, isArray := elementsOf(bodyNode(chains, ref.Target)); isArray { return elements } return []ir.TypeRef{ref} } -// elementsOf returns the element types of td where it is a list or a tuple, a +// elementsOf returns the element types of typeDef where it is a list or a tuple, a // tuple's rest included. -func elementsOf(td ir.TypeDef) (elements []ir.TypeRef, isArray bool) { - switch t := td.(type) { +func elementsOf(typeDef ir.TypeDef) (elements []ir.TypeRef, isArray bool) { + switch t := typeDef.(type) { case *ir.List: return []ir.TypeRef{t.ElementType}, true case *ir.Tuple: @@ -132,14 +134,14 @@ const maxDefaultValues = 256 // a null passed over, and none where two differ, a value takes none, or none // is left to read. encodedBy is what the part's declarations say of // contentEncoding. -func defaultContentType(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), rules specrules.EncodingRules, values []ir.TypeRef, encodedBy contentEncoding) []string { +func defaultContentType(unions *partUnions, chains *runChains, rules specrules.EncodingRules, values []ir.TypeRef, encodedBy contentEncoding) []string { pending := append([]ir.TypeRef(nil), values...) taken := "" for range maxDefaultValues { if len(pending) == 0 { break } - valueReading := readValue(unions, node, rules, pending[0], encodedBy) + valueReading := readValue(unions, chains, rules, pending[0], encodedBy) pending = append(pending[1:], valueReading.instead...) switch { case valueReading.null || len(valueReading.instead) > 0: @@ -157,7 +159,7 @@ func defaultContentType(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bo // valueReading is what one value says of its default content type: the one // it takes, "" for none; that it is null, which takes none and needs none; or -// the values whose content types stand for its own, a nested union's members +// the values whose content types name its own, a nested union's members // or, where the minor gives an array inside an array no row, its items. type valueReading struct { contentType string @@ -166,40 +168,29 @@ type valueReading struct { } // readValue reads the value of type ref as its default content type is keyed -// (valueReading), through the alias scalars on its chain, noting the encoding -// the first scalar naming one names, and bounded by maxBodyAliasHops. -func readValue(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), rules specrules.EncodingRules, ref ir.TypeRef, encodedBy contentEncoding) valueReading { - encoding := "" - id := ref.Target - for range maxBodyAliasHops { - td, found := node(id) - if !found { - return valueReading{} - } - if scalar, alias := td.(*ir.Scalar); alias && scalar != nil && scalar.Base != nil { - if encoding == "" && scalar.Encoding != nil { - encoding = scalar.Encoding.Name - } - id = scalar.Base.Target - continue - } - return readNode(unions, node, rules, td, encoding, encodedBy) +// (valueReading), through the alias scalars on its chain, however long, noting +// the encoding the first scalar naming one names. A chain naming no node, or +// meeting an alias twice, reads nothing (runChains.end). +func readValue(unions *partUnions, chains *runChains, rules specrules.EncodingRules, ref ir.TypeRef, encodedBy contentEncoding) valueReading { + end := chains.end(ref.Target) + if !end.found || end.cyclic { + return valueReading{} } - return valueReading{} + return readNode(unions, chains, rules, end.typeDef, chains.firstEncoding(ref.Target), encodedBy) } -// readNode reads td, the node a value's alias chain ends on, encoding being +// readNode reads typeDef, the node a value's alias chain ends on, encoding being // the one a scalar on the chain names: a primitive, an enum and a literal by // their primitive (primitiveCase), a model and a map as objects, an array // inside an array by its row or else its items, and a union by its members. -func readNode(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), rules specrules.EncodingRules, td ir.TypeDef, encoding string, encodedBy contentEncoding) valueReading { - if elements, isArray := elementsOf(td); isArray { +func readNode(unions *partUnions, chains *runChains, rules specrules.EncodingRules, typeDef ir.TypeDef, encoding string, encodedBy contentEncoding) valueReading { + if elements, isArray := elementsOf(typeDef); isArray { if ct, ok := rules.ContentType(specrules.DefaultNestedArray); ok { return valueReading{contentType: ct} } return valueReading{instead: elements} } - switch t := td.(type) { + switch t := typeDef.(type) { case *ir.Primitive: return byCase(rules, primitiveCase(t.PrimitiveKind, encoding, encodedBy)) case *ir.Enum: @@ -209,7 +200,7 @@ func readNode(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool), rules case *ir.Model, *ir.MapT: return byCase(rules, specrules.DefaultObject) case *ir.Union: - if members, ok := unions.membersOf(node, t); ok && len(members) > 0 { + if members, ok := unions.membersOf(chains, t); ok && len(members) > 0 { return valueReading{instead: members} } return valueReading{} @@ -303,12 +294,8 @@ type itemDefault struct { } // Settle writes the default to the item encoding and no node of reg. -func (d itemDefault) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { - node := func(id ir.TypeID) (ir.TypeDef, bool) { - td, ok := reg[id] - return td, ok - } - types := partUnionsOf(d.c).itemDefault(node, service.EncodingRules(d.c), d.item, d.encoded) +func (d itemDefault) Settle(_ context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + types := partUnionsOf(d.c).itemDefault(runChainsOf(d.c, reg, aliases), service.EncodingRules(d.c), d.item, d.encoded) d.encoding.ContentTypes = slices.Clone(types) return nil } diff --git a/compilers/openapi/internal/operation/partdefault_internal_test.go b/compilers/openapi/internal/operation/partdefault_internal_test.go index 6ad8e12ae..8383ccd0c 100644 --- a/compilers/openapi/internal/operation/partdefault_internal_test.go +++ b/compilers/openapi/internal/operation/partdefault_internal_test.go @@ -59,7 +59,6 @@ func defaultsRegistry() ir.TypeRegistry { func TestDefaultContentType_ReadsEachValueByItsRow(t *testing.T) { t.Parallel() reg := defaultsRegistry() - node := func(id ir.TypeID) (ir.TypeDef, bool) { td, ok := reg[id]; return td, ok } const ( octet = "application/octet-stream" text = "text/plain" @@ -107,8 +106,9 @@ func TestDefaultContentType_ReadsEachValueByItsRow(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() + chains := chainsOver(reg) for version, want := range map[string]string{"3.0.3": tc.v30, "3.1.0": tc.v31, "3.2.0": tc.v32} { - got := defaultContentType(newPartUnions(), node, specrules.Table().EncodingRules(version), []ir.TypeRef{{Target: tc.value}}, tc.encodedBy) + got := defaultContentType(newPartUnions(), chains, specrules.Table().EncodingRules(version), []ir.TypeRef{{Target: tc.value}}, tc.encodedBy) if want == "" { assert.Nil(t, got, version) continue @@ -117,13 +117,13 @@ func TestDefaultContentType_ReadsEachValueByItsRow(t *testing.T) { } }) } - rules := specrules.Table().EncodingRules("3.1.0") - assert.Equal(t, []string{"text/plain"}, defaultContentType(newPartUnions(), node, rules, + chains, rules := chainsOver(reg), specrules.Table().EncodingRules("3.1.0") + assert.Equal(t, []string{"text/plain"}, defaultContentType(newPartUnions(), chains, rules, []ir.TypeRef{{Target: ir.PrimitiveTypeID(ir.PrimitiveString)}, {Target: ir.PrimitiveTypeID(ir.PrimitiveBool)}}, unencoded), "values of one row take it") - assert.Nil(t, defaultContentType(newPartUnions(), node, rules, + assert.Nil(t, defaultContentType(newPartUnions(), chains, rules, []ir.TypeRef{{Target: ir.PrimitiveTypeID(ir.PrimitiveString)}, {Target: "type/model"}}, unencoded), "values of two rows take none") - assert.Nil(t, defaultContentType(newPartUnions(), node, rules, nil, unencoded), "no value takes none") + assert.Nil(t, defaultContentType(newPartUnions(), chains, rules, nil, unencoded), "no value takes none") } // TestDefaultContentType_ReadsUpToItsBound holds the values one part's @@ -131,9 +131,9 @@ func TestDefaultContentType_ReadsEachValueByItsRow(t *testing.T) { // one of a string more takes no default. func TestDefaultContentType_ReadsUpToItsBound(t *testing.T) { t.Parallel() - union := func(n int) ir.TypeRegistry { + union := func(count int) ir.TypeRegistry { union := &ir.Union{ID: "type/u"} - for range n { + for range count { union.Variants = append(union.Variants, ir.Variant{Type: ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveString)}}) } return ir.TypeRegistry{"type/u": union, ir.PrimitiveTypeID(ir.PrimitiveString): &ir.Primitive{ID: ir.PrimitiveTypeID(ir.PrimitiveString), PrimitiveKind: ir.PrimitiveString}} @@ -141,8 +141,8 @@ func TestDefaultContentType_ReadsUpToItsBound(t *testing.T) { rules := specrules.Table().EncodingRules("3.1.0") for n, want := range map[int][]string{maxDefaultValues - 1: {"text/plain"}, maxDefaultValues: nil} { reg := union(n) - node := func(id ir.TypeID) (ir.TypeDef, bool) { td, ok := reg[id]; return td, ok } - assert.Equal(t, want, defaultContentType(newPartUnions(), node, rules, []ir.TypeRef{{Target: "type/u"}}, unencoded), + chains := chainsOver(reg) + assert.Equal(t, want, defaultContentType(newPartUnions(), chains, rules, []ir.TypeRef{{Target: "type/u"}}, unencoded), "%d strings beside the union read", n) } } @@ -155,28 +155,32 @@ func TestPartValues_ReadsEachItemOfEachDeclaration(t *testing.T) { t.Parallel() reg := defaultsRegistry() reg["type/u/lists"] = &ir.Union{ID: "type/u/lists", Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/list"}}, {Type: ir.TypeRef{Target: "type/model"}}}} - node := func(id ir.TypeID) (ir.TypeDef, bool) { td, ok := reg[id]; return td, ok } + chains := chainsOver(reg) decl := func(id ir.TypeID) *ir.Property { return &ir.Property{Type: ir.TypeRef{Target: id}} } - values, ok := partValues(newPartUnions(), node, []*ir.Property{decl("type/tuple"), decl("type/u/lists"), decl("type/model")}) + values, ok := partValues(newPartUnions(), chains, []*ir.Property{decl("type/tuple"), decl("type/u/lists"), decl("type/model")}) require.True(t, ok) assert.Equal(t, []ir.TypeRef{ {Target: ir.PrimitiveTypeID(ir.PrimitiveInt64)}, {Target: ir.PrimitiveTypeID(ir.PrimitiveBool)}, {Target: ir.PrimitiveTypeID(ir.PrimitiveString)}, {Target: "type/model"}, {Target: "type/model"}, }, values) - values, ok = partValues(newPartUnions(), node, []*ir.Property{decl("type/model"), decl("type/u/missing")}) + values, ok = partValues(newPartUnions(), chains, []*ir.Property{decl("type/model"), decl("type/u/missing")}) assert.False(t, ok, "a union whose members are not read") assert.Nil(t, values) } // TestReadContentEncoding_ReadsEveryDeclaration holds what a part's // declarations say of contentEncoding to each of them, through a $ref, a -// boolean schema saying nothing: none, each, or some writing it. +// boolean schema saying nothing: none, each, or some writing it. One written +// beside a $ref to a string, in either spelling, restricts the reference, and +// is read there as the node the declaration lowers to carries it. func TestReadContentEncoding_ReadsEveryDeclaration(t *testing.T) { t.Parallel() lowerer, _ := loweredFor(t, openapitest.ComponentSpec( - " Plain: {type: string}\n Encoded: {type: string, contentEncoding: base64}\n Ref: {$ref: '#/components/schemas/Encoded'}\n")) + " Plain: {type: string}\n Encoded: {type: string, contentEncoding: base64}\n Ref: {$ref: '#/components/schemas/Encoded'}\n"+ + " Beside: {$ref: '#/components/schemas/Plain', contentEncoding: base64}\n"+ + " Entry: {allOf: [{$ref: '#/components/schemas/Plain'}, {contentEncoding: base64}]}\n")) get := func(name string) *oas3.JSONSchema[oas3.Referenceable] { js, ok := lowerer.ctx.Doc.Components.Schemas.Get(name) require.True(t, ok, name) @@ -192,6 +196,7 @@ func TestReadContentEncoding_ReadsEveryDeclaration(t *testing.T) { {"each, one through a $ref", []*oas3.JSONSchema[oas3.Referenceable]{get("Encoded"), get("Ref"), boolean}, encoded}, {"some", []*oas3.JSONSchema[oas3.Referenceable]{get("Plain"), get("Ref")}, partlyEncoded}, {"no declaration", nil, unencoded}, + {"beside a $ref it restricts", []*oas3.JSONSchema[oas3.Referenceable]{get("Beside"), get("Entry")}, encoded}, } { assert.Equal(t, tc.want, readContentEncoding(lowerer.ctx, tc.schemas), tc.name) } diff --git a/compilers/openapi/internal/operation/partfile.go b/compilers/openapi/internal/operation/partfile.go index 0a19e6c67..d06b7b845 100644 --- a/compilers/openapi/internal/operation/partfile.go +++ b/compilers/openapi/internal/operation/partfile.go @@ -79,8 +79,8 @@ func untypedPartFile(serviceContext service.Ctx, least fileReading) partFile { // but for an array branch of a union it writes, read through its elements too // (readPartBranch). func readDeclaration(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Referenceable]) fileReading { - if s := schemaOf(serviceContext.Bindings(), js); isArraySchema(s) { - return readElements(serviceContext, js, s) + if oasSchema := schemaOf(serviceContext.Bindings(), js); isArraySchema(oasSchema) { + return readElements(serviceContext, js, oasSchema) } return readSchema(serviceContext, js, branchReading{read: readPartBranch, part: true}) } @@ -89,29 +89,29 @@ func readDeclaration(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Refere // body's union branch is read (readBranch), but an array through its elements // (readElements), as the part repeats where the branch holds. func readPartBranch(serviceContext service.Ctx, branch *oas3.JSONSchema[oas3.Referenceable]) fileReading { - if s := schemaOf(serviceContext.Bindings(), branch); isArraySchema(s) { - return readElements(serviceContext, branch, s) + if oasSchema := schemaOf(serviceContext.Bindings(), branch); isArraySchema(oasSchema) { + return readElements(serviceContext, branch, oasSchema) } return readBranch(serviceContext, branch) } -// isArraySchema reports whether s writes the type array, alone or with null. -func isArraySchema(s *oas3.Schema) bool { - return s != nil && slices.Equal(withoutNull(s.GetType()), []oas3.SchemaType{oas3.SchemaTypeArray}) +// isArraySchema reports whether oasSchema writes the type array, alone or with null. +func isArraySchema(oasSchema *oas3.Schema) bool { + return oasSchema != nil && slices.Equal(withoutNull(oasSchema.GetType()), []oas3.SchemaType{oas3.SchemaTypeArray}) } -// readElements reads the elements of the array js, whose schema is s, as one: +// readElements reads the elements of the array js, whose schema is oasSchema, as one: // a draft's tuple entries and the additionalItems past them // (schema.ListedTuple), else its prefixItems and the items following them, a // rest of false admitting none. An array writing no rest reads as other, as // one admitting no element does: what its elements past its prefix are is // left unsaid, not said to be anything. -func readElements(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Referenceable], s *oas3.Schema) fileReading { +func readElements(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Referenceable], oasSchema *oas3.Schema) fileReading { elements, rest, tuple := schema.ListedTuple(serviceContext.Ctx, serviceContext.Statements().Of(js)) if !tuple { - rest = serviceContext.Statements().Of(s.GetItems()) - for _, e := range s.GetPrefixItems() { - elements = append(elements, serviceContext.Statements().Of(e)) + rest = serviceContext.Statements().Of(oasSchema.GetItems()) + for _, item := range oasSchema.GetPrefixItems() { + elements = append(elements, serviceContext.Statements().Of(item)) } } if rest.Truth == statement.Unwritten { @@ -123,8 +123,8 @@ func readElements(serviceContext service.Ctx, js *oas3.JSONSchema[oas3.Reference if len(elements) == 0 { return readsOther } - return leastOf(serviceContext, elements, func(serviceContextValue service.Ctx, schemaStatement *statement.Statement) fileReading { - return readFile(serviceContextValue, statement.ParsedAt(schemaStatement)) + return leastOf(serviceContext, elements, func(serviceContext service.Ctx, schemaStatement *statement.Statement) fileReading { + return readFile(serviceContext, statement.ParsedAt(schemaStatement)) }) } @@ -149,40 +149,24 @@ func partContentFile(serviceContext service.Ctx, contentTypes []string) partFile // rawTuple reports whether every element tuple admits is raw bytes (rawBytes): // each of ElementTypes and, where elements may follow them, Rest. A tuple // admitting no element at all is no file. -func rawTuple(node func(ir.TypeID) (ir.TypeDef, bool), tuple *ir.Tuple) bool { +func rawTuple(chains *runChains, tuple *ir.Tuple) bool { if len(tuple.ElementTypes) == 0 && tuple.Rest == nil { return false } for _, element := range tuple.ElementTypes { - if !rawBytes(node, element) { + if !rawBytes(chains, element) { return false } } - return tuple.Rest == nil || rawBytes(node, *tuple.Rest) + return tuple.Rest == nil || rawBytes(chains, *tuple.Rest) } // rawBytes reports whether ref ends in bytes that travel raw, through the alias // scalars a hoisted position puts over the primitive, none of which re-encodes -// it: a `format: byte` element is base64 text. The walk is bounded by -// maxBodyAliasHops. -func rawBytes(node func(ir.TypeID) (ir.TypeDef, bool), ref ir.TypeRef) bool { - id := ref.Target - for range maxBodyAliasHops { - td, found := node(id) - if !found { - return false - } - switch t := td.(type) { - case *ir.Primitive: - return t.PrimitiveKind == ir.PrimitiveBytes - case *ir.Scalar: - if t.Base == nil || t.Encoding != nil && t.Encoding.Name != "" { - return false - } - id = t.Base.Target - default: - return false - } - } - return false +// it: a `format: byte` element is base64 text. A chain naming no node or +// meeting an alias twice ends in none (runChains.end). +func rawBytes(chains *runChains, ref ir.TypeRef) bool { + typeDef := chains.end(ref.Target).typeDef + primitive, isPrimitive := typeDef.(*ir.Primitive) + return isPrimitive && primitive.PrimitiveKind == ir.PrimitiveBytes && chains.firstEncoding(ref.Target) == "" } diff --git a/compilers/openapi/internal/operation/partunions.go b/compilers/openapi/internal/operation/partunions.go index 452d4f703..d973774b6 100644 --- a/compilers/openapi/internal/operation/partunions.go +++ b/compilers/openapi/internal/operation/partunions.go @@ -24,7 +24,7 @@ import ( // (compile.Types.QueueSettlementBeforeDeferredOnes). type partUnions struct { members map[ir.TypeID]unionRead - flags map[unionFlagsKey]unionFlags + flags map[unionFlagsKey]structuralFlags values map[ir.TypeID]unionRead defaults map[defaultKey]defaultRead } @@ -60,8 +60,10 @@ type unionFlagsKey struct { multipart bool } -// unionFlags is what partTypeFlags reads off a union's members. -type unionFlags struct { +// structuralFlags are the structural flags a part's type gives it +// (partTypeFlags): multi where the part repeats, file where it is a file, and +// decided where its type is one the reading can answer for. +type structuralFlags struct { multi, file, decided bool } @@ -69,7 +71,7 @@ type unionFlags struct { func newPartUnions() *partUnions { return &partUnions{ members: map[ir.TypeID]unionRead{}, - flags: map[unionFlagsKey]unionFlags{}, + flags: map[unionFlagsKey]structuralFlags{}, values: map[ir.TypeID]unionRead{}, defaults: map[defaultKey]defaultRead{}, } @@ -79,28 +81,28 @@ func newPartUnions() *partUnions { // (defaultContentType over partValues), read once for each type, rules and // encodedBy, and false where the values it applies to are not read. The list // is shared, so a caller copies it before keeping it. -func (u *partUnions) partDefault(node func(ir.TypeID) (ir.TypeDef, bool), rules specrules.EncodingRules, decl *ir.Property, encodedBy contentEncoding) ([]string, bool) { +func (u *partUnions) partDefault(chains *runChains, rules specrules.EncodingRules, decl *ir.Property, encodedBy contentEncoding) ([]string, bool) { key := defaultKey{rules: rules, of: decl.Type.Target, encodedBy: encodedBy} if defaultRead, read := u.defaults[key]; read { return defaultRead.types, defaultRead.ok } - var defaultReadValue defaultRead - if values, ok := partValues(u, node, []*ir.Property{decl}); ok { - defaultReadValue = defaultRead{types: defaultContentType(u, node, rules, values, encodedBy), ok: true} + var read defaultRead + if values, ok := partValues(u, chains, []*ir.Property{decl}); ok { + read = defaultRead{types: defaultContentType(u, chains, rules, values, encodedBy), ok: true} } - u.defaults[key] = defaultReadValue - return defaultReadValue.types, defaultReadValue.ok + u.defaults[key] = read + return read.types, read.ok } // itemDefault returns the default content type of the items of type item a // sequential body holds, read once for each type, rules and encodedBy. The // list is shared, so a caller copies it before keeping it. -func (u *partUnions) itemDefault(node func(ir.TypeID) (ir.TypeDef, bool), rules specrules.EncodingRules, item ir.TypeRef, encodedBy contentEncoding) []string { +func (u *partUnions) itemDefault(chains *runChains, rules specrules.EncodingRules, item ir.TypeRef, encodedBy contentEncoding) []string { key := defaultKey{rules: rules, of: item.Target, encodedBy: encodedBy, item: true} if defaultRead, read := u.defaults[key]; read { return defaultRead.types } - types := defaultContentType(u, node, rules, []ir.TypeRef{item}, encodedBy) + types := defaultContentType(u, chains, rules, []ir.TypeRef{item}, encodedBy) u.defaults[key] = defaultRead{types: types, ok: true} return types } @@ -112,11 +114,11 @@ func partUnionsOf(serviceContext service.Ctx) *partUnions { } // membersOf returns the members of union (unionMembers), read once. -func (u *partUnions) membersOf(node func(ir.TypeID) (ir.TypeDef, bool), union *ir.Union) ([]ir.TypeRef, bool) { +func (u *partUnions) membersOf(chains *runChains, union *ir.Union) ([]ir.TypeRef, bool) { if unionRead, read := u.members[union.ID]; read { return unionRead.refs, unionRead.ok } - refs, ok := unionMembers(node, union) + refs, ok := unionMembers(chains, union) refs = slices.Clip(refs) u.members[union.ID] = unionRead{refs: refs, ok: ok} return refs, ok @@ -124,35 +126,36 @@ func (u *partUnions) membersOf(node func(ir.TypeID) (ir.TypeDef, bool), union *i // flagsOf returns the structural flags union's members give a part // (partTypeFlags), read once for a multipart body and once for any other. -func (u *partUnions) flagsOf(node func(ir.TypeID) (ir.TypeDef, bool), union *ir.Union, multipart bool) (multi, file, decided bool) { +func (u *partUnions) flagsOf(chains *runChains, union *ir.Union, multipart bool) structuralFlags { key := unionFlagsKey{id: union.ID, multipart: multipart} - if unionFlags, read := u.flags[key]; read { - return unionFlags.multi, unionFlags.file, unionFlags.decided + if flags, read := u.flags[key]; read { + return flags } - members, ok := u.membersOf(node, union) + members, ok := u.membersOf(chains, union) + flags := structuralFlags{decided: ok} if ok { - file = multipart && len(members) > 0 + flags.file = multipart && len(members) > 0 for _, member := range members { - memberMulti, memberFile, _ := memberFlags(node, member, multipart) - multi, file = multi || memberMulti, file && memberFile + read := memberFlags(chains, member, multipart) + flags.multi, flags.file = flags.multi || read.multi, flags.file && read.file } } - u.flags[key] = unionFlags{multi: multi, file: file, decided: ok} - return multi, file, ok + u.flags[key] = flags + return flags } // valuesOf returns the values an encoding of a part of type union applies to // (partValues): each member's items, read once. The list is shared, so a // caller reads it and never writes it. -func (u *partUnions) valuesOf(node func(ir.TypeID) (ir.TypeDef, bool), union *ir.Union) ([]ir.TypeRef, bool) { +func (u *partUnions) valuesOf(chains *runChains, union *ir.Union) ([]ir.TypeRef, bool) { if unionRead, read := u.values[union.ID]; read { return unionRead.refs, unionRead.ok } - members, ok := u.membersOf(node, union) + members, ok := u.membersOf(chains, union) var values []ir.TypeRef if ok { for _, typeRef := range members { - values = append(values, itemsOf(node, typeRef)...) + values = append(values, itemsOf(chains, typeRef)...) } } values = slices.Clip(values) diff --git a/compilers/openapi/internal/operation/partunions_internal_test.go b/compilers/openapi/internal/operation/partunions_internal_test.go index 45ad33aaa..a1f6f6073 100644 --- a/compilers/openapi/internal/operation/partunions_internal_test.go +++ b/compilers/openapi/internal/operation/partunions_internal_test.go @@ -39,8 +39,8 @@ func countingNode(reg ir.TypeRegistry, counted map[ir.TypeID]bool, reads *int) f if counted[id] { *reads++ } - td, ok := reg[id] - return td, ok + typeDef, ok := reg[id] + return typeDef, ok } } @@ -54,13 +54,13 @@ func TestPartUnions_ReadAUnionOncePerRun(t *testing.T) { reg, models := unionRegistry() ref := ir.TypeRef{Target: "type/u"} decls := []*ir.Property{{Type: ref}} - readers := map[string]func(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool)){ - "a part's flags": func(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool)) { - partTypeFlags(unions, node, ref, true /* multipart */) - partTypeFlags(unions, node, ref, false) + readers := map[string]func(unions *partUnions, chains *runChains){ + "a part's flags": func(unions *partUnions, chains *runChains) { + partTypeFlags(unions, chains, ref, true /* multipart */) + partTypeFlags(unions, chains, ref, false) }, - "a part's values": func(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool)) { - partValues(unions, node, decls) + "a part's values": func(unions *partUnions, chains *runChains) { + partValues(unions, chains, decls) }, } for name, read := range readers { @@ -70,9 +70,9 @@ func TestPartUnions_ReadAUnionOncePerRun(t *testing.T) { for _, parts := range []int{1, 8} { n := 0 unions := newPartUnions() - node := countingNode(reg, models, &n) + chains := chainsThrough(reg, countingNode(reg, models, &n)) for range parts { - read(unions, node) + read(unions, chains) } reads[parts] = n } @@ -92,17 +92,17 @@ func TestPartUnions_ReadADefaultContentTypeOncePerRun(t *testing.T) { reg, models := unionRegistry() reg["type/list"] = &ir.List{ID: "type/list", ElementType: ir.TypeRef{Target: "type/u"}} rules := specrules.Table().EncodingRules("3.1.0") - partOf := func(id ir.TypeID) func(*partUnions, func(ir.TypeID) (ir.TypeDef, bool)) { - return func(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool)) { - pe := withDefaultContentType(unions, node, rules, &ir.Property{Type: ir.TypeRef{Target: id}}, unencoded, ir.PartEncoding{}) + partOf := func(id ir.TypeID) func(*partUnions, *runChains) { + return func(unions *partUnions, chains *runChains) { + pe := withDefaultContentType(unions, chains, rules, &ir.Property{Type: ir.TypeRef{Target: id}}, unencoded, ir.PartEncoding{}) assert.Equal(t, []string{"application/json"}, pe.ContentTypes, "a part of objects takes JSON") } } - item := func(unions *partUnions, node func(ir.TypeID) (ir.TypeDef, bool)) { - got := unions.itemDefault(node, rules, ir.TypeRef{Target: "type/u"}, unencoded) + item := func(unions *partUnions, chains *runChains) { + got := unions.itemDefault(chains, rules, ir.TypeRef{Target: "type/u"}, unencoded) assert.Equal(t, []string{"application/json"}, got, "an item of objects takes JSON") } - readers := map[string]func(*partUnions, func(ir.TypeID) (ir.TypeDef, bool)){ + readers := map[string]func(*partUnions, *runChains){ "a part of the union": partOf("type/u"), "a part listing the union": partOf("type/list"), "an item of the union": item, @@ -114,9 +114,9 @@ func TestPartUnions_ReadADefaultContentTypeOncePerRun(t *testing.T) { for _, parts := range []int{1, 8} { n := 0 unions := newPartUnions() - node := countingNode(reg, models, &n) + chains := chainsThrough(reg, countingNode(reg, models, &n)) for range parts { - read(unions, node) + read(unions, chains) } reads[parts] = n } @@ -127,10 +127,10 @@ func TestPartUnions_ReadADefaultContentTypeOncePerRun(t *testing.T) { n := 0 unions := newPartUnions() - node := countingNode(reg, models, &n) - partOf("type/list")(unions, node) + chains := chainsThrough(reg, countingNode(reg, models, &n)) + partOf("type/list")(unions, chains) first := n - item(unions, node) + item(unions, chains) assert.LessOrEqual(t, n-first, unionWidth, "an item of the union reads its members' values, not its variants again") } @@ -147,25 +147,22 @@ func TestPartUnions_KeepsADefaultContentTypeByAllItTurnsOn(t *testing.T) { "type/tags": &ir.List{ID: "type/tags", ElementType: ir.TypeRef{Target: "type/text"}}, "type/nested": &ir.List{ID: "type/nested", ElementType: ir.TypeRef{Target: "type/tags"}}, } - node := func(id ir.TypeID) (ir.TypeDef, bool) { - td, ok := reg[id] - return td, ok - } v31, v32 := specrules.Table().EncodingRules("3.1.0"), specrules.Table().EncodingRules("3.2.0") - part := func(of ir.TypeID, rules specrules.EncodingRules, by contentEncoding) func(*testing.T, *partUnions) []string { - return func(t *testing.T, partUnionsValue *partUnions) []string { + type reading = func(*testing.T, *partUnions, *runChains) []string + part := func(of ir.TypeID, rules specrules.EncodingRules, by contentEncoding) reading { + return func(t *testing.T, partUnions *partUnions, chains *runChains) []string { t.Helper() - types, ok := partUnionsValue.partDefault(node, rules, &ir.Property{Type: ir.TypeRef{Target: of}}, by) + types, ok := partUnions.partDefault(chains, rules, &ir.Property{Type: ir.TypeRef{Target: of}}, by) require.True(t, ok, "the values of a part of %s are read", of) return types } } - item := func(of ir.TypeID, rules specrules.EncodingRules, by contentEncoding) func(*testing.T, *partUnions) []string { - return func(_ *testing.T, partUnionsValue *partUnions) []string { - return partUnionsValue.itemDefault(node, rules, ir.TypeRef{Target: of}, by) + item := func(of ir.TypeID, rules specrules.EncodingRules, by contentEncoding) reading { + return func(_ *testing.T, partUnions *partUnions, chains *runChains) []string { + return partUnions.itemDefault(chains, rules, ir.TypeRef{Target: of}, by) } } - for name, pair := range map[string][2]func(*testing.T, *partUnions) []string{ + for name, pair := range map[string][2]reading{ "a part and an item of one list": {part("type/tags", v32, unencoded), item("type/tags", v32, unencoded)}, "an item under two minors' rules": {item("type/tags", v31, unencoded), item("type/tags", v32, unencoded)}, "an item encoded and not": {item("type/text", v31, unencoded), item("type/text", v31, encoded)}, @@ -174,12 +171,13 @@ func TestPartUnions_KeepsADefaultContentTypeByAllItTurnsOn(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - alone := pair[1](t, newPartUnions()) - require.NotEqual(t, pair[0](t, newPartUnions()), alone, "the two readings differ") + chains := chainsOver(reg) + alone := pair[1](t, newPartUnions(), chains) + require.NotEqual(t, pair[0](t, newPartUnions(), chains), alone, "the two readings differ") shared := newPartUnions() - pair[0](t, shared) - assert.Equal(t, alone, pair[1](t, shared), "the second reading takes its own answer") + pair[0](t, shared, chains) + assert.Equal(t, alone, pair[1](t, shared, chains), "the second reading takes its own answer") }) } } diff --git a/compilers/openapi/internal/operation/pathitem.go b/compilers/openapi/internal/operation/pathitem.go index 7e2d75df7..e2f5c4ecf 100644 --- a/compilers/openapi/internal/operation/pathitem.go +++ b/compilers/openapi/internal/operation/pathitem.go @@ -80,9 +80,9 @@ type pathOperation struct { // reports it. func pathOperations(pi *soa.PathItem) []pathOperation { operations := make([]pathOperation, 0, len(httpMethods)) - for _, m := range httpMethods { - if src := m.get(pi); src != nil { - operations = append(operations, pathOperation{method: strings.ToUpper(m.name), seg: ids.Ptr(m.name), src: src}) + for _, method := range httpMethods { + if src := method.get(pi); src != nil { + operations = append(operations, pathOperation{method: strings.ToUpper(method.name), seg: ids.Ptr(method.name), src: src}) } } extra := pi.GetAdditionalOperations() @@ -140,7 +140,7 @@ func lowerPathItem(serviceContext service.Ctx, loweringState operationLoweringSt template, fragment, fragmented := pathRoute(path) route := operationContext{key: path, template: template, groups: groups} ptr := ids.Ptr("paths", path) - mounted, diags := mountPathItem(loweringState, layers, mountSite{ptr: ptr, use: serviceContext, usePtr: ptr, residue: &svc.Unmodeled}, route) + mounted, diags := mountPathItem(loweringState, layers, mountSite{ptr: ptr, use: serviceContext, usePtr: ptr, orphanUnmodeled: &svc.Unmodeled}, route) for _, mountedOperation := range mounted { if fragmented { diags = append(diags, keepFragment(serviceContext, &mountedOperation.operation, ptr, fragment)...) @@ -160,7 +160,7 @@ func lowerPathItem(serviceContext service.Ctx, loweringState operationLoweringSt // is text whatever it spells, as a quoted scalar is, so "123" stays no number. func keepFragment(serviceContext service.Ctx, operation *ir.Operation, ptr jsontext.Pointer, fragment string) []ir.Diagnostic { text := &yaml.Node{Kind: yaml.ScalarNode, Style: yaml.DoubleQuotedStyle, Value: fragment} - _, diags := annotation.PreserveNodeInto(&operation.Bindings.HTTP[0].Unmodeled, annotation.EntryKey("", "fragment"), text, + _, diags := annotation.KeepNodeInto(&operation.Bindings.HTTP[0].Unmodeled, annotation.EntryKey("", "fragment"), text, ir.ReasonDegradedLowering, serviceContext.Place().At(ptr)) return diags } @@ -182,21 +182,21 @@ type mountedOperation struct { // webhook's use site is the mount; a callback expression's is where its // Callback Object writes it, which a mount below a $ref'd one does not address. type mountSite struct { - ptr jsontext.Pointer - use service.Ctx - usePtr jsontext.Pointer - residue *ir.Unmodeled + ptr jsontext.Pointer + use service.Ctx + usePtr jsontext.Pointer + orphanUnmodeled *ir.Unmodeled } // mountPathItem lowers every operation the layers of one path item mount, below // at.ptr, the one way a path, a webhook and a callback expression lower them. // Each lowers from the nearest layer declaring it, in that layer's context and // below its declaration pointer, in mountedOperations' order; it takes every -// layer's item parameters merged into its own, the mount's servers where it names -// none (itemServers), and what the layers keep (keepOn). A mount lowering none -// keeps what its layers declare in at.residue instead (preserveUnmounted). -// route holds what the route sets on every operation; each brings its own -// method, pointers and parameters. +// layer's item parameters merged into its own, the mount's servers where it +// names none (itemServers), and what the layers keep (keepOn). A mount lowering +// none keeps what its layers declare in at.orphanUnmodeled instead +// (keepUnmounted). route holds what the route sets on every operation; each +// brings its own method, pointers and parameters. func mountPathItem(loweringState operationLoweringState, layers []layer, at mountSite, route operationContext) ([]mountedOperation, []ir.Diagnostic) { mount := at.ptr operations := mountedOperations(layers) @@ -205,7 +205,7 @@ func mountPathItem(loweringState operationLoweringState, layers []layer, at moun named, serverDiags := itemServers(loweringState.servers, layers, owner) diags = append(diags, serverDiags...) if len(operations) == 0 { - return nil, append(diags, preserveUnmounted(layers, owner, named, at)...) + return nil, append(diags, keepUnmounted(layers, owner, named, at)...) } var kept ir.Unmodeled var docs ir.Docs @@ -288,7 +288,7 @@ func applyPathItem(serviceContext service.Ctx, into carrier, pi *soa.PathItem, d *into.unmodeled = annotation.MergeUnmodeled(*into.unmodeled, ext) diags = append(diags, extDiags...) return append(diags, annotation.UnknownKeysNamed(into.unmodeled, keptKeys(undeclaredPathItemKeys(pi), cedes), - pi.GetRootNode(), serviceContext.Place(), declPtr, into.scope)...) + pi.GetRootNode(), serviceContext.Place(), declPtr, into.scope).Diagnostics()...) } // carrier is where a path item's own declarations are kept, and under what key @@ -334,7 +334,7 @@ func onNearestNode(unmodeled *ir.Unmodeled, mountPtr jsontext.Pointer) carrier { return carrier{unmodeled: unmodeled, scope: pathItemScope + string(mountPtr)} } -// preserveUnmounted keeps what the layers of a mount that produced no +// keepUnmounted keeps what the layers of a mount that produced no // operation write, and says so once, at the mount's use site: a reader seeing // their declarations away from any operation needs to know why. Each layer // keeps what applyPathItem keeps, and its parameters (keepItemParams), less @@ -344,8 +344,8 @@ func onNearestNode(unmodeled *ir.Unmodeled, mountPtr jsontext.Pointer) carrier { // in from past nodeview.MergeDepthLimit is read by the model and not by // nodeview.Child, so a model predicate would claim a preservation that did not // happen. -func preserveUnmounted(layers []layer, owner owners, named []ir.ServerID, at mountSite) []ir.Diagnostic { - into := onNearestNode(at.residue, at.ptr) +func keepUnmounted(layers []layer, owner owners, named []ir.ServerID, at mountSite) []ir.Diagnostic { + into := onNearestNode(at.orphanUnmodeled, at.ptr) before := len(*into.unmodeled) var diags []ir.Diagnostic for i, layer := range layers { @@ -435,7 +435,7 @@ var pathItemDocKeywords = []string{"summary", "description"} // applyPathItemDocs writes a path item's summary and description into the // PathDocs into holds, less what cedes says another layer of the mount writes, -// so a $ref site's summary stands in front of its target's. Nothing is +// so a $ref site's summary sits in front of its target's. Nothing is // reported: the pair reaches a field. An item mounting none keeps the pair // verbatim beside what else it keeps on the nearest node, which // preserveUnmountedPathItem announces (GitHub #383). @@ -454,7 +454,7 @@ func applyPathItemDocs(serviceContext service.Ctx, into carrier, pi *soa.PathIte if cedes(constructOf(constructDoc, keyword)) { continue } - _, fieldDiags := annotation.PreserveNodeInto(into.unmodeled, annotation.EntryKey(into.scope, keyword), + _, fieldDiags := annotation.KeepNodeInto(into.unmodeled, annotation.EntryKey(into.scope, keyword), nodeview.Child(pi.GetRootNode(), keyword), ir.ReasonNoIRHome, serviceContext.Place().At(declPtr+ids.Ptr(keyword))) diags = append(diags, fieldDiags...) @@ -488,22 +488,22 @@ func keepItemParams(serviceContext service.Ctx, into carrier, pi *soa.PathItem, cedes func(string) bool, ) []ir.Diagnostic { var diags []ir.Diagnostic - ledger := newParamLedger(mountPtr) + numbering := newParameterNumbering(mountPtr) for i, rp := range pi.GetParameters() { slot, ok := paramKey(serviceContext.Bindings(), rp) if !ok || cedes(paramConstruct(slot)) { continue } - p := componentlookup.Object[soa.Parameter](serviceContext.Bindings(), rp) + parameter := componentlookup.Object[soa.Parameter](serviceContext.Bindings(), rp) entry := declPtr + ids.Ptr("parameters", strconv.Itoa(i)) - occurrence := ledger.count(p.GetName(), string(p.GetIn())) - key := "openapi:" + into.scope + string(ids.ParamPath(p.GetName(), string(p.GetIn()), occurrence)) - kept, keepDiags := annotation.PreserveNodeInto(into.unmodeled, key, rp.GetCore().GetRootNode(), + occurrence := numbering.count(parameter.GetName(), string(parameter.GetIn())) + key := "openapi:" + into.scope + string(ids.ParamPath(parameter.GetName(), string(parameter.GetIn()), occurrence)) + kept, keepDiags := annotation.KeepNodeInto(into.unmodeled, key, rp.GetCore().GetRootNode(), ir.ReasonNoIRHome, serviceContext.Place().At(entry)) + diags = append(diags, keepDiags...) if kept { - schema.RecordReached(serviceContext.Ctx, entry) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, entry)...) } - diags = append(diags, keepDiags...) } return diags } diff --git a/compilers/openapi/internal/operation/pathitem_internal_test.go b/compilers/openapi/internal/operation/pathitem_internal_test.go index 0d176eac9..52b9ef960 100644 --- a/compilers/openapi/internal/operation/pathitem_internal_test.go +++ b/compilers/openapi/internal/operation/pathitem_internal_test.go @@ -208,7 +208,7 @@ func pathItemOf(t *testing.T, src string) *soa.PathItem { // TestKeepOn_RefusesAnEntryTheOperationHolds pins that copying what a mount // keeps never replaces an entry the operation already holds: the entry is -// refused and reported, and the operation's own stands. +// refused and reported, and the operation's own remains. func TestKeepOn_RefusesAnEntryTheOperationHolds(t *testing.T) { t.Parallel() key := "openapi:pathItem/x-id" diff --git a/compilers/openapi/internal/operation/pathitem_test.go b/compilers/openapi/internal/operation/pathitem_test.go index c19990715..a2265d78e 100644 --- a/compilers/openapi/internal/operation/pathitem_test.go +++ b/compilers/openapi/internal/operation/pathitem_test.go @@ -409,9 +409,9 @@ func TestPathItem_AdditionalOperationsBindCallbacks(t *testing.T) { // binds an empty HTTP method, which no request can be sent with. // // The entry still lowers, so nothing it declares is lost — dropping it would -// trade a reported defect for a silent one, which is the trade this whole change -// exists to undo. speakeasy rejects a key naming a standard method and accepts -// this one, so the compiler is the only thing that can report it. +// trade a reported defect for an unreported one, which is the trade this whole +// change exists to undo. speakeasy rejects a key naming a standard method and +// accepts this one, so the compiler is the only thing that can report it. func TestPathItem_EmptyAdditionalOperationsKeyReported(t *testing.T) { t.Parallel() doc, diags := parseFull(t, `openapi: 3.2.0 @@ -629,11 +629,11 @@ paths: assert.Equal(t, 1, announced) } -// TestPathItem_WithNoOperationAndNothingToKeepIsSilent holds the other half: an -// item that produces no operation and wrote nothing beside it has lost nothing, -// so there is nothing to keep and nothing to announce. An empty summary and -// description document nothing either. -func TestPathItem_WithNoOperationAndNothingToKeepIsSilent(t *testing.T) { +// TestPathItem_WithNoOperationAndNothingToKeepReportsNothing holds the other +// half: an item that produces no operation and wrote nothing beside it has lost +// nothing, so there is nothing to keep and nothing to announce. An empty +// summary and description document nothing either. +func TestPathItem_WithNoOperationAndNothingToKeepReportsNothing(t *testing.T) { t.Parallel() svc, diags := serviceWithGrouping(t, `openapi: 3.1.0 info: {title: T, version: "1"} diff --git a/compilers/openapi/internal/operation/pathitemref.go b/compilers/openapi/internal/operation/pathitemref.go index 92c6a6faf..78e49a705 100644 --- a/compilers/openapi/internal/operation/pathitemref.go +++ b/compilers/openapi/internal/operation/pathitemref.go @@ -120,35 +120,35 @@ type itemConstruct struct { rel jsontext.Pointer } -// itemConstructs returns what layerValue declares, in the order its findings +// itemConstructs returns what layer declares, in the order its findings // are reported. -func itemConstructs(layerValue layer) []itemConstruct { +func itemConstructs(layer layer) []itemConstruct { var out []itemConstruct add := func(kind, name, label string, rel jsontext.Pointer) { out = append(out, itemConstruct{key: constructOf(kind, name), label: label, rel: rel}) } - for _, po := range pathOperations(layerValue.item) { + for _, po := range pathOperations(layer.item) { add(constructOperation, string(po.seg), "the "+po.method+" operation", po.seg) } for _, keyword := range pathItemDocKeywords { - if declaresText(layerValue.item, keyword) { + if declaresText(layer.item, keyword) { add(constructDoc, keyword, "the "+keyword, ids.Ptr(keyword)) } } - if len(layerValue.item.GetServers()) > 0 { + if len(layer.item.GetServers()) > 0 { add(constructServers, "", "the servers list", ids.Ptr("servers")) } - for _, name := range extensionNames(layerValue.item) { + for _, name := range extensionNames(layer.item) { add(constructExtension, name, "the extension "+strconv.Quote(name), ids.Ptr(name)) } - for _, key := range slices.Sorted(slices.Values(undeclaredPathItemKeys(layerValue.item))) { + for _, key := range slices.Sorted(slices.Values(undeclaredPathItemKeys(layer.item))) { add(constructKey, key, "the undeclared key "+strconv.Quote(key), ids.Ptr(key)) } - for i, rp := range layerValue.item.GetParameters() { - if slot, ok := paramKey(layerValue.in.Bindings(), rp); ok { - p := componentlookup.Object[soa.Parameter](layerValue.in.Bindings(), rp) + for i, rp := range layer.item.GetParameters() { + if slot, ok := paramKey(layer.in.Bindings(), rp); ok { + parameter := componentlookup.Object[soa.Parameter](layer.in.Bindings(), rp) out = append(out, itemConstruct{key: paramConstruct(slot), - label: fmt.Sprintf("the parameter %q in %s", p.GetName(), p.GetIn()), + label: fmt.Sprintf("the parameter %q in %s", parameter.GetName(), parameter.GetIn()), rel: ids.Ptr("parameters", strconv.Itoa(i))}) } } @@ -190,9 +190,9 @@ func (o owners) cedes(i int) func(key string) bool { } // precedence returns which of layers keeps each construct, and one finding for -// each declaration a nearer layer takes over, sited at the keeper's and naming -// the other's position, so neither is silent. One layer, every mount with -// nothing beside a $ref, keeps all it declares. +// each declaration a nearer layer takes over, sited at the chosen layer's and +// naming the other's position, so neither goes unreported. One layer, every +// mount with nothing beside a $ref, keeps all it declares. // // A farther layer is looked up by key, never scanned, so the work is the // constructs times the layers, which the reference chain bound caps. @@ -305,8 +305,8 @@ func mountedOperations(layers []layer) []layerOperation { } } } - for _, m := range httpMethods { - take(ids.Ptr(m.name)) + for _, method := range httpMethods { + take(ids.Ptr(method.name)) } for _, seg := range extra { take(seg) diff --git a/compilers/openapi/internal/operation/pathitemref_collisions_test.go b/compilers/openapi/internal/operation/pathitemref_collisions_test.go index e8e8f67c6..0fd20901a 100644 --- a/compilers/openapi/internal/operation/pathitemref_collisions_test.go +++ b/compilers/openapi/internal/operation/pathitemref_collisions_test.go @@ -52,8 +52,8 @@ paths: // TestPathItemRefSiblings_CollisionIsLoudAndUseSiteWins pins the collision rule // GitHub #577 settles: OpenAPI leaves the result of a field written beside a // $ref undefined, so the use site's declaration wins every construct, as a -// $ref-adjacent schema sibling's does, and the losing one is reported rather -// than dropped in silence. +// $ref-adjacent schema sibling's does, and the passed-over one is reported +// rather than dropped in silence. func TestPathItemRefSiblings_CollisionIsLoudAndUseSiteWins(t *testing.T) { t.Parallel() doc, diags := parseFull(t, pathItemRefCollisionSpec) @@ -187,7 +187,7 @@ func TestPathItemRefSiblings_CollisionIsOrderIndependent(t *testing.T) { "a collision is a property of the document, not of the order it was written in") for _, at := range []struct{ method, uri string }{{"GET", "/a"}, {"GET", "/b"}} { want, got := operationByPath(t, forwardDoc, at.method, at.uri), operationByPath(t, reversedDoc, at.method, at.uri) - assert.Empty(t, cmp.Diff(want, got), "what %s %s lowers to, the winners included, follows no order", at.method, at.uri) + assert.Empty(t, cmp.Diff(want, got), "what %s %s lowers to, the chosen ones included, follows no order", at.method, at.uri) } } diff --git a/compilers/openapi/internal/operation/pathitemref_fields_test.go b/compilers/openapi/internal/operation/pathitemref_fields_test.go index aa45cafdc..0647006f0 100644 --- a/compilers/openapi/internal/operation/pathitemref_fields_test.go +++ b/compilers/openapi/internal/operation/pathitemref_fields_test.go @@ -54,7 +54,7 @@ paths: // TestPathItemRefSiblings_AChainCarriesTheFieldsBesideEachRef pins a chain: the // path item a $ref names is that item with the fields beside its own $ref, so // /a mounts /b's put and /c's post, takes /b's servers, and keeps its own get -// and summary over both deeper ones, each loser named once. +// and summary over both deeper ones, each passed-over one named once. func TestPathItemRefSiblings_AChainCarriesTheFieldsBesideEachRef(t *testing.T) { t.Parallel() doc, diags := parseFull(t, pathItemRefChainSpec) @@ -84,7 +84,7 @@ func TestPathItemRefSiblings_AChainCarriesTheFieldsBesideEachRef(t *testing.T) { "/paths/~1a/get /paths/~1c/get", "/paths/~1a/summary /paths/~1b/summary", "/paths/~1b/get /paths/~1c/get", - }, collided, "each declaration a nearer one takes over is named once, at the one kept") + }, collided, "each declaration a nearer one takes over is named once, at the chosen one") } // TestPathItemRefSiblings_FieldsAnotherDocumentWritesAreModelled pins the chain diff --git a/compilers/openapi/internal/operation/pathitemref_references_test.go b/compilers/openapi/internal/operation/pathitemref_references_test.go index b0ed10fbb..e895123b6 100644 --- a/compilers/openapi/internal/operation/pathitemref_references_test.go +++ b/compilers/openapi/internal/operation/pathitemref_references_test.go @@ -734,9 +734,9 @@ components: // mapsTag reports whether a discriminator anywhere in doc maps tag. func mapsTag(doc *ir.Document, tag string) bool { - for _, td := range doc.Types { + for _, typeDef := range doc.Types { var discriminator *ir.Discriminator - switch n := td.(type) { + switch n := typeDef.(type) { case *ir.Union: discriminator = n.Discriminator case *ir.Model: diff --git a/compilers/openapi/internal/operation/pathkeys.go b/compilers/openapi/internal/operation/pathkeys.go index 7187b46e3..213db7a19 100644 --- a/compilers/openapi/internal/operation/pathkeys.go +++ b/compilers/openapi/internal/operation/pathkeys.go @@ -49,9 +49,9 @@ func pathKeyDiags(serviceContext service.Ctx, key string) []ir.Diagnostic { // Only the path is judged. A "?" ends it in a query, and a "#" outside a // template expression in a fragment, each named whole and nothing in it read. func pathKeyDefects(key string) []string { - pathKeyScanValue := pathKeyScan{key: key, fragmentAt: -1} - pathKeyScanValue.read() - return pathKeyScanValue.defects() + pathKeyScan := pathKeyScan{key: key, fragmentAt: -1} + pathKeyScan.read() + return pathKeyScan.defects() } // pathRoute splits a Paths Object key into the route a request is sent to and @@ -59,21 +59,21 @@ func pathKeyDefects(key string) []string { // which no request sends (RFC 3986 §3.5), without the "#". fragmented reports // whether the key carries one, empty or not. func pathRoute(key string) (route, fragment string, fragmented bool) { - pathKeyScanValue := pathKeyScan{key: key, fragmentAt: -1} - pathKeyScanValue.read() - if pathKeyScanValue.fragmentAt < 0 { + pathKeyScan := pathKeyScan{key: key, fragmentAt: -1} + pathKeyScan.read() + if pathKeyScan.fragmentAt < 0 { return key, "", false } - return key[:pathKeyScanValue.fragmentAt], key[pathKeyScanValue.fragmentAt+1:], true + return key[:pathKeyScan.fragmentAt], key[pathKeyScan.fragmentAt+1:], true } // pathOnly returns template, a URI template carrying no fragment, less the // query it carries: from the "?" a pathKeyScan reads as beginning one, so a // "?" inside a template expression begins none. func pathOnly(template string) string { - pathKeyScanValue := pathKeyScan{key: template, fragmentAt: -1} - pathKeyScanValue.read() - return template[:len(template)-len(pathKeyScanValue.query)] + pathKeyScan := pathKeyScan{key: template, fragmentAt: -1} + pathKeyScan.read() + return template[:len(template)-len(pathKeyScan.query)] } // pathKeyScan is one left-to-right reading of a Paths key, recording the path @@ -136,12 +136,12 @@ func (s *pathKeyScan) read() { // than a brace, then "}". A "{" that opens none is stray, and reading resumes // just past it, so what follows is read as path. func (s *pathKeyScan) expression(i int) int { - n := strings.IndexAny(s.key[i+1:], "{}") - if n <= 0 || s.key[i+1+n] == '{' { + offset := strings.IndexAny(s.key[i+1:], "{}") + if offset <= 0 || s.key[i+1+offset] == '{' { s.strayBrace = true return i + 1 } - name := s.key[i+1 : i+1+n] + name := s.key[i+1 : i+1+offset] if s.uses == nil { s.uses = make(map[string]int) } @@ -149,7 +149,7 @@ func (s *pathKeyScan) expression(i int) int { if s.uses[name] == 2 { s.repeated = append(s.repeated, name) } - return i + n + 2 + return i + offset + 2 } // percent reads the "%" at key[i] and returns where reading resumes. It must @@ -164,7 +164,7 @@ func (s *pathKeyScan) percent(i int) int { } // literal reads the character at key[i] and returns where reading resumes. A -// byte in pathLiteralBytes stands as written; any other character, non-ASCII +// byte in pathLiteralBytes is left as written; any other character, non-ASCII // included, a path admits only percent-encoded. A byte beginning no UTF-8 // encoding is read alone. func (s *pathKeyScan) literal(i int) int { @@ -229,8 +229,8 @@ func quotedList(items []string, prefix, suffix string) string { return strings.Join(quoted[:last], ", ") + " and " + quoted[last] } -// isHexDigit reports whether b is one of the sixteen hexadecimal digits, in +// isHexDigit reports whether character is one of the sixteen hexadecimal digits, in // either case. -func isHexDigit(b byte) bool { - return b >= '0' && b <= '9' || b >= 'a' && b <= 'f' || b >= 'A' && b <= 'F' +func isHexDigit(character byte) bool { + return character >= '0' && character <= '9' || character >= 'a' && character <= 'f' || character >= 'A' && character <= 'F' } diff --git a/compilers/openapi/internal/operation/pathkeys_internal_test.go b/compilers/openapi/internal/operation/pathkeys_internal_test.go index 89cafb87b..04ea2a4f6 100644 --- a/compilers/openapi/internal/operation/pathkeys_internal_test.go +++ b/compilers/openapi/internal/operation/pathkeys_internal_test.go @@ -142,7 +142,7 @@ func TestPathKeyDefects(t *testing.T) { } // TestPathKeyDefects_EveryByte reads each byte between two letters and holds -// the verdict to RFC 3986's pchar, so no byte is admitted or refused by a slip +// the answer to RFC 3986's pchar, so no byte is admitted or refused by a slip // in pathLiteralBytes. The bytes with a reading of their own are left to the // table above. func TestPathKeyDefects_EveryByte(t *testing.T) { diff --git a/compilers/openapi/internal/operation/recopy.go b/compilers/openapi/internal/operation/recopy.go index 8f23501e4..fed5fdc43 100644 --- a/compilers/openapi/internal/operation/recopy.go +++ b/compilers/openapi/internal/operation/recopy.go @@ -33,8 +33,8 @@ func chargeItemCopy(serviceContext service.Ctx, kept, servers int, taken []sourc if sp.in != nil { pc = *sp.in } - if p := componentlookup.Object[soa.Parameter](serviceContext.Bindings(), sp.ref); p != nil { - service.ChargeExpansionAt(pc, sp.pointer, p.GetRootNode()) + if parameter := componentlookup.Object[soa.Parameter](serviceContext.Bindings(), sp.ref); parameter != nil { + service.ChargeExpansionAt(pc, sp.pointer, parameter.GetRootNode()) } } } diff --git a/compilers/openapi/internal/operation/responses.go b/compilers/openapi/internal/operation/responses.go index 07c1d69ed..92c06370c 100644 --- a/compilers/openapi/internal/operation/responses.go +++ b/compilers/openapi/internal/operation/responses.go @@ -59,8 +59,8 @@ func lowerResponses(serviceContext service.Ctx, loweringState operationLoweringS // operation to make the same mistake lost its warning to the first, // since the diagnostic stream dedups on full identity. entry := operationDeclPtr + ids.Ptr("responses", code) - r, rc, rptr := service.Declared[soa.Response](serviceContext, rr, entry) - if r == nil { + response, rc, rptr := service.Declared[soa.Response](serviceContext, rr, entry) + if response == nil { continue } beside, besideDiags := service.Beside[soa.Response](serviceContext, rr, entry, true) @@ -78,13 +78,13 @@ func lowerResponses(serviceContext service.Ctx, loweringState operationLoweringS // statusConditions lets the success side record no status at all. // TestStatusRange_NamesNoStatus is what pins the pairing. if isErrorRange(rng) { - ec, drafts, ecDiags := lowerErrorCase(rc, loweringState, r, code, rng, rptr, rr) + ec, drafts, ecDiags := lowerErrorCase(rc, loweringState, response, code, rng, rptr, rr) ec.Unmodeled = annotation.MergeUnmodeled(ec.Unmodeled, beside) diags = append(diags, ecDiags...) loweringState.links.add(operation.ID, responseSlot{list: compileddoc.ListErrors, index: len(operation.Errors)}, drafts) operation.Errors = append(operation.Errors, ec) } else { - resp, drafts, respDiags := lowerResponse(rc, loweringState, r, code, statusConditions(rng, named), rptr, rr) + resp, drafts, respDiags := lowerResponse(rc, loweringState, response, code, statusConditions(rng, named), rptr, rr) resp.Unmodeled = annotation.MergeUnmodeled(resp.Unmodeled, beside) diags = append(diags, respDiags...) loweringState.links.add(operation.ID, responseSlot{list: compileddoc.ListResponses, index: len(operation.Responses)}, drafts) @@ -145,8 +145,8 @@ func duplicateStatusKeyDiags(serviceContext service.Ctx, byRange map[ir.StatusRa // status (see statusConditions). ref is the entry the document wrote there, // which carries the summary and description a Reference Object may put beside // its $ref. -func lowerResponse(serviceContext service.Ctx, loweringState operationLoweringState, r *soa.Response, code string, conds ir.ResponseConditions, rptr jsontext.Pointer, ref *soa.ReferencedResponse) (ir.Response, []linkDraft, []ir.Diagnostic) { - parts, diags := lowerResponseParts(serviceContext, loweringState, r, code, rptr, ref) +func lowerResponse(serviceContext service.Ctx, loweringState operationLoweringState, response *soa.Response, code string, conds ir.ResponseConditions, rptr jsontext.Pointer, ref *soa.ReferencedResponse) (ir.Response, []linkDraft, []ir.Diagnostic) { + parts, diags := lowerResponseParts(serviceContext, loweringState, response, code, rptr, ref) resp := ir.Response{ Name: parts.name, Conditions: conds, @@ -179,55 +179,43 @@ type responseParts struct { // error interns its body once, so two naming fallbacks would rename it when // paths are reordered. The use-site docs fold over ref, the entry written here, // must agree across classes for the same reason (GitHub #610). -func lowerResponseParts(serviceContext service.Ctx, loweringState operationLoweringState, r *soa.Response, code string, rptr jsontext.Pointer, ref *soa.ReferencedResponse) (responseParts, []ir.Diagnostic) { - headers, diags := lowerHeaders(serviceContext, loweringState, r.GetHeaders(), rptr) - payload, payloadDiags := lowerPayload(serviceContext, loweringState, r.GetContent(), rptr) +func lowerResponseParts(serviceContext service.Ctx, loweringState operationLoweringState, response *soa.Response, code string, rptr jsontext.Pointer, ref *soa.ReferencedResponse) (responseParts, []ir.Diagnostic) { + headers, diags := lowerHeaders(serviceContext, loweringState, response.GetHeaders(), rptr) + payload, payloadDiags := lowerPayload(serviceContext, loweringState, response.GetContent(), rptr) diags = append(diags, payloadDiags...) - parts := responseParts{name: responseName(code), payload: payload, headers: headers} - summary, taken, summaryDiags := responseSummary(serviceContext, &parts.unmodeled, r, rptr) + // OpenAPI names no response, so its neutral naming hints at the status key as + // declared, not the range it parses to (GitHub #259, #262); Source stays + // empty, as a components/responses key names a reusable definition. + parts := responseParts{name: compile.NamingHint(code), payload: payload, headers: headers} + summary, taken, summaryDiags := responseSummary(serviceContext, &parts.unmodeled, response, rptr) diags = append(diags, summaryDiags...) - parts.docs = componentlookup.UseDocs[soa.Response](serviceContext.Bindings(), ref, ir.Docs{Summary: summary, Description: r.GetDescription()}) - links, linkDiags := draftLinks(serviceContext, r, rptr) + parts.docs = componentlookup.UseDocs[soa.Response](serviceContext.Bindings(), ref, ir.Docs{Summary: summary, Description: response.GetDescription()}) + links, linkDiags := draftLinks(serviceContext, response, rptr) parts.links = links diags = append(diags, linkDiags...) - return parts, append(diags, preserveResponseExtras(serviceContext, &parts.unmodeled, r, rptr, taken...)...) + return parts, append(diags, keepResponseExtras(serviceContext, &parts.unmodeled, response, rptr, taken...)...) } // responseSummary reads the summary OpenAPI 3.2 gives a Response Object, which // the parser's model names no member for (GitHub #615), and returns the keys it // read for the census to leave alone. It reads at every version, as load // reports the key below 3.2 (diag.LaterVersionConstruct). -func responseSummary(serviceContext service.Ctx, unmodeled *ir.Unmodeled, r *soa.Response, rptr jsontext.Pointer) (string, []string, []ir.Diagnostic) { - summary, read, diags := annotation.TakeString(unmodeled, r.GetRootNode(), "summary", nil, serviceContext.Place(), rptr, "") +func responseSummary(serviceContext service.Ctx, unmodeled *ir.Unmodeled, response *soa.Response, rptr jsontext.Pointer) (string, []string, []ir.Diagnostic) { + summary, read, diags := annotation.TakeString(unmodeled, response.GetRootNode(), "summary", nil, serviceContext.Place(), rptr, "") if !read { return "", nil, diags } return summary, []string{"summary"}, diags } -// preserveResponseExtras keeps what a Response Object declares that has no home +// keepResponseExtras keeps what a Response Object declares that has no home // on its node: its x-* extensions, and the undefined keys other than taken // (responseSummary's). One helper serves ir.Response and ir.ErrorCase, so // neither keeps a construct the other drops (GitHub #275). -func preserveResponseExtras(serviceContext service.Ctx, unmodeled *ir.Unmodeled, r *soa.Response, rptr jsontext.Pointer, taken ...string) []ir.Diagnostic { - ext, diags := annotation.ExtensionsFrom(r.GetExtensions(), serviceContext.Place(), rptr) +func keepResponseExtras(serviceContext service.Ctx, unmodeled *ir.Unmodeled, response *soa.Response, rptr jsontext.Pointer, taken ...string) []ir.Diagnostic { + ext, diags := annotation.ExtensionsFrom(response.GetExtensions(), serviceContext.Place(), rptr) *unmodeled = annotation.MergeUnmodeled(*unmodeled, ext) - return append(diags, annotation.UnknownKeysIn(unmodeled, r, serviceContext.Place(), rptr, taken...)...) -} - -// responseName builds a success response's neutral naming. OpenAPI names no -// response, so the hint docs/ir/responses.md allows is the status key: "200", -// "2_xx", or the shared mint for a key with no word in it (GitHub #259). -// -// It is the key as declared, not the range it parses to, so "2XX" is not named -// by a spelling its document never used, nor a key naming no status by the -// catch-all range (GitHub #262). Source stays empty: a components/responses key -// names a reusable definition, not this mount of it. -// -// The error side calls this too, since ErrorCase.Name is Response.Name (GitHub -// #422). -func responseName(code string) ir.Naming { - return compile.NamingHint(code) + return append(diags, annotation.UnknownKeysIn(unmodeled, response, serviceContext.Place(), rptr, taken...)...) } // lowerErrorCase lowers one error response into an ErrorCase: naming, status @@ -239,8 +227,8 @@ func responseName(code string) ir.Naming { // #422). code is the responses-map key, the only record of how the source // spelled a status its range cannot state ("4XX"); ref is the entry written // here. -func lowerErrorCase(serviceContext service.Ctx, loweringState operationLoweringState, r *soa.Response, code string, rng ir.StatusRange, rptr jsontext.Pointer, ref *soa.ReferencedResponse) (ir.ErrorCase, []linkDraft, []ir.Diagnostic) { - parts, diags := lowerResponseParts(serviceContext, loweringState, r, code, rptr, ref) +func lowerErrorCase(serviceContext service.Ctx, loweringState operationLoweringState, response *soa.Response, code string, rng ir.StatusRange, rptr jsontext.Pointer, ref *soa.ReferencedResponse) (ir.ErrorCase, []linkDraft, []ir.Diagnostic) { + parts, diags := lowerResponseParts(serviceContext, loweringState, response, code, rptr, ref) ec := ir.ErrorCase{ Name: parts.name, Conditions: ir.ResponseConditions{StatusCodes: []ir.StatusRange{rng}}, @@ -283,10 +271,10 @@ func statusRange(code string) (ir.StatusRange, bool) { return ir.StatusRange{From: base + rest, To: base + rest}, true } -// isWildcard reports whether b is the wildcard character of a status range. +// isWildcard reports whether character is the wildcard character of a status range. // OpenAPI writes it uppercase; lowercase is read too, because the reading is // unambiguous and documents in the wild spell it both ways. -func isWildcard(b byte) bool { return b == 'X' || b == 'x' } +func isWildcard(character byte) bool { return character == 'X' || character == 'x' } // twoDigits reads the tens and units of a status-code key, reporting false when // either character is not a digit. It is what separates "200" from "20A" and @@ -330,7 +318,7 @@ func invalidStatusKeyDiag(serviceContext service.Ctx, code string, entry jsontex // to one status range. // // A warning, and every response is kept: no key is wrong on its own, and -// dropping one would choose a winner on declaration order. The caller is told +// dropping one would choose one on declaration order. The caller is told // the entries answer to one status and cannot be told apart by name or // condition. It is sited at the map and names all the keys, so the report reads // the same from either spelling of the map. diff --git a/compilers/openapi/internal/operation/responses_test.go b/compilers/openapi/internal/operation/responses_test.go index 303519e51..a4888707a 100644 --- a/compilers/openapi/internal/operation/responses_test.go +++ b/compilers/openapi/internal/operation/responses_test.go @@ -439,7 +439,7 @@ func TestErrorCase_EveryMediaTypeIsAContent(t *testing.T) { multi := errs[400] require.NotNil(t, multi.Payload) - require.Len(t, multi.Payload.Contents, 2, "every media type is kept, none elected") + require.Len(t, multi.Payload.Contents, 2, "every media type is kept, none chosen") assert.Equal(t, []string{"application/json", "application/problem+json"}, []string{multi.Payload.Contents[0].MediaType, multi.Payload.Contents[1].MediaType}) assert.NotEqual(t, multi.Payload.Contents[0].Type.Target, multi.Payload.Contents[1].Type.Target, @@ -550,9 +550,9 @@ func TestResponses_ASharedBodyIsNamedAlikeFromEitherStatusClass(t *testing.T) { t.Helper() doc, _, diags := compileService(t, openapitest.PathsSpec(paths)) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types["type/anonymous/paths/~1a/get/responses/200/content/application~1json/schema"] + typeDef, ok := doc.Types["type/anonymous/paths/~1a/get/responses/200/content/application~1json/schema"] require.True(t, ok, "the shared body is interned once at its declaration pointer; got %v", slices.Sorted(maps.Keys(doc.Types))) - return td.Common().Name.Hint + return typeDef.Common().Name.Hint } successFirst := hintOf(success + failure) diff --git a/compilers/openapi/internal/operation/runchains.go b/compilers/openapi/internal/operation/runchains.go new file mode 100644 index 000000000..eddea569d --- /dev/null +++ b/compilers/openapi/internal/operation/runchains.go @@ -0,0 +1,70 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package operation + +import ( + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/service" + "github.com/dexpace/morphic/ir" +) + +// runChains is what operation's settlements read of the registry and its +// alias chains, each chain's first encoding read once for the run. Of a +// chain's end it holds only the ID, reading the node when asked. Like its +// index, it is not safe for concurrent use. +type runChains struct { + reg ir.TypeRegistry + lookup func(ir.TypeID) (ir.TypeDef, bool) + index *ir.AliasChainIndex + encodings *ir.AliasChainAnswers[string] +} + +// newRunChains returns the readings of reg's alias chains through lookup and +// index, both over reg. +func newRunChains(reg ir.TypeRegistry, lookup func(ir.TypeID) (ir.TypeDef, bool), index *ir.AliasChainIndex) *runChains { + encodings := ir.NewAliasChainAnswers(index, func(ir.TypeID, ir.TypeDef) string { return "" }, + func(scalar *ir.Scalar, next string) string { + if scalar.Encoding.Encodes() { + return scalar.Encoding.Name + } + return next + }) + return &runChains{reg: reg, lookup: lookup, index: index, encodings: encodings} +} + +// runChainsOf returns the run's readings of reg's alias chains through +// aliases, built at the first settlement reading them and shared by the rest, +// as each form body, item and stream settles on its own. Readings built over +// another index are not reused, so none answers for an index it does not read. +func runChainsOf(serviceContext service.Ctx, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) *runChains { + chains := lowering.Settled(serviceContext.Ctx, func() *runChains { return newRunChains(reg, reg.Lookup, aliases) }) + if chains.index != aliases { + return newRunChains(reg, reg.Lookup, aliases) + } + return chains +} + +// end returns the type the chain of alias scalars from id ends on, however +// long: found false, and no type, where a link names no node, and cyclic where +// it meets an alias twice, which ends it on that alias. +func (chains *runChains) end(id ir.TypeID) chainEnd { + end, cyclic := chains.index.End(id) + typeDef, found := chains.lookup(end) + return chainEnd{typeDef: typeDef, found: found, cyclic: cyclic} +} + +// chainEnd is the type a chain of alias scalars ends on (runChains.end). +type chainEnd struct { + typeDef ir.TypeDef + found bool + cyclic bool +} + +// firstEncoding returns the name of the encoding the nearest scalar of the +// chain from id naming one names, and "" where none does or the chain is +// cyclic or names no node. +func (chains *runChains) firstEncoding(id ir.TypeID) string { + name, _ := chains.encodings.AnswerFor(id) + return name +} diff --git a/compilers/openapi/internal/operation/runchains_internal_test.go b/compilers/openapi/internal/operation/runchains_internal_test.go new file mode 100644 index 000000000..38947e590 --- /dev/null +++ b/compilers/openapi/internal/operation/runchains_internal_test.go @@ -0,0 +1,117 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package operation + +import ( + "fmt" + "testing" + + soa "github.com/speakeasy-api/openapi/openapi" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/ir" +) + +// chainsOver is the readings of reg's alias chains a test reads, reading reg +// through its own lookup. +func chainsOver(reg ir.TypeRegistry) *runChains { + return chainsThrough(reg, reg.Lookup) +} + +// chainsThrough is the readings of reg's alias chains a test reads, reading +// every type through lookup, which the test may count. +func chainsThrough(reg ir.TypeRegistry, lookup func(ir.TypeID) (ir.TypeDef, bool)) *runChains { + return newRunChains(reg, lookup, ir.NewAliasChainIndex(lookup)) +} + +// bytesDownAChain is a chain of n aliases over bytes, the one at encoded, +// where encoded is below n, naming base64, and a list of each alias. +func bytesDownAChain(count, encoded int) ir.TypeRegistry { + bytes := ir.PrimitiveTypeID(ir.PrimitiveBytes) + reg := ir.TypeRegistry{bytes: &ir.Primitive{ID: bytes, PrimitiveKind: ir.PrimitiveBytes}} + base := bytes + for i := range count { + id := ir.TypeID(fmt.Sprintf("type/B%d", i)) + alias := &ir.Scalar{ID: id, Base: &ir.TypeRef{Target: base}} + if i == encoded { + alias.Encoding = &ir.Encoding{Name: "base64"} + } + reg[id], base = alias, id + list := ir.TypeID(fmt.Sprintf("type/L%d", i)) + reg[list] = &ir.List{ID: list, ElementType: ir.TypeRef{Target: id}} + } + return reg +} + +// TestRunChains_ReadEachChainOncePerRun pins what a run's settlements read of +// one long chain many parts reach: a part on every link of a chain of 1,000, +// 2,000 and 4,000 aliases over bytes, as a list, reads in lookups growing +// linearly, each link read once for the run, and travels raw only below the +// alias naming an encoding. +func TestRunChains_ReadEachChainOncePerRun(t *testing.T) { + t.Parallel() + var counts [3]int + for i, n := range []int{1000, 2000, 4000} { + reg := bytesDownAChain(n, n/2) + reads := 0 + chains := chainsThrough(reg, func(id ir.TypeID) (ir.TypeDef, bool) { + reads++ + typeDef, found := reg[id] + return typeDef, found + }) + for link := range n { + flags := memberFlags(chains, ir.TypeRef{Target: ir.TypeID(fmt.Sprintf("type/L%d", link))}, true) + require.True(t, flags.multi && flags.decided, "%d links: L%d repeats", n, link) + require.Equal(t, link < n/2, flags.file, "%d links: B%d is raw bytes below the encoded alias alone", n, link) + } + counts[i] = reads + } + assert.LessOrEqual(t, float64(counts[2]-counts[1]), 2.5*float64(counts[1]-counts[0]), + "lookups at 1,000, 2,000 and 4,000 links: %v", counts) +} + +// TestRunChains_ReadAChainToItsEnd pins the answers of the run's readings at +// a chain's two ends: a cycle of aliases is decided as no file, and reads no +// value or list; a chain naming no node is undecided and reads no value. +func TestRunChains_ReadAChainToItsEnd(t *testing.T) { + t.Parallel() + reg := ir.TypeRegistry{ + "type/A": &ir.Scalar{ID: "type/A", Base: &ir.TypeRef{Target: "type/B"}}, + "type/B": &ir.Scalar{ID: "type/B", Base: &ir.TypeRef{Target: "type/A"}}, + "type/Gone": &ir.Scalar{ID: "type/Gone", Base: &ir.TypeRef{Target: "type/absent"}}, + } + chains := chainsOver(reg) + + assert.Equal(t, structuralFlags{decided: true}, memberFlags(chains, ir.TypeRef{Target: "type/A"}, true), "a cycle is decided as no file") + assert.Equal(t, structuralFlags{}, memberFlags(chains, ir.TypeRef{Target: "type/Gone"}, true), "a chain naming no node is undecided") + assert.Nil(t, bodyNode(chains, "type/A"), "a cycle names no node") + _, listed := listBehind(chains, "type/A") + assert.False(t, listed) + assert.Equal(t, valueReading{}, readValue(newPartUnions(), chains, specrules.Table().EncodingRules("3.1.0"), ir.TypeRef{Target: "type/A"}, unencoded)) + assert.Equal(t, valueReading{}, readValue(newPartUnions(), chains, specrules.Table().EncodingRules("3.1.0"), ir.TypeRef{Target: "type/Gone"}, unencoded)) + assert.Empty(t, chains.firstEncoding("type/A")) +} + +// TestRunChainsOf_ReadsOneIndexOncePerRun pins the run's store: every +// settlement of a run handed one index reads one set of readings, and an index +// other than the one they were built over is read by readings of its own, +// which read its registry. +func TestRunChainsOf_ReadsOneIndexOncePerRun(t *testing.T) { + t.Parallel() + lowerer := newRawLowerer(&soa.OpenAPI{}) + first := ir.TypeRegistry{"type/L": &ir.List{ID: "type/L"}} + other := ir.TypeRegistry{"type/L": &ir.Scalar{ID: "type/L"}} + firstIndex := ir.NewAliasChainIndex(first.Lookup) + + chains := runChainsOf(lowerer.ctx, first, firstIndex) + assert.Same(t, chains, runChainsOf(lowerer.ctx, first, firstIndex), "one index, one set of readings") + apart := runChainsOf(lowerer.ctx, other, ir.NewAliasChainIndex(other.Lookup)) + assert.NotSame(t, chains, apart) + _, listed := listBehind(apart, "type/L") + assert.False(t, listed, "the other registry's node is read") + _, listed = listBehind(chains, "type/L") + assert.True(t, listed) +} diff --git a/compilers/openapi/internal/operation/sequential.go b/compilers/openapi/internal/operation/sequential.go index e70baaa71..3b8667ac8 100644 --- a/compilers/openapi/internal/operation/sequential.go +++ b/compilers/openapi/internal/operation/sequential.go @@ -76,12 +76,12 @@ func fillSequential(serviceContext service.Ctx, loweringState operationLoweringS // encoding of parts a body with none does not have. Load warns of the field. func keepItemEncoding(serviceContext service.Ctx, content *ir.Content, media *soa.MediaType, mediaPtr jsontext.Pointer) []ir.Diagnostic { at := mediaPtr + ids.Ptr("itemEncoding") - kept, diags := annotation.PreserveNodeInto(&content.Unmodeled, "openapi:itemEncoding", + kept, diags := annotation.KeepNodeInto(&content.Unmodeled, "openapi:itemEncoding", nodeview.Child(media.GetRootNode(), "itemEncoding"), ir.ReasonNoIRHome, serviceContext.Place().At(at)) if !kept { return diags } - schema.RecordReached(serviceContext.Ctx, at) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, at)...) return append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, "itemEncoding belongs to a media type that is not multipart, where it has no effect, so Content.ItemEncoding "+ "has none; kept verbatim under Unmodeled")) @@ -123,14 +123,14 @@ func positionalEncoding(serviceContext service.Ctx, content *ir.Content, media * // lowering here: an itemEncoding beside it is optional, so its absence must not // suppress the message, and its own conversion failure reports separately. at := mediaPtr + ids.Ptr("prefixEncoding") - kept, diags := annotation.PreserveNodeInto(&content.Unmodeled, "openapi:prefixEncoding", + kept, diags := annotation.KeepNodeInto(&content.Unmodeled, "openapi:prefixEncoding", nodeview.Child(root, "prefixEncoding"), ir.ReasonNoIRHome, serviceContext.Place().At(at)) itemAt := mediaPtr + ids.Ptr("itemEncoding") - itemKept, itemDiags := annotation.PreserveNodeInto(&content.Unmodeled, "openapi:itemEncoding", + itemKept, itemDiags := annotation.KeepNodeInto(&content.Unmodeled, "openapi:itemEncoding", nodeview.Child(root, "itemEncoding"), ir.ReasonNoIRHome, serviceContext.Place().At(itemAt)) diags = append(diags, itemDiags...) if itemKept { - schema.RecordReached(serviceContext.Ctx, itemAt) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, itemAt)...) } if !kept { // Reaching here means prefixEncoding is declared — that is the only reason @@ -141,7 +141,7 @@ func positionalEncoding(serviceContext service.Ctx, content *ir.Content, media * "prefixEncoding is declared but its source node could not be read; it is "+ "represented in the IR in no form at all")) } - schema.RecordReached(serviceContext.Ctx, at) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, at)...) return append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, mediaPtr, "prefixEncoding is positional and has no per-item IR home; it and any itemEncoding are kept under Unmodeled")) } diff --git a/compilers/openapi/internal/operation/sharedroute.go b/compilers/openapi/internal/operation/sharedroute.go index 319cd5835..792792abb 100644 --- a/compilers/openapi/internal/operation/sharedroute.go +++ b/compilers/openapi/internal/operation/sharedroute.go @@ -22,9 +22,9 @@ type route struct { // callback's is a runtime expression, so neither is counted. func (g *serviceGroups) markSharedRoutes() { routed := map[route]int{} - g.eachRoutedBinding(func(_ *ir.HTTPBinding, routeValue route) { routed[routeValue]++ }) - g.eachRoutedBinding(func(hb *ir.HTTPBinding, routeValue route) { - if routed[routeValue] > 1 { + g.eachRoutedBinding(func(_ *ir.HTTPBinding, route route) { routed[route]++ }) + g.eachRoutedBinding(func(hb *ir.HTTPBinding, route route) { + if routed[route] > 1 { hb.SharedRoute = true } }) @@ -50,17 +50,17 @@ func (g *serviceGroups) eachRoutedBinding(visit func(*ir.HTTPBinding, route)) { // templates of one shape route the same requests, as OpenAPI says of paths // that differ only in their expressions' names. func routeShape(template string) string { - var b strings.Builder - b.Grow(len(template)) + var builder strings.Builder + builder.Grow(len(template)) for i := 0; i < len(template); i++ { - b.WriteByte(template[i]) + builder.WriteByte(template[i]) if template[i] != '{' { continue } - if n := strings.IndexAny(template[i+1:], "{}"); n > 0 && template[i+1+n] == '}' { - b.WriteByte('}') - i += n + 1 + if offset := strings.IndexAny(template[i+1:], "{}"); offset > 0 && template[i+1+offset] == '}' { + builder.WriteByte('}') + i += offset + 1 } } - return b.String() + return builder.String() } diff --git a/compilers/openapi/internal/operation/streaming.go b/compilers/openapi/internal/operation/streaming.go index 3df4df28b..435c08134 100644 --- a/compilers/openapi/internal/operation/streaming.go +++ b/compilers/openapi/internal/operation/streaming.go @@ -29,27 +29,22 @@ type streamCandidate struct { // media type's schema applies to the whole body, which OpenAPI maps to an array // of its values (3.2 §4.14.3.1), so a list describes the body and its Elem one // frame. Any other schema has no array to read, and is the frame itself. -func (s streamCandidate) frame(reg ir.TypeRegistry) ir.TypeRef { +func (s streamCandidate) frame(chains *runChains) ir.TypeRef { if s.item { return s.events } - if list, ok := listBehind(reg, s.events.Target); ok { + if list, ok := listBehind(chains, s.events.Target); ok { return list.ElementType } return s.events } -// listBehind returns the List id stands for, read through the alias scalars a -// $ref with siblings hoists, and false where it stands for anything else. -func listBehind(reg ir.TypeRegistry, id ir.TypeID) (*ir.List, bool) { - for range maxBodyAliasHops { - base, alias := ir.AliasBase(reg, id) - if !alias { - break - } - id = base - } - list, ok := reg[id].(*ir.List) +// listBehind returns the List id names, read through the alias scalars a +// $ref with siblings hoists however many there are, and false where it is +// for anything else, a cycle of aliases among them (runChains.end). +func listBehind(chains *runChains, id ir.TypeID) (*ir.List, bool) { + typeDef := chains.end(id).typeDef + list, ok := typeDef.(*ir.List) return list, ok } @@ -85,8 +80,8 @@ func applyStreaming(serviceContext service.Ctx, ts *compile.Types, operation *ir if len(request) == 0 && len(response) == 0 { return "" } - operation.RequestStream = electStream(serviceContext, ts, request, declPtr+ids.Ptr("requestBody"), "request") - operation.ResponseStream = electStream(serviceContext, ts, response, declPtr+ids.Ptr("responses"), "response") + operation.RequestStream = chooseStreamElement(serviceContext, ts, request, declPtr+ids.Ptr("requestBody"), "request") + operation.ResponseStream = chooseStreamElement(serviceContext, ts, response, declPtr+ids.Ptr("responses"), "response") operation.Streaming = streamingMode(operation.RequestStream != nil, operation.ResponseStream != nil) var markers []ir.Inferred for _, candidate := range slices.Concat(request, response) { @@ -95,10 +90,10 @@ func applyStreaming(serviceContext service.Ctx, ts *compile.Types, operation *ir return ir.JoinInferred(markers...) } -// electStream returns the detail of a direction with candidates, nil for one -// with none, and queues the election of its element. pointer and direction name +// chooseStreamElement returns the detail of a direction with candidates, nil for one +// with none, and queues the choice of its element. pointer and direction name // the direction in the report a disagreement draws. -func electStream(serviceContext service.Ctx, ts *compile.Types, candidates []streamCandidate, pointer jsontext.Pointer, direction string) *ir.StreamDetail { +func chooseStreamElement(serviceContext service.Ctx, ts *compile.Types, candidates []streamCandidate, pointer jsontext.Pointer, direction string) *ir.StreamDetail { if len(candidates) == 0 { return nil } @@ -107,11 +102,11 @@ func electStream(serviceContext service.Ctx, ts *compile.Types, candidates []str return detail } -// streamElement elects one direction's Events once the registry is whole +// streamElement chooses one direction's Events once the registry is whole // (compile.Settlement): a frame can be a node a $ref promised, not built mid-walk, // so reading it there would follow declaration order. // -// Candidates that disagree elect nothing, and unelectedElementDiag reports it: +// Candidates that disagree choose nothing, and unchosenElementDiag reports it: // StreamDetail holds one Events per direction while Payload keeps every media type, // so naming one would be the primary-content selection invariant 2 forbids. They are // compared, not counted: one frame under two media types is content negotiation. == @@ -126,11 +121,12 @@ type streamElement struct { } // Settle writes the element to the detail and no node of reg. -func (e streamElement) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { - events := e.candidates[0].frame(reg) +func (e streamElement) Settle(_ context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + chains := runChainsOf(e.c, reg, aliases) + events := e.candidates[0].frame(chains) for _, candidate := range e.candidates[1:] { - if candidate.frame(reg) != events { - return []ir.Diagnostic{unelectedElementDiag(e.c, e.pointer, e.direction)} + if candidate.frame(chains) != events { + return []ir.Diagnostic{unchosenElementDiag(e.c, e.pointer, e.direction)} } } e.detail.Events = &events @@ -196,15 +192,15 @@ func streamingMode(request, response bool) ir.StreamingMode { } } -// unelectedElementDiag reports a direction whose element type was left unnamed +// unchosenElementDiag reports a direction whose element type was left unnamed // because its streaming contents name different ones. Nothing is lost — every // content is still on the payload — but the IR now says less than the source -// did, which is what makes it a degradation rather than a silent choice. +// did, which is what makes it a degradation rather than an unreported choice. // // It names the disagreement rather than counting media types: contents that // agree keep their element, and one media type appearing on two responses is // not several media types. -func unelectedElementDiag(serviceContext service.Ctx, pointer jsontext.Pointer, direction string) ir.Diagnostic { +func unchosenElementDiag(serviceContext service.Ctx, pointer jsontext.Pointer, direction string) ir.Diagnostic { return serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, "the %s streams more than one element type, so it is left unnamed rather than electing one", direction) } diff --git a/compilers/openapi/internal/operation/streaming_test.go b/compilers/openapi/internal/operation/streaming_test.go index 1a1047fb3..ee46c19d7 100644 --- a/compilers/openapi/internal/operation/streaming_test.go +++ b/compilers/openapi/internal/operation/streaming_test.go @@ -177,7 +177,7 @@ func TestStreaming_ItemSchemaDeclaresTheStream(t *testing.T) { // StreamDetail holds one element type per direction while Payload keeps every // media type, so naming one of two streaming contents would be the // primary-content selection invariant 2 forbids a compiler to make. The -// direction still streams, and the refusal is reported rather than silent. +// direction still streams, and the refusal is reported. func TestStreaming_SeveralStreamingContentsLeaveTheElementUnnamed(t *testing.T) { t.Parallel() spec := openapitest.PathsSpec(` /events: @@ -204,8 +204,8 @@ func TestStreaming_SeveralStreamingContentsLeaveTheElementUnnamed(t *testing.T) assert.Equal(t, ir.StreamingBidirectional, operation.Streaming) require.NotNil(t, operation.RequestStream) require.NotNil(t, operation.ResponseStream) - assert.Nil(t, operation.RequestStream.Events, "two candidate element types, so none is elected") - assert.Nil(t, operation.ResponseStream.Events, "two candidate element types, so none is elected") + assert.Nil(t, operation.RequestStream.Events, "two candidate element types, so none is chosen") + assert.Nil(t, operation.ResponseStream.Events, "two candidate element types, so none is chosen") require.NotNil(t, operation.Request) assert.Len(t, operation.Request.Contents, 2, "every content is still kept") @@ -293,7 +293,7 @@ func TestStreaming_AnItemSchemaIsItsFrameWhateverItHolds(t *testing.T) { assert.IsType(t, &ir.List{}, doc.Types[operation.ResponseStream.Events.Target]) } -// TestStreaming_ContentsCompareByTheirFrames holds the election to what each frame +// TestStreaming_ContentsCompareByTheirFrames holds the choice to what each frame // is, not how a schema spelled it: a list of one type agrees with that type, and two // lists of different types disagree, which comparing the lists could not tell from // two spellings of one element. @@ -429,7 +429,7 @@ func TestStreaming_OrdinaryContentDoesNotStream(t *testing.T) { // TestStreaming_ContentOrderDoesNotChooseAnElement is the two-order oracle for // the one place a choice was available. Compiled with the two streaming media // types declared either way round, the operation's streaming fields have to -// agree — electing the first candidate would pass a single-order test and +// agree — choosing the first candidate would pass a single-order test and // produce a different element type here. func TestStreaming_ContentOrderDoesNotChooseAnElement(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/operation/typespelling.go b/compilers/openapi/internal/operation/typespelling.go index 8502a176e..65c1d7b26 100644 --- a/compilers/openapi/internal/operation/typespelling.go +++ b/compilers/openapi/internal/operation/typespelling.go @@ -27,8 +27,8 @@ import ( // typeSpelling is how a parameter or header stated its type: the schema node, // the context and pointer it is declared at, the media type serializing it, // empty for the `schema` spelling, the examples a content-style entry -// declares, and what the elected entry writes beyond its type and the spelling -// the election passed over, for the carrier to merge onto its Unmodeled. A +// declares, and what the chosen entry writes beyond its type and the spelling +// the choice passed over, for the carrier to merge onto its Unmodeled. A // content entry written as a $ref declares its schema where the chain ends // (declaredMedia), in that document's context. carries is the scopes the // carrier keeps what the spelling's objects write under, nearest first @@ -47,7 +47,7 @@ type typeSpelling struct { // writes under, the last of carries. func (s typeSpelling) schemaScope() string { return s.carries[len(s.carries)-1] } -// electTypeSpelling picks the spelling a parameter or header states its type +// chooseTypeSpelling picks the spelling a parameter or header states its type // with, keeping the other verbatim where the document writes both. // // OpenAPI forbids both `schema` and `content`, and neither position can lower @@ -57,9 +57,9 @@ func (s typeSpelling) schemaScope() string { return s.carries[len(s.carries)-1] // `content` wins: its entry carries a schema and the media type serializing it, // both with IR homes here (HTTPParamBinding.ContentType, // Property.Encoding.MediaType), where `schema` would push the media type into -// Unmodeled. The specification gives no precedence. The election is +// Unmodeled. The specification gives no precedence. The choice is // unconditional, even where the entry names no schema (GitHub #320). -func electTypeSpelling(serviceContext service.Ctx, loweringState operationLoweringState, js *oas3.JSONSchema[oas3.Referenceable], +func chooseTypeSpelling(serviceContext service.Ctx, loweringState operationLoweringState, js *oas3.JSONSchema[oas3.Referenceable], content *sequencedmap.Map[string, *soa.MediaType], root *yaml.Node, at jsontext.Pointer, carrier, home string, ) (typeSpelling, []ir.Diagnostic) { @@ -72,73 +72,73 @@ func electTypeSpelling(serviceContext service.Ctx, loweringState operationLoweri mt, media, ok := chooseSingleContentEntry(content) if ok { mediaPtr := at + ids.Ptr("content", mt) - elected, electedDiags := contentSpelling(serviceContext, media, mt, mediaPtr, carrier, home) - diags = append(diags, electedDiags...) + chosen, chosenDiags := contentSpelling(serviceContext, media, mt, mediaPtr, carrier, home) + diags = append(diags, chosenDiags...) diags = append(diags, loweringState.kept.once(serviceContext.IDs().Coordinate(at), func() (ir.Unmodeled, []ir.Diagnostic) { return passedOverEntries(serviceContext, nodeview.Pairs(nodeview.Child(root, "content")), mt, at) })...) - diags = append(diags, passedOverSpelling(serviceContext, &elected.unmodeled, root, "schema", "content", at)...) - return elected, diags + diags = append(diags, passedOverSpelling(serviceContext, &chosen.unmodeled, root, "schema", "content", at)...) + return chosen, diags } - elected := typeSpelling{ctx: serviceContext, js: js, pointer: at + ids.Ptr("schema"), carries: promotion.CarrierScopes("")} + chosen := typeSpelling{ctx: serviceContext, js: js, pointer: at + ids.Ptr("schema"), carries: promotion.CarrierScopes("")} if js == nil { - // Neither spelling states a type — a header carrying only a description, - // or a `content` map naming no usable entry — so there is no winner, and - // nothing was passed over for one. - return elected, diags + // Neither spelling states a type — a header carrying only a + // description, or a `content` map naming no usable entry — so there is + // no choice, and nothing was passed over for one. + return chosen, diags } - diags = append(diags, passedOverSpelling(serviceContext, &elected.unmodeled, root, "content", "schema", at)...) - return elected, diags + diags = append(diags, passedOverSpelling(serviceContext, &chosen.unmodeled, root, "content", "schema", at)...) + return chosen, diags } -// contentSpelling is the typeSpelling of media, the elected entry of a +// contentSpelling is the typeSpelling of media, the chosen entry of a // parameter's or header's content map, written under mt at mediaPtr: its -// schema, examples and residue as it declares them (declaredMedia). One +// schema, examples and kept keywords as it declares them (declaredMedia). One // written as a $ref that resolves to nothing states no type, as one naming no // schema does, but still names its media type. func contentSpelling(serviceContext service.Ctx, media *soa.MediaType, mt string, mediaPtr jsontext.Pointer, carrier, home string, ) (typeSpelling, []ir.Diagnostic) { - elected := typeSpelling{ctx: serviceContext, pointer: mediaPtr + ids.Ptr("schema"), mediaType: mt, + chosen := typeSpelling{ctx: serviceContext, pointer: mediaPtr + ids.Ptr("schema"), mediaType: mt, carries: promotion.CarrierScopes(mt)} mediaDecl, found := declaredMedia(serviceContext, media, mediaPtr) if !found { - return elected, nil + return chosen, nil } scope := ids.Scope("content", mt) - examples, residue, diags := contentEntryFields(mediaDecl, scope, carrier, home) + examples, mediaUnmodeled, diags := contentEntryFields(mediaDecl, scope, carrier, home) if mediaDecl.use != nil { // The carrier has no docs for what the entry's chain writes beside its // $ref, so its summary and description are kept with its other keys. beside, besideDiags := service.Beside[soa.MediaType](mediaDecl.entryCtx, mediaDecl.use, mediaDecl.entryPtr, false) - residue = annotation.MergeUnmodeled(residue, annotation.Under(scope, beside)) + mediaUnmodeled = annotation.MergeUnmodeled(mediaUnmodeled, annotation.Under(scope, beside)) diags = append(diags, besideDiags...) } - elected.ctx, elected.js, elected.pointer = mediaDecl.ctx, mediaDecl.media.GetSchema(), mediaDecl.pointer+ids.Ptr("schema") - elected.unmodeled, elected.examples = residue, examples - return elected, diags + chosen.ctx, chosen.js, chosen.pointer = mediaDecl.ctx, mediaDecl.media.GetSchema(), mediaDecl.pointer+ids.Ptr("schema") + chosen.unmodeled, chosen.examples = mediaUnmodeled, examples + return chosen, diags } -// passedOverSpelling keeps verbatim the spelling the election passed over and -// reports it once, naming both. A document that wrote only the elected one +// passedOverSpelling keeps verbatim the spelling the choice passed over and +// reports it once, naming both. A document that wrote only the chosen one // records nothing and says nothing. // // The reason is ReasonDegradedLowering, as schema.recordSkippedFamilies uses for // the keyword families its own dispatch passes over. The severity is warning, // not the info announcing a conjunction JSON Schema allows, because OpenAPI // forbids this one; it matches passedOverEntries'. It is not an error: the -// document lowers as well as an election can make it. -func passedOverSpelling(serviceContext service.Ctx, unmodeled *ir.Unmodeled, root *yaml.Node, passed, elected string, at jsontext.Pointer) []ir.Diagnostic { +// document lowers as well as an choice can make it. +func passedOverSpelling(serviceContext service.Ctx, unmodeled *ir.Unmodeled, root *yaml.Node, passed, chosen string, at jsontext.Pointer) []ir.Diagnostic { pointer := at + ids.Ptr(passed) - kept, diags := annotation.PreserveNodeInto(unmodeled, "openapi:"+passed, + kept, diags := annotation.KeepNodeInto(unmodeled, "openapi:"+passed, nodeview.Child(root, passed), ir.ReasonDegradedLowering, serviceContext.Place().At(pointer)) if !kept { return diags } - schema.RecordReached(serviceContext.Ctx, pointer) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, pointer)...) return append(diags, serviceContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, pointer, "a parameter or header declares either schema or content, not both; this one declares "+ - "both, so it lowered as its %s, with %s kept verbatim under Unmodeled", elected, passed)) + "both, so it lowered as its %s, with %s kept verbatim under Unmodeled", chosen, passed)) } // chooseSingleContentEntry returns the one entry a content-style header or @@ -146,44 +146,44 @@ func passedOverSpelling(serviceContext service.Ctx, unmodeled *ir.Unmodeled, roo // // OpenAPI requires exactly one entry at both positions, and ir.Property and // ir.Parameter each hold a single type, so a document declaring more needs an -// election. It takes the lowest key as written, which no declaration order can +// choice. It takes the lowest key as written, which no declaration order can // change: the specification ranks none, and the entry a run lowers must not // follow the order of a map. func chooseSingleContentEntry(content *sequencedmap.Map[string, *soa.MediaType]) (string, *soa.MediaType, bool) { - var elected string + var chosenMediaType string var chosen *soa.MediaType for mt, media := range content.All() { - if media != nil && (chosen == nil || mt < elected) { - elected, chosen = mt, media + if media != nil && (chosen == nil || mt < chosenMediaType) { + chosenMediaType, chosen = mt, media } } - return elected, chosen, chosen != nil + return chosenMediaType, chosen, chosen != nil } // passedOverEntries returns each entry of written, a content map's pairs, but -// elected, kept verbatim under openapi:, and reports them once at +// chosen, kept verbatim under openapi:, and reports them once at // the map, sorted, so the report follows no declaration order. // // They are the Document's rather than the carrier's (keptOnce): a carrier // a $ref reaches lowers once per reference, and an entry belongs to the -// declaration, which no node stands for. So what they cost is what the source +// declaration, which no node names. So what they cost is what the source // wrote, and none need dropping. // // The reason and severity are passedOverSpelling's. An entry interns no node, and // --explain does not read Unmodeled (GitHub #693), so only the warning names it. -func passedOverEntries(serviceContext service.Ctx, written []nodeview.Pair, elected string, at jsontext.Pointer) (ir.Unmodeled, []ir.Diagnostic) { +func passedOverEntries(serviceContext service.Ctx, written []nodeview.Pair, chosen string, at jsontext.Pointer) (ir.Unmodeled, []ir.Diagnostic) { passed := slices.DeleteFunc(slices.SortedFunc(slices.Values(written), byKey), - func(entry nodeview.Pair) bool { return entry.Key == elected }) + func(entry nodeview.Pair) bool { return entry.Key == chosen }) var entries ir.Unmodeled var diags []ir.Diagnostic var kept []string for _, entry := range passed { pointer := at + ids.Ptr("content", entry.Key) - ok, keptDiags := annotation.PreserveNodeInto(&entries, "openapi:"+serviceContext.IDs().Coordinate(pointer), + ok, keptDiags := annotation.KeepNodeInto(&entries, "openapi:"+serviceContext.IDs().Coordinate(pointer), entry.Val, ir.ReasonDegradedLowering, serviceContext.Place().At(pointer)) diags = append(diags, keptDiags...) if ok { - schema.RecordReached(serviceContext.Ctx, pointer) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, pointer)...) kept = append(kept, entry.Key) } } @@ -192,7 +192,7 @@ func passedOverEntries(serviceContext service.Ctx, written []nodeview.Pair, elec } return entries, append(diags, serviceContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, at+ids.Ptr("content"), "a content-style header or parameter must declare exactly one media type; "+ - "%q is lowered and %s kept verbatim under the document's Unmodeled", elected, namedEntries(kept))) + "%q is lowered and %s kept verbatim under the document's Unmodeled", chosen, namedEntries(kept))) } // namedEntries lists keys for one warning: each quoted, so a key cannot break the @@ -214,8 +214,8 @@ func namedEntries(keys []string) string { // byKey orders two pairs of one mapping, whose keys differ. func byKey(a, b nodeview.Pair) int { return strings.Compare(a.Key, b.Key) } -// contentEntryFields returns everything the Media Type Object mediaDeclValue -// declares at a parameter's or header's elected `content` position beyond the +// contentEntryFields returns everything the Media Type Object mediaDecl +// declares at a parameter's or header's chosen `content` position beyond the // one type that position lowers: its example/examples, its x-* and undeclared // keys, and the fields contentOnlyFields names, none of which may vanish // without a diagnostic (GitHub #611). @@ -223,8 +223,8 @@ func byKey(a, b nodeview.Pair) int { return strings.Compare(a.Key, b.Key) } // scope is the content entry's own path, so several media types and the // enclosing object cannot collide on one key. carrier and home name the // position in each content-only field's info, with ReasonNoIRHome. -func contentEntryFields(mediaDeclValue mediaDecl, scope, carrier, home string) ([]ir.Example, ir.Unmodeled, []ir.Diagnostic) { - serviceContext, media, mediaPtr := mediaDeclValue.ctx, mediaDeclValue.media, mediaDeclValue.pointer +func contentEntryFields(mediaDecl mediaDecl, scope, carrier, home string) ([]ir.Example, ir.Unmodeled, []ir.Diagnostic) { + serviceContext, media, mediaPtr := mediaDecl.ctx, mediaDecl.media, mediaDecl.pointer examples, diags := exampleList(serviceContext, media.GetExample(), media.GetExamples(), mediaPtr) var unmodeled ir.Unmodeled ext, extDiags := annotation.ExtensionsUnder(media.GetExtensions(), serviceContext.Place(), mediaPtr, scope) @@ -232,13 +232,13 @@ func contentEntryFields(mediaDeclValue mediaDecl, scope, carrier, home string) ( diags = append(diags, extDiags...) for _, field := range contentOnlyFields(media) { at := mediaPtr + ids.Ptr(field.keyword) - kept, keptDiags := annotation.PreserveNodeInto(&unmodeled, + kept, keptDiags := annotation.KeepNodeInto(&unmodeled, annotation.EntryKey(scope, field.keyword), field.node, ir.ReasonNoIRHome, serviceContext.Place().At(at)) diags = append(diags, keptDiags...) if !kept { continue } - schema.RecordReached(serviceContext.Ctx, at) + diags = append(diags, schema.KeptVerbatimAt(serviceContext.Ctx, at)...) diags = append(diags, serviceContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, "%s content media type %s has no %s home; kept verbatim under Unmodeled", carrier, field.keyword, home)) diff --git a/compilers/openapi/internal/operation/typespelling_internal_test.go b/compilers/openapi/internal/operation/typespelling_internal_test.go index 2fa409256..f231293d2 100644 --- a/compilers/openapi/internal/operation/typespelling_internal_test.go +++ b/compilers/openapi/internal/operation/typespelling_internal_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" ) -// TestChooseSingleContentEntry_SkipsANilEntry holds the election to an entry +// TestChooseSingleContentEntry_SkipsANilEntry holds the choice to an entry // that can lower: a nil one, which no parse yields, sorts first and is not // taken, in either order. func TestChooseSingleContentEntry_SkipsANilEntry(t *testing.T) { @@ -29,9 +29,9 @@ func TestChooseSingleContentEntry_SkipsANilEntry(t *testing.T) { } } -// TestChooseSingleContentEntry_NoEntryElectsNothing is the other way an -// election ends: no map, or one that holds nothing that can lower. -func TestChooseSingleContentEntry_NoEntryElectsNothing(t *testing.T) { +// TestChooseSingleContentEntry_NoEntryChoosesNothing is the other way an +// choice ends: no map, or one that holds nothing that can lower. +func TestChooseSingleContentEntry_NoEntryChoosesNothing(t *testing.T) { t.Parallel() for name, content := range map[string]*sequencedmap.Map[string, *soa.MediaType]{ "no map": nil, diff --git a/compilers/openapi/internal/operation/typespelling_test.go b/compilers/openapi/internal/operation/typespelling_test.go index 8abe973e4..e1a11e373 100644 --- a/compilers/openapi/internal/operation/typespelling_test.go +++ b/compilers/openapi/internal/operation/typespelling_test.go @@ -101,15 +101,15 @@ components: const ( paramMap = "/paths/~1x/get/parameters/0/content" headerMap = "/paths/~1x/get/responses/200/headers/X-H/content" - xmlValue = `{"schema":{"type":"boolean"}}` - plainValue = `{"example":"hi","schema":{"$ref":"#/components/schemas/Str"},"x-kept":1}` + xml = `{"schema":{"type":"boolean"}}` + plain = `{"example":"hi","schema":{"$ref":"#/components/schemas/Str"},"x-kept":1}` wantWarning = `"application/json" is lowered and "application/xml", "text/plain" kept verbatim under the document's Unmodeled` ) wantValues := map[string]string{ - "openapi:" + paramMap + "/application~1xml": xmlValue, - "openapi:" + paramMap + "/text~1plain": plainValue, - "openapi:" + headerMap + "/application~1xml": xmlValue, - "openapi:" + headerMap + "/text~1plain": plainValue, + "openapi:" + paramMap + "/application~1xml": xml, + "openapi:" + paramMap + "/text~1plain": plain, + "openapi:" + headerMap + "/application~1xml": xml, + "openapi:" + headerMap + "/text~1plain": plain, } for _, entries := range [][]string{ @@ -118,10 +118,10 @@ components: {xmlEntry, numberEntry, plainEntry}, {xmlEntry, plainEntry, numberEntry}, } { doc, diags := parseFull(t, spec(entries...)) - for name, elected := range map[string]func(*testing.T, *ir.Document) (ir.TypeID, string, ir.Unmodeled){ + for name, chosen := range map[string]func(*testing.T, *ir.Document) (ir.TypeID, string, ir.Unmodeled){ "parameter": electedParam, "header": electedHeader, } { - target, mediaType, unmodeled := elected(t, doc) + target, mediaType, unmodeled := chosen(t, doc) assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Num"), target, "%s, %q", name, entries) assert.Equal(t, "application/json", mediaType, "%s, %q", name, entries) assert.Empty(t, unmodeled, "%s, %q: a passed-over entry is the document's", name, entries) @@ -139,8 +139,8 @@ components: } } -// TestPassedOverEntries_KeepsEntriesAMergeKeyWrote holds the keeper to the map -// the election read: a `content` written through `<<` is the parser's, and a +// TestPassedOverEntries_KeepsEntriesAMergeKeyWrote holds the keep to the map +// the choice read: a `content` written through `<<` is the parser's, and a // read of the raw mapping that missed it would keep nothing. func TestPassedOverEntries_KeepsEntriesAMergeKeyWrote(t *testing.T) { t.Parallel() @@ -164,12 +164,10 @@ paths: assert.Contains(t, doc.Unmodeled, "openapi:/paths/~1x/get/parameters/0/content/text~1plain") } -// TestPassedOverEntries_NamesOnlyWhatItKept holds the warning to what reached -// the IR: an entry whose node cannot be kept is reported as unpreservable, and -// naming it as kept as well would announce a preservation that did not happen. -func TestPassedOverEntries_NamesOnlyWhatItKept(t *testing.T) { - t.Parallel() - doc, diags := parseFull(t, openapitest.PathsSpec(` /x: +// passedOverSpec is a parameter whose content writes three entries, the second +// being xml. +func passedOverSpec(xml string) string { + return openapitest.PathsSpec(` /x: get: operationId: getX parameters: @@ -177,10 +175,21 @@ func TestPassedOverEntries_NamesOnlyWhatItKept(t *testing.T) { in: query content: application/json: {schema: {type: integer}} - application/xml: {x-nan: .nan} + application/xml: ` + xml + ` text/plain: {schema: {type: string}} responses: {"200": {description: ok}} -`)) +`) +} + +// TestPassedOverEntries_NamesOnlyWhatItKept holds the warning to what reached +// the IR: an entry whose node cannot be kept is reported as unpreservable, and +// naming it as kept as well would announce a preservation that did not happen. +// An extension no JSON holds is left out wherever it is kept, so an entry +// writing one is kept and named as its twin without it is, the extension +// alone dropped with its own warning. +func TestPassedOverEntries_NamesOnlyWhatItKept(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, passedOverSpec("{example: .nan}")) _, mediaType, _ := electedParam(t, doc) assert.Equal(t, "application/json", mediaType) assert.Equal(t, []string{"openapi:/paths/~1x/get/parameters/0/content/text~1plain"}, @@ -189,6 +198,15 @@ func TestPassedOverEntries_NamesOnlyWhatItKept(t *testing.T) { assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, "/paths/~1x/get/parameters/0/content"), `"application/json" is lowered and "text/plain" kept verbatim under the document's Unmodeled`) + + extension, extensionDiags := parseFull(t, passedOverSpec("{x-nan: .nan}")) + twin, twinDiags := parseFull(t, passedOverSpec("{}")) + assert.Equal(t, twin.Unmodeled, extension.Unmodeled, "the entry is kept as its twin") + assert.Contains(t, openapitest.DiagMessageAt(t, extensionDiags, diag.DegradedConstruct, ir.SeverityWarning, + "/paths/~1x/get/parameters/0/content/application~1xml"), `extension "x-nan" could not be serialized`) + assert.Len(t, extensionDiags, len(twinDiags)+1, "and reported as its twin, but for the extension's warning") + _, refused := openapitest.FirstDiag(extensionDiags, diag.UnpreservableConstruct) + assert.False(t, refused, "nothing is refused") } // TestPassedOverEntries_QuotesWhatItNames holds the warning to one line that names @@ -216,7 +234,7 @@ func TestPassedOverEntries_QuotesWhatItNames(t *testing.T) { // TestPassedOverEntries_KeepsEveryEntryAndNamesTheLowest holds a map at the bound // on the names one warning lists and one past it, declared in both orders: the // bound shortens the line and drops no entry, what it leaves out must not follow -// the document, and the count must exclude the elected entry, which is no name. +// the document, and the count must exclude the chosen entry, which is no name. func TestPassedOverEntries_KeepsEveryEntryAndNamesTheLowest(t *testing.T) { t.Parallel() const at = "/paths/~1x/get/parameters/0/content" @@ -257,12 +275,12 @@ func TestPassedOverEntries_KeepsEveryEntryAndNamesTheLowest(t *testing.T) { } } -// TestPassedOverEntries_KeepsOneCopyPerDeclaration lowers a parameter and a header -// through several references. What they pass over belongs to the declaration, so -// the Document holds it once and no reference copies it, and the walk reads it -// once, its warning standing once in the walk's own report rather than left to -// compile.Diags to drop: the work grows with the source, not with its product with -// the references (GitHub #1240). +// TestPassedOverEntries_KeepsOneCopyPerDeclaration lowers a parameter and a +// header through several references. What they pass over belongs to the +// declaration, so the Document holds it once and no reference copies it, and +// the walk reads it once, its warning appearing once in the walk's own report +// rather than left to compile.Diags to drop: the work grows with the source, +// not with its product with the references (GitHub #1240). func TestPassedOverEntries_KeepsOneCopyPerDeclaration(t *testing.T) { t.Parallel() const ( @@ -317,7 +335,7 @@ func TestPassedOverEntries_KeepsOneCopyPerDeclaration(t *testing.T) { } // TestPassedOverEntries_KeepsOneAtEveryPosition puts a content map of two -// entries at each position the service walk reaches the election from: a path +// entries at each position the service walk reaches the choice from: a path // item's, an operation's, a callback's and a webhook's parameter, and a success, // error-range and default response's, a form part's and a 3.2 sequential item's // header. Each route hands the walk down itself, so one handing its lowerings a @@ -398,10 +416,10 @@ webhooks: assert.Equal(t, contentMaps, openapitest.PointersOf(reported, diag.DegradedConstruct), "%+v", reported) } -// TestChooseSingleContentEntry_OneEntryIsSilent is the control: the legal +// TestChooseSingleContentEntry_OneEntryReportsNothing is the control: the legal // one-entry spelling must not warn, or every content-style header and parameter // would. -func TestChooseSingleContentEntry_OneEntryIsSilent(t *testing.T) { +func TestChooseSingleContentEntry_OneEntryReportsNothing(t *testing.T) { t.Parallel() _, diags := parseFull(t, openapitest.PathsSpec(" /x:\n get:\n responses:\n"+ " \"200\":\n description: ok\n headers:\n"+ @@ -411,10 +429,10 @@ func TestChooseSingleContentEntry_OneEntryIsSilent(t *testing.T) { "one media type is the legal spelling: %+v", diags) } -// TestElectTypeSpelling_NeitherSpelling covers a header that declares no type at -// all. It is legal — a header may carry only a description — and must lower to -// the top type without reporting a loss, since nothing was written to lose. -func TestElectTypeSpelling_NeitherSpelling(t *testing.T) { +// TestChooseTypeSpelling_NeitherSpelling covers a header that declares no type +// at all. It is legal — a header may carry only a description — and must lower +// to the top type without reporting a loss, since nothing was written to lose. +func TestChooseTypeSpelling_NeitherSpelling(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.PathsSpec(" /x:\n get:\n operationId: untypedHeader\n responses:\n"+ " \"200\":\n description: ok\n headers:\n"+ @@ -429,20 +447,20 @@ func TestElectTypeSpelling_NeitherSpelling(t *testing.T) { assert.Equal(t, "untyped", headers[0].Docs.Description) } -// TestElectTypeSpelling_CoDeclaredSpellingsElectContent covers the invalid +// TestChooseTypeSpelling_CoDeclaredSpellingsChooseContent covers the invalid // document OpenAPI forbids at the two positions one rule governs: a parameter, // and a header which follows the parameter rules, declaring `schema` and // `content` together. The table reports the rule broken, and each position -// holds one type, so one spelling is elected and the other kept verbatim beside +// holds one type, so one spelling is chosen and the other kept verbatim beside // it — where both positions used to take one in silence, and in opposite // directions (GitHub #320). -func TestElectTypeSpelling_CoDeclaredSpellingsElectContent(t *testing.T) { +func TestChooseTypeSpelling_CoDeclaredSpellingsChooseContent(t *testing.T) { t.Parallel() tests := []struct { - name string - spec string - at string - elected func(*testing.T, *ir.Document) (ir.TypeID, string, ir.Unmodeled) + name string + spec string + at string + chosen func(*testing.T, *ir.Document) (ir.TypeID, string, ir.Unmodeled) }{ { name: "operation parameter", @@ -457,8 +475,8 @@ func TestElectTypeSpelling_CoDeclaredSpellingsElectContent(t *testing.T) { application/json: {schema: {type: string}} responses: {"200": {description: ok}} `), - at: "/paths/~1x/get/parameters/0", - elected: electedParam, + at: "/paths/~1x/get/parameters/0", + chosen: electedParam, }, { name: "response header", @@ -474,8 +492,8 @@ func TestElectTypeSpelling_CoDeclaredSpellingsElectContent(t *testing.T) { content: application/json: {schema: {type: string}} `), - at: "/paths/~1x/get/responses/200/headers/X-H", - elected: electedHeader, + at: "/paths/~1x/get/responses/200/headers/X-H", + chosen: electedHeader, }, } for _, tc := range tests { @@ -484,7 +502,7 @@ func TestElectTypeSpelling_CoDeclaredSpellingsElectContent(t *testing.T) { doc, diags := parseFull(t, tc.spec) assert.Equal(t, []string{"openapi/validation/validation-mutually-exclusive-fields at " + tc.at}, errorFindings(diags)) - target, mediaType, unmodeled := tc.elected(t, doc) + target, mediaType, unmodeled := tc.chosen(t, doc) assert.Equal(t, ir.TypeID("type/primitive/string"), target, "the content entry's schema is the type, not the schema written beside it") @@ -499,17 +517,17 @@ func TestElectTypeSpelling_CoDeclaredSpellingsElectContent(t *testing.T) { "located at the keyword itself, not at the object that carried it") message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, tc.at+"/schema") - assert.Contains(t, message, "lowered as its content", "the message names the elected spelling") + assert.Contains(t, message, "lowered as its content", "the message names the chosen spelling") assert.Contains(t, message, "with schema kept verbatim", "and the one it passed over") }) } } -// TestElectTypeSpelling_SoleSpellingReportsNothing is the control. A position -// that writes one spelling has no election to make, so it must keep nothing and +// TestChooseTypeSpelling_SoleSpellingReportsNothing is the control. A position +// that writes one spelling has no choice to make, so it must keep nothing and // say nothing — otherwise every well-formed parameter and header in every -// document would carry a residue entry and a warning. -func TestElectTypeSpelling_SoleSpellingReportsNothing(t *testing.T) { +// document would carry an Unmodeled entry and a warning. +func TestChooseTypeSpelling_SoleSpellingReportsNothing(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.PathsSpec(` /x: get: @@ -533,7 +551,7 @@ func TestElectTypeSpelling_SoleSpellingReportsNothing(t *testing.T) { `)) openapitest.RequireNoErrorDiags(t, diags) assert.Equal(t, 0, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning), - "one spelling is the legal form, so there is no election to announce: %+v", diags) + "one spelling is the legal form, so there is no choice to announce: %+v", diags) operation := openapitest.FindOperation(t, doc, "getX") require.Len(t, operation.Params, 2) @@ -547,16 +565,16 @@ func TestElectTypeSpelling_SoleSpellingReportsNothing(t *testing.T) { } } -// TestElectTypeSpelling_ElectedContentWithoutASchemaStillWins pins the edge the -// election's rationale is stated against: `content` is elected because it is the -// more expressive spelling, and the rule holds even at the one shape where it is -// not — an entry naming a media type but no schema. +// TestChooseTypeSpelling_ChosenContentWithoutASchemaStillWins pins the edge the +// choice's rationale is stated against: `content` is chosen because it is the +// more expressive spelling, and the rule holds even at the one shape where it +// is not — an entry naming a media type but no schema. // // The type is `any` and the declared integer sits beside it, rather than the -// other way round. Electing per entry would recover this case and lose what the -// election is for: two documents alike but for whether an entry names a schema -// would then elect different spellings, which is the disagreement being fixed. -func TestElectTypeSpelling_ElectedContentWithoutASchemaStillWins(t *testing.T) { +// other way round. Choosing per entry would recover this case and lose what the +// choice is for: two documents alike but for whether an entry names a schema +// would then choose different spellings, which is the disagreement being fixed. +func TestChooseTypeSpelling_ChosenContentWithoutASchemaStillWins(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.PathsSpec(` /x: get: @@ -572,7 +590,7 @@ func TestElectTypeSpelling_ElectedContentWithoutASchemaStillWins(t *testing.T) { operation := openapitest.FindOperation(t, doc, "getX") require.Len(t, operation.Params, 1) assert.Equal(t, ir.TypeID("type/primitive/any"), operation.Params[0].Type.Target, - "the elected content states no schema, so the position states no type") + "the chosen content states no schema, so the position states no type") require.Len(t, operation.Bindings.HTTP, 1) require.Len(t, operation.Bindings.HTTP[0].ParamBindings, 1) assert.Equal(t, "application/json", operation.Bindings.HTTP[0].ParamBindings[0].ContentType, @@ -586,18 +604,19 @@ func TestElectTypeSpelling_ElectedContentWithoutASchemaStillWins(t *testing.T) { assert.Equal(t, jsontext.Pointer(at), entry.Provenance.Pointer) message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, at) - assert.Contains(t, message, "lowered as its content", "the message names the elected spelling") + assert.Contains(t, message, "lowered as its content", "the message names the chosen spelling") } -// TestElectTypeSpelling_UnusableContentElectsSchemaAndKeepsIt covers the other -// direction. A `content` map yielding no entry states no type, so the schema is -// elected instead — but the document declared both spellings either way, and the -// one passed over is kept and named exactly as it is when content wins. +// TestChooseTypeSpelling_UnusableContentChoosesSchemaAndKeepsIt covers the +// other direction. A `content` map yielding no entry states no type, so the +// schema is chosen instead — but the document declared both spellings either +// way, and the one passed over is kept and named exactly as it is when content +// wins. // // The library's validator reports the empty map beside this, which is the same // invalidity seen from its angle rather than a second finding: Compile lowers the // whole document rather than stopping at it, so the assertions below are reached. -func TestElectTypeSpelling_UnusableContentElectsSchemaAndKeepsIt(t *testing.T) { +func TestChooseTypeSpelling_UnusableContentChoosesSchemaAndKeepsIt(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.PathsSpec(` /x: get: @@ -626,7 +645,7 @@ func TestElectTypeSpelling_UnusableContentElectsSchemaAndKeepsIt(t *testing.T) { assert.Equal(t, jsontext.Pointer(at), entry.Provenance.Pointer) message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, at) - assert.Contains(t, message, "lowered as its schema", "the message names the elected spelling") + assert.Contains(t, message, "lowered as its schema", "the message names the chosen spelling") assert.Contains(t, message, "with content kept verbatim", "and the one it passed over") } @@ -657,7 +676,7 @@ func TestParamContent_MergedFieldIsKept(t *testing.T) { } // TestParamContent_MediaTypeFieldsReachTheParameter pins GitHub #611 at the -// parameter position: electing a `content` entry used to read only the media +// parameter position: choosing a `content` entry used to read only the media // type's schema, so the object's example/examples, its x-*, its undeclared keys // and the parser-modelled fields no ir.Parameter holds vanished with no field, // no Unmodeled entry and no diagnostic. @@ -742,7 +761,7 @@ paths: } // TestParamAndHeaderSchema_NeverRecordContentFields is the passed-over case: the -// schema spelling elects no media type, so nothing content-scoped can appear on +// schema spelling chooses no media type, so nothing content-scoped can appear on // the carrier and no info is reported. func TestParamAndHeaderSchema_NeverRecordContentFields(t *testing.T) { t.Parallel() @@ -762,7 +781,7 @@ func TestParamAndHeaderSchema_NeverRecordContentFields(t *testing.T) { operation := openapitest.FirstOperation(t, svc) require.Len(t, operation.Params, 1) for key := range operation.Params[0].Unmodeled { - assert.NotContains(t, key, "openapi:content/", "the schema spelling elects no media type") + assert.NotContains(t, key, "openapi:content/", "the schema spelling chooses no media type") } assert.Empty(t, operation.Params[0].Examples) require.Len(t, operation.Responses[0].Headers, 1) @@ -774,7 +793,7 @@ func TestParamAndHeaderSchema_NeverRecordContentFields(t *testing.T) { "nothing was passed over, so nothing is announced") } -// electedParam reads what the election left on the operation's single +// electedParam reads what the choice left on the operation's single // parameter: its type, the media type on its binding, and its Unmodeled. func electedParam(t *testing.T, doc *ir.Document) (ir.TypeID, string, ir.Unmodeled) { t.Helper() diff --git a/compilers/openapi/internal/operation/usesites_beside_test.go b/compilers/openapi/internal/operation/usesites_beside_test.go index 7e089de5e..6253ab3af 100644 --- a/compilers/openapi/internal/operation/usesites_beside_test.go +++ b/compilers/openapi/internal/operation/usesites_beside_test.go @@ -37,10 +37,10 @@ func TestContentDocs_ChainAndDeclarationKeepApart(t *testing.T) { func TestContentDocs_AKeyIsReadWhole(t *testing.T) { t.Parallel() doc, _ := parseFull(t, specFrom(t, specsDir, "content_key_read_whole")) - a := operationTree(t, doc, "a") + operationTree := operationTree(t, doc, "a") const mt = `openapi:content/application~1json; profile="a~1b c"/` - q := namedItem(t, valueAtPath(a, "params"), "q") + q := namedItem(t, valueAtPath(operationTree, "params"), "q") values := entries(t, valueAtPath(q, "unmodeled")) assert.Len(t, values, 6) for key, want := range map[string]string{ @@ -54,7 +54,7 @@ func TestContentDocs_AKeyIsReadWhole(t *testing.T) { assert.Contains(t, values[key], want, key) } - p := namedItem(t, valueAtPath(a, "params"), "p") + p := namedItem(t, valueAtPath(operationTree, "params"), "p") pg := entries(t, valueAtPath(p, "unmodeled")) assert.Len(t, pg, 2) assert.Contains(t, pg["openapi:schema~1x-a"], `"FROM_OBJECT_KEY"`) diff --git a/compilers/openapi/internal/operation/usesites_bodies_test.go b/compilers/openapi/internal/operation/usesites_bodies_test.go index a8d7b7809..937ca8c4a 100644 --- a/compilers/openapi/internal/operation/usesites_bodies_test.go +++ b/compilers/openapi/internal/operation/usesites_bodies_test.go @@ -76,9 +76,10 @@ func TestPartKeys_KeysACatchAll(t *testing.T) { toJSON(t, catchAll(mixed)), "each variant of the union is keyed, not the union") } -// TestPartless_FormBodyWithNoObject holds a form body whose schema stands for -// no model and no map to one warning at its schema: an array of strings. An -// untyped body, a file body and a body the compiler can name parts of draw none. +// TestPartless_FormBodyWithNoObject holds a form body whose schema names no +// model and no map to one warning at its schema: an array of strings. An +// untyped body, a file body and a body the compiler can name parts of draw +// none. func TestPartless_FormBodyWithNoObject(t *testing.T) { t.Parallel() doc, diags := parseFull(t, specFrom(t, specsDir, "media_key_and_form_bodies")) diff --git a/compilers/openapi/internal/operation/usesites_params_test.go b/compilers/openapi/internal/operation/usesites_params_test.go index 5aa054762..7477140ea 100644 --- a/compilers/openapi/internal/operation/usesites_params_test.go +++ b/compilers/openapi/internal/operation/usesites_params_test.go @@ -41,16 +41,16 @@ components: ` // TestParameter_SchemaEntriesAreScoped holds what a parameter's schema writes to -// openapi:schema/, what an elected content entry's schema writes to +// openapi:schema/, what an chosen content entry's schema writes to // openapi:content//schema/, and the parameter's own keys to no scope, with // the redaction either states filling the parameter and marking it. func TestParameter_SchemaEntriesAreScoped(t *testing.T) { t.Parallel() doc, diags := parseFull(t, specFrom(t, conformanceSpecsDir, "carried-keys")) assert.Equal(t, []string{"openapi/unpromoted-extension info /tags/1/x-stability"}, findings(diags)) - a := operationTree(t, doc, "a") + operationTree := operationTree(t, doc, "a") - p := namedItem(t, valueAtPath(a, "params"), "p") + p := namedItem(t, valueAtPath(operationTree, "params"), "p") assert.Empty(t, cmp.Diff(map[string]string{ "openapi:x-a": `vendor_extension "FROM_PARAMETER" /paths/~1a/get/parameters/0/x-a`, "openapi:schema/x-a": `vendor_extension "FROM_SCHEMA" /paths/~1a/get/parameters/0/schema/x-a`, @@ -60,7 +60,7 @@ func TestParameter_SchemaEntriesAreScoped(t *testing.T) { assert.Equal(t, "extension-promotion", valueAtPath(p, "provenance", "inferred")) const media = "/paths/~1a/get/parameters/1/content/application~1json" - c := namedItem(t, valueAtPath(a, "params"), "c") + c := namedItem(t, valueAtPath(operationTree, "params"), "c") assert.Empty(t, cmp.Diff(map[string]string{ "openapi:content/application~1json/x-a": `vendor_extension "FROM_MEDIA" ` + media + `/x-a`, "openapi:content/application~1json/x-sensitive": `vendor_extension true ` + media + `/x-sensitive`, @@ -70,7 +70,7 @@ func TestParameter_SchemaEntriesAreScoped(t *testing.T) { assert.Equal(t, "extension-promotion", valueAtPath(c, "provenance", "inferred")) const header = "/paths/~1a/get/responses/200/headers/X-H" - h := namedItem(t, valueAtPath(a, "responses", "0", "headers"), "X-H") + h := namedItem(t, valueAtPath(operationTree, "responses", "0", "headers"), "X-H") assert.Empty(t, cmp.Diff(map[string]string{ "openapi:x-a": `vendor_extension "FROM_HEADER" ` + header + `/x-a`, "openapi:content/text~1plain/x-sensitive": `vendor_extension true ` + header + @@ -91,8 +91,7 @@ func TestParameter_SchemaAndObjectSpellOneKey(t *testing.T) { "openapi:schema/divisibleBy": `out_of_scope "FROM_SCHEMA" /paths/~1a/get/parameters/0/schema/divisibleBy`, }, "r": { - "openapi:format": `out_of_scope "FROM_PARAMETER_OBJECT" /paths/~1a/get/parameters/1/format`, - "openapi:schema/format": `degraded_lowering "FROM_SCHEMA_BESIDE_REF" /paths/~1a/get/parameters/1/schema/format`, + "openapi:format": `out_of_scope "FROM_PARAMETER_OBJECT" /paths/~1a/get/parameters/1/format`, }, } wantHeader := map[string]string{ @@ -111,14 +110,15 @@ func TestParameter_SchemaAndObjectSpellOneKey(t *testing.T) { for _, f := range findings(diags) { assert.NotContains(t, f, "unknown-key-entry-already-claimed", name) } - assert.Len(t, findings(diags), 6, "%s: three table findings, two schema keywords, the $ref's key", name) + // The format beside r's $ref restricts it, keeping nothing. + assert.Len(t, findings(diags), 5, "%s: three table findings, two schema keywords", name) - a := operationTree(t, doc, "a") + operationTree := operationTree(t, doc, "a") for param, entry := range want { - assert.Empty(t, cmp.Diff(entry, entries(t, valueAtPath(namedItem(t, valueAtPath(a, "params"), param), "unmodeled"))), + assert.Empty(t, cmp.Diff(entry, entries(t, valueAtPath(namedItem(t, valueAtPath(operationTree, "params"), param), "unmodeled"))), "%s: %s", name, param) } - h := namedItem(t, valueAtPath(a, "responses", "0", "headers"), "X-H") + h := namedItem(t, valueAtPath(operationTree, "responses", "0", "headers"), "X-H") assert.Empty(t, cmp.Diff(wantHeader, entries(t, valueAtPath(h, "unmodeled"))), name) } assert.Empty(t, cmp.Diff(withoutSources(t, docs["object key first"]), withoutSources(t, docs["schema first"])), @@ -143,20 +143,21 @@ func TestParameter_XMLKeptOnce(t *testing.T) { }, entries(t, valueAtPath(q, "unmodeled")))) } -// TestParameter_BranchKeptOnce holds the keywords an allOf entry of a -// parameter's schema keeps to one entry each, beneath the schema's scope: the -// format no use of its string holds, and the readOnly the parameter has no -// field for, each reported where the keyword's keeper reports it. +// TestParameter_BranchKeptOnce holds what an allOf of a parameter's schema +// keeps to one entry each, beneath the schema's scope: the $ref the entry's +// `format: uuid` takes precedence over, the parameter being the uuid, and the +// readOnly the parameter has no field for, each reported where its keep reports +// it. func TestParameter_BranchKeptOnce(t *testing.T) { t.Parallel() doc, diags := parseFull(t, specFrom(t, specsDir, "param_branch_kept_once")) id := namedItem(t, valueAtPath(operationTree(t, doc, "g"), "params"), "schema_id") assert.Empty(t, cmp.Diff(map[string]string{ - "openapi:schema/format": `degraded_lowering "uuid" /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/1/format`, + "openapi:schema/$ref": `degraded_lowering "#/components/schemas/Id" /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/0`, "openapi:schema/readOnly": `no_ir_home true /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/1/readOnly`, }, entries(t, valueAtPath(id, "unmodeled")))) assert.Equal(t, []string{ - "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/1", + "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/0", "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/0/schema/allOf/1/readOnly", "openapi/degraded-construct info /paths/~1s~1{schema_id}/get/parameters/1/schema/xml", }, findings(diags)) @@ -171,20 +172,20 @@ func TestParameter_RedactionIsSingleSided(t *testing.T) { t.Parallel() doc, diags := parseFull(t, specFrom(t, specsDir, "param_redaction_single_sided")) assert.Empty(t, diags) - a := operationTree(t, doc, "a") + operationTree := operationTree(t, doc, "a") - inl := namedItem(t, valueAtPath(a, "params"), "inl") + inl := namedItem(t, valueAtPath(operationTree, "params"), "inl") assert.Equal(t, true, valueAtPath(inl, "secret")) assert.Equal(t, "extension-promotion", valueAtPath(inl, "provenance", "inferred")) assert.Empty(t, cmp.Diff(map[string]string{ "openapi:x-sensitive": `vendor_extension false /paths/~1a/get/parameters/0/x-sensitive`, "openapi:schema/x-sensitive": `vendor_extension true /paths/~1a/get/parameters/0/schema/x-sensitive`, }, entries(t, valueAtPath(inl, "unmodeled")))) - assert.Equal(t, true, valueAtPath(namedItem(t, valueAtPath(a, "params"), "ref"), "secret")) + assert.Equal(t, true, valueAtPath(namedItem(t, valueAtPath(operationTree, "params"), "ref"), "secret")) var found bool - for _, td := range doc.Types { - model, ok := td.(*ir.Model) + for _, typeDef := range doc.Types { + model, ok := typeDef.(*ir.Model) if !ok { continue } @@ -199,7 +200,7 @@ func TestParameter_RedactionIsSingleSided(t *testing.T) { } // TestGroups_ARepeatedTagNameTakesItsFirstDeclaration holds two tags of one -// name: the load's duplicate-key error stands and the document is still built, +// name: the load's duplicate-key error remains and the document is still built, // each tag keeping its own keys, and the group the name forms taking the first // declaration's tier and keys. func TestGroups_ARepeatedTagNameTakesItsFirstDeclaration(t *testing.T) { @@ -216,19 +217,19 @@ func TestGroups_ARepeatedTagNameTakesItsFirstDeclaration(t *testing.T) { "openapi:x-stability": `vendor_extension "alpha" /tags/1/x-stability`, }, entries(t, valueAtPath(d, "tagDefs", "1", "unmodeled")))) - g := tree(t, doc.Services[0].Groups[0]) - assert.Equal(t, "operation-group/tags/T", valueAtPath(g, "id")) - assert.Equal(t, "beta", valueAtPath(g, "stability")) - assert.Equal(t, "extension-promotion", valueAtPath(g, "inferred")) + tree := tree(t, doc.Services[0].Groups[0]) + assert.Equal(t, "operation-group/tags/T", valueAtPath(tree, "id")) + assert.Equal(t, "beta", valueAtPath(tree, "stability")) + assert.Equal(t, "extension-promotion", valueAtPath(tree, "inferred")) assert.Empty(t, cmp.Diff(map[string]string{ "openapi:x-first": `vendor_extension 1 /tags/0/x-first`, "openapi:x-stability": `vendor_extension "beta" /tags/0/x-stability`, - }, entries(t, valueAtPath(g, "unmodeled")))) + }, entries(t, valueAtPath(tree, "unmodeled")))) } // TestParameter_AContentEntrysRedactionIsSingleSided holds a content // parameter's own x-sensitive: false to withdrawing nothing its content entry -// states, as its schema's statement stands beside the same key. +// states, as its schema's statement sits beside the same key. func TestParameter_AContentEntrysRedactionIsSingleSided(t *testing.T) { t.Parallel() doc, diags := parseFull(t, `openapi: 3.1.0 diff --git a/compilers/openapi/internal/overlay/aliasing_test.go b/compilers/openapi/internal/overlay/aliasing_test.go index abc895b5f..287efba42 100644 --- a/compilers/openapi/internal/overlay/aliasing_test.go +++ b/compilers/openapi/internal/overlay/aliasing_test.go @@ -24,7 +24,7 @@ const aliasedSpec = `components: // TestApply_DrawsNoFindingForTheAliasesTheSourceWrites pins that a source's // YAML aliases and merge keys are no warning: an overlay reads the value they -// stand for and writes one position of it, so an action on an anchor, on +// name and writes one position of it, so an action on an anchor, on // something inside it, on a node no one names or on the anchor's removal each // applies with nothing to say, but for a primitive it replaces. func TestApply_DrawsNoFindingForTheAliasesTheSourceWrites(t *testing.T) { diff --git a/compilers/openapi/internal/overlay/attribution.go b/compilers/openapi/internal/overlay/attribution.go index f5dea3ad1..612b0f175 100644 --- a/compilers/openapi/internal/overlay/attribution.go +++ b/compilers/openapi/internal/overlay/attribution.go @@ -103,7 +103,7 @@ func (f *frame) position(positions *provenance.Positions) *provenance.Position { // // Mapping keys are not walked in their own right; each rides on its value's // frame, since a member is added with its key. An alias node is a leaf, -// because the content it stands for lives at the anchor's own position, which +// because the content it names lives at the anchor's own position, which // the walk reaches there, and the overlay writes no alias. func children(frameValue *frame) []*frame { switch frameValue.node.Kind { diff --git a/compilers/openapi/internal/overlay/copyonwrite_test.go b/compilers/openapi/internal/overlay/copyonwrite_test.go index d81f1afff..7b524fc6d 100644 --- a/compilers/openapi/internal/overlay/copyonwrite_test.go +++ b/compilers/openapi/internal/overlay/copyonwrite_test.go @@ -30,7 +30,7 @@ const aliasedSource = head + `components: ` // expandedSource is aliasedSource with every alias and merge written out by -// hand: the value it stands for, with no node shared. +// hand: the value it names, with no node shared. const expandedSource = head + `components: schemas: A: {type: object, properties: {x: {type: string}}} @@ -39,7 +39,7 @@ const expandedSource = head + `components: ` // schemasAfter returns the components.schemas the three schemas hold after an -// overlay, each written as the flow mapping its position stands for. +// overlay, each written as the flow mapping its position names. func schemasAfter(a, b, c string) string { return head + "components:\n schemas:\n A: " + a + "\n B: " + b + "\n C: " + c + "\n" } @@ -52,7 +52,7 @@ const ( // holders returns the position of each mapping under root holding key with // the value value, each as the keys and indexes that reach it, joined by a // slash, in document order. An alias is read as the node it names, once for -// each position it stands at. +// each position it sits at. func holders(root *yaml.Node, key, value string) []string { var out []string var walk func(node *yaml.Node, at string) @@ -84,7 +84,7 @@ func holders(root *yaml.Node, key, value string) []string { // nodesIn counts the nodes a Content walk reaches from root: an alias is one // node, and what it names is not entered, so the count is the size of the -// tree the overlay left and not of the value it stands for. +// tree the overlay left and not of the value it names. func nodesIn(root *yaml.Node) int { count := 0 stack := []*yaml.Node{root} @@ -191,7 +191,7 @@ func TestApply_GivesTheSharedValueTheSameTreeAsItsExpansion(t *testing.T) { // TestApply_LeavesAnAnchorsOtherUsesAsTheSourceWroteThem pins what an update of // the anchor leaves of the nodes that name it: B and C keep the value they -// stood for, a merge key's members and its own description among them, which +// named, a merge key's members and its own description among them, which // the overlay never wrote. func TestApply_LeavesAnAnchorsOtherUsesAsTheSourceWroteThem(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/overlay/fields.go b/compilers/openapi/internal/overlay/fields.go index bce6a3b3a..832060e6c 100644 --- a/compilers/openapi/internal/overlay/fields.go +++ b/compilers/openapi/internal/overlay/fields.go @@ -323,7 +323,7 @@ func (r *reader) selectors(a *action, fields map[string]*yaml.Node) { // reference reads a Reusable Action Reference: its $ref names an entry of // components.actions by a JSON pointer in the document's own fragment, and -// the action it stands for is that entry's fields at the reference's own +// the action it names is that entry's fields at the reference's own // target. A description, the reference's or the entry's, has no effect. func (r *reader) reference(node *yaml.Node, at jsontext.Pointer, what string, reusable map[string]map[string]*yaml.Node, ) map[string]*yaml.Node { diff --git a/compilers/openapi/internal/overlay/graft.go b/compilers/openapi/internal/overlay/graft.go index c2dcc1a83..ecbb2c7ff 100644 --- a/compilers/openapi/internal/overlay/graft.go +++ b/compilers/openapi/internal/overlay/graft.go @@ -37,7 +37,7 @@ type grafter struct { // size is the sequence's count of the tree's nodes against the node // budget, nil for no budget. size *budget.Budget - // copies holds the nodes a copy of a shared value built, which stand at + // copies holds the nodes a copy of a shared value built, which sit at // a position the source does not write them at. copies map[*yaml.Node]bool // detached reports that a node an alias may name left the tree, by a @@ -134,7 +134,7 @@ func where(node *yaml.Node) string { // write writes payload into each of targets, and reports whether that changed // the tree. Under Overlay 1.1 and 1.2 the targets must be of one shape. An // update the rules refuse is an error naming why, and ends the action where -// it stands. +// it is. func (g *grafter) write(ctx context.Context, targets []*yaml.Node, payload *yaml.Node) (bool, error) { payload = nodeview.Deref(payload) if payload == nil || payload.Kind == yaml.AliasNode { @@ -255,7 +255,7 @@ func (g *grafter) mergeMember(ctx context.Context, name string, current, value * // replace writes the primitive value over the primitive target in place, // keeping its node, and reports whether that changed it. A value the source -// declares where it stands, one no earlier action wrote and no copy moved, is +// declares where it sits, one no earlier action wrote and no copy moved, is // recorded as replaced. func (g *grafter) replace(target, value *yaml.Node) bool { tag := value.ShortTag() @@ -316,7 +316,7 @@ func (g *grafter) clone(node *yaml.Node, depth int) (*yaml.Node, error) { // copyOf returns a copy of node, which holder is to hold, depth levels below // the node an action selected. The copy holds no alias: an alias is replaced by -// a copy of what it names, the value it stands for. It keeps no anchor, since +// a copy of what it names, the value it names. It keeps no anchor, since // the node it named is not the one being written, and no line and column, since // the document it lands in does not write it there. built, when set, is handed // each node built, the node it copies and its holder, nil for the root, and diff --git a/compilers/openapi/internal/overlay/graft_test.go b/compilers/openapi/internal/overlay/graft_test.go index 2097b321a..9c8564b21 100644 --- a/compilers/openapi/internal/overlay/graft_test.go +++ b/compilers/openapi/internal/overlay/graft_test.go @@ -257,7 +257,7 @@ func TestGrafter_ReportsAValueACopyReplaced(t *testing.T) { } // TestGrafter_TakesACopyOfTheSourceAsTheActionBegan pins the template a copy -// takes: a source that holds a target is copied as it stood, not as writing +// takes: a source that holds a target is copied as it was, not as writing // it into the target left it, and a target that holds the source takes it // whole. func TestGrafter_TakesACopyOfTheSourceAsTheActionBegan(t *testing.T) { @@ -290,7 +290,7 @@ func TestGrafter_RefusesACopyOfManyNodes(t *testing.T) { // TestGrafter_WritesOnePositionOfAnAlias pins what an action selecting a // YAML alias, or merging into a member the source writes as one, does: it // writes that position, and the anchor and every other use of it keep the -// value they stood for. +// value they named. func TestGrafter_WritesOnePositionOfAnAlias(t *testing.T) { t.Parallel() const src = "x-a: &a {k: v}\nx-b: *a\nx-c: {d: *a}\n" @@ -312,7 +312,7 @@ func TestGrafter_WritesOnePositionOfAnAlias(t *testing.T) { } // TestGrafter_WritesWhatAnAliasInTheUpdateNames pins an alias the overlay -// writes in its update: it stands for its anchor's value, so what is written +// writes in its update: it names its anchor's value, so what is written // is a copy of that value, holding no alias, with no anchor of its own. func TestGrafter_WritesWhatAnAliasInTheUpdateNames(t *testing.T) { t.Parallel() @@ -358,7 +358,7 @@ func aliasNodes(root *yaml.Node) int { // TestRepairAliases_CopiesWhatARemoveLeftAnAliasNaming pins what a remove of // an anchored node leaves at each alias of it: a copy of the value the alias -// stands for, holding no alias, so every reader walking the tree sees what the +// names, holding no alias, so every reader walking the tree sees what the // parser follows (GitHub #477). An alias reached through a `<<` merge key and // one inside another anchored value are copied alike, and one both the anchor // and the alias of which were removed leaves nothing. @@ -382,7 +382,7 @@ func TestRepairAliases_CopiesWhatARemoveLeftAnAliasNaming(t *testing.T) { // TestRepairAliases_KeepsTheWriterOfWhatItCopies pins the attribution of a // copy a remove's repair makes: an update of the anchor writes a copy of it, -// so the alias goes on standing for what the source declares, and the copy +// so the alias goes on naming what the source declares, and the copy // the remove's repair leaves there is the source's. func TestRepairAliases_KeepsTheWriterOfWhatItCopies(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/overlay/repair.go b/compilers/openapi/internal/overlay/repair.go index f8853df52..2d37b7f9b 100644 --- a/compilers/openapi/internal/overlay/repair.go +++ b/compilers/openapi/internal/overlay/repair.go @@ -14,7 +14,7 @@ import ( ) // repairAliases replaces each alias the actions left naming a node outside the -// tree, as a remove of its anchor leaves it, with a copy of the value it stands +// tree, as a remove of its anchor leaves it, with a copy of the value it names // for, since readers here walk Content and read an alias as a leaf while the // parser follows it (GitHub #477). It runs once grafterValue removed a node, // the one way grafterValue detaches one, and is whole or refused: done is false @@ -99,7 +99,7 @@ func substituteDetached(ctx context.Context, node *yaml.Node, reachable map[*yam // // A copy of a node the overlay wrote is the overlay's too, and a copy of one // the source declares is the source's, keeping the line and column the source -// writes it at: it stands at the alias's position for what the source wrote +// writes it at: it sits at the alias's position for what the source wrote // at the anchor. func substituteChildren(node *yaml.Node, reachable map[*yaml.Node]bool, work *budget.Budget, copies map[*yaml.Node]bool) bool { for i, child := range node.Content { diff --git a/compilers/openapi/internal/overlay/repair_internal_test.go b/compilers/openapi/internal/overlay/repair_internal_test.go index 4ed45a793..7a87e2035 100644 --- a/compilers/openapi/internal/overlay/repair_internal_test.go +++ b/compilers/openapi/internal/overlay/repair_internal_test.go @@ -113,7 +113,7 @@ func TestRepairAliases_IsRefusedOnceTheContextIsDone(t *testing.T) { // TestRepairAliases_RunsOnlyOnceARemoveApplied pins the gate: nothing but a // remove detaches a node, so a grafter that removed none leaves the tree to // the actions, and an alias naming nothing, which no parse produces, refuses -// a repair rather than stand for no value. +// a repair rather than name no value. func TestRepairAliases_RunsOnlyOnceARemoveApplied(t *testing.T) { t.Parallel() root, grafter := detached() diff --git a/compilers/openapi/internal/overlay/sequence.go b/compilers/openapi/internal/overlay/sequence.go index 5fa22dcce..89f5cc3f3 100644 --- a/compilers/openapi/internal/overlay/sequence.go +++ b/compilers/openapi/internal/overlay/sequence.go @@ -139,7 +139,7 @@ type selection struct { } // selected returns what a's selectors select in the value the tree now -// stands for, each target location once. A view is made for the action, +// names, each target location once. A view is made for the action, // since each write changes the tree. func (s *sequence) selected(ctx context.Context, a action) (selection, error) { if a.kind == kindNone { @@ -210,7 +210,7 @@ func (s *sequence) step(ctx context.Context, a action, sel selection) error { payload := a.payload if a.kind == kindCopy { // A template is taken of the source first, so each target receives - // it as it stood when the action began, though the source may hold a + // it as it was when the action began, though the source may hold a // target, or a target the source. template, err := copyOf(sources[0].Node, nil, 0, nil) if err != nil { diff --git a/compilers/openapi/internal/overlay/sequence_internal_test.go b/compilers/openapi/internal/overlay/sequence_internal_test.go index ac1429adf..565a95b6b 100644 --- a/compilers/openapi/internal/overlay/sequence_internal_test.go +++ b/compilers/openapi/internal/overlay/sequence_internal_test.go @@ -218,7 +218,7 @@ func TestSequence_ChargesAnActionAfterARemoveOnTheTreeItLeft(t *testing.T) { // TestSequence_AppliesNoActionOnceItsContextRefused cancels a sequence at // every check of its context a whole one makes, the recounts its overstated // charges take and the index a remove reads among them, and requires the tree -// it leaves to be the tree as it stood at the refusal: no action is applied +// it leaves to be the tree as it was at the refusal: no action is applied // once a check has refused, since a charge or an index a cancel cut short may // be partial. Each action writes a title of its own, so one applied late shows. func TestSequence_AppliesNoActionOnceItsContextRefused(t *testing.T) { @@ -302,7 +302,7 @@ func TestWeigher_CountsWhatTheCloneBuilds(t *testing.T) { assert.Equal(t, 0, newWeigher(budget.AtMost(10)).weigh(nil, 0)) } -// TestSequence_NeverChargesLessThanItBuilds is the property the budget stands +// TestSequence_NeverChargesLessThanItBuilds is the property the budget rests // on. The charge is taken before an action runs and the tree is measured after, // and a charge below what the action built would let an overlay build past the // budget one action at a time. So the charge must bound what is built, for diff --git a/compilers/openapi/internal/overlay/steps_internal_test.go b/compilers/openapi/internal/overlay/steps_internal_test.go index 845b06315..734e70fcb 100644 --- a/compilers/openapi/internal/overlay/steps_internal_test.go +++ b/compilers/openapi/internal/overlay/steps_internal_test.go @@ -41,7 +41,7 @@ func chainSource(n int) string { return stepsHead + "x-deep: " + strings.Repeat("{a: ", n) + "{}" + strings.Repeat("}", n) + "\n" } -// needOf returns the steps the query costs over the value src stands for, +// needOf returns the steps the query costs over the value src names, // measured by the evaluator itself. func needOf(t testing.TB, src, query string) int { t.Helper() diff --git a/compilers/openapi/internal/overlay/twin_test.go b/compilers/openapi/internal/overlay/twin_test.go index 8141064ac..869ad9f3d 100644 --- a/compilers/openapi/internal/overlay/twin_test.go +++ b/compilers/openapi/internal/overlay/twin_test.go @@ -85,7 +85,7 @@ func (s *sharer) source() string { return b.String() } -// expansion writes the value src stands for with no node shared: every alias +// expansion writes the value src names with no node shared: every alias // and merge written out, as decoding the source and encoding it again does. func expansion(t *testing.T, src string) string { t.Helper() @@ -113,7 +113,7 @@ var twinActions = []string{ } // withoutInfo returns codes but the replaced-value infos, which turn on -// whether the source writes a value where it stands, and nil for none. +// whether the source writes a value where it is, and nil for none. func withoutInfo(codes []string) []string { kept := slices.DeleteFunc(codes, func(c string) bool { return c == "info "+diag.OverlayReplacedValue }) if len(kept) == 0 { diff --git a/compilers/openapi/internal/overlay/value.go b/compilers/openapi/internal/overlay/value.go index 34d4090db..ec9093128 100644 --- a/compilers/openapi/internal/overlay/value.go +++ b/compilers/openapi/internal/overlay/value.go @@ -32,7 +32,7 @@ type position struct { } // ownSlot makes the value at holder.Content[slot] the action's own to write -// and returns it: as it is, or, where an alias stands there or an alias names +// and returns it: as it is, or, where an alias sits there or an alias names // the node, a copy of it in its place. The copy keeps the aliases it holds as // aliases, and drops its anchors, since no alias names the copy. func (g *grafter) ownSlot(ctx context.Context, holder *yaml.Node, slot int) (*yaml.Node, error) { @@ -174,10 +174,10 @@ func mergedKeys(node *yaml.Node) map[nodeview.Pair]*yaml.Node { // copyContent returns a copy of the tree under node, built after its nodes are // charged to the node budget: each node the tree holds, an alias kept as an // alias, so the copy is the size of what the source wrote and not of the value -// it stands for. It drops anchors, keeps the line and column the source writes +// it names. It drops anchors, keeps the line and column the source writes // each node at, and records as written what the overlay wrote. A copy moved to // another position than node's, an alias's or a merge's, is recorded as one, -// since the source does not write it where it stands. +// since the source does not write it where it is. func (g *grafter) copyContent(ctx context.Context, node *yaml.Node, moved bool) (*yaml.Node, error) { size := nodeview.Walk{Nodes: math.MaxInt}.Run(ctx, node) if size.Cut || !g.admit(ctx, size.Visited) { @@ -206,7 +206,7 @@ func (g *grafter) copyTree(node *yaml.Node, moved bool) *yaml.Node { } // copyNode returns a copy of node alone, its anchor dropped, moved where it -// does not stand at node's position; a copied alias is one more alias naming +// does not sit at node's position; a copied alias is one more alias naming // what node names. func (g *grafter) copyNode(node *yaml.Node, moved bool) *yaml.Node { copied := &yaml.Node{Kind: node.Kind, Style: node.Style, Tag: node.Tag, Value: node.Value, Alias: node.Alias, diff --git a/compilers/openapi/internal/overlay/value_test.go b/compilers/openapi/internal/overlay/value_test.go index 58c8aabed..c108790b2 100644 --- a/compilers/openapi/internal/overlay/value_test.go +++ b/compilers/openapi/internal/overlay/value_test.go @@ -167,7 +167,7 @@ func TestApply_WritesAMergedMemberAsTheMappingsOwn(t *testing.T) { // TestApply_RemovesEveryCopyOfAKeyWrittenTwice pins a remove of a member whose // key the mapping writes twice: the value reads the last copy, and removing -// the member removes the earlier one too, which would otherwise stand in its +// the member removes the earlier one too, which would otherwise take its // place. func TestApply_RemovesEveryCopyOfAKeyWrittenTwice(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/pagination/extension_internal_test.go b/compilers/openapi/internal/pagination/extension_internal_test.go index 020eb83fa..1cf7111e0 100644 --- a/compilers/openapi/internal/pagination/extension_internal_test.go +++ b/compilers/openapi/internal/pagination/extension_internal_test.go @@ -26,8 +26,8 @@ func TestMarker_AUseOfATypeTheRegistryLacksMarksNothing(t *testing.T) { t.Parallel() markerValue := &marker{pg: pagerOver(ir.TypeRegistry{}), target: promotion.TargetPaginationItems, src: promotion.ExtensionSource{Key: "x-k", Values: []string{"items"}}} - keeper, marked := markerValue.marksUse(nil, &ir.Provenance{}, "type/gone") - assert.Nil(t, keeper) + marking, marked := markerValue.marksUse(nil, &ir.Provenance{}, "type/gone") + assert.Nil(t, marking) assert.False(t, marked) } diff --git a/compilers/openapi/internal/pagination/extension_marks.go b/compilers/openapi/internal/pagination/extension_marks.go index 15c10b5b9..22cf41b0c 100644 --- a/compilers/openapi/internal/pagination/extension_marks.go +++ b/compilers/openapi/internal/pagination/extension_marks.go @@ -16,7 +16,7 @@ import ( // one walk as short. type position struct { segments []ir.PropertyID - keeper *ir.Provenance + marking *ir.Provenance shared bool header bool } @@ -34,17 +34,17 @@ type marker struct { // marks returns the provenance of the node keeping unmodeled when src marks // it. -func (m *marker) marks(unmodeled ir.Unmodeled, keeper *ir.Provenance) (*ir.Provenance, bool) { +func (m *marker) marks(unmodeled ir.Unmodeled, marking *ir.Provenance) (*ir.Provenance, bool) { st, diags := promotion.PageStatementOf(m.pg.p, m.target, m.src, unmodeled, nil) m.diags = append(m.diags, diags...) m.written = m.written || st.Written - return keeper, st.Stated + return marking, st.Stated } // marksUse returns the node marking a use of a type, the property or // parameter holding the use or, where its own keys do not, the type it names. -func (m *marker) marksUse(own ir.Unmodeled, keeper *ir.Provenance, of ir.TypeID) (*ir.Provenance, bool) { - if at, ok := m.marks(own, keeper); ok { +func (m *marker) marksUse(own ir.Unmodeled, marking *ir.Provenance, of ir.TypeID) (*ir.Provenance, bool) { + if at, ok := m.marks(own, marking); ok { return at, true } td := m.pg.w.Types[of] @@ -67,13 +67,13 @@ func (pg *pager) markedInput(operation *ir.Operation, target promotion.Extension // A mark is a valued fact: the parameter's own key, else the nearest object // it carries writing one. own := promotion.Carried(pg.p, parameter.Unmodeled, promotion.CarrierScopes(mediaTypes[parameter.ID])...) - if keeper, ok := markerValue.marksUse(own, ¶meter.Provenance, parameter.Type.Target); ok { - found, read = append(found, &ir.InputPath{Param: ¶meter.ID}), append(read, keeper) + if marking, ok := markerValue.marksUse(own, ¶meter.Provenance, parameter.Type.Target); ok { + found, read = append(found, &ir.InputPath{Param: ¶meter.ID}), append(read, marking) } } body, failure := markerValue.within(operation.Request) if body != nil { - found, read = append(found, &ir.InputPath{Segments: body.segments}), append(read, body.keeper) + found, read = append(found, &ir.InputPath{Segments: body.segments}), append(read, body.marking) } resolvedValue := resolved[*ir.InputPath]{read: read, at: operation.Provenance, stated: len(found) > 0 || failure != "", written: markerValue.written} @@ -107,11 +107,11 @@ func (pg *pager) markedOutput(operation *ir.Operation, target promotion.Extensio lacking = true bodiedLacking = bodiedLacking || body != nil case resolvedValue.value == nil: - resolvedValue.value, resolvedValue.read, resolvedValue.stated = found.path(), []*ir.Provenance{found.keeper}, true + resolvedValue.value, resolvedValue.read, resolvedValue.stated = found.path(), []*ir.Provenance{found.marking}, true case !sameOutput(resolvedValue.value, found.path()): return resolvedValue, "marks different members of the success responses", markerValue.diags default: - resolvedValue.read = append(resolvedValue.read, found.keeper) + resolvedValue.read = append(resolvedValue.read, found.marking) } } if resolvedValue.value != nil && (bodiedLacking || lacking && resolvedValue.value.In == "header") { @@ -136,13 +136,13 @@ func (m *marker) inResponse(body *ir.Payload, headers []ir.Header) (*position, s mediaType = property.Encoding.MediaType } own := promotion.Carried(m.pg.p, property.Unmodeled, promotion.CarrierScopes(mediaType)...) - keeper, ok := m.marksUse(own, &property.Provenance, property.Type.Target) + marking, ok := m.marksUse(own, &property.Provenance, property.Type.Target) switch { case !ok: case found != nil: return nil, "marks more than one value of a response" default: - found = &position{segments: []ir.PropertyID{property.ID}, keeper: keeper, header: true} + found = &position{segments: []ir.PropertyID{property.ID}, marking: marking, header: true} } } return found, "" @@ -194,8 +194,8 @@ func (m *marker) within(body *ir.Payload) (*position, string) { // its body. func (m *marker) search(root ir.TypeID) []position { if td := m.pg.w.Types[root]; !ir.IsNilTypeDef(td) { - if keeper, ok := m.marks(td.Common().Unmodeled, &td.Common().Provenance); ok { - return []position{{keeper: keeper}} + if marking, ok := m.marks(td.Common().Unmodeled, &td.Common().Provenance); ok { + return []position{{marking: marking}} } } reach := m.pg.reaching(m.src.Key) @@ -263,8 +263,8 @@ func (m *marker) descend(level []step, seen, reach map[ir.TypeID]bool) ([]positi at := map[ir.TypeID]int{} for _, stepValue := range level { for _, property := range m.pg.w.Members(stepValue.model) { - if keeper, ok := m.marksUse(property.Unmodeled, &property.Provenance, property.Type.Target); ok { - found = append(found, position{segments: stepValue.trail.segments(property.ID), keeper: keeper, shared: stepValue.shared}) + if marking, ok := m.marksUse(property.Unmodeled, &property.Provenance, property.Type.Target); ok { + found = append(found, position{segments: stepValue.trail.segments(property.ID), marking: marking, shared: stepValue.shared}) } typeID := property.Type.Target if i, ok := at[typeID]; ok { @@ -298,9 +298,9 @@ func (pg *pager) reaching(key string) map[ir.TypeID]bool { if !pg.anyMember(keeps) { return set } - // Each keeper's namers are added after it, so the set is the answer and the - // registry's order, which seeds the queue, is not. - namers, queue := pg.keepers(keeps, set) + // Each keeping model's namers are added after it, so the set is the answer + // and the registry's order, which seeds the queue, is not. + namers, queue := pg.keepingModelsAndNamers(keeps, set) for len(queue) > 0 { typeID := queue[len(queue)-1] queue = queue[:len(queue)-1] @@ -330,10 +330,10 @@ func (pg *pager) keeping(entry string) func(*ir.Property) bool { } } -// keepers reads every model's members once. It adds to set each model with a -// member keeps answers true for, returns those models, and returns, for each -// model, the models naming it by a member. -func (pg *pager) keepers(keeps func(*ir.Property) bool, set map[ir.TypeID]bool) (map[ir.TypeID][]ir.TypeID, []ir.TypeID) { +// keepingModelsAndNamers reads every model's members once. It adds to set each +// model with a member keeps answers true for, returns those models, and +// returns, for each model, the models naming it by a member. +func (pg *pager) keepingModelsAndNamers(keeps func(*ir.Property) bool, set map[ir.TypeID]bool) (map[ir.TypeID][]ir.TypeID, []ir.TypeID) { namers := map[ir.TypeID][]ir.TypeID{} var found []ir.TypeID for id := range pg.w.Types { @@ -366,10 +366,10 @@ func (pg *pager) anyMember(keeps func(*ir.Property) bool) bool { return false } -// isModel reports whether id stands for a model, read through alias scalars +// isModel reports whether id names a model, read through alias scalars // as a model's members are (compileddoc.CompiledDocumentView.Members). func (pg *pager) isModel(id ir.TypeID) bool { - _, ok := pg.w.Stands(id).(*ir.Model) + _, ok := pg.w.ChainEndNode(id).(*ir.Model) return ok } diff --git a/compilers/openapi/internal/pagination/extension_pathitem_test.go b/compilers/openapi/internal/pagination/extension_pathitem_test.go index 70314be07..d3143eabf 100644 --- a/compilers/openapi/internal/pagination/extension_pathitem_test.go +++ b/compilers/openapi/internal/pagination/extension_pathitem_test.go @@ -43,11 +43,11 @@ func TestPromote_TrueReadsThePathItemFirst(t *testing.T) { "a statement read from the path item draws no finding") } -// TestPromote_ASilentOperationReadsNeitherItsPathItemNorTheRoot holds an +// TestPromote_AnOperationWritingNoKeyReadsNeitherItsPathItemNorTheRoot holds an // operation that wrote no pagination key to none: a path item's statement of a // walk says nothing of a method that did not opt in. The path item's key stays // kept on the operation. -func TestPromote_ASilentOperationReadsNeitherItsPathItemNorTheRoot(t *testing.T) { +func TestPromote_AnOperationWritingNoKeyReadsNeitherItsPathItemNorTheRoot(t *testing.T) { t.Parallel() src, err := os.ReadFile(pageTruePathItem) require.NoError(t, err) diff --git a/compilers/openapi/internal/pagination/extension_resolve.go b/compilers/openapi/internal/pagination/extension_resolve.go index 7b5532af1..da0c7d40f 100644 --- a/compilers/openapi/internal/pagination/extension_resolve.go +++ b/compilers/openapi/internal/pagination/extension_resolve.go @@ -38,12 +38,12 @@ type resolved[T any] struct { // firstResolved returns what the first of target's sources to state anything on // operation resolves to, written where any source's key is, and true where a // source stated a value that does not resolve, which is reported and fills no -// pagination. A later source naming another value is reported and loses, as it -// does for every target. +// pagination. A later source naming another value is reported and passed over, +// as it does for every target. func firstResolved[T any](pg *pager, operation *ir.Operation, target promotion.ExtensionTarget, read func(promotion.ExtensionSource) (resolved[T], string, []ir.Diagnostic), same func(T, T) bool, ) (resolved[T], bool, []ir.Diagnostic) { - var kept resolved[T] + var chosen resolved[T] var first promotion.ExtensionSource var diags []ir.Diagnostic written := false @@ -56,16 +56,16 @@ func firstResolved[T any](pg *pager, operation *ir.Operation, target promotion.E return resolved[T]{written: true}, true, append(diags, diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, resolvedValue.at, "extension %q %s, so operation %q takes no pagination from its extensions", src, failure, operation.ID)) case !resolvedValue.stated: - case !kept.stated: - kept, first = resolvedValue, src - case !same(kept.value, resolvedValue.value): + case !chosen.stated: + chosen, first = resolvedValue, src + case !same(chosen.value, resolvedValue.value): diags = append(diags, diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, resolvedValue.at, "extension %q states another %s than %q, which the policy reads first, and does not fill it", src, target, first)) } } - kept.written = written - return kept, false, diags + chosen.written = written + return chosen, false, diags } // input resolves what operation's extensions state of target, a value of its diff --git a/compilers/openapi/internal/pagination/extension_stated_test.go b/compilers/openapi/internal/pagination/extension_stated_test.go index 7b99600ca..c85836c64 100644 --- a/compilers/openapi/internal/pagination/extension_stated_test.go +++ b/compilers/openapi/internal/pagination/extension_stated_test.go @@ -154,7 +154,7 @@ func TestPromote_SaysWhichOperationsSpeakOfAPagination(t *testing.T) { } // keyPosition is a place a pagination key is read: the operation writing ops, -// in which V stands for the key's value, and the components it adds, the +// in which V names the key's value, and the components it adds, the // pointer the key sits at, and whether it is the expression key or a mark, and // one a page reads. type keyPosition struct { diff --git a/compilers/openapi/internal/pagination/links.go b/compilers/openapi/internal/pagination/links.go index 57d3ee4b3..e4ce6e1a2 100644 --- a/compilers/openapi/internal/pagination/links.go +++ b/compilers/openapi/internal/pagination/links.go @@ -233,7 +233,7 @@ func partIf(ok bool, part linkPart) linkPart { func (r *reader) linkPage(id ir.TypeID) page { parts := map[linkPart][]*ir.Property{} for _, property := range r.w.Members(id) { - part := linkPartOf(property.Name.Canonical, r.w.Stands(property.Type.Target)) + part := linkPartOf(property.Name.Canonical, r.w.ChainEndNode(property.Type.Target)) if part == partOther { return page{why: "is no page"} } @@ -263,7 +263,7 @@ func linkHeader(compiledDocumentView *compileddoc.CompiledDocumentView, operatio return false } at := slices.IndexFunc(headers, func(header ir.Header) bool { return header.ID == found[0] }) - if primitive, ok := compiledDocumentView.Stands(headers[at].Type.Target).(*ir.Primitive); !ok || primitive.PrimitiveKind != ir.PrimitiveString { + if primitive, ok := compiledDocumentView.ChainEndNode(headers[at].Type.Target).(*ir.Primitive); !ok || primitive.PrimitiveKind != ir.PrimitiveString { return false } declared = true diff --git a/compilers/openapi/internal/pagination/page.go b/compilers/openapi/internal/pagination/page.go index 8a7282b81..d851022e3 100644 --- a/compilers/openapi/internal/pagination/page.go +++ b/compilers/openapi/internal/pagination/page.go @@ -175,7 +175,7 @@ func (r *reader) page(key pageKey) page { // readPage reads where the body key names holds a page: a list holds its items // whole and nothing more, and a model holds them at a member. func (r *reader) readPage(key pageKey) page { - switch td := r.w.Stands(key.body).(type) { + switch td := r.w.ChainEndNode(key.body).(type) { case *ir.List: if key.cursor != "" { return page{nextWhy: "is a list, which holds no next cursor"} @@ -429,7 +429,7 @@ func (ms *models) of(id ir.TypeID) *model { } modelValue := &model{scalars: map[string][]scalar{}, urls: map[string][]*ir.Property{}} for _, property := range ms.w.Members(id) { - switch td := ms.w.Stands(property.Type.Target).(type) { + switch td := ms.w.ChainEndNode(property.Type.Target).(type) { case *ir.List: modelValue.lists = append(modelValue.lists, property) case *ir.Model: diff --git a/compilers/openapi/internal/pagination/request.go b/compilers/openapi/internal/pagination/request.go index db6e5ae79..5af22e35a 100644 --- a/compilers/openapi/internal/pagination/request.go +++ b/compilers/openapi/internal/pagination/request.go @@ -140,10 +140,10 @@ func queryPlaced(placements []compileddoc.Placement) (ir.HTTPLocation, bool) { return "", false } -// sendable returns the primitive the type id stands for, read through alias +// sendable returns the primitive the type id names, read through alias // scalars, when a walk can send it or count with it (sendableAs). func sendable(compiledDocumentView *compileddoc.CompiledDocumentView, id ir.TypeID) (ir.PrimitiveKind, bool) { - return sendableAs(compiledDocumentView.Stands(id)) + return sendableAs(compiledDocumentView.ChainEndNode(id)) } // sendableAs returns td's primitive when a walk can send it or count with it: @@ -325,7 +325,7 @@ func places(compiledDocumentView *compileddoc.CompiledDocumentView, operation *i } // paramPlaces returns the places operation's query parameters name. An object -// parameter, bound in the query or as the query string and standing for a +// parameter, bound in the query or as the query string and naming a // model, is read through its members, one level down, where one of them // names a role, a continuation or a page size, its own name then giving it // none; otherwise a parameter bound in the query is read by its own name. @@ -358,7 +358,7 @@ func paramPlaces(compiledDocumentView *compileddoc.CompiledDocumentView, operati } // memberPlaces returns the places the members of parameter name, where -// parameter's type stands for a model, and none otherwise. +// parameter's type names a model, and none otherwise. func memberPlaces(compiledDocumentView *compileddoc.CompiledDocumentView, parameter *ir.Parameter) (continuations, limits []place) { for _, property := range compiledDocumentView.Members(parameter.Type.Target) { switch roleValue := roleOf(property.Name.Canonical); { diff --git a/compilers/openapi/internal/paramchoice/paramchoice_test.go b/compilers/openapi/internal/paramchoice/paramchoice_test.go index 9111b967b..fa74921db 100644 --- a/compilers/openapi/internal/paramchoice/paramchoice_test.go +++ b/compilers/openapi/internal/paramchoice/paramchoice_test.go @@ -58,8 +58,8 @@ func compile(t *testing.T, src string) (ir.Operation, map[string]string) { return openapitest.FindOperation(t, doc, "getR"), found } -// TestPromote_ReadsEachChoiceWholeOrNotAtAll pins each way a choice is -// refused, one report at the coordinate that says why, the others standing. +// TestPromote_ReadsEachChoiceWholeOrNotAtAll pins each way a choice is refused, +// one report at the coordinate that says why, the others left in place. func TestPromote_ReadsEachChoiceWholeOrNotAtAll(t *testing.T) { t.Parallel() const good = " good:\n optional: true\n variants: {x: [a], y: [b]}\n" @@ -88,7 +88,7 @@ func TestPromote_ReadsEachChoiceWholeOrNotAtAll(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() operation, found := compile(t, spec(tc.choice+good)) - require.Len(t, operation.ParamChoices, 1, "the readable choice stands") + require.Len(t, operation.ParamChoices, 1, "the readable choice remains") assert.Equal(t, "good", operation.ParamChoices[0].Name.Source) assert.Equal(t, map[string]string{key + tc.at: found[key+tc.at]}, found) assert.Contains(t, found[key+tc.at], tc.why) diff --git a/compilers/openapi/internal/promotion/carried_test.go b/compilers/openapi/internal/promotion/carried_test.go index e3927c577..5be9d9622 100644 --- a/compilers/openapi/internal/promotion/carried_test.go +++ b/compilers/openapi/internal/promotion/carried_test.go @@ -98,7 +98,7 @@ func TestWithOwnCarriedState_ASingleSidedFactHoldsWhereAnyStatesIt(t *testing.T) } // TestCarrierScopes_NamesTheSchemaOrTheContentEntryThenItsSchema holds the -// scopes a parameter or a header is read through to the spelling it elects, +// scopes a parameter or a header is read through to the spelling it chooses, // nearest first, a media type escaped as one segment. func TestCarrierScopes_NamesTheSchemaOrTheContentEntryThenItsSchema(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/promotion/contained.go b/compilers/openapi/internal/promotion/contained.go index e1741e2c9..eec427982 100644 --- a/compilers/openapi/internal/promotion/contained.go +++ b/compilers/openapi/internal/promotion/contained.go @@ -25,6 +25,28 @@ func DropContained(promoter Promoter, unmodeled *ir.Unmodeled, whole ...string) dropContained(promoter, unmodeled, holdsWhole, whole) } +// DropContainedWithin is DropContained for the entries written strictly beneath +// within, in its source, alone: the parts of a construct kept whole there, +// such as a discriminator's extensions, which another entry holding the +// construct holds already. An entry written anywhere else stays, whatever holds +// it. +func DropContainedWithin(promoter Promoter, unmodeled *ir.Unmodeled, within ir.Provenance) { + if unmodeled == nil || len(*unmodeled) < 2 { + return + } + beneath := string(within.Pointer) + "/" + at := holdersAt(*unmodeled, slices.Collect(maps.Keys(*unmodeled))) + for key, inner := range *unmodeled { + if inner.Provenance.Source != within.Source || !strings.HasPrefix(string(inner.Provenance.Pointer), beneath) || + namesReadKey(promoter.keys, key) { + continue + } + if heldBy(*unmodeled, at, key, inner, holdsWhole) { + delete(*unmodeled, key) + } + } +} + // dropContained is DropContained asking holds whether one entry holds another, // of the entries whose provenance lies above the other's only: each entry // listed as a holder is found by where it is written (holdersAt), and an entry diff --git a/compilers/openapi/internal/promotion/contained_cost_internal_test.go b/compilers/openapi/internal/promotion/contained_cost_internal_test.go index a7ad224ac..8eee865e1 100644 --- a/compilers/openapi/internal/promotion/contained_cost_internal_test.go +++ b/compilers/openapi/internal/promotion/contained_cost_internal_test.go @@ -52,7 +52,7 @@ func TestDropContained_AsksEachEntryOfItsAncestorsOnly(t *testing.T) { } // TestDropContained_DropsWhatAnyEntryHolds pins the drop to the plain reading -// of its definition, each entry asked of every other as the set stood, over +// of its definition, each entry asked of every other as the set was, over // entries that nest in a chain, lie in other sources, differ in value, and // sit at one pointer: what a dropped entry held is dropped with it, so the // order the entries are visited in changes nothing. diff --git a/compilers/openapi/internal/promotion/contained_test.go b/compilers/openapi/internal/promotion/contained_test.go index b2d024205..32a504f25 100644 --- a/compilers/openapi/internal/promotion/contained_test.go +++ b/compilers/openapi/internal/promotion/contained_test.go @@ -135,3 +135,32 @@ func keysOf(unmodeled ir.Unmodeled) []string { slices.Sort(out) return out } + +// TestDropContainedWithin_DropsOnlyWhatLiesBeneath holds the drop to the +// entries strictly beneath its position, in its source: a discriminator's +// extension the kept discriminator holds goes, and an entry another holds +// elsewhere, one at the position itself, one in another source, one a +// promotion reads and one no entry holds all stay. +func TestDropContainedWithin_DropsOnlyWhatLiesBeneath(t *testing.T) { + t.Parallel() + within := ir.Provenance{Source: 0, Pointer: "/s/discriminator"} + unmodeled := ir.Unmodeled{ + "openapi:discriminator": held(0, "/s/discriminator", `{"propertyName":"k","x-b":5,"x-sensitive":true}`), + "openapi:discriminator/x-b": held(0, "/s/discriminator/x-b", `5`), + "openapi:discriminator/x-c": held(0, "/s/discriminator/x-c", `6`), + "openapi:discriminator/x-sensitive": held(0, "/s/discriminator/x-sensitive", `true`), + "openapi:schema/discriminator": held(0, "/s/discriminator", `{"propertyName":"k","x-b":5,"x-sensitive":true}`), + "openapi:other/x-b": held(1, "/s/discriminator/x-b", `5`), + "openapi:not": held(0, "/s/not", `{"x-d":1}`), + "openapi:not/x-d": held(0, "/s/not/x-d", `1`), + } + reads := promotion.New(mapping(promotion.TargetRedaction, promotion.ExtensionSource{Key: "x-sensitive"})) + promotion.DropContainedWithin(reads, &unmodeled, within) + assert.Equal(t, []string{"openapi:discriminator", "openapi:discriminator/x-c", "openapi:discriminator/x-sensitive", + "openapi:not", "openapi:not/x-d", "openapi:other/x-b", "openapi:schema/discriminator"}, keysOf(unmodeled)) + + alone := ir.Unmodeled{"openapi:discriminator/x-b": held(0, "/s/discriminator/x-b", `5`)} + promotion.DropContainedWithin(noPromotions(), &alone, within) + assert.Equal(t, []string{"openapi:discriminator/x-b"}, keysOf(alone), "one entry holds no other") + promotion.DropContainedWithin(noPromotions(), nil, within) +} diff --git a/compilers/openapi/internal/promotion/pagination.go b/compilers/openapi/internal/promotion/pagination.go index 9aae1b83b..dc1e70fc3 100644 --- a/compilers/openapi/internal/promotion/pagination.go +++ b/compilers/openapi/internal/promotion/pagination.go @@ -79,7 +79,7 @@ func (p Promoter) Sources(target ExtensionTarget) []ExtensionSource { // spells where it lists no Values, and whether its value is one of them where // it does. The key written false says nothing is there to read. Any other // value stating nothing to every pagination source of the key is reported, -// worded alike for each, so one report stands per node. root is the document +// worded alike for each, so one report appears per node. root is the document // root's Unmodeled where the node is an operation, and nil otherwise, as an // operation's true reads the root's (rootStatement). func PageStatementOf(promoter Promoter, target ExtensionTarget, src ExtensionSource, unmodeled, root ir.Unmodeled) (PageStatement, []ir.Diagnostic) { diff --git a/compilers/openapi/internal/promotion/prefixes.go b/compilers/openapi/internal/promotion/prefixes.go index 907fb76ec..1a734c62b 100644 --- a/compilers/openapi/internal/promotion/prefixes.go +++ b/compilers/openapi/internal/promotion/prefixes.go @@ -14,7 +14,7 @@ import ( "github.com/dexpace/morphic/ir" ) -// UnreadExtensions reports each vendor extension doc keeps under a prefix p's +// UnreadExtensions reports each vendor extension doc keeps under a prefix promoter's // policy owns that the compiler reads no key of, naming the nearest key it // reads, as the likeliest one it misspells. The keys read are each reader's // own: the promotion mapping's (Promoter.Keys) and grouping, the keys the run's diff --git a/compilers/openapi/internal/promotion/promotion.go b/compilers/openapi/internal/promotion/promotion.go index 802098661..45e517509 100644 --- a/compilers/openapi/internal/promotion/promotion.go +++ b/compilers/openapi/internal/promotion/promotion.go @@ -624,8 +624,8 @@ type reading[T comparable] struct { // textReading reads a value as prose, a version or a date. Text is taken as // written; a date is not parsed, because the mapping is the caller's statement -// that the key holds one. Empty text states nothing: a field holding it reads as -// unset, so it could fill nothing and would stand in front of a later source. +// that the key holds one. Empty text states nothing: a field holding it reads +// as unset, so it could fill nothing and would sit in front of a later source. func textReading(target ExtensionTarget) reading[string] { return reading[string]{ target: target, @@ -676,20 +676,20 @@ func (p Promoter) redactionReading() reading[bool] { // whether any did. Precedence is the policy's order and never a sorted one, so // a document writing two mapped keys cannot resolve by how the keys spell. // -// A later source stating another value loses, and is reported at its own key, -// as is a value the target cannot hold: the entry stays either way, so the +// A later source stating another value is passed over, and reported at its own +// key, as is a value the target cannot hold: the entry stays either way, so the // report is what tells a reader the field did not take it. func firstStated[T comparable](unmodeled ir.Unmodeled, sources []ExtensionSource, readingValue reading[T]) (T, bool, []ir.Diagnostic) { - kept, _, found, diags := firstStatedAt(unmodeled, sources, readingValue) - return kept, found, diags + chosen, _, found, diags := firstStatedAt(unmodeled, sources, readingValue) + return chosen, found, diags } // firstStatedAt is firstStated, also returning the provenance of the source // whose value it returns. func firstStatedAt[T comparable](unmodeled ir.Unmodeled, sources []ExtensionSource, readingValue reading[T]) (T, ir.Provenance, bool, []ir.Diagnostic) { - var kept T + var chosen T var first ExtensionSource - var keptAt ir.Provenance + var chosenAt ir.Provenance var found bool var diags []ir.Diagnostic for _, src := range sources { @@ -718,14 +718,14 @@ func firstStatedAt[T comparable](unmodeled ir.Unmodeled, sources []ExtensionSour "extension %q %s, so it does not fill %s", src, want, readingValue.target)) case said != states: case !found: - kept, first, keptAt, found = v, src, at, true - case v != kept: + chosen, first, chosenAt, found = v, src, at, true + case v != chosen: diags = append(diags, diag.Newf(ir.SeverityInfo, diag.DegradedConstruct, at, "extension %q states another %s than %q, which the policy reads first, and does not fill it", src, readingValue.target, first)) } } - return kept, keptAt, found, diags + return chosen, chosenAt, found, diags } // readStability reads a value as a tier. diff --git a/compilers/openapi/internal/promotion/promotion_test.go b/compilers/openapi/internal/promotion/promotion_test.go index bf6fed953..cb42d5c6b 100644 --- a/compilers/openapi/internal/promotion/promotion_test.go +++ b/compilers/openapi/internal/promotion/promotion_test.go @@ -179,9 +179,9 @@ func TestPromoterDeprecation_ValueThatIsNotTextIsReported(t *testing.T) { } } -// TestPromoterDeprecation_EmptyTextStatesNothing pins what a field holding "" is: -// unset. So empty text writes nothing and leaves no marker saying it did, and it -// does not stand in front of a later source that has something to say. +// TestPromoterDeprecation_EmptyTextStatesNothing pins what a field holding "" +// is: unset. So empty text writes nothing and leaves no marker saying it did, +// and it does not sit in front of a later source that has something to say. func TestPromoterDeprecation_EmptyTextStatesNothing(t *testing.T) { t.Parallel() for _, tc := range []struct { @@ -269,17 +269,17 @@ func TestPromoter_PolicyIsCopiedIntoThePromoter(t *testing.T) { // TestPromoter_ReadsSourcesInPolicyOrder is the fix for two keys resolving by // how they sort: the list states precedence, the first stating a value fills -// the field, and the loser is reported at its own key rather than dropped in -// silence (GitHub #655). Both orders run, because a promoter sorting its keys -// passes either one alone. +// the field, and the passed-over one is reported at its own key rather than +// dropped in silence (GitHub #655). Both orders run, because a promoter sorting +// its keys passes either one alone. func TestPromoter_ReadsSourcesInPolicyOrder(t *testing.T) { t.Parallel() alpha, zulu := promotion.ExtensionSource{Key: "x-alpha-msg"}, promotion.ExtensionSource{Key: "x-zulu-msg"} for _, tc := range []struct { - name string - order []promotion.ExtensionSource - want string - loserAt jsontext.Pointer + name string + order []promotion.ExtensionSource + want string + passedOverAt jsontext.Pointer }{ {"alpha first", []promotion.ExtensionSource{alpha, zulu}, "FROM-ALPHA", "/x-zulu-msg"}, {"zulu first", []promotion.ExtensionSource{zulu, alpha}, "FROM-ZULU", "/x-alpha-msg"}, @@ -294,12 +294,12 @@ func TestPromoter_ReadsSourcesInPolicyOrder(t *testing.T) { }, promotion.Referent{}, &dep, &prov) assert.Equal(t, tc.want, dep.Message) - require.Len(t, diags, 1, "the loser is reported") + require.Len(t, diags, 1, "the passed-over one is reported") assert.Equal(t, ir.SeverityInfo, diags[0].Severity) assert.Equal(t, "openapi/degraded-construct", diags[0].Code) - assert.Equal(t, tc.loserAt, diags[0].Provenance.Pointer) + assert.Equal(t, tc.passedOverAt, diags[0].Provenance.Pointer) assert.Contains(t, diags[0].Message, tc.order[1].Key) - assert.Contains(t, diags[0].Message, tc.order[0].Key, "and names the key it lost to") + assert.Contains(t, diags[0].Message, tc.order[0].Key, "and names the key chosen over it") }) } } @@ -769,7 +769,7 @@ func TestEnumOpenness_NonEnumCarrierIsTheWholeAnswer(t *testing.T) { // TestEnumOpenness_FirstStatedDecides holds the enum to the order every // other target reads in: the explicit false a policy reads first declines, and -// a later key stating the set open loses and is reported. +// a later key stating the set open is passed over and reported. func TestEnumOpenness_FirstStatedDecides(t *testing.T) { t.Parallel() enum := ir.Enum{Closed: true} diff --git a/compilers/openapi/internal/promotion/statement.go b/compilers/openapi/internal/promotion/statement.go index 9cc8291b3..2d73a9b6c 100644 --- a/compilers/openapi/internal/promotion/statement.go +++ b/compilers/openapi/internal/promotion/statement.go @@ -26,12 +26,12 @@ func (p Promoter) StatementOf(target ExtensionTarget, own ir.Unmodeled) (RawStat return p.firstValue(target, own, nil) } -// firstValue returns the value the first of p's sources of target writes on -// the node keeping own, by the policy's order, against which refuse, where -// set, gives no reason. A later source writing an equal value is silent, as +// firstValue returns the value the first of p's sources of target writes on the +// node keeping own, by the policy's order, against which refuse, where set, +// gives no reason. A later source writing an equal value reports nothing, as // firstStated's is; one writing another is reported at its own key and not -// read, as are a value refuse gives a reason against and a member of a key -// that is no object. Each report is info diag.UnpromotedExtension. +// read, as are a value refuse gives a reason against and a member of a key that +// is no object. Each report is info diag.UnpromotedExtension. func (p Promoter) firstValue(target ExtensionTarget, own ir.Unmodeled, refuse func(ir.RawValue) string) (RawStatement, bool, []ir.Diagnostic) { outcome := "it does not fill " + string(target) var st RawStatement diff --git a/compilers/openapi/internal/promotion/stream_test.go b/compilers/openapi/internal/promotion/stream_test.go index fdcb7fd7e..70301a4ac 100644 --- a/compilers/openapi/internal/promotion/stream_test.go +++ b/compilers/openapi/internal/promotion/stream_test.go @@ -15,7 +15,7 @@ import ( // TestTextOf_ReadsTheFirstSourceStatingAText pins how a stream target reads // its sources on one node: the first to state a text wins, a later one -// stating the same is silent and one stating another is reported, and a +// stating the same reports nothing and one stating another is reported, and a // value that is no text or an empty text states nothing and is reported, as is // a member of a value that is no object. Each report is info, at the key, and // names the target it does not fill. @@ -76,8 +76,8 @@ func TestTextOf_ReadsTheFirstSourceStatingAText(t *testing.T) { // TestStatementOf_ReadsTheFirstSourceWritten pins that a target read whole is // read from the first source whose key the node writes, whatever it holds: a -// later source writing the same value is silent, and one writing another is -// reported and not read. A source reading a member the key does not hold +// later source writing the same value reports nothing, and one writing another +// is reported and not read. A source reading a member the key does not hold // writes nothing. func TestStatementOf_ReadsTheFirstSourceWritten(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/provenance/order.go b/compilers/openapi/internal/provenance/order.go new file mode 100644 index 000000000..5f206644c --- /dev/null +++ b/compilers/openapi/internal/provenance/order.go @@ -0,0 +1,205 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package provenance + +import ( + "cmp" + "encoding/binary" + "encoding/json/jsontext" + "strings" +) + +// ComparePointers orders two JSON Pointers as a document is written, token by +// token: an array index by its number and before any other token, any other by +// its unescaped text, so /allOf/9 comes before /allOf/10, a key `a/` before +// `a~`, and a pointer before every one beneath it. It agrees with +// AppendPointerSortKey's keys compared as bytes. +func ComparePointers(a, b jsontext.Pointer) int { + shared := sharedTokens(string(a), string(b)) + rest, other := string(a[shared:]), string(b[shared:]) + for rest != "" && other != "" { + var token, otherToken string + token, rest = nextToken(rest) + otherToken, other = nextToken(other) + if order := compareTokenKeys(newTokenKey(token), newTokenKey(otherToken)); order != 0 { + return order + } + } + return cmp.Compare(len(rest), len(other)) +} + +// AppendPointerSortKey appends to key the bytes pointer sorts by, which +// compare as ComparePointers compares the pointers, so a sort can write each +// key once. +func AppendPointerSortKey(key []byte, pointer jsontext.Pointer) []byte { + for rest := string(pointer); rest != ""; { + var token string + token, rest = nextToken(rest) + key = appendTokenKey(key, token) + } + return key +} + +// appendTokenKey appends to key the tokenKey of token, an escaped JSON Pointer +// token, a run at a time where its text holds no 0x00. +func appendTokenKey(key []byte, token string) []byte { + if isArrayIndex(token) || strings.IndexByte(token, 0) >= 0 { + tokenKeyValue := newTokenKey(token) + return tokenKeyValue.appendTo(key) + } + key = append(key, textTag) + for { + escape := strings.IndexByte(token, '~') + if escape < 0 { + return append(append(key, token...), 0, 0) + } + var textByte byte + key = append(key, token[:escape]...) + textByte, token = nextUnescaped(token[escape:]) + key = append(key, textByte) + } +} + +// sharedTokens is how many bytes the tokens a and b, two JSON Pointers, open +// with alike take: up to the `/` starting the token holding their first +// difference, which escapes no token holds. +func sharedTokens(a, b string) int { + alike := 0 + for alike < len(a) && alike < len(b) && a[alike] == b[alike] { + alike++ + } + return max(strings.LastIndexByte(a[:alike], '/'), 0) +} + +// nextToken splits pointer, a JSON Pointer holding a token, into its first +// token, still escaped, and what follows it. +func nextToken(pointer string) (token, rest string) { + pointer = strings.TrimPrefix(pointer, "/") + if i := strings.IndexByte(pointer, '/'); i >= 0 { + return pointer[:i], pointer[i:] + } + return pointer, "" +} + +// The first byte of a token's key, which puts an array index before any +// other token. +const ( + indexTag byte = 1 + textTag byte = 2 +) + +// tokenKey reads the sort key of one escaped JSON Pointer token a byte at a +// time, the one definition of the order AppendPointerSortKey writes and +// ComparePointers reads. An array index is indexTag, its length as eight +// bytes and its digits, so indices sort by number. Any other token is +// textTag, the text it escapes with each 0x00 written 0x00 0xff, and 0x00 +// 0x00, which sorts a token before every longer one it opens. +type tokenKey struct { + // head is the tag, and an index's length, of which heads bytes are the + // key's and read have been read. + head [9]byte + heads, read int + // body is what is left of the token, escaped, and index whether it is an + // array index, whose digits are read as written. + body string + index bool + // zero is whether the 0xff after a 0x00 of the text is due, and tail how + // many bytes of the closing 0x00 0x00 are. + zero bool + tail int +} + +// newTokenKey is the key of token, an escaped JSON Pointer token, none read. +func newTokenKey(token string) tokenKey { + if isArrayIndex(token) { + tokenKeyValue := tokenKey{body: token, index: true, heads: len(tokenKey{}.head)} + tokenKeyValue.head[0] = indexTag + binary.BigEndian.PutUint64(tokenKeyValue.head[1:], uint64(len(token))) + return tokenKeyValue + } + return tokenKey{head: [9]byte{textTag}, heads: 1, body: token, tail: 2} +} + +// next returns the key's next byte, and false once it is read in full. +func (k *tokenKey) next() (byte, bool) { + switch { + case k.read < k.heads: + k.read++ + return k.head[k.read-1], true + case k.zero: + k.zero = false + return 0xff, true + case k.body != "" && k.index: + digit := k.body[0] + k.body = k.body[1:] + return digit, true + case k.body != "": + var textByte byte + textByte, k.body = nextUnescaped(k.body) + k.zero = textByte == 0 + return textByte, true + case k.tail > 0: + k.tail-- + return 0, true + default: + return 0, false + } +} + +// appendTo appends to key what next reads of k: an index's at once, and any +// other a byte at a time. +func (k *tokenKey) appendTo(key []byte) []byte { + if k.index { + return append(append(key, k.head[:k.heads]...), k.body...) + } + for { + keyByte, more := k.next() + if !more { + return key + } + key = append(key, keyByte) + } +} + +// compareTokenKeys orders two token keys as bytes, reading each only as far +// as they differ. No token's key opens another's, as no text's holds its +// closing 0x00 0x00 sooner and two indices of one length end together, so +// two keys ending at once are alike. +func compareTokenKeys(a, b tokenKey) int { + for { + aByte, aMore := a.next() + bByte, bMore := b.next() + switch { + case !aMore || !bMore: + return 0 + case aByte != bByte: + return cmp.Compare(aByte, bByte) + } + } +} + +// nextUnescaped splits token, a non-empty escaped JSON Pointer token, into +// the byte its first character escapes, `~1` escaping `/` and `~0` `~`, and +// what follows it. A `~` starting no escape names itself. +func nextUnescaped(token string) (byte, string) { + if token[0] == '~' && len(token) > 1 { + switch token[1] { + case '0': + return '~', token[2:] + case '1': + return '/', token[2:] + } + } + return token[0], token[1:] +} + +// isArrayIndex reports whether token is written as RFC 6901 writes an array +// index: 0, or a decimal with no leading zero. +func isArrayIndex(token string) bool { + digits := 0 + for digits < len(token) && '0' <= token[digits] && token[digits] <= '9' { + digits++ + } + return token != "" && digits == len(token) && (token[0] != '0' || token == "0") +} diff --git a/compilers/openapi/internal/provenance/order_key_test.go b/compilers/openapi/internal/provenance/order_key_test.go new file mode 100644 index 000000000..0a48d7371 --- /dev/null +++ b/compilers/openapi/internal/provenance/order_key_test.go @@ -0,0 +1,60 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package provenance_test + +import ( + "cmp" + "encoding/json/jsontext" + "math/rand/v2" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" +) + +// TestAppendPointerSortKey_OrdersAsComparePointers holds each pointer's sort +// key to ComparePointers: two keys compare as bytes as their pointers compare, +// on edge pairs and on pairs drawn from tokens that sort against each other, +// against the separator and against the escapes, indices of many digits among +// them. +func TestAppendPointerSortKey_OrdersAsComparePointers(t *testing.T) { + t.Parallel() + tokens := []string{"", "0", "1", "2", "9", "10", "01", "00", "99999999999999999999", "100000000000000000000", + "a", "a0", "a~0", "a~1", "a~1b", "a~", "~", "~2", "~0", "~1", "x~0", "x~1", "a-b", "a.b", "b", "é", "\x00"} + pointer := func(r *rand.Rand) jsontext.Pointer { + var b strings.Builder + for range r.IntN(5) { + b.WriteString("/" + tokens[r.IntN(len(tokens))]) + } + return jsontext.Pointer(b.String()) + } + edges := [][2]jsontext.Pointer{ + {"", "/"}, {"/", "//"}, {"/9", "/10"}, {"/0", "/a"}, {"/01", "/1"}, {"/00", "/0"}, {"/a~1", "/a~0"}, + {"/a~1", "/a~1b"}, {"/~2", "/~0"}, {"/~2", "/~1"}, {"/x~0", "/x~1"}, {"/M", "/M/allOf/0"}, {"/a/b", "/a-b"}, + {"/a", "/a/0"}, {"/99999999999999999999", "/100000000000000000000"}, {"/M/allOf/9/x", "/M/allOf/10"}, + } + r := rand.New(rand.NewPCG(2354, 1)) + pairs := make([][2]jsontext.Pointer, 0, len(edges)+20000) + pairs = append(pairs, edges...) + for range 20000 { + pairs = append(pairs, [2]jsontext.Pointer{pointer(r), pointer(r)}) + } + for _, pair := range slices.Concat(pairs, reversedPairs(pairs)) { + want := provenance.ComparePointers(pair[0], pair[1]) + got := strings.Compare(string(provenance.AppendPointerSortKey(nil, pair[0])), string(provenance.AppendPointerSortKey(nil, pair[1]))) + require.Equal(t, cmp.Compare(want, 0), cmp.Compare(got, 0), "%q against %q", pair[0], pair[1]) + } +} + +// reversedPairs is each of pairs with its two pointers swapped. +func reversedPairs(pairs [][2]jsontext.Pointer) [][2]jsontext.Pointer { + out := make([][2]jsontext.Pointer, len(pairs)) + for i, pair := range pairs { + out[i] = [2]jsontext.Pointer{pair[1], pair[0]} + } + return out +} diff --git a/compilers/openapi/internal/provenance/order_test.go b/compilers/openapi/internal/provenance/order_test.go new file mode 100644 index 000000000..232d89892 --- /dev/null +++ b/compilers/openapi/internal/provenance/order_test.go @@ -0,0 +1,72 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package provenance_test + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" +) + +// TestComparePointers_OrdersAsADocumentIsWritten pins the order pointers are +// written in: token by token, two array indices by their number, an index +// before any other token, two other tokens by their text, unescaped, a `~` +// starting no escape naming itself, and a pointer before those beneath +// it. Two tokens opening with the same bytes are read whole, digits after a +// letter as text. +func TestComparePointers_OrdersAsADocumentIsWritten(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + a, b jsontext.Pointer + want int + }{ + {a: "/M/allOf/9/properties/p", b: "/M/allOf/10/properties/p", want: -1}, + {a: "/M/allOf/10", b: "/M/allOf/9", want: 1}, + {a: "/M/allOf/0", b: "/M/allOf/1", want: -1}, + {a: "/M/properties/0", b: "/M/properties/a", want: -1}, + {a: "/M/properties/a", b: "/M/properties/0", want: 1}, + {a: "/M/properties/01", b: "/M/properties/1", want: 1}, + {a: "/A/properties/p", b: "/B/properties/p", want: -1}, + {a: "/M", b: "/M/allOf/0", want: -1}, + {a: "/M/allOf/0", b: "/M", want: 1}, + {a: "", b: "/M", want: -1}, + {a: "/M/allOf/2", b: "/M/allOf/2", want: 0}, + {a: "/M/properties/a~1", b: "/M/properties/a~0", want: -1}, + {a: "/M/properties/a~0", b: "/M/properties/a0", want: 1}, + {a: "/M/properties/a~1", b: "/M/properties/a~1b", want: -1}, + {a: "/M/properties/a~1b", b: "/M/properties/a~1", want: 1}, + {a: "/M/properties/~2", b: "/M/properties/~0", want: 1}, + {a: "/M/properties/~2", b: "/M/properties/~1", want: 1}, + {a: "/M/properties/~2", b: "/M/properties/~3", want: -1}, + {a: "/x~0", b: "/x~1", want: 1}, + {a: "/x~1", b: "/x~0", want: -1}, + {a: "/a100", b: "/a12", want: -1}, + } { + assert.Equal(t, tc.want, provenance.ComparePointers(tc.a, tc.b), "%s against %s", tc.a, tc.b) + } +} + +// TestComparePointers_CostsNoAllocation pins that ordering two pointers builds +// nothing, escapes and indices included: a sort calls it for every pair it +// compares. It is not parallel, as testing.AllocsPerRun measures the process. +func TestComparePointers_CostsNoAllocation(t *testing.T) { + pairs := [][2]jsontext.Pointer{ + {"/M/allOf/9/properties/p", "/M/allOf/10/properties/p"}, + {"/M/properties/a~1", "/M/properties/a~0"}, + {"/M/properties/a~1", "/M/properties/a~1b"}, + {"/M/properties/~2", "/M/properties/~0"}, + {"/x~0", "/x~1"}, + {"/M", "/M/allOf/0"}, + {"/A/properties/p", "/B/properties/p"}, + } + allocations := testing.AllocsPerRun(100, func() { + for _, pair := range pairs { + provenance.ComparePointers(pair[0], pair[1]) + } + }) + assert.Zero(t, allocations) +} diff --git a/compilers/openapi/internal/reftable/bases.go b/compilers/openapi/internal/reftable/bases.go index 5d058c696..bfc167111 100644 --- a/compilers/openapi/internal/reftable/bases.go +++ b/compilers/openapi/internal/reftable/bases.go @@ -36,10 +36,10 @@ type walked struct { held bool } -// newBases returns bases over resourcesValue, whose documents' dialect roots +// newBases returns bases over resources, whose documents' dialect roots // ids holds, having walked nothing. -func newBases(resourcesValue resources, ids *identifiers) *bases { - return &bases{res: resourcesValue, walks: map[DocumentPointer]walked{}, ids: ids} +func newBases(resources resources, ids *identifiers) *bases { + return &bases{res: resources, walks: map[DocumentPointer]walked{}, ids: ids} } // holding is resources.holding of documentPointer read as a schema, along what @@ -105,16 +105,16 @@ func (b *bases) walk(at []DocumentPointer) (int, bool) { // walk remembers every position on its way, so those walked are a run from the // first, and a search halving it finds its end. func (b *bases) deepest(at []DocumentPointer) int { - n := len(at) - 1 - if _, ok := b.walks[at[n]]; ok { - return n + depth := len(at) - 1 + if _, ok := b.walks[at[depth]]; ok { + return depth } - lo, hi := -1, n - if n > 0 { - if _, ok := b.walks[at[n-1]]; ok { - return n - 1 // the parent of a position asked, as a deep schema's levels ask + lo, hi := -1, depth + if depth > 0 { + if _, ok := b.walks[at[depth-1]]; ok { + return depth - 1 // the parent of a position asked, as a deep schema's levels ask } - hi = n - 1 + hi = depth - 1 } for hi-lo > 1 { mid := lo + (hi-lo)/2 @@ -145,12 +145,12 @@ func prefixes(documentPointer DocumentPointer, most int) []DocumentPointer { } // past is the walk from, gone on to node at here, which the grammar reads at -// stateValue: a schema, or a position of a document of schemas, is entered, so +// state: a schema, or a position of a document of schemas, is entered, so // an identifier it writes starts the resource the walk is in past it, and its // `$schema` the dialect (resources.holding). -func (b *bases) past(from walked, node *yaml.Node, stateValue state, here DocumentPointer) walked { - out := walked{node: node, s: stateValue, in: from.in, known: from.known, dialect: from.dialect, held: heldBelow(from)} - if stateValue == sSchema || stateValue == sLoose { +func (b *bases) past(from walked, node *yaml.Node, state state, here DocumentPointer) walked { + out := walked{node: node, s: state, in: from.in, known: from.known, dialect: from.dialect, held: heldBelow(from)} + if state == sSchema || state == sLoose { entering := b.entered(from, node, here) out.in, out.known, out.dialect = entering.res, entering.known, entering.dialect } @@ -161,18 +161,19 @@ func (b *bases) past(from walked, node *yaml.Node, stateValue state, here Docume // it is in past it, whether that is known, and the dialect what node holds is // read in, as resources.holding enters each schema on its way. func (b *bases) entered(from walked, node *yaml.Node, here DocumentPointer) entering { - enteringValue := entering{dialect: from.dialect} + entering := entering{dialect: from.dialect} if b.ids.readsDialects(here.Doc) { held := heldBelow(from) - enteringValue = b.res.enterIn(from.in, here, node, from.dialect, func() bool { return held }) + entering = b.res.enterIn(from.in, here, node, from.dialect, func() bool { return held }) } else { - enteringValue.res, enteringValue.rooted, enteringValue.known = b.res.enter(from.in, node, dialectRule(b.res.docs, here.Doc, from.dialect)) + entering = b.res.enter(from.in, node, dialectRule(b.res.docs, here.Doc, from.dialect)) + entering.dialect = from.dialect } - if enteringValue.rooted { - enteringValue.res.root = here + if entering.rooted { + entering.res.root = here } - enteringValue.known = from.known && enteringValue.known - return enteringValue + entering.known = from.known && entering.known + return entering } // heldBelow reports whether a schema holds what lies directly below the walk diff --git a/compilers/openapi/internal/reftable/budget_test.go b/compilers/openapi/internal/reftable/budget_test.go index 538ce447e..a5a08ac21 100644 --- a/compilers/openapi/internal/reftable/budget_test.go +++ b/compilers/openapi/internal/reftable/budget_test.go @@ -66,7 +66,7 @@ func TestBind_StopsAtItsBudget(t *testing.T) { assert.Equal(t, budget.Unbounded(), full.Limit(), "an unset limit is unbounded") assert.False(t, bound(t, budgetSpec, budgetConfig(budget.AtMost(full.Steps()))).Exhausted(), "the cost itself suffices") want := map[reftable.DocumentPointer]reftable.ReferenceSite{} - for _, referenceSite := range full.Entries() { + for _, referenceSite := range full.ReferenceSites() { want[referenceSite.Site] = referenceSite } disc := documentPointerAt("/components/schemas/P/discriminator") @@ -77,9 +77,9 @@ func TestBind_StopsAtItsBudget(t *testing.T) { cut := bound(t, budgetSpec, budgetConfig(budget.AtMost(limit))) require.True(t, cut.Exhausted(), "limit %d", limit) assert.Equal(t, budget.AtMost(limit), cut.Limit()) - assert.Equal(t, cut.Entries(), bound(t, budgetSpec, budgetConfig(budget.AtMost(limit))).Entries(), "limit %d", limit) - missing += len(want) - len(cut.Entries()) - for _, referenceSite := range cut.Entries() { + assert.Equal(t, cut.ReferenceSites(), bound(t, budgetSpec, budgetConfig(budget.AtMost(limit))).ReferenceSites(), "limit %d", limit) + missing += len(want) - len(cut.ReferenceSites()) + for _, referenceSite := range cut.ReferenceSites() { if referenceSite.Hop.Status == reftable.OverBudget || referenceSite.Chain.Status == reftable.OverBudget { stopped++ continue @@ -108,7 +108,7 @@ func TestBind_StopsAtItsBudget(t *testing.T) { // out in is the last, wherever in it the budget does. A document the first // pass reads as a location, whose own content leads to a declaration naming it // elsewhere, is reached by no later pass, and one step less than the least -// budget that begins a second pass ends in the first, which stands, rather +// budget that begins a second pass ends in the first, which remains, rather // than begin one with nothing to spend. func TestBind_ThePassTheBudgetRunsOutInStands(t *testing.T) { t.Parallel() @@ -139,8 +139,8 @@ func TestBind_ThePassTheBudgetRunsOutInStands(t *testing.T) { require.True(t, first.Exhausted()) require.Equal(t, 1, first.Passes()) a := docNamed(t, first, "/a.yaml") - assert.False(t, first.Document(a).Unreached, "the first pass stands, a.yaml reached in it") - referenceSite, ok := first.Entry(reftable.DocumentPointer{Pointer: "/components/schemas/Y"}) + assert.False(t, first.Document(a).Unreached, "the first pass remains, a.yaml reached in it") + referenceSite, ok := first.ReferenceSiteAt(reftable.DocumentPointer{Pointer: "/components/schemas/Y"}) require.True(t, ok) assert.NotEqual(t, reftable.DocumentPointer{Doc: docNamed(t, first, "/z.yaml"), Pointer: "/S"}, referenceSite.Hop.Target, "no answer of a second pass") @@ -157,8 +157,8 @@ func TestBind_ThePassTheBudgetRunsOutInStands(t *testing.T) { func TestBind_CountsWorkLinearAcrossHeldDocuments(t *testing.T) { t.Parallel() name := func(i int) string { return fmt.Sprintf("https://x.test/d%d.yaml", i) } - tail := func(i, n int, link string) string { - if i == n { + tail := func(i, count int, link string) string { + if i == count { return "" } return link @@ -168,44 +168,44 @@ func TestBind_CountsWorkLinearAcrossHeldDocuments(t *testing.T) { doc func(i, n int) string check func(t *testing.T, table *reftable.ReferenceTargetTable, n int) }{ - {"a chain", func(i, n int) string { - return "S: " + cmp.Or(tail(i, n, fmt.Sprintf("{$ref: '%s#/S'}", name(i+1))), "{type: string}") + "\n" + {"a chain", func(i, count int) string { + return "S: " + cmp.Or(tail(i, count, fmt.Sprintf("{$ref: '%s#/S'}", name(i+1))), "{type: string}") + "\n" }, resolvesA}, - {"a chain spelled relatively", func(i, n int) string { - return "S: " + cmp.Or(tail(i, n, fmt.Sprintf("{$ref: 'd%d.yaml#/S'}", i+1)), "{type: string}") + "\n" + {"a chain spelled relatively", func(i, count int) string { + return "S: " + cmp.Or(tail(i, count, fmt.Sprintf("{$ref: 'd%d.yaml#/S'}", i+1)), "{type: string}") + "\n" }, resolvesA}, - {"a loop", func(i, n int) string { - return fmt.Sprintf("S: {$ref: '%s#/S'}\n", name(i%n+1)) - }, func(t *testing.T, table *reftable.ReferenceTargetTable, n int) { + {"a loop", func(i, count int) string { + return fmt.Sprintf("S: {$ref: '%s#/S'}\n", name(i%count+1)) + }, func(t *testing.T, table *reftable.ReferenceTargetTable, count int) { t.Helper() require.Len(t, table.Loops(), 1, "the loop is found whole") - assert.Len(t, table.Loops()[0].Members, n) + assert.Len(t, table.Loops()[0].Members, count) }}, - {"mapping values", func(i, n int) string { + {"mapping values", func(i, count int) string { return fmt.Sprintf("S: {discriminator: {propertyName: k, mapping: {%s}}}\n", - tail(i, n, fmt.Sprintf("m: '%s#/S'", name(i+1)))) - }, func(t *testing.T, table *reftable.ReferenceTargetTable, n int) { + tail(i, count, fmt.Sprintf("m: '%s#/S'", name(i+1)))) + }, func(t *testing.T, table *reftable.ReferenceTargetTable, count int) { t.Helper() - at := reftable.DocumentPointer{Doc: docNamed(t, table, name(n-1)), Pointer: "/S/discriminator"} - mapping, ok := table.Mapping(at, name(n)+"#/S") + at := reftable.DocumentPointer{Doc: docNamed(t, table, name(count-1)), Pointer: "/S/discriminator"} + mapping, ok := table.Mapping(at, name(count)+"#/S") require.True(t, ok) assert.Equal(t, reftable.Resolved, mapping.Chain.Status) }}, - {"links naming the one before by its $id", func(i, n int) string { + {"links naming the one before by its $id", func(i, count int) string { return fmt.Sprintf("S: {$id: 'https://x.test/id%d', properties: {p: {$ref: 'https://x.test/id%d'}%s}}\n", - i, i-1, tail(i, n, fmt.Sprintf(", n: {$ref: '%s#/S'}", name(i+1)))) - }, func(t *testing.T, table *reftable.ReferenceTargetTable, n int) { + i, i-1, tail(i, count, fmt.Sprintf(", n: {$ref: '%s#/S'}", name(i+1)))) + }, func(t *testing.T, table *reftable.ReferenceTargetTable, count int) { t.Helper() - referenceSite, ok := table.Entry(reftable.DocumentPointer{Doc: docNamed(t, table, name(n)), Pointer: "/S/properties/p"}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: docNamed(t, table, name(count)), Pointer: "/S/properties/p"}) require.True(t, ok) - assert.Equal(t, reftable.DocumentPointer{Doc: docNamed(t, table, name(n-1)), Pointer: "/S"}, referenceSite.Hop.Target) + assert.Equal(t, reftable.DocumentPointer{Doc: docNamed(t, table, name(count-1)), Pointer: "/S"}, referenceSite.Hop.Target) }}, } for _, shape := range shapes { - steps := func(n int) int { + steps := func(count int) int { docs := map[string]string{} - for i := 1; i <= n; i++ { - docs[name(i)] = shape.doc(i, n) + for i := 1; i <= count; i++ { + docs[name(i)] = shape.doc(i, count) } cfg, _ := recordingDocuments(t, docs) open := cfg.Open @@ -223,8 +223,8 @@ func TestBind_CountsWorkLinearAcrossHeldDocuments(t *testing.T) { slices.Sort(asks) slices.Sort(names) assert.Len(t, slices.Compact(asks), len(asks), "%s: each document asked once by each asker", shape.name) - assert.Len(t, slices.Compact(names), n, "%s: each document asked for, and no identifier", shape.name) - shape.check(t, table, n) + assert.Len(t, slices.Compact(names), count, "%s: each document asked for, and no identifier", shape.name) + shape.check(t, table, count) return table.Steps() } n, twice, four := steps(500), steps(1_000), steps(2_000) @@ -264,43 +264,43 @@ func TestBind_CountsWorkLinearInTheDocument(t *testing.T) { return fmt.Sprintf("{$ref: '#/components/schemas/%s%d'}", name, i) } shapes := map[string]func(b *strings.Builder, n int){ - "a chain": func(b *strings.Builder, n int) { - for i := range n { + "a chain": func(b *strings.Builder, count int) { + for i := range count { fmt.Fprintf(b, " C%d: %s\n", i, ref("C", i+1)) } - fmt.Fprintf(b, " C%d: {type: string}\n", n) + fmt.Fprintf(b, " C%d: {type: string}\n", count) }, - "one chain every other $ref enters": func(b *strings.Builder, n int) { - for i := range n / 2 { + "one chain every other $ref enters": func(b *strings.Builder, count int) { + for i := range count / 2 { fmt.Fprintf(b, " C%d: %s\n F%d: %s\n", i, ref("C", i+1), i, ref("C", 0)) } - fmt.Fprintf(b, " C%d: {type: string}\n", n/2) + fmt.Fprintf(b, " C%d: {type: string}\n", count/2) }, - "a loop": func(b *strings.Builder, n int) { - for i := range n { - fmt.Fprintf(b, " C%d: %s\n", i, ref("C", (i+1)%n)) + "a loop": func(b *strings.Builder, count int) { + for i := range count { + fmt.Fprintf(b, " C%d: %s\n", i, ref("C", (i+1)%count)) } }, - "sites only what earlier $refs land on hold": func(b *strings.Builder, n int) { + "sites only what earlier $refs land on hold": func(b *strings.Builder, count int) { b.WriteString(" A: {$ref: '#/components/schemas/X/x-l/L0'}\n X:\n x-l:\n") - for i := range n { + for i := range count { next := fmt.Sprintf("'#/components/schemas/X/x-l/L%d'", i+1) fmt.Fprintf(b, " L%d: {properties: {p: {$ref: %s}}, discriminator: {propertyName: k, mapping: {m: %s}}}\n", i, next, next) } - fmt.Fprintf(b, " L%d: {type: string}\n", n) + fmt.Fprintf(b, " L%d: {type: string}\n", count) }, - "definitions of their own": func(b *strings.Builder, n int) { - for i := range n { + "definitions of their own": func(b *strings.Builder, count int) { + for i := range count { fmt.Fprintf(b, " S%d: {$defs: {k%d: {}}, properties: {p: {$ref: '#/$defs/k%d'}}}\n", i, i, i) } }, } for name, shape := range shapes { - steps := func(n int) int { + steps := func(count int) int { var b strings.Builder b.WriteString(head + "components:\n schemas:\n") - shape(&b, n) + shape(&b, count) table := bound(t, b.String(), self) require.False(t, table.Exhausted(), name) if name == "a loop" { @@ -332,9 +332,9 @@ func TestTable_SaysWhyARefWentUnread(t *testing.T) { other := bound(t, deepMerge()+" O: {$ref: 'other.yaml#/S'}\n", withDocuments(map[string]string{"other.yaml": "S: {type: string}\n"})) require.Equal(t, 2, other.Documents()) - assert.True(t, other.Truncated(), "a document read cleanly after the source keeps its verdict") + assert.True(t, other.Truncated(), "a document read cleanly after the source keeps its answer") assert.Equal(t, "it is past a `<<` merge chain deeper than the 64 levels the compiler expands", deep.Unread()) - _, ok := deep.Entry(documentPointerAt("/components/schemas/A")) + _, ok := deep.ReferenceSiteAt(documentPointerAt("/components/schemas/A")) assert.False(t, ok, "A's $ref is past the bound") assert.Equal(t, documentPointerAt("/components/schemas/T"), entryAt(t, deep, "/components/schemas/B").Hop.Target) } @@ -462,7 +462,7 @@ func TestBind_AnswersAlikeInEitherOrder(t *testing.T) { reversed := slices.Clone(lines) slices.Reverse(reversed) forward, backward := build(lines), build(reversed) - assert.Equal(t, forward.Entries(), backward.Entries()) + assert.Equal(t, forward.ReferenceSites(), backward.ReferenceSites()) assert.Equal(t, forward.Loops(), backward.Loops()) assert.Equal(t, forward.Landings(), backward.Landings()) disc := documentPointerAt("/components/schemas/P/discriminator") @@ -550,15 +550,15 @@ const asksAfterRefusal = 8 // manyMappings writes a discriminator mapping n values, each to a schema whose // $ref the binding follows, so a binding has many sites and mapping values to // read. -func manyMappings(n int) string { +func manyMappings(count int) string { var b strings.Builder b.WriteString("openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + " P: {discriminator: {propertyName: k, mapping: {") - for i := range n { + for i := range count { fmt.Fprintf(&b, "m%d: '#/components/schemas/S%d', ", i, i) } b.WriteString("}}}\n") - for i := range n { + for i := range count { fmt.Fprintf(&b, " S%d: {$ref: '#/components/schemas/T%d'}\n T%d: {type: object}\n", i, i, i) } return b.String() diff --git a/compilers/openapi/internal/reftable/chains.go b/compilers/openapi/internal/reftable/chains.go index 4b29a5578..723b978d5 100644 --- a/compilers/openapi/internal/reftable/chains.go +++ b/compilers/openapi/internal/reftable/chains.go @@ -101,51 +101,51 @@ func newWaits() *waits { } // requeue forgets each held hop, and notes each held site, mapping value and -// reference object in finderValue to settle again, now the documents they wait +// reference object in finder to settle again, now the documents they wait // for are read. A held position waits no longer, so its own chain reads its hop // again; one that leads to it waits on until release. -func (w *waits) requeue(finderValue *finder, hops map[DocumentPointer]Hop, objHops map[DocumentPointer]objectHop) { +func (w *waits) requeue(finder *finder, hops map[DocumentPointer]Hop, objHops map[DocumentPointer]objectHop) { for _, documentPointer := range w.held { delete(hops, documentPointer) delete(w.on, documentPointer) if w.sites[documentPointer] { delete(w.sites, documentPointer) - finderValue.fresh = append(finderValue.fresh, documentPointer) + finder.fresh = append(finder.fresh, documentPointer) } } for _, documentPointer := range w.heldObjects { delete(objHops, documentPointer) for kind := range RefKind(len(refStates)) { - objectKeyValue := objectKey{at: documentPointer, kind: kind + 1} - delete(w.onObjects, objectKeyValue) - if w.objects[objectKeyValue] { - delete(w.objects, objectKeyValue) - finderValue.freshObjects = append(finderValue.freshObjects, objectKeyValue) + objectKey := objectKey{at: documentPointer, kind: kind + 1} + delete(w.onObjects, objectKey) + if w.objects[objectKey] { + delete(w.objects, objectKey) + finder.freshObjects = append(finder.freshObjects, objectKey) } } } for _, mappingKey := range w.heldMappings { delete(w.mappings, mappingKey) - finderValue.freshMappings = append(finderValue.freshMappings, mappingKey) + finder.freshMappings = append(finder.freshMappings, mappingKey) } w.held, w.heldObjects, w.heldMappings, w.released, w.declaring = nil, nil, nil, false, nil } -// release notes in finderValue every site, mapping value and reference object +// release notes in finder every site, mapping value and reference object // that waits, to settle once more now nothing is held, and reports whether // there was any. A second release with no held document read since would meet // the same hops, so it releases nothing, which bounds the pass: what still // waits then has no entry. -func (w *waits) release(finderValue *finder) bool { +func (w *waits) release(finder *finder) bool { if w.released || len(w.sites) == 0 && len(w.mappings) == 0 && len(w.objects) == 0 { return false } w.released = true clear(w.on) clear(w.onObjects) - finderValue.fresh = slices.AppendSeq(finderValue.fresh, maps.Keys(w.sites)) - finderValue.freshMappings = slices.AppendSeq(finderValue.freshMappings, maps.Keys(w.mappings)) - finderValue.freshObjects = slices.AppendSeq(finderValue.freshObjects, maps.Keys(w.objects)) + finder.fresh = slices.AppendSeq(finder.fresh, maps.Keys(w.sites)) + finder.freshMappings = slices.AppendSeq(finder.freshMappings, maps.Keys(w.mappings)) + finder.freshObjects = slices.AppendSeq(finder.freshObjects, maps.Keys(w.objects)) clear(w.sites) clear(w.mappings) clear(w.objects) @@ -188,11 +188,11 @@ func (b *binder) placeLoops() { for i := range b.loops { b.loops[i].Site = b.loops[i].Members[0] } - slices.SortFunc(b.loops, func(loop, loopValue Loop) int { - if c := b.docs.compare(loop.Site, loopValue.Site); c != 0 { - return c + slices.SortFunc(b.loops, func(loop, otherLoop Loop) int { + if order := b.docs.compare(loop.Site, otherLoop.Site); order != 0 { + return order } - return int(loop.Kind) - int(loopValue.Kind) + return int(loop.Kind) - int(otherLoop.Kind) }) - b.loops = slices.CompactFunc(b.loops, func(loop, loopValue Loop) bool { return loop.Site == loopValue.Site }) + b.loops = slices.CompactFunc(b.loops, func(loop, otherLoop Loop) bool { return loop.Site == otherLoop.Site }) } diff --git a/compilers/openapi/internal/reftable/defs.go b/compilers/openapi/internal/reftable/defs.go index 6e51c6c87..cef0d7493 100644 --- a/compilers/openapi/internal/reftable/defs.go +++ b/compilers/openapi/internal/reftable/defs.go @@ -34,27 +34,27 @@ type definitions struct { // definition is where a "#/$defs/..." pointer written at site, reached along // path, in its document's own resource, lands, by the rule // docs/compilers/openapi.md#references states: the position it names from the -// document's root, which readingValue and reason read, else the definitions of +// document's root, which found and reason read, else the definitions of // the nearest object above site holding "$defs" in the model, whatever was read // before (docs/parser-library.md#defs-order, docs/parser-library.md#root-defs). // A schema's own answer only where an identifier makes it a resource, which // resolve reads instead; where schema says site's own hold the key, the reason // says so. A read the merge bound stopped answers MergeBound. func (d definitions) definition(site DocumentPointer, path []*yaml.Node, pointer jsontext.Pointer, schema bool, - readingValue reading, reason Reason, + found reading, reason Reason, ) (reading, Reason) { switch { - case reason == NoReason && answers(readingValue.role(), readingValue.node): - return readingValue, NoReason + case reason == NoReason && answers(found.role(), found.node): + return found, NoReason case reason == MergeBound: return reading{}, MergeBound } - readingValue, why := d.ancestorDefinition(site, path, pointer) + found, why := d.ancestorDefinition(site, path, pointer) if key, single := singleKey(pointer); schema && single && (why == NoDefinition || why == RawDefinition) && d.holds(site.Doc, path[len(path)-1], []string{"$defs", key}) { why = OwnDefinition // the nearer definition left unread } - return readingValue, why + return found, why } // ancestorDefinition is the definition the nearest object above site that @@ -90,9 +90,9 @@ func (d definitions) ancestorDefinition(site DocumentPointer, path []*yaml.Node, continue } node, past := d.below(site.Doc, path[i], rest) - if readingValue := (reading{node: node, place: places[i].along(rest)}); node != nil && answers(readingValue.role(), node) { - readingValue.at = DocumentPointer{Doc: site.Doc, Pointer: jsontext.Pointer(prefix(site.Pointer, i)) + pointer} - return readingValue, NoReason + if reading := (reading{node: node, place: places[i].along(rest)}); node != nil && answers(reading.role(), node) { + reading.at = DocumentPointer{Doc: site.Doc, Pointer: jsontext.Pointer(prefix(site.Pointer, i)) + pointer} + return reading, NoReason } if past { return reading{}, MergeBound @@ -138,20 +138,20 @@ func answers(role Role, node *yaml.Node) bool { } } -// prefix is the pointer to pointer's first n tokens: pointer up to the '/' +// prefix is the pointer to pointer's first count tokens: pointer up to the '/' // opening the token after them, since an escaped token holds none. -func prefix(pointer jsontext.Pointer, n int) string { - s := string(pointer) - for i := range len(s) { - if s[i] != '/' { +func prefix(pointer jsontext.Pointer, count int) string { + text := string(pointer) + for i := range len(text) { + if text[i] != '/' { continue } - if n == 0 { - return s[:i] + if count == 0 { + return text[:i] } - n-- + count-- } - return s + return text } // singleKey is the one key "/$defs/key" names, and whether pointer names one diff --git a/compilers/openapi/internal/reftable/derive.go b/compilers/openapi/internal/reftable/derive.go index 35fa86f5d..28eb37eb3 100644 --- a/compilers/openapi/internal/reftable/derive.go +++ b/compilers/openapi/internal/reftable/derive.go @@ -37,8 +37,8 @@ var ( // (TestObjectFields_ReadsEveryObjectOfTheTable). func objectFields(spec specrules.Spec) map[state]map[string]state { out := make(map[state]map[string]state, len(kindStates)) - for kind, stateValue := range kindStates { - if _, container := entries[stateValue]; container || stateValue == sSchema { + for kind, kindState := range kindStates { + if _, container := entries[kindState]; container || kindState == sSchema { continue } object, _ := spec.Object(kind) @@ -46,7 +46,7 @@ func objectFields(spec specrules.Spec) map[state]map[string]state { for _, field := range object.Fields { fs[field.Name] = leads(field.Shape, field.Of) } - out[stateValue] = fs + out[kindState] = fs } return out } @@ -60,7 +60,7 @@ func leads(shape specrules.Shape, of specrules.Kind) state { case specrules.AnyShapeUnchecked: return sRaw case specrules.String, specrules.Boolean, specrules.Number, specrules.PositiveNumber, specrules.Natural: - return sValue + return s case specrules.RawMap, specrules.RawList: return sRawEntries case specrules.Nested: @@ -79,8 +79,8 @@ func leads(shape specrules.Shape, of specrules.Kind) state { // of is read at, or sObject where the binder reads no such container. func containerOf(in map[state]state, of specrules.Kind) state { if state, ok := kindStates[of]; ok { - if stateValue, ok := in[state]; ok { - return stateValue + if state, ok := in[state]; ok { + return state } } return sObject diff --git a/compilers/openapi/internal/reftable/derive_internal_test.go b/compilers/openapi/internal/reftable/derive_internal_test.go index d9de921c2..304b3414f 100644 --- a/compilers/openapi/internal/reftable/derive_internal_test.go +++ b/compilers/openapi/internal/reftable/derive_internal_test.go @@ -53,7 +53,7 @@ func TestObjectFields_ReadsEveryObjectOfTheTable(t *testing.T) { for _, kind := range plainKinds { assert.Contains(t, objects, kind) for _, field := range objects[kind].Fields { - assert.Equal(t, sValue, class(leads(field.Shape, field.Of)), "%s.%s", objects[kind].Name, field.Name) + assert.Equal(t, s, class(leads(field.Shape, field.Of)), "%s.%s", objects[kind].Name, field.Name) } } } @@ -61,7 +61,7 @@ func TestObjectFields_ReadsEveryObjectOfTheTable(t *testing.T) { // TestObjectFields_ReadsAReferenceWhereTheTableAdmitsOne holds refKinds to the // rule table, both ways: an object state is read as a reference object where // it writes a $ref exactly where its object is one a Reference Object may -// stand in for at some minor, or defines a $ref of its own, as a Path Item +// take the place of at some minor, or defines a $ref of its own, as a Path Item // Object does. A schema's $ref is a site of its own (finder.visit). func TestObjectFields_ReadsAReferenceWhereTheTableAdmitsOne(t *testing.T) { t.Parallel() @@ -90,11 +90,11 @@ func TestObjectFields_LeadsEachShapeWhereItsValueIsRead(t *testing.T) { want state }{ {specrules.AnyShapeUnchecked, 0, sRaw}, - {specrules.String, 0, sValue}, - {specrules.Boolean, 0, sValue}, - {specrules.Number, 0, sValue}, - {specrules.PositiveNumber, 0, sValue}, - {specrules.Natural, 0, sValue}, + {specrules.String, 0, s}, + {specrules.Boolean, 0, s}, + {specrules.Number, 0, s}, + {specrules.PositiveNumber, 0, s}, + {specrules.Natural, 0, s}, {specrules.StringList, 0, sObject}, {specrules.StringMap, 0, sObject}, {specrules.RawMap, 0, sRawEntries}, diff --git a/compilers/openapi/internal/reftable/dialects.go b/compilers/openapi/internal/reftable/dialects.go index 175cc07a2..619726d95 100644 --- a/compilers/openapi/internal/reftable/dialects.go +++ b/compilers/openapi/internal/reftable/dialects.go @@ -24,16 +24,16 @@ type DialectRoot struct { } // heldBySchema reports whether a schema holds the position tokens reach from a -// document's root read at stateValue, the state the document is identified by: +// document's root read at state, the state the document is identified by: // a position below a Schema Object, or below the root of a document that is no // OpenAPI document, which holds every schema in it. The root of a resource an // $id embeds is held so, and roots a resource all the same. -func heldBySchema(stateValue state, tokens []string) bool { +func heldBySchema(state state, tokens []string) bool { for _, token := range tokens { - if stateValue == sSchema || stateValue == sLoose { + if state == sSchema || state == sLoose { return true } - stateValue = step(stateValue, token) + state = step(state, token) } return false } @@ -52,18 +52,18 @@ func dialectsByDocument(roots map[DocumentPointer]DialectRoot) map[DocID][]Diale } // stepIn is step for a token of the mapping node of document id, read at -// stateValue in dialect, which a dialect the drafts before 2020-12 spell reads +// state in dialect, which a dialect the drafts before 2020-12 spell reads // otherwise (dialectStep), at a schema or at a document of schemas' root alike. // Every child a walk reads asks it, so the other tokens take step without a // call more. -func stepIn(docsValue *docs, id DocID, node *yaml.Node, stateValue state, token, dialect string) state { - if stateValue == sSchema || stateValue == sLoose { +func stepIn(docs *docs, id DocID, node *yaml.Node, state state, token, dialect string) state { + if state == sSchema || state == sLoose { switch token { case "items", "additionalItems", "definitions", "dependencies": - return dialectStep(docsValue, id, node, stateValue, token, dialect) + return dialectStep(docs, id, node, state, token, dialect) } } - return step(stateValue, token) + return step(state, token) } // dialectStep is stepIn for a schema's token a dialect reads otherwise @@ -71,32 +71,32 @@ func stepIn(docsValue *docs, id DocID, node *yaml.Node, stateValue state, token, // holds schemas and the `additionalItems` beside it holds its rest, and where // it has `definitions`, or `dependencies`, hold schemas, they do, a property's // list of names among the latter's entries holding none. -func dialectStep(docsValue *docs, id DocID, node *yaml.Node, stateValue state, token, dialect string) state { +func dialectStep(docs *docs, id DocID, node *yaml.Node, state state, token, dialect string) state { switch token { case "definitions": - if dialectRule(docsValue, id, dialect).Definitions { + if dialectRule(docs, id, dialect).Definitions { return sSchemaMap } case "dependencies": - if dialectRule(docsValue, id, dialect).Dependencies { + if dialectRule(docs, id, dialect).Dependencies { return sSchemaMap } case "items": - if listsItems(docsValue, id, node) && dialectRule(docsValue, id, dialect).Tuples { + if listsItems(docs, id, node) && dialectRule(docs, id, dialect).Tuples { return sSchemaList } case "additionalItems": - if listsItems(docsValue, id, node) && dialectRule(docsValue, id, dialect).Tuples { + if listsItems(docs, id, node) && dialectRule(docs, id, dialect).Tuples { return sSchema } } - return step(stateValue, token) + return step(state, token) } // listsItems reports whether the schema mapping node writes `items` as a list, // a tuple, in document id. -func listsItems(docsValue *docs, id DocID, node *yaml.Node) bool { - items := nodeview.Deref(docsValue.list[id].view.ChildByToken(nodeview.Deref(node), "items")) +func listsItems(docs *docs, id DocID, node *yaml.Node) bool { + items := nodeview.Deref(docs.list[id].view.ChildByToken(nodeview.Deref(node), "items")) return items != nil && items.Kind == yaml.SequenceNode } @@ -126,26 +126,30 @@ func (r resources) enterIn(in resource, at DocumentPointer, node *yaml.Node, enc if named && !held { own = dialectRule(r.docs, doc, uri) } - res, rooted, known := r.enter(in, node, own) + entry := r.enter(in, node, own) switch { case !named: - return entering{res: res, rooted: rooted, known: known, dialect: enclosing} + entry.dialect = enclosing + return entry case !held: - return entering{res: res, rooted: rooted, known: known, names: true, dialect: uri} + entry.names, entry.dialect = true, uri + return entry } spelled := dialectRule(r.docs, doc, uri) - if !rooted && spelled.Keyword != own.Keyword && !r.ignoresIdentifier(doc, node, own) { - res, rooted, known = r.enter(in, node, spelled) + if !entry.rooted && spelled.Keyword != own.Keyword && !r.ignoresIdentifier(doc, node, own) { + entry = r.enter(in, node, spelled) } - if !rooted { - return entering{res: res, known: known, dialect: enclosing} + if !entry.rooted { + entry.dialect = enclosing + return entry } - return entering{res: res, rooted: true, known: known, names: true, dialect: uri} + entry.names, entry.dialect = true, uri + return entry } // heldAt reports whether a schema holds the position at (heldBySchema). -func heldAt(docsValue *docs, at DocumentPointer) bool { - return heldBySchema(docsValue.identityState(at.Doc), slices.Collect(at.Pointer.Tokens())) +func heldAt(docs *docs, at DocumentPointer) bool { + return heldBySchema(docs.identityState(at.Doc), slices.Collect(at.Pointer.Tokens())) } // DialectAt returns the innermost of roots, a dialect root by where it is, at @@ -155,8 +159,8 @@ func heldAt(docsValue *docs, at DocumentPointer) bool { // node, so a node an alias places under two roots reads each one's at each. func DialectAt[V any](roots map[DocumentPointer]V, documentPointer DocumentPointer) (V, bool) { for ptr := documentPointer.Pointer; len(roots) > 0; ptr = ptr.Parent() { - if r, ok := roots[DocumentPointer{Doc: documentPointer.Doc, Pointer: ptr}]; ok { - return r, true + if root, ok := roots[DocumentPointer{Doc: documentPointer.Doc, Pointer: ptr}]; ok { + return root, true } if ptr == "" { break @@ -170,11 +174,11 @@ func DialectAt[V any](roots map[DocumentPointer]V, documentPointer DocumentPoint // which a walk from documentPointer starts in: that of the dialect root at or // above it the documents declare (identifiers.dialects), or its document's // default. -func dialectAbove(docsValue *docs, ix *identifiers, documentPointer DocumentPointer) string { +func dialectAbove(docs *docs, ix *identifiers, documentPointer DocumentPointer) string { if dialectRoot, ok := DialectAt(ix.dialects, documentPointer); ok { return dialectRoot.URI } - return defaultDialect(docsValue, documentPointer.Doc) + return defaultDialect(docs, documentPointer.Doc) } // rootDialect returns the dialect the root at documentPointer names, where one @@ -188,11 +192,11 @@ func rootDialect(ix *identifiers, documentPointer DocumentPointer, inherited str // defaultDialect returns the dialect the schemas of document id name none of // their own are read in: an OpenAPI document's jsonSchemaDialect, or "". -func defaultDialect(docsValue *docs, id DocID) string { - if !docsValue.list[id].openapi { +func defaultDialect(docs *docs, id DocID) string { + if !docs.list[id].openapi { return "" } - uri, _ := scalarOf(docsValue.list[id].view.ChildByToken(docsValue.list[id].root, "jsonSchemaDialect")) + uri, _ := scalarOf(docs.list[id].view.ChildByToken(docs.list[id].root, "jsonSchemaDialect")) return uri } @@ -200,22 +204,22 @@ func defaultDialect(docsValue *docs, id DocID) string { // dialect (Config.Dialect), the keyword `$id` where the configuration says // none. Every schema asks it, so each document's answer for a dialect is // remembered, and the last one asked, nearly every asking's, kept to hand. -func dialectRule(docsValue *docs, id DocID, dialect string) DialectRule { - ruleKeyValue := ruleKey{doc: id, dialect: dialect} - if docsValue.last.key == ruleKeyValue && docsValue.last.asked { - return docsValue.last.rule +func dialectRule(docs *docs, id DocID, dialect string) DialectRule { + ruleKey := ruleKey{doc: id, dialect: dialect} + if docs.last.key == ruleKey && docs.last.asked { + return docs.last.rule } - rule, asked := docsValue.rules[ruleKeyValue] + rule, asked := docs.rules[ruleKey] if !asked { - if docsValue.cfg.Dialect != nil { - rule = docsValue.cfg.Dialect(docsValue.list[id].name, dialect) + if docs.cfg.Dialect != nil { + rule = docs.cfg.Dialect(docs.list[id].name, dialect) } if rule.Keyword == "" { rule.Keyword = "$id" } - docsValue.rules[ruleKeyValue] = rule + docs.rules[ruleKey] = rule } - docsValue.last.key, docsValue.last.rule, docsValue.last.asked = ruleKeyValue, rule, true + docs.last.key, docs.last.rule, docs.last.asked = ruleKey, rule, true return rule } @@ -225,19 +229,19 @@ func dialectRule(docsValue *docs, id DocID, dialect string) DialectRule { // no other landing's schema holds, so the `$schema` chooses the dialect of what // it holds (docs/compilers/openapi.md#dialect-keywords). Whether one holds it // turns on the landings alone, so no order of reading decides it. -func landingRoot(finderValue *finder, documentPointer DocumentPointer, node *yaml.Node) (DialectRoot, bool) { - if !finderValue.landings[documentPointer] || heldBySchema(finderValue.docs.identityState(documentPointer.Doc), slices.Collect(documentPointer.Pointer.Tokens())) { +func landingRoot(finder *finder, documentPointer DocumentPointer, node *yaml.Node) (DialectRoot, bool) { + if !finder.landings[documentPointer] || heldBySchema(finder.docs.identityState(documentPointer.Doc), slices.Collect(documentPointer.Pointer.Tokens())) { return DialectRoot{}, false } for above := documentPointer.Pointer; above != ""; { above = above.Parent() - if finderValue.landings[DocumentPointer{Doc: documentPointer.Doc, Pointer: above}] { + if finder.landings[DocumentPointer{Doc: documentPointer.Doc, Pointer: above}] { return DialectRoot{}, false } } node = nodeview.Deref(node) - uri, written := scalarOf(finderValue.docs.list[documentPointer.Doc].view.ChildByToken(node, "$schema")) - if !written || dialectRule(finderValue.docs, documentPointer.Doc, uri).NamesNone { + uri, written := scalarOf(finder.docs.list[documentPointer.Doc].view.ChildByToken(node, "$schema")) + if !written || dialectRule(finder.docs, documentPointer.Doc, uri).NamesNone { return DialectRoot{}, false } return DialectRoot{At: documentPointer, URI: uri, Node: node}, true @@ -246,22 +250,22 @@ func landingRoot(finderValue *finder, documentPointer DocumentPointer, node *yam // startDialect is the dialect a walk from documentPointer, holding node, starts // in: the one documentPointer roots as a landing (landingRoot), else the one // above it (dialectAbove). -func startDialect(finderValue *finder, documentPointer DocumentPointer, node *yaml.Node) string { - if root, ok := landingRoot(finderValue, documentPointer, node); ok { +func startDialect(finder *finder, documentPointer DocumentPointer, node *yaml.Node) string { + if root, ok := landingRoot(finder, documentPointer, node); ok { return root.URI } - return dialectAbove(finderValue.docs, finderValue.ids, documentPointer) + return dialectAbove(finder.docs, finder.ids, documentPointer) } -// withLandingRoots returns roots with each landing finderValue found that is a +// withLandingRoots returns roots with each landing finder found that is a // dialect root of its own (landingRoot) added, roots itself where none is. Each // landing's node is read as the walk that found it read it, charged then. -func withLandingRoots(finderValue *finder, roots map[DocumentPointer]DialectRoot) map[DocumentPointer]DialectRoot { +func withLandingRoots(finder *finder, roots map[DocumentPointer]DialectRoot) map[DocumentPointer]DialectRoot { out := roots - for at := range finderValue.landings { - doc := finderValue.docs.list[at.Doc] + for at := range finder.landings { + doc := finder.docs.list[at.Doc] path, _ := doc.view.DocumentPath(doc.root, at.Pointer) - if root, ok := landingRoot(finderValue, at, path[len(path)-1]); ok { + if root, ok := landingRoot(finder, at, path[len(path)-1]); ok { if len(out) == len(roots) { out = make(map[DocumentPointer]DialectRoot, len(roots)+1) maps.Copy(out, roots) diff --git a/compilers/openapi/internal/reftable/discriminators.go b/compilers/openapi/internal/reftable/discriminators.go new file mode 100644 index 000000000..99e93a77b --- /dev/null +++ b/compilers/openapi/internal/reftable/discriminators.go @@ -0,0 +1,71 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package reftable + +import ( + "encoding/json/jsontext" + "slices" + "strings" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" +) + +// Discriminator is a discriminator object a schema the walks read writes. The +// walks meet one wherever the grammar reads a schema, a field whose content no +// model holds included. +type Discriminator struct { + At DocumentPointer + Node *yaml.Node +} + +// Discriminators is each discriminator the walks met in one document, in the +// order of their pointers' bytes, so those beneath one position are +// contiguous (Within). +type Discriminators []Discriminator + +// Within returns each of d written at pointer or beneath it, in d's order: +// those a node keeping the value written at pointer verbatim keeps with it. +func (d Discriminators) Within(pointer jsontext.Pointer) Discriminators { + from, _ := slices.BinarySearchFunc(d, pointer, func(written Discriminator, target jsontext.Pointer) int { + return strings.Compare(string(written.At.Pointer), string(target)) + }) + var out Discriminators + for _, written := range d[from:] { + if !strings.HasPrefix(string(written.At.Pointer), string(pointer)) { + break + } + if pointer.Contains(written.At.Pointer) { + out = append(out, written) + } + } + return out +} + +// noteDiscriminator notes the discriminator mapping the schema node at +// schemaPointer writes, keeping the first node a walk met it at. +func (w *finder) noteDiscriminator(view *nodeview.View, node *yaml.Node, schemaPointer DocumentPointer) { + discriminatorNode := nodeview.Deref(view.ChildByToken(node, "discriminator")) + if discriminatorNode == nil || discriminatorNode.Kind != yaml.MappingNode { + return + } + disc := schemaPointer.below("discriminator") + if _, met := w.discriminators[disc]; !met { + w.discriminators[disc] = discriminatorNode + } +} + +// discriminatorsByDocument returns what found notes by the document each is +// written in, each document's in the order Discriminators.Within searches. +func discriminatorsByDocument(found map[DocumentPointer]*yaml.Node) map[DocID]Discriminators { + out := map[DocID]Discriminators{} + for at, node := range found { + out[at.Doc] = append(out[at.Doc], Discriminator{At: at, Node: node}) + } + for _, list := range out { + slices.SortFunc(list, func(a, b Discriminator) int { return strings.Compare(string(a.At.Pointer), string(b.At.Pointer)) }) + } + return out +} diff --git a/compilers/openapi/internal/reftable/discriminators_test.go b/compilers/openapi/internal/reftable/discriminators_test.go new file mode 100644 index 000000000..e80c883fe --- /dev/null +++ b/compilers/openapi/internal/reftable/discriminators_test.go @@ -0,0 +1,94 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package reftable_test + +import ( + "encoding/json/jsontext" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" +) + +// discriminatorPointers returns where each discriminator found is written. +func discriminatorPointers(found reftable.Discriminators) []jsontext.Pointer { + out := make([]jsontext.Pointer, 0, len(found)) + for _, written := range found { + out = append(out, written.At.Pointer) + } + return out +} + +// TestDiscriminators_WithinFindsEachWrittenAtOrBeneath pins the +// discriminators the walks meet where the grammar reads a schema, a nested +// Encoding Object's header schema among them, and the search beneath a +// position: at it, beneath it, and not at a sibling whose key only begins +// alike, nor where no schema is written, under an extension or a keyword +// 2020-12 does not define. +func TestDiscriminators_WithinFindsEachWrittenAtOrBeneath(t *testing.T) { + t.Parallel() + const disc = "{propertyName: k}" + table := bound(t, "openapi: 3.2.0\ninfo: {title: t, version: '1'}\npaths:\n /a:\n post:\n"+ + " requestBody: {content: {multipart/form-data: {encoding: {d: {encoding: {e: {headers: {X: {schema: {discriminator: "+disc+"}}}}}}}}}}\n"+ + " responses: {'200': {description: ok}}\n"+ + "components:\n schemas:\n"+ + " N: {discriminator: "+disc+", not: {discriminator: "+disc+"}, x-e: {discriminator: "+disc+"}, "+ + "dependencies: {p: {discriminator: "+disc+"}}}\n"+ + " N2: {discriminator: "+disc+"}\n M: {discriminator: 5}\n", self) + found := table.Document(reftable.Source).Discriminators + assert.Equal(t, []jsontext.Pointer{"/components/schemas/N/discriminator", "/components/schemas/N/not/discriminator"}, + discriminatorPointers(found.Within("/components/schemas/N")), "a sibling N2 begins alike") + assert.Equal(t, []jsontext.Pointer{"/components/schemas/N/not/discriminator"}, + discriminatorPointers(found.Within("/components/schemas/N/not/discriminator"))) + assert.Empty(t, found.Within("/components/schemas/M"), "no object is no discriminator") + assert.Empty(t, found.Within("/z"), "past every one written") + assert.Equal(t, []jsontext.Pointer{ + "/paths/~1a/post/requestBody/content/multipart~1form-data/encoding/d/encoding/e/headers/X/schema/discriminator", + }, discriminatorPointers(found.Within("/paths"))) + assert.Len(t, found.Within(""), 4, "every one the source writes: %v", discriminatorPointers(found)) + assert.Equal(t, reftable.Source, found[0].At.Doc) + assert.Equal(t, "propertyName", found[0].Node.Content[0].Value, "the node is the discriminator object") +} + +// TestDiscriminators_KeepsEachDocumentApart pins the list to the document +// writing each: a document a $ref reads holds its own, which the source's +// list leaves out. +func TestDiscriminators_KeepsEachDocumentApart(t *testing.T) { + t.Parallel() + other := "X: {discriminator: {propertyName: k}}\n" + table := bound(t, head+"components:\n schemas:\n S: {$ref: 'other.yaml#/X'}\n T: {discriminator: {propertyName: k}}\n", + reftable.Config{Self: "spec.yaml", Open: func(name, _ string) (*yaml.Node, error) { + if name != "other.yaml" { + return nil, errors.New("no such document") + } + return openapitest.YAMLDocument(t, other), nil + }}) + landed := entryAt(t, table, "/components/schemas/S") + require.Equal(t, reftable.Resolved, landed.Chain.Status) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/T/discriminator"}, + discriminatorPointers(table.Document(reftable.Source).Discriminators.Within("")), "the source's alone") + assert.Equal(t, []jsontext.Pointer{"/X/discriminator"}, + discriminatorPointers(table.Document(landed.Chain.End.Doc).Discriminators.Within("")), "the other's alone") +} + +// TestDiscriminators_AreInPointerOrderAtEveryBinding pins the order the +// search reads: each binding lists a document's discriminators by their +// pointers' bytes, whatever order the walks noted them in, so several +// bindings, which would each draw an order of their own, list them alike. +func TestDiscriminators_AreInPointerOrderAtEveryBinding(t *testing.T) { + t.Parallel() + const disc = "{discriminator: {propertyName: k}}" + src := head + "components:\n schemas:\n A: " + disc + "\n B: " + disc + "\n C: " + disc + "\n D: " + disc + + "\n E: " + disc + "\n" + want := []jsontext.Pointer{"/components/schemas/A/discriminator", "/components/schemas/B/discriminator", + "/components/schemas/C/discriminator", "/components/schemas/D/discriminator", "/components/schemas/E/discriminator"} + for range 8 { + assert.Equal(t, want, discriminatorPointers(bound(t, src, self).Document(reftable.Source).Discriminators)) + } +} diff --git a/compilers/openapi/internal/reftable/documents.go b/compilers/openapi/internal/reftable/documents.go index 30ca9ffe9..c579e1e53 100644 --- a/compilers/openapi/internal/reftable/documents.go +++ b/compilers/openapi/internal/reftable/documents.go @@ -80,18 +80,18 @@ type ruleKey struct { } // newDocs returns the documents of a table over the source tree root. -func newDocs(root *yaml.Node, cfg Config, workValue *work) *docs { +func newDocs(root *yaml.Node, cfg Config, work *work) *docs { src := &document{name: cfg.Self, root: nodeview.DocumentRoot(root), view: nodeview.New(), grammar: true, openapi: true} components := make(map[string]bool, len(cfg.Components)) for _, name := range cfg.Components { components[name] = true } - docsValue := &docs{cfg: cfg, list: []*document{src}, byName: map[string]DocID{cfg.Self: Source}, - failed: map[string]error{}, work: workValue, reached: map[DocID]bool{Source: true}, rules: map[ruleKey]DialectRule{}, + docs := &docs{cfg: cfg, list: []*document{src}, byName: map[string]DocID{cfg.Self: Source}, + failed: map[string]error{}, work: work, reached: map[DocID]bool{Source: true}, rules: map[ruleKey]DialectRule{}, components: components, schemes: setOf(cfg.SecuritySchemes), keyRefs: map[DocumentPointer]string{}} - src.self, src.absolute = docsValue.selfOf(src) - return docsValue + src.self, src.absolute = docs.selfOf(src) + return docs } // selfOf is the URI the $self doc's OpenAPI Object writes names, resolved @@ -107,8 +107,8 @@ func (d *docs) selfOf(doc *document) (string, bool) { if !doc.openapi || !ok || strings.Contains(written, "#") { return "", false } - if u, err := url.Parse(written); err == nil && len(u.Scheme) > 1 { - return NormalURI(u), true + if parsed, err := url.Parse(written); err == nil && len(parsed.Scheme) > 1 { + return NormalURI(parsed), true } uri, ok := resources{d}.resolveURI(written, doc.name) if !ok { @@ -142,14 +142,14 @@ func (d *docs) locate(uri, base string) (string, bool) { } // opening is the name the document uri names, written in the document named -// base, is opened under in docsValue: located (docs.locate), then put where the +// base, is opened under in docs: located (docs.locate), then put where the // caller mapped it (Config.Map). -func opening(docsValue *docs, uri, base string) (string, bool) { - name, ok := docsValue.locate(uri, base) - if !ok || docsValue.cfg.Map == nil { +func opening(docs *docs, uri, base string) (string, bool) { + name, ok := docs.locate(uri, base) + if !ok || docs.cfg.Map == nil { return name, ok } - return docsValue.cfg.Map(name), true + return docs.cfg.Map(name), true } // refusal is why Config.Refuse refuses a reference whose document part is @@ -215,9 +215,9 @@ func (d *docs) judge(name, from string) error { // askOpen asks Config.Open, which is set, for the document named name as from // reads it, a step of the work: the one call bind makes into the reader, for a // read and a judgement alike. -func askOpen(docsValue *docs, name, from string) (*yaml.Node, error) { - docsValue.work.spend(1) - return docsValue.cfg.Open(name, from) +func askOpen(docs *docs, name, from string) (*yaml.Node, error) { + docs.work.spend(1) + return docs.cfg.Open(name, from) } // reach notes that the pass under way asked for document id. @@ -272,8 +272,8 @@ func (d *docs) node(documentPointer DocumentPointer) *yaml.Node { // compare orders positions as a table reads them: the source's first, // another document's by its name, then by pointer (comparePositions). -func (d *docs) compare(documentPointer, documentPointerValue DocumentPointer) int { - return compareNamed(documentPointer, documentPointerValue, d.name) +func (d *docs) compare(documentPointer, otherDocumentPointer DocumentPointer) int { + return compareNamed(documentPointer, otherDocumentPointer, d.name) } // name returns the name of the document id names. @@ -322,7 +322,7 @@ func (d *docs) refOf(id DocID, node *yaml.Node) (string, bool) { return refNode.Value, true } -// reading is where a read of a pointer stands: the position, the node there, +// reading is where a read of a pointer is: the position, the node there, // and its place in the grammar. type reading struct { at DocumentPointer @@ -330,9 +330,9 @@ type reading struct { place } -// spelledAs is r at the pointer spelled in b. -func (r reading) spelledAs(b []byte) reading { - r.at.Pointer = jsontext.Pointer(b) +// spelledAs is r at the pointer spelled in spelling. +func (r reading) spelledAs(spelling []byte) reading { + r.at.Pointer = jsontext.Pointer(spelling) return r } diff --git a/compilers/openapi/internal/reftable/dynamic.go b/compilers/openapi/internal/reftable/dynamic.go index 57ba5de7e..4a4d24433 100644 --- a/compilers/openapi/internal/reftable/dynamic.go +++ b/compilers/openapi/internal/reftable/dynamic.go @@ -14,11 +14,12 @@ import ( ) // dynamicRefs is what a pass reads of the $dynamicRefs schemas write beside no -// $ref, which is that schema's entry where it writes one. JSON Schema 2020-12 §8.2.3.2 resolves one as a $ref, and -// reads it as dynamic only where that lands on a fragment a $dynamicAnchor -// created: named holds each verdict known so far, true for such a one, and -// spelled each position whose hop read one (ReferenceSite.Keyword). waiting is each -// site settled as a $ref while its verdict waits for a document (resettle). +// $ref, which is that schema's entry where it writes one. JSON Schema 2020-12 +// §8.2.3.2 resolves one as a $ref, and reads it as dynamic only where that +// lands on a fragment a $dynamicAnchor created: named holds each answer known +// so far, true for such a one, and spelled each position whose hop read one +// (ReferenceSite.Keyword). waiting is each site settled as a $ref while its +// answer waits for a document (resettle). type dynamicRefs struct { named map[DocumentPointer]bool spelled map[DocumentPointer]bool @@ -32,11 +33,11 @@ func newDynamicRefs() *dynamicRefs { // dynamicRefValue is the $dynamicRef the schema node of document id writes, // read as refOf reads a $ref, and whether it writes a string one. -func dynamicRefValue(docsValue *docs, id DocID, node *yaml.Node) (string, bool) { +func dynamicRefValue(docs *docs, id DocID, node *yaml.Node) (string, bool) { if node = nodeview.Deref(node); node == nil || node.Kind != yaml.MappingNode { return "", false } - dynamicRefNode := nodeview.Deref(docsValue.list[id].view.ChildByToken(node, "$dynamicRef")) + dynamicRefNode := nodeview.Deref(docs.list[id].view.ChildByToken(node, "$dynamicRef")) if dynamicRefNode == nil || dynamicRefNode.Kind != yaml.ScalarNode || dynamicRefNode.Tag == "!!null" { return "", false } @@ -52,29 +53,29 @@ func dynamicRefValue(docsValue *docs, id DocID, node *yaml.Node) (string, bool) // the anchor: the lowering keeps those (docs/compilers/openapi.md#dynamic-ref). // known is false, and nothing kept, while its hop waits for a document not yet // read. -func namesDynamic(b *binder, documentPointer DocumentPointer, path []*yaml.Node, value string) (dynamic, known bool) { - if v, ok := b.dyn.named[documentPointer]; ok { - return v, true +func namesDynamic(binder *binder, documentPointer DocumentPointer, path []*yaml.Node, value string) (dynamic, known bool) { + if named, ok := binder.dyn.named[documentPointer]; ok { + return named, true } name := string(fragment.Pointer(value)) if name == "" || strings.HasPrefix(name, "/") { - b.dyn.named[documentPointer] = false + binder.dyn.named[documentPointer] = false return false, true } - hop := b.resolve(documentPointer, path, value, true) + hop := binder.resolve(documentPointer, path, value, true) switch { case hop.Reason == PendingExternalDocumentRead: return false, false - case b.work.over(): + case binder.work.over(): return true, true case hop.Status == Resolved: - dynamic = slices.Contains(b.ids.dynamic[dynamicKey{doc: hop.Target.Doc, name: name}], hop.Target) + dynamic = slices.Contains(binder.ids.dynamic[dynamicKey{doc: hop.Target.Doc, name: name}], hop.Target) case hop.Reason == DuplicateAnchor: - dynamic = duplicateDynamic(b, documentPointer, path, value, name) + dynamic = duplicateDynamic(binder, documentPointer, path, value, name) default: dynamic = hop.Reason == MergeBound } - b.dyn.named[documentPointer] = dynamic + binder.dyn.named[documentPointer] = dynamic return dynamic, true } @@ -84,12 +85,12 @@ func namesDynamic(b *binder, documentPointer DocumentPointer, path []*yaml.Node, // resource's own, as resolve read them, and no other resource's of its // document. A resource it cannot name again, which resolve named, reads as // dynamic. -func duplicateDynamic(b *binder, documentPointer DocumentPointer, path []*yaml.Node, value, name string) bool { - in, known := b.resources.holding(documentPointer, path, true, b.ids.readsDialects(documentPointer.Doc)) +func duplicateDynamic(binder *binder, documentPointer DocumentPointer, path []*yaml.Node, value, name string) bool { + in, known := binder.resources.holding(documentPointer, path, true, binder.ids.readsDialects(documentPointer.Doc)) uri, _, _ := strings.Cut(value, "#") - to, reason, _ := b.named(in, uri) - dynamic := b.ids.dynamic[dynamicKey{doc: to.root.Doc, name: name}] - return !known || reason != NoReason || slices.ContainsFunc(b.ids.anchors[anchorKey{root: to.root, name: name}], + to, reason, _ := binder.named(in, uri) + dynamic := binder.ids.dynamic[dynamicKey{doc: to.root.Doc, name: name}] + return !known || reason != NoReason || slices.ContainsFunc(binder.ids.anchors[anchorKey{root: to.root, name: name}], func(at DocumentPointer) bool { return slices.Contains(dynamic, at) }) } @@ -98,56 +99,56 @@ func duplicateDynamic(b *binder, documentPointer DocumentPointer, path []*yaml.N // read, among the sites to settle, as a $ref written there would be. The // dynamic ones, and those beside a $ref, are left to land (landDynamic). A // binding its context stopped reads none further. -func staticSites(b *binder) { - dynamic := b.find.freshDynamic[:0] - for _, dynamicSite := range b.find.freshDynamic { - if b.work.cancelled() { +func staticSites(binder *binder) { + dynamic := binder.find.freshDynamic[:0] + for _, dynamicSite := range binder.find.freshDynamic { + if binder.work.cancelled() { break } if dynamicSite.beside { dynamic = append(dynamic, dynamicSite) continue } - path, _ := b.docs.path(dynamicSite.at) - named, known := namesDynamic(b, dynamicSite.at, path, dynamicSite.value) + path, _ := binder.docs.path(dynamicSite.at) + named, known := namesDynamic(binder, dynamicSite.at, path, dynamicSite.value) if named { dynamic = append(dynamic, dynamicSite) continue } if !known { - b.dyn.waiting[dynamicSite.at] = dynamicSite.value + binder.dyn.waiting[dynamicSite.at] = dynamicSite.value } - if !b.find.sites[dynamicSite.at] { - b.find.sites[dynamicSite.at] = true - b.find.fresh = append(b.find.fresh, dynamicSite.at) + if !binder.find.sites[dynamicSite.at] { + binder.find.sites[dynamicSite.at] = true + binder.find.fresh = append(binder.find.fresh, dynamicSite.at) } } - b.find.freshDynamic = dynamic + binder.find.freshDynamic = dynamic } // resettle reports whether site, settled as a $ref while its $dynamicRef's -// verdict waited for a document, is dynamic now that verdict is known, and +// answer waited for a document, is dynamic now that answer is known, and // leaves it to land (landDynamic) where it is: it has no entry. -func resettle(b *binder, site DocumentPointer) bool { - value, waited := b.dyn.waiting[site] +func resettle(binder *binder, site DocumentPointer) bool { + value, waited := binder.dyn.waiting[site] if !waited { return false } - path, _ := b.docs.path(site) - named, known := namesDynamic(b, site, path, value) + path, _ := binder.docs.path(site) + named, known := namesDynamic(binder, site, path, value) if known { - delete(b.dyn.waiting, site) + delete(binder.dyn.waiting, site) } if named { - b.find.freshDynamic = append(b.find.freshDynamic, dynamicSite{at: site, value: value}) + binder.find.freshDynamic = append(binder.find.freshDynamic, dynamicSite{at: site, value: value}) } return named } // keywordAt is the keyword the reference whose hop the pass read at // documentPointer is written under. -func keywordAt(b *binder, documentPointer DocumentPointer) string { - if b.dyn.spelled[documentPointer] { +func keywordAt(binder *binder, documentPointer DocumentPointer) string { + if binder.dyn.spelled[documentPointer] { return "$dynamicRef" } return "$ref" diff --git a/compilers/openapi/internal/reftable/dynamic_test.go b/compilers/openapi/internal/reftable/dynamic_test.go index 2e299d095..c284bad6f 100644 --- a/compilers/openapi/internal/reftable/dynamic_test.go +++ b/compilers/openapi/internal/reftable/dynamic_test.go @@ -66,7 +66,7 @@ func TestBind_ReadsADynamicRefAsTheRefItSpellsUnlessItNamesADynamicAnchor(t *tes assert.Equal(t, documentPointer, entryAt(t, table, "/components/schemas/ByAnchor").Hop.Target) assert.Equal(t, reftable.DuplicateAnchor, entryAt(t, table, "/components/schemas/Twinned").Hop.Reason) for _, name := range []string{"Dynamic", "Duplicated", "Mixed", "Null", "Listed"} { - _, ok := table.Entry(documentPointerAt(jsontext.Pointer("/components/schemas/" + name))) + _, ok := table.ReferenceSiteAt(documentPointerAt(jsontext.Pointer("/components/schemas/" + name))) assert.False(t, ok, "%s is no $ref site", name) } for _, name := range []string{"Beside", "BesidePointer"} { @@ -74,7 +74,7 @@ func TestBind_ReadsADynamicRefAsTheRefItSpellsUnlessItNamesADynamicAnchor(t *tes assert.Equal(t, "$ref", referenceSite.Keyword, "%s: the $ref beside it is the entry", name) assert.Equal(t, documentPointer, referenceSite.Hop.Target, name) } - _, ok := (*reftable.ReferenceTargetTable)(nil).Entry(documentPointer) + _, ok := (*reftable.ReferenceTargetTable)(nil).ReferenceSiteAt(documentPointer) assert.False(t, ok, "a nil table read none") toDynamic := entryAt(t, table, "/components/schemas/ToDynamic") @@ -91,12 +91,12 @@ func TestBind_ReadsADynamicRefIntoAnotherDocumentOnceItIsRead(t *testing.T) { t.Parallel() const src = head + "components:\n schemas:\n S: {$ref: '#/components/schemas/A'}\n" + " A: {$dynamicRef: 'o.yaml#n'}\n" - a := documentPointerAt("/components/schemas/A") + documentPointer := documentPointerAt("/components/schemas/A") dynamic := bound(t, src, withDocuments(map[string]string{"o.yaml": "T: {$dynamicAnchor: n}\n"})) - _, ok := dynamic.Entry(a) + _, ok := dynamic.ReferenceSiteAt(documentPointer) assert.False(t, ok, "it lands on a $dynamicAnchor of its name") - assert.Equal(t, reftable.Chain{End: a, Hops: 1, Status: reftable.Resolved}, entryAt(t, dynamic, "/components/schemas/S").Chain) + assert.Equal(t, reftable.Chain{End: documentPointer, Hops: 1, Status: reftable.Resolved}, entryAt(t, dynamic, "/components/schemas/S").Chain) static := bound(t, src, withDocuments(map[string]string{"o.yaml": "T: {$anchor: n}\n"})) referenceSite := entryAt(t, static, "/components/schemas/A") @@ -114,7 +114,7 @@ func TestBind_ReadsADynamicRefIntoAnotherDocumentOnceItIsRead(t *testing.T) { func TestBind_ReadsADynamicRefAMergeMayHideTheAnchorOfAsDynamic(t *testing.T) { t.Parallel() const ref = " D: {$dynamicRef: '#n'}\n" - _, ok := bound(t, deepMerge()+ref, self).Entry(documentPointerAt("/components/schemas/D")) + _, ok := bound(t, deepMerge()+ref, self).ReferenceSiteAt(documentPointerAt("/components/schemas/D")) assert.False(t, ok) assert.Equal(t, "$dynamicRef", entryAt(t, bound(t, head+"components:\n schemas:\n"+ref, self), "/components/schemas/D").Keyword) @@ -129,13 +129,13 @@ func TestBind_ADynamicRefTheBudgetCutsIsNoOtherEntry(t *testing.T) { full := bound(t, dynamicSpec, self) require.False(t, full.Exhausted()) want := map[reftable.DocumentPointer]reftable.ReferenceSite{} - for _, referenceSite := range full.Entries() { + for _, referenceSite := range full.ReferenceSites() { want[referenceSite.Site] = referenceSite } for limit := 1; limit < full.Steps(); limit++ { cfg := self cfg.Limit = budget.AtMost(limit) - for _, referenceSite := range bound(t, dynamicSpec, cfg).Entries() { + for _, referenceSite := range bound(t, dynamicSpec, cfg).ReferenceSites() { whole, ok := want[referenceSite.Site] require.True(t, ok, "limit %d: %s holds no entry read whole", limit, referenceSite.Site.Pointer) if referenceSite.Hop.Status != reftable.OverBudget && referenceSite.Chain.Status != reftable.OverBudget { diff --git a/compilers/openapi/internal/reftable/export_test.go b/compilers/openapi/internal/reftable/export_test.go index 923d8655c..73e4c3f33 100644 --- a/compilers/openapi/internal/reftable/export_test.go +++ b/compilers/openapi/internal/reftable/export_test.go @@ -22,7 +22,7 @@ const MaxPointerTokens = maxPointerTokens // tests read, to try every limit short of it. func (t *ReferenceTargetTable) Steps() int { return t.steps } -// Passes reports how many passes the table was read in, the last standing, +// Passes reports how many passes the table was read in, the last one left, // which only this package's external tests read. func (t *ReferenceTargetTable) Passes() int { return t.passes } diff --git a/compilers/openapi/internal/reftable/grammar.go b/compilers/openapi/internal/reftable/grammar.go index a7f6737b0..6b28c31d2 100644 --- a/compilers/openapi/internal/reftable/grammar.go +++ b/compilers/openapi/internal/reftable/grammar.go @@ -11,12 +11,12 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/specrules" ) -// state is where the OpenAPI grammar stands after reading a pointer's tokens. +// state is where the OpenAPI grammar is after reading a pointer's tokens. type state uint8 const ( sRaw state = iota - sValue + s sDocument sComponents sSchemaMap @@ -82,7 +82,7 @@ func withSchema(objects map[state]map[string]state) map[state]map[string]state { // one, so the lowering keeps each verbatim. place.below is its one reader. var unheld = map[state]map[string]bool{sEncoding: {"encoding": true, "prefixEncoding": true, "itemEncoding": true}} -// place is where a read stands in the grammar: the state it reads a position +// place is where a read is in the grammar: the state it reads a position // at, and whether a token it read since it began, or since the last reference // it passed, named a field whose content no model holds (unheld). Beneath one a // schema is raw YAML to the model, as one under an extension is @@ -129,22 +129,22 @@ func (p place) held() bool { return modelled(p.state) && !p.beneath } // reads: a schema, a map or list of them, a literal kept raw, a list of // literals, or a value. func schemaFields() map[string]state { - m := map[string]state{} + transitions := map[string]state{} for _, k := range []string{"not", "if", "then", "else", "additionalProperties", "items", "contains", "propertyNames", "unevaluatedItems", "unevaluatedProperties", "contentSchema"} { - m[k] = sSchema + transitions[k] = sSchema } for _, k := range []string{"properties", "patternProperties", "dependentSchemas", "$defs"} { - m[k] = sSchemaMap + transitions[k] = sSchemaMap } for _, k := range []string{"allOf", "anyOf", "oneOf", "prefixItems"} { - m[k] = sSchemaList + transitions[k] = sSchemaList } for _, k := range []string{"example", "default", "const"} { - m[k] = sRaw + transitions[k] = sRaw } for _, k := range []string{"enum", "examples"} { - m[k] = sRawEntries + transitions[k] = sRawEntries } for _, k := range []string{"$ref", "$id", "$schema", "$anchor", "type", "title", "description", "format", "multipleOf", "maximum", "minimum", "exclusiveMaximum", "exclusiveMinimum", "maxLength", "minLength", @@ -153,9 +153,9 @@ func schemaFields() map[string]state { "deprecated", "discriminator", "xml", "externalDocs", "$vocabulary", "dependentRequired"} { // The rule table judges such a value entry by entry and places a finding // at each it refuses, so NamedPointerBytes names it node by node. - m[k] = sValue + transitions[k] = s } - return m + return transitions } // entries maps a container state to the state of each of its entries. @@ -188,7 +188,7 @@ var entries = map[state]state{ var extensible = map[state]bool{sPaths: true, sResponses: true, sCallback: true} // refKinds holds the states of the objects modelled as a Reference Object when -// they write a $ref, each with the kind of object the reference stands for: the +// they write a $ref, each with the kind of object the reference names: the // parser's own kinds, and a Media Type Object, which the load phase models // (GitHub #856). A pointer read through one reads on in the object its chain // ends on (binder.through). @@ -206,23 +206,23 @@ var refStates = []state{sPathItem, sParameter, sHeader, sRequestBody, sResponse, // state is the state an object of kind k is read at. func (k RefKind) state() state { return refStates[k-1] } -// step is the state one token below stateValue. -func step(stateValue state, token string) state { - switch stateValue { +// step is the state one token below from. +func step(from state, token string) state { + switch from { case sRaw: return sRaw - case sValue, sObject: - return sValue + case s, sObject: + return s case sLoose: return looseStep(token) } - if state, ok := entries[stateValue]; ok { - if strings.HasPrefix(token, "x-") && extensible[stateValue] { + if state, ok := entries[from]; ok { + if strings.HasPrefix(token, "x-") && extensible[from] { return sRaw } return state } - if next, ok := fields[stateValue][token]; ok { + if next, ok := fields[from][token]; ok { return next } return sRaw @@ -243,17 +243,17 @@ func looseStep(token string) state { return sLoose } -// stateOf is the state tokens reach from stateValue. -func stateOf(stateValue state, tokens []string) state { +// stateOf is the state tokens reach from state. +func stateOf(state state, tokens []string) state { for _, t := range tokens { - stateValue = step(stateValue, t) + state = step(state, t) } - return stateValue + return state } -// roleOf is the role a position read at state stateValue has. -func roleOf(stateValue state) Role { - switch stateValue { +// roleOf is the role a position read at state state has. +func roleOf(state state) Role { + switch state { case sSchema: return Schema case sRaw: @@ -263,10 +263,10 @@ func roleOf(stateValue state) Role { } } -// modelled reports whether the model holds a position read at stateValue as an +// modelled reports whether the model holds a position read at state as an // object or a list of its own, rather than as raw YAML or a scalar value. -func modelled(stateValue state) bool { - return stateValue != sRaw && stateValue != sValue +func modelled(state state) bool { + return state != sRaw && state != s } // DefinitionsCeiling returns the shallowest ancestor pointer of at in at.Doc @@ -351,6 +351,6 @@ func dialectSchemaStep(token string, afterItems bool) (state, bool) { // isArrayIndex reports whether token spells a non-negative base-10 integer. func isArrayIndex(token string) bool { - n, err := strconv.Atoi(token) - return err == nil && n >= 0 + index, err := strconv.Atoi(token) + return err == nil && index >= 0 } diff --git a/compilers/openapi/internal/reftable/grammar_internal_test.go b/compilers/openapi/internal/reftable/grammar_internal_test.go index 1fec2ffd6..29077d5fc 100644 --- a/compilers/openapi/internal/reftable/grammar_internal_test.go +++ b/compilers/openapi/internal/reftable/grammar_internal_test.go @@ -56,26 +56,26 @@ var lags = map[state][]string{ // of lags is one the model names, so a release adding one fails here. func TestGrammar_FieldsAreTheModels(t *testing.T) { t.Parallel() - for model, stateValue := range modelStates { + for model, expected := range modelStates { want := map[string]state{} for f := range model.Fields() { if key := f.Tag.Get("key"); key != "" && key != "extensions" && key != "$ref" { want[key] = modelState(t, f.Type) } } - if state, isContainer := entries[stateValue]; isContainer { + if state, isContainer := entries[expected]; isContainer { for key, ws := range want { assert.Equal(t, class(ws), class(state), "%s.%s is read as an entry", model.Name(), key) } continue } - got := maps.Clone(fields[stateValue]) + got := maps.Clone(fields[expected]) delete(got, "$ref") - for _, lag := range lags[stateValue] { + for _, lag := range lags[expected] { assert.NotContains(t, want, lag, "%s.%s is a field the model names", model.Name(), lag) delete(got, lag) } - if stateValue == sPathItem { + if expected == sPathItem { for key, ks := range got { if ks == sOperation { assert.True(t, soa.IsStandardMethod(key), "%s is no method the model reads", key) @@ -119,11 +119,11 @@ func TestGrammar_ReadsAnExtensionWhereTheModelDoes(t *testing.T) { // class is what a state means to a reading: a value and an object other than // the model's kinds are alike, since neither holds a schema or raw YAML. -func class(stateValue state) state { - if stateValue == sObject || stateValue == sSecurityList { - return sValue +func class(state state) state { + if state == sObject || state == sSecurityList { + return s } - return stateValue + return state } // modelState is the state the model reads a field of type ft at. @@ -144,7 +144,7 @@ func modelState(t *testing.T, ft reflect.Type) state { if strings.Contains(name, "oas3/core.Schema") { return sSchema } - return sValue + return s case strings.HasPrefix(name, "core.Reference["): o, _ := ft.FieldByName("Object") return modelState(t, o.Type) @@ -157,7 +157,7 @@ func modelState(t *testing.T, ft reflect.Type) state { case ft == reflect.TypeFor[yaml.Node](): return sRaw default: - return sValue + return s } } @@ -167,7 +167,7 @@ func modelContainer(in map[state]state, holds state) state { if state, ok := in[holds]; ok { return state } - return sValue + return s } // loadModels holds the fields of lags the load phase models in the parser's @@ -223,9 +223,9 @@ func TestPlace_ReadsBeneathAFieldNoModelHoldsAsRaw(t *testing.T) { {encoding + "headers/H", Object, true}, } for _, tc := range tests { - placeValue := place{state: sDocument}.along(strings.Split(tc.pointer, "/")) - assert.Equal(t, tc.role, placeValue.role(), tc.pointer) - assert.Equal(t, tc.held, placeValue.held(), tc.pointer) + place := place{state: sDocument}.along(strings.Split(tc.pointer, "/")) + assert.Equal(t, tc.role, place.role(), tc.pointer) + assert.Equal(t, tc.held, place.held(), tc.pointer) } past := place{state: sDocument}.along(strings.Split(encoding+"encoding/g/headers/H", "/")) fresh := place{state: past.state}.along([]string{"schema"}) diff --git a/compilers/openapi/internal/reftable/held_reads_test.go b/compilers/openapi/internal/reftable/held_reads_test.go index 54ae3541b..4e08825db 100644 --- a/compilers/openapi/internal/reftable/held_reads_test.go +++ b/compilers/openapi/internal/reftable/held_reads_test.go @@ -61,12 +61,12 @@ func (l *askLog) names() []string { // d(K+1) and whose q names f(K+1). base prefixes each name ("" for paths, a // URL's origin for URLs). It returns the source and the documents by the name // a reference to them resolves to under prefix. -func ladder(n int, base string) (src string, docs map[string]string) { +func ladder(count int, base string) (src string, docs map[string]string) { docs = map[string]string{} src = head + "components:\n schemas:\n A: {$ref: 'f1.yaml'}\n B: {$ref: 'd1.yaml#/T'}\n" - for k := 1; k <= n; k++ { + for k := 1; k <= count; k++ { var body string - if k < n { + if k < count { body = fmt.Sprintf("T: {type: string}\nS: {$id: 'f%d.yaml', properties: {p: {$ref: 'd%d.yaml#/T'}, q: {$ref: 'f%d.yaml'}}}\n", k, k+1, k+1) } else { body = fmt.Sprintf("T: {type: string}\nS: {$id: 'f%d.yaml', type: string}\n", k) @@ -78,9 +78,9 @@ func ladder(n int, base string) (src string, docs map[string]string) { // laddered binds ladder(n, base) as the source named self reads it, through // log. -func laddered(t *testing.T, n int, base string, log *askLog) *reftable.ReferenceTargetTable { +func laddered(t *testing.T, count int, base string, log *askLog) *reftable.ReferenceTargetTable { t.Helper() - src, docs := ladder(n, base) + src, docs := ladder(count, base) cfg := resolving cfg.Self = base + "spec.yaml" if base == "" { @@ -116,13 +116,13 @@ func assertLinear(t *testing.T, label string, steps func(n int) int, sizes ...in // resolving, in n+1 documents. func TestBind_AChainOfDeclaringDocumentsCostsWorkLinearInItsLength(t *testing.T) { t.Parallel() - steps := func(n int) int { return laddered(t, n, "", &askLog{}).Steps() } + steps := func(count int) int { return laddered(t, count, "", &askLog{}).Steps() } assertLinear(t, "paths", steps, 50, 100, 200) assertLinear(t, "paths", steps, 100, 200, 400) table := laddered(t, 100, "", &askLog{}) assert.Equal(t, 101, table.Documents(), "the source and one document per rung") - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { assert.Equal(t, reftable.Resolved, referenceSite.Chain.Status, "%v", referenceSite.Site) } assert.Zero(t, table.Passes()-1, "the chain is answered in one pass, not one per link") @@ -135,12 +135,12 @@ func TestBind_AChainOfDeclaringDocumentsCostsWorkLinearInItsLength(t *testing.T) func TestBind_AChainOfDeclaringURLsCostsWorkLinearAndEachIsRequestedOnce(t *testing.T) { t.Parallel() const base = "https://x.test/" - steps := func(n int) int { return laddered(t, n, base, &askLog{}).Steps() } + steps := func(count int) int { return laddered(t, count, base, &askLog{}).Steps() } assertLinear(t, "https", steps, 50, 100, 200) var log askLog table := laddered(t, 50, base, &log) - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { assert.Equal(t, reftable.Resolved, referenceSite.Chain.Status, "%v", referenceSite.Site) } count := map[string]int{} diff --git a/compilers/openapi/internal/reftable/hop.go b/compilers/openapi/internal/reftable/hop.go index 1d016d3eb..4d908efdb 100644 --- a/compilers/openapi/internal/reftable/hop.go +++ b/compilers/openapi/internal/reftable/hop.go @@ -110,11 +110,11 @@ func (b *binder) named(in resource, uri string) (resource, Reason, string) { // names as a location, key being the URI it resolves to: read against an // $id's or a $self's base where only those name it (readAt), else where it // is written (opened). -func locatedAt(b *binder, in resource, uri, key string) (resource, Reason, string) { +func locatedAt(binder *binder, in resource, uri, key string) (resource, Reason, string) { if (in.namedByDollarID || in.based) && !fragment.Absolute(uri) { - return b.readAt(in, uri, key) + return binder.readAt(in, uri, key) } - return b.opened(in, uri, key) + return binder.opened(in, uri, key) } // opened is the resource of the document uri, written in the resource in, @@ -161,7 +161,7 @@ func (b *binder) readAt(in resource, uri, key string) (resource, Reason, string) return resource{}, Unreadable, why } name := key - if u, err := url.Parse(key); err == nil && len(u.Scheme) > 1 { + if parsed, err := url.Parse(key); err == nil && len(parsed.Scheme) > 1 { if located, ok := opening(b.docs, key, key); ok { name = located } @@ -177,11 +177,11 @@ func (b *binder) readAt(in resource, uri, key string) (resource, Reason, string) const OffNetwork = "a reference in a document read over http or https reads only http and https URLs" // reachable reports whether a reference written in the resource in, of one of -// docsValue's documents, may read the document named name: judged by the +// docs's documents, may read the document named name: judged by the // location in's document was read from, never by a URI an $id gives in, so that // no $id moves a reference in a document read over the network onto a file. -func reachable(docsValue *docs, in resource, name string) bool { - return Reachable(docsValue.name(in.root.Doc), name) +func reachable(docs *docs, in resource, name string) bool { + return Reachable(docs.name(in.root.Doc), name) } // Reachable reports whether a reference written in the document read from @@ -198,8 +198,8 @@ func Reachable(from, target string) bool { // network: an http or https URL, its scheme in any case. A file URI, a path // and a URL of any other scheme are not. func OverNetwork(location string) bool { - u, err := url.Parse(location) - return err == nil && (strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https")) + parsed, err := url.Parse(location) + return err == nil && (strings.EqualFold(parsed.Scheme, "http") || strings.EqualFold(parsed.Scheme, "https")) } // read is the resource of the document named name, read through Config.Open as @@ -247,11 +247,11 @@ func (b *binder) land(site DocumentPointer, path []*yaml.Node, to resource, ref reading, reason := b.readPointer(site.Doc, pointer) return b.defs.definition(site, path, pointer, schema, reading, reason) } - readingValue, reason := b.readPointer(to.root.Doc, to.root.Pointer+pointer) + reading, reason := b.readPointer(to.root.Doc, to.root.Pointer+pointer) if reason == NoTarget && to.namedByDollarID { reason, hop.Detail = NoResourceTarget, to.uri } - return readingValue, reason + return reading, reason } // anchored reads the schema the resource to declares the plain name name in, as @@ -288,18 +288,18 @@ func (b *binder) hop(documentPointer DocumentPointer) Hop { ref, _ = dynamicRefValue(b.docs, documentPointer.Doc, path[len(path)-1]) b.dyn.spelled[documentPointer] = true } - hopValue := b.resolve(documentPointer, path, ref, true) + hop := b.resolve(documentPointer, path, ref, true) if b.work.over() { - hopValue = Hop{Ref: ref, Status: OverBudget} + hop = Hop{Ref: ref, Status: OverBudget} } - b.hops[documentPointer] = hopValue - if hopValue.Status == Resolved { - b.find.landed(hopValue) + b.hops[documentPointer] = hop + if hop.Status == Resolved { + b.find.landed(hop) } - if hopValue.Reason == PendingExternalDocumentRead { + if hop.Reason == PendingExternalDocumentRead { b.wait.held = append(b.wait.held, documentPointer) } - return hopValue + return hop } // DynamicFragment returns the anchor name a $dynamicRef written as ref @@ -323,15 +323,15 @@ func DynamicFragment(ref string) (name, why string, ok bool) { return name, "", true } -// anchorNamed reports whether s is a name the anchor keyword can declare in a +// anchorNamed reports whether text is a name the anchor keyword can declare in a // schema read as rule says: by the plain-name grammar for `$anchor` where the // dialect gives it that grammar (DialectRule.PlainNames), as 2019-09 does; by // 2020-12's for any other, as for `$dynamicAnchor`, which 2020-12 added, and // for an `$anchor` in a draft defining none, read as 2020-12 reads it. An // identifier's name is fragmentName's. -func anchorNamed(rule DialectRule, keyword, s string) bool { +func anchorNamed(rule DialectRule, keyword, text string) bool { if keyword == "$anchor" && rule.PlainNames { - return specrules.ValidFormat(specrules.PlainName, s) + return specrules.ValidFormat(specrules.PlainName, text) } - return specrules.ValidFormat(specrules.AnchorName, s) + return specrules.ValidFormat(specrules.AnchorName, text) } diff --git a/compilers/openapi/internal/reftable/identifiers_test.go b/compilers/openapi/internal/reftable/identifiers_test.go index ae67b3957..40ab40f07 100644 --- a/compilers/openapi/internal/reftable/identifiers_test.go +++ b/compilers/openapi/internal/reftable/identifiers_test.go @@ -116,7 +116,7 @@ func TestBind_ReadsBelowAnIDOfAnotherDocument(t *testing.T) { withDocuments(map[string]string{"o.yaml": other})) doc := docNamed(t, table, "o.yaml") for _, site := range []jsontext.Pointer{"/Pet/properties/a", "/Pet/properties/b"} { - referenceSite, ok := table.Entry(reftable.DocumentPointer{Doc: doc, Pointer: site}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: doc, Pointer: site}) require.True(t, ok, site) require.Equal(t, reftable.Resolved, referenceSite.Hop.Status, referenceSite.Hop.Why()) assert.Equal(t, reftable.DocumentPointer{Doc: doc, Pointer: "/Pet/$defs/Tag"}, referenceSite.Hop.Target) @@ -134,10 +134,10 @@ func TestBind_AnIDNamingItsDocumentReturnsToIt(t *testing.T) { table := bound(t, head+"components:\n schemas:\n A: {$ref: 'https://x.test/o.yaml#a'}\n"+ " B: {$ref: 'https://x.test/outer#a'}\n", withDocuments(map[string]string{"https://x.test/o.yaml": other})) - a := entryAt(t, table, "/components/schemas/A") - require.Equal(t, reftable.Resolved, a.Hop.Status, a.Hop.Why()) + entry := entryAt(t, table, "/components/schemas/A") + require.Equal(t, reftable.Resolved, entry.Hop.Status, entry.Hop.Why()) doc := docNamed(t, table, "https://x.test/o.yaml") - assert.Equal(t, reftable.DocumentPointer{Doc: doc, Pointer: "/Outer/properties/back/properties/leaf"}, a.Hop.Target) + assert.Equal(t, reftable.DocumentPointer{Doc: doc, Pointer: "/Outer/properties/back/properties/leaf"}, entry.Hop.Target) assert.Equal(t, reftable.NoAnchor, entryAt(t, table, "/components/schemas/B").Hop.Reason) } @@ -156,7 +156,7 @@ func TestBind_AnIdentifierIsNoLocationToFetch(t *testing.T) { cfg, reads := recordingDocuments(t, map[string]string{"o.yaml": declaring}) table := bound(t, head+"components:\n schemas:\n"+schemas, cfg) assert.Equal(t, []string{"o.yaml"}, *reads, "an identifier is never read as a location") - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { assert.Equal(t, reftable.Resolved, referenceSite.Hop.Status, referenceSite.Hop.Why()) } } @@ -170,7 +170,7 @@ func TestBind_AnIdentifierIsNoLocationToFetch(t *testing.T) { // TestBind_AHeldDocumentMayDeclareAnothersURI pins documents held together: // both are read, as neither is read before the other, the URI one of them // declares names its schema, and the other, read for nothing, is reached by no -// pass that stands, in either declaration order. +// pass that remains, in either declaration order. func TestBind_AHeldDocumentMayDeclareAnothersURI(t *testing.T) { t.Parallel() docs := map[string]string{ @@ -205,10 +205,10 @@ func TestBind_ARefusedURIADocumentDeclaresIsAnIdentifier(t *testing.T) { assert.Equal(t, reftable.Resolved, entryAt(t, table, "/components/schemas/A").Hop.Status) } -// TestBind_ALocationADocumentDeclaresIsThatIdentifier pins the pass that does not -// stand: a reference answered as a location, read before a document declaring -// that URI, is answered again as the identifier, and the document the first -// answer read holds nothing the table does, so it is marked unreached. +// TestBind_ALocationADocumentDeclaresIsThatIdentifier pins the pass that does +// not remain: a reference answered as a location, read before a document +// declaring that URI, is answered again as the identifier, and the document the +// first answer read holds nothing the table does, so it is marked unreached. func TestBind_ALocationADocumentDeclaresIsThatIdentifier(t *testing.T) { t.Parallel() docs := map[string]string{ @@ -252,7 +252,7 @@ func TestBind_TheSourceDeclaresOnceWhateverThePasses(t *testing.T) { // TestBind_ADocumentNoPassReachesDeclaresNothing pins the document a pass read // as a location before another declared that URI. Once no pass reaches it, what // it declares answers for nothing, so a URI it and a reached document declare -// names the reached one's, and its merge past the bound is no verdict of the +// names the reached one's, and its merge past the bound is no answer of the // table, in either order. func TestBind_ADocumentNoPassReachesDeclaresNothing(t *testing.T) { t.Parallel() @@ -378,7 +378,7 @@ func TestBind_DeclarationOrderReachesNoAnswer(t *testing.T) { cfg := resolving cfg.Open = func(name, _ string) (*yaml.Node, error) { return openapitest.YAMLDocument(t, docs[name]), nil } table := bound(t, src, cfg) - entries := table.Entries() + entries := table.ReferenceSites() got := make([]reftable.Status, 0, len(entries)) for _, referenceSite := range entries { got = append(got, referenceSite.Hop.Status) @@ -418,7 +418,7 @@ func TestBind_LandsOnTheAnchorAnotherDocumentsDynamicRefNames(t *testing.T) { assert.Equal(t, reftable.DocumentPointer{Doc: doc, Pointer: "/E"}, landing.Site) } } - referenceSite, ok := table.Entry(reftable.DocumentPointer{Doc: doc, Pointer: "/T/properties/p"}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: doc, Pointer: "/T/properties/p"}) require.True(t, ok, "what the anchor's schema holds is read") assert.Equal(t, reftable.Resolved, referenceSite.Hop.Status, referenceSite.Hop.Why()) @@ -455,7 +455,7 @@ func TestDynamicAnchor_CountsWhatADocumentDeclares(t *testing.T) { []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}}, {"a merge key does too", " A: &a {$dynamicAnchor: t}\n B: {<<: *a, description: d}\n", []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}}, - {"an explicit key beats the merged one", " A: &a {$dynamicAnchor: t}\n B: {<<: *a, $dynamicAnchor: o}\n", + {"an explicit key takes precedence over the merged one", " A: &a {$dynamicAnchor: t}\n B: {<<: *a, $dynamicAnchor: o}\n", []jsontext.Pointer{"/components/schemas/A"}}, {"a key written twice declares its last", " A: {$dynamicAnchor: o, $dynamicAnchor: t}\n", []jsontext.Pointer{"/components/schemas/A"}}, @@ -534,12 +534,12 @@ func TestDynamicAnchor_SaysWhenTheCountProvesNothing(t *testing.T) { assert.Equal(t, reftable.DynamicAnchor{Complete: true}, none.DynamicAnchor(reftable.Source, "t")) } -// TestResource_NamesTheRootOfAPositionsResource pins what stands in for a walk -// of every key on the way down: only a schema's $id starts a resource, so a -// property named $id does not, raw YAML above a position does not, and an $id +// TestResource_NamesTheRootOfAPositionsResource pins what takes the place of a +// walk of every key on the way down: only a schema's $id starts a resource, so +// a property named $id does not, raw YAML above a position does not, and an $id // restating its document's does not, in the source and in a document of schemas -// alike. The position's own $id counts wherever it is, as one a $ref lands on is -// read as a schema. +// alike. The position's own $id counts wherever it is, as one a $ref lands on +// is read as a schema. func TestResource_NamesTheRootOfAPositionsResource(t *testing.T) { t.Parallel() table := resourcesTable(t) diff --git a/compilers/openapi/internal/reftable/kinds.go b/compilers/openapi/internal/reftable/kinds.go index 86ac729cf..dd8b92fcc 100644 --- a/compilers/openapi/internal/reftable/kinds.go +++ b/compilers/openapi/internal/reftable/kinds.go @@ -41,10 +41,10 @@ const ( KindEncoding ) -// kindOf is the Kind of a position read at stateValue. -func kindOf(stateValue state) Kind { - switch stateValue { - case sRaw, sValue: +// kindOf is the Kind of a position read at state. +func kindOf(state state) Kind { + switch state { + case sRaw, s: return KindRaw case sComponents: return KindComponents @@ -80,7 +80,7 @@ func kindOf(stateValue state) Kind { // kinds, the lesser counts, so the answer depends on no reading order. func (t *ReferenceTargetTable) Kinds(documentPointer DocumentPointer) []Kind { var out []Kind - statesTo(t.roots, documentPointer, func(stateValue state) { out = append(out, kindOf(stateValue)) }) + statesTo(t.roots, documentPointer, func(state state) { out = append(out, kindOf(state)) }) return out } @@ -99,7 +99,7 @@ func (t *ReferenceTargetTable) ReadingAt(documentPointer DocumentPointer) Readin return Reading{} } var reading Reading - if !statesTo(t.roots, documentPointer, func(stateValue state) { reading = Reading{p: place{state: stateValue}} }) { + if !statesTo(t.roots, documentPointer, func(state state) { reading = Reading{p: place{state: state}} }) { return Reading{} } return reading @@ -116,7 +116,7 @@ func (r Reading) Below(token string) Reading { return Reading{p: r.p.below(token func (r Reading) Schema() bool { return r.p.role() == Schema } // Referable reports whether r reads an object the model holds that a reference -// object can stand for, so a $ref written there names an object of that kind. +// object can name, so a $ref written there names an object of that kind. func (r Reading) Referable() bool { _, ok := refKinds[r.p.state] return ok && r.p.held() @@ -128,12 +128,12 @@ func (r Reading) Referable() bool { // read every token of documentPointer's pointer rather than stopping at // maxPointerTokens. func statesTo(roots map[DocumentPointer]state, documentPointer DocumentPointer, visit func(state)) bool { - stateValue := sRaw + state := sRaw if documentPointer.Doc == Source { - stateValue = sDocument + state = sDocument } - stateValue = rooted(roots, DocumentPointer{Doc: documentPointer.Doc}, stateValue) - visit(stateValue) + state = rooted(roots, DocumentPointer{Doc: documentPointer.Doc}, state) + visit(state) pointer := string(documentPointer.Pointer) i := 0 for tokens := 0; i < len(pointer) && tokens < maxPointerTokens; tokens++ { @@ -144,22 +144,22 @@ func statesTo(roots map[DocumentPointer]state, documentPointer DocumentPointer, end += i + 1 } token := jsontext.Pointer(pointer[i:end]).LastToken() - stateValue = rooted(roots, DocumentPointer{Doc: documentPointer.Doc, Pointer: jsontext.Pointer(pointer[:end])}, step(stateValue, token)) - visit(stateValue) + state = rooted(roots, DocumentPointer{Doc: documentPointer.Doc, Pointer: jsontext.Pointer(pointer[:end])}, step(state, token)) + visit(state) i = end } return i >= len(pointer) } -// rooted returns stateValue, the state the grammar reads at, or, where that is +// rooted returns state, the state the grammar reads at, or, where that is // raw YAML, the state a reference read at as a root of its own, where roots // records one. -func rooted(roots map[DocumentPointer]state, at DocumentPointer, stateValue state) state { - if stateValue != sRaw { - return stateValue +func rooted(roots map[DocumentPointer]state, at DocumentPointer, state state) state { + if state != sRaw { + return state } if state, ok := roots[at]; ok { return state } - return stateValue + return state } diff --git a/compilers/openapi/internal/reftable/kinds_test.go b/compilers/openapi/internal/reftable/kinds_test.go index 657feae80..67f1c6763 100644 --- a/compilers/openapi/internal/reftable/kinds_test.go +++ b/compilers/openapi/internal/reftable/kinds_test.go @@ -144,7 +144,7 @@ func TestKinds_StopsAtTheTokenCap(t *testing.T) { // TestReadingAt_ReadsWhatKindsReadsLast pins a Reading against Kinds: the // position Kinds ends at is a schema exactly where ReadingAt reads one, and -// can stand for a reference object exactly where ReadingAt reads that, in the +// can name a reference object exactly where ReadingAt reads that, in the // source and in a document only a reference reads. func TestReadingAt_ReadsWhatKindsReadsLast(t *testing.T) { t.Parallel() diff --git a/compilers/openapi/internal/reftable/named.go b/compilers/openapi/internal/reftable/named.go index 8e445f024..f550162d6 100644 --- a/compilers/openapi/internal/reftable/named.go +++ b/compilers/openapi/internal/reftable/named.go @@ -31,36 +31,36 @@ import ( // alone: TestNamedPointerBytes_TotalsWhatATablesWalksSpell the binder's, // e2e's TestCompile_SpellsNoPointerTheNamedTotalLeavesOut a compile's. func NamedPointerBytes(ctx context.Context, root *yaml.Node, maxSteps int) (bytes int, complete bool) { - namedValue := named{memo: map[namedKey]namedShape{}, steps: budget.New(budget.AtMost(maxSteps)), + named := named{memo: map[namedKey]namedShape{}, steps: budget.New(budget.AtMost(maxSteps)), view: nodeview.New(), root: nodeview.DocumentRoot(root), complete: true} - if namedValue.root == nil { + if named.root == nil { return 0, true } - namedValue.components, namedValue.schemes = namedValue.declared("schemas"), namedValue.declared("securitySchemes") - version, _ := scalarText(namedValue.view.ChildByToken(namedValue.root, "openapi")) - namedValue.keysByURI = specrules.Table().SecurityRules(version).NamesByURI() - total := namedValue.shapeOf(ctx, namedKey{n: namedValue.root, s: sDocument}).pointers + named.components, named.schemes = named.declared("schemas"), named.declared("securitySchemes") + version, _ := scalarText(named.view.ChildByToken(named.root, "openapi")) + named.keysByURI = specrules.Table().SecurityRules(version).NamesByURI() + total := named.shapeOf(ctx, namedKey{n: named.root, s: sDocument}).pointers landed := map[namedLanding]bool{} - for i := 0; i < len(namedValue.refs) && namedValue.complete; i++ { - target, pointer, ok := namedValue.landing(namedValue.refs[i].ref) - at := namedLanding{pointer: pointer, s: namedValue.refs[i].s} + for i := 0; i < len(named.refs) && named.complete; i++ { + target, pointer, ok := named.landing(named.refs[i].ref) + at := namedLanding{pointer: pointer, s: named.refs[i].s} if !ok || landed[at] || stateOf(sDocument, slices.Collect(pointer.Tokens())) == at.s { continue } landed[at] = true - got := namedValue.shapeOf(ctx, namedKey{n: target, s: at.s}) + got := named.shapeOf(ctx, namedKey{n: target, s: at.s}) total = sat(total, sat(got.pointers, satMul(got.nodes, pointerBytes(pointer)))) } - return total, namedValue.complete && !namedValue.view.Exhausted() + return total, named.complete && !named.view.Exhausted() } // pointerBytes is the bytes of pointer as its tokens are written. func pointerBytes(pointer jsontext.Pointer) int { - n := 0 + count := 0 for token := range pointer.Tokens() { - n = sat(n, len(token)+1) + count = sat(count, len(token)+1) } - return n + return count } // namedKey is a node read at a state of the grammar. @@ -147,43 +147,43 @@ func (w *named) shapeOf(ctx context.Context, top namedKey) namedShape { return w.memo[top] } -// below returns the (node, state) pairs namedKeyValue's shape is made of, and -// notes the references namedKeyValue writes. A scalar read raw holds none, so a +// below returns the (node, state) pairs at's shape is made of, and +// notes the references at writes. A scalar read raw holds none, so a // raw value costs a step for each mapping and list it holds. -func (w *named) below(namedKeyValue namedKey) []namedFrame { - node := namedKeyValue.n +func (w *named) below(at namedKey) []namedFrame { + node := at.n if node == nil { return nil } - w.noteRefs(namedKeyValue) + w.noteRefs(at) var out []namedFrame - w.eachNamedChild(node, namedKeyValue.s, func(child *yaml.Node, stateValue state, _ int) { - if stateValue == sRaw && (child == nil || child.Kind == yaml.ScalarNode) { + w.eachNamedChild(node, at.s, func(child *yaml.Node, state state, _ int) { + if state == sRaw && (child == nil || child.Kind == yaml.ScalarNode) { return } - if _, done := w.memo[namedKey{n: child, s: stateValue}]; !done { - out = append(out, namedFrame{key: namedKey{n: child, s: stateValue}}) + if _, done := w.memo[namedKey{n: child, s: state}]; !done { + out = append(out, namedFrame{key: namedKey{n: child, s: state}}) } }) return out } -// measured is namedKeyValue's shape once what it is made of is measured. A node +// measured is at's shape once what it is made of is measured. A node // read raw names what a compile names inside it and not itself, which the node // holding it adds (rawNamed). -func (w *named) measured(namedKeyValue namedKey) namedShape { - node := namedKeyValue.n +func (w *named) measured(at namedKey) namedShape { + node := at.n if node == nil { return namedShape{} } out := namedShape{nodes: 1} - if namedKeyValue.s == sRaw { + if at.s == sRaw { out = rawNamed(node) } - member := node.Kind == yaml.MappingNode && namedKeyValue.s != sRaw - w.eachNamedChild(node, namedKeyValue.s, func(child *yaml.Node, stateValue state, edge int) { - got := w.memo[namedKey{n: child, s: stateValue}] - if stateValue == sRaw && namedKeyValue.s != sRaw { + member := node.Kind == yaml.MappingNode && at.s != sRaw + w.eachNamedChild(node, at.s, func(child *yaml.Node, state state, edge int) { + got := w.memo[namedKey{n: child, s: state}] + if state == sRaw && at.s != sRaw { // A raw value's root, which a compile names alone. got.nodes = sat(got.nodes, 1) } @@ -213,59 +213,59 @@ func rawNamed(node *yaml.Node) namedShape { return out } -// eachNamedChild hands visit each child of node read at stateValue, what an +// eachNamedChild hands visit each child of node read at state, what an // alias names in its place, with the state it is read at and the bytes its step // adds to a pointer: a key or an index, and a '/'. A mapping's are its members' // values as the binder reads them (nodeview.View.MappingPairs): those a `<<` // merge key brings in among its own, which a compile names at the mapping, and // a key written twice at its last copy. -func (w *named) eachNamedChild(node *yaml.Node, stateValue state, visit func(child *yaml.Node, otherState state, edge int)) { +func (w *named) eachNamedChild(node *yaml.Node, state state, visit func(child *yaml.Node, otherState state, edge int)) { switch node.Kind { case yaml.MappingNode: for _, pair := range w.view.MappingPairs(node) { - visit(pair.Val, step(stateValue, pair.Key), len(pair.Key)+1) + visit(pair.Val, step(state, pair.Key), len(pair.Key)+1) } case yaml.SequenceNode: for i, item := range node.Content { token := strconv.Itoa(i) - visit(nodeview.Deref(item), step(stateValue, token), len(token)+1) + visit(nodeview.Deref(item), step(state, token), len(token)+1) } default: } } -// noteRefs notes what the mapping namedKeyValue reads as a reference: its $ref +// noteRefs notes what the mapping namedKey reads as a reference: its $ref // where its state reads one, and for a schema its $dynamicRef, which lands as a // $ref does or on the anchor its plain name expands to, and each value its // discriminator names a schema by (mappingValues), by its text whatever its // tag, that spells no schema component's key, which names that component where // it is declared. A Security Requirement Object's are its keys (noteKeys). -func (w *named) noteRefs(namedKeyValue namedKey) { - if namedKeyValue.n.Kind != yaml.MappingNode { +func (w *named) noteRefs(namedKey namedKey) { + if namedKey.n.Kind != yaml.MappingNode { return } - if namedKeyValue.s == sSecurityRequirement { - w.noteKeys(namedKeyValue.n) + if namedKey.s == sSecurityRequirement { + w.noteKeys(namedKey.n) return } - _, object := refKinds[namedKeyValue.s] - if namedKeyValue.s != sSchema && !object { + _, object := refKinds[namedKey.s] + if namedKey.s != sSchema && !object { return } - if ref, ok := scalarText(w.view.ChildByToken(namedKeyValue.n, "$ref")); ok { - w.refs = append(w.refs, namedRef{ref: ref, s: namedKeyValue.s}) + if ref, ok := scalarText(w.view.ChildByToken(namedKey.n, "$ref")); ok { + w.refs = append(w.refs, namedRef{ref: ref, s: namedKey.s}) } - if namedKeyValue.s != sSchema { + if namedKey.s != sSchema { return } - if ref, ok := scalarText(w.view.ChildByToken(namedKeyValue.n, "$dynamicRef")); ok { + if ref, ok := scalarText(w.view.ChildByToken(namedKey.n, "$dynamicRef")); ok { w.refs = append(w.refs, namedRef{ref: ref, s: sSchema}) } - if w.view.ChildByToken(namedKeyValue.n, "$id") != nil { + if w.view.ChildByToken(namedKey.n, "$id") != nil { w.complete = false return } - for _, node := range mappingValues(w.view, namedKeyValue.n) { + for _, node := range mappingValues(w.view, namedKey.n) { if !w.components[node.Value] { w.refs = append(w.refs, namedRef{ref: node.Value, s: sSchema}) } diff --git a/compilers/openapi/internal/reftable/named_spelled_test.go b/compilers/openapi/internal/reftable/named_spelled_test.go index 8499169ab..f76f2b228 100644 --- a/compilers/openapi/internal/reftable/named_spelled_test.go +++ b/compilers/openapi/internal/reftable/named_spelled_test.go @@ -62,31 +62,31 @@ type spelled struct { func spelledBy(t *testing.T, text string) spelled { t.Helper() doc := openapitest.YAMLDocument(t, text) - var spelledValue spelled - spelledValue.weighed, spelledValue.complete = reftable.NamedPointerBytes(t.Context(), doc, namedSteps) + var spelled spelled + spelled.weighed, spelled.complete = reftable.NamedPointerBytes(t.Context(), doc, namedSteps) table := reftable.Bind(t.Context(), doc, compileConfig(doc).Spelling(func(at reftable.DocumentPointer, member bool) { bytes := 0 for token := range at.Pointer.Tokens() { bytes += len(token) + 1 } - spelledValue.walked += bytes - spelledValue.named += bytes + spelled.walked += bytes + spelled.named += bytes if member { - spelledValue.named += bytes + spelled.named += bytes } })) require.False(t, table.Exhausted() || table.Truncated(), "the table is whole") require.Equal(t, 1, table.Passes(), "the table is read in one pass") - return spelledValue + return spelled } // landedOn returns a bringer whose n positions are raw values holding the // anchored schema, each written by mount, which returns its line and the // fragment naming the schema in it, and named by a $ref. func landedOn(name string, mount func(id, i string) (line, fragment string)) bringer { - return bringer{name: name, bring: func(id string, n int, inner string) brought { - lines, refs := make([]string, 0, n), make([]string, 0, n) - for i := range n { + return bringer{name: name, bring: func(id string, count int, inner string) brought { + lines, refs := make([]string, 0, count), make([]string, 0, count) + for i := range count { line, fragment := mount(id, strconv.Itoa(i)) lines, refs = append(lines, line+"\n"), append(refs, "{$ref: '"+fragment+"'}") } @@ -120,7 +120,7 @@ var landings = []bringer{ // write the value brought at each `@` and one member more at each `%` of the // wider document. unread marks one whose `%` no walk reads, byURI one read // only where a requirement key is a URI, and over one where the total names -// what no walk reads: what stands beside a Reference Object's $ref, and where +// what no walk reads: what sits beside a Reference Object's $ref, and where // a reference the binder refuses would land. full marks one held to every // chain (spotChains). type spot struct { @@ -129,9 +129,9 @@ type spot struct { } // fully returns spotValue held to every chain. -func fully(spotValue spot) spot { - spotValue.full = true - return spotValue +func fully(spot spot) spot { + spot.full = true + return spot } // okResponses is the responses of an operation a spot writes. @@ -169,7 +169,7 @@ func mountedSpot(name, object string, maps ...string) spot { // spots lists where a document holds what a chain of bringers brings: each // schema keyword and each object that holds a schema, values the grammar keeps // raw, objects holding no schema that a $ref or a requirement key lands on, -// one value landed on as every kind, and what stands beside a $ref. +// one value landed on as every kind, and what sits beside a $ref. var spots = []spot{ fully(schemaSpot("a schema", "{allOf: [@]%}")), schemaSpot("$defs", "{$defs: {d: @%}}"), @@ -266,7 +266,7 @@ const wideMember = ", x-wwwwwwwwwwwwwwwwwwwwwwww: {a: b}" // spotDocument writes the document of a minor holding, at each `@` of // spotValue, the leaf chain brings to broughtCopies positions by each bringer // in turn. -func spotDocument(spotValue spot, version string, chain []bringer, wide bool) string { +func spotDocument(spot spot, version string, chain []bringer, wide bool) string { var defs, mounts []string schema, more := broughtLeaf(wide), "" for depth, by := range slices.Backward(chain) { @@ -277,7 +277,7 @@ func spotDocument(spotValue spot, version string, chain []bringer, wide bool) st more = wideMember } return "openapi: " + version + "\ninfo: {title: t, version: '1'}\nx-defs: {" + strings.Join(defs, ", ") + "}\n" + - strings.Join(mounts, "") + strings.NewReplacer("@", schema, "%", more).Replace(spotValue.body) + strings.Join(mounts, "") + strings.NewReplacer("@", schema, "%", more).Replace(spot.body) } // spotChains lists the chains a spot is held to: each bringer and landing diff --git a/compilers/openapi/internal/reftable/named_test.go b/compilers/openapi/internal/reftable/named_test.go index 6251e5424..5dabbe81d 100644 --- a/compilers/openapi/internal/reftable/named_test.go +++ b/compilers/openapi/internal/reftable/named_test.go @@ -443,7 +443,7 @@ func TestNamedPointerBytes_NamesTheEntriesOfAListAndTheReferenceOfAnObject(t *te // node, an absent one names none. func TestNamedPointerBytes_NamesNothingForANodeThatIsAbsent(t *testing.T) { t.Parallel() - key := func(s string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: s} } + key := func(text string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: text} } mapping := func(content ...*yaml.Node) *yaml.Node { return &yaml.Node{Kind: yaml.MappingNode, Content: content} } schemas := func(entry *yaml.Node) *yaml.Node { return mapping(key("components"), mapping(key("schemas"), mapping(key("S"), entry))) diff --git a/compilers/openapi/internal/reftable/named_walks_test.go b/compilers/openapi/internal/reftable/named_walks_test.go index e1bc0d0c4..1bf5456cd 100644 --- a/compilers/openapi/internal/reftable/named_walks_test.go +++ b/compilers/openapi/internal/reftable/named_walks_test.go @@ -59,8 +59,8 @@ func repeating(b bringer) bringer { } // each writes item for every index below n, joined by sep. -func each(n int, sep string, item func(i string) string) string { - items := make([]string, n) +func each(count int, sep string, item func(i string) string) string { + items := make([]string, count) for i := range items { items[i] = item(strconv.Itoa(i)) } @@ -70,9 +70,9 @@ func each(n int, sep string, item func(i string) string) string { // anchored returns a bringer whose n positions are properties, each written by // use around an alias of the anchored schema, beside the anchors more adds. func anchored(name, more string, use func(alias, i string) string) bringer { - return bringer{name: name, bring: func(id string, n int, inner string) brought { + return bringer{name: name, bring: func(id string, count int, inner string) brought { defs := "a" + id + ": &a" + id + " " + inner + strings.ReplaceAll(more, "@", id) - return brought{defs: defs, schema: "{type: object, properties: {" + each(n, ", ", func(i string) string { + return brought{defs: defs, schema: "{type: object, properties: {" + each(count, ", ", func(i string) string { return strings.ReplaceAll(use("a"+id, i), "@", id) }) + "}}"} }} @@ -82,12 +82,12 @@ func anchored(name, more string, use func(alias, i string) string) bringer { // schema, each named by the reference site writes around its pointer, the // sites held as within writes them. func landed(name string, within func(sites string) string, site func(ref, i string) string) bringer { - return bringer{name: name, bring: func(id string, n int, inner string) brought { + return bringer{name: name, bring: func(id string, count int, inner string) brought { mount := func(i string) string { return "x-r" + id + "-" + i } return brought{ defs: "a" + id + ": &a" + id + " " + inner, - mounts: each(n, "", func(i string) string { return mount(i) + ": *a" + id + "\n" }), - schema: within(each(n, ", ", func(i string) string { return site("'#/"+mount(i)+"'", i) })), + mounts: each(count, "", func(i string) string { return mount(i) + ": *a" + id + "\n" }), + schema: within(each(count, ", ", func(i string) string { return site("'#/"+mount(i)+"'", i) })), } }} } @@ -102,11 +102,11 @@ var bringers = []bringer{ anchored("alias", "", func(a, i string) string { return "q" + i + ": *" + a }), anchored("merge", "", func(a, i string) string { return "q" + i + ": {<<: *" + a + "}" }), repeating(anchored("twice", "", func(a, i string) string { return "q" + i + ": {type: string}, q" + i + ": *" + a })), - {name: "list", bring: func(id string, n int, inner string) brought { + {name: "list", bring: func(id string, count int, inner string) brought { return brought{defs: "a" + id + ": &a" + id + " " + inner, - schema: "{allOf: [" + each(n, ", ", func(string) string { return "*a" + id }) + "]}"} + schema: "{allOf: [" + each(count, ", ", func(string) string { return "*a" + id }) + "]}"} }}, - landed("ref", func(s string) string { return "{allOf: [" + s + "]}" }, + landed("ref", func(text string) string { return "{allOf: [" + text + "]}" }, func(ref, _ string) string { return "{$ref: " + ref + "}" }), anchored("merge list", ", b@: &b@ {description: b}", func(a, i string) string { return "q" + i + ": {<<: [*b@, *" + a + "]}" }), @@ -114,23 +114,23 @@ var bringers = []bringer{ func(_, i string) string { return "q" + i + ": {<<: *b@}" }), repeating(anchored("twice in a merged source", ", s@: &s@ {type: object, properties: {p: *a@}, properties: {}}", func(_, i string) string { return "q" + i + ": {<<: *s@}" })), - landed("dynamic ref", func(s string) string { return "{allOf: [" + s + "]}" }, + landed("dynamic ref", func(text string) string { return "{allOf: [" + text + "]}" }, func(ref, _ string) string { return "{$dynamicRef: " + ref + "}" }), - landed("mapping", func(s string) string { - return "{type: object, discriminator: {propertyName: t, mapping: {" + s + ", n: T}}}" + landed("mapping", func(text string) string { + return "{type: object, discriminator: {propertyName: t, mapping: {" + text + ", n: T}}}" }, func(ref, i string) string { return "m" + i + ": " + ref }), - landed("default mapping", func(s string) string { return "{anyOf: [" + s + "]}" }, func(ref, _ string) string { + landed("default mapping", func(text string) string { return "{anyOf: [" + text + "]}" }, func(ref, _ string) string { return "{type: object, discriminator: {propertyName: t, defaultMapping: " + ref + "}}" }), - landed("mapping tagged null", func(s string) string { - return "{type: object, discriminator: {propertyName: t, mapping: {" + s + "}}}" + landed("mapping tagged null", func(text string) string { + return "{type: object, discriminator: {propertyName: t, mapping: {" + text + "}}}" }, func(ref, i string) string { return "m" + i + ": !!null " + ref }), - {name: "ref into a landing", bring: func(id string, n int, inner string) brought { + {name: "ref into a landing", bring: func(id string, count int, inner string) brought { mount := func(i string) string { return "x-n" + id + "-" + i } return brought{ defs: "a" + id + ": &a" + id + " {x-in: " + inner + "}", - mounts: each(n, "", func(i string) string { return mount(i) + ": *a" + id + "\n" }), - schema: "{allOf: [" + each(n, ", ", func(i string) string { + mounts: each(count, "", func(i string) string { return mount(i) + ": *a" + id + "\n" }), + schema: "{allOf: [" + each(count, ", ", func(i string) string { // The mount is named on both sides, so it is read before in either order. return "{$ref: '#/" + mount(i) + "'}, {$ref: '#/" + mount(i) + "/x-in'}, {$ref: '#/" + mount(i) + "'}" }) + "]}", @@ -191,8 +191,8 @@ func broughtChains() [][]bringer { } for _, a := range bringers[:coreBringers] { for _, b := range bringers[:coreBringers] { - for _, bringerValue := range bringers[:coreBringers] { - chains = append(chains, []bringer{a, b, bringerValue}) + for _, core := range bringers[:coreBringers] { + chains = append(chains, []bringer{a, b, core}) } } } @@ -221,8 +221,8 @@ func broughtDocument(chain []bringer, at int, wide bool) string { id := strconv.Itoa(i) objects = append(objects, "x-o"+id+": &o"+id+" "+strings.ReplaceAll(o.object, "@", held[3+i])+ "\nx-o"+id+"-0: *o"+id+"\nx-o"+id+"-1: *o"+id+"\n") - for _, c := range o.components { - named = append(named, c+": {A: {$ref: '#/x-o"+id+"-0'}, B: {$ref: '#/x-o"+id+"-1'}}") + for _, component := range o.components { + named = append(named, component+": {A: {$ref: '#/x-o"+id+"-0'}, B: {$ref: '#/x-o"+id+"-1'}}") } } return "openapi: 3.2.0\ninfo: {title: t, version: '1'}\nx-defs: {" + strings.Join(defs, ", ") + "}\n" + @@ -246,7 +246,7 @@ func broughtTotals(t *testing.T, text string) (weighed, entries, spelled int) { require.True(t, complete, "the total is whole") table := reftable.Bind(t.Context(), doc, self) require.False(t, table.Exhausted() || table.Truncated(), "the table is whole") - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { entries++ for token := range referenceSite.Site.Pointer.Tokens() { spelled += len(token) + 1 diff --git a/compilers/openapi/internal/reftable/normaluri_test.go b/compilers/openapi/internal/reftable/normaluri_test.go index c219ea9e7..a4d49bd1b 100644 --- a/compilers/openapi/internal/reftable/normaluri_test.go +++ b/compilers/openapi/internal/reftable/normaluri_test.go @@ -16,10 +16,10 @@ import ( ) // normal parses s and spells it as reftable.NormalURI does. -func normal(t *testing.T, s string) string { +func normal(t *testing.T, text string) string { t.Helper() - u, err := url.Parse(s) - require.NoError(t, err, s) + u, err := url.Parse(text) + require.NoError(t, err, text) return reftable.NormalURI(u) } diff --git a/compilers/openapi/internal/reftable/pointers.go b/compilers/openapi/internal/reftable/pointers.go index 435c4279e..50a39c6c3 100644 --- a/compilers/openapi/internal/reftable/pointers.go +++ b/compilers/openapi/internal/reftable/pointers.go @@ -11,8 +11,8 @@ import ( // it, and through each reference object it passes, into what that object's // chain ends on (through), settling each such chain first. func (b *binder) readPointer(id DocID, pointer jsontext.Pointer) (reading, Reason) { - readingValue, reason, _ := b.readFrom(id, pointer, true) - return readingValue, reason + reading, reason, _ := b.readFrom(id, pointer, true) + return reading, reason } // readFrom is readPointer. With settle false it settles no chain: where it reaches a @@ -22,9 +22,9 @@ func (b *binder) readPointer(id DocID, pointer jsontext.Pointer) (reading, Reaso // into the reading only where one is passed or returned, so a read costs its // pointer's length rather than its square. func (b *binder) readFrom(id DocID, pointer jsontext.Pointer, settle bool) (reading, Reason, objectKey) { - readingValue := reading{at: DocumentPointer{Doc: id}, node: b.docs.list[id].root, state: b.docs.rootState(id)} + rootReading := reading{at: DocumentPointer{Doc: id}, node: b.docs.list[id].root, state: b.docs.rootState(id)} // grammar is the state the grammar places readingValue's position at, which - // says where a reference object stands: readingValue's own in the source, + // says where a reference object sits: readingValue's own in the source, // and in another OpenAPI document what it places there although // readingValue reads raw YAML, which no model holds (docs.identityState). grammar := b.docs.identityState(id) @@ -32,35 +32,35 @@ func (b *binder) readFrom(id DocID, pointer jsontext.Pointer, settle bool) (read tokens := 0 for token := range pointer.Tokens() { if tokens++; tokens > maxPointerTokens || !b.work.spend(1) { - return readingValue.spelledAs(soFar), NoTarget, objectKey{} + return rootReading.spelledAs(soFar), NoTarget, objectKey{} } - if kind, isRef := refKinds[grammar]; isRef && b.docs.writesRef(readingValue) { - next, reason, need := b.through(readingValue.spelledAs(soFar), kind, token, settle) + if kind, isRef := refKinds[grammar]; isRef && b.docs.writesRef(rootReading) { + next, reason, need := b.through(rootReading.spelledAs(soFar), kind, token, settle) if reason != NoReason || need.kind != 0 { return next, reason, need } - readingValue, soFar = next, append(soFar[:0], next.at.Pointer...) + rootReading, soFar = next, append(soFar[:0], next.at.Pointer...) } - child := b.docs.child(readingValue.at.Doc, readingValue.node, token) + child := b.docs.child(rootReading.at.Doc, rootReading.node, token) if child == nil { - return readingValue.spelledAs(soFar), b.docs.absent(readingValue.at.Doc, readingValue.node), objectKey{} + return rootReading.spelledAs(soFar), b.docs.absent(rootReading.at.Doc, rootReading.node), objectKey{} } soFar = append(soFar, jsontext.Pointer("").AppendToken(token)...) - readingValue = reading{at: DocumentPointer{Doc: readingValue.at.Doc}, node: child, place: readingValue.below(token)} + rootReading = reading{at: DocumentPointer{Doc: rootReading.at.Doc}, node: child, place: rootReading.below(token)} grammar = step(grammar, token) } - return readingValue.spelledAs(soFar), NoReason, objectKey{} + return rootReading.spelledAs(soFar), NoReason, objectKey{} } -// writesRef reports whether readingValue, read at a reference object's state, +// writesRef reports whether reading, read at a reference object's state, // writes a $ref, which makes it a reference. -func (d *docs) writesRef(readingValue reading) bool { - _, ok := d.refOf(readingValue.at.Doc, readingValue.node) +func (d *docs) writesRef(reading reading) bool { + _, ok := d.refOf(reading.at.Doc, reading.node) return ok } -// through carries readingValue, a reference object of kind with token left to -// read, on to where its chain ends, read at readingValue's state afresh +// through carries from, a reference object of kind with token left to +// read, on to where its chain ends, read at from's state afresh // (place): a pointer through a response reads on in the response it names, in // whichever document. A path item's token the mapping writes beside its $ref is // read where it is written, as a mount keeps the nearer layer @@ -68,11 +68,11 @@ func (d *docs) writesRef(readingValue reading) bool { // resolve is Unpassable, and one that waits for documents a pass has yet to // read is PendingExternalDocumentRead. Without settle, a chain not settled is // returned as what the read needs. -func (b *binder) through(readingValue reading, kind RefKind, token string, settle bool) (reading, Reason, objectKey) { - if kind == RefPathItem && token != "$ref" && b.docs.child(readingValue.at.Doc, readingValue.node, token) != nil { - return readingValue, NoReason, objectKey{} +func (b *binder) through(from reading, kind RefKind, token string, settle bool) (reading, Reason, objectKey) { + if kind == RefPathItem && token != "$ref" && b.docs.child(from.at.Doc, from.node, token) != nil { + return from, NoReason, objectKey{} } - key := objectKey{at: readingValue.at, kind: kind} + key := objectKey{at: from.at, kind: kind} chain, settled := b.objs.chains[key] if !settled && settle && !b.wait.onObjects[key] { b.objs.settle(key) @@ -80,13 +80,13 @@ func (b *binder) through(readingValue reading, kind RefKind, token string, settl } switch { case !settled && b.wait.onObjects[key]: - return readingValue, PendingExternalDocumentRead, objectKey{} + return from, PendingExternalDocumentRead, objectKey{} case !settled && !settle: - return readingValue, NoReason, key + return from, NoReason, key case chain.Status != Resolved: // A chain the budget left unsettled is no chain that resolved: the hop // reading through it is answered OverBudget (binder.hop). - return readingValue, Unpassable, objectKey{} + return from, Unpassable, objectKey{} } - return reading{at: chain.End, node: b.docs.node(chain.End), state: readingValue.state}, NoReason, objectKey{} + return reading{at: chain.End, node: b.docs.node(chain.End), state: from.state}, NoReason, objectKey{} } diff --git a/compilers/openapi/internal/reftable/pointers_internal_test.go b/compilers/openapi/internal/reftable/pointers_internal_test.go index d947ea7bb..c305aa5e1 100644 --- a/compilers/openapi/internal/reftable/pointers_internal_test.go +++ b/compilers/openapi/internal/reftable/pointers_internal_test.go @@ -24,9 +24,9 @@ func binderOver(t *testing.T, src string) *binder { var root yaml.Node require.NoError(t, yaml.Unmarshal([]byte(src), &root)) cfg := Config{Self: "spec.yaml"} - workValue := &work{ctx: t.Context(), steps: budget.New(budget.AtMost(MaxSteps))} - docs := newDocs(&root, cfg, workValue) - return newBinder(cfg, docs, workValue, newIdentifiers(resources{docs}.document(Source)), newReads()) + work := &work{ctx: t.Context(), steps: budget.New(budget.AtMost(MaxSteps))} + docs := newDocs(&root, cfg, work) + return newBinder(cfg, docs, work, newIdentifiers(resources{docs}.document(Source)), newReads()) } // TestBinder_ReadPointerCostsItsPointersLength pins that a read spells the position it diff --git a/compilers/openapi/internal/reftable/positionsortkeys.go b/compilers/openapi/internal/reftable/positionsortkeys.go new file mode 100644 index 000000000..24751cf3e --- /dev/null +++ b/compilers/openapi/internal/reftable/positionsortkeys.go @@ -0,0 +1,100 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package reftable + +import ( + "bytes" + "cmp" + "encoding/binary" + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" +) + +// positionSortKeyWriter writes the bytes a position sorts by as compareNamed +// orders it: its document's rank, the source first and others by name, then +// provenance.AppendPointerSortKey and a 0x00, below any token's first byte, so +// bytes written after a position count only where positions are alike. +type positionSortKeyWriter struct { + // ranks is each document's rank, by DocID. + ranks []uint64 +} + +// positionSortKeyWriterOf returns the key writer of the documents docs holds now. +func positionSortKeyWriterOf(docs *docs) positionSortKeyWriter { + return newPositionSortKeyWriter(len(docs.list), docs.name) +} + +// SortPositions sorts positions as PositionOrder(referenceTargetTable) orders +// them, writing each one's key once. +func SortPositions(referenceTargetTable *ReferenceTargetTable, positions []DocumentPointer) { + keys := newPositionSortKeyWriter(len(referenceTargetTable.docs), func(id DocID) string { return referenceTargetTable.docs[id].Name }) + sortByKeys(positions, keys.append) +} + +// newPositionSortKeyWriter returns the key writer of the documents DocIDs below +// count name. Two documents are never named alike, as a table opens each name +// once. +func newPositionSortKeyWriter(count int, name func(DocID) string) positionSortKeyWriter { + others := make([]DocID, 0, count) + for id := range count { + if DocID(id) != Source { + others = append(others, DocID(id)) + } + } + slices.SortFunc(others, func(a, b DocID) int { return cmp.Compare(name(a), name(b)) }) + ranks := make([]uint64, count) + for rank, id := range others { + ranks[id] = uint64(rank) + 1 + } + return positionSortKeyWriter{ranks: ranks} +} + +// append appends to key the key of documentPointer. +func (keys positionSortKeyWriter) append(key []byte, documentPointer DocumentPointer) []byte { + key = binary.BigEndian.AppendUint64(key, keys.ranks[documentPointer.Doc]) + return append(provenance.AppendPointerSortKey(key, documentPointer.Pointer), 0) +} + +// appendObject appends to key the key of the reference object of kind at site: +// its position's, then its kind's, as reference objects sort. +func (keys positionSortKeyWriter) appendObject(key []byte, site DocumentPointer, kind RefKind) []byte { + return append(keys.append(key, site), byte(kind)) +} + +// appendReference appends to key the key of reference's object (appendObject). +func (keys positionSortKeyWriter) appendReference(key []byte, reference Reference) []byte { + return keys.appendObject(key, reference.Site, reference.Kind) +} + +// keyedItem is an item of a sort beside the key it sorts by. +type keyedItem[T any] struct { + key []byte + item T +} + +// sortByKeys sorts items by the bytes keyOf appends for each, written once an +// item rather than read from two positions at every comparison. It is not +// stable. +func sortByKeys[T any](items []T, keyOf func(key []byte, item T) []byte) { + if len(items) < 2 { + return + } + ends := make([]int, len(items)) + var written []byte + for i, item := range items { + written = keyOf(written, item) + ends[i] = len(written) + } + keyed := make([]keyedItem[T], len(items)) + start := 0 + for i, item := range items { + keyed[i] = keyedItem[T]{key: written[start:ends[i]], item: item} + start = ends[i] + } + slices.SortFunc(keyed, func(a, b keyedItem[T]) int { return bytes.Compare(a.key, b.key) }) + for i := range keyed { + items[i] = keyed[i].item + } +} diff --git a/compilers/openapi/internal/reftable/positionsortkeys_internal_test.go b/compilers/openapi/internal/reftable/positionsortkeys_internal_test.go new file mode 100644 index 000000000..2708c81bc --- /dev/null +++ b/compilers/openapi/internal/reftable/positionsortkeys_internal_test.go @@ -0,0 +1,36 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package reftable + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestSortByKeys_SortsReferenceObjectsByPositionAndThenKind pins the order of +// reference objects sorted by their keys (positionKeys.appendObject): by +// position, as written, an object before one beneath its position whatever +// its kind, and of one position by kind. +func TestSortByKeys_SortsReferenceObjectsByPositionAndThenKind(t *testing.T) { + t.Parallel() + at := func(pointer string, kind RefKind) Reference { + return Reference{Site: DocumentPointer{Doc: Source, Pointer: jsontext.Pointer(pointer)}, Kind: kind} + } + for name, want := range map[string][]Reference{ + "an object before one beneath its position": {at("/P", RefResponse), at("/P/0", RefPathItem), at("/P/x", RefPathItem)}, + "of one position, by kind": {at("/P", RefParameter), at("/P", RefResponse)}, + } { + keys := newPositionSortKeyWriter(1, func(DocID) string { return "" }) + got := make([]Reference, len(want)) + for i := range want { + got[i] = want[len(want)-1-i] + } + + sortByKeys(got, keys.appendReference) + + assert.Equal(t, want, got, name) + } +} diff --git a/compilers/openapi/internal/reftable/purereferenceloops.go b/compilers/openapi/internal/reftable/purereferenceloops.go new file mode 100644 index 000000000..e30bae3dd --- /dev/null +++ b/compilers/openapi/internal/reftable/purereferenceloops.go @@ -0,0 +1,333 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package reftable + +import ( + "cmp" + "maps" + "slices" + "strconv" + "strings" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/stronglyconnected" +) + +// pureReferenceGraph is the graph a loop of pure references is read over: a +// position writing a $ref leads where its hop lands, and a pure reference, a +// schema writing only an allOf of such positions and keys saying nothing of +// the instance, leads to its entries. order lists every node sorted, so the +// walk turns on no map order. +type pureReferenceGraph struct { + successors map[DocumentPointer][]DocumentPointer + pureReferences map[DocumentPointer]bool + order []DocumentPointer +} + +// closePureReferenceLoops records each loop pure references close, bare $refs +// among them (docs/compilers/openapi.md#reference-cycles): a set of the +// graph's nodes, a pure reference among them, none leading out, so it never +// reaches a schema. Every chain into one ends Cyclic, as one into a loop of +// bare $refs does; a loop of bare $refs alone is closeLoop's. +func closePureReferenceLoops(binder *binder, referenceTargetTable *ReferenceTargetTable) { + graph, read := pureReferenceGraphOf(binder, referenceTargetTable) + if !read || len(graph.pureReferences) == 0 { + return + } + onLoop := map[DocumentPointer]bool{} + for _, members := range closedComponents(graph) { + if !slices.ContainsFunc(members, func(member DocumentPointer) bool { return graph.pureReferences[member] }) { + continue + } + for _, member := range members { + onLoop[member] = true + } + binder.loops = append(binder.loops, Loop{Members: slices.SortedFunc(slices.Values(pureReferenceLoopMembers(graph, members)), binder.docs.compare)}) + } + if len(onLoop) == 0 { + return + } + for site, referenceSite := range referenceTargetTable.referenceSites { + if chain, ends := endsOnPureReferenceLoop(referenceSite.Chain, site, onLoop); ends { + referenceSite.Chain = chain + referenceTargetTable.referenceSites[site] = referenceSite + } + } + for site, chain := range binder.chains { + if chain, ends := endsOnPureReferenceLoop(chain, site, onLoop); ends { + binder.chains[site] = chain + } + } +} + +// pureReferenceLoopMembers returns the members of a loop of pure references a +// report names: each but the entries of a pure reference among them, which the +// pure reference names. +func pureReferenceLoopMembers(graph pureReferenceGraph, members []DocumentPointer) []DocumentPointer { + in := make(map[DocumentPointer]bool, len(members)) + for _, member := range members { + in[member] = true + } + return slices.DeleteFunc(slices.Clone(members), func(member DocumentPointer) bool { + holder, isEntry := allOfHolder(member) + return isEntry && in[holder] && graph.pureReferences[holder] + }) +} + +// endsOnPureReferenceLoop returns the Cyclic chain of the $ref at site where +// site lies on a loop of onLoop or its resolved chain ends on one. +func endsOnPureReferenceLoop(chain Chain, site DocumentPointer, onLoop map[DocumentPointer]bool) (Chain, bool) { + switch { + case onLoop[site]: + return Chain{Status: Cyclic, PositionLiesOnReferenceCycle: true}, true + case chain.Status == Resolved && onLoop[chain.End]: + return Chain{Status: Cyclic}, true + default: + return Chain{}, false + } +} + +// pureReferenceGraphOf reads the graph of referenceTargetTable's sites and the +// pure references above them, each node a step of the work, and reports false +// where the budget runs out. A table holding no allOf entry costs nothing. +func pureReferenceGraphOf(binder *binder, referenceTargetTable *ReferenceTargetTable) (pureReferenceGraph, bool) { + graph := pureReferenceGraph{successors: map[DocumentPointer][]DocumentPointer{}, pureReferences: map[DocumentPointer]bool{}} + holders := pureReferenceHolders(binder, referenceTargetTable) + if len(holders) == 0 { + return graph, true + } + for _, holder := range holders { + if conjuncts, ok := pureReferenceConjuncts(binder, referenceTargetTable, graph.pureReferences, holder); ok { + graph.successors[holder], graph.pureReferences[holder] = conjuncts, true + } + } + for site, referenceSite := range referenceTargetTable.referenceSites { + var next []DocumentPointer + if referenceSite.Hop.Status == Resolved { + next = []DocumentPointer{referenceSite.Hop.Target} + } + graph.successors[site] = next + } + for node := range graph.successors { + graph.order = append(graph.order, node) + } + slices.SortFunc(graph.order, binder.docs.compare) + return graph, binder.work.spend(len(graph.order)) +} + +// pureReferenceHolders returns every schema whose allOf lists a site of +// referenceTargetTable, or lists such a schema, deepest first, so a holder is +// read after each holder its entries are. +func pureReferenceHolders(binder *binder, referenceTargetTable *ReferenceTargetTable) []DocumentPointer { + seen := map[DocumentPointer]bool{} + for site := range referenceTargetTable.referenceSites { + for holder, ok := allOfHolder(site); ok && !seen[holder]; holder, ok = allOfHolder(holder) { + seen[holder] = true + } + } + return slices.SortedFunc(maps.Keys(seen), func(holder, otherHolder DocumentPointer) int { + if order := cmp.Compare(pointerDepth(otherHolder), pointerDepth(holder)); order != 0 { + return order + } + return binder.docs.compare(holder, otherHolder) + }) +} + +// pointerDepth counts the tokens of documentPointer's pointer. +func pointerDepth(documentPointer DocumentPointer) int { + return strings.Count(string(documentPointer.Pointer), "/") +} + +// allOfHolder returns the schema whose allOf lists site as an entry, false +// where site is no allOf entry. +func allOfHolder(site DocumentPointer) (DocumentPointer, bool) { + if _, err := strconv.Atoi(site.Pointer.LastToken()); err != nil || site.Pointer.Parent().LastToken() != "allOf" { + return DocumentPointer{}, false + } + return DocumentPointer{Doc: site.Doc, Pointer: site.Pointer.Parent().Parent()}, true +} + +// pureReferenceConjuncts returns the entries of holder's allOf where holder is +// a pure reference: each entry a pure reference already found, a $ref with +// only keys saying nothing beside it, as a 3.0 $ref's siblings are read too, +// or a schema saying nothing, which it leaves out. It returns at least one. +func pureReferenceConjuncts(binder *binder, referenceTargetTable *ReferenceTargetTable, pureReferences map[DocumentPointer]bool, + holder DocumentPointer, +) ([]DocumentPointer, bool) { + var items []*yaml.Node + for _, pair := range binder.docs.list[holder.Doc].view.MappingPairs(binder.docs.node(holder)) { + if pair.Key == "allOf" { + items = sequenceItems(pair.Val) + } else if !saysNothingAt(binder, holder, pair) { + return nil, false + } + } + var conjuncts []DocumentPointer + for i, item := range items { + entry := allOfEntryAt(holder, i) + referenceSite, isSite := referenceTargetTable.referenceSites[entry] + switch { + case pureReferences[entry]: + conjuncts = append(conjuncts, entry) + case isSite && writesOnlyKeysSayingNothingBeside(binder, entry, item, referenceSite.Keyword): + conjuncts = append(conjuncts, entry) + case !isSite && schemaSaysNothingAt(binder, entry, item): + default: + return nil, false + } + } + return conjuncts, len(conjuncts) > 0 +} + +// writesOnlyKeysSayingNothingBeside reports whether the mapping node at +// schemaPointer writes nothing beside its reference keyword but keys saying +// nothing. +func writesOnlyKeysSayingNothingBeside(binder *binder, schemaPointer DocumentPointer, node *yaml.Node, keyword string) bool { + for _, pair := range binder.docs.list[schemaPointer.Doc].view.MappingPairs(node) { + if pair.Key != keyword && !saysNothingAt(binder, schemaPointer, pair) { + return false + } + } + return true +} + +// saysNothingCandidate is a schema node schemaSaysNothingAt reads and where it +// is written. +type saysNothingCandidate struct { + at DocumentPointer + node *yaml.Node +} + +// schemaSaysNothingAt reports whether the schema node at schemaPointer says +// nothing of the instance: `true`, or a mapping writing only keys saying +// nothing and an allOf every entry of which says nothing, each node read a +// step of the work. +func schemaSaysNothingAt(binder *binder, schemaPointer DocumentPointer, node *yaml.Node) bool { + stack := []saysNothingCandidate{{at: schemaPointer, node: node}} + for len(stack) > 0 { + top := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if !binder.work.spend(1) { + return false + } + entries, saysNothing := saysNothingEntries(binder, top) + if !saysNothing { + return false + } + stack = append(stack, entries...) + } + return true +} + +// saysNothingEntries reports whether candidate's node says nothing beside its +// allOf, being `true` or a mapping writing only keys saying nothing, and +// returns the entries of that allOf, each of which must say nothing too. +func saysNothingEntries(binder *binder, candidate saysNothingCandidate) ([]saysNothingCandidate, bool) { + schema := nodeview.Deref(candidate.node) + switch { + case schema != nil && schema.Kind == yaml.ScalarNode && schema.ShortTag() == "!!bool" && schema.Value == "true": + return nil, true + case schema == nil || schema.Kind != yaml.MappingNode: + return nil, false + } + var entries []saysNothingCandidate + for _, pair := range binder.docs.list[candidate.at.Doc].view.MappingPairs(schema) { + if pair.Key != "allOf" { + if !saysNothingAt(binder, candidate.at, pair) { + return nil, false + } + continue + } + list := nodeview.Deref(pair.Val) + if list == nil || list.Kind != yaml.SequenceNode { + return nil, false + } + for i, item := range list.Content { + entries = append(entries, saysNothingCandidate{at: allOfEntryAt(candidate.at, i), node: item}) + } + } + return entries, true +} + +// allOfEntryAt returns the position of the entry at index i of the allOf the +// schema at holder writes. +func allOfEntryAt(holder DocumentPointer, i int) DocumentPointer { + return DocumentPointer{Doc: holder.Doc, Pointer: holder.Pointer.AppendToken("allOf").AppendToken(strconv.Itoa(i))} +} + +// saysNothingAt reports whether pair, written in the schema at schemaPointer, +// says nothing of the instance: a key saysNothingOfAPureReference admits, or +// one whose value schemaPointer's dialect does not read. +func saysNothingAt(binder *binder, schemaPointer DocumentPointer, pair nodeview.Pair) bool { + if saysNothingOfAPureReference(pair.Key) { + return true + } + return !dialectRule(binder.docs, schemaPointer.Doc, dialectAbove(binder.docs, binder.ids, schemaPointer)).Schema.ReadsValue(pair.Key, pair.Val) +} + +// saysNothingOfAPureReference reports whether key, beside a pure reference's +// allOf or $ref, says nothing of the instance: a note, an identifier or meta +// keyword, or an extension. A loop writing them is still a loop +// (docs/compilers/openapi.md#reference-cycles). +func saysNothingOfAPureReference(key string) bool { + slot := specrules.SlotOf(key) + return slot == specrules.SlotNotes || slot == specrules.SlotResource || strings.HasPrefix(key, "x-") +} + +// sequenceItems returns the items of val, its alias followed, where it is a +// sequence, and none otherwise. +func sequenceItems(val *yaml.Node) []*yaml.Node { + if val = nodeview.Deref(val); val == nil || val.Kind != yaml.SequenceNode { + return nil + } + return val.Content +} + +// closedComponents returns each strongly connected component of graph every +// member of which leads somewhere and only within it. A successor that is no +// node, a schema saying more than a pure reference, is no edge of the search. +func closedComponents(graph pureReferenceGraph) [][]DocumentPointer { + vertex := make(map[DocumentPointer]int, len(graph.order)) + for v, node := range graph.order { + vertex[node] = v + } + adjacency := make([][]int, len(graph.order)) + for v, node := range graph.order { + for _, next := range graph.successors[node] { + if w, isNode := vertex[next]; isNode { + adjacency[v] = append(adjacency[v], w) + } + } + } + var closed [][]DocumentPointer + for _, component := range stronglyconnected.Components(adjacency) { + members := make([]DocumentPointer, len(component)) + for k, v := range component { + members[k] = graph.order[v] + } + if leadsOnlyWithin(graph, members) { + closed = append(closed, members) + } + } + return closed +} + +// leadsOnlyWithin reports whether every one of members leads somewhere, and +// only to members. +func leadsOnlyWithin(graph pureReferenceGraph, members []DocumentPointer) bool { + in := make(map[DocumentPointer]bool, len(members)) + for _, member := range members { + in[member] = true + } + for _, member := range members { + successors := graph.successors[member] + if len(successors) == 0 || slices.ContainsFunc(successors, func(next DocumentPointer) bool { return !in[next] }) { + return false + } + } + return true +} diff --git a/compilers/openapi/internal/reftable/purereferenceloops_internal_test.go b/compilers/openapi/internal/reftable/purereferenceloops_internal_test.go new file mode 100644 index 000000000..1ad6c8e9a --- /dev/null +++ b/compilers/openapi/internal/reftable/purereferenceloops_internal_test.go @@ -0,0 +1,24 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package reftable + +import ( + "testing" + + "github.com/stretchr/testify/assert" + yaml "go.yaml.in/yaml/v3" +) + +// TestSequenceItems_ReadsASequenceAlone pins that an allOf a pure reference is +// read through holds items only where it is a sequence, an alias to one +// included. +func TestSequenceItems_ReadsASequenceAlone(t *testing.T) { + t.Parallel() + item := &yaml.Node{Kind: yaml.MappingNode} + list := &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{item}} + assert.Equal(t, []*yaml.Node{item}, sequenceItems(list)) + assert.Equal(t, []*yaml.Node{item}, sequenceItems(&yaml.Node{Kind: yaml.AliasNode, Alias: list})) + assert.Empty(t, sequenceItems(&yaml.Node{Kind: yaml.MappingNode, Content: []*yaml.Node{item, item}})) + assert.Empty(t, sequenceItems(nil)) +} diff --git a/compilers/openapi/internal/reftable/purereferenceloops_test.go b/compilers/openapi/internal/reftable/purereferenceloops_test.go new file mode 100644 index 000000000..0a89c920a --- /dev/null +++ b/compilers/openapi/internal/reftable/purereferenceloops_test.go @@ -0,0 +1,176 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package reftable_test + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" +) + +// TestBind_ALoopOfAllOfPureReferencesIsALoop pins the loops a chain of pure +// references closes (docs/compilers/openapi.md#reference-cycles): an allOf of +// $refs writing nothing else saying anything of the instance, notes, +// identifiers, meta keywords and extensions aside, is a pure reference, so a +// set of pure references and bare $refs none of which leads out of it is one +// loop, reported at its least member, each member's $ref on it and a $ref +// leading in not, in either declaration order. A pure reference leading out, an +// entry naming nothing, an entry that is no $ref and a key saying something +// each leave no loop. +func TestBind_ALoopOfAllOfPureReferencesIsALoop(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } + for _, tc := range []struct { + name string + schemas []string + members []jsontext.Pointer + onLoop []jsontext.Pointer + leadsIn []jsontext.Pointer + }{ + {"a self-reference beside a use of an object", []string{"C: {allOf: [" + ref("C") + "], description: d}", "U: " + ref("O"), "O: {type: object}"}, + []jsontext.Pointer{"/components/schemas/C"}, []jsontext.Pointer{"/components/schemas/C/allOf/0"}, nil}, + {"two pure references and a use", []string{"B: {allOf: [" + ref("A") + "]}", "A: {allOf: [" + ref("B") + "]}", "R: " + ref("A")}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}, + []jsontext.Pointer{"/components/schemas/A/allOf/0", "/components/schemas/B/allOf/0"}, + []jsontext.Pointer{"/components/schemas/R"}}, + {"a pure reference and a bare $ref", []string{"A: " + ref("B"), "B: {allOf: [" + ref("A") + "]}"}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B/allOf/0"}, nil}, + {"every entry on the loop", []string{"A: {allOf: [" + ref("A") + ", " + ref("B") + "]}", "B: {allOf: [" + ref("A") + "]}"}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}, + []jsontext.Pointer{"/components/schemas/A/allOf/0", "/components/schemas/A/allOf/1", "/components/schemas/B/allOf/0"}, nil}, + {"a self-reference writing what says nothing", []string{"C: {allOf: [" + ref("C") + "], $anchor: c, $defs: {D: {}}, x-a: 1, $comment: k}"}, + []jsontext.Pointer{"/components/schemas/C"}, []jsontext.Pointer{"/components/schemas/C/allOf/0"}, nil}, + {"a pure reference nested in a single entry", []string{"A: {allOf: [{allOf: [" + ref("B") + "]}]}", "B: {allOf: [" + ref("A") + "]}"}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}, + []jsontext.Pointer{"/components/schemas/A/allOf/0/allOf/0", "/components/schemas/B/allOf/0"}, nil}, + {"a pure reference beside a true entry", []string{"A: {allOf: [" + ref("B") + ", true]}", "B: {allOf: [" + ref("A") + "]}"}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}, + []jsontext.Pointer{"/components/schemas/A/allOf/0", "/components/schemas/B/allOf/0"}, nil}, + {"a pure reference beside entries saying nothing all through", []string{"A: {allOf: [{description: d}, " + ref("B") + ", {allOf: [{$comment: c}, true]}]}", "B: {allOf: [" + ref("A") + "]}"}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}, + []jsontext.Pointer{"/components/schemas/A/allOf/1", "/components/schemas/B/allOf/0"}, nil}, + {"an entry writing what says nothing beside its $ref", []string{"A: {allOf: [{$ref: '#/components/schemas/B', description: d, $comment: c}]}", "B: {allOf: [" + ref("A") + "]}"}, + []jsontext.Pointer{"/components/schemas/A", "/components/schemas/B"}, + []jsontext.Pointer{"/components/schemas/A/allOf/0", "/components/schemas/B/allOf/0"}, nil}, + } { + for _, reversed := range []bool{false, true} { + table := bound(t, pureReferenceSpec(tc.schemas, reversed), self) + require.Len(t, table.Loops(), 1, "%s reversed=%t", tc.name, reversed) + loop := table.Loops()[0] + if use, ok := table.ReferenceSiteAt(documentPointerAt("/components/schemas/U")); ok { + assert.Equal(t, reftable.Resolved, use.Chain.Status, "%s: a $ref no loop holds keeps its chain", tc.name) + } + members := make([]jsontext.Pointer, 0, len(loop.Members)) + for _, member := range loop.Members { + members = append(members, member.Pointer) + } + assert.Equal(t, tc.members, members, tc.name) + assert.Equal(t, documentPointerAt(tc.members[0]), loop.Site, tc.name) + for _, site := range tc.onLoop { + chain := entryAt(t, table, site).Chain + assert.Equal(t, reftable.Cyclic, chain.Status, "%s: %s", tc.name, site) + assert.True(t, chain.PositionLiesOnReferenceCycle, "%s: %s lies on the loop", tc.name, site) + } + for _, site := range tc.leadsIn { + chain := entryAt(t, table, site).Chain + assert.Equal(t, reftable.Cyclic, chain.Status, "%s: %s", tc.name, site) + assert.False(t, chain.PositionLiesOnReferenceCycle, "%s: %s leads in", tc.name, site) + } + } + } +} + +// TestBind_ASchemaSayingMoreThanAPureReferenceClosesNoLoop pins the cycles that +// stay compositions: a pure reference composing a $ref off the cycle, an entry +// naming nothing, an inline entry, a key saying something of the instance, and +// an allOf no entry of which is a $ref each leave the table with no loop. An +// extension says nothing, so it no longer sits among them. +func TestBind_ASchemaSayingMoreThanAPureReferenceClosesNoLoop(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } + for name, schemas := range map[string][]string{ + "a reference off the cycle": {"A: {allOf: [" + ref("B") + ", " + ref("O") + "]}", "B: {allOf: [" + ref("A") + "]}", "O: {type: object}"}, + "an entry naming nothing": {"A: {allOf: [" + ref("A") + ", {$ref: '#/nowhere'}]}"}, + "an inline entry": {"A: {allOf: [" + ref("A") + ", {type: string}]}"}, + "a member": {"A: {allOf: [" + ref("A") + "], properties: {a: {type: string}}}"}, + "an unevaluated keyword": {"A: {allOf: [" + ref("A") + "], unevaluatedProperties: false}"}, + "no $ref entry": {"A: {allOf: [{type: string}]}"}, + "a kind beside an entry's $ref": {"A: {allOf: [{$ref: '#/components/schemas/B', type: string}]}", "B: {allOf: [" + ref("A") + "]}"}, + "a member beside an entry's $ref": {"A: {allOf: [{$ref: '#/components/schemas/B', properties: {p: {}}}]}", + "B: {allOf: [" + ref("A") + "]}"}, + "a false entry": {"A: {allOf: [" + ref("A") + ", false]}"}, + "a nested pure reference saying something": {"A: {allOf: [{allOf: [" + ref("A") + "], type: string}]}"}, + "a nested entry saying something": {"A: {allOf: [" + ref("A") + ", {allOf: [{$comment: c}, {minLength: 2}]}]}"}, + "a nested allOf no list": {"A: {allOf: [" + ref("A") + ", {allOf: {}}]}"}, + } { + table := bound(t, pureReferenceSpec(schemas, false), self) + assert.Empty(t, table.Loops(), name) + } +} + +// TestBind_ALoopOfBareRefsBesideAPureReferenceIsReportedOnce pins that a loop +// of bare $refs is the chains' own, reported once beside a loop of pure +// references, each at its least member. +func TestBind_ALoopOfBareRefsBesideAPureReferenceIsReportedOnce(t *testing.T) { + t.Parallel() + table := bound(t, pureReferenceSpec([]string{"A: {$ref: '#/components/schemas/B'}", "B: {$ref: '#/components/schemas/A'}", + "C: {allOf: [{$ref: '#/components/schemas/C'}]}"}, false), self) + sites := make([]reftable.DocumentPointer, 0, len(table.Loops())) + for _, loop := range table.Loops() { + sites = append(sites, loop.Site) + } + assert.Equal(t, []reftable.DocumentPointer{documentPointerAt("/components/schemas/A"), documentPointerAt("/components/schemas/C")}, sites) +} + +// TestBind_ABudgetRunningOutLeavesThePureReferencesUnread pins that the pure +// references are read within the table's budget: one too small to read them +// past the chains finds no loop of pure references, and one that reads the +// chains and the pure references finds it. +func TestBind_ABudgetRunningOutLeavesThePureReferencesUnread(t *testing.T) { + t.Parallel() + src := pureReferenceSpec([]string{"C: {allOf: [{$ref: '#/components/schemas/C'}]}"}, false) + full := bound(t, src, self) + require.Len(t, full.Loops(), 1) + cfg := self + cfg.Limit = budget.AtMost(full.Steps() - 1) + cut := bound(t, src, cfg) + assert.True(t, cut.Exhausted()) + assert.Empty(t, cut.Loops(), "a budget that runs out reads no pure reference") +} + +// TestBind_ABudgetRunningOutAmongEntriesSayingNothingLeavesThePureReferencesUnread +// pins that the entries a pure reference sets aside are read within the table's +// budget: at every limit below what the whole read costs, no loop of pure +// references is found. +func TestBind_ABudgetRunningOutAmongEntriesSayingNothingLeavesThePureReferencesUnread(t *testing.T) { + t.Parallel() + src := pureReferenceSpec([]string{"C: {allOf: [{$ref: '#/components/schemas/C'}, {allOf: [true, {allOf: [{$comment: c}, true]}]}]}"}, false) + full := bound(t, src, self) + require.Len(t, full.Loops(), 1) + for limit := 1; limit < full.Steps(); limit++ { + cfg := self + cfg.Limit = budget.AtMost(limit) + assert.Empty(t, bound(t, src, cfg).Loops(), "limit %d", limit) + } +} + +// pureReferenceSpec writes schemas as the source's components, in reverse where +// reversed says so. +func pureReferenceSpec(schemas []string, reversed bool) string { + src := head + "components:\n schemas:\n" + for i := range schemas { + at := i + if reversed { + at = len(schemas) - 1 - i + } + src += " " + schemas[at] + "\n" + } + return src +} diff --git a/compilers/openapi/internal/reftable/reach.go b/compilers/openapi/internal/reftable/reach.go index 33a8567fe..e238957ea 100644 --- a/compilers/openapi/internal/reftable/reach.go +++ b/compilers/openapi/internal/reftable/reach.go @@ -17,92 +17,176 @@ import ( // known is false where a resource on the way was not placed, as a merge past // the bound may hide one. type reach struct { - out map[DocumentPointer][]DocumentPointer + // nodes numbers each resource an edge leaves or lands on, and edges lists, + // by number, the resources each leads to, in position order. + nodes map[DocumentPointer]int + edges [][]int work *work known bool } -// reachOf builds the graph over what the pass b settled into +// reachOf builds the graph over what the pass binder settled into // referenceTargetTable, placing each position through referenceTargetTable's // bases, in the order referenceTargetTable lists them, so where the budget runs // out depends on no order of reading. Past the budget, or once the binding's // context is done, it links nothing more and is not known. -func reachOf(b *binder, referenceTargetTable *ReferenceTargetTable) reach { - reachValue := reach{out: map[DocumentPointer][]DocumentPointer{}, work: b.work, known: true} +func reachOf(binder *binder, referenceTargetTable *ReferenceTargetTable) reach { + reach := reach{work: binder.work, known: true} + out := map[DocumentPointer][]DocumentPointer{} cut := false place := func(documentPointer DocumentPointer) DocumentPointer { - if cut = cut || b.work.over(); cut { + if cut = cut || binder.work.over(); cut { return DocumentPointer{} } in, known := referenceTargetTable.bases.holding(documentPointer) - reachValue.known = reachValue.known && known + reach.known = reach.known && known return in.root } link := func(from, to DocumentPointer) { inFrom, inTo := place(from), place(to) - reachValue.known = reachValue.known && !cut + reach.known = reach.known && !cut if !cut && inFrom != inTo { - reachValue.out[inFrom] = append(reachValue.out[inFrom], inTo) + out[inFrom] = append(out[inFrom], inTo) } } - for _, res := range b.ids.resources { - if res.root.Pointer != "" && b.docs.reached[res.root.Doc] { + for _, res := range binder.ids.resources { + if res.root.Pointer != "" && binder.docs.reached[res.root.Doc] { link(DocumentPointer{Doc: res.root.Doc, Pointer: res.root.Pointer.Parent()}, res.root) } } - for _, referenceSite := range referenceTargetTable.entryList { + for _, referenceSite := range referenceTargetTable.referenceSiteList { if referenceSite.Hop.Status == Resolved { link(referenceSite.Site, referenceSite.Hop.Target) } } - for _, mappingKey := range slices.SortedFunc(maps.Keys(referenceTargetTable.mappings), mappingOrder(b.docs)) { + for _, mappingKey := range slices.SortedFunc(maps.Keys(referenceTargetTable.mappings), mappingOrder(binder.docs)) { if mapping := referenceTargetTable.mappings[mappingKey]; mapping.Hop.Status == Resolved { link(mapping.At, mapping.Hop.Target) } } - for at, out := range reachValue.out { - slices.SortFunc(out, comparePositions) - reachValue.out[at] = slices.Compact(out) - } - return reachValue + reach.nodes, reach.edges = numbered(out) + return reach } -// reachers returns whether a resource is reached by an origin other than -// itself, along the graph's edges, origins being resources. Each resource -// keeps at most two distinct origins, which is enough to tell one other than -// itself, so each edge is walked at most twice for each resource it leaves, -// and each walk is a step of the binding's budget: past it, the walk stops -// short and the budget says so. A graph not known is not walked. -func (r reach) reachers(origins []DocumentPointer) func(resource DocumentPointer) bool { - held := map[DocumentPointer][]DocumentPointer{} - if !r.known { - // What no verdict rests on, as it is not known, is not walked. - origins = nil - } - type visit struct{ at, origin DocumentPointer } - var queue []visit - add := func(at, origin DocumentPointer) { - if len(held[at]) < 2 && !slices.Contains(held[at], origin) { - held[at] = append(held[at], origin) - queue = append(queue, visit{at: at, origin: origin}) +// numbered numbers each resource out names and lists by number the resources +// each leads to, sorted and once each, so a walk hashes no position. +func numbered(out map[DocumentPointer][]DocumentPointer) (map[DocumentPointer]int, [][]int) { + nodes := make(map[DocumentPointer]int, len(out)) + number := func(documentPointer DocumentPointer) int { + n, numberedBefore := nodes[documentPointer] + if !numberedBefore { + n = len(nodes) + nodes[documentPointer] = n + } + return n + } + targets := make(map[int][]int, len(out)) + for at, to := range out { + slices.SortFunc(to, comparePositions) + to = slices.Compact(to) + numbers := make([]int, len(to)) + for i, documentPointer := range to { + numbers[i] = number(documentPointer) } + targets[number(at)] = numbers + } + edges := make([][]int, len(nodes)) + for n, numbers := range targets { + edges[n] = numbers + } + return nodes, edges +} + +// reachWalk walks a reach graph from origins and answers of its last walk. A +// walk empties only what the last touched, so a walk per name costs its own +// steps. +type reachWalk struct { + graph reach + held []heldOrigins + queue []reachVisit +} + +// reachVisit is a resource a walk reached, and the origin it carried there, +// each by its number. +type reachVisit struct{ at, origin int } + +// newReachWalk returns a walk of graph that has walked from no origin. +func newReachWalk(graph reach) *reachWalk { + return &reachWalk{graph: graph, held: make([]heldOrigins, len(graph.nodes))} +} + +// from walks the graph from origins, resources, forgetting the last walk. +// Each resource keeps at most two distinct origins, which is enough to tell +// one other than itself, so each edge is walked at most twice for each +// resource it leaves, and each walk of one is a step of the binding's budget: +// past it, the walk stops short and the budget says so. A graph not known is +// not walked. +func (w *reachWalk) from(origins []DocumentPointer) { + for _, visit := range w.queue { + w.held[visit.at] = heldOrigins{} + } + w.queue = w.queue[:0] + if !w.graph.known { + // What no answer rests on, as it is not known, is not walked. + return } for _, documentPointer := range origins { - add(documentPointer, documentPointer) + if n, linked := w.graph.nodes[documentPointer]; linked { + w.add(n, n) + } } - for len(queue) > 0 && !r.work.over() { - visit := queue[0] - queue = queue[1:] - for _, next := range r.out[visit.at] { - if !r.work.spend(1) { + for taken := 0; taken < len(w.queue) && !w.graph.work.over(); taken++ { + visit := w.queue[taken] + for _, to := range w.graph.edges[visit.at] { + if !w.graph.work.spend(1) { break } - add(next, visit.origin) + w.add(to, visit.origin) } } - return func(resource DocumentPointer) bool { - return slices.ContainsFunc(held[resource], func(documentPointer DocumentPointer) bool { return documentPointer != resource }) +} + +// add holds origin at the resource at and queues the visit where +// heldOrigins.with adds it. Every resource held is queued, so the queue names +// what the next walk empties. +func (w *reachWalk) add(at, origin int) { + if grown, added := w.held[at].with(origin); added { + w.held[at] = grown + w.queue = append(w.queue, reachVisit{at: at, origin: origin}) + } +} + +// reachedByAnother reports whether the last walk reached resource from an +// origin other than resource itself. +func (w *reachWalk) reachedByAnother(resource DocumentPointer) bool { + n, linked := w.graph.nodes[resource] + return linked && w.held[n].other(n) +} + +// heldOrigins are the distinct origins a reachWalk met at a resource, by +// number, at most two, in the order it met them. +type heldOrigins struct { + first, second, count int +} + +// with returns held with origin added, and whether it was added: it is not +// where held already has two origins, or has origin. +func (held heldOrigins) with(origin int) (heldOrigins, bool) { + switch { + case held.count == 0: + held.first = origin + case held.count == 1 && held.first != origin: + held.second = origin + default: + return held, false } + held.count++ + return held, true +} + +// other reports whether held has an origin other than resource. +func (held heldOrigins) other(resource int) bool { + return held.count > 0 && held.first != resource || held.count > 1 && held.second != resource } // sharedNames returns each $dynamicAnchor name more than one document @@ -118,8 +202,8 @@ func sharedNames(ids *identifiers) map[string][]dynamicKey { delete(out, name) continue } - slices.SortFunc(keys, func(dynamicKeyValue, otherDynamicKey dynamicKey) int { - return int(dynamicKeyValue.doc) - int(otherDynamicKey.doc) + slices.SortFunc(keys, func(dynamicKey, otherDynamicKey dynamicKey) int { + return int(dynamicKey.doc) - int(otherDynamicKey.doc) }) } return out @@ -134,22 +218,23 @@ type dynamicReach struct { unknown map[dynamicKey]bool } -// dynamicReachOf walks reachValue once for each name shared declares, its +// dynamicReachOf walks reach once for each name shared declares, its // declaring resources the origins, in name order, so where the budget runs out // depends on no order of reading (JSON Schema 2020-12 §8.2.3.2: the outermost // resource of the dynamic scope declaring the name wins). Once the graph is not // known, the budget is spent or the binding's context is done, nothing more is // known. -func dynamicReachOf(ids *identifiers, b *bases, reachValue reach, shared map[string][]dynamicKey) dynamicReach { +func dynamicReachOf(ids *identifiers, bases *bases, reach reach, shared map[string][]dynamicKey) dynamicReach { out := dynamicReach{by: map[dynamicKey]bool{}, unknown: map[dynamicKey]bool{}} - stopped := !reachValue.known + stopped := !reach.known place := func(documentPointer DocumentPointer) (DocumentPointer, bool) { - if stopped = stopped || reachValue.work.over(); stopped { + if stopped = stopped || reach.work.over(); stopped { return DocumentPointer{}, false } - res, placed := b.holding(documentPointer) + res, placed := bases.holding(documentPointer) return res.root, placed } + walk := newReachWalk(reach) for _, name := range slices.Sorted(maps.Keys(shared)) { keys := shared[name] first := map[dynamicKey]DocumentPointer{} @@ -169,9 +254,9 @@ func dynamicReachOf(ids *identifiers, b *bases, reachValue reach, shared map[str if stopped { origins = nil } - reached := reachValue.reachers(origins) + walk.from(origins) for _, dynamicKey := range keys { - out.by[dynamicKey], out.unknown[dynamicKey] = reached(first[dynamicKey]), !known + out.by[dynamicKey], out.unknown[dynamicKey] = walk.reachedByAnother(first[dynamicKey]), !known } } return out diff --git a/compilers/openapi/internal/reftable/reach_edges_test.go b/compilers/openapi/internal/reftable/reach_edges_test.go index 4a0d51933..96e7ba758 100644 --- a/compilers/openapi/internal/reftable/reach_edges_test.go +++ b/compilers/openapi/internal/reftable/reach_edges_test.go @@ -42,7 +42,7 @@ func TestTable_ANestedResourceOfADocumentNoPassReachesLeadsNowhere(t *testing.T) assert.True(t, reached.Reached, "in a reached document the outer resource reaches the nested one") passed, unreached := anchorOf(" A: {$ref: 'a.yaml#/$defs/T'}\n Z: {$ref: 'z.yaml#/S'}\n") - require.True(t, unreached, "a.yaml is read, and no pass that stands reaches it") + require.True(t, unreached, "a.yaml is read, and no pass that remains reaches it") require.Equal(t, 2, passed.Count) assert.False(t, passed.Reached, "a document no pass reaches leads nowhere") } diff --git a/compilers/openapi/internal/reftable/reach_test.go b/compilers/openapi/internal/reftable/reach_test.go index 42d4912a3..29926df27 100644 --- a/compilers/openapi/internal/reftable/reach_test.go +++ b/compilers/openapi/internal/reftable/reach_test.go @@ -6,6 +6,8 @@ package reftable_test import ( "encoding/json/jsontext" "fmt" + "math" + "runtime" "strings" "testing" @@ -32,12 +34,12 @@ func reachConfig() reftable.Config { // anchoredChain is n anchored resources, each `$ref`ing the next and each // writing a `$recursiveRef`. -func anchoredChain(n int) string { +func anchoredChain(count int) string { var b strings.Builder b.WriteString(head + "components:\n schemas:\n") - for i := range n { + for i := range count { fmt.Fprintf(&b, " R%d: {$schema: '%s', $id: 'https://x.test/r%d', $recursiveAnchor: true, properties: {r: {$recursiveRef: '#'}}", i, reachDraft, i) - if i+1 < n { + if i+1 < count { fmt.Fprintf(&b, ", $ref: 'https://x.test/r%d'", i+1) } b.WriteString("}\n") @@ -96,7 +98,7 @@ func TestBind_TheRecursiveReachGrowsLinearly(t *testing.T) { // TestRecursiveAnchor_AWalkTheBudgetCutsKnowsNothing pins every cut of the // reading of a chain of anchored resources: a table the budget ran out in, -// the walk over its resources included, knows of no verdict, so every +// the walk over its resources included, knows of no answer, so every // reference resting on one is kept. func TestRecursiveAnchor_AWalkTheBudgetCutsKnowsNothing(t *testing.T) { t.Parallel() @@ -117,7 +119,7 @@ func TestRecursiveAnchor_AWalkTheBudgetCutsKnowsNothing(t *testing.T) { // TestRecursiveAnchor_AReferenceTheMergeBoundHidesTheResourceOfKnowsNothing // pins that a reference site whose resource a merge past the bound may hide, -// in another document, leaves the walk short of an edge, so no verdict it +// in another document, leaves the walk short of an edge, so no answer it // gives is known, though neither the source nor the budget is cut. func TestRecursiveAnchor_AReferenceTheMergeBoundHidesTheResourceOfKnowsNothing(t *testing.T) { t.Parallel() @@ -175,9 +177,9 @@ const onePlacement = 6 // document's resource `$ref`ing the second's, which `$ref`s one resource of // its own for each name, each declaring its name and writing a `$dynamicRef` // to it: a graph of resources that grows with the names. -func dynamicNames(n int) (spec string, other string) { +func dynamicNames(count int) (spec string, other string) { var top, low, each strings.Builder - for i := range n { + for i := range count { fmt.Fprintf(&top, "n%d: {$dynamicAnchor: n%d}, ", i, i) fmt.Fprintf(&low, "p%d: {$ref: 'https://x.test/l%d'}, ", i, i) fmt.Fprintf(&each, "L%d: {$id: 'https://x.test/l%d', properties: {r: {$dynamicRef: '#n%d'}}, "+ @@ -198,10 +200,10 @@ func dynamicNames(n int) (spec string, other string) { // second document is reached by a resource of the first. func TestTable_ANameSeveralDocumentsDeclareIsWalkedOncePerName(t *testing.T) { t.Parallel() - steps := func(n int) (*reftable.ReferenceTargetTable, int) { - spec, other := dynamicNames(n) + steps := func(count int) (*reftable.ReferenceTargetTable, int) { + spec, other := dynamicNames(count) table := bound(t, spec, withDocuments(map[string]string{"other.yaml": other})) - require.False(t, table.Exhausted(), "n=%d", n) + require.False(t, table.Exhausted(), "n=%d", count) return table, table.Steps() } _, s100 := steps(100) @@ -221,6 +223,35 @@ func TestTable_ANameSeveralDocumentsDeclareIsWalkedOncePerName(t *testing.T) { } } +// TestTable_TheWalksOfManyNamesAllocateWhatOneWalkDoes pins that the walk of +// each name several documents declare empties and reuses what the walk before +// it held: the bytes a binding allocates grow about twice with a doubling of +// the names, where the steps, each name's walk over a graph growing with the +// names, grow about four times, as the bytes did while each walk held its own. +// It is not parallel, as the count is the process's, and takes the least of +// three counts, since anything else allocating only adds to one. +func TestTable_TheWalksOfManyNamesAllocateWhatOneWalkDoes(t *testing.T) { + allocated := func(count int) uint64 { + spec, other := dynamicNames(count) + cfg := withDocuments(map[string]string{"other.yaml": other}) + var stats runtime.MemStats + least := uint64(math.MaxUint64) + for range 3 { + src := openapitest.YAMLDocument(t, spec) + runtime.ReadMemStats(&stats) + before := stats.TotalAlloc + table := reftable.Bind(t.Context(), src, cfg) + runtime.ReadMemStats(&stats) + require.False(t, table.Exhausted(), "n=%d", count) + least = min(least, stats.TotalAlloc-before) + } + return least + } + a100, a200, a400 := allocated(100), allocated(200), allocated(400) + require.Less(t, a100, a200) + assert.LessOrEqual(t, a400-a200, 5*(a200-a100)/2, "bytes at 100, 200, 400: %d, %d, %d", a100, a200, a400) +} + // TestTable_ANameTheBudgetCutsTheWalkOfIsNotKnown pins every cut of the // reading of names two documents declare: a table the budget ran out in, the // walks over its resources included, knows no name's declarations whole. @@ -285,13 +316,13 @@ func TestBind_AReferenceToADynamicRefThatReadsAsARefEndsWhereItEnds(t *testing.T assert.Equal(t, reftable.Resolved, referenceSite.Chain.Status, site) assert.Equal(t, pet, referenceSite.Chain.End, site) } - referenceSiteValue := entryAt(t, table, "/components/schemas/S") - assert.Equal(t, "$ref", referenceSiteValue.Keyword) - assert.Equal(t, pet, referenceSiteValue.Chain.End, "the chain of a $ref onto the static $dynamicRef runs through it") - assert.Equal(t, 2, referenceSiteValue.Chain.Hops) + referenceSite := entryAt(t, table, "/components/schemas/S") + assert.Equal(t, "$ref", referenceSite.Keyword) + assert.Equal(t, pet, referenceSite.Chain.End, "the chain of a $ref onto the static $dynamicRef runs through it") + assert.Equal(t, 2, referenceSite.Chain.Hops) // A truly dynamic reference is no entry. dyn := bound(t, head+"components:\n schemas:\n Pet: {$dynamicAnchor: pet}\n D: {$dynamicRef: '#pet'}\n", self) - _, ok := dyn.Entry(documentPointerAt("/components/schemas/D")) + _, ok := dyn.ReferenceSiteAt(documentPointerAt("/components/schemas/D")) assert.False(t, ok, "a reference naming a dynamic anchor is dynamic") } diff --git a/compilers/openapi/internal/reftable/reads.go b/compilers/openapi/internal/reftable/reads.go index 9fccad4bb..21f446559 100644 --- a/compilers/openapi/internal/reftable/reads.go +++ b/compilers/openapi/internal/reftable/reads.go @@ -53,9 +53,9 @@ func (r *reads) hold(name string, from DocID) { // unread reports whether a read of name asked for by from would be the // first: neither the document's read nor this asker's refusal is known. -func (r *reads) unread(docsValue *docs, name, from string) bool { +func (r *reads) unread(docs *docs, name, from string) bool { _, barred := r.barred[ask{name, from}] - return !barred && docsValue.unread(name) + return !barred && docs.unread(name) } // open returns the document named name, as the document from may read it: @@ -64,24 +64,24 @@ func (r *reads) unread(docsValue *docs, name, from string) bool { // first, or failed to, since what such a document may reach turns on where // both were read from, and a failure says what lies at an address. A refusal // to from alone is kept for from alone. -func (r *reads) open(docsValue *docs, name, from string) (DocID, error) { - askValue := ask{name, from} - if err, ok := r.barred[askValue]; ok { +func (r *reads) open(docs *docs, name, from string) (DocID, error) { + ask := ask{name, from} + if err, ok := r.barred[ask]; ok { return 0, err } - _, opened := docsValue.byName[name] - _, failed := docsValue.failed[name] - if (opened || failed) && OverNetwork(from) && !r.judged[askValue] { - r.judged[askValue] = true - if err := docsValue.judge(name, from); err != nil { - r.barred[askValue] = err + _, opened := docs.byName[name] + _, failed := docs.failed[name] + if (opened || failed) && OverNetwork(from) && !r.judged[ask] { + r.judged[ask] = true + if err := docs.judge(name, from); err != nil { + r.barred[ask] = err return 0, err } } - r.judged[askValue] = true - id, err := docsValue.open(name, from) + r.judged[ask] = true + id, err := docs.open(name, from) if barred := (*BarredError)(nil); errors.As(err, &barred) { - r.barred[askValue] = err + r.barred[ask] = err } return id, err } @@ -90,11 +90,11 @@ func (r *reads) open(docsValue *docs, name, from string) (DocID, error) { // which declares a URI from asks for: the source and from itself always, // any other where from is not read from the network or Config.Open judges // that it may, as a declaration answers only an asker that could read it. -func (r *reads) admits(docsValue *docs, decl, from DocID) bool { - if decl == Source || decl == from || !OverNetwork(docsValue.name(from)) { +func (r *reads) admits(docs *docs, decl, from DocID) bool { + if decl == Source || decl == from || !OverNetwork(docs.name(from)) { return true } - _, err := r.open(docsValue, docsValue.name(decl), docsValue.name(from)) + _, err := r.open(docs, docs.name(decl), docs.name(from)) return err == nil } @@ -105,28 +105,28 @@ func (r *reads) admits(docsValue *docs, decl, from DocID) bool { // location to request. Each is read for each document that asked, in one // order. A failure is kept for the hop that asks again (docs.open, // reads.open). -func (r *reads) drain(docsValue *docs, identifyAll func(), declares func(uri string, from DocID) bool) { +func (r *reads) drain(docs *docs, identifyAll func(), declares func(uri string, from DocID) bool) { var urls []string for _, name := range slices.Sorted(maps.Keys(r.held)) { if OverNetwork(name) { urls = append(urls, name) continue } - r.readFor(docsValue, name, func(DocID) bool { return true }) + r.readFor(docs, name, func(DocID) bool { return true }) } identifyAll() for _, name := range urls { - r.readFor(docsValue, name, func(from DocID) bool { return !declares(name, from) }) + r.readFor(docs, name, func(from DocID) bool { return !declares(name, from) }) } identifyAll() clear(r.held) } // readFor reads name for each document that held it and wants says reads it. -func (r *reads) readFor(docsValue *docs, name string, wants func(from DocID) bool) { +func (r *reads) readFor(docs *docs, name string, wants func(from DocID) bool) { for _, from := range slices.Sorted(maps.Keys(r.held[name])) { if wants(from) { - _, _ = r.open(docsValue, name, docsValue.name(from)) + _, _ = r.open(docs, name, docs.name(from)) } } } diff --git a/compilers/openapi/internal/reftable/reads_test.go b/compilers/openapi/internal/reftable/reads_test.go index 23298b533..db5415547 100644 --- a/compilers/openapi/internal/reftable/reads_test.go +++ b/compilers/openapi/internal/reftable/reads_test.go @@ -44,7 +44,7 @@ func TestBind_AReadBarredToOneAskerIsNoAnswerOfTheDocument(t *testing.T) { table := bound(t, head+"components:\n schemas:\n"+schemas, cfg) assert.Equal(t, reftable.Resolved, entryAt(t, table, "/components/schemas/B").Chain.Status) - referenceSite, ok := table.Entry(reftable.DocumentPointer{Doc: docNamed(t, table, evil), Pointer: "/X"}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: docNamed(t, table, evil), Pointer: "/X"}) require.True(t, ok) assert.Equal(t, reftable.Unresolved, referenceSite.Hop.Status) assert.Equal(t, why, referenceSite.Hop.Detail) diff --git a/compilers/openapi/internal/reftable/references.go b/compilers/openapi/internal/reftable/references.go index de10e13a6..a0faa5261 100644 --- a/compilers/openapi/internal/reftable/references.go +++ b/compilers/openapi/internal/reftable/references.go @@ -53,18 +53,18 @@ func (o *objects) hopAt(documentPointer DocumentPointer) (objectHop, objectKey) return o.hops[documentPointer], objectKey{} } ref := o.refAt(documentPointer) - objectHopValue, need := o.readRef(documentPointer.Doc, ref) + landed, need := o.readRef(documentPointer.Doc, ref) if need.kind != 0 { return objectHop{}, need } if o.b.work.over() { - objectHopValue = objectHop{hop: Hop{Ref: ref, Status: OverBudget}} + landed = objectHop{hop: Hop{Ref: ref, Status: OverBudget}} } - o.hops[documentPointer] = objectHopValue - if objectHopValue.hop.Reason == PendingExternalDocumentRead { + o.hops[documentPointer] = landed + if landed.hop.Reason == PendingExternalDocumentRead { o.b.wait.heldObjects = append(o.b.wait.heldObjects, documentPointer) } - return objectHopValue, objectKey{} + return landed, objectKey{} } // readRef reads ref, a reference object's $ref written in document id: its @@ -107,16 +107,16 @@ func (o *objects) readRef(id DocID, ref string) (objectHop, objectKey) { return objectHop{hop: hop, target: reading.state, mapping: node != nil && node.Kind == yaml.MappingNode, refs: refs}, objectKey{} } -// ofKind is objectHopValue read as a hop of a reference object of kind: -// objectHopValue itself where it lands on a mapping the grammar reads as an +// ofKind is objectHop read as a hop of a reference object of kind: +// objectHop itself where it lands on a mapping the grammar reads as an // object of kind, or raw YAML it reads as one, and NotObject where it lands on // anything else, such as an object of another kind, a schema, a value, or no // mapping. -func ofKind(objectHopValue objectHop, kind RefKind) Hop { - if objectHopValue.hop.Status != Resolved || objectHopValue.mapping && (objectHopValue.target == kind.state() || objectHopValue.target == sRaw) { - return objectHopValue.hop +func ofKind(objectHop objectHop, kind RefKind) Hop { + if objectHop.hop.Status != Resolved || objectHop.mapping && (objectHop.target == kind.state() || objectHop.target == sRaw) { + return objectHop.hop } - return Hop{Ref: objectHopValue.hop.Ref, Status: Unresolved, Reason: NotObject, Detail: kind.String()} + return Hop{Ref: objectHop.hop.Ref, Status: Unresolved, Reason: NotObject, Detail: kind.String()} } // settle settles the chain of the reference object key, and before it @@ -182,12 +182,12 @@ func (o *objects) chain(key objectKey) (DocumentPointer, objectKey) { on := map[DocumentPointer]int{} var end Chain for documentPointer := key.at; ; { - objectKeyValue := objectKey{at: documentPointer, kind: key.kind} - if chain, done := o.chains[objectKeyValue]; done { + keyed := objectKey{at: documentPointer, kind: key.kind} + if chain, done := o.chains[keyed]; done { end = chain break } - if o.b.wait.onObjects[objectKeyValue] { + if o.b.wait.onObjects[keyed] { o.waitOn(path, key.kind) return DocumentPointer{}, objectKey{} } @@ -259,42 +259,34 @@ func (o *objects) closeLoop(members []DocumentPointer, kind RefKind) { } } -// reference is the entry of the reference object objectKeyValue, its chain +// reference is the entry of the reference object objectKey, its chain // settled first, and reports that it waits for documents the pass has yet to // read. One the budget, or a cancel, left unsettled is OverBudget. -func (o *objects) reference(objectKeyValue objectKey) (Reference, bool) { - if _, done := o.chains[objectKeyValue]; !done && !o.b.wait.onObjects[objectKeyValue] { - o.settle(objectKeyValue) +func (o *objects) reference(objectKey objectKey) (Reference, bool) { + if _, done := o.chains[objectKey]; !done && !o.b.wait.onObjects[objectKey] { + o.settle(objectKey) } - if o.b.wait.onObjects[objectKeyValue] { + if o.b.wait.onObjects[objectKey] { return Reference{}, true } - _, key := o.b.docs.keyRefs[objectKeyValue.at] - reference := Reference{Site: objectKeyValue.at, Kind: objectKeyValue.kind, Hop: Hop{Status: OverBudget}, Chain: Chain{Status: OverBudget}, IsSecurityRequirementKey: key} - if chain, done := o.chains[objectKeyValue]; done { + _, key := o.b.docs.keyRefs[objectKey.at] + reference := Reference{Site: objectKey.at, Kind: objectKey.kind, Hop: Hop{Status: OverBudget}, Chain: Chain{Status: OverBudget}, IsSecurityRequirementKey: key} + if chain, done := o.chains[objectKey]; done { reference.Chain = chain } - if objectHop, read := o.hops[objectKeyValue.at]; read { - reference.Hop = ofKind(objectHop, objectKeyValue.kind) + if objectHop, read := o.hops[objectKey.at]; read { + reference.Hop = ofKind(objectHop, objectKey.kind) } return reference, false } -// compareObjects orders reference objects by position in docsValue, then by -// kind. -func compareObjects(docsValue *docs) func(objectKeyValue, otherObjectKey objectKey) int { - return func(objectKeyValue, otherObjectKey objectKey) int { - if c := docsValue.compare(objectKeyValue.at, otherObjectKey.at); c != 0 { - return c - } - return int(objectKeyValue.kind) - int(otherObjectKey.kind) - } -} - // settleAll answers each of keys, the reference objects binder.settle took, // in order of position and then kind, as settle answers sites. func (o *objects) settleAll(referenceTargetTable *ReferenceTargetTable, keys []objectKey) { - slices.SortFunc(keys, compareObjects(o.b.docs)) + positions := positionSortKeyWriterOf(o.b.docs) + sortByKeys(keys, func(key []byte, objectKey objectKey) []byte { + return positions.appendObject(key, objectKey.at, objectKey.kind) + }) for _, objectKey := range keys { if o.b.work.cancelled() { return @@ -317,11 +309,11 @@ func (o *objects) landings(referenceTargetTable *ReferenceTargetTable) []ObjectL site, reached := reach[objectKey] out = append(out, ObjectLanding{At: objectKey.at, Kind: objectKey.kind, Name: referenceTargetTable.docs[objectKey.at.Doc].Name, Site: site, Reached: reached}) } - slices.SortFunc(out, func(objectLanding, objectLandingValue ObjectLanding) int { - if c := o.b.docs.compare(objectLanding.At, objectLandingValue.At); c != 0 { - return c + slices.SortFunc(out, func(objectLanding, otherLanding ObjectLanding) int { + if order := o.b.docs.compare(objectLanding.At, otherLanding.At); order != 0 { + return order } - return int(objectLanding.Kind) - int(objectLandingValue.Kind) + return int(objectLanding.Kind) - int(otherLanding.Kind) }) return out } @@ -337,17 +329,15 @@ func (o *objects) attribute(referenceTargetTable *ReferenceTargetTable) map[obje starts = append(starts, reference) } } - slices.SortFunc(starts, func(reference, referenceValue Reference) int { - return compareObjects(o.b.docs)(objectKey{at: reference.Site, kind: reference.Kind}, objectKey{at: referenceValue.Site, kind: referenceValue.Kind}) - }) + sortByKeys(starts, positionSortKeyWriterOf(o.b.docs).appendReference) reach := map[objectKey]DocumentPointer{} for _, reference := range starts { for documentPointer := reference.Hop.Target; ; { - objectKeyValue := objectKey{at: documentPointer, kind: reference.Kind} - if _, seen := reach[objectKeyValue]; seen { + objectKey := objectKey{at: documentPointer, kind: reference.Kind} + if _, seen := reach[objectKey]; seen { break } - reach[objectKeyValue] = reference.Site + reach[objectKey] = reference.Site objectHop, ok := o.hops[documentPointer] if !ok || ofKind(objectHop, reference.Kind).Status != Resolved { break diff --git a/compilers/openapi/internal/reftable/references_test.go b/compilers/openapi/internal/reftable/references_test.go index f8c102538..c0f9276f4 100644 --- a/compilers/openapi/internal/reftable/references_test.go +++ b/compilers/openapi/internal/reftable/references_test.go @@ -213,27 +213,27 @@ func TestBind_CountsReferenceObjectWorkLinear(t *testing.T) { t.Parallel() alias := func(i int) string { return fmt.Sprintf(" P%d: {$ref: '#/components/parameters/P%d'}\n", i, i+1) } shapes := map[string]func(b *strings.Builder, n int){ - "a chain": func(b *strings.Builder, n int) { - for i := range n { + "a chain": func(b *strings.Builder, count int) { + for i := range count { b.WriteString(alias(i)) } - fmt.Fprintf(b, " P%d: {name: q, in: query}\n", n) + fmt.Fprintf(b, " P%d: {name: q, in: query}\n", count) }, - "references into one chain": func(b *strings.Builder, n int) { + "references into one chain": func(b *strings.Builder, count int) { for i := range 64 { b.WriteString(alias(i)) } b.WriteString(" P64: {name: q, in: query}\n") - for i := range n { + for i := range count { fmt.Fprintf(b, " U%d: {$ref: '#/components/parameters/P0'}\n", i) } }, } for name, shape := range shapes { - steps := func(n int) int { + steps := func(count int) int { var b strings.Builder b.WriteString(head + "components:\n parameters:\n") - shape(&b, n) + shape(&b, count) table := bound(t, b.String(), self) require.False(t, table.Exhausted(), name) return table.Steps() @@ -315,7 +315,8 @@ x-l: // TestPositionOrder_ReadsTheSourceFirstThenEachDocumentByName pins the order a // table reads positions in, whatever order it read the documents in: b.yaml -// is read first, as a.yaml is named only from it. +// is read first, as a.yaml is named only from it. Within a document a pointer +// is read as it is written, an array index by its number. func TestPositionOrder_ReadsTheSourceFirstThenEachDocumentByName(t *testing.T) { t.Parallel() table := bound(t, head+`components: @@ -335,6 +336,35 @@ func TestPositionOrder_ReadsTheSourceFirstThenEachDocumentByName(t *testing.T) { assert.Negative(t, order(reftable.DocumentPointer{Doc: a, Pointer: "/P"}, reftable.DocumentPointer{Doc: b, Pointer: "/A"})) assert.Negative(t, order(documentPointerAt("/z"), reftable.DocumentPointer{Doc: a, Pointer: "/A"})) assert.Negative(t, order(reftable.DocumentPointer{Doc: a, Pointer: "/A"}, reftable.DocumentPointer{Doc: a, Pointer: "/P"})) + assert.Negative(t, order(documentPointerAt("/allOf/9"), documentPointerAt("/allOf/10")), "an index by its number") +} + +// TestSortPositions_SortsAsTheTableReadsPositions pins the sort of positions +// by keys written once: it orders them as PositionOrder does, the source's +// first, then each other document's by its name, within one by pointer as it +// is written, whatever order they are given in. +func TestSortPositions_SortsAsTheTableReadsPositions(t *testing.T) { + t.Parallel() + table := bound(t, head+`components: + parameters: + A: {$ref: 'b.yaml#/P'} + B: {$ref: 'b.yaml#/Q'} +`, withDocuments(map[string]string{ + "a.yaml": "P: {name: a, in: query}\n", + "b.yaml": "P: {name: b, in: query}\nQ: {$ref: 'a.yaml#/P'}\n", + })) + b, ok := table.Find("b.yaml") + require.True(t, ok) + a, ok := table.Find("a.yaml") + require.True(t, ok) + want := []reftable.DocumentPointer{documentPointerAt("/allOf/9"), documentPointerAt("/allOf/10"), documentPointerAt("/z"), + {Doc: a, Pointer: "/A"}, {Doc: a, Pointer: "/P"}, {Doc: b, Pointer: "/A"}} + positions := []reftable.DocumentPointer{want[4], want[5], want[2], want[1], want[3], want[0]} + + reftable.SortPositions(table, positions) + + assert.Equal(t, want, positions) + assert.True(t, slices.IsSortedFunc(positions, reftable.PositionOrder(table)), "the order PositionOrder reads") } // TestRefKind_SpellsEachKind pins how a kind of object reads in a message. diff --git a/compilers/openapi/internal/reftable/entry_lands_test.go b/compilers/openapi/internal/reftable/referencesite_lands_test.go similarity index 85% rename from compilers/openapi/internal/reftable/entry_lands_test.go rename to compilers/openapi/internal/reftable/referencesite_lands_test.go index a2d10af48..8e685cad7 100644 --- a/compilers/openapi/internal/reftable/entry_lands_test.go +++ b/compilers/openapi/internal/reftable/referencesite_lands_test.go @@ -11,10 +11,10 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/reftable" ) -// TestEntry_LandsWhereItsHopResolvesOffALoop pins Lands: a hop that resolves +// TestReferenceSiteAt_LandsWhereItsHopResolvesOffALoop pins Lands: a hop that resolves // lands, unless its position is a member of a loop of $refs, whose chain // resolves nowhere, and a hop that does not resolve lands nowhere. -func TestEntry_LandsWhereItsHopResolvesOffALoop(t *testing.T) { +func TestReferenceSiteAt_LandsWhereItsHopResolvesOffALoop(t *testing.T) { t.Parallel() resolved := reftable.Hop{Status: reftable.Resolved} assert.True(t, reftable.ReferenceSite{Hop: resolved, Chain: reftable.Chain{Status: reftable.Resolved}}.Lands()) diff --git a/compilers/openapi/internal/reftable/resources.go b/compilers/openapi/internal/reftable/resources.go index 68bf50f59..6a2032955 100644 --- a/compilers/openapi/internal/reftable/resources.go +++ b/compilers/openapi/internal/reftable/resources.go @@ -140,17 +140,17 @@ func (ix *identifiers) readsDialects(id DocID) bool { return ix.named[id] || !ix.read[id] } -// document adds resourceValue, doc's own resource, and returns its index. +// document adds resource, doc's own resource, and returns its index. // Another document than the source declares the URI its $self names at its // root, as an $id declares one; the source is named by its $self directly // (names). -func (ix *identifiers) document(doc DocID, resourceValue resource) int32 { +func (ix *identifiers) document(doc DocID, resource resource) int32 { i := int32(len(ix.resources)) - ix.resources = append(ix.resources, resourceValue) + ix.resources = append(ix.resources, resource) ix.own[doc] = i - if resourceValue.based && doc != Source { - ix.declared[resourceValue.uri] = append(ix.declared[resourceValue.uri], resourceValue.root) - ix.byDoc[doc] = append(ix.byDoc[doc], resourceValue.uri) + if resource.based && doc != Source { + ix.declared[resource.uri] = append(ix.declared[resource.uri], resource.root) + ix.byDoc[doc] = append(ix.byDoc[doc], resource.uri) } return i } @@ -160,9 +160,9 @@ func (ix *identifiers) document(doc DocID, resourceValue resource) int32 { // names among it where node roots a resource (enterIn), and returns the index // of the resource its content is in, its own where it writes an identifier // naming another URI, and the dialect that content is read in. -func (ix *identifiers) declare(resourcesValue resources, in int32, at DocumentPointer, node *yaml.Node, enclosing string) (int32, string) { +func (ix *identifiers) declare(resources resources, in int32, at DocumentPointer, node *yaml.Node, enclosing string) (int32, string) { held := ix.resources[in] - entering := resourcesValue.enterIn(held, at, node, enclosing, func() bool { return heldAt(resourcesValue.docs, at) }) + entering := resources.enterIn(held, at, node, enclosing, func() bool { return heldAt(resources.docs, at) }) res := entering.res ix.truncated[at.Doc] = ix.truncated[at.Doc] || !entering.known switch { @@ -175,28 +175,28 @@ func (ix *identifiers) declare(resourcesValue resources, in int32, at DocumentPo case res != held: in = ix.own[at.Doc] } - view := resourcesValue.docs.list[at.Doc].view + view := resources.docs.list[at.Doc].view if entering.names { ix.dialects[at] = DialectRoot{At: at, URI: entering.dialect, Node: nodeview.Deref(node)} ix.named[at.Doc] = true } - rule := dialectRule(resourcesValue.docs, at.Doc, entering.dialect) + rule := dialectRule(resources.docs, at.Doc, entering.dialect) for _, keyword := range []string{"$anchor", "$dynamicAnchor", rule.Keyword} { name, ok := scalarOf(view.ChildByToken(nodeview.Deref(node), keyword)) switch { case keyword == rule.Keyword: - name, ok = fragmentName(rule, name, ok && rule.Fragments && !resourcesValue.ignoresIdentifier(at.Doc, node, rule)) + name, ok = fragmentName(rule, name, ok && rule.Fragments && !resources.ignoresIdentifier(at.Doc, node, rule)) case ok: ok = anchorNamed(rule, keyword, name) } if !ok { continue } - anchorKeyValue := anchorKey{root: res.root, name: name} - ix.anchors[anchorKeyValue] = append(ix.anchors[anchorKeyValue], at) + anchorKey := anchorKey{root: res.root, name: name} + ix.anchors[anchorKey] = append(ix.anchors[anchorKey], at) if keyword == "$dynamicAnchor" { - dynamicKeyValue := dynamicKey{doc: at.Doc, name: name} - ix.dynamic[dynamicKeyValue] = append(ix.dynamic[dynamicKeyValue], at) + dynamicKey := dynamicKey{doc: at.Doc, name: name} + ix.dynamic[dynamicKey] = append(ix.dynamic[dynamicKey], at) } } if rule.Recursive && recursiveAnchored(view, node) { @@ -212,8 +212,8 @@ func (ix *identifiers) declare(resourcesValue resources, in int32, at DocumentPo // only for a URI of its own origin, scheme, host and port, so it supplies no // other host's content; and a document read over http(s) is answered by no // file, nor by a source that is one, which it reaches by no route. -func admitted(docsValue *docs, decl, from DocID, uri string) bool { - declarer, asker := docsValue.list[decl].name, docsValue.list[from].name +func admitted(docs *docs, decl, from DocID, uri string) bool { + declarer, asker := docs.list[decl].name, docs.list[from].name switch { case decl == from: return true @@ -403,23 +403,23 @@ func (ix *identifiers) lookupAnchor(root DocumentPointer, name string) (Document // (ignoresIdentifier). rooted reports that node roots the resource returned, // whose root the caller sets. known is false where node writes no identifier // and merges past the view's bound, which may hide one. -func (r resources) enter(in resource, node *yaml.Node, rule DialectRule) (res resource, rooted, known bool) { +func (r resources) enter(in resource, node *yaml.Node, rule DialectRule) entering { if r.ignoresIdentifier(in.root.Doc, node, rule) { - return in, false, true + return entering{res: in, known: true} } id, written := r.idOf(in.root.Doc, node, rule.Keyword) if !written { - return in, false, r.docs.list[in.root.Doc].view.Expanded(nodeview.Deref(node)) + return entering{res: in, known: r.docs.list[in.root.Doc].view.Expanded(nodeview.Deref(node))} } uri, part, ok := r.identify(id, in.uri) switch { case !ok || uri == in.uri: - return in, false, true + return entering{res: in, known: true} case r.names(in.root.Doc, uri): - return r.document(in.root.Doc), false, true + return entering{res: r.document(in.root.Doc), known: true} default: detached := in.detached || fragment.Absolute(part) || strings.HasPrefix(part, "/") - return resource{uri: uri, namedByDollarID: true, detached: detached}, true, true + return entering{res: resource{uri: uri, namedByDollarID: true, detached: detached}, rooted: true, known: true} } } @@ -431,8 +431,8 @@ func (r resources) names(id DocID, uri string) bool { if uri == name || uri == r.docs.list[id].self { return true } - u, err := url.Parse(name) - return err == nil && len(u.Scheme) > 1 && uri == NormalURI(u) + parsed, err := url.Parse(name) + return err == nil && len(parsed.Scheme) > 1 && uri == NormalURI(parsed) } // identify is the URI an $id of id names, written where the base is base, and @@ -458,53 +458,53 @@ func (r resources) identify(id, base string) (uri, part string, ok bool) { // location, such as a file's path. An absolute result is spelled as RFC 3986 // §6.2.2 normalizes one (NormalURI), so two spellings of one identifier match. func (r resources) resolveURI(ref, base string) (string, bool) { - b, err := url.Parse(base) - if err != nil || len(b.Scheme) < 2 { + parsedBase, err := url.Parse(base) + if err != nil || len(parsedBase.Scheme) < 2 { named, ok := r.docs.locate(ref, base) - if u, err := url.Parse(named); ok && err == nil && len(u.Scheme) > 1 { - return NormalURI(u), true + if parsed, err := url.Parse(named); ok && err == nil && len(parsed.Scheme) > 1 { + return NormalURI(parsed), true } return named, ok } - u, err := url.Parse(ref) + parsed, err := url.Parse(ref) if err != nil { return "", false } - return NormalURI(b.ResolveReference(u)), true + return NormalURI(parsedBase.ResolveReference(parsed)), true } -// NormalURI is the absolute URI u spelled as RFC 3986 §6.2.2 normalizes it, +// NormalURI is the absolute URI uri spelled as RFC 3986 §6.2.2 normalizes it, // and an http or https one as §6.2.3 does too: its scheme and host in lower // case; each escape of an unreserved character decoded and every other one's // hex in upper case (normalEscapes), before its dot segments are removed, so // an escaped dot segment is removed and a second pass changes nothing; and // for http and https an empty path made "/", and an empty or default port // dropped. An empty query's "?" and a host's final dot stay. -func NormalURI(u *url.URL) string { - n := *u - n.Host = strings.ToLower(n.Host) - if n.Opaque != "" { - return normalEscapes(n.String()) - } - path := removeDots(normalEscapes(n.EscapedPath())) - if n.Scheme == "http" || n.Scheme == "https" { - n.Host = strings.TrimSuffix(strings.TrimSuffix(n.Host, ":"), defaultPort(n.Scheme)) +func NormalURI(uri *url.URL) string { + normal := *uri + normal.Host = strings.ToLower(normal.Host) + if normal.Opaque != "" { + return normalEscapes(normal.String()) + } + path := removeDots(normalEscapes(normal.EscapedPath())) + if normal.Scheme == "http" || normal.Scheme == "https" { + normal.Host = strings.TrimSuffix(strings.TrimSuffix(normal.Host, ":"), defaultPort(normal.Scheme)) path = cmp.Or(path, "/") } - hasQuery, hasFragment := n.ForceQuery || n.RawQuery != "", n.Fragment != "" - rawQuery, rawFragment := n.RawQuery, n.EscapedFragment() + hasQuery, hasFragment := normal.ForceQuery || normal.RawQuery != "", normal.Fragment != "" + rawQuery, rawFragment := normal.RawQuery, normal.EscapedFragment() // A path of "/" has String write the authority's "//" wherever the URL // wrote one, an empty host's included, which is then trimmed to the "/". - n.Path, n.RawPath, n.RawQuery, n.ForceQuery, n.Fragment, n.RawFragment = "/", "", "", false, "", "" - var b strings.Builder - b.WriteString(strings.TrimSuffix(n.String(), "/") + path) + normal.Path, normal.RawPath, normal.RawQuery, normal.ForceQuery, normal.Fragment, normal.RawFragment = "/", "", "", false, "", "" + var builder strings.Builder + builder.WriteString(strings.TrimSuffix(normal.String(), "/") + path) if hasQuery { - b.WriteString("?" + normalEscapes(rawQuery)) + builder.WriteString("?" + normalEscapes(rawQuery)) } if hasFragment { - b.WriteString("#" + normalEscapes(rawFragment)) + builder.WriteString("#" + normalEscapes(rawFragment)) } - return b.String() + return builder.String() } // defaultPort is the port RFC 3986 §6.2.3 has an http or https URL default @@ -516,22 +516,22 @@ func defaultPort(scheme string) string { return ":80" } -// removeDots is the path p, escaped and holding no escape of a dot, with its +// removeDots is the path path, escaped and holding no escape of a dot, with its // dot segments removed as RFC 3986 §5.2.4 removes them: "." is no segment, -// ".." takes the one before it away, and either ending p leaves p ending in +// ".." takes the one before it away, and either ending path leaves path ending in // "/". -func removeDots(p string) string { - if !strings.Contains(p, ".") { - return p +func removeDots(path string) string { + if !strings.Contains(path, ".") { + return path } - segments := strings.Split(p, "/") + segments := strings.Split(path, "/") out := make([]string, 0, len(segments)) - for i, s := range segments { + for i, segment := range segments { switch { - case s == "..": + case segment == "..": out = out[:max(len(out)-1, min(len(out), 1))] - case s != ".": - out = append(out, s) + case segment != ".": + out = append(out, segment) continue } if i == len(segments)-1 { @@ -541,57 +541,57 @@ func removeDots(p string) string { return strings.Join(out, "/") } -// normalEscapes is s with each percent-encoding of an unreserved character +// normalEscapes is text with each percent-encoding of an unreserved character // decoded and every other one's hex digits in upper case (RFC 3986 §6.2.2.1, // §6.2.2.2). An encoding of any other character, such as "%2F", keeps its // meaning, so it stays encoded, and a '%' opening none, which an opaque URI // or a query may hold, stays as written. -func normalEscapes(s string) string { - var b strings.Builder - for i := 0; i < len(s); i++ { - c, ok := escaped(s, i) +func normalEscapes(text string) string { + var builder strings.Builder + for i := 0; i < len(text); i++ { + decoded, ok := escaped(text, i) switch { case !ok: - b.WriteByte(s[i]) + builder.WriteByte(text[i]) continue - case unreserved(c): - b.WriteByte(c) + case unreserved(decoded): + builder.WriteByte(decoded) default: - b.WriteString(strings.ToUpper(s[i : i+3])) + builder.WriteString(strings.ToUpper(text[i : i+3])) } i += 2 } - return b.String() + return builder.String() } -// escaped is the byte the percent-encoding at s[i] spells, and false where +// escaped is the byte the percent-encoding at text[i] spells, and false where // none starts there. -func escaped(s string, i int) (byte, bool) { - if s[i] != '%' || i+2 >= len(s) { +func escaped(text string, i int) (byte, bool) { + if text[i] != '%' || i+2 >= len(text) { return 0, false } - hi, okHi := hexValue(s[i+1]) - lo, okLo := hexValue(s[i+2]) + hi, okHi := hexValue(text[i+1]) + lo, okLo := hexValue(text[i+2]) return hi<<4 | lo, okHi && okLo } -// hexValue is the value of the hex digit c, and false for a byte that is none. -func hexValue(c byte) (byte, bool) { +// hexValue is the value of the hex digit digit, and false for a byte that is none. +func hexValue(digit byte) (byte, bool) { switch { - case c >= '0' && c <= '9': - return c - '0', true - case c >= 'a' && c <= 'f': - return c - 'a' + 10, true - case c >= 'A' && c <= 'F': - return c - 'A' + 10, true + case digit >= '0' && digit <= '9': + return digit - '0', true + case digit >= 'a' && digit <= 'f': + return digit - 'a' + 10, true + case digit >= 'A' && digit <= 'F': + return digit - 'A' + 10, true default: return 0, false } } -// unreserved reports whether c is an unreserved character of RFC 3986 §2.3. -func unreserved(c byte) bool { - return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte("-._~", c) >= 0 +// unreserved reports whether character is an unreserved character of RFC 3986 §2.3. +func unreserved(character byte) bool { + return character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || character >= '0' && character <= '9' || strings.IndexByte("-._~", character) >= 0 } // idOf is the identifier node writes in document id under keyword, and whether @@ -663,17 +663,18 @@ func (r resources) holding(documentPointer DocumentPointer, path []*yaml.Node, s if state != sSchema && state != sLoose && (i < len(path)-1 || !schema) { continue } - enteringValue := entering{dialect: dialect} + entering := entering{dialect: dialect} if named { - enteringValue = r.enterIn(res, DocumentPointer{Doc: documentPointer.Doc}, node, dialect, func() bool { return held }) + entering = r.enterIn(res, DocumentPointer{Doc: documentPointer.Doc}, node, dialect, func() bool { return held }) } else { - enteringValue.res, enteringValue.rooted, enteringValue.known = r.enter(res, node, rule) + entering = r.enter(res, node, rule) + entering.dialect = dialect } - known = known && enteringValue.known - if enteringValue.rooted { - enteringValue.res.root = DocumentPointer{Doc: documentPointer.Doc, Pointer: jsontext.Pointer(prefix(documentPointer.Pointer, i))} + known = known && entering.known + if entering.rooted { + entering.res.root = DocumentPointer{Doc: documentPointer.Doc, Pointer: jsontext.Pointer(prefix(documentPointer.Pointer, i))} } - res, dialect = enteringValue.res, enteringValue.dialect + res, dialect = entering.res, entering.dialect } return res, known } diff --git a/compilers/openapi/internal/reftable/resources_test.go b/compilers/openapi/internal/reftable/resources_test.go index 6fa5bfb0f..0b3cfa62a 100644 --- a/compilers/openapi/internal/reftable/resources_test.go +++ b/compilers/openapi/internal/reftable/resources_test.go @@ -156,10 +156,10 @@ func TestBind_ReadsAMappingValueNamingNoComponentAsAReference(t *testing.T) { require.True(t, ok) assert.Equal(t, reftable.NoAnchor, mapping.Hop.Reason, "an anchor of the document's resource, read in d's") for _, value := range []string{"y", "y#"} { - mappingValue, ok := table.Mapping(disc, value) + mapping, ok := table.Mapping(disc, value) require.True(t, ok, "%q names no component, so it is a URI reference", value) - require.Equal(t, reftable.Resolved, mappingValue.Hop.Status, value) - assert.Equal(t, documentPointerAt("/components/schemas/Y"), mappingValue.Hop.Target, "%q is read against d's resource", value) + require.Equal(t, reftable.Resolved, mapping.Hop.Status, value) + assert.Equal(t, documentPointerAt("/components/schemas/Y"), mapping.Hop.Target, "%q is read against d's resource", value) } _, ok = table.Mapping(disc, "Y") assert.False(t, ok, "a value naming a component is read by name, not by the table") @@ -351,8 +351,8 @@ func TestBind_AReferenceInANetworkDocumentReadsOnlyTheNetwork(t *testing.T) { back := withDocuments(map[string]string{"https://h/b.yaml": "B: {$ref: 'file:///dir/spec.yaml#/components/schemas/T'}\n"}) back.Self, back.Locate = "file:///dir/spec.yaml", resolving.Locate table = bound(t, head+"components:\n schemas:\n A: {$ref: 'https://h/b.yaml#/B'}\n T: {type: string}\n", back) - referenceSiteValue, ok := table.Entry(reftable.DocumentPointer{Doc: 1, Pointer: "/B"}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: 1, Pointer: "/B"}) require.True(t, ok) - assert.Equal(t, "the document it names could not be read: "+reftable.OffNetwork, referenceSiteValue.Hop.Why(), + assert.Equal(t, "the document it names could not be read: "+reftable.OffNetwork, referenceSite.Hop.Why(), "the source, named back from the network by its own location") } diff --git a/compilers/openapi/internal/reftable/rounds_internal_test.go b/compilers/openapi/internal/reftable/rounds_internal_test.go index 04b436795..50be85ddc 100644 --- a/compilers/openapi/internal/reftable/rounds_internal_test.go +++ b/compilers/openapi/internal/reftable/rounds_internal_test.go @@ -23,14 +23,14 @@ func TestGoOn_ARoundThatChangesNothingEndsOnTheBudget(t *testing.T) { t.Fatal(err) } cfg := Config{Self: "https://x.test/spec.yaml", Limit: budget.AtMost(100)} - workValue := &work{ctx: t.Context(), steps: budget.New(cfg.Limit)} - docs := newDocs(&src, cfg, workValue) - b := newBinder(cfg, docs, workValue, newIdentifiers(resources{docs}.document(Source)), newReads()) + work := &work{ctx: t.Context(), steps: budget.New(cfg.Limit)} + docs := newDocs(&src, cfg, work) + binder := newBinder(cfg, docs, work, newIdentifiers(resources{docs}.document(Source)), newReads()) rounds := 0 - for ; rounds < 1_000 && !b.work.over(); rounds++ { - b.reads.hold("https://x.test/held.yaml", Source) - goOn(b) + for ; rounds < 1_000 && !binder.work.over(); rounds++ { + binder.reads.hold("https://x.test/held.yaml", Source) + goOn(binder) } - assert.True(t, b.work.over(), "the budget ends rounds that change nothing") + assert.True(t, binder.work.over(), "the budget ends rounds that change nothing") assert.LessOrEqual(t, rounds, 101, "one step a round") } diff --git a/compilers/openapi/internal/reftable/self_test.go b/compilers/openapi/internal/reftable/self_test.go index 573486027..a2e9878b1 100644 --- a/compilers/openapi/internal/reftable/self_test.go +++ b/compilers/openapi/internal/reftable/self_test.go @@ -41,13 +41,13 @@ func TestBind_ASelfIsADocumentsBaseAndName(t *testing.T) { require.Equal(t, reftable.Resolved, referenceSite.Chain.Status, site) assert.Equal(t, reftable.Source, referenceSite.Chain.End.Doc, "%s names the source by its $self", site) } - referenceSiteValue := entryAt(t, table, "/components/schemas/W") - require.Equal(t, reftable.Resolved, referenceSiteValue.Chain.Status, "a relative reference is read against the $self") - assert.Equal(t, "https://e.test/api/local/other.yaml", table.Document(referenceSiteValue.Chain.End.Doc).Name) - assert.Equal(t, "https://e.test/o/other.yaml", table.Document(referenceSiteValue.Chain.End.Doc).Self) + referenceSite := entryAt(t, table, "/components/schemas/W") + require.Equal(t, reftable.Resolved, referenceSite.Chain.Status, "a relative reference is read against the $self") + assert.Equal(t, "https://e.test/api/local/other.yaml", table.Document(referenceSite.Chain.End.Doc).Name) + assert.Equal(t, "https://e.test/o/other.yaml", table.Document(referenceSite.Chain.End.Doc).Self) otherReferenceSite := entryAt(t, table, "/components/schemas/Y") require.Equal(t, reftable.Resolved, otherReferenceSite.Chain.Status, "another document's $self is declared at its root") - assert.Equal(t, referenceSiteValue.Chain.End, otherReferenceSite.Chain.End) + assert.Equal(t, referenceSite.Chain.End, otherReferenceSite.Chain.End) relative := bound(t, "openapi: 3.2.0\n$self: sub/x.yaml\n", reftable.Config{Self: "/r/spec.yaml", Locate: resolving.Locate}) assert.Equal(t, "/r/sub/x.yaml", relative.Document(reftable.Source).Self, "a relative $self is read against the document") @@ -80,7 +80,7 @@ func TestBind_AMappedLocationIsJudgedWhereAFetchedDocumentReadsIt(t *testing.T) }}) var why string - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { if referenceSite.Hop.Status == reftable.Unresolved { why = referenceSite.Hop.Why() } @@ -156,8 +156,8 @@ func TestBind_AMappedURLUnderABaseIsJudgedWhereItLands(t *testing.T) { referenceSite := entryAt(t, table, "/components/schemas/S") require.Equal(t, reftable.Resolved, referenceSite.Chain.Status) assert.Equal(t, "/files/b.yaml", table.Document(referenceSite.Chain.End.Doc).Name, "read where the mapping puts it") - referenceSiteValue := entryAt(t, table, "/components/schemas/F") - assert.Equal(t, reftable.Unresolved, referenceSiteValue.Chain.Status, "a fetched document is mapped onto no file") + siteF := entryAt(t, table, "/components/schemas/F") + assert.Equal(t, reftable.Unresolved, siteF.Chain.Status, "a fetched document is mapped onto no file") assert.Equal(t, []string{"/files/b.yaml", "https://n.test/net.yaml"}, opened) } @@ -181,7 +181,7 @@ func TestBind_AMappedNameIsOpenedWhereMapPutsIt(t *testing.T) { return openapitest.YAMLDocument(t, "B: {type: string}\n"), nil }}) - a := entryAt(t, table, "/components/schemas/A") - assert.Equal(t, reftable.Resolved, a.Chain.Status) + entry := entryAt(t, table, "/components/schemas/A") + assert.Equal(t, reftable.Resolved, entry.Chain.Status) assert.Equal(t, []string{"/local/b.yaml"}, opened) } diff --git a/compilers/openapi/internal/reftable/table.go b/compilers/openapi/internal/reftable/table.go index 30e993206..f6c522862 100644 --- a/compilers/openapi/internal/reftable/table.go +++ b/compilers/openapi/internal/reftable/table.go @@ -16,6 +16,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/budget" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" ) // MaxSteps bounds the work the load phase lets one table cost: each node @@ -105,6 +106,10 @@ type DialectRule struct { // the drafts before 2019-09 ignore every keyword beside one. IgnoresRefFields bool NamesNone bool + // Schema is the rows a schema read in the dialect is read with, which read + // a key beside a link's allOf as every reader of a schema's keys reads it + // (specrules.SchemaRules.ReadsValue). The zero rows define no keyword. + Schema specrules.SchemaRules } // ErrEmptyDocument is the failure of Config.Open, or of the tree it returns, @@ -140,9 +145,9 @@ type work struct { steps budget.Budget } -// spend charges n steps and reports whether the binding may go on. -func (w *work) spend(n int) bool { - w.steps.Spend(n) +// spend charges amount steps and reports whether the binding may go on. +func (w *work) spend(amount int) bool { + w.steps.Spend(amount) return !w.over() } @@ -191,150 +196,157 @@ type binder struct { // It reads in passes, as whether a URI is an identifier turns on which // documents are read, and which are read on what the URIs name. A pass reruns // only when what it reached changes a URI it asked for, and only the last -// stands, so no declaration order reaches an answer (reread); each reads what +// remains, so no declaration order reaches an answer (reread); each reads what // none before it did (identifiers.commit). func Bind(ctx context.Context, src *yaml.Node, cfg Config) *ReferenceTargetTable { - workValue := &work{ctx: ctx, steps: budget.New(cfg.Limit)} - docs := newDocs(src, cfg, workValue) + work := &work{ctx: ctx, steps: budget.New(cfg.Limit)} + docs := newDocs(src, cfg, work) ids := newIdentifiers(resources{docs}.document(Source)) asked := newReads() for passes := 1; ; passes++ { - b := newBinder(cfg, docs, workValue, ids, asked) - referenceTargetTable := run(b) - if !reread(b) { + binder := newBinder(cfg, docs, work, ids, asked) + referenceTargetTable := run(binder) + if !reread(binder) { referenceTargetTable.passes = passes - return b.table(referenceTargetTable) + return binder.table(referenceTargetTable) } } } -// newBinder returns a pass over docsValue, knowing what ids holds and who asked +// newBinder returns a pass over docs, knowing what ids holds and who asked // for what (asked), and nothing else. -func newBinder(cfg Config, docsValue *docs, workValue *work, ids *identifiers, asked *reads) *binder { - docsValue.reached, docsValue.fresh = map[DocID]bool{Source: true}, nil +func newBinder(cfg Config, docs *docs, work *work, ids *identifiers, asked *reads) *binder { + docs.reached, docs.fresh = map[DocID]bool{Source: true}, nil clear(asked.held) - b := &binder{cfg: cfg, docs: docsValue, work: workValue, defs: definitions{docs: docsValue, work: workValue}, resources: resources{docsValue}, - find: newFinder(docsValue, workValue, ids), ids: ids, reads: asked, wait: newWaits(), hops: map[DocumentPointer]Hop{}, + created := &binder{cfg: cfg, docs: docs, work: work, defs: definitions{docs: docs, work: work}, resources: resources{docs}, + find: newFinder(docs, work, ids), ids: ids, reads: asked, wait: newWaits(), hops: map[DocumentPointer]Hop{}, chains: map[DocumentPointer]Chain{}, dyn: newDynamicRefs()} - b.objs = &objects{b: b, hops: map[DocumentPointer]objectHop{}, chains: map[objectKey]Chain{}} - return b + created.objs = &objects{b: created, hops: map[DocumentPointer]objectHop{}, chains: map[objectKey]Chain{}} + return created } -// run answers every reference the pass b reaches, going on past what it held +// run answers every reference the pass binder reaches, going on past what it held // for as long as that changes no answer it gave (goOn). A site still waiting // when the pass ends, as the budget or a change stopped it, has no entry: the // table says why (ReferenceTargetTable.Unread), or the pass is read again. -func run(b *binder) *ReferenceTargetTable { - b.find.walk(rootOf(Source, sDocument), false) - b.ids.begin() - referenceTargetTable := &ReferenceTargetTable{entries: map[DocumentPointer]ReferenceSite{}, mappings: map[mappingKey]Mapping{}, references: map[objectKey]Reference{}} +func run(binder *binder) *ReferenceTargetTable { + binder.find.walk(rootOf(Source, sDocument), false) + binder.ids.begin() + referenceTargetTable := &ReferenceTargetTable{referenceSites: map[DocumentPointer]ReferenceSite{}, mappings: map[mappingKey]Mapping{}, references: map[objectKey]Reference{}} for { - for more := true; more && !b.work.over(); more = b.find.walkPending() { - b.settle(referenceTargetTable) + for more := true; more && !binder.work.over(); more = binder.find.walkPending() { + binder.settle(referenceTargetTable) } - if b.work.over() || !goOn(b) { + if binder.work.over() { + binder.placeLoops() + return referenceTargetTable + } + if !goOn(binder) { break } } - b.placeLoops() + if !binder.stale { + closePureReferenceLoops(binder, referenceTargetTable) + } + binder.placeLoops() return referenceTargetTable } -// goOn reports whether the pass b, its walks done, goes on. It does while +// goOn reports whether the pass binder, its walks done, goes on. It does while // what the documents it reached declare changes no URI whose answer it kept // (settled): to read the documents it held (readHeld), to ask again the hops // that wait for a declaration of a document read and not yet reached, or, // once nothing is held or waits so, to settle what waited. A change ends it, // to be read again. Each round is a step of the work, so one that changes // nothing ends on the budget rather than going on unbounded. -func goOn(b *binder) bool { - b.work.steps.Spend(1) - if !settled(b) { - b.stale = true +func goOn(binder *binder) bool { + binder.work.steps.Spend(1) + if !settled(binder) { + binder.stale = true return false } switch { - case len(b.reads.held) > 0: - readHeld(b) - case len(b.wait.held) > 0 || len(b.wait.heldObjects) > 0 || len(b.wait.heldMappings) > 0: + case len(binder.reads.held) > 0: + readHeld(binder) + case len(binder.wait.held) > 0 || len(binder.wait.heldObjects) > 0 || len(binder.wait.heldMappings) > 0: // What waits, waits for a declaration of a document read and not yet // reached: while a drain reaches one, ask again. Once one reaches none, // the documents declaring what waits are reached, as a read reaches the // document it reads; once that reaches none either, what still waits is // read as a location. - b.wait.unwaited = b.wait.unwaited || !b.grew && !reachDeclaring(b) + binder.wait.unwaited = binder.wait.unwaited || !binder.grew && !reachDeclaring(binder) default: - return b.wait.release(b.find) + return binder.wait.release(binder.find) } - b.wait.requeue(b.find, b.hops, b.objs.hops) + binder.wait.requeue(binder.find, binder.hops, binder.objs.hops) return true } -// settled reports whether what the documents the pass b reached declare leaves +// settled reports whether what the documents the pass binder reached declare leaves // the declarations of every URI it asked for as it read them. Its first drain // commits what it reached whole, as a document an earlier pass reached may no // longer be. A pass only adds to what it reaches, so a later drain grows by // what it reached since (identifiers.grow), and commits only to judge a change. // Each document a drain counts is a step. -func settled(b *binder) bool { - b.find.identifyAll() - fresh := b.docs.takeFresh() - b.grew = len(fresh) > 0 - b.work.spend(len(fresh)) - if b.committed && !b.ids.grow(fresh) { +func settled(binder *binder) bool { + binder.find.identifyAll() + fresh := binder.docs.takeFresh() + binder.grew = len(fresh) > 0 + binder.work.spend(len(fresh)) + if binder.committed && !binder.ids.grow(fresh) { return true } - b.committed = true - b.work.spend(len(b.docs.reached)) - return !b.ids.commit(b.docs.reached) + binder.committed = true + binder.work.spend(len(binder.docs.reached)) + return !binder.ids.commit(binder.docs.reached) } -// reread reports whether the pass b, ended, must be run again: what the +// reread reports whether the pass binder, ended, must be run again: what the // documents it reached declare changed a URI it asked for, so an answer it gave // is not theirs (goOn). A document only an earlier pass reached declares // nothing. The pass the budget runs out in, wherever in it, is the last, and -// its answers stand, so no pass begins with nothing to spend. Only a location +// its answers remain, so no pass begins with nothing to spend. Only a location // whose own content leads to a declaration of its URI reads a pass again: a // reference a declaration may answer waits for it (goOn). -func reread(b *binder) bool { - return b.stale && !b.work.over() +func reread(binder *binder) bool { + return binder.stale && !binder.work.over() } -// readHeld reads the documents the pass b held back, as no document it read +// readHeld reads the documents the pass binder held back, as no document it read // answers for their names (OAS 3.1 §4.3.1), in a drain's two tiers // (reads.drain): a URL a document open declares to its asker is not read // while what waits for that declaration may wait. -func readHeld(b *binder) { - b.reads.drain(b.docs, b.find.identifyAll, func(uri string, from DocID) bool { - return !b.wait.unwaited && declaredFor(b, uri, from) +func readHeld(binder *binder) { + binder.reads.drain(binder.docs, binder.find.identifyAll, func(uri string, from DocID) bool { + return !binder.wait.unwaited && declaredFor(binder, uri, from) }) } // reachDeclaring reaches each document whose declaration a hop waits for, and // reports whether one was not reached before. -func reachDeclaring(b *binder) bool { +func reachDeclaring(binder *binder) bool { reached := false - for _, id := range b.wait.declaring { - reached = reached || !b.docs.reached[id] - b.docs.reach(id) + for _, id := range binder.wait.declaring { + reached = reached || !binder.docs.reached[id] + binder.docs.reach(id) } return reached } // declaredFor reports whether a document open declares uri to the document // asker (admitted, reads.admits). -func declaredFor(b *binder, uri string, asker DocID) bool { - for _, documentPointer := range b.ids.declared[uri] { - if admitted(b.docs, documentPointer.Doc, asker, uri) && b.reads.admits(b.docs, documentPointer.Doc, asker) { +func declaredFor(binder *binder, uri string, asker DocID) bool { + for _, documentPointer := range binder.ids.declared[uri] { + if admitted(binder.docs, documentPointer.Doc, asker, uri) && binder.reads.admits(binder.docs, documentPointer.Doc, asker) { return true } } return false } -// rootOf is the root at the root of document id, read at stateValue. -func rootOf(id DocID, stateValue state) root { - return root{at: DocumentPointer{Doc: id}, state: stateValue} +// rootOf is the root at the root of document id, read at state. +func rootOf(id DocID, state state) root { + return root{at: DocumentPointer{Doc: id}, state: state} } // settle answers every site, mapping value and reference object noted since it @@ -346,7 +358,7 @@ func (b *binder) settle(referenceTargetTable *ReferenceTargetTable) { sites, keys, objects := b.find.fresh, b.find.freshMappings, b.find.freshObjects b.find.fresh, b.find.freshMappings, b.find.freshObjects = nil, nil, nil b.work.spend(len(sites) + len(keys) + len(objects)) - slices.SortFunc(sites, b.docs.compare) + sortByKeys(sites, positionSortKeyWriterOf(b.docs).append) for _, site := range sites { if b.work.cancelled() { return @@ -357,7 +369,7 @@ func (b *binder) settle(referenceTargetTable *ReferenceTargetTable) { if chain, waits := b.chain(site); waits { b.wait.sites[site] = true } else { - referenceTargetTable.entries[site] = ReferenceSite{Site: site, Hop: b.hops[site], Chain: chain, Keyword: keywordAt(b, site)} + referenceTargetTable.referenceSites[site] = ReferenceSite{Site: site, Hop: b.hops[site], Chain: chain, Keyword: keywordAt(b, site)} } } slices.SortFunc(keys, mappingOrder(b.docs)) @@ -384,50 +396,50 @@ func (b *binder) settle(referenceTargetTable *ReferenceTargetTable) { // dynamic. A hop left unresolved lands nowhere. A name is asked only of a // document open, whose identifiers are read whole. It asks no context // between sites (GitHub #1968). -func landDynamic(b *binder) { - dynamic, recursive := b.find.freshDynamic, b.find.freshRecursive - b.find.freshDynamic, b.find.freshRecursive = nil, nil +func landDynamic(binder *binder) { + dynamic, recursive := binder.find.freshDynamic, binder.find.freshRecursive + binder.find.freshDynamic, binder.find.freshRecursive = nil, nil for _, dynamicSite := range dynamic { name, _, ok := DynamicFragment(dynamicSite.value) if !ok { continue } - b.find.identify(dynamicSite.at.Doc) - at := b.ids.dynamic[dynamicKey{doc: dynamicSite.at.Doc, name: name}] + binder.find.identify(dynamicSite.at.Doc) + at := binder.ids.dynamic[dynamicKey{doc: dynamicSite.at.Doc, name: name}] if len(at) != 1 { continue } - path, _ := b.docs.path(dynamicSite.at) - if hop := b.resolve(dynamicSite.at, path, "#"+url.PathEscape(name), true); hop.Status == Resolved && hop.Target == at[0] { - b.find.landOn(dynamicSite.at, hop) + path, _ := binder.docs.path(dynamicSite.at) + if hop := binder.resolve(dynamicSite.at, path, "#"+url.PathEscape(name), true); hop.Status == Resolved && hop.Target == at[0] { + binder.find.landOn(dynamicSite.at, hop) } } for _, site := range recursive { - path, _ := b.docs.path(site) - if hop := b.resolve(site, path, "#", true); hop.Status == Resolved { - b.find.landOn(site, hop) + path, _ := binder.docs.path(site) + if hop := binder.resolve(site, path, "#", true); hop.Status == Resolved { + binder.find.landOn(site, hop) } } } // mappingOrder orders mapping values by their discriminator's position in -// docsValue, then by value. -func mappingOrder(docsValue *docs) func(mappingKeyValue, otherMappingKey mappingKey) int { - return func(mappingKeyValue, otherMappingKey mappingKey) int { - if c := docsValue.compare(mappingKeyValue.at, otherMappingKey.at); c != 0 { - return c +// docs, then by value. +func mappingOrder(docs *docs) func(mappingKeyValue, otherMappingKey mappingKey) int { + return func(mappingKey, otherMappingKey mappingKey) int { + if order := docs.compare(mappingKey.at, otherMappingKey.at); order != 0 { + return order } - return cmp.Compare(mappingKeyValue.value, otherMappingKey.value) + return cmp.Compare(mappingKey.value, otherMappingKey.value) } } // table finishes referenceTargetTable: an entry for each position a chain // passed that no walk found, which only a budget cutting the walks leaves, the -// loops, the landings, and the verdicts of the budget and of the merge bound. +// loops, the landings, and the answers of the budget and of the merge bound. func (b *binder) table(referenceTargetTable *ReferenceTargetTable) *ReferenceTargetTable { for documentPointer, chain := range b.chains { - if _, found := referenceTargetTable.entries[documentPointer]; !found { - referenceTargetTable.entries[documentPointer] = ReferenceSite{Site: documentPointer, Hop: b.hops[documentPointer], Chain: chain, Keyword: keywordAt(b, documentPointer)} + if _, found := referenceTargetTable.referenceSites[documentPointer]; !found { + referenceTargetTable.referenceSites[documentPointer] = ReferenceSite{Site: documentPointer, Hop: b.hops[documentPointer], Chain: chain, Keyword: keywordAt(b, documentPointer)} } } for objectKey, chain := range b.objs.chains { @@ -437,9 +449,9 @@ func (b *binder) table(referenceTargetTable *ReferenceTargetTable) *ReferenceTar IsSecurityRequirementKey: key} } } - referenceTargetTable.entryList = slices.SortedFunc(maps.Values(referenceTargetTable.entries), func(referenceSite, referenceSiteValue ReferenceSite) int { - return b.docs.compare(referenceSite.Site, referenceSiteValue.Site) - }) + keys := positionSortKeyWriterOf(b.docs) + referenceTargetTable.referenceSiteList = slices.Collect(maps.Values(referenceTargetTable.referenceSites)) + sortByKeys(referenceTargetTable.referenceSiteList, func(key []byte, referenceSite ReferenceSite) []byte { return keys.append(key, referenceSite.Site) }) referenceTargetTable.roots, referenceTargetTable.bases, referenceTargetTable.ids = b.find.roots, newBases(b.resources, b.ids), b.ids shared := sharedNames(b.ids) var graph reach @@ -451,10 +463,11 @@ func (b *binder) table(referenceTargetTable *ReferenceTargetTable) *ReferenceTar referenceTargetTable.loops, referenceTargetTable.steps, referenceTargetTable.limit, referenceTargetTable.exhausted = b.loops, b.work.steps.Spent(), b.work.steps.Limit(), b.work.steps.Exhausted() referenceTargetTable.dynamic = dynamicAnchorsOf(b.ids, referenceTargetTable.exhausted, reached) dialects := dialectsByDocument(withLandingRoots(b.find, b.ids.dialects)) + discriminators := discriminatorsByDocument(b.find.discriminators) for id, document := range b.docs.list { reached := b.docs.reached[DocID(id)] referenceTargetTable.docs = append(referenceTargetTable.docs, ReferencedDocument{Name: document.name, Self: document.self, Root: document.root, Unreached: !reached, - Dialects: dialects[DocID(id)]}) + Dialects: dialects[DocID(id)], Discriminators: discriminators[DocID(id)]}) referenceTargetTable.truncated = referenceTargetTable.truncated || reached && document.view.Exhausted() } reach := b.attribute(referenceTargetTable) @@ -467,11 +480,11 @@ func (b *binder) table(referenceTargetTable *ReferenceTargetTable) *ReferenceTar referenceTargetTable.landings = append(referenceTargetTable.landings, Landing{At: at, Name: referenceTargetTable.docs[at.Doc].Name, Site: holder, Reached: true}) } } - slices.SortFunc(referenceTargetTable.landings, func(landing, landingValue Landing) int { return b.docs.compare(landing.At, landingValue.At) }) + keys = positionSortKeyWriterOf(b.docs) + sortByKeys(referenceTargetTable.landings, func(key []byte, landing Landing) []byte { return keys.append(key, landing.At) }) referenceTargetTable.objLandings = b.objs.landings(referenceTargetTable) - referenceTargetTable.refList = slices.SortedFunc(maps.Values(referenceTargetTable.references), func(reference, referenceValue Reference) int { - return compareObjects(b.docs)(objectKey{at: reference.Site, kind: reference.Kind}, objectKey{at: referenceValue.Site, kind: referenceValue.Kind}) - }) + referenceTargetTable.refList = slices.Collect(maps.Values(referenceTargetTable.references)) + sortByKeys(referenceTargetTable.refList, keys.appendReference) return referenceTargetTable } @@ -490,7 +503,7 @@ func (b *binder) attribute(referenceTargetTable *ReferenceTargetTable) map[Docum starts = append(starts, start{from: from, first: hop.Target}) } } - for _, referenceSite := range referenceTargetTable.entries { + for _, referenceSite := range referenceTargetTable.referenceSites { add(referenceSite.Site, referenceSite.Hop) } for _, mapping := range referenceTargetTable.mappings { @@ -499,11 +512,9 @@ func (b *binder) attribute(referenceTargetTable *ReferenceTargetTable) map[Docum for _, expansion := range b.find.expansions { add(expansion.from, Hop{Status: Resolved, Target: expansion.to}) } - slices.SortFunc(starts, func(startValue, otherStart start) int { - if c := b.docs.compare(startValue.from, otherStart.from); c != 0 { - return c - } - return b.docs.compare(startValue.first, otherStart.first) + keys := positionSortKeyWriterOf(b.docs) + sortByKeys(starts, func(key []byte, start start) []byte { + return keys.append(keys.append(key, start.from), start.first) }) reach := map[DocumentPointer]DocumentPointer{} for _, start := range starts { @@ -523,18 +534,20 @@ func (b *binder) attribute(referenceTargetTable *ReferenceTargetTable) map[Docum } // ReferencedDocument is a document a table read: its name and its root node. -// Unreached reports that only a pass that did not stand asked for it, so that +// Unreached reports that only a pass that did not remain asked for it, so that // nothing the table holds is in it: a reference read it as a location before a // later document declared that URI. Dialects is each schema resource root in it -// that names its dialect, in pointer order. +// that names its dialect, in pointer order, and Discriminators each +// discriminator object a schema the walks read in it writes. type ReferencedDocument struct { Name string // Self is the URI the document's $self names, resolved against Name, or // empty for none: a second name of the document, and its base. - Self string - Root *yaml.Node - Dialects []DialectRoot - Unreached bool + Self string + Root *yaml.Node + Dialects []DialectRoot + Discriminators Discriminators + Unreached bool } // ReferenceTargetTable is every reference a source holds, a schema's $ref or a @@ -544,21 +557,21 @@ type ReferencedDocument struct { // make (bases), so one is not safe for concurrent use. Each list it gives is // sorted once, as it is built, in the order docs.compare reads positions in. type ReferenceTargetTable struct { - entries map[DocumentPointer]ReferenceSite - references map[objectKey]Reference - roots map[DocumentPointer]state - mappings map[mappingKey]Mapping - loops []Loop - landings []Landing - objLandings []ObjectLanding - entryList []ReferenceSite - refList []Reference - docs []ReferencedDocument - steps int - passes int - limit budget.Limit - exhausted bool - truncated bool + referenceSites map[DocumentPointer]ReferenceSite + references map[objectKey]Reference + roots map[DocumentPointer]state + mappings map[mappingKey]Mapping + loops []Loop + landings []Landing + objLandings []ObjectLanding + referenceSiteList []ReferenceSite + refList []Reference + docs []ReferencedDocument + steps int + passes int + limit budget.Limit + exhausted bool + truncated bool // bases remembers each walk Base and Resource make, filled as they // ask. It changes no answer, each being what a walk from the root gives, // and nothing guards it, as only the lowering asks, on one goroutine. @@ -568,19 +581,21 @@ type ReferenceTargetTable struct { dynamic map[dynamicKey]DynamicAnchor } -// Entry returns the entry of the $ref written at site, and false for a -// position the table read no $ref at: one writing none, or one the budget -// left unread. A nil table read none. -func (t *ReferenceTargetTable) Entry(site DocumentPointer) (ReferenceSite, bool) { +// ReferenceSiteAt returns the reference site of the $ref written at site, and +// false for a position the table read no $ref at: one writing none, or one the +// budget left unread. A nil table read none. +func (t *ReferenceTargetTable) ReferenceSiteAt(site DocumentPointer) (ReferenceSite, bool) { if t == nil { return ReferenceSite{}, false } - referenceSite, ok := t.entries[site] + referenceSite, ok := t.referenceSites[site] return referenceSite, ok } -// Entries returns every entry, ordered by site. -func (t *ReferenceTargetTable) Entries() []ReferenceSite { return slices.Clone(t.entryList) } +// ReferenceSites returns every reference site, ordered by site. +func (t *ReferenceTargetTable) ReferenceSites() []ReferenceSite { + return slices.Clone(t.referenceSiteList) +} // Mapping returns where the mapping value written by the discriminator at at // lands, and false for one the table did not read: a value naming a schema @@ -637,8 +652,8 @@ func (t *ReferenceTargetTable) DynamicAnchor(id DocID, name string) DynamicAncho if t == nil { return DynamicAnchor{Complete: true} } - if a, ok := t.dynamic[dynamicKey{doc: id, name: name}]; ok { - return a + if anchor, ok := t.dynamic[dynamicKey{doc: id, name: name}]; ok { + return anchor } return DynamicAnchor{Complete: !t.exhausted && !t.ids.truncated[id]} } @@ -682,31 +697,32 @@ type recursiveAnchors struct { } // recursiveAnchorsOf returns what the declarations ids holds say, by document, -// the resource of each read from b once, and which resource another declaring -// one reaches read over reachValue in one walk, so a $recursiveRef asks a +// the resource of each read from bases once, and which resource another declaring +// one reaches read over reach in one walk, so a $recursiveRef asks a // lookup rather than a read of every declaration. -func recursiveAnchorsOf(ids *identifiers, b *bases, reachValue reach) map[DocID]recursiveAnchors { +func recursiveAnchorsOf(ids *identifiers, bases *bases, reach reach) map[DocID]recursiveAnchors { out := make(map[DocID]recursiveAnchors, len(ids.recursive)) var origins []DocumentPointer for id, sites := range ids.recursive { - recursiveAnchorsValue := recursiveAnchors{sites: make(map[DocumentPointer]bool, len(sites)), reached: map[DocumentPointer]bool{}, - unplaced: !reachValue.known} + recursiveAnchors := recursiveAnchors{sites: make(map[DocumentPointer]bool, len(sites)), reached: map[DocumentPointer]bool{}, + unplaced: !reach.known} for _, site := range sites { - recursiveAnchorsValue.sites[site] = true - if !reachValue.known { - continue // no verdict is known, so none is read + recursiveAnchors.sites[site] = true + if !reach.known { + continue // no answer is known, so none is read } - res, known := b.holding(site) - recursiveAnchorsValue.reached[res.root] = false - recursiveAnchorsValue.unplaced = recursiveAnchorsValue.unplaced || !known + res, known := bases.holding(site) + recursiveAnchors.reached[res.root] = false + recursiveAnchors.unplaced = recursiveAnchors.unplaced || !known origins = append(origins, res.root) } - out[id] = recursiveAnchorsValue + out[id] = recursiveAnchors } - reached := reachValue.reachers(origins) + walk := newReachWalk(reach) + walk.from(origins) for _, recursiveAnchors := range out { for root := range recursiveAnchors.reached { - recursiveAnchors.reached[root] = reached(root) + recursiveAnchors.reached[root] = walk.reachedByAnother(root) } } return out diff --git a/compilers/openapi/internal/reftable/table_cuts_test.go b/compilers/openapi/internal/reftable/table_cuts_test.go index db6db87e2..ff4e2f2f2 100644 --- a/compilers/openapi/internal/reftable/table_cuts_test.go +++ b/compilers/openapi/internal/reftable/table_cuts_test.go @@ -35,7 +35,7 @@ func TestBind_AStaticDynamicRefAChainPassedInAnotherDocumentIsWordedAsOneAtEvery if !ok { continue } - referenceSite, ok := cut.Entry(reftable.DocumentPointer{Doc: docID, Pointer: "/S"}) + referenceSite, ok := cut.ReferenceSiteAt(reftable.DocumentPointer{Doc: docID, Pointer: "/S"}) if !ok { continue } @@ -43,11 +43,11 @@ func TestBind_AStaticDynamicRefAChainPassedInAnotherDocumentIsWordedAsOneAtEvery assert.Equal(t, "$dynamicRef", referenceSite.Keyword, "limit %d", limit) } assert.Positive(t, seen, "some cut holds an entry for it") - docIDValue, ok := full.Find("o.yaml") + docID, ok := full.Find("o.yaml") require.True(t, ok) - referenceSiteValue, ok := full.Entry(reftable.DocumentPointer{Doc: docIDValue, Pointer: "/S"}) + referenceSite, ok := full.ReferenceSiteAt(reftable.DocumentPointer{Doc: docID, Pointer: "/S"}) require.True(t, ok) - assert.Equal(t, reftable.Unresolved, referenceSiteValue.Hop.Status) + assert.Equal(t, reftable.Unresolved, referenceSite.Hop.Status) } // TestRecursiveAnchor_AWalkCutMidwayStopsAtTheBudget pins that the walk over diff --git a/compilers/openapi/internal/reftable/table_test.go b/compilers/openapi/internal/reftable/table_test.go index 63165a55a..4f861f996 100644 --- a/compilers/openapi/internal/reftable/table_test.go +++ b/compilers/openapi/internal/reftable/table_test.go @@ -45,7 +45,7 @@ func bound(t *testing.T, src string, cfg reftable.Config) *reftable.ReferenceTar // entryAt returns the entry the table holds at the source pointer site. func entryAt(t *testing.T, table *reftable.ReferenceTargetTable, site jsontext.Pointer) reftable.ReferenceSite { t.Helper() - referenceSite, ok := table.Entry(reftable.DocumentPointer{Pointer: site}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Pointer: site}) require.True(t, ok, "an entry at %s", site) return referenceSite } @@ -511,9 +511,9 @@ func TestBind_ReportsADocumentThatDoesNotParse(t *testing.T) { table := bound(t, "components:\n schemas:\n A: {$ref: 'bad.yaml#/x'}\n", cfg) - a := entryAt(t, table, "/components/schemas/A") - assert.Equal(t, reftable.Unparsable, a.Hop.Reason) - assert.Equal(t, "the document it names does not parse: yaml: line 1: did not find expected node content", a.Hop.Why()) + entry := entryAt(t, table, "/components/schemas/A") + assert.Equal(t, reftable.Unparsable, entry.Hop.Reason) + assert.Equal(t, "the document it names does not parse: yaml: line 1: did not find expected node content", entry.Hop.Why()) err := &reftable.UnparsableError{Err: parser} require.EqualError(t, err, "it does not parse: yaml: line 1: did not find expected node content") assert.ErrorIs(t, err, parser) @@ -560,7 +560,7 @@ func TestBind_ReadsOtherDocuments(t *testing.T) { back := entryAt(t, table, "/components/schemas/Back") assert.Equal(t, reftable.Chain{Status: reftable.Resolved, End: documentPointerAt("/components/schemas/Leaf"), Hops: 2}, back.Chain, "a chain back into the source ends there, past a $ref naming another document") - there, ok := table.Entry(reftable.DocumentPointer{Doc: back.Hop.Target.Doc, Pointer: "/S"}) + there, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: back.Hop.Target.Doc, Pointer: "/S"}) require.True(t, ok) assert.Equal(t, reftable.Chain{Status: reftable.Resolved, End: documentPointerAt("/components/schemas/Leaf"), Hops: 1}, there.Chain, "another document's $ref naming the source") for _, value := range []string{"other.yaml#/S", "other.yaml#/T", "#/components/schemas/Leaf"} { @@ -579,7 +579,7 @@ func TestBind_ReadsOtherDocuments(t *testing.T) { id, ok := table.Find("other.yaml") require.True(t, ok) assert.Equal(t, "other.yaml", table.Document(id).Name) - defs, ok := table.Entry(reftable.DocumentPointer{Doc: id, Pointer: "/T/properties/d"}) + defs, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: id, Pointer: "/T/properties/d"}) require.True(t, ok, "a site in raw YAML another document holds") assert.Equal(t, reftable.NoDefinition, defs.Hop.Reason, "raw YAML holds no ancestor's definitions") _, ok = table.Find("gone.yaml") diff --git a/compilers/openapi/internal/reftable/table_through_test.go b/compilers/openapi/internal/reftable/table_through_test.go index d0bb5b400..b6372c869 100644 --- a/compilers/openapi/internal/reftable/table_through_test.go +++ b/compilers/openapi/internal/reftable/table_through_test.go @@ -195,7 +195,7 @@ func TestBind_ReadsWhatAReferenceObjectResolvedTo(t *testing.T) { table := bound(t, throughSpec, throughConfig()) id, ok := table.Find("other.yaml") require.True(t, ok) - referenceSite, ok := table.Entry(reftable.DocumentPointer{Doc: id, Pointer: "/R/content/application~1json/schema/properties/n"}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: id, Pointer: "/R/content/application~1json/schema/properties/n"}) require.True(t, ok, "the site in what R resolved to is read") assert.Equal(t, reftable.DocumentPointer{Doc: id, Pointer: "/Elsewhere"}, referenceSite.Hop.Target, "read against the document holding it") } @@ -219,8 +219,8 @@ func TestBind_ReadsEverySchemaSiteOnce(t *testing.T) { " parameters:\n P: {$ref: '#/components/parameters/Q'}\n" + " responses:\n R:\n description: r\n headers: {x-h: {schema: {$ref: '#/components/schemas/A'}}}\n" table := bound(t, src, self) - sites := make([]jsontext.Pointer, 0, len(table.Entries())) - for _, referenceSite := range table.Entries() { + sites := make([]jsontext.Pointer, 0, len(table.ReferenceSites())) + for _, referenceSite := range table.ReferenceSites() { sites = append(sites, referenceSite.Site.Pointer) } assert.Equal(t, []jsontext.Pointer{"/components/responses/R/headers/x-h/schema", "/components/schemas/A", diff --git a/compilers/openapi/internal/reftable/tuples_test.go b/compilers/openapi/internal/reftable/tuples_test.go index e4eac8e17..51275d8aa 100644 --- a/compilers/openapi/internal/reftable/tuples_test.go +++ b/compilers/openapi/internal/reftable/tuples_test.go @@ -51,13 +51,13 @@ func TestTuples_AListOfItemsHoldsSchemas(t *testing.T) { referenceSite := entryAt(t, table, site) assert.Equal(t, reftable.Resolved, referenceSite.Hop.Status, "%s: %s", site, referenceSite.Hop.Why()) } - _, ok := table.Entry(documentPointerAt("/components/schemas/U/additionalItems")) + _, ok := table.ReferenceSiteAt(documentPointerAt("/components/schemas/U/additionalItems")) assert.False(t, ok, "beside one items schema additionalItems is no schema the table reads") plain := bound(t, src, self) assert.Empty(t, landingsAt(t, plain), "2020-12 reads no tuple in a list of items") for _, site := range []jsontext.Pointer{tuple + "/items/1", tuple + "/additionalItems"} { - _, ok := plain.Entry(documentPointerAt(site)) + _, ok := plain.ReferenceSiteAt(documentPointerAt(site)) assert.False(t, ok, "%s is no schema 2020-12 reads", site) } } @@ -138,8 +138,8 @@ func TestDialectRule_AFragmentIdentifierDeclaresByItsDialectsGrammar(t *testing. assert.Equal(t, reftable.DuplicateAnchor, twice.Hop.Reason, twice.Hop.Why()) plain := reftable.DialectRule{Keyword: "$id", Fragments: true, PlainFragments: true, Definitions: true} - referenceSiteValue := entryAt(t, bound(t, src("$id", ""), ruleFor(self, plain)), "/components/schemas/D/properties/x") - assert.Equal(t, reftable.BadPointer, referenceSiteValue.Hop.Reason, "a plain name opens with a letter: %s", referenceSiteValue.Hop.Why()) + referenceSite := entryAt(t, bound(t, src("$id", ""), ruleFor(self, plain)), "/components/schemas/D/properties/x") + assert.Equal(t, reftable.BadPointer, referenceSite.Hop.Reason, "a plain name opens with a letter: %s", referenceSite.Hop.Why()) } // TestDialectRule_AnEmbedderIgnoringARefsSiblingsRootsNothingThere pins a @@ -192,13 +192,13 @@ func TestDialectRule_AnIdentifierBesideARefNamesNothing(t *testing.T) { require.Equal(t, reftable.Resolved, referenceSite.Hop.Status, referenceSite.Hop.Why()) assert.Equal(t, documentPointerAt(c.p), referenceSite.Hop.Target, "the base p's $ref resolves against") for site, target := range map[jsontext.Pointer]jsontext.Pointer{"g": properties + "f", "h": properties + "p"} { - referenceSiteValue := entryAt(t, table, properties+site) + referenceSite := entryAt(t, table, properties+site) if !c.ignores { - require.Equal(t, reftable.Resolved, referenceSiteValue.Hop.Status, "%s: %s", site, referenceSiteValue.Hop.Why()) - assert.Equal(t, documentPointerAt(target), referenceSiteValue.Hop.Target, site) + require.Equal(t, reftable.Resolved, referenceSite.Hop.Status, "%s: %s", site, referenceSite.Hop.Why()) + assert.Equal(t, documentPointerAt(target), referenceSite.Hop.Target, site) continue } - assert.NotEqual(t, reftable.Resolved, referenceSiteValue.Hop.Status, "%s names what an ignored id would", site) + assert.NotEqual(t, reftable.Resolved, referenceSite.Hop.Status, "%s names what an ignored id would", site) } }) } @@ -233,7 +233,7 @@ func TestDialectRule_ReadsWhatADialectSpellsOtherwise(t *testing.T) { for _, site := range []jsontext.Pointer{"/components/schemas/T/properties/a", "/components/schemas/T/properties/b"} { assert.NotEqual(t, reftable.Resolved, entryAt(t, plain, site).Hop.Status, "%s reads as 2020-12 does", site) } - _, ok := plain.Entry(documentPointerAt("/components/schemas/T/definitions/Foo/properties/c")) + _, ok := plain.ReferenceSiteAt(documentPointerAt("/components/schemas/T/definitions/Foo/properties/c")) assert.False(t, ok, "a definitions entry is no schema 2020-12 reads") } @@ -280,7 +280,7 @@ func TestDialectRule_AWalkStartsInTheDialectAboveIt(t *testing.T) { table := bound(t, head+"components:\n schemas:\n S: {$ref: 'o.yaml#/definitions/A'}\n", draftRule(withDocuments(map[string]string{"o.yaml": other}))) doc := docNamed(t, table, "o.yaml") - referenceSite, ok := table.Entry(reftable.DocumentPointer{Doc: doc, Pointer: "/definitions/A/definitions/B"}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: doc, Pointer: "/definitions/A/definitions/B"}) require.True(t, ok, "the nested entry is a schema of the draft 4 document") assert.Equal(t, reftable.Resolved, referenceSite.Hop.Status, referenceSite.Hop.Why()) } @@ -313,7 +313,7 @@ func TestDialectRule_ANestedSchemaNamesItsDialectAtAResourceRoot(t *testing.T) { } assert.NotEqual(t, reftable.Resolved, entryAt(t, table, "/components/schemas/A/properties/u").Hop.Status, "a fragment id roots no resource, so its $schema names nothing and 2020-12 reads no anchor in it") - _, ok := table.Entry(documentPointerAt("/components/schemas/A/properties/p/definitions/X")) + _, ok := table.ReferenceSiteAt(documentPointerAt("/components/schemas/A/properties/p/definitions/X")) assert.False(t, ok, "a schema rooting no resource holds no definitions") } @@ -330,7 +330,7 @@ func TestDialectRule_AWalkEntersARootBelowWhereItStarts(t *testing.T) { draftRule(withDocuments(map[string]string{"o.yaml": other}))) doc := docNamed(t, table, "o.yaml") const x = "/$defs/A/properties/x" - referenceSite, ok := table.Entry(reftable.DocumentPointer{Doc: doc, Pointer: x + "/definitions/Y"}) + referenceSite, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: doc, Pointer: x + "/definitions/Y"}) require.True(t, ok, "the definitions entry is a schema of the draft 4 resource") require.Equal(t, reftable.Resolved, referenceSite.Hop.Status, referenceSite.Hop.Why()) assert.Equal(t, reftable.DocumentPointer{Doc: doc, Pointer: x + "/definitions/Z"}, referenceSite.Hop.Target) @@ -392,7 +392,7 @@ func TestDialectRule_ADocumentOfSchemasReadsItsDraftAtItsRoot(t *testing.T) { referenceSite := entryAt(t, table, "/components/schemas/S") require.Equal(t, reftable.Resolved, referenceSite.Hop.Status, referenceSite.Hop.Why()) assert.Equal(t, reftable.DocumentPointer{Doc: doc, Pointer: "/items/0"}, referenceSite.Hop.Target) - dep, ok := table.Entry(reftable.DocumentPointer{Doc: doc, Pointer: "/dependencies/a"}) + dep, ok := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: doc, Pointer: "/dependencies/a"}) require.True(t, ok, "a schema in dependencies is one the table reads") assert.Equal(t, reftable.Resolved, dep.Hop.Status, dep.Hop.Why()) } diff --git a/compilers/openapi/internal/reftable/typed/build_internal_test.go b/compilers/openapi/internal/reftable/typed/build_internal_test.go index 1d63964e2..38bc7a636 100644 --- a/compilers/openapi/internal/reftable/typed/build_internal_test.go +++ b/compilers/openapi/internal/reftable/typed/build_internal_test.go @@ -122,7 +122,9 @@ func decodedAt(t *testing.T, bd *Builder, src string, documentPointer reftable.D func TestMend_DecodesAgainAMappingTheParserReadAsFalse(t *testing.T) { t.Parallel() bd := NewBuilder(nil) - at := func(p string) reftable.DocumentPointer { return reftable.DocumentPointer{Pointer: jsontext.Pointer(p)} } + at := func(path string) reftable.DocumentPointer { + return reftable.DocumentPointer{Pointer: jsontext.Pointer(path)} + } decodedAt(t, bd, chainOf(3), at("/c")) held := bd.Bindings().At(at("/c/items")) require.NotNil(t, held) diff --git a/compilers/openapi/internal/reftable/typed/typed.go b/compilers/openapi/internal/reftable/typed/typed.go index a2c0a5c3b..5debd5b58 100644 --- a/compilers/openapi/internal/reftable/typed/typed.go +++ b/compilers/openapi/internal/reftable/typed/typed.go @@ -62,14 +62,14 @@ func (b *Bindings) Site(js *schemaRef) (reftable.DocumentPointer, bool) { return documentPointer, ok } -// Entry returns the table's entry for the $ref js writes, and false for a -// schema b does not know or one the table read no $ref at. -func (b *Bindings) Entry(js *schemaRef) (reftable.ReferenceSite, bool) { +// ReferenceSiteAt returns the table's reference site of the $ref js writes, +// and false for a schema b does not know or one the table read no $ref at. +func (b *Bindings) ReferenceSiteAt(js *schemaRef) (reftable.ReferenceSite, bool) { documentPointer, ok := b.Site(js) if !ok { return reftable.ReferenceSite{}, false } - return b.table.Entry(documentPointer) + return b.table.ReferenceSiteAt(documentPointer) } // RefKeyword returns the keyword js is a reference site under, which the @@ -87,7 +87,7 @@ func (b *Bindings) RefKeyword(js *schemaRef) string { if js.GetSchema().Ref != nil { return "$ref" } - if referenceSite, ok := b.Entry(js); ok && referenceSite.Keyword == "$dynamicRef" { + if referenceSite, ok := b.ReferenceSiteAt(js); ok && referenceSite.Keyword == "$dynamicRef" { return referenceSite.Keyword } return "" @@ -100,15 +100,15 @@ func (b *Bindings) RefSite(js *schemaRef) bool { return b.RefKeyword(js) != "" } // Declared returns the schema written where js's $ref lands, or nil where it // does not land on one. func (b *Bindings) Declared(js *schemaRef) *schemaRef { - s, _ := b.DeclaredAt(js) - return s + schema, _ := b.DeclaredAt(js) + return schema } // DeclaredAt returns what Declared does and the position its $ref lands at, // which names the document holding it; the zero position where it lands on // none. func (b *Bindings) DeclaredAt(js *schemaRef) (*schemaRef, reftable.DocumentPointer) { - referenceSite, ok := b.Entry(js) + referenceSite, ok := b.ReferenceSiteAt(js) if !ok || referenceSite.Hop.Status != reftable.Resolved { return nil, reftable.DocumentPointer{} } @@ -118,7 +118,7 @@ func (b *Bindings) DeclaredAt(js *schemaRef) (*schemaRef, reftable.DocumentPoint // End returns the schema the chain of $refs from js ends on, in whichever // document, or nil where it does not end on one. func (b *Bindings) End(js *schemaRef) *schemaRef { - referenceSite, ok := b.Entry(js) + referenceSite, ok := b.ReferenceSiteAt(js) if !ok || referenceSite.Chain.Status != reftable.Resolved { return nil } @@ -280,10 +280,10 @@ func (bd *Builder) Object(model any, kind reftable.RefKind, documentPointer reft if model == nil || kind == 0 { return } - objectSiteValue := objectSite{at: documentPointer, kind: kind} - bd.b.objectSites[model] = objectSiteValue - if _, held := bd.b.objects[objectSiteValue]; !held { - bd.b.objects[objectSiteValue] = model + objectSite := objectSite{at: documentPointer, kind: kind} + bd.b.objectSites[model] = objectSite + if _, held := bd.b.objects[objectSite]; !held { + bd.b.objects[objectSite] = model } } @@ -305,7 +305,7 @@ func (bd *Builder) Walk(ctx context.Context, js *schemaRef, documentPointer reft at := reftable.DocumentPointer{Doc: documentPointer.Doc, Pointer: documentPointer.Pointer + PointerOf(item.Location)} // Match returns only what its matcher does, and this one never fails. _ = item.Match(oas3.SchemaMatcher{ - Schema: func(s *schemaRef) error { bd.Schema(s, at); return nil }, + Schema: func(schemaRef *schemaRef) error { bd.Schema(schemaRef, at); return nil }, }) } } @@ -317,24 +317,24 @@ func (bd *Builder) Walk(ctx context.Context, js *schemaRef, documentPointer reft // a time copies it at each, which costs the square of a deep schema's depth. func PointerOf[T any](locations walk.Locations[T]) jsontext.Pointer { var out []byte - for _, l := range locations { - if l.ParentField != "" { - out = appendToken(out, l.ParentField) + for _, location := range locations { + if location.ParentField != "" { + out = appendToken(out, location.ParentField) } switch { - case l.ParentKey != nil: - out = appendToken(out, *l.ParentKey) - case l.ParentIndex != nil: - out = appendToken(out, strconv.Itoa(*l.ParentIndex)) + case location.ParentKey != nil: + out = appendToken(out, *location.ParentKey) + case location.ParentIndex != nil: + out = appendToken(out, strconv.Itoa(*location.ParentIndex)) } } return jsontext.Pointer(out) } -// appendToken appends token to the pointer spelled in b, escaped as +// appendToken appends token to the pointer spelled in key, escaped as // jsontext.Pointer.AppendToken escapes one. -func appendToken(b []byte, token string) []byte { - return append(b, jsontext.Pointer("").AppendToken(token)...) +func appendToken(key []byte, token string) []byte { + return append(key, jsontext.Pointer("").AppendToken(token)...) } // errNothingThere is why no schema is built for a landing whose document diff --git a/compilers/openapi/internal/reftable/typed/typed_test.go b/compilers/openapi/internal/reftable/typed/typed_test.go index b36c3793e..1ce0fdd2e 100644 --- a/compilers/openapi/internal/reftable/typed/typed_test.go +++ b/compilers/openapi/internal/reftable/typed/typed_test.go @@ -95,7 +95,7 @@ func TestBindings_AnswerByTheSchemaTheLoweringHolds(t *testing.T) { assert.Nil(t, b.Declared(u)) assert.Nil(t, b.End(u)) - _, ok = b.Entry(a) + _, ok = b.ReferenceSiteAt(a) assert.False(t, ok, "a schema writing no $ref has no entry") stranger := oas3.NewJSONSchemaFromReference("#/components/schemas/A") _, ok = b.Site(stranger) @@ -162,9 +162,9 @@ func TestBuilder_BuildsEachLandingOnce(t *testing.T) { assert.Equal(t, jsontext.Pointer("/x-lib/S"), built[0].Landing.At.Pointer) assert.Equal(t, jsontext.Pointer("/x-lib/S/properties/x"), built[1].Landing.At.Pointer) assert.Equal(t, jsontext.Pointer("/x-lib/T"), built[2].Landing.At.Pointer) - for _, builtValue := range built { - require.NoError(t, builtValue.Err) - assert.Same(t, builtValue.Schema, b.At(builtValue.Landing.At)) + for _, built := range built { + require.NoError(t, built.Err) + assert.Same(t, built.Schema, b.At(built.Landing.At)) } x, ok := built[0].Schema.GetSchema().GetProperties().Get("x") require.True(t, ok) @@ -210,18 +210,18 @@ func TestBindings_HoldsTheFirstObjectRecordedAtAPosition(t *testing.T) { bd.Object(header, reftable.RefHeader, documentPointer) bd.Object(nil, reftable.RefParameter, reftable.DocumentPointer{Pointer: "/x"}) bd.Object(&soa.ReferencedLink{}, 0, reftable.DocumentPointer{Pointer: "/y"}) - b := bd.Bindings() + bindings := bd.Bindings() - assert.Same(t, first, b.ObjectAt(documentPointer, reftable.RefParameter), "the first recorded is held") - assert.Same(t, header, b.ObjectAt(documentPointer, reftable.RefHeader), "another kind beside it") + assert.Same(t, first, bindings.ObjectAt(documentPointer, reftable.RefParameter), "the first recorded is held") + assert.Same(t, header, bindings.ObjectAt(documentPointer, reftable.RefHeader), "another kind beside it") assert.True(t, bd.HoldsObject(documentPointer, reftable.RefParameter)) assert.False(t, bd.HoldsObject(documentPointer, reftable.RefLink)) - at, kind, ok := b.ObjectSite(second) + at, kind, ok := bindings.ObjectSite(second) require.True(t, ok, "a wrapper not held is placed all the same") assert.Equal(t, documentPointer, at) assert.Equal(t, reftable.RefParameter, kind) - assert.Nil(t, b.ObjectAt(reftable.DocumentPointer{Pointer: "/x"}, reftable.RefParameter), "no wrapper, none held") - assert.Nil(t, b.ObjectAt(reftable.DocumentPointer{Pointer: "/y"}, 0), "no kind, none held") + assert.Nil(t, bindings.ObjectAt(reftable.DocumentPointer{Pointer: "/x"}, reftable.RefParameter), "no wrapper, none held") + assert.Nil(t, bindings.ObjectAt(reftable.DocumentPointer{Pointer: "/y"}, 0), "no kind, none held") } // TestBindings_ReadsTheReferenceAtAWrappersSite pins Reference: the table's @@ -246,16 +246,16 @@ components: bd.Object(q, reftable.RefParameter, reftable.DocumentPointer{Pointer: "/components/parameters/Q"}) other := &soa.ReferencedHeader{} bd.Object(other, reftable.RefHeader, reftable.DocumentPointer{Pointer: "/components/parameters/P"}) - b := bd.Bindings() + bindings := bd.Bindings() - reference, ok := b.Reference(p) + reference, ok := bindings.Reference(p) require.True(t, ok) assert.Equal(t, reftable.DocumentPointer{Pointer: "/components/parameters/Q"}, reference.Chain.End) - _, ok = b.Reference(q) + _, ok = bindings.Reference(q) assert.False(t, ok, "an inline object writes no reference") - _, ok = b.Reference(other) + _, ok = bindings.Reference(other) assert.False(t, ok, "read as another kind, the table read none") - _, ok = b.Reference(&soa.ReferencedParameter{}) + _, ok = bindings.Reference(&soa.ReferencedParameter{}) assert.False(t, ok, "a wrapper never recorded") } @@ -298,20 +298,20 @@ func TestPointerOf_CostsItsLength(t *testing.T) { // each time and cost four times. It is not parallel, as the count is the // process's. func TestBuild_CostsLinearInItsLandings(t *testing.T) { - cost := func(n int) uint64 { + cost := func(count int) uint64 { var b strings.Builder b.WriteString("openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n schemas:\n") - for i := range n { + for i := range count { fmt.Fprintf(&b, " S%d: {$ref: '#/x-lib/T%d'}\n", i, i) } b.WriteString("x-lib:\n") - for i := range n { + for i := range count { fmt.Fprintf(&b, " T%d: {type: string}\n", i) } var root yaml.Node require.NoError(t, yaml.Unmarshal([]byte(b.String()), &root)) table := reftable.Bind(t.Context(), &root, reftable.Config{Self: "spec.yaml"}) - require.Len(t, table.Landings(), n) + require.Len(t, table.Landings(), count) return allocated(func() { typed.NewBuilder(table).Build(t.Context()) }) } assert.Less(t, cost(2_000), 3*cost(1_000), "twice the landings, about twice the bytes") diff --git a/compilers/openapi/internal/reftable/types.go b/compilers/openapi/internal/reftable/types.go index f198da51f..5c249aa8b 100644 --- a/compilers/openapi/internal/reftable/types.go +++ b/compilers/openapi/internal/reftable/types.go @@ -9,6 +9,7 @@ import ( "strconv" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" ) // DocID names a document a table reads: Source, or one opened for a @@ -25,15 +26,16 @@ type DocumentPointer struct { Pointer jsontext.Pointer } -// comparePositions orders positions by document, then pointer: the order a -// table reads them in where they share a document or one is the source's. +// comparePositions orders positions by document, then pointer as it is +// written (provenance.ComparePointers): the order a table reads them in where +// they share a document or one is the source's. // Two other documents are ordered by name (docs.compare): a DocID numbers them // in the order the table first needed them, which a declaration order changes. -func comparePositions(documentPointer, documentPointerValue DocumentPointer) int { - if c := cmp.Compare(documentPointer.Doc, documentPointerValue.Doc); c != 0 { - return c +func comparePositions(documentPointer, otherDocumentPointer DocumentPointer) int { + if order := cmp.Compare(documentPointer.Doc, otherDocumentPointer.Doc); order != 0 { + return order } - return cmp.Compare(documentPointer.Pointer, documentPointerValue.Pointer) + return provenance.ComparePointers(documentPointer.Pointer, otherDocumentPointer.Pointer) } // PositionOrder returns the order referenceTargetTable reads positions in: the @@ -41,28 +43,28 @@ func comparePositions(documentPointer, documentPointerValue DocumentPointer) int // by it depends on no order documents were read in. func PositionOrder(referenceTargetTable *ReferenceTargetTable) func(documentPointer, documentPointerValue DocumentPointer) int { name := func(id DocID) string { return referenceTargetTable.docs[id].Name } - return func(documentPointer, documentPointerValue DocumentPointer) int { - return compareNamed(documentPointer, documentPointerValue, name) + return func(documentPointer, otherDocumentPointer DocumentPointer) int { + return compareNamed(documentPointer, otherDocumentPointer, name) } } -// compareNamed orders documentPointer and documentPointerValue as a table reads +// compareNamed orders documentPointer and otherDocumentPointer as a table reads // them, documents named by name (PositionOrder, docs.compare). -func compareNamed(documentPointer, documentPointerValue DocumentPointer, name func(DocID) string) int { - if c, ok := byName(documentPointer, documentPointerValue, name); ok { - return c +func compareNamed(documentPointer, otherDocumentPointer DocumentPointer, name func(DocID) string) int { + if order, ok := byName(documentPointer, otherDocumentPointer, name); ok { + return order } - return comparePositions(documentPointer, documentPointerValue) + return comparePositions(documentPointer, otherDocumentPointer) } -// byName orders documentPointer and documentPointerValue, positions in two +// byName orders documentPointer and otherDocumentPointer, positions in two // documents neither of which is the source, by the names name gives those // documents. -func byName(documentPointer, documentPointerValue DocumentPointer, name func(DocID) string) (int, bool) { - if documentPointer.Doc == documentPointerValue.Doc || documentPointer.Doc == Source || documentPointerValue.Doc == Source { +func byName(documentPointer, otherDocumentPointer DocumentPointer, name func(DocID) string) (int, bool) { + if documentPointer.Doc == otherDocumentPointer.Doc || documentPointer.Doc == Source || otherDocumentPointer.Doc == Source { return 0, false } - return cmp.Compare(name(documentPointer.Doc), name(documentPointerValue.Doc)), true + return cmp.Compare(name(documentPointer.Doc), name(otherDocumentPointer.Doc)), true } // Role is what a reference reads at the position it lands on. @@ -249,7 +251,7 @@ func (e ReferenceSite) Lands() bool { // Loop is a cycle of $refs: its members, ordered, and Site, where it is // reported: the least of them, in whichever document. Kind is the kind of -// object a loop of reference objects stands for, and zero for one of schema +// object a loop of reference objects names, and zero for one of schema // $refs. type Loop struct { Members []DocumentPointer @@ -257,12 +259,12 @@ type Loop struct { Kind RefKind } -// RefKind is the kind of object a Reference Object stands for, which the +// RefKind is the kind of object a Reference Object names, which the // position writing it reads and which its $ref must land on. The zero RefKind // is none: a schema's $ref. type RefKind uint8 -// The kinds of object a Reference Object can stand for, in the order a +// The kinds of object a Reference Object can name, in the order a // position reading several is settled in. const ( RefPathItem RefKind = iota + 1 diff --git a/compilers/openapi/internal/reftable/waits_test.go b/compilers/openapi/internal/reftable/waits_test.go index 384411d75..a00941464 100644 --- a/compilers/openapi/internal/reftable/waits_test.go +++ b/compilers/openapi/internal/reftable/waits_test.go @@ -43,7 +43,7 @@ func TestBind_AReferenceObjectWaitsForADeclarationOfADocumentRead(t *testing.T) // TestBind_ABudgetThatRunsOutInAPassWhoseDeclarationsChangedEndsThere pins that // a pass the budget ran out in is the last though what it reached changed a URI // it asked for: at each limit from the one that ends the first pass to the one -// below the least that begins a second, the first stands, and one step more +// below the least that begins a second, the first remains, and one step more // begins the second. The first pass of this input costs 62 to 66 steps of // budget; a second begun with none would answer nothing. func TestBind_ABudgetThatRunsOutInAPassWhoseDeclarationsChangedEndsThere(t *testing.T) { @@ -60,7 +60,7 @@ func TestBind_ABudgetThatRunsOutInAPassWhoseDeclarationsChangedEndsThere(t *test } for limit := 62; limit <= 66; limit++ { - assert.Equal(t, 1, passes(limit), "limit %d: the pass the budget ran out in stands", limit) + assert.Equal(t, 1, passes(limit), "limit %d: the pass the budget ran out in remains", limit) } assert.Equal(t, 2, passes(67), "a budget left after the first pass begins a second") } @@ -68,7 +68,7 @@ func TestBind_ABudgetThatRunsOutInAPassWhoseDeclarationsChangedEndsThere(t *test // TestBind_AThirdDeclarationOfADuplicateURIReadsThePassAgain pins that a URI // two documents declare, answered as declared twice, is kept as one the pass // asked for: a third declaration that a document read since brings changes what -// the pass was told of it, so the pass is read again and the table stands on a +// the pass was told of it, so the pass is read again and the table rests on a // pass that saw every declaration. The URI is no identifier of any of them // either way. func TestBind_AThirdDeclarationOfADuplicateURIReadsThePassAgain(t *testing.T) { @@ -86,5 +86,5 @@ func TestBind_AThirdDeclarationOfADuplicateURIReadsThePassAgain(t *testing.T) { assert.Equal(t, []string{"o.yaml", "p.yaml", "q.yaml"}, *reads) assert.Equal(t, reftable.DuplicateID, entryAt(t, table, "/components/schemas/R").Hop.Reason) - assert.Equal(t, 2, table.Passes(), "the pass that saw the third declaration is the one that stands") + assert.Equal(t, 2, table.Passes(), "the pass that saw the third declaration is the one that remains") } diff --git a/compilers/openapi/internal/reftable/walk.go b/compilers/openapi/internal/reftable/walk.go index 7f08bf8a0..ada4580b5 100644 --- a/compilers/openapi/internal/reftable/walk.go +++ b/compilers/openapi/internal/reftable/walk.go @@ -59,38 +59,42 @@ type finder struct { objLandings map[objectKey]bool // tupled is each schema the parser's model cannot hold, by the schema // writing it (tupleOf). - tupled map[DocumentPointer]DocumentPointer - pending []root - covered map[root]bool - roots map[DocumentPointer]state + tupled map[DocumentPointer]DocumentPointer + // discriminators is each discriminator object a schema the walks read + // writes, by where it is written (noteDiscriminator). + discriminators map[DocumentPointer]*yaml.Node + pending []root + covered map[root]bool + roots map[DocumentPointer]state } // newFinder returns a finder over docs that has found nothing, noting what the // documents declare in ids. -func newFinder(docsValue *docs, workValue *work, ids *identifiers) *finder { - return &finder{docs: docsValue, ids: ids, work: workValue, sites: map[DocumentPointer]bool{}, mappingSites: map[mappingKey]bool{}, +func newFinder(docs *docs, work *work, ids *identifiers) *finder { + return &finder{docs: docs, ids: ids, work: work, sites: map[DocumentPointer]bool{}, mappingSites: map[mappingKey]bool{}, objects: map[objectKey]bool{}, landings: map[DocumentPointer]bool{}, objLandings: map[objectKey]bool{}, - tupled: map[DocumentPointer]DocumentPointer{}, covered: map[root]bool{}, roots: map[DocumentPointer]state{}} + tupled: map[DocumentPointer]DocumentPointer{}, discriminators: map[DocumentPointer]*yaml.Node{}, covered: map[root]bool{}, + roots: map[DocumentPointer]state{}} } -// walk reads every position below rootValue by the grammar, noting each schema position +// walk reads every position below from by the grammar, noting each schema position // that writes a $ref (a site), each discriminator mapping value that can name a // position (mapping), and each reference object (objects). A node an alias places at several positions is read at each, // as the parser reads it. With mark, each position read at a state is noted, so // a later root inside one already read is not read again; the source's own walk // from its root notes none, and reads its identifiers the first time it runs. -func (w *finder) walk(rootValue root, mark bool) { - if prev, seen := w.roots[rootValue.at]; !seen || rootValue.state < prev { - w.roots[rootValue.at] = rootValue.state +func (w *finder) walk(from root, mark bool) { + if prev, seen := w.roots[from.at]; !seen || from.state < prev { + w.roots[from.at] = from.state } - declaring := !mark && !w.ids.read[rootValue.at.Doc] + declaring := !mark && !w.ids.read[from.at.Doc] if !declaring { // The dialect roots a walk reads are those its document declares. - w.identify(rootValue.at.Doc) + w.identify(from.at.Doc) } - w.ids.read[rootValue.at.Doc] = w.ids.read[rootValue.at.Doc] || declaring - node := w.docs.node(rootValue.at) - stack := []frame{{node: node, at: rootValue.at, state: rootValue.state, dialect: startDialect(w, rootValue.at, node)}} + w.ids.read[from.at.Doc] = w.ids.read[from.at.Doc] || declaring + node := w.docs.node(from.at) + stack := []frame{{node: node, at: from.at, state: from.state, dialect: startDialect(w, from.at, node)}} for len(stack) > 0 && w.work.spend(1) { frame := stack[len(stack)-1] stack = stack[:len(stack)-1] @@ -153,88 +157,88 @@ func (w *finder) identifyAll() { } } -// declared notes the identifiers the schema at frameValue, holding node, -// declares, and returns frameValue as its children read it: in the resource its +// declared notes the identifiers the schema at frame, holding node, +// declares, and returns frame as its children read it: in the resource its // content is in. -func (w *finder) declared(node *yaml.Node, frameValue frame) frame { - if frameValue.state == sSchema || frameValue.state == sLoose { - frameValue.res, frameValue.dialect = w.ids.declare(resources{w.docs}, frameValue.res, frameValue.at, node, frameValue.dialect) +func (w *finder) declared(node *yaml.Node, frame frame) frame { + if frame.state == sSchema || frame.state == sLoose { + frame.res, frame.dialect = w.ids.declare(resources{w.docs}, frame.res, frame.at, node, frame.dialect) } - return frameValue + return frame } -// visit notes what the position frameValue, holding node, gives the table. -func (w *finder) visit(node *yaml.Node, frameValue frame) { - if frameValue.state == sSecurityRequirement { - w.requirementKeys(node, frameValue) +// visit notes what the position frame, holding node, gives the table. +func (w *finder) visit(node *yaml.Node, frame frame) { + if frame.state == sSecurityRequirement { + w.requirementKeys(node, frame) return } - if frameValue.state != sSchema { - w.objectOf(node, frameValue) + if frame.state != sSchema { + w.objectOf(node, frame) return } - if _, ok := w.docs.refOf(frameValue.at.Doc, node); ok && !w.sites[frameValue.at] { - w.sites[frameValue.at] = true - w.fresh = append(w.fresh, frameValue.at) + if _, ok := w.docs.refOf(frame.at.Doc, node); ok && !w.sites[frame.at] { + w.sites[frame.at] = true + w.fresh = append(w.fresh, frame.at) } - w.mappingsOf(node, frameValue.at) + w.mappingsOf(node, frame.at) } -// objectOf notes the position frameValue, holding node, as a reference object +// objectOf notes the position frame, holding node, as a reference object // of the kind its state reads, where it writes a $ref: a string one, read as // the model reads the mapping, a `<<` merging it in included. -func (w *finder) objectOf(node *yaml.Node, frameValue frame) { - kind, ok := refKinds[frameValue.state] +func (w *finder) objectOf(node *yaml.Node, frame frame) { + kind, ok := refKinds[frame.state] if !ok { return } - if _, refs := w.docs.refOf(frameValue.at.Doc, node); !refs { + if _, refs := w.docs.refOf(frame.at.Doc, node); !refs { return } - if objectKeyValue := (objectKey{at: frameValue.at, kind: kind}); !w.objects[objectKeyValue] { - w.objects[objectKeyValue] = true - w.freshObjects = append(w.freshObjects, objectKeyValue) + if objectKey := (objectKey{at: frame.at, kind: kind}); !w.objects[objectKey] { + w.objects[objectKey] = true + w.freshObjects = append(w.freshObjects, objectKey) } } // requirementKeys notes each key of the Security Requirement Object node, at -// frameValue, that names no securitySchemes component of the source, as a +// frame, that names no securitySchemes component of the source, as a // reference to a Security Scheme Object written where the key is, the key its // URI, where the document holding it reads a key as a URI (Config.KeysByURI). -func (w *finder) requirementKeys(node *yaml.Node, frameValue frame) { - if node.Kind != yaml.MappingNode || !w.docs.keysByURI(frameValue.at.Doc) { +func (w *finder) requirementKeys(node *yaml.Node, frame frame) { + if node.Kind != yaml.MappingNode || !w.docs.keysByURI(frame.at.Doc) { return } for _, pair := range nodeview.Pairs(node) { if w.docs.schemes[pair.Key] { continue } - at := frameValue.at.below(pair.Key) + at := frame.at.below(pair.Key) w.docs.keyRefs[at] = pair.Key - if objectKeyValue := (objectKey{at: at, kind: RefSecurityScheme}); !w.objects[objectKeyValue] { - w.objects[objectKeyValue] = true - w.freshObjects = append(w.freshObjects, objectKeyValue) + if objectKey := (objectKey{at: at, kind: RefSecurityScheme}); !w.objects[objectKey] { + w.objects[objectKey] = true + w.freshObjects = append(w.freshObjects, objectKey) } } } -// tupleOf notes each schema the schema at frameValue, holding node and read in -// frameValue's dialect, writes where the parser's model has no member to hold +// tupleOf notes each schema the schema at frame, holding node and read in +// frame's dialect, writes where the parser's model has no member to hold // one: each entry of an `items` written as a list the dialect reads as a tuple, // and the `additionalItems` beside it, its rest. The table builds a schema for // each, as for a landing, held by the schema writing it. -func (w *finder) tupleOf(node *yaml.Node, frameValue frame) { - schema := frameValue.state == sSchema || frameValue.state == sLoose - if !schema || !dialectRule(w.docs, frameValue.at.Doc, frameValue.dialect).Tuples || !listsItems(w.docs, frameValue.at.Doc, node) { +func (w *finder) tupleOf(node *yaml.Node, frame frame) { + schema := frame.state == sSchema || frame.state == sLoose + if !schema || !dialectRule(w.docs, frame.at.Doc, frame.dialect).Tuples || !listsItems(w.docs, frame.at.Doc, node) { return } - view := w.docs.list[frameValue.at.Doc].view - items := frameValue.at.below("items") + view := w.docs.list[frame.at.Doc].view + items := frame.at.below("items") for i := range nodeview.Deref(view.ChildByToken(node, "items")).Content { - w.tupled[items.below(strconv.Itoa(i))] = frameValue.at + w.tupled[items.below(strconv.Itoa(i))] = frame.at } if nodeview.Deref(view.ChildByToken(node, "additionalItems")) != nil { - w.tupled[frameValue.at.below("additionalItems")] = frameValue.at + w.tupled[frame.at.below("additionalItems")] = frame.at } } @@ -253,23 +257,23 @@ type expansion struct { from, to DocumentPointer } -// dynamicOf notes the dynamic reference the schema at frameValue, holding node -// and read in frameValue's dialect, writes: a $dynamicRef, which settle reads +// dynamicOf notes the dynamic reference the schema at frame, holding node +// and read in frame's dialect, writes: a $dynamicRef, which settle reads // as the $ref it spells or as dynamic (staticSites), and a $recursiveRef of "#" // where the dialect defines one (DialectRule.Recursive). Nothing but a // reference builds a schema the model does not hold, another document's or raw // YAML's (landed), and an expansion is one, so settle lands on what each // dynamic one names (landDynamic). -func (w *finder) dynamicOf(node *yaml.Node, frameValue frame) { - view := w.docs.list[frameValue.at.Doc].view - if ref, ok := dynamicRefValue(w.docs, frameValue.at.Doc, node); ok { - _, beside := w.docs.refOf(frameValue.at.Doc, node) - w.freshDynamic = append(w.freshDynamic, dynamicSite{at: frameValue.at, value: ref, beside: beside}) +func (w *finder) dynamicOf(node *yaml.Node, frame frame) { + view := w.docs.list[frame.at.Doc].view + if ref, ok := dynamicRefValue(w.docs, frame.at.Doc, node); ok { + _, beside := w.docs.refOf(frame.at.Doc, node) + w.freshDynamic = append(w.freshDynamic, dynamicSite{at: frame.at, value: ref, beside: beside}) return } ref, ok := scalarOf(view.ChildByToken(node, "$recursiveRef")) - if ok && strings.TrimSpace(ref) == "#" && dialectRule(w.docs, frameValue.at.Doc, frameValue.dialect).Recursive { - w.freshRecursive = append(w.freshRecursive, frameValue.at) + if ok && strings.TrimSpace(ref) == "#" && dialectRule(w.docs, frame.at.Doc, frame.dialect).Recursive { + w.freshRecursive = append(w.freshRecursive, frame.at) } } @@ -280,20 +284,22 @@ func (w *finder) landOn(from DocumentPointer, hop Hop) { w.expansions = append(w.expansions, expansion{from: from, to: hop.Target}) } -// mappingsOf notes each value of the discriminator the schema at at, holding -// node, writes that names no schema component of the source -// (Config.Components): a URI reference, with a fragment or without, as OpenAPI -// reads a value naming no schema. The parser reads none -// (docs/parser-library.md#mapping-unresolved), so each is bound here. -func (w *finder) mappingsOf(node *yaml.Node, at DocumentPointer) { - disc := DocumentPointer{Doc: at.Doc, Pointer: at.Pointer.AppendToken("discriminator")} - for _, mappingValue := range mappingValues(w.docs.list[at.Doc].view, node) { - if w.docs.components[mappingValue.Value] { +// mappingsOf notes the discriminator the schema at schemaPointer, holding +// node, writes (noteDiscriminator), and each value of it that names no schema +// component of the source (Config.Components): a URI reference, with a +// fragment or without, as OpenAPI reads a value naming no schema. The parser +// reads none (docs/parser-library.md#mapping-unresolved), so each is bound +// here. +func (w *finder) mappingsOf(node *yaml.Node, schemaPointer DocumentPointer) { + disc := DocumentPointer{Doc: schemaPointer.Doc, Pointer: schemaPointer.Pointer.AppendToken("discriminator")} + w.noteDiscriminator(w.docs.list[schemaPointer.Doc].view, node, schemaPointer) + for _, mapping := range mappingValues(w.docs.list[schemaPointer.Doc].view, node) { + if w.docs.components[mapping.Value] { continue } - if mappingKeyValue := (mappingKey{at: disc, value: mappingValue.Value}); !w.mappingSites[mappingKeyValue] { - w.mappingSites[mappingKeyValue] = true - w.freshMappings = append(w.freshMappings, mappingKeyValue) + if mappingKey := (mappingKey{at: disc, value: mapping.Value}); !w.mappingSites[mappingKey] { + w.mappingSites[mappingKey] = true + w.freshMappings = append(w.freshMappings, mappingKey) } } } @@ -315,29 +321,29 @@ func mappingValues(view *nodeview.View, node *yaml.Node) []*yaml.Node { return slices.DeleteFunc(values, func(otherNode *yaml.Node) bool { return otherNode == nil || otherNode.Kind != yaml.ScalarNode }) } -// pushChildren returns stack with the positions directly below frameValue, +// pushChildren returns stack with the positions directly below parent, // whose node is node, appended in order, so a walk reads its children with no // slice of their own. Nothing beside a reference object's $ref is read but a // path item's fields (refsOnly): OpenAPI ignores it, so it holds no reference // and declares no identifier. Every frame a walk reads past its root is pushed // here, which is where a test counts the pointers the walks spell // (Config.pushed). -func (w *finder) pushChildren(stack []frame, node *yaml.Node, frameValue frame) []frame { - if w.refsOnly(node, frameValue) { +func (w *finder) pushChildren(stack []frame, node *yaml.Node, parent frame) []frame { + if w.refsOnly(node, parent) { return stack } from := len(stack) switch node.Kind { case yaml.MappingNode: - for _, pair := range w.docs.list[frameValue.at.Doc].view.MappingPairs(node) { - stack = append(stack, frame{node: pair.Val, at: frameValue.at.below(pair.Key), - state: stepIn(w.docs, frameValue.at.Doc, node, frameValue.state, pair.Key, frameValue.dialect), res: frameValue.res, dialect: frameValue.dialect}) + for _, pair := range w.docs.list[parent.at.Doc].view.MappingPairs(node) { + stack = append(stack, frame{node: pair.Val, at: parent.at.below(pair.Key), + state: stepIn(w.docs, parent.at.Doc, node, parent.state, pair.Key, parent.dialect), res: parent.res, dialect: parent.dialect}) } case yaml.SequenceNode: for i, child := range node.Content { token := strconv.Itoa(i) - stack = append(stack, frame{node: child, at: frameValue.at.below(token), state: step(frameValue.state, token), res: frameValue.res, - dialect: frameValue.dialect}) + stack = append(stack, frame{node: child, at: parent.at.below(token), state: step(parent.state, token), res: parent.res, + dialect: parent.dialect}) } } if note := w.docs.cfg.pushed; note != nil { @@ -348,16 +354,16 @@ func (w *finder) pushChildren(stack []frame, node *yaml.Node, frameValue frame) return stack } -// refsOnly reports whether frameValue, holding node, is a reference object +// refsOnly reports whether frame, holding node, is a reference object // other than a path item, whose fields beside its $ref OpenAPI gives a meaning // (docs/compilers/openapi.md#path-item-ref-fields): one whose $ref is all of it // the specification reads. -func (w *finder) refsOnly(node *yaml.Node, frameValue frame) bool { - kind, ok := refKinds[frameValue.state] +func (w *finder) refsOnly(node *yaml.Node, frame frame) bool { + kind, ok := refKinds[frame.state] if !ok || kind == RefPathItem { return false } - _, refs := w.docs.refOf(frameValue.at.Doc, node) + _, refs := w.docs.refOf(frame.at.Doc, node) return refs } @@ -390,11 +396,9 @@ func (w *finder) landedObject(at DocumentPointer, kind RefKind, raw bool) { func (w *finder) walkPending() bool { roots := w.pending w.pending = nil - slices.SortFunc(roots, func(rootValue, otherRoot root) int { - if c := w.docs.compare(rootValue.at, otherRoot.at); c != 0 { - return c - } - return int(rootValue.state) - int(otherRoot.state) + keys := positionSortKeyWriterOf(w.docs) + sortByKeys(roots, func(key []byte, root root) []byte { + return append(keys.append(key, root.at), byte(root.state)) }) walked := false for _, root := range slices.Compact(roots) { @@ -416,21 +420,21 @@ type mappingKey struct { value string } -// mapping is where the mapping value mappingKeyValue names, read as a $ref +// mapping is where the mapping value mappingKey names, read as a $ref // written at the discriminator: a hop, and the chain on from where it lands. It // reports waits where either waits for a document the pass has yet to read // (waits). -func (b *binder) mapping(mappingKeyValue mappingKey) (Mapping, bool) { +func (b *binder) mapping(mappingKey mappingKey) (Mapping, bool) { // A discriminator is a position its document holds, so the path reaches it. - path, _ := b.docs.path(mappingKeyValue.at) - mapping := Mapping{At: mappingKeyValue.at, Hop: b.resolve(mappingKeyValue.at, path, mappingKeyValue.value, false)} + path, _ := b.docs.path(mappingKey.at) + mapping := Mapping{At: mappingKey.at, Hop: b.resolve(mappingKey.at, path, mappingKey.value, false)} if b.work.over() { - mapping.Hop = Hop{Ref: mappingKeyValue.value, Status: OverBudget} + mapping.Hop = Hop{Ref: mappingKey.value, Status: OverBudget} } if mapping.Hop.Status != Resolved { mapping.Chain = Chain{Status: mapping.Hop.Status} if mapping.Hop.Reason == PendingExternalDocumentRead { - b.wait.heldMappings = append(b.wait.heldMappings, mappingKeyValue) + b.wait.heldMappings = append(b.wait.heldMappings, mappingKey) return mapping, true } return mapping, false diff --git a/compilers/openapi/internal/replacement/phrase.go b/compilers/openapi/internal/replacement/phrase.go index bb890929e..72a687574 100644 --- a/compilers/openapi/internal/replacement/phrase.go +++ b/compilers/openapi/internal/replacement/phrase.go @@ -19,7 +19,7 @@ type named struct { // The words a phrase is read by, in lower case // (docs/compilers/openapi.md#replacement-inference). var ( - // leads may stand before a `use` opening its sentence. + // leads may sit before a `use` opening its sentence. leads = map[string]bool{"please": true, "should": true, "must": true, "instead": true} // cues introduce a replacement anywhere in a sentence, by their last word // and the words before it. @@ -30,11 +30,11 @@ var ( // negations before a cue in its sentence rule it out, beside a word ending // in n't. negations = map[string]bool{"not": true, "never": true, "no": true, "cannot": true} - // fillers may stand between a cue and the name it introduces. + // fillers may sit between a cue and the name it introduces. fillers = map[string]bool{"the": true, "a": true, "an": true, "new": true} ) -// phraseState is where a reading stands between a cue and the names after it. +// phraseState is where a reading sits between a cue and the names after it. type phraseState int const ( @@ -56,7 +56,7 @@ type phrase struct { state phraseState // negated reports a negation earlier in the sentence. negated bool - // lead reports that nothing but words stands before here in the sentence, + // lead reports that nothing but words sits before here in the sentence, // a comma after a lead word aside, so a `use` here may open it. lead bool // last is the sentence's last word, and window the words before it, both @@ -149,7 +149,7 @@ func (r *phrase) remember(w string) { } // comma reads a comma: a joining word after an introduced name, else -// something between words that a lead word alone may stand before. +// something between words that a lead word alone may sit before. func (r *phrase) comma() { if r.state == introduced { r.state = joined diff --git a/compilers/openapi/internal/replacement/phrase_lead_test.go b/compilers/openapi/internal/replacement/phrase_lead_test.go index 109621efb..60854bf2d 100644 --- a/compilers/openapi/internal/replacement/phrase_lead_test.go +++ b/compilers/openapi/internal/replacement/phrase_lead_test.go @@ -13,7 +13,7 @@ import ( ) // TestMessage_UseOpensItsSentence pins that `use` is a cue only where nothing -// but words stands before it in its sentence, a comma after a lead word +// but words sits before it in its sentence, a comma after a lead word // aside: a name or a mark before a lead word leaves the `use` after it no // cue, as `use` is then no instruction the sentence opens with. func TestMessage_UseOpensItsSentence(t *testing.T) { diff --git a/compilers/openapi/internal/replacement/phrase_test.go b/compilers/openapi/internal/replacement/phrase_test.go index 051540f9b..c008fbdf3 100644 --- a/compilers/openapi/internal/replacement/phrase_test.go +++ b/compilers/openapi/internal/replacement/phrase_test.go @@ -102,7 +102,7 @@ func TestMessage_ReadsOnlyIntroducedNames(t *testing.T) { {"USE `a`.", []string{"a"}}, {"Use `a` and `b`; `c` and `d` are not.", []string{"a", "b"}}, {"Use `a`, `c` and `d`.", []string{"a", "c", "d"}}, - // A filler word, and an opening parenthesis, may stand between the cue + // A filler word, and an opening parenthesis, may sit between the cue // and the name; nothing else does. {"Use the `a`.", []string{"a"}}, {"Use a `a`.", []string{"a"}}, diff --git a/compilers/openapi/internal/scan/amplification.go b/compilers/openapi/internal/scan/amplification.go index aa5b170c7..04f671841 100644 --- a/compilers/openapi/internal/scan/amplification.go +++ b/compilers/openapi/internal/scan/amplification.go @@ -235,11 +235,11 @@ func (w *aliasWeigher) pushChildren(stack *[]*weighFrame, node *yaml.Node) { // computeWeight returns node's expandedWeight, given that every node it depends // on (via childrenOf) already has a recorded weight. An alias node's weight is // exactly its target's — substituting a copy of the target, unexpanded -// further, is what an alias stands in for. Every other node's weight is 1 +// further, is what an alias takes the place of. Every other node's weight is 1 // (itself) plus its children's, counted against the allowance and held at the // first count past it, with the loop exiting the moment the total exceeds the // allowance, since nothing further down the same Content list can change that -// verdict. +// answer. func (w *aliasWeigher) computeWeight(node *yaml.Node) int { if node.Kind == yaml.AliasNode { if node.Alias == nil { diff --git a/compilers/openapi/internal/scan/amplification_internal_test.go b/compilers/openapi/internal/scan/amplification_internal_test.go index ac5a171b9..116d195dd 100644 --- a/compilers/openapi/internal/scan/amplification_internal_test.go +++ b/compilers/openapi/internal/scan/amplification_internal_test.go @@ -151,7 +151,7 @@ func TestAliases_SyntheticWideBaseReuseIsNowRefused(t *testing.T) { assert.Equal(t, ir.SeverityError, diags[0].Severity) unbounded := Aliases(t.Context(), provenance.Tree{}, ir.Provenance{}, indexOf(t, []byte(src)), budget.Unbounded(), budget.Unbounded()) - require.NotEmpty(t, unbounded, "turning the alias budget off leaves the ratio rule standing") + require.NotEmpty(t, unbounded, "turning the alias budget off leaves the ratio rule in place") assert.Equal(t, diag.AliasAmplification, unbounded[0].Code) } @@ -344,7 +344,7 @@ func TestAliases_MergeChainWithinBoundIsClean(t *testing.T) { // nodeview.MergeDepthLimit and past the alias allowance with room to spare. The // scan does not read merge keys through the mapping view, whose depth bound // would make it report an incomplete scan beside the refusal, so the refusal -// stands alone. +// is alone. func TestAliases_MergeChainPastBoundIsRefused(t *testing.T) { t.Parallel() diags := scanBytes(t, []byte(ynode.MergeChainSpec(500))) diff --git a/compilers/openapi/internal/scan/pointerbytes.go b/compilers/openapi/internal/scan/pointerbytes.go index 7609e0750..a4e0d284a 100644 --- a/compilers/openapi/internal/scan/pointerbytes.go +++ b/compilers/openapi/internal/scan/pointerbytes.go @@ -30,7 +30,7 @@ const maxPointerAmplification = 128 const minPointerBytes = 1 << 26 // 64 MiB // PointerAmplification refuses a document whose nodes' pointers total past what -// its size allows (pointerAllowance) before the parser builds it, as a +// its size allows (PointerAllowance) before the parser builds it, as a // diag.PointerAmplification error at whole, the document's place, or reports // nothing for one within it. The index must cover the tree the parser will be // handed, untruncated, and a document holding a recursive anchor the index diff --git a/compilers/openapi/internal/scan/rehome.go b/compilers/openapi/internal/scan/rehome.go index d1d96f7b6..2a26aab2a 100644 --- a/compilers/openapi/internal/scan/rehome.go +++ b/compilers/openapi/internal/scan/rehome.go @@ -4,10 +4,13 @@ package scan import ( + "encoding/json/jsontext" "slices" "strings" yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" ) // rehome places each node aliases mount at the least of its places: where it @@ -106,15 +109,25 @@ func tokensOf(steps map[*yaml.Node]step, node *yaml.Node) []string { return tokens } -// lessTokens reports whether the pointer a spells comes before b's, token by -// token, each token compared by its bytes as written, and a pointer that is a -// prefix of another first: `/A/x` before `/A-/x`, where the bytes of the whole -// strings would put `-` before `/`. +// lessTokens reports whether the pointer a spells comes before b's as the +// source writes them (provenance.ComparePointers): token by token, an array +// index by its number, and a pointer that is a prefix of another first, so +// `/A/x` comes before `/A-/x` and `/A/9` before `/A/10`. func lessTokens(a, b []string) bool { - for i := range min(len(a), len(b)) { - if c := strings.Compare(a[i], b[i]); c != 0 { - return c < 0 - } + return provenance.ComparePointers(spelledPointer(a), spelledPointer(b)) < 0 +} + +// spelledPointer is the JSON Pointer tokens spell from the top down, each +// escaped (RFC 6901, section 3). +func spelledPointer(tokens []string) jsontext.Pointer { + var spelled strings.Builder + for _, token := range tokens { + spelled.WriteByte('/') + spelled.WriteString(pointerEscapes.Replace(token)) } - return len(a) < len(b) + return jsontext.Pointer(spelled.String()) } + +// pointerEscapes escapes a token as a JSON Pointer spells it (RFC 6901, +// section 3). +var pointerEscapes = strings.NewReplacer("~", "~0", "/", "~1") diff --git a/compilers/openapi/internal/scan/scan_internal_test.go b/compilers/openapi/internal/scan/scan_internal_test.go index 7a13a8935..14a4996c7 100644 --- a/compilers/openapi/internal/scan/scan_internal_test.go +++ b/compilers/openapi/internal/scan/scan_internal_test.go @@ -198,7 +198,7 @@ components: } // TestAliases_LegalAliasAndMergeUseIsClean pins that ordinary anchor reuse, a -// merge key and an alias standing for a scalar are not refused. +// merge key and an alias naming a scalar are not refused. func TestAliases_LegalAliasAndMergeUseIsClean(t *testing.T) { t.Parallel() for _, tc := range legalAliasSpecs { diff --git a/compilers/openapi/internal/scan/site.go b/compilers/openapi/internal/scan/site.go index 2b9253e95..91c87f4ac 100644 --- a/compilers/openapi/internal/scan/site.go +++ b/compilers/openapi/internal/scan/site.go @@ -5,11 +5,11 @@ package scan import ( "context" - "strings" yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" ) // Least returns the node of nodes whose JSON pointer in root's tree, as @@ -87,9 +87,9 @@ func pathsTo(steps map[*yaml.Node]step, nodes []*yaml.Node, want map[*yaml.Node] // leastSteps returns, of the nodes one step below those of level, which share // one pointer, the ones under which the least pointer lies. Their pointers -// share everything up to the step, so the step's token decides, compared by -// its bytes as lessTokens compares one, and of one token a wanted node comes -// first, its own pointer a prefix of every other under it. +// share everything up to the step, so the step's token decides, compared as +// lessTokens compares one, and of one token a wanted node comes first, its own +// pointer a prefix of every other under it. func leastSteps(steps map[*yaml.Node]step, level []*yaml.Node, under map[*yaml.Node][]*yaml.Node, want map[*yaml.Node]int, ) []*yaml.Node { @@ -100,7 +100,7 @@ func leastSteps(steps map[*yaml.Node]step, level []*yaml.Node, under map[*yaml.N for _, node := range under[at] { token := steps[node].token _, wanted := want[node] - c := strings.Compare(token, leastToken) + c := provenance.ComparePointers(spelledPointer([]string{token}), spelledPointer([]string{leastToken})) switch { case least == nil || c < 0 || c == 0 && wanted && !leastWanted: least, leastToken, leastWanted = append(least[:0], node), token, wanted diff --git a/compilers/openapi/internal/scan/site_internal_test.go b/compilers/openapi/internal/scan/site_internal_test.go index 758fd6641..f684cd064 100644 --- a/compilers/openapi/internal/scan/site_internal_test.go +++ b/compilers/openapi/internal/scan/site_internal_test.go @@ -17,6 +17,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" "github.com/dexpace/morphic/compilers/openapi/internal/ynode" "github.com/dexpace/morphic/ir" ) @@ -36,10 +37,11 @@ func nodesAt(t *testing.T, root *yaml.Node, pointers []jsontext.Pointer) []*yaml } // TestLeast_OrdersByThePointersTokens pins the order as that of the pointers' -// tokens one by one, each by its bytes as written, not of the pointers spelled -// out, in the places the two part: a key that another extends with a character -// sorting below the separator, the escapes of `~` and `/`, which a token holds -// unescaped, and sequence indexes, which compare as text. +// tokens one by one, as provenance.ComparePointers orders them, not of the +// pointers spelled out, in the places the two part: a key that another extends +// with a character sorting below the separator, the escapes of `~` and `/`, +// which a token compares unescaped, and sequence indexes, which compare as +// numbers. func TestLeast_OrdersByThePointersTokens(t *testing.T) { t.Parallel() tests := []struct { @@ -55,7 +57,9 @@ func TestLeast_OrdersByThePointersTokens(t *testing.T) { {"a node and what it holds", "a: {x: {}}\n", []jsontext.Pointer{"/a/x", "/a"}, "/a"}, {"escaped tilde and slash", "'a/': {}\n'a~': {}\na0: {}\n", []jsontext.Pointer{"/a~0", "/a~1", "/a0"}, "/a~1"}, {"a slash before a tilde", "'a/': {}\n'a~': {}\n", []jsontext.Pointer{"/a~0", "/a~1"}, "/a~1"}, - {"indexes as text", "s: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]\n", []jsontext.Pointer{"/s/2", "/s/10"}, "/s/10"}, + {"indexes as numbers", "s: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]\n", []jsontext.Pointer{"/s/9", "/s/10"}, "/s/9"}, + {"a slash before a tilde beneath an index", "s: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {'a/': {}, 'a~': {}}]\n", + []jsontext.Pointer{"/s/10/a~0", "/s/10/a~1"}, "/s/10/a~1"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -79,7 +83,7 @@ func randomTree(r *rand.Rand, depth int) string { return "{}" } if r.IntN(3) == 0 { - items := make([]string, r.IntN(12)+1) // past ten, so "10" sorts before "2" + items := make([]string, r.IntN(12)+1) // past ten, so an index of two digits meets one of one for i := range items { items[i] = "{}" if r.IntN(4) == 0 { @@ -101,8 +105,8 @@ func randomTree(r *rand.Rand, depth int) string { // TestLeast_AgreesWithSortingEveryPointer holds Least to the plain reading of // its contract: spell every candidate's pointer, as a diagnostic carries it, -// and take the least, token by token. Thousands of generated trees and candidate sets -// are compared. +// and take the least as provenance.ComparePointers orders them. Thousands of +// generated trees and candidate sets are compared. func TestLeast_AgreesWithSortingEveryPointer(t *testing.T) { t.Parallel() r := rand.New(rand.NewPCG(905, 912)) @@ -124,7 +128,7 @@ func TestLeast_AgreesWithSortingEveryPointer(t *testing.T) { want := slices.MinFunc(candidates, func(a, b *yaml.Node) int { pa, _ := pointers(a) pb, _ := pointers(b) - return slices.Compare(slices.Collect(pa.Tokens()), slices.Collect(pb.Tokens())) + return provenance.ComparePointers(pa, pb) }) got := Least(t.Context(), root, candidates) gotPointer, _ := pointers(got) diff --git a/compilers/openapi/internal/schema/admission.go b/compilers/openapi/internal/schema/admission.go index e47bc7f32..7a138c54c 100644 --- a/compilers/openapi/internal/schema/admission.go +++ b/compilers/openapi/internal/schema/admission.go @@ -4,9 +4,7 @@ package schema import ( - "encoding/json/jsontext" "slices" - "strconv" "github.com/dexpace/morphic/compilers/openapi/internal/budget" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" @@ -18,28 +16,32 @@ import ( // admission is what one statement admits, read once a run, and what the read // met on the way. type admission struct { - // admitted is what an election compares. + // admitted is what a choice compares. admitted admitted - // admits is the kinds of instance the statement's keywords leave, null - // aside; words those the keywords beside its $ref leave; and kinds those it + // admits is the kinds of instance the statement's keywords leave, null aside; + // besideRefKinds those the keywords beside its $ref leave; and kinds those it // lowers to, which a bound is placed by (settleKinds). - admits, words, kinds kindSet - // firm is the kinds what the statement declares leaves, its `type` and - // value sets conjoined with each conjunct's; claims the kinds the - // kind-inference policy reads off its own shape keywords (claimedKinds), - // united with the kinds of each conjunct whose kinds are claims. - firm, claims kindSet + admits, besideRefKinds, kinds kindSet + // firm is the kinds what the statement declares leaves, its `type` and value + // sets conjoined with each conjunct's; inferredKinds the kinds the + // kind-inference policy reads off its own shape keywords + // (kindsInferredFromShape), united with the kinds of each conjunct whose kinds + // are inferred. + firm, inferredKinds kindSet // partial is the kinds some instance of which a keyword the read took in // refuses while admitting others (narrowedWithin), so admits holds every // instance of a kind only where partial does not hold it. partial kindSet - // cut marks a statement on or reaching a cycle of conjunct edges, a $ref - // landing on no schema or a value set no reading converts; loose one - // meeting a keyword the read does not follow that could refuse a kind - // (looseIn), a $dynamicRef the bindings read as no $ref among them, so - // admits may claim more than the schema admits; inferred one whose kinds - // are its claims, nothing it declares naming a kind. - cut, loose, inferred bool + // loose marks a statement meeting a keyword the read does not follow that + // could refuse a kind (logicKinds), a $dynamicRef the bindings read as no + // $ref among them, so admits may claim more than the schema admits; + // inferred one whose kinds are its inferredKinds, nothing it declares naming a + // kind. + loose, inferred bool + // expands marks a statement whose dynamic reference, or one its allOf's + // entry in place writes, the read expanded to what it names, read + // alone (dynamicExpansionOf). + expands bool // reads and members are the schemas and value-set members the read takes // in, each counted per path and held to one past a reader's cap. reads, members int @@ -64,7 +66,7 @@ func (r *admission) conjoin(child *admission) { func (r *admission) conjoinKinds(child *admission) { r.firm &= child.firm if child.inferred { - r.claims |= child.kinds + r.inferredKinds |= child.kinds } } @@ -73,12 +75,12 @@ func (r *admission) conjoinKinds(child *admission) { // one, inferred, else every kind. func (r *admission) settleKinds() { switch { - case r.firm != anyInstance: + case r.firm != everyKindButNull: r.kinds, r.inferred = r.firm, false - case r.claims != 0 && r.claims != anyInstance: - r.kinds, r.inferred = r.claims, true + case r.inferredKinds != 0 && r.inferredKinds != everyKindButNull: + r.kinds, r.inferred = r.inferredKinds, true default: - r.kinds, r.inferred = anyInstance, false + r.kinds, r.inferred = everyKindButNull, false } } @@ -86,7 +88,6 @@ func (r *admission) settleKinds() { // and reports whether r is still within both caps. One past either stops // (past). func (r *admission) addChildReadCostAndCheckCaps(child *admission) bool { - r.cut = r.cut || child.cut r.loose = r.loose || child.loose r.reads = min(r.reads+child.reads, maxAdmissionReads+1) r.members = min(r.members+child.members, maxAdmissionMembers+1) @@ -103,14 +104,13 @@ func (r *admission) within() bool { return r.reads <= maxAdmissionReads && r.members <= maxAdmissionMembers } -// past is r once its read takes in more than a cap: what an election compares +// past is r once its read takes in more than a cap: what a choice compares // admits every kind and holds no value set or format, so what it merges stops // growing with the paths to it, as the formats a read conjoins are one per -// schema taken in, and the election reads it as cut short (admissionReader.of). The -// kinds r admits, declares and lowers to are still read over every edge, each -// statement once, so they stay whole and cut stays false. The element schema -// is kept, child's where r holds none, which missingArrayItemsConjoined reads -// past a cut. +// schema taken in, and the choice reads it as cut short (admissionReader.of). +// The kinds r admits, declares and lowers to are still read over every edge, +// each statement once, so they stay whole. The element schema is kept, child's +// where r holds none, which missingArrayItems reads past a cut. func (r *admission) past(child *admission) { items := r.admitted.items if items == nil { @@ -119,16 +119,56 @@ func (r *admission) past(child *admission) { r.admitted = admitted{kinds: kindAny, items: items} } -// cycleRead is what a statement on a cycle of conjunct edges reads as: cut, -// whichever of its statements the read entered at, and past every reader's -// cap. -func cycleRead() *admission { - return &admission{admitted: admitted{kinds: kindAny}, admits: anyInstance, words: anyInstance, kinds: anyInstance, - firm: anyInstance, partial: anyInstance, cut: true, reads: maxAdmissionReads + 1} +// cycleSeed is where the reading of a statement on a cycle of conjunct edges +// starts: every kind, which a loop admits there, so the reading is the +// greatest fixpoint (narrowCycleKinds). +func cycleSeed() *admission { + return &admission{admitted: admitted{kinds: kindAny}, admits: everyKindButNull, besideRefKinds: everyKindButNull, kinds: everyKindButNull, + firm: everyKindButNull, reads: 1} +} + +// kindBits is the number of JSON instance kinds a kindSet tells apart. +const kindBits = 7 + +// narrowCycleKinds reads members, a cycle of conjunct edges, to the greatest +// fixpoint: each starts at every kind (cycleSeed) and is read over its edges +// (readOne) until no member's kinds narrow, a loop admitting every kind there +// (docs/compilers/openapi.md#allof-refinement). Each pass but the last +// narrows a member's declared or admitted kinds or widens its claims, so it +// ends within the passes kindBits allows each. A member's values are not +// compared: what it admits is its kinds alone. +func (walk *admissionWalk) narrowCycleKinds(members []*statement.Statement) { + edges := make([][]*statement.Statement, len(members)) + conditions := make([]conditional, len(members)) + for i, member := range members { + var logic logicEdges + edges[i], logic = splitLogic(walk.loweringContext, member, readEdgesOf(walk.loweringContext, member)) + conditions[i] = walk.conditionalRead(logic) + } + for _, member := range members { + walk.store.read[member] = cycleSeed() + } + for range 3*kindBits*len(members) + 1 { + changed := false + for i, member := range members { + next, previous := walk.readOne(member, edges[i], conditions[i]), walk.store.read[member] + changed = changed || next.firm != previous.firm || next.admits != previous.admits || next.inferredKinds != previous.inferredKinds + walk.store.read[member] = next + } + if !changed { + break + } + } + for _, member := range members { + settled := walk.store.read[member] + root := settled.admitted.root + settled.admitted = admitted{kinds: settled.admitted.kinds, items: settled.admitted.items, marks: root, root: root} + settled.reads, settled.members = 1, 0 + } } // admissionsIn keys a run's admissions. A statement the bindings do not place -// is read in the dialect of the context asking (definesNullableAt), so each +// is read in the dialect of the context asking (definesNullableFor), so each // dialect keeps its own. type admissionsIn struct { nullable bool @@ -140,270 +180,343 @@ type admissionsIn struct { // settled hold, which they hold to grow with the document and not with its // paths. type admissions struct { - read map[*statement.Statement]*admission + read map[*statement.Statement]*admission + // unexpanded is what an allOf entry writing a dynamic reference admits + // read beside another conjunct, which no position expands (unexpanded). + unexpanded map[*statement.Statement]*admission visits, edges, merged int } -// admissionOf returns what st admits, read once a run. The first ask walks -// every statement st reaches by its conjunct edges that no read has settled, -// and settles each. -func admissionOf(loweringContext lowering.Ctx, st *statement.Statement) *admission { +// admissionOf returns what schemaStatement admits, read once a run. The first +// ask walks every statement schemaStatement reaches by its conjunct edges that +// no read has settled, and settles each. +func admissionOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) *admission { store := admissionStore(loweringContext) - if admission, ok := store.read[st]; ok { + if admission, ok := store.read[schemaStatement]; ok { return admission } - admissionWalkValue := admissionWalk{c: loweringContext, store: store, index: map[*statement.Statement]int{}} - admissionWalkValue.run(st) - return store.read[st] + walk := admissionWalk{loweringContext: loweringContext, store: store} + walkComponents(schemaStatement, walk.edgesOf, + func(next *statement.Statement) bool { _, settled := store.read[next]; return settled }, walk.settle) + return store.read[schemaStatement] } // admissionStore returns the run's admissions in the dialect loweringContext // reads an unplaced schema in. func admissionStore(loweringContext lowering.Ctx) *admissions { return lowering.ReadOncePerRun(loweringContext, admissionsIn{loweringContext.SchemaRules().Defines("nullable")}, func() *admissions { - return &admissions{read: map[*statement.Statement]*admission{}} + return &admissions{read: map[*statement.Statement]*admission{}, unexpanded: map[*statement.Statement]*admission{}} }) } -// conjunctsOf returns the statements st conjoins with, each conjunct edge in -// the order the read conjoins them, a statement as often as st names it: the -// reference written beside its keywords (statement.Schema.BesideRef) and its -// allOf entries, its oneOf and then anyOf branches, and the statement its -// $ref's first hop lands on, or, for a $dynamicRef the bindings read as no -// $ref, the one it expands to (dynamicExpansionOf). A `properties` or an -// `items` consumes the instance, so it is no edge. -func conjunctsOf(loweringContext lowering.Ctx, st *statement.Statement) []*statement.Statement { - if st.Truth != statement.Stated { +// conjunctsOf returns the statements schemaStatement conjoins with, each +// conjunct edge in the order the read conjoins them, a statement as often as +// schemaStatement names it: the reference written beside its keywords +// (statement.Schema.BesideRef) and its allOf entries, its oneOf and then anyOf +// branches, and the statement its $ref's first hop lands on, or, for a +// $dynamicRef the bindings read as no $ref, the one it expands to +// (dynamicExpansionOf). A `properties` or an `items` consumes the instance, so +// it is no edge. +func conjunctsOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) []*statement.Statement { + if schemaStatement.Truth != statement.Stated { return nil } - choice := st.ChoiceKeywords() - subs := slices.Concat(st.AllOf, choice.OneOf, choice.AnyOf) - out := make([]*statement.Statement, 0, len(subs)+2) - if st.BesideRef != nil { - out = append(out, loweringContext.Statements().Read(st.BesideRef)) + choice := schemaStatement.ChoiceKeywords() + out := conjunctsIn(loweringContext, schemaStatement.Schema) + for _, branch := range slices.Concat(choice.OneOf, choice.AnyOf) { + out = append(out, loweringContext.Statements().Subschema(branch)) } - for _, b := range subs { - out = append(out, loweringContext.Statements().Subschema(b)) - } - if next, _ := declaredOf(loweringContext, st); next != nil { + if next, _ := declaredOf(loweringContext, schemaStatement); next != nil { out = append(out, next) - } else if at, ok := dynamicExpansionOf(loweringContext, st); ok { + } else if at, ok := dynamicExpansionOf(loweringContext, schemaStatement); ok { out = append(out, loweringContext.Statements().At(at)) } return out } -// dynamicExpansionOf returns the position the $dynamicRef or $recursiveRef st -// writes names, read at st's own position in its own document, where dynamic -// scope is static (dynamicTarget), and false where it writes none the bindings -// do not read as a $ref, names none, or is placed nowhere. One an allOf entry -// writes names none: no position expands it (keepEntryDynamicRef), so it masks -// no kind (docs/compilers/openapi.md#allof-refinement). -func dynamicExpansionOf(loweringContext lowering.Ctx, st *statement.Statement) (reftable.DocumentPointer, bool) { - at, placed := siteOf(st.Schema) - if st.Ref != nil || !placed || !declaresDynamicRef(st.Schema) || writtenAsEntry(at.Pointer) { +// readEdgesOf returns the statements the read of schemaStatement waits on: its +// conjuncts (conjunctsOf) and then the `if` it writes, which applies to the +// same instance and decides which of its branches applies to each kind, and +// those branches (logicOf). +func readEdgesOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) []*statement.Statement { + return append(conjunctsOf(loweringContext, schemaStatement), logicOf(loweringContext, schemaStatement).edges()...) +} + +// splitLogic returns edges, schemaStatement's read edges (readEdgesOf), as its +// conjuncts and the statements of the `if` it writes and of that if's branches. +func splitLogic(loweringContext lowering.Ctx, schemaStatement *statement.Statement, edges []*statement.Statement) ([]*statement.Statement, logicEdges) { + logic := logicOf(loweringContext, schemaStatement) + return edges[:len(edges)-len(logic.edges())], logic +} + +// logicEdges are the statements of the `if` a statement writes and of the +// `then` and `else` beside it, each nil where it is not written. +type logicEdges struct { + condition, then, otherwise *statement.Statement +} + +// logicOf returns the statements of the `if` schemaStatement writes and of its +// branches, none where it writes no `if`, which leaves its branches applying to +// nothing (JSON Schema Core 2020-12 §10.2.2). +func logicOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) logicEdges { + if !writesCondition(schemaStatement) { + return logicEdges{} + } + logic := schemaStatement.Logic + out := logicEdges{condition: loweringContext.Statements().Subschema(logic.If)} + if written(logic.Then) { + out.then = loweringContext.Statements().Subschema(logic.Then) + } + if written(logic.Else) { + out.otherwise = loweringContext.Statements().Subschema(logic.Else) + } + return out +} + +// edges returns the statements l holds, the `if` first and then its branches. +func (l logicEdges) edges() []*statement.Statement { + return slices.DeleteFunc([]*statement.Statement{l.condition, l.then, l.otherwise}, func(edge *statement.Statement) bool { return edge == nil }) +} + +// writesCondition reports whether schemaStatement writes an `if` schema, one +// written null being the keyword left out +// (docs/compilers/openapi.md#null-schema). +func writesCondition(schemaStatement *statement.Statement) bool { + return schemaStatement.Truth == statement.Stated && schemaStatement.Logic != nil && written(schemaStatement.Logic.If) +} + +// dynamicExpansionOf returns the position the $dynamicRef or $recursiveRef +// schemaStatement writes names, read at schemaStatement's own position in its +// own document, where dynamic scope is static (dynamicTarget), and false where +// it writes none the bindings do not read as a $ref, names none, or is placed +// nowhere. It reads schemaStatement alone, as a $ref naming it does; the allOf +// listing schemaStatement as an entry beside another conjunct reads it +// unexpanded (admissionWalk.entryAdmission). +func dynamicExpansionOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) (reftable.DocumentPointer, bool) { + at, placed := siteOf(schemaStatement.Schema) + if schemaStatement.Ref != nil || !placed || !declaresDynamicRef(schemaStatement.Schema) { return reftable.DocumentPointer{}, false } in, _ := lowering.InDocument(loweringContext, at.Doc) - return dynamicTarget(in, st.Schema, at.Pointer) + return dynamicTarget(in, schemaStatement.Schema, at.Pointer) } -// writtenAsEntry reports whether pointer names an entry of an allOf. The -// statement reads an entry whose reference names nothing off its pointer too, -// by a parse of its own that takes a signed index where this one takes none -// (statement.Table's failedEntry). Neither knows how the schema is reached; a -// statement saying so replaces both (GitHub #2058). -func writtenAsEntry(pointer jsontext.Pointer) bool { - _, err := strconv.ParseUint(pointer.LastToken(), 10, 64) - return err == nil && pointer.Parent().LastToken() == "allOf" +// entryInPlace reports whether the one entry schema's allOf lists is in +// place, as written at schema (JSON Schema Core 2020-12 §10.2.1.1): it is +// schema's only conjunct, and schema writes beside it nothing a dynamic +// reference's expansion cannot carry (dynamicRefSiblings), so a dynamic +// reference the entry writes expands as written at schema +// (docs/compilers/openapi.md#dynamic-ref). +func entryInPlace(schema *statement.Schema) bool { + return len(schema.AllOf) == 1 && schema.BesideRef == nil && schema.Ref == nil && !declaresUnion(schema) && + slices.Equal(siblingKeywords(schema), []string{"allOf"}) } -// admissionWalk is one walk settling the admissions a first ask needs, by -// Tarjan's strongly connected components over the conjunct edges, on stacks -// of its own: it recurses nowhere, and visits each statement it has not -// settled and each of that statement's edges once. A component is settled -// when its root returns, every component it reaches settled before it. +// admissionWalk is what one walk settling the admissions a first ask needs +// reads and keeps (walkComponents), by Tarjan's strongly connected components +// over the conjunct edges: it recurses nowhere, and visits each statement it +// has not settled and each of that statement's edges once. A component is +// settled when its root returns, every component it reaches settled before it. type admissionWalk struct { - c lowering.Ctx - store *admissions - index map[*statement.Statement]int - low []int - open []*statement.Statement - frames []admissionFrame -} - -// admissionFrame is one statement the walk is inside: its place in the order -// visited, its conjunct edges, and the next one to follow. -type admissionFrame struct { - st *statement.Statement - at int - edges []*statement.Statement - next int -} - -// run walks from root. Each pass of the loop follows one edge or leaves one -// statement, so it ends after the statements and edges reached, twice over. -func (w *admissionWalk) run(root *statement.Statement) { - w.enter(root) - for len(w.frames) > 0 { - top := len(w.frames) - 1 - if admissionFrame := &w.frames[top]; admissionFrame.next < len(admissionFrame.edges) { - next := admissionFrame.edges[admissionFrame.next] - admissionFrame.next++ - w.follow(admissionFrame.at, next) - continue - } - admissionFrameValue := w.frames[top] - w.frames = w.frames[:top] - if top > 0 { - parent := w.frames[top-1].at - w.low[parent] = min(w.low[parent], w.low[admissionFrameValue.at]) - } - if w.low[admissionFrameValue.at] == admissionFrameValue.at { - w.settle(&admissionFrameValue) - } - } + loweringContext lowering.Ctx + store *admissions } -// enter visits st: it is given the next place in the order, pushed open, and -// its edges read. -func (w *admissionWalk) enter(st *statement.Statement) { - at := len(w.low) - w.index[st] = at - w.low = append(w.low, at) - w.open = append(w.open, st) - edges := conjunctsOf(w.c, st) - w.frames = append(w.frames, admissionFrame{st: st, at: at, edges: edges}) - w.store.visits++ - w.store.edges += len(edges) +// edgesOf returns the conjunct edges of schemaStatement (readEdgesOf), and +// counts the visit and the edges. +func (walk *admissionWalk) edgesOf(schemaStatement *statement.Statement) []*statement.Statement { + edges := readEdgesOf(walk.loweringContext, schemaStatement) + walk.store.visits++ + walk.store.edges += len(edges) + return edges } -// follow takes the edge from the statement at place from to next: settled -// already, there is nothing to walk; unvisited, it is entered; still open, it -// is on from's component. -func (w *admissionWalk) follow(from int, next *statement.Statement) { - if _, settled := w.store.read[next]; settled { - return - } - at, seen := w.index[next] - if !seen { - w.enter(next) +// settle records what each statement of component admits: a component holding +// more than one statement, or one naming itself, is a cycle; any other reads +// over its edges, each settled. +func (walk *admissionWalk) settle(component closedComponent[*statement.Statement]) { + if component.cyclic { + walk.narrowCycleKinds(component.members) return } - w.low[from] = min(w.low[from], at) + root := component.members[0] + conjuncts, logic := splitLogic(walk.loweringContext, root, component.rootEdges) + admission := walk.readOne(root, conjuncts, walk.conditionalRead(logic)) + walk.store.read[root] = admission + walk.store.merged += len(admission.admitted.forms) + admission.admitted.size() } -// settle pops the component whose root is admissionFrameValue's statement and -// records what each of its statements admits: one holding more than one -// statement, or one naming itself, is a cycle; any other reads over its edges, -// each settled. -func (w *admissionWalk) settle(admissionFrameValue *admissionFrame) { - from := len(w.open) - 1 - for w.open[from] != admissionFrameValue.st { - from-- - } - members := w.open[from:] - if len(members) > 1 || slices.Contains(admissionFrameValue.edges, admissionFrameValue.st) { - for _, schemaStatement := range members { - w.store.read[schemaStatement] = cycleRead() - } - } else { - admission := w.readOne(admissionFrameValue.st, admissionFrameValue.edges) - w.store.read[admissionFrameValue.st] = admission - w.store.merged += len(admission.admitted.forms) + admission.admitted.size() - } - w.open = w.open[:from] -} - -// readOne reads st, whose conjunct edges each lead to a settled statement: -// what its own keywords say, in the dialect of the document holding it, -// conjoined with its allOf entries, the join of each union's branches and what -// its $ref lands on, in conjunctsOf's order, its kinds settled last -// (settleKinds). A statement stating no schema object admits nothing where it -// reads as `false`, and anything else. -func (w *admissionWalk) readOne(st *statement.Statement, edges []*statement.Statement) *admission { - if st.Truth != statement.Stated { - if st.Truth.ReadsFalse() { +// readOne reads schemaStatement, whose conjunct edges each lead to a settled +// statement: what its own keywords say, in the dialect of the document holding +// it, the `if` it writes as logic tells (readOwnAdmission), conjoined with +// its allOf entries, the combination of each union's branches and what its $ref +// lands on, in conjunctsOf's order, its kinds settled last (settleKinds). A +// statement stating no schema object admits nothing where it reads as `false`, +// and anything else. +func (walk *admissionWalk) readOne(schemaStatement *statement.Statement, edges []*statement.Statement, logic conditional) *admission { + if schemaStatement.Truth != statement.Stated { + if schemaStatement.Truth.ReadsFalse() { return &admission{reads: 1} } - return &admission{admitted: admitted{kinds: kindAny}, admits: anyInstance, words: anyInstance, kinds: anyInstance, - firm: anyInstance, reads: 1} + return &admission{admitted: admitted{kinds: kindAny}, admits: everyKindButNull, besideRefKinds: everyKindButNull, kinds: everyKindButNull, + firm: everyKindButNull, reads: 1} } - admissionValue := w.readOwn(st) - choice := st.ChoiceKeywords() - conjuncts := len(st.AllOf) - if st.BesideRef != nil { + admissionValue := readOwnAdmission(walk.loweringContext, schemaStatement, logic) + choice := schemaStatement.ChoiceKeywords() + conjuncts := len(schemaStatement.AllOf) + if schemaStatement.BesideRef != nil { conjuncts++ } - for _, schemaStatement := range edges[:conjuncts] { - admissionValue.conjoin(w.store.read[schemaStatement]) + for _, edge := range edges[:conjuncts] { + entry := walk.entryAdmission(schemaStatement, edge) + admissionValue.conjoin(entry) + // An entry in place expands as written at schemaStatement, so + // schemaStatement expands what it does, and beside another conjunct is read + // unexpanded too. + admissionValue.expands = admissionValue.expands || entry.expands } edges = edges[conjuncts:] for i, branches := range [][]statement.Subschema{choice.OneOf, choice.AnyOf} { if len(branches) > 0 { - admissionValue.conjoin(w.join(edges[:len(branches)], i == 0)) + admissionValue.conjoin(walk.unionOfBranches(edges[:len(branches)], i == 0)) edges = edges[len(branches):] } } - admissionValue.words = admissionValue.admits + admissionValue.besideRefKinds = admissionValue.admits switch { - case st.Ref != nil && len(edges) == 0: - admissionValue.cut = true - case st.Ref != nil: - admissionValue.conjoin(w.store.read[edges[0]]) + case schemaStatement.Ref != nil && len(edges) == 0: + // A $ref landing on no schema admits every kind and cuts nothing + // (docs/compilers/openapi.md#allof-refinement). + case schemaStatement.Ref != nil: + admissionValue.conjoin(walk.store.read[edges[0]]) case len(edges) > 0: - target := w.store.read[edges[0]] - admissionValue.admits &= target.admits - admissionValue.partial |= target.partial - admissionValue.conjoinKinds(target) - admissionValue.cut = admissionValue.cut || target.cut - admissionValue.loose = admissionValue.loose || target.loose + admissionValue.expands = true + admissionValue.conjoin(walk.store.read[edges[0]]) } admissionValue.settleKinds() + admissionValue.admitted.root = admissionValue.admitted.settledRoot(schemaStatement.Schema) return admissionValue } -// readOwn reads what st's own keywords say: what they admit, the kinds their -// type and value sets leave, and the members those sets hold. -func (w *admissionWalk) readOwn(st *statement.Statement) *admission { - own := admissionReader{c: w.c, reads: budget.New(budget.Unbounded()), members: budget.New(budget.Unbounded())} - admissionValue := &admission{reads: 1, admitted: own.written(st.Schema, definesNullableAt(w.c, st))} - admissionValue.firm, admissionValue.claims = ownKinds(w.c, st.Schema) +// entryAdmission returns what entry, a conjunct schemaStatement lists, admits +// as schemaStatement reads it (entryAdmissionIn): in place where it is +// schemaStatement's one entry (entryInPlace). +func (walk *admissionWalk) entryAdmission(schemaStatement, entry *statement.Statement) *admission { + return entryAdmissionIn(walk.loweringContext, walk.store, entryInPlace(schemaStatement.Schema), entry, walk.store.read[entry]) +} + +// composedEntryAdmission returns what entry, an entry of the flattened allOf +// schema writes, admits as schema reads it (entryAdmissionIn): in place where +// it is so at schema (endsInPlaceChain). +func composedEntryAdmission(loweringContext lowering.Ctx, schema *statement.Schema, entry *statement.Statement) *admission { + inPlace := endsInPlaceChain(loweringContext, schema, entry.Schema) + return entryAdmissionIn(loweringContext, admissionStore(loweringContext), inPlace, entry, admissionOf(loweringContext, entry)) +} + +// endsInPlaceChain reports whether entry, listed in the flattened allOf schema +// writes, is in place at schema: it ends the chain of one-entry allOfs +// from schema each of which holds its entry in place (entryInPlace), which +// flattening nests at most statement.MaxFlattenDepth deep. +func endsInPlaceChain(loweringContext lowering.Ctx, schema, entry *statement.Schema) bool { + for depth := 0; depth <= statement.MaxFlattenDepth && entryInPlace(schema); depth++ { + schema = loweringContext.Statements().Subschema(schema.AllOf[0]).Schema + if schema == entry { + return true + } + } + return false +} + +// entryAdmissionIn returns what entry, a conjunct of an allOf, admits as the +// allOf reads it, read being what it admits alone: an entry whose dynamic +// reference expands read alone is read unexpanded beside another conjunct, as +// no position expands it there (keepEntryDynamicRef), and expanded where it +// is in place. Each entry's unexpanded reading is read once a run. +func entryAdmissionIn(loweringContext lowering.Ctx, store *admissions, inPlace bool, entry *statement.Statement, read *admission) *admission { + if !read.expands || inPlace { + return read + } + if unexpanded, ok := store.unexpanded[entry]; ok { + return unexpanded + } + unexpanded := readUnexpanded(loweringContext, store, entry) + store.unexpanded[entry] = unexpanded + return unexpanded +} + +// readUnexpanded reads what entry, whose dynamic reference expands read alone, +// admits unexpanded: its own keywords and those of each schema down the chain +// of entries it holds in place (entryInPlace) to the one writing the +// reference. An expanding dynamic reference is written beside no other +// conjunct (dynamicRefSiblings), and each hop of the chain writes its one +// entry and no other conjunct, so their keywords are all the chain says. An +// `if` the chain writes is not followed (unreadCondition), its branches read +// as store holds them (branchReadIn): the reading may be asked while a cycle +// holding the `if` settles. +func readUnexpanded(loweringContext lowering.Ctx, store *admissions, entry *statement.Statement) *admission { + unfollowed := func(schemaStatement *statement.Statement) conditional { + logic := logicOf(loweringContext, schemaStatement) + return conditional{condition: unreadCondition(), then: branchReadIn(store, logic.then), otherwise: branchReadIn(store, logic.otherwise)} + } + unexpanded := readOwnAdmission(loweringContext, entry, unfollowed(entry)) + chainNode := entry + for depth := 0; depth <= statement.MaxFlattenDepth && entryInPlace(chainNode.Schema); depth++ { + chainNode = loweringContext.Statements().Subschema(chainNode.AllOf[0]) + own := readOwnAdmission(loweringContext, chainNode, unfollowed(chainNode)) + own.settleKinds() + unexpanded.conjoin(own) + } + unexpanded.besideRefKinds = unexpanded.admits + unexpanded.settleKinds() + unexpanded.admitted.root = unexpanded.admitted.settledRoot(entry.Schema) + return unexpanded +} + +// readOwnAdmission reads what schemaStatement's own keywords say: what they +// admit, the kinds their type and value sets leave, and the members those sets +// hold. The `if` schemaStatement writes is read as logic tells (logicKinds). +func readOwnAdmission(loweringContext lowering.Ctx, schemaStatement *statement.Statement, logic conditional) *admission { + own := admissionReader{loweringContext: loweringContext, reads: budget.New(budget.Unbounded()), members: budget.New(budget.Unbounded())} + admissionValue := &admission{reads: 1, admitted: own.written(schemaStatement.Schema, definesNullableFor(loweringContext, schemaStatement.Schema))} + admissionValue.firm, admissionValue.inferredKinds = ownKinds(loweringContext, schemaStatement.Schema) + logicAdmits, logicPartial, exact := logicKinds(loweringContext, schemaStatement.Schema, logic) + admissionValue.firm &= logicAdmits admissionValue.admits = admissionValue.firm - admissionValue.partial = narrowedWithin(w.c.Statements(), st.Schema) + admissionValue.partial = narrowedWithin(loweringContext.Statements(), schemaStatement.Schema) | logicPartial admissionValue.members = min(own.members.Spent(), maxAdmissionMembers+1) if !admissionValue.within() { admissionValue.past(admissionValue) } - admissionValue.cut = own.members.Exhausted() - admissionValue.loose = declaresDynamicRef(st.Schema) && st.Ref == nil || looseIn(st.Schema) + admissionValue.loose = declaresDynamicRef(schemaStatement.Schema) && schemaStatement.Ref == nil || !exact return admissionValue } // ownKinds returns the kinds the keywords schema writes itself leave: firm, -// those its type declares met with those its value sets hold (valueKinds), and -// claims, those the kind-inference policy reads off its shape keywords -// (claimedKinds). The walk (readOwn), restKinds, which reads a schema with its -// union left out, and restAdmitsObjects take them from here; toldWhereWritten -// still meets a schema's type with its value sets in a switch arm of its own. -func ownKinds(loweringContext lowering.Ctx, schema *statement.Schema) (firm, claims kindSet) { - return declaredInstanceTypes(schema) & valueKinds(loweringContext, schema), claimedKinds(loweringContext, schema) -} - -// join is what any of a union's settled branches admits, declares and lowers -// to, with what their reads took in: a branch reading as every kind leaves -// what the join declares open, so the kinds the branches lower to reach the -// position as a claim where any branch's is one. A kind is admitted whole -// where some branch admits it whole and, for an exclusive union, which refuses -// an instance two branches admit, no other branch admits it at all. -func (w *admissionWalk) join(branches []*statement.Statement, exclusive bool) *admission { - first := w.store.read[branches[0]] +// those its type declares intersected with those its value sets hold +// (valueKinds), and inferredKinds, those the kind-inference policy reads off +// its shape keywords (kindsInferredFromShape). The walk (readOwnAdmission), +// restKinds, which reads a schema with its union left out, and the union +// reading (restOfConjunction) take them from here; toldWhereWritten still +// intersects a schema's type with its value sets in a switch arm of its own. +func ownKinds(loweringContext lowering.Ctx, schema *statement.Schema) (firm, inferredKinds kindSet) { + return declaredInstanceTypes(schema) & valueKinds(loweringContext, schema), kindsInferredFromShape(loweringContext, schema) +} + +// unionOfBranches is what any of a union's settled branches admits, declares +// and lowers to, with what their reads took in: a branch reading as every kind +// leaves what the unionOfBranches declares open, so the kinds the branches +// lower to reach the position as a claim where any branch's is one. A kind is +// admitted whole where some branch admits it whole and, for an exclusive union, +// which refuses an instance two branches admit, no other branch admits it at +// all. +func (walk *admissionWalk) unionOfBranches(branches []*statement.Statement, exclusive bool) *admission { + first := walk.store.read[branches[0]] out := &admission{admitted: first.admitted, admits: first.admits, kinds: first.kinds, firm: first.firm, inferred: first.inferred} out.addChildReadCostAndCheckCaps(first) whole, shared := first.admits&^first.partial, kindSet(0) - for _, b := range branches[1:] { - branch := w.store.read[b] + for _, branch := range branches[1:] { + branch := walk.store.read[branch] shared |= out.admits & branch.admits whole |= branch.admits &^ branch.partial out.admits |= branch.admits @@ -418,6 +531,7 @@ func (w *admissionWalk) join(branches []*statement.Statement, exclusive bool) *a if exclusive { out.partial |= shared } + out.admitted = out.admitted.branchesRead() return out } @@ -427,17 +541,17 @@ func (w *admissionWalk) join(branches []*statement.Statement, exclusive bool) *a // format, and an array or an object for a keyword applying to that kind alone // (specrules.SlotOf), `dependentSchemas` and the drafts' `dependencies` among // them, but one refusing none (refusesNothing). A `type` refuses a kind whole, -// which admits holds; a `not` or an `if` makes the read loose (looseIn); and a +// which admits holds; a `not` and an `if` are read by logicKinds; and a // keyword written null is left out. func narrowedWithin(memoizingSchemaReader *statement.MemoizingSchemaReader, schema *statement.Schema) kindSet { var out kindSet for _, key := range schema.Keys { - if key.Null { + if key.WritesNull() { continue } switch key.Slot { case specrules.SlotValues: - out |= anyInstance + out |= everyKindButNull case specrules.SlotFormat: if _, ok := formOf(schema); ok { out |= kindString | kindNumber @@ -466,12 +580,13 @@ func narrowedWithin(memoizingSchemaReader *statement.MemoizingSchemaReader, sche // refusesNothing reports whether the keyword name schema writes refuses no // instance of the kind it applies to: a schema applied to each of an instance's -// parts that states nothing, `true` or `{}`, or a `properties`, +// parts that states nothing, `true`, `{}` or one writing only identifier and +// meta keywords, or a `properties`, // `patternProperties` or `prefixItems` each of whose schemas states nothing. // Any other array or object keyword is read as refusing some. func refusesNothing(memoizingSchemaReader *statement.MemoizingSchemaReader, schema *statement.Schema, name string) bool { statesNothing := func(sub statement.Subschema) bool { - return sub.SchemaValueForm() == statement.Anything || sub.SchemaValueForm() == statement.Stated && len(memoizingSchemaReader.Subschema(sub).Keys) == 0 + return sub.SchemaValueForm() == statement.Anything || sub.SchemaValueForm() == statement.Stated && memoizingSchemaReader.Subschema(sub).WritesOnlyIdentifierAndMetaKeywords() } switch name { case "items": @@ -495,14 +610,135 @@ func refusesNothing(memoizingSchemaReader *statement.MemoizingSchemaReader, sche } } -// looseIn reports whether schema writes a keyword the read of what it admits -// does not follow and that could refuse a value of some kind: a `not`, an `if` -// or a `dependentSchemas` holding a schema. One written null is the keyword -// left out (docs/compilers/openapi.md#null-schema), and refuses nothing. -func looseIn(schema *statement.Schema) bool { +// logicKinds returns the kinds schema's logic keywords leave, those of them +// they leave only in part, and whether the read follows all they say (GitHub +// #1671): a `not` of a schema stating only a type refuses those kinds alone, +// and an `if` sends each kind to a branch as logic, the read of its `if` and +// its branches, tells (conditional.leaves). A `not` saying more, a branch read +// loosely, and a `dependentSchemas` holding a schema could refuse a value of +// some kind the read does not follow: not exact. One written null is the +// keyword left out (docs/compilers/openapi.md#null-schema). +func logicKinds(loweringContext lowering.Ctx, schema *statement.Schema, logic conditional) (kinds, partial kindSet, exact bool) { if schema.Logic == nil { - return false + return everyKindButNull, 0, true + } + keywords := schema.Logic + if slices.ContainsFunc(keywords.DependentSchemas, written) { + return everyKindButNull, 0, false + } + kinds, exact = everyKindButNull, true + if written(keywords.Not) { + refused, typed := typeOnlyKinds(loweringContext, keywords.Not) + kinds, exact = kinds&^refused, typed + } + if written(keywords.If) { + left, leftPartial := logic.leaves() + kinds, partial, exact = kinds&left, kinds&leftPartial, exact && logic.then.exact && logic.otherwise.exact + } + return kinds, partial, exact +} + +// conditionKinds is what the read of an `if` schema tells of each kind: the +// kinds it admits every instance of, and those it admits any instance of. +type conditionKinds struct { + whole, admitted kindSet +} + +// unreadCondition is an `if` the read does not follow: one admitting some +// instances of each kind, so each goes to either branch. +func unreadCondition() conditionKinds { + return conditionKinds{admitted: everyKindButNull} +} + +// conditionRead returns what the walk's read of condition, the statement of an +// `if`, tells of each kind: unread (unreadCondition) where it is not settled, +// as none is and one on the cycle of the statement writing it is not +// (narrowCycleKinds). A loose read admits no kind whole, as it may claim more +// than the schema admits; a kind it leaves out it still admits none of. +func (walk *admissionWalk) conditionRead(condition *statement.Statement) conditionKinds { + read, settled := walk.store.read[condition] + if !settled { + return unreadCondition() + } + if read.loose { + return conditionKinds{admitted: read.admits} + } + return conditionKinds{whole: read.admits &^ read.partial, admitted: read.admits} +} + +// conditional is what the read of an `if` and of its branches tells: of each +// kind, what its condition admits (conditionKinds), and what its `then` and +// its `else` admit (branchRead). +type conditional struct { + condition conditionKinds + then, otherwise branchRead +} + +// conditionalRead returns what the walk's read of logic, the statements of an +// `if` and of its branches, tells (conditionRead, branchReadIn). +func (walk *admissionWalk) conditionalRead(logic logicEdges) conditional { + return conditional{condition: walk.conditionRead(logic.condition), then: branchReadIn(walk.store, logic.then), + otherwise: branchReadIn(walk.store, logic.otherwise)} +} + +// leaves returns the kinds an `if` read as c leaves, and those of them it +// leaves in part (JSON Schema Core 2020-12 §10.2.2.1): a kind its condition +// admits whole goes to its `then` alone, one the condition admits none of to +// its `else` alone, each as that branch admits it, and any other to either, so +// admitted only in part. +func (c conditional) leaves() (kinds, partial kindSet) { + toThen, toElse := c.condition.whole, everyKindButNull&^c.condition.admitted + either := (c.condition.admitted &^ c.condition.whole) & (c.then.admits | c.otherwise.admits) + kinds = toThen&c.then.admits | toElse&c.otherwise.admits | either + return kinds, toThen&c.then.partial | toElse&c.otherwise.partial | either +} + +// branchRead is what the read of an `if`'s `then` or `else` tells: the kinds +// it admits, those of them it admits only in part, and whether the read +// follows all it says. +type branchRead struct { + admits, partial kindSet + exact bool +} + +// branchReadIn returns what store holds of branch, an `if`'s `then` or `else`, +// as every position's kinds are read (admissionOf): every kind where it is not +// written, and where its read is not settled, as none is on the cycle of the +// statement writing it (narrowCycleKinds), some of each kind, not followed. A +// loose read admits no kind whole and is not followed either. +func branchReadIn(store *admissions, branch *statement.Statement) branchRead { + if branch == nil { + return branchRead{admits: everyKindButNull, exact: true} + } + read, settled := store.read[branch] + switch { + case !settled: + return branchRead{admits: everyKindButNull, partial: everyKindButNull} + case read.loose: + return branchRead{admits: read.admits, partial: read.admits} + default: + return branchRead{admits: read.admits, partial: read.partial, exact: true} + } +} + +// typeOnlyKinds returns the kinds the schema sub, a `not`'s, states through +// `type` alone, and false where it states anything else that could refuse a +// value: any key read beside `type` but a note, an identifier or an extension. +func typeOnlyKinds(loweringContext lowering.Ctx, sub statement.Subschema) (kindSet, bool) { + schema := loweringContext.Statements().Subschema(sub).Schema + if !stated(schema) || schema.Truncated || schema.Ref != nil { + return 0, false + } + typed := false + for _, key := range schema.Keys { + if _, read := schema.Key(key.Name); !read || key.Slot == specrules.SlotNotes || key.Slot == specrules.SlotResource { + continue + } + if key.Name != "type" { + return 0, false + } + typed = true } - logic := schema.Logic - return written(logic.Not) || written(logic.If) || slices.ContainsFunc(logic.DependentSchemas, written) + kinds := declaredInstanceTypes(schema) + return kinds, typed && kinds != 0 } diff --git a/compilers/openapi/internal/schema/admission_caps_internal_test.go b/compilers/openapi/internal/schema/admission_caps_internal_test.go index 8f8a87a83..593440e74 100644 --- a/compilers/openapi/internal/schema/admission_caps_internal_test.go +++ b/compilers/openapi/internal/schema/admission_caps_internal_test.go @@ -16,29 +16,29 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/service/servicetest" ) -// TestAdmission_ACapStopsTheElectionsSummaryAlone pins what each kind of read -// leaves its readers: one that finishes, one a cycle of conjunct edges cuts, -// and one at and past each cap, the members of an allOf's entries summed. A -// cut leaves no kind known; a cap is no cut, so the kinds stay whole, but past -// it the summary an election compares admits every kind and the read is no -// longer within the caps. -func TestAdmission_ACapStopsTheElectionsSummaryAlone(t *testing.T) { +// TestAdmission_ACapStopsTheChoicesSummaryAlone pins what each kind of read +// leaves its readers: one that finishes, one on a cycle of conjunct edges, and +// one at and past each cap, the members of an allOf's entries summed. A cycle +// cuts nothing: a loop admits every kind, so its read finishes within the caps +// and the summary a choice compares admits every kind. A cap is no cut, so +// the kinds stay whole, but past it the summary admits every kind and the read +// is no longer within the caps. +func TestAdmission_ACapStopsTheChoicesSummaryAlone(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.ComponentSpecVer("3.1.0", capsSpec()), service.Policy{}) for name, want := range map[string]struct { - cut, within bool - kinds kindSet + cut, within, admitsEvery bool + kinds kindSet }{ - "Str": {within: true, kinds: kindString}, "Cyc": {cut: true, kinds: anyInstance}, + "Str": {within: true, kinds: kindString}, "Cyc": {within: true, admitsEvery: true, kinds: everyKindButNull}, "AtReads": {within: true, kinds: kindString}, "PastReads": {kinds: kindString}, "AtMembers": {within: true, kinds: kindString}, "PastMembers": {kinds: kindString}, "AtMembersSummed": {within: true, kinds: kindString}, "PastMembersSummed": {kinds: kindString}, } { admission := admissionOf(serviceContext.Ctx, heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name))) - assert.Equal(t, want.cut, admission.cut, "%s: cut", name) assert.Equal(t, want.within, admission.within(), "%s: within the caps", name) assert.Equal(t, want.kinds, admission.kinds, "%s: the kinds it lowers to", name) - assert.Equal(t, want.within, admission.admitted.kinds != kindAny, "%s: the summary an election compares", name) + assert.Equal(t, want.within && !want.admitsEvery, admission.admitted.kinds != kindAny, "%s: the summary a choice compares", name) } } @@ -52,8 +52,8 @@ func TestDeadBranch_ReadsABranchPastTheCapsByItsKinds(t *testing.T) { for name, dead := range map[string]bool{ "ObjectWithin": true, "ObjectPast": true, "NullableWithin": true, "NullablePast": false, "NullableMembersPast": false, } { - st := heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name)) - assert.Equal(t, []bool{dead}, deadBranches(serviceContext.Ctx, st.Schema, st.Schema), name) + schemaStatement := heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name)) + assert.Equal(t, []bool{dead}, deadBranches(serviceContext.Ctx, schemaStatement.Schema, schemaStatement.Schema), name) } } diff --git a/compilers/openapi/internal/schema/admission_internal_test.go b/compilers/openapi/internal/schema/admission_internal_test.go index 248813119..f52210ffa 100644 --- a/compilers/openapi/internal/schema/admission_internal_test.go +++ b/compilers/openapi/internal/schema/admission_internal_test.go @@ -32,46 +32,57 @@ import ( ) // formerWhole is the read admissionOf replaced, kept to hold it to: recursive, -// it reads js afresh at each ask, spending w's budget per schema, and is cut -// short where the budget runs out, at a $dynamicRef the bindings read as no -// $ref and at a $ref landing on no schema. -func (w *admissionReader) formerWhole(js *statement.Statement) admitted { - if !w.reads.Spend(1) || js.Truth == statement.Unwritten { +// it reads schemaStatement afresh at each ask, spending reader's budget per +// schema, and is cut short where the budget runs out, at a $dynamicRef the +// bindings read as no $ref and at a $ref landing on no schema. What it reads of +// a stated schema settles its root (admitted.settledRoot). +func (reader *admissionReader) formerWhole(schemaStatement *statement.Statement) admitted { + out := reader.formerRead(schemaStatement) + if schemaStatement.Truth == statement.Stated { + out.root = out.settledRoot(schemaStatement.Schema) + } + return out +} + +// formerRead is formerWhole's reading of schemaStatement before its root +// settles. +func (reader *admissionReader) formerRead(schemaStatement *statement.Statement) admitted { + if !reader.reads.Spend(1) || schemaStatement.Truth == statement.Unwritten { return admitted{kinds: kindAny} } - if js.Truth != statement.Stated { - if js.Truth.ReadsFalse() { + if schemaStatement.Truth != statement.Stated { + if schemaStatement.Truth.ReadsFalse() { return admitted{} } return admitted{kinds: kindAny} } - if declaresDynamicRef(js.Schema) && js.Ref == nil { - w.reads.Exhaust() + if declaresDynamicRef(schemaStatement.Schema) && schemaStatement.Ref == nil { + reader.reads.Exhaust() } - out := w.written(js.Schema, definesNullableAt(w.c, js)) - for _, b := range conjunctsIn(w.c, js.Schema) { - out = out.and(w.formerWhole(b)) + out := reader.written(schemaStatement.Schema, definesNullableFor(reader.loweringContext, schemaStatement.Schema)) + for _, branch := range conjunctsIn(reader.loweringContext, schemaStatement.Schema) { + out = out.and(reader.formerWhole(branch)) } - choice := js.ChoiceKeywords() + choice := schemaStatement.ChoiceKeywords() for _, branches := range [][]statement.Subschema{choice.OneOf, choice.AnyOf} { if len(branches) == 0 { continue } - union := w.formerWhole(w.c.Statements().Subschema(branches[0])) - for _, b := range branches[1:] { - union = union.or(w.formerWhole(w.c.Statements().Subschema(b))) + union := reader.formerWhole(reader.loweringContext.Statements().Subschema(branches[0])) + for _, branch := range branches[1:] { + union = union.or(reader.formerWhole(reader.loweringContext.Statements().Subschema(branch))) } - out = out.and(union) + out = out.and(union.branchesRead()) } - if js.Ref == nil { + if schemaStatement.Ref == nil { return out } - next, _ := declaredOf(w.c, js) + next, _ := declaredOf(reader.loweringContext, schemaStatement) if next == nil { - w.reads.Exhaust() + reader.reads.Exhaust() return out } - return out.and(w.formerWhole(next)) + return out.and(reader.formerWhole(next)) } // specsUnder returns the OpenAPI 3 documents under the repository's testdata, @@ -106,14 +117,14 @@ func loweredOrNot(t *testing.T, src []byte) *Lowerer { // statementsOfDocument calls visit with the statement of each schema the // root document of lowerer writes, wherever it is written. -func statementsOfDocument(lowerer *Lowerer, visit func(at jsontext.Pointer, st *statement.Statement)) { +func statementsOfDocument(lowerer *Lowerer, visit func(at jsontext.Pointer, schemaStatement *statement.Statement)) { var walk func(node *yaml.Node, at jsontext.Pointer, depth int) walk = func(node *yaml.Node, at jsontext.Pointer, depth int) { if node == nil || depth > 512 { return } - if st := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: at}); st.Held() { - visit(at, st) + if schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: at}); schemaStatement.Held() { + visit(at, schemaStatement) } switch node.Kind { case yaml.MappingNode: @@ -142,11 +153,11 @@ func TestAdmissionOf_AgreesWithAReadOfItsOwn(t *testing.T) { if lowerer == nil { continue } - statementsOfDocument(lowerer, func(at jsontext.Pointer, st *statement.Statement) { - admission := admissionOf(lowerer.Ctx, st) + statementsOfDocument(lowerer, func(at jsontext.Pointer, schemaStatement *statement.Statement) { + admission := admissionOf(lowerer.Ctx, schemaStatement) former := newAdmissionReader(lowerer.Ctx) - want := former.formerWhole(st) - if admission.cut || admission.reads > maxAdmissionReads || admission.members > maxAdmissionMembers || former.incomplete() { + want := former.formerWhole(schemaStatement) + if admission.reads > maxAdmissionReads || admission.members > maxAdmissionMembers || former.incomplete() { return } compared++ @@ -159,7 +170,8 @@ func TestAdmissionOf_AgreesWithAReadOfItsOwn(t *testing.T) { // TestAdmissionOf_ACycleReadsAlikeWhicheverStatementIsAskedFirst holds the // reading of every schema of a cycle, and of one reaching it and one beside // it, to one answer whichever is asked first: a read is never remembered from -// inside an open cycle. +// inside an open cycle. A loop admits every kind and cuts nothing, so the +// schema reaching it is no cut read. func TestAdmissionOf_ACycleReadsAlikeWhicheverStatementIsAskedFirst(t *testing.T) { t.Parallel() const n = 64 @@ -184,12 +196,33 @@ func TestAdmissionOf_ACycleReadsAlikeWhicheverStatementIsAskedFirst(t *testing.T return out } want := readAll("Beside") - assert.Contains(t, want["Reaches"], "true", "a schema reaching the cycle is cut") for _, first := range []string{"Reaches", "K0", "K31", "K63"} { assert.Equal(t, want, readAll(first), "asked %s first", first) } } +// TestAdmissionOf_ReadsAnIfOnItsOwnCycleUnread holds a schema whose `if` +// leads back to it to reading that `if` as admitting some of each kind, so +// each kind goes to either branch and is admitted in part, whichever of the +// two is asked first: the cycle's seed decides no branch. +func TestAdmissionOf_ReadsAnIfOnItsOwnCycleUnread(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpecVer("3.1.0", + " A: {if: {$ref: '#/components/schemas/A'}, then: {type: string}, else: {type: integer}}\n") + for _, conditionFirst := range []bool{false, true} { + lowerer, _ := LoweredFor(t, spec) + holder := lowerer.Ctx.Statements().Of(lowerer.Doc.Components.Schemas.GetOrZero("A")) + condition := lowerer.Ctx.Statements().Subschema(holder.Logic.If) + if conditionFirst { + admissionOf(lowerer.Ctx, condition) + } + read := admissionOf(lowerer.Ctx, holder) + assert.Equal(t, kindString|kindInteger, read.admits, "condition first: %v", conditionFirst) + assert.Equal(t, kindString|kindInteger, read.partial, "condition first: %v", conditionFirst) + assert.False(t, read.loose, "condition first: %v", conditionFirst) + } +} + // TestAdmissionOf_VisitsEachStatementAndEdgeOnce holds a run's walks to one // visit of each statement they settle and one of each of its conjunct edges, // on a cycle and on a chain each read at three sizes, so the cost of the read @@ -197,30 +230,30 @@ func TestAdmissionOf_ACycleReadsAlikeWhicheverStatementIsAskedFirst(t *testing.T func TestAdmissionOf_VisitsEachStatementAndEdgeOnce(t *testing.T) { t.Parallel() chain := func(n int) string { - var b strings.Builder - b.WriteString(" C0: {type: string}\n") + var builder strings.Builder + builder.WriteString(" C0: {type: string}\n") for i := 1; i < n; i++ { - fmt.Fprintf(&b, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}, {$ref: '#/components/schemas/C%d'}]}\n", + fmt.Fprintf(&builder, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}, {$ref: '#/components/schemas/C%d'}]}\n", i, i-1, max(0, i-2)) } - return b.String() + return builder.String() } - for _, tc := range []struct { + for _, testCase := range []struct { name string shape func(int) string }{{"clique", clique}, {"chain", chain}} { for _, n := range []int{16, 32, 64} { - lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", tc.shape(n))) - for _, js := range lowerer.Doc.Components.Schemas.All() { - admissionOf(lowerer.Ctx, lowerer.Ctx.Statements().Of(js)) + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", testCase.shape(n))) + for _, jsonSchema := range lowerer.Doc.Components.Schemas.All() { + admissionOf(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema)) } store := admissionStore(lowerer.Ctx) edges := 0 - for st := range store.read { - edges += len(conjunctsOf(lowerer.Ctx, st)) + for schemaStatement := range store.read { + edges += len(readEdgesOf(lowerer.Ctx, schemaStatement)) } - assert.Equal(t, len(store.read), store.visits, "%s of %d: each statement once", tc.name, n) - assert.Equal(t, edges, store.edges, "%s of %d: each edge once", tc.name, n) + assert.Equal(t, len(store.read), store.visits, "%s of %d: each statement once", testCase.name, n) + assert.Equal(t, edges, store.edges, "%s of %d: each edge once", testCase.name, n) } } } @@ -229,16 +262,16 @@ func TestAdmissionOf_VisitsEachStatementAndEdgeOnce(t *testing.T) { // that each combine the next and write a format and a value set of their own, // so the paths to the last schema double at each step. func diamonds(comb string, n int) string { - var b strings.Builder - fmt.Fprintf(&b, " D%d: {type: string, format: leaf, enum: [z]}\n", n) + var builder strings.Builder + fmt.Fprintf(&builder, " D%d: {type: string, format: leaf, enum: [z]}\n", n) for i := range n { side := func(tag string) string { return fmt.Sprintf("{%s: [{$ref: '#/components/schemas/D%d'}], type: string, format: f%s%d, enum: [z, %s%d]}", comb, i+1, tag, i, tag, i) } - fmt.Fprintf(&b, " D%d: {%s: [%s, %s]}\n", i, comb, side("a"), side("b")) + fmt.Fprintf(&builder, " D%d: {%s: [%s, %s]}\n", i, comb, side("a"), side("b")) } - return b.String() + return builder.String() } // TestAdmissionOf_MergesWhatGrowsWithTheDocument holds the formats and value- @@ -263,7 +296,7 @@ func TestAdmissionOf_MergesWhatGrowsWithTheDocument(t *testing.T) { // TestInstanceKinds_ReadsEachKindOfInstance pins the kinds each kind of JSON // instance a merge asks of a structure's source is (modelFields.Admits): an // integer apart from a number, which holds it, and none for the null, which -// the nulls walk reads. +// the null answer reads. func TestInstanceKinds_ReadsEachKindOfInstance(t *testing.T) { t.Parallel() for kind, want := range map[merge.JSONInstanceKind]kindSet{ @@ -276,12 +309,11 @@ func TestInstanceKinds_ReadsEachKindOfInstance(t *testing.T) { } // TestAdmission_TakesItsNullFromTheNullsWalk holds the null a conjunct admits, -// as a disjoint report reads it (empty), to the nulls walk's verdict on every +// as a disjoint report reads it (admitsNoValue), to the null answer on every // schema the documents under testdata write and on each spelling of a // `nullable` beside a `type`, at every version, read where the IR holds it, a -// union's variants among it (mayAdmitNull): the admission reads its kinds -// with null aside and derives null no second way. A null read past its budget -// is undecided and set aside. +// union's variants among it (nullAnswerReadingsOf): the admission reads its +// kinds with null aside and derives null no second way. func TestAdmission_TakesItsNullFromTheNullsWalk(t *testing.T) { t.Parallel() specs := specsUnder(t) @@ -297,15 +329,10 @@ func TestAdmission_TakesItsNullFromTheNullsWalk(t *testing.T) { if lowerer == nil { continue } - statementsOfDocument(lowerer, func(at jsontext.Pointer, st *statement.Statement) { - nulls := newNulls(lowerer.Ctx) - nulls.variants = true - want := nulls.conjunct(st, nullSite{}).admits(lowerer.Ctx) - if nulls.conjuncts.Exhausted() { - return - } + statementsOfDocument(lowerer, func(at jsontext.Pointer, schemaStatement *statement.Statement) { + want := nullAnswerReadingsOf(lowerer.Ctx, schemaStatement).mayAdmit(lowerer.Ctx) compared++ - assert.Equal(t, want, !empty(lowerer.Ctx, conjunctAtom{st: st}), "%s#%s", path, at) + assert.Equal(t, want, !admitsNoValue(lowerer.Ctx, conjunctAtom{schemaStatement: schemaStatement}), "%s#%s", path, at) }) } assert.Greater(t, compared, 1000, "the corpus reaches what it compares") @@ -327,7 +354,7 @@ func TestVariantHolders_ClimbsEverySchemaHoldingAUnionBranch(t *testing.T) { at := func(p string) reftable.DocumentPointer { return reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer(p)} } - for _, tc := range []struct { + for _, testCase := range []struct { from string holders []string }{ @@ -343,14 +370,14 @@ func TestVariantHolders_ClimbsEverySchemaHoldingAUnionBranch(t *testing.T) { {"/components/schemas/U/oneOf/0", nil}, {"/components/schemas/U", nil}, } { - want := []*statement.Statement{lowerer.Ctx.Statements().At(at(tc.from))} - for _, h := range tc.holders { + want := []*statement.Statement{lowerer.Ctx.Statements().At(at(testCase.from))} + for _, h := range testCase.holders { want = append(want, lowerer.Ctx.Statements().At(at(h))) } - got := variantHolders(lowerer.Ctx, at(tc.from), want[0]) - require.Len(t, got, len(want), tc.from) + got := variantHolders(lowerer.Ctx, at(testCase.from), want[0]) + require.Len(t, got, len(want), testCase.from) for i := range want { - assert.Same(t, want[i], got[i], "%s: holder %d", tc.from, i) + assert.Same(t, want[i], got[i], "%s: holder %d", testCase.from, i) } } other := lowerer.Ctx.Statements().At(at("/components/schemas/O/oneOf/0")) @@ -368,7 +395,7 @@ func loweredKinds(t *testing.T, doc *ir.Document, id ir.TypeID) kindSet { require.NotNil(t, td.Base, "%s is an alias", id) id = td.Base.Target case *ir.Primitive: - return map[ir.PrimitiveKind]kindSet{ir.PrimitiveString: kindString, ir.PrimitiveAny: anyInstance}[td.PrimitiveKind] + return map[ir.PrimitiveKind]kindSet{ir.PrimitiveString: kindString, ir.PrimitiveAny: everyKindButNull}[td.PrimitiveKind] case *ir.List: return kindArray case *ir.Model: @@ -381,11 +408,11 @@ func loweredKinds(t *testing.T, doc *ir.Document, id ir.TypeID) kindSet { return 0 } -// TestAdmissionOf_KindsAreWhatEachConjunctionLowersTo holds the kinds the -// run's admission reads a conjunction as to the node it lowers to, where a -// shape keyword's claim meets a declaration: a declared kind beside an entry -// or a $ref target the keywords claim another kind of, a use of an inferred -// kind, and compositions over claims. Each is one kind, in both entry orders. +// TestAdmissionOf_KindsAreWhatEachConjunctionLowersTo holds the kinds the run's +// admission reads a conjunction as to the node it lowers to, where a shape +// keyword's claim intersects a declaration: a declared kind beside an entry or +// a $ref target the keywords claim another kind of, a use of an inferred kind, +// and compositions over claims. Each is one kind, in both entry orders. func TestAdmissionOf_KindsAreWhatEachConjunctionLowersTo(t *testing.T) { t.Parallel() const items, ref = "{items: {type: string}}", "{$ref: '#/components/schemas/E'}" @@ -415,8 +442,8 @@ func TestAdmissionOf_KindsAreWhatEachConjunctionLowersTo(t *testing.T) { lowerer, _ := LoweredWith(t, openapitest.ComponentSpecVer("3.1.0", schemas), lowering.Policy{}) lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) doc := lowerer.Document(t) - for name, st := range lowerer.Schemas() { - admission := admissionOf(lowerer.Ctx, st) + for name, schemaStatement := range lowerer.Schemas() { + admission := admissionOf(lowerer.Ctx, schemaStatement) assert.Equal(t, admission.kinds, loweredKinds(t, doc, ir.TypeID("type/openapi/components/schemas/"+name)), "%s swapped=%t", name, swap) if row, ok := rows[name]; ok { assert.Equal(t, row.kinds, admission.kinds, "%s swapped=%t", name, swap) @@ -472,8 +499,8 @@ func TestAdmissionOf_PartialIsWhatAKeywordRefusesInPart(t *testing.T) { } lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", schemas.String())) for name, row := range rows { - st := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) - admission := admissionOf(lowerer.Ctx, st) + schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) + admission := admissionOf(lowerer.Ctx, schemaStatement) assert.Equal(t, row.partial, admission.partial&admission.admits, "%s: %s", name, row.schema) } } @@ -481,16 +508,16 @@ func TestAdmissionOf_PartialIsWhatAKeywordRefusesInPart(t *testing.T) { // fanout writes n statements, each a oneOf of the one value set of n members // and a set of a member of its own, as an allOf entry. func fanout(n int) string { - var b strings.Builder - b.WriteString(" Base: {enum: [") + var builder strings.Builder + builder.WriteString(" Base: {enum: [") for i := range n { - fmt.Fprintf(&b, "b%d, ", i) + fmt.Fprintf(&builder, "b%d, ", i) } - b.WriteString("b]}\n") + builder.WriteString("b]}\n") for i := range n { - fmt.Fprintf(&b, " S%d: {allOf: [{oneOf: [{$ref: '#/components/schemas/Base'}, {enum: [x%d]}]}]}\n", i, i) + fmt.Fprintf(&builder, " S%d: {allOf: [{oneOf: [{$ref: '#/components/schemas/Base'}, {enum: [x%d]}]}]}\n", i, i) } - return b.String() + return builder.String() } // heldMembers is how many value-set members the run's readings hold, each set @@ -506,24 +533,24 @@ func heldMembers(store *admissions) int { } for _, admission := range store.read { count(admission.admitted.values) - for _, set := range admission.admitted.joined { + for _, set := range admission.admitted.unionedSets { count(set) } } return held } -// TestAdmissionOf_AUnionSharesTheSetsItJoins holds the value-set members a +// TestAdmissionOf_AUnionSharesTheSetsItCombines holds the value-set members a // run's readings hold to growth linear in the document where n statements each -// join one set of n members with one of their own: a union holds its +// combine one set of n members with one of their own: a union holds its // branches' sets, which copying them into one would make quadratic. -func TestAdmissionOf_AUnionSharesTheSetsItJoins(t *testing.T) { +func TestAdmissionOf_AUnionSharesTheSetsItCombines(t *testing.T) { t.Parallel() held := func(n int) int { lowerer, diags := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", fanout(n))) require.Empty(t, diags) - for name, st := range lowerer.Schemas() { - require.True(t, admissionOf(lowerer.Ctx, st).admitted.fixed, name) + for name, schemaStatement := range lowerer.Schemas() { + require.True(t, admissionOf(lowerer.Ctx, schemaStatement).admitted.fixed, name) } return heldMembers(admissionStore(lowerer.Ctx)) } @@ -531,17 +558,17 @@ func TestAdmissionOf_AUnionSharesTheSetsItJoins(t *testing.T) { assert.LessOrEqual(t, at32-at16, 5*(at16-at8)/2, "held %d, %d, %d at 8, 16, 32", at8, at16, at32) } -// TestAdmitted_AUnionHoldsEveryMemberOfTheSetsItJoins holds a union's value -// set to the members of each set it joins, read in place: a member of any of +// TestAdmitted_AUnionHoldsEveryMemberOfTheSetsItCombines holds a union's value +// set to the members of each set it combines, read in place: a member of any of // them is one, what it shares with another set is what any of them shares, and // a member two of them hold is one value, so a union holding it twice is // within a set holding it once. -func TestAdmitted_AUnionHoldsEveryMemberOfTheSetsItJoins(t *testing.T) { +func TestAdmitted_AUnionHoldsEveryMemberOfTheSetsItCombines(t *testing.T) { t.Parallel() set := func(keys ...string) admitted { values := map[string]kindSet{} - for _, k := range keys { - values[k] = kindString + for _, key := range keys { + values[key] = kindString } return admitted{kinds: kindString, fixed: true, values: values} } @@ -566,29 +593,66 @@ func TestAdmitted_AUnionHoldsEveryMemberOfTheSetsItJoins(t *testing.T) { } // TestAdmissionOf_AUnionHoldsFewSetsApart holds the sets a union of k -// branches, each naming a set of its own, holds apart to maxJoinedSets beside +// branches, each naming a set of its own, holds apart to maxUnionedSets beside // its first at k, 4k and 16k, so asking whether it holds a member reads a // bounded number of maps whatever its width, and its members to every // branch's. func TestAdmissionOf_AUnionHoldsFewSetsApart(t *testing.T) { t.Parallel() for _, k := range []int{4, 16, 64} { - var b strings.Builder - b.WriteString(" U: {oneOf: [") + var builder strings.Builder + builder.WriteString(" U: {oneOf: [") for j := range k { - fmt.Fprintf(&b, "{$ref: '#/components/schemas/E%d'}, ", j) + fmt.Fprintf(&builder, "{$ref: '#/components/schemas/E%d'}, ", j) } - b.WriteString("]}\n") + builder.WriteString("]}\n") for j := range k { - fmt.Fprintf(&b, " E%d: {enum: [a%d, b%d, c]}\n", j, j, j) + fmt.Fprintf(&builder, " E%d: {enum: [a%d, b%d, c]}\n", j, j, j) } - lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", b.String())) + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", builder.String())) at := reftable.DocumentPointer{Doc: reftable.Source, Pointer: "/components/schemas/U"} union := admissionOf(lowerer.Ctx, lowerer.Ctx.Statements().At(at)).admitted - assert.LessOrEqual(t, len(union.joined), maxJoinedSets, "a union of %d", k) + assert.LessOrEqual(t, len(union.unionedSets), maxUnionedSets, "a union of %d", k) assert.Equal(t, 2*k+1, union.size(), "a union of %d holds each member once", k) for _, admission := range admissionStore(lowerer.Ctx).read { - assert.LessOrEqual(t, len(admission.admitted.joined), maxJoinedSets, "a union of %d", k) + assert.LessOrEqual(t, len(admission.admitted.unionedSets), maxUnionedSets, "a union of %d", k) } } } + +// TestAdmissionOf_ReadsAnIfsBranchesAsEveryPositionIsRead holds the kinds an +// `if` leaves to what its branches admit as the walk reads any schema's +// kinds: a keyword narrowing within a kind removes none and leaves it in +// part, a `$ref` is read through, `false` admits nothing, and a branch read +// loosely, one leading back to the schema writing it among them, leaves +// the schema's read loose. +func TestAdmissionOf_ReadsAnIfsBranchesAsEveryPositionIsRead(t *testing.T) { + t.Parallel() + const everyButString = everyKindButNull &^ kindString + rows := map[string]struct { + schema string + admits, partial kindSet + loose bool + }{ + "Narrowing": {"{if: {type: string}, then: {maxLength: 2}}", everyKindButNull, kindString, false}, + "TypedBound": {"{if: {type: string}, then: {type: string, maxLength: 2}}", everyKindButNull, kindString, false}, + "Required": {"{if: {type: object}, then: {required: [a]}}", everyKindButNull, kindObject, false}, + "Else": {"{if: {type: string}, else: {type: integer}}", kindString | kindInteger, 0, false}, + "ThroughRef": {"{if: {type: string}, then: {$ref: '#/components/schemas/Short'}}", everyKindButNull, kindString, false}, + "False": {"{if: {type: string}, then: false}", everyButString, 0, false}, + "Loose": {"{if: {type: string}, then: {not: {minLength: 3}}}", everyKindButNull, kindString, true}, + "Cycle": {"{if: {type: string}, then: {$ref: '#/components/schemas/Cycle'}}", everyKindButNull, kindString, true}, + } + schemas := " Short: {type: string, maxLength: 2}\n" + for name, row := range rows { + schemas += " " + name + ": " + row.schema + "\n" + } + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", schemas)) + for name, row := range rows { + schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) + admission := admissionOf(lowerer.Ctx, schemaStatement) + assert.Equal(t, row.admits, admission.admits, "%s: %s", name, row.schema) + assert.Equal(t, row.partial, admission.partial&admission.admits, "%s: %s", name, row.schema) + assert.Equal(t, row.loose, admission.loose, "%s: %s", name, row.schema) + } +} diff --git a/compilers/openapi/internal/schema/admissionreader.go b/compilers/openapi/internal/schema/admissionreader.go index 38baaf8a6..84b57faf6 100644 --- a/compilers/openapi/internal/schema/admissionreader.go +++ b/compilers/openapi/internal/schema/admissionreader.go @@ -17,11 +17,11 @@ import ( // A position's reading of what a schema admits is cut twice: past // maxAdmissionReads schemas taken in, each counted per path to it, and past -// maxAdmissionMembers value-set members. Past either, what an election compares +// maxAdmissionMembers value-set members. Past either, what a choice compares // says nothing (admission.past), and the position stays the composition it would // be with no reading at all, which loses nothing; the kinds the read admits and // lowers to stay whole. What each statement admits is read once a run -// (admissionOf), and a position spends what that read takes in, so its verdict +// (admissionOf), and a position spends what that read takes in, so its answer // is the one a read of its own would reach. const ( maxAdmissionReads = 256 @@ -33,23 +33,19 @@ const ( // values a schema admits and mirrors no lowering's dispatch. A reading cut short // is told by incomplete, and says nothing. type admissionReader struct { - c lowering.Ctx - // nullable reports whether the dialect c reads its schemas in defines the - // nullable keyword (specrules.SchemaRules.Defines). A schema the read - // reaches elsewhere is read in its own document's (definesNullableAt). + loweringContext lowering.Ctx + // nullable reports whether the dialect loweringContext reads its schemas in + // defines the nullable keyword (specrules.SchemaRules.Defines). A schema the + // read reaches elsewhere is read in its own document's (definesNullableFor). nullable bool - // cut marks a read that met what no cap answers for: a cycle, a $ref - // landing on no schema or a value it cannot convert. incomplete holds it - // too, and a read past a cap besides. - cut bool - reads budget.Budget - members budget.Budget - // walked hears how many members each value set comparison of the election + reads budget.Budget + members budget.Budget + // walked hears how many members each value set comparison of the choice // looks up, for a test to hold it to the sets it compares; a compile leaves // it nil. walked func(int) // compared hears each comparison of two readings (within), for a test to - // hold an election to one per pair of conjuncts; a compile leaves it nil. + // hold a choice to one per pair of conjuncts; a compile leaves it nil. compared func() } @@ -57,68 +53,70 @@ type admissionReader struct { // loweringContext reads its schemas in. It returns a value so the read lives on // its caller's stack. func newAdmissionReader(loweringContext lowering.Ctx) admissionReader { - return admissionReader{c: loweringContext, nullable: loweringContext.SchemaRules().Defines("nullable"), + return admissionReader{loweringContext: loweringContext, nullable: loweringContext.SchemaRules().Defines("nullable"), reads: budget.New(budget.AtMost(maxAdmissionReads)), members: budget.New(budget.AtMost(maxAdmissionMembers))} } -// incomplete reports whether the read met what it cannot answer for: a cycle -// or more than its budget, a $ref landing on no schema, or a value it cannot -// convert. -func (w *admissionReader) incomplete() bool { return w.reads.Exhausted() || w.members.Exhausted() } - -// of is what js, a schema of any form written anywhere, admits, as the run -// reads it once (admissionOf): what its keywords say, in the dialect of the -// document holding it, conjoined with its allOf, its unions and what its $ref -// lands on. It spends what that read takes in, so a read past either cap, or -// one admissionOf could not settle, is cut short here as reading it would be. -// A $dynamicRef the read meets masks no kind: one the position expands is read -// as what it names, and any other admits every kind. -func (w *admissionReader) of(js *statement.Statement) admitted { - admission := admissionOf(w.c, js) - w.reads.Spend(admission.reads) - w.members.Spend(admission.members) - if admission.cut { - w.cut = true - w.reads.Exhaust() - } +// incomplete reports whether the read met what it cannot answer for: more +// schemas or value-set members than its budget takes. A cycle, a $ref landing +// on no schema and a value set no reading converts each admit every kind, and +// cut nothing. +func (reader *admissionReader) incomplete() bool { + return reader.reads.Exhausted() || reader.members.Exhausted() +} + +// of is what schemaStatement, a schema of any form written anywhere, admits, as +// the run reads it once (admissionOf): what its keywords say, in the dialect of +// the document holding it, conjoined with its allOf, its unions and what its +// $ref lands on. It spends what that read takes in, so a read past either cap +// is cut short here as reading it would be. A $dynamicRef the read meets masks +// no kind: one the position expands is read as what it names, and any other +// admits every kind. +func (reader *admissionReader) of(schemaStatement *statement.Statement) admitted { + return reader.take(admissionOf(reader.loweringContext, schemaStatement)) +} + +// take is what admission admits, spending what its read takes in. +func (reader *admissionReader) take(admission *admission) admitted { + reader.reads.Spend(admission.reads) + reader.members.Spend(admission.members) return admission.admitted } -// lowered is what js admits as the node it lowers to does: what +// lowered is what schemaStatement admits as the node it lowers to does: what // admissionReaderValue reads of it, narrowed to the kinds the kind-inference -// policy read off shape keywords where nothing js declares names a kind -// (loweredAs). An election weighs what each conjunct declares, and reads +// policy read off shape keywords where nothing schemaStatement declares names a +// kind (asLowered). A choice weighs what each conjunct declares, and reads // admissionReader.of; a reader asking whether a position already says what a // keyword does reads this. -func lowered(admissionReaderValue *admissionReader, js *statement.Statement) admitted { - return loweredAs(admissionReaderValue.c, js, admissionReaderValue.of(js)) +func lowered(admissionReaderValue *admissionReader, schemaStatement *statement.Statement) admitted { + return admissionReaderValue.loweredFrom(admissionOf(admissionReaderValue.loweringContext, schemaStatement)) } -// loweredAs is read, what js admits, narrowed to the kinds js lowers to where -// the kind-inference policy read them (lowersTo), as the node it lowers to +// loweredFrom is what admission admits as the node its statement lowers to +// does (asLowered), spending what its read takes in. Where the statement is an +// allOf entry, admission is the reading of the composition listing it +// (composedEntryAdmission). +func (reader *admissionReader) loweredFrom(admission *admission) admitted { + return asLowered(admission, reader.take(admission)) +} + +// asLowered is read narrowed to the kinds admission lowers to where the +// kind-inference policy read them (settleKinds), as the node it lowers to // excludes every other kind. -func loweredAs(loweringContext lowering.Ctx, js *statement.Statement, read admitted) admitted { - if kinds, inferred := lowersTo(loweringContext, js); inferred { - read.kinds &= kinds +func asLowered(admission *admission, read admitted) admitted { + if admission.inferred { + read.kinds &= admission.kinds } return read } -// lowersTo returns the kinds js lowers to, null aside, and whether the -// kind-inference policy read them: what the run's admission of it settles -// (settleKinds), and where that read is cut short, what the policy reads off -// the keywords js writes itself (claimedKinds), else every kind. The election, -// the readers of what a position already says and the lowering of a schema -// naming no kind each read a statement's kinds here. -func lowersTo(loweringContext lowering.Ctx, js *statement.Statement) (kindSet, bool) { - admission := admissionOf(loweringContext, js) - if !admission.cut { - return admission.kinds, admission.inferred - } - if claims := claimedKinds(loweringContext, js.Schema); claims != 0 { - return claims, true - } - return anyInstance, false +// lowersTo returns the kinds schemaStatement lowers to, null aside, and whether +// the kind-inference policy read them: what the run's admission of it settles +// (settleKinds), read whole at any size. +func lowersTo(loweringContext lowering.Ctx, schemaStatement *statement.Statement) (kindSet, bool) { + admission := admissionOf(loweringContext, schemaStatement) + return admission.kinds, admission.inferred } // writtenLowered is what schema's own keywords admit as admissionReaderValue @@ -132,7 +130,7 @@ func writtenLowered(admissionReaderValue *admissionReader, schema *statement.Sch if writesType(schema) { return read } - if kinds, _ := untypedKinds(admissionReaderValue.c, schema); kinds != 0 { + if kinds, _ := untypedKinds(admissionReaderValue.loweringContext, schema); kinds != 0 { read.kinds &= kinds } return read @@ -155,9 +153,9 @@ type declarationSet struct { // the first time it is asked for and kept, so every claim restating the place // shares one reading. type place struct { - decls []*statement.Statement - held *admitted - inner *declarationSet + decls []*statement.Statement + admitsTogether *admitted + inner *declarationSet } // newDeclarationSet returns an empty set, the one form property can be asked @@ -203,33 +201,33 @@ func (d *declarationSet) property(memoizingSchemaReader *statement.MemoizingSche // same budget. func declarationsOf(admissionReaderValue *admissionReader, schema *statement.Schema) declarationSet { out := newDeclarationSet() - out.add(admissionReaderValue.c.Statements(), schema) - out.declare(admissionReaderValue, conjunctsIn(admissionReaderValue.c, schema)) + out.add(admissionReaderValue.loweringContext.Statements(), schema) + out.declare(admissionReaderValue, conjunctsIn(admissionReaderValue.loweringContext, schema)) return out } -// admits returns what p's declarations admit together, as admissionReaderValue -// reads them, read once. -func (p *place) admits(admissionReaderValue *admissionReader) admitted { - if p.held == nil { - held := lowered(admissionReaderValue, p.decls[0]) - for _, schemaStatement := range p.decls[1:] { - held = held.and(lowered(admissionReaderValue, schemaStatement)) +// admits returns what place's declarations admit together, as +// admissionReaderValue reads them, read once. +func (place *place) admits(admissionReaderValue *admissionReader) admitted { + if place.admitsTogether == nil { + admitsTogether := lowered(admissionReaderValue, place.decls[0]) + for _, schemaStatement := range place.decls[1:] { + admitsTogether = admitsTogether.and(lowered(admissionReaderValue, schemaStatement)) } - p.held = &held + place.admitsTogether = &admitsTogether } - return *p.held + return *place.admitsTogether } -// declares returns what p's declarations declare together, as declarationsOf -// reads one, read once. -func (p *place) declares(admissionReaderValue *admissionReader) declarationSet { - if p.inner == nil { +// declares returns what place's declarations declare together, as +// declarationsOf reads one, read once. +func (place *place) declares(admissionReaderValue *admissionReader) declarationSet { + if place.inner == nil { inner := newDeclarationSet() - inner.declare(admissionReaderValue, slices.Clone(p.decls)) - p.inner = &inner + inner.declare(admissionReaderValue, slices.Clone(place.decls)) + place.inner = &inner } - return *p.inner + return *place.inner } // declare adds to d what each schema on stack declares, its conjuncts @@ -240,12 +238,12 @@ func (p *place) declares(admissionReaderValue *admissionReader) declarationSet { // order of each list is no answer. func (d *declarationSet) declare(admissionReaderValue *admissionReader, stack []*statement.Statement) { for len(stack) > 0 && admissionReaderValue.reads.Spend(1) { - st := stack[len(stack)-1] + schemaStatement := stack[len(stack)-1] stack = stack[:len(stack)-1] - d.composed = append(d.composed, st) - d.add(admissionReaderValue.c.Statements(), st.Schema) - stack = append(stack, conjunctsIn(admissionReaderValue.c, st.Schema)...) - if next, _ := declaredOf(admissionReaderValue.c, st); next != nil { + d.composed = append(d.composed, schemaStatement) + d.add(admissionReaderValue.loweringContext.Statements(), schemaStatement.Schema) + stack = append(stack, conjunctsIn(admissionReaderValue.loweringContext, schemaStatement.Schema)...) + if next, _ := declaredOf(admissionReaderValue.loweringContext, schemaStatement); next != nil { stack = append(stack, next) } } @@ -255,40 +253,29 @@ func (d *declarationSet) declare(admissionReaderValue *admissionReader, stack [] // order. func statementsOf(loweringContext lowering.Ctx, list []statement.Subschema) []*statement.Statement { out := make([]*statement.Statement, len(list)) - for i, b := range list { - out[i] = loweringContext.Statements().Subschema(b) + for i, branch := range list { + out[i] = loweringContext.Statements().Subschema(branch) } return out } // union reads a oneOf's or anyOf's branches, any of which an instance may be. -func (w *admissionReader) union(branches []statement.Subschema) admitted { - out := w.of(w.c.Statements().Subschema(branches[0])) - for _, b := range branches[1:] { - out = out.or(w.of(w.c.Statements().Subschema(b))) +func (reader *admissionReader) union(branches []statement.Subschema) admitted { + out := reader.of(reader.loweringContext.Statements().Subschema(branches[0])) + for _, branch := range branches[1:] { + out = out.or(reader.of(reader.loweringContext.Statements().Subschema(branch))) } return out } -// definesNullableAt reports whether the dialect of the document holding js -// defines nullable: where loweringContext's bindings place js, that document's, -// and loweringContext's own for a schema they do not place. -func definesNullableAt(loweringContext lowering.Ctx, js *statement.Statement) bool { - at, ok := siteOf(js.Schema) - if !ok { - return loweringContext.SchemaRules().Defines("nullable") - } - return definesNullableIn(loweringContext, at.Doc) -} - // written reads the keywords schema itself writes that say what a value is, in // a dialect defining nullable where nullable says: `type`, which a `nullable` // adds null to there, `format`, `enum`, `const` and `items`. A schema in c's -// document is read in w.nullable's dialect. -func (w *admissionReader) written(schema *statement.Schema, nullable bool) admitted { +// document is read in reader.nullable's dialect. +func (reader *admissionReader) written(schema *statement.Schema, nullable bool) admitted { out := admitted{kinds: writtenKinds(schema, nullable)} // `items: true` admits what no `items` does, so it holds an element to nothing. - if items := w.c.Statements().Subschema(itemsSchema(schema)); items.Truth == statement.Stated || items.Truth.ReadsFalse() { + if items := reader.loweringContext.Statements().Subschema(itemsSchema(schema)); items.Truth == statement.Stated || items.Truth.ReadsFalse() { out.items = items } if form, ok := formOf(schema); ok { @@ -297,27 +284,37 @@ func (w *admissionReader) written(schema *statement.Schema, nullable bool) admit out.kinds &= kindInteger | kindNull } } + out.typed, out.types = writtenTypes(schema) + if schema.TextKeywords().ContentEncoding != "" { + out.content = schema + } + if root, set := writtenSetRoot(reader.loweringContext, schema); set { + // A value set's members are what its node's ValueType types them. + out.marks = root + } if enumWritten(schema) { - out = out.and(w.valueSet(valueSetOf{schema, "enum"}, schema.Enum())) + out = out.and(reader.valueSet(valueSetOf{schema, "enum"}, schema.Enum())) } if constant := schema.Const(); constant != nil { - out = out.and(w.valueSet(valueSetOf{schema, "const"}, []*yaml.Node{constant})) + out = out.and(reader.valueSet(valueSetOf{schema, "const"}, []*yaml.Node{constant})) } return out } // writtenKinds reads a schema's `type`, with the null a `nullable: true` adds // to it, beside a $ref as anywhere, where the dialect defines the keyword, as -// nullable says. A schema writing none, a null `type` among them (writesType), -// admits every kind, whatever shape keywords it writes: each passes an -// instance of another kind (docs/compilers/openapi.md#shape-applicator). +// nullable says, each word as a schema writing it alone lowers it +// (kindsOfTypeNameOrString). A schema writing none, a null `type` among them +// (writesType), admits every kind, whatever shape keywords it writes: each +// passes an instance of another kind +// (docs/compilers/openapi.md#shape-applicator). func writtenKinds(schema *statement.Schema, nullable bool) kindSet { if !writesType(schema) { return kindAny } var out kindSet for _, jsonSchemaTypeName := range schema.Types() { - out |= kindOfType(jsonSchemaTypeName) + out |= kindsOfTypeNameOrString(jsonSchemaTypeName) } if nullable && nullableTrue(schema) { out |= kindNull @@ -333,7 +330,7 @@ func formOf(schema *statement.Schema) (scalarForm, bool) { return scalarForm{}, false } primitive, listed := formatPrimitive(schema) - return scalarForm{spelled: format, primitive: primitive, listed: listed}, true + return scalarForm{conjunctSchema: schema, spelled: format, primitive: primitive, listed: listed}, true } // valueSetOf keys the members one keyword of one schema writes. @@ -352,16 +349,17 @@ type memberSet struct { // valueSet reads the members of an enum or a const. Reading them is remembered, // so a shared enum costs its members once and not at each position naming it, but -// spending is not: a read's verdict turns on what it spends, so a remembered set -// must cut a read as reading it would, or lowering order would decide. -func (w *admissionReader) valueSet(key valueSetOf, members []*yaml.Node) admitted { - if !w.members.Spend(len(members)) { +// spending is not: a read's answer turns on what it spends, so a remembered set +// must cut a read as reading it would, or lowering order would decide. A set no +// reading converts is no conjunct of the reading, which it leaves every kind +// (docs/compilers/openapi.md#allof-refinement). +func (reader *admissionReader) valueSet(key valueSetOf, members []*yaml.Node) admitted { + if !reader.members.Spend(len(members)) { return admitted{fixed: true} } - set := memberSetOf(w.c, key, members) + set := memberSetOf(reader.loweringContext, key, members) if set.unread { - w.cut = true - w.members.Exhaust() + return admitted{kinds: kindAny} } return admitted{kinds: set.kinds, fixed: true, values: set.values} } @@ -373,15 +371,17 @@ func memberSetOf(loweringContext lowering.Ctx, key valueSetOf, members []*yaml.N } // valueKinds returns the kinds the enum and the const schema writes leave, null -// aside: every kind where it writes neither, and none for a set no reading -// converts, which cuts the read (readOwn). +// aside: every kind where it writes neither, or one no reading converts, which +// is no conjunct of the reading (valueSet). func valueKinds(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { - kinds := anyInstance - if enumWritten(schema) { - kinds &= memberSetOf(loweringContext, valueSetOf{schema, "enum"}, schema.Enum()).kinds + kinds := everyKindButNull + if set := memberSetOf(loweringContext, valueSetOf{schema, "enum"}, schema.Enum()); enumWritten(schema) && !set.unread { + kinds &= set.kinds } if constant := schema.Const(); constant != nil { - kinds &= memberSetOf(loweringContext, valueSetOf{schema, "const"}, []*yaml.Node{constant}).kinds + if set := memberSetOf(loweringContext, valueSetOf{schema, "const"}, []*yaml.Node{constant}); !set.unread { + kinds &= set.kinds + } } return kinds } @@ -402,49 +402,59 @@ func readMembers(members []*yaml.Node) memberSet { // within reports whether every value a admits b admits, so far as what a reading // holds can say. -func (w *admissionReader) within(a, b admitted) bool { - if w.compared != nil { - w.compared() +func (reader *admissionReader) within(a, b admitted) bool { + if reader.compared != nil { + reader.compared() } - return a.kindsWithin(b) && a.valuesWithin(b) && a.formsWithin(b) && w.itemsWithin(a, b) + return a.kindsWithin(b) && a.valuesWithin(b) && a.formsWithin(b) && reader.itemsWithin(a, b) } // itemsWithin reports whether a's elements are all b's elements can be. -func (w *admissionReader) itemsWithin(a, b admitted) bool { +func (reader *admissionReader) itemsWithin(a, b admitted) bool { if b.items == nil || a.items == b.items { return true } - return a.items != nil && w.restates(w.of(a.items), a.items, b.items) + return a.items != nil && reader.restates(reader.of(a.items), a.items, b.items) } -// restates reports whether what held admits, read from from, says all that js -// writes: the same schema written twice, nothing a keyword of js adds, or no value -// at all, which is within anything. A keyword no reading compares, a $ref among -// them, says what it cannot tell, and a null one says nothing. -func (w *admissionReader) restates(held admitted, from, js *statement.Statement) bool { - if !held.reachable() || sameText(w.c, from, js) { +// restates reports whether what held admits, read from from, says all that +// schemaStatement writes: the same schema written twice, nothing a keyword of +// schemaStatement adds, or no value at all, which is within anything. A keyword +// no reading compares, a $ref among them, says what it cannot tell, and a null +// one says nothing. +func (reader *admissionReader) restates(held admitted, from, schemaStatement *statement.Statement) bool { + if !held.reachable() || sameText(reader.loweringContext, from, schemaStatement) { return true } - if js.Truth != statement.Stated || w.reads.Exhausted() { + if schemaStatement.Truth != statement.Stated || reader.reads.Exhausted() { return false } - return !slices.ContainsFunc(js.Keys, func(key statement.Key) bool { - return !annotation.WritesKeywordLeftOut(js.Schema, key.Name) && !w.holds(held, js.Schema, key.Name) + return !slices.ContainsFunc(schemaStatement.Keys, func(key statement.Key) bool { + return !annotation.WritesKeywordLeftOut(schemaStatement.Schema, key.Name) && !reader.holds(held, schemaStatement.Schema, key.Name) }) } // holds reports whether what held admits says all that schema's keyword key // does, so a position lowered to held loses nothing leaving it unread. -func (w *admissionReader) holds(held admitted, schema *statement.Schema, key string) bool { +func (reader *admissionReader) holds(held admitted, schema *statement.Schema, key string) bool { switch key { case "type": - return held.kindsWithin(admitted{kinds: writtenKinds(schema, w.nullable)}) + return held.kindsWithin(admitted{kinds: writtenKinds(schema, reader.nullable)}) case "format": - return held.formsWithin(w.written(schema, w.nullable)) + return held.formsWithin(reader.written(schema, reader.nullable)) case "enum", "const": - return held.valuesWithin(w.written(schema, w.nullable)) + // A set no reading converts is no conjunct of the reading, which + // leaves it every kind: kept and reported as written, never said. + members := schema.Enum() + if key == "const" { + members = []*yaml.Node{schema.Const()} + } + if memberSetOf(reader.loweringContext, valueSetOf{schema, key}, members).unread { + return false + } + return held.valuesWithin(reader.written(schema, reader.nullable)) case "items": - return w.itemsWithin(held, w.written(schema, w.nullable)) + return reader.itemsWithin(held, reader.written(schema, reader.nullable)) default: return false } diff --git a/compilers/openapi/internal/schema/admissionreader_internal_test.go b/compilers/openapi/internal/schema/admissionreader_internal_test.go index 210e8f212..eae04ba53 100644 --- a/compilers/openapi/internal/schema/admissionreader_internal_test.go +++ b/compilers/openapi/internal/schema/admissionreader_internal_test.go @@ -21,19 +21,19 @@ import ( // nullable adds null to the type beside it and a 3.1 one adds nothing. func TestAdmissionReader_ASchemaNoBindingPlacesIsReadInTheContextsDialect(t *testing.T) { t.Parallel() - js := &oas3.JSONSchema[oas3.Referenceable]{} - valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader("{type: string, nullable: true}"), js) + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader("{type: string, nullable: true}"), jsonSchema) require.NoError(t, err) require.Empty(t, valErrs, "the fixture parses cleanly") - for _, tc := range []struct { + for _, testCase := range []struct { version string kinds kindSet }{ {"3.0.3", kindString | kindNull}, {"3.1.0", kindString}, } { - lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer(tc.version, " A: {type: string}\n")) + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer(testCase.version, " A: {type: string}\n")) admissionReader := newAdmissionReader(lowerer.Ctx) - assert.Equal(t, tc.kinds, admissionReader.of(Standalone(js)).kinds, tc.version) + assert.Equal(t, testCase.kinds, admissionReader.of(Standalone(jsonSchema)).kinds, testCase.version) } } diff --git a/compilers/openapi/internal/schema/admitted.go b/compilers/openapi/internal/schema/admitted.go index 9f95bf399..a0023f4bd 100644 --- a/compilers/openapi/internal/schema/admitted.go +++ b/compilers/openapi/internal/schema/admitted.go @@ -15,12 +15,14 @@ import ( "github.com/dexpace/morphic/ir" ) -// scalarForm is one `format` a reading holds: as written, and the primitive the -// type and format beside each other select where the table has a row for them. +// scalarForm is one `format` a reading holds: as written, the primitive the +// type and format beside each other select where the table has a row for them, +// and the conjunct writing it (formatConjunct). type scalarForm struct { - spelled string - primitive ir.PrimitiveKind - listed bool + conjunctSchema *statement.Schema + spelled string + primitive ir.PrimitiveKind + listed bool } // narrows reports whether f is the form scalarFormValue is, or a narrower one. @@ -38,15 +40,31 @@ func (f scalarForm) narrows(scalarFormValue scalarForm) bool { type admitted struct { kinds kindSet // fixed marks a value set, values then holding each member's key (memberOf) - // with its kind, none where the set is empty, and joined the sets a union - // adds to it (joinSets), each still the branch's own where it can be: a + // with its kind, none where the set is empty, and unionedSets the sets a union + // adds to it (unionOfValueSets), each still the branch's own where it can be: a // union shares its branches' sets rather than copying them, no member is // held twice, and none is written to. - fixed bool - values map[string]kindSet - joined []map[string]kindSet - forms []scalarForm - items *statement.Statement + fixed bool + values map[string]kindSet + unionedSets []map[string]kindSet + forms []scalarForm + items *statement.Statement + // typed marks a reading whose conjunction writes a `type`, types the kinds + // those name together, null aside, and content the first schema writing + // contentEncoding: with forms, what Scalar the conjunction lowers to + // (settledRoot), which no union's reading names (branchesRead). + typed bool + types kindSet + content *statement.Schema + // marks is the boundRoot of the value sets and union branches the reading + // takes in, which no format beside them moves: a value set's is its node's + // ValueType's (writtenSetRoot), a branch's its settled root. + marks boundRoot + // root is what its string and number instances are once its statement is + // read (settledRoot): the marks, and where no value set fixes it, those of + // the Scalar its conjunction lowers to, whichever conjunct writes its type, + // format or contentEncoding. + root boundRoot } // hasMember reports whether a's value set holds the member keyed key. @@ -54,7 +72,7 @@ func (a admitted) hasMember(key string) bool { if _, ok := a.values[key]; ok { return true } - for _, set := range a.joined { + for _, set := range a.unionedSets { if _, ok := set[key]; ok { return true } @@ -69,7 +87,7 @@ func (a admitted) members(yield func(string, kindSet) bool) { return } } - for _, set := range a.joined { + for _, set := range a.unionedSets { for v, kind := range set { if !yield(v, kind) { return @@ -81,7 +99,7 @@ func (a admitted) members(yield func(string, kindSet) bool) { // size is how many members a's value set holds. func (a admitted) size() int { n := len(a.values) - for _, set := range a.joined { + for _, set := range a.unionedSets { n += len(set) } return n @@ -93,18 +111,36 @@ func (a admitted) and(b admitted) admitted { out := a out.kinds &= b.kinds out.forms = slices.Concat(a.forms, b.forms) + out.marks = a.marks | b.marks + out.typed, out.types = a.typed || b.typed, conjoinedTypes(a, b) + if out.content == nil { + out.content = b.content + } if out.items == nil { out.items = b.items } switch { case a.fixed && b.fixed: - out.values, out.joined = sharedValues(a, b), nil + out.values, out.unionedSets = sharedValues(a, b), nil case b.fixed: - out.fixed, out.values, out.joined = true, b.values, b.joined + out.fixed, out.values, out.unionedSets = true, b.values, b.unionedSets } return out } +// conjoinedTypes returns the kinds the types a and b write name together: +// those both name where each writes one, else those of the one writing one. +func conjoinedTypes(a, b admitted) kindSet { + switch { + case a.typed && b.typed: + return a.types & b.types + case b.typed: + return b.types + default: + return a.types + } +} + // sharedValues returns the members a's and b's value sets hold, walking the // smaller: a value set is shared by every reader of it, so neither may be // written to. @@ -122,29 +158,38 @@ func sharedValues(a, b admitted) map[string]kindSet { } // or is what either of a and b admits: a union, whose branches hold no one -// format or element schema an instance is held to, and whose value set joins -// theirs. +// format or element schema an instance is held to, and whose value set combines +// theirs. Each is a settled reading, whose root the union's holds. func (a admitted) or(b admitted) admitted { - out := admitted{kinds: a.kinds | b.kinds, fixed: a.fixed && b.fixed} + out := admitted{kinds: a.kinds | b.kinds, fixed: a.fixed && b.fixed, root: a.root | b.root} if out.fixed { - out.values, out.joined = joinSets(a, b) + out.values, out.unionedSets = unionOfValueSets(a, b) } return out } -// maxJoinedSets bounds the sets a value set joins beside its first, so asking -// whether it holds a member reads at most that many more maps. -const maxJoinedSets = 8 +// branchesRead returns a, what a union's settled branches admit, as the +// conjunction beside the union reads it: its marks the roots its branches +// settle to, of a lone branch as of several, and no type named, as a format +// beside a union types none of its branches. +func (a admitted) branchesRead() admitted { + a.marks, a.typed, a.types, a.content = a.root, false, 0, nil + return a +} + +// maxUnionedSets bounds the sets a value set combines beside its first, so +// asking whether it holds a member reads at most that many more maps. +const maxUnionedSets = 8 -// joinSets returns the sets the union of a's and b's value sets holds: the -// larger's as they are, and the smaller's where the larger holds none of their -// members, else one set of the members it lacks, so no member is held twice. -// Past maxJoinedSets sets beside the first, they are copied into one. -func joinSets(a, b admitted) (map[string]kindSet, []map[string]kindSet) { +// unionOfValueSets returns the sets the union of a's and b's value sets holds: +// the larger's as they are, and the smaller's where the larger holds none of +// their members, else one set of the members it lacks, so no member is held +// twice. Past maxUnionedSets sets beside the first, they are copied into one. +func unionOfValueSets(a, b admitted) (map[string]kindSet, []map[string]kindSet) { if b.size() > a.size() { a, b = b, a } - added := slices.Concat([]map[string]kindSet{b.values}, b.joined) + added := slices.Concat([]map[string]kindSet{b.values}, b.unionedSets) for v := range b.members { if a.hasMember(v) { rest := make(map[string]kindSet, b.size()) @@ -157,12 +202,12 @@ func joinSets(a, b admitted) (map[string]kindSet, []map[string]kindSet) { break } } - joined := slices.Concat(a.joined, slices.DeleteFunc(added, func(set map[string]kindSet) bool { return len(set) == 0 })) - if len(joined) <= maxJoinedSets { - return a.values, joined + unionedSets := slices.Concat(a.unionedSets, slices.DeleteFunc(added, func(set map[string]kindSet) bool { return len(set) == 0 })) + if len(unionedSets) <= maxUnionedSets { + return a.values, unionedSets } one := make(map[string]kindSet, a.size()+b.size()) - for _, set := range slices.Concat([]map[string]kindSet{a.values}, joined) { + for _, set := range slices.Concat([]map[string]kindSet{a.values}, unionedSets) { maps.Copy(one, set) } return one, nil @@ -217,10 +262,10 @@ func (a admitted) walkWithin(b admitted) (within bool, walked int) { return true, walked } -// narrowedTo reports whether joint, what a and the conjuncts beside it admit -// together, leaves out a kind or a value a admits. -func (a admitted) narrowedTo(joint admitted) bool { - return a.kinds != joint.kinds || !a.valuesWithin(joint) +// narrowedTo reports whether admittedTogether, what a and the conjuncts beside +// it admit together, leaves out a kind or a value a admits. +func (a admitted) narrowedTo(admittedTogether admitted) bool { + return a.kinds != admittedTogether.kinds || !a.valuesWithin(admittedTogether) } // formsWithin reports whether a is held to some form narrowing each of b's. diff --git a/compilers/openapi/internal/schema/agreement.go b/compilers/openapi/internal/schema/agreement.go index 2cd6e1935..a19a6d614 100644 --- a/compilers/openapi/internal/schema/agreement.go +++ b/compilers/openapi/internal/schema/agreement.go @@ -11,44 +11,50 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/merge" "github.com/dexpace/morphic/compilers/openapi/internal/provenance" "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" "github.com/dexpace/morphic/ir" ) // agreement is what the conjuncts of one allOf write for the position holding -// it, entry by entry: the first writer's rendering of each, the entries two -// writers render apart, and what the writers of each bound say of it together. -// It is a set over the conjuncts, so no order decides what agrees. +// it, entry by entry: the first conjunct's rendering of each, the entries two +// conjuncts render apart, and what the conjuncts of each bound say of it +// together. It is a set over the conjuncts, so no order decides what agrees. type agreement struct { - c lowering.Ctx - first map[string]foldRendering - split map[string]bool - bounds map[string]*boundReading + loweringContext lowering.Ctx + first map[string]foldRendering + split map[string]bool + bounds map[string]*boundReading + // formats is each conjunct's format, which agree where they nest + // (formatsNest). + formats []*statement.Schema + // unrendered is, for each conjunct, the entries it writes that render to + // no value, an extension no JSON holds among them, which report themselves + // and agree with nothing. + unrendered map[*statement.Schema]map[string]bool } // newAgreement returns an agreement no conjunct has written to, reading each // conjunct's value bounds in its dialect (exclusiveIsBoolean). func newAgreement(loweringContext lowering.Ctx) *agreement { - return &agreement{c: loweringContext, first: map[string]foldRendering{}, split: map[string]bool{}, - bounds: map[string]*boundReading{}} + return &agreement{loweringContext: loweringContext, first: map[string]foldRendering{}, split: map[string]bool{}, + bounds: map[string]*boundReading{}, unrendered: map[*statement.Schema]map[string]bool{}} } // write records what conjunct writes for the position and returns its entries, -// rendering each once: the first writer's is compared with every later one's. +// rendering each once: the first conjunct's is compared with every later one's. func (a *agreement) write(conjunct *statement.Schema) []string { var entries []string var cons *ir.Constraints read := false for _, key := range conjunct.Keys { keyword := key.Name - entry, fold := foldEntry(a.c, conjunct, keyword) + entry, fold := foldKey(a.loweringContext, conjunct, keyword) if !fold || annotation.WritesKeywordLeftOut(conjunct, keyword) { continue } entries = append(entries, entry) - rendered := foldValue(conjunct, entry) - if writesFalseFlag(entry, rendered) { - // A false states nothing a true elsewhere disagrees with - // (annotation.EffectiveDeprecated), so it is compared with nothing. + rendered, compared := a.render(conjunct, keyword, entry) + if !compared { continue } if held, ok := a.first[entry]; !ok { @@ -56,92 +62,147 @@ func (a *agreement) write(conjunct *statement.Schema) []string { } else if !held.agrees(rendered) { a.split[entry] = true } + if entry == "format" { + a.formats = append(a.formats, conjunct) + } if !isBound(entry) { continue } if !read { - // A bound no decimal spells, or in the other form than the dialect's, - // is the rule table's to report (docs/compilers/openapi.md#constraints). - // What else it warns of and keeps, the lowering does where it reads an - // entry that folds; an entry kept apart is kept whole instead. - // Nothing this reading places is kept, so it places at the zero Doc. - cons, _, _ = annotation.Constraints(conjunct, annotation.AllBounds, exclusiveIsBoolean(a.c, conjunct), "", provenance.Doc{}) - cons = merge.Constraints(cons, heldCollectionBounds(conjunct)) - read = true + cons, read = writtenBounds(a.loweringContext, conjunct), true } a.bound(entry).add(boundOf(entry, cons)) } return entries } -// isBound reports whether entry is a bound whose writers agree by meeting: a +// render returns entry rendered for comparison, and false for an extension no +// JSON holds: every keeping leaves it out (annotation.ExtensionNoJSONHolds), so +// it cannot set two conjuncts apart. An entry rendering to no value is noted +// unrendered. +func (a *agreement) render(conjunct *statement.Schema, keyword, entry string) (foldRendering, bool) { + noJSON := annotation.ExtensionNoJSONHolds(conjunct, keyword) + var rendered foldRendering + if !noJSON { + rendered = foldValue(a.loweringContext, conjunct, entry) + } + if noJSON || rendered.err != nil { + if a.unrendered[conjunct] == nil { + a.unrendered[conjunct] = map[string]bool{} + } + a.unrendered[conjunct][entry] = true + } + return rendered, !noJSON +} + +// writtenBounds returns the bounds conjunct writes, read in its dialect +// (exclusiveIsBoolean), as the conjuncts of each bound intersect them. A bound +// no decimal spells, or in the other form than the dialect's, is the rule +// table's to report (docs/compilers/openapi.md#constraints). What else it warns +// of and keeps, the lowering does where it reads an entry that folds; an entry +// kept apart is kept whole instead. Nothing this reading places is kept, so it +// places at the zero Doc. +func writtenBounds(loweringContext lowering.Ctx, conjunct *statement.Schema) *ir.Constraints { + cons, _, _ := annotation.Constraints(conjunct, annotation.AllBounds, exclusiveIsBoolean(loweringContext, conjunct), "", provenance.Doc{}) + return merge.Constraints(cons, heldCollectionBounds(conjunct)) +} + +// isBound reports whether entry is a bound whose conjuncts agree by intersecting: a // value bound or a count. A uniqueItems that folds is `true` (referenceHolds), -// so its writers agree by rendering it alike. +// so its conjuncts agree by rendering it alike. func isBound(entry string) bool { return slices.Contains(valueConstraintKeywords, entry) || entry == "minItems" || entry == "maxItems" } // bound returns the reading of the value bound entry, starting one. func (a *agreement) bound(entry string) *boundReading { - b, ok := a.bounds[entry] + reading, ok := a.bounds[entry] if !ok { - b = &boundReading{} - a.bounds[entry] = b + reading = &boundReading{} + a.bounds[entry] = reading } - return b + return reading } -// writesFalseFlag reports whether rendered is a false of a boolean annotation -// JSON Schema reads in force where any occurrence is true: deprecated, readOnly -// or writeOnly. -func writesFalseFlag(entry string, rendered foldRendering) bool { - switch entry { - case "deprecated", "readOnly", "writeOnly": - return rendered.err == nil && string(rendered.raw) == "false" - default: +// apart reports whether the conjuncts of entry disagree, so none of them folds: +// a bound agrees where the values its conjuncts state intersect, as a +// redeclared field's bounds do (merge.Constraints), and any entry agrees where +// every conjunct renders it alike. +func (a *agreement) apart(entry string) bool { + if reading, ok := a.bounds[entry]; ok && reading.valuesIntersect() { return false } -} - -// apart reports whether the writers of entry disagree, so none of them folds: a -// bound agrees where the values its writers state meet, as a redeclared field's -// bounds do (merge.Constraints), and any entry agrees where every writer renders -// it alike. -func (a *agreement) apart(entry string) bool { - if b, ok := a.bounds[entry]; ok && b.meets() { + if entry == "format" && formatsNest(a.formats) { return false } return a.split[entry] } -// boundReading is what the writers of one bound say of it together. +// formatsNest reports whether the formats conjuncts write nest pairwise, so the +// narrowest names them all (formatConjunct), as a narrower bound does for a +// wider one. +func formatsNest(conjunctList []*statement.Schema) bool { + for i, a := range conjunctList { + for _, b := range conjunctList[i+1:] { + if !formatsRelate(a, b) { + return false + } + } + } + return true +} + +// formatsRelate reports whether the formats a and b write nest, one within the +// other. +func formatsRelate(a, b *statement.Schema) bool { + primitiveA, knownA := writtenFormatPrimitive(a) + primitiveB, knownB := writtenFormatPrimitive(b) + if !knownA || !knownB { + return writtenFormat(a) == writtenFormat(b) + } + rel := typeformat.Relate(primitiveA, primitiveB) + return rel == typeformat.Same || rel == typeformat.ANarrower || rel == typeformat.BNarrower +} + +// writtenFormatPrimitive returns the primitive the format schema writes +// selects, whether or not schema declares a type. +func writtenFormatPrimitive(schema *statement.Schema) (ir.PrimitiveKind, bool) { + if primitive, ok := formatPrimitive(schema); ok { + return primitive, true + } + return typelessFormatPrimitive(schema, func(ir.PrimitiveKind) bool { return true }) +} + +// boundReading is what the conjuncts of one bound say of it together. type boundReading struct { - // met is what they say together, nil before one states a value. - met *ir.Constraints - // disjoint marks two values no one value holds (merge.Meets). + // intersection is what they say together, nil before one states a value. + intersection *ir.Constraints + // disjoint marks two values no one value states (merge.IntersectsWithoutDisagreement). disjoint bool } -// add records one writer's reading of the bound. A writer whose keyword fills no -// field, a 3.0 exclusive modifier with no bound beside it, one of false, or a -// value the reader refused, states nothing a value needs to meet, so it parts no -// writer: where its entry folds, its own reading is reported and kept there. +// add records one conjunct's reading of the bound. A conjunct whose keyword +// fills no field, a 3.0 exclusive modifier with no bound beside it, one of +// false, or a value the reader refused, states nothing a value needs to +// intersect, so it parts no conjunct: where its entry folds, its own reading is +// reported and kept there. func (b *boundReading) add(bound ir.Constraints) { switch { case bound == ir.Constraints{}: - case b.met == nil: - b.met = &bound - case !merge.Meets(b.met, &bound): + case b.intersection == nil: + b.intersection = &bound + case !merge.IntersectsWithoutDisagreement(b.intersection, &bound): b.disjoint = true default: - b.met = merge.Constraints(b.met, &bound) + b.intersection = merge.Constraints(b.intersection, &bound) } } -// meets reports whether the values the writers state meet. Whether two meet is a -// set's answer: an ordered bound always meets another, and one with no order, or -// a literal no decimal holds, meets only one written alike. -func (b *boundReading) meets() bool { return !b.disjoint } +// valuesIntersect reports whether the values the conjuncts state intersect. +// Whether two intersect is a set's answer: an ordered bound always intersects +// another, and one with no order, or a literal no decimal holds, intersects +// only one written alike. +func (b *boundReading) valuesIntersect() bool { return !b.disjoint } // boundOf returns the fields of cons the bound keyword entry fills. A 3.0 // exclusive modifier moves the bound beside it, so a minimum and its exclusive diff --git a/compilers/openapi/internal/schema/agreement_internal_test.go b/compilers/openapi/internal/schema/agreement_internal_test.go index 6dc5a87a0..611870e67 100644 --- a/compilers/openapi/internal/schema/agreement_internal_test.go +++ b/compilers/openapi/internal/schema/agreement_internal_test.go @@ -18,8 +18,9 @@ import ( // TestBoundOf_FillsAFieldForEveryValueBound holds boundOf to // valueConstraintKeywords: each keyword the constraint reader fills a field for -// projects a field of a full reading, so a keyword the list gains and the switch -// lacks agrees with nothing it should meet, and anything else projects none. +// projects a field of a full reading, so a keyword the list gains and the +// switch lacks agrees with nothing it should intersect, and anything else +// projects none. func TestBoundOf_FillsAFieldForEveryValueBound(t *testing.T) { t.Parallel() full := &ir.Constraints{ @@ -35,25 +36,25 @@ func TestBoundOf_FillsAFieldForEveryValueBound(t *testing.T) { } // TestAgreement_ReadsABoundInTheDialectOfItsSchemas pins the dialect the -// writers of a value bound are read in. A numeric exclusiveMinimum is a bound -// from 3.1 on, so two writers of one meet; in 3.0 it is no bound of the dialect, -// which the load phase reports and the lowering drops, so the writers state -// nothing, and part no writer however they write it. +// conjuncts of a value bound are read in. A numeric exclusiveMinimum is a bound +// from 3.1 on, so two conjuncts of one intersect; in 3.0 it is no bound of the +// dialect, which the load phase reports and the lowering drops, so the +// conjuncts state nothing, and part no conjunct however they write it. func TestAgreement_ReadsABoundInTheDialectOfItsSchemas(t *testing.T) { t.Parallel() conjunct := func(text string) *oas3.Schema { - js := &oas3.JSONSchema[oas3.Referenceable]{} - valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader(text), js) + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader(text), jsonSchema) require.NoError(t, err) require.Empty(t, valErrs, "the fixture parses cleanly") - return js.GetSchema() + return jsonSchema.GetSchema() } - for version, met := range map[string]*ir.Constraints{"3.0.3": nil, "3.1.0": {ExclusiveMin: new(ir.BigVal("6"))}} { + for version, intersection := range map[string]*ir.Constraints{"3.0.3": nil, "3.1.0": {ExclusiveMin: new(ir.BigVal("6"))}} { lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer(version, " A: {type: string}\n")) - a := newAgreement(lowerer.Ctx) - a.write(StandaloneSchema(conjunct("{exclusiveMinimum: 5}"))) - a.write(StandaloneSchema(conjunct("{exclusiveMinimum: 6}"))) - assert.Equal(t, met, a.bounds["exclusiveMinimum"].met, version) - assert.False(t, a.apart("exclusiveMinimum"), version) + entryAgreement := newAgreement(lowerer.Ctx) + entryAgreement.write(StandaloneSchema(conjunct("{exclusiveMinimum: 5}"))) + entryAgreement.write(StandaloneSchema(conjunct("{exclusiveMinimum: 6}"))) + assert.Equal(t, intersection, entryAgreement.bounds["exclusiveMinimum"].intersection, version) + assert.False(t, entryAgreement.apart("exclusiveMinimum"), version) } } diff --git a/compilers/openapi/internal/schema/allof.go b/compilers/openapi/internal/schema/allof.go index 74d9c2fa6..500f0cfad 100644 --- a/compilers/openapi/internal/schema/allof.go +++ b/compilers/openapi/internal/schema/allof.go @@ -17,6 +17,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" "github.com/dexpace/morphic/compilers/openapi/internal/merge" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) @@ -26,51 +27,116 @@ import ( // entries are flattened first. Inline entries contribute their properties, // with provenance into their source entry. // -// Value constraints written beside the allOf (minProperties, ...), or on an entry -// that folds, are read as lowerModel reads a plain object's, on the same field, -// not Unmodeled (GitHub #407). A composition that leaves only a -// catch-all is a map, as a plain object's is (objectNode). Where discriminated is -// false, a union the model composes, mixin where not nil, took s's discriminator -// (lowerSubtypeUnion). fin finishes the node. -func lowerAllOf(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, discriminated bool, mixin *unionAt, - fin finisher, -) (ir.TypeID, []ir.Diagnostic) { +// Value constraints written beside the allOf (minProperties, ...), or on an +// entry that folds, are read as lowerModelAt reads a plain object's, on the +// same field, not Unmodeled (GitHub #407). A composition that leaves only a +// catch-all is a map, as a plain object's is (objectNode). Where discriminated +// is false, a union the model composes, mixin where not nil, took schema's +// discriminator (lowerSubtypeUnion). when may defer registering it +// (composeOneReference). +func lowerAllOf(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, discriminated bool, mixin *loweredUnionSite, + when registration, +) (builtPosition, []ir.Diagnostic) { + if built, diags, composed := composeOneReference(loweringContext, types, depth, schema, pointer, discriminated, mixin, when); composed { + return built, diags + } var diags []ir.Diagnostic - id := internNode(loweringContext, ts, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + var pendingKeeps annotation.PendingKeeps + built := internNode(loweringContext, types, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { // The one flattened list; the readers composeModel calls take it, not // schema. - td, read, modelDiags := composeModel(loweringContext, ts, depth, schema, pointer, discriminated, common, readAllOf(loweringContext, schema, pointer)) + typeDef, read, modelDiags := composeModel(loweringContext, types, depth, schema, pointer, discriminated, common, readAllOf(loweringContext, schema, pointer), &pendingKeeps) diags = modelDiags - diags = append(diags, composeMixin(loweringContext, ts, depth, td, mixin, pointer)...) - return td, read - }, fin) - return id, diags + diags = append(diags, composeMixin(loweringContext, types, depth, typeDef, mixin, pointer)...) + return typeDef, read + }) + built.pendingKeeps.AddAll(pendingKeeps) + return built, diags +} + +// registration is when a node the walk builds is registered: at its build, as +// a node is wherever a revisit may meet it, or once the frame lowering its +// position has finished it and judged what it holds (schemaBody, hoistHolding). +type registration bool + +const ( + registeredAtBuild registration = false + registeredWhenFinished registration = true +) + +// composeOneReference builds, on no registry, the Model schema, written at +// pointer, composes where it is one reference and what is written beside it +// (composesOneReference), when is registeredWhenFinished and no union is mixed +// in, for the frame lowering the position to register it where it holds +// anything (schemaBody). It reports false where it builds none. +func composeOneReference(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, discriminated bool, + mixin *loweredUnionSite, when registration, +) (builtPosition, []ir.Diagnostic, bool) { + if when != registeredWhenFinished || mixin != nil { + return builtPosition{}, nil, false + } + comp := readAllOf(loweringContext, schema, pointer) + if !composesOneReference(loweringContext, schema, comp) { + return builtPosition{}, nil, false + } + common := commonFor(loweringContext, loweringContext.IDs().ForPointer(pointer), pointer) + built := builtPosition{id: common.ID, pending: true} + typeDef, read, diags := composeModel(loweringContext, types, depth, schema, pointer, discriminated, common, comp, &built.pendingKeeps) + built.node, built.read, built.closesAfterComposition = typeDef, read, closedAfterComposition(typeDef) + return built, diags, true +} + +// composesOneReference reports whether comp, the conjuncts of schema, is one +// $ref and what is written beside it, lowering to an object alone, whose Model +// holds nothing but its Base where the keywords beside keep nothing: that +// position then lowers as the reference alone does, and a node built for it +// elsewhere is that same Model (buildOwnNode). A read cut short composes +// whatever it holds. +func composesOneReference(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) bool { + if len(comp.entries) != 1 || comp.entries[0].schema.Ref == nil { + return false + } + kinds, _ := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) + return kinds == kindObject } // composeModel builds the Model of schema, written at pointer, composing comp, -// its flattened conjuncts, and returns what it read of schema. -func composeModel(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, - discriminated bool, common ir.TypeCommon, comp allOfComposition, +// its flattened conjuncts, adding to pendingKeeps what its entries keep beside +// it, and returns what it read of schema. +func composeModel(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + discriminated bool, common ir.TypeCommon, comp allOfComposition, pendingKeeps *annotation.PendingKeeps, ) (ir.TypeDef, keySet, []ir.Diagnostic) { - if admissionOf(loweringContext, loweringContext.Statements().Read(schema)).inferred { + if bottomAt(loweringContext, schema) { + return composeBottom(loweringContext, schema, common, comp, pointer) + } + if _, inferred := lowersTo(loweringContext, loweringContext.Statements().Read(schema)); inferred || decisionOf(loweringContext, schema).inferred { // No conjunct declares the kind: the model is one by the - // kind-inference policy's reading of their shape keywords. + // kind-inference policy's reading of their shape keywords, those + // outside every union where a $ref beside them admits every kind. common.Provenance.Inferred = ir.JoinInferred(common.Provenance.Inferred, lowering.KindInferenceHeuristic) } - cons, diags := ConstraintsOf(loweringContext, &common.Unmodeled, schema, positionFoldedEntries(loweringContext, schema, pointer, ir.TypeRef{}), pointer, comp.bounds) + cons, diags := ConstraintsOf(loweringContext, &common.Unmodeled, schema, positionFlattenedEntries(loweringContext, schema, pointer, ir.TypeRef{}), pointer, comp.homes.value) model := &ir.Model{TypeCommon: common, Constraints: cons} - diags = append(diags, diagDisjointConjuncts(loweringContext, comp, composedShape)...) - fields := newModelFields(loweringContext, ts, model) - base, hasBase := selectAllOfBase(loweringContext, comp.entries, common.ID) - diags = append(diags, fillAllOf(loweringContext, ts, depth, model, fields, comp, base, hasBase)...) - diags = append(diags, fillModelProperties(loweringContext, ts, depth, fields, schema, pointer)...) + diags = append(diags, diagDisjointConjuncts(loweringContext, schema, comp, composedShape)...) + fields := newModelFields(loweringContext, types, model) + base, hasBase := selectAllOfBase(loweringContext, comp.entries, schema, common.ID) + diags = append(diags, fillAllOf(loweringContext, types, depth, model, fields, comp, schema, base, hasBase, pendingKeeps)...) + addWritingPendingKeeps(loweringContext, pendingKeeps, schema, comp, comp.kept, nil, textBoundIntersection{}) + if !propertiesRestated(loweringContext, schema, comp) { + diags = append(diags, fillModelProperties(loweringContext, types, depth, fields, schema, pointer)...) + } requireMembers(model, compositionRequired(schema.ObjectKeywords().Required, comp)) - diags = append(diags, fillComposedAdditional(loweringContext, ts, depth, model, schema, comp)...) + diags = append(diags, fillComposedAdditional(loweringContext, types, depth, model, schema, comp)...) + diags = append(diags, typeUnevaluatedCatchAll(loweringContext, types, depth, model, schema, comp.pointer)...) + diags = append(diags, diagComposedCatchAll(loweringContext, model, schema, comp)...) + addFalseEntryPendingKeeps(loweringContext, pendingKeeps, comp) diags = append(diags, applyFalseEntries(loweringContext, model, comp)...) if discriminated { - discriminator, discDiags := lowerDiscriminator(loweringContext, ts, schema.Discriminator(), pointer, model, nil) + written := modelDiscriminator(loweringContext, schema) + discriminator, discDiags := lowerDiscriminator(loweringContext, types, written.discriminator, pointer+written.rel, model, nil) diags = append(diags, discDiags...) model.Discriminator = discriminator + holdModelDiscriminator(loweringContext, types, written, pointer, model) } var first *statement.Schema // the base's hierarchy tags the model first if hasBase { @@ -79,15 +145,68 @@ func composeModel(loweringContext lowering.Ctx, ts *compile.Types, depth int, sc tag, tagDiags := subtypeDiscriminatorValue(loweringContext, schema, common.ID, pointer, first) model.DiscriminatorValue = tag.value diags = append(diags, tagDiags...) - deferSubtypeTag(loweringContext, ts, tag, common.ID, pointer) - return objectNode(model), modelReads(schema, model, comp.bounds), diags + deferSubtypeTag(loweringContext, types, tag, common.ID, pointer) + return objectNode(model), modelReads(schema, model, comp.homes.value), diags +} + +// composeBottom builds the bottom of an allOf whose conjuncts' kinds share +// none, written at pointer: the closed Model with no member a `false` schema +// lowers to, which reads none of the keywords beside the allOf, so each is kept +// under its own key, and keeps each entry written there whole under its entry +// key, a $ref written beside nothing else as a refinement keeps one it passes +// over (docs/compilers/openapi.md#allof-refinement). The conjuncts sharing no +// value, which schema writes, are reported at pointer. +func composeBottom(loweringContext lowering.Ctx, schema *statement.Schema, common ir.TypeCommon, comp allOfComposition, pointer jsontext.Pointer, +) (ir.TypeDef, keySet, []ir.Diagnostic) { + model := &ir.Model{TypeCommon: common, Additional: ir.AdditionalClosed} + diags := diagDisjointConjuncts(loweringContext, schema, comp, bottomShape) + whole := map[jsontext.Pointer]bool{} + for _, entry := range comp.entries { + if entry.schema.Ref == nil && entry.pointer.Parent() == pointer+"/allOf" && !dropsAllBeside(entry) { + whole[entry.pointer] = true + } + } + var refs []keptRefEntry + for _, entry := range comp.entries { + switch { + case entry.pointer != pointer && entry.pointer.Parent() != pointer+"/allOf": + // A flattened wrapper's entries are kept with it; a $ref beside the + // keywords is an entry at the position itself. + case entry.schema.Ref != nil && !whole[entry.pointer]: + refs = append(refs, keptRefEntry{entry: entry}) + case entry.schema.Ref == nil && !dropsAllBeside(entry): + node := entry.schema.Node + if entry.schema.WrittenBeside != nil { + // An entry writing a $ref beside other keys is kept once, as + // written, its reference among them. + node = heldAt(loweringContext, entry.pointer).Node + } + _, keptDiags := keepNode(loweringContext, &model.Unmodeled, comp.entryKey(entry.pointer), + node, ir.ReasonDegradedLowering, entry.pointer) + diags = append(diags, keptDiags...) + } + } + _, refDiags := keepRefConjuncts(loweringContext, &model.Unmodeled, refs, pointer) + return model, 0, append(diags, refDiags...) } -// compositionReads names the readDomain keywords an allOf composition reads -// itself, so neither the keeping of a $ref entry's unread keywords nor that of -// the composed position reports them again: lowerAllOf lands every required -// list on the composed model (requireMembers). -var compositionReads = keyBit("required") +// dropsAllBeside reports whether entry is what an allOf entry writes beside a +// $ref (besideRef) and writes only vendor extensions no JSON holds +// (annotation.ExtensionNoJSONHolds), which every keeping leaves out, so the +// entry reads as its twin writing the $ref alone. +func dropsAllBeside(entry allOfEntry) bool { + return besideRef(entry) && !slices.ContainsFunc(entry.schema.Keys, func(key statement.Key) bool { + return !annotation.ExtensionNoJSONHolds(entry.schema.Schema, key.Name) + }) +} + +// writesBeside reports whether the $ref entry of a written at pointer writes +// beside its reference anything a keeping holds (dropsAllBeside). +func (a allOfComposition) writesBeside(pointer jsontext.Pointer) bool { + return slices.ContainsFunc(a.entries, func(entry allOfEntry) bool { + return entry.pointer == pointer && besideRef(entry) && !dropsAllBeside(entry) + }) +} // allOfEntry is one inline-or-ref entry of an allOf composition after nested // wrappers are flattened into the list (GitHub #599). @@ -114,38 +233,53 @@ type allOfEntry struct { type allOfComposition struct { pointer jsontext.Pointer entries []allOfEntry + // entryAt is each entry's index in entries by the pointer it was written + // at, built with them (newAllOfComposition), so finding an entry's site + // is a lookup: scanning entries for each entry is quadratic in them. + entryAt map[jsontext.Pointer]int // disjoint names what each conjunct states where the schema draws the // warning docs/compilers/openapi.md#allof-disjoint-conjuncts describes, and // is nil otherwise (readAllOf). disjoint []string - // speaks marks each entry that folds at the position (foldingAllOfEntries), - // and rebased each whose folding keywords write a relative $ref it reads - // against another base, so it does not. They are nil where the allOf is not - // what the position lowers (allOfDecides). + // entryFoldsIntoPosition marks each entry that folds at the position + // (allOfEntryFoldingOf), and rebased each whose folding keywords write a + // relative $ref it reads against another base, so it does not. They are nil + // where the allOf is not what the position lowers (allOfDecides). entryFoldsIntoPosition []bool rebased []bool + // apart is, by index, what each entry's conjuncts write otherwise, which + // does not fold (allOfEntryFolding.apart). + apart []map[string]bool // conjoins is the pointer of the entry whose union the position lowers, // distributing it across its variants (entryUnion), whose merge consumes it, // and empty where no entry's is. conjoins jsontext.Pointer - // bounds is the kinds whose value bounds the Model composing the entries - // reads, those of the types the position admits (boundKinds) that it takes - // (modelTakes), so an entry's bound folds where they take it. - bounds kindSet - // closer names the schema object whose additionalProperties and - // patternProperties the Model composing the entries types (closerOf). - closer closure + // mixinKeeps are the unions a routed subtype passes over, which the Union + // it composes as a mixin keeps, so no entry writing one keeps it as + // unread keywords (mixinPassedUnions). + mixinKeeps []conjunctionUnion + // homes are the bounds the Model composing the entries holds of them + // (boundKinds, modelTakes), decided here once so that every reader of the + // composition folds an entry's bound alike. + homes boundHomes + // catchAll names the schema object whose additionalProperties and + // patternProperties the Model composing the entries types (catchAllSourceOf). + catchAll catchAllSource // kept is what each inline entry keeps verbatim beside the Model // composing them, by index (entryKeeps). kept []keptEntry + // discriminatorConjunct is the inline entry whose discriminator the Model + // composing the entries holds (modelDiscriminator), nil for none. + discriminatorConjunct *statement.Schema } -// entrySpeaks reports whether the entry at index i folds at the position. -func (a allOfComposition) entrySpeaks(i int) bool { - return a.entryFoldsIntoPosition != nil && a.entryFoldsIntoPosition[i] +// folding is what a's entries fold at the position, as allOfEntryFoldingOf +// read it where the allOf decides there. +func (a allOfComposition) folding() allOfEntryFolding { + return allOfEntryFolding{entryFoldsIntoPosition: a.entryFoldsIntoPosition, rebased: a.rebased, apart: a.apart} } -// allOfEntries returns the entries of s's allOf as its statement flattens +// allOfEntries returns the entries of schema's allOf as its statement flattens // them (statement.Statement.Entries), each with the pointer it was written at, // under the schema written at pointer. allOf is associative, so the list // classifies exactly as its flat spelling would. @@ -157,34 +291,57 @@ func allOfEntries(loweringContext lowering.Ctx, schema *statement.Schema, pointe schema: loweringContext.Statements().Read(allOfConjunct.Schema), pointer: pointer + allOfConjunct.Rel, wrapper: allOfConjunct.Wrapper, capped: allOfConjunct.Capped, split: allOfConjunct.Split, }) } - return allOfComposition{pointer: pointer, entries: out} + return newAllOfComposition(pointer, out) +} + +// newAllOfComposition is the composition of entries under the schema written +// at pointer, each indexed by the pointer it was written at. +func newAllOfComposition(pointer jsontext.Pointer, entries []allOfEntry) allOfComposition { + entryAt := make(map[jsontext.Pointer]int, len(entries)) + for i, entry := range entries { + if _, seen := entryAt[entry.pointer]; !seen { + entryAt[entry.pointer] = i + } + } + return allOfComposition{pointer: pointer, entries: entries, entryAt: entryAt} +} + +// entryIndex is the index in a.entries of the entry written at pointer, and +// false where none is. +func (a allOfComposition) entryIndex(pointer jsontext.Pointer) (int, bool) { + i, found := a.entryAt[pointer] + return i, found } // readAllOf is allOfEntries of the schema written at pointer, with what its // conjuncts jointly admit read and, where the allOf is what the position // lowers, which entries fold there (allOfEntryFoldingOf) and which writes the // union the position lowers (entryUnion), for a lowering that composes it. That -// gate is positionFoldedEntries', so an entry gives up a keyword only where a -// reader of the position takes it up; both composers pass it, and the report of -// an allOf the election passed over does not. +// gate is positionFlattenedEntries', so an entry gives up a keyword only where +// a reader of the position takes it up; both composers pass it, and the report +// of an allOf the choice passed over does not. func readAllOf(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) allOfComposition { comp := allOfEntries(loweringContext, schema, pointer) comp.disjoint = disjointNames(loweringContext, schema, comp) - comp.bounds = modelTakes(boundKinds(loweringContext, schema)) - comp.closer = closerOf(loweringContext, schema, comp) + comp.homes = boundHomes{value: modelTakes(boundKinds(loweringContext, schema))} + comp.catchAll = catchAllSourceOf(schema, comp) if allOfDecides(loweringContext, schema) { allOfEntryFolding := allOfEntryFoldingOf(loweringContext, schema) - comp.entryFoldsIntoPosition, comp.rebased = allOfEntryFolding.entryFoldsIntoPosition, allOfEntryFolding.rebased + comp.entryFoldsIntoPosition, comp.rebased, comp.apart = allOfEntryFolding.entryFoldsIntoPosition, allOfEntryFolding.rebased, allOfEntryFolding.apart } - if unionAt, _, ok := entryUnion(loweringContext, schema, pointer); ok { - comp.conjoins = unionAt.at + if unionSite, _, ok := entryUnion(loweringContext, schema, pointer); ok { + comp.conjoins = unionSite.pointer } - comp.kept = entryKeeps(loweringContext, schema, comp, func(i int) []string { return compositionResidue(loweringContext, comp, i) }, - allOfEntryFolding{entryFoldsIntoPosition: comp.entryFoldsIntoPosition, rebased: comp.rebased}, catchAllKeyword, nil) + comp.mixinKeeps = mixinPassedUnions(loweringContext, schema) + if written := modelDiscriminator(loweringContext, schema); written.conjunctSchema != schema { + comp.discriminatorConjunct = written.conjunctSchema + } + comp.kept = entryKeeps(loweringContext, schema, comp, func(i int) []string { return compositionUnreadKeywords(loweringContext, schema, comp, i) }, + comp.folding(), catchAllKeyword) return comp } -// allOfRefEntries yields the statements of the $ref entries of s's allOf +// allOfRefEntries yields the statements of the $ref entries of schema's allOf // after flattening: the view an ancestor walk needs, which reads no pointer. func allOfRefEntries(loweringContext lowering.Ctx, schema *statement.Schema) iter.Seq[*statement.Statement] { return func(yield func(*statement.Statement) bool) { @@ -196,33 +353,6 @@ func allOfRefEntries(loweringContext lowering.Ctx, schema *statement.Schema) ite } } -// FlatEntry is one entry of the allOf FlattenedAllOf reads. -type FlatEntry struct { - // Schema is the entry as written, or the wrapper a run of its own entries - // ended with. - Schema *statement.Statement - // Ref marks an entry that names its schema by $ref, which the reader follows - // itself and bounds on its own. - Ref bool - // Capped marks an inline entry whose own allOf sits past - // statement.MaxFlattenDepth and was not flattened, so the reader has not reached - // what it declares. - Capped bool -} - -// FlattenedAllOf returns s's allOf as the lowering reads it, so a reader outside -// this package takes the same flattening and the same cap, in the same order -// (docs/compilers/openapi.md#allof-classification). It reads the entries -// allOfEntries does. -func FlattenedAllOf(loweringContext lowering.Ctx, schema *statement.Schema) []FlatEntry { - entries := loweringContext.Statements().Read(schema).Entries - out := make([]FlatEntry, 0, len(entries)) - for _, allOfConjunct := range entries { - out = append(out, FlatEntry{Schema: loweringContext.Statements().Read(allOfConjunct.Schema), Ref: allOfConjunct.Ref != nil, Capped: allOfConjunct.Capped}) - } - return out -} - // entryKey is the Unmodeled key an allOf entry at bptr is kept under: "openapi:" // and its path from the composed schema. The path's tokens are `allOf` and // decimal indices, so trimming the prefix is exact. @@ -263,54 +393,92 @@ func compositionRequired(own []string, comp allOfComposition) []string { return append(out, own...) } -// fillAllOf classifies and lowers the entries of comp into m (GitHub #599). +// fillAllOf classifies and lowers the entries of comp into model (GitHub #599). // // An inline entry merges in place: its `properties` and `required` // (requireMembers) merge, its catch-all keywords where it closes the model -// (closerOf), what it writes for the position folds there -// (foldingAllOfEntries), and the rest stays verbatim beside the model -// (preserveUnmergedEntry, GitHub -// #123). +// (catchAllSourceOf), what it writes for the position folds there +// (allOfEntryFoldingOf), and the rest stays verbatim beside the model +// (keepUnmergedEntry, GitHub #123). // // A $ref entry is the reference alone, composing what it names // (fillRefEntry). The keywords written beside its $ref are an inline entry // of their own at its pointer, merged as above, a oneOf or anyOf among them // lowering as on any entry (docs/ir/models.md#composition-entries). -func fillAllOf(loweringContext lowering.Ctx, ts *compile.Types, depth int, model *ir.Model, fields modelFields, comp allOfComposition, - base int, hasBase bool, +func fillAllOf(loweringContext lowering.Ctx, types *compile.Types, depth int, model *ir.Model, fields modelFields, comp allOfComposition, + position *statement.Schema, base int, hasBase bool, pendingKeeps *annotation.PendingKeeps, ) []ir.Diagnostic { var diags []ir.Diagnostic var failed []int - var uncomposed []wholeRefEntry + var uncomposed []keptRefEntry + restated := propertiesRestated(loweringContext, position, comp) for i, entry := range comp.entries { switch { case entry.schema.Ref == nil: - diags = append(diags, fillModelProperties(loweringContext, ts, depth, fields, entry.schema.Schema, entry.pointer)...) - diags = append(diags, preserveUnmergedEntry(loweringContext, ts, model, comp, i)...) - case composesRef(loweringContext, entry): - refDiags, resolved := fillRefEntry(loweringContext, ts, fields, entry, hasBase && i == base) + if !restated { + diags = append(diags, fillModelProperties(loweringContext, types, depth, fields, entry.schema.Schema, entry.pointer)...) + } + diags = append(diags, keepUnmergedEntry(loweringContext, pendingKeeps, comp, i, nodeShape(ir.KindModel))...) + case composesRef(loweringContext, entry, position): + refDiags, resolved := fillRefEntry(loweringContext, types, fields, entry, hasBase && i == base) diags = append(diags, refDiags...) if !resolved { failed = append(failed, i) } default: - uncomposed = append(uncomposed, wholeRefEntry{entry: entry}) + uncomposed = append(uncomposed, keptRefEntry{entry: entry}) } } - apart, failedDiags := keepFailedRefs(loweringContext, ts, model, comp, failed) + apart, failedDiags := keepFailedRefs(loweringContext, pendingKeeps, comp, failed) diags = append(diags, failedDiags...) - return append(diags, keepUncomposedRefs(loweringContext, ts, model, comp.pointer, apart, uncomposed)...) + return append(diags, keepUncomposedRefs(loweringContext, types, model, comp.pointer, apart, uncomposed)...) +} + +// propertiesRestated reports whether the properties position and comp's +// inline entries write all restate those of the referent of comp's one $ref +// (restatesReferentProperties), beside no union the composition distributes: +// they say nothing the Base does not, wherever written, so no member folds +// from them (docs/compilers/openapi.md#allof-refinement). A referent on one +// cycle of compositions with position restates none: the cycle folds every +// model's own declarations as one unit, so each declaration counts there. +func propertiesRestated(loweringContext lowering.Ctx, position *statement.Schema, comp allOfComposition) bool { + ref := oneQuietRef(comp) + if ref == nil || position == nil || declaresUnion(position) { + return false + } + if referent, _ := declaredOf(loweringContext, ref); referent != nil && onOneCompositionCycle(loweringContext, position, referent.Schema) { + return false + } + conjunctList := []*statement.Schema{position} + for _, entry := range comp.entries { + if entry.schema.Ref == nil { + conjunctList = append(conjunctList, entry.schema.Schema) + } + } + restated := false + for _, written := range conjunctList { + if len(written.ObjectKeywords().Properties) == 0 { + continue + } + if !restatesReferentProperties(loweringContext, ref, written) { + return false + } + restated = true + } + return restated } // composesRef reports whether the $ref entry allOfEntryValue is a Base or a // Mixin of the composition: the schema it lands on lowers to an object alone, // null aside (lowersTo), or to the union of a type list holding an object, -// whose object variant it composes (objectVariant), or its read is cut short, -// which leaves the composition as it is with no read. A model composes only -// models (docs/compilers/openapi.md#allof-classification). -func composesRef(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) bool { +// whose object variant it composes (objectVariant), or it leads round a loop +// of references back to position, nil for none, whose Model this is. One +// landing on no schema is handed to fillRefEntry, which resolves nothing and +// leaves it to keepFailedRefs. A model composes only models +// (docs/compilers/openapi.md#allof-classification). +func composesRef(loweringContext lowering.Ctx, allOfEntryValue allOfEntry, position *statement.Schema) bool { target, _ := declaredOf(loweringContext, allOfEntryValue.schema) - if target == nil || admissionOf(loweringContext, target).cut { + if target == nil || position != nil && leadsBackTo(loweringContext, allOfEntryValue.schema, position) { return true } if kinds, _ := lowersTo(loweringContext, target); kinds == kindObject { @@ -322,10 +490,10 @@ func composesRef(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) bool // objectVariant returns the ID of the object variant of the union the $ref // conjunct ref lands on, an allOf entry or a distributed union's branch, where -// that schema lowers by a type list holding an object (lowerUnion), and false -// for any other: the variant stands at the list's position, one per type, so -// it is named before the union is built. A union a oneOf or anyOf writes may -// hold several objects, or none a model is, and is not unpacked. +// that schema lowers by a type list holding an object (lowerTypeArrayUnion), +// and false for any other: the variant sits at the list's position, one per +// type, so it is named before the union is built. A union a oneOf or anyOf +// writes may hold several objects, or none a model is, and is not unpacked. func objectVariant(loweringContext lowering.Ctx, ref *statement.Statement) (ir.TypeID, bool) { target, at := declaredOf(loweringContext, ref) if target == nil || target.Ref != nil || declaresUnion(target.Schema) { @@ -339,7 +507,7 @@ func objectVariant(loweringContext lowering.Ctx, ref *statement.Statement) (ir.T if i < 0 { return "", false } - return in.IDs().ForPointer(at.Pointer + ids.Ptr("type", strconv.Itoa(i))), true + return in.IDs().ForPointer(typeVariantAt(at.Pointer, i)), true } // keepUncomposedRefs keeps beside model the $ref entries of its composition, @@ -348,16 +516,16 @@ func objectVariant(loweringContext lowering.Ctx, ref *statement.Statement) (ir.T // alone, ranked together (keepRefConjuncts). It reports each uncomposed one // kept, resolving its target so the document holds what it names; a failed // one is reported where it is written. -func keepUncomposedRefs(loweringContext lowering.Ctx, ts *compile.Types, model *ir.Model, pointer jsontext.Pointer, - apart, uncomposed []wholeRefEntry, +func keepUncomposedRefs(loweringContext lowering.Ctx, types *compile.Types, model *ir.Model, pointer jsontext.Pointer, + apart, uncomposed []keptRefEntry, ) []ir.Diagnostic { - for _, b := range uncomposed { - resolveSchemaRef(loweringContext, ts, b.entry.schema) + for _, refEntry := range uncomposed { + resolveSchemaRef(loweringContext, types, refEntry.entry.schema) } kept, diags := keepRefConjuncts(loweringContext, &model.Unmodeled, slices.Concat(apart, uncomposed), pointer) - for _, b := range uncomposed { - if kept[b.entry.pointer] { - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, b.entry.pointer, "%s", + for _, refEntry := range uncomposed { + if kept[refEntry.entry.pointer] { + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, refEntry.entry.pointer, "%s", "the schema this $ref names is not an object alone, and a model composes only models, so the $ref "+ "is kept verbatim under Unmodeled")) } @@ -371,15 +539,13 @@ func keepUncomposedRefs(loweringContext lowering.Ctx, ts *compile.Types, model * // list it names (objectVariant). A $ref it cannot resolve adds nothing and // reports false, which keepFailedRefs answers; it is reported unless it lies on a // loop of $refs, which load reports once (onLoop). -func fillRefEntry(loweringContext lowering.Ctx, ts *compile.Types, fields modelFields, allOfEntryValue allOfEntry, isBase bool) ([]ir.Diagnostic, bool) { +func fillRefEntry(loweringContext lowering.Ctx, types *compile.Types, fields modelFields, allOfEntryValue allOfEntry, isBase bool) ([]ir.Diagnostic, bool) { var diags []ir.Diagnostic - b := allOfEntryValue.schema - id, ok := resolveSchemaRef(loweringContext, ts, b) + branch := allOfEntryValue.schema + id, ok := resolveSchemaRef(loweringContext, types, branch) if !ok { - if !onLoop(b) { - keyword, ref := refSpelling(b) - diags = append(diags, loweringContext.DiagAt(ir.SeverityError, diag.UnresolvedRef, allOfEntryValue.pointer, - "unresolved allOf %s %q%s", keyword, ref, unresolvedWhy(loweringContext, b))) + if !onLoop(branch) { + diags = append(diags, unresolvedRefReport(loweringContext, allOfEntryValue.pointer, branch, "unresolved allOf %s %q%s")) } return diags, false } @@ -387,145 +553,187 @@ func fillRefEntry(loweringContext lowering.Ctx, ts *compile.Types, fields modelF recordDiscarded(loweringContext, id) id = variant } - unhomed := unreadByReference(loweringContext, b.Schema, compositionReads) - var kept finished - keep := keepUnreadOn(loweringContext, ts, b.Schema, unhomed, refSiteShape, allOfEntryValue.pointer, stand{}, &kept, nil) - ref, homeDiags := homeDeclaration(loweringContext, ts, b.Schema, ir.TypeRef{Target: id}, allOfEntryValue.pointer, annotation.HomeOwnNode, len(unhomed) > 0, keep) + // Any keyword read beside $ref was already split into an inline entry + // (statement.MemoizingSchemaReader), so a resolved $ref entry writes none + // for a node to keep beyond what homeDeclaration checks. + _, ref, homeDiags := homeDeclaration(loweringContext, types, branch.Schema, ir.TypeRef{Target: id}, allOfEntryValue.pointer, annotation.HomeOwnNode, false) diags = append(diags, homeDiags...) - diags = append(diags, kept.diags...) if isBase { - fields.m.Base = &ref + fields.model.Base = &ref } else { - fields.m.Mixins = append(fields.m.Mixins, ref) + fields.model.Mixins = append(fields.model.Mixins, ref) } fields.compose(ref.Target, allOfEntryValue.pointer) return diags, true } -// applyFalseEntries closes m for each boolean `false` allOf entry and keeps -// the entry verbatim under Unmodeled. It runs after fillComposedAdditional, -// whose result it overrides, the catch-all included -// (docs/compilers/openapi.md#allof-false-branch). -// -// A `false` entry admits nothing, so m must not stay open; the rule -// docs/compilers/openapi.md#whole-schema-fallbacks closes a bare `false` schema -// the same way. m keeps the other entries' contributions, because emptying it -// would trade one silent loss for another. The verbatim entry tells this from -// a plain `additionalProperties: false`; a diagnostic does not, being no part -// of the document. A `true` entry constrains nothing and is skipped. -func applyFalseEntries(loweringContext lowering.Ctx, model *ir.Model, comp allOfComposition) []ir.Diagnostic { - var diags []ir.Diagnostic +// addFalseEntryPendingKeeps adds to pendingKeeps, the pending keeps of the +// Model comp composes, each boolean `false` entry of comp, kept verbatim under +// its entry key with the report that it matches nothing, as what the Model's +// build keeps (docs/compilers/openapi.md#allof-false-branch). The verbatim +// entry tells the closed Model from a plain `additionalProperties: false`; a +// diagnostic does not, being no part of the document. +func addFalseEntryPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, comp allOfComposition) { for _, entry := range comp.entries { if !entry.schema.Truth.ReadsFalse() { continue // `true`, a null and any schema with a body close nothing. } - model.Additional = ir.AdditionalClosed - annotation.PreserveInto(&model.Unmodeled, comp.entryKey(entry.pointer), - ir.RawValue("false"), ir.ReasonDegradedLowering, loweringContext.Place().At(entry.pointer)) - - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.FalseSchema, entry.pointer, + site := entrySiteAt(comp, entry.pointer, annotation.WritesBeside) + pendingKeep := pendingKeepOf(loweringContext, site, site.EntryKey, writtenKeyword(site.EntryKey), ir.RawValue("false"), ir.ReasonDegradedLowering, nil) + pendingKeep.Provenance, pendingKeep.Source = loweringContext.Place().At(entry.pointer), annotation.KeptByBuild + pendingKeep.Report = []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityInfo, diag.FalseSchema, entry.pointer, "boolean false allOf entry matches nothing, so the composition matches nothing; "+ - "composed model closed and the entry kept verbatim under Unmodeled")) + "composed model closed and the entry kept verbatim under Unmodeled")} + pendingKeeps.Add(pendingKeep) } +} - closer := comp.closer - if closer.schema != nil && model.Additional == ir.AdditionalClosed && model.AdditionalProperties != nil && model.AdditionalProperties.Value != nil { - _, keptDiags := preserveSchemaKeyword(loweringContext, &model.Unmodeled, closer.schema, "additionalProperties", - ir.ReasonDegradedLowering, closer.at) +// applyFalseEntries closes model where comp holds a boolean `false` allOf +// entry, which addFalseEntryPendingKeeps keeps. It runs after +// fillComposedAdditional, whose result it overrides, the catch-all included +// (docs/compilers/openapi.md#allof-false-branch). +// +// A `false` entry admits nothing, so model must not stay open; the rule +// docs/compilers/openapi.md#whole-schema-fallbacks closes a bare `false` schema +// the same way. model keeps the other entries' contributions, because emptying +// it would trade one unreported loss for another. A `true` entry constrains +// nothing. +func applyFalseEntries(loweringContext lowering.Ctx, model *ir.Model, comp allOfComposition) []ir.Diagnostic { + if slices.ContainsFunc(comp.entries, func(entry allOfEntry) bool { return entry.schema.Truth.ReadsFalse() }) { + model.Additional = ir.AdditionalClosed + } + var diags []ir.Diagnostic + catchAll := comp.catchAll + if catchAll.schema != nil && model.Additional == ir.AdditionalClosed && model.AdditionalProperties != nil && model.AdditionalProperties.Value != nil { + _, keptDiags := keepSchemaKeyword(loweringContext, &model.Unmodeled, catchAll.schema, "additionalProperties", + ir.ReasonDegradedLowering, catchAll.at) diags = append(diags, keptDiags...) } forbidRest(loweringContext, model) return diags } -// preserveUnmergedEntry keeps what the inline allOf entry at index i of comp +// keepUnmergedEntry keeps what the inline allOf entry at index i of comp // writes that the merge consumes nowhere beside the composed model, as comp.kept // says: each keyword under its own key and reason, or the entry whole under a // key comp gives it, so sibling entries never overwrite one another // (docs/compilers/openapi.md#allof-inline-residue). -func preserveUnmergedEntry(loweringContext lowering.Ctx, ts *compile.Types, model *ir.Model, comp allOfComposition, i int) []ir.Diagnostic { +func keepUnmergedEntry(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, comp allOfComposition, i int, shape string, +) []ir.Diagnostic { keptEntryValue := comp.kept[i] disjoint := len(comp.disjoint) > 0 warn := entryExcludesObject(keptEntryValue.entry.schema.Schema) && !disjoint - return recordKeptEntry(loweringContext, ts, &model.Unmodeled, comp, keptEntryValue, nodeShape(ir.KindModel), warn, func(otherKeptEntry keptEntry) ir.Diagnostic { + return addKeptEntryPendingKeeps(loweringContext, pendingKeeps, comp, keptEntryValue, annotation.WritesBeside, shape, warn, func(otherKeptEntry keptEntry) ir.Diagnostic { return diagUnmergedEntry(loweringContext, otherKeptEntry, disjoint) }) } -// compositionResidue returns what the inline allOf entry at index i of comp -// writes that the in-place merge reads nowhere: not its properties and -// required, nor what folds where comp says it speaks, nor the union the -// position lowers, nor the catch-all of the entry closing the model. A -// flattened entry's allOf is consumed: allOfEntries replaced it by its own -// entries. A boolean entry has no keywords to leave a residue -// (applyFalseEntries), and a $ref entry homes its siblings on an alias over -// its target (fillRefEntry), unless it names nothing (failedRefResidue). -func compositionResidue(loweringContext lowering.Ctx, comp allOfComposition, i int) []string { +// compositionUnreadKeywords returns what the inline entry i of comp, position's +// allOf, writes that the merge reads nowhere: not its properties and required, +// but where no variant of a union split by kind composes them +// (composesNoObject), what folds where comp says it speaks, the union the +// position lowers with the type and discriminator it reads +// (unionBesideRest.readsType, routesUnion), nor the catch-all of the entry +// closing the model. A flattened entry's allOf is consumed; a boolean entry +// leaves no unread keywords (addFalseEntryPendingKeeps), and a $ref entry homes +// its siblings on an alias (fillRefEntry), unless it names nothing +// (failedRefUnreadKeywords). +func compositionUnreadKeywords(loweringContext lowering.Ctx, position *statement.Schema, comp allOfComposition, i int) []string { + typeRead, noObject := readLoweredUnion(loweringContext, position).besideRest.readsType(), composesNoObject(loweringContext, position) entry := comp.entries[i] if entry.schema.Truth != statement.Stated { return nil } if entry.schema.Ref != nil { - return failedRefResidue(loweringContext, entry) + return failedRefUnreadKeywords(loweringContext, entry) } - speaks := comp.entrySpeaks(i) + folding := comp.folding() + speaks := folding.entryFoldsIntoPosition != nil && folding.entryFoldsIntoPosition[i] conjoined := comp.conjoins != "" && entry.pointer == comp.conjoins - closes := comp.closer.entryAt(entry.pointer) + liftedAt, lifted := liftedEntryUnion(loweringContext, position, comp.pointer) + closes := comp.catchAll.entryAt(entry.pointer) + taken := comp.discriminatorConjunct == entry.schema.Schema + homes := comp.homes + homes.value |= splitTakes(loweringContext, position) return unmergedEntryKeys(entry.schema.Schema, func(keyword string) bool { - return mergeConsumes(entry.schema.Schema, keyword, entry.wrapper) || (speaks && folds(loweringContext, entry.schema.Schema, keyword, boundHomes{value: comp.bounds})) || - (conjoined && conjoinedKeyword(keyword)) || (closes && catchAllKeyword(keyword)) + folded := speaks && !folding.apartAt(loweringContext, entry.schema.Schema, i, keyword) && + folds(loweringContext, entry.schema.Schema, keyword, homes) + consumed := mergeConsumes(entry.schema.Schema, keyword, entry.wrapper) && (!objectKeys.has(keyword) || !noObject) + return consumed || folded || typeRead && keyword == "type" || + keyword == "discriminator" && (taken || routesUnion(loweringContext, position, entry.schema.Schema)) || + (conjoined && givenToTheUnion(keyword)) || (closes && catchAllKeyword(keyword)) || comp.keptOnMixin(entry.schema.Schema, keyword) || + keyword == lifted && entry.pointer+ids.Ptr(keyword) == liftedAt }) } -// diagUnmergedEntry builds the diagnostic announcing the entry k keeps whole, -// naming the keywords so two entries of the same schema are told apart. The -// caller records it. +// keptOnMixin reports whether the union holder, an entry of a, writes under +// keyword is one the Union a routed subtype composes as a mixin keeps +// (allOfComposition.mixinKeeps). +func (a allOfComposition) keptOnMixin(holder *statement.Schema, keyword string) bool { + return slices.ContainsFunc(a.mixinKeeps, func(union conjunctionUnion) bool { return union.holder == holder && string(union.keyword) == keyword }) +} + +// liftedEntryUnion returns where the union position's conjunction chooses is +// written, position at pointer, and its keyword, where an inline entry of its +// allOf writes it and its null branches lift onto the reference to the body +// (unionLiftsNull), which says all of it; "" where none is. +func liftedEntryUnion(loweringContext lowering.Ctx, position *statement.Schema, pointer jsontext.Pointer) (jsontext.Pointer, string) { + loweredUnion, ok := readConjunction(loweringContext, position).loweredUnion() + if !ok || loweredUnion.holder == position || readLoweredUnion(loweringContext, position).besideRest != unionLiftsNull { + return "", "" + } + return loweredUnion.keyword.keywordAt(pointer + loweredUnion.rel), string(loweredUnion.keyword) +} + +// diagUnmergedEntry builds the diagnostic announcing the entry keptEntryValue +// keeps whole, naming the keywords so two entries of the same schema are told +// apart. The caller records it. // // An entry declaring a type that cannot be an object is a warning rather than // info: the composed ir.Model asserts the value *is* an object, which the entry -// contradicts. Any other residue only narrows a model the IR describes correctly, -// the under-constrained case (docs/compilers/openapi.md#allof-inline-residue). -// disjoint says the schema reports its conjuncts share no value, so this -// reports residue alone. +// contradicts. Any other unread keyword only narrows a model the IR describes +// correctly, the under-constrained case +// (docs/compilers/openapi.md#allof-inline-residue). disjoint says the schema +// reports its conjuncts share no value, so this reports unread keywords alone. func diagUnmergedEntry(loweringContext lowering.Ctx, keptEntryValue keptEntry, disjoint bool) ir.Diagnostic { - entry, residue := keptEntryValue.entry, keptEntryValue.residue + entry, unreadKeywords := keptEntryValue.entry, keptEntryValue.unreadKeywords if entryExcludesObject(entry.schema.Schema) && !disjoint { names := namesOf(entry) message := names.lead + " declares a type that is not an object, which the composed model asserts it is; " + names.kept + " (" + - strings.Join(keptKeywords(residue, entry), ", ") + ") is kept verbatim under Unmodeled" + strings.Join(keptKeywords(unreadKeywords, entry), ", ") + ") is kept verbatim under Unmodeled" if entry.capped { message += ", and its own allOf, nested past the flattening depth of " + strconv.Itoa(statement.MaxFlattenDepth) + ", was not flattened" } - return loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, entry.pointer, "%s", message) + return loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, entry.pointer, "%s", message) } if why := wholeWhy(keptEntryValue); why != "" && !entry.capped { return loweringContext.DiagAt(ir.SeverityInfo, wholeCode(keptEntryValue), entry.pointer, "%s", why) } - return loweringContext.DiagAt(ir.SeverityInfo, wholeCode(keptEntryValue), entry.pointer, "%s", unmergedWhy(residue, entry)) + return loweringContext.DiagAt(ir.SeverityInfo, wholeCode(keptEntryValue), entry.pointer, "%s", unmergedWhy(unreadKeywords, entry)) } -// keptKeywords is residue as a diagnostic names it: a capped entry is kept for -// its depth, so its allOf is not listed as a keyword the merge declines. -func keptKeywords(residue []string, allOfEntryValue allOfEntry) []string { +// keptKeywords is the unread keywords as a diagnostic names them: a capped +// entry is kept for its depth, so its allOf is not listed as a keyword the +// merge declines. +func keptKeywords(unreadKeywords []string, allOfEntryValue allOfEntry) []string { if !allOfEntryValue.capped { - return residue + return unreadKeywords } - return slices.DeleteFunc(slices.Clone(residue), func(k string) bool { return k == "allOf" }) + return slices.DeleteFunc(slices.Clone(unreadKeywords), func(k string) bool { return k == "allOf" }) } -// unmergedWhy words why an entry with residue is kept: what merges and folds is -// gone from residue, which is the rest. A flattened entry's nested allOf composes -// too. A capped one is kept for its depth, not for allOf being a keyword the merge -// declines, so allOf is left out of the keywords it lists. -func unmergedWhy(residue []string, allOfEntryValue allOfEntry) string { +// unmergedWhy words why an entry with unread keywords, the rest once what +// merges and folds is gone, is kept, a capped one naming them as keptKeywords +// does. +func unmergedWhy(unreadKeywords []string, allOfEntryValue allOfEntry) string { const keptTail = " is kept verbatim under Unmodeled" names := namesOf(allOfEntryValue) switch { case allOfEntryValue.wrapper: return names.lead + " is merged in place, its nested allOf composes, and nothing reads the rest of it; " + names.kept + " (" + - strings.Join(residue, ", ") + ")" + keptTail + strings.Join(unreadKeywords, ", ") + ")" + keptTail case allOfEntryValue.capped: - rest := keptKeywords(residue, allOfEntryValue) + rest := keptKeywords(unreadKeywords, allOfEntryValue) why := names.lead + " is nested past the flattening depth of " + strconv.Itoa(statement.MaxFlattenDepth) + ", so its own allOf was not flattened, and " + names.kept if len(rest) > 0 { @@ -534,21 +742,21 @@ func unmergedWhy(residue []string, allOfEntryValue allOfEntry) string { return why + keptTail default: return names.lead + " is merged in place, and nothing reads the rest of it; " + names.kept + " (" + - strings.Join(residue, ", ") + ")" + keptTail + strings.Join(unreadKeywords, ", ") + ")" + keptTail } } // unmergedEntryKeys returns the keywords the entry declares that consumes does -// not claim, in the order the parser's model holds them. +// not take, in the order the parser's model holds them. // // The keys are the entry's own (statement.Schema.Keys) rather than a list of // keywords worth preserving, which is what keeps this from rotting: a keyword a // later dialect adds counts as unconsumed the moment a source writes it, with // nobody to remember it here. -func unmergedEntryKeys(bs *statement.Schema, consumes func(key string) bool) []string { - out := make([]string, 0, len(bs.Keys)) - for _, key := range bs.Keys { - if consumes(key.Name) || annotation.WritesKeywordLeftOut(bs, key.Name) { +func unmergedEntryKeys(entrySchema *statement.Schema, consumes func(key string) bool) []string { + out := make([]string, 0, len(entrySchema.Keys)) + for _, key := range entrySchema.Keys { + if consumes(key.Name) || annotation.WritesKeywordLeftOut(entrySchema, key.Name) { continue } out = append(out, key.Name) @@ -557,11 +765,13 @@ func unmergedEntryKeys(bs *statement.Schema, consumes func(key string) bool) []s } // mergeConsumes reports whether fillAllOf's in-place merge reads entry keyword -// key. It is the complete statement of what the merge keeps; everything else the -// entry wrote is residue. `allOf` is consumed exactly when flattened -// (docs/compilers/openapi.md#allof-classification); otherwise it is residue like -// the rest. -func mergeConsumes(bs *statement.Schema, key string, flattened bool) bool { +// key. It is the complete statement of what the merge keeps; everything else +// the entry wrote is an unread keyword. `allOf` is consumed exactly when +// flattened (docs/compilers/openapi.md#allof-classification); otherwise it is +// an unread keyword like the rest. No build can return it instead: the merge +// reads every inline entry's properties and required whatever the entry builds, +// so what it read is known before any build runs. +func mergeConsumes(entrySchema *statement.Schema, key string, flattened bool) bool { switch key { case "allOf": return flattened // allOfEntries replaced the entry by its own entries @@ -570,53 +780,44 @@ func mergeConsumes(bs *statement.Schema, key string, flattened bool) bool { case "required": return true // requireMembers lands these on m case "type": - return declaresObjectOnly(bs) // a bare `object` only restates the composed Model + return typeReadAs(entrySchema, statement.KindObject) != 0 // an `object`, null aside, restates the composed Model default: return false } } -// conjoinedKeyword reports whether keyword is one an entry whose union the -// position lowers gives up to that union: its oneOf or anyOf, and the -// discriminator it writes, which is the union's where the position lowers it -// (findEntryUnion). -func conjoinedKeyword(keyword string) bool { - return keyword == "oneOf" || keyword == "anyOf" || keyword == "discriminator" -} - -// declaresObjectOnly reports whether the entry's declared type is exactly -// `object`, which the composed ir.Model already restates so the merge loses -// nothing by reading it. A set — `[object, "null"]` included — says more than -// that, and the more is what the merge would drop. -func declaresObjectOnly(bs *statement.Schema) bool { - types := bs.Types() - return len(types) == 1 && types[0] == statement.KindObject +// givenToTheUnion reports whether keyword is one an entry whose union the +// position lowers gives up to that union: the union itself (isUnionKeyword), +// and the discriminator, read with the conjunction's union wherever it is +// written (loweredUnionAt). +func givenToTheUnion(keyword string) bool { + return isUnionKeyword(keyword) || keyword == "discriminator" } // entryExcludesObject reports whether the entry declares a type set with no // `object` in it. An undeclared type set excludes nothing. -func entryExcludesObject(bs *statement.Schema) bool { - return writesType(bs) && !slices.Contains(bs.Types(), statement.KindObject) +func entryExcludesObject(entrySchema *statement.Schema) bool { + return writesType(entrySchema) && !slices.Contains(entrySchema.Types(), statement.KindObject) } // selectAllOfBase returns the index into entries, the conjuncts of the -// composition whose node is id, of the one that becomes Model.Base, and false -// when none qualifies (multiple non-hierarchy refs stay Mixins): of the $refs -// the composition takes (composesRef), the one, or of several, of those whose -// $ref lands on a schema taking part in a discriminator hierarchy +// composition of position whose node is id, of the one that becomes Model.Base, +// and false when none qualifies (multiple non-hierarchy refs stay Mixins): of +// the $refs the composition takes (composesRef), the one, or of several, of +// those whose $ref lands on a schema taking part in a discriminator hierarchy // (inHierarchy), one whose hierarchy's mapping routes id before one whose does // not, then the one whose reference text is the least, so no order written // decides. -func selectAllOfBase(loweringContext lowering.Ctx, entries []allOfEntry, id ir.TypeID) (int, bool) { +func selectAllOfBase(loweringContext lowering.Ctx, entries []allOfEntry, position *statement.Schema, id ir.TypeID) (int, bool) { refIdxs := make([]int, 0, len(entries)) for i, entry := range entries { - if entry.schema.Ref != nil && composesRef(loweringContext, entry) { + if entry.schema.Ref != nil && composesRef(loweringContext, entry, position) { refIdxs = append(refIdxs, i) } } // Ranked by whether the hierarchy routes id, by reference text, then by - // pointer, for a $ref written twice. - // Only a target in a hierarchy can be elected, so only its routes are read: + // where the entry is written, for a $ref written twice. + // Only a target in a hierarchy can be chosen, so only its routes are read: // a walk of the ancestors per $ref costs a wide composition naming no // hierarchy a walk of the whole graph each. routes := make(map[int]bool, len(refIdxs)) @@ -628,7 +829,7 @@ func selectAllOfBase(loweringContext lowering.Ctx, entries []allOfEntry, id ir.T _, a := refSpelling(entries[i].schema) _, b := refSpelling(entries[j].schema) return cmp.Or(compareTrueFirst(routes[i], routes[j]), strings.Compare(a, b), - strings.Compare(string(entries[i].pointer), string(entries[j].pointer))) + provenance.ComparePointers(entries[i].pointer, entries[j].pointer)) }) return merge.SelectBase(refIdxs, func(i int) bool { target := refBranchTarget(loweringContext, entries[i].schema) @@ -640,8 +841,8 @@ func selectAllOfBase(loweringContext lowering.Ctx, entries []allOfEntry, id ir.T // schema, or one of its discriminated ancestors declares names id, the node a // composition of schema lowers to; an empty id is no node, which none names. func routesTo(loweringContext lowering.Ctx, schema *statement.Schema, id ir.TypeID) bool { - return slices.ContainsFunc(append([]*statement.Schema{schema}, discriminatedAncestors(loweringContext, schema)...), func(a *statement.Schema) bool { - discriminator := a.Discriminator() + return slices.ContainsFunc(append([]*statement.Schema{schema}, slices.Concat(ancestorLevels(loweringContext, schema)...)...), func(a *statement.Schema) bool { + discriminator := modelDiscriminator(loweringContext, a).discriminator return discriminator != nil && len(mappingTagsFor(loweringContext, discriminator, id)) > 0 }) } @@ -665,11 +866,11 @@ type inHierarchyOf struct { // inHierarchy reports whether schema takes part in a discriminator hierarchy: // it declares a discriminator, or composes through allOf, at any depth, a -// schema that does, the ancestors whose routes tag it (discriminatedAncestors). +// schema that does, the ancestors whose routes tag it (ancestorLevels). // It reads the source, so no lowering order decides it, and every composition // naming schema asks, so it is read once a run. func inHierarchy(loweringContext lowering.Ctx, schema *statement.Schema) bool { return lowering.ReadOncePerRun(loweringContext, inHierarchyOf{schema}, func() bool { - return schema.Discriminator() != nil || len(discriminatedAncestors(loweringContext, schema)) > 0 + return discriminates(loweringContext, schema) || len(slices.Concat(ancestorLevels(loweringContext, schema)...)) > 0 }) } diff --git a/compilers/openapi/internal/schema/allof_apart_sets_test.go b/compilers/openapi/internal/schema/allof_apart_sets_test.go new file mode 100644 index 000000000..46c7e5687 --- /dev/null +++ b/compilers/openapi/internal/schema/allof_apart_sets_test.go @@ -0,0 +1,163 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// keptNaming counts the entries of kept holding what keyword writes: under its +// own key, or inside an entry kept whole. +func keptNaming(kept ir.Unmodeled, keyword string) int { + n := 0 + for key, entry := range kept { + switch { + case key == "openapi:"+keyword: + n++ + case strings.HasPrefix(key, "openapi:allOf/") && strings.Contains(string(entry.Value), `"`+keyword+`"`): + n++ + } + } + return n +} + +// TestAllOf_AConstAndAnEnumSharingNoMemberAreTheClosedEmptyEnumInEverySpelling +// holds a const and an enum of integers sharing no member to the closed empty +// Enum of integers, keeping each set once, whether both are written on the +// position, the enum on an entry, or each on an entry of its own: the flat +// spelling lowers as the allOf spellings do, each drawing one warning. +func TestAllOf_AConstAndAnEnumSharingNoMemberAreTheClosedEmptyEnumInEverySpelling(t *testing.T) { + t.Parallel() + for name, schema := range map[string]string{ + "flat": "{type: integer, const: 1, enum: [2]}", + "enum on entry": "{type: integer, const: 1, allOf: [{enum: [2]}]}", + "both on entries": "{allOf: [{type: integer, const: 1}, {enum: [2]}]}", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+schema+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "the closed empty enum: got %T", typeByName(doc, "S")) + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Equal(t, ir.PrimitiveInteger, enum.ValueType) + assert.Equal(t, 1, keptNaming(enum.Unmodeled, "const"), "the const is kept once: %v", enum.Unmodeled) + assert.Equal(t, 1, keptNaming(enum.Unmodeled, "enum"), "the enum is kept once: %v", enum.Unmodeled) + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/S"), 1, "%+v", diags) + }) + } +} + +// TestAllOf_ListAndObjectValueSetsSharingNoMemberAreTheBottom holds value sets +// of lists or of objects sharing no member, which no Enum types: the bottom +// kinds sharing none give, a closed Model with no member keeping every set, +// with one warning at the position, beside the allOf or on entries alike. +func TestAllOf_ListAndObjectValueSetsSharingNoMemberAreTheBottom(t *testing.T) { + t.Parallel() + for name, schema := range map[string]string{ + "two list sets": "{allOf: [{enum: [[1]]}, {enum: [[2]]}]}", + "two object sets": "{allOf: [{enum: [{a: 1}]}, {enum: [{b: 2}]}]}", + "an object set beside": "{enum: [{a: 1}], allOf: [{enum: [{b: 2}]}]}", + "two object consts": "{allOf: [{const: {a: 1}}, {const: {b: 2}}]}", + "a list const and an enum": "{allOf: [{const: [1]}, {enum: [[2]]}]}", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+schema+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "S").(*ir.Model) + require.True(t, ok, "the bottom: got %T", typeByName(doc, "S")) + assert.Empty(t, model.Properties) + assert.Equal(t, ir.AdditionalClosed, model.Additional) + assert.Equal(t, strings.Count(schema, "enum:")+strings.Count(schema, "const:"), + keptNaming(model.Unmodeled, "enum")+keptNaming(model.Unmodeled, "const"), "every set is kept: %v", model.Unmodeled) + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/S"), 1, "%+v", diags) + }) + } +} + +// TestAllOf_MixedValueSetsSharingNoMemberAreTheBottom holds value sets each +// holding a string and a number and sharing no member, which no one value type +// holds: the bottom, a closed Model with no member keeping every set, with one +// warning at the position, the sets written inline or on $ref entries, a type +// list or a bound beside them. +func TestAllOf_MixedValueSetsSharingNoMemberAreTheBottom(t *testing.T) { + t.Parallel() + const ( + refE = "{$ref: '#/components/schemas/E'}" + refF = "{$ref: '#/components/schemas/F'}" + ) + refSets := []string{`"#/components/schemas/E"`, `"#/components/schemas/F"`} + for name, testCase := range map[string]struct { + schema string + sets []string // what each set is kept as, inside the JSON of the entry keeping it + }{ + "two refs": {"{allOf: [" + refE + ", " + refF + "]}", refSets}, + "a type beside": {"{type: [string, number], allOf: [" + refE + ", " + refF + "]}", refSets}, + "a bound beside": {"{allOf: [" + refE + ", " + refF + ", {maxLength: 2}]}", refSets}, + "inline": {"{allOf: [{enum: [a, 1]}, {enum: [b, 2]}]}", []string{`["a",1]`, `["b",2]`}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " E: {enum: [a, 1]}\n F: {enum: [b, 2]}\n S: "+testCase.schema+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "S").(*ir.Model) + require.True(t, ok, "the bottom: got %T", typeByName(doc, "S")) + assert.Empty(t, model.Properties) + assert.Equal(t, ir.AdditionalClosed, model.Additional) + for _, set := range testCase.sets { + n := 0 + for _, entry := range model.Unmodeled { + if strings.Contains(string(entry.Value), set) { + n++ + } + } + assert.Equal(t, 1, n, "%s is kept once: %v", set, model.Unmodeled) + } + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/S"), 1, "%+v", diags) + }) + } +} + +// TestDynamicRef_OneNamingNothingIsKeptUnderItsOwnKeyword holds a $dynamicRef +// that resolves to no schema, beside the position's keywords or on an allOf +// entry: the position lowers as without it, keeping it verbatim under +// openapi:$dynamicRef, the keyword written, never under openapi:$ref, beside +// its one unresolved-reference error. A $recursiveRef no schema answers is kept +// under openapi:$recursiveRef alike. +func TestDynamicRef_OneNamingNothingIsKeptUnderItsOwnKeyword(t *testing.T) { + t.Parallel() + const draft201909 = "$schema: 'https://json-schema.org/draft/2019-09/schema', " + for name, testCase := range map[string]struct{ schema, keyword, value string }{ + "a pointer beside a bound": {"{$dynamicRef: '#/components/schemas/Ghost', minLength: 2}", "$dynamicRef", "#/components/schemas/Ghost"}, + "a pointer on an entry": {"{allOf: [{$dynamicRef: '#/components/schemas/Ghost'}], minLength: 2}", "$dynamicRef", "#/components/schemas/Ghost"}, + "a pointer beside an object": {"{allOf: [{$dynamicRef: '#/components/schemas/Ghost'}, {type: object, properties: {b: {type: string}}}]}", "$dynamicRef", "#/components/schemas/Ghost"}, + "an anchor beside a type": {"{$dynamicRef: '#nowhere', type: string, minLength: 2}", "$dynamicRef", "#nowhere"}, + "a recursive root": {"{" + draft201909 + "$recursiveRef: '#', minLength: 2}", "$recursiveRef", "#"}, + "a recursive root on an entry": {"{" + draft201909 + "allOf: [{$recursiveRef: '#'}], minLength: 2}", "$recursiveRef", "#"}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+testCase.schema+"\n")) + kept := typeByName(doc, "S").Common().Unmodeled + require.Contains(t, kept, "openapi:"+testCase.keyword, "%v", kept) + assert.Equal(t, ir.ReasonDegradedLowering, kept["openapi:"+testCase.keyword].Reason) + assert.JSONEq(t, `"`+testCase.value+`"`, string(kept["openapi:"+testCase.keyword].Value)) + assert.NotContains(t, kept, "openapi:$ref", "the keyword written is kept, not another") + if testCase.keyword == "$dynamicRef" { + assert.Len(t, withCode(diags, diag.UnresolvedRef), 1, "%+v", diags) + } + }) + } +} diff --git a/compilers/openapi/internal/schema/allof_apart_test.go b/compilers/openapi/internal/schema/allof_apart_test.go index 9c7f1a7c0..dbf737bf9 100644 --- a/compilers/openapi/internal/schema/allof_apart_test.go +++ b/compilers/openapi/internal/schema/allof_apart_test.go @@ -5,8 +5,6 @@ package schema_test import ( "encoding/json/jsontext" - "fmt" - "maps" "slices" "strings" "testing" @@ -14,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) @@ -25,84 +24,102 @@ import ( // none (docs/compilers/openapi.md#allof-disjoint-conjuncts). func TestAllOf_ASplitEntrysReferenceIsNamedWhateverIsBesideIt(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct{ entries, names string }{ + for name, testCase := range map[string]struct{ entries, names string }{ "the keywords beside it follow": {"{$ref: '#/components/schemas/A', enum: [b]}, {enum: [c]}", - "allOf/0/$ref: 1 value, allOf/0: 1 value, allOf/1: 1 value"}, + `allOf/0: enum ["b"], allOf/0/$ref: enum ["a"], allOf/1: enum ["c"]`}, "an allOf beside it lies between": {"{$ref: '#/components/schemas/A', enum: [b], allOf: [{enum: [c]}]}", - "allOf/0/$ref: 1 value, allOf/0/allOf/0: 1 value, allOf/0: 1 value"}, + `allOf/0: enum ["b"], allOf/0/$ref: enum ["a"], allOf/0/allOf/0: enum ["c"]`}, } { t.Run(name, func(t *testing.T) { t.Parallel() - _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " A: {enum: [a]}\n S: {allOf: ["+tc.entries+"]}\n")) + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " A: {enum: [a]}\n S: {allOf: ["+testCase.entries+"]}\n")) openapitest.RequireNoErrorDiags(t, diags) warnings := disjointReports(diags) require.Len(t, warnings, 1, "%+v", diags) assert.Equal(t, jsontext.Pointer("/components/schemas/S"), warnings[0].Provenance.Pointer) - assert.Contains(t, warnings[0].Message, "share no value ("+tc.names+")") + assert.Contains(t, warnings[0].Message, "("+testCase.names+")") }) } } -// TestAllOf_ValueSetsSharingNoMemberWarnOnce holds the one reading of conjuncts -// sharing no value, the election's: value sets sharing no member, a format -// the election reads as excluding a member, and an enum beside the allOf each -// draw one warning naming every set by its member count, as a contradiction -// in the kinds does. None is a Model unless its kinds are an object alone: the -// keywords beside the allOf decide, the top type where they name no kind, and -// a value set elected before the rest stays elected. +// TestAllOf_ValueSetsSharingNoMemberWarnOnce holds the report of an allOf +// whose conjuncts share no value to the choice's: value sets sharing no +// member, a format excluding a member, and an enum beside the allOf each draw +// one warning naming every set by its members, no entry reporting a set. +// Sets of one value type sharing no member are the closed empty Enum of that +// type, keeping every set under its own key, the chosen one included. Two bare +// consts are typed number, as {enum: [1, 2]} is: one reader decides a value +// set's type whichever keyword writes it. func TestAllOf_ValueSetsSharingNoMemberWarnOnce(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { - schema, names, shape string - kind ir.TypeKind + for name, testCase := range map[string]struct { + schema, names string + valueType ir.PrimitiveKind + kept []string }{ - "two enums": {"{allOf: [{enum: [a, b]}, {enum: [c, d]}]}", - "allOf/0: 2 values, allOf/1: 2 values", "the top type it lowered as", ir.KindScalar}, - "two consts": {"{allOf: [{const: 1}, {const: 2}]}", - "allOf/0: 1 value, allOf/1: 1 value", "the top type it lowered as", ir.KindScalar}, - "an enum beside": {"{enum: [a, b], allOf: [{enum: [c, d]}]}", - "allOf/0: 2 values, enum: 2 values", "the enum it lowered as", ir.KindEnum}, - "a format excluding the member": {"{allOf: [{type: number, format: int32}, {type: number, enum: [1.5]}]}", - "allOf/1: 1 value, allOf/0: integer of format int32", "the enum it lowered as", ir.KindEnum}, + "two enums": {"{allOf: [{enum: [a, b]}, {enum: [c, d]}]}", `allOf/0: enum ["a", "b"], allOf/1: enum ["c", "d"]`, + ir.PrimitiveString, []string{"openapi:allOf/0", "openapi:allOf/1"}}, + "two consts": {"{allOf: [{const: 1}, {const: 2}]}", "allOf/0: const 1, allOf/1: const 2", + ir.PrimitiveNumber, []string{"openapi:allOf/0", "openapi:allOf/1"}}, + "three enums": {"{allOf: [{enum: [a]}, {enum: [b]}, {enum: [c]}]}", `allOf/0: enum ["a"], allOf/1: enum ["b"], allOf/2: enum ["c"]`, + ir.PrimitiveString, []string{"openapi:allOf/0", "openapi:allOf/1", "openapi:allOf/2"}}, + "an enum and a const": {"{allOf: [{enum: [b]}, {const: a}]}", `allOf/0: enum ["b"], allOf/1: const "a"`, + ir.PrimitiveString, []string{"openapi:enum", "openapi:const"}}, + "an enum beside": {"{enum: [a, b], allOf: [{enum: [c, d]}]}", `enum: ["a", "b"], allOf/0: enum ["c", "d"]`, + ir.PrimitiveString, []string{"openapi:enum", "openapi:allOf/0"}}, "two typed sets": {"{allOf: [{type: string, enum: [a]}, {type: string, enum: [b]}]}", - "allOf/0: 1 value, allOf/1: 1 value", "the top type it lowered as", ir.KindScalar}, + `allOf/0: enum ["a"], allOf/1: enum ["b"]`, ir.PrimitiveString, []string{"openapi:allOf/0", "openapi:allOf/1"}}, "a type beside": {"{type: string, allOf: [{enum: [a]}, {enum: [b]}]}", - "allOf/0: 1 value, allOf/1: 1 value, type: string", "the string it lowered as", ir.KindScalar}, - "two object sets": {"{allOf: [{enum: [{a: 1}]}, {enum: [{b: 2}]}]}", - "allOf/0: 1 value, allOf/1: 1 value", "a composition", ir.KindModel}, + `type: string, allOf/0: enum ["a"], allOf/1: enum ["b"]`, ir.PrimitiveString, []string{"openapi:allOf/0", "openapi:allOf/1"}}, "a format beside": {"{allOf: [{format: uuid}, {enum: [a]}, {enum: [b]}]}", - "allOf/1: 1 value, allOf/2: 1 value, allOf/0: format uuid", "the top type it lowered as", ir.KindScalar}, + `allOf/0: format uuid, allOf/1: enum ["a"], allOf/2: enum ["b"]`, ir.PrimitiveString, + []string{"openapi:allOf/1", "openapi:allOf/2"}}, } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) warnings := disjointReports(diags) require.Len(t, warnings, 1, "%+v", diags) assert.Equal(t, jsontext.Pointer("/components/schemas/S"), warnings[0].Provenance.Pointer) - assert.Contains(t, warnings[0].Message, "share no value ("+tc.names+")") - assert.Contains(t, warnings[0].Message, "which "+tc.shape+" cannot state") + assert.Contains(t, warnings[0].Message, "("+testCase.names+")") assert.Len(t, warningsAt(diags), 1, "no other warning: %+v", diags) - typeDef := typeByName(doc, "S") - require.NotNil(t, typeDef) - assert.Equal(t, tc.kind, typeDef.Kind()) - if scalar, ok := typeDef.(*ir.Scalar); ok && tc.shape == "the top type it lowered as" { - require.NotNil(t, scalar.Base) - assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveAny), scalar.Base.Target, "no kind is claimed") - for i := range strings.Count(tc.schema, "}, {") + 1 { - entry := fmt.Sprintf("/components/schemas/S/allOf/%d", i) - assert.True(t, slices.ContainsFunc(slices.Collect(maps.Values(scalar.Unmodeled)), func(unmodeledEntry ir.UnmodeledEntry) bool { - return strings.HasPrefix(string(unmodeledEntry.Provenance.Pointer), entry) - }), "the entry at %s is kept", entry) - } + infos := 0 + if name == "a format beside" { + infos = 1 // the format, which no set is + } + assert.Len(t, slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { return diagnostic.Severity != ir.SeverityInfo }), infos, + "no entry reports a set: %+v", diags) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "the closed empty enum: got %T", typeByName(doc, "S")) + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Equal(t, testCase.valueType, enum.ValueType) + for _, key := range testCase.kept { + assert.Contains(t, enum.Unmodeled, key, "every value set is kept under its own key") } }) } + for name, testCase := range map[string]struct { + schema, names, shape string + kind ir.TypeKind + }{ + "a format excluding the member": {"{allOf: [{type: number, format: int32}, {type: number, enum: [1.5]}]}", + "allOf/0: integer of format int32, allOf/1: enum [1.5]", "its enum", ir.KindEnum}, + } { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+testCase.schema+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + warnings := disjointReports(diags) + require.Len(t, warnings, 1, "%s: %+v", name, diags) + assert.Contains(t, warnings[0].Message, "("+testCase.names+")", name) + assert.Contains(t, warnings[0].Message, "; lowered as "+testCase.shape+" — ", name) + assert.Equal(t, testCase.kind, typeByName(doc, "S").Kind(), name) + } } // TestAllOf_ValueSetsSharingAValueDrawNoWarning holds the reading to what it // says: sets sharing a member, a null among them, share a value, so nothing -// warns, and a set within the other is elected as before. +// warns, and a set within the other is chosen as before. func TestAllOf_ValueSetsSharingAValueDrawNoWarning(t *testing.T) { t.Parallel() for name, schema := range map[string]string{ @@ -119,20 +136,58 @@ func TestAllOf_ValueSetsSharingAValueDrawNoWarning(t *testing.T) { } // TestAllOf_ValueSetsSharingNoMemberReportAlikeInEitherOrder holds the report -// and the lowering to one document whichever order the sets are written in: -// the report lists the sets by what each states, so swapping the entries -// swaps their names and nothing else. +// of value sets sharing no member to name each by where it is written, in +// pointer order, whichever order the sets are written in, and to lower alike. func TestAllOf_ValueSetsSharingNoMemberReportAlikeInEitherOrder(t *testing.T) { t.Parallel() one, oneDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: [{enum: [a, b]}, {enum: [c]}]}\n")) two, twoDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: [{enum: [c]}, {enum: [a, b]}]}\n")) - swap := strings.NewReplacer("allOf/0", "allOf/1", "allOf/1", "allOf/0") require.Len(t, disjointReports(oneDiags), 1) require.Len(t, disjointReports(twoDiags), 1) - assert.Equal(t, disjointReports(oneDiags)[0].Message, swap.Replace(disjointReports(twoDiags)[0].Message)) + assert.Contains(t, disjointReports(oneDiags)[0].Message, `(allOf/0: enum ["a", "b"], allOf/1: enum ["c"])`) + assert.Contains(t, disjointReports(twoDiags)[0].Message, `(allOf/0: enum ["c"], allOf/1: enum ["a", "b"])`) assert.Equal(t, typeByName(one, "S").Kind(), typeByName(two, "S").Kind()) } +// TestAllOf_AValueSetIsNamedByWhatWritesIt pins how a report of conjuncts +// sharing no value names a value set: an enum by its first five members and +// a count of the rest, a list or an object by its brackets, a set no one +// schema writes, as an allOf holds one, by its size, and a union one of whose +// branches writes none so too; a dead branch writing a set is named by it +// (docs/compilers/openapi.md#allof-disjoint-conjuncts). +func TestAllOf_AValueSetIsNamedByWhatWritesIt(t *testing.T) { + t.Parallel() + const held = " E: {allOf: [{enum: [a, b]}, {type: string}]}\n" + for name, testCase := range map[string]struct{ schema, at, names string }{ + "a long enum": {"{allOf: [{enum: [a, b, c, d, e, f, g]}, {enum: [z]}]}", "", + `allOf/0: enum ["a", "b", "c", "d", "e", … 2 more], allOf/1: enum ["z"]`}, + "lists and objects": {"{allOf: [{enum: [[1], {a: 1}]}, {enum: [z]}]}", "", `allOf/0: enum [[…], {…}], allOf/1: enum ["z"]`}, + "a set an allOf holds": {"{allOf: [{$ref: '#/components/schemas/E'}, {enum: [c]}]}", "", `allOf/0: a value set of size 2, allOf/1: enum ["c"]`}, + "a pair of unions": {"{oneOf: [{enum: [d]}, {$ref: '#/components/schemas/E'}], anyOf: [{enum: [c]}]}", "", + `oneOf: a value set of size 3, anyOf: one of ["c"]`}, + "a dead branch": {"{type: string, oneOf: [{enum: [1, 2]}, {format: uuid}, {format: date}]}", "/oneOf", "oneOf/0: enum [1, 2]"}, + } { + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", held+" S: "+testCase.schema+"\n")) + got := openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/S"+testCase.at) + assert.Contains(t, got, "("+testCase.names+")", name) + } +} + +// TestAllOf_ConjunctsAreNamedInTheOrderTheirEntriesAreWritten pins the order +// a report of conjuncts sharing no value names them in: each entry by where +// its path is written, an index by its number, so a oneOf at entry 9 comes +// before an anyOf at entry 10. +func TestAllOf_ConjunctsAreNamedInTheOrderTheirEntriesAreWritten(t *testing.T) { + t.Parallel() + entries := slices.Repeat([]string{"{}"}, 9) + entries = append(entries, "{oneOf: [{enum: [a]}, {enum: [b]}]}", "{anyOf: [{enum: [c]}, {enum: [d]}]}") + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+strings.Join(entries, ", ")+"]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + warnings := disjointReports(diags) + require.Len(t, warnings, 1, "%+v", diags) + assert.Contains(t, warnings[0].Message, `(allOf/9/oneOf: one of ["a", "b"], allOf/10/anyOf: one of ["c", "d"])`) +} + // warningsAt returns the warnings among diags. func warningsAt(diags []ir.Diagnostic) []ir.Diagnostic { var out []ir.Diagnostic @@ -144,25 +199,79 @@ func warningsAt(diags []ir.Diagnostic) []ir.Diagnostic { return out } -// TestAllOf_ARefAmongValueSetsSharingNoMemberIsKept holds that a $ref beside -// value sets sharing no member is no principal, as none of the conjuncts is: -// the position is the top type, the $ref kept with an info saying why. +// TestAllOf_ARefAmongValueSetsSharingNoMemberIsKept holds value sets sharing +// no member, one of them a $ref's target, on entries or beside the $ref: the +// position is the closed empty Enum of their value type, keeping every set +// verbatim under its own key, the $ref and the one written beside it among +// them, with one warning. func TestAllOf_ARefAmongValueSetsSharingNoMemberIsKept(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " E: {enum: [a, b]}\n"+ - " S: {allOf: [{$ref: '#/components/schemas/E'}, {enum: [c]}, {enum: [d]}]}\n")) - require.Len(t, disjointReports(diags), 1, "%+v", diags) - scalar, ok := typeByName(doc, "S").(*ir.Scalar) - require.True(t, ok, "%T", typeByName(doc, "S")) - require.NotNil(t, scalar.Base) - assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveAny), scalar.Base.Target) - assert.Contains(t, scalar.Unmodeled, "openapi:$ref") - var why []string - for _, diagnostic := range diags { - if diagnostic.Provenance.Pointer == "/components/schemas/S/allOf/0" { - why = append(why, diagnostic.Message) + " S: {allOf: [{$ref: '#/components/schemas/E'}, {enum: [c]}, {enum: [d]}]}\n"+ + " TwoEnums: {allOf: [{enum: [a, b]}, {enum: [c]}]}\n"+ + " Pos: {$ref: '#/components/schemas/E', enum: [other]}\n")) + for name, kept := range map[string][]string{ + "S": {"openapi:$ref", "openapi:allOf/1", "openapi:allOf/2"}, + "TwoEnums": {"openapi:allOf/0", "openapi:allOf/1"}, + "Pos": {"openapi:$ref", "openapi:enum"}, + } { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s: got %T", name, typeByName(doc, name)) + assert.Empty(t, enum.Members, name) + assert.True(t, enum.Closed, name) + assert.Equal(t, ir.PrimitiveString, enum.ValueType, name) + assert.Subset(t, unmodeledKeys(enum.Unmodeled), kept, "%s keeps every value set", name) + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name), 1, name) + } + assert.JSONEq(t, `["other"]`, string(typeByName(doc, "Pos").Common().Unmodeled["openapi:enum"].Value), "Pos keeps its own set") +} + +// TestAllOf_AnEntryKeptWholeNamesTheSetItWrites holds two entries kept whole +// for an extension they write otherwise, each beside a value set the two share +// no member of: each report names every keyword its entry holds, the set the +// reading chosen among them, in either order of the entries. +func TestAllOf_AnEntryKeptWholeNamesTheSetItWrites(t *testing.T) { + t.Parallel() + const first, second = "{enum: [a], x-k: 1}", "{enum: [b], x-k: 2}" + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Written: {allOf: ["+first+", "+second+"]}\n Reversed: {allOf: ["+second+", "+first+"]}\n")) + for _, name := range []string{"Written", "Reversed"} { + for _, at := range []string{"/allOf/0", "/allOf/1"} { + pointer := "/components/schemas/" + name + at + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, pointer), "the entry (enum, x-k) is kept", pointer) } } - require.Len(t, why, 1) - assert.Contains(t, why[0], "the value sets of this allOf share no member, so no conjunct is the one it lowers from") +} + +// TestAllOf_AnEnumAConstElsewherePassesOverIsKeptAsFlat holds an enum the +// const a position lowers as passes over, written on another conjunct than the +// const: in either order of the entries, and with either beside the allOf, the +// position is the const's Literal keeping the enum verbatim under its own key, +// with the one report at the position the flat twin draws +// (docs/compilers/openapi.md#competing-keywords). +func TestAllOf_AnEnumAConstElsewherePassesOverIsKeptAsFlat(t *testing.T) { + t.Parallel() + spellings := map[string]string{ + "Flat": "{enum: [a, b], const: b}", + "Entries": "{allOf: [{enum: [a, b]}, {const: b}]}", + "Reversed": "{allOf: [{const: b}, {enum: [a, b]}]}", + "EnumBeside": "{enum: [a, b], allOf: [{const: b}]}", + "ConstBeside": "{const: b, allOf: [{enum: [a, b]}]}", + } + var lines strings.Builder + for name, schema := range spellings { + lines.WriteString(" " + name + ": " + schema + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", lines.String())) + openapitest.RequireNoErrorDiags(t, diags) + for name := range spellings { + at := "/components/schemas/" + name + literal, ok := typeByName(doc, name).(*ir.Literal) + require.True(t, ok, "%s: the const: got %T", name, typeByName(doc, name)) + assert.Equal(t, []string{"openapi:enum"}, unmodeledKeys(literal.Unmodeled), name) + assert.JSONEq(t, `["a","b"]`, string(literal.Unmodeled["openapi:enum"].Value), name) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), + "this position declares enum beside its const", name) + assert.Len(t, diagsUnder(diags, at), 1, "%s: the one report: %+v", name, diags) + } } diff --git a/compilers/openapi/internal/schema/allof_bounds_test.go b/compilers/openapi/internal/schema/allof_bounds_test.go index 565ca8796..8c5f9442e 100644 --- a/compilers/openapi/internal/schema/allof_bounds_test.go +++ b/compilers/openapi/internal/schema/allof_bounds_test.go @@ -34,12 +34,12 @@ func redeclared(t *testing.T, a, b string) (ir.Property, *ir.Document, []ir.Diag } // TestAllOf_ABoundTakesItsTightestValueInEitherOrder pins a field typed by a -// shared primitive, where a bound stands on the property. Each pair is declared +// shared primitive, where a bound sits on the property. Each pair is declared // looser first as well as tighter first, since the first declaration's bound used // to be kept: a fixture declaring only the tighter first passes on that code. func TestAllOf_ABoundTakesItsTightestValueInEitherOrder(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name string looser, tighter string want *ir.Constraints @@ -71,8 +71,10 @@ func TestAllOf_ABoundTakesItsTightestValueInEitherOrder(t *testing.T) { &ir.Constraints{Min: new(ir.BigVal("2e1000001"))}, }, { - "a step too large for a rational", "{type: number, multipleOf: 1e1000001}", "{type: number, multipleOf: 1e1000002}", - &ir.Constraints{MultipleOf: new(ir.BigVal("1e1000002"))}, + // A step whose numerator passes the 1,024 digits a step intersection reads + // intersects no other, so the scale no rational holds is below one. + "a step too fine for a rational", "{type: number, multipleOf: 1e-1000002}", "{type: number, multipleOf: 1e-1000001}", + &ir.Constraints{MultipleOf: new(ir.BigVal("1e-1000001"))}, }, { "multipleOf, one dividing the other", "{type: number, multipleOf: 0.5}", "{type: number, multipleOf: 2}", @@ -83,12 +85,12 @@ func TestAllOf_ABoundTakesItsTightestValueInEitherOrder(t *testing.T) { &ir.Constraints{MultipleOf: new(ir.BigVal("12"))}, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - for _, order := range [][2]string{{tc.looser, tc.tighter}, {tc.tighter, tc.looser}} { + for _, order := range [][2]string{{testCase.looser, testCase.tighter}, {testCase.tighter, testCase.looser}} { property, _, diags := redeclared(t, order[0], order[1]) - assert.Equal(t, tc.want, property.Constraints) + assert.Equal(t, testCase.want, property.Constraints) assert.Empty(t, diags, "a bound the field implies is no disagreement") assert.Empty(t, property.Unmodeled, "and nothing of it is lost") } @@ -107,7 +109,7 @@ func TestAllOf_ANodesBoundsReachTheFieldInEitherOrder(t *testing.T) { tuple := func(extra string) string { return "{type: array, prefixItems: [{type: string}]" + extra + "}" } custom := func(extra string) string { return "{type: string, format: x-custom" + extra + "}" } lo, hi := new(int64(1)), new(int64(5)) - for _, tc := range []struct { + for _, testCase := range []struct { name string a, b string want *ir.Constraints @@ -121,15 +123,15 @@ func TestAllOf_ANodesBoundsReachTheFieldInEitherOrder(t *testing.T) { {name: "a scalar adding a bound", a: custom(""), b: custom(", maxLength: 5"), want: &ir.Constraints{MaxLength: hi}}, {name: "two scalars each adding a bound", a: custom(", minLength: 1"), b: custom(", maxLength: 5"), want: &ir.Constraints{MinLength: lo, MaxLength: hi}, minted: true}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - for _, order := range [][2]string{{tc.a, tc.b}, {tc.b, tc.a}} { + for _, order := range [][2]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { property, doc, diags := redeclared(t, order[0], order[1]) - td, ok := doc.Types[property.Type.Target] + typeDef, ok := doc.Types[property.Type.Target] require.True(t, ok, "the field's type is in the document") - assert.Equal(t, tc.want, openapitest.NodeConstraints(t, td)) - assert.Contains(t, string(property.Type.Target), map[bool]string{true: "type/composed/", false: "type/anonymous/"}[tc.minted]) + assert.Equal(t, testCase.want, openapitest.NodeConstraints(t, typeDef)) + assert.Contains(t, string(property.Type.Target), map[bool]string{true: "type/composed/", false: "type/anonymous/"}[testCase.minted]) assert.Empty(t, diags) assert.Empty(t, property.Unmodeled) } @@ -150,7 +152,7 @@ func TestAllOf_ANodeHoldingMoreThanBoundsIsAdoptedInEitherOrder(t *testing.T) { mapOf := func(extra string) string { return "{type: object, additionalProperties: {type: string}" + extra + "}" } tuple := func(extra string) string { return "{type: array, prefixItems: [{type: string}]" + extra + "}" } custom := func(extra string) string { return "{type: string, format: x-custom" + extra + "}" } - for _, tc := range []struct{ name, a, b string }{ + for _, testCase := range []struct{ name, a, b string }{ {"two lists meeting, one deprecated", list(", minItems: 1, deprecated: true"), list(", maxItems: 5")}, {"two lists meeting, one with XML hints", list(", minItems: 1, xml: {wrapped: true}"), list(", maxItems: 5")}, {"a narrower list and a broader one deprecated", list(", minItems: 1, maxItems: 5"), list(", minItems: 1, deprecated: true")}, @@ -158,13 +160,13 @@ func TestAllOf_ANodeHoldingMoreThanBoundsIsAdoptedInEitherOrder(t *testing.T) { {"two tuples meeting, one deprecated", tuple(", minItems: 1, deprecated: true"), tuple(", maxItems: 5")}, {"two scalars meeting, one deprecated", custom(", minLength: 1, deprecated: true"), custom(", maxLength: 5")}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() built := make([]ir.TypeDef, 0, 2) - for _, order := range [][2]string{{tc.a, tc.b}, {tc.b, tc.a}} { + for _, order := range [][2]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { property, doc, diags := redeclared(t, order[0], order[1]) - assert.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/1/properties/v"), property.Type.Target) + assert.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/properties/v"), property.Type.Target) assert.Empty(t, property.Unmodeled) assert.Empty(t, diags) node := doc.Types[property.Type.Target] @@ -184,30 +186,32 @@ func TestAllOf_ANodeHoldingMoreThanBoundsIsAdoptedInEitherOrder(t *testing.T) { } // TestAllOf_ADefaultABoundOnThePropertyRefusesIsKeptInEitherOrder pins a default -// against a bound another declaration wrote on the property, which lowers as the -// same bound on a node does: not adopted, reported, and the declaration kept. A -// declaration whose own bound refuses its own default is left to it. +// against a bound on the property, which lowers as the same bound on a node does: +// not adopted, reported, and the declaration kept, whether another declaration +// wrote the bound or the one giving the default did. func TestAllOf_ADefaultABoundOnThePropertyRefusesIsKeptInEitherOrder(t *testing.T) { t.Parallel() - valued, bound := "{type: string, default: hello}", "{type: string, maxLength: 3}" - for _, order := range []struct{ a, b, kept string }{ - {valued, bound, "/components/schemas/T/allOf/0/properties/v"}, - {bound, valued, "/components/schemas/T/allOf/1/properties/v"}, + for name, testCase := range map[string]struct{ valued, other string }{ + "another's bound": {"{type: string, default: hello}", "{type: string, maxLength: 3}"}, + "its own bound": {"{type: string, maxLength: 3, default: hello}", "{type: string}"}, } { - property, _, diags := redeclared(t, order.a, order.b) + t.Run(name, func(t *testing.T) { + t.Parallel() + for _, order := range []struct{ a, b, kept string }{ + {testCase.valued, testCase.other, "/components/schemas/T/allOf/0/properties/v"}, + {testCase.other, testCase.valued, "/components/schemas/T/allOf/1/properties/v"}, + } { + property, _, diags := redeclared(t, order.a, order.b) - assert.Nil(t, property.Default) - assert.Equal(t, &ir.Constraints{MaxLength: new(int64(3))}, property.Constraints) - assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+order.kept) - require.Len(t, diags, 1) - assert.Equal(t, diag.DegradedConstruct, diags[0].Code) - assert.Equal(t, order.kept, string(diags[0].Provenance.Pointer)) + assert.Nil(t, property.Default) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(3))}, property.Constraints) + assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+order.kept) + require.Len(t, diags, 1) + assert.Equal(t, diag.DegradedConstruct, diags[0].Code) + assert.Equal(t, order.kept, string(diags[0].Provenance.Pointer)) + } + }) } - - irProperty, _, diags := redeclared(t, "{type: string, maxLength: 3, default: hello}", "{type: string}") - require.NotNil(t, irProperty.Default, "a default its own bound refuses stays as it was") - assert.Equal(t, "hello", irProperty.Default.String) - assert.Empty(t, diags) } // TestAllOf_AFoldedDeclarationLeavesNoRecordOfItself pins what a field keeps of a @@ -259,13 +263,13 @@ func TestAllOf_ACountNoFieldStatesIsKeptInEitherOrder(t *testing.T) { } // TestAllOf_TheBindingCountIsKeptInEveryOrder pins counts no field states that -// several writers of one position give, on its entries or beside its allOf: +// several conjuncts of one position give, on its entries or beside its allOf: // the one binding the rest is kept, the smallest maximum and the largest // minimum compared exactly, with one info where it was written, in every order. // want is the kept entry's JSON. func TestAllOf_TheBindingCountIsKeptInEveryOrder(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, typ, keyword string counts []string want string @@ -275,23 +279,23 @@ func TestAllOf_TheBindingCountIsKeptInEveryOrder(t *testing.T) { {"three minima", "string", "minLength", []string{"99999999999999999999", "88888888888888888888", "77777777777777777777"}, "99999999999999999999"}, } { - for _, order := range permutations(len(tc.counts)) { + for _, order := range permutations(len(testCase.counts)) { entries := make([]string, len(order)) for k, i := range order { - entries[k] = "{" + tc.keyword + ": " + tc.counts[i] + "}" + entries[k] = "{" + testCase.keyword + ": " + testCase.counts[i] + "}" } for _, beside := range []bool{false, true} { - spec := " T: {type: " + tc.typ + ", allOf: [" + strings.Join(entries, ", ") + "]}\n" + spec := " T: {type: " + testCase.typ + ", allOf: [" + strings.Join(entries, ", ") + "]}\n" if beside { - spec = " T: {type: " + tc.typ + ", " + entries[0][1:len(entries[0])-1] + ", allOf: [" + + spec = " T: {type: " + testCase.typ + ", " + entries[0][1:len(entries[0])-1] + ", allOf: [" + strings.Join(entries[1:], ", ") + "]}\n" } doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(spec)) openapitest.RequireNoErrorDiags(t, diags) um := typeByName(doc, "T").Common().Unmodeled - require.Equal(t, []string{"openapi:" + tc.keyword}, unmodeledKeys(um), "%s %v %v", tc.name, order, beside) - assert.Equal(t, tc.want, string(um["openapi:"+tc.keyword].Value), "%s %v %v", tc.name, order, beside) - assert.Len(t, diags, 1, "%s %v %v: one report", tc.name, order, beside) + require.Equal(t, []string{"openapi:" + testCase.keyword}, unmodeledKeys(um), "%s %v %v", testCase.name, order, beside) + assert.Equal(t, testCase.want, string(um["openapi:"+testCase.keyword].Value), "%s %v %v", testCase.name, order, beside) + assert.Len(t, diags, 1, "%s %v %v: one report", testCase.name, order, beside) } } } @@ -327,7 +331,7 @@ func TestAllOf_TheBindingCountPastTheDecimalRangeIsRefusedInEveryOrder(t *testin require.Len(t, diags, 1, "%v %v: one report", order, beside) assert.Equal(t, ir.SeverityError, diags[0].Severity, "%v %v", order, beside) assert.Equal(t, diag.UnpreservableConstruct, diags[0].Code, "%v %v", order, beside) - assert.Equal(t, jsontext.Pointer(at), diags[0].Provenance.Pointer, "%v %v", order, beside) + assert.Equal(t, jsontext.Pointer(at+"/maxLength"), diags[0].Provenance.Pointer, "%v %v: at the count", order, beside) } } } @@ -391,8 +395,8 @@ func TestAllOf_ABoundBesideACompositionIsReadByItsType(t *testing.T) { require.True(t, isModel, "got %T", doc.Types[variant.Type.Target]) assert.Equal(t, held, model.Constraints) } - for name, td := range map[string]ir.TypeDef{"Comp": comp, "Dist": dist} { - assert.Equal(t, []string{"openapi:minLength"}, unmodeledKeys(td.Common().Unmodeled), name) + for name, typeDef := range map[string]ir.TypeDef{"Comp": comp, "Dist": dist} { + assert.Equal(t, []string{"openapi:minLength"}, unmodeledKeys(typeDef.Common().Unmodeled), name) assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/"+name), "no home for minLength", name) } diff --git a/compilers/openapi/internal/schema/allof_conflicts_test.go b/compilers/openapi/internal/schema/allof_conflicts_test.go index bd612f9d3..6457eb3be 100644 --- a/compilers/openapi/internal/schema/allof_conflicts_test.go +++ b/compilers/openapi/internal/schema/allof_conflicts_test.go @@ -113,14 +113,14 @@ func TestAllOf_RedeclarationOrsSecret(t *testing.T) { secret := " token: {type: string, format: password}\n" bounded := " token: {type: string, minLength: 3, description: the token}\n" entry := " - type: object\n properties:\n" - for _, tc := range []struct{ name, first, second string }{ + for _, testCase := range []struct{ name, first, second string }{ {"password first", secret, bounded}, {"password second", bounded, secret}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(" Tokenish:\n allOf:\n" + - entry + tc.first + entry + tc.second) + entry + testCase.first + entry + testCase.second) doc, diags := schema.LowerSpec(t, spec) assert.Empty(t, diags, "nothing conflicts") model, ok := doc.Types[componentID("Tokenish")].(*ir.Model) @@ -132,7 +132,7 @@ func TestAllOf_RedeclarationOrsSecret(t *testing.T) { require.NotNil(t, tok.Constraints, "the other entry's bound is folded, not dropped") assert.Equal(t, new(int64(3)), tok.Constraints.MinLength) assert.Equal(t, "the token", tok.Docs.Description) - assert.Empty(t, tok.Unmodeled, "no declaration was kept as a loser") + assert.Empty(t, tok.Unmodeled, "no declaration was kept as a passed-over one") }) } } @@ -150,7 +150,7 @@ func TestAllOf_RedeclarationMarksAPromotedSecretOnly(t *testing.T) { deprecated := " token: {type: string, deprecated: true}\n" dated := " token: {type: string, format: password, deprecated: true, x-sunset: \"2030-01-01\"}\n" entry := " - type: object\n properties:\n" - for _, tc := range []struct { + for _, testCase := range []struct { name, first, second string want ir.Inferred }{ @@ -158,16 +158,16 @@ func TestAllOf_RedeclarationMarksAPromotedSecretOnly(t *testing.T) { {"a key's redaction first", keyed, bare, marker}, {"a declared redaction beside a dropped promoted date", dated, deprecated, ""}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(" Tokenish:\n allOf:\n" + - entry + tc.first + entry + tc.second) + entry + testCase.first + entry + testCase.second) doc, _ := schema.LowerSpec(t, spec) model, ok := doc.Types[componentID("Tokenish")].(*ir.Model) require.True(t, ok, "Tokenish should be a model") require.Len(t, model.Properties, 1, "token reconciles to a single property") assert.True(t, model.Properties[0].Secret) - assert.Equal(t, tc.want, model.Properties[0].Provenance.Inferred) + assert.Equal(t, testCase.want, model.Properties[0].Provenance.Inferred) }) } } @@ -231,14 +231,14 @@ func TestAllOf_ConflictingRedeclaredTypeDiagnosedAndKept(t *testing.T) { // A diagnostic is not part of the document, so the losing declaration is // also kept where a consumer reading the IR will reach it (GitHub #424). - lost, ok := model.Properties[0].Unmodeled["openapi:conflicting-redeclaration"+ + passedOver, ok := model.Properties[0].Unmodeled["openapi:conflicting-redeclaration"+ "/components/schemas/Conflictish/allOf/0/properties/id"] require.True(t, ok, - "the discarded type is kept beside the winner; got %v", model.Properties[0].Unmodeled) - assert.Equal(t, ir.ReasonDegradedLowering, lost.Reason) - assert.JSONEq(t, `{"type":"string"}`, string(lost.Value), + "the discarded type is kept beside the chosen one; got %v", model.Properties[0].Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, passedOver.Reason) + assert.JSONEq(t, `{"type":"string"}`, string(passedOver.Value), "and it is the declaration the first entry wrote, not the one that won") - assert.Equal(t, jsontext.Pointer("/components/schemas/Conflictish/allOf/0/properties/id"), lost.Provenance.Pointer) + assert.Equal(t, jsontext.Pointer("/components/schemas/Conflictish/allOf/0/properties/id"), passedOver.Provenance.Pointer) } // TestAllOf_OverlappingPrimitivesAreReportedNotConflicting pins that two @@ -310,19 +310,19 @@ func TestAllOf_EnumPairsAreJudgedByKind(t *testing.T) { {"enum against an enum sharing no member", "{type: string, enum: [a]}", "{type: string, enum: [b]}", false, true}, {"enum against string", "{type: string, enum: [a]}", "{type: string}", false, false}, } - for _, tc := range cases { + for _, testCase := range cases { for _, swap := range []bool{false, true} { - a, b := tc.a, tc.b + a, b := testCase.a, testCase.b if swap { a, b = b, a } - t.Run(fmt.Sprintf("%s swapped=%t", tc.name, swap), func(t *testing.T) { + t.Run(fmt.Sprintf("%s swapped=%t", testCase.name, swap), func(t *testing.T) { t.Parallel() _, diags := schema.LowerSpec(t, allOfConflictSpec(a, b)) openapitest.RequireNoErrorDiags(t, diags) - assert.Equal(t, tc.info, openapitest.HasDiagAt(diags, diag.DegradedConstruct, ir.SeverityInfo), + assert.Equal(t, testCase.info, openapitest.HasDiagAt(diags, diag.DegradedConstruct, ir.SeverityInfo), "the overlap info") - if tc.warn { + if testCase.warn { assert.Len(t, conflictDiags(diags), 1, "one conflict warning") return } @@ -332,11 +332,12 @@ func TestAllOf_EnumPairsAreJudgedByKind(t *testing.T) { } } -// TestAllOf_ALosingRedeclarationIsKeptAsWritten pins what the entry holds at -// the two property shapes that have no schema node of their own to speak of: a -// `$ref` is kept as the `$ref` the position wrote, not as the target it names, -// and a boolean schema — which has no source node to render — is kept as its value. -func TestAllOf_ALosingRedeclarationIsKeptAsWritten(t *testing.T) { +// TestAllOf_APassedOverRedeclarationIsKeptAsWritten pins what the entry holds +// at the two property shapes that have no schema node of their own to speak of: +// a `$ref` is kept as the `$ref` the position wrote, not as the target it +// names, and a boolean schema — which has no source node to render — is kept as +// its value. +func TestAllOf_APassedOverRedeclarationIsKeptAsWritten(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(` Str: {type: string} Referred: @@ -359,24 +360,24 @@ func TestAllOf_ALosingRedeclarationIsKeptAsWritten(t *testing.T) { doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) - for _, tc := range []struct{ model, want string }{ + for _, testCase := range []struct{ model, want string }{ {"Referred", `{"$ref":"#/components/schemas/Str"}`}, {"Nothing", `false`}, } { - model, ok := doc.Types[componentID(tc.model)].(*ir.Model) - require.True(t, ok, "%s should be a model", tc.model) + model, ok := doc.Types[componentID(testCase.model)].(*ir.Model) + require.True(t, ok, "%s should be a model", testCase.model) require.Len(t, model.Properties, 1) - key := "openapi:conflicting-redeclaration/components/schemas/" + tc.model + "/allOf/0/properties/id" - lost, ok := model.Properties[0].Unmodeled[key] - require.True(t, ok, "%s keeps its losing declaration; got %v", tc.model, model.Properties[0].Unmodeled) - assert.JSONEq(t, tc.want, string(lost.Value)) + key := "openapi:conflicting-redeclaration/components/schemas/" + testCase.model + "/allOf/0/properties/id" + passedOver, ok := model.Properties[0].Unmodeled[key] + require.True(t, ok, "%s keeps its losing declaration; got %v", testCase.model, model.Properties[0].Unmodeled) + assert.JSONEq(t, testCase.want, string(passedOver.Value)) } } func TestAllOf_ConflictingRedeclaredConstraintDiagnosed(t *testing.T) { t.Parallel() // Same target type, but the two entries pin a keyword with no order to - // different values. The chosen winner is arbitrary source order, so the + // different values. The chosen declaration is arbitrary source order, so the // dropped pattern is surfaced rather than silently discarded. spec := openapitest.ComponentSpec(` Boundish: allOf: @@ -405,10 +406,10 @@ func TestAllOf_ConflictingRedeclaredConstraintDiagnosed(t *testing.T) { assert.Contains(t, diagnostic.Message, "allOf/1") } -func TestAllOf_CompatibleRedeclarationStaysSilent(t *testing.T) { +func TestAllOf_CompatibleRedeclarationReportsNothing(t *testing.T) { t.Parallel() // The reconcilable case: identical target type, the second entry only adds - // `required`. This must stay silent — a redeclaration is not by itself a + // `required`. This must report nothing — a redeclaration is not by itself a // conflict, only an incompatible one is. spec := openapitest.ComponentSpec(` Compatish: allOf: @@ -554,7 +555,7 @@ func TestAllOf_UntypedRedeclarationDoesNotConflict(t *testing.T) { func TestAllOf_EquivalentNumericBoundsDoNotConflict(t *testing.T) { t.Parallel() // The same bound spelled two ways (10 and 10.0) denotes one value, so it must - // compare equal by magnitude and stay silent. + // compare equal by magnitude and report nothing. spec := openapitest.ComponentSpec(` Boundish: allOf: - type: object @@ -647,23 +648,23 @@ func TestAllOf_ConstraintAndFormatConflictsDiagnosed(t *testing.T) { wantDetail: "incompatible types", }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - _, diags := schema.LowerSpec(t, allOfConflictSpec(tc.a, tc.b)) + _, diags := schema.LowerSpec(t, allOfConflictSpec(testCase.a, testCase.b)) openapitest.RequireNoErrorDiags(t, diags) conflicts := conflictDiags(diags) - require.Len(t, conflicts, 1, "%s is diagnosed exactly once", tc.name) + require.Len(t, conflicts, 1, "%s is diagnosed exactly once", testCase.name) assert.Contains(t, conflicts[0].Message, `"v"`, "the diagnostic names the field") assert.Contains(t, conflicts[0].Message, "allOf/0", "names the first entry site") assert.Contains(t, conflicts[0].Message, "allOf/1", "names the second entry site") - assert.Contains(t, conflicts[0].Message, tc.wantDetail, - "%s: the diagnostic names what actually differs", tc.name) + assert.Contains(t, conflicts[0].Message, testCase.wantDetail, + "%s: the diagnostic names what actually differs", testCase.name) }) } } -func TestAllOf_CompatibleConstraintRedeclarationsStaySilent(t *testing.T) { +func TestAllOf_CompatibleConstraintRedeclarationsReportNothing(t *testing.T) { t.Parallel() // The false-positive guards for the constraint path: a keyword present on // only one entry (both entries still carry constraints) is intersected, @@ -735,18 +736,18 @@ func TestAllOf_CompatibleConstraintRedeclarationsStaySilent(t *testing.T) { }, {name: "custom format over base", a: "{type: string, format: weird}", b: "{type: string}"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, allOfConflictSpec(tc.a, tc.b)) - assert.Empty(t, diags, "%s draws no diagnostic", tc.name) - if tc.assertMerged == nil { + doc, diags := schema.LowerSpec(t, allOfConflictSpec(testCase.a, testCase.b)) + assert.Empty(t, diags, "%s draws no diagnostic", testCase.name) + if testCase.assertMerged == nil { return } model, ok := typeByName(doc, "T").(*ir.Model) require.True(t, ok, "T should be a model") require.Len(t, model.Properties, 1, "v reconciles to one property") - tc.assertMerged(t, model.Properties[0].Constraints) + testCase.assertMerged(t, model.Properties[0].Constraints) }) } } @@ -794,7 +795,7 @@ func TestAllOf_ThreeWayRedeclarationProducesTwoDiagnostics(t *testing.T) { require.Len(t, conflicts, 2, "three-way redeclaration produces two diagnostics") } -func TestAllOf_ThreeWayCompatibleRedeclarationStaysSilent(t *testing.T) { +func TestAllOf_ThreeWayCompatibleRedeclarationReportsNothing(t *testing.T) { t.Parallel() // When three allOf entries declare the same field with compatible types // (all the same), no conflict is reported. @@ -813,10 +814,10 @@ func TestAllOf_ThreeWayCompatibleRedeclarationStaysSilent(t *testing.T) { _, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, conflictDiags(diags), - "three-way compatible redeclaration stays silent") + "three-way compatible redeclaration reports nothing") } -func TestAllOf_SatisfiableNarrowingsStaySilent(t *testing.T) { +func TestAllOf_SatisfiableNarrowingsReportNothing(t *testing.T) { t.Parallel() // Each case narrows a base type to a stricter but satisfiable shape under // allOf intersection (enum of the base's own primitive, const pinning a @@ -830,12 +831,12 @@ func TestAllOf_SatisfiableNarrowingsStaySilent(t *testing.T) { {"const narrows base type", "{type: string}", "{type: string, const: dog}"}, {"union narrowed to one member", "{type: [string, integer]}", "{type: string}"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - _, diags := schema.LowerSpec(t, allOfConflictSpec(tc.a, tc.b)) + _, diags := schema.LowerSpec(t, allOfConflictSpec(testCase.a, testCase.b)) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, conflictDiags(diags), "%s must not be reported as a conflict", tc.name) + assert.Empty(t, conflictDiags(diags), "%s must not be reported as a conflict", testCase.name) }) } } @@ -856,14 +857,17 @@ func TestAllOf_EnumVersusIncompatibleTypeStillConflicts(t *testing.T) { func TestAllOf_TypeConflictMessageNamesBothTypes(t *testing.T) { t.Parallel() // The type-conflict diagnostic must say what actually differs, not just - // that something did: the two conflicting type identities, so the author - // can see at a glance what disagreed without cross-referencing the spec. + // that something did: the two conflicting types as the author wrote them, + // each beside the place writing it, so the author can see at a glance what + // disagreed without cross-referencing the spec, and no type ID, which the + // author never wrote. _, diags := schema.LowerSpec(t, allOfConflictSpec("{type: string}", "{type: integer}")) openapitest.RequireNoErrorDiags(t, diags) conflicts := conflictDiags(diags) require.Len(t, conflicts, 1) - assert.Contains(t, conflicts[0].Message, "type/primitive/string", "names the first entry's type") - assert.Contains(t, conflicts[0].Message, "type/primitive/integer", "names the second entry's type") + assert.Contains(t, conflicts[0].Message, "/components/schemas/T/allOf/1/properties/v and /components/schemas/T/allOf/0/properties/v "+ + "disagree: incompatible types integer and string; chose what the first says", "names each entry's type, the chosen one's first") + assert.NotContains(t, conflicts[0].Message, "type/", "names no type ID") } func TestAllOf_PropertyAlongsideAllOfConflictMessageIsAccurate(t *testing.T) { @@ -914,13 +918,12 @@ const redeclaredModelsSpec = ` Meeting: ` // composedField returns the model the field wire of the component name composes -// to, and asserts its ID is the pointer of the declaration naming the field, the -// component's second allOf entry here, in the composed space, and that it is -// anonymous and points back at that declaration. +// to, and asserts its ID is the fold's key, /allOf/properties/, +// in the composed space, and that it is anonymous and points back at that key. func composedField(t *testing.T, doc *ir.Document, name, wire string) *ir.Model { t.Helper() property := propertyOf(t, doc, name, wire) - field := "/components/schemas/" + name + "/allOf/1/properties/" + wire + field := "/components/schemas/" + name + "/allOf/properties/" + wire want := ir.TypeID("type/composed" + field) require.Equal(t, want, property.Type.Target) model, ok := doc.Types[want].(*ir.Model) @@ -941,24 +944,24 @@ func TestAllOf_AFieldRedeclaredAsTwoModelsComposesThem(t *testing.T) { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(redeclaredModelsSpec)) assert.Empty(t, diags, "nothing is lost, so nothing is reported") - for _, tc := range []struct { + for _, testCase := range []struct { name, inline string }{ {"T", "type/anonymous/components/schemas/T/allOf/1/properties/data"}, {"U", "type/anonymous/components/schemas/U/allOf/0/properties/data"}, } { - model := composedField(t, doc, tc.name, "data") - require.NotNil(t, model.Base, tc.name) - assert.Equal(t, componentID("Meeting"), model.Base.Target, tc.name) - require.Len(t, model.Mixins, 1, tc.name) - assert.Equal(t, ir.TypeID(tc.inline), model.Mixins[0].Target, tc.name) - assert.Empty(t, model.Properties, "%s: the composition stays in source form", tc.name) - assert.Empty(t, propertyOf(t, doc, tc.name, "data").Unmodeled, "%s: nothing is kept", tc.name) - - inline, ok := doc.Types[ir.TypeID(tc.inline)].(*ir.Model) - require.True(t, ok, tc.name) - require.Len(t, inline.Properties, 1, tc.name) - assert.Equal(t, "ai", inline.Properties[0].WireName, tc.name) + model := composedField(t, doc, testCase.name, "data") + require.NotNil(t, model.Base, testCase.name) + assert.Equal(t, componentID("Meeting"), model.Base.Target, testCase.name) + require.Len(t, model.Mixins, 1, testCase.name) + assert.Equal(t, ir.TypeID(testCase.inline), model.Mixins[0].Target, testCase.name) + assert.Empty(t, model.Properties, "%s: the composition stays in source form", testCase.name) + assert.Empty(t, propertyOf(t, doc, testCase.name, "data").Unmodeled, "%s: nothing is kept", testCase.name) + + inline, ok := doc.Types[ir.TypeID(testCase.inline)].(*ir.Model) + require.True(t, ok, testCase.name) + require.Len(t, inline.Properties, 1, testCase.name) + assert.Equal(t, "ai", inline.Properties[0].WireName, testCase.name) } } @@ -990,12 +993,12 @@ func TestAllOf_AComposedFieldKeepsADiscriminatedBase(t *testing.T) { assert.Equal(t, componentID("Plain"), model.Mixins[0].Target) } -// TestAllOf_AComposedFieldElectsTheBaseAWrittenAllOfDoes pins a field declared +// TestAllOf_AComposedFieldChoosesTheBaseAWrittenAllOfDoes pins a field declared // as Plain and as a member of a hierarchy whose discriminator a union holds: one -// standing with a union on its allOf entry, or an ancestor's beside its oneOf. -// The minted model's Base is the one a written allOf of the two elects, in +// beside a union on its allOf entry, or an ancestor's beside its oneOf. +// The minted model's Base is the one a written allOf of the two chooses, in // either declaration order. -func TestAllOf_AComposedFieldElectsTheBaseAWrittenAllOfDoes(t *testing.T) { +func TestAllOf_AComposedFieldChoosesTheBaseAWrittenAllOfDoes(t *testing.T) { t.Parallel() ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } field := func(name string) string { @@ -1060,7 +1063,7 @@ func TestAllOf_EveryDistributedVariantSharesOneComposedField(t *testing.T) { - {$ref: '#/components/schemas/D'} `)) openapitest.RequireNoErrorDiags(t, diags) - const shared = ir.TypeID("type/composed/components/schemas/S/allOf/1/properties/data") + const shared = ir.TypeID("type/composed/components/schemas/S/allOf/properties/data") for _, variant := range []ir.TypeID{ "type/composed/components/schemas/S/oneOf/0", "type/composed/components/schemas/S/oneOf/1", @@ -1078,13 +1081,13 @@ func TestAllOf_EveryDistributedVariantSharesOneComposedField(t *testing.T) { assert.Equal(t, componentID("B"), body.Mixins[1].Target) } -// TestAllOf_AnAliasIsJudgedAsTheTypeItStandsFor pins the judgment through an alias +// TestAllOf_AnAliasIsJudgedAsTheTypeItNames pins the judgment through an alias // component, in either order: an alias of a model composes as that model does, // and against a kind it is the conflict that model would be. -func TestAllOf_AnAliasIsJudgedAsTheTypeItStandsFor(t *testing.T) { +func TestAllOf_AnAliasIsJudgedAsTheTypeItNames(t *testing.T) { t.Parallel() alias, other, kind := "{$ref: '#/components/schemas/Z'}", "{$ref: '#/components/schemas/B'}", "{type: string}" - for _, tc := range []struct { + for _, testCase := range []struct { first, second string mixins []ir.TypeID // nil where the pair conflicts }{ @@ -1107,17 +1110,17 @@ func TestAllOf_AnAliasIsJudgedAsTheTypeItStandsFor(t *testing.T) { allOf: - {type: object, properties: {v: %s}} - {type: object, properties: {v: %s}} -`, tc.first, tc.second))) +`, testCase.first, testCase.second))) openapitest.RequireNoErrorDiags(t, diags) - name := tc.first + " then " + tc.second - if tc.mixins == nil { + name := testCase.first + " then " + testCase.second + if testCase.mixins == nil { assert.Len(t, conflictDiags(diags), 1, name) continue } assert.Empty(t, diags, name) model := composedField(t, doc, "T", "v") require.Len(t, model.Mixins, 2, name) - assert.Equal(t, tc.mixins, []ir.TypeID{model.Mixins[0].Target, model.Mixins[1].Target}, name) + assert.Equal(t, testCase.mixins, []ir.TypeID{model.Mixins[0].Target, model.Mixins[1].Target}, name) } } @@ -1125,8 +1128,9 @@ func TestAllOf_AnAliasIsJudgedAsTheTypeItStandsFor(t *testing.T) { // no other declaration holds, in either order: a model and an alias of it, a // model and what composes it, a model and a bare object, and a bare object and // an alias of it each name one type, which is the narrower, with nothing kept -// and nothing reported. Two aliases of one model each may say more than the -// model, and two bare objects declared apart are two types, so those compose. +// and nothing reported. Two aliases of one model adding docs alone, and two +// bare objects declared apart, are one type, the one written first, the +// declaration naming the other kept and reported. func TestAllOf_ATypeHoldingAnotherTakesTheField(t *testing.T) { t.Parallel() const spec = ` A: @@ -1156,7 +1160,7 @@ func TestAllOf_ATypeHoldingAnotherTakesTheField(t *testing.T) { - {type: object, properties: {v: %s}} ` ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } - for _, tc := range []struct { + for _, testCase := range []struct { name, a, b string want ir.TypeID }{ @@ -1165,36 +1169,51 @@ func TestAllOf_ATypeHoldingAnotherTakesTheField(t *testing.T) { {"a model and a bare object", ref("A"), "{type: object}", componentID("A")}, {"a bare object and its alias", ref("Bare"), ref("MinTwo"), componentID("MinTwo")}, } { - for _, order := range [][2]string{{tc.a, tc.b}, {tc.b, tc.a}} { + for _, order := range [][2]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, order[0], order[1]))) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, diags, tc.name) + assert.Empty(t, diags, testCase.name) property := propertyOf(t, doc, "T", "v") - assert.Empty(t, property.Unmodeled, tc.name) - assert.Equal(t, tc.want, property.Type.Target, tc.name) + assert.Empty(t, property.Unmodeled, testCase.name) + assert.Equal(t, testCase.want, property.Type.Target, testCase.name) } } - // Z and Y each lend the field their own description, which the field keeps - // one of and reports the other (docs/compilers/openapi.md#ref-use-site). - for _, tc := range []struct { - pair [2]string - reports int - }{{[2]string{"Z", "Y"}, 1}, {[2]string{"Bare", "Twin"}, 0}} { - pair := tc.pair + // Z and Y, aliases of A adding a description alone, admit what A does, so + // they are one type, the one written first, and Z's declaration is kept: + // one info that the two are annotated apart, and one that each lends the + // field its own description, the later's taken, the other kept + // (docs/compilers/openapi.md#ref-use-site). + for _, pair := range [][2]string{{"Z", "Y"}, {"Y", "Z"}} { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, ref(pair[0]), ref(pair[1])))) openapitest.RequireNoErrorDiags(t, diags) - assert.Len(t, diags, tc.reports, pair[0]) - assert.Equal(t, []ir.TypeRef{{Target: componentID(pair[0])}, {Target: componentID(pair[1])}}, - composedField(t, doc, "T", "v").Mixins, pair[0]) + property := propertyOf(t, doc, "T", "v") + assert.Equal(t, componentID("Y"), property.Type.Target, "%v", pair) + at := slices.Index(pair[:], "Z") + assert.Contains(t, property.Unmodeled, fmt.Sprintf("openapi:conflicting-redeclaration/components/schemas/T/allOf/%d/properties/v", at), + "%v: the declaration naming Z is kept", pair) + require.Len(t, diags, 2, "%v", pair) + for _, diagnostic := range diags { + assert.Equal(t, diag.DegradedConstruct, diagnostic.Code, "%v", pair) + } + } + + for _, pair := range [][2]string{{"Bare", "Twin"}, {"Twin", "Bare"}} { + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, ref(pair[0]), ref(pair[1])))) + openapitest.RequireNoErrorDiags(t, diags) + property := propertyOf(t, doc, "T", "v") + assert.Equal(t, componentID("Bare"), property.Type.Target, "%v: the least", pair) + require.Len(t, diags, 1, "%v", pair) + assert.Equal(t, diag.DegradedConstruct, diags[0].Code, "%v", pair) + assert.Len(t, property.Unmodeled, 1, "%v: the declaration naming Twin is kept", pair) } } // TestAllOf_AnObjectSayingMoreThanItsTypeComposes pins what keeps a declaration -// from being taken for a bare object. A type the winner composes stays reachable -// through it, and a bare object it narrows does not, so a declaration saying -// anything else, or an alias that may, composes with a model in either order, -// and the composition reaches what it says. +// from being taken for a bare object. A type the chosen declaration composes +// stays reachable through it, and a bare object it narrows does not, so a +// declaration saying anything else, or an alias that may, composes with a model +// in either order, and the composition reaches what it says. func TestAllOf_AnObjectSayingMoreThanItsTypeComposes(t *testing.T) { t.Parallel() const spec = ` A: @@ -1215,7 +1234,7 @@ func TestAllOf_AnObjectSayingMoreThanItsTypeComposes(t *testing.T) { inline := func(entry int) ir.TypeID { return ir.TypeID(fmt.Sprintf("type/anonymous/components/schemas/T/allOf/%d/properties/v", entry)) } - for _, tc := range []struct { + for _, testCase := range []struct { name, decl string says func(entry int) ir.TypeID }{ @@ -1227,17 +1246,17 @@ func TestAllOf_AnObjectSayingMoreThanItsTypeComposes(t *testing.T) { {"an XML name", "{type: object, xml: {name: held}}", inline}, {"an example", "{type: object, example: {a: held}}", inline}, } { - for entry, order := range [][2]string{{tc.decl, model}, {model, tc.decl}} { + for entry, order := range [][2]string{{testCase.decl, model}, {model, testCase.decl}} { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, order[0], order[1]))) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, diags, tc.name) - assert.Empty(t, propertyOf(t, doc, "T", "v").Unmodeled, tc.name) + assert.Empty(t, diags, testCase.name) + assert.Empty(t, propertyOf(t, doc, "T", "v").Unmodeled, testCase.name) model := composedField(t, doc, "T", "v") parts := model.Mixins if model.Base != nil { parts = append(slices.Clip(parts), *model.Base) } - assert.ElementsMatch(t, []ir.TypeRef{{Target: componentID("A")}, {Target: tc.says(entry)}}, parts, tc.name) + assert.ElementsMatch(t, []ir.TypeRef{{Target: componentID("A")}, {Target: testCase.says(entry)}}, parts, testCase.name) } } } @@ -1252,7 +1271,7 @@ func TestAllOf_RelatedStructuresAreNotCalledAConflict(t *testing.T) { tuple := "{type: array, prefixItems: [{type: string}]}" model := "{$ref: '#/components/schemas/A'}" object := "{const: {a: x}}" - for _, tc := range []struct{ name, a, b string }{ + for _, testCase := range []struct{ name, a, b string }{ {"a list, then a tuple", list, tuple}, {"a tuple, then a list", tuple, list}, {"a model, then a const object", model, object}, @@ -1270,15 +1289,15 @@ func TestAllOf_RelatedStructuresAreNotCalledAConflict(t *testing.T) { allOf: - {type: object, properties: {v: %s}} - {type: object, properties: {v: %s}} -`, tc.a, tc.b)) +`, testCase.a, testCase.b)) doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, conflictDiags(diags), tc.name) + assert.Empty(t, conflictDiags(diags), testCase.name) merged := withCode(diags, diag.DegradedConstruct) - require.Len(t, merged, 1, tc.name) - assert.Contains(t, merged[0].Message, "that the merge does not compare", tc.name) + require.Len(t, merged, 1, testCase.name) + assert.Contains(t, merged[0].Message, "that the merge does not compare", testCase.name) assert.Contains(t, propertyOf(t, doc, "T", "v").Unmodeled, - "openapi:conflicting-redeclaration/components/schemas/T/allOf/0/properties/v", tc.name) + "openapi:conflicting-redeclaration/components/schemas/T/allOf/0/properties/v", testCase.name) } } @@ -1341,7 +1360,7 @@ func TestAllOf_ACopyOfAComponentUnderAnotherBaseStaysApart(t *testing.T) { - {type: object, properties: {x: %[1]s}} - {type: object, properties: {x: {$ref: 'https://ex.test/b/c.json#/$defs/e'}}} ` - for _, tc := range []struct { + for _, testCase := range []struct { name, schemas, not string kept bool }{ @@ -1350,20 +1369,20 @@ func TestAllOf_ACopyOfAComponentUnderAnotherBaseStaysApart(t *testing.T) { {"NamedInAnotherResource", namedInAnotherResource, "{$ref: '#n'}", true}, {"NamedInAnotherResource", namedInAnotherResource, "{const: q}", false}, } { - x := "{type: string, enum: [ab, abcdef], not: " + tc.not + "}" + x := "{type: string, enum: [ab, abcdef], not: " + testCase.not + "}" doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", - " A: {$anchor: n, type: string, maxLength: 1}\n"+fmt.Sprintf(tc.schemas, x))) + " A: {$anchor: n, type: string, maxLength: 1}\n"+fmt.Sprintf(testCase.schemas, x))) openapitest.RequireNoErrorDiags(t, diags) model, ok := typeByName(doc, "S").(*ir.Model) - require.True(t, ok, tc.name) + require.True(t, ok, testCase.name) got, ok := openapitest.PropertiesByWire(model.Properties)["x"] - require.True(t, ok, tc.name) - assert.NotContains(t, got.Type.Target, "/allOf/", "%s %s: the named schema is the type", tc.name, tc.not) + require.True(t, ok, testCase.name) + assert.NotContains(t, got.Type.Target, "/allOf/", "%s %s: the named schema is the type", testCase.name, testCase.not) _, kept := got.Unmodeled["openapi:conflicting-redeclaration/components/schemas/S/allOf/0/properties/x"] - assert.Equal(t, tc.kept, kept, "%s %s", tc.name, tc.not) - assert.Equal(t, tc.kept, + assert.Equal(t, testCase.kept, kept, "%s %s", testCase.name, testCase.not) + assert.Equal(t, testCase.kept, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/S/allOf/0/properties/x"), - "%s %s", tc.name, tc.not) + "%s %s", testCase.name, testCase.not) } } @@ -1402,7 +1421,7 @@ func TestAllOf_RedeclarationsWritingNoRelativeReferenceFoldUnderAnyBase(t *testi } // TestAllOf_AnAliasOfTheTopTypeAddsNoConjunct pins GitHub #1194 wherever the -// alias stands among the declarations: a component that is `{}` with a +// alias sits among the declarations: a component that is `{}` with a // description is the top type, so beside two models it adds no conjunct and the // field composes the models, as a bare `{}` does, with nothing kept or reported. // The description reaches the field, which a reference carries it down to. An @@ -1446,10 +1465,10 @@ func TestAllOf_AnAliasOfTheTopTypeAddsNoConjunct(t *testing.T) { // both entry orders: a schema writing `properties` and no `type` constrains // objects and admits a string, so a scalar or an array declared beside it is // the narrower, and the field takes it with nothing kept or reported. A schema -// stating `object`, directly or through its allOf, still conflicts with one, -// and so does one whose allOf cycles past what the read of its source spends, -// which keeps the verdict a structure had before that read. One holding examples -// would lose them, so the two overlap. +// stating `object`, directly or through its allOf, still conflicts with one. +// One whose allOf is a loop writing no type is such a structure too, as a loop +// admits every kind and cuts no read. One holding examples would lose them, so +// the two overlap. func TestAllOf_AStructureStatingNoTypeAdmitsEveryOtherKind(t *testing.T) { t.Parallel() const spec = ` Str: {type: string} @@ -1469,7 +1488,7 @@ func TestAllOf_AStructureStatingNoTypeAdmitsEveryOtherKind(t *testing.T) { - {properties: {f: %s}} ` ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } - for _, tc := range []struct { + for _, testCase := range []struct { narrow, untyped string want ir.TypeID }{ @@ -1478,43 +1497,43 @@ func TestAllOf_AStructureStatingNoTypeAdmitsEveryOtherKind(t *testing.T) { {ref("Int"), ref("Props"), componentID("Int")}, {ref("List"), ref("Props"), componentID("List")}, {ref("Str"), ref("PropsAlias"), componentID("Str")}, + {ref("Int"), ref("Loop"), componentID("Int")}, {"{type: string}", "{properties: {a: {type: string}}}", "type/primitive/string"}, } { - for _, order := range [][2]string{{tc.narrow, tc.untyped}, {tc.untyped, tc.narrow}} { + for _, order := range [][2]string{{testCase.narrow, testCase.untyped}, {testCase.untyped, testCase.narrow}} { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, order[0], order[1]))) openapitest.RequireNoErrorDiags(t, diags) name := order[0] + " then " + order[1] assert.Empty(t, diags, name) property := propertyOf(t, doc, "T", "f") - assert.Equal(t, tc.want, property.Type.Target, name) + assert.Equal(t, testCase.want, property.Type.Target, name) assert.Empty(t, property.Unmodeled, name) } } - for _, tc := range []struct { + for _, testCase := range []struct { other, code string }{ {ref("Obj"), diag.ConflictingRedecl}, {ref("ObjByAllOf"), diag.ConflictingRedecl}, - {ref("Loop"), diag.ConflictingRedecl}, {ref("Sampled"), diag.DegradedConstruct}, } { - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, tc.other, ref("Int")))) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, testCase.other, ref("Int")))) openapitest.RequireNoErrorDiags(t, diags) - require.Len(t, withCode(diags, tc.code), 1, tc.other) - assert.Equal(t, componentID("Int"), propertyOf(t, doc, "T", "f").Type.Target, tc.other) + require.Len(t, withCode(diags, testCase.code), 1, testCase.other) + assert.Equal(t, componentID("Int"), propertyOf(t, doc, "T", "f").Type.Target, testCase.other) } } // TestAllOf_AnUntypedReadPassingOverAKeywordKeepsTheConflict pins a structure // writing no `type` beside a string, where a schema its allOf reaches writes -// what the read of instance types does not follow but which can refuse a -// string: a union, a `not`, a condition, an `enum` or `const`, a dynamic -// reference, a keyword beside an entry's or an alias's $ref, a $ref landing on -// nothing or on `false`, or a `false` entry. -// The structure may admit no string, so the pair stays the conflict it was. A -// `true` entry, and an alias of a structure holding only docs, refuse nothing, -// so the string still narrows them. +// what can refuse a string: a union, a `not`, a condition, an `enum` or +// `const`, a keyword beside an entry's or an alias's $ref, a $ref landing on +// `false`, or a `false` entry, each read as admitting no string, keeps the +// conflict; a dynamic reference, which the read does not follow, leaves the two +// undecided. A `true` entry, an alias of docs alone and a $ref naming nothing +// refuse nothing, so the string narrows them, the last reported only as +// unresolved. func TestAllOf_AnUntypedReadPassingOverAKeywordKeepsTheConflict(t *testing.T) { t.Parallel() const spec = ` Empty: {} @@ -1542,10 +1561,18 @@ func TestAllOf_AnUntypedReadPassingOverAKeywordKeepsTheConflict(t *testing.T) { "{$ref: '#/components/schemas/Empty', type: object}", "{$ref: '#/components/schemas/Empty', allOf: [{type: object}]}", "{const: {a: x}}", "{anyOf: [{type: object}]}", "{not: {type: string}}", "{$dynamicRef: '#dyn'}", - "{$recursiveRef: '#'}", "false", ref("Missing"), ref("Refuses"), + "{$recursiveRef: '#'}", "false", ref("Refuses"), } { property, diags := compile(entry) - require.Len(t, withCode(diags, diag.ConflictingRedecl), 1, entry) + code := diag.ConflictingRedecl + if strings.Contains(entry, "Ref: '#") { + code = diag.DegradedConstruct + } + reported := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return !slices.ContainsFunc(diagnostic.Related, func(related ir.Related) bool { return related.Role == ir.RelatedChosen }) + }) + require.Len(t, reported, 1, entry) + assert.Equal(t, code, reported[0].Code, entry) assert.Equal(t, ir.TypeID("type/primitive/string"), property.Type.Target, entry) assert.Len(t, property.Unmodeled, 1, "the structure is kept: %s", entry) } @@ -1564,14 +1591,29 @@ func TestAllOf_AnUntypedReadPassingOverAKeywordKeepsTheConflict(t *testing.T) { assert.Empty(t, property.Unmodeled, entry) } + property, diags := compile(ref("Missing")) + for _, diagnostic := range diags { + if strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/T/") { + assert.Equal(t, diag.UnresolvedRef, diagnostic.Code, "the fold reports nothing: %+v", diagnostic) + } + } + assert.Equal(t, ir.TypeID("type/primitive/string"), property.Type.Target, "the string narrows a $ref naming nothing") + require.Len(t, property.Unmodeled, 1, "the $ref alone is kept: %v", property.Unmodeled) + for key, kept := range property.Unmodeled { + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason, key) + assert.Contains(t, []string{`"#/components/schemas/Missing"`, `{"$ref":"#/components/schemas/Missing"}`}, + string(kept.Value), "%s keeps the $ref and nothing the string does not read", key) + } + // A union admitting an object and an array makes the structure no model but // a use of the union, which the merge does not compare with a string. irProperty, diags := compile(ref("ObjAnyOf")) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, withCode(diags, diag.ConflictingRedecl), "a union is not compared") assert.Equal(t, ir.TypeID("type/primitive/string"), irProperty.Type.Target) - assert.Contains(t, irProperty.Unmodeled, "openapi:properties", "the structure's own keyword is kept beside the use") - assert.Len(t, irProperty.Unmodeled, 2, "and so is the union the merge did not compare") + assert.Len(t, irProperty.Unmodeled, 1, "the union the merge did not compare is kept") + assert.NotContains(t, irProperty.Unmodeled, "openapi:properties", + "the structure's own keyword goes with the declaration kept, as its type's shape does") // A oneOf and an anyOf on one entry distribute the oneOf over the structure, // as on two entries: a union, which the merge does not compare either. @@ -1593,7 +1635,7 @@ func TestAllOf_AnUntypedReadPassingOverAKeywordKeepsTheConflict(t *testing.T) { assert.Len(t, property.Unmodeled, 1, "the structure is kept: %s", entry) } - // An enum of objects is elected before the composition, as written without + // An enum of objects is chosen before the composition, as written without // the allOf: a union of literals, which the merge does not compare either. irProperty, diags = compile("{enum: [{a: x}]}") openapitest.RequireNoErrorDiags(t, diags) @@ -1692,7 +1734,7 @@ func TestAllOf_ModelsAlikeAreOneType(t *testing.T) { ` owner := "{$ref: '#/components/schemas/Owner'}" inline := "{type: object, properties: {name: {type: string}, address: {type: object, properties: {street: {type: string}}}}}" - for _, tc := range []struct { + for _, testCase := range []struct { a, b string want ir.TypeID }{ @@ -1700,11 +1742,11 @@ func TestAllOf_ModelsAlikeAreOneType(t *testing.T) { {inline, owner, componentID("Owner")}, {inline, inline, "type/anonymous/components/schemas/T/allOf/0/properties/owner"}, } { - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, tc.a, tc.b))) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, testCase.a, testCase.b))) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, diags) property := propertyOf(t, doc, "T", "owner") - assert.Equal(t, tc.want, property.Type.Target) + assert.Equal(t, testCase.want, property.Type.Target) assert.Empty(t, property.Unmodeled) } @@ -1753,7 +1795,7 @@ func TestAllOf_AModelComposesWithAMapOrAUnion(t *testing.T) { } // TestAllOf_ContainersOfDifferentModelsComposeTheirMembers pins GitHub #1180 in -// both entry orders: lists, maps or tuples of two different models stand on +// both entry orders: lists, maps or tuples of two different models sit on // one container whose member is a model composing both, each minted at a // position of its own, so both models' properties are reached, with nothing // kept or reported. @@ -1766,20 +1808,20 @@ func TestAllOf_ContainersOfDifferentModelsComposeTheirMembers(t *testing.T) { - {type: object, properties: {v: %s}} - {type: object, properties: {v: %s}} ` - field := "type/composed/components/schemas/T/allOf/1/properties/v" - for _, tc := range []struct { + field := "type/composed/components/schemas/T/allOf/properties/v" + for _, testCase := range []struct { shape string member func(ir.TypeDef) ir.TypeRef at string }{ {"{type: array, items: {$ref: '#/components/schemas/%s'}}", - func(td ir.TypeDef) ir.TypeRef { return td.(*ir.List).ElementType }, "/items"}, + func(typeDef ir.TypeDef) ir.TypeRef { return typeDef.(*ir.List).ElementType }, "/items"}, {"{type: object, additionalProperties: {$ref: '#/components/schemas/%s'}}", - func(td ir.TypeDef) ir.TypeRef { return td.(*ir.MapT).Value }, "/additionalProperties"}, + func(typeDef ir.TypeDef) ir.TypeRef { return typeDef.(*ir.MapT).Value }, "/additionalProperties"}, {"{type: array, prefixItems: [{$ref: '#/components/schemas/%s'}]}", - func(td ir.TypeDef) ir.TypeRef { return td.(*ir.Tuple).ElementTypes[0] }, "/prefixItems/0"}, + func(typeDef ir.TypeDef) ir.TypeRef { return typeDef.(*ir.Tuple).ElementTypes[0] }, "/prefixItems/0"}, } { - a, b := fmt.Sprintf(tc.shape, "A"), fmt.Sprintf(tc.shape, "B") + a, b := fmt.Sprintf(testCase.shape, "A"), fmt.Sprintf(testCase.shape, "B") for _, order := range [][2]string{{a, b}, {b, a}} { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(spec, order[0], order[1]))) openapitest.RequireNoErrorDiags(t, diags) @@ -1787,8 +1829,8 @@ func TestAllOf_ContainersOfDifferentModelsComposeTheirMembers(t *testing.T) { property := propertyOf(t, doc, "T", "v") assert.Empty(t, property.Unmodeled, order[0]) require.Equal(t, ir.TypeID(field), property.Type.Target, order[0]) - member := tc.member(doc.Types[property.Type.Target]) - require.Equal(t, ir.TypeID(field+tc.at), member.Target, order[0]) + member := testCase.member(doc.Types[property.Type.Target]) + require.Equal(t, ir.TypeID(field+testCase.at), member.Target, order[0]) model, ok := doc.Types[member.Target].(*ir.Model) require.True(t, ok, order[0]) assert.ElementsMatch(t, []ir.TypeID{componentID("A"), componentID("B")}, refTargets(model.Mixins), order[0]) @@ -1796,12 +1838,12 @@ func TestAllOf_ContainersOfDifferentModelsComposeTheirMembers(t *testing.T) { } } -// TestAllOf_AMemberBehindAnAliasIsJudgedByWhatItStandsFor pins GitHub #1365 in +// TestAllOf_AMemberBehindAnAliasIsJudgedByWhatItNames pins GitHub #1365 in // both entry orders: a list's or a map's member written as an enum or a const // beside a bound is an alias of it, judged by its members, so against a uuid no // member is, beside a container never empty, the field draws the conflict its // direct spelling draws. -func TestAllOf_AMemberBehindAnAliasIsJudgedByWhatItStandsFor(t *testing.T) { +func TestAllOf_AMemberBehindAnAliasIsJudgedByWhatItNames(t *testing.T) { t.Parallel() const components = ` E: {type: string, enum: [a, b]} C: {const: a} @@ -1834,7 +1876,7 @@ func TestAllOf_AMemberBehindAnAliasIsJudgedByWhatItStandsFor(t *testing.T) { // draws no conflict, as the same structure writing none does (GitHub #2036). func TestAllOf_ANullNotOrIfIsTheKeywordLeftOut(t *testing.T) { t.Parallel() - for _, tc := range []struct{ name, p string }{ + for _, testCase := range []struct{ name, p string }{ {"a not beside the structure", "{properties: {x: {type: string}}, not: null}"}, {"a not in its allOf", "{allOf: [{properties: {x: {type: string}}, not: null}]}"}, {"an if beside the structure", "{properties: {x: {type: string}}, if: null}"}, @@ -1842,17 +1884,17 @@ func TestAllOf_ANullNotOrIfIsTheKeywordLeftOut(t *testing.T) { } { for _, order := range [][2]string{{"A", "B"}, {"B", "A"}} { doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {p: {type: integer}}} - B: {type: object, properties: {p: `+tc.p+`}} + B: {type: object, properties: {p: `+testCase.p+`}} Plain: {type: object, properties: {p: {properties: {x: {type: string}}}}} M: {allOf: [{$ref: '#/components/schemas/`+order[0]+`'}, {$ref: '#/components/schemas/`+order[1]+`'}]} N: {allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/Plain'}]} `)) - assert.Empty(t, findingsOf(diags, diag.ConflictingRedecl), "%s, %s first", tc.name, order[0]) + assert.Empty(t, findingsOf(diags, diag.ConflictingRedecl), "%s, %s first", testCase.name, order[0]) for _, name := range []string{"M", "N"} { model, ok := typeByName(doc, name).(*ir.Model) require.True(t, ok, name) require.Len(t, model.Properties, 1, name) - assert.Equal(t, ir.TypeID("type/primitive/integer"), model.Properties[0].Type.Target, "%s: %s, %s first", name, tc.name, order[0]) + assert.Equal(t, ir.TypeID("type/primitive/integer"), model.Properties[0].Type.Target, "%s: %s, %s first", name, testCase.name, order[0]) } } } @@ -1863,7 +1905,8 @@ func TestAllOf_ANullNotOrIfIsTheKeywordLeftOut(t *testing.T) { // object beside it together, so the variant built from an array branch admits // no array, and a redeclaration as a nullable list is not read as narrower than // it, which would drop the list's null. The two stay unrelated, in either -// order, as they were before the source was read. +// order, as they were before the source was read, reported where the +// declaration that lost is written. func TestAllOf_ADistributedVariantIsReadWithItsUnion(t *testing.T) { t.Parallel() schemas := []string{ @@ -1875,9 +1918,39 @@ func TestAllOf_ADistributedVariantIsReadWithItsUnion(t *testing.T) { model, ok := typeByName(doc, "Coll").(*ir.Model) require.True(t, ok) require.Len(t, model.Properties, 1) - assert.True(t, model.Properties[0].Type.Nullable, "the list's null stands") + assert.True(t, model.Properties[0].Type.Nullable, "the list's null remains") assert.Empty(t, findingsOf(diags, diag.ConflictingRedecl)) assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, - "/components/schemas/Coll/allOf/0"), "that the merge does not compare") + "/components/schemas/Common/properties/r"), "that the merge does not compare") + } +} + +// TestAllOf_ANullableRestrictionNarrowsAPlainRedeclaration holds a member one +// entry declares as a 3.0 `{type: string, nullable: true, format: email}` and +// the other as `{type: string}`, as github.json's webhook-status commit +// committer and author declare email, to their intersection in either order: +// the email restriction, whose Base keeps its schema's null, named by a use +// admitting none, the two bits intersecting, with nothing kept or reported. +func TestAllOf_ANullableRestrictionNarrowsAPlainRedeclaration(t *testing.T) { + t.Parallel() + const ( + restriction = "{type: object, properties: {email: {type: string, nullable: true, format: email}}}" + plain = "{type: object, properties: {email: {type: string}}}" + ) + for _, entries := range [][2]string{{restriction, plain}, {plain, restriction}} { + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.0.3", " C: {allOf: ["+entries[0]+", "+entries[1]+"]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "C").(*ir.Model) + require.True(t, ok) + email := openapitest.PropertiesByWire(model.Properties)["email"] + assert.False(t, email.Type.Nullable, "the intersection admits no null") + assert.Empty(t, email.Unmodeled, "no declaration is kept") + scalar, ok := doc.Types[email.Type.Target].(*ir.Scalar) + require.True(t, ok, "the email restriction wins; got %v", email.Type.Target) + require.NotNil(t, scalar.Base) + assert.Equal(t, ir.TypeRef{Target: "type/primitive/string", Nullable: true}, *scalar.Base, "its Base keeps its schema's null") + require.NotNil(t, scalar.Encoding) + assert.Equal(t, "email", scalar.Encoding.Name, "the format is kept") + assert.Empty(t, diagsUnder(diags, "/components/schemas/C"), "nothing is reported") } } diff --git a/compilers/openapi/internal/schema/allof_disjoint.go b/compilers/openapi/internal/schema/allof_disjoint.go index 402601193..92ed0074f 100644 --- a/compilers/openapi/internal/schema/allof_disjoint.go +++ b/compilers/openapi/internal/schema/allof_disjoint.go @@ -7,36 +7,38 @@ import ( "cmp" "encoding/json/jsontext" "slices" - "strconv" "strings" yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) // conjunctAtom is one conjunct of an allOf, as a disjoint report names it: // its name below the composing schema, what it admits, and whether its read -// was cut short. Its null is the statement st's, or, for keywords read apart -// from a $ref or an allOf they stand beside, those of the schema words. +// was cut short. Its null is the statement schemaStatement's, or, for keywords +// read apart from a $ref or an allOf they sit beside, those of the schema +// keywordsSchema. // written is where the conjunct is written apart from the allOf, whose report // of admitting nothing would be its own (toldWhereWritten): what a $ref entry // lands on, or a `false` entry itself, and nil for any other. type conjunctAtom struct { - name string - admits kindSet - st *statement.Statement - words *statement.Schema - written *statement.Statement + name string + admits kindSet + schemaStatement *statement.Statement + keywordsSchema *statement.Schema + written *statement.Statement // union is the branch set of a union read as one conjunct (unionAtoms), // whose null is any branch's. union []statement.Subschema cut bool - // null marks an atom whose own read admits null, which admits holds - // apart from (electedAtom), so it admits a value whatever st reads. + // null marks an atom whose own read admits null, which admits holds apart from + // (entryAtomWithChosenUnion), so it admits a value whatever schemaStatement + // reads. null bool } @@ -45,7 +47,7 @@ const noValue = "no value" // disjointNames names what each conjunct of comp, the allOf schema writes, // states where they share no value: what their kinds leave (disjointAtoms), -// else, where those share a kind, what the election found apart +// else, where those share a kind, what the choice found apart // (conjunctsApart). func disjointNames(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) []string { if names := disjointAtoms(loweringContext, schema, conjunctAtoms(loweringContext, schema, comp)); len(names) > 0 { @@ -55,62 +57,78 @@ func disjointNames(loweringContext lowering.Ctx, schema *statement.Schema, comp } // conjunctsApart names what each conjunct of the allOf schema writes states -// where the election reads them sharing no value though their kinds share one, -// as two enums sharing no member do: a value set by its member count -// (decision.apart). A null they share (nullShared) is a value, so it names none -// there. +// where the choice reads them sharing no value though their kinds share one, +// as two enums sharing no member do (decision.apart). A null they may share is +// a value, so it names none there. func conjunctsApart(loweringContext lowering.Ctx, schema *statement.Schema) []string { names := decisionOf(loweringContext, schema).apart if len(names) == 0 { return nil } - if nullShared(loweringContext, schema) { + if nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(schema)).mayAdmit(loweringContext) { return nil } return names } -// apartNames names what each conjunct of schema, read as the election reads -// them, states where their reads share no value at all, the null included, -// joint being what they admit together: a value set by its member count, any -// other conjunct by the kinds and formats it admits, one admitting every kind -// left out, listed by what each states, so no order written orders them. It -// names none where a conjunct admits no value by itself, which its own schema -// reports where it is written, or fewer than two are named. -func apartNames(schema *statement.Schema, comp allOfComposition, conjuncts []conjunct, joint admitted) []string { - if joint.reachable() { +// apartNames names what each conjunct of schema, as the choice reads it, +// states where their reads share no value, the null included, admittedTogether +// being what they admit together (conjunctWords), one admitting every kind +// left out. It names none where a conjunct admits no value by itself, which +// its own schema reports, or fewer than two are named; at the bottom, which +// reports itself, one is enough, such a conjunct named as admitting none. +func apartNames(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, conjuncts []conjunct, admittedTogether admitted, bottom bool) []string { + if admittedTogether.reachable() { return nil } names := make([]string, 0, len(conjuncts)) - for _, cj := range conjuncts { - if !cj.read.reachable() { + for _, conjunct := range conjuncts { + name := conjunctName(schema, comp, conjunct) + word := conjunctWords(loweringContext, name, conjunct) + switch { + case conjunct.read.reachable(): + case !bottom: return nil + default: + word = noValue } - if word := readWords(cj.read); word != "" { - names = append(names, conjunctName(schema, comp, cj)+": "+word) + if word != "" { + names = append(names, name+": "+word) } } - if len(names) < 2 { + if len(names) < 2 && !bottom || len(names) == 0 { return nil } - slices.SortFunc(names, func(a, b string) int { - _, wa, _ := strings.Cut(a, ": ") - _, wb, _ := strings.Cut(b, ": ") - return cmp.Or(strings.Compare(wa, wb), strings.Compare(a, b)) - }) return names } -// conjunctName is how a disjoint report names cj, a conjunct of comp, the +// conjunctWords spells what conjunct, a conjunct of a disjoint report named +// name, states: a value set by its members, the keywords beside the allOf +// writing one being named by its keyword already, and any other read as +// readWords spells it. +func conjunctWords(loweringContext lowering.Ctx, name string, conjunct conjunct) string { + switch { + case !conjunct.read.fixed: + return readWords(conjunct.read) + case conjunct.entry != nil: + return fixedWords(loweringContext, conjunct.entry.schema, conjunct.read) + case name == "const": + return membersWords(name, []*yaml.Node{conjunct.schema.Const()}) + default: + return membersWords("enum", conjunct.schema.Enum()) + } +} + +// conjunctName is how a disjoint report names conjunct, a conjunct of comp, the // allOf s writes, as conjunctAtoms names one: the keywords beside the allOf by // the value set or the type they write, an entry by its path, a $ref written // beside other keys by its own. -func conjunctName(schema *statement.Schema, comp allOfComposition, cj conjunct) string { +func conjunctName(schema *statement.Schema, comp allOfComposition, conjunct conjunct) string { switch { - case cj.entry != nil && cj.entry.split: - return comp.entryPath(cj.entry.pointer) + "/$ref" - case cj.entry != nil: - return comp.entryPath(cj.entry.pointer) + case conjunct.entry != nil && conjunct.entry.split && comp.writesBeside(conjunct.entry.pointer): + return comp.entryPath(conjunct.entry.pointer) + "/$ref" + case conjunct.entry != nil: + return comp.entryPath(conjunct.entry.pointer) case schema.Const() != nil: return "const" case enumWritten(schema): @@ -120,27 +138,21 @@ func conjunctName(schema *statement.Schema, comp allOfComposition, cj conjunct) } } -// readWords spells what read admits for a disjoint report: a value set's -// member count, else its kinds, null aside, with the formats it is held to, -// and nothing for a read admitting every kind and held to none. +// readWords spells what read, no value set, admits for a disjoint report: its +// kinds, null aside, with the formats it is held to, and nothing for a read +// admitting every kind and held to none. func readWords(read admitted) string { - if read.fixed { - if n := read.size(); n != 1 { - return strconv.Itoa(n) + " values" - } - return "1 value" - } formats := make([]string, 0, len(read.forms)) for _, scalarForm := range read.forms { formats = append(formats, scalarForm.spelled) } kinds := read.kinds &^ kindNull switch { - case len(formats) == 0 && kinds == anyInstance: + case len(formats) == 0 && kinds == everyKindButNull: return "" case len(formats) == 0: return instanceWords(kinds) - case kinds == anyInstance: + case kinds == everyKindButNull: return "format " + strings.Join(formats, ", ") default: return instanceWords(kinds) + " of format " + strings.Join(formats, ", ") @@ -149,56 +161,79 @@ func readWords(read admitted) string { // contradictionShape describes what the refinement refinementValue of schema, // whose conjuncts share no value, lowered as, for diagDisjointConjuncts: the -// value set elected before them, else the union an inline principal writes, -// else what the keywords beside the allOf write, a family or a type, else the -// top type, where they write neither. +// closed empty Enum of sets sharing no member, else the value set chosen +// before them, else what the keywords beside the allOf write, a family or a +// type, else the top type, where they write neither. No union is the principal +// of conjuncts sharing no value: decideRefinement reads them so only where none +// is (unionPrincipal). func contradictionShape(refinementValue refinement, schema *statement.Schema) string { - if won := electedSet(refinementValue, schema); won != "" { - return "the " + won + " it lowered as" + if refinementValue.sharesNoMember { + // The set chosen lowers to the closed empty Enum, a const among them. + return "a closed enum with no member" } - if refinementValue.principal != nil && refinementValue.principal.schema.Ref == nil && declaresUnion(refinementValue.principal.schema.Schema) { - return unionShape + if chosenSet := chosenSetKeyword(refinementValue, schema); chosenSet != "" { + return "its " + chosenSet } - if kinds := declaredInstanceTypes(schema); kinds != anyInstance { - return "the " + instanceWords(kinds) + " it lowered as" + if kinds := declaredInstanceTypes(schema); kinds != everyKindButNull { + return "the " + instanceWords(kinds) + " its type names" + } + return "the top type" +} + +// builtShape names what a position choosing no allOf entry lowered as, for +// diagDisjointConjuncts: target, the reference it lowered to, where that is a +// primitive, the top type for any, and else positionNode, the node it built and +// target names, by its kind (nodeShape). +func builtShape(positionNode ir.TypeDef, target ir.TypeID) string { + primitive, isPrimitive := strings.CutPrefix(string(target), string(ir.PrimitiveTypeID(""))) + switch { + case !isPrimitive: + return nodeShape(positionNode.Kind()) + case ir.PrimitiveKind(primitive) == ir.PrimitiveAny: + return "the top type" + default: + return primitiveNoun(ir.PrimitiveKind(primitive)) } - return "the top type it lowered as" } // disjointAtoms names what each of atoms, the conjuncts of the allOf schema // writes, admits where they share no value, and returns nil where they share -// one (docs/compilers/openapi.md#allof-disjoint-conjuncts), a null among them -// where every conjunct may admit it (nullShared). A read cut short decides nothing, -// and a conjunct admitting nothing whose schema reports it where it is written -// leaves the report to it. One conjunct contradicts nothing, so a lone -// `type: "null"` beside what takes its null away draws nil too, but one -// admitting nothing by itself is named, as nothing else reports it. +// one (docs/compilers/openapi.md#allof-disjoint-conjuncts), a null every +// conjunct may admit among them. A read cut short decides nothing. A conjunct +// admitting nothing whose schema reports it where it is written leaves the +// report to it, but at the bottom, schema's own lowering. One conjunct +// contradicts nothing, so a lone `type: "null"` beside what takes its null +// away draws nil too, but one admitting nothing by itself is named. func disjointAtoms(loweringContext lowering.Ctx, schema *statement.Schema, atoms []conjunctAtom) []string { - joint := anyInstance - for _, a := range atoms { - if a.cut { + kindsTogether := everyKindButNull + for _, atom := range atoms { + if atom.cut { return nil } - joint &= a.admits + kindsTogether &= atom.admits } - if joint != 0 { + if kindsTogether != 0 { return nil } - if nullShared(loweringContext, schema) { + if nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(schema)).mayAdmit(loweringContext) { return nil } var names []string - void := false - for _, a := range atoms { + // A false entry leaves the composition no value, as the bottom does, so + // the position reports itself beside the entry's own report. + void, bottom := false, bottomAt(loweringContext, schema) || slices.ContainsFunc(atoms, func(atom conjunctAtom) bool { + return atom.written != nil && atom.written.Truth.ReadsFalse() + }) + for _, atom := range atoms { switch { - case !empty(loweringContext, a): - if a.admits != anyInstance { - names = append(names, a.name+": "+instanceWords(a.admits)) + case !admitsNoValue(loweringContext, atom): + if atom.admits != everyKindButNull { + names = append(names, atom.name+": "+atomWords(loweringContext, atom)) } - case a.written != nil && toldWhereWritten(loweringContext, a.written): + case !bottom && atom.written != nil && toldWhereWritten(loweringContext, atom.written): return nil default: - names, void = append(names, a.name+": "+noValue), true + names, void = append(names, atom.name+": "+noValue), true } } if len(names) < 2 && !void { @@ -209,44 +244,42 @@ func disjointAtoms(loweringContext lowering.Ctx, schema *statement.Schema, atoms // conjunctAtoms returns the conjuncts of comp, in order: the `type` s writes // beside it, the value set it writes there (valueSetAtom), each union s writes -// beside it that shares no kind with the rest (unionAside) or declares no +// beside it that shares no kind with the rest (unionLeavesNoBranch) or declares no // shape, else the one it passes over (passedOver), and each flattened entry: // a wrapper by its own `type`, an entry nested past statement.MaxFlattenDepth -// as cut, an inline entry writing two unions as the one it elects and the +// as cut, an inline entry writing two unions as the one it chooses and the // other, and a $ref entry writing keywords that narrow what it admits as the // reference and the keywords beside it. func conjunctAtoms(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) []conjunctAtom { out := make([]conjunctAtom, 0, 4+len(comp.entries)) - out = append(out, conjunctAtom{name: "type", admits: declaredInstanceTypes(schema), words: schema}) - if set, ok := valueSetAtom(loweringContext, schema); ok { - out = append(out, set) + out = append(out, conjunctAtom{name: "type", admits: declaredInstanceTypes(schema), keywordsSchema: schema}) + if atom, ok := valueSetAtom(loweringContext, schema); ok { + out = append(out, atom) } - if unionAside(loweringContext, schema) || declaresUnion(schema) && !unionBranchesDeclareShape(loweringContext, schema) { - choice := schema.ChoiceKeywords() - out = append(out, unionAtoms(loweringContext, "oneOf", choice.OneOf)...) - out = append(out, unionAtoms(loweringContext, "anyOf", choice.AnyOf)...) - } else if passed, key := passedOver(loweringContext, schema, schema); passed != nil { - out = append(out, unionAtoms(loweringContext, key, passed)...) + if readLoweredUnion(loweringContext, schema).besideRest == unionLeavesNoBranch || declaresUnion(schema) && !unionBranchesDeclareShape(loweringContext, schema) { + out = append(out, writtenUnionAtoms(loweringContext, "", schema)...) + } else if passed, ok := passedOver(loweringContext, schema, schema); ok { + out = append(out, unionAtoms(loweringContext, string(passed), passed.branchesOf(schema))...) } for _, entry := range comp.entries { name := comp.entryPath(entry.pointer) - admission := admissionOf(loweringContext, entry.schema) + admission := composedEntryAdmission(loweringContext, schema, entry.schema) ref, _ := declaredOf(loweringContext, entry.schema) - passed, key := passedOver(loweringContext, schema, entry.schema.Schema) + passed, passes := passedOver(loweringContext, schema, entry.schema.Schema) switch { case entry.wrapper: - out = append(out, conjunctAtom{name: name, admits: declaredInstanceTypes(entry.schema.Schema), words: entry.schema.Schema}) - case entry.split: - out = append(out, conjunctAtom{name: name + "/$ref", admits: admission.admits, st: entry.schema, cut: admission.cut, written: ref}) - case passed != nil && entry.schema.Ref == nil: - out = append(out, electedAtom(loweringContext, schema, entry, name, ref)) - out = append(out, unionAtoms(loweringContext, name+"/"+key, passed)...) + out = append(out, conjunctAtom{name: name, admits: declaredInstanceTypes(entry.schema.Schema), keywordsSchema: entry.schema.Schema}) + case entry.split && comp.writesBeside(entry.pointer): + out = append(out, conjunctAtom{name: name + "/$ref", admits: admission.admits, schemaStatement: entry.schema, written: ref}) + case passes && entry.schema.Ref == nil: + out = append(out, entryAtomWithChosenUnion(loweringContext, schema, entry, name, ref)) + out = append(out, unionAtoms(loweringContext, joinedPath(name, string(passed)), passed.branchesOf(entry.schema.Schema))...) default: - a := conjunctAtom{name: name, admits: admission.admits, st: entry.schema, cut: admission.cut || entry.capped, written: ref} + atom := conjunctAtom{name: name, admits: admission.admits, schemaStatement: entry.schema, cut: entry.capped, written: ref} if entry.schema.Truth.ReadsFalse() { - a.written = entry.schema + atom.written = entry.schema } - out = append(out, a) + out = append(out, atom) } } return out @@ -257,26 +290,24 @@ func conjunctAtoms(loweringContext lowering.Ctx, schema *statement.Schema, comp // leave it no kind, which is read as the same keywords beside the allOf are: // its `type`, its set and each union it writes, a set holding no value its own // type admits saying so where it is written (valueSetAtom), as the dispatch of -// competing keywords lowers it there (setElected). +// competing keywords lowers it there (chosenSetConjunct). func refinedAtoms(loweringContext lowering.Ctx, schema *statement.Schema, refinementValue refinement) []conjunctAtom { atoms := conjunctAtoms(loweringContext, schema, refinementValue.comp) entry, ok := valueSetPrincipal(refinementValue) if !ok { return atoms } - at := slices.IndexFunc(atoms, func(a conjunctAtom) bool { return a.st == entry.schema }) + at := slices.IndexFunc(atoms, func(atom conjunctAtom) bool { return atom.schemaStatement == entry.schema }) if at < 0 || atoms[at].admits != 0 { return atoms } - name, bs := atoms[at].name, entry.schema.Schema - own := []conjunctAtom{{name: name + "/type", admits: declaredInstanceTypes(bs), words: bs}} - if set, written := valueSetAtom(loweringContext, bs); written { - set.name = name + "/" + set.name - own = append(own, set) + name, entrySchema := atoms[at].name, entry.schema.Schema + own := []conjunctAtom{{name: name + "/type", admits: declaredInstanceTypes(entrySchema), keywordsSchema: entrySchema}} + if atom, written := valueSetAtom(loweringContext, entrySchema); written { + atom.name = name + "/" + atom.name + own = append(own, atom) } - choice := bs.ChoiceKeywords() - own = append(own, unionAtoms(loweringContext, name+"/oneOf", choice.OneOf)...) - own = append(own, unionAtoms(loweringContext, name+"/anyOf", choice.AnyOf)...) + own = append(own, writtenUnionAtoms(loweringContext, name, entrySchema)...) return slices.Concat(atoms[:at], own, atoms[at+1:]) } @@ -297,37 +328,34 @@ func valueSetAtom(loweringContext lowering.Ctx, schema *statement.Schema) (conju return conjunctAtom{}, false } unread := memberSetOf(loweringContext, valueSetOf{schema, name}, members).unread - return conjunctAtom{name: name, admits: valueKinds(loweringContext, schema), words: schema, written: loweringContext.Statements().Read(schema), cut: unread}, true + return conjunctAtom{name: name, admits: valueKinds(loweringContext, schema), keywordsSchema: schema, written: loweringContext.Statements().Read(schema), cut: unread}, true } -// toldWhereWritten reports whether st, written apart from the allOf naming it -// and admitting no value, says so where it is written, so the allOf need not: -// it reads as `false` (docs/compilers/openapi.md#allof-false-branch), its -// value set holds no value its own type admits (docs/compilers/openapi.md#enum-const), -// its allOf's conjuncts share no kind, which this report reads at it, no -// branch of a union beside its object body lives (keepsDeadUnion), or a union -// shares no kind with a body that is no Model (keepsUnionApartFromBody). A $ref -// to a schema admitting no value is read through, up to maxAdmissionReads -// hops; nothing else is reported elsewhere. -func toldWhereWritten(loweringContext lowering.Ctx, st *statement.Statement) bool { - for range maxAdmissionReads { +// toldWhereWritten reports whether schemaStatement, written apart from the +// allOf naming it and admitting no value, says so where it is written, so the +// allOf need not: it reads as `false` +// (docs/compilers/openapi.md#allof-false-branch), its value set holds no value +// its own type admits (docs/compilers/openapi.md#enum-const), its allOf's +// conjuncts share no kind, or no branch of a union beside its body lives +// (keepsDeadUnion), read through $refs each admitting no value (refChain). +func toldWhereWritten(loweringContext lowering.Ctx, schemaStatement *statement.Statement) bool { + for step := range refChain(loweringContext, schemaStatement) { + written := step.statement + if step.from != nil && (written == nil || !admitsNoValue(loweringContext, conjunctAtom{admits: admissionOf(loweringContext, written).admits, schemaStatement: written})) { + break + } switch { - case st.Truth.ReadsFalse(): + case written.Truth.ReadsFalse(): return true - case st.Truth != statement.Stated: + case written.Truth != statement.Stated: return false - case (enumWritten(st.Schema) || st.Const() != nil) && declaredInstanceTypes(st.Schema)&valueKinds(loweringContext, st.Schema) == 0: + case (enumWritten(written.Schema) || written.Const() != nil) && declaredInstanceTypes(written.Schema)&valueKinds(loweringContext, written.Schema) == 0: return true - case st.Ref == nil && len(st.AllOf) > 0: - return conjunctsShareNothing(loweringContext, st.Schema) - case st.Ref == nil && (keepsDeadUnion(loweringContext, st.Schema) || keepsUnionApartFromBody(loweringContext, st.Schema)): - return true - } - next, _ := declaredOf(loweringContext, st) - if next == nil || !empty(loweringContext, conjunctAtom{admits: admissionOf(loweringContext, next).admits, st: next}) { - return false + case written.Ref == nil && len(written.AllOf) > 0: + return conjunctsShareNothing(loweringContext, written.Schema) + case written.Ref == nil: + return keepsDeadUnion(loweringContext, written.Schema) } - st = next } return false } @@ -338,24 +366,35 @@ func toldWhereWritten(loweringContext lowering.Ctx, st *statement.Statement) boo // nothing. func conjunctsShareNothing(loweringContext lowering.Ctx, schema *statement.Schema) bool { at, _ := siteOf(schema) - joint := anyInstance - for _, a := range conjunctAtoms(loweringContext, schema, allOfEntries(loweringContext, schema, at.Pointer)) { - joint &= a.admits + kindsTogether := everyKindButNull + for _, atom := range conjunctAtoms(loweringContext, schema, allOfEntries(loweringContext, schema, at.Pointer)) { + kindsTogether &= atom.admits } - return joint == 0 + return kindsTogether == 0 } -// electedAtom is the inline entry allOfEntryValue of schema's allOf, named -// name, writing two unions, as a conjunct beside the one it passes over: its -// own keywords and the union it elects. -func electedAtom(loweringContext lowering.Ctx, schema *statement.Schema, allOfEntryValue allOfEntry, name string, ref *statement.Statement) conjunctAtom { +// entryAtomWithChosenUnion is the inline entry allOfEntryValue of schema's +// allOf, named name, writing two unions, as a conjunct beside the one it passes +// over: its own keywords and the union it chooses. +func entryAtomWithChosenUnion(loweringContext lowering.Ctx, schema *statement.Schema, allOfEntryValue allOfEntry, name string, ref *statement.Statement) conjunctAtom { admissionReader := newAdmissionReader(loweringContext) - elected, _, _ := unionBranches(loweringContext, schema, allOfEntryValue.schema.Schema) - read := admissionReader.written(allOfEntryValue.schema.Schema, admissionReader.nullable).and(admissionReader.union(elected)) - return conjunctAtom{name: name, admits: read.kinds &^ kindNull, null: read.kinds&kindNull != 0, st: allOfEntryValue.schema, + chosenBranches := loweredKeyword(loweringContext, schema, allOfEntryValue.schema.Schema).branchesOf(allOfEntryValue.schema.Schema) + read := admissionReader.written(allOfEntryValue.schema.Schema, admissionReader.nullable).and(admissionReader.union(chosenBranches)) + return conjunctAtom{name: name, admits: read.kinds &^ kindNull, null: read.kinds&kindNull != 0, schemaStatement: allOfEntryValue.schema, cut: admissionReader.incomplete() || allOfEntryValue.capped, written: ref} } +// writtenUnionAtoms returns the atoms of the oneOf and the anyOf schema +// writes, in that order, each named by its path from the position below path +// (unionAtoms). +func writtenUnionAtoms(loweringContext lowering.Ctx, path string, schema *statement.Schema) []conjunctAtom { + out := make([]conjunctAtom, 0, len(unionKeywords)) + for _, union := range unionKeywords { + out = append(out, unionAtoms(loweringContext, joinedPath(path, string(union)), union.branchesOf(schema))...) + } + return out +} + // unionAtoms returns the union keyword names, written beside an allOf with // branches, as one conjunct admitting what any branch does, and none where it // writes none. @@ -364,198 +403,211 @@ func unionAtoms(loweringContext lowering.Ctx, keyword string, branches []stateme return nil } atom := conjunctAtom{name: keyword, union: branches} - for _, b := range branches { - admission := admissionOf(loweringContext, loweringContext.Statements().Subschema(b)) + for _, branch := range branches { + admission := admissionOf(loweringContext, loweringContext.Statements().Subschema(branch)) atom.admits |= admission.admits - atom.cut = atom.cut || admission.cut } return []conjunctAtom{atom} } -// nullShared reports whether the conjuncts of the allOf schema writes may share -// a null: each may admit it wherever the IR holds it, as mayAdmitNull reads it, -// so one keeping it out, a union none of whose branches admits it among them, -// leaves none to share. Where the read passes the walk's budget, which -// conjuncts it reached would follow their order, so each is read on its own: -// one that keeps null out within its own budget decides, and otherwise they -// share it. -func nullShared(loweringContext lowering.Ctx, schema *statement.Schema) bool { - nullsValue := newNulls(loweringContext) - nullsValue.variants = true - if nullReading := nullsValue.conjunct(loweringContext.Statements().Read(schema), nullSite{}); !nullsValue.conjuncts.Exhausted() { - return nullReading.admits(loweringContext) - } - keepsOut := func(read func(otherNulls *nulls) nullReading) bool { - anotherNulls := newNulls(loweringContext) - anotherNulls.variants = true - return read(&anotherNulls).forbids(loweringContext) && !anotherNulls.conjuncts.Exhausted() - } - if keepsOut(func(otherNulls *nulls) nullReading { return otherNulls.own(schema) }) { - return false - } - return !slices.ContainsFunc(conjunctsIn(loweringContext, schema), func(b *statement.Statement) bool { - return keepsOut(func(otherNulls *nulls) nullReading { return otherNulls.conjunct(b, nullSite{}) }) - }) -} - -// empty reports whether a admits no value by itself, the null included as -// nulls reads it, which makes it its own schema's to report rather than the -// allOf's. -func empty(loweringContext lowering.Ctx, a conjunctAtom) bool { - if a.admits != 0 || a.null { +// admitsNoValue reports whether atom admits no value by itself, the null +// included as nulls reads it, which makes it its own schema's to report rather +// than the allOf's. +func admitsNoValue(loweringContext lowering.Ctx, atom conjunctAtom) bool { + if atom.admits != 0 || atom.null { return false } switch { - case a.st != nil: - return !mayAdmitNull(loweringContext, a.st, nil) - case a.union != nil: - return !slices.ContainsFunc(a.union, func(b statement.Subschema) bool { - return mayAdmitNull(loweringContext, loweringContext.Statements().Subschema(b), nil) + case atom.schemaStatement != nil: + return !nullAnswerReadingsOf(loweringContext, atom.schemaStatement).mayAdmit(loweringContext) + case atom.union != nil: + return !slices.ContainsFunc(atom.union, func(branch statement.Subschema) bool { + return nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Subschema(branch)).mayAdmit(loweringContext) }) default: - return typeNullVerdict(a.words) != nullAdmitted + return typeNullAnswer(atom.keywordsSchema) != nullAdmittedByReference } } // diagDisjointConjuncts is the one report an allOf whose conjuncts share no -// value draws, at the schema that writes them, which lowered to shape: a -// composition, or the value set an election passed it over for. -func diagDisjointConjuncts(loweringContext lowering.Ctx, comp allOfComposition, shape string) []ir.Diagnostic { +// value draws, at schema, which writes them and lowered as shape: what it +// names the conjuncts of (disjointSubject), each with what it states, what +// schema lowered as and the unions it keeps (keptDeadUnions), and that one of +// them is to be removed or corrected. +func diagDisjointConjuncts(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, shape string) []ir.Diagnostic { if len(comp.disjoint) == 0 { return nil } - return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, comp.pointer, - "the conjuncts of %s share no value (%s), so no instance satisfies this schema, which %s cannot state", - comp.subject(), strings.Join(comp.disjoint, ", "), shape)} + names := slices.Clone(comp.disjoint) + slices.SortStableFunc(names, compareConjunctNames) + subject, one := disjointSubject(names) + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, comp.pointer, + "no value satisfies %s (%s); lowered as %s%s — remove or correct %s", + subject, strings.Join(names, ", "), shape, keptDeadUnions(loweringContext, schema), one)} } -// composedShape is the shape a composition lowers to, for diagDisjointConjuncts. -const composedShape = "a composition" +// disjointSubject is what a disjoint report naming names says no value +// satisfies, and which of them to correct: each keyword beside the allOf it +// names, then every allOf entry where it names one, and one entry where it +// names entries alone, one of them otherwise. +func disjointSubject(names []string) (string, string) { + var items []string + entries := false + for _, name := range names { + path, _, _ := strings.Cut(name, ": ") + switch { + case strings.HasPrefix(path, "allOf/"): + entries = true + case !slices.Contains(items, "the "+path): + items = append(items, "the "+path) + } + } + one := "one of them" + if entries { + if len(items) == 0 { + one = "one entry" + } + items = append(items, "every allOf entry") + } + switch len(items) { + case 1: + return items[0], one + case 2: + return "both " + items[0] + " and " + items[1], one + default: + return strings.Join(items[:len(items)-1], ", ") + " and " + items[len(items)-1] + " together", one + } +} + +// composedShape is the shape a composition lowers to, for diagDisjointConjuncts, +// as nodeShape names a Model. +const composedShape = `a node of kind "model"` + +// bottomShape is the shape conjuncts sharing no kind lower to, for +// diagDisjointConjuncts. +const bottomShape = "the closed model with no member a false schema lowers to" -// unionShape is the shape a position lowering to the union it elects of two -// standing alone lowers to, for diagDisjointConjuncts. -const unionShape = "the union it lowered as" +// unionShape is the shape schema, a position lowering to the union its +// conjunction chooses of two, lowers to, for diagDisjointConjuncts: that union, +// by its path from the position. +func unionShape(loweringContext lowering.Ctx, schema *statement.Schema) string { + loweredUnion, _ := readConjunction(loweringContext, schema).loweredUnion() + return "its " + strings.TrimPrefix(string(loweredUnion.rel)+"/"+string(loweredUnion.keyword), "/") +} // diagUnionsShareNothing is the warning schema, written at pointer and writing -// a oneOf and an anyOf, draws where the two share no value (pairApart), a null -// only where both may admit it, as the same two on its allOf's entries draw +// a oneOf and an anyOf, draws where the two share no value (pairReadingOf), a +// null only where both may admit it, as the same two on its allOf's entries draw // (docs/compilers/openapi.md#allof-disjoint-conjuncts): each named by its // keyword, and the position lowered as shape. func diagUnionsShareNothing(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, shape string) []ir.Diagnostic { comp := allOfComposition{pointer: pointer} - comp.disjoint = pairApart(loweringContext, schema) - return diagDisjointConjuncts(loweringContext, comp, shape) + comp.disjoint = pairReadingOf(loweringContext, schema).apart + return diagDisjointConjuncts(loweringContext, schema, comp, shape) } -// keywordRank orders the keywords a disjoint report names a conjunct by: the -// type, the oneOf, then the anyOf. -var keywordRank = map[string]int{"type": 0, "oneOf": 1, "anyOf": 2} +// keywordRank orders the keywords a disjoint report names a conjunct by: an +// entry itself, then the type, the value set, the $ref, the oneOf and the +// anyOf it writes. +var keywordRank = map[string]int{"": -1, "type": 0, "enum": 1, "const": 1, "$ref": 2, string(oneOfKeyword): 3, string(anyOfKeyword): 4} // compareConjunctNames orders two names of a disjoint report as every report -// lists them: the keywords beside the allOf by keywordRank, then each entry -// by its path, its own keywords in the same order. +// lists them: by where each is written (provenance.ComparePointers), the +// keywords beside the allOf, which have no path, first, and an entry before +// its own keywords, the keywords of one schema by keywordRank. func compareConjunctNames(a, b string) int { - pa, _, _ := strings.Cut(a, ": ") - pb, _, _ := strings.Cut(b, ": ") - da, ka := splitConjunctName(pa) - db, kb := splitConjunctName(pb) - if da != db { - // The keywords beside the allOf have no path, which sorts first. - return strings.Compare(da, db) - } - return cmp.Compare(keywordRank[ka], keywordRank[kb]) + pathA, _, _ := strings.Cut(a, ": ") + pathB, _, _ := strings.Cut(b, ": ") + pointerA, keywordA := splitConjunctName(pathA) + pointerB, keywordB := splitConjunctName(pathB) + if pointerA != pointerB { + return provenance.ComparePointers(jsontext.Pointer("/"+pointerA), jsontext.Pointer("/"+pointerB)) + } + return cmp.Compare(keywordRank[keywordA], keywordRank[keywordB]) } -// splitConjunctName is the entry path and the keyword of name. +// splitConjunctName is the path of the schema name is written on and the +// keyword it names there, empty where name is a whole entry's path. func splitConjunctName(name string) (string, string) { - if path, keyword, ok := strings.CutLast(name, "/"); ok { + path, keyword, ok := strings.CutLast(name, "/") + switch { + case !ok: + return "", name + case keywordRank[keyword] > 0 || keyword == "type": return path, keyword + default: + return name, "" } - return "", name } -// pairApartOf keys what pairApart read of a position. -type pairApartOf struct{ s *statement.Schema } - -// pairApart names the oneOf and the anyOf written for the position schema, -// beside its allOf or on its inline entries at any depth, where they share no -// value as an admissionReader reads them, value sets included and a null only -// where both admit it: each by where it is written and what it admits, nothing -// being noValue, in the order every report names them (compareConjunctNames). -// It is nil where they share one, the read is cut short, or no pair is written. -// Read once a run, so every spelling reads one answer -// (docs/compilers/openapi.md#competing-keywords). -func pairApart(loweringContext lowering.Ctx, schema *statement.Schema) []string { - return pairReadingOf(loweringContext, schema).apart -} - -// pairNullAlone reports whether the oneOf and the anyOf written for the -// position schema, read as pairApart reads them, admit null and nothing else -// together, neither admitting null alone by itself. -func pairNullAlone(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return pairReadingOf(loweringContext, schema).nullAlone -} +// pairApartKey keys what pairReadingOf read of a position. +type pairApartKey struct{ schema *statement.Schema } -// pairReading is what a position's oneOf and anyOf admit together: named +// unionPairReading is what a position's oneOf and anyOf admit together: named // apart where nothing, and whether null alone. -type pairReading struct { +type unionPairReading struct { apart []string nullAlone bool } -// pairReadingOf reads the pair pairApart describes, once a run. -func pairReadingOf(loweringContext lowering.Ctx, schema *statement.Schema) pairReading { - return lowering.ReadOncePerRun(loweringContext, pairApartOf{schema}, func() pairReading { +// pairReadingOf reads the oneOf and the anyOf written for the position schema, +// beside its allOf or on its inline entries at any depth, once a run, so every +// spelling reads one answer (docs/compilers/openapi.md#competing-keywords). +// apart names them where they share no value as an admissionReader reads them, +// value sets included and a null only where both admit it: each by where it is +// written and what it admits, nothing being noValue, in the order every report +// names them (compareConjunctNames). It is nil where they share one, the read +// is cut short, or no pair is written. +func pairReadingOf(loweringContext lowering.Ctx, schema *statement.Schema) unionPairReading { + return lowering.ReadOncePerRun(loweringContext, pairApartKey{schema}, func() unionPairReading { comp := allOfEntries(loweringContext, schema, "") if !writesUnionPair(schema, comp) { - return pairReading{} + return unionPairReading{} } admissionReader := newAdmissionReader(loweringContext) - admissionReader.nullable = definesNullableAt(loweringContext, loweringContext.Statements().Read(schema)) - pairReadsValue := pairReads{joint: admitted{kinds: kindAny}} - pairReadsValue.read(&admissionReader, "", schema) + admissionReader.nullable = definesNullableFor(loweringContext, schema) + tally := unionPairTally{admittedTogether: admitted{kinds: kindAny}} + tally.read(&admissionReader, "", schema) for _, entry := range comp.entries { if entry.schema.Ref == nil && declaresUnion(entry.schema.Schema) { - pairReadsValue.read(&admissionReader, comp.entryPath(entry.pointer), entry.schema.Schema) + tally.read(&admissionReader, comp.entryPath(entry.pointer), entry.schema.Schema) } } if admissionReader.incomplete() { - return pairReading{} + return unionPairReading{} } - if pairReadsValue.joint.reachable() || len(pairReadsValue.names) < 2 { - return pairReading{nullAlone: pairReadsValue.joint.reachable() && pairReadsValue.joint.kinds == kindNull && !pairReadsValue.nullUnion} + if tally.admittedTogether.reachable() || len(tally.names) < 2 { + return unionPairReading{nullAlone: tally.admittedTogether.reachable() && tally.admittedTogether.kinds == kindNull && !tally.nullUnion} } - slices.SortFunc(pairReadsValue.names, compareConjunctNames) - return pairReading{apart: pairReadsValue.names} + slices.SortFunc(tally.names, compareConjunctNames) + return unionPairReading{apart: tally.names} }) } -// pairReads is what pairApart has read of a position's unions: what they +// unionPairTally is what pairReadingOf has read of a position's unions: what they // admit together, each named by what it admits, and whether one admits null // alone. -type pairReads struct { - joint admitted - names []string - nullUnion bool +type unionPairTally struct { + admittedTogether admitted + names []string + nullUnion bool } // read adds the oneOf and the anyOf schema writes, at the path at from the // position, as admissionReaderValue reads each. -func (p *pairReads) read(admissionReaderValue *admissionReader, at string, schema *statement.Schema) { - choice := schema.ChoiceKeywords() - for key, branches := range map[string][]statement.Subschema{"oneOf": choice.OneOf, "anyOf": choice.AnyOf} { +func (tally *unionPairTally) read(admissionReaderValue *admissionReader, at string, schema *statement.Schema) { + for _, union := range unionKeywords { + branches := union.branchesOf(schema) if len(branches) == 0 { continue } read := admissionReaderValue.union(branches) - p.joint = p.joint.and(read) - p.nullUnion = p.nullUnion || read.reachable() && read.kinds == kindNull - word := readWords(read) - if !read.reachable() { - word = noValue - } - if word != "" { - p.names = append(p.names, strings.TrimPrefix(at+"/"+key, "/")+": "+word) + tally.admittedTogether = tally.admittedTogether.and(read) + tally.nullUnion = tally.nullUnion || read.reachable() && read.kinds == kindNull + // A union admitting no value leaves every branch of the other dead, + // so no union read here is one (readLoweredUnion). + if word := unionWords(admissionReaderValue.loweringContext, branches, read); word != "" { + tally.names = append(tally.names, strings.TrimPrefix(at+"/"+string(union), "/")+": "+word) } } } diff --git a/compilers/openapi/internal/schema/allof_disjoint_entry_test.go b/compilers/openapi/internal/schema/allof_disjoint_entry_test.go index 8b18677f0..3e13c83cd 100644 --- a/compilers/openapi/internal/schema/allof_disjoint_entry_test.go +++ b/compilers/openapi/internal/schema/allof_disjoint_entry_test.go @@ -16,30 +16,33 @@ import ( // report of an allOf whose inline entry writes a value set its keywords leave // no kind, which the position lowers as: the entry's type, its set and each // union it writes are each a conjunct, as beside the allOf, so a set saying -// where it is written that it holds no value draws no report, while an entry -// the position does not lower as is named "no value". +// where it is written that it holds no value draws no report. A const and an +// enum of two value types on one entry are the bottom, named as admitting no +// value. An empty enum on an entry is chosen as beside the allOf, drawing +// only its own warning. func TestAllOf_AnEntryLoweringAsItsValueSetIsReadAsBesideTheAllOf(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, s, want string }{ {"a const outside its type", `{allOf: [` + refString + `, {type: integer, const: z}]}`, - "allOf/0: string, allOf/1/type: integer, allOf/1/const: string)"}, + `allOf/0: string, allOf/1/type: integer, allOf/1/const: "z")`}, {"a const beside a union of another kind", `{allOf: [{$ref: '#/components/schemas/U'}, {const: 1, oneOf: [{type: string}, {type: boolean}]}]}`, - "allOf/1/const: integer, allOf/1/oneOf: string or boolean)"}, - {"a const and an enum of two kinds", `{allOf: [{$ref: '#/components/schemas/U'}, {const: 1, enum: [a]}]}`, ""}, - {"an empty enum, which nothing elects", `{allOf: [` + refString + `, {enum: []}]}`, "allOf/1: no value)"}, + "allOf/1/const: 1, allOf/1/oneOf: string or boolean)"}, + {"a const and an enum of two kinds", `{allOf: [{$ref: '#/components/schemas/U'}, {const: 1, enum: [a]}]}`, + "allOf/1: no value)"}, + {"an empty enum, chosen as beside the allOf", `{allOf: [` + refString + `, {enum: []}]}`, ""}, } { - doc, diags := parseFull(t, disjointSpec(tc.s, "")) - require.NotNil(t, doc, tc.name) + doc, diags := parseFull(t, disjointSpec(testCase.s, "")) + require.NotNil(t, doc, testCase.name) reports := disjointReports(diags) - if tc.want == "" { - assert.Empty(t, reports, tc.name) + if testCase.want == "" { + assert.Empty(t, reports, testCase.name) continue } - require.Len(t, reports, 1, "%s: %+v", tc.name, diags) - assert.Contains(t, reports[0].Message, tc.want, tc.name) - assert.Equal(t, ir.SeverityWarning, reports[0].Severity, tc.name) + require.Len(t, reports, 1, "%s: %+v", testCase.name, diags) + assert.Contains(t, reports[0].Message, testCase.want, testCase.name) + assert.Equal(t, ir.SeverityWarning, reports[0].Severity, testCase.name) } } diff --git a/compilers/openapi/internal/schema/allof_disjoint_internal_test.go b/compilers/openapi/internal/schema/allof_disjoint_internal_test.go index 88710174c..dfa5a2c9f 100644 --- a/compilers/openapi/internal/schema/allof_disjoint_internal_test.go +++ b/compilers/openapi/internal/schema/allof_disjoint_internal_test.go @@ -18,15 +18,15 @@ import ( // aliasChain writes n schemas, the first named name, each a $ref to the next, // and the last a $ref to last. func aliasChain(name string, n int, last string) string { - var b strings.Builder + var builder strings.Builder for i := range n { next := fmt.Sprintf("%s%d", name, i+1) if i == n-1 { next = last } - fmt.Fprintf(&b, " %s%d: {$ref: '#/components/schemas/%s'}\n", name, i, next) + fmt.Fprintf(&builder, " %s%d: {$ref: '#/components/schemas/%s'}\n", name, i, next) } - return b.String() + return builder.String() } // TestToldWhereWritten_ReadsWhatSaysASchemaAdmitsNothing holds which schemas @@ -34,15 +34,15 @@ func aliasChain(name string, n int, last string) string { // of whose members its type admits, an empty enum, an allOf of conjuncts // sharing no kind, an object beside a union no branch of which an object or // null satisfies and another type beside a union none of whose branches it -// admits, each also through a chain of $refs up to the read's cap; and which -// do not: a type beside a $ref to another kind, a chain past the cap, and -// `true`, which admits everything. +// admits, each also through a chain of $refs however long; and which do not: +// a type beside a $ref to another kind, a $ref to a schema admitting a value, +// and `true`, which admits everything. func TestToldWhereWritten_ReadsWhatSaysASchemaAdmitsNothing(t *testing.T) { t.Parallel() rows := map[string]bool{ "F": true, "S": true, "K": true, "E": true, "D": true, "AliasS": true, "AliasF": true, - "Short0": true, "U": true, "AliasU": true, "W": true, "AliasW": true, "Str": false, "Beside": false, "Long0": false, - "T": false, + "Short0": true, "U": true, "AliasU": true, "W": true, "AliasW": true, "Str": false, "Beside": false, "Long0": true, + "AliasStr": false, "T": false, } lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` F: false T: true @@ -58,10 +58,11 @@ func TestToldWhereWritten_ReadsWhatSaysASchemaAdmitsNothing(t *testing.T) { W: {type: string, anyOf: [{type: integer}, {type: boolean}]} AliasW: {$ref: '#/components/schemas/W'} Beside: {$ref: '#/components/schemas/Str', type: object} + AliasStr: {$ref: '#/components/schemas/Str'} `+aliasChain("Short", maxAdmissionReads-1, "F")+aliasChain("Long", maxAdmissionReads, "F"))) for name, want := range rows { - st := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) - assert.Equal(t, want, toldWhereWritten(lowerer.Ctx, st), name) + schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) + assert.Equal(t, want, toldWhereWritten(lowerer.Ctx, schemaStatement), name) } } @@ -70,7 +71,7 @@ func TestToldWhereWritten_ReadsWhatSaysASchemaAdmitsNothing(t *testing.T) { // number with a fraction apart from an integer, with no empty word. func TestInstanceWords_NamesEverySetOfKinds(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { kinds kindSet words string }{ @@ -80,12 +81,12 @@ func TestInstanceWords_NamesEverySetOfKinds(t *testing.T) { {kindInteger, "integer"}, {kindFraction | kindString, "string or number that is no integer"}, {kindInteger | kindBoolean, "integer or boolean"}, - {anyInstance, "object or array or string or number or boolean"}, + {everyKindButNull, "object or array or string or number or boolean"}, } { - assert.Equal(t, tc.words, instanceWords(tc.kinds), "%07b", tc.kinds) + assert.Equal(t, testCase.words, instanceWords(testCase.kinds), "%07b", testCase.kinds) } - for kinds := kindSet(1); kinds <= anyInstance; kinds++ { - if kinds&^anyInstance != 0 { + for kinds := kindSet(1); kinds <= everyKindButNull; kinds++ { + if kinds&^everyKindButNull != 0 { continue } for word := range strings.SplitSeq(instanceWords(kinds), " or ") { @@ -94,11 +95,11 @@ func TestInstanceWords_NamesEverySetOfKinds(t *testing.T) { } } -// TestUnionApartFromBody_ReadsKindsAndACutReadSharesOne holds that a union -// beside a string body shares no kind with it where its branches admit -// integers, shares one where they admit a string, and shares one where a -// branch's read is cut short on a cycle, which admits more than it reads. -func TestUnionApartFromBody_ReadsKindsAndACutReadSharesOne(t *testing.T) { +// TestReadChosenUnion_ReadsKindsAndACutReadSharesOne holds that a union beside +// a string body leaves no branch where its branches admit integers, leaves one +// where they admit a string, and leaves one where a branch's read is cut short +// on a cycle, which admits more than it reads. +func TestReadChosenUnion_ReadsKindsAndACutReadSharesOne(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` Cyc: {allOf: [{$ref: '#/components/schemas/Cyc'}]} Apart: {type: string, anyOf: [{type: integer}]} @@ -106,7 +107,7 @@ func TestUnionApartFromBody_ReadsKindsAndACutReadSharesOne(t *testing.T) { Cut: {type: string, anyOf: [{type: integer}, {$ref: '#/components/schemas/Cyc'}]} `)) for name, want := range map[string]bool{"Apart": true, "Shared": false, "Cut": false} { - st := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) - assert.Equal(t, want, unionApartFromBody(lowerer.Ctx, st.Schema), name) + schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) + assert.Equal(t, want, readLoweredUnion(lowerer.Ctx, schemaStatement.Schema).besideRest == unionLeavesNoBranch, name) } } diff --git a/compilers/openapi/internal/schema/allof_disjoint_test.go b/compilers/openapi/internal/schema/allof_disjoint_test.go index 3c61bbf8e..b283d087d 100644 --- a/compilers/openapi/internal/schema/allof_disjoint_test.go +++ b/compilers/openapi/internal/schema/allof_disjoint_test.go @@ -4,6 +4,8 @@ package schema_test import ( + "encoding/json/jsontext" + "slices" "strings" "testing" @@ -51,8 +53,8 @@ func disjointSpec(s, extra string) string { func disjointReports(diags []ir.Diagnostic) []ir.Diagnostic { var out []ir.Diagnostic for _, diagnostic := range diags { - if diagnostic.Code == diag.DegradedConstruct && diagnostic.Severity == ir.SeverityWarning && - strings.Contains(diagnostic.Message, "share no value") { + if diagnostic.Code == diag.UnsatisfiableSchema && diagnostic.Severity == ir.SeverityWarning && + strings.Contains(diagnostic.Message, "no value satisfies") { out = append(out, diagnostic) } } @@ -67,17 +69,17 @@ func TestAllOf_DisjointConjunctsReportOnceAtTheSchema(t *testing.T) { t.Parallel() // own counts the warnings an entry draws of itself, apart from the report. own := map[string]int{ - "an entry the enum beats that cannot be kept": 1, - "an entry the const beats beside a family kept": 1, + "an entry the enum is chosen over that cannot be kept": 1, + "an entry the const is chosen over beside a family kept": 1, } - for _, tc := range []struct { + for _, testCase := range []struct { name, s, want string }{ {"a type beside the allOf against a $ref", `{type: object, allOf: [` + refList + `]}`, "type: object, allOf/0: array"}, {"two $refs", `{allOf: [` + refString + `, ` + refObj + `]}`, "allOf/0: string, allOf/1: object"}, - {"an allOf beside a $ref, which joins its conjunction", + {"an allOf beside a $ref, which combines its conjunction", `{$ref: '#/components/schemas/Str', allOf: [` + refObj + `]}`, "$ref: string, allOf/0: object"}, {"an inline entry against a $ref", `{allOf: [` + refObj + `, {type: string}]}`, "allOf/0: object, allOf/1: string"}, @@ -108,27 +110,25 @@ func TestAllOf_DisjointConjunctsReportOnceAtTheSchema(t *testing.T) { `{allOf: [{allOf: [` + refString + `, ` + refObj + `]}]}`, "allOf/0/allOf/0: string, allOf/0/allOf/1: object"}, {"a flattened wrapper's own type", - `{allOf: [{type: string, allOf: [` + refObj + `]}]}`, "allOf/0/allOf/0: object, allOf/0: string"}, - {"a null against an object", - `{allOf: [{type: "null"}, ` + refObj + `]}`, "allOf/0: null, allOf/1: object"}, + `{allOf: [{type: string, allOf: [` + refObj + `]}]}`, "allOf/0: string, allOf/0/allOf/0: object"}, {"a nullable string against an object", `{allOf: [{$ref: '#/components/schemas/NullStr'}, ` + refObj + `]}`, "allOf/0: string, allOf/1: object"}, {"an entry stating nothing goes unnamed", `{allOf: [` + refString + `, {description: d}, ` + refObj + `]}`, "allOf/0: string, allOf/2: object"}, {"two nullable types beside an enum", `{allOf: [{type: [string, "null"]}, {type: [object, "null"]}, {enum: [a]}]}`, - "allOf/0: string, allOf/1: object, allOf/2: string"}, + `allOf/0: string, allOf/1: object, allOf/2: enum ["a"]`}, {"a union of a string and an integer", `{allOf: [{$ref: '#/components/schemas/U'}, {type: object}]}`, "allOf/0: string or integer, allOf/1: object"}, {"a keyword beside a $ref", `{allOf: [{$ref: '#/components/schemas/Props', type: string}, {type: object}]}`, "allOf/0: string, allOf/1: object"}, {"a keyword beside a $ref it contradicts", `{allOf: [{$ref: '#/components/schemas/Str', type: object}]}`, - "allOf/0/$ref: string, allOf/0: object"}, + "allOf/0: object, allOf/0/$ref: string"}, {"a keyword and an allOf beside a $ref they contradict", `{allOf: [{$ref: '#/components/schemas/Str', type: object, allOf: [{type: integer}]}]}`, - "allOf/0/$ref: string, allOf/0/allOf/0: integer, allOf/0: object"}, - {"a null beside an enum", `{allOf: [{type: "null"}, {enum: [a]}]}`, "allOf/0: null, allOf/1: string"}, - {"a null beside a const", `{allOf: [{type: "null"}, {const: 1}]}`, "allOf/0: null, allOf/1: integer"}, + "allOf/0: object, allOf/0/$ref: string, allOf/0/allOf/0: integer"}, + {"a null beside an enum", `{allOf: [{type: "null"}, {enum: [a]}]}`, `allOf/0: null, allOf/1: enum ["a"]`}, + {"a null beside a const", `{allOf: [{type: "null"}, {const: 1}]}`, "allOf/0: null, allOf/1: const 1"}, {"a type of null beside entries stating nothing", `{allOf: [{$ref: '#/components/schemas/NullComposed'}, ` + refObj + `]}`, "allOf/0: null, allOf/1: object"}, {"a distributed union with an inline branch", @@ -142,42 +142,44 @@ func TestAllOf_DisjointConjunctsReportOnceAtTheSchema(t *testing.T) { {"a union beside sharing no kind with a refinement", `{allOf: [` + refString + `], anyOf: [{type: integer}, {type: boolean}]}`, "anyOf: integer or boolean, allOf/0: string"}, {"an allOf an enum passes over", `{enum: [a], allOf: [` + refString + `, ` + refObj + `]}`, - "enum: string, allOf/0: string, allOf/1: object"}, + `enum: ["a"], allOf/0: string, allOf/1: object`}, {"an allOf a const passes over", `{type: string, const: a, allOf: [{type: integer}]}`, - "type: string, const: string, allOf/0: integer"}, + `type: string, const: "a", allOf/0: integer`}, {"an allOf an enum passes over beside a union", `{enum: [a], oneOf: [{type: string}, {type: integer}], allOf: [` + refString + `, ` + refObj + `]}`, - "enum: string, oneOf: string or integer, allOf/0: string, allOf/1: object"}, - {"an entry the enum beats that cannot be kept", + `enum: ["a"], oneOf: string or integer, allOf/0: string, allOf/1: object`}, + {"an entry the enum is chosen over that cannot be kept", `{enum: [a], allOf: [{type: string}, {type: integer, x-v: ` + unpreservableValue + `}]}`, - "enum: string, allOf/0: string, allOf/1: integer"}, - {"an entry the const beats beside a family kept", + `enum: ["a"], allOf/0: string, allOf/1: integer`}, + {"an entry the const is chosen over beside a family kept", `{const: a, enum: [a], allOf: [{type: string}, {type: integer, x-v: ` + unpreservableValue + `}]}`, - "enum: string, allOf/0: string, allOf/1: integer"}, + `enum: ["a"], allOf/0: string, allOf/1: integer`}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, _ := parseFull(t, disjointSpec(tc.s, "")) + doc, _ := parseFull(t, disjointSpec(testCase.s, "")) reports := disjointReports(doc.Diagnostics) require.Len(t, reports, 1, "one report, wherever the conjuncts are written: %+v", doc.Diagnostics) assert.Equal(t, "/components/schemas/S", string(reports[0].Provenance.Pointer)) - assert.Contains(t, reports[0].Message, "share no value ("+tc.want+")") - assert.Equal(t, 1+own[tc.name], openapitest.CountDiagsAt(doc.Diagnostics, diag.DegradedConstruct, ir.SeverityWarning), + assert.Contains(t, reports[0].Message, "("+testCase.want+")") + assert.Equal(t, 1, openapitest.CountDiagsAt(doc.Diagnostics, diag.UnsatisfiableSchema, ir.SeverityWarning), + "no other unsatisfiable-schema warning in the document: %+v", doc.Diagnostics) + assert.Equal(t, own[testCase.name], openapitest.CountDiagsAt(doc.Diagnostics, diag.DegradedConstruct, ir.SeverityWarning), "no other degraded-construct warning in the document: %+v", doc.Diagnostics) }) } } -// TestAllOf_DisjointReportNamesWhatThePositionLoweredAs pins the report's last -// clause to the node it describes: a composition, or the value set an election -// passed the allOf over for. +// TestAllOf_DisjointReportNamesWhatThePositionLoweredAs pins the report's +// lowered-as clause to the node it describes: the bottom its conjuncts sharing +// no kind lower to, or the value set a choice passed the allOf over for. func TestAllOf_DisjointReportNamesWhatThePositionLoweredAs(t *testing.T) { t.Parallel() for written, shape := range map[string]string{ - `{type: string, allOf: [{type: integer}]}`: "which a composition cannot state", - `{type: string, enum: [a], allOf: [{type: integer}]}`: "which the enum it lowered as cannot state", - `{type: string, const: a, allOf: [{type: integer}]}`: "which the const it lowered as cannot state", + `{type: string, allOf: [{type: integer}]}`: "; lowered as the closed model with no member a false schema lowers to — ", + `{type: string, enum: [a], allOf: [{type: integer}]}`: "; lowered as its enum — ", + `{type: string, const: a, allOf: [{type: integer}]}`: "; lowered as its const — ", } { doc, _ := parseFull(t, disjointSpec(written, "")) reports := disjointReports(doc.Diagnostics) @@ -186,18 +188,19 @@ func TestAllOf_DisjointReportNamesWhatThePositionLoweredAs(t *testing.T) { } } -// TestAllOf_DisjointReportStaysSilent holds the readings that must not report: +// TestAllOf_DisjointReportDrawsNothing holds the readings that must not report: // a conjunct writing no type states nothing, and neither does a `true` or an -// unresolved $ref; a conjunct admitting nothing, a `false` among them, is its -// own to report; a null both sides admit is a value they share; a lone +// unresolved $ref; a null both sides admit is a value they share; a lone // conjunct narrowing the instance types contradicts nothing; and an allOf -// beside a $ref, which does not compose, is not read. -func TestAllOf_DisjointReportStaysSilent(t *testing.T) { +// beside a $ref, which does not compose, is not read. A `false` entry, or a +// $ref landing on one, makes the schema a bottom drawing its own warning +// (TestAllOf_AFalseEntryMakesTheSchemaABottomOfItsOwn). +func TestAllOf_DisjointReportDrawsNothing(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, s, extra string // also is a code the case must still draw, which is what a case that - // stays silent about the conjuncts says about something else. + // reports nothing about the conjuncts says about something else. also string }{ {"an integer with a number", `{allOf: [{type: integer}, {type: number}]}`, "", ""}, @@ -210,38 +213,53 @@ func TestAllOf_DisjointReportStaysSilent(t *testing.T) { {"a null with a nullable object", `{allOf: [{type: "null"}, {$ref: '#/components/schemas/NullObj'}]}`, "", ""}, {"a type set holding the other's type", `{allOf: [{type: [string, object]}, ` + refObj + `]}`, "", ""}, - {"a true and a false entry", `{allOf: [true, false, ` + refObj + `]}`, "", diag.FalseSchema}, {"a schema composing itself", `{allOf: [{$ref: '#/components/schemas/Cy'}, ` + refObj + `]}`, " Cy: {allOf: [{$ref: '#/components/schemas/Cy'}, {$ref: '#/components/schemas/Cy'}]}\n", ""}, {"an unresolved $ref", `{allOf: [{$ref: '#/components/schemas/Ghost'}, ` + refObj + `]}`, "", ""}, {"a $ref landing on a boolean", `{allOf: [{$ref: '#/components/schemas/Yes'}, ` + refObj + `]}`, "", ""}, - {"a type no dialect defines", `{type: widget, allOf: [` + refObj + `]}`, "", ""}, {"a null read past its budget", `{allOf: [` + strings.Repeat(`{$ref: '#/components/schemas/Props'}, `, 130) + `{$ref: '#/components/schemas/NullStr'}, {$ref: '#/components/schemas/NullObj'}]}`, "", ""}, - {"a null beside a false entry", `{allOf: [{type: "null"}, false]}`, "", diag.FalseSchema}, {"a null beside every other type", `{allOf: [{type: "null"}, {type: [string, number, boolean, array, object]}]}`, "", ""}, - {"two nullable types beside a false entry", - `{allOf: [{type: [string, "null"]}, {type: [object, "null"]}, false]}`, "", diag.FalseSchema}, - {"a type of null beside a false entry", `{type: "null", allOf: [false]}`, "", diag.FalseSchema}, - {"a null beside a $ref landing on false", `{allOf: [{type: "null"}, {$ref: '#/components/schemas/No'}]}`, - " No: false\n", diag.FalseSchema}, {"a distributed union composing nothing", `{properties: {a: {type: string}}, oneOf: [` + refObj + `, ` + refList + `]}`, "", ""}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, _ := parseFull(t, disjointSpec(tc.s, tc.extra)) + doc, _ := parseFull(t, disjointSpec(testCase.s, testCase.extra)) assert.Empty(t, disjointReports(doc.Diagnostics)) - if tc.also != "" { - assert.True(t, openapitest.HasDiag(doc.Diagnostics, tc.also), - "the case still draws %s: %+v", tc.also, doc.Diagnostics) + if testCase.also != "" { + assert.True(t, openapitest.HasDiag(doc.Diagnostics, testCase.also), + "the case still draws %s: %+v", testCase.also, doc.Diagnostics) } }) } } +// TestAllOf_AFalseEntryMakesTheSchemaABottomOfItsOwn holds an allOf writing a +// `false` entry, beside whatever else: no instance satisfies the schema, so it +// is a bottom, which draws its own warning at the position beside the entry's +// report that it matches nothing. +func TestAllOf_AFalseEntryMakesTheSchemaABottomOfItsOwn(t *testing.T) { + t.Parallel() + for name, s := range map[string]string{ + "a true and a false entry": `{allOf: [true, false, ` + refObj + `]}`, + "a null beside a false entry": `{allOf: [{type: "null"}, false]}`, + "two nullable types beside a false entry": `{allOf: [{type: [string, "null"]}, {type: [object, "null"]}, false]}`, + "a type of null beside a false entry": `{type: "null", allOf: [false]}`, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, disjointSpec(s, "")) + assert.True(t, openapitest.HasDiag(doc.Diagnostics, diag.FalseSchema), "the entry reports itself: %+v", doc.Diagnostics) + warnings := diagsAtPointer(doc.Diagnostics, diag.UnsatisfiableSchema, "/components/schemas/S") + require.Len(t, warnings, 1, "%+v", doc.Diagnostics) + assert.Equal(t, ir.SeverityWarning, warnings[0].Severity) + }) + } +} + // TestAllOf_AKeywordBesideARefIsReadAtEveryVersion holds a keyword beside a // $ref entry in the reading at 3.0 as at 3.1, since the lowering applies it at // both (docs/compilers/openapi.md#ref-use-site): an untyped target narrowed to @@ -255,14 +273,17 @@ func TestAllOf_AKeywordBesideARefIsReadAtEveryVersion(t *testing.T) { `)) reports := disjointReports(doc.Diagnostics) require.Len(t, reports, 1, version) - assert.Contains(t, reports[0].Message, "share no value (allOf/0: string, allOf/1: object)", version) + assert.Contains(t, reports[0].Message, "(allOf/0: string, allOf/1: object)", version) assert.Equal(t, version == "3.0.3", openapitest.HasDiag(doc.Diagnostics, diag.LaterVersionConstruct), version) } } // TestAllOf_ComposingADisjointSchemaDrawsNoSecondReport holds a schema composing -// one whose conjuncts share no value to the one report, at the schema that -// writes them. +// one whose conjuncts share no value to the one report of that contradiction, +// at the schema that writes it: Outer, whose one conjunct is Mid, is Mid and +// draws nothing. Outer2 conjoins Mid with an object, so it admits nothing +// either, and as a bottom of its own it draws its own warning naming Mid as +// admitting no value, so a reader of Outer2 alone learns that it is empty. func TestAllOf_ComposingADisjointSchemaDrawsNoSecondReport(t *testing.T) { t.Parallel() doc, _ := parseFull(t, disjointSpec(`{allOf: [`+refList+`]}`, ` Mid: {allOf: [`+refString+`, `+refObj+`]} @@ -271,60 +292,104 @@ func TestAllOf_ComposingADisjointSchemaDrawsNoSecondReport(t *testing.T) { `)) reports := disjointReports(doc.Diagnostics) - require.Len(t, reports, 1, "%+v", doc.Diagnostics) + require.Len(t, reports, 2, "%+v", doc.Diagnostics) assert.Equal(t, "/components/schemas/Mid", string(reports[0].Provenance.Pointer)) + assert.Contains(t, reports[0].Message, "(allOf/0: string, allOf/1: object)") + assert.Equal(t, "/components/schemas/Outer2", string(reports[1].Provenance.Pointer)) + assert.Contains(t, reports[1].Message, "(allOf/0: no value, allOf/1: object)") } -// TestAllOf_DisjointInlineEntryReportsItsResidueAsInfo holds an inline entry -// the schema's report covers to its residue alone: an info that names what is -// kept, each keyword under its own key, since the warning is the schema's. The -// residue is the type and the bound the object beside the entry cannot take. -func TestAllOf_DisjointInlineEntryReportsItsResidueAsInfo(t *testing.T) { +// TestAllOf_ANullBesideARefIsTheIdiomOrItsOwnBottom holds a type of null +// conjoined with one $ref, an object's or one landing on `false`. Under the +// nullable-inference policy the null widens the reference, so the position is +// the nullable reference to the target, with no report of its own. With the +// policy off the two share no value: the schema draws its own warning, naming +// a `false` target as admitting no value, whatever the target reports. +func TestAllOf_ANullBesideARefIsTheIdiomOrItsOwnBottom(t *testing.T) { t.Parallel() - doc, _ := parseFull(t, disjointSpec(`{allOf: [`+refObj+`, {type: string, maxLength: 3}]}`, "")) + for _, testCase := range []struct{ target, extra, want string }{ + {"Obj", "", "(allOf/0: null, allOf/1: object)"}, + {"No", " No: false\n", "(allOf/0: null, allOf/1: no value)"}, + } { + spec := disjointSpec(`{allOf: [{type: "null"}, {$ref: '#/components/schemas/`+testCase.target+`'}]}`, testCase.extra) + on, onDiags := compileNullable(t, spec, false) + assert.Empty(t, disjointReports(onDiags), "%s: the null widens the reference", testCase.target) + alias, ok := typeByName(on, "S").(*ir.Scalar) + require.True(t, ok, "%s: the position is the reference", testCase.target) + require.NotNil(t, alias.Base, testCase.target) + assert.Equal(t, inferred(componentID(testCase.target)), *alias.Base, testCase.target) + off, offDiags := compileNullable(t, spec, true) + require.NotNil(t, off) + reports := disjointReports(offDiags) + require.Len(t, reports, 1, "%+v", offDiags) + assert.Equal(t, "/components/schemas/S", string(reports[0].Provenance.Pointer)) + assert.Contains(t, reports[0].Message, testCase.want) + } + _, diags := compileNullable(t, disjointSpec(`{allOf: [{type: "null"}, {$ref: '#/components/schemas/No'}]}`, " No: false\n"), true) + assert.True(t, openapitest.HasDiag(diags, diag.FalseSchema), "the target reports itself: %+v", diags) +} - var atEntry []ir.Diagnostic +// TestAllOf_DisjointInlineEntryReportsItsUnreadKeywordsAsInfo holds an inline +// string entry beside an object $ref, which share no kind: the position is the +// closed bottom, which keeps the inline entry whole under its entry key and the +// $ref under its own, and the schema's one warning is the only report, the +// entry drawing none of its own. +func TestAllOf_DisjointInlineEntryReportsItsUnreadKeywordsAsInfo(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, disjointSpec(`{allOf: [`+refObj+`, {type: string, maxLength: 3}]}`, "")) for _, diagnostic := range doc.Diagnostics { - if diagnostic.Provenance.Pointer == "/components/schemas/S/allOf/1" { - atEntry = append(atEntry, diagnostic) - } + assert.NotEqual(t, jsontext.Pointer("/components/schemas/S/allOf/1"), diagnostic.Provenance.Pointer, + "the entry draws no report: %s", diagnostic.Message) } - require.Len(t, atEntry, 1, "%+v", doc.Diagnostics) - assert.Equal(t, ir.SeverityInfo, atEntry[0].Severity) - assert.Contains(t, atEntry[0].Message, "no home for type, maxLength written on this inline entry") - + require.Len(t, disjointReports(doc.Diagnostics), 1) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) - assert.Equal(t, []string{"openapi:maxLength", "openapi:type"}, unmodeledKeys(model.Unmodeled)) - assert.JSONEq(t, `3`, string(model.Unmodeled["openapi:maxLength"].Value), - "the maxLength the object beside it cannot take") - assert.JSONEq(t, `"string"`, string(model.Unmodeled["openapi:type"].Value)) + assert.Equal(t, []string{"openapi:$ref", "openapi:allOf/1"}, unmodeledKeys(model.Unmodeled)) + assert.JSONEq(t, `{"type":"string","maxLength":3}`, string(model.Unmodeled["openapi:allOf/1"].Value), "the entry whole") } // TestAllOf_DisjointConjunctsFollowTheNullableReading holds the report to the // reading of null the nullable-inference policy selects: a schema written -// `nullable: true` beside conjuncts that share no other value admits null while -// the policy is on, and does not once it is off. +// `nullable: true` beside inline conjuncts that share no other value admits +// null while the policy is on, and does not once it is off. Beside two +// references the policy widens nothing, reading a null as one reference or +// null, so the report remains under either policy. func TestAllOf_DisjointConjunctsFollowTheNullableReading(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpecVer("3.0.3", ` Str: {type: string} Obj: {type: object} S: + allOf: [{type: string}, {type: object}] + nullable: true + R: allOf: [`+refString+`, `+refObj+`] nullable: true `) on, onDiags := compileNullable(t, spec, false) require.NotNil(t, on) - assert.Empty(t, disjointReports(onDiags), "the policy reads null in, which both conjuncts then share") - assert.True(t, openapitest.HasDiag(onDiags, diag.InferredNullable), "and says it did: %+v", onDiags) + assert.Equal(t, []string{"/components/schemas/R"}, reportPointers(disjointReports(onDiags)), + "the policy reads null in beside inline conjuncts, which both then share") + assert.True(t, openapitest.HasDiagCodeAt(onDiags, diag.InferredNullable, "/components/schemas/S/nullable"), "and says it did: %+v", onDiags) + assert.False(t, openapitest.HasDiagCodeAt(onDiags, diag.InferredNullable, "/components/schemas/R/nullable"), "beside two references it reads none in") off, offDiags := compileNullable(t, spec, true) require.NotNil(t, off) - assert.Len(t, disjointReports(offDiags), 1, "as 3.0 defines nullable, the string and the object share nothing") + assert.Equal(t, []string{"/components/schemas/R", "/components/schemas/S"}, reportPointers(disjointReports(offDiags)), + "as 3.0 defines nullable, the string and the object share nothing") assert.False(t, openapitest.HasDiag(offDiags, diag.InferredNullable)) } +// reportPointers is where each of reports sits, sorted. +func reportPointers(reports []ir.Diagnostic) []string { + out := make([]string, 0, len(reports)) + for _, report := range reports { + out = append(out, string(report.Provenance.Pointer)) + } + slices.Sort(out) + return out +} + // TestAllOf_DisjointConjunctsIgnoreDeclarationOrder holds the report to what // the source writes, not to which component lowered first: the composing schema // is declared before the schemas it names and then after them. @@ -343,7 +408,7 @@ func TestAllOf_DisjointConjunctsIgnoreDeclarationOrder(t *testing.T) { got, want := reported(disjointReports(before.Diagnostics)), reported(disjointReports(after.Diagnostics)) require.Len(t, got, 1, "%+v", before.Diagnostics) - assert.Contains(t, got[0], "share no value (allOf/0: array, allOf/1: object, allOf/2: string)") + assert.Contains(t, got[0], "(allOf/0: array, allOf/1: object, allOf/2: string)") assert.Empty(t, cmp.Diff(want, got), "the report does not depend on the declaration order") } diff --git a/compilers/openapi/internal/schema/allof_disjoint_valueset_test.go b/compilers/openapi/internal/schema/allof_disjoint_valueset_test.go index b7c9d1ac3..dfaec0d1f 100644 --- a/compilers/openapi/internal/schema/allof_disjoint_valueset_test.go +++ b/compilers/openapi/internal/schema/allof_disjoint_valueset_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) @@ -32,7 +33,7 @@ func TestAllOf_AValueSetBesideAUnionWarnsOnce(t *testing.T) { } assert.Len(t, warnings, 2, "a warning for each spelling and no other: %v", warnings) for _, name := range []string{"Wrap", "Entry"} { - at := diagsAtPointer(disjointReports(diags), "openapi/degraded-construct", "/components/schemas/"+name) + at := diagsAtPointer(disjointReports(diags), diag.UnsatisfiableSchema, "/components/schemas/"+name) assert.Len(t, at, 1, "%s: one warning that its conjuncts share no value", name) _, isEnum := typeByName(doc, name).(*ir.Enum) assert.True(t, isEnum, name) diff --git a/compilers/openapi/internal/schema/allof_flattening.go b/compilers/openapi/internal/schema/allof_flattening.go new file mode 100644 index 000000000..445cc4920 --- /dev/null +++ b/compilers/openapi/internal/schema/allof_flattening.go @@ -0,0 +1,479 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// flattenedEntryNodeKeywords are the node keywords (nodeKeywords) a builder +// reads off whichever conjunct writes them, as it reads a bound. Every other +// has a reader of its own, the choice's, the in-place merge's or the union's, +// and no fold reads it. +var flattenedEntryNodeKeywords = []string{"format", "items", "prefixItems", "additionalItems", "maxItems", "minItems", "uniqueItems"} + +// foldKey returns the entry a position keeps keyword in once schema, an inline +// allOf entry of it, folds, and whether a fold reads keyword: one scoped to any +// conjunct or moving with its group, read as written beside the allOf +// (docs/compilers/openapi.md#allof-inline-residue), but not a node keyword +// read apart, and `nullable`, which folds decides. A group folds as one entry +// (foldGroup), and a draft's spelling as its twin (TwinKeyword). +func foldKey(loweringContext lowering.Ctx, schema *statement.Schema, keyword string) (string, bool) { + if keyword == "nullable" { + return keyword, true + } + rules := rulesOf(loweringContext, schema) + if scope := rules.KeywordScopeOf(keyword); scope != specrules.KeywordScopeAnyConjunct && scope != specrules.KeywordScopeWithGroup { + return keyword, false + } + canonicalKeyword := TwinKeyword(loweringContext, schema, keyword) + switch { + case readApart(canonicalKeyword): + return keyword, false + case slices.Contains(collectionBoundKeywords, canonicalKeyword): + // A collection bound ir.Constraints cannot state keeps its entry whole. + return keyword, referenceHolds(schema, keyword) + case canonicalKeyword == "example": + return "examples", true + } + return foldGroup(rules, keyword), true +} + +// readApart reports whether keyword is a node keyword with a reader of its own, +// no flattened entry of which a builder reads (flattenedEntryNodeKeywords). +func readApart(keyword string) bool { + return slices.Contains(nodeKeywords, keyword) && !slices.Contains(flattenedEntryNodeKeywords, keyword) +} + +// foldGroup returns the entry keyword folds as: the first anchor of the group +// it moves with (specrules.SchemaRules.GroupAnchorKeywords), but where that +// anchor is a bound, which agrees by intersecting (isBound), or is read apart +// (readApart), keyword itself. An anchor heads its own group. +func foldGroup(rules specrules.SchemaRules, keyword string) string { + anchors := rules.GroupAnchorKeywords(keyword) + if len(anchors) == 0 || isBound(anchors[0]) || readApart(anchors[0]) { + return keyword + } + return anchors[0] +} + +// foldRendering is what a conjunct writes for an entry, rendered to compare +// with another conjunct's as the node's pending keeps compare two writings +// (annotation.CanonicalRendering), read once. One that cannot be rendered +// agrees with nothing, which keeps its entry; a keyword may render to nothing, +// which is no failure. +type foldRendering struct { + raw ir.RawValue + err error + canonical string +} + +// agrees reports whether r and foldRenderingValue write an entry alike. +func (r foldRendering) agrees(foldRenderingValue foldRendering) bool { + return r.err == nil && foldRenderingValue.err == nil && r.canonical == foldRenderingValue.canonical +} + +// foldValue renders what schema writes for entry, a group's members together +// (groupMembers). +func foldValue(loweringContext lowering.Ctx, schema *statement.Schema, entry string) foldRendering { + var foldRenderingValue foldRendering + switch members := groupMembers(loweringContext, schema, entry); { + case entry == "examples": + foldRenderingValue.raw, _, foldRenderingValue.err = annotation.ExamplesRaw(schema) + case entry == "if": + foldRenderingValue.raw, _, foldRenderingValue.err = annotation.IfThenElseRaw(schema) + case entry == "contains": + foldRenderingValue.raw, _, foldRenderingValue.err = annotation.ContainsRaw(schema) + case len(members) > 1 || len(members) == 1 && members[0] != entry: + foldRenderingValue.raw, _, foldRenderingValue.err = annotation.CombinedRaw(schema, members...) + default: + return keyRendering(schema, entry) + } + if foldRenderingValue.err == nil { + foldRenderingValue.canonical = annotation.CanonicalRendering(foldRenderingValue.raw) + } + return foldRenderingValue +} + +// keyRendering renders what schema writes under key alone. +func keyRendering(schema *statement.Schema, key string) foldRendering { + var foldRenderingValue foldRendering + foldRenderingValue.raw, foldRenderingValue.err = annotation.RawFromNode(keyNode(schema, key)) + if foldRenderingValue.err == nil { + foldRenderingValue.canonical = annotation.CanonicalRendering(foldRenderingValue.raw) + } + return foldRenderingValue +} + +// groupMembers returns the keys schema writes that fold as entry, in the order +// written. +func groupMembers(loweringContext lowering.Ctx, schema *statement.Schema, entry string) []string { + var out []string + for _, key := range schema.Keys { + if folded, folds := foldKey(loweringContext, schema, key.Name); folds && folded == entry { + out = append(out, key.Name) + } + } + return out +} + +// allOfDecides reports whether schema's allOf is what its position lowers: +// one the dispatch of competing keywords made the value, or one refining, +// whose rival there, an enum or a const beside it, is one of its conjuncts. An +// allOf that value set is chosen over otherwise stays verbatim +// (docs/compilers/openapi.md#competing-keywords). A union beside the composing +// allOf or on one of its entries leaves it deciding, composed into each variant +// the union distributes across, or into the Model keeping the union verbatim or +// composing it as a mixin, and so does a $dynamicRef it keeps from expanding. +func allOfDecides(loweringContext lowering.Ctx, schema *statement.Schema) bool { + if !writesConjuncts(schema) { + return false + } + if dispatchOf(schema).lowered == "allOf" { + return true + } + return decisionOf(loweringContext, schema).refines() +} + +// allOfEntryFoldingKey keys what allOfEntryFoldingOf reads of one schema. +type allOfEntryFoldingKey struct { + schema *statement.Schema +} + +// allOfEntryFolding is what a schema's allOf says for the position holding it, +// per entry of the flattened list: whether it folds a keyword, whether it +// lends a use a keyword the schema and the folding entries before it do not +// write, and whether what it folds writes a relative $ref read against another +// base than the position's (readsAtPosition), so nothing it writes folds. +// apart holds the entries of foldKey its conjuncts write otherwise, which do +// not fold, nil for none (docs/compilers/openapi.md#allof-inline-residue). +type allOfEntryFolding struct { + entryFoldsIntoPosition []bool + addsKeywordNoEarlierEntryWrites []bool + rebased []bool + apart []map[string]bool +} + +// apartAt reports whether keyword, a key the entry at index i writes, is one +// its conjuncts write otherwise, so it does not fold (allOfEntryFolding.apart). +func (f allOfEntryFolding) apartAt(loweringContext lowering.Ctx, schema *statement.Schema, i int, keyword string) bool { + if f.apart == nil || f.apart[i] == nil { + return false + } + entry, fold := foldKey(loweringContext, schema, keyword) + return fold && f.apart[i][entry] +} + +// folds returns whether the entry at index i, writing schema, folds a key. +func (f allOfEntryFolding) folds(loweringContext lowering.Ctx, schema *statement.Schema, i int) func(string) bool { + return func(key string) bool { + return f.entryFoldsIntoPosition[i] && !f.apartAt(loweringContext, schema, i, key) + } +} + +// foldsWhole reports whether the entry at index i folds every keyword it +// writes that folds. +func (f allOfEntryFolding) foldsWhole(i int) bool { + return f.entryFoldsIntoPosition != nil && f.entryFoldsIntoPosition[i] && (f.apart == nil || f.apart[i] == nil) +} + +// allOfEntryFoldingOf reads schema's folding once a run. An inline entry folds +// each keyword it writes for the position that every other conjunct writing +// it, schema's own among them, writes alike (agreement): the whole set is +// read, so no order decides. +func allOfEntryFoldingOf(loweringContext lowering.Ctx, schema *statement.Schema) allOfEntryFolding { + return lowering.ReadOncePerRun(loweringContext, allOfEntryFoldingKey{schema}, func() allOfEntryFolding { return readAllOfEntryFolding(loweringContext, schema) }) +} + +// readAllOfEntryFolding reads what allOfEntryFoldingOf remembers. +func readAllOfEntryFolding(loweringContext lowering.Ctx, schema *statement.Schema) allOfEntryFolding { + entryAgreement := newAgreement(loweringContext) + addsKeywordNoEarlierEntryWrites := map[string]bool{} + for _, entry := range entryAgreement.write(schema) { + addsKeywordNoEarlierEntryWrites[entry] = true + } + comp := allOfEntries(loweringContext, schema, "") + n := len(comp.entries) + out := allOfEntryFolding{entryFoldsIntoPosition: make([]bool, n), addsKeywordNoEarlierEntryWrites: make([]bool, n), rebased: make([]bool, n), + apart: make([]map[string]bool, n)} + if decisionOf(loweringContext, schema).refinement.cutBy != "" { + // A read a bound cut keeps each conjunct saying something verbatim, + // as their comparison was cut (cutRead). + return out + } + writes := make([][]string, n) + ids := idWrappers(comp) + for i, entry := range comp.entries { + if stated(entry.schema.Schema) && entry.schema.Ref == nil { + if out.rebased[i] = underID(entry, entry.schema.Schema, ids) && foldsReference(loweringContext, entry.schema.Schema) && !readsAtPosition(loweringContext, entry); !out.rebased[i] { + writes[i] = entryAgreement.write(entry.schema.Schema) + } + } + } + for i, entries := range writes { + out.apart[i] = apartEntries(entryAgreement, entries) + unrendered := entryAgreement.unrendered[comp.entries[i].schema.Schema] + for _, entry := range entries { + // Beside what disagrees, a value rendering to none, which reports + // itself, folds nothing either. + if out.apart[i][entry] || out.apart[i] != nil && unrendered[entry] { + continue + } + out.entryFoldsIntoPosition[i] = true + out.addsKeywordNoEarlierEntryWrites[i] = out.addsKeywordNoEarlierEntryWrites[i] || !addsKeywordNoEarlierEntryWrites[entry] + addsKeywordNoEarlierEntryWrites[entry] = true + } + } + return out +} + +// apartEntries returns the entries of entries, what one conjunct writes, its +// conjuncts write otherwise (agreement.apart), nil for none. +func apartEntries(entryAgreement *agreement, entries []string) map[string]bool { + var out map[string]bool + for _, entry := range entries { + if entryAgreement.apart(entry) { + if out == nil { + out = map[string]bool{} + } + out[entry] = true + } + } + return out +} + +// foldingNode returns the schema of the entry at index i of schema's allOf a +// reader of what the position folds reads: the entry's own, less what its +// conjuncts write otherwise where they do (allOfEntryFolding.apart). +func foldingNode(loweringContext lowering.Ctx, schema *statement.Schema, i int, entry *statement.Schema) *statement.Schema { + folding := allOfEntryFoldingOf(loweringContext, schema) + if folding.apart[i] == nil { + return entry + } + var apart []string + for _, key := range entry.Keys { + if folding.apartAt(loweringContext, entry, i, key.Name) { + apart = append(apart, key.Name) + } + } + return loweringContext.Statements().Without(entry, apart) +} + +// idWrappers returns where the flattened wrappers of comp writing an +// identifier are (writesIdentifier), each one that may give what it holds +// another base than the position's. +func idWrappers(comp allOfComposition) map[jsontext.Pointer]bool { + out := map[jsontext.Pointer]bool{} + for _, entry := range comp.entries { + if entry.wrapper && writesIdentifier(entry.schema.Schema) { + out[entry.pointer] = true + } + } + return out +} + +// underID reports whether entrySchema, the inline allOf entry e, or a wrapper +// holding it writes an identifier. Only one can give the entry another base +// than the position holding the allOf, so an entry under none reads at the +// position without a base being looked up. The wrappers holding e are the +// prefixes of its pointer, as many as statement.MaxFlattenDepth allows, so each +// is looked up. +func underID(allOfEntryValue allOfEntry, entrySchema *statement.Schema, wrappers map[jsontext.Pointer]bool) bool { + if writesIdentifier(entrySchema) { + return true + } + p := string(allOfEntryValue.pointer) + for i := strings.LastIndexByte(p, '/'); i > 0; i = strings.LastIndexByte(p[:i], '/') { + if wrappers[jsontext.Pointer(p[:i])] { + return true + } + } + return false +} + +// writesIdentifier reports whether schema writes `$id`, or `id`, draft 4's +// spelling of it. Either may name a resource, and the base a lookup returns +// says whether it does, so one that names none costs that lookup alone. +func writesIdentifier(schema *statement.Schema) bool { + return hasKey(schema, "$id") || hasKey(schema, "id") +} + +// foldsReference reports whether what entrySchema folds writes a relative $ref, +// the one text a base changes: an entry writing none in it says the same at any +// base. +func foldsReference(loweringContext lowering.Ctx, entrySchema *statement.Schema) bool { + return slices.ContainsFunc(entrySchema.Keys, func(key statement.Key) bool { + entry, fold := foldKey(loweringContext, entrySchema, key.Name) + return fold && annotation.WritesReference(foldValue(loweringContext, entrySchema, entry).raw) + }) +} + +// readsAtPosition reports whether the inline allOf entry e reads its $refs +// against the base the position holding the allOf does, so what it writes means +// there what it means where it is written: an identifier at or above it naming +// another URI gives the same spelling another schema. The position is e's site +// less e's path from it, as the allOf may be read where a $ref landed. A base +// the bindings cannot tell is no match. +func readsAtPosition(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) bool { + site, placed := siteOf(allOfEntryValue.schema.Schema) + at := reftable.DocumentPointer{Doc: site.Doc, Pointer: jsontext.Pointer(strings.TrimSuffix(string(site.Pointer), string(allOfEntryValue.pointer)))} + own, known := loweringContext.Bindings().Table().Base(site) + position, knownAt := loweringContext.Bindings().Table().Base(at) + return placed && known && knownAt && own == position +} + +// disagreedWhy words why an entry that would have folded is kept, as +// entryNamesValue names it: its keywords have homes, and what they say is what +// is in question. folded says it folds what its conjuncts agree on, which +// unreadKeywords then leaves out. +func disagreedWhy(unreadKeywords []string, entryNamesValue entryNames, folded bool) string { + outcome := "so nothing it writes folds" + if folded { + outcome = "so what they disagree on does not fold, though what they agree on does" + } + return "the conjuncts of this allOf disagree on a keyword " + entryNamesValue.this + " writes, " + outcome + "; " + + entryNamesValue.kept + " (" + strings.Join(unreadKeywords, ", ") + ") is kept verbatim under Unmodeled" +} + +// disagreed reports whether the unread keywords, what an entry that did not +// fold keeps of entrySchema, holds a keyword folding reads: allOfEntryFoldingOf +// passes over an entry for writing none or for a disagreement, and this tells +// them apart. +func disagreed(loweringContext lowering.Ctx, entrySchema *statement.Schema, unreadKeywords []string) bool { + return slices.ContainsFunc(unreadKeywords, func(keyword string) bool { + _, fold := foldKey(loweringContext, entrySchema, keyword) + return fold + }) +} + +// folds reports whether an entry that folds consumes keyword: homes says which +// bounds the position has a field for, and a `nullable` folds where the null +// answer reads it for the conjunction, whichever object writes it +// (docs/compilers/openapi.md#nullable). +func folds(loweringContext lowering.Ctx, entrySchema *statement.Schema, keyword string, homes boundHomes) bool { + if keyword == "nullable" { + return declaresNullable(loweringContext, entrySchema) || loweringContext.NullableInference.Honours() && nullableRead(loweringContext, entrySchema) + } + if slices.Contains(valueConstraintKeywords, keyword) { + return (homes.textKeeps|homes.textIntersection.consumedFrom(entrySchema))&keyBit(keyword) != 0 || taken(conjunctTakes(homes.value, entrySchema), keyword) + } + _, fold := foldKey(loweringContext, entrySchema, keyword) + switch { + case slices.Contains(collectionBoundKeywords, keyword): + return fold && homes.collection + case slices.Contains(itemsGroup, keyword): + return homes.elements + case keyword == "format": + return homes.format || annotation.DeclaresRedaction(entrySchema) + case slices.Contains(contentKeywords, keyword): + return homes.content + } + return fold +} + +// itemsGroup is the keywords a List or a Tuple reads its elements off, one +// group, as lowerArray reads them off one conjunct (elementConjunct). +var itemsGroup = []string{"items", "prefixItems", "additionalItems"} + +// declaresNullable reports whether entrySchema's `nullable: true` adds null to +// its `type` as a declared fact (declaredTypeAnswer), which the null answer +// reads into the conjunction whatever the policy, so it is never left unread. +func declaresNullable(loweringContext lowering.Ctx, entrySchema *statement.Schema) bool { + return definesNullableFor(loweringContext, entrySchema) && writesType(entrySchema) && nullableTrue(entrySchema) +} + +// positionFlattenedEntries returns the flattened entries of schema, written at +// pointer, as a reader of what the position holds takes them, target being what +// the position lowered to. An entry whose own node that is, the alias a $ref +// principal writing keywords beside it sits at its entry, keeps what it writes +// there. +func positionFlattenedEntries(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef) []annotation.FlattenedAllOfEntry { + if !allOfDecides(loweringContext, schema) { + return nil + } + comp := allOfEntries(loweringContext, schema, pointer) + var out []annotation.FlattenedAllOfEntry + for i, speaks := range allOfEntryFoldingOf(loweringContext, schema).entryFoldsIntoPosition { + entry := comp.entries[i] + if !speaks || LoweredToOwnNode(loweringContext, entry.pointer, target) { + continue + } + flattenedAllOfEntry := flattenedEntryAt(loweringContext, foldingNode(loweringContext, schema, i, entry.schema.Schema), entry.pointer) + // The entry keeps a `dependencies` that does not fold (entryKeeps). + flattenedAllOfEntry.Dependencies = flattenedAllOfEntry.Dependencies && !foldsNoDependencies(loweringContext, schema, pointer) + out = append(out, flattenedAllOfEntry) + } + return out +} + +// flattenedEntryAt returns the flattened entry of node, written at at, which +// reads its `dependencies` in the dialect node is written in, as a fold of it +// does (TwinKeyword): an allOf entry naming a draft by its own `$schema` keeps +// the draft's keyword beside a position read in 2020-12, as the same schema +// written flat in the draft keeps it +// (docs/compilers/openapi.md#dialect-keywords). +func flattenedEntryAt(loweringContext lowering.Ctx, node *statement.Schema, at jsontext.Pointer) annotation.FlattenedAllOfEntry { + return annotation.FlattenedAllOfEntry{Node: node, At: at, Dependencies: rulesOf(loweringContext, node).Defines("dependencies")} +} + +// lendingEntries returns the entries of schema that fold, each at its pointer +// below it, for a use reading what schema lends it, but those writing only +// what schema or such an entry before them writes: the conjuncts of a keyword a +// use reads agree (allOfEntryFoldingOf), so a reader taking the nearest takes +// the same value from any of them, and a use pays for each keyword once, not +// for each entry repeating it. Bounds, which agree by intersecting, are no such +// keyword: a use never reads them through its $ref. +func lendingEntries(loweringContext lowering.Ctx, schema *statement.Schema) []allOfEntry { + if !allOfDecides(loweringContext, schema) { + return nil + } + comp := allOfEntries(loweringContext, schema, "") + var out []allOfEntry + for i, addsKeyword := range allOfEntryFoldingOf(loweringContext, schema).addsKeywordNoEarlierEntryWrites { + if addsKeyword { + entry := comp.entries[i] + entry.schema = loweringContext.Statements().Read(foldingNode(loweringContext, schema, i, entry.schema.Schema)) + out = append(out, entry) + } + } + return out +} + +// declaresScoped reports whether a flattened entry writes what only the +// position can hold, as declaresPositionScoped asks of the schema written +// there. +func declaresScoped(loweringContext lowering.Ctx, flattenedEntries []annotation.FlattenedAllOfEntry) bool { + return slices.ContainsFunc(flattenedEntries, func(flattenedAllOfEntry annotation.FlattenedAllOfEntry) bool { + return declaresPositionScoped(loweringContext, flattenedAllOfEntry.Node, flattenedAllOfEntry.At) + }) +} + +// recordFlattenedEntryKeeps adds a pending keep of what binds a use that +// flattenedEntries, the flattened entries of schema written at pointer, write +// (recordUseBound), each reported at the keyword it wrote, each entry its own +// conjunct of the node, so the pending keeps keep one writing of what several +// write alike at the nearest. +func recordFlattenedEntryKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, pointer jsontext.Pointer, + flattenedEntries []annotation.FlattenedAllOfEntry, +) []ir.Diagnostic { + if len(flattenedEntries) == 0 { + return nil + } + comp := allOfEntries(loweringContext, schema, pointer) + diags := make([]ir.Diagnostic, 0, len(flattenedEntries)) + for _, flattenedAllOfEntry := range flattenedEntries { + site := flattenedEntrySite(loweringContext, schema, comp, flattenedAllOfEntry.At) + diags = append(diags, addUseBoundPendingKeeps(loweringContext, pendingKeeps, site, flattenedAllOfEntry.Node, flattenedAllOfEntry.At)...) + } + return diags +} diff --git a/compilers/openapi/internal/schema/voices_test.go b/compilers/openapi/internal/schema/allof_flattening_test.go similarity index 69% rename from compilers/openapi/internal/schema/voices_test.go rename to compilers/openapi/internal/schema/allof_flattening_test.go index 1968beac4..a2741d62a 100644 --- a/compilers/openapi/internal/schema/voices_test.go +++ b/compilers/openapi/internal/schema/allof_flattening_test.go @@ -17,15 +17,17 @@ import ( "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) -// foldedEntriesDoc is a document of Base, A and B, objects, Meta, an object +// flattenedEntriesDoc is a document of Base, A and B, objects, Meta, an object // anchored dynamically, Holder, an object using S through a $ref, and a // component S written as written. -func foldedEntriesDoc(written string) string { +func flattenedEntriesDoc(written string) string { return openapitest.ComponentSpecVer("3.1.0", " Base: {type: object, properties: {id: {type: string}}}\n"+ " A: {type: object, properties: {a: {type: string}}}\n"+ " B: {type: object, properties: {b: {type: string}}}\n"+ @@ -78,14 +80,14 @@ func TestAllOfEntryFolding_AKeywordFoldsWhereTheAllOfWouldKeepIt(t *testing.T) { "propertyNames": "propertyNames: {pattern: '^a'}", "a redaction": "format: password", } { - for shape, tc := range besideTheAllOf { + for shape, testCase := range besideTheAllOf { t.Run(shape+"/"+name, func(t *testing.T) { t.Parallel() ref := "{$ref: '#/components/schemas/Base'}" - want, wantDiags := parseFull(t, foldedEntriesDoc("{allOf: ["+ref+"], "+keyword+tc.beside+"}")) - got, gotDiags := parseFull(t, foldedEntriesDoc("{allOf: ["+ref+", {"+keyword+"}]"+tc.beside+"}")) - if tc.code != "" { - require.True(t, openapitest.HasDiagCodeAt(gotDiags, tc.code, "/components/schemas/S"+tc.at), + want, wantDiags := parseFull(t, flattenedEntriesDoc("{allOf: ["+ref+"], "+keyword+testCase.beside+"}")) + got, gotDiags := parseFull(t, flattenedEntriesDoc("{allOf: ["+ref+", {"+keyword+"}]"+testCase.beside+"}")) + if testCase.code != "" { + require.True(t, openapitest.HasDiagCodeAt(gotDiags, testCase.code, "/components/schemas/S"+testCase.at), "the outcome this row names; got %v", gotDiags) } assert.False(t, openapitest.HasDiagCodeAt(gotDiags, diag.DegradedConstruct, "/components/schemas/S/allOf/1"), @@ -137,18 +139,19 @@ func severityCodes(diags []ir.Diagnostic) []string { return out } -// TestFoldedAllOfEntries_KeptAndMetEntriesHoldAtEveryOutcome pins that what -// keeps an entry whole, or meets two, holds at each outcome besideTheAllOf -// names as it does alone (docs/compilers/openapi.md#allof-inline-residue): an -// entry disagreeing with a conjunct, or reading a $ref against another base, -// stays whole on each Model the composition lowers to, with one report saying -// why and nothing it writes folded, and two bounds meet there in either order. -func TestFoldedAllOfEntries_KeptAndMetEntriesHoldAtEveryOutcome(t *testing.T) { +// TestFlattenedAllOfEntries_KeptAndIntersectedEntriesHoldAtEveryOutcome pins +// that what keeps an entry whole, or intersects two, holds at each outcome +// besideTheAllOf names as it does alone +// (docs/compilers/openapi.md#allof-inline-residue): an entry disagreeing with a +// conjunct, or reading a $ref against another base, stays whole on each Model +// the composition lowers to, with one report saying why and nothing it writes +// folded, and two bounds intersect there in either order. +func TestFlattenedAllOfEntries_KeptAndIntersectedEntriesHoldAtEveryOutcome(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Base'}" const n = "\n N: {$id: 'https://ex.test/a/n.json', type: string}" // what `n.json` names under https://ex.test/a/ - met := &ir.Constraints{MaxProperties: new(int64(3))} - for name, tc := range map[string]struct { + intersection := &ir.Constraints{MaxProperties: new(int64(3))} + for name, testCase := range map[string]struct { entries string kept []string why string @@ -160,27 +163,32 @@ func TestFoldedAllOfEntries_KeptAndMetEntriesHoldAtEveryOutcome(t *testing.T) { "the conjuncts of this allOf disagree", nil}, "another base": {ref + ", {$id: 'https://ex.test/a/x.json', not: {$ref: 'n.json'}, description: d}", []string{"allOf/1"}, "reads its $refs against another base", nil}, - "bounds meeting": {ref + ", {maxProperties: 3}, {maxProperties: 5}", nil, "", met}, - "bounds meeting swapped": {ref + ", {maxProperties: 5}, {maxProperties: 3}", nil, "", met}, + "bounds meeting": {ref + ", {maxProperties: 3}, {maxProperties: 5}", nil, "", intersection}, + "bounds meeting swapped": {ref + ", {maxProperties: 5}, {maxProperties: 3}", nil, "", intersection}, } { for shape, outcome := range besideTheAllOf { t.Run(shape+"/"+name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, foldedEntriesDoc("{allOf: ["+tc.entries+"]"+outcome.beside+"}"+n)) + doc, diags := parseFull(t, flattenedEntriesDoc("{allOf: ["+testCase.entries+"]"+outcome.beside+"}"+n)) openapitest.RequireNoErrorDiags(t, diags) if outcome.code != "" { require.True(t, openapitest.HasDiagCodeAt(diags, outcome.code, "/components/schemas/S"+outcome.at), "the outcome this row names; got %v", diags) } - for _, path := range tc.kept { + for _, path := range testCase.kept { got := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S/"+path) - assert.Contains(t, got, tc.why, path) + assert.Contains(t, got, testCase.why, path) } assert.Empty(t, typeByName(doc, "S").Common().Docs.Description, "nothing a kept entry writes folds") + holder := typeByName(doc, "S") for _, model := range composedModels(t, doc) { - assert.ElementsMatch(t, tc.kept, keptEntries(model), model.ID) - assert.Equal(t, tc.cons, model.Constraints, model.ID) + if model.ID != holder.Common().ID { + // A distributed union keeps what its entries keep once, on itself. + assert.Empty(t, keptEntries(model), model.ID) + } + assert.Equal(t, testCase.cons, model.Constraints, model.ID) } + assert.ElementsMatch(t, testCase.kept, keptEntries(holder), holder.Common().ID) }) } } @@ -206,10 +214,10 @@ func composedModels(t *testing.T, doc *ir.Document) []*ir.Model { return out } -// keptEntries returns the path of each allOf entry m keeps whole. -func keptEntries(model *ir.Model) []string { +// keptEntries returns the path of each allOf entry node keeps whole. +func keptEntries(node ir.TypeDef) []string { var out []string - for key := range model.Unmodeled { + for key := range node.Common().Unmodeled { if path, ok := strings.CutPrefix(key, "openapi:"); ok && strings.HasPrefix(path, "allOf/") { out = append(out, path) } @@ -228,7 +236,7 @@ func TestAllOfEntryFolding_AFalseFlagAgreesWithATrue(t *testing.T) { "{deprecated: false}, {deprecated: true}", "{writeOnly: false}, {writeOnly: true}"} { t.Run(flags, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, foldedEntriesDoc("{allOf: ["+ref+", "+flags+"]}")) + doc, diags := parseFull(t, flattenedEntriesDoc("{allOf: ["+ref+", "+flags+"]}")) openapitest.RequireNoErrorDiags(t, diags) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) @@ -239,14 +247,14 @@ func TestAllOfEntryFolding_AFalseFlagAgreesWithATrue(t *testing.T) { } } -// TestFoldedAllOfEntries_AnEntryDisagreeingFoldsNothingInEveryOrder pins that a -// keyword two conjuncts write differently has no winner: the keywords beside -// the allOf stand, and each entry writing another value stays whole, whichever -// comes first. -func TestFoldedAllOfEntries_AnEntryDisagreeingFoldsNothingInEveryOrder(t *testing.T) { +// TestFlattenedAllOfEntries_AnEntryDisagreeingFoldsNothingInEveryOrder pins +// that a keyword two conjuncts write differently has no chosen one: the +// keywords beside the allOf remain, and each entry writing another value stays +// whole, whichever comes first, folding only what no conjunct writes otherwise. +func TestFlattenedAllOfEntries_AnEntryDisagreeingFoldsNothingInEveryOrder(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Base'}" - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string kept []string }{ @@ -270,45 +278,46 @@ func TestFoldedAllOfEntries_AnEntryDisagreeingFoldsNothingInEveryOrder(t *testin } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, foldedEntriesDoc(tc.schema)) + doc, diags := parseFull(t, flattenedEntriesDoc(testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) - var kept []string + kept := make([]string, 0, len(model.Unmodeled)) for key := range model.Unmodeled { kept = append(kept, key) } - assert.ElementsMatch(t, tc.kept, kept) + assert.ElementsMatch(t, testCase.kept, kept) // An entry holding validation logic alone is reported as that. reports := append(withCode(diags, diag.DegradedConstruct), withCode(diags, diag.ValidationOnlyKeyword)...) - assert.Len(t, reports, len(tc.kept)) + assert.Len(t, reports, len(testCase.kept)) }) } - // A disagreeing entry folds nothing, not only the keyword it disagrees on. - doc, diags := parseFull(t, foldedEntriesDoc("{allOf: ["+ref+", {description: a, title: only}, {description: b}]}")) + // A disagreeing entry folds what no conjunct writes otherwise, and only + // that: a keyword folds or not by its own conjuncts. + doc, diags := parseFull(t, flattenedEntriesDoc("{allOf: ["+ref+", {description: a, title: only}, {description: b}]}")) openapitest.RequireNoErrorDiags(t, diags) irModel, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) - assert.Empty(t, irModel.Docs.Summary) + assert.Equal(t, "only", irModel.Docs.Summary, "a keyword one conjunct alone writes folds") assert.Empty(t, irModel.Docs.Description, "no precedence chooses between two descriptions") } -// TestAllOfEntryFolding_BoundsMeetInEveryOrder pins value bounds two conjuncts -// write apart: they meet as a redeclared field's do, each taking what they say -// together, in either order. A writer stating no value, as a 3.0 exclusive -// modifier with no bound beside it or one of false, parts none (GitHub #1494): -// both fold, and the modifier that bounds nothing is kept and warned of at its -// own entry. A count folds into the model a Base declaring no type composes, -// and a numeric bound into the scalar a refinement of a number lowers to, the -// node of a kind that takes it. -func TestAllOfEntryFolding_BoundsMeetInEveryOrder(t *testing.T) { +// TestAllOfEntryFolding_BoundsIntersectInEveryOrder pins value bounds two +// conjuncts write apart: they intersect as a redeclared field's do, each taking +// what they say together, in either order. A conjunct stating no value, as a +// 3.0 exclusive modifier with no bound beside it or one of false, parts none +// (GitHub #1494): both fold, and the modifier that bounds nothing is kept and +// warned of at its own entry. A count folds into the model a Base declaring no +// type composes, and a numeric bound into the scalar a refinement of a number +// lowers to, the node of a kind that takes it. +func TestAllOfEntryFolding_BoundsIntersectInEveryOrder(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Base'}" const ( untyped = "{description: declares no type}" number = "{type: number}" ) - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { version, base, a, b string want *ir.Constraints }{ @@ -321,21 +330,21 @@ func TestAllOfEntryFolding_BoundsMeetInEveryOrder(t *testing.T) { "a 3.0 modifier beside one of false": {"3.0.3", number, "{minimum: 3, exclusiveMinimum: true}", "{exclusiveMinimum: false}", &ir.Constraints{ExclusiveMin: new(ir.BigVal("3"))}}, } { - for _, order := range [][2]string{{tc.a, tc.b}, {tc.b, tc.a}} { - doc, diags := parseFull(t, openapitest.ComponentSpecVer(tc.version, - " Base: "+tc.base+"\n S: {allOf: ["+ref+", "+order[0]+", "+order[1]+"]}\n")) + for _, order := range [][2]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer(testCase.version, + " Base: "+testCase.base+"\n S: {allOf: ["+ref+", "+order[0]+", "+order[1]+"]}\n")) openapitest.RequireNoErrorDiags(t, diags) node := typeByName(doc, "S") require.NotNil(t, node, name) - assert.Equal(t, tc.want, heldBounds(node), "%s: %v", name, order) + assert.Equal(t, testCase.want, heldBounds(node), "%s: %v", name, order) assert.Empty(t, node.Common().Unmodeled, "%s: %v", name, order) } } - doc, _ := parseFull(t, foldedEntriesDoc("{maxProperties: 3, allOf: ["+ref+", {maxProperties: 5}]}")) + doc, _ := parseFull(t, flattenedEntriesDoc("{maxProperties: 3, allOf: ["+ref+", {maxProperties: 5}]}")) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) - assert.Equal(t, &ir.Constraints{MaxProperties: new(int64(3))}, model.Constraints, "a bound beside the allOf meets one on an entry") + assert.Equal(t, &ir.Constraints{MaxProperties: new(int64(3))}, model.Constraints, "a bound beside the allOf intersects one on an entry") assert.Empty(t, model.Unmodeled) for i, order := range []string{"{exclusiveMinimum: true}, {exclusiveMinimum: false}", "{exclusiveMinimum: false}, {exclusiveMinimum: true}"} { @@ -353,14 +362,14 @@ func TestAllOfEntryFolding_BoundsMeetInEveryOrder(t *testing.T) { } } -// TestFoldedAllOfEntries_ABoundTheComposedModelCannotTakeKeepsItsEntry pins a +// TestFlattenedAllOfEntries_ABoundTheComposedModelCannotTakeKeepsItsEntry pins a // value bound written beside a Base declaring an object: the allOf lowers to a // model, which takes property counts alone, so it holds the count written // beside the allOf and keeps the string bound there under its keyword, and the // numeric bound each inline entry writes under its own, each with one info at // its entry, in either order of the entries // (docs/compilers/openapi.md#constraints). -func TestFoldedAllOfEntries_ABoundTheComposedModelCannotTakeKeepsItsEntry(t *testing.T) { +func TestFlattenedAllOfEntries_ABoundTheComposedModelCannotTakeKeepsItsEntry(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Base'}" for _, order := range [][2]string{{"{multipleOf: 4}", "{maximum: 9}"}, {"{maximum: 9}", "{multipleOf: 4}"}} { @@ -385,13 +394,13 @@ func TestFoldedAllOfEntries_ABoundTheComposedModelCannotTakeKeepsItsEntry(t *tes } } -// TestAllOfEntryFolding_ARefusedBoundPartsNoWriter pins a bound beside one the -// rule table refuses, in either order (GitHub #1494): the refused value states -// nothing, so both entries fold, the stated bound reaches the node, and the -// refusal is reported once, at the keyword, as it is beside the allOf. Base is -// a number, so the node the entries fold into, a scalar over it, takes the +// TestAllOfEntryFolding_ARefusedBoundPartsNoConjunct pins a bound beside one +// the rule table refuses, in either order (GitHub #1494): the refused value +// states nothing, so both entries fold, the stated bound reaches the node, and +// the refusal is reported once, at the keyword, as it is beside the allOf. Base +// is a number, so the node the entries fold into, a scalar over it, takes the // bound. -func TestAllOfEntryFolding_ARefusedBoundPartsNoWriter(t *testing.T) { +func TestAllOfEntryFolding_ARefusedBoundPartsNoConjunct(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Base'}" for i, order := range []string{"{exclusiveMinimum: 5}, {exclusiveMinimum: true}", "{exclusiveMinimum: true}, {exclusiveMinimum: 5}"} { @@ -412,7 +421,7 @@ func TestAllOfEntryFolding_ARefusedBoundPartsNoWriter(t *testing.T) { // conjuncts write alike is one statement: it folds, once. func TestAllOfEntryFolding_AgreeingConjunctsSayItOnce(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, foldedEntriesDoc("{description: same, example: {id: a}, allOf: ["+ + doc, diags := parseFull(t, flattenedEntriesDoc("{description: same, example: {id: a}, allOf: ["+ "{$ref: '#/components/schemas/Base'}, {description: same, example: {id: a}}, {description: same}]}")) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, withCode(diags, diag.DegradedConstruct)) @@ -429,7 +438,7 @@ func TestAllOfEntryFolding_AgreeingConjunctsSayItOnce(t *testing.T) { func TestAllOfEntryFolding_ANullKeywordWritesNothing(t *testing.T) { t.Parallel() for _, entries := range []string{"{description: null}, {description: d}", "{description: d}, {description: null}"} { - doc, _ := parseFull(t, foldedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base'}, "+entries+"]}")) + doc, _ := parseFull(t, flattenedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base'}, "+entries+"]}")) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok, entries) assert.Equal(t, "d", model.Docs.Description, entries) @@ -445,7 +454,7 @@ func TestAllOfEntryFolding_ANullKeywordWritesNothing(t *testing.T) { func TestAllOfEntryFolding_ADisagreementIsReportedAsOne(t *testing.T) { t.Parallel() const disagreed = "the conjuncts of this allOf disagree on a keyword this inline entry writes" - for name, tc := range map[string]struct{ schema, unsaid string }{ + for name, testCase := range map[string]struct{ schema, unsaid string }{ "a composition": { "{allOf: [{$ref: '#/components/schemas/Obj'}, {description: one}, {description: two}]}", "nothing reads", }, @@ -456,17 +465,19 @@ func TestAllOfEntryFolding_ADisagreementIsReportedAsOne(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() _, diags := parseFull(t, openapitest.ComponentSpec( - " Obj: {type: object}\n Str: {type: string}\n T: "+tc.schema+"\n")) + " Obj: {type: object}\n Str: {type: string}\n T: "+testCase.schema+"\n")) for _, at := range []string{"/components/schemas/T/allOf/1", "/components/schemas/T/allOf/2"} { got := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at) assert.Contains(t, got, disagreed) - assert.NotContains(t, got, tc.unsaid) + assert.NotContains(t, got, testCase.unsaid) } }) } - _, diags := parseFull(t, openapitest.ComponentSpec( - " Str: {type: string}\n T: {allOf: [{$ref: '#/components/schemas/Str'}, {format: uuid}, {description: d}]}\n")) + // A format beside a $ref to a string carrying an encoding of another name + // is kept, as a nearer Encoding would replace the target's. + _, diags := parseFull(t, openapitest.ComponentSpec(" Str: {type: string, format: x-other}\n"+ + " T: {allOf: [{$ref: '#/components/schemas/Str'}, {format: x-fmt}, {description: d}]}\n")) got := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/T/allOf/1") assert.Contains(t, got, "has no home for format written on this inline entry", "nothing was disagreed on") @@ -477,17 +488,18 @@ func TestAllOfEntryFolding_ADisagreementIsReportedAsOne(t *testing.T) { _, diags = parseFull(t, openapitest.ComponentSpec(" Obj: {type: object}\n"+ " T: {allOf: [{$ref: '#/components/schemas/Obj'}, {nullable: true, properties: {a: {type: string}}}]}\n")) - got = openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/T/allOf/1") - assert.NotContains(t, got, disagreed, "an entry that folds keeps what it declares of a shape, disagreed on by nothing") + got = openapitest.DiagMessageAt(t, diags, diag.UnwidenedNullable, ir.SeverityWarning, "/components/schemas/T/allOf/1/nullable") + assert.NotContains(t, got, disagreed, "an entry's nullable the policy reads, disagreed on by nothing, folds and says what it admits") deep := "{description: deep, allOf: [{type: object}]}" for range statement.MaxFlattenDepth { deep = "{allOf: [" + deep + "]}" } _, diags = parseFull(t, openapitest.ComponentSpec(" T: {description: top, allOf: ["+deep+"]}\n")) - kept := withCode(diags, diag.DegradedConstruct) - require.NotEmpty(t, kept) - assert.Contains(t, kept[0].Message, "nested past the flattening depth", "a capped entry says so first") + depth := slices.ContainsFunc(withCode(diags, diag.DegradedConstruct), func(diagnostic ir.Diagnostic) bool { + return strings.Contains(diagnostic.Message, "nested past the flattening depth") + }) + assert.True(t, depth, "a capped entry says so: %+v", diags) } // TestAllOfEntryFolding_AnExampleRenderingNothingStillAgrees pins that a @@ -496,7 +508,7 @@ func TestAllOfEntryFolding_ADisagreementIsReportedAsOne(t *testing.T) { // with nothing. func TestAllOfEntryFolding_AnExampleRenderingNothingStillAgrees(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, foldedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base'}, "+ + doc, diags := parseFull(t, flattenedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base'}, "+ "{example: null, description: d}, {example: null}]}")) for _, at := range []string{"/components/schemas/S/allOf/1", "/components/schemas/S/allOf/2"} { assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, at), at) @@ -508,16 +520,22 @@ func TestAllOfEntryFolding_AnExampleRenderingNothingStillAgrees(t *testing.T) { } // TestAllOfEntryFolding_AValueThatWillNotRenderAgreesWithNothing pins two -// entries writing one value no JSON holds: neither can be shown to say what the -// other does, so neither folds, and each is reported as the whole entry it -// could not keep. +// entries writing one value no JSON holds under a key no dialect defines: +// neither can be shown to say what the other does, so neither folds, and each +// is refused at its keyword. An extension no JSON holds is left out wherever +// it is kept, so two entries writing one fold as their twin without it does, +// agreeing on the rest. func TestAllOfEntryFolding_AValueThatWillNotRenderAgreesWithNothing(t *testing.T) { t.Parallel() - const bad = "{x-t: " + unpreservableValue + "}" - _, diags := parseFull(t, foldedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base'}, "+bad+", "+bad+"]}")) - for _, at := range []string{"/components/schemas/S/allOf/1", "/components/schemas/S/allOf/2"} { - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, at), at) - } + const bad = "{foo: " + unpreservableValue + "}" + _, diags := parseFull(t, flattenedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base'}, "+bad+", "+bad+"]}")) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/S/allOf/1/foo", "/components/schemas/S/allOf/2/foo"}, + openapitest.PointersOf(diags, diag.UnpreservableConstruct)) + + const extension = "{description: d" + unconvertibleExtension + "}" + doc := requireKeptWithoutExtension(t, parseFull, flattenedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base'}, "+extension+", "+extension+"]}"), + unconvertibleExtension, "/components/schemas/S/allOf/1", "/components/schemas/S/allOf/2") + assert.Equal(t, "d", typeByName(doc, "S").Common().Docs.Description, "the entries agree on the rest, so they fold") } // TestAllOfEntryFolding_KeywordsOneEntryHoldsDisagreeAsOne pins the keywords a @@ -535,40 +553,40 @@ func TestAllOfEntryFolding_KeywordsOneEntryHoldsDisagreeAsOne(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, _ := parseFull(t, foldedEntriesDoc("{allOf: ["+ref+", "+entries+"]}")) + doc, _ := parseFull(t, flattenedEntriesDoc("{allOf: ["+ref+", "+entries+"]}")) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) assert.NotContains(t, model.Unmodeled, "openapi:if-then-else") assert.NotContains(t, model.Unmodeled, "openapi:contains") }) } - doc, diags := parseFull(t, foldedEntriesDoc("{allOf: ["+ref+", {if: {required: [a]}}, {if: {required: [a]}}]}")) + doc, diags := parseFull(t, flattenedEntriesDoc("{allOf: ["+ref+", {if: {required: [a]}}, {if: {required: [a]}}]}")) openapitest.RequireNoErrorDiags(t, diags) irModel, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) assert.Contains(t, irModel.Unmodeled, "openapi:if-then-else") } -// TestFoldedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry pins that no +// TestFlattenedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry pins that no // unevaluated keyword folds: on an entry it applies to what that entry alone // evaluates, which beside the allOf it would not, so it stays with the entry // kept whole, whatever its form, whether or not the entry speaks for the // position, and the position keeps none of it. -func TestFoldedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry(t *testing.T) { +func TestFlattenedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Base'}" for name, entry := range map[string]string{ - "a closure": "{unevaluatedProperties: false}", - "a closure beside what folds": "{description: d, unevaluatedProperties: false}", - "a schema": "{unevaluatedProperties: {type: string}}", - "a schema beside what folds": "{description: d, unevaluatedProperties: {type: string}}", - "items": "{unevaluatedItems: false}", - "items beside what folds": "{description: d, unevaluatedItems: false}", - "inert beside its catch-all": "{description: d, additionalProperties: true, unevaluatedProperties: false}", - "inert beside its items": "{description: d, items: true, unevaluatedItems: false}", - "both": "{description: d, unevaluatedProperties: false, unevaluatedItems: true}", + "a closure": "{unevaluatedProperties: false}", + "a closure beside what folds": "{description: d, unevaluatedProperties: false}", + "a schema": "{unevaluatedProperties: {type: string}}", + "a schema beside what folds": "{description: d, unevaluatedProperties: {type: string}}", + "items": "{unevaluatedItems: false}", + "items beside what folds": "{description: d, unevaluatedItems: false}", + "saying nothing beside its catch-all": "{description: d, additionalProperties: true, unevaluatedProperties: false}", + "saying nothing beside its items": "{description: d, items: true, unevaluatedItems: false}", + "both": "{description: d, unevaluatedProperties: false, unevaluatedItems: true}", } { - for shape, tc := range map[string]struct{ schema, at string }{ + for shape, testCase := range map[string]struct{ schema, at string }{ "a model": {"{allOf: [" + ref + ", " + entry + "]}", "allOf/1"}, "a model, turned": {"{allOf: [" + entry + ", " + ref + "]}", "allOf/0"}, "a list": {"{type: array, allOf: [" + entry + "]}", "allOf/0"}, @@ -576,14 +594,14 @@ func TestFoldedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry(t *testing.T) } { t.Run(shape+"/"+name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, foldedEntriesDoc(tc.schema)) + doc, diags := parseFull(t, flattenedEntriesDoc(testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) common := typeByName(doc, "S").Common() - require.Contains(t, common.Unmodeled, "openapi:"+tc.at, "the entry is kept whole") + require.Contains(t, common.Unmodeled, "openapi:"+testCase.at, "the entry is kept whole") assert.NotContains(t, common.Unmodeled, "openapi:unevaluated", "the position keeps none of it") at := make([]ir.Diagnostic, 0, 1) for _, code := range []string{diag.ValidationOnlyKeyword, diag.DegradedConstruct} { - at = append(at, diagsAtPointer(diags, code, "/components/schemas/S/"+tc.at)...) + at = append(at, diagsAtPointer(diags, code, "/components/schemas/S/"+testCase.at)...) } require.Len(t, at, 1, "the entry's one report: nothing folds to be reported; got %v", diags) assert.Contains(t, at[0].Message, "the entry (", "the report is the entry's") @@ -598,7 +616,8 @@ func TestFoldedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry(t *testing.T) // TestAllOfEntryFolding_AUseBindingKeywordReachesItsCarrierOrItsNode pins // readOnly and default on an entry: a carrier holds them as beside the allOf, a // union distributed across it or not, and with no carrier a node the position -// owns keeps them verbatim, reported at the keyword. +// owns keeps them verbatim, two entries writing one alike at the nearest, +// reported at the position, as order alone tells the two apart. func TestAllOfEntryFolding_AUseBindingKeywordReachesItsCarrierOrItsNode(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Base: {type: object, properties: {id: {type: string}}} @@ -626,12 +645,12 @@ func TestAllOfEntryFolding_AUseBindingKeywordReachesItsCarrierOrItsNode(t *testi entry, ok := bare.Unmodeled["openapi:readOnly"] require.True(t, ok, "got %v", bare.Unmodeled) assert.Equal(t, "/components/schemas/Bare/allOf/1/readOnly", string(entry.Provenance.Pointer), "the nearest of the two") - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Bare/allOf/1/readOnly")) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Bare")) } -// TestFoldedAllOfEntries_APromotedExtensionReadsFromAnEntry pins a key the +// TestFlattenedAllOfEntries_APromotedExtensionReadsFromAnEntry pins a key the // promotion policy maps: on an entry it reads as it does beside the allOf. -func TestFoldedAllOfEntries_APromotedExtensionReadsFromAnEntry(t *testing.T) { +func TestFlattenedAllOfEntries_APromotedExtensionReadsFromAnEntry(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Base: {type: object, properties: {a: {type: string}}} Plain: {type: string} @@ -654,14 +673,14 @@ func TestFoldedAllOfEntries_APromotedExtensionReadsFromAnEntry(t *testing.T) { assert.Equal(t, "gone", property.Deprecation.Message) } -// TestAllOfEntryFolding_AnEntrysKeywordsBesideItsRefAreAFoldedEntry pins that +// TestAllOfEntryFolding_AnEntrysKeywordsBesideItsRefAreAFlattenedEntry pins that // what an allOf entry writes beside its $ref is a conjunct of the position, as // an inline entry is: it folds where it agrees with every other conjunct, and // where it disagrees neither folds and each entry is kept whole. The $ref is // the Base itself in both, with no node hoisted at the entry. -func TestAllOfEntryFolding_AnEntrysKeywordsBesideItsRefAreAFoldedEntry(t *testing.T) { +func TestAllOfEntryFolding_AnEntrysKeywordsBesideItsRefAreAFlattenedEntry(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, beside string kept []string description string @@ -669,22 +688,64 @@ func TestAllOfEntryFolding_AnEntrysKeywordsBesideItsRefAreAFoldedEntry(t *testin {"agreeing", "same", nil, "same"}, {"disagreeing", "beside", []string{"openapi:allOf/0", "openapi:allOf/1"}, ""}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() other := "same" - if tc.kept != nil { + if testCase.kept != nil { other = "other" } - doc, diags := parseFull(t, foldedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base', description: "+tc.beside+ + doc, diags := parseFull(t, flattenedEntriesDoc("{allOf: [{$ref: '#/components/schemas/Base', description: "+testCase.beside+ "}, {title: mine, description: "+other+"}]}")) openapitest.RequireNoErrorDiags(t, diags) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) require.NotNil(t, model.Base) assert.Equal(t, componentID("Base"), model.Base.Target, "the $ref is the Base itself") - assert.Equal(t, tc.description, model.Docs.Description) - assert.Equal(t, tc.kept, slices.Sorted(maps.Keys(model.Unmodeled))) + assert.Equal(t, testCase.description, model.Docs.Description) + assert.Equal(t, testCase.kept, slices.Sorted(maps.Keys(model.Unmodeled))) assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/S/allOf/0"), "no node at the entry") }) } } + +// TestAllOfEntryFolding_ATypedNullableIsReadUnderEitherPolicy holds a 3.0 +// entry's `nullable: true` beside its `type`, a declared fact, to the null +// reader's answer under either policy, never kept as unread: beside a +// description it admits null, and beside an entry or a $ref excluding null it +// does not with the policy off, nor beside the $ref with it on, where the entry +// writes properties. The policy's widening of the entry beside a string is +// marked inferred (docs/compilers/openapi.md#allof-inline-residue). +func TestAllOfEntryFolding_ATypedNullableIsReadUnderEitherPolicy(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpecVer("3.0.3", ` Obj: {type: object, properties: {s: {type: string}}} + Desc: {allOf: [{type: string, nullable: true}], description: d} + Two: {allOf: [{type: string, nullable: true}, {type: string}]} + Shaped: {allOf: [{$ref: '#/components/schemas/Obj'}, {type: object, nullable: true, properties: {f: {type: string}}}]} + Holder: + type: object + properties: + desc: {$ref: '#/components/schemas/Desc'} + two: {$ref: '#/components/schemas/Two'} + shaped: {$ref: '#/components/schemas/Shaped'} +`) + for _, off := range []bool{false, true} { + doc, diags := schema.LowerSpecWith(t, spec, lowering.Policy{NullableInference: lowering.NullableInference{Disabled: off}}) + openapitest.RequireNoErrorDiags(t, diags) + holder, ok := typeByName(doc, "Holder").(*ir.Model) + require.True(t, ok) + properties := openapitest.PropertiesByWire(holder.Properties) + for name, want := range map[string]ir.TypeRef{ + "desc": {Nullable: true}, + "two": {Nullable: !off, Inferred: map[bool]ir.Inferred{false: lowering.NullableInferenceHeuristic}[off]}, + "shaped": {}, + } { + label := fmt.Sprintf("%s off=%t", name, off) + assert.Equal(t, want.Nullable, properties[name].Type.Nullable, label) + assert.Equal(t, want.Inferred, properties[name].Type.Inferred, label) + component := strings.ToUpper(name[:1]) + name[1:] + assert.NotContains(t, typeByName(doc, component).Common().Unmodeled, "openapi:nullable", label) + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/"+component+"/allOf/0"), label) + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/"+component+"/allOf/1"), label) + } + } +} diff --git a/compilers/openapi/internal/schema/allof_internal_test.go b/compilers/openapi/internal/schema/allof_internal_test.go index 4dd292226..6061c2bbc 100644 --- a/compilers/openapi/internal/schema/allof_internal_test.go +++ b/compilers/openapi/internal/schema/allof_internal_test.go @@ -20,12 +20,12 @@ import ( // TestAllOfEntries_DepthCapKeepsWrapperVerbatim pins the bound on flattening: a // chain of wrappers as deep as the cap is flattened whole, and one level more -// leaves the wrapper at the cap verbatim under a key spelling its path, with the -// ref inside it unclassified and everything above it flattened. The diagnostic -// blames the depth, not allOf. +// cuts the read of the kinds, so the position is the top type keeping its +// allOf whole, beside the report at the wrapper at the cap, which blames the +// depth, not allOf. func TestAllOfEntries_DepthCapKeepsWrapperVerbatim(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name string wrappers int flat bool @@ -33,31 +33,36 @@ func TestAllOfEntries_DepthCapKeepsWrapperVerbatim(t *testing.T) { {"at the cap", statement.MaxFlattenDepth, true}, {"one past the cap", statement.MaxFlattenDepth + 1, false}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - var b strings.Builder - b.WriteString(" A: {type: object, properties: {a: {type: string}}}\n M:\n allOf:\n") - for i := range tc.wrappers { - b.WriteString(strings.Repeat(" ", i) + " - allOf:\n") + var builder strings.Builder + builder.WriteString(" A: {type: object, properties: {a: {type: string}}}\n M:\n allOf:\n") + for i := range testCase.wrappers { + builder.WriteString(strings.Repeat(" ", i) + " - allOf:\n") } - b.WriteString(strings.Repeat(" ", tc.wrappers) + " - {$ref: '#/components/schemas/A'}\n") + builder.WriteString(strings.Repeat(" ", testCase.wrappers) + " - {$ref: '#/components/schemas/A'}\n") - doc, diags := LowerSpec(t, openapitest.ComponentSpec(b.String())) + doc, diags := LowerSpec(t, openapitest.ComponentSpec(builder.String())) openapitest.RequireNoErrorDiags(t, diags) - model, ok := doc.Types[ir.TypeID("type/openapi/components/schemas/M")].(*ir.Model) - require.True(t, ok, "M should be a model") - if tc.flat { + node := doc.Types[ir.TypeID("type/openapi/components/schemas/M")] + if testCase.flat { + model, ok := node.(*ir.Model) + require.True(t, ok, "M should be a model") require.NotNil(t, model.Base, "the ref at the bottom is classified") assert.Equal(t, ir.TypeID("type/openapi/components/schemas/A"), model.Base.Target) assert.Empty(t, model.Unmodeled) return } - assert.Nil(t, model.Base, "the ref sits inside the wrapper kept verbatim") + top, ok := node.(*ir.Scalar) + require.True(t, ok, "M is the top type; got %T", node) + require.NotNil(t, top.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveAny), top.Base.Target) + entry, ok := top.Unmodeled["openapi:allOf"] + require.True(t, ok, "the allOf is kept whole; got %v", top.Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) + assert.Equal(t, jsontext.Pointer("/components/schemas/M/allOf"), entry.Provenance.Pointer) + assert.Len(t, top.Unmodeled, 1) path := strings.TrimSuffix(strings.Repeat("allOf/0/", statement.MaxFlattenDepth+1), "/") - entry, ok := model.Unmodeled["openapi:"+path] - require.True(t, ok, "the wrapper at the cap is kept under its path; got %v", model.Unmodeled) - assert.Equal(t, jsontext.Pointer("/components/schemas/M/"+path), entry.Provenance.Pointer) - assert.Len(t, model.Unmodeled, 1) message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/M/"+path) assert.Equal(t, "inline allOf entry is nested past the flattening depth of "+strconv.Itoa(statement.MaxFlattenDepth)+ @@ -120,8 +125,8 @@ func TestAllOfRefEntries_StopsWhenTheConsumerDoes(t *testing.T) { `)) schema := StatedIn(lowerer, componentSchema(t, lowerer, "M")) var all []*statement.Statement - for b := range allOfRefEntries(lowerer.Ctx, schema) { - all = append(all, b) + for branch := range allOfRefEntries(lowerer.Ctx, schema) { + all = append(all, branch) } require.Len(t, all, 2, "the nested $ref and the one beside it") assert.Equal(t, StatedIn(lowerer, componentSchema(t, lowerer, "A")), refBranchTarget(lowerer.Ctx, all[0])) @@ -136,41 +141,55 @@ func TestAllOfRefEntries_StopsWhenTheConsumerDoes(t *testing.T) { } // TestAllOfEntries_DepthCapNamesWhatElseTheWrapperWrites pins that a wrapper -// kept at the cap lists the keywords it writes besides allOf, so the message -// says both why it was kept and what rides along. A wrapper whose type is not an -// object reads as a warning, which names the depth as well. +// at the cap lists the keywords it writes besides allOf, so the message says +// both why it was kept and what rides along, whatever kind it writes: no +// composed model asserts an object past the cap, so a wrapper writing a string +// draws the same info. func TestAllOfEntries_DepthCapNamesWhatElseTheWrapperWrites(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name string sibling string + code string severity ir.Severity want string }{ - {"a keyword nothing reads", "minItems: 1", ir.SeverityInfo, "the entry (minItems) is kept verbatim"}, - {"non-object type", "type: string", ir.SeverityWarning, "the entry (type) is kept verbatim"}, + {"a keyword nothing reads", "minItems: 1", diag.DegradedConstruct, ir.SeverityInfo, "the entry (minItems) is kept verbatim"}, + {"non-object type", "type: string", diag.DegradedConstruct, ir.SeverityInfo, "the entry (type) is kept verbatim"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - var b strings.Builder - b.WriteString(" A: {type: object, properties: {a: {type: string}}}\n M:\n allOf:\n") + var builder strings.Builder + builder.WriteString(" A: {type: object, properties: {a: {type: string}}}\n M:\n allOf:\n") for i := range statement.MaxFlattenDepth { - b.WriteString(strings.Repeat(" ", i) + " - allOf:\n") + builder.WriteString(strings.Repeat(" ", i) + " - allOf:\n") } pad := strings.Repeat(" ", statement.MaxFlattenDepth) - b.WriteString(pad + " - " + tc.sibling + "\n" + pad + " allOf:\n" + + builder.WriteString(pad + " - " + testCase.sibling + "\n" + pad + " allOf:\n" + pad + " - {$ref: '#/components/schemas/A'}\n") - _, diags := LowerSpec(t, openapitest.ComponentSpec(b.String())) + _, diags := LowerSpec(t, openapitest.ComponentSpec(builder.String())) openapitest.RequireNoErrorDiags(t, diags) path := strings.TrimSuffix(strings.Repeat("allOf/0/", statement.MaxFlattenDepth+1), "/") - message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, - tc.severity, "/components/schemas/M/"+path) + message := openapitest.DiagMessageAt(t, diags, testCase.code, + testCase.severity, "/components/schemas/M/"+path) assert.Contains(t, message, "nested past the flattening depth of "+strconv.Itoa(statement.MaxFlattenDepth)) assert.Contains(t, message, "was not flattened") - assert.Contains(t, message, tc.want) + assert.Contains(t, message, testCase.want) assert.NotContains(t, message, "allOf)", "allOf is not listed as a kept keyword") assert.NotContains(t, message, ", allOf") }) } } + +// TestKeptKeywords_OnlyACappedEntryLeavesItsAllOfOut holds the keywords a +// report names an entry it keeps by: what the entry leaves as written, but +// for one nested past the flattening depth, kept for its depth, whose allOf +// the merge does not decline and is not named. +func TestKeptKeywords_OnlyACappedEntryLeavesItsAllOfOut(t *testing.T) { + t.Parallel() + unreadKeywords := []string{"type", "allOf"} + assert.Equal(t, unreadKeywords, keptKeywords(unreadKeywords, allOfEntry{})) + assert.Equal(t, []string{"type"}, keptKeywords(unreadKeywords, allOfEntry{capped: true})) + assert.Equal(t, []string{"type", "allOf"}, unreadKeywords, "the unread keywords are left as written") +} diff --git a/compilers/openapi/internal/schema/allof_loop_test.go b/compilers/openapi/internal/schema/allof_loop_test.go new file mode 100644 index 000000000..dbb93c7dc --- /dev/null +++ b/compilers/openapi/internal/schema/allof_loop_test.go @@ -0,0 +1,68 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestAllOf_ALoopBesideAnUntypedUnionComposesAsItsTwin holds a schema whose +// allOf names itself beside properties and a oneOf whose branches name no +// kind: the kinds beside a loop of references are read outside every union, +// so it composes itself as its twin without the oneOf does, marked as the +// kind-inference policy's reading, and keeps and reports no $ref. +func TestAllOf_ALoopBesideAnUntypedUnionComposesAsItsTwin(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Self: + allOf: [{$ref: '#/components/schemas/Self'}] + properties: {html: {type: string}, url: {type: string}} + oneOf: [{required: [html], properties: {html: {type: string}}}, {required: [url]}] + Bare: + allOf: [{$ref: '#/components/schemas/Bare'}] + properties: {html: {type: string}} +`)) + for _, name := range []string{"Self", "Bare"} { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s: got %T", name, typeByName(doc, name)) + require.NotNil(t, model.Base, name) + assert.Equal(t, componentID(name), model.Base.Target, "%s composes itself", name) + assert.NotContains(t, model.Unmodeled, "openapi:$ref", name) + assert.Equal(t, ir.Inferred("kind-inference"), model.Provenance.Inferred, name) + assert.Empty(t, reportsAt(diags, "/components/schemas/"+name+"/allOf/0"), name) + } +} + +// TestAllOf_ATypeNoDialectDefinesLowersAsItsFlatTwin holds a `type` word no +// dialect defines, which load reports and a schema writing it alone lowers to +// a Scalar over string: written on an allOf entry, alone or not, or beside the +// allOf, it admits that string, so the conjunction lowers as its flat twin +// does, and beside an object it shares no value with it, as a string does. +func TestAllOf_ATypeNoDialectDefinesLowersAsItsFlatTwin(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", ` Obj: {type: object, properties: {a: {type: string}}} + Flat: {type: file, description: d} + Entry: {allOf: [{type: file}, {description: d}]} + Alone: {allOf: [{type: file}], description: d} + Beside: {allOf: [{description: d}], type: file} + Apart: {type: widget, allOf: [{$ref: '#/components/schemas/Obj'}]} +`)) + flat, ok := typeByName(doc, "Flat").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "Flat")) + for _, name := range []string{"Entry", "Alone", "Beside"} { + scalar, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s: got %T", name, typeByName(doc, name)) + assert.Equal(t, flat.Base, scalar.Base, name) + assert.Equal(t, "d", scalar.Docs.Description, name) + assert.Empty(t, scalar.Unmodeled, name) + } + assert.Equal(t, []jsontext.Pointer{"/components/schemas/Apart"}, openapitest.PointersOf(diags, diag.UnsatisfiableSchema)) +} diff --git a/compilers/openapi/internal/schema/allof_narrowing_test.go b/compilers/openapi/internal/schema/allof_narrowing_test.go index cf9144671..8f8967388 100644 --- a/compilers/openapi/internal/schema/allof_narrowing_test.go +++ b/compilers/openapi/internal/schema/allof_narrowing_test.go @@ -6,6 +6,8 @@ package schema_test import ( "encoding/json/jsontext" "fmt" + "maps" + "slices" "strings" "testing" @@ -30,14 +32,14 @@ func TestAllOf_AnInadmissibleBroadValueIsKeptInEitherOrder(t *testing.T) { const broad = " p: {type: number, default: 1.5}\n" const narrow = " p: {type: integer}\n" entry := " - type: object\n properties:\n" - for _, tc := range []struct{ name, first, second, broadPtr string }{ + for _, testCase := range []struct{ name, first, second, broadPtr string }{ {"broad first", broad, narrow, "/components/schemas/Ranged/allOf/0/properties/p"}, {"narrow first", narrow, broad, "/components/schemas/Ranged/allOf/1/properties/p"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" Ranged:\n allOf:\n"+ - entry+tc.first+entry+tc.second)) + entry+testCase.first+entry+testCase.second)) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("Ranged")].(*ir.Model) require.True(t, ok, "Ranged should be a model") @@ -49,8 +51,8 @@ func TestAllOf_AnInadmissibleBroadValueIsKeptInEitherOrder(t *testing.T) { require.Len(t, diags, 1, "one info and nothing else") assert.Equal(t, ir.SeverityInfo, diags[0].Severity) assert.Equal(t, diag.DegradedConstruct, diags[0].Code) - assert.Equal(t, jsontext.Pointer(tc.broadPtr), diags[0].Provenance.Pointer) - entry, ok := property.Unmodeled["openapi:conflicting-redeclaration"+tc.broadPtr] + assert.Equal(t, jsontext.Pointer(testCase.broadPtr), diags[0].Provenance.Pointer) + entry, ok := property.Unmodeled["openapi:conflicting-redeclaration"+testCase.broadPtr] require.True(t, ok, "the broad entry is kept at its own pointer; got %v", property.Unmodeled) assert.JSONEq(t, `{"type":"number","default":1.5}`, string(entry.Value)) assert.Len(t, property.Unmodeled, 1) @@ -67,14 +69,14 @@ func TestAllOf_ANullOnARefOverTheTopTypeIsKept(t *testing.T) { const withNull = " p: {$ref: '#/components/schemas/Y', default: null}\n" const plain = " p: {$ref: '#/components/schemas/Y'}\n" entry := " - type: object\n properties:\n" - for _, tc := range []struct{ name, first, second string }{ + for _, testCase := range []struct{ name, first, second string }{ {"null first", withNull, plain}, {"null second", plain, withNull}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" Y: {description: free}\n Held:\n allOf:\n"+ - entry+tc.first+entry+tc.second)) + entry+testCase.first+entry+testCase.second)) assert.Empty(t, diags, "nothing is refused") model, ok := doc.Types[componentID("Held")].(*ir.Model) require.True(t, ok, "Held should be a model") @@ -93,7 +95,7 @@ func TestAllOf_ANullOnARefOverTheTopTypeIsKept(t *testing.T) { // nothing kept. func TestAllOf_NonBareNarrowingIsOrderInvariant(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, extra, narrow, broad string kind ir.TypeKind }{ @@ -108,18 +110,18 @@ func TestAllOf_NonBareNarrowingIsOrderInvariant(t *testing.T) { {"a ref declared before the schema", " Id: {type: integer, format: int32}\n", "{$ref: '#/components/schemas/Id'}", "{type: integer}", ir.KindScalar}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() types := make([]ir.TypeDef, 0, 2) - for _, order := range [][2]string{{tc.narrow, tc.broad}, {tc.broad, tc.narrow}} { - doc, diags := schema.LowerSpec(t, nonBareSpec(tc.extra, order[0], order[1])) + for _, order := range [][2]string{{testCase.narrow, testCase.broad}, {testCase.broad, testCase.narrow}} { + doc, diags := schema.LowerSpec(t, nonBareSpec(testCase.extra, order[0], order[1])) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("T")].(*ir.Model) require.True(t, ok) require.Len(t, model.Properties, 1) property := model.Properties[0] types = append(types, doc.Types[property.Type.Target]) - assert.Equal(t, tc.kind, doc.Types[property.Type.Target].Kind(), "the narrower declaration's type wins") + assert.Equal(t, testCase.kind, doc.Types[property.Type.Target].Kind(), "the narrower declaration's type wins") assert.Empty(t, property.Unmodeled, "nothing is kept") for _, diagnostic := range diags { assert.NotContains(t, []string{diag.ConflictingRedecl, diag.DegradedConstruct}, diagnostic.Code, diagnostic.Message) @@ -128,7 +130,7 @@ func TestAllOf_NonBareNarrowingIsOrderInvariant(t *testing.T) { assert.Empty(t, cmp.Diff(types[0], types[1], cmpopts.IgnoreFields(ir.TypeCommon{}, "ID", "Name", "Provenance"), cmpopts.IgnoreFields(ir.EnumMember{}, "ID")), - "the winner does not depend on entry order") + "the chosen declaration does not depend on entry order") }) } } @@ -140,7 +142,7 @@ func TestAllOf_NonBareNarrowingIsOrderInvariant(t *testing.T) { func TestAllOf_AnUnknownFormatWinsInEitherOrder(t *testing.T) { t.Parallel() plain := "{type: string}" - formatted := "{type: string, format: hex-token, minLength: 8, default: x, description: the token}" + formatted := "{type: string, format: hex-token, minLength: 8, default: deadbeef, description: the token}" for i, order := range [][2]string{{plain, formatted}, {formatted, plain}} { doc, diags := schema.LowerSpec(t, nonBareSpec("", order[0], order[1])) openapitest.RequireNoErrorDiags(t, diags) @@ -151,7 +153,7 @@ func TestAllOf_AnUnknownFormatWinsInEitherOrder(t *testing.T) { assert.Equal(t, ir.KindScalar, doc.Types[property.Type.Target].Kind(), "the format's scalar types the field (order %d)", i) require.NotNil(t, property.Default, "order %d", i) - assert.Equal(t, "x", property.Default.String, "order %d", i) + assert.Equal(t, "deadbeef", property.Default.String, "order %d", i) assert.Nil(t, property.Constraints, "order %d", i) sc, ok := doc.Types[property.Type.Target].(*ir.Scalar) require.True(t, ok, "order %d", i) @@ -164,9 +166,10 @@ func TestAllOf_AnUnknownFormatWinsInEitherOrder(t *testing.T) { } } -// TestAllOf_TheTopTypeAndANullableKindMeetAsNullableInEitherOrder pins that `{}` -// against `type: [integer, "null"]` is a nullable integer whichever is first. -func TestAllOf_TheTopTypeAndANullableKindMeetAsNullableInEitherOrder(t *testing.T) { +// TestAllOf_TheTopTypeAndANullableKindIntersectAsNullableInEitherOrder pins +// that `{}` against `type: [integer, "null"]` is a nullable integer whichever +// is first. +func TestAllOf_TheTopTypeAndANullableKindIntersectAsNullableInEitherOrder(t *testing.T) { t.Parallel() top, nullable := "{}", `{type: [integer, "null"]}` for i, order := range [][2]string{{top, nullable}, {nullable, top}} { @@ -184,20 +187,20 @@ func TestAllOf_TheTopTypeAndANullableKindMeetAsNullableInEitherOrder(t *testing. } // TestAllOf_ADefaultTheNarrowerNodeRefusesIsKeptInEitherOrder pins that the -// broader declaration's default is judged against a winner that is not a bare -// primitive: one the enum does not admit is not adopted, and the declaration -// that wrote it is kept at its own pointer, whichever entry it is. +// broader declaration's default is judged against the chosen declaration that +// is not a bare primitive: one the enum does not admit is not adopted, and the +// declaration that wrote it is kept at its own pointer, whichever entry it is. func TestAllOf_ADefaultTheNarrowerNodeRefusesIsKeptInEitherOrder(t *testing.T) { t.Parallel() enum, broad := "{type: integer, enum: [1, 2]}", "{type: integer, default: 5}" - for i, tc := range []struct { + for i, testCase := range []struct { order [2]string kept string }{ {[2]string{enum, broad}, "/components/schemas/T/allOf/1/properties/v"}, {[2]string{broad, enum}, "/components/schemas/T/allOf/0/properties/v"}, } { - doc, diags := schema.LowerSpec(t, nonBareSpec("", tc.order[0], tc.order[1])) + doc, diags := schema.LowerSpec(t, nonBareSpec("", testCase.order[0], testCase.order[1])) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("T")].(*ir.Model) require.True(t, ok) @@ -207,19 +210,20 @@ func TestAllOf_ADefaultTheNarrowerNodeRefusesIsKeptInEitherOrder(t *testing.T) { assert.Equal(t, ir.KindEnum, doc.Types[property.Type.Target].Kind(), "the enum wins (order %d)", i) assert.Nil(t, property.Default, "the refused default is not adopted (order %d)", i) require.Len(t, property.Unmodeled, 1, "order %d", i) - assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+tc.kept, "order %d", i) + assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+testCase.kept, "order %d", i) require.Len(t, diags, 1, "order %d", i) assert.Equal(t, diag.DegradedConstruct, diags[0].Code, "order %d", i) assert.Equal(t, ir.SeverityInfo, diags[0].Severity, "order %d", i) } } -// TestAllOf_AWinnersConstraintsRefuseADefaultInEitherOrder pins that the -// winning node holds the broader declaration's default to its constraints as -// well as its kind: a string past a component's maxLength, or a list past its -// maxItems, is not adopted, and the declaration that wrote it is kept at its -// own pointer, whichever entry it is and wherever the component is declared. -func TestAllOf_AWinnersConstraintsRefuseADefaultInEitherOrder(t *testing.T) { +// TestAllOf_AChosenDeclarationsConstraintsRefuseADefaultInEitherOrder pins that +// the winning node holds the broader declaration's default to its constraints +// as well as its kind: a string past a component's maxLength, or a list past +// its maxItems, is not adopted, and the declaration that wrote it is kept at +// its own pointer, whichever entry it is and wherever the component is +// declared. +func TestAllOf_AChosenDeclarationsConstraintsRefuseADefaultInEitherOrder(t *testing.T) { t.Parallel() named := "{$ref: '#/components/schemas/C'}" lowerings := map[string]func(extra, a, b string) (*ir.Document, []ir.Diagnostic){ @@ -228,18 +232,18 @@ func TestAllOf_AWinnersConstraintsRefuseADefaultInEitherOrder(t *testing.T) { }, "declared after": func(extra, a, b string) (*ir.Document, []ir.Diagnostic) { return settledSpec(t, extra, a, b) }, } - for _, tc := range []struct{ name, component, broad string }{ + for _, testCase := range []struct{ name, component, broad string }{ {"a string past maxLength", " C: {type: string, maxLength: 3}\n", "{type: string, default: hello}"}, {"a list past maxItems", " C: {type: array, items: {type: integer, format: int32}, maxItems: 2}\n", "{type: array, items: {type: integer}, default: [1, 2, 3, 4]}"}, } { for where, lower := range lowerings { for _, order := range []struct{ a, b, kept string }{ - {named, tc.broad, "/components/schemas/T/allOf/1/properties/v"}, - {tc.broad, named, "/components/schemas/T/allOf/0/properties/v"}, + {named, testCase.broad, "/components/schemas/T/allOf/1/properties/v"}, + {testCase.broad, named, "/components/schemas/T/allOf/0/properties/v"}, } { - doc, diags := lower(tc.component, order.a, order.b) - at := tc.name + ", " + where + ", kept " + order.kept + doc, diags := lower(testCase.component, order.a, order.b) + at := testCase.name + ", " + where + ", kept " + order.kept openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("T")].(*ir.Model) require.True(t, ok, at) @@ -266,14 +270,14 @@ func TestAllOf_TwoEqualListsRefuseANullTheMergeDoesNotAdmit(t *testing.T) { t.Parallel() nullable := `{type: [array, "null"], items: {type: integer}, default: null}` plain := "{type: array, items: {type: integer}}" - for i, tc := range []struct { + for i, testCase := range []struct { order [2]string kept string }{ {[2]string{nullable, plain}, "/components/schemas/T/allOf/0/properties/v"}, {[2]string{plain, nullable}, "/components/schemas/T/allOf/1/properties/v"}, } { - doc, diags := schema.LowerSpec(t, nonBareSpec("", tc.order[0], tc.order[1])) + doc, diags := schema.LowerSpec(t, nonBareSpec("", testCase.order[0], testCase.order[1])) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("T")].(*ir.Model) require.True(t, ok) @@ -284,19 +288,19 @@ func TestAllOf_TwoEqualListsRefuseANullTheMergeDoesNotAdmit(t *testing.T) { assert.False(t, property.Type.Nullable, "order %d", i) assert.Nil(t, property.Default, "the refused null is not adopted (order %d)", i) require.Len(t, property.Unmodeled, 1, "order %d", i) - assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+tc.kept, "order %d", i) + assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration"+testCase.kept, "order %d", i) require.Len(t, diags, 1, "order %d", i) assert.Equal(t, diag.DegradedConstruct, diags[0].Code, "order %d", i) assert.Equal(t, ir.SeverityInfo, diags[0].Severity, "order %d", i) - assert.Equal(t, jsontext.Pointer(tc.kept), diags[0].Provenance.Pointer, "order %d", i) + assert.Equal(t, jsontext.Pointer(testCase.kept), diags[0].Provenance.Pointer, "order %d", i) } } // TestAllOf_IdenticalNodesAreOneType compiles a field written twice with the // same enum, const or format, in either order. Two inline copies are one type, // and a component wins over an inline copy of itself: no diagnostic and nothing -// kept. Two components declared alike are two types the source named apart: an -// info, with the later kept and the earlier's $ref kept verbatim. +// kept. Two components declared alike are one type too, the least, in either +// order: an info, with the other's $ref kept verbatim. func TestAllOf_IdenticalNodesAreOneType(t *testing.T) { t.Parallel() for _, body := range []string{ @@ -311,35 +315,35 @@ func TestAllOf_IdenticalNodesAreOneType(t *testing.T) { t.Parallel() extra := " P: " + body + "\n Q: " + body + "\n" p, q := "{$ref: '#/components/schemas/P'}", "{$ref: '#/components/schemas/Q'}" - for i, tc := range []struct { + for i, testCase := range []struct { order [2]string - win ir.TypeID // the type that stands + win ir.TypeID // the type taken same bool }{ {[2]string{body, body}, "type/anonymous/components/schemas/T/allOf/0/properties/v", true}, {[2]string{p, body}, componentID("P"), true}, {[2]string{body, p}, componentID("P"), true}, - {[2]string{p, q}, componentID("Q"), false}, + {[2]string{p, q}, componentID("P"), false}, {[2]string{q, p}, componentID("P"), false}, } { - doc, diags := schema.LowerSpec(t, nonBareSpec(extra, tc.order[0], tc.order[1])) + doc, diags := schema.LowerSpec(t, nonBareSpec(extra, testCase.order[0], testCase.order[1])) model, ok := doc.Types[componentID("T")].(*ir.Model) require.True(t, ok, "order %d", i) require.Len(t, model.Properties, 1, "order %d", i) property := model.Properties[0] - assert.Equal(t, tc.win, property.Type.Target, "order %d", i) - if tc.same { + assert.Equal(t, testCase.win, property.Type.Target, "order %d", i) + if testCase.same { assert.Empty(t, diags, "order %d", i) assert.Empty(t, property.Unmodeled, "order %d", i) } else { require.Len(t, diags, 1, "order %d", i) assert.Equal(t, diag.DegradedConstruct, diags[0].Code, "order %d", i) - assert.Len(t, property.Unmodeled, 1, "the earlier $ref is kept (order %d)", i) + assert.Len(t, property.Unmodeled, 1, "the other $ref is kept (order %d)", i) } for _, name := range []string{"P", "Q"} { - td, ok := doc.Types[componentID(name)] + typeDef, ok := doc.Types[componentID(name)] require.True(t, ok, "%s (order %d)", name, i) - for key, unmodeledEntry := range td.Common().Unmodeled { + for key, unmodeledEntry := range typeDef.Common().Unmodeled { assert.True(t, strings.HasPrefix(string(unmodeledEntry.Provenance.Pointer), "/components/schemas/"+name+"/"), "%s keeps where its %s came from, got %q (order %d)", name, key, unmodeledEntry.Provenance.Pointer, i) } @@ -352,38 +356,39 @@ func TestAllOf_IdenticalNodesAreOneType(t *testing.T) { // TestAllOf_ARefToAnInlineNodeIsDeclaredApart compiles a field redeclared as // a $ref to a node written inline elsewhere (X/properties/c), in either order. // That node was declared apart from the field, as a component is: it wins over -// an inline copy of itself, and against a $ref to its twin (X/properties/d) the -// pair is an info, with the later kept and the earlier's $ref kept verbatim. +// an inline copy of itself, and with a $ref to its twin (X/properties/d) it is +// one type, the least, in either order: an info, with the other's $ref kept +// verbatim. func TestAllOf_ARefToAnInlineNodeIsDeclaredApart(t *testing.T) { t.Parallel() const enum = "{type: string, enum: [a, b]}" extra := " X: {type: object, properties: {c: " + enum + ", d: " + enum + "}}\n" c, d := "{$ref: '#/components/schemas/X/properties/c'}", "{$ref: '#/components/schemas/X/properties/d'}" at := func(p string) ir.TypeID { return ir.TypeID("type/anonymous/components/schemas/X/properties/" + p) } - for i, tc := range []struct { + for i, testCase := range []struct { order [2]string win ir.TypeID same bool }{ {[2]string{c, enum}, at("c"), true}, {[2]string{enum, c}, at("c"), true}, - {[2]string{c, d}, at("d"), false}, + {[2]string{c, d}, at("c"), false}, {[2]string{d, c}, at("c"), false}, } { - doc, diags := schema.LowerSpec(t, nonBareSpec(extra, tc.order[0], tc.order[1])) + doc, diags := schema.LowerSpec(t, nonBareSpec(extra, testCase.order[0], testCase.order[1])) model, ok := doc.Types[componentID("T")].(*ir.Model) require.True(t, ok, "order %d", i) require.Len(t, model.Properties, 1, "order %d", i) property := model.Properties[0] - assert.Equal(t, tc.win, property.Type.Target, "order %d", i) - if tc.same { + assert.Equal(t, testCase.win, property.Type.Target, "order %d", i) + if testCase.same { assert.Empty(t, diags, "order %d", i) assert.Empty(t, property.Unmodeled, "order %d", i) continue } require.Len(t, diags, 1, "order %d", i) assert.Equal(t, diag.DegradedConstruct, diags[0].Code, "order %d", i) - assert.Len(t, property.Unmodeled, 1, "the earlier $ref is kept (order %d)", i) + assert.Len(t, property.Unmodeled, 1, "the other $ref is kept (order %d)", i) } } @@ -473,16 +478,16 @@ func TestAllOf_ARefToASiblingFieldIsDeclaredApart(t *testing.T) { } // TestAllOf_ATimeIsJudgedByItsGrammar pins the fold on a field one declaration -// writes as format: time, which lowers to a Scalar the table pairs with no kind: -// a full-time default is adopted and a const that is one narrows the field, -// while a value with no offset, another string format and an enum of no time -// are refused with a warning, and a node holding detail of its own meets the -// const in a literal holding it too. Each case is compiled in both entry -// orders. +// writes as format: time, which lowers to a Scalar the table pairs with no +// kind: a full-time default is adopted and a const that is one narrows the +// field, while a value with no offset, another string format and an enum of no +// time are refused with a warning, and a node holding detail of its own +// intersects the const in a literal holding it too. Each case is compiled in +// both entry orders. func TestAllOf_ATimeIsJudgedByItsGrammar(t *testing.T) { t.Parallel() const timed = "{type: string, format: time}" - for _, tc := range []struct { + for _, testCase := range []struct { name, a, b string kind ir.TypeKind // the field's type, or "" where the overlap keeps entry order def string // the field's default, or "" for none @@ -498,30 +503,30 @@ func TestAllOf_ATimeIsJudgedByItsGrammar(t *testing.T) { {"a full-time const beside detail", "{type: string, format: time, description: d}", `{const: "12:00:00Z"}`, ir.KindLiteral, "", ""}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - for _, order := range [][2]string{{tc.a, tc.b}, {tc.b, tc.a}} { + for _, order := range [][2]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { doc, diags := schema.LowerSpec(t, nonBareSpec("", order[0], order[1])) model, ok := doc.Types[componentID("T")].(*ir.Model) require.True(t, ok, "%v", order) require.Len(t, model.Properties, 1, "%v", order) property := model.Properties[0] - if tc.kind != "" { - assert.Equal(t, tc.kind, doc.Types[property.Type.Target].Kind(), "%v", order) + if testCase.kind != "" { + assert.Equal(t, testCase.kind, doc.Types[property.Type.Target].Kind(), "%v", order) } - if tc.def == "" { + if testCase.def == "" { assert.Nil(t, property.Default, "%v", order) } else if assert.NotNil(t, property.Default, "%v", order) { - assert.Equal(t, tc.def, property.Default.String, "%v", order) + assert.Equal(t, testCase.def, property.Default.String, "%v", order) } - if tc.code == "" { + if testCase.code == "" { assert.Empty(t, diags, "%v", order) assert.Empty(t, property.Unmodeled, "%v", order) continue } require.Len(t, diags, 1, "%v: %v", order, reported(diags)) - assert.Equal(t, tc.code, diags[0].Code, "%v", order) + assert.Equal(t, testCase.code, diags[0].Code, "%v", order) assert.Len(t, property.Unmodeled, 1, "the declaration not taken is kept (%v)", order) } }) @@ -537,7 +542,7 @@ func TestAllOf_ATimeIsJudgedByItsGrammar(t *testing.T) { func TestAllOf_ARedeclarationIsJudgedOnceTheComponentsHaveLowered(t *testing.T) { t.Parallel() p, q := "{$ref: '#/components/schemas/P'}", "{$ref: '#/components/schemas/Q'}" - for _, tc := range []struct { + for _, testCase := range []struct { name, pdecl, qdecl string items bool kind ir.TypeKind @@ -548,14 +553,14 @@ func TestAllOf_ARedeclarationIsJudgedOnceTheComponentsHaveLowered(t *testing.T) {"a string against an integer", "{type: string}", "{type: integer}", false, ir.KindScalar, diag.ConflictingRedecl}, {"enums declared alike as list items", "{type: string, enum: [a, b]}", "{type: string, enum: [a, b]}", true, ir.KindList, diag.DegradedConstruct}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() a, b := p, q - if tc.items { + if testCase.items { a, b = "{type: array, items: "+p+"}", "{type: array, items: "+q+"}" } - pq := " P: " + tc.pdecl + "\n Q: " + tc.qdecl + "\n" - qp := " Q: " + tc.qdecl + "\n P: " + tc.pdecl + "\n" + pq := " P: " + testCase.pdecl + "\n Q: " + testCase.qdecl + "\n" + qp := " Q: " + testCase.qdecl + "\n P: " + testCase.pdecl + "\n" for i, lower := range []func() (*ir.Document, []ir.Diagnostic){ func() (*ir.Document, []ir.Diagnostic) { return schema.LowerSpec(t, nonBareSpec(pq, a, b)) }, func() (*ir.Document, []ir.Diagnostic) { return settledSpec(t, pq, a, b) }, @@ -567,14 +572,14 @@ func TestAllOf_ARedeclarationIsJudgedOnceTheComponentsHaveLowered(t *testing.T) require.Len(t, model.Properties, 1, "order %d", i) property := model.Properties[0] - assert.Equal(t, tc.kind, doc.Types[property.Type.Target].Kind(), "order %d", i) - if tc.code == "" { + assert.Equal(t, testCase.kind, doc.Types[property.Type.Target].Kind(), "order %d", i) + if testCase.code == "" { assert.Empty(t, diags, "order %d", i) assert.Empty(t, property.Unmodeled, "order %d", i) continue } require.Len(t, diags, 1, "order %d", i) - assert.Equal(t, tc.code, diags[0].Code, "order %d", i) + assert.Equal(t, testCase.code, diags[0].Code, "order %d", i) assert.Len(t, property.Unmodeled, 1, "the losing declaration is kept (order %d)", i) } }) @@ -603,7 +608,7 @@ func TestAllOf_WhatAFieldKeepsOfItsDetailIsOrderFree(t *testing.T) { } require.Contains(t, property.Unmodeled, "openapi:x-foo", "order %v", order) - assert.Equal(t, ir.RawValue(later), property.Unmodeled["openapi:x-foo"].Value, "the later value stands") + assert.Equal(t, ir.RawValue(later), property.Unmodeled["openapi:x-foo"].Value, "the later value remains") assert.Contains(t, property.Unmodeled, "openapi:x-same") assert.Contains(t, property.Unmodeled, "openapi:conflicting-redeclaration/components/schemas/T/allOf/0/properties/v", "the other declaration is kept verbatim") @@ -617,14 +622,14 @@ func TestAllOf_WhatAFieldKeepsOfItsDetailIsOrderFree(t *testing.T) { } // TestAllOf_ContainerMembersAreJudgedAsFieldsAre pins that two lists' members -// get the verdict two fields of those types get. Enums sharing no value, one +// get the answer two fields of those types get. Enums sharing no value, one // list never empty, are a conflict; the same lists both admitting the empty one // overlap in it. Members judged only as a fallback for top-level fields were // once left unrelated, which the merge reported as a pair it does not compare. func TestAllOf_ContainerMembersAreJudgedAsFieldsAre(t *testing.T) { t.Parallel() stringSchema, number := "{type: array, items: {type: string, enum: [a]}%s}", "{type: array, items: {type: integer, enum: [1]}}" - for _, tc := range []struct { + for _, testCase := range []struct { name, min string code string sev ir.Severity @@ -632,13 +637,13 @@ func TestAllOf_ContainerMembersAreJudgedAsFieldsAre(t *testing.T) { {"one list never empty", ", minItems: 1", diag.ConflictingRedecl, ir.SeverityWarning}, {"both lists admitting the empty one", "", diag.DegradedConstruct, ir.SeverityInfo}, } { - for _, order := range [][2]string{{fmt.Sprintf(stringSchema, tc.min), number}, {number, fmt.Sprintf(stringSchema, tc.min)}} { + for _, order := range [][2]string{{fmt.Sprintf(stringSchema, testCase.min), number}, {number, fmt.Sprintf(stringSchema, testCase.min)}} { _, diags := schema.LowerSpec(t, nonBareSpec("", order[0], order[1])) - require.Len(t, diags, 1, "%s, order %v: %+v", tc.name, order, diags) - assert.Equal(t, tc.code, diags[0].Code, "%s, order %v", tc.name, order) - assert.Equal(t, tc.sev, diags[0].Severity, "%s, order %v", tc.name, order) - if tc.code == diag.DegradedConstruct { - assert.Contains(t, diags[0].Message, "whose values overlap", "%s, order %v", tc.name, order) + require.Len(t, diags, 1, "%s, order %v: %+v", testCase.name, order, diags) + assert.Equal(t, testCase.code, diags[0].Code, "%s, order %v", testCase.name, order) + assert.Equal(t, testCase.sev, diags[0].Severity, "%s, order %v", testCase.name, order) + if testCase.code == diag.DegradedConstruct { + assert.Contains(t, diags[0].Message, "whose values overlap", "%s, order %v", testCase.name, order) } } } @@ -662,11 +667,11 @@ func TestAllOf_PrimitiveNarrowingIsLosslessInEitherOrder(t *testing.T) { {"double and number", "{type: number}", "{type: number, format: double}", "type/primitive/float64"}, {"uuid and string", "{type: string}", "{type: string, format: uuid}", "type/primitive/uuid"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() var merged [2]ir.TypeRef - for i, spec := range []string{allOfConflictSpec(tc.broad, tc.narrow), allOfConflictSpec(tc.narrow, tc.broad)} { + for i, spec := range []string{allOfConflictSpec(testCase.broad, testCase.narrow), allOfConflictSpec(testCase.narrow, testCase.broad)} { doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, diags, "a narrowing draws no diagnostic (order %d)", i) @@ -674,7 +679,7 @@ func TestAllOf_PrimitiveNarrowingIsLosslessInEitherOrder(t *testing.T) { require.True(t, ok) require.Len(t, model.Properties, 1) property := model.Properties[0] - assert.Equal(t, tc.want, property.Type.Target, "the narrower target wins (order %d)", i) + assert.Equal(t, testCase.want, property.Type.Target, "the narrower target wins (order %d)", i) for key := range property.Unmodeled { assert.NotContains(t, key, "openapi:conflicting-redeclaration", "nothing is kept (order %d)", i) } @@ -704,7 +709,7 @@ func nonBareSpec(extra, schemaA, schemaB string) string { // broader list is adopted the same way. Nothing is kept or reported. func TestAllOf_EnumsAndListsNarrowToWhatTheyShare(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, broad, narrow string check func(t *testing.T, doc *ir.Document, target ir.TypeID) }{ @@ -744,32 +749,32 @@ func TestAllOf_EnumsAndListsNarrowToWhatTheyShare(t *testing.T) { assert.Contains(t, list.Unmodeled, "openapi:x-kept") }}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - for _, order := range [][2]string{{tc.broad, tc.narrow}, {tc.narrow, tc.broad}} { + for _, order := range [][2]string{{testCase.broad, testCase.narrow}, {testCase.narrow, testCase.broad}} { property, doc, diags := redeclared(t, order[0], order[1]) assert.Empty(t, diags, "%v", order) assert.Empty(t, property.Unmodeled, "%v", order) - tc.check(t, doc, property.Type.Target) + testCase.check(t, doc, property.Type.Target) } }) } } -// TestAllOf_EnumsSharingSomeValuesMeetInAnEnumOfThem pins the enum minted for -// two sharing only some values: it holds those, each member identified beneath -// it in the composed namespace, where irverify holds a member's ID. -func TestAllOf_EnumsSharingSomeValuesMeetInAnEnumOfThem(t *testing.T) { +// TestAllOf_EnumsSharingSomeValuesIntersectInAnEnumOfThem pins the enum minted +// for two sharing only some values: it holds those, each member identified +// beneath it in the composed namespace, where irverify holds a member's ID. +func TestAllOf_EnumsSharingSomeValuesIntersectInAnEnumOfThem(t *testing.T) { t.Parallel() property, doc, diags := redeclared(t, "{type: string, enum: [a, b]}", "{type: string, enum: [b, c]}") assert.Empty(t, diags) - require.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/1/properties/v"), property.Type.Target) + require.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/properties/v"), property.Type.Target) enum, ok := doc.Types[property.Type.Target].(*ir.Enum) require.True(t, ok) require.Len(t, enum.Members, 1) assert.Equal(t, "b", enum.Members[0].Value.String) - assert.Equal(t, ir.EnumMemberID("enum-member/composed/components/schemas/T/allOf/1/properties/v/string:b"), enum.Members[0].ID) + assert.Equal(t, ir.EnumMemberID("enum-member/composed/components/schemas/T/allOf/properties/v/string:b"), enum.Members[0].ID) assert.Empty(t, validated(t, doc), "the minted enum's members live where irverify holds them") declared, ok := doc.Types["type/anonymous/components/schemas/T/allOf/0/properties/v"].(*ir.Enum) require.True(t, ok) @@ -797,29 +802,32 @@ func TestAllOf_ADefaultIsJudgedByTheNodeTheFieldHolds(t *testing.T) { } } -// TestAllOf_ADefaultIsItsOwnTypesWhicheverDeclarationTheNodeCopies pins a -// default written against its own declaration's type, where the field's node -// is one the fold built: two lists of one enum, each holding a bound, meet in -// a list whose element is the copy one declaration hoisted. The default lists -// a value the enum lacks, which its own declaration answers for, so the field -// keeps it with nothing reported, whichever declaration wrote it and whichever -// the built list's element copies. -func TestAllOf_ADefaultIsItsOwnTypesWhicheverDeclarationTheNodeCopies(t *testing.T) { +// TestAllOf_ADefaultItsOwnTypeRefusesIsNotAdoptedWhicheverDeclarationTheNodeCopies +// pins a default written against its own declaration's type, where the field's +// node is one the fold built: two lists of one enum, each holding a bound, +// intersect in a list whose element is the copy one declaration hoisted. The +// default lists a value the enum lacks, which that type refuses, so the field +// does not adopt it, and one info at the declaration that wrote it says so, +// whichever declaration that is and whichever the built list's element copies. +func TestAllOf_ADefaultItsOwnTypeRefusesIsNotAdoptedWhicheverDeclarationTheNodeCopies(t *testing.T) { t.Parallel() const items = "items: {type: string, enum: [x, y]}" valued, bare := "{type: array, maxItems: 5, default: [q, q, q], "+items+"}", "{type: array, minItems: 3, "+items+"}" - for _, order := range [][2]string{{valued, bare}, {bare, valued}} { + for i, order := range [][2]string{{valued, bare}, {bare, valued}} { property, _, diags := redeclared(t, order[0], order[1]) - assert.Empty(t, diags, "%v", order) - require.NotNil(t, property.Default, "%v", order) - assert.Len(t, property.Default.List, 3, "%v", order) + assert.Nil(t, property.Default, "%v", order) + require.Len(t, diags, 1, "%v", order) + assert.Equal(t, diag.DegradedConstruct, diags[0].Code, "%v", order) + assert.Equal(t, fmt.Sprintf("/components/schemas/T/allOf/%d/properties/v", i), string(diags[0].Provenance.Pointer), "%v", order) + assert.Contains(t, diags[0].Message, "admits the default", "%v", order) } } // TestAllOf_EnumsOfDifferentValueTypesAreJudgedByTheirValues pins GitHub #1654 // in both entry orders: an enum of integer within an enum of number is the -// field's type, and two each holding a value the other lacks meet in an enum of -// what they share, of the narrower value type, with nothing reported or kept. +// field's type, and two each holding a value the other lacks intersect in an +// enum of what they share, of the narrower value type, with nothing reported or +// kept. func TestAllOf_EnumsOfDifferentValueTypesAreJudgedByTheirValues(t *testing.T) { t.Parallel() const within = "{type: integer, enum: [1]}" @@ -837,7 +845,7 @@ func TestAllOf_EnumsOfDifferentValueTypesAreJudgedByTheirValues(t *testing.T) { } { property, doc, diags := redeclared(t, order[0], order[1]) assert.Empty(t, diags, "%v", order) - require.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/1/properties/v"), property.Type.Target, "%v", order) + require.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/properties/v"), property.Type.Target, "%v", order) enum, ok := doc.Types[property.Type.Target].(*ir.Enum) require.True(t, ok, "%v", order) assert.Equal(t, ir.PrimitiveInteger, enum.ValueType, "%v", order) @@ -847,12 +855,12 @@ func TestAllOf_EnumsOfDifferentValueTypesAreJudgedByTheirValues(t *testing.T) { } } -// TestAllOf_AnAliasMeetsAsTheNodeItStandsFor pins GitHub #1672 in both entry +// TestAllOf_AnAliasIntersectsAsTheNodeItNames pins GitHub #1672 in both entry // orders: a component wrapping an enum or a list in an allOf, one only a $ref, -// and one beside a description, each meet the enum or the list beside them as the -// node they stand for, in a node holding what the alias adds, with nothing +// and one beside a description, each intersect the enum or the list beside them +// as the node they name, in a node holding what the alias adds, with nothing // reported or kept. -func TestAllOf_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { +func TestAllOf_AnAliasIntersectsAsTheNodeItNames(t *testing.T) { t.Parallel() const components = ` L1: {type: array, items: {type: string, enum: [a, b, c]}} L2: {type: array, items: {type: string, enum: [b, c, d]}} @@ -864,7 +872,7 @@ func TestAllOf_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { Described: {$ref: '#/components/schemas/E1', description: d} ` ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } - for _, tc := range []struct { + for _, testCase := range []struct { alias, other, docs string list bool }{ @@ -873,15 +881,15 @@ func TestAllOf_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { {alias: "BareRef", other: "E2"}, {alias: "Described", other: "E2", docs: "d"}, } { - for _, order := range [][2]string{{ref(tc.alias), ref(tc.other)}, {ref(tc.other), ref(tc.alias)}} { + for _, order := range [][2]string{{ref(testCase.alias), ref(testCase.other)}, {ref(testCase.other), ref(testCase.alias)}} { doc, diags := settledSpec(t, components, order[0], order[1]) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, diags, "%v", order) property := propertyOf(t, doc, "T", "v") assert.Empty(t, property.Unmodeled, "%v", order) - require.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/1/properties/v"), property.Type.Target, "%v", order) + require.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/properties/v"), property.Type.Target, "%v", order) target := property.Type.Target - if tc.list { + if testCase.list { list, ok := doc.Types[target].(*ir.List) require.True(t, ok, "%v", order) target = list.ElementType.Target @@ -889,18 +897,18 @@ func TestAllOf_AnAliasMeetsAsTheNodeItStandsFor(t *testing.T) { enum, ok := doc.Types[target].(*ir.Enum) require.True(t, ok, "%v", order) assert.Equal(t, []string{"b", "c"}, []string{enum.Members[0].Value.String, enum.Members[1].Value.String}, "%v", order) - assert.Equal(t, tc.docs, doc.Types[property.Type.Target].Common().Docs.Description, "%v", order) + assert.Equal(t, testCase.docs, doc.Types[property.Type.Target].Common().Docs.Description, "%v", order) assert.Empty(t, validated(t, doc), "%v", order) } } } // TestAllOf_AnAliasIsJudgedByWhatItAdds pins, in both entry orders, what an -// alias adds to the node it stands for: docs read field by field down its -// chain; a bound on an open enum, which no node of its kind holds, judged as -// written; one alias of the top type within the other; and null alone, so the -// node it stands for is within it, while one adding docs too, or holding null -// beside a node it would be within, overlaps it. A field keeping a type the +// alias adds to the node it names: docs read down its chain; a bound on an +// open enum, which no node of its kind holds, as written; one alias of the top +// type within the other; and null alone, so the node it names is within +// it, one adding docs too overlapping it, and one beside a wider node within +// it, the field admitting null where both uses do. A field keeping a type the // other refuses reports it and keeps that one verbatim. func TestAllOf_AnAliasIsJudgedByWhatItAdds(t *testing.T) { t.Parallel() @@ -922,7 +930,7 @@ func TestAllOf_AnAliasIsJudgedByWhatItAdds(t *testing.T) { LN: {anyOf: [{$ref: '#/components/schemas/L'}, {type: 'null'}]} ` ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } - for _, tc := range []struct { + for _, testCase := range []struct { alias, other string // want is the field's type, "" for a node the merge mints. want ir.TypeID @@ -938,17 +946,15 @@ func TestAllOf_AnAliasIsJudgedByWhatItAdds(t *testing.T) { {alias: "NAny", other: "E1", want: componentID("E1"), docs: ir.Docs{Description: "e1"}}, {alias: "MN", other: "M", want: componentID("M")}, {alias: "LN", other: "L", want: componentID("L")}, - {alias: "NAny", other: "E3", kept: true}, - // DN and E1 each lend their own description, which the field reports too. - {alias: "DN", other: "E1", kept: true, reports: 1}, + {alias: "NAny", other: "E3", want: componentID("NAny")}, } { - for _, order := range [][2]string{{ref(tc.alias), ref(tc.other)}, {ref(tc.other), ref(tc.alias)}} { + for _, order := range [][2]string{{ref(testCase.alias), ref(testCase.other)}, {ref(testCase.other), ref(testCase.alias)}} { doc, diags := settledSpec(t, components, order[0], order[1]) openapitest.RequireNoErrorDiags(t, diags) property := propertyOf(t, doc, "T", "v") later := componentID(strings.TrimSuffix(strings.TrimPrefix(order[1], "{$ref: '#/components/schemas/"), "'}")) - if tc.kept { - assert.Len(t, diags, 1+tc.reports, "%v: the declaration the field refuses is reported", order) + if testCase.kept { + assert.Len(t, diags, 1+testCase.reports, "%v: the declaration the field refuses is reported", order) assert.Len(t, property.Unmodeled, 1, "%v: and kept", order) assert.Equal(t, later, property.Type.Target, "%v: the field keeps the later", order) continue @@ -956,15 +962,57 @@ func TestAllOf_AnAliasIsJudgedByWhatItAdds(t *testing.T) { assert.Empty(t, diags, "%v", order) assert.Empty(t, property.Unmodeled, "%v", order) assert.False(t, property.Type.Nullable, "%v: one declaration refuses null", order) - if tc.want != "" { - assert.Equal(t, tc.want, property.Type.Target, "%v", order) + if testCase.want != "" { + assert.Equal(t, testCase.want, property.Type.Target, "%v", order) } else { - assert.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/1/properties/v"), property.Type.Target, "%v", order) + assert.Equal(t, ir.TypeID("type/composed/components/schemas/T/allOf/properties/v"), property.Type.Target, "%v", order) } - if tc.docs.Summary != "" || tc.docs.Description != "" { - assert.Equal(t, tc.docs, doc.Types[property.Type.Target].Common().Docs, "%v", order) + if testCase.docs.Summary != "" || testCase.docs.Description != "" { + assert.Equal(t, testCase.docs, doc.Types[property.Type.Target].Common().Docs, "%v", order) } assert.Empty(t, validated(t, doc), "%v", order) } } + + // DN and E1 each lend their own description, which the field reports, and + // the declaration naming DN, which the field does not name, is kept. + for _, order := range [][2]string{{ref("DN"), ref("E1")}, {ref("E1"), ref("DN")}} { + doc, diags := settledSpec(t, components, order[0], order[1]) + openapitest.RequireNoErrorDiags(t, diags) + property := propertyOf(t, doc, "T", "v") + assert.Equal(t, componentID("E1"), property.Type.Target, "%v: E1 is narrower", order) + assert.True(t, slices.ContainsFunc(diags, func(diagnostic ir.Diagnostic) bool { + return strings.Contains(diagnostic.Message, "give its description differently") + }), "%v: the descriptions are reported", order) + assert.True(t, slices.ContainsFunc(slices.Collect(maps.Values(property.Unmodeled)), func(entry ir.UnmodeledEntry) bool { + return strings.Contains(string(entry.Value), "schemas/DN") + }), "%v: the declaration naming DN is kept", order) + } +} + +// TestAllOf_AFormatAloneIntersectsTheKindItNarrows pins a field declared as a +// string and as a schema writing a format alone: the two intersect at the +// format's primitive in either order, with no report of the fold, while a +// format of another kind's text leaves the two overlapping. +func TestAllOf_AFormatAloneIntersectsTheKindItNarrows(t *testing.T) { + t.Parallel() + for _, testCase := range []struct { + kind, format string + want ir.TypeID + }{ + {"string", "uuid", ir.PrimitiveTypeID(ir.PrimitiveUUID)}, + {"integer", "int64", ir.PrimitiveTypeID(ir.PrimitiveInt64)}, + } { + kind, format := "{type: "+testCase.kind+"}", "{format: "+testCase.format+"}" + for _, order := range [][2]string{{kind, format}, {format, kind}} { + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec( + " T: {allOf: [{properties: {f: "+order[0]+"}}, {properties: {f: "+order[1]+"}}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + assert.Equal(t, testCase.want, propertyOf(t, doc, "T", "f").Type.Target, "%v", order) + assert.Empty(t, propertyOf(t, doc, "T", "f").Unmodeled, "%v", order) + for _, diagnostic := range diags { + assert.Empty(t, diagnostic.Related, "%v: no fold report: %s", order, diagnostic.Message) + } + } + } } diff --git a/compilers/openapi/internal/schema/allof_nesting_test.go b/compilers/openapi/internal/schema/allof_nesting_test.go index d8c919c9a..9d204bc40 100644 --- a/compilers/openapi/internal/schema/allof_nesting_test.go +++ b/compilers/openapi/internal/schema/allof_nesting_test.go @@ -30,11 +30,11 @@ import ( // property for every reader of the list. func TestAllOf_NestedLowersAsFlat(t *testing.T) { t.Parallel() - for _, tc := range equivalencePairs { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range equivalencePairs { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - nested, nestedCodes := compileView(t, tc.nested) - flat, flatCodes := compileView(t, tc.flat) + nested, nestedCodes := compileView(t, testCase.nested) + flat, flatCodes := compileView(t, testCase.flat) assert.NotEqual(t, composedView{}, flat, "the flat spelling lowers to something to compare") assert.Empty(t, cmp.Diff(flat, nested), "the nested spelling composes as the flat one does") assert.Equal(t, flatCodes, nestedCodes, "and reports the same codes") @@ -45,14 +45,14 @@ func TestAllOf_NestedLowersAsFlat(t *testing.T) { // TestAllOf_NestedLowersAsFlat_ReachesWhatItCompares pins that the projection // sees the distinctions the pairs rely on, so a pair that agrees does so for a // reason: a distributed union has variants, the discriminated subtype has its -// tag, a false entry closes the model, and a required name the base declares -// is held in Requires. The residue and the false entry are also kept, which +// tag, a false entry closes the model, and a required name the base declares is +// held in Requires. An unread keyword and the false entry are also kept, which // only a positive Kept shows. func TestAllOf_NestedLowersAsFlat_ReachesWhatItCompares(t *testing.T) { t.Parallel() byName := map[string]string{} - for _, tc := range equivalencePairs { - byName[tc.name] = tc.flat + for _, testCase := range equivalencePairs { + byName[testCase.name] = testCase.flat } distributed, _ := compileView(t, byName["a distributed oneOf beside the wrappers"]) require.Len(t, distributed.Variants, 2, "the oneOf distributes") @@ -66,12 +66,12 @@ func TestAllOf_NestedLowersAsFlat_ReachesWhatItCompares(t *testing.T) { required, _ := compileView(t, byName["a required name only the base declares"]) assert.Equal(t, []string{"a"}, required.Requires, "the name is required of the composition, not of a property it holds") - residue, _ := compileView(t, byName["a residue"]) - assert.Positive(t, residue.Kept, "the residue is kept") + unreadView, _ := compileView(t, byName["an unread keyword"]) + assert.Positive(t, unreadView.Kept, "the unread keyword is kept") closure, _ := compileView(t, byName["a closure"]) assert.Equal(t, ir.AdditionalClosed, closure.Additional, "the wrapper declaring no member closes the model") - assert.Zero(t, closure.Kept, "and nothing of it is kept") + assert.Positive(t, closure.Kept, "and is kept, as it applies to the members the $refs bring") subtype, _ := compileView(t, byName["a discriminated base inside a wrapper"]) assert.Equal(t, "dog", subtype.DiscValue) @@ -137,18 +137,18 @@ func TestAllOf_NestedInlineWrapperFlattens(t *testing.T) { properties: map[string]string{"w": "/components/schemas/M/allOf/0/properties/w"}, }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - for _, doc := range nestedOrders(t, tc.m, nestedAB) { + for _, doc := range nestedOrders(t, testCase.m, nestedAB) { model, ok := typeByName(doc, "M").(*ir.Model) require.True(t, ok, "M should be a model") - if tc.base == "" { + if testCase.base == "" { assert.Nil(t, model.Base) } else if assert.NotNil(t, model.Base) { - assert.Equal(t, tc.base, model.Base.Target) + assert.Equal(t, testCase.base, model.Base.Target) } - assert.Equal(t, append([]ir.TypeID{}, tc.mixins...), refTargets(model.Mixins)) + assert.Equal(t, append([]ir.TypeID{}, testCase.mixins...), refTargets(model.Mixins)) assert.Empty(t, model.Unmodeled, "a flattened wrapper is not kept verbatim") assert.False(t, slices.ContainsFunc(doc.Diagnostics, func(diagnostic ir.Diagnostic) bool { return strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/M") @@ -157,7 +157,7 @@ func TestAllOf_NestedInlineWrapperFlattens(t *testing.T) { for _, property := range model.Properties { got[property.WireName] = string(property.Provenance.Pointer) } - want := tc.properties + want := testCase.properties if want == nil { want = map[string]string{} } @@ -271,10 +271,10 @@ func TestAllOf_NestedWrapperBaseSelection(t *testing.T) { - {$ref: '#/components/schemas/Pet'} `}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - for _, doc := range nestedOrders(t, tc.dog, pet) { + for _, doc := range nestedOrders(t, testCase.dog, pet) { dog, ok := typeByName(doc, "Dog").(*ir.Model) require.True(t, ok, "Dog should be a model") require.NotNil(t, dog.Base) @@ -308,34 +308,33 @@ func TestAllOf_NestedFalseEntryClosesModel(t *testing.T) { } } -// TestAllOf_NestedWrapperWithResidueKeptVerbatim pins that a wrapper writing -// a keyword the merge does not consume is still flattened: its entries and -// properties compose as the flat spelling's do, and what it writes is kept as -// any entry's is, each keyword under its own key at the wrapper, or the whole -// wrapper under its key for an unevaluated keyword, reported once at the +// TestAllOf_NestedWrapperWithUnreadKeywordsKeptVerbatim pins that a wrapper +// writing a keyword the merge does not consume is still flattened: its entries +// and properties compose as the flat spelling's do, and what it writes is kept +// as any entry's is, each keyword under its own key at the wrapper, or the +// whole wrapper under its key for an unevaluated keyword, reported once at the // wrapper naming the extra keyword and not allOf, as the validation-only // keyword the unevaluated one is. -func TestAllOf_NestedWrapperWithResidueKeptVerbatim(t *testing.T) { +func TestAllOf_NestedWrapperWithUnreadKeywordsKeptVerbatim(t *testing.T) { t.Parallel() tests := []struct { name string sibling string - residue string + keyword string whole bool }{ - {"discriminator", "discriminator: {propertyName: kind}", "discriminator", false}, {"oneOf", "oneOf: [{type: string}]", "oneOf", false}, {"unevaluatedProperties false", "unevaluatedProperties: false", "unevaluatedProperties", true}, - {"type set with null", `type: [object, "null"]`, "type", false}, + {"type set with an array", `type: [object, array]`, "type", false}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() m := ` M: allOf: - allOf: - {$ref: '#/components/schemas/A'} - ` + tc.sibling + ` + ` + testCase.sibling + ` properties: {w: {type: string}} ` for _, doc := range nestedOrders(t, m, nestedAB) { @@ -347,7 +346,7 @@ func TestAllOf_NestedWrapperWithResidueKeptVerbatim(t *testing.T) { _, hasW := openapitest.PropertiesByWire(model.Properties)["w"] assert.True(t, hasW, "the wrapper's properties still merge") code := diag.DegradedConstruct - if tc.whole { + if testCase.whole { code = diag.ValidationOnlyKeyword } var infos []ir.Diagnostic @@ -358,31 +357,31 @@ func TestAllOf_NestedWrapperWithResidueKeptVerbatim(t *testing.T) { } require.Len(t, infos, 1, "exactly one %s at the wrapper", code) assert.NotContains(t, infos[0].Message, "(allOf") - if !tc.whole { - entry, ok := model.Unmodeled["openapi:"+tc.residue] + if !testCase.whole { + entry, ok := model.Unmodeled["openapi:"+testCase.keyword] require.True(t, ok, "the keyword is kept under its own key; got %+v", model.Unmodeled) - assert.Equal(t, jsontext.Pointer("/components/schemas/M/allOf/0/"+tc.residue), entry.Provenance.Pointer) + assert.Equal(t, jsontext.Pointer("/components/schemas/M/allOf/0/"+testCase.keyword), entry.Provenance.Pointer) assert.NotContains(t, model.Unmodeled, "openapi:allOf/0") - assert.Contains(t, infos[0].Message, "no home for "+tc.residue+" written on this inline entry") + assert.Contains(t, infos[0].Message, "no home for "+testCase.keyword+" written on this inline entry") continue } entry, ok := model.Unmodeled["openapi:allOf/0"] require.True(t, ok, "the wrapper is kept verbatim; got %+v", model.Unmodeled) assert.Equal(t, jsontext.Pointer("/components/schemas/M/allOf/0"), entry.Provenance.Pointer) assert.Contains(t, string(entry.Value), `"allOf"`, "the whole wrapper is kept") - assert.Contains(t, infos[0].Message, "("+tc.residue+")") + assert.Contains(t, infos[0].Message, "("+testCase.keyword+")") assert.Contains(t, infos[0].Message, "nested allOf compose") } }) } } -// TestAllOf_KeptEntryOfAKeptWrapperIsKeptTwice pins the trade-off -// docs/compilers/openapi.md#allof-inline-residue states: a wrapper kept for -// its residue is kept whole, its entries included, so an entry kept itself, or -// a false one, is in Unmodeled twice, inside the wrapper's copy and under its -// own path. -func TestAllOf_KeptEntryOfAKeptWrapperIsKeptTwice(t *testing.T) { +// TestAllOf_AKeptAllOfEntryOfAKeptWrapperIsKeptTwice pins the trade-off +// docs/compilers/openapi.md#allof-inline-residue states: a wrapper kept for its +// unread keywords are kept whole, its entries included, so an entry kept +// itself, or a false one, is in Unmodeled twice, inside the wrapper's copy and +// under its own path. +func TestAllOf_AKeptAllOfEntryOfAKeptWrapperIsKeptTwice(t *testing.T) { t.Parallel() m := ` M: allOf: @@ -617,7 +616,7 @@ var equivalencePairs = []struct { `, ` M: allOf: [{$ref: '#/components/schemas/A'}, false] `}, - {"a residue", ` M: + {"an unread keyword", ` M: allOf: - unevaluatedProperties: false allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}] diff --git a/compilers/openapi/internal/schema/allof_nullable_use_test.go b/compilers/openapi/internal/schema/allof_nullable_use_test.go new file mode 100644 index 000000000..288dc061d --- /dev/null +++ b/compilers/openapi/internal/schema/allof_nullable_use_test.go @@ -0,0 +1,51 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// TestAllOf_ANullableSayingNothingLeavesTheUseOfOneRef holds an allOf of one +// $ref beside a 3.0 `nullable`, at a property and at items, to what the null +// answer reads it as: `false` says nothing, nor does a `true` the +// nullable-inference policy widens nothing by, an entry beside the $ref +// writing structure, so each position is the $ref alone, no Model of its own +// there. A `true` the policy widens the lone $ref by says that null: the +// property's carrier holds it on the use, and items compose a node of their +// own, each use admitting the null. +func TestAllOf_ANullableSayingNothingLeavesTheUseOfOneRef(t *testing.T) { + t.Parallel() + const obj = "{$ref: '#/components/schemas/Obj'}" + for name, testCase := range map[string]struct { + schema string + itemsAlone, nul bool + }{ + "false": {"{allOf: [" + obj + "], nullable: false}", true, false}, + "says nothing": {"{allOf: [{type: object, properties: {a: {type: string}}, nullable: true}, " + obj + "]}", true, false}, + "widened": {"{allOf: [" + obj + "], nullable: true}", false, true}, + } { + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.0.3", ` Obj: {type: object, properties: {a: {type: string}}} + H: {type: object, properties: {p: `+testCase.schema+`}} + L: {type: array, items: `+testCase.schema+`} +`)) + openapitest.RequireNoErrorDiags(t, diags) + holder, ok := typeByName(doc, "H").(*ir.Model) + require.True(t, ok, name) + list, ok := typeByName(doc, "L").(*ir.List) + require.True(t, ok, name) + property := openapitest.PropertiesByWire(holder.Properties)["p"].Type + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Obj"), property.Target, "%s at the property", name) + assert.Equal(t, testCase.itemsAlone, list.ElementType.Target == "type/openapi/components/schemas/Obj", "%s at items: %v", name, list.ElementType.Target) + assert.Equal(t, testCase.nul, property.Nullable, "%s at the property", name) + assert.Equal(t, testCase.nul, list.ElementType.Nullable, "%s at items", name) + } +} diff --git a/compilers/openapi/internal/schema/allof_reach_test.go b/compilers/openapi/internal/schema/allof_reach_test.go new file mode 100644 index 000000000..3ca83b81e --- /dev/null +++ b/compilers/openapi/internal/schema/allof_reach_test.go @@ -0,0 +1,473 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "encoding/json/v2" + "slices" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// nestedAllOf is schema wrapped in depth allOfs of one entry each. +func nestedAllOf(schema string, depth int) string { + for range depth { + schema = "{allOf: [" + schema + "]}" + } + return schema +} + +// keptWithoutRefs is what typeDef keeps, as key, reason and value, with each +// kept $ref taken out: a key of its own, or a member of an entry kept whole. +func keptWithoutRefs(t *testing.T, typeDef ir.TypeDef) []string { + t.Helper() + require.NotNil(t, typeDef) + var out []string + for key, entry := range typeDef.Common().Unmodeled { + if strings.HasPrefix(key, "openapi:$ref") { + continue + } + value := entry.Value + var members map[string]jsontext.Value + if json.Unmarshal(value, &members) == nil && members["$ref"] != nil { + delete(members, "$ref") + raw, err := json.Marshal(members, json.Deterministic(true)) + require.NoError(t, err) + value = raw + } + out = append(out, key+" "+string(entry.Reason)+" "+string(value)) + } + slices.Sort(out) + return out +} + +// findingSites is each of diags as its severity, code and pointer, sorted. +func findingSites(diags []ir.Diagnostic) []string { + out := make([]string, 0, len(diags)) + for _, diagnostic := range diags { + out = append(out, string(diagnostic.Severity)+" "+diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + slices.Sort(out) + return out +} + +// withoutCode is diags but those carrying code. +func withoutCode(diags []ir.Diagnostic, code string) []ir.Diagnostic { + return slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { return diagnostic.Code == code }) +} + +// TestAllOf_ARefToATypeListHoldingNoObjectSharingNullIsTheNull holds a $ref +// entry landing on a type list that names no object, beside an object entry +// the two share null alone with: the position is the null type, as +// `{type: 'null'}` is, the $ref kept verbatim with the info saying why, and no +// node takes one of the list's variants as its base. +func TestAllOf_ARefToATypeListHoldingNoObjectSharingNullIsTheNull(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` SIN: {type: [string, integer, 'null']} + P: {allOf: [{$ref: '#/components/schemas/SIN'}, {type: [object, 'null'], properties: {a: {type: string}}}]} +`)) + + openapitest.RequireNoErrorDiags(t, diags) + kept, ok := typeByName(doc, "P").Common().Unmodeled["openapi:$ref"] + require.True(t, ok, "the $ref is kept: %v", typeByName(doc, "P").Common().Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) + assert.JSONEq(t, `"#/components/schemas/SIN"`, string(kept.Value)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/P/allOf/0"), + "admit null alone together") + _, isEnum := typeByName(doc, "P").(*ir.Enum) + assert.True(t, isEnum, "the null type: got %T", typeByName(doc, "P")) + for id, typeDef := range doc.Types { + if model, isModel := typeDef.(*ir.Model); isModel && model.Base != nil { + assert.NotContains(t, string(model.Base.Target), "components/schemas/SIN", "%s composes a variant of the list", id) + } + } +} + +// TestAllOf_ARefToATypeListHoldingNoObjectBesideAUnionIsKept holds the same +// entries beside a union, whose rules weigh the null they share: the list has +// no object variant to compose, so the $ref is kept verbatim with the info +// saying why, and no node takes one of the list's variants as its base. +func TestAllOf_ARefToATypeListHoldingNoObjectBesideAUnionIsKept(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` SIN: {type: [string, integer, 'null']} + P: + allOf: [{$ref: '#/components/schemas/SIN'}, {type: [object, 'null'], properties: {a: {type: string}}}] + anyOf: [{required: [a]}, {required: [b]}] +`)) + + openapitest.RequireNoErrorDiags(t, diags) + kept, ok := typeByName(doc, "P").Common().Unmodeled["openapi:$ref"] + require.True(t, ok, "the $ref is kept: %v", typeByName(doc, "P").Common().Unmodeled) + assert.JSONEq(t, `"#/components/schemas/SIN"`, string(kept.Value)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/P/allOf/0"), + "not an object alone") + for id, typeDef := range doc.Types { + if model, isModel := typeDef.(*ir.Model); isModel && model.Base != nil { + assert.NotContains(t, string(model.Base.Target), "components/schemas/SIN", "%s composes a variant of the list", id) + } + } +} + +// TestAllOf_ACappedEntryNotAnObjectNamesItsUnflattenedAllOf holds an entry +// nested past the flattening depth that declares a string beside the closed +// composition a `false` entry leaves: its warning that it is no object also +// says that its own allOf, nested past the depth, was not flattened. +func TestAllOf_ACappedEntryNotAnObjectNamesItsUnflattenedAllOf(t *testing.T) { + t.Parallel() + capped := nestedAllOf("{type: string, allOf: [{$ref: '#/components/schemas/A'}]}", 32) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {a: {type: string}}} + Capped: {allOf: [false, `+capped+`]} +`)) + + openapitest.RequireNoErrorDiags(t, diags) + require.NotNil(t, typeByName(doc, "Capped")) + var said []string + for _, diagnostic := range diags { + if diagnostic.Code == diag.UnsatisfiableSchema && strings.Contains(diagnostic.Message, "declares a type that is not an object") { + said = append(said, diagnostic.Message) + } + } + require.Len(t, said, 1, "%+v", diags) + assert.Contains(t, said[0], ", and its own allOf, nested past the flattening depth of 32, was not flattened") +} + +// TestUnion_APairReadPastTheCapsDrawsNoDisjointReport holds a oneOf beside an +// anyOf whose branches share a kind and no value: read within the caps the +// pair draws the warning that no instance satisfies it, and read past them, +// three hundred branches wide, it decides nothing and draws none, as a read a +// bound cuts draws no disjoint report. +func TestUnion_APairReadPastTheCapsDrawsNoDisjointReport(t *testing.T) { + t.Parallel() + var targets strings.Builder + refs := make([]string, 0, 300) + for i := range 300 { + targets.WriteString(" S" + strconv.Itoa(i) + ": {type: string, enum: [s" + strconv.Itoa(i) + "]}\n") + refs = append(refs, "{$ref: '#/components/schemas/S"+strconv.Itoa(i)+"'}") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", targets.String()+ + " Wide: {oneOf: ["+strings.Join(refs, ", ")+"], anyOf: [{type: string, enum: [zz]}]}\n"+ + " Narrow: {oneOf: ["+strings.Join(refs[:3], ", ")+"], anyOf: [{type: string, enum: [zz]}]}\n")) + + openapitest.RequireNoErrorDiags(t, diags) + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/Narrow"), 1, "the control reads the pair") + assert.Empty(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/Wide"), "a cut read decides nothing") + union, ok := typeByName(doc, "Wide").(*ir.Union) + require.True(t, ok, "got %T", typeByName(doc, "Wide")) + assert.Len(t, union.Variants, 300) + assert.Contains(t, union.Unmodeled, "openapi:anyOf") +} + +// TestAllOf_TwoValueSetsInACutReadChooseNeither holds an allOf whose conjuncts +// pass the choice's bound, two of them inline value sets: no one value set +// is chosen, so the position is what the kinds name, a string, keeping each +// conjunct saying more verbatim, with the one info naming the bound. +func TestAllOf_TwoValueSetsInACutReadChooseNeither(t *testing.T) { + t.Parallel() + entries := strings.Repeat("{type: string, minLength: 1}, ", 65) + "{enum: [a]}, {enum: [a, b]}" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " M: {allOf: ["+entries+"]}\n")) + + openapitest.RequireNoErrorDiags(t, diags) + scalar, ok := typeByName(doc, "M").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "M")) + require.NotNil(t, scalar.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), scalar.Base.Target) + assert.Len(t, scalar.Unmodeled, 67, "each conjunct is kept") + assert.Contains(t, scalar.Unmodeled, "openapi:allOf/65") + assert.Contains(t, scalar.Unmodeled, "openapi:allOf/66") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/M"), + "passed the 64 conjuncts one election compares") +} + +// TestAllOf_ACutReadNamingAnObjectAndAStringIsTheirUnion holds an allOf whose +// conjuncts pass the choice's bound, each naming an object or a string: the +// kinds are no object alone, so the position is what they name, the union of +// the two, keeping each conjunct verbatim, with the one info naming the bound. +func TestAllOf_ACutReadNamingAnObjectAndAStringIsTheirUnion(t *testing.T) { + t.Parallel() + entries := strings.TrimSuffix(strings.Repeat("{type: [object, string], minLength: 1}, ", 65), ", ") + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " U: {allOf: ["+entries+"]}\n")) + + openapitest.RequireNoErrorDiags(t, diags) + union, ok := typeByName(doc, "U").(*ir.Union) + require.True(t, ok, "got %T", typeByName(doc, "U")) + kinds := make([]ir.TypeKind, 0, len(union.Variants)) + for _, variant := range union.Variants { + kinds = append(kinds, doc.Types[variant.Type.Target].Kind()) + } + assert.ElementsMatch(t, []ir.TypeKind{ir.KindModel, ir.KindPrimitive}, kinds, "an object and a string") + assert.Len(t, union.Unmodeled, 65, "each conjunct is kept") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/U"), + "passed the 64 conjuncts one election compares") +} + +// TestDeadBranch_ARestCutShortDecidesNothing holds an object body beside a +// oneOf one of whose branches is a string, and an allOf nested past the +// flattening depth: the rest's read is cut short, so it decides nothing, and +// the string branch, though no object, is not reported as admitting nothing. +func TestDeadBranch_ARestCutShortDecidesNothing(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " W1: {type: object, properties: {a: {type: string}}, oneOf: [{type: string}, {type: object}], allOf: ["+ + nestedAllOf("{type: object}", 33)+"]}\n")) + + openapitest.RequireNoErrorDiags(t, diags) + assert.Empty(t, openapitest.PointersOf(diags, diag.UnsatisfiableSchema), "nothing is reported dead") + _, ok := typeByName(doc, "W1").(*ir.Union) + assert.True(t, ok, "got %T", typeByName(doc, "W1")) +} + +// TestAllOf_ARefWithNotesOverABottomIsItsAlias holds a $ref with a description +// beside it whose target admits nothing: one reference with notes is the +// reference whatever its target admits, so the position is the alias of the +// target, which alone reports that it is empty. +func TestAllOf_ARefWithNotesOverABottomIsItsAlias(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` T: {type: string} + C: {allOf: [{$ref: '#/components/schemas/T'}, {type: integer}]} + U: {$ref: '#/components/schemas/C', description: d} +`)) + + openapitest.RequireNoErrorDiags(t, diags) + scalar, ok := typeByName(doc, "U").(*ir.Scalar) + require.True(t, ok, "the alias: got %T", typeByName(doc, "U")) + require.NotNil(t, scalar.Base) + assert.Equal(t, componentID("C"), scalar.Base.Target) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/C"}, openapitest.PointersOf(diags, diag.UnsatisfiableSchema), + "the target alone reports that it is empty") +} + +// TestAllOf_AChoicePastTheMemberBoundChoosesTheValueSet holds an entry whose +// value set holds more members than the choice compares, beside a string: +// the read is cut, and the value set, chosen by its keyword before any read, +// is the node, a string Enum of every member keeping the entry's integer type, +// each member drawing its own finding. +func TestAllOf_AChoicePastTheMemberBoundChoosesTheValueSet(t *testing.T) { + t.Parallel() + members := make([]string, 0, 2100) + for i := range 2100 { + members = append(members, "s"+strconv.Itoa(i)) + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " B1: {allOf: [{type: integer, enum: ["+strings.Join(members, ", ")+"]}, {type: string}]}\n")) + + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "B1").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "B1")) + assert.Len(t, enum.Members, 2100) + assert.Equal(t, ir.PrimitiveString, enum.ValueType) + assert.Equal(t, []string{"openapi:type"}, unmodeledKeys(enum.Unmodeled)) + assert.Len(t, openapitest.PointersOf(diags, diag.UnsatisfiableSchema), 2100, "each member draws its finding") +} + +// TestAllOf_RefValueSetsSharingNoMemberAreTheClosedEmptyEnum holds two $ref +// entries whose targets are string value sets sharing no member: the closed +// empty Enum of strings, keeping each $ref, which names its set, under +// its own key, and the one warning that no instance satisfies the schema, no +// entry reporting the set it names, as the flat twin's sets draw nothing +// beside its warning. +func TestAllOf_RefValueSetsSharingNoMemberAreTheClosedEmptyEnum(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` EA: {enum: [a, c]} + EB: {enum: [b, d]} + R: {allOf: [{$ref: '#/components/schemas/EA'}, {$ref: '#/components/schemas/EB'}]} +`)) + + openapitest.RequireNoErrorDiags(t, diags) + assert.Empty(t, openapitest.PointersOf(diags, diag.DegradedConstruct), "no entry reports its set: %+v", diags) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/R"}, openapitest.PointersOf(diags, diag.UnsatisfiableSchema)) + enum, ok := typeByName(doc, "R").(*ir.Enum) + require.True(t, ok, "the closed empty enum: got %T", typeByName(doc, "R")) + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Equal(t, ir.PrimitiveString, enum.ValueType) + assert.Equal(t, []string{"openapi:$ref/0", "openapi:$ref/1"}, unmodeledKeys(enum.Unmodeled), "each set is kept") +} + +// TestAllOf_AnEntryValueSetNoReadingConvertsIsReported holds an inline entry +// whose value set holds a value no JSON holds beside a string: the set is no +// conjunct of the reading, so the position is the string. An entry with no +// cause to be kept whole keeps keyword by keyword, so the value set, which +// reaches the IR in no form, is refused at its keyword, where it is written. +func TestAllOf_AnEntryValueSetNoReadingConvertsIsReported(t *testing.T) { + t.Parallel() + for name, entry := range map[string]string{"enum": "{enum: [.nan]}", "const": "{const: .nan}"} { + at := "/components/schemas/Q/allOf/0/" + name + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Q: {allOf: ["+entry+", {type: string}]}\n")) + scalar, ok := typeByName(doc, "Q").(*ir.Scalar) + require.True(t, ok, "%s: got %T", name, typeByName(doc, "Q")) + require.NotNil(t, scalar.Base, name) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), scalar.Base.Target, name) + assert.Equal(t, []jsontext.Pointer{jsontext.Pointer(at)}, openapitest.PointersOf(diags, diag.UnpreservableConstruct), + "%s: the value no JSON holds is refused at its keyword: %+v", name, diags) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnpreservableConstruct, ir.SeverityError, at), "openapi:"+name, name) + } +} + +// TestAllOf_TwoRefsWrittenAlikeAreOneConjunct holds an allOf writing one $ref +// twice beside a bound: the two read alike, so the position is the use of +// the target holding the bound, keeping nothing and reporting nothing. +func TestAllOf_TwoRefsWrittenAlikeAreOneConjunct(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Str: {type: string} + T1: {allOf: [{$ref: '#/components/schemas/Str'}, {$ref: '#/components/schemas/Str'}, {maxLength: 3}]} +`)) + + assert.Empty(t, diags) + scalar, ok := typeByName(doc, "T1").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "T1")) + require.NotNil(t, scalar.Base) + assert.Equal(t, componentID("Str"), scalar.Base.Target) + assert.Equal(t, &ir.Constraints{MaxLength: new(int64(3))}, scalar.Constraints) + assert.Empty(t, scalar.Unmodeled) +} + +// TestAllOf_TiedRefsChooseTheLeastEntryTextInEitherOrder holds two $ref entries +// writing one reference text that their $ids resolve to two alike schemas: +// each lies within as many conjuncts, so the tie goes to the least text of the +// entry, the one under .../a/, in either order the entries are written. +func TestAllOf_TiedRefsChooseTheLeastEntryTextInEitherOrder(t *testing.T) { + t.Parallel() + const ( + underA = "{$id: 'https://ex.test/a/', $ref: n.json}" + underB = "{$id: 'https://ex.test/b/', $ref: n.json}" + ) + for _, entries := range []string{underA + ", " + underB, underB + ", " + underA} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` A: {$id: 'https://ex.test/a/n.json', type: string, maxLength: 5} + B: {$id: 'https://ex.test/b/n.json', type: string, maxLength: 5} + T: {allOf: [`+entries+`, {maxLength: 9}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + scalar, ok := typeByName(doc, "T").(*ir.Scalar) + require.True(t, ok, "%s: got %T", entries, typeByName(doc, "T")) + require.NotNil(t, scalar.Base, entries) + assert.Equal(t, componentID("A"), scalar.Base.Target, "the least entry text wins, written %s", entries) + } +} + +// TestAllOf_AGhostRefEntryKeepingAKeyLowersAsWithoutIt holds an allOf entry +// writing a $ref that names nothing beside a key the position keeps: the +// position lowers as the same schema without the $ref, which is kept, and the +// unresolved reference is the one report added. Where another conjunct writes +// the key otherwise, the entry is kept whole, saying that its $ref names +// nothing. +func TestAllOf_AGhostRefEntryKeepingAKeyLowersAsWithoutIt(t *testing.T) { + t.Parallel() + const ghost = "$ref: '#/components/schemas/Ghost', " + for name, schema := range map[string]string{ + "the key kept apart": "{allOf: [{" + ghost + "$recursiveAnchor: true}, {type: object, properties: {b: {type: string}}}]}", + "the entry kept whole": "{allOf: [{" + ghost + "$recursiveAnchor: true}, " + + "{type: object, $recursiveAnchor: false, properties: {b: {type: string}}}]}", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Y: "+schema+"\n")) + equivalent, equivalentDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Y: "+strings.Replace(schema, ghost, "", 1)+"\n")) + assert.Equal(t, keptWithoutRefs(t, typeByName(equivalent, "Y")), keptWithoutRefs(t, typeByName(doc, "Y"))) + assert.Equal(t, typeByName(equivalent, "Y").Kind(), typeByName(doc, "Y").Kind()) + assert.Equal(t, findingSites(equivalentDiags), findingSites(withoutCode(diags, diag.UnresolvedRef)), "no other report") + assert.Len(t, withCode(diags, diag.UnresolvedRef), 1) + if strings.Contains(schema, "$recursiveAnchor: false") { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Y/allOf/0"), + "this allOf entry's $ref names nothing") + } + }) + } +} + +// TestMembers_AModelOverAModelInAnotherDocumentReadsThroughIt holds a model +// composing a model another document declares, the composition a $dynamicRef +// there expands to, beside a schema redeclaring that composition's member: the +// redeclaration is read against the member the model leads to, settled, and +// its report names the type that member settled to, as its $ref twin's does. +func TestMembers_AModelOverAModelInAnotherDocumentReadsThroughIt(t *testing.T) { + t.Parallel() + doc, diags, _ := compileFiles(t, map[string]string{"other.yaml": `openapi: 3.1.0 +info: {title: other, version: "1"} +paths: {} +components: + schemas: + Base: {type: object, properties: {children: {type: array, items: {type: string}}, b: {type: integer}}} + Tree: + $dynamicAnchor: node + allOf: + - {$ref: '#/components/schemas/Base'} + - {type: object, properties: {children: {type: array, maxItems: 3}, b: {type: integer, minimum: 1}}} + Leaf: {$dynamicRef: "#node"} +`}, openapitest.ComponentSpecVer("3.1.0", ` Leaf: {$ref: "./other.yaml#/components/schemas/Leaf"} + Sub: {allOf: [{$ref: "./other.yaml#/components/schemas/Leaf"}, {type: object, properties: {children: {type: string}, b: {type: integer, maximum: 9}}}]} +`), openapi.Options{AllowExternalRefs: true}) + + openapitest.RequireNoErrorDiags(t, diags) + require.NotNil(t, typeByName(doc, "Leaf")) + redeclared := withCode(diags, diag.DegradedConstruct) + require.Len(t, redeclared, 1, "the redeclared member is read through the alias: %+v", diags) + assert.Contains(t, redeclared[0].Message, "/components/schemas/Tree/allOf/1/allOf/properties/children give types string and a list "+ + "that the merge cannot show to share a value or to share none") +} + +// TestMembers_AModelOverAnAliasSettlesAfterTheModelItNames holds a model +// composing the nullable alias a lone allOf of a model admitting null lowers +// to, beside a schema redeclaring that model's member: the model the alias +// names settles first, whatever the names sort as, so the redeclaration is +// read against its settled member, and the report names the type that member +// settled to. +func TestMembers_AModelOverAnAliasSettlesAfterTheModelItNames(t *testing.T) { + t.Parallel() + for _, composer := range []string{"Alpha", "Zulu"} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Root: + type: [object, "null"] + properties: {children: {type: array, items: {type: string}}} + Zed: + type: [object, "null"] + allOf: [{$ref: '#/components/schemas/Root'}] + properties: {children: {type: array, maxItems: 3}} + Wrap: {allOf: [{$ref: '#/components/schemas/Zed'}]} + `+composer+`: + allOf: + - $ref: '#/components/schemas/Wrap' + - {type: object, properties: {children: {type: string}}} +`)) + openapitest.RequireNoErrorDiags(t, diags) + alias, isAlias := typeByName(doc, "Wrap").(*ir.Scalar) + require.True(t, isAlias, "%s: the lone allOf lowers to an alias: %T", composer, typeByName(doc, "Wrap")) + require.NotNil(t, alias.Base, composer) + assert.Equal(t, typeByName(doc, "Zed").Common().ID, alias.Base.Target, composer) + redeclared := withCode(diags, diag.DegradedConstruct) + require.Len(t, redeclared, 1, "%s: %+v", composer, diags) + assert.Contains(t, redeclared[0].Message, "/components/schemas/Zed/allOf/properties/children give types string and a list "+ + "that the merge cannot show to share a value or to share none", composer) + } +} + +// TestAllOf_AnUnconvertedConstBesideKindsSharingNoneIsTheBottom holds a const +// no reading converts beside an allOf whose kinds share none: the const is no +// conjunct of the reading, so the position is the bottom, a closed Model with +// no member keeping each entry, the const reported where it is written as at +// the base, for an enum alike. +func TestAllOf_AnUnconvertedConstBesideKindsSharingNoneIsTheBottom(t *testing.T) { + t.Parallel() + for _, keyword := range []string{"const: .nan", "enum: [.nan]"} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " K: {"+keyword+", allOf: [{type: integer}, {type: boolean}]}\n")) + model, ok := typeByName(doc, "K").(*ir.Model) + require.True(t, ok, "%s: the bottom: got %T", keyword, typeByName(doc, "K")) + assert.Empty(t, model.Properties, keyword) + assert.Equal(t, ir.AdditionalClosed, model.Additional, keyword) + assert.Equal(t, []string{"openapi:allOf/0", "openapi:allOf/1"}, unmodeledKeys(model.Unmodeled), keyword) + name, _, _ := strings.Cut(keyword, ":") + at := "/components/schemas/K/" + name + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, at), "%s: %+v", keyword, diags) + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/K"), 1, keyword) + } +} diff --git a/compilers/openapi/internal/schema/allof_required_test.go b/compilers/openapi/internal/schema/allof_required_test.go index bc2be266d..d3ed5b11f 100644 --- a/compilers/openapi/internal/schema/allof_required_test.go +++ b/compilers/openapi/internal/schema/allof_required_test.go @@ -98,16 +98,16 @@ func TestAllOf_CompositionRequiredAttaches(t *testing.T) { wire: "id", }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, tc.spec) + doc, diags := schema.LowerSpec(t, testCase.spec) openapitest.RequireNoErrorDiags(t, diags) - model, ok := doc.Types[componentID(tc.model)].(*ir.Model) - require.True(t, ok, "%s should be a model", tc.model) - property, ok := openapitest.PropertiesByWire(model.Properties)[tc.wire] - require.True(t, ok, "%s should have a %q property", tc.model, tc.wire) - assert.True(t, property.Required, "%s.%s should be required via composition-scope required", tc.model, tc.wire) + model, ok := doc.Types[componentID(testCase.model)].(*ir.Model) + require.True(t, ok, "%s should be a model", testCase.model) + property, ok := openapitest.PropertiesByWire(model.Properties)[testCase.wire] + require.True(t, ok, "%s should have a %q property", testCase.model, testCase.wire) + assert.True(t, property.Required, "%s.%s should be required via composition-scope required", testCase.model, testCase.wire) assert.Empty(t, model.Requires, "every required name matches an own property, so none is listed beside them") }) } diff --git a/compilers/openapi/internal/schema/allof_residue_test.go b/compilers/openapi/internal/schema/allof_residue_test.go deleted file mode 100644 index 45a43808a..000000000 --- a/compilers/openapi/internal/schema/allof_residue_test.go +++ /dev/null @@ -1,455 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema_test - -import ( - "encoding/json/jsontext" - "fmt" - "slices" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" - "github.com/dexpace/morphic/compilers/openapi/internal/schema" - "github.com/dexpace/morphic/ir" -) - -// TestAllOf_InlineEntryResidueKeptVerbatim covers GitHub #123: what an inline -// allOf entry writes that neither the merge nor the position reads used to be -// dropped without a diagnostic. The entry now survives whole beside the composed -// model, and what the position does read lands where it would beside the allOf, -// what it would keep verbatim kept once, inside the entry. -func TestAllOf_InlineEntryResidueKeptVerbatim(t *testing.T) { - t.Parallel() - spec := openapitest.ComponentSpec(` S: - allOf: - - type: object - properties: {a: {type: string}} - required: [a] - unevaluatedProperties: false - not: {type: string} - minProperties: 2 - description: BranchDoc - x-vendor: keepme -`) - doc, diags := schema.LowerSpec(t, spec) - openapitest.RequireNoErrorDiags(t, diags) - model, ok := typeByName(doc, "S").(*ir.Model) - require.True(t, ok, "S should be a model") - - a, ok := openapitest.PropertiesByWire(model.Properties)["a"] - require.True(t, ok, "the merge still contributes the entry's properties") - assert.True(t, a.Required, "and still ORs the entry's required list onto them") - - entry, ok := model.Unmodeled["openapi:allOf/0"] - require.True(t, ok, "the entry is kept verbatim; got %+v", model.Unmodeled) - assert.Equal(t, ir.ReasonValidationOnly, entry.Reason, "the reason its unevaluatedProperties has beside the allOf") - assert.Equal(t, jsontext.Pointer("/components/schemas/S/allOf/0"), entry.Provenance.Pointer, - "the Unmodeled entry locates the allOf entry, not the composed schema") - for _, kept := range []string{ - `"unevaluatedProperties":false`, `"not":{"type":"string"}`, `"minProperties":2`, - `"description":"BranchDoc"`, `"x-vendor":"keepme"`, - } { - assert.Contains(t, string(entry.Value), kept, "the whole allOf entry is preserved") - } - assert.True(t, slices.ContainsFunc(diagsAtPointer(diags, diag.ValidationOnlyKeyword, "/components/schemas/S/allOf/0"), - func(diagnostic ir.Diagnostic) bool { - return strings.Contains(diagnostic.Message, "the entry (unevaluatedProperties)") - }), - "the diagnostic names what nothing read: %+v", diags) - assert.Equal(t, "BranchDoc", model.Docs.Description) - require.NotNil(t, model.Constraints) - assert.Equal(t, new(int64(2)), model.Constraints.MinProperties) - // What the entry kept whole folds is kept once, inside it. - assert.NotContains(t, model.Unmodeled, "openapi:x-vendor") - assert.NotContains(t, model.Unmodeled, "openapi:not") -} - -// TestAllOf_InlineEntryNonObjectTypeWarns is the worse half of #123: a scalar -// entry beside an object entry, the two sharing only null, contradicts the -// ir.Model they compose, which asserts the value is an object the entry says -// is a string, and no report of conjuncts sharing no value is drawn, since a -// shared null is a value. Preserving the entry keeps the source recoverable, -// and the severity says the IR states something wrong rather than merely -// incomplete. -func TestAllOf_InlineEntryNonObjectTypeWarns(t *testing.T) { - t.Parallel() - spec := openapitest.ComponentSpec(` T: - allOf: - - {type: object, nullable: true, properties: {a: {type: string}}} - - {type: string, nullable: true, maxLength: 3} -`) - doc, diags := schema.LowerSpec(t, spec) - openapitest.RequireNoErrorDiags(t, diags) - model, ok := typeByName(doc, "T").(*ir.Model) - require.True(t, ok, "the composed node is still a model") - require.Len(t, model.Properties, 1, "a scalar entry declares no properties to merge") - assert.Equal(t, "a", model.Properties[0].WireName) - - entry, ok := model.Unmodeled["openapi:allOf/1"] - require.True(t, ok, "the whole entry is kept verbatim; got %+v", model.Unmodeled) - assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assert.JSONEq(t, `{"type":"string","nullable":true,"maxLength":3}`, string(entry.Value)) - assert.Contains(t, - openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, "/components/schemas/T/allOf/1"), - "declares a type that is not an object") - assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/T/allOf/1"), 1, - "a contradicted model is a warning, not the info a merely narrowed one gets") -} - -// TestAllOf_EntryWrittenByReferenceStillDerivesResidue pins the residue against -// the two ways YAML lets an entry be written by reference rather than in place. -// An entry spelled `*anchor` writes no keys of its own and one spelled -// `<<: *anchor` writes only `<<`, so reading the literal text reports either no -// residue at all — merging an entry that declares plenty to an empty model, in -// silence, which is exactly the loss #123 closed for entries written in place — -// or a residue named `<<`, which names nothing a reader can act on. -func TestAllOf_EntryWrittenByReferenceStillDerivesResidue(t *testing.T) { - t.Parallel() - spec := openapitest.ComponentSpec(` O: {type: object, properties: {o: {type: string}}} - Shared: &br {unevaluatedProperties: false, type: string, maxLength: 3} - Aliased: {allOf: [{$ref: '#/components/schemas/O'}, *br]} - Merged: {allOf: [{$ref: '#/components/schemas/O'}, {<<: *br}]} - Overridden: {allOf: [{$ref: '#/components/schemas/O'}, {<<: *br, type: object, properties: {a: {type: string}}}]} -`) - doc, diags := schema.LowerSpec(t, spec) - openapitest.RequireNoErrorDiags(t, diags) - - cases := []struct { - name, wantKeys string - sev ir.Severity - }{ - {"Aliased", "unevaluatedProperties, type, maxLength", ir.SeverityInfo}, - {"Merged", "unevaluatedProperties, type, maxLength", ir.SeverityInfo}, - {"Overridden", "unevaluatedProperties, maxLength", ir.SeverityInfo}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - model, ok := typeByName(doc, tc.name).(*ir.Model) - require.True(t, ok, "%s should be a model", tc.name) - - entry, ok := model.Unmodeled["openapi:allOf/1"] - require.True(t, ok, "%s keeps the entry verbatim; got %+v", tc.name, model.Unmodeled) - assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assert.Contains(t, string(entry.Value), `"maxLength":3`, - "the payload resolves the reference too, so the entry is recoverable") - assert.Contains(t, - openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, tc.sev, - "/components/schemas/"+tc.name+"/allOf/1"), - "the entry ("+tc.wantKeys+")", - "the keywords the entry effectively declares are named, not `<<`") - }) - } -} - -// TestAllOf_MergedEntryKeywordsAreNotResidue guards the opposite direction: the -// keywords the merge does consume must not be preserved, or every allOf in the -// corpus would grow an Unmodeled entry restating what the composed model already -// holds. `type: object` counts as consumed because the composed node is a Model -// already. TypedBranch is the shape allof-inline-merge.yaml writes and -// RequiredOnlyBranch is allof-required-only.yaml's last entry; UntypedBranch — -// properties with no `type` at all — is written out here rather than borrowed -// from the corpus, which writes no such entry. -func TestAllOf_MergedEntryKeywordsAreNotResidue(t *testing.T) { - t.Parallel() - spec := openapitest.ComponentSpec(` Base: {type: object, properties: {id: {type: string}}} - TypedBranch: - allOf: - - {$ref: '#/components/schemas/Base'} - - type: object - properties: {name: {type: string}} - UntypedBranch: - allOf: - - {$ref: '#/components/schemas/Base'} - - properties: {name: {type: string}} - RequiredOnlyBranch: - allOf: - - {$ref: '#/components/schemas/Base'} - - type: object - properties: {name: {type: string}} - - required: [name] -`) - doc, diags := schema.LowerSpec(t, spec) - openapitest.RequireNoErrorDiags(t, diags) - for _, name := range []string{"TypedBranch", "UntypedBranch", "RequiredOnlyBranch"} { - model, ok := typeByName(doc, name).(*ir.Model) - require.True(t, ok, "%s should be a model", name) - assert.Empty(t, model.Unmodeled, - "%s: properties, required and a bare `type: object` are merged, not residue", name) - } - assert.Zero(t, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityInfo), - "an entry the merge fully consumes announces nothing; got %+v", diags) -} - -// TestAllOf_EntryResidueDerivedFromDeclaredKeys pins that the residue is derived -// from the entry's own declared keys rather than from a list of keywords worth -// keeping — a keyword this compiler models nothing for still counts, so a keyword -// a later dialect adds needs no change here to survive. The `[object, "null"]` -// case is the same rule from the other side: `type` is consumed only when it is -// exactly `object`, so the null a set also declares stays recoverable. -func TestAllOf_EntryResidueDerivedFromDeclaredKeys(t *testing.T) { - t.Parallel() - spec := openapitest.ComponentSpec(` Unknown: - allOf: - - type: object - properties: {a: {type: string}} - futureKeyword: {some: thing} - NullableBranch: - allOf: - - type: [object, 'null'] - properties: {a: {type: string}} -`) - doc, diags := schema.LowerSpec(t, spec) - openapitest.RequireNoErrorDiags(t, diags) - - for name, tc := range map[string]struct{ key, value, code, at string }{ - "Unknown": {"openapi:futureKeyword", `{"some":"thing"}`, diag.UnknownSchemaKeyword, "/allOf/0/futureKeyword"}, - "NullableBranch": {"openapi:type", `["object","null"]`, diag.DegradedConstruct, "/allOf/0"}, - } { - model, ok := typeByName(doc, name).(*ir.Model) - require.True(t, ok, "%s should be a model", name) - require.Len(t, model.Properties, 1, "%s still merges the entry's properties", name) - entry, ok := model.Unmodeled[tc.key] - require.True(t, ok, "%s keeps the keyword under its own key; got %+v", name, model.Unmodeled) - assert.JSONEq(t, tc.value, string(entry.Value), "%s", name) - assert.Contains(t, - openapitest.DiagMessageAt(t, diags, tc.code, ir.SeverityInfo, "/components/schemas/"+name+tc.at), - "kept verbatim under Unmodeled", name) - } -} - -// TestAllOf_EachInlineEntryKeyedSeparately: two entries that both leave residue -// must not overwrite each other's Unmodeled entry, and each is reported at its -// own entry. -func TestAllOf_EachInlineEntryKeyedSeparately(t *testing.T) { - t.Parallel() - spec := openapitest.ComponentSpec(` Multi: - allOf: - - type: object - properties: {a: {type: string}} - additionalProperties: false - - type: object - properties: {b: {type: string}} - patternProperties: {'^x': {type: string}} -`) - doc, diags := schema.LowerSpec(t, spec) - openapitest.RequireNoErrorDiags(t, diags) - model, ok := typeByName(doc, "Multi").(*ir.Model) - require.True(t, ok, "Multi should be a model") - require.Len(t, model.Properties, 2, "both entries still merge their properties") - require.Len(t, model.Unmodeled, 2, "one Unmodeled entry per allOf entry; got %+v", model.Unmodeled) - assert.Contains(t, string(model.Unmodeled["openapi:allOf/0"].Value), `"additionalProperties":false`) - assert.Contains(t, string(model.Unmodeled["openapi:allOf/1"].Value), `"patternProperties":`) - - for i, want := range []string{"additionalProperties", "patternProperties"} { - at := fmt.Sprintf("/components/schemas/Multi/allOf/%d", i) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), want, - "entry %d is reported at its own pointer, naming its own residue", i) - } -} - -// TestAllOf_EntryResidueRidesEveryDistributedVariant covers fillAllOf's second -// caller: buildComposedVariant re-runs the same merge once per union variant, so -// the residue, the whole entry, has to land on every variant the composition -// rides on, while what the entry folds reaches the Union. The diagnostic is -// announced once even so — the entry is one source construct however many -// variants carry it. -func TestAllOf_EntryResidueRidesEveryDistributedVariant(t *testing.T) { - t.Parallel() - spec := openapitest.ComponentSpec(` Base: {type: object, properties: {id: {type: string}}} - A: {type: object, properties: {a: {type: string}}} - B: {type: object, properties: {b: {type: string}}} - Distributed: - allOf: - - {$ref: '#/components/schemas/Base'} - - type: object - properties: {c: {type: string}} - description: BranchDoc - unevaluatedProperties: false - oneOf: - - {$ref: '#/components/schemas/A'} - - {$ref: '#/components/schemas/B'} -`) - doc, diags := schema.LowerSpec(t, spec) - openapitest.RequireNoErrorDiags(t, diags) - union, ok := typeByName(doc, "Distributed").(*ir.Union) - require.True(t, ok, "Distributed distributes into a union") - require.Len(t, union.Variants, 2) - - for i, irVariant := range union.Variants { - variant, ok := doc.Types[irVariant.Type.Target].(*ir.Model) - require.True(t, ok, "variant %d is a composed model", i) - entry, ok := variant.Unmodeled["openapi:allOf/1"] - require.True(t, ok, "variant %d carries the entry residue; got %+v", i, variant.Unmodeled) - assert.Contains(t, string(entry.Value), `"description":"BranchDoc"`, "variant %d", i) - } - assert.Equal(t, "BranchDoc", union.Docs.Description) - assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.ValidationOnlyKeyword, ir.SeverityInfo), - "one entry, one diagnostic, however many variants carry it; got %+v", diags) -} - -// TestAllOf_UnpreservableEntryIsNotAnnounced is -// TestUnhomedApplicator_UnpreservableKeywordIsNotAnnounced's pairing on the -// composition path: an entry the merge does not consume whole is normally kept -// beside the model and reported, and when the keeping fails the report must not -// happen either. -func TestAllOf_UnpreservableEntryIsNotAnnounced(t *testing.T) { - t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` M: - allOf: - - {additionalProperties: false, x-t: `+unpreservableValue+`} -`)) - - td := typeByName(doc, "M") - require.NotNil(t, td) - assert.NotContains(t, td.Common().Unmodeled, "openapi:allOf/0", "the entry did not convert") - assert.True(t, openapitest.HasDiag(diags, diag.UnpreservableConstruct)) - assert.Empty(t, openapitest.PreservationClaims(diags), - "no degradation is announced for an entry that was not kept") -} - -// TestAllOf_AnUnpreservableUncomposedRefIsNotAnnounced pins the same for an -// entry writing beside a $ref a composition keeps rather than composes, its -// target no object: the reference is kept, and announced, and the extension -// the rest of the entry writes, a conjunct of its own, folds and is reported -// where it fails to convert, which claims no preservation. -func TestAllOf_AnUnpreservableUncomposedRefIsNotAnnounced(t *testing.T) { - t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Str: {type: string} - M: - allOf: - - {$ref: '#/components/schemas/Str', x-t: `+unpreservableValue+`} - - {type: object, properties: {a: {type: string}}} -`)) - - model, ok := typeByName(doc, "M").(*ir.Model) - require.True(t, ok, "the conjuncts share no value, so the allOf composes") - assert.Nil(t, model.Base, "a model composes no string") - assert.Contains(t, model.Unmodeled, "openapi:$ref", "the reference converts") - assert.NotContains(t, model.Unmodeled, "openapi:allOf/0", "the rest of the entry, which folds, is no residue") - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, - "/components/schemas/M/allOf/0"), `extension "x-t" could not be serialized`) - assert.Len(t, openapitest.PreservationClaims(diags), 1, "only the reference is announced") -} - -// TestAllOf_ANullTypeExcludesNoObject pins that an entry's `type: null` is the -// keyword left out, so what it keeps as residue is reported as an info, not as -// the warning a type excluding object draws. An entry writing properties keeps -// the allOf a composition, where an entry's type is weighed against an object. -func TestAllOf_ANullTypeExcludesNoObject(t *testing.T) { - t.Parallel() - _, diags := parseFull(t, openapitest.ComponentSpec(` S: {allOf: [{type: null, minItems: 1}, {properties: {p: {}}}]} -`)) - var severities []ir.Severity - for _, diagnostic := range diags { - if diagnostic.Code == diag.DegradedConstruct && strings.Contains(diagnostic.Message, "inline") { - severities = append(severities, diagnostic.Severity) - } - } - assert.Equal(t, []ir.Severity{ir.SeverityInfo}, severities) -} - -// rebasedEntryTargets declares the two schemas `n.json` names under the two -// bases the rebased-entry cases write. -const rebasedEntryTargets = ` A: {$id: 'https://ex.test/a/n.json', type: string} - B: {$id: 'https://ex.test/b/n.json', type: integer} -` - -// TestAllOf_AnEntryReadAgainstAnotherBaseFoldsNothing holds an inline entry -// under an $id naming another URI to keeping what it writes, wherever the $id -// is written: `n.json` names A there and B at the position, so folding its `not` -// would read it as B's. Spelled shows the outer entry folding as it does when -// its $ref names B outright, and Annotated that the rule holds for a keyword -// with no $ref in it. -func TestAllOf_AnEntryReadAgainstAnotherBaseFoldsNothing(t *testing.T) { - t.Parallel() - // code is the report's: an entry holding validation logic alone is kept as - // that, and reported so. - for name, tc := range map[string]struct{ schema, kept, folded, code string }{ - "Wrapped": {` $id: 'https://ex.test/b/s.json' - allOf: - - $id: 'https://ex.test/a/w.json' - allOf: [{type: object, not: {$ref: 'n.json'}}] - - {type: object, not: {$ref: 'n.json'}} -`, "openapi:allOf/0/allOf/0", `{"$ref":"n.json"}`, diag.ValidationOnlyKeyword}, - "Spelled": {` $id: 'https://ex.test/b/s.json' - allOf: - - $id: 'https://ex.test/a/w.json' - allOf: [{type: object, not: {$ref: 'n.json'}}] - - {type: object, not: {$ref: 'https://ex.test/b/n.json'}} -`, "openapi:allOf/0/allOf/0", `{"$ref":"https://ex.test/b/n.json"}`, diag.ValidationOnlyKeyword}, - "Annotated": {` allOf: - - {type: object, properties: {a: {type: string}}} - - {$id: 'https://ex.test/a/x.json', not: {$ref: 'n.json'}, description: d} -`, "openapi:allOf/1", "", diag.DegradedConstruct}, - } { - t.Run(name, func(t *testing.T) { - t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", rebasedEntryTargets+" S:\n"+tc.schema)) - openapitest.RequireNoErrorDiags(t, diags) - um := typeByName(doc, "S").Common().Unmodeled - - kept, ok := um[tc.kept] - require.True(t, ok, "the entry is kept whole; got %+v", um) - assert.Contains(t, string(kept.Value), `"not":{"$ref":"n.json"}`) - assert.Contains(t, - openapitest.DiagMessageAt(t, diags, tc.code, ir.SeverityInfo, "/components/schemas/S/"+tc.kept[len("openapi:"):]), - "reads its $refs against another base") - assert.Equal(t, tc.folded, string(um["openapi:not"].Value), "the outer entry folds its not, if it writes one") - assert.Empty(t, typeByName(doc, "S").Common().Docs.Description, "nothing the kept entry writes folds") - }) - } -} - -// TestAllOf_AnEntryWritingNoRelativeReferenceFoldsUnderAnyBase pins that an $id -// naming another URI keeps an entry whole only where what it folds writes a -// relative $ref: text naming none reads the same at the position, so the bounds -// and the `not` of entries under two other bases fold as they would with no -// $id, and so do M's description beside a $ref its property resolves where it -// is written, and N's beside an absolute $ref. -func TestAllOf_AnEntryWritingNoRelativeReferenceFoldsUnderAnyBase(t *testing.T) { - t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", rebasedEntryTargets+` S: - type: string - allOf: - - {$id: 'https://ex.test/a/x.json', minLength: 1, not: {const: q}} - - $id: 'https://ex.test/a/w.json' - allOf: [{maxLength: 5}] - M: - type: object - allOf: - - {$id: 'https://ex.test/a/x.json', type: object, properties: {a: {$ref: 'n.json'}}, description: d} - - {type: object, properties: {b: {type: string}}} - N: - type: object - allOf: - - {$id: 'https://ex.test/a/x.json', description: d, not: {$ref: 'https://ex.test/b/n.json'}} - - {type: object, properties: {b: {type: string}}} -`)) - openapitest.RequireNoErrorDiags(t, diags) - model, ok := typeByName(doc, "M").(*ir.Model) - require.True(t, ok) - assert.Equal(t, "d", model.Docs.Description) - typeCommon := typeByName(doc, "N").Common() - assert.Equal(t, "d", typeCommon.Docs.Description) - assert.JSONEq(t, `{"$ref":"https://ex.test/b/n.json"}`, string(typeCommon.Unmodeled["openapi:not"].Value)) - assert.Equal(t, typeByName(doc, "A").Common().ID, openapitest.PropertiesByWire(model.Properties)["a"].Type.Target) - scalar, ok := typeByName(doc, "S").(*ir.Scalar) - require.True(t, ok) - require.NotNil(t, scalar.Constraints) - require.NotNil(t, scalar.Constraints.MinLength) - require.NotNil(t, scalar.Constraints.MaxLength) - assert.Equal(t, int64(1), *scalar.Constraints.MinLength) - assert.Equal(t, int64(5), *scalar.Constraints.MaxLength) - assert.NotContains(t, scalar.Unmodeled, "openapi:not", "its entries write $id apart, so each is kept whole, holding its not") - assert.Contains(t, string(scalar.Unmodeled["openapi:allOf/0"].Value), `"not":{"const":"q"}`) - for _, diagnostic := range diags { - assert.NotContains(t, diagnostic.Message, "against another base") - } -} diff --git a/compilers/openapi/internal/schema/allof_test.go b/compilers/openapi/internal/schema/allof_test.go index 7b96f1748..390d50781 100644 --- a/compilers/openapi/internal/schema/allof_test.go +++ b/compilers/openapi/internal/schema/allof_test.go @@ -75,11 +75,11 @@ func TestAllOf_ExtraRefsBecomeMixins(t *testing.T) { } // TestAllOf_ARefToAHierarchyMemberIsTheBase pins the Base an allOf of several -// $refs elects (docs/compilers/openapi.md#allof-classification): the first whose -// target takes part in a discriminator hierarchy, declaring the discriminator or -// composing one that does at any depth, so a schema composing a subtype is a -// subtype too, in either declaration order; where none does, each $ref is a -// Mixin (GitHub #986). +// $refs chooses (docs/compilers/openapi.md#allof-classification): the first +// whose target takes part in a discriminator hierarchy, declaring the +// discriminator or composing one that does at any depth, so a schema composing +// a subtype is a subtype too, in either declaration order; where none does, +// each $ref is a Mixin (GitHub #986). func TestAllOf_ARefToAHierarchyMemberIsTheBase(t *testing.T) { t.Parallel() ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } @@ -99,7 +99,7 @@ func TestAllOf_ARefToAHierarchyMemberIsTheBase(t *testing.T) { Other: {type: object, properties: {x: {type: string}}} Extra: {type: object, properties: {y: {type: string}}} `) { - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { base string mixins []string }{ @@ -112,14 +112,14 @@ func TestAllOf_ARefToAHierarchyMemberIsTheBase(t *testing.T) { for _, typeRef := range model.Mixins { mixins = append(mixins, strings.TrimPrefix(string(typeRef.Target), string(componentID("")))) } - assert.Equal(t, tc.mixins, mixins, name) - if tc.base == "" { + assert.Equal(t, testCase.mixins, mixins, name) + if testCase.base == "" { assert.Nil(t, model.Base, name) assert.False(t, ir.IsSubtype(doc, componentID(name), componentID("Root")), name) continue } require.NotNil(t, model.Base, name) - assert.Equal(t, componentID(tc.base), model.Base.Target, name) + assert.Equal(t, componentID(testCase.base), model.Base.Target, name) assert.True(t, ir.IsSubtype(doc, componentID(name), componentID("Root")), "%s is a subtype of Root", name) } } @@ -251,16 +251,16 @@ func TestAllOf_ARefEntryNamingNothingIsReportedByTheLowering(t *testing.T) { - $ref: '#/components/schemas/A' `, []ir.TypeRef{{Target: componentID("A")}}, false}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := lowerSpecOnly(t, openapitest.ComponentSpec(" A: {type: object, properties: {a: {type: string}}}\n Y:\n allOf:\n"+tc.entries)) + doc, diags := lowerSpecOnly(t, openapitest.ComponentSpec(" A: {type: object, properties: {a: {type: string}}}\n Y:\n allOf:\n"+testCase.entries)) require.Len(t, diags, 1, "got %+v", diags) assert.Equal(t, diag.UnresolvedRef, diags[0].Code) assert.Equal(t, ir.SeverityError, diags[0].Severity) assert.Equal(t, jsontext.Pointer("/components/schemas/Y/allOf/0"), diags[0].Provenance.Pointer) - if tc.reference { + if testCase.reference { scalar, ok := typeByName(doc, "Y").(*ir.Scalar) require.True(t, ok, "Y is the reference, got %T", typeByName(doc, "Y")) assert.Equal(t, ir.TypeID("type/primitive/any"), scalar.Base.Target) @@ -269,7 +269,7 @@ func TestAllOf_ARefEntryNamingNothingIsReportedByTheLowering(t *testing.T) { model, ok := typeByName(doc, "Y").(*ir.Model) require.True(t, ok, "Y is a Model, got %T", typeByName(doc, "Y")) assert.Nil(t, model.Base, "the entry naming nothing is not the base") - assert.Equal(t, tc.mixins, model.Mixins, "the entry naming nothing is not a mixin") + assert.Equal(t, testCase.mixins, model.Mixins, "the entry naming nothing is not a mixin") }) } } @@ -295,19 +295,25 @@ func TestAllOf_MultiRefWithUnresolvedDoesNotAnchor(t *testing.T) { } // TestAllOf_EmptyAllOfBesideNonObjectTypeNamesBoth pins that an entry whose -// empty allOf was not flattened lists allOf among the kept keywords on the -// warning arm too: only a capped entry leaves it out. The source breaks the -// schema's minItems, an error the load reports and parseFull tolerates. +// empty allOf was not flattened lists allOf among the keywords it keeps: only +// a capped entry leaves it out. Conjuncts sharing null alone, a union among +// them, are the null type, the closed empty Enum no Model is, so the entry's +// report is an info. The source breaks the schema's minItems, an error the +// load reports and parseFull tolerates. func TestAllOf_EmptyAllOfBesideNonObjectTypeNamesBoth(t *testing.T) { t.Parallel() doc, _ := parseFull(t, openapitest.ComponentSpec(nestedAB+` M: allOf: - - {type: string, nullable: true, allOf: []} - - {type: object, nullable: true, properties: {u: {type: string}}} + - {type: [string, 'null'], allOf: []} + - {oneOf: [{type: object, properties: {u: {type: string}}}, {type: 'null'}]} `)) + node, ok := typeByName(doc, "M").(*ir.Enum) + require.True(t, ok, "the null type; got %T", typeByName(doc, "M")) + assert.True(t, node.Closed) + assert.Empty(t, node.Members) message := openapitest.DiagMessageAt(t, doc.Diagnostics, diag.DegradedConstruct, - ir.SeverityWarning, "/components/schemas/M/allOf/0") - assert.Contains(t, message, "the entry (type, allOf) is kept verbatim") + ir.SeverityInfo, "/components/schemas/M/allOf/0") + assert.Contains(t, message, "the entry (allOf) is kept verbatim", "naming the allOf it holds") } // TestAllOf_FalseEntryClosesTheCatchAllItForbids pins that a `false` allOf @@ -329,12 +335,12 @@ func TestAllOf_FalseEntryClosesTheCatchAllItForbids(t *testing.T) { {"patterns alone", patterns, true, false}, {"patterns beside a written catch-all", written + patterns, true, true}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() const entries = " allOf: [false, {type: object, required: [a]}]\n" - spec := openapitest.ComponentSpec(pq + " M:\n" + entries + tc.beside + - " U:\n oneOf: [{$ref: '#/components/schemas/P'}, {$ref: '#/components/schemas/Q'}]\n" + entries + tc.beside) + spec := openapitest.ComponentSpec(pq + " M:\n" + entries + testCase.beside + + " U:\n oneOf: [{$ref: '#/components/schemas/P'}, {$ref: '#/components/schemas/Q'}]\n" + entries + testCase.beside) doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) @@ -345,12 +351,12 @@ func TestAllOf_FalseEntryClosesTheCatchAllItForbids(t *testing.T) { require.True(t, ok, "%s is a model, not %T", id, doc.Types[id]) assert.Equal(t, ir.AdditionalClosed, model.Additional, id) entry, raw := model.Unmodeled["openapi:additionalProperties"] - require.Equal(t, tc.raw, raw, "%s: what the source writes is kept, and only that: %+v", id, model.Unmodeled) + require.Equal(t, testCase.raw, raw, "%s: what the source writes is kept, and only that: %+v", id, model.Unmodeled) if raw { assert.JSONEq(t, `{"type": "string"}`, string(entry.Value), id) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason, id) } - if !tc.kept { + if !testCase.kept { assert.Nil(t, model.AdditionalProperties, "%s: a catch-all left no pattern is none", id) continue } @@ -362,12 +368,12 @@ func TestAllOf_FalseEntryClosesTheCatchAllItForbids(t *testing.T) { } } -// TestAllOf_ACatchAllLeavesAClosureAfterCompositionInert pins the other side of -// that rule: a catch-all `additionalProperties` writes evaluates every key the -// patterns leave, so `unevaluatedProperties: false` beside it forbids none of -// them. The value stays, the model stays open, and the keyword is kept beside -// the catch-all that leaves it inert. -func TestAllOf_ACatchAllLeavesAClosureAfterCompositionInert(t *testing.T) { +// TestAllOf_ACatchAllLeavesAClosureAfterCompositionSayingNothing pins the other +// side of that rule: a catch-all `additionalProperties` writes evaluates every +// key the patterns leave, so `unevaluatedProperties: false` beside it forbids +// none of them. The value stays, the model stays open, and the keyword is kept +// beside the catch-all that leaves it saying nothing. +func TestAllOf_ACatchAllLeavesAClosureAfterCompositionSayingNothing(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` M: allOf: [{type: object, required: [a]}] @@ -406,10 +412,10 @@ func TestAllOf_FalseEntryBesideUnionClosesEveryVariant(t *testing.T) { const pq = ` P: {type: object, properties: {p: {type: string}}} Q: {type: object, properties: {q: {type: string}}} ` - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - u := " U:\n oneOf: [{$ref: '#/components/schemas/P'}, {$ref: '#/components/schemas/Q'}]\n allOf:\n" + tc.allOf + u := " U:\n oneOf: [{$ref: '#/components/schemas/P'}, {$ref: '#/components/schemas/Q'}]\n allOf:\n" + testCase.allOf for _, doc := range nestedOrders(t, u, nestedAB+pq) { for _, id := range []ir.TypeID{ "type/composed/components/schemas/U/oneOf/0", @@ -418,15 +424,15 @@ func TestAllOf_FalseEntryBesideUnionClosesEveryVariant(t *testing.T) { model, ok := doc.Types[id].(*ir.Model) require.True(t, ok, "%s should be a model", id) assert.Equal(t, ir.AdditionalClosed, model.Additional, id) - entry, ok := model.Unmodeled[tc.key] - require.True(t, ok, "%s: the false is kept under %s; got %+v", id, tc.key, model.Unmodeled) + entry, ok := model.Unmodeled[testCase.key] + require.True(t, ok, "%s: the false is kept under %s; got %+v", id, testCase.key, model.Unmodeled) assert.Equal(t, "false", string(entry.Value)) - assert.Equal(t, jsontext.Pointer(tc.pointer), entry.Provenance.Pointer) + assert.Equal(t, jsontext.Pointer(testCase.pointer), entry.Provenance.Pointer) } n := 0 for _, diagnostic := range doc.Diagnostics { if diagnostic.Code == diag.FalseSchema && diagnostic.Severity == ir.SeverityInfo && - diagnostic.Provenance.Pointer == jsontext.Pointer(tc.pointer) { + diagnostic.Provenance.Pointer == jsontext.Pointer(testCase.pointer) { n++ } } diff --git a/compilers/openapi/internal/schema/allof_unread_keywords_test.go b/compilers/openapi/internal/schema/allof_unread_keywords_test.go new file mode 100644 index 000000000..55df8c6ab --- /dev/null +++ b/compilers/openapi/internal/schema/allof_unread_keywords_test.go @@ -0,0 +1,576 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "fmt" + "slices" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// TestAllOf_InlineEntryUnreadKeywordsKeptVerbatim covers GitHub #123: what an +// inline allOf entry writes that neither the merge nor the position reads used +// to be dropped without a diagnostic. The entry now survives whole beside the +// composed model, and what the position does read lands where it would beside +// the allOf, what it would keep verbatim kept once, inside the entry, and the +// entry's one report names every keyword it holds that nothing reads. +func TestAllOf_InlineEntryUnreadKeywordsKeptVerbatim(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpec(` S: + allOf: + - type: object + properties: {a: {type: string}} + required: [a] + unevaluatedProperties: false + not: {type: string} + minProperties: 2 + description: BranchDoc + x-vendor: keepme +`) + doc, diags := schema.LowerSpec(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "S").(*ir.Model) + require.True(t, ok, "S should be a model") + + a, ok := openapitest.PropertiesByWire(model.Properties)["a"] + require.True(t, ok, "the merge still contributes the entry's properties") + assert.True(t, a.Required, "and still ORs the entry's required list onto them") + + entry, ok := model.Unmodeled["openapi:allOf/0"] + require.True(t, ok, "the entry is kept verbatim; got %+v", model.Unmodeled) + assert.Equal(t, ir.ReasonValidationOnly, entry.Reason, "the reason its unevaluatedProperties has beside the allOf") + assert.Equal(t, jsontext.Pointer("/components/schemas/S/allOf/0"), entry.Provenance.Pointer, + "the Unmodeled entry locates the allOf entry, not the composed schema") + for _, kept := range []string{ + `"unevaluatedProperties":false`, `"not":{"type":"string"}`, `"minProperties":2`, + `"description":"BranchDoc"`, `"x-vendor":"keepme"`, + } { + assert.Contains(t, string(entry.Value), kept, "the whole allOf entry is preserved") + } + assert.True(t, slices.ContainsFunc(diagsAtPointer(diags, diag.ValidationOnlyKeyword, "/components/schemas/S/allOf/0"), + func(diagnostic ir.Diagnostic) bool { + return strings.Contains(diagnostic.Message, "the entry (unevaluatedProperties, not, x-vendor)") + }), + "the diagnostic names what nothing read: %+v", diags) + assert.Equal(t, "BranchDoc", model.Docs.Description) + require.NotNil(t, model.Constraints) + assert.Equal(t, new(int64(2)), model.Constraints.MinProperties) + // What the entry kept whole folds is kept once, inside it. + assert.NotContains(t, model.Unmodeled, "openapi:x-vendor") + assert.NotContains(t, model.Unmodeled, "openapi:not") +} + +// TestAllOf_InlineEntryNonObjectTypeSharingOnlyNullIsTheNull holds a scalar +// entry beside an object entry, the two sharing only null: no Model asserts an +// object the scalar entry rules out, the position is the null type, as +// `{type: 'null'}` is, and what each entry writes the Enum has no field for is +// kept at the entry with an info, its nullable said by the null the Enum's use +// admits (docs/compilers/openapi.md#allof-refinement). +func TestAllOf_InlineEntryNonObjectTypeSharingOnlyNullIsTheNull(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpecVer("3.0.3", ` T: + allOf: + - {type: object, nullable: true, properties: {a: {type: string}}} + - {type: string, nullable: true, maxLength: 3} +`) + doc, diags := schema.LowerSpec(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "T").(*ir.Enum) + require.True(t, ok, "the null type: got %T", typeByName(doc, "T")) + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.ElementsMatch(t, []string{"openapi:properties", "openapi:maxLength"}, unmodeledKeys(enum.Unmodeled)) + for _, entry := range []string{"/components/schemas/T/allOf/0", "/components/schemas/T/allOf/1"} { + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, entry), 1, entry) + } + assert.Zero(t, openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning)) +} + +// TestAllOf_EntryWrittenByReferenceStillDerivesUnreadKeywords pins the unread +// keywords against the two ways YAML lets an entry be written by reference +// rather than in place. An entry spelled `*anchor` writes no keys of its own +// and one spelled `<<: *anchor` writes only `<<`, so reading the literal text +// reports either no unread keywords at all — merging an entry that declares +// plenty to an empty model, in silence, which is exactly the loss #123 closed +// for entries written in place — or an unread keyword named `<<`, which names +// nothing a reader can act on. +func TestAllOf_EntryWrittenByReferenceStillDerivesUnreadKeywords(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpec(` O: {type: object, properties: {o: {type: string}}} + Shared: &br {unevaluatedProperties: false, type: string, maxLength: 3} + Aliased: {allOf: [{$ref: '#/components/schemas/O'}, *br]} + Merged: {allOf: [{$ref: '#/components/schemas/O'}, {<<: *br}]} + Overridden: {allOf: [{$ref: '#/components/schemas/O'}, {<<: *br, type: object, properties: {a: {type: string}}}]} +`) + doc, diags := schema.LowerSpec(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + + // A string entry beside the object O shares no kind with it, so Aliased + // and Merged are the closed bottom, which keeps the entry whole under its + // entry key, resolved, beside the schema's one warning. + for _, name := range []string{"Aliased", "Merged"} { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s is the bottom", name) + assert.Empty(t, model.Properties, name) + entry, ok := model.Unmodeled["openapi:allOf/1"] + require.True(t, ok, "%s keeps the entry whole; got %+v", name, model.Unmodeled) + assert.Contains(t, string(entry.Value), `"maxLength":3`, "%s: the payload resolves the reference", name) + assert.NotContains(t, string(entry.Value), "<<", name) + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name), 1, name) + } + cases := []struct { + name, wantKeys string + sev ir.Severity + }{ + {"Overridden", "unevaluatedProperties, maxLength", ir.SeverityInfo}, + } + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + model, ok := typeByName(doc, testCase.name).(*ir.Model) + require.True(t, ok, "%s should be a model", testCase.name) + + entry, ok := model.Unmodeled["openapi:allOf/1"] + require.True(t, ok, "%s keeps the entry verbatim; got %+v", testCase.name, model.Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) + assert.Contains(t, string(entry.Value), `"maxLength":3`, + "the payload resolves the reference too, so the entry is recoverable") + assert.Contains(t, + openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, testCase.sev, + "/components/schemas/"+testCase.name+"/allOf/1"), + "the entry ("+testCase.wantKeys+")", + "the keywords the entry effectively declares are named, not `<<`") + }) + } +} + +// TestAllOf_MergedEntryKeywordsAreNotUnread guards the opposite direction: the +// keywords the merge does consume must not be preserved, or every allOf in the +// corpus would grow an Unmodeled entry restating what the composed model +// already holds. `type: object` counts as consumed because the composed node is +// a Model already. TypedBranch is the shape allof-inline-merge.yaml writes and +// RequiredOnlyBranch is allof-required-only.yaml's last entry; UntypedBranch — +// properties with no `type` at all — is written out here rather than borrowed +// from the corpus, which writes no such entry. +func TestAllOf_MergedEntryKeywordsAreNotUnread(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpec(` Base: {type: object, properties: {id: {type: string}}} + TypedBranch: + allOf: + - {$ref: '#/components/schemas/Base'} + - type: object + properties: {name: {type: string}} + UntypedBranch: + allOf: + - {$ref: '#/components/schemas/Base'} + - properties: {name: {type: string}} + RequiredOnlyBranch: + allOf: + - {$ref: '#/components/schemas/Base'} + - type: object + properties: {name: {type: string}} + - required: [name] +`) + doc, diags := schema.LowerSpec(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"TypedBranch", "UntypedBranch", "RequiredOnlyBranch"} { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s should be a model", name) + assert.Empty(t, model.Unmodeled, + "%s: properties, required and a bare `type: object` are merged, not unread", name) + } + assert.Zero(t, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityInfo), + "an entry the merge fully consumes announces nothing; got %+v", diags) +} + +// TestAllOf_EntryUnreadKeywordsDerivedFromDeclaredKeys pins that the unread +// keywords are derived from the entry's own declared keys rather than from a +// list of keywords worth keeping — a keyword this compiler models nothing for +// still counts, so a keyword a later dialect adds needs no change here to +// survive. A `type` list naming `object`, null aside, is consumed as one beside +// the allOf is, the Model restating it and the null reading reading its null, +// so a use of it admits null and nothing keeps the keyword. +func TestAllOf_EntryUnreadKeywordsDerivedFromDeclaredKeys(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpec(` Unknown: + allOf: + - type: object + properties: {a: {type: string}} + futureKeyword: {some: thing} + NullableBranch: + allOf: + - type: [object, 'null'] + properties: {a: {type: string}} + Holder: + type: object + properties: + n: {$ref: '#/components/schemas/NullableBranch'} +`) + doc, diags := schema.LowerSpec(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + + nullable, ok := typeByName(doc, "NullableBranch").(*ir.Model) + require.True(t, ok, "NullableBranch should be a model") + require.Len(t, nullable.Properties, 1, "NullableBranch still merges the entry's properties") + assert.Empty(t, nullable.Unmodeled, "NullableBranch keeps nothing") + holder, ok := typeByName(doc, "Holder").(*ir.Model) + require.True(t, ok, "Holder should be a model") + require.Len(t, holder.Properties, 1) + assert.True(t, holder.Properties[0].Type.Nullable, "a use of NullableBranch admits its null") + for name, testCase := range map[string]struct{ key, value, code, at string }{ + "Unknown": {"openapi:futureKeyword", `{"some":"thing"}`, diag.UnknownSchemaKeyword, "/allOf/0/futureKeyword"}, + } { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s should be a model", name) + require.Len(t, model.Properties, 1, "%s still merges the entry's properties", name) + entry, ok := model.Unmodeled[testCase.key] + require.True(t, ok, "%s keeps the keyword under its own key; got %+v", name, model.Unmodeled) + assert.JSONEq(t, testCase.value, string(entry.Value), "%s", name) + assert.Contains(t, + openapitest.DiagMessageAt(t, diags, testCase.code, ir.SeverityInfo, "/components/schemas/"+name+testCase.at), + "kept verbatim under Unmodeled", name) + } +} + +// TestAllOf_EachInlineEntryKeyedSeparately: two entries that both leave unread +// keywords must not overwrite each other's Unmodeled entry, and each is +// reported at its own entry. +func TestAllOf_EachInlineEntryKeyedSeparately(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpec(` Multi: + allOf: + - type: object + properties: {a: {type: string}} + additionalProperties: false + - type: object + properties: {b: {type: string}} + patternProperties: {'^x': {type: string}} +`) + doc, diags := schema.LowerSpec(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "Multi").(*ir.Model) + require.True(t, ok, "Multi should be a model") + require.Len(t, model.Properties, 2, "both entries still merge their properties") + require.Len(t, model.Unmodeled, 2, "one Unmodeled entry per allOf entry; got %+v", model.Unmodeled) + assert.Contains(t, string(model.Unmodeled["openapi:allOf/0"].Value), `"additionalProperties":false`) + assert.Contains(t, string(model.Unmodeled["openapi:allOf/1"].Value), `"patternProperties":`) + + for i, want := range []string{"additionalProperties", "patternProperties"} { + at := fmt.Sprintf("/components/schemas/Multi/allOf/%d", i) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), want, + "entry %d is reported at its own pointer, naming its own unread keywords", i) + } +} + +// TestAllOf_EntryUnreadKeywordsAreKeptOnceOnTheDistributedUnion holds that the +// unread keyword of an entry beside a union written beside the allOf, the +// keyword the IR has no home for, is kept once, on the Union at the position, +// and on no variant the composition rides on, as a keyword written beside the +// allOf is: one fact is said on one node, where a reader of the position looks, +// whichever spelling writes it. What the entry folds reaches the Union, and the +// diagnostic is announced once (GitHub #2054). +func TestAllOf_EntryUnreadKeywordsAreKeptOnceOnTheDistributedUnion(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpec(` Base: {type: object, properties: {id: {type: string}}} + A: {type: object, properties: {a: {type: string}}} + B: {type: object, properties: {b: {type: string}}} + Distributed: + allOf: + - {$ref: '#/components/schemas/Base'} + - type: object + properties: {c: {type: string}} + description: BranchDoc + unevaluatedProperties: false + oneOf: + - {$ref: '#/components/schemas/A'} + - {$ref: '#/components/schemas/B'} +`) + doc, diags := schema.LowerSpec(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + union, ok := typeByName(doc, "Distributed").(*ir.Union) + require.True(t, ok, "Distributed distributes into a union") + require.Len(t, union.Variants, 2) + + for i, irVariant := range union.Variants { + variant, ok := doc.Types[irVariant.Type.Target].(*ir.Model) + require.True(t, ok, "variant %d is a composed model", i) + assert.Empty(t, keptUnreadKeywords(variant.Unmodeled), "variant %d keeps no unread keywords", i) + } + assert.Len(t, keptUnreadKeywords(union.Unmodeled), 1, "the Union keeps the unread keywords once; got %+v", union.Unmodeled) + assert.Equal(t, "BranchDoc", union.Docs.Description) + assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.ValidationOnlyKeyword, ir.SeverityInfo), + "one entry, one diagnostic; got %+v", diags) +} + +// keptUnreadKeywords lists the keys of unmodeled keeping the entry's +// unevaluatedProperties, under its own key or inside the entry kept whole. +func keptUnreadKeywords(unmodeled ir.Unmodeled) []string { + var keys []string + for key, entry := range unmodeled { + if strings.HasSuffix(key, "unevaluatedProperties") || strings.Contains(string(entry.Value), `"unevaluatedProperties"`) { + keys = append(keys, key) + } + } + return keys +} + +// unconvertibleExtension is an extension whose value converts to no JSON, as a +// spec writes it after another member of a flow mapping. +const unconvertibleExtension = ", x-t: " + unpreservableValue + +// requireKeptWithoutExtension holds spec, as compile compiles it, writing +// extension once on each object at at, to the document the same spec compiles +// to without it, but for the extension's own warning at each: the extension +// alone is dropped, what holds it kept and reported as without it, with no +// error and no claim that the extension was kept. +func requireKeptWithoutExtension( + t *testing.T, compile func(*testing.T, string) (*ir.Document, []ir.Diagnostic), spec, extension string, at ...string, +) *ir.Document { + t.Helper() + require.Equal(t, len(at), strings.Count(spec, extension), "the spec writes the extension once at each site") + name, _, _ := strings.Cut(strings.TrimPrefix(extension, ", "), ":") + doc, diags := compile(t, spec) + withoutExtension, withoutExtensionDiags := compile(t, strings.ReplaceAll(spec, extension, "")) + + openapitest.RequireNoErrorDiags(t, diags) + for _, pointer := range at { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, pointer), + `extension "`+name+`" could not be serialized`, "the extension reports itself at %s", pointer) + } + others := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Severity == ir.SeverityWarning && strings.Contains(diagnostic.Message, "could not be serialized") + }) + assert.Empty(t, cmp.Diff(withoutExtensionDiags, others, cmpopts.EquateEmpty()), "what holds it is reported as without the extension") + assert.Empty(t, cmp.Diff(withoutExtension.Types, doc.Types, cmpopts.EquateEmpty()), "what holds it is kept as without the extension") + for _, claim := range openapitest.MessagesSayingKept(diags) { + assert.NotContains(t, claim, name, "nothing claims the extension was kept") + } + return doc +} + +// TestAllOf_AnEntryIsKeptWithoutAnExtensionNoJSONHolds holds an entry the +// merge does not consume whole, which is kept beside the node and reported, +// writing an extension whose value converts to no JSON: under a node no +// conjunct lowers from, and beside a composed Model, where the conjuncts +// disagree on a keyword it writes. Each keeps the entry without the extension, +// which draws its own warning, and a valid document draws no error. +func TestAllOf_AnEntryIsKeptWithoutAnExtensionNoJSONHolds(t *testing.T) { + t.Parallel() + for name, schemas := range map[string]string{ + "no conjunct lowers the node": ` M: {allOf: [{additionalProperties: false` + unconvertibleExtension + `}]} +`, + "an ordinary composition": ` A: {type: object, properties: {a: {type: string}}} + M: {allOf: [{$ref: '#/components/schemas/A'}, {type: object, not: {required: [x]}` + unconvertibleExtension + `}, {not: {required: [y]}}]} +`, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + at := "/components/schemas/M/allOf/0" + if strings.Contains(schemas, "$ref") { + at = "/components/schemas/M/allOf/1" + } + doc := requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpec(schemas), unconvertibleExtension, at) + key := "openapi:allOf/" + at[strings.LastIndex(at, "/")+1:] + require.Contains(t, typeByName(doc, "M").Common().Unmodeled, key, "the entry is kept") + }) + } +} + +// TestAllOf_AKeywordKeptApartIsKeptWithoutAnExtensionNoJSONHolds holds a +// keyword the inline principal keeps apart, under its entry's key, as the +// keywords beside the allOf write it otherwise, whose value writes an +// extension no JSON holds: the keyword is kept without the extension, which +// draws its own warning where written, as the same keyword written flat does. +func TestAllOf_AKeywordKeptApartIsKeptWithoutAnExtensionNoJSONHolds(t *testing.T) { + t.Parallel() + doc := requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpecVer("3.1.0", + " S: {foo: {a: 2}, allOf: [{type: string, foo: {a: 1"+unconvertibleExtension+"}}]}\n"), + unconvertibleExtension, "/components/schemas/S/allOf/0/foo") + unmodeled := typeByName(doc, "S").Common().Unmodeled + require.Contains(t, unmodeled, "openapi:allOf/0", "the principal's keyword is kept apart") + assert.JSONEq(t, `{"foo":{"a":1}}`, string(unmodeled["openapi:allOf/0"].Value)) +} + +// TestAllOf_AnUnpreservableUncomposedRefIsNotAnnounced pins an entry writing +// beside a $ref to a string an extension no JSON holds, beside an object: the +// two share no kind, so the position is the bottom. The extension alone is +// left out, with its usual warning, so the entry is the $ref its twin writes +// alone, kept and reported as that twin's, and the document refused nowhere; +// so is one whose value set shares no member with the set beside it, and an +// inline entry the bottom keeps whole. +func TestAllOf_AnUnpreservableUncomposedRefIsNotAnnounced(t *testing.T) { + t.Parallel() + doc := requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpecVer("3.1.0", ` Str: {type: string} + M: + allOf: + - {$ref: '#/components/schemas/Str'`+unconvertibleExtension+`} + - {type: object, properties: {a: {type: string}}} +`), unconvertibleExtension, "/components/schemas/M/allOf/0") + + model, ok := typeByName(doc, "M").(*ir.Model) + require.True(t, ok, "the bottom") + assert.Nil(t, model.Base, "the bottom composes nothing") + require.Contains(t, model.Unmodeled, "openapi:$ref", "the reference is kept as its twin keeps it") + assert.JSONEq(t, `"#/components/schemas/Str"`, string(model.Unmodeled["openapi:$ref"].Value)) + + requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpecVer("3.1.0", ` Set: {enum: [a, b]} + V: {allOf: [{$ref: '#/components/schemas/Set'`+unconvertibleExtension+`}, {enum: [c]}]} +`), unconvertibleExtension, "/components/schemas/V/allOf/0") + requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpecVer("3.1.0", + " B: {allOf: [{type: string}, {type: integer"+unconvertibleExtension+"}]}\n"), unconvertibleExtension, "/components/schemas/B/allOf/1") +} + +// TestAllOf_ANullTypeExcludesNoObject pins that an entry's `type: null` is the +// keyword left out, so what it keeps as unread keywords is reported as an info, +// not as the warning a type excluding object draws. An entry writing properties +// keeps the allOf a composition, where an entry's type is weighed against an +// object. +func TestAllOf_ANullTypeExcludesNoObject(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpec(` S: {allOf: [{type: null, minItems: 1}, {properties: {p: {}}}]} +`)) + var severities []ir.Severity + for _, diagnostic := range diags { + if diagnostic.Code == diag.DegradedConstruct && strings.Contains(diagnostic.Message, "inline") { + severities = append(severities, diagnostic.Severity) + } + } + assert.Equal(t, []ir.Severity{ir.SeverityInfo}, severities) +} + +// rebasedEntryTargets declares the two schemas `n.json` names under the two +// bases the rebased-entry cases write. +const rebasedEntryTargets = ` A: {$id: 'https://ex.test/a/n.json', type: string} + B: {$id: 'https://ex.test/b/n.json', type: integer} +` + +// TestAllOf_AnEntryReadAgainstAnotherBaseFoldsNothing holds an inline entry +// under an $id naming another URI to keeping what it writes, wherever the $id +// is written: `n.json` names A there and B at the position, so folding its +// `not` would read it as B's. Spelled shows the outer entry folding as it does +// when its $ref names B outright, and Annotated that the rule holds for a +// keyword with no $ref in it. +func TestAllOf_AnEntryReadAgainstAnotherBaseFoldsNothing(t *testing.T) { + t.Parallel() + // code is the report's: an entry holding validation logic alone is kept as + // that, and reported so. + for name, testCase := range map[string]struct{ schema, kept, folded, code string }{ + "Wrapped": {` $id: 'https://ex.test/b/s.json' + allOf: + - $id: 'https://ex.test/a/w.json' + allOf: [{type: object, not: {$ref: 'n.json'}}] + - {type: object, not: {$ref: 'n.json'}} +`, "openapi:allOf/0/allOf/0", `{"$ref":"n.json"}`, diag.ValidationOnlyKeyword}, + "Spelled": {` $id: 'https://ex.test/b/s.json' + allOf: + - $id: 'https://ex.test/a/w.json' + allOf: [{type: object, not: {$ref: 'n.json'}}] + - {type: object, not: {$ref: 'https://ex.test/b/n.json'}} +`, "openapi:allOf/0/allOf/0", `{"$ref":"https://ex.test/b/n.json"}`, diag.ValidationOnlyKeyword}, + "Annotated": {` allOf: + - {type: object, properties: {a: {type: string}}} + - {$id: 'https://ex.test/a/x.json', not: {$ref: 'n.json'}, description: d} +`, "openapi:allOf/1", "", diag.DegradedConstruct}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", rebasedEntryTargets+" S:\n"+testCase.schema)) + openapitest.RequireNoErrorDiags(t, diags) + um := typeByName(doc, "S").Common().Unmodeled + + kept, ok := um[testCase.kept] + require.True(t, ok, "the entry is kept whole; got %+v", um) + assert.Contains(t, string(kept.Value), `"not":{"$ref":"n.json"}`) + assert.Contains(t, + openapitest.DiagMessageAt(t, diags, testCase.code, ir.SeverityInfo, "/components/schemas/S/"+testCase.kept[len("openapi:"):]), + "reads its $refs against another base") + assert.Equal(t, testCase.folded, string(um["openapi:not"].Value), "the outer entry folds its not, if it writes one") + assert.Empty(t, typeByName(doc, "S").Common().Docs.Description, "nothing the kept entry writes folds") + }) + } +} + +// TestAllOf_AnEntryWritingNoRelativeReferenceFoldsUnderAnyBase pins that an $id +// naming another URI keeps an entry whole only where what it folds writes a +// relative $ref: text naming none reads the same at the position, so the bounds +// and the `not` of entries under two other bases fold as they would with no +// $id, and so do M's description beside a $ref its property resolves where it +// is written, and N's beside an absolute $ref. +func TestAllOf_AnEntryWritingNoRelativeReferenceFoldsUnderAnyBase(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", rebasedEntryTargets+` S: + type: string + allOf: + - {$id: 'https://ex.test/a/x.json', minLength: 1, not: {const: q}} + - $id: 'https://ex.test/a/w.json' + allOf: [{maxLength: 5}] + M: + type: object + allOf: + - {$id: 'https://ex.test/a/x.json', type: object, properties: {a: {$ref: 'n.json'}}, description: d} + - {type: object, properties: {b: {type: string}}} + N: + type: object + allOf: + - {$id: 'https://ex.test/a/x.json', description: d, not: {$ref: 'https://ex.test/b/n.json'}} + - {type: object, properties: {b: {type: string}}} +`)) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "M").(*ir.Model) + require.True(t, ok) + assert.Equal(t, "d", model.Docs.Description) + typeCommon := typeByName(doc, "N").Common() + assert.Equal(t, "d", typeCommon.Docs.Description) + assert.JSONEq(t, `{"$ref":"https://ex.test/b/n.json"}`, string(typeCommon.Unmodeled["openapi:not"].Value)) + assert.Equal(t, typeByName(doc, "A").Common().ID, openapitest.PropertiesByWire(model.Properties)["a"].Type.Target) + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, scalar.Constraints) + require.NotNil(t, scalar.Constraints.MinLength) + require.NotNil(t, scalar.Constraints.MaxLength) + assert.Equal(t, int64(1), *scalar.Constraints.MinLength) + assert.Equal(t, int64(5), *scalar.Constraints.MaxLength) + assert.NotContains(t, scalar.Unmodeled, "openapi:not", "its entries write $id apart, so each is kept whole, holding its not") + assert.Contains(t, string(scalar.Unmodeled["openapi:allOf/0"].Value), `"not":{"const":"q"}`) + for _, diagnostic := range diags { + assert.NotContains(t, diagnostic.Message, "against another base") + } +} + +// TestAllOf_AFlattenedEntrysReportsTravelWithWhatEachKeeps holds each report a +// flattened entry's reading draws to the entry it reports: the entry's own +// validation-only `not`, written alike beside the allOf, is one value, kept +// once and reported once, by the keywords beside the allOf, however its +// report reads beside the if/then the entry keeps alone at the same pointer. +func TestAllOf_AFlattenedEntrysReportsTravelWithWhatEachKeeps(t *testing.T) { + t.Parallel() + _, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` S: + type: string + not: {const: a} + allOf: + - {if: {minLength: 1}, then: {maxLength: 3}, not: {const: a}} +`)) + var notes []string + for _, diagnostic := range diags { + if diagnostic.Code == diag.ValidationOnlyKeyword { + notes = append(notes, string(diagnostic.Provenance.Pointer)+": "+diagnostic.Message) + } + } + assert.Equal(t, []string{ + `/components/schemas/S: validation-only keyword "not" kept verbatim under Unmodeled`, + `/components/schemas/S/allOf/0: validation-only keyword "if/then/else" kept verbatim under Unmodeled`, + }, notes) +} diff --git a/compilers/openapi/internal/schema/ancestors.go b/compilers/openapi/internal/schema/ancestors.go new file mode 100644 index 000000000..50107414f --- /dev/null +++ b/compilers/openapi/internal/schema/ancestors.go @@ -0,0 +1,234 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "cmp" + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// ancestorsOfRun keys the run's ancestorIndex. +type ancestorsOfRun struct{} + +// ancestorIndex holds each schema's discriminated ancestors, read once a run +// over the source's composition edges +// (docs/compilers/openapi.md#discriminator-value). The climb runs while the +// lowering decides each Base, so it reads the source rather than the IR. +type ancestorIndex struct { + answers map[*statement.Schema]ancestorAnswer + parents map[*statement.Schema][]*statement.Schema + // components numbers each answered schema's strongly connected component + // of the composition edges. + components map[*statement.Schema]int +} + +// ancestorAnswer is one schema's discriminated ancestors: each with its least +// distance, nearest first, and the same grouped by distance. +type ancestorAnswer struct { + at []ancestorAt + levels [][]*statement.Schema +} + +// ancestorAt is a discriminated ancestor and the least number of composition +// edges the climb takes to it. +type ancestorAt struct { + schema *statement.Schema + distance int +} + +// ancestorIndexOf returns the run's ancestorIndex. +func ancestorIndexOf(loweringContext lowering.Ctx) *ancestorIndex { + return lowering.ReadOncePerRun(loweringContext, ancestorsOfRun{}, func() *ancestorIndex { + return &ancestorIndex{answers: map[*statement.Schema]ancestorAnswer{}, parents: map[*statement.Schema][]*statement.Schema{}, + components: map[*statement.Schema]int{}} + }) +} + +// ancestorLevels returns schema's discriminated ancestors grouped by least +// distance, nearest first, each level in the order the climb meets them: the +// nearest decides between two whose mappings name one subtype. The answer is +// the run's: a caller reorders a copy, never it. +func ancestorLevels(loweringContext lowering.Ctx, schema *statement.Schema) [][]*statement.Schema { + index := ancestorIndexOf(loweringContext) + if answer, solved := index.answers[schema]; solved { + return answer.levels + } + index.solve(loweringContext, schema) + return index.answers[schema].levels +} + +// onOneCompositionCycle reports whether a and b, two schemas, lie on one cycle +// of composition edges: each composes the other, at any depth. +func onOneCompositionCycle(loweringContext lowering.Ctx, a, b *statement.Schema) bool { + if a == nil || b == nil || a == b { + return false + } + index := ancestorIndexOf(loweringContext) + for _, schema := range [...]*statement.Schema{a, b} { + if _, solved := index.answers[schema]; !solved { + index.solve(loweringContext, schema) + } + } + return index.components[a] == index.components[b] +} + +// parentsOf returns the schemas schema's composition edges land on, in source +// order, each once: its $ref allOf entries, and the $ref of an +// aloneRefComponent. It counts each edge it reads (ancestorStepCount). +func (x *ancestorIndex) parentsOf(loweringContext lowering.Ctx, schema *statement.Schema) []*statement.Schema { + if parents, read := x.parents[schema]; read { + return parents + } + var parents []*statement.Schema + add := func(target *statement.Schema) { + *ancestorStepCount(loweringContext)++ + if stated(target) && !slices.Contains(parents, target) { + parents = append(parents, target) + } + } + if aloneRefComponent(schema) { + add(refBranchTarget(loweringContext, loweringContext.Statements().Read(schema))) + } + for branch := range allOfRefEntries(loweringContext, schema) { + add(refBranchTarget(loweringContext, branch)) + } + x.parents[schema] = parents + return parents +} + +// aloneRefComponent reports whether schema is a component of the entry +// document writing a $ref and nothing beside it, which lowers to a model with +// the Base the $ref names (docs/compilers/openapi.md#discriminator-value). +func aloneRefComponent(schema *statement.Schema) bool { + if schema == nil || schema.Ref == nil || schema.At.Doc != reftable.Source { + return false + } + _, state := ids.ComponentSchema(schema.At.Pointer) + return state == ids.NamedComponent +} + +// solve answers each unanswered schema the climb from start reaches, one +// strongly connected component at a time, parents first. A component's +// members are answered in source order, so no climb's start orders an answer. +func (x *ancestorIndex) solve(loweringContext lowering.Ctx, start *statement.Schema) { + walkComponents(start, + func(schema *statement.Schema) []*statement.Schema { return x.parentsOf(loweringContext, schema) }, + func(parent *statement.Schema) bool { _, solved := x.answers[parent]; return solved }, + func(component closedComponent[*statement.Schema]) { + members := slices.Clone(component.members) + slices.SortFunc(members, compareSchemaPlaces) + x.answerComponent(loweringContext, members) + }) +} + +// compareSchemaPlaces orders two schemas by their documents, then their +// pointers as the documents are written. +func compareSchemaPlaces(a, b *statement.Schema) int { + return cmp.Or(cmp.Compare(a.At.Doc, b.At.Doc), provenance.ComparePointers(a.At.Pointer, b.At.Pointer)) +} + +// answerComponent answers each member of a strongly connected component whose +// edges out land on answered components. The members share the ancestors +// outside it and add the component's other discriminated members, never +// themselves: a schema on a composition cycle is no ancestor of its own. +func (x *ancestorIndex) answerComponent(loweringContext lowering.Ctx, members []*statement.Schema) { + in := make(map[*statement.Schema]bool, len(members)) + for _, member := range members { + in[member] = true + } + var outside []ancestorAt + children := map[*statement.Schema][]*statement.Schema{} + for _, member := range members { + for _, parent := range x.parentsOf(loweringContext, member) { + if in[parent] { + children[parent] = append(children[parent], member) + continue + } + outside = x.through(loweringContext, outside, parent) + } + } + component := len(x.components) + found := make(map[*statement.Schema][]ancestorAt, len(members)) + for _, discriminated := range members { + if discriminates(loweringContext, discriminated) { + for member, distance := range distancesTo(children, discriminated) { + found[member] = append(found[member], ancestorAt{schema: discriminated, distance: distance}) + } + } + } + for _, member := range members { + inside := found[member] + slices.SortFunc(inside, func(a, b ancestorAt) int { return compareSchemaPlaces(a.schema, b.schema) }) + x.answers[member] = groupedAnswer(slices.Concat(outside, inside)) + x.components[member] = component + } +} + +// through appends to found what the edge to parent brings: parent itself one +// edge away, where it writes a discriminator, then each of its answer's +// ancestors one edge further. +func (x *ancestorIndex) through(loweringContext lowering.Ctx, found []ancestorAt, parent *statement.Schema) []ancestorAt { + if discriminates(loweringContext, parent) { + found = append(found, ancestorAt{schema: parent, distance: 1}) + } + for _, ancestor := range x.answers[parent].at { + found = append(found, ancestorAt{schema: ancestor.schema, distance: ancestor.distance + 1}) + } + return found +} + +// distancesTo returns the least number of a component's edges from each +// member that reaches target to it, target itself left out, walking +// children, the component's edges reversed, breadth first from target. +func distancesTo(children map[*statement.Schema][]*statement.Schema, target *statement.Schema) map[*statement.Schema]int { + distances := map[*statement.Schema]int{} + level := []*statement.Schema{target} + for distance := 1; len(level) > 0; distance++ { + var next []*statement.Schema + for _, schema := range level { + for _, child := range children[schema] { + if _, seen := distances[child]; seen || child == target { + continue + } + distances[child] = distance + next = append(next, child) + } + } + level = next + } + return distances +} + +// groupedAnswer keeps each ancestor of found at its least distance, nearest +// first and, at one distance, in the order found lists them, and groups them +// by distance. +func groupedAnswer(found []ancestorAt) ancestorAnswer { + least := make(map[*statement.Schema]int, len(found)) + for _, ancestor := range found { + if distance, seen := least[ancestor.schema]; !seen || ancestor.distance < distance { + least[ancestor.schema] = ancestor.distance + } + } + var answer ancestorAnswer + for _, ancestor := range found { + if least[ancestor.schema] == ancestor.distance { + answer.at = append(answer.at, ancestor) + delete(least, ancestor.schema) + } + } + slices.SortStableFunc(answer.at, func(a, b ancestorAt) int { return cmp.Compare(a.distance, b.distance) }) + for i, ancestor := range answer.at { + if i == 0 || answer.at[i-1].distance != ancestor.distance { + answer.levels = append(answer.levels, nil) + } + answer.levels[len(answer.levels)-1] = append(answer.levels[len(answer.levels)-1], ancestor.schema) + } + return answer +} diff --git a/compilers/openapi/internal/schema/ancestors_reads_internal_test.go b/compilers/openapi/internal/schema/ancestors_reads_internal_test.go new file mode 100644 index 000000000..ed2479b00 --- /dev/null +++ b/compilers/openapi/internal/schema/ancestors_reads_internal_test.go @@ -0,0 +1,33 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" +) + +// TestAncestors_StepsGrowLinearlyWhereNoLevelComposesADiscriminator pins +// GitHub #1993's hierarchy, each level composing the one below and a fresh +// part, with no discriminator anywhere: the composition edges the run's one +// climb to discriminated ancestors follows grow linearly with the levels, +// each followed once, where walking each level's ancestry followed every edge +// below it. +func TestAncestors_StepsGrowLinearlyWhereNoLevelComposesADiscriminator(t *testing.T) { + t.Parallel() + var steps [3]int + for k, n := range []int{50, 100, 200} { + lowerer, diags := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", freshPartEachLevel(n))) + lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) + lowerer.Document(t) + openapitest.RequireNoErrorDiags(t, append(diags, lowerer.Diags.List()...)) + steps[k] = *ancestorStepCount(lowerer.Ctx) + require.GreaterOrEqual(t, steps[k], n-1, "at %d levels every level's edges are followed", n) + } + assert.LessOrEqual(t, float64(steps[2]-steps[1]), 2.5*float64(steps[1]-steps[0]), "steps at 50, 100, 200 levels: %v", steps) +} diff --git a/compilers/openapi/internal/schema/annotated_copies_test.go b/compilers/openapi/internal/schema/annotated_copies_test.go new file mode 100644 index 000000000..7fa4bcbe0 --- /dev/null +++ b/compilers/openapi/internal/schema/annotated_copies_test.go @@ -0,0 +1,181 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/v2" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// annotatedApart is what the fold says of a declaration it keeps for its +// type's annotations alone. +const annotatedApart = "that admit the same values but are annotated apart" + +// TestFold_ACopyAnnotatedApartLosesNothing pins the fold of a member whose +// declarations admit the same values but say different docs, in every order +// of the entries: the field's type, docs and kept text say every annotation a +// declaration wrote, each copy the field's type does not carry is reported +// once, and the field takes one type whatever the order. Two components are +// one type too, the one written first, a component carrying all a copy says +// is no loss, and docs written beside a reference fold by the field's own +// rule. +func TestFold_ACopyAnnotatedApartLosesNothing(t *testing.T) { + t.Parallel() + components := " Host: {type: string, format: hostname, description: one}\n" + + " Other: {type: string, format: hostname, description: two}\n" + + " Obj: {type: object, properties: {x: {type: string, description: one}}}\n" + + " Side: {type: object, properties: {y: {type: string}}}\n" + + " Alias: {$ref: '#/components/schemas/Host', description: aliased}\n" + for name, testCase := range map[string]struct { + declarations []string + said []string + reports int + oneType bool + }{ + "two inline copies": {[]string{"{type: string, format: hostname, description: one}", + "{type: string, format: hostname, description: two}"}, []string{"one", "two"}, 1, false}, + "a component and an inline copy": {[]string{"{$ref: '#/components/schemas/Host'}", + "{type: string, format: hostname, description: two}"}, []string{"one", "two"}, 1, true}, + "two components": {[]string{"{$ref: '#/components/schemas/Host'}", "{$ref: '#/components/schemas/Other'}"}, + []string{"one", "two"}, 1, true}, + "titles apart": {[]string{"{type: string, format: hostname, title: one}", + "{type: string, format: hostname, title: two}"}, []string{"one", "two"}, 1, false}, + "a deprecation and a description": {[]string{"{type: string, format: hostname, deprecated: true}", + "{type: string, format: hostname, description: two}"}, []string{"deprecat", "two"}, 1, false}, + "examples apart": {[]string{"{type: string, format: hostname, examples: [exone]}", + "{type: string, format: hostname, examples: [extwo]}"}, []string{"exone", "extwo"}, 0, false}, + "extensions apart": {[]string{"{type: string, format: hostname, x-note: one}", + "{type: string, format: hostname, x-note: two}"}, []string{"one", "two"}, 0, false}, + "a member's description": {[]string{"{type: object, properties: {x: {type: string, description: one}}}", + "{type: object, properties: {x: {type: string, description: two}}}"}, []string{"one", "two"}, 1, false}, + "an item's description": {[]string{"{type: array, items: {type: string, format: hostname, description: one}}", + "{type: array, items: {type: string, format: hostname, description: two}}"}, []string{"one", "two"}, 1, false}, + "a copy beside a composition": {[]string{"{$ref: '#/components/schemas/Obj'}", + "{type: object, properties: {x: {type: string, description: two}}}", "{$ref: '#/components/schemas/Side'}"}, + []string{"one", "two"}, 1, true}, + "a copy of a part the field does not win by": {[]string{"{$ref: '#/components/schemas/Obj'}", + "{type: object, properties: {x: {type: string, description: two}}}", "{$ref: '#/components/schemas/Side'}", + "{type: object, properties: {y: {type: string}}}"}, []string{"one", "two"}, 1, true}, + "a component carrying the copy": {[]string{"{$ref: '#/components/schemas/Host'}", + "{type: string, format: hostname}"}, []string{"one"}, 0, true}, + "an alias whose chain carries the copy": {[]string{"{$ref: '#/components/schemas/Alias'}", + "{type: string, format: hostname, description: one}"}, []string{"one", "aliased"}, 0, true}, + "an alias whose chain does not": {[]string{"{$ref: '#/components/schemas/Alias'}", + "{type: string, format: hostname, description: two}"}, []string{"one", "two", "aliased"}, 1, true}, + "docs on a bare type": {[]string{"{type: string, title: one}", "{type: string, title: two}"}, + []string{"one", "two"}, 0, true}, + "docs beside a reference": {[]string{"{allOf: [{$ref: '#/components/schemas/Host'}], description: two}", + "{allOf: [{$ref: '#/components/schemas/Host'}], description: three}"}, []string{"one", "two", "three"}, 0, true}, + } { + var targets []ir.TypeID + for _, order := range permutations(len(testCase.declarations)) { + var entries strings.Builder + for _, at := range order { + entries.WriteString(" - {type: object, properties: {p: " + testCase.declarations[at] + "}}\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", components+" M:\n allOf:\n"+entries.String())) + + model, isModel := typeByName(doc, "M").(*ir.Model) + require.True(t, isModel, "%s %v", name, order) + at := slices.IndexFunc(model.Properties, func(property ir.Property) bool { return property.WireName == "p" }) + require.GreaterOrEqual(t, at, 0, "%s %v: M declares p", name, order) + said := fieldText(t, doc, model.Properties[at]) + for _, text := range testCase.said { + assert.Contains(t, said, text, "%s %v", name, order) + } + reported := 0 + for _, diagnostic := range diags { + if strings.Contains(diagnostic.Message, annotatedApart) { + reported++ + } + } + assert.Equal(t, testCase.reports, reported, "%s %v", name, order) + targets = append(targets, model.Properties[at].Type.Target) + } + if testCase.oneType { + assert.Len(t, slices.Compact(targets), 1, "%s: one type in every order: %v", name, targets) + } + } +} + +// TestFold_ACopyAnnotatedApartInAHeldTypeIsReportedOnce pins the one report of +// a copy whose type admits what the field's does but is annotated apart in a +// type it holds, an item or the list itself, or a member, in every order of the +// entries: each copy the field does not take is reported once, where it is +// written, the report naming the annotations held apart, where the fold's +// intersection and its keeping of the copy each reported it. +func TestFold_ACopyAnnotatedApartInAHeldTypeIsReportedOnce(t *testing.T) { + t.Parallel() + for name, testCase := range map[string]struct { + declarations []string + held string + }{ + "items described apart": {[]string{"{type: array, items: {type: string, description: a}}", + "{type: array, items: {type: string, description: b}}", "{type: array, items: {type: string, description: c}}"}, + "in the docs of a type it holds"}, + "lists described apart": {[]string{"{type: array, items: {type: string}, description: a}", + "{type: array, items: {type: string}, description: b}"}, "in the docs of a type it holds"}, + "members described apart": {[]string{"{type: object, properties: {m: {type: string, description: a}}}", + "{type: object, properties: {m: {type: string, description: b}}}"}, "annotated apart"}, + "items titled apart": {[]string{"{type: array, items: {type: string, title: a}}", + "{type: array, items: {type: string, title: b}}"}, "in the docs of a type it holds"}, + } { + for _, order := range permutations(len(testCase.declarations)) { + var entries strings.Builder + for _, at := range order { + entries.WriteString(" - {properties: {x: " + testCase.declarations[at] + "}}\n") + } + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " M:\n allOf:\n"+entries.String())) + + reported := map[string]int{} + for _, diagnostic := range diags { + reported[string(diagnostic.Provenance.Pointer)]++ + assert.Contains(t, diagnostic.Message, annotatedApart, "%s %v", name, order) + assert.Contains(t, diagnostic.Message, testCase.held, "%s %v", name, order) + } + assert.Len(t, reported, len(testCase.declarations)-1, "%s %v: each copy not taken: %v", name, order, reported) + for at, count := range reported { + assert.Equal(t, 1, count, "%s %v: one report at %s", name, order, at) + } + } + } +} + +// fieldText is what property says, its type and the nodes that type names at +// any depth, and the nodes what it keeps verbatim names, encoded and joined, +// so a test reads whether a text the source wrote reached the field. +func fieldText(t *testing.T, doc *ir.Document, property ir.Property) string { + t.Helper() + raw, err := json.Marshal(property, json.Deterministic(true)) + require.NoError(t, err) + out := []string{string(raw)} + seen := map[ir.TypeID]bool{} + for queue := []ir.TypeID{property.Type.Target}; len(queue) > 0 && len(seen) < 256; queue = queue[1:] { + typeDef, held := doc.Types[queue[0]] + if seen[queue[0]] || !held { + continue + } + seen[queue[0]] = true + raw, err := json.Marshal(typeDef, json.Deterministic(true)) + require.NoError(t, err) + out = append(out, string(raw)) + queue = append(queue, slices.Collect(ir.TypeEdges(typeDef))...) + } + for _, entry := range property.Unmodeled { + for _, target := range entry.Targets { + raw, err := json.Marshal(doc.Types[target], json.Deterministic(true)) + require.NoError(t, err) + out = append(out, string(raw)) + } + } + return strings.Join(out, "\n") +} diff --git a/compilers/openapi/internal/schema/array.go b/compilers/openapi/internal/schema/array.go index 220a0f9d5..263bcd3ea 100644 --- a/compilers/openapi/internal/schema/array.go +++ b/compilers/openapi/internal/schema/array.go @@ -20,38 +20,62 @@ import ( "github.com/dexpace/morphic/ir" ) -// lowerArray hoists an array schema, written at pointer, at at, as a Tuple when -// its `items` is a list its dialect reads as one (listedTuple), or when -// prefixItems is present, else a List over its item schema, each with the -// collection bounds it declares met with those foldedEntries write, fin -// finishing it once built. -func lowerArray(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer, at jsontext.Pointer, - foldedEntries []annotation.FoldedAllOfEntry, fin finisher, -) (ir.TypeID, []ir.Diagnostic) { +// lowerArray hoists an array schema, written at pointer, as a Tuple where its +// `items` is a list its dialect reads as one or it writes prefixItems, else as +// a List, with the collection bounds it and flattenedEntries write intersected. +func lowerArray(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement, + flattenedEntries []annotation.FlattenedAllOfEntry, homes boundHomes, +) (builtPosition, []ir.Diagnostic) { var diags []ir.Diagnostic + var pendingKeeps annotation.PendingKeeps + keeps := builtKeeps{pendingKeeps: &pendingKeeps, pointer: pointer, placement: placement} read := keyBit("items") | typeReadAs(schema, statement.KindArray) | collectionReads(schema) - id := internNode(loweringContext, ts, at, func(common ir.TypeCommon) (ir.TypeDef, keySet) { - cons := collectionBoundsMetWithFoldedEntries(ownCollectionConstraints(schema), foldedEntries) - if n, tuple := listedTuple(loweringContext, schema); tuple { - typeDef, tupleDiags := buildListedTuple(loweringContext, ts, depth, schema, common, pointer, n, cons) + conjunctSchema, written := elementConjunct(schema, pointer, flattenedEntries) + built := internNode(loweringContext, types, placement.pointer(pointer), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + cons := collectionBoundsIntersectedWithFlattenedEntries(ownCollectionConstraints(schema), flattenedEntries, homes) + if n, tuple := listedTuple(loweringContext, conjunctSchema); tuple { + typeDef, tupleDiags := buildListedTuple(loweringContext, types, depth, conjunctSchema, common, written, n, cons, keeps) diags = append(diags, tupleDiags...) return typeDef, read | keySetOf("prefixItems", "additionalItems") } - if prefix := schema.PrefixItems(); len(prefix) > 0 { - typeDef, tupleDiags := buildTuple(loweringContext, ts, depth, schema, common, pointer, prefix, cons) + if prefix := conjunctSchema.PrefixItems(); len(prefix) > 0 { + typeDef, tupleDiags := buildTuple(loweringContext, types, depth, conjunctSchema, common, written, prefix, cons) diags = append(diags, tupleDiags...) return typeDef, read | keySetOf("prefixItems", "additionalItems") } - element, elementDiags := Ref(loweringContext, ts, depth, loweringContext.Statements().Subschema(itemsSchema(schema)), pointer+ids.Ptr("items")) + elements, keyword := elementsPast(loweringContext, conjunctSchema) + element, elementDiags := Ref(loweringContext, types, depth, loweringContext.Statements().Subschema(elements), written+ids.Ptr(keyword)) diags = append(diags, elementDiags...) return &ir.List{TypeCommon: common, ElementType: element, Constraints: cons}, read - }, fin) - return id, diags + }) + built.pendingKeeps.AddAll(pendingKeeps) + return built, diags +} + +// elementConjunct returns the conjunct the node reads its elements off, and +// where it is written: schema where it writes a keyword of the `items` group, +// else the first flattened entry writing one, as the group reaches any conjunct +// whole (docs/compilers/openapi.md#allof-refinement). Taking the first is +// sound: an entry writing the group otherwise than another conjunct is not +// folded (foldingNode). +func elementConjunct(schema *statement.Schema, pointer jsontext.Pointer, flattenedEntries []annotation.FlattenedAllOfEntry) (*statement.Schema, jsontext.Pointer) { + writes := func(conjunctSchema *statement.Schema) bool { + return slices.ContainsFunc(itemsGroup, func(keyword string) bool { return hasKey(conjunctSchema, keyword) }) + } + if writes(schema) { + return schema, pointer + } + for _, flattenedAllOfEntry := range flattenedEntries { + if writes(flattenedAllOfEntry.Node) { + return flattenedAllOfEntry.Node, flattenedAllOfEntry.At + } + } + return schema, pointer } // listedTuple returns how many schemas schema writes `items` as a list of where // the rows of its dialect, read where schema is written (rulesOf) whatever -// pointer its node stands at, read that list as a tuple, as the drafts before +// pointer its node sits at, read that list as a tuple, as the drafts before // 2020-12 spell one, and false where they do not or it writes no list. A list // read so nowhere is the table's to report (docs/compilers/openapi.md#tuples). func listedTuple(loweringContext lowering.Ctx, schema *statement.Schema) (int, bool) { @@ -89,23 +113,25 @@ func itemsSchema(schema *statement.Schema) statement.Subschema { // and `false` admits none. An entry or rest written as a number, a string or a // list lowers as `false` does, and a `null` as one left out, as 2020-12's are, // which the load phase reports. -func buildListedTuple(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, common ir.TypeCommon, pointer jsontext.Pointer, n int, - cons *ir.Constraints, +func buildListedTuple(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, common ir.TypeCommon, pointer jsontext.Pointer, n int, + cons *ir.Constraints, keeps builtKeeps, ) (ir.TypeDef, []ir.Diagnostic) { var diags []ir.Diagnostic there, site := writtenAt(loweringContext, schema, pointer) elements := make([]ir.TypeRef, 0, n) for i := range n { entry := ids.Ptr("items", strconv.Itoa(i)) - ref, refDiags := Ref(loweringContext, ts, depth, heldAt(there, site+entry), pointer+entry) + ref, refDiags := Ref(loweringContext, types, depth, heldAt(there, site+entry), pointer+entry) diags = append(diags, refDiags...) elements = append(elements, ref) } tuple := &ir.Tuple{TypeCommon: common, ElementTypes: elements, Constraints: cons} - diags = append(diags, keepPrefixItems(loweringContext, &tuple.Unmodeled, schema, pointer)...) + diags = append(diags, keeps.keep(loweringContext, &tuple.Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepPrefixItems(loweringContext, unmodeled, schema, pointer) + })...) rest := ids.Ptr("additionalItems") - if js := heldAt(there, site+rest); !js.Truth.ReadsFalse() { - ref, restDiags := Ref(loweringContext, ts, depth, js, pointer+rest) + if schemaStatement := heldAt(there, site+rest); !schemaStatement.Truth.ReadsFalse() { + ref, restDiags := Ref(loweringContext, types, depth, schemaStatement, pointer+rest) diags = append(diags, restDiags...) tuple.Rest = &ref } @@ -116,16 +142,16 @@ func buildListedTuple(loweringContext lowering.Ctx, ts *compile.Types, depth int // beside the items list its dialect reads as the tuple, which is the dialect's // own spelling of one, where no text makes the two one tuple // (docs/compilers/openapi.md#tuples), and reports it once. -func keepPrefixItems(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { +func keepPrefixItems(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) annotation.KeptReports { if !hasKey(schema, "prefixItems") { return nil } - kept, diags := preserveSchemaKeyword(loweringContext, unmodeled, schema, "prefixItems", ir.ReasonDegradedLowering, pointer) + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, schema, "prefixItems", ir.ReasonDegradedLowering, pointer) if kept { diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer+ids.Ptr("prefixItems"), "prefixItems is kept verbatim: this schema's dialect reads its items list as the tuple")) } - return diags + return annotation.ReportsOf(annotation.EntryKey("", "prefixItems"), diags...) } // writtenAt returns where schema, lowered at pointer, is written: where the @@ -138,26 +164,26 @@ func writtenAt(loweringContext lowering.Ctx, schema *statement.Schema, pointer j return loweringContext, pointer } -// ListedTuple returns the entries the array js writes as a tuple in a list of -// `items`, its $ref followed, where the dialect of where it is reads that list -// so (listedTuple), and the `additionalItems` beside them, Unwritten where -// none is written: the schemas the load phase built there, as the parser's -// model holds neither. It is false where js is no such tuple, or the bindings -// place it in no document the compile read. -func ListedTuple(loweringContext lowering.Ctx, js *statement.Statement) ( +// ListedTuple returns the entries the array schemaStatement writes as a tuple +// in a list of `items`, its $ref followed, where the dialect of where it is +// reads that list so (listedTuple), and the `additionalItems` beside them, +// Unwritten where none is written: the schemas the load phase built there, as +// the parser's model holds neither. It is false where schemaStatement is no +// such tuple, or the bindings place it in no document the compile read. +func ListedTuple(loweringContext lowering.Ctx, schemaStatement *statement.Statement) ( entries []*statement.Statement, rest *statement.Statement, ok bool, ) { - if js.Ref != nil { - if end, ok := runEnd(loweringContext, js); ok && end.Held() { - js = end + if schemaStatement.Ref != nil { + if end, ok := runEnd(loweringContext, schemaStatement); ok && end.Held() { + schemaStatement = end } } - at, placed := siteOf(js.Schema) + at, placed := siteOf(schemaStatement.Schema) there, read := lowering.InDocument(loweringContext, at.Doc) if !placed || !read { return nil, nil, false } - n, tuple := listedTuple(there, js.Schema) + n, tuple := listedTuple(there, schemaStatement.Schema) if !tuple { return nil, nil, false } @@ -182,88 +208,102 @@ func heldAt(loweringContext lowering.Ctx, pointer jsontext.Pointer) *statement.S // leaves no Rest. Any other lowers as a List's items does, under the same name, // since /items is named alike whichever node holds it (lowering.NameAt). An absent one // lowers to the top type as `items: true` does, though only the latter makes an -// unevaluatedItems beside it inert. No field is derived from another: +// unevaluatedItems beside it saying nothing. No field is derived from another: // ElementTypes is never trimmed to maxItems, and a closed tuple gains no // maxItems. -func buildTuple(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, common ir.TypeCommon, pointer jsontext.Pointer, prefix []statement.Subschema, +func buildTuple(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, common ir.TypeCommon, pointer jsontext.Pointer, prefix []statement.Subschema, cons *ir.Constraints, ) (ir.TypeDef, []ir.Diagnostic) { var diags []ir.Diagnostic elements := make([]ir.TypeRef, 0, len(prefix)) for i, ps := range prefix { - ref, refDiags := Ref(loweringContext, ts, depth, loweringContext.Statements().Subschema(ps), pointer+ids.Ptr("prefixItems", strconv.Itoa(i))) + ref, refDiags := Ref(loweringContext, types, depth, loweringContext.Statements().Subschema(ps), pointer+ids.Ptr("prefixItems", strconv.Itoa(i))) diags = append(diags, refDiags...) elements = append(elements, ref) } tuple := &ir.Tuple{TypeCommon: common, ElementTypes: elements, Constraints: cons} - if items := loweringContext.Statements().Subschema(itemsSchema(schema)); !items.Truth.ReadsFalse() { - rest, restDiags := Ref(loweringContext, ts, depth, items, pointer+ids.Ptr("items")) + past, keyword := elementsPast(loweringContext, schema) + if items := loweringContext.Statements().Subschema(past); !items.Truth.ReadsFalse() { + rest, restDiags := Ref(loweringContext, types, depth, items, pointer+ids.Ptr(keyword)) diags = append(diags, restDiags...) tuple.Rest = &rest } return tuple, diags } -// ownCollectionConstraints reads the collection bounds s itself writes, which -// bound the whole instance whether it lowers to a List or a Tuple, and nil -// where it states none. Only the integer and boolean bounds are read here, as -// the statement holds the model's, each count where the model holds the -// number its literal states (annotation.ExactCount); one it does not -// is kept unread (keptCount). +// ownCollectionConstraints reads the collection bounds schema itself writes, +// which bound the whole instance whether it lowers to a List or a Tuple, and +// nil where it states none. Only the integer and boolean bounds are read here, +// as the statement holds the model's, each count where the model holds the +// number its literal states (annotation.ExactCount); one it does not is kept +// unread (keptCount). A uniqueItems the statement does not read bounds nothing +// (hasKey). func ownCollectionConstraints(schema *statement.Schema) *ir.Constraints { array := schema.ArrayKeywords() minItems, maxItems := annotation.ExactCount(schema, "minItems", array.MinItems), annotation.ExactCount(schema, "maxItems", array.MaxItems) - if minItems == nil && maxItems == nil && array.UniqueItems == nil { + unique := array.UniqueItems + if !hasKey(schema, "uniqueItems") { + unique = nil + } + if minItems == nil && maxItems == nil && unique == nil { return nil } cons := &ir.Constraints{MinItems: minItems, MaxItems: maxItems} - if array.UniqueItems != nil { - cons.UniqueItems = *array.UniqueItems + if unique != nil { + cons.UniqueItems = *unique } return cons } -// missingArrayItems reports a 3.0 schema that writes type array and no items, -// which 3.0 requires and 2020-12 leaves optional (GitHub #650). The lowering -// is alike in every dialect, so only this tells the document. -// -// It reads the declaration, never what it lowered to, so an array lowering to -// a tuple or an enum is held to the rule as a List is, a 3.0 prefixItems -// among them (docs/compilers/openapi.md#later-version-construct). `items: {}` -// is silent, as is a list, read off the raw node, which no documented parser -// behaviour models. missingArrayItemsConjoined reads past a schema's -// conjuncts; a subschema kept verbatim never reaches it. +// missingArrayItems reports, once at pointer, a 3.0 position whose conjunction +// states type array where no conjunct writes the items 3.0 requires +// (docs/compilers/openapi.md#missing-array-items). It reads the declaration, +// not the lowered type, so a tuple or an enum of arrays is held to the rule +// too. A $ref's target supplies items where admission's reading finds +// one, which items: true and a union's branches do not give. func missingArrayItems(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - if !slices.Contains(schema.Types(), statement.KindArray) { + if !loweringContext.SchemaRules().RequiredWhen("items", "type", string(statement.KindArray)) { return nil } - if _, listed := listedItems(schema); listed || written(schema.ArrayKeywords().Items) { + inline := inlineConjuncts(loweringContext, schema) + writesArrayType := func(conjunct *statement.Schema) bool { return slices.Contains(conjunct.Types(), statement.KindArray) } + if !slices.ContainsFunc(inline, writesArrayType) || slices.ContainsFunc(inline, writesItems) { return nil } - if !loweringContext.SchemaRules().RequiredWhen("items", "type", string(statement.KindArray)) { + if !writesConjuncts(schema) { + return []ir.Diagnostic{missingArrayItemsAt(loweringContext, pointer)} + } + admissionReader := newAdmissionReader(loweringContext) + if admissionReader.of(loweringContext.Statements().Read(schema)).items != nil { return nil } - return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.MissingArrayItems, pointer, + return []ir.Diagnostic{missingArrayItemsAt(loweringContext, pointer)} +} + +// missingArrayItemsAt is the warning missingArrayItems draws at pointer. +func missingArrayItemsAt(loweringContext lowering.Ctx, pointer jsontext.Pointer) ir.Diagnostic { + return loweringContext.DiagAt(ir.SeverityWarning, diag.MissingArrayItems, pointer, "OpenAPI 3.0 requires items when type is array, and this schema writes none, "+ - "so only its other keywords constrain its elements")} + "so only its other keywords constrain its elements") } -// missingArrayItemsConjoined is missingArrayItems for a schema writing -// conjuncts beside its keywords (writesConjuncts), a $ref or an allOf, which -// conjoin with them: a type array there leaves its elements to them, so it is -// reported only where admission's reading of the conjunction holds them to no -// items, which neither items: true nor a union's branches do. An items the -// reading found holds however much of the rest it read, and one cut short -// before reaching any leaves the keywords held to the rule as they are -// written. -func missingArrayItemsConjoined(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - diags := missingArrayItems(loweringContext, schema, pointer) - if len(diags) == 0 || !writesConjuncts(schema) { - return diags +// inlineConjuncts returns schema and each inline entry of its flattened allOf, +// the schema objects a position writes in place. +func inlineConjuncts(loweringContext lowering.Ctx, schema *statement.Schema) []*statement.Schema { + out := []*statement.Schema{schema} + if !writesConjuncts(schema) { + return out } - admissionReader := newAdmissionReader(loweringContext) - if admissionReader.of(loweringContext.Statements().Read(schema)).items != nil { - return nil + for _, entry := range loweringContext.Statements().Read(schema).Entries { + if stated(entry.Schema) && entry.Ref == nil { + out = append(out, entry.Schema) + } } - return diags + return out +} + +// writesItems reports whether schema writes `items`, one schema or a list. +func writesItems(schema *statement.Schema) bool { + _, listed := listedItems(schema) + return listed || written(schema.ArrayKeywords().Items) } diff --git a/compilers/openapi/internal/schema/array_internal_test.go b/compilers/openapi/internal/schema/array_internal_test.go index 308bf47b7..4caec7dcd 100644 --- a/compilers/openapi/internal/schema/array_internal_test.go +++ b/compilers/openapi/internal/schema/array_internal_test.go @@ -28,9 +28,9 @@ components: schemas: U: {type: [array, object], items: [{description: a}]} `) - js, ok := lowerer.Doc.Components.Schemas.Get("U") + jsonSchema, ok := lowerer.Doc.Components.Schemas.Get("U") require.True(t, ok) - _, at := writtenAt(lowerer.Ctx, lowerer.Ctx.Statements().Of(js).Schema, "/components/schemas/U/type/0") + _, at := writtenAt(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema).Schema, "/components/schemas/U/type/0") assert.Equal(t, jsontext.Pointer("/components/schemas/U"), at) _, at = writtenAt(lowerer.Ctx, StandaloneSchema(&oas3.Schema{}), "/x") assert.Equal(t, jsontext.Pointer("/x"), at, "a schema the bindings place nowhere") @@ -56,9 +56,9 @@ components: Prefixed: {type: array, prefixItems: [{description: a}], items: false} `) component := func(name string) *oas3.JSONSchema[oas3.Referenceable] { - js, ok := lowerer.Doc.Components.Schemas.Get(name) + jsonSchema, ok := lowerer.Doc.Components.Schemas.Get(name) require.True(t, ok, "sanity: %s is declared", name) - return js + return jsonSchema } descriptions := func(entries []*statement.Statement) []string { out := make([]string, 0, len(entries)) diff --git a/compilers/openapi/internal/schema/array_test.go b/compilers/openapi/internal/schema/array_test.go index 323899139..7cb2a7ee6 100644 --- a/compilers/openapi/internal/schema/array_test.go +++ b/compilers/openapi/internal/schema/array_test.go @@ -26,7 +26,7 @@ func TestLower_TupleRest(t *testing.T) { t.Parallel() const head = " type: array\n prefixItems: [{type: string}, {type: integer}]\n" i64 := func(v int64) *int64 { return &v } - for _, tc := range []struct { + for _, testCase := range []struct { name string body string rest ir.TypeID // "" = no rest @@ -70,28 +70,28 @@ func TestLower_TupleRest(t *testing.T) { consts: &ir.Constraints{MinItems: i64(3), MaxItems: i64(1), UniqueItems: true}, }, { - name: "unevaluatedItems is kept and the rest read from items alone", + // Nothing beside it evaluates an element past the head, so it lowers + // as items false does (GitHub #1883). + name: "a live unevaluatedItems false closes the tuple past its head", body: head + " unevaluatedItems: false\n", - rest: "type/primitive/any", - kept: []string{"openapi:unevaluated"}, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" Tup:\n"+tc.body)) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" Tup:\n"+testCase.body)) openapitest.RequireNoErrorDiags(t, diags) tup, ok := typeByName(doc, "Tup").(*ir.Tuple) require.True(t, ok, "prefixItems hoists a Tuple") assert.Equal(t, []ir.TypeRef{{Target: "type/primitive/string"}, {Target: "type/primitive/integer"}}, tup.ElementTypes) - if tc.rest == "" { + if testCase.rest == "" { assert.Nil(t, tup.Rest, "no element may follow the head") } else if assert.NotNil(t, tup.Rest) { - assert.Equal(t, tc.rest, tup.Rest.Target) + assert.Equal(t, testCase.rest, tup.Rest.Target) assert.Contains(t, doc.Types, tup.Rest.Target, "the rest is lowered into the registry") } - assert.Equal(t, tc.consts, tup.Constraints, "the instance's bounds reach Tuple.Constraints") - assert.Equal(t, tc.kept, unmodeledKeys(tup.Unmodeled)) + assert.Equal(t, testCase.consts, tup.Constraints, "the instance's bounds reach Tuple.Constraints") + assert.Equal(t, testCase.kept, unmodeledKeys(tup.Unmodeled)) assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Tup"), "a modeled rest is no degradation") }) @@ -150,7 +150,7 @@ func TestLower_MissingArrayItems(t *testing.T) { name string version string schemas string - want []string // report pointers, in order; nil when silent + want []string // report pointers, in order; nil when it reports nothing // invalid is the error the load phase reports, the case writing what its // version does not allow; "" for none. invalid string @@ -180,9 +180,9 @@ func TestLower_MissingArrayItems(t *testing.T) { {name: "a $ref to it from a sibling", version: "3.0.3", schemas: holder + " l: {$ref: '#/components/schemas/L'}\n L: {type: array}\n", want: []string{"/components/schemas/L"}}, - {name: "items written empty is silent", version: "3.0.3", + {name: "items written empty reports nothing", version: "3.0.3", schemas: " L: {type: array, items: {}}\n"}, - {name: "array keywords without a type are silent", version: "3.0.3", + {name: "array keywords without a type report nothing", version: "3.0.3", schemas: " L: {minItems: 1}\n"}, {name: "a $ref site's sibling type", version: "3.0.3", schemas: " L: {$ref: '#/components/schemas/S', type: array}\n S: {type: string}\n", @@ -191,12 +191,12 @@ func TestLower_MissingArrayItems(t *testing.T) { schemas: holder + " l: {$ref: '#/components/schemas/L'}\n" + " L: {$ref: '#/components/schemas/S', type: array}\n S: {type: string}\n", want: []string{"/components/schemas/L"}}, - {name: "a $ref site over a target writing items is silent", version: "3.0.3", + {name: "a $ref site over a target writing items reports nothing", version: "3.0.3", schemas: " L: {$ref: '#/components/schemas/X', type: array}\n X: {type: array, items: {type: string}}\n"}, - {name: "the same written as an allOf is silent", version: "3.0.3", + {name: "the same written as an allOf reports nothing", version: "3.0.3", schemas: " L: {allOf: [{$ref: '#/components/schemas/X'}, {type: array}]}\n" + " X: {type: array, items: {type: string}}\n"}, - {name: "a $ref site over an alias whose end writes items is silent", version: "3.0.3", + {name: "a $ref site over an alias whose end writes items reports nothing", version: "3.0.3", schemas: " L: {$ref: '#/components/schemas/M', type: array}\n M: {$ref: '#/components/schemas/X'}\n" + " X: {allOf: [{type: array, items: {type: string}}]}\n"}, {name: "a $ref site over a union whose branches write items", version: "3.0.3", @@ -209,17 +209,17 @@ func TestLower_MissingArrayItems(t *testing.T) { {name: "a $ref site over an untyped target", version: "3.0.3", schemas: " L: {$ref: '#/components/schemas/A', type: array}\n A: {}\n", want: []string{"/components/schemas/L"}}, - {name: "a $ref site's sibling type in 3.1 is silent", version: "3.1.0", + {name: "a $ref site's sibling type in 3.1 reports nothing", version: "3.1.0", schemas: " L: {$ref: '#/components/schemas/S', type: array}\n S: {type: string}\n"}, - {name: "an array kept verbatim under not is silent", version: "3.0.3", + {name: "an array kept verbatim under not reports nothing", version: "3.0.3", schemas: " L: {type: integer, not: {type: array}}\n"}, - {name: "3.1 is silent", version: "3.1.0", schemas: " L: {type: array}\n"}, - {name: "3.2 is silent", version: "3.2.0", schemas: " L: {type: array}\n"}, + {name: "3.1 reports nothing", version: "3.1.0", schemas: " L: {type: array}\n"}, + {name: "3.2 reports nothing", version: "3.2.0", schemas: " L: {type: array}\n"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - lowerer, loadDiags := schema.LoweredFor(t, openapitest.ComponentSpecVer(tc.version, tc.schemas)) + lowerer, loadDiags := schema.LoweredFor(t, openapitest.ComponentSpecVer(testCase.version, testCase.schemas)) raw := schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas()) openapitest.RequireNoErrorDiags(t, raw) var invalid []string @@ -228,8 +228,8 @@ func TestLower_MissingArrayItems(t *testing.T) { invalid = append(invalid, diagnostic.Code) } } - assert.Equal(t, tc.invalid, strings.Join(invalid, ", "), "the load phase's errors: %+v", loadDiags) - assert.Equal(t, tc.want, missingItemsAt(t, raw)) + assert.Equal(t, testCase.invalid, strings.Join(invalid, ", "), "the load phase's errors: %+v", loadDiags) + assert.Equal(t, testCase.want, missingItemsAt(t, raw)) }) } } diff --git a/compilers/openapi/internal/schema/besideref.go b/compilers/openapi/internal/schema/besideref.go new file mode 100644 index 000000000..5852c2a91 --- /dev/null +++ b/compilers/openapi/internal/schema/besideref.go @@ -0,0 +1,790 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "cmp" + "encoding/json/jsontext" + "slices" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// besideRefOutcome is how a format or content keyword written on a conjunct +// beside one $ref to a scalar lowers, read as its flat twin, the keyword over +// the target's JSON type, reads it (docs/compilers/openapi.md#allof-refinement). +type besideRefOutcome uint8 + +const ( + // besideRefNone marks a conjunction writing no such keyword. + besideRefNone besideRefOutcome = iota + // besideRefRestricts marks a keyword selecting no primitive of its own: + // the position restricts the reference, carrying the twin's Encoding. + besideRefRestricts + // besideRefConjunctIsPrincipal marks a format selecting a primitive narrower + // than the target's root, or a contentEncoding beside a root read from the + // text: the conjunct writing it is the principal, the $ref kept. + besideRefConjunctIsPrincipal + // besideRefRestates marks a format the target's root already is, or lies + // within: it says nothing. + besideRefRestates + // besideRefKept marks a keyword kept as written beside any use: the + // target carries an Encoding of another name, or the format selects a + // primitive neither within nor wider than the target's. + besideRefKept +) + +// keywordBesideRef is the reading of a format, or the content vocabulary, +// written beside a conjunction's one $ref to a scalar: the conjunct writing +// the format or contentEncoding, else contentMediaType, and where it is among +// the conjuncts; the conjunct writing contentMediaType or contentSchema where +// another, and where it is; where the $ref is, the target's JSON type and the +// schema of its chain writing those two (scalarRoot.media), what the flat twin +// lowers to, the outcome, and whether the $ref's chain lands on more than +// maxScalarChainNodes schemas, which leaves the keyword unread against the +// scalar it ends on. +type keywordBesideRef struct { + conjunctSchema *statement.Schema + media *statement.Schema + chainMedia *statement.Schema + jsonType statement.JSONSchemaTypeName + flatShape scalarShape + conjunctAt annotation.ConjunctIndex + mediaAt annotation.ConjunctIndex + refAt annotation.ConjunctIndex + outcome besideRefOutcome + cut bool +} + +// writes reports whether schema writes a keyword r reads: it is the conjunct, +// or the conjunct writing contentMediaType or contentSchema. +func (r keywordBesideRef) writes(schema *statement.Schema) bool { + return schema != nil && (schema == r.conjunctSchema || schema == r.media) +} + +// consumes reports whether the outcome reads key, a keyword schema writes, as +// said: the conjunct's keyword where it restricts the reference or restates it. +func (r keywordBesideRef) consumes(schema *statement.Schema, key string) bool { + if !r.writes(schema) || r.outcome != besideRefRestricts && r.outcome != besideRefRestates { + return false + } + return key == "format" || slices.Contains(contentKeywords, key) +} + +// principalAt returns where the conjunct the position lowers from is among the +// conjuncts: the conjunct where it is chosen, else the $ref. +func (r keywordBesideRef) principalAt() annotation.ConjunctIndex { + if r.outcome == besideRefConjunctIsPrincipal { + return r.conjunctAt + } + return r.refAt +} + +// scalarRoot is what a chain of $refs ends on, read as the lowering roots it: +// the JSON type, the primitive the chain is rooted at, whether the chain +// carries an Encoding and the name it carries, its nearest one, the nearest +// schema of the chain writing contentMediaType or contentSchema, nil for +// none, and whether it ends on an enum rather than a scalar. +type scalarRoot struct { + media *statement.Schema + jsonType statement.JSONSchemaTypeName + root ir.PrimitiveKind + encoding string + carries bool + enum bool +} + +// chainNodeConjuncts is a conjunction holding one $ref beside conjuncts that +// write nothing of a shape but a type naming one kind: where that $ref is, each +// type a conjunct names, and the conjuncts writing a format, a contentEncoding +// and contentMediaType or contentSchema, each by one conjunct at most, with +// where each is among the conjuncts, read only where it is written. A hop +// writes a format beside none of the content vocabulary (chainNodeConjunctsOf); +// a target holding no $ref may (conjoinedRoot). +type chainNodeConjuncts struct { + ref *statement.Statement + format *statement.Schema + encoding *statement.Schema + media *statement.Schema + types []statement.JSONSchemaTypeName + refAt annotation.ConjunctIndex + formatAt annotation.ConjunctIndex + encodingAt annotation.ConjunctIndex + mediaAt annotation.ConjunctIndex +} + +// conjunct returns the conjunct whose keyword decides the reading, the +// format's, else contentEncoding's, else the content vocabulary's, and where it +// is among the conjuncts, nil where none writes one. +func (l chainNodeConjuncts) conjunctSchema() (*statement.Schema, annotation.ConjunctIndex) { + switch { + case l.format != nil: + return l.format, l.formatAt + case l.encoding != nil: + return l.encoding, l.encodingAt + default: + return l.media, l.mediaAt + } +} + +// encodingName returns the contentEncoding the conjuncts write, "" for none. +func (l chainNodeConjuncts) encodingName() string { + if l.encoding == nil { + return "" + } + return l.encoding.TextKeywords().ContentEncoding +} + +// besideRefsOfRun keys the run's store of the readings of keywords beside a +// $ref. +type besideRefsOfRun struct{} + +// besideRefStore is what a run has read of keywords beside a $ref: each +// position's reading, and what the chain from each hop or end it walked +// reaches. +type besideRefStore struct { + read map[*statement.Schema]keywordBesideRef + roots map[*statement.Schema]chainedRoot +} + +// besideRefsOf returns the run's store. +func besideRefsOf(loweringContext lowering.Ctx) *besideRefStore { + return lowering.ReadOncePerRun(loweringContext, besideRefsOfRun{}, func() *besideRefStore { + return &besideRefStore{read: map[*statement.Schema]keywordBesideRef{}, roots: map[*statement.Schema]chainedRoot{}} + }) +} + +// besideRefOf returns how schema's conjunction reads a format or content +// keyword written beside its one $ref to a scalar (keywordBesideRef), read +// once a run, and the zero reading where it writes no such conjunction. +func besideRefOf(loweringContext lowering.Ctx, schema *statement.Schema) keywordBesideRef { + if !writesConjuncts(schema) { + return keywordBesideRef{} + } + store := besideRefsOf(loweringContext) + if read, ok := store.read[schema]; ok { + return read + } + read := readBesideRef(loweringContext, schema) + store.read[schema] = read + return read +} + +// readBesideRef reads what besideRefOf remembers. The target is read through +// its chain of $refs and the hops writing beside them, which no bound of an +// admission's read cuts, so a long chain follows the same outcome, up to +// maxScalarChainNodes schemas. +func readBesideRef(loweringContext lowering.Ctx, schema *statement.Schema) keywordBesideRef { + chainNode, ok := chainNodeConjunctsOf(loweringContext, schema) + conjunctSchema, _ := chainNode.conjunctSchema() + if !ok || conjunctSchema == nil { + return keywordBesideRef{} + } + target, within := scalarChainOf(loweringContext, chainNode.ref) + if !within { + return keywordBesideRef{conjunctSchema: conjunctSchema, cut: true} + } + if !target.ok || !chainNode.typesWithin(target.root.jsonType) { + return keywordBesideRef{} + } + return chainNode.read(target.root) +} + +// scalarChainPastBound returns the error schema, written at pointer, draws +// where the chain of $refs beside whose one $ref it writes a format or content +// keyword lands on more than maxScalarChainNodes schemas +// (keywordBesideRef.cut): the keyword is then not read against the scalar the +// chain ends on. +func scalarChainPastBound(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + if !besideRefOf(loweringContext, schema).cut { + return nil + } + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.BudgetExceeded, pointer, + "the chain of $refs beside which this schema writes a format or content keyword lands on more than %d schemas, "+ + "past which the keyword is not read against the scalar the chain ends on", maxScalarChainNodes)} +} + +// chainNodeConjunctsOf reads schema's flattened conjunction as +// chainNodeConjuncts, and false where it holds no $ref, scalarConjunctsOf reads +// none, or a format is written beside the content vocabulary. +func chainNodeConjunctsOf(loweringContext lowering.Ctx, schema *statement.Schema) (chainNodeConjuncts, bool) { + chainNode, ok := scalarConjunctsOf(loweringContext, schema) + return chainNode, ok && chainNode.ref != nil && !chainNode.formatBesideContent() +} + +// formatBesideContent reports whether the conjuncts write a format and any of +// the content vocabulary, on one conjunct or several. +func (l chainNodeConjuncts) formatBesideContent() bool { + return l.format != nil && (l.encoding != nil || l.media != nil) +} + +// scalarConjunctsOf reads schema's flattened conjunction as chainNodeConjuncts, +// and false where it holds more than one $ref, a boolean `false`, an allOf +// nested past the flattening depth, or a conjunct writing more. +func scalarConjunctsOf(loweringContext lowering.Ctx, schema *statement.Schema) (chainNodeConjuncts, bool) { + var chainNode chainNodeConjuncts + if !chainNode.take(schema, annotation.BesideAllOf) { + return chainNodeConjuncts{}, false + } + for i, entry := range allOfEntries(loweringContext, schema, "").entries { + switch { + case entry.capped || entry.schema.Truth.ReadsFalse(): + return chainNodeConjuncts{}, false + case entry.schema.Truth != statement.Stated: + case entry.schema.Ref != nil && chainNode.ref != nil: + return chainNodeConjuncts{}, false + case entry.schema.Ref != nil: + chainNode.ref, chainNode.refAt = entry.schema, annotation.ConjunctIndex(i) + case !chainNode.take(entry.schema.Schema, annotation.ConjunctIndex(i)): + return chainNodeConjuncts{}, false + } + } + return chainNode, true +} + +// conjoinedRoot returns the scalar schema, whose conjunction l reads, lowers +// to as its flat twin does where it holds no $ref: the one kind its conjuncts +// name, rooted where the format one writes selects beside the content +// vocabulary the others write, each read off the conjunct writing it; and +// false where it holds a $ref or they name no kind, several, an object or an +// array. +func (l chainNodeConjuncts) conjoinedRoot(schema *statement.Schema) (scalarRoot, bool) { + if l.ref != nil || len(l.types) == 0 || !l.typesWithin(l.types[0]) || l.types[0] == statement.KindObject || l.types[0] == statement.KindArray { + return scalarRoot{}, false + } + format := "" + if l.format != nil { + format = writtenFormat(l.format) + } + content := cmp.Or(l.encoding, l.media, l.format, schema) + return rootOfConjuncts(content, format, l.media, l.types[0]), true +} + +// take reads schema, a conjunct but the $ref, at at among the conjuncts: it +// writes no union, dynamic reference, value set or shape keyword, a type +// naming one kind alone where it writes one, and a format, a contentEncoding +// or contentMediaType with contentSchema no other conjunct writes where it +// writes one. +func (l *chainNodeConjuncts) take(schema *statement.Schema, at annotation.ConjunctIndex) bool { + if declaresUnion(schema) || declaresDynamicRef(schema) || slices.ContainsFunc(siblingKeywords(schema), func(key string) bool { + return key != "type" && key != "allOf" + }) { + return false + } + if writesType(schema) { + if len(effectiveTypes(schema)) != 1 { + return false + } + l.types = append(l.types, effectiveTypes(schema)[0]) + } + text := schema.TextKeywords() + format, encoding, media := writtenFormat(schema) != "", text.ContentEncoding != "", text.ContentMediaType != "" || written(text.ContentSchema) + if format && l.format != nil || encoding && l.encoding != nil || media && l.media != nil { + return false + } + if format { + l.format, l.formatAt = schema, at + } + if encoding { + l.encoding, l.encodingAt = schema, at + } + if media { + l.media, l.mediaAt = schema, at + } + return true +} + +// typesWithin reports whether every type the conjuncts name is jsonType. +func (l chainNodeConjuncts) typesWithin(jsonType statement.JSONSchemaTypeName) bool { + return !slices.ContainsFunc(l.types, func(named statement.JSONSchemaTypeName) bool { return named != jsonType }) +} + +// read returns how the conjunct's keyword reads beside a $ref to target. +func (l chainNodeConjuncts) read(target scalarRoot) keywordBesideRef { + conjunctSchema, conjunctAt := l.conjunctSchema() + out := keywordBesideRef{conjunctSchema: conjunctSchema, conjunctAt: conjunctAt, refAt: l.refAt, jsonType: target.jsonType, chainMedia: target.media} + if l.media != conjunctSchema { + out.media, out.mediaAt = l.media, l.mediaAt + } + if target.enum { + out.flatShape = scalarShape{base: target.root, format: writtenFormat(conjunctSchema)} + out.outcome = enumOutcome(target, conjunctSchema, scalarShapeOf(conjunctSchema, target.jsonType, writtenFormat(conjunctSchema))) + return out + } + out.flatShape = scalarShapeOf(conjunctSchema, target.jsonType, writtenFormat(conjunctSchema)) + if l.format == nil { + out.outcome = contentOutcome(target, l.encodingName()) + return out + } + out.outcome = formatOutcome(target, out.flatShape) + return out +} + +// enumOutcome is how the keyword conjunct writes reads beside a $ref to target, +// an enum, whose flat twin lowers to flatShape: a format selecting no primitive +// of its own restricts the reference with an Encoding naming it, as it +// restricts one to a scalar, so the enum's members stay the target's alone, +// unless a hop nearer the enum carries an Encoding, which one of the same name +// restates and one of another keeps beside it. A format selecting a primitive +// no use of the enum is rooted at is kept, as is the content vocabulary, as at +// any use. +func enumOutcome(target scalarRoot, conjunctSchema *statement.Schema, flatShape scalarShape) besideRefOutcome { + switch { + case declaresContentVocabulary(conjunctSchema): + return besideRefNone + case !flatShape.selectsNoPrimitive(target.jsonType): + return besideRefKept + case !target.carries: + return besideRefRestricts + case target.encoding == writtenFormat(conjunctSchema): + return besideRefRestates + default: + return besideRefKept + } +} + +// contentOutcome is how the content vocabulary, content its contentEncoding, +// reads beside a $ref to target, as its flat twin, the vocabulary over the +// target, reads: a contentEncoding of another name over a root read from the +// text makes the string that encoding's text, its conjunct chosen; otherwise a +// restriction, unless target carries an Encoding naming another encoding, +// where it is kept, and none beside a root no string is, which takes no +// content. +func contentOutcome(target scalarRoot, content string) besideRefOutcome { + switch { + case target.jsonType != statement.KindString: + return besideRefNone + case encodesTextRoot(target, content): + return besideRefConjunctIsPrincipal + case target.carries && target.encoding != "" && target.encoding != content: + return besideRefKept + default: + return besideRefRestricts + } +} + +// encodesTextRoot reports whether content, a contentEncoding, written beside a +// $ref to target, a string's root, makes the string that encoding's text where +// the root is a value read from the text: no plain string or bytes, and no +// Encoding of content's own name that the root carries, which it restates. +func encodesTextRoot(target scalarRoot, content string) bool { + if content == "" || target.root == ir.PrimitiveString || target.root == ir.PrimitiveBytes { + return false + } + return !target.carries || target.encoding != content +} + +// selectsNoPrimitive reports whether s, the flat twin of a format over +// jsonType, selects no primitive of its own: it is the type's plain primitive, +// travelling as itself. +func (s scalarShape) selectsNoPrimitive(jsonType statement.JSONSchemaTypeName) bool { + return s.base == baseForType(jsonType) && s.wire == nil +} + +// formatOutcome is how a format whose flat twin lowers to flatShape reads +// beside a $ref to target (docs/compilers/openapi.md#allof-refinement): +// selecting no primitive of its own, it restricts the reference where target +// carries no Encoding, restates the one of its own name and is kept beside +// another; selecting the target's root, or one wider than a format root, it +// says nothing; one narrower, or another over a plain root, is chosen; any +// other is kept. +func formatOutcome(target scalarRoot, flatShape scalarShape) besideRefOutcome { + plain := baseForType(target.jsonType) + switch { + case flatShape.selectsNoPrimitive(target.jsonType) && target.carries: + if target.encoding == flatShape.format { + return besideRefRestates + } + return besideRefKept + case flatShape.selectsNoPrimitive(target.jsonType): + return besideRefRestricts + case flatShape.base == target.root: + return besideRefRestates + case target.root == plain, typeformat.Relate(flatShape.base, target.root) == typeformat.ANarrower: + return besideRefConjunctIsPrincipal + case typeformat.Relate(target.root, flatShape.base) == typeformat.ANarrower: + return besideRefRestates + default: + return besideRefKept + } +} + +// maxScalarChainNodes bounds the schemas a chain of $refs to a scalar target +// may land on, its hops and its end, for a keyword beside its first $ref to +// read it (scalarChainOf), as the compiler bounds nesting at 1024: an +// admission's bounds do not cut the chain, and each hop's reading is kept +// once a run, so the reads of a document's chains are linear in their hops +// together. +const maxScalarChainNodes = 1024 + +// chainedRoot is a hop's reading kept once a run: the scalar its chain ends +// on, whether it ends on one, and the schemas its chain lands on from it, +// itself included, which a chain through it counts against +// maxScalarChainNodes. +type chainedRoot struct { + root scalarRoot + nodeCount int + ok bool +} + +// scalarChainOf returns what the chain of $refs from ref reaches: the scalar it +// ends on, read through each hop writing a conjunction of one $ref +// (chainNodeConjunctsOf), and not ok where it ends on anything else, lands +// nowhere or closes a loop; and false where it lands on more than +// maxScalarChainNodes schemas, counted whole, so no other reading decides where +// it is cut. A hop's keyword moves the root or the Encoding (readChainNodes). +// The walk goes forward to the first schema the run has read, then reads back, +// each schema once a run. +func scalarChainOf(loweringContext lowering.Ctx, ref *statement.Statement) (chainedRoot, bool) { + store := besideRefsOf(loweringContext).roots + var chainNodes []*statement.Schema + seen := map[*statement.Schema]bool{} + for schemaStatement := ref; len(chainNodes) < maxScalarChainNodes; { + end, ok := runEnd(loweringContext, schemaStatement) + if !ok || end.Truth != statement.Stated || seen[end.Schema] { + return readChainNodes(loweringContext, store, chainNodes, chainedRoot{}), true + } + if read, known := store[end.Schema]; known { + return readChainNodes(loweringContext, store, chainNodes, read), len(chainNodes)+read.nodeCount <= maxScalarChainNodes + } + seen[end.Schema] = true + if !writesConjuncts(end.Schema) { + root, ok := scalarRootOf(end.Schema) + store[end.Schema] = chainedRoot{root: root, nodeCount: 1, ok: ok} + return readChainNodes(loweringContext, store, chainNodes, store[end.Schema]), true + } + chainNode, ok := scalarConjunctsOf(loweringContext, end.Schema) + if !ok || chainNode.ref == nil || chainNode.formatBesideContent() { + root, scalar := chainNode.conjoinedRoot(end.Schema) + store[end.Schema] = chainedRoot{root: root, nodeCount: 1, ok: ok && scalar} + return readChainNodes(loweringContext, store, chainNodes, store[end.Schema]), true + } + chainNodes = append(chainNodes, end.Schema) + schemaStatement = chainNode.ref + } + return chainedRoot{}, false +} + +// readChainNodes reads hops, each writing one $ref to the next and the last to +// what read says its chain reaches, back from the last, keeping each one's +// reading in store, and returns the first's: each hop's types within the +// root's, a restriction carrying its Encoding and a chosen format rooting +// it at its primitive, and the schemas from it counted. +func readChainNodes(loweringContext lowering.Ctx, store map[*statement.Schema]chainedRoot, chainNodes []*statement.Schema, read chainedRoot) chainedRoot { + count := read.nodeCount + for _, schema := range slices.Backward(chainNodes) { + chainNode, _ := chainNodeConjunctsOf(loweringContext, schema) + count++ + read = chainNodeOver(chainNode, read) + read.nodeCount = count + store[schema] = read + } + return read +} + +// chainNodeOver returns what the chain from chainNode reaches, read being what +// its $ref's chain does. +func chainNodeOver(chainNode chainNodeConjuncts, read chainedRoot) chainedRoot { + if !read.ok || !chainNode.typesWithin(read.root.jsonType) { + return chainedRoot{} + } + if conjunctSchema, _ := chainNode.conjunctSchema(); conjunctSchema == nil { + return read + } + switch over := chainNode.read(read.root); over.outcome { + case besideRefRestricts: + read.root.encoding, read.root.carries = restrictionName(over), true + read.root.media = over.mediaConjunct() + case besideRefConjunctIsPrincipal: + if chainNode.format == nil { + read.root.root, read.root.encoding, read.root.carries = ir.PrimitiveString, restrictionName(over), true + read.root.media = over.mediaConjunct() + break + } + read.root.root, read.root.encoding, read.root.carries = over.flatShape.base, over.flatShape.format, !over.flatShape.shared + default: + } + return read +} + +// mediaConjunct returns the schema whose contentMediaType and contentSchema a +// restriction or a chosen contentEncoding beside the $ref carries: the +// conjunct writing them, else the nearest schema of the target's chain, nil +// for none. +func (r keywordBesideRef) mediaConjunct() *statement.Schema { + switch { + case r.media != nil: + return r.media + case r.conjunctSchema != nil && writesMedia(r.conjunctSchema): + return r.conjunctSchema + default: + return r.chainMedia + } +} + +// writesMedia reports whether schema writes contentMediaType or contentSchema. +func writesMedia(schema *statement.Schema) bool { + text := schema.TextKeywords() + return text.ContentMediaType != "" || written(text.ContentSchema) +} + +// restrictionName is the name the Encoding a restriction carries holds: its +// conjunct's contentEncoding, else the format. +func restrictionName(read keywordBesideRef) string { + if content := read.conjunctSchema.TextKeywords().ContentEncoding; content != "" { + return content + } + return read.flatShape.format +} + +// scalarRootOf returns the scalar schema, ending a chain of $refs, lowers to: +// one writing a type naming one primitive kind and nothing of a shape, value +// set or union beside it, rooted where its type and format select, carrying +// the Encoding its Scalar holds where it is no shared primitive; or the enum of +// such a type writing nothing else of a shape (enumRootOf). +func scalarRootOf(schema *statement.Schema) (scalarRoot, bool) { + types := effectiveTypes(schema) + if len(types) != 1 || types[0] == statement.KindObject || types[0] == statement.KindArray || + declaresUnion(schema) || declaresDynamicRef(schema) { + return scalarRoot{}, false + } + switch keywords := siblingKeywords(schema); { + case slices.Equal(keywords, []string{"enum", "type"}): + return enumRootOf(schema, types[0]) + case !slices.Equal(keywords, []string{"type"}): + return scalarRoot{}, false + } + return rootOfShape(schema, types[0]), true +} + +// rootOfShape returns the root a scalar of jsonType that schema writes, with +// its format and content vocabulary, is (rootOfConjuncts). +func rootOfShape(schema *statement.Schema, jsonType statement.JSONSchemaTypeName) scalarRoot { + var media *statement.Schema + if writesMedia(schema) { + media = schema + } + return rootOfConjuncts(schema, writtenFormat(schema), media, jsonType) +} + +// rootOfConjuncts returns the root a scalar of jsonType is, its format given +// and content writing its contentEncoding, or else the rest of its content +// vocabulary, as scalarShapeOf reads them: where its type and format select, +// carrying the Encoding its Scalar holds where it is no shared primitive, and +// media, the schema writing contentMediaType or contentSchema, nil for none, +// for a type that takes them. +func rootOfConjuncts(content *statement.Schema, format string, media *statement.Schema, jsonType statement.JSONSchemaTypeName) scalarRoot { + shape := scalarShapeOf(content, jsonType, format) + root := scalarRoot{jsonType: jsonType, root: shape.base, carries: !shape.shared} + if media != nil && takesContent(kindsOfTypeNameOrAny(jsonType)) { + root.media = media + } + if root.carries { + root.encoding = shape.format + if encoding := content.TextKeywords().ContentEncoding; encoding != "" && takesContent(kindsOfTypeNameOrAny(jsonType)) { + root.encoding = encoding + } + } + return root +} + +// enumRootOf returns the root a chain ending on schema, an enum of jsonType, +// reads: the enum, beside whose reference a format carries an Encoding naming +// it (enumOutcome), its members read nowhere, so no bound on reading them cuts +// it. One writing a format or the content vocabulary of its own, which an Enum +// holds no field for, is none, and a keyword beside it is kept as at any use +// (docs/compilers/openapi.md#allof-refinement). +func enumRootOf(schema *statement.Schema, jsonType statement.JSONSchemaTypeName) (scalarRoot, bool) { + if schema.FormatName() != "" || declaresContentVocabulary(schema) { + return scalarRoot{}, false + } + return scalarRoot{jsonType: jsonType, root: baseForType(jsonType), enum: true}, true +} + +// besideRefDecision returns the decision on schema, whose conjuncts, comp's +// as admissionReader read them, write a format or content keyword beside one +// $ref to a scalar (besideRefOf), and false where they write none. The $ref is +// the principal, or the conjunct writing a format it chooses, read as its flat +// twin, the $ref then kept as a beaten conjunct; on both sides of a bound of +// the read alike, as the chain's root is read whole. +func besideRefDecision(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, conjuncts []conjunct) (refinementDecision, bool) { + read := besideRefOf(loweringContext, schema) + if read.outcome == besideRefNone { + return refinementDecision{}, false + } + at := slices.IndexFunc(conjuncts, func(conjunct conjunct) bool { return conjunct.entryIndex == read.principalAt() }) + if at < 0 { + return refinementDecision{}, false + } + refChoiceReasons := make([]refChoiceReason, len(comp.entries)) + if read.outcome == besideRefConjunctIsPrincipal { + refChoiceReasons[read.refAt] = refChoiceReasonBesideConjunct(read) + conjuncts[at].read = flatSpellingRead(conjuncts[at].read, read) + } + admittedTogether := conjuncts[0].read + for _, conjunct := range conjuncts[1:] { + admittedTogether = admittedTogether.and(conjunct.read) + } + principal := &conjuncts[at] + refinementValue := refinement{refChoiceReasons: refChoiceReasons, admittedTogether: admittedTogether, loweredAdmits: loweredAdmitsOf(loweringContext, schema, principal), besideRef: read} + refAt, readsThrough := readThrough(conjuncts, principal) + return refinementDecision{refinement: refinementValue, principalAt: principal.entryIndex, refAt: refAt, outcome: decisionRefines, hasPrincipal: true, readsThrough: readsThrough}, true +} + +// refChoiceReasonBesideConjunct returns how the $ref a chosen conjunct passed +// over fared: beside a format narrowing its target's root, or beside a +// contentEncoding making the string the text its root is read from. +func refChoiceReasonBesideConjunct(read keywordBesideRef) refChoiceReason { + if declaresContentVocabulary(read.conjunctSchema) { + return refContentEncodesText + } + return refFormatNarrows +} + +// flatSpellingRead is what a chosen conjunct's conjunct, read as admitted, +// admits as its flat twin does: the kinds of the target's JSON type, null as it +// reads it, held to the format the twin's primitive is where it writes one. +func flatSpellingRead(read admitted, besideRefValue keywordBesideRef) admitted { + read.kinds &= kindsOfTypeName(besideRefValue.jsonType) | kindNull + format := writtenFormat(besideRefValue.conjunctSchema) + if format == "" { + return read + } + primitive, listed := typeformat.Lookup(string(besideRefValue.jsonType) + "/" + format) + read.forms = []scalarForm{{conjunctSchema: besideRefValue.conjunctSchema, spelled: format, primitive: primitive, listed: listed}} + return read +} + +// flatSpellingTypeOf returns the type schema, the principal, lowers by as its +// flat twin: the target's JSON type where schema is the chosen format's +// conjunct writing no type, and "" for any other. +func (r keywordBesideRef) flatSpellingTypeOf(schema *statement.Schema) statement.JSONSchemaTypeName { + if r.outcome != besideRefConjunctIsPrincipal || schema != r.conjunctSchema || writesType(schema) { + return "" + } + return r.jsonType +} + +// typingOfFlatSpelling returns typingValue, a schema's own typing, or, where it +// names no type and flatSpellingType does, the type it names +// (nodePlacement.flatSpellingType). +func typingOfFlatSpelling(typingValue typing, flatSpellingType statement.JSONSchemaTypeName) typing { + if flatSpellingType == "" || !typingValue.top() { + return typingValue + } + return typing{types: []statement.JSONSchemaTypeName{flatSpellingType}} +} + +// restrictionEncoding returns the Encoding schema, written at pointer, +// restricts its reference with (besideRefRestricts), built as the flat twin's +// is (scalarEncoding): named by the conjunct, its media type and content +// schema, lowered at depth, those the conjuncts write, else the target's +// chain's (mediaConjunct); nil for none. A format is written beside none of the +// content vocabulary, so no name of the one is kept for the other's. +func restrictionEncoding(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, +) (*ir.Encoding, []ir.Diagnostic) { + read := besideRefOf(loweringContext, schema) + if read.outcome != besideRefRestricts { + return nil, nil + } + if !takesContent(kindsOfTypeNameOrAny(read.jsonType)) { + return &ir.Encoding{Name: read.flatShape.format}, nil + } + enc := &ir.Encoding{Name: restrictionName(read)} + media := read.mediaConjunct() + if media == nil { + return enc, nil + } + writing := contentWriting{media: annotation.FlattenedAllOfEntry{Node: media}, chained: media == read.chainMedia} + switch media { + case read.media: + writing.media.At = conjunctPointer(loweringContext, schema, pointer, read.mediaAt) + case read.conjunctSchema: + writing.media.At = conjunctPointer(loweringContext, schema, pointer, read.conjunctAt) + default: + } + content, diags := writing.contentSchema(loweringContext, types, depth) + enc.MediaType, enc.Schema = media.TextKeywords().ContentMediaType, content + return enc, diags +} + +// conjunctPointer returns where the conjunct of schema, written at pointer, at +// at among its conjuncts is written: pointer for annotation.BesideAllOf, the +// position's own keywords, else where its flattened entry is. +func conjunctPointer(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, at annotation.ConjunctIndex) jsontext.Pointer { + i, isEntry := at.Entry() + if !isEntry { + return pointer + } + return allOfEntries(loweringContext, schema, pointer).entries[i].pointer +} + +// chosenEncodingMedia returns the schema of the target's chain writing +// contentMediaType or contentSchema that a contentEncoding chosen beside the +// $ref reads where no conjunct writes them, as its flat twin reads the +// target's, nil where none does or the reading chooses no contentEncoding. +func (r keywordBesideRef) chosenEncodingMedia() *statement.Schema { + if r.outcome != besideRefConjunctIsPrincipal || r.conjunctSchema == nil || writtenFormat(r.conjunctSchema) != "" { + return nil + } + return r.chainMedia +} + +// readsContentOf reports whether the content vocabulary schema writes is read +// beside the reference rather than kept as content no node holds: schema +// writes it as a conjunct whose restriction carries it, or keeps it as a +// keyword beside a target carrying an Encoding of another name (keptContent). +func (r keywordBesideRef) readsContentOf(schema *statement.Schema) bool { + return r.writes(schema) && (r.outcome == besideRefRestricts || r.outcome == besideRefKept) && declaresContentVocabulary(schema) +} + +// keptContent returns the content keywords schema, the position, writes that +// it keeps beside a target carrying an Encoding of another name, as a format +// written there is kept, where it writes them as its own keywords. +func (r keywordBesideRef) keptContent(schema *statement.Schema) []string { + if !r.writes(schema) || r.outcome != besideRefKept { + return nil + } + return slices.DeleteFunc(slices.Clone(contentKeywords), func(key string) bool { return !hasKey(schema, key) }) +} + +// keepsContentOf reports whether the content vocabulary schema, a conjunct, +// writes is kept beside a target carrying an Encoding of another name, so +// it is reported as a kept format is, not as content no shape holds. +func (r keywordBesideRef) keepsContentOf(schema *statement.Schema) bool { + return r.outcome == besideRefKept && r.writes(schema) && declaresContentVocabulary(schema) +} + +// restrictedUse interns at pointer the Scalar over target carrying enc, the +// Encoding the schema written there restricts the reference with, as the flat +// twin's Scalar carries it, for a position whose carrier holds what else it +// declares, and returns the use of it, which keeps what target says of null. +func restrictedUse(loweringContext lowering.Ctx, types *compile.Types, target ir.TypeRef, pointer jsontext.Pointer, enc *ir.Encoding) ir.TypeRef { + out := target + out.Target = internNode(loweringContext, types, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + alias := aliasHolding(common, nil, target) + alias.Encoding = enc + return alias, 0 + }).id + return out +} + +// RestrictionContentEncoding returns the contentEncoding a conjunct writes +// beside schema's $ref to a string that restricts the reference with it +// (besideRefRestricts), which the node schema lowers to carries, and "" where +// none does: a reader of what that node carries reads it there, as it reads +// what the schema deciding it writes (DecidingSchema) otherwise. +func RestrictionContentEncoding(loweringContext lowering.Ctx, schema *statement.Schema) string { + read := besideRefOf(loweringContext, schema) + if read.outcome != besideRefRestricts { + return "" + } + return read.conjunctSchema.TextKeywords().ContentEncoding +} diff --git a/compilers/openapi/internal/schema/besideref_internal_test.go b/compilers/openapi/internal/schema/besideref_internal_test.go new file mode 100644 index 000000000..deb8cb4b1 --- /dev/null +++ b/compilers/openapi/internal/schema/besideref_internal_test.go @@ -0,0 +1,213 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" +) + +// besideRefTargets are the scalars, and the hops over them, the outcome +// cases are written beside: plain primitives, an Encoding carried of a +// target's own and through a restricting hop, a format primitive, values read +// from the text and a hop encoding one, a hop choosing a number as text, one +// naming a type its target excludes, a loop, enums with and without a format +// and a restricting hop, a type list naming null, conjunctions naming one +// scalar kind, content split across them, and an object, a const and +// conjunctions naming no kind, two or an object. +const besideRefTargets = ` S: {type: string} + I: {type: integer} + SX: {type: string, format: x-other} + SU: {type: string, format: uuid} + I32: {type: integer, format: int32} + D: {type: string, format: date} + DT: {type: string, format: date-time} + N64: {type: string, format: int64} + EncodedText: {allOf: [{$ref: '#/components/schemas/DT'}], contentEncoding: base64} + B64: {type: string, contentEncoding: base64} + FormatLink: {$ref: '#/components/schemas/S', format: x-link} + ContentLink: {$ref: '#/components/schemas/S', contentEncoding: base64} + TextLink: {allOf: [{$ref: '#/components/schemas/S'}, {format: int64}]} + TypedLink: {allOf: [{$ref: '#/components/schemas/S'}], type: integer} + LoopA: {allOf: [{$ref: '#/components/schemas/LoopB'}], maxLength: 2} + LoopB: {allOf: [{$ref: '#/components/schemas/LoopA'}], maxLength: 3} + E: {type: string, enum: [a, b]} + EF: {type: string, enum: [a, b], format: date} + EnumLink: {allOf: [{$ref: '#/components/schemas/E'}, {format: email}]} + Obj: {type: object} + Const: {type: string, const: a} + SN: {type: [string, 'null']} + Conjoined: {allOf: [{type: string}, {maxLength: 3}]} + ConjoinedText: {allOf: [{type: string}, {format: date-time}]} + ConjoinedContent: {allOf: [{type: string}, {contentEncoding: base64}, {contentMediaType: text/plain}]} + ConjoinedFormatMedia: {allOf: [{type: string}, {format: date-time}, {contentMediaType: text/plain}]} + ConjoinedMediaFormat: {allOf: [{contentMediaType: text/plain}, {format: date-time}, {type: string}]} + MixedLink: {allOf: [{$ref: '#/components/schemas/S'}, {type: string}, {format: date-time}, {contentMediaType: text/plain}]} + NoKind: {allOf: [{maxLength: 3}]} + TwoKinds: {allOf: [{type: string}, {type: integer}]} + ObjectKind: {allOf: [{type: object}]} + FalseConjunct: {allOf: [{type: string}, false]} +` + +// TestBesideRef_ReadsEachOutcome holds the reading of a format or content +// keyword beside a $ref to a scalar to each outcome its flat twin gives, a +// target read through each hop of its chain, and to none where the chain +// ends on no scalar or the keyword takes no part (keywordBesideRef). +func TestBesideRef_ReadsEachOutcome(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "$ref: '#/components/schemas/" + name + "'" } + uses := map[string]besideRefOutcome{ + "{" + ref("S") + ", format: x-fmt}": besideRefRestricts, + "{allOf: [{" + ref("S") + "}, {format: uuid}]}": besideRefConjunctIsPrincipal, + "{" + ref("SU") + ", format: uuid}": besideRefRestates, + "{" + ref("SX") + ", format: x-other}": besideRefRestates, + "{" + ref("I32") + ", format: int64}": besideRefRestates, + "{" + ref("SX") + ", format: x-fmt}": besideRefKept, + "{" + ref("D") + ", format: date-time}": besideRefKept, + "{" + ref("S") + ", contentEncoding: base64}": besideRefRestricts, + "{" + ref("B64") + ", contentEncoding: base64}": besideRefRestricts, + "{" + ref("SX") + ", contentEncoding: base64}": besideRefKept, + "{" + ref("I") + ", contentEncoding: base64}": besideRefNone, + "{" + ref("DT") + ", contentEncoding: base64}": besideRefConjunctIsPrincipal, + "{" + ref("SU") + ", contentEncoding: base64}": besideRefConjunctIsPrincipal, + "{" + ref("N64") + ", contentEncoding: base64}": besideRefConjunctIsPrincipal, + "{" + ref("TextLink") + ", contentEncoding: base64}": besideRefConjunctIsPrincipal, + "{" + ref("DT") + ", contentMediaType: text/plain}": besideRefRestricts, + "{" + ref("N64") + ", contentMediaType: text/plain}": besideRefKept, + "{" + ref("EncodedText") + ", contentEncoding: base64}": besideRefRestricts, + "{" + ref("EncodedText") + ", format: x-fmt}": besideRefKept, + "{allOf: [{" + ref("FormatLink") + "}, {format: uuid}]}": besideRefConjunctIsPrincipal, + "{" + ref("FormatLink") + ", format: x-other}": besideRefKept, + "{" + ref("ContentLink") + ", format: x-fmt}": besideRefKept, + "{" + ref("TextLink") + ", format: x-fmt}": besideRefKept, + "{" + ref("TypedLink") + ", format: uuid}": besideRefNone, + "{" + ref("LoopA") + ", format: uuid}": besideRefNone, + "{" + ref("S") + ", format: uuid, contentEncoding: b}": besideRefNone, + "{" + ref("E") + ", format: uuid}": besideRefKept, + "{" + ref("E") + ", format: email}": besideRefRestricts, + "{" + ref("SN") + ", format: x-fmt}": besideRefRestricts, + "{" + ref("Conjoined") + ", format: x-fmt}": besideRefRestricts, + "{allOf: [{" + ref("Conjoined") + "}, {format: uuid}]}": besideRefConjunctIsPrincipal, + "{" + ref("ConjoinedText") + ", contentEncoding: base64}": besideRefConjunctIsPrincipal, + "{" + ref("ConjoinedContent") + ", contentEncoding: base64}": besideRefRestricts, + "{" + ref("ConjoinedFormatMedia") + ", contentEncoding: base64}": besideRefConjunctIsPrincipal, + "{" + ref("ConjoinedMediaFormat") + ", contentEncoding: base64}": besideRefConjunctIsPrincipal, + "{" + ref("MixedLink") + ", format: x-fmt}": besideRefNone, + "{allOf: [{" + ref("S") + "}, {format: uuid}, {contentMediaType: text/plain}]}": besideRefNone, + "{" + ref("NoKind") + ", format: x-fmt}": besideRefNone, + "{" + ref("TwoKinds") + ", format: x-fmt}": besideRefNone, + "{" + ref("ObjectKind") + ", format: x-fmt}": besideRefNone, + "{" + ref("FalseConjunct") + ", format: x-fmt}": besideRefNone, + "{" + ref("E") + ", contentEncoding: base64}": besideRefNone, + "{" + ref("EnumLink") + ", format: email}": besideRefRestates, + "{" + ref("EnumLink") + ", format: uuid}": besideRefKept, + "{" + ref("EnumLink") + ", format: hostname}": besideRefKept, + "{" + ref("EF") + ", format: uuid}": besideRefNone, + "{" + ref("Obj") + ", format: uuid}": besideRefNone, + "{" + ref("Const") + ", format: uuid}": besideRefNone, + } + var spec strings.Builder + spec.WriteString(besideRefTargets) + names := map[string]string{} + i := 0 + for use := range uses { + name := fmt.Sprintf("Use%d", i) + names[name] = use + fmt.Fprintf(&spec, " %s: %s\n", name, use) + i++ + } + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", spec.String())) + for name, use := range names { + schema := StatedIn(lowerer, componentSchema(t, lowerer, name)) + read := besideRefOf(lowerer.Ctx, schema) + assert.Equal(t, uses[use], read.outcome, use) + content := "" + if read.outcome == besideRefRestricts && strings.Contains(use, "contentEncoding") { + content = "base64" + } + assert.Equal(t, content, RestrictionContentEncoding(lowerer.Ctx, schema), "%s: what the restriction carries", use) + } +} + +// TestBesideRef_AChainIsReadToItsBound holds the walk of a target's chain to +// maxScalarChainNodes schemas: within it a format beside the chain is chosen +// over its root, past it the chain is cut and read as ending on no scalar. The +// chain is counted whole, so a position nearer its end, read first, moves +// nothing. +func TestBesideRef_AChainIsReadToItsBound(t *testing.T) { + t.Parallel() + chain := func(hops int) string { + var builder strings.Builder + builder.WriteString(" F: {allOf: [{$ref: '#/components/schemas/C0'}, {format: uuid}]}\n") + builder.WriteString(" Mid: {allOf: [{$ref: '#/components/schemas/C1'}, {format: uuid}]}\n") + for i := range hops - 1 { + fmt.Fprintf(&builder, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}]}\n", i, i+1) + } + fmt.Fprintf(&builder, " C%d: {type: string}\n", hops-1) + return builder.String() + } + for _, hops := range []int{maxScalarChainNodes, maxScalarChainNodes + 1} { + want, cut := besideRefConjunctIsPrincipal, false + if hops > maxScalarChainNodes { + want, cut = besideRefNone, true + } + for _, order := range [][]string{{"F", "Mid"}, {"Mid", "F"}} { + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", chain(hops))) + reads := map[string]keywordBesideRef{} + for _, name := range order { + reads[name] = besideRefOf(lowerer.Ctx, StatedIn(lowerer, componentSchema(t, lowerer, name))) + } + assert.Equal(t, want, reads["F"].outcome, "%d schemas, read in order %v", hops, order) + assert.Equal(t, cut, reads["F"].cut, "%d schemas, read in order %v", hops, order) + assert.Equal(t, besideRefConjunctIsPrincipal, reads["Mid"].outcome, "%d schemas, read in order %v: Mid lands on one fewer", hops, order) + assert.False(t, reads["Mid"].cut, "%d schemas, read in order %v", hops, order) + } + } +} + +// TestBesideRefDecision_DecidesNothingWithoutItsPrincipal holds the decision +// to the conjunct the reading chooses: read without it, it decides nothing, so +// the choice proper does. +func TestBesideRefDecision_DecidesNothingWithoutItsPrincipal(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " S: {type: string}\n"+ + " F: {allOf: [{$ref: '#/components/schemas/S'}, {format: uuid}]}\n")) + schema := StatedIn(lowerer, componentSchema(t, lowerer, "F")) + comp := allOfEntries(lowerer.Ctx, schema, "") + admissionReader := newAdmissionReader(lowerer.Ctx) + conjuncts, _ := admissionReader.conjuncts(schema, comp, false) + require.Len(t, conjuncts, 3) + _, decided := besideRefDecision(lowerer.Ctx, schema, comp, conjuncts[:2]) + assert.False(t, decided, "the conjunct of the chosen format is no conjunct read") + _, decided = besideRefDecision(lowerer.Ctx, schema, comp, conjuncts) + assert.True(t, decided) +} + +// TestBesideRefDecision_AChosenContentEncodingReadsNoForm holds the twin +// reading of a contentEncoding chosen beside a $ref to a value read from the +// text to the string its flat twin admits: the content vocabulary names no +// format, so the conjunction's combined reading holds the target's form alone. +func TestBesideRefDecision_AChosenContentEncodingReadsNoForm(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " T: {type: string, format: date-time}\n"+ + " F: {allOf: [{$ref: '#/components/schemas/T'}, {contentEncoding: base64}]}\n")) + schema := StatedIn(lowerer, componentSchema(t, lowerer, "F")) + comp := allOfEntries(lowerer.Ctx, schema, "") + admissionReader := newAdmissionReader(lowerer.Ctx) + conjuncts, _ := admissionReader.conjuncts(schema, comp, false) + decided, ok := besideRefDecision(lowerer.Ctx, schema, comp, conjuncts) + require.True(t, ok) + spelled := make([]string, 0, len(decided.refinement.admittedTogether.forms)) + for _, form := range decided.refinement.admittedTogether.forms { + spelled = append(spelled, form.spelled) + } + assert.Equal(t, []string{"date-time"}, spelled) + assert.Equal(t, refContentEncodesText, decided.refinement.refChoiceReasons[0], "the $ref passed over sat beside the encoding") +} diff --git a/compilers/openapi/internal/schema/besideref_test.go b/compilers/openapi/internal/schema/besideref_test.go new file mode 100644 index 000000000..faba9c4de --- /dev/null +++ b/compilers/openapi/internal/schema/besideref_test.go @@ -0,0 +1,163 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// TestBesideRef_ContentBesideAnotherEncodingIsKeptAsAFormatIs holds the content +// vocabulary beside a $ref to a string carrying an Encoding of another name to +// the use of the reference keeping it, degraded, with one report at the +// position worded as a kept format's: the node is a Scalar, so no report says +// it holds no Encoding (docs/compilers/openapi.md#content-vocabulary). +func TestBesideRef_ContentBesideAnotherEncodingIsKeptAsAFormatIs(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " SX: {type: string, format: x-other}\n"+ + " Use: {$ref: '#/components/schemas/SX', contentEncoding: base64, contentMediaType: text/plain}\n")) + openapitest.RequireNoErrorDiags(t, diags) + use, ok := typeByName(doc, "Use").(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, use.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/SX"), use.Base.Target) + assert.Nil(t, use.Encoding) + for _, key := range []string{"openapi:contentEncoding", "openapi:contentMediaType"} { + entry, kept := use.Unmodeled[key] + require.True(t, kept, key) + assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason, key) + } + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Use") + assert.Contains(t, message, "no home for contentEncoding, contentMediaType declared beside it") + assert.NotContains(t, message, "no Encoding field") +} + +// TestBesideRef_ARestrictionOfANumberCarriesTheFormatAlone holds a format +// selecting no primitive beside a $ref to an integer, which takes no content, +// to a Scalar over the reference whose Encoding names the format alone. +func TestBesideRef_ARestrictionOfANumberCarriesTheFormatAlone(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " I: {type: integer}\n"+ + " Use: {$ref: '#/components/schemas/I', format: uuid}\n")) + openapitest.RequireNoErrorDiags(t, diags) + use, ok := typeByName(doc, "Use").(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, use.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/I"), use.Base.Target) + assert.Equal(t, &ir.Encoding{Name: "uuid"}, use.Encoding) + assert.Empty(t, use.Unmodeled) +} + +// TestBesideRef_AChainPastItsBoundIsReportedAtThePosition holds a format beside +// a $ref whose chain lands on more than maxScalarChainNodes schemas to one +// openapi/budget-exceeded error at each position writing one, in the allOf +// spelling and beside the $ref, where the format is not read against the +// chain's scalar; a position whose chain lands on one fewer reads it, the +// reference restricted, with no report (docs/compilers/openapi.md#allof-refinement). +func TestBesideRef_AChainPastItsBoundIsReportedAtThePosition(t *testing.T) { + t.Parallel() + assert.Equal(t, 1024, schema.MaxScalarChainLinks, "docs/compilers/openapi.md#allof-refinement says so") + var builder strings.Builder + builder.WriteString(" Use: {allOf: [{$ref: '#/components/schemas/C0'}, {format: x-fmt}]}\n") + builder.WriteString(" Beside: {$ref: '#/components/schemas/C0', format: x-fmt}\n") + builder.WriteString(" Within: {allOf: [{$ref: '#/components/schemas/C1'}, {format: x-fmt}]}\n") + for i := range schema.MaxScalarChainLinks { + fmt.Fprintf(&builder, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}]}\n", i, i+1) + } + fmt.Fprintf(&builder, " C%d: {type: string}\n", schema.MaxScalarChainLinks) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", builder.String())) + assert.Equal(t, []string{"/components/schemas/Beside", "/components/schemas/Use"}, + pointerStrings(openapitest.PointersOf(diags, diag.BudgetExceeded)), "one report at each position past the bound") + for _, diagnostic := range diags { + if diagnostic.Code == diag.BudgetExceeded { + assert.Equal(t, ir.SeverityError, diagnostic.Severity) + assert.Contains(t, diagnostic.Message, "more than 1024 schemas") + } + } + within, ok := typeByName(doc, "Within").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "Within")) + require.NotNil(t, within.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/C1"), within.Base.Target, "within the bound the reference is restricted") + assert.Equal(t, &ir.Encoding{Name: "x-fmt"}, within.Encoding) + use, ok := typeByName(doc, "Use").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "Use")) + if use.Base != nil { + assert.NotEqual(t, ir.TypeID("type/openapi/components/schemas/C0"), use.Base.Target, "past it the reference is not restricted") + } +} + +// TestBesideRef_AContentEncodingBesideATextRootIsTheEncodedString holds a +// contentEncoding beside a $ref to a scalar rooted at a value read from the +// text to its flat twin's reading: the string is that encoding's text, so the +// position is a Scalar over string under the encoding, the $ref kept as a +// beaten conjunct with one info saying so; without a contentEncoding the +// vocabulary restricts the reference, as the twin keeps the primitive +// (docs/compilers/openapi.md#content-vocabulary). +func TestBesideRef_AContentEncodingBesideATextRootIsTheEncodedString(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " T: {type: string, format: date-time}\n"+ + " Use: {$ref: '#/components/schemas/T', contentEncoding: base64, contentMediaType: text/plain}\n"+ + " Media: {$ref: '#/components/schemas/T', contentMediaType: text/plain}\n")) + openapitest.RequireNoErrorDiags(t, diags) + use, ok := typeByName(doc, "Use").(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, use.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), use.Base.Target, "the encoding's text") + assert.Equal(t, &ir.Encoding{Name: "base64", MediaType: "text/plain"}, use.Encoding) + require.Len(t, use.Unmodeled, 1) + assert.Equal(t, ir.ReasonDegradedLowering, use.Unmodeled["openapi:$ref"].Reason, "the beaten $ref is kept") + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Use") + assert.Contains(t, message, "that encoding's text") + media, ok := typeByName(doc, "Media").(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, media.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/T"), media.Base.Target, "a restriction of the reference") + assert.Equal(t, &ir.Encoding{MediaType: "text/plain"}, media.Encoding) + assert.Empty(t, media.Unmodeled) +} + +// TestBesideRef_ContentIsReadAcrossConjunctsAndTheTargetChain pins the +// Encoding the content vocabulary beside a $ref builds as its flat twin's: a +// contentEncoding chosen over a target read from the text takes the media +// type and content schema its target writes, the content schema the node the +// target's own lowering names; a restriction of a string takes the media type +// another conjunct or the target writes; and an entry's contentEncoding beside +// a target carrying another encoding is kept as a kept format is. +func TestBesideRef_ContentIsReadAcrossConjunctsAndTheTargetChain(t *testing.T) { + t.Parallel() + const ref = "$ref: '#/components/schemas/" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " S: {type: string}\n SX: {type: string, format: x-other}\n"+ + " SM: {type: string, contentMediaType: text/plain}\n"+ + " DTS: {type: string, format: date-time, contentMediaType: application/json, contentSchema: {type: object}}\n"+ + " Elected: {"+ref+"DTS', contentEncoding: base64}\n"+ + " Split: {allOf: [{"+ref+"S'}, {contentMediaType: text/plain}, {contentEncoding: base64}]}\n"+ + " Restricted: {"+ref+"SM', contentEncoding: base64}\n"+ + " Kept: {allOf: [{"+ref+"SX'}, {contentEncoding: base64}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + for name, want := range map[string]*ir.Encoding{ + "Elected": {Name: "base64", MediaType: "application/json", Schema: &ir.TypeRef{Target: "type/anonymous/components/schemas/DTS/contentSchema"}}, + "Split": {Name: "base64", MediaType: "text/plain"}, + "Restricted": {Name: "base64", MediaType: "text/plain"}, + } { + use, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, name) + assert.Equal(t, want, use.Encoding, name) + } + kept, ok := typeByName(doc, "Kept").(*ir.Scalar) + require.True(t, ok) + assert.Equal(t, ir.ReasonDegradedLowering, kept.Unmodeled["openapi:contentEncoding"].Reason) + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Kept/allOf/1") + assert.Contains(t, message, "no home for contentEncoding") + assert.NotContains(t, message, "no Encoding field") +} diff --git a/compilers/openapi/internal/schema/boundhomes.go b/compilers/openapi/internal/schema/boundhomes.go index bae7f86b9..39320a09c 100644 --- a/compilers/openapi/internal/schema/boundhomes.go +++ b/compilers/openapi/internal/schema/boundhomes.go @@ -5,105 +5,460 @@ package schema import ( "encoding/json/jsontext" + "slices" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/merge" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) // boundHomes says which bounds the position an allOf is written at has a field -// for, so that an entry writing one folds there: the value bounds that apply to -// a value of the kinds value (keywordKinds), and the collection bounds; and -// whether the node it owns carries a number as text, which holds none of an -// entry's value bounds (keepTextBounds). +// for, so that an entry writing one folds there: the value bounds of the kinds +// value (typeformat.InstanceKindsKeywordAppliesTo) and the collection bounds; +// those a value of text of another kind keeps verbatim (boundRoot); and what +// its builder reads off whichever conjunct writes it: the `items` group, the +// format and the content vocabulary. type boundHomes struct { value kindSet collection bool - numberText bool -} - -// reads returns the bounds schema writes that a node holding what h says reads, -// schema being the position's own schema or a folded entry of it: the value -// bounds of the kinds h.value names (boundsRead), and where h.collection holds, -// the collection bounds a field states, uniqueItems only where it holds it, -// true (referenceHolds). -func (h boundHomes) reads(schema *statement.Schema) keySet { - out := boundsRead(schema, h.value, nil) - if h.collection { - out |= collectionReads(schema) &^ keyBit("uniqueItems") - if referenceHolds(schema, "uniqueItems") { - out |= keyBit("uniqueItems") - } + // otherText is the value bounds the Scalar built for the position keeps + // verbatim, its value text of another kind (boundRoot.ownKept); heldText + // those the node or carrier holding the position's bounds over such a value + // keeps itself, which it reads; root what that text is of. + otherText, heldText keySet + root boundRoot + // textKeeps is the value bounds a type list's variant carrying text of another + // kind takes of its flattened entries, the intersected value kept + // (intersectTextBounds). + textKeeps keySet + // textYields is the list's own value bounds such a variant keeps a flattened + // entry's value of, or the value they intersect in, instead. + textYields keySet + // textIntersection is, of a Scalar carrying text of another kind, what its + // conjuncts of each value bound intersect in (intersectTextBounds): which + // writings the intersected value replaces, and the value no conjunct writes. + textIntersection textBoundIntersection + elements bool + format bool + content bool +} + +// reads returns the bounds schema writes that a node holding what homes says +// reads, schema being the position's own schema or a flattened entry of it. +func (homes boundHomes) reads(schema *statement.Schema) keySet { + out := homes.valueReads(schema) + if homes.collection { + out |= heldCollectionReads(schema) + } + return out +} + +// valueReads returns the value bounds schema writes that a node holding what +// homes says reads: those of the kinds homes.value names (boundsRead), and +// those it keeps itself, its value text of another kind (homes.heldText). +func (homes boundHomes) valueReads(schema *statement.Schema) keySet { + return boundsRead(schema, homes.value, nil) | keySetOf(writtenKept(schema, homes.heldText)...) +} + +// heldOver returns homes holding none of the bounds of a kind root marks as +// written as another value, keeping those itself (heldText), where admits is +// what the position admits. +func (homes boundHomes) heldOver(root boundRoot, admits kindSet) boundHomes { + homes.root, homes.heldText = root, root.heldKept(admits) + homes.value = root.heldTakes(homes.value) + return homes +} + +// heldCollectionReads returns the collection bounds of schema a field states, +// uniqueItems only where it holds it, true (referenceHolds). +func heldCollectionReads(schema *statement.Schema) keySet { + out := collectionReads(schema) &^ keyBit("uniqueItems") + if referenceHolds(schema, "uniqueItems") { + out |= keyBit("uniqueItems") } return out } -// homesAt returns which bounds the position s is written at, lowered to target, -// holds for its voices, as the keeping of unread keywords asks of those written -// beside its allOf. A carrier or an alias holds the value bounds the types the -// position admits take (boundKinds), and collection bounds where it is a use of -// the principal, a reference (referenceReads), where those types admit an -// array. A node the position owns holds what the lowering that builds it folds -// of them (ownHomes). +// homesAt returns which bounds the position schema, written at pointer and +// lowered to target, holds for its flattened entries, as the keeping of unread +// keywords beside its allOf asks. The alias a union kept beside a $ref +// principal needs (lowerBesideUnmodeledUnion) holds the value bounds alone; +// any other node the position owns, what its lowering folds (boundsHeldAt). func homesAt(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer) boundHomes { + refinement, refined := refinementOf(loweringContext, schema, pointer) + refPrincipal := refined && refinement.principal != nil && refinement.principal.schema.Ref != nil + if _, set := valueSetPrincipal(refinement); refined && set { + refPrincipal = false + } + referenced := loweringContext.Statements().Read(schema) + if refPrincipal { + referenced = refinement.principal.schema + } + if refPrincipal && LoweredToOwnNode(loweringContext, pointer, target) { + // That alias takes the value bounds alone; a collection bound is kept. + takes := boundKinds(loweringContext, schema) + return boundHomes{value: takes}.heldOver(boundRootOf(loweringContext, schema)|referentRoot(loweringContext, referenced), takes) + } if !LoweredToOwnNode(loweringContext, pointer, target) { - refinement, refined := refinementOf(loweringContext, schema, pointer) takes := boundKinds(loweringContext, schema) - return boundHomes{value: takes, collection: refined && refinement.principal != nil && takes&kindArray != 0} + inline := !refined || refinement.principal == nil || refinement.principal.schema.Ref == nil + kinds, _ := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) + homes := boundHomes{value: takes, collection: refined && refinement.principal != nil && takes&kindArray != 0, + format: inline && scalarKindsOnly(kinds)} + return homes.heldOver(targetRootOf(loweringContext, schema, target)|referentRoot(loweringContext, referenced), takes) } - return ownHomes(loweringContext, schema, pointer) + return boundsHeldAt(loweringContext, schema, pointer) +} + +// scalarKindsOnly reports whether kinds, null aside, are some kinds a Scalar +// holds and no other, so the node holding them is one. +func scalarKindsOnly(kinds kindSet) bool { + kinds &^= kindNull + return kinds != 0 && kinds&^primitiveKinds == 0 } -// ownHomes returns which bounds the node the refinement s, written at pointer, -// owns holds for the voices of its allOf: where an inline principal built it, -// that principal's (nodeHomes), none for a value set's or a $ref's, and -// otherwise what s's own dispatch builds. -func ownHomes(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) boundHomes { - takes := boundKinds(loweringContext, schema) - if refinement, refined := refinementOf(loweringContext, schema, pointer); refined && refinement.principal != nil { +// boundsHeldAt returns which bounds the node the position schema, written at +// pointer, owns holds for the flattenedEntries of its allOf: where an inline +// principal built it, that principal's (nodeHomes), none for a $ref's or a +// value set's but an enum's, and otherwise what schema's own dispatch builds. +func boundsHeldAt(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) boundHomes { + takes, root := boundKinds(loweringContext, schema), boundRootOf(loweringContext, schema)|referentRoot(loweringContext, loweringContext.Statements().Read(schema)) + refinement, refined := refinementOf(loweringContext, schema, pointer) + if refined && refinement.principal != nil { entry := refinement.principal - if _, set := valueSetPrincipal(refinement); set || entry.schema.Ref != nil { + if _, set := valueSetPrincipal(refinement); set && principalDispatch(*entry).lowered != "enum" || entry.schema.Ref != nil { return boundHomes{} } - return nodeHomes(loweringContext, entry.schema.Schema, principalDispatch(*entry), takes) + root |= referentRoot(loweringContext, entry.schema) + flattenedEntries := nodePlacement{position: schema, positionPointer: pointer}.flattenedEntries(loweringContext, entry.schema.Schema, entry.pointer) + contentConjuncts := contentConjuncts(entry.schema.Schema, entry.pointer, flattenedEntries) + if flatSpellingType := refinement.besideRef.flatSpellingTypeOf(entry.schema.Schema); flatSpellingType != "" { + return typingHomes(contentConjuncts, typingOfFlatSpelling(typingOf(loweringContext, entry.schema.Schema), flatSpellingType), takes) + } + principal := principalDispatch(*entry) + homes := nodeHomes(loweringContext, entry.schema.Schema, contentConjuncts, principal, takes, heldRoot(loweringContext, refinement, schema, pointer, principal, root)) + return unionHomes(loweringContext, schema, withTextIntersection(loweringContext, homes, entry.schema.Schema, flattenedEntries), takes) } dispatch, _ := dispatchAt(loweringContext, schema, pointer) - return nodeHomes(loweringContext, schema, dispatch, takes) -} - -// nodeHomes returns which bounds the node s lowers to by the dispatch d holds, -// as its builder reads them of the voices, takes the kinds its position -// admits: none of a value set's, the value bounds of the types a Scalar built -// for each type its lowering names (typingOf) takes, the collection bounds of -// an array's List or Tuple, a type list's variant's among them, a union's of -// oneOf or anyOf the value bounds alone, and none of an object's, which -// lowerModel builds with no voice. -func nodeHomes(loweringContext lowering.Ctx, schema *statement.Schema, dispatchValue dispatch, takes kindSet) boundHomes { - if dispatchValue.won == "const" || dispatchValue.won == "enum" { - return boundHomes{} + if refined && refinement.sharesNoMember && dispatch.lowered == "" { + return boundHomes{} // the closed empty Enum of $ref sets (lowerRefSets) } - if declaresUnion(schema) { - return boundHomes{value: takes} + flattenedEntries := positionFlattenedEntries(loweringContext, schema, pointer, ir.TypeRef{}) + homes := nodeHomes(loweringContext, schema, contentConjuncts(schema, pointer, flattenedEntries), dispatch, takes, + heldRoot(loweringContext, refinement, schema, pointer, dispatch, root)) + return unionHomes(loweringContext, schema, withTextIntersection(loweringContext, homes, schema, flattenedEntries), takes) +} + +// unionHomes returns homes, those of the node the position schema lowers to, +// where that node is the Union its conjunction chooses (unionNodeRoot), +// whichever schema is its principal: the value bounds of the kinds takes names +// that no variant's root marks (heldOver). +func unionHomes(loweringContext lowering.Ctx, schema *statement.Schema, homes boundHomes, takes kindSet) boundHomes { + root, union := unionNodeRoot(loweringContext, schema) + if !union { + return homes } - typing := typingOf(loweringContext, schema) - if typing.top() { - return boundHomes{value: takes} + homes.value = takes + return homes.heldOver(root, takes) +} + +// heldRoot returns the boundRoot of the node the position schema builds by +// dispatchValue: an enum's ValueType's, as its build reads it +// (valueSetSite.homesOf), and any other's root. +func heldRoot(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, pointer jsontext.Pointer, + dispatchValue dispatch, root boundRoot, +) boundRoot { + if dispatchValue.lowered == "enum" { + return valueSetRootAt(loweringContext, refinementValue, schema, pointer) } - var homes boundHomes - for _, st := range typing.types { - switch st { - case statement.KindObject: - case statement.KindArray: - homes.collection = true - default: - // A type list's variant takes the format only where no other listed - // type pairs with it (variantFormat), as lowerTypeVariant builds it. - if carriesText(schema, st, variantFormat(schema, st, typing.types)) { - homes.numberText = true + return root +} + +// withTextIntersection returns homes, those of the node principal builds, +// holding what it takes of the bounds flattenedEntries write where it carries +// text of another kind (intersectTextBounds): a type list's variant every bound +// they intersect in, which it keeps itself, and a Scalar the intersection. +func withTextIntersection(loweringContext lowering.Ctx, homes boundHomes, principal *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry) boundHomes { + if homes.otherText == 0 { + return homes + } + text := intersectTextBounds(loweringContext, principal, flattenedEntries, homes.otherText) + if len(effectiveTypes(principal)) > 1 { + homes.textKeeps = text.intersected + return homes + } + if text.intersected != 0 { + homes.textIntersection = text + } + return homes +} + +// consumedFrom returns the value bounds schema writes whose writing the value +// t's conjuncts intersect in replaces. +func (t textBoundIntersection) consumedFrom(schema *statement.Schema) keySet { + var out keySet + for keyword, conjunctList := range t.consumed { + if slices.Contains(conjunctList, schema) { + out |= keyBit(keyword) + } + } + return out +} + +// textBoundIntersection is what a node carrying text of another kind takes of +// the value bounds its own schema, the list, and its flattened entries write +// (intersectTextBounds): those whose conjuncts intersect, the list's a value it +// does not write replaces, the flattened entry each is kept from where one +// writes the value, the value they intersect in where none does, and each +// conjunct stating a value the intersected one replaces. +type textBoundIntersection struct { + intersected keySet + yields keySet + kept map[string]int + values map[string]ir.RawValue + consumed map[string][]*statement.Schema +} + +// keep keeps on unmodeled, of a type list's variant written at pointer over +// root, each bound whose intersected value t keeps from one of flattenedEntries +// or keeps itself, and returns the reports (keepTextBounds, +// keepIntersectedTextBound). +func (t textBoundIntersection) keep(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer, + root boundRoot, +) []ir.Diagnostic { + var diags []ir.Diagnostic + for i, flattenedEntry := range flattenedEntries { + bounds := slices.DeleteFunc(declaredConstraints(flattenedEntry.Node), func(keyword string) bool { + owner, kept := t.kept[keyword] + return !kept || owner != i + }) + diags = append(diags, keepTextBounds(loweringContext, unmodeled, flattenedEntry.Node, bounds, pointer, root)...) + } + for _, keyword := range valueConstraintKeywords { + if value, intersected := t.values[keyword]; intersected { + diags = append(diags, keepIntersectedTextBound(loweringContext, unmodeled, keyword, value, pointer, root)...) + } + } + return diags +} + +// boundConjunct is where a conjunct of a bound a node carrying text of another +// kind intersects is (intersectTextBounds): listConjunct, noConjunct, or the +// index of a flattened entry among the flattened entries the node is read +// beside. +type boundConjunct int + +const ( + // listConjunct is the list, the schema whose node carries the text. + listConjunct boundConjunct = -1 + // noConjunct is where the conjuncts intersect in a value none of them writes. + noConjunct boundConjunct = -2 +) + +// flattenedEntryIndex returns the index of the flattened entry owner is, and +// false where owner is listConjunct or noConjunct. +func (owner boundConjunct) flattenedEntryIndex() (int, bool) { + return int(owner), owner >= 0 +} + +// intersectionWriting is the writing of a bound its conjuncts intersect in: the +// conjunct, or noConjunct and the value, and each other conjunct stating a +// value, which the intersected one replaces. +type intersectionWriting struct { + value ir.RawValue + consumed []boundConjunct + owner boundConjunct +} + +// intersectTextBounds returns what a node carrying text of another kind takes +// of the value bounds of keys that list and flattenedEntries write (#2117). +// The conjuncts of each bound intersect as any bound's do (boundReading), and +// the node keeps the writing of the value they intersect in, or that value +// where none writes it, as two steps intersect in their common multiple. +// Conjuncts intersecting in none, two patterns, give none, and the position +// keeps them. +func intersectTextBounds(loweringContext lowering.Ctx, list *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, keys keySet) textBoundIntersection { + out := textBoundIntersection{kept: map[string]int{}, values: map[string]ir.RawValue{}, consumed: map[string][]*statement.Schema{}} + listBounds := writtenBounds(loweringContext, list) + flattenedEntryBounds := make([]*ir.Constraints, len(flattenedEntries)) + for i, flattenedEntry := range flattenedEntries { + flattenedEntryBounds[i] = writtenBounds(loweringContext, flattenedEntry.Node) + } + for _, keyword := range valueConstraintKeywords { + if !keys.has(keyword) { + continue + } + intersection, ok := intersectionConjunct(loweringContext, keyword, list, listBounds, flattenedEntries, flattenedEntryBounds) + if !ok { + continue + } + out.intersected |= keyBit(keyword) + for _, owner := range intersection.consumed { + flattenedEntryIndex, isFlattenedEntry := owner.flattenedEntryIndex() + if !isFlattenedEntry { + // A consumed conjunct states a value: the list, never noConjunct. + out.yields |= keyBit(keyword) + out.consumed[keyword] = append(out.consumed[keyword], list) continue } - homes.value |= takes & typeKinds(st) + out.consumed[keyword] = append(out.consumed[keyword], flattenedEntries[flattenedEntryIndex].Node) + } + flattenedEntryIndex, isFlattenedEntry := intersection.owner.flattenedEntryIndex() + switch { + case isFlattenedEntry: + out.kept[keyword] = flattenedEntryIndex + case intersection.owner == noConjunct: + out.values[keyword] = intersection.value + default: // the list's own writing, which the node keeps itself + } + } + return out +} + +// intersectionConjunct returns the writing of keyword that list and +// flattenedEntries intersect in: the first writing the value they intersect +// in, the list's before a flattened entry's, or that value where none writes +// it; false where no flattened entry writes keyword or no one value holds what +// they write. A conjunct stating no value, one the reading refused, intersects +// none and is consumed by none. +func intersectionConjunct(loweringContext lowering.Ctx, keyword string, list *statement.Schema, listBounds *ir.Constraints, + flattenedEntries []annotation.FlattenedAllOfEntry, flattenedEntryBounds []*ir.Constraints, +) (intersectionWriting, bool) { + var reading boundReading + var owners, stating []boundConjunct + read := func(owner boundConjunct, schema *statement.Schema, bounds *ir.Constraints) { + owners = append(owners, owner) + if own := ownBound(loweringContext, schema, keyword, bounds); own != (ir.Constraints{}) { + reading.add(own) + stating = append(stating, owner) + } + } + if hasKey(list, keyword) { + read(listConjunct, list, listBounds) + } + for i, flattenedEntry := range flattenedEntries { + if slices.Contains(declaredConstraints(flattenedEntry.Node), keyword) { + read(boundConjunct(i), flattenedEntry.Node, flattenedEntryBounds[i]) + } + } + switch { + case !slices.ContainsFunc(owners, func(owner boundConjunct) bool { + _, isFlattenedEntry := owner.flattenedEntryIndex() + return isFlattenedEntry + }): + return intersectionWriting{}, false + case len(owners) == 1: + return intersectionWriting{owner: owners[0]}, true // one flattened entry alone, kept as written + case !reading.valuesIntersect() || reading.intersection == nil: + return intersectionWriting{}, false + } + for _, owner := range stating { + schema, bounds := list, listBounds + if flattenedEntryIndex, isFlattenedEntry := owner.flattenedEntryIndex(); isFlattenedEntry { + schema, bounds = flattenedEntries[flattenedEntryIndex].Node, flattenedEntryBounds[flattenedEntryIndex] } + if own := ownBound(loweringContext, schema, keyword, bounds); merge.SameConstraints(&own, reading.intersection) { + others := slices.DeleteFunc(slices.Clone(stating), func(other boundConjunct) bool { return other == owner }) + return intersectionWriting{owner: owner, consumed: others}, true + } + } + value, ok := boundValue(keyword, *reading.intersection) + return intersectionWriting{value: value, owner: noConjunct, consumed: stating}, ok +} + +// boundValue returns the multipleOf cons, the conjuncts' multipleOf +// intersected, holds, and false for any other keyword: an intersected bound, +// count or pattern is one conjunct's value, which intersectionConjunct takes +// before asking, or holds both fields of a pair, which no one keyword states. +func boundValue(keyword string, cons ir.Constraints) (ir.RawValue, bool) { + if keyword != "multipleOf" || cons.MultipleOf == nil { + return nil, false + } + return ir.RawValue(*cons.MultipleOf), true +} + +// ownBound returns the fields of bounds, what schema writes, the bound keyword +// fills on its own: boundOf's, but where schema's dialect spells an exclusive +// bound as a number, a minimum and an exclusiveMinimum fill a field each, and +// the maximum's likewise. +func ownBound(loweringContext lowering.Ctx, schema *statement.Schema, keyword string, bounds *ir.Constraints) ir.Constraints { + paired := boundOf(keyword, bounds) + if exclusiveIsBoolean(loweringContext, schema) { + return paired + } + switch keyword { + case "minimum", "maximum": + return ir.Constraints{Min: paired.Min, Max: paired.Max} + case "exclusiveMinimum", "exclusiveMaximum": + return ir.Constraints{ExclusiveMin: paired.ExclusiveMin, ExclusiveMax: paired.ExclusiveMax} + default: + return paired + } +} + +// nodeHomes returns which bounds the node schema lowers to by dispatchValue +// holds, takes being the kinds its position admits. A union holds the value +// bounds where it is the node, none beside it (hasUnionSiblings), and an enum +// or a union holds none of a kind root marks (heldOver). +func nodeHomes(loweringContext lowering.Ctx, schema *statement.Schema, contentConjuncts contentWriting, dispatchValue dispatch, takes kindSet, root boundRoot) boundHomes { + switch dispatchValue.lowered { + case "const": + return boundHomes{} + case "enum": + listed := takes & listedKinds(loweringContext, schema) + return boundHomes{value: listed}.heldOver(root, listed) + default: + } + if declaresUnion(schema) && !hasUnionSiblings(loweringContext, schema) { + return boundHomes{value: takes}.heldOver(root, takes) + } + return typingHomes(contentConjuncts, typingOf(loweringContext, schema), takes) +} + +// typingHomes returns the boundHomes held by a node built for typingValue, +// conjuncts writing the format and the contentEncoding it takes, where the +// enclosing position admits takes. +func typingHomes(contentConjuncts contentWriting, typingValue typing, takes kindSet) boundHomes { + if typingValue.top() { + return boundHomes{value: takes} + } + var homes boundHomes + for _, typeName := range typingValue.types { + typeHomes := typeHome(contentConjuncts, typeName, typingValue.types, takes) + homes.value |= typeHomes.value + homes.collection = homes.collection || typeHomes.collection + homes.otherText |= typeHomes.otherText + homes.root |= typeHomes.root + homes.elements = homes.elements || typeHomes.elements + homes.format = homes.format || typeHomes.format + homes.content = homes.content || typeHomes.content } return homes } + +// typeHome returns the boundHomes for one declared or inferred type typeName +// among types, conjuncts writing the format and the contentEncoding the node +// takes, whichever conjunct writes each, where the enclosing position admits +// takes. +func typeHome(contentConjuncts contentWriting, typeName statement.JSONSchemaTypeName, types []statement.JSONSchemaTypeName, takes kindSet) boundHomes { + switch typeName { + case statement.KindObject: + return boundHomes{value: modelTakes(takes)} + case statement.KindArray: + return boundHomes{collection: true, elements: true} + default: + // A type list's variant takes the format only where no other listed + // type pairs with it (variantFormat), as lowerTypeVariant builds it. + content := contentConjuncts.encoding.Node + root := shapeBoundRoot(content, typeName, scalarShapeOf(content, typeName, variantFormat(writtenFormat(contentConjuncts.format.Node), typeName, types))) + if root == rootIsValue { + return boundHomes{value: takes & kindsOfTypeNameOrAny(typeName), format: true, content: takesContent(kindsOfTypeNameOrAny(typeName))} + } + // Its instances are written as a value of another kind, whose bounds + // it keeps; a number written as text takes no content vocabulary. + return boundHomes{otherText: root.ownKept(), root: root, value: root.heldTakes(takes & kindsOfTypeNameOrAny(typeName)), format: true, + content: root&rootTextOfNumber == 0 && takesContent(kindsOfTypeNameOrAny(typeName))} + } +} diff --git a/compilers/openapi/internal/schema/boundhomes_test.go b/compilers/openapi/internal/schema/boundhomes_test.go index 42945237f..5f65eb365 100644 --- a/compilers/openapi/internal/schema/boundhomes_test.go +++ b/compilers/openapi/internal/schema/boundhomes_test.go @@ -4,6 +4,8 @@ package schema_test import ( + "maps" + "slices" "testing" "github.com/google/go-cmp/cmp" @@ -18,29 +20,27 @@ import ( // allOf entry writes land on the node the position owns where no entry decides // what it lowers to, and which are kept verbatim: each is read off what builds // the node, the position's types, and never off the node it built. A union of -// types holds a value bound in the node built for the type that takes it, and -// none of an object's, which the model of a type list builds with no voice, so -// a bound written for an object there is kept rather than dropped. +// types holds a value bound in the node built for the type that takes it, an +// object's in the model, which reads the type list's flattened entries, as +// written flat. func TestRefinement_AnOwnedNodeHoldsTheBoundsItsLoweringFolds(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string kept []string // the keywords kept verbatim on the position's own node holder string // the node its folded bounds land on, if not the position's min string // the bound that folds there, by Constraints field }{ - "object variant takes no voice": { + "object variant takes a conjunct's bound": { schema: "{type: [object, array], minProperties: 1, allOf: [{maxProperties: 2}]}", - kept: []string{"openapi:maxProperties"}, + holder: "/type/0", min: "maxProperties", }, - "string variant takes its own bound, an object's is kept": { + "string variant takes its own bound, the object variant an object's": { schema: "{type: [object, string], allOf: [{minProperties: 2, minLength: 2}]}", - kept: []string{"openapi:minProperties"}, - holder: "/type/1", min: "minLength", + holder: "/type/0", min: "minProperties", }, - "array variant takes a collection bound": { + "array variant takes a collection bound, the object variant an object's": { schema: "{type: [object, array], allOf: [{maxItems: 3, minProperties: 2}]}", - kept: []string{"openapi:minProperties"}, holder: "/type/1", min: "maxItems", }, "no type to build for lowers to the top type's alias, which holds every bound": { @@ -49,29 +49,35 @@ func TestRefinement_AnOwnedNodeHoldsTheBoundsItsLoweringFolds(t *testing.T) { min: "minLength", }, } { - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " X: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " X: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, validated(t, doc), name) - kept := make([]string, 0, len(tc.kept)) + kept := make([]string, 0, len(testCase.kept)) for key := range typeByName(doc, "X").Common().Unmodeled { kept = append(kept, key) } - assert.ElementsMatch(t, tc.kept, kept, "%s: what the position keeps", name) + assert.ElementsMatch(t, testCase.kept, kept, "%s: what the position keeps", name) - if tc.min == "" { + if testCase.min == "" { continue } holder := componentID("X") - if tc.holder != "" { - holder = ir.TypeID("type/anonymous/components/schemas/X" + tc.holder) + if testCase.holder != "" { + holder = ir.TypeID("type/anonymous/components/schemas/X" + testCase.holder) } cons := constraintsOf(t, doc.Types[holder]) require.NotNil(t, cons, name) - switch tc.min { + switch testCase.min { case "minLength": require.NotNil(t, cons.MinLength, name) assert.EqualValues(t, 2, *cons.MinLength, name) + case "minProperties": + require.NotNil(t, cons.MinProperties, name) + assert.EqualValues(t, 2, *cons.MinProperties, name) + case "maxProperties": + require.NotNil(t, cons.MaxProperties, name) + assert.EqualValues(t, 2, *cons.MaxProperties, name) default: require.NotNil(t, cons.MaxItems, name) assert.EqualValues(t, 3, *cons.MaxItems, name) @@ -79,16 +85,19 @@ func TestRefinement_AnOwnedNodeHoldsTheBoundsItsLoweringFolds(t *testing.T) { } } -// constraintsOf returns the Constraints of td, a Scalar or a List. -func constraintsOf(t *testing.T, td ir.TypeDef) *ir.Constraints { +// constraintsOf returns the Constraints of typeDef, a Scalar, a List or a +// Model. +func constraintsOf(t *testing.T, typeDef ir.TypeDef) *ir.Constraints { t.Helper() - switch n := td.(type) { + switch n := typeDef.(type) { case *ir.Scalar: return n.Constraints case *ir.List: return n.Constraints + case *ir.Model: + return n.Constraints default: - require.Failf(t, "no constraints", "got %T", td) + require.Failf(t, "no constraints", "got %T", typeDef) return nil } } @@ -98,16 +107,16 @@ func constraintsOf(t *testing.T, td ir.TypeDef) *ir.Constraints { // list for an array's keywords, and a union of an object's and an array's. func TestRefinement_AnOwnedNodeOfAnUntypedShapeKeepsNothingItHolds(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string kind ir.TypeKind }{ "array": {"{items: {type: string}, allOf: [{description: d}]}", ir.KindList}, "object, array": {"{properties: {a: {type: string}}, items: {type: string}, allOf: [{description: d}]}", ir.KindUnion}, } { - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " X: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " X: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) - assert.Equal(t, tc.kind, typeByName(doc, "X").Kind(), name) + assert.Equal(t, testCase.kind, typeByName(doc, "X").Kind(), name) assert.Empty(t, typeByName(doc, "X").Common().Unmodeled, name) } } @@ -133,3 +142,31 @@ func TestRefinement_AnOwnedNodeHoldsTheSameWhicheverIsDeclaredFirst(t *testing.T assert.Empty(t, cmp.Diff(first.Types, second.Types), name) } } + +// TestRefinement_ABodyBesideAKeptUnionHoldsTheBoundsItsEntriesFold pins that an +// array written beside a oneOf kept verbatim holds the bound its allOf entry +// writes as it holds one written beside its type, at 3.0 as at 3.1: in its +// constraints alone, with nothing kept but the union and no finding but the +// union's. The union holds no bound, so the body's own types decide where its +// entries' bounds land. +func TestRefinement_ABodyBesideAKeptUnionHoldsTheBoundsItsEntriesFold(t *testing.T) { + t.Parallel() + const union = "oneOf: [{items: {maxLength: 2}}, {minItems: 4}]" + for name, schema := range map[string]string{ + "on an allOf entry": "{type: array, uniqueItems: true, items: {type: string}, " + union + ", allOf: [{maxItems: 9}]}", + "beside its own type": "{type: array, uniqueItems: true, maxItems: 9, items: {type: string}, " + union + "}", + } { + for _, version := range []string{"3.0.3", "3.1.0"} { + at := name + " at " + version + doc, diags := parseFull(t, openapitest.ComponentSpecVer(version, " F: "+schema+"\n")) + assert.Equal(t, []string{`info openapi/validation-only-keyword /components/schemas/F: validation-only keyword "oneOf" kept verbatim under Unmodeled`}, + reported(diags), at) + assert.Empty(t, validated(t, doc), at) + require.Equal(t, string(ir.ReasonValidationOnly), unionReading(doc, "F"), "%s: the union is kept verbatim", at) + assert.Equal(t, []string{"openapi:oneOf"}, slices.Sorted(maps.Keys(typeByName(doc, "F").Common().Unmodeled)), at) + cons := constraintsOf(t, typeByName(doc, "F")) + require.NotNil(t, cons, at) + assert.Equal(t, ir.Constraints{MaxItems: new(int64(9)), UniqueItems: true}, *cons, at) + } + } +} diff --git a/compilers/openapi/internal/schema/boundroot.go b/compilers/openapi/internal/schema/boundroot.go new file mode 100644 index 000000000..4314fe0d7 --- /dev/null +++ b/compilers/openapi/internal/schema/boundroot.go @@ -0,0 +1,316 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "cmp" + "encoding/json/jsontext" + "slices" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// boundRoot marks each kind whose instances at a node are the written form of a +// value of another kind, as the root its chain ends on reads them +// (docs/ir/constraints.md#constraints). A bound binds only the kind its node's +// value is, so a holder keeps verbatim a bound of a marked kind. +type boundRoot uint8 + +// rootIsValue marks no kind: every string and number instance is the value +// itself. +const rootIsValue boundRoot = 0 + +const ( + // rootTextOfValue marks string instances that are the text of a value of + // another kind, such as an instant or bytes written as base64. + rootTextOfValue boundRoot = 1 << iota + // rootTextOfNumber marks string instances that are a number's text. + rootTextOfNumber + // rootNumberOfValue marks number instances that are the written form of a + // value of another kind: an instant's seconds since the epoch. + rootNumberOfValue +) + +// textBoundKeys are the value bounds of a string instance, its length and its +// pattern (typeformat.InstanceKindsKeywordAppliesTo), and numericBoundKeys those of a number. +var ( + textBoundKeys = boundKeysOf(kindString) + numericBoundKeys = boundKeysOf(kindNumber) +) + +// boundKeysOf returns the value bounds applying to a value of one of kinds. +func boundKeysOf(kinds kindSet) keySet { + var out keySet + for _, keyword := range valueConstraintKeywords { + if taken(kinds, keyword) { + out |= keyBit(keyword) + } + } + return out +} + +// shapeBoundRoot returns the boundRoot of a Scalar of type typeName over shape, +// content writing the contentEncoding beside it. Bytes no encoding writes are +// their own value: a length counts their octets. +func shapeBoundRoot(content *statement.Schema, typeName statement.JSONSchemaTypeName, shape scalarShape) boundRoot { + switch { + case typeName == statement.KindInteger || typeName == statement.KindNumber: + if shape.wire != nil { + return rootNumberOfValue + } + return rootIsValue + case typeName != statement.KindString: + return rootIsValue + case shape.wire == nil && shape.base == ir.PrimitiveString, + shape.wire == nil && shape.base == ir.PrimitiveBytes && shape.format == "" && content.TextKeywords().ContentEncoding == "": + return rootIsValue + case shape.format == numberTextEncoding && shape.wire != nil: + return rootTextOfNumber + default: + return rootTextOfValue + } +} + +// settledRoot returns the boundRoot of the node the reading a, of the +// statement whose own schema is own, lowers to. It reads the format and the +// contentEncoding whichever conjunct writes each, as the build does +// (contentConjuncts). +func (a admitted) settledRoot(own *statement.Schema) boundRoot { + if a.fixed || !a.typed { + return a.marks + } + return a.marks | formRoot(cmp.Or(a.content, own), a.settledFormat(), a.types) +} + +// settledFormat returns the format the Scalar a's conjunction lowers to takes, +// chosen as formatConjunct chooses one among conjuncts. +func (a admitted) settledFormat() string { + var chosenConjunct *statement.Schema + for _, form := range a.forms { + if chosenConjunct == nil || narrowerFormat(form.conjunctSchema, chosenConjunct) { + chosenConjunct = form.conjunctSchema + } + } + if chosenConjunct == nil { + return "" + } + return writtenFormat(chosenConjunct) +} + +// formRoot returns the boundRoot of the Scalars a schema of the types kinds +// names lowers to with format, content writing the contentEncoding, each type +// taking the format its variant would (variantFormat). +func formRoot(content *statement.Schema, format string, kinds kindSet) boundRoot { + types := scalarTypesOf(kinds) + var out boundRoot + for _, typeName := range types { + out |= shapeBoundRoot(content, typeName, scalarShapeOf(content, typeName, variantFormat(format, typeName, types))) + } + return out +} + +// scalarTypesOf returns the types of the string and number instances kinds +// names: a string, and a number, or an integer where no fraction is named. +func scalarTypesOf(kinds kindSet) []statement.JSONSchemaTypeName { + var out []statement.JSONSchemaTypeName + if kinds&kindString != 0 { + out = append(out, statement.KindString) + } + switch { + case kinds&kindFraction != 0: + out = append(out, statement.KindNumber) + case kinds&kindInteger != 0: + out = append(out, statement.KindInteger) + } + return out +} + +// writtenTypes reports whether schema writes a `type`, and the kinds it +// names, null aside (effectiveTypes): a word no dialect defines names none. +func writtenTypes(schema *statement.Schema) (bool, kindSet) { + if !writesType(schema) { + return false, 0 + } + var out kindSet + for _, jsonSchemaTypeName := range effectiveTypes(schema) { + out |= kindsOfTypeName(jsonSchemaTypeName) + } + return true, out +} + +// primitiveRoot returns the boundRoot of a value an Enum's ValueType or a +// Literal types as primitive. +func primitiveRoot(primitive ir.PrimitiveKind) boundRoot { + if slices.Contains(valuePrimitives, primitive) { + return rootTextOfValue + } + return rootIsValue +} + +// writtenSetRoot returns the boundRoot of the node the value set schema writes +// lowers to, as schema's own keywords type it, and false where it writes none +// or a member converts to no value (valueSet). A conjunct's format narrowing the +// ValueType is read by a reader of a reference to the set (referentRoot). +func writtenSetRoot(loweringContext lowering.Ctx, schema *statement.Schema) (boundRoot, bool) { + members, enum := schema.Enum(), enumWritten(schema) + switch { + case enum && !loweringContext.Limits.MaxEnumMembers.Admits(len(members)): + return rootIsValue, true + case !enum && schema.Const() == nil: + return rootIsValue, false + case !enum: + members = []*yaml.Node{schema.Const()} + } + entries := slices.DeleteFunc(readEnum(members, ""), enumEntry.isNull) + if slices.ContainsFunc(entries, func(entry enumEntry) bool { return entry.err != nil }) { + return rootIsValue, false + } + if primitive, one := enumMemberPrimitive(entries); one && enum { + fits := func(primitiveKind ir.PrimitiveKind) bool { return entriesAre(entries, primitiveKind) } + return primitiveRoot(enumValueType(schema, fits, primitive)), true + } + var out boundRoot + for _, entry := range entries { + out |= primitiveRoot(literalValueType(schema, entry.val)) + } + return out, true +} + +// valueSetNodeRoot returns the boundRoot of typeDef, the node a value set +// listing entries lowered to at site. +func valueSetNodeRoot(loweringContext lowering.Ctx, site valueSetSite, typeDef ir.TypeDef, entries []enumEntry) boundRoot { + switch node := typeDef.(type) { + case *ir.Enum: + return primitiveRoot(node.ValueType) + case *ir.Union: + var out boundRoot + for _, entry := range entries { + if entry.err == nil && !entry.isNull() { + out |= primitiveRoot(site.memberSite(entry.at).literalType(loweringContext, entry.val)) + } + } + return out + default: + return rootIsValue + } +} + +// valueSetRootAt returns the boundRoot of the node the value set of +// refinementValue's position schema, written at pointer, lowers to, read from +// the source alone as its build types it. +func valueSetRootAt(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, pointer jsontext.Pointer) boundRoot { + if primitive, typed := refinedValueType(loweringContext, refinementValue, schema, pointer).valueType(); typed { + return primitiveRoot(primitive) + } + set := schema + if entry, ok := valueSetPrincipal(refinementValue); ok { + set = entry.schema.Schema + } + root, _ := writtenSetRoot(loweringContext, set) + return root +} + +// marksText reports whether r marks string instances as the text of a value of +// another kind or of a number. +func (r boundRoot) marksText() bool { + return r&(rootTextOfValue|rootTextOfNumber) != 0 +} + +// ownKept returns the value bounds the Scalar a position builds over r keeps +// verbatim. Beside a number written as text it keeps every one: none bounds the +// number its Constraints speak of. +func (r boundRoot) ownKept() keySet { + if r&rootTextOfNumber != 0 { + return keySetOf(valueConstraintKeywords...) + } + var out keySet + if r&rootTextOfValue != 0 { + out |= textBoundKeys + } + if r&rootNumberOfValue != 0 { + out |= numericBoundKeys + } + return out +} + +// heldKept returns the value bounds a node or carrier over r, holding the +// bounds of the kinds admits, keeps verbatim itself. A number written as text +// keeps its numeric bounds only where no number instance takes them. +func (r boundRoot) heldKept(admits kindSet) keySet { + var out keySet + if r.marksText() { + out |= textBoundKeys + } + if r&rootNumberOfValue != 0 || r&rootTextOfNumber != 0 && admits&kindNumber == 0 { + out |= numericBoundKeys + } + return out +} + +// heldTakes returns the kinds of admits whose bounds a holder over r holds: +// none of a kind r marks. +func (r boundRoot) heldTakes(admits kindSet) kindSet { + if r.marksText() { + admits &^= kindString + } + if r&rootNumberOfValue != 0 { + admits &^= kindNumber + } + return admits +} + +// boundRootOf returns the boundRoot of the instances the position schema +// admits, read from the schemas its reading takes in (admission), so it holds +// before a referent's node is built. Where schema writes no bound +// (writesBound), nothing asks, and it reads as the value. +func boundRootOf(loweringContext lowering.Ctx, schema *statement.Schema) boundRoot { + if !stated(schema) || !writesBound(loweringContext, schema) { + return rootIsValue + } + return admissionOf(loweringContext, loweringContext.Statements().Read(schema)).admitted.root +} + +// valuePrimitives are the shared primitives whose value a string is the text +// of: an instant, a date, a time, a duration, a url and a uuid. +var valuePrimitives = []ir.PrimitiveKind{ + ir.PrimitiveDate, ir.PrimitiveTime, ir.PrimitiveDatetime, ir.PrimitiveDatetimeOffset, ir.PrimitiveDuration, + ir.PrimitiveURL, ir.PrimitiveUUID, +} + +// targetRootOf returns the boundRoot of a position schema lowered to target. A +// shared primitive is read off target, as the lowering selected it whichever +// conjunct wrote the format. +func targetRootOf(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef) boundRoot { + if slices.ContainsFunc(valuePrimitives, func(primitiveKind ir.PrimitiveKind) bool { return target.Target == ir.PrimitiveTypeID(primitiveKind) }) { + return rootTextOfValue + } + return boundRootOf(loweringContext, schema) +} + +// writtenKept returns the value bounds of keys schema writes, in +// valueConstraintKeywords order. +func writtenKept(schema *statement.Schema, keys keySet) []string { + return slices.DeleteFunc(declaredConstraints(schema), func(keyword string) bool { return !keys.has(keyword) }) +} + +// boundsNone completes a report of keyword, a bound kept beside a kind r +// marks: what it bounds, and why the node's Constraints, which speak of the +// value, hold none of it. +func (r boundRoot) boundsNone(keyword string) string { + switch { + case r&rootNumberOfValue != 0 && numericBoundKeys.has(keyword): + return " bounds the number a value of another kind is written as, not the value its Constraints speak of: " + + "a bound binds only the kind its node's value is" + case r&rootTextOfNumber != 0: + return " bounds no number written as text, whose Constraints speak of the number: a length or a pattern bounds " + + "the text, and any other bound no string instance" + default: + return " bounds the text a value of another kind is written as, not the value its Constraints speak of: " + + "a keyword of the text binds only text" + } +} diff --git a/compilers/openapi/internal/schema/boundroot_test.go b/compilers/openapi/internal/schema/boundroot_test.go new file mode 100644 index 000000000..691bb66f7 --- /dev/null +++ b/compilers/openapi/internal/schema/boundroot_test.go @@ -0,0 +1,522 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// TestBoundRoot_ANumericBoundBesideANumberAsTextIsKeptWhereNoNumberTakesIt pins +// a numeric bound beside a reference to a number carried as text: the alias +// keeps it verbatim with the length beside it, as the referent written flat +// does, while a union holding a number carried as a JSON number beside such +// a branch holds it, that number taking it, and keeps only the length. +func TestBoundRoot_ANumericBoundBesideANumberAsTextIsKeptWhereNoNumberTakesIt(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " N: {type: string, format: int64}\n"+ + " ByRef: {$ref: '#/components/schemas/N', minimum: 5, maxLength: 9}\n"+ + " Either: {anyOf: [{$ref: '#/components/schemas/N'}, {type: integer}], minimum: 5, maxLength: 9}\n")) + openapitest.RequireNoErrorDiags(t, diags) + byRef, ok := typeByName(doc, "ByRef").(*ir.Scalar) + require.True(t, ok) + assert.Nil(t, byRef.Constraints) + for _, key := range []string{"openapi:minimum", "openapi:maxLength"} { + assert.Equal(t, ir.ReasonNoIRHome, byRef.Unmodeled[key].Reason, key) + } + either, ok := typeByName(doc, "Either").(*ir.Union) + require.True(t, ok) + require.NotNil(t, either.Constraints) + assert.Equal(t, new(ir.BigVal("5")), either.Constraints.Min, "the integer takes the minimum") + assert.Nil(t, either.Constraints.MaxLength) + assert.Equal(t, ir.ReasonNoIRHome, either.Unmodeled["openapi:maxLength"].Reason, "no branch's text is a string's") + assert.NotContains(t, either.Unmodeled, "openapi:minimum") +} + +// TestBoundRoot_APrincipalWritingABoundOtherwiseKeepsItUnderItsEntry pins an +// enum or a union principal whose members are text of another kind writing a +// length the position beside its allOf writes too: the position's takes the +// plain key, the principal's, written otherwise, its entry key, and written +// alike the two are one writing, kept once. +func TestBoundRoot_APrincipalWritingABoundOtherwiseKeepsItUnderItsEntry(t *testing.T) { + t.Parallel() + const uuid = "['123e4567-e89b-12d3-a456-426614174000']" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " Apart: {allOf: [{type: string, format: uuid, enum: "+uuid+", maxLength: 36}], maxLength: 40}\n"+ + " Alike: {allOf: [{type: string, format: uuid, enum: "+uuid+", maxLength: 36}], maxLength: 36}\n"+ + " Union: {allOf: [{anyOf: [{type: string, format: date-time}, {type: integer}], maxLength: 5}], maxLength: 9}\n")) + openapitest.RequireNoErrorDiags(t, diags) + kept := func(name string) map[string]string { + out := map[string]string{} + for key, entry := range typeByName(doc, name).Common().Unmodeled { + out[key] = string(entry.Value) + " " + string(entry.Reason) + } + return out + } + assert.Equal(t, map[string]string{"openapi:maxLength": "40 no_ir_home", "openapi:allOf/0/maxLength": "36 no_ir_home"}, kept("Apart")) + assert.Equal(t, map[string]string{"openapi:maxLength": "36 no_ir_home"}, kept("Alike")) + assert.Equal(t, map[string]string{"openapi:maxLength": "9 no_ir_home", "openapi:allOf/0/maxLength": "5 no_ir_home"}, kept("Union")) +} + +// secondsSchemas write a numeric bound beside an instant written as its +// seconds, on an integer or a number: on the Scalar the format hoists, beside +// a reference to one, on an allOf entry beside it and beside an allOf over +// it, on a type list's integer variant, beside a union one branch of which +// is such seconds, and at a property and a carrier over a reference; and, +// for a control, beside a width carried as a JSON number. +var secondsSchemas = []string{ + "T: {type: integer, format: unixtime}", + "Own: {type: integer, format: unixtime, minimum: 0, maximum: 9}", + "Fraction: {type: number, format: unixtime, multipleOf: 0.5}", + "Ref: {$ref: '#/components/schemas/T', minimum: 1}", + "Voice: {allOf: [{type: integer, format: unixtime}, {minimum: 2}]}", + "Beside: {allOf: [{type: integer, format: unixtime}], minimum: 3}", + "List: {type: [integer, string], format: unixtime, minimum: 4}", + "Either: {anyOf: [{$ref: '#/components/schemas/T'}, {type: integer}], minimum: 5}", + "Width: {type: integer, format: int64, minimum: 6}", + "Holder: {type: object, properties: {own: {type: integer, format: unixtime, minimum: 7}, " + + "viaRef: {$ref: '#/components/schemas/T', maximum: 8}}}", +} + +// TestBoundRoot_ANumericBoundBesideAnInstantsSecondsIsKept pins that a +// numeric bound binds only a number that is the value: beside an instant +// written as its seconds, on an integer or a number, at every holder, it +// reaches no Constraints and is kept verbatim with no IR home and one info at +// it, while a width carried as a JSON number holds it. It holds in both +// declaration orders, a referent built before its use or after +// (docs/compilers/openapi.md#numeric-formats). +func TestBoundRoot_ANumericBoundBesideAnInstantsSecondsIsKept(t *testing.T) { + t.Parallel() + reversed := slices.Clone(secondsSchemas) + slices.Reverse(reversed) + for order, schemas := range map[string][]string{"declared": secondsSchemas, "reversed": reversed} { + t.Run(order, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpec(" "+strings.Join(schemas, "\n ")+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + nodes := map[string]ir.TypeDef{ + "Own": typeByName(doc, "Own"), "Fraction": typeByName(doc, "Fraction"), "Ref": typeByName(doc, "Ref"), + "Voice": typeByName(doc, "Voice"), "Beside": typeByName(doc, "Beside"), "Either": typeByName(doc, "Either"), + "List": doc.Types["type/anonymous/components/schemas/List/type/0"], + "own": doc.Types["type/anonymous/components/schemas/Holder/properties/own"], + } + for name, kept := range map[string][]string{ + "Own": {"openapi:maximum", "openapi:minimum"}, "Fraction": {"openapi:multipleOf"}, "Ref": {"openapi:minimum"}, + "Voice": {"openapi:minimum"}, "Beside": {"openapi:minimum"}, "Either": {"openapi:minimum"}, + "List": {"openapi:minimum"}, "own": {"openapi:minimum"}, + } { + require.NotNil(t, nodes[name], name) + assert.Nil(t, boundsHeldBy(nodes[name]), "%s holds no bound of the seconds", name) + assert.Equal(t, kept, keptWithNoHome(nodes[name].Common().Unmodeled), name) + } + viaRef := propertyOf(t, doc, "Holder", "viaRef") + assert.Nil(t, viaRef.Constraints) + assert.Equal(t, []string{"openapi:maximum"}, keptWithNoHome(viaRef.Unmodeled)) + assert.Equal(t, 10, openapitest.CountDiagsAt(diags, diag.UnhomedConstruct, ir.SeverityInfo), "one info at each bound kept") + width := asKind[*ir.Scalar](t, typeByName(doc, "Width")) + require.NotNil(t, width.Constraints, "a width carried as a JSON number holds it") + assert.Equal(t, new(ir.BigVal("6")), width.Constraints.Min) + }) + } +} + +// TestBoundRoot_AnEnumsRootIsItsValueType pins that what an enum's members are +// is its ValueType, not the format beside them: an Enum of strings, its members +// no instant, holds a length and draws no report for it; one an allOf entry's +// format alone types as instants keeps one, its own or a flattened entry's +// once; one of integers holds a minimum beside unixtime, and one of +// strings beside a number's text format keeps a minimum as of another kind. A +// union of literals holds what each Literal's ValueType takes, and a reference +// to an Enum of strings holds a length too, in both orders. +func TestBoundRoot_AnEnumsRootIsItsValueType(t *testing.T) { + t.Parallel() + schemas := []string{ + "Listed: {type: string, format: date-time, enum: [abc, de], maxLength: 3}", + "Typed: {enum: ['2020-01-01T00:00:00Z'], allOf: [{format: date-time}], maxLength: 30}", + "Voiced: {allOf: [{enum: ['2020-01-01T00:00:00Z']}, {format: date-time}, {maxLength: 30}]}", + "Seconds: {type: integer, format: unixtime, enum: [1, 2], minimum: 0}", + "Text: {type: string, format: int64, enum: ['1'], maxLength: 4, minimum: 0}", + "Mixed: {type: [string, integer], format: date-time, enum: ['2020-01-01T00:00:00Z', 1], maxLength: 30, minimum: 0}", + "Instant: {type: string, format: date-time, enum: ['2020-01-01T00:00:00Z', {a: 1}], maxLength: 30}", + "ByRef: {$ref: '#/components/schemas/Listed', maxLength: 2}", + "Holder: {type: object, properties: {viaRef: {$ref: '#/components/schemas/Listed', maxLength: 4}}}", + } + reversed := slices.Clone(schemas) + slices.Reverse(reversed) + for order, written := range map[string][]string{"declared": schemas, "reversed": reversed} { + t.Run(order, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpec(" "+strings.Join(written, "\n ")+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + for name, held := range map[string][]string{ + "Listed": {"maxLength"}, "Seconds": {"min"}, "Text": {"maxLength"}, "Mixed": {"maxLength", "min"}, "ByRef": {"maxLength"}, + } { + assert.Equal(t, held, heldFields(boundsHeldBy(typeByName(doc, name))), name) + assert.Empty(t, keptWithNoHome(typeByName(doc, name).Common().Unmodeled), name) + } + assert.Equal(t, ir.PrimitiveString, asKind[*ir.Enum](t, typeByName(doc, "Listed")).ValueType) + assert.Equal(t, ir.ReasonDegradedLowering, typeByName(doc, "Text").Common().Unmodeled["openapi:minimum"].Reason, + "a numeric bound applies to no string") + for _, name := range []string{"Typed", "Voiced", "Instant"} { + assert.Nil(t, boundsHeldBy(typeByName(doc, name)), name) + assert.Equal(t, []string{"openapi:maxLength"}, keptWithNoHome(typeByName(doc, name).Common().Unmodeled), name) + } + assert.Equal(t, ir.PrimitiveDatetimeOffset, asKind[*ir.Enum](t, typeByName(doc, "Typed")).ValueType) + viaRef := propertyOf(t, doc, "Holder", "viaRef") + assert.Equal(t, []string{"maxLength"}, heldFields(viaRef.Constraints)) + assert.Equal(t, 3, openapitest.CountDiagsAt(diags, diag.UnhomedConstruct, ir.SeverityInfo), "one info at each length kept") + }) + } +} + +// TestBoundRoot_AReferencedValueSetIsReadByItsNodesType pins a bound beside a +// reference to a value set read by the node the set lowers to: a const +// written beside an instant's format, its value no instant, is a Literal of +// a string, and an enum past the budget the top type, so each alias holds a +// length; one whose member converts to no value reads as no set. +func TestBoundRoot_AReferencedValueSetIsReadByItsNodesType(t *testing.T) { + t.Parallel() + lowerer, _ := schema.LoweredFor(t, openapitest.ComponentSpec(""+ + " C: {type: string, format: date-time, const: abc}\n"+ + " E: {type: string, format: date-time, enum: ['2020-01-01T00:00:00Z', '2021-01-01T00:00:00Z']}\n"+ + " I: {type: string, format: date-time, enum: [.inf]}\n"+ + " ByC: {$ref: '#/components/schemas/C', maxLength: 3}\n"+ + " ByE: {$ref: '#/components/schemas/E', maxLength: 3}\n"+ + " ByI: {$ref: '#/components/schemas/I', maxLength: 3}\n")) + lowerer.Ctx.Limits = lowering.Limits{MaxEnumMembers: budget.AtMost(1)} + diags := schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas()) + doc := lowerer.Document(t) + for _, name := range []string{"ByC", "ByE"} { + assert.Equal(t, []string{"maxLength"}, heldFields(boundsHeldBy(typeByName(doc, name))), name) + } + assert.Equal(t, []string{"openapi:maxLength"}, keptWithNoHome(typeByName(doc, "ByI").Common().Unmodeled), + "a member no value reads is no set: the format's instant decides") + assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.UnhomedConstruct, ir.SeverityInfo)) +} + +// boundsHeldBy returns the Constraints typeDef holds, nil for a kind holding +// none. +func boundsHeldBy(typeDef ir.TypeDef) *ir.Constraints { + switch node := typeDef.(type) { + case *ir.Scalar: + return node.Constraints + case *ir.Enum: + return node.Constraints + case *ir.Union: + return node.Constraints + default: + return nil + } +} + +// heldFields returns the value bounds constraints holds, by their JSON names, +// sorted. +func heldFields(constraints *ir.Constraints) []string { + if constraints == nil { + return nil + } + var out []string + for name, set := range map[string]bool{ + "min": constraints.Min != nil, "max": constraints.Max != nil, "exclusiveMin": constraints.ExclusiveMin != nil, + "exclusiveMax": constraints.ExclusiveMax != nil, "multipleOf": constraints.MultipleOf != nil, + "minLength": constraints.MinLength != nil, "maxLength": constraints.MaxLength != nil, "pattern": constraints.Pattern != "", + } { + if set { + out = append(out, name) + } + } + slices.Sort(out) + return out +} + +// keptWithNoHome returns the keys unmodeled keeps with no IR home, sorted. +func keptWithNoHome(unmodeled ir.Unmodeled) []string { + var out []string + for key, entry := range unmodeled { + if entry.Reason == ir.ReasonNoIRHome { + out = append(out, key) + } + } + slices.Sort(out) + return out +} + +// placementGroup is documents spelling one bound beside one format otherwise: +// the first is the flat spelling each other is held to, and at names the node +// holding the bounds below the components. +type placementGroup struct { + name, at string + spellings [][]string +} + +// spelledAs returns, for each spelling of spellings (openapitest.Spellings) in +// name order, the components written: the schema in place of %s in each of +// components, the rest written as they are. +func spelledAs(spellings map[string]string, components ...string) [][]string { + out := make([][]string, 0, len(spellings)) + for _, name := range slices.Sorted(maps.Keys(spellings)) { + written := make([]string, len(components)) + for i, component := range components { + written[i] = strings.ReplaceAll(component, "%s", spellings[name]) + } + out = append(out, written) + } + return out +} + +// requireGroupsAlike holds every spelling of each of groups, in both +// declaration orders, to the placement of its first. +func requireGroupsAlike(t *testing.T, groups []placementGroup) { + t.Helper() + for _, group := range groups { + t.Run(group.name, func(t *testing.T) { + t.Parallel() + want := placementOf(t, group.spellings[0], group.at) + for _, spelling := range group.spellings { + reversed := slices.Clone(spelling) + slices.Reverse(reversed) + for _, written := range [][]string{spelling, reversed} { + assert.Equal(t, want, placementOf(t, written, group.at), "%s", strings.Join(written, "; ")) + } + } + }) + } +} + +// refU and useU write a reference to U and one through an allOf over it, each +// with %s beside it. +const ( + refU = "P: {$ref: '#/components/schemas/U', %s}" + useU = "P: {allOf: [{$ref: '#/components/schemas/U'}], %s}" +) + +// besideReferences returns the spellings of a reference to U, spelt each way +// openapitest.Spellings writes body and parts, with bound beside the +// reference and beside an allOf over it. +func besideReferences(bound, body string, parts ...string) [][]string { + referents := openapitest.Spellings(body, parts...) + return slices.Concat(spelledAs(referents, "U: %s", strings.Replace(refU, "%s", bound, 1)), + spelledAs(referents, "U: %s", strings.Replace(useU, "%s", bound, 1))) +} + +// settledGroups write one bound beside one format, the type, the format, the +// contentEncoding and the bound each on the schema, another conjunct, a $ref's +// target, a union's branch or a property, as openapitest.Spellings places +// them. +func settledGroups() []placementGroup { + at := func(name, at string, flat []string, rest ...[][]string) placementGroup { + return placementGroup{name: name, at: at, spellings: slices.Concat(append([][][]string{{flat}}, rest...)...)} + } + return []placementGroup{ + at("seconds", "P", []string{"P: {type: integer, format: unixtime, minimum: 0}"}, + spelledAs(openapitest.Spellings("type: integer", "format: unixtime", "minimum: 0"), "P: %s"), + besideReferences("minimum: 0", "type: integer", "format: unixtime"), + [][]string{{"P: {type: integer, oneOf: [{format: unixtime}], minimum: 0}"}}), + at("instant", "P", []string{"P: {type: string, format: date-time, maxLength: 30}"}, + spelledAs(openapitest.Spellings("type: string", "format: date-time", "maxLength: 30"), "P: %s"), + besideReferences("maxLength: 30", "type: string", "format: date-time")), + at("number as text", "P", []string{"P: {type: string, format: int64, maxLength: 3, minimum: 0}"}, + spelledAs(openapitest.Spellings("type: string", "format: int64", "maxLength: 3, minimum: 0"), "P: %s"), + besideReferences("maxLength: 3, minimum: 0", "type: string", "format: int64")), + at("encoded bytes", "P", []string{"P: {type: string, format: binary, contentEncoding: base64, maxLength: 3}"}, + spelledAs(openapitest.Spellings("type: string", "format: binary", "contentEncoding: base64", "maxLength: 3"), "P: %s"), + besideReferences("maxLength: 3", "type: string", "format: binary", "contentEncoding: base64")), + at("encoded instant", "P", []string{"P: {type: string, format: date-time, contentEncoding: base64, maxLength: 3}"}, + besideReferences("maxLength: 3", "type: string", "format: date-time", "contentEncoding: base64")), + at("cyclic referent", "P", []string{"P: {type: integer, format: unixtime, minimum: 0}"}, + [][]string{{"U: {type: integer, format: unixtime, allOf: [{$ref: '#/components/schemas/U'}]}", strings.Replace(refU, "%s", "minimum: 0", 1)}}), + at("format beside a union", "P", []string{"P: {oneOf: [{type: integer}], minimum: 0}"}, + [][]string{ + {"P: {format: unixtime, oneOf: [{type: integer}], minimum: 0}"}, + {"U: {format: unixtime, oneOf: [{type: integer}]}", strings.Replace(refU, "%s", "minimum: 0", 1)}, + {"U: {format: unixtime, oneOf: [{type: integer}, {type: string}]}", strings.Replace(refU, "%s", "minimum: 0", 1)}, + }), + at("union branch", "P", []string{"P: {oneOf: [{type: integer, format: unixtime}, {type: string}], minimum: 0}"}, + spelledAs(openapitest.Spellings("type: integer", "format: unixtime"), "P: {oneOf: [%s, {type: string}], minimum: 0}")), + at("type list variant", "P/type/0", []string{"P: {type: [integer, string], format: unixtime, minimum: 0}"}, + spelledAs(openapitest.Spellings("type: [integer, string]", "format: unixtime", "minimum: 0"), "P: %s")), + at("conjoined branch", "P/oneOf/0", []string{"P: {oneOf: [{type: integer, format: unixtime, minimum: 1}, {type: integer, format: int32}]}"}, + [][]string{{"P: {type: integer, oneOf: [{format: unixtime, minimum: 1}, {format: int32}]}"}}), + at("conjoined text branch", "P/oneOf/0", []string{"P: {oneOf: [{type: string, format: date-time, maxLength: 9}, {type: string, format: uuid}]}"}, + [][]string{{"P: {type: string, oneOf: [{format: date-time, maxLength: 9}, {format: uuid}]}"}}), + at("property", "P/properties/a", []string{"P: {type: object, properties: {a: {type: integer, format: unixtime, minimum: 0}}}"}, + spelledAs(openapitest.Spellings("type: integer", "format: unixtime", "minimum: 0"), "P: {type: object, properties: {a: %s}}")), + } +} + +// TestBoundRoot_EverySpellingPlacesABoundAsTheFlatOneDoes pins that a bound +// binds the settled node's root, whichever conjunct, $ref target or branch +// writes the type, the format or the contentEncoding that root is read from: +// each spelling of a group lowers to the node its flat one does, holds the +// bounds it holds, and keeps the rest as it keeps them, each with one info, in +// both declaration orders (docs/compilers/openapi.md#numeric-formats). +func TestBoundRoot_EverySpellingPlacesABoundAsTheFlatOneDoes(t *testing.T) { + t.Parallel() + requireGroupsAlike(t, settledGroups()) +} + +// placement is where the bounds of one position land: what its chain ends on, +// the bounds it holds, each value bound it keeps by keyword with its value and +// reason, and the keyword of each unhomed-construct info. +type placement struct { + node string + held []string + kept map[string]string + infos []string +} + +// placementOf compiles the components schemas write and returns the placement +// of the node at at below them. +func placementOf(t *testing.T, schemas []string, at string) placement { + t.Helper() + doc, diags := parseFull(t, openapitest.ComponentSpec(" "+strings.Join(schemas, "\n ")+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + node := typeByName(doc, at) + for _, namespace := range []string{"anonymous", "composed"} { + if node == nil { + node = doc.Types[ir.TypeID("type/"+namespace+"/components/schemas/"+at)] + } + } + require.NotNil(t, node, at) + out := placement{node: chainEnd(doc, node), held: heldFields(boundsHeldBy(node)), kept: map[string]string{}} + for key, entry := range node.Common().Unmodeled { + if keyword := key[strings.LastIndexAny(key, ":/")+1:]; isValueBound(keyword) { + out.kept[keyword] = string(entry.Value) + " " + string(entry.Reason) + } + } + for _, d := range diags { + if keyword := d.Provenance.Pointer.LastToken(); d.Code == diag.UnhomedConstruct && isValueBound(keyword) { + out.infos = append(out.infos, keyword) + } + } + slices.Sort(out.infos) + return out +} + +// isValueBound reports whether keyword is a bound of a string's or a number's +// value. +func isValueBound(keyword string) bool { + return slices.Contains([]string{"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minLength", "maxLength", "pattern"}, keyword) +} + +// chainEnd describes what node's chain of Scalars ends on: the kind of a node +// no Scalar is, else the primitive it is rooted at and the nearest Encoding's +// name and WireType. +func chainEnd(doc *ir.Document, node ir.TypeDef) string { + var encoding *ir.Encoding + for range 8 { + scalar, ok := node.(*ir.Scalar) + if !ok { + break + } + if encoding == nil { + encoding = scalar.Encoding + } + node = doc.Types[scalar.Base.Target] + } + primitive, ok := node.(*ir.Primitive) + if !ok { + return string(node.Kind()) + } + if encoding == nil { + return string(primitive.PrimitiveKind) + } + wire := ir.TypeID("") + if encoding.WireType != nil { + wire = encoding.WireType.Target + } + return string(primitive.PrimitiveKind) + " as " + encoding.Name + " over " + string(wire) +} + +// referencedSetGroups spell a value set with a format, the first with the +// set flat, the rest reaching it through a $ref, a union's branch or both, +// the set spelt each way openapitest.Spellings writes its type, members and +// format, and the bound beside the reference. A const's first is a +// reference, as a Literal holds no bound. Members that are no instant are a +// control. +func referencedSetGroups() []placementGroup { + const instant = "'2020-01-01T00:00:00Z'" + union := "T: {oneOf: [{$ref: '#/components/schemas/U'}, {type: integer}]}" + return []placementGroup{ + {name: "enum of instants", at: "P", spellings: slices.Concat( + [][]string{{"P: {type: string, enum: [" + instant + "], format: date-time, maxLength: 30}"}}, + besideReferences("maxLength: 30", "type: string", "enum: ["+instant+"]", "format: date-time"), + [][]string{{"U: {allOf: [{type: string, enum: [" + instant + "]}, {format: date-time}]}", + "V: {$ref: '#/components/schemas/U'}", "P: {$ref: '#/components/schemas/V', maxLength: 30}"}})}, + {name: "const instant", at: "P", spellings: besideReferences("maxLength: 30", "type: string", "const: "+instant, "format: date-time")}, + {name: "enum of text", at: "P", spellings: slices.Concat( + [][]string{{"P: {type: string, enum: [abc], format: date-time, maxLength: 3}"}}, + besideReferences("maxLength: 3", "type: string", "enum: [abc]", "format: date-time"))}, + {name: "union branch", at: "P", spellings: spelledAs(openapitest.Spellings("type: string", "enum: ["+instant+"]", "format: date-time"), + "U: %s", "P: {oneOf: [{$ref: '#/components/schemas/U'}, {type: integer}], maxLength: 30}")}, + {name: "reference to a union branch", at: "P", spellings: spelledAs(openapitest.Spellings("type: string", "enum: ["+instant+"]", "format: date-time"), + "U: %s", union, "P: {$ref: '#/components/schemas/T', maxLength: 30}")}, + } +} + +// TestBoundRoot_AReferencedSetReadsTheFormatItsConjunctsWrite pins that a +// bound beside a reference to a value set, or a union holding one, binds the +// kind the set's node's ValueType is, as every conjunct of the set narrows it, +// whichever writes the format: each spelling places the bound as the flat set +// does, in both declaration orders +// (docs/compilers/openapi.md#constraints). +func TestBoundRoot_AReferencedSetReadsTheFormatItsConjunctsWrite(t *testing.T) { + t.Parallel() + requireGroupsAlike(t, referencedSetGroups()) +} + +// unionGroups write a bound beside a union of branches of one kind, the first +// with each branch's type written on it, the rest with the type, the union and +// the bound placed each way openapitest.Spellings writes them, behind a $ref +// the branches are conjoined with, or the union behind a reference. One +// branch an instant keeps the bound; branches all of their own values hold it. +func unionGroups() []placementGroup { + beside := func(name, flat, kind, branches, bound string) placementGroup { + ref := "T: {type: " + kind + "}" + return placementGroup{name: name, at: "P", spellings: slices.Concat( + [][]string{{"P: " + flat}}, + spelledAs(openapitest.Spellings("type: "+kind, "oneOf: "+branches, bound), "P: %s"), + spelledAs(openapitest.Spellings("$ref: '#/components/schemas/T'", "oneOf: "+branches, bound), ref, "P: %s"), + besideReferences(bound, "type: "+kind, "oneOf: "+branches))} + } + return []placementGroup{ + beside("a variant of seconds", "{oneOf: [{type: integer, format: unixtime}, {type: integer, format: int32}], minimum: 0}", + "integer", "[{format: unixtime}, {format: int32}]", "minimum: 0"), + beside("variants of widths", "{oneOf: [{type: integer, format: int64}, {type: integer, format: int32}], minimum: 0}", + "integer", "[{format: int64}, {format: int32}]", "minimum: 0"), + beside("variants of instants' text", "{oneOf: [{type: string, format: date-time}, {type: string, format: uuid}], maxLength: 9}", + "string", "[{format: date-time}, {format: uuid}]", "maxLength: 9"), + {name: "typed variants beside a body", at: "P", spellings: slices.Concat( + [][]string{{"P: {oneOf: [{type: string, format: uuid}, {type: string, format: email}], maxLength: 9}"}}, + spelledAs(openapitest.Spellings("type: string", "oneOf: [{type: string, format: uuid}, {type: string, format: email}]", "maxLength: 9"), "P: %s"))}, + {name: "one live variant", at: "P", spellings: [][]string{ + {"P: {type: string, format: uuid, maxLength: 9}"}, + {"P: {type: string, maxLength: 9, oneOf: [{type: integer}, {format: uuid}]}"}, + }}, + } +} + +// TestBoundRoot_ABoundBesideAUnionBindsEachVariantsRoot pins that a bound +// beside a union reaches its Constraints only where every variant of the +// bound's kind is a value of that kind, read per variant whichever schema +// writes the type a branch is conjoined with, and is kept verbatim with one +// info otherwise: each spelling places it as the union of typed branches +// does, in both declaration orders (docs/compilers/openapi.md#constraints). +func TestBoundRoot_ABoundBesideAUnionBindsEachVariantsRoot(t *testing.T) { + t.Parallel() + requireGroupsAlike(t, unionGroups()) +} diff --git a/compilers/openapi/internal/schema/branch.go b/compilers/openapi/internal/schema/branch.go deleted file mode 100644 index 277396ab4..000000000 --- a/compilers/openapi/internal/schema/branch.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/reftable" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" -) - -// refBranchTarget returns the schema the chain of references from b, an -// allOf entry's or a union branch's statement, ends on, as the bindings -// resolved it (Reference.Entry), and nil where b is no reference site -// (typed.Bindings.RefSite). -// Where the chain ends on no schema, or on a bare boolean schema, it returns -// one that is no schema object (stated). -func refBranchTarget(loweringContext lowering.Ctx, b *statement.Statement) *statement.Schema { - if b.Ref == nil { - return nil - } - if end, ok := runEnd(loweringContext, b); ok { - return end.Schema - } - return loweringContext.Statements().Read(nil).Schema -} - -// runEnd returns the statement the run of $refs from st ends on: the first -// schema it reaches writing no $ref, or writing keys beside one, which -// conjoins the two rather than naming one (statement.Schema.BesideRef), -// whether or not the chain the bindings follow past it resolves. It is false -// where a hop before it lands on no schema, and for a loop of $refs, which -// maxChainHops ends. -func runEnd(loweringContext lowering.Ctx, st *statement.Statement) (*statement.Statement, bool) { - if referenceSite := st.Ref.Entry; st.Ref.Bound && referenceSite.Chain.Status == reftable.Resolved && referenceSite.Chain.Hops == 1 { - return loweringContext.Statements().At(referenceSite.Chain.End), true // the one hop is the run - } - for range maxChainHops { - next, _ := declaredOf(loweringContext, st) - switch { - case next == nil: - return nil, false - case next.Ref == nil: - return next, true - } - st = next - } - return nil, false -} - -// declaredOf returns the statement of the schema written where st's $ref -// lands, as the bindings resolved its first hop (typed.Bindings.DeclaredAt), -// and the position it lands at; nil and the zero position where it lands on -// none. -func declaredOf(loweringContext lowering.Ctx, st *statement.Statement) (*statement.Statement, reftable.DocumentPointer) { - if st.Ref == nil || !st.Ref.Bound || st.Ref.Entry.Hop.Status != reftable.Resolved { - return nil, reftable.DocumentPointer{} - } - return loweringContext.Statements().At(st.Ref.Entry.Hop.Target), st.Ref.Entry.Hop.Target -} - -// declared returns the statement of the schema written where schemaStatement's -// $ref lands, as declaredOf reads it, and an Unwritten one where it lands on -// none, for a reader taking the statement of none (fallbackAnnotationsOf). -func declared(loweringContext lowering.Ctx, schemaStatement *statement.Statement) *statement.Statement { - if st, _ := declaredOf(loweringContext, schemaStatement); st != nil { - return st - } - return loweringContext.Statements().Read(nil) -} - -// siteOf returns the position the bindings read schema at, and false for a -// schema they do not place, which the statement reads at the zero position. -func siteOf(schema *statement.Schema) (reftable.DocumentPointer, bool) { - if schema == nil || schema.At == (reftable.DocumentPointer{}) { - return reftable.DocumentPointer{}, false - } - return schema.At, true -} - -// refKeyword returns the keyword st is a reference site under -// (typed.Bindings.RefKeyword), "" for one writing no reference. -func refKeyword(st *statement.Statement) string { - if st.Ref == nil { - return "" - } - return st.Ref.Keyword -} - -// writesConjuncts reports whether schema says what an allOf says: it writes -// one, or it is the rest of an object writing a reference beside it, whose -// conjuncts are the reference and the rest (statement.Schema.BesideRef). -func writesConjuncts(schema *statement.Schema) bool { - return schema != nil && (len(schema.AllOf) > 0 || schema.BesideRef != nil) -} - -// conjunctsIn returns the statements of the conjuncts schema writes beside its -// own keywords, unflattened: the reference written beside them -// (writesConjuncts), then each schema its allOf lists. -func conjunctsIn(loweringContext lowering.Ctx, schema *statement.Schema) []*statement.Statement { - if schema == nil { - return nil - } - out := make([]*statement.Statement, 0, 1+len(schema.AllOf)) - if schema.BesideRef != nil { - out = append(out, loweringContext.Statements().Read(schema.BesideRef)) - } - for _, b := range schema.AllOf { - out = append(out, loweringContext.Statements().Subschema(b)) - } - return out -} - -// referenceOf returns the statement of the $ref st writes: st where it writes -// one alone, the reference written beside its keywords where it writes both -// (statement.Schema.BesideRef), and nil where it writes none. -func referenceOf(loweringContext lowering.Ctx, st *statement.Statement) *statement.Statement { - switch { - case st.Ref != nil: - return st - case st.BesideRef != nil: - return loweringContext.Statements().Read(st.BesideRef) - default: - return nil - } -} - -// allOfIn returns the schemas schema's allOf lists, nil for a nil schema and -// one writing none. -func allOfIn(schema *statement.Schema) []statement.Subschema { - if schema == nil { - return nil - } - return schema.AllOf -} - -// refWritten reports whether schema writes `$ref`, as the parser's model holds -// it: a reference site under that keyword, not a $dynamicRef the bindings read -// as one (statement.Reference). -func refWritten(schema *statement.Schema) bool { - return schema != nil && schema.Ref != nil && schema.Ref.Keyword == "$ref" -} diff --git a/compilers/openapi/internal/schema/branchshape.go b/compilers/openapi/internal/schema/branchshape.go index 38113297b..3786ef696 100644 --- a/compilers/openapi/internal/schema/branchshape.go +++ b/compilers/openapi/internal/schema/branchshape.go @@ -21,7 +21,7 @@ import ( // (docs/compilers/openapi.md#union-beside-structure). var shapelessKeywords = slices.Concat( []string{"title", "description", "$comment", "deprecated", "examples", "example", "externalDocs"}, - []string{"$anchor", "$dynamicAnchor", "$defs"}, + []string{"$anchor", "$dynamicAnchor", "$defs", "$schema", "$vocabulary"}, []string{ "required", "nullable", "not", "if", "then", "else", "dependentSchemas", "dependentRequired", "propertyNames", "contains", "minContains", "maxContains", "unevaluatedItems", @@ -31,45 +31,47 @@ var shapelessKeywords = slices.Concat( // bodyReading is what a union's branches are judged against: what the body's // own keywords and its allOf admit, its unions apart, and what it declares of -// its properties and elements, read once a branch nests a claim. One admissionReader -// reads all of it, so a body's branches share one budget, and each place they -// restate is read once, so repeating a restatement reads no more of the body. -// What each branch writes is still read within it, an enum's members included. +// its properties and elements, read once a branch nests a restated schema. One +// admissionReader reads all of it, so a body's branches share one budget, and +// each place they restate is read once, so repeating a restatement reads no +// more of the body. What each branch writes is still read within it, an enum's +// members included. type bodyReading struct { - w admissionReader - body *statement.Schema - held admitted - decls *declarationSet + reader admissionReader + body *statement.Schema + bodyAdmits admitted + decls *declarationSet // own marks a reading of the body's own keywords and declarations alone, // nothing it composes (readOwnBody). own bool } -// readBody reads schema, the schema at the position of a union holder writes, -// for the union's branches to be judged against: holder's own keywords without -// its oneOf and anyOf, as where schema itself is the holder, so a union is -// judged by the rest whichever entry writes it. Where holder is an entry, -// another inline entry's union is no body either, as two unions beside the -// allOf judge each other by neither. -func readBody(loweringContext lowering.Ctx, schema, holder *statement.Schema) *bodyReading { - bodyReadingValue := &bodyReading{w: newAdmissionReader(loweringContext), body: schema} - bodyReadingValue.held = writtenLowered(&bodyReadingValue.w, schema, bodyReadingValue.w.nullable) - for _, b := range conjunctsIn(loweringContext, schema) { - if otherEntryUnion(b, schema, holder) { - bodyReadingValue.held = bodyReadingValue.held.and(writtenLowered(&bodyReadingValue.w, b.Schema, bodyReadingValue.w.nullable)) - continue - } - bodyReadingValue.held = bodyReadingValue.held.and(conjunctWithout(&bodyReadingValue.w, b, holder)) - } +// readBody reads schema, the schema at a union's position, for the branches +// to be judged against: what its conjunction admits outside every union, so a +// union is judged by the rest whichever conjunct writes it, and by no other +// union. +func readBody(loweringContext lowering.Ctx, schema *statement.Schema) *bodyReading { + bodyReadingValue := &bodyReading{reader: newAdmissionReader(loweringContext), body: schema} + bodyReadingValue.bodyAdmits = bodyWithoutUnions(&bodyReadingValue.reader, schema) return bodyReadingValue } -// otherEntryUnion reports whether b, a conjunct of schema, is an inline entry -// writing a union of its own beside holder, another entry of schema, which -// neither it nor a $ref it writes beside its keywords holds. -func otherEntryUnion(b *statement.Statement, schema, holder *statement.Schema) bool { - return holder != schema && b.Ref == nil && b.BesideRef == nil && b.Schema != holder && declaresUnion(b.Schema) && - !slices.ContainsFunc(b.Entries, func(allOfConjunct statement.AllOfConjunct) bool { return allOfConjunct.Schema == holder }) +// bodyWithoutUnions is what schema's conjunction admits outside every union +// it writes: each inline conjunct by its own keywords, and each $ref entry as +// what it lowers to, its target's unions its own. +func bodyWithoutUnions(admissionReaderValue *admissionReader, schema *statement.Schema) admitted { + read := writtenLowered(admissionReaderValue, schema, admissionReaderValue.nullable) + for _, entry := range admissionReaderValue.loweringContext.Statements().Read(schema).Entries { + switch { + case !stated(entry.Schema): + case entry.Ref != nil: + schemaStatement := admissionReaderValue.loweringContext.Statements().Read(entry.Schema) + read = read.and(admissionReaderValue.loweredFrom(composedEntryAdmission(admissionReaderValue.loweringContext, schema, schemaStatement))) + default: + read = read.and(writtenLowered(admissionReaderValue, entry.Schema, admissionReaderValue.nullable)) + } + } + return read } // readOwnBody reads only what schema itself writes: its own keywords, and its @@ -77,21 +79,21 @@ func otherEntryUnion(b *statement.Statement, schema, holder *statement.Schema) b // read whole as readBody reads it. It spends a budget of its own, so what it // reads the whole reading does not pay for. func readOwnBody(loweringContext lowering.Ctx, schema *statement.Schema) *bodyReading { - bodyReadingValue := &bodyReading{w: newAdmissionReader(loweringContext), body: schema, own: true} - bodyReadingValue.held = writtenLowered(&bodyReadingValue.w, schema, bodyReadingValue.w.nullable) + bodyReadingValue := &bodyReading{reader: newAdmissionReader(loweringContext), body: schema, own: true} + bodyReadingValue.bodyAdmits = writtenLowered(&bodyReadingValue.reader, schema, bodyReadingValue.reader.nullable) return bodyReadingValue } -// declared returns what the body declares of its properties and elements, -// read the first time a branch nests a claim, so a verdict needing none spends -// none of the budget on them. +// declared returns what the body declares of its properties and elements, read +// the first time a branch nests a restated schema, so an answer needing none +// spends none of the budget on them. func (r *bodyReading) declared() declarationSet { if r.decls == nil { declarationSet := newDeclarationSet() if r.own { - declarationSet.add(r.w.c.Statements(), r.body) + declarationSet.add(r.reader.loweringContext.Statements(), r.body) } else { - declarationSet = declarationsOf(&r.w, r.body) + declarationSet = declarationsOf(&r.reader, r.body) } r.decls = &declarationSet } @@ -107,36 +109,34 @@ func (r *bodyReading) declared() declarationSet { // a reading its budget cut short says nothing, so it counts as one that does. func unionBranchesDeclareShape(loweringContext lowering.Ctx, schema *statement.Schema) bool { choice := schema.ChoiceKeywords() - return setsDeclareShape(loweringContext, schema, schema, choice.OneOf, choice.AnyOf) + return setsDeclareShape(loweringContext, schema, choice.OneOf, choice.AnyOf) } // setsDeclareShape is unionBranchesDeclareShape for the branches of sets, -// written by holder, s or an allOf entry of it, judged against s as the body, -// read without holder's unions; a nil holder reads the conjunction whole. The -// body's own reading settles first each branch restating what s itself writes -// (ownRestatements), and only the rest are judged against the whole reading, -// which they would restate under too, as more declarations admit less. -func setsDeclareShape(loweringContext lowering.Ctx, schema, holder *statement.Schema, sets ...[]statement.Subschema) bool { +// written by schema or an allOf entry of it. A branch restating schema's own +// keywords is settled before the whole body is read: it would restate that +// too, as more declarations admit less. +func setsDeclareShape(loweringContext lowering.Ctx, schema *statement.Schema, sets ...[]statement.Subschema) bool { branches := statementsOf(loweringContext, slices.Concat(sets...)) - if slices.ContainsFunc(branches, func(b *statement.Statement) bool { return referenceOf(loweringContext, b) != nil }) { + if slices.ContainsFunc(branches, func(branch *statement.Statement) bool { return referenceOf(loweringContext, branch) != nil }) { return true } settled := ownRestatements(loweringContext, schema, branches) var bodyReadingValue *bodyReading body := func() *bodyReading { if bodyReadingValue == nil { - bodyReadingValue = readBody(loweringContext, schema, holder) + bodyReadingValue = readBody(loweringContext, schema) } return bodyReadingValue } found := false - for i, b := range branches { - if (settled == nil || !settled[i]) && branchDeclaresShape(loweringContext.Statements(), body, b) { + for i, branch := range branches { + if (settled == nil || !settled[i]) && branchDeclaresShape(loweringContext, body, branch) { found = true break } } - return found || bodyReadingValue != nil && bodyReadingValue.w.incomplete() + return found || bodyReadingValue != nil && bodyReadingValue.reader.incomplete() } // ownRestatements marks, by index, the inline branches of branches that restate @@ -152,59 +152,59 @@ func ownRestatements(loweringContext lowering.Ctx, schema *statement.Schema, bra return bodyReadingValue } settled := make([]bool, len(branches)) - for i, b := range branches { - if !branchDeclaresShape(loweringContext.Statements(), body, b) { + for i, branch := range branches { + if !branchDeclaresShape(loweringContext, body, branch) { settled[i] = true } } - if bodyReadingValue != nil && bodyReadingValue.w.incomplete() { + if bodyReadingValue != nil && bodyReadingValue.reader.incomplete() { return nil } return settled } -// branchDeclaresShape reports whether the inline union branch b declares data -// shape beside the body body reads, its schemas read from -// memoizingSchemaReader. A boolean never does, and any other does where one +// branchDeclaresShape reports whether the inline union branch declares data +// shape beside the body body reads, its schemas read through +// loweringContext. A boolean never does, and any other does where one // keyword it writes does: bare or beside a repeated `type`, a keyword is judged -// alike, so restating the body changes no verdict. A branch writing no key +// alike, so restating the body changes no answer. A branch writing no key // judged against the body, `required` alone the commonest, leaves it unread. -func branchDeclaresShape(memoizingSchemaReader *statement.MemoizingSchemaReader, body func() *bodyReading, b *statement.Statement) bool { - if b.Truth != statement.Stated { +func branchDeclaresShape(loweringContext lowering.Ctx, body func() *bodyReading, branch *statement.Statement) bool { + if branch.Truth != statement.Stated { return false } - writesJudged := slices.ContainsFunc(b.Keys, func(key statement.Key) bool { - return judged(memoizingSchemaReader, b.Schema, key.Name) + writesJudged := slices.ContainsFunc(branch.Keys, func(key statement.Key) bool { + return judged(loweringContext, branch.Schema, key.Name) }) if !writesJudged { return false } bodyReadingValue := body() - return !bodyReadingValue.restates(claim{written: b, held: bodyReadingValue.held}) + return !bodyReadingValue.restates(restatedSchema{written: branch, bodyAdmits: bodyReadingValue.bodyAdmits}) } // judged reports whether schema's key is judged against what the body says: it -// is neither shapeless, its schemas read from memoizingSchemaReader, nor a -// `type` naming only null, which contributes the null. -func judged(memoizingSchemaReader *statement.MemoizingSchemaReader, schema *statement.Schema, key string) bool { - return !shapeless(memoizingSchemaReader, schema, key) && (key != "type" || len(effectiveTypes(schema)) > 0) +// is neither shapeless nor a `type` naming only null, which contributes the +// null. +func judged(loweringContext lowering.Ctx, schema *statement.Schema, key string) bool { + return !shapeless(loweringContext, schema, key) && (key != "type" || len(effectiveTypes(schema)) > 0) } -// claim is a schema a branch writes, for itself, a property or an element, or -// as an allOf conjunct of one, with what the body admits there and the place -// the body declares it, nil for the branch itself, which restates the body -// whole. -type claim struct { - written *statement.Statement - held admitted - at *place +// restatedSchema is a schema a branch writes, for itself, a property or an +// element, or as an allOf conjunct of one, with what the body admits there and +// the place the body declares it, nil for the branch itself, which restates the +// body whole. +type restatedSchema struct { + written *statement.Statement + bodyAdmits admitted + bodyPlace *place } -// nested is a property or an element a claim writes, and the place the body -// declares it, nil where the body declares none. -type nested struct { - written *statement.Statement - at *place +// nestedSchema is a property or an element a restated schema writes, and the +// place the body declares it, nil where the body declares none. +type nestedSchema struct { + written *statement.Statement + bodyPlace *place } // restates reports whether top, and each conjunct, property and element it @@ -214,164 +214,148 @@ type nested struct { // (docs/compilers/openapi.md#source-budgets), while what each restates is read // within the admissionReader's budget. Comparing a nested schema's text renders it again // at each level, so restating one d levels deep renders about d squared nodes. -func (r *bodyReading) restates(top claim) bool { - claims := []claim{top} - for len(claims) > 0 { - claimValue := claims[len(claims)-1] - claims = claims[:len(claims)-1] - conjuncts, inner, ok := r.keysRestate(claimValue) +func (r *bodyReading) restates(top restatedSchema) bool { + restatedSchemas := []restatedSchema{top} + for len(restatedSchemas) > 0 { + restated := restatedSchemas[len(restatedSchemas)-1] + restatedSchemas = restatedSchemas[:len(restatedSchemas)-1] + conjuncts, inner, ok := r.keysRestate(restated) if !ok { return false } for _, subschema := range conjuncts { - claims = append(claims, claim{written: r.w.c.Statements().Subschema(subschema), held: claimValue.held, at: claimValue.at}) + restatedSchemas = append(restatedSchemas, restatedSchema{written: r.reader.loweringContext.Statements().Subschema(subschema), bodyAdmits: restated.bodyAdmits, bodyPlace: restated.bodyPlace}) } for _, nested := range inner { - sub, open, ok := r.claimOf(nested) - if !ok { + restatedInner, restatement := r.checkNested(nested) + switch restatement { + case nestedNewShape: return false - } - if open { - claims = append(claims, sub) + case nestedOpen: + restatedSchemas = append(restatedSchemas, restatedInner) + case nestedSaysNothing: } } } return true } -// keysRestate reports whether each key claimValue writes says nothing of shape +// keysRestate reports whether each key restated writes says nothing of shape // the body does not, and returns the allOf conjuncts, which restate what -// claimValue does, and the properties and element it writes, for restates to +// restated does, and the properties and element it writes, for restates to // judge. A key declares none where it is not judged, a `$ref` landing where -// claimValue's declarations compose, or a `type`, `format`, `enum` or `const` -// every value c.held admits holds to. A boolean conjunct says nothing or only -// forbids. Keys are the statement's, which hold the keywords the model has no -// field for (docs/parser-library.md#unmodeled-keywords). -func (r *bodyReading) keysRestate(claimValue claim) ([]statement.Subschema, []nested, bool) { - if !stated(claimValue.written.Schema) { +// restated's declarations compose, or a `type`, `format`, `enum` or `const` +// every value restated.bodyAdmits admits holds to. A boolean conjunct says +// nothing or only forbids. Keys are the statement's, which hold the keywords +// the model has no field for (docs/parser-library.md#unmodeled-keywords). +func (r *bodyReading) keysRestate(restated restatedSchema) ([]statement.Subschema, []nestedSchema, bool) { + if !stated(restated.written.Schema) { return nil, nil, true } - memoizingSchemaReader := r.w.c.Statements() - var inner []nested + memoizingSchemaReader := r.reader.loweringContext.Statements() + var inner []nestedSchema var conjuncts []statement.Subschema - for _, key := range claimValue.written.Keys { + for _, key := range restated.written.Keys { switch { - case !judged(memoizingSchemaReader, claimValue.written.Schema, key.Name): + case !judged(r.reader.loweringContext, restated.written.Schema, key.Name): case key.Name == "allOf": - conjuncts = claimValue.written.AllOf + conjuncts = restated.written.AllOf case key.Name == "properties": - decls := r.declarationsAt(claimValue) - for _, subschema := range claimValue.written.ObjectKeywords().Properties { - inner = append(inner, nested{written: memoizingSchemaReader.Subschema(subschema), at: decls.property(memoizingSchemaReader, subschema.Name)}) + decls := r.declarationsAt(restated) + for _, subschema := range restated.written.ObjectKeywords().Properties { + inner = append(inner, nestedSchema{written: memoizingSchemaReader.Subschema(subschema), bodyPlace: decls.property(memoizingSchemaReader, subschema.Name)}) } case key.Name == "items": - if _, listed := listedItems(claimValue.written.Schema); listed { + if _, listed := listedItems(restated.written.Schema); listed { // A tuple, or a malformed list, which no element the body declares restates. return nil, nil, false } - inner = append(inner, nested{written: memoizingSchemaReader.Subschema(claimValue.written.ArrayKeywords().Items), at: r.declarationsAt(claimValue).items}) - case key.Name == refKeyword(claimValue.written): - if !r.lands(claimValue) { + inner = append(inner, nestedSchema{written: memoizingSchemaReader.Subschema(restated.written.ArrayKeywords().Items), bodyPlace: r.declarationsAt(restated).items}) + case key.Name == refKeyword(restated.written): + if !r.lands(restated) { return nil, nil, false } - case !r.w.holds(claimValue.held, claimValue.written.Schema, key.Name): + case !r.reader.holds(restated.bodyAdmits, restated.written.Schema, key.Name): return nil, nil, false } } return conjuncts, inner, true } -// declarationsAt returns what the body declares of what claimValue nests: its -// own declarations for the branch itself, and what claimValue's place declares -// otherwise, each read the first time a claim nests something. -func (r *bodyReading) declarationsAt(claimValue claim) declarationSet { - if claimValue.at == nil { +// declarationsAt returns what the body declares of what restated nests: its +// own declarations for the branch itself, and what restated's place declares +// otherwise, each read the first time a restated schema nests something. +func (r *bodyReading) declarationsAt(restated restatedSchema) declarationSet { + if restated.bodyPlace == nil { return r.declared() } - return claimValue.at.declares(&r.w) + return restated.bodyPlace.declares(&r.reader) } -// claimOf returns the claim nestedValue makes, and false for open where -// nestedValue says nothing whatever its keys: a boolean says nothing or only -// forbids what it is written for, a declaration written alike against one base -// says the same, and declarations admitting nothing together leave nothing to -// say. ok is false where the body declares nothing there, so nestedValue is new -// shape. What nestedValue restates is what its declarations say together, each -// read as an admissionReader reads it, the keywords beside a $ref conjoining -// with it at every version (docs/compilers/openapi.md#ref-use-site). -func (r *bodyReading) claimOf(nestedValue nested) (sub claim, open, ok bool) { - if nestedValue.at == nil { - return claim{}, false, false +// nestedRestatement is what a property or an element a restated schema writes +// says of shape against what the body declares there (checkNested). +type nestedRestatement uint8 + +const ( + // nestedNewShape marks one the body declares nothing at: new shape. + nestedNewShape nestedRestatement = iota + // nestedSaysNothing marks one saying nothing whatever its keys. + nestedSaysNothing + // nestedOpen marks one whose own restated schema is judged in turn. + nestedOpen +) + +// checkNested returns the restated schema nested makes and what it says: a +// boolean, a declaration written alike against one base, or declarations +// admitting nothing together say nothing. What it restates is what its +// declarations say together (docs/compilers/openapi.md#ref-use-site). +func (r *bodyReading) checkNested(nested nestedSchema) (restatedSchema, nestedRestatement) { + if nested.bodyPlace == nil { + return restatedSchema{}, nestedNewShape } alike := func(schemaStatement *statement.Statement) bool { - return sameText(r.w.c, schemaStatement, nestedValue.written) + return sameText(r.reader.loweringContext, schemaStatement, nested.written) } - if nestedValue.written.Truth != statement.Stated || slices.ContainsFunc(nestedValue.at.decls, alike) { - return claim{}, false, true + if nested.written.Truth != statement.Stated || slices.ContainsFunc(nested.bodyPlace.decls, alike) { + return restatedSchema{}, nestedSaysNothing } - held := nestedValue.at.admits(&r.w) - if !held.reachable() { - return claim{}, false, true + bodyAdmits := nested.bodyPlace.admits(&r.reader) + if !bodyAdmits.reachable() { + return restatedSchema{}, nestedSaysNothing } - return claim{written: nestedValue.written, held: held, at: nestedValue.at}, true, true + return restatedSchema{written: nested.written, bodyAdmits: bodyAdmits, bodyPlace: nested.bodyPlace}, nestedOpen } -// lands reports whether the $ref claimValue writes lands on a schema -// claimValue's declarations compose, through allOf conjuncts and $refs, so it +// lands reports whether the $ref restated writes lands on a schema +// restated's declarations compose, through allOf conjuncts and $refs, so it // names what they already imply. The branch itself restates no declaration: // unionBranchesDeclareShape settles a $ref branch, and a $ref conjunct of one // declares shape as it does. -func (r *bodyReading) lands(claimValue claim) bool { - if claimValue.at == nil { +func (r *bodyReading) lands(restated restatedSchema) bool { + if restated.bodyPlace == nil { return false } - at, _ := declaredOf(r.w.c, claimValue.written) - return at != nil && slices.Contains(claimValue.at.declares(&r.w).composed, at) + at, _ := declaredOf(r.reader.loweringContext, restated.written) + return at != nil && slices.Contains(restated.bodyPlace.declares(&r.reader).composed, at) } // shapeless reports whether schema's keyword key declares no shape whatever it -// holds: a null that reads as the keyword left out, an extension, a keyword -// shapelessKeywords names, or an unevaluatedProperties other than false, read -// from memoizingSchemaReader, which is validation logic where false closes the -// object (docs/ir/boundaries.md#validation-only-constructs). -func shapeless(memoizingSchemaReader *statement.MemoizingSchemaReader, schema *statement.Schema, key string) bool { +// holds. An unevaluatedProperties other than false is validation logic, where +// false closes the object (docs/ir/boundaries.md#validation-only-constructs). +func shapeless(loweringContext lowering.Ctx, schema *statement.Schema, key string) bool { if annotation.WritesKeywordLeftOut(schema, key) || strings.HasPrefix(key, "x-") || slices.Contains(shapelessKeywords, key) { return true } - return key == "unevaluatedProperties" && !memoizingSchemaReader.Subschema(schema.ObjectKeywords().UnevaluatedProperties).Truth.ReadsFalse() + if TwinKeyword(loweringContext, schema, key) == "$id" { + return namesNoBase(schema) + } + return key == "unevaluatedProperties" && !loweringContext.Statements().Subschema(schema.ObjectKeywords().UnevaluatedProperties).Truth.ReadsFalse() } -// conjunctWithout is what the conjunct b admits, as lowered reads it, but -// where b is holder or holds it among its flattened entries, nested in an -// allOf or written beside a $ref: there holder is read by its own keywords, -// its unions left out, and every other entry as it is. -func conjunctWithout(admissionReaderValue *admissionReader, b *statement.Statement, holder *statement.Schema) admitted { - switch { - case b.Schema == holder && b.Ref == nil: - return writtenLowered(admissionReaderValue, holder, admissionReaderValue.nullable) - case holder != nil && b.BesideRef != nil && holder.WrittenBeside == b.BesideRef: - // An entry writing its union beside a $ref is listed as that reference - // and the keywords beside it (statement.Table.besideRefOf), the holder. - return lowered(admissionReaderValue, admissionReaderValue.c.Statements().Read(b.BesideRef)).and(writtenLowered(admissionReaderValue, holder, admissionReaderValue.nullable)) - } - if holder == nil || !slices.ContainsFunc(b.Entries, func(allOfConjunct statement.AllOfConjunct) bool { return allOfConjunct.Schema == holder }) { - return lowered(admissionReaderValue, b) - } - read := inlineConjunct(admissionReaderValue, b.Schema) - for _, allOfConjunct := range b.Entries { - st := admissionReaderValue.c.Statements().Read(allOfConjunct.Schema) - switch { - case allOfConjunct.Schema == holder: - read = read.and(writtenLowered(admissionReaderValue, holder, admissionReaderValue.nullable)) - case allOfConjunct.Wrapper: - read = read.and(inlineConjunct(admissionReaderValue, allOfConjunct.Schema)) - case st.Ref == nil && st.BesideRef == nil && declaresUnion(allOfConjunct.Schema): - // Another entry's union is no body of holder's, as beside it - // (otherEntryUnion). - read = read.and(writtenLowered(admissionReaderValue, allOfConjunct.Schema, admissionReaderValue.nullable)) - default: - read = read.and(lowered(admissionReaderValue, st)) - } - } - return read +// namesNoBase reports whether schema, which writes an identifier, writes no +// relative reference at any depth: then the base the identifier names is read +// by nothing, and it declares no shape. +func namesNoBase(schema *statement.Schema) bool { + raw, err := annotation.RawFromNode(schema.Node) + return err == nil && !annotation.WritesReference(raw) } diff --git a/compilers/openapi/internal/schema/carriedannotations.go b/compilers/openapi/internal/schema/carriedannotations.go new file mode 100644 index 000000000..d8dd7c7d4 --- /dev/null +++ b/compilers/openapi/internal/schema/carriedannotations.go @@ -0,0 +1,86 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/v2" + "reflect" + + "github.com/dexpace/morphic/ir" +) + +// givenAnnotation is one thing a node says that documents rather than admits, +// a member of an ir.Docs or an ir.Deprecation whole, at the path the walk of +// the node reaches it by (ir.WalkPath), with its value's encoding. +type givenAnnotation struct { + at string + value string +} + +// carries reports whether kept's nodes give every annotation other's do. What +// an alias says is given wherever on its chain of bare aliases it is written, +// and what a node says below it, as a property's description, at that place. +func (m *sameMeaning) carries(kept, other ir.TypeID) bool { + given := m.chainAnnotations(kept) + for item := range m.chainAnnotations(other) { + if !given[item] { + return false + } + } + return true +} + +// chainAnnotations returns the annotations the node id names gives, with +// those of each node its chain of bare aliases reaches (bareAliasChain). +func (m *sameMeaning) chainAnnotations(id ir.TypeID) map[givenAnnotation]bool { + items := map[givenAnnotation]bool{} + for at := range m.bareAliasChain(id) { + for _, item := range annotationsOf(m.nodes.node(at)) { + items[item] = true + } + } + return items +} + +// The types annotationsOf reads: each member of a Docs, and a Deprecation. +var ( + docsType = reflect.TypeFor[ir.Docs]() + deprecationType = reflect.TypeFor[*ir.Deprecation]() +) + +// annotationsOf returns the annotations typeDef gives wherever it holds them, +// its own and a property's, a variant's or an enum member's. +func annotationsOf(typeDef ir.TypeDef, held bool) []givenAnnotation { + if !held { + return nil + } + var items []givenAnnotation + // Whether the walk stopped goes unread: one node lies far within its + // bounds, its values nesting no deeper than the compiler's own limit. + ir.WalkValues(typeDef, "", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + owner, _, isField := at.Field() + if (!isField || owner != docsType) && v.Type() != deprecationType { + return true + } + if item, given := annotationAt(v, at); given { + items = append(items, item) + } + return false + })) + return items +} + +// annotationAt returns the annotation v, a member of a Docs or a Deprecation, +// gives at at, and false where the encoding omits it, being empty, or cannot +// write it. +func annotationAt(v reflect.Value, at ir.WalkPath) (givenAnnotation, bool) { + if v.IsZero() || (v.Kind() == reflect.Slice && v.Len() == 0) { + return givenAnnotation{}, false + } + value, err := json.Marshal(v.Interface(), json.Deterministic(true)) + if err != nil { + return givenAnnotation{}, false + } + return givenAnnotation{at: at.String(), value: string(value)}, true +} diff --git a/compilers/openapi/internal/schema/carriedannotations_internal_test.go b/compilers/openapi/internal/schema/carriedannotations_internal_test.go new file mode 100644 index 000000000..607ede7d5 --- /dev/null +++ b/compilers/openapi/internal/schema/carriedannotations_internal_test.go @@ -0,0 +1,41 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestAnnotationsOf_ReadsEachDocsMemberAndDeprecation pins the annotations a +// node gives: each member of a docs object its encoding writes, its own or a +// property's, and a deprecation, empty or not, each at its place with its +// value's encoding, and not a member spelt docs inside text kept verbatim, +// which is the source's, nor one the encoding cannot write; a node not held +// gives none. +func TestAnnotationsOf_ReadsEachDocsMemberAndDeprecation(t *testing.T) { + t.Parallel() + model := &ir.Model{ID: "type/m", Docs: ir.Docs{Summary: "title", Description: "about"}, + Deprecation: &ir.Deprecation{}, Unmodeled: ir.Unmodeled{"openapi:x-note": {Reason: ir.ReasonVendorExtension, + Value: ir.RawValue(`{"docs":{"description":"verbatim"}}`)}}, + Properties: []ir.Property{ + {ID: "property/m/a", WireName: "a", Type: ir.TypeRef{Target: "type/primitive/string"}, Docs: ir.Docs{Description: "member"}}, + {ID: "property/m/b", WireName: "b", Type: ir.TypeRef{Target: "type/primitive/string"}, Docs: ir.Docs{Description: "\xff"}}, + }} + + items := annotationsOf(model, true) + slices.SortFunc(items, func(a, b givenAnnotation) int { return strings.Compare(a.at, b.at) }) + assert.Equal(t, []givenAnnotation{ + {at: ".Deprecation", value: `{}`}, + {at: ".Docs.Description", value: `"about"`}, + {at: ".Docs.Summary", value: `"title"`}, + {at: ".Properties[0].Docs.Description", value: `"member"`}, + }, items) + assert.Empty(t, annotationsOf(nil, false), "a node not held") +} diff --git a/compilers/openapi/internal/schema/catchall.go b/compilers/openapi/internal/schema/catchall.go new file mode 100644 index 000000000..c64fce1fc --- /dev/null +++ b/compilers/openapi/internal/schema/catchall.go @@ -0,0 +1,130 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// catchAllSource names the schema object whose catch-all keywords a composed +// model types, and where it is written; own marks the position's own object. +// The zero catchAllSource names none. +type catchAllSource struct { + schema *statement.Schema + at jsontext.Pointer + own bool +} + +// entryAt reports whether c names the inline entry written at at. +func (c catchAllSource) entryAt(at jsontext.Pointer) bool { + return c.schema != nil && !c.own && c.at == at +} + +// catchAllSourceOf returns the schema object whose catch-all keywords the model +// composed from comp types (docs/compilers/openapi.md#additional-properties): +// the position's own, else the one inline entry writing one, so the catch-all +// has one source; two such entries give none. +func catchAllSourceOf(schema *statement.Schema, comp allOfComposition) catchAllSource { + if writesCatchAll(schema) { + return catchAllSource{schema: schema, at: comp.pointer, own: true} + } + var entry catchAllSource + entries := 0 + for _, schemaEntry := range comp.entries { + if schemaEntry.schema.Truth == statement.Stated && schemaEntry.schema.Ref == nil && writesCatchAll(schemaEntry.schema.Schema) { + entries++ + entry = catchAllSource{schema: schemaEntry.schema.Schema, at: schemaEntry.pointer} + } + } + if entries != 1 { + return catchAllSource{} + } + return entry +} + +// writesCatchAll reports whether schema writes a keyword typing members its +// properties do not name: additionalProperties, or patternProperties naming a +// pattern. +func writesCatchAll(schema *statement.Schema) bool { + return schema.ObjectKeywords().AdditionalProperties.SchemaValueForm() != statement.Unwritten || len(schema.ObjectKeywords().PatternProperties) > 0 +} + +// declaresMembers reports whether schema names a member its +// additionalProperties leaves alone: a property, or a pattern. +func declaresMembers(schema *statement.Schema) bool { + return len(schema.ObjectKeywords().Properties) > 0 || len(schema.ObjectKeywords().PatternProperties) > 0 +} + +// catchAllKeyword reports whether keyword is one the in-place merge takes off +// the entry closing the model (catchAllSourceOf, fillComposedAdditional). +func catchAllKeyword(keyword string) bool { + return keyword == "additionalProperties" || keyword == "patternProperties" +} + +// fillComposedAdditional fills model's openness and catch-all from the object +// catchAllSourceOf names. An entry's additionalProperties evaluates every +// member it could apply to, so it leaves an unevaluatedProperties: false +// beside the allOf saying nothing (JSON Schema 2020-12 §11.3). +func fillComposedAdditional(loweringContext lowering.Ctx, types *compile.Types, depth int, model *ir.Model, schema *statement.Schema, comp allOfComposition) []ir.Diagnostic { + if comp.catchAll.own && closedByFalseBesideMembers(comp) { + return keepUnclosing(loweringContext, model, schema, comp.pointer) + } + if comp.catchAll.own { + return fillCatchAll(loweringContext, types, depth, model, schema.ObjectKeywords().AdditionalProperties, schema, comp.pointer, closesAfterComposition(loweringContext, schema)) + } + + closes := closesAfterComposition(loweringContext, schema) + catchAll := comp.catchAll + if catchAll.schema == nil { + return fillCatchAll(loweringContext, types, depth, model, statement.Subschema{}, schema, comp.pointer, closes) + } + additionalProperties := catchAll.schema.ObjectKeywords().AdditionalProperties + return fillCatchAll(loweringContext, types, depth, model, additionalProperties, catchAll.schema, catchAll.at, closes && additionalProperties.SchemaValueForm() == statement.Unwritten) +} + +// closedByFalseBesideMembers reports whether comp holds a `false` entry beside +// one declaring members, so the model admits no instance and the position's +// closure types nothing of it. +func closedByFalseBesideMembers(comp allOfComposition) bool { + return slices.ContainsFunc(comp.entries, func(entry allOfEntry) bool { return entry.schema.Truth.ReadsFalse() }) && + slices.ContainsFunc(comp.entries, func(entry allOfEntry) bool { + return stated(entry.schema.Schema) && declaresMembers(entry.schema.Schema) + }) +} + +// diagComposedCatchAll keeps and reports what the model's closure reads of the +// members the composition brings (diagCatchAllScope), and reports a $ref +// entry's closed model refusing a member another conjunct requires +// (diagClosedTargets). +func diagComposedCatchAll(loweringContext lowering.Ctx, model *ir.Model, schema *statement.Schema, comp allOfComposition) []ir.Diagnostic { + diags := diagClosedTargets(loweringContext, schema, comp) + if comp.catchAll.own && closedByFalseBesideMembers(comp) { + return diags + } + return append(diags, diagCatchAllScope(loweringContext, &model.Unmodeled, comp.catchAll, func() composedMembers { + return membersOfConjunction(loweringContext, schema) + })...) +} + +// keepUnclosing keeps verbatim the position's additionalProperties where an +// allOf entry beside it declares members: the keyword reads only schema's own +// properties, so it also applies to those members, and typing it on the model +// would close or type members it never read. The model stays open. +func keepUnclosing(loweringContext lowering.Ctx, model *ir.Model, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + kept, diags := keepSchemaKeyword(loweringContext, &model.Unmodeled, schema, "additionalProperties", ir.ReasonDegradedLowering, pointer) + if !kept { + return diags + } + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, "%s", + "additionalProperties reads only the properties and patternProperties written beside it, so it also applies "+ + "to the members an allOf entry here declares; the composed model does not take it, and it is kept verbatim "+ + "under Unmodeled")) +} diff --git a/compilers/openapi/internal/schema/catchall_internal_test.go b/compilers/openapi/internal/schema/catchall_internal_test.go new file mode 100644 index 000000000..2d7b3174a --- /dev/null +++ b/compilers/openapi/internal/schema/catchall_internal_test.go @@ -0,0 +1,192 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "cmp" + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestCloserOf_NamesTheObjectWhoseClosureTypesTheModel pins which schema object +// of a composition catchAllSourceOf names: the position where it writes a +// catch-all keyword, else the one inline entry writing one, whatever members +// the other conjuncts declare, which it also applies to, else none (GitHub +// #2047). "own" names the position, "" none, and any other want the entry's +// path from it. +func TestCloserOf_NamesTheObjectWhoseClosureTypesTheModel(t *testing.T) { + t.Parallel() + const ref = "{$ref: '#/components/schemas/U'}" + for _, testCase := range []struct{ name, m, want string }{ + {"the position, no member declared", "{allOf: [" + ref + "], additionalProperties: false}", "own"}, + {"the position, declaring its own", "{properties: {a: {}}, additionalProperties: false, allOf: [" + ref + "]}", "own"}, + {"the position, patterns alone", "{allOf: [" + ref + "], patternProperties: {'^x': {}}}", "own"}, + {"the position, before an entry", "{allOf: [{additionalProperties: true}], additionalProperties: false}", "own"}, + {"the position, an entry declaring", "{allOf: [{properties: {b: {}}}], additionalProperties: false}", "own"}, + {"patterns, an entry declaring", "{allOf: [{properties: {b: {}}}], patternProperties: {'^x': {}}}", "own"}, + {"an entry, no member declared", "{allOf: [" + ref + ", {additionalProperties: false}]}", "allOf/1"}, + {"an entry, declaring its own", "{allOf: [{properties: {b: {}}, additionalProperties: false}, " + ref + "]}", "allOf/0"}, + {"an entry, an empty properties beside", "{allOf: [{properties: {}}, {additionalProperties: false}]}", "allOf/1"}, + {"an entry, a boolean beside", "{allOf: [true, {additionalProperties: false}]}", "allOf/1"}, + {"a wrapper", "{allOf: [{additionalProperties: false, allOf: [" + ref + "]}]}", "allOf/0"}, + {"an entry, another declaring", "{allOf: [{properties: {b: {}}}, {additionalProperties: false}]}", "allOf/1"}, + {"an entry, the position declaring", "{properties: {a: {}}, allOf: [{additionalProperties: false}]}", "allOf/0"}, + {"an entry, a $ref entry's own members", "{allOf: [{$ref: '#/components/schemas/U', properties: {b: {}}}, {additionalProperties: false}]}", "allOf/1"}, + {"an entry, a $ref entry's own closure, a second", "{allOf: [{$ref: '#/components/schemas/U', additionalProperties: false}, {additionalProperties: false}]}", ""}, + {"an entry, a closure beside its $ref", "{allOf: [{$ref: '#/components/schemas/U', additionalProperties: false}]}", "allOf/0"}, + {"an entry, its union's branch declaring", "{allOf: [{additionalProperties: false, oneOf: [{properties: {t: {}}}, {properties: {u: {}}}]}, " + ref + "]}", "allOf/0"}, + {"an entry, the position's union declaring", "{anyOf: [{properties: {t: {}}}], allOf: [{additionalProperties: false}]}", "allOf/0"}, + {"an entry, a union of references beside", "{allOf: [{additionalProperties: false, oneOf: [" + ref + ", " + ref + "]}]}", "allOf/0"}, + {"two entries", "{allOf: [{additionalProperties: true}, {additionalProperties: false}]}", ""}, + {"none written", "{allOf: [" + ref + ", {properties: {b: {}}}]}", ""}, + } { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " U: {type: object}\n M: "+testCase.m+"\n")) + decl, ok := lowerer.Doc.Components.Schemas.Get("M") + require.True(t, ok) + schema := lowerer.Ctx.Statements().Of(decl).Schema + const at = jsontext.Pointer("/components/schemas/M") + got := catchAllSourceOf(schema, allOfEntries(lowerer.Ctx, schema, at)) + switch testCase.want { + case "own": + assert.True(t, got.own) + assert.Same(t, schema, got.schema) + assert.Equal(t, at, got.at) + assert.False(t, got.entryAt(at), "the position is no entry") + case "": + assert.False(t, got.own) + assert.Nil(t, got.schema) + assert.Empty(t, got.at) + default: + assert.False(t, got.own) + assert.NotNil(t, got.schema) + assert.Equal(t, at+"/"+jsontext.Pointer(testCase.want), got.at) + assert.True(t, got.entryAt(at+"/"+jsontext.Pointer(testCase.want))) + assert.False(t, got.entryAt(at), "the position is no entry") + } + }) + } +} + +// TestKeepUnclosing_AClosureBesideAnEntrysMembersIsKeptOnce pins that an +// additionalProperties beside an allOf an entry of which declares members +// types the model's catch-all and is also kept once under its own key, at the +// keyword, with one info there (GitHub #2047). +func TestKeepUnclosing_AClosureBesideAnEntrysMembersIsKeptOnce(t *testing.T) { + t.Parallel() + doc, diags := LowerSpec(t, openapitest.ComponentSpec(" M: {allOf: [{properties: {a: {type: string}}}], additionalProperties: {type: string}}\n")) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := doc.Types["type/openapi/components/schemas/M"].(*ir.Model) + require.True(t, ok, "M is a model") + require.NotNil(t, model.AdditionalProperties, "the model takes the catch-all") + kept, ok := model.Unmodeled["openapi:additionalProperties"] + require.True(t, ok, "the keyword is kept; got %+v", model.Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) + assert.Equal(t, jsontext.Pointer("/components/schemas/M/additionalProperties"), kept.Provenance.Pointer) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/M/additionalProperties"}, openapitest.PointersOf(diags, diag.DegradedConstruct), + "one info, at the keyword") +} + +// TestKeepUnclosing_AFalseEntryKeepsTheClosureOnce pins that a false entry +// closing the model keeps an additionalProperties beside an allOf an entry of +// which declares members no second time: it is kept once under its own key, +// at the keyword, with one info at the position. +func TestKeepUnclosing_AFalseEntryKeepsTheClosureOnce(t *testing.T) { + t.Parallel() + for name, allOf := range map[string]string{ + "and a false entry closing": "[false, {properties: {a: {type: string}}}]", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := LowerSpec(t, openapitest.ComponentSpec(" M: {allOf: "+allOf+", additionalProperties: {type: string}}\n")) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := doc.Types["type/openapi/components/schemas/M"].(*ir.Model) + require.True(t, ok, "M is a model") + assert.Nil(t, model.AdditionalProperties, "the model takes no catch-all") + kept, ok := model.Unmodeled["openapi:additionalProperties"] + require.True(t, ok, "the keyword is kept; got %+v", model.Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) + assert.Equal(t, jsontext.Pointer("/components/schemas/M/additionalProperties"), kept.Provenance.Pointer) + assert.Len(t, openapitest.PointersOf(diags, diag.DegradedConstruct), 1, "one info, at the position") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/M"), + "also applies to the members an allOf entry here declares") + }) + } +} + +// TestKeepUnclosing_AClosureNoJSONHoldsReportsItselfAlone pins a closure the +// model does not take whose value no JSON holds: it is kept nowhere, and its +// own failure to keep is the one report, no info saying it was kept. +func TestKeepUnclosing_AClosureNoJSONHoldsReportsItselfAlone(t *testing.T) { + t.Parallel() + doc, diags := LowerSpec(t, openapitest.ComponentSpec( + " M: {allOf: [false, {properties: {a: {type: string}}}], additionalProperties: {type: string, foo: .inf}}\n")) + model, ok := doc.Types["type/openapi/components/schemas/M"].(*ir.Model) + require.True(t, ok, "M is a model") + assert.NotContains(t, model.Unmodeled, "openapi:additionalProperties") + for _, diagnostic := range diags { + assert.NotContains(t, diagnostic.Message, "also applies to the members an allOf entry here declares", "no keep is said") + } +} + +// TestCatchAllRejects_APatternCatchAllRejectsNoBranchsMember pins a closure +// written as patternProperties alone beside a union of branches each +// requiring a member no pattern matches: no additionalProperties refuses the +// member, so every branch lives and nothing warns. +func TestCatchAllRejects_APatternCatchAllRejectsNoBranchsMember(t *testing.T) { + t.Parallel() + doc, diags := LowerSpec(t, openapitest.ComponentSpec(" C: {type: object, patternProperties: {'^x': {type: string}}, "+ + "oneOf: [{required: [a], properties: {a: {type: string}}}, {required: [b], properties: {b: {type: integer}}}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + union, ok := doc.Types["type/openapi/components/schemas/C"].(*ir.Union) + require.True(t, ok, "both branches live; got %T", doc.Types["type/openapi/components/schemas/C"]) + assert.Len(t, union.Variants, 2) + for _, diagnostic := range diags { + assert.NotEqual(t, diag.UnsatisfiableSchema, diagnostic.Code, diagnostic.Message) + } +} + +// TestDiagClosureScope_AsksForTheMembersOnlyWhereTheClosureReadsThem pins the +// members a closure reads, which collecting reads the whole composition below +// the model: asked once of a closure refusing a member or writing patterns, +// and never of none, nor of one admitting every member (GitHub #1993). +func TestDiagClosureScope_AsksForTheMembersOnlyWhereTheClosureReadsThem(t *testing.T) { + t.Parallel() + for _, testCase := range []struct { + name, m string + asks int + }{ + {"no closure", "", 0}, + {"a closure admitting every member", "{type: object, additionalProperties: true}", 0}, + {"an empty closure", "{type: object, additionalProperties: {}}", 0}, + {"a closure refusing every member", "{type: object, additionalProperties: false}", 1}, + {"a closure typing its members", "{type: object, additionalProperties: {type: string}}", 1}, + {"patterns", "{type: object, patternProperties: {'^x': {}}}", 1}, + } { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " M: {type: object}\n C: "+cmp.Or(testCase.m, "{}")+"\n")) + var reached catchAllSource + if testCase.m != "" { + decl, ok := lowerer.Doc.Components.Schemas.Get("C") + require.True(t, ok) + reached = catchAllSource{schema: lowerer.Ctx.Statements().Of(decl).Schema, at: "/components/schemas/C", own: true} + } + asks := 0 + diagCatchAllScope(lowerer.Ctx, &ir.Unmodeled{}, reached, func() composedMembers { + asks++ + return newComposedMembers() + }) + assert.Equal(t, testCase.asks, asks) + }) + } +} diff --git a/compilers/openapi/internal/schema/catchall_scope_test.go b/compilers/openapi/internal/schema/catchall_scope_test.go new file mode 100644 index 000000000..0fcc1120b --- /dev/null +++ b/compilers/openapi/internal/schema/catchall_scope_test.go @@ -0,0 +1,214 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// TestCatchAllScope_WhatItRefusesOfComposedMembersIsSaid holds a closure over +// the members a composition brings +// (docs/compilers/openapi.md#additional-properties): a typed catch-all refusing +// a required member's type, or false refusing a required member, admits no +// instance, warned at the keyword; one refusing a member no conjunct requires +// draws the info; a closure refusing a name only an entry requires, declared +// nowhere and matching no pattern, warns too; a pattern is kept where a +// composed member matches it and reports nothing where none does; and a closed +// model a $ref brings, declaring no member another entry requires, draws one +// warning at the position. +func TestCatchAllScope_WhatItRefusesOfComposedMembersIsSaid(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` N: {type: object, properties: {n: {type: integer}}} + Shut: {type: object, properties: {s: {type: string}}, additionalProperties: false} + TypedRequired: {allOf: [{$ref: '#/components/schemas/N'}, {required: [n]}], additionalProperties: {type: string}} + TypedOptional: {allOf: [{$ref: '#/components/schemas/N'}], additionalProperties: {type: string}} + Undeclared: {allOf: [{$ref: '#/components/schemas/N'}, {required: [z]}], additionalProperties: false} + Matched: {allOf: [{$ref: '#/components/schemas/N'}], patternProperties: {'^n': {type: integer}}} + Unmatched: {allOf: [{$ref: '#/components/schemas/N'}], patternProperties: {'^q': {type: integer}}} + ClosedTarget: {allOf: [{$ref: '#/components/schemas/Shut'}, {required: [t]}]} + FalseRequired: {allOf: [{$ref: '#/components/schemas/N'}, {required: [n]}], additionalProperties: false} + PatternMissed: {allOf: [{$ref: '#/components/schemas/N'}, {required: [z]}], additionalProperties: false, patternProperties: {'^q': {}}} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, want := range map[string]struct { + code, at string + kept string + }{ + "TypedRequired": {diag.UnsatisfiableSchema, "/additionalProperties", "openapi:additionalProperties"}, + "TypedOptional": {diag.DegradedConstruct, "/additionalProperties", "openapi:additionalProperties"}, + "Undeclared": {diag.UnsatisfiableSchema, "/additionalProperties", "openapi:additionalProperties"}, + "FalseRequired": {diag.UnsatisfiableSchema, "/additionalProperties", "openapi:additionalProperties"}, + "PatternMissed": {diag.UnsatisfiableSchema, "/additionalProperties", "openapi:additionalProperties"}, + "Matched": {diag.DegradedConstruct, "/patternProperties", "openapi:patternProperties"}, + } { + at := "/components/schemas/" + name + want.at + assert.True(t, openapitest.HasDiagCodeAt(diags, want.code, at), "%s: %s at %s", name, want.code, at) + assert.Contains(t, typeByName(doc, name).Common().Unmodeled, want.kept, name) + } + assert.NotContains(t, typeByName(doc, "Unmatched").Common().Unmodeled, "openapi:patternProperties", + "a pattern no member matches reports nothing") + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Unmatched/patternProperties")) + closed := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/ClosedTarget") + require.Len(t, closed, 1, "the closed target refuses the member the entry requires") + assert.Contains(t, closed[0].Message, "#/components/schemas/Shut") + assert.Equal(t, ir.SeverityWarning, closed[0].Severity) +} + +// TestUnionByKind_ATypeListBranchSplitsOverItsKinds holds a body beside a union +// of an object and a type list of a string and an integer: the body +// distributes by kind, the object branch's variant composing the members, and +// the type list's a Union of its kinds, the string holding the body's string +// bound and the integer its own primitive. +func TestUnionByKind_ATypeListBranchSplitsOverItsKinds(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Obj: {type: object, properties: {a: {type: string}}} + U: {properties: {p: {type: string}}, minLength: 2, oneOf: [{$ref: '#/components/schemas/Obj'}, {type: [string, integer]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + union, ok := typeByName(doc, "U").(*ir.Union) + require.True(t, ok, "U distributes by kind; got %T", typeByName(doc, "U")) + require.Len(t, union.Variants, 2) + split, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Union) + require.True(t, ok, "the type list's variant is a Union of its kinds; got %T", doc.Types[union.Variants[1].Type.Target]) + require.Len(t, split.Variants, 2) + text, ok := doc.Types[split.Variants[0].Type.Target].(*ir.Scalar) + require.True(t, ok, "the string kind holds the body's string bound") + require.NotNil(t, text.Constraints) + assert.Equal(t, int64(2), *text.Constraints.MinLength) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInteger), split.Variants[1].Type.Target, "no body keyword applies to the integer") +} + +// TestUnionByKind_ATypeListHoldingAnObjectSplitsOverItsKinds holds a body +// naming no kind beside a union of a type list of an object and a string and +// an integer: the list's variant is a Union of its kinds, the object's a model +// composing the body's member over the list's own object, the string's the +// body's string bound over the list's own string, keeping its own bound, and +// the Union saying what the list says; the integer is its primitive. A $ref +// to the branch lowers it apart, read whole, keeping none of its bounds. +func TestUnionByKind_ATypeListHoldingAnObjectSplitsOverItsKinds(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` R: {$ref: '#/components/schemas/U/oneOf/0'} + U: + properties: {a: {type: string}} + minLength: 3 + oneOf: [{type: [object, string], maxLength: 9, description: listed}, {type: integer}] +`)) + openapitest.RequireNoErrorDiags(t, diags) + branch, ok := doc.Types["type/anonymous/components/schemas/U/oneOf/0"].(*ir.Union) + require.True(t, ok, "the $ref'd branch lowers at its own pointer") + assert.Empty(t, branch.Unmodeled, "and reads its bounds there") + union, ok := typeByName(doc, "U").(*ir.Union) + require.True(t, ok, "U distributes by kind; got %T", typeByName(doc, "U")) + require.Len(t, union.Variants, 2) + assert.Empty(t, union.Unmodeled, "every keyword of the body has its kind's variant") + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInteger), union.Variants[1].Type.Target) + split, ok := doc.Types[union.Variants[0].Type.Target].(*ir.Union) + require.True(t, ok, "the type list's variant is a Union of its kinds; got %T", doc.Types[union.Variants[0].Type.Target]) + assert.Equal(t, "listed", split.Docs.Description, "the Union says what the list says") + require.Len(t, split.Variants, 2) + object, ok := doc.Types[split.Variants[0].Type.Target].(*ir.Model) + require.True(t, ok, "the object kind composes the body; got %T", doc.Types[split.Variants[0].Type.Target]) + require.Len(t, object.Properties, 1) + assert.Equal(t, "a", object.Properties[0].Name.Source) + require.NotNil(t, object.Base, "over the list's own object") + assert.Nil(t, object.Constraints, "the body's string bound is no object's") + text, ok := doc.Types[split.Variants[1].Type.Target].(*ir.Scalar) + require.True(t, ok, "the string kind holds the body's string bound") + require.NotNil(t, text.Constraints) + assert.Equal(t, int64(3), *text.Constraints.MinLength) + require.NotNil(t, text.Base) + own, ok := doc.Types[text.Base.Target].(*ir.Scalar) + require.True(t, ok, "over the list's own string, which keeps its bound; got %T", doc.Types[text.Base.Target]) + require.NotNil(t, own.Constraints) + assert.Equal(t, int64(9), *own.Constraints.MaxLength) +} + +// TestUnionByKind_NoSourcePointerNamesATypesNode holds that the node a split +// type list lowers a type to, at /type/-/ beneath the +// variant's key, is named by no pointer the source writes: a $ref to it +// resolves to nothing, reported, at a component and a property alike +// (docs/ir/identity.md#the-id-grammar). +func TestUnionByKind_NoSourcePointerNamesATypesNode(t *testing.T) { + t.Parallel() + const typesNode = "'#/components/schemas/U/oneOf/0/type/-/0'" + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` R: {$ref: `+typesNode+`} + H: {type: object, properties: {r: {$ref: `+typesNode+`}}} + U: + properties: {a: {type: string}} + minLength: 3 + oneOf: [{type: [object, string]}, {type: integer}] +`)) + require.Contains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/U/oneOf/0/type/-/0"), "the split puts its object there") + for _, at := range []string{"/components/schemas/R", "/components/schemas/H/properties/r"} { + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnresolvedRef, at), "%s names nothing", at) + } + holder, ok := typeByName(doc, "H").(*ir.Model) + require.True(t, ok) + require.Len(t, holder.Properties, 1) + assert.NotEqual(t, ir.TypeID("type/anonymous/components/schemas/U/oneOf/0/type/-/0"), holder.Properties[0].Type.Target, + "no reference reaches the split's node") +} + +// TestCatchAllScope_EveryBranchRefusedLeavesTheModel holds a union every +// branch of which requires a member the closure beside it refuses, beside the +// object or beside an allOf of it: the position is the closed model keeping +// the union, with one warning naming each branch and the members it requires +// (docs/compilers/openapi.md#union-beside-structure). +func TestCatchAllScope_EveryBranchRefusedLeavesTheModel(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Flat: {type: object, properties: {a: {type: string}}, additionalProperties: false, oneOf: [{required: [z]}, {required: [y]}]} + Beside: {allOf: [{type: object, properties: {a: {type: string}}}], additionalProperties: false, oneOf: [{required: [z]}, {required: [y]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Flat", "Beside"} { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s is the closed model; got %T", name, typeByName(doc, name)) + assert.Equal(t, ir.ReasonDegradedLowering, model.Unmodeled["openapi:oneOf"].Reason, name) + warned := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name) + require.Len(t, warned, 1, name) + assert.Contains(t, warned[0].Message, "oneOf/0: z; oneOf/1: y", name) + } +} + +// TestUnionBeside_WhatAnEntryWritesSitsWithTheUnion holds what an inline +// allOf entry writes beside a union at the schema: its discriminator routes +// the union, its bound is the string branch's under the split by kind, and +// its type naming null leaves null alone beside a $ref to null +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_WhatAnEntryWritesSitsWithTheUnion(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Obj: {type: object, properties: {a: {type: string}}} + Null: {type: 'null'} + Routed: {allOf: [{discriminator: {propertyName: k}}], oneOf: [{$ref: '#/components/schemas/Obj'}]} + Split: {allOf: [{minLength: 2}], properties: {p: {type: string}}, oneOf: [{$ref: '#/components/schemas/Obj'}, {type: string}]} + NullLeft: {allOf: [{type: ['null']}], oneOf: [{$ref: '#/components/schemas/Null'}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + routed, ok := typeByName(doc, "Routed").(*ir.Union) + require.True(t, ok, "Routed is its union; got %T", typeByName(doc, "Routed")) + require.NotNil(t, routed.Discriminator) + assert.Equal(t, "k", routed.Discriminator.PropertyName) + + split, ok := typeByName(doc, "Split").(*ir.Union) + require.True(t, ok, "Split distributes by kind; got %T", typeByName(doc, "Split")) + require.Len(t, split.Variants, 2) + text, ok := doc.Types[split.Variants[1].Type.Target].(*ir.Scalar) + require.True(t, ok, "the string kind holds the entry's bound") + require.NotNil(t, text.Constraints) + assert.Equal(t, int64(2), *text.Constraints.MinLength) + assert.Empty(t, split.Unmodeled, "the bound is read, so nothing is kept") + + nullLeft, ok := typeByName(doc, "NullLeft").(*ir.Enum) + require.True(t, ok, "NullLeft is null alone; got %T", typeByName(doc, "NullLeft")) + assert.Empty(t, nullLeft.Members) + assert.Contains(t, nullLeft.Unmodeled, "openapi:oneOf") +} diff --git a/compilers/openapi/internal/schema/catchallreach.go b/compilers/openapi/internal/schema/catchallreach.go new file mode 100644 index 000000000..1a25f66c1 --- /dev/null +++ b/compilers/openapi/internal/schema/catchallreach.go @@ -0,0 +1,265 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "maps" + "regexp" + "slices" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// composedMembers is what the conjuncts of a composition declare of members: +// each member's declarations by name, and the names they require. +type composedMembers struct { + declared map[string][]*statement.Statement + required map[string]bool +} + +// newComposedMembers returns a set declaring and requiring no member. +func newComposedMembers() composedMembers { + return composedMembers{declared: map[string][]*statement.Statement{}, required: map[string]bool{}} +} + +// add records what schemaStatement declares and requires, through its flattened +// allOf and each $ref it or an entry writes, each schema read once (seen): the +// set of schemas a document holds bounds the walk. +func (m composedMembers) add(loweringContext lowering.Ctx, schemaStatement *statement.Statement, seen map[*statement.Schema]bool) { + stack := []*statement.Statement{schemaStatement} + for len(stack) > 0 { + next := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if next == nil || seen[next.Schema] { + continue + } + seen[next.Schema] = true + if target, _ := declaredOf(loweringContext, next); target != nil { + stack = append(stack, target) + continue + } + if !stated(next.Schema) { + continue + } + m.addOwn(loweringContext, next.Schema) + for _, entry := range loweringContext.Statements().Read(next.Schema).Entries { + stack = append(stack, loweringContext.Statements().Read(entry.Schema)) + } + } +} + +// addOwn records the members schema's own object declares and requires. +func (m composedMembers) addOwn(loweringContext lowering.Ctx, schema *statement.Schema) { + for _, property := range schema.ObjectKeywords().Properties { + m.declared[property.Name] = append(m.declared[property.Name], loweringContext.Statements().Subschema(property)) + } + for _, name := range schema.ObjectKeywords().Required { + m.required[name] = true + } +} + +// membersOfConjunction is what the composition of schema declares and +// requires, every conjunct outside its unions: schema's own object, each entry +// of its flattened allOf and what each $ref among them names. +func membersOfConjunction(loweringContext lowering.Ctx, schema *statement.Schema) composedMembers { + out := newComposedMembers() + seen := map[*statement.Schema]bool{} + out.addOwn(loweringContext, schema) + seen[schema] = true + for _, entry := range loweringContext.Statements().Read(schema).Entries { + out.add(loweringContext, loweringContext.Statements().Read(entry.Schema), seen) + } + return out +} + +// catchAllScope is what a catch-all source reads of the members a model holds: +// those its own object does not declare and none of its patterns matches, which +// it applies to as well, sorted, and those of them another conjunct requires +// that it refuses. +type catchAllScope struct { + appliesTo, rejected []string +} + +// catchAllScopeOf returns catchAll's scope over members, the members the model +// it types holds: the additionalProperties of catchAll's object applies to +// every member its properties and patternProperties leave (JSON Schema 2020-12 +// §10.3.2.3), refusing a required one where it is false, or where the member's +// declarations share no kind with what it admits. +func catchAllScopeOf(loweringContext lowering.Ctx, catchAll catchAllSource, members composedMembers) catchAllScope { + object := catchAll.schema.ObjectKeywords() + own := map[string]bool{} + for _, property := range object.Properties { + own[property.Name] = true + } + patterns := compiledPatterns(object.PatternProperties) + additionalProperties := loweringContext.Statements().Subschema(object.AdditionalProperties) + var out catchAllScope + for _, name := range slices.Sorted(maps.Keys(members.declared)) { + if own[name] || slices.ContainsFunc(patterns, func(pattern *regexp.Regexp) bool { return pattern.MatchString(name) }) { + continue + } + out.appliesTo = append(out.appliesTo, name) + if members.required[name] && rejects(loweringContext, additionalProperties, members.declared[name]) { + out.rejected = append(out.rejected, name) + } + } + for _, name := range slices.Sorted(maps.Keys(members.required)) { + if _, declared := members.declared[name]; !declared && !own[name] && additionalProperties.Truth.ReadsFalse() && + !slices.ContainsFunc(patterns, func(pattern *regexp.Regexp) bool { return pattern.MatchString(name) }) { + out.rejected = append(out.rejected, name) + } + } + return out +} + +// rejects reports whether additionalProperties refuses a member whose +// declarations are decls. +func rejects(loweringContext lowering.Ctx, additionalProperties *statement.Statement, decls []*statement.Statement) bool { + if additionalProperties.Truth.ReadsFalse() { + return true + } + if additionalProperties.Truth != statement.Stated { + return false + } + admits, _ := lowersTo(loweringContext, additionalProperties) + return slices.ContainsFunc(decls, func(decl *statement.Statement) bool { + kinds, inferred := lowersTo(loweringContext, decl) + return !inferred && kinds&admits == 0 + }) +} + +// compiledPatterns returns the patterns of patternProperties that compile, as +// Go reads them; one that does not matches no member. +func compiledPatterns(patternProperties []statement.Subschema) []*regexp.Regexp { + out := make([]*regexp.Regexp, 0, len(patternProperties)) + for _, sub := range patternProperties { + if pattern, err := regexp.Compile(sub.Name); err == nil { + out = append(out, pattern) + } + } + return out +} + +// diagCatchAllScope keeps verbatim on unmodeled, and reports +// (keepCatchAllKeyword), each catch-all keyword of catchAll whose scope reaches +// a member the model holds beside its own object's +// (docs/compilers/openapi.md#additional-properties): the model is the closed +// subtype its author means. membersOf is asked only where catchAll reads +// members, as it reads the whole composition below the model. +func diagCatchAllScope(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, catchAll catchAllSource, membersOf func() composedMembers) []ir.Diagnostic { + if !readsMembers(loweringContext, catchAll) { + return nil + } + members := membersOf() + var diags []ir.Diagnostic + additionalProperties := loweringContext.Statements().Subschema(catchAll.schema.ObjectKeywords().AdditionalProperties) + if additionalPropertiesRejects(additionalProperties) { + scope := catchAllScopeOf(loweringContext, catchAll, members) + diags = append(diags, keepCatchAllKeyword(loweringContext, unmodeled, catchAll, "additionalProperties", scope)...) + } + if matched := patternMatched(catchAll.schema, members); len(matched) > 0 { + diags = append(diags, keepCatchAllKeyword(loweringContext, unmodeled, catchAll, "patternProperties", catchAllScope{appliesTo: matched})...) + } + return diags +} + +// readsMembers reports whether catchAll writes a catch-all keyword reading the +// members its model holds. +func readsMembers(loweringContext lowering.Ctx, catchAll catchAllSource) bool { + if catchAll.schema == nil { + return false + } + object := catchAll.schema.ObjectKeywords() + return additionalPropertiesRejects(loweringContext.Statements().Subschema(object.AdditionalProperties)) || len(object.PatternProperties) > 0 +} + +// additionalPropertiesRejects reports whether additionalProperties may refuse a +// member: true and a schema saying nothing of an instance refuse none. +func additionalPropertiesRejects(additionalProperties *statement.Statement) bool { + return additionalProperties.Truth.ReadsFalse() || additionalProperties.Truth == statement.Stated && !additionalProperties.WritesOnlyIdentifierAndMetaKeywords() +} + +// patternMatched returns, sorted, the members of members and schema's own +// properties that a pattern of schema's patternProperties matches. +func patternMatched(schema *statement.Schema, members composedMembers) []string { + patterns := compiledPatterns(schema.ObjectKeywords().PatternProperties) + if len(patterns) == 0 { + return nil + } + names := slices.Collect(maps.Keys(members.declared)) + for _, property := range schema.ObjectKeywords().Properties { + names = append(names, property.Name) + } + var out []string + for _, name := range slices.Compact(slices.Sorted(slices.Values(names))) { + if slices.ContainsFunc(patterns, func(pattern *regexp.Regexp) bool { return pattern.MatchString(name) }) { + out = append(out, name) + } + } + return out +} + +// keepCatchAllKeyword keeps keyword, written by catchAll, verbatim on unmodeled +// where scope names a member it reads beside its own object's, and reports it +// once at the keyword. +func keepCatchAllKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, catchAll catchAllSource, keyword string, scope catchAllScope, +) []ir.Diagnostic { + if len(scope.appliesTo) == 0 && len(scope.rejected) == 0 { + return nil + } + at := catchAll.at + ids.Ptr(keyword) + _, diags := keepSchemaKeyword(loweringContext, unmodeled, catchAll.schema, keyword, ir.ReasonDegradedLowering, catchAll.at) + if len(scope.rejected) > 0 { + return append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, at, + "%s refuses %s, which another conjunct requires, so no instance satisfies this schema; the model "+ + "closes as written, and the keyword is kept verbatim under Unmodeled", keyword, strings.Join(scope.rejected, ", "))) + } + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, + "%s also applies to %s, which the composition brings and its own object does not declare; the model "+ + "takes it as the closed subtype written, and it is kept verbatim under Unmodeled", keyword, strings.Join(scope.appliesTo, ", "))) +} + +// diagClosedTargets is the one warning the composition of schema, written at +// pointer, draws where a model a $ref entry brings is closed by its own +// additionalProperties and declares no member another conjunct requires: no +// instance satisfies the two (docs/compilers/openapi.md#additional-properties). +func diagClosedTargets(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) []ir.Diagnostic { + required := map[string]bool{} + for _, name := range schema.ObjectKeywords().Required { + required[name] = true + } + for _, entry := range comp.entries { + if entry.schema.Ref == nil && stated(entry.schema.Schema) { + for _, name := range entry.schema.ObjectKeywords().Required { + required[name] = true + } + } + } + for _, entry := range comp.entries { + target, _ := declaredOf(loweringContext, entry.schema) + if target == nil || !stated(target.Schema) || !loweringContext.Statements().Subschema(target.ObjectKeywords().AdditionalProperties).Truth.ReadsFalse() { + continue + } + members := newComposedMembers() + members.add(loweringContext, target, map[*statement.Schema]bool{}) + var refused []string + for _, name := range slices.Sorted(maps.Keys(required)) { + if _, declared := members.declared[name]; !declared { + refused = append(refused, name) + } + } + if len(refused) > 0 { + _, ref := refSpelling(entry.schema) + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, comp.pointer, + "%s is closed by its own additionalProperties and declares no %s, which another conjunct of this allOf "+ + "requires, so no instance satisfies this schema", ref, strings.Join(refused, ", "))} + } + } + return nil +} diff --git a/compilers/openapi/internal/schema/closure.go b/compilers/openapi/internal/schema/closure.go deleted file mode 100644 index 4ad7e61ab..000000000 --- a/compilers/openapi/internal/schema/closure.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "encoding/json/jsontext" - "slices" - - "github.com/dexpace/morphic/compilers/compile" - "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" - "github.com/dexpace/morphic/ir" -) - -// closure names the schema object of a composition whose catch-all keywords -// its model types (closerOf), and the pointer it is written at: the position's -// own, which own marks, or an inline entry's. The zero closure names none. -type closure struct { - schema *statement.Schema - at jsontext.Pointer - own bool -} - -// entryAt reports whether c names the inline entry written at at. -func (c closure) entryAt(at jsontext.Pointer) bool { - return c.schema != nil && !c.own && c.at == at -} - -// closerOf returns the schema object of comp, the allOf schema writes, whose -// catch-all keywords the composed model types, and the zero closure where none -// does (docs/compilers/openapi.md#additional-properties). additionalProperties -// applies to the members its own object's properties and patternProperties -// leave (JSON Schema 2020-12 §10.3.2.3), so it types the model only where that -// object declares every member the conjunction declares, or none declares any. -// That object is the position, or else the one inline entry writing a catch-all -// keyword, so the model's catch-all has one source. A $ref entry's members -// beside its $ref count; its target's do not. -func closerOf(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) closure { - var entry, declarer closure - entries, declarers := 0, 0 - distributes := unionDeclares(loweringContext, schema) - for _, schemaEntry := range comp.entries { - if schemaEntry.schema.Truth != statement.Stated { - continue - } - at := closure{schema: schemaEntry.schema.Schema, at: schemaEntry.pointer} - if schemaEntry.schema.Ref == nil && writesCatchAll(schemaEntry.schema.Schema) { - entries++ - entry = at - } - if declaresMembers(schemaEntry.schema.Schema) { - declarers++ - declarer = at - } - distributes = distributes || unionDeclares(loweringContext, schemaEntry.schema.Schema) - } - - switch { - case writesCatchAll(schema): - if declarers == 0 { - return closure{schema: schema, at: comp.pointer, own: true} - } - return closure{} - case entries != 1 || declarers > 1 || (declarers == 1 && declarer != entry) || declaresMembers(schema) || distributes: - return closure{} - default: - return entry - } -} - -// writesCatchAll reports whether schema writes a keyword typing members its -// properties do not name: additionalProperties, or patternProperties naming a -// pattern. -func writesCatchAll(schema *statement.Schema) bool { - return schema.ObjectKeywords().AdditionalProperties.SchemaValueForm() != statement.Unwritten || len(schema.ObjectKeywords().PatternProperties) > 0 -} - -// declaresMembers reports whether schema names a member its -// additionalProperties leaves alone: a property, or a pattern. -func declaresMembers(schema *statement.Schema) bool { - return len(schema.ObjectKeywords().Properties) > 0 || len(schema.ObjectKeywords().PatternProperties) > 0 -} - -// unionDeclares reports whether an inline branch of the oneOf or anyOf schema -// writes declares a member, which the union distributes into the composed -// model, where an entry's additionalProperties applies to it as well. -func unionDeclares(loweringContext lowering.Ctx, schema *statement.Schema) bool { - choice := schema.ChoiceKeywords() - for _, sub := range slices.Concat(choice.OneOf, choice.AnyOf) { - b := loweringContext.Statements().Subschema(sub) - if b.Truth == statement.Stated && b.Ref == nil && declaresMembers(b.Schema) { - return true - } - } - return false -} - -// catchAllKeyword reports whether keyword is one the in-place merge takes off -// the entry closing the model (closerOf, fillComposedAdditional). -func catchAllKeyword(keyword string) bool { - return keyword == "additionalProperties" || keyword == "patternProperties" -} - -// fillComposedAdditional fills model's openness and catch-all from the schema -// object comp's closure names (closerOf). With none, the position's -// patternProperties still type the catch-all, as a pattern reads no member -// another object declares, and its additionalProperties is kept (keepUnclosing). -// The additionalProperties of an entry closing the model evaluates every -// member it could apply to, which leaves an unevaluatedProperties: false beside -// the allOf inert (JSON Schema 2020-12 §11.3), as one beside it would be. -func fillComposedAdditional(loweringContext lowering.Ctx, ts *compile.Types, depth int, model *ir.Model, schema *statement.Schema, comp allOfComposition) []ir.Diagnostic { - if comp.closer.own { - return fillAdditional(loweringContext, ts, depth, model, schema, comp.pointer) - } - - closes := annotation.ClosesAfterComposition(schema) - closure := comp.closer - if closure.schema == nil { - diags := keepUnclosing(loweringContext, model, schema, comp.pointer) - return append(diags, fillCatchAll(loweringContext, ts, depth, model, statement.Subschema{}, schema, comp.pointer, closes)...) - } - ap := closure.schema.ObjectKeywords().AdditionalProperties - return fillCatchAll(loweringContext, ts, depth, model, ap, closure.schema, closure.at, closes && ap.SchemaValueForm() == statement.Unwritten) -} - -// keepUnclosing keeps the additionalProperties schema, the position written at -// pointer, writes beside an allOf an entry of which declares members: the -// keyword reads schema's own properties alone, so it applies to those members -// too, and typing it on the model would close or type members it never read, -// where schema refuses an instance setting one the keyword does not admit. The -// model stays open and the keyword is reported. -func keepUnclosing(loweringContext lowering.Ctx, model *ir.Model, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - kept, diags := preserveSchemaKeyword(loweringContext, &model.Unmodeled, schema, "additionalProperties", ir.ReasonDegradedLowering, pointer) - if !kept { - return diags - } - return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, "%s", - "additionalProperties reads only the properties and patternProperties written beside it, so it also applies "+ - "to the members an allOf entry here declares; the composed model does not take it, and it is kept verbatim "+ - "under Unmodeled")) -} diff --git a/compilers/openapi/internal/schema/closure_internal_test.go b/compilers/openapi/internal/schema/closure_internal_test.go deleted file mode 100644 index 8734255b2..000000000 --- a/compilers/openapi/internal/schema/closure_internal_test.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "encoding/json/jsontext" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" - "github.com/dexpace/morphic/ir" -) - -// TestCloserOf_NamesTheObjectWhoseClosureTypesTheModel pins which schema object -// of a composition closerOf names: the position where it writes a catch-all -// keyword and no entry declares a member, else the one inline entry writing -// one where no other object declares a member, else none. "own" names the -// position, "" none, and any other want the entry's path from it. -func TestCloserOf_NamesTheObjectWhoseClosureTypesTheModel(t *testing.T) { - t.Parallel() - const ref = "{$ref: '#/components/schemas/U'}" - for _, tc := range []struct{ name, m, want string }{ - {"the position, no member declared", "{allOf: [" + ref + "], additionalProperties: false}", "own"}, - {"the position, declaring its own", "{properties: {a: {}}, additionalProperties: false, allOf: [" + ref + "]}", "own"}, - {"the position, patterns alone", "{allOf: [" + ref + "], patternProperties: {'^x': {}}}", "own"}, - {"the position, before an entry", "{allOf: [{additionalProperties: true}], additionalProperties: false}", "own"}, - {"the position, an entry declaring", "{allOf: [{properties: {b: {}}}], additionalProperties: false}", ""}, - {"patterns, an entry declaring", "{allOf: [{properties: {b: {}}}], patternProperties: {'^x': {}}}", ""}, - {"an entry, no member declared", "{allOf: [" + ref + ", {additionalProperties: false}]}", "allOf/1"}, - {"an entry, declaring its own", "{allOf: [{properties: {b: {}}, additionalProperties: false}, " + ref + "]}", "allOf/0"}, - {"an entry, an empty properties beside", "{allOf: [{properties: {}}, {additionalProperties: false}]}", "allOf/1"}, - {"an entry, a boolean beside", "{allOf: [true, {additionalProperties: false}]}", "allOf/1"}, - {"a wrapper", "{allOf: [{additionalProperties: false, allOf: [" + ref + "]}]}", "allOf/0"}, - {"an entry, another declaring", "{allOf: [{properties: {b: {}}}, {additionalProperties: false}]}", ""}, - {"an entry, the position declaring", "{properties: {a: {}}, allOf: [{additionalProperties: false}]}", ""}, - {"an entry, a $ref entry's own members", "{allOf: [{$ref: '#/components/schemas/U', properties: {b: {}}}, {additionalProperties: false}]}", ""}, - {"an entry, a $ref entry's own closure, a second", "{allOf: [{$ref: '#/components/schemas/U', additionalProperties: false}, {additionalProperties: false}]}", ""}, - {"an entry, a closure beside its $ref", "{allOf: [{$ref: '#/components/schemas/U', additionalProperties: false}]}", "allOf/0"}, - {"an entry, its union's branch declaring", "{allOf: [{additionalProperties: false, oneOf: [{properties: {t: {}}}, {properties: {u: {}}}]}, " + ref + "]}", ""}, - {"an entry, the position's union declaring", "{anyOf: [{properties: {t: {}}}], allOf: [{additionalProperties: false}]}", ""}, - {"an entry, a union of references beside", "{allOf: [{additionalProperties: false, oneOf: [" + ref + ", " + ref + "]}]}", "allOf/0"}, - {"two entries", "{allOf: [{additionalProperties: true}, {additionalProperties: false}]}", ""}, - {"none written", "{allOf: [" + ref + ", {properties: {b: {}}}]}", ""}, - } { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " U: {type: object}\n M: "+tc.m+"\n")) - decl, ok := lowerer.Doc.Components.Schemas.Get("M") - require.True(t, ok) - schema := lowerer.Ctx.Statements().Of(decl).Schema - const at = jsontext.Pointer("/components/schemas/M") - got := closerOf(lowerer.Ctx, schema, allOfEntries(lowerer.Ctx, schema, at)) - switch tc.want { - case "own": - assert.True(t, got.own) - assert.Same(t, schema, got.schema) - assert.Equal(t, at, got.at) - assert.False(t, got.entryAt(at), "the position is no entry") - case "": - assert.False(t, got.own) - assert.Nil(t, got.schema) - assert.Empty(t, got.at) - default: - assert.False(t, got.own) - assert.NotNil(t, got.schema) - assert.Equal(t, at+"/"+jsontext.Pointer(tc.want), got.at) - assert.True(t, got.entryAt(at+"/"+jsontext.Pointer(tc.want))) - assert.False(t, got.entryAt(at), "the position is no entry") - } - }) - } -} - -// TestKeepUnclosing_AClosureBesideAnEntrysMembersIsKeptOnce pins that an -// additionalProperties beside an allOf an entry of which declares members -// leaves the model open and is kept once under its own key, at the keyword, -// with one info at the position: a false entry closing the model keeps it no -// second time. -func TestKeepUnclosing_AClosureBesideAnEntrysMembersIsKeptOnce(t *testing.T) { - t.Parallel() - for name, allOf := range map[string]string{ - "an entry declaring": "[{properties: {a: {type: string}}}]", - "and a false entry closing": "[false, {properties: {a: {type: string}}}]", - } { - t.Run(name, func(t *testing.T) { - t.Parallel() - doc, diags := LowerSpec(t, openapitest.ComponentSpec(" M: {allOf: "+allOf+", additionalProperties: {type: string}}\n")) - openapitest.RequireNoErrorDiags(t, diags) - model, ok := doc.Types["type/openapi/components/schemas/M"].(*ir.Model) - require.True(t, ok, "M is a model") - assert.Nil(t, model.AdditionalProperties, "the model takes no catch-all") - kept, ok := model.Unmodeled["openapi:additionalProperties"] - require.True(t, ok, "the keyword is kept; got %+v", model.Unmodeled) - assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) - assert.Equal(t, jsontext.Pointer("/components/schemas/M/additionalProperties"), kept.Provenance.Pointer) - assert.Len(t, openapitest.PointersOf(diags, diag.DegradedConstruct), 1, "one info, at the position") - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/M"), - "also applies to the members an allOf entry here declares") - }) - } -} diff --git a/compilers/openapi/internal/schema/componentsettle.go b/compilers/openapi/internal/schema/componentsettle.go new file mode 100644 index 000000000..cb0ca8a2a --- /dev/null +++ b/compilers/openapi/internal/schema/componentsettle.go @@ -0,0 +1,73 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + + "github.com/dexpace/morphic/stronglyconnected" +) + +// closedComponent is a strongly connected component a walk has closed, handed +// to the function settling it. +type closedComponent[Vertex comparable] struct { + // members are the component's vertices in the order the walk met them, the + // first its root. The slice is the walk's own once the settling function + // returns. + members []Vertex + // rootEdges are the edges of the root, read once. + rootEdges []Vertex + // cyclic reports that a vertex of the component is reached from itself: it + // holds more than one, or its root has an edge to the root. + cyclic bool +} + +// componentWalk walks a graph by Tarjan's strongly connected components on +// stronglyconnected.Search's stacks, so it recurses nowhere. It reads each +// vertex's edges once and follows none to a vertex settled already. +type componentWalk[Vertex comparable] struct { + edgesOf func(Vertex) []Vertex + settled func(Vertex) bool + settle func(closedComponent[Vertex]) + // edges holds the edges of each vertex met whose component is not closed. + edges map[Vertex][]Vertex +} + +// walkComponents walks the graph edgesOf reads from root, and hands settle each +// component it closes, in an order that puts a component after every one its +// edges reach. A vertex settled (settled) is no part of the walk. +func walkComponents[Vertex comparable](root Vertex, edgesOf func(Vertex) []Vertex, settled func(Vertex) bool, + settle func(closedComponent[Vertex]), +) { + walk := &componentWalk[Vertex]{edgesOf: edgesOf, settled: settled, settle: settle, edges: map[Vertex][]Vertex{}} + stronglyconnected.NewSearch[Vertex](walk).From(root) +} + +// Edge returns the vertex from's edge at index, followed unless it is settled, +// reading from's edges the first time it is asked of it. +func (walk *componentWalk[Vertex]) Edge(from Vertex, index int) (to Vertex, follow, more bool) { + if index == 0 { + walk.edges[from] = walk.edgesOf(from) + } + edges := walk.edges[from] + if index == len(edges) { + return to, false, false + } + return edges[index], !walk.settled(edges[index]), true +} + +// LeaveVertex keeps nothing of a vertex left. +func (*componentWalk[Vertex]) LeaveVertex(Vertex) {} + +// CloseComponent settles the component members holds and forgets its edges. +func (walk *componentWalk[Vertex]) CloseComponent(members []Vertex) { + rootEdges := walk.edges[members[0]] + walk.settle(closedComponent[Vertex]{ + members: members, rootEdges: rootEdges, + cyclic: len(members) > 1 || slices.Contains(rootEdges, members[0]), + }) + for _, member := range members { + delete(walk.edges, member) + } +} diff --git a/compilers/openapi/internal/schema/conjunction_internal_test.go b/compilers/openapi/internal/schema/conjunction_internal_test.go deleted file mode 100644 index 37d5ebad9..000000000 --- a/compilers/openapi/internal/schema/conjunction_internal_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "testing" - - soa "github.com/speakeasy-api/openapi/openapi" - "github.com/stretchr/testify/assert" -) - -// TestConjunctsIn_ANilSchemaWritesNone pins the guards of the two readers of -// what a schema conjoins beside its own keywords: a nil schema writes no -// reference and no allOf. -func TestConjunctsIn_ANilSchemaWritesNone(t *testing.T) { - t.Parallel() - lowerer := NewRawLowerer(&soa.OpenAPI{}) - assert.Empty(t, conjunctsIn(lowerer.Ctx, nil)) - assert.Empty(t, allOfIn(nil)) -} diff --git a/compilers/openapi/internal/schema/const_enum_flat_test.go b/compilers/openapi/internal/schema/const_enum_flat_test.go new file mode 100644 index 000000000..2e1b844ac --- /dev/null +++ b/compilers/openapi/internal/schema/const_enum_flat_test.go @@ -0,0 +1,221 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestConstEnum_AFlatPairSharingNoMemberOfNoEnumTypeIsTheBottom holds a const +// and an enum written flat that share no member and no Enum types: lists, +// objects, or two value types. The position is the closed Model with no member +// a false schema lowers to, keeping each keyword under its own key, with one +// warning at the position naming that shape, and no degraded-construct report. +func TestConstEnum_AFlatPairSharingNoMemberOfNoEnumTypeIsTheBottom(t *testing.T) { + t.Parallel() + for name, testCase := range map[string]struct { + schema string + kept []string + }{ + "lists": {"{type: array, const: [1], enum: [[2]]}", []string{"openapi:const", "openapi:enum", "openapi:type"}}, + "objects": {"{type: object, const: {a: 1}, enum: [{a: 2}]}", []string{"openapi:const", "openapi:enum", "openapi:type"}}, + "two value types": {"{const: 2, enum: [a]}", []string{"openapi:const", "openapi:enum"}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+testCase.schema+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "S").(*ir.Model) + require.True(t, ok, "the bottom: got %T", typeByName(doc, "S")) + assert.Empty(t, model.Properties) + assert.Equal(t, ir.AdditionalClosed, model.Additional) + assert.Equal(t, testCase.kept, unmodeledKeys(model.Unmodeled)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/S"), + "it lowered as the closed model with no member a false schema lowers to") + assert.False(t, openapitest.HasDiag(diags, diag.DegradedConstruct), "%+v", diags) + }) + } +} + +// TestConstEnum_AFlatPairSharingAMemberIsTheConst holds a const whose value +// the enum beside it holds: the two share it, so the position is the const, +// keeping the enum it passed over with the report saying so. +func TestConstEnum_AFlatPairSharingAMemberIsTheConst(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {type: string, const: a, enum: [a, b]}\n")) + + assert.Empty(t, openapitest.PointersOf(diags, diag.UnsatisfiableSchema)) + literal, ok := typeByName(doc, "S").(*ir.Literal) + require.True(t, ok, "got %T", typeByName(doc, "S")) + assert.Equal(t, "a", literal.Value.String) + assert.Equal(t, []string{"openapi:enum"}, unmodeledKeys(literal.Unmodeled)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S"), + "it lowered as the const, with enum kept verbatim under Unmodeled") +} + +// TestConstEnum_AFlatPairTheTypeExcludesIsTheConst holds a const and an enum +// sharing no member, neither of the declared type: the type excludes them, so +// the position is the const, keeping the enum and the type, the const drawing +// its own finding that no instance matches it. +func TestConstEnum_AFlatPairTheTypeExcludesIsTheConst(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {type: string, const: 2, enum: [1]}\n")) + + literal, ok := typeByName(doc, "S").(*ir.Literal) + require.True(t, ok, "got %T", typeByName(doc, "S")) + assert.Equal(t, "2", literal.Value.Number.String()) + assert.Equal(t, []string{"openapi:enum", "openapi:type"}, unmodeledKeys(literal.Unmodeled)) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/S/const"}, openapitest.PointersOf(diags, diag.UnsatisfiableSchema)) + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/S"), 2, "what it keeps and what it passed over") +} + +// TestConstEnum_AFlatPairNoReadingConvertsLowersAsAtTheBase holds a const and +// an enum written flat, one holding a value no JSON holds: no reading compares +// the two, so each lowers as it did before the sets were compared, the const +// over an enum it cannot keep, the enum kept beside a const it cannot convert. +func TestConstEnum_AFlatPairNoReadingConvertsLowersAsAtTheBase(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Const: {const: a, enum: [.nan]}\n Enum: {const: .nan, enum: [a]}\n")) + + literal, ok := typeByName(doc, "Const").(*ir.Literal) + require.True(t, ok, "got %T", typeByName(doc, "Const")) + assert.Equal(t, "a", literal.Value.String) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, "/components/schemas/Const/enum"), "%+v", diags) + unconverted := typeByName(doc, "Enum") + require.NotNil(t, unconverted) + assert.Equal(t, ir.KindAny, unconverted.Kind(), "the top type") + assert.Equal(t, []string{"openapi:enum"}, unmodeledKeys(unconverted.Common().Unmodeled)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, "/components/schemas/Enum"), + "unconvertible value lowered as the top type") + assert.Empty(t, openapitest.PointersOf(diags, diag.UnsatisfiableSchema)) +} + +// TestAllOf_RefBooleanSetsSharingNoMemberAreTheClosedEmptyEnumOfBooleans holds +// two $ref entries whose targets are boolean value sets sharing no member: the +// closed empty Enum of booleans, keeping each $ref. +func TestAllOf_RefBooleanSetsSharingNoMemberAreTheClosedEmptyEnumOfBooleans(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` BA: {enum: [true]} + BB: {enum: [false]} + S: {allOf: [{$ref: '#/components/schemas/BA'}, {$ref: '#/components/schemas/BB'}]} +`)) + + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "S")) + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Equal(t, ir.PrimitiveBool, enum.ValueType) + assert.Equal(t, []string{"openapi:$ref/0", "openapi:$ref/1"}, unmodeledKeys(enum.Unmodeled)) +} + +// TestAllOf_ATypeExcludingTheOneMemberSetsShareIsNamedInTheReport holds two +// value sets sharing one member that the type beside the allOf excludes: no +// value is left, so the position is a use of the type, keeping each set, and +// the report says it lowered as that type. +func TestAllOf_ATypeExcludingTheOneMemberSetsShareIsNamedInTheReport(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {type: string, allOf: [{enum: [1, a]}, {enum: [1, b]}]}\n")) + + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "S")) + require.NotNil(t, scalar.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), scalar.Base.Target) + assert.Equal(t, []string{"openapi:allOf/0", "openapi:allOf/1"}, unmodeledKeys(scalar.Unmodeled)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/S"), + "; lowered as the string its type names — ") +} + +// TestAllOf_AnEntryNotAnObjectBesideARefSharingNullIsTheNull holds an entry +// declaring a string beside a $ref to an object, the two sharing the null each +// admits and nothing else: the position is the null type, as `{type: 'null'}` +// is, keeping the $ref and the bound with an info each, and no report says +// the conjuncts share no value (docs/compilers/openapi.md#allof-refinement). +func TestAllOf_AnEntryNotAnObjectBesideARefSharingNullIsTheNull(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` O: {type: [object, 'null'], properties: {a: {type: string}}} + S: {allOf: [{$ref: '#/components/schemas/O'}, {type: [string, 'null'], maxLength: 2}]} +`)) + + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "S")) + assert.Empty(t, enum.Members) + assert.ElementsMatch(t, []string{"openapi:$ref", "openapi:maxLength"}, unmodeledKeys(enum.Unmodeled)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S/allOf/0"), + "admit null alone together") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S/allOf/1"), + "no home for maxLength") + assert.Zero(t, openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning)) +} + +// TestAllOf_AnEntryNotAnObjectBesideAModelAndAUnionIsWarnedByKeyword holds the +// same entries beside a union, whose rules weigh the null the conjuncts share: +// the model composes the target, and the entry's keywords, kept apart, draw +// the warning that the entry is no object. +func TestAllOf_AnEntryNotAnObjectBesideAModelAndAUnionIsWarnedByKeyword(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` O: {type: [object, 'null'], properties: {a: {type: string}}} + S: + allOf: [{$ref: '#/components/schemas/O'}, {type: [string, 'null'], maxLength: 2}] + anyOf: [{required: [a]}, {required: [b]}] +`)) + + _, ok := typeByName(doc, "S").(*ir.Model) + require.True(t, ok, "got %T", typeByName(doc, "S")) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/S/allOf/1"), + "declares a type that is not an object, which the composed model asserts it is; type, maxLength, written on it, kept verbatim") +} + +// diagSites is diags as severity, code and pointer, sorted, without the +// reports the nullable-inference policy draws where it reads a null. +func diagSites(diags []ir.Diagnostic) []string { + var out []string + for _, diagnostic := range diags { + if diagnostic.Code != diag.InferredNullable { + out = append(out, string(diagnostic.Severity)+" "+diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + } + slices.Sort(out) + return out +} + +// TestNullable_AUnionBesideAPolicyNullPairLeavesThatNullAlone holds a union +// whose branches declare shape, beside an unread value set and an allOf whose +// conjuncts share only the null the nullable-inference policy reads on each: +// the policy reads that null for the whole conjunction, and no branch shares +// a value with the rest, so the position admits that null alone, the closed +// empty Enum keeping the union, its dead branches reported at the union and +// the position not, where its twin admitting the null in its own dialect +// keeps the null out and lowers as its value set. +func TestNullable_AUnionBesideAPolicyNullPairLeavesThatNullAlone(t *testing.T) { + t.Parallel() + const rest = "], enum: [.nan, null], oneOf: [{type: object, properties: {a: {type: string}}}, " + + "{type: object, properties: {b: {type: string}}}]}\n" + policy, policyDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " S: {allOf: [{type: string, nullable: true}, {type: integer, nullable: true}"+rest)) + equivalentDoc, equivalentDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " S: {allOf: [{type: [string, 'null']}, {type: [integer, 'null']}"+rest)) + + enum, ok := typeByName(policy, "S").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(policy, "S")) + assert.True(t, enum.Closed) + assert.Empty(t, enum.Members) + assert.Equal(t, []string{"openapi:oneOf"}, unmodeledKeys(enum.Unmodeled)) + assert.Equal(t, []string{"info " + diag.DegradedConstruct + " /components/schemas/S", + "warning " + diag.UnsatisfiableSchema + " /components/schemas/S/oneOf"}, diagSites(policyDiags), + "the dead branches are reported at the union, the position admitting the policy's null") + equivalent, ok := typeByName(equivalentDoc, "S").(*ir.Union) + require.True(t, ok, "the twin is its value set; got %T", typeByName(equivalentDoc, "S")) + assert.Contains(t, diagSites(equivalentDiags), "warning "+diag.UnsatisfiableSchema+" /components/schemas/S/enum/1", "the twin keeps its null member out") + assert.NotEmpty(t, equivalent.Variants) +} diff --git a/compilers/openapi/internal/schema/constraints.go b/compilers/openapi/internal/schema/constraints.go index 6acc2d139..f88b5ea1e 100644 --- a/compilers/openapi/internal/schema/constraints.go +++ b/compilers/openapi/internal/schema/constraints.go @@ -6,6 +6,7 @@ package schema import ( "cmp" "encoding/json/jsontext" + "maps" "slices" "strconv" "strings" @@ -22,32 +23,84 @@ import ( "github.com/dexpace/morphic/ir" ) -// ConstraintsOf returns the value constraints schema and its foldedEntries -// write that apply to a value of the kinds takes, the position's types', and of -// each writer's (writerTakes), or nil where they write none, for the node or -// carrier at pointer to hold (docs/compilers/openapi.md#constraints). A bound -// several write meets (merge.Constraints): a folded entry speaks only where -// its bounds meet every other writer's -// (docs/compilers/openapi.md#allof-inline-residue). Of two patterns the first -// writer's stands: schema's, but the position's own keywords' -// (annotation.FoldedAllOfEntry.Beside) before an inline principal's +// ConstraintsOf returns the value constraints schema and flattenedEntries, +// written at pointer, write for the kinds takes and each conjunct's +// (conjunctTakes) name, nil where none are, and keeps on unmodeled what no +// field holds (docs/compilers/openapi.md#constraints). takes is what the node's +// frame decided its homes hold, or the kinds of its own bounds where it reads +// no flattened entry. +func ConstraintsOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer, takes kindSet) (*ir.Constraints, []ir.Diagnostic) { + cons, kept, reports := boundsKept(loweringContext, *unmodeled, schema, flattenedEntries, pointer, takes) + *unmodeled = annotation.MergeUnmodeled(*unmodeled, kept) + return cons, reports.Diagnostics() +} + +// boundsKept returns ConstraintsOf's constraints and what no field holds, each +// report paired with its key; a key held already holds is kept by none. +// Conjuncts intersect (merge.Constraints), and of two patterns the first +// conjunct's is taken, the position's own before an inline principal's // (patternBeside). -// -// unmodeled is the Unmodeled of that node or carrier, keeping a 3.0 exclusive -// modifier with no bound beside it (GitHub #286). -func ConstraintsOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, foldedEntries []annotation.FoldedAllOfEntry, pointer jsontext.Pointer, takes kindSet) (*ir.Constraints, []ir.Diagnostic) { - cons, diags := constraintsAt(loweringContext, unmodeled, schema, pointer, boundsFor(takes)) - for _, foldedAllOfEntry := range foldedEntries { - foldedConstraints, foldedConstraintDiags := constraintsAt(loweringContext, unmodeled, foldedAllOfEntry.Node, foldedAllOfEntry.At, boundsFor(writerTakes(takes, foldedAllOfEntry.Node))) - diags = append(diags, foldedConstraintDiags...) - if foldedAllOfEntry.Beside { - cons = merge.Constraints(foldedConstraints, cons) +func boundsKept(loweringContext lowering.Ctx, held ir.Unmodeled, schema *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer, + takes kindSet, +) (*ir.Constraints, ir.Unmodeled, annotation.KeptReports) { + keepsPerConjunct := make([]conjunctKeeps, 1, 1+len(flattenedEntries)) + cons, reports := constraintsAt(loweringContext, &keepsPerConjunct[0].kept, schema, pointer, boundsFor(takes)) + keepsPerConjunct[0].reports, keepsPerConjunct[0].at = reports, pointer + for _, flattenedAllOfEntry := range flattenedEntries { + keeps := conjunctKeeps{at: flattenedAllOfEntry.At, beside: flattenedAllOfEntry.Beside} + flattenedConstraints, flattenedReports := constraintsAt(loweringContext, &keeps.kept, flattenedAllOfEntry.Node, flattenedAllOfEntry.At, boundsFor(conjunctTakes(takes, flattenedAllOfEntry.Node))) + keeps.reports = flattenedReports + keepsPerConjunct = append(keepsPerConjunct, keeps) + if flattenedAllOfEntry.Beside { + cons = merge.Constraints(flattenedConstraints, cons) continue } - cons = merge.Constraints(cons, foldedConstraints) + cons = merge.Constraints(cons, flattenedConstraints) } - writers := append([]annotation.FoldedAllOfEntry{{Node: schema, At: pointer}}, foldedEntries...) - return cons, append(diags, keepCounts(loweringContext, unmodeled, writers, takes)...) + kept, keptReports := keepsOnce(held, keepsPerConjunct) + flattenedConjuncts := append([]annotation.FlattenedAllOfEntry{{Node: schema, At: pointer}}, flattenedEntries...) + counts, countReports := keptCounts(loweringContext, flattenedConjuncts, takes) + return cons, annotation.MergeUnmodeled(kept, counts), append(keptReports, countReports...) +} + +// conjunctKeeps is what one conjunct of a node's bounds keeps of them, written +// at at, the position's own schema where beside says so, with the reports of +// its reading, each paired with its key. +type conjunctKeeps struct { + kept ir.Unmodeled + reports annotation.KeptReports + at jsontext.Pointer + beside bool +} + +// keepsOnce returns what keepsPerConjunct keep, each key kept and reported +// once, by the outermost conjunct, the position's own schema first, and a key +// held already holds by none; the reports stay in the order the conjuncts read. +func keepsOnce(held ir.Unmodeled, keepsPerConjunct []conjunctKeeps) (ir.Unmodeled, annotation.KeptReports) { + order := make([]int, 0, len(keepsPerConjunct)) + for i, keeps := range keepsPerConjunct { + if keeps.beside { + order = append([]int{i}, order...) + continue + } + order = append(order, i) + } + var kept ir.Unmodeled + for _, i := range order { + for _, key := range slices.Sorted(maps.Keys(keepsPerConjunct[i].kept)) { + _, before := held[key] + if _, again := kept[key]; before || again { + keepsPerConjunct[i].reports = slices.DeleteFunc(keepsPerConjunct[i].reports, func(report annotation.KeptReport) bool { return report.Key == key }) + continue + } + annotation.KeepInto(&kept, key, keepsPerConjunct[i].kept[key].Value, keepsPerConjunct[i].kept[key].Reason, keepsPerConjunct[i].kept[key].Provenance) + } + } + var reports annotation.KeptReports + for _, keeps := range keepsPerConjunct { + reports = append(reports, keeps.reports...) + } + return kept, reports } // modelTakes returns the kinds of takes whose value bounds a Model or a MapT @@ -59,47 +112,54 @@ func modelTakes(takes kindSet) kindSet { return takes & kindObject } -// carriesNumberAsText reports whether td is a Scalar over a number written as -// its text (scalarTypeID), whose Constraints would speak of the number -// (docs/ir/constraints.md#constraints). Every value bound written beside it -// bounds something else, the text's length or pattern or an instance of -// another kind than the string JSON Schema applies it to, so it holds none -// (keepTextBounds). -func carriesNumberAsText(td ir.TypeDef) bool { - sc, ok := td.(*ir.Scalar) - return ok && sc != nil && sc.Encoding != nil && sc.Encoding.Name == numberTextEncoding && - sc.Encoding.WireType != nil -} - -// carriesText reports whether the Scalar a type st that schema writes lowers -// to, taking format, is one carriesNumberAsText holds, read off the shape -// scalarTypeID builds it by. -func carriesText(schema *statement.Schema, st statement.JSONSchemaTypeName, format string) bool { - shape := scalarShapeOf(schema, st, format) - return shape.format == numberTextEncoding && shape.wire != nil -} - // keepTextBounds keeps each of bounds, value bounds schema writes, verbatim on -// unmodeled, under openapi: with no_ir_home, for a position carrying a -// number as text, whose Constraints hold none (carriesNumberAsText), with an -// info at each: those written beside the position's own keywords, and those an -// inline allOf entry keeps (recordOwnKeywords). The node keeps them, and a -// carrier of it keeps none (CarrierConstraintsOf). -func keepTextBounds(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, bounds []string, pointer jsontext.Pointer) []ir.Diagnostic { +// unmodeled under openapi: with no_ir_home, with an info at each, for +// a position whose value is text of another kind, root says which, so its +// Constraints hold none (boundRoot). Only the node or carrier holding the +// position's bounds keeps them. +func keepTextBounds(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, bounds []string, pointer jsontext.Pointer, + root boundRoot, +) []ir.Diagnostic { var diags []ir.Diagnostic for _, keyword := range bounds { - kept, keptDiags := preserveSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonNoIRHome, pointer) + kept, keptDiags := keepSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonNoIRHome, pointer) diags = append(diags, keptDiags...) if kept { - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer+ids.Ptr(keyword), - "%s bounds no number written as text, whose Constraints speak of the number: a length or a "+ - "pattern bounds the text, and any other bound no string instance; kept verbatim under Unmodeled", - keyword)) + diags = append(diags, textBoundKept(loweringContext, keyword, pointer, root)) } } return diags } +// keepTextBoundAs is keepTextBounds for one bound, keyword, kept under key. +func keepTextBoundAs(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword, key string, pointer jsontext.Pointer, + root boundRoot, +) []ir.Diagnostic { + kept, diags := annotation.KeepNodeInto(unmodeled, key, keyNode(schema, keyword), ir.ReasonNoIRHome, loweringContext.Place().At(pointer+ids.Ptr(keyword))) + if kept { + diags = append(diags, textBoundKept(loweringContext, keyword, pointer, root)) + } + return diags +} + +// textBoundKept reports keyword, a bound written at pointer of text of root's +// kind, kept verbatim (keepTextBounds). +func textBoundKept(loweringContext lowering.Ctx, keyword string, pointer jsontext.Pointer, root boundRoot) ir.Diagnostic { + return loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, pointer+ids.Ptr(keyword), "%s%s; kept verbatim under Unmodeled", keyword, root.boundsNone(keyword)) +} + +// keepIntersectedTextBound keeps intersectionValue, the value the conjuncts of +// the bound keyword intersect in that none of them writes, as keepTextBounds +// keeps a written one, with an info naming the value. +func keepIntersectedTextBound(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, keyword string, intersectionValue ir.RawValue, pointer jsontext.Pointer, + root boundRoot, +) []ir.Diagnostic { + at := pointer + ids.Ptr(keyword) + annotation.KeepInto(unmodeled, annotation.EntryKey("", keyword), intersectionValue, ir.ReasonNoIRHome, loweringContext.Place().At(at)) + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, at, + "%s%s; its writers meet in %s, kept under Unmodeled", keyword, root.boundsNone(keyword), intersectionValue)} +} + // exclusiveIsBoolean reports whether schema spells an exclusive bound as a // boolean modifying the bound beside it, the shape 3.0's rows and draft 4's // give exclusiveMinimum, rather than as the bound itself. A keyword's shape is @@ -113,50 +173,54 @@ func exclusiveIsBoolean(loweringContext lowering.Ctx, schema *statement.Schema) // constraintsAt reads what schema, written at pointer, bounds of the groups // take names. -func constraintsAt(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, take annotation.Bounds) (*ir.Constraints, []ir.Diagnostic) { +func constraintsAt(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, take annotation.Bounds) (*ir.Constraints, annotation.KeptReports) { if !stated(schema) { return nil, nil } - cons, kept, diags := annotation.Constraints(schema, take, exclusiveIsBoolean(loweringContext, schema), pointer, loweringContext.Place()) + cons, kept, reports := annotation.Constraints(schema, take, exclusiveIsBoolean(loweringContext, schema), pointer, loweringContext.Place()) *unmodeled = annotation.MergeUnmodeled(*unmodeled, kept) - return cons, stampConstraintDiags(loweringContext, diags, pointer) + for i := range reports { + reports[i].Diagnostic.Provenance = loweringContext.Place().At(pointer) + } + return cons, reports } // valueCountKeywords are the counts annotation.Constraints reads, in the order -// keepCounts keeps them. +// keptCounts keeps them. var valueCountKeywords = []string{"maxLength", "maxProperties", "minLength", "minProperties"} -// keepCounts keeps verbatim in unmodeled each value count that writers, a -// position's schema and its folded entries, write and no field states +// keptCounts returns, kept verbatim, each value count that conjuncts, a +// position's schema and its flattened entries, write and no field states // (keptCount), of those a reader of the kinds takes reads of each -// (writerTakes): of several writing one keyword, the one binding the rest -// (bindingCount), so the entry is the same whatever their order. Each writer's -// kept counts are reported once, where it was written -// (docs/compilers/openapi.md#constraints). A count no such reader reads is the -// node's finishing to keep (keepUnread). -func keepCounts(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, writers []annotation.FoldedAllOfEntry, takes kindSet) []ir.Diagnostic { +// (conjunctTakes): of several writing one keyword, the one binding the rest +// (bindingCount), so the entry is the same whatever their order. Each +// conjunct's kept counts are reported once, where it was written, the report +// paired with the first count's key (docs/compilers/openapi.md#constraints). A +// count no such reader reads is the node's finishing to keep (keepUnread). +func keptCounts(loweringContext lowering.Ctx, flattenedConjuncts []annotation.FlattenedAllOfEntry, takes kindSet) (ir.Unmodeled, annotation.KeptReports) { binding := make([]int, len(valueCountKeywords)) for k, keyword := range valueCountKeywords { - binding[k] = bindingCount(writers, keyword, takes) + binding[k] = bindingCount(flattenedConjuncts, keyword, takes) } - var diags []ir.Diagnostic - for w, writer := range writers { + var out ir.Unmodeled + var reports annotation.KeptReports + for w, flattenedConjunct := range flattenedConjuncts { var kept []string for k, keyword := range valueCountKeywords { if binding[k] != w { continue } - ok, keptDiags := preserveSchemaKeyword(loweringContext, unmodeled, writer.Node, keyword, ir.ReasonDegradedLowering, writer.At) - diags = append(diags, stampConstraintDiags(loweringContext, keptDiags, writer.At)...) + ok, keptDiags := keepSchemaKeyword(loweringContext, &out, flattenedConjunct.Node, keyword, ir.ReasonDegradedLowering, flattenedConjunct.At) + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), stampConstraintDiags(loweringContext, keptDiags, flattenedConjunct.At+ids.Ptr(keyword))...)...) if ok { kept = append(kept, keyword) } } if len(kept) > 0 { - diags = append(diags, countsKept(loweringContext, kept, writer.At)) + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", kept[0]), countsKept(loweringContext, kept, flattenedConjunct.At))...) } } - return diags + return out, reports } // countsKept reports the counts kept, which no field states, at pointer. @@ -166,20 +230,20 @@ func countsKept(loweringContext lowering.Ctx, kept []string, pointer jsontext.Po strings.Join(kept, ", ")) } -// bindingCount returns the index of the writer whose keyword, a count keptCount -// keeps and a reader of the kinds takes reads of it, binds every other such -// writer's: the smallest maximum or the largest minimum, compared as the -// integers they are (compareCounts), the first of one value written twice. It -// returns -1 where no writer writes one. -func bindingCount(writers []annotation.FoldedAllOfEntry, keyword string, takes kindSet) int { +// bindingCount returns the index of the conjunct whose keyword, a count +// keptCount keeps and a reader of the kinds takes reads of it, binds every +// other such conjunct's: the smallest maximum or the largest minimum, compared +// as the integers they are (compareCounts), the first of one value written +// twice. It returns -1 where no conjunct writes one. +func bindingCount(flattenedConjuncts []annotation.FlattenedAllOfEntry, keyword string, takes kindSet) int { best, sign := -1, 1 if strings.HasPrefix(keyword, "max") { sign = -1 } var bound string - for w, writer := range writers { - count, ok := keptLiteral(writer.Node, keyword) - if ok && taken(writerTakes(takes, writer.Node), keyword) && (best < 0 || sign*compareCounts(count, bound) > 0) { + for w, flattenedConjunct := range flattenedConjuncts { + count, ok := keptLiteral(flattenedConjunct.Node, keyword) + if ok && taken(conjunctTakes(takes, flattenedConjunct.Node), keyword) && (best < 0 || sign*compareCounts(count, bound) > 0) { best, bound = w, count } } @@ -239,14 +303,14 @@ func magnitude(lit string) (power, digits string) { func shifted(exponent string, offset int64) string { exponent = strings.TrimPrefix(exponent, "+") long := strings.TrimLeft(strings.TrimPrefix(exponent, "-"), "0") - e, err := strconv.ParseInt(cmp.Or(exponent, "0"), 10, 64) + exponentValue, err := strconv.ParseInt(cmp.Or(exponent, "0"), 10, 64) switch { case len(long) >= 19 && exponent[0] != '-': return plus(long, offset) case len(long) >= 19, err != nil: - e = 0 + exponentValue = 0 } - return strconv.FormatInt(e+offset, 10) + return strconv.FormatInt(exponentValue+offset, 10) } // plus returns n, the digits of a number past |offset|, plus offset, carrying @@ -256,12 +320,12 @@ func plus(n string, offset int64) string { out := []byte(n) carry := offset for i := len(out) - 1; i >= 0 && carry != 0; i-- { - d := int64(out[i]-'0') + carry - carry = d / 10 - if d%10 < 0 { + digit := int64(out[i]-'0') + carry + carry = digit / 10 + if digit%10 < 0 { carry-- } - out[i] = byte('0' + d - carry*10) + out[i] = byte('0' + digit - carry*10) } return strings.TrimLeft(string(out), "0") } @@ -325,48 +389,113 @@ func stampConstraintDiags(loweringContext lowering.Ctx, diags []ir.Diagnostic, p // (docs/ir/annotations.md#one-structural-home-per-declaration), so its carrier // holds none. One owning none holds those a reference does // (referenceConstraintsOf), since the keeping of unread keywords hoists an -// alias to keep any other. PreserveRefSiteKeywords draws the same line. -func CarrierConstraintsOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, foldedEntries []annotation.FoldedAllOfEntry, typeRef ir.TypeRef, pointer jsontext.Pointer) (*ir.Constraints, []ir.Diagnostic) { +// alias to keep any other. KeepRefSiteKeywords draws the same line. +func CarrierConstraintsOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, typeRef ir.TypeRef, pointer jsontext.Pointer) (*ir.Constraints, []ir.Diagnostic) { if !LoweredToOwnNode(loweringContext, pointer, typeRef) { - return referenceConstraintsOf(loweringContext, unmodeled, schema, foldedEntries, typeRef, pointer) + return referenceConstraintsOf(loweringContext, unmodeled, schema, flattenedEntries, typeRef, pointer) } return nil, nil } -// referenceConstraintsOf is ConstraintsOf for a position that lowered to target, -// a reference, a $ref site, a collapsed union, an expanded $dynamicRef or a -// refinement: no node of its own holds the collection bounds it wrote, so they -// join its value bounds on the alias or carrier it owns -// (docs/compilers/openapi.md#constraints), with those its voices write where -// the position holds them (homesAt). Every bound is read by the types the -// position admits, those of the schemas it names among them (boundKinds), -// so a collection bound is held only where they admit an array, and one they -// do not is kept unread (unreadByReference). -func referenceConstraintsOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, foldedEntries []annotation.FoldedAllOfEntry, target ir.TypeRef, pointer jsontext.Pointer) (*ir.Constraints, []ir.Diagnostic) { +// referenceConstraintsOf is ConstraintsOf for a position that lowered to +// target, a reference, a $ref site, a collapsed union, an expanded $dynamicRef +// or a refinement: no node of its own holds the collection bounds it wrote, so +// they sit with its value bounds on its alias or carrier +// (docs/compilers/openapi.md#constraints), with those its flattened entries +// write where the position holds them (homesAt). Every bound is read by the +// types the position admits, those of the schemas it names among them +// (boundKinds), so a collection bound is held only where they admit an array, +// and one they do not is kept unread (unreadByReference). +func referenceConstraintsOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, target ir.TypeRef, pointer jsontext.Pointer) (*ir.Constraints, []ir.Diagnostic) { + cons, kept, reports := referenceBoundsKept(loweringContext, *unmodeled, schema, flattenedEntries, target, pointer) + *unmodeled = annotation.MergeUnmodeled(*unmodeled, kept) + return cons, reports.Diagnostics() +} + +// referenceBoundsKept returns referenceConstraintsOf's constraints, and what +// no field holds (boundsKept, heldTextKept), each report paired with its key: +// an unread keyword held holds already is kept by none. +func referenceBoundsKept(loweringContext lowering.Ctx, held ir.Unmodeled, schema *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, + target ir.TypeRef, pointer jsontext.Pointer, +) (*ir.Constraints, ir.Unmodeled, annotation.KeptReports) { if !stated(schema) { - return nil, nil + return nil, nil, nil } - takes := boundKinds(loweringContext, schema) - cons, diags := ConstraintsOf(loweringContext, unmodeled, schema, foldedEntries, pointer, takes) - if takes&kindArray == 0 { - return cons, diags + homes := homesAt(loweringContext, schema, target, pointer) + cons, kept, reports := boundsKept(loweringContext, held, schema, flattenedEntries, pointer, homes.value) + text, textReports := heldTextKept(loweringContext, schema, flattenedEntries, pointer, homes) + kept, reports = annotation.MergeUnmodeled(kept, text), append(reports, textReports...) + if !referenceHoldsCollection(homes) { + return cons, kept, reports } cons = merge.Constraints(cons, heldCollectionBounds(schema)) - if len(foldedEntries) > 0 && homesAt(loweringContext, schema, target, pointer).collection { - cons = collectionBoundsMetWithFoldedEntries(cons, foldedEntries) + return collectionBoundsIntersectedWithFlattenedEntries(cons, flattenedEntries, homes), kept, reports +} + +// heldTextKept returns, each report paired with its key, the bounds of +// homes.heldText that schema and the position's own schema beside its allOf +// write, kept as keepTextBounds keeps them. The position, the outermost +// conjunct, takes the plain key; a principal writing a bound otherwise takes +// its entry key. An allOf entry keeps its own (addOwnKeywordPendingKeeps). +func heldTextKept(loweringContext lowering.Ctx, schema *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer, + homes boundHomes, +) (ir.Unmodeled, annotation.KeptReports) { + if homes.heldText == 0 { + return nil, nil } - return cons, diags + var kept ir.Unmodeled + var reports annotation.KeptReports + var plain []string + besides := slices.DeleteFunc(slices.Clone(flattenedEntries), func(flattenedAllOfEntry annotation.FlattenedAllOfEntry) bool { return !flattenedAllOfEntry.Beside }) + for _, beside := range besides { + reports = append(reports, textBoundsKept(loweringContext, &kept, beside.Node, writtenKept(beside.Node, homes.heldText), beside.At, homes.root)...) + } + for _, keyword := range writtenKept(schema, homes.heldText) { + at := slices.IndexFunc(besides, func(beside annotation.FlattenedAllOfEntry) bool { return hasKey(beside.Node, keyword) }) + switch { + case at < 0: + plain = append(plain, keyword) + case !keyWrittenAlike(besides[at].Node, schema, keyword): + key := annotation.EntryKey(strings.TrimPrefix(string(pointer), string(besides[at].At)+"/"), keyword) + reports = append(reports, annotation.ReportsOf(key, keepTextBoundAs(loweringContext, &kept, schema, keyword, key, pointer, homes.root)...)...) + } + } + return kept, append(reports, textBoundsKept(loweringContext, &kept, schema, plain, pointer, homes.root)...) +} + +// textBoundsKept is keepTextBounds with each report paired with the key of +// the bound it reports. +func textBoundsKept(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, bounds []string, pointer jsontext.Pointer, + root boundRoot, +) annotation.KeptReports { + reports := make(annotation.KeptReports, 0, len(bounds)) + for _, keyword := range bounds { + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), + keepTextBounds(loweringContext, unmodeled, schema, []string{keyword}, pointer, root)...)...) + } + return reports } -// collectionBoundsMetWithFoldedEntries is cons met with the collection bounds -// foldedEntries write, which agree where they speak (foldingAllOfEntries). -func collectionBoundsMetWithFoldedEntries(cons *ir.Constraints, foldedEntries []annotation.FoldedAllOfEntry) *ir.Constraints { - for _, foldedAllOfEntry := range foldedEntries { - cons = merge.Constraints(cons, heldCollectionBounds(foldedAllOfEntry.Node)) +// collectionBoundsIntersectedWithFlattenedEntries is cons intersected with the +// collection bounds flattenedEntries write where homes.collection holds, which +// agree where they speak (allOfEntryFoldingOf). +func collectionBoundsIntersectedWithFlattenedEntries(cons *ir.Constraints, flattenedEntries []annotation.FlattenedAllOfEntry, homes boundHomes) *ir.Constraints { + if !homes.collection { + return cons + } + for _, flattenedAllOfEntry := range flattenedEntries { + cons = merge.Constraints(cons, heldCollectionBounds(flattenedAllOfEntry.Node)) } return cons } +// referenceHoldsCollection reports whether the alias or carrier of a position +// lowered to a reference holds the collection bounds the position writes: +// where homes admit an array. +func referenceHoldsCollection(homes boundHomes) bool { + return homes.value&kindArray != 0 +} + // heldCollectionBounds returns the collection bounds of schema that a // reference's constraints hold (referenceHolds), and nil where it writes none // of them. @@ -385,11 +514,11 @@ func heldCollectionBounds(schema *statement.Schema) *ir.Constraints { } // referenceHolds reports whether referenceConstraintsOf fills the collection -// bound keyword from s, which is the whole test of what a reference keeps +// bound keyword from schema, which is the whole test of what a reference keeps // unread, so a bound ir.Constraints cannot state stays verbatim: a count the -// parser misread (annotation.CountIsExact), and a false uniqueItems, which a -// plain bool cannot tell from unset and which would stop an alias being a -// decorator. +// parser misread (annotation.CountIsExact). A uniqueItems holds only where +// true: a false says nothing (statement.Key), and a plain bool cannot tell it +// from unset. func referenceHolds(schema *statement.Schema, keyword string) bool { array := schema.ArrayKeywords() switch keyword { @@ -410,7 +539,7 @@ func referenceHolds(schema *statement.Schema, keyword string) bool { // with. // // One list, read by the predicate that hoists a node for them -// (declaresValueConstraints) and by the recorder that keeps the ones no node can +// (declaresBound) and by the recorder that keeps the ones no node can // hold (declaredConstraints), so the two can never disagree about what a schema // wrote. Collection bounds are absent because they belong to the collection // nodes, or to what a reference owns, and are read by collectionConstraints or @@ -423,16 +552,6 @@ var valueConstraintKeywords = []string{ // collectionBoundKeywords are the keywords collectionConstraints reads. var collectionBoundKeywords = []string{"maxItems", "minItems", "uniqueItems"} -// declaresValueConstraints reports whether schema sets any keyword -// annotation.Constraints reads. It does not call it: that reports a malformed -// bound, and a predicate must not emit diagnostics. The keywords are detected on -// their raw nodes for the same reason numericBounds reads them there — a -// magnitude beyond float64 leaves the model field nil while the keyword is -// plainly written. -func declaresValueConstraints(schema *statement.Schema) bool { - return hasAnyKey(schema, valueConstraintKeywords) -} - // declaredConstraints returns the value-constraint keywords schema writes, in // valueConstraintKeywords order. func declaredConstraints(schema *statement.Schema) []string { diff --git a/compilers/openapi/internal/schema/constraints_internal_test.go b/compilers/openapi/internal/schema/constraints_internal_test.go index 105c85f45..4d81b5e16 100644 --- a/compilers/openapi/internal/schema/constraints_internal_test.go +++ b/compilers/openapi/internal/schema/constraints_internal_test.go @@ -4,15 +4,19 @@ package schema import ( + "strings" "testing" "github.com/speakeasy-api/openapi/jsonschema/oas3" + "github.com/speakeasy-api/openapi/marshaller" soa "github.com/speakeasy-api/openapi/openapi" "github.com/speakeasy-api/openapi/references" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) @@ -29,7 +33,7 @@ func TestConstraintsOf_NonSchemaInputs(t *testing.T) { Standalone(oas3.NewJSONSchemaFromReference("#/components/schemas/Other")).Schema, } { var kept ir.Unmodeled - cons, diags := ConstraintsOf(lowerer.Ctx, &kept, schema, nil, "/p", anyInstance) + cons, diags := ConstraintsOf(lowerer.Ctx, &kept, schema, nil, "/p", everyKindButNull) assert.Nil(t, cons) assert.Empty(t, diags) assert.Empty(t, kept) @@ -64,9 +68,9 @@ func TestReferenceHolds_NoCollectionBoundIsHeld(t *testing.T) { func TestConstraintsOf_EmptyRefSchema(t *testing.T) { t.Parallel() lowerer := NewRawLowerer(&soa.OpenAPI{}) - js := oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{Ref: new(references.Reference(""))}) + jsonSchema := oas3.NewJSONSchemaFromSchema[oas3.Referenceable](&oas3.Schema{Ref: new(references.Reference(""))}) var kept ir.Unmodeled - cons, diags := ConstraintsOf(lowerer.Ctx, &kept, Standalone(js).Schema, nil, "/p", anyInstance) + cons, diags := ConstraintsOf(lowerer.Ctx, &kept, Standalone(jsonSchema).Schema, nil, "/p", everyKindButNull) assert.Nil(t, cons) assert.Empty(t, diags) assert.Empty(t, kept) @@ -101,7 +105,7 @@ func TestStampConstraintDiags_RelocatesEveryDiagnosticToTheReadingPointer(t *tes // read as 0. func TestCompareCounts_OrdersLiteralsExactly(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { a, b string want int }{ @@ -123,7 +127,93 @@ func TestCompareCounts_OrdersLiteralsExactly(t *testing.T) { {"1e-10000000000000000000", "1", 0}, {"1e-1000000000000000000", "1", 0}, } { - assert.Equal(t, tc.want, compareCounts(tc.a, tc.b), "%s against %s", tc.a, tc.b) - assert.Equal(t, -tc.want, compareCounts(tc.b, tc.a), "%s against %s", tc.b, tc.a) + assert.Equal(t, testCase.want, compareCounts(testCase.a, testCase.b), "%s against %s", testCase.a, testCase.b) + assert.Equal(t, -testCase.want, compareCounts(testCase.b, testCase.a), "%s against %s", testCase.b, testCase.a) + } +} + +// TestBoundsHeldAt_DecidesValueCollectionAndNumberText pins that boundsHeldAt +// decides once which value, collection, and number-as-text bounds a position's +// own node holds, and which node keywords its builder reads off a flattened +// entry: a string's format and content vocabulary, a number as text's format, +// an array's `items` group. collectionBoundsIntersectedWithFlattenedEntries +// honors homes.collection directly. +func TestBoundsHeldAt_DecidesValueCollectionAndNumberText(t *testing.T) { + t.Parallel() + lowerer := NewRawLowerer(&soa.OpenAPI{}) + + str := StandaloneSchema(&oas3.Schema{Type: oas3.NewTypeFromString(oas3.SchemaTypeString)}) + assert.Equal(t, boundHomes{value: kindString, format: true, content: true}, boundsHeldAt(lowerer.Ctx, str, "/components/schemas/Str")) + + arr := StandaloneSchema(&oas3.Schema{Type: oas3.NewTypeFromString(oas3.SchemaTypeArray)}) + assert.Equal(t, boundHomes{collection: true, elements: true}, boundsHeldAt(lowerer.Ctx, arr, "/components/schemas/Arr")) + + numText := StandaloneSchema(&oas3.Schema{ + Type: oas3.NewTypeFromString(oas3.SchemaTypeString), + Format: new("int64"), + }) + assert.Equal(t, boundHomes{otherText: keySetOf(valueConstraintKeywords...), root: rootTextOfNumber, format: true}, + boundsHeldAt(lowerer.Ctx, numText, "/components/schemas/NumText")) + + instant := StandaloneSchema(&oas3.Schema{ + Type: oas3.NewTypeFromString(oas3.SchemaTypeString), + Format: new("date-time"), + }) + assert.Equal(t, boundHomes{otherText: keySetOf("maxLength", "minLength", "pattern"), root: rootTextOfValue, format: true, content: true}, + boundsHeldAt(lowerer.Ctx, instant, "/components/schemas/Instant"), "an instant's text holds no length or pattern of its own") + + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader("{minItems: 2}"), jsonSchema) + require.NoError(t, err) + require.Empty(t, valErrs) + entry := []annotation.FlattenedAllOfEntry{{Node: StandaloneSchema(jsonSchema.GetSchema()), At: "/components/schemas/Arr/allOf/0"}} + assert.Nil(t, collectionBoundsIntersectedWithFlattenedEntries(nil, entry, boundHomes{})) + got := collectionBoundsIntersectedWithFlattenedEntries(nil, entry, boundHomes{collection: true}) + require.NotNil(t, got) + assert.Equal(t, new(int64(2)), got.MinItems) +} + +// TestIntersectTextBounds_ConjunctsIntersectingInNoValueGiveNone holds the +// reading of a text variant's bounds to the fold's: two flattened entries +// writing patterns no one value holds intersect in none, so the variant takes +// neither, and a bound one flattened entry writes alone it takes from that +// flattened entry. +func TestIntersectTextBounds_ConjunctsIntersectingInNoValueGiveNone(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " L: {type: [string, boolean], format: int64}\n"+ + " A: {pattern: a, minLength: 2}\n"+ + " B: {pattern: b}\n")) + flattenedEntries := []annotation.FlattenedAllOfEntry{ + {Node: StatedIn(lowerer, componentSchema(t, lowerer, "A"))}, + {Node: StatedIn(lowerer, componentSchema(t, lowerer, "B"))}, + } + got := intersectTextBounds(lowerer.Ctx, StatedIn(lowerer, componentSchema(t, lowerer, "L")), flattenedEntries, rootTextOfNumber.ownKept()) + assert.Equal(t, keyBit("minLength"), got.intersected) + assert.Equal(t, map[string]int{"minLength": 0}, got.kept) +} + +// TestBoundValue_SpellsTheValueABoundStatesInItsOneField pins the value an +// intersected multipleOf no conjunct writes is kept as, and none where its +// field is unset, for a pair holding both fields, as a 3.0 bound intersected +// with its exclusive modifier, or for a pattern, which intersects only one +// written alike. +func TestBoundValue_SpellsTheValueABoundStatesInItsOneField(t *testing.T) { + t.Parallel() + six, four := ir.BigVal("6"), ir.BigVal("4") + for _, testCase := range []struct { + keyword string + cons ir.Constraints + want string + }{ + {"minimum", ir.Constraints{Min: &six, ExclusiveMin: &four}, ""}, + {"multipleOf", ir.Constraints{MultipleOf: &six}, "6"}, + {"multipleOf", ir.Constraints{}, ""}, + {"maxProperties", ir.Constraints{}, ""}, + {"pattern", ir.Constraints{Pattern: "a"}, ""}, + } { + got, ok := boundValue(testCase.keyword, testCase.cons) + assert.Equal(t, testCase.want != "", ok, "%s %+v", testCase.keyword, testCase.cons) + assert.Equal(t, testCase.want, string(got), "%s %+v", testCase.keyword, testCase.cons) } } diff --git a/compilers/openapi/internal/schema/constraints_named_test.go b/compilers/openapi/internal/schema/constraints_named_test.go index 0020cd6c2..4207e3edd 100644 --- a/compilers/openapi/internal/schema/constraints_named_test.go +++ b/compilers/openapi/internal/schema/constraints_named_test.go @@ -91,8 +91,8 @@ func namedSites(t *testing.T, doc *ir.Document) []namedSite { // baseOf returns the type a scalar or a model is declared over, "" for any // other node. -func baseOf(td ir.TypeDef) ir.TypeID { - switch n := td.(type) { +func baseOf(typeDef ir.TypeDef) ir.TypeID { + switch n := typeDef.(type) { case *ir.Scalar: return n.Base.Target case *ir.Model: @@ -167,30 +167,30 @@ func keywordsOf(kept []keptAt) []string { } // assertNamedRow compiles the row and holds S and p to its facts. -func assertNamedRow(t *testing.T, tc namedRow) { +func assertNamedRow(t *testing.T, testCase namedRow) { t.Helper() - version := tc.version + version := testCase.version if version == "" { version = "3.1.0" } - doc, diags := parseFull(t, namedSpec(version, tc.schema, tc.extra, false)) + doc, diags := parseFull(t, namedSpec(version, testCase.schema, testCase.extra, false)) openapitest.RequireNoErrorDiags(t, diags) - if tc.diags != 0 { - assert.Len(t, diags, tc.diags, "%+v", diags) + if testCase.diags != 0 { + assert.Len(t, diags, testCase.diags, "%+v", diags) } - if tc.quiet { + if testCase.quiet { assert.Empty(t, diags) } sites := namedSites(t, doc) - if tc.base != "" { - assert.Equal(t, tc.base, sites[0].base, "S") + if testCase.base != "" { + assert.Equal(t, testCase.base, sites[0].base, "S") } - for _, key := range tc.keptOnS { + for _, key := range testCase.keptOnS { assert.Contains(t, sites[0].kept, "openapi:"+key, "S") } for _, site := range sites { - assert.Equal(t, tc.held, site.held, site.at) - for _, keptAt := range tc.kept { + assert.Equal(t, testCase.held, site.held, site.at) + for _, keptAt := range testCase.kept { entry, ok := site.kept["openapi:"+keptAt.key] if !assert.True(t, ok, "%s keeps %s: got %v", site.at, keptAt.key, unmodeledKeys(site.kept)) { continue @@ -207,13 +207,13 @@ func assertNamedRow(t *testing.T, tc namedRow) { assert.Regexp(t, "no home for .*"+keptAt.key, message, "%s %s", site.at, keptAt.key) } } - if len(keywordsOf(tc.kept)) > 0 { + if len(keywordsOf(testCase.kept)) > 0 { message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, site.at) - for _, want := range tc.messages { + for _, want := range testCase.messages { assert.Contains(t, message, want, site.at) } } - if tc.quiet { + if testCase.quiet { assert.Empty(t, site.kept, site.at) } } @@ -225,7 +225,7 @@ func assertNamedRow(t *testing.T, tc namedRow) { // reported, whichever of $ref, allOf or a union names the other schema. func TestConstraints_ABoundIsReadByTheTypesItsSchemaNames(t *testing.T) { t.Parallel() - for _, tc := range []namedRow{ + for _, testCase := range []namedRow{ { name: "row 1: a refinement of an array", schema: "{allOf: [" + refTo("Arr") + "], minLength: 1}", kept: []keptAt{{key: "minLength"}}, base: componentID("Arr"), diags: 2, @@ -285,9 +285,9 @@ func TestConstraints_ABoundIsReadByTheTypesItsSchemaNames(t *testing.T) { held: &ir.Constraints{MinLength: new(int64(2))}, kept: []keptAt{{key: "minimum"}}, base: componentID("TextOrList"), }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - assertNamedRow(t, tc) + assertNamedRow(t, testCase) }) } } @@ -297,13 +297,13 @@ func TestConstraints_ABoundIsReadByTheTypesItsSchemaNames(t *testing.T) { // is reported as ignored beside it. func TestConstraints_ABoundBesideARefIn30IsKeptAsIn31(t *testing.T) { t.Parallel() - tc := namedRow{ + testCase := namedRow{ version: "3.0.3", schema: "{$ref: '#/components/schemas/Arr', minLength: 1}", kept: []keptAt{{key: "minLength"}}, } - assertNamedRow(t, tc) + assertNamedRow(t, testCase) - _, diags := parseFull(t, namedSpec(tc.version, tc.schema, "", false)) + _, diags := parseFull(t, namedSpec(testCase.version, testCase.schema, "", false)) for _, at := range []string{namedS, namedP} { assert.Len(t, diagsAtPointer(diags, diag.LaterVersionConstruct, at+"/minLength"), 1, at) } @@ -315,7 +315,7 @@ func TestConstraints_ABoundBesideARefIn30IsKeptAsIn31(t *testing.T) { // stays held and draws no report. func TestConstraints_ABoundANamedTypeTakesIsRead(t *testing.T) { t.Parallel() - for _, tc := range []namedRow{ + for _, testCase := range []namedRow{ { name: "row 16: a string takes string bounds", schema: "{allOf: [" + refTo("Str") + "], minLength: 2, pattern: '^a'}", held: &ir.Constraints{MinLength: new(int64(2)), Pattern: "^a"}, base: componentID("Str"), quiet: true, @@ -329,9 +329,9 @@ func TestConstraints_ABoundANamedTypeTakesIsRead(t *testing.T) { quiet: true, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - assertNamedRow(t, tc) + assertNamedRow(t, testCase) }) } } @@ -363,15 +363,15 @@ func TestConstraints_ATypeBesideANamedSchemaStillNarrowsTheRead(t *testing.T) { func TestConstraints_AUnionIsReadByWhatItsBranchesAdmit(t *testing.T) { t.Parallel() const union = "type/anonymous/components/schemas/Holder/properties/p" - for _, tc := range []struct{ name, schema string }{ + for _, testCase := range []struct{ name, schema string }{ {"row 19: an array or an object", "{anyOf: [" + refTo("Arr") + ", " + refTo("Obj") + "], minLength: 1}"}, {"row 20: an array or null alone", "{anyOf: [" + refTo("Arr") + ", " + refTo("Nil") + "], minLength: 1}"}, {"an array, an object or a null writing no type", "{anyOf: [" + refTo("Arr") + ", " + refTo("Obj") + ", {enum: [null]}], minLength: 1}"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, namedSpec("3.1.0", tc.schema, "", false)) + doc, diags := parseFull(t, namedSpec("3.1.0", testCase.schema, "", false)) openapitest.RequireNoErrorDiags(t, diags) property := propertyOf(t, doc, "Holder", "p") @@ -409,7 +409,7 @@ func TestConstraints_AUnionIsReadByWhatItsBranchesAdmit(t *testing.T) { // or carrier only where the position admits an array, and kept otherwise. func TestCollectionBound_IsReadByTheTypesItsSchemaNames(t *testing.T) { t.Parallel() - for _, tc := range []namedRow{ + for _, testCase := range []namedRow{ { name: "row 22: a $ref to a string", schema: "{$ref: '#/components/schemas/Str', minItems: 1}", kept: []keptAt{{key: "minItems", value: "1"}}, messages: []string{"a use of one of its conjuncts"}, @@ -442,9 +442,9 @@ func TestCollectionBound_IsReadByTheTypesItsSchemaNames(t *testing.T) { kept: []keptAt{{key: "minLength", entry: "allOf/1", value: "1"}}, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - assertNamedRow(t, tc) + assertNamedRow(t, testCase) }) } } @@ -544,7 +544,10 @@ func TestAllOf_ACompositionReadsBoundsByTheTypesItComposes(t *testing.T) { // TestAllOf_AnEmptyConjunctionKeepsEveryBound pins row 33: the conjuncts of // the named schema share no kind, so it admits none and none of the bounds is -// read, as it would be were the named schema null alone. +// read, as it would be were the named schema null alone. Each position that +// admits nothing is a bottom of its own, so S and the property each draw their +// own warning beside the one at ArrAndObj, naming the target that admits no +// value: a reader of S alone learns that S is empty. func TestAllOf_AnEmptyConjunctionKeepsEveryBound(t *testing.T) { t.Parallel() doc, diags := parseFull(t, namedSpec("3.1.0", "{allOf: ["+refTo("ArrAndObj")+"], minLength: 1}", @@ -557,14 +560,18 @@ func TestAllOf_AnEmptyConjunctionKeepsEveryBound(t *testing.T) { assert.Contains(t, model.Unmodeled, "openapi:minLength") assert.Nil(t, propertyOf(t, doc, "Holder", "p").Constraints) - var warnings []ir.Diagnostic + var warnings []string for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityWarning { - warnings = append(warnings, diagnostic) + assert.Equal(t, diag.UnsatisfiableSchema, diagnostic.Code, "%+v", diagnostic) + warnings = append(warnings, string(diagnostic.Provenance.Pointer)) } } - require.Len(t, warnings, 1, "%+v", diags) - assert.Equal(t, "/components/schemas/ArrAndObj", string(warnings[0].Provenance.Pointer)) + assert.ElementsMatch(t, []string{"/components/schemas/ArrAndObj", namedP, namedS}, warnings, "%+v", diags) + for _, at := range []string{namedS, namedP} { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, at), + "(allOf/0: no value)", "%s names its target as admitting nothing", at) + } } // distributedSpec writes a union beside an allOf and the bounds the variants @@ -638,19 +645,20 @@ func TestUnion_ADistributedBodyReadsBoundsByTheTypesItComposes(t *testing.T) { // budgetSpec writes a position naming a schema of n entries none of which // declares a type, beside an array, in either order. func budgetSpec(n int) string { - var b strings.Builder - b.WriteString(" Wide: {allOf: [" + strings.TrimSuffix(strings.Repeat(refTo("Open")+", ", n), ", ") + "]}\n") - b.WriteString(" Open: {description: no type}\n Arr: {type: array, items: {type: string}}\n") - b.WriteString(" H:\n type: object\n properties:\n") - b.WriteString(" wideFirst: {allOf: [" + refTo("Wide") + ", " + refTo("Arr") + "], minLength: 1}\n") - b.WriteString(" arrFirst: {allOf: [" + refTo("Arr") + ", " + refTo("Wide") + "], minLength: 1}\n") - return openapitest.ComponentSpec(b.String()) + var builder strings.Builder + builder.WriteString(" Wide: {allOf: [" + strings.TrimSuffix(strings.Repeat(refTo("Open")+", ", n), ", ") + "]}\n") + builder.WriteString(" Open: {description: no type}\n Arr: {type: array, items: {type: string}}\n") + builder.WriteString(" H:\n type: object\n properties:\n") + builder.WriteString(" wideFirst: {allOf: [" + refTo("Wide") + ", " + refTo("Arr") + "], minLength: 1}\n") + builder.WriteString(" arrFirst: {allOf: [" + refTo("Arr") + ", " + refTo("Wide") + "], minLength: 1}\n") + return openapitest.ComponentSpec(builder.String()) } // TestConstraints_AReadOfAnySizeKeepsTheBoundInEitherOrder pins that the read -// of the named schemas is decided whatever it takes in, so no verdict turns on -// how far it reads or on the order an allOf lists its entries in: either side -// of 256 schemas read, both properties keep a string bound beside an array. +// of the named schemas is decided whatever it takes in, so no answer turns on +// the order an allOf lists its entries in: where the read is cut, the kinds, +// read whole, are an array alone, so each property is a List keeping the +// string bound beside it, with one report at the position. func TestConstraints_AReadOfAnySizeKeepsTheBoundInEitherOrder(t *testing.T) { t.Parallel() for _, n := range []int{254, 255} { @@ -661,9 +669,10 @@ func TestConstraints_AReadOfAnySizeKeepsTheBoundInEitherOrder(t *testing.T) { for _, wire := range []string{"wideFirst", "arrFirst"} { property := propertyOf(t, doc, "H", wire) assert.Nil(t, property.Constraints, wire) - node, ok := doc.Types[property.Type.Target].(*ir.Model) + node, ok := doc.Types[property.Type.Target].(*ir.List) require.True(t, ok, "%s: got %T", wire, doc.Types[property.Type.Target]) assert.Contains(t, node.Unmodeled, "openapi:minLength", wire) + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/H/properties/"+wire), 1, wire) } }) } @@ -696,14 +705,14 @@ func TestConstraints_AnExpandedReferenceIsNamedByItsKeyword(t *testing.T) { t.Parallel() doc, diags := parseFull(t, recursiveSpec) openapitest.RequireNoErrorDiags(t, diags) - for _, tc := range []struct{ at, has, hasNot string }{ + for _, testCase := range []struct{ at, has, hasNot string }{ {"/components/schemas/Tree/items", "its $recursiveRef expands to", "$dynamicRef"}, {"/components/schemas/Dyn/items", "its $dynamicRef expands to", "$recursiveRef"}, } { - message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, tc.at) - assert.Contains(t, message, tc.has, tc.at) - assert.NotContains(t, message, tc.hasNot, tc.at) - assert.Contains(t, message, "minLength", tc.at) + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, testCase.at) + assert.Contains(t, message, testCase.has, testCase.at) + assert.NotContains(t, message, testCase.hasNot, testCase.at) + assert.Contains(t, message, "minLength", testCase.at) } for _, name := range []string{"Tree", "Dyn"} { items, ok := doc.Types[ir.TypeID("type/anonymous/components/schemas/"+name+"/items")] @@ -730,7 +739,7 @@ func reportedAt(diags []ir.Diagnostic) []string { // reached them in. func TestConstraints_ABoundIsReadTheSameInEitherDeclarationOrder(t *testing.T) { t.Parallel() - for _, tc := range []struct{ name, schema string }{ + for _, testCase := range []struct{ name, schema string }{ {"row 1", "{allOf: [" + refTo("Arr") + "], minLength: 1}"}, {"row 2", "{$ref: '#/components/schemas/Arr', minLength: 1}"}, {"row 19", "{anyOf: [" + refTo("Arr") + ", " + refTo("Obj") + "], minLength: 1}"}, @@ -738,10 +747,10 @@ func TestConstraints_ABoundIsReadTheSameInEitherDeclarationOrder(t *testing.T) { {"row 27", "{allOf: [" + refTo("Arr") + ", {minLength: 1}]}"}, {"row 30", "{allOf: [" + refTo("Obj") + "], minLength: 1, minimum: 2, minProperties: 3}"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - after, afterDiags := parseFull(t, namedSpec("3.1.0", tc.schema, "", false)) - before, beforeDiags := parseFull(t, namedSpec("3.1.0", tc.schema, "", true)) + after, afterDiags := parseFull(t, namedSpec("3.1.0", testCase.schema, "", false)) + before, beforeDiags := parseFull(t, namedSpec("3.1.0", testCase.schema, "", true)) assert.Empty(t, cmp.Diff(after.Types, before.Types, orderInvariantIR()...)) assert.Equal(t, reportedAt(afterDiags), reportedAt(beforeDiags)) assert.NotEmpty(t, afterDiags, "a row that reports nothing compares nothing") @@ -751,10 +760,10 @@ func TestConstraints_ABoundIsReadTheSameInEitherDeclarationOrder(t *testing.T) { // TestConstraints_AReferenceLandingOnAPropertyReadsItsNode pins a $ref naming a // property's own schema, a union's or an enum's with a bound beside it: the -// bound is on the node the property owns, in the Union's Constraints or the -// Enum's Unmodeled, which the property and the landing both reach through -// their references, neither holding a copy, whichever of the two is declared -// first (GitHub #1924, #1988). +// bound is on the node the property owns, in the Union's or the Enum's +// Constraints (GitHub #2004), which the property and the landing both reach +// through their references, neither holding a copy, whichever of the two is +// declared first (GitHub #1924, #1988). func TestConstraints_AReferenceLandingOnAPropertyReadsItsNode(t *testing.T) { t.Parallel() const holder = " H: {type: object, properties: {u: {oneOf: [{type: string}, {type: integer}], minLength: 1}, " + @@ -775,7 +784,8 @@ func TestConstraints_AReferenceLandingOnAPropertyReadsItsNode(t *testing.T) { assert.Nil(t, propertyOf(t, doc, "H", "u").Constraints) enum, ok := doc.Types["type/anonymous/components/schemas/H/properties/e"].(*ir.Enum) require.True(t, ok, "got %T", doc.Types["type/anonymous/components/schemas/H/properties/e"]) - assert.Contains(t, enum.Unmodeled, "openapi:minLength") + assert.Equal(t, want, enum.Constraints) + assert.NotContains(t, enum.Unmodeled, "openapi:minLength") assert.Nil(t, propertyOf(t, doc, "H", "e").Constraints) for _, name := range []string{"qu", "qe"} { property := propertyOf(t, doc, "A", name) @@ -815,7 +825,7 @@ func TestConstraints_ABoundBesideAUnionItsTypeExcludesIsKept(t *testing.T) { } } require.Len(t, bound, 1, at) - assert.Contains(t, bound[0], `a node of kind "primitive"`, at) + assert.Contains(t, bound[0], `a node of kind "scalar"`, at) } } @@ -823,10 +833,10 @@ func TestConstraints_ABoundBesideAUnionItsTypeExcludesIsKept(t *testing.T) { // beside the $ref of an allOf entry: a conjunct of the position, as the same // bound on an entry of its own is, read by what the position lowers to. One // its node takes is held there; one it cannot take keeps the entry, with a -// report at it; and no node stands at the entry. +// report at it; and no node sits at the entry. func TestAllOf_ABoundBesideAnEntrysOwnRefIsThePositions(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, schema, kept string held *ir.Constraints }{ @@ -837,26 +847,26 @@ func TestAllOf_ABoundBesideAnEntrysOwnRefIsThePositions(t *testing.T) { {name: "a value bound the target takes", held: &ir.Constraints{MinLength: new(int64(1))}, schema: "{allOf: [{$ref: '#/components/schemas/Str', minLength: 1}]}"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, namedSpec("3.1.0", tc.schema, "", false)) + doc, diags := parseFull(t, namedSpec("3.1.0", testCase.schema, "", false)) openapitest.RequireNoErrorDiags(t, diags) at := namedS + "/allOf/0" assert.NotContains(t, doc.Types, "type/anonymous"+ir.TypeID(at), "no node at the entry") scalar, ok := doc.Types[componentID("S")].(*ir.Scalar) require.True(t, ok, "got %T", doc.Types[componentID("S")]) - assert.Equal(t, tc.held, scalar.Constraints) - if tc.held != nil { + assert.Equal(t, testCase.held, scalar.Constraints) + if testCase.held != nil { assert.Empty(t, scalar.Unmodeled) assert.Empty(t, diags) return } // The bound the entry writes beside its $ref is kept on its own, as // an inline entry's is, at the keyword, and reported at the entry. - assert.Equal(t, []string{"openapi:" + tc.kept}, unmodeledKeys(scalar.Unmodeled)) - assert.Equal(t, ir.ReasonDegradedLowering, scalar.Unmodeled["openapi:"+tc.kept].Reason) - assert.Equal(t, at+"/"+tc.kept, string(scalar.Unmodeled["openapi:"+tc.kept].Provenance.Pointer)) + assert.Equal(t, []string{"openapi:" + testCase.kept}, unmodeledKeys(scalar.Unmodeled)) + assert.Equal(t, ir.ReasonDegradedLowering, scalar.Unmodeled["openapi:"+testCase.kept].Reason) + assert.Equal(t, at+"/"+testCase.kept, string(scalar.Unmodeled["openapi:"+testCase.kept].Provenance.Pointer)) reports := diagsAtPointer(diags, diag.DegradedConstruct, at) require.Len(t, reports, 1) assert.Equal(t, ir.SeverityInfo, reports[0].Severity) @@ -872,15 +882,15 @@ func TestAllOf_ABoundBesideAnEntrysOwnRefIsThePositions(t *testing.T) { // position admits holds its own. func TestConstraints_ATypeListReadsWhatThePositionAdmits(t *testing.T) { t.Parallel() - for _, tc := range []struct{ name, schema, key, value, reportAt string }{ + for _, testCase := range []struct{ name, schema, key, value, reportAt string }{ {name: "a bound on an entry", key: "minimum", value: "1", reportAt: "/allOf/1", schema: "{type: [string, integer], allOf: [{type: [string, boolean]}, {minimum: 1}], minLength: 2}"}, {name: "a bound beside the allOf", key: "minimum", value: "1", schema: "{type: [string, integer], allOf: [{type: [string, boolean]}], minimum: 1, minLength: 2}"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, namedSpec("3.1.0", tc.schema, "", false)) + doc, diags := parseFull(t, namedSpec("3.1.0", testCase.schema, "", false)) openapitest.RequireNoErrorDiags(t, diags) assert.Nil(t, propertyOf(t, doc, "Holder", "p").Constraints) @@ -894,10 +904,10 @@ func TestConstraints_ATypeListReadsWhatThePositionAdmits(t *testing.T) { } } assert.Equal(t, []*ir.Constraints{{MinLength: new(int64(2))}}, held, at) - entry, kept := union.Unmodeled["openapi:"+tc.key] + entry, kept := union.Unmodeled["openapi:"+testCase.key] require.True(t, kept, "%s: got %v", at, unmodeledKeys(union.Unmodeled)) - assert.JSONEq(t, tc.value, string(entry.Value), at) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at+tc.reportAt), + assert.JSONEq(t, testCase.value, string(entry.Value), at) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at+testCase.reportAt), "minimum", at) } }) @@ -942,26 +952,27 @@ func TestConstraints_ANamedSchemasDynamicReferenceIsReadThrough(t *testing.T) { // TestConstraints_AnInlineEntryIsReadAtItsOwnPointer pins that an inline // entry is read where it is written: its dynamic reference resolves in its own // schema resource, so one under an identifier of its own names no anchor of the -// document's, which makes it the $ref it spells, resolving nowhere, so the -// position stays a model holding the property count, while one in the -// document's resource names the array's anchor, which no entry expands, so it -// masks no kind and the top type the position lowers to holds the count. +// document's, which makes it the $ref it spells, resolving nowhere: it admits +// every kind and cuts nothing, so the top type the position lowers to holds +// the property count. One in the document's resource, the allOf's only entry, +// is in place and expands as written at the schema, so the position is the +// array's use keeping the property count, as the flat spelling does. func TestConstraints_AnInlineEntryIsReadAtItsOwnPointer(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, entry string held *ir.Constraints model bool errs []string }{ - {name: "in the document's resource", entry: "{$dynamicRef: '#list'}", held: &ir.Constraints{MinProperties: new(int64(1))}}, + {name: "in the document's resource", entry: "{$dynamicRef: '#list'}"}, {name: "in a resource of its own", entry: "{$id: 'https://example.com/inner', $dynamicRef: '#list'}", - held: &ir.Constraints{MinProperties: new(int64(1))}, model: true, + held: &ir.Constraints{MinProperties: new(int64(1))}, errs: []string{"openapi/unresolved-ref at /components/schemas/S/allOf/0"}}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+tc.entry+"], minProperties: 1}\n"+ + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+testCase.entry+"], minProperties: 1}\n"+ " List: {$dynamicAnchor: list, type: array, items: {type: string}}\n")) var errs []string for _, diagnostic := range diags { @@ -969,12 +980,12 @@ func TestConstraints_AnInlineEntryIsReadAtItsOwnPointer(t *testing.T) { errs = append(errs, diagnostic.Code+" at "+string(diagnostic.Provenance.Pointer)) } } - assert.Equal(t, tc.errs, errs, "%+v", diags) - td := typeByName(doc, "S") - assert.Equal(t, tc.model, td.Kind() == ir.KindModel, "got %T", td) - assert.Equal(t, tc.held, heldBounds(td)) - _, kept := td.Common().Unmodeled["openapi:minProperties"] - assert.Equal(t, tc.held == nil, kept, "got %v", unmodeledKeys(td.Common().Unmodeled)) + assert.Equal(t, testCase.errs, errs, "%+v", diags) + typeDef := typeByName(doc, "S") + assert.Equal(t, testCase.model, typeDef.Kind() == ir.KindModel, "got %T", typeDef) + assert.Equal(t, testCase.held, heldBounds(typeDef)) + _, kept := typeDef.Common().Unmodeled["openapi:minProperties"] + assert.Equal(t, testCase.held == nil, kept, "got %v", unmodeledKeys(typeDef.Common().Unmodeled)) }) } } diff --git a/compilers/openapi/internal/schema/constraints_test.go b/compilers/openapi/internal/schema/constraints_test.go index d88f20308..6a51f2546 100644 --- a/compilers/openapi/internal/schema/constraints_test.go +++ b/compilers/openapi/internal/schema/constraints_test.go @@ -70,14 +70,14 @@ func TestCoDeclaredBound_BothKeywordsReachTheCarriersConstraints(t *testing.T) { read: maxSide, wantIncl: new(ir.BigVal("5")), wantExcl: new(ir.BigVal("100")), }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - require.NotNil(t, tc.bound, "both bounds reach ir.Constraints") - incl, excl := tc.read(tc.bound) - assert.Equal(t, tc.wantIncl, incl, "the inclusive keyword as written") - assert.Equal(t, tc.wantExcl, excl, "the exclusive keyword as written, beside it") - assert.Empty(t, tc.unmod, "with a field apiece there is nothing left to keep") + require.NotNil(t, testCase.bound, "both bounds reach ir.Constraints") + incl, excl := testCase.read(testCase.bound) + assert.Equal(t, testCase.wantIncl, incl, "the inclusive keyword as written") + assert.Equal(t, testCase.wantExcl, excl, "the exclusive keyword as written, beside it") + assert.Empty(t, testCase.unmod, "with a field apiece there is nothing left to keep") }) } } @@ -118,15 +118,15 @@ func TestExclusiveModifier_WithNoBoundIsKeptOnTheCarrierThatReadIt(t *testing.T) carrier: "/components/schemas/Holder/properties/low", }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - entry, ok := tc.unmod[tc.wantKept] - require.True(t, ok, "%s is kept on the carrier that read it; got %v", tc.wantKept, tc.unmod) + entry, ok := testCase.unmod[testCase.wantKept] + require.True(t, ok, "%s is kept on the carrier that read it; got %v", testCase.wantKept, testCase.unmod) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) assert.JSONEq(t, "true", string(entry.Value)) - assert.Equal(t, jsontext.Pointer(tc.at), entry.Provenance.Pointer, "located at the keyword itself") - assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, tc.carrier), 1, + assert.Equal(t, jsontext.Pointer(testCase.at), entry.Provenance.Pointer, "located at the keyword itself") + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, testCase.carrier), 1, "and reported once, at the schema that read it: %+v", diags) }) } @@ -268,17 +268,17 @@ func TestConstraints_LosslessNumericLiterals(t *testing.T) { {"high-precision decimal", "0.12345678901234567890123456789", "0.12345678901234567890123456789"}, {"exponential notation", "6.022e23", "6.022e23"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - spec := openapitest.ComponentSpec(" S:\n type: object\n properties:\n n: {type: number, minimum: " + tc.literal + "}\n") + spec := openapitest.ComponentSpec(" S:\n type: object\n properties:\n n: {type: number, minimum: " + testCase.literal + "}\n") doc, diags := schema.LowerSpec(t, spec) // A valid number, however spelled, is accepted with no error: the // library's float64/JSON complaint is not surfaced. openapitest.RequireNoErrorDiags(t, diags) constraints := propertyConstraints(t, doc, "S", "n") require.NotNil(t, constraints.Min) - assert.Equal(t, tc.want, *constraints.Min) + assert.Equal(t, testCase.want, *constraints.Min) }) } } @@ -333,11 +333,11 @@ func TestConstraints_ExclusiveWrongDialectForm(t *testing.T) { {"boolean under 3.2", "3.2.0", "false"}, {"number under 3.0", "3.0.3", "5"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - spec := openapitest.ComponentSpecVer(tc.version, - " S:\n type: object\n properties:\n n: {type: number, exclusiveMinimum: "+tc.value+"}\n") + spec := openapitest.ComponentSpecVer(testCase.version, + " S:\n type: object\n properties:\n n: {type: number, exclusiveMinimum: "+testCase.value+"}\n") doc, diags := schema.LowerSpec(t, spec) require.NotNil(t, doc) assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.ExclusiveBoundForm, ir.SeverityError), @@ -437,7 +437,7 @@ func allBounds() *ir.Constraints { // reported as having no home. func TestCollectionBound_BesideAReferenceReachesTheAlias(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string at ir.TypeID pointer string @@ -455,16 +455,16 @@ func TestCollectionBound_BesideAReferenceReachesTheAlias(t *testing.T) { {"union branch", "{oneOf: [" + boundedRef + ", {type: string}]}", "type/anonymous/components/schemas/S/oneOf/0", "/components/schemas/S/oneOf/0"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(tagsSchema+" S: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpec(tagsSchema+" S: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) - alias, ok := doc.Types[tc.at].(*ir.Scalar) - require.True(t, ok, "the position owns an alias: %#v", doc.Types[tc.at]) + alias, ok := doc.Types[testCase.at].(*ir.Scalar) + require.True(t, ok, "the position owns an alias: %#v", doc.Types[testCase.at]) assert.Equal(t, allBounds(), alias.Constraints) assert.Empty(t, alias.Unmodeled, "a bound the alias holds is not also kept") - assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, tc.pointer), + assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, testCase.pointer), "a bound the alias holds is not reported as homeless: %+v", diags) }) } @@ -522,7 +522,7 @@ func TestCollectionBound_ARefinementReachesWhatThePositionOwns(t *testing.T) { func TestCollectionBound_OnAnEntryLandsAsItsFlatSpelling(t *testing.T) { t.Parallel() const items = "items: {type: string}" - for name, tc := range map[string]struct{ flat, entry string }{ + for name, testCase := range map[string]struct{ flat, entry string }{ "a type beside": {"{type: array, " + items + ", maxItems: 2}", "{type: array, " + items + ", allOf: [{maxItems: 2}]}"}, "an inline principal": {"{allOf: [{type: array, " + items + "}], maxItems: 2}", "{allOf: [{type: array, " + items + "}, {maxItems: 2}]}"}, @@ -534,7 +534,7 @@ func TestCollectionBound_OnAnEntryLandsAsItsFlatSpelling(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", - " Holder:\n type: object\n properties:\n flat: "+tc.flat+"\n branch: "+tc.entry+"\n")) + " Holder:\n type: object\n properties:\n flat: "+testCase.flat+"\n branch: "+testCase.entry+"\n")) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, withCode(diags, diag.DegradedConstruct)) want := &ir.Constraints{MaxItems: new(int64(2))} @@ -558,26 +558,26 @@ func statedBounds(t *testing.T, doc *ir.Document, wire string) bounds { t.Helper() property := propertyOf(t, doc, "Holder", wire) out := bounds{carrier: property.Constraints} - td := doc.Types[property.Type.Target] - if union, ok := td.(*ir.Union); ok { + typeDef := doc.Types[property.Type.Target] + if union, ok := typeDef.(*ir.Union); ok { require.NotEmpty(t, union.Variants) - td = doc.Types[union.Variants[0].Type.Target] + typeDef = doc.Types[union.Variants[0].Type.Target] } - switch n := td.(type) { + switch n := typeDef.(type) { case *ir.List: out.node = n.Constraints case *ir.Tuple: out.node = n.Constraints default: - t.Fatalf("%s lowered to %T", wire, td) + t.Fatalf("%s lowered to %T", wire, typeDef) } return out } -// TestCollectionBound_OnAnEntryMeetsInEveryOrder pins that the conjuncts writing -// one collection bound agree by meeting, as value bounds do: the tightest count -// lands, and a uniqueItems any of them writes holds. -func TestCollectionBound_OnAnEntryMeetsInEveryOrder(t *testing.T) { +// TestCollectionBound_OnAnEntryIntersectsInEveryOrder pins that the conjuncts +// writing one collection bound agree by intersecting, as value bounds do: the +// tightest count lands, and a uniqueItems any of them writes holds. +func TestCollectionBound_OnAnEntryIntersectsInEveryOrder(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Tags'}" a, b := "{minItems: 1, maxItems: 5}", "{minItems: 3, maxItems: 4, uniqueItems: true}" @@ -599,17 +599,17 @@ func TestCollectionBound_OnAnEntryMeetsInEveryOrder(t *testing.T) { // TestCollectionBound_OnAnEntryWithNoFieldStaysWithItsEntry pins the bounds an // entry keeps under their own keys, reported at the entry: one ir.Constraints // cannot state, and one where the position has no collection to bound, as it -// is kept beside the type, so the carrier holds none of it. +// is kept beside the type, so the carrier holds none of it. A false +// uniqueItems is no such bound: it says nothing +// (TestCollectionBound_AFalseUniqueItemsSaysNothing). func TestCollectionBound_OnAnEntryWithNoFieldStaysWithItsEntry(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/Tags'}" const noHome = " written on this inline entry" - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { written, entry, key, report string held *ir.Constraints }{ - "uniqueItems false": {"{allOf: [" + ref + ", {minItems: 1, uniqueItems: false}]}", "allOf/1", "uniqueItems", - "no home for uniqueItems" + noHome, &ir.Constraints{MinItems: new(int64(1))}}, "a count past int64": {"{allOf: [" + ref + ", {minItems: 99999999999999999999}]}", "allOf/1", "minItems", "past what a 64-bit integer holds", nil}, "a string": {"{type: string, allOf: [{minItems: 1}]}", "allOf/0", "minItems", "no home for minItems" + noHome, nil}, @@ -619,19 +619,19 @@ func TestCollectionBound_OnAnEntryWithNoFieldStaysWithItsEntry(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec(tagsSchema+ - " Holder:\n type: object\n properties:\n f: "+tc.written+"\n")) + " Holder:\n type: object\n properties:\n f: "+testCase.written+"\n")) openapitest.RequireNoErrorDiags(t, diags) property := propertyOf(t, doc, "Holder", "f") - assert.Equal(t, tc.held, property.Constraints) + assert.Equal(t, testCase.held, property.Constraints) kept := property.Unmodeled if model, composed := doc.Types[property.Type.Target].(*ir.Model); composed { assert.Nil(t, model.Constraints) kept = model.Unmodeled } - assert.Equal(t, []string{"openapi:" + tc.key}, unmodeledKeys(kept)) - at := "/components/schemas/Holder/properties/f/" + tc.entry - assert.Equal(t, jsontext.Pointer(at+"/"+tc.key), kept["openapi:"+tc.key].Provenance.Pointer) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), tc.report) + assert.Equal(t, []string{"openapi:" + testCase.key}, unmodeledKeys(kept)) + at := "/components/schemas/Holder/properties/f/" + testCase.entry + assert.Equal(t, jsontext.Pointer(at+"/"+testCase.key), kept["openapi:"+testCase.key].Provenance.Pointer) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), testCase.report) }) } } @@ -639,8 +639,8 @@ func TestCollectionBound_OnAnEntryWithNoFieldStaysWithItsEntry(t *testing.T) { // TestCollectionBound_BesideAnExpandedDynamicRefReachesWhatThePositionOwns pins // the third position that lowers to a reference. What it keeps unread turns on // what the reader filled, as a $ref site's does, so a bound the reader cannot -// state is kept verbatim and reported rather than read as a false 0 or a stated -// false. +// state is kept verbatim and reported rather than read as a false 0, and a +// false uniqueItems, which equals the keyword left out, is kept nowhere. func TestCollectionBound_BesideAnExpandedDynamicRefReachesWhatThePositionOwns(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec(` Node: @@ -661,7 +661,7 @@ func TestCollectionBound_BesideAnExpandedDynamicRefReachesWhatThePositionOwns(t assert.Empty(t, carried.Unmodeled, "a bound the carrier holds is not also kept") unread := propertyOf(t, doc, "Holder", "unread") assert.Nil(t, unread.Constraints) - assert.Equal(t, []string{"openapi:maxItems", "openapi:uniqueItems"}, unmodeledKeys(unread.Unmodeled)) + assert.Equal(t, []string{"openapi:maxItems"}, unmodeledKeys(unread.Unmodeled)) assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Holder/properties/unread")) alias, ok := doc.Types["type/anonymous/components/schemas/Element/items"].(*ir.Scalar) require.True(t, ok) @@ -685,12 +685,12 @@ func TestCollectionBound_BesideARefIn30IsReadAsIn31(t *testing.T) { // TestCollectionBound_ARedeclaredFieldFoldsIt pins the merge over a bound the // carrier holds (docs/compilers/openapi.md#allof-redeclared-property): as a -// value bound does, it joins the intersection of the declarations, the larger +// value bound does, it takes the intersection of the declarations, the larger // minItems and the smaller maxItems in either order, and is not also kept. func TestCollectionBound_ARedeclaredFieldFoldsIt(t *testing.T) { t.Parallel() ref := "{$ref: '#/components/schemas/Tags', " - for _, tc := range []struct { + for _, testCase := range []struct { name, a, b string want *ir.Constraints }{ @@ -703,12 +703,12 @@ func TestCollectionBound_ARedeclaredFieldFoldsIt(t *testing.T) { {"uniqueItems from either", ref + "minItems: 1}", ref + "uniqueItems: true}", &ir.Constraints{MinItems: new(int64(1)), UniqueItems: true}}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := settledSpec(t, tagsSchema, tc.a, tc.b) + doc, diags := settledSpec(t, tagsSchema, testCase.a, testCase.b) property := propertyOf(t, doc, "T", "v") - assert.Equal(t, tc.want, property.Constraints) + assert.Equal(t, testCase.want, property.Constraints) assert.Empty(t, property.Unmodeled, "the fold reads the typed field") assert.Empty(t, diags) }) @@ -717,35 +717,35 @@ func TestCollectionBound_ARedeclaredFieldFoldsIt(t *testing.T) { // TestCollectionBound_RedeclaredListsAreJudgedByTheirElementsBounds pins what // an element alias's bound now gives the fold: two lists alike in all but it -// are judged by it, the narrower winning in either order, and two that meet -// overlap, keeping the first and reporting the other. +// are judged by it, the narrower winning in either order, and two that +// intersect overlap, keeping the first and reporting the other. func TestCollectionBound_RedeclaredListsAreJudgedByTheirElementsBounds(t *testing.T) { t.Parallel() list := func(bound string) string { return "{type: array, items: {$ref: '#/components/schemas/Tags', " + bound + "}}" } - for _, tc := range []struct { + for _, testCase := range []struct { name, a, b string kept ir.TypeID }{ {"the narrower second", list("maxItems: 5"), list("maxItems: 3"), "type/anonymous/components/schemas/T/allOf/1/properties/v"}, {"the narrower first", list("maxItems: 3"), list("maxItems: 5"), "type/anonymous/components/schemas/T/allOf/0/properties/v"}, - {"meeting", list("minItems: 1"), list("maxItems: 3"), "type/composed/components/schemas/T/allOf/1/properties/v"}, + {"meeting", list("minItems: 1"), list("maxItems: 3"), "type/composed/components/schemas/T/allOf/properties/v"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := settledSpec(t, tagsSchema, tc.a, tc.b) + doc, diags := settledSpec(t, tagsSchema, testCase.a, testCase.b) openapitest.RequireNoErrorDiags(t, diags) property := propertyOf(t, doc, "T", "v") - assert.Equal(t, tc.kept, property.Type.Target) + assert.Equal(t, testCase.kept, property.Type.Target) assert.Empty(t, property.Unmodeled) assert.Empty(t, diags) }) } doc, _ := settledSpec(t, tagsSchema, list("minItems: 1"), list("maxItems: 3")) - irList, ok := doc.Types["type/composed/components/schemas/T/allOf/1/properties/v"].(*ir.List) - require.True(t, ok, "two lists whose elements meet stand on a list built of both") + irList, ok := doc.Types["type/composed/components/schemas/T/allOf/properties/v"].(*ir.List) + require.True(t, ok, "two lists whose elements intersect sit on a list built of both") element, ok := doc.Types[irList.ElementType.Target].(*ir.Scalar) require.True(t, ok, "whose element is built of both elements") assert.Equal(t, &ir.Constraints{MinItems: new(int64(1)), MaxItems: new(int64(3))}, element.Constraints) @@ -756,25 +756,25 @@ func TestCollectionBound_RedeclaredListsAreJudgedByTheirElementsBounds(t *testin // refuses is not taken, and one it admits is. func TestCollectionBound_ADefaultIsJudgedAgainstTheAliasHoldingIt(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, bound string taken bool }{{"refused", "maxItems: 1", false}, {"admitted", "maxItems: 2", true}} { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := settledSpec(t, tagsSchema, - "{type: array, items: {$ref: '#/components/schemas/Tags', "+tc.bound+"}}", + "{type: array, items: {$ref: '#/components/schemas/Tags', "+testCase.bound+"}}", "{type: array, items: {$ref: '#/components/schemas/Tags'}, default: [[a, b]]}") openapitest.RequireNoErrorDiags(t, diags) - assert.Equal(t, tc.taken, propertyOf(t, doc, "T", "v").Default != nil) + assert.Equal(t, testCase.taken, propertyOf(t, doc, "T", "v").Default != nil) }) } } -// TestCollectionBound_BesideAValueBoundReachesOneConstraints pins the join: a -// position writing both kinds holds both, on one ir.Constraints, where the -// schema it names declares no type and so excludes neither. +// TestCollectionBound_BesideAValueBoundReachesOneConstraints pins the +// combination: a position writing both kinds holds both, on one ir.Constraints, +// where the schema it names declares no type and so excludes neither. func TestCollectionBound_BesideAValueBoundReachesOneConstraints(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( @@ -788,12 +788,14 @@ func TestCollectionBound_BesideAValueBoundReachesOneConstraints(t *testing.T) { } // TestCollectionBound_ALiteralReadExactlyReachesConstraints pins the spellings -// of a count the parser's model reads as the number they state. +// of a count the parser's model reads as the number they state. A floor of 0 +// equals the keyword left out, so it says nothing beside the $ref and the +// alias holds no bound. func TestCollectionBound_ALiteralReadExactlyReachesConstraints(t *testing.T) { t.Parallel() - for literal, want := range map[string]int64{ - "0": 0, "1.0": 1, "1e3": 1000, "1e18": 1e18, "0x10": 16, "0o17": 15, - "9223372036854775807": 9223372036854775807, + for literal, want := range map[string]*int64{ + "0": nil, "1.0": new(int64(1)), "1e3": new(int64(1000)), "1e18": new(int64(1e18)), "0x10": new(int64(16)), + "0o17": new(int64(15)), "9223372036854775807": new(int64(9223372036854775807)), } { t.Run(literal, func(t *testing.T) { t.Parallel() @@ -803,7 +805,11 @@ func TestCollectionBound_ALiteralReadExactlyReachesConstraints(t *testing.T) { alias, ok := typeByName(doc, "S").(*ir.Scalar) require.True(t, ok) - assert.Equal(t, &ir.Constraints{MinItems: &want}, alias.Constraints) + var held *ir.Constraints + if want != nil { + held = &ir.Constraints{MinItems: want} + } + assert.Equal(t, held, alias.Constraints) assert.Empty(t, alias.Unmodeled) }) } @@ -831,16 +837,14 @@ func TestCollectionBound_ASpellingOfYAMLReachesConstraints(t *testing.T) { // TestCollectionBound_AReferenceKeepsWhatConstraintsCannotState pins the // keeping of unread keywords to what the reader filled, at an alias and at a // carrier alike. The parser's model reads a count past int64 as another number, -// so calling it homed would write a false bound over the verbatim one, and a -// false uniqueItems has no spelling a plain bool can tell from unset. +// so calling it homed would write a false bound over the verbatim one. func TestCollectionBound_AReferenceKeepsWhatConstraintsCannotState(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, keywords string kept []string held *ir.Constraints }{ - {"uniqueItems false", "uniqueItems: false", []string{"openapi:uniqueItems"}, nil}, {"integer past int64", "minItems: 99999999999999999999", []string{"openapi:minItems"}, nil}, {"one past int64", "minItems: 9223372036854775808", []string{"openapi:minItems"}, nil}, {"exponent past int64", "minItems: 1e19", []string{"openapi:minItems"}, nil}, @@ -848,50 +852,140 @@ func TestCollectionBound_AReferenceKeepsWhatConstraintsCannotState(t *testing.T) {"only the unreadable one", "minItems: 1, maxItems: 1e400", []string{"openapi:maxItems"}, &ir.Constraints{MinItems: new(int64(1))}}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - written := "{$ref: '#/components/schemas/Tags', " + tc.keywords + "}" + written := "{$ref: '#/components/schemas/Tags', " + testCase.keywords + "}" doc, diags := parseFull(t, openapitest.ComponentSpec(tagsSchema+ " S: "+written+"\n Holder:\n type: object\n properties:\n f: "+written+"\n")) openapitest.RequireNoErrorDiags(t, diags) alias, ok := typeByName(doc, "S").(*ir.Scalar) require.True(t, ok) - assert.Equal(t, tc.held, alias.Constraints) - assert.Equal(t, tc.kept, unmodeledKeys(alias.Unmodeled)) + assert.Equal(t, testCase.held, alias.Constraints) + assert.Equal(t, testCase.kept, unmodeledKeys(alias.Unmodeled)) assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/S")) property := propertyOf(t, doc, "Holder", "f") - assert.Equal(t, tc.held, property.Constraints) - assert.Equal(t, tc.kept, unmodeledKeys(property.Unmodeled)) + assert.Equal(t, testCase.held, property.Constraints) + assert.Equal(t, testCase.kept, unmodeledKeys(property.Unmodeled)) assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Holder/properties/f")) }) } } +// TestCollectionBound_AReferenceHoldsWhereItsTypesAdmitAnArray pins what the +// alias or carrier of a position lowered to a reference holds of the +// collection bounds it writes, and what it keeps verbatim. An expanded +// $dynamicRef, a collapsed union, a $ref principal and a $ref beside a bound +// hold them where the types they admit include an array, whether or not an +// allOf principal builds the position; a collapsed union over an object keeps +// them. +func TestCollectionBound_AReferenceHoldsWhereItsTypesAdmitAnArray(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpec( + " L: {type: array, items: {type: string}}\n"+ + " O: {type: object}\n"+ + " E1: {$dynamicRef: '#/components/schemas/L', maxItems: 3, uniqueItems: true}\n"+ + " E2: {oneOf: [{$ref: '#/components/schemas/L'}, {type: 'null'}], maxItems: 2, uniqueItems: true}\n"+ + " E3: {allOf: [{$ref: '#/components/schemas/L'}], maxItems: 2, uniqueItems: true}\n"+ + " E4: {oneOf: [{$ref: '#/components/schemas/O'}, {type: 'null'}], maxItems: 2}\n"+ + " E5: {$ref: '#/components/schemas/L', maxItems: 2, minimum: 1}\n"+ + " E6: {type: object, properties: {p: {oneOf: [{$ref: '#/components/schemas/L'}, {type: 'null'}], minItems: 1}}}\n"+ + " E7: {type: array, items: {oneOf: [{$ref: '#/components/schemas/L'}, {type: 'null'}], maxItems: 4}}\n"+ + " E8: {allOf: [{$ref: '#/components/schemas/L'}, {maxItems: 3}], minItems: 1}\n")) + openapitest.RequireNoErrorDiags(t, diags) + + type bounds func() (*ir.Constraints, ir.Unmodeled) + alias := func(id ir.TypeID) bounds { + return func() (*ir.Constraints, ir.Unmodeled) { + scalar, ok := doc.Types[id].(*ir.Scalar) + require.True(t, ok, "%s is an alias", id) + return scalar.Constraints, scalar.Unmodeled + } + } + carrier := func() (*ir.Constraints, ir.Unmodeled) { + property := propertyOf(t, doc, "E6", "p") + return property.Constraints, property.Unmodeled + } + const component = "type/openapi/components/schemas/" + for _, testCase := range []struct { + name string + read bounds + held *ir.Constraints + kept []string + }{ + {"an expanded $dynamicRef", alias(component + "E1"), &ir.Constraints{MaxItems: new(int64(3)), UniqueItems: true}, nil}, + {"a collapsed union", alias(component + "E2"), &ir.Constraints{MaxItems: new(int64(2)), UniqueItems: true}, nil}, + {"a $ref principal", alias(component + "E3"), &ir.Constraints{MaxItems: new(int64(2)), UniqueItems: true}, nil}, + {"a collapsed union over an object", alias(component + "E4"), nil, []string{"openapi:maxItems"}}, + {"a $ref beside a bound", alias(component + "E5"), &ir.Constraints{MaxItems: new(int64(2))}, []string{"openapi:minimum"}}, + {"a collapsed union a property carries", carrier, &ir.Constraints{MinItems: new(int64(1))}, nil}, + {"a collapsed union as items", alias("type/anonymous/components/schemas/E7/items"), &ir.Constraints{MaxItems: new(int64(4))}, nil}, + {"a $ref principal beside a bound", alias(component + "E8"), &ir.Constraints{MaxItems: new(int64(3)), MinItems: new(int64(1))}, nil}, + } { + held, unmodeled := testCase.read() + assert.Equal(t, testCase.held, held, testCase.name) + assert.Equal(t, testCase.kept, unmodeledKeys(unmodeled), testCase.name) + } +} + // TestCollectionBound_DecidesWhetherAnAliasDecorates pins ir.Decorated to the // line the keeping of unread keywords draws: a bound the alias holds says -// something of the value, and a false uniqueItems, kept verbatim, says nothing. +// something of the value, and a description says nothing of it. A false +// uniqueItems hoists no alias at all (TestCollectionBound_AFalseUniqueItemsSaysNothing). func TestCollectionBound_DecidesWhetherAnAliasDecorates(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { keyword string decorates bool - }{{"minItems: 1", false}, {"uniqueItems: true", false}, {"uniqueItems: false", true}} { - t.Run(tc.keyword, func(t *testing.T) { + }{{"minItems: 1", false}, {"uniqueItems: true", false}, {"description: d", true}} { + t.Run(testCase.keyword, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec(tagsSchema+ - " S: {type: array, items: {$ref: '#/components/schemas/Tags', "+tc.keyword+"}}\n")) + " S: {type: array, items: {$ref: '#/components/schemas/Tags', "+testCase.keyword+"}}\n")) openapitest.RequireNoErrorDiags(t, diags) alias := doc.Types["type/anonymous/components/schemas/S/items"] require.NotNil(t, alias) _, decorates := ir.Decorated(alias) - assert.Equal(t, tc.decorates, decorates) + assert.Equal(t, testCase.decorates, decorates) }) } } +// TestCollectionBound_AFalseUniqueItemsSaysNothing pins a uniqueItems written +// false, which equals the keyword left out (Validation 2020-12 §6.4.3): beside +// a $ref, on an entry beside one and at a list's element it is kept nowhere and +// reported nowhere, so each position lowers as the same schema without it does. +func TestCollectionBound_AFalseUniqueItemsSaysNothing(t *testing.T) { + t.Parallel() + const ref = "{$ref: '#/components/schemas/Tags'" + doc, diags := parseFull(t, openapitest.ComponentSpec(tagsSchema+ + " S: "+ref+", uniqueItems: false}\n"+ + " L: {type: array, items: "+ref+", uniqueItems: false}}\n"+ + " Holder:\n type: object\n properties:\n"+ + " beside: "+ref+", uniqueItems: false}\n"+ + " entry: {allOf: ["+ref+"}, {minItems: 1, uniqueItems: false}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + + alias, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok) + assert.Nil(t, alias.Constraints) + assert.Empty(t, alias.Unmodeled) + list, ok := typeByName(doc, "L").(*ir.List) + require.True(t, ok) + assert.Equal(t, ir.TypeRef{Target: componentID("Tags")}, list.ElementType, "no alias is hoisted for the element") + beside := propertyOf(t, doc, "Holder", "beside") + assert.Equal(t, ir.TypeRef{Target: componentID("Tags")}, beside.Type) + assert.Nil(t, beside.Constraints) + assert.Empty(t, beside.Unmodeled) + entry := propertyOf(t, doc, "Holder", "entry") + assert.Equal(t, ir.TypeRef{Target: componentID("Tags")}, entry.Type) + assert.Equal(t, &ir.Constraints{MinItems: new(int64(1))}, entry.Constraints) + assert.Empty(t, entry.Unmodeled) + assert.Empty(t, withCode(diags, diag.DegradedConstruct), "nothing is kept, so nothing is reported") +} + // TestCollectionBound_ACarrierLeavesItToTheNodeItsPositionOwns pins one home per // declaration: a position that lowered to a collection node holds its bounds // there, so the carrier restates none. @@ -916,8 +1010,8 @@ func TestCollectionBound_ACarrierLeavesItToTheNodeItsPositionOwns(t *testing.T) // nodeConstraints returns the Constraints of a node kind with the field, and nil // for one without. -func nodeConstraints(td ir.TypeDef) *ir.Constraints { - switch n := td.(type) { +func nodeConstraints(typeDef ir.TypeDef) *ir.Constraints { + switch n := typeDef.(type) { case *ir.Scalar: return n.Constraints case *ir.Model: @@ -935,7 +1029,7 @@ func nodeConstraints(td ir.TypeDef) *ir.Constraints { // Constraints, and neither does the carrier beside it. func TestCollectionBound_ANodeOfAnotherShapeKeepsItVerbatim(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string kind ir.TypeKind }{ @@ -948,17 +1042,17 @@ func TestCollectionBound_ANodeOfAnotherShapeKeepsItVerbatim(t *testing.T) { {"null-only union", "{oneOf: [{type: 'null'}], minItems: 1}", ir.KindEnum}, {"type of null", "{type: 'null', minItems: 1}", ir.KindEnum}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( - " S: "+tc.schema+"\n Holder:\n type: object\n properties:\n f: "+tc.schema+"\n")) + " S: "+testCase.schema+"\n Holder:\n type: object\n properties:\n f: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) - for _, td := range []ir.TypeDef{typeByName(doc, "S"), doc.Types["type/anonymous/components/schemas/Holder/properties/f"]} { - require.NotNil(t, td) - assert.Equal(t, tc.kind, td.Kind()) - assert.Contains(t, td.Common().Unmodeled, "openapi:minItems") - assert.Nil(t, nodeConstraints(td), "the node holds no bound it also keeps") + for _, typeDef := range []ir.TypeDef{typeByName(doc, "S"), doc.Types["type/anonymous/components/schemas/Holder/properties/f"]} { + require.NotNil(t, typeDef) + assert.Equal(t, testCase.kind, typeDef.Kind()) + assert.Contains(t, typeDef.Common().Unmodeled, "openapi:minItems") + assert.Nil(t, nodeConstraints(typeDef), "the node holds no bound it also keeps") } assert.Nil(t, propertyOf(t, doc, "Holder", "f").Constraints) }) @@ -996,7 +1090,7 @@ func TestCollectionBound_ARefNamingThePositionIsOrderInvariant(t *testing.T) { func TestConstraints_ACountNoFieldStatesIsKeptVerbatim(t *testing.T) { t.Parallel() const past = "99999999999999999999" - for _, tc := range []struct { + for _, testCase := range []struct { name, schema, keyword string held *ir.Constraints }{ @@ -1010,17 +1104,17 @@ func TestConstraints_ACountNoFieldStatesIsKeptVerbatim(t *testing.T) { {"a list's minItems", "{type: array, items: {type: string}, minItems: " + past + "}", "minItems", nil}, {"a tuple's maxItems", "{type: array, prefixItems: [{type: string}], maxItems: 1e400}", "maxItems", nil}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(" S: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpec(" S: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) - td := typeByName(doc, "S") - assert.Equal(t, []string{"openapi:" + tc.keyword}, unmodeledKeys(td.Common().Unmodeled)) - assert.Equal(t, tc.held, heldBounds(td)) + typeDef := typeByName(doc, "S") + assert.Equal(t, []string{"openapi:" + testCase.keyword}, unmodeledKeys(typeDef.Common().Unmodeled)) + assert.Equal(t, testCase.held, heldBounds(typeDef)) require.Len(t, diags, 1, "%+v", diags) assert.Equal(t, ir.SeverityInfo, diags[0].Severity) assert.Equal(t, jsontext.Pointer("/components/schemas/S"), diags[0].Provenance.Pointer) - assert.Equal(t, tc.keyword+" is past what a 64-bit integer holds, so no Constraints field states it; "+ + assert.Equal(t, testCase.keyword+" is past what a 64-bit integer holds, so no Constraints field states it; "+ "kept verbatim under Unmodeled", diags[0].Message, "the node holds the keyword, so it is no homeless one") }) } @@ -1049,15 +1143,15 @@ func TestConstraints_ACountPastTheDecimalRangeIsRefused(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( " S: {type: string, format: x-f, maxLength: 1e1000000000000000000}\n")) - td := typeByName(doc, "S") - assert.Empty(t, td.Common().Unmodeled, "no entry holds it") - assert.Nil(t, heldBounds(td), "no field states it") + typeDef := typeByName(doc, "S") + assert.Empty(t, typeDef.Common().Unmodeled, "no entry holds it") + assert.Nil(t, heldBounds(typeDef), "no field states it") require.NotEmpty(t, diags) for _, diagnostic := range diags { assert.Equal(t, ir.SeverityError, diagnostic.Severity, "%+v", diagnostic) assert.Equal(t, diag.UnpreservableConstruct, diagnostic.Code, "%+v", diagnostic) } - assert.Equal(t, jsontext.Pointer("/components/schemas/S"), diags[0].Provenance.Pointer) + assert.Equal(t, jsontext.Pointer("/components/schemas/S/maxLength"), diags[0].Provenance.Pointer, "at the count") } // TestConstraints_ACountTheLoadPhaseRefusesReachesNoField pins a count literal @@ -1076,9 +1170,9 @@ func TestConstraints_ACountTheLoadPhaseRefusesReachesNoField(t *testing.T) { " O: {type: object, properties: {a: {type: string}}, maxProperties: "+literal+"}\n"+ " M: {type: object, additionalProperties: {type: string}, minProperties: "+literal+"}\n")) for _, name := range []string{"S", "L", "R", "O", "M"} { - td := typeByName(doc, name) - assert.Empty(t, td.Common().Unmodeled, "%s %s", literal, name) - if constraints := heldBounds(td); constraints != nil { + typeDef := typeByName(doc, name) + assert.Empty(t, typeDef.Common().Unmodeled, "%s %s", literal, name) + if constraints := heldBounds(typeDef); constraints != nil { assert.Nil(t, constraints.MaxLength, "%s %s", literal, name) assert.Nil(t, constraints.MaxItems, "%s %s", literal, name) } @@ -1088,9 +1182,9 @@ func TestConstraints_ACountTheLoadPhaseRefusesReachesNoField(t *testing.T) { } } -// heldBounds returns the Constraints td holds, nil for a kind with none. -func heldBounds(td ir.TypeDef) *ir.Constraints { - switch n := td.(type) { +// heldBounds returns the Constraints typeDef holds, nil for a kind with none. +func heldBounds(typeDef ir.TypeDef) *ir.Constraints { + switch n := typeDef.(type) { case *ir.Scalar: return n.Constraints case *ir.Model: @@ -1103,6 +1197,8 @@ func heldBounds(td ir.TypeDef) *ir.Constraints { return n.Constraints case *ir.Union: return n.Constraints + case *ir.Enum: + return n.Constraints default: return nil } @@ -1110,8 +1206,8 @@ func heldBounds(td ir.TypeDef) *ir.Constraints { // TestConstraints_ACountAVariantKeepsIsKeptOnce pins a count no field states // beside a type array: kept where the variant whose type reads it keeps it, and -// not again on the union, with one report, and on the union alone where no -// listed type reads it. +// not again on the union, with one report where the count is written (GitHub +// #1888), and on the union alone where no listed type reads it. func TestConstraints_ACountAVariantKeepsIsKeptOnce(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( @@ -1124,7 +1220,7 @@ func TestConstraints_ACountAVariantKeepsIsKeptOnce(t *testing.T) { variant := doc.Types[ir.TypeID("type/anonymous/components/schemas/"+name+"/"+at)] require.NotNil(t, variant, name) assert.Equal(t, []string{"openapi:maxLength"}, unmodeledKeys(variant.Common().Unmodeled), name) - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/"+name+"/"+at), name) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/"+name), "%s: reported where it is written", name) } assert.Equal(t, []string{"openapi:maxLength"}, unmodeledKeys(typeByName(doc, "None").Common().Unmodeled)) assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, diff --git a/compilers/openapi/internal/schema/constraints_types_test.go b/compilers/openapi/internal/schema/constraints_types_test.go index 605d96bf7..05211c619 100644 --- a/compilers/openapi/internal/schema/constraints_types_test.go +++ b/compilers/openapi/internal/schema/constraints_types_test.go @@ -4,6 +4,7 @@ package schema_test import ( + "maps" "slices" "strings" "testing" @@ -140,31 +141,43 @@ func boundLiteral(keyword string) string { // TestConstraints_ABoundIsReadWhereItsTypeTakesIt pins every value bound beside // each of the six types, a number hoisted as a Scalar for its format, and a // string or integer a format encodes as an instant or bytes, at a component, a -// property, items and a parameter: it -// reaches Constraints exactly where the type is one it applies to, and is kept -// verbatim under openapi: once, with one info, everywhere else -// (docs/compilers/openapi.md#constraints). +// property, items and a parameter: it reaches Constraints exactly where the +// type is one it applies to, and is kept verbatim once, with one info, +// everywhere else (docs/compilers/openapi.md#constraints). A bound binds only +// the kind its node's value is, so one of the text or the seconds an instant +// or bytes are written as is kept with no IR home +// (docs/ir/constraints.md#constraints). func TestConstraints_ABoundIsReadWhereItsTypeTakesIt(t *testing.T) { t.Parallel() - shapes := map[string]struct{ typ, shape string }{ - "string": {"string", "type: string"}, "integer": {"integer", "type: integer"}, - "number": {"number", "type: number"}, "boolean": {"boolean", "type: boolean"}, - "object": {"object", "type: object"}, "array": {"array", "type: array, items: {type: string}"}, - "formatted number": {"number", "type: number, format: x-mine"}, - "string as an instant": {"string", "type: string, format: http-date"}, - "string as bytes": {"string", "type: string, format: base64url"}, - "integer as an instant": {"integer", "type: integer, format: unixtime"}, + shapes := map[string]struct { + typ, shape string + otherKind bool + }{ + "string": {"string", "type: string", false}, "integer": {"integer", "type: integer", false}, + "number": {"number", "type: number", false}, "boolean": {"boolean", "type: boolean", false}, + "object": {"object", "type: object", false}, "array": {"array", "type: array, items: {type: string}", false}, + "formatted number": {"number", "type: number, format: x-mine", false}, + "string as an instant": {"string", "type: string, format: http-date", true}, + "string as bytes": {"string", "type: string, format: base64url", true}, + "integer as an instant": {"integer", "type: integer, format: unixtime", true}, } for keyword, takers := range boundTypes { - for name, tc := range shapes { + for name, testCase := range shapes { t.Run(keyword+"/"+name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, atEverySite("3.1.0", "{"+tc.shape+", "+keyword+": "+boundLiteral(keyword)+"}")) + doc, diags := parseFull(t, atEverySite("3.1.0", "{"+testCase.shape+", "+keyword+": "+boundLiteral(keyword)+"}")) openapitest.RequireNoErrorDiags(t, diags) - taken := slices.Contains(takers, tc.typ) + taken := slices.Contains(takers, testCase.typ) for _, site := range sitesOf(t, doc) { - assert.Equal(t, taken, site.holds(keyword), site.pointer) infos := diagsAtPointer(diags, diag.DegradedConstruct, site.pointer) + if taken && testCase.otherKind { + assert.False(t, site.holds(keyword), site.pointer) + assert.Equal(t, 1, site.keeps(keyword), site.pointer) + assert.Empty(t, infos, site.pointer) + assert.Len(t, diagsAtPointer(diags, diag.UnhomedConstruct, site.pointer+"/"+keyword), 1, site.pointer) + continue + } + assert.Equal(t, taken, site.holds(keyword), site.pointer) if taken { assert.Zero(t, site.keeps(keyword), site.pointer) assert.Empty(t, infos, site.pointer) @@ -249,7 +262,7 @@ func TestConstraints_AReferenceOutcomeReadsByTheTypesItNames(t *testing.T) { " Node: {$dynamicAnchor: node, type: string}\n" stringReference := "'#/components/schemas/Str'" arr := "'#/components/schemas/Arr'" - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string held, kept []string }{ @@ -264,16 +277,16 @@ func TestConstraints_AReferenceOutcomeReadsByTheTypesItNames(t *testing.T) { {"a refinement with a type", "{type: array, allOf: [{$ref: " + arr + "}], minLength: 1, maxItems: 2}", []string{"maxItems"}, []string{"minLength"}}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, atEverySite("3.1.0", tc.schema)+targets) + doc, diags := parseFull(t, atEverySite("3.1.0", testCase.schema)+targets) openapitest.RequireNoErrorDiags(t, diags) for _, site := range sitesOf(t, doc) { - for _, keyword := range tc.held { + for _, keyword := range testCase.held { assert.True(t, site.holds(keyword) || heldCount(site, keyword), "%s %s", site.pointer, keyword) assert.Zero(t, site.keeps(keyword), "%s %s", site.pointer, keyword) } - for _, keyword := range tc.kept { + for _, keyword := range testCase.kept { assert.False(t, site.holds(keyword), "%s %s", site.pointer, keyword) assert.Equal(t, 1, site.keeps(keyword), "%s %s", site.pointer, keyword) message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, site.pointer) @@ -350,6 +363,7 @@ func TestConstraints_AModifierATypeCannotTakeIsKeptUnread(t *testing.T) { // node holds those its kind takes, a Scalar hoisted for its format, a Model and // a union alike, so each bound is written once. The Union a type list lowers to // holds none, its variants holding each (docs/compilers/openapi.md#type-arrays), +// but the Union of literals a mixed enum lowers to holds them (GitHub #2004), // and neither does one beside which no branch takes the bound. func TestConstraints_ACarrierOwningItsNodeHoldsNoBound(t *testing.T) { t.Parallel() @@ -359,7 +373,7 @@ func TestConstraints_ACarrierOwningItsNodeHoldsNoBound(t *testing.T) { "{oneOf: [{type: string}, {type: integer}], maxLength: 3}": {MaxLength: new(int64(3))}, "{type: [string, integer], maxLength: 3, minimum: 1}": nil, "{type: [string, integer], format: x-mine, maxLength: 3}": nil, - "{type: [string, integer], enum: [a, 1], maxLength: 3}": nil, + "{type: [string, integer], enum: [a, 1], maxLength: 3}": {MaxLength: new(int64(3))}, "{oneOf: [{type: string}, {type: integer}], minProperties: 1}": nil, } { doc, diags := parseFull(t, atEverySite("3.1.0", schema)) @@ -378,52 +392,75 @@ func TestConstraints_ACarrierOwningItsNodeHoldsNoBound(t *testing.T) { // TestConstraints_ABoundBesideAValueSetOrAUnionHasOneHome pins a value bound // written beside a union, a value set or a branch folding into either, at every // site atEverySite writes: a oneOf or anyOf holds it in its Union's -// Constraints, whether or not its branches list values, and an Enum, a Literal -// or the Union of literals a mixed enum lowers to keeps it verbatim, once, with -// one report. A carrier holds none either way (GitHub #1924, #1988). +// Constraints, an Enum in its own, a bound an inline entry folds in too, the +// Union of literals a mixed enum lowers to in its Union's (GitHub #2004), and +// the Enum a union of value sets lowers to in its own, keeping the union once; +// a Literal keeps it verbatim, once, with one report. A carrier holds none +// either way (GitHub #1924, #1988). func TestConstraints_ABoundBesideAValueSetOrAUnionHasOneHome(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { schema string held *ir.Constraints // kept is the key the node keeps the bound under where it holds none, - // reported once at the site's pointer and under, naming bound. + // reported once at the site's pointer and under, naming bound; a held + // bound written under is reported there by nothing. kept, under, bound string + // besides holds words of the one info the lowering draws at the site + // apart from any bound, where it draws one. + besides string + // union is the key a node holding the bound keeps a union of value + // sets under, "" for none. + union string }{ {schema: "{oneOf: [{type: string}, {type: integer}], minLength: 1}", held: &ir.Constraints{MinLength: new(int64(1))}}, {schema: "{anyOf: [{type: string}, {type: 'null'}, {type: integer}], minLength: 1}", held: &ir.Constraints{MinLength: new(int64(1))}}, {schema: "{oneOf: [{type: string}, {type: integer}], allOf: [{maxLength: 9}], minLength: 1}", held: &ir.Constraints{MinLength: new(int64(1)), MaxLength: new(int64(9))}}, {schema: "{oneOf: [{enum: [a, bb]}, {type: integer}], maxLength: 1}", held: &ir.Constraints{MaxLength: new(int64(1))}}, - {schema: "{oneOf: [{const: a}, {const: bb}], maxLength: 1}", held: &ir.Constraints{MaxLength: new(int64(1))}}, - {schema: "{anyOf: [{const: 1}, {enum: [2, 3]}], maximum: 1}", held: &ir.Constraints{Max: new(ir.BigVal("1"))}}, - {schema: "{type: string, enum: [a, bb], minLength: 1}", kept: "minLength", bound: "minLength"}, - {schema: "{type: [string, 'null'], enum: [a, null], minLength: 1}", kept: "minLength", bound: "minLength"}, + {schema: "{oneOf: [{const: a}, {const: bb}], maxLength: 1}", held: &ir.Constraints{MaxLength: new(int64(1))}, + besides: "holds no member of the enum", union: "openapi:oneOf"}, + {schema: "{anyOf: [{const: 1}, {enum: [2, 3]}], maximum: 1}", held: &ir.Constraints{Max: new(ir.BigVal("1"))}, + besides: "holds no member of the enum", union: "openapi:anyOf"}, + {schema: "{type: string, enum: [a, bb], minLength: 1}", held: &ir.Constraints{MinLength: new(int64(1))}}, + {schema: "{type: [string, 'null'], enum: [a, null], minLength: 1}", held: &ir.Constraints{MinLength: new(int64(1))}}, {schema: "{const: abc, minLength: 1}", kept: "minLength", bound: "minLength"}, - {schema: "{enum: [a, 1], minLength: 1}", kept: "minLength", bound: "minLength"}, - {schema: "{type: string, enum: [a, bb], allOf: [{maxLength: 9}]}", kept: "maxLength", under: "/allOf/0", bound: "maxLength"}, + {schema: "{enum: [a, 1], minLength: 1}", held: &ir.Constraints{MinLength: new(int64(1))}, besides: "union of literals"}, + {schema: "{type: string, enum: [a, bb], allOf: [{maxLength: 9}]}", held: &ir.Constraints{MaxLength: new(int64(9))}, under: "/allOf/0"}, } { - doc, diags := parseFull(t, atEverySite("3.1.0", tc.schema)) + doc, diags := parseFull(t, atEverySite("3.1.0", testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) for _, site := range sitesOf(t, doc) { - require.NotNil(t, site.node, "%s: %s owns its node", tc.schema, site.pointer) - if tc.held != nil { - assert.Equal(t, tc.held, heldBounds(site.node), "%s: %s", tc.schema, site.pointer) - assert.Empty(t, site.node.Common().Unmodeled, "%s: %s", tc.schema, site.pointer) - assert.Nil(t, site.held, "%s: the carrier at %s", tc.schema, site.pointer) - assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, site.pointer), "%s: %s", tc.schema, site.pointer) + require.NotNil(t, site.node, "%s: %s owns its node", testCase.schema, site.pointer) + if testCase.held != nil { + assert.Equal(t, testCase.held, heldBounds(site.node), "%s: %s", testCase.schema, site.pointer) + keys := slices.Collect(maps.Keys(site.node.Common().Unmodeled)) + if testCase.union != "" { + assert.Equal(t, []string{testCase.union}, keys, "%s: %s keeps the union once", testCase.schema, site.pointer) + } else { + assert.Empty(t, keys, "%s: %s", testCase.schema, site.pointer) + } + assert.Nil(t, site.held, "%s: the carrier at %s", testCase.schema, site.pointer) + reported := diagsAtPointer(diags, diag.DegradedConstruct, site.pointer) + if testCase.besides != "" && len(reported) == 1 && strings.Contains(reported[0].Message, testCase.besides) { + reported = nil + } + assert.Empty(t, reported, "%s: %s", testCase.schema, site.pointer) + if testCase.under != "" { + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, site.pointer+testCase.under), "%s: %s%s", testCase.schema, site.pointer, testCase.under) + } continue } - assert.Nil(t, site.held, "%s: the carrier at %s", tc.schema, site.pointer) - assert.Nil(t, heldBounds(site.node), "%s: %s", tc.schema, site.pointer) - assert.Equal(t, 1, site.keeps(tc.kept), "%s: %s", tc.schema, site.pointer) + assert.Nil(t, site.held, "%s: the carrier at %s", testCase.schema, site.pointer) + assert.Nil(t, heldBounds(site.node), "%s: %s", testCase.schema, site.pointer) + assert.Equal(t, 1, site.keeps(testCase.kept), "%s: %s", testCase.schema, site.pointer) var reports int - for _, diagnostic := range diagsAtPointer(diags, diag.DegradedConstruct, site.pointer+tc.under) { - if strings.Contains(diagnostic.Message, tc.bound) { + for _, diagnostic := range diagsAtPointer(diags, diag.DegradedConstruct, site.pointer+testCase.under) { + if strings.Contains(diagnostic.Message, testCase.bound) { reports++ } } - assert.Equal(t, 1, reports, "%s: %s", tc.schema, site.pointer) + assert.Equal(t, 1, reports, "%s: %s", testCase.schema, site.pointer) } } } @@ -436,22 +473,22 @@ func TestConstraints_ABoundBesideAValueSetOrAUnionHasOneHome(t *testing.T) { // nor a composed Model reads it. func TestConstraints_AnEntryReadsTheBoundsItsOwnTypeTakes(t *testing.T) { t.Parallel() - for _, tc := range []struct{ schema, keyword, entry string }{ + for _, testCase := range []struct{ schema, keyword, entry string }{ {"{allOf: [{type: string, minimum: 1}, {type: string, minimum: 2}]}", "minimum", "openapi:allOf/1"}, {"{allOf: [{type: string, minimum: 2}, {type: string, minimum: 1}]}", "minimum", "openapi:allOf/0"}, {"{type: [string, integer], format: x-mine, allOf: [{type: string, minimum: 1}]}", "minimum", "openapi:allOf/0"}, {"{allOf: [{$ref: '#/components/schemas/O'}, {type: object, properties: {a: {type: string}}, maxLength: 3}]}", "maxLength", "openapi:maxLength"}, } { - doc, diags := parseFull(t, atEverySite("3.1.0", tc.schema)+" O: {properties: {o: {type: string}}}\n") + doc, diags := parseFull(t, atEverySite("3.1.0", testCase.schema)+" O: {properties: {o: {type: string}}}\n") openapitest.RequireNoErrorDiags(t, diags) - for id, td := range doc.Types { - assert.False(t, boundField(heldBounds(td), tc.keyword), "%s: %s", tc.schema, id) + for id, typeDef := range doc.Types { + assert.False(t, boundField(heldBounds(typeDef), testCase.keyword), "%s: %s", testCase.schema, id) } for _, site := range sitesOf(t, doc) { - assert.False(t, site.holds(tc.keyword), "%s: %s", tc.schema, site.pointer) + assert.False(t, site.holds(testCase.keyword), "%s: %s", testCase.schema, site.pointer) } - assert.Contains(t, marshalForTest(t, doc), `"`+tc.entry+`"`, tc.schema) + assert.Contains(t, marshalForTest(t, doc), `"`+testCase.entry+`"`, testCase.schema) } } diff --git a/compilers/openapi/internal/schema/cutread.go b/compilers/openapi/internal/schema/cutread.go new file mode 100644 index 000000000..075992e60 --- /dev/null +++ b/compilers/openapi/internal/schema/cutread.go @@ -0,0 +1,140 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + "strconv" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// entriesCut decides schema, whose allOf entries a choice cannot compare. An +// entry nesting past the flattening depth cuts the read of the kinds, so the +// position is the top type keeping its allOf whole; more than +// maxRefinedConjuncts entries leave what the conjuncts say to decide (cutRead). +// A false entry leaves the decision to the composition, which keeps it. +func entriesCut(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, one bool) refinementDecision { + switch { + case slices.ContainsFunc(comp.entries, func(entry allOfEntry) bool { return entry.schema.Truth.ReadsFalse() }): + return refinementDecision{} + case slices.ContainsFunc(comp.entries, func(entry allOfEntry) bool { return entry.capped }): + return refinementDecision{outcome: decisionRefinesKeepingAllOfWhole, + refinement: refinement{refChoiceReasons: make([]refChoiceReason, len(comp.entries)), admittedTogether: admitted{kinds: kindAny}, loweredAdmits: admitted{kinds: kindAny}}} + } + admissionReader := newAdmissionReader(loweringContext) + admissionReader.nullable = definesNullableFor(loweringContext, schema) + conjuncts, _ := admissionReader.conjuncts(schema, comp, one) + return cutRead(loweringContext, schema, conjuncts, len(comp.entries), "the "+strconv.Itoa(maxRefinedConjuncts)+" conjuncts one election compares") +} + +// cutRead decides schema, whose conjunct reading the bound named cut short, by +// what the conjuncts say, choosing nothing from what the bound let in +// (docs/compilers/openapi.md#allof-refinement). The kinds are read whole, and a +// conjunct writing nothing past them says nothing. +func cutRead(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct, entries int, bound string) refinementDecision { + kinds, _ := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) + whole := admitted{kinds: kinds} + remaining := declaringPastKinds(conjuncts) + if set := soleValueSet(loweringContext, conjuncts); set != nil { + remaining = []*conjunct{set} + admissionReader := newAdmissionReader(loweringContext) + whole = competingSet(&admissionReader, set.schema) + } + if len(remaining) != 1 && (kinds&^kindNull == 0 || kinds&^kindNull == kindObject) { + // The kinds are read whole, so these decide as within the bounds. + composed := refinementDecision{outcome: decisionComposes} + if kinds == 0 { + composed.outcome = decisionComposesBottom + } + return composed + } + refinementValue := refinement{refChoiceReasons: make([]refChoiceReason, entries), admittedTogether: whole, loweredAdmits: whole} + out := refinementDecision{outcome: decisionRefines} + switch { + case len(remaining) == 1: + out.principalAt, out.hasPrincipal = remaining[0].entryIndex, true + case len(remaining) > 1: + refinementValue.cutBy, refinementValue.kindsNamed = bound, true + default: + refinementValue.kindsNamed = true + } + principal, hasPrincipal := out.principal() + _, principalIsEntry := namedEntry(principal, hasPrincipal) + for _, conjunct := range conjuncts { + if !conjunct.writesRef() { + continue + } + if hasPrincipal && conjunct.entryIndex == principal { + out.refAt, out.readsThrough = conjunct.entryIndex, true + } else if !principalIsEntry { + // A principal beside the allOf chooses no entry: each $ref is kept + // as the cut read leaves it. + refinementValue.refChoiceReasons[conjunct.entryIndex] = refCut + } + } + out.refinement = refinementValue + return out +} + +// declaringPastKinds returns the conjuncts writing something past their kinds, +// which a cut read cannot weigh: each $ref, and each conjunct writing a keyword +// the reading reads other than a type, a nullable, a note or an extension. +func declaringPastKinds(conjuncts []conjunct) []*conjunct { + var out []*conjunct + for i := range conjuncts { + conjunct := &conjuncts[i] + role := annotation.AllOfEntrySchema + if conjunct.entry == nil { + role = annotation.PositionSchema + } + if conjunct.writesRef() || writesPastKinds(conjunct.schema, role) { + out = append(out, conjunct) + } + } + return out +} + +// writesPastKinds reports whether schema writes a keyword the reading reads +// other than its kinds and a key saying nothing; at the position, role +// PositionSchema, its allOf is the conjunction itself and not counted. +func writesPastKinds(schema *statement.Schema, role annotation.SchemaRole) bool { + return slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { + switch { + case keySaysNothing(schema, key), role == annotation.PositionSchema && key.Name == "allOf", key.Name == "type", key.Name == "nullable": + return false + default: + return true + } + }) +} + +// soleValueSet returns the one inline conjunct stating a value set some +// reading converts, the keywords beside the allOf among them, and nil where +// none or several do. +func soleValueSet(loweringContext lowering.Ctx, conjuncts []conjunct) *conjunct { + var set *conjunct + for i := range conjuncts { + conjunct := &conjuncts[i] + if conjunct.writesRef() || !enumWritten(conjunct.schema) && conjunct.schema.Const() == nil || + writesUnreadValueSet(loweringContext, conjunct.schema) { + continue + } + if set != nil { + return nil + } + set = conjunct + } + return set +} + +// budgetCut names the cap admissionReaderValue's read went past. +func budgetCut(admissionReaderValue *admissionReader) string { + if admissionReaderValue.members.Exhausted() { + return "the " + strconv.Itoa(maxAdmissionMembers) + " value-set members one reading takes in" + } + return "the " + strconv.Itoa(maxAdmissionReads) + " schemas one reading takes in" +} diff --git a/compilers/openapi/internal/schema/deadbranch.go b/compilers/openapi/internal/schema/deadbranch.go index cf5f30ed0..fab119e36 100644 --- a/compilers/openapi/internal/schema/deadbranch.go +++ b/compilers/openapi/internal/schema/deadbranch.go @@ -13,6 +13,7 @@ import ( "go.yaml.in/yaml/v3" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" @@ -20,375 +21,306 @@ import ( "github.com/dexpace/morphic/ir" ) -// deadBranchesOf keys what deadBranches read of one body and union. -type deadBranchesOf struct { - body, holder *statement.Schema -} - // deadBranches marks, by index, each branch of the union holder writes that no -// instance of body satisfies (deadBranch), read once a run, as every reader of -// the position asks. None is marked where what body writes but the union -// admits anything but objects, or is cut short (restAdmitsObjects): a rest -// sharing no kind is the warning's that -// docs/compilers/openapi.md#allof-disjoint-conjuncts gives of the schema -// whole. That reading leaves null out: the nulls walk would classify body's -// union again. +// instance of the conjunction of body satisfies, as the union reading reads it +// (readLoweredUnion) where holder writes the union that conjunction chooses, +// read against everything else in it; none for any other union. func deadBranches(loweringContext lowering.Ctx, body, holder *statement.Schema) []bool { - return lowering.ReadOncePerRun(loweringContext, deadBranchesOf{body, holder}, func() []bool { - branches, _, _ := unionBranches(loweringContext, body, holder) - out := make([]bool, len(branches)) - if !restAdmitsObjects(loweringContext, body, holder) { - return out - } - for i, b := range branches { - st := loweringContext.Statements().Subschema(b) - out[i] = !nullBranch(loweringContext, st) && deadBranch(loweringContext, body, holder, st) - } - return out - }) -} - -// restAdmitsObjects reports whether what body writes but the union holder -// writes, beside it or on an entry of its allOf whose own type and value set -// stay, admits objects alone, null aside, as its conjuncts are read for a -// disjoint report (conjunctAtoms): the premise deadBranch reads a branch -// against. A rest of another kind leaves the contradiction to that report, -// and one cut short, as by a $ref naming no schema, decides nothing. -func restAdmitsObjects(loweringContext lowering.Ctx, body, holder *statement.Schema) bool { - at, _ := siteOf(body) - joint := anyInstance - for _, a := range conjunctAtoms(loweringContext, body, allOfEntries(loweringContext, body, at.Pointer)) { - switch { - case a.cut: - return false - case a.st != nil && a.st.Schema == holder: - firm, _ := ownKinds(loweringContext, holder) - joint &= firm - default: - joint &= a.admits - } - } - return joint == kindObject -} - -// deadBranch reports whether no instance satisfies both body, which admits -// objects alone, null aside, as a union distributing it requires, and the -// union branch b of the union holder writes: the kinds b lowers to (lowersTo) -// hold no object, and b or body admits no null (mayAdmitNull). Kinds the -// kind-inference policy read, on either side, and a read cut short decide -// nothing, so such a branch lives. A read past the admission's caps keeps its -// kinds, which are whole, and beside a body that may admit null it lives, its -// null reading not asked (docs/compilers/openapi.md#union-beside-structure). -func deadBranch(loweringContext lowering.Ctx, body, holder *statement.Schema, b *statement.Statement) bool { - kinds, inferred := lowersTo(loweringContext, b) - if inferred || kinds&kindObject != 0 || bodyKindInferred(loweringContext, body) { - return false - } - if !bodyAdmitsNull(loweringContext, body, holder) { - return true - } - // lowersTo reads a cut read as every kind, so b's reaches no cycle through - // body. Past the caps b's null is not read, as the rule says. - if !admissionOf(loweringContext, b).within() { - return false - } - return !mayAdmitNull(loweringContext, b, nil) -} - -// bodyAdmitsNull reports whether body may admit null by what it writes but the -// union of holder, whose branches are read against it. The union holder passes -// over is a conjunct of that rest wherever it is written, keeping null out -// where every branch does within the read's budget, as an entry writing it is -// read (docs/compilers/openapi.md#union-beside-structure). -func bodyAdmitsNull(loweringContext lowering.Ctx, body, holder *statement.Schema) bool { - if !mayAdmitNull(loweringContext, loweringContext.Statements().Read(body), holder) { - return false - } - passed, _ := passedOver(loweringContext, body, holder) - if passed == nil { - return true + if loweredUnionWrittenBy(loweringContext, body, holder) { + return readLoweredUnion(loweringContext, body).dead } - nulls := newNulls(loweringContext) - nulls.variants = true - return !nulls.branchesNull(passed).forbids(loweringContext) || nulls.conjuncts.Exhausted() + branches := loweredKeyword(loweringContext, body, holder).branchesOf(holder) + return make([]bool, len(branches)) } -// deadBranchAt is one branch of u that dead marks, with where it is written. +// deadBranchAt is one branch of a union that dead marks, with where it is +// written. type deadBranchAt struct { - st *statement.Statement - at jsontext.Pointer + schemaStatement *statement.Statement + at jsontext.Pointer } -// deadOf returns the branches of unionAtValue that dead marks, in branch order. -func deadOf(loweringContext lowering.Ctx, unionAtValue unionAt, dead []bool) []deadBranchAt { - branches, key, _ := unionAtValue.branches(loweringContext) +// deadOf returns the branches of unionSite that dead marks, in branch order. +func deadOf(loweringContext lowering.Ctx, unionSite loweredUnionSite, dead []bool) []deadBranchAt { + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) var out []deadBranchAt - for i, b := range branches { + for i, branch := range branches { if dead[i] { - out = append(out, deadBranchAt{st: loweringContext.Statements().Subschema(b), at: unionAtValue.at + ids.Ptr(key, strconv.Itoa(i))}) + out = append(out, deadBranchAt{schemaStatement: loweringContext.Statements().Subschema(branch), at: key.branchAt(unionSite.pointer, i)}) } } return out } -// keepDeadBranches keeps each branch of unionAtValue, a union distributed over +// keepDeadBranches keeps each branch of unionSite, a union distributed over // body, written at pointer, that no instance of body satisfies -// (unionAtValue.dead) verbatim under unmodeled, the Union's Unmodeled -// (unionBranchKey), and reports them once, at body (diagDeadBranches). Such a -// branch is no variant and lowers nowhere, so this is its one home. -func keepDeadBranches(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, body *statement.Schema, unionAtValue unionAt, pointer jsontext.Pointer, -) []ir.Diagnostic { - var diags []ir.Diagnostic +// (unionSite.dead) verbatim under unmodeled, the Union's Unmodeled +// (unionBranchKey), and reports them once, at body (diagDeadBranches), the +// report of a branch it cannot keep paired with its key. Such a branch is no +// variant and lowers nowhere, so this is its one home. +func keepDeadBranches(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, body *statement.Schema, unionSite loweredUnionSite, pointer jsontext.Pointer, +) annotation.KeptReports { + var reports annotation.KeptReports all := true - for _, deadBranchAt := range deadOf(loweringContext, unionAtValue, unionAtValue.dead) { - kept, keptDiags := preserveNode(loweringContext, unmodeled, unionBranchKey(deadBranchAt.at), deadBranchAt.st.Node, - ir.ReasonDegradedLowering, deadBranchAt.at) - diags = append(diags, keptDiags...) + for _, deadBranchAt := range deadOf(loweringContext, unionSite, unionSite.dead) { + key := unionBranchKey(deadBranchAt.at) + kept, keptDiags := keepNode(loweringContext, unmodeled, key, deadBranchAt.schemaStatement.Node, ir.ReasonDegradedLowering, deadBranchAt.at) + reports = append(reports, annotation.ReportsOf(key, keptDiags...)...) all = all && kept } - return append(diags, diagDeadBranches(loweringContext, body, unionAtValue, unionAtValue.dead, pointer, all)...) + return append(reports, annotation.ReportsOf("", diagDeadBranches(loweringContext, body, unionSite, unionSite.dead, pointer, all)...)...) } // diagDeadBranches is the one warning body, written at pointer, draws whose -// union unionAtValue holds branches no instance of it satisfies, as dead marks +// union unionSite holds branches no instance of it satisfies, as dead marks // them: it names each by its path from the body, with the kinds it admits, and // says whether the union lives on in the others, keeping them where kept says // each was stored, or the body lowers alone. -func diagDeadBranches(loweringContext lowering.Ctx, body *statement.Schema, unionAtValue unionAt, dead []bool, pointer jsontext.Pointer, +func diagDeadBranches(loweringContext lowering.Ctx, body *statement.Schema, unionSite loweredUnionSite, dead []bool, pointer jsontext.Pointer, kept bool, ) []ir.Diagnostic { - found := deadOf(loweringContext, unionAtValue, dead) + found := deadOf(loweringContext, unionSite, dead) if len(found) == 0 { return nil } names := make([]string, 0, len(found)) for _, deadBranchAt := range found { - kinds, _ := lowersTo(loweringContext, deadBranchAt.st) - word := noValue - if kinds != 0 { - word = instanceWords(kinds) + names = append(names, pathFrom(pointer, deadBranchAt.at)+": "+deadBranchWords(loweringContext, deadBranchAt.schemaStatement)) + } + report := deadReport{listed: strings.Join(names, ", "), deadCount: len(found), deadAdmitOnlyNull: unionSite.deadBranchesAdmitOnlyNull, kept: kept, + admits: readLoweredUnion(loweringContext, body).restKinds &^ kindNull} + report.key = unionSite.loweredKeyword(loweringContext) + report.branches = report.key.branchesOf(unionSite.holder) + if unionSite.holderIsAllOfEntry { + report.entryPath = pathFrom(pointer, unionSite.pointer) + } + if hasLiveBranch(loweringContext, unionSite, dead) { + report.routes = routesClause(unionSite, "it") + if report.deadCount > 1 { + report.routes = routesClause(unionSite, "them") } - names = append(names, pathFrom(pointer, deadBranchAt.at)+": "+word) - } - deadReportValue := deadReport{listed: strings.Join(names, ", "), dead: len(found), nulls: unionAtValue.nulls} - deadReportValue.branches, deadReportValue.key, _ = unionAtValue.branches(loweringContext) - if unionAtValue.entry { - deadReportValue.on = pathFrom(pointer, unionAtValue.at) + report.forbidsNull = !restNull(loweringContext, body, unionSite.holder).mayAdmit(loweringContext) + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, pointer, "%s", report.withLiveBranches())} } - if hasLiveBranch(loweringContext, unionAtValue, dead) { - deadReportValue.routes = routesClause(unionAtValue, "it") - if deadReportValue.dead > 1 { - deadReportValue.routes = routesClause(unionAtValue, "them") - } - return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, pointer, "%s", - deadReportValue.some(!bodyAdmitsNull(loweringContext, body, unionAtValue.holder), kept))} - } - return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, pointer, "%s", - deadReportValue.none(loweringContext, body, unionAtValue.holder))} + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, pointer, "%s", + report.withoutLiveBranch(loweringContext, body))} } // deadReport is what diagDeadBranches says of a union: its keyword and -// branches, the dead ones listed, and on, the path from the body of the allOf -// entry it is written on, empty for a union beside the body. +// branches, the dead ones listed, and entryPath, the path from the body of the +// allOf entry it is written on, empty for a union beside the body. type deadReport struct { - branches []statement.Subschema - key, on string - listed string - routes string - dead int - nulls bool + branches []statement.Subschema + key unionKeyword + entryPath string + listed string + routes string + deadCount int + // admits is what the body admits, null aside. + admits kindSet + deadAdmitOnlyNull bool + // forbidsNull marks a body keeping null out, and kept dead branches each + // kept verbatim. + forbidsNull, kept bool } -// subject opens a report of a union beside its body, which admits objects -// alone, and null where it does not keep it out, in which case a dead branch -// admits no null either (deadBranch): it returns the opening and how to say -// that a branch admits some of what the body admits, and none of it. -func (r deadReport) subject(forbids bool) (opening, either, neither string) { - if forbids { - return "the body beside this " + r.key + " admits objects alone, and", "an object", "no object" - } - return "the body beside this " + r.key + " admits objects alone, null aside, and", "an object or null", - "no object and no null" +// subject opens a report of a union beside its body, which admits the kinds +// r.admits names, and null where it does not keep it out (r.forbidsNull), in +// which case a dead branch admits no null either: it returns the opening and +// how to say that a branch admits none of what the body admits. +func (r deadReport) subject() (opening, neither string) { + admits, none := "objects alone", "no object" + if r.admits != kindObject { + admits, none = "only an instance of type "+instanceWords(r.admits), "none of them" + } + if r.forbidsNull { + return "the body beside this " + string(r.key) + " admits " + admits + ", and", none + } + return "the body beside this " + string(r.key) + " admits " + admits + ", null aside, and", none + " and no null" } -// some is the report of dead branches beside live ones: they are no variants, -// kept verbatim where kept says so. A union on an entry is judged against the -// rest of the allOf, which may admit more kinds than an object, none a -// distributed branch admits. -func (r deadReport) some(forbids, kept bool) string { +// withLiveBranches is the report of dead branches beside live ones: they are no +// variants, kept verbatim where r.kept says so. A union on an entry is judged +// against the rest of the allOf, which may admit more kinds than an object, +// none a distributed branch admits. +func (r deadReport) withLiveBranches() string { verb, pronoun, rest := "admit", "them", "they are no variants of the union" - if r.dead == 1 { + if r.deadCount == 1 { verb, pronoun, rest = "admits", "it", "it is no variant of the union" } - if kept { + if r.kept { rest += ", kept verbatim under Unmodeled" } rest += r.routes - if r.on != "" { + if r.entryPath != "" { return fmt.Sprintf("%d of the %d branches of the %s on %s %s no value the rest of the allOf admits (%s), "+ - "so no instance satisfies %s: %s", r.dead, len(r.branches), r.key, r.on, verb, r.listed, pronoun, rest) + "so no instance satisfies %s: %s", r.deadCount, len(r.branches), r.key, r.entryPath, verb, r.listed, pronoun, rest) } - if r.nulls { + if r.deadAdmitOnlyNull { return fmt.Sprintf("%d of the %d branches of this %s %s nothing but null, which the rest of this schema keeps "+ - "out (%s), so no instance satisfies %s: %s", r.dead, len(r.branches), r.key, verb, r.listed, pronoun, rest) + "out (%s), so no instance satisfies %s: %s", r.deadCount, len(r.branches), r.key, verb, r.listed, pronoun, rest) } - opening, _, neither := r.subject(forbids) + opening, neither := r.subject() return fmt.Sprintf("%s %d of its branches %s %s (%s), so no instance satisfies %s: %s", - opening, r.dead, verb, neither, r.listed, pronoun, rest) + opening, r.deadCount, verb, neither, r.listed, pronoun, rest) } -// none is the report of a union no branch of which lives, each but its null -// ones dead: the schema lowers as its body alone, and admits null alone where -// the body admits null and the union of holder takes it, by its one null -// branch or by any of them where it is an anyOf. -func (r deadReport) none(loweringContext lowering.Ctx, body, holder *statement.Schema) string { - nulls := len(r.branches) - r.dead - forbids := !bodyAdmitsNull(loweringContext, body, holder) - if r.on != "" { - // What the schema lowers as is the rest of its allOf, whose null a null - // branch of the union on the entry takes: the schema read whole. - forbids = !mayAdmitNull(loweringContext, loweringContext.Statements().Read(body), nil) - } - but, none := "", "no instance" - if nulls > 0 && !forbids { +// withoutLiveBranch is the report of a union on an allOf entry no branch of +// which lives, each but its null ones dead: the schema lowers as the rest of +// its allOf. A null branch that rest's null leaves is a oneOf's two sharing it, +// which the oneOf refuses, so no instance satisfies the schema +// (readLoweredUnion). +func (r deadReport) withoutLiveBranch(loweringContext lowering.Ctx, body *statement.Schema) string { + but := "" + if len(r.branches) > r.deadCount && nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(body)).mayAdmit(loweringContext) { but = " but its null ones" - if nulls == 1 { - but = " but a null one" - } - if nulls == 1 || r.key == "anyOf" { - none = "no instance but null" - } } - if r.on != "" { - return fmt.Sprintf("none of the %d branches of the %s on %s%s admits a value the rest of the allOf admits "+ - "(%s), so %s satisfies this schema, which lowers as the rest of the allOf", - len(r.branches), r.key, r.on, but, r.listed, none) - } - opening, either, _ := r.subject(forbids) - return fmt.Sprintf("%s none of its %d branches%s admits %s (%s), so %s satisfies this schema, which lowers as "+ - "its body alone", opening, len(r.branches), but, either, r.listed, none) + return fmt.Sprintf("none of the %d branches of the %s on %s%s admits a value the rest of the allOf admits "+ + "(%s), so no instance satisfies this schema, which lowers as the rest of the allOf", + len(r.branches), r.key, r.entryPath, but, r.listed) } // diagDeadEntryUnion is the one warning schema, written at pointer, draws where -// unionAtValue, the union on an entry of its allOf, keeps no branch beside the -// rest of it (unionNoLiveBranch) and the report of conjuncts sharing no value -// (docs/compilers/openapi.md#allof-disjoint-conjuncts) is silent, as where a -// null branch of unionAtValue takes a null the rest admits, which the two then -// share. -func diagDeadEntryUnion(loweringContext lowering.Ctx, schema *statement.Schema, unionAtValue unionAt, pointer jsontext.Pointer) []ir.Diagnostic { +// unionSite, the union on an entry of its allOf, keeps no branch beside the +// rest of it (unionLeavesNoBranch) and the report of conjuncts sharing no value +// (docs/compilers/openapi.md#allof-disjoint-conjuncts) reports nothing, as +// where a null branch of unionSite takes a null the rest admits, which the two +// then share; schema lowered as shape. +func diagDeadEntryUnion(loweringContext lowering.Ctx, schema *statement.Schema, unionSite loweredUnionSite, pointer jsontext.Pointer, shape string) []ir.Diagnostic { if len(disjointNames(loweringContext, schema, allOfEntries(loweringContext, schema, pointer))) > 0 { return nil } - return diagDeadBranches(loweringContext, schema, unionAtValue, deadBranches(loweringContext, schema, unionAtValue.holder), pointer, false) + if refused := diagRefusedBranches(loweringContext, schema, pointer, shape); len(refused) > 0 { + return refused + } + return diagDeadBranches(loweringContext, schema, unionSite, deadBranches(loweringContext, schema, unionSite.holder), pointer, false) } -// deadRoute is a route the discriminator standing with a union takes to a -// dead branch of it, which routes to no variant: the mapping entry keyed tag, -// written to target, the defaultMapping, tag empty, or, keyword empty, the -// implicit route by tag, the name of the component the branch names. +// deadRouteKind is how the discriminator beside a union routes to a +// dead branch of it. +type deadRouteKind uint8 + +const ( + // routeByMapping is the mapping entry keyed tag, written to target. + routeByMapping deadRouteKind = iota + // routeByDefaultMapping is the defaultMapping, written to target. + routeByDefaultMapping + // routeByComponentName is the implicit route by tag, the name of the + // component the branch names, which writes nothing. + routeByComponentName +) + +// deadRoute is a route the discriminator beside a union takes to a +// dead branch of it, which routes to no variant, as kind says, by tag to +// target. type deadRoute struct { - keyword, tag, target string + tag, target string + kind deadRouteKind } -// deadRoutesOf returns the routes the discriminator standing with unionAtValue +// deadRoutesOf returns the routes the discriminator beside unionSite // takes to a dead branch: each value of its mapping and its defaultMapping // whose chain a dead branch meets first, every branch but a null one indexed as // indexBranches indexes a variant's, and the name of each dead branch's // component that no entry keys and no other branch names, which OpenAPI routes // by. A union with no dead branch has none. -func deadRoutesOf(loweringContext lowering.Ctx, unionAtValue unionAt) []deadRoute { - if unionAtValue.disc == nil || !slices.Contains(unionAtValue.dead, true) { +func deadRoutesOf(loweringContext lowering.Ctx, unionSite loweredUnionSite) []deadRoute { + if unionSite.discriminator == nil || !slices.Contains(unionSite.dead, true) { return nil } - branches, key, _ := unionAtValue.branches(loweringContext) + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) branchIndex := newBranchIndex(nil) named := map[string][]int{} - for n, b := range branches { - st := loweringContext.Statements().Subschema(b) - if nullBranch(loweringContext, st) { + for n, branch := range branches { + schemaStatement := loweringContext.Statements().Subschema(branch) + if nullBranch(loweringContext, schemaStatement) { continue } - branchIndex.key(loweringContext, st, unionAtValue.at+ids.Ptr(key, strconv.Itoa(n)), n) - if name, _, ok := componentNamed(loweringContext.RefScope(), referenceOf(loweringContext, st)); ok { + branchIndex.key(loweringContext, schemaStatement, key.branchAt(unionSite.pointer, n), n) + if name, _, ok := componentNamed(loweringContext.RefScope(), referenceOf(loweringContext, schemaStatement)); ok { named[name] = append(named[name], n) } } - meets := func(value string) bool { - chain, ok := chainOf(loweringContext, unionAtValue.disc, value) + routesToDeadBranch := func(value string) bool { + chain, ok := chainOf(loweringContext, unionSite.discriminator, value) if !ok { return false } - n, _, met := branchIndex.route(chain) - return met && unionAtValue.dead[n] + n, _, routed := branchIndex.route(chain) + return routed && unionSite.dead[n] } var out []deadRoute - for _, mappingEntry := range unionAtValue.disc.Mapping { - if meets(mappingEntry.Target) { - out = append(out, deadRoute{keyword: "mapping", tag: mappingEntry.Value, target: mappingEntry.Target}) + for _, mappingEntry := range unionSite.discriminator.Mapping { + if routesToDeadBranch(mappingEntry.Target) { + out = append(out, deadRoute{kind: routeByMapping, tag: mappingEntry.Value, target: mappingEntry.Target}) } delete(named, mappingEntry.Value) // an entry keying the name overrides its route } - if dm := unionAtValue.disc.DefaultMapping; dm != "" && meets(dm) { - out = append(out, deadRoute{keyword: "defaultMapping", target: dm}) + if defaultMapping := unionSite.discriminator.DefaultMapping; defaultMapping != "" && routesToDeadBranch(defaultMapping) { + out = append(out, deadRoute{kind: routeByDefaultMapping, target: defaultMapping}) } for _, name := range slices.Sorted(maps.Keys(named)) { - if ns := named[name]; len(ns) == 1 && unionAtValue.dead[ns[0]] { - out = append(out, deadRoute{tag: name}) + if branchIndexes := named[name]; len(branchIndexes) == 1 && unionSite.dead[branchIndexes[0]] { + out = append(out, deadRoute{kind: routeByComponentName, tag: name}) } } return out } -// keepDeadRoutes keeps on n, the Union of u, each route its discriminator -// writes to a dead branch of u, which n's Discriminator leaves out: verbatim, -// keyed by its path from n's position as the discriminator's extensions are -// (discriminatorScope), `openapi:discriminator/mapping/` beside the -// union. Where n holds no discriminator it is kept whole, unread. -func keepDeadRoutes(loweringContext lowering.Ctx, union *ir.Union, unionAtValue unionAt) []ir.Diagnostic { +// keepDeadRoutes keeps on unmodeled each route the discriminator of union, the +// Union of unionSite, writes to a dead branch, which union's Discriminator +// leaves out: verbatim, keyed by its path from union's position as the +// discriminator's extensions are (discriminatorScope), +// `openapi:discriminator/mapping/` beside the union, each report paired +// with its key. Where union holds no discriminator it is kept whole, unread. +func keepDeadRoutes(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, union *ir.Union, unionSite loweredUnionSite) annotation.KeptReports { if union.Discriminator == nil { return nil } - owner, scope := discriminatorScope(unionAtValue, union.Provenance.Pointer) - var diags []ir.Diagnostic - for _, deadRoute := range unionAtValue.deadRoutes { - if deadRoute.keyword == "" { + owner, scope := discriminatorScope(unionSite, union.Provenance.Pointer) + var reports annotation.KeptReports + for _, deadRoute := range unionSite.deadRoutes { + var at jsontext.Pointer + switch deadRoute.kind { + case routeByMapping: + at = ids.Ptr("mapping", deadRoute.tag) + case routeByDefaultMapping: + at = ids.Ptr("defaultMapping") + case routeByComponentName: continue // an implicit route writes nothing to keep } - tokens := []string{deadRoute.keyword} - if deadRoute.keyword == "mapping" { - tokens = append(tokens, deadRoute.tag) - } - at := ids.Ptr(tokens...) node := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: deadRoute.target} - _, keptDiags := preserveNode(loweringContext, &union.Unmodeled, "openapi:"+scope+string(at), node, - ir.ReasonDegradedLowering, owner+at) - diags = append(diags, keptDiags...) + key := "openapi:" + scope + string(at) + _, keptDiags := keepNode(loweringContext, unmodeled, key, node, ir.ReasonDegradedLowering, owner+at) + reports = append(reports, annotation.ReportsOf(key, keptDiags...)...) } - return diags + return reports } -// routesClause is what the warning of unionAtValue's dead branches says of the +// routesClause is what the warning of unionSite's dead branches says of the // routes its discriminator takes to them (deadRoutesOf), pronoun naming the // branches: none routes, and those it writes are kept. Each route is listed by // the byte order of what the clause says of it, which puts the defaultMapping // first, then the mapping keys and then the names, as no order of the mapping // is the document's. -func routesClause(unionAtValue unionAt, pronoun string) string { - if len(unionAtValue.deadRoutes) == 0 { +func routesClause(unionSite loweredUnionSite, pronoun string) string { + if len(unionSite.deadRoutes) == 0 { return "" } - tags := make([]string, 0, len(unionAtValue.deadRoutes)) + tags := make([]string, 0, len(unionSite.deadRoutes)) written := false - for _, deadRoute := range unionAtValue.deadRoutes { - switch deadRoute.keyword { - case "mapping": + for _, deadRoute := range unionSite.deadRoutes { + switch deadRoute.kind { + case routeByMapping: tags = append(tags, "mapping "+strconv.Quote(deadRoute.tag)) - case "defaultMapping": + case routeByDefaultMapping: tags = append(tags, "defaultMapping") - default: + case routeByComponentName: tags = append(tags, "the name "+strconv.Quote(deadRoute.tag)) } - written = written || deadRoute.keyword != "" + written = written || deadRoute.kind != routeByComponentName } slices.Sort(tags) clause := "; no tag of the discriminator routes to " + pronoun + " (" + strings.Join(tags, ", ") + ")" @@ -398,12 +330,12 @@ func routesClause(unionAtValue unionAt, pronoun string) string { return clause } -// hasLiveBranch reports whether some branch of unionAtValue is neither dead nor +// hasLiveBranch reports whether some branch of unionSite is neither dead nor // null. -func hasLiveBranch(loweringContext lowering.Ctx, unionAtValue unionAt, dead []bool) bool { - branches, _, _ := unionAtValue.branches(loweringContext) - for i, b := range branches { - if !dead[i] && !nullBranch(loweringContext, loweringContext.Statements().Subschema(b)) { +func hasLiveBranch(loweringContext lowering.Ctx, unionSite loweredUnionSite, dead []bool) bool { + branches := unionSite.branches(loweringContext) + for i, branch := range branches { + if !dead[i] && !nullBranch(loweringContext, loweringContext.Statements().Subschema(branch)) { return true } } @@ -416,23 +348,23 @@ func pathFrom(pointer, at jsontext.Pointer) string { } // keepsDeadUnion reports whether schema, read at the position its bindings -// place it at, writes a union beside its object body none of whose branches an +// place it at, writes a union beside its body none of whose branches an // instance of the body satisfies, which schema reports where it is written -// (diagDeadBranches), as distributesUnion reads a distribution there. +// (diagDeadBranches), as the lowering reads a distribution there. func keepsDeadUnion(loweringContext lowering.Ctx, schema *statement.Schema) bool { at, placed := siteOf(schema) - if !placed || !declaresUnion(schema) || !hasUnionSiblings(loweringContext, schema) { + if !placed || !declaresUnion(schema) { return false } in, _ := lowering.InDocument(loweringContext, at.Doc) - return classifyUnionSiblings(in, schema, at.Pointer) == unionNoLiveBranch + return hasUnionSiblings(loweringContext, schema) && readLoweredUnion(in, schema).besideRest == unionLeavesNoBranch } // unionBranchKey is the Unmodeled key a branch of a distributed union, written // at at, is kept under: `openapi:/`, the last two tokens of at, // its provenance saying where it is written, beside the body or on an allOf // entry, as an entry's own keywords are kept. A position distributes one union -// (findEntryUnion), so no two branches it keeps share a key. +// (readConjunction), so no two branches it keeps share a key. func unionBranchKey(at jsontext.Pointer) string { index := strings.LastIndexByte(string(at), '/') keyword := strings.LastIndexByte(string(at[:index]), '/') diff --git a/compilers/openapi/internal/schema/deadbranch_null_internal_test.go b/compilers/openapi/internal/schema/deadbranch_null_internal_test.go index e96ce8842..86f3e4522 100644 --- a/compilers/openapi/internal/schema/deadbranch_null_internal_test.go +++ b/compilers/openapi/internal/schema/deadbranch_null_internal_test.go @@ -17,45 +17,49 @@ import ( ) // TestDeadBranch_ReadsANullWhereTheIRHoldsIt holds the dead-branch check to the -// one reading of null (mayAdmitNull): a branch naming a union admits the null -// a variant of it admits, declared or read in by the nullable-inference -// policy; a body admits the null all it writes but the union does; and a body -// whose read passes the walk's budget may admit null unless what it read keeps -// null out (docs/compilers/openapi.md#union-beside-structure). +// one reading of null: a branch naming a union admits the null a variant of it +// admits, declared or read in by the nullable-inference policy; a body admits +// the null all it writes but the union does; and a body reached through a +// chain of 300 allOf references reads the null at its end, which no depth cuts +// (docs/compilers/openapi.md#union-beside-structure). func TestDeadBranch_ReadsANullWhereTheIRHoldsIt(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.ComponentSpecVer("3.1.0", deadNullSpec()), service.Policy{}) for name, dead := range map[string]bool{ "OnAVariant": false, "OnALenientVariant": false, "BesideNoNull": true, - "PastTheWalk": false, "KeptOutPastTheWalk": true, + "DownAChainToNoNull": true, "KeptOutDownAChain": true, "DownAChainToNull": false, } { - st := heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name)) - assert.Equal(t, []bool{dead, false}, deadBranches(serviceContext.Ctx, st.Schema, st.Schema), name) + schemaStatement := heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name)) + assert.Equal(t, []bool{dead, false}, deadBranches(serviceContext.Ctx, schemaStatement.Schema, schemaStatement.Schema), name) } } // deadNullSpec declares bodies beside a union of a branch admitting strings // and perhaps null, and an object: over a union of a string and a $ref to // null, over one whose second branch admits null only by the policy's reading -// of nullable, which 3.1 does not define, and an allOf chain the walk cannot -// finish, ending on an object alone, beside no type or one keeping null out. +// of nullable, which 3.1 does not define, and a chain of 300 allOf references +// ending on an object alone, beside no type or one keeping null out, or on an +// object or null. func deadNullSpec() string { ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } - var b strings.Builder - b.WriteString(" S0: {type: string}\n NUL: {type: 'null'}\n O: {type: object}\n") - b.WriteString(" T: {anyOf: [" + ref("S0") + ", " + ref("NUL") + "]}\n") - b.WriteString(" L: {anyOf: [" + ref("S0") + ", {type: string, nullable: true}]}\n") + var builder strings.Builder + builder.WriteString(" S0: {type: string}\n NUL: {type: 'null'}\n O: {type: object}\n") + builder.WriteString(" T: {anyOf: [" + ref("S0") + ", " + ref("NUL") + "]}\n") + builder.WriteString(" L: {anyOf: [" + ref("S0") + ", {type: string, nullable: true}]}\n") union := func(t string) string { return "properties: {u: {type: string}}, anyOf: [" + ref(t) + ", " + ref("O") + "]" } - fmt.Fprintf(&b, " OnAVariant: {type: [object, 'null'], %s}\n", union("T")) - fmt.Fprintf(&b, " OnALenientVariant: {type: [object, 'null'], %s}\n", union("L")) - fmt.Fprintf(&b, " BesideNoNull: {type: object, %s}\n", union("T")) - fmt.Fprintf(&b, " PastTheWalk: {allOf: [%s], %s}\n", ref("B0"), union("T")) - fmt.Fprintf(&b, " KeptOutPastTheWalk: {type: object, allOf: [%s], %s}\n", ref("B0"), union("T")) - for i := range maxNullConjuncts { - fmt.Fprintf(&b, " B%d: {allOf: [%s]}\n", i, ref(fmt.Sprintf("B%d", i+1))) + fmt.Fprintf(&builder, " OnAVariant: {type: [object, 'null'], %s}\n", union("T")) + fmt.Fprintf(&builder, " OnALenientVariant: {type: [object, 'null'], %s}\n", union("L")) + fmt.Fprintf(&builder, " BesideNoNull: {type: object, %s}\n", union("T")) + fmt.Fprintf(&builder, " DownAChainToNoNull: {allOf: [%s], %s}\n", ref("B0"), union("T")) + fmt.Fprintf(&builder, " KeptOutDownAChain: {type: object, allOf: [%s], %s}\n", ref("B0"), union("T")) + fmt.Fprintf(&builder, " DownAChainToNull: {allOf: [%s], %s}\n", ref("N0"), union("T")) + const hops = 300 + for i := range hops { + fmt.Fprintf(&builder, " B%d: {allOf: [%s]}\n", i, ref(fmt.Sprintf("B%d", i+1))) + fmt.Fprintf(&builder, " N%d: {allOf: [%s]}\n", i, ref(fmt.Sprintf("N%d", i+1))) } - fmt.Fprintf(&b, " B%d: {type: object}\n", maxNullConjuncts) - return b.String() + fmt.Fprintf(&builder, " B%d: {type: object}\n N%d: {type: [object, 'null']}\n", hops, hops) + return builder.String() } diff --git a/compilers/openapi/internal/schema/deadbranch_report_test.go b/compilers/openapi/internal/schema/deadbranch_report_test.go index 19cde17db..ec0693f60 100644 --- a/compilers/openapi/internal/schema/deadbranch_report_test.go +++ b/compilers/openapi/internal/schema/deadbranch_report_test.go @@ -16,13 +16,13 @@ import ( ) // TestOneOf_TheWarningOfADeadBranchSaysWhereTheUnionIs holds the one warning -// a schema with a dead branch draws to what is true of it: null satisfies a -// body admitting it beside a union taking it, by its one null branch or by -// any of them in an anyOf, and nothing satisfies a body keeping it out; a -// union on an allOf entry is judged against the rest of the allOf, which may -// admit more kinds than an object, and draws this warning only where the one -// of conjuncts sharing no value is silent, as where its null branch takes the -// null of a rest admitting it. +// a schema with a dead branch draws to what is true of it: null alone +// satisfies a body admitting it beside a union taking it, which warns of +// nothing; a oneOf whose two null branches both take it refuses it; beside a +// body keeping null out, the nullable-inference policy lifts a null branch's +// null, leaving null alone, its dead branches named at the union; a union on +// an allOf entry is judged against the rest of the allOf, and draws this +// warning only where the one of conjuncts sharing no value reports nothing. func TestOneOf_TheWarningOfADeadBranchSaysWhereTheUnionIs(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {a: {type: string}}} @@ -55,23 +55,32 @@ func TestOneOf_TheWarningOfADeadBranchSaysWhereTheUnionIs(t *testing.T) { doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) require.NotNil(t, doc) + for _, name := range []string{"Null", "AnyNulls", "EntryNullBranch"} { + // Null alone satisfies the schema: the closed empty Enum behind a + // nullable reference, which warns of nothing. + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s admits null alone", name) + assert.Empty(t, enum.Members, name) + for _, diagnostic := range diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name) { + assert.NotEqual(t, ir.SeverityWarning, diagnostic.Severity, "%s: %s", name, diagnostic.Message) + } + } + for name, union := range map[string]string{"Forbids": "/oneOf", "EntryNoNull": "/allOf/1/oneOf"} { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s is null alone; got %T", name, typeByName(doc, name)) + assert.Empty(t, enum.Members, name) + assert.Empty(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name), name) + warned := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name+union) + require.Len(t, warned, 1, name) + assert.Contains(t, warned[0].Message, "1 of the 2 branches of this oneOf shares no value with the rest of the schema", name) + } for name, want := range map[string]string{ - "Null": "admits objects alone, null aside, and none of its 2 branches but a null one admits an object or " + - "null (oneOf/1: integer), so no instance but null satisfies this schema", - "Forbids": "admits objects alone, and none of its 2 branches admits an object (oneOf/1: integer), so no " + - "instance satisfies this schema", - "AnyNulls": "none of its 3 branches but its null ones admits an object or null (anyOf/1: integer), so no " + - "instance but null satisfies this schema", - "OneNulls": "none of its 3 branches but its null ones admits an object or null (oneOf/1: integer), so no " + - "instance satisfies this schema", + "OneNulls": "null matches more than one of them, which a oneOf refuses; lowered as ", "Entry": "1 of the 2 branches of the oneOf on allOf/1 admits no value the rest of the allOf admits " + "(allOf/1/oneOf/1: boolean), so no instance satisfies it", - "EntryNull": "the conjuncts of this allOf share no value (allOf/0: object, allOf/1: string or boolean)", - "EntryNullBranch": "none of the 2 branches of the oneOf on allOf/1 but a null one admits a value the rest " + - "of the allOf admits (allOf/1/oneOf/1: string), so no instance but null satisfies this schema", - "EntryNoNull": "the conjuncts of this allOf share no value", + "EntryNull": "no value satisfies every allOf entry (allOf/0: object, allOf/1: string or boolean)", } { - reports := diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/"+name) + reports := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name) var warned []string for _, diagnostic := range reports { if diagnostic.Severity == ir.SeverityWarning { diff --git a/compilers/openapi/internal/schema/deadbranch_route_test.go b/compilers/openapi/internal/schema/deadbranch_route_test.go index 025148ad9..877f153ce 100644 --- a/compilers/openapi/internal/schema/deadbranch_route_test.go +++ b/compilers/openapi/internal/schema/deadbranch_route_test.go @@ -16,7 +16,7 @@ import ( ) // TestDiscriminator_ARouteToADeadBranchRoutesNowhere holds each route the -// discriminator standing with a distributed union takes to a branch no +// discriminator beside a distributed union takes to a branch no // instance of the body satisfies to no route: a mapping entry and a // defaultMapping left out of the Discriminator and kept verbatim beside it, // the name of the branch's component leaving the Mapping too, and the one @@ -59,7 +59,7 @@ func TestDiscriminator_ARouteToADeadBranchRoutesNowhere(t *testing.T) { "Unlocated": `no tag of the discriminator routes to it (mapping "s", the name "Str"), the routes it writes`, } { var warned []string - for _, diagnostic := range diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/"+name) { + for _, diagnostic := range diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name) { if diagnostic.Severity == ir.SeverityWarning { warned = append(warned, diagnostic.Message) } @@ -67,7 +67,7 @@ func TestDiscriminator_ARouteToADeadBranchRoutesNowhere(t *testing.T) { require.Len(t, warned, 1, name) assert.Contains(t, warned[0], want, name) } - assert.NotContains(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Twice")[0].Message, + assert.NotContains(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/Twice")[0].Message, "no tag", "a name two branches name routes to neither") written, ok := doc.Types[componentID("Written")].(*ir.Union) diff --git a/compilers/openapi/internal/schema/deadbranch_test.go b/compilers/openapi/internal/schema/deadbranch_test.go index dac8a68b9..1aea8799d 100644 --- a/compilers/openapi/internal/schema/deadbranch_test.go +++ b/compilers/openapi/internal/schema/deadbranch_test.go @@ -18,34 +18,30 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestOneOf_AnUnpreservableDeadBranchIsNotAnnounced pins the pairing GitHub -// #144 exists for at a branch no instance of the body satisfies: one that -// fails to convert is reported as such, the union keeps nothing for it, and the -// warning naming it claims nothing was kept. -func TestOneOf_AnUnpreservableDeadBranchIsNotAnnounced(t *testing.T) { +// TestOneOf_ADeadBranchIsKeptWithoutAnExtensionNoJSONHolds pins a branch no +// instance of the body satisfies, writing an extension whose value converts to +// no JSON: the extension alone is dropped, with its own warning at the branch, +// the union keeps and reports the branch as without it, and a valid document +// draws no error. +func TestOneOf_ADeadBranchIsKeptWithoutAnExtensionNoJSONHolds(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` A: {type: object, properties: {a: {type: string}}} + doc := requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpec(` A: {type: object, properties: {a: {type: string}}} Combo: type: object properties: {kind: {type: string}} - oneOf: [{$ref: '#/components/schemas/A'}, {type: string, x-t: `+unpreservableValue+`}] -`)) + oneOf: [{$ref: '#/components/schemas/A'}, {type: string`+unconvertibleExtension+`}] +`), unconvertibleExtension, "/components/schemas/Combo/oneOf/1") union, ok := typeByName(doc, "Combo").(*ir.Union) require.True(t, ok) require.Len(t, union.Variants, 1) - assert.NotContains(t, union.Unmodeled, "openapi:oneOf/1", "the conversion failed, so nothing was kept") - assert.True(t, openapitest.HasDiag(diags, diag.UnpreservableConstruct), "the failure itself is reported") - assert.Empty(t, openapitest.PreservationClaims(diags), - "nothing was written under Unmodeled, so nothing may announce that it was") - reports := diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Combo") - require.Len(t, reports, 1, "the branch is still named as admitting no object") - assert.Contains(t, reports[0].Message, "oneOf/1: string") + require.Contains(t, union.Unmodeled, "openapi:oneOf/1", "the dead branch is kept") + assert.JSONEq(t, `{"type":"string"}`, string(union.Unmodeled["openapi:oneOf/1"].Value)) } // TestOneOf_ADeadBranchIsReadAgainstItsEntrysOwnType pins the rest a branch of // a union written on an allOf entry is read against: the entry's own type stays -// in it, its union left out (restAdmitsObjects), so beside `type: object` on +// in it, its union left out (restOfConjunction), so beside `type: object` on // that entry a branch admitting no object is dead, and the warning says so. func TestOneOf_ADeadBranchIsReadAgainstItsEntrysOwnType(t *testing.T) { t.Parallel() @@ -57,7 +53,7 @@ func TestOneOf_ADeadBranchIsReadAgainstItsEntrysOwnType(t *testing.T) { union, ok := typeByName(doc, "S").(*ir.Union) require.True(t, ok, "%T", typeByName(doc, "S")) assert.Len(t, union.Variants, 1, "the string branch is no variant") - reports := diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/S") + reports := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/S") require.Len(t, reports, 1, "%+v", diags) assert.Contains(t, reports[0].Message, "(allOf/0/oneOf/0: string)") } @@ -92,7 +88,7 @@ func TestOneOf_ADeadBranchIsReadForTheNullTheBodyAdmits(t *testing.T) { require.True(t, ok) want := map[bool]int{false: 2, true: 1}[off] assert.Len(t, flagged.Variants, want, "policy off %t", off) - assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Flagged"), 2-want, + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/Flagged"), 2-want, "a warning where the branch is dead, policy off %t", off) } } diff --git a/compilers/openapi/internal/schema/decidingconjunct.go b/compilers/openapi/internal/schema/decidingconjunct.go new file mode 100644 index 000000000..90b138473 --- /dev/null +++ b/compilers/openapi/internal/schema/decidingconjunct.go @@ -0,0 +1,232 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "bytes" + "slices" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// chooseConjunctToLowerFrom picks the conjunct the position lowers from, refs +// being the $refs that may be: an inline value set within every other, since +// it fixes the values; else a $ref, since replacing it drops what its target +// says; else the conjunct naming a kind within the most others. No tie goes +// by the order written. +func (reader *admissionReader) chooseConjunctToLowerFrom(conjuncts []conjunct, refs []*conjunct) *conjunct { + for i := range conjuncts { + if reader.narrowsAll(conjuncts, i, refs) { + return untie(reader, conjuncts, narrowingSets(conjuncts, i, refs)) + } + } + if len(refs) > 0 { + return narrowestRef(reader, conjuncts, refs) + } + tied := mostWithin(reader, conjuncts) + if len(tied) > 1 && !admitAlike(reader, tied) { + return &conjuncts[0] + } + return untie(reader, conjuncts, tied) +} + +// narrowingSets returns the value sets within every other conjunct, the first +// of them at i: those after it whose kinds and values are its own, as each +// set within every other is within the first, and the first within it. +func narrowingSets(conjuncts []conjunct, i int, refs []*conjunct) []*conjunct { + first := &conjuncts[i] + sets := []*conjunct{first} + for j := i + 1; j < len(conjuncts); j++ { + conjunct := &conjuncts[j] + if conjunct.read.fixed && !slices.Contains(refs, conjunct) && sameValues(conjunct.read, first.read) { + sets = append(sets, conjunct) + } + } + return sets +} + +// sameValues reports whether a and b, two value sets, admit the same kinds and +// hold the same members. +func sameValues(a, b admitted) bool { + return a.kindsWithin(b) && b.kindsWithin(a) && a.valuesWithin(b) && b.valuesWithin(a) +} + +// mostWithin returns the conjuncts naming a kind that lie within the most +// conjuncts, in the order written. +func mostWithin(admissionReaderValue *admissionReader, conjuncts []conjunct) []*conjunct { + var tied []*conjunct + most := 0 + for i := range conjuncts { + conjunct := &conjuncts[i] + if !conjunct.declaresKind { + continue + } + switch n := admissionReaderValue.countConjunctsContaining(conjuncts, conjunct.read); { + case n > most: + tied, most = append(tied[:0], conjunct), n + case n == most: + tied = append(tied, conjunct) + } + } + return tied +} + +// admitAlike reports whether each of tied lies within every other: what they admit +// is one, so far as a reading holds it. +func admitAlike(admissionReaderValue *admissionReader, tied []*conjunct) bool { + first := tied[0].read + return !slices.ContainsFunc(tied[1:], func(conjunct *conjunct) bool { + return !admissionReaderValue.within(first, conjunct.read) || !admissionReaderValue.within(conjunct.read, first) + }) +} + +// untie returns which of tied the position lowers from. With none tied, the +// keywords beside the allOf, conjuncts[0], decide +// (docs/compilers/openapi.md#allof-refinement). +func untie(admissionReaderValue *admissionReader, conjuncts []conjunct, tied []*conjunct) *conjunct { + switch len(tied) { + case 0: + return &conjuncts[0] + case 1: + return tied[0] + default: + return untieWords(admissionReaderValue, &conjuncts[0], tied) + } +} + +// principalKeywords are the keywords a node's build reads from the principal +// alone and no other conjunct folds into, so two conjuncts admitting alike +// still part on them: what each lowers its elements or its content by. +var principalKeywords = slices.Concat([]string{"items", "prefixItems", "additionalItems"}, contentKeywords) + +// untieWords returns which of tied, conjuncts admitting alike, the position +// lowers from. The pick shows only in principalKeywords, so it is one writing +// every such keyword any other does, alike, else beside, the keywords beside +// the allOf. +func untieWords(admissionReaderValue *admissionReader, beside *conjunct, tied []*conjunct) *conjunct { + most := slices.MaxFunc(tied, func(a, b *conjunct) int { + return countKeys(a.schema, principalKeywords) - countKeys(b.schema, principalKeywords) + }) + if slices.ContainsFunc(tied, func(conjunct *conjunct) bool { return !writesWithin(conjunct.schema, most.schema) }) { + return beside + } + tied = slices.DeleteFunc(slices.Clone(tied), func(conjunct *conjunct) bool { return !writesWithin(most.schema, conjunct.schema) }) + if slices.Contains(tied, beside) { + return beside + } + return leastText(admissionReaderValue, tied) +} + +// countKeys counts the keys of keys schema writes (hasKey). +func countKeys(schema *statement.Schema, keys []string) int { + n := 0 + for _, key := range keys { + if hasKey(schema, key) { + n++ + } + } + return n +} + +// writesWithin reports whether each of principalKeywords a writes, b writes +// alike. +func writesWithin(a, b *statement.Schema) bool { + return !slices.ContainsFunc(principalKeywords, func(key string) bool { + return hasKey(a, key) && (!hasKey(b, key) || !keyRendering(a, key).agrees(keyRendering(b, key))) + }) +} + +// leastText returns the one of tied whose text, keys sorted, is least +// bytewise, which no order written decides. Of a schema written twice, the +// first copy names both: the one place order shows, in that node's pointer. +func leastText(admissionReaderValue *admissionReader, tied []*conjunct) *conjunct { + best := tied[0] + for _, conjunct := range tied[1:] { + if bytes.Compare(writtenText(admissionReaderValue.loweringContext, conjunct.entry.schema), writtenText(admissionReaderValue.loweringContext, best.entry.schema)) < 0 { + best = conjunct + } + } + return best +} + +// narrowestRef returns the one of refs lying within the most conjuncts, a tie +// going by refBefore, so no order written decides. Of a $ref written twice +// alike, the first copy is taken for both. +func narrowestRef(admissionReaderValue *admissionReader, conjuncts []conjunct, refs []*conjunct) *conjunct { + best, most := refs[0], admissionReaderValue.countConjunctsContaining(conjuncts, refs[0].read) + for _, ref := range refs[1:] { + n := admissionReaderValue.countConjunctsContaining(conjuncts, ref.read) + if n > most || n == most && refBefore(admissionReaderValue, ref, best) { + best, most = ref, n + } + } + return best +} + +// refBefore reports whether the $ref conjunct a goes before b: by reference +// text, which edits to its target leave alone, then by the entry's text. +func refBefore(admissionReaderValue *admissionReader, a, b *conjunct) bool { + if order := strings.Compare(refText(a), refText(b)); order != 0 { + return order < 0 + } + return bytes.Compare(entryText(admissionReaderValue.loweringContext, a.entry.schema), entryText(admissionReaderValue.loweringContext, b.entry.schema)) < 0 +} + +// entryText is the text of the allOf entry the $ref conjunct schemaStatement +// names, with the keywords beside its reference, which schemaStatement leaves +// out: without them two entries alike but for those would tie on order. +func entryText(loweringContext lowering.Ctx, schemaStatement *statement.Statement) ir.RawValue { + if at, placed := siteOf(schemaStatement.Schema); placed { + if held := loweringContext.Statements().At(at); held.Schema != nil && held.Schema != schemaStatement.Schema { + return writtenText(loweringContext, held) + } + } + return writtenText(loweringContext, schemaStatement) +} + +// refText is the reference the $ref conjunct conjunct writes, as written. +func refText(conjunct *conjunct) string { + _, text := refSpelling(conjunct.entry.schema) + return text +} + +// narrowsAll reports whether conjunct i is a value set within every other and +// more than a restatement of what a $ref of refs fixes. No set is compared +// with itself, which answers nothing and walks the whole set. +func (reader *admissionReader) narrowsAll(conjuncts []conjunct, i int, refs []*conjunct) bool { + candidate := &conjuncts[i] + if !candidate.read.fixed || slices.Contains(refs, candidate) || + slices.ContainsFunc(refs, func(ref *conjunct) bool { return reader.setWithin(ref.read, candidate.read) }) { + return false + } + for j := range conjuncts { + if conjunct := &conjuncts[j]; j != i && (!candidate.read.kindsWithin(conjunct.read) || !reader.setWithin(candidate.read, conjunct.read)) { + return false + } + } + return true +} + +// setWithin is a.valuesWithin(b), telling walked how many members it looked up. +func (reader *admissionReader) setWithin(a, b admitted) bool { + within, walked := a.walkWithin(b) + if reader.walked != nil { + reader.walked(walked) + } + return within +} + +// countConjunctsContaining counts the conjuncts what read admits lies within. +func (reader *admissionReader) countConjunctsContaining(conjuncts []conjunct, read admitted) int { + n := 0 + for j := range conjuncts { + if reader.within(read, conjuncts[j].read) { + n++ + } + } + return n +} diff --git a/compilers/openapi/internal/schema/decision.go b/compilers/openapi/internal/schema/decision.go deleted file mode 100644 index f73b6c150..000000000 --- a/compilers/openapi/internal/schema/decision.go +++ /dev/null @@ -1,914 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "encoding/json/jsontext" - "slices" - - yaml "go.yaml.in/yaml/v3" - - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/reftable" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" -) - -// maxRefinedConjuncts bounds the conjuncts one election compares, every pair of -// them: an allOf past it stays a composition, which loses nothing. -const maxRefinedConjuncts = 64 - -// refinement is an allOf whose kinds are not an object alone: one use of the -// conjunct that decides it, its principal, rather than a composition -// (docs/compilers/openapi.md#allof-refinement). -type refinement struct { - comp allOfComposition - // principal is the entry the position is a use of, nil where the keywords - // written beside the allOf decide it or nothing does. - principal *allOfEntry - // ref is the $ref entry a use reads on through: the principal where it is - // one, else the one $ref written, nil where none or several are. - ref *allOfEntry - // votes is how each entry of comp stood in the election, by index: a - // $ref the position's kinds outvoted, or one another conjunct beat. - votes []refCandidacy - // joint is what the conjuncts admit together. - joint admitted - // held is what the position lowers to admits, which decides what a keyword - // left unread loses. - held admitted - // contradicts marks conjuncts sharing no value: a value set was elected - // before the composition they would otherwise lower to, or, for value sets - // sharing no member, no conjunct was (decide). - contradicts bool -} - -// principalIs reports whether e is the entry the position lowers from: its -// schema at its pointer, as an entry writing a $ref beside other keys is two -// entries at one pointer (statement.Entry). -func (r refinement) principalIs(allOfEntryValue allOfEntry) bool { - return r.principal != nil && r.principal.pointer == allOfEntryValue.pointer && r.principal.schema == allOfEntryValue.schema -} - -// refCandidacy is how a $ref conjunct stood in the election of a principal. -type refCandidacy uint8 - -const ( - // refCandidateForDecidingConjunct marks a $ref that could be the principal, - // and is, or lost to a value set. - refCandidateForDecidingConjunct refCandidacy = iota - // refNarrowed marks one another $ref beat, lying within more conjuncts. - refNarrowed - // refInferredApart marks one whose target the kind-inference policy reads - // as a kind the position's declarations exclude. - refInferredApart - // refAdmitsEvery marks one whose target admits every kind beside a - // position declaring its kinds. - refAdmitsEvery - // refOutsideSet marks one whose target admits none of the value set - // elected before the composition the conjuncts would lower to. - refOutsideSet - // refApart marks one of conjuncts whose value sets share no member, of - // which none is the principal (decide). - refApart -) - -// conjunct is one conjunct's reading, for the election. -type conjunct struct { - // entry is nil for the keywords written beside the allOf, and at is its - // index among the composition's entries. - entry *allOfEntry - at int - read admitted - // schema writes the conjunct's keywords: the entry's, or the position's - // for the keywords beside the allOf. - schema *statement.Schema - // says marks an inline conjunct writing what kind of value this is, and - // form how it names it. - says bool - form conjunctForm -} - -// conjunctForm is how an inline conjunct names its kinds, ranked for a tie -// between two lying within as many conjuncts: a union before the words, which -// then bound it, and a oneOf before an anyOf, as the one Union a schema -// writing both lowers to is its oneOf's -// (docs/compilers/openapi.md#competing-keywords). -type conjunctForm uint8 - -const ( - // formWords marks a conjunct naming its kinds by `type`, `enum` or `const`. - formWords conjunctForm = iota - // formAnyOf marks one writing an anyOf and no oneOf. - formAnyOf - // formOneOf marks one writing a oneOf. - formOneOf -) - -// unionForm is the form of a conjunct whose keywords schema writes, its unions -// among them. -func unionForm(schema *statement.Schema) conjunctForm { - switch choice := schema.ChoiceKeywords(); { - case len(choice.OneOf) > 0: - return formOneOf - case len(choice.AnyOf) > 0: - return formAnyOf - default: - return formWords - } -} - -// decisionAt keys a schema's decision: nothing decide reads turns on where the -// schema is written, which only prefixes its entries' pointers. -type decisionAt struct { - schema *statement.Schema -} - -// decision is what a position's readers share: a refinement, where it is one, -// its composition, principal and ref left for refinementOf to read at the -// pointer asked; the indices of that principal and ref among the entries, -1 -// for none and the principal for the keywords beside the allOf; whether a -// union written beside the allOf shares no kind with the rest, which the -// position leaves out and keeps (unionAside); apart, what each conjunct -// states where the election found they share no value (apartNames). -type decision struct { - r refinement - apart []string - principalAt int - refAt int - refines bool - aside bool -} - -// refinementOf decides whether schema, written at pointer, refines rather than -// composes (docs/compilers/openapi.md#allof-refinement). It reads the source and -// the bindings, never the registry, so a decision turns on no lowering order, and -// the many readers of a schema share one reading wherever it is written. -func refinementOf(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (refinement, bool) { - decision := decisionOf(loweringContext, schema) - if !decision.refines { - return refinement{}, false - } - refinementValue := decision.r - refinementValue.comp = allOfEntries(loweringContext, schema, pointer) - refinementValue.principal, refinementValue.ref = entryAt(refinementValue.comp, decision.principalAt), entryAt(refinementValue.comp, decision.refAt) - return refinementValue, true -} - -// entryAt returns the entry of comp at index i, nil for -1. -func entryAt(comp allOfComposition, i int) *allOfEntry { - if i < 0 { - return nil - } - return &comp.entries[i] -} - -// entryStatement returns the statement of the entry of s's allOf at index i, as -// allOfEntries reads it, nil for -1: a reader of the decision with no pointer -// builds no entry list. -func entryStatement(loweringContext lowering.Ctx, schema *statement.Schema, i int) *statement.Statement { - if i < 0 { - return nil - } - return loweringContext.Statements().Read(loweringContext.Statements().Read(schema).Entries[i].Schema) -} - -// decisionOf returns the decision on schema, read once a run, and none where -// its allOf may not refine. -func decisionOf(loweringContext lowering.Ctx, schema *statement.Schema) decision { - if !allOfMayRefine(schema) { - return decision{} - } - return lowering.ReadOncePerRun(loweringContext, decisionAt{schema}, func() decision { return decide(loweringContext, schema) }) -} - -// unionAside reports whether the oneOf or anyOf schema writes beside its allOf -// shares no kind with what the rest of schema admits: no instance satisfies -// them together, so the position lowers as the rest does and keeps the union -// (docs/compilers/openapi.md#union-beside-structure). -func unionAside(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return decisionOf(loweringContext, schema).aside -} - -// usesOneRef reports whether schema, whose flattened conjuncts are comp, is a -// use of one target saying nothing of it: one conjunct is a $ref writing -// nothing read beside it, as an entry read whole may (statement.ReadBeside), -// and schema and every other conjunct state nothing (statesNothing), or, where -// a carrier holds schema's position (carriedAt), nothing but what binds the use -// (bindsUseOnly), which the carrier holds. It is the reference, as the $ref -// alone is (docs/compilers/openapi.md#allof-classification). -func usesOneRef(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) bool { - carried := carriedAt(loweringContext, schema) - quiet := func(statementSchema *statement.Schema) bool { - return statesNothing(statementSchema) || carried && bindsUseOnly(loweringContext, statementSchema) - } - refs := 0 - for _, entry := range comp.entries { - switch { - case entry.schema.Ref != nil && slices.ContainsFunc(entry.schema.Keys, func(key statement.Key) bool { - return statement.ReadBeside(key.Name, key.Node, entry.schema.Ref.Keyword) - }): - return false - case entry.schema.Ref != nil: - refs++ - case !quiet(entry.schema.Schema): - return false - } - } - return refs == 1 && quiet(schema) -} - -// bindsUseOnly reports whether every key schema writes that says something of -// the instance binds a use of the type rather than the type: one of -// residueKeywords, or a `nullable: true` the nullable-inference policy reads as -// widening the reference (docs/compilers/openapi.md#nullable), each of which a -// carrier holds and a node cannot -// (docs/compilers/openapi.md#use-bound-annotations). -func bindsUseOnly(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return schema.Truth == statement.Stated && !slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { - switch { - case key.Name == "allOf" && len(schema.AllOf) > 0, !statement.ReadBeside(key.Name, key.Node, ""), - slices.Contains(residueKeywords, key.Name): - return false - case key.Name == "nullable": - return !loweringContext.NullableInference.Honours() || !nullableTrue(schema) - default: - return true - } - }) -} - -// carriedAt reports whether a carrier holds the position the bindings place -// schema at: a property a schema lists, or the schema of a parameter or a -// header, its content's included. It reads the placement, never the lowering -// that reaches schema, so every reader of schema's decision, the carrier's and -// a $ref's naming the position alike, reads one answer. -func carriedAt(loweringContext lowering.Ctx, schema *statement.Schema) bool { - at, placed := siteOf(schema) - if !placed { - return false - } - pointer := at.Pointer - if pointer.Parent().LastToken() == "properties" { - owner := loweringContext.Statements().At(reftable.DocumentPointer{Doc: at.Doc, Pointer: pointer.Parent().Parent()}) - return owner.Truth == statement.Stated && slices.ContainsFunc(owner.ObjectKeywords().Properties, func(sub statement.Subschema) bool { - return sub.Name == pointer.LastToken() && loweringContext.Statements().Subschema(sub).Schema == schema - }) - } - if pointer.LastToken() != "schema" { - return false - } - holder := reftable.DocumentPointer{Doc: at.Doc, Pointer: pointer.Parent()} - if holder.Pointer.Parent().LastToken() == "content" { - holder.Pointer = holder.Pointer.Parent().Parent() - } - return loweringContext.Bindings().ObjectAt(holder, reftable.RefParameter) != nil || loweringContext.Bindings().ObjectAt(holder, reftable.RefHeader) != nil -} - -// statesNothing reports whether schema states nothing of the instance: `true`, -// a value written as no schema (docs/compilers/openapi.md#null-schema), or a -// schema object writing nothing but the allOf its statement flattens, a list -// holding an entry, and keys that say nothing of the instance -// (statement.ReadBeside): a comment, an anchor, schemas a reference reaches, a -// keyword left out. -func statesNothing(schema *statement.Schema) bool { - if schema.Truth == statement.Anything || schema.Truth == statement.Unwritten { - return true - } - return schema.Truth == statement.Stated && !slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { - return (key.Name != "allOf" || len(schema.AllOf) == 0) && statement.ReadBeside(key.Name, key.Node, "") - }) -} - -// decide reads what refinementOf remembers. Two unions standing alone elect -// one (unionPair). Else conjuncts sharing no value, or whose kinds, null -// aside, are an object alone, compose, unless it first elects a conjunct's -// value set (docs/compilers/openapi.md#competing-keywords) or, where they share -// one, a union standing alone (soleUnion); so does a read cut short, or past a -// cap but weighing one $ref alone (pastAlone). Value sets sharing no member -// compose a Model only where those kinds are an object alone; elsewhere the -// keywords beside the allOf decide. Anything else, a use of one target saying -// nothing more (usesOneRef) included, uses its principal. -func decide(loweringContext lowering.Ctx, schema *statement.Schema) decision { - comp := allOfEntries(loweringContext, schema, "") - if !refinableEntries(comp) { - return decision{} - } - admissionReader := newAdmissionReader(loweringContext) - // The decision is remembered by schema alone, so schema is read in its own - // document's dialect, never in that of the reader asking first. - admissionReader.nullable = definesNullableAt(loweringContext, loweringContext.Statements().Read(schema)) - conjuncts, aside := admissionReader.conjuncts(schema, comp) - joint := conjuncts[0].read - for _, cj := range conjuncts[1:] { - joint = joint.and(cj.read) - } - if composesNullPair(loweringContext, schema, conjuncts, joint, aside) { - return decision{} - } - kinds, inferred := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) - if aside { - kinds, inferred = restKinds(loweringContext, schema, comp) - } - var principal *conjunct - if !aside { - // A pair the reading puts aside lowers as the rest, standing alone or not. - principal = unionPair(loweringContext, schema, conjuncts) - } - one := usesOneRef(loweringContext, schema, comp) - contradicts := !one && disjoint(joint, conjuncts, pairEntries(schema, conjuncts)) - apart := contradicts && joint.fixed && joint.kinds&^kindNull != 0 && kinds != kindObject - var names []string - if contradicts { - names = apartNames(schema, comp, conjuncts, joint) - } - if principal == nil && (contradicts || kinds == kindObject && !one) { - principal = composingElected(loweringContext, &admissionReader, schema, conjuncts, contradicts) - if principal == nil && !apart { - return decision{aside: aside, apart: names} - } - } - votes, electable := voteRefs(loweringContext, conjuncts, kinds, inferred, len(comp.entries)) - undecided := principal == nil && apart - switch { - case undecided: - principal = &conjuncts[0] - case principal == nil: - principal = pairedWith(loweringContext, schema, conjuncts, admissionReader.chooseConjunctToLowerFrom(conjuncts, electable)) - } - principal = nullPairBody(loweringContext, schema, conjuncts, joint, principal) - refinementValue := refinement{votes: votes, joint: joint, held: pairHeld(loweringContext, schema, conjuncts, principal), contradicts: contradicts} - refAt := readThrough(conjuncts, principal) - markBeaten(&admissionReader, refinementValue.votes, electable, principal, contradicts, undecided) - // A use saying nothing more of a reference naming no schema is that - // reference, which has nothing for the read to finish. - failed := one && refAt >= 0 && !namesReferent(loweringContext, comp.entries[refAt].schema) - refines := failed || !admissionReader.incomplete() || !admissionReader.cut && pastAlone(loweringContext, conjuncts, one) - return decision{r: refinementValue, apart: names, principalAt: principal.at, refAt: refAt, refines: refines, aside: aside} -} - -// composingElected returns the conjunct elected where the conjuncts of schema -// would otherwise compose: a value set one states (setElected), else, where -// they share a value (contradicts says not), a union standing alone -// (soleUnion), and nil where neither is. -func composingElected(loweringContext lowering.Ctx, admissionReaderValue *admissionReader, schema *statement.Schema, conjuncts []conjunct, contradicts bool) *conjunct { - if set := setElected(admissionReaderValue, schema, conjuncts); set != nil || contradicts { - return set - } - return soleUnion(loweringContext, schema, conjuncts) -} - -// soleUnion returns the inline conjunct writing the union the position is, -// nothing beside it conjoining with it, as hasUnionSiblings reads one written -// at the position (docs/compilers/openapi.md#union-beside-structure): one -// conjunct writes a union (unionEntries) and nothing else conjoins with it -// (standsAlone). -func soleUnion(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct) *conjunct { - unions := unionEntries(schema, conjuncts) - if len(unions) != 1 || !standsAlone(loweringContext, schema, conjuncts, unions, unions[0]) { - return nil - } - return unions[0] -} - -// unionPair returns the conjunct writing the union the position elects where -// its conjuncts write a oneOf and an anyOf, on one inline entry or one each on -// two, and nothing else conjoining with them (standsAlone): the -// position is then one schema writing both -// (docs/compilers/openapi.md#competing-keywords), whatever the kinds their -// branches admit. -func unionPair(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct) *conjunct { - unions := unionEntries(schema, conjuncts) - elected := pairElected(loweringContext, schema, unions) - if elected == nil || !standsAlone(loweringContext, schema, conjuncts, unions, elected) { - return nil - } - return elected -} - -// pairElected returns the conjunct of unions whose union the position elects -// where they write one oneOf and one anyOf between them: the one entry -// writing both, which elects within itself (unionBranches), or of two entries -// the one whose branches declare shape against the position, the oneOf's where -// both or neither do, as anyOfElected reads one schema; else nil. -func pairElected(loweringContext lowering.Ctx, schema *statement.Schema, unions []*conjunct) *conjunct { - if len(unions) == 1 { - if choice := unions[0].schema.ChoiceKeywords(); len(choice.OneOf) > 0 && len(choice.AnyOf) > 0 { - return unions[0] - } - return nil - } - if len(unions) != 2 { - return nil - } - one, other := unions[0], unions[1] - if len(one.schema.ChoiceKeywords().OneOf) == 0 { - one, other = other, one - } - oneOf, anyOf := one.schema.ChoiceKeywords(), other.schema.ChoiceKeywords() - if len(oneOf.AnyOf) > 0 || len(oneOf.OneOf) == 0 || len(anyOf.OneOf) > 0 || len(anyOf.AnyOf) == 0 { - return nil - } - if !setsDeclareShape(loweringContext, schema, one.schema, oneOf.OneOf) && setsDeclareShape(loweringContext, schema, other.schema, anyOf.AnyOf) { - return other - } - return one -} - -// pairedWith returns the conjunct the refinement elects where elected writes -// one union of a oneOf and an anyOf written one each on two inline entries -// (pairEntries): of the two, the one competing keywords prefer at schema -// (pairElected), as one schema writing both elects, not the one the kinds of -// the conjuncts favour (docs/compilers/openapi.md#competing-keywords). Else it -// is elected. pairEntries finds one oneOf and one anyOf, so pairElected -// returns one of them. -func pairedWith(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct, elected *conjunct) *conjunct { - unions := pairEntries(schema, conjuncts) - if !slices.Contains(unions, elected) { - return elected - } - return pairElected(loweringContext, schema, unions) -} - -// nullPairBody returns the conjunct a position elects where the oneOf and the -// anyOf written for it admit null alone (pairNullAlone) and its conjuncts -// share that null: the first entry writing no union that says what the -// position is, so the position is a use of that body keeping both, as a $ref -// body is elected by its vote (docs/compilers/openapi.md#allof-refinement). -// It is elected, the conjunct elected without it, where none is. -func nullPairBody(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct, joint admitted, elected *conjunct) *conjunct { - if !joint.reachable() || !pairNullAlone(loweringContext, schema) { - return elected - } - for i := range conjuncts { - if cj := &conjuncts[i]; cj.entry != nil && cj.says && !declaresUnion(cj.schema) { - return cj - } - } - return elected -} - -// composesNullPair reports whether the body nullPairBody finds for a position -// not setting its unions aside admits objects alone, null aside: the allOf -// then composes it keeping both, its Model standing at the position as the -// schema writing all three flat does -// (docs/compilers/openapi.md#union-beside-structure). -func composesNullPair(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct, joint admitted, aside bool) bool { - body := nullPairBody(loweringContext, schema, conjuncts, joint, nil) - return !aside && body != nil && body.read.kinds&^kindNull == kindObject -} - -// pairEntries returns the two inline entries writing a union, one a oneOf -// and the other an anyOf, where they are the only conjuncts writing one, and -// nil otherwise. -func pairEntries(schema *statement.Schema, conjuncts []conjunct) []*conjunct { - if declaresUnion(schema) { - return nil - } - var unions []*conjunct - for i := range conjuncts { - cj := &conjuncts[i] - if cj.entry != nil && cj.entry.schema.Ref == nil && !cj.entry.wrapper && declaresUnion(cj.schema) { - unions = append(unions, cj) - } - } - if len(unions) != 2 || writesBothUnions(unions[0].schema) || writesBothUnions(unions[1].schema) || - (len(unions[0].schema.ChoiceKeywords().OneOf) > 0) == (len(unions[1].schema.ChoiceKeywords().OneOf) > 0) { - return nil - } - return unions -} - -// pairHeld is what the position lowering to principal admits: what principal -// does, and where it writes one union of a pair on two entries (pairEntries, -// pairElected), what the union passed over admits too, as one schema writing -// both holds both. -func pairHeld(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct, principal *conjunct) admitted { - held := heldBy(loweringContext, principal) - unions := pairEntries(schema, conjuncts) - if !slices.Contains(unions, principal) || pairElected(loweringContext, schema, unions) != principal { - return held - } - other := unions[0] - if other == principal { - other = unions[1] - } - return held.and(heldBy(loweringContext, other)) -} - -// unionEntries returns the conjuncts writing a union where each is an inline -// entry writing no allOf of its own, schema writes no union and no conjunct is -// a $ref, and nil otherwise. The unions are looked for first, as most composing -// allOfs write none. -func unionEntries(schema *statement.Schema, conjuncts []conjunct) []*conjunct { - if declaresUnion(schema) { - return nil - } - var unions []*conjunct - for i := range conjuncts { - cj := &conjuncts[i] - switch { - case cj.entry == nil || cj.entry.schema.Ref == nil && !declaresUnion(cj.schema): - case cj.entry.schema.Ref != nil || cj.entry.wrapper: - return nil - default: - unions = append(unions, cj) - } - } - return unions -} - -// standsAlone reports whether nothing beside unions, the conjuncts -// writing them, conjoins with them, elected writing the one the position is: no -// other conjunct writes a discriminator, which routes that union, and each -// keyword a conjunct writes that a variant would carry (siblingKeywords), an -// allOf aside, every branch of each union says (branchesSay), a union declaring -// shape against the rest where one is written. -func standsAlone(loweringContext lowering.Ctx, schema *statement.Schema, conjuncts []conjunct, unions []*conjunct, elected *conjunct) bool { - written := false - for i := range conjuncts { - cj := &conjuncts[i] - if cj != elected && cj.schema.Discriminator() != nil { - return false - } - keys := slices.DeleteFunc(siblingKeywords(cj.schema), func(k string) bool { return k == "allOf" }) - if len(keys) == 0 { - continue - } - for _, conjunct := range unions { - said := branchesSay(loweringContext, conjunct.schema, cj.schema) - if slices.ContainsFunc(keys, func(k string) bool { return !slices.Contains(said, k) }) { - return false - } - } - written = true - } - return !written || slices.ContainsFunc(unions, func(conjunctValue *conjunct) bool { - choice := conjunctValue.schema.ChoiceKeywords() - return setsDeclareShape(loweringContext, schema, conjunctValue.schema, choice.OneOf, choice.AnyOf) - }) -} - -// pastAlone reports whether conjuncts, read past a cap, still refine: the -// election weighs one $ref and nothing else (soleRef), so it compares no two -// readings, which is all a cap stops. What it leaves open is whether the -// conjunction admits a value, read through the target's kinds, whole past a -// cap, null aside, and not asked of a use saying nothing more (one), as within -// the caps (docs/compilers/openapi.md#allof-refinement). -func pastAlone(loweringContext lowering.Ctx, conjuncts []conjunct, one bool) bool { - ref := soleRef(conjuncts) - if ref == nil { - return false - } - kinds, _ := lowersTo(loweringContext, ref.entry.schema) - return one || kinds != 0 -} - -// soleRef returns the one $ref of conjuncts where every other conjunct names -// no kind and holds an instance to nothing a reading compares -// (admitsEverything), and nil where none or several are, or another conjunct -// is weighed. -func soleRef(conjuncts []conjunct) *conjunct { - var ref *conjunct - for i := range conjuncts { - cj := &conjuncts[i] - isRef := cj.entry != nil && cj.entry.schema.Ref != nil - switch { - case isRef && ref == nil: - ref = cj - case isRef || cj.says || !cj.read.admitsEverything(): - return nil - } - } - return ref -} - -// markBeaten marks in votes how each $ref of electable stood once principal -// was elected: beaten by a $ref principal, outside the value set elected for -// conjuncts that contradict one another, or, where value sets sharing no -// member leave no conjunct the principal (undecided), apart. -func markBeaten(admissionReaderValue *admissionReader, votes []refCandidacy, electable []*conjunct, principal *conjunct, contradicts, undecided bool) { - for _, cj := range electable { - switch { - case undecided: - votes[cj.at] = refApart - case cj != principal && principal.entry != nil && principal.entry.schema.Ref != nil: - votes[cj.at] = refNarrowed - case contradicts && !admissionReaderValue.within(principal.read, cj.read): - votes[cj.at] = refOutsideSet - } - } -} - -// setElected returns the conjunct stating a value set that is elected before -// a composition: of the sets lying within every other stated, the one untie -// picks among sets alike, and nil where none states one, none lies within the -// rest, or untie elects none. A $ref's target is no statement of the -// position's. A set its own keywords leave no value is read as the keyword -// competing keywords pick (competingSet), so it lowers alike beside the allOf -// and on an entry; one that keyword leaves none either, as `enum: []`, is none -// to lower: the composition reports it. -func setElected(admissionReaderValue *admissionReader, schema *statement.Schema, conjuncts []conjunct) *conjunct { - var sets []*conjunct - for i := range conjuncts { - cj := &conjuncts[i] - bs := schema - if cj.entry != nil { - bs = cj.entry.schema.Schema - } - inline := cj.entry == nil || cj.entry.schema.Ref == nil - if !inline || !enumWritten(bs) && bs.Const() == nil { - continue - } - if !cj.read.reachable() { - cj.read = competingSet(admissionReaderValue, bs) - } - if cj.read.fixed && cj.read.reachable() { - sets = append(sets, cj) - } - } - within := slices.DeleteFunc(slices.Clone(sets), func(cj *conjunct) bool { - return slices.ContainsFunc(sets, func(conjunctValue *conjunct) bool { - return conjunctValue != cj && !admissionReaderValue.setWithin(cj.read, conjunctValue.read) - }) - }) - if len(within) == 0 { - return nil - } - if elected := untie(admissionReaderValue, conjuncts, strongest(within)); slices.Contains(within, elected) { - return elected - } - return nil -} - -// competingSet is what the value set s writes admits read as the dispatch of -// competing keywords lowers it, its `const` before its `enum`, each alone -// (docs/compilers/openapi.md#competing-keywords). -func competingSet(admissionReaderValue *admissionReader, schema *statement.Schema) admitted { - if constant := schema.Const(); constant != nil { - return admissionReaderValue.valueSet(valueSetOf{schema, "const"}, []*yaml.Node{constant}) - } - return admissionReaderValue.valueSet(valueSetOf{schema, "enum"}, schema.Enum()) -} - -// restKinds returns the kinds s lowers to with the union it writes beside -// its allOf left out, and whether the kind-inference policy read them: what -// its own keywords (ownKinds) and comp's entries declare, else claim, as the -// run's admission settles a statement's (settleKinds). -func restKinds(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) (kindSet, bool) { - var rest admission - rest.firm, rest.claims = ownKinds(loweringContext, schema) - for _, entry := range comp.entries { - bs := entry.schema.Schema - if entry.schema.Ref == nil && declaresUnion(bs) { - // An entry's union is the one left out, as s's own (entryUnionsApart). - var own admission - own.firm, own.claims = ownKinds(loweringContext, bs) - rest.conjoinKinds(&own) - continue - } - rest.conjoinKinds(admissionOf(loweringContext, entry.schema)) - } - rest.settleKinds() - return rest.kinds, rest.inferred -} - -// voteRefs returns how each $ref conjunct stands where the position lowers to -// kinds, declared unless inferred, indexed by entry, and the conjuncts of -// those that may be the principal. The position says what it is where those -// kinds are declared, or where a conjunct names a kind, a union beside the -// allOf among them. -func voteRefs(loweringContext lowering.Ctx, conjuncts []conjunct, kinds kindSet, inferred bool, entries int) ([]refCandidacy, []*conjunct) { - says := !inferred && kinds != anyInstance || slices.ContainsFunc(conjuncts, func(cj conjunct) bool { return cj.says }) - votes := make([]refCandidacy, entries) - var electable []*conjunct - for i := range conjuncts { - cj := &conjuncts[i] - if cj.entry == nil || cj.entry.schema.Ref == nil { - continue - } - votes[cj.at] = voteOf(loweringContext, kinds, says, cj) - if votes[cj.at] == refCandidateForDecidingConjunct { - electable = append(electable, cj) - } - } - return votes, electable -} - -// voteOf returns how the $ref conjunct ref stands where the position lowers -// to kinds and says, or not, what it is. What the document declares decides -// first (docs/compilers/openapi.md#policies): before a kind the policy reads -// off the target's shape keywords where kinds hold one, null aside, that it -// leaves out, as the target then admits that kind whole, and before a target -// admitting every kind, which says nothing of what the position is. -func voteOf(loweringContext lowering.Ctx, kinds kindSet, says bool, ref *conjunct) refCandidacy { - target, targetInferred := lowersTo(loweringContext, ref.entry.schema) - switch { - case targetInferred && (kinds&^kindNull&^target != 0 || kinds&target == 0): - return refInferredApart - case !targetInferred && target == anyInstance && says: - return refAdmitsEvery - default: - return refCandidateForDecidingConjunct - } -} - -// readThrough returns the index of the $ref entry a use of the position reads -// on through: the principal where it is a $ref, else the one $ref written, -1 -// where none or several are. -func readThrough(conjuncts []conjunct, principal *conjunct) int { - if principal.entry != nil && principal.entry.schema.Ref != nil { - return principal.at - } - ref := -1 - for _, cj := range conjuncts { - if cj.entry == nil || cj.entry.schema.Ref == nil { - continue - } - if ref >= 0 { - return -1 - } - ref = cj.at - } - return ref -} - -// heldBy returns what the position lowering to the conjunct principal admits: -// what the node an entry lowers to admits (loweredAs), and what the keywords -// beside the allOf admit where none is the principal. -func heldBy(loweringContext lowering.Ctx, principal *conjunct) admitted { - if principal.entry == nil { - return principal.read - } - return loweredAs(loweringContext, principal.entry.schema, principal.read) -} - -// refinableEntries reports whether every entry of comp can be read as a -// conjunct of a refinement: none nests past the flattening depth or is -// `false`, and there are no more than the election compares. A union on an -// entry is a conjunct admitting what its branches do (inlineConjunct). -func refinableEntries(comp allOfComposition) bool { - if len(comp.entries) > maxRefinedConjuncts { - return false - } - return !slices.ContainsFunc(comp.entries, func(allOfEntryValue allOfEntry) bool { - return allOfEntryValue.capped || allOfEntryValue.schema.Truth.ReadsFalse() - }) -} - -// conjuncts reads s's own keywords, then each entry of comp but a `true`, -// which says nothing, then a union s writes beside the allOf as part of its -// own keywords, as on an inline entry. A union sharing no kind with the rest, -// one of null alone beside a rest admitting no null among them, is left out, -// which the second result reports. A wrapper's own keywords are -// read alone: its entries are conjuncts of their own. -func (w *admissionReader) conjuncts(schema *statement.Schema, comp allOfComposition) ([]conjunct, bool) { - out := make([]conjunct, 0, 1+len(comp.entries)) - claims := inferredClaims(w.c, schema) - own := conjunct{read: w.written(schema, w.nullable), schema: schema, says: saysKind(schema) || claimsAll(w.c, schema, claims), at: -1} - if nullIdiom(w.c, schema) { - // The null is the reference's, which the policy widens (nulls.widenRef). - own.read.kinds, own.says = kindAny, false - } - out = append(out, own) - for i := range comp.entries { - entry := &comp.entries[i] - bs := entry.schema.Schema - switch { - case !stated(bs): - case entry.schema.Ref != nil: - out = append(out, conjunct{entry: entry, at: i, read: w.of(entry.schema), schema: bs}) - default: - out = append(out, conjunct{entry: entry, at: i, read: inlineConjunct(w, bs), schema: bs, - says: saysKind(bs) || declaresUnion(bs) || claimsAll(w.c, bs, claims), form: unionForm(bs)}) - } - } - if !declaresUnion(schema) { - return out, w.entryUnionsApart(schema, comp, out) - } - union, rest := unionsIn(w, schema), out[0].read - for _, cj := range out[1:] { - rest = rest.and(cj.read) - } - if rest.reachable() && (pairSharesNoValue(w.c, schema) && pairApartBeside(rest) || union.kinds != 0 && rest.kinds&union.kinds == 0) { - return out, true - } - out[0].read, out[0].says, out[0].form = out[0].read.and(union), true, unionForm(schema) - return out, false -} - -// entryUnionsApart reports whether the unions comp's inline entries write -// leave nothing beside a rest that admits a value and is no object: a oneOf -// and an anyOf sharing no value (pairApart), or unions sharing no kind with -// that rest. No instance satisfies them, so the position lowers as the rest -// does, as beside the allOf (unionAside); each such entry of out is then read -// by its own keywords alone. Beside a rest of objects alone, null aside, the -// allOf composes as it would anyway. -func (w *admissionReader) entryUnionsApart(schema *statement.Schema, comp allOfComposition, out []conjunct) bool { - rest, unions := out[0].read, admitted{kinds: kindAny} - var holders []int - for i := 1; i < len(out); i++ { - cj := &out[i] - if cj.entry == nil || cj.entry.schema.Ref != nil || !declaresUnion(cj.schema) { - rest = rest.and(cj.read) - continue - } - rest = rest.and(w.written(cj.schema, w.nullable)) - unions = unions.and(unionsIn(w, cj.schema)) - holders = append(holders, i) - } - if len(holders) == 0 || w.incomplete() || !rest.reachable() || !pairApartBeside(rest) { - return false - } - noKind := unions.kinds != 0 && rest.kinds&unions.kinds == 0 - if !noKind && (!writesUnionPair(schema, comp) || pairApart(w.c, schema) == nil) { - return false - } - for _, i := range holders { - bs := out[i].schema - out[i].read, out[i].says, out[i].form = w.written(bs, w.nullable), saysKind(bs), formWords - } - return true -} - -// pairApartBeside reports whether a oneOf and an anyOf sharing no value -// (pairApart) lower apart from a rest admitting rest: one neither every kind, -// where the two stand alone (unionPair), nor objects alone, null aside, where -// the allOf composes the Model keeping both. -func pairApartBeside(rest admitted) bool { - return rest.kinds != kindAny && rest.kinds&^kindNull != kindObject -} - -// inferredClaims returns the kinds schema lowers to, null aside, where the -// kind-inference policy read them off the claims of its conjuncts, and none -// where schema or a conjunct declares a kind. -func inferredClaims(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { - kinds, inferred := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) - if !inferred { - return 0 - } - return kinds &^ kindNull -} - -// claimsAll reports whether the keywords schema writes itself claim every kind of -// claims, the kinds the position lowers to by the kind-inference policy -// (inferredClaims): schema then says what kind of value the position is, as one -// writing that `type` would, so `{allOf: [{items: X}]}` is a use of the list -// its entry is, as `{items: X}` is one (docs/compilers/openapi.md#shape-applicator). -func claimsAll(loweringContext lowering.Ctx, schema *statement.Schema, claims kindSet) bool { - return claims != 0 && claims&^claimedKinds(loweringContext, schema) == 0 -} - -// inlineConjunct is what bs, an inline entry, admits as w reads it: its own -// keywords and the oneOf and anyOf it writes, whose branches name the kinds it -// admits. Its allOf is read apart, since its entries are conjuncts of their -// own. -func inlineConjunct(admissionReaderValue *admissionReader, bs *statement.Schema) admitted { - read := admissionReaderValue.written(bs, admissionReaderValue.nullable) - if declaresUnion(bs) { - read = read.and(unionsIn(admissionReaderValue, bs)) - } - return read -} - -// unionsIn is what an instance of each oneOf and anyOf schema writes admits -// together, any of a union's branches, as admissionReaderValue reads them. -func unionsIn(admissionReaderValue *admissionReader, schema *statement.Schema) admitted { - read := admitted{kinds: kindAny} - choice := schema.ChoiceKeywords() - for _, branches := range [][]statement.Subschema{choice.OneOf, choice.AnyOf} { - if len(branches) > 0 { - read = read.and(admissionReaderValue.union(branches)) - } - } - return read -} - -// nullIdiom reports whether schema writes beside its $ref a type naming null -// alone, which the nullable-inference policy reads as that reference or null -// (docs/compilers/openapi.md#nullable): the null widens the reference rather -// than conjoining with it, so the type says nothing else of the position. -func nullIdiom(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return schema.BesideRef != nil && loweringContext.NullableInference.Honours() && writesType(schema) && len(effectiveTypes(schema)) == 0 -} - -// saysKind reports whether schema writes what kind of value it admits. -func saysKind(schema *statement.Schema) bool { - return writesType(schema) || enumWritten(schema) || schema.Const() != nil -} - -// disjoint reports whether the conjuncts share no value. A null they all admit -// is no value a type is left to describe, unless a conjunct admits nothing else, -// the two entries of a pair (pairEntries) read together as one schema writing -// both is. Such an allOf stays a composition, and -// docs/compilers/openapi.md#allof-refinement says which report each -// contradiction gets. -func disjoint(joint admitted, conjuncts []conjunct, pair []*conjunct) bool { - if !joint.reachable() { - return true - } - if joint.kinds != kindNull || len(pair) == 2 && pair[0].read.and(pair[1].read).kinds == kindNull { - return false - } - return !slices.ContainsFunc(conjuncts, func(cj conjunct) bool { return cj.read.kinds == kindNull }) -} diff --git a/compilers/openapi/internal/schema/decision_internal_test.go b/compilers/openapi/internal/schema/decision_internal_test.go deleted file mode 100644 index 717b47315..000000000 --- a/compilers/openapi/internal/schema/decision_internal_test.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "encoding/json/jsontext" - "testing" - - "github.com/speakeasy-api/openapi/jsonschema/oas3" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" - "github.com/dexpace/morphic/compilers/openapi/internal/reftable" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" -) - -// TestRefinementOf_AnUnrefinedSchemaHoldsNothing pins that a schema whose allOf -// composes, or may not refine, gives its readers no refinement to read. -func TestRefinementOf_AnUnrefinedSchemaHoldsNothing(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Obj: {type: object, properties: {a: {type: string}}} - T: {allOf: [{$ref: '#/components/schemas/Obj'}, {properties: {b: {type: string}}}]} - U: {type: string} -`)) - for _, name := range []string{"T", "U"} { - refinement, refined := refinementOf(lowerer.Ctx, StatedIn(lowerer, componentSchema(t, lowerer, name)), jsontext.Pointer("/components/schemas/"+name)) - assert.False(t, refined, name) - assert.Empty(t, refinement.comp.entries, "%s: no entry list is built", name) - assert.Nil(t, refinement.principal, name) - } -} - -// TestEntryStatement_ReadsTheEntryAtAnIndex pins the statement a reader of the -// decision with no pointer takes for an index, and none for -1. -func TestEntryStatement_ReadsTheEntryAtAnIndex(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Port: {type: integer} - T: {allOf: [{description: d}, {$ref: '#/components/schemas/Port'}]} -`)) - schema := StatedIn(lowerer, componentSchema(t, lowerer, "T")) - assert.Nil(t, entryStatement(lowerer.Ctx, schema, -1)) - got := entryStatement(lowerer.Ctx, schema, 1) - require.NotNil(t, got) - assert.Same(t, allOfEntries(lowerer.Ctx, schema, "").entries[1].schema, got) - assert.NotNil(t, got.Ref, "the entry at 1 is the $ref") -} - -// TestCarriedAt_ReadsWhereASchemaIsWritten pins which positions a carrier -// holds by where the bindings place the schema: a property a schema lists, -// and a parameter's or a header's schema, its content's included, but not a -// component, a list's element, a schema keyed `schema` beneath a component -// named as a carrier's collection is, nor a schema no binding places. -func TestCarriedAt_ReadsWhereASchemaIsWritten(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, `openapi: 3.1.0 -info: {title: t, version: "1"} -paths: - /x: - get: - parameters: - - {name: q, in: query, schema: {type: string}} - - {name: c, in: query, content: {application/json: {schema: {type: string}}}} - responses: {"204": {description: ok, headers: {X-A: {schema: {type: string}}}}} -components: - schemas: - H: {type: object, properties: {p: {type: string}}} - L: {type: array, items: {type: string}} - parameters: {type: object, $defs: {schema: {type: string}}} - headers: {type: object, patternProperties: {schema: {type: string}}} -`) - for at, want := range map[jsontext.Pointer]bool{ - "/components/schemas/H/properties/p": true, - "/paths/~1x/get/parameters/0/schema": true, - "/paths/~1x/get/parameters/1/content/application~1json/schema": true, - "/paths/~1x/get/responses/204/headers/X-A/schema": true, - "/components/schemas/H": false, - "/components/schemas/L/items": false, - "/components/schemas/parameters/$defs/schema": false, - "/components/schemas/headers/patternProperties/schema": false, - } { - st := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Pointer: at}) - require.Equal(t, statement.Stated, st.Truth, "%s is written", at) - assert.Equal(t, want, carriedAt(lowerer.Ctx, st.Schema), at) - } - js := &oas3.JSONSchema[oas3.Referenceable]{} - assert.False(t, carriedAt(lowerer.Ctx, StandaloneSchema(js.GetSchema())), "a schema no binding places is held by none") -} diff --git a/compilers/openapi/internal/schema/declaration.go b/compilers/openapi/internal/schema/declaration.go index 434c125d9..b1da83a4f 100644 --- a/compilers/openapi/internal/schema/declaration.go +++ b/compilers/openapi/internal/schema/declaration.go @@ -18,207 +18,171 @@ import ( "github.com/dexpace/morphic/ir" ) -// homeDeclaration gives what s writes at this position a home and returns the -// reference the position resolves to — an alias over target where the keywords -// need a node of their own, target itself where the position declares none. +// homeDeclaration gives what schema writes at this position a home and returns +// the built node (if hoisted) and the reference the position resolves to — an +// alias over target where the keywords need a node of their own, target itself +// where the position declares none. // // It is the one statement of that step, so its two callers, a $ref site // (refSiteRef) and an allOf entry's $ref (fillRefEntry), keep a declaration // the same way; a position skipping it would drop what was written at it -// without a word (GitHub #116, #143). The alias's build writes the -// declaration (declarationOn), then fin. -func homeDeclaration(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, home annotation.Home, - unhomed bool, fin finisher, -) (ir.TypeRef, []ir.Diagnostic) { - if !homesDeclaration(loweringContext, schema, target, pointer, home, unhomed || declaresScoped(loweringContext, declarationFoldedEntries(loweringContext, schema, target, pointer))) { - return target, nil +// without a word (GitHub #116, #143). +func homeDeclaration(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, home annotation.Home, + unhomed bool, +) (builtPosition, ir.TypeRef, []ir.Diagnostic) { + if !homesDeclaration(loweringContext, schema, target, pointer, home, unhomed || declaresScoped(loweringContext, positionFlattenedEntries(loweringContext, schema, pointer, target))) { + return builtPosition{}, target, unhomedFindings(loweringContext, schema, target, pointer, home) } - var decl finished - ref, diags := hoistDeclarationHome(loweringContext, ts, schema, target, pointer, decl.on(func(td ir.TypeDef) []ir.Diagnostic { - return declarationOn(loweringContext, ts, schema, target, pointer, home, td) - }).then(fin)) - return ref, append(diags, decl.diags...) + var scratch builtPosition + alias, findings := scratchAlias(loweringContext, schema, target, pointer, nil, &scratch.pendingKeeps) + // The scratch home is settled before it is judged, so what its keepers add as + // pending keeps is what it holds, and the node registered is settled once. + scratch.node, scratch.id = alias, alias.ID + findings = append(findings, declarationOn(loweringContext, schema, target, pointer, home, &scratch)...) + findings = append(findings, settleNode(loweringContext, schema, target, pointer, &scratch)...) + return hoistHolding(loweringContext, types, pointer, target, alias, findings) } -// declarationFoldedEntries returns the folded entries of the position schema, -// written at pointer and lowered to target, each marked where its entry is kept -// whole. -func declarationFoldedEntries(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer) []annotation.FoldedAllOfEntry { - return markKeptWhole(loweringContext, schema, pointer, target, positionFoldedEntries(loweringContext, schema, pointer, target)) +// scratchAlias builds, on no registry, the alias over target homing the +// declaration schema, written at pointer, where its lowering left it no node, +// holding the bounds a reference's home holds and enc, a restriction's +// Encoding; what no field holds goes to pendingKeeps. A position that reached a +// shared node with one written had its alias hoisted by the keeping of unread +// keywords first, so this reads none it also keeps. +func scratchAlias(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, enc *ir.Encoding, + pendingKeeps *annotation.PendingKeeps, +) (*ir.Scalar, []ir.Diagnostic) { + cons, kept, reports := referenceBoundsKept(loweringContext, nil, schema, positionFlattenedEntries(loweringContext, schema, pointer, target), target, pointer) + alias := aliasHolding(commonFor(loweringContext, loweringContext.IDs().ForPointer(pointer), pointer), cons, target) + alias.Encoding = enc + return alias, addBuiltPendingKeeps(loweringContext, nodePlacement{}, pendingKeeps, pointer, kept, reports) } -// declarationOn writes the declaration schema, written at pointer and lowered -// to target, on td, in hand, the node standing there: its annotations -// (attachDeclaredAnnotations), and where that node is its home, what binds a -// use, its folded entries' first (recordFoldedEntryResidue, recordResidue). A -// carrier keeps the latter itself. -func declarationOn(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, home annotation.Home, - td ir.TypeDef, +// declarationOn adds to built's pending keeps what the declaration schema, +// written at pointer and lowered to target, keeps on its node: its annotations, +// and where that node is its home, what binds a use, which a carrier keeps +// itself. The frame owning the node settles the pending keeps (settleNode). +func declarationOn(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, home annotation.Home, + built *builtPosition, ) []ir.Diagnostic { if !stated(schema) { // No schema object, so nothing written for a node to keep. return nil } - diags := attachDeclaredAnnotations(loweringContext, ts, schema, pointer, target, td) + diags := attachDeclaredAnnotations(loweringContext, schema, pointer, target, built) if home != annotation.HomeOwnNode { return diags } - diags = append(diags, recordFoldedEntryResidue(loweringContext, td, schema, declarationFoldedEntries(loweringContext, schema, target, pointer))...) - leaves := leftToWhole(loweringContext, schema, target, pointer) - return append(diags, recordResidue(loweringContext, td.Common(), schema, pointer, func(keyword string) bool { return slices.Contains(leaves, keyword) })...) + diags = append(diags, recordFlattenedEntryKeeps(loweringContext, &built.pendingKeeps, schema, pointer, positionFlattenedEntries(loweringContext, schema, pointer, target))...) + return append(diags, addUseBoundPendingKeeps(loweringContext, &built.pendingKeeps, positionSite(pointer), schema, pointer)...) } -// leftToWhole returns the keywords schema, written at pointer and lowered to -// target, writes as the inline principal of its allOf does where it keeps that -// principal whole, or a wrapper around it: the entry holds the one writing, so -// no reader of schema keeps it again, but an extension the promotion policy -// reads, which stays where a promotion finds it -// (docs/compilers/openapi.md#allof-refinement). -func leftToWhole(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer) []string { - if !writesConjuncts(schema) { - return nil - } - refinement, refined := refinementOf(loweringContext, schema, pointer) - if !refined || refinement.principal == nil || refinement.principal.schema.Ref != nil { - return nil - } - var alike []string - for _, key := range schema.Keys { - if keyWrittenAlike(schema, refinement.principal.schema.Schema, key.Name) && !loweringContext.Promoter().Reads(annotation.EntryKey("", key.Name)) { - alike = append(alike, key.Name) - } - } - if len(alike) == 0 { - return nil - } - for _, keptEntry := range keepsAtOutcome(loweringContext, schema, target, pointer).entries { - if !keptEntry.keptWhole() || !lowersFrom(refinement.principal, keptEntry.entry) { - continue - } - if _, err := annotation.RawFromNode(keptEntry.entry.schema.Node); err == nil { - return alike - } +// settleNode settles built's pending keeps onto its node, then reads the +// promotions off what the node holds, as a promotion reads the kept entries. +func settleNode(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, built *builtPosition) []ir.Diagnostic { + common := built.node.Common() + diags := settleOn(loweringContext, &common.Unmodeled, &built.pendingKeeps, pointer) + if !stated(schema) { + return diags } - return nil + return append(diags, promoteNode(loweringContext, schema, pointer, target, built.node)...) } -// homesDeclaration reports whether the declaration s, written at pointer and -// lowered to ref, takes a node of its own (hoistDeclarationHome): its lowering +// homesDeclaration reports whether the declaration schema, written at pointer and +// lowered to ref, may take a node of its own (hoistHolding): its lowering // left it none and it wrote something only a node can hold // (declaresPositionScoped; GitHub #116), since a shared node must never carry // one declaration's annotations. One owning its node keeps it, checked after // that gate so a position declaring nothing resolves to its target. unhomed is -// the verdict on what a position lowered to a reference keeps unread -// (referenceOutcomeKeywords, or a $ref site), which declaresPositionScoped +// the answer on what a position lowered to a reference keeps unread +// (referenceOutcome, or a $ref site), which declaresPositionScoped // cannot judge. func homesDeclaration(loweringContext lowering.Ctx, schema *statement.Schema, ref ir.TypeRef, pointer jsontext.Pointer, home annotation.Home, unhomed bool) bool { if home != annotation.HomeOwnNode || !stated(schema) { return false } - if !unhomed && !declaresPositionScoped(loweringContext, schema) { + if !unhomed && !declaresPositionScoped(loweringContext, schema, pointer) { return false } return !LoweredToOwnNode(loweringContext, pointer, ref) } -// hoistDeclarationHome interns the alias over ref a declaration homesDeclaration -// gives a node of its own, finished by fin, which the position's first lowering -// builds, so no home turns on declaration order -// (docs/ir/models.md#composition-beside-a-union). -func hoistDeclarationHome(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, ref ir.TypeRef, pointer jsontext.Pointer, fin finisher, -) (ir.TypeRef, []ir.Diagnostic) { - // The home stands where its target stood, so it keeps what the reference - // said of null, the marker naming a heuristic that read it in included. - out := ref - id, diags := internReferenceAlias(loweringContext, ts, schema, pointer, ref, fin) - out.Target = id - return out, diags +// unhomedFindings returns what reading the annotations of the declaration +// schema, written at pointer and lowered to target, reports where no node holds +// them. A finding needs no node, so it is reported as the alias holding them +// would report it (attachDeclaredAnnotations). +func unhomedFindings(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, home annotation.Home, +) []ir.Diagnostic { + if home != annotation.HomeOwnNode || !stated(schema) || LoweredToOwnNode(loweringContext, pointer, target) { + return nil + } + _, reports := ReadAnnotations(loweringContext, nodeUse(loweringContext, schema, pointer, target).SiteAt(loweringContext, schema, pointer), pointer) + return reports.Diagnostics() } // hoistUseHome hoists the home of the declaration schema, written at pointer, -// whose body lowered to ref, a use of what it names: over an object alone the -// Model composing it, as internOwnNode builds one, so no Scalar stands over a -// model, a position a carrier holds that a $ref naming it reaches among them -// (usesOneRef); over anything else the alias hoistDeclarationHome builds. -func hoistUseHome(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, ref ir.TypeRef, pointer jsontext.Pointer, - fin finisher, +// whose body lowered to ref, a use of what it names, where it holds anything, +// and returns the reference the position resolves to. The home is built once, +// on no registry, so no keeper runs on it twice. +func hoistUseHome(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, ref ir.TypeRef, pointer jsontext.Pointer, home annotation.Home, + enc *ir.Encoding, ) (ir.TypeRef, []ir.Diagnostic) { - js := loweringContext.Statements().Read(schema) - if kinds, _ := lowersTo(loweringContext, js); kinds != kindObject || ref.Nullable { - return hoistDeclarationHome(loweringContext, ts, schema, ref, pointer, fin) - } - out := ref - out.Target = loweringContext.IDs().ForPointer(pointer) - return out, internOwnNode(loweringContext, ts, js, pointer, ref, fin) + scratch, diags := useHome(loweringContext, types, schema, ref, pointer, enc) + // The home is settled before it is judged (homeDeclaration). + diags = slices.Concat(diags, declarationOn(loweringContext, schema, ref, pointer, home, &scratch), + keptOn(loweringContext, schema, ref, pointer, &scratch, scratch.read), settleNode(loweringContext, schema, ref, pointer, &scratch)) + _, out, diags := hoistHolding(loweringContext, types, pointer, ref, scratch.node, diags) + return out, diags } -// declaresPositionScoped reports whether schema writes anything that binds the -// position it is written at rather than the shape it lowers to — an annotation -// attachDeclaredAnnotations records, a bound internReferenceAlias carries, a -// keyword declarationOn keeps as residue, or one PreserveUnknownKeywords keeps. -// It is the gate on hoisting an alias, so it must stay in step with what those -// actually keep: a keyword listed here but stored nowhere would hoist an empty -// node, and one stored but missing here would still be dropped. A $dynamicRef -// schema is a reference site under (typed.Bindings.RefSite) is its reference, -// which recordUnexpandedDynamicRef keeps nowhere, as a $ref. -func declaresPositionScoped(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return declaresAnnotations(schema) || declaresValueConstraints(schema) || - hasAnyKey(schema, collectionBoundKeywords) || - declaresValidationOnly(schema) || hasAnyKey(schema, residueKeywords) || - declaresContentVocabulary(schema) || declaresDynamicRef(schema) && schema.Ref == nil || - declaresDialectKeyword(schema) || - annotation.WritesUnknownKeyword(schema) || len(undefinedKeywords(loweringContext, schema)) > 0 +// useHome builds, on no registry, the home of the declaration schema, written +// at pointer, whose body lowered to ref, a use of what it names. Over an object +// alone it is the Model composing it, so no Scalar sits over a model. +func useHome(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, ref ir.TypeRef, pointer jsontext.Pointer, + enc *ir.Encoding, +) (builtPosition, []ir.Diagnostic) { + if usesAlias(loweringContext, schema, ref) { + var built builtPosition + alias, diags := scratchAlias(loweringContext, schema, ref, pointer, enc, &built.pendingKeeps) + built.node, built.id = alias, alias.ID + return built, diags + } + var built builtPosition + typeDef, read, diags := buildOwnNode(loweringContext, types, loweringContext.Statements().Read(schema), pointer, ref, + commonFor(loweringContext, loweringContext.IDs().ForPointer(pointer), pointer), &built.pendingKeeps) + built.node, built.id, built.read, built.closesAfterComposition = typeDef, typeDef.Common().ID, read, closedAfterComposition(typeDef) + return built, diags } -// declaresDialectKeyword reports whether schema writes one of the dialect -// keywords annotation keeps out of scope, read from its keys as hasAnyKey -// reads. -func declaresDialectKeyword(schema *statement.Schema) bool { - for keyword := range annotation.DialectKeywords() { - if hasKey(schema, keyword) { - return true - } - } - return false +// usesAlias reports whether useHome homes the declaration schema, lowered to +// ref, on an alias rather than on the Model buildOwnNode builds. +func usesAlias(loweringContext lowering.Ctx, schema *statement.Schema, ref ir.TypeRef) bool { + kinds, _ := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) + return kinds != kindObject || ref.Nullable } -// declaresAnnotations reports whether schema carries documentation, -// deprecation, a redaction, XML hints, vendor extensions, or examples — the -// TypeCommon fields attachDeclaredAnnotations fills. -func declaresAnnotations(schema *statement.Schema) bool { - if notes := schema.Notes; notes != nil { - if notes.Title != "" || notes.Description != "" || notes.ExternalDocs != nil || notes.XML != nil { - return true - } - if notes.Example != nil || len(notes.Examples) > 0 { - return true - } - } - if annotation.EffectiveDeprecated([]*statement.Schema{schema}) || annotation.DeclaresRedaction(schema) { - return true - } - return len(schema.Extensions) > 0 +// declaresPositionScoped reports whether schema, written at pointer, writes +// anything that binds the position rather than the shape it lowers to: a cheap +// necessary condition for building a home (hoistHolding). Each disjunct reads +// through its keeper's own list or predicate: one too narrow drops what the +// home would hold, one too wide costs only the dry run. +func declaresPositionScoped(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) bool { + dialect := dialectIn(loweringContext.Rules().At(loweringContext.Position(pointer)), schema) + return annotation.ReadKeeps(schema, dialect) || // attachDeclaredAnnotations + declaresBound(schema) || // scratchAlias + hasAnyKey(schema, useBoundKeywords) || // recordUseBound + declaresContentVocabulary(schema) || // recordUnplacedContent + besideRefOf(loweringContext, schema).outcome == besideRefRestricts || // scratchAlias + keepsUnexpandedDynamicRef(loweringContext, schema, pointer) || + keepsUnknownKeywords(loweringContext, schema, pointer) } -// declaresValidationOnly reports whether schema writes a validation-only -// keyword that annotation.Read keeps verbatim under Unmodeled. A `false` -// unevaluatedProperties counts: only a Model, which owns its pointer and so -// needs no node hoisted, holds it as its openness (closureTyped). -func declaresValidationOnly(schema *statement.Schema) bool { - if a := schema.Array; a != nil { - if written(a.Contains) || written(a.UnevaluatedItems) || a.MinContains != nil || a.MaxContains != nil { - return true - } - } - if object := schema.Object; object != nil && (written(object.PropertyNames) || written(object.UnevaluatedProperties)) { - return true - } - if logic := schema.Logic; logic != nil { - if written(logic.Not) || written(logic.If) || written(logic.Then) || written(logic.Else) || len(logic.DependentSchemas) > 0 { - return true - } - } - return hasKey(schema, "dependentRequired") && !annotation.WritesEmptyDependencyMap(schema, "dependentRequired") +// keepsUnexpandedDynamicRef reports whether recordUnexpandedDynamicRef keeps +// the dynamic reference schema writes at pointer. An expanded one is a +// reference, as a $ref is, which no keeper holds. +func keepsUnexpandedDynamicRef(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) bool { + _, _, kept := unexpandedDynamicRef(loweringContext, schema, pointer) + return kept } // written reports whether sub is a schema written at its position, which a @@ -235,108 +199,122 @@ func stated(schema *statement.Schema) bool { return schema != nil && schema.Truth == statement.Stated } -// closureTyped reports whether td, the node s lowered to, holds s's -// `unevaluatedProperties: false` as a model's openness, so no entry keeps it: -// the keyword is live (annotation.ClosesAfterComposition), and td is a Model -// closed after composition, or a Union whose variants s builds itself -// (buildsVariants), one of them such a Model. A `false` allOf entry that -// closed the model outright leaves it holding the keyword no longer. -func closureTyped(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, td ir.TypeDef) bool { - if !annotation.ClosesAfterComposition(schema) { +// closureTyped reports whether built, the node schema lowered to, holds +// schema's `unevaluatedProperties: false` as a model's openness, so no entry +// keeps it: the keyword is live (annotation.ClosesAfterComposition), and +// built.node is a Model closed after composition, or a Union whose variants +// schema builds itself (buildsVariants), one of them such a Model. A `false` +// allOf entry that closed the model outright leaves it holding the keyword no +// longer. +func closureTyped(loweringContext lowering.Ctx, schema *statement.Schema, built builtPosition) bool { + if !closesAfterComposition(loweringContext, schema) { return false } - switch n := td.(type) { + switch built.node.(type) { case *ir.Model: - return closedAfterComposition(n) + return built.closesAfterComposition case *ir.Union: - return buildsVariants(loweringContext, schema) && slices.ContainsFunc(variantNodes(ts, n), closedAfterComposition) + return buildsVariants(loweringContext, schema) && built.closesAfterComposition default: return false } } -// variantNodes returns the registered nodes of union's variants. -func variantNodes(ts *compile.Types, union *ir.Union) []ir.TypeDef { - nodes := make([]ir.TypeDef, 0, len(union.Variants)) - for _, variant := range union.Variants { - if td, ok := ts.Node(variant.Type.Target); ok { - nodes = append(nodes, td) - } - } - return nodes -} - // principalDiscriminatorKeys returns what the discriminator the inline // principal of schema's allOf writes declares that reaches no IR field, where -// the principal's node stands at schema's position, written at pointer and -// lowered to target (standsAtPosition): that node holds the discriminator as -// one written at the position, so it keeps the object's keys as the position's -// own (annotation.DiscriminatorKeys), which no folded entry's read keeps. +// the principal's node sits at schema's position, written at pointer and +// lowered to target (inlinePrincipalBuiltPositionNode): that node holds the +// discriminator as one written at the position, so it keeps the object's keys +// as the position's own (annotation.DiscriminatorKeys), which no flattened +// entry's read keeps. func principalDiscriminatorKeys(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, -) (ir.Unmodeled, []ir.Diagnostic) { +) (ir.Unmodeled, annotation.KeptReports) { refinement, refines := refinementOf(loweringContext, schema, pointer) - if !refines || !standsAtPosition(loweringContext, refinement, target, pointer) { + if !refines || !inlinePrincipalBuiltPositionNode(loweringContext, refinement, target, pointer) { return nil, nil } return annotation.DiscriminatorKeys(refinement.principal.schema.Schema, refinement.principal.pointer, loweringContext.Place()) } -// closedAfterComposition reports whether td is a Model closed once composition -// is resolved. -func closedAfterComposition(td ir.TypeDef) bool { - model, ok := td.(*ir.Model) +// entryDiscriminatorKeys returns what the discriminator an inline entry of +// schema's allOf writes, written at pointer, declares that reaches no IR field, +// where schema's model holds it as one written beside the allOf +// (modelDiscriminator): the node keeps the object's keys under the keys and +// reasons that one keeps them (annotation.DiscriminatorKeys), which no +// flattened entry's read keeps. A discriminator kept whole holds them instead +// (keepDiscriminator), as one written beside the allOf does. +func entryDiscriminatorKeys(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (ir.Unmodeled, annotation.KeptReports) { + written := modelDiscriminator(loweringContext, schema) + if written.discriminator == nil || written.conjunctSchema == schema { + return nil, nil + } + return annotation.DiscriminatorKeys(written.conjunctSchema, pointer+written.rel, loweringContext.Place()) +} + +// closedAfterComposition reports whether typeDef is a Model closed once +// composition is resolved. +func closedAfterComposition(typeDef ir.TypeDef) bool { + model, ok := typeDef.(*ir.Model) return ok && model.Additional == ir.AdditionalClosedAfterComposition } -// attachDeclaredAnnotations records every annotation schema declares on td, in -// hand, the type node pointer owns, the one structural home they have -// (ir.TypeCommon). -// -// It reads every declaration's annotations, above lower()'s dispatch: each -// reaches it through the finishing of the node its position builds -// (declarationOn) or an alias fallback, so a new lowering destination cannot -// forget to read them (GitHub #114). +// attachDeclaredAnnotations records every annotation schema declares on +// built.node, the type node pointer owns (ir.TypeCommon), and adds to built's +// pending keeps what it keeps verbatim there. // -// A schema whose body reduced to a shared primitive owns no node; its -// annotations stay with the declaring property (FillPropertyDetail). Only the -// build of the node converts them, so its conversion diagnostics are drawn -// once. target says what speaks there (nodeUse). -func attachDeclaredAnnotations(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, - td ir.TypeDef, +// Every declaration's annotations are read here, through the node its position +// builds or an alias, so no lowering destination forgets them (GitHub #114). A +// schema reduced to a shared primitive owns no node; its annotations stay with +// its carrier (FillPropertyDetail). +func attachDeclaredAnnotations(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, + built *builtPosition, ) []ir.Diagnostic { - use := nodeUse(loweringContext, schema, pointer, target) - site := use.SiteAt(loweringContext, schema, pointer) - site.Closure = closureTyped(loweringContext, ts, schema, td) - site.Leaves = leftToWhole(loweringContext, schema, target, pointer) - a, diags := ReadAnnotations(loweringContext, site, pointer) - held, heldDiags := principalDiscriminatorKeys(loweringContext, schema, pointer, target) - a.Unmodeled = annotation.MergeUnmodeled(a.Unmodeled, held) - diags = append(diags, heldDiags...) + typeDef := built.node + site := nodeUse(loweringContext, schema, pointer, target).SiteAt(loweringContext, schema, pointer) + site.Typed = unevaluatedTyped(loweringContext, schema, *built) + annotations, reports := ReadAnnotations(loweringContext, site, pointer) + held, heldReports := principalDiscriminatorKeys(loweringContext, schema, pointer, target) + entryKeys, entryReports := entryDiscriminatorKeys(loweringContext, schema, pointer) + kept := annotation.MergeUnmodeled(annotations.Unmodeled, annotation.MergeUnmodeled(held, entryKeys)) + reports = append(append(reports, heldReports...), entryReports...) - common := td.Common() - common.Docs = a.Docs - if a.Deprecated { + common := typeDef.Common() + common.Docs = annotations.Docs + if annotations.Deprecated { common.Deprecation = &ir.Deprecation{} } - if a.Sensitive { + if annotations.Sensitive { common.Sensitive = true } - if a.XML != nil { - common.XML = a.XML + if annotations.XML != nil { + common.XML = annotations.XML + } + if len(annotations.Examples) > 0 { + common.Examples = annotations.Examples + } + reports = append(reports, recordUnplacedContent(loweringContext, &kept, schema, typeDef, pointer)...) + reports = append(reports, recordUnexpandedDynamicRef(loweringContext, &kept, schema, pointer)...) + reports = append(reports, KeepUnknownKeywords(loweringContext, &kept, schema, pointer, typeDef)...) + diags := addPendingKeepsKeptAs(loweringContext, &built.pendingKeeps, positionSite(pointer), kept, reports, annotation.KeptByReader, nil, false) + return append(diags, addFlattenedEntryPendingKeeps(loweringContext, &built.pendingKeeps, schema, pointer, annotations.FlattenedEntries)...) +} + +// promoteNode reads the promotions off what typeDef, the node schema written at +// pointer lowered to, holds once settled. A discriminator the node keeps whole +// holds the extensions read out of it, which the node keeps no second time +// (keepNodeDiscriminators, GitHub #849). +func promoteNode(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, typeDef ir.TypeDef) []ir.Diagnostic { + common := typeDef.Common() + diags := keepNodeDiscriminators(loweringContext, &common.Unmodeled) + if isKind(typeDef, ir.KindModel) && bottomAt(loweringContext, schema) { + // The bottom keeps each entry whole (composeBottom), so what an entry's + // fold kept beside it is kept once, inside the entry. + promotion.DropContained(loweringContext.Promoter(), &common.Unmodeled) } - common.Unmodeled = annotation.MergeUnmodeled(common.Unmodeled, a.Unmodeled) - // A discriminator kept whole as unread holds the extensions just read out - // of it, which the node keeps no second time (GitHub #849). - promotion.DropContained(loweringContext.Promoter(), &common.Unmodeled, "openapi:discriminator") - dropFoldedIntoWhole(loweringContext, &common.Unmodeled) - from := use.fallbackKeys(loweringContext) + from := nodeUse(loweringContext, schema, pointer, target).fallbackKeys(loweringContext) diags = append(diags, loweringContext.Promoter().Deprecation(common.Unmodeled, from, &common.Deprecation, &common.Provenance)...) diags = append(diags, loweringContext.Promoter().Redaction(common.Unmodeled, from, &common.Sensitive, &common.Provenance)...) - // The openness promotions are applied here rather than where the Enum or - // Union is built, for the same reason the deprecation one is: a promotion - // reads the preserved Unmodeled entries, and this is the point at which the - // declaration's extensions have reached the node's map. - switch n := td.(type) { + switch n := typeDef.(type) { case *ir.Enum: diags = append(diags, promotion.EnumOpenness(loweringContext.Promoter(), common.Unmodeled, &n.Closed, &common.Provenance)...) case *ir.Union: @@ -344,73 +322,118 @@ func attachDeclaredAnnotations(loweringContext lowering.Ctx, ts *compile.Types, // lowers to reads the enum's, as the enum would, and only that one: one // fact read through two targets would let either override the other. openness := promotion.UnionOpenness - if dispatchOf(schema).won == "enum" { + if dispatchOf(schema).lowered == "enum" { openness = promotion.EnumOpenness } diags = append(diags, openness(loweringContext.Promoter(), common.Unmodeled, &n.Closed, &common.Provenance)...) default: // Openness is a fact of an enum's or a union's value space alone. } - if len(a.Examples) > 0 { - common.Examples = a.Examples + return diags +} + +// addFlattenedEntryPendingKeeps adds as pending keeps what each of +// flattenedEntries, the flattened entries of schema written at pointer, keeps, +// each as the entry it is: one the position lowers from, or one beside it. +func addFlattenedEntryPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, pointer jsontext.Pointer, + flattenedEntries []annotation.FlattenedEntryKept, +) []ir.Diagnostic { + if len(flattenedEntries) == 0 { + return nil + } + comp := allOfEntries(loweringContext, schema, pointer) + var diags []ir.Diagnostic + for _, flattenedEntry := range flattenedEntries { + site := flattenedEntrySite(loweringContext, schema, comp, flattenedEntry.At) + if len(flattenedEntry.Unmodeled) > 0 { + recordFlattenedEntry(loweringContext, pendingKeeps, comp, site) + } + var written *statement.Schema + if i, listed := site.Order.Entry(); listed { + written = comp.entries[i].schema.Schema + } + diags = append(diags, addPendingKeepsKeptAs(loweringContext, pendingKeeps, site, flattenedEntry.Unmodeled, flattenedEntry.Reports, annotation.KeptByFold, written, false)...) } - diags = append(diags, recordUnplacedContent(loweringContext, &common.Unmodeled, schema, td, pointer)...) - diags = append(diags, recordUnexpandedDynamicRef(loweringContext, &common.Unmodeled, schema, pointer)...) - return append(diags, PreserveUnknownKeywords(loweringContext, &common.Unmodeled, schema, pointer, td, site.Leaves...)...) + return diags +} + +// flattenedEntrySite is the conjunct site of the flattened entry of comp, the +// allOf schema writes, written at at: an entry the position lowers from where +// its refinement's inline principal is it or lies inside it. +func flattenedEntrySite(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, at jsontext.Pointer) annotation.ConjunctSite { + role := annotation.WritesBeside + if refinement, refined := refinementOf(loweringContext, schema, comp.pointer); refined { + principal, inline := inlinePrincipal(refinement.principal) + if i := slices.IndexFunc(comp.entries, func(entry allOfEntry) bool { return entry.pointer == at }); inline && i >= 0 && lowersFrom(principal, comp.entries[i]) { + role = annotation.WritesLoweredFrom + } + } + return entrySiteAt(comp, at, role) } -// residueKeywords are the keywords a schema can write that bind a *use* of the +// useBoundKeywords are the keywords a schema can write that bind a *use* of the // type rather than the type itself, so no type node has a field to hold them: // `default` (Property/Parameter.Default is its only home) and // readOnly/writeOnly (Property.Visibility is theirs). // // One list, read by both the predicate that hoists a node for them // (declaresPositionScoped, via hasAnyKey) and the recorder that -// fills it (recordResidue), so the two can never drift into either half of +// fills it (recordUseBound), so the two can never drift into either half of // declaresPositionScoped's trap. -var residueKeywords = []string{"default", "readOnly", "writeOnly"} +var useBoundKeywords = []string{"default", "readOnly", "writeOnly"} -// ResidueKeywords returns that list, for the carrier lowerings outside this -// package that preserve the same set at their own positions. +// UseBoundKeywords returns that list, for the carrier lowerings outside this +// package that keep the same set at their own positions. // // It hands back a copy rather than the slice. Being one list is the whole point -// — a keyword added here has to reach every position that preserves one — and an +// — a keyword added here has to reach every position that keeps one — and an // exported slice is a mutable global: any importer could rewrite what every -// schema position in the process preserves, silently and for good. -func ResidueKeywords() []string { return slices.Clone(residueKeywords) } +// schema position in the process keeps, unreported and for good. +func UseBoundKeywords() []string { return slices.Clone(useBoundKeywords) } -// recordResidue keeps each declared residue keyword verbatim in -// common.Unmodeled and reports it at the keyword's own pointer. +// addUseBoundPendingKeeps adds a pending keep of each use-bound keyword schema, +// written at pointer by site, declares, kept verbatim and reported at the +// keyword's own pointer (recordUseBound). +func addUseBoundPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, site annotation.ConjunctSite, schema *statement.Schema, + pointer jsontext.Pointer, +) []ir.Diagnostic { + var kept ir.Unmodeled + return addPendingKeepsKeptAs(loweringContext, pendingKeeps, site, kept, recordUseBound(loweringContext, &kept, schema, pointer), annotation.KeptByReader, nil, false) +} + +// recordUseBound keeps each declared use-bound keyword verbatim in unmodeled and +// reports it at the keyword's own pointer. // // The message says the keyword is applied wherever a carrier has a field for // it: `default` at every carrier, readOnly/writeOnly at a property or header // but not at a parameter, which has no Visibility field. So a $ref'd // declaration's readOnly reaches a referencing parameter only here, on the // declaration's own node. A default no ir.Value holds reaches no carrier -// (residueReach). -func recordResidue(loweringContext lowering.Ctx, common *ir.TypeCommon, schema *statement.Schema, pointer jsontext.Pointer, left func(string) bool, -) []ir.Diagnostic { - var diags []ir.Diagnostic - for _, keyword := range residueKeywords { - if left(keyword) { - continue - } - kept, keptDiags := preserveSchemaKeyword(loweringContext, &common.Unmodeled, schema, keyword, ir.ReasonNoIRHome, pointer) - diags = append(diags, keptDiags...) - if !kept { - continue - } - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer+ids.Ptr(keyword), - "%s on a type declaration binds a use of the type, not the type; it is kept "+ - "verbatim under Unmodeled and %s", keyword, residueReach(schema, keyword))) +// (useBoundScope). +func recordUseBound(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) annotation.KeptReports { + reports := make(annotation.KeptReports, 0, len(useBoundKeywords)) + for _, keyword := range useBoundKeywords { + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), recordUseBoundKeyword(loweringContext, unmodeled, schema, keyword, pointer)...)...) } - return diags + return reports +} + +// recordUseBoundKeyword keeps keyword, a use-bound keyword schema writes at +// pointer, as recordUseBound keeps each. +func recordUseBoundKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, pointer jsontext.Pointer) []ir.Diagnostic { + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonNoIRHome, pointer) + if !kept { + return diags + } + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer+ids.Ptr(keyword), + "%s on a type declaration binds a use of the type, not the type; it is kept "+ + "verbatim under Unmodeled and %s", keyword, useBoundScope(schema, keyword))) } -// residueReach says where the residue keyword schema writes reaches: each +// useBoundScope says where the use-bound keyword schema writes reaches: each // referencing carrier with a field for it, but for a default no ir.Value // holds, which no carrier takes (Use.Default, which reports it). -func residueReach(schema *statement.Schema, keyword string) string { +func useBoundScope(schema *statement.Schema, keyword string) string { if keyword == "default" { if _, err := value.FromNode(schema.Default()); err != nil { return "applied to no carrier, as no IR value holds it" diff --git a/compilers/openapi/internal/schema/declaration_internal_test.go b/compilers/openapi/internal/schema/declaration_internal_test.go index 39f9f3669..a92f5db66 100644 --- a/compilers/openapi/internal/schema/declaration_internal_test.go +++ b/compilers/openapi/internal/schema/declaration_internal_test.go @@ -18,49 +18,58 @@ import ( ) // TestDeclarationOn_WritesTheDeclarationOnTheNodeInHand pins the finishing of -// a position's node: its annotations wherever it stands, and what binds a use -// only where the node is its home, a carrier keeping that itself. +// a position's node: its annotations wherever it sits, and what binds a use +// only where the node is its home, a carrier keeping that itself. A schema that +// is no object writes nothing, and its node promotes nothing it holds. func TestDeclarationOn_WritesTheDeclarationOnTheNodeInHand(t *testing.T) { t.Parallel() lowerer, schema, at := lowererDeclaringS(t) target := ir.TypeRef{Target: lowerer.Ctx.IDs().ForPointer(at)} carried := &ir.Model{ID: target.Target} - assert.Empty(t, declarationOn(lowerer.Ctx, lowerer.Types, schema, target, at, annotation.HomeCarrier, carried)) + carriedBuilt := &builtPosition{node: carried, id: target.Target} + assert.Empty(t, declarationOn(lowerer.Ctx, schema, target, at, annotation.HomeCarrier, carriedBuilt)) + assert.Empty(t, settleNode(lowerer.Ctx, schema, target, at, carriedBuilt)) assert.Equal(t, "kept", carried.Docs.Description, "a carrier's node takes the annotations") - assert.NotContains(t, carried.Unmodeled, "openapi:readOnly", "and no residue, which the carrier holds") + assert.NotContains(t, carried.Unmodeled, "openapi:readOnly", "and no use-bound keyword, which the carrier holds") owned := &ir.Model{ID: target.Target} - assert.NotEmpty(t, declarationOn(lowerer.Ctx, lowerer.Types, schema, target, at, annotation.HomeOwnNode, owned), - "what it keeps is reported") + ownedBuilt := &builtPosition{node: owned, id: target.Target} + assert.NotEmpty(t, append(declarationOn(lowerer.Ctx, schema, target, at, annotation.HomeOwnNode, ownedBuilt), + settleNode(lowerer.Ctx, schema, target, at, ownedBuilt)...), "what it keeps is reported") assert.Equal(t, "kept", owned.Docs.Description) - assert.Contains(t, owned.Unmodeled, "openapi:readOnly", "the node it is home to keeps the residue") + assert.Contains(t, owned.Unmodeled, "openapi:readOnly", "the node it is home to keeps the use-bound keyword") none := &ir.Model{ID: target.Target} - assert.Empty(t, declarationOn(lowerer.Ctx, lowerer.Types, &statement.Schema{Truth: statement.Anything}, target, at, - annotation.HomeOwnNode, none)) + assert.Empty(t, declarationOn(lowerer.Ctx, &statement.Schema{Truth: statement.Anything}, target, at, + annotation.HomeOwnNode, &builtPosition{node: none, id: target.Target})) assert.Equal(t, &ir.Model{ID: target.Target}, none, "a schema that is no object writes nothing") + + sensitive := ir.Unmodeled{"openapi:x-sensitive": {Value: ir.RawValue("true"), Reason: ir.ReasonVendorExtension}} + unstated := &ir.Model{ID: target.Target} + unstated.Unmodeled = sensitive + assert.Empty(t, settleNode(lowerer.Ctx, &statement.Schema{Truth: statement.Anything}, target, at, + &builtPosition{node: unstated, id: target.Target})) + assert.False(t, unstated.Sensitive, "a schema that is no object promotes nothing") } // TestHomeDeclaration_HoistsAHomeFinishedWithTheDeclaration pins the alias a // declaration needing a node of its own takes over a target it does not own: -// built once, the declaration written on it in its build, then the outer -// frame's finisher. A $ref site, its one caller lowering a reference, writes +// built once, the declaration written on it, and returned in hand for outer +// frames to finish. A $ref site, its one caller lowering a reference, writes // nothing beside it to need one, so no source reaches this. func TestHomeDeclaration_HoistsAHomeFinishedWithTheDeclaration(t *testing.T) { t.Parallel() lowerer, schema, at := lowererDeclaringS(t) - var outer []ir.TypeDef - ref, diags := homeDeclaration(lowerer.Ctx, lowerer.Types, schema, lowerer.Types.PrimitiveRef(ir.PrimitiveString), at, annotation.HomeOwnNode, false, - func(td ir.TypeDef, _ keySet, _ *principalKept) { outer = append(outer, td) }) + built, ref, diags := homeDeclaration(lowerer.Ctx, lowerer.Types, schema, lowerer.Types.PrimitiveRef(ir.PrimitiveString), at, annotation.HomeOwnNode, false) assert.Equal(t, lowerer.Ctx.IDs().ForPointer(at), ref.Target, "the position resolves to its own alias") assert.NotEmpty(t, diags, "what the alias keeps is reported") - td, ok := lowerer.Types.Node(ref.Target) + typeDef, ok := lowerer.Types.Node(ref.Target) require.True(t, ok) - assert.Equal(t, "kept", td.Common().Docs.Description, "the declaration is written on the alias") - assert.Contains(t, td.Common().Unmodeled, "openapi:readOnly") - assert.Equal(t, []ir.TypeDef{td}, outer, "and the outer finisher runs on it once") + assert.Equal(t, "kept", typeDef.Common().Docs.Description, "the declaration is written on the alias") + assert.Contains(t, typeDef.Common().Unmodeled, "openapi:readOnly") + assert.Same(t, typeDef, built.node, "the built node is returned in hand for outer frames") } // TestSchemaBody_ALaterVisitWritesNothing pins that only the visit building a @@ -69,18 +78,18 @@ func TestHomeDeclaration_HoistsAHomeFinishedWithTheDeclaration(t *testing.T) { func TestSchemaBody_ALaterVisitWritesNothing(t *testing.T) { t.Parallel() lowerer, schema, at := lowererDeclaringS(t) - js := lowerer.Ctx.Statements().Read(schema) - first, firstDiags := Ref(lowerer.Ctx, lowerer.Types, TopLevelDepth, js, at) + schemaStatement := lowerer.Ctx.Statements().Read(schema) + first, firstDiags := Ref(lowerer.Ctx, lowerer.Types, TopLevelDepth, schemaStatement, at) require.NotEmpty(t, firstDiags, "the first visit keeps readOnly and reports it") - td, ok := lowerer.Types.Node(first.Target) + typeDef, ok := lowerer.Types.Node(first.Target) require.True(t, ok, "the first visit built S") - before := maps.Clone(td.Common().Unmodeled) + before := maps.Clone(typeDef.Common().Unmodeled) - ref, diags := Ref(lowerer.Ctx, lowerer.Types, TopLevelDepth, js, at) + ref, diags := Ref(lowerer.Ctx, lowerer.Types, TopLevelDepth, schemaStatement, at) assert.Equal(t, first.Target, ref.Target, "the position resolves to the node the first visit built") assert.Empty(t, diags, "and reports nothing again") - assert.Equal(t, before, td.Common().Unmodeled, "nor keeps anything a second time") + assert.Equal(t, before, typeDef.Common().Unmodeled, "nor keeps anything a second time") } // lowererDeclaringS returns a lowerer over a component S that declares a diff --git a/compilers/openapi/internal/schema/declaration_test.go b/compilers/openapi/internal/schema/declaration_test.go index f63f0900d..6f79004de 100644 --- a/compilers/openapi/internal/schema/declaration_test.go +++ b/compilers/openapi/internal/schema/declaration_test.go @@ -14,7 +14,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/compilers/openapi/internal/schema" @@ -368,21 +367,21 @@ func TestInlinePosition_ReachedAgainWhileBuildingIsLeftToItsBuilder(t *testing.T {"items beneath /paths", openapitest.PathsSpec, pathRef, pathOwner, response, []string{"openapi:format"}}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - refFirst, diags := parseFull(t, tc.spec(tc.reference+tc.owner)) + refFirst, diags := parseFull(t, testCase.spec(testCase.reference+testCase.owner)) openapitest.RequireNoErrorDiags(t, diags) - declFirst, diags := parseFull(t, tc.spec(tc.owner+tc.reference)) + declFirst, diags := parseFull(t, testCase.spec(testCase.owner+testCase.reference)) openapitest.RequireNoErrorDiags(t, diags) - id := ir.TypeID("type/anonymous" + tc.revisited) + id := ir.TypeID("type/anonymous" + testCase.revisited) for _, doc := range []*ir.Document{refFirst, declFirst} { - td, ok := doc.Types[id] + typeDef, ok := doc.Types[id] require.True(t, ok, "the revisited position is interned") - assert.Equal(t, "kept", td.Common().Docs.Description, "its declaration's annotations reach it") - for _, key := range tc.wantUnmodeled { - assert.Contains(t, td.Common().Unmodeled, key, "and what it declares with no home is kept") + assert.Equal(t, "kept", typeDef.Common().Docs.Description, "its declaration's annotations reach it") + for _, key := range testCase.wantUnmodeled { + assert.Contains(t, typeDef.Common().Unmodeled, key, "and what it declares with no home is kept") } } assert.Empty(t, cmp.Diff(refFirst.Types, declFirst.Types), @@ -430,7 +429,7 @@ func TestInlinePosition_OutsideRefDoesNotMoveTheHome(t *testing.T) { // TestInlinePosition_HoistGateFollowsWhatIsKept walks every keyword that only a // node of its own can hold, one at a time, and requires each to give the // position that node. The gate and the three things that fill it — -// attachDeclaredAnnotations, internAlias and recordResidue — have to +// attachDeclaredAnnotations, internAlias and recordUseBound — have to // agree keyword for // keyword: one listed here but stored nowhere hoists an empty node, and one // stored but missing here is still dropped. @@ -478,14 +477,14 @@ func TestInlinePosition_HoistGateFollowsWhatIsKept(t *testing.T) { {"$schema", "$schema: 'https://json-schema.org/draft/2020-12/schema'"}, {"$vocabulary", "$vocabulary: {'https://json-schema.org/draft/2020-12/vocab/core': true}"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( - " A: {type: array, items: {type: string, "+tc.keyword+"}}\n")) + " A: {type: array, items: {type: string, "+testCase.keyword+"}}\n")) openapitest.RequireNoErrorDiags(t, diags) assert.Contains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/A/items"), - "%s binds the position it is written at, so the position must own a node", tc.keyword) + "%s binds the position it is written at, so the position must own a node", testCase.keyword) }) } } @@ -499,11 +498,11 @@ func TestInlinePosition_NothingToHoldHoistsNoNode(t *testing.T) { {"none", "type: string"}, {"a null unevaluatedProperties", "type: string, unevaluatedProperties: null"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( - " A: {type: array, items: {"+tc.keyword+"}}\n")) + " A: {type: array, items: {"+testCase.keyword+"}}\n")) openapitest.RequireNoErrorDiags(t, diags) assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/A/items")) list, ok := doc.Types[componentID("A")].(*ir.List) @@ -513,12 +512,12 @@ func TestInlinePosition_NothingToHoldHoistsNoNode(t *testing.T) { } } -// TestInlinePosition_ResidueIsKeptAtEveryHomeOwnNodePosition pins the other half -// of the residue rule: default/readOnly/writeOnly bind a *use* of a type, and -// the position that writes one is usually not a property — so every position -// that owns its node keeps them, not just a named component declaration -// (GitHub #138). -func TestInlinePosition_ResidueIsKeptAtEveryHomeOwnNodePosition(t *testing.T) { +// TestInlinePosition_UseBoundKeywordsAreKeptAtEveryHomeOwnNodePosition pins the +// other half of the use-bound keywords rule: default/readOnly/writeOnly bind a +// *use* of a type, and the position that writes one is usually not a property — +// so every position that owns its node keeps them, not just a named component +// declaration (GitHub #138). +func TestInlinePosition_UseBoundKeywordsAreKeptAtEveryHomeOwnNodePosition(t *testing.T) { t.Parallel() cases := []struct{ name, body, at string }{ {"items", " A: {type: array, items: {type: string, RESIDUE}}\n", @@ -535,25 +534,25 @@ func TestInlinePosition_ResidueIsKeptAtEveryHomeOwnNodePosition(t *testing.T) { " A: {type: array, items: {$ref: '#/components/schemas/B', RESIDUE}}\n", "type/anonymous/components/schemas/A/items"}, } - const residue = "default: a, readOnly: true" - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + const useBoundKeywords = "default: a, readOnly: true" + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(strings.ReplaceAll(tc.body, "RESIDUE", residue))) + doc, diags := parseFull(t, openapitest.ComponentSpec(strings.ReplaceAll(testCase.body, "RESIDUE", useBoundKeywords))) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types[ir.TypeID(tc.at)] + typeDef, ok := doc.Types[ir.TypeID(testCase.at)] require.True(t, ok, "the position owns a node to hold what it wrote") - assertResidueKeptAndAnnounced(t, td.Common().Unmodeled, diags, "default", `"a"`) - assertResidueKeptAndAnnounced(t, td.Common().Unmodeled, diags, "readOnly", `true`) + assertUseBoundKeywordKeptAndAnnounced(t, typeDef.Common().Unmodeled, diags, "default", `"a"`) + assertUseBoundKeywordKeptAndAnnounced(t, typeDef.Common().Unmodeled, diags, "readOnly", `true`) }) } } -// TestPropertyPosition_ResidueStaysOutOfTheTypeNode is the deliberate non-goal. -// A property lands all three in their real fields, so recording them again as -// residue would restate what the carrier already holds. -func TestPropertyPosition_ResidueStaysOutOfTheTypeNode(t *testing.T) { +// TestPropertyPosition_UseBoundKeywordsStayOutOfTheTypeNode is the deliberate +// non-goal. A property lands all three in their real fields, so recording them +// again as use-bound keywords would restate what the carrier already holds. +func TestPropertyPosition_UseBoundKeywordsStayOutOfTheTypeNode(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( " A: {type: object, properties: {p: {type: array, items: {type: string}, "+ @@ -566,11 +565,11 @@ func TestPropertyPosition_ResidueStaysOutOfTheTypeNode(t *testing.T) { ir.LifecycleRead, ir.LifecycleDelete, ir.LifecycleQuery, }}, property.Visibility, "readOnly lands in the property's own field") - td, ok := doc.Types[property.Type.Target] + typeDef, ok := doc.Types[property.Type.Target] require.True(t, ok) - assert.NotContains(t, td.Common().Unmodeled, "openapi:default", + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:default", "the carrier holds it, so the node must not restate it") - assert.NotContains(t, td.Common().Unmodeled, "openapi:readOnly", + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:readOnly", "the carrier holds it, so the node must not restate it") assert.Empty(t, property.Unmodeled, "nor does the property preserve what it modelled") } @@ -581,15 +580,12 @@ func TestPropertyPosition_ResidueStaysOutOfTheTypeNode(t *testing.T) { // node is coming for them — never dropped in silence, and never read as a base // URI for reference resolution. // -// The keyword list is written out here rather than read from -// annotation.DialectKeywords: ranging over the production list would let a -// keyword dropped from it narrow this test instead of failing it, so the two -// are compared as sets and each is then exercised. +// The keyword list is written out here rather than read from the production +// list, which annotation's tests hold to the same members: ranging over it +// would let a keyword dropped from it narrow this test instead of failing it. func TestDialectKeywords_KeptOutOfScope(t *testing.T) { t.Parallel() want := []string{"$id", "$schema", "$vocabulary"} - require.ElementsMatch(t, want, slices.Collect(annotation.DialectKeywords()), - "a keyword joining or leaving the exclusion must be decided here too") doc, diags := parseFull(t, openapitest.ComponentSpec( " A:\n"+ @@ -600,26 +596,26 @@ func TestDialectKeywords_KeptOutOfScope(t *testing.T) { " type: string\n")) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types[componentID("A")] + typeDef, ok := doc.Types[componentID("A")] require.True(t, ok) for _, keyword := range want { - entry, ok := td.Common().Unmodeled["openapi:"+keyword] + entry, ok := typeDef.Common().Unmodeled["openapi:"+keyword] require.True(t, ok, "%s must be kept verbatim", keyword) assert.Equal(t, ir.ReasonOutOfScope, entry.Reason) openapitest.AssertInfoDiagAt(t, diags, string(entry.Provenance.Pointer)) } - assert.NotContains(t, td.Common().Unmodeled, "openapi:$comment", + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:$comment", "2020-12 §8.3 forbids presenting $comment, so it is dropped rather than kept") } -// TestResidueKeywords_HandsBackACopy pins the reason this is a function and not +// TestUseBoundKeywords_HandsBackACopy pins the reason this is a function and not // the slice. One list is the whole point — a keyword added to it has to reach // every position that preserves one — so the list itself must not be reachable // from outside. An exported slice would let any importer rewrite what every // schema position in the process preserves, for the life of the process. -func TestResidueKeywords_HandsBackACopy(t *testing.T) { +func TestUseBoundKeywords_HandsBackACopy(t *testing.T) { t.Parallel() - first := schema.ResidueKeywords() + first := schema.UseBoundKeywords() require.NotEmpty(t, first, "an empty list would make this pass vacuously") clobbered := slices.Clone(first) @@ -627,7 +623,7 @@ func TestResidueKeywords_HandsBackACopy(t *testing.T) { first[i] = "clobbered" } - assert.Equal(t, clobbered, schema.ResidueKeywords(), + assert.Equal(t, clobbered, schema.UseBoundKeywords(), "writing through one caller's slice must not change what the next one reads") } @@ -684,12 +680,12 @@ func stolenPositions() []stolenPosition { } } -// assertResidueKeptAndAnnounced checks one residue keyword's entry and its -// diagnostic together. The end-to-end tests' assertResidueKept and -// assertResidueDiag (compilers/openapi/e2e) do the same job in two calls; this +// assertUseBoundKeywordKeptAndAnnounced checks one use-bound keyword's entry +// and its diagnostic together. The end-to-end tests' assertKeywordsKept and +// assertKeptKeywordDiag (compilers/openapi/e2e) do the same job in two calls; this // package cannot import them, so the pairing lives here under a name that is // not a transposition of either. -func assertResidueKeptAndAnnounced(t *testing.T, unmodeled ir.Unmodeled, diags []ir.Diagnostic, keyword, wantJSON string) { +func assertUseBoundKeywordKeptAndAnnounced(t *testing.T, unmodeled ir.Unmodeled, diags []ir.Diagnostic, keyword, wantJSON string) { t.Helper() entry, ok := unmodeled["openapi:"+keyword] require.True(t, ok, "%s must be kept verbatim under Unmodeled", keyword) @@ -702,7 +698,7 @@ func assertResidueKeptAndAnnounced(t *testing.T, unmodeled ir.Unmodeled, diags [ return } } - assert.Fail(t, "missing residue diagnostic", "nothing announced %s; got %+v", keyword, diags) + assert.Fail(t, "missing use-bound keyword diagnostic", "nothing announced %s; got %+v", keyword, diags) } // inlinePosition is one schema position with no ir.Property or ir.Parameter to @@ -722,11 +718,12 @@ type inlinePosition struct { // schema and a parameter's schema alike: into a Model's openness where the // position built one closed after composition, itself or as a variant of a // union it built, and verbatim under openapi:unevaluated, once, wherever it -// built anything else (docs/compilers/openapi.md#validation-only). +// built anything else or the keyword reaches an evaluator the IR does not type +// (docs/compilers/openapi.md#validation-only). func TestClosureTyped_EveryOutcomeKeepsWhatItDoesNotType(t *testing.T) { t.Parallel() const live, base = "'#/components/schemas/Live'", "'#/components/schemas/Base'" - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string typed bool }{ @@ -744,15 +741,17 @@ func TestClosureTyped_EveryOutcomeKeepsWhatItDoesNotType(t *testing.T) { {"a model", "{type: object, properties: {k: {type: string}}, unevaluatedProperties: false}", true}, {"a composition", "{allOf: [{$ref: " + live + "}, {type: object, properties: {k: {type: string}}}], unevaluatedProperties: false}", true}, {"a type array with an object", "{type: [object, string], properties: {k: {type: string}}, unevaluatedProperties: false}", true}, - {"a distributed union", "{type: object, properties: {k: {type: string}}, oneOf: [{$ref: " + live + "}, {$ref: " + base + "}], " + - "unevaluatedProperties: false}", true}, + // Branches requiring no disjoint tags may both match, which only + // the kept keyword refuses (GitHub #1904). + {"a distributed union whose branches may overlap", "{type: object, properties: {k: {type: string}}, oneOf: [{$ref: " + live + "}, {$ref: " + base + "}], " + + "unevaluatedProperties: false}", false}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, outcomeSpec(tc.schema)) + doc, diags := parseFull(t, outcomeSpec(testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) want := map[jsontext.Pointer][]string{} - if !tc.typed { + if !testCase.typed { for _, at := range []jsontext.Pointer{"/components/schemas/C", "/components/schemas/H/properties/p", "/components/schemas/L/items", "/paths/~1p/get/parameters/0/schema"} { want[at] = []string{`{"unevaluatedProperties":false}`} @@ -794,9 +793,9 @@ func unevaluatedEntries(doc *ir.Document) map[jsontext.Pointer][]string { out[unmodeledEntry.Provenance.Pointer] = append(out[unmodeledEntry.Provenance.Pointer], string(unmodeledEntry.Value)) } } - for _, td := range doc.Types { - add(td.Common().Unmodeled) - if model, ok := td.(*ir.Model); ok { + for _, typeDef := range doc.Types { + add(typeDef.Common().Unmodeled) + if model, ok := typeDef.(*ir.Model); ok { for _, property := range model.Properties { add(property.Unmodeled) } @@ -811,14 +810,14 @@ func unevaluatedEntries(doc *ir.Document) map[jsontext.Pointer][]string { } // TestClosureTyped_ReadsAlikeInEitherEntryOrder pins that where an allOf's -// entries stand changes nothing of where its `unevaluatedProperties: false` -// goes: a composition holds it as its closure, a false entry closes the model -// and leaves it kept, and an entry's own stays with that entry, in either +// entries are written changes nothing of where its `unevaluatedProperties: +// false` goes: a composition holds it as its closure, a false entry closes the +// model and leaves it kept, and an entry's own stays with that entry, in either // order, but for the index in the kept entry's key. func TestClosureTyped_ReadsAlikeInEitherEntryOrder(t *testing.T) { t.Parallel() const live, closes = "{$ref: '#/components/schemas/Live'}", ", unevaluatedProperties: false" - for name, tc := range map[string]struct{ other, beside string }{ + for name, testCase := range map[string]struct{ other, beside string }{ "a composition": {"{type: object, properties: {k: {type: string}}}", closes}, "a false entry": {"false", closes}, "an entry's own false": {"{type: object, properties: {k: {type: string}}" + closes + "}", ""}, @@ -826,14 +825,14 @@ func TestClosureTyped_ReadsAlikeInEitherEntryOrder(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() read := func(first, second string) (ir.AdditionalMode, map[jsontext.Pointer][]string, []string) { - doc, diags := parseFull(t, outcomeSpec("{allOf: ["+first+", "+second+"]"+tc.beside+"}")) + doc, diags := parseFull(t, outcomeSpec("{allOf: ["+first+", "+second+"]"+testCase.beside+"}")) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("C")].(*ir.Model) require.True(t, ok, "got %T", doc.Types[componentID("C")]) return model.Additional, unevaluatedEntries(doc), slices.Sorted(maps.Keys(model.Unmodeled)) } - mode, kept, keys := read(live, tc.other) - swappedMode, swappedKept, swappedKeys := read(tc.other, live) + mode, kept, keys := read(live, testCase.other) + swappedMode, swappedKept, swappedKeys := read(testCase.other, live) assert.Equal(t, mode, swappedMode) assert.Empty(t, cmp.Diff(kept, swappedKept)) for i, key := range swappedKeys { diff --git a/compilers/openapi/internal/schema/discriminator.go b/compilers/openapi/internal/schema/discriminator.go index cc10dde62..692b90e67 100644 --- a/compilers/openapi/internal/schema/discriminator.go +++ b/compilers/openapi/internal/schema/discriminator.go @@ -4,7 +4,6 @@ package schema import ( - "context" "encoding/json/jsontext" "maps" "slices" @@ -15,7 +14,6 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/promotion" "github.com/dexpace/morphic/compilers/openapi/internal/reftable" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" @@ -30,27 +28,27 @@ import ( // names it by PropertyName alone. branchIndexValue is a union's branches, nil // for a model: a union routes to its variants (branchIndex.route), a model to // the type each value's chain ends on (hierarchyRoute). -func lowerDiscriminator(loweringContext lowering.Ctx, ts *compile.Types, discriminator *statement.Discriminator, pointer jsontext.Pointer, model *ir.Model, branchIndexValue *branchIndex) (*ir.Discriminator, []ir.Diagnostic) { +func lowerDiscriminator(loweringContext lowering.Ctx, types *compile.Types, discriminator *statement.Discriminator, pointer jsontext.Pointer, model *ir.Model, branchIndexValue *branchIndex) (*ir.Discriminator, []ir.Diagnostic) { if discriminator == nil || !tagLocated(discriminator, model) { return nil, nil } - mapping, diags := discriminatorMapping(loweringContext, ts, discriminator, branchIndexValue, pointer) + mapping, diags := discriminatorMapping(loweringContext, types, discriminator, branchIndexValue, pointer) disc := &ir.Discriminator{Mapping: mapping} if pid, ok := propertyIDByName(model, discriminator.PropertyName); ok { disc.Property = pid } else { disc.PropertyName = discriminator.PropertyName } - defaultID, defaultDiags := discriminatorDefault(loweringContext, ts, discriminator, branchIndexValue, pointer) + defaultID, defaultDiags := discriminatorDefault(loweringContext, types, discriminator, branchIndexValue, pointer) disc.Default = defaultID return disc, append(diags, defaultDiags...) } -// tagLocated reports whether the IR can locate the tag d names, on m where a -// model declares it: by any name but the empty one, which PropertyName empty -// cannot spell, and by that one only as the PropertyID of a property m declares -// itself (docs/compilers/openapi.md#discriminator). One it cannot locate is no -// node's, and it is kept verbatim, unread. +// tagLocated reports whether the IR can locate the tag discriminator names, on +// model where a model declares it: by any name but the empty one, which +// PropertyName empty cannot spell, and by that one only as the PropertyID of a +// property model declares itself (docs/compilers/openapi.md#discriminator). +// One it cannot locate is no node's, and it is kept verbatim, unread. func tagLocated(discriminator *statement.Discriminator, model *ir.Model) bool { if discriminator.PropertyName != "" { return true @@ -93,25 +91,26 @@ type subtypeTag struct { // discriminator routes to it by name (GitHub #505, #517). // // Every discriminated ancestor is asked, nearest first (GitHub #305); within a -// level, first, the schema schema's Base names, and its ancestors lead, so the -// Base's hierarchy tags it whichever entry is written first. Of several keys -// the smallest in byte order is elected (GitHub #410), with an info. +// level, first, the schema the Base of schema names, and its ancestors lead, so +// the Base's hierarchy tags it whichever entry is written first. Of several +// keys the smallest in byte order is chosen (GitHub #410), with an info. func subtypeDiscriminatorValue(loweringContext lowering.Ctx, schema *statement.Schema, id ir.TypeID, pointer jsontext.Pointer, first *statement.Schema, ) (subtypeTag, []ir.Diagnostic) { var lead []*statement.Schema if stated(first) { - lead = append([]*statement.Schema{first}, discriminatedAncestors(loweringContext, first)...) + lead = append([]*statement.Schema{first}, slices.Concat(ancestorLevels(loweringContext, first)...)...) } var ancestors []*statement.Schema for _, level := range ancestorLevels(loweringContext, schema) { + level = slices.Clone(level) slices.SortStableFunc(level, func(a, b *statement.Schema) int { return compareTrueFirst(slices.Contains(lead, a), slices.Contains(lead, b)) }) ancestors = append(ancestors, level...) } for _, a := range ancestors { - tags := mappingTagsFor(loweringContext, a.Discriminator(), id) + tags := mappingTagsFor(loweringContext, modelDiscriminator(loweringContext, a).discriminator, id) if len(tags) == 0 { continue } @@ -125,14 +124,16 @@ func subtypeDiscriminatorValue(loweringContext lowering.Ctx, schema *statement.S len(tags), strings.Join(tags, ", "))} } // Read the state, not only the name: a top-level entry of another kind, such - // as components/x-shared/Cat, has none to read (GitHub #572). + // as components/x-shared/Cat, has none to read (GitHub #572), and a name + // routes only a component of the entry document (componentNamed). name, state := ids.ComponentSchema(pointer) - if state != ids.NamedComponent { + source := ids.DocumentIDNamespace{} + if state != ids.NamedComponent || source.NamedType(ids.Ptr("components", "schemas", name)) != id { return subtypeTag{}, nil } for _, a := range ancestors { if routesByName(loweringContext, a, schema) { - return subtypeTag{value: name, routed: true, byName: a.Discriminator()}, nil + return subtypeTag{value: name, routed: true, byName: modelDiscriminator(loweringContext, a).discriminator}, nil } } return subtypeTag{}, nil @@ -143,26 +144,22 @@ type listedBy struct { schema *statement.Schema } -// routesByName reports whether the discriminator the ancestor a declares routes -// the component schema schema by its name, OpenAPI's implicit mapping. One -// standing with no oneOf or anyOf routes every schema composing a through -// allOf. One standing with either (standingUnion) routes the schemas that union -// lists, every possible one listed there -// (docs/compilers/openapi.md#discriminator-value): those a $ref branch of it -// ends on, as discriminatedAncestors reads a $ref, read once a run, as every -// subtype of a asks. Any other schema composing a narrows that union, each -// instance carrying its variant's tag, and composes it as written +// routesByName reports whether the discriminator the ancestor declarer declares +// routes the component schema by its name, OpenAPI's implicit mapping. One +// beside no union routes every schema composing declarer, one beside a union +// only those its $ref branches end on +// (docs/compilers/openapi.md#discriminator-value): any other narrows that union // (docs/ir/models.md#a-union-a-composition-names). -func routesByName(loweringContext lowering.Ctx, a, schema *statement.Schema) bool { - holder := standingUnion(loweringContext, a) +func routesByName(loweringContext lowering.Ctx, declarer, schema *statement.Schema) bool { + holder := unionOfDiscriminator(loweringContext, declarer) if !stated(holder) { return true } - branches, _, _ := unionBranches(loweringContext, a, holder) - listed := lowering.ReadOncePerRun(loweringContext, listedBy{a}, func() map[*statement.Schema]bool { + branches := loweredKeyword(loweringContext, declarer, holder).branchesOf(holder) + listed := lowering.ReadOncePerRun(loweringContext, listedBy{declarer}, func() map[*statement.Schema]bool { set := make(map[*statement.Schema]bool, len(branches)) - for _, b := range branches { - if target := refBranchTarget(loweringContext, loweringContext.Statements().Subschema(b)); stated(target) { + for _, branch := range branches { + if target := refBranchTarget(loweringContext, loweringContext.Statements().Subschema(branch)); stated(target) { set[target] = true } } @@ -171,161 +168,90 @@ func routesByName(loweringContext lowering.Ctx, a, schema *statement.Schema) boo return listed[schema] } -// standingUnion returns the schema writing the union the discriminator a -// declares stands with: a where it writes one, else the entry of a's allOf -// whose union a lowers (findEntryUnion), which writes no discriminator of its -// own beside a's, and nil for none, a hierarchy's base. -func standingUnion(loweringContext lowering.Ctx, a *statement.Schema) *statement.Schema { - if declaresUnion(a) { - return a - } - at := entryUnionIndexOf(loweringContext, a) - if !at.ok { +// unionOfDiscriminator returns the schema writing the union the discriminator +// declarer declares sits with, declarer itself or an allOf entry writing no +// discriminator of its own, and nil for a hierarchy's base. +func unionOfDiscriminator(loweringContext lowering.Ctx, declarer *statement.Schema) *statement.Schema { + if declaresUnion(declarer) { + return declarer + } + loweredUnion, ok := readConjunction(loweringContext, declarer).loweredUnion() + if !ok || loweredUnion.holder.Discriminator() != nil { return nil } - return allOfEntries(loweringContext, a, "").entries[at.index].schema.Schema -} - -// maxDiscriminatorAncestorDepth bounds how many composition levels -// discriminatedAncestors climbs (styleguide bounded-everything rule). The visited -// set below is what makes the walk terminate; this is the explicit limit, set far -// beyond any hierarchy a source document plausibly declares. -const maxDiscriminatorAncestorDepth = 256 - -// discriminatedAncestors returns s's composition ancestors declaring a -// discriminator, nearest first: the resolved targets of s's own $ref entries -// in source order, then theirs, level by level. Nearest means fewest hops, -// which decides between two ancestors whose mappings name the same subtype. -// -// The visited set bounds the work; the depth cap bounds only the levels. A -// schema reached by several entries would be walked once per path, so the -// frontier multiplies by the fan-out each level (2^level for a chain of -// diamonds). TestAllOf_DiscriminatorValueCyclicComposition (cyclic) and -// TestCompile_SharedCompositionAncestorsDoNotAmplify (acyclic) pin it. -func discriminatedAncestors(loweringContext lowering.Ctx, schema *statement.Schema) []*statement.Schema { - return slices.Concat(ancestorLevels(loweringContext, schema)...) -} - -// ancestorLevels is discriminatedAncestors level by level, nearest first. -func ancestorLevels(loweringContext lowering.Ctx, schema *statement.Schema) [][]*statement.Schema { - var out [][]*statement.Schema - visited := make(map[*statement.Schema]bool) - // schema is visited before the walk starts, so a composition cycle cannot - // bring it back as one of its own ancestors. Without this a schema in a - // cycle that declares a discriminator answers to its own mapping, which is - // a hierarchy of one thing standing above itself. - visited[schema] = true - level := []*statement.Schema{schema} - for depth := 0; depth < maxDiscriminatorAncestorDepth && len(level) > 0; depth++ { - next := make([]*statement.Schema, 0, len(level)) - for _, cur := range level { - next = append(next, unvisitedRefTargets(loweringContext, cur, visited)...) - } - var found []*statement.Schema - for _, target := range next { - if target.Discriminator() != nil { - found = append(found, target) - } - } - if len(found) > 0 { - out = append(out, found) - } - level = next - } - return out + return loweredUnion.holder } // composedByOf keys what composedByBranch read of one schema and the union -// standing with it. +// beside it. type composedByOf struct { schema, holder *statement.Schema } -// composedByBranch reports whether a branch of u, a union of s's, the combinator -// unionBranches elects, composes s through allOf at any depth, so that s's -// discriminator routes to a subtype of s: s is then the base of a hierarchy, -// which a union of its subtypes would no longer be -// (docs/compilers/openapi.md#union-beside-structure). Such a branch finds s's -// discriminator among its ancestors' (discriminatedAncestors). Where s writes -// one, it is the one standing with u (findEntryUnion). Every reader of the +// composedByBranch reports whether a branch of the union unionSite lowers +// composes schema through allOf at any depth, so that schema's discriminator +// routes to a subtype of it: schema is then the base of a hierarchy, which a +// union of its subtypes would no longer be +// (docs/compilers/openapi.md#union-beside-structure). Every reader of the // position asks, so it is read once a run. -func composedByBranch(loweringContext lowering.Ctx, schema *statement.Schema, unionAtValue unionAt) bool { +func composedByBranch(loweringContext lowering.Ctx, schema *statement.Schema, unionSite loweredUnionSite) bool { discriminator := schema.Discriminator() if discriminator == nil { return false } - return lowering.ReadOncePerRun(loweringContext, composedByOf{schema, unionAtValue.holder}, func() bool { - branches, _, _ := unionAtValue.branches(loweringContext) - return slices.ContainsFunc(branches, func(b statement.Subschema) bool { - st := loweringContext.Statements().Subschema(b) - target := st.Schema - if st.Ref != nil { - target = refBranchTarget(loweringContext, st) + return lowering.ReadOncePerRun(loweringContext, composedByOf{schema, unionSite.holder}, func() bool { + branches := unionSite.branches(loweringContext) + return slices.ContainsFunc(branches, func(branch statement.Subschema) bool { + schemaStatement := loweringContext.Statements().Subschema(branch) + target := schemaStatement.Schema + if schemaStatement.Ref != nil { + target = refBranchTarget(loweringContext, schemaStatement) } - return stated(target) && slices.ContainsFunc(discriminatedAncestors(loweringContext, target), - func(a *statement.Schema) bool { return a.Discriminator() == discriminator }) + return stated(target) && slices.ContainsFunc(slices.Concat(ancestorLevels(loweringContext, target)...), + func(a *statement.Schema) bool { + return modelDiscriminator(loweringContext, a).discriminator == discriminator + }) }) }) } -// unvisitedRefTargets returns the schemas s's $ref composition entries resolve -// to, in source order, skipping those already seen and marking those it returns. -// Marking as it enqueues rather than when the walk reaches them is what keeps a -// schema two entries both name from being queued, and walked, twice. -func unvisitedRefTargets(loweringContext lowering.Ctx, schema *statement.Schema, visited map[*statement.Schema]bool) []*statement.Schema { - var out []*statement.Schema - for b := range allOfRefEntries(loweringContext, schema) { - target := refBranchTarget(loweringContext, b) - if !stated(target) || visited[target] { - continue - } - visited[target] = true - out = append(out, target) - } - return out -} - -// discriminatorBesideUnion returns the finisher queueing a settlement for the -// discriminator s writes, which the model in hand holds beside the union holder -// writes, kept verbatim: beside the model by lowerBesideUnmodeledUnion, or with -// its allOf entry. A body that lowered to anything else holds none: its -// discriminator was kept unread where the rest was, a multi-typed body's on its -// union (lowerTypeVariant). -func discriminatorBesideUnion(loweringContext lowering.Ctx, ts *compile.Types, schema, holder *statement.Schema, pointer jsontext.Pointer) finisher { - return func(td ir.TypeDef, _ keySet, _ *principalKept) { - if isKind(td, ir.KindModel) { - ts.Defer(besideUnionDiscriminator{c: loweringContext, s: schema, pointer: pointer, model: td.Common().ID, named: namedBranches(loweringContext, schema, holder)}) - } +// deferDiscriminatorBesideUnion marks the discriminator schema writes beside +// the union holder writes, which the model typeDef holds, so the run's +// settlement of model discriminators routes the components that union's +// branches name by their names. A body lowered to anything else holds none: +// its discriminator was kept unread where the rest was. +func deferDiscriminatorBesideUnion(loweringContext lowering.Ctx, schema, holder *statement.Schema, typeDef ir.TypeDef) { + if isKind(typeDef, ir.KindModel) { + modelDiscriminatorsOf(loweringContext).besideKeptUnion(loweringContext, typeDef.Common().ID, schema, holder) } } // namedBranches returns the components named by $ref among the branches of -// the union holder elects at the position schema, in branch order: the types a -// discriminator routes to by name when no mapping key routes to them. An inline -// branch has no name and neither has any other position, so the discriminator -// reaches those only through its mapping, which the model's Discriminator -// already holds. -func namedBranches(loweringContext lowering.Ctx, schema, holder *statement.Schema) []ir.TypeID { +// the union holder chooses at the position schema, each once in branch order: +// the types a discriminator routes to by name. It reaches any other branch only +// through its mapping. +func namedBranches(loweringContext lowering.Ctx, schema, holder *statement.Schema) []namedBranch { scope := loweringContext.RefScope() - branches, _, _ := unionBranches(loweringContext, schema, holder) - var named []ir.TypeID - for _, b := range branches { - if _, id, ok := componentNamed(scope, referenceOf(loweringContext, loweringContext.Statements().Subschema(b))); ok { - named = append(named, id) + key := loweredKeyword(loweringContext, schema, holder) + branches := key.branchesOf(holder) + var named []namedBranch + for i, branch := range branches { + name, id, ok := componentNamed(scope, referenceOf(loweringContext, loweringContext.Statements().Subschema(branch))) + if ok && !slices.ContainsFunc(named, func(n namedBranch) bool { return n.id == id }) { + named = append(named, namedBranch{name: name, id: id, at: key.branchAt(holder.At.Pointer, i)}) } } return named } -// componentNamed returns the source component the union branch b names by -// $ref, by name and by ID: the route OpenAPI's implicit mapping takes to it. It -// is false for a branch naming none, one written inline or a $ref to any other -// position. b is the branch's reference (referenceOf), nil for none. -func componentNamed(scope componentlookup.Scope, b *statement.Statement) (string, ir.TypeID, bool) { - if b == nil { +// componentNamed returns the source component the union branch, its reference +// (referenceOf) or nil, names by $ref, by name and by ID: the route OpenAPI's +// implicit mapping takes to it. +func componentNamed(scope componentlookup.Scope, branch *statement.Statement) (string, ir.TypeID, bool) { + if branch == nil { return "", "", false } - at, ok := landsAt(b) + at, ok := landsAt(branch) if !ok || at.Doc != reftable.Source { return "", "", false } @@ -337,20 +263,18 @@ func componentNamed(scope componentlookup.Scope, b *statement.Statement) (string return name, id, true } -// spellImplicitRoutes writes into the discriminator of union, the Union at -// lowers, the route OpenAPI implies to each variant no mapping entry routes: -// the name of the component its $ref branch names, unless another branch names -// it too or an entry spells it. The IR routes by type name only where the -// Mapping is nil (docs/ir/models.md#discriminator), so these are written where -// it holds an entry, or a variant's type is not that component, as a composed -// variant's or an alias's is not. A non-null branch lacking its variant is a -// compiler bug, reported at pointer. -func spellImplicitRoutes(loweringContext lowering.Ctx, at unionAt, union *ir.Union, pointer jsontext.Pointer) []ir.Diagnostic { +// spellImplicitRoutes writes into the discriminator of union, the Union +// unionSite lowers, the route OpenAPI implies to each variant, unless another +// branch names it too or an entry spells it. A variant an entry routes under +// another key takes it decode-only, as its conjunct takes its tag from the +// Mapping alone. Nothing is written where a nil Mapping, read as type names +// (docs/ir/models.md#discriminator), says them already. +func spellImplicitRoutes(loweringContext lowering.Ctx, unionSite loweredUnionSite, union *ir.Union, pointer jsontext.Pointer) []ir.Diagnostic { discriminator := union.Discriminator if discriminator == nil { return nil } - routes := implicitRoutes(loweringContext, at) + routes := implicitRoutes(loweringContext, unionSite) if len(routes) != len(union.Variants) { return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, "internal: the union has %d variants for %d branches, so no route is written for them", @@ -369,27 +293,33 @@ func spellImplicitRoutes(loweringContext lowering.Ctx, at unionAt, union *ir.Uni for _, target := range discriminator.Mapping { routed[target] = true } + spelled := maps.Clone(discriminator.Mapping) for i, implicitRoute := range routes { - variant := union.Variants[i].Type.Target - // An unnamed route writes nothing. count skips one too, but only as it - // counts named routes alone, so the guard says it where it is meant. A - // routed variant's name stays out though OpenAPI routes by it: a writer - // takes the variant's tag from the Mapping, which cannot mark a second - // route as only read (docs/compilers/openapi.md#discriminator). - if !implicitRoute.named || count[implicitRoute.name] != 1 || routed[variant] { + // An unnamed route writes nothing: count leaves it out only incidentally. + if !implicitRoute.named || count[implicitRoute.name] != 1 { continue } - if _, spelled := discriminator.Mapping[implicitRoute.name]; spelled { + if _, keyed := spelled[implicitRoute.name]; keyed { continue } - if discriminator.Mapping == nil { - discriminator.Mapping = map[string]ir.TypeID{} + variant := union.Variants[i].Type.Target + if routed[variant] { + addRoute(&discriminator.DecodeOnlyRoutes, implicitRoute.name, variant) + continue } - discriminator.Mapping[implicitRoute.name] = variant + addRoute(&discriminator.Mapping, implicitRoute.name, variant) } return nil } +// addRoute routes tag to target in routes, made where it is nil. +func addRoute(routes *map[string]ir.TypeID, tag string, target ir.TypeID) { + if *routes == nil { + *routes = map[string]ir.TypeID{} + } + (*routes)[tag] = target +} + // implicitRoute is the route OpenAPI's implicit mapping takes to a union // branch: the name of the component its $ref names, and that component's ID, // where it names one. @@ -405,12 +335,12 @@ func (r implicitRoute) routesExactly(set []string) bool { return r.named && len(set) == 1 && set[0] == r.name } -// typesAreNamed reports whether each variant whose branch names a component, -// routes holding the route to each in order, is of that component's type, so -// that the name of its type is its route. +// typesAreNamed reports whether each variant, routes holding the route to each +// in order, is the component its branch names, so its type's name is its route +// and no other variant's type name is read as one. func typesAreNamed(routes []implicitRoute, variants []ir.Variant) bool { for i, implicitRoute := range routes { - if implicitRoute.named && implicitRoute.component != variants[i].Type.Target { + if !implicitRoute.named || implicitRoute.component != variants[i].Type.Target { return false } } @@ -418,98 +348,39 @@ func typesAreNamed(routes []implicitRoute, variants []ir.Variant) bool { } // implicitRoutes returns the implicit route to each branch of the union -// unionAtValue that is a variant (unionAt.variantBranch), in branch order: one -// per variant. A branch written inline, or a $ref to any other position, names -// none. -func implicitRoutes(loweringContext lowering.Ctx, unionAtValue unionAt) []implicitRoute { +// unionSite that is a variant, in branch order: one per variant. +func implicitRoutes(loweringContext lowering.Ctx, unionSite loweredUnionSite) []implicitRoute { scope := loweringContext.RefScope() - branches, _, _ := unionAtValue.branches(loweringContext) + branches := unionSite.branches(loweringContext) routes := make([]implicitRoute, 0, len(branches)) - for i, b := range branches { - st := loweringContext.Statements().Subschema(b) - if !unionAtValue.variantBranch(loweringContext, i, st) { + for i, branch := range branches { + schemaStatement := loweringContext.Statements().Subschema(branch) + if !unionSite.variantBranch(loweringContext, i, schemaStatement) { continue } - name, id, ok := componentNamed(scope, referenceOf(loweringContext, st)) + name, id, ok := componentNamed(scope, referenceOf(loweringContext, schemaStatement)) routes = append(routes, implicitRoute{name: name, component: id, named: ok}) } return routes } -// besideUnionDiscriminator settles a discriminator a model holds beside a -// union kept verbatim. A model discriminator says the model is a hierarchy's -// base, so it stays only where every type it routes to is a subtype -// (ir.IsSubtype). Otherwise it moves, whole, to the model's Unmodeled, beside -// the union it was written for, a route to the model itself among them, which -// pass/validate takes from a concrete model (GitHub #1806). -// -// It is a settlement because only a lowered node says whether its type is a -// subtype, and a subtype lowered after the model has no Base yet when the -// model lowers. -type besideUnionDiscriminator struct { - c lowering.Ctx - s *statement.Schema - pointer jsontext.Pointer - model ir.TypeID // holds the discriminator and keeps the union verbatim - named []ir.TypeID // namedBranches -} +// discriminatorFactsBuilt keys the count of document indexes the run's +// model-discriminator settlement built. +type discriminatorFactsBuilt struct{} -// Settle keeps the model's discriminator or moves it. A model holding none is -// left alone: it declared none, or it was settled already, by the settlement a -// reference deferred when it built the model before its declaration did. -// -// It moves only what it could copy (GitHub #144). One converting to no JSON, -// such as one writing an extension `.nan`, is reported as unpreservable and -// stays on the model rather than vanish, where pass/validate reports its -// routes. -// -// A move leaving a map swaps in its MapT (ir.AsMap), which homes all the model -// did; a later settlement leaves the map alone. -func (d besideUnionDiscriminator) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { - if mt, settled := reg[d.model].(*ir.MapT); settled && mt != nil { - return nil - } - model, isModel := reg[d.model].(*ir.Model) - if !isModel || model == nil { - return []ir.Diagnostic{d.c.DiagAt(ir.SeverityError, diag.InternalInvariant, d.pointer, - "internal: %q is no model, so the discriminator settlement deferred for it is not taken", d.model)} - } - if model.Discriminator == nil || routesToSubtypes(reg, model, d.named) { - return nil - } - at := d.pointer + ids.Ptr("discriminator") - kept, diags := preserveSchemaKeyword(d.c, &model.Unmodeled, d.s, "discriminator", - ir.ReasonDegradedLowering, d.pointer) - if !kept { - return diags - } - promotion.DropContained(d.c.Promoter(), &model.Unmodeled, "openapi:discriminator") - recordKeptDiscriminatorRoutes(d.c, at, d.s.Discriminator(), model.Discriminator.Mapping, model.Discriminator.Default) - model.Discriminator = nil - if mt, isMap := ir.AsMap(model); isMap { - reg[d.model] = mt - } - return append(diags, d.c.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, - "the discriminator routes to a type that is not a subtype of the model holding it, so it cannot "+ - "stay there; kept verbatim under Unmodeled beside the union it was written for")) +// discriminatorFactsCount returns how many document indexes the run's +// model-discriminator settlement built, which only the tests read. +func discriminatorFactsCount(loweringContext lowering.Ctx) *int { + return lowering.ReadOncePerRun(loweringContext, discriminatorFactsBuilt{}, func() *int { return new(int) }) } -// routesToSubtypes reports whether every type model's discriminator routes to -// is a subtype of model: each mapping target, the default, and each of named. -// Each is one ir.IsSubtype walk rather than a question of an -// irfacts.DocumentFacts, which indexes the whole registry: a settlement asks a -// few questions, of a registry the settlements before it may have rewritten. -// Walks are not shared between settlements (GitHub #1008). -func routesToSubtypes(reg ir.TypeRegistry, model *ir.Model, named []ir.TypeID) bool { - doc := &ir.Document{Types: reg} - routes := slices.AppendSeq(slices.Clone(named), maps.Values(model.Discriminator.Mapping)) - if model.Discriminator.Default != "" { - routes = append(routes, model.Discriminator.Default) - } - for _, target := range routes { - if !ir.IsSubtype(doc, target, model.ID) { - return false - } - } - return true +// ancestorStepsTaken keys the count of composition edges the climb to +// discriminated ancestors followed. +type ancestorStepsTaken struct{} + +// ancestorStepCount returns how many composition edges the climb to each +// schema's discriminated ancestors followed in the run, which only the tests +// read. +func ancestorStepCount(loweringContext lowering.Ctx) *int { + return lowering.ReadOncePerRun(loweringContext, ancestorStepsTaken{}, func() *int { return new(int) }) } diff --git a/compilers/openapi/internal/schema/discriminator_allof_test.go b/compilers/openapi/internal/schema/discriminator_allof_test.go index d93526863..2d386cdd1 100644 --- a/compilers/openapi/internal/schema/discriminator_allof_test.go +++ b/compilers/openapi/internal/schema/discriminator_allof_test.go @@ -126,11 +126,11 @@ func TestAllOf_ExtensionSubtypeIsTaggedOnlyByAMapping(t *testing.T) { const subtypes = `%[1]sCat: {allOf: [{$ref: '#/components/schemas/Pet'}], type: object, properties: {purr: {type: string}}} %[1]sDog: {allOf: [{$ref: '#/components/schemas/Pet'}], type: object, properties: {bark: {type: string}}} ` - for _, tc := range []struct{ name, host, section string }{ + for _, testCase := range []struct{ name, host, section string }{ {"a root extension", "x-lib", "x-lib:\n" + fmt.Sprintf(subtypes, " ")}, {"another component kind", "components/x-shared", " x-shared:\n" + fmt.Sprintf(subtypes, " ")}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf(` Holder: type: object @@ -146,18 +146,18 @@ func TestAllOf_ExtensionSubtypeIsTaggedOnlyByAMapping(t *testing.T) { propertyName: kind mapping: cat: '#/%[1]s/Cat' -`, tc.host))+tc.section) +`, testCase.host))+testCase.section) assert.Empty(t, diags) - cat := ir.TypeID("type/anonymous/" + tc.host + "/Cat") - dog := ir.TypeID("type/anonymous/" + tc.host + "/Dog") + cat := ir.TypeID("type/anonymous/" + testCase.host + "/Cat") + dog := ir.TypeID("type/anonymous/" + testCase.host + "/Dog") assert.Empty(t, cmp.Diff(map[ir.TypeID]string{cat: "cat", dog: ""}, discriminatorValues(t, doc, cat, dog)), "the mapping tags Cat, and no name is implicit for Dog (-want +got)") pet, ok := doc.Types[componentID("Pet")].(*ir.Model) require.True(t, ok, "Pet lowers to a model") require.NotNil(t, pet.Discriminator) - assert.Empty(t, cmp.Diff(map[string]ir.TypeID{"cat": cat}, pet.Discriminator.Mapping), - "the base's mapping names the subtype's own node (-want +got)") + assert.Empty(t, cmp.Diff(map[string]ir.TypeID{"cat": cat, "Pet": componentID("Pet")}, pet.Discriminator.Mapping), + "the base's mapping names the subtype's own node, and the concrete base by its name (-want +got)") }) } } @@ -216,8 +216,9 @@ func TestAllOf_InlineSubtypeDiscriminatorValueFromMapping(t *testing.T) { pet, ok := doc.Types[componentID("Pet")].(*ir.Model) require.True(t, ok, "Pet should be a model") require.NotNil(t, pet.Discriminator) - assert.Equal(t, map[string]ir.TypeID{"woofer": kennelDog}, pet.Discriminator.Mapping, - "the base's own mapping resolves the same inline subtype the tag was read from") + assert.Equal(t, map[string]ir.TypeID{"woofer": kennelDog, "Dog": componentID("Dog"), "Pet": componentID("Pet")}, + pet.Discriminator.Mapping, + "the base's own mapping resolves the same inline subtype the tag was read from, beside the routes names give") } // TestAllOf_DiscriminatorValueFromDistantMapping pins the mapping-key spelling of @@ -337,7 +338,7 @@ func TestAllOf_DiscriminatorValueUndiscriminatedChain(t *testing.T) { func TestAllOf_DiscriminatorValueCyclicComposition(t *testing.T) { t.Parallel() const n = 6 - var b strings.Builder + var builder strings.Builder for i := range n { refs := make([]string, 0, n-1) for j := range n { @@ -345,10 +346,10 @@ func TestAllOf_DiscriminatorValueCyclicComposition(t *testing.T) { refs = append(refs, fmt.Sprintf("{$ref: '#/components/schemas/X%d'}", j)) } } - fmt.Fprintf(&b, " X%d:\n allOf: [%s]\n properties: {p%d: {type: string}}\n", + fmt.Fprintf(&builder, " X%d:\n allOf: [%s]\n properties: {p%d: {type: string}}\n", i, strings.Join(refs, ", "), i) } - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(b.String())) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(builder.String())) openapitest.RequireNoErrorDiags(t, diags) for i := range n { @@ -362,7 +363,7 @@ func TestAllOf_DiscriminatorValueCyclicComposition(t *testing.T) { // TestAllOf_DiscriminatorValueSelfAncestorInCycle pins that a composition cycle // does not make a schema one of its own ancestors. A declares the discriminator // and composes B, which composes A back, so walking A's ancestors comes round to -// A — whose mapping names A. A hierarchy of one schema standing above itself is +// A — whose mapping names A. A hierarchy of one schema above itself is // not a hierarchy, so the walk skips the schema it started from. func TestAllOf_DiscriminatorValueSelfAncestorInCycle(t *testing.T) { t.Parallel() @@ -388,44 +389,32 @@ func TestAllOf_DiscriminatorValueSelfAncestorInCycle(t *testing.T) { "and takes no tag from its own mapping by way of the cycle") } -// TestAllOf_DiscriminatorValueChainDeeperThanCap pins the ancestor walk's cap as -// behaviour rather than as a comment. A chain longer than the cap stops being -// searched, so the tag the root would have supplied is not stamped — stated here -// so the limit is a decision on record and a chain that grows past it is a -// failing test rather than a silent reversion to the bug this walk fixed. -// -// The shallower half is the control: the same construction one level inside the -// cap does carry the tag, which is what says the deep case failed on the cap and -// not on the construction. -func TestAllOf_DiscriminatorValueChainDeeperThanCap(t *testing.T) { +// TestAllOf_DiscriminatorValueTagsAChainOfAnyDepth pins that the climb to a +// discriminated ancestor stops at no depth: the leaf of a chain one hop and +// five hops past the 256 levels the climb once stopped at carries its name, +// which the root's Mapping routes, as the leaf of a shallower chain does. +func TestAllOf_DiscriminatorValueTagsAChainOfAnyDepth(t *testing.T) { t.Parallel() - // The two cases below straddle the cap. - const ancestorCap = schema.MaxDiscriminatorAncestorDepth - for _, tc := range []struct { - name string - links int - want string - }{ - {"within the cap", ancestorCap - 1, fmt.Sprintf("S%d", ancestorCap-2)}, - {"beyond the cap", ancestorCap + 4, ""}, - } { - t.Run(tc.name, func(t *testing.T) { + for _, hops := range []int{255, 257, 261} { + t.Run(fmt.Sprintf("%d hops", hops), func(t *testing.T) { t.Parallel() - var b strings.Builder - b.WriteString(" Root:\n type: object\n properties: {k: {type: string}}\n" + + var builder strings.Builder + builder.WriteString(" Root:\n type: object\n properties: {k: {type: string}}\n" + " discriminator: {propertyName: k}\n") prev := "Root" - for i := range tc.links { - fmt.Fprintf(&b, " S%d:\n allOf: [{$ref: '#/components/schemas/%s'}]\n"+ + for i := range hops { + fmt.Fprintf(&builder, " S%d:\n allOf: [{$ref: '#/components/schemas/%s'}]\n"+ " properties: {p%d: {type: string}}\n", i, prev, i) prev = fmt.Sprintf("S%d", i) } - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(b.String())) + doc, diags := parseFull(t, openapitest.ComponentSpec(builder.String())) openapitest.RequireNoErrorDiags(t, diags) leaf := typeByName(doc, prev).(*ir.Model) - assert.Equal(t, tc.want, leaf.DiscriminatorValue, - "%s is %d links below the discriminated root", prev, tc.links) + assert.Equal(t, prev, leaf.DiscriminatorValue, "%s is %d hops below the discriminated root", prev, hops) + root := typeByName(doc, "Root").(*ir.Model) + require.NotNil(t, root.Discriminator) + assert.Equal(t, componentID(prev), root.Discriminator.Mapping[prev], "the root routes the leaf by its name") }) } } @@ -466,7 +455,7 @@ func TestAllOf_BoolRefEntryHasNoDiscriminator(t *testing.T) { // Model.DiscriminatorValue holds one value, and a mapping is unordered, so the // key it holds must be chosen by a rule the source order cannot reach: the // smallest in byte order. The base keeps every key, so nothing is lost, and the -// election is reported so a reader knows the subtype's tag set is wider than +// choice is reported so a reader knows the subtype's tag set is wider than // the field shows. func TestAllOf_DiscriminatorAliasTagIsOrderInvariant(t *testing.T) { t.Parallel() @@ -485,13 +474,13 @@ func TestAllOf_DiscriminatorAliasTagIsOrderInvariant(t *testing.T) { const alpha = " alpha: '#/components/schemas/Dog'\n" const zulu = " zulu: '#/components/schemas/Dog'\n" - for _, tc := range []struct{ name, mapping string }{ + for _, testCase := range []struct{ name, mapping string }{ {"zulu first", zulu + alpha}, {"alpha first", alpha + zulu}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(base+tc.mapping+sub)) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(base+testCase.mapping+sub)) openapitest.RequireNoErrorDiags(t, diags) dog, ok := doc.Types[componentID("Dog")].(*ir.Model) @@ -501,11 +490,11 @@ func TestAllOf_DiscriminatorAliasTagIsOrderInvariant(t *testing.T) { pet, ok := doc.Types[componentID("Pet")].(*ir.Model) require.True(t, ok, "Pet should be a model") - assert.Equal(t, map[string]ir.TypeID{"alpha": componentID("Dog"), "zulu": componentID("Dog")}, - pet.Discriminator.Mapping, "the base keeps both keys") + assert.Equal(t, map[string]ir.TypeID{"alpha": componentID("Dog"), "zulu": componentID("Dog"), "Pet": componentID("Pet")}, + pet.Discriminator.Mapping, "the base keeps both keys, beside its own name") assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Dog"), - "the election is reported at the subtype: %+v", diags) + "the choice is reported at the subtype: %+v", diags) assert.True(t, openapitest.HasDiagAt(diags, diag.DegradedConstruct, ir.SeverityInfo), "as information, since the base's mapping loses nothing") }) @@ -525,3 +514,38 @@ func discriminatorValues(t *testing.T, doc *ir.Document, typeIDs ...ir.TypeID) m } return got } + +// TestAllOf_AnEntrysDiscriminatorKeepsWhatItsFlatTwinKeeps holds a +// discriminator an allOf entry writes, which the Model the allOf composes +// holds, to keeping the keys OpenAPI defines for no Discriminator Object and +// its extensions under the keys and reasons the discriminator written flat +// keeps them, each at the pointer it is written at, in every spelling and in +// either order. +func TestAllOf_AnEntrysDiscriminatorKeepsWhatItsFlatTwinKeeps(t *testing.T) { + t.Parallel() + const rest = "type: object, required: [dogType], properties: {dogType: {type: string}}" + const part = "discriminator: {propertyName: dogType, required: [dogType], x-ext: 1}" + spellings := openapitest.Spellings(rest, part) + for spelling, text := range openapitest.Reversed(rest, part) { + spellings[spelling+"Reversed"] = text + } + var written strings.Builder + for spelling, text := range spellings { + written.WriteString(" " + spelling + ": " + text + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + want := map[string]ir.UnmodeledReason{"openapi:discriminator/required": ir.ReasonOutOfScope, "openapi:discriminator/x-ext": ir.ReasonVendorExtension} + for spelling := range spellings { + model, ok := typeByName(doc, spelling).(*ir.Model) + require.True(t, ok, "%s: got %T", spelling, typeByName(doc, spelling)) + require.NotNil(t, model.Discriminator, spelling) + got := map[string]ir.UnmodeledReason{} + for key, entry := range model.Unmodeled { + got[key] = entry.Reason + assert.True(t, strings.HasSuffix(string(entry.Provenance.Pointer), "/discriminator/"+strings.TrimPrefix(key, "openapi:discriminator/")), + "%s: %s at %s", spelling, key, entry.Provenance.Pointer) + } + assert.Equal(t, want, got, spelling) + } +} diff --git a/compilers/openapi/internal/schema/discriminator_beside_union_test.go b/compilers/openapi/internal/schema/discriminator_beside_union_test.go index cba4db2dc..c39103cf7 100644 --- a/compilers/openapi/internal/schema/discriminator_beside_union_test.go +++ b/compilers/openapi/internal/schema/discriminator_beside_union_test.go @@ -20,63 +20,100 @@ import ( "github.com/dexpace/morphic/ir/irtest" ) -// TestDiscriminatorBesideUnion_MovesWhenARouteIsNoSubtype pins that a model -// beside a union kept verbatim does not keep a discriminator that routes to a -// type that is not its subtype, which pass.Validate rejects. Each route counts: -// a mapping target, the default, and a component a $ref branch names, which -// the discriminator routes to by name. Each "lowers to" row names a type whose -// own allOf names Pet but which lowers to no Model with that Base, which only -// the lowered document can tell. -func TestDiscriminatorBesideUnion_MovesWhenARouteIsNoSubtype(t *testing.T) { +// TestDiscriminatorBesideUnion_KeepsEachRouteToNoSubtype pins that a model +// beside a kept union keeps its discriminator, each route to a type not its +// subtype set aside: an entry or the default kept verbatim, a branch's name +// route unwritten, each reported once where written. A "lowers to" row's type +// names Pet in its allOf but is no Model with that Base. A mixin is no +// subtype, Cat taking Animal, which maps it too, as Base; a $ref beside an +// allOf naming Pet composes a subtype, while a value naming it reads through +// its $ref to Other. +func TestDiscriminatorBesideUnion_KeepsEachRouteToNoSubtype(t *testing.T) { t.Parallel() const viaPet = "{allOf: [{$ref: '#/components/schemas/Pet'}]" + const entry, catBranch, dogBranch, defaultMapping = "discriminator/mapping/cat", "oneOf/0", "oneOf/1", "discriminator/defaultMapping" cases := []struct { - name, version, discriminator, rest, want string + name, version, discriminator, rest string + mapping, decodeOnly map[string]string + lost []string }{ - {"mapped", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", cat + subDog, `"mapping"`}, - {"named by branch", "3.1.0", "{propertyName: kind}", cat + subDog, `"propertyName"`}, + {"mapped", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", cat + subDog, + map[string]string{"Dog": "Dog", "Pet": "Pet"}, nil, []string{entry, catBranch}}, + {"named by branch", "3.1.0", "{propertyName: kind}", cat + subDog, + map[string]string{"Dog": "Dog", "Pet": "Pet"}, nil, []string{catBranch}}, {"one mapped subtype and one branch that is not", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", - " Cat: " + viaPet + "}\n" + dog, `"mapping"`}, + " Cat: " + viaPet + "}\n" + dog, + map[string]string{"cat": "Cat", "Pet": "Pet"}, map[string]string{"Cat": "Cat"}, []string{dogBranch}}, {"default", "3.2.0", "{propertyName: kind, defaultMapping: '#/components/schemas/Other'}", - subtypes + " Other: {type: object}\n", `"defaultMapping"`}, + subtypes + " Other: {type: object}\n", + map[string]string{"Cat": "Cat", "Dog": "Dog", "Pet": "Pet"}, nil, []string{defaultMapping}}, {"mixin only", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", - " Cat: {allOf: [{$ref: '#/components/schemas/Other'}, {$ref: '#/components/schemas/Pet'}]}\n" + - dog + " Other: {type: object}\n", `"mapping"`}, + " Cat: {allOf: [{$ref: '#/components/schemas/Animal'}, {$ref: '#/components/schemas/Pet'}]}\n" + subDog + + " Animal: {type: object, properties: {kind: {type: string}}, " + + "discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}}\n", + map[string]string{"Dog": "Dog", "Pet": "Pet"}, nil, []string{entry, catBranch}}, {"position declaring an inline object", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Holder/properties/pet'}}", subtypes + " Holder: {type: object, properties: {pet: {type: object, properties: {kind: {type: string}}}}}\n", - `"mapping"`}, + map[string]string{"Cat": "Cat", "Dog": "Dog", "Pet": "Pet"}, nil, []string{entry}}, {"component that is a $ref to no subtype", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Alias'}}", - cat + subDog + " Alias: {$ref: '#/components/schemas/Cat'}\n", `"mapping"`}, + cat + subDog + " Alias: {$ref: '#/components/schemas/Cat'}\n", + map[string]string{"Dog": "Dog", "Pet": "Pet"}, nil, []string{entry, catBranch}}, {"lowers to an enum", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", - " Cat: " + viaPet + ", enum: [{kind: cat}]}\n" + subDog, `"mapping"`}, + " Cat: " + viaPet + ", enum: [{kind: cat}]}\n" + subDog, + map[string]string{"Dog": "Dog", "Pet": "Pet"}, nil, []string{entry, catBranch}}, {"lowers to a literal", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", - " Cat: " + viaPet + ", const: {kind: cat}}\n" + subDog, `"mapping"`}, - {"lowers to an alias over its $ref", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", + " Cat: " + viaPet + ", const: {kind: cat}}\n" + subDog, + map[string]string{"Dog": "Dog", "Pet": "Pet"}, nil, []string{entry, catBranch}}, + {"a $ref beside its allOf composing Pet, a subtype", "3.1.0", "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}", " Cat: {$ref: '#/components/schemas/Other', allOf: [{$ref: '#/components/schemas/Pet'}]}\n" + - " Other: {type: object}\n" + subDog, `"mapping"`}, + " Other: {type: object}\n" + dog, + map[string]string{"Cat": "Cat", "Pet": "Pet"}, nil, []string{entry, dogBranch}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() for _, doc := range discriminatedOrders(t, c.version, petWith(c.discriminator), c.rest) { - assertMoved(t, doc, c.want) + assertStayed(t, doc) + assert.Equal(t, routes{Mapping: c.mapping, DecodeOnly: c.decodeOnly}, routesOf(t, doc, "Pet")) + assertLostRoutes(t, doc, c.lost) } }) } } -// TestDiscriminatorBesideUnion_LeavesAMapWhenItMoves pins that a discriminator -// moving off a body whose one other member fact is its catch-all leaves a map, -// which is a MapT, as it is when no discriminator is written -// (docs/ir/containers.md). -func TestDiscriminatorBesideUnion_LeavesAMapWhenItMoves(t *testing.T) { +// assertLostRoutes requires one info at each route set aside, its pointer +// below Pet's, and none elsewhere. +func assertLostRoutes(t *testing.T, doc *ir.Document, lost []string) { + t.Helper() + const at = "/components/schemas/Pet/" + want := make([]string, 0, len(lost)) + for _, pointer := range lost { + want = append(want, at+pointer) + } + var got []string + for _, diagnostic := range doc.Diagnostics { + if diagnostic.Code == diag.UnhomedConstruct { + got = append(got, string(diagnostic.Provenance.Pointer)) + } + } + assert.ElementsMatch(t, want, got, "one info at each route set aside") + assert.False(t, openapitest.HasDiagCodeAt(doc.Diagnostics, diag.DegradedConstruct, at+"discriminator"), + "the discriminator is not kept whole") +} + +// TestDiscriminatorBesideUnion_AMapKeepingARouteStaysAModel pins a body whose +// one other member fact is its catch-all: its discriminator, keeping the +// routes to itself and to Dog, stays, so the body is a Model, the route to +// Cat, no subtype, set aside (docs/ir/containers.md). +func TestDiscriminatorBesideUnion_AMapKeepingARouteStaysAModel(t *testing.T) { t.Parallel() for _, doc := range discriminatedOrders(t, "3.1.0", mapPet, cat+subDog) { - assertMovedToMap(t, typeByName(doc, "Pet")) - assert.Empty(t, unreadReports(doc.Diagnostics, "/components/schemas/Pet"), - "the map holds all that would otherwise be kept unread, and the move keeps the discriminator itself") + assertStayed(t, doc) + assert.NotNil(t, petModel(t, doc).AdditionalProperties, "the catch-all stays beside the discriminator") + assert.Equal(t, routes{Mapping: map[string]string{"Dog": "Dog", "Pet": "Pet"}}, routesOf(t, doc, "Pet")) + assertLostRoutes(t, doc, []string{"oneOf/0"}) } } @@ -101,29 +138,32 @@ func TestDiscriminatorBesideUnion_SettlesAMapAReferenceNamesFirst(t *testing.T) } // TestDiscriminatorBesideUnion_ARequiredNameKeepsTheBodyAModel pins a body -// whose catch-all sits beside a required name its properties do not declare: -// the name is in Model.Requires, which no map holds, so the discriminator's -// move leaves a Model, nothing kept verbatim for want of a home. It holds for -// a plain object and a composed one. +// whose catch-all sits beside a required name its properties do not declare, +// at a position whose discriminator keeps no route typed, so it is kept +// whole: the name is in Model.Requires, which no map holds, so the body stays +// a Model, nothing kept verbatim for want of a home. It holds for a plain +// object and a composed one. func TestDiscriminatorBesideUnion_ARequiredNameKeepsTheBodyAModel(t *testing.T) { t.Parallel() const ( - body = " additionalProperties: {type: string}\n required: [a]\n discriminator: {propertyName: kind}\n" + petBranches - pointer = "/components/schemas/Pet" + body = " additionalProperties: {type: string}\n required: [a]\n" + + " discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}\n" + + " oneOf: [{required: [kind]}, {required: [x]}]\n" + pointer = "/components/schemas/Holder/properties/pet" ) - for _, tc := range []struct { - name, pet string - node ir.TypeID - }{ - {"plain", " Pet:\n type: object\n" + body, componentID("Pet")}, - {"composed", " Pet:\n allOf: [{type: object}]\n" + body, componentID("Pet")}, + outside := " Outside: {$ref: '#/components/schemas/Holder/properties/pet'}\n" + for _, testCase := range []struct{ name, pet string }{ + {"plain", " Holder:\n type: object\n properties:\n pet:\n type: object\n" + body}, + {"composed", " Holder:\n type: object\n properties:\n pet:\n allOf: [{type: object}]\n" + body}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - for _, doc := range discriminatedOrders(t, "3.1.0", tc.pet, cat+subDog) { - model, ok := doc.Types[tc.node].(*ir.Model) - require.True(t, ok, "a required name keeps the body a Model; got %T", doc.Types[tc.node]) - assert.Nil(t, model.Discriminator, "the discriminator moved") + for _, doc := range discriminatedOrders(t, "3.1.0", outside, testCase.pet+cat+dog) { + node := doc.Types["type/anonymous"+pointer] + model, ok := node.(*ir.Model) + require.True(t, ok, "a required name keeps the body a Model; got %T", node) + assert.Nil(t, model.Discriminator, "the discriminator is kept whole") + assert.Contains(t, model.Unmodeled, "openapi:discriminator") assert.Equal(t, []string{"a"}, model.Requires) assert.NotContains(t, model.Unmodeled, "openapi:required") assert.Empty(t, unreadReports(doc.Diagnostics, pointer)) @@ -145,10 +185,12 @@ func TestDiscriminatorBesideUnion_KeepsARoutingMapAModel(t *testing.T) { // TestDiscriminatorBesideUnion_StaysWhenEveryRouteIsASubtype pins the case the // model keeps its discriminator beside a kept union: every route is a subtype, -// at any distance and however it is spelled, a route writing a union beside -// its allOf among them, which the route keeps a subtype. A branch no name -// reaches, inline or a position, is no route, so it does not move the -// discriminator either, an inline one composing Pet keeping Pet a model. +// at any distance and however spelled, a route writing a union beside its +// allOf among them. A branch no name reaches, inline or a position, is no +// route, an inline one composing Pet keeping Pet a model. A subtype the union +// does not list no route reaches, which validation notes: a component that is +// a $ref composes what it names; an inline branch the kept union holds +// verbatim is none. func TestDiscriminatorBesideUnion_StaysWhenEveryRouteIsASubtype(t *testing.T) { t.Parallel() const grand = " Cat: {allOf: [{$ref: '#/components/schemas/Mid'}], type: object}\n" + @@ -157,31 +199,33 @@ func TestDiscriminatorBesideUnion_StaysWhenEveryRouteIsASubtype(t *testing.T) { unnamed := " Pet:\n type: object\n discriminator: {propertyName: kind}\n" + " oneOf: [{allOf: [{$ref: '#/components/schemas/Pet'}], properties: {kind: {type: string}}}, " + "{$ref: '#/components/schemas/Holder/properties/pet'}]\n" + const unrouted = "pass/discriminator-unrouted-variant" cases := []struct { name, version, pet, rest string + told []string }{ - {"mapped", "3.1.0", petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}"), subtypes}, - {"named by branch", "3.1.0", petWith("{propertyName: kind}"), subtypes}, - {"mapped by bare name", "3.1.0", petWith("{propertyName: kind, mapping: {cat: Cat, dog: Dog}}"), subtypes}, + {"mapped", "3.1.0", petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}"), subtypes, nil}, + {"named by branch", "3.1.0", petWith("{propertyName: kind}"), subtypes, nil}, + {"mapped by bare name", "3.1.0", petWith("{propertyName: kind, mapping: {cat: Cat, dog: Dog}}"), subtypes, nil}, {"mapped through a position that is only a $ref", "3.1.0", petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Holder/properties/pet'}}"), - subtypes + " Holder: {type: object, properties: {pet: {$ref: '#/components/schemas/Cat'}}}\n"}, + subtypes + " Holder: {type: object, properties: {pet: {$ref: '#/components/schemas/Cat'}}}\n", nil}, {"mapped through a component that is a $ref", "3.1.0", petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Alias'}}"), - subtypes + " Alias: {$ref: '#/components/schemas/Cat'}\n"}, - {"grandchild", "3.1.0", petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}"), grand}, - {"default", "3.2.0", petWith("{propertyName: kind, defaultMapping: '#/components/schemas/Dog'}"), subtypes}, - {"branches no name reaches", "3.1.0", unnamed, cat + " Holder: {type: object, properties: {pet: {type: object}}}\n"}, + subtypes + " Alias: {$ref: '#/components/schemas/Cat'}\n", []string{unrouted}}, + {"grandchild", "3.1.0", petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}"), grand, []string{unrouted}}, + {"default", "3.2.0", petWith("{propertyName: kind, defaultMapping: '#/components/schemas/Dog'}"), subtypes, nil}, + {"branches no name reaches", "3.1.0", unnamed, cat + " Holder: {type: object, properties: {pet: {type: object}}}\n", nil}, {"a union beside its allOf, which a route keeps undistributed", "3.1.0", petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}"), " Cat: {allOf: [{$ref: '#/components/schemas/Pet'}], " + "oneOf: [{$ref: '#/components/schemas/House'}, {$ref: '#/components/schemas/Wild'}]}\n" + - " House: {type: object}\n Wild: {type: object}\n" + subDog}, + " House: {type: object}\n Wild: {type: object}\n" + subDog, nil}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - for _, doc := range discriminatedOrders(t, c.version, c.pet, c.rest) { + for _, doc := range discriminatedOrdersTold(t, c.version, c.pet, c.rest, c.told) { assertStayed(t, doc) } }) @@ -189,8 +233,9 @@ func TestDiscriminatorBesideUnion_StaysWhenEveryRouteIsASubtype(t *testing.T) { } // TestDiscriminatorBesideUnion_StaysForASubtypeAtAnyDepth pins that no depth bound -// stands between a route and Pet: pass.Validate follows a hierarchy to any -// depth, so a bound here would move a discriminator it accepts. +// sits between a route and Pet: pass.Validate follows a hierarchy to any +// depth, so a bound here would move a discriminator it accepts. The hops the +// union does not list and no entry routes are subtypes no route reaches. func TestDiscriminatorBesideUnion_StaysForASubtypeAtAnyDepth(t *testing.T) { t.Parallel() var chain strings.Builder @@ -199,39 +244,45 @@ func TestDiscriminatorBesideUnion_StaysForASubtypeAtAnyDepth(t *testing.T) { } chain.WriteString(" C300: {allOf: [{$ref: '#/components/schemas/Pet'}], type: object}\n") pet := petWith("{propertyName: kind, mapping: {c: '#/components/schemas/C0'}}") - for _, doc := range discriminatedOrders(t, "3.1.0", pet, subtypes+chain.String()) { + told := slices.Repeat([]string{"pass/discriminator-unrouted-variant"}, 300) + for _, doc := range discriminatedOrdersTold(t, "3.1.0", pet, subtypes+chain.String(), told) { assertStayed(t, doc) } } -// TestDiscriminatorBesideUnion_ReportsTheMoveOnce pins the diagnostic: exactly -// one, at the discriminator, when it moves, in either declaration order, and -// none when it stays. -func TestDiscriminatorBesideUnion_ReportsTheMoveOnce(t *testing.T) { +// TestDiscriminatorBesideUnion_ReportsEachLostRouteOnce pins the diagnostics: +// exactly one at each route set aside, the entry and the branch naming Cat, +// in either declaration order, none where every route is a subtype, and the +// discriminator never reported as kept whole. +func TestDiscriminatorBesideUnion_ReportsEachLostRouteOnce(t *testing.T) { t.Parallel() pet := petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}") - for _, src := range []string{pet + cat + subDog, cat + subDog + pet} { - _, diags := parseFull(t, openapitest.ComponentSpec(src)) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, movedPointer), - "not a subtype of the model holding it") + for _, doc := range discriminatedOrders(t, "3.1.0", pet, cat+subDog) { + assertLostRoutes(t, doc, []string{"discriminator/mapping/cat", "oneOf/0"}) + } + for _, doc := range discriminatedOrders(t, "3.1.0", pet, subtypes) { + assertLostRoutes(t, doc, nil) } - _, diags := parseFull(t, openapitest.ComponentSpec(pet+subtypes)) - assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, movedPointer)) } // TestDiscriminatorBesideUnion_EveryDegradedShapeIsSettled pins that the rule // holds on every union kept verbatim beside a model, not only one its -// discriminator alone degrades, both ways. +// discriminator alone degrades, both ways: an entry routing to no subtype is +// kept alone, and one routing to a subtype stays. Dog, which no inline branch +// lists, no route reaches. func TestDiscriminatorBesideUnion_EveryDegradedShapeIsSettled(t *testing.T) { t.Parallel() for _, shape := range degradedShapes { t.Run(shape.name, func(t *testing.T) { t.Parallel() for _, doc := range discriminatedOrders(t, "3.1.0", degradedPet(shape.branches), cat+dog) { - assertMoved(t, doc, `"mapping"`) + assertEntryKept(t, doc, "cat", "#/components/schemas/Cat") + assert.Equal(t, map[string]string{"Pet": "Pet"}, routesOf(t, doc, "Pet").Mapping) } - for _, doc := range discriminatedOrders(t, "3.1.0", degradedPet(shape.branches), subtypes) { + told := []string{"pass/discriminator-unrouted-variant"} + for _, doc := range discriminatedOrdersTold(t, "3.1.0", degradedPet(shape.branches), subtypes, told) { assertStayed(t, doc) + assert.Equal(t, map[string]string{"cat": "Cat", "Pet": "Pet"}, routesOf(t, doc, "Pet").Mapping) } }) } @@ -245,45 +296,51 @@ func TestDiscriminatorBesideUnion_AllOfBodyIsSettled(t *testing.T) { pet := " Pet:\n allOf: [{$ref: '#/components/schemas/Base'}]\n" + " discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}\n" + petBranches for _, doc := range discriminatedOrders(t, "3.1.0", pet, cat+subDog+" Base: {type: object}\n") { - assertMoved(t, doc, `"mapping"`) + assertStayed(t, doc) + assert.Equal(t, routes{Mapping: map[string]string{"Dog": "Dog", "Pet": "Pet"}}, routesOf(t, doc, "Pet")) + assertLostRoutes(t, doc, []string{"discriminator/mapping/cat", "oneOf/0"}) } } -// TestDiscriminatorBesideUnion_MovesOnlyWhatItCopied pins that the move never -// loses a discriminator it could not keep verbatim. One merged in through `<<` -// is read as a written one is (GitHub #395), so Pet lowers as it does with the -// discriminator written in place. One that converts to no JSON, through an -// extension written `.nan`, is reported as unpreservable and stays on the -// model, and nothing claims a copy never made. -func TestDiscriminatorBesideUnion_MovesOnlyWhatItCopied(t *testing.T) { +// TestDiscriminatorBesideUnion_KeepsWholeOnlyWhatItCopied pins that keeping a +// discriminator no route of which stays typed never loses one it could not +// keep verbatim. One merged in through `<<` is read as a written one is +// (GitHub #395), so the position lowers as it does with the discriminator +// written in place. One writing an extension that converts to no JSON is kept +// as it is without it, the extension alone dropped with its own warning, and +// no error drawn: what its twin does with the discriminator, the spelling with +// the extension does. +func TestDiscriminatorBesideUnion_KeepsWholeOnlyWhatItCopied(t *testing.T) { t.Parallel() - const disc = "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}" - written, _ := parseFull(t, openapitest.ComponentSpec(cat+subDog+petWith(disc))) - merged, diags := parseFull(t, openapitest.ComponentSpec(cat+subDog+ - " Pet:\n <<: {discriminator: "+disc+"}\n type: object\n"+petBranches)) + const disc = "{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}" + holder := func(discriminator string) string { + return " Holder:\n type: object\n properties:\n pet:\n type: object\n" + + " properties: {name: {type: string}}\n" + discriminator + + " oneOf: [{required: [kind]}, {required: [x]}]\n" + } + at := "type/anonymous" + anonymousPetPointer + written, _ := parseFull(t, openapitest.ComponentSpec(cat+dog+holder(" discriminator: "+disc+"}\n"))) + merged, diags := parseFull(t, openapitest.ComponentSpec(cat+dog+holder(" <<: {discriminator: "+disc+"}}\n"))) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, cmp.Diff(typeByName(written, "Pet"), typeByName(merged, "Pet")), + assert.Empty(t, cmp.Diff(written.Types[ir.TypeID(at)], merged.Types[ir.TypeID(at)]), "a merged discriminator lowers as a written one") - doc, diags := parseFull(t, openapitest.ComponentSpec(cat+subDog+ - petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}, x-weight: .nan}"))) - pet := petModel(t, doc) - require.NotNil(t, pet.Discriminator, "the model read it, so it is not lost") - assert.Equal(t, "kind", pet.Discriminator.PropertyName) - assert.NotContains(t, pet.Unmodeled, "openapi:discriminator") - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, movedPointer), - "the failed copy is reported: %+v", diags) - assert.False(t, slices.ContainsFunc(diags, func(diagnostic ir.Diagnostic) bool { - return strings.Contains(diagnostic.Message, "beside the union it was written for") - }), "no move is announced") + requireKeptWithoutExtension(t, parseFull, openapitest.ComponentSpec(cat+dog+ + holder(" discriminator: "+disc+unconvertibleExtension+"}\n")), + unconvertibleExtension, anonymousPetPointer+"/discriminator") } +// anonymousPetPointer is where the Holder those tests declare writes the +// position its pet property is. +const anonymousPetPointer = "/components/schemas/Holder/properties/pet" + // TestDiscriminatorBesideUnion_UnreachableBranchesAreNoRoute pins that a // branch the discriminator cannot route to by name decides nothing, whichever // way it is unreachable: a $ref to an undeclared component, or one into // another document, though its fragment spells a component this one declares, -// Lone, which is no subtype. The unresolved $refs are error diagnostics, so -// the document is checked with pass.Validate directly. +// Lone, which is no subtype. Beside a non-subtype the discriminator stays, its +// routes to Cat set aside. The unresolved $refs are error diagnostics, so the +// document is checked with pass.Validate directly. func TestDiscriminatorBesideUnion_UnreachableBranchesAreNoRoute(t *testing.T) { t.Parallel() const branches = " oneOf: [{$ref: '#/components/schemas/Cat'}, {$ref: '#/components/schemas/Nope'}, " + @@ -302,13 +359,13 @@ func TestDiscriminatorBesideUnion_UnreachableBranchesAreNoRoute(t *testing.T) { docs := make([]*ir.Document, 0, 2) for _, src := range []string{pet + c.rest, c.rest + pet} { doc, _ := parseFull(t, openapitest.ComponentSpec(src)) - assert.Empty(t, validated(t, doc), "the document must validate") + assert.Empty(t, routeFindings(t, doc), "the document must validate") docs = append(docs, doc) - if c.stays { - assertStayed(t, doc) - continue + assertStayed(t, doc) + if !c.stays { + assert.Equal(t, routes{Mapping: map[string]string{"Pet": "Pet"}}, routesOf(t, doc, "Pet")) + assertLostRoutes(t, doc, []string{"discriminator/mapping/cat", "oneOf/0"}) } - assertMoved(t, doc, `"mapping"`) } assert.Empty(t, cmp.Diff(docs[0].Types, docs[1].Types, orderInvariantIR()...)) assert.Equal(t, reported(docs[0].Diagnostics), reported(docs[1].Diagnostics)) @@ -317,28 +374,43 @@ func TestDiscriminatorBesideUnion_UnreachableBranchesAreNoRoute(t *testing.T) { } // TestDiscriminatorBesideUnion_CyclicRouteMoves pins that a route whose -// hierarchy loops without reaching Pet is no subtype, and the check ends. +// hierarchy loops without reaching Pet is no subtype, and the check ends: its +// entry is kept alone, the routes to the subtypes staying typed. A loop of +// allOf hops is a reference loop, reported once at its least member, the top +// type, so it composes nothing and no composition cycle is reported, in either +// declaration order. func TestDiscriminatorBesideUnion_CyclicRouteMoves(t *testing.T) { t.Parallel() pet := petWith("{propertyName: kind, mapping: {loop: '#/components/schemas/Loop'}}") rest := subtypes + " Loop: {allOf: [{$ref: '#/components/schemas/LoopB'}]}\n" + " LoopB: {allOf: [{$ref: '#/components/schemas/Loop'}]}\n" - loop := []string{"pass/composition-cycle", "pass/composition-cycle"} - for _, doc := range discriminatedOrdersTold(t, "3.1.0", pet, rest, loop) { - assertMoved(t, doc, `"loop"`) + for _, src := range []string{pet + rest, rest + pet} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", src)) + var errs []string + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityError { + errs = append(errs, diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + } + assert.Equal(t, []string{diag.CyclicRef + " /components/schemas/Loop"}, errs, "the one error is the loop's") + assert.Empty(t, irtest.DiagCodes(validated(t, doc)), "the document must validate") + assertEntryKept(t, doc, "loop", "#/components/schemas/Loop") + assert.Equal(t, map[string]string{"Cat": "Cat", "Dog": "Dog", "Pet": "Pet"}, routesOf(t, doc, "Pet").Mapping) } } -// TestDiscriminatorBesideUnion_SubtypeKeepsItsTag pins what a move leaves -// alone: a route that is a subtype still carries the tag the mapping gives it, -// since that is the value its instances carry on the wire. +// TestDiscriminatorBesideUnion_SubtypeKeepsItsTag pins what keeping an entry +// leaves alone: a route that is a subtype still carries the tag the mapping +// gives it, since that is the value its instances carry on the wire, and stays +// typed beside the entry kept. func TestDiscriminatorBesideUnion_SubtypeKeepsItsTag(t *testing.T) { t.Parallel() pet := petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat', dog: '#/components/schemas/Dog'}}") rest := subCat + dog for _, doc := range discriminatedOrders(t, "3.1.0", pet, rest) { - assertMoved(t, doc, `"dog"`) + assertEntryKept(t, doc, "dog", "#/components/schemas/Dog") + assert.Equal(t, map[string]string{"cat": "Cat", "Pet": "Pet"}, routesOf(t, doc, "Pet").Mapping) sub, ok := typeByName(doc, "Cat").(*ir.Model) require.True(t, ok) assert.Equal(t, "cat", sub.DiscriminatorValue) @@ -347,7 +419,9 @@ func TestDiscriminatorBesideUnion_SubtypeKeepsItsTag(t *testing.T) { // TestDiscriminatorBesideUnion_SettlesAnOperationsSchemaToo pins that the // settlement waits for the operations as well as the components: a request -// body lowers in the service walk, after every component. +// body lowers in the service walk, after every component. Its one route names +// no subtype and it has no name of its own, so no route stays typed and the +// discriminator is kept whole, reported once. func TestDiscriminatorBesideUnion_SettlesAnOperationsSchemaToo(t *testing.T) { t.Parallel() spec := `openapi: 3.1.0 @@ -372,16 +446,19 @@ components: openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, validated(t, doc)) const at = "/paths/~1pets/post/requestBody/content/application~1json/schema/discriminator" - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, at), "%+v", diags) + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, at), 1, "kept whole, reported once: %+v", diags) + assert.Empty(t, withCode(diags, diag.UnhomedConstruct), "no entry is reported apart") } // TestDiscriminatorBesideUnion_SettlesAPositionAReferenceNamesFirst pins a // model a $ref names before its declaration lowers it: the reference builds -// nothing, so the declaration alone lowers the model and defers its settlement, -// which moves the discriminator off it once, in either order. +// nothing, so the declaration alone lowers the model and defers its +// settlement, which keeps the discriminator whole once, in either order, as no +// route stays typed: its one entry names no subtype, and the position has no +// name of its own. func TestDiscriminatorBesideUnion_SettlesAPositionAReferenceNamesFirst(t *testing.T) { t.Parallel() - const at = "/components/schemas/Holder/properties/pet" + const at = anonymousPetPointer outside := " Outside: {$ref: '#/components/schemas/Holder/properties/pet'}\n" holder := " Holder:\n type: object\n properties:\n pet:\n type: object\n" + " properties: {name: {type: string}}\n" + @@ -391,9 +468,11 @@ func TestDiscriminatorBesideUnion_SettlesAPositionAReferenceNamesFirst(t *testin pet, ok := doc.Types["type/anonymous"+at].(*ir.Model) require.True(t, ok) assert.Nil(t, pet.Discriminator) - assert.Contains(t, pet.Unmodeled, "openapi:discriminator") + assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/mapping/cat": componentID("Cat")}, pet.Unmodeled["openapi:discriminator"].Targets, + "kept whole, its entry naming the type it lowered to") assert.Contains(t, openapitest.DiagMessageAt(t, doc.Diagnostics, diag.DegradedConstruct, ir.SeverityInfo, at+"/discriminator"), - "not a subtype", "one move, reported once") + "not a subtype", "kept whole, reported once") + assert.Empty(t, withCode(doc.Diagnostics, diag.UnhomedConstruct), "no entry is reported apart") } } @@ -431,18 +510,18 @@ func discriminatedOrdersTold(t *testing.T, version, pet, rest string, told []str return docs } -// assertMoved requires Pet's discriminator to be kept verbatim, whole, rather -// than on the model, and want to appear in what was kept. -func assertMoved(t *testing.T, doc *ir.Document, want string) { +// assertEntryKept requires Pet to hold its discriminator less the entry +// routing to no subtype, which is kept verbatim on Pet, naming target, and +// reported once where it is written, and the discriminator nowhere else. +func assertEntryKept(t *testing.T, doc *ir.Document, entry, target string) { t.Helper() pet := petModel(t, doc) - assert.Nil(t, pet.Discriminator, "a discriminator routing to a non-subtype stays off the model") - entry, ok := pet.Unmodeled["openapi:discriminator"] - require.True(t, ok, "the discriminator is kept verbatim") - assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assert.Equal(t, ir.Provenance{Pointer: movedPointer}, entry.Provenance) - assert.Contains(t, string(entry.Value), `"propertyName":"kind"`, "the whole object is kept") - assert.Contains(t, string(entry.Value), want) + require.NotNil(t, pet.Discriminator, "an entry routing to no subtype leaves the rest on the model") + assert.NotContains(t, pet.Discriminator.Mapping, entry, "the entry is no typed route") + assert.NotContains(t, pet.Unmodeled, "openapi:discriminator", "the discriminator is not kept whole") + assert.Equal(t, 1, keptNamingTarget(pet.Unmodeled, target), "the entry is kept verbatim, once") + assert.Len(t, diagsAtPointer(doc.Diagnostics, diag.UnhomedConstruct, movedPointer+"/mapping/"+entry), 1) + assert.False(t, openapitest.HasDiagCodeAt(doc.Diagnostics, diag.DegradedConstruct, movedPointer)) } // assertStayed requires Pet to hold its discriminator and to store it nowhere @@ -473,12 +552,12 @@ func unreadReports(diags []ir.Diagnostic, pointer jsontext.Pointer) []string { return out } -// assertMovedToMap requires td to be the MapT a map body is once its +// assertMovedToMap requires typeDef to be the MapT a map body is once its // discriminator has moved, holding the union and the discriminator verbatim. -func assertMovedToMap(t *testing.T, td ir.TypeDef) { +func assertMovedToMap(t *testing.T, typeDef ir.TypeDef) { t.Helper() - mt, ok := td.(*ir.MapT) - require.True(t, ok, "got %T", td) + mt, ok := typeDef.(*ir.MapT) + require.True(t, ok, "got %T", typeDef) assert.Equal(t, ir.TypeRef{Target: "type/primitive/string"}, mt.Value) assert.Contains(t, mt.Unmodeled, "openapi:oneOf", "the union is kept beside it") assert.Contains(t, mt.Unmodeled, "openapi:discriminator", "and the discriminator with it") @@ -512,16 +591,28 @@ func petModel(t *testing.T, doc *ir.Document) *ir.Model { } // TestDiscriminatorBesideUnion_ASettledDiscriminatorHoldsItsExtensions holds -// a discriminator settled verbatim onto its model's Unmodeled to that one -// entry: an extension written inside it is within the entry, so the model -// keeps it no second time under openapi:discriminator/. +// a discriminator kept whole onto its model's Unmodeled, as no route of it +// stays typed, to that one entry: an extension written inside it is within +// the entry, so the model keeps it no second time under +// openapi:discriminator/. One that stays keeps its extension under that +// key, beside the entry it sets aside. func TestDiscriminatorBesideUnion_ASettledDiscriminatorHoldsItsExtensions(t *testing.T) { t.Parallel() - pet := " Pet:\n allOf: [{$ref: '#/components/schemas/Base'}]\n" + - " discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}, x-tag: 5}\n" + petBranches - for _, doc := range discriminatedOrders(t, "3.1.0", pet, cat+subDog+" Base: {type: object}\n") { - kept := petModel(t, doc).Unmodeled + const disc = "discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}, x-tag: 5}\n" + outside := " Outside: {$ref: '#/components/schemas/Holder/properties/pet'}\n" + holder := " Holder:\n type: object\n properties:\n pet:\n" + + " allOf: [{$ref: '#/components/schemas/Base'}]\n " + disc + + " oneOf: [{required: [kind]}, {required: [x]}]\n" + for _, doc := range discriminatedOrders(t, "3.1.0", outside, holder+cat+dog+" Base: {type: object}\n") { + kept := doc.Types[ir.TypeID("type/anonymous"+anonymousPetPointer)].Common().Unmodeled assert.Contains(t, string(kept["openapi:discriminator"].Value), `"x-tag":5`) assert.NotContains(t, kept, "openapi:discriminator/x-tag") } + pet := " Pet:\n allOf: [{$ref: '#/components/schemas/Base'}]\n " + disc + petBranches + for _, doc := range discriminatedOrders(t, "3.1.0", pet, cat+subDog+" Base: {type: object}\n") { + kept := petModel(t, doc).Unmodeled + assert.Equal(t, `5`, string(kept["openapi:discriminator/x-tag"].Value)) + assert.Contains(t, kept, "openapi:discriminator/mapping") + assert.NotContains(t, kept, "openapi:discriminator") + } } diff --git a/compilers/openapi/internal/schema/discriminator_cost_test.go b/compilers/openapi/internal/schema/discriminator_cost_test.go new file mode 100644 index 000000000..1ea5fa8af --- /dev/null +++ b/compilers/openapi/internal/schema/discriminator_cost_test.go @@ -0,0 +1,91 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" +) + +// settledModels declares a chain C0 to Cn and n models, each discriminated +// beside a union of validation-only branches it keeps verbatim, whose mapping +// names the chain's deepest hop, GitHub #1008's shape: every model's +// settlement asks whether that hop is a subtype of it, of the whole chain. +func settledModels(n int) string { + var builder strings.Builder + builder.WriteString(" C0: {type: object, properties: {kind: {type: string}}}\n") + for i := 1; i <= n; i++ { + fmt.Fprintf(&builder, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}], type: object}\n", i, i-1) + } + for k := range n { + fmt.Fprintf(&builder, " M%d: {type: object, properties: {name: {type: string}}, "+ + "discriminator: {propertyName: kind, mapping: {x: '#/components/schemas/C%d'}}, "+ + "oneOf: [{required: [kind]}, {required: [x]}]}\n", k, n) + } + return openapitest.ComponentSpec(builder.String()) +} + +// TestDiscriminatorSettlement_BuildsOneIndexARun pins GitHub #1008: every +// model discriminator is judged by one settlement asking one document index +// for the run, however many models it settles, so no settlement walks the +// hierarchy afresh. +func TestDiscriminatorSettlement_BuildsOneIndexARun(t *testing.T) { + t.Parallel() + for _, n := range []int{8, 64} { + _, diags, built := schema.LowerSpecCountingDiscriminatorFacts(t, settledModels(n)) + openapitest.RequireNoErrorDiags(t, diags) + assert.Equal(t, 1, built, "%d models settle against one index", n) + } +} + +// TestDiscriminatorValue_ClimbsAHierarchyLinearly pins that each schema's +// discriminated ancestors are read once a run, so the climb's steps over a +// chain, and over one whose every hop composes the two above it, grow by +// about a doubling per doubling of the levels. The sizes are the smallest +// showing the growth; a climb per schema costs a pass per level. +func TestDiscriminatorValue_ClimbsAHierarchyLinearly(t *testing.T) { + t.Parallel() + for _, shape := range []struct { + name string + build func(levels int) string + }{ + {"a chain", func(levels int) string { return openapitest.ComponentSpec(deepHierarchy(levels, false)) }}, + {"a chain of two parents", twoParentHierarchy}, + } { + t.Run(shape.name, func(t *testing.T) { + t.Parallel() + steps := func(levels int) int { + _, diags, counted := schema.LowerSpecCountingAncestorSteps(t, shape.build(levels)) + openapitest.RequireNoErrorDiags(t, diags) + return counted + } + a, b, c := steps(250), steps(500), steps(1000) + require.Less(t, a, b) + assert.LessOrEqual(t, float64(c-b), 2.2*float64(b-a), "steps at 250, 500, 1000: %d, %d, %d", a, b, c) + }) + } +} + +// twoParentHierarchy declares Pet, discriminated, and hops C1 to Cn, each +// composing the two before it. +func twoParentHierarchy(levels int) string { + var builder strings.Builder + builder.WriteString(" Pet: {type: object, required: [kind], properties: {kind: {type: string}}, discriminator: {propertyName: kind}}\n") + builder.WriteString(" C1: {allOf: [{$ref: '#/components/schemas/Pet'}]}\n") + for i := 2; i <= levels; i++ { + older := "Pet" + if i > 2 { + older = fmt.Sprintf("C%d", i-2) + } + fmt.Fprintf(&builder, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}, {$ref: '#/components/schemas/%s'}]}\n", i, i-1, older) + } + return openapitest.ComponentSpec(builder.String()) +} diff --git a/compilers/openapi/internal/schema/discriminator_internal_test.go b/compilers/openapi/internal/schema/discriminator_internal_test.go index b3cd23e30..53f9f751f 100644 --- a/compilers/openapi/internal/schema/discriminator_internal_test.go +++ b/compilers/openapi/internal/schema/discriminator_internal_test.go @@ -4,6 +4,8 @@ package schema import ( + "context" + "encoding/json/jsontext" "testing" "github.com/stretchr/testify/assert" @@ -16,6 +18,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/service/servicetest" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" ) func TestPropertyIDByName_NotFound(t *testing.T) { @@ -73,7 +76,8 @@ func TestDiscriminatorMapping_DefsValueNamesItsOwnInternedSibling(t *testing.T) // interned yet: hoisted where it is written, as any mapping to a sub-schema is // (GitHub #530), not at the document-rooted /$defs/cat the value spells, which // this document does not hold (GitHub #557, #910). Each component's tag names -// its own definition, in either declaration order. +// its own definition, a subtype of it, beside the route its own name gives, +// in either declaration order. func TestDiscriminatorMapping_DefsValueNothingInternedIsHoistedAtItsOwnPosition(t *testing.T) { t.Parallel() for name, blocks := range map[string]string{ @@ -91,7 +95,8 @@ func TestDiscriminatorMapping_DefsValueNothingInternedIsHoistedAtItsOwnPosition( require.NotNil(t, model.Discriminator, owner) want := ids.DocumentIDNamespace{}.ForPointer(ids.Ptr("components", "schemas", owner, "$defs", "cat")) - assert.Equal(t, map[string]ir.TypeID{"cat": want}, model.Discriminator.Mapping, owner) + ownerID := ids.DocumentIDNamespace{}.NamedType(ids.Ptr("components", "schemas", owner)) + assert.Equal(t, map[string]ir.TypeID{"cat": want, owner: ownerID}, model.Discriminator.Mapping, owner) _, interned := doc.Types[want] assert.True(t, interned, "%s's definition is interned where it is written", owner) } @@ -99,25 +104,29 @@ func TestDiscriminatorMapping_DefsValueNothingInternedIsHoistedAtItsOwnPosition( } } -// TestBesideUnionDiscriminator_ReportsWhatItCannotSettle pins that a settlement -// whose model is missing, nil or no model is announced rather than skipped: -// the discriminator it was deferred for would otherwise be settled nowhere, -// unremarked. A nil map is no settled one. -func TestBesideUnionDiscriminator_ReportsWhatItCannotSettle(t *testing.T) { +// TestModelRouteSettlement_ReportsWhatItCannotSettle pins that a stored +// discriminator whose model the registry does not hold as the store does, or +// which lost its discriminator, is announced rather than skipped: its routes +// would otherwise be settled nowhere, unremarked. A nil map is no settled one. +func TestModelRouteSettlement_ReportsWhatItCannotSettle(t *testing.T) { t.Parallel() + ghostModel := &ir.Model{ID: "type/ghost"} for name, reg := range map[string]ir.TypeRegistry{ - "model missing": {"type/other": &ir.Model{ID: "type/other"}}, - "no model": {"type/ghost": &ir.Scalar{ID: "type/ghost"}}, - "nil model": {"type/ghost": (*ir.Model)(nil)}, - "nil map": {"type/ghost": (*ir.MapT)(nil)}, + "model missing": {"type/other": &ir.Model{ID: "type/other"}}, + "another model": {"type/ghost": &ir.Model{ID: "type/ghost", Discriminator: &ir.Discriminator{PropertyName: "k"}}}, + "no model": {"type/ghost": &ir.Scalar{ID: "type/ghost"}}, + "nil map": {"type/ghost": (*ir.MapT)(nil)}, + "the discriminator gone": {"type/ghost": ghostModel}, } { t.Run(name, func(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.EmptySpec, service.Policy{}) - besideUnionDiscriminatorValue := besideUnionDiscriminator{c: serviceContext.Ctx, pointer: "/components/schemas/Ghost", model: "type/ghost"} + stored := &storedDiscriminator{loweringContext: serviceContext.Ctx, model: ghostModel, pointer: "/components/schemas/Ghost", + discriminator: &statement.Discriminator{PropertyName: "k"}} - diags := besideUnionDiscriminatorValue.Settle(t.Context(), reg) + diags, asMap := stored.settle(irfacts.New(&ir.Document{Types: reg}), reg, ir.NewAliasChainIndex(reg.Lookup)) + assert.Nil(t, asMap) require.Len(t, diags, 1) assert.Equal(t, diag.InternalInvariant, diags[0].Code) assert.Equal(t, ir.SeverityError, diags[0].Severity) @@ -125,17 +134,57 @@ func TestBesideUnionDiscriminator_ReportsWhatItCannotSettle(t *testing.T) { } } -// TestBesideUnionDiscriminator_LeavesASettledMapAlone pins the second -// settlement for one model: the first moved the discriminator and left a MapT, -// so the second has nothing to settle and reports nothing. -func TestBesideUnionDiscriminator_LeavesASettledMapAlone(t *testing.T) { +// TestModelRouteSettlement_AsksTheContextBetweenModels pins that the run's one +// settlement of model discriminators asks its context before each model, so a +// cancelled run settles none: each model keeps the entry routing to no subtype +// typed, reported nowhere. +func TestModelRouteSettlement_AsksTheContextBetweenModels(t *testing.T) { + t.Parallel() + serviceContext := servicetest.Context(t, openapitest.EmptySpec, service.Policy{}) + reg := ir.TypeRegistry{"type/other": &ir.Model{ID: "type/other"}} + store := &modelDiscriminators{stored: map[ir.TypeID]*storedDiscriminator{}} + for _, id := range []ir.TypeID{"type/a", "type/b"} { + model := &ir.Model{ID: id, Discriminator: &ir.Discriminator{PropertyName: "k", Mapping: map[string]ir.TypeID{"o": "type/other"}}} + reg[id] = model + store.stored[id] = &storedDiscriminator{loweringContext: serviceContext.Ctx, model: model, pointer: "/components/schemas/" + jsontext.Pointer(id), + discriminator: &statement.Discriminator{PropertyName: "k", Mapping: []statement.MappingEntry{{Value: "o", Target: "Other"}}}} + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + assert.Empty(t, modelRouteSettlement{loweringContext: serviceContext.Ctx, store: store}.Settle(ctx, reg, ir.NewAliasChainIndex(reg.Lookup))) + for _, id := range []ir.TypeID{"type/a", "type/b"} { + assert.Equal(t, map[string]ir.TypeID{"o": "type/other"}, reg[id].(*ir.Model).Discriminator.Mapping, "%s is not settled", id) + } +} + +// TestModelDiscriminators_ForgetsOnlyTheNodeItWasHanded pins forget: a model +// a dry run built and discarded drops out of the store, and one that only +// shares its ID, the node the registry holds, stays. +func TestModelDiscriminators_ForgetsOnlyTheNodeItWasHanded(t *testing.T) { + t.Parallel() + held := &ir.Model{ID: "type/pet"} + store := &modelDiscriminators{stored: map[ir.TypeID]*storedDiscriminator{"type/pet": {model: held}}} + store.forget(&ir.Model{ID: "type/pet"}) + assert.Contains(t, store.stored, ir.TypeID("type/pet"), "another node of the ID leaves it held") + store.forget(held) + assert.NotContains(t, store.stored, ir.TypeID("type/pet"), "the node it was handed is forgotten") +} + +// TestModelRouteSettlement_LeavesASettledMapAlone pins a model a settlement +// already swapped for its MapT: nothing is left to settle, and nothing is +// reported. +func TestModelRouteSettlement_LeavesASettledMapAlone(t *testing.T) { t.Parallel() mt := &ir.MapT{ID: "type/pet", Value: ir.TypeRef{Target: "type/primitive/string"}} reg := ir.TypeRegistry{"type/pet": mt} serviceContext := servicetest.Context(t, openapitest.EmptySpec, service.Policy{}) - besideUnionDiscriminatorValue := besideUnionDiscriminator{c: serviceContext.Ctx, pointer: "/components/schemas/Pet", model: "type/pet"} + stored := &storedDiscriminator{loweringContext: serviceContext.Ctx, model: &ir.Model{ID: "type/pet"}, pointer: "/components/schemas/Pet", + discriminator: &statement.Discriminator{PropertyName: "k"}} - assert.Empty(t, besideUnionDiscriminatorValue.Settle(t.Context(), reg)) + diags, asMap := stored.settle(irfacts.New(&ir.Document{Types: reg}), reg, ir.NewAliasChainIndex(reg.Lookup)) + assert.Empty(t, diags) + assert.Nil(t, asMap, "nothing is swapped again") assert.Same(t, mt, reg["type/pet"], "the map is left in place") } @@ -143,9 +192,9 @@ func TestBesideUnionDiscriminator_LeavesASettledMapAlone(t *testing.T) { // in lowerer's document. func petDiscriminator(t *testing.T, lowerer *Lowerer) *statement.Discriminator { t.Helper() - js, ok := lowerer.Doc.Components.GetSchemas().Get("Pet") + jsonSchema, ok := lowerer.Doc.Components.GetSchemas().Get("Pet") require.True(t, ok) - discriminator := (lowerer.Ctx.Statements().Of(js).Schema).Discriminator() + discriminator := (lowerer.Ctx.Statements().Of(jsonSchema).Schema).Discriminator() require.NotNil(t, discriminator) return discriminator } @@ -164,21 +213,21 @@ const defsSiblingMappingSchemas = ` Pet: // defsMappingPet and defsMappingToy each map a tag to a "#/$defs/cat" definition // that nothing else in the schema references, so no oneOf branch has interned -// it when the mapping asks. They spell the same pointer for different -// definitions, GitHub #557's shape. +// it when the mapping asks, each definition a subtype of its owner. They spell +// the same pointer for different definitions, GitHub #557's shape. const ( defsMappingPet = ` Pet: type: object properties: {kind: {type: string}} discriminator: {propertyName: kind, mapping: {cat: "#/$defs/cat"}} $defs: - cat: {type: object, properties: {meow: {type: string}}} + cat: {allOf: [{$ref: '#/components/schemas/Pet'}], type: object, properties: {meow: {type: string}}} ` defsMappingToy = ` Toy: type: object properties: {kind: {type: string}} discriminator: {propertyName: kind, mapping: {cat: "#/$defs/cat"}} $defs: - cat: {type: object, properties: {squeak: {type: string}}} + cat: {allOf: [{$ref: '#/components/schemas/Toy'}], type: object, properties: {squeak: {type: string}}} ` ) diff --git a/compilers/openapi/internal/schema/discriminator_kept_keepers_test.go b/compilers/openapi/internal/schema/discriminator_kept_keepers_test.go new file mode 100644 index 000000000..6d731e3cb --- /dev/null +++ b/compilers/openapi/internal/schema/discriminator_kept_keepers_test.go @@ -0,0 +1,207 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// keeperSpec writes a 3.2 document whose body, the text after its info, holds +// keptDisc wherever it writes D. +func keeperSpec(body string) string { + return "openapi: 3.2.0\ninfo: {title: T, version: \"1\"}\n" + strings.ReplaceAll(body, "D", keptDisc) +} + +// keeperOperation is keeperSpec for one operation's text, at /a. +func keeperOperation(operation string) string { + return keeperSpec("paths:\n /a:\n post:\n responses: {'200': {description: ok}}\n" + operation) +} + +// keeperBody is keeperOperation for a request body of one media type. +func keeperBody(mediaType, content string) string { + return keeperOperation(" requestBody:\n content:\n " + mediaType + ": " + content + "\n") +} + +// keeperCallbacks nests callbacks around a request body schema written as D, +// one level past those the compiler lowers, whose map it keeps verbatim. +func keeperCallbacks() (string, string) { + inner := "{cb: {'{$request.body#/u}': {post: {requestBody: {content: {application/json: {schema: D}}}, " + + "responses: {'200': {description: ok}}}}}}" + entry := "/callbacks/cb/{$request.body#~1u}/post/requestBody/content/application~1json/schema" + for range 4 { + inner = "{cb: {'{$request.body#/u}': {post: {responses: {'200': {description: ok}}, callbacks: " + inner + "}}}}" + entry = "/callbacks/cb/{$request.body#~1u}/post" + entry + } + return keeperOperation(" callbacks: " + inner + "\n"), "/paths/~1a/post" + entry +} + +// TestKeptDiscriminator_ResolvesItsValuesAtEveryOtherKeeper pins GitHub #2006 +// at the keepers TestKeptDiscriminator_ResolvesItsValuesWhereverItIsKept does +// not reach: a keyword kept beside a node with no home for it, union branches +// kept beside a body, an allOf entry kept whole or keeping a validation-only +// keyword, one beside a $ref, a draft's dependencies, and the OpenAPI objects +// an operation keeps verbatim. Each keeps a discriminator whose one value names nothing, reported +// once at its entry. +func TestKeptDiscriminator_ResolvesItsValuesAtEveryOtherKeeper(t *testing.T) { + t.Parallel() + callbacks, callbackEntry := keeperCallbacks() + components := func(schemas string) string { return keeperSpec("paths: {}\ncomponents:\n schemas:\n" + schemas) } + sites := []keptSite{ + {"a keyword beside a node with no home for it", components(" S: {type: string, properties: {p: D}}\n"), + "/components/schemas/S/properties/p"}, + {"union branches kept beside a body", components(" S: {type: string, oneOf: [D, {type: integer}]}\n"), + "/components/schemas/S/oneOf/0"}, + {"union branches kept as validation-only", + components(" S: {type: object, properties: {a: {type: string}}, anyOf: [{required: [a]}, {not: D}]}\n"), + "/components/schemas/S/anyOf/1/not"}, + {"an allOf entry kept whole", components(" S: {allOf: [{type: string}, {type: integer, properties: {x: D}}]}\n"), + "/components/schemas/S/allOf/1/properties/x"}, + {"an allOf entry kept whole for a closure it does not type", + components(" S: {allOf: [{type: object, properties: {a: {type: string}}}, {additionalProperties: false, propertyNames: D}]}\n"), + "/components/schemas/S/allOf/1/propertyNames"}, + {"an allOf entry's validation-only keyword kept apart", + components(" S: {allOf: [{type: string, not: D}], not: {type: integer}}\n"), "/components/schemas/S/allOf/0/not"}, + {"a validation-only keyword beside a $ref", + components(" X: {type: object}\n S: {$ref: '#/components/schemas/X', not: D}\n"), "/components/schemas/S/not"}, + {"a validation-only keyword an allOf entry writes", + components(" S: {allOf: [{type: object, properties: {p: {type: string}}, not: D}, {type: object}]}\n"), + "/components/schemas/S/allOf/0/not"}, + {"a draft's dependencies", + components(" S: {$schema: 'http://json-schema.org/draft-07/schema#', type: object, dependencies: {p: D}}\n"), + "/components/schemas/S/dependencies/p"}, + {"an Encoding Object's headers where they take no effect", + keeperBody("application/x-www-form-urlencoded", + "{schema: {type: object, properties: {doc: {type: string}}}, encoding: {doc: {headers: {X: {schema: D}}}}}"), + "/paths/~1a/post/requestBody/content/application~1x-www-form-urlencoded/encoding/doc/headers/X/schema"}, + {"an encoding entry naming no part", + keeperBody("multipart/form-data", "{schema: {type: object, properties: {doc: {type: string}}}, encoding: {nope: {headers: {X: {schema: D}}}}}"), + "/paths/~1a/post/requestBody/content/multipart~1form-data/encoding/nope/headers/X/schema"}, + {"an itemEncoding where it takes no effect", + keeperBody("application/jsonl", "{itemSchema: {type: object}, itemEncoding: {headers: {X: {schema: D}}}}"), + "/paths/~1a/post/requestBody/content/application~1jsonl/itemEncoding/headers/X/schema"}, + {"an itemEncoding beside a prefixEncoding", + keeperBody("multipart/mixed", "{schema: {type: array, prefixItems: [{type: string}]}, prefixEncoding: [{contentType: text/plain}], "+ + "itemEncoding: {headers: {X: {schema: D}}}}"), + "/paths/~1a/post/requestBody/content/multipart~1mixed/itemEncoding/headers/X/schema"}, + {"the parameters of a path item mounting no operation", keeperSpec("paths:\n /a:\n parameters: [{name: q, in: query, schema: D}]\n"), + "/paths/~1a/parameters/0/schema"}, + {"a parameter's schema beside its content", + keeperOperation(" parameters: [{name: q, in: query, schema: D, content: {application/json: {schema: {type: string}}}}]\n"), + "/paths/~1a/post/parameters/0/schema"}, + {"a parameter's media type not chosen", + keeperOperation(" parameters: [{name: q, in: query, content: {application/json: {schema: {type: string}}, text/plain: {schema: D}}}]\n"), + "/paths/~1a/post/parameters/0/content/text~1plain/schema"}, + {"a parameter's content entry's itemSchema", + keeperOperation(" parameters: [{name: q, in: query, content: {application/json: {schema: {type: string}, itemSchema: D}}}]\n"), + "/paths/~1a/post/parameters/0/content/application~1json/itemSchema"}, + {"callbacks nested past those lowered", callbacks, callbackEntry}, + } + for _, site := range sites { + t.Run(site.name, func(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, site.spec) + entry := site.entry + "/discriminator/mapping/a" + assert.Len(t, diagsAtPointer(diags, diag.UnresolvedRef, entry), 1, "reported once at its entry: %v", reported(diags)) + }) + } +} + +// TestKeptDiscriminator_AValueALoweringReadsTooIsReportedOnce pins a +// discriminator two readers read: an allOf entry kept whole for the +// unevaluatedProperties it writes holds a property the model folds from it, +// whose discriminator its node holds. The entry records the route it holds, +// and a value naming nothing is reported once. +func TestKeptDiscriminator_AValueALoweringReadsTooIsReportedOnce(t *testing.T) { + t.Parallel() + routed := "{type: object, discriminator: {propertyName: k, mapping: {a: '#/components/schemas/Nope', x: '#/components/schemas/X'}}}" + doc, diags := parseFull(t, keeperSpec("paths: {}\ncomponents:\n schemas:\n X: {type: object}\n"+ + " S: {allOf: [{type: object, properties: {a: {type: string}}}, {unevaluatedProperties: false, properties: {p: "+routed+"}}]}\n")) + kept := typeByName(doc, "S").Common().Unmodeled["openapi:allOf/1"] + require.Contains(t, string(kept.Value), "Nope", "the entry is kept whole") + assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/properties/p/discriminator/mapping/x": componentID("X")}, kept.Targets) + assert.Len(t, diagsAtPointer(diags, diag.UnresolvedRef, "/components/schemas/S/allOf/1/properties/p/discriminator/mapping/a"), 1, + "%v", reported(diags)) +} + +// TestKeptDiscriminator_RoutesAValueWhereNoModelHoldsTheSchema pins a +// discriminator kept beneath an Encoding Object a 3.2 one nests, which no +// model holds, read as the binding reads it: a value naming a component routes +// to it, one naming a $defs member only it reaches has that member lowered, +// and both are recorded on the kept entry. +func TestKeptDiscriminator_RoutesAValueWhereNoModelHoldsTheSchema(t *testing.T) { + t.Parallel() + routed := "{type: object, discriminator: {propertyName: k, mapping: {x: X, s: '#/components/schemas/H/$defs/S'}}}" + doc, diags := parseFull(t, keeperBody("multipart/form-data", + "{schema: {type: object, properties: {doc: {type: object, properties: {inner: {type: string}}}}}, "+ + "encoding: {doc: {encoding: {inner: {headers: {X-Inner: {schema: "+routed+"}}}}}}}")+ + "components:\n schemas:\n X: {type: object}\n H: {type: string, $defs: {S: {type: object, properties: {s: {type: string}}}}}\n") + assert.Empty(t, withCode(diags, diag.UnresolvedRef)) + kept := doc.Services[0].Groups[0].Operations[0].Request.Contents[0].Unmodeled["openapi:encoding/doc/encoding"] + assert.Equal(t, map[jsontext.Pointer]ir.TypeID{ + "/inner/headers/X-Inner/schema/discriminator/mapping/x": componentID("X"), + "/inner/headers/X-Inner/schema/discriminator/mapping/s": "type/anonymous/components/schemas/H/$defs/S", + }, kept.Targets) +} + +// TestKeptDiscriminator_RoutesAValueOfANodeBuiltOnceLoweringReturned pins the +// promise a kept value makes while the registry builds what a $ref promised: a +// $defs member only a $ref reaches is built once every lowering has returned, +// and a discriminator its `not` keeps routes to another member only it +// reaches, which is promised and built then. +func TestKeptDiscriminator_RoutesAValueOfANodeBuiltOnceLoweringReturned(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, keeperSpec("paths: {}\ncomponents:\n schemas:\n"+ + " S:\n type: object\n properties: {p: {$ref: '#/components/schemas/S/$defs/A'}}\n"+ + " $defs:\n A: {type: object, not: {discriminator: {propertyName: k, mapping: {b: '#/components/schemas/S/$defs/B'}}}}\n"+ + " B: {type: object, properties: {b: {type: string}}}\n")) + assert.Empty(t, withCode(diags, diag.UnresolvedRef)) + a := doc.Types["type/anonymous/components/schemas/S/$defs/A"] + require.NotNil(t, a, "the $ref builds its target") + assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/discriminator/mapping/b": "type/anonymous/components/schemas/S/$defs/B"}, + a.Common().Unmodeled["openapi:not"].Targets) + assert.Contains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/S/$defs/B"), "the value's target is built") +} + +// TestKeptDiscriminator_AValueWhoseChainBreaksRoutesNowhere pins a kept +// value naming a component whose $ref lands on nothing: the value routes +// nowhere and is recorded on no entry, and only the failing $ref is reported, +// where it is written. +func TestKeptDiscriminator_AValueWhoseChainBreaksRoutesNowhere(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, keeperSpec("paths: {}\ncomponents:\n schemas:\n"+ + " Broken: {$ref: '#/components/schemas/Nope'}\n"+ + " S: {type: object, not: {discriminator: {propertyName: k, mapping: {b: '#/components/schemas/Broken'}}}}\n")) + kept := typeByName(doc, "S").Common().Unmodeled["openapi:not"] + require.Contains(t, string(kept.Value), "Broken") + assert.Empty(t, kept.Targets, "a broken chain names no type") + unresolved := withCode(diags, diag.UnresolvedRef) + at := make([]string, 0, len(unresolved)) + for _, diagnostic := range unresolved { + at = append(at, string(diagnostic.Provenance.Pointer)) + } + assert.Equal(t, []string{"/components/schemas/Broken"}, at) +} + +// TestKeepDiscriminatorWhole_KeepsNothingOfASchemaWritingNone pins the +// function's guard: a schema writing no discriminator keeps nothing, drops +// nothing and reports nothing. +func TestKeepDiscriminatorWhole_KeepsNothingOfASchemaWritingNone(t *testing.T) { + t.Parallel() + lowerer, _ := schema.LoweredFor(t, keeperSpec("paths: {}\ncomponents:\n schemas:\n S: {type: object, x-a: 1}\n")) + at := reftable.DocumentPointer{Doc: reftable.Source, Pointer: "/components/schemas/S"} + unmodeled := ir.Unmodeled{"openapi:discriminator/x-a": {Value: ir.RawValue("1"), + Provenance: ir.Provenance{Pointer: "/components/schemas/S/discriminator/x-a"}}} + assert.Empty(t, schema.KeepDiscriminator(lowerer.Ctx, &unmodeled, lowerer.Ctx.Statements().At(at).Discriminator(), at.Pointer)) + assert.Contains(t, unmodeled, "openapi:discriminator/x-a") +} diff --git a/compilers/openapi/internal/schema/discriminator_kept_sites_test.go b/compilers/openapi/internal/schema/discriminator_kept_sites_test.go new file mode 100644 index 000000000..914faa23c --- /dev/null +++ b/compilers/openapi/internal/schema/discriminator_kept_sites_test.go @@ -0,0 +1,150 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" +) + +// keptDisc is a schema writing a discriminator whose one mapping value names +// nothing. +const keptDisc = "{type: object, discriminator: {propertyName: k, mapping: {a: '#/components/schemas/Nope'}}}" + +// keptSite is a position that keeps a schema, or an object holding one, +// verbatim: the document writing keptDisc there, and the pointer of its +// mapping entry. +type keptSite struct { + name, spec, entry string +} + +// keptSchemaSite writes keptDisc at the keyword of the component Kept, a +// schema of the given type, as the keyword's value spelled by wrap. +func keptSchemaSite(name, version, kind, keyword, wrap, at string) keptSite { + spec := "openapi: " + version + "\ninfo: {title: T, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n" + + " Kept: {type: " + kind + ", " + keyword + ": " + strings.ReplaceAll(wrap, "D", keptDisc) + "}\n" + return keptSite{name, spec, "/components/schemas/Kept/" + at + "/discriminator/mapping/a"} +} + +// keptDraft07Site is keptSchemaSite at 3.1.0 with Kept's $schema naming JSON +// Schema draft-07, a dialect defining keywords 2020-12 does not. +func keptDraft07Site(name, keyword, wrap, at string) keptSite { + site := keptSchemaSite(name, "3.1.0", "object", keyword, wrap, at) + site.spec = strings.Replace(site.spec, "Kept: {", "Kept: {$schema: 'http://json-schema.org/draft-07/schema#', ", 1) + return site +} + +// keptComponentSite declares an unreferenced component of section holding +// keptDisc as its schema, written by body. +func keptComponentSite(section, body, at string) keptSite { + spec := "openapi: 3.1.0\ninfo: {title: T, version: \"1\"}\npaths: {}\ncomponents:\n " + section + ":\n" + + " Unused: " + strings.ReplaceAll(body, "D", keptDisc) + "\n" + return keptSite{"an unreferenced " + section + " component", spec, + "/components/" + section + "/Unused/" + at + "/discriminator/mapping/a"} +} + +// keptEncodingSite writes keptDisc as a header schema under the 3.2 Media Type +// Object's content, at the encoding path given. +func keptEncodingSite(name, mediaType, content, at string) keptSite { + spec := "openapi: 3.2.0\ninfo: {title: T, version: \"1\"}\npaths:\n /a:\n post:\n requestBody:\n" + + " content:\n " + mediaType + ": " + strings.ReplaceAll(content, "D", keptDisc) + "\n" + + " responses: {'200': {description: ok}}\n" + return keptSite{name, spec, "/paths/~1a/post/requestBody/content/" + strings.ReplaceAll(mediaType, "/", "~1") + + "/" + at + "/discriminator/mapping/a"} +} + +var keptSites = []keptSite{ + keptSchemaSite("not", "3.1.0", "object", "not", "D", "not"), + keptSchemaSite("not at 3.0", "3.0.3", "object", "not", "D", "not"), + keptSchemaSite("not at 3.2", "3.2.0", "object", "not", "D", "not"), + keptSchemaSite("if", "3.1.0", "object", "if", "D", "if"), + keptSchemaSite("then", "3.1.0", "object", "then", "D", "then"), + keptSchemaSite("else", "3.1.0", "object", "else", "D", "else"), + keptSchemaSite("dependentSchemas", "3.1.0", "object", "dependentSchemas", "{p: D}", "dependentSchemas/p"), + keptSchemaSite("contains", "3.1.0", "array", "contains", "D", "contains"), + keptSchemaSite("propertyNames", "3.1.0", "object", "propertyNames", "D", "propertyNames"), + keptSchemaSite("unevaluatedProperties", "3.1.0", "object", "unevaluatedProperties", "D", "unevaluatedProperties"), + keptSchemaSite("unevaluatedItems", "3.1.0", "array", "unevaluatedItems", "D", "unevaluatedItems"), + keptDraft07Site("dependencies at draft-07", "dependencies", "{p: D}", "dependencies/p"), + keptComponentSite("headers", "{schema: D}", "schema"), + keptComponentSite("parameters", "{name: q, in: query, schema: D}", "schema"), + keptComponentSite("requestBodies", "{content: {application/json: {schema: D}}}", "content/application~1json/schema"), + keptComponentSite("responses", "{description: d, content: {application/json: {schema: D}}}", "content/application~1json/schema"), + keptComponentSite("pathItems", "{get: {responses: {'200': {description: ok, content: {application/json: {schema: D}}}}}}", + "get/responses/200/content/application~1json/schema"), + keptEncodingSite("a nested Encoding Object's encoding", "multipart/form-data", + "{schema: {type: object, properties: {doc: {type: object, properties: {inner: {type: string}}}}}, "+ + "encoding: {doc: {encoding: {inner: {headers: {X-Inner: {schema: D}}}}}}}", + "encoding/doc/encoding/inner/headers/X-Inner/schema"), + keptEncodingSite("an Encoding Object's itemEncoding", "multipart/form-data", + "{schema: {type: object, properties: {doc: {type: array, items: {type: string}}}}, "+ + "encoding: {doc: {itemEncoding: {headers: {X-Inner: {schema: D}}}}}}", + "encoding/doc/itemEncoding/headers/X-Inner/schema"), + keptEncodingSite("an Encoding Object's prefixEncoding", "multipart/form-data", + "{schema: {type: object, properties: {doc: {type: array, prefixItems: [{type: string}]}}}, "+ + "encoding: {doc: {prefixEncoding: [{headers: {X-Inner: {schema: D}}}]}}}", + "encoding/doc/prefixEncoding/0/headers/X-Inner/schema"), + keptEncodingSite("a Media Type Object's itemEncoding", "multipart/mixed", + "{schema: {type: array, items: {type: string}}, itemEncoding: {headers: {X-Inner: {schema: D}}}}", + "itemEncoding/headers/X-Inner/schema"), + keptEncodingSite("a Media Type Object's prefixEncoding", "multipart/mixed", + "{schema: {type: array, prefixItems: [{type: string}]}, prefixEncoding: [{headers: {X-Inner: {schema: D}}}]}", + "prefixEncoding/0/headers/X-Inner/schema"), +} + +// TestKeptDiscriminator_ResolvesItsValuesWhereverItIsKept pins GitHub #2006: +// a discriminator kept verbatim inside a schema or an object kept whole has +// each mapping value read as the reference it is, a value naming nothing +// reported once as an unresolved reference at its entry, at every site that +// keeps one, as where its schema is lowered (a Media Type Object's +// itemEncoding here). +func TestKeptDiscriminator_ResolvesItsValuesWhereverItIsKept(t *testing.T) { + t.Parallel() + for _, site := range keptSites { + t.Run(site.name, func(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, site.spec) + assert.Len(t, diagsAtPointer(diags, diag.UnresolvedRef, site.entry), 1, "reported once at its entry: %v", reported(diags)) + }) + } +} + +// TestKeptDiscriminator_ReadsNoValueUnderAKeywordTheDialectLacks pins the +// other side of the draft-07 row above: 2020-12 defines no dependencies, so +// nothing under it is a schema, and a discriminator written there, within a +// not kept whole, has no value read as a reference. Under draft-07 the same +// value is read. +func TestKeptDiscriminator_ReadsNoValueUnderAKeywordTheDialectLacks(t *testing.T) { + t.Parallel() + for _, c := range []struct { + site keptSite + want int + }{ + {keptSchemaSite("2020-12", "3.1.0", "object", "not", "{dependencies: {p: D}}", "not/dependencies/p"), 0}, + {keptDraft07Site("draft-07", "not", "{dependencies: {p: D}}", "not/dependencies/p"), 1}, + } { + t.Run(c.site.name, func(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, c.site.spec) + assert.Len(t, diagsAtPointer(diags, diag.UnresolvedRef, c.site.entry), c.want, "%v", reported(diags)) + }) + } +} + +// TestKeptDiscriminator_ACollapsedUnionKeepsItsExtensionOnce is GitHub +// #2102's own document: a union collapsing to a nullable reference keeps its +// discriminator whole, the extension within it and under no key of its own. +func TestKeptDiscriminator_ACollapsedUnionKeepsItsExtensionOnce(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, "openapi: 3.1.0\ninfo: {title: t, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n"+ + " X: {type: object, properties: {k: {type: string}}}\n"+ + " Flat: {oneOf: [{$ref: '#/components/schemas/X'}, {type: \"null\"}], discriminator: {propertyName: k, x-b: 5}}\n") + kept := typeByName(doc, "Flat").Common().Unmodeled + assert.Contains(t, string(kept["openapi:discriminator"].Value), `"x-b":5`) + assert.NotContains(t, kept, "openapi:discriminator/x-b") +} diff --git a/compilers/openapi/internal/schema/discriminator_mapping_test.go b/compilers/openapi/internal/schema/discriminator_mapping_test.go index 1a821bff1..77089f5e1 100644 --- a/compilers/openapi/internal/schema/discriminator_mapping_test.go +++ b/compilers/openapi/internal/schema/discriminator_mapping_test.go @@ -4,6 +4,7 @@ package schema_test import ( + "encoding/json/jsontext" "fmt" "maps" "path/filepath" @@ -128,30 +129,30 @@ func TestDiscriminatorMapping_InlineTargetResolvesInEitherOrder(t *testing.T) { "type/anonymous" + pathsBase, "type/anonymous" + pathsTarget, false}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - first, diags := parseFull(t, tc.spec(tc.base+tc.owner)) + first, diags := parseFull(t, testCase.spec(testCase.base+testCase.owner)) openapitest.RequireNoErrorDiags(t, diags) - last, diags := parseFull(t, tc.spec(tc.owner+tc.base)) + last, diags := parseFull(t, testCase.spec(testCase.owner+testCase.base)) openapitest.RequireNoErrorDiags(t, diags) for _, doc := range []*ir.Document{first, last} { - base, ok := doc.Types[tc.baseID].(*ir.Model) + base, ok := doc.Types[testCase.baseID].(*ir.Model) require.True(t, ok, "the discriminator base is a model") require.NotNil(t, base.Discriminator) - subtype, ok := doc.Types[tc.targetID].(*ir.Model) + subtype, ok := doc.Types[testCase.targetID].(*ir.Model) require.True(t, ok, "the mapping target is a model") - if tc.wantDefault { - assert.Equal(t, tc.targetID, base.Discriminator.Default) + if testCase.wantDefault { + assert.Equal(t, testCase.targetID, base.Discriminator.Default) // defaultMapping is the fallback for a tag the mapping does not // recognize, so it names no tag for its target, and an inline // subtype has no name to imply one (GitHub #517). assert.Empty(t, subtype.DiscriminatorValue) } else { - assert.Equal(t, tc.targetID, base.Discriminator.Mapping["woofer"]) + assert.Equal(t, testCase.targetID, base.Discriminator.Mapping["woofer"]) assert.Equal(t, "woofer", subtype.DiscriminatorValue) } } @@ -172,6 +173,7 @@ func TestDiscriminatorMapping_InlineTargetResolvesInEitherOrder(t *testing.T) { // variant written there does. A component is a declaration of its own and // keeps its own node. Each row is compiled base-first and reversed: both must // map each tag to the same type, with nothing reported, pass.Validate included. +// A model base routes itself by its own name beside. func TestDiscriminatorMapping_ToAPureRefNamesItsTarget(t *testing.T) { t.Parallel() const subtype = "{allOf: [{$ref: '#/components/schemas/Pet'}], type: object, properties: {woof: {type: string}}}" @@ -189,7 +191,7 @@ func TestDiscriminatorMapping_ToAPureRefNamesItsTarget(t *testing.T) { name: "a model base's mapping to a property", base: fmt.Sprintf(pet, "woofer: '#/components/schemas/Kennel/properties/Dog'"), owner: " Dog: " + subtype + "\n Kennel: {type: object, properties: {Dog: {$ref: '#/components/schemas/Dog'}}}\n", - want: map[string]ir.TypeID{"woofer": componentID("Dog")}, + want: map[string]ir.TypeID{"woofer": componentID("Dog"), "Pet": componentID("Pet")}, }, { name: "a union's mapping to its branches", @@ -205,7 +207,7 @@ func TestDiscriminatorMapping_ToAPureRefNamesItsTarget(t *testing.T) { owner: " Dog: " + subtype + "\n Kennel:\n type: object\n properties:\n" + " a: {$ref: '#/components/schemas/Kennel/properties/b'}\n" + " b: {$ref: '#/components/schemas/Dog'}\n", - want: map[string]ir.TypeID{"woofer": componentID("Dog")}, + want: map[string]ir.TypeID{"woofer": componentID("Dog"), "Pet": componentID("Pet")}, }, { name: "a union branch naming a component alias", @@ -233,74 +235,69 @@ func TestDiscriminatorMapping_ToAPureRefNamesItsTarget(t *testing.T) { assert.Empty(t, cmp.Diff(first, last, orderInvariantIR()...)) for _, doc := range []*ir.Document{first, last} { assert.Equal(t, c.want, discriminatorOf(t, doc, componentID("Pet")).Mapping) - assert.Empty(t, validated(t, doc), "every target is a variant") + assert.Empty(t, routeFindings(t, doc), "every target is a variant") } }) } } -// TestDiscriminatorMapping_ChainOfPositionsDeeperThanCap pins the chain's -// bound as behaviour rather than as a comment, as -// TestAllOf_DiscriminatorValueChainDeeperThanCap does for the ancestor walk. A -// chain of $ref positions, or of components, longer than the bound that is no -// cycle stops at the position the bound reached, so the mapping names what is -// declared there. The chain exactly the bound long is the control: it reads -// through to Dog, and tags it. +// TestDiscriminatorMapping_ChainOfPositionsDeeperThanCap pins that a chain of +// $ref positions, or of components, the bindings resolve is read to its end +// however long: one longer than the bound on a chain they resolve no end for +// reads through to Dog, and tags it, as one exactly the bound long does. func TestDiscriminatorMapping_ChainOfPositionsDeeperThanCap(t *testing.T) { t.Parallel() - const hopCap = schema.MaxChainHops - // Each kind writes a chain of links $refs from its first position, which - // first names, to Dog, and names its i-th position. + const hopCap = schema.MaxRefHops + // Each kind writes a chain of hops $refs from its first position, which + // first names, to Dog. kinds := []struct { name, first string - chain func(links int) string - at func(i int) ir.TypeID + chain func(hops int) string }{ - {"positions", "'#/components/schemas/Kennel/properties/a0'", func(links int) string { + {"positions", "'#/components/schemas/Kennel/properties/a0'", func(hops int) string { var kennel strings.Builder kennel.WriteString(" Kennel:\n type: object\n properties:\n") - for i := range links - 1 { + for i := range hops - 1 { fmt.Fprintf(&kennel, " a%d: {$ref: '#/components/schemas/Kennel/properties/a%d'}\n", i, i+1) } - fmt.Fprintf(&kennel, " a%d: {$ref: '#/components/schemas/Dog'}\n", links-1) + fmt.Fprintf(&kennel, " a%d: {$ref: '#/components/schemas/Dog'}\n", hops-1) return kennel.String() - }, func(i int) ir.TypeID { - return ir.TypeID(fmt.Sprintf("type/anonymous/components/schemas/Kennel/properties/a%d", i)) }}, - {"components", "C0", func(links int) string { + {"components", "C0", func(hops int) string { var chain strings.Builder - for i := range links - 1 { + for i := range hops - 1 { fmt.Fprintf(&chain, " C%d: {$ref: '#/components/schemas/C%d'}\n", i, i+1) } - fmt.Fprintf(&chain, " C%d: {$ref: '#/components/schemas/Dog'}\n", links-1) + fmt.Fprintf(&chain, " C%d: {$ref: '#/components/schemas/Dog'}\n", hops-1) return chain.String() - }, func(i int) ir.TypeID { return componentID(fmt.Sprintf("C%d", i)) }}, + }}, } for _, kind := range kinds { - for _, tc := range []struct { - name string - links int - want ir.TypeID - tag string + for _, testCase := range []struct { + name string + hops int + want ir.TypeID + tag string }{ {"as long as the cap", hopCap, componentID("Dog"), "woofer"}, - {"beyond the cap", hopCap + 1, kind.at(hopCap), "Dog"}, + {"beyond the cap", hopCap + 1, componentID("Dog"), "woofer"}, } { - t.Run(kind.name+"/"+tc.name, func(t *testing.T) { + t.Run(kind.name+"/"+testCase.name, func(t *testing.T) { t.Parallel() spec := " Pet:\n type: object\n required: [kind]\n properties: {kind: {type: string}}\n" + " discriminator: {propertyName: kind, mapping: {woofer: " + kind.first + "}}\n" + " Dog: {allOf: [{$ref: '#/components/schemas/Pet'}], type: object, properties: {woof: {type: string}}}\n" + - kind.chain(tc.links) + kind.chain(testCase.hops) doc, diags := parseFull(t, openapitest.ComponentSpec(spec)) openapitest.RequireNoErrorDiags(t, diags) - assert.Equal(t, map[string]ir.TypeID{"woofer": tc.want}, discriminatorOf(t, doc, componentID("Pet")).Mapping, - "the first is %d $refs above Dog", tc.links) + mapping := discriminatorOf(t, doc, componentID("Pet")).Mapping + assert.Equal(t, testCase.want, mapping["woofer"], "the first is %d $refs above Dog", testCase.hops) + assert.Equal(t, componentID("Pet"), mapping["Pet"], "the base routes itself by its name") dog, ok := doc.Types[componentID("Dog")].(*ir.Model) require.True(t, ok) - assert.Equal(t, tc.tag, dog.DiscriminatorValue, "a key, or Dog's name where none reaches it") + assert.Equal(t, testCase.tag, dog.DiscriminatorValue, "a key, or Dog's name where none reaches it") }) } } @@ -327,6 +324,9 @@ func TestDiscriminatorMapping_ABrokenChainDrawsOnlyItsRefsError(t *testing.T) { " discriminator: {propertyName: k, mapping: {" + mapping + "}}\n" } top := map[string]ir.TypeID{"a": "type/primitive/any"} + // A model's entry is left out, and B routes itself and C, which composes + // it, by their names. + ownAndC := map[string]ir.TypeID{"B": componentID("B"), "C": componentID("C")} tests := []struct { name, version, owner string blocks []string @@ -349,18 +349,18 @@ func TestDiscriminatorMapping_ABrokenChainDrawsOnlyItsRefsError(t *testing.T) { " B:\n type: object\n properties: {k: {type: string}}\n" + " discriminator: {propertyName: k, mapping: {a: '#/components/schemas/C/allOf/0'}}\n", " C: {allOf: [" + ref("/components/schemas/C/allOf/0") + ", " + ref("/components/schemas/B") + "]}\n", - }, []string{"error openapi/cyclic-ref /components/schemas/C/allOf/0"}, map[string]ir.TypeID{}}, + }, []string{"error openapi/cyclic-ref /components/schemas/C/allOf/0"}, ownAndC}, {"what only the mapping reaches", "3.1.0", "B", []string{ model("a: '#/components/schemas/B/$defs/Broken', b: '#/components/schemas/C/allOf/0'"), " C: {allOf: [" + ref("/components/schemas/Ghost2") + ", " + ref("/components/schemas/B") + "]}\n", }, []string{"error openapi/unresolved-ref /components/schemas/B/$defs/Broken", - "error openapi/unresolved-ref /components/schemas/C/allOf/0"}, map[string]ir.TypeID{}}, + "error openapi/unresolved-ref /components/schemas/C/allOf/0"}, ownAndC}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() for _, reversed := range []bool{false, true} { - doc, diags := parseFull(t, rawSpec(tc.version, tc.blocks, "", reversed)) + doc, diags := parseFull(t, rawSpec(testCase.version, testCase.blocks, "", reversed)) var got []string for _, diagnostic := range append(diags, validated(t, doc)...) { if diagnostic.Severity == ir.SeverityError { @@ -368,8 +368,8 @@ func TestDiscriminatorMapping_ABrokenChainDrawsOnlyItsRefsError(t *testing.T) { } } slices.Sort(got) - assert.Equal(t, tc.want, got, "reversed %t", reversed) - discriminator := discriminatorOf(t, doc, componentID(tc.owner)) + assert.Equal(t, testCase.want, got, "reversed %t", reversed) + discriminator := discriminatorOf(t, doc, componentID(testCase.owner)) routes := maps.Clone(discriminator.Mapping) if routes == nil { routes = map[string]ir.TypeID{} @@ -377,7 +377,7 @@ func TestDiscriminatorMapping_ABrokenChainDrawsOnlyItsRefsError(t *testing.T) { if discriminator.Default != "" { routes["default"] = discriminator.Default } - assert.Equal(t, tc.routes, routes, "reversed %t", reversed) + assert.Equal(t, testCase.routes, routes, "reversed %t", reversed) } }) } @@ -416,7 +416,8 @@ func TestDiscriminatorMapping_ThroughARefNamingTheSourceByItsFileName(t *testing doc, diags := parseFull(t, openapitest.ComponentSpec(pet(mapping))+lib) openapitest.RequireNoErrorDiags(t, diags) got := discriminatorOf(t, doc, componentID("Pet")).Mapping - assert.Equal(t, map[string]ir.TypeID{"cat": "type/anonymous/x-lib/Cat", "alias": "type/anonymous/x-lib/Cat"}, got, mapping) + assert.Equal(t, map[string]ir.TypeID{"cat": "type/anonymous/x-lib/Cat", "alias": "type/anonymous/x-lib/Cat", + "Pet": componentID("Pet")}, got, mapping) } } @@ -546,16 +547,16 @@ func TestDiscriminatorMapping_NamesTheVariantNamingThePosition(t *testing.T) { variant: componentID("Cat"), }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - version := tc.version + version := testCase.version if version == "" { version = "3.1.0" } - first, diags := parseFull(t, rawSpec(version, tc.components, tc.tail, false)) + first, diags := parseFull(t, rawSpec(version, testCase.components, testCase.tail, false)) openapitest.RequireNoErrorDiags(t, diags) - last, diags := parseFull(t, rawSpec(version, tc.components, tc.tail, true)) + last, diags := parseFull(t, rawSpec(version, testCase.components, testCase.tail, true)) openapitest.RequireNoErrorDiags(t, diags) for _, doc := range []*ir.Document{first, last} { @@ -563,13 +564,13 @@ func TestDiscriminatorMapping_NamesTheVariantNamingThePosition(t *testing.T) { require.True(t, ok, "Pet is a union") require.Len(t, pet.Variants, 1) require.NotNil(t, pet.Discriminator) - assert.Equal(t, tc.variant, pet.Variants[0].Type.Target) + assert.Equal(t, testCase.variant, pet.Variants[0].Type.Target) got := pet.Discriminator.Mapping["c"] - if tc.isDefault { + if testCase.isDefault { got = pet.Discriminator.Default } assert.Equal(t, pet.Variants[0].Type.Target, got, "the mapping names what the variant names") - assert.Empty(t, validated(t, doc), "every target is a variant") + assert.Empty(t, routeFindings(t, doc), "every target is a variant") } assert.Empty(t, cmp.Diff(first.Types, last.Types), "declaring the union before or after what its variant names must not change the registry") @@ -582,6 +583,8 @@ func TestDiscriminatorMapping_NamesTheVariantNamingThePosition(t *testing.T) { // mapping entry and a defaultMapping alike. The targets sit under not and if, // which no declaration lowers, so the hoist is the only lowering that sees the // format each declares beside a model: dropping its findings would lose them. +// Neither target is a subtype, so each route is kept verbatim on Pet, naming +// the type it lowered to. func TestDiscriminatorMapping_HoistedTargetKeepsItsDiagnostics(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.2.0", ` Pet: @@ -603,8 +606,8 @@ func TestDiscriminatorMapping_HoistedTargetKeepsItsDiagnostics(t *testing.T) { pet, ok := doc.Types[componentID("Pet")].(*ir.Model) require.True(t, ok, "Pet is a model") require.NotNil(t, pet.Discriminator) - assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Kennel/not"), pet.Discriminator.Mapping["n"]) - assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Kennel/if"), pet.Discriminator.Default) + assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Kennel/not"), keptRoute(t, pet, "n")) + assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Kennel/if"), keptRoute(t, pet, "")) for _, pointer := range []string{"/components/schemas/Kennel/not", "/components/schemas/Kennel/if"} { assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, pointer), @@ -687,7 +690,8 @@ func TestDiscriminatorMapping_ToRawTargetsIsOrderInvariant(t *testing.T) { " - {type: object, properties: {wingspan: {type: number}}}\n", }, // A member that is an object is lowered to a literal, which no model - // subtypes, so only the resolution is pinned here, not a variant. + // subtypes, so its route is kept verbatim on Pet, naming the type + // the resolution gives. wants: []wantMapping{{pet, "e", anonymous("components/schemas/Kennel/properties/e/enum/0"), ir.KindLiteral}}, }, { @@ -720,20 +724,20 @@ func TestDiscriminatorMapping_ToRawTargetsIsOrderInvariant(t *testing.T) { }, }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - version := tc.version + version := testCase.version if version == "" { version = "3.1.0" } - first, diags := parseFull(t, rawSpec(version, tc.components, tc.tail, false)) + first, diags := parseFull(t, rawSpec(version, testCase.components, testCase.tail, false)) openapitest.RequireNoErrorDiags(t, diags) - last, diags := parseFull(t, rawSpec(version, tc.components, tc.tail, true)) + last, diags := parseFull(t, rawSpec(version, testCase.components, testCase.tail, true)) openapitest.RequireNoErrorDiags(t, diags) for _, doc := range []*ir.Document{first, last} { - for _, want := range tc.wants { + for _, want := range testCase.wants { base, ok := doc.Types[want.base].(*ir.Model) require.True(t, ok, "%s is a model", want.base) require.NotNil(t, base.Discriminator, "%s is discriminated", want.base) @@ -742,6 +746,9 @@ func TestDiscriminatorMapping_ToRawTargetsIsOrderInvariant(t *testing.T) { if want.tag != "" { got = base.Discriminator.Mapping[want.tag] } + if want.kind != ir.KindModel { + got = keptRoute(t, base, want.tag) + } assert.Equal(t, want.target, got, "%s %q", want.base, want.tag) target, ok := doc.Types[want.target] @@ -756,6 +763,21 @@ func TestDiscriminatorMapping_ToRawTargetsIsOrderInvariant(t *testing.T) { } } +// keptRoute returns the type the route of base's discriminator keyed tag, or +// its defaultMapping for "", names, where the route is kept verbatim as it +// reaches no subtype. +func keptRoute(t *testing.T, base *ir.Model, tag string) ir.TypeID { + t.Helper() + if tag == "" { + entry, ok := base.Unmodeled["openapi:discriminator/defaultMapping"] + require.True(t, ok, "the defaultMapping is kept") + return entry.Targets[""] + } + entry, ok := base.Unmodeled[schema.KeptMappingKey] + require.True(t, ok, "the entries are kept") + return entry.Targets[jsontext.Pointer("/"+tag)] +} + // discriminatorOf returns the discriminator the model or union id declares. func discriminatorOf(t *testing.T, doc *ir.Document, id ir.TypeID) *ir.Discriminator { t.Helper() @@ -823,8 +845,9 @@ var valueFiles = map[string]string{ // a URI reference written at the discriminator, a fragment or none, to a // sibling file, a schema in one, or a schema's $id, read against the resource // the discriminator is in, Animal's $id resolving `cat`. A base routes to the -// subtype, which takes the least key as its tag, and a union to the variant, -// in either declaration order, and pass.Validate holds every route. +// subtype, which takes the least key as its tag, and itself by its name, and a +// union to the variant, in either declaration order, and pass.Validate holds +// every route. func TestDiscriminatorMapping_ReadsAValueNamingNoComponentAsAReference(t *testing.T) { t.Parallel() blocks := []string{` Pet: @@ -853,8 +876,9 @@ func TestDiscriminatorMapping_ReadsAValueNamingNoComponentAsAReference(t *testin `, " Tabby2: {$id: 'https://x.test/cat2', type: object, properties: {kind: {type: string}}}\n"} want := map[ir.TypeID]*ir.Discriminator{ componentID("Pet"): {Mapping: map[string]ir.TypeID{"f": "type/anonymous@cat.yaml", "g": "type/anonymous@cat.yaml", - "x": "type/anonymous@other.yaml/X"}, Default: "type/anonymous@dog.yaml"}, - componentID("Animal"): {Mapping: map[string]ir.TypeID{"c": componentID("Tabby"), "r": componentID("Tabby")}}, + "x": "type/anonymous@other.yaml/X", "Pet": componentID("Pet")}, Default: "type/anonymous@dog.yaml"}, + componentID("Animal"): {Mapping: map[string]ir.TypeID{"c": componentID("Tabby"), "r": componentID("Tabby"), + "Animal": componentID("Animal")}}, componentID("Pets"): {Mapping: map[string]ir.TypeID{"c": componentID("Tabby2"), "f": "type/anonymous@cat2.yaml", "g": "type/anonymous@cat2.yaml", "y": "type/anonymous@other.yaml/Y"}, Default: "type/anonymous@dog2.yaml"}, } @@ -987,10 +1011,13 @@ func TestDiscriminatorMapping_ReadsThroughAComponentThatIsARef(t *testing.T) { for _, reversed := range []bool{false, true} { doc, diags := parseFull(t, rawSpec("3.1.0", blocks, "", reversed)) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc), "every route is a subtype or a variant") + assert.Empty(t, routeFindings(t, doc), "every route is a subtype or a variant") sub := componentID("Sub") - assert.Equal(t, map[string]ir.TypeID{"sub": sub, "sib": sub, "tri": sub, "via": sub}, - discriminatorOf(t, doc, componentID("Root")).Mapping, "reversed %t", reversed) + root := discriminatorOf(t, doc, componentID("Root")) + assert.Equal(t, map[string]ir.TypeID{"sub": sub, "sib": sub, "tri": sub, "via": sub, "Root": componentID("Root"), + "AliasSub": componentID("AliasSub"), "SiblingSub": componentID("SiblingSub"), "Alias2": componentID("Alias2"), + "Alias3": componentID("Alias3"), "Holder": componentID("Holder")}, root.Mapping, "reversed %t", reversed) + assert.Equal(t, map[string]ir.TypeID{"Sub": sub}, root.DecodeOnlyRoutes, "reversed %t", reversed) subModel, ok := doc.Types[sub].(*ir.Model) require.True(t, ok) assert.Equal(t, "sib", subModel.DiscriminatorValue) @@ -1069,7 +1096,7 @@ func TestDiscriminatorMapping_RoutesToTheNearestVariant(t *testing.T) { " CatAlias: {$ref: '#/components/schemas/Cat'}\n"} for _, reversed := range []bool{false, true} { doc, diags := parseFull(t, rawSpec("3.1.0", blocks, "", reversed)) - assert.Empty(t, withCode(diags, diag.DegradedConstruct), "nothing is elected") + assert.Empty(t, withCode(diags, diag.DegradedConstruct), "nothing is chosen") openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, validated(t, doc), "the route is a variant") assert.Equal(t, c.want, discriminatorOf(t, doc, componentID("Pet")).Mapping["c"], "reversed %t", reversed) @@ -1079,9 +1106,11 @@ func TestDiscriminatorMapping_RoutesToTheNearestVariant(t *testing.T) { } // TestDiscriminatorMapping_LeavesAValueNamingNoVariantToValidate pins a value -// naming a schema that is no variant of its union, or no subtype of its base: -// the compiler routes to it and reports nothing, as the value names a schema, -// and pass.Validate reports the route once, in either declaration order. +// naming a schema that is no variant of its union: the compiler routes to it +// and reports nothing, as the value names a schema, and pass.Validate reports +// the route once, in either declaration order. On a base, one naming no +// subtype is set aside: kept verbatim on the base, reported once where it is +// written, so validation finds nothing there. func TestDiscriminatorMapping_LeavesAValueNamingNoVariantToValidate(t *testing.T) { t.Parallel() blocks := []string{ @@ -1094,17 +1123,16 @@ func TestDiscriminatorMapping_LeavesAValueNamingNoVariantToValidate(t *testing.T } for _, reversed := range []bool{false, true} { doc, diags := parseFull(t, rawSpec("3.1.0", blocks, "", reversed)) - assert.Empty(t, diags, "the compiler reports nothing") + assert.Equal(t, []string{"info " + diag.UnhomedConstruct + " /components/schemas/Base/discriminator/mapping/b"}, + reportedAt(diags), "the base's entry is set aside, and reported once") assert.Equal(t, componentID("Bird"), discriminatorOf(t, doc, componentID("Pet")).Mapping["b"]) - assert.Equal(t, componentID("Bird"), discriminatorOf(t, doc, componentID("Base")).Mapping["b"]) + assert.Equal(t, map[string]ir.TypeID{"Base": componentID("Base")}, discriminatorOf(t, doc, componentID("Base")).Mapping) var got []string for _, diagnostic := range validated(t, doc) { got = append(got, diagnostic.Code+": "+diagnostic.Message) } - slices.Sort(got) const missing = "pass/discriminator-missing-variant: discriminator mapping \"b\" on " const bird = " references \"type/openapi/components/schemas/Bird\", which is not a variant of it" - assert.Equal(t, []string{missing + string(componentID("Base")) + bird, missing + string(componentID("Pet")) + bird}, - got, "reversed %t", reversed) + assert.Equal(t, []string{missing + string(componentID("Pet")) + bird}, got, "reversed %t", reversed) } } diff --git a/compilers/openapi/internal/schema/discriminator_routes_test.go b/compilers/openapi/internal/schema/discriminator_routes_test.go new file mode 100644 index 000000000..326308be6 --- /dev/null +++ b/compilers/openapi/internal/schema/discriminator_routes_test.go @@ -0,0 +1,570 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irverify" +) + +// routes is a discriminator's two route maps, each target spelled by the name +// of the component it is, so a table reads as the source does. An empty map is +// nil: none. +type routes struct { + Mapping, DecodeOnly map[string]string +} + +// routesOf returns the routes of the discriminator the component name's node +// holds, requiring it to hold one. +func routesOf(t *testing.T, doc *ir.Document, name string) routes { + t.Helper() + discriminator := heldDiscriminator(t, doc, name) + require.NotNil(t, discriminator, "%s holds a discriminator", name) + return routes{Mapping: spelledRoutes(discriminator.Mapping), DecodeOnly: spelledRoutes(discriminator.DecodeOnlyRoutes)} +} + +// heldDiscriminator returns the discriminator of the model or union the +// component name lowers to, nil for none. +func heldDiscriminator(t *testing.T, doc *ir.Document, name string) *ir.Discriminator { + t.Helper() + switch node := typeByName(doc, name).(type) { + case *ir.Model: + return node.Discriminator + case *ir.Union: + return node.Discriminator + default: + require.Failf(t, "no discriminator holder", "%s lowers to %T", name, node) + return nil + } +} + +// spelledRoutes spells each route's target by its component name, keeping any +// other ID whole, and gives nil for an empty map. +func spelledRoutes(byTag map[string]ir.TypeID) map[string]string { + if len(byTag) == 0 { + return nil + } + out := make(map[string]string, len(byTag)) + for tag, target := range byTag { + out[tag] = strings.TrimPrefix(string(target), string(componentID(""))) + } + return out +} + +// tagsOf returns the DiscriminatorValue of each named component model. +func tagsOf(t *testing.T, doc *ir.Document, names map[string]string) map[string]string { + t.Helper() + out := make(map[string]string, len(names)) + for name := range names { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s lowers to a model; got %T", name, typeByName(doc, name)) + out[name] = model.DiscriminatorValue + } + return out +} + +// requireVerified fails t unless doc holds every structural invariant, the +// one-spelling-per-route rule among them. +func requireVerified(t *testing.T, doc *ir.Document) { + t.Helper() + require.Empty(t, irverify.Verify(doc), "the compiled document verifies") +} + +// routeRow is a document whose discriminators the test reads: the block +// compiled first and the rest, the routes each named discriminator holds, the +// tag each named subtype carries, and the codes validation reports. +type routeRow struct { + name, version, first, rest string + want map[string]routes + tags map[string]string + told []string +} + +// assertRouteRow compiles row in both declaration orders and holds each to its +// routes and tags, every document verified. +func assertRouteRow(t *testing.T, row routeRow) { + t.Helper() + version := row.version + if version == "" { + version = "3.1.0" + } + for _, doc := range discriminatedOrdersTold(t, version, row.first, row.rest, row.told) { + requireVerified(t, doc) + got := make(map[string]routes, len(row.want)) + for name := range row.want { + got[name] = routesOf(t, doc, name) + } + assert.Empty(t, cmp.Diff(row.want, got), "routes") + if row.tags != nil { + assert.Equal(t, row.tags, tagsOf(t, doc, row.tags), "the tag each subtype carries") + } + } +} + +// Shared blocks: a concrete base tagging petType, and subtypes of it. +const ( + petTypeBase = " Pet:\n type: object\n required: [petType]\n properties: {petType: {type: string}}\n" + plainDog = " Dog: {allOf: [{$ref: '#/components/schemas/Pet'}]}\n" + plainCat = " Cat: {allOf: [{$ref: '#/components/schemas/Pet'}]}\n" +) + +// pinning declares name as a subtype of Pet pinning petType to pin. +func pinning(name, pin string) string { + return " " + name + ":\n allOf:\n - $ref: '#/components/schemas/Pet'\n" + + " - {type: object, properties: {petType: " + pin + "}}\n" +} + +// TestDiscriminatorRoutes_AHierarchyMapsEveryRouteItGives pins what a model +// discriminator's Mapping holds: its whole route table, each entry it keeps +// typed, each subtype no entry keys under its pins or else its name, and a +// concrete base's own name (GitHub #2313, #1863). A name an entry routes under +// another key, or the tag refuses, is decode-only, and no route is spelled +// twice. DiscriminatorValue keeps what the base gives it. +func TestDiscriminatorRoutes_AHierarchyMapsEveryRouteItGives(t *testing.T) { + t.Parallel() + for _, row := range hierarchyRows { + t.Run(row.name, func(t *testing.T) { + t.Parallel() + assertRouteRow(t, row) + }) + } +} + +var hierarchyRows = []routeRow{ + { + name: "an entry routes its subtype under a key, the name decode-only", version: "3.0.3", + first: petTypeBase + " discriminator: {propertyName: petType, mapping: {dog: Dog}}\n", + rest: plainDog + plainCat, + want: map[string]routes{"Pet": { + Mapping: map[string]string{"dog": "Dog", "Cat": "Cat", "Pet": "Pet"}, + DecodeOnly: map[string]string{"Dog": "Dog"}, + }}, + tags: map[string]string{"Dog": "dog", "Cat": "Cat"}, + }, + { + name: "a concrete base no entry names routes by its own name", + first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: plainDog + plainCat, + want: map[string]routes{"Pet": {Mapping: map[string]string{"Pet": "Pet", "Dog": "Dog", "Cat": "Cat"}}}, + tags: map[string]string{"Dog": "Dog", "Cat": "Cat"}, + }, + { + name: "each pinned string maps, the name the pin refuses decode-only", + first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: pinning("Dog", "{const: dog}") + pinning("Cat", "{enum: [cat]}"), + want: map[string]routes{"Pet": { + Mapping: map[string]string{"Pet": "Pet", "dog": "Dog", "cat": "Cat"}, + DecodeOnly: map[string]string{"Dog": "Dog", "Cat": "Cat"}, + }}, + tags: map[string]string{"Dog": "dog", "Cat": "cat"}, + }, + { + name: "two subtypes pinning one string share no key", + first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: pinning("Dog", "{const: dog}") + pinning("Cat", "{enum: [cat, kitty]}") + + " Labrador:\n allOf:\n - $ref: '#/components/schemas/Dog'\n" + + " - {type: object, properties: {coat: {type: string}}}\n", + want: map[string]routes{"Pet": { + Mapping: map[string]string{"Pet": "Pet", "cat": "Cat", "kitty": "Cat"}, + DecodeOnly: map[string]string{"Dog": "Dog", "Labrador": "Labrador", "Cat": "Cat"}, + }}, + tags: map[string]string{"Dog": "dog", "Labrador": "dog", "Cat": ""}, + }, + { + name: "a pin listing the name maps it beside the other pins", + first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: pinning("Dog2", "{type: string, enum: [Dog2, dog]}") + pinning("Cat2", "{const: cat}"), + want: map[string]routes{"Pet": { + Mapping: map[string]string{"Pet": "Pet", "Dog2": "Dog2", "dog": "Dog2", "cat": "Cat2"}, + DecodeOnly: map[string]string{"Cat2": "Cat2"}, + }}, + tags: map[string]string{"Dog2": "Dog2", "Cat2": "cat"}, + }, + { + name: "a name an entry keys to another schema keeps that schema's route alone", + first: petTypeBase + " discriminator:\n propertyName: petType\n" + + " mapping: {hound: '#/components/schemas/Hound', Hound: '#/components/schemas/Cat2'}\n", + rest: " Hound: {allOf: [{$ref: '#/components/schemas/Pet'}], properties: {petType: {type: string}}}\n" + + " Cat2: {allOf: [{$ref: '#/components/schemas/Pet'}]}\n", + want: map[string]routes{"Pet": { + Mapping: map[string]string{"hound": "Hound", "Hound": "Cat2", "Pet": "Pet"}, + DecodeOnly: map[string]string{"Cat2": "Cat2"}, + }}, + tags: map[string]string{"Hound": "hound", "Cat2": "Hound"}, + }, + { + // Hound pins hound, which Cat2 admits, its tag a plain string, but + // does not pin: only another routed subtype pinning a string keeps it + // from mapping, so hound routes to Hound, whose name an entry keys to + // Cat2. + name: "a string a sibling only admits still maps", + first: petTypeBase + " discriminator:\n propertyName: petType\n" + + " mapping: {Hound: '#/components/schemas/Cat2'}\n", + rest: " Hound: {allOf: [{$ref: '#/components/schemas/Pet'}], properties: {petType: {const: hound}}}\n" + + " Cat2: {allOf: [{$ref: '#/components/schemas/Pet'}]}\n", + want: map[string]routes{"Pet": { + Mapping: map[string]string{"hound": "Hound", "Hound": "Cat2", "Pet": "Pet"}, + DecodeOnly: map[string]string{"Cat2": "Cat2"}, + }}, + tags: map[string]string{"Hound": "hound", "Cat2": "Hound"}, + }, + { + // Dog pins Cat, the name by which the source routes Cat: the pin + // overrides no route the source gives, so Cat keeps it and Dog is + // routed by its own name, for a decoder alone. + name: "a pin spelling another subtype's name leaves that name its route", + first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: pinning("Dog", "{const: Cat}") + plainCat, + want: map[string]routes{"Pet": { + Mapping: map[string]string{"Pet": "Pet", "Cat": "Cat"}, + DecodeOnly: map[string]string{"Dog": "Dog"}, + }}, + tags: map[string]string{"Dog": "Cat", "Cat": "Cat"}, + }, + { + // GitHub #2316: Kitten pins cat, which an entry spells, so its name is + // its route, and no subtype is left unrouted. + name: "a subtype whose pin an entry spells routes by its name", + first: petTypeBase + " discriminator: {propertyName: petType, mapping: {cat: '#/components/schemas/Cat'}}\n", + rest: " Cat: {allOf: [{$ref: '#/components/schemas/Pet'}], type: object, properties: {petType: {const: cat}}}\n" + + " Kitten: {allOf: [{$ref: '#/components/schemas/Cat'}], type: object}\n", + want: map[string]routes{"Pet": { + Mapping: map[string]string{"cat": "Cat", "Pet": "Pet"}, + DecodeOnly: map[string]string{"Cat": "Cat", "Kitten": "Kitten"}, + }}, + tags: map[string]string{"Cat": "cat", "Kitten": "cat"}, + }, + { + // GitHub #2060: each spelling of one schema is a subtype tagged by its + // name, a bare $ref among them. + name: "a bare $ref, its allOf and a $ref with notes are routed subtypes", + first: " Pet: {type: object, required: [kind], properties: {kind: {type: string}}, discriminator: {propertyName: kind}}\n", + rest: " A: {$ref: '#/components/schemas/Pet'}\n B: {allOf: [{$ref: '#/components/schemas/Pet'}]}\n" + + " C: {$ref: '#/components/schemas/Pet', description: d}\n", + want: map[string]routes{"Pet": {Mapping: map[string]string{"Pet": "Pet", "A": "A", "B": "B", "C": "C"}}}, + tags: map[string]string{"A": "A", "B": "B", "C": "C"}, + }, + { + // A composes B composes A: A has no discriminated ancestor, B has A, + // and C, below B, has A at two levels, as at the base. + name: "a base on a composition cycle routes its own name and each subtype's", + first: " A:\n allOf: [{$ref: '#/components/schemas/B'}]\n required: [k]\n" + + " properties: {k: {type: string}}\n discriminator: {propertyName: k}\n", + rest: " B: {allOf: [{$ref: '#/components/schemas/A'}], properties: {b: {type: string}}}\n" + + " C: {allOf: [{$ref: '#/components/schemas/B'}], properties: {c: {type: string}}}\n", + want: map[string]routes{"A": {Mapping: map[string]string{"A": "A", "B": "B", "C": "C"}}}, + tags: map[string]string{"A": "", "B": "B", "C": "C"}, + told: []string{"pass/composition-cycle", "pass/composition-cycle"}, + }, +} + +// The three shapes of GitHub #2313: Labrador below Dog below Pet, each base +// discriminating a property of its own. +const ( + breedDog = " Dog:\n allOf: [{$ref: '#/components/schemas/Pet'}]\n type: object\n" + + " required: [breed]\n properties: {breed: {type: string}}\n" + labrador = " Labrador: {allOf: [{$ref: '#/components/schemas/Dog'}], type: object, properties: {bark: {type: boolean}}}\n" +) + +// TestDiscriminatorRoutes_EachOfTwoDiscriminatorsMapsItsRoutes pins GitHub +// #2313's three shapes: each discriminator's Mapping holds every route it +// gives, so the route one gives Labrador is read off it whichever the other +// tags Labrador with. Each concrete base routes by its own name, and the +// document validates, a valid hierarchy of two discriminators drawing no +// error. +func TestDiscriminatorRoutes_EachOfTwoDiscriminatorsMapsItsRoutes(t *testing.T) { + t.Parallel() + for _, row := range []routeRow{ + { + name: "no entries", first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: breedDog + " discriminator: {propertyName: breed}\n" + labrador, + want: map[string]routes{ + "Pet": {Mapping: map[string]string{"Pet": "Pet", "Dog": "Dog", "Labrador": "Labrador"}}, + "Dog": {Mapping: map[string]string{"Dog": "Dog", "Labrador": "Labrador"}}, + }, + tags: map[string]string{"Dog": "Dog", "Labrador": "Labrador"}, + }, + { + name: "the nearer writes an entry", first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: breedDog + " discriminator: {propertyName: breed, mapping: {lab: '#/components/schemas/Labrador'}}\n" + labrador, + want: map[string]routes{ + "Pet": {Mapping: map[string]string{"Pet": "Pet", "Dog": "Dog", "Labrador": "Labrador"}}, + "Dog": { + Mapping: map[string]string{"Dog": "Dog", "lab": "Labrador"}, + DecodeOnly: map[string]string{"Labrador": "Labrador"}, + }, + }, + tags: map[string]string{"Dog": "Dog", "Labrador": "lab"}, + }, + { + name: "the further writes entries", + first: petTypeBase + " discriminator:\n propertyName: petType\n" + + " mapping: {lab: '#/components/schemas/Labrador', dog: '#/components/schemas/Dog'}\n", + rest: breedDog + " discriminator: {propertyName: breed}\n" + labrador, + want: map[string]routes{ + "Pet": { + Mapping: map[string]string{"Pet": "Pet", "lab": "Labrador", "dog": "Dog"}, + DecodeOnly: map[string]string{"Dog": "Dog", "Labrador": "Labrador"}, + }, + "Dog": {Mapping: map[string]string{"Dog": "Dog", "Labrador": "Labrador"}}, + }, + tags: map[string]string{"Dog": "dog", "Labrador": "lab"}, + }, + } { + t.Run(row.name, func(t *testing.T) { + t.Parallel() + assertRouteRow(t, row) + }) + } +} + +// TestDiscriminatorRoutes_AUnionRoutesEveryRouteTheSourceGives pins a union +// discriminator's two maps (GitHub #1863, #1798): Mapping holds each entry and +// the route implied to each variant no entry routes, and DecodeOnlyRoutes the +// name of each variant an entry routes under another key, or whose name +// inference replaces, whether or not the variant admits it. A name an entry +// keys to another variant routes there alone, and a variant no route reaches +// draws validation's info. +func TestDiscriminatorRoutes_AUnionRoutesEveryRouteTheSourceGives(t *testing.T) { + t.Parallel() + for _, row := range unionRows { + t.Run(row.name, func(t *testing.T) { + t.Parallel() + assertRouteRow(t, row) + }) + } +} + +// Shared union variants: Dog and Cat leaving kind a plain string. +const ( + kindDog = " Dog: {type: object, required: [kind, bark], properties: {kind: {type: string}, bark: {type: string}}}\n" + kindCat = " Cat: {type: object, required: [kind, name], properties: {kind: {type: string}, name: {type: string}}}\n" + dogCat = " oneOf: [{$ref: '#/components/schemas/Dog'}, {$ref: '#/components/schemas/Cat'}]\n" +) + +// pinnedVariant declares name as an object pinning kind to pin. +func pinnedVariant(name, pin string) string { + return " " + name + ": {type: object, required: [kind], properties: {kind: " + pin + "}}\n" +} + +var unionRows = []routeRow{ + { + name: "an entry routes a variant under a key, the name decode-only", version: "3.0.3", + first: " Pet:\n" + dogCat + " discriminator: {propertyName: kind, mapping: {dog: '#/components/schemas/Dog'}}\n", + rest: kindDog + kindCat, + want: map[string]routes{"Pet": { + Mapping: map[string]string{"dog": "Dog", "Cat": "Cat"}, + DecodeOnly: map[string]string{"Dog": "Dog"}, + }}, + }, + { + name: "the name stays decode-only beside a default", version: "3.2.0", + first: " Pet:\n oneOf: [{$ref: '#/components/schemas/Dog'}, {$ref: '#/components/schemas/Cat'}, " + + "{$ref: '#/components/schemas/Other'}]\n discriminator: {propertyName: kind, " + + "mapping: {dog: '#/components/schemas/Dog'}, defaultMapping: '#/components/schemas/Other'}\n", + rest: kindDog + kindCat + + " Other: {type: object, required: [kind, color], properties: {kind: {type: string}, color: {type: string}}}\n", + want: map[string]routes{"Pet": { + Mapping: map[string]string{"dog": "Dog", "Cat": "Cat", "Other": "Other"}, + DecodeOnly: map[string]string{"Dog": "Dog"}, + }}, + }, + { + // The golden spec's shape: entries route every variant under another + // key, one variant pinning its tag to a value refusing its name, one + // leaving it a plain string. Both names are routes. + name: "every name an entry routes elsewhere is decode-only, admitted or not", + first: " Link:\n oneOf: [{$ref: '#/components/schemas/Physical'}, {$ref: '#/components/schemas/Virtual'}]\n" + + " discriminator:\n propertyName: kind\n" + + " mapping: {direct: '#/components/schemas/Physical', partner: '#/components/schemas/Virtual'}\n", + rest: pinnedVariant("Physical", "{type: string, enum: [direct]}") + pinnedVariant("Virtual", "{type: string}"), + want: map[string]routes{"Link": { + Mapping: map[string]string{"direct": "Physical", "partner": "Virtual"}, + DecodeOnly: map[string]string{"Physical": "Physical", "Virtual": "Virtual"}, + }}, + }, + { + name: "a name an entry keys to another variant routes there alone", + first: " U:\n" + dogCat + " discriminator: {propertyName: kind, mapping: {dog: '#/components/schemas/Dog', Dog: '#/components/schemas/Cat'}}\n", + rest: kindDog + kindCat, + want: map[string]routes{"U": { + Mapping: map[string]string{"dog": "Dog", "Dog": "Cat"}, + DecodeOnly: map[string]string{"Cat": "Cat"}, + }}, + }, + { + // Dog pins dog, which Cat admits too, so nothing replaces its name, and + // an entry keys that name to Cat: no route reaches Dog. + name: "a pinned variant whose name an entry keys elsewhere has no route", + first: " U:\n" + dogCat + " discriminator: {propertyName: kind, mapping: {Dog: '#/components/schemas/Cat'}}\n", + rest: pinnedVariant("Dog", "{const: dog}") + pinnedVariant("Cat", "{type: string}"), + want: map[string]routes{"U": { + Mapping: map[string]string{"Dog": "Cat"}, + DecodeOnly: map[string]string{"Cat": "Cat"}, + }}, + told: []string{"pass/discriminator-unrouted-variant"}, + }, + { + // GitHub #1844: an inline variant has no name, and no entry routes it. + name: "an inline variant no entry routes has no route", + first: " Pet:\n discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}\n" + + " oneOf:\n - $ref: '#/components/schemas/Cat'\n" + + " - {type: object, required: [kind, bark], properties: {kind: {type: string}, bark: {type: boolean}}}\n", + rest: pinnedVariant("Cat", "{type: string}"), + want: map[string]routes{"Pet": { + Mapping: map[string]string{"cat": "Cat"}, + DecodeOnly: map[string]string{"Cat": "Cat"}, + }}, + told: []string{"pass/discriminator-unrouted-variant"}, + }, + { + // GitHub #1798: Dog, which no entry routes, pins dog, which no other + // variant admits and no entry spells. + name: "a declared mapping's left-out variant maps the strings it pins", + first: " Pet:\n" + dogCat + " discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}\n", + rest: pinnedVariant("Dog", "{const: dog}") + pinnedVariant("Cat", "{const: cat}"), + want: map[string]routes{"Pet": { + Mapping: map[string]string{"cat": "Cat", "dog": "Dog"}, + DecodeOnly: map[string]string{"Cat": "Cat", "Dog": "Dog"}, + }}, + }, + { + name: "a left-out variant whose pin an entry spells keeps its name", + first: " Pet:\n" + dogCat + " discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat', dog: '#/components/schemas/Cat'}}\n", + rest: pinnedVariant("Dog", "{const: dog}") + pinnedVariant("Cat", "{const: cat}"), + want: map[string]routes{"Pet": { + Mapping: map[string]string{"cat": "Cat", "dog": "Cat", "Dog": "Dog"}, + DecodeOnly: map[string]string{"Cat": "Cat"}, + }}, + }, + { + // With no mapping, inference maps both of Dog's pins, its name among + // them, and replaces Cat's name, which is then decode-only. + name: "a name inference replaces is decode-only", + first: " U:\n" + dogCat + " discriminator: {propertyName: kind}\n", + rest: pinnedVariant("Dog", "{type: string, enum: [Dog, dog]}") + pinnedVariant("Cat", "{const: cat}"), + want: map[string]routes{"U": { + Mapping: map[string]string{"Dog": "Dog", "dog": "Dog", "cat": "Cat"}, + DecodeOnly: map[string]string{"Cat": "Cat"}, + }}, + }, +} + +// TestDiscriminatorRoutes_ADeclaredMappingInfersWhatItLeavesOut pins GitHub +// #1798's marks: the union whose left-out variants' tags inference reads is +// marked inferred and reported once at its discriminator, as an undeclared +// mapping's is, and one whose left-out variant's pin an entry spells is +// neither. +func TestDiscriminatorRoutes_ADeclaredMappingInfersWhatItLeavesOut(t *testing.T) { + t.Parallel() + const variants = " Dog: {type: object, required: [kind], properties: {kind: {const: dog}}}\n" + + " Cat: {type: object, required: [kind], properties: {kind: {const: cat}}}\n" + for _, c := range []struct { + name, mapping string + inferred bool + }{ + {"inferred", "{cat: '#/components/schemas/Cat'}", true}, + {"an entry spells the pin", "{cat: '#/components/schemas/Cat', dog: '#/components/schemas/Cat'}", false}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + pet := " Pet:\n" + dogCat + " discriminator: {propertyName: kind, mapping: " + c.mapping + "}\n" + for _, doc := range discriminatedOrders(t, "3.1.0", pet, variants) { + union, ok := typeByName(doc, "Pet").(*ir.Union) + require.True(t, ok) + assert.Equal(t, c.inferred, strings.Contains(string(union.Provenance.Inferred), "discriminator-inference"), + "inferred: %q", union.Provenance.Inferred) + want := 0 + if c.inferred { + want = 1 + } + assert.Len(t, diagsAtPointer(doc.Diagnostics, diag.InferredDiscriminator, "/components/schemas/Pet/discriminator"), want) + } + }) + } +} + +// TestDiscriminatorRoutes_ANameTheTagRefusesIsNoMappingKey pins both branches +// of a subtype's reading: one pinning strings maps them and leaves its name +// decode-only, and one pinning none whose tag member refuses its name has the +// name decode-only, so neither is a key an encoder writes and both are routed. +// The second reads the refusal through value admission, which the member +// fold's reader gives. +func TestDiscriminatorRoutes_ANameTheTagRefusesIsNoMappingKey(t *testing.T) { + t.Parallel() + for _, row := range []routeRow{ + { + name: "pinned", first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: pinning("Dog", "{type: string, enum: [dog, hound]}") + pinning("Cat", "{const: cat}"), + want: map[string]routes{"Pet": { + Mapping: map[string]string{"Pet": "Pet", "dog": "Dog", "hound": "Dog", "cat": "Cat"}, + DecodeOnly: map[string]string{"Dog": "Dog", "Cat": "Cat"}, + }}, + }, + { + name: "refusing without a pin", first: petTypeBase + " discriminator: {propertyName: petType}\n", + rest: pinning("Dog", "{type: string, minLength: 4}") + plainCat, + want: map[string]routes{"Pet": { + Mapping: map[string]string{"Pet": "Pet", "Cat": "Cat"}, + DecodeOnly: map[string]string{"Dog": "Dog"}, + }}, + }, + } { + t.Run(row.name, func(t *testing.T) { + t.Parallel() + assertRouteRow(t, row) + }) + } +} + +// TestDiscriminatorRoutes_KeptEntriesShareOneObject pins where a model keeps +// the routes it sets aside: every entry routing to neither it nor a subtype +// under one openapi:discriminator/mapping object, spelled as the source's +// mapping writes them, each naming the type it lowered to and reported once +// at its value, and the entries routing to subtypes typed, in either +// declaration order. +func TestDiscriminatorRoutes_KeptEntriesShareOneObject(t *testing.T) { + t.Parallel() + pet := petTypeBase + " discriminator:\n propertyName: petType\n" + + " mapping: {a: '#/components/schemas/A', b: B, dog: '#/components/schemas/Dog'}\n" + rest := plainDog + " A: {type: object, properties: {x: {type: string}}}\n B: {type: object, properties: {y: {type: string}}}\n" + for _, doc := range discriminatedOrders(t, "3.1.0", pet, rest) { + requireVerified(t, doc) + assert.Equal(t, routes{Mapping: map[string]string{"dog": "Dog", "Pet": "Pet"}, DecodeOnly: map[string]string{"Dog": "Dog"}}, + routesOf(t, doc, "Pet")) + kept := typeByName(doc, "Pet").Common().Unmodeled[schema.KeptMappingKey] + assert.Equal(t, ir.ReasonNoIRHome, kept.Reason) + assert.JSONEq(t, `{"a": "#/components/schemas/A", "b": "B"}`, string(kept.Value)) + assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/a": componentID("A"), "/b": componentID("B")}, kept.Targets) + assert.Equal(t, ir.Provenance{Pointer: "/components/schemas/Pet/discriminator/mapping"}, kept.Provenance) + for _, key := range []string{"a", "b"} { + assert.Len(t, diagsAtPointer(doc.Diagnostics, diag.UnhomedConstruct, "/components/schemas/Pet/discriminator/mapping/"+key), 1) + } + } +} + +// TestDiscriminatorRoutes_APinSpellingANameMapsNothing pins that a string a +// subtype pins which is another subtype's name maps nothing: the source routes +// it by that name, so the inference policy reads nothing into the base's +// Mapping and the base names no heuristic, in either declaration order. +func TestDiscriminatorRoutes_APinSpellingANameMapsNothing(t *testing.T) { + t.Parallel() + pet := petTypeBase + " discriminator: {propertyName: petType}\n" + for _, doc := range discriminatedOrders(t, "3.1.0", pet, pinning("Dog", "{const: Cat}")+plainCat) { + model, ok := typeByName(doc, "Pet").(*ir.Model) + require.True(t, ok) + assert.Empty(t, model.Provenance.Inferred, "no pin is mapped") + assert.Equal(t, componentID("Cat"), model.Discriminator.Mapping["Cat"]) + } +} diff --git a/compilers/openapi/internal/schema/discriminator_settled_test.go b/compilers/openapi/internal/schema/discriminator_settled_test.go new file mode 100644 index 000000000..9a2064f29 --- /dev/null +++ b/compilers/openapi/internal/schema/discriminator_settled_test.go @@ -0,0 +1,404 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "slices" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" + "github.com/dexpace/morphic/ir/irverify" +) + +// TestDiscriminatorRoutes_ARouteToItsOwnModelKeepsTheDiscriminator pins +// GitHub #1806: beside a union kept verbatim, an entry routing to the model +// itself, which is not Abstract, is a route, so the discriminator stays on the +// model, every entry typed, in either declaration order. The base, routed +// under another key, has its own name decode-only, as each subtype does. +func TestDiscriminatorRoutes_ARouteToItsOwnModelKeepsTheDiscriminator(t *testing.T) { + t.Parallel() + pet := " Pet:\n type: object\n required: [kind]\n properties: {kind: {type: string}}\n" + petBranches + + " discriminator:\n propertyName: kind\n mapping:\n" + + " pet: '#/components/schemas/Pet'\n cat: '#/components/schemas/Cat'\n" + + " dog: '#/components/schemas/Dog'\n" + for _, doc := range discriminatedOrders(t, "3.1.0", pet, subtypes) { + requireVerified(t, doc) + model := petModel(t, doc) + require.NotNil(t, model.Discriminator, "every route is the model or a subtype of it") + assert.NotContains(t, model.Unmodeled, "openapi:discriminator", "nothing is kept twice") + assert.False(t, openapitest.HasDiagCodeAt(doc.Diagnostics, diag.DegradedConstruct, movedPointer)) + assert.Empty(t, cmp.Diff(routes{ + Mapping: map[string]string{"pet": "Pet", "cat": "Cat", "dog": "Dog"}, + DecodeOnly: map[string]string{"Pet": "Pet", "Cat": "Cat", "Dog": "Dog"}, + }, routesOf(t, doc, "Pet"))) + } +} + +// TestDiscriminatorRoutes_AnEntryRoutingToNoSubtypeIsKeptOnItsModel pins +// GitHub #2051: an entry routing to neither the model nor a subtype of it is +// kept verbatim on the model with one info at the entry, the document +// compiling and validating, and the routes to the model and its subtypes stay +// typed. A schema composing the model only as a mixin is no subtype (the +// lowering keeps the other discriminated parent as Base), so its entry is +// kept alike. Each row holds in either declaration order. +func TestDiscriminatorRoutes_AnEntryRoutingToNoSubtypeIsKeptOnItsModel(t *testing.T) { + t.Parallel() + const kind = " type: object\n required: [kind]\n properties: {kind: {type: string}}\n" + for _, c := range []struct { + name, version, pet, rest, entry, target string + want map[string]routes + }{ + { + name: "an unrelated schema", version: "3.0.3", + pet: " Pet:\n" + kind + " discriminator: {propertyName: kind, mapping: {a: '#/components/schemas/A'}}\n", + rest: " A: {type: object, properties: {kind: {type: string}, x: {type: string}}}\n", + entry: "a", target: "#/components/schemas/A", + want: map[string]routes{"Pet": {Mapping: map[string]string{"Pet": "Pet"}}}, + }, + { + name: "a sibling composing the same base", version: "3.1.0", + pet: " Pet:\n allOf: [{$ref: '#/components/schemas/Base'}]\n" + + " discriminator: {propertyName: kind, mapping: {c: '#/components/schemas/Cat'}}\n", + rest: " Base: {type: object, properties: {kind: {type: string}}}\n" + + " Cat: {allOf: [{$ref: '#/components/schemas/Base'}], properties: {lives: {type: integer}}}\n", + entry: "c", target: "#/components/schemas/Cat", + want: map[string]routes{"Pet": {Mapping: map[string]string{"Pet": "Pet"}}}, + }, + { + name: "a schema composing the model as a mixin", version: "3.1.0", + pet: " Pet:\n" + kind + " discriminator: {propertyName: kind, mapping: {dog: '#/components/schemas/Dog'}}\n", + rest: " Animal:\n" + kind + " discriminator: {propertyName: kind, mapping: {dog: '#/components/schemas/Dog'}}\n" + + " Dog:\n allOf:\n - $ref: '#/components/schemas/Pet'\n - $ref: '#/components/schemas/Animal'\n" + + " - {type: object, properties: {bark: {type: boolean}}}\n", + entry: "dog", target: "#/components/schemas/Dog", + want: map[string]routes{ + "Pet": {Mapping: map[string]string{"Pet": "Pet"}}, + "Animal": {Mapping: map[string]string{"dog": "Dog", "Animal": "Animal"}, DecodeOnly: map[string]string{"Dog": "Dog"}}, + }, + }, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + at := "/components/schemas/Pet/discriminator/mapping/" + c.entry + for _, doc := range discriminatedOrders(t, c.version, c.pet, c.rest) { + requireVerified(t, doc) + got := make(map[string]routes, len(c.want)) + for name := range c.want { + got[name] = routesOf(t, doc, name) + } + assert.Empty(t, cmp.Diff(c.want, got), "the routes to the model and its subtypes stay typed") + reports := diagsAtPointer(doc.Diagnostics, diag.UnhomedConstruct, at) + if assert.Len(t, reports, 1, "one info at the entry") { + assert.Equal(t, ir.SeverityInfo, reports[0].Severity) + } + assert.Equal(t, 1, keptNamingTarget(typeByName(doc, "Pet").Common().Unmodeled, c.target), + "the entry is kept verbatim on the model, once") + } + }) + } +} + +// keptNamingTarget counts the entries of kept, each kept for want of a home, +// whose value spells target. +func keptNamingTarget(kept ir.Unmodeled, target string) int { + count := 0 + for _, entry := range kept { + if entry.Reason == ir.ReasonNoIRHome && strings.Contains(string(entry.Value), target) { + count++ + } + } + return count +} + +// TestDiscriminatorRoutes_AnEntryDiscriminatorLowersAsOneBesideTheAllOf pins +// GitHub #2052: a discriminator an inline allOf entry writes, whose +// propertyName the composed model holds, lowers as the same one written +// beside the allOf does, the entry's property its tag, and routes the subtype +// composing the model, in either declaration order. Nothing is kept of it, and +// nothing reported. +func TestDiscriminatorRoutes_AnEntryDiscriminatorLowersAsOneBesideTheAllOf(t *testing.T) { + t.Parallel() + const base = " Base: {type: object, properties: {id: {type: string}}}\n" + for _, c := range []struct{ name, pet, cat, tag string }{ + {"beside the allOf", "PetBeside", "CatBeside", "property/openapi/components/schemas/PetBeside/properties/kind"}, + {"on an entry", "PetEntry", "CatEntry", "property/openapi/components/schemas/PetEntry/allOf/1/properties/kind"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + mapping := "{propertyName: kind, mapping: {cat: '#/components/schemas/" + c.cat + "'}}" + pet := " " + c.pet + ":\n allOf:\n - $ref: '#/components/schemas/Base'\n" + if c.pet == "PetEntry" { + pet += " - type: object\n properties: {kind: {type: string}}\n discriminator: " + mapping + "\n" + } else { + pet += " type: object\n properties: {kind: {type: string}}\n discriminator: " + mapping + "\n" + } + cat := " " + c.cat + ": {allOf: [{$ref: '#/components/schemas/" + c.pet + "'}, " + + "{type: object, properties: {lives: {type: integer}}}]}\n" + for _, doc := range discriminatedOrders(t, "3.1.0", pet, base+cat) { + requireVerified(t, doc) + model, ok := typeByName(doc, c.pet).(*ir.Model) + require.True(t, ok) + require.NotNil(t, model.Discriminator, "the model holds the discriminator") + assert.Equal(t, ir.PropertyID(c.tag), model.Discriminator.Property) + assert.Empty(t, cmp.Diff(routes{ + Mapping: map[string]string{"cat": c.cat, c.pet: c.pet}, + DecodeOnly: map[string]string{c.cat: c.cat}, + }, routesOf(t, doc, c.pet))) + assert.Equal(t, map[string]string{c.cat: "cat"}, tagsOf(t, doc, map[string]string{c.cat: ""})) + assert.Empty(t, model.Unmodeled, "nothing of the discriminator is kept") + assert.Empty(t, withCode(doc.Diagnostics, diag.DegradedConstruct)) + } + }) + } +} + +// TestDiscriminatorRoutes_AnEntryDiscriminatorNamingNoMemberLowersAsItsTwin +// pins GitHub #2052 where the composed model declares no member the +// discriminator's propertyName names: written on an inline allOf entry, beside +// the schema's properties or beside an entry writing them, it lowers as its +// flat twin, the name as written its tag, and routes the subtype composing the +// model, in either declaration order. Nothing is kept of it, and nothing +// reported. +func TestDiscriminatorRoutes_AnEntryDiscriminatorNamingNoMemberLowersAsItsTwin(t *testing.T) { + t.Parallel() + const disc = "{propertyName: b, mapping: {sub: '#/components/schemas/Sub'}}" + const sub = " Sub: {allOf: [{$ref: '#/components/schemas/Pet'}, {type: object, properties: {c: {type: integer}}}]}\n" + want := &ir.Discriminator{PropertyName: "b", + Mapping: map[string]ir.TypeID{"sub": componentID("Sub"), "Pet": componentID("Pet")}, + DecodeOnlyRoutes: map[string]ir.TypeID{"Sub": componentID("Sub")}} + for _, c := range []struct{ name, pet string }{ + {"flat", " Pet: {type: object, properties: {a: {type: string}}, discriminator: " + disc + "}\n"}, + {"on an entry beside the properties", " Pet: {type: object, properties: {a: {type: string}}, allOf: [{discriminator: " + disc + "}]}\n"}, + {"on an entry beside an entry declaring them", + " Pet: {allOf: [{type: object, properties: {a: {type: string}}}, {discriminator: " + disc + "}]}\n"}, + {"on a wrapper entry nesting an allOf", + " Pet: {allOf: [{allOf: [{type: object, properties: {a: {type: string}}}], discriminator: " + disc + "}]}\n"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + for _, doc := range discriminatedOrders(t, "3.1.0", c.pet, sub) { + requireVerified(t, doc) + model, ok := typeByName(doc, "Pet").(*ir.Model) + require.True(t, ok) + assert.Empty(t, cmp.Diff(want, model.Discriminator), "the flat twin's discriminator") + assert.Equal(t, map[string]string{"Sub": "sub"}, tagsOf(t, doc, map[string]string{"Sub": ""})) + assert.Empty(t, model.Unmodeled, "nothing of the discriminator is kept") + assert.Empty(t, doc.Diagnostics, "nothing is reported") + } + }) + } +} + +// TestDiscriminatorRoutes_AVariantOfAnotherDocumentIsRoutedAlikeUnderEither +// pins GitHub #1829: a component name routes only what the entry document's +// components hold, so a variant whose branch names another document's +// component takes no name route beneath a mapping holding an entry or beneath +// none, the second written out rather than nil, which would route the +// variant by its type's name. Each variant no route reaches draws +// validation's info. +func TestDiscriminatorRoutes_AVariantOfAnotherDocumentIsRoutedAlikeUnderEither(t *testing.T) { + t.Parallel() + const branches = " oneOf: [{$ref: '#/components/schemas/Cat'}, {$ref: './other.yaml#/components/schemas/Dog'}]\n" + doc, diags, _ := compileBeside(t, + map[string]string{"other.yaml": "openapi: 3.1.0\ninfo: {title: o, version: \"1\"}\npaths: {}\n" + + "components:\n schemas:\n Dog: {type: object, properties: {kind: {type: string}, bark: {type: string}}}\n"}, + openapitest.ComponentSpec(" Mapped:\n discriminator: {propertyName: kind, mapping: {c: '#/components/schemas/Cat'}}\n"+ + branches+" Unmapped:\n discriminator: {propertyName: kind}\n"+branches+ + " Cat: {type: object, properties: {kind: {type: string}}}\n")) + openapitest.RequireNoErrorDiags(t, diags) + requireVerified(t, doc) + assert.Empty(t, cmp.Diff(map[string]routes{ + "Mapped": {Mapping: map[string]string{"c": "Cat"}, DecodeOnly: map[string]string{"Cat": "Cat"}}, + "Unmapped": {Mapping: map[string]string{"Cat": "Cat"}}, + }, map[string]routes{"Mapped": routesOf(t, doc, "Mapped"), "Unmapped": routesOf(t, doc, "Unmapped")})) + assert.Equal(t, []string{"pass/discriminator-unrouted-variant", "pass/discriminator-unrouted-variant"}, + irtest.DiagCodes(validated(t, doc)), "Dog is reached by recognition alone, beneath either") +} + +// TestDiscriminatorRoutes_ASubtypeOfAnotherDocumentHasNoName pins GitHub +// #1829 on a hierarchy: a component name routes only what the entry +// document's components hold, so a subtype another document declares +// carries no name as its tag and takes no route by it, which validation +// notes, while the entry document's own subtype is routed by its name. +func TestDiscriminatorRoutes_ASubtypeOfAnotherDocumentHasNoName(t *testing.T) { + t.Parallel() + doc, diags, _ := compileBeside(t, + map[string]string{"other.yaml": "openapi: 3.1.0\ninfo: {title: o, version: \"1\"}\npaths: {}\n" + + "components:\n schemas:\n Dog: {allOf: [{$ref: 'root.yaml#/components/schemas/Pet'}], properties: {bark: {type: string}}}\n"}, + openapitest.ComponentSpec(petTypeBase+" discriminator: {propertyName: petType}\n"+plainCat+ + " Kennel: {type: object, properties: {dog: {$ref: './other.yaml#/components/schemas/Dog'}}}\n")) + openapitest.RequireNoErrorDiags(t, diags) + requireVerified(t, doc) + assert.Equal(t, routes{Mapping: map[string]string{"Pet": "Pet", "Cat": "Cat"}}, routesOf(t, doc, "Pet")) + var dog *ir.Model + for _, node := range doc.Types { + if model, ok := node.(*ir.Model); ok && model.Name.Source == "Dog" { + dog = model + } + } + require.NotNil(t, dog, "other.yaml's Dog is lowered") + assert.Empty(t, dog.DiscriminatorValue, "no name of the entry document tags it") + assert.Equal(t, []string{"pass/discriminator-unrouted-variant"}, irtest.DiagCodes(validated(t, doc))) +} + +// TestDiscriminatorSettlement_LeavesEverySupertypeEdge holds the settlements +// to the supertype edges the lowering built, which the model discriminators' +// settlement reads them by: each model's Base, Mixins and Implements are the +// same once the registry has settled, beside routes set aside, a discriminator +// kept whole and a map body swapped for its MapT. +func TestDiscriminatorSettlement_LeavesEverySupertypeEdge(t *testing.T) { + t.Parallel() + src := openapitest.ComponentSpec(petWith("{propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}") + cat + subDog + + " Animal: {type: object, properties: {kind: {type: string}}, discriminator: {propertyName: kind, mapping: {m: '#/components/schemas/Mix'}}}\n" + + " Mix: {allOf: [{$ref: '#/components/schemas/Animal'}, {$ref: '#/components/schemas/Pet'}]}\n" + + " Holder:\n type: object\n properties:\n pet:\n type: object\n" + + " additionalProperties: {type: string}\n" + + " discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}}\n" + + " oneOf: [{required: [kind]}, {required: [x]}]\n") + lowerer, diags := schema.LoweredFor(t, src) + lowerer.Diags.AppendAll(schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) + openapitest.RequireNoErrorDiags(t, diags) + type edges struct { + base *ir.TypeRef + mixins, implement []ir.TypeRef + } + before := map[ir.TypeID]edges{} + for _, name := range []string{"Pet", "Cat", "Dog", "Animal", "Mix", "Holder"} { + if model, ok := lowerer.Types.Node(componentID(name)); ok { + if model, isModel := model.(*ir.Model); isModel { + before[model.ID] = edges{base: model.Base, mixins: slices.Clone(model.Mixins), implement: slices.Clone(model.Implements)} + } + } + } + require.Len(t, before, 6, "every component lowered to a model") + doc := lowerer.Document(t) + for id, was := range before { + model, ok := doc.Types[id].(*ir.Model) + require.True(t, ok, "%s stays a model", id) + assert.Equal(t, was, edges{base: model.Base, mixins: model.Mixins, implement: model.Implements}, "%s", id) + } + assert.IsType(t, &ir.MapT{}, doc.Types["type/anonymous/components/schemas/Holder/properties/pet"], "the map body is swapped") +} + +// TestDiscriminatorValue_ALoopOfTwoBasesTagsEachByTheNearest pins a +// composition loop holding two discriminated members, A and B, and C, which +// reaches both: each member answers to the loop's other discriminated members +// at their distances from it, never to itself, so A is tagged by B, B by A and +// C by B, the nearer, by their names, in either declaration order. +func TestDiscriminatorValue_ALoopOfTwoBasesTagsEachByTheNearest(t *testing.T) { + t.Parallel() + blocks := []string{ + " A: {allOf: [{$ref: '#/components/schemas/C'}], properties: {k: {type: string}}, discriminator: {propertyName: k}}\n", + " B: {allOf: [{$ref: '#/components/schemas/A'}], properties: {k: {type: string}}, discriminator: {propertyName: k}}\n", + " C: {allOf: [{$ref: '#/components/schemas/B'}], properties: {c: {type: string}}}\n", + } + docs := make([]*ir.Document, 0, 2) + for _, src := range []string{strings.Join(blocks, ""), blocks[2] + blocks[1] + blocks[0]} { + doc, diags := parseFull(t, openapitest.ComponentSpec(src)) + openapitest.RequireNoErrorDiags(t, diags) + assert.Equal(t, map[string]string{"A": "A", "B": "B", "C": "C"}, tagsOf(t, doc, map[string]string{"A": "", "B": "", "C": ""})) + docs = append(docs, doc) + } + assert.Empty(t, cmp.Diff(docs[0].Types, docs[1].Types, orderInvariantIR()...), "declaration order must not change the types") +} + +// deepHierarchy declares Pet, discriminated, and hops subtypes C1 to Cn, each +// composing the one before, written top down or bottom up. +func deepHierarchy(hops int, bottomUp bool) string { + blocks := make([]string, 0, hops+1) + blocks = append(blocks, " Pet: {type: object, required: [kind], properties: {kind: {type: string}}, discriminator: {propertyName: kind}}\n") + previous := "Pet" + for i := 1; i <= hops; i++ { + blocks = append(blocks, fmt.Sprintf(" C%d: {allOf: [{$ref: '#/components/schemas/%s'}]}\n", i, previous)) + previous = fmt.Sprintf("C%d", i) + } + if bottomUp { + for i, j := 0, len(blocks)-1; i < j; i, j = i+1, j-1 { + blocks[i], blocks[j] = blocks[j], blocks[i] + } + } + return strings.Join(blocks, "") +} + +// TestDiscriminatorRoutes_EveryLevelOfADeepHierarchyIsRouted pins that no +// bound on the climb to a discriminated ancestor stops a route: in a +// 300-level hierarchy every level carries its name and the base's Mapping +// routes each, where the base left the levels past 256 untagged, in either +// declaration order. +func TestDiscriminatorRoutes_EveryLevelOfADeepHierarchyIsRouted(t *testing.T) { + t.Parallel() + const hops = 300 + want := routes{Mapping: map[string]string{"Pet": "Pet"}} + tags := map[string]string{} + for i := 1; i <= hops; i++ { + name := fmt.Sprintf("C%d", i) + want.Mapping[name] = name + tags[name] = name + } + for _, bottomUp := range []bool{false, true} { + doc, diags := parseFull(t, openapitest.ComponentSpec(deepHierarchy(hops, bottomUp))) + openapitest.RequireNoErrorDiags(t, diags) + requireVerified(t, doc) + assert.Empty(t, validated(t, doc)) + assert.Empty(t, cmp.Diff(want, routesOf(t, doc, "Pet")), "bottom up: %v", bottomUp) + assert.Empty(t, cmp.Diff(tags, tagsOf(t, doc, tags)), "bottom up: %v", bottomUp) + } +} + +// TestDiscriminatorRoutes_TheChecksReachACompiledDocument holds the route +// checks to compiled output, not only to hand-built documents: a union's and +// a hierarchy's decode-only routes verify and validate clean as compiled, and +// a second spelling of one route, or a route to no variant, planted in the +// compiled document, is each found. +func TestDiscriminatorRoutes_TheChecksReachACompiledDocument(t *testing.T) { + t.Parallel() + const stray = " Stray: {type: object, properties: {kind: {type: string}}}\n" + for _, c := range []struct{ name, schemas, holder string }{ + {"a union", " Pet:\n" + dogCat + " discriminator: {propertyName: kind, mapping: {dog: '#/components/schemas/Dog'}}\n" + + kindDog + kindCat + stray, "Pet"}, + {"a hierarchy", petTypeBase + " discriminator: {propertyName: petType, mapping: {dog: '#/components/schemas/Dog'}}\n" + + plainDog + plainCat + stray, "Pet"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpec(c.schemas)) + openapitest.RequireNoErrorDiags(t, diags) + discriminator := heldDiscriminator(t, doc, c.holder) + require.NotNil(t, discriminator) + require.Equal(t, componentID("Dog"), discriminator.DecodeOnlyRoutes["Dog"], "the compile fills a decode-only route") + requireVerified(t, doc) + require.Empty(t, validated(t, doc)) + + discriminator.Mapping["Dog"] = componentID("Dog") + assert.Equal(t, []string{"ir/discriminator-route-duplicate"}, violationCodes(irverify.Verify(doc)), + "a key both maps hold is a route spelled twice") + delete(discriminator.Mapping, "Dog") + + discriminator.DecodeOnlyRoutes["Dog"] = componentID("Stray") + found := validated(t, doc) + require.Len(t, found, 1) + assert.Equal(t, "pass/discriminator-missing-variant", found[0].Code) + assert.Contains(t, found[0].Message, `decode-only route "Dog"`) + }) + } +} + +// violationCodes returns the code of each violation, in order. +func violationCodes(violations []irverify.Violation) []string { + out := make([]string, 0, len(violations)) + for _, violation := range violations { + out = append(out, violation.Code) + } + return out +} diff --git a/compilers/openapi/internal/schema/discriminator_test.go b/compilers/openapi/internal/schema/discriminator_test.go index b07783626..ba8520155 100644 --- a/compilers/openapi/internal/schema/discriminator_test.go +++ b/compilers/openapi/internal/schema/discriminator_test.go @@ -18,6 +18,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/compilers/openapi/internal/schema" "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" "github.com/dexpace/morphic/ir/irverify" ) @@ -87,7 +88,7 @@ components: discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}} `) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc)) + assert.Empty(t, routeFindings(t, doc)) pet, ok := typeByName(doc, "Pet").(*ir.Union) require.True(t, ok) alias := pet.Variants[0].Type.Target @@ -107,8 +108,9 @@ components: // branch names, each variant no entry routes takes the name of that component, // past a null branch, unless two branches name it, an entry spells it already // or the branch names none. A union whose variants are the components their -// branches name, with no mapping, routes by their names and holds none. Each is -// read in both declaration orders, and the policy reading tags reads nothing in. +// branches name, with no mapping, holds none. A variant an entry routes has +// its name decode-only, and one no route reaches draws validation's note. Each +// is read in both declaration orders. func TestDiscriminatorMapping_WritesTheRoutesItImplies(t *testing.T) { t.Parallel() const cat, dog = "{$ref: '#/components/schemas/Cat'}", "{$ref: '#/components/schemas/Dog'}" @@ -117,22 +119,28 @@ func TestDiscriminatorMapping_WritesTheRoutesItImplies(t *testing.T) { cases := []struct { name, ver, branches, mapping string want map[string]string // tag -> the variant's target; "alias" for U/oneOf/0's + decodeOnly map[string]string // tag -> the variant's target + unrouted int // the variants no route reaches }{ // OpenAPI routes the value Cat to Cat beside the entry, but a mapping is - // what a writer takes Cat's tag from, and the key Cat would give it a - // second tag to write, which nothing could mark as only read (#1863). + // what a conjunct takes Cat's tag from, and the key Cat would give it a + // second tag to write, so it is a route of DecodeOnlyRoutes, which a + // decoder reads and an encoder never writes (#1863). {"an entry beside an unnamed variant", "3.1.0", cat + ", " + dog, "{cat: Cat}", - map[string]string{"cat": "Cat", "Dog": "Dog"}}, + map[string]string{"cat": "Cat", "Dog": "Dog"}, map[string]string{"Cat": "Cat"}, 0}, {"past a null branch", "3.1.0", "{type: 'null'}, " + cat + ", " + dog, "{cat: Cat}", - map[string]string{"cat": "Cat", "Dog": "Dog"}}, + map[string]string{"cat": "Cat", "Dog": "Dog"}, map[string]string{"Cat": "Cat"}, 0}, {"an aliased variant", "3.1.0", aliasedCat + ", " + dog, "", - map[string]string{"Cat": "alias", "Dog": "Dog"}}, - {"the components themselves", "3.1.0", cat + ", " + dog, "", nil}, - {"an entry spelling the name", "3.1.0", cat + ", " + dog, "{Dog: Cat}", map[string]string{"Dog": "Cat"}}, - {"two branches naming one", "3.1.0", aliasedCat + ", " + cat + ", " + dog, "{d: Dog}", map[string]string{"d": "Dog"}}, - {"an inline variant", "3.1.0", cat + ", " + inline, "{cat: Cat}", map[string]string{"cat": "Cat"}}, + map[string]string{"Cat": "alias", "Dog": "Dog"}, nil, 0}, + {"the components themselves", "3.1.0", cat + ", " + dog, "", nil, nil, 0}, + {"an entry spelling the name", "3.1.0", cat + ", " + dog, "{Dog: Cat}", map[string]string{"Dog": "Cat"}, + map[string]string{"Cat": "Cat"}, 1}, + {"two branches naming one", "3.1.0", aliasedCat + ", " + cat + ", " + dog, "{d: Dog}", map[string]string{"d": "Dog"}, + map[string]string{"Dog": "Dog"}, 2}, + {"an inline variant", "3.1.0", cat + ", " + inline, "{cat: Cat}", map[string]string{"cat": "Cat"}, + map[string]string{"Cat": "Cat"}, 1}, {"the default named", "3.2.0", cat + ", " + dog, "{cat: Cat}, defaultMapping: Dog", - map[string]string{"cat": "Cat", "Dog": "Dog"}}, + map[string]string{"cat": "Cat", "Dog": "Dog"}, map[string]string{"Cat": "Cat"}, 0}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -148,7 +156,8 @@ func TestDiscriminatorMapping_WritesTheRoutesItImplies(t *testing.T) { for _, src := range []string{union + rest, rest + union} { doc, diags := parseFull(t, openapitest.ComponentSpecVer(c.ver, src)) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc), "the document must validate") + assert.Equal(t, slices.Repeat([]string{"pass/discriminator-unrouted-variant"}, c.unrouted), + irtest.DiagCodes(validated(t, doc)), "the document validates, each variant no route reaches noted") docs = append(docs, doc) } assert.Empty(t, cmp.Diff(docs[0].Types, docs[1].Types)) @@ -156,6 +165,7 @@ func TestDiscriminatorMapping_WritesTheRoutesItImplies(t *testing.T) { require.True(t, ok) require.NotNil(t, irUnion.Discriminator) assert.Empty(t, irUnion.Provenance.Inferred, "the routes are the document's") + assert.Empty(t, cmp.Diff(c.decodeOnly, spelledRoutes(irUnion.Discriminator.DecodeOnlyRoutes)), "decode-only routes") if c.want == nil { assert.Nil(t, irUnion.Discriminator.Mapping) return @@ -191,7 +201,7 @@ components: discriminator: {propertyName: kind, defaultMapping: '#/components/schemas/Cat'} `) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc)) + assert.Empty(t, routeFindings(t, doc)) pet, ok := typeByName(doc, "Pet").(*ir.Union) require.True(t, ok) assert.NotEqual(t, ir.TypeID("type/openapi/components/schemas/Cat"), pet.Variants[0].Type.Target) @@ -244,7 +254,7 @@ func TestDiscriminatorMapping_ATypeSeveralVariantsAliasRoutesToTheFirst(t *testi doc, diags := parseFull(t, openapitest.ComponentSpec(src)) assert.Equal(t, []string{info("green_apple"), info("red_apple")}, reported(withCode(diags, diag.DegradedConstruct))) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc), "every tag routes to a variant") + assert.Empty(t, routeFindings(t, doc), "every tag routes to a variant") union, ok := typeByName(doc, "Fruit").(*ir.Union) require.True(t, ok) first := ir.TypeID("type/anonymous" + branch(c.first)) @@ -314,7 +324,7 @@ components: Subs: {type: array, items: {$ref: '#/components/schemas/Sub', `+beside+`}} `) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc)) + assert.Empty(t, routeFindings(t, doc)) pet, ok := typeByName(doc, "Pet").(*ir.Union) require.True(t, ok) assert.Empty(t, cmp.Diff(map[string]ir.TypeID{ @@ -366,12 +376,12 @@ func TestDiscriminator_AnEmptyPropertyNameIsKeptVerbatim(t *testing.T) { names := []string{"Plain", "Inherits", "Mapped", "Union", "Beside", "Routed"} kept := make([]string, 0, len(names)) for _, name := range names { - td := typeByName(doc, name) - assert.Nil(t, discriminatorIn(td), "%s holds none", name) - assert.Equal(t, ir.ReasonDegradedLowering, td.Common().Unmodeled["openapi:discriminator"].Reason, name) - assert.Empty(t, td.Common().Provenance.Inferred, "%s: nothing is inferred", name) + typeDef := typeByName(doc, name) + assert.Nil(t, discriminatorIn(typeDef), "%s holds none", name) + assert.Equal(t, ir.ReasonDegradedLowering, typeDef.Common().Unmodeled["openapi:discriminator"].Reason, name) + assert.Empty(t, typeDef.Common().Provenance.Inferred, "%s: nothing is inferred", name) kept = append(kept, "info "+diag.DegradedConstruct+" /components/schemas/"+name+": this position "+ - "lowered to a "+string(td.Kind())+" routed by no tag (the IR's PropertyName cannot hold the empty "+ + "lowered to a "+string(typeDef.Kind())+" routed by no tag (the IR's PropertyName cannot hold the empty "+ "name its discriminator gives the tag property), which has no home for discriminator declared "+ "beside it; kept verbatim under Unmodeled") } @@ -417,10 +427,10 @@ func TestDiscriminator_AnEmptyPropertyNameBesideAnUntaggedUnionIsKeptForItsNode( } } -// discriminatorIn returns the discriminator the model or union td holds, or -// nil for none or another kind. -func discriminatorIn(td ir.TypeDef) *ir.Discriminator { - switch n := td.(type) { +// discriminatorIn returns the discriminator the model or union typeDef holds, +// or nil for none or another kind. +func discriminatorIn(typeDef ir.TypeDef) *ir.Discriminator { + switch n := typeDef.(type) { case *ir.Model: return n.Discriminator case *ir.Union: diff --git a/compilers/openapi/internal/schema/disjointwords.go b/compilers/openapi/internal/schema/disjointwords.go new file mode 100644 index 000000000..2f23b88ac --- /dev/null +++ b/compilers/openapi/internal/schema/disjointwords.go @@ -0,0 +1,147 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "strconv" + "strings" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/value" + "github.com/dexpace/morphic/ir" +) + +// maxNamedMembers bounds the members a report names of one value set; it +// counts the rest. +const maxNamedMembers = 5 + +// writtenSet returns the keyword and members of the value set schemaStatement +// writes, its enum before its const, read through the $refs it lands on; false +// where none of them writes one. +func writtenSet(loweringContext lowering.Ctx, schemaStatement *statement.Statement) (string, []*yaml.Node, bool) { + for hops := 0; schemaStatement != nil && schemaStatement.Truth == statement.Stated && hops < maxAdmissionReads; hops++ { + if enumWritten(schemaStatement.Schema) { + return "enum", schemaStatement.Enum(), true + } + if constant := schemaStatement.Const(); constant != nil { + return "const", []*yaml.Node{constant}, true + } + schemaStatement, _ = declaredOf(loweringContext, schemaStatement) + } + return "", nil, false +} + +// setWords spells a value set written under keyword with members, for a +// conjunct named otherwise: the keyword, then the members (membersWords). +func setWords(keyword string, members []*yaml.Node) string { + return keyword + " " + membersWords(keyword, members) +} + +// membersWords spells the members of a value set written under keyword: a +// const by its value, an enum by its first maxNamedMembers members in brackets, +// counting the rest. +func membersWords(keyword string, members []*yaml.Node) string { + if keyword == "const" { + return memberText(members[0]) + } + shown := members[:min(len(members), maxNamedMembers)] + texts := make([]string, 0, len(shown)+1) + for _, member := range shown { + texts = append(texts, memberText(member)) + } + if rest := len(members) - len(shown); rest > 0 { + texts = append(texts, "… "+strconv.Itoa(rest)+" more") + } + return "[" + strings.Join(texts, ", ") + "]" +} + +// memberText spells one member of a value set, a scalar as an enum member's +// finding names it. +func memberText(node *yaml.Node) string { + member, err := value.FromNode(node) + switch { + case err == nil && member.Kind == ir.ValueList: + return "[…]" + case err == nil && member.Kind == ir.ValueObject: + return "{…}" + default: + return describeEntry(enumEntry{node: node, err: err, val: member}) + } +} + +// fixedWords spells the value set schemaStatement, a conjunct of a disjoint +// report, holds as read: by the members it writes, else, where it is held +// another way, as by an allOf of sets, by its size. A union of sets on an +// entry is the union's to report (readLoweredUnion), so none is read here. +func fixedWords(loweringContext lowering.Ctx, schemaStatement *statement.Statement, read admitted) string { + if keyword, members, ok := writtenSet(loweringContext, schemaStatement); ok { + return setWords(keyword, members) + } + return "a value set of size " + strconv.Itoa(read.size()) +} + +// branchSetWords spells the members of the value sets the branches of one +// union write, in branch order; false where some branch writes none, or none +// holds a member. +func branchSetWords(loweringContext lowering.Ctx, branches []statement.Subschema) (string, bool) { + var members []*yaml.Node + for _, branch := range branches { + _, set, ok := writtenSet(loweringContext, loweringContext.Statements().Subschema(branch)) + if !ok { + return "", false + } + members = append(members, set...) + } + return "one of " + membersWords("enum", members), len(members) > 0 +} + +// atomWords spells what atom, a conjunct of a disjoint report admitting some +// value, states. The keywords beside the allOf are named by their keyword +// already (valueSetAtom), so their value set is spelt by its members alone. +func atomWords(loweringContext lowering.Ctx, atom conjunctAtom) string { + switch { + case atom.schemaStatement == nil && atom.written != nil && atom.keywordsSchema != nil: + _, keyword := splitConjunctName(atom.name) + if keyword == "const" { + return membersWords(keyword, []*yaml.Node{atom.keywordsSchema.Const()}) + } + return membersWords("enum", atom.keywordsSchema.Enum()) + case atom.schemaStatement != nil: + if keyword, members, ok := writtenSet(loweringContext, atom.schemaStatement); ok { + return setWords(keyword, members) + } + } + return instanceWords(atom.admits) +} + +// unionWords spells what a union of branches, read as read, admits for a +// disjoint report. +func unionWords(loweringContext lowering.Ctx, branches []statement.Subschema, read admitted) string { + if read.fixed { + if words, ok := branchSetWords(loweringContext, branches); ok { + return words + } + return "a value set of size " + strconv.Itoa(read.size()) + } + return readWords(read) +} + +// deadBranchWords spells what schemaStatement, a branch a report names dead, +// admits. +func deadBranchWords(loweringContext lowering.Ctx, schemaStatement *statement.Statement) string { + if keyword, members, ok := writtenSet(loweringContext, schemaStatement); ok { + return setWords(keyword, members) + } + switch kinds, _ := lowersTo(loweringContext, schemaStatement); { + case kinds != 0: + return instanceWords(kinds) + case nullAnswerReadingsOf(loweringContext, schemaStatement).mayAdmit(loweringContext): + return "null" + default: + return noValue + } +} diff --git a/compilers/openapi/internal/schema/drafts_test.go b/compilers/openapi/internal/schema/drafts_test.go index 32cf7ff00..ce363e9b7 100644 --- a/compilers/openapi/internal/schema/drafts_test.go +++ b/compilers/openapi/internal/schema/drafts_test.go @@ -56,14 +56,14 @@ func TestLower_AListOfItemsInADraftIsATuple(t *testing.T) { assert.Equal(t, ir.TypeID("type/primitive/any"), irList.ElementType.Target) } -// TestPreserveUnknownKeywords_ReadsWhatADraftSpellsOtherwise pins what the +// TestKeepUnknownKeywords_ReadsWhatADraftSpellsOtherwise pins what the // census keeps of a draft 4 schema: additionalItems nothing where the tuple // holds it as its rest, and where the position lowered to no tuple, verbatim // beside its list of items as a degraded lowering, as the twin `items` beside // `prefixItems` is, but beside an `items` that is no list as an unknown // keyword; `dependencies` as a validation-only keyword; `id` as `$id` is kept; // and `definitions` nothing, as `$defs` is not. -func TestPreserveUnknownKeywords_ReadsWhatADraftSpellsOtherwise(t *testing.T) { +func TestKeepUnknownKeywords_ReadsWhatADraftSpellsOtherwise(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( " T: {"+d4+", type: array, items: [{type: string}], additionalItems: false}\n"+ diff --git a/compilers/openapi/internal/schema/dryrun_test.go b/compilers/openapi/internal/schema/dryrun_test.go new file mode 100644 index 000000000..a9f5a33f0 --- /dev/null +++ b/compilers/openapi/internal/schema/dryrun_test.go @@ -0,0 +1,152 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "slices" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestAliasDryRun_APrincipalsDiscriminatorKeysRemain holds the alias set up +// for an inline principal's position to what the position keeps on it of the +// principal's discriminator: an extension it keeps makes the alias remain +// though the discriminator whole cannot be kept, and one no JSON value holds is +// reported once where no alias remains, at items and at a component. +func TestAliasDryRun_APrincipalsDiscriminatorKeysRemain(t *testing.T) { + t.Parallel() + const principal = "{allOf: [{type: string, discriminator: {propertyName: k, %s}}]}" + kept := openapitest.ComponentSpecVer("3.1.0", " S: {type: array, items: {allOf: [{type: string, "+ + "discriminator: {propertyName: k, x-k: 1, mapping: {a: .nan}}}]}}\n") + doc, _ := parseFull(t, kept) + alias, hoisted := doc.Types["type/anonymous/components/schemas/S/items"] + if assert.True(t, hoisted, "the extension kept makes the alias remain") { + assert.Contains(t, alias.Common().Unmodeled, "openapi:discriminator/x-k") + } + + for name, at := range map[string]string{ + "items": " S: {type: array, items: " + principal + "}\n", + "component": " S: " + principal + "\n", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + src := openapitest.ComponentSpecVer("3.1.0", fmt.Sprintf(at, "x-k: .nan")) + _, diags := parseFull(t, src) + var warnings int + for _, diagnostic := range diags { + if diagnostic.Code == diag.DegradedConstruct && diagnostic.Message == `extension "x-k" could not be serialized` { + warnings++ + } + } + assert.Equal(t, 1, warnings, "the extension no JSON value holds is reported once") + }) + } +} + +// TestAliasDryRun_AUseHomeOverAnObjectIsAModel holds the home a use of an +// object hoists, where nothing beside its reference is read but a keyword a +// node keeps, to the Model composing the object, built once and holding it. +func TestAliasDryRun_AUseHomeOverAnObjectIsAModel(t *testing.T) { + t.Parallel() + src := openapitest.ComponentSpecVer("3.1.0", " T: {type: object, properties: {t: {type: string}}}\n"+ + " S: {type: array, items: {allOf: [{$ref: '#/components/schemas/T'}], unknownWord: null}}\n") + doc, _ := parseFull(t, src) + home, hoisted := doc.Types["type/anonymous/components/schemas/S/items"] + require.True(t, hoisted, "the kept keyword needs a home") + model, isModel := home.(*ir.Model) + require.True(t, isModel, "no Scalar sits over a model") + require.NotNil(t, model.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/T"), model.Base.Target) + assert.Contains(t, model.Unmodeled, "openapi:unknownWord") +} + +// TestAliasDryRun_ARevisitReportsNothingTwice holds a response's schema, which +// each operation using the response lowers, to one alias and one report of +// the keyword it keeps unread, under an inline principal or not. +func TestAliasDryRun_ARevisitReportsNothingTwice(t *testing.T) { + t.Parallel() + const operation = " get:\n responses: {'200': {$ref: '#/components/responses/R'}}\n" + for name, schema := range map[string]string{ + "its own position": "{type: string, required: [a]}", + "an inline principal": "{allOf: [{type: string, required: [a]}]}", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + src := "openapi: 3.1.0\ninfo: {title: T, version: '1'}\npaths:\n /a:\n" + operation + " /b:\n" + operation + + "components:\n responses:\n R:\n description: r\n content: {text/plain: {schema: " + schema + "}}\n" + doc, diags := parseFull(t, src) + alias, hoisted := doc.Types["type/anonymous/components/responses/R/content/text~1plain/schema"] + require.True(t, hoisted) + assert.Contains(t, alias.Common().Unmodeled, "openapi:required") + var reports int + for _, diagnostic := range diags { + if diagnostic.Code == diag.DegradedConstruct && strings.Contains(diagnostic.Message, "no home for required") { + reports++ + } + } + assert.Equal(t, 1, reports) + }) + } +} + +// TestAliasDryRun_ADynamicReferenceOverAnObjectComposesIt holds the home an +// expanded dynamic reference to an object hoists, at a position no carrier +// holds and at a component, to the Model composing that object, as a $ref +// there makes, never a Scalar over it; one holding nothing hoists none. +func TestAliasDryRun_ADynamicReferenceOverAnObjectComposesIt(t *testing.T) { + t.Parallel() + src := openapitest.ComponentSpecVer("3.1.0", " T: {$dynamicAnchor: t, type: object, properties: {a: {type: string}}}\n"+ + " S: {type: array, items: {$dynamicRef: '#t', description: d}}\n"+ + " E: {type: array, items: {$dynamicRef: '#t', example: .nan}}\n"+ + " C: {$dynamicRef: '#t', description: c}\n") + doc, _ := parseFull(t, src) + for _, id := range []ir.TypeID{"type/anonymous/components/schemas/S/items", "type/openapi/components/schemas/C"} { + model, isModel := doc.Types[id].(*ir.Model) + if assert.True(t, isModel, "%s: no Scalar sits over a model", id) { + require.NotNil(t, model.Base, id) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/T"), model.Base.Target, id) + assert.NotEmpty(t, model.Docs.Description, id) + } + } + assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/E/items"), "a home holding nothing is hoisted nowhere") +} + +// TestAliasDryRun_ADynamicReferenceComposesAsItsRefTwin holds an expanded +// dynamic reference to an object, beside each keyword a Model homes (a +// discriminator, unevaluatedProperties, notes and bounds) or one it keeps, to +// its $ref twin, at items and at a component: the two compile to the same +// types and the same findings but the expansion's own report. +func TestAliasDryRun_ADynamicReferenceComposesAsItsRefTwin(t *testing.T) { + t.Parallel() + const head = " T: {$dynamicAnchor: t, type: object, properties: {a: {type: string}}}\n" + for _, beside := range []string{ + "discriminator: {propertyName: a}", "unevaluatedProperties: false", "unevaluatedProperties: {type: string}", + "description: d", "title: X", "deprecated: true", "examples: [{a: b}]", "xml: {name: n}", + "externalDocs: {url: 'https://example.com'}", "minProperties: 1", "maxProperties: 3", "format: uuid", + } { + t.Run(beside, func(t *testing.T) { + t.Parallel() + document := func(reference string) string { + use := "{" + reference + ", " + beside + "}" + return openapitest.ComponentSpecVer("3.1.0", head+" S: {type: array, items: "+use+"}\n C: "+use+"\n") + } + dynamicDoc, dynamicDiags := parseFull(t, document("$dynamicRef: '#t'")) + refDoc, refDiags := parseFull(t, document("$ref: '#/components/schemas/T'")) + assert.Empty(t, cmp.Diff(refDoc.Types, dynamicDoc.Types), "the expansion composes as the $ref does") + withoutExpansion := slices.DeleteFunc(slices.Clone(dynamicDiags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code == diag.DynamicRefExpanded + }) + assert.Empty(t, cmp.Diff(reported(refDiags), reported(withoutExpansion)), "and reports alike") + }) + } +} diff --git a/compilers/openapi/internal/schema/dynamicref.go b/compilers/openapi/internal/schema/dynamicref.go index ca6c2d88c..c6b9f498c 100644 --- a/compilers/openapi/internal/schema/dynamicref.go +++ b/compilers/openapi/internal/schema/dynamicref.go @@ -66,9 +66,10 @@ func dynamicTarget(loweringContext lowering.Ctx, schema *statement.Schema, point // (dynamicTargetOf), read against the anchors of the document it is written // in, so one another document holds names its own (GitHub #762), and it is what // a $ref to that position resolves to (resolvesAt). One closing a cycle of -// expansions is irreducible (dynamicChainVerdict). One naming no +// expansions is irreducible (dynamicChainAnswer). One naming no // $dynamicAnchor is a reference site (typed.Bindings.RefKeyword). func dynamicExpansion(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (at reftable.DocumentPointer, why string, ok bool) { + schema, pointer = dynamicRefConjunct(loweringContext, schema, pointer) ref, why, ok := expandableRef(loweringContext, schema, pointer) if !ok { return reftable.DocumentPointer{}, why, false @@ -77,12 +78,57 @@ func dynamicExpansion(loweringContext lowering.Ctx, schema *statement.Schema, po if at, why, ok = dynamicTargetOf(loweringContext, ref, from); !ok { return reftable.DocumentPointer{}, why, false } - if why, ok = dynamicChainVerdict(loweringContext, at, from); !ok { + if why, ok = dynamicChainAnswer(loweringContext, at, from); !ok { return reftable.DocumentPointer{}, why, false } + if narrowsExpansionToNull(loweringContext, schema, at) { + return reftable.DocumentPointer{}, "it is co-declared with value keywords narrowing it to null, which the IR cannot intersect with it", false + } return at, "", true } +// narrowsExpansionToNull reports whether the value keywords beside schema's +// dynamic reference, expanding to at, narrow it to null, which no expansion +// carries: they say null alone, and the nullable-inference policy does not +// read them as its reference-or-null idiom (nullIdiomConsumes). +func narrowsExpansionToNull(loweringContext lowering.Ctx, schema *statement.Schema, at reftable.DocumentPointer) bool { + if !declaresNullAlone(loweringContext, schema) { + return false + } + target := loweringContext.Statements().At(at) + consumed := idiomWidens(loweringContext, loweringContext.Statements().Read(schema), true) && target != nil && + nullAnswerReadingsOf(loweringContext, target).forbids(loweringContext) + return !consumed +} + +// dynamicRefConjunct returns the schema writing the dynamic reference schema, +// written at pointer, expands through, and where it is written: schema itself, +// or down the one entry each allOf holds in place (entryInPlace, +// docs/compilers/openapi.md#dynamic-ref), at most statement.MaxFlattenDepth +// deep, as flattening nests. +func dynamicRefConjunct(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (*statement.Schema, jsontext.Pointer) { + for range statement.MaxFlattenDepth + 1 { + if declaresDynamicRef(schema) || !entryInPlace(schema) { + break + } + schema, pointer = loweringContext.Statements().Subschema(schema.AllOf[0]).Schema, pointer+ids.Ptr("allOf", "0") + } + return schema, pointer +} + +// expandsInPlace reports whether schema expands the dynamic reference the one +// entry its allOf holds in place writes (dynamicRefConjunct), read at its own +// site, so its allOf neither composes nor refines: it is that expansion. +func expandsInPlace(loweringContext lowering.Ctx, schema *statement.Schema) bool { + at, placed := siteOf(schema) + if !placed || declaresDynamicRef(schema) || !entryInPlace(schema) { + return false + } + in, _ := lowering.InDocument(loweringContext, at.Doc) + _, _, expanded := dynamicExpansion(in, schema, at.Pointer) + return expanded +} + // expandableRef returns the dynamic reference schema, read at pointer, writes, // or why none can expand: none is written, it is co-declared with what an // expansion cannot carry, or its value is no string. @@ -91,7 +137,7 @@ func expandableRef(loweringContext lowering.Ctx, schema *statement.Schema, point switch { case !ok: return dynamicRef{}, "no dynamic reference is written here", false - case dynamicRefSiblings(schema): + case dynamicRefSiblings(schema) && !nullKeywordsAlone(loweringContext, schema): return dynamicRef{}, "it is co-declared with another applicator, which the IR cannot intersect with it", false case ref.node.Kind != yaml.ScalarNode: return dynamicRef{}, "its value is not a reference string", false @@ -104,7 +150,7 @@ func expandableRef(loweringContext lowering.Ctx, schema *statement.Schema, point // from, names, or why it names none that expands: for a $dynamicRef the one // $dynamicAnchor of its name its document declares, in its own resource, and // for a $recursiveRef the root of its resource (recursiveTarget); each where a -// schema stands to resolve to. +// schema is to resolve to. func dynamicTargetOf(loweringContext lowering.Ctx, ref dynamicRef, from reftable.DocumentPointer) (reftable.DocumentPointer, string, bool) { if ref.keyword == "$recursiveRef" { return recursiveTarget(loweringContext, ref.node.Value, from) @@ -186,6 +232,15 @@ func recursiveScope(loweringContext lowering.Ctx, root reftable.DocumentPointer) } } +// nullKeywordsAlone reports whether what schema writes beside its dynamic +// reference is value keywords saying null alone (declaresNullAlone), which the +// expansion reads as the nullable-inference policy's idiom or as narrowing it +// to null (narrowsExpansionToNull). +func nullKeywordsAlone(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return declaresNullAlone(loweringContext, schema) && !refWritten(schema) && !declaresUnion(schema) && + !writesSiblingKeyword(schema, "type", "const", "enum") +} + // dynamicRefSiblings reports whether schema writes anything beside its // $dynamicRef that the expansion would have to intersect with. JSON Schema // conjoins keywords and the IR has no node that intersects a reference with a @@ -228,15 +283,15 @@ func soleAnchorSite(loweringContext lowering.Ctx, name string) (reftable.Documen } } -// dynamicChainVerdict reports whether from may take the expansion to the anchor +// dynamicChainAnswer reports whether from may take the expansion to the anchor // declared at at, following the target's own expansions in turn, and the // chain of each reference site it meets (dynamicHop). A chain returning to // from would make the position's own type its base, a loop no emitter can -// resolve; every member of such a cycle reaches this verdict independently, +// resolve; every member of such a cycle reaches this answer independently, // so the whole cycle is preserved. // // The loop is bounded: each turn returns or adds a position to seen. -func dynamicChainVerdict(loweringContext lowering.Ctx, at, from reftable.DocumentPointer) (string, bool) { +func dynamicChainAnswer(loweringContext lowering.Ctx, at, from reftable.DocumentPointer) (string, bool) { seen := map[reftable.DocumentPointer]bool{} for cur := at; !seen[cur]; { if cur == from { @@ -281,7 +336,7 @@ func sameResource(loweringContext lowering.Ctx, from, at reftable.DocumentPointe // else ends the chain: a position that lowers to a shape rather than to // another reference cannot extend a cycle of references. func dynamicHop(loweringContext lowering.Ctx, at reftable.DocumentPointer) (reftable.DocumentPointer, bool) { - if referenceSite, ok := loweringContext.Bindings().Table().Entry(at); ok { + if referenceSite, ok := loweringContext.Bindings().Table().ReferenceSiteAt(at); ok { return referenceSite.Chain.End, referenceSite.Chain.Status == reftable.Resolved } schema := annotation.At(loweringContext.Statements().At(at)).Node @@ -303,33 +358,77 @@ func dynamicHop(loweringContext lowering.Ctx, at reftable.DocumentPointer) (reft // position's type and must not also be preserved — that would tell a consumer // the compiler ignored it — and one schema is a reference site under // (typed.Bindings.RefKeyword) is the $ref it spells, resolved as one. -func recordUnexpandedDynamicRef(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - ref, written := dynamicRefOf(loweringContext, schema, pointer) - if !written || schema.Ref != nil && schema.Ref.Keyword == ref.keyword { +func recordUnexpandedDynamicRef(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) annotation.KeptReports { + ref, why, unexpanded := unexpandedDynamicRef(loweringContext, schema, pointer) + if !unexpanded { return nil } - _, why, expanded := dynamicExpansion(loweringContext, schema, pointer) - if expanded { - return nil - } - kept, diags := preserveSchemaKeyword(loweringContext, unmodeled, schema, ref.keyword, ir.ReasonDegradedLowering, pointer) + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, schema, ref.keyword, ir.ReasonDegradedLowering, pointer) if kept { diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer+ids.Ptr(ref.keyword), "%s was not expanded because %s; it is kept verbatim under Unmodeled", ref.keyword, why)) } - return diags + return annotation.ReportsOf(annotation.EntryKey("", ref.keyword), diags...) +} + +// unexpandedDynamicRef returns the dynamic reference schema writes at pointer +// that recordUnexpandedDynamicRef keeps, and why it was not expanded. +func unexpandedDynamicRef(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (dynamicRef, string, bool) { + ref, written := dynamicRefOf(loweringContext, schema, pointer) + if !written || schema.Ref != nil && schema.Ref.Keyword == ref.keyword { + return dynamicRef{}, "", false + } + if _, why, expanded := dynamicExpansion(loweringContext, schema, pointer); !expanded { + return ref, why, true + } + return dynamicRef{}, "", false } // dynamicExpanded reports the expansion of the dynamic reference schema writes -// at pointer to target, at the keyword it is written as. +// at pointer to target, at the keyword it is written as, naming the context +// that reached it where an allOf entry is read alone (readAlone). func dynamicExpanded(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeID) ir.Diagnostic { + reached := readAlone(loweringContext, schema) + schema, pointer = dynamicRefConjunct(loweringContext, schema, pointer) ref, _ := dynamicRefOf(loweringContext, schema, pointer) what := "the one matching $dynamicAnchor in this document" if ref.keyword == "$recursiveRef" { what = "the root of the schema resource it is written in" } - return loweringContext.DiagAt(ir.SeverityInfo, diag.DynamicRefExpanded, pointer+ids.Ptr(ref.keyword), "%s expanded to %q, %s", - ref.keyword, target, what) + return loweringContext.DiagAt(ir.SeverityInfo, diag.DynamicRefExpanded, pointer+ids.Ptr(ref.keyword), "%s%s expanded to %q, %s", + ref.keyword, reached, target, what) +} + +// readAlone returns how a report on schema names the context reading it where +// schema is an allOf entry also lowered as a position of its own: as the target +// of the least $ref landing on it, or of a reference where none does; "" for +// any other schema. +func readAlone(loweringContext lowering.Ctx, schema *statement.Schema) string { + at, placed := siteOf(schema) + if !placed || at.Pointer.Parent().LastToken() != "allOf" { + return "" + } + if site, ok := firstReferrers(loweringContext)[at]; ok { + return fmt.Sprintf(", read alone as the target of the $ref at %q,", site.Pointer) + } + return ", read alone as the target of a reference," +} + +// referrersOfRun keys the run's index of the $refs landing on each position. +type referrersOfRun struct{} + +// firstReferrers returns, by the position each lands on, the least site of a +// $ref the run's table holds landing there, read once a run. +func firstReferrers(loweringContext lowering.Ctx) map[reftable.DocumentPointer]reftable.DocumentPointer { + return lowering.ReadOncePerRun(loweringContext, referrersOfRun{}, func() map[reftable.DocumentPointer]reftable.DocumentPointer { + out := map[reftable.DocumentPointer]reftable.DocumentPointer{} + for _, entry := range loweringContext.Bindings().Table().ReferenceSites() { + if _, seen := out[entry.Hop.Target]; entry.Lands() && !seen { + out[entry.Hop.Target] = entry.Site + } + } + return out + }) } // declaresDynamicRef reports whether schema writes a $dynamicRef or a diff --git a/compilers/openapi/internal/schema/dynamicref_entry_test.go b/compilers/openapi/internal/schema/dynamicref_entry_test.go index ad3610cd9..620d01abd 100644 --- a/compilers/openapi/internal/schema/dynamicref_entry_test.go +++ b/compilers/openapi/internal/schema/dynamicref_entry_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) @@ -24,14 +25,14 @@ type dynamicSpelling struct { Value string } -// dynamicSpellingOf reads td as dynamicSpelling does. -func dynamicSpellingOf(t *testing.T, td ir.TypeDef) dynamicSpelling { +// dynamicSpellingOf reads typeDef as dynamicSpelling does. +func dynamicSpellingOf(t *testing.T, typeDef ir.TypeDef) dynamicSpelling { t.Helper() - require.NotNil(t, td) - kept, ok := td.Common().Unmodeled["openapi:$dynamicRef"] - require.True(t, ok, "no $dynamicRef kept on %s", td.Common().ID) - out := dynamicSpelling{Kind: td.Kind(), Reason: kept.Reason, Value: string(kept.Value)} - switch n := td.(type) { + require.NotNil(t, typeDef) + kept, ok := typeDef.Common().Unmodeled["openapi:$dynamicRef"] + require.True(t, ok, "no $dynamicRef kept on %s", typeDef.Common().ID) + out := dynamicSpelling{Kind: typeDef.Kind(), Reason: kept.Reason, Value: string(kept.Value)} + switch n := typeDef.(type) { case *ir.Model: if n.Base != nil { out.Base = n.Base.Target @@ -77,3 +78,32 @@ func TestDynamicRefEntry_OnAnEntryLowersAsBesideTheAllOf(t *testing.T) { } } } + +// TestDynamicRefEntry_EachReportNamesTheReadingThatDrewIt pins the two reports +// an allOf entry's $dynamicRef draws where its composition keeps it and a +// reference reads the entry alone, expanding it: each names its reading, the +// entry of the allOf and the target of the least $ref landing on the entry, or +// of a reference where a discriminator's mapping alone names it, so the two do +// not contradict (docs/compilers/openapi.md#allof-refinement). +func TestDynamicRefEntry_EachReportNamesTheReadingThatDrewIt(t *testing.T) { + t.Parallel() + const anchored = " M: {$dynamicAnchor: m, type: object, properties: {k: {type: string}}}\n" + + " Q: {allOf: [{type: object, properties: {a: {type: string}}}, {$dynamicRef: '#m'}]}\n" + for _, testCase := range []struct { + name, reader, reading string + }{ + {"by two $refs", " Z: {$ref: '#/components/schemas/Q/allOf/1'}\n Y: {$ref: '#/components/schemas/Q/allOf/1'}\n", + `read alone as the target of the $ref at "/components/schemas/Y", expanded to`}, + {"by a mapping", " U: {type: object, properties: {k: {type: string}}, discriminator: {propertyName: k, " + + "mapping: {x: '#/components/schemas/Q/allOf/1'}}}\n", "read alone as the target of a reference, expanded to"}, + } { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", anchored+testCase.reader)) + at := "/components/schemas/Q/allOf/1/$dynamicRef" + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DynamicRefExpanded, ir.SeverityInfo, at), testCase.reading) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), + "read as an entry of this allOf, was not expanded") + }) + } +} diff --git a/compilers/openapi/internal/schema/dynamicref_internal_test.go b/compilers/openapi/internal/schema/dynamicref_internal_test.go index 061d3fb98..6c9d4263a 100644 --- a/compilers/openapi/internal/schema/dynamicref_internal_test.go +++ b/compilers/openapi/internal/schema/dynamicref_internal_test.go @@ -27,19 +27,19 @@ import ( // deepMergeSpec holds a schema in its document's resource, one under an $id, and // one merging through a chain past the view's bound, built rather than spelled -// since it is 70 links long. +// since it is 70 hops long. var deepMergeSpec = func() string { - var b strings.Builder - b.WriteString("openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\nx-c0: &c0 {$id: 'https://x.test/deep'}\n") + var builder strings.Builder + builder.WriteString("openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\nx-c0: &c0 {$id: 'https://x.test/deep'}\n") for i := 1; i <= 70; i++ { - fmt.Fprintf(&b, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) + fmt.Fprintf(&builder, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) } - b.WriteString("components:\n schemas:\n Plain: {type: string}\n") - b.WriteString(" Held: {$id: 'https://x.test/held', $defs: {d: {type: string}}}\n Deep: {<<: *c70}\n") - return b.String() + builder.WriteString("components:\n schemas:\n Plain: {type: string}\n") + builder.WriteString(" Held: {$id: 'https://x.test/held', $defs: {d: {type: string}}}\n Deep: {<<: *c70}\n") + return builder.String() }() -// TestSameResource_SaysWhyTwoPositionsMayLieInTwo pins the verdict's three +// TestSameResource_SaysWhyTwoPositionsMayLieInTwo pins the answer's three // answers: two schemas in one resource, their document's or one an $id starts, // two an $id between puts in two, and one a merge past the bound may hide an // identifier above, which must not read as none. @@ -47,7 +47,7 @@ func TestSameResource_SaysWhyTwoPositionsMayLieInTwo(t *testing.T) { t.Parallel() lowerer, diags := LoweredFor(t, deepMergeSpec) openapitest.RequireNoErrorDiags(t, diags) - for _, tc := range []struct { + for _, testCase := range []struct { from, at jsontext.Pointer want string }{ @@ -58,9 +58,9 @@ func TestSameResource_SaysWhyTwoPositionsMayLieInTwo(t *testing.T) { {"/components/schemas/Deep", "/components/schemas/Plain", "may hide an identifier"}, {"/components/schemas/Plain", "/components/schemas/Deep", "may hide an identifier"}, } { - why, ok := sameResource(lowerer.Ctx, reftable.DocumentPointer{Pointer: tc.from}, reftable.DocumentPointer{Pointer: tc.at}) - assert.Equal(t, tc.want == "", ok, "%s %s", tc.from, tc.at) - assert.Contains(t, why, tc.want, "%s %s", tc.from, tc.at) + why, ok := sameResource(lowerer.Ctx, reftable.DocumentPointer{Pointer: testCase.from}, reftable.DocumentPointer{Pointer: testCase.at}) + assert.Equal(t, testCase.want == "", ok, "%s %s", testCase.from, testCase.at) + assert.Contains(t, why, testCase.want, "%s %s", testCase.from, testCase.at) } two, diags := LoweredFor(t, openapitest.ComponentSpec(" A: {$id: 'https://x.test/a', $defs: {d: {}}}\n"+ " B: {$id: 'https://x.test/b', $defs: {d: {}}}\n")) @@ -71,7 +71,7 @@ func TestSameResource_SaysWhyTwoPositionsMayLieInTwo(t *testing.T) { } // TestDynamicHop_HopsOnlyWhenExactlyOneAnchorSiteIsNamed pins every way the -// chain walk can stop, since a wrong verdict either expands what it should +// chain walk can stop, since a wrong answer either expands what it should // refuse or refuses what it should expand (#202). // // A hop needs a schema at the position, a $dynamicRef written on it, and @@ -119,25 +119,25 @@ func TestDynamicHop_HopsOnlyWhenExactlyOneAnchorSiteIsNamed(t *testing.T) { wantNext: "/components/schemas/A", }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - lowerer, diags := LoweredFor(t, openapitest.ComponentSpec(tc.schemas)) + lowerer, diags := LoweredFor(t, openapitest.ComponentSpec(testCase.schemas)) openapitest.RequireNoErrorDiags(t, diags) - if tc.anchor != "" { - require.Equal(t, tc.wantSites, lowerer.Ctx.DynamicAnchor(tc.anchor).Count, + if testCase.anchor != "" { + require.Equal(t, testCase.wantSites, lowerer.Ctx.DynamicAnchor(testCase.anchor).Count, "the fixture must set up the case it is named for") } - next, hops := dynamicHop(lowerer.Ctx, reftable.DocumentPointer{Pointer: tc.at}) + next, hops := dynamicHop(lowerer.Ctx, reftable.DocumentPointer{Pointer: testCase.at}) - assert.Equal(t, tc.wantNext != "", hops) - assert.Equal(t, tc.wantNext, next.Pointer) + assert.Equal(t, testCase.wantNext != "", hops) + assert.Equal(t, testCase.wantNext, next.Pointer) }) } } -// TestResolvesAt_AnswersAsResolvePointerDoes pins that the verdict an +// TestResolvesAt_AnswersAsResolvePointerDoes pins that the answer an // expansion asks is resolvePointer's own, at every landing the bindings of the // dynamic-ref and schema-identifiers cases make, and at each site and target // of their $refs. @@ -153,7 +153,7 @@ func TestResolvesAt_AnswersAsResolvePointerDoes(t *testing.T) { for _, landing := range table.Landings() { positions = append(positions, landing.At) } - for _, referenceSite := range table.Entries() { + for _, referenceSite := range table.ReferenceSites() { positions = append(positions, referenceSite.Site, referenceSite.Hop.Target) } for _, at := range positions { @@ -191,9 +191,9 @@ func TestBases_AnUnknownBaseIsNoMatch(t *testing.T) { assert.ElementsMatch(t, []jsontext.Pointer{"/components/schemas/Deep/properties/p/items", "/components/schemas/Deep/allOf/0/not"}, unresolved, "%+v", diags) at := func(name string) *oas3.JSONSchema[oas3.Referenceable] { - js := lowerer.Ctx.Bindings().At(reftable.DocumentPointer{Pointer: jsontext.Pointer("/components/schemas/" + name + "/properties/p")}) - require.NotNil(t, js, name) - return js + schemaRef := lowerer.Ctx.Bindings().At(reftable.DocumentPointer{Pointer: jsontext.Pointer("/components/schemas/" + name + "/properties/p")}) + require.NotNil(t, schemaRef, name) + return schemaRef } entry := func(name string) allOfEntry { schema := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Pointer: jsontext.Pointer("/components/schemas/" + name)}).Schema @@ -202,14 +202,14 @@ func TestBases_AnUnknownBaseIsNoMatch(t *testing.T) { prov := func(name string) ir.Provenance { return lowerer.Ctx.Place().At(jsontext.Pointer("/components/schemas/" + name + "/properties/p")) } - fields := modelFields{c: lowerer.Ctx} + fields := modelFields{loweringContext: lowerer.Ctx, types: lowerer.Types} assert.True(t, sameText(lowerer.Ctx, lowerer.Ctx.Statements().Of(at("Plain")), lowerer.Ctx.Statements().Of(at("Twin")))) assert.False(t, sameText(lowerer.Ctx, lowerer.Ctx.Statements().Of(at("Plain")), lowerer.Ctx.Statements().Of(at("Deep")))) assert.True(t, readsAtPosition(lowerer.Ctx, entry("Plain"))) assert.False(t, readsAtPosition(lowerer.Ctx, entry("Deep"))) - assert.True(t, fields.Alike(prov("Plain"), prov("Twin"))) - assert.False(t, fields.Alike(prov("Plain"), prov("Deep"))) + assert.True(t, fields.DeclarationsAdmitAlike(prov("Plain"), prov("Twin"))) + assert.False(t, fields.DeclarationsAdmitAlike(prov("Plain"), prov("Deep"))) } // TestUnresolvedRoot_SaysWhatHoldsNoSchema pins why a $recursiveRef whose @@ -221,7 +221,7 @@ func TestUnresolvedRoot_SaysWhatHoldsNoSchema(t *testing.T) { assert.Equal(t, `"#" names "/x", where no schema could be built`, unresolvedRoot(reftable.DocumentPointer{Doc: 1, Pointer: "/x"})) } -// TestResolvesAt_ResolvesNothingInADocumentTheCompileDidNotRead pins the verdict +// TestResolvesAt_ResolvesNothingInADocumentTheCompileDidNotRead pins the answer // at a position of a document the bindings read and the compile does not list // beside the source: no reference resolves there, as resolveAt reads it. func TestResolvesAt_ResolvesNothingInADocumentTheCompileDidNotRead(t *testing.T) { @@ -233,7 +233,7 @@ func TestResolvesAt_ResolvesNothingInADocumentTheCompileDidNotRead(t *testing.T) require.NoError(t, err) require.NotNil(t, doc) read := LowererOver(service.New(0, doc, service.Policy{})) - referenceSite, ok := read.Ctx.Bindings().Table().Entry(reftable.DocumentPointer{Pointer: "/components/schemas/A"}) + referenceSite, ok := read.Ctx.Bindings().Table().ReferenceSiteAt(reftable.DocumentPointer{Pointer: "/components/schemas/A"}) require.True(t, ok) require.True(t, resolvesAt(read.Ctx, referenceSite.Hop.Target), "sanity: the document the compile read resolves") none := *doc diff --git a/compilers/openapi/internal/schema/dynamicref_test.go b/compilers/openapi/internal/schema/dynamicref_test.go index 2bb8fbed9..2d03ebbe0 100644 --- a/compilers/openapi/internal/schema/dynamicref_test.go +++ b/compilers/openapi/internal/schema/dynamicref_test.go @@ -25,7 +25,8 @@ import ( // TestDynamicRef_ExpandsAgainstTheDocumentItIsWrittenIn pins a $dynamicRef in // content another document holds: its fragment names that document's // $dynamicAnchor, so it expands there, to the type lowered where that document -// declares it, never to the source's anchor of the same name (GitHub #762). +// declares it, never to the source's anchor of the same name (GitHub #762). The +// body names that type, as a $ref there would, with no alias between. func TestDynamicRef_ExpandsAgainstTheDocumentItIsWrittenIn(t *testing.T) { t.Parallel() doc, diags, _ := compileBeside(t, map[string]string{"ext.yaml": `paths: @@ -52,11 +53,10 @@ components: require.Len(t, diags, 1) assert.Equal(t, "openapi/dynamic-ref-expanded", diags[0].Code) assert.Equal(t, ir.Provenance{Source: 1, Pointer: body + "/$dynamicRef"}, diags[0].Provenance) - held, ok := doc.Types[onlyBodyTarget(t, doc)].(*ir.Scalar) - require.True(t, ok, "the position holds an alias, as it holds one over the source's own") - require.NotNil(t, held.Base) - assert.Equal(t, other, held.Base.Target, "the source's anchor of that name is not what the reference names") - assert.Empty(t, held.Unmodeled, "an expanded reference is not kept as well") + assert.Equal(t, other, onlyBodyTarget(t, doc), "the source's anchor of that name is not what the reference names") + for id, typeDef := range doc.Types { + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:$dynamicRef", "%s: an expanded reference is not kept as well", id) + } target, ok := doc.Types[other].(*ir.Model) require.True(t, ok) assert.Equal(t, ir.Provenance{Source: 1, Pointer: "/components/schemas/Other"}, target.Provenance) @@ -119,14 +119,11 @@ func TestDynamicRef_ExpandsAgainstTheOneMatchingAnchor(t *testing.T) { kids, ok := doc.Types[ir.TypeID("type/anonymous/components/schemas/Tree/properties/kids")].(*ir.List) require.True(t, ok) - element, ok := doc.Types[kids.ElementType.Target].(*ir.Scalar) - require.True(t, ok, "the items position keeps a node of its own") - require.NotNil(t, element.Base) - assert.Equal(t, componentID("Tree"), element.Base.Target, - "a self-recursive dynamic reference terminates on the interned component ID") - - for _, td := range doc.Types { - assert.NotContains(t, td.Common().Unmodeled, "openapi:$dynamicRef", + assert.Equal(t, componentID("Tree"), kids.ElementType.Target, + "a self-recursive dynamic reference terminates on the interned component ID, as a $ref there does") + + for _, typeDef := range doc.Types { + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:$dynamicRef", "an expanded reference is the position's type; keeping it too would read as ignored") } @@ -238,17 +235,17 @@ func TestDynamicRef_IrreducibleIsKeptAndSaysWhy(t *testing.T) { wantWhy: `closes a cycle of $dynamicRef expansions back onto "/components/schemas/A"`, }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(tc.schemas)) + doc, diags := parseFull(t, openapitest.ComponentSpec(testCase.schemas)) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types[componentID("A")] + typeDef, ok := doc.Types[componentID("A")] require.True(t, ok, "the position owns a node to keep the reference on") - entry, ok := td.Common().Unmodeled["openapi:$dynamicRef"] + entry, ok := typeDef.Common().Unmodeled["openapi:$dynamicRef"] require.True(t, ok, "an irreducible $dynamicRef is kept verbatim, not dropped") assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assertDiagContains(t, diags, string(entry.Provenance.Pointer), tc.wantWhy) + assertDiagContains(t, diags, string(entry.Provenance.Pointer), testCase.wantWhy) }) } } @@ -257,13 +254,14 @@ func TestDynamicRef_IrreducibleIsKeptAndSaysWhy(t *testing.T) { // docs/compilers/openapi.md#dynamic-ref: a $dynamicRef whose fragment names no // $dynamicAnchor, as a $ref resolves it, is that $ref (JSON Schema 2020-12 // §8.2.3.2). One resolving nowhere draws the error its $ref twin draws, worded -// with its keyword, and lowers the top type, keeping nothing; a pointer -// resolves. +// with its keyword, and lowers the top type; one in a resource of its own is +// kept under openapi:$dynamicRef, the keyword written. A pointer resolves. func TestDynamicRef_NamingNoDynamicAnchorIsTheRefItSpells(t *testing.T) { t.Parallel() const anchor = " M: {$dynamicAnchor: m, type: string}\n" cases := []struct { name, schemas, ref, at, invalid string + kept bool // the $dynamicRef is kept on the node at at }{ {name: "no such anchor", schemas: " A: {$dynamicRef: '#nope'}\n", ref: "#nope"}, {name: "another document", schemas: " A: {$dynamicRef: 'other.json#m'}\n", ref: "other.json#m"}, @@ -280,16 +278,16 @@ func TestDynamicRef_NamingNoDynamicAnchorIsTheRefItSpells(t *testing.T) { schemas: " M: {$id: 'https://example.com/m', $dynamicAnchor: m, type: string}\n A: {$dynamicRef: '#m'}\n", ref: "#m"}, {name: "the reference is in a resource of its own", - schemas: anchor + " A: {$id: 'https://example.com/a', $dynamicRef: '#m'}\n", ref: "#m"}, + schemas: anchor + " A: {$id: 'https://example.com/a', $dynamicRef: '#m'}\n", ref: "#m", kept: true}, {name: "an enclosing schema starts the resource", schemas: anchor + " A: {$id: 'https://example.com/a', type: array, items: {$dynamicRef: '#m'}}\n", ref: "#m", at: "/components/schemas/A/items"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(tc.schemas)) - at := tc.at + doc, diags := parseFull(t, openapitest.ComponentSpec(testCase.schemas)) + at := testCase.at if at == "" { at = "/components/schemas/A" } @@ -304,13 +302,20 @@ func TestDynamicRef_NamingNoDynamicAnchorIsTheRefItSpells(t *testing.T) { } } want := []string{"openapi/unresolved-ref at " + at} - if tc.invalid != "" { - want = append(want, tc.invalid) + if testCase.invalid != "" { + want = append(want, testCase.invalid) } assert.ElementsMatch(t, want, errs, "%+v", diags) - assertDiagContains(t, diags, at, `unresolved $dynamicRef "`+tc.ref+`": `) - for id, td := range doc.Types { - assert.NotContains(t, td.Common().Unmodeled, "openapi:$dynamicRef", id) + assertDiagContains(t, diags, at, `unresolved $dynamicRef "`+testCase.ref+`": `) + if testCase.kept { + entry, held := doc.Types[componentID("A")].Common().Unmodeled["openapi:$dynamicRef"] + require.True(t, held, "kept under the keyword written") + assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) + assert.JSONEq(t, `"`+testCase.ref+`"`, string(entry.Value)) + return + } + for id, typeDef := range doc.Types { + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:$dynamicRef", id) } }) } @@ -327,7 +332,7 @@ func TestDynamicRef_NamingNoDynamicAnchorIsTheRefItSpells(t *testing.T) { // TestDynamicRef_AnAnchorOnlyAnotherDocumentDeclaresIsKept pins a $dynamicRef // whose fragment lands on a $dynamicAnchor of another document: it is dynamic, // and read against the declarations of the document it is written in, where -// none of its name stands, so it is kept. +// none of its name is declared, so it is kept. func TestDynamicRef_AnAnchorOnlyAnotherDocumentDeclaresIsKept(t *testing.T) { t.Parallel() doc, diags, _ := compileBeside(t, map[string]string{"ext.yaml": "$defs: {M: {$dynamicAnchor: m, type: string}}\n"}, @@ -364,7 +369,7 @@ func TestDynamicRef_AnAnchorAnotherDocumentsResourceReachesIsKept(t *testing.T) } } -// TestDynamicRef_ResourceBoundaryVerdictIsOrderInvariant pins that which schema +// TestDynamicRef_ResourceBoundaryAnswerIsOrderInvariant pins that which schema // lowered first cannot decide whether the other sees the $id above it, nor // whether the compiler reports stopping at its merge bound. Both come from a // nodeview.View, whose merge-expansion memo records the depth an entry is good @@ -376,7 +381,7 @@ func TestDynamicRef_AnAnchorAnotherDocumentsResourceReachesIsKept(t *testing.T) // // A chain past the bound expands to nothing, so an $id past it is not seen. It // must not read as none: in either order neither reference expands (GitHub #401). -func TestDynamicRef_ResourceBoundaryVerdictIsOrderInvariant(t *testing.T) { +func TestDynamicRef_ResourceBoundaryAnswerIsOrderInvariant(t *testing.T) { t.Parallel() first, diags := parseFull(t, mergeBoundOrderSpec(true)) openapitest.RequireNoErrorDiags(t, diags) @@ -384,7 +389,7 @@ func TestDynamicRef_ResourceBoundaryVerdictIsOrderInvariant(t *testing.T) { openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, cmp.Diff(first.Types, last.Types, orderInvariantIR()...), - "the declaration order must not decide a resource-boundary verdict") + "the declaration order must not decide a resource-boundary answer") // As a set: the per-schema diagnostics follow traversal order, which the // permutation changes by design, so what is compared is what was reported @@ -415,8 +420,8 @@ func TestDynamicRef_ReadsWhatASchemaDeclares(t *testing.T) { doc, diags := parseFull(t, spec) openapitest.RequireNoErrorDiags(t, diags) assert.Contains(t, irtest.DiagCodes(diags), "openapi/dynamic-ref-expanded") - for _, td := range doc.Types { - assert.NotContains(t, td.Common().Unmodeled, "openapi:$dynamicRef") + for _, typeDef := range doc.Types { + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:$dynamicRef") } }) } @@ -428,13 +433,13 @@ func TestDynamicRef_ReadsWhatASchemaDeclares(t *testing.T) { // Its report says the read was cut, and the one warning names the bound that did. func TestDynamicRef_RestsOnNoReadTheMergeBoundCut(t *testing.T) { t.Parallel() - var b strings.Builder - b.WriteString("openapi: 3.1.0\ninfo: {title: Deep, version: \"1\"}\npaths: {}\nx-l0: &l0 {$id: 'https://example.com/deep'}\n") + var builder strings.Builder + builder.WriteString("openapi: 3.1.0\ninfo: {title: Deep, version: \"1\"}\npaths: {}\nx-l0: &l0 {$id: 'https://example.com/deep'}\n") for i := 1; i <= 70; i++ { - fmt.Fprintf(&b, "x-l%d: &l%d {<<: *l%d}\n", i, i, i-1) + fmt.Fprintf(&builder, "x-l%d: &l%d {<<: *l%d}\n", i, i, i-1) } - b.WriteString("components:\n schemas:\n Node: {$dynamicAnchor: T, type: string}\n A: {<<: *l70, $dynamicRef: '#T'}\n") - doc, diags := parseFull(t, b.String()) + builder.WriteString("components:\n schemas:\n Node: {$dynamicAnchor: T, type: string}\n A: {<<: *l70, $dynamicRef: '#T'}\n") + doc, diags := parseFull(t, builder.String()) sc, ok := doc.Types[componentID("A")].(*ir.Scalar) require.True(t, ok) @@ -452,7 +457,7 @@ func TestDynamicRef_RestsOnNoReadTheMergeBoundCut(t *testing.T) { // TestDynamicRef_CycleIsRefusedAtEveryEdge pins that a cycle of $dynamicRef // expansions is preserved whole rather than broken at whichever edge lowered -// first. Each member reaches the verdict from its own position, so no Scalar +// first. Each member reaches the answer from its own position, so no Scalar // ends up with a Base chain that never terminates — the shape a loop of pure // $refs lowers to the top type to avoid, and which neither pass.Validate nor // irverify checks for aliases. @@ -469,7 +474,7 @@ func TestDynamicRef_CycleIsRefusedAtEveryEdge(t *testing.T) { require.True(t, ok, "%s still owns a node", name) require.NotNil(t, sc.Base) assert.Equal(t, ir.TypeID("type/primitive/any"), sc.Base.Target, - "%s aliases the top type, never a link of the cycle", name) + "%s aliases the top type, never a hop of the cycle", name) assert.Contains(t, sc.Unmodeled, "openapi:$dynamicRef", "%s keeps the reference it could not take", name) } @@ -478,9 +483,9 @@ func TestDynamicRef_CycleIsRefusedAtEveryEdge(t *testing.T) { } // TestDynamicRef_ExpandsIntoACycleItIsNotPartOf pins the other side of that -// verdict: a position outside a cycle still expands onto it. Every member of the +// answer: a position outside a cycle still expands onto it. Every member of the // cycle refuses its own expansion, so the target is an ordinary alias over the -// top type rather than a link that loops. +// top type rather than a hop that loops. func TestDynamicRef_ExpandsIntoACycleItIsNotPartOf(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( @@ -500,7 +505,7 @@ func TestDynamicRef_ExpandsIntoACycleItIsNotPartOf(t *testing.T) { // TestDynamicRef_ChainEndsAtAnAnchorItCannotFollow pins where the chain walk // stops. A hop landing on an anchor that is not a component schema, or on a name // declared more than once, cannot be followed any further — and a chain it -// cannot follow is not a chain that returns, so the expansion still stands. +// cannot follow is not a chain that returns, so the expansion still holds. func TestDynamicRef_ChainEndsAtAnAnchorItCannotFollow(t *testing.T) { t.Parallel() cases := map[string]string{ @@ -540,38 +545,38 @@ func TestDynamicRef_NonScalarValueIsKeptNotExpanded(t *testing.T) { doc, diags := parseFull(t, openapitest.ComponentSpec( " M1: {$dynamicAnchor: ok, type: string}\n"+schemas)) - td, ok := doc.Types[componentID("A")] + typeDef, ok := doc.Types[componentID("A")] require.True(t, ok, "the position owns a node") - assert.NotContains(t, td.Common().Unmodeled, "openapi:$dynamicRef", "the malformed $dynamicRef is read as left out") + assert.NotContains(t, typeDef.Common().Unmodeled, "openapi:$dynamicRef", "the malformed $dynamicRef is read as left out") assertDiagContains(t, diags, "/components/schemas/A/$dynamicRef", "must be a string") }) } } // mergeBoundOrderSpec writes one document whose resource boundary is reachable -// only through a YAML merge chain, with the two schemas that walk it declared in -// the given order. P's chain is 51 links and expands whole; Q's rides on P's tail -// for 72, past nodeview's MergeDepthLimit of 64. +// only through a YAML merge chain, with the two schemas that walk it declared +// in the given order. P's chain is 51 hops and expands whole; Q's rides on P's +// tail for 72, past nodeview's MergeDepthLimit of 64. func mergeBoundOrderSpec(pFirst bool) string { - var b strings.Builder - b.WriteString("openapi: 3.1.0\ninfo: {title: MergeBound, version: \"1\"}\npaths: {}\n") - b.WriteString("x-c0: &c0 {$id: 'https://example.com/boundary'}\n") + var builder strings.Builder + builder.WriteString("openapi: 3.1.0\ninfo: {title: MergeBound, version: \"1\"}\npaths: {}\n") + builder.WriteString("x-c0: &c0 {$id: 'https://example.com/boundary'}\n") for i := 1; i <= 50; i++ { - fmt.Fprintf(&b, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) + fmt.Fprintf(&builder, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) } - b.WriteString("x-d0: &d0 {<<: *c50}\n") + builder.WriteString("x-d0: &d0 {<<: *c50}\n") for i := 1; i <= 20; i++ { - fmt.Fprintf(&b, "x-d%d: &d%d {<<: *d%d}\n", i, i, i-1) + fmt.Fprintf(&builder, "x-d%d: &d%d {<<: *d%d}\n", i, i, i-1) } - b.WriteString("components:\n schemas:\n Node: {$dynamicAnchor: T, type: string}\n") + builder.WriteString("components:\n schemas:\n Node: {$dynamicAnchor: T, type: string}\n") const p = " P:\n <<: *c50\n $dynamicRef: '#T'\n" const q = " Q:\n <<: *d20\n $dynamicRef: '#T'\n" if pFirst { - b.WriteString(p + q) - return b.String() + builder.WriteString(p + q) + return builder.String() } - b.WriteString(q + p) - return b.String() + builder.WriteString(q + p) + return builder.String() } // diagnosticSet renders diagnostics as a sorted multiset of severity, code and @@ -622,7 +627,7 @@ func dynamicAtSpec(holder, uses string, first bool) string { // after it are one. func TestDynamicRef_ExpandsToAnyPositionARefNames(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct{ holder, name, pointer string }{ + for name, testCase := range map[string]struct{ holder, name, pointer string }{ "$defs": {" Outer: {type: object, $defs: {Inner: {$dynamicAnchor: n, type: object}}}\n", "n", "/components/schemas/Outer/$defs/Inner"}, "a property": {" Outer: {type: object, properties: {p: {$dynamicAnchor: n, type: object}}}\n", "n", @@ -635,17 +640,17 @@ func TestDynamicRef_ExpandsToAnyPositionARefNames(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - uses := " Uses: {type: object, properties: {m: {$dynamicRef: '#" + tc.name + "'}, r: {$ref: '#" + - tc.pointer + "'}}}\n" + uses := " Uses: {type: object, properties: {m: {$dynamicRef: '#" + testCase.name + "'}, r: {$ref: '#" + + testCase.pointer + "'}}}\n" docs := make([]*ir.Document, 0, 2) for _, first := range []bool{false, true} { - doc, diags := parseFull(t, dynamicAtSpec(tc.holder, uses, first)) + doc, diags := parseFull(t, dynamicAtSpec(testCase.holder, uses, first)) for _, diagnostic := range diags { assert.NotEqual(t, ir.SeverityError, diagnostic.Severity, "%+v", diagnostic) } property, irProperty := propertyOf(t, doc, "Uses", "m"), propertyOf(t, doc, "Uses", "r") assert.Equal(t, irProperty.Type.Target, property.Type.Target, "the expansion names what the $ref names") - assert.Equal(t, ids.In("").ForPointer(jsontext.Pointer(tc.pointer)), property.Type.Target) + assert.Equal(t, ids.In("").ForPointer(jsontext.Pointer(testCase.pointer)), property.Type.Target) assert.NotContains(t, property.Unmodeled, "openapi:$dynamicRef") assert.Equal(t, []jsontext.Pointer{"/components/schemas/Uses/properties/m/$dynamicRef"}, openapitest.PointersOf(diags, diag.DynamicRefExpanded)) @@ -661,7 +666,7 @@ func TestDynamicRef_ExpandsToAnyPositionARefNames(t *testing.T) { // TestDynamicRef_ExpandsWithinOneResource pins the reference and its anchor // read in one schema resource an $id starts: the reference expands to the // anchor, there the resource's root, as the usual JSON Schema spelling of a -// recursive schema has it. An $id between the two puts them in two resources, +// recursive schema has it, the list naming it as one of a $ref would. An $id between the two puts them in two resources, // so the fragment names no anchor of the reference's, which makes it the $ref // it spells, resolving nowhere. func TestDynamicRef_ExpandsWithinOneResource(t *testing.T) { @@ -671,10 +676,9 @@ func TestDynamicRef_ExpandsWithinOneResource(t *testing.T) { " properties: {children: {type: array, items: {$dynamicRef: '#node'}}}\n"+ " Split:\n $dynamicAnchor: split\n type: object\n"+ " properties: {c: {$id: 'https://example.com/c', type: array, items: {$dynamicRef: '#split'}}}\n")) - items, ok := doc.Types[ir.TypeID("type/anonymous/components/schemas/Dyn/properties/children/items")].(*ir.Scalar) + children, ok := doc.Types[ir.TypeID("type/anonymous/components/schemas/Dyn/properties/children")].(*ir.List) require.True(t, ok) - require.NotNil(t, items.Base) - assert.Equal(t, componentID("Dyn"), items.Base.Target) + assert.Equal(t, componentID("Dyn"), children.ElementType.Target) var errs []string for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityError { @@ -707,15 +711,15 @@ func TestRecursiveRef_ExpandsWhereItsTargetIsStatic(t *testing.T) { } tree := items("Tree", "$id: 'https://example.com/tree', $recursiveAnchor: true, ", "{$recursiveRef: '#'}") chain := func() string { - var b strings.Builder - b.WriteString("x-c0: &c0 {description: d}\n") + var builder strings.Builder + builder.WriteString("x-c0: &c0 {description: d}\n") for i := 1; i <= 70; i++ { - fmt.Fprintf(&b, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) + fmt.Fprintf(&builder, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) } - return b.String() + return builder.String() }() const at = "/components/schemas/%s/properties/c/items" - for _, tc := range []struct { + for _, testCase := range []struct { name, schemas, extra, model, expandsTo, why string }{ {name: "an anchored root under an identifier", schemas: tree, model: "Tree", expandsTo: "Tree"}, @@ -752,28 +756,27 @@ func TestRecursiveRef_ExpandsWhereItsTargetIsStatic(t *testing.T) { schemas: " Deep: {<<: *c70, " + d2019 + ", type: object, properties: {c: {type: array, items: {$recursiveRef: '#'}}}}\n", why: `a schema at or above "/components/schemas/Deep/properties/c/items" merges past the levels`}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - src := strings.Replace(openapitest.ComponentSpec(tc.schemas), "components:", tc.extra+"components:", 1) + src := strings.Replace(openapitest.ComponentSpec(testCase.schemas), "components:", testCase.extra+"components:", 1) doc, diags := parseFull(t, src) - pointer := fmt.Sprintf(at, tc.model) - node := doc.Types[ir.TypeID("type/anonymous"+pointer)] - require.NotNil(t, node, "the items position owns a node") - if tc.expandsTo != "" { - scalar, ok := node.(*ir.Scalar) + pointer := fmt.Sprintf(at, testCase.model) + node, hoisted := doc.Types[ir.TypeID("type/anonymous"+pointer)] + if testCase.expandsTo != "" { + assert.False(t, hoisted, "the expansion is the position's type, as a $ref's would be, so no alias sits there") + list, ok := doc.Types[ir.TypeID("type/anonymous"+strings.TrimSuffix(pointer, "/items"))].(*ir.List) require.True(t, ok) - require.NotNil(t, scalar.Base) - assert.Equal(t, componentID(tc.expandsTo), scalar.Base.Target) + assert.Equal(t, componentID(testCase.expandsTo), list.ElementType.Target) assert.Equal(t, []jsontext.Pointer{jsontext.Pointer(pointer + "/$recursiveRef")}, openapitest.PointersOf(diags, diag.DynamicRefExpanded)) assertDiagContains(t, diags, pointer+"/$recursiveRef", "the root of the schema resource it is written in") - assert.NotContains(t, node.Common().Unmodeled, "openapi:$recursiveRef") return } + require.True(t, hoisted, "the items position owns a node holding the reference") entry, ok := node.Common().Unmodeled["openapi:$recursiveRef"] require.True(t, ok, "kept verbatim") assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assertDiagContains(t, diags, pointer+"/$recursiveRef", "$recursiveRef was not expanded because "+tc.why) + assertDiagContains(t, diags, pointer+"/$recursiveRef", "$recursiveRef was not expanded because "+testCase.why) }) } } @@ -803,7 +806,8 @@ func TestRecursiveRef_IsAKeywordOnlyWhereItsDialectDefinesIt(t *testing.T) { // TestDynamicRef_ExpandsToAnAnchorOnlyADraftPlaces pins an anchor at a position // the parser's model holds no schema for, a JSON Schema draft's `definitions` // entry: the reference lands there, as a $ref naming the anchor would, so the -// schema is built and the reference expands to it. Where a $ref naming it +// schema is built and the reference expands to it, the component writing it +// the Model over that object a $ref there makes. Where a $ref naming it // would not resolve, an `$anchor` of its name making the name ambiguous in its // resource, nothing builds it, and the reference is kept, saying so. func TestDynamicRef_ExpandsToAnAnchorOnlyADraftPlaces(t *testing.T) { @@ -815,10 +819,10 @@ func TestDynamicRef_ExpandsToAnAnchorOnlyADraftPlaces(t *testing.T) { inner := ir.TypeID("type/anonymous/components/schemas/Outer/definitions/Inner") _, built := doc.Types[inner].(*ir.Model) assert.True(t, built) - scalar, ok := doc.Types[componentID("D")].(*ir.Scalar) - require.True(t, ok) - require.NotNil(t, scalar.Base) - assert.Equal(t, inner, scalar.Base.Target) + model, ok := doc.Types[componentID("D")].(*ir.Model) + require.True(t, ok, "no Scalar sits over a model") + require.NotNil(t, model.Base) + assert.Equal(t, inner, model.Base.Target) doc, diags = parseFull(t, openapitest.ComponentSpec(outer+" Twin: {$anchor: n, type: string}\n")) assert.NotContains(t, doc.Types, inner) @@ -830,7 +834,7 @@ func TestDynamicRef_ExpandsToAnAnchorOnlyADraftPlaces(t *testing.T) { // TestRecursiveRef_LandsOnTheRootOfItsResource pins a $recursiveRef in // another document whose resource's root no $ref reaches: the reference lands // there as a $ref of "#" would, so the root is built and the reference expands -// to it, in that document's namespace. +// to it, in that document's namespace, the list naming it directly. func TestRecursiveRef_LandsOnTheRootOfItsResource(t *testing.T) { t.Parallel() doc, diags, _ := compileBeside(t, map[string]string{"ext.json": `{"$schema": "https://json-schema.org/draft/2019-09/schema", @@ -841,10 +845,9 @@ func TestRecursiveRef_LandsOnTheRootOfItsResource(t *testing.T) { root := ids.In("ext.json").ForPointer("/$defs/T") _, built := doc.Types[root].(*ir.Model) require.True(t, built, "the root no $ref reaches is built") - items, ok := doc.Types[ids.In("ext.json").ForPointer("/$defs/T/properties/c/items")].(*ir.Scalar) + list, ok := doc.Types[ids.In("ext.json").ForPointer("/$defs/T/properties/c")].(*ir.List) require.True(t, ok) - require.NotNil(t, items.Base) - assert.Equal(t, root, items.Base.Target) + assert.Equal(t, root, list.ElementType.Target) } // TestDynamicRef_AListAnotherReadingKeepsIsNoReference holds a $dynamicRef @@ -879,3 +882,126 @@ func TestDiscriminator_AListAnotherReadingKeepsResolvesNothing(t *testing.T) { assert.Equal(t, jsontext.Pointer("/components/schemas/S/discriminator"), diags[0].Provenance.Pointer) assert.Contains(t, doc.Types[componentID("S")].Common().Unmodeled, "openapi:discriminator", "kept verbatim") } + +// TestDynamicRef_AnExpandedReferenceAloneHoistsNoAlias pins an expanded dynamic +// reference written alone at a position no carrier holds: it is a reference, as +// a $ref there is, so the position lowers to its target and no alias holding +// only a Base is hoisted (docs/compilers/openapi.md#dynamic-ref). Each position +// is asked at 3.1 and 3.2, and in a 2019-09 schema spelling it $recursiveRef, +// the expansion reported at each as before. +func TestDynamicRef_AnExpandedReferenceAloneHoistsNoAlias(t *testing.T) { + t.Parallel() + const tree = "/components/schemas/Tree/properties/" + positions := map[string]func(doc *ir.Document) ir.TypeID{ + tree + "items/items": func(doc *ir.Document) ir.TypeID { + return reachedAs[*ir.List](t, doc, tree+"items").ElementType.Target + }, + tree + "map/additionalProperties": func(doc *ir.Document) ir.TypeID { + return reachedAs[*ir.MapT](t, doc, tree+"map").Value.Target + }, + tree + "tuple/prefixItems/0": func(doc *ir.Document) ir.TypeID { + return reachedAs[*ir.Tuple](t, doc, tree+"tuple").ElementTypes[0].Target + }, + tree + "branch/oneOf/0": func(doc *ir.Document) ir.TypeID { + return reachedAs[*ir.Union](t, doc, tree+"branch").Variants[0].Type.Target + }, + } + properties := "properties: {items: {type: array, items: %[1]s}, map: {type: object, additionalProperties: %[1]s}, " + + "tuple: {type: array, prefixItems: [%[1]s]}, branch: {oneOf: [%[1]s, {type: integer}]}}" + for _, testCase := range []struct { + name, version, head, ref, keyword string + }{ + {name: "3.1", version: "3.1.0", head: "$dynamicAnchor: node", ref: `{$dynamicRef: "#node"}`, keyword: "$dynamicRef"}, + {name: "3.2", version: "3.2.0", head: "$dynamicAnchor: node", ref: `{$dynamicRef: "#node"}`, keyword: "$dynamicRef"}, + {name: "2019-09", version: "3.1.0", head: d2019 + ", $id: 'https://example.com/tree', $recursiveAnchor: true", + ref: "{$recursiveRef: '#'}", keyword: "$recursiveRef"}, + } { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer(testCase.version, + " Tree: {"+testCase.head+", type: object, "+fmt.Sprintf(properties, testCase.ref)+"}\n")) + expanded := make([]jsontext.Pointer, 0, len(positions)) + for pointer, target := range positions { + _, hoisted := doc.Types[ir.TypeID("type/anonymous"+pointer)] + assert.False(t, hoisted, "%s: no alias is hoisted", pointer) + assert.Equal(t, componentID("Tree"), target(doc), "%s: the position names the expansion's target", pointer) + expanded = append(expanded, jsontext.Pointer(pointer+"/"+testCase.keyword)) + } + assert.ElementsMatch(t, expanded, openapitest.PointersOf(diags, diag.DynamicRefExpanded)) + }) + } +} + +// TestDynamicRef_ContentBesideAnExpandedReferenceIsKept pins the content +// vocabulary written beside an expanded dynamic reference: the position has no +// Encoding to hold contentMediaType and contentEncoding, so the Model over the +// expansion's target, an object, keeps both verbatim and reports each, as a +// $ref there makes, at each position +// and in each spelling TestDynamicRef_AnExpandedReferenceAloneHoistsNoAlias +// asks. +func TestDynamicRef_ContentBesideAnExpandedReferenceIsKept(t *testing.T) { + t.Parallel() + const tree = "/components/schemas/Tree/properties/" + positions := []string{tree + "items/items", tree + "map/additionalProperties", tree + "tuple/prefixItems/0", tree + "branch/oneOf/0"} + properties := "properties: {items: {type: array, items: %[1]s}, map: {type: object, additionalProperties: %[1]s}, " + + "tuple: {type: array, prefixItems: [%[1]s]}, branch: {oneOf: [%[1]s, {type: integer}]}}" + const content = ", contentMediaType: text/plain, contentEncoding: base64}" + for _, testCase := range []struct{ name, version, head, ref string }{ + {"3.1", "3.1.0", "$dynamicAnchor: node", `{$dynamicRef: "#node"` + content}, + {"3.2", "3.2.0", "$dynamicAnchor: node", `{$dynamicRef: "#node"` + content}, + {"2019-09", "3.1.0", d2019 + ", $id: 'https://example.com/tree', $recursiveAnchor: true", "{$recursiveRef: '#'" + content}, + } { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer(testCase.version, + " Tree: {"+testCase.head+", type: object, "+fmt.Sprintf(properties, testCase.ref)+"}\n")) + for _, pointer := range positions { + home := reachedAs[*ir.Model](t, doc, pointer) + require.NotNil(t, home.Base, pointer) + assert.Equal(t, componentID("Tree"), home.Base.Target, "%s: the Model is over the expansion's target", pointer) + assert.Equal(t, []string{"openapi:contentEncoding", "openapi:contentMediaType"}, unmodeledKeys(home.Unmodeled), pointer) + for _, keyword := range []string{"contentEncoding", "contentMediaType"} { + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, pointer+"/"+keyword), "%s: %s is reported", pointer, keyword) + } + } + }) + } +} + +// reachedAs returns the node the position at pointer lowered to, held to the +// kind T. +func reachedAs[T ir.TypeDef](t *testing.T, doc *ir.Document, pointer string) T { + t.Helper() + node, ok := doc.Types[ir.TypeID("type/anonymous"+pointer)].(T) + require.True(t, ok, "%s lowers to a %T", pointer, node) + return node +} + +// TestDynamicRef_AWrapperInPlaceIsReadAsItsEntry pins an allOf's lone +// entry that is itself a lone entry of a $dynamicRef: it is in place twice +// over, so the position expands as one lone entry does, and beside a $ref the +// wrapper is read unexpanded, its keywords and its entry's all it says, so the +// position composes the $ref's object, keeping the keyword, as an entry +// writing the $dynamicRef there does (docs/compilers/openapi.md#allof-refinement). +func TestDynamicRef_AWrapperInPlaceIsReadAsItsEntry(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " M: {$dynamicAnchor: m, type: string}\n"+ + " O: {type: object, properties: {a: {type: string}}}\n"+ + " Two: {allOf: [{allOf: [{$dynamicRef: '#m'}]}]}\n"+ + " Wrapped: {allOf: [{allOf: [{$dynamicRef: '#m', description: d}]}, {$ref: '#/components/schemas/O'}]}\n"+ + " Entry: {allOf: [{$dynamicRef: '#m', description: d}, {$ref: '#/components/schemas/O'}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + two, ok := typeByName(doc, "Two").(*ir.Scalar) + require.True(t, ok, "%T", typeByName(doc, "Two")) + require.NotNil(t, two.Base) + assert.Equal(t, componentID("M"), two.Base.Target, "the position is the expansion's use") + assert.Contains(t, openapitest.PointersOf(diags, diag.DynamicRefExpanded), jsontext.Pointer("/components/schemas/Two/allOf/0/allOf/0/$dynamicRef")) + for _, name := range []string{"Wrapped", "Entry"} { + model, isModel := typeByName(doc, name).(*ir.Model) + require.True(t, isModel, "%s: %T", name, typeByName(doc, name)) + require.NotNil(t, model.Base, name) + assert.Equal(t, componentID("O"), model.Base.Target, "%s composes the $ref", name) + assert.Contains(t, model.Unmodeled, "openapi:$dynamicRef", name) + } +} diff --git a/compilers/openapi/internal/schema/election.go b/compilers/openapi/internal/schema/election.go deleted file mode 100644 index 7fc87e114..000000000 --- a/compilers/openapi/internal/schema/election.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "bytes" - "slices" - "strings" - - "github.com/dexpace/morphic/compilers/openapi/internal/statement" -) - -// chooseConjunctToLowerFrom picks the conjunct the position lowers from, of -// refs the $refs that may be: an inline value set within every other, since it -// fixes the values and what it narrows cannot; else a $ref, since replacing it -// drops what its target says (narrowestRef); else, of those naming a kind, the -// conjunct within the most others. A `format` or `items` naming no kind only -// qualifies one, so it never decides, and where nothing names a kind no entry -// does. No tie goes by the order written: untie breaks one, and words neither -// within the other elect none. -func (w *admissionReader) chooseConjunctToLowerFrom(conjuncts []conjunct, refs []*conjunct) *conjunct { - for i := range conjuncts { - if w.narrowsAll(conjuncts, i, refs) { - return untie(w, conjuncts, strongest(narrowingSets(conjuncts, i, refs))) - } - } - if len(refs) > 0 { - return narrowestRef(w, conjuncts, refs) - } - tied := strongest(mostWithin(w, conjuncts)) - if len(tied) > 1 && tied[0].form == formWords && !admitAlike(w, tied) { - return &conjuncts[0] - } - return untie(w, conjuncts, tied) -} - -// narrowingSets returns the value sets within every other conjunct, the first -// of them at i: those after it whose kinds and values are its own, as each -// set within every other is within the first, and the first within it. -func narrowingSets(conjuncts []conjunct, i int, refs []*conjunct) []*conjunct { - first := &conjuncts[i] - sets := []*conjunct{first} - for j := i + 1; j < len(conjuncts); j++ { - cj := &conjuncts[j] - if cj.read.fixed && !slices.Contains(refs, cj) && sameValues(cj.read, first.read) { - sets = append(sets, cj) - } - } - return sets -} - -// sameValues reports whether a and b, two value sets, admit the same kinds and -// hold the same members. -func sameValues(a, b admitted) bool { - return a.kindsWithin(b) && b.kindsWithin(a) && a.valuesWithin(b) && b.valuesWithin(a) -} - -// mostWithin returns the conjuncts naming a kind that lie within the most -// conjuncts, in the order written. -func mostWithin(admissionReaderValue *admissionReader, conjuncts []conjunct) []*conjunct { - var tied []*conjunct - most := 0 - for i := range conjuncts { - cj := &conjuncts[i] - if !cj.says { - continue - } - switch n := admissionReaderValue.conesOver(conjuncts, cj.read); { - case n > most: - tied, most = append(tied[:0], cj), n - case n == most: - tied = append(tied, cj) - } - } - return tied -} - -// strongest returns those of tied whose form ranks first (conjunctForm). -func strongest(tied []*conjunct) []*conjunct { - top := formWords - for _, cj := range tied { - top = max(top, cj.form) - } - return slices.DeleteFunc(tied, func(cj *conjunct) bool { return cj.form != top }) -} - -// admitAlike reports whether each of tied lies within every other: what they admit -// is one, so far as a reading holds it. -func admitAlike(admissionReaderValue *admissionReader, tied []*conjunct) bool { - first := tied[0].read - return !slices.ContainsFunc(tied[1:], func(cj *conjunct) bool { - return !admissionReaderValue.within(first, cj.read) || !admissionReaderValue.within(cj.read, first) - }) -} - -// untie returns which of tied, conjuncts of one form, the position lowers -// from: the one there is; of words admitting alike, the pick untieWords makes; -// of unions of one keyword, the first where each is that one schema written -// again, else none, as no rule ranks their branches, and the keywords beside -// the allOf decide (docs/compilers/openapi.md#allof-refinement). A tie of no -// conjunct leaves those keywords too. -func untie(admissionReaderValue *admissionReader, conjuncts []conjunct, tied []*conjunct) *conjunct { - switch { - case len(tied) == 0: - return &conjuncts[0] - case len(tied) == 1: - return tied[0] - case tied[0].form == formWords: - return untieWords(admissionReaderValue, &conjuncts[0], tied) - case writtenAlike(admissionReaderValue, tied): - return tied[0] - default: - return &conjuncts[0] - } -} - -// writtenAlike reports whether each of tied is an allOf entry written as the -// first is (sameText): one schema written several times. -func writtenAlike(admissionReaderValue *admissionReader, tied []*conjunct) bool { - return !slices.ContainsFunc(tied, func(cj *conjunct) bool { - return cj.entry == nil || !sameText(admissionReaderValue.c, tied[0].entry.schema, cj.entry.schema) - }) -} - -// principalKeywords are the keywords a node's build reads from the principal -// alone and no other conjunct folds into, so two conjuncts admitting alike -// still part on them: what each lowers its elements or its content by. -var principalKeywords = slices.Concat([]string{"items", "prefixItems", "additionalItems"}, contentKeywords) - -// untieWords returns which of tied, conjuncts admitting alike that name their -// kinds by words, the position lowers from. The pick shows only in -// principalKeywords: of those writing every such keyword any other does, and -// alike, one is elected, and where none does, none is, and beside, the -// keywords beside the allOf, decide. Where nothing tells them apart, beside -// stands if tied, else the least text (leastText). -func untieWords(admissionReaderValue *admissionReader, beside *conjunct, tied []*conjunct) *conjunct { - most := slices.MaxFunc(tied, func(a, b *conjunct) int { - return countKeys(a.schema, principalKeywords) - countKeys(b.schema, principalKeywords) - }) - if slices.ContainsFunc(tied, func(cj *conjunct) bool { return !writesWithin(cj.schema, most.schema) }) { - return beside - } - tied = slices.DeleteFunc(slices.Clone(tied), func(cj *conjunct) bool { return !writesWithin(most.schema, cj.schema) }) - if slices.Contains(tied, beside) { - return beside - } - return leastText(admissionReaderValue, tied) -} - -// countKeys counts the keys of keys schema writes (hasKey). -func countKeys(schema *statement.Schema, keys []string) int { - n := 0 - for _, key := range keys { - if hasKey(schema, key) { - n++ - } - } - return n -} - -// writesWithin reports whether each of principalKeywords a writes, b writes -// alike. -func writesWithin(a, b *statement.Schema) bool { - return !slices.ContainsFunc(principalKeywords, func(key string) bool { - return hasKey(a, key) && (!hasKey(b, key) || !foldValue(a, key).agrees(foldValue(b, key))) - }) -} - -// leastText returns the one of tied, allOf entries admitting alike, whose -// text is the least, bytewise: the pick shows in little more than where its -// node stands, and the text, its keys sorted, reads no order the entries are -// written in. Of a schema written twice, the first copy stands for both, the -// one place order shows, and only in that node's pointer. -func leastText(admissionReaderValue *admissionReader, tied []*conjunct) *conjunct { - best := tied[0] - for _, cj := range tied[1:] { - if bytes.Compare(writtenText(admissionReaderValue.c, cj.entry.schema), writtenText(admissionReaderValue.c, best.entry.schema)) < 0 { - best = cj - } - } - return best -} - -// narrowestRef returns the one of refs lying within the most conjuncts, a tie -// going to the least reference text, then to the least text of the entry -// writing it: a $ref's name stays put under edits to what it names, so no -// order written decides. Of a $ref written twice alike, the first copy stands -// for both, and keepsAtOutcome keeps neither. -func narrowestRef(admissionReaderValue *admissionReader, conjuncts []conjunct, refs []*conjunct) *conjunct { - best, most := refs[0], admissionReaderValue.conesOver(conjuncts, refs[0].read) - for _, ref := range refs[1:] { - n := admissionReaderValue.conesOver(conjuncts, ref.read) - if n > most || n == most && refBefore(admissionReaderValue, ref, best) { - best, most = ref, n - } - } - return best -} - -// refBefore reports whether the $ref conjunct a goes before b where both lie -// within as many conjuncts: by reference text, then by the text of the entry. -func refBefore(admissionReaderValue *admissionReader, a, b *conjunct) bool { - if order := strings.Compare(refText(a), refText(b)); order != 0 { - return order < 0 - } - return bytes.Compare(writtenText(admissionReaderValue.c, a.entry.schema), writtenText(admissionReaderValue.c, b.entry.schema)) < 0 -} - -// refText is the reference the $ref conjunct cj writes, as written. -func refText(cj *conjunct) string { - _, text := refSpelling(cj.entry.schema) - return text -} - -// narrowsAll reports whether conjunct i is a value set within every other -// conjunct and more than a restatement of what a $ref of refs fixes, which a -// $ref's own is not. The keywords beside the allOf are one where they write an -// enum or a const (allOfDecides). No set is compared with itself, which answers -// nothing and walks the whole set. -func (w *admissionReader) narrowsAll(conjuncts []conjunct, i int, refs []*conjunct) bool { - cj := &conjuncts[i] - if !cj.read.fixed || slices.Contains(refs, cj) || - slices.ContainsFunc(refs, func(ref *conjunct) bool { return w.setWithin(ref.read, cj.read) }) { - return false - } - for j := range conjuncts { - if conjunct := &conjuncts[j]; j != i && (!cj.read.kindsWithin(conjunct.read) || !w.setWithin(cj.read, conjunct.read)) { - return false - } - } - return true -} - -// setWithin is a.valuesWithin(b), telling walked how many members it looked up. -func (w *admissionReader) setWithin(a, b admitted) bool { - within, walked := a.walkWithin(b) - if w.walked != nil { - w.walked(walked) - } - return within -} - -// conesOver counts the conjuncts what read admits lies within. -func (w *admissionReader) conesOver(conjuncts []conjunct, read admitted) int { - n := 0 - for j := range conjuncts { - if w.within(read, conjuncts[j].read) { - n++ - } - } - return n -} diff --git a/compilers/openapi/internal/schema/empty_enum_const_test.go b/compilers/openapi/internal/schema/empty_enum_const_test.go new file mode 100644 index 000000000..049c164f6 --- /dev/null +++ b/compilers/openapi/internal/schema/empty_enum_const_test.go @@ -0,0 +1,200 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// emptyBeside is a spelling of `enum: []` beside another value set: where its +// one finding sits below the schema, and the key and value the other set +// is kept under. +type emptyBeside struct{ at, key, kept string } + +// TestEmptyEnum_BesideASetIsTheClosedEmptyEnumOfItsValues holds `enum: []` +// beside `const: a` or `enum: [a]`, flat, on two entries, and one beside the +// allOf and the other on its entry, each in both orders: the empty enum lies +// within the other set, so the position is the closed empty Enum its values +// type, the node `{type: string, enum: []}` lowers to, keeping the other set +// verbatim under its conjunct's key, and the one finding is the empty enum's, +// where it is written (docs/compilers/openapi.md#enum-const). +func TestEmptyEnum_BesideASetIsTheClosedEmptyEnumOfItsValues(t *testing.T) { + t.Parallel() + equivalent, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {type: string, enum: []}\n")) + want, ok := typeByName(equivalent, "S").(*ir.Enum) + require.True(t, ok) + for schema, testCase := range map[string]emptyBeside{ + "{enum: [], const: a}": {"", "openapi:const", `"a"`}, + "{const: a, enum: []}": {"", "openapi:const", `"a"`}, + "{allOf: [{enum: []}, {const: a}]}": {"/allOf/0", "openapi:const", `"a"`}, + "{allOf: [{const: a}, {enum: []}]}": {"/allOf/1", "openapi:const", `"a"`}, + "{const: a, allOf: [{enum: []}]}": {"/allOf/0", "openapi:const", `"a"`}, + "{allOf: [{enum: []}], const: a}": {"/allOf/0", "openapi:const", `"a"`}, + "{enum: [], allOf: [{const: a}]}": {"", "openapi:const", `"a"`}, + "{allOf: [{const: a}], enum: []}": {"", "openapi:const", `"a"`}, + "{allOf: [{enum: [], const: a}]}": {"/allOf/0", "openapi:const", `"a"`}, + "{allOf: [{const: a, enum: []}]}": {"/allOf/0", "openapi:const", `"a"`}, + "{allOf: [{enum: []}, {const: a}], description: d}": {"/allOf/0", "openapi:const", `"a"`}, + "{allOf: [{enum: []}, {enum: [a]}]}": {"/allOf/0", "openapi:allOf/1", `{"enum": ["a"]}`}, + "{allOf: [{enum: [a]}, {enum: []}]}": {"/allOf/1", "openapi:allOf/0", `{"enum": ["a"]}`}, + "{enum: [], allOf: [{enum: [a]}]}": {"", "openapi:allOf/0", `{"enum": ["a"]}`}, + "{allOf: [{enum: [a]}], enum: []}": {"", "openapi:allOf/0", `{"enum": ["a"]}`}, + "{enum: [a], allOf: [{enum: []}]}": {"/allOf/0", "openapi:enum", `["a"]`}, + "{allOf: [{enum: []}], enum: [a]}": {"/allOf/0", "openapi:enum", `["a"]`}, + } { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+schema+"\n")) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "%s: got %T", schema, typeByName(doc, "S")) + assert.Empty(t, cmp.Diff(want, enum, cmpopts.IgnoreFields(ir.TypeCommon{}, "Docs", "Unmodeled")), schema) + require.Equal(t, []string{testCase.key}, unmodeledKeys(enum.Unmodeled), schema) + assert.JSONEq(t, testCase.kept, string(enum.Unmodeled[testCase.key].Value), schema) + require.Len(t, diags, 1, "%s: %+v", schema, diags) + assert.Equal(t, diag.EmptyEnum, diags[0].Code, schema) + assert.Equal(t, "/components/schemas/S"+testCase.at, string(diags[0].Provenance.Pointer), schema) + } +} + +// TestEmptyEnum_BesideAConstTypedByNoPrimitiveIsTheTopType holds `enum: []` +// beside a const a primitive types and one none does, flat and beside the +// allOf: the closed empty Enum is typed as a Literal of the value is, the top +// type for a list or an object, and keeps the const as written. +func TestEmptyEnum_BesideAConstTypedByNoPrimitiveIsTheTopType(t *testing.T) { + t.Parallel() + for schema, want := range map[string]ir.PrimitiveKind{ + "{enum: [], const: 1}": ir.PrimitiveNumber, + "{allOf: [{enum: []}, {const: 1}]}": ir.PrimitiveNumber, + "{enum: [], const: true}": ir.PrimitiveBool, + "{enum: [], allOf: [{const: true}]}": ir.PrimitiveBool, + "{enum: [], const: [1]}": ir.PrimitiveAny, + "{enum: [], allOf: [{const: [1]}]}": ir.PrimitiveAny, + "{const: [1], allOf: [{enum: []}]}": ir.PrimitiveAny, + "{allOf: [{const: {a: 1}}, {enum: []}]}": ir.PrimitiveAny, + } { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+schema+"\n")) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "%s: got %T", schema, typeByName(doc, "S")) + assert.Equal(t, want, enum.ValueType, schema) + assert.Empty(t, enum.Members, schema) + assert.Equal(t, []string{"openapi:const"}, unmodeledKeys(enum.Unmodeled), schema) + assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.EmptyEnum, ir.SeverityWarning), schema) + assert.Len(t, diags, 1, "%s: %+v", schema, diags) + } +} + +// TestEmptyEnum_BesideSetsSharingNoneStaysApart holds `enum: []` beside sets +// that share no member among themselves: the empty enum is no one fact there, +// so every set is kept, the empty one included, under the warning that the +// conjuncts share no value. +func TestEmptyEnum_BesideSetsSharingNoneStaysApart(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Apart: {allOf: [{enum: []}, {enum: [a]}, {enum: [b]}]}\n")) + enum, ok := typeByName(doc, "Apart").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "Apart")) + assert.Empty(t, enum.Members) + assert.ElementsMatch(t, []string{"openapi:allOf/0", "openapi:allOf/1", "openapi:allOf/2"}, unmodeledKeys(enum.Unmodeled)) + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, severitiesAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Apart")) +} + +// emptyEnumTargets are the schemas an empty enum beside a $ref to them lies within, +// by name, each with the flat twin typing the closed empty Enum alike. +var emptyEnumTargets = map[string]struct{ body, equivalent string }{ + "S": {"{type: string}", "{type: string, enum: []}"}, + "SE": {"{type: string, enum: [a, b]}", "{type: string, enum: []}"}, + "O": {"{type: object, properties: {a: {type: string}}}", "{type: object, enum: []}"}, +} + +// TestEmptyEnum_BesideARefIsTheClosedEmptyEnumOfItsTarget holds `enum: []` +// beside a $ref to a schema stating a type or a set, on an entry in either +// order, beside the allOf and beside the $ref, either key first: the empty +// enum lies within the target, so the position is the closed empty Enum the +// target's values or type type, as the flat twin is, the target saying its +// own, so nothing is kept at the position, and the one finding is the empty +// enum's, where it is written (docs/compilers/openapi.md#enum-const). +func TestEmptyEnum_BesideARefIsTheClosedEmptyEnumOfItsTarget(t *testing.T) { + t.Parallel() + for name, target := range emptyEnumTargets { + ref := "{$ref: '#/components/schemas/" + name + "'}" + equivalent, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+target.equivalent+"\n")) + want, ok := typeByName(equivalent, "S").(*ir.Enum) + require.True(t, ok, name) + for schema, at := range map[string]string{ + "{allOf: [" + ref + ", {enum: []}]}": "/allOf/1", + "{allOf: [{enum: []}, " + ref + "]}": "/allOf/0", + "{allOf: [" + ref + "], enum: []}": "", + "{enum: [], allOf: [" + ref + "]}": "", + "{$ref: '#/components/schemas/" + name + "', enum: []}": "", + "{enum: [], $ref: '#/components/schemas/" + name + "'}": "", + } { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " "+name+": "+target.body+"\n P: "+schema+"\n")) + enum, ok := typeByName(doc, "P").(*ir.Enum) + require.True(t, ok, "%s: got %T", schema, typeByName(doc, "P")) + assert.Empty(t, cmp.Diff(want, enum, cmpopts.IgnoreFields(ir.TypeCommon{}, "ID", "Name", "Provenance")), schema) + require.Len(t, diags, 1, "%s: %+v", schema, diags) + assert.Equal(t, diag.EmptyEnum, diags[0].Code, schema) + assert.Equal(t, "/components/schemas/P"+at, string(diags[0].Provenance.Pointer), schema) + } + } +} + +// TestEmptyEnum_TheEntrySpellingLowersAsBesideTheAllOf holds the reproduction +// of GitHub #2066: an empty enum on an allOf entry beside a $ref to an object +// or a string lowers as the same enum beside the allOf does, the closed empty +// Enum keeping nothing, with the empty enum's warning alone, and an entry's +// enum with members is still chosen keeping the $ref it narrows. +func TestEmptyEnum_TheEntrySpellingLowersAsBesideTheAllOf(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` O: {type: object, properties: {a: {type: string}}} + S: {type: string} + EntryObj: {allOf: [{$ref: '#/components/schemas/O'}, {enum: []}]} + WrapObj: {allOf: [{$ref: '#/components/schemas/O'}], enum: []} + EntryStr: {allOf: [{$ref: '#/components/schemas/S'}, {enum: []}]} + WrapStr: {allOf: [{$ref: '#/components/schemas/S'}], enum: []} + EntryFull: {allOf: [{$ref: '#/components/schemas/S'}, {enum: [a]}]} +`)) + for _, pair := range [][2]string{{"EntryObj", "WrapObj"}, {"EntryStr", "WrapStr"}} { + entry, ok := typeByName(doc, pair[0]).(*ir.Enum) + require.True(t, ok, "%s: got %T", pair[0], typeByName(doc, pair[0])) + wrap, ok := typeByName(doc, pair[1]).(*ir.Enum) + require.True(t, ok, "%s: got %T", pair[1], typeByName(doc, pair[1])) + assert.Empty(t, cmp.Diff(wrap, entry, cmpopts.IgnoreFields(ir.TypeCommon{}, "ID", "Name", "Provenance")), pair[0]) + assert.Empty(t, entry.Unmodeled, pair[0]) + } + full, ok := typeByName(doc, "EntryFull").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "EntryFull")) + assert.Len(t, full.Members, 1) + assert.Equal(t, []string{"openapi:$ref"}, unmodeledKeys(full.Unmodeled)) + codes := make([]string, 0, len(diags)) + for _, diagnostic := range diags { + codes = append(codes, diagnostic.Code) + } + assert.ElementsMatch(t, []string{diag.EmptyEnum, diag.EmptyEnum, diag.EmptyEnum, diag.EmptyEnum, diag.DegradedConstruct}, codes, + "one empty-enum per empty enum, and the info for EntryFull's narrowed $ref alone") +} + +// TestEmptyEnum_BesideARefStatingNoKindKeepsTheRef holds `enum: []` beside a +// $ref to a schema stating no kind, and to one naming nothing: the target +// says nothing the empty enum lies within, so the $ref is kept as written, +// with its own report. +func TestEmptyEnum_BesideARefStatingNoKindKeepsTheRef(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Any: {} + P: {allOf: [{$ref: '#/components/schemas/Any'}, {enum: []}]} + G: {allOf: [{$ref: '#/components/schemas/Missing'}, {enum: []}]} +`)) + for _, name := range []string{"P", "G"} { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s: got %T", name, typeByName(doc, name)) + assert.Equal(t, []string{"openapi:$ref"}, unmodeledKeys(enum.Unmodeled), name) + } + assert.NotEmpty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/P/allOf/0")) +} diff --git a/compilers/openapi/internal/schema/empty_principal_test.go b/compilers/openapi/internal/schema/empty_principal_test.go new file mode 100644 index 000000000..10ac8a995 --- /dev/null +++ b/compilers/openapi/internal/schema/empty_principal_test.go @@ -0,0 +1,116 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// emptyPrincipalCase is an allOf whose one entry is `enum: []`, which the +// position lowers from, beside another entry writing what that principal does +// not say: the keyword kept, the value it holds, and what reports it. +type emptyPrincipalCase struct { + other, keyword, value, code string +} + +// emptyPrincipalCases are the other entries the empty principal says nothing +// of: a const of a list, a number or an object, a second enum, and a union. +var emptyPrincipalCases = map[string]emptyPrincipalCase{ + "a list const": {"{const: [1]}", "const", "[1]", diag.DegradedConstruct}, + "a number const": {"{const: 1}", "const", "1", diag.DegradedConstruct}, + "an object const": {"{const: {a: 1}}", "const", `{"a":1}`, diag.DegradedConstruct}, + "a second enum": {"{enum: [1]}", "enum", "[1]", diag.DegradedConstruct}, + "an enum of lists": {"{enum: [[1]]}", "enum", "[[1]]", diag.DegradedConstruct}, + "an anyOf": {"{anyOf: [{type: string}, {type: integer}]}", "anyOf", `[{"type":"string"},{"type":"integer"}]`, diag.ValidationOnlyKeyword}, + "a one-branch oneOf": {"{oneOf: [{type: string}]}", "oneOf", `[{"type":"string"}]`, diag.ValidationOnlyKeyword}, +} + +// keptHolding returns the keys of kept whose value is value, or holds it under +// keyword inside an entry kept whole. +func keptHolding(kept ir.Unmodeled, keyword, value string) []string { + var keys []string + for key, entry := range kept { + if string(entry.Value) == value || strings.Contains(string(entry.Value), `"`+keyword+`":`+value) { + keys = append(keys, key) + } + } + return keys +} + +// TestAllOf_AnEmptyPrincipalSaysNoValueSetOrUnionBesideIt holds an allOf whose +// principal, an empty enum, admits no value beside an entry writing a value set +// or a union: the principal says none of it, so the position is the closed +// empty Enum, keeping what the other entry writes once, as written, with the +// report that it is kept where that entry is written, but for a value set, +// which shares no member with the empty one and is reported by no entry, in +// both entry orders. +func TestAllOf_AnEmptyPrincipalSaysNoValueSetOrUnionBesideIt(t *testing.T) { + t.Parallel() + for name, testCase := range emptyPrincipalCases { + for _, empty := range []int{0, 1} { + t.Run(fmt.Sprintf("%s/empty-at-%d", name, empty), func(t *testing.T) { + t.Parallel() + entries := "{enum: []}, " + testCase.other + if empty == 1 { + entries = testCase.other + ", {enum: []}" + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+entries+"]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "the empty principal: got %T", typeByName(doc, "S")) + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Len(t, keptHolding(enum.Unmodeled, testCase.keyword, testCase.value), 1, "kept once, as written: %v", enum.Unmodeled) + other := fmt.Sprintf("/components/schemas/S/allOf/%d", 1-empty) + if testCase.keyword == "enum" || testCase.keyword == "const" { + assert.Empty(t, diagsAtPointer(diags, testCase.code, other), "a value set sharing no member is reported by no entry") + } else { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, testCase.code, ir.SeverityInfo, other), "kept verbatim under Unmodeled") + } + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, + severitiesAt(diags, diag.EmptyEnum, fmt.Sprintf("/components/schemas/S/allOf/%d", empty)), "the empty enum's own warning") + }) + } + } +} + +// severitiesAt returns the severity of each of diags carrying code at pointer. +func severitiesAt(diags []ir.Diagnostic, code, pointer string) []ir.Severity { + var out []ir.Severity + for _, diagnostic := range diags { + if diagnostic.Code == code && string(diagnostic.Provenance.Pointer) == pointer { + out = append(out, diagnostic.Severity) + } + } + return out +} + +// TestAllOf_ASetBesideTheAllOfOverAnEmptyPrincipalIsKept holds an enum beside +// an allOf whose principal, an empty enum, lies within it: the empty enum is +// the one fact, so the position is the closed empty Enum the set's values +// type, keeping the set once, as written, and the empty enum's warning is the +// one report, in both entry orders (docs/compilers/openapi.md#enum-const). +func TestAllOf_ASetBesideTheAllOfOverAnEmptyPrincipalIsKept(t *testing.T) { + t.Parallel() + for _, entries := range []string{"{enum: []}, {description: d}", "{description: d}, {enum: []}"} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+entries+"], enum: [1]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "%s: got %T", entries, typeByName(doc, "S")) + assert.Empty(t, enum.Members, entries) + assert.Equal(t, ir.PrimitiveNumber, enum.ValueType, entries) + assert.Equal(t, []string{"openapi:enum"}, unmodeledKeys(enum.Unmodeled), "%s: kept once, as written", entries) + require.Len(t, diags, 1, "%s: %+v", entries, diags) + assert.Equal(t, diag.EmptyEnum, diags[0].Code, entries) + } +} diff --git a/compilers/openapi/internal/schema/entry_apart_wording_test.go b/compilers/openapi/internal/schema/entry_apart_wording_test.go new file mode 100644 index 000000000..2a32e1d1e --- /dev/null +++ b/compilers/openapi/internal/schema/entry_apart_wording_test.go @@ -0,0 +1,35 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestAllOf_EntriesWritingAKeyDifferentlyKeepItEachUnderItsEntryKey holds two +// inline entries writing one unknown key two ways, neither around the +// other: no conjunct takes the plain key, so each keeps it under its own entry +// key, and the report says the entries write it differently, not that the +// keywords beside the allOf do, since nothing is written beside it. +func TestAllOf_EntriesWritingAKeyDifferentlyKeepItEachUnderItsEntryKey(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: [{type: string, foo: 1}, {foo: 2}]}\n")) + + kept := typeByName(doc, "S").Common().Unmodeled + assert.NotContains(t, kept, "openapi:foo", "no conjunct takes the plain key") + for key, value := range map[string]string{"openapi:allOf/0": `{"foo":1}`, "openapi:allOf/1": `{"foo":2}`} { + require.Contains(t, kept, key) + assert.JSONEq(t, value, string(kept[key].Value), key) + } + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S/allOf/0") + assert.Regexp(t, `writes? foo differently`, message) + assert.NotContains(t, message, "beside this allOf", "nothing is written beside the allOf") +} diff --git a/compilers/openapi/internal/schema/entry_union_wording_test.go b/compilers/openapi/internal/schema/entry_union_wording_test.go new file mode 100644 index 000000000..5c93e97e7 --- /dev/null +++ b/compilers/openapi/internal/schema/entry_union_wording_test.go @@ -0,0 +1,45 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestAllOf_AnEntrysUnionIsReportedAsItsBesideSpellingIs holds a union an +// entry keeps to the words the same union written beside the allOf draws: one +// finding naming it with the entry's other keywords the node has no home for, +// whatever the principal, and the co-declared wording only where the entry is +// the value set the position lowers to, as that set and union beside the allOf +// are co-declared. Each union refuses a member of the value set beside it, so +// it says something and is kept. +func TestAllOf_AnEntrysUnionIsReportedAsItsBesideSpellingIs(t *testing.T) { + t.Parallel() + const types = ` Arr: {type: array, items: {type: string}} + Str: {type: string} +` + for schema, want := range map[string]string{ + "{allOf: [{$ref: '#/components/schemas/Arr'}, {items: {type: integer}, oneOf: [{type: array, maxItems: 5}, {type: boolean}]}]}": "has no home for items, oneOf written on this inline entry", + "{allOf: [{$ref: '#/components/schemas/Arr'}, {oneOf: [{type: array, maxItems: 5}, {type: boolean}]}]}": "has no home for oneOf written on this inline entry", + "{allOf: [{type: string, enum: [a, bb]}, {oneOf: [{type: string, maxLength: 1}, {type: boolean}]}]}": "has no home for oneOf written on this inline entry", + "{allOf: [{$ref: '#/components/schemas/Str'}, {enum: [a, b], oneOf: [{enum: [a]}, {type: integer}]}]}": "oneOf/anyOf co-declared with structural keywords", + } { + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", types+" S: "+schema+"\n")) + var messages []string + for _, diagnostic := range diags { + if diagnostic.Code == diag.DegradedConstruct && diagnostic.Severity == ir.SeverityInfo && diagnostic.Provenance.Pointer == "/components/schemas/S/allOf/1" { + messages = append(messages, diagnostic.Message) + } + } + if assert.Len(t, messages, 1, "%s: the entry draws one finding: %v", schema, messages) { + assert.Contains(t, messages[0], want, schema) + } + } +} diff --git a/compilers/openapi/internal/schema/entrydiscriminator.go b/compilers/openapi/internal/schema/entrydiscriminator.go new file mode 100644 index 000000000..740468318 --- /dev/null +++ b/compilers/openapi/internal/schema/entrydiscriminator.go @@ -0,0 +1,62 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// writtenDiscriminator is the discriminator a model holds, the schema object +// writing it, and that object's pointer below the model's schema, empty for +// the schema's own. +type writtenDiscriminator struct { + discriminator *statement.Discriminator + conjunctSchema *statement.Schema + rel jsontext.Pointer +} + +// modelDiscriminatorOf keys modelDiscriminator's reading of one schema. +type modelDiscriminatorOf struct { + schema *statement.Schema +} + +// modelDiscriminator returns the discriminator of the model schema lowers to: +// its own, else, where no union sits with the conjunction, the first an inline +// allOf entry writes, lowered as one written beside the allOf +// (docs/compilers/openapi.md#discriminator). Every reader of a hierarchy asks, +// so it is read once a run. +func modelDiscriminator(loweringContext lowering.Ctx, schema *statement.Schema) writtenDiscriminator { + if discriminator := schema.Discriminator(); discriminator != nil { + return writtenDiscriminator{discriminator: discriminator, conjunctSchema: schema} + } + return lowering.ReadOncePerRun(loweringContext, modelDiscriminatorOf{schema}, func() writtenDiscriminator { + return entryDiscriminator(loweringContext, schema) + }) +} + +// entryDiscriminator is modelDiscriminator's reading of the entries of +// schema, which writes no discriminator of its own. +func entryDiscriminator(loweringContext lowering.Ctx, schema *statement.Schema) writtenDiscriminator { + if _, lowersUnion := readConjunction(loweringContext, schema).loweredUnion(); declaresUnion(schema) || lowersUnion { + return writtenDiscriminator{} + } + for _, entry := range loweringContext.Statements().Read(schema).Entries { + if entry.Schema == nil || entry.Ref != nil || declaresUnion(entry.Schema) { + continue + } + if discriminator := entry.Discriminator(); discriminator != nil { + return writtenDiscriminator{discriminator: discriminator, conjunctSchema: entry.Schema, rel: entry.Rel} + } + } + return writtenDiscriminator{} +} + +// discriminates reports whether the model schema lowers to holds a +// discriminator (modelDiscriminator). +func discriminates(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return modelDiscriminator(loweringContext, schema).discriminator != nil +} diff --git a/compilers/openapi/internal/schema/entrykept.go b/compilers/openapi/internal/schema/entrykept.go index b859ef5e4..8152a1efc 100644 --- a/compilers/openapi/internal/schema/entrykept.go +++ b/compilers/openapi/internal/schema/entrykept.go @@ -6,17 +6,16 @@ package schema import ( "bytes" "encoding/json/jsontext" - "maps" "slices" "strings" - "github.com/dexpace/morphic/compilers/compile" + yaml "go.yaml.in/yaml/v3" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/budget" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/promotion" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) @@ -24,42 +23,63 @@ import ( // keptEntry is what one inline allOf entry keeps verbatim beside what its // position lowered to (docs/compilers/openapi.md#allof-inline-residue): each // keyword nothing read, under the key and reason it has beside the allOf, or -// the entry whole, where a keyword of it is read against the rest of it or -// another conjunct writes it otherwise. +// the entry whole where a keyword of it is read against the rest of it. The +// node's pending keeps settle what another conjunct writes alike or otherwise. type keptEntry struct { entry allOfEntry - // residue is what the entry writes that nothing read, in the order written. - residue []string - // own is what of residue the entry keeps under its own keys: residue less - // what a rule consumes and what the position writes alike, which keeps it. + // unreadKeywords is what the entry writes that nothing read, in the order + // written. + unreadKeywords []string + // own is what of unreadKeywords the entry keeps: unreadKeywords less what a + // rule consumes. own []string - // alike is what of own another inline entry keeps alike, kept once, at the - // position's pointer. - alike []string // validation is what of own is a union of validation logic - // (entryUnionReason). + // (keptUnionReason). validation []string - // apart is what an entry the position lowers from (lowersFrom) keeps that - // another conjunct writes otherwise: under its own key where the position - // holds none there, else under the entry's, the rest of it lowered - // (wholePrincipal). - apart []string - // whole is why the entry is kept whole, keptApart where it is not. + // whole is why the entry is kept whole for a cause read before lowering, + // keptApart where none is. whole wholeCause - // reason is what a whole entry is kept as (sharedReason). + // folded says the entry folds what its conjuncts agree on, beside what it + // keeps (allOfEntryFolding). + folded bool + // reason is what the entry kept whole is kept as, the reason its pending keeps + // share once the node settles, for its report. reason ir.UnmodeledReason - // numberText says the position's own node carries a number as text, whose - // Constraints hold no value bound own keeps (keepTextBounds). - numberText bool -} + // text is the value bounds the position's own node or holder keeps + // verbatim, its value of another kind, root saying which, whose + // Constraints hold none of them own keeps (keepTextBounds). + text keySet + root boundRoot + // carried keeps each keyword the carrier holding the position has no field + // for, as it keeps its own, nil at a node. + carried CarrierKeywordKeeps + // unionWhy says why a union the entry keeps is no variant's, as the same + // union written beside the allOf says it (lowerCoDeclaredUnion), "" where + // the entry's position composes. + unionWhy string + // contentKeptBeside says the entry's content vocabulary is kept beside a + // $ref to a target carrying an Encoding of another name, reported as a + // kept format is (keywordBesideRef.keepsContentOf). + contentKeptBeside bool + // setsApart says the position's value sets share no member, which its one + // warning reports, so the entry's own reports name none of them. + setsApart bool + // passedOverAt is the position whose chosen const passes over an enum the + // entry writes, reported there as the same enum written beside it is, "" + // where no const is chosen. + passedOverAt jsontext.Pointer +} + +// CarrierKeywordKeeps holds, by keyword, the function keeping what a carrier +// has no field for, written by schema at pointer, on unmodeled, as the carrier +// keeps its schema's own. +type CarrierKeywordKeeps map[string]func(unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic // keeps reports whether k keeps anything. -func (k keptEntry) keeps() bool { return k.keptWhole() || len(k.own) > 0 || len(k.apart) > 0 } +func (k keptEntry) keeps() bool { return k.keptWhole() || len(k.own) > 0 } -// keptWhole reports whether k is kept whole, holding what its entry writes: it -// is no writer of a keyword it writes alike with another conjunct, kept apart -// or folded, which that conjunct keeps alone -// (annotation.FoldedAllOfEntry.KeptWhole). +// keptWhole reports whether k is kept whole for a cause read before lowering, +// holding what its entry writes (annotation.KeptAllOfEntry.KeptWhole). func (k keptEntry) keptWhole() bool { return k.whole != keptApart } // wholeCause is why an inline allOf entry is kept whole. @@ -79,7 +99,7 @@ const ( // reference against another base than the position does. keptWholeBecauseReadAgainstAnotherBase // keptWholeBecauseConjunctsDisagree marks one writing what folds, which - // another conjunct writes otherwise (foldingAllOfEntries). + // another conjunct writes otherwise (allOfEntryFoldingOf). keptWholeBecauseConjunctsDisagree // keptWholeBecauseKeywordCannotShareEntry marks one keeping a keyword // another conjunct writes otherwise, which one entry under that keyword @@ -88,70 +108,43 @@ const ( ) // entryKeeps decides what each inline entry of comp, the allOf schema writes, -// keeps of what residueOf says it left unread, by index: nothing where that is -// nothing a rule does not consume, else the entry whole (wholeCauseOf), where -// closure names a keyword the position types no closure from, else each keyword -// apart. allOfEntryFoldingValue is schema's folding, nil where its allOf does -// not decide, and principal the inline principal the position lowers from, nil -// for none: what it or a wrapper around it (lowersFrom) keeps that another -// conjunct writes otherwise never keeps it whole (keptEntry.apart). -func entryKeeps(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, residueOf func(int) []string, - allOfEntryFoldingValue allOfEntryFolding, closure func(string) bool, principal *allOfEntry, +// keeps of what unreadKeywordsOf says it left unread, by index. closure names +// a keyword the position types no closure from, and allOfEntryFoldingValue is +// schema's folding, nil where its allOf does not decide. What another conjunct +// of the node writes otherwise the node's pending keeps settle. +func entryKeeps(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, unreadKeywordsOf func(int) []string, + allOfEntryFoldingValue allOfEntryFolding, closure func(string) bool, ) []keptEntry { out := make([]keptEntry, len(comp.entries)) for i := range comp.entries { - out[i] = keptEntry{entry: comp.entries[i], residue: withDraftDependencies(loweringContext, schema, comp, i, residueOf(i))} - } - kepts := make([][]string, len(out)) - for i, keptEntry := range out { - kepts[i] = keptOf(loweringContext, keptEntry) - } - apart, apartKept := writtenApartKeys(loweringContext, schema, comp, kepts, new(budget.Budget)) - held := map[string]int{} - for i, keptEntry := range out { - kept := kepts[i] + out[i] = keptEntry{entry: comp.entries[i], unreadKeywords: withDraftDependencies(loweringContext, schema, comp, i, unreadKeywordsOf(i))} + kept := keptOf(loweringContext, out[i]) if len(kept) == 0 { continue } - apartHere := apart - if failedRef(loweringContext, keptEntry.entry) { - apartHere = apartKept - } - var otherwise []string - if lowersFrom(principal, keptEntry.entry) { - otherwise = slices.DeleteFunc(slices.Clone(kept), func(key string) bool { return !apartHere[key] }) - kept = slices.DeleteFunc(kept, func(key string) bool { return apartHere[key] }) - } - out[i].whole = wholeCauseOf(loweringContext, comp, i, keptEntry.residue, allOfEntryFoldingValue, closure, kept, apartHere) - if out[i].keptWhole() { - out[i].reason = sharedReason(loweringContext, schema, comp, i, slices.Concat(kept, otherwise)) - continue - } - out[i].apart = otherwise - out[i].own = slices.DeleteFunc(kept, func(key string) bool { return hasKey(schema, key) }) - for _, key := range out[i].own { - held[key]++ - if (key == "oneOf" || key == "anyOf") && entryUnionReason(loweringContext, schema, comp, i) == ir.ReasonValidationOnly { + out[i].whole = wholeCauseOf(loweringContext, comp, i, out[i].unreadKeywords, allOfEntryFoldingValue, closure, kept) + out[i].folded = allOfEntryFoldingValue.entryFoldsIntoPosition != nil && allOfEntryFoldingValue.entryFoldsIntoPosition[i] + out[i].own, out[i].unionWhy = kept, foldedUnionWhy(loweringContext, schema, comp.entries[i].schema.Schema) + for _, key := range kept { + if isUnionKeyword(key) && comp.entries[i].schema.Ref == nil && + keptUnionReason(loweringContext, schema, conjunctionUnion{holder: comp.entries[i].schema.Schema, keyword: unionKeyword(key)}) == ir.ReasonValidationOnly { out[i].validation = append(out[i].validation, key) } } } - for i := range out { - out[i].alike = slices.DeleteFunc(slices.Clone(out[i].own), func(key string) bool { return held[key] < 2 }) - } return out } -// withDraftDependencies returns residue, what the entry at index i of comp -// leaves unread, with the `dependencies` it writes where foldsNoDependencies -// says that does not fold: kept, it is held against the position's as any -// keyword two conjuncts keep is. -func withDraftDependencies(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, i int, residue []string) []string { - bs := comp.entries[i].schema.Schema - if !hasKey(bs, "dependencies") || slices.Contains(residue, "dependencies") || !foldsNoDependencies(loweringContext, schema, comp.pointer) { - return residue +// withDraftDependencies returns unreadKeywords, what the entry at index i of +// comp leaves unread, with the `dependencies` it writes where +// foldsNoDependencies says that does not fold: kept, it is held against the +// position's as any keyword two conjuncts keep is. +func withDraftDependencies(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, i int, unreadKeywords []string) []string { + entrySchema := comp.entries[i].schema.Schema + if !hasKey(entrySchema, "dependencies") || slices.Contains(unreadKeywords, "dependencies") || !foldsNoDependencies(loweringContext, schema, comp.pointer) { + return unreadKeywords } - return unmergedEntryKeys(bs, func(key string) bool { return key != "dependencies" && !slices.Contains(residue, key) }) + return unmergedEntryKeys(entrySchema, func(key string) bool { return key != "dependencies" && !slices.Contains(unreadKeywords, key) }) } // foldsNoDependencies reports whether schema, written at pointer, writes a @@ -164,185 +157,48 @@ func foldsNoDependencies(loweringContext lowering.Ctx, schema *statement.Schema, return hasKey(schema, "dependencies") && writesUnknown(loweringContext, schema, "dependencies", pointer) } -// markKeptWhole marks each of voices, the voices of s written at pointer, which -// lowered to target, whose entry the outcome keeps whole (keptWhole), so -// annotation.Read counts it as no writer of what it folds, as entryKeeps -// counts no such entry as a writer of what it keeps: the entry holds it once. -// One voice writes no keyword alike with another, so fewer than two stand. -func markKeptWhole(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, - foldedEntries []annotation.FoldedAllOfEntry, -) []annotation.FoldedAllOfEntry { - if len(foldedEntries) < 2 { - return foldedEntries - } - var kept []keptEntry - if _, refined := refinementOf(loweringContext, schema, pointer); refined { - kept = keepsAtOutcome(loweringContext, schema, target, pointer).entries - } else { - kept = readAllOf(loweringContext, schema, pointer).kept - } - whole := map[jsontext.Pointer]bool{} - for _, keptEntry := range kept { - if keptEntry.keptWhole() { - whole[keptEntry.entry.pointer] = true - } - } - if len(whole) == 0 { - return foldedEntries - } - out := slices.Clone(foldedEntries) - for i, foldedAllOfEntry := range out { - out[i].KeptWhole = whole[foldedAllOfEntry.At] - } - return out -} - -// writtenApartKeys returns which of the keywords the entries of comp keep, -// kepts by index, their writers write apart: otherwise than one another, or in -// a value that cannot be rendered. The writers are schema and the inline -// entries (and $refs naming nothing) writing the key; among keepers, as a $ref -// naming nothing is asked, only the entries keeping it, as no merge or fold of -// another entry parts it. Each writer is read once whatever it keeps: reads is -// charged a step for each key asked of. -func writtenApartKeys(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, kepts [][]string, - reads *budget.Budget, -) (writers, keepers map[string]bool) { - asked, askedKeepers := writtenKeys{}, writtenKeys{} - for i, kept := range kepts { - failed := len(kept) > 0 && failedRef(loweringContext, comp.entries[i]) - for _, key := range kept { - asked[key] = keyWrite{} - if failed { - askedKeepers[key] = keyWrite{} - } - } - } - asked.readWriter(schema, reads) - askedKeepers.readWriter(schema, reads) - for i, entry := range comp.entries { - if (entry.schema.Ref != nil && !failedRef(loweringContext, entry)) || !stated(entry.schema.Schema) { - continue - } - asked.readWriter(entry.schema.Schema, reads) - askedKeepers.readKept(entry.schema.Schema, kepts[i], reads) - } - return asked.apart(), askedKeepers.apart() -} - -// keyWrite is what the writers of one key met so far write: the first one's -// rendering, and whether any writer wrote it otherwise or could not be -// rendered, which no later writer changes. -type keyWrite struct { - first ir.RawValue - met bool - apart bool -} - -// writtenKeys maps each key asked of to what its writers met so far write. -type writtenKeys map[string]keyWrite - -// readWriter notes of each key bs writes that w asks of, what it writes. -func (w writtenKeys) readWriter(bs *statement.Schema, reads *budget.Budget) { - if len(w) == 0 { - return - } - for _, key := range bs.Keys { - reads.Spend(1) - if _, asked := w[key.Name]; asked { - w.note(bs, key.Name) - } - } -} - -// readKept notes of each of kept, the keys an entry bs keeps, that w asks of, -// what bs writes, where it writes it. -func (w writtenKeys) readKept(bs *statement.Schema, kept []string, reads *budget.Budget) { - if len(w) == 0 { - return - } - for _, key := range kept { - reads.Spend(1) - if _, asked := w[key]; asked { - w.note(bs, key) - } - } -} - -// note records what bs writes for key, unless it writes none (hasKey): the -// first writer's rendering is kept and each later one is compared with it, and -// a key already apart is read no further. -func (w writtenKeys) note(bs *statement.Schema, key string) { - statementKey, read := bs.Key(key) - if !read { - return - } - seen := w[key] - if seen.apart { - return - } - raw, err := annotation.RawFromNode(statementKey.Node) - switch { - case err != nil || (seen.met && !bytes.Equal(seen.first, raw)): - seen = keyWrite{met: true, apart: true} - case !seen.met: - seen = keyWrite{first: raw, met: true} - } - w[key] = seen -} - -// apart returns which of the keys asked of their writers write apart. -func (w writtenKeys) apart() map[string]bool { - out := make(map[string]bool, len(w)) - for key, seen := range w { - out[key] = seen.apart - } - return out -} - -// keptOf is what of keptEntryValue's residue a rule does not consume +// keptOf is what of keptEntryValue's unreadKeywords a rule does not consume // (consumedByRule): what the entry keeps, whole or apart. func keptOf(loweringContext lowering.Ctx, keptEntryValue keptEntry) []string { - if len(keptEntryValue.residue) == 0 { + if len(keptEntryValue.unreadKeywords) == 0 { return nil } - bs := keptEntryValue.entry.schema.Schema - return slices.DeleteFunc(slices.Clone(keptEntryValue.residue), func(key string) bool { - return consumedByRule(loweringContext, bs, key, keptEntryValue.entry.pointer) + entrySchema := keptEntryValue.entry.schema.Schema + return slices.DeleteFunc(slices.Clone(keptEntryValue.unreadKeywords), func(key string) bool { + return consumedByRule(loweringContext, entrySchema, key, keptEntryValue.entry.pointer) }) } -// consumedByRule reports whether key, a key bs writes at pointer, is one the -// dialect reads as a target or drops, beside an allOf and on its entry alike: -// $comment, $anchor, $dynamicAnchor and $defs, or a draft's twin of one, but -// where the dialect bs is read in defines no such keyword +// consumedByRule reports whether key, a key entrySchema writes at pointer, is +// one the dialect reads as a target or drops, beside an allOf and on its entry +// alike: one scoped to its own object that says nothing of the instance, as a +// comment or an anchor, where the dialect entrySchema is read in defines it // (docs/compilers/openapi.md#dialect-keywords). -func consumedByRule(loweringContext lowering.Ctx, bs *statement.Schema, key string, pointer jsontext.Pointer) bool { - switch TwinKeyword(loweringContext, bs, key) { - case "$comment", "$anchor", "$dynamicAnchor", "$defs": - return !writesUnknown(loweringContext, bs, key, pointer) - default: +func consumedByRule(loweringContext lowering.Ctx, entrySchema *statement.Schema, key string, pointer jsontext.Pointer) bool { + written, ok := entrySchema.Key(key) + if !ok || rulesOf(loweringContext, entrySchema).KeywordScopeOf(key) != specrules.KeywordScopeOwnObject || statement.ReadBeside(written, "") { return false } + return !writesUnknown(loweringContext, entrySchema, key, pointer) } -// wholeCauseOf returns why the inline entry at index i of comp, leaving residue -// unread, of which it keeps kept, is kept whole, and keptApart where it keeps -// each keyword apart. apart says which keywords their writers write apart. -func wholeCauseOf(loweringContext lowering.Ctx, comp allOfComposition, i int, residue []string, allOfEntryFoldingValue allOfEntryFolding, - closure func(string) bool, kept []string, apart map[string]bool, +// wholeCauseOf returns why the inline entry at index i of comp, leaving +// unreadKeywords unread, of which it keeps kept, is kept whole for a cause read +// before lowering, and keptApart where none is: a keyword another conjunct +// keeps otherwise the node's pending keeps settle. +func wholeCauseOf(loweringContext lowering.Ctx, comp allOfComposition, i int, unreadKeywords []string, allOfEntryFoldingValue allOfEntryFolding, + closure func(string) bool, kept []string, ) wholeCause { entry := comp.entries[i] switch { - case slices.ContainsFunc(residue, closure) || slices.ContainsFunc(residue, unevaluatedKeyword): + case slices.ContainsFunc(unreadKeywords, closure) || slices.ContainsFunc(unreadKeywords, scopedConstraint(rulesOf(loweringContext, entry.schema.Schema))): return keptWholeBecauseOfClosure - case entry.capped || slices.Contains(residue, "allOf"): + case entry.capped || slices.Contains(unreadKeywords, "allOf"): return keptWholeBecauseAllOfNotFlattened case allOfEntryFoldingValue.rebased != nil && allOfEntryFoldingValue.rebased[i] || readsElsewhere(loweringContext, comp, entry, kept): return keptWholeBecauseReadAgainstAnotherBase - case entry.schema.Ref == nil && (allOfEntryFoldingValue.entryFoldsIntoPosition == nil || !allOfEntryFoldingValue.entryFoldsIntoPosition[i]) && disagreed(loweringContext, entry.schema.Schema, residue): + case entry.schema.Ref == nil && !allOfEntryFoldingValue.foldsWhole(i) && disagreed(loweringContext, entry.schema.Schema, unreadKeywords): return keptWholeBecauseConjunctsDisagree - case slices.ContainsFunc(kept, func(key string) bool { return apart[key] }): - return keptWholeBecauseKeywordCannotShareEntry default: return keptApart } @@ -350,17 +206,17 @@ func wholeCauseOf(loweringContext lowering.Ctx, comp allOfComposition, i int, re // failedRef reports whether allOfEntryValue is a $ref entry whose reference // lands on no schema, as resolveSchemaRef finds, a loop of $refs among them: no -// node stands for it, so nothing reads what it writes. +// node names it, so nothing reads what it writes. func failedRef(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) bool { return allOfEntryValue.schema.Ref != nil && !namesReferent(loweringContext, allOfEntryValue.schema) } -// failedRefResidue is what the $ref entry e writes that nothing reads, in the -// order written, where its reference names nothing, else nil: every keyword -// beside the reference but `required`, which the composition's members read -// (compositionRequired). Where the reference resolves, its target's alias homes -// the keywords beside it (fillRefEntry). -func failedRefResidue(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) []string { +// failedRefUnreadKeywords is what the $ref entry allOfEntryValue writes that +// nothing reads, in the order written, where its reference names nothing, else +// nil: every keyword beside the reference but `required`, which the +// composition's members read (compositionRequired). Where the reference +// resolves, its target's alias homes the keywords beside it (fillRefEntry). +func failedRefUnreadKeywords(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) []string { if !failedRef(loweringContext, allOfEntryValue) { return nil } @@ -368,307 +224,313 @@ func failedRefResidue(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) return unmergedEntryKeys(allOfEntryValue.schema.Schema, func(key string) bool { return key == keyword || key == "required" }) } -// unevaluatedKeyword reports whether keyword is an unevaluated one, which on an -// entry holds the instance to what that entry alone evaluates. -func unevaluatedKeyword(keyword string) bool { - return keyword == "unevaluatedProperties" || keyword == "unevaluatedItems" +// scopedConstraint returns whether a keyword, read with rules, constrains the +// instance and is scoped to its own object (specrules.KeywordScopeOf): an +// unevaluated one, which on an entry holds the instance to what that entry +// alone evaluates. Identifiers and comments are scoped so too and constrain +// nothing, and a key the rows do not define is kept where written. +func scopedConstraint(rules specrules.SchemaRules) func(string) bool { + return func(keyword string) bool { + switch specrules.SlotOf(keyword) { + case specrules.SlotResource, specrules.SlotNotes, specrules.SlotUnknown: + return false + default: + return (rules.Defines(keyword) || rules.Later(keyword)) && rules.KeywordScopeOf(keyword) == specrules.KeywordScopeOwnObject + } + } } // readsElsewhere reports whether a keyword the inline entry allOfEntryValue of -// comp keeps, of residue, writes a relative reference at any depth, read +// comp keeps, of unreadKeywords, writes a relative reference at any depth, read // against another base than the position's: an identifier at or above the entry // names another URI (underID, readsAtPosition), so the reference, kept apart // from that identifier, would name another schema. What the entry merges in // place is lowered where it is written, against its own base. -func readsElsewhere(loweringContext lowering.Ctx, comp allOfComposition, allOfEntryValue allOfEntry, residue []string) bool { - bs := allOfEntryValue.schema.Schema - if !underID(allOfEntryValue, bs, idWrappers(comp)) { +func readsElsewhere(loweringContext lowering.Ctx, comp allOfComposition, allOfEntryValue allOfEntry, unreadKeywords []string) bool { + entrySchema := allOfEntryValue.schema.Schema + if !underID(allOfEntryValue, entrySchema, idWrappers(comp)) { return false } - return slices.ContainsFunc(residue, func(key string) bool { - raw, err := annotation.RawFromNode(keyNode(bs, key)) + return slices.ContainsFunc(unreadKeywords, func(key string) bool { + raw, err := annotation.RawFromNode(keyNode(entrySchema, key)) return err != nil || annotation.WritesReference(raw) }) && !readsAtPosition(loweringContext, allOfEntryValue) } -// sharedReason is the reason the keywords kept of the inline entry at index i -// of comp, the allOf schema writes, share where they share one, else -// degraded_lowering: what a consumer filtering by reason reads of the entry -// kept whole. -func sharedReason(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, i int, kept []string) ir.UnmodeledReason { - var shared ir.UnmodeledReason - for n, key := range kept { - reason := keywordReason(loweringContext, schema, comp, i, key) - if n > 0 && reason != shared { - return ir.ReasonDegradedLowering - } - shared = reason +// keptUnionReason is the reason union, a union the conjunction of schema writes +// that a node keeps verbatim, is kept under, as one written beside the allOf +// would be (docs/compilers/openapi.md#union-beside-structure): where the union +// the conjunction chooses is kept beside its body, every union is kept as that +// one is; otherwise degraded where its branches declare a shape against the +// body (docs/compilers/openapi.md#competing-keywords). +func keptUnionReason(loweringContext lowering.Ctx, schema *statement.Schema, union conjunctionUnion) ir.UnmodeledReason { + if reason, kept := loweredUnionKeptReason(loweringContext, schema); kept { + return reason } - return shared -} - -// logicKeywords are the validation-only keywords a schema keeps under -// ReasonValidationOnly (docs/compilers/openapi.md#validation-only), as their -// 2020-12 twins (TwinKeyword). -var logicKeywords = []string{ - "not", "if", "then", "else", "dependentSchemas", "dependentRequired", "propertyNames", - "contains", "minContains", "maxContains", -} - -// keywordReason is the reason key, a keyword the inline entry at index i of -// comp, the allOf schema writes, writes, is kept under on its own, as beside -// the allOf: its slot's (docs/compilers/openapi.md#allof-inline-residue). -func keywordReason(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, i int, key string) ir.UnmodeledReason { - entry := comp.entries[i] - bs := entry.schema.Schema - twin := TwinKeyword(loweringContext, bs, key) - switch { - case strings.HasPrefix(key, "x-"): - return ir.ReasonVendorExtension - case key == "dependencies" && twin != key: - // A draft's own keyword, validation logic as written flat in it. - return ir.ReasonValidationOnly - case annotation.DialectKeyword(twin), writesUnknown(loweringContext, bs, key, entry.pointer): - return ir.ReasonOutOfScope - case slices.Contains(logicKeywords, twin), unevaluatedKeyword(twin): - return ir.ReasonValidationOnly - case key == "oneOf" || key == "anyOf": - return entryUnionReason(loweringContext, schema, comp, i) - case slices.Contains(contentKeywords, key): - return ir.ReasonNoIRHome - default: - return ir.ReasonDegradedLowering - } -} - -// entryUnionReason is the reason the oneOf or anyOf the inline entry at index i -// of comp, the allOf schema writes, is kept under, as the union beside schema -// would be: validation logic where its branches declare no shape against -// schema, and degraded where they do or the union shares no kind with the rest -// (docs/compilers/openapi.md#union-beside-structure). Where schema refines to -// no union, each kept union is judged with the others, as beside schema -// (keptUnion). -func entryUnionReason(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, i int) ir.UnmodeledReason { - holder := comp.entries[i].schema.Schema - choice := holder.ChoiceKeywords() - sets := [][]statement.Subschema{choice.OneOf, choice.AnyOf} - if refinesToNoUnion(loweringContext, schema) { - sets = entryUnionSets(comp) - } - if unionApart(loweringContext, schema, comp, i) || setsDeclareShape(loweringContext, schema, holder, sets...) || - keptWithElected(loweringContext, schema, comp.pointer) || pairedWithNullOnly(loweringContext, schema) { + if setsDeclareShape(loweringContext, schema, union.branches()) { return ir.ReasonDegradedLowering } return ir.ReasonValidationOnly } -// refinesToNoUnion reports whether schema, writing no union, refines to a -// principal writing none, so every union its entries write is kept beside it. -func refinesToNoUnion(loweringContext lowering.Ctx, schema *statement.Schema) bool { - decision := decisionOf(loweringContext, schema) - if !decision.refines || declaresUnion(schema) { - return false - } - return decision.principalAt < 0 || !declaresUnion(entryStatement(loweringContext, schema, decision.principalAt).Schema) -} - -// entryUnionSets returns the branch sets of every union comp's inline entries -// write, in order. -func entryUnionSets(comp allOfComposition) [][]statement.Subschema { - var sets [][]statement.Subschema - for _, entry := range comp.entries { - if entry.schema.Ref != nil { - continue - } - choice := entry.schema.ChoiceKeywords() - sets = append(sets, choice.OneOf, choice.AnyOf) - } - return sets -} - -// pairedWithNullOnly reports whether schema refines to the union one inline -// entry of its allOf writes, of a pair (electsOneOfPair), every branch of which -// is a null branch: the position lowers as null alone, which keeps the union -// passed over as degraded_lowering, as the same two beside the allOf do, a body -// beside them or none (docs/compilers/openapi.md#union-null-only). -func pairedWithNullOnly(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return electsOneOfPair(loweringContext, schema) && allNullUnion(loweringContext, schema, entryStatement(loweringContext, schema, decisionOf(loweringContext, schema).principalAt).Schema) -} - -// keptWithElected reports whether schema, written at pointer, elects the union -// an entry of its allOf writes and keeps it whole on that entry, as the shapes -// of docs/compilers/openapi.md#union-beside-structure do, which keep every -// other union as they keep that one, as degraded_lowering, as beside the allOf. -func keptWithElected(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) bool { - unionAt, _, distributed := entryUnion(loweringContext, schema, pointer) - return unionAt.holder != nil && !distributed -} - -// unionApart reports whether the oneOf and anyOf the inline entry at index i of -// comp writes, with those other inline entries write where schema writes none, -// share no kind with what the rest of schema, the schema writing comp, admits, -// the entries' other keywords among it: no instance satisfies them together, as -// admissionReader.conjuncts reads two unions beside the allOf. A read cut short -// says no. -func unionApart(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, i int) bool { - admissionReader := newAdmissionReader(loweringContext) - bs := comp.entries[i].schema.Schema - union := unionsIn(&admissionReader, bs) - rest := admissionReader.written(schema, admissionReader.nullable).and(admissionReader.written(bs, admissionReader.nullable)) - if declaresUnion(schema) { - rest = rest.and(unionsIn(&admissionReader, schema)) - } - for j, entry := range comp.entries { - switch { - case j == i || !stated(entry.schema.Schema): - case entry.schema.Ref != nil: - rest = rest.and(admissionReader.of(entry.schema)) - case !declaresUnion(schema) && declaresUnion(entry.schema.Schema): - // Unions on two entries are read together, as two beside the - // allOf are (unionAside). - union = union.and(unionsIn(&admissionReader, entry.schema.Schema)) - rest = rest.and(admissionReader.written(entry.schema.Schema, admissionReader.nullable)) - default: - rest = rest.and(inlineConjunct(&admissionReader, entry.schema.Schema)) - } +// loweredUnionKeptReason returns the reason the union schema's conjunction +// chooses is kept under beside its body, and false where it is not kept but +// lowered. +func loweredUnionKeptReason(loweringContext lowering.Ctx, schema *statement.Schema) (ir.UnmodeledReason, bool) { + switch readLoweredUnion(loweringContext, schema).besideRest { + case unionLeavesNoBranch, unionLeavesNullAlone, unionKeptByRest, unionKeptWithDeadBranch, unionUnresolvedBranch, unionHierarchyBase: + return ir.ReasonDegradedLowering, true + case unionKeptAsValidation, unionValidationOnly: + return ir.ReasonValidationOnly, true + default: + return "", false } - return !admissionReader.incomplete() && rest.reachable() && union.kinds&^kindNull != 0 && rest.kinds&union.kinds == 0 } -// recordKeptEntry keeps keptEntryValue, an inline entry of comp, on unmodeled, -// beside what the allOf lowered to, shape, and reports it: whole, under the -// entry's key and keptEntryValue.reason, reported by report, or each keyword -// apart (recordOwnKeywords), warn turning the report of what has no home into a -// warning. A keyword other inline entries keep alike takes the provenance of -// the position comp is written at. -func recordKeptEntry(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, comp allOfComposition, - keptEntryValue keptEntry, shape string, warn bool, report func(keptEntry) ir.Diagnostic, +// addKeptEntryPendingKeeps adds as pending keeps what keptEntryValue, an inline +// entry of comp related to the position as role says, keeps beside shape, what +// the allOf lowered to: the entry, reported by report where kept whole, and +// each keyword it keeps as written flat, warn turning the report of what has +// no home into a warning. +func addKeptEntryPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, comp allOfComposition, + keptEntryValue keptEntry, role annotation.ConjunctRole, shape string, warn bool, report func(keptEntry) ir.Diagnostic, ) []ir.Diagnostic { if !keptEntryValue.keeps() { return nil } - schemaEntry := keptEntryValue.entry - if keptEntryValue.keptWhole() { - kept, diags := preserveNode(loweringContext, unmodeled, comp.entryKey(schemaEntry.pointer), schemaEntry.schema.Node, keptEntryValue.reason, schemaEntry.pointer) - if !kept { - return diags - } - return append(diags, report(keptEntryValue)) - } - var held ir.Unmodeled - diags := recordOwnKeywords(loweringContext, ts, &held, keptEntryValue, shape, warn) - for _, key := range keptEntryValue.alike { - if entry, ok := held[annotation.EntryKey("", key)]; ok { - entry.Provenance = loweringContext.Place().At(comp.pointer) - held[annotation.EntryKey("", key)] = entry - } - } - return append(diags, mergeKept(loweringContext, unmodeled, held, schemaEntry.pointer)...) + site := entrySiteAt(comp, keptEntryValue.entry.pointer, role) + pendingKeeps.AddEntry(keptEntrySite(loweringContext, comp, keptEntryValue, site, report)) + var own annotation.PendingKeeps + diags := addOwnKeywordPendingKeeps(loweringContext, &own, site, keptEntryValue, shape, warn) + own.AsOneReading() + pendingKeeps.AddAll(own) + return diags } -// dropFoldedIntoWhole removes from unmodeled each entry an allOf entry kept -// whole holds, what its fold kept beside it, so that is kept once, inside the -// entry (docs/ir/unmodeled.md#keys); a key the promotion policy reads stays. An -// entry kept whole within another stays under its own path too, as -// docs/compilers/openapi.md#allof-inline-residue keeps it. -func dropFoldedIntoWhole(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled) { - var whole ir.Unmodeled - for key, entry := range *unmodeled { - if strings.HasPrefix(key, allOfKeyPrefix) && !writesTopLevelRef(entry.Value) { - whole = annotation.MergeUnmodeled(whole, ir.Unmodeled{key: entry}) +// keptEntrySite is the entry keptEntryValue of comp, written at site, as the +// node's pending keeps hold it, with the reports of what its key holds, whole +// (report) or apart (otherwiseReport). +func keptEntrySite(loweringContext lowering.Ctx, comp allOfComposition, keptEntryValue keptEntry, site annotation.ConjunctSite, + report func(keptEntry) ir.Diagnostic, +) annotation.KeptAllOfEntry { + entry := keptEntryValue.entry + whole, dropped := renderedWhole(entry.schema.Node) + return annotation.KeptAllOfEntry{ + Site: site, Whole: whole, Dropped: dropped, Provenance: loweringContext.Place().At(entry.pointer), KeptWhole: keptEntryValue.keptWhole(), + AgainstKept: failedRef(loweringContext, entry), + ReportWhole: func(held []string, reason ir.UnmodeledReason) []ir.Diagnostic { + told := keptEntryValue + told.unreadKeywords = slices.DeleteFunc(heldOf(keptEntryValue, held), func(keyword string) bool { + return slices.Contains(dropped, jsontext.Pointer("").AppendToken(keyword)) + }) + if !told.keptWhole() { + if keptEntryValue.setsApart { + // What collides is a value set, which the one warning reports. + return nil + } + told.whole = keptWholeBecauseKeywordCannotShareEntry + } + told.reason = reason + return append([]ir.Diagnostic{report(told)}, KeepDiscriminatorsWithin(loweringContext, nil, entry.pointer)...) + }, + ReportApart: func(apart []string) []ir.Diagnostic { + return append([]ir.Diagnostic{otherwiseReport(loweringContext, comp, apart, entry.pointer)}, + discriminatorsKept(loweringContext, apart, entry.pointer)...) + }, + } +} + +// renderedWhole renders node, an entry kept whole, but each vendor extension +// no JSON holds, which it leaves out, returning their pointers from node: nil +// where no JSON holds the rest, or nothing is left of it. +func renderedWhole(node *yaml.Node) (ir.RawValue, []jsontext.Pointer) { + whole, dropped, err := annotation.RenderDroppingExtensions(node) + if err != nil || len(dropped) > 0 && bytes.Equal(whole, []byte("{}")) { + return nil, dropped + } + return whole, dropped +} + +// heldOf returns the keywords an entry kept whole holds, what keptEntryValue +// leaves unread and the keywords its conjuncts added as pending keeps, in the +// order written. +func heldOf(keptEntryValue keptEntry, held []string) []string { + out := slices.Clone(keptEntryValue.unreadKeywords) + order := keptEntryValue.entry.schema.Schema + for _, keyword := range held { + if !slices.Contains(out, keyword) && keyIndex(order, keyword) < len(order.Keys) { + out = append(out, keyword) } } - if len(whole) == 0 { - return - } - promotion.DropContained(loweringContext.Promoter(), unmodeled, slices.Collect(maps.Keys(whole))...) - maps.Copy(*unmodeled, whole) + slices.SortStableFunc(out, func(a, b string) int { return keyIndex(order, a) - keyIndex(order, b) }) + return out } -// writesTopLevelRef reports whether raw, a kept entry's value, is an object -// naming a $ref member: a $ref entry an allOf keeps whole, which folds nothing, -// where an inline one writes none. Asking only inline entries what they hold -// keeps the question linear in an allOf of many $refs. -func writesTopLevelRef(raw ir.RawValue) bool { - dec := jsontext.NewDecoder(bytes.NewReader(raw)) - if tok, err := dec.ReadToken(); err != nil || tok.Kind() != '{' { - return false - } - for dec.PeekKind() == '"' { - name, err := dec.ReadToken() - if err != nil { - return false - } - if name.String() == "$ref" { - return true - } - if dec.SkipValue() != nil { - return false - } +// keyIndex is the index of keyword among the keys schema writes, past every +// one where it writes none. +func keyIndex(schema *statement.Schema, keyword string) int { + if i := slices.IndexFunc(schema.Keys, func(key statement.Key) bool { return key.Name == keyword }); i >= 0 { + return i } - return false + return len(schema.Keys) } -// allOfKeyPrefix opens the key of an allOf entry kept whole (entryKey). -const allOfKeyPrefix = "openapi:allOf/" - -// mergeKept writes held, what an inline entry at pointer keeps apart, onto -// unmodeled. No other reader keeps one of its keys otherwise (entryKeeps), so a -// key held with another value is an invariant broken, reported, never -// overwritten. -func mergeKept(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, held ir.Unmodeled, pointer jsontext.Pointer) []ir.Diagnostic { - var diags []ir.Diagnostic - for _, key := range slices.Sorted(maps.Keys(held)) { - if other, taken := (*unmodeled)[key]; taken && !bytes.Equal(other.Value, held[key].Value) { - diags = append(diags, loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, - "internal: %s, kept apart from this allOf entry, is held with another value", key)) - continue - } - if *unmodeled == nil { - *unmodeled = make(ir.Unmodeled, len(held)) +// otherwiseReport reports the keywords apart, which an inline entry of comp +// the position lowers from, written at pointer, writes otherwise than another +// conjunct keeps them, kept under its entry's key, which every carrier's key +// ends in, so the report names the entry's path. +func otherwiseReport(loweringContext lowering.Ctx, comp allOfComposition, apart []string, pointer jsontext.Pointer) ir.Diagnostic { + position, entry := heldAt(loweringContext, comp.pointer).Schema, heldAt(loweringContext, pointer).Schema + written := func(key string) bool { return hasKey(position, boundFoldKey(entry, key)) } + beside := slices.ContainsFunc(apart, written) + elsewhere := slices.ContainsFunc(apart, func(key string) bool { return !written(key) }) + othersText, differ := "the keywords beside "+comp.subject(), "otherwise than" + switch { + case !beside: + othersText, differ = "the other entries of "+comp.subject(), "differently from" + case elsewhere: + othersText += " and its other entries" + } + return loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + "%s write %s %s this inline entry, and one Unmodeled entry under a keyword holds one value; the entry's are "+ + "kept verbatim under Unmodeled under the key naming it, %s, the rest of it lowered", + othersText, strings.Join(apart, ", "), differ, comp.entryPath(pointer)) +} + +// boundFoldKey returns the keyword key, written on schema, settles with: the +// bound a boolean exclusive flag modifies (boundModifiedBy), which writes it +// as one unit, and key itself for any other. +func boundFoldKey(schema *statement.Schema, key string) string { + if node := keyNode(schema, key); node != nil { + if bound := boundModifiedBy(key, node); bound != "" { + keyword, _ := annotation.EntryKeyword(bound) + return keyword } - (*unmodeled)[key] = held[key] } - return diags + return key } -// recordOwnKeywords keeps each keyword of k.own verbatim on unmodeled, under -// its own key and the reason its slot gives, and reports them as beside the -// allOf: an unknown, content, dialect or dynamic reference keyword at the -// keyword, a vendor extension in no finding, a union of validation logic at the -// entry, and the rest in one finding at the entry (recordEntryUnhomed). -func recordOwnKeywords(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, keptEntryValue keptEntry, shape string, warn bool, +// addOwnKeywordPendingKeeps adds a pending keep of each keyword of +// keptEntryValue.own, written at site, under its own key and the reason its +// slot gives, reported as the same keyword written beside the allOf is. +func addOwnKeywordPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, site annotation.ConjunctSite, + keptEntryValue keptEntry, shape string, warn bool, ) []ir.Diagnostic { - bs, at := keptEntryValue.entry.schema.Schema, keptEntryValue.entry.pointer - var diags []ir.Diagnostic - var unknown, unhomed, text []string + entrySchema, at := keptEntryValue.entry.schema.Schema, keptEntryValue.entry.pointer + var kept ir.Unmodeled + var reports annotation.KeptReports + var unknown, unhomed, text, logic []string + dialect := dialectIn(loweringContext.Rules().At(loweringContext.Position(at)), entrySchema) + logical := validationOnlyKeys(loweringContext, entrySchema, at, dialect) for _, key := range keptEntryValue.own { - switch twin := TwinKeyword(loweringContext, bs, key); { - case keptEntryValue.numberText && slices.Contains(valueConstraintKeywords, key): + ownKey := annotation.EntryKey("", key) + switch canonicalKeyword := TwinKeyword(loweringContext, entrySchema, key); { + case keptEntryValue.text.has(key): text = append(text, key) - case annotation.DialectKeyword(twin): - // Ahead of the unknown keywords, as Read keeps $vocabulary before - // PreserveUnknownKeywords meets it. - dialect := dialectIn(loweringContext.Rules().At(loweringContext.Position(at)), bs) - diags = append(diags, annotation.KeepDialectKeyword(unmodeled, bs, key, at, loweringContext.Place(), dialect)...) + case annotation.DialectKeyword(canonicalKeyword): + reports = append(reports, annotation.ReportsOf(ownKey, annotation.KeepDialectKeyword(&kept, entrySchema, key, at, loweringContext.Place(), dialect)...)...) case strings.HasPrefix(key, "x-"): - _, keptDiags := preserveSchemaKeyword(loweringContext, unmodeled, bs, key, ir.ReasonVendorExtension, at) - diags = append(diags, keptDiags...) - case writesUnknown(loweringContext, bs, key, at): + _, keptDiags := keepSchemaKeyword(loweringContext, &kept, entrySchema, key, ir.ReasonVendorExtension, at) + reports = append(reports, annotation.ReportsOf(ownKey, keptDiags...)...) + case logical[key]: + logic = append(logic, key) + case keptEntryValue.carried[key] != nil: + reports = append(reports, annotation.ReportsOf(ownKey, keptEntryValue.carried[key](&kept, entrySchema, at)...)...) + case slices.Contains(useBoundKeywords, key): + reports = append(reports, annotation.ReportsOf(ownKey, recordUseBoundKeyword(loweringContext, &kept, entrySchema, key, at)...)...) + case keptEntryValue.setsApart && (key == "enum" || key == "const"): + _, keptDiags := keepSchemaKeyword(loweringContext, &kept, entrySchema, key, ir.ReasonDegradedLowering, at) + reports = append(reports, annotation.ReportsOf(ownKey, keptDiags...)...) + case writesUnknown(loweringContext, entrySchema, key, at): unknown = append(unknown, key) - case slices.Contains(contentKeywords, key): - diags = append(diags, keepContentKeyword(loweringContext, unmodeled, bs, key, at, noEncodingField)...) - case slices.Contains(keptEntryValue.validation, key): - diags = append(diags, preserveValidationOnlyKeyword(loweringContext, unmodeled, bs, key, at)...) - case key == "$dynamicRef" || key == "$recursiveRef": - diags = append(diags, keepEntryDynamicRef(loweringContext, unmodeled, bs, key, at)...) default: - unhomed = append(unhomed, key) + unhomed = append(unhomed, keptEntryValue.addPendingKeepElsewhere(loweringContext, &kept, &reports, key)...) + } + } + reports = append(reports, keepUnknownOf(loweringContext, &kept, entrySchema, unknown, at)...) + reports = append(reports, keepValidationOnly(loweringContext, &kept, entrySchema, logic, at, dialect)...) + diags := addPendingKeepsKeptAs(loweringContext, pendingKeeps, site, kept, reports, annotation.KeptByReader, entrySchema, true) + addPendingKeeping(loweringContext, pendingKeeps, site, entrySchema, keeping{keys: text, reason: ir.ReasonNoIRHome, + keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return keepTextBounds(loweringContext, unmodeled, entrySchema, keys, at, keptEntryValue.root) + }}) + where := namesOf(keptEntryValue.entry).where + unhomedKeeping := keeping{keys: unhomed, reason: ir.ReasonDegradedLowering, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return recordEntryUnhomed(loweringContext, unmodeled, keptEntryValue.entry, keys, shape, where, warn) + }} + if !warn { + unhomedKeeping.keepAtPosition = func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return recordEntryUnhomed(loweringContext, unmodeled, keptEntryValue.entry, keys, shape, "", false) + } + } + addPendingKeeping(loweringContext, pendingKeeps, site, entrySchema, unhomedKeeping) + return diags +} + +// addPendingKeepElsewhere keeps on kept key, a keyword k keeps, where a keeper +// of its own keeps it, appending its reports, paired with key, to reports, and +// returns key where none does, for the report of what has no home. An enum a +// const chosen elsewhere passes over is reported at that position, paired with +// no key. +func (k keptEntry) addPendingKeepElsewhere(loweringContext lowering.Ctx, kept *ir.Unmodeled, reports *annotation.KeptReports, key string) []string { + entrySchema, at, ownKey := k.entry.schema.Schema, k.entry.pointer, annotation.EntryKey("", key) + switch { + case key == "enum" && passesOverEnum(entrySchema): + *reports = append(*reports, annotation.ReportsOf(ownKey, + recordSkippedFamilies(loweringContext, nil, kept, entrySchema, dispatch{lowered: "const", skipped: []string{"enum"}}, at).Diagnostics()...)...) + case key == "enum" && k.passedOverAt != "": + passedOver := recordSkippedFamilies(loweringContext, nil, kept, entrySchema, dispatch{lowered: "const", skipped: []string{"enum"}}, at).Diagnostics() + for i := range passedOver { + if passedOver[i].Provenance.Pointer == at { + passedOver[i].Provenance = loweringContext.Place().At(k.passedOverAt) + } + } + *reports = append(*reports, annotation.ReportsOf("", passedOver...)...) + case slices.Contains(contentKeywords, key) && !k.contentKeptBeside: + *reports = append(*reports, annotation.ReportsOf(ownKey, keepContentKeyword(loweringContext, kept, entrySchema, key, at, noEncodingField)...)...) + case slices.Contains(k.validation, key): + *reports = append(*reports, annotation.ReportsOf(ownKey, keepValidationOnlyKeyword(loweringContext, kept, entrySchema, key, at)...)...) + case isUnionKeyword(key) && k.unionWhy != "": + *reports = append(*reports, annotation.ReportsOf(ownKey, keepEntryUnion(loweringContext, kept, entrySchema, key, at, k.unionWhy)...)...) + case key == "$dynamicRef" || key == "$recursiveRef": + *reports = append(*reports, annotation.ReportsOf(ownKey, keepEntryDynamicRef(loweringContext, kept, entrySchema, key, at)...)...) + default: + return []string{key} + } + return nil +} + +// validationOnlyKeys returns the keywords the validation-only reader keeps of +// entrySchema, written at pointer in dialect, as written beside an allOf. +func validationOnlyKeys(loweringContext lowering.Ctx, entrySchema *statement.Schema, pointer jsontext.Pointer, dialect annotation.Dialect) map[string]bool { + written := make([]string, 0, len(entrySchema.Keys)) + for _, key := range entrySchema.Keys { + written = append(written, key.Name) + } + kept, _, _ := annotation.ValidationOnlyOf(entrySchema, written, pointer, loweringContext.Place(), dialect) + out := map[string]bool{} + for key := range kept { + for _, keyword := range annotation.ValidationOnlyKeywordsOf(key) { + out[keyword] = true } } - diags = append(diags, keepUnknownOf(loweringContext, unmodeled, bs, unknown, at)...) - diags = append(diags, keepTextBounds(loweringContext, unmodeled, bs, text, at)...) - return append(diags, recordEntryUnhomed(loweringContext, ts, unmodeled, keptEntryValue.entry, unhomed, shape, namesOf(keptEntryValue.entry).where, warn)...) + return out +} + +// keepValidationOnly keeps on kept the validation logic of logic, keywords +// entrySchema writes at pointer in dialect, as the validation-only reader keeps +// it beside an allOf, recording what no JSON holds as a discarded site, and +// keeps whole each discriminator within what it keeps. +func keepValidationOnly(loweringContext lowering.Ctx, kept *ir.Unmodeled, entrySchema *statement.Schema, logic []string, pointer jsontext.Pointer, + dialect annotation.Dialect, +) annotation.KeptReports { + if len(logic) == 0 { + return nil + } + logical, unpreserved, reports := annotation.ValidationOnlyOf(entrySchema, logic, pointer, loweringContext.Place(), dialect) + recordDiscardedSites(loweringContext, unpreserved) + *kept = annotation.MergeUnmodeled(*kept, logical) + return append(reports, keepValidationOnlyDiscriminators(loweringContext, logical)...) } // besideRef reports whether allOfEntryValue is what an allOf entry writing a @@ -684,69 +546,82 @@ func besideRef(allOfEntryValue allOfEntry) bool { // where a keyword it keeps is written (where). type entryNames struct{ lead, this, kept, where string } -// namesOf returns how a report names e: as an inline entry, or as the -// conjunct written beside its $ref where it is one (besideRef), a keyword of -// an entry whose own $ref names nothing being written beside that $ref. +// namesOf returns how a report names allOfEntryValue: as an inline entry, or as +// the conjunct written beside its $ref where it is one (besideRef), which holds +// every keyword an entry writes beside a $ref, one naming nothing included. func namesOf(allOfEntryValue allOfEntry) entryNames { - entryNamesValue := entryNames{lead: "inline allOf entry", this: "this inline entry", kept: "the entry", where: "on this inline entry"} if besideRef(allOfEntryValue) { - entryNamesValue = entryNames{lead: "conjunct beside this allOf entry's $ref", this: "the conjunct beside this $ref", + return entryNames{lead: "conjunct beside this allOf entry's $ref", this: "the conjunct beside this $ref", kept: "the conjunct", where: "beside this $ref"} } - if allOfEntryValue.schema.Ref != nil { - entryNamesValue.where = "beside this $ref, which names nothing" + return entryNames{lead: "inline allOf entry", this: "this inline entry", kept: "the entry", where: "on this inline entry"} +} + +// keepEntryUnion keeps the union keyword an inline entry entrySchema at pointer +// writes verbatim on unmodeled, as degraded_lowering, and reports it as the +// same union written beside the allOf is reported, why saying why it is no +// variant's. +func keepEntryUnion(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, entrySchema *statement.Schema, keyword string, pointer jsontext.Pointer, why string) []ir.Diagnostic { + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, entrySchema, keyword, ir.ReasonDegradedLowering, pointer) + if !kept || why == unionKeptInReport { + return diags } - return entryNamesValue + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + "%s%s; union branches kept verbatim under Unmodeled", coDeclaredUnionWhyPrefix, why)) } -// keepEntryDynamicRef keeps the dynamic reference keyword the inline entry bs -// at pointer writes verbatim on unmodeled, as degraded_lowering, and reports it -// at the keyword, as recordUnexpandedDynamicRef reports one beside the allOf: -// no entry expands one, as it is a conjunct the IR cannot intersect with the -// rest. -func keepEntryDynamicRef(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, bs *statement.Schema, keyword string, pointer jsontext.Pointer) []ir.Diagnostic { - kept, diags := preserveSchemaKeyword(loweringContext, unmodeled, bs, keyword, ir.ReasonDegradedLowering, pointer) +// keepEntryDynamicRef keeps the dynamic reference keyword the inline entry +// entrySchema at pointer writes verbatim on unmodeled, as degraded_lowering, +// and reports it at the keyword, as recordUnexpandedDynamicRef reports one +// beside the allOf: no entry expands one, as it is a conjunct the IR cannot +// intersect with the rest. +func keepEntryDynamicRef(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, entrySchema *statement.Schema, keyword string, pointer jsontext.Pointer) []ir.Diagnostic { + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, entrySchema, keyword, ir.ReasonDegradedLowering, pointer) if !kept { return diags } return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer+ids.Ptr(keyword), - "%s was not expanded because it is written on an allOf entry beside another conjunct, which the IR "+ - "cannot intersect with it; it is kept verbatim under Unmodeled", keyword)) + "%s, read as an entry of this allOf, was not expanded because it is written beside another conjunct, which "+ + "the IR cannot intersect with it; it is kept verbatim under Unmodeled", keyword)) } -// keepUnknownOf keeps the keywords of keys, each one bs, the schema at pointer, -// writes that PreserveUnknownKeywords keeps (writesUnknown), as it keeps them, -// and none of the others bs writes. -func keepUnknownOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, bs *statement.Schema, keys []string, pointer jsontext.Pointer) []ir.Diagnostic { +// keepUnknownOf keeps the keywords of keys, each one entrySchema, the schema at +// pointer, writes that KeepUnknownKeywords keeps (writesUnknown), as it +// keeps them, and none of the others entrySchema writes. +func keepUnknownOf(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, entrySchema *statement.Schema, keys []string, pointer jsontext.Pointer) annotation.KeptReports { if len(keys) == 0 { return nil } var others []string - for _, key := range bs.Keys { + for _, key := range entrySchema.Keys { if !slices.Contains(keys, key.Name) { others = append(others, key.Name) } } - undefined := slices.DeleteFunc(undefinedKeywords(loweringContext, bs), func(key string) bool { return !slices.Contains(keys, key) }) - unpreserved, diags := annotation.UnknownKeywordsIn(unmodeled, bs, pointer, loweringContext.Place(), others...) + undefined := slices.DeleteFunc(undefinedKeywords(loweringContext, entrySchema), func(key string) bool { return !slices.Contains(keys, key) }) + unpreserved, reports := annotation.UnknownKeywordsIn(unmodeled, entrySchema, pointer, loweringContext.Place(), others...) recordDiscardedSites(loweringContext, unpreserved) - return append(diags, annotation.UndefinedKeywordsIn(unmodeled, bs, undefined, pointer, loweringContext.Place())...) + return append(reports, annotation.UndefinedKeywordsIn(unmodeled, entrySchema, undefined, pointer, loweringContext.Place())...) } -// recordEntryUnhomed keeps each of unhomed, keywords the entry e writes that -// no home the position lowered to, shape, holds, as degraded_lowering -// (keepUnreadKeys), and reports them in one finding at the entry, where says how -// they are written: a warning where warn says e declares a type no object is, -// which the composed model asserts it is. -func recordEntryUnhomed(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, allOfEntryValue allOfEntry, unhomed []string, +// recordEntryUnhomed keeps each of unhomed, keywords allOfEntryValue writes +// that no home the position lowered to, shape, holds, as degraded_lowering, and +// reports them in one finding at the entry, where saying how they are written: +// a warning where warn says the entry declares a type no object is, which the +// composed model asserts it is. A where of "" words them as written beside the +// allOf, for keywords several entries keep alike. +func recordEntryUnhomed(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, allOfEntryValue allOfEntry, unhomed []string, shape, where string, warn bool, ) []ir.Diagnostic { - kept, diags := keepUnreadKeys(loweringContext, ts, unmodeled, allOfEntryValue.schema.Schema, unhomed, allOfEntryValue.pointer) + kept, diags := keepUnreadKeys(loweringContext, unmodeled, allOfEntryValue.schema.Schema, unhomed, allOfEntryValue.pointer) if len(kept) == 0 { return diags } + if where == "" { + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, allOfEntryValue.pointer, unreadReport, shape, strings.Join(kept, ", "))) + } if warn { - return append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, allOfEntryValue.pointer, + return append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, allOfEntryValue.pointer, "%s declares a type that is not an object, which the composed model asserts it is; "+ "%s, written on it, kept verbatim under Unmodeled", namesOf(allOfEntryValue).lead, strings.Join(kept, ", "))) } @@ -764,12 +639,12 @@ func wholeWhy(keptEntryValue keptEntry) string { case keptWholeBecauseReadAgainstAnotherBase: return "this " + names.lead + " reads its $refs against another base than the position does, as an " + "identifier at or above it names another URI, so nothing it writes folds or is kept apart; " + names.kept + - " (" + strings.Join(keptEntryValue.residue, ", ") + ") is kept verbatim under Unmodeled" + " (" + strings.Join(keptEntryValue.unreadKeywords, ", ") + ") is kept verbatim under Unmodeled" case keptWholeBecauseConjunctsDisagree: - return disagreedWhy(keptEntryValue.residue, names) + return disagreedWhy(keptEntryValue.unreadKeywords, names, keptEntryValue.folded) case keptWholeBecauseKeywordCannotShareEntry: return "another conjunct of this allOf writes a keyword " + names.this + " keeps otherwise, and one Unmodeled entry " + - "under that keyword holds one value; " + names.kept + " (" + strings.Join(keptEntryValue.residue, ", ") + + "under that keyword holds one value; " + names.kept + " (" + strings.Join(keptEntryValue.unreadKeywords, ", ") + ") is kept verbatim under Unmodeled" default: return "" @@ -786,23 +661,23 @@ func wholeCode(keptEntryValue keptEntry) string { return diag.DegradedConstruct } -// keepFailedRefs keeps beside the composed model m what the $ref entries of -// comp at the indices failed, each reference of which names nothing, write -// beside the reference: each keyword as an inline entry's is kept +// keepFailedRefs adds to pendingKeeps, the composed model's, what the $ref +// entries of comp at the indices failed, each reference of which names nothing, +// write beside the reference: each keyword as an inline entry's is kept // (entryKeeps), or the entry whole where one is. It returns the entries kept // apart, whose references keepUncomposedRefs keeps. The failure itself is // reported where the reference is written (fillRefEntry), so nothing here // reports it again. -func keepFailedRefs(loweringContext lowering.Ctx, ts *compile.Types, model *ir.Model, comp allOfComposition, failed []int, -) ([]wholeRefEntry, []ir.Diagnostic) { +func keepFailedRefs(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, comp allOfComposition, failed []int, +) ([]keptRefEntry, []ir.Diagnostic) { diags := make([]ir.Diagnostic, 0, len(failed)) - var apart []wholeRefEntry + var apart []keptRefEntry for _, i := range failed { keptEntryValue := comp.kept[i] if !keptEntryValue.keptWhole() { - apart = append(apart, wholeRefEntry{entry: keptEntryValue.entry}) + apart = append(apart, keptRefEntry{entry: keptEntryValue.entry}) } - diags = append(diags, recordKeptEntry(loweringContext, ts, &model.Unmodeled, comp, keptEntryValue, nodeShape(ir.KindModel), false, + diags = append(diags, addKeptEntryPendingKeeps(loweringContext, pendingKeeps, comp, keptEntryValue, annotation.WritesBeside, nodeShape(ir.KindModel), false, func(otherKeptEntry keptEntry) ir.Diagnostic { return loweringContext.DiagAt(ir.SeverityInfo, wholeCode(otherKeptEntry), otherKeptEntry.entry.pointer, "%s", failedRefWholeWhy(otherKeptEntry)) })...) @@ -815,5 +690,5 @@ func keepFailedRefs(loweringContext lowering.Ctx, ts *compile.Types, model *ir.M func failedRefWholeWhy(keptEntryValue keptEntry) string { return "this allOf entry's $ref names nothing, so nothing reads what it writes, and a keyword that reads the " + "others beside it, or that another conjunct writes otherwise, cannot be kept apart; the entry (" + - strings.Join(keptEntryValue.residue, ", ") + ") is kept verbatim under Unmodeled" + strings.Join(keptEntryValue.unreadKeywords, ", ") + ") is kept verbatim under Unmodeled" } diff --git a/compilers/openapi/internal/schema/entrykept_cost_internal_test.go b/compilers/openapi/internal/schema/entrykept_cost_internal_test.go index 44d7e68ee..064e0bad2 100644 --- a/compilers/openapi/internal/schema/entrykept_cost_internal_test.go +++ b/compilers/openapi/internal/schema/entrykept_cost_internal_test.go @@ -4,170 +4,35 @@ package schema import ( - "bytes" "fmt" "slices" + "strconv" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/budget" - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" - "github.com/dexpace/morphic/ir" ) // keptShape writes the schema X of a document: `top` beside an allOf of n // entries, entry(i) writing the i-th, so one shape varies how many keywords the // entries keep and whether they write them alike. func keptShape(n int, top string, entry func(i int) string) string { - var b strings.Builder - b.WriteString("openapi: 3.1.0\ninfo: {title: t, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n X:\n") - b.WriteString(" type: object\n" + top + " allOf:\n") + var builder strings.Builder + builder.WriteString("openapi: 3.1.0\ninfo: {title: t, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n X:\n") + builder.WriteString(" type: object\n" + top + " allOf:\n") for i := range n { - b.WriteString(" - " + entry(i) + "\n") - } - return b.String() -} - -// keptOfShape returns what writtenApartKeys reads for the schema X of src: the -// composition's entries and what each keeps. -func keptOfShape(t *testing.T, src string) (lowering.Ctx, *statement.Schema, allOfComposition, [][]string) { - t.Helper() - lowerer, _ := LoweredFor(t, src) - for name, st := range lowerer.Schemas() { - if name != "X" { - continue - } - comp := allOfEntries(lowerer.Ctx, st.Schema, "/components/schemas/X") - kepts := make([][]string, len(comp.entries)) - for i, entry := range comp.entries { - kepts[i] = keptOf(lowerer.Ctx, keptEntry{entry: entry, residue: compositionResidue(lowerer.Ctx, comp, i)}) - } - return lowerer.Ctx, st.Schema, comp, kepts - } - require.Fail(t, "the document declares no schema X") - return lowering.Ctx{}, nil, allOfComposition{}, nil -} - -// keyShapes are the spellings an allOf of n entries keeps keywords in: each -// written by one entry (as many keys as entries), by all of them alike, by all -// of them otherwise, and beside a $ref naming nothing, which asks the entries -// keeping a key apart from the rest of its writers. -var keyShapes = []struct { - name string - top string - of func(i int) string -}{ - {"each key written once", "", func(i int) string { - return fmt.Sprintf("{k%da: 1, k%db: 2, k%dc: 3, k%dd: 4, k%de: 5}", i, i, i, i, i) - }}, - {"each key written alike", "", func(int) string { return "{ka: 1, kb: 2, kc: 3, kd: 4, ke: 5}" }}, - {"each key written otherwise", "", func(i int) string { - return fmt.Sprintf("{ka: %d, kb: %d, kc: %d, kd: %d, ke: %d}", i, i, i, i, i) - }}, - {"keys beside a $ref naming nothing", " k0a: 1\n", func(i int) string { - return fmt.Sprintf("{$ref: '#/components/schemas/None', k%da: 1, k%db: 2, k0a: 1}", i, i) - }}, -} - -// TestEntryKeeps_ReadsEachWrittenKeyOnce pins that keeping an allOf's keywords -// apart costs what the entries write once, not once for each kept keyword -// across every entry: from 2n entries to 4n the reads grow at most 2.5 times -// what they grow from n to 2n, whichever way the entries spell the keywords. -func TestEntryKeeps_ReadsEachWrittenKeyOnce(t *testing.T) { - t.Parallel() - for _, shape := range keyShapes { - t.Run(shape.name, func(t *testing.T) { - t.Parallel() - var spent [3]int - for i, n := range []int{100, 200, 400} { - loweringContext, schema, comp, kepts := keptOfShape(t, keptShape(n, shape.top, shape.of)) - var reads budget.Budget - writtenApartKeys(loweringContext, schema, comp, kepts, &reads) - spent[i] = reads.Spent() - } - assert.Positive(t, spent[0], "nothing was read: the shape reaches no key") - assert.LessOrEqual(t, float64(spent[2]-spent[1]), 2.5*float64(spent[1]-spent[0]), - "reads at 100, 200 and 400 entries: %v", spent) - }) - } -} - -// writtenApartOf is the definition writtenApartKeys answers for one key, read -// the plain way: the writers of key in order, one walk of the composition each. -func writtenApartOf(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, key string, kepts [][]string) bool { - var raws []ir.RawValue - if hasKey(schema, key) { - raw, err := annotation.RawFromNode(keyNode(schema, key)) - if err != nil { - return true - } - raws = append(raws, raw) - } - for i, entry := range comp.entries { - if (entry.schema.Ref != nil && !failedRef(loweringContext, entry)) || !stated(entry.schema.Schema) || !hasKey(entry.schema.Schema, key) || - (kepts != nil && !slices.Contains(kepts[i], key)) { - continue - } - raw, err := annotation.RawFromNode(keyNode(entry.schema.Schema, key)) - if err != nil { - return true - } - raws = append(raws, raw) - } - return slices.ContainsFunc(raws, func(raw ir.RawValue) bool { return !bytes.Equal(raws[0], raw) }) -} - -// TestWrittenApartKeys_AnswersWhatTheirWritersWrite pins writtenApartKeys to -// the plain reading of its definition, writtenApartOf, for every kept key of -// shapes that vary who writes it, with what, and who keeps it: alike and -// otherwise, by the allOf's own schema, by an entry that writes it null, by one -// whose value cannot be rendered, and beside a $ref naming nothing. -func TestWrittenApartKeys_AnswersWhatTheirWritersWrite(t *testing.T) { - t.Parallel() - for name, entries := range map[string][]string{ - "alike": {"{ka: 1}", "{ka: 1}", "{kb: 2}"}, - "otherwise": {"{ka: 1}", "{ka: 2}", "{kb: 2}"}, - "one writer": {"{ka: 1}", "{kb: 2}"}, - "null and a value": {"{ka: null}", "{ka: 1}"}, - "an unrendered key": {"{ka: !!int abc}", "{kb: 1}"}, - "two unrendered": {"{ka: !!int abc}", "{ka: !!int abc}"}, - "a $ref's keys": {"{$ref: '#/components/schemas/None', ka: 1}", "{ka: 1}", "{$ref: '#/components/schemas/None', ka: 2}"}, - "a $ref's lone key": {"{$ref: '#/components/schemas/None', ka: 1}", "{ka: 2}"}, - "a keyword merged in place": {"{$ref: '#/components/schemas/None', properties: {a: {}}}", "{properties: {b: {}}}"}, - "a $ref's own value": {"{$ref: '#/components/schemas/None', ka: 1}", "{$ref: '#/components/schemas/None', ka: 1}"}, - } { - for _, top := range []string{"", " ka: 1\n", " ka: 3\n"} { - t.Run(fmt.Sprintf("%s beside %q", name, top), func(t *testing.T) { - t.Parallel() - loweringContext, schema, comp, kepts := keptOfShape(t, keptShape(len(entries), top, func(i int) string { return entries[i] })) - var reads budget.Budget - writers, keepers := writtenApartKeys(loweringContext, schema, comp, kepts, &reads) - wantKeepers := map[string]bool{} - wantWriters := map[string]bool{} - for i, kept := range kepts { - for _, key := range kept { - wantWriters[key] = writtenApartOf(loweringContext, schema, comp, key, nil) - if failedRef(loweringContext, comp.entries[i]) { - wantKeepers[key] = writtenApartOf(loweringContext, schema, comp, key, kepts) - } - } - } - assert.Equal(t, wantWriters, writers, "the writers of each kept key") - assert.Equal(t, wantKeepers, keepers, "the writers among the entries keeping it") - }) - } + builder.WriteString(" - " + entry(i) + "\n") } + return builder.String() } // TestEntryKeeps_KeepsTheSameKeysInEitherOrder pins that what an allOf's -// entries keep, and the order it is reported in, do not depend on the order -// the entries are written in: the keys kept apart are the same, and so are the -// entries kept whole, with the keywords they hold. +// entries keep does not depend on the order the entries are written in: the +// keys kept apart are the same, and so are the entries kept whole, with the +// keywords they hold. A $ref entry naming nothing conjoins as two conjuncts, +// its reference and what it writes beside it, so each kept conjunct is read +// by the entry it was written in. func TestEntryKeeps_KeepsTheSameKeysInEitherOrder(t *testing.T) { t.Parallel() entries := []string{ @@ -177,15 +42,19 @@ func TestEntryKeeps_KeepsTheSameKeysInEitherOrder(t *testing.T) { kept := func(order []string) map[string][]string { t.Helper() lowerer, _ := LoweredFor(t, keptShape(len(order), " kz: 9\n", func(i int) string { return order[i] })) - for name, st := range lowerer.Schemas() { + for name, schemaStatement := range lowerer.Schemas() { if name != "X" { continue } - comp := readAllOf(lowerer.Ctx, st.Schema, "/components/schemas/X") + comp := readAllOf(lowerer.Ctx, schemaStatement.Schema, "/components/schemas/X") out := map[string][]string{} - for i, keptEntry := range comp.kept { - entry := strings.TrimSpace(order[i]) - out[entry] = append(slices.Clone(keptEntry.own), fmt.Sprint(keptEntry.whole, keptEntry.reason)) + for _, keptEntry := range comp.kept { + written, cut := strings.CutPrefix(string(keptEntry.entry.pointer), "/components/schemas/X/allOf/") + index, err := strconv.Atoi(strings.SplitN(written, "/", 2)[0]) + require.True(t, cut && err == nil && index < len(order), "%s is an entry written", keptEntry.entry.pointer) + entry := strings.TrimSpace(order[index]) + out[entry] = append(out[entry], fmt.Sprint(keptEntry.own, keptEntry.whole, keptEntry.reason)) + slices.Sort(out[entry]) } return out } diff --git a/compilers/openapi/internal/schema/entrykept_internal_test.go b/compilers/openapi/internal/schema/entrykept_internal_test.go index 35f0a72a4..4fafd9e2c 100644 --- a/compilers/openapi/internal/schema/entrykept_internal_test.go +++ b/compilers/openapi/internal/schema/entrykept_internal_test.go @@ -9,28 +9,10 @@ import ( "github.com/speakeasy-api/openapi/jsonschema/oas3" soa "github.com/speakeasy-api/openapi/openapi" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/dexpace/morphic/ir" ) -// TestMergeKept_AKeyHeldWithAnotherValueIsAnInvariantBroken pins what no source -// reaches: entryKeeps keeps an entry whole where another conjunct writes one of -// its keywords otherwise, so a key held with another value is reported broken -// and the entry held keeps its value, and a key nothing holds is written. -func TestMergeKept_AKeyHeldWithAnotherValueIsAnInvariantBroken(t *testing.T) { - t.Parallel() - lowerer := NewRawLowerer(&soa.OpenAPI{}) - held := ir.Unmodeled{"openapi:format": {Value: ir.RawValue(`"a"`)}} - unmodeled := ir.Unmodeled{"openapi:format": {Value: ir.RawValue(`"b"`)}} - assertInternalInvariant(t, mergeKept(lowerer.Ctx, &unmodeled, held, "/p/allOf/1")) - assert.Equal(t, ir.RawValue(`"b"`), unmodeled["openapi:format"].Value, "what is held stands") - - var empty ir.Unmodeled - require.Empty(t, mergeKept(lowerer.Ctx, &empty, held, "/p/allOf/1")) - assert.Equal(t, held, empty) -} - // TestKeepEntryDynamicRef_AnEntryWritingNoneKeepsNothing pins that a dynamic // reference an entry does not write is kept and reported nowhere. func TestKeepEntryDynamicRef_AnEntryWritingNoneKeepsNothing(t *testing.T) { @@ -40,23 +22,3 @@ func TestKeepEntryDynamicRef_AnEntryWritingNoneKeepsNothing(t *testing.T) { assert.Empty(t, keepEntryDynamicRef(lowerer.Ctx, &unmodeled, StandaloneSchema(&oas3.Schema{}), "$dynamicRef", "/p/allOf/1")) assert.Empty(t, unmodeled) } - -// TestWritesTopLevelRef_TellsAKeptRefFromAnInlineEntry pins the reading that -// keeps dropFoldedIntoWhole from asking a kept $ref what it holds: a $ref at -// the top of an object only, and nothing of a value no object is or that does -// not decode. -func TestWritesTopLevelRef_TellsAKeptRefFromAnInlineEntry(t *testing.T) { - t.Parallel() - for raw, want := range map[string]bool{ - `{"$ref":"#/a"}`: true, - `{"x-a":1,"$ref":"#/a"}`: true, - `{"properties":{"p":{"$ref":"#/a"}}}`: false, - `false`: false, - `{"a"`: false, - `{"a`: false, - `{`: false, - ``: false, - } { - assert.Equal(t, want, writesTopLevelRef(ir.RawValue(raw)), raw) - } -} diff --git a/compilers/openapi/internal/schema/entrykept_once_test.go b/compilers/openapi/internal/schema/entrykept_once_test.go index a5444317e..2f5234964 100644 --- a/compilers/openapi/internal/schema/entrykept_once_test.go +++ b/compilers/openapi/internal/schema/entrykept_once_test.go @@ -28,7 +28,7 @@ type keptOnceCase struct { // the entry kept whole holds its own, and the other entry's is kept at its // keyword, not at the position, in every order of the three entries. A vendor // extension and a validation-only keyword fold; readOnly is kept as each folded -// branch's residue. +// branch's unread keyword. func TestEntryKeptOnce_AKeywordAnEntryKeptWholeSharesIsKeptInsideItAlone(t *testing.T) { t.Parallel() ref := "{$ref: '#/components/schemas/Str'}" @@ -54,7 +54,7 @@ func TestEntryKeptOnce_AKeywordAnEntryKeptWholeSharesIsKeptInsideItAlone(t *test } } -// indexOf returns where item stands in items, as a pointer token. +// indexOf returns where item sits in items, as a pointer token. func indexOf(items []string, item string) string { for i, s := range items { if s == item { @@ -116,7 +116,7 @@ func TestEntryKeptOnce_APromotedKeyStaysBesideTheEntryKeptWhole(t *testing.T) { // keptOnceShapes are the entries the grid test below draws from: two vendor // extensions apart, a closure and an unevaluated keyword that keep their entry -// whole, and a validation-only keyword with a residue keyword. Each key one +// whole, and a validation-only keyword with a use-bound keyword. Each key one // writes is a member of the entry. var keptOnceShapes = []string{ "{x-a: 1}", @@ -133,8 +133,8 @@ var keptOnceKeys = []string{"x-a", "not", "readOnly"} // keptOnceShapes after a $ref to a string and to an object, and holds each // member an entry writes to one record: inside its entry where that is kept // whole, else at its keyword where no other entry kept apart writes it, else -// at the position, but readOnly, a residue keyword, at the nearest writer's -// (recordFoldedEntryResidue). +// at the position, but readOnly, a use-bound keyword, at the nearest conjunct's +// (recordFlattenedEntryKeeps). func TestEntryKeptOnce_EveryKeywordOfAGridIsKeptOnce(t *testing.T) { t.Parallel() var schemas strings.Builder @@ -155,9 +155,9 @@ func TestEntryKeptOnce_EveryKeywordOfAGridIsKeptOnce(t *testing.T) { doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", schemas.String())) openapitest.RequireNoErrorDiags(t, diags) for n, name := range names { - td := typeByName(doc, name) - require.NotNil(t, td, name) - assertKeptOnce(t, name, td.Common().Unmodeled, entries[n]) + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) + assertKeptOnce(t, name, typeDef.Common().Unmodeled, entries[n]) } } diff --git a/compilers/openapi/internal/schema/entrykept_test.go b/compilers/openapi/internal/schema/entrykept_test.go index ef460989e..5be879030 100644 --- a/compilers/openapi/internal/schema/entrykept_test.go +++ b/compilers/openapi/internal/schema/entrykept_test.go @@ -5,9 +5,13 @@ package schema_test import ( "encoding/json/jsontext" + "encoding/json/v2" + "slices" + "strings" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" @@ -17,7 +21,8 @@ import ( // TestEntryKept_ContentTwoEntriesWriteApartIsKeptWholeAsItsReason pins an entry // kept whole for a keyword another entry writes otherwise: each is kept under // its index with the reason its keywords share, content vocabulary's here, and -// reported at itself, in either order of the entries. +// reported at itself as disagreeing, since the vocabulary folds by its +// conjuncts, in either order of the entries. func TestEntryKept_ContentTwoEntriesWriteApartIsKeptWholeAsItsReason(t *testing.T) { t.Parallel() for _, entries := range []string{ @@ -34,7 +39,7 @@ func TestEntryKept_ContentTwoEntriesWriteApartIsKeptWholeAsItsReason(t *testing. } for _, at := range []string{"/components/schemas/S/allOf/1", "/components/schemas/S/allOf/2"} { assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), - "another conjunct of this allOf writes a keyword this inline entry keeps otherwise", entries) + "the conjuncts of this allOf disagree on a keyword this inline entry writes", entries) } } } @@ -79,7 +84,9 @@ func TestEntryKept_WhatARefEntryWritesBesideItsRefIsReportedAsBesideIt(t *testin // TestEntryKept_AnEntryKeptWholeHoldsWhatItFoldsOnce pins an entry kept whole // for a closure it does not type while what else it writes folds: its vendor // extension and its validation-only keyword are kept inside it alone, and its -// description is typed, where the allOf refines and where it composes. +// description is typed, where the allOf refines. Where it composes, the +// closure types the model, kept under its keyword over the member another +// entry brings, the rest of the entry under theirs. func TestEntryKept_AnEntryKeptWholeHoldsWhatItFoldsOnce(t *testing.T) { t.Parallel() const entry = "{additionalProperties: false, x-a: 1, propertyNames: {pattern: '^a'}, description: d}" @@ -87,101 +94,119 @@ func TestEntryKept_AnEntryKeptWholeHoldsWhatItFoldsOnce(t *testing.T) { " S: {allOf: [{$ref: '#/components/schemas/Str'}, "+entry+"]}\n"+ " M: {allOf: [{type: object, properties: {a: {type: string}}}, "+entry+"]}\n")) openapitest.RequireNoErrorDiags(t, diags) - for _, name := range []string{"S", "M"} { - td := typeByName(doc, name) - assert.Equal(t, []string{"openapi:allOf/1"}, unmodeledKeys(td.Common().Unmodeled), name) - assert.Equal(t, "d", td.Common().Docs.Description, name) + for name, keys := range map[string][]string{ + "S": {"openapi:allOf/1"}, + "M": {"openapi:additionalProperties", "openapi:propertyNames", "openapi:x-a"}, + } { + typeDef := typeByName(doc, name) + assert.Equal(t, keys, unmodeledKeys(typeDef.Common().Unmodeled), name) + assert.Equal(t, "d", typeDef.Common().Docs.Description, name) } } // TestEntryKept_AnEntryOfAnUndecidedAllOfIsReportedAgainstTheKeywordsBesideIt -// pins the report of what an entry keeps where no entry is elected: the -// position lowered by the keywords beside the allOf, the top type here, and -// says so, not that it is a use of a conjunct. +// pins the report of what an entry keeps where no entry is chosen: the +// position lowered by the kinds its entries admit together, a string here, +// and says so, not that it is a use of a conjunct. The entry's type naming +// that string the node restates, so that entry keeps and reports nothing. func TestEntryKept_AnEntryOfAnUndecidedAllOfIsReportedAgainstTheKeywordsBesideIt(t *testing.T) { t.Parallel() _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: [{type: string}, {enum: [a, 1]}]}\n")) openapitest.RequireNoErrorDiags(t, diags) - for _, at := range []string{"/components/schemas/S/allOf/0", "/components/schemas/S/allOf/1"} { - message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at) - assert.Contains(t, message, "as no entry of it is the one it lowers from", at) - assert.NotContains(t, message, "a use of one of its allOf conjuncts", at) - } + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S/allOf/1") + assert.Contains(t, message, "as no entry of it is the one it lowers from") + assert.NotContains(t, message, "a use of one of its allOf conjuncts") + assert.Equal(t, []jsontext.Pointer{"/components/schemas/S/allOf/1"}, openapitest.PointersOf(diags, diag.DegradedConstruct)) } -// TestEntryKept_AFailedRefKeepsItsReferenceAndEachKeywordBesideIt pins a $ref -// entry naming nothing: its reference is kept as written under openapi:$ref and -// each keyword beside it under its own key, reported once at the entry beside -// the error the failure draws, and its required list still reads on the model. -func TestEntryKept_AFailedRefKeepsItsReferenceAndEachKeywordBesideIt(t *testing.T) { - t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Obj: {type: object, properties: {b: {type: string}}}\n"+ - " S: {allOf: [{$ref: '#/components/schemas/Ghost', minLength: 2, required: [b], x-a: 1}, {$ref: '#/components/schemas/Obj'}]}\n")) - td := typeByName(doc, "S") - kept := td.Common().Unmodeled - assert.Equal(t, []string{"openapi:$ref", "openapi:minLength", "openapi:x-a"}, unmodeledKeys(kept)) - assert.JSONEq(t, `"#/components/schemas/Ghost"`, string(kept["openapi:$ref"].Value)) - assert.Equal(t, ir.ReasonDegradedLowering, kept["openapi:$ref"].Reason) - assert.Equal(t, ir.ReasonVendorExtension, kept["openapi:x-a"].Reason) - assert.Equal(t, jsontext.Pointer("/components/schemas/S/allOf/0"), kept["openapi:$ref"].Provenance.Pointer) - assert.Equal(t, []string{"b"}, td.(*ir.Model).Requires) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnresolvedRef, ir.SeverityError, "/components/schemas/S/allOf/0"), "Ghost") - message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S/allOf/0") - assert.Contains(t, message, "minLength written beside this $ref, which names nothing") - assert.NotContains(t, message, "x-a") +// ghostLowering is what a component lowers to, with each $ref it keeps taken +// out: its node's kind, members' wire names and bounds, each Unmodeled entry +// by key as JSON, a $ref kept inside an entry's object removed from it, and +// each finding but an unresolved reference's by severity, code and pointer. +type ghostLowering struct { + kind ir.TypeKind + members []string + constraints *ir.Constraints + kept map[string]string + findings []string } -// TestEntryKept_FailedRefsAreKeptByTheirReferenceInEitherOrder pins the keys of -// several $ref entries naming nothing, by reference text and then by the entry -// as written, two written alike being one entry at the position, and one with -// no keyword beside it drawing nothing but the error. -func TestEntryKept_FailedRefsAreKeptByTheirReferenceInEitherOrder(t *testing.T) { - t.Parallel() - for _, entries := range []string{ - "{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/A', minLength: 2}, {$ref: '#/components/schemas/A', minLength: 2}", - "{$ref: '#/components/schemas/A', minLength: 2}, {$ref: '#/components/schemas/A', minLength: 2}, {$ref: '#/components/schemas/B'}", - } { - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+entries+"]}\n")) - kept := typeByName(doc, "S").Common().Unmodeled - assert.Equal(t, []string{"openapi:$ref/0", "openapi:$ref/1", "openapi:minLength"}, unmodeledKeys(kept), entries) - assert.JSONEq(t, `"#/components/schemas/A"`, string(kept["openapi:$ref/0"].Value), entries) - assert.JSONEq(t, `"#/components/schemas/B"`, string(kept["openapi:$ref/1"].Value), entries) - assert.Equal(t, jsontext.Pointer("/components/schemas/S"), kept["openapi:$ref/0"].Provenance.Pointer, entries) - assert.Equal(t, jsontext.Pointer("/components/schemas/S"), kept["openapi:minLength"].Provenance.Pointer, entries) - var errs int - for _, diagnostic := range diags { - if diagnostic.Severity == ir.SeverityError { - errs++ - } +// loweringWithoutRefs reads ghostLowering off doc's component name, and +// counts the $refs it took out. +func loweringWithoutRefs(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, name string) (ghostLowering, int) { + t.Helper() + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) + out, refs := ghostLowering{kind: typeDef.Kind(), kept: map[string]string{}}, 0 + if model, isModel := typeDef.(*ir.Model); isModel { + for _, property := range model.Properties { + out.members = append(out.members, property.WireName) } - assert.Equal(t, 3, errs, "each reference is reported where it is written: %s", entries) } + if scalar, isScalar := typeDef.(*ir.Scalar); isScalar { + out.constraints = scalar.Constraints + } + for key, entry := range typeDef.Common().Unmodeled { + if strings.HasPrefix(key, "openapi:$ref") { + refs++ + continue + } + var members map[string]any + if json.Unmarshal(entry.Value, &members) == nil && members["$ref"] != nil { + delete(members, "$ref") + refs++ + raw, err := json.Marshal(members, json.Deterministic(true)) + require.NoError(t, err) + out.kept[key] = string(raw) + continue + } + out.kept[key] = string(entry.Value) + } + for _, diagnostic := range diags { + if diagnostic.Code != diag.UnresolvedRef { + out.findings = append(out.findings, string(diagnostic.Severity)+" "+diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + } + slices.Sort(out.findings) + return out, refs } -// TestEntryKept_AFailedRefIsKeptWholeWhereItsKeywordsCannotBeKeptApart pins a -// $ref entry naming nothing kept whole, its reference inside it, for a closure -// it does not type and for a keyword another entry or the position writes -// otherwise, and kept apart for a member another entry's merge reads. -func TestEntryKept_AFailedRefIsKeptWholeWhereItsKeywordsCannotBeKeptApart(t *testing.T) { +// TestEntryKept_AFailedRefLowersAsItsEntryWithoutIt pins a $ref entry naming +// nothing, which admits every kind and cuts nothing: the position lowers as +// the same schema with the $ref removed does, keeping each reference once and +// drawing one unresolved-reference error for each, and no other report. Its +// required list still reads on a composed model, and several references are +// kept by their text, in either order of the entries. +func TestEntryKept_AFailedRefLowersAsItsEntryWithoutIt(t *testing.T) { t.Parallel() - const ghost = "$ref: '#/components/schemas/Ghost'" - for name, tc := range map[string]struct { + const ghost = "$ref: '#/components/schemas/Ghost', " + for name, testCase := range map[string]struct { schema string - keys []string - said string + refs int }{ - "closure": {"{allOf: [{" + ghost + ", additionalProperties: false}, {type: object}]}", - []string{"openapi:allOf/0"}, "names nothing, so nothing reads what it writes"}, - "another entry": {"{allOf: [{" + ghost + ", minLength: 2}, {minLength: 3}]}", - []string{"openapi:allOf/0", "openapi:allOf/1"}, "names nothing, so nothing reads what it writes"}, - "the position": {"{minLength: 3, allOf: [{" + ghost + ", minLength: 2}, {type: object}]}", - []string{"openapi:allOf/0", "openapi:minLength"}, "names nothing, so nothing reads what it writes"}, - "a merged member": {"{allOf: [{" + ghost + ", properties: {a: {type: string}}}, {properties: {b: {type: string}}}]}", - []string{"openapi:$ref", "openapi:properties"}, "properties written beside this $ref, which names nothing"}, + "each keyword beside it": {"{allOf: [{" + ghost + "minLength: 2, required: [b], x-a: 1}, {$ref: '#/components/schemas/Obj'}]}", 1}, + "a closure": {"{allOf: [{" + ghost + "additionalProperties: false}, {type: object}]}", 1}, + "another entry": {"{allOf: [{" + ghost + "minLength: 2}, {minLength: 3}]}", 1}, + "the position": {"{minLength: 3, allOf: [{" + ghost + "minLength: 2}, {type: object}]}", 1}, + "a merged member": {"{allOf: [{" + ghost + "properties: {a: {type: string}}}, {properties: {b: {type: string}}}]}", 1}, + "several, A first": {"{allOf: [{$ref: '#/components/schemas/A', minLength: 2}, {$ref: '#/components/schemas/A', minLength: 2}, " + + "{$ref: '#/components/schemas/B'}]}", 2}, + "several, B first": {"{allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/A', minLength: 2}, " + + "{$ref: '#/components/schemas/A', minLength: 2}]}", 2}, } { - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+tc.schema+"\n")) - assert.Equal(t, tc.keys, unmodeledKeys(typeByName(doc, "S").Common().Unmodeled), name) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S/allOf/0"), - tc.said, name) + const obj = " Obj: {type: object, properties: {b: {type: string}}}\n" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", obj+" S: "+testCase.schema+"\n")) + twinSchema := testCase.schema + for _, ref := range []string{ghost, "$ref: '#/components/schemas/A', ", "$ref: '#/components/schemas/A'", "$ref: '#/components/schemas/B'"} { + twinSchema = strings.ReplaceAll(twinSchema, ref, "") + } + equivalent, equivalentDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", obj+" S: "+twinSchema+"\n")) + got, refs := loweringWithoutRefs(t, doc, diags, "S") + want, _ := loweringWithoutRefs(t, equivalent, equivalentDiags, "S") + assert.Equal(t, want, got, "%s lowers as %s", name, twinSchema) + assert.Equal(t, testCase.refs, refs, "%s keeps each reference once", name) + if model, isModel := typeByName(doc, "S").(*ir.Model); isModel && name == "each keyword beside it" { + assert.Equal(t, []string{"b"}, model.Requires, "its required list reads on the model") + } } } diff --git a/compilers/openapi/internal/schema/enum.go b/compilers/openapi/internal/schema/enum.go index e9498a065..adf0d0329 100644 --- a/compilers/openapi/internal/schema/enum.go +++ b/compilers/openapi/internal/schema/enum.go @@ -4,6 +4,7 @@ package schema import ( + "cmp" "encoding/base64" "encoding/json/jsontext" "slices" @@ -13,6 +14,7 @@ import ( yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" @@ -35,65 +37,258 @@ import ( // A `null` entry is neither member nor variant but the reference's Nullable // bit, which schemaAdmitsNull decides at every site (enumEntries), so a list // of null alone is an Enum with no member. -func lowerEnum(loweringContext lowering.Ctx, ts *compile.Types, site valueSetSite) (ir.TypeID, []ir.Diagnostic) { - schema, written := site.set, site.written - members := schema.Enum() +func lowerEnum(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite) (builtPosition, []ir.Diagnostic) { + schema, written := site.schema, site.pointer + if typeExcludesEnumMember(schema) { + return lowerNullTypedEnum(loweringContext, types, site) + } + members := site.enumMembers(loweringContext) var diags []ir.Diagnostic + var pendingKeeps annotation.PendingKeeps + keeps := builtKeeps{pendingKeeps: &pendingKeeps, pointer: written, placement: site.placement} + takes := site.boundTakes(loweringContext) build := func(common ir.TypeCommon) ir.TypeDef { // The degenerate list first, then the budget. They cannot both hold — a // member count of zero exceeds no positive budget — so the order decides // nothing, but reading the empty case beside the members it lacks is // clearer than reading it after a bound on how many there may be. + if _, setsIntersect := site.sharedMembers(loweringContext); setsIntersect && len(members) == 0 { + // The value sets share no member: no value satisfies the position. + enum := &ir.Enum{TypeCommon: common, ValueType: site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny), Closed: true} + diags = append(diags, keepChosenSet(loweringContext, keeps, &enum.Unmodeled, site, "enum")...) + diags = append(diags, refusedSetMemberReports(loweringContext, site)...) + return enum + } if len(members) == 0 { - def, emptyDiags := emptyEnum(loweringContext, site, common) + def, emptyDiags := emptyEnum(loweringContext, site, common, keeps) diags = append(diags, emptyDiags...) return def } if n := len(members); !loweringContext.Limits.MaxEnumMembers.Admits(n) { - diags = append(diags, loweringContext.DiagAt(ir.SeverityError, diag.BudgetExceeded, written, - "enum declares %d members, past the %d-member budget; lowered as any", - n, loweringContext.Limits.MaxEnumMembers.Cap())) + diags = append(diags, enumPastBudget(loweringContext, written, n)) return &ir.Any{TypeCommon: common} } - entries := readEnum(members) - diags = append(diags, enumRepeats(loweringContext, entries, written)...) - kept, keptDiags := enumEntries(loweringContext, schema, entries, written) - diags = append(diags, keptDiags...) - members, memberPrimitive, ok := enumMembers(kept, common.ID) - if !ok { - def, enumDiags := enumAsUnion(loweringContext, ts, site, common, kept) - diags = append(diags, enumDiags...) - return def + entries := site.withUnionNotes(loweringContext, readEnum(members, written)) + diags = append(diags, enumRepeats(loweringContext, schema, entries)...) + node, nodeDiags := enumNode(loweringContext, types, site, common, entries, takes, keeps) + diags = append(diags, nodeDiags...) + enum, isEnum := node.(*ir.Enum) + if union, isUnion := node.(*ir.Union); isUnion { + if _, setsIntersect := site.sharedMembers(loweringContext); setsIntersect { + // The Union of literals holds what the sets share, as an Enum + // would below, so the set is kept. + diags = append(diags, keepChosenSet(loweringContext, keeps, &union.Unmodeled, site, "enum")...) + diags = append(diags, refusedSetMemberReports(loweringContext, site)...) + } + } + if !isEnum { + return node + } + if site.sharesNoMember(loweringContext) { + // The sets the conjuncts state share no member: no value of the + // type satisfies the position (refinement.sharesNoMember). + enum.Members = nil + diags = append(diags, keepChosenSet(loweringContext, keeps, &enum.Unmodeled, site, "enum")...) + } + if _, setsIntersect := site.sharedMembers(loweringContext); setsIntersect { + // The node holds what the sets share, so each set is kept. + diags = append(diags, keepChosenSet(loweringContext, keeps, &enum.Unmodeled, site, "enum")...) + diags = append(diags, refusedSetMemberReports(loweringContext, site)...) } - return &ir.Enum{ - TypeCommon: common, - ValueType: site.enumType(loweringContext, func(primitiveKind ir.PrimitiveKind) bool { return enumMembersAre(members, primitiveKind) }, memberPrimitive), - Members: members, - Closed: true, + enum.Constraints, diags = withValueSetBounds(loweringContext, site, &enum.Unmodeled, boundHomes{value: takes}.heldOver(primitiveRoot(enum.ValueType), takes), diags, keeps) + diags = append(diags, boundsRefuseEveryMember(loweringContext, site, enum)...) + return enum + } + built := internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + typeDef := build(common) + return typeDef, valueSetReads(loweringContext, site.schema, typeDef) | valueSetBoundsRead(site.schema, typeDef, site.homesOf(loweringContext, typeDef)) + }) + built.pendingKeeps.AddAll(pendingKeeps) + return built, diags +} + +// boundsRefuseEveryMember is the one warning the Enum site lowers to draws, at +// the position, where its bounds refuse every member it lists +// (docs/compilers/openapi.md#enum-const). The members and bounds stay as +// written. Bounds admitting no value of a member's kind at all are the cause, +// which pass reports, so they draw nothing here. +func boundsRefuseEveryMember(loweringContext lowering.Ctx, site valueSetSite, enum *ir.Enum) []ir.Diagnostic { + admitted := func(enumMember ir.EnumMember) bool { + return ir.ConstraintsAdmit(enum.Constraints, enumMember.Value) != ir.AdmitsNo + } + boundsAdmitNone := func(enumMember ir.EnumMember) bool { + return ir.ConstraintsAdmitNoValue(enum.Constraints, enumMember.Value.Kind) + } + if len(enum.Members) == 0 || slices.ContainsFunc(enum.Members, admitted) || slices.ContainsFunc(enum.Members, boundsAdmitNone) { + return nil + } + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, site.nodePointer(), + "the enum and the bounds this schema writes share no value, each member lying outside the bounds, so no "+ + "instance satisfies it; it lowered as the enum as written, holding the bounds in its constraints")} +} + +// enumPastBudget is the error a value set written at pointer, listing n +// members, more than the enum budget admits, draws where it lowers as any. +func enumPastBudget(loweringContext lowering.Ctx, pointer jsontext.Pointer, n int) ir.Diagnostic { + return loweringContext.DiagAt(ir.SeverityError, diag.BudgetExceeded, pointer, + "enum declares %d members, past the %d-member budget; lowered as any", n, loweringContext.Limits.MaxEnumMembers.Cap()) +} + +// enumNode builds the node a value set listing entries lowers to at site: the +// closed Enum of the entries enumEntries keeps, whose bounds its caller reads, +// or, where no one Enum holds them, the Union of literals over them holding its +// bounds itself. An enum and a union of value sets beside a body +// (lowerMembersFilteredByRest) both lower through it. +func enumNode(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite, common ir.TypeCommon, entries []enumEntry, takes kindSet, + keeps builtKeeps, +) (ir.TypeDef, []ir.Diagnostic) { + kept, diags := enumEntries(loweringContext, site.schema, entries) + members, memberPrimitive, ok := enumMembers(kept, common.ID) + if !ok { + union, unionDiags := enumAsUnion(loweringContext, types, site, common, kept) + homes := boundHomes{value: takes}.heldOver(valueSetNodeRoot(loweringContext, site, union, kept), takes) + union.Constraints, unionDiags = withValueSetBounds(loweringContext, site, &union.Unmodeled, homes, unionDiags, keeps) + return union, append(diags, unionDiags...) + } + return &ir.Enum{ + TypeCommon: common, + ValueType: site.enumType(loweringContext, func(primitiveKind ir.PrimitiveKind) bool { return enumMembersAre(members, primitiveKind) }, memberPrimitive), + Members: members, + Closed: true, + }, diags +} + +// typeExcludesEnumMember reports whether schema writes a type naming null +// alone beside an enum listing a member that is not null, which the type +// decides over (docs/compilers/openapi.md#null-alone). +func typeExcludesEnumMember(schema *statement.Schema) bool { + return typeOfNullAlone(schema) && slices.ContainsFunc(schema.Enum(), func(node *yaml.Node) bool { return !isNullValue(node) }) +} + +// lowerNullTypedEnum lowers a value set whose type of null alone excludes a +// member of the enum beside it: the type decides, so it is the node of null +// alone, the enum left unread and kept verbatim, each member it excludes +// reported where it is written. +func lowerNullTypedEnum(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite) (builtPosition, []ir.Diagnostic) { + built := internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + enum := &ir.Enum{TypeCommon: common, ValueType: site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny), Closed: true} + return enum, valueSetReads(loweringContext, site.schema, enum)&^keyBit("enum") | keyBit("type") + }) + entries := readEnum(site.schema.Enum(), site.pointer) + return built, slices.Concat(enumRepeats(loweringContext, site.schema, entries), excludedEnumMembers(loweringContext, entries)) +} + +// excludedEnumMembers reports each of entries, an enum written beside a type +// of null alone, that is not null: no value of that type, so no +// instance matches it, the enum being kept verbatim. +func excludedEnumMembers(loweringContext lowering.Ctx, entries []enumEntry) []ir.Diagnostic { + var diags []ir.Diagnostic + for _, enumEntry := range entries { + if enumEntry.isNull() { + continue } + diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, enumEntry.at, + "enum member %s is no value of the declared type null, which JSON Schema conjoins with enum and which decides "+ + "over it, so no instance matches it; the enum is kept verbatim under Unmodeled", describeEntry(enumEntry))) } - id := internNode(loweringContext, ts, site.pointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { - td := build(common) - return td, valueSetReads(site.set, td) - }, site.finish) - return id, diags + return diags } -// enumEntry is one entry of an enum as written: its node, its index in the -// list, and the value it converts to, or why it converts to none. +// describeEntry spells an enum entry for a message: its value, or, for one +// converting to none, its node's text. +func describeEntry(enumEntry enumEntry) string { + if enumEntry.err != nil { + return strconv.Quote(enumEntry.node.Value) + } + return describeValue(enumEntry.val) +} + +// boundTakes returns the kinds whose bounds the node vs's enum lowers to holds: +// those of the values it lists (listedKinds) that its position admits +// (boundKinds). +func (vs valueSetSite) boundTakes(loweringContext lowering.Ctx) kindSet { + return boundKinds(loweringContext, vs.placement.positionOrSchema(vs.schema)) & listedKinds(loweringContext, vs.schema) +} + +// homesOf returns the bounds typeDef, the node vs's enum lowered to, holds: +// none of a kind its root (valueSetNodeRoot) marks, which it keeps, read as the +// frame dispatching to it reads that root (boundsHeldAt), so a flattened +// entry's bound is never both held there and kept on the entry. +func (vs valueSetSite) homesOf(loweringContext lowering.Ctx, typeDef ir.TypeDef) boundHomes { + entries := readEnum(vs.enumMembers(loweringContext), vs.pointer) + takes := vs.boundTakes(loweringContext) + return boundHomes{value: takes}.heldOver(valueSetNodeRoot(loweringContext, vs, typeDef, entries), takes) +} + +// listedKinds returns the kinds of the values the enum schema writes lists, +// null aside, as the run reads them once (memberSetOf), and none where one +// converts to no value, whose node holds no bound of a kind it may not list. +func listedKinds(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { + set := memberSetOf(loweringContext, valueSetOf{schema, "enum"}, schema.Enum()) + if set.unread { + return 0 + } + return set.kinds &^ kindNull +} + +// withValueSetBounds returns the value bounds of the kinds homes.value names +// that the set, the flattened entries beside it and its position's $refs write, +// with diags and its reports appended, keeping where keeps says what no field +// states (docs/compilers/openapi.md#constraints). A bound of another kind stays +// unread, kept as on any node (keepUnread). +func withValueSetBounds(loweringContext lowering.Ctx, site valueSetSite, unmodeled *ir.Unmodeled, homes boundHomes, diags []ir.Diagnostic, + keeps builtKeeps, +) (*ir.Constraints, []ir.Diagnostic) { + flattenedEntries := site.placement.flattenedEntries(loweringContext, site.schema, site.pointer) + reached := referredOf(loweringContext, site.placement.positionOrSchema(site.schema)) + var cons *ir.Constraints + diags = append(diags, keeps.keep(loweringContext, unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + bounds, kept, reports := boundsKept(loweringContext, *unmodeled, site.schema, flattenedEntries, site.pointer, homes.value) + text, textReports := heldTextKept(loweringContext, site.schema, flattenedEntries, site.pointer, homes) + referredText, referredReports := reached.textKept(loweringContext, homes, site.nodePointer()) + *unmodeled = annotation.MergeUnmodeled(annotation.MergeUnmodeled(annotation.MergeUnmodeled(*unmodeled, kept), text), referredText) + cons = merge.Constraints(bounds, reached.constraints(loweringContext, homes.value)) + return slices.Concat(reports, textReports, referredReports) + })...) + return cons, append(diags, reached.walkCutReport(loweringContext, site.nodePointer())...) +} + +// valueSetBoundsRead returns the value bounds set writes that typeDef, an Enum +// or a Union of literals holding what homes says, read, those it keeps as text +// of another kind among them, and none for any other node. +func valueSetBoundsRead(set *statement.Schema, typeDef ir.TypeDef, homes boundHomes) keySet { + held := keySetOf(writtenKept(set, homes.heldText)...) + switch n := typeDef.(type) { + case *ir.Enum: + return nodeBoundsRead(set, homes.value, n.Constraints, n.Unmodeled) | held + case *ir.Union: + return nodeBoundsRead(set, homes.value, n.Constraints, n.Unmodeled) | held + default: + return 0 + } +} + +// enumEntry is one entry of a value set as written: its node, where it is +// written, its index in its list, and the value it converts to, or why it +// converts to none. type enumEntry struct { node *yaml.Node err error val ir.Value + at jsontext.Pointer index int + // notes is what the branch of a union of value sets writing the entry + // alone says of it (filteredMemberNotes), nothing for an enum's entry. + notes memberNotes } -// readEnum converts each entry of an enum once, for every reader of the list. -func readEnum(nodes []*yaml.Node) []enumEntry { +// readEnum converts each entry of the enum written at pointer once, for every +// reader of the list. +func readEnum(nodes []*yaml.Node, pointer jsontext.Pointer) []enumEntry { out := make([]enumEntry, 0, len(nodes)) for i, node := range nodes { val, err := value.FromNode(node) - out = append(out, enumEntry{node: node, err: err, val: val, index: i}) + out = append(out, enumEntry{node: node, err: err, val: val, at: pointer + ids.Ptr("enum", strconv.Itoa(i)), index: i}) } return out } @@ -101,30 +296,33 @@ func readEnum(nodes []*yaml.Node) []enumEntry { // isNull reports whether e converts to the null value. func (e enumEntry) isNull() bool { return e.err == nil && e.val.Kind == ir.ValueNull } -// enumEntries returns the entries of s's enum that a member or a variant holds: -// each but a null, which is the reference's (lowerEnum). Two kinds of entry -// admit no instance, since JSON Schema conjoins enum with the keywords beside -// it, and each is reported at itself as a warning: a null where those keywords -// exclude null, which nothing then holds, and a value no type s declares -// admits, a type of null included, which is kept as written beside the type -// kept verbatim as unread. -func enumEntries(loweringContext lowering.Ctx, schema *statement.Schema, entries []enumEntry, pointer jsontext.Pointer) ([]enumEntry, []ir.Diagnostic) { +// enumEntries returns the entries of schema's enum that a member or a variant +// holds: each but a null, which is the reference's (lowerEnum). Two kinds of +// entry admit no instance, since JSON Schema conjoins enum with the keywords +// beside it, and each is reported at itself as a warning: a null where those +// keywords exclude null, which nothing then holds, and a value no type schema +// declares admits, kept as written beside the type kept verbatim as unread. An +// enum of null alone a conjunct beside it excludes is the conjuncts' report +// instead (nullExcludedOnlyBeside). +func enumEntries(loweringContext lowering.Ctx, schema *statement.Schema, entries []enumEntry) ([]enumEntry, []ir.Diagnostic) { admitsNull := slices.ContainsFunc(entries, enumEntry.isNull) && schemaAdmitsNull(loweringContext, schema) + reported := !admitsNull && (slices.ContainsFunc(entries, func(member enumEntry) bool { return !member.isNull() }) || + !nullExcludedOnlyBeside(loweringContext, schema)) types := schema.Types() kept := make([]enumEntry, 0, len(entries)) var diags []ir.Diagnostic for _, enumEntry := range entries { - at := pointer + ids.Ptr("enum", strconv.Itoa(enumEntry.index)) + at := enumEntry.at switch { case enumEntry.isNull(): - if !admitsNull { - diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, at, + if reported { + diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, at, "enum member null admits no instance: a keyword beside the enum excludes null, and JSON "+ "Schema conjoins the two; the member is dropped, and the reference admits no null")) } continue case enumEntry.err == nil && !typesAdmit(types, enumEntry.val): - diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, at, + diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, at, "enum member %s is no value of the declared type %s, which JSON Schema conjoins with enum, so no "+ "instance matches it; the members are lowered as written", describeValue(enumEntry.val), typeList(types))) } @@ -133,18 +331,14 @@ func enumEntries(loweringContext lowering.Ctx, schema *statement.Schema, entries return kept, diags } -// typesAdmit reports whether irValue is a value of one of types, read by the -// JSON kinds the admission reading gives a type and a value (kindOfType, -// kindOfValue). An empty list declares no type, and a type no schema defines -// judges nothing, which validation reports; either admits irValue. +// typesAdmit reports whether irValue is a value of one of types, by the JSON +// kinds the admission reading gives each (kindsOfTypeNameOrString, +// kindOfValue). A type no schema defines, which validation reports, admits the +// string its scalar lowers over; an empty list admits irValue. func typesAdmit(types []statement.JSONSchemaTypeName, irValue ir.Value) bool { var admitted kindSet for _, jsonSchemaTypeName := range types { - kindSet := kindOfType(jsonSchemaTypeName) - if kindSet == 0 { - return true - } - admitted |= kindSet + admitted |= kindsOfTypeNameOrString(jsonSchemaTypeName) } return len(types) == 0 || kindOfValue(irValue)&admitted != 0 } @@ -193,14 +387,26 @@ func describeValue(irValue ir.Value) string { // ValueType is what the declaration selects, else the top type. Whether a // reference admits null is not settled here: schemaAdmitsNull reads the type // keyword at each use site (GitHub #288). -func emptyEnum(loweringContext lowering.Ctx, site valueSetSite, common ir.TypeCommon) (ir.TypeDef, []ir.Diagnostic) { - diags := []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.EmptyEnum, site.written, - "enum declares no member, so this position accepts no value; lowered as a closed enum with no members")} - return &ir.Enum{ +func emptyEnum(loweringContext lowering.Ctx, site valueSetSite, common ir.TypeCommon, keeps builtKeeps) (ir.TypeDef, []ir.Diagnostic) { + diags := []ir.Diagnostic{emptyEnumFinding(loweringContext, site.pointer)} + enum := &ir.Enum{ TypeCommon: common, ValueType: site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny), Closed: true, - }, diags + } + if site.sharesNoMember(loweringContext) { + // Chosen among sets sharing no member, it is kept as every set is + // (emptySetApart). + diags = append(diags, keepChosenSet(loweringContext, keeps, &enum.Unmodeled, site, "enum")...) + } + return enum, diags +} + +// emptyEnumFinding is the one warning `enum: []`, written at the schema at +// pointer, draws. +func emptyEnumFinding(loweringContext lowering.Ctx, pointer jsontext.Pointer) ir.Diagnostic { + return loweringContext.DiagAt(ir.SeverityWarning, diag.EmptyEnum, pointer, + "enum declares no member, so this position accepts no value; lowered as a closed enum with no members") } // enumMembers converts the entries enumEntries kept into scalar members, @@ -228,11 +434,11 @@ func enumMembers(entries []enumEntry, enum ir.TypeID) ([]ir.EnumMember, ir.Primi return nil, "", false } primitive = memberPrimitive - members = append(members, ir.EnumMember{ + members = append(members, enumEntry.notes.onMember(ir.EnumMember{ ID: id, Name: ir.NamingFor(text), Value: enumEntry.val, - }) + })) } return members, primitive, true } @@ -268,7 +474,7 @@ func enumMemberPrimitive(entries []enumEntry) (ir.PrimitiveKind, bool) { // enumMembersAre asks of the members they lower to. func entriesAre(entries []enumEntry, primitive ir.PrimitiveKind) bool { for _, enumEntry := range entries { - if !merge.Admits(primitive, enumEntry.val) { + if ir.PrimitiveAdmits(primitive, enumEntry.val) != ir.AdmitsYes { return false } } @@ -279,17 +485,20 @@ func entriesAre(entries []enumEntry, primitive ir.PrimitiveKind) bool { // enumEntries kept to a Union of Literals, each hoisted at the pointer its // entry is written at, emitting one info diagnostic. The Union is exclusive where those // entries are distinct: otherwise an instance can match two variants. -func enumAsUnion(loweringContext lowering.Ctx, ts *compile.Types, site valueSetSite, common ir.TypeCommon, entries []enumEntry) (ir.TypeDef, []ir.Diagnostic) { - diags := []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, site.written, - "heterogeneous or non-scalar enum lowered as a union of literals")} +func enumAsUnion(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite, common ir.TypeCommon, entries []enumEntry) (*ir.Union, []ir.Diagnostic) { + why := "heterogeneous or non-scalar enum lowered as a union of literals" + if site.unionMembers { + why = "the values the branches of this schema's union of value sets list are heterogeneous or non-scalar, " + + "so they are lowered as a union of literals" + } + diags := []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, site.pointer, "%s", why)} variants := make([]ir.Variant, 0, len(entries)) for _, enumEntry := range entries { - lptr := site.written + ids.Ptr("enum", strconv.Itoa(enumEntry.index)) - litID, litDiags := hoistLiteral(loweringContext, ts, site.memberSite(lptr), enumEntry.node) + litBuilt, litDiags := memberLiteral(loweringContext, types, site.memberSite(enumEntry.at), enumEntry) diags = append(diags, litDiags...) variants = append(variants, ir.Variant{ - Name: compile.NamingHint(lowering.NameAt(loweringContext, lptr)), - Type: ir.TypeRef{Target: litID}, + Name: compile.NamingHint(lowering.NameAt(loweringContext, enumEntry.at)), + Type: ir.TypeRef{Target: litBuilt.id}, }) } return &ir.Union{ @@ -300,55 +509,152 @@ func enumAsUnion(loweringContext lowering.Ctx, ts *compile.Types, site valueSetS }, diags } +// memberLiteral is the Literal of entry, a member of a value set lowered as a +// Union of literals: hoisted where it is written, but for a member of a union +// of value sets minted in the composed namespace at site's pointer and typed as +// site types it. Every such member converts to a value (branchMembers). +func memberLiteral(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite, entry enumEntry) (builtPosition, []ir.Diagnostic) { + if !site.unionMembers { + return hoistLiteral(loweringContext, types, site, entry.node, entry.notes) + } + id := loweringContext.IDs().ComposedType(site.pointer) + common := entry.notes.onCommon(commonFor(loweringContext, id, site.pointer)) + types.Register(id, &ir.Literal{TypeCommon: common, Value: entry.val, ValueType: site.literalType(loweringContext, entry.val)}) + return builtPosition{id: id}, nil +} + // lowerConst hoists the const site's schema writes as a Literal of its value // (hoistLiteral), but a null, which is no Literal's (nullConst), and reports, // at the const, a value no type that schema declares admits, as enumEntries reports an enum member. The Literal // holds the value as written, and a type it does not fit is kept // verbatim as unread. -func lowerConst(loweringContext lowering.Ctx, ts *compile.Types, site valueSetSite) (ir.TypeID, []ir.Diagnostic) { - constant := site.set.Const() +func lowerConst(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite) (builtPosition, []ir.Diagnostic) { + constant := site.schema.Const() val, err := value.FromNode(constant) if err == nil && val.Kind == ir.ValueNull { - return nullConst(loweringContext, ts, site) + return nullConst(loweringContext, types, site) + } + if err == nil && site.sharesNoMember(loweringContext) { + return emptyConstSet(loweringContext, types, site, site.literalType(loweringContext, val)) + } + if shared, setsIntersect := site.sharedMembers(loweringContext); err == nil && setsIntersect && shared.size() == 0 { + // A union beside the const holds no member of it: of value sets, or of + // typed branches refusing it. + built, diags := emptyConstSet(loweringContext, types, site, site.literalType(loweringContext, val)) + return built, append(diags, refusedSetMemberReports(loweringContext, site)...) } - id, diags := hoistLiteral(loweringContext, ts, site, constant) + if err == nil && constEnumOverlapOf(loweringContext, site.schema) == constBesideEmptyEnum { + // The empty enum is the one fact, its warning the one report, typed as + // a Literal of the const is, the top type where no primitive types it + // (docs/compilers/openapi.md#enum-const). + built, diags := emptyConstSet(loweringContext, types, site, cmp.Or(site.literalType(loweringContext, val), ir.PrimitiveAny)) + return built, append(diags, emptyEnumFinding(loweringContext, site.pointer)) + } + if err == nil && constEnumOverlapOf(loweringContext, site.schema) == constEnumBottom { + return lowerConstEnumBottom(loweringContext, types, site), nil + } + built, diags := hoistLiteral(loweringContext, types, site, constant, memberNotes{}) if err != nil { - return id, diags // hoistLiteral reported it + return built, diags // hoistLiteral reported it } - if types := site.set.Types(); !typesAdmit(types, val) { - diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, site.written+ids.Ptr("const"), + if types := site.schema.Types(); !typesAdmit(types, val) { + diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, site.pointer+ids.Ptr("const"), "const %s is no value of the declared type %s, which JSON Schema conjoins with const, so no instance "+ "matches it; the literal holds the value as written", describeValue(val), typeList(types))) } - return id, diags + return built, diags +} + +// lowerConstEnumBottom lowers a const beside an enum sharing no member with it +// to the closed Model with no member a false schema lowers to, which reads none +// of the schema's keywords, so each is kept under its own key, as the bottom of +// an allOf keeps the keywords beside it (composeBottom). +func lowerConstEnumBottom(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite) builtPosition { + return internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + return &ir.Model{TypeCommon: common, Additional: ir.AdditionalClosed}, 0 + }) +} + +// emptyConstSet lowers a const whose position's sets share no member, whose own +// enum shares none with it, or whose enum is `enum: []`, as an enum there +// lowers: the closed Enum of valueType with no member, keeping the const. +func emptyConstSet(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite, valueType ir.PrimitiveKind) (builtPosition, []ir.Diagnostic) { + var diags []ir.Diagnostic + var pendingKeeps annotation.PendingKeeps + keeps := builtKeeps{pendingKeeps: &pendingKeeps, pointer: site.pointer, placement: site.placement} + built := internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + enum := &ir.Enum{TypeCommon: common, ValueType: valueType, Closed: true} + diags = keepChosenSet(loweringContext, keeps, &enum.Unmodeled, site, "const") + return enum, valueSetReads(loweringContext, site.schema, enum) + }) + built.pendingKeeps.AddAll(pendingKeeps) + return built, diags +} + +// keepChosenSet keeps verbatim the value set site lowers where the node holds +// only some of its members, or none: as degraded_lowering, but validation_only +// where a union of typed branches beside it refuses the rest, as the Enum then +// holds every value an instance is. An entry's set is kept by the principal's +// build, which the settlement places as any conjunct's +// (docs/compilers/openapi.md#allof-refinement). +func keepChosenSet(loweringContext lowering.Ctx, keeps builtKeeps, unmodeled *ir.Unmodeled, site valueSetSite, keyword string) []ir.Diagnostic { + reason := ir.ReasonDegradedLowering + if refused, _ := site.refusedByUnion(loweringContext); len(refused) > 0 { + reason = ir.ReasonValidationOnly + } + return keeps.keep(loweringContext, unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + _, diags := keepSchemaKeyword(loweringContext, unmodeled, site.schema, keyword, reason, site.pointer) + return annotation.ReportsOf(annotation.EntryKey("", keyword), diags...) + }) } // nullConst lowers `const: null` as `enum: [null]` lowers (lowerEnum), to the // node of null alone (lowerNullAlone), so no Literal holds a null // (docs/ir/containers.md#literals). Where a keyword beside the const excludes // null, the position admits nothing, which is reported at the const as -// enumEntries reports such a member. -func nullConst(loweringContext lowering.Ctx, ts *compile.Types, site valueSetSite) (ir.TypeID, []ir.Diagnostic) { - id := lowerNullAlone(loweringContext, ts, site) - if schemaAdmitsNull(loweringContext, site.set) { - return id, nil - } - return id, []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, site.written+ids.Ptr("const"), +// enumEntries reports such a member, and where only a conjunct beside it does, +// by the report of conjuncts sharing no value (nullExcludedOnlyBeside). +func nullConst(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite) (builtPosition, []ir.Diagnostic) { + built := lowerNullAlone(loweringContext, types, site) + if schemaAdmitsNull(loweringContext, site.schema) || nullExcludedOnlyBeside(loweringContext, site.schema) { + return built, nil + } + return built, []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, site.pointer+ids.Ptr("const"), "const null admits no instance: a keyword beside the const excludes null, and JSON Schema "+ "conjoins the two; lowered as an enum with no member, and the reference admits no null")} } +// nullExcludedOnlyBeside reports whether only a conjunct beside schema, a value +// set of null alone, keeps null out, its own keywords admitting it: the +// position's report of conjuncts sharing no value then says so, and the member +// draws none of its own (docs/compilers/openapi.md#enum-const). +func nullExcludedOnlyBeside(loweringContext lowering.Ctx, schema *statement.Schema) bool { + nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(schema)) + return !ownNull(loweringContext, schema, nullSkip{}, nullAnswerMemoOf(loweringContext).settled).forbids(loweringContext) +} + // lowerNullAlone hoists at the site's position the node its schema, whose own // keywords leave it no value but null, lowers to: a closed Enum with no member, // the empty value space, which the nullable reference its position takes widens // by null alone (docs/compilers/openapi.md#null-alone). Its ValueType is what // that schema's type and format select, as an enum's is (enumValueType), the // top type where they select none, narrowed as the site types it. -func lowerNullAlone(loweringContext lowering.Ctx, ts *compile.Types, site valueSetSite) ir.TypeID { - return internNode(loweringContext, ts, site.pointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { - td := &ir.Enum{TypeCommon: common, ValueType: site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny), Closed: true} - return td, valueSetReads(site.set, td) - }, site.finish) +func lowerNullAlone(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite) builtPosition { + return internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + enum := &ir.Enum{TypeCommon: common, ValueType: site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny), Closed: true} + return enum, valueSetReads(loweringContext, site.schema, enum) + }) +} + +// lowerNullIntersection hoists the node an allOf whose conjuncts together admit +// null alone lowers to: the closed Enum with no member `{type: 'null'}` lowers +// to, typed by no conjunct, as no value of their types is left +// (docs/compilers/openapi.md#allof-refinement). +func lowerNullIntersection(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite) builtPosition { + return internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + enum := &ir.Enum{TypeCommon: common, ValueType: ir.PrimitiveAny, Closed: true} + return enum, valueSetReads(loweringContext, site.schema, enum) + }) } // hoistLiteral hoists a single node as a Literal type at the site's position, @@ -359,27 +665,27 @@ func lowerNullAlone(loweringContext lowering.Ctx, ts *compile.Types, site valueS // component's stable named ID) and each individual member of a heterogeneous // enum (enumAsUnion, always an anonymous sub-pointer). // -// It returns the interned ID, plus the diagnostic an unconvertible node +// It returns the built node, plus the diagnostic an unconvertible node // produces — none when the node converts. -func hoistLiteral(loweringContext lowering.Ctx, ts *compile.Types, site valueSetSite, node *yaml.Node) (ir.TypeID, []ir.Diagnostic) { +func hoistLiteral(loweringContext lowering.Ctx, types *compile.Types, site valueSetSite, node *yaml.Node, notes memberNotes) (builtPosition, []ir.Diagnostic) { // Captured from inside the build rather than reported around it, which keeps // the report tied to the node actually being constructed. Reporting eagerly // would be indistinguishable today — a second visit produces the identical // diagnostic, which Diags.Append drops — so nothing observable rests on this; // it is the honest place for it, not a load-bearing one. var diags []ir.Diagnostic - id := internNode(loweringContext, ts, site.pointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + built := internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { val, err := value.FromNode(node) if err != nil { - diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, site.written, + diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DegradedConstruct, site.pointer, "unconvertible value lowered as the top type: %s", err.Error())) top := &ir.Any{TypeCommon: common} - return top, valueSetReads(site.set, top) + return top, valueSetReads(loweringContext, site.schema, top) } - td := &ir.Literal{TypeCommon: common, Value: val, ValueType: site.literalType(loweringContext, val)} - return td, valueSetReads(site.set, td) - }, site.finish) - return id, diags + literal := &ir.Literal{TypeCommon: notes.onCommon(common), Value: val, ValueType: site.literalType(loweringContext, val)} + return literal, valueSetReads(loweringContext, site.schema, literal) + }) + return built, diags } // literalValueType picks a Literal's ValueType as enumValueType picks an @@ -389,7 +695,9 @@ func hoistLiteral(loweringContext lowering.Ctx, ts *compile.Types, site valueSet // object, which no primitive types. A refinement's value set is then typed by // every conjunct (valueSetSite.valueType). func literalValueType(schema *statement.Schema, val ir.Value) ir.PrimitiveKind { - if primitive, ok := declaredPrimitive(schema, func(primitiveKind ir.PrimitiveKind) bool { return merge.Admits(primitiveKind, val) }); ok { + if primitive, ok := declaredPrimitive(schema, func(primitiveKind ir.PrimitiveKind) bool { + return ir.PrimitiveAdmits(primitiveKind, val) == ir.AdmitsYes + }); ok { return primitive } @@ -415,16 +723,24 @@ func enumValueType(schema *statement.Schema, admits func(ir.PrimitiveKind) bool, return memberPrimitive } -// valueSetReads returns what the build of td, the node the value set set writes -// lowers to, read of set: the value set; the type where it says nothing td does -// not (valueSetTypeRead); and the format where td's ValueType is the primitive -// it pairs the type with, or a narrower one (valueTypeHoldsFormat). -func valueSetReads(set *statement.Schema, td ir.TypeDef) keySet { +// valueSetReads returns what the build of typeDef, the node the value set set +// writes lowers to, read of set: the value set; the type where it says nothing +// typeDef does not (valueSetTypeRead); and the format where typeDef's ValueType +// is the primitive it pairs the type with, or a narrower one +// (valueTypeHoldsFormat). +func valueSetReads(loweringContext lowering.Ctx, set *statement.Schema, typeDef ir.TypeDef) keySet { + return valueSetReadsBeside(loweringContext, set, set, typeDef) +} + +// valueSetReadsBeside is valueSetReads of set beside listed, the schema writing +// the enum typeDef's members are: set itself, or the inline principal an +// allOf's own keywords are read beside. +func valueSetReadsBeside(loweringContext lowering.Ctx, set, listed *statement.Schema, typeDef ir.TypeDef) keySet { read := keySetOf("enum", "const") - if valueSetTypeRead(set, td) { + if valueSetTypeRead(loweringContext, set, listed, typeDef) { read |= keyBit("type") } - switch n := td.(type) { + switch n := typeDef.(type) { case *ir.Enum: if valueTypeHoldsFormat(n.ValueType, set) { read |= keyBit("format") @@ -439,13 +755,15 @@ func valueSetReads(set *statement.Schema, td ir.TypeDef) keySet { return read } -// valueSetTypeRead reports whether the type set writes says nothing td, the -// node its value set lowers to, does not: no member is left to type; each +// valueSetTypeRead reports whether the type set writes says nothing typeDef, +// the node its value set lowers to, does not: no member is left to type; each // member is a value of it, none naming an object or array (membersTyped); the -// Literal's value is one of it (literalTyped); or td is the top type, which no -// type contradicts. A union of literals holds none of a type naming a primitive. -func valueSetTypeRead(set *statement.Schema, td ir.TypeDef) bool { - switch n := td.(type) { +// Literal's value is one of it (literalTyped); each member the enum listed +// writes, which the union of literals holds, is one of it, a null where set +// reads nullable as admitting one (writtenMembersTyped); or typeDef is the top +// type, which no type contradicts. +func valueSetTypeRead(loweringContext lowering.Ctx, set, listed *statement.Schema, typeDef ir.TypeDef) bool { + switch n := typeDef.(type) { case *ir.Enum: return len(n.Members) == 0 || membersTyped(n.Members, set) && !slices.ContainsFunc(effectiveTypes(set), structural) case *ir.Literal: @@ -453,14 +771,28 @@ func valueSetTypeRead(set *statement.Schema, td ir.TypeDef) bool { case *ir.Any: return true default: - return len(effectiveTypes(set)) == 0 + _, union := typeDef.(*ir.Union) + admitsNull := loweringContext.SchemaRules().Defines("nullable") && nullableTrue(set) + return len(effectiveTypes(set)) == 0 || union && len(listed.Enum()) > 0 && writtenMembersTyped(set.Types(), admitsNull, listed.Enum()) } } -// structural reports whether st names an object or an array, which no +// writtenMembersTyped reports whether every member, as an enum writes it, is a +// value of types, or a null where admitsNull says a 3.0 nullable admits one, +// as a type list naming null does: they then say nothing the Literals the +// members lower to do not. A member no value reads is none. +func writtenMembersTyped(types []statement.JSONSchemaTypeName, admitsNull bool, members []*yaml.Node) bool { + return !slices.ContainsFunc(members, func(member *yaml.Node) bool { + irValue, err := value.FromNode(member) + nullAdmitted := admitsNull && irValue.Kind == ir.ValueNull + return err != nil || !typesAdmit(types, irValue) && !nullAdmitted + }) +} + +// structural reports whether typeName names an object or an array, which no // primitive types. -func structural(st statement.JSONSchemaTypeName) bool { - return st == statement.KindObject || st == statement.KindArray +func structural(typeName statement.JSONSchemaTypeName) bool { + return typeName == statement.KindObject || typeName == statement.KindArray } // literalTyped reports whether lit holds the type schema declares: its @@ -501,7 +833,7 @@ func membersTyped(members []ir.EnumMember, schema *statement.Schema) bool { // enumMembersAre reports whether every member's value is a value of primitive. func enumMembersAre(members []ir.EnumMember, primitive ir.PrimitiveKind) bool { for _, enumMember := range members { - if !merge.Admits(primitive, enumMember.Value) { + if ir.PrimitiveAdmits(primitive, enumMember.Value) != ir.AdmitsYes { return false } } @@ -543,12 +875,13 @@ func enumMemberForm(irValue ir.Value) (ir.PrimitiveKind, string, bool) { } } -// enumRepeats reports each entry of the enum at pointer whose value an earlier -// entry already holds, at the repeat's own pointer. It reads the list as written, -// so a repeat is reported whether the set lowers to an Enum or a Union, and a -// repeated null though no member holds one. Values compare by valueKey, so a -// repeat in an Enum is a member whose ID ends in its occurrence number. -func enumRepeats(loweringContext lowering.Ctx, entries []enumEntry, pointer jsontext.Pointer) []ir.Diagnostic { +// enumRepeats reports each entry of schema's enum whose value an earlier entry +// already holds, at the repeat's own pointer, reading the list as written +// whether it lowers to an Enum or a Union. A repeated null is reported unless a +// keyword excludes null, whose drop enumEntries reports instead. Values compare +// by valueKey, so a repeat in an Enum is a member whose ID ends in its +// occurrence number. +func enumRepeats(loweringContext lowering.Ctx, schema *statement.Schema, entries []enumEntry) []ir.Diagnostic { firstAt := make(map[string]int, len(entries)) var diags []ir.Diagnostic for _, enumEntry := range entries { @@ -561,9 +894,15 @@ func enumRepeats(loweringContext lowering.Ctx, entries []enumEntry, pointer json firstAt[key] = enumEntry.index continue } - diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DuplicateEnumValue, - pointer+ids.Ptr("enum", strconv.Itoa(enumEntry.index)), - "enum value repeats the entry at index %d; every occurrence is kept", first)) + at := enumEntry.at + switch { + case !enumEntry.isNull(): + diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DuplicateEnumValue, at, + "enum value repeats the entry at index %d; every occurrence is kept", first)) + case schemaAdmitsNull(loweringContext, schema): + diags = append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.DuplicateEnumValue, at, + "enum value null repeats the entry at index %d; the reference to this position admits null once", first)) + } } return diags } @@ -627,16 +966,16 @@ func valueKey(irValue ir.Value, depth int) (key string, ok bool) { // listKey returns the key of a list at depth: "l", then each element's key in // order. func listKey(elements []ir.Value, depth int) (string, bool) { - var b strings.Builder - b.WriteString("l") + var builder strings.Builder + builder.WriteString("l") for _, irValue := range elements { - k, ok := valueKey(irValue, depth+1) + key, ok := valueKey(irValue, depth+1) if !ok { return "", false } - b.WriteString(lengthPrefixed(k)) + builder.WriteString(lengthPrefixed(key)) } - return b.String(), true + return builder.String(), true } // objectKey returns the key of an object at depth: "o", then each member's name @@ -644,11 +983,11 @@ func listKey(elements []ir.Value, depth int) (string, bool) { func objectKey(fields []ir.Field, depth int) (string, bool) { members := make([]string, 0, len(fields)) for _, field := range fields { - k, ok := valueKey(field.Value, depth+1) + key, ok := valueKey(field.Value, depth+1) if !ok { return "", false } - members = append(members, lengthPrefixed(field.Name)+lengthPrefixed(k)) + members = append(members, lengthPrefixed(field.Name)+lengthPrefixed(key)) } slices.Sort(members) return "o" + strings.Join(members, ""), true diff --git a/compilers/openapi/internal/schema/enum_bounds_members_test.go b/compilers/openapi/internal/schema/enum_bounds_members_test.go new file mode 100644 index 000000000..8e2aa4341 --- /dev/null +++ b/compilers/openapi/internal/schema/enum_bounds_members_test.go @@ -0,0 +1,127 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// enumBoundsReading is what a spelling of an enum beside bounds lowers to: the +// members its Enum keeps, whether it holds bounds, and where below the +// position each unsatisfiable-schema warning sits, "" at the position. +type enumBoundsReading struct { + Members []string + Bounds bool + Reports []string +} + +// TestEnum_BoundsRefusingEveryMemberDrawOneReport pins +// docs/compilers/openapi.md#enum-const for an enum beside bounds of its kind, +// in every placement openapitest.Spellings gives the enum and the bound, each +// held to the flat one in either order of the components: the Enum keeps its +// members and holds the bounds as written, and where the bounds refuse every +// member it lists one openapi/unsatisfiable-schema warning sits at the +// position. A bound refusing some members only, a pattern refusing every +// member, which ir does not evaluate, and bounds admitting no value of the +// members' kind, which pass reports as their cause, draw none of it. +func TestEnum_BoundsRefusingEveryMemberDrawOneReport(t *testing.T) { + t.Parallel() + rows := []openapitest.Row{ + {Name: "OneRefused", Spellings: openapitest.Spellings("type: string, enum: [a, abcd]", "maxLength: 3")}, + {Name: "EveryRefused", Spellings: openapitest.Spellings("type: string, enum: [abcd, abcde]", "maxLength: 3")}, + {Name: "EveryNumber", Spellings: openapitest.Spellings("type: number, enum: [1.5, 2.5]", "multipleOf: 1")}, + {Name: "Pattern", Spellings: openapitest.Spellings("type: string, enum: [b, bb]", "pattern: '^(?!b)'")}, + {Name: "CrossedLengths", Spellings: openapitest.Spellings("type: string, enum: [abcd, abcde]", "maxLength: 3", "minLength: 5")}, + {Name: "CrossedRange", Spellings: openapitest.Spellings("type: integer, enum: [1, 9]", "minimum: 5", "exclusiveMaximum: 5")}, + } + readings := readEnumBoundsRows(t, rows) + openapitest.RequireRowsAlike(t, readings, rows, "Flat") + for name, want := range map[string]enumBoundsReading{ + "OneRefused": {Members: []string{"a", "abcd"}, Bounds: true}, + "EveryRefused": {Members: []string{"abcd", "abcde"}, Bounds: true, Reports: []string{""}}, + "EveryNumber": {Members: []string{"1.5", "2.5"}, Bounds: true, Reports: []string{""}}, + "Pattern": {Members: []string{"b", "bb"}, Bounds: true}, + "CrossedLengths": {Members: []string{"abcd", "abcde"}, Bounds: true}, + "CrossedRange": {Members: []string{"1", "9"}, Bounds: true}, + } { + assert.Equal(t, want, readings[false][name]["Flat"]["component"], "%s: one report, at the position, where every member is refused", name) + } + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+ + "{type: string, maxLength: 3, allOf: [{enum: [abcd, a]}, {enum: [abcd, b]}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/E"}, unsatisfiableWarnings(diags), "what meeting sets share, refused") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/E"), + "the enum and the bounds this schema writes share no value, each member lying outside the bounds") + assert.Equal(t, []string{"abcd"}, enumBoundsOf(t, doc, "E").Members) + + doc, diags = schema.LowerSpec(t, openapitest.ComponentSpec(" E: {type: string, enum: [], maxLength: 3}\n")) + openapitest.RequireNoErrorDiags(t, diags) + assert.Empty(t, unsatisfiableWarnings(diags), "an empty enum is the empty-enum report's alone") + assert.IsType(t, &ir.Enum{}, doc.Types[componentID("E")]) +} + +// readEnumBoundsRows lowers every spelling of rows as a component, in each +// order of the components, and reads each as enumBoundsReading at the +// position "component". +func readEnumBoundsRows(t *testing.T, rows []openapitest.Row) openapitest.Readings[enumBoundsReading] { + t.Helper() + var schemas []string + for _, row := range rows { + for _, spelling := range slices.Sorted(maps.Keys(row.Spellings)) { + schemas = append(schemas, " "+row.Name+"_"+spelling+": "+row.Spellings[spelling]+"\n") + } + } + out := openapitest.Readings[enumBoundsReading]{} + for _, reversed := range []bool{false, true} { + ordered := slices.Clone(schemas) + if reversed { + slices.Reverse(ordered) + } + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(strings.Join(ordered, ""))) + openapitest.RequireNoErrorDiags(t, diags) + out[reversed] = map[string]map[string]map[string]enumBoundsReading{} + for _, row := range rows { + out[reversed][row.Name] = map[string]map[string]enumBoundsReading{} + for spelling := range row.Spellings { + name := row.Name + "_" + spelling + reading := enumBoundsOf(t, doc, name) + component := "/components/schemas/" + name + for _, at := range unsatisfiableWarnings(diags) { + if rel, beneath := strings.CutPrefix(string(at), component); beneath && (rel == "" || strings.HasPrefix(rel, "/")) { + reading.Reports = append(reading.Reports, rel) + } + } + out[reversed][row.Name][spelling] = map[string]enumBoundsReading{"component": reading} + } + } + } + return out +} + +// enumBoundsOf reads the component name of doc, an Enum, as +// enumBoundsReading: its members' values as written and whether it holds +// bounds. +func enumBoundsOf(t *testing.T, doc *ir.Document, name string) enumBoundsReading { + t.Helper() + enum, isEnum := doc.Types[componentID(name)].(*ir.Enum) + require.True(t, isEnum, "%s: got %T", name, doc.Types[componentID(name)]) + var reading enumBoundsReading + for _, enumMember := range enum.Members { + reading.Members = append(reading.Members, enumMember.Value.String+string(enumMember.Value.Number)) + } + reading.Bounds = enum.Constraints != nil + return reading +} diff --git a/compilers/openapi/internal/schema/enum_internal_test.go b/compilers/openapi/internal/schema/enum_internal_test.go index 16104d0c5..e4dfff1c4 100644 --- a/compilers/openapi/internal/schema/enum_internal_test.go +++ b/compilers/openapi/internal/schema/enum_internal_test.go @@ -32,13 +32,13 @@ func TestEnumMemberForm_ClassifiesEveryValueKind(t *testing.T) { {"bool", ir.Value{Kind: ir.ValueBool, Bool: true}, ir.PrimitiveBool, "true"}, {"bytes", ir.Value{Kind: ir.ValueBytes, Bytes: []byte("hi")}, ir.PrimitiveBytes, "aGk="}, } - for _, tc := range admissible { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range admissible { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - primitive, text, ok := enumMemberForm(tc.val) - require.True(t, ok, "%s is admissible as an enum member", tc.name) - assert.Equal(t, tc.primitive, primitive) - assert.Equal(t, tc.text, text) + primitive, text, ok := enumMemberForm(testCase.val) + require.True(t, ok, "%s is admissible as an enum member", testCase.name) + assert.Equal(t, testCase.primitive, primitive) + assert.Equal(t, testCase.text, text) }) } @@ -66,12 +66,12 @@ func TestEnumMembers_KeepsNoneBeneathAnIDNoMemberFits(t *testing.T) { t.Parallel() nodes := []*yaml.Node{{Kind: yaml.ScalarNode, Tag: "!!str", Value: "a"}} - members, _, ok := enumMembers(readEnum(nodes), "type/openapi/components/schemas/E") + members, _, ok := enumMembers(readEnum(nodes, ""), "type/openapi/components/schemas/E") require.True(t, ok) assert.Equal(t, []ir.EnumMember{{ID: "enum-member/openapi/components/schemas/E/string:a", Name: ir.NamingFor("a"), Value: ir.Value{Kind: ir.ValueString, String: "a"}}}, members) - members, primitive, ok := enumMembers(readEnum(nodes), "openapi/components/schemas/E") + members, primitive, ok := enumMembers(readEnum(nodes, ""), "openapi/components/schemas/E") assert.False(t, ok, "no member is placed beneath an ID that is no type ID") assert.Empty(t, members) assert.Empty(t, primitive) @@ -163,7 +163,7 @@ func TestTypesAdmit_ReadsEachTypesKinds(t *testing.T) { null, yes := ir.Value{Kind: ir.ValueNull}, ir.Value{Kind: ir.ValueBool, Bool: true} obj, list := ir.Value{Kind: ir.ValueObject}, ir.Value{Kind: ir.ValueList} bin := ir.Value{Kind: ir.ValueBytes, Bytes: []byte("hi")} - for _, tc := range []struct { + for _, testCase := range []struct { types []statement.JSONSchemaTypeName admits []ir.Value not []ir.Value @@ -176,13 +176,16 @@ func TestTypesAdmit_ReadsEachTypesKinds(t *testing.T) { {[]statement.JSONSchemaTypeName{statement.KindObject}, []ir.Value{obj}, []ir.Value{list}}, {[]statement.JSONSchemaTypeName{statement.KindArray}, []ir.Value{list}, []ir.Value{obj}}, {[]statement.JSONSchemaTypeName{statement.KindInteger, statement.KindBoolean}, []ir.Value{one, yes}, []ir.Value{stringValue}}, - {[]statement.JSONSchemaTypeName{statement.KindInteger, "file"}, []ir.Value{stringValue, one, null}, nil}, + // A word no dialect defines admits what its scalar lowers over, a string + // (baseForType), as the conjunction's kind reading reads it. + {[]statement.JSONSchemaTypeName{statement.KindInteger, "file"}, []ir.Value{stringValue, one}, []ir.Value{null, yes}}, + {[]statement.JSONSchemaTypeName{"file"}, []ir.Value{stringValue, bin}, []ir.Value{one, obj}}, } { - for _, value := range tc.admits { - assert.True(t, typesAdmit(tc.types, value), "%v admits %+v", tc.types, value) + for _, value := range testCase.admits { + assert.True(t, typesAdmit(testCase.types, value), "%v admits %+v", testCase.types, value) } - for _, value := range tc.not { - assert.False(t, typesAdmit(tc.types, value), "%v admits no %+v", tc.types, value) + for _, value := range testCase.not { + assert.False(t, typesAdmit(testCase.types, value), "%v admits no %+v", testCase.types, value) } } } diff --git a/compilers/openapi/internal/schema/enum_null_test.go b/compilers/openapi/internal/schema/enum_null_test.go index e7dd0b6fe..cd4845d4d 100644 --- a/compilers/openapi/internal/schema/enum_null_test.go +++ b/compilers/openapi/internal/schema/enum_null_test.go @@ -15,8 +15,8 @@ import ( "github.com/dexpace/morphic/ir" ) -// nullAlonePositions writes the schema at every position one can stand at: a -// required and an optional property, a list's element, a map's value, a union +// nullAlonePositions writes the schema at every position one can be written at: +// a required and an optional property, a list's element, a map's value, a union // variant through a $ref, a $ref and a chain of two, a property an allOf // composes, an allOf of it alone, a required path, an optional query and a // required query parameter, and an optional and a required response header. @@ -70,7 +70,7 @@ components: // that position is not asked of it. func TestLowerNullAlone_EveryPositionNamesAnEnumWithNoMember(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string nullable bool }{ @@ -78,16 +78,16 @@ func TestLowerNullAlone_EveryPositionNamesAnEnumWithNoMember(t *testing.T) { {name: "a type list of null", schema: `{type: ["null"]}`, nullable: true}, {name: "a const of null a type excludes", schema: `{type: string, const: null}`}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, fmt.Sprintf(nullAlonePositions, tc.schema)) + doc, diags := parseFull(t, fmt.Sprintf(nullAlonePositions, testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) for _, nullAloneUse := range nullAloneUses(t, doc) { - if nullAloneUse.label == "allOfNil" && !tc.nullable { + if nullAloneUse.label == "allOfNil" && !testCase.nullable { continue } assertNullAloneAt(t, doc, nullAloneUse.label, nullAloneUse.ref) - assert.Equal(t, tc.nullable, nullAloneUse.ref.Nullable, "%s: the reference alone says the null", nullAloneUse.label) + assert.Equal(t, testCase.nullable, nullAloneUse.ref.Nullable, "%s: the reference alone says the null", nullAloneUse.label) if nullAloneUse.carried { assert.Equal(t, nullAloneUse.wantRequired, nullAloneUse.required, "%s keeps its own presence", nullAloneUse.label) } @@ -148,16 +148,16 @@ func nullAloneUses(t *testing.T, doc *ir.Document) []nullAloneUse { // hoist, to name a closed Enum with no member. func assertNullAloneAt(t *testing.T, doc *ir.Document, label string, ref ir.TypeRef) { t.Helper() - td := doc.Types[ref.Target] + typeDef := doc.Types[ref.Target] for range 3 { - alias, ok := td.(*ir.Scalar) + alias, ok := typeDef.(*ir.Scalar) if !ok || alias.Base == nil { break } - td = doc.Types[alias.Base.Target] + typeDef = doc.Types[alias.Base.Target] } - enum, ok := td.(*ir.Enum) - require.True(t, ok, "%s names an Enum, got %T", label, td) + enum, ok := typeDef.(*ir.Enum) + require.True(t, ok, "%s names an Enum, got %T", label, typeDef) assert.Empty(t, enum.Members, "%s: the Enum has no member", label) assert.True(t, enum.Closed, label) } @@ -188,7 +188,7 @@ func TestLowerNullAlone_IsToldFromTheTopType(t *testing.T) { // draws nothing (docs/compilers/openapi.md#shape-applicator). func TestLowerNullAlone_KeepsWhatTheEnumCannotHold(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string kept []string infos int // one for what is kept unread, one for a union kept @@ -200,9 +200,9 @@ func TestLowerNullAlone_KeepsWhatTheEnumCannotHold(t *testing.T) { {name: "a union of null", schema: `{oneOf: [{type: "null"}], minimum: 3}`, kept: []string{"minimum", "oneOf"}, infos: 2}, {name: "nothing", schema: `{type: "null", description: d}`}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) enum, ok := doc.Types[componentID("S")].(*ir.Enum) require.True(t, ok, "got %T", doc.Types[componentID("S")]) @@ -212,13 +212,13 @@ func TestLowerNullAlone_KeepsWhatTheEnumCannotHold(t *testing.T) { keys = append(keys, key) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason, key) } - want := make([]string, 0, len(tc.kept)) - for _, k := range tc.kept { - want = append(want, "openapi:"+k) + want := make([]string, 0, len(testCase.kept)) + for _, key := range testCase.kept { + want = append(want, "openapi:"+key) } assert.ElementsMatch(t, want, keys, "only what the Enum cannot hold is kept, never the type") got := codesAt(diags, "/components/schemas/S") - assert.Len(t, got, tc.infos, "each keeping is reported once, and nothing else is") + assert.Len(t, got, testCase.infos, "each keeping is reported once, and nothing else is") for _, diagnostic := range got { assert.Equal(t, ir.Diagnostic{Severity: ir.SeverityInfo, Code: diag.DegradedConstruct}, diagnostic) } diff --git a/compilers/openapi/internal/schema/enum_prim_internal_test.go b/compilers/openapi/internal/schema/enum_prim_internal_test.go index 9437f23b2..184dca776 100644 --- a/compilers/openapi/internal/schema/enum_prim_internal_test.go +++ b/compilers/openapi/internal/schema/enum_prim_internal_test.go @@ -32,7 +32,7 @@ func TestEnumMemberPrimitive_ReadsWhatEnumMembersGives(t *testing.T) { "a list": {{Kind: yaml.SequenceNode, Tag: "!!seq"}}, "none": nil, } { - entries := readEnum(nodes) + entries := readEnum(nodes, "") members, wantPrimitive, wantOK := enumMembers(entries, "type/openapi/components/schemas/E") primitive, ok := enumMemberPrimitive(entries) assert.Equal(t, wantOK, ok, name) @@ -51,7 +51,7 @@ func TestEnumMemberPrimitive_BuildsNoMember(t *testing.T) { for i := range 200 { nodes = append(nodes, scalar("!!str", fmt.Sprintf("v%d", i))) } - entries := readEnum(nodes) + entries := readEnum(nodes, "") allocs := testing.AllocsPerRun(10, func() { if _, ok := enumMemberPrimitive(entries); !ok || !entriesAre(entries, ir.PrimitiveString) { t.Fatal("200 strings are an Enum of strings") diff --git a/compilers/openapi/internal/schema/enum_test.go b/compilers/openapi/internal/schema/enum_test.go index fdf8b7032..bd904adba 100644 --- a/compilers/openapi/internal/schema/enum_test.go +++ b/compilers/openapi/internal/schema/enum_test.go @@ -112,10 +112,10 @@ func TestEnum_NullMemberNormalizesToNullable(t *testing.T) { wantMembers: numberMembers, }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, enumPropertySpec(tc.version, tc.schema)) + doc, diags := schema.LowerSpec(t, enumPropertySpec(testCase.version, testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) assert.False(t, openapitest.HasDiag(diags, diag.DegradedConstruct), "a normalized nullable enum is not a degradation; got %+v", diags) @@ -130,14 +130,14 @@ func TestEnum_NullMemberNormalizesToNullable(t *testing.T) { enum, ok := doc.Types[enumID].(*ir.Enum) require.True(t, ok, "the property lowers to an Enum, not a union of literals") assert.True(t, enum.Closed, "a JSON Schema enum stays closed") - assert.Equal(t, tc.wantValueType, enum.ValueType) + assert.Equal(t, testCase.wantValueType, enum.ValueType) got := make([]ir.Value, 0, len(enum.Members)) for _, member := range enum.Members { assert.NotEmpty(t, member.Name.Source, "every kept member is named") got = append(got, member.Value) } - if diff := cmp.Diff(tc.wantMembers, got); diff != "" { + if diff := cmp.Diff(testCase.wantMembers, got); diff != "" { t.Errorf("enum members (-want +got):\n%s", diff) } }) @@ -187,24 +187,24 @@ func TestEnum_NullIsNeverAMember(t *testing.T) { {name: "null alone, a type excludes it", version: "3.1.0", schema: `{type: object, enum: [null]}`, wantMembers: []ir.Value{}, wantDropped: "/enum/0"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, enumPropertySpec(tc.version, tc.schema)) + doc, diags := schema.LowerSpec(t, enumPropertySpec(testCase.version, testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) const at = "/components/schemas/S/properties/p" owner, ok := doc.Types[componentID("S")].(*ir.Model) require.True(t, ok, "S is a model") require.Len(t, owner.Properties, 1) - assert.Equal(t, tc.wantNullable, owner.Properties[0].Type.Nullable, + assert.Equal(t, testCase.wantNullable, owner.Properties[0].Type.Nullable, "the reference alone says whether the position admits null") got, isUnion := enumValuesAt(t, doc, ir.TypeID("type/anonymous"+at)) - assert.Equal(t, tc.wantVariants != nil, isUnion, "an Enum unless the non-null members are of several kinds") - want := tc.wantMembers - if tc.wantVariants != nil { - want = tc.wantVariants + assert.Equal(t, testCase.wantVariants != nil, isUnion, "an Enum unless the non-null members are of several kinds") + want := testCase.wantMembers + if testCase.wantVariants != nil { + want = testCase.wantVariants } if diff := cmp.Diff(want, got); diff != "" { t.Errorf("no member or variant holds the null (-want +got):\n%s", diff) @@ -213,10 +213,10 @@ func TestEnum_NullIsNeverAMember(t *testing.T) { "only a union reports its kind; got %+v", diags) var wantDropped []jsontext.Pointer - if tc.wantDropped != "" { - wantDropped = []jsontext.Pointer{jsontext.Pointer(at + tc.wantDropped)} + if testCase.wantDropped != "" { + wantDropped = []jsontext.Pointer{jsontext.Pointer(at + testCase.wantDropped)} } - assert.Equal(t, wantDropped, degradedWarnings(diags), + assert.Equal(t, wantDropped, unsatisfiableWarnings(diags), "a null the schema excludes is reported at itself, and only it") }) } @@ -250,15 +250,15 @@ func TestEnum_NullAgreesWithTheOneOfSpelling(t *testing.T) { // member, typed alike, behind a reference that alone says whether the position // admits null, and the same warning where a keyword beside it excludes null. No // Literal holds a null (docs/ir/containers.md#literals). A union branch of -// either is the union's null (TestUnion_EverySpellingOfANullBranchLowersAlike). +// either is the union's null (TestNullBranch_EverySpellingLowersAlike). func TestConst_NullLowersAsAnEnumOfNullAlone(t *testing.T) { t.Parallel() read := func(t *testing.T, body string) (*ir.Enum, bool, []jsontext.Pointer) { t.Helper() doc, diags := schema.LowerSpec(t, enumPropertySpec("3.1.0", body)) openapitest.RequireNoErrorDiags(t, diags) - for id, td := range doc.Types { - lit, isLit := td.(*ir.Literal) + for id, typeDef := range doc.Types { + lit, isLit := typeDef.(*ir.Literal) assert.False(t, isLit && lit.Value.Kind == ir.ValueNull, "%s is a Literal of null", id) } owner, ok := doc.Types[componentID("S")].(*ir.Model) @@ -266,9 +266,9 @@ func TestConst_NullLowersAsAnEnumOfNullAlone(t *testing.T) { ref := owner.Properties[0].Type enum, ok := doc.Types[ref.Target].(*ir.Enum) require.True(t, ok, "%s lowers to an Enum, got %T", body, doc.Types[ref.Target]) - return enum, ref.Nullable, degradedWarnings(diags) + return enum, ref.Nullable, unsatisfiableWarnings(diags) } - for _, tc := range []struct { + for _, testCase := range []struct { name, beside string nullable bool }{ @@ -277,22 +277,22 @@ func TestConst_NullLowersAsAnEnumOfNullAlone(t *testing.T) { {name: "a nullable string", beside: `type: [string, "null"], `, nullable: true}, {name: "a string excluding null", beside: `type: string, `}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - body := func(set string) string { return "{" + tc.beside + set + "}" } + body := func(set string) string { return "{" + testCase.beside + set + "}" } got, gotNull, gotWarned := read(t, body("const: null")) want, wantNull, wantWarned := read(t, body("enum: [null]")) assert.Empty(t, got.Members, "no member holds the null") assert.True(t, got.Closed) assert.Empty(t, got.Unmodeled, "the const and a type beside it are read, so nothing is kept verbatim") assert.Equal(t, want.ValueType, got.ValueType, "typed as the enum spelling is") - assert.Equal(t, tc.nullable, gotNull, "the reference alone admits the null") + assert.Equal(t, testCase.nullable, gotNull, "the reference alone admits the null") assert.Equal(t, wantNull, gotNull) assert.Len(t, gotWarned, len(wantWarned), "warned where the enum spelling is") for _, at := range gotWarned { assert.True(t, strings.HasSuffix(string(at), "/const"), "the warning is at the const, got %s", at) } - assert.Equal(t, !tc.nullable, len(gotWarned) == 1, "a null the type excludes is reported") + assert.Equal(t, !testCase.nullable, len(gotWarned) == 1, "a null the type excludes is reported") }) } } @@ -323,12 +323,12 @@ func enumValuesAt(t *testing.T, doc *ir.Document, id ir.TypeID) ([]ir.Value, boo } } -// degradedWarnings returns the pointers of diags' openapi/degraded-construct +// unsatisfiableWarnings returns the pointers of diags' openapi/unsatisfiable-schema // warnings, in order. -func degradedWarnings(diags []ir.Diagnostic) []jsontext.Pointer { +func unsatisfiableWarnings(diags []ir.Diagnostic) []jsontext.Pointer { var out []jsontext.Pointer for _, diagnostic := range diags { - if diagnostic.Code == diag.DegradedConstruct && diagnostic.Severity == ir.SeverityWarning { + if diagnostic.Code == diag.UnsatisfiableSchema && diagnostic.Severity == ir.SeverityWarning { out = append(out, diagnostic.Provenance.Pointer) } } @@ -383,7 +383,6 @@ func TestEnum_EmptyMemberListMatchesNoValue(t *testing.T) { enum: []`, wantValueType: ir.PrimitiveAny, wantEmpty: true, - wantKept: "openapi:$ref", }, { name: "beside a nullable type array", @@ -398,29 +397,29 @@ func TestEnum_EmptyMemberListMatchesNoValue(t *testing.T) { wantMembers: 2, }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(tc.schema+"\n")) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) enum, ok := typeByName(doc, "S").(*ir.Enum) require.True(t, ok, "the enum keyword lowers to an Enum, got %T", typeByName(doc, "S")) assert.True(t, enum.Closed, "an enum admits its members and nothing else") - assert.Len(t, enum.Members, tc.wantMembers, "the member list is the declared one") - assert.Equal(t, tc.wantValueType, enum.ValueType) + assert.Len(t, enum.Members, testCase.wantMembers, "the member list is the declared one") + assert.Equal(t, testCase.wantValueType, enum.ValueType) want := 0 - if tc.wantEmpty { + if testCase.wantEmpty { want = 1 } assert.Equal(t, want, openapitest.CountDiagsAt(diags, diag.EmptyEnum, ir.SeverityWarning), "a value space with no member is reported once; got %+v", diags) - if tc.wantKept == "" { + if testCase.wantKept == "" { return } - assert.Contains(t, enum.Unmodeled, tc.wantKept, + assert.Contains(t, enum.Unmodeled, testCase.wantKept, "the keyword the dispatch passed over stays beside the enum") }) } @@ -477,8 +476,8 @@ func TestHoistLiteral_UnconvertibleConstBecomesAny(t *testing.T) { irAny, ok := doc.Types[componentID("K")].(*ir.Any) require.True(t, ok, "an unconvertible const hoists the schemaless top type at its own pointer") assert.Equal(t, ir.KindAny, irAny.Kind()) - for _, td := range doc.Types { - _, isLiteral := td.(*ir.Literal) + for _, typeDef := range doc.Types { + _, isLiteral := typeDef.(*ir.Literal) assert.False(t, isLiteral, "no Literal is produced anywhere; nothing lies about the value being null") } require.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning), @@ -502,9 +501,9 @@ func TestEnumAsUnion_UnconvertibleMemberBecomesAny(t *testing.T) { require.True(t, ok, "the convertible member still hoists a Literal") assert.Equal(t, ir.Value{Kind: ir.ValueString, String: "ok"}, member0.Value) - member1, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Any) + firstMember, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Any) require.True(t, ok, "the unconvertible member hoists the schemaless top type, not a lying null Literal") - assert.Equal(t, ir.KindAny, member1.Kind()) + assert.Equal(t, ir.KindAny, firstMember.Kind()) require.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning), "exactly one warning for the unconvertible member, distinct from the heterogeneous-enum info diagnostic") @@ -516,13 +515,13 @@ func TestEnumAsUnion_UnconvertibleMemberBecomesAny(t *testing.T) { func TestEnum_UnquotedDatesStayClosedEnum(t *testing.T) { t.Parallel() // The exact issue repro: YAML 1.1 resolves an unquoted date to !!timestamp. - // Before the fix, scalarValue had no case for it, so both enum members - // failed to convert, enumMembers bailed to enumAsUnion, and the union - // fallback turned every member into a null literal — the actual dates never - // survived. One diagnostic stands beside that, not about a date: the - // component-level default is kept as residue (it binds a use of the type, so - // the type node has no field for it; see - // TestProperty_UnquotedDateDefaultPreserved for the default path). + // Before the fix, scalarValue had no case for it, so both enum members failed + // to convert, enumMembers bailed to enumAsUnion, and the union fallback turned + // every member into a null literal — the actual dates never survived. One + // diagnostic sits beside that, not about a date: the component-level default + // is kept as an unread keyword (it binds a use of the type, so the type node + // has no field for it; see TestProperty_UnquotedDateDefaultPreserved for the + // default path). spec := openapitest.ComponentSpec(` D: type: string format: date @@ -571,17 +570,17 @@ func TestEnum_ValueTypeReadsTheFormatItsMembersFit(t *testing.T) { {"no format", `{type: integer, enum: [1, 2]}`, ir.PrimitiveInteger, false}, {"a redaction", `{type: string, format: password, enum: [a]}`, ir.PrimitiveString, false}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+tc.schema+"\n")) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) enum, ok := doc.Types[componentID("E")].(*ir.Enum) require.True(t, ok) - assert.Equal(t, tc.want, enum.ValueType) + assert.Equal(t, testCase.want, enum.ValueType) _, kept := enum.Unmodeled["openapi:format"] - assert.Equal(t, tc.kept, kept) - assert.Equal(t, tc.kept, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/E"), + assert.Equal(t, testCase.kept, kept) + assert.Equal(t, testCase.kept, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/E"), "the format is reported exactly where it is kept: %+v", diags) }) } @@ -614,31 +613,29 @@ func TestEnum_AMemberNoTypeAdmitsIsReportedAndKept(t *testing.T) { {"an integer written with a point", `{type: integer, enum: [1.0, 2]}`, ir.PrimitiveInteger, nil}, {"binary with no type", `{enum: [!!binary aGk=, !!binary aG8=]}`, ir.PrimitiveBytes, nil}, {"members of their type", `{type: number, enum: [1, 2.5]}`, ir.PrimitiveNumber, nil}, - {"a string under null alone", `{type: "null", enum: [a, null]}`, ir.PrimitiveString, []string{"/enum/0"}}, - {"numbers under a null list", `{type: ["null"], enum: [1, 2]}`, ir.PrimitiveNumber, []string{"/enum/0", "/enum/1"}}, {"a string under a nullable integer", `{type: [integer, "null"], enum: [a, null]}`, ir.PrimitiveString, []string{"/enum/0"}}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+tc.schema+"\n")) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) const at = "/components/schemas/E" var want []jsontext.Pointer - for _, r := range tc.rejected { + for _, r := range testCase.rejected { want = append(want, jsontext.Pointer(at+r)) } - assert.Equal(t, want, degradedWarnings(diags), "each member no type admits, and only it") + assert.Equal(t, want, unsatisfiableWarnings(diags), "each member no type admits, and only it") enum, isEnum := doc.Types[componentID("E")].(*ir.Enum) - assert.Equal(t, tc.want != "", isEnum, "got %T", doc.Types[componentID("E")]) + assert.Equal(t, testCase.want != "", isEnum, "got %T", doc.Types[componentID("E")]) if isEnum { - assert.Equal(t, tc.want, enum.ValueType, "the members' primitive") + assert.Equal(t, testCase.want, enum.ValueType, "the members' primitive") _, kept := enum.Unmodeled["openapi:type"] - assert.Equal(t, tc.rejected != nil, kept, "a type the members are not values of stays verbatim") + assert.Equal(t, testCase.rejected != nil, kept, "a type the members are not values of stays verbatim") } - if isEnum && tc.rejected != nil { + if isEnum && testCase.rejected != nil { assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), "lowered to an enum whose members are not all values of its declared type,", "the keeping says why") } @@ -646,6 +643,40 @@ func TestEnum_AMemberNoTypeAdmitsIsReportedAndKept(t *testing.T) { } } +// TestEnum_ATypeOfNullAloneDecidesOverItsMembers pins +// docs/compilers/openapi.md#null-alone for an enum beside a type of null +// alone: the type decides, so the position is the closed Enum with no member, +// each member it excludes reported at itself, and the enum, not the type, is +// kept verbatim, as no node holds what it lists. +func TestEnum_ATypeOfNullAloneDecidesOverItsMembers(t *testing.T) { + t.Parallel() + for name, testCase := range map[string]struct { + schema string + rejected []string + }{ + "a string under null alone": {`{type: "null", enum: [a, null]}`, []string{"/enum/0"}}, + "numbers under a null list": {`{type: ["null"], enum: [1, 2]}`, []string{"/enum/0", "/enum/1"}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+testCase.schema+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + var want []jsontext.Pointer + for _, r := range testCase.rejected { + want = append(want, jsontext.Pointer("/components/schemas/E"+r)) + } + assert.Equal(t, want, unsatisfiableWarnings(diags), "each member the type excludes, and only it") + enum, isEnum := doc.Types[componentID("E")].(*ir.Enum) + require.True(t, isEnum, "got %T", doc.Types[componentID("E")]) + assert.Empty(t, enum.Members) + assert.True(t, enum.Closed) + assert.Contains(t, enum.Unmodeled, "openapi:enum") + assert.Equal(t, ir.ReasonDegradedLowering, enum.Unmodeled["openapi:enum"].Reason) + assert.NotContains(t, enum.Unmodeled, "openapi:type", "the type is read") + }) + } +} + // TestEnum_ReportsWhyAFormatStayedVerbatim holds the report to the cause that // fired. An Enum's ValueType is a home for what the table pairs, so a format the // members do not fit says so, and only one with no pairing has no home at all. @@ -664,12 +695,12 @@ func TestEnum_ReportsWhyAFormatStayedVerbatim(t *testing.T) { {"no declared type", `{format: int64, enum: [1, 2]}`, `a node of kind "enum",`}, {"a fit beside a homeless keyword", `{type: integer, format: int8, enum: [1], maxItems: 2}`, `a node of kind "enum",`}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - _, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+tc.schema+"\n")) + _, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+testCase.schema+"\n")) assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/E"), - "lowered to "+tc.want+" which has no home for") + "lowered to "+testCase.want+" which has no home for") }) } } @@ -712,13 +743,13 @@ func TestEnumAsUnion_ExclusiveWhereNoInstanceMatchesTwoEntries(t *testing.T) { {"a repeated composite", `{enum: [[1], "a", [1.0]]}`, false}, {"an unconvertible entry", `{enum: [1, !foo bar]}`, false}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, _ := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+tc.schema+"\n")) + doc, _ := schema.LowerSpec(t, openapitest.ComponentSpec(" E: "+testCase.schema+"\n")) union, ok := doc.Types[componentID("E")].(*ir.Union) require.True(t, ok) - assert.Equal(t, tc.want, union.Exclusive) + assert.Equal(t, testCase.want, union.Exclusive) }) } } @@ -1048,31 +1079,53 @@ func TestLiteral_ValueTypeReadsTheTypeAndFormatItsValueFits(t *testing.T) { {"an object the type is not", `{type: array, const: {a: 1}}`, "", "openapi:type", true}, {"a list the type is not", `{type: object, const: [1]}`, "", "openapi:type", true}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" L: "+tc.schema+"\n")) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" L: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) lit, ok := doc.Types[componentID("L")].(*ir.Literal) require.True(t, ok, "got %T", doc.Types[componentID("L")]) - assert.Equal(t, tc.want, lit.ValueType) + assert.Equal(t, testCase.want, lit.ValueType) var kept []string for key := range lit.Unmodeled { kept = append(kept, key) } - if tc.kept == "" { + if testCase.kept == "" { assert.Empty(t, kept) } else { - assert.Equal(t, []string{tc.kept}, kept) + assert.Equal(t, []string{testCase.kept}, kept) } - assert.Equal(t, tc.kept != "", openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/L"), + assert.Equal(t, testCase.kept != "", openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/L"), "a keyword is reported exactly where it is kept: %+v", diags) var want []jsontext.Pointer - if tc.rejected { + if testCase.rejected { want = []jsontext.Pointer{"/components/schemas/L/const"} } - assert.Equal(t, want, degradedWarnings(diags), + assert.Equal(t, want, unsatisfiableWarnings(diags), "a const no instance matches is reported at it, and only then") }) } } + +// TestEnum_ATypeEveryListedMemberHasRestatesTheUnionOfLiterals pins a type +// beside an enum lowering to a union of literals: every member a value of a +// kind it names, flat or beside the allOf whose entry writes the enum, it +// restates the union and is kept nowhere; one a member is no value of is kept; +// and beside the bottom a const and an enum sharing no list lower to, it is +// kept as the bottom keeps the position's own keywords. +func TestEnum_ATypeEveryListedMemberHasRestatesTheUnionOfLiterals(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " Flat: {type: [array, object], enum: [[1], {a: 1}]}\n"+ + " Beside: {allOf: [{enum: [[1], [2]]}], type: array}\n"+ + " Lacking: {type: array, enum: [[1], {a: 1}]}\n"+ + " Bottom: {allOf: [{const: [1], enum: [[2]]}], type: array}\n")) + openapitest.RequireNoErrorDiags(t, diags) + for name, kept := range map[string]bool{"Flat": false, "Beside": false, "Lacking": true, "Bottom": true} { + _, keeps := typeByName(doc, name).Common().Unmodeled["openapi:type"] + assert.Equal(t, kept, keeps, name) + } + _, isModel := typeByName(doc, "Bottom").(*ir.Model) + assert.True(t, isModel, "a const and an enum sharing no list lower to the bottom") +} diff --git a/compilers/openapi/internal/schema/export_test.go b/compilers/openapi/internal/schema/export_test.go index 783018b3d..7dcac194e 100644 --- a/compilers/openapi/internal/schema/export_test.go +++ b/compilers/openapi/internal/schema/export_test.go @@ -4,6 +4,7 @@ package schema import ( + "encoding/json/jsontext" "iter" "slices" "testing" @@ -22,12 +23,8 @@ import ( "github.com/dexpace/morphic/ir" ) -// MaxDiscriminatorAncestorDepth is maxDiscriminatorAncestorDepth, for the -// external tests. -const MaxDiscriminatorAncestorDepth = maxDiscriminatorAncestorDepth - -// MaxChainHops is maxChainHops, for the external tests. -const MaxChainHops = maxChainHops +// MaxRefHops is maxRefHops, for the external tests. +const MaxRefHops = maxRefHops // MaxAdmissionReads is maxAdmissionReads, for the external tests. const MaxAdmissionReads = maxAdmissionReads @@ -38,6 +35,9 @@ const MaxAdmissionMembers = maxAdmissionMembers // MaxRefinedConjuncts is maxRefinedConjuncts, for the external tests. const MaxRefinedConjuncts = maxRefinedConjuncts +// MaxScalarChainLinks is maxScalarChainNodes, for the external tests. +const MaxScalarChainLinks = maxScalarChainNodes + // Lowerer is test scaffolding, not a compiler type. The compiler has no such // struct: every lowering is a function of the context and the registry, and // the caller owns the document being built (#177). It is declared here, once, @@ -96,13 +96,65 @@ func LowerSpecWith(t *testing.T, src string, policy lowering.Policy) (*ir.Docume } // LowerSpecCountingLands lowers src as LowerSpec does, and returns too how -// many hop readings were made reading what a $ref lands on. +// many readings the run's null answer made of a $ref landing on another, each +// hop of an alias chain read once. func LowerSpecCountingLands(t *testing.T, src string) (*ir.Document, []ir.Diagnostic, int) { t.Helper() lowerer, diags := LoweredFor(t, src) lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) doc := lowerer.Document(t) - return doc, append(diags, lowerer.Diags.List()...), *landingCount(lowerer.Ctx) + return doc, append(diags, lowerer.Diags.List()...), nullAnswerMemoOf(lowerer.Ctx).aliasReads +} + +// LowerSpecCountingNullReads lowers src as LowerSpec does, and returns too how +// many readings of a schema the run's null answer made: one for each schema +// read once from its own keywords and its dependencies' answers, and one for +// each re-read a cycle's fixpoints make (nullAnswerReads). +func LowerSpecCountingNullReads(t *testing.T, src string) (*ir.Document, []ir.Diagnostic, int) { + t.Helper() + lowerer, diags := LoweredFor(t, src) + lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) + doc := lowerer.Document(t) + return doc, append(diags, lowerer.Diags.List()...), nullAnswerReads(lowerer.Ctx) +} + +// nullAnswerReads is the count of readings the null answer of +// loweringContext's run has made, kept in the run's read-once store. +func nullAnswerReads(loweringContext lowering.Ctx) int { + return nullAnswerMemoOf(loweringContext).reads +} + +// LowerSpecCountingDiscriminatorFacts lowers src as LowerSpec does, and +// returns too how many irfacts.DocumentFacts the run's model-discriminator +// store built for its settlement. +func LowerSpecCountingDiscriminatorFacts(t *testing.T, src string) (*ir.Document, []ir.Diagnostic, int) { + t.Helper() + lowerer, diags := LoweredFor(t, src) + lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) + doc := lowerer.Document(t) + return doc, append(diags, lowerer.Diags.List()...), *discriminatorFactsCount(lowerer.Ctx) +} + +// LowerSpecCountingAncestorSteps lowers src as LowerSpec does, and returns too +// how many composition edges the climb to each schema's discriminated +// ancestors followed in the run. +func LowerSpecCountingAncestorSteps(t *testing.T, src string) (*ir.Document, []ir.Diagnostic, int) { + t.Helper() + lowerer, diags := LoweredFor(t, src) + lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) + doc := lowerer.Document(t) + return doc, append(diags, lowerer.Diags.List()...), *ancestorStepCount(lowerer.Ctx) +} + +// LowerSpecCountingReferentReads lowers src as LowerSpec does, and returns too +// how many referenced schemas the run read where each is written, and how +// many it read all a reference reaches from. +func LowerSpecCountingReferentReads(t *testing.T, src string) (doc *ir.Document, diags []ir.Diagnostic, sites, reached int) { + t.Helper() + lowerer, loadDiags := LoweredFor(t, src) + lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) + reads := referentReadCount(lowerer.Ctx) + return lowerer.Document(t), append(loadDiags, lowerer.Diags.List()...), reads.sites, reads.reached } // NewRawLowerer builds a fixture over a hand-constructed document, bypassing the @@ -115,17 +167,17 @@ func NewRawLowerer(doc *soa.OpenAPI) *Lowerer { // document, as run hands them to LowerComponentSchemas. func (l *Lowerer) Schemas() iter.Seq2[string, *statement.Statement] { return func(yield func(string, *statement.Statement) bool) { - for name, js := range l.Doc.Components.GetSchemas().All() { - if !yield(name, l.Ctx.Statements().Of(js)) { + for name, jsonSchema := range l.Doc.Components.GetSchemas().All() { + if !yield(name, l.Ctx.Statements().Of(jsonSchema)) { return } } } } -// Document finishes the registry as run does once every lowering has -// returned, and returns the document under construction holding it. What the -// settling reports joins the fixture's diagnostics; a refusal is a compiler bug +// Document finishes the registry as run does once every lowering has returned, +// and returns the document under construction holding it. What the settling +// reports are added to the fixture's diagnostics; a refusal is a compiler bug // no fixture provokes, so one fails the test. func (l *Lowerer) Document(t *testing.T) *ir.Document { t.Helper() @@ -138,11 +190,11 @@ func (l *Lowerer) Document(t *testing.T) *ir.Document { return l.Out } -// Standalone returns the statement of js read alone, by a table of its own -// that knows no bindings and reads no rows: for a test handing a schema it +// Standalone returns the statement of jsonSchema read alone, by a table of its +// own that knows no bindings and reads no rows: for a test handing a schema it // decoded to a reader that takes a statement. -func Standalone(js *oas3.JSONSchema[oas3.Referenceable]) *statement.Statement { - return statement.NewTable(statement.Source{}).Of(js) +func Standalone(jsonSchema *oas3.JSONSchema[oas3.Referenceable]) *statement.Statement { + return statement.NewTable(statement.Source{}).Of(jsonSchema) } // StandaloneSchema is Standalone for a schema object decoded alone, nil for a @@ -161,9 +213,9 @@ func StandaloneSchema(s *oas3.Schema) *statement.Schema { // reference binding, so the reader would answer for another schema than the // run's without the test saying so. func StatedIn(lowerer *Lowerer, s *oas3.Schema) *statement.Schema { - for _, js := range lowerer.Doc.Components.Schemas.All() { - if js.GetSchema() == s { - return lowerer.Ctx.Statements().Of(js).Schema + for _, jsonSchema := range lowerer.Doc.Components.Schemas.All() { + if jsonSchema.GetSchema() == s { + return lowerer.Ctx.Statements().Of(jsonSchema).Schema } } panic("schema: StatedIn of a schema no component of the fixture's document declares") @@ -181,8 +233,8 @@ func LowerSource(t *testing.T, src compilers.Source) (*ir.Document, []*statement lowerer := LowererOver(service.New(0, loaded, service.Policy{})) lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) var statements []*statement.Statement - for _, js := range lowerer.Schemas() { - statements = append(statements, js) + for _, schemaStatement := range lowerer.Schemas() { + statements = append(statements, schemaStatement) } return lowerer.Document(t), statements, true } @@ -194,3 +246,22 @@ func UnreadKeys(schema *statement.Schema, read []string) []string { // ReadDomain returns readDomain. func ReadDomain() []string { return slices.Clone(readDomain) } + +// UnknownTaken is unknownTaken, for the tests enumerating the keys it returns. +func UnknownTaken(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []string { + return unknownTaken(loweringContext, schema, pointer) +} + +// KeepsUnknownKeywords is keepsUnknownKeywords, the alias gate's reading of +// what KeepUnknownKeywords keeps. +func KeepsUnknownKeywords(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) bool { + return keepsUnknownKeywords(loweringContext, schema, pointer) +} + +// NodeHolds is nodeHolds, for the test holding it to the fields it reads. +func NodeHolds(typeDef ir.TypeDef) bool { return nodeHolds(typeDef) } + +// KeepDiscriminator is keepDiscriminator, for the test pinning its guard. +func KeepDiscriminator(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, discriminator *statement.Discriminator, pointer jsontext.Pointer) []ir.Diagnostic { + return keepDiscriminator(loweringContext, unmodeled, discriminator, pointer) +} diff --git a/compilers/openapi/internal/schema/helpers_test.go b/compilers/openapi/internal/schema/helpers_test.go index 2c4c3ffc7..a32e9d6cf 100644 --- a/compilers/openapi/internal/schema/helpers_test.go +++ b/compilers/openapi/internal/schema/helpers_test.go @@ -45,6 +45,20 @@ func validated(t *testing.T, doc *ir.Document) []ir.Diagnostic { return diags } +// routeFindings returns what pass.Validate reports of doc other than a +// variant or subtype no route reaches, a note on what the source routes, +// for a test holding every route a discriminator writes to a variant. +func routeFindings(t *testing.T, doc *ir.Document) []ir.Diagnostic { + t.Helper() + var out []ir.Diagnostic + for _, diagnostic := range validated(t, doc) { + if diagnostic.Code != "pass/discriminator-unrouted-variant" { + out = append(out, diagnostic) + } + } + return out +} + // parseFull runs the whole public compiler pipeline over src. It reaches back // through openapi deliberately: a schema position under a parameter or a request // body is only hoisted once the operation walk has resolved its way down to it, @@ -100,24 +114,25 @@ const ( // union is kept under, oneOf's where both are, "" where there is no such // component. func unionReading(doc *ir.Document, name string) string { - td := typeByName(doc, name) - if td == nil { + typeDef := typeByName(doc, name) + if typeDef == nil { return "" } + union, isUnion := typeDef.(*ir.Union) + if isUnion && slices.ContainsFunc(union.Variants, func(variant ir.Variant) bool { + return strings.HasPrefix(string(variant.Type.Target), "type/composed/") + }) { + // A distributed Union keeps the union it passes over. + return readDistributed + } for _, key := range []string{"openapi:oneOf", "openapi:anyOf"} { - if kept, ok := td.Common().Unmodeled[key]; ok { + if kept, ok := typeDef.Common().Unmodeled[key]; ok { return string(kept.Reason) } } - union, ok := td.(*ir.Union) - if !ok { + if !isUnion { return "" } - if slices.ContainsFunc(union.Variants, func(variant ir.Variant) bool { - return strings.HasPrefix(string(variant.Type.Target), "type/composed/") - }) { - return readDistributed - } return readAlone } @@ -244,12 +259,12 @@ type stolenPosition struct { // spec writes the position's owner and an outside $ref naming it, the reference // declared first or last. Components lower in source order, so the two are the // two orders in which the pointer's node can be reached. -func (p stolenPosition) spec(refFirst bool) string { - outsider := " Outsider: {$ref: '#" + strings.TrimPrefix(string(p.id), "type/anonymous") + "'}\n" +func (stolen stolenPosition) spec(refFirst bool) string { + outsider := " Outsider: {$ref: '#" + strings.TrimPrefix(string(stolen.id), "type/anonymous") + "'}\n" if refFirst { - return openapitest.ComponentSpec(outsider + p.owner) + return openapitest.ComponentSpec(outsider + stolen.owner) } - return openapitest.ComponentSpec(p.owner + outsider) + return openapitest.ComponentSpec(stolen.owner + outsider) } // orderInvariantIR compares two whole IR documents, minus what differs by diff --git a/compilers/openapi/internal/schema/hoist.go b/compilers/openapi/internal/schema/hoist.go index 9edf19987..bf99db310 100644 --- a/compilers/openapi/internal/schema/hoist.go +++ b/compilers/openapi/internal/schema/hoist.go @@ -11,183 +11,292 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) -// finisher writes on a node, in hand, what the frames lowering its position -// keep there beyond its build: its declaration's facts, the keywords it has no -// field for, the families a dispatch passed over, the branches kept beside -// it, the kind-inference mark, a discriminator settled beside a union. -// internNode runs it once, on the node it builds, before the registry stores -// it, so no write looks its node up, and a visit finding the node built writes -// nothing. read is what the build read, and held what an inline principal's -// readers keep after the frames outside (principalKept), nil for none. -type finisher func(td ir.TypeDef, read keySet, held *principalKept) - -// then returns the finisher running f, then finisherValue, either of which may -// be nil. -func (f finisher) then(finisherValue finisher) finisher { - switch { - case f == nil: - return finisherValue - case finisherValue == nil: - return f - default: - return func(td ir.TypeDef, read keySet, held *principalKept) { - f(td, read, held) - finisherValue(td, read, held) - } - } -} - -// run runs f, a nil one finishing nothing. -func (f finisher) run(td ir.TypeDef, read keySet, held *principalKept) { - if f != nil { - f(td, read, held) - } -} - -// finished is what one frame's finisher wrote: whether it ran, and what it -// reported, which the frame joins to its own findings where they always stood, -// so finishing a node in its build moves no finding. -type finished struct { - ran bool - diags []ir.Diagnostic -} - -// on returns the finisher writing with write, recording into f that it ran and -// what it reported. -func (f *finished) on(write func(td ir.TypeDef) []ir.Diagnostic) finisher { - return func(td ir.TypeDef, _ keySet, _ *principalKept) { - f.ran = true - f.diags = append(f.diags, write(td)...) - } +// builtPosition is what one lowering visit made at its position: the ID it +// lowered to and, where this visit built the node there, that node in hand, +// the pending keeps its readers and build add for the frame owning it to +// settle, its builder's name for it (shape), what the build read, whether it +// holds unevaluatedProperties:false as a closure, and whether it is registered +// nowhere yet (registeredWhenFinished). +type builtPosition struct { + node ir.TypeDef // nil: found built, a shared primitive, or a reference + pendingKeeps annotation.PendingKeeps + id ir.TypeID + shape string + read keySet + closesAfterComposition bool + pending bool } -// internNode is the single hoisting entry point: it derives pointer's stable -// TypeID (ids.DocumentIDNamespace.ForPointer) and shared TypeCommon (commonFor) -// once, then interns build's result under that ID, finished by fin. build -// receives the built TypeCommon, so it never re-derives pointer, name or id, -// and returns what it read of the schema it builds from. +// internNode derives pointer's stable TypeID and TypeCommon once, then interns +// build's result under that ID. It returns a builtPosition whose node is set +// only on the visit that built it, so outer frames finish the node as the +// stack unwinds and revisits write nothing. // // A $ref promises the node rather than building it (resolvePointer), so every -// lowering reaching pointer does so in the context its position gives it, and -// the first build, finished, stands for all. -func internNode(loweringContext lowering.Ctx, ts *compile.Types, pointer jsontext.Pointer, build func(common ir.TypeCommon) (ir.TypeDef, keySet), - fin finisher, -) ir.TypeID { +// lowering reaching pointer does so in its own position's context, and the +// first build names all. +func internNode(loweringContext lowering.Ctx, types *compile.Types, pointer jsontext.Pointer, build func(common ir.TypeCommon) (ir.TypeDef, keySet)) builtPosition { id := loweringContext.IDs().ForPointer(pointer) - return ts.Intern(loweringContext.IDs().Coordinate(pointer), id, func() ir.TypeDef { - td, read := build(commonFor(loweringContext, id, pointer)) - if fin != nil && !ir.IsNilTypeDef(td) { - fin(td, read, nil) + var built builtPosition + buildNode := func() ir.TypeDef { + typeDef, read := build(commonFor(loweringContext, id, pointer)) + if !ir.IsNilTypeDef(typeDef) { + built.node = typeDef + built.read = read + built.closesAfterComposition = closedAfterComposition(typeDef) } - return td - }) + return typeDef + } + coordinate := loweringContext.IDs().Coordinate(pointer) + if _, minted := loweringContext.IDs().Minted(pointer); minted { + // A node minted in place of the position's own claims a minted + // namespace (lowering.Minting). + built.id = types.InternMinted(coordinate, id, buildNode) + return built + } + built.id = types.Intern(coordinate, id, buildNode) + return built } // commonFor builds the TypeCommon shared by every hoisted node at pointer. A // top-level component schema is named (source + canonical words); any deeper // inline position is anonymous and carries only the hint its coordinate names -// it by (lowering.NameAt), whichever lowering builds it. +// it by (lowering.NameAt), whichever lowering builds it. A node minted in +// place of the position's own sits at its key, placed and named by the +// pointer the context gives (lowering.Minting). func commonFor(loweringContext lowering.Ctx, id ir.TypeID, pointer jsontext.Pointer) ir.TypeCommon { + key, placedBy, minted := loweringContext.MintedAt(pointer) + if !minted { + key, placedBy = pointer, pointer + } common := ir.TypeCommon{ ID: id, - Provenance: loweringContext.Place().At(pointer), + Provenance: loweringContext.Place().At(key, placedBy), } - switch name, state := ids.ComponentSchema(pointer); state { + switch name, state := ids.ComponentSchema(placedBy); state { case ids.NamedComponent: common.Name = ir.NamingFor(name) case ids.UnnamedComponent: // A component schema keyed "" is a declared top-level component in // OpenAPISpace (Anonymous: false), carrying a minted "empty" hint // (departing from GitHub #405). - common.Name = compile.NamingHint(lowering.NameAt(loweringContext, pointer)) + common.Name = compile.NamingHint(lowering.NameAt(loweringContext, placedBy)) default: common.Anonymous = true - common.Name = compile.NamingHint(lowering.NameAt(loweringContext, pointer)) + common.Name = compile.NamingHint(lowering.NameAt(loweringContext, placedBy)) } return common } -// internOwnNode interns the node the position js, written at pointer, owns -// where it lowered to ref, a use of what ref names, and nothing else built one: -// over an object alone the Model composing it, as the allOf of its $ref alone -// composes it, so no Scalar stands over a model; over any other target, one -// no node answers, or where the use admits null, which a Base does not carry, -// the Scalar alias (docs/compilers/openapi.md#allof-classification). fin -// finishes whichever it builds. -func internOwnNode(loweringContext lowering.Ctx, ts *compile.Types, js *statement.Statement, pointer jsontext.Pointer, ref ir.TypeRef, - fin finisher, -) []ir.Diagnostic { - if kinds, _ := lowersTo(loweringContext, js); ref.Nullable || kinds != kindObject || !stated(js.Schema) { - _, diags := internAlias(loweringContext, ts, js.Schema, pointer, ref, fin, stand{}) - return diags - } - comp := allOfComposition{pointer: pointer, entries: []allOfEntry{{schema: js, pointer: pointer}}} - if js.Ref == nil { - comp = readAllOf(loweringContext, js.Schema, pointer) +// internOwnNode interns the node the position schemaStatement, written at +// pointer, owns where it lowered to ref, a use of what ref names, and nothing +// else built one (buildOwnNode). +func internOwnNode(loweringContext lowering.Ctx, types *compile.Types, schemaStatement *statement.Statement, pointer jsontext.Pointer, ref ir.TypeRef, +) (builtPosition, []ir.Diagnostic) { + var diags []ir.Diagnostic + var pendingKeeps annotation.PendingKeeps + built := internNode(loweringContext, types, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + typeDef, read, buildDiags := buildOwnNode(loweringContext, types, schemaStatement, pointer, ref, common, &pendingKeeps) + diags = buildDiags + return typeDef, read + }) + built.pendingKeeps.AddAll(pendingKeeps) + return built, diags +} + +// buildOwnNode builds of common, on no registry, the node the position +// schemaStatement, written at pointer, owns where it lowered to ref, a use of +// what ref names: over an object alone the Model composing it, as the allOf of +// its $ref alone composes it, so no Scalar sits over a model; over any other +// target, one no node answers, or where the use admits null, which a Base does +// not carry, the Scalar alias (docs/compilers/openapi.md#allof-classification). +func buildOwnNode(loweringContext lowering.Ctx, types *compile.Types, schemaStatement *statement.Statement, pointer jsontext.Pointer, ref ir.TypeRef, + common ir.TypeCommon, pendingKeeps *annotation.PendingKeeps, +) (ir.TypeDef, keySet, []ir.Diagnostic) { + if kinds, _ := lowersTo(loweringContext, schemaStatement); ref.Nullable || kinds != kindObject || !stated(schemaStatement.Schema) { + return ownAlias(loweringContext, schemaStatement.Schema, pointer, ref, common, pendingKeeps) + } + if at, _, expanded := dynamicExpansion(loweringContext, schemaStatement.Schema, pointer); expanded { + return composeExpansion(loweringContext, types, schemaStatement.Schema, pointer, at, common, pendingKeeps) + } + comp := newAllOfComposition(pointer, []allOfEntry{{schema: schemaStatement, pointer: pointer}}) + if schemaStatement.Ref == nil { + comp = readAllOf(loweringContext, schemaStatement.Schema, pointer) } if !slices.ContainsFunc(comp.entries, func(allOfEntryValue allOfEntry) bool { if allOfEntryValue.schema.Ref == nil { return false } - _, resolved := resolveSchemaRef(loweringContext, ts, allOfEntryValue.schema) + _, resolved := resolveSchemaRef(loweringContext, types, allOfEntryValue.schema) return resolved }) { // The reference lowered to the top type, already reported. - _, diags := internAlias(loweringContext, ts, js.Schema, pointer, ref, fin, stand{}) - return diags + return ownAlias(loweringContext, schemaStatement.Schema, pointer, ref, common, pendingKeeps) + } + return composeModel(loweringContext, types, TopLevelDepth, schemaStatement.Schema, pointer, true, common, comp, pendingKeeps) +} + +// composeExpansion builds of common the Model composing the object at, which +// the expanded dynamic reference schema writes at pointer names, as its $ref +// twin is composed: the reference is its one entry, and every keyword beside +// it is read as the twin's are, so no Scalar sits over a model. +func composeExpansion(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, at reftable.DocumentPointer, + common ir.TypeCommon, pendingKeeps *annotation.PendingKeeps, +) (ir.TypeDef, keySet, []ir.Diagnostic) { + conjunctSchema, writtenAt := dynamicRefConjunct(loweringContext, schema, pointer) + written, _ := dynamicRefOf(loweringContext, conjunctSchema, writtenAt) + comp := readAllOf(loweringContext, schema, pointer) + comp.entries = []allOfEntry{{schema: loweringContext.Statements().Expansion(conjunctSchema, written.keyword, written.node, at), pointer: pointer, split: true}} + return composeModel(loweringContext, types, TopLevelDepth, schema, pointer, true, common, comp, pendingKeeps) +} + +// ownAlias builds of common the alias over ref buildOwnNode gives the position +// schema, written at pointer, holding the bounds internAlias's alias holds, +// what no field holds of them added to pendingKeeps (addBuiltPendingKeeps). +func ownAlias(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, ref ir.TypeRef, common ir.TypeCommon, + pendingKeeps *annotation.PendingKeeps, +) (ir.TypeDef, keySet, []ir.Diagnostic) { + cons, kept, reports := aliasBounds(loweringContext, schema, pointer, ref, nodePlacement{}) + return aliasHolding(common, cons, ref), 0, addBuiltPendingKeeps(loweringContext, nodePlacement{}, pendingKeeps, pointer, kept, reports) +} + +// nodeHolds reports whether typeDef, a node a dry run built to sit at a +// position over what the position uses, holds anything beside that use. A node +// of a kind other than a Scalar or a Model is a shape of its own. A position a +// dry run decides hoists only a node holding something. +func nodeHolds(typeDef ir.TypeDef) bool { + if commonHolds(typeDef.Common()) { + return true + } + if scalar, isScalar := typeDef.(*ir.Scalar); isScalar { + return scalar.Constraints != nil || scalar.Encoding != nil + } + model, isModel := typeDef.(*ir.Model) + return !isModel || modelHolds(model) +} + +// commonHolds reports whether common holds anything the source wrote beside +// the node's identity, name and place, an empty set of XML hints among them as +// the IR records one. +func commonHolds(common *ir.TypeCommon) bool { + docs := common.Docs + if docs.Summary != "" || docs.Description != "" || len(docs.Refs) > 0 || len(docs.ExternalDocs) > 0 { + return true + } + return len(common.Namespace) > 0 || len(common.Tags) > 0 || common.Sensitive || common.Access != "" || + common.Deprecation != nil || common.Availability != nil || len(common.WireNameByFormat) > 0 || + common.MediaTypeHint != "" || common.XML != nil || len(common.Examples) > 0 || + common.Instantiation != nil || len(common.Unmodeled) > 0 +} + +// modelHolds reports whether model holds a field of its own beside its Base, +// the use it names. +func modelHolds(model *ir.Model) bool { + return len(model.Properties) > 0 || len(model.Requires) > 0 || len(model.Implements) > 0 || len(model.Mixins) > 0 || + model.AdditionalProperties != nil || model.Additional != ir.AdditionalUnspecified || model.Constraints != nil || + model.Abstract || model.Positional || len(model.ExtensionRanges) > 0 || model.Discriminator != nil || + model.DiscriminatorValue != "" || model.InputOnly +} + +// hoistHolding registers typeDef, the node a dry run built and finished to +// sit at pointer over ref, where it holds anything (nodeHolds), and returns +// what the visit built and the reference the position resolves to. findings, +// what typeDef's build and keepers reported, sit at the position either way, +// but on a revisit, whose first visit reported them. +func hoistHolding(loweringContext lowering.Ctx, types *compile.Types, pointer jsontext.Pointer, ref ir.TypeRef, typeDef ir.TypeDef, + findings []ir.Diagnostic, +) (builtPosition, ir.TypeRef, []ir.Diagnostic) { + if !nodeHolds(typeDef) { + forgetDiscarded(loweringContext, typeDef) + return builtPosition{id: ref.Target}, ref, findings + } + built := internNode(loweringContext, types, pointer, func(ir.TypeCommon) (ir.TypeDef, keySet) { return typeDef, 0 }) + // The home sits where its target sat, so it keeps what the reference + // said of null, the marker naming a heuristic that read it in included. + out := ref + out.Target = built.id + if built.node == nil { + forgetDiscarded(loweringContext, typeDef) + return built, out, nil + } + return built, out, findings +} + +// forgetDiscarded drops what the run recorded of typeDef, a node a dry run +// built and registered nowhere. +func forgetDiscarded(loweringContext lowering.Ctx, typeDef ir.TypeDef) { + if model, isModel := typeDef.(*ir.Model); isModel { + membersOf(loweringContext).forget(model) + modelDiscriminatorsOf(loweringContext).forget(model) } - var diags []ir.Diagnostic - internNode(loweringContext, ts, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { - td, read, modelDiags := composeModel(loweringContext, ts, TopLevelDepth, js.Schema, pointer, true, common, comp) - diags = modelDiags - return td, read - }, fin) - return diags } // internAlias interns a Scalar at pointer whose Base is target, so a component // (or a sibling-carrying schema) whose body lowered to a shared or referenced // target still owns a resolvable node at its own TypeID. It carries the value -// constraints schema writes that the types the position admits take -// (boundKinds), and the exclusive modifier no Constraints field holds, for the -// reason hoistScalar records. fin finishes the alias where this builds it, -// which is where st says. -func internAlias(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, - fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { - var kept ir.Unmodeled - foldedEntries := positionFoldedEntries(loweringContext, schema, pointer, target) - if st.of != nil { - foldedEntries = st.foldedEntries(loweringContext, schema, pointer) - } - cons, diags := ConstraintsOf(loweringContext, &kept, schema, foldedEntries, pointer, st.takes(loweringContext, schema)) - return internAliasHolding(loweringContext, ts, cons, kept, boundsRead(schema, st.takes(loweringContext, schema), nil), st.pointer(pointer), target, fin), diags -} - -// internReferenceAlias is internAlias for the home of a declaration whose -// unread keywords left it no node, which also holds the collection bounds s -// writes. A position that reached a shared node with one written had its alias -// hoisted by the keeping of unread keywords first, so this reads none it also -// keeps. -func internReferenceAlias(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, - fin finisher, -) (ir.TypeID, []ir.Diagnostic) { - var kept ir.Unmodeled - cons, diags := referenceConstraintsOf(loweringContext, &kept, schema, positionFoldedEntries(loweringContext, schema, pointer, target), target, pointer) - return internAliasHolding(loweringContext, ts, cons, kept, referenceReads(loweringContext, schema), pointer, target, fin), diags -} - -// internAliasHolding interns the alias over target, holding the bounds its caller -// read, those of read, and the keyword kept beside them, finished by fin. -func internAliasHolding(loweringContext lowering.Ctx, ts *compile.Types, cons *ir.Constraints, kept ir.Unmodeled, read keySet, - pointer jsontext.Pointer, target ir.TypeRef, fin finisher, -) ir.TypeID { - return internNode(loweringContext, ts, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { - common.Unmodeled = annotation.MergeUnmodeled(common.Unmodeled, kept) - return &ir.Scalar{TypeCommon: common, Base: new(target), Constraints: cons}, read - }, fin) +// constraints schema writes of the kinds its position's homes take +// (aliasHomes), and adds what no Constraints field holds to its pending keeps. +// A revisit builds no node, so no frame settles what it adds: its first visit +// kept and reported it. +func internAlias(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, + placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { + cons, kept, reports := aliasBounds(loweringContext, schema, pointer, target, placement) + built := internAliasHolding(loweringContext, types, cons, placement.pointer(pointer), target) + diags := addBuiltPendingKeeps(loweringContext, placement, &built.pendingKeeps, pointer, kept, reports) + return built, diags +} + +// aliasBounds returns what the alias internAlias hoists holds of the bounds +// schema, written at pointer and placed where placement says, writes, and +// what no field holds of them, each report paired with its key. +func aliasBounds(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, placement nodePlacement, +) (*ir.Constraints, ir.Unmodeled, annotation.KeptReports) { + flattenedEntries := positionFlattenedEntries(loweringContext, schema, pointer, target) + if placement.position != nil { + flattenedEntries = placement.flattenedEntries(loweringContext, schema, pointer) + } + homes := aliasHomes(loweringContext, schema, pointer, target, placement) + cons, kept, reports := boundsKept(loweringContext, nil, schema, flattenedEntries, pointer, homes.value) + text, textReports := heldTextKept(loweringContext, schema, flattenedEntries, pointer, homes) + return cons, annotation.MergeUnmodeled(kept, text), append(reports, textReports...) +} + +// scalarBase is the Base of the Scalar a schema's position builds over target: +// target admitting null where the position's own schema does +// (docs/ir/scalars.md#aliases), so an alias keeping a keyword beside its body, +// or a restriction its format names, says of null what an alias keeping +// nothing does. +func scalarBase(loweringContext lowering.Ctx, schema *statement.Schema, placement nodePlacement, target ir.TypeID) ir.TypeRef { + return nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(placement.positionOrSchema(schema))).ref(loweringContext, target) +} + +// aliasHomes returns the homes of the alias over target hoisted for schema, +// written at pointer and placed where placement says: those homesAt gives the +// position, whose visit built no node. +func aliasHomes(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef, placement nodePlacement) boundHomes { + if placement.position != nil { + return homesAt(loweringContext, placement.position, target, placement.positionPointer) + } + return homesAt(loweringContext, schema, target, pointer) +} + +// internAliasHolding interns the alias over target, holding cons, the bounds +// its caller read. +func internAliasHolding(loweringContext lowering.Ctx, types *compile.Types, cons *ir.Constraints, pointer jsontext.Pointer, target ir.TypeRef) builtPosition { + return internNode(loweringContext, types, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + // No reader asks what an alias read: what its position leaves unread + // is decided before it is hoisted (keepUnreadShared, keepsAtOutcome). + return aliasHolding(common, cons, target), 0 + }) +} + +// aliasHolding returns the alias over target of common, holding cons. +func aliasHolding(common ir.TypeCommon, cons *ir.Constraints, target ir.TypeRef) *ir.Scalar { + return &ir.Scalar{TypeCommon: common, Base: new(target), Constraints: cons} } diff --git a/compilers/openapi/internal/schema/hoist_internal_test.go b/compilers/openapi/internal/schema/hoist_internal_test.go index 83b374428..5c03e9a8d 100644 --- a/compilers/openapi/internal/schema/hoist_internal_test.go +++ b/compilers/openapi/internal/schema/hoist_internal_test.go @@ -63,7 +63,7 @@ func TestCommonFor_StampsTheDeclaringPointer(t *testing.T) { func TestInternNode_DerivesTheIDAndInternsOnce(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.EmptySpec, service.Policy{}) - ts := compile.NewTypes() + types := compile.NewTypes() const at = "/components/schemas/User" var built int @@ -72,57 +72,45 @@ func TestInternNode_DerivesTheIDAndInternsOnce(t *testing.T) { return &ir.Model{TypeCommon: common}, 0 } - first := internNode(serviceContext.Ctx, ts, at, build, nil) - second := internNode(serviceContext.Ctx, ts, at, build, nil) + first := internNode(serviceContext.Ctx, types, at, build) + second := internNode(serviceContext.Ctx, types, at, build) - assert.Equal(t, ids.DocumentIDNamespace{}.ForPointer(at), first, "the ID is derived from the pointer") - assert.Equal(t, first, second, "a second visit returns the interned ID") + assert.Equal(t, ids.DocumentIDNamespace{}.ForPointer(at), first.id, "the ID is derived from the pointer") + assert.Equal(t, first.id, second.id, "a second visit returns the interned ID") assert.Equal(t, 1, built, "and does not build the node again") - td, ok := ts.Node(first) + typeDef, ok := types.Node(first.id) require.True(t, ok, "the node is registered under the ID it returned") - assert.Equal(t, first, td.Common().ID, "and carries that same ID") + assert.Equal(t, first.id, typeDef.Common().ID, "and carries that same ID") } -// TestInternNode_FinishesTheNodeItBuildsOnceBeforeStoringIt pins where a node -// is finished: on the node its build returned, in hand, before the registry -// holds it, and only by the visit building it, so a later visit writes nothing. -func TestInternNode_FinishesTheNodeItBuildsOnceBeforeStoringIt(t *testing.T) { +// TestInternNode_FinishesTheNodeBeforeAnyOtherLoweringReadsIt pins that +// internNode returns the node it built in hand on the first visit, with what +// its build read and whether it closes after composition, and nil on every +// later visit, so frames finish the node as the stack unwinds and a later +// visit writes nothing. That no other lowering reads the node before then is +// held by TestRegistryReads_HeldToTheBaseline (internal/archtest): this +// package's one read of the registry returns an ID, never a node. +func TestInternNode_FinishesTheNodeBeforeAnyOtherLoweringReadsIt(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.EmptySpec, service.Policy{}) - ts := compile.NewTypes() + types := compile.NewTypes() const at = "/components/schemas/User" - var finished []ir.TypeDef - var stored []bool - fin := finisher(func(td ir.TypeDef, _ keySet, _ *principalKept) { - _, held := ts.Node(td.Common().ID) - finished, stored = append(finished, td), append(stored, held) - }) - build := func(common ir.TypeCommon) (ir.TypeDef, keySet) { return &ir.Model{TypeCommon: common}, 0 } - id := internNode(serviceContext.Ctx, ts, at, build, fin) - internNode(serviceContext.Ctx, ts, at, build, fin) - - require.Len(t, finished, 1, "only the visit building the node finishes it") - assert.Equal(t, []bool{false}, stored, "before the registry holds it") - td, ok := ts.Node(id) + build := func(common ir.TypeCommon) (ir.TypeDef, keySet) { + return &ir.Model{TypeCommon: common, Additional: ir.AdditionalClosedAfterComposition}, keyBit("properties") + } + first := internNode(serviceContext.Ctx, types, at, build) + second := internNode(serviceContext.Ctx, types, at, build) + + require.NotNil(t, first.node, "the visit building the node gets it in hand to finish") + assert.Equal(t, keyBit("properties"), first.read) + assert.True(t, first.closesAfterComposition) + assert.Nil(t, second.node, "a revisit finds the node built and writes nothing") + assert.Equal(t, first.id, second.id) + typeDef, ok := types.Node(first.id) require.True(t, ok) - assert.Same(t, td, finished[0], "the node in hand is the node stored") -} - -// TestFinisher_ThenRunsBothInOrder pins the composition the frames of a -// position build their finishing from: each in turn, a nil one skipped. -func TestFinisher_ThenRunsBothInOrder(t *testing.T) { - t.Parallel() - var ran []string - first := finisher(func(ir.TypeDef, keySet, *principalKept) { ran = append(ran, "first") }) - second := finisher(func(ir.TypeDef, keySet, *principalKept) { ran = append(ran, "second") }) - var none finisher - first.then(second)(&ir.Model{}, 0, nil) - none.then(first)(&ir.Model{}, 0, nil) - first.then(none)(&ir.Model{}, 0, nil) - assert.Equal(t, []string{"first", "second", "first", "first"}, ran) - assert.Nil(t, none.then(none), "two nil finishers finish nothing") + assert.Same(t, typeDef, first.node, "the node in hand is the node stored") } // TestUnionVariant_StopsAtTheHopCap pins naming.MaxHops through a compile. @@ -132,7 +120,7 @@ func TestFinisher_ThenRunsBothInOrder(t *testing.T) { // two are named apart, as the cap's doc says. func TestUnionVariant_StopsAtTheHopCap(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name string branches int variant string @@ -140,13 +128,13 @@ func TestUnionVariant_StopsAtTheHopCap(t *testing.T) { {"T within reach", naming.MaxHops - 1, "t"}, {"T one hop past the cap", naming.MaxHops, "variant_0"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() var spec strings.Builder spec.WriteString(" Choice: {oneOf: [{$ref: '#/components/schemas/S0/oneOf/0'}, {type: integer}]}\n") - for i := range tc.branches { + for i := range testCase.branches { next := "#/components/schemas/T" - if i+1 < tc.branches { + if i+1 < testCase.branches { next = "#/components/schemas/S" + strconv.Itoa(i+1) + "/oneOf/0" } spec.WriteString(" S" + strconv.Itoa(i) + ": {oneOf: [{$ref: '" + next + "'}, {type: integer}]}\n") @@ -158,7 +146,7 @@ func TestUnionVariant_StopsAtTheHopCap(t *testing.T) { choice, ok := doc.Types[ids.DocumentIDNamespace{}.ForPointer(ids.Ptr("components", "schemas", "Choice"))].(*ir.Union) require.True(t, ok, "Choice should be a union") variant := choice.Variants[0] - assert.Equal(t, tc.variant, variant.Name.Hint) + assert.Equal(t, testCase.variant, variant.Name.Hint) node, ok := doc.Types[variant.Type.Target] require.True(t, ok, "the variant's target %s is interned", variant.Type.Target) assert.Equal(t, "t", node.Common().Name.Hint, "the node the variant holds reaches T either way") @@ -166,14 +154,14 @@ func TestUnionVariant_StopsAtTheHopCap(t *testing.T) { } } -// TestMarkKindInferred_JoinsWhatTheNodeNames pins that the kind-inference -// marker joins what a node's provenance already names, once however often it +// TestMarkKindInferred_CombinesWhatTheNodeNames pins that the kind-inference +// marker adds to what a node's provenance already names, once however often it // is written. -func TestMarkKindInferred_JoinsWhatTheNodeNames(t *testing.T) { +func TestMarkKindInferred_CombinesWhatTheNodeNames(t *testing.T) { t.Parallel() node := &ir.Model{Provenance: ir.Provenance{Inferred: lowering.NullableInferenceHeuristic}} - markKindInferred(node, 0, nil) - markKindInferred(node, 0, nil) + markKindInferred(node) + markKindInferred(node) assert.Equal(t, ir.JoinInferred(lowering.NullableInferenceHeuristic, lowering.KindInferenceHeuristic), node.Provenance.Inferred) } diff --git a/compilers/openapi/internal/schema/hoist_test.go b/compilers/openapi/internal/schema/hoist_test.go index 538bdade4..fdb3d87ab 100644 --- a/compilers/openapi/internal/schema/hoist_test.go +++ b/compilers/openapi/internal/schema/hoist_test.go @@ -169,7 +169,7 @@ func TestUntitledProbe_WritesNoTitle(t *testing.T) { // naming.TestAt_NamesASchemaByItsStructure every spelling the namer gives. func TestInlinePosition_HintIsTheSameInBothOrders(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name string owner string id ir.TypeID @@ -248,22 +248,22 @@ func TestInlinePosition_HintIsTheSameInBothOrders(t *testing.T) { "type/anonymous/components/schemas/A/oneOf/0/items/items", "variant_0_item_item", "type/anonymous/components/schemas/A/oneOf/0/items"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - refAt := tc.refAt + refAt := testCase.refAt if refAt == "" { - refAt = tc.id + refAt = testCase.id } - pos := stolenPosition{name: tc.name, owner: tc.owner, id: refAt} + pos := stolenPosition{name: testCase.name, owner: testCase.owner, id: refAt} for _, order := range []struct { name string refFirst bool }{{"owner declared first", false}, {"reference declared first", true}} { doc, diags := parseFull(t, pos.spec(order.refFirst)) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types[tc.id] - require.True(t, ok, "%s: the position owns a node at %s", order.name, tc.id) - assert.Equal(t, tc.hint, td.Common().Name.Hint, order.name) + typeDef, ok := doc.Types[testCase.id] + require.True(t, ok, "%s: the position owns a node at %s", order.name, testCase.id) + assert.Equal(t, testCase.hint, typeDef.Common().Name.Hint, order.name) } }) } @@ -330,7 +330,7 @@ func TestInlinePosition_UnderPathsIsNamedByItsDeclaration(t *testing.T) { func TestPureRefPosition_IsNamedByItsDeclarationInBothOrders(t *testing.T) { t.Parallel() const tDecl = " T: {type: object, properties: {t: {type: string}}}\n" - for _, tc := range []struct { + for _, testCase := range []struct { name string owner string id ir.TypeID @@ -352,18 +352,18 @@ func TestPureRefPosition_IsNamedByItsDeclarationInBothOrders(t *testing.T) { {"a union branch", " A: {oneOf: [{$ref: '#/components/schemas/T'}, {type: integer}]}\n" + tDecl, "type/anonymous/components/schemas/A/oneOf/0", "t"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - pos := stolenPosition{name: tc.name, owner: tc.owner, id: tc.id} + pos := stolenPosition{name: testCase.name, owner: testCase.owner, id: testCase.id} for _, order := range []struct { name string refFirst bool }{{"owner declared first", false}, {"reference declared first", true}} { doc, diags := parseFull(t, pos.spec(order.refFirst)) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types[tc.id] - require.True(t, ok, "%s: the position owns a node at %s", order.name, tc.id) - assert.Equal(t, tc.hint, td.Common().Name.Hint, order.name) + typeDef, ok := doc.Types[testCase.id] + require.True(t, ok, "%s: the position owns a node at %s", order.name, testCase.id) + assert.Equal(t, testCase.hint, typeDef.Common().Name.Hint, order.name) } }) } @@ -419,7 +419,7 @@ func TestPureRefPosition_UnderPathsIsNamedByItsDeclaration(t *testing.T) { // hoists to own what it wrote keeps the value constraints written beside it: // beside an applicator its lowered node has no home for, as an untyped one // with the kind-inference policy off. The alias owns the pointer, so -// hoistDeclarationHome hoists nothing else that could carry them. +// homeDeclaration hoists nothing else that could carry them. func TestAlias_CarriesTheBoundsWrittenBesideIt(t *testing.T) { t.Parallel() one, two := ir.BigVal("1"), ir.BigVal("2") diff --git a/compilers/openapi/internal/schema/hoistholding_internal_test.go b/compilers/openapi/internal/schema/hoistholding_internal_test.go new file mode 100644 index 000000000..e2ff02b9a --- /dev/null +++ b/compilers/openapi/internal/schema/hoistholding_internal_test.go @@ -0,0 +1,48 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestHoistHolding_AModelRegisteredNowhereLeavesTheMembers holds a Model a dry +// run built to the members record (members.forget): one holding nothing, and +// one a revisit built where a node sits already, are noted no longer, while +// the node registered keeps its own record. +func TestHoistHolding_AModelRegisteredNowhereLeavesTheMembers(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " T: {type: object}\n")) + pointer := jsontext.Pointer("/components/schemas/S/items") + id := lowerer.Ctx.IDs().ForPointer(pointer) + use := ir.TypeRef{Target: "type/openapi/components/schemas/T"} + record := membersOf(lowerer.Ctx) + scratch := func(description string) *ir.Model { + model := &ir.Model{ID: id, Docs: ir.Docs{Description: description}} + record.note(modelFields{loweringContext: lowerer.Ctx, types: lowerer.Types, model: model, pointer: pointer}) + return model + } + + built, ref, _ := hoistHolding(lowerer.Ctx, lowerer.Types, pointer, use, scratch(""), nil) + assert.Nil(t, built.node) + assert.Equal(t, use, ref) + assert.NotContains(t, record.byID, id, "a model holding nothing is noted no longer") + + held := scratch("d") + built, _, _ = hoistHolding(lowerer.Ctx, lowerer.Types, pointer, use, held, nil) + require.Equal(t, ir.TypeDef(held), built.node) + findings := []ir.Diagnostic{{Code: "x"}} + built, ref, findings = hoistHolding(lowerer.Ctx, lowerer.Types, pointer, use, scratch("d"), findings) + assert.Nil(t, built.node) + assert.Equal(t, id, ref.Target) + assert.Empty(t, findings, "a revisit reports nothing") + assert.Same(t, held, record.byID[id].model, "the node registered keeps its record") +} diff --git a/compilers/openapi/internal/schema/inference.go b/compilers/openapi/internal/schema/inference.go index 125d39e52..16d25d451 100644 --- a/compilers/openapi/internal/schema/inference.go +++ b/compilers/openapi/internal/schema/inference.go @@ -21,12 +21,12 @@ import ( // policy's where it read any, off schema or a conjunct, the document's // otherwise. func untypedKinds(loweringContext lowering.Ctx, schema *statement.Schema) (kindSet, bool) { - claims := shapeKinds(schema) - if claims == 0 || !stated(schema) { + inferredKinds := shapeKinds(schema) + if inferredKinds == 0 || !stated(schema) { return 0, false } kinds, inferred := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) - if kinds&^claims != 0 { + if kinds&^inferredKinds != 0 { return 0, false } return kinds, inferred @@ -37,45 +37,46 @@ func untypedKinds(loweringContext lowering.Ctx, schema *statement.Schema) (kindS // whichever order the keywords are written in. var inferredKinds = []statement.JSONSchemaTypeName{statement.KindObject, statement.KindArray} -// lowerTypeList lowers s, at pointer, by the several types typingValue names, -// one variant per type, each from this same schema (lowerUnion): the types it -// lists, an object and an array its shape keywords speak of, or the kinds an -// allOf electing no entry admits (typingOf). The homes are the variants', not -// the Union's, and a type list is what built them, so its `type` is read. Where -// the policy read the kinds, the union and each variant are marked, as each -// variant's kind was read off the keywords too. The union stands where st says. -func lowerTypeList(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, typingValue typing, - fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { - var mark finisher - if typingValue.inferred { - mark = markKindInferred - } +// lowerTypeList lowers schema, at pointer, by the several types typingValue +// names, one variant per type, each from this same schema +// (lowerTypeArrayUnion): the types it lists, an object and an array its shape +// keywords speak of, or the kinds an allOf choosing no entry admits (typingOf). +// The homes are the variants', not the Union's, and a type list is what built +// them, so its `type` is read. Where the policy read the kinds, the union and +// each variant are marked, as each variant's kind was read off the keywords +// too. The union is placed where placement says. +func lowerTypeList(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, typingValue typing, + placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { var read keySet if typingValue.by == byType { read = keyBit("type") } - var kept finished - id, diags := lowerUnion(loweringContext, ts, depth, schema, pointer, typeArray{types: typingValue.types, mark: mark}, - mark.then(keepUnreadAcross(loweringContext, ts, schema, nodeShape(ir.KindUnion), read, pointer, st, &kept, fin)), st) - return id, append(diags, kept.diags...) + built, diags := lowerTypeArrayUnion(loweringContext, types, depth, schema, pointer, typeArray{types: typingValue.types, inferred: typingValue.inferred}, placement) + if built.node != nil { + if typingValue.inferred { + markKindInferred(built.node) + } + diags = append(diags, keepUnreadAcross(loweringContext, schema, nodeShape(ir.KindUnion), read, pointer, placement, &built)...) + } + return built, diags } -// claimedKinds returns the kinds c's kind-inference policy reads off the -// keywords s writes that give a type to the instances they apply to, a -// member's, an element's or a value's (siblingKeyword.infers), and none where -// the policy is off. The run's admission reads it as the kinds a statement -// declaring none lowers to (readOne), which lowerTyping lowers by +// kindsInferredFromShape returns the kinds the kind-inference policy reads off +// the keywords schema writes that give a type to the instances they apply to, +// a member's, an element's or a value's (siblingKeyword.infers), and none +// where the policy is off. The run's admission reads it as the kinds a +// statement declaring none lowers to (readOne), which lowerTyping lowers by // (untypedKinds). -func claimedKinds(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { +func kindsInferredFromShape(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { if !loweringContext.KindInference.Honours() { return 0 } var out kindSet for _, set := range [...][]siblingKeyword{shapeKeywords, narrowingKeywords} { for _, siblingKeyword := range set { - if siblingKeyword.infers != nil && siblingKeyword.claims&^out != 0 && siblingKeyword.infers(loweringContext.Statements(), schema) { - out |= siblingKeyword.claims + if siblingKeyword.infers != nil && siblingKeyword.inferredKinds&^out != 0 && siblingKeyword.infers(loweringContext.Statements(), schema) { + out |= siblingKeyword.inferredKinds } } } @@ -95,19 +96,19 @@ func shapeKinds(schema *statement.Schema) kindSet { } for _, set := range [...][]siblingKeyword{shapeKeywords, narrowingKeywords} { for _, siblingKeyword := range set { - if siblingKeyword.claims&^out != 0 && siblingKeyword.writes(schema) { - out |= siblingKeyword.claims + if siblingKeyword.inferredKinds&^out != 0 && siblingKeyword.writes(schema) { + out |= siblingKeyword.inferredKinds } } } return out } -// markKindInferred names the kind-inference policy in the provenance of td, -// in hand, the node a position owns whose kind lowerTyping read off its shape -// keywords (docs/compilers/openapi.md#policies). -func markKindInferred(td ir.TypeDef, _ keySet, _ *principalKept) { - common := td.Common() +// markKindInferred names the kind-inference policy in the provenance of +// typeDef, in hand, the node a position owns whose kind lowerTyping read off +// its shape keywords (docs/compilers/openapi.md#policies). +func markKindInferred(typeDef ir.TypeDef) { + common := typeDef.Common() common.Provenance.Inferred = ir.JoinInferred(common.Provenance.Inferred, lowering.KindInferenceHeuristic) } @@ -115,13 +116,13 @@ func markKindInferred(td ir.TypeDef, _ keySet, _ *principalKept) { // leaves something for the position to carry, with how a schema writes it, the // kind of instance it speaks of where it applies to one kind alone, and, for a // keyword giving the type of a member, an element or a value, where it does, -// which a schema naming no kind is read as (claimedKinds). infers is nil for a -// keyword that never does. +// which a schema naming no kind is read as (kindsInferredFromShape). infers is +// nil for a keyword that never does. type siblingKeyword struct { - key string - writes func(*statement.Schema) bool - claims kindSet - infers func(*statement.MemoizingSchemaReader, *statement.Schema) bool + key string + writes func(*statement.Schema) bool + inferredKinds kindSet + infers func(*statement.MemoizingSchemaReader, *statement.Schema) bool } // shapeKeywords are the keywords that declare data shape — a type, a property @@ -172,11 +173,12 @@ var narrowingKeywords = []siblingKeyword{ // typesInstances reports whether sub, the schema an `items` or an // `additionalProperties` writes, gives a type to the instances it applies to: a -// schema object writing a keyword. `true` and `{}` state nothing, as leaving -// the keyword out does (JSON Schema Core 2020-12 §10.3.1.2, §10.3.2.3), and -// `false`, which admits no instance, types none either. +// schema object writing a keyword past identifier and meta keywords. `true`, +// `{}` and a schema writing only those state nothing, as leaving the keyword +// out does (JSON Schema Core 2020-12 §10.3.1.2, §10.3.2.3), and `false`, which +// admits no instance, types none either. func typesInstances(memoizingSchemaReader *statement.MemoizingSchemaReader, sub statement.Subschema) bool { - return sub.SchemaValueForm() == statement.Stated && len(memoizingSchemaReader.Subschema(sub).Keys) > 0 + return sub.SchemaValueForm() == statement.Stated && !memoizingSchemaReader.Subschema(sub).WritesOnlyIdentifierAndMetaKeywords() } // siblingKeywords returns the keywords of shapeKeywords and narrowingKeywords @@ -194,9 +196,11 @@ func siblingKeywords(schema *statement.Schema) []string { } // writesSiblingKeyword reports whether siblingKeywords(schema) holds any -// keyword, without building the list, as most schemas a reader asks of write -// one. -func writesSiblingKeyword(schema *statement.Schema) bool { - writes := func(siblingKeywordValue siblingKeyword) bool { return siblingKeywordValue.writes(schema) } +// keyword but those but names, without building the list, as most schemas a +// reader asks of write one. +func writesSiblingKeyword(schema *statement.Schema, but ...string) bool { + writes := func(siblingKeywordValue siblingKeyword) bool { + return !slices.Contains(but, siblingKeywordValue.key) && siblingKeywordValue.writes(schema) + } return slices.ContainsFunc(shapeKeywords, writes) || slices.ContainsFunc(narrowingKeywords, writes) } diff --git a/compilers/openapi/internal/schema/preserve.go b/compilers/openapi/internal/schema/keep.go similarity index 56% rename from compilers/openapi/internal/schema/preserve.go rename to compilers/openapi/internal/schema/keep.go index 53cf0be6c..be1ce8e8f 100644 --- a/compilers/openapi/internal/schema/preserve.go +++ b/compilers/openapi/internal/schema/keep.go @@ -21,85 +21,111 @@ import ( // position it is located at, the conversion of its value, and the report when // it cannot be kept. This package calls annotation for that directly, with // c.Place(). What it decides is what a position keeps and why: which -// keywords, under which reason, announced how. PreserveUnknownKeywords is one +// keywords, under which reason, announced how. KeepUnknownKeywords is one // such decision, reading the dialect a schema is read in. A preservation // function that decides nothing and only keys, locates or converts belongs in // annotation, or the same call gains a second spelling. // -// ReadAnnotations, preserveNode, preserveSchemaKeyword, and -// preserveValidationOnlyKeyword are deliberate departures from calling +// ReadAnnotations, keepNode, keepSchemaKeyword, and +// keepValidationOnlyKeyword are deliberate departures from calling // annotation directly: each feeds failed conversions into RecordDiscardedSite // on lowering.Ctx so post-settlement pruning removes landings beneath // unpreservable constructs without inspecting diagnostics by code or pulling -// lowering.Ctx down into annotation. +// lowering.Ctx down into annotation, and keeps whole each discriminator within +// what it keeps (KeepDiscriminatorsWithin), whose values are references. -// ReadAnnotations reads site's annotations at pointer and records any -// unpreservable construct provenances as discarded sites for pruning. -func ReadAnnotations(loweringContext lowering.Ctx, site annotation.SchemaPositionAnnotationSources, pointer jsontext.Pointer) (annotation.Set, []ir.Diagnostic) { - set, diags := annotation.Read(site, pointer, loweringContext.Place()) - recordDiscardedSites(loweringContext, set.Unpreserved) - return set, diags +// ReadAnnotations reads site's annotations at pointer, records any +// unpreservable construct provenances as discarded sites for pruning, and keeps +// whole each discriminator a validation-only entry of the site or a flattened +// entry holds. +func ReadAnnotations(loweringContext lowering.Ctx, site annotation.SchemaPositionAnnotationSources, pointer jsontext.Pointer) (annotation.Set, annotation.KeptReports) { + set, reports := annotation.Read(site, pointer, loweringContext.Place()) + recordDiscardedSites(loweringContext, set.Unkept) + reports = append(reports, keepValidationOnlyDiscriminators(loweringContext, set.Unmodeled)...) + for _, flattenedEntry := range set.FlattenedEntries { + reports = append(reports, keepValidationOnlyDiscriminators(loweringContext, flattenedEntry.Unmodeled)...) + } + return set, reports } -// preserveNode converts node into unmodeled at at and records at as a +// keepNode converts node into unmodeled at at and records at as a // discarded site when conversion fails. -func preserveNode(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, key string, node *yaml.Node, +func keepNode(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, key string, node *yaml.Node, reason ir.UnmodeledReason, at jsontext.Pointer, ) (bool, []ir.Diagnostic) { prov := loweringContext.Place().At(at) - kept, diags := annotation.PreserveNodeInto(unmodeled, key, node, reason, prov) - if !kept && len(diags) > 0 { - RecordDiscardedSite(loweringContext, prov) + kept, diags := annotation.KeepNodeInto(unmodeled, key, node, reason, prov) + if !kept { + if len(diags) > 0 { + RecordDiscardedSite(loweringContext, prov) + } + return false, diags } - return kept, diags + return true, append(diags, KeepDiscriminatorsWithin(loweringContext, unmodeled, at)...) } -// preserveSchemaKeyword keeps keyword of schema at pointer in unmodeled and +// keepSchemaKeyword keeps keyword of schema at pointer in unmodeled and // records the keyword's provenance as a discarded site when conversion fails. -func preserveSchemaKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, +func keepSchemaKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, reason ir.UnmodeledReason, pointer jsontext.Pointer, ) (bool, []ir.Diagnostic) { - kept, diags := annotation.PreserveSchemaKeyword(unmodeled, schema, keyword, reason, pointer, loweringContext.Place()) - if !kept && len(diags) > 0 { - RecordDiscardedSite(loweringContext, loweringContext.Place().At(pointer+ids.Ptr(keyword))) + kept, diags := annotation.KeepSchemaKeyword(unmodeled, schema, keyword, reason, pointer, loweringContext.Place()) + if !kept { + if len(diags) > 0 { + RecordDiscardedSite(loweringContext, loweringContext.Place().At(pointer+ids.Ptr(keyword))) + } + return false, diags } - return kept, diags + return true, append(diags, KeepDiscriminatorsWithin(loweringContext, unmodeled, pointer+ids.Ptr(keyword))...) } -// preserveValidationOnlyKeyword keeps a validation-only keyword of schema at +// keepValidationOnlyKeyword keeps a validation-only keyword of schema at // pointer in unmodeled and records the keyword's provenance as a discarded // site when conversion fails. -func preserveValidationOnlyKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, +func keepValidationOnlyKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, pointer jsontext.Pointer, ) []ir.Diagnostic { - kept, diags := annotation.PreserveValidationOnlyKeyword(unmodeled, schema, keyword, pointer, loweringContext.Place()) - if !kept && len(diags) > 0 { - RecordDiscardedSite(loweringContext, loweringContext.Place().At(pointer+ids.Ptr(keyword))) + kept, diags := annotation.KeepValidationOnlyKeyword(unmodeled, schema, keyword, pointer, loweringContext.Place()) + if !kept { + if len(diags) > 0 { + RecordDiscardedSite(loweringContext, loweringContext.Place().At(pointer+ids.Ptr(keyword))) + } + return diags } - return diags + return append(diags, KeepDiscriminatorsWithin(loweringContext, unmodeled, pointer+ids.Ptr(keyword))...) } -// PreserveUnknownKeywords records every keyword schema writes that no field of +// KeepUnknownKeywords records every keyword schema writes that no field of // the schema model names, or that the model names and the dialect does not -// define (undefinedKeywords), and no reader above it already kept (GitHub #297). +// define (undefinedKeywords), and no reader above it already kept (GitHub +// #297). // // It is the last thing an attachment does, as annotation.UnknownKeywordsIn -// requires, so it is called here rather than inside annotation.Read: a -// dynamic reference, which the model names no field for, is decided by +// requires, so it is called here rather than inside annotation.Read: a dynamic +// reference, which the model names no field for, is decided by // recordUnexpandedDynamicRef, run after Read; a draft's `dependencies` is -// Read's (annotation.Dialect), and `additionalItems` beside a list the -// tuple's, its rest. td is the node the position lowered to, nil for none. -func PreserveUnknownKeywords(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, td ir.TypeDef, +// Read's (annotation.Dialect), and `additionalItems` beside a list the tuple's, +// its rest. typeDef is the node the position lowered to, nil for none. +func KeepUnknownKeywords(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, typeDef ir.TypeDef, left ...string, -) []ir.Diagnostic { - unpreserved, diags := annotation.UnknownKeywordsIn(unmodeled, schema, pointer, loweringContext.Place(), slices.Concat(unknownTaken(loweringContext, schema, pointer), left)...) +) annotation.KeptReports { + unpreserved, reports := annotation.UnknownKeywordsIn(unmodeled, schema, pointer, loweringContext.Place(), slices.Concat(unknownTaken(loweringContext, schema, pointer), left)...) recordDiscardedSites(loweringContext, unpreserved) - return append(diags, annotation.UndefinedKeywordsIn(unmodeled, schema, undefinedKeywords(loweringContext, schema), pointer, loweringContext.Place())...) + return append(reports, annotation.UndefinedKeywordsIn(unmodeled, schema, undefinedKeywords(loweringContext, schema), pointer, loweringContext.Place())...) +} + +// keepsUnknownKeywords reports whether KeepUnknownKeywords keeps a keyword +// schema writes at pointer. +func keepsUnknownKeywords(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) bool { + if len(undefinedKeywords(loweringContext, schema)) > 0 { + return true + } + return annotation.WritesUnknownKeyword(schema, unknownTaken(loweringContext, schema, pointer)...) } // unknownTaken returns the keys schema, written at pointer, writes that the // schema model names no field for and a reader other than -// PreserveUnknownKeywords reads, by the dialect it is read in. +// KeepUnknownKeywords reads, by the dialect it is read in. func unknownTaken(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []string { var taken []string if _, listed := listedItems(schema); listed { @@ -112,7 +138,7 @@ func unknownTaken(loweringContext lowering.Ctx, schema *statement.Schema, pointe } if rules.Defines("$recursiveRef") { // 2019-09's dynamic reference, which recordUnexpandedDynamicRef decides - // where no $dynamicRef stands beside it, and the anchor it reads, which + // where no $dynamicRef sits beside it, and the anchor it reads, which // the binder consumes as a $dynamicAnchor. taken = append(taken, "$recursiveAnchor") if !hasKey(schema, "$dynamicRef") { @@ -123,7 +149,7 @@ func unknownTaken(loweringContext lowering.Ctx, schema *statement.Schema, pointe } // writesUnknown reports whether key, a key schema writes at pointer, is one -// PreserveUnknownKeywords keeps there. +// KeepUnknownKeywords keeps there. func writesUnknown(loweringContext lowering.Ctx, schema *statement.Schema, key string, pointer jsontext.Pointer) bool { if slices.Contains(undefinedKeywords(loweringContext, schema), key) { return true diff --git a/compilers/openapi/internal/schema/keeping_internal_test.go b/compilers/openapi/internal/schema/keeping_internal_test.go new file mode 100644 index 000000000..c891ff736 --- /dev/null +++ b/compilers/openapi/internal/schema/keeping_internal_test.go @@ -0,0 +1,122 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// componentOf returns the fixture over a document declaring components, the +// statement of the component schema named name, and its pointer. +func componentOf(t *testing.T, components, name string) (*Lowerer, *statement.Statement, jsontext.Pointer) { + t.Helper() + lowerer, diags := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", components)) + openapitest.RequireNoErrorDiags(t, diags) + decl, ok := lowerer.Doc.Components.Schemas.Get(name) + require.True(t, ok, name) + return lowerer, lowerer.Ctx.Statements().Of(decl), jsontext.Pointer("/components/schemas/" + name) +} + +// TestAddPendingKeeping_AddsOnlyAKeyTheSchemaWrites pins a keeping listing keys +// its schema does not write, an exclusive flag among them, whose bound a +// pending keep reads off what is written: nothing is added for them, the keys +// written are. +func TestAddPendingKeeping_AddsOnlyAKeyTheSchemaWrites(t *testing.T) { + t.Parallel() + lowerer, schema, at := lowererDeclaringS(t) + var pendingKeeps annotation.PendingKeeps + keepingValue := keeping{keys: []string{"exclusiveMinimum", "maxLength", "readOnly"}, reason: ir.ReasonDegradedLowering, + keep: func(*ir.Unmodeled, []string) []ir.Diagnostic { return nil }} + addPendingKeeping(lowerer.Ctx, &pendingKeeps, positionSite(at), schema, keepingValue) + assert.Equal(t, []string{"readOnly"}, pendingKeeps.Keywords(), "what S does not write is no pending keep") +} + +// TestConjunctSiteAt_NamesTheEntryWritingAKeptValue pins who writes what a +// principal's build keeps, by where it is written: the principal, an entry +// beside it, or the position. +func TestConjunctSiteAt_NamesTheEntryWritingAKeptValue(t *testing.T) { + t.Parallel() + lowerer, schemaStatement, at := componentOf(t, " S: {allOf: [{type: string}, {description: d}], description: e}\n", "S") + comp := allOfEntries(lowerer.Ctx, schemaStatement.Schema, at) + principal := at + "/allOf/0" + + beside := conjunctSiteAt(comp, at+"/allOf/1/description", principal) + assert.Equal(t, annotation.WritesBeside, beside.Role) + assert.Equal(t, at+"/allOf/1", beside.Pointer) + lowered := conjunctSiteAt(comp, principal+"/type", principal) + assert.Equal(t, annotation.WritesLoweredFrom, lowered.Role) + assert.Equal(t, principal, lowered.Pointer) + assert.Equal(t, positionSite(at), conjunctSiteAt(comp, at+"/description", principal)) +} + +// TestKeptAllOfEntrySite_ReportsWhatItKeepsApartByItsConjuncts pins the report a kept +// entry draws of the keywords its key holds apart: who writes them otherwise, +// at the entry. +func TestKeptAllOfEntrySite_ReportsWhatItKeepsApartByItsConjuncts(t *testing.T) { + t.Parallel() + lowerer, schemaStatement, at := componentOf(t, " S: {allOf: [{type: string}, {x-k: 1}], x-k: 2}\n", "S") + comp := allOfEntries(lowerer.Ctx, schemaStatement.Schema, at) + entry := comp.entries[1] + held := keptEntrySite(lowerer.Ctx, comp, keptEntry{entry: entry}, entrySiteAt(comp, entry.pointer, annotation.WritesBeside), + func(keptEntry) ir.Diagnostic { return ir.Diagnostic{} }) + require.NotNil(t, held.ReportApart) + + diags := held.ReportApart([]string{"x-k"}) + require.Len(t, diags, 1) + assert.Equal(t, entry.pointer, diags[0].Provenance.Pointer) + assert.Contains(t, diags[0].Message, "the keywords beside this allOf write x-k otherwise than this inline entry") +} + +// TestKeepRefSiteKeywords_AnEntryKeepsWhatItsCarrierKeeps pins an entry a +// carrier's position keeps, writing a keyword the carrier has a keeper for +// otherwise than the position: the carrier's keeper keeps it, at the entry. +func TestKeepRefSiteKeywords_AnEntryKeepsWhatItsCarrierKeeps(t *testing.T) { + t.Parallel() + lowerer, schemaStatement, at := componentOf(t, " Str: {type: string}\n"+ + " P: {allOf: [{$ref: '#/components/schemas/Str'}, {xml: {name: a}}], xml: {name: b}}\n", "P") + target := ir.TypeRef{Target: lowerer.Ctx.IDs().ForPointer("/components/schemas/Str")} + var keptAt []jsontext.Pointer + keeps := CarrierKeywordKeeps{"xml": func(_ *ir.Unmodeled, _ *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + keptAt = append(keptAt, pointer) + return nil + }} + var pendingKeeps annotation.PendingKeeps + KeepRefSiteKeywords(lowerer.Ctx, lowerer.Types, &pendingKeeps, schemaStatement, target, at, keeps) + assert.Equal(t, []jsontext.Pointer{at + "/allOf/1"}, keptAt, "the entry's xml is the carrier's to keep") +} + +// TestKeepValidationOnlyKeyword_RecordsWhatItCannotKeep pins a +// validation-only keyword no JSON holds: refused, kept nowhere, and its site +// recorded as discarded, so what it names is pruned. A keeping the node's +// pending keeps settle is refused by the pending keeps first, so a direct +// keeper is held here. +func TestKeepValidationOnlyKeyword_RecordsWhatItCannotKeep(t *testing.T) { + t.Parallel() + lowerer, schemaStatement, at := componentOf(t, " S: {type: string, not: {foo: .nan}}\n", "S") + var unmodeled ir.Unmodeled + diags := keepValidationOnlyKeyword(lowerer.Ctx, &unmodeled, schemaStatement.Schema, "not", at) + require.Len(t, diags, 1) + assert.Equal(t, at+"/not", diags[0].Provenance.Pointer) + assert.Empty(t, unmodeled) + assert.Equal(t, []ir.Provenance{{Pointer: at + "/not"}}, DiscardedSites(lowerer.Ctx)) +} + +// TestLoweredTypeKinds_ReadsAWordAsItsScalarLowers pins the kinds a type word +// admits to what a schema writing it alone lowers to: a word no dialect +// defines admits the string its scalar is over (baseForType). +func TestLoweredTypeKinds_ReadsAWordAsItsScalarLowers(t *testing.T) { + t.Parallel() + assert.Equal(t, ir.PrimitiveString, baseForType("file")) + assert.Equal(t, kindString, kindsOfTypeNameOrString("file")) + assert.Equal(t, kindObject, kindsOfTypeNameOrString(statement.KindObject)) +} diff --git a/compilers/openapi/internal/schema/keeping_refusal_test.go b/compilers/openapi/internal/schema/keeping_refusal_test.go new file mode 100644 index 000000000..ff47267fb --- /dev/null +++ b/compilers/openapi/internal/schema/keeping_refusal_test.go @@ -0,0 +1,119 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestKeeping_AValueNoJSONHoldsIsRefusedWhereItIsWritten holds the keepings of +// a construct no field holds to the pairing GitHub #144 asks for, with a value +// no JSON holds under a key no dialect defines, since an extension's is left +// out instead: the construct is refused where it is written, and of the claims +// its twin without that value draws, the one for the construct alone is +// missing. +func TestKeeping_AValueNoJSONHoldsIsRefusedWhereItIsWritten(t *testing.T) { + t.Parallel() + const bad = ", foo: " + unpreservableValue + for name, testCase := range map[string]struct{ spec, bad, at string }{ + "a union kept beside the one lowered": {openapitest.ComponentSpec( + " S: {oneOf: [{type: string}, {type: integer}], anyOf: [{type: number" + bad + "}]}\n"), bad, "/components/schemas/S/anyOf"}, + "a branch the variant model does not compose": {openapitest.ComponentSpec( + " A: {type: object, properties: {a: {type: string}}}\n" + + " Combo: {type: object, properties: {kind: {type: string}}, " + + "oneOf: [{$ref: '#/components/schemas/A'}, {anyOf: [{type: object}, {type: string}]" + bad + "}]}\n"), + bad, "/components/schemas/Combo/oneOf/1"}, + "a discriminator kept whole beside its union": {openapitest.ComponentSpec(cat + dog + + " Holder:\n type: object\n properties:\n pet:\n type: object\n" + + " properties: {name: {type: string}}\n" + + " discriminator: {propertyName: kind, mapping: {cat: '#/components/schemas/Cat'}" + bad + "}\n" + + " oneOf: [{required: [kind]}, {required: [x]}]\n"), bad, anonymousPetPointer + "/discriminator"}, + "an entry's union": {openapitest.ComponentSpecVer("3.1.0", " T: {type: string}\n"+ + " S: {allOf: [{$ref: '#/components/schemas/T'}, {enum: [a, b], oneOf: [{type: string, pattern: '^a'"+bad+"}, {type: integer}]}]}\n"), + bad, "/components/schemas/S/allOf/1/oneOf"}, + "a discriminator beside a union's own": {openapitest.ComponentSpecVer("3.1.0", + " Tag: {allOf: [{oneOf: [{type: string}, {type: integer}], discriminator: {propertyName: a}}], "+ + "discriminator: {propertyName: b, mapping: {x: "+unpreservableValue+"}}}\n"), + ", mapping: {x: " + unpreservableValue + "}", "/components/schemas/Tag/discriminator"}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + require.Equal(t, 1, strings.Count(testCase.spec, testCase.bad), "the value is written once") + _, diags := parseFull(t, testCase.spec) + _, equivalentDiags := parseFull(t, strings.ReplaceAll(testCase.spec, testCase.bad, "")) + + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, testCase.at), "refused where written: %+v", diags) + claims, twinClaims := openapitest.MessagesSayingKept(diags), openapitest.MessagesSayingKept(equivalentDiags) + for _, claim := range claims { + assert.Contains(t, twinClaims, claim, "what is claimed is claimed of the twin too") + } + assert.Len(t, claims, len(twinClaims)-1, "the twin's claim of the construct is the one not drawn: %v", twinClaims) + }) + } +} + +// TestKeeping_ABooleanFlagIsKeptWithItsBound holds the text bounds an inline +// principal carrying a number as text keeps, at 3.0, beside a bound the +// position writes otherwise: a boolean exclusive flag is one writing with its +// bound, intersecting the position's in no one value, so kept with it under the +// entry's key, though the position writes no flag. A flag no JSON holds is +// refused where written, its bound intersecting the position's, as bounds the +// position and another entry write do; a plain string keeps those apart, +// reported as written by both. +func TestKeeping_ABooleanFlagIsKeptWithItsBound(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", + " S: {allOf: [{type: string, format: int64, minimum: 1, exclusiveMinimum: true, maximum: 9, exclusiveMaximum: true}], minimum: 2, maximum: 10}\n"+ + " N: {allOf: [{type: string, format: int64, minimum: 1, exclusiveMinimum: "+unpreservableValue+"}], minimum: 2}\n"+ + " T: {allOf: [{type: string, format: int64, minimum: 1, maximum: 9}, {maximum: 8}], minimum: 2}\n"+ + " P: {allOf: [{type: string, minimum: 1, maximum: 9}, {maximum: 8}], minimum: 2}\n")) + assert.Equal(t, map[string]string{ + "openapi:allOf/0": `{"exclusiveMaximum":true,"exclusiveMinimum":true,"maximum":9,"minimum":1} [no_ir_home]`, + "openapi:minimum": "2 [no_ir_home]", + "openapi:maximum": "10 [no_ir_home]", + }, keptOn(t, doc, "S")) + assert.Equal(t, map[string]string{"openapi:minimum": "2 [no_ir_home]"}, keptOn(t, doc, "N")) + assert.Equal(t, map[string]string{"openapi:minimum": "2 [no_ir_home]", "openapi:maximum": "8 [no_ir_home]"}, keptOn(t, doc, "T")) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, "/components/schemas/N/allOf/0/exclusiveMinimum")) + apart := reportsAt(diags, "/components/schemas/S/allOf/0") + require.Len(t, apart, 1) + assert.Contains(t, apart[0], "the keywords beside this allOf write exclusiveMaximum, exclusiveMinimum, maximum, minimum otherwise") + assert.NotContains(t, apart[0], "other entries", "the allOf has no other entry") + assert.Empty(t, reportsAt(diags, "/components/schemas/T/allOf/0"), "the conjuncts intersect, so nothing is kept apart") + both := reportsAt(diags, "/components/schemas/P/allOf/0") + require.Len(t, both, 1) + assert.Contains(t, both[0], "the keywords beside this allOf and its other entries write maximum, minimum otherwise") +} + +// TestKeeping_AnEnumAConstPassesOverIsKeptAsWrittenAlone holds an enum an +// inline entry writes beside its const, which its own choice passes over: an +// entry no principal is keeps it as the same schema written alone does, under +// its plain key with that one report, whatever the value set beside it says; +// and the position's own enum beside a value set principal writing its const +// is kept as it writes it, the principal's apart. +func TestKeeping_AnEnumAConstPassesOverIsKeptAsWrittenAlone(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Alone: {type: string, const: a, enum: [a, b]}\n"+ + " Entry: {allOf: [{type: string}, {const: a, enum: [a, b]}], const: a}\n"+ + " Beside: {allOf: [{enum: [a, b], const: a}], enum: [a, b]}\n")) + alone := reportsAt(diags, "/components/schemas/Alone") + require.Len(t, alone, 1) + assert.Equal(t, map[string]string{"openapi:enum": `["a","b"] [degraded_lowering]`}, keptOn(t, doc, "Entry")) + assert.Equal(t, alone, reportsAt(diags, "/components/schemas/Entry/allOf/1"), "reported as written alone") + assert.Equal(t, map[string]string{"openapi:enum": `["a","b"] [degraded_lowering]`}, keptOn(t, doc, "Beside")) + assert.Equal(t, alone, reportsAt(diags, "/components/schemas/Beside"), "the position's enum is reported as written alone") + assert.True(t, slices.ContainsFunc(diags, func(diagnostic ir.Diagnostic) bool { + return diagnostic.Provenance.Pointer == "/components/schemas/Beside/allOf/0" && diagnostic.Message == alone[0] + }), "and so is the principal's, which its own choice passes over") +} diff --git a/compilers/openapi/internal/schema/keptdiscriminator.go b/compilers/openapi/internal/schema/keptdiscriminator.go new file mode 100644 index 000000000..63a874c24 --- /dev/null +++ b/compilers/openapi/internal/schema/keptdiscriminator.go @@ -0,0 +1,179 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + "strconv" + "strings" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/promotion" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// KeepDiscriminatorsWithin keeps whole each discriminator written at at or +// beneath it, which a keeper keeping the value at at verbatim on unmodeled +// keeps with it. One no model holds is read as the binding reads it +// (statement.WrittenDiscriminator). +func KeepDiscriminatorsWithin(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, at jsontext.Pointer) []ir.Diagnostic { + found := discriminatorsWithin(loweringContext, at) + diags := make([]ir.Diagnostic, 0, len(found)) + for _, written := range found { + diags = append(diags, keepWritten(loweringContext, unmodeled, written)...) + } + return diags +} + +// discriminatorsWithin returns each discriminator object the walks met written +// at at, or beneath it, in loweringContext's document +// (reftable.Discriminators.Within). +func discriminatorsWithin(loweringContext lowering.Ctx, at jsontext.Pointer) reftable.Discriminators { + position := loweringContext.Position(at) + return loweringContext.Bindings().Table().Document(position.Doc).Discriminators.Within(position.Pointer) +} + +// keepWritten keeps written whole, read as the schema holding it reads it, or, +// where no model holds that schema, as the binding reads it. +func keepWritten(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, written reftable.Discriminator) []ir.Diagnostic { + schemaAt := reftable.DocumentPointer{Doc: written.At.Doc, Pointer: written.At.Pointer.Parent()} + discriminator := loweringContext.Statements().At(schemaAt).Discriminator() + if discriminator == nil { + discriminator = statement.WrittenDiscriminator(written.Node, written.At) + } + return keepDiscriminator(loweringContext, unmodeled, discriminator, schemaAt.Pointer) +} + +// keepNodeDiscriminators keeps whole each discriminator unmodeled, the entries +// a node settled on, keeps under an entry of its own: an entry holding it whole +// holds its extensions, so none takes an entry of its own beside it. +func keepNodeDiscriminators(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled) []ir.Diagnostic { + source := loweringContext.Place().At("").Source + var positions []jsontext.Pointer + for _, entry := range *unmodeled { + if entry.Provenance.Source == source && strings.HasSuffix(string(entry.Provenance.Pointer), "/discriminator") { + positions = append(positions, entry.Provenance.Pointer) + } + } + slices.Sort(positions) + var diags []ir.Diagnostic + for _, pointer := range slices.Compact(positions) { + for _, written := range discriminatorsWithin(loweringContext, pointer) { + if written.At.Pointer == pointer { + diags = append(diags, keepWritten(loweringContext, unmodeled, written)...) + } + } + } + return diags +} + +// keepDiscriminator keeps whole discriminator, the one the schema written at +// pointer writes, which its caller keeps verbatim on unmodeled: unmodeled drops +// the entries written within it, and each mapping value and the defaultMapping +// is read as the reference it is (docs/compilers/openapi.md#discriminator). It +// promises nothing itself (promiseKeptTargets), so a settlement may call it. +func keepDiscriminator(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, discriminator *statement.Discriminator, pointer jsontext.Pointer) []ir.Diagnostic { + if discriminator == nil { + return nil + } + at := pointer + ids.Ptr("discriminator") + if unmodeled != nil { + promotion.DropContainedWithin(loweringContext.Promoter(), unmodeled, loweringContext.Place().At(at)) + } + var diags []ir.Diagnostic + mapping := make(map[string]ir.TypeID, len(discriminator.Mapping)) + for _, entry := range discriminator.Mapping { + id, ok, entryDiags := keptRoute(loweringContext, discriminator, entry.Target, + "discriminator mapping "+strconv.Quote(entry.Value), at+ids.Ptr("mapping", entry.Value)) + diags = append(diags, entryDiags...) + if ok { + mapping[entry.Value] = id + } + } + var def ir.TypeID + if discriminator.DefaultMapping != "" { + id, ok, defaultDiags := keptRoute(loweringContext, discriminator, discriminator.DefaultMapping, + "discriminator defaultMapping", at+ids.Ptr("defaultMapping")) + diags = append(diags, defaultDiags...) + if ok { + def = id + } + } + recordKeptDiscriminatorRoutes(loweringContext, at, discriminator, mapping, def) + return diags +} + +// keptRoute returns the type value, of the kept discriminator, routes to, as a +// model's routes (hierarchyRoute), and queues its chain's end to be promised a +// node (promiseKeptTargets). A broken chain routes nowhere, its end promised +// all the same. +func keptRoute(loweringContext lowering.Ctx, discriminator *statement.Discriminator, value, subject string, at jsontext.Pointer, +) (ir.TypeID, bool, []ir.Diagnostic) { + chain, ok := chainOf(loweringContext, discriminator, value) + if !ok { + return "", false, valueNamingNothing(loweringContext, discriminator, value, subject, at) + } + end := chain.end() + trackers := runTrackersOf(loweringContext) + trackers.keptTargets = append(trackers.keptTargets, end) + if chain.broken { + recordDiscarded(loweringContext, end.id) + return "", false, nil + } + return end.id, true, nil +} + +// valueNamingNothing is the report of value, of discriminator, naming no +// schema, worded alike by a node's reader and a keeper's: an entry both read is +// one reference, which the compile reports once. +func valueNamingNothing(loweringContext lowering.Ctx, discriminator *statement.Discriminator, value, subject string, at jsontext.Pointer) []ir.Diagnostic { + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.UnresolvedRef, at, + "%s references unresolved schema %q%s", subject, value, mappingWhy(loweringContext, discriminator, value))} +} + +// promiseKeptTargets promises a node at each position a kept discriminator's +// value led to since it last ran, as a $ref's target is promised (resolveAt). +// One a settlement queues once the registry is fulfilled is promised by no +// one: the node holding the discriminator promised it as it lowered. +func promiseKeptTargets(loweringContext lowering.Ctx, types *compile.Types, trackers *runTrackers) { + targets := trackers.keptTargets + trackers.keptTargets = nil + for _, target := range targets { + resolveAt(loweringContext, types, target.at, target.decl) + } +} + +// keepValidationOnlyDiscriminators keeps whole each discriminator within the +// keywords the validation-only entries of kept hold, an entry combining several +// being kept at the schema writing them. Its reports are of the discriminator, +// not of the entry's keeping, so they pair with no key. +func keepValidationOnlyDiscriminators(loweringContext lowering.Ctx, kept ir.Unmodeled) annotation.KeptReports { + var keys []string + for key, entry := range kept { + if entry.Reason == ir.ReasonValidationOnly { + keys = append(keys, key) + } + } + slices.Sort(keys) + var reports annotation.KeptReports + for _, key := range keys { + entry := kept[key] + keywords := annotation.ValidationOnlyKeywordsOf(key) + if len(keywords) <= 1 { + reports = append(reports, annotation.ReportsOf("", KeepDiscriminatorsWithin(loweringContext, nil, entry.Provenance.Pointer)...)...) + continue + } + for _, keyword := range keywords { + reports = append(reports, annotation.ReportsOf("", KeepDiscriminatorsWithin(loweringContext, nil, entry.Provenance.Pointer+ids.Ptr(keyword))...)...) + } + } + return reports +} diff --git a/compilers/openapi/internal/schema/keys.go b/compilers/openapi/internal/schema/keys.go index eb5e96daa..4457771e5 100644 --- a/compilers/openapi/internal/schema/keys.go +++ b/compilers/openapi/internal/schema/keys.go @@ -5,12 +5,23 @@ package schema import ( "slices" + "strings" yaml "go.yaml.in/yaml/v3" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" "github.com/dexpace/morphic/compilers/openapi/internal/statement" ) +// keySaysNothing reports whether key, which schema writes, says nothing of the +// instance schema applies to. Every reader asking whether a schema writes +// anything beside some keywords asks it, so they agree. +func keySaysNothing(schema *statement.Schema, key statement.Key) bool { + return slices.Contains(noteKeywords, key.Name) || strings.HasPrefix(key.Name, "x-") || + specrules.SlotOf(key.Name) == specrules.SlotResource || annotation.WritesKeywordLeftOut(schema, key.Name) +} + // hasKey reports whether schema writes key and it is read: a null is the // keyword left out unless the keyword holds an instance (statement.Schema.Key). func hasKey(schema *statement.Schema, key string) bool { @@ -20,7 +31,7 @@ func hasKey(schema *statement.Schema, key string) bool { // hasAnyKey reports whether schema writes any of keys (hasKey). It reads the // keys as written rather than the model's fields because the recorders reading -// the same keyword lists read them there (recordResidue, declaredConstraints +// the same keyword lists read them there (recordUseBound, declaredConstraints // and annotation's dialectAt), and a predicate consulting a different source // could disagree with them in either direction. func hasAnyKey(schema *statement.Schema, keys []string) bool { diff --git a/compilers/openapi/internal/schema/keywordkinds.go b/compilers/openapi/internal/schema/keywordkinds.go index 6d7a37e4d..e8e902119 100644 --- a/compilers/openapi/internal/schema/keywordkinds.go +++ b/compilers/openapi/internal/schema/keywordkinds.go @@ -4,35 +4,14 @@ package schema import ( + "slices" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" ) -// keywordKinds maps each keyword JSON Schema applies to instances of some types -// alone to the kinds of those types: the numeric bounds to numbers, the string -// bounds and the content vocabulary to strings, and the property counts to -// objects (JSON Schema Validation 2020-12 §6.2, §6.3, §6.5 and §8, which the -// earlier drafts group alike). An instance of another kind satisfies such a -// keyword (JSON Schema Core 2020-12 §7.6.1), so it says nothing of a value only -// other kinds can be. The collection bounds are left to the List and Tuple -// readers, which ask the node. -var keywordKinds = map[string]kindSet{ - "exclusiveMaximum": kindNumber, - "exclusiveMinimum": kindNumber, - "maximum": kindNumber, - "minimum": kindNumber, - "multipleOf": kindNumber, - "maxLength": kindString, - "minLength": kindString, - "pattern": kindString, - "contentEncoding": kindString, - "contentMediaType": kindString, - "contentSchema": kindString, - "maxProperties": kindObject, - "minProperties": kindObject, -} - // boundKinds returns the kinds a reader of the bounds schema writes takes: // those its home lowers to (docs/compilers/openapi.md#constraints), as the run // reads its statement once (admissionOf), its value sets, a type beside a $ref @@ -45,66 +24,51 @@ func boundKinds(loweringContext lowering.Ctx, schema *statement.Schema) kindSet if !stated(schema) || !writesBound(loweringContext, schema) { return own } - admission := admissionOf(loweringContext, loweringContext.Statements().Read(schema)) - if admission.cut { - return own - } - return admission.kinds + return admissionOf(loweringContext, loweringContext.Statements().Read(schema)).kinds } -// writesBound reports whether s, or an inline entry of its flattened allOf, +// writesBound reports whether schema, or an inline entry of its flattened allOf, // writes a value or collection bound: where none does, no reader asks its types. // A bound beside an entry's own $ref is that entry's. func writesBound(loweringContext lowering.Ctx, schema *statement.Schema) bool { - if declaresBound(schema) { - return true - } - for _, allOfConjunct := range loweringContext.Statements().Read(schema).Entries { - if stated(allOfConjunct.Schema) && allOfConjunct.Ref == nil && declaresBound(allOfConjunct.Schema) { - return true - } - } - return false + return slices.ContainsFunc(inlineConjuncts(loweringContext, schema), declaresBound) } // declaresBound reports whether schema writes a value bound or a collection // bound. func declaresBound(schema *statement.Schema) bool { - return declaresValueConstraints(schema) || hasAnyKey(schema, collectionBoundKeywords) + return hasAnyKey(schema, valueConstraintKeywords) || hasAnyKey(schema, collectionBoundKeywords) } -// writerTakes returns the kinds whose value bounds a reader of the kinds takes -// reads of w, a position's schema or an allOf entry folding there: those w's -// own types admit too, as an entry declaring a type bounds no value of another -// kind. A reader's kinds are those its position admits (boundKinds), within -// what the position's own schema declares, so that schema leaves them as they -// are. -func writerTakes(takes kindSet, schema *statement.Schema) kindSet { +// conjunctTakes returns the kinds whose value bounds a reader of the kinds +// takes reads of schema, a position's schema or an allOf entry folding there: +// those schema's own types admit too, as an entry declaring a type bounds no +// value of another kind. A reader's kinds are those its position admits +// (boundKinds), within what the position's own schema declares, so that schema +// leaves them as they are. +func conjunctTakes(takes kindSet, schema *statement.Schema) kindSet { return takes & declaredInstanceTypes(schema) } -// taken reports whether a reader of values of the kinds takes reads keyword: -// whether keyword applies to a value of one of them. One the table does not list -// applies to every value. +// taken reports whether a reader of values of the kinds takes reads keyword, +// a value bound or the content vocabulary: whether keyword applies to a value +// of one of them (typeformat.InstanceKindsKeywordAppliesTo). func taken(takes kindSet, keyword string) bool { - kinds, listed := keywordKinds[keyword] - return !listed || takes&kinds != 0 + return takes&typeformat.InstanceKindsKeywordAppliesTo(keyword, nil) != 0 } // boundsFor returns the groups of value bounds annotation.Constraints reads for -// a reader of the kinds takes: the numeric bounds for a number, the string -// bounds for a string and the property counts for an object, as keywordKinds -// gives each keyword its kinds. +// a reader of the kinds takes: each group whose keywords apply to one of them +// (typeformat.InstanceKindsKeywordAppliesTo). func boundsFor(takes kindSet) annotation.Bounds { - var b annotation.Bounds - if takes&kindNumber != 0 { - b |= annotation.NumberBounds - } - if takes&kindString != 0 { - b |= annotation.StringBounds - } - if takes&kindObject != 0 { - b |= annotation.ObjectBounds + var bounds annotation.Bounds + for _, group := range []struct { + keyword string + bounds annotation.Bounds + }{{"minimum", annotation.NumberBounds}, {"minLength", annotation.StringBounds}, {"minProperties", annotation.ObjectBounds}} { + if takes&typeformat.InstanceKindsKeywordAppliesTo(group.keyword, nil) != 0 { + bounds |= group.bounds + } } - return b + return bounds } diff --git a/compilers/openapi/internal/schema/keywordkinds_internal_test.go b/compilers/openapi/internal/schema/keywordkinds_internal_test.go index f991ee0a1..93ccadb52 100644 --- a/compilers/openapi/internal/schema/keywordkinds_internal_test.go +++ b/compilers/openapi/internal/schema/keywordkinds_internal_test.go @@ -6,28 +6,33 @@ package schema import ( "encoding/json/jsontext" "fmt" - "maps" "slices" "strings" "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/compilers/openapi/internal/provenance" "github.com/dexpace/morphic/compilers/openapi/internal/service" "github.com/dexpace/morphic/compilers/openapi/internal/service/servicetest" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" ) -// TestKeywordKinds_ListsEveryValueBoundAndTheContentVocabulary holds the -// table's rows to the keywords annotation.Constraints and scalarEncoding read, -// so a bound added to one list and not to the table, or the reverse, fails here. -func TestKeywordKinds_ListsEveryValueBoundAndTheContentVocabulary(t *testing.T) { +// TestKeywordAppliesTo_ReadsEveryValueBoundAndTheContentVocabularyByItsKind +// holds each keyword annotation.Constraints and scalarEncoding read to a kind +// narrower than every kind, as the applies-to table reads it, so a bound the +// table reads as applying to every kind fails here. +func TestKeywordAppliesTo_ReadsEveryValueBoundAndTheContentVocabularyByItsKind(t *testing.T) { t.Parallel() - want := slices.Sorted(slices.Values(slices.Concat(valueConstraintKeywords, contentKeywords))) - assert.Equal(t, want, slices.Sorted(maps.Keys(keywordKinds))) + for _, keyword := range slices.Concat(valueConstraintKeywords, contentKeywords) { + kinds := typeformat.InstanceKindsKeywordAppliesTo(keyword, nil) + assert.NotZero(t, kinds, keyword) + assert.NotEqual(t, kindAny, kinds, keyword) + } + assert.Equal(t, kindAny, typeformat.InstanceKindsKeywordAppliesTo("description", nil)) + assert.Equal(t, kindString, typeformat.InstanceKindsKeywordAppliesTo("format", jsontext.Value(`"uuid"`))) } // TestBoundsFor_ReadsEachBoundForTheKindsItAppliesTo holds the table, the groups @@ -41,11 +46,11 @@ func TestBoundsFor_ReadsEachBoundForTheKindsItAppliesTo(t *testing.T) { if keyword == "pattern" { literal = "'^a'" } - s := openapitest.SchemaFromYAML(t.Context(), t, keyword+": "+literal+"\n").GetSchema() - kinds := keywordKinds[keyword] - read, _, _ := annotation.Constraints(StandaloneSchema(s), boundsFor(kinds), false, "/p", provenance.Doc{}) + schemaObject := openapitest.SchemaFromYAML(t.Context(), t, keyword+": "+literal+"\n").GetSchema() + kinds := typeformat.InstanceKindsKeywordAppliesTo(keyword, nil) + read, _, _ := annotation.Constraints(StandaloneSchema(schemaObject), boundsFor(kinds), false, "/p", provenance.Doc{}) assert.NotNil(t, read, keyword) - unread, _, _ := annotation.Constraints(StandaloneSchema(s), boundsFor(anyInstance&^kinds), false, "/p", provenance.Doc{}) + unread, _, _ := annotation.Constraints(StandaloneSchema(schemaObject), boundsFor(everyKindButNull&^kinds), false, "/p", provenance.Doc{}) assert.Nil(t, unread, keyword) } } @@ -57,16 +62,16 @@ func TestBoundsFor_ReadsEachBoundForTheKindsItAppliesTo(t *testing.T) { func TestDeclaredInstanceTypes_ReadsTheTypesASchemaDeclares(t *testing.T) { t.Parallel() for body, want := range map[string]kindSet{ - "description: d\n": anyInstance, + "description: d\n": everyKindButNull, "type: 'null'\n": 0, "type: ['null']\n": 0, - "type: strin\n": anyInstance, + "type: strin\n": everyKindButNull, "type: [string, 'null']\n": kindString, "type: [integer, object]\n": kindInteger | kindObject, "type: [number, array, boolean]\n": kindNumber | kindArray | kindBoolean, } { - s := openapitest.SchemaFromYAML(t.Context(), t, body).GetSchema() - assert.Equal(t, want, declaredInstanceTypes(StandaloneSchema(s)), body) + schemaObject := openapitest.SchemaFromYAML(t.Context(), t, body).GetSchema() + assert.Equal(t, want, declaredInstanceTypes(StandaloneSchema(schemaObject)), body) } } @@ -74,16 +79,17 @@ func TestDeclaredInstanceTypes_ReadsTheTypesASchemaDeclares(t *testing.T) { // every kind but null for a spelling no dialect defines. func TestTypeKinds_ReadsOneListedType(t *testing.T) { t.Parallel() - assert.Equal(t, kindString, typeKinds("string")) - assert.Equal(t, kindNumber, typeKinds("number")) - assert.Equal(t, anyInstance, typeKinds("strin")) + assert.Equal(t, kindString, kindsOfTypeNameOrAny("string")) + assert.Equal(t, kindNumber, kindsOfTypeNameOrAny("number")) + assert.Equal(t, everyKindButNull, kindsOfTypeNameOrAny("strin")) } // TestTaken_AKeywordTheTableDoesNotListAppliesToEveryKind pins the default of -// taken: a keyword applying to no kind in particular is read by every reader. +// taken: a keyword applying to no kind in particular is read by every reader +// of a kind. func TestTaken_AKeywordTheTableDoesNotListAppliesToEveryKind(t *testing.T) { t.Parallel() - assert.True(t, taken(0, "description")) + assert.True(t, taken(kindBoolean, "description")) assert.False(t, taken(kindString|kindObject, "minimum")) assert.True(t, taken(kindInteger, "minimum")) } @@ -96,7 +102,7 @@ func TestWritesBound_FindsABoundOnTheSchemaOrAnInlineEntry(t *testing.T) { t.Parallel() const obj = "{$ref: '#/components/schemas/Obj'}" lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" Obj: {type: object}\n")) - for _, tc := range []struct { + for _, testCase := range []struct { name, body string want bool }{ @@ -109,32 +115,29 @@ func TestWritesBound_FindsABoundOnTheSchemaOrAnInlineEntry(t *testing.T) { {"a collection bound on a later entry", "allOf: [" + obj + ", {properties: {a: {}}}, {uniqueItems: true}]\n", true}, {"a bound on an entry of a nested allOf", "allOf: [" + obj + ", {allOf: [{pattern: '^a'}]}]\n", true}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - s := openapitest.SchemaFromYAML(t.Context(), t, tc.body).GetSchema() - assert.Equal(t, tc.want, writesBound(lowerer.Ctx, StandaloneSchema(s))) + schemaObject := openapitest.SchemaFromYAML(t.Context(), t, testCase.body).GetSchema() + assert.Equal(t, testCase.want, writesBound(lowerer.Ctx, StandaloneSchema(schemaObject))) }) } } // TestBoundKinds_ReadsEachShapeWhole pins the kinds a bound beside each of // budgetShapes is read by, each a thousand wide or long or 300 deep: a read of any size is -// decided, a null branch adds no kind, a chain of dynamic references is read -// to the schema it expands to, and a read meeting a cycle of $refs or a $ref -// landing on no schema leaves the position's own type to decide. +// decided, a null branch adds no kind, and a chain of dynamic references is read +// to the schema it expands to. A cycle of $refs and a $ref landing on no schema +// each admit every kind, as {} does, so neither cuts the read: Dangling admits +// every kind, and Mixed and All, which conjoin them with strings, a string. func TestBoundKinds_ReadsEachShapeWhole(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.ComponentSpecVer("3.1.0", budgetShapes(1000)), service.Policy{}) for name, want := range map[string]kindSet{ - "AllOf": kindString, "AnyOf": kindString, "Nulls": kindString, "Trues": anyInstance, "D0": kindString, - "Deep": kindString, "Dangling": anyInstance, "Mixed": anyInstance, "All": anyInstance, + "AllOf": kindString, "AnyOf": kindString, "Nulls": kindString, "Trues": everyKindButNull, "D0": kindString, + "Deep": kindString, "Dangling": everyKindButNull, "Mixed": kindString, "All": kindString, } { admission := admissionOf(serviceContext.Ctx, heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name))) - cut := name == "Dangling" || name == "Mixed" || name == "All" - assert.Equal(t, cut, admission.cut, name) - if !cut { - assert.Equal(t, want, admission.kinds, name) - } + assert.Equal(t, want, admission.kinds, name) } } @@ -173,10 +176,10 @@ func budgetShapes(n int) string { "{$ref: '#/components/schemas/D0'}], $ref: '#/components/schemas/Str', anyOf: [{$ref: '#/components/schemas/Nulls'}]}\n" } -// TestBoundKinds_ACycleLeavesTheOwnTypeToDecide pins the fallback of a read cut -// by a cycle of conjunct edges, of dynamic references or of $refs, and by a -// $ref landing on no schema: a bound beside it is read by the position's own -// type, every bound where it writes none. +// TestBoundKinds_ACycleLeavesTheOwnTypeToDecide pins a bound beside a cycle of +// dynamic references or of $refs, or beside a $ref landing on no schema: each +// admits every kind and cuts no read, so the bound is read by the position's +// own type, every bound where it writes none. func TestBoundKinds_ACycleLeavesTheOwnTypeToDecide(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.ComponentSpecVer("3.1.0", ` A: {$dynamicAnchor: a, $dynamicRef: '#b', minimum: 1} @@ -184,9 +187,8 @@ func TestBoundKinds_ACycleLeavesTheOwnTypeToDecide(t *testing.T) { R: {allOf: [{$ref: '#/components/schemas/R'}], type: integer, minLength: 1} Dangling: {allOf: [{$ref: '#/components/schemas/Nowhere'}], minLength: 1} `), service.Policy{}) - for name, want := range map[string]kindSet{"A": anyInstance, "R": kindInteger, "Dangling": anyInstance} { - st := heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name)) - require.True(t, admissionOf(serviceContext.Ctx, st).cut, name) - assert.Equal(t, want, boundKinds(serviceContext.Ctx, st.Schema), name) + for name, want := range map[string]kindSet{"A": everyKindButNull, "R": kindInteger, "Dangling": everyKindButNull} { + schemaStatement := heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name)) + assert.Equal(t, want, boundKinds(serviceContext.Ctx, schemaStatement.Schema), name) } } diff --git a/compilers/openapi/internal/schema/kinds.go b/compilers/openapi/internal/schema/kinds.go index 0a142b8d5..2ccccf9ee 100644 --- a/compilers/openapi/internal/schema/kinds.go +++ b/compilers/openapi/internal/schema/kinds.go @@ -6,91 +6,113 @@ package schema import ( "strings" + "github.com/dexpace/morphic/compilers/openapi/internal/merge" "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" "github.com/dexpace/morphic/ir" ) -// kindSet is a set of JSON instance kinds. An integer and a number with a -// fraction are two kinds, since `integer` admits one of them and `number` both. -type kindSet uint8 +// kindSet is a set of JSON instance kinds, the one type the applies-to table +// (typeformat.InstanceKindsKeywordAppliesTo) and the lowering name them by. An +// integer and a number with a fraction are two kinds, since `integer` admits +// one of them and `number` both. +type kindSet = typeformat.JSONInstanceKinds const ( - kindString kindSet = 1 << iota - kindInteger - kindFraction - kindBoolean - kindArray - kindObject - kindNull + kindString = typeformat.InstanceString + kindInteger = typeformat.InstanceInteger + kindFraction = typeformat.InstanceNumber + kindBoolean = typeformat.InstanceBoolean + kindArray = typeformat.InstanceArray + kindObject = typeformat.InstanceObject + kindNull = typeformat.InstanceNull kindNumber = kindInteger | kindFraction - kindAny = kindString | kindNumber | kindBoolean | kindArray | kindObject | kindNull + kindAny = typeformat.EveryInstanceKind ) -// kindOfType returns the kinds a `type` member admits, and none for a spelling -// no schema defines. -func kindOfType(jsonSchemaTypeName statement.JSONSchemaTypeName) kindSet { - switch jsonSchemaTypeName { - case statement.KindString: - return kindString - case statement.KindInteger: - return kindInteger - case statement.KindNumber: - return kindNumber - case statement.KindBoolean: - return kindBoolean - case statement.KindArray: - return kindArray - case statement.KindObject: - return kindObject - case statement.KindNull: - return kindNull - default: - return 0 +// kindCount counts the kinds of kinds, null aside, a number one kind whether +// integer or not. +func kindCount(kinds kindSet) int { + count := 0 + for _, kind := range []kindSet{kindObject, kindArray, kindString, kindNumber, kindBoolean} { + if kinds&kind != 0 { + count++ + } + } + return count +} + +// typeNameKinds pairs each `type` word with the instance kind merge names it +// by and the kinds it admits. +var typeNameKinds = []struct { + typeName statement.JSONSchemaTypeName + instance merge.JSONInstanceKind + kinds kindSet +}{ + {statement.KindString, merge.InstanceString, kindString}, + {statement.KindInteger, merge.InstanceInteger, kindInteger}, + {statement.KindNumber, merge.InstanceNumber, kindNumber}, + {statement.KindBoolean, merge.InstanceBoolean, kindBoolean}, + {statement.KindArray, merge.InstanceArray, kindArray}, + {statement.KindObject, merge.InstanceObject, kindObject}, + {statement.KindNull, merge.InstanceNull, kindNull}, +} + +// kindsOfTypeName returns the kinds a `type` member admits, and none for a +// spelling no schema defines. +func kindsOfTypeName(jsonSchemaTypeName statement.JSONSchemaTypeName) kindSet { + for _, row := range typeNameKinds { + if row.typeName == jsonSchemaTypeName { + return row.kinds + } + } + return 0 +} + +// instanceKinds returns the kinds an instance of kind may be, none for the +// null, which a reader of what a schema admits leaves to nulls. +func instanceKinds(kind merge.JSONInstanceKind) kindSet { + for _, row := range typeNameKinds { + if row.instance == kind && kind != merge.InstanceNull { + return row.kinds + } + } + return 0 +} + +// kindsOfTypeNameOrString returns the kinds a schema writing the `type` word +// typeName alone lowers to: those typeName names, and for a word no dialect +// defines the string its scalar lowers over (baseForType), so a conjunct +// writing it admits what the same schema written alone does. +func kindsOfTypeNameOrString(typeName statement.JSONSchemaTypeName) kindSet { + if kinds := kindsOfTypeName(typeName); kinds != 0 { + return kinds } + return kindString } -// kindOfValue returns the JSON kind of value. +// kindOfValue returns the JSON kind of value (typeformat.KindsOfValue): a +// symbol and bytes are the text they spell, and a reference, a constructor and +// a non-finite number are no JSON instance's value. func kindOfValue(value ir.Value) kindSet { switch value.Kind { - case ir.ValueString, ir.ValueSymbol, ir.ValueBytes: + case ir.ValueSymbol, ir.ValueBytes: return kindString - case ir.ValueBool: - return kindBoolean - case ir.ValueNull: - return kindNull - case ir.ValueList: - return kindArray - case ir.ValueObject: - return kindObject - case ir.ValueNumber: - return kindOfNumber(string(value.Number)) - case ir.ValueRefKind, ir.ValueConstructor, ir.ValueInfinity, ir.ValueNegativeInfinity, ir.ValueNaN: - // A reference, a constructor and a non-finite number are no JSON - // instance's value. + case ir.ValueNull, ir.ValueBool, ir.ValueString, ir.ValueNumber, ir.ValueList, ir.ValueObject: + kinds, _ := typeformat.KindsOfValue(value) + return kinds + case ir.ValueInfinity, ir.ValueNegativeInfinity, ir.ValueNaN, ir.ValueRefKind, ir.ValueConstructor: return 0 default: return 0 } } -// kindOfNumber returns the kind of a decimal literal. One with an exponent may -// be integral or not, and telling them apart costs what the exponent says, so it -// answers for both. -func kindOfNumber(number string) kindSet { - if strings.ContainsAny(number, "eE") { - return kindNumber - } - if _, fraction, _ := strings.Cut(number, "."); strings.Trim(fraction, "0") != "" { - return kindFraction - } - return kindInteger -} - -// anyInstance is what a schema writing no `type` admits, null aside: nulls is -// the one reading of null, so a set here holds no kindNull, and its zero is a -// schema writing `type: "null"`. -const anyInstance = kindAny &^ kindNull +// everyKindButNull is what a schema writing no `type` admits, null aside: nulls +// is the one reading of null, so a set here holds no kindNull, and its zero is +// a schema writing `type: "null"`. +const everyKindButNull = kindAny &^ kindNull // kindWords spells the members of a kindSet in the order a diagnostic lists // them. A number holds an integer and a number with a fraction, so it is @@ -126,30 +148,31 @@ func instanceWords(kindSetValue kindSet) string { // declaredInstanceTypes is the set schema's own `type` keyword states. A schema // writing none excludes nothing, whatever else it writes: `properties` alone -// constrains objects and admits a string. A word no dialect defines says -// nothing either: load reports it, so it is no conjunct's to contradict another. +// constrains objects and admits a string. A word no dialect defines, which load +// reports, excludes nothing in this reading; the kinds a conjunction admits +// read it as its scalar lowers (kindsOfTypeNameOrString). func declaredInstanceTypes(schema *statement.Schema) kindSet { declared := schema.Types() if len(declared) == 0 { - return anyInstance + return everyKindButNull } var out kindSet - for _, st := range declared { - kinds := kindOfType(st) + for _, typeName := range declared { + kinds := kindsOfTypeName(typeName) if kinds == 0 { - kinds = anyInstance + kinds = everyKindButNull } out |= kinds &^ kindNull } return out } -// typeKinds returns the kinds st, one type a type array lists, admits, and every -// kind but null for a spelling no dialect defines, as declaredInstanceTypes -// reads one. -func typeKinds(st statement.JSONSchemaTypeName) kindSet { - if kinds := kindOfType(st) &^ kindNull; kinds != 0 { +// kindsOfTypeNameOrAny returns the kinds typeName, one type a type array lists, +// admits, and every kind but null for a spelling no dialect defines, as +// declaredInstanceTypes reads one. +func kindsOfTypeNameOrAny(typeName statement.JSONSchemaTypeName) kindSet { + if kinds := kindsOfTypeName(typeName) &^ kindNull; kinds != 0 { return kinds } - return anyInstance + return everyKindButNull } diff --git a/compilers/openapi/internal/schema/loophop_internal_test.go b/compilers/openapi/internal/schema/loophop_internal_test.go new file mode 100644 index 000000000..20879730d --- /dev/null +++ b/compilers/openapi/internal/schema/loophop_internal_test.go @@ -0,0 +1,73 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// TestHopRefOf_ReadsAHopAsAPureHopIs pins which schemas a loop's reader +// follows as a hop (docs/compilers/openapi.md#reference-cycles): an allOf of +// one $ref beside entries and keys saying nothing, nested in place, an +// identifier in a draft's spelling among them, is one; an +// entry `false`, an entry or a key saying something, a second $ref and an allOf +// nested past the flattening depth, whose entries go unread, are not. +func TestHopRefOf_ReadsAHopAsAPureHopIs(t *testing.T) { + t.Parallel() + ref := "{$ref: '#/components/schemas/T'}" + capped := "{allOf: [" + ref + ", " + strings.Repeat("{allOf: [", statement.MaxFlattenDepth+2) + "{minLength: 2}" + + strings.Repeat("]}", statement.MaxFlattenDepth+2) + "]}" + hops := map[string]bool{ + "{allOf: [" + ref + "]}": true, + "{allOf: [" + ref + ", true, {description: d}], $comment: c}": true, + "{allOf: [{allOf: [" + ref + "]}], x-a: 1}": true, + "{allOf: [" + ref + "], id: e}": true, + "{allOf: [" + ref + ", false]}": false, + "{allOf: [" + ref + ", {minLength: 2}]}": false, + "{allOf: [" + ref + "], type: string}": false, + "{allOf: [" + ref + ", " + ref + "]}": false, + "{allOf: [{$ref: '#/components/schemas/T', type: string}]}": false, + capped: false, + "{type: string}": false, + } + var spec strings.Builder + spec.WriteString(" T: {type: string}\n") + names := map[string]string{} + for written := range hops { + name := "L" + string(rune('A'+len(names))) + names[name] = written + spec.WriteString(" " + name + ": " + written + "\n") + } + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", spec.String())) + for name, written := range names { + schemaStatement := lowerer.Ctx.Statements().Read(StatedIn(lowerer, componentSchema(t, lowerer, name))) + hopRef := hopRefOf(lowerer.Ctx, schemaStatement) + if !hops[written] { + assert.Nil(t, hopRef, written) + continue + } + require.NotNil(t, hopRef, written) + assert.Equal(t, "#/components/schemas/T", hopRef.Ref.Text, written) + } +} + +// TestKeptWhy_ALoopAloneIsTheTopType pins the report on a $ref leading round a +// loop of references back to a position writing nothing else, which only a +// read the table's budget cut short leaves unreported as a loop: the loop +// admits every kind there, so the position is the top type; beside another +// conjunct, what that conjunct says decides. +func TestKeptWhy_ALoopAloneIsTheTopType(t *testing.T) { + t.Parallel() + refEntry := keptRefEntry{choiceReason: refAround} + assert.Contains(t, keptWhy(lowering.Ctx{}, nil, allOfComposition{}, refEntry, true), "nothing beside it says more, so the position is the top type") + assert.Contains(t, keptWhy(lowering.Ctx{}, nil, allOfComposition{}, refEntry, false), "so what its other conjuncts say decides") +} diff --git a/compilers/openapi/internal/schema/looplink.go b/compilers/openapi/internal/schema/looplink.go new file mode 100644 index 000000000..1b34c4ec1 --- /dev/null +++ b/compilers/openapi/internal/schema/looplink.go @@ -0,0 +1,53 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// hopRefOf returns the $ref schemaStatement is a pure hop of, an allOf saying +// nothing beside one $ref entry, and nil for any other schema +// (docs/compilers/openapi.md#reference-cycles). A loop through such a hop +// reads, by kind, only what its other members write. +func hopRefOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) *statement.Statement { + if schemaStatement.Ref != nil || len(schemaStatement.Entries) == 0 || !saysNothingBeside(schemaStatement.Schema, "") { + return nil + } + var ref *statement.Statement + for _, entry := range schemaStatement.Entries { + read := loweringContext.Statements().Read(entry.Schema) + switch { + case entry.Capped: + return nil + case read.Ref == nil && saysNothingBeside(read.Schema, ""): + case read.Ref != nil && ref == nil && saysNothingBeside(read.Schema, read.Ref.Keyword): + ref = read + default: + return nil + } + } + return ref +} + +// saysNothingBeside reports whether schema says nothing of the instance beside +// keyword and an allOf, whose entries are read apart. A schema whose merges ran +// past their limit says something. +func saysNothingBeside(schema *statement.Schema, keyword string) bool { + switch { + case schema.Truth == statement.Anything || schema.Truth == statement.Unwritten: + return true + case schema.Truth != statement.Stated || schema.Truncated: + return false + } + return !slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { + // Every note says nothing of a hop, readOnly and default among + // them, which keySaysNothing reads as saying something. + return key.Name != keyword && key.Name != "allOf" && key.Slot != specrules.SlotNotes && !keySaysNothing(schema, key) + }) +} diff --git a/compilers/openapi/internal/schema/mapping.go b/compilers/openapi/internal/schema/mapping.go index 57006abd0..dc551d4b1 100644 --- a/compilers/openapi/internal/schema/mapping.go +++ b/compilers/openapi/internal/schema/mapping.go @@ -19,17 +19,11 @@ import ( "github.com/dexpace/morphic/ir" ) -// maxChainHops bounds how many $refs a mapping value's chain reads -// (styleguide bounded-everything rule). A chain no loop ends that is longer -// stops at the position the bound reached, as though that position wrote no -// $ref: a loop breaks the chain where the binding finds it, long before. -const maxChainHops = 64 - -// link is one position of a mapping value's chain, the schema held there, +// chainNode is one position of a mapping value's chain, the schema held there, // which a reference object the position's $ref passes may have the bindings // read in another document (reftable.Hop.Target), and the ID of the type // declared there (declaredAt). -type link struct { +type chainNode struct { at reftable.DocumentPointer decl *statement.Statement id ir.TypeID @@ -40,12 +34,12 @@ type link struct { // every one a position a type is declared at. broken reports that the last // writes a $ref landing on no such position, or lies on a loop. type valueChain struct { - links []link - broken bool + chainNodes []chainNode + broken bool } // end is the last position of v, which holds at least one. -func (v valueChain) end() link { return v.links[len(v.links)-1] } +func (v valueChain) end() chainNode { return v.chainNodes[len(v.chainNodes)-1] } // chainFrom keys the chain read from a position and the schema held there // (follow). @@ -71,7 +65,7 @@ func chainOf(loweringContext lowering.Ctx, discriminator *statement.Discriminato return valueChain{}, false } return lowering.ReadOncePerRun(loweringContext, chainFrom{at, decl}, func() valueChain { - return follow(loweringContext, link{at: at, decl: decl, id: id}) + return follow(loweringContext, chainNode{at: at, decl: decl, id: id}) }), true } @@ -88,43 +82,42 @@ func valuePosition(loweringContext lowering.Ctx, discriminator *statement.Discri return at, loweringContext.Statements().At(at), ok } -// follow returns the chain from start: each $ref read in turn, to the first -// position writing none, or past maxChainHops to the one the bound reached. A +// follow returns the chain from start, each $ref read in turn (refChain). A // component is read through as any other position: one writing a $ref lowers // to a use of what it names, which is no subtype or variant, so a route -// naming it means what its $ref names, written beside other keys too -// (referenceOf). -func follow(loweringContext lowering.Ctx, start link) valueChain { - chain := valueChain{links: []link{start}} - for range maxChainHops { - decl := referenceOf(loweringContext, chain.end().decl) - if decl == nil || !decl.Ref.Bound { +// naming it means what its $ref names, written beside other keys too. +func follow(loweringContext lowering.Ctx, start chainNode) valueChain { + chain := valueChain{chainNodes: []chainNode{start}} + for step := range refChain(loweringContext, start.decl) { + if step.from == nil { + continue + } + if !step.from.Ref.Bound { break } - at, ok := landsAt(decl) - next, _ := declaredOf(loweringContext, decl) - linkValue := link{at: at, decl: next} + at, ok := landsAt(step.from) + chainNodeValue := chainNode{at: at, decl: step.statement} if ok { - linkValue.id, ok = declaredAt(loweringContext, linkValue.at, linkValue.decl) + chainNodeValue.id, ok = declaredAt(loweringContext, chainNodeValue.at, chainNodeValue.decl) } if !ok { chain.broken = true break } - chain.links = append(chain.links, linkValue) + chain.chainNodes = append(chain.chainNodes, chainNodeValue) } return chain } -// landsAt returns where the $ref st writes lands, as the compiler resolved -// it: the position its hop reaches (reftable.Hop.Target). It is false for a -// statement writing no $ref the table read, one landing on no schema and one -// on a loop of $refs, which lands nowhere a type can be read. -func landsAt(st *statement.Statement) (reftable.DocumentPointer, bool) { - if st.Ref == nil || !st.Ref.Bound || !st.Ref.Entry.Lands() { +// landsAt returns where the $ref schemaStatement writes lands, as the compiler +// resolved it: the position its hop reaches (reftable.Hop.Target). It is false +// for a statement writing no $ref the table read, one landing on no schema and +// one on a loop of $refs, which lands nowhere a type can be read. +func landsAt(schemaStatement *statement.Statement) (reftable.DocumentPointer, bool) { + if schemaStatement.Ref == nil || !schemaStatement.Ref.Bound || !schemaStatement.Ref.Entry.Lands() { return reftable.DocumentPointer{}, false } - return st.Ref.Entry.Hop.Target, true + return schemaStatement.Ref.Entry.Hop.Target, true } // declaredAt returns the ID of the type declared at at, holding decl, which a @@ -146,9 +139,9 @@ func declaredAt(loweringContext lowering.Ctx, at reftable.DocumentPointer, decl // failing there is lowered and reported where it is written, though only the // mapping reaches it, and recorded as discarded so post-settlement pruning // removes it when nothing else references it. -func hierarchyRoute(loweringContext lowering.Ctx, ts *compile.Types, chain valueChain) (ir.TypeID, bool) { +func hierarchyRoute(loweringContext lowering.Ctx, types *compile.Types, chain valueChain) (ir.TypeID, bool) { end := chain.end() - id, ok := resolveAt(loweringContext, ts, end.at, end.decl) + id, ok := resolveAt(loweringContext, types, end.at, end.decl) if ok && chain.broken { recordDiscarded(loweringContext, id) } @@ -177,48 +170,49 @@ func newBranchIndex(variants []ir.Variant) *branchIndex { several: map[ir.TypeID][]int{}} } -// indexBranches indexes the branches of the union unionAtValue, whose variants +// indexBranches indexes the branches of the union unionSite, whose variants // are built, so the mapping beside it routes to them (route). It reads the // branches and the variants' IDs, never the registry, so no lowering order // reaches an answer. A branch's chain is read as a value's is (follow). -func indexBranches(loweringContext lowering.Ctx, unionAtValue unionAt, variants []ir.Variant) *branchIndex { - branches, key, _ := unionAtValue.branches(loweringContext) +func indexBranches(loweringContext lowering.Ctx, unionSite loweredUnionSite, variants []ir.Variant) *branchIndex { + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) branchIndexValue := newBranchIndex(variants) - branchIndexValue.dead = unionAtValue.deadRoutes - for n, b := range branches { + branchIndexValue.dead = unionSite.deadRoutes + for n, branch := range branches { // A non-null branch lacking its variant is a compiler bug // spellImplicitRoutes reports; it routes nothing here. i := len(branchIndexValue.pointers) - st := loweringContext.Statements().Subschema(b) - if !unionAtValue.variantBranch(loweringContext, n, st) || i == len(variants) { + schemaStatement := loweringContext.Statements().Subschema(branch) + if !unionSite.variantBranch(loweringContext, n, schemaStatement) || i == len(variants) { continue } - vptr := unionAtValue.at + ids.Ptr(key, strconv.Itoa(n)) - branchIndexValue.pointers = append(branchIndexValue.pointers, vptr) + variantPointer := key.branchAt(unionSite.pointer, n) + branchIndexValue.pointers = append(branchIndexValue.pointers, variantPointer) keepFirst(branchIndexValue.is, variants[i].Type.Target, i) - branchIndexValue.key(loweringContext, st, vptr, i) + branchIndexValue.key(loweringContext, schemaStatement, variantPointer, i) } return branchIndexValue } -// key keys st, the branch written at vptr, as i: its own position's declared -// type, and each position its chain of $refs passes. -func (x *branchIndex) key(loweringContext lowering.Ctx, st *statement.Statement, vptr jsontext.Pointer, i int) { - own := loweringContext.Position(vptr) - if id, ok := declaredAt(loweringContext, own, st); ok { +// key keys schemaStatement, the branch written at variantPointer, as i: its own +// position's declared type, and each position its chain of $refs passes. +func (x *branchIndex) key(loweringContext lowering.Ctx, schemaStatement *statement.Statement, variantPointer jsontext.Pointer, i int) { + own := loweringContext.Position(variantPointer) + if id, ok := declaredAt(loweringContext, own, schemaStatement); ok { keepFirst(x.is, id, i) } - for _, linkValue := range follow(loweringContext, link{at: own, decl: st}).links[1:] { - keepFirst(x.passes, linkValue.id, i) - x.several[linkValue.id] = append(x.several[linkValue.id], i) + for _, chainNodeValue := range follow(loweringContext, chainNode{at: own, decl: schemaStatement}).chainNodes[1:] { + keepFirst(x.passes, chainNodeValue.id, i) + x.several[chainNodeValue.id] = append(x.several[chainNodeValue.id], i) } } -// routesDead reports whether the route keyword names, the mapping entry keyed -// tag or the defaultMapping, names a dead branch of the union x indexes. -func (x *branchIndex) routesDead(keyword, tag string) bool { +// routesDead reports whether the route of kind, the mapping entry keyed tag +// or the defaultMapping, names a dead branch of the union x indexes. +func (x *branchIndex) routesDead(kind deadRouteKind, tag string) bool { return x != nil && slices.ContainsFunc(x.dead, func(deadRouteValue deadRoute) bool { - return deadRouteValue.keyword == keyword && deadRouteValue.tag == tag + return deadRouteValue.kind == kind && deadRouteValue.tag == tag }) } @@ -234,12 +228,12 @@ func keepFirst(index map[ir.TypeID]int, id ir.TypeID, i int) { // type it is, else the first whose chain passes it, beside every branch // passing it where several do. It is false where no branch meets the chain. func (x *branchIndex) route(chain valueChain) (int, []int, bool) { - for _, link := range chain.links { - if i, ok := x.is[link.id]; ok { + for _, hop := range chain.chainNodes { + if i, ok := x.is[hop.id]; ok { return i, nil, true } - if i, ok := x.passes[link.id]; ok { - return i, x.several[link.id], true + if i, ok := x.passes[hop.id]; ok { + return i, x.several[hop.id], true } } return 0, nil, false @@ -249,17 +243,17 @@ func (x *branchIndex) route(chain valueChain) (int, []int, bool) { // tag routes to (routeEntry). An entry that routes nowhere is left out, never // given an ID nothing backs (GitHub #14); a mapping left with none is nil, // which routes by type name, and round-trips as written. -func discriminatorMapping(loweringContext lowering.Ctx, ts *compile.Types, discriminator *statement.Discriminator, branchIndexValue *branchIndex, pointer jsontext.Pointer) (map[string]ir.TypeID, []ir.Diagnostic) { +func discriminatorMapping(loweringContext lowering.Ctx, types *compile.Types, discriminator *statement.Discriminator, branchIndexValue *branchIndex, pointer jsontext.Pointer) (map[string]ir.TypeID, []ir.Diagnostic) { if len(discriminator.Mapping) == 0 { return nil, nil } var diags []ir.Diagnostic out := make(map[string]ir.TypeID, len(discriminator.Mapping)) for _, mappingEntry := range discriminator.Mapping { - if branchIndexValue.routesDead("mapping", mappingEntry.Value) { + if branchIndexValue.routesDead(routeByMapping, mappingEntry.Value) { continue } - id, ok, entryDiags := routeEntry(loweringContext, ts, discriminator, branchIndexValue, mappingEntry.Target, "discriminator mapping "+strconv.Quote(mappingEntry.Value), + id, ok, entryDiags := routeEntry(loweringContext, types, discriminator, branchIndexValue, mappingEntry.Target, "discriminator mapping "+strconv.Quote(mappingEntry.Value), pointer+ids.Ptr("discriminator", "mapping", mappingEntry.Value)) diags = append(diags, entryDiags...) if ok { @@ -274,12 +268,12 @@ func discriminatorMapping(loweringContext lowering.Ctx, ts *compile.Types, discr // discriminatorDefault resolves an OpenAPI 3.2 defaultMapping to the type it // routes to, as discriminatorMapping resolves an entry. -func discriminatorDefault(loweringContext lowering.Ctx, ts *compile.Types, discriminator *statement.Discriminator, branchIndexValue *branchIndex, pointer jsontext.Pointer) (ir.TypeID, []ir.Diagnostic) { - dm := discriminator.DefaultMapping - if dm == "" || branchIndexValue.routesDead("defaultMapping", "") { +func discriminatorDefault(loweringContext lowering.Ctx, types *compile.Types, discriminator *statement.Discriminator, branchIndexValue *branchIndex, pointer jsontext.Pointer) (ir.TypeID, []ir.Diagnostic) { + defaultMapping := discriminator.DefaultMapping + if defaultMapping == "" || branchIndexValue.routesDead(routeByDefaultMapping, "") { return "", nil } - id, ok, diags := routeEntry(loweringContext, ts, discriminator, branchIndexValue, dm, "discriminator defaultMapping", pointer+ids.Ptr("discriminator", "defaultMapping")) + id, ok, diags := routeEntry(loweringContext, types, discriminator, branchIndexValue, defaultMapping, "discriminator defaultMapping", pointer+ids.Ptr("discriminator", "defaultMapping")) if !ok { return "", diags } @@ -293,21 +287,20 @@ func discriminatorDefault(loweringContext lowering.Ctx, ts *compile.Types, discr // A value that resolves to no schema is reported here, once; one whose chain // breaks routes nowhere, unreported, as its failing $ref is reported where it // is written. -func routeEntry(loweringContext lowering.Ctx, ts *compile.Types, discriminator *statement.Discriminator, branchIndexValue *branchIndex, value, subject string, +func routeEntry(loweringContext lowering.Ctx, types *compile.Types, discriminator *statement.Discriminator, branchIndexValue *branchIndex, value, subject string, at jsontext.Pointer, ) (ir.TypeID, bool, []ir.Diagnostic) { chain, ok := chainOf(loweringContext, discriminator, value) if !ok { - return "", false, []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.UnresolvedRef, at, - "%s references unresolved schema %q%s", subject, value, mappingWhy(loweringContext, discriminator, value))} + return "", false, valueNamingNothing(loweringContext, discriminator, value, subject, at) } if branchIndexValue == nil { - id, ok := hierarchyRoute(loweringContext, ts, chain) + id, ok := hierarchyRoute(loweringContext, types, chain) return id, ok, nil } i, among, routed := branchIndexValue.route(chain) if !routed { - id, ok := hierarchyRoute(loweringContext, ts, chain) + id, ok := hierarchyRoute(loweringContext, types, chain) return id, ok, nil } if len(among) < 2 { @@ -342,30 +335,14 @@ func mappingWhy(loweringContext lowering.Ctx, discriminator *statement.Discrimin cmp.Or(strings.TrimPrefix(why, ": "), "it names no schema") } -// resolveDiscriminatorRoutes resolves the mapping and defaultMapping values of -// s's discriminator, written at pointer, where no node holds it and it is kept -// verbatim, unread: each value reaches what it names as a reference does, so -// the type each chain ends on is promised a node, and one naming no schema is -// reported at its entry, as on a model. -func resolveDiscriminatorRoutes(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - discriminator := schema.Discriminator() - if discriminator == nil { - return nil - } - mapping, diags := discriminatorMapping(loweringContext, ts, discriminator, nil, pointer) - def, defaultDiags := discriminatorDefault(loweringContext, ts, discriminator, nil, pointer) - recordKeptDiscriminatorRoutes(loweringContext, pointer+ids.Ptr("discriminator"), discriminator, mapping, def) - return append(diags, defaultDiags...) -} - // tagsOf keys the keys each type a discriminator's mapping routes to on a model // (mappingTagsFor). type tagsOf struct { - d *statement.Discriminator + discriminator *statement.Discriminator } // mappingTagsFor returns every key discriminator's mapping spells for the type -// id, sorted in byte order, as the caller elects the first and a mapping's key +// id, sorted in byte order, as the caller chooses the first and a mapping's key // order is no property of the document. They are the keys whose chain ends on // id unbroken, as hierarchyRoute routes them, so a base's Mapping and its // subtypes' tags cannot disagree. Nothing sends the caller to the implicit diff --git a/compilers/openapi/internal/schema/mapping_internal_test.go b/compilers/openapi/internal/schema/mapping_internal_test.go index 4d656b658..272213914 100644 --- a/compilers/openapi/internal/schema/mapping_internal_test.go +++ b/compilers/openapi/internal/schema/mapping_internal_test.go @@ -84,9 +84,9 @@ func TestDeclaredAt_NamesNoUndeclaredComponentOrUnreadDocument(t *testing.T) { unlisted := *loaded unlisted.Others = load.Others{} serviceContext := service.New(0, &unlisted, service.Policy{}) - js, ok := serviceContext.Doc.Components.GetSchemas().Get("Pet") + jsonSchema, ok := serviceContext.Doc.Components.GetSchemas().Get("Pet") require.True(t, ok) - discriminator := (serviceContext.Statements().Of(js).Schema).Discriminator() + discriminator := (serviceContext.Statements().Of(jsonSchema).Schema).Discriminator() require.NotNil(t, discriminator) at, ok := serviceContext.RefScope().MappingTarget(discriminator.At, "./ext.yaml#/X") require.True(t, ok, "the bindings read ext.yaml") diff --git a/compilers/openapi/internal/schema/members.go b/compilers/openapi/internal/schema/members.go index 21da16b30..6b84f0586 100644 --- a/compilers/openapi/internal/schema/members.go +++ b/compilers/openapi/internal/schema/members.go @@ -13,6 +13,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/lowering" "github.com/dexpace/morphic/compilers/openapi/internal/merge" "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" ) // members is the run's record of the models with members to settle, each with @@ -30,6 +31,22 @@ type members struct { // (maxMemberReads), and cut the first model it read none for. reads budget.Budget cut ir.TypeID + // queued says settleMembers is queued, once a run. + queued bool + // reg is the registry the settlement reads, aliases its alias-chain index, + // and aliasChainMemos merge's memos along those chains, built at the first + // model settled, whose fields walk them. + reg ir.TypeRegistry + aliases *ir.AliasChainIndex + aliasChainMemos *merge.AliasChainAnswerMemos + // valueAdmission is the folds' value admission reader over reg and + // aliases (runValueAdmissionReader), built with aliasChainMemos. + valueAdmission *ir.ValueAdmissionReader + // reach answers what the round's composition reaches, from an index over + // the registry as the round reads it, and minted holds the nodes the + // round's folds minted, which it answers from their edges (isComposedOf). + reach *irfacts.DocumentFacts + minted map[ir.TypeID]bool } // membersOf returns the run's record of models with members to settle. @@ -44,11 +61,21 @@ func membersOf(loweringContext lowering.Ctx) *members { // and queues the settlement at the first model noted (settleMembers). The first // fields to note a model place what is minted and reported for it. func (rec *members) note(modelFieldsValue modelFields) { - if len(rec.byID) == 0 { - modelFieldsValue.ts.QueueSettlementBeforeDeferredOnes(settleMembers{c: modelFieldsValue.c}) + if !rec.queued { + modelFieldsValue.types.QueueSettlementBeforeDeferredOnes(settleMembers{loweringContext: modelFieldsValue.loweringContext}) + rec.queued = true } - if _, ok := rec.byID[modelFieldsValue.m.ID]; !ok { - rec.byID[modelFieldsValue.m.ID] = modelFieldsValue + if _, ok := rec.byID[modelFieldsValue.model.ID]; !ok { + rec.byID[modelFieldsValue.model.ID] = modelFieldsValue + } +} + +// forget drops the record of model, which a dry run built and registered +// nowhere (hoistHolding), so the fields of a node built at its ID later are +// the ones noted. A record of another model at that ID stays. +func (rec *members) forget(model *ir.Model) { + if noted, ok := rec.byID[model.ID]; ok && noted.model == model { + delete(rec.byID, model.ID) } } @@ -59,7 +86,7 @@ func (rec *members) note(modelFieldsValue modelFields) { // (compile.Types.QueueSettlementBeforeDeferredOnes), so it reads every node the // walks built and every other settlement reads what it writes. type settleMembers struct { - c lowering.Ctx + loweringContext lowering.Ctx } // maxMemberRounds bounds the rounds Settle reads the record in. A round @@ -67,54 +94,50 @@ type settleMembers struct { // one and read in the next, so each round reads a fold nested one level deeper. const maxMemberRounds = 8 -// maxMemberAliasHops bounds how many alias scalars composed and modelOf read a -// part through (styleguide bounded-everything rule), as maxTagAliasHops bounds -// a tag's. A longer chain, or a loop, stops on an alias, which has no members, -// though the flattening reads on (GitHub #1994). -const maxMemberAliasHops = 64 - // maxMemberReads bounds the declarations the settlement reads of what the // models a model composes say (merge.RedeclaredWireNameTable), summed over the // run (styleguide bounded-everything rule). A table holds only the names more // than one model declares, so a hierarchy costs its depth again at each level // only where every level adds such a name, or composes a model redeclaring one -// it holds, whose declaration may stand within the hierarchy +// it holds, whose declaration may lie within the hierarchy // (merge.Merger.Reads). A read of a model not settled yet, as a cycle's are, // counts the composition its flattening walks too (chargeComposition). Past the // bound each model left settles its own declarations alone. const maxMemberReads = 1 << 24 -// Settle settles each noted model, saying once a conflict every model composing -// its two declarations draws alike (merge.ReportOnce). -func (k settleMembers) Settle(ctx context.Context, reg ir.TypeRegistry) []ir.Diagnostic { - return merge.ReportOnce(k.inRounds(ctx, reg)) +// Settle settles each noted model. What every model composing a member's +// declarations reports alike is said once after pruning (merge.ReportOnce). +func (k settleMembers) Settle(ctx context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + return k.inRounds(ctx, reg, aliases) } // inRounds settles each noted model in rounds, each round in settleOrder, so // every model settles after each noted model it composes, however deep a -// hierarchy nests, and the order models are declared in decides nothing. It -// asks ctx before each model, as one fold may judge 64 declarations pair by -// pair, and returns once it is done: the run then assembles no document. -func (k settleMembers) inRounds(ctx context.Context, reg ir.TypeRegistry) []ir.Diagnostic { - rec := membersOf(k.c) - rec.shared = sharedNames(reg) - sources := k.c.Sources() +// hierarchy nests, and the order models are declared in decides nothing. A +// cyclic component of the round's composition settles as one unit once each of +// its members is reached (settleRound). It asks ctx before each model, as one +// fold may judge 64 declarations pair by pair, and returns once it is done: +// the run then assembles no document. +func (k settleMembers) inRounds(ctx context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + rec := membersOf(k.loweringContext) + rec.shared, rec.reg, rec.aliases = sharedNames(reg), reg, aliases + sources := k.loweringContext.Sources() var diags []ir.Diagnostic for range maxMemberRounds { pending := rec.pending() if len(pending) == 0 { return append(diags, rec.budgetCut()...) } - for _, id := range rec.settleOrder(reg, pending) { - if ctx.Err() != nil { - return diags - } - diags = append(diags, rec.settle(reg, id, sources)...) + rec.reach, rec.minted = irfacts.New(&ir.Document{Types: reg}), map[ir.TypeID]bool{} + roundDiags, done := rec.settleRound(ctx, reg, pending, sources) + diags = append(diags, roundDiags...) + if !done { + return diags } } if pending := rec.pending(); len(pending) > 0 { first := rec.byID[pending[0]] - diags = append(diags, first.c.DiagAt(ir.SeverityError, diag.BudgetExceeded, first.pointer, + diags = append(diags, first.loweringContext.DiagAt(ir.SeverityError, diag.BudgetExceeded, first.pointer, "models composing what a fold composes nest past the %d rounds their members are settled in; %d models "+ "are left as their declarations stand", maxMemberRounds, len(pending))) } @@ -128,7 +151,7 @@ func (rec *members) budgetCut() []ir.Diagnostic { return nil } modelFields := rec.byID[rec.cut] - return []ir.Diagnostic{modelFields.c.DiagAt(ir.SeverityError, diag.BudgetExceeded, modelFields.pointer, + return []ir.Diagnostic{modelFields.loweringContext.DiagAt(ir.SeverityError, diag.BudgetExceeded, modelFields.pointer, "the settlement read past %d declarations and composition entries at this model; it and each model "+ "settled after it fold only their own declarations, not those their entries bring", maxMemberReads)} } @@ -150,9 +173,9 @@ type settleFrame struct { // lists a model once its parts are listed, run on an explicit stack, as a // hierarchy may nest as deep as a document is long. A part already on the path // closes a cycle of compositions, so the model naming it reads it as it -// stands; which model of a cycle settles first follows their IDs, not the +// is; which model of a cycle settles first follows their IDs, not the // order the source declares them in (GitHub #1995). -func (rec *members) settleOrder(reg ir.TypeRegistry, pending []ir.TypeID) []ir.TypeID { +func (rec *members) settleOrder(pending []ir.TypeID) []ir.TypeID { order := make([]ir.TypeID, 0, len(pending)) seen := make(map[ir.TypeID]bool, len(pending)) for _, root := range pending { @@ -160,7 +183,7 @@ func (rec *members) settleOrder(reg ir.TypeRegistry, pending []ir.TypeID) []ir.T continue } seen[root] = true - path := []settleFrame{{id: root, parts: rec.composed(reg, root)}} + path := []settleFrame{{id: root, parts: rec.composed(root)}} for len(path) > 0 { top := &path[len(path)-1] if len(top.parts) == 0 { @@ -172,89 +195,199 @@ func (rec *members) settleOrder(reg ir.TypeRegistry, pending []ir.TypeID) []ir.T top.parts = top.parts[1:] if !seen[part] && !rec.settled[part] { seen[part] = true - path = append(path, settleFrame{id: part, parts: rec.composed(reg, part)}) + path = append(path, settleFrame{id: part, parts: rec.composed(part)}) } } } return order } +// settleRound settles pending in settleOrder: a model alone in its strongly +// connected component of the composition where settleOrder reaches it, and a +// cyclic component's members together once it has reached every one. It +// reports false where ctx ended the round. +func (rec *members) settleRound(ctx context.Context, reg ir.TypeRegistry, pending []ir.TypeID, sources []ir.SourceInfo) ([]ir.Diagnostic, bool) { + components := irfacts.CompositionStronglyConnectedComponents(reg, pending) + componentOf, unsettled := make(map[ir.TypeID]int, len(pending)), make([]int, len(components)) + for componentIndex, component := range components { + for _, id := range component { + componentOf[id] = componentIndex + } + unsettled[componentIndex] = len(component) + } + var diags []ir.Diagnostic + for _, id := range rec.settleOrder(pending) { + if ctx.Err() != nil { + return diags, false + } + componentIndex := componentOf[id] + if unsettled[componentIndex]--; len(components[componentIndex]) < 2 { + diags = append(diags, rec.settle(reg, id, sources)...) + } else if unsettled[componentIndex] == 0 { + diags = append(diags, rec.settleCycle(reg, components[componentIndex], sources)...) + } + } + return diags, true +} + // settle settles the model id names, reading each model it composes as it -// stands, which settleOrder puts first. A tag reading reads the members it -// settles (tagReadings), so one stored before it is a compiler bug, reported at +// is, which settleOrder puts first. A tag reading reads the members it +// settles (tagSetMemo), so one stored before it is a compiler bug, reported at // the model. func (rec *members) settle(reg ir.TypeRegistry, id ir.TypeID, sources []ir.SourceInfo) []ir.Diagnostic { rec.settled[id] = true modelFields := rec.byID[id] - trackers := runTrackersOf(modelFields.c) - merger := merge.Merger{ - Reg: reg, - IDs: modelFields.c.IDs(), - Doc: modelFields.c.Place(), - Sources: sources, - Reads: &rec.reads, - PrunedDiagnostics: &trackers.prunedDiagnostics, - Discarded: trackers.discarded, - DiscardedSites: &trackers.discardedSites, - Walk: modelFields, - } - diags, table := modelFields.idx.Settle(merger, rec.partTables(reg, modelFields.m), rec.shared) + diags, table := modelFields.idx.Settle(rec.mergerFor(reg, modelFields, sources), rec.partTables(reg, modelFields.model, nil), rec.shared) rec.tables[id] = table rec.cutAt(id) - if readingsOf(modelFields.c).stored() { - diags = append(diags, modelFields.c.DiagAt(ir.SeverityError, diag.InternalInvariant, modelFields.pointer, - "internal: the model's members settle after a discriminator-inference reading is stored, which may "+ - "have read them unsettled")) + return append(diags, rec.readBefore(modelFields)...) +} + +// settleCycle settles the members of component, a cyclic component of the +// composition, as one unit (merge.SettleCompositionCycle), through a Merger +// built for its member of least ID, reading the table of each model they +// compose outside it. +func (rec *members) settleCycle(reg ir.TypeRegistry, component []ir.TypeID, sources []ir.SourceInfo) []ir.Diagnostic { + ids := slices.Sorted(slices.Values(component)) + inComponent := map[ir.TypeID]bool{} + declarations := make([]*merge.ModelPropertyDeclarations, len(ids)) + for i, id := range ids { + rec.settled[id], inComponent[id] = true, true + declarations[i] = rec.byID[id].idx + } + tables := map[ir.TypeID]merge.RedeclaredWireNameTable{} + for _, id := range ids { + maps.Copy(tables, rec.partTables(reg, rec.byID[id].model, inComponent)) + } + least := rec.byID[ids[0]] + diags, settled := merge.SettleCompositionCycle(declarations, rec.mergerFor(reg, least, sources), tables, rec.shared) + maps.Copy(rec.tables, settled) + rec.cutAt(least.model.ID) + return append(diags, rec.readBefore(least)...) +} + +// mergerFor returns the Merger the model modelFieldsValue builds settles +// through, reading the run's alias chains through the readings built at the +// first model settled. +func (rec *members) mergerFor(reg ir.TypeRegistry, modelFieldsValue modelFields, sources []ir.SourceInfo) merge.Merger { + if rec.aliasChainMemos == nil { + rec.aliasChainMemos = merge.NewAliasChainAnswerMemos(reg.Lookup, rec.aliases, modelFieldsValue) + } + trackers := runTrackersOf(modelFieldsValue.loweringContext) + return merge.Merger{ + Reg: reg, + IDs: modelFieldsValue.loweringContext.IDs(), + Doc: modelFieldsValue.loweringContext.Place(), + Sources: sources, + AliasChainAnswerMemos: rec.aliasChainMemos, + ValueAdmissionReader: runValueAdmissionReader(rec, reg), + Discarded: trackers.discarded, + DiscardedSites: &trackers.discardedSites, + Walk: modelFieldsValue, + } +} + +// runValueAdmissionReader returns the run's value admission reader, which each +// fold's is Fresh of, built at first use so a chain or an enum many folds' +// values read is read once. +func runValueAdmissionReader(rec *members, reg ir.TypeRegistry) *ir.ValueAdmissionReader { + if rec.valueAdmission == nil { + rec.valueAdmission = merge.NewFoldValueAdmissionReader(reg.Lookup, rec.aliases) + } + return rec.valueAdmission +} + +// readBefore reports, at the model modelFieldsValue builds, a tag reading +// stored before its members settled: a tag reading reads the members it +// settles (tagSetMemo), so one stored before it is a compiler bug. +func (rec *members) readBefore(modelFieldsValue modelFields) []ir.Diagnostic { + if !tagSetMemoOf(modelFieldsValue.loweringContext).stored() { + return nil + } + return []ir.Diagnostic{modelFieldsValue.loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, modelFieldsValue.pointer, + "internal: the model's members settle after a discriminator-inference reading is stored, which may "+ + "have read them unsettled")} +} + +// isComposedOf reports whether id is composed of target: a node a fold of the +// round minted, which the round's reach index may not hold, through its +// ir.ComposedOf edges, and every other node through the index. +func (rec *members) isComposedOf(id, target ir.TypeID) bool { + if !rec.minted[id] { + return rec.reach.CompositionReaches(id, target) + } + seen := map[ir.TypeID]bool{id: true} + for queue := []ir.TypeID{id}; len(queue) > 0; queue = queue[1:] { + for _, part := range ir.ComposedOf(rec.reg[queue[0]]) { + switch { + case part == target: + return true + case rec.minted[part]: + if !seen[part] { + seen[part] = true + queue = append(queue, part) + } + case rec.reach.CompositionReaches(part, target): + return true + } + } + } + return false +} + +// mint records id, a node a fold of the round minted (modelFields.Mint), which +// the round's reach index may not hold. +func (rec *members) mint(id ir.TypeID) { + if rec.minted != nil { + rec.minted[id] = true } - return diags } // composed returns the noted models id's composition reaches through alias // scalars, by ID. -func (rec *members) composed(reg ir.TypeRegistry, id ir.TypeID) []ir.TypeID { +func (rec *members) composed(id ir.TypeID) []ir.TypeID { var out []ir.TypeID - for _, part := range merge.ComposedOf(rec.byID[id].m) { - for range maxMemberAliasHops { - if _, noted := rec.byID[part]; noted { - out = append(out, part) - break - } - scalar, isAlias := reg[part].(*ir.Scalar) - if !isAlias || scalar.Base == nil { - break - } - part = scalar.Base.Target + for _, part := range ir.ComposedOf(rec.byID[id].model) { + if _, noted := rec.byID[part]; !noted { + part, _ = rec.aliases.End(part) + } + if _, noted := rec.byID[part]; noted { + out = append(out, part) } } slices.Sort(out) return slices.Compact(out) } -// partTables returns the Table of each type model composes (merge.ComposedOf), -// read for model (tableOf). -func (rec *members) partTables(reg ir.TypeRegistry, model *ir.Model) map[ir.TypeID]merge.RedeclaredWireNameTable { +// partTables returns the Table of each type model composes (ir.ComposedOf), +// read for model (tableOf), but those naming a model of within, which settles +// beside it. +func (rec *members) partTables(reg ir.TypeRegistry, model *ir.Model, within map[ir.TypeID]bool) map[ir.TypeID]merge.RedeclaredWireNameTable { out := map[ir.TypeID]merge.RedeclaredWireNameTable{} - for _, target := range merge.ComposedOf(model) { + for _, target := range ir.ComposedOf(model) { + if id, isModel := rec.modelOf(reg, target); isModel && within[id] { + continue + } out[target] = rec.tableOf(reg, target, model.ID) } return out } // tableOf returns the table of the model target names through alias scalars, -// charged to the run's reads: the one its settlement left, or, for a model -// not settled yet, which a cycle reaches or the walks did not note, what its -// flattening takes as it stands but from's (asItStands). A model the walks did -// not note composes nothing, so its table is kept. It returns none once the +// charged to the run's reads: the one its settlement left, or, for a model not +// settled yet, which a cycle reaches or the walks did not note, what its +// flattening takes as it is but from's (asRegistered). A model the walks +// did not note composes nothing, so its table is kept. It returns none once the // reads run out, and none for a type naming no model. func (rec *members) tableOf(reg ir.TypeRegistry, target, from ir.TypeID) merge.RedeclaredWireNameTable { - id, isModel := modelOf(reg, target) + id, isModel := rec.modelOf(reg, target) if !isModel || rec.reads.Exhausted() { rec.cutAt(from) return nil } table, kept := rec.tables[id] if !kept { - table = rec.asItStands(reg, id, from) + table = rec.asRegistered(reg, id, from) if _, noted := rec.byID[id]; !noted { rec.tables[id] = table } @@ -274,30 +407,19 @@ func (rec *members) cutAt(from ir.TypeID) { } } -// modelOf returns the model target names through alias scalars, and false -// where it names none within maxMemberAliasHops. -func modelOf(reg ir.TypeRegistry, target ir.TypeID) (ir.TypeID, bool) { - for range maxMemberAliasHops { - switch td := reg[target].(type) { - case *ir.Model: - return target, true - case *ir.Scalar: - if td.Base == nil { - return "", false - } - target = td.Base.Target - default: - return "", false - } - } - return "", false +// modelOf returns the model target names through alias scalars, read through +// the run's index however long the chain, and false where it names none. +func (rec *members) modelOf(reg ir.TypeRegistry, target ir.TypeID) (ir.TypeID, bool) { + end, _ := rec.aliases.End(target) + _, isModel := reg[end].(*ir.Model) + return end, isModel } -// asItStands returns the table of the model id as reg holds it: for each name +// asRegistered returns the table of the model id as reg holds it: for each name // more than one model declares, the declaration its flattening takes but // from's (merge.TakenOutside), charging what the flattening walks and reads. // It returns none once the reads run out. -func (rec *members) asItStands(reg ir.TypeRegistry, id, from ir.TypeID) merge.RedeclaredWireNameTable { +func (rec *members) asRegistered(reg ir.TypeRegistry, id, from ir.TypeID) merge.RedeclaredWireNameTable { if !rec.chargeComposition(reg, id) { return nil } @@ -330,7 +452,7 @@ func (rec *members) declared(propertyDecl ir.PropertyDecl) merge.Declared { func (rec *members) chargeComposition(reg ir.TypeRegistry, id ir.TypeID) bool { seen := map[ir.TypeID]bool{id: true} for queue := []ir.TypeID{id}; len(queue) > 0; { - parts := merge.ComposedOf(reg[queue[len(queue)-1]]) + parts := ir.ComposedOf(reg[queue[len(queue)-1]]) queue = queue[:len(queue)-1] if !rec.reads.Spend(1 + len(parts)) { return false @@ -349,8 +471,8 @@ func (rec *members) chargeComposition(reg ir.TypeRegistry, id ir.TypeID) bool { // model counted once: a name one model alone declares decides no member twice. func sharedNames(reg ir.TypeRegistry) map[string]bool { first, shared := map[string]ir.TypeID{}, map[string]bool{} - for id, td := range reg { - model, isModel := td.(*ir.Model) + for id, typeDef := range reg { + model, isModel := typeDef.(*ir.Model) if !isModel { continue } diff --git a/compilers/openapi/internal/schema/members_internal_test.go b/compilers/openapi/internal/schema/members_internal_test.go index 1ef3930b8..093038ca5 100644 --- a/compilers/openapi/internal/schema/members_internal_test.go +++ b/compilers/openapi/internal/schema/members_internal_test.go @@ -38,24 +38,24 @@ func settledUnder(t *testing.T, schemas string, limit budget.Limit) (*ir.Documen // number, and declaring a member of its own: a name no other model declares, // or, where shared, one an unrelated model declares too. func hierarchy(n int, wide, shared bool) string { - var b strings.Builder - b.WriteString(" A0: {type: object, properties: {x: {type: integer}}}\n") + var builder strings.Builder + builder.WriteString(" A0: {type: object, properties: {x: {type: integer}}}\n") if shared { - b.WriteString(" U: {type: object, properties: {") + builder.WriteString(" U: {type: object, properties: {") for i := 1; i < n; i++ { - fmt.Fprintf(&b, "m%d: {type: string}, ", i) + fmt.Fprintf(&builder, "m%d: {type: string}, ", i) } - b.WriteString("}}\n") + builder.WriteString("}}\n") } for i := 1; i < n; i++ { entries := fmt.Sprintf("{$ref: '#/components/schemas/A%d'}", i-1) if wide { entries += ", {$ref: '#/components/schemas/A0'}" } - fmt.Fprintf(&b, " A%d: {allOf: [%s, {type: object, properties: {x: {type: number}, m%d: {type: string}}}]}\n", + fmt.Fprintf(&builder, " A%d: {allOf: [%s, {type: object, properties: {x: {type: number}, m%d: {type: string}}}]}\n", i, entries, i) } - return b.String() + return builder.String() } // TestMembers_ADeclarationASettledModelHoldsKeepsWhereItsTypeIsWritten pins @@ -150,14 +150,15 @@ func TestMembers_ReadsAPartThroughItsAliasesAndNothingElse(t *testing.T) { "type/u": &ir.Union{ID: "type/u"}, } rec := &members{byID: map[ir.TypeID]modelFields{"type/N": {}}, settled: map[ir.TypeID]bool{}, - tables: map[ir.TypeID]merge.RedeclaredWireNameTable{}, shared: map[string]bool{"p": true}, reads: budget.New(budget.Unbounded())} + tables: map[ir.TypeID]merge.RedeclaredWireNameTable{}, shared: map[string]bool{"p": true}, reads: budget.New(budget.Unbounded()), + aliases: ir.NewAliasChainIndex(reg.Lookup)} got := rec.tableOf(reg, "type/alias", "type/X") require.Len(t, got, 1, "q is declared once") assert.Equal(t, ir.TypeID("type/M"), got["p"].Owner) assert.Contains(t, rec.tables, ir.TypeID("type/M"), "a model the walks did not note is read once") assert.Len(t, rec.tableOf(reg, "type/N", "type/X"), 1) - assert.NotContains(t, rec.tables, ir.TypeID("type/N"), "a noted model is read as it stands until settled") + assert.NotContains(t, rec.tables, ir.TypeID("type/N"), "a noted model is read as it is until settled") for _, target := range []ir.TypeID{"type/loop", "type/bare", "type/u", "type/missing"} { assert.Nil(t, rec.tableOf(reg, target, "type/X"), target) } @@ -165,7 +166,7 @@ func TestMembers_ReadsAPartThroughItsAliasesAndNothingElse(t *testing.T) { } // TestMembers_ReadingAModelNotSettledChargesItsComposition pins what reading a -// model as it stands costs: its flattening walks each type its composition +// model as it is costs: its flattening walks each type its composition // reaches and each entry naming one, besides the declarations it reads, so // the reads charge both. N composes M through an alias and M2 beside it: four // types, three entries, one name read with its two overridden declarations, @@ -183,7 +184,8 @@ func TestMembers_ReadingAModelNotSettledChargesItsComposition(t *testing.T) { "type/M2": &ir.Model{ID: "type/M2", Properties: []ir.Property{property("property/M2")}}, } rec := &members{byID: map[ir.TypeID]modelFields{"type/N": {}}, settled: map[ir.TypeID]bool{}, - tables: map[ir.TypeID]merge.RedeclaredWireNameTable{}, shared: map[string]bool{"p": true}, reads: budget.New(budget.Unbounded())} + tables: map[ir.TypeID]merge.RedeclaredWireNameTable{}, shared: map[string]bool{"p": true}, reads: budget.New(budget.Unbounded()), + aliases: ir.NewAliasChainIndex(reg.Lookup)} require.Len(t, rec.tableOf(reg, "type/N", "type/X"), 1) assert.Equal(t, 4+3+3+1, rec.reads.Spent(), "types, entries, declarations and the table's entry") @@ -192,22 +194,22 @@ func TestMembers_ReadingAModelNotSettledChargesItsComposition(t *testing.T) { // deepLeaf is Leaf, redeclaring the id Base declares through a chain of depth // models above Base, and M, composing Leaf and Base again. func deepLeaf(depth int) string { - var b strings.Builder - b.WriteString(" Base: {type: object, properties: {id: {type: integer, description: base}}}\n") + var builder strings.Builder + builder.WriteString(" Base: {type: object, properties: {id: {type: integer, description: base}}}\n") below := "Base" for i := 1; i <= depth; i++ { - fmt.Fprintf(&b, " L%d: {allOf: [{$ref: '#/components/schemas/%s'}]}\n", i, below) + fmt.Fprintf(&builder, " L%d: {allOf: [{$ref: '#/components/schemas/%s'}]}\n", i, below) below = fmt.Sprintf("L%d", i) } - fmt.Fprintf(&b, " Leaf: {allOf: [{$ref: '#/components/schemas/%s'}, "+ + fmt.Fprintf(&builder, " Leaf: {allOf: [{$ref: '#/components/schemas/%s'}, "+ "{type: object, properties: {id: {type: integer, description: leaf, minimum: 5}}}]}\n", below) - b.WriteString(" M: {allOf: [{$ref: '#/components/schemas/Leaf'}, {$ref: '#/components/schemas/Base'}]}\n") - return b.String() + builder.WriteString(" M: {allOf: [{$ref: '#/components/schemas/Leaf'}, {$ref: '#/components/schemas/Base'}]}\n") + return builder.String() } // TestMembers_ABaseComposedBesideItsHierarchyBringsNothingAtAnyDepth pins a // model composing a hierarchy and its base again: the base's declaration -// stands within the hierarchy however deep it nests, so the model declares +// sits within the hierarchy however deep it nests, so the model declares // nothing, reports nothing, and its flattening takes Leaf's declaration. func TestMembers_ABaseComposedBesideItsHierarchyBringsNothingAtAnyDepth(t *testing.T) { t.Parallel() @@ -227,15 +229,15 @@ func TestMembers_ABaseComposedBesideItsHierarchyBringsNothingAtAnyDepth(t *testi } } -// TestMembers_ACutTellingDeclarationsApartIsReported pins the bound on telling -// whether one part's declaration stands within another's composition: it -// spends the run's reads, and where they run out there, in the last model to -// settle, the cut is reported at that model. -func TestMembers_ACutTellingDeclarationsApartIsReported(t *testing.T) { +// TestMembers_ACutIsReportedAtTheModelReadingPastIt pins where the run's reads +// run out: reading the tables of the models a model composes spends them, so a +// run one read short is cut at the last model to settle, M, reading Base's +// table after Leaf's, and reports the cut there. +func TestMembers_ACutIsReportedAtTheModelReadingPastIt(t *testing.T) { t.Parallel() _, _, all := settledUnder(t, deepLeaf(200), budget.Unbounded()) - _, diags, _ := settledUnder(t, deepLeaf(200), budget.AtMost(all-50)) + _, diags, _ := settledUnder(t, deepLeaf(200), budget.AtMost(all-1)) assert.Equal(t, []jsontext.Pointer{"/components/schemas/M"}, openapitest.PointersOf(diags, diag.BudgetExceeded), "%+v", diags) } @@ -243,49 +245,51 @@ func TestMembers_ACutTellingDeclarationsApartIsReported(t *testing.T) { // twoDeepLeaves is deepLeaf twice over, for x over BaseX and y over BaseY, and M // composing both hierarchies and both bases again. func twoDeepLeaves(depth int) string { - var b strings.Builder + var builder strings.Builder for _, name := range []string{"X", "Y"} { - fmt.Fprintf(&b, " Base%s: {type: object, properties: {%s: {type: integer}}}\n", name, strings.ToLower(name)) + fmt.Fprintf(&builder, " Base%s: {type: object, properties: {%s: {type: integer}}}\n", name, strings.ToLower(name)) below := "Base" + name for i := 1; i <= depth; i++ { - fmt.Fprintf(&b, " L%s%d: {allOf: [{$ref: '#/components/schemas/%s'}]}\n", name, i, below) + fmt.Fprintf(&builder, " L%s%d: {allOf: [{$ref: '#/components/schemas/%s'}]}\n", name, i, below) below = fmt.Sprintf("L%s%d", name, i) } - fmt.Fprintf(&b, " Leaf%s: {allOf: [{$ref: '#/components/schemas/%s'}, "+ + fmt.Fprintf(&builder, " Leaf%s: {allOf: [{$ref: '#/components/schemas/%s'}, "+ "{type: object, properties: {%s: {type: integer, minimum: 5}}}]}\n", name, below, strings.ToLower(name)) } - b.WriteString(" M: {allOf: [{$ref: '#/components/schemas/LeafX'}, {$ref: '#/components/schemas/BaseX'}, " + + builder.WriteString(" M: {allOf: [{$ref: '#/components/schemas/LeafX'}, {$ref: '#/components/schemas/BaseX'}, " + "{$ref: '#/components/schemas/LeafY'}, {$ref: '#/components/schemas/BaseY'}]}\n") - return b.String() + return builder.String() } -// TestMembers_ACutTellingDeclarationsApartFallsAlikeInEveryRun pins the order -// a settlement asks of its names: where the reads run out between two names' -// walks, the same name is cut in every run, so the document does not follow -// the order a map yields them in. -func TestMembers_ACutTellingDeclarationsApartFallsAlikeInEveryRun(t *testing.T) { +// TestMembers_ACutFallsAlikeInEveryRun pins the order a settlement reads its +// models' tables in: where the reads run out short of the end, the same model +// is cut, and the same names declared, in every run, so the document does not +// follow the order a map yields them in. +func TestMembers_ACutFallsAlikeInEveryRun(t *testing.T) { t.Parallel() _, _, all := settledUnder(t, twoDeepLeaves(100), budget.Unbounded()) - declared := func() []string { - doc, _, _ := settledUnder(t, twoDeepLeaves(100), budget.AtMost(all-60)) + cut := func() ([]jsontext.Pointer, []string) { + doc, diags, _ := settledUnder(t, twoDeepLeaves(100), budget.AtMost(all-60)) model, ok := doc.Types["type/openapi/components/schemas/M"].(*ir.Model) require.True(t, ok) wires := make([]string, 0, len(model.Properties)) for _, property := range model.Properties { wires = append(wires, property.WireName) } - return wires + return openapitest.PointersOf(diags, diag.BudgetExceeded), wires } - first := declared() - require.Len(t, first, 1, "the cut walk leaves one name's candidates both in") + firstCut, firstWires := cut() + require.Len(t, firstCut, 1, "the reads run out once") for range 30 { - assert.Equal(t, first, declared()) + at, wires := cut() + assert.Equal(t, firstCut, at) + assert.Equal(t, firstWires, wires) } } // clique is n models each composing every other, each declaring x. func clique(n int) string { - var b strings.Builder + var builder strings.Builder for i := range n { var entries []string for j := range n { @@ -293,28 +297,29 @@ func clique(n int) string { entries = append(entries, fmt.Sprintf("{$ref: '#/components/schemas/K%d'}", j)) } } - fmt.Fprintf(&b, " K%d: {allOf: [%s, {type: object, properties: {x: {type: integer}}}]}\n", i, strings.Join(entries, ", ")) + fmt.Fprintf(&builder, " K%d: {allOf: [%s, {type: object, properties: {x: {type: integer}}}]}\n", i, strings.Join(entries, ", ")) } - return b.String() + return builder.String() } -// TestMembers_ACycleIsChargedTheCompositionsItsReadsWalk pins the bound on a -// cycle of compositions: a model of it is read as it stands by each settled -// before it, each read walking every entry of the cycle, so the reads grow -// with the square of its entries, faster than the declarations they find, -// and a cycle dense enough is cut at the bound and reported once. -func TestMembers_ACycleIsChargedTheCompositionsItsReadsWalk(t *testing.T) { +// TestMembers_ACycleReadsNoMemberAsItIs pins a cycle of compositions +// settled as one unit: no model of it reads another as it is, so a clique of +// 6 or 12 models, each composing every other, spends none of the run's reads, +// settles under a budget of none without a cut, and gives every model one x. +func TestMembers_ACycleReadsNoMemberAsItIs(t *testing.T) { t.Parallel() - read := func(n int) int { - _, diags, reads := settledUnder(t, clique(n), budget.Unbounded()) + for _, n := range []int{6, 12} { + doc, diags, reads := settledUnder(t, clique(n), budget.AtMost(0)) + openapitest.RequireNoErrorDiags(t, diags) - return reads + assert.Zero(t, reads, "%d models", n) + for i := range n { + model, ok := doc.Types[ir.TypeID(fmt.Sprintf("type/openapi/components/schemas/K%d", i))].(*ir.Model) + require.True(t, ok) + require.Len(t, model.Properties, 1, "%d models: K%d", n, i) + assert.Equal(t, "x", model.Properties[0].WireName) + } } - a, b := read(6), read(12) - assert.GreaterOrEqual(t, b, 12*a, "reads at 6 and 12 models: %d, %d", a, b) - - _, diags, _ := settledUnder(t, clique(12), budget.AtMost(b/2)) - assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.BudgetExceeded, ir.SeverityError), "%+v", diags) } // TestMembers_TheSettlementAsksItsContextBeforeEachModel pins where a cancel diff --git a/compilers/openapi/internal/schema/members_reach_internal_test.go b/compilers/openapi/internal/schema/members_reach_internal_test.go new file mode 100644 index 000000000..f09612fbe --- /dev/null +++ b/compilers/openapi/internal/schema/members_reach_internal_test.go @@ -0,0 +1,199 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/merge" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" +) + +// freshPartEachLevel is n levels, each A(i) composing A(i-1) and a part X(i) +// of its own that redeclares x with a maximum of its own, A0 declaring x a +// number: each level's fold meets a declaration no level below it brings. +func freshPartEachLevel(n int) string { + var builder strings.Builder + builder.WriteString(" A0: {type: object, properties: {x: {type: number}}}\n") + for i := 1; i < n; i++ { + fmt.Fprintf(&builder, " X%d: {type: object, properties: {x: {type: number, maximum: %d}}}\n", i, 100000-i) + fmt.Fprintf(&builder, " A%d: {allOf: [{$ref: '#/components/schemas/A%d'}, {$ref: '#/components/schemas/X%d'}]}\n", i, i-1, i) + } + return builder.String() +} + +// TestMembers_ReadsGrowLinearlyWhereEachLevelBringsAFreshPart pins the +// settlement's reads where telling one part's declaration from another's +// asks what each composes: answered from the settlement's reach index, the reads +// grow linearly with the levels, where walking each candidate's composition +// until it met the others read 2n², and the top level holds every level's +// maximum met. +func TestMembers_ReadsGrowLinearlyWhereEachLevelBringsAFreshPart(t *testing.T) { + t.Parallel() + var reads [3]int + for k, n := range []int{100, 200, 400} { + doc, diags, spent := settledUnder(t, freshPartEachLevel(n), budget.Unbounded()) + openapitest.RequireNoErrorDiags(t, diags) + top, ok := doc.Types[ir.TypeID(fmt.Sprintf("type/openapi/components/schemas/A%d", n-1))].(*ir.Model) + require.True(t, ok) + var held *ir.Constraints + for _, property := range top.Properties { + if property.WireName == "x" { + held = property.Constraints + } + } + require.NotNil(t, held, "at %d levels the top level folds x", n) + require.NotNil(t, held.Max) + assert.Equal(t, ir.BigVal(fmt.Sprint(100000-(n-1))), *held.Max, "at %d levels: every level's maximum met", n) + reads[k] = spent + } + assert.LessOrEqual(t, float64(reads[2]-reads[1]), 2.5*float64(reads[1]-reads[0]), "reads at 100, 200, 400 levels: %v", reads) +} + +// TestMembers_AModelMintedThisRoundIsComposedOfItsParts pins the reach a fold +// asks of a node another fold of the same round minted, which the round's +// index may not hold, read from its own edges and those of each minted node +// they name: M1 folds f into a model composing A and B; N and M2, composing M1 +// and redeclaring f as A and as Z, keep it, as it is composed of A and of Z +// through A; M3, redeclaring it as D, which it is not composed of, folds a +// model composing both; and M4 one composing that and E. Nothing is reported. +func TestMembers_AModelMintedThisRoundIsComposedOfItsParts(t *testing.T) { + t.Parallel() + refining := func(name, part, field string) string { + return fmt.Sprintf(" %s: {allOf: [{$ref: '#/components/schemas/%s'}, {type: object, properties: {f: {$ref: '#/components/schemas/%s'}}}]}\n", + name, part, field) + } + doc, diags, _ := settledUnder(t, ` Z: {type: object, properties: {z: {type: string}}} + A: {allOf: [{$ref: '#/components/schemas/Z'}], type: object, properties: {a: {type: string}}} + B: {type: object, properties: {b: {type: string}}} + D: {type: object, properties: {d: {type: string}}} + E: {type: object, properties: {e: {type: string}}} + M1: {allOf: [{type: object, properties: {f: {$ref: '#/components/schemas/A'}}}, {type: object, properties: {f: {$ref: '#/components/schemas/B'}}}]} +`+refining("N", "M1", "A")+refining("M2", "M1", "Z")+refining("M3", "M2", "D")+refining("M4", "M3", "E"), budget.Unbounded()) + + openapitest.RequireNoErrorDiags(t, diags) + fieldOf := func(name string) ir.TypeID { + flat := ir.FlattenedProperties(doc.Types, componentType(name)) + member, ok := flatMember(flat, "f") + require.True(t, ok, name) + return member.Property.Type.Target + } + composes := func(name string, parts ...ir.TypeID) { + t.Helper() + model, ok := doc.Types[fieldOf(name)].(*ir.Model) + require.True(t, ok, "%s's f is a model: %s", name, fieldOf(name)) + for _, part := range parts { + assert.True(t, irfacts.New(doc).CompositionReaches(model.ID, part), "%s's f composes %s", name, part) + } + } + composes("M1", componentType("A"), componentType("B")) + assert.Equal(t, fieldOf("M1"), fieldOf("N"), "N keeps M1's, composed of A") + assert.Equal(t, fieldOf("M1"), fieldOf("M2"), "M2 keeps M1's, composed of Z") + composes("M3", fieldOf("M1"), componentType("D")) + composes("M4", fieldOf("M3"), componentType("E")) + for _, diagnostic := range diags { + assert.NotContains(t, []string{"N", "M1", "M2", "M3", "M4"}, strings.TrimPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"), + "%+v", diagnostic) + } +} + +// componentType is the ID of the component schema name. +func componentType(name string) ir.TypeID { + return ir.TypeID("type/openapi/components/schemas/" + name) +} + +// TestMembers_ASelfComposingModelIsCutWhereItsReadRunsOut pins the one read a +// model's own composition still costs where it composes itself, a component of +// one: read as it is, charged its composition, so a run of no reads cuts it +// there, reported at the model. +func TestMembers_ASelfComposingModelIsCutWhereItsReadRunsOut(t *testing.T) { + t.Parallel() + _, diags, _ := settledUnder(t, " A: {allOf: [{$ref: '#/components/schemas/A'}, {type: object, properties: {x: {type: integer}}}], "+ + "properties: {x: {type: number}}}\n", budget.AtMost(0)) + + assert.Equal(t, []jsontext.Pointer{"/components/schemas/A"}, openapitest.PointersOf(diags, diag.BudgetExceeded), "%+v", diags) +} + +// TestModelFields_ASourceNoDocumentRecordsIsNotPlaced pins a site whose Source +// no document the compile read records: no node sits there, it admits +// nothing, exactly or not, and it takes part in no discriminator hierarchy. +func TestModelFields_ASourceNoDocumentRecordsIsNotPlaced(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " A: {type: string}\n")) + fields := modelFields{loweringContext: lowerer.Ctx, types: lowerer.Types} + at := ir.Provenance{Source: 7, Pointer: "/components/schemas/A"} + + assert.False(t, fields.Interned(at)) + admits, exact := fields.Admits(at, merge.InstanceString) + assert.Equal(t, merge.AdmitsSomeOfKind, admits) + assert.False(t, exact) + assert.False(t, fields.InDiscriminatorHierarchy(at)) +} + +// TestModelFields_AdmitsReadsEverySomeOrNoneOfAKind pins what the fold reads +// of a source against a kind's instances: every one, none, or some, null among +// them, exactly, a note beside a `not`'s type saying nothing; a `not` of more +// than a type, or of a $ref, is read inexactly. An `if` sends a kind its +// condition admits whole to `then`, one it admits none of to `else`, and any +// other to either; a `false` branch admits none, a `true` one every one. No row +// contradicts a validator. +func TestModelFields_AdmitsReadsEverySomeOrNoneOfAKind(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " NotStr: {not: {type: string}}\n"+ + " Min: {minimum: 5}\n Loose: {not: {type: string, minLength: 1}}\n"+ + " NotRef: {not: {$ref: '#/components/schemas/Min'}}\n NotNoted: {not: {type: string, description: d}}\n"+ + " IfStr: {if: {type: string}, then: {type: string}, else: {type: integer}}\n"+ + " IfReq: {if: {required: [k]}, then: {type: object}, else: {type: integer}}\n"+ + " IfMin: {if: {minimum: 3}, then: {type: object}, else: {type: integer}}\n"+ + " IfLoose: {if: {not: {minLength: 1}}, then: {type: string}, else: {type: integer}}\n"+ + " IfFalse: {if: {minimum: 0}, then: false, else: {type: string}}\n"+ + " IfTrue: {if: {minimum: 0}, then: true, else: {type: string}}\n")) + fields := modelFields{loweringContext: lowerer.Ctx, types: lowerer.Types} + for _, testCase := range []struct { + name string + kind merge.JSONInstanceKind + want merge.KindAdmission + exact bool + }{ + {"NotStr", merge.InstanceString, merge.AdmitsNoneOfKind, true}, + {"NotStr", merge.InstanceInteger, merge.AdmitsEveryOfKind, true}, + {"NotStr", merge.InstanceNull, merge.AdmitsSomeOfKind, true}, + {"Min", merge.InstanceInteger, merge.AdmitsSomeOfKind, true}, + {"Loose", merge.InstanceInteger, merge.AdmitsSomeOfKind, false}, + {"NotRef", merge.InstanceInteger, merge.AdmitsSomeOfKind, false}, + {"NotNoted", merge.InstanceString, merge.AdmitsNoneOfKind, true}, + {"IfStr", merge.InstanceString, merge.AdmitsEveryOfKind, true}, + {"IfStr", merge.InstanceInteger, merge.AdmitsEveryOfKind, true}, + {"IfStr", merge.InstanceNumber, merge.AdmitsSomeOfKind, true}, + {"IfStr", merge.InstanceObject, merge.AdmitsNoneOfKind, true}, + {"IfReq", merge.InstanceInteger, merge.AdmitsNoneOfKind, true}, + {"IfReq", merge.InstanceString, merge.AdmitsNoneOfKind, true}, + {"IfReq", merge.InstanceObject, merge.AdmitsSomeOfKind, true}, + {"IfMin", merge.InstanceInteger, merge.AdmitsSomeOfKind, true}, + {"IfMin", merge.InstanceNumber, merge.AdmitsSomeOfKind, true}, + {"IfMin", merge.InstanceObject, merge.AdmitsEveryOfKind, true}, + {"IfMin", merge.InstanceString, merge.AdmitsNoneOfKind, true}, + {"IfLoose", merge.InstanceString, merge.AdmitsSomeOfKind, true}, + {"IfLoose", merge.InstanceInteger, merge.AdmitsSomeOfKind, true}, + {"IfLoose", merge.InstanceObject, merge.AdmitsNoneOfKind, true}, + {"IfFalse", merge.InstanceInteger, merge.AdmitsNoneOfKind, true}, + {"IfFalse", merge.InstanceString, merge.AdmitsNoneOfKind, true}, + {"IfTrue", merge.InstanceInteger, merge.AdmitsSomeOfKind, true}, + {"IfTrue", merge.InstanceString, merge.AdmitsEveryOfKind, true}, + } { + admits, exact := fields.Admits(ir.Provenance{Pointer: jsontext.Pointer("/components/schemas/" + testCase.name)}, testCase.kind) + assert.Equal(t, testCase.want, admits, "%s, kind %d", testCase.name, testCase.kind) + assert.Equal(t, testCase.exact, exact, "%s, kind %d", testCase.name, testCase.kind) + } +} diff --git a/compilers/openapi/internal/schema/members_test.go b/compilers/openapi/internal/schema/members_test.go index a4d8637d0..d6c59e20f 100644 --- a/compilers/openapi/internal/schema/members_test.go +++ b/compilers/openapi/internal/schema/members_test.go @@ -5,6 +5,7 @@ package schema_test import ( "fmt" + "slices" "strings" "testing" @@ -44,16 +45,16 @@ func diagsUnder(diags []ir.Diagnostic, prefix string) []ir.Diagnostic { // member two allOf entries declare apart: the composing model declares it, in // the composed namespace under one identity in either entry order, and a pair // no value satisfies keeps the entry written later, the specialization, with a -// report where the declaration that lost is written, naming the property it +// report where the declaration that lost is written, listing the property it // decided (GitHub #1920). func TestMembers_TwoEntriesDeclaringAMemberApartDeclareItOnTheComposition(t *testing.T) { t.Parallel() const parts = " A: {type: object, properties: {p: {type: string}}}\n" + " B: {type: object, properties: {p: {type: integer}}}\n" const id = "property/composed/components/schemas/AB/allOf/properties/p" - for entries, tc := range map[string]struct { - later ir.TypeID - lost string + for entries, testCase := range map[string]struct { + later ir.TypeID + passedOver string }{ "[{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]": {"type/primitive/integer", "/components/schemas/A/properties/p"}, "[{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/A'}]": {"type/primitive/string", "/components/schemas/B/properties/p"}, @@ -62,24 +63,32 @@ func TestMembers_TwoEntriesDeclaringAMemberApartDeclareItOnTheComposition(t *tes property := propertyOf(t, doc, "AB", "p") assert.Equal(t, ir.PropertyID(id), property.ID, entries) - assert.Equal(t, tc.later, property.Type.Target, "the entry written later: %s", entries) + assert.Equal(t, testCase.later, property.Type.Target, "the entry written later: %s", entries) assert.Empty(t, property.Unmodeled, "the declaration that lost stays on its model: %s", entries) flat := ir.FlattenedProperties(doc.Types, componentID("AB")) require.Len(t, flat.Properties, 1) assert.Equal(t, property.ID, flat.Properties[0].Property.ID, "the flattening takes the composition's own") require.Len(t, diags, 1, "%+v", diags) - found := diagsAtPointer(diags, diag.ConflictingRedecl, tc.lost) + found := diagsAtPointer(diags, diag.ConflictingRedecl, testCase.passedOver) require.Len(t, found, 1, entries) - assert.Equal(t, id, found[0].Provenance.Node, entries) + assert.True(t, decides(found[0], id), entries) } } +// decides reports whether diagnostic lists member among what it decided +// (ir.RelatedDecided). +func decides(diagnostic ir.Diagnostic, member string) bool { + return slices.ContainsFunc(diagnostic.Related, func(related ir.Related) bool { + return related.Role == ir.RelatedDecided && related.Provenance.Node == member + }) +} + // TestMembers_ARefAndTheSchemaItNamesWrittenInlineFoldAlike pins a member a // model declares itself beside one a $ref entry brings (GitHub #1951): in // either entry order, the field takes the type, docs and bounds it takes where // the named schema's declaration is written inline in the entry's place, the // narrower type wherever it is written and, of a pair no value satisfies, the -// later. A report about the entry's declaration names the member, and the +// later. As many reports decide the member as decide its inline twin, and the // property keeps the identity of the declaration the model writes. func TestMembers_ARefAndTheSchemaItNamesWrittenInlineFoldAlike(t *testing.T) { t.Parallel() @@ -108,13 +117,16 @@ func TestMembers_ARefAndTheSchemaItNamesWrittenInlineFoldAlike(t *testing.T) { assert.Equal(t, written.Type, byRef.Type, name) assert.Equal(t, written.Docs, byRef.Docs, name) assert.Equal(t, written.Constraints, byRef.Constraints, name) - atRef := 0 + atRef, atInline := 0, 0 for _, diagnostic := range diags { - if diagnostic.Provenance.Node == string(byRef.ID) { + if decides(diagnostic, string(byRef.ID)) { atRef++ } + if decides(diagnostic, string(written.ID)) { + atInline++ + } } - assert.Equal(t, len(diagsUnder(diags, "/components/schemas/Inline/")), atRef, "%s: as many reports: %+v", name, diags) + assert.Equal(t, atInline, atRef, "%s: as many reports: %+v", name, diags) } } } @@ -123,7 +135,7 @@ func TestMembers_ARefAndTheSchemaItNamesWrittenInlineFoldAlike(t *testing.T) { // the schema it names written inline fold apart: the entry's schema declares // the member as a string and then an integer, a tie its settlement gives the // later. Beside one more string, the entry brings the integer alone, which -// ties again and stands as the later, while the inline spelling counts two +// ties again and is the later, while the inline spelling counts two // strings against one integer. Each spelling reports its tie. func TestMembers_ATieAnEntrySettledIsNotCountedAgain(t *testing.T) { t.Parallel() @@ -179,15 +191,15 @@ func TestMembers_AMemberAPartSettledIsJudgedWhereItsTypeIsWritten(t *testing.T) } } -// TestMembers_AMemberAPartMeetsIsJudgedAtEachDeclarationItHolds pins a member -// an entry brings met, in either entry order. The part declares it as a list -// of strings, then of an enum, each holding a bound, so its member is a list -// the fold built, whose element the second declaration hoisted. Folded with -// another entry's list of that enum, the element reads as written at the -// part's declaration: the lists meet in the tightest bounds, and the other -// entry's default, listing a value the enum lacks, is its own type's to answer -// for, as written inline. -func TestMembers_AMemberAPartMeetsIsJudgedAtEachDeclarationItHolds(t *testing.T) { +// TestMembers_AMemberAPartIntersectsIsJudgedAtEachDeclarationItHolds pins a +// member an entry brings intersected, in either entry order. The part declares +// it as a list of strings, then of an enum, each holding a bound, so its member +// is a list the fold built, whose element the second declaration hoisted. +// Folded with another entry's list of that enum, the element reads as written +// at the part's declaration: the lists intersect in the tightest bounds, and +// the other entry's default, listing a value the enum lacks, is refused by that +// type, reported where it is written and not adopted, as written inline. +func TestMembers_AMemberAPartIntersectsIsJudgedAtEachDeclarationItHolds(t *testing.T) { t.Parallel() list := func(rest string) string { return "{type: object, properties: {b: {type: array, " + rest + "}}}" } const enum = "items: {type: string, enum: [x, y]}" @@ -207,15 +219,19 @@ func TestMembers_AMemberAPartMeetsIsJudgedAtEachDeclarationItHolds(t *testing.T) require.Empty(t, irverify.Verify(doc)) three, five := int64(3), int64(5) - for _, model := range []string{"Ref", "Inline"} { + leafAt := map[bool]string{true: "0", false: "1"}[leafFirst] + for model, writtenAt := range map[string]string{ + "Ref": "/components/schemas/S2/properties/b", "Inline": "/components/schemas/Inline/allOf/" + leafAt + "/properties/b", + } { name := fmt.Sprintf("%s, leaf first %v", model, leafFirst) b := propertyOf(t, doc, model, "b") - met, isList := doc.Types[b.Type.Target].(*ir.List) + list, isList := doc.Types[b.Type.Target].(*ir.List) require.True(t, isList, name) - assert.Equal(t, &ir.Constraints{MinItems: &three, MaxItems: &five}, met.Constraints, name) - require.NotNil(t, b.Default, name) - assert.Len(t, b.Default.List, 3, name) - assert.Empty(t, diagsUnder(diags, "/components/schemas/"+model+"/"), name) + assert.Equal(t, &ir.Constraints{MinItems: &three, MaxItems: &five}, list.Constraints, name) + assert.Nil(t, b.Default, name) + refusals := diagsAtPointer(diags, diag.DegradedConstruct, writtenAt) + require.Len(t, refusals, 1, name) + assert.Contains(t, refusals[0].Message, "admits the default", name) } } } @@ -233,7 +249,7 @@ func TestMembers_AMemberOnlyEntriesDeclareIsJudgedWhereItsTypeIsWritten(t *testi return "{allOf: [{$ref: '#/components/schemas/" + a + "'}, {$ref: '#/components/schemas/" + b + "'}]}" } one, nine := int64(1), int64(9) - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { first, second [2]string members int want *ir.Constraints @@ -250,8 +266,8 @@ func TestMembers_AMemberOnlyEntriesDeclareIsJudgedWhereItsTypeIsWritten(t *testi }, } { doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", - " A1: "+holding(tc.first[0])+"\n B1: "+holding(tc.first[1])+"\n One: "+composing("A1", "B1")+"\n"+ - " A2: "+holding(tc.second[0])+"\n B2: "+holding(tc.second[1])+"\n Two: "+composing("A2", "B2")+"\n"+ + " A1: "+holding(testCase.first[0])+"\n B1: "+holding(testCase.first[1])+"\n One: "+composing("A1", "B1")+"\n"+ + " A2: "+holding(testCase.second[0])+"\n B2: "+holding(testCase.second[1])+"\n Two: "+composing("A2", "B2")+"\n"+ " Ref: "+composing("One", "Two")+"\n")) openapitest.RequireNoErrorDiags(t, diags) require.Empty(t, irverify.Verify(doc), name) @@ -259,20 +275,20 @@ func TestMembers_AMemberOnlyEntriesDeclareIsJudgedWhereItsTypeIsWritten(t *testi b := propertyOf(t, doc, "Ref", "b") enum, isEnum := doc.Types[b.Type.Target].(*ir.Enum) require.True(t, isEnum, name) - assert.Len(t, enum.Members, tc.members, name) - assert.Equal(t, tc.want, b.Constraints, name) + assert.Len(t, enum.Members, testCase.members, name) + assert.Equal(t, testCase.want, b.Constraints, name) assert.Empty(t, diagsUnder(diags, "/components/schemas/Ref/"), name) } } -// TestMembers_ABroughtMembersDefaultIsItsOwnTypesWhereThatIsWritten pins the +// TestMembers_ABroughtMembersDefaultItsOwnTypeRefusesIsNotAdopted pins the // default a settled member an entry brings holds, written against its own // type: the part declares a list of strings and then one of an enum, giving // the default, beside another entry's list of that enum, whose copy the built -// list takes. The default lists a value the enum lacks, which its own -// declaration answers for, so the member keeps it in either entry order, as -// the part's own member does. -func TestMembers_ABroughtMembersDefaultIsItsOwnTypesWhereThatIsWritten(t *testing.T) { +// list takes. The default lists a value the enum lacks, which that type +// refuses, so the part's own member does not adopt it, and the member another +// model brings from the part holds none either, in either entry order. +func TestMembers_ABroughtMembersDefaultItsOwnTypeRefusesIsNotAdopted(t *testing.T) { t.Parallel() list := func(rest, items string) string { return "{type: object, properties: {b: {type: array, " + rest + ", items: {type: string" + items + "}}}}" @@ -287,41 +303,46 @@ func TestMembers_ABroughtMembersDefaultIsItsOwnTypesWhereThatIsWritten(t *testin require.Empty(t, irverify.Verify(doc)) b := propertyOf(t, doc, "Ref", "b") - require.NotNil(t, b.Default, "%v", order) - assert.Equal(t, propertyOf(t, doc, "S", "b").Default, b.Default, "%v", order) + assert.Nil(t, propertyOf(t, doc, "S", "b").Default, "%v", order) + assert.Nil(t, b.Default, "%v", order) + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/S/allOf/1/properties/b"), 1, "%v", order) assert.Empty(t, diagsUnder(diags, "/components/schemas/Ref/"), "%v", order) } } // TestMembers_AReportNamesABroughtMemberWhereItSaysWhatItDoes pins what a -// report says of a member an entry brings settled. Where one declaration gave -// its type, the report names that declaration, not the first the member is -// named for, which says another type. Where its model's composition built the -// type of what only its entries declare, no schema is written where the model -// declares it, so the report names the entry bringing it. Either way the -// report sits where it names. +// report about a type says of a member an entry brings settled: where one +// declaration gave its type, the report names that declaration, not the +// first the member keeps the identity of, which says another type, as every +// report names a place writing what it speaks of +// (docs/compilers/openapi.md#allof-redeclared-property). Where its model's +// composition built the type of what only its entries declare, nothing is +// written where the model declares it, so the report names that model. +// Either way the report sits where it names. func TestMembers_AReportNamesABroughtMemberWhereItSaysWhatItDoes(t *testing.T) { t.Parallel() holding := func(schema string) string { return "{type: object, properties: {p: " + schema + "}}" } const composing = "{allOf: [{$ref: '#/components/schemas/M'}, {$ref: '#/components/schemas/C'}]}" - for name, tc := range map[string]struct{ part, over string }{ + for name, testCase := range map[string]struct{ part, over string }{ "the declaration giving its type": { part: "{allOf: [" + holding("{type: string}") + ", " + holding("{type: integer}") + "]}", over: "/components/schemas/M/allOf/1/properties/p", }, - "the entry bringing what is written nowhere": { + "the model settling what is written nowhere": { part: "{allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}", - over: "/components/schemas/N/allOf/0", + over: "/components/schemas/M", }, } { _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " A: "+holding("{type: string, enum: [x, y]}")+"\n B: "+holding("{type: string, enum: [y, z]}")+"\n"+ - " M: "+tc.part+"\n C: "+holding("{type: boolean}")+"\n N: "+composing+"\n")) + " M: "+testCase.part+"\n C: "+holding("{type: boolean}")+"\n N: "+composing+"\n")) - at := diagsAtPointer(diags, diag.ConflictingRedecl, tc.over) + at := slices.DeleteFunc(diagsAtPointer(diags, diag.ConflictingRedecl, testCase.over), func(diagnostic ir.Diagnostic) bool { + return !strings.Contains(diagnostic.Message, "/components/schemas/C/properties/p") + }) require.Len(t, at, 1, name) - assert.Contains(t, at[0].Message, "kept what the declaration at /components/schemas/C/properties/p says over the one at "+ - tc.over+", which stays declared on its model", name) + assert.Contains(t, at[0].Message, ": /components/schemas/C/properties/p and "+testCase.over+" disagree:", name) + assert.Contains(t, at[0].Message, "; chose what the first says; the second stays declared on its model", name) } } @@ -330,7 +351,7 @@ func TestMembers_AReportNamesABroughtMemberWhereItSaysWhatItDoes(t *testing.T) { // member with no type and then as an inline object, so the member keeps the // first declaration's identity and the model the second hoisted. No $ref names // that model, so the composition lists it among its Mixins, as it lists the -// other entry's, and elects no Base (SelectBase). +// other entry's, and chooses no Base (SelectBase). func TestMembers_ASettledMembersInlineTypeIsNoBaseOfWhatComposesIt(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", @@ -400,11 +421,32 @@ func TestMembers_RequiresAndTheDiscriminatorFollowTheDeclaredMember(t *testing.T } } +// TestMembers_ASettledMembersDescriptionIsReportedWhereItIsWritten pins a +// report about a description a member an entry brings lost: M keeps its own +// declaration's identity, at M/allOf/1, and Base's description, and N's own +// description overrides it, so the report sits at, and names, Base's +// declaration, which writes the description, and not M's, which writes none. +func TestMembers_ASettledMembersDescriptionIsReportedWhereItIsWritten(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Base: {type: object, properties: {p: {type: string, description: base}}}\n"+ + " M: {allOf: [{$ref: '#/components/schemas/Base'}, {type: object, properties: {p: {type: string}}}]}\n"+ + " N: {allOf: [{$ref: '#/components/schemas/M'}, {type: object, properties: {p: {type: string, description: n}}}]}\n")) + + at := diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Base/properties/p") + require.Len(t, at, 1, "%+v", diags) + assert.Contains(t, at[0].Message, ": /components/schemas/N/allOf/1/properties/p and /components/schemas/Base/properties/p "+ + "give its description differently; chose the one the first gives") + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/M/allOf/1/properties/p")) +} + // TestMembers_AModelIsSettledAfterWhatItComposes pins a model composing one // whose member a fold settles: it reads that member settled, through an // alias entry too, whichever is declared first, so Mid's integer, not its own -// number, is what Top's string meets, each conflict sitting where that integer -// is written. +// number, is what Top's string intersects. Each conflict sits where Base writes +// that integer, not where Mid writes the member it keeps the identity of, +// which says number: a report about a type names a place writing it +// (docs/compilers/openapi.md#allof-redeclared-property). func TestMembers_AModelIsSettledAfterWhatItComposes(t *testing.T) { t.Parallel() const base = " Base: {type: object, properties: {id: {type: integer}}}\n" @@ -416,8 +458,8 @@ func TestMembers_AModelIsSettledAfterWhatItComposes(t *testing.T) { found := diagsAtPointer(diags, diag.ConflictingRedecl, "/components/schemas/Base/properties/id") require.Len(t, found, 2, "%+v", diags) for i, model := range []string{"Aliased", "Top"} { - assert.Contains(t, found[i].Message, "type/primitive/integer", model) - assert.Contains(t, found[i].Message, "kept what the declaration at /components/schemas/"+model+"/allOf/1/properties/id", model) + assert.Contains(t, found[i].Message, ": /components/schemas/"+model+"/allOf/1/properties/id and /components/schemas/Base/properties/id "+ + "disagree: incompatible types string and integer; chose what the first says", model) } } } @@ -447,9 +489,9 @@ func TestMembers_AModelAFoldComposesIsSettledInTheNextRound(t *testing.T) { A: {type: object, properties: {q: {$ref: '#/components/schemas/A1'}}} B: {type: object, properties: {q: {$ref: '#/components/schemas/B1'}}} ` - for entries, tc := range map[string]struct { - later ir.TypeID - lost string + for entries, testCase := range map[string]struct { + later ir.TypeID + passedOver string }{ "[{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]": {"type/primitive/integer", "/components/schemas/A1/properties/r"}, "[{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/A'}]": {"type/primitive/string", "/components/schemas/B1/properties/r"}, @@ -460,8 +502,8 @@ func TestMembers_AModelAFoldComposesIsSettledInTheNextRound(t *testing.T) { composed, ok := doc.Types[property.Type.Target].(*ir.Model) require.True(t, ok, "got %T", doc.Types[property.Type.Target]) require.Len(t, composed.Properties, 1, "its own r") - assert.Equal(t, tc.later, composed.Properties[0].Type.Target, entries) - assert.Len(t, diagsAtPointer(diags, diag.ConflictingRedecl, tc.lost), 1, "%s: %+v", entries, diags) + assert.Equal(t, testCase.later, composed.Properties[0].Type.Target, entries) + assert.Len(t, diagsAtPointer(diags, diag.ConflictingRedecl, testCase.passedOver), 1, "%s: %+v", entries, diags) } } @@ -547,7 +589,7 @@ func TestMembers_AHierarchyOfAnyDepthSettlesWhateverItsModelsAreNamed(t *testing // variants: the bound bounds that type's values too, which the variants do not // say, so the type is not taken as narrower, which would drop the bound // unreported; the pair is reported as not compared, written inline or brought -// by an entry. +// by an entry, where the union's declaration is written. func TestMembers_AUnionBoundedBesideItIsNotTakenForAVariant(t *testing.T) { t.Parallel() _, diags := composedDoc(t, ` U: {anyOf: [{type: string}, {type: integer}], maxLength: 2} @@ -561,7 +603,7 @@ func TestMembers_AUnionBoundedBesideItIsNotTakenForAVariant(t *testing.T) { - $ref: '#/components/schemas/Base' - {type: object, properties: {p: {type: string}}} `) - for _, at := range []string{"/components/schemas/Inline/allOf/0/properties/p", "/components/schemas/Brought/allOf/0"} { + for _, at := range []string{"/components/schemas/Inline/allOf/0/properties/p", "/components/schemas/Base/properties/p"} { found := diagsAtPointer(diags, diag.DegradedConstruct, at) require.Len(t, found, 1, "%s: %+v", at, diags) assert.Contains(t, found[0].Message, "that the merge does not compare", at) @@ -569,38 +611,39 @@ func TestMembers_AUnionBoundedBesideItIsNotTakenForAVariant(t *testing.T) { } // TestMembers_AModelTheMergeComposesNamesItsMembersApart pins the members a -// model the merge composes settles, a field's composition and a distributed -// variant, each at the pointer of the schema written there, which settles a -// member of that name too: the two are different properties, so each takes an -// identity of its own, and the document verifies. +// model the merge composes settles, a field's composition, at the fold's key, +// and a distributed variant, at the pointer of the schema written there, beside +// a schema settling a member of that name too: the two are different +// properties, so each takes an identity of its own, and the document verifies. func TestMembers_AModelTheMergeComposesNamesItsMembersApart(t *testing.T) { t.Parallel() const parts = ` X1: {type: object, properties: {y: {type: integer, enum: [1, 2]}}} X2: {type: object, properties: {y: {type: number}}} X3: {type: object, properties: {y: {type: integer}}} ` - for name, tc := range map[string]struct{ schemas, at string }{ + for name, testCase := range map[string]struct{ schemas, at, composedAt string }{ "a field's composition": {schemas: parts + ` A: {type: object, properties: {x: {$ref: '#/components/schemas/X1'}}} M: allOf: [{$ref: '#/components/schemas/A'}] properties: x: {allOf: [{$ref: '#/components/schemas/X2'}, {$ref: '#/components/schemas/X3'}]} -`, at: "components/schemas/M/properties/x"}, +`, at: "components/schemas/M/properties/x", composedAt: "components/schemas/M/allOf/properties/x"}, "a distributed variant": {schemas: parts + ` C: {type: object, properties: {w: {type: string}}} U: allOf: [{$ref: '#/components/schemas/X1'}] oneOf: - allOf: [{$ref: '#/components/schemas/X2'}, {$ref: '#/components/schemas/X3'}] - $ref: '#/components/schemas/C' -`, at: "components/schemas/U/oneOf/0"}, +`, at: "components/schemas/U/oneOf/0", composedAt: "components/schemas/U/oneOf/0"}, } { - doc, _ := composedDoc(t, tc.schemas) + doc, _ := composedDoc(t, testCase.schemas) - for space, id := range map[string]ir.PropertyID{ - "anonymous": ir.PropertyID("property/composed/" + tc.at + "/allOf/properties/y"), - "composed": ir.PropertyID("property/composed/" + tc.at + "/allOf/allOf/properties/y"), - } { - model, ok := doc.Types[ir.TypeID("type/"+space+"/"+tc.at)].(*ir.Model) + for space, at := range map[string]string{"anonymous": testCase.at, "composed": testCase.composedAt} { + id := ir.PropertyID("property/composed/" + at + "/allOf/properties/y") + if space == "composed" { + id = ir.PropertyID("property/composed/" + at + "/allOf/allOf/properties/y") + } + model, ok := doc.Types[ir.TypeID("type/"+space+"/"+at)].(*ir.Model) require.True(t, ok, "%s: the %s model", name, space) property, ok := openapitest.PropertiesByWire(model.Properties)["y"] require.True(t, ok, "%s: the %s model settles y", name, space) diff --git a/compilers/openapi/internal/schema/model.go b/compilers/openapi/internal/schema/model.go index 8aa9a5919..67ea29d22 100644 --- a/compilers/openapi/internal/schema/model.go +++ b/compilers/openapi/internal/schema/model.go @@ -20,35 +20,55 @@ import ( "github.com/dexpace/morphic/ir" ) -// lowerModel hoists an object schema as a Model, or as a MapT when the object -// is a map and nothing else (objectNode): its value constraints, those that -// apply to a value of the kinds takes, the property-set cardinality among them, -// its own properties and which are required, its catch-all (fillAdditional) -// and, where discriminated, the discriminator it declares. It reads no -// annotations: fin, finishing the node, writes them for every destination. -// -// Cardinality is read here rather than on lowerComponentSchema's internAlias -// fallback because an object-shaped schema owns its node before that fallback -// would run, so the fallback never fires for one (GitHub #129). -func lowerModel(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, discriminated bool, - takes kindSet, fin finisher, -) (ir.TypeID, []ir.Diagnostic) { +// discriminatorLowering says whether a Model lowers the discriminator its +// schema writes (lowerModelAt). +type discriminatorLowering uint8 + +const ( + // lowersDiscriminator lowers it onto the Model. + lowersDiscriminator discriminatorLowering = iota + // leavesDiscriminator leaves it to the Union of the type list the Model is + // the object variant of, which keeps it unread. + leavesDiscriminator +) + +// lowerModelAt hoists an object schema as a Model at at, or as a MapT when the +// object is a map alone (objectNode), lowering its discriminator as +// discriminator says. It reads the property-set cardinality itself, as an +// object-shaped schema owns its node before lowerComponentSchema's internAlias +// fallback runs (GitHub #129). A type list's object variant reads schema where +// it is written, at pointer (docs/compilers/openapi.md#type-arrays), with +// flattenedEntries and objectConjuncts, the conjuncts beside the list. +func lowerModelAt(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer, at jsontext.Pointer, + discriminator discriminatorLowering, takes kindSet, flattenedEntries []annotation.FlattenedAllOfEntry, objectConjuncts []objectConjunct, +) (builtPosition, []ir.Diagnostic) { var diags []ir.Diagnostic - id := internNode(loweringContext, ts, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { - cons, consDiags := ConstraintsOf(loweringContext, &common.Unmodeled, schema, nil, pointer, modelTakes(takes)) + held := modelTakes(takes) + built := internNode(loweringContext, types, at, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + cons, consDiags := ConstraintsOf(loweringContext, &common.Unmodeled, schema, flattenedEntries, pointer, held) diags = append(diags, consDiags...) model := &ir.Model{TypeCommon: common, Constraints: cons} - diags = append(diags, fillModelProperties(loweringContext, ts, depth, newModelFields(loweringContext, ts, model), schema, pointer)...) + fields := newModelFields(loweringContext, types, model) + diags = append(diags, fillModelProperties(loweringContext, types, depth, fields, schema, pointer)...) requireMembers(model, schema.ObjectKeywords().Required) - diags = append(diags, fillAdditional(loweringContext, ts, depth, model, schema, pointer)...) - if discriminated { - discriminator, discDiags := lowerDiscriminator(loweringContext, ts, schema.Discriminator(), pointer, model, nil) + for _, objectConjunct := range objectConjuncts { + diags = append(diags, fillModelProperties(loweringContext, types, depth, fields, objectConjunct.schema, objectConjunct.at)...) + requireMembers(model, objectConjunct.schema.ObjectKeywords().Required) + } + diags = append(diags, fillCatchAll(loweringContext, types, depth, model, schema.ObjectKeywords().AdditionalProperties, schema, pointer, closesAfterComposition(loweringContext, schema))...) + diags = append(diags, typeUnevaluatedCatchAll(loweringContext, types, depth, model, schema, pointer)...) + // Patterns matching a member the object declares apply to it too. + diags = append(diags, diagCatchAllScope(loweringContext, &model.Unmodeled, catchAllSource{schema: schema, at: pointer, own: true}, + func() composedMembers { return membersOfConjunction(loweringContext, schema) })...) + if discriminator == lowersDiscriminator { + lowered, discDiags := lowerDiscriminator(loweringContext, types, schema.Discriminator(), pointer, model, nil) diags = append(diags, discDiags...) - model.Discriminator = discriminator + model.Discriminator = lowered + holdModelDiscriminator(loweringContext, types, writtenDiscriminator{discriminator: schema.Discriminator(), conjunctSchema: schema}, pointer, model) } - return objectNode(model), modelReads(schema, model, modelTakes(takes)) - }, fin) - return id, diags + return objectNode(model), modelReads(schema, model, held) + }) + return built, diags } // modelReads returns what the build of model read of schema, a Model's or a @@ -85,17 +105,17 @@ func objectNode(model *ir.Model) ir.TypeDef { // order the declarations lower in (GitHub #898). It is the walk the fold asks // (merge.FieldDeclarationContext). pointer is where the model is written. type modelFields struct { - c lowering.Ctx - ts *compile.Types - m *ir.Model - idx *merge.ModelPropertyDeclarations - pointer jsontext.Pointer + loweringContext lowering.Ctx + types *compile.Types + model *ir.Model + idx *merge.ModelPropertyDeclarations + pointer jsontext.Pointer } // newModelFields returns the fields of model, which holds no property yet, -// lowered in loweringContext and registered with ts. -func newModelFields(loweringContext lowering.Ctx, ts *compile.Types, model *ir.Model) modelFields { - return modelFields{c: loweringContext, ts: ts, m: model, idx: merge.NewModelPropertyDeclarations(model), pointer: model.Provenance.Pointer} +// lowered in loweringContext and registered with types. +func newModelFields(loweringContext lowering.Ctx, types *compile.Types, model *ir.Model) modelFields { + return modelFields{loweringContext: loweringContext, types: types, model: model, idx: merge.NewModelPropertyDeclarations(model), pointer: model.Provenance.Pointer} } // merge lands property on the model, or records it as one more declaration of @@ -104,7 +124,7 @@ func newModelFields(loweringContext lowering.Ctx, ts *compile.Types, model *ir.M // first redeclaration. func (f modelFields) merge(property ir.Property, source merge.DeclarationConstructRenderer, secretBy ir.Inferred) { if f.idx.MergeProperty(property, source, secretBy) { - membersOf(f.c).note(f) + membersOf(f.loweringContext).note(f) } } @@ -112,91 +132,148 @@ func (f modelFields) merge(property ir.Property, source merge.DeclarationConstru // walk meets it (merge.ModelPropertyDeclarations.Compose), and notes the model. func (f modelFields) compose(target ir.TypeID, at jsontext.Pointer) { f.idx.Compose(target, at) - membersOf(f.c).note(f) + membersOf(f.loweringContext).note(f) } -// Interned reports whether a node stands at pointer of the model's document -// (merge.FieldDeclarationContext.Interned). -func (f modelFields) Interned(pointer jsontext.Pointer) bool { - _, ok := f.ts.Lookup(f.c.IDs().Coordinate(pointer)) +// Interned reports whether a node sits at the pointer at names, in at's own +// document (merge.FieldDeclarationContext.Interned). +func (f modelFields) Interned(at ir.Provenance) bool { + in, placed := lowering.InDocumentOf(f.loweringContext, at) + if !placed { + return false + } + _, ok := f.loweredAt(in.IDs().Coordinate(at.Pointer)) return ok } -// place returns where provenance is in the bindings' table, read at f.c's -// position for its pointer, as the model's own document holds it, and false for -// a site in another document, such as a component a $ref there reached. -func (f modelFields) place(provenance ir.Provenance) (reftable.DocumentPointer, bool) { - return f.c.Position(provenance.Pointer), provenance.Source == f.c.Place().At(provenance.Pointer).Source +// InDiscriminatorHierarchy is merge.FieldDeclarationContext's: whether the +// declaration written at provenance, read in its own document, writes a $ref +// whose run ends on a stated schema in a discriminator hierarchy, as a written +// allOf's choice reads one (selectAllOfBase). +func (f modelFields) InDiscriminatorHierarchy(provenance ir.Provenance) bool { + in, at, placed := f.place(provenance) + if !placed { + return false + } + target := refBranchTarget(in, in.Statements().At(at)) + return stated(target) && inHierarchy(in, target) +} + +// loweredAt returns the ID of the node lowered at coordinate, and false where +// none was (compile.Types.Lookup). +func (f modelFields) loweredAt(coordinate string) (ir.TypeID, bool) { + return f.types.Lookup(coordinate) } -// Alike is merge.FieldDeclarationContext.Alike. A site place does not place, or -// one whose base the bindings cannot tell, is no match. -func (f modelFields) Alike(a, b ir.Provenance) bool { - base := func(provenance ir.Provenance) (string, bool) { - at, placed := f.place(provenance) - uri, known := f.c.Bindings().Table().Base(at) - return uri, placed && known - } - ua, okA := base(a) - ub, okB := base(b) - return okA && okB && ua == ub +// Primitive is merge.FieldDeclarationContext.Primitive: the primitive of kind, +// interned in the compile's registry. +func (f modelFields) Primitive(kind ir.PrimitiveKind) ir.TypeID { + return f.types.PrimitiveID(kind) +} + +// IsComposedOf reports whether id is composed of target, as the round's reach +// index answers (merge.FieldDeclarationContext.IsComposedOf; +// members.isComposedOf). +func (f modelFields) IsComposedOf(id, target ir.TypeID) bool { + return membersOf(f.loweringContext).isComposedOf(id, target) +} + +// place returns the context reading provenance's own document, and where +// provenance is in the bindings' table, and false for a Source no document +// the compile read records (lowering.InDocumentOf), so a site is read alike +// whichever model's walk asks. +func (f modelFields) place(provenance ir.Provenance) (lowering.Ctx, reftable.DocumentPointer, bool) { + in, placed := lowering.InDocumentOf(f.loweringContext, provenance) + return in, in.Position(provenance.Pointer), placed +} + +// DeclarationsAdmitAlike is merge.FieldDeclarationContext's, judged on the +// nodes the settlement's registry holds (sameMeaning). +func (f modelFields) DeclarationsAdmitAlike(a, b ir.Provenance) bool { + return newSameMeaning(f.loweringContext, f.lowered()).declarations(a, b) } -// Admits is merge.FieldDeclarationContext.Admits: the schema written at -// provenance admits every instance of kind, as the run reads what its statement -// admits (admissionOf), its value sets, unions and the keywords beside a $ref -// among them, and no keyword it takes in refuses some instance of kind -// (narrowedWithin), a variant read with every schema holding it -// (variantHolders). A site place does not place, one holding no schema object, -// and a read cut short or meeting a keyword it does not follow that could -// refuse a kind (looseIn) are not exact, which keeps the verdict a structure -// had before its source was read. -func (f modelFields) Admits(provenance ir.Provenance, kind merge.JSONInstanceKind) (admits, exact bool) { - at, placed := f.place(provenance) +// NodesAdmitAlike is merge.FieldDeclarationContext.NodesAdmitAlike, judged on +// the nodes the settlement's registry holds (sameMeaning). +func (f modelFields) NodesAdmitAlike(a, b ir.TypeID) bool { + return newSameMeaning(f.loweringContext, f.lowered()).admitAlike([][2]ir.TypeID{{a, b}}) +} + +// AnnotationsCarried is merge.FieldDeclarationContext.AnnotationsCarried, +// judged on the nodes the settlement's registry holds (sameMeaning). +func (f modelFields) AnnotationsCarried(kept, other ir.TypeID) merge.AnnotationCarriage { + return newSameMeaning(f.loweringContext, f.lowered()).annotationsCarried(kept, other) +} + +// lowered finds the nodes lowered at a coordinate and those the settlement's +// registry holds, which a judgment of meaning reads. +func (f modelFields) lowered() loweredNodes { + return loweredNodes{at: f.loweredAt, node: membersOf(f.loweringContext).reg.Lookup} +} + +// Admits is merge.FieldDeclarationContext.Admits, reading the schema at +// provenance as the run reads it (admissionOf), a variant with every schema +// holding it (variantHolders). A site it cannot read, or a read a keyword it +// does not follow could narrow (logicKinds), is not exact, which keeps the +// answer a structure had before its source was read. +func (f modelFields) Admits(provenance ir.Provenance, kind merge.JSONInstanceKind) (admits merge.KindAdmission, exact bool) { + in, at, placed := f.place(provenance) if !placed { - return false, false + return merge.AdmitsSomeOfKind, false } - st := f.c.Statements().At(at) - if st.Truth != statement.Stated { - return false, false + schemaStatement := in.Statements().At(at) + if schemaStatement.Truth != statement.Stated { + return merge.AdmitsSomeOfKind, false } - kinds, partial, inexact := anyInstance, kindSet(0), false - for _, read := range variantHolders(f.c, at, st) { - admission := admissionOf(f.c, read) - kinds, partial, inexact = kinds&admission.admits, partial|admission.partial, inexact || admission.cut || admission.loose + kinds, partial, inexact := everyKindButNull, kindSet(0), false + for _, read := range variantHolders(in, at, schemaStatement) { + admission := admissionOf(in, read) + kinds, partial, inexact = kinds&admission.admits, partial|admission.partial, inexact || admission.loose } if inexact { - return false, false + return merge.AdmitsSomeOfKind, false + } + return kindAdmission(kinds, partial, instanceKinds(kind)), true +} + +// kindAdmission is what a read admitting kinds, partial of them only in part, +// admits of the instances want names; some where want names none, as of the +// null. +func kindAdmission(kinds, partial, want kindSet) merge.KindAdmission { + switch { + case want == 0: + return merge.AdmitsSomeOfKind + case kinds&want == 0: + return merge.AdmitsNoneOfKind + case kinds&want == want && partial&want == 0: + return merge.AdmitsEveryOfKind + default: + return merge.AdmitsSomeOfKind } - want := instanceKinds(kind) - return want != 0 && kinds&want == want && partial&want == 0, true } -// variantHolders returns st, written at at, and where st is an entry of a -// oneOf or an anyOf, every schema an instance of that variant also meets: the -// one writing the union, and each holding that one in turn as an entry of its -// allOf or a branch of its union, as a distributed variant composes what each -// writes beside it. A schema st is an allOf entry of, and no union branch, is -// no variant, so st alone is read. Each holder stands two tokens up the -// pointer, so the climb ends within half its tokens. -func variantHolders(loweringContext lowering.Ctx, at reftable.DocumentPointer, st *statement.Statement) []*statement.Statement { - out := []*statement.Statement{st} +// variantHolders returns schemaStatement, written at at, and where it is a +// oneOf or anyOf branch, every schema an instance of that variant also +// satisfies: each holding it in turn as an allOf entry or a union branch, as a +// distributed variant composes what each writes beside it. Each holder sits +// two tokens up the pointer, so the climb ends within half its tokens. +func variantHolders(loweringContext lowering.Ctx, at reftable.DocumentPointer, schemaStatement *statement.Statement) []*statement.Statement { + out := []*statement.Statement{schemaStatement} for range strings.Count(string(at.Pointer), "/") / 2 { - holder, keyword, ok := holderOf(loweringContext, at, st) + holder, keyword, ok := holderOf(loweringContext, at, schemaStatement) if !ok || len(out) == 1 && keyword == "allOf" { break } out = append(out, holder) - at, st = reftable.DocumentPointer{Doc: at.Doc, Pointer: at.Pointer.Parent().Parent()}, holder + at, schemaStatement = reftable.DocumentPointer{Doc: at.Doc, Pointer: at.Pointer.Parent().Parent()}, holder } return out } // holderOf returns the statement writing the oneOf, anyOf or allOf an entry of -// which st, at at, is, with that keyword, and false where st is no such entry: -// its pointer ends elsewhere, names an entry its holder lacks, or st is read -// elsewhere. -func holderOf(loweringContext lowering.Ctx, at reftable.DocumentPointer, st *statement.Statement) (*statement.Statement, string, bool) { +// which schemaStatement, at at, is, with that keyword, and false where it is +// no such entry. +func holderOf(loweringContext lowering.Ctx, at reftable.DocumentPointer, schemaStatement *statement.Statement) (*statement.Statement, string, bool) { index, err := strconv.Atoi(at.Pointer.LastToken()) if err != nil { return nil, "", false @@ -205,42 +282,19 @@ func holderOf(loweringContext lowering.Ctx, at reftable.DocumentPointer, st *sta holder := loweringContext.Statements().At(reftable.DocumentPointer{Doc: at.Doc, Pointer: at.Pointer.Parent().Parent()}) var entries []statement.Subschema switch keyword { - case "oneOf": - entries = holder.ChoiceKeywords().OneOf - case "anyOf": - entries = holder.ChoiceKeywords().AnyOf + case string(oneOfKeyword), string(anyOfKeyword): + entries = unionKeyword(keyword).branchesOf(holder.Schema) case "allOf": entries = holder.AllOf default: return nil, "", false } - if index < 0 || index >= len(entries) || loweringContext.Statements().Subschema(entries[index]) != st { + if index < 0 || index >= len(entries) || loweringContext.Statements().Subschema(entries[index]) != schemaStatement { return nil, "", false } return holder, keyword, true } -// instanceKinds returns the kinds an instance of kind may be, none for the -// null, which a reader of what a schema admits leaves to nulls. -func instanceKinds(kind merge.JSONInstanceKind) kindSet { - switch kind { - case merge.InstanceString: - return kindString - case merge.InstanceInteger: - return kindInteger - case merge.InstanceNumber: - return kindNumber - case merge.InstanceBoolean: - return kindBoolean - case merge.InstanceArray: - return kindArray - case merge.InstanceObject: - return kindObject - default: - return 0 - } -} - // Mint registers node, the type of the field the declaration at pointer names // (merge.FieldDeclarationContext.Mint). That pointer denotes the declaration's // own schema, so node takes the ID of a node no schema occupies @@ -251,20 +305,21 @@ func instanceKinds(kind merge.JSONInstanceKind) kindSet { // schema is written is placed by the positions it is assembled from // (assembled). func (f modelFields) Mint(pointer jsontext.Pointer, node ir.TypeDef, brought, assembled []jsontext.Pointer) ir.TypeID { - id := f.c.IDs().ComposedType(pointer) - site, common := commonFor(f.c, id, pointer), node.Common() - site.Provenance = f.c.Place().At(pointer, assembled...) + id := f.loweringContext.IDs().ComposedType(pointer) + site, common := commonFor(f.loweringContext, id, pointer), node.Common() + site.Provenance = f.loweringContext.Place().At(pointer, assembled...) from := common.ID common.ID, common.Name, common.Anonymous, common.Provenance = site.ID, site.Name, site.Anonymous, site.Provenance if enum, ok := node.(*ir.Enum); ok { enum.Members = membersBeneath(enum.Members, from, func(tail string) ir.EnumMemberID { - return f.c.IDs().ComposedMember(pointer, tail) + return f.loweringContext.IDs().ComposedMember(pointer, tail) }) } - f.ts.Register(id, node) + f.types.Register(id, node) + membersOf(f.loweringContext).mint(id) if model, ok := node.(*ir.Model); ok { - minted := newModelFields(f.c, f.ts, model) - for i, part := range merge.ComposedOf(model) { + minted := newModelFields(f.loweringContext, f.types, model) + for i, part := range ir.ComposedOf(model) { minted.compose(part, brought[i]) } } @@ -290,14 +345,14 @@ func membersBeneath(ms []ir.EnumMember, from ir.TypeID, idAt func(tail string) i // fillModelProperties lowers a model's own properties in source order, each with // its full property-level detail (constraints, visibility, defaults, docs, ...). // Which are required is requireMembers' to say, once every property is in. -func fillModelProperties(loweringContext lowering.Ctx, ts *compile.Types, depth int, fields modelFields, schema *statement.Schema, +func fillModelProperties(loweringContext lowering.Ctx, types *compile.Types, depth int, fields modelFields, schema *statement.Schema, pointer jsontext.Pointer, ) []ir.Diagnostic { var diags []ir.Diagnostic for _, statementProperty := range schema.ObjectKeywords().Properties { - js := loweringContext.Statements().Subschema(statementProperty) + schemaStatement := loweringContext.Statements().Subschema(statementProperty) ppointer := pointer + ids.Ptr("properties", statementProperty.Name) - ref, refDiags := CarriedRef(loweringContext, ts, depth, js, ppointer) + ref, refDiags := CarriedRef(loweringContext, types, depth, schemaStatement, ppointer) diags = append(diags, refDiags...) property := ir.Property{ ID: loweringContext.IDs().Property(ppointer), @@ -306,14 +361,14 @@ func fillModelProperties(loweringContext lowering.Ctx, ts *compile.Types, depth Type: ref, Provenance: loweringContext.Place().At(ppointer), } - diags = append(diags, FillPropertyDetail(loweringContext, ts, &property, js, ppointer)...) + diags = append(diags, FillPropertyDetail(loweringContext, types, &property, schemaStatement, ppointer)...) declared := property.Secret - diags = append(diags, PromoteUse(loweringContext, FallbackKeysForCarrier(loweringContext, js, property.Type, ppointer), property.Unmodeled, &property.Deprecation, &property.Secret, &property.Provenance)...) + diags = append(diags, PromoteUse(loweringContext, FallbackKeysForCarrier(loweringContext, schemaStatement, property.Type, ppointer), property.Unmodeled, &property.Deprecation, &property.Secret, &property.Provenance)...) var secretBy ir.Inferred if property.Secret && !declared { secretBy = promotion.ExtensionPromotionHeuristic } - fields.merge(property, redeclarationSource(js), secretBy) + fields.merge(property, redeclarationSource(schemaStatement), secretBy) } return diags } @@ -327,13 +382,13 @@ func fillModelProperties(loweringContext lowering.Ctx, ts *compile.Types, depth // // A boolean schema has no node of its own to render, so its value is spelled // out; a `$ref` is rendered as the `$ref` the position wrote, not the target. -func redeclarationSource(js *statement.Statement) merge.DeclarationConstructRenderer { +func redeclarationSource(schemaStatement *statement.Statement) merge.DeclarationConstructRenderer { return func() (ir.RawValue, error) { - switch js.Truth { + switch schemaStatement.Truth { case statement.Anything, statement.Nothing, statement.Unread: - return ir.RawValue(strconv.FormatBool(js.Truth == statement.Anything)), nil + return ir.RawValue(strconv.FormatBool(schemaStatement.Truth == statement.Anything)), nil default: - return annotation.RawFromNode(js.Node) + return annotation.RawFromNode(schemaStatement.Node) } } } @@ -360,41 +415,28 @@ func requireMembers(model *ir.Model, required []string) { } } -// fillAdditional lowers additionalProperties, patternProperties, and -// unevaluatedProperties into the model's openness and catch-all shape +// fillCatchAll lowers the additionalProperties additional, the +// patternProperties schema writes, and whether an unevaluatedProperties: false +// closes model after composition into the model's openness and catch-all shape // (docs/compilers/openapi.md#additional-properties). -// // `additionalProperties: true` types the catch-all as the top type, as `{}` -// does: the two are one schema in JSON Schema, and both state that members -// beyond the declared ones are allowed. Only an absent keyword writes no -// catch-all, unless patterns need one. Neither spelling touches Additional, -// which this sets only for `false` and for an `unevaluatedProperties: false` -// no additionalProperties leaves inert (annotation.ClosesAfterComposition). -func fillAdditional(loweringContext lowering.Ctx, ts *compile.Types, depth int, model *ir.Model, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - return fillCatchAll(loweringContext, ts, depth, model, schema.ObjectKeywords().AdditionalProperties, schema, pointer, annotation.ClosesAfterComposition(schema)) -} - -// fillCatchAll is fillAdditional with its sources named: the -// additionalProperties additional, and the patternProperties schema writes, -// both written in the schema object at pointer, and whether an -// unevaluatedProperties: false closes model after composition. A composition -// reads them off the object closing it (fillComposedAdditional). -func fillCatchAll(loweringContext lowering.Ctx, ts *compile.Types, depth int, model *ir.Model, additional statement.Subschema, +// does: the two are one schema in JSON Schema. +func fillCatchAll(loweringContext lowering.Ctx, types *compile.Types, depth int, model *ir.Model, additional statement.Subschema, schema *statement.Schema, pointer jsontext.Pointer, closes bool, ) []ir.Diagnostic { var diags []ir.Diagnostic - ap := loweringContext.Statements().Subschema(additional) + additionalProperties := loweringContext.Statements().Subschema(additional) switch { - case ap.Truth == statement.Unwritten: + case additionalProperties.Truth == statement.Unwritten: // Left out, or a null, which states nothing: no catch-all is written. - case ap.Truth.ReadsFalse(): + case additionalProperties.Truth.ReadsFalse(): model.Additional = ir.AdditionalClosed default: - ref, refDiags := Ref(loweringContext, ts, depth, ap, pointer+ids.Ptr("additionalProperties")) + ref, refDiags := Ref(loweringContext, types, depth, additionalProperties, pointer+ids.Ptr("additionalProperties")) diags = append(diags, refDiags...) model.AdditionalProperties = &ir.AdditionalProperties{Value: &ref} } - patterns, patternDiags := patternProperties(loweringContext, ts, depth, schema, pointer) + patterns, patternDiags := patternProperties(loweringContext, types, depth, schema, pointer) diags = append(diags, patternDiags...) if len(patterns) > 0 { if model.AdditionalProperties == nil { @@ -404,7 +446,7 @@ func fillCatchAll(loweringContext lowering.Ctx, ts *compile.Types, depth int, mo // composition evaluates it. model.AdditionalProperties = &ir.AdditionalProperties{} if !closes { - top := ts.PrimitiveRef(ir.PrimitiveAny) + top := types.PrimitiveRef(ir.PrimitiveAny) model.AdditionalProperties.Value = &top } } @@ -419,7 +461,7 @@ func fillCatchAll(loweringContext lowering.Ctx, ts *compile.Types, depth int, mo // forbidRest drops from a closed model's catch-all the value typing the keys no // pattern matches, which the closure allows none of, and the catch-all itself -// when no pattern is left (docs/ir/models.md#catch-alls). Each writer of a +// when no pattern is left (docs/ir/models.md#catch-alls). Each conjunct of a // closure beside a catch-all calls it once the closure is decided. func forbidRest(loweringContext lowering.Ctx, model *ir.Model) { if model.Additional != ir.AdditionalClosed || model.AdditionalProperties == nil { @@ -436,7 +478,7 @@ func forbidRest(loweringContext lowering.Ctx, model *ir.Model) { // patternProperties lowers patternProperties into pattern/value bindings in // source order. -func patternProperties(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer) ([]ir.PatternProperties, []ir.Diagnostic) { +func patternProperties(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer) ([]ir.PatternProperties, []ir.Diagnostic) { pp := schema.ObjectKeywords().PatternProperties if len(pp) == 0 { return nil, nil @@ -444,7 +486,7 @@ func patternProperties(loweringContext lowering.Ctx, ts *compile.Types, depth in var diags []ir.Diagnostic out := make([]ir.PatternProperties, 0, len(pp)) for _, subschema := range pp { - ref, refDiags := Ref(loweringContext, ts, depth, loweringContext.Statements().Subschema(subschema), pointer+ids.Ptr("patternProperties", subschema.Name)) + ref, refDiags := Ref(loweringContext, types, depth, loweringContext.Statements().Subschema(subschema), pointer+ids.Ptr("patternProperties", subschema.Name)) diags = append(diags, refDiags...) out = append(out, ir.PatternProperties{Pattern: subschema.Name, Value: ref}) } diff --git a/compilers/openapi/internal/schema/model_test.go b/compilers/openapi/internal/schema/model_test.go index a1e011784..525bf4f21 100644 --- a/compilers/openapi/internal/schema/model_test.go +++ b/compilers/openapi/internal/schema/model_test.go @@ -93,7 +93,7 @@ func TestModel_AdditionalPropertiesFalseClosed(t *testing.T) { func TestObject_MapAndNothingElseLowersToMapT(t *testing.T) { t.Parallel() i64 := func(v int64) *int64 { return &v } - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string value ir.TypeID bounds *ir.Constraints @@ -108,15 +108,15 @@ func TestObject_MapAndNothingElseLowersToMapT(t *testing.T) { "type/primitive/string", &ir.Constraints{MinProperties: i64(1), MaxProperties: i64(5)}}, {"composed", `{allOf: [{type: object}], additionalProperties: {type: string}}`, "type/primitive/string", nil}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" S: "+tc.schema+"\n")) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" S: "+testCase.schema+"\n")) assert.Empty(t, diags, "a map holds everything the position declared") mt, ok := doc.Types[componentID("S")].(*ir.MapT) require.True(t, ok, "a map and nothing else is a MapT; got %T", doc.Types[componentID("S")]) assert.Nil(t, mt.Key, "JSON object keys are strings, which a nil Key states") - assert.Equal(t, ir.TypeRef{Target: tc.value}, mt.Value) - assert.Empty(t, cmp.Diff(tc.bounds, mt.Constraints)) + assert.Equal(t, ir.TypeRef{Target: testCase.value}, mt.Value) + assert.Empty(t, cmp.Diff(testCase.bounds, mt.Constraints)) }) } } @@ -175,7 +175,7 @@ func TestObject_CatchAllBesideAnotherFactStaysModel(t *testing.T) { const base = " B: {type: object, properties: {b: {type: string}}}\n" anyRef := &ir.AdditionalProperties{Value: &ir.TypeRef{Target: "type/primitive/any"}} stringRef := ir.TypeRef{Target: "type/primitive/string"} - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string catchAll *ir.AdditionalProperties }{ @@ -194,13 +194,13 @@ func TestObject_CatchAllBesideAnotherFactStaysModel(t *testing.T) { {"unwritten", `{type: object}`, nil}, {"closed", `{type: object, additionalProperties: false}`, nil}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(base+" S: "+tc.schema+"\n")) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(base+" S: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("S")].(*ir.Model) require.True(t, ok, "got %T", doc.Types[componentID("S")]) - assert.Empty(t, cmp.Diff(tc.catchAll, model.AdditionalProperties)) + assert.Empty(t, cmp.Diff(testCase.catchAll, model.AdditionalProperties)) }) } } @@ -217,15 +217,15 @@ func TestModel_PatternPropertiesOrder(t *testing.T) { {name: "written in sorted order", patterns: []string{"^x-", "^y-"}}, {name: "written against it", patterns: []string{"^y-", "^x-"}}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(fmt.Sprintf(` S: type: object patternProperties: %q: {type: string} %q: {type: integer} -`, tc.patterns[0], tc.patterns[1])) +`, testCase.patterns[0], testCase.patterns[1])) doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("S")].(*ir.Model) @@ -235,14 +235,14 @@ func TestModel_PatternPropertiesOrder(t *testing.T) { for _, patternProperties := range model.AdditionalProperties.Patterns { got = append(got, patternProperties.Pattern) } - assert.Equal(t, tc.patterns, got) + assert.Equal(t, testCase.patterns, got) }) } } // TestModel_UnevaluatedPropertiesClosedAfterComposition pins where // `unevaluatedProperties: false` is a model's openness: only where no -// additionalProperties stands beside it, which would evaluate every property it +// additionalProperties sits beside it, which would evaluate every property it // could apply to (docs/compilers/openapi.md#additional-properties). Beside one, // the openness is additionalProperties' alone and the keyword is kept with it; // beside patterns alone, nothing types a key no pattern matches. @@ -251,7 +251,7 @@ func TestModel_UnevaluatedPropertiesClosedAfterComposition(t *testing.T) { stringType, top := ir.TypeRef{Target: "type/primitive/string"}, ir.TypeRef{Target: "type/primitive/any"} patterns := []ir.PatternProperties{{Pattern: "^x-", Value: stringType}} const properties, pattern = "properties: {a: {type: string}}", `patternProperties: {"^x-": {type: string}}` - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string mode ir.AdditionalMode catchAll *ir.AdditionalProperties @@ -278,29 +278,30 @@ func TestModel_UnevaluatedPropertiesClosedAfterComposition(t *testing.T) { "", &ir.AdditionalProperties{Value: &stringType, Patterns: patterns}, `{"additionalProperties":{"type":"string"},"unevaluatedProperties":false}`}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(" S: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpec(" S: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, irverify.Verify(doc), "the IR holds its invariants") model, ok := doc.Types[componentID("S")].(*ir.Model) require.True(t, ok, "got %T", doc.Types[componentID("S")]) - assert.Equal(t, tc.mode, model.Additional) - assert.Empty(t, cmp.Diff(tc.catchAll, model.AdditionalProperties)) - if tc.kept == "" { + assert.Equal(t, testCase.mode, model.Additional) + assert.Empty(t, cmp.Diff(testCase.catchAll, model.AdditionalProperties)) + if testCase.kept == "" { assert.NotContains(t, model.Unmodeled, "openapi:unevaluated", "a closure the model holds is kept nowhere else") return } require.Contains(t, model.Unmodeled, "openapi:unevaluated") - assert.Equal(t, tc.kept, string(model.Unmodeled["openapi:unevaluated"].Value)) + assert.Equal(t, testCase.kept, string(model.Unmodeled["openapi:unevaluated"].Value)) }) } } -// TestObject_AnInertClosureLeavesAMap pins that an inert closure leaves a map a -// map: an object whose one member fact is its catch-all is a MapT, which holds -// the keyword beside the catch-all that leaves it inert. -func TestObject_AnInertClosureLeavesAMap(t *testing.T) { +// TestObject_AClosureSayingNothingLeavesAMap pins that a closure saying nothing +// leaves a map a map: an object whose one member fact is its catch-all is a +// MapT, which holds the keyword beside the catch-all that leaves it saying +// nothing. +func TestObject_AClosureSayingNothingLeavesAMap(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( " S: {type: object, additionalProperties: {type: integer}, unevaluatedProperties: false}\n")) diff --git a/compilers/openapi/internal/schema/modelroutes.go b/compilers/openapi/internal/schema/modelroutes.go new file mode 100644 index 000000000..94c1713fe --- /dev/null +++ b/compilers/openapi/internal/schema/modelroutes.go @@ -0,0 +1,491 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "cmp" + "context" + "encoding/json/jsontext" + "encoding/json/v2" + "maps" + "slices" + "strconv" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/merge" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" +) + +// KeptMappingKey is the Unmodeled key a model keeps the entries of its +// discriminator's mapping under that route to neither it nor a subtype of it, +// as one object shaped as the source's mapping. +const KeptMappingKey = "openapi:discriminator/mapping" + +// modelDiscriminators is the run's store of the discriminators models hold, +// which one deferred settlement judges. That is sound while every member is +// folded before a tag is read and no deferred settlement rewrites a supertype +// edge. +type modelDiscriminators struct { + stored map[ir.TypeID]*storedDiscriminator + deferred bool + // admission is the settlement's value admission reader, built at its + // first question, which each route table's is Fresh of (valueAdmission). + admission *ir.ValueAdmissionReader +} + +// storedDiscriminator is one model's discriminator as the store holds it. +type storedDiscriminator struct { + loweringContext lowering.Ctx + model *ir.Model + schema *statement.Schema // writes discriminator: the model's schema or an inline entry of its allOf + discriminator *statement.Discriminator + pointer jsontext.Pointer // where schema is written + besideUnion bool // it sits beside a union kept verbatim + branches []namedBranch // the components that union's $ref branches name +} + +// namedBranch is a union branch naming a component by $ref: the route OpenAPI's +// implicit mapping takes to it, and where the branch is written. +type namedBranch struct { + name string + id ir.TypeID + at jsontext.Pointer +} + +// modelDiscriminatorsOf returns the run's store, which every copy of +// loweringContext shares. +func modelDiscriminatorsOf(loweringContext lowering.Ctx) *modelDiscriminators { + return lowering.Settled(loweringContext, func() *modelDiscriminators { + return &modelDiscriminators{stored: map[ir.TypeID]*storedDiscriminator{}} + }) +} + +// holdModelDiscriminator stores the discriminator model, written at pointer, +// holds, as written says, and queues the run's one settlement of them on the +// first. +func holdModelDiscriminator(loweringContext lowering.Ctx, types *compile.Types, written writtenDiscriminator, pointer jsontext.Pointer, model *ir.Model) { + if model.Discriminator == nil { + return + } + store := modelDiscriminatorsOf(loweringContext) + store.stored[model.ID] = &storedDiscriminator{loweringContext: loweringContext, model: model, schema: written.conjunctSchema, + discriminator: written.discriminator, pointer: pointer + written.rel} + if !store.deferred { + store.deferred = true + types.Defer(modelRouteSettlement{loweringContext: loweringContext, store: store}) + } +} + +// forget drops what the store holds of model, a node a dry run built and +// registered nowhere. +func (s *modelDiscriminators) forget(model *ir.Model) { + if stored, ok := s.stored[model.ID]; ok && stored.model == model { + delete(s.stored, model.ID) + } +} + +// besideKeptUnion marks the discriminator the model id holds as written +// beside the union holder writes, kept verbatim, whose $ref branches it routes +// by name (routesByName). +func (s *modelDiscriminators) besideKeptUnion(loweringContext lowering.Ctx, id ir.TypeID, schema, holder *statement.Schema) { + stored, ok := s.stored[id] + if !ok { + return + } + stored.besideUnion = true + stored.branches = namedBranches(loweringContext, schema, holder) +} + +// modelRouteSettlement judges every model discriminator of the run. +type modelRouteSettlement struct { + loweringContext lowering.Ctx + store *modelDiscriminators +} + +// Settle settles each held discriminator in model ID order against one index +// of the document's facts, swapping a model it leaves a map for its MapT. +func (s modelRouteSettlement) Settle(ctx context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { + *discriminatorFactsCount(s.loweringContext)++ + facts := irfacts.New(&ir.Document{Types: reg}) + var diags []ir.Diagnostic + for _, id := range slices.Sorted(maps.Keys(s.store.stored)) { + if ctx.Err() != nil { + return diags + } + settled, asMap := s.store.stored[id].settle(facts, reg, aliases) + diags = append(diags, settled...) + if asMap != nil { + reg[id] = asMap + } + } + return diags +} + +// settle keeps verbatim each route to a type neither the model nor a subtype +// of it, or the whole discriminator where no route stays typed, and returns +// the MapT the model becomes where that leaves it a map. +func (stored *storedDiscriminator) settle(facts *irfacts.DocumentFacts, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) ([]ir.Diagnostic, *ir.MapT) { + if mt, isMap := reg[stored.model.ID].(*ir.MapT); isMap && mt != nil { + return nil, nil + } + if reg[stored.model.ID] != ir.TypeDef(stored.model) || stored.model.Discriminator == nil { + return []ir.Diagnostic{stored.loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, stored.pointer, + "internal: %q is not the model holding the discriminator its lowering stored, so its routes are not settled", stored.model.ID)}, nil + } + table := newRouteTable(stored, facts, reg, aliases) + table.judge() + if table.lost > 0 && table.empty() { + return stored.keepWhole() + } + table.route() + return table.keep(), nil +} + +// keepWhole moves the model's discriminator, none of whose routes stays +// typed, to its Unmodeled, and returns the model's MapT where that leaves it a +// map. +func (stored *storedDiscriminator) keepWhole() ([]ir.Diagnostic, *ir.MapT) { + model := stored.model + kept, diags := keepSchemaKeyword(stored.loweringContext, &model.Unmodeled, stored.schema, "discriminator", ir.ReasonDegradedLowering, stored.pointer) + if !kept { + return diags, nil + } + model.Discriminator = nil + diags = append(diags, stored.loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, stored.pointer+ids.Ptr("discriminator"), + "every route the discriminator gives names a type that is not a subtype of the model holding it, so "+ + "none stays typed; the discriminator is kept verbatim under Unmodeled")) + if mt, isMap := ir.AsMap(model); isMap { + return diags, mt + } + return diags, nil +} + +// routeTable is one model discriminator's routes as its settlement builds +// them. +type routeTable struct { + stored *storedDiscriminator + facts *irfacts.DocumentFacts + reg ir.TypeRegistry + aliases *ir.AliasChainIndex // the index of reg's alias chains + disc *ir.Discriminator + property string // the tag's wire name + spelled map[string]bool // every key the source's mapping writes + kept map[string]string // each entry kept verbatim, by key + keptIDs map[string]ir.TypeID // the type each kept entry named + keptDef string // the defaultMapping kept verbatim, "" for none + keptDefID ir.TypeID // the type it named + lost int // the routes kept verbatim + byEntry map[ir.TypeID]bool + byName map[ir.TypeID]string // each type routed by its component name + branchOut []namedBranch // the branches naming a type no route can reach + inferred bool // a string a type pins is mapped, by the inference policy + // admission is the table's value admission reader (valueAdmission). + admission *ir.ValueAdmissionReader +} + +// newRouteTable starts the table of stored's discriminator. +func newRouteTable(stored *storedDiscriminator, facts *irfacts.DocumentFacts, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) *routeTable { + table := &routeTable{stored: stored, facts: facts, reg: reg, aliases: aliases, disc: stored.model.Discriminator, property: stored.discriminator.PropertyName, + spelled: map[string]bool{}, kept: map[string]string{}, keptIDs: map[string]ir.TypeID{}, byEntry: map[ir.TypeID]bool{}, byName: map[ir.TypeID]string{}} + for _, entry := range stored.discriminator.Mapping { + table.spelled[entry.Value] = true + } + return table +} + +// routes reports whether target may be routed to: the model itself unless +// Abstract, or a subtype of it, which a mixin is not. +func (t *routeTable) routes(target ir.TypeID) bool { + model := t.stored.model + return (target == model.ID && !model.Abstract) || t.facts.IsSubtype(target, model.ID) +} + +// empty reports whether no route of the table stays typed. +func (t *routeTable) empty() bool { + return len(t.disc.Mapping) == 0 && len(t.disc.DecodeOnlyRoutes) == 0 && t.disc.Default == "" && len(t.byName) == 0 +} + +// judge keeps each entry, the defaultMapping and each branch's name route that +// reaches neither the model nor a subtype of it out of the typed routes, and +// collects the types the rest route to. +func (t *routeTable) judge() { + written := map[string]string{} + for _, entry := range t.stored.discriminator.Mapping { + written[entry.Value] = entry.Target + } + for _, key := range slices.Sorted(maps.Keys(t.disc.Mapping)) { + target := t.disc.Mapping[key] + if t.routes(target) { + t.byEntry[target] = true + continue + } + delete(t.disc.Mapping, key) + t.kept[key], t.keptIDs[key] = written[key], target + t.lost++ + } + if t.disc.Default != "" && !t.routes(t.disc.Default) { + t.keptDef, t.keptDefID = t.stored.discriminator.DefaultMapping, t.disc.Default + t.disc.Default = "" + t.lost++ + } + t.nameRoutes() +} + +// nameRoutes collects the types OpenAPI's implicit mapping routes by component +// name: the model's own and, beside a kept union, each branch's that routes, +// else each subtype's. +func (t *routeTable) nameRoutes() { + model := t.stored.model + if name, ok := entryComponentName(t.stored.loweringContext, t.reg, model.ID); ok && !model.Abstract { + t.byName[model.ID] = name + } + if t.stored.besideUnion { + for _, branch := range t.stored.branches { + if !t.routes(branch.id) { + t.branchOut = append(t.branchOut, branch) + t.lost++ + continue + } + t.byName[branch.id] = branch.name + } + return + } + for _, sub := range t.facts.Subtypes(model.ID) { + if name, ok := entryComponentName(t.stored.loweringContext, t.reg, sub); ok && sub != model.ID { + t.byName[sub] = name + } + } +} + +// route writes each route the names and pinned tags give +// (docs/compilers/openapi.md#discriminator). A name an entry keys is never a +// route of another type, and no tag has two routes. +func (t *routeTable) route() { + fixedTags := t.fixedTagsOfRouted() + pinners := map[string]int{} + for _, set := range fixedTags { + for _, tag := range set { + pinners[tag]++ + } + } + named := slices.SortedFunc(maps.Keys(t.byName), cmp.Compare[ir.TypeID]) + for _, id := range named { + if t.byEntry[id] { + continue + } + for _, tag := range fixedTags[id] { + if pinners[tag] == 1 && !t.spelled[tag] && !t.namesAnother(tag, id) { + t.mapRoute(tag, id) + t.inferred = true + } + } + } + for _, id := range named { + t.routeName(id, fixedTags[id]) + } + if t.inferred { + model := t.stored.model + model.Provenance.Inferred = ir.JoinInferred(model.Provenance.Inferred, lowering.DiscriminatorInferenceHeuristic) + } +} + +// namesAnother reports whether tag is the name of a type other than id that +// the discriminator routes by its name, a route the source gives, which a +// string a type pins does not override. +func (t *routeTable) namesAnother(tag string, id ir.TypeID) bool { + for other, name := range t.byName { + if other != id && name == tag { + return true + } + } + return false +} + +// routeName writes the route the name of id gives once its pinned tags are +// mapped. +func (t *routeTable) routeName(id ir.TypeID, fixedTags []string) { + name := t.byName[id] + if t.spelled[name] { + return + } + switch { + case t.byEntry[id]: + t.decodeOnly(name, id) + case len(fixedTags) > 0: + if t.disc.Mapping[name] != id { + t.decodeOnly(name, id) + } + case t.refusesName(id, name): + t.decodeOnly(name, id) + default: + t.mapRoute(name, id) + } +} + +// mapRoute maps tag to id. No two routes meet at one tag: an entry's key is +// spelled, a pin is one type's alone and no other type's name, and a name is +// one type's. +func (t *routeTable) mapRoute(tag string, id ir.TypeID) { + addRoute(&t.disc.Mapping, tag, id) +} + +// decodeOnly routes tag, a type's own name, to id for a decoder alone. +func (t *routeTable) decodeOnly(tag string, id ir.TypeID) { + addRoute(&t.disc.DecodeOnlyRoutes, tag, id) +} + +// fixedTagsOfRouted returns the strings each routed type pins the tag to, as +// discriminator-inference reads them +// (docs/compilers/openapi.md#discriminator-inference), none where the policy +// is off. +func (t *routeTable) fixedTagsOfRouted() map[ir.TypeID][]string { + fixedTags := map[ir.TypeID][]string{} + if !t.stored.loweringContext.DiscriminatorInference.Honours() { + return fixedTags + } + for id := range t.byEntry { + fixedTags[id] = t.fixedTagsOf(id) + } + for id := range t.byName { + fixedTags[id] = t.fixedTagsOf(id) + } + return fixedTags +} + +// fixedTagsOf returns the strings id pins the tag to, sorted, nil for none. +func (t *routeTable) fixedTagsOf(id ir.TypeID) []string { + got := t.tagOf(id) + if !got.fixesTags() { + return nil + } + return slices.Sorted(slices.Values(got.strings)) +} + +// refusesName reports whether id's tag member refuses name, as the +// discriminator-inference policy reads it. +func (t *routeTable) refusesName(id ir.TypeID, name string) bool { + if !t.stored.loweringContext.DiscriminatorInference.Honours() { + return false + } + return !t.tagOf(id).admits(name) || t.declarationRefuses(id, name) +} + +// declarationRefuses reports whether a declaration of id's tag member, the +// overridden ones included, refuses name: an instance satisfies every one. +func (t *routeTable) declarationRefuses(id ir.TypeID, name string) bool { + member, declared := flatMember(ir.FlattenedProperties(t.reg, id), t.property) + if !declared { + return false + } + value := ir.Value{Kind: ir.ValueString, String: name} + for _, declaration := range slices.Concat([]ir.PropertyDecl{member.PropertyDecl}, member.Overridden) { + if t.valueAdmission().AdmitsAtPosition(declaration.Property.Type, declaration.Property.Constraints, value) == ir.AdmitsNo { + return true + } + } + return false +} + +// valueAdmission returns the table's value admission reader, a Fresh copy of +// the settlement's, since the settlement swaps a model it leaves a map +// between two tables. +func (t *routeTable) valueAdmission() *ir.ValueAdmissionReader { + if t.admission != nil { + return t.admission + } + store := modelDiscriminatorsOf(t.stored.loweringContext) + if store.admission == nil { + store.admission = merge.NewFoldValueAdmissionReader(t.reg.Lookup, t.aliases) + } + t.admission = store.admission.Fresh() + return t.admission +} + +// tagOf returns what an instance of id holds at the tag. +func (t *routeTable) tagOf(id ir.TypeID) tagSet { + flat := ir.FlattenedProperties(t.reg, id) + member, declared := flatMember(flat, t.property) + return tagSetMemoOf(t.stored.loweringContext).object(aliasedTypes{registry: t.reg, aliases: t.aliases}, flat, member, declared, t.property) +} + +// keep keeps what judge set aside verbatim on the model, the entries under +// one object as the source's mapping writes them, and reports each. +func (t *routeTable) keep() []ir.Diagnostic { + var diags []ir.Diagnostic + at := t.stored.pointer + ids.Ptr("discriminator") + model := t.stored.model + if len(t.kept) > 0 { + raw, err := json.Marshal(t.kept, json.Deterministic(true)) + if err == nil { + keepRoute(&model.Unmodeled, KeptMappingKey, raw, t.stored.loweringContext.Place().At(at+ids.Ptr("mapping"))) + } + for _, key := range slices.Sorted(maps.Keys(t.kept)) { + diags = append(diags, t.stored.loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, at+ids.Ptr("mapping", key), + "the mapping routes %q to %s, which is neither the model holding the discriminator nor a subtype of it; "+ + "the entry is kept verbatim under Unmodeled, the other routes typed", key, strconv.Quote(t.kept[key]))) + } + } + if t.keptDef != "" { + raw, err := json.Marshal(t.keptDef) + if err == nil { + keepRoute(&model.Unmodeled, "openapi:discriminator/defaultMapping", raw, t.stored.loweringContext.Place().At(at+ids.Ptr("defaultMapping"))) + } + diags = append(diags, t.stored.loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, at+ids.Ptr("defaultMapping"), + "the defaultMapping names %s, which is neither the model holding the discriminator nor a subtype of it; "+ + "it is kept verbatim under Unmodeled, the other routes typed", strconv.Quote(t.keptDef))) + } + t.recordKeptRoutes(at) + for _, branch := range t.branchOut { + diags = append(diags, t.stored.loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, branch.at, + "the discriminator beside this union routes this branch by its component name, %q, which names a type "+ + "that is neither the model holding the discriminator nor a subtype of it; no route is written for it", + branch.name)) + } + return diags +} + +// recordKeptRoutes saves the type each route kept verbatim names, under at, +// the discriminator's pointer, so the kept entries' Targets name them. +func (t *routeTable) recordKeptRoutes(at jsontext.Pointer) { + trackers := runTrackersOf(t.stored.loweringContext) + source := t.stored.loweringContext.Place().Source + if len(t.kept) > 0 { + landings := make([]Landing, 0, len(t.kept)) + for _, key := range slices.Sorted(maps.Keys(t.kept)) { + landings = append(landings, Landing{ID: t.keptIDs[key], Path: ids.Ptr(key), Ref: t.kept[key]}) + } + trackers.keptDiscriminatorRoutes[LandingSite{Source: source, Pointer: at + ids.Ptr("mapping")}] = landings + } + if t.keptDef != "" { + trackers.keptDiscriminatorRoutes[LandingSite{Source: source, Pointer: at + ids.Ptr("defaultMapping")}] = + []Landing{{ID: t.keptDefID, Ref: t.keptDef}} + } +} + +// keepRoute keeps raw, a route set aside, under key in unmodeled, as a +// route that reaches no typed field (ir.ReasonNoIRHome). +func keepRoute(unmodeled *ir.Unmodeled, key string, raw jsontext.Value, prov ir.Provenance) { + if *unmodeled == nil { + *unmodeled = ir.Unmodeled{} + } + (*unmodeled)[key] = ir.UnmodeledEntry{Reason: ir.ReasonNoIRHome, Value: raw, Provenance: prov} +} + +// entryComponentName returns the name of the entry document's component the +// type id, which reg holds, is, false for any other type: the name OpenAPI's +// implicit mapping routes it by (componentNamed). +func entryComponentName(loweringContext lowering.Ctx, reg ir.TypeRegistry, id ir.TypeID) (string, bool) { + pointer := reg[id].Common().Provenance.Pointer + name, state := ids.ComponentSchema(pointer) + source := ids.DocumentIDNamespace{} + if state != ids.NamedComponent || !loweringContext.DeclaresSchema(name) || source.NamedType(ids.Ptr("components", "schemas", name)) != id { + return "", false + } + return name, true +} diff --git a/compilers/openapi/internal/schema/nodeholds_test.go b/compilers/openapi/internal/schema/nodeholds_test.go new file mode 100644 index 000000000..f282f741e --- /dev/null +++ b/compilers/openapi/internal/schema/nodeholds_test.go @@ -0,0 +1,125 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "go/types" + "reflect" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/internal/decls" + "github.com/dexpace/morphic/ir" +) + +// nodeHoldsIgnores names each field the alias dry run's judge (nodeHolds) +// deliberately does not read, with why: every node a dry run builds has it, +// or it is the use the node names. +var nodeHoldsIgnores = map[string]string{ + "TypeCommon.ID": "every node has its identity", + "TypeCommon.Name": "every node has the hint its position names it by", + "TypeCommon.Anonymous": "every node a position hoists is inline", + "TypeCommon.Provenance": "every node records where it sits; a heuristic it names read a field held", + "Scalar.TypeCommon": "judged field by field", + "Scalar.Base": "the use the alias names", + "Model.TypeCommon": "judged field by field", + "Model.Base": "the use the Model names", +} + +// TestNodeHolds_ReadsEveryFieldItDoesNotName holds nodeHolds to every field +// ir.TypeCommon, ir.Scalar and ir.Model declare, read off the ir package by +// internal/decls, a struct-typed field member by member, recursively: a node +// with that one member set holds something, but for the fields +// nodeHoldsIgnores names. A field or member added later reddens this until +// it is read or named there. +func TestNodeHolds_ReadsEveryFieldItDoesNotName(t *testing.T) { + t.Parallel() + loadedPackage, err := decls.Load("github.com/dexpace/morphic/ir") + require.NoError(t, err) + nodes := map[string]func() ir.TypeDef{ + "Scalar": func() ir.TypeDef { return &ir.Scalar{} }, + "Model": func() ir.TypeDef { return &ir.Model{} }, + } + seen := map[string]bool{} + for _, owner := range []string{"TypeCommon", "Scalar", "Model"} { + named, err := loadedPackage.Named(owner) + require.NoError(t, err) + for _, path := range memberPaths(t, named, nil) { + name := owner + "." + strings.Join(path, ".") + seen[owner+"."+path[0]] = true + _, ignored := nodeHoldsIgnores[owner+"."+path[0]] + for kind, build := range nodes { + if owner != "TypeCommon" && owner != kind { + continue + } + node := build() + member := reflect.ValueOf(node).Elem() + if owner == "TypeCommon" { + member = member.FieldByName("TypeCommon") + } + for _, step := range path { + member = member.FieldByName(step) + } + fill(t, member) + assert.Equal(t, !ignored, schema.NodeHolds(node), "%s on a %s", name, kind) + } + } + } + for name := range nodeHoldsIgnores { + assert.True(t, seen[name], "%s names no field the ir package declares", name) + } +} + +// memberPaths returns the path of each member of named's struct, prefix +// before it, a struct-typed member's own members in its place, recursively, +// and an embedded one whole, as its own type is walked apart. +func memberPaths(t *testing.T, named *types.Named, prefix []string) [][]string { + t.Helper() + structure, isStruct := named.Underlying().(*types.Struct) + require.True(t, isStruct, named.Obj().Name()) + var paths [][]string + for field := range structure.Fields() { + path := append(slices.Clone(prefix), field.Name()) + if nested, isNamed := field.Type().(*types.Named); isNamed && !field.Embedded() { + if _, nestedStruct := nested.Underlying().(*types.Struct); nestedStruct { + paths = append(paths, memberPaths(t, nested, path)...) + continue + } + } + paths = append(paths, path) + } + return paths +} + +// fill sets value, a member of a node that is no struct of its own walked +// member by member, to a value of its type that is not its zero: an embedded +// struct through its first field. +func fill(t *testing.T, value reflect.Value) { + t.Helper() + switch value.Kind() { + case reflect.String: + value.SetString("x") + case reflect.Bool: + value.SetBool(true) + case reflect.Int, reflect.Int64: + value.SetInt(1) + case reflect.Pointer: + value.Set(reflect.New(value.Type().Elem())) + case reflect.Slice: + value.Set(reflect.MakeSlice(value.Type(), 1, 1)) + case reflect.Map: + filled := reflect.MakeMap(value.Type()) + filled.SetMapIndex(reflect.New(value.Type().Key()).Elem(), reflect.New(value.Type().Elem()).Elem()) + value.Set(filled) + case reflect.Struct: + fill(t, value.Field(0)) + default: + t.Fatalf("no value fills a field of kind %s", value.Kind()) + } +} diff --git a/compilers/openapi/internal/schema/null_idiom_reach_test.go b/compilers/openapi/internal/schema/null_idiom_reach_test.go new file mode 100644 index 000000000..716bd99a3 --- /dev/null +++ b/compilers/openapi/internal/schema/null_idiom_reach_test.go @@ -0,0 +1,54 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// idiomReachSpec writes a value keyword of null beside one $ref and a `false` +// conjunct, two conjuncts intersecting in null alone with neither saying null +// alone, and a type of null beside a dynamic reference to an integer. +const idiomReachSpec = ` T: {type: integer} + NM: {$dynamicAnchor: nm, type: integer} + False: {$ref: '#/components/schemas/T', type: 'null', allOf: [false]} + Meet: {allOf: [{type: [string, 'null']}, {type: [integer, 'null']}]} + Dynamic: {$dynamicRef: '#nm', type: 'null'} +` + +// TestNullIdiom_ReadsEachConjunctAndExpansion holds the idiom to the answer's +// widening at each conjunct it reads: a `false` conjunct beside the $ref +// leaves no idiom, the position admitting nothing; conjuncts intersecting in null +// with neither saying null alone admit that null; and a type of null beside a +// dynamic reference is the nullable reference to its expansion with the +// policy on, and with it off narrows the expansion, which is not expanded. +func TestNullIdiom_ReadsEachConjunctAndExpansion(t *testing.T) { + t.Parallel() + for _, off := range []bool{false, true} { + doc, diags := compileNullable(t, openapitest.ComponentSpecVer("3.1.0", idiomReachSpec), off) + require.NotNil(t, typeByName(doc, "False"), off) + _, isScalar := typeByName(doc, "False").(*ir.Scalar) + assert.False(t, isScalar, "policy off %t: a false conjunct leaves no idiom", off) + require.NotNil(t, typeByName(doc, "Meet"), off) + dynamic := typeByName(doc, "Dynamic") + if off { + enum, ok := dynamic.(*ir.Enum) + require.True(t, ok, "policy off: the null narrows the expansion; got %T", dynamic) + assert.Contains(t, enum.Unmodeled, "openapi:$dynamicRef") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Dynamic/$dynamicRef"), + "narrowing it to null") + continue + } + alias, ok := dynamic.(*ir.Scalar) + require.True(t, ok, "policy on: the idiom expands; got %T", dynamic) + assert.Equal(t, inferred(componentID("NM")), *alias.Base) + } +} diff --git a/compilers/openapi/internal/schema/null_intersection_test.go b/compilers/openapi/internal/schema/null_intersection_test.go new file mode 100644 index 000000000..fbb1c7f09 --- /dev/null +++ b/compilers/openapi/internal/schema/null_intersection_test.go @@ -0,0 +1,105 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// nullTypeEquivalent is the twin of conjuncts admitting null alone together, at +// a component and at a property, in a document of version 3.1. +const nullTypeEquivalent = ` S: {type: 'null'} + H: {type: object, properties: {p: {type: 'null'}}} +` + +// TestNullIntersection_ConjunctsSharingOnlyNullLowerAsTheirTwin holds conjuncts +// whose types share null alone, each spelling in every order, at a component +// and at a property: no Model composes and no report says they share no value, +// the IR is the one `{type: 'null'}` lowers to, and nothing is reported, as for +// the twin (docs/compilers/openapi.md#allof-refinement). +func TestNullIntersection_ConjunctsSharingOnlyNullLowerAsTheirTwin(t *testing.T) { + t.Parallel() + equivalent, equivalentDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", nullTypeEquivalent)) + for name, testCase := range map[string]struct{ version, schema string }{ + "3.1 entries": {"3.1.0", "{allOf: [{type: [string, 'null']}, {type: [integer, 'null']}]}"}, + "3.1 entries reversed": {"3.1.0", "{allOf: [{type: [integer, 'null']}, {type: [string, 'null']}]}"}, + "3.0 entries": {"3.0.3", "{allOf: [{type: string, nullable: true}, {type: integer, nullable: true}]}"}, + "3.0 entries reversed": {"3.0.3", "{allOf: [{type: integer, nullable: true}, {type: string, nullable: true}]}"}, + "beside": {"3.1.0", "{type: [string, 'null'], allOf: [{type: [integer, 'null']}]}"}, + "beside after": {"3.1.0", "{allOf: [{type: [integer, 'null']}], type: [string, 'null']}"}, + "three entries": {"3.1.0", "{allOf: [{type: [string, 'null']}, {type: [integer, 'null', boolean]}, {type: [boolean, 'null']}]}"}, + "a null entry": {"3.1.0", "{allOf: [{type: [string, 'null']}, {type: 'null'}]}"}, + "a null entry first": {"3.1.0", "{allOf: [{type: 'null'}, {type: [string, 'null']}]}"}, + "a null entry beside": {"3.1.0", "{type: [string, 'null'], allOf: [{type: 'null'}]}"}, + "a null type beside": {"3.1.0", "{type: 'null', allOf: [{type: [string, 'null']}]}"}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer(testCase.version, + " S: "+testCase.schema+"\n H: {type: object, properties: {p: "+testCase.schema+"}}\n")) + assert.Empty(t, cmp.Diff(equivalent.Types, doc.Types), "the IR of the twin") + assert.Equal(t, equivalentDiags, diags, "the twin's reports, which are none") + }) + } +} + +// TestNullIntersection_ARefSharingOnlyNullIsKept holds a $ref beside an entry, +// the two sharing null alone: the position is the null type, and the $ref, a +// use of no target there, is kept with the one info saying why, in either +// order. +func TestNullIntersection_ARefSharingOnlyNullIsKept(t *testing.T) { + t.Parallel() + for _, schema := range []string{ + "{allOf: [{$ref: '#/components/schemas/NS'}, {type: [integer, 'null']}]}", + "{allOf: [{type: [integer, 'null']}, {$ref: '#/components/schemas/NS'}]}", + } { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " NS: {type: [string, 'null']}\n S: "+schema+"\n")) + enum, ok := typeByName(doc, "S").(*ir.Enum) + if !assert.True(t, ok, "%s: got %T", schema, typeByName(doc, "S")) { + continue + } + assert.Equal(t, ir.PrimitiveAny, enum.ValueType, schema) + assert.Equal(t, []string{"openapi:$ref"}, unmodeledKeys(enum.Unmodeled), schema) + infos := 0 + for _, diagnostic := range diags { + assert.NotEqual(t, ir.SeverityWarning, diagnostic.Severity, "%s: %s", schema, diagnostic.Message) + if diagnostic.Code == diag.DegradedConstruct { + infos++ + assert.Contains(t, diagnostic.Message, "admit null alone together", schema) + } + } + assert.Equal(t, 1, infos, schema) + } +} + +// TestNullIntersection_A30NullEntryLowersAsItsTwin holds the 3.0 spelling of a +// conjunct admitting null alone, `enum: [null]` with `nullable: true`, beside +// a nullable string, in either order: the position is the Enum its twin is, +// typed by no conjunct (docs/compilers/openapi.md#null-alone). +func TestNullIntersection_A30NullEntryLowersAsItsTwin(t *testing.T) { + t.Parallel() + const null = "{enum: [null], nullable: true}" + equivalent, _ := parseFull(t, openapitest.ComponentSpecVer("3.0.3", " S: "+null+"\n")) + want, ok := typeByName(equivalent, "S").(*ir.Enum) + if !assert.True(t, ok, "got %T", typeByName(equivalent, "S")) { + return + } + for _, schema := range []string{ + "{allOf: [{type: string, nullable: true}, " + null + "]}", + "{allOf: [" + null + ", {type: string, nullable: true}]}", + } { + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.0.3", " S: "+schema+"\n")) + enum, ok := typeByName(doc, "S").(*ir.Enum) + if assert.True(t, ok, "%s: got %T", schema, typeByName(doc, "S")) { + assert.Empty(t, cmp.Diff(want, enum), schema) + } + } +} diff --git a/compilers/openapi/internal/schema/nulls_chain_test.go b/compilers/openapi/internal/schema/nullanswer_chain_test.go similarity index 84% rename from compilers/openapi/internal/schema/nulls_chain_test.go rename to compilers/openapi/internal/schema/nullanswer_chain_test.go index 1757eebca..ba9ad2df2 100644 --- a/compilers/openapi/internal/schema/nulls_chain_test.go +++ b/compilers/openapi/internal/schema/nullanswer_chain_test.go @@ -18,13 +18,13 @@ import ( // refChain is n component schemas each `$ref`ing the next, ending on a string // (#1652's generator). func refChain(n int) string { - var b strings.Builder - b.WriteString("openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n schemas:\n") + var builder strings.Builder + builder.WriteString("openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n schemas:\n") for i := range n { - fmt.Fprintf(&b, " S%d: {$ref: '#/components/schemas/S%d'}\n", i, i+1) + fmt.Fprintf(&builder, " S%d: {$ref: '#/components/schemas/S%d'}\n", i, i+1) } - fmt.Fprintf(&b, " S%d: {type: string}\n", n) - return b.String() + fmt.Fprintf(&builder, " S%d: {type: string}\n", n) + return builder.String() } // TestLower_ARefChainIsReadOncePerHop pins the cost of reading what a chain diff --git a/compilers/openapi/internal/schema/nullanswer_cost_test.go b/compilers/openapi/internal/schema/nullanswer_cost_test.go new file mode 100644 index 000000000..b361c6681 --- /dev/null +++ b/compilers/openapi/internal/schema/nullanswer_cost_test.go @@ -0,0 +1,81 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// nullAnswerShapes are the documents the null answer's cost is measured +// over, each of n hops: a chain of allOf references ending on null, the same +// chain closed into a cycle by a union holder naming its first hop beside a +// null branch, and the chain with a use of every hop, each entering it at +// another schema. +var nullAnswerShapes = []struct { + name string + spec func(n int) string +}{ + {"an allOf chain", func(n int) string { return nullAnswerChain(n, "{type: 'null'}", false) }}, + {"a cycle through a union holder", func(n int) string { + return nullAnswerChain(n, "{anyOf: [{$ref: '#/components/schemas/C0'}, {type: 'null'}]}", false) + }}, + {"many uses of one chain", func(n int) string { return nullAnswerChain(n, "{type: 'null'}", true) }}, +} + +// nullAnswerChain is n component schemas, each but the last an allOf naming +// the next and the last written last, with, where uses, a model whose n +// properties each name one hop. +func nullAnswerChain(n int, last string, uses bool) string { + var builder strings.Builder + for i := range n - 1 { + fmt.Fprintf(&builder, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}]}\n", i, i+1) + } + fmt.Fprintf(&builder, " C%d: %s\n", n-1, last) + if uses { + builder.WriteString(" Uses:\n type: object\n properties:\n") + for i := range n { + fmt.Fprintf(&builder, " p%d: {$ref: '#/components/schemas/C%d'}\n", i, i) + } + } + return openapitest.ComponentSpec(builder.String()) +} + +// TestNullAnswer_ReadsGrowLinearlyWithTheSchemasRead pins the cost of the +// null answer, which reads each schema once per run in dependency order and +// settles a cycle in time linear in its edges: over each shape at 1,000, 2,000 +// and 4,000 hops, the readings the run makes, counted through the read-once +// store, grow by at most 2.5 times as much over the second doubling as over +// the first, and are at least one per hop. Each size compiles with no +// finding, and its first hop admits the null the chain ends on. +func TestNullAnswer_ReadsGrowLinearlyWithTheSchemasRead(t *testing.T) { + t.Parallel() + for _, shape := range nullAnswerShapes { + t.Run(shape.name, func(t *testing.T) { + t.Parallel() + reads := map[int]int{} + for _, n := range []int{1000, 2000, 4000} { + doc, diags, count := schema.LowerSpecCountingNullReads(t, shape.spec(n)) + require.Empty(t, diags, "n=%d", n) + require.GreaterOrEqual(t, count, n, "n=%d: every hop is read", n) + first, ok := doc.Types[ir.TypeID("type/openapi/components/schemas/C0")].(*ir.Scalar) + require.True(t, ok, "n=%d", n) + require.NotNil(t, first.Base, "n=%d", n) + assert.True(t, first.Base.Nullable, "n=%d: the first hop admits the null the chain ends on", n) + reads[n] = count + } + require.Positive(t, reads[2000]-reads[1000], "the count grows with the hops: %v", reads) + assert.LessOrEqual(t, float64(reads[4000]-reads[2000]), 2.5*float64(reads[2000]-reads[1000]), + "the second doubling costs about what the first did, not four times: %v", reads) + }) + } +} diff --git a/compilers/openapi/internal/schema/nulls_cut_test.go b/compilers/openapi/internal/schema/nullanswer_cut_test.go similarity index 54% rename from compilers/openapi/internal/schema/nulls_cut_test.go rename to compilers/openapi/internal/schema/nullanswer_cut_test.go index 9f1d742ba..754eb4771 100644 --- a/compilers/openapi/internal/schema/nulls_cut_test.go +++ b/compilers/openapi/internal/schema/nullanswer_cut_test.go @@ -12,13 +12,13 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/schema" ) -// TestLower_AChainEndTheConjunctBudgetCutsShortIsReadAgain pins that what a -// reference site lands on is kept for the later sites of its chain only where -// the read that made it ran within its conjunct budget: two properties naming -// a chain of two aliases over a schema of a few members read each hop once, and -// over one of more members than the budget (256) reads the hops again for the -// second property, as a read with a budget of its own may read the rest. -func TestLower_AChainEndTheConjunctBudgetCutsShortIsReadAgain(t *testing.T) { +// TestLower_AChainEndIsReadOnceWhateverItsWidth pins that what a reference +// site lands on is read once per compile for every later site of its chain, +// however many schemas the end conjoins: two properties naming a chain of two +// aliases read each hop once over an end of a few members and over one of +// more members than a walk on a budget of 256 schemas read, since no reading +// is cut short (docs/compilers/openapi.md#nullable). +func TestLower_AChainEndIsReadOnceWhateverItsWidth(t *testing.T) { t.Parallel() reads := func(members int) int { end := strings.TrimSuffix(strings.Repeat("{type: string}, ", members), ", ") @@ -32,9 +32,6 @@ func TestLower_AChainEndTheConjunctBudgetCutsShortIsReadAgain(t *testing.T) { return count } - within := reads(10) - cut := reads(300) - - assert.Equal(t, 3, within, "read once per hop") - assert.Greater(t, cut, within, "a reading the budget cut short is read again by the next site") + assert.Equal(t, 3, reads(10), "read once per hop") + assert.Equal(t, 3, reads(300), "read once per hop, though the end conjoins more schemas than a budget held") } diff --git a/compilers/openapi/internal/schema/nullanswer_internal_test.go b/compilers/openapi/internal/schema/nullanswer_internal_test.go new file mode 100644 index 000000000..259d47b67 --- /dev/null +++ b/compilers/openapi/internal/schema/nullanswer_internal_test.go @@ -0,0 +1,145 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "strings" + "testing" + + "github.com/speakeasy-api/openapi/jsonschema/oas3" + "github.com/speakeasy-api/openapi/marshaller" + soa "github.com/speakeasy-api/openapi/openapi" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestRefNullRef_AnUnresolvedRefIsNotNullable pins the guard on the second half +// of the question. A $ref site admits null as its own keywords and its target +// jointly say; a reference no binding resolved has no target to ask, and must +// read as not-nullable rather than dereference nothing. +func TestRefNullRef_AnUnresolvedRefIsNotNullable(t *testing.T) { + t.Parallel() + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + valErrs, err := marshaller.Unmarshal(t.Context(), + strings.NewReader("$ref: '#/components/schemas/Missing'"), jsonSchema) + require.NoError(t, err) + require.Empty(t, valErrs, "the fixture parses cleanly") + + ref, diags := refNullRef(NewRawLowerer(&soa.OpenAPI{}).Ctx, "type/x", Standalone(jsonSchema), "/x") + assert.Equal(t, ir.TypeRef{Target: "type/x"}, ref) + assert.Empty(t, diags) +} + +// TestSchemaAdmitsNull_ReadsANullAtAnyDepth pins that no depth cuts the null +// reading: a null any number of schemas down an allOf nest is read, at a depth +// a walk on a budget of 256 schemas said nothing past and well beyond it +// (docs/compilers/openapi.md#nullable), and one ending on no null is read so. +func TestSchemaAdmitsNull_ReadsANullAtAnyDepth(t *testing.T) { + t.Parallel() + chain := func(levels int, leaf string) *oas3.Schema { + src := strings.Repeat("{allOf: [", levels) + leaf + strings.Repeat("]}", levels) + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader(src), jsonSchema) + require.NoError(t, err) + require.Empty(t, valErrs) + return jsonSchema.GetSchema() + } + loweringContext := NewRawLowerer(&soa.OpenAPI{}).Ctx + for _, levels := range []int{1, 255, 256, 257, 300} { + assert.True(t, schemaAdmitsNull(loweringContext, StandaloneSchema(chain(levels, "{type: [string, 'null']}"))), "%d levels down", levels) + } + assert.False(t, schemaAdmitsNull(loweringContext, StandaloneSchema(chain(300, "{type: string}"))), "a nest ending on no null admits none") +} + +// TestNulls_AnEntryWithNoSchemaSaysNothing pins the guard on an +// absent allOf entry. The parser never produces a nil entry, so nothing in the +// corpus reaches it; a conjunct that is not there constrains nothing, which is +// silence rather than a refusal — reading it as forbidding would let one +// missing entry strip a sibling's null. +func TestNulls_AnEntryWithNoSchemaSaysNothing(t *testing.T) { + t.Parallel() + loweringContext := NewRawLowerer(&soa.OpenAPI{}).Ctx + assert.Equal(t, nullAnswerReadingsAlike(nullSaysNothing), nullAnswerReadingsOf(loweringContext, nil)) + assert.Equal(t, nullAnswerReadingsAlike(nullSaysNothing), nullAnswerReadingsOf(loweringContext, Standalone(openapitest.EmptyEitherSchema())), + "an entry whose either-value holds neither schema nor bool says nothing either") +} + +// TestNullAlone_IsTheWholeSchemasReading holds the reading a null branch is +// taken by to the one every Nullable site shares: over a schema whose own +// keywords leave no value but null, a type of null alone deciding over an +// enum beside it, NullAlone is what the schema's answer gives under each +// reading and each dialect's nullable, so the union that lifts the branch and +// the branch lowered alone cannot disagree. +func TestNullAlone_IsTheWholeSchemasReading(t *testing.T) { + t.Parallel() + schemas := []string{ + `{type: "null"}`, `{type: ["null", "null"]}`, `{enum: [null]}`, `{const: null}`, + `{type: string, const: null}`, `{type: [string, "null"], enum: [null]}`, `{type: string, enum: [null]}`, + `{type: object, enum: [null], nullable: true}`, `{type: string, const: null, nullable: true}`, + `{type: "null", nullable: false}`, `{enum: [null], const: 1}`, `{type: "null", enum: [null, a]}`, `{type: "null", enum: [a]}`, + } + for _, version := range []string{"3.0.3", "3.1.0"} { + var body strings.Builder + for i, s := range schemas { + body.WriteString(" S" + string(rune('a'+i)) + ": " + s + "\n") + } + for _, policy := range []bool{false, true} { + lowerer, _ := LoweredWith(t, openapitest.ComponentSpecVer(version, body.String()), lowering.Policy{NullableInference: lowering.NullableInference{Disabled: policy}}) + for i, src := range schemas { + if version == "3.0.3" && src == `{type: ["null", "null"]}` { + continue // 3.0 writes no type list, so it reads this one as left out + } + s := StatedIn(lowerer, componentSchema(t, lowerer, "S"+string(rune('a'+i)))) + require.True(t, leavesOnlyNull(lowerer.Ctx, s), "%s %s leaves no value but null", version, src) + answer := nullAnswerReadingsOf(lowerer.Ctx, lowerer.Ctx.Statements().Read(s)) + assert.Equal(t, answer.selected(lowerer.Ctx) == nullAdmittedByReference, NullAlone(lowerer.Ctx, s), "%s %s", version, src) + } + } + } + lowererValue, _ := LoweredFor(t, openapitest.ComponentSpec(" S: {type: [string, \"null\"]}\n")) + assert.False(t, leavesOnlyNull(lowererValue.Ctx, StatedIn(lowererValue, componentSchema(t, lowererValue, "S"))), + "a type admitting a string leaves more than null") +} + +// TestNullAnswerOf_ReadsASchemaOnce pins that a schema's answer is read once +// a run, since every reader of a union asks of every branch, and an enum of +// nulls costs a read per member: it goes after the first read, which no +// lowering does, so only a remembered answer stays. +func TestNullAnswerOf_ReadsASchemaOnce(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" S: {enum: [null]}\n U: {oneOf: [{type: string}, {type: 'null'}]}\n")) + for _, name := range []string{"S", "U"} { + s := StatedIn(lowerer, componentSchema(t, lowerer, name)) + schemaStatement := lowerer.Ctx.Statements().Read(s) + first := nullAnswerReadingsOf(lowerer.Ctx, schemaStatement) + require.Equal(t, nullAnswerReadingsAlike(nullAdmittedByReference), first, name) + s.Values, s.Choice = nil, nil + assert.Equal(t, first, nullAnswerReadingsOf(lowerer.Ctx, schemaStatement), "%s: the second ask reads what the first read", name) + } +} + +// TestNullAnswerOf_AUnionBesideABodyReadsItsBranches pins that a union's null +// is its branches' wherever it is written and however it lowers: beside a body +// the bindings place nowhere, which no position distributes the union at, its +// null branch admits null for the reference, and the body's type takes it away. +func TestNullAnswerOf_AUnionBesideABodyReadsItsBranches(t *testing.T) { + t.Parallel() + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader( + "{type: object, properties: {p: {type: string}}, oneOf: [{type: object}, {type: 'null'}]}"), jsonSchema) + require.NoError(t, err) + require.Empty(t, valErrs, "the fixture parses cleanly") + + loweringContext := NewRawLowerer(&soa.OpenAPI{}).Ctx + schemaStatement := Standalone(jsonSchema) + require.True(t, hasUnionSiblings(loweringContext, schemaStatement.Schema), "the union sits beside a body") + answer := nullAnswerReadingsOf(loweringContext, schemaStatement) + branches := ownUnionsNull(loweringContext, schemaStatement.Schema, nullSkip{}, nullAnswerMemoOf(loweringContext).settled) + assert.Equal(t, nullAnswerReadingsAlike(nullAdmittedByReference), branches, "the null branch is the union's null") + assert.Equal(t, nullAnswerReadingsAlike(nullForbidden), answer, "the object type takes it away") +} diff --git a/compilers/openapi/internal/schema/nullanswer_reports_test.go b/compilers/openapi/internal/schema/nullanswer_reports_test.go new file mode 100644 index 000000000..018669bf9 --- /dev/null +++ b/compilers/openapi/internal/schema/nullanswer_reports_test.go @@ -0,0 +1,225 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// TestNullableInference_WhyNamesTheUnionOrEntryTheNullIsBeside pins the +// reason a `nullable: true` read in gives (docs/compilers/openapi.md#nullable): +// beside a union none of whose branches admits null, the union by its +// keyword, never an allOf the schema does not write; and on an allOf entry +// whose own keywords admit null, the conjunct beside it that excludes null. +func TestNullableInference_WhyNamesTheUnionOrEntryTheNullIsBeside(t *testing.T) { + t.Parallel() + for _, testCase := range []struct{ p, at, why string }{ + {"{type: string, nullable: true, anyOf: [{type: string, minLength: 1}]}", "/nullable", "anyOf admits null in none"}, + {"{type: string, nullable: true, oneOf: [{type: string, minLength: 1}]}", "/nullable", "oneOf admits null in none"}, + {"{type: string, allOf: [{nullable: true, enum: [a, null]}]}", "/allOf/0/nullable", "another conjunct of this allOf excludes null"}, + } { + doc, diags := compileNullable(t, openapitest.HolderSpec("3.0.3", testCase.p, ""), false) + assert.True(t, holderP(t, doc).Nullable, testCase.p) + assert.NotEmpty(t, holderP(t, doc).Inferred, testCase.p) + message := openapitest.DiagMessageAt(t, diags, diag.InferredNullable, ir.SeverityInfo, "/components/schemas/Holder/properties/p"+testCase.at) + assert.Contains(t, message, testCase.why, testCase.p) + if testCase.at == "/nullable" { + assert.NotContains(t, message, "allOf", testCase.p) + } + } +} + +// TestNullAlone_ALiftedBranchKeepsTheMembersItsTypeExcludes pins a union +// branch of a type of null alone beside an enum listing null and another +// value (docs/compilers/openapi.md#null-alone): the type decides, so the +// branch is the union's null, lifted onto the reference, and kept whole under +// its entry key at the union's position as degraded, the member it excludes +// reported where it is written, and the target keeping nothing of it. +func TestNullAlone_ALiftedBranchKeepsTheMembersItsTypeExcludes(t *testing.T) { + t.Parallel() + doc, diags := compileNullable(t, openapitest.HolderSpec("3.1.0", "{$ref: '#/components/schemas/P'}", + " X: {type: object, properties: {a: {type: string}}}\n"+ + " P: {oneOf: [{$ref: '#/components/schemas/X'}, {type: 'null', enum: [null, a]}]}\n"), false) + assert.True(t, holderP(t, doc).Nullable) + alias, ok := typeByName(doc, "P").(*ir.Scalar) + require.True(t, ok, "P collapses to its $ref") + kept, ok := alias.Unmodeled["openapi:oneOf/1"] + require.True(t, ok, "%+v", alias.Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) + assert.Contains(t, string(kept.Value), `"a"`) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/P/oneOf/1/enum/1")) + assert.Empty(t, typeByName(doc, "X").Common().Unmodeled) +} + +// TestNullAlone_AMemberNoValueHoldsIsNamedByItsText pins the report of an enum +// member beside a type of null alone that converts to no value: it names the +// member as written, and the enum, which no JSON holds, is reported as kept in +// no form at all. +func TestNullAlone_AMemberNoValueHoldsIsNamedByItsText(t *testing.T) { + t.Parallel() + _, diags := compileNullable(t, openapitest.ComponentSpec(" E: {type: 'null', enum: [null, .nan]}\n"), false) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, "/components/schemas/E/enum/1"), + `enum member ".nan" is no value of the declared type null`) + assert.True(t, openapitest.HasDiag(diags, diag.UnpreservableConstruct), "the enum no JSON holds: %+v", diags) +} + +// TestNullIdiom_AnEmptyEnumBesideAReferenceSaysNoNullAlone pins that +// `enum: []` beside a $ref states no null of the idiom, a `nullable: true` +// beside it or not: it admits no value, so the position is the closed empty +// Enum keeping the $ref. Alone it admits no null; the nullable widens the +// reference, which the policy reports. +func TestNullIdiom_AnEmptyEnumBesideAReferenceSaysNoNullAlone(t *testing.T) { + t.Parallel() + for _, testCase := range []struct { + beside string + nullable bool + }{{"enum: []", false}, {"nullable: true, enum: []", true}} { + doc, diags := compileNullable(t, openapitest.HolderSpec("3.1.0", "{$ref: '#/components/schemas/X', "+testCase.beside+"}", + " X: {type: object, properties: {a: {type: string}}}\n"), false) + ref := holderP(t, doc) + assert.Equal(t, testCase.nullable, ref.Nullable, testCase.beside) + enum, ok := doc.Types[ref.Target].(*ir.Enum) + require.True(t, ok, "%s: %T", testCase.beside, doc.Types[ref.Target]) + assert.Empty(t, enum.Members, testCase.beside) + assert.Equal(t, testCase.nullable, len(withCode(diags, diag.InferredNullable)) == 1, testCase.beside) + } +} + +// TestNullableInference_AnEntryWritingPropertiesWidensTheAllOf pins that a +// `nullable: true` on any object of a conjunction holding no reference, an +// allOf entry writing properties among them, admits null for the whole of it, +// as the flat twin writing them in one object does, reported once at the +// keyword and kept nowhere. +func TestNullableInference_AnEntryWritingPropertiesWidensTheAllOf(t *testing.T) { + t.Parallel() + for name, p := range map[string]string{ + "on an entry": "{type: object, allOf: [{nullable: true, properties: {x: {type: string}}}], oneOf: [{type: object, required: [x]}]}", + "flat": "{type: object, nullable: true, properties: {x: {type: string}}, oneOf: [{type: object, required: [x]}]}", + } { + doc, diags := compileNullable(t, openapitest.HolderSpec("3.0.3", p, ""), false) + ref := holderP(t, doc) + assert.True(t, ref.Nullable, name) + assert.NotEmpty(t, ref.Inferred, name) + assert.NotContains(t, doc.Types[ref.Target].Common().Unmodeled, "openapi:nullable", name) + assert.Len(t, withCode(diags, diag.InferredNullable), 1, name) + } +} + +// TestNullableInference_ANullableBesideAReferenceItWidensNothingIsReported pins +// the warning at a `nullable: true` the policy widens nothing by, beside a $ref +// and a union, structure, a second reference or a conjunct excluding null, an +// enum beside it in its own object among them, which it does not override: it +// admits no null there, and the warning names each conjunct keeping null out, +// by its path from the position, and the reference left without one; beside a +// reference the policy widens, and beside one admitting null, it says nothing +// of the kind. +func TestNullableInference_ANullableBesideAReferenceItWidensNothingIsReported(t *testing.T) { + t.Parallel() + const rest = " X: {type: object, properties: {a: {type: string}}}\n Y: {type: object}\n N: {type: [object, 'null']}\n" + + " S: {type: string}\n" + // An entry nested past the flattening depth is named by the allOf the + // last conjunct read whole writes. + deep := "{type: object}" + for range statement.MaxFlattenDepth + 1 { + deep = "{allOf: [" + deep + "]}" + } + capped := "allOf/1" + strings.Repeat("/allOf/0", statement.MaxFlattenDepth) + "/allOf" + const own, entry = "a reference to this schema", "a reference to the schema writing this allOf" + for _, testCase := range []struct { + p, at, excluded, holder string + }{ + {"{$ref: '#/components/schemas/X', nullable: true, oneOf: [{required: [a]}, {required: [b]}]}", "/nullable", + "$ref (#/components/schemas/X) excludes", own}, + {"{$ref: '#/components/schemas/X', nullable: true, oneOf: [{type: string}, {type: integer}]}", "/nullable", + "oneOf and $ref (#/components/schemas/X) exclude", own}, + {"{$ref: '#/components/schemas/X', nullable: true, properties: {b: {type: string}}}", "/nullable", + "$ref (#/components/schemas/X) excludes", own}, + {"{allOf: [{$ref: '#/components/schemas/X'}, {$ref: '#/components/schemas/Y'}], nullable: true}", "/nullable", + "allOf/0/$ref (#/components/schemas/X) and allOf/1/$ref (#/components/schemas/Y) exclude", own}, + {"{allOf: [{$ref: '#/components/schemas/X'}, {type: object}], nullable: true}", "/nullable", + "allOf/0/$ref (#/components/schemas/X) and allOf/1/type exclude", own}, + {"{allOf: [{$ref: '#/components/schemas/X'}, {nullable: true, properties: {b: {}}}]}", "/allOf/1/nullable", + "allOf/0/$ref (#/components/schemas/X) excludes", entry}, + {"{allOf: [{$ref: '#/components/schemas/X'}, {nullable: true, properties: {b: {}}}], type: object}", "/allOf/1/nullable", + "type and allOf/0/$ref (#/components/schemas/X) exclude", entry}, + {"{$ref: '#/components/schemas/S', nullable: true, enum: [a]}", "/nullable", + "enum and $ref (#/components/schemas/S) exclude", own}, + {"{$ref: '#/components/schemas/S', nullable: true, const: a, properties: {b: {}}}", "/nullable", + "const and $ref (#/components/schemas/S) exclude", own}, + {"{allOf: [{$ref: '#/components/schemas/S'}, {nullable: true}], enum: [a]}", "/allOf/1/nullable", + "enum and allOf/0/$ref (#/components/schemas/S) exclude", entry}, + {"{allOf: [{$ref: '#/components/schemas/X'}, " + deep + "], nullable: true}", "/nullable", + "allOf/0/$ref (#/components/schemas/X) and " + capped + " exclude", own}, + {"{$ref: '#/components/schemas/X', nullable: true}", "/nullable", "", ""}, + {"{$ref: '#/components/schemas/N', nullable: true, properties: {b: {type: string}}}", "/nullable", "", ""}, + } { + doc, diags := compileNullable(t, openapitest.HolderSpec("3.1.0", testCase.p, rest), false) + at := "/components/schemas/Holder/properties/p" + testCase.at + assert.Equal(t, testCase.excluded != "", openapitest.HasDiagCodeAt(diags, diag.UnwidenedNullable, at), testCase.p) + if testCase.excluded != "" { + assert.False(t, holderP(t, doc).Nullable, testCase.p) + assert.Equal(t, "nullable: true makes nothing nullable here: "+testCase.excluded+" null, so "+testCase.holder+ + " is not nullable; the nullable-inference policy widens only a $ref standing alone", + openapitest.DiagMessageAt(t, diags, diag.UnwidenedNullable, ir.SeverityWarning, at), testCase.p) + } + _, offDiags := compileNullable(t, openapitest.HolderSpec("3.1.0", testCase.p, rest), true) + assert.Empty(t, withCode(offDiags, diag.UnwidenedNullable), "policy off: %s", testCase.p) + } +} + +// TestNullIdiom_WithThePolicyOffAValueSetOfNullBesideAReferenceDrawsOneReport +// pins the one report a value set of null alone draws with the policy off +// beside a $ref whose target admits no null: the conjuncts' sharing no value, +// at the schema, and none at the const or the member; an enum some of whose +// members are left draws its finding at the null, and a type beside the const +// excluding null draws its finding at the const. +func TestNullIdiom_WithThePolicyOffAValueSetOfNullBesideAReferenceDrawsOneReport(t *testing.T) { + t.Parallel() + for _, testCase := range []struct{ p, at string }{ + {"{$ref: '#/components/schemas/X', const: null}", ""}, + {"{$ref: '#/components/schemas/X', enum: [null]}", ""}, + {"{$ref: '#/components/schemas/S', enum: [a, null]}", "/enum/1"}, + {"{type: string, const: null}", "/const"}, + } { + _, diags := compileNullable(t, openapitest.HolderSpec("3.1.0", testCase.p, + " X: {type: object, properties: {a: {type: string}}}\n S: {type: string}\n"), true) + warnings := withCode(diags, diag.UnsatisfiableSchema) + require.Len(t, warnings, 1, "%s: %+v", testCase.p, warnings) + assert.Equal(t, "/components/schemas/Holder/properties/p"+testCase.at, string(warnings[0].Provenance.Pointer), testCase.p) + } +} + +// TestUnionPair_SharingANullThePolicyReadsIsNotApart pins the report of a +// oneOf and an anyOf sharing only a null the nullable-inference policy reads +// in: under the policy they share it, so the union reading leaves the position +// that null alone, the one report naming the oneOf's dead string branch at its +// keyword, as every null-alone outcome names its dead branches, none the +// position, and the reference admits it, marked inferred; with the policy off +// they share nothing, and the report at the position remains. +func TestUnionPair_SharingANullThePolicyReadsIsNotApart(t *testing.T) { + t.Parallel() + src := openapitest.HolderSpec("3.1.0", "{$ref: '#/components/schemas/P1'}", + " P1: {oneOf: [{type: object, nullable: true, enum: [null]}, {type: string}], anyOf: [{type: 'null'}, {type: integer}]}\n") + on, onDiags := compileNullable(t, src, false) + assert.Equal(t, inferred(componentID("P1")), holderP(t, on)) + enum, ok := typeByName(on, "P1").(*ir.Enum) + require.True(t, ok, "the pair leaves the policy's null alone; got %T", typeByName(on, "P1")) + assert.Empty(t, enum.Members) + reported := withCode(diagsUnder(onDiags, "/components/schemas/P1"), diag.UnsatisfiableSchema) + require.Len(t, reported, 1) + assert.Equal(t, "/components/schemas/P1/oneOf", string(reported[0].Provenance.Pointer)) + assert.Contains(t, reported[0].Message, "(oneOf/1: string)") + off, offDiags := compileNullable(t, src, true) + assert.False(t, holderP(t, off).Nullable) + assert.True(t, openapitest.HasDiagCodeAt(offDiags, diag.UnsatisfiableSchema, "/components/schemas/P1")) +} diff --git a/compilers/openapi/internal/schema/nulls_test.go b/compilers/openapi/internal/schema/nullanswer_test.go similarity index 87% rename from compilers/openapi/internal/schema/nulls_test.go rename to compilers/openapi/internal/schema/nullanswer_test.go index f85ce9b86..6749e9824 100644 --- a/compilers/openapi/internal/schema/nulls_test.go +++ b/compilers/openapi/internal/schema/nullanswer_test.go @@ -71,7 +71,7 @@ func TestNullableInference_EachShapeReadsByItsVersion(t *testing.T) { const at = "/components/schemas/Holder/properties/p" anonymous := ir.TypeID("type/anonymous/components/schemas/Holder/properties/p") stringType := ir.TypeRef{Target: primitive(ir.PrimitiveString)} - for _, tc := range []struct { + for _, testCase := range []struct { name, version, p, rest string on, off ir.TypeRef // report is where the policy reports the null it reads in, and why a @@ -98,9 +98,15 @@ func TestNullableInference_EachShapeReadsByItsVersion(t *testing.T) { ir.TypeRef{Target: anonymous, Nullable: true}, ir.TypeRef{Target: anonymous, Nullable: true}, "", "", ""}, {"3.0 beside a const", "3.0.3", "{type: string, nullable: true, const: a}", "", inferred(anonymous), ir.TypeRef{Target: anonymous}, at + "/nullable", "const is not null", ""}, - {"3.0 beside an allOf excluding null", "3.0.3", + // A type naming the one kind the $ref's target admits restates it and + // says nothing, so the schema is the nullable reference its twin + // writing no type is, under either policy. + {"3.0 beside an allOf excluding null, a type restating its $ref", "3.0.3", "{type: object, nullable: true, allOf: [{$ref: '#/components/schemas/Pet'}]}", "", - inferred(anonymous), ir.TypeRef{Target: anonymous}, at + "/nullable", "allOf entry", ""}, + inferred(componentID("Pet")), ir.TypeRef{Target: anonymous}, at + "/nullable", "allOf entry", ""}, + {"3.0 beside an allOf excluding null, its twin writing no type", "3.0.3", + "{nullable: true, allOf: [{$ref: '#/components/schemas/Pet'}]}", "", + inferred(componentID("Pet")), ir.TypeRef{Target: anonymous}, at + "/nullable", "writes none", ""}, {"3.0 beside a $ref", "3.0.3", "{$ref: '#/components/schemas/Plain', nullable: true}", "", inferred(componentID("Plain")), ir.TypeRef{Target: componentID("Plain")}, at + "/nullable", "writes none", ""}, {"3.1 beside a $ref", "3.1.0", "{$ref: '#/components/schemas/Plain', nullable: true}", "", @@ -146,10 +152,12 @@ func TestNullableInference_EachShapeReadsByItsVersion(t *testing.T) { "{$ref: '#/components/schemas/Plain', type: string, nullable: true}", "", inferred(componentID("Plain")), ir.TypeRef{Target: componentID("Plain")}, at + "/nullable", "lands on excludes null", ""}, + // Two references in one conjunction leave the policy nothing to widen: + // it reads a null as one reference or null. {"3.0 beside a $ref, a type and an allOf excluding null, which compose", "3.0.3", "{$ref: '#/components/schemas/Free', type: object, nullable: true, allOf: [{$ref: '#/components/schemas/Pet'}]}", " Free: {}\n", - inferred(anonymous), ir.TypeRef{Target: anonymous}, at + "/nullable", "allOf entry", ""}, + ir.TypeRef{Target: anonymous}, ir.TypeRef{Target: anonymous}, "", "", ""}, {"3.1 in an allOf entry of the target a $ref lands on", "3.1.0", "{$ref: '#/components/schemas/N'}", " N: {allOf: [{type: string, nullable: true}]}\n", inferred(componentID("N")), ir.TypeRef{Target: componentID("N")}, "/components/schemas/N/allOf/0/nullable", @@ -190,26 +198,26 @@ func TestNullableInference_EachShapeReadsByItsVersion(t *testing.T) { "oneOf: [{$ref: '#/components/schemas/Pet'}, {type: object}]}", "", inferred(anonymous), ir.TypeRef{Target: anonymous}, at + "/nullable", "no nullable keyword", ""}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - src := openapitest.HolderSpec(tc.version, tc.p, tc.rest) + src := openapitest.HolderSpec(testCase.version, testCase.p, testCase.rest) for _, off := range []bool{false, true} { doc, diags := compileNullable(t, src, off) - want, reports := tc.on, openapitest.PointersOf(diags, diag.InferredNullable) + want, reports := testCase.on, openapitest.PointersOf(diags, diag.InferredNullable) if off { - want = tc.off + want = testCase.off } assert.Equal(t, want, holderP(t, doc), "policy off: %v", off) - if off || tc.report == "" { + if off || testCase.report == "" { assert.Empty(t, reports, "policy off: %v", off) continue } - wantReports := []jsontext.Pointer{tc.report} - if tc.also != "" { - wantReports = append(wantReports, tc.also) + wantReports := []jsontext.Pointer{testCase.report} + if testCase.also != "" { + wantReports = append(wantReports, testCase.also) } assert.Equal(t, wantReports, reports) - assert.Contains(t, diagMessage(diags, diag.InferredNullable), tc.why) + assert.Contains(t, diagMessage(diags, diag.InferredNullable), testCase.why) } }) } @@ -260,7 +268,7 @@ func TestNullableInference_AnEnumsNullMemberFollowsTheReadingInForce(t *testing. holder, ok := doc.Types["type/openapi/components/schemas/Holder"].(*ir.Model) require.True(t, ok) assert.Equal(t, !disabled, holder.Properties[0].Type.Nullable, "the reference admits null only under the policy") - assert.Equal(t, disabled, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, member), + assert.Equal(t, disabled, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, member), "the null is reported as admitting nothing only where the reading excludes it") } } @@ -268,21 +276,19 @@ func TestNullableInference_AnEnumsNullMemberFollowsTheReadingInForce(t *testing. // chainSpec is a document of the version whose Holder.p reaches end through n // aliases, each a bare $ref to the one before. func chainSpec(version, end string, n int) string { - var b strings.Builder - b.WriteString(" End: " + end + "\n") + var builder strings.Builder + builder.WriteString(" End: " + end + "\n") prev := "End" for i := range n { - fmt.Fprintf(&b, " A%d: {$ref: '#/components/schemas/%s'}\n", i, prev) + fmt.Fprintf(&builder, " A%d: {$ref: '#/components/schemas/%s'}\n", i, prev) prev = fmt.Sprintf("A%d", i) } - return openapitest.HolderSpec(version, "{$ref: '#/components/schemas/"+prev+"'}", b.String()) + return openapitest.HolderSpec(version, "{$ref: '#/components/schemas/"+prev+"'}", builder.String()) } // TestNullableInference_ALongChainOfAliasesReadsAsAShortOne pins how a $ref's -// chain is read: hop by hop, so each alias's keywords count, but in a loop -// the chain's own length bounds rather than from the walk's budget. Charged -// per hop, a chain longer than the budget would read as silent and drop the -// null its end admits. +// chain is read: hop by hop, so each alias's keywords count, and at any +// length, so a long chain keeps the null its end admits. func TestNullableInference_ALongChainOfAliasesReadsAsAShortOne(t *testing.T) { t.Parallel() for _, n := range []int{1, maxChainProbe} { @@ -368,14 +374,15 @@ func TestAllOf_NullabilityFollowsTheConjuncts(t *testing.T) { assert.False(t, isModel, "a conjunct admitting no object composes nothing") } -// TestNullableInference_AnEntryWidensTheAllOfHoldingIt pins `nullable: true` on an -// inline entry writing no properties: under the policy it says what the keyword -// beside the allOf says, with one report at the keyword, whichever spelling of the -// entry admits it, and the declared reading stays conjoined. +// TestNullableInference_AnEntryWidensTheAllOfHoldingIt pins `nullable: true` on +// an inline entry writing no properties: under the policy it says what the +// keyword beside the allOf says, with one report at the keyword, whichever +// spelling of the entry admits it, its conjuncts disagreeing on another keyword +// or not, and the declared reading stays conjoined. func TestNullableInference_AnEntryWidensTheAllOfHoldingIt(t *testing.T) { t.Parallel() const at = "/components/schemas/Holder/properties/p/allOf/1/nullable" - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { entries string version string widens bool @@ -388,18 +395,19 @@ func TestNullableInference_AnEntryWidensTheAllOfHoldingIt(t *testing.T) { "a wrapper": {"[{$ref: '#/components/schemas/Pet'}, {allOf: [{nullable: true}]}]", "3.0.3", true, ""}, "writing properties": {"[{$ref: '#/components/schemas/Pet'}, {nullable: true, properties: {a: {type: string}}}]", "3.0.3", false, ""}, - "disagreeing": {"[{$ref: '#/components/schemas/Pet'}, {nullable: true, title: a}, {title: b}]", "3.0.3", false, ""}, - "false": {"[{$ref: '#/components/schemas/Pet'}, {nullable: false}]", "3.0.3", false, ""}, + "disagreeing on another keyword": {"[{$ref: '#/components/schemas/Pet'}, {nullable: true, title: a}, {title: b}]", "3.0.3", + true, "this schema writes none"}, + "false": {"[{$ref: '#/components/schemas/Pet'}, {nullable: false}]", "3.0.3", false, ""}, } { t.Run(name, func(t *testing.T) { t.Parallel() - src := openapitest.HolderSpec(tc.version, "{allOf: "+tc.entries+"}", "") + src := openapitest.HolderSpec(testCase.version, "{allOf: "+testCase.entries+"}", "") doc, diags := compileNullable(t, src, false) got := holderP(t, doc) - assert.Equal(t, tc.widens, got.Nullable) - assert.Equal(t, tc.widens, got.Inferred != "", "the null is the policy's") - if tc.report != "" { - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.InferredNullable, ir.SeverityInfo, at), tc.report) + assert.Equal(t, testCase.widens, got.Nullable) + assert.Equal(t, testCase.widens, got.Inferred != "", "the null is the policy's") + if testCase.report != "" { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.InferredNullable, ir.SeverityInfo, at), testCase.report) } off, _ := compileNullable(t, src, true) assert.False(t, holderP(t, off).Nullable, "the declared reading stays conjoined") @@ -438,39 +446,43 @@ func TestNullableInference_AnEntryWidensTheAllOfHoldingIt(t *testing.T) { // The `true` beside an entry's $ref is a conjunct of the position, as on an // entry of its own: it folds beside an entry writing none, and an entry - // writing `false` disagrees with it, so neither folds. - for name, tc := range map[string]struct { + // writing `false`, which at 3.0 equals the keyword left out, writes none. + // The string beside the allOf excludes null, so the policy widens nothing. + for name, testCase := range map[string]struct { entry, description string nullable bool }{ - "nullable false": {"{nullable: false, description: d}", "", false}, - "none": {"{description: d}", "d", true}, + "nullable false": {"{nullable: false, description: d}", "d", false}, + "none": {"{description: d}", "d", false}, } { src := openapitest.HolderSpec("3.0.3", - "{type: string, allOf: [{$ref: '#/components/schemas/Plain', nullable: true}, "+tc.entry+"]}", "") + "{type: string, allOf: [{$ref: '#/components/schemas/Plain', nullable: true}, "+testCase.entry+"]}", "") doc, _ = compileNullable(t, src, false) - assert.Equal(t, tc.nullable, holderP(t, doc).Nullable, name) - assert.Equal(t, tc.description, propertyOf(t, doc, "Holder", "p").Docs.Description, name) + assert.Equal(t, testCase.nullable, holderP(t, doc).Nullable, name) + assert.Equal(t, testCase.description, propertyOf(t, doc, "Holder", "p").Docs.Description, name) } - for name, tc := range map[string]struct{ union, code string }{ + // A union beside the reference conjoins with it, so the policy widens + // nothing there, however the union lowers. + for name, testCase := range map[string]struct{ union, code string }{ "degraded": {"oneOf: [{$ref: '#/components/schemas/Pet'}], anyOf: [{$ref: '#/components/schemas/Toy'}]", diag.DegradedConstruct}, "distributed": {"oneOf: [{$ref: '#/components/schemas/Pet'}, {$ref: '#/components/schemas/Toy'}]", diag.CompositionLowering}, } { - besideUnion := openapitest.HolderSpec("3.0.3", "{"+tc.union+", allOf: [{$ref: '#/components/schemas/Pet'}, {nullable: true}]}", + besideUnion := openapitest.HolderSpec("3.0.3", "{"+testCase.union+", allOf: [{$ref: '#/components/schemas/Pet'}, {nullable: true}]}", " Toy: {type: object, properties: {kind: {type: string}}}\n") doc, diags = compileNullable(t, besideUnion, false) - require.True(t, openapitest.HasDiagCodeAt(diags, tc.code, "/components/schemas/Holder/properties/p"), name) - assert.True(t, holderP(t, doc).Nullable, "%s: so does one beside a union, as beside the allOf", name) - assert.NotEmpty(t, holderP(t, doc).Inferred, name) + require.True(t, openapitest.HasDiagCodeAt(diags, testCase.code, "/components/schemas/Holder/properties/p"), name) + assert.False(t, holderP(t, doc).Nullable, "%s: a union beside the reference widens nothing", name) + assert.Empty(t, withCode(diags, diag.InferredNullable), name) } properties := openapitest.HolderSpec("3.0.3", "{allOf: [{$ref: '#/components/schemas/Pet'}, {nullable: true, properties: {a: {type: string}}}]}", "") - doc, _ = compileNullable(t, properties, false) + doc, diags = compileNullable(t, properties, false) kept, ok := doc0Model(doc) require.True(t, ok) - assert.Contains(t, kept.Unmodeled, "openapi:nullable", "a nullable that folds nothing is kept under its own key") + assert.NotContains(t, kept.Unmodeled, "openapi:nullable", "the policy reads the nullable, which widens nothing past the structure") + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnwidenedNullable, "/components/schemas/Holder/properties/p/allOf/1/nullable")) off, offDiags := compileNullable(t, src, true) model, ok := doc0Model(off) @@ -497,9 +509,10 @@ func doc0Model(doc *ir.Document) (*ir.Model, bool) { // admission the way a non-empty `enum` does — it is the one-member spelling of // the same keyword. // -// `{type: [string, "null"], const: "a"}` is the const form of the enum case that -// used to overstate: the type array puts null in the type space and the const -// takes it back out of the value space, so the position does not admit it. +// `{type: [string, "null"], const: "a"}` is the const form of the enum case +// that used to overstate: the type array puts null in the type space and the +// const takes it back out of the value space, so the position does not admit +// it. func TestConst_FixesWhetherTheValueSpaceHoldsNull(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(` S: @@ -535,10 +548,10 @@ func TestSchemaRef_NullableNormalization(t *testing.T) { {"3.1 type array", "3.1.0", `{type: [string, "null"]}`, true, "type/primitive/string"}, {"plain", "3.1.0", "{type: string}", false, "type/primitive/string"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - spec := "openapi: " + tc.version + "\n" + + spec := "openapi: " + testCase.version + "\n" + "info: {title: T, version: \"1\"}\n" + "paths: {}\n" + "components:\n" + @@ -546,14 +559,14 @@ func TestSchemaRef_NullableNormalization(t *testing.T) { " S:\n" + " type: object\n" + " properties:\n" + - " p: " + tc.schema + "\n" + " p: " + testCase.schema + "\n" doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("S")].(*ir.Model) require.True(t, ok) require.Len(t, model.Properties, 1) - assert.Equal(t, tc.wantTarget, model.Properties[0].Type.Target) - assert.Equal(t, tc.wantNullable, model.Properties[0].Type.Nullable) + assert.Equal(t, testCase.wantTarget, model.Properties[0].Type.Target) + assert.Equal(t, testCase.wantNullable, model.Properties[0].Type.Nullable) }) } } @@ -851,9 +864,10 @@ func TestSchema_RefNullableAcrossSpellings(t *testing.T) { properties: {a: {type: string}} oneOf: [{type: string}, {type: "null"}] `, - wantNullable: false, + wantNullable: true, wantTarget: targetID, - message: "a union co-declared with a structural body intersects with it, so its null branch admits nothing", + message: "no branch lives beside the body, and the nullable-inference policy lifts the null branch's null, " + + "so the position is null alone", }, { name: "3.1 ref to a closed enum with a null branch sibling", @@ -890,16 +904,16 @@ func TestSchema_RefNullableAcrossSpellings(t *testing.T) { message: "a nullable enum target reads as nullable at a $ref like every other null spelling", }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - spec := openapitest.ComponentSpecVer(tc.version, tc.schemas) + spec := openapitest.ComponentSpecVer(testCase.version, testCase.schemas) doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) model := typeByName(doc, "Owner").(*ir.Model) require.Len(t, model.Properties, 1) - assert.Equal(t, tc.wantNullable, model.Properties[0].Type.Nullable, tc.message) - assert.Equal(t, tc.wantTarget, model.Properties[0].Type.Target, + assert.Equal(t, testCase.wantNullable, model.Properties[0].Type.Nullable, testCase.message) + assert.Equal(t, testCase.wantTarget, model.Properties[0].Type.Target, "ref resolves to the expected target") }) } @@ -982,12 +996,13 @@ oneOf: [{type: string}, {type: "null"}]` assert.Equal(t, properties["inline"].Type.Nullable, properties["viaRef"].Type.Nullable, "the same body must not change nullability by being reached through a $ref") - assert.False(t, properties["viaRef"].Type.Nullable, - "an intersected union's null branch admits nothing, so neither spelling is nullable") + assert.True(t, properties["viaRef"].Type.Nullable, + "no branch lives beside the body, so the policy's lift of the null branch leaves null alone in both spellings") + assert.Equal(t, ir.Inferred("nullable-inference"), properties["viaRef"].Type.Inferred, "the policy's null is marked") } -// TestSchema_RefNullableAtNonPropertyPosition pins that the lifted bit reaches a -// $ref used as a list element, not just a model property. +// TestSchema_RefNullableAtNonPropertyPosition pins that the lifted bit reaches +// a $ref used as a list element, not just a model property. func TestSchema_RefNullableAtNonPropertyPosition(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(` Owner: @@ -1011,12 +1026,13 @@ func TestSchema_RefNullableAtNonPropertyPosition(t *testing.T) { // TestNullAlone_ReadsTheSchemasOwnKeywords holds the predicate a schema of null // alone and a union's null branch are read by // (docs/compilers/openapi.md#null-alone): own keywords leaving no value but -// null, and a null admitted as the policy in force reads it. A schema writing a -// $ref or a combinator beside them admits what those do too, so it is none, -// whatever its own keywords say. +// null, a type of null alone deciding over an enum beside it, and a null +// admitted as the policy in force reads it. A schema writing a $ref or a +// combinator beside them admits what those do too, so it is none, whatever its +// own keywords say, and so is one writing an empty enum. func TestNullAlone_ReadsTheSchemasOwnKeywords(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { version, schema string on, off bool // the predicate with the nullable-inference policy on and off }{ @@ -1035,7 +1051,8 @@ func TestNullAlone_ReadsTheSchemasOwnKeywords(t *testing.T) { {version: "3.1.0", schema: `{type: [string, "null"]}`}, {version: "3.1.0", schema: `{type: string, enum: [null]}`}, {version: "3.1.0", schema: `{type: string, const: null}`}, - {version: "3.1.0", schema: `{type: "null", enum: [null, a]}`}, + {version: "3.1.0", schema: `{type: "null", enum: [null, a]}`, on: true, off: true}, + {version: "3.1.0", schema: `{type: "null", enum: [a]}`}, {version: "3.1.0", schema: `{type: "null", enum: []}`}, {version: "3.1.0", schema: `{const: null, enum: [null, a]}`}, {version: "3.1.0", schema: `{$ref: '#/components/schemas/Nil'}`}, @@ -1045,19 +1062,19 @@ func TestNullAlone_ReadsTheSchemasOwnKeywords(t *testing.T) { {version: "3.1.0", schema: `{type: "null", anyOf: [{type: string}]}`}, {version: "3.1.0", schema: `{type: "null", $dynamicRef: '#node'}`}, } { - t.Run(tc.version+" "+tc.schema, func(t *testing.T) { + t.Run(testCase.version+" "+testCase.schema, func(t *testing.T) { t.Parallel() - src := openapitest.ComponentSpecVer(tc.version, " Nil: {type: \"null\"}\n Str: {type: string}\n"+ - " Node: {$dynamicAnchor: node, type: string}\n S: "+tc.schema+"\n") + src := openapitest.ComponentSpecVer(testCase.version, " Nil: {type: \"null\"}\n Str: {type: string}\n"+ + " Node: {$dynamicAnchor: node, type: string}\n S: "+testCase.schema+"\n") for _, off := range []bool{false, true} { lowerer, _ := schema.LoweredWith(t, src, lowering.Policy{NullableInference: lowering.NullableInference{Disabled: off}}) - js, ok := lowerer.Doc.Components.GetSchemas().Get("S") + jsonSchema, ok := lowerer.Doc.Components.GetSchemas().Get("S") require.True(t, ok) - want := tc.on + want := testCase.on if off { - want = tc.off + want = testCase.off } - assert.Equal(t, want, schema.NullAlone(lowerer.Ctx, lowerer.Ctx.Statements().Of(js).Schema), "policy off: %v", off) + assert.Equal(t, want, schema.NullAlone(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema).Schema), "policy off: %v", off) } }) } diff --git a/compilers/openapi/internal/schema/nullanswermemo_bound_internal_test.go b/compilers/openapi/internal/schema/nullanswermemo_bound_internal_test.go new file mode 100644 index 000000000..65fc62eef --- /dev/null +++ b/compilers/openapi/internal/schema/nullanswermemo_bound_internal_test.go @@ -0,0 +1,81 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/service" + "github.com/dexpace/morphic/compilers/openapi/internal/service/servicetest" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// boundCycleSpec is a cycle of three schemas each reading the other two, the +// last admitting null beside them, so every member's answer changes. +const boundCycleSpec = ` A: {allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/C'}]} + B: {anyOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/C'}]} + C: {anyOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}, {type: 'null'}]} +` + +// TestNullCycle_TheFixpointHoldsToItsBound holds the fixpoint settling a cycle +// to fixpointReadLimit: a run settles the dense cycle within it, every member +// admitting the null its last member does; held to a limit of no read, it +// records each member as overrun, and the site of one draws the invariant's +// error rather than an answer trusted in silence. +func TestNullCycle_TheFixpointHoldsToItsBound(t *testing.T) { + t.Parallel() + serviceContext := servicetest.Context(t, openapitest.ComponentSpecVer("3.1.0", boundCycleSpec), service.Policy{}) + members := make([]*statement.Statement, 0, 3) + for _, name := range []string{"A", "B", "C"} { + members = append(members, heldAt(serviceContext.Ctx, jsontext.Pointer("/components/schemas/"+name))) + } + store := nullAnswerMemoOf(serviceContext.Ctx) + for _, schemaStatement := range members { + assert.True(t, nullAnswerReadingsOf(serviceContext.Ctx, schemaStatement).mayAdmit(serviceContext.Ctx)) + } + require.Empty(t, store.overran, "a cycle settles within its bound") + + cycle := newNullCycle(serviceContext.Ctx, members) + assert.Equal(t, len(members)+nullAnswerReadingsHeight*2, cycle.fixpointReadLimit(), "of the three, A alone reads the others itself; B and C read theirs through their branches") + cycle.fixpoint(serviceContext.Ctx, store, 0, func(int) nullAnswerReadings { return nullAnswerReadingsAlike(nullSaysNothing) }, keepingForbidden) + for _, schemaStatement := range members { + assert.True(t, store.overran[schemaStatement]) + } + _, diags := refNullRef(serviceContext.Ctx, "type/x", members[0], "/components/schemas/A") + require.Len(t, diags, 1) + assert.Equal(t, ir.SeverityError, diags[0].Severity) + assert.Equal(t, diag.InternalInvariant, diags[0].Code) +} + +// TestNullLift_ALiftAskedInsideAnotherIsNotTrusted holds a null branch beside +// an object keeping null out, whose null the policy lifts for the whole +// schema when read alone, to no lift where it is asked while another lift's +// union reading is under way, which reads only answers already settled: the +// schema is recorded as unlifted, and its site draws the invariant's error. +func TestNullLift_ALiftAskedInsideAnotherIsNotTrusted(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpecVer("3.1.0", ` L: {type: object, properties: {a: {type: string}}, oneOf: [{type: 'null'}]} +`) + alone := servicetest.Context(t, spec, service.Policy{}) + assert.True(t, nullAnswerReadingsOf(alone.Ctx, heldAt(alone.Ctx, "/components/schemas/L")).admits(alone.Ctx), "read alone, the branch's null is lifted") + + nested := servicetest.Context(t, spec, service.Policy{}) + schemaStatement := heldAt(nested.Ctx, "/components/schemas/L") + store := nullAnswerMemoOf(nested.Ctx) + store.readingUnionNull = true + assert.False(t, nullAnswerReadingsOf(nested.Ctx, schemaStatement).admits(nested.Ctx), "asked inside another lift, none is read") + require.True(t, store.askedDuringUnionReading[schemaStatement]) + _, diags := refNullRef(nested.Ctx, "type/x", schemaStatement, "/components/schemas/L") + require.Len(t, diags, 1) + assert.Equal(t, ir.SeverityError, diags[0].Severity) + assert.Equal(t, diag.InternalInvariant, diags[0].Code) + assert.Contains(t, diags[0].Message, "inside another schema's union reading") +} diff --git a/compilers/openapi/internal/schema/nullbranch.go b/compilers/openapi/internal/schema/nullbranch.go index b5ca38df5..3d5196802 100644 --- a/compilers/openapi/internal/schema/nullbranch.go +++ b/compilers/openapi/internal/schema/nullbranch.go @@ -5,7 +5,7 @@ package schema import ( "encoding/json/jsontext" - "strconv" + "slices" "strings" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" @@ -16,73 +16,56 @@ import ( "github.com/dexpace/morphic/ir" ) -// nullBranch reports whether the union branch js is the union's null, lifted -// onto the reference to the union rather than made a variant +// nullBranch reports whether the union branch schemaStatement is the union's +// null, lifted onto the reference to the union rather than made a variant // (docs/compilers/openapi.md#union-null-variant): written inline and of null // alone (NullAlone), so it would lower on its own to the Enum with no member // behind a nullable reference that the reference's bit says. A $ref branch // names a node the source declares, and stays the variant naming it. -func nullBranch(loweringContext lowering.Ctx, js *statement.Statement) bool { - return inlineBranch(js) && NullAlone(loweringContext, js.Schema) +func nullBranch(loweringContext lowering.Ctx, schemaStatement *statement.Statement) bool { + return inlineBranch(schemaStatement) && NullAlone(loweringContext, schemaStatement.Schema) } -// variantsNull is what schema's oneOf and anyOf say of null where the IR holds -// a union's null on its variants as on the reference to it, the two conjoined: -// each admits null where any branch does and keeps it out where every branch -// does, each read by n, whose budget bounds them, so a branch left unread keeps -// nothing out. That holds of a union however it lowers, so none is asked -// whether it is distributed (unionNullReading), and the read starts no -// classification. -func (n *nulls) variantsNull(schema *statement.Schema) nullReading { - choice := schema.ChoiceKeywords() - return foldNullReadings(n.branchesNull(choice.OneOf), n.branchesNull(choice.AnyOf)) +// restNull is what body says of null by all it writes but the union of holder +// it chooses, holder being body or an entry of its allOf, so the union passed +// over is a conjunct of that rest wherever it is written +// (docs/compilers/openapi.md#union-beside-structure). +func restNull(loweringContext lowering.Ctx, body, holder *statement.Schema) nullAnswerReadings { + keyword := loweredKeyword(loweringContext, body, holder) + return settledNullRead(loweringContext, loweringContext.Statements().Read(body), nullSkip{schema: holder, keyword: keyword}).answer() } -// branchesNull is what one union's branches say of null, under each reading: -// admitted where a branch admits it, forbidden where every branch forbids it, -// and silent where it writes none. -func (n *nulls) branchesNull(branches []statement.Subschema) nullReading { - if len(branches) == 0 { - return nullReadingAlikeUnderBothPolicies(nullUnconstrained) - } - out := nullReadingAlikeUnderBothPolicies(nullForbidden) - for _, b := range branches { - nullReading := n.conjunct(n.c.Statements().Subschema(b), nullSite{}) - out.declared = disjoinNullVerdicts(out.declared, nullReading.declared) - out.lenient = disjoinNullVerdicts(out.lenient, nullReading.lenient) +// bodyNull is what schema says of null outside every union its conjunction +// holds, widened where the policy widens the whole conjunction. No depth cuts +// it. +func bodyNull(loweringContext lowering.Ctx, schema *statement.Schema) nullAnswerReadings { + out := settledNullRead(loweringContext, loweringContext.Statements().Read(schema), nullSkip{every: true}).total + if policyWidens(loweringContext, schema) { + out.underInference = nullAdmittedByReference } return out } -// disjoinNullVerdicts is what two branches of a union say of null together: -// one admitting it decides, and the union keeps it out only where both do. -func disjoinNullVerdicts(a, b nullDeclaration) nullDeclaration { - switch { - case a == nullAdmitted || b == nullAdmitted: - return nullAdmitted - case a == nullForbidden && b == nullForbidden: - return nullForbidden - default: - return nullUnconstrained - } +// policyWidens reports whether the nullable-inference policy reads schema's +// whole conjunction, its unions among it, as admitting null, so each of its +// unions shares that null. +func policyWidens(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return loweringContext.NullableInference.Honours() && + settledNullRead(loweringContext, loweringContext.Statements().Read(schema), nullSkip{}).widens() } -// mayAdmitNull reports whether b admits null wherever the IR holds it, on a -// variant of a union it is or reaches as on its own keywords, under the reading -// loweringContext's policy selects. holder is a schema whose own union the read -// leaves out, nil for none. A read past the walk's budget may, unless what it -// read keeps null out, which no conjunct left unread lets back in. -func mayAdmitNull(loweringContext lowering.Ctx, b *statement.Statement, holder *statement.Schema) bool { - nulls := newNulls(loweringContext) - nulls.variants, nulls.rest = true, holder - nullReading := nulls.conjunct(b, nullSite{}) - return nullReading.admits(loweringContext) || nulls.conjuncts.Exhausted() && !nullReading.forbids(loweringContext) +// settledNullRead is readNull of schemaStatement over the run's settled +// answers: settling schemaStatement's own answer first settles every answer +// its reading asks, so the reading settles nothing itself. +func settledNullRead(loweringContext lowering.Ctx, schemaStatement *statement.Statement, skip nullSkip) nullConjunctionRead { + nullAnswerReadingsOf(loweringContext, schemaStatement) + return readNull(loweringContext, schemaStatement, skip, nullAnswerMemoOf(loweringContext).settled) } -// inlineBranch reports whether js is a schema written in place: no boolean, -// and no reference site (typed.Bindings.RefSite). -func inlineBranch(js *statement.Statement) bool { - return js != nil && stated(js.Schema) && js.Ref == nil +// inlineBranch reports whether schemaStatement is a schema written in place: no +// boolean, and no reference site (typed.Bindings.RefSite). +func inlineBranch(schemaStatement *statement.Statement) bool { + return schemaStatement != nil && stated(schemaStatement.Schema) && schemaStatement.Ref == nil } // liftedNull is a null branch (nullBranch) of a union, where it is written, @@ -94,33 +77,36 @@ type liftedNull struct { key string } -// liftedNulls returns the null branches of the union unionBranches elects of +// liftedNulls returns the null branches of the union unionBranches chooses of // schema at position, schema written at pointer, in source order. func liftedNulls(loweringContext lowering.Ctx, position, schema *statement.Schema, pointer jsontext.Pointer) []liftedNull { - branches, key, _ := unionBranches(loweringContext, position, schema) + key := loweredKeyword(loweringContext, position, schema) + branches := key.branchesOf(schema) var out []liftedNull - for i, b := range branches { - st := loweringContext.Statements().Subschema(b) - if !nullBranch(loweringContext, st) { + for i, branch := range branches { + schemaStatement := loweringContext.Statements().Subschema(branch) + if !nullBranch(loweringContext, schemaStatement) { continue } - index := strconv.Itoa(i) - out = append(out, liftedNull{schema: st.Schema, at: pointer + ids.Ptr(key, index), key: "openapi:" + key + "/" + index}) + out = append(out, liftedNull{schema: schemaStatement.Schema, at: key.branchAt(pointer, i), key: "openapi:" + key.branchPath(i)}) } return out } -// saysTheNull reports whether key, written on the null branch b, says only -// the null the reference to its union holds: a type, an enum or a const, and a -// nullable where it is read, by the dialect defining it or by the -// nullable-inference policy (docs/compilers/openapi.md#nullable). A nullable -// neither reads is a keyword its dialect does not define, kept as one is. -func saysTheNull(loweringContext lowering.Ctx, b liftedNull, key string) bool { +// declaresOnlyTheNull reports whether key, written on the null branch +// liftedBranch, says only the null the reference to its union holds: a type, an +// enum or a const, and a nullable where it is read, by the dialect defining it +// or by the nullable-inference policy (docs/compilers/openapi.md#nullable). A +// nullable neither reads is a keyword its dialect does not define, kept as one +// is. +func declaresOnlyTheNull(loweringContext lowering.Ctx, liftedBranch liftedNull, key string) bool { switch key { - case "type", "enum", "const": + case "type", "const": return true + case "enum": + return !typeExcludesEnumMember(liftedBranch.schema) case "nullable": - return loweringContext.Rules().At(loweringContext.Position(b.at)).Defines(key) || loweringContext.NullableInference.Honours() && nullableTrue(b.schema) + return loweringContext.Rules().At(loweringContext.Position(liftedBranch.at)).Defines(key) || loweringContext.NullableInference.Honours() && nullableTrue(liftedBranch.schema) default: return false } @@ -134,57 +120,88 @@ type keptNullBranch struct { } // nullBranchKeeps returns the null branches of schema's union, written at -// pointer, that write a key beside those saying the null (saysTheNull): an -// annotation, an extension or any other keyword, but a `null` written for one, -// which is that keyword left out (annotation.WritesKeywordLeftOut). A branch is -// no variant, so nothing else keeps what it says. +// pointer, that write a key beside those saying the null, a keyword written +// `null` and an extension no JSON holds aside. A branch is no variant, so +// nothing else keeps what it says. func nullBranchKeeps(loweringContext lowering.Ctx, position, schema *statement.Schema, pointer jsontext.Pointer) []keptNullBranch { var out []keptNullBranch - for _, b := range liftedNulls(loweringContext, position, schema, pointer) { + for _, liftedBranch := range liftedNulls(loweringContext, position, schema, pointer) { var written []string - for _, key := range b.schema.Keys { - if !saysTheNull(loweringContext, b, key.Name) && !annotation.WritesKeywordLeftOut(b.schema, key.Name) { + for _, key := range liftedBranch.schema.Keys { + if !declaresOnlyTheNull(loweringContext, liftedBranch, key.Name) && !annotation.WritesKeywordLeftOut(liftedBranch.schema, key.Name) && + !annotation.ExtensionNoJSONHolds(liftedBranch.schema, key.Name) { written = append(written, key.Name) } } if len(written) > 0 { - out = append(out, keptNullBranch{liftedNull: b, written: written}) + out = append(out, keptNullBranch{liftedNull: liftedBranch, written: written}) } } return out } -// recordNullBranches keeps each of kept whole in unmodeled under its key, as -// no_ir_home: nothing is degraded, the null being typed exactly, and only what -// else the branch says of that alternative has no field. One stored is reported -// at its branch, and one the keeper cannot convert is reported by it instead. -func recordNullBranches(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, kept []keptNullBranch) []ir.Diagnostic { - var diags []ir.Diagnostic - for _, b := range kept { - stored, keptDiags := preserveNode(loweringContext, unmodeled, b.key, b.schema.Node, ir.ReasonNoIRHome, b.at) - diags = append(diags, keptDiags...) +// nullBranchesKept returns each of kept whole under its key, as no_ir_home: +// the null is typed exactly, and only what else the branch says has no field. +// Each report is paired with the branch's key. +func nullBranchesKept(loweringContext lowering.Ctx, kept []keptNullBranch) (ir.Unmodeled, annotation.KeptReports) { + var held ir.Unmodeled + reports := make(annotation.KeptReports, 0, len(kept)) + for _, keptBranch := range kept { + stored, keptDiags := keepNullBranch(loweringContext, &held, keptBranch) if stored { - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, b.at, + keptDiags = append(keptDiags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, keptBranch.at, "this branch admits null alone, which the reference to this position holds, so it is no variant; "+ - "the branch (%s) is kept verbatim under Unmodeled", strings.Join(b.written, ", "))) + "the branch (%s) is kept verbatim under Unmodeled", strings.Join(keptBranch.written, ", "))) } + reports = append(reports, annotation.ReportsOf(keptBranch.key, keptDiags...)...) } - return diags + return held, reports +} + +// recordNullBranches keeps each of kept on unmodeled and returns the reports, +// each paired with its branch's key (nullBranchesKept). +func recordNullBranches(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, kept []keptNullBranch) annotation.KeptReports { + held, reports := nullBranchesKept(loweringContext, kept) + *unmodeled = annotation.MergeUnmodeled(*unmodeled, held) + return reports +} + +// keepNullBranch keeps keptBranch whole in unmodeled under its key, but +// each extension no JSON holds, reporting one written below keptBranch's own +// keywords, which the branch's reading does not reach. +func keepNullBranch(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, keptBranch keptNullBranch) (bool, []ir.Diagnostic) { + reason := ir.ReasonNoIRHome + if typeExcludesEnumMember(keptBranch.schema) { + // The enum lists members its type excludes, which the IR holds nowhere. + reason = ir.ReasonDegradedLowering + } + whole, dropped, err := annotation.RenderDroppingExtensions(keptBranch.schema.Node) + if err != nil { + return keepNode(loweringContext, unmodeled, keptBranch.key, keptBranch.schema.Node, reason, keptBranch.at) + } + annotation.KeepInto(unmodeled, keptBranch.key, whole, reason, loweringContext.Place().At(keptBranch.at)) + deeper := slices.DeleteFunc(dropped, func(at jsontext.Pointer) bool { return at.Parent() == "" }) + return true, annotation.DroppedExtensionDiags(loweringContext.Place().At(keptBranch.at), deeper) } // liftedNullFindings returns what reading each null branch of schema's union, -// written at pointer, reports at the branch, as its own lowering reports it -// where it is a variant: a null the nullable-inference policy reads in -// (nulls.findings), and an enum entry repeating an earlier one (enumRepeats), -// which the document writes whichever path takes the branch. +// written at pointer, reports at the branch, as its own lowering would as a +// variant: the document writes them whichever path takes the branch. func liftedNullFindings(loweringContext lowering.Ctx, position, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { lifted := liftedNulls(loweringContext, position, schema, pointer) diags := make([]ir.Diagnostic, 0, len(lifted)) - for _, b := range lifted { - nulls := newNulls(loweringContext) - nulls.schema(b.schema, siteAt(b.at)) - diags = append(diags, nulls.findings(loweringContext)...) - diags = append(diags, enumRepeats(loweringContext, readEnum(b.schema.Enum()), b.at)...) + for _, liftedBranch := range lifted { + diags = append(diags, nullFindings(loweringContext, loweringContext.Statements().Read(liftedBranch.schema), liftedBranch.at)...) + entries := readEnum(liftedBranch.schema.Enum(), liftedBranch.at) + diags = append(diags, enumRepeats(loweringContext, liftedBranch.schema, entries)...) + if typeExcludesEnumMember(liftedBranch.schema) { + diags = append(diags, excludedEnumMembers(loweringContext, entries)...) + } + for _, key := range liftedBranch.schema.Keys { + if annotation.ExtensionNoJSONHolds(liftedBranch.schema, key.Name) { + diags = append(diags, annotation.ExtensionDroppedDiag(loweringContext.Place().At(liftedBranch.at+ids.Ptr(key.Name)))) + } + } } return diags } diff --git a/compilers/openapi/internal/schema/nullbranch_extension_test.go b/compilers/openapi/internal/schema/nullbranch_extension_test.go new file mode 100644 index 000000000..a1f99aee1 --- /dev/null +++ b/compilers/openapi/internal/schema/nullbranch_extension_test.go @@ -0,0 +1,89 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// keptNullBranchAt is where keptNullBranchSpec writes its null branch. +const keptNullBranchAt = "/components/schemas/Holder/properties/p/oneOf/1" + +// keptNullBranchSpec is a property whose oneOf is a $ref to an object and the null +// branch given, which the reference's nullability holds. +func keptNullBranchSpec(branch string) string { + return openapitest.ComponentSpecVer("3.1.0", ` X: {type: object} + Holder: + type: object + properties: + p: {oneOf: [{$ref: '#/components/schemas/X'}, `+branch+`]} +`) +} + +// TestNullBranch_AKeptBranchDropsOnlyAnExtensionNoJSONHolds pins a null branch +// the keeper stores, writing an extension whose value converts to no JSON: the +// extension alone is left out, with the extension reader's one warning where it +// is written, on the branch or nested in it, and the branch is kept without it, +// or not at all where nothing else of it is kept. A valid document draws no +// error, and nothing claims the extension was kept. +func TestNullBranch_AKeptBranchDropsOnlyAnExtensionNoJSONHolds(t *testing.T) { + t.Parallel() + for name, testCase := range map[string]struct { + branch, warnedAt, kept string + }{ + "beside a note": {`{type: "null", description: d, x-t: .nan}`, keptNullBranchAt, `{"description":"d","type":"null"}`}, + "alone": {`{type: "null", x-t: .nan}`, keptNullBranchAt, ""}, + "nested in a keyword": {`{type: "null", description: d, x-m: 1, not: {x-t: .nan}}`, keptNullBranchAt + "/not", + `{"description":"d","not":{},"type":"null","x-m":1}`}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, keptNullBranchSpec(testCase.branch)) + openapitest.RequireNoErrorDiags(t, diags) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, testCase.warnedAt), + `extension "x-t" could not be serialized`) + var dropped int + for _, diagnostic := range diags { + if strings.Contains(diagnostic.Message, "could not be serialized") { + dropped++ + } + } + assert.Equal(t, 1, dropped, "one warning: %+v", diags) + property := propertyOf(t, doc, "Holder", "p") + kept, held := property.Unmodeled["openapi:oneOf/1"] + if testCase.kept == "" { + assert.False(t, held, "nothing of the branch is kept: %v", property.Unmodeled) + } else { + require.True(t, held, "the branch is kept: %v", property.Unmodeled) + assert.JSONEq(t, testCase.kept, string(kept.Value)) + } + for _, claim := range openapitest.MessagesSayingKept(diags) { + assert.NotContains(t, claim, "x-t", "nothing claims the extension was kept") + } + }) + } +} + +// TestNullBranch_AKeptBranchWhoseKeywordNoJSONHoldsIsRefused pins the fallback +// of a kept null branch writing a value no JSON holds that is no extension: the +// branch reaches the IR in no form, refused once where it is written, and the +// property keeps nothing of it. +func TestNullBranch_AKeptBranchWhoseKeywordNoJSONHoldsIsRefused(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, keptNullBranchSpec(`{type: "null", description: d, default: .nan}`)) + + got := codesAt(diags, keptNullBranchAt) + require.Len(t, got, 1, "%+v", diags) + assert.Equal(t, diag.UnpreservableConstruct, got[0].Code) + assert.Equal(t, ir.SeverityError, got[0].Severity) + assert.NotContains(t, propertyOf(t, doc, "Holder", "p").Unmodeled, "openapi:oneOf/1") +} diff --git a/compilers/openapi/internal/schema/nullbranch_test.go b/compilers/openapi/internal/schema/nullbranch_test.go index b6d6b4032..7654d4cd0 100644 --- a/compilers/openapi/internal/schema/nullbranch_test.go +++ b/compilers/openapi/internal/schema/nullbranch_test.go @@ -32,7 +32,7 @@ var nullBranchSpellings = []struct{ version, branch string }{ {"3.0.3", `{enum: [null]}`}, } -// nullBranchSpec writes the union shapes a null branch stands in, the branch +// nullBranchSpec writes the union shapes a null branch sits in, the branch // spelled as branch: beside one other branch, first or last, under either // combinator, twice, and beside two others under either combinator. X and Y pin // a tag, which the discriminator-inference policy reads off a union of them. @@ -80,8 +80,8 @@ func TestNullBranch_IsTheReferencesInEverySpelling(t *testing.T) { require.NotNil(t, union.Discriminator, "%s: the tags its variants pin are read", wire) assert.Equal(t, map[string]ir.TypeID{"x": typeID, "y": irTypeID}, union.Discriminator.Mapping, wire) } - for id, td := range doc.Types { - enum, isEnum := td.(*ir.Enum) + for id, typeDef := range doc.Types { + enum, isEnum := typeDef.(*ir.Enum) assert.False(t, isEnum && len(enum.Members) == 0, "no null branch lowered as a variant: %s", id) } }) @@ -143,7 +143,7 @@ func TestNullBranch_ARefToANullAloneSchemaStaysAVariant(t *testing.T) { // TestNullBranch_ADiscriminatorLinesItsVariantsUpPastTheNull pins the readers // that line a union's variants up with its branches, skipping the null branches -// no variant stands for: a mapping naming a $ref branch's target routes to the +// no variant names: a mapping naming a $ref branch's target routes to the // variant the branch lowered to, and the implicit mapping a discriminator with // none reads is one tag per variant. func TestNullBranch_ADiscriminatorLinesItsVariantsUpPastTheNull(t *testing.T) { @@ -205,7 +205,7 @@ func TestNullBranch_KeepsWhatTheBranchWrites(t *testing.T) { list, ok := doc.Types[propertyOf(t, doc, "Holder", "list").Type.Target].(*ir.List) require.True(t, ok) - for _, tc := range []struct { + for _, testCase := range []struct { name string p ir.Unmodeled key, at string // the entry's key, and the branch's pointer @@ -222,13 +222,13 @@ func TestNullBranch_KeepsWhatTheBranchWrites(t *testing.T) { {"the second of two", holder("twice"), "openapi:anyOf/2", at + "twice/anyOf/2", `{"const":null,"description":"b"}`}, {"a merge", holder("merged"), "openapi:oneOf/1", at + "merged/oneOf/1", `{"description":"merged","type":"null"}`}, } { - entry, ok := tc.p[tc.key] - require.True(t, ok, "%s keeps %s, got %v", tc.name, tc.key, tc.p) - assert.Equal(t, ir.ReasonNoIRHome, entry.Reason, tc.name) - assert.JSONEq(t, tc.raw, string(entry.Value), tc.name) - assert.Equal(t, jsontext.Pointer(tc.at), entry.Provenance.Pointer, tc.name) + entry, ok := testCase.p[testCase.key] + require.True(t, ok, "%s keeps %s, got %v", testCase.name, testCase.key, testCase.p) + assert.Equal(t, ir.ReasonNoIRHome, entry.Reason, testCase.name) + assert.JSONEq(t, testCase.raw, string(entry.Value), testCase.name) + assert.Equal(t, jsontext.Pointer(testCase.at), entry.Provenance.Pointer, testCase.name) assert.Equal(t, []ir.Diagnostic{{Severity: ir.SeverityInfo, Code: diag.DegradedConstruct}}, - codesAt(diags, tc.at), "%s is reported once, at the branch", tc.name) + codesAt(diags, testCase.at), "%s is reported once, at the branch", testCase.name) } for _, wire := range []string{"said", "leftOut"} { assert.Empty(t, holder(wire), "%s writes nothing beside its null", wire) @@ -247,21 +247,18 @@ func codesAt(diags []ir.Diagnostic, pointer string) []ir.Diagnostic { return out } -// TestNullBranch_AKeptBranchTheKeeperCannotConvertIsReportedByIt pins the one -// branch the keeper stores nothing of: a value no IR value holds, which it -// reports itself, so nothing claims the branch was kept. -func TestNullBranch_AKeptBranchTheKeeperCannotConvertIsReportedByIt(t *testing.T) { +// TestNullBranch_AKeptBranchIsKeptWithoutAnExtensionNoJSONHolds pins a null +// branch the keeper stores, writing an extension that converts to no JSON: +// the branch is kept and reported as without it, the extension alone dropped +// with its own warning at the branch, and a valid document draws no error. +func TestNullBranch_AKeptBranchIsKeptWithoutAnExtensionNoJSONHolds(t *testing.T) { t.Parallel() - _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` X: {type: object} + requireKeptWithoutExtension(t, parseFull, openapitest.ComponentSpecVer("3.1.0", ` X: {type: object} Holder: type: object properties: - p: {oneOf: [{$ref: '#/components/schemas/X'}, {type: "null", x-v: .nan}]} -`)) - at := "/components/schemas/Holder/properties/p/oneOf/1" - got := codesAt(diags, at) - require.Len(t, got, 1, "%+v", diags) - assert.Equal(t, diag.UnpreservableConstruct, got[0].Code) + p: {oneOf: [{$ref: '#/components/schemas/X'}, {type: "null"`+unconvertibleExtension+`}]} +`), unconvertibleExtension, "/components/schemas/Holder/properties/p/oneOf/1") } // TestNullBranch_BesideABodyIsLiftedPastTheDistribution pins a null branch, @@ -302,7 +299,7 @@ func TestNullBranch_BesideABodyIsLiftedPastTheDistribution(t *testing.T) { // as a schema writing it alone keeps it (docs/compilers/openapi.md#nullable). func TestNullBranch_KeepsANullableNothingReads(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { version, branch string off, kept bool }{ @@ -311,14 +308,14 @@ func TestNullBranch_KeepsANullableNothingReads(t *testing.T) { {version: "3.0.3", branch: `{enum: [null], nullable: true}`}, {version: "3.0.3", branch: `{enum: [null], nullable: true}`, off: true}, } { - doc, diags := compileNullable(t, openapitest.HolderSpec(tc.version, - "{oneOf: [{$ref: '#/components/schemas/Pet'}, "+tc.branch+"]}", ""), tc.off) + doc, diags := compileNullable(t, openapitest.HolderSpec(testCase.version, + "{oneOf: [{$ref: '#/components/schemas/Pet'}, "+testCase.branch+"]}", ""), testCase.off) openapitest.RequireNoErrorDiags(t, diags) - name := tc.version + " " + tc.branch + name := testCase.version + " " + testCase.branch assert.Equal(t, ir.TypeRef{Target: componentID("Pet"), Nullable: true}, holderP(t, doc), name) property := propertyOf(t, doc, "Holder", "p") _, kept := property.Unmodeled["openapi:oneOf/1"] - assert.Equal(t, tc.kept, kept, "%s, policy off: %v", name, tc.off) + assert.Equal(t, testCase.kept, kept, "%s, policy off: %v", name, testCase.off) } } @@ -336,19 +333,19 @@ components: X: {type: object, properties: {id: {type: string}}} H: {oneOf: [{$ref: '#/components/schemas/X'}, {enum: [null, null, null]}]} ` - for _, tc := range []struct { + for _, testCase := range []struct { limit int refused bool }{{limit: 3}, {limit: 2, refused: true}} { lowerer, _ := schema.LoweredFor(t, spec) - lowerer.Ctx.Limits = lowering.Limits{MaxEnumMembers: budget.AtMost(tc.limit)} + lowerer.Ctx.Limits = lowering.Limits{MaxEnumMembers: budget.AtMost(testCase.limit)} diags := schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas()) doc := lowerer.Document(t) union, isUnion := typeByName(doc, "H").(*ir.Union) - assert.Equal(t, tc.refused, isUnion, "limit %d: a union only where the branch is past the budget", tc.limit) + assert.Equal(t, testCase.refused, isUnion, "limit %d: a union only where the branch is past the budget", testCase.limit) refusals := openapitest.PointersOf(diags, diag.BudgetExceeded) - if !tc.refused { - assert.Empty(t, refusals, "limit %d", tc.limit) + if !testCase.refused { + assert.Empty(t, refusals, "limit %d", testCase.limit) continue } require.Len(t, union.Variants, 2, "the branch is a variant") diff --git a/compilers/openapi/internal/schema/nullentry_internal_test.go b/compilers/openapi/internal/schema/nullentry_internal_test.go new file mode 100644 index 000000000..5738735cd --- /dev/null +++ b/compilers/openapi/internal/schema/nullentry_internal_test.go @@ -0,0 +1,86 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/service" + "github.com/dexpace/morphic/compilers/openapi/internal/service/servicetest" +) + +// unionNullSettled is what a run reads of one schema whose union says of null +// beyond its branches: its answer and the union reading's facts the second +// stage reads (settleUnionNull). +type unionNullSettled struct { + answer nullAnswerReadings + besideRest unionBesideRest + lifted int + lifts bool + refusesNull bool + askedDuringUnionReading bool +} + +// TestNullAnswer_SettlesAlikeFromEveryEntryPoint holds the two stages of a +// answer to one answer whichever entry point a run asks first: the schema's +// answer, its union reading, or the answer of a schema whose $ref lands on it, +// the walk then entering it from outside. Each union here lifts a null branch, +// refuses a null two branches leave in, or intersects its body as a flat enum +// would, the three readings the second stage reads in. +func TestNullAnswer_SettlesAlikeFromEveryEntryPoint(t *testing.T) { + t.Parallel() + spec := openapitest.ComponentSpecVer("3.1.0", ` Lift: {type: object, properties: {a: {type: string}}, oneOf: [{type: 'null'}]} + Refuse: {type: [string, 'null'], oneOf: [{minLength: 1}, {maxLength: 3}]} + Meet: {type: [string, 'null'], anyOf: [{const: a}, {const: null}]} + ToLift: {$ref: '#/components/schemas/Lift'} + ToRefuse: {$ref: '#/components/schemas/Refuse'} + ToMeet: {$ref: '#/components/schemas/Meet'} +`) + read := func(loweringContext lowering.Ctx, name string) unionNullSettled { + schemaStatement := heldAt(loweringContext, jsontext.Pointer("/components/schemas/"+name)) + reading := readLoweredUnion(loweringContext, schemaStatement.Schema) + lifted, lifts := reading.liftedBranch() + return unionNullSettled{answer: nullAnswerReadingsOf(loweringContext, schemaStatement), besideRest: reading.besideRest, lifted: lifted, lifts: lifts, + refusesNull: reading.refusesNull, askedDuringUnionReading: nullAnswerMemoOf(loweringContext).askedDuringUnionReading[schemaStatement]} + } + entries := map[string]func(loweringContext lowering.Ctx, name string){ + "answer first": func(loweringContext lowering.Ctx, name string) { + nullAnswerReadingsOf(loweringContext, heldAt(loweringContext, jsontext.Pointer("/components/schemas/"+name))) + }, + "union reading first": func(loweringContext lowering.Ctx, name string) { + readLoweredUnion(loweringContext, heldAt(loweringContext, jsontext.Pointer("/components/schemas/"+name)).Schema) + }, + "referrer first": func(loweringContext lowering.Ctx, name string) { + nullAnswerReadingsOf(loweringContext, heldAt(loweringContext, jsontext.Pointer("/components/schemas/To"+name))) + }, + } + for _, name := range []string{"Lift", "Refuse", "Meet"} { + var want unionNullSettled + for entry, ask := range entries { + run := servicetest.Context(t, spec, service.Policy{}) + ask(run.Ctx, name) + got := read(run.Ctx, name) + assert.False(t, got.askedDuringUnionReading, "%s, %s", name, entry) + if want == (unionNullSettled{}) { + want = got + continue + } + assert.Equal(t, want, got, "%s, %s", name, entry) + } + switch name { + case "Lift": + require.True(t, want.lifts && want.answer.admits(servicetest.Context(t, spec, service.Policy{}).Ctx), "the branch's null is lifted") + case "Refuse": + require.True(t, want.refusesNull, "the oneOf refuses the null") + default: + require.Equal(t, unionMembersFilteredByRest, want.besideRest, "the union intersects the body") + } + } +} diff --git a/compilers/openapi/internal/schema/nullfindings.go b/compilers/openapi/internal/schema/nullfindings.go new file mode 100644 index 000000000..0e9d959bd --- /dev/null +++ b/compilers/openapi/internal/schema/nullfindings.go @@ -0,0 +1,268 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// nullFindings returns a finding at each null the nullable-inference policy +// reads in where schemaStatement, written at pointer, writes it and its version +// does not, each saying why, and at each `nullable: true` beside a reference +// that widens nothing. It returns none while the policy is off. +func nullFindings(loweringContext lowering.Ctx, schemaStatement *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { + if !loweringContext.NullableInference.Honours() || schemaStatement.Truth != statement.Stated { + return nil + } + read := settledNullRead(loweringContext, schemaStatement, nullSkip{}) + store := nullAnswerMemoOf(loweringContext) + // A oneOf refusing the null its branches share takes it out of the + // declared reading too (settleUnionNull). + read.total.asDeclared = store.of[schemaStatement].asDeclared + var out []ir.Diagnostic + for _, conjunctValue := range nullConjuncts(schemaStatement) { + if conjunctValue.Ref != nil || !stated(conjunctValue.Schema) { + continue + } + reader := nullWhy{loweringContext: loweringContext, schemaStatement: schemaStatement, conjunct: conjunctValue, read: read, answerOf: store.settled} + at := pointer + conjunctValue.Rel + if reader.keywordsFinding() { + out = append(out, loweringContext.DiagAt(ir.SeverityInfo, diag.InferredNullable, at, "%s", reader.besideReferenceFinding())) + } + if code, message, ok := reader.nullableFinding(); ok { + out = append(out, loweringContext.DiagAt(nullableSeverity(code), code, nullableAt(at), "%s", message)) + } + } + return append(out, liftedFinding(loweringContext, schemaStatement, read, pointer)...) +} + +// liftedFinding is the info at the branch, written below pointer, whose null +// the nullable-inference policy lifts for the whole of schemaStatement +// (settleUnionNull) where read, what its conjuncts conjoin to, admits none. +func liftedFinding(loweringContext lowering.Ctx, schemaStatement *statement.Statement, read nullConjunctionRead, pointer jsontext.Pointer) []ir.Diagnostic { + if nullAnswerMemoOf(loweringContext).of[schemaStatement].underInference != nullAdmittedByReference || read.answer().underInference == nullAdmittedByReference { + return nil + } + reading := readLoweredUnion(loweringContext, schemaStatement.Schema) + index, lifted := reading.liftedBranch() + if reading.besideRest == unionMembersFilteredByRest || !lifted { + return nil + } + loweredUnion, _ := readConjunction(loweringContext, schemaStatement.Schema).loweredUnion() + at := loweredUnion.keyword.branchAt(pointer+loweredUnion.rel, index) + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityInfo, diag.InferredNullable, at, "%s", liftedBranchFinding)} +} + +// liftedBranchFinding is the message of a null branch the nullable-inference +// policy lifts for the whole schema beside a rest keeping null out. +const liftedBranchFinding = "this branch admits null alone and the rest of the schema keeps null out, which JSON Schema " + + "conjoins to no value, but the nullable-inference policy reads the branch as admitting null for the whole reference; a " + + "reference whose null rests on it is marked inferred" + +// nullWhy reads one conjunct of schemaStatement's conjunction for a null the +// policy reads in: read is what the conjunction says, and answerOf the settled +// answers. +type nullWhy struct { + loweringContext lowering.Ctx + schemaStatement *statement.Statement + conjunct statement.AllOfConjunct + read nullConjunctionRead + answerOf func(*statement.Statement) nullAnswerReadings +} + +// own reports whether the conjunct is the keywords schemaStatement's own object +// writes. +func (reason nullWhy) own() bool { + return reason.conjunct.Rel == "" && reason.conjunct.Schema == reason.schemaStatement.Schema +} + +// keywordsFinding reports whether the policy widens the reference +// schemaStatement holds by the value keywords the conjunct writes, which admit +// null where what the reference lands on does not. +func (reason nullWhy) keywordsFinding() bool { + return reason.read.references > 0 && reason.read.widens() && typedNull(reason.loweringContext, reason.conjunct.Schema).underInference.admits() && + reason.read.total.underInference != nullAdmittedByReference +} + +// nullableFinding returns the code and message of a finding at the `nullable: +// true` the conjunct writes, and false for none. +func (reason nullWhy) nullableFinding() (string, string, bool) { + schema := reason.conjunct.Schema + switch { + case !nullableTrue(schema): + return "", "", false + case reason.read.references > 0 && !reason.read.widens(): + return diag.UnwidenedNullable, reason.unwidenedFinding(), reason.read.total.underInference != nullAdmittedByReference + case reason.read.total.asDeclared == nullAdmittedByReference && (reason.own() || reason.read.references > 0): + return "", "", false + case reason.own(), ownNull(reason.loweringContext, schema, nullSkip{}, reason.answerOf).asDeclared != nullAdmittedByReference: + return diag.InferredNullable, nullableFinding(reason.why()), true + default: + return diag.InferredNullable, anotherConjunctFinding, reason.read.total.asDeclared != nullAdmittedByReference + } +} + +// nullableSeverity is the severity of a finding at a `nullable: true`: a +// warning where it widens nothing, since the null its author wrote is then on +// no reference, and an info where the policy reads it in. +func nullableSeverity(code string) ir.Severity { + if code == diag.UnwidenedNullable { + return ir.SeverityWarning + } + return ir.SeverityInfo +} + +// unwidenedFinding is the message of a `nullable: true` beside a reference the +// nullable-inference policy widens nothing by: it names each conjunct keeping +// null out (nullExcluders) and the reference left without a null. +func (reason nullWhy) unwidenedFinding() string { + excluders := nullExcluders(reason.loweringContext, reason.schemaStatement, reason.answerOf) + verb := "excludes" + if len(excluders) > 1 { + verb = "exclude" + } + holder := "this schema" + if !reason.own() { + holder = "the schema writing this allOf" + } + return "nullable: true makes nothing nullable here: " + strings.Join(excluders, " and ") + " " + verb + + " null, so a reference to " + holder + " is not nullable; the nullable-inference policy widens only a $ref standing alone" +} + +// nullExcluders names, by its path from schemaStatement's position, each +// conjunct of schemaStatement's conjunction that keeps null out under the +// lenient reading, as readNull conjoins them. A $dynamicRef schemaStatement +// expands sits beside keywords saying null alone, which the policy widens it +// by, so it is none. +func nullExcluders(loweringContext lowering.Ctx, schemaStatement *statement.Statement, answerOf func(*statement.Statement) nullAnswerReadings) []string { + var out []string + for _, conjunctValue := range nullConjuncts(schemaStatement) { + path := strings.TrimPrefix(string(conjunctValue.Rel), "/") + switch { + case conjunctValue.Ref != nil: + if target := nullTargetOf(loweringContext, conjunctValue.Schema); target != nil && answerOf(target).underInference == nullForbidden { + out = append(out, joinedPath(path, "$ref")+" ("+conjunctValue.Ref.Text+")") + } + case stated(conjunctValue.Schema): + out = append(out, keywordsExcludingNull(loweringContext, conjunctValue, path, answerOf)...) + } + } + return out +} + +// keywordsExcludingNull names, below path, each keyword conjunctValue writes +// that keeps null out under the lenient reading (ownNull). +func keywordsExcludingNull(loweringContext lowering.Ctx, conjunctValue statement.AllOfConjunct, path string, + answerOf func(*statement.Statement) nullAnswerReadings, +) []string { + schema := conjunctValue.Schema + excludes := map[string]bool{ + "type": !nullableTrue(schema) && typeNullAnswer(schema) == nullForbidden, + "const": constNullAnswer(schema) == nullForbidden, + "enum": enumNullAnswer(schema) == nullForbidden, + "allOf": conjunctValue.Capped && slices.ContainsFunc(conjunctValue.AllOf, func(entry statement.Subschema) bool { + return answerOf(loweringContext.Statements().Subschema(entry)).underInference == nullForbidden + }), + } + for _, union := range unionKeywords { + branches := union.branchesOf(schema) + excludes[string(union)] = len(branches) > 0 && branchesNull(loweringContext, branches, answerOf).underInference == nullForbidden + } + var out []string + for _, keyword := range []string{"type", "const", "enum", string(oneOfKeyword), string(anyOfKeyword), "allOf"} { + if excludes[keyword] { + out = append(out, joinedPath(path, keyword)) + } + } + return out +} + +// joinedPath is keyword below path, a path from a position, empty for the +// position itself. +func joinedPath(path, keyword string) string { + if path == "" { + return keyword + } + return path + "/" + keyword +} + +// anotherConjunctFinding is the message of a `nullable: true` on an allOf +// entry whose own keywords admit null, read in for the whole conjunction +// another conjunct of which excludes it. +const anotherConjunctFinding = "nullable: true is read as admitting null under the nullable-inference policy, though another " + + "conjunct of this allOf excludes null, and OpenAPI 3.0's nullable does not override it; a reference " + + "whose null rests on it is marked inferred" + +// nullableFinding is the message of a `nullable: true` the policy reads in, +// though why says its version does not. +func nullableFinding(why string) string { + return "nullable: true is read as admitting null under the nullable-inference policy, though " + why + + "; a reference whose null rests on it is marked inferred" +} + +// besideReferenceFinding is the message of value keywords admitting null that +// the policy widens a reference by, at the object writing them. +func (reason nullWhy) besideReferenceFinding() string { + if reason.own() && reason.schemaStatement.BesideRef != nil { + return "the keywords beside this $ref admit null and what it lands on does not, which JSON Schema " + + "conjoins to no null, but the nullable-inference policy reads them as admitting null for the whole " + + "reference; a reference whose null rests on them is marked inferred" + } + return "these keywords admit null and what the $ref they conjoin with lands on does not, which JSON Schema " + + "conjoins to no null, but the nullable-inference policy reads them as admitting null for the whole " + + "reference; a reference whose null rests on them is marked inferred" +} + +// why says why the declared reading leaves the conjunct's conjunction without +// null although it writes `nullable: true`, naming what excludes it. +func (reason nullWhy) why() string { + schema := reason.conjunct.Schema + switch { + case !definesNullableFor(reason.loweringContext, schema): + return "the dialect this schema is read in defines no nullable keyword" + case !writesType(schema): + return "OpenAPI 3.0 applies nullable only to a type written in the same Schema Object, and this schema writes none" + case enumNullAnswer(schema) == nullForbidden: + return "this schema's enum lists no null, and OpenAPI 3.0's nullable does not override it" + case constNullAnswer(schema) == nullForbidden: + return "this schema's const is not null, and OpenAPI 3.0's nullable does not override it" + } + if readLoweredUnion(reason.loweringContext, reason.schemaStatement.Schema).refusesNull { + return "null matches more than one branch of the oneOf beside it, which a oneOf refuses, and OpenAPI 3.0's " + + "nullable does not override it" + } + if keyword, ok := reason.unionExcludingNull(); ok { + return "this schema's " + string(keyword) + " admits null in none of its branches, and OpenAPI 3.0's nullable does not override it" + } + return reason.conjoinedWhy() +} + +// unionExcludingNull returns the keyword of a union the conjunct writes none of +// whose branches admits null under the declared reading, and false where it +// writes none. +func (reason nullWhy) unionExcludingNull() (unionKeyword, bool) { + for _, union := range unionKeywords { + branches := union.branchesOf(reason.conjunct.Schema) + if len(branches) > 0 && branchesNull(reason.loweringContext, branches, reason.answerOf).asDeclared == nullForbidden { + return union, true + } + } + return "", false +} + +// conjoinedWhy names the conjunct beside the own object's `nullable: true` +// that excludes null: its $ref, or otherwise an entry of its allOf. +func (reason nullWhy) conjoinedWhy() string { + if reason.schemaStatement.BesideRef != nil { + return "what its $ref lands on excludes null, which the keywords beside it conjoin with" + } + return "an allOf entry of this schema excludes null, and OpenAPI 3.0's nullable does not override it" +} diff --git a/compilers/openapi/internal/schema/nullread.go b/compilers/openapi/internal/schema/nullread.go new file mode 100644 index 000000000..d66d6f15c --- /dev/null +++ b/compilers/openapi/internal/schema/nullread.go @@ -0,0 +1,210 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// nullConjunctionRead is what one reading of a statement's conjunction found +// (readNull): every conjunct conjoined, before the policy widens anything; its +// conjuncts but its references conjoined; how many references it holds; +// whether a conjunct but a reference writes a union, structure or `nullable: +// true`; and whether a reference it holds lands on another. +type nullConjunctionRead struct { + total, own nullAnswerReadings + references int + union, structure, nullable bool + landsOnReference bool +} + +// widens reports whether the nullable-inference policy reads the conjunction +// as admitting null whatever its conjuncts conjoin to +// (docs/compilers/openapi.md#nullable): with one reference, only where the rest +// admits null and writes no union or structure, so it is that reference or +// null. +func (r nullConjunctionRead) widens() bool { + if r.references == 0 { + return r.nullable + } + return r.references == 1 && !r.union && !r.structure && r.own.underInference == nullAdmittedByReference +} + +// answer is the statement's answer: its conjuncts conjoined, the lenient +// reading widened where the policy widens it. +func (r nullConjunctionRead) answer() nullAnswerReadings { + out := r.total + if r.widens() { + out.underInference = nullAdmittedByReference + } + return out +} + +// nullSkip is the unions a reading leaves out: the one schema writes under +// keyword, as a union holder's rest does, every union where every says, as a +// body read outside them does, and none for the zero nullSkip. +type nullSkip struct { + schema *statement.Schema + keyword unionKeyword + every bool +} + +// skips reports whether s leaves out the union schema writes under keyword. +func (s nullSkip) skips(schema *statement.Schema, keyword unionKeyword) bool { + return s.every || s.schema != nil && s.schema == schema && s.keyword == keyword +} + +// readNull reads schemaStatement's conjunction for null over answerOf, the +// answers of the schemas it reads (nullReadsOf), the union skip names aside. +func readNull(loweringContext lowering.Ctx, schemaStatement *statement.Statement, skip nullSkip, answerOf func(*statement.Statement) nullAnswerReadings) nullConjunctionRead { + var read nullConjunctionRead + if schemaStatement.Truth != statement.Stated { + if schemaStatement.Truth.ReadsFalse() { + read.total = nullAnswerReadingsAlike(nullForbidden) + } + return read + } + for _, conjunctValue := range nullConjuncts(schemaStatement) { + if conjunctValue.Ref != nil { + read.references++ + } + read.add(loweringContext, conjunctValue, skip, answerOf) + } + if expansion := nullExpansionOf(loweringContext, schemaStatement); expansion != nil { + read.references++ + read.total = read.total.conjoin(answerOf(expansion)) + } + return read +} + +// add conjoins conjunctValue, one conjunct of the conjunction r reads, the +// union skip names left out. +func (r *nullConjunctionRead) add(loweringContext lowering.Ctx, conjunctValue statement.AllOfConjunct, skip nullSkip, + answerOf func(*statement.Statement) nullAnswerReadings, +) { + switch { + case conjunctValue.Ref != nil: + target := nullTargetOf(loweringContext, conjunctValue.Schema) + if target == nil { + return + } + r.total = r.total.conjoin(answerOf(target)) + r.landsOnReference = r.landsOnReference || target.Ref != nil + case conjunctValue.Truth.ReadsFalse(): + r.total, r.own = r.total.conjoin(nullAnswerReadingsAlike(nullForbidden)), r.own.conjoin(nullAnswerReadingsAlike(nullForbidden)) + case stated(conjunctValue.Schema): + own := ownNull(loweringContext, conjunctValue.Schema, skip, answerOf) + if conjunctValue.Capped { + for _, entry := range conjunctValue.AllOf { + own = own.conjoin(answerOf(loweringContext.Statements().Subschema(entry))) + } + } + r.total, r.own = r.total.conjoin(own), r.own.conjoin(own) + r.union = r.union || writesUnionBut(conjunctValue.Schema, skip) + r.structure = r.structure || hasAnyKey(conjunctValue.Schema, structureKeywords) + r.nullable = r.nullable || nullableTrue(conjunctValue.Schema) + } +} + +// ownNull is what schema, one object of a conjunction, says of null by its own +// keywords, the union skip names aside. +func ownNull(loweringContext lowering.Ctx, schema *statement.Schema, skip nullSkip, answerOf func(*statement.Statement) nullAnswerReadings) nullAnswerReadings { + return writtenNull(loweringContext, schema).conjoin(ownUnionsNull(loweringContext, schema, skip, answerOf)) +} + +// writtenNull is what schema's value keywords say of null. A `nullable: true` +// admits null for its type under the lenient reading, as OpenAPI 3.0.3 applies +// it, a const or enum beside it still conjoining. +func writtenNull(loweringContext lowering.Ctx, schema *statement.Schema) nullAnswerReadings { + typed := typedNull(loweringContext, schema) + if nullableTrue(schema) { + typed.underInference = foldNullAnswers(nullAdmittedByReference, constNullAnswer(schema), enumNullAnswer(schema)) + } + return typed +} + +// ownUnionsNull is what the unions schema writes but the one skip names say of +// null, conjoined (branchesNull). +func ownUnionsNull(loweringContext lowering.Ctx, schema *statement.Schema, skip nullSkip, answerOf func(*statement.Statement) nullAnswerReadings) nullAnswerReadings { + out := nullAnswerReadingsAlike(nullSaysNothing) + for _, union := range unionKeywords { + if branches := union.branchesOf(schema); len(branches) > 0 && !skip.skips(schema, union) { + out = out.conjoin(branchesNull(loweringContext, branches, answerOf)) + } + } + return out +} + +// writesUnionBut reports whether schema writes a union but the one skip names. +func writesUnionBut(schema *statement.Schema, skip nullSkip) bool { + return slices.ContainsFunc(unionKeywords, func(union unionKeyword) bool { + return len(union.branchesOf(schema)) > 0 && !skip.skips(schema, union) + }) +} + +// structureKeywords are the keywords applying to the members or elements of an +// instance, which the nullable-inference policy reads as a conjunct of its own +// beside a reference. +var structureKeywords = []string{"properties", "items", "prefixItems", "additionalProperties", "patternProperties"} + +// branchesNull is what one union's branches say of null, read over answerOf, +// under each reading. Where the union lifts a branch beside one other, it +// collapses to the reference to that one, which holds the null it admits +// (docs/compilers/openapi.md#union-null-variant), so asLowered counts it there. +func branchesNull(loweringContext lowering.Ctx, branches []statement.Subschema, answerOf func(*statement.Statement) nullAnswerReadings) nullAnswerReadings { + declared, lenient, asLowered := branchesRead{forbid: true}, branchesRead{forbid: true}, branchesRead{forbid: true} + liftedCount := 0 + for _, branch := range branches { + branchStatement := loweringContext.Statements().Subschema(branch) + answer := answerOf(branchStatement) + lifted := inlineBranch(branchStatement) && leavesOnlyNull(loweringContext, branchStatement.Schema) && answer.admits(loweringContext) + declared.add(answer.asDeclared, lifted) + lenient.add(answer.underInference, lifted) + asLowered.add(answer.asLowered, lifted) + if lifted { + liftedCount++ + } + } + out := nullAnswerReadings{asDeclared: declared.answer(), underInference: lenient.answer(), asLowered: asLowered.answer()} + if liftedCount > 0 && len(branches)-liftedCount == 1 && out.asLowered == nullAdmittedByVariants { + out.asLowered = nullAdmittedByReference + } + return out +} + +// branchesRead is what a union's branches read so far say of null under one +// reading: whether every one forbids it, and whether a lifted branch, or +// another, admits it. +type branchesRead struct { + forbid, lifted, admits bool +} + +// add reads one more branch, whose answer is answer and which the union +// lifts where lifted. +func (r *branchesRead) add(answer nullAnswer, lifted bool) { + r.forbid = r.forbid && answer == nullForbidden + switch { + case lifted && answer == nullAdmittedByReference: + r.lifted = true + case answer.admits(): + r.admits = true + } +} + +// answer is the union's answer under the reading r reads. +func (r branchesRead) answer() nullAnswer { + switch { + case r.forbid: + return nullForbidden + case r.lifted: + return nullAdmittedByReference + case r.admits: + return nullAdmittedByVariants + default: + return nullSaysNothing + } +} diff --git a/compilers/openapi/internal/schema/nulls.go b/compilers/openapi/internal/schema/nulls.go deleted file mode 100644 index 732bb5709..000000000 --- a/compilers/openapi/internal/schema/nulls.go +++ /dev/null @@ -1,834 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "encoding/json/jsontext" - "slices" - "strconv" - - yaml "go.yaml.in/yaml/v3" - - "github.com/dexpace/morphic/compilers/openapi/internal/budget" - "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/ids" - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/reftable" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" - "github.com/dexpace/morphic/compilers/openapi/internal/value" - "github.com/dexpace/morphic/ir" -) - -// nullDeclaration is what one keyword family says about the null value. JSON -// Schema conjoins keywords, so the families are read together rather than -// first-match: a schema admits null when one family puts it in the value space -// and no other takes it out. -type nullDeclaration int - -const ( - // nullUnconstrained is a family the schema does not declare, or one that - // constrains only non-null instances. It forbids nothing. - nullUnconstrained nullDeclaration = iota - // nullAdmitted is a family that puts null in the value space. - nullAdmitted - // nullForbidden is a family that takes null out of it. - nullForbidden -) - -// maxNullConjuncts bounds the walk below (styleguide bounded-recursion rule). -// One step is spent per schema the walk reads, each conjunct and $ref -// site among them, so it caps the walk's depth as well as its breadth: an -// `allOf` naming its own schema, or a diamond of conjunctions, terminates on it -// rather than on the shape of the source. A walk deeper or wider than this -// reads as silent, the answer that claims the least. The aliases a $ref chain -// passes are read without it, in a loop the chain bounds (lands). -const maxNullConjuncts = 256 - -// nullReading is what a schema says about null under each reading -// (docs/compilers/openapi.md#nullable): declared, as the document's version -// defines its keywords, and lenient, as the nullable-inference policy reads -// them, a null spelled by `nullable` or beside a $ref widening what it is -// written on. The two differ only there, so lenient admits wherever declared -// does. -type nullReading struct { - declared, lenient nullDeclaration -} - -// nullReadingAlikeUnderBothPolicies is the reading of a family that reads the -// same under both. -func nullReadingAlikeUnderBothPolicies(nullDeclarationValue nullDeclaration) nullReading { - return nullReading{declared: nullDeclarationValue, lenient: nullDeclarationValue} -} - -// foldNullReadings conjoins readings, each reading on its own. -func foldNullReadings(a, b nullReading) nullReading { - return nullReading{ - declared: foldNullVerdicts(a.declared, b.declared), - lenient: foldNullVerdicts(a.lenient, b.lenient), - } -} - -// admits reports whether the reading loweringContext's policy selects admits -// null: lenient while the policy is on, declared once it is off. -func (r nullReading) admits(loweringContext lowering.Ctx) bool { - return r.selected(loweringContext) == nullAdmitted -} - -// forbids reports whether the reading loweringContext's policy selects keeps -// null out. -func (r nullReading) forbids(loweringContext lowering.Ctx) bool { - return r.selected(loweringContext) == nullForbidden -} - -// selected is the verdict of the reading loweringContext's policy selects. -func (r nullReading) selected(loweringContext lowering.Ctx) nullDeclaration { - if loweringContext.NullableInference.Honours() { - return r.lenient - } - return r.declared -} - -// ref returns a reference to target that admits null as loweringContext's -// policy reads it (nullRef). -func (r nullReading) ref(loweringContext lowering.Ctx, target ir.TypeID) ir.TypeRef { - return nullRef(loweringContext, target, r.declared == nullAdmitted, r.lenient == nullAdmitted) -} - -// nullRef returns a reference to target that admits null where the reading -// loweringContext's policy selects does: lenient while it is on, declared once -// it is off. Where only lenient admits null, the reference names the policy's -// heuristic in Inferred, so the declared bit is still Nullable with Inferred -// empty. -func nullRef(loweringContext lowering.Ctx, target ir.TypeID, declared, lenient bool) ir.TypeRef { - if !loweringContext.NullableInference.Honours() { - return ir.TypeRef{Target: target, Nullable: declared} - } - out := ir.TypeRef{Target: target, Nullable: lenient} - if lenient && !declared { - out.Inferred = lowering.NullableInferenceHeuristic - } - return out -} - -// schemaAdmitsNull reports whether a schema admits the null value as -// loweringContext's policy reads it. Lowering lifts every spelling of that onto -// the enclosing TypeRef rather than into the type node, so the walk below is -// the one reading every site computing a Nullable bit goes through: a -// definition site, a union, an allOf conjunct and a $ref use site must never -// disagree about one schema. It reports nothing; schemaNullRef is the reading a -// position takes its own bit from. -func schemaAdmitsNull(loweringContext lowering.Ctx, schema *statement.Schema) bool { - nulls := newNulls(loweringContext) - return nulls.schema(schema, nullSite{}).admits(loweringContext) -} - -// schemaNullRef returns a reference to target from schema, a schema that writes -// no $ref, carrying what schema says about null, and reports each null the -// policy reads in where site's position writes it (nullSite). -func schemaNullRef(loweringContext lowering.Ctx, target ir.TypeID, schema *statement.Schema, site nullSite) (ir.TypeRef, []ir.Diagnostic) { - nulls := newNulls(loweringContext) - return nulls.schema(schema, site).ref(loweringContext, target), nulls.findings(loweringContext) -} - -// refNullRef is schemaNullRef for a $ref usage, read across the reference. -func refNullRef(loweringContext lowering.Ctx, target ir.TypeID, js *statement.Statement, site nullSite) (ir.TypeRef, []ir.Diagnostic) { - nulls := newNulls(loweringContext) - return nulls.ref(js, site).ref(loweringContext, target), nulls.findings(loweringContext) -} - -// nullSite is where a schema the walk reads is written, for a report about a -// null the policy reads in there, or none. A schema read across a $ref has -// none: its own position lowers it, and reports it there, so a report is made -// once per schema whatever references it. -type nullSite struct { - at jsontext.Pointer - ok bool -} - -// siteAt is the site of the schema written at pointer. -func siteAt(pointer jsontext.Pointer) nullSite { return nullSite{at: pointer, ok: true} } - -// child is the site of a schema written under s at the tokens. -func (s nullSite) child(tokens ...string) nullSite { - if !s.ok { - return s - } - return siteAt(s.at + ids.Ptr(tokens...)) -} - -// nulls reads what schemas say about null: across each $ref along its chain, -// an alias's own keywords included, within one budget for the whole read, -// conjuncts. -type nulls struct { - c lowering.Ctx - // nullable reports whether the dialect of the schema being read defines the - // nullable keyword (specrules.SchemaRules.Defines), the one question of the - // version this read asks. - nullable bool - // variants marks a read of whether a schema admits null wherever the IR - // holds it, a variant included, so a union admits null where any branch - // does and keeps it out where every branch does (variantsNull), not only - // where its null lifts onto the reference (unionNullReading); rest is a - // schema whose own union it leaves out. - variants bool - rest *statement.Schema - conjuncts budget.Budget - // found is each null the lenient reading reads in where the declared one - // leaves its schema without null, at a site the walk has. - found []nullFinding -} - -// nullFinding is one null the policy reads in: where the schema spelling it is -// written, and the report's message. -type nullFinding struct { - at jsontext.Pointer - message string -} - -// newNulls returns a read with the whole budget, over loweringContext's -// bindings and in the dialect loweringContext reads its schemas in. It returns -// a value so the read lives on its caller's stack, as one per position read is. -func newNulls(loweringContext lowering.Ctx) nulls { - return nulls{c: loweringContext, nullable: loweringContext.SchemaRules().Defines("nullable"), - conjuncts: budget.New(budget.AtMost(maxNullConjuncts))} -} - -// findings returns what n found as diagnostics, or none while loweringContext's -// policy is off: a null then admits only what its version says it does, and -// nothing is read in for a report to say so. -func (n *nulls) findings(loweringContext lowering.Ctx) []ir.Diagnostic { - if !loweringContext.NullableInference.Honours() || len(n.found) == 0 { - return nil - } - out := make([]ir.Diagnostic, 0, len(n.found)) - for _, nullFinding := range n.found { - out = append(out, loweringContext.DiagAt(ir.SeverityInfo, diag.InferredNullable, nullFinding.at, "%s", nullFinding.message)) - } - return out -} - -// schema reads a whole schema that writes no $ref, by conjoining what each of -// its keyword families says (keywords), then widening it where it writes -// `nullable: true` or an inline allOf entry speaking for it does. -func (n *nulls) schema(schema *statement.Schema, site nullSite) nullReading { - if !stated(schema) || !n.conjuncts.Spend(1) { - return nullReadingAlikeUnderBothPolicies(nullUnconstrained) - } - if schema.BesideRef != nil { - // The keywords written beside a $ref are read over what it lands on, as - // the policy reads its idiom there (docs/compilers/openapi.md#nullable). - return n.widenByEntry(schema, n.usage(schema, n.lands(n.c.Statements().Read(schema.BesideRef)), site), site) - } - own := n.keywords(schema, site) - return n.widenByEntry(schema, n.widen(schema, own, own, site), site) -} - -// ref reads a $ref usage as JSON Schema reads it: the keywords beside the $ref -// conjoined with what it lands on (lands). The target is read here because one -// interned at its own ID discards the reference its definition produced. -func (n *nulls) ref(js *statement.Statement, site nullSite) nullReading { - if !stated(js.Schema) || !n.conjuncts.Spend(1) { - return nullReadingAlikeUnderBothPolicies(nullUnconstrained) - } - return n.usage(js.Schema, n.lands(js), site) -} - -// usage is schema, a schema writing a $ref, read over target, what the $ref -// lands on: schema's own keywords conjoined with it, which the lenient reading -// widens where they admit null (widenRef) or write `nullable: true` (widen). A -// read of variants takes a union's null as its branches' and no keyword's -// beside the $ref, so it widens nothing there. -func (n *nulls) usage(schema *statement.Schema, target nullReading, site nullSite) nullReading { - typed, union := n.valueParts(schema) - own := foldNullReadings(typed, n.allOf(schema, site)) - all := foldNullReadings(own, union) - if !n.variants { - own = all - } - return n.widen(schema, all, n.widenRef(own, foldNullReadings(all, target), site), site) -} - -// lands reads what js's $ref lands on along the chain the bindings resolved: -// the schema it ends on, read over by each alias it passes, each in its own -// document's dialect. A chain that ends on no schema says nothing. What each -// reference site lands on is read once per compile (landing): the hops are -// walked forward to the first already read, on a stack the chain's length -// bounds, then read backward, each once, so n sites of one chain cost n -// readings, not n squared over two. -func (n *nulls) lands(js *statement.Statement) nullReading { - if js.Ref == nil || !js.Ref.Bound || js.Ref.Entry.Chain.Status != reftable.Resolved { - return nullReadingAlikeUnderBothPolicies(nullUnconstrained) - } - referenceSite := js.Ref.Entry - sites := []*landing{landingOf(n, js)} - var aliases []nullHop - hop, at := declaredOf(n.c, js) - for i := 1; i < referenceSite.Chain.Hops && hop != nil && hop.Ref != nil && !sites[len(sites)-1].kept; i++ { - aliases = append(aliases, nullHop{s: hop.Schema, nullable: definesNullableIn(n.c, at.Doc)}) - sites = append(sites, landingOf(n, hop)) - hop, at = declaredOf(n.c, hop) - } - // Each read below is in its own document's dialect, and the walk returns to - // its own on every way out. - defer func(outer bool) { n.nullable = outer }(n.nullable) - if last := sites[len(sites)-1]; !last.kept { - end, endDoc := hop, at.Doc - if hop == nil || hop.Ref != nil { - // The chain's end, unless a schema writing keys beside its $ref ended - // the run, the two one conjunction (statement.Schema.BesideRef). - end, endDoc = n.c.Statements().At(referenceSite.Chain.End), referenceSite.Chain.End.Doc - } - n.nullable = definesNullableIn(n.c, endDoc) - n.keep(last, n.conjunct(end, nullSite{})) - } - // Only the last site can be kept already: the walk stops at the first. - for i, a := range slices.Backward(aliases) { - n.nullable = a.nullable - *landingCount(n.c)++ - n.keep(sites[i], n.usage(a.s, sites[i+1].reading, nullSite{})) - } - return sites[0].reading -} - -// landing is what one reference site lands on, read once per compile: the -// reading, and whether it is kept. A reading the conjunct budget cut short -// is not, so a later read with a budget of its own reads it again. -type landing struct { - reading nullReading - kept bool -} - -// landedOn keys the landing of a reference site in the compile's readings, one -// for each way of reading a union (nulls.variants) and a union left out. -type landedOn struct { - js *statement.Statement - rest *statement.Schema - variants bool -} - -// landsRead keys the count of hop readings lands has made. -type landsRead struct{} - -// landingOf returns the landing of the reference site js as nullsValue reads -// it, one per compile. -func landingOf(nullsValue *nulls, js *statement.Statement) *landing { - return lowering.ReadOncePerRun(nullsValue.c, landedOn{js: js, rest: nullsValue.rest, variants: nullsValue.variants}, func() *landing { return &landing{} }) -} - -// landingCount returns the count of hop readings lands has made in the -// compile, which only the tests read. -func landingCount(loweringContext lowering.Ctx) *int { - return lowering.ReadOncePerRun(loweringContext, landsRead{}, func() *int { return new(int) }) -} - -// keep notes nullReadingValue as what landingValue lands on, kept unless the -// read's conjunct budget ran out on the way. -func (n *nulls) keep(landingValue *landing, nullReadingValue nullReading) { - landingValue.reading, landingValue.kept = nullReadingValue, !n.conjuncts.Exhausted() -} - -// nullHop is an alias a $ref chain passes, and whether the dialect of the -// document holding it defines nullable. -type nullHop struct { - s *statement.Schema - nullable bool -} - -// definesNullableIn reports whether the dialect the schemas of document doc -// are read in defines the nullable keyword. -func definesNullableIn(loweringContext lowering.Ctx, doc reftable.DocID) bool { - return loweringContext.Rules().In(doc).Defines("nullable") -} - -// widenRef is the lenient reading of keywords beside a $ref that admit null on -// their own, own, over the usage nullReadingValue they conjoin with what the -// $ref lands on: "this reference, or null", as `nullable: true` beside a $ref -// is meant and `type: [T, "null"]` is its spelling once nullable is gone. JSON -// Schema conjoins the two, so where the target excludes null the declared usage -// does too; one admitting null only so is noted at site. -func (n *nulls) widenRef(own, nullReadingValue nullReading, site nullSite) nullReading { - if own.lenient != nullAdmitted || nullReadingValue.lenient == nullAdmitted { - return nullReadingValue - } - // The declared reading admits null no more than the lenient one, which - // does not here, so the usage admits it only so. - if site.ok { - n.found = append(n.found, nullFinding{at: site.at, message: "the keywords beside this $ref admit null " + - "and what it lands on does not, which JSON Schema conjoins to no null, but the nullable-inference " + - "policy reads them as admitting null for the whole reference; a reference whose null rests on " + - "them is marked inferred"}) - } - nullReadingValue.lenient = nullAdmitted - return nullReadingValue -} - -// keywords conjoins what schema's own keyword families say, its allOf conjuncts -// among them but not a $ref it writes. Only `type` has a rule of its own for -// each reading, the nullable keyword's declared effect on it -// (declaredTypeVerdict); the conjuncts differ only as each is read. -func (n *nulls) keywords(schema *statement.Schema, site nullSite) nullReading { - typed, union := n.valueParts(schema) - return foldNullReadings(foldNullReadings(typed, union), n.allOf(schema, site)) -} - -// own is what schema says of null by its own keywords, its unions among them -// and its conjuncts aside, widened as schema widens it. -func (n *nulls) own(schema *statement.Schema) nullReading { - typed, union := n.valueParts(schema) - own := foldNullReadings(typed, union) - return n.widenByEntry(schema, n.widen(schema, own, own, nullSite{}), nullSite{}) -} - -// valueParts is what schema's type, const and enum say of null, and apart what -// its oneOf and anyOf say, as n reads a union. -func (n *nulls) valueParts(schema *statement.Schema) (typed, union nullReading) { - var valueVerdictsValue valueVerdicts - switch { - case !n.variants: - valueVerdictsValue = valueNulls(n.c, schema) - case schema == n.rest: - valueVerdictsValue = valueSetNulls(n.c, schema) - default: - valueVerdictsValue = valueSetNulls(n.c, schema) - valueVerdictsValue.union = n.variantsNull(schema) - } - return n.typed(schema, valueVerdictsValue.constant, valueVerdictsValue.enum), valueVerdictsValue.union -} - -// typed is what schema's type says of null under each reading, conjoined with -// the verdicts of its const and enum. -func (n *nulls) typed(schema *statement.Schema, constant, enum nullDeclaration) nullReading { - return nullReading{ - declared: foldNullVerdicts(n.declaredTypeVerdict(schema), constant, enum), - lenient: foldNullVerdicts(typeNullVerdict(schema), constant, enum), - } -} - -// valueNullsOf keys what valueNulls read of one schema, and valueSetNullsOf -// what valueSetNulls did. -type ( - valueNullsOf struct { - schema *statement.Schema - } - valueSetNullsOf struct { - schema *statement.Schema - } -) - -// valueVerdicts is what a schema's const, enum and union families say of null. -// Each reads only the schema, the same whichever site asks; the union's is read -// under each reading, as its null branches are. -type valueVerdicts struct { - constant, enum nullDeclaration - union nullReading -} - -// valueNulls returns schema's valueVerdicts, read once a run: every $ref to -// schema asks, and the enum and union families scan each member and branch, so -// reading them at each reference would cost the references times the members. -func valueNulls(loweringContext lowering.Ctx, schema *statement.Schema) valueVerdicts { - return lowering.ReadOncePerRun(loweringContext, valueNullsOf{schema}, func() valueVerdicts { - valueVerdictsValue := valueSetNulls(loweringContext, schema) - valueVerdictsValue.union = unionNullReading(loweringContext, schema) - return valueVerdictsValue - }) -} - -// valueSetNulls returns what schema's const and enum say of null, read once a -// run, with no union: a read of null on variants reads that otherwise -// (nulls.variantsNull), asking no union whether it is distributed. -func valueSetNulls(loweringContext lowering.Ctx, schema *statement.Schema) valueVerdicts { - return lowering.ReadOncePerRun(loweringContext, valueSetNullsOf{schema}, func() valueVerdicts { - return valueVerdicts{constant: constNullVerdict(schema), enum: enumNullVerdict(schema)} - }) -} - -// widen is the lenient reading of `nullable: true` on schema: it admits null -// for the whole of schema, whatever else schema says, where the declared -// reading makes it a member of a `type` that the rest of schema conjoins with. -// own is what schema's own keywords say, and nullReadingValue what schema says -// in all. A keyword that admits null only so is noted at site, with why its -// version does not. -func (n *nulls) widen(schema *statement.Schema, own, nullReadingValue nullReading, site nullSite) nullReading { - if !nullableTrue(schema) { - return nullReadingValue - } - if nullReadingValue.declared != nullAdmitted && site.ok { - n.found = append(n.found, nullFinding{at: site.at + ids.Ptr("nullable"), message: "nullable: true is " + - "read as admitting null under the nullable-inference policy, though " + n.why(schema, own) + - "; a reference whose null rests on it is marked inferred"}) - } - nullReadingValue.lenient = nullAdmitted - return nullReadingValue -} - -// why says why the declared reading of schema leaves it without null although -// schema writes `nullable: true`, own being what schema's own keywords say. -// Once schema writes a `type` the keyword adds null to, only an enum, a const -// or an allOf beside it forbids it, which leaves own without null, or, for -// schema writing a $ref, what that lands on, which own's null conjoins with. -func (n *nulls) why(schema *statement.Schema, own nullReading) string { - switch { - case !n.nullable: - return "the dialect this schema is read in defines no nullable keyword" - case !writesType(schema): - return "OpenAPI 3.0 applies nullable only to a type written in the same Schema Object, " + - "and this schema writes none" - case enumNullVerdict(schema) == nullForbidden: - return "this schema's enum lists no null, and OpenAPI 3.0's nullable does not override it" - case constNullVerdict(schema) == nullForbidden: - return "this schema's const is not null, and OpenAPI 3.0's nullable does not override it" - case own.declared != nullAdmitted: - return "an allOf entry of this schema excludes null, and OpenAPI 3.0's nullable does not override it" - default: - return "what its $ref lands on excludes null, which the keywords beside it conjoin with" - } -} - -// declaredTypeVerdict is typeNullVerdict as the dialect schema is read in reads -// a `nullable: true` beside the type. Where it defines the keyword, as 3.0 -// does, it adds null to a type written in the same Schema Object, beside a $ref -// as anywhere, as `type: [T, "null"]` spells it from 3.1, so the result then -// conjoins like any type. Where it does not, nullable says nothing. -func (n *nulls) declaredTypeVerdict(schema *statement.Schema) nullDeclaration { - nullDeclarationValue := typeNullVerdict(schema) - if nullDeclarationValue == nullForbidden && n.nullable && nullableTrue(schema) { - return nullAdmitted - } - return nullDeclarationValue -} - -// foldNullVerdicts conjoins keyword verdicts: one forbidding family decides the -// schema, otherwise one admitting family does, and a schema no family speaks for -// stays silent — which is not the same answer as forbidding, since a silent -// conjunct must not veto a sibling that admits. -func foldNullVerdicts(verdicts ...nullDeclaration) nullDeclaration { - out := nullUnconstrained - for _, nullDeclaration := range verdicts { - if nullDeclaration == nullForbidden { - return nullForbidden - } - if nullDeclaration == nullAdmitted { - out = nullAdmitted - } - } - return out -} - -// typeNullVerdict reads the `type` keyword. A schema writing none constrains no -// instance kind at all, so it is silent rather than forbidding. -func typeNullVerdict(schema *statement.Schema) nullDeclaration { - if !writesType(schema) { - return nullUnconstrained - } - if slices.Contains(schema.Types(), statement.KindNull) { - return nullAdmitted - } - return nullForbidden -} - -// constNullVerdict reads `const`, which fixes the value space to one member. -func constNullVerdict(schema *statement.Schema) nullDeclaration { - node := schema.Const() - if node == nil { - return nullUnconstrained - } - if isNullValue(node) { - return nullAdmitted - } - return nullForbidden -} - -// enumNullVerdict reads `enum`, which fixes the value space to its members: the -// position admits null exactly when a member is null. -// -// An empty enum is silent rather than forbidding. It lists no member at all, so -// reading it as "no null member" would let a degenerate keyword strip a -// co-declared type array's null; what an empty enum lowers to is GitHub #278's -// question, and this rule leaves it open. -func enumNullVerdict(schema *statement.Schema) nullDeclaration { - nodes := schema.Enum() - if len(nodes) == 0 { - return nullUnconstrained - } - if slices.ContainsFunc(nodes, isNullValue) { - return nullAdmitted - } - return nullForbidden -} - -// isNullValue reports whether an enum member or const node is the null literal, -// read through the same converter enumEntries drops a member by. Both must -// recognize one spelling: the null this predicate lifts onto a reference is -// exactly the member that lowering strips. -func isNullValue(node *yaml.Node) bool { - val, err := value.FromNode(node) - return err == nil && val.Kind == ir.ValueNull -} - -// unionNullReading reads the null branches of schema's oneOf and anyOf -// (nullAloneReading) under each reading: the union admits null where a branch -// does, so its null rests on the policy where only a branch's lenient reading -// admits it. A null branch counts where the union is the type itself or is -// distributed across the structural siblings beside it (buildUnion), their -// verdicts conjoining with it; a union kept verbatim beside them says nothing. -// One union never forbids; a oneOf and an anyOf together forbid null where -// one keeps it out (pairMayAdmitNull). -func unionNullReading(loweringContext lowering.Ctx, schema *statement.Schema) nullReading { - choice := schema.ChoiceKeywords() - out := nullReadingAlikeUnderBothPolicies(nullUnconstrained) - for _, b := range slices.Concat(choice.OneOf, choice.AnyOf) { - st := loweringContext.Statements().Subschema(b) - if !inlineBranch(st) { - continue - } - nullReading, ok := nullAloneReading(loweringContext, st.Schema) - if !ok { - continue - } - if nullReading.declared == nullAdmitted { - out.declared = nullAdmitted - } - if nullReading.lenient == nullAdmitted { - out.lenient = nullAdmitted - } - } - // The lenient reading admits wherever the declared one does, so a union it - // leaves silent is silent under both, and asks no more of its siblings. - if !pairMayAdmitNull(loweringContext, choice) { - // A oneOf and an anyOf are conjuncts: one keeping null out keeps it - // out of the position, as on two allOf entries (pairKeepsNullOut). - return nullReadingAlikeUnderBothPolicies(nullForbidden) - } - if out.lenient == nullUnconstrained || hasUnionSiblings(loweringContext, schema) && !distributesUnion(loweringContext, schema) { - return nullReadingAlikeUnderBothPolicies(nullUnconstrained) - } - return out -} - -// pairMayAdmitNull reports whether each of a oneOf and an anyOf written -// together may admit null, as an instance of both must, a null being shared -// only where every conjunct may admit it, read by one walk in the reading a -// passed-over union beside a body has (bodyAdmitsNull). One union alone asks -// nothing more. -func pairMayAdmitNull(loweringContext lowering.Ctx, choice statement.Choice) bool { - if len(choice.OneOf) == 0 || len(choice.AnyOf) == 0 { - return true - } - nulls := newNulls(loweringContext) - nulls.variants = true - return !pairForbidsNull(&nulls, choice) -} - -// pairForbidsNull reports whether nullsValue's walk, whose budget bounds this -// read as the rest of the walk, finds the oneOf or the anyOf of choice keeping -// null out: every branch of it does within that budget. -func pairForbidsNull(nullsValue *nulls, choice statement.Choice) bool { - for _, branches := range [][]statement.Subschema{choice.OneOf, choice.AnyOf} { - if nullsValue.branchesNull(branches).forbids(nullsValue.c) && !nullsValue.conjuncts.Exhausted() { - return true - } - } - return false -} - -// distributesUnion reports whether schema, writing a union beside structural -// keywords, lowers to a union of models conjoining its body with each branch -// (classifyUnionSiblings), as read at the position its bindings place it at. -func distributesUnion(loweringContext lowering.Ctx, schema *statement.Schema) bool { - at, placed := siteOf(schema) - if !placed { - return false - } - in, _ := lowering.InDocument(loweringContext, at.Doc) - return classifyUnionSiblings(in, schema, at.Pointer) == unionDistributed -} - -// NullAlone reports whether schema admits null and no other value by its own -// keywords, as loweringContext's policy reads null -// (docs/compilers/openapi.md#null-alone). Such a schema lowers to an Enum with -// no member behind a nullable reference, and a union branch written so is the -// union's null. -func NullAlone(loweringContext lowering.Ctx, schema *statement.Schema) bool { - nullReading, ok := nullAloneReading(loweringContext, schema) - return ok && nullReading.admits(loweringContext) -} - -// nullAloneOf keys what nullAloneReading read of one schema. -type nullAloneOf struct { - schema *statement.Schema -} - -// nullAloneRead is nullAloneReading's answer for one schema. -type nullAloneRead struct { - reading nullReading - ok bool -} - -// nullAloneReading is what schema, a schema whose own keywords leave it no -// value but null (leavesOnlyNull), says of that null under each reading, and -// false for any other schema. It writes no union, allOf or $ref, so its type, -// const and enum, widened where it writes `nullable: true`, are all a read of -// the whole schema finds (schemaAdmitsNull), read here without asking -// valueNulls, which reads a union's branches by this. Every reader of a branch -// asks, so it is read once a run. -func nullAloneReading(loweringContext lowering.Ctx, schema *statement.Schema) (nullReading, bool) { - nullAloneReadValue := lowering.ReadOncePerRun(loweringContext, nullAloneOf{schema}, func() nullAloneRead { - if !leavesOnlyNull(loweringContext, schema) { - return nullAloneRead{} - } - nulls := newNulls(loweringContext) - own := nulls.typed(schema, constNullVerdict(schema), enumNullVerdict(schema)) - return nullAloneRead{reading: nulls.widen(schema, own, own, nullSite{}), ok: true} - }) - return nullAloneReadValue.reading, nullAloneReadValue.ok -} - -// leavesOnlyNull reports whether the keywords schema itself writes leave it no -// value but null, whether or not they admit that one: it writes no $ref, allOf, -// oneOf, anyOf or $dynamicRef, which admit what other schemas do; an enum it -// writes lists null and nothing else, within the member budget an enum past -// which lowers to the top type (lowerEnum); and it writes a const, which the -// null reading holds to null, such an enum, or a type naming null alone. -func leavesOnlyNull(loweringContext lowering.Ctx, schema *statement.Schema) bool { - if !stated(schema) || refWritten(schema) || writesConjuncts(schema) || declaresUnion(schema) || declaresDynamicRef(schema) { - return false - } - if enumWritten(schema) { - members := schema.Enum() - return len(members) > 0 && loweringContext.Limits.MaxEnumMembers.Admits(len(members)) && - !slices.ContainsFunc(members, func(node *yaml.Node) bool { return !isNullValue(node) }) - } - return schema.Const() != nil || writesType(schema) && len(effectiveTypes(schema)) == 0 -} - -// allOf conjoins what the allOf entries say. A conjunction admits null when an -// entry does and none forbids it, which is what makes `{allOf: [{$ref: T}]}` -// answer the same as `{$ref: T}`: the composition declares no nullability of its -// own, and the usage naming it has nowhere else to derive the bit from (GitHub -// #279). Model.Base and Mixins still carry no Nullable bit: they name a -// conjunct, and nullability is a property of the usage that names the -// conjunction. -func (n *nulls) allOf(schema *statement.Schema, site nullSite) nullReading { - out := nullReadingAlikeUnderBothPolicies(nullUnconstrained) - for _, b := range allOfIn(schema) { - out = foldNullReadings(out, n.conjunct(n.c.Statements().Subschema(b), site.child("allOf", strconv.Itoa(b.Index)))) - } - if pairKeepsNullOut(n, schema) { - out = foldNullReadings(out, nullReadingAlikeUnderBothPolicies(nullForbidden)) - } - return out -} - -// pairKeepsNullOut reports whether schema and its inline allOf entries write a -// oneOf and an anyOf between them, no one of them writing both, of which a -// union keeps null out, read by nullsValue's walk (pairForbidsNull): an -// instance of the position is one of each, so that union's null is no value it -// admits. One schema writing both is read by unionNullReading. -func pairKeepsNullOut(nullsValue *nulls, schema *statement.Schema) bool { - var pair statement.Choice - note := func(statementSchema *statement.Schema) bool { - choice := statementSchema.ChoiceKeywords() - if len(choice.OneOf) > 0 && len(choice.AnyOf) > 0 { - return false - } - if len(choice.OneOf) > 0 { - pair.OneOf = choice.OneOf - } - if len(choice.AnyOf) > 0 { - pair.AnyOf = choice.AnyOf - } - return true - } - if !note(schema) { - return false - } - for _, b := range allOfIn(schema) { - if st := nullsValue.c.Statements().Subschema(b); inlineBranch(st) && !note(st.Schema) { - return false - } - } - if len(pair.OneOf) == 0 || len(pair.AnyOf) == 0 { - return false - } - // Each union's null is its branches', as one schema writing both reads it - // (pairMayAdmitNull), so a branch that is a union keeps null out where its - // own branches do; the read stays on nullsValue's budget. - variants := nullsValue.variants - nullsValue.variants = true - forbids := pairForbidsNull(nullsValue, pair) - nullsValue.variants = variants - return forbids -} - -// widenByEntry is the lenient reading of a `nullable: true` that folds: written -// on an inline entry that speaks for the position, it says what the keyword -// beside the allOf says, and widens all of s (widen), a `type` beside the allOf -// included, where the declared reading leaves it conjoined. An entry whose own -// keywords admit null said so by themselves, so widen said nothing of it, and it -// is noted here, where s is written. A 3.1 `type: [T, "null"]` on a conjunct -// stays conjoined, which beside a $ref it does not -// (docs/compilers/openapi.md#allof-refinement). -func (n *nulls) widenByEntry(schema *statement.Schema, nullReadingValue nullReading, site nullSite) nullReading { - for _, entry := range nullableFoldingEntries(n.c, schema) { - nullReadingValue.lenient = nullAdmitted - if !site.ok { - break // a read across a $ref reports nothing, so one widening is all it needs - } - if nullReadingValue.declared != nullAdmitted && n.keywords(entry.schema.Schema, nullSite{}).declared == nullAdmitted { - n.found = append(n.found, nullFinding{at: site.at + entry.pointer + ids.Ptr("nullable"), message: "nullable: true " + - "is read as admitting null under the nullable-inference policy, though another conjunct of this allOf " + - "excludes null, and OpenAPI 3.0's nullable does not override it; a reference whose null rests on it " + - "is marked inferred"}) - } - } - return nullReadingValue -} - -// nullableFoldingEntriesKey keys what nullableFoldingEntries read of one -// schema. -type nullableFoldingEntriesKey struct { - schema *statement.Schema -} - -// nullableFoldingEntries returns the entries of s's flattened allOf, each at -// its pointer under s's, that speak for s, write `nullable: true` and write no -// properties (foldsNullable). Every use of s asks, so it is read once a run. An -// entry writing `false` widens nothing, though it speaks where the only `true` -// beside it is on a $ref entry, which no fold compares. -func nullableFoldingEntries(loweringContext lowering.Ctx, schema *statement.Schema) []allOfEntry { - return lowering.ReadOncePerRun(loweringContext, nullableFoldingEntriesKey{schema}, func() []allOfEntry { - if !allOfDecides(loweringContext, schema) { - return nil - } - comp := allOfEntries(loweringContext, schema, "") - var out []allOfEntry - for i, speaks := range foldingAllOfEntries(loweringContext, schema) { - entry := comp.entries[i] - if speaks && nullableTrue(entry.schema.Schema) && foldsNullable(entry.schema.Schema) { - out = append(out, entry) - } - } - return out - }) -} - -// conjunct reads one allOf entry, or what a $ref lands on. A `false` schema -// admits no instance whatever, null included; a `true` one constrains nothing, -// nor does a `null` written for one, which is no `false` -// (statement.Truth.ReadsFalse). -func (n *nulls) conjunct(b *statement.Statement, site nullSite) nullReading { - switch { - case b == nil: - return nullReadingAlikeUnderBothPolicies(nullUnconstrained) - case b.Truth.ReadsFalse(): - return nullReadingAlikeUnderBothPolicies(nullForbidden) - case b.Truth != statement.Stated: - return nullReadingAlikeUnderBothPolicies(nullUnconstrained) - case b.Ref != nil: - return n.ref(b, site) - default: - return n.schema(b.Schema, site) - } -} diff --git a/compilers/openapi/internal/schema/nulls_internal_test.go b/compilers/openapi/internal/schema/nulls_internal_test.go deleted file mode 100644 index 47636aaf8..000000000 --- a/compilers/openapi/internal/schema/nulls_internal_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "strings" - "testing" - - "github.com/speakeasy-api/openapi/jsonschema/oas3" - "github.com/speakeasy-api/openapi/marshaller" - soa "github.com/speakeasy-api/openapi/openapi" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/dexpace/morphic/compilers/openapi/internal/budget" - "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" - "github.com/dexpace/morphic/ir" -) - -// TestRefNullRef_AnUnresolvedRefIsNotNullable pins the guard on the second half -// of the question. A $ref site admits null as its own keywords and its target -// jointly say; a reference no binding resolved has no target to ask, and must -// read as not-nullable rather than dereference nothing. -func TestRefNullRef_AnUnresolvedRefIsNotNullable(t *testing.T) { - t.Parallel() - js := &oas3.JSONSchema[oas3.Referenceable]{} - valErrs, err := marshaller.Unmarshal(t.Context(), - strings.NewReader("$ref: '#/components/schemas/Missing'"), js) - require.NoError(t, err) - require.Empty(t, valErrs, "the fixture parses cleanly") - - ref, diags := refNullRef(NewRawLowerer(&soa.OpenAPI{}).Ctx, "type/x", Standalone(js), siteAt("/x")) - assert.Equal(t, ir.TypeRef{Target: "type/x"}, ref) - assert.Empty(t, diags) -} - -// TestNulls_TheConjunctWalkIsBounded pins the budget the conjunct -// walk runs on. Whether a schema admits null is decided partly by its allOf -// conjuncts, each reached through a $ref whose target is asked the same -// question, so a schema conjoining itself would otherwise not terminate. -// -// A budget spent per schema visited caps depth as well as breadth, and an -// exhausted walk answers "silent" — the verdict that claims the least, so a -// spec too deep to read is never reported as admitting a null it does not. -func TestNulls_TheConjunctWalkIsBounded(t *testing.T) { - t.Parallel() - nullable := &oas3.Schema{ - Type: oas3.NewTypeFromArray([]oas3.SchemaType{oas3.SchemaTypeString, oas3.SchemaTypeNull}), - } - - loweringContext := NewRawLowerer(&soa.OpenAPI{}).Ctx - require.Equal(t, nullReadingAlikeUnderBothPolicies(nullAdmitted), (&nulls{c: loweringContext, conjuncts: budget.New(budget.AtMost(1))}).schema(StandaloneSchema(nullable), nullSite{}), - "the fixture admits null while there is budget to read it") - - assert.Equal(t, nullReadingAlikeUnderBothPolicies(nullUnconstrained), (&nulls{c: loweringContext, conjuncts: budget.New(budget.AtMost(0))}).schema(StandaloneSchema(nullable), nullSite{}), - "an exhausted budget stops the walk without claiming anything") - assert.Positive(t, maxNullConjuncts, "the cap is a real bound, not zero") -} - -// TestSchemaAdmitsNull_ReadsMaxNullConjunctsSchemas pins the budget as the -// lowering spends it: a null maxNullConjuncts schemas down an allOf chain is -// read, and one a schema deeper is not, the walk falling silent there. -func TestSchemaAdmitsNull_ReadsMaxNullConjunctsSchemas(t *testing.T) { - t.Parallel() - chain := func(levels int) *oas3.Schema { - src := strings.Repeat("{allOf: [", levels) + "{type: [string, 'null']}" + strings.Repeat("]}", levels) - js := &oas3.JSONSchema[oas3.Referenceable]{} - valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader(src), js) - require.NoError(t, err) - require.Empty(t, valErrs) - return js.GetSchema() - } - loweringContext := NewRawLowerer(&soa.OpenAPI{}).Ctx - assert.True(t, schemaAdmitsNull(loweringContext, StandaloneSchema(chain(maxNullConjuncts-1))), "the null the last schema the budget reads admits") - assert.False(t, schemaAdmitsNull(loweringContext, StandaloneSchema(chain(maxNullConjuncts))), "one schema deeper, the walk is silent") -} - -// TestNulls_AnEntryWithNoSchemaSaysNothing pins the guard on an -// absent allOf entry. The parser never produces a nil entry, so nothing in the -// corpus reaches it; a conjunct that is not there constrains nothing, which is -// silence rather than a refusal — reading it as forbidding would let one -// missing entry strip a sibling's null. -func TestNulls_AnEntryWithNoSchemaSaysNothing(t *testing.T) { - t.Parallel() - nullsValue := &nulls{c: NewRawLowerer(&soa.OpenAPI{}).Ctx, conjuncts: budget.New(budget.AtMost(maxNullConjuncts))} - assert.Equal(t, nullReadingAlikeUnderBothPolicies(nullUnconstrained), nullsValue.conjunct(nil, nullSite{})) - assert.Equal(t, nullReadingAlikeUnderBothPolicies(nullUnconstrained), nullsValue.conjunct(Standalone(openapitest.EmptyEitherSchema()), nullSite{}), - "an entry whose either-value holds neither schema nor bool says nothing either") -} - -// TestNullAloneReading_IsTheWholeSchemasReading holds the reading a null branch -// is taken by to the one every Nullable site shares: over a schema whose own -// keywords leave no value but null, it is what reading the whole schema gives, -// under each reading and each dialect's nullable, so the union that lifts the -// branch and the branch lowered alone cannot disagree. -func TestNullAloneReading_IsTheWholeSchemasReading(t *testing.T) { - t.Parallel() - schemas := []string{ - `{type: "null"}`, `{type: ["null", "null"]}`, `{enum: [null]}`, `{const: null}`, - `{type: string, const: null}`, `{type: [string, "null"], enum: [null]}`, `{type: string, enum: [null]}`, - `{type: object, enum: [null], nullable: true}`, `{type: string, const: null, nullable: true}`, - `{type: "null", nullable: false}`, `{enum: [null], const: 1}`, - } - for _, version := range []string{"3.0.3", "3.1.0"} { - var body strings.Builder - for i, s := range schemas { - body.WriteString(" S" + string(rune('a'+i)) + ": " + s + "\n") - } - lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer(version, body.String())) - for i, src := range schemas { - if version == "3.0.3" && src == `{type: ["null", "null"]}` { - continue // 3.0 writes no type list, so it reads this one as left out - } - s := componentSchema(t, lowerer, "S"+string(rune('a'+i))) - got, ok := nullAloneReading(lowerer.Ctx, StatedIn(lowerer, s)) - require.True(t, ok, "%s %s leaves no value but null", version, src) - nulls := newNulls(lowerer.Ctx) - assert.Equal(t, nulls.schema(StatedIn(lowerer, s), nullSite{}), got, "%s %s", version, src) - } - } - lowererValue, _ := LoweredFor(t, openapitest.ComponentSpec(" S: {type: [string, \"null\"]}\n")) - _, ok := nullAloneReading(lowererValue.Ctx, StatedIn(lowererValue, componentSchema(t, lowererValue, "S"))) - assert.False(t, ok, "a type admitting a string leaves more than null") -} - -// TestNullAloneReading_ReadsASchemaOnce pins that a schema's reading as a -// branch of null alone is read once a run, since each reader of a union asks of -// every branch, and an enum of nulls costs a read per member: it goes after the -// first read, which no lowering does, so only a remembered answer stays. -func TestNullAloneReading_ReadsASchemaOnce(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" S: {enum: [null]}\n")) - s := componentSchema(t, lowerer, "S") - first, ok := nullAloneReading(lowerer.Ctx, StatedIn(lowerer, s)) - require.True(t, ok) - StatedIn(lowerer, s).Values.Enum = nil - again, ok := nullAloneReading(lowerer.Ctx, StatedIn(lowerer, s)) - assert.True(t, ok, "the second ask reads what the first read") - assert.Equal(t, first, again) -} - -// TestUnionNullReading_AnUnplacedUnionBesideABodyDistributesNothing pins the -// guard on where a union beside a body is distributed: a schema the bindings -// place nowhere has no position to lower its union at, so it distributes -// nothing and its null branch says nothing of the reference, as beside a body -// that keeps the union whole. -func TestUnionNullReading_AnUnplacedUnionBesideABodyDistributesNothing(t *testing.T) { - t.Parallel() - js := &oas3.JSONSchema[oas3.Referenceable]{} - valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader( - "{type: object, properties: {p: {type: string}}, oneOf: [{type: object}, {type: 'null'}]}"), js) - require.NoError(t, err) - require.Empty(t, valErrs, "the fixture parses cleanly") - - loweringContext := NewRawLowerer(&soa.OpenAPI{}).Ctx - schema := Standalone(js).Schema - require.True(t, hasUnionSiblings(loweringContext, schema), "the union stands beside a body") - assert.False(t, distributesUnion(loweringContext, schema)) - assert.Equal(t, nullReadingAlikeUnderBothPolicies(nullUnconstrained), unionNullReading(loweringContext, schema)) -} diff --git a/compilers/openapi/internal/schema/nullverdict.go b/compilers/openapi/internal/schema/nullverdict.go new file mode 100644 index 000000000..fcc2857af --- /dev/null +++ b/compilers/openapi/internal/schema/nullverdict.go @@ -0,0 +1,322 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/value" + "github.com/dexpace/morphic/ir" +) + +// nullAnswer is what a schema says of null under one reading +// (docs/compilers/openapi.md#nullable). The admitting answers are ordered, so +// the one holding more of the null is the greater. +type nullAnswer uint8 + +const ( + // nullSaysNothing is a schema saying nothing of null, which forbids nothing. + nullSaysNothing nullAnswer = iota + // nullForbidden is a schema null is no value of. + nullForbidden + // nullAdmittedByVariants is a schema admitting null that only a variant + // of its union holds, as a branch naming a nullable schema does. + nullAdmittedByVariants + // nullAdmittedByReference is a schema admitting null the reference naming + // it holds. + nullAdmittedByReference +) + +// admits reports whether v admits null, wherever the IR holds it. +func (v nullAnswer) admits() bool { + return v == nullAdmittedByReference || v == nullAdmittedByVariants +} + +// conjoinNullAnswers is what two conjuncts say of null together: a forbidding +// one decides, else the one holding more of it. +func conjoinNullAnswers(a, b nullAnswer) nullAnswer { + if a == nullForbidden || b == nullForbidden { + return nullForbidden + } + return max(a, b) +} + +// nullAnswerReadings is a schema's answer as its document's version defines its +// keywords (asDeclared), as the nullable-inference policy reads them +// (underInference), which admits wherever asDeclared does, and as the policy's +// lowering holds the declared one (asLowered): a union it collapses to the +// reference to its one non-null branch holds that branch's null there. +type nullAnswerReadings struct { + asDeclared, underInference, asLowered nullAnswer +} + +// nullAnswerReadingsAlike is the reading of what reads the same under both +// policies. +func nullAnswerReadingsAlike(answer nullAnswer) nullAnswerReadings { + return nullAnswerReadings{asDeclared: answer, underInference: answer, asLowered: answer} +} + +// conjoin is r and other read as conjuncts, each reading on its own. +func (r nullAnswerReadings) conjoin(other nullAnswerReadings) nullAnswerReadings { + return nullAnswerReadings{asDeclared: conjoinNullAnswers(r.asDeclared, other.asDeclared), underInference: conjoinNullAnswers(r.underInference, other.underInference), + asLowered: conjoinNullAnswers(r.asLowered, other.asLowered)} +} + +// selected is the answer of the reading loweringContext's policy selects: +// underInference while it is on, asDeclared once it is off. +func (r nullAnswerReadings) selected(loweringContext lowering.Ctx) nullAnswer { + if loweringContext.NullableInference.Honours() { + return r.underInference + } + return r.asDeclared +} + +// admits reports whether the reference naming the schema holds a null as +// loweringContext's policy reads it. +func (r nullAnswerReadings) admits(loweringContext lowering.Ctx) bool { + return r.selected(loweringContext) == nullAdmittedByReference +} + +// mayAdmit reports whether the schema admits null as loweringContext's policy +// reads it, wherever the IR holds it, a variant of its union included. +func (r nullAnswerReadings) mayAdmit(loweringContext lowering.Ctx) bool { + return r.selected(loweringContext).admits() +} + +// forbids reports whether the reading loweringContext's policy selects keeps +// null out. +func (r nullAnswerReadings) forbids(loweringContext lowering.Ctx) bool { + return r.selected(loweringContext) == nullForbidden +} + +// ref returns a reference to target that holds a null as loweringContext's +// policy reads it (nullRef). +func (r nullAnswerReadings) ref(loweringContext lowering.Ctx, target ir.TypeID) ir.TypeRef { + return nullRef(loweringContext, target, r.declaredOnReference(loweringContext), r.underInference == nullAdmittedByReference) +} + +// declaredOnReference reports whether the reference naming the schema holds a +// declared null, as the policy's lowering places it while the policy is on +// (asLowered), so only a null the policy alone reads in marks it inferred. +func (r nullAnswerReadings) declaredOnReference(loweringContext lowering.Ctx) bool { + if loweringContext.NullableInference.Honours() { + return r.asLowered == nullAdmittedByReference + } + return r.asDeclared == nullAdmittedByReference +} + +// nullRef returns a reference to target that admits null where the reading +// loweringContext's policy selects does: lenient while it is on, declared once +// it is off. Where only lenient admits null, the reference names the policy's +// heuristic in Inferred, so the declared bit is still Nullable with Inferred +// empty. +func nullRef(loweringContext lowering.Ctx, target ir.TypeID, declared, lenient bool) ir.TypeRef { + if !loweringContext.NullableInference.Honours() { + return ir.TypeRef{Target: target, Nullable: declared} + } + out := ir.TypeRef{Target: target, Nullable: lenient} + if lenient && !declared { + out.Inferred = lowering.NullableInferenceHeuristic + } + return out +} + +// schemaAdmitsNull reports whether the reference naming schema holds a null as +// loweringContext's policy reads it. Every site computing a Nullable bit reads +// it so (nullAnswerReadingsOf), and none disagrees about one schema. It reports +// nothing; a position takes its own bit from schemaNullRef. +func schemaAdmitsNull(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(schema)).admits(loweringContext) +} + +// schemaNullRef returns a reference to target from schema, written at +// pointer, carrying what schema says about null, and reports each null the +// policy reads in where schema writes it (nullFindings). +func schemaNullRef(loweringContext lowering.Ctx, target ir.TypeID, schema *statement.Schema, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { + return refNullRef(loweringContext, target, loweringContext.Statements().Read(schema), pointer) +} + +// refNullRef is schemaNullRef for the statement schemaStatement, a $ref usage +// among them, written at pointer. +func refNullRef(loweringContext lowering.Ctx, target ir.TypeID, schemaStatement *statement.Statement, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { + ref := nullAnswerReadingsOf(loweringContext, schemaStatement).ref(loweringContext, target) + return ref, append(nullFindings(loweringContext, schemaStatement, pointer), nullBoundFindings(loweringContext, schemaStatement, pointer)...) +} + +// nullBoundFindings is the error schemaStatement draws where its cycle's +// fixpoint passed fixpointReadLimit or its union reading was asked inside +// another's (settleUnionNull): neither can happen, so its null is the +// compiler's fault, not the source's. +func nullBoundFindings(loweringContext lowering.Ctx, schemaStatement *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { + store := nullAnswerMemoOf(loweringContext) + switch { + case store.overran[schemaStatement]: + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, + "the null this schema admits was read past the bound its cycle's fixpoint is held to, which no cycle reaches")} + case store.askedDuringUnionReading[schemaStatement]: + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, + "the null this schema admits was read inside another schema's union reading, which reads no schema unsettled")} + default: + return nil + } +} + +// definesNullableIn reports whether the dialect the schemas of document doc +// are read in defines the nullable keyword. +func definesNullableIn(loweringContext lowering.Ctx, doc reftable.DocID) bool { + return loweringContext.Rules().In(doc).Defines("nullable") +} + +// definesNullableFor reports whether the dialect of the document the bindings +// place schema in, else loweringContext's own, defines nullable. +func definesNullableFor(loweringContext lowering.Ctx, schema *statement.Schema) bool { + at, ok := siteOf(schema) + if !ok { + return loweringContext.SchemaRules().Defines("nullable") + } + return definesNullableIn(loweringContext, at.Doc) +} + +// typedNull is what schema's type, const and enum say of null under each +// reading. Only the declared reading adds a `nullable: true` to the type +// (declaredTypeAnswer): the policy's widening is read apart (ownNull). +func typedNull(loweringContext lowering.Ctx, schema *statement.Schema) nullAnswerReadings { + constant, enum := constNullAnswer(schema), enumNullAnswer(schema) + declared := foldNullAnswers(declaredTypeAnswer(schema, definesNullableFor(loweringContext, schema)), constant, enum) + return nullAnswerReadings{asDeclared: declared, underInference: foldNullAnswers(typeNullAnswer(schema), constant, enum), asLowered: declared} +} + +// declaredTypeAnswer is typeNullAnswer as a dialect defining nullable where +// nullable says reads a `nullable: true` beside the type. Where it defines the +// keyword, as 3.0 does, it adds null to a type written in the same Schema +// Object, beside a $ref as anywhere, as `type: [T, "null"]` spells it from 3.1, +// so the result then conjoins like any type. Where it does not, nullable says +// nothing. +func declaredTypeAnswer(schema *statement.Schema, nullable bool) nullAnswer { + nullAnswerValue := typeNullAnswer(schema) + if nullAnswerValue == nullForbidden && nullable && nullableTrue(schema) { + return nullAdmittedByReference + } + return nullAnswerValue +} + +// foldNullAnswers conjoins keyword answers (conjoinNullAnswers): a schema no +// keyword speaks for says nothing, which is not the same answer as forbidding, +// since a conjunct saying nothing must not veto a sibling that admits. +func foldNullAnswers(answers ...nullAnswer) nullAnswer { + out := nullSaysNothing + for _, answer := range answers { + out = conjoinNullAnswers(out, answer) + } + return out +} + +// typeNullAnswer reads the `type` keyword. A schema writing none constrains no +// instance kind at all, so it says nothing rather than forbidding. +func typeNullAnswer(schema *statement.Schema) nullAnswer { + if !writesType(schema) { + return nullSaysNothing + } + if slices.Contains(schema.Types(), statement.KindNull) { + return nullAdmittedByReference + } + return nullForbidden +} + +// constNullAnswer reads `const`, which fixes the value space to one member. +func constNullAnswer(schema *statement.Schema) nullAnswer { + node := schema.Const() + if node == nil { + return nullSaysNothing + } + if isNullValue(node) { + return nullAdmittedByReference + } + return nullForbidden +} + +// enumNullAnswer reads `enum`, which fixes the value space to its members: the +// position admits null exactly when a member is null. +// +// An empty enum says nothing rather than forbidding. It lists no member at all, +// so reading it as "no null member" would let a degenerate keyword strip a +// co-declared type array's null; what an empty enum lowers to is GitHub #278's +// question, and this rule leaves it open. +func enumNullAnswer(schema *statement.Schema) nullAnswer { + nodes := schema.Enum() + if len(nodes) == 0 { + return nullSaysNothing + } + if slices.ContainsFunc(nodes, isNullValue) { + return nullAdmittedByReference + } + return nullForbidden +} + +// isNullValue reports whether an enum member or const node is the null literal, +// read through the same converter enumEntries drops a member by. Both must +// recognize one spelling: the null this predicate lifts onto a reference is +// exactly the member that lowering strips. +func isNullValue(node *yaml.Node) bool { + val, err := value.FromNode(node) + return err == nil && val.Kind == ir.ValueNull +} + +// NullAlone reports whether schema admits null and no other value by its own +// keywords, as loweringContext's policy reads null +// (docs/compilers/openapi.md#null-alone). Such a schema lowers to an Enum with +// no member behind a nullable reference, and a union branch written so is the +// union's null. +func NullAlone(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return leavesOnlyNull(loweringContext, schema) && schemaAdmitsNull(loweringContext, schema) +} + +// leavesOnlyNull reports whether the keywords schema itself writes leave it no +// value but null, whether or not they admit it. A $ref, allOf, oneOf, anyOf or +// $dynamicRef admits what other schemas do, so a schema writing one never does. +func leavesOnlyNull(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return stated(schema) && !refWritten(schema) && !writesConjuncts(schema) && !declaresUnion(schema) && !declaresDynamicRef(schema) && + writesNullAlone(loweringContext, schema) +} + +// writesNullAlone reports whether schema's type, enum and const leave it no +// value but null. A type naming null alone decides over an enum beside it; an +// enum past the member budget lowers to the top type (lowerEnum), and an empty +// enum is never null alone. +func writesNullAlone(loweringContext lowering.Ctx, schema *statement.Schema) bool { + members := schema.Enum() + switch { + case enumWritten(schema) && len(members) == 0: + return false + case typeOfNullAlone(schema): + return true + case enumWritten(schema): + return loweringContext.Limits.MaxEnumMembers.Admits(len(members)) && + !slices.ContainsFunc(members, func(node *yaml.Node) bool { return !isNullValue(node) }) + default: + return schema.Const() != nil && isNullValue(schema.Const()) + } +} + +// typeOfNullAlone reports whether schema writes a type naming null alone, which +// admits no value but null whatever an enum beside it lists +// (docs/compilers/openapi.md#null-alone) and lowers to the value set of null +// (lowerNullAlone). +func typeOfNullAlone(schema *statement.Schema) bool { + return writesType(schema) && len(effectiveTypes(schema)) == 0 +} + +// nullableAt is the pointer of the `nullable` keyword of the schema written at +// pointer. +func nullableAt(pointer jsontext.Pointer) jsontext.Pointer { + return pointer + ids.Ptr("nullable") +} diff --git a/compilers/openapi/internal/schema/nullverdictstore.go b/compilers/openapi/internal/schema/nullverdictstore.go new file mode 100644 index 000000000..9cbd330ab --- /dev/null +++ b/compilers/openapi/internal/schema/nullverdictstore.go @@ -0,0 +1,360 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// nullAnswerMemo is the run's null answers by statement (nullAnswerReadingsOf). +// reads counts the readings settling them, and aliasReads those landing on +// another reference, which only the tests read. +type nullAnswerMemo struct { + of map[*statement.Statement]nullAnswerReadings + reads int + aliasReads int + // overran holds the members of a cycle whose fixpoint passed its bound + // (fixpointReadLimit), which no component can, so their answers are not + // to be trusted (nullBoundFindings). + overran map[*statement.Statement]bool + // readingUnionNull marks a union reading under way for an answer + // (settleUnionNull), which reads only answers already settled; + // askedDuringUnionReading holds each statement whose reading was asked + // inside one, which none is, so its answer is not to be trusted either. + readingUnionNull bool + askedDuringUnionReading map[*statement.Statement]bool +} + +// nullAnswerMemoKey keys the run's nullAnswerMemo. +type nullAnswerMemoKey struct{} + +// nullAnswerMemoOf returns the run's nullAnswerMemo, made on the first ask. +func nullAnswerMemoOf(loweringContext lowering.Ctx) *nullAnswerMemo { + return lowering.ReadOncePerRun(loweringContext, nullAnswerMemoKey{}, func() *nullAnswerMemo { + return &nullAnswerMemo{of: map[*statement.Statement]nullAnswerReadings{}, overran: map[*statement.Statement]bool{}, + askedDuringUnionReading: map[*statement.Statement]bool{}} + }) +} + +// nullAnswerReadingsOf returns what schemaStatement says of null, settled once +// a run in dependency order (walkComponents) from its own keywords and the +// answers of the schemas it reads for null, so it is the same whichever site +// asks first. No depth cuts it: the walk recurses only through a union +// reading, once (settleUnionNull). +func nullAnswerReadingsOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) nullAnswerReadings { + if schemaStatement == nil { + return nullAnswerReadingsAlike(nullSaysNothing) + } + store := nullAnswerMemoOf(loweringContext) + if answer, ok := store.of[schemaStatement]; ok { + return answer + } + walkComponents(schemaStatement, + func(next *statement.Statement) []*statement.Statement { return nullReadsOf(loweringContext, next) }, + func(next *statement.Statement) bool { _, settled := store.of[next]; return settled }, + func(component closedComponent[*statement.Statement]) { + settleNullComponent(loweringContext, store, component) + }) + return store.of[schemaStatement] +} + +// nullConjuncts returns the conjuncts of schemaStatement's conjunction: itself +// where it writes a reference alone, else its own keywords then its flattened +// entries, a reference beside its keywords first (statement.Statement). +func nullConjuncts(schemaStatement *statement.Statement) []statement.AllOfConjunct { + own := statement.AllOfConjunct{Schema: schemaStatement.Schema} + if schemaStatement.Ref != nil { + return []statement.AllOfConjunct{own} + } + return slices.Concat([]statement.AllOfConjunct{own}, schemaStatement.Entries) +} + +// nullTargetOf returns the statement the reference schema writes lands on at +// its first hop (declaredOf), nil where the chain it starts resolves to no +// schema, which says nothing of null. +func nullTargetOf(loweringContext lowering.Ctx, schema *statement.Schema) *statement.Statement { + schemaStatement := loweringContext.Statements().Read(schema) + if schemaStatement.Ref == nil || !schemaStatement.Ref.Bound || schemaStatement.Ref.Entry.Chain.Status != reftable.Resolved { + return nil + } + target, _ := declaredOf(loweringContext, schemaStatement) + return target +} + +// nullExpansionOf returns the statement the $dynamicRef or $recursiveRef +// schemaStatement writes expands to (dynamicExpansionOf), read for null as a +// $ref to it is (GitHub #1967), and nil where schemaStatement expands none. +func nullExpansionOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) *statement.Statement { + at, ok := dynamicExpansionOf(loweringContext, schemaStatement) + if !ok { + return nil + } + return loweringContext.Statements().At(at) +} + +// nullReadsOf returns the statements readNull reads for schemaStatement's +// answer, in its order. The walk's edges are the reading's own, so the union +// reading (settleUnionNull) finds each it reads settled. +func nullReadsOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) []*statement.Statement { + var out []*statement.Statement + readNull(loweringContext, schemaStatement, nullSkip{}, func(read *statement.Statement) nullAnswerReadings { + out = append(out, read) + return nullAnswerReadingsAlike(nullSaysNothing) + }) + return out +} + +// settleNullComponent records the answer of each member of component, which +// nullAnswerReadingsOf's walk closed, then reads each member's union over the +// settled answers. +func settleNullComponent(loweringContext lowering.Ctx, store *nullAnswerMemo, component closedComponent[*statement.Statement]) { + if component.cyclic { + settleNullCycle(loweringContext, store, component.members) + } else { + root := component.members[0] + store.of[root] = readNullCounted(loweringContext, store, root, store.settled) + } + for _, schemaStatement := range component.members { + settleUnionNull(loweringContext, store, schemaStatement) + } +} + +// settleUnionNull reads into schemaStatement's settled answer what the union +// its conjunction chooses says of null beyond its branches': a filtered value +// set as its members' flat enum, a lifted null branch +// (docs/compilers/openapi.md#union-beside-structure), a oneOf's refusal +// (docs/compilers/openapi.md#union-null-only). It reads only settled answers, +// so one asked inside another union reading is recorded unlifted. +func settleUnionNull(loweringContext lowering.Ctx, store *nullAnswerMemo, schemaStatement *statement.Statement) { + answer := store.of[schemaStatement] + lifts := loweringContext.NullableInference.Honours() && answer.underInference != nullAdmittedByReference && holdsNullBranch(loweringContext, schemaStatement) + refuses := answer != nullAnswerReadingsAlike(nullForbidden) && holdsOneOf(schemaStatement) + if !lifts && !refuses && !holdsValueSetUnion(loweringContext, schemaStatement) { + return + } + if store.readingUnionNull { + store.askedDuringUnionReading[schemaStatement] = true + return + } + store.readingUnionNull = true + union := readLoweredUnion(loweringContext, schemaStatement.Schema) + store.readingUnionNull = false + _, liftsBranch := union.liftedBranch() + switch { + case union.besideRest == unionMembersFilteredByRest: + answer = filteredMembersNull(loweringContext, schemaStatement, union.admittedMembers.members, store.settled) + case lifts && liftsBranch: + answer.underInference = nullAdmittedByReference + case refuses && union.refusesNull: + answer = nullAnswerReadingsAlike(nullForbidden) + if readNull(loweringContext, schemaStatement, nullSkip{}, store.settled).widens() { + answer.underInference = nullAdmittedByReference + } + } + store.of[schemaStatement] = answer +} + +// filteredMembersNull is what schemaStatement, whose union of value sets its +// body filters (unionMembersFilteredByRest), says of null: what the body says +// beside a flat enum of members, those it admits, read as that enum's schema +// is (nullConjunctionRead.answer). +func filteredMembersNull(loweringContext lowering.Ctx, schemaStatement *statement.Statement, members []unionMember, answerOf func(*statement.Statement) nullAnswerReadings) nullAnswerReadings { + loweredUnion, _ := readConjunction(loweringContext, schemaStatement.Schema).loweredUnion() + read := readNull(loweringContext, schemaStatement, nullSkip{schema: loweredUnion.holder, keyword: loweredUnion.keyword}, answerOf) + listed := nullAnswerReadingsAlike(membersNull(members)) + read.total, read.own = read.total.conjoin(listed), read.own.conjoin(listed) + return read.answer() +} + +// membersNull is what an enum listing members says of null, as enumNullAnswer +// reads one. +func membersNull(members []unionMember) nullAnswer { + switch { + case len(members) == 0: + return nullSaysNothing + case slices.ContainsFunc(members, func(member unionMember) bool { return member.value.Kind == ir.ValueNull }): + return nullAdmittedByReference + default: + return nullForbidden + } +} + +// holdsValueSetUnion reports whether a conjunct of schemaStatement but a +// reference writes a union of value sets, the one kind a body meets as a set. +func holdsValueSetUnion(loweringContext lowering.Ctx, schemaStatement *statement.Statement) bool { + if schemaStatement.Truth != statement.Stated { + return false + } + return slices.ContainsFunc(nullConjuncts(schemaStatement), func(conjunctValue statement.AllOfConjunct) bool { + if conjunctValue.Ref != nil || !stated(conjunctValue.Schema) { + return false + } + choice := conjunctValue.ChoiceKeywords() + return len(choice.OneOf) > 0 && pureValueSets(loweringContext, choice.OneOf) || len(choice.AnyOf) > 0 && pureValueSets(loweringContext, choice.AnyOf) + }) +} + +// holdsOneOf reports whether a conjunct of schemaStatement's conjunction but a +// reference writes a oneOf of more than one branch, the one kind of union that +// refuses a null two of its branches leave in. +func holdsOneOf(schemaStatement *statement.Statement) bool { + return schemaStatement.Truth == statement.Stated && slices.ContainsFunc(nullConjuncts(schemaStatement), func(conjunctValue statement.AllOfConjunct) bool { + return conjunctValue.Ref == nil && stated(conjunctValue.Schema) && len(conjunctValue.ChoiceKeywords().OneOf) > 1 + }) +} + +// holdsNullBranch reports whether a conjunct of schemaStatement's conjunction +// but a reference writes a union a branch of which is written in place and +// leaves no value but null (leavesOnlyNull), the one kind of branch the policy +// lifts. +func holdsNullBranch(loweringContext lowering.Ctx, schemaStatement *statement.Statement) bool { + if schemaStatement.Truth != statement.Stated { + return false + } + return slices.ContainsFunc(nullConjuncts(schemaStatement), func(conjunctValue statement.AllOfConjunct) bool { + if conjunctValue.Ref != nil || !stated(conjunctValue.Schema) { + return false + } + choice := conjunctValue.ChoiceKeywords() + return slices.ContainsFunc(slices.Concat(choice.OneOf, choice.AnyOf), func(branch statement.Subschema) bool { + branchStatement := loweringContext.Statements().Subschema(branch) + return inlineBranch(branchStatement) && leavesOnlyNull(loweringContext, branchStatement.Schema) + }) + }) +} + +// settled is the answer of schemaStatement, which the walk settled before +// reading what reads it. +func (n *nullAnswerMemo) settled(schemaStatement *statement.Statement) nullAnswerReadings { + return n.of[schemaStatement] +} + +// readNullCounted is readNull's answer on schemaStatement over answerOf, +// counted in store. +func readNullCounted(loweringContext lowering.Ctx, store *nullAnswerMemo, schemaStatement *statement.Statement, answerOf func(*statement.Statement) nullAnswerReadings) nullAnswerReadings { + store.reads++ + read := readNull(loweringContext, schemaStatement, nullSkip{}, answerOf) + if read.landsOnReference { + store.aliasReads++ + } + return read.answer() +} + +// settleNullCycle records the answer of each of members, a strongly connected +// component, as two least fixpoints over answers that only grow: first which +// members forbid null, then how far each admits it, those forbidding it +// staying so. Re-reading only the readers of a changed member settles the +// component in time linear in its edges, the same wherever the walk entered it. +func settleNullCycle(loweringContext lowering.Ctx, store *nullAnswerMemo, members []*statement.Statement) { + cycle := newNullCycle(loweringContext, members) + limit := cycle.fixpointReadLimit() + forbidden := cycle.fixpoint(loweringContext, store, limit, func(int) nullAnswerReadings { return nullAnswerReadingsAlike(nullSaysNothing) }, keepingForbidden) + admitted := cycle.fixpoint(loweringContext, store, limit, func(i int) nullAnswerReadings { return keepingForbidden(forbidden[i]) }, + func(read nullAnswerReadings) nullAnswerReadings { return read }) + for i, schemaStatement := range members { + store.of[schemaStatement] = admitted[i] + } +} + +// nullCycle is a component being settled: its members, their places, and the +// members reading each. +type nullCycle struct { + members []*statement.Statement + place map[*statement.Statement]int + readers [][]int +} + +// newNullCycle indexes members and, for each, the members that read it. +func newNullCycle(loweringContext lowering.Ctx, members []*statement.Statement) nullCycle { + cycle := nullCycle{members: members, place: make(map[*statement.Statement]int, len(members)), readers: make([][]int, len(members))} + for i, schemaStatement := range members { + cycle.place[schemaStatement] = i + } + for i, schemaStatement := range members { + for _, edge := range nullReadsOf(loweringContext, schemaStatement) { + if at, in := cycle.place[edge]; in && !slices.Contains(cycle.readers[at], i) { + cycle.readers[at] = append(cycle.readers[at], i) + } + } + } + return cycle +} + +// nullAnswerReadingsHeight is how often one member's answer changes in a +// fixpoint at most: each of a reading's three answers only grows, through the +// four values an answer takes, three steps each. +const nullAnswerReadingsHeight = 9 + +// fixpointReadLimit is the most reads one fixpoint over c makes: each member +// once, and once per edge for each of at most nullAnswerReadingsHeight changes. +func (c nullCycle) fixpointReadLimit() int { + edges := 0 + for _, readers := range c.readers { + edges += len(readers) + } + return len(c.members) + nullAnswerReadingsHeight*edges +} + +// keepingForbidden is read with each reading kept where it forbids null and +// saying nothing otherwise: the first fixpoint's answer. +func keepingForbidden(read nullAnswerReadings) nullAnswerReadings { + return nullAnswerReadings{asDeclared: keepForbidden(read.asDeclared), underInference: keepForbidden(read.underInference), asLowered: keepForbidden(read.asLowered)} +} + +// keepForbidden is answer where it forbids null, and says nothing otherwise. +func keepForbidden(answer nullAnswer) nullAnswer { + if answer == nullForbidden { + return nullForbidden + } + return nullSaysNothing +} + +// fixpoint returns the members' least fixpoint of answer over readNull, each +// starting at start and re-read where one it reads changed. The second +// fixpoint starts the members the first found forbidding null there, so every +// answer only grows. It reads limit times at most (fixpointReadLimit), which +// no component reaches; one that would is recorded as overrun. +func (c nullCycle) fixpoint(loweringContext lowering.Ctx, store *nullAnswerMemo, limit int, start func(int) nullAnswerReadings, + answer func(nullAnswerReadings) nullAnswerReadings, +) []nullAnswerReadings { + answers := make([]nullAnswerReadings, len(c.members)) + pending := make([]bool, len(c.members)) + work := make([]int, 0, len(c.members)) + for i := range c.members { + answers[i], pending[i] = start(i), true + work = append(work, i) + } + answerOf := func(schemaStatement *statement.Statement) nullAnswerReadings { + if at, in := c.place[schemaStatement]; in { + return answers[at] + } + return store.of[schemaStatement] + } + for reads := 0; len(work) > 0; reads++ { + if reads == limit { + for _, schemaStatement := range c.members { + store.overran[schemaStatement] = true + } + break + } + i := work[len(work)-1] + work, pending[i] = work[:len(work)-1], false + next := answer(readNullCounted(loweringContext, store, c.members[i], answerOf)) + if next == answers[i] { + continue + } + answers[i] = next + for _, reader := range c.readers[i] { + if !pending[reader] { + pending[reader], work = true, append(work, reader) + } + } + } + return answers +} diff --git a/compilers/openapi/internal/schema/number_text_beside_test.go b/compilers/openapi/internal/schema/number_text_beside_test.go index 938b27f31..eb72586ea 100644 --- a/compilers/openapi/internal/schema/number_text_beside_test.go +++ b/compilers/openapi/internal/schema/number_text_beside_test.go @@ -4,11 +4,13 @@ package schema_test import ( + "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" "github.com/dexpace/morphic/ir" ) @@ -24,7 +26,7 @@ func TestScalar_ABoundBesideANumberAsTextPrincipalIsKeptAsItsOwn(t *testing.T) { " B: {allOf: [{type: string, format: double}], minimum: 31, pattern: '^[0-9]+$', minItems: 2}\n")) openapitest.RequireNoErrorDiags(t, diags) sc, ok := typeByName(doc, "B").(*ir.Scalar) - require.True(t, ok, "the principal's Scalar stands at the position") + require.True(t, ok, "the principal's Scalar sits at the position") assert.Nil(t, sc.Constraints) for keyword, want := range map[string]ir.UnmodeledReason{ "openapi:minimum": ir.ReasonNoIRHome, "openapi:pattern": ir.ReasonNoIRHome, "openapi:minItems": ir.ReasonDegradedLowering, @@ -35,3 +37,137 @@ func TestScalar_ABoundBesideANumberAsTextPrincipalIsKeptAsItsOwn(t *testing.T) { } } } + +// TestScalar_ConjunctsWritingATextVariantsBoundIntersect pins the value bounds +// a type list's variant carrying a number as text takes of the list and the +// conjuncts beside it: the conjuncts of a bound intersect, and the variant +// keeps the writing of the value they intersect in, the list's or a conjunct's; +// conjuncts intersecting in no value one of them writes, two steps, keep that value; +// conjuncts intersecting in none, two patterns, are kept on the Union as entries, +// the variant keeping none. A 3.1 numeric exclusive bound intersects apart from +// its plain twin, and a draft-04 bound with its boolean modifier. +func TestScalar_ConjunctsWritingATextVariantsBoundIntersect(t *testing.T) { + t.Parallel() + const list = "{type: [string, boolean], format: int64" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " Voice: {allOf: ["+list+"}, {minimum: 31}, {minimum: 40}]}\n"+ + " List: {allOf: ["+list+", minimum: 40}, {minimum: 31}]}\n"+ + " Exclusive: {allOf: ["+list+"}, {minimum: 5, exclusiveMinimum: 31}, {exclusiveMinimum: 40}]}\n"+ + " Draft: {$schema: 'http://json-schema.org/draft-04/schema#', allOf: ["+list+ + "}, {minimum: 31}, {minimum: 40}]}\n"+ + " Steps: {allOf: ["+list+"}, {multipleOf: 2}, {multipleOf: 3}]}\n"+ + " Patterns: {allOf: ["+list+"}, {pattern: a}, {pattern: b}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + for name, want := range map[string]map[string]string{ + "Voice": {"openapi:minimum": "40"}, + "List": {"openapi:minimum": "40"}, + "Exclusive": {"openapi:minimum": "5", "openapi:exclusiveMinimum": "40"}, + "Draft": {"openapi:minimum": "40"}, + "Steps": {"openapi:multipleOf": "6"}, + "Patterns": {}, + } { + variant, ok := doc.Types[ir.TypeID("type/anonymous/components/schemas/"+name+"/type/0")].(*ir.Scalar) + require.True(t, ok, name) + got := map[string]string{} + for key, entry := range variant.Unmodeled { + got[key] = string(entry.Value) + } + assert.Equal(t, want, got, "%s: the variant keeps the value its conjuncts intersect in", name) + union := typeByName(doc, name) + require.NotNil(t, union, name) + var entries []string + for key := range union.Common().Unmodeled { + if strings.HasPrefix(key, "openapi:allOf/") { + entries = append(entries, key) + } + } + if len(want) == 0 { + assert.Len(t, entries, 2, "%s: the conjuncts stay on the Union", name) + } else { + assert.Empty(t, entries, "%s: no conjunct stays on the Union", name) + } + } +} + +// TestScalar_StepsOnANumberAsTextKeepTheirCommonMultiple pins two steps on a +// Scalar carrying a number as text, an inline principal's and a position's +// own, whose common multiple neither writes: the Scalar keeps that multiple +// under its own key, no_ir_home, its report naming it, and no conjunct apart. +func TestScalar_StepsOnANumberAsTextKeepTheirCommonMultiple(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " Principal: {allOf: [{type: string, format: int64}, {multipleOf: 2}, {multipleOf: 3}]}\n"+ + " Own: {type: string, format: int64, multipleOf: 2, allOf: [{multipleOf: 3}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Principal", "Own"} { + sc, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, name) + require.Len(t, sc.Unmodeled, 1, "%s keeps no conjunct apart", name) + entry, kept := sc.Unmodeled["openapi:multipleOf"] + require.True(t, kept, name) + assert.Equal(t, "6", string(entry.Value), name) + assert.Equal(t, ir.ReasonNoIRHome, entry.Reason, name) + message := openapitest.DiagMessageAt(t, diags, diag.UnhomedConstruct, ir.SeverityInfo, string(entry.Provenance.Pointer)) + assert.Contains(t, message, "meet in 6", name) + } +} + +// TestScalar_StepsPastAWholePrincipalKeepEachConjunct pins two steps on a +// number as text intersecting in a multiple neither writes, beside an inline +// principal its conjuncts keep whole: the multiple, added as a pending keep on +// the principal, is held whole with it, so no conjunct's step is dropped. The +// principal's stays in its whole entry, the position's is kept under its own +// key, and each entry's under its entry key with the report that another +// conjunct writes it otherwise. +func TestScalar_StepsPastAWholePrincipalKeepEachConjunct(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " Beside: {allOf: [{type: string, format: int64, multipleOf: 2, x-k: 1}], multipleOf: 3, x-k: 2}\n"+ + " Entries: {allOf: [{type: string, format: int64, x-k: 1}, {multipleOf: 2}, {multipleOf: 3}], x-k: 2}\n")) + openapitest.RequireNoErrorDiags(t, diags) + held := func(name string) map[string]string { + out := map[string]string{} + for key, entry := range typeByName(doc, name).Common().Unmodeled { + out[key] = string(entry.Value) + } + return out + } + beside := held("Beside") + assert.JSONEq(t, `{"type":"string","format":"int64","multipleOf":2,"x-k":1}`, beside["openapi:allOf/0"], "the principal's in its whole entry") + assert.Equal(t, "3", beside["openapi:multipleOf"], "the position's under its own key") + entries := held("Entries") + assert.JSONEq(t, `{"multipleOf":2}`, entries["openapi:allOf/1"]) + assert.JSONEq(t, `{"multipleOf":3}`, entries["openapi:allOf/2"]) + for _, at := range []string{"/components/schemas/Entries/allOf/1", "/components/schemas/Entries/allOf/2"} { + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, at), "keeps otherwise", at) + } +} + +// TestScalar_AContentEncodingOnAnotherConjunctLeavesNoNumberAsText pins a +// number written as text whose contentEncoding another conjunct writes: the +// string is that encoding's text, so the Scalar is over string under the +// encoding, holding a length as a string's bound, the format kept where it is +// written and the contentEncoding nowhere else, as written flat. Where the +// contentEncoding names the number's own encoding the text stays the number. +func TestScalar_AContentEncodingOnAnotherConjunctLeavesNoNumberAsText(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " Encoded: {allOf: [{type: string, format: int64, maxLength: 3}, {contentEncoding: base64}]}\n"+ + " Restated: {allOf: [{type: string, format: int64, maxLength: 3}, {contentEncoding: string}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + encoded, ok := typeByName(doc, "Encoded").(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, encoded.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), encoded.Base.Target) + assert.Equal(t, &ir.Encoding{Name: "base64"}, encoded.Encoding) + require.NotNil(t, encoded.Constraints) + assert.Equal(t, new(int64(3)), encoded.Constraints.MaxLength, "a length bounds the text") + require.Len(t, encoded.Unmodeled, 1) + assert.Equal(t, ir.ReasonNoIRHome, encoded.Unmodeled["openapi:format"].Reason) + assert.Equal(t, "/components/schemas/Encoded/allOf/0/format", string(encoded.Unmodeled["openapi:format"].Provenance.Pointer)) + restated, ok := typeByName(doc, "Restated").(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, restated.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInt64), restated.Base.Target, "the text stays the number") + assert.Nil(t, restated.Constraints, "a number as text holds no length") +} diff --git a/compilers/openapi/internal/schema/onerefrest.go b/compilers/openapi/internal/schema/onerefrest.go new file mode 100644 index 000000000..10e1ed767 --- /dev/null +++ b/compilers/openapi/internal/schema/onerefrest.go @@ -0,0 +1,179 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// oneRefRest is the rest of a position's conjunction where it holds one $ref, +// to a scalar no enum is (oneRefRestOf): root, what that chain of $refs ends +// on, and unionEntryRel, the Rel of the inline entry writing the union the +// conjunction lowers, empty where the position writes it. +type oneRefRest struct { + root scalarRoot + unionEntryRel jsontext.Pointer +} + +// oneRefRestOf returns the body of schema's conjunction where it holds one +// $ref, whose chain ends within its bounds on a scalar no enum is +// (scalarChainOf), beside it only a type naming that kind and value bounds, and +// one union it lowers, passing over none. Each live branch of that union is the +// allOf of the body and itself (refConjoinedVariant). +func oneRefRestOf(loweringContext lowering.Ctx, schema *statement.Schema) (oneRefRest, bool) { + conjunctionRead := readConjunction(loweringContext, schema) + loweredUnion, ok := conjunctionRead.loweredUnion() + if !ok || len(conjunctionRead.passed()) > 0 { + return oneRefRest{}, false + } + holder := loweredUnion.rel + if loweredUnion.holder == schema { + holder = "" + } + ref, one := oneRefEntry(loweringContext, schema) + if !one { + return oneRefRest{}, false + } + chain, within := scalarChainOf(loweringContext, ref) + if !within || !chain.ok || chain.root.enum || slices.ContainsFunc(readConjunction(loweringContext, schema).written, func(written *statement.Schema) bool { + return !writesOnlyBound(written, chain.root.jsonType) + }) { + return oneRefRest{}, false + } + return oneRefRest{root: chain.root, unionEntryRel: holder}, true +} + +// oneRefEntry returns the one $ref among the conjuncts of schema's flattened +// allOf, its own $ref among them, and false where it writes none or several, or +// nests one past statement.MaxFlattenDepth. +func oneRefEntry(loweringContext lowering.Ctx, schema *statement.Schema) (*statement.Statement, bool) { + var ref *statement.Statement + for _, entry := range loweringContext.Statements().Read(schema).Entries { + switch { + case !stated(entry.Schema): + case entry.Ref != nil && ref != nil, entry.Capped: + return nil, false + case entry.Ref != nil: + ref = loweringContext.Statements().Read(entry.Schema) + } + } + return ref, ref != nil +} + +// writesOnlyBound reports whether schema writes, of a shape, only a type +// naming kind, any one where kind is empty, and value bounds, beside keys +// saying nothing of a value, a discriminator and its own allOf and unions. +func writesOnlyBound(schema *statement.Schema, kind statement.JSONSchemaTypeName) bool { + return !slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { + switch { + case !bodyKeyword(schema, key): + return false + case key.Name == "type": + types := schema.Types() + return len(types) != 1 || kind != "" && types[0] != kind + default: + return !slices.Contains(valueConstraintKeywords, key.Name) + } + }) +} + +// bodyKeyword reports whether key, which schema, a body, writes beside its +// unions, says what each variant conjoins: none saying nothing of a value +// (keySaysNothing), a discriminator, an allOf or a union, which the +// position's own node keeps. +func bodyKeyword(schema *statement.Schema, key statement.Key) bool { + return !isUnionKeyword(key.Name) && key.Name != "allOf" && key.Name != "discriminator" && !keySaysNothing(schema, key) +} + +// writesBesideUnion reports whether schema writes beside its unions, its allOf +// and its $ref a keyword saying anything of a value but a discriminator +// (bodyKeyword). +func writesBesideUnion(schema *statement.Schema) bool { + return slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { return bodyKeyword(schema, key) }) +} + +// notBodyKeywords returns the keys schema and its inline entries write that no +// variant of the union beside its body conjoins (bodyKeyword): its unions, +// their notes and the rest the position's own node keeps. +func notBodyKeywords(loweringContext lowering.Ctx, schema *statement.Schema) []string { + var out []string + for _, conjunctSchema := range inlineConjuncts(loweringContext, schema) { + for _, key := range conjunctSchema.Keys { + if !bodyKeyword(conjunctSchema, key) && key.Name != "allOf" && !slices.Contains(out, key.Name) { + out = append(out, key.Name) + } + } + } + return out +} + +// conjoinedOneRefRest returns the body of schema's conjunction where the union +// it chooses lowers as the Union of its live branches, each conjoined with a +// body holding one $ref (oneRefRestOf), and false otherwise. +func conjoinedOneRefRest(loweringContext lowering.Ctx, schema *statement.Schema) (oneRefRest, bool) { + if readLoweredUnion(loweringContext, schema).besideRest != unionConjoined { + return oneRefRest{}, false + } + return oneRefRestOf(loweringContext, schema) +} + +// oneRefRestBounds returns the value bounds of rest's kind that position, +// written at at, and its inline entries write beside its $ref: the Union holds +// them, as beside a body naming its type inline, but those a variant's root +// marks, which it keeps where each is written (conjoinedUnionRoot). It returns +// what it read of reader, the position or the inline principal taking its place. +func oneRefRestBounds(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, reader, position *statement.Schema, at jsontext.Pointer, rest oneRefRest, +) (*ir.Constraints, keySet, annotation.KeptReports) { + var entries []annotation.FlattenedAllOfEntry + for _, entry := range loweringContext.Statements().Read(position).Entries { + if entry.Ref == nil && stated(entry.Schema) { + entries = append(entries, flattenedEntryAt(loweringContext, entry.Schema, at+entry.Rel)) + } + } + takes := kindsOfTypeName(rest.root.jsonType) + root, _ := conjoinedUnionRoot(loweringContext, position) + homes := boundHomes{value: takes}.heldOver(root, takes) + cons, kept, reports := boundsKept(loweringContext, *unmodeled, position, entries, at, homes.value) + *unmodeled = annotation.MergeUnmodeled(*unmodeled, kept) + reports = append(reports, textBoundsKept(loweringContext, unmodeled, position, writtenKept(position, homes.heldText), at, root)...) + for _, entry := range entries { + reports = append(reports, textBoundsKept(loweringContext, unmodeled, entry.Node, writtenKept(entry.Node, homes.heldText), entry.At, root)...) + } + return cons, nodeBoundsRead(reader, homes.value, cons, *unmodeled), reports +} + +// conjoinedEntry reports whether entry, of schema's allOf, is a conjunct of +// the body each variant of the union schema's conjunction chooses conjoins +// (refConjoinedVariant), so no refinement of schema keeps it: one but the +// entry writing that union. +func conjoinedEntry(loweringContext lowering.Ctx, schema *statement.Schema, entry allOfEntry) bool { + if _, conjoined := conjoinedOneRefRest(loweringContext, schema); !conjoined { + return false + } + loweredUnion, _ := readConjunction(loweringContext, schema).loweredUnion() + return entry.schema.Schema != loweredUnion.holder +} + +// refConjoinedVariant is the variant over branch, a live branch written at +// variantPointer, of a union beside body's one $ref (oneRefRestOf): the allOf of +// that $ref, the type beside it and branch +// (statement.MemoizingSchemaReader.Conjoined), lowered, its node minted at the +// branch's key (composedVariantKey). The body's notes and bounds stay the +// position's, which the Union holds. +func refConjoinedVariant(loweringContext lowering.Ctx, types *compile.Types, depth int, branch *statement.Statement, variantPointer jsontext.Pointer, + body composedBody, rest oneRefRest, +) (ir.TypeRef, []ir.Diagnostic) { + position := body.comp.pointer + conjunction := loweringContext.Statements().Conjoined(body.schema, slices.Concat(notBodyKeywords(loweringContext, body.schema), valueConstraintKeywords), rest.unionEntryRel, branch, + variantPointer[len(position):]) + minting := lowering.Minting(loweringContext, position, composedVariantKey(body, variantPointer), variantPointer) + return Ref(minting, types, depth, conjunction, position) +} diff --git a/compilers/openapi/internal/schema/onerefrest_test.go b/compilers/openapi/internal/schema/onerefrest_test.go new file mode 100644 index 000000000..e534dd49b --- /dev/null +++ b/compilers/openapi/internal/schema/onerefrest_test.go @@ -0,0 +1,226 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/v2" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// oneRefRestBranches are the branches the $ref-body rows write beside a body +// holding one $ref to B, a string: formats choosing a narrower primitive or +// none, bounds, the content vocabulary, $refs, one writing beside its $ref, +// and a branch restating B. +var oneRefRestBranches = []string{ + "{format: uuid, minLength: 2}", "{format: foo}", "{$ref: '#/components/schemas/U'}", "{$ref: '#/components/schemas/C'}", + "{$ref: '#/components/schemas/C', description: c}", "{$ref: '#/components/schemas/U', maxLength: 3}", "{format: byte}", + "{contentEncoding: base64}", "{format: email, contentEncoding: base64}", "{type: string}", +} + +// equivalentSpec writes, beside B, U and C, the position P, the body written +// with a union of oneRefRestBranches, and Twin, the allOf of equivalent, the +// body less its own bounds, and branch i. +func equivalentSpec(body, equivalent string) string { + src := ` B: {type: string, maxLength: 40} + U: {type: string, format: uuid} + C: {type: string, pattern: '^c'} + P: {` + body + `, oneOf: [` + for i, branch := range oneRefRestBranches { + if i > 0 { + src += ", " + } + src += branch + } + src += "]}\n" + for i, branch := range oneRefRestBranches { + src += " Twin" + string(rune('0'+i)) + ": {allOf: [{" + equivalent + "}, " + branch + "]}\n" + } + return src +} + +// nodeView is node as a variant and its twin compare: its JSON with where it +// sits, its name, its notes and where what it keeps is written left out. A +// bound kept beside a root of another text is read by its reason and keyword +// alone, whether kept under its keyword or under the entry writing it, since a +// variant and its twin write it at different places. +func nodeView(t *testing.T, node ir.TypeDef) map[string]any { + t.Helper() + require.NotNil(t, node) + raw, err := json.Marshal(node, json.Deterministic(true)) + require.NoError(t, err) + var view map[string]any + require.NoError(t, json.Unmarshal(raw, &view)) + for _, key := range []string{"id", "name", "provenance", "anonymous", "docs"} { + delete(view, key) + } + if kept, ok := view["unmodeled"].(map[string]any); ok { + var written []string + for key, entry := range kept { + fields := entry.(map[string]any) + delete(fields, "provenance") + if keyword, plain := strings.CutPrefix(key, "openapi:"); plain && slices.Contains([]string{"maxLength", "minLength", "pattern"}, keyword) { + fields["value"] = map[string]any{keyword: fields["value"]} + } else if !strings.Contains(key, "/") { + continue + } + encoded, err := json.Marshal(fields, json.Deterministic(true)) + require.NoError(t, err) + written = append(written, string(encoded)) + delete(kept, key) + } + slices.Sort(written) + view["keptWhereWritten"] = written + } + return view +} + +// useOf returns the target twin, a component's node, aliases where it holds +// nothing beside it, as a component's allOf naming one target lowers. +func useOf(equivalent ir.TypeDef) (ir.TypeID, bool) { + alias, isScalar := equivalent.(*ir.Scalar) + if !isScalar || alias.Base == nil || alias.Constraints != nil || alias.Encoding != nil || len(alias.Unmodeled) > 0 { + return "", false + } + return alias.Base.Target, true +} + +// TestUnionBeside_ARefBodyConjoinsEachBranchAsItsAllOf holds each variant of a +// union beside a body holding one $ref to a string to what the allOf of that +// $ref, a type written beside it, and its branch lowers to, written as a +// component: over a body that is the $ref alone, one writing a bound beside +// it, on an entry or the $ref's own object, and one writing its type. A +// variant whose allOf is a use of a shared target is that target. The Union +// keeps the body's length, which binds no uuid's or bytes' text, and holds +// none of B's bounds. +func TestUnionBeside_ARefBodyConjoinsEachBranchAsItsAllOf(t *testing.T) { + t.Parallel() + const ref = "$ref: '#/components/schemas/B'" + for _, row := range []struct{ body, equivalent string }{ + {"allOf: [{" + ref + "}]", "allOf: [{" + ref + "}]"}, + {"allOf: [{" + ref + "}, {maxLength: 9}]", "allOf: [{" + ref + "}]"}, + {"allOf: [{" + ref + "}], type: string", "allOf: [{" + ref + "}], type: string"}, + {ref + ", maxLength: 9", ref}, + } { + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", equivalentSpec(row.body, row.equivalent))) + openapitest.RequireNoErrorDiags(t, diags) + union, ok := typeByName(doc, "P").(*ir.Union) + require.True(t, ok, "%s: P is a Union of its conjoined branches; got %T", row.body, typeByName(doc, "P")) + require.Len(t, union.Variants, len(oneRefRestBranches), row.body) + assert.Nil(t, union.Constraints, "%s: neither B's bound nor the body's is the Union's", row.body) + if row.body != row.equivalent { + kept := union.Unmodeled["openapi:maxLength"] + assert.Equal(t, ir.ReasonNoIRHome, kept.Reason, "%s: the body's length is kept", row.body) + assert.JSONEq(t, "9", string(kept.Value), row.body) + } + for i, variant := range union.Variants { + equivalent := typeByName(doc, "Twin"+string(rune('0'+i))) + if use, isUse := useOf(equivalent); isUse { + assert.Equal(t, use, variant.Type.Target, "%s: branch %d is the target its allOf uses", row.body, i) + continue + } + assert.Equal(t, nodeView(t, equivalent), nodeView(t, doc.Types[variant.Type.Target]), "%s: branch %d lowers as its allOf", row.body, i) + } + } +} + +// TestUnionBeside_ARefBodysBoundsAreTheUnionsAsInline holds a bound written +// beside a body's $ref, on an entry of the allOf or beside the $ref itself, to +// the Union's Constraints, as a bound beside a type written inline is, in the +// spellings a union beside such a body has, its variants each a string whose +// value is its text. +func TestUnionBeside_ARefBodysBoundsAreTheUnionsAsInline(t *testing.T) { + t.Parallel() + const union = "oneOf: [{format: email}, {format: hostname}]" + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` B: {type: string} + Inline: {type: string, maxLength: 5, `+union+`} + Entry: {allOf: [{$ref: '#/components/schemas/B'}, {maxLength: 5}], `+union+`} + Sibling: {$ref: '#/components/schemas/B', maxLength: 5, `+union+`} + UnionEntry: {allOf: [{$ref: '#/components/schemas/B', maxLength: 5}, {`+union+`}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + inline, ok := typeByName(doc, "Inline").(*ir.Union) + require.True(t, ok) + for _, name := range []string{"Entry", "Sibling", "UnionEntry"} { + spelled, isUnion := typeByName(doc, name).(*ir.Union) + require.True(t, isUnion, "%s; got %T", name, typeByName(doc, name)) + assert.Equal(t, inline.Constraints, spelled.Constraints, name) + assert.Len(t, spelled.Variants, len(inline.Variants), name) + assert.Empty(t, spelled.Unmodeled, "%s keeps nothing", name) + for _, variant := range spelled.Variants { + assert.Nil(t, doc.Types[variant.Type.Target].(*ir.Scalar).Constraints, "%s: no variant holds the body's bound", name) + } + } +} + +// TestUnionBeside_ARefBodysNotesStayThePositions holds the notes of a body +// holding one $ref, its own and its entries', to the Union the position +// lowers to, each once, and a branch's to the variant conjoining it. +func TestUnionBeside_ARefBodysNotesStayThePositions(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` B: {type: string} + Own: {allOf: [{$ref: '#/components/schemas/B'}], description: d, oneOf: [{format: uuid}, {format: date, description: b}]} + Entry: {allOf: [{$ref: '#/components/schemas/B'}, {maxLength: 5, description: e}], oneOf: [{format: uuid}, {format: date}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, want := range map[string]string{"Own": "d", "Entry": "e"} { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s; got %T", name, typeByName(doc, name)) + assert.Equal(t, want, union.Docs.Description, name) + require.Len(t, union.Variants, 2, name) + assert.Empty(t, doc.Types[union.Variants[0].Type.Target].Common().Docs.Description, "%s: the body's notes are no variant's", name) + } + own := typeByName(doc, "Own").(*ir.Union) + assert.Equal(t, "b", doc.Types[own.Variants[1].Type.Target].Common().Docs.Description, "a branch's notes are its variant's") +} + +// TestUnionBeside_AHolderWritingMoreIsReadAsTheBody holds a union written on +// an allOf entry beside a second $ref to no body of one $ref, the entry's +// $ref kept, and one whose entry writes an allOf of its own to the body that +// allOf is a conjunct of: the Union keeps its bound, as written beside it. +func TestUnionBeside_AHolderWritingMoreIsReadAsTheBody(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` B: {type: string, maxLength: 40} + X: {type: string, pattern: '^x'} + Two: {allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/X', oneOf: [{format: uuid}, {format: date}]}]} + Wrap: {allOf: [{$ref: '#/components/schemas/B'}, {oneOf: [{format: uuid}, {format: date}], allOf: [{maxLength: 5}]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + two, ok := typeByName(doc, "Two").(*ir.Scalar) + require.True(t, ok, "Two; got %T", typeByName(doc, "Two")) + kept, isKept := two.Unmodeled["openapi:$ref"] + require.True(t, isKept, "the entry's $ref is kept") + assert.JSONEq(t, `"#/components/schemas/X"`, string(kept.Value)) + wrap, ok := typeByName(doc, "Wrap").(*ir.Union) + require.True(t, ok, "Wrap; got %T", typeByName(doc, "Wrap")) + assert.Len(t, wrap.Variants, 2) + kept, isKept = wrap.Unmodeled["openapi:maxLength"] + require.True(t, isKept, "the entry's own allOf is read") + assert.Equal(t, ir.ReasonNoIRHome, kept.Reason, "a length binds no uuid's or date's value") +} + +// TestUnionBeside_ABodyTypedApartIsNoRefBody holds a body whose type, written +// beside its $ref or on an entry of its allOf, names another kind than the +// $ref's target to no body of one $ref, alike in either spelling: its +// conjuncts share no value, which no variant conjoins. +func TestUnionBeside_ABodyTypedApartIsNoRefBody(t *testing.T) { + t.Parallel() + doc, _ := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` B: {type: string} + Own: {allOf: [{$ref: '#/components/schemas/B'}], type: integer, oneOf: [{format: uuid}, {format: date}]} + Entry: {allOf: [{$ref: '#/components/schemas/B'}, {type: integer}], oneOf: [{format: uuid}, {format: date}]} +`)) + for _, name := range []string{"Own", "Entry"} { + _, isUnion := typeByName(doc, name).(*ir.Union) + assert.False(t, isUnion, "%s's body is typed apart from its $ref", name) + } + assert.Equal(t, typeByName(doc, "Own").Kind(), typeByName(doc, "Entry").Kind(), "alike in either spelling") +} diff --git a/compilers/openapi/internal/schema/pendingkeeps.go b/compilers/openapi/internal/schema/pendingkeeps.go new file mode 100644 index 000000000..b3ff39455 --- /dev/null +++ b/compilers/openapi/internal/schema/pendingkeeps.go @@ -0,0 +1,281 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "bytes" + "encoding/json/jsontext" + "maps" + "slices" + "strings" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// Every conjunct writing a node adds what it keeps to the node's pending keeps +// (annotation.PendingKeeps), and the frame owning the node settles them once +// (docs/compilers/openapi.md#allof-inline-residue). What a pending keep +// carries that the settlement does not decide is decided here: where its +// conjunct lies, the bound a boolean exclusive flag modifies, and whether the +// promotion policy reads its key, which keeps it at every conjunct. + +// positionSite is the conjunct site of the schema written at pointer, the +// outermost conjunct of the node lowered there. +func positionSite(pointer jsontext.Pointer) annotation.ConjunctSite { + return annotation.ConjunctSite{Pointer: pointer, Role: annotation.WritesAtPosition, Order: annotation.BesideAllOf} +} + +// entrySiteAt is the conjunct site of the entry of comp written at pointer, as +// role says it relates to the position, keyed by its path from comp's schema. +func entrySiteAt(comp allOfComposition, pointer jsontext.Pointer, role annotation.ConjunctRole) annotation.ConjunctSite { + order := annotation.UnlistedEntry + if i, found := comp.entryIndex(pointer); found { + order = annotation.ConjunctIndex(i) + } + return annotation.ConjunctSite{Pointer: pointer, EntryKey: comp.entryKey(pointer), Role: role, Order: order} +} + +// addPendingKeeping records on pendingKeeps, as site's, a pending keep of each +// of keepingValue's keys schema writes, by the YAML node the node renders when +// it settles; a key schema does not write is never kept. +func addPendingKeeping(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, site annotation.ConjunctSite, schema *statement.Schema, + keepingValue keeping, +) { + if len(keepingValue.keys) == 0 { + return + } + chosenKeeping := &annotation.KeptKeywordKeeping{Keep: keepingValue.keep, KeepAtPosition: keepingValue.keepAtPosition} + for _, keyword := range keepingValue.keys { + node := keyNode(schema, keyword) + if node == nil { + continue + } + pendingKeep := pendingKeepOf(loweringContext, site, annotation.EntryKey("", keyword), keyword, nil, keepingValue.reason, chosenKeeping) + pendingKeep.Written, pendingKeep.Modifies = node, boundModifiedBy(keyword, node) + pendingKeeps.Add(pendingKeep) + } +} + +// pendingKeepOf is the pending keep of what site keeps of keyword under key, +// kept by chosenKeeping, a reader's keep (annotation.KeptByReader). +func pendingKeepOf(loweringContext lowering.Ctx, site annotation.ConjunctSite, key, keyword string, value ir.RawValue, reason ir.UnmodeledReason, + chosenKeeping *annotation.KeptKeywordKeeping, +) annotation.PendingKeep { + return annotation.PendingKeep{ + Key: key, + Keyword: keyword, + Modifies: boundModified(key, keyword, value), + Value: value, + Reason: reason, + WrittenBy: site, + Source: annotation.KeptByReader, + KeptBy: chosenKeeping, + KeptAtEveryConjunctSite: loweringContext.Promoter().Reads(key), + } +} + +// addPendingKeepsKeptAs adds a pending keep of each entry of kept, what site +// wrote, with the reports paired with its key, and returns the unpaired ones. +// written, where not nil, is the schema an entry kept at its keyword's node +// renders from. entryUnread marks what an allOf entry leaves unread, which the +// entry kept whole holds, so none of it is kept at every conjunct site. +func addPendingKeepsKeptAs(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, site annotation.ConjunctSite, kept ir.Unmodeled, + keptReports annotation.KeptReports, source annotation.KeptKeywordSource, written *statement.Schema, entryUnread bool, +) []ir.Diagnostic { + reports, rest := keyedReports(kept, keptReports) + diags := keptReports.Diagnostics() + for _, key := range reportOrder(kept, reports, len(diags)) { + entry := kept[key] + pendingKeep := pendingKeepOf(loweringContext, site, key, writtenKeyword(key), entry.Value, entry.Reason, nil) + if written != nil && entry.Provenance.Pointer == site.Pointer+ids.Ptr(pendingKeep.Keyword) { + pendingKeep.Written = keyNode(written, pendingKeep.Keyword) + } + for _, i := range reports[key] { + pendingKeep.Report = append(pendingKeep.Report, diags[i]) + } + pendingKeep.Provenance = entry.Provenance + pendingKeep.KeptAtEveryConjunctSite = pendingKeep.KeptAtEveryConjunctSite && !entryUnread + pendingKeep.Source = source + pendingKeeps.Add(pendingKeep) + } + return rest +} + +// keyedReports returns, by key, the indices of the reports paired with a key +// kept holds, and the rest in order, which remain where they are drawn. +func keyedReports(kept ir.Unmodeled, reports annotation.KeptReports) (map[string][]int, []ir.Diagnostic) { + out := make(map[string][]int, len(kept)) + var rest []ir.Diagnostic + for i, report := range reports { + if _, held := kept[report.Key]; held { + out[report.Key] = append(out[report.Key], i) + continue + } + rest = append(rest, report.Diagnostic) + } + return out, rest +} + +// addWritingPendingKeeps adds as pending keeps what each conjunct of comp's +// node writes of a keyword an entry of kept or another conjunct keeps +// (pendingKept) and the node reads in (annotation.ConsumedIntoNode), in the +// role principal gives it. A bound the conjuncts' intersection replaces +// (textBoundIntersection.consumedFrom) is no value of the node's, so adds none. +func addWritingPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, comp allOfComposition, kept []keptEntry, + principal *allOfEntry, textIntersection textBoundIntersection, pendingKept ...string, +) { + keywords := map[string]bool{} + for _, keyword := range pendingKept { + keywords[keyword] = true + } + for _, keptEntryValue := range kept { + for _, key := range keptEntryValue.own { + keywords[key] = true + } + } + if len(keywords) == 0 { + return + } + addWrittenPendingKeeps(loweringContext, pendingKeeps, positionSite(comp.pointer), schema, keywords, textIntersection.consumedFrom(schema)) + principalAt, inline := inlinePrincipal(principal) + for _, entry := range comp.entries { + if !stated(entry.schema.Schema) || entry.schema.Ref != nil && !failedRef(loweringContext, entry) { + continue + } + role := annotation.WritesBeside + if inline && lowersFrom(principalAt, entry) { + role = annotation.WritesLoweredFrom + } + site := entrySiteAt(comp, entry.pointer, role) + if addWrittenPendingKeeps(loweringContext, pendingKeeps, site, entry.schema.Schema, keywords, textIntersection.consumedFrom(entry.schema.Schema)) { + pendingKeeps.AddEntry(loweredEntrySite(loweringContext, comp, entry, site)) + } + } +} + +// recordFlattenedEntry records on pendingKeeps the flattened entry of comp +// written at site, as written, so of entries keeping a value alike the +// settlement reports it at the one sorting first and their order decides +// nothing (docs/compilers/openapi.md#allof-inline-residue). Its record carries +// no report: a flattened entry keeps nothing another conjunct writes otherwise. +// An entry comp does not hold is not recorded. +func recordFlattenedEntry(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, comp allOfComposition, site annotation.ConjunctSite) { + if i, listed := site.Order.Entry(); listed { + entry := comp.entries[i] + whole, _ := renderedWhole(entry.schema.Node) + pendingKeeps.AddEntry(annotation.KeptAllOfEntry{Site: site, Whole: whole, Provenance: loweringContext.Place().At(entry.pointer)}) + } +} + +// addWrittenPendingKeeps adds a pending keep of each of keywords schema, +// written at site, writes, as read into the node, and reports whether it added +// one. A value spelling the keyword left out, or one of replaced, adds none. +func addWrittenPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, site annotation.ConjunctSite, schema *statement.Schema, + keywords map[string]bool, replaced keySet, +) bool { + pending := false + for _, key := range schema.Keys { + if !keywords[key.Name] || !hasKey(schema, key.Name) || annotation.WritesKeywordLeftOut(schema, key.Name) || replaced&keyBit(key.Name) != 0 { + continue + } + raw, _, err := annotation.RenderDroppingExtensions(key.Node) + if err != nil || len(raw) == 0 { + continue + } + pendingKeep := pendingKeepOf(loweringContext, site, annotation.EntryKey("", key.Name), key.Name, raw, ir.ReasonDegradedLowering, nil) + pendingKeep.Source = annotation.ConsumedIntoNode + pendingKeeps.Add(pendingKeep) + pending = true + } + return pending +} + +// reportOrder returns the keys of kept in the order their reports, indices +// into a list of n, are drawn, so a node settled reports what it keeps as its +// keepers did, those reported by none last, by key. +func reportOrder(kept ir.Unmodeled, reports map[string][]int, n int) []string { + keys := slices.Sorted(maps.Keys(kept)) + first := func(key string) int { + if len(reports[key]) == 0 { + return n + } + return reports[key][0] + } + slices.SortStableFunc(keys, func(a, b string) int { return first(a) - first(b) }) + return keys +} + +// writtenKeyword is the keyword of the schema the entry under key holds: the +// first of those a validation-only entry combines, else the one it is kept +// for (annotation.EntryKeyword), "" for an allOf entry kept whole. +func writtenKeyword(key string) string { + if combined := annotation.ValidationOnlyKeywordsOf(key); len(combined) > 1 { + return combined[0] + } + keyword, _ := annotation.EntryKeyword(key) + return keyword +} + +// boundModifiedBy is boundModified for a flag written as node: a scalar +// rendering to a boolean. +func boundModifiedBy(keyword string, node *yaml.Node) string { + if keyword != "exclusiveMinimum" && keyword != "exclusiveMaximum" || nodeview.Deref(node).Kind != yaml.ScalarNode { + return "" + } + raw, err := annotation.RawFromNode(node) + if err != nil { + return "" + } + return boundModified(annotation.EntryKey("", keyword), keyword, raw) +} + +// boundModified returns the key of the bound a boolean exclusive flag, one +// draft 4 and OpenAPI 3.0 write, modifies, so the two settle as one unit, and +// "" for any other keyword or value. +func boundModified(key, keyword string, value ir.RawValue) string { + if !bytes.Equal(value, []byte("true")) && !bytes.Equal(value, []byte("false")) { + return "" + } + scope := strings.TrimSuffix(key, keyword) + switch keyword { + case "exclusiveMinimum": + return scope + "minimum" + case "exclusiveMaximum": + return scope + "maximum" + default: + return "" + } +} + +// settleOn settles pendingKeeps onto unmodeled, a node's or a carrier's, +// reading what unmodeled already holds as written at the position at, its +// reports already drawn. +func settleOn(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, pendingKeeps *annotation.PendingKeeps, at jsontext.Pointer) []ir.Diagnostic { + if pendingKeeps.Empty() { + return nil + } + var settled annotation.PendingKeeps + position := positionSite(at) + for _, key := range slices.Sorted(maps.Keys(*unmodeled)) { + entry := (*unmodeled)[key] + pendingKeep := pendingKeepOf(loweringContext, position, key, writtenKeyword(key), entry.Value, entry.Reason, nil) + pendingKeep.Provenance = entry.Provenance + settled.Add(pendingKeep) + } + settled.AddAll(*pendingKeeps) + *pendingKeeps = annotation.PendingKeeps{} + kept, diags := settled.Settle(loweringContext.Place().At(at)) + *unmodeled = kept + if len(kept) == 0 { + *unmodeled = nil + } + return diags +} diff --git a/compilers/openapi/internal/schema/placement.go b/compilers/openapi/internal/schema/placement.go new file mode 100644 index 000000000..3a761b2fb --- /dev/null +++ b/compilers/openapi/internal/schema/placement.go @@ -0,0 +1,80 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// nodePlacement is where the node a schema lowers to is placed where that is +// not where the schema is written, such as the position whose allOf the schema +// is the inline principal of (docs/compilers/openapi.md#allof-refinement); the +// zero nodePlacement is the schema's own. It is a parameter, never read off the +// schema or the context, since a $ref to the entry lowers the same schema at +// its own pointer. +type nodePlacement struct { + position *statement.Schema + positionPointer jsontext.Pointer + // homes are the bounds the node holds of its position's flattened entries, as + // boundsHeldAt decides them in the frame dispatching to the build. + homes boundHomes + // keptWholeByPosition says the node is a type list's variant whose + // principal the position keeps whole under its entry's key (keptWhole), so + // it keeps none of its bounds verbatim. + keptWholeByPosition bool + // flatSpellingType is the type the node's schema, a chosen format writing + // none, lowers by: its flat twin's over the $ref it passed over + // (keywordBesideRef). + flatSpellingType statement.JSONSchemaTypeName +} + +// positionOrSchema returns the schema a union schema writes is chosen at +// (docs/compilers/openapi.md#competing-keywords): its position, whose branches +// declare shape against all it conjoins. +func (placement nodePlacement) positionOrSchema(schema *statement.Schema) *statement.Schema { + if placement.position == nil { + return schema + } + return placement.position +} + +// pointer returns where the node of a schema written at written is placed. +func (placement nodePlacement) pointer(written jsontext.Pointer) jsontext.Pointer { + if placement.positionPointer == "" { + return written + } + return placement.positionPointer +} + +// flattenedEntries returns what the node of schema, written at written, reads +// as its own beside schema: placed at another position, that position's own +// keywords and each flattened entry of its allOf but schema. +func (placement nodePlacement) flattenedEntries(loweringContext lowering.Ctx, schema *statement.Schema, written jsontext.Pointer) []annotation.FlattenedAllOfEntry { + if placement.position == nil { + return positionFlattenedEntries(loweringContext, schema, written, ir.TypeRef{}) + } + flattenedEntries := positionFlattenedEntries(loweringContext, placement.position, placement.positionPointer, ir.TypeRef{}) + out := make([]annotation.FlattenedAllOfEntry, 0, len(flattenedEntries)+1) + beside := flattenedEntryAt(loweringContext, placement.position, placement.positionPointer) + beside.Beside = true + out = append(out, beside) + for _, flattenedAllOfEntry := range flattenedEntries { + if flattenedAllOfEntry.Node != schema || flattenedAllOfEntry.At != written { + out = append(out, flattenedAllOfEntry) + } + } + return out +} + +// inlinePrincipalBuiltPositionNode reports whether refinementValue's principal +// is inline and built the node the position written at pointer owns, having +// lowered to target. +func inlinePrincipalBuiltPositionNode(loweringContext lowering.Ctx, refinementValue refinement, target ir.TypeRef, pointer jsontext.Pointer) bool { + return refinementValue.principal != nil && refinementValue.principal.schema.Ref == nil && LoweredToOwnNode(loweringContext, pointer, target) +} diff --git a/compilers/openapi/internal/schema/stand_test.go b/compilers/openapi/internal/schema/placement_test.go similarity index 74% rename from compilers/openapi/internal/schema/stand_test.go rename to compilers/openapi/internal/schema/placement_test.go index 0dabb2832..a8f49c46c 100644 --- a/compilers/openapi/internal/schema/stand_test.go +++ b/compilers/openapi/internal/schema/placement_test.go @@ -13,12 +13,13 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestStand_AUnionKeptBesideAPrincipalsBodyStandsAtThePosition pins an inline -// principal writing a union whose branches declare no shape beside a body that -// lowers to a shared primitive: the alias keeping the union stands at the -// position, as it does where the same keywords are written beside each other, -// the union kept where it is written (docs/compilers/openapi.md#allof-refinement). -func TestStand_AUnionKeptBesideAPrincipalsBodyStandsAtThePosition(t *testing.T) { +// TestPlacement_AUnionKeptBesideAPrincipalsBodySitsAtThePosition pins an +// inline principal writing a union whose branches declare no shape beside a +// body that lowers to a shared primitive: the alias keeping the union sits at +// the position, as it does where the same keywords are written beside each +// other, the union kept where it is written +// (docs/compilers/openapi.md#allof-refinement). +func TestPlacement_AUnionKeptBesideAPrincipalsBodySitsAtThePosition(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Beside: {description: d, type: string, oneOf: [{minLength: 1}, {maxLength: 3}]}\n"+ @@ -36,15 +37,15 @@ func TestStand_AUnionKeptBesideAPrincipalsBodyStandsAtThePosition(t *testing.T) assert.Equal(t, at, string(kept.Provenance.Pointer), "%s: kept where it is written", name) } _, atEntry := doc.Types["type/anonymous/components/schemas/Entry/allOf/1"] - assert.False(t, atEntry, "nothing stands at the entry") + assert.False(t, atEntry, "nothing sits at the entry") } -// TestStand_ContentVocabularyIsReadWhereThePrincipalsNodeHoldsIt pins the +// TestPlacement_ContentVocabularyIsReadWhereThePrincipalsNodeHoldsIt pins the // content vocabulary an inline principal writes beside its type: the Scalar a // string builds holds it in its Encoding, keeping nothing, and the Enum a value // set builds, which has no Encoding, keeps it, each as the same keywords beside // each other do. -func TestStand_ContentVocabularyIsReadWhereThePrincipalsNodeHoldsIt(t *testing.T) { +func TestPlacement_ContentVocabularyIsReadWhereThePrincipalsNodeHoldsIt(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " ScalarBeside: {description: d, type: string, contentEncoding: base64}\n"+ @@ -68,12 +69,12 @@ func TestStand_ContentVocabularyIsReadWhereThePrincipalsNodeHoldsIt(t *testing.T } } -// TestStand_ContentVocabularyItsNodeCannotHoldIsKept pins the content +// TestPlacement_ContentVocabularyItsNodeCannotHoldIsKept pins the content // vocabulary an inline principal writes beside a union, a null alone or an // inferred list, whose node has no Encoding: it is kept on that node where it // is written, as the same keywords beside each other keep it // (docs/compilers/openapi.md#content-vocabulary). -func TestStand_ContentVocabularyItsNodeCannotHoldIsKept(t *testing.T) { +func TestPlacement_ContentVocabularyItsNodeCannotHoldIsKept(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " UnionBeside: {description: d, oneOf: [{type: string}, {type: integer}], contentMediaType: text/plain}\n"+ @@ -87,22 +88,23 @@ func TestStand_ContentVocabularyItsNodeCannotHoldIsKept(t *testing.T) { "NullEntry": "/components/schemas/NullEntry/allOf/1/contentMediaType", "ListEntry": "/components/schemas/ListEntry/allOf/1/contentMediaType", } { - td := typeByName(doc, name) - require.NotNil(t, td, name) - kept, held := td.Common().Unmodeled["openapi:contentMediaType"] - require.True(t, held, "%s keeps what no Encoding holds, on %T", name, td) + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) + kept, held := typeDef.Common().Unmodeled["openapi:contentMediaType"] + require.True(t, held, "%s keeps what no Encoding holds, on %T", name, typeDef) assert.Equal(t, ir.ReasonNoIRHome, kept.Reason, name) assert.Equal(t, at, string(kept.Provenance.Pointer), "%s: kept where it is written", name) } } -// TestStand_ContentBesideTheAllOfIsKeptBesideThePrincipalsEncoding pins a +// TestPlacement_ContentBesideTheAllOfReachesThePrincipalsEncoding pins a // content keyword the position writes beside an allOf whose inline principal -// builds a Scalar holding an Encoding of its own: the Encoding is the entry's, -// so the keyword is kept beside it where it is written, never dropped, where -// the keywords beside an allOf electing no entry build the Encoding holding it +// builds a Scalar holding an Encoding of its own: the vocabulary reaches any +// conjunct, so the Encoding holds what the entry writes and what the position +// does, as written flat, and nothing is kept, as where the keywords beside an +// allOf choosing no entry build the Encoding // (docs/compilers/openapi.md#content-vocabulary). -func TestStand_ContentBesideTheAllOfIsKeptBesideThePrincipalsEncoding(t *testing.T) { +func TestPlacement_ContentBesideTheAllOfReachesThePrincipalsEncoding(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Beside: {allOf: [{type: string, contentEncoding: base64}], contentMediaType: text/plain}\n"+ @@ -116,10 +118,7 @@ func TestStand_ContentBesideTheAllOfIsKeptBesideThePrincipalsEncoding(t *testing sc, ok := typeByName(doc, "Beside").(*ir.Scalar) require.True(t, ok, "Beside is the scalar, not %T", typeByName(doc, "Beside")) require.NotNil(t, sc.Encoding) - assert.Equal(t, "base64", sc.Encoding.Name, "the entry's Encoding stands") - assert.Empty(t, sc.Encoding.MediaType, "and holds nothing the position writes") - kept, held := sc.Unmodeled["openapi:contentMediaType"] - require.True(t, held, "the position's keyword is kept") - assert.Equal(t, ir.ReasonNoIRHome, kept.Reason) - assert.Equal(t, "/components/schemas/Beside/contentMediaType", string(kept.Provenance.Pointer)) + assert.Equal(t, "base64", sc.Encoding.Name, "the entry's name remains") + assert.Equal(t, "text/plain", sc.Encoding.MediaType, "beside the position's media type") + assert.Empty(t, sc.Unmodeled, "nothing is kept") } diff --git a/compilers/openapi/internal/schema/placementkept.go b/compilers/openapi/internal/schema/placementkept.go new file mode 100644 index 000000000..a2c71096f --- /dev/null +++ b/compilers/openapi/internal/schema/placementkept.go @@ -0,0 +1,191 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "cmp" + "encoding/json/jsontext" + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// keeping is what one reader keeps verbatim of a schema on the node it lowered +// to: keys, for reason, each under its own key by keep, which reports them as +// the same keywords written flat are reported, naming the node shape where the +// reader names one, and by keepAtPosition where the node reports them at its +// position, worded as written beside the allOf, nil where keep words them so. +type keeping struct { + keys []string + reason ir.UnmodeledReason + shape string + keep func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic + keepAtPosition func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic +} + +// keepAround records keepingValue for one reader of schema, written at pointer, +// on built. On the schema's own node it keeps immediately. On the node set up +// for placement's position the reader adds what it keeps as pending keeps, +// which the frame owning that node settles with what every other conjunct of it +// adds (docs/compilers/openapi.md#allof-inline-residue). +func keepAround(loweringContext lowering.Ctx, placement nodePlacement, built *builtPosition, schema *statement.Schema, pointer jsontext.Pointer, keepingValue keeping) []ir.Diagnostic { + if placement.position == nil { + return keepingValue.keep(&built.node.Common().Unmodeled, keepingValue.keys) + } + built.shape = cmp.Or(keepingValue.shape, built.shape) + if len(keepingValue.keys) == 0 { + return nil + } + addPendingKeeping(loweringContext, &built.pendingKeeps, principalSite(loweringContext, placement, &built.pendingKeeps, pointer), schema, keepingValue) + return nil +} + +// principalSite is the conjunct site of the inline principal written at pointer +// of the allOf placement's position writes, an entry the position lowers from, +// recorded on pendingKeeps with the report of what it keeps apart. +func principalSite(loweringContext lowering.Ctx, placement nodePlacement, pendingKeeps *annotation.PendingKeeps, pointer jsontext.Pointer) annotation.ConjunctSite { + comp := allOfEntries(loweringContext, placement.position, placement.positionPointer) + site := entrySiteAt(comp, pointer, annotation.WritesLoweredFrom) + if i, listed := site.Order.Entry(); listed { + pendingKeeps.AddEntry(loweredEntrySite(loweringContext, comp, comp.entries[i], site)) + } + return site +} + +// loweredEntrySite is allOfEntryValue, an entry of comp the position lowers +// from, written at site, as the node's pending keeps hold it before the +// position says whether it keeps it whole. +func loweredEntrySite(loweringContext lowering.Ctx, comp allOfComposition, allOfEntryValue allOfEntry, site annotation.ConjunctSite) annotation.KeptAllOfEntry { + whole, _ := renderedWhole(allOfEntryValue.schema.Node) + return annotation.KeptAllOfEntry{ + Site: site, Whole: whole, Provenance: loweringContext.Place().At(allOfEntryValue.pointer), + ReportApart: func(apart []string) []ir.Diagnostic { + return append([]ir.Diagnostic{otherwiseReport(loweringContext, comp, apart, allOfEntryValue.pointer)}, + discriminatorsKept(loweringContext, apart, allOfEntryValue.pointer)...) + }, + } +} + +// addBuiltPendingKeeps adds to pendingKeeps, those of the node placement +// places, each entry of kept, what the build of the schema written at pointer +// keeps there, with the reports paired with its key, and returns the reports +// paired with none. The build reports what it kept wherever it is kept, so the +// report of an entry kept whole names it not again +// (docs/compilers/openapi.md#allof-inline-residue). +func addBuiltPendingKeeps(loweringContext lowering.Ctx, placement nodePlacement, pendingKeeps *annotation.PendingKeeps, pointer jsontext.Pointer, kept ir.Unmodeled, + keptReports annotation.KeptReports, +) []ir.Diagnostic { + reports, rest := keyedReports(kept, keptReports) + diags := keptReports.Diagnostics() + var comp allOfComposition + if placement.position != nil { + comp = allOfEntries(loweringContext, placement.position, placement.positionPointer) + } + for _, key := range reportOrder(kept, reports, len(diags)) { + entry := kept[key] + site := positionSite(placement.pointer(pointer)) + if placement.position != nil { + site = conjunctSiteAt(comp, entry.Provenance.Pointer, pointer) + } + if i, listed := site.Order.Entry(); listed { + pendingKeeps.AddEntry(loweredEntrySite(loweringContext, comp, comp.entries[i], site)) + } + pendingKeep := pendingKeepOf(loweringContext, site, key, writtenKeyword(key), entry.Value, entry.Reason, nil) + pendingKeep.Provenance, pendingKeep.Source = entry.Provenance, annotation.KeptByBuild + for _, i := range reports[key] { + pendingKeep.Report = append(pendingKeep.Report, diags[i]) + } + pendingKeeps.Add(pendingKeep) + } + return rest +} + +// builtKeeps is where the build of the schema written at pointer keeps what no +// field of the node placement places holds: on the schema's own node +// immediately, else in pendingKeeps, which the frame owning the node settles. +type builtKeeps struct { + pendingKeeps *annotation.PendingKeeps + pointer jsontext.Pointer + placement nodePlacement +} + +// keep runs write, one keeping of the build, on unmodeled, the node's own +// Unmodeled, or on a scratch it adds to (addBuiltPendingKeeps), and returns the +// reports it added with no entry. +func (k builtKeeps) keep(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, write func(*ir.Unmodeled) annotation.KeptReports) []ir.Diagnostic { + if k.placement.position == nil { + return write(unmodeled).Diagnostics() + } + var kept ir.Unmodeled + reports := write(&kept) + return addBuiltPendingKeeps(loweringContext, k.placement, k.pendingKeeps, k.pointer, kept, reports) +} + +// conjunctSiteAt returns the conjunct site of what is written at at, among the +// entries of comp, principal being the inline principal's pointer: the entry +// written at or above at, else the position. +func conjunctSiteAt(comp allOfComposition, at, principal jsontext.Pointer) annotation.ConjunctSite { + best := -1 + for i, entry := range comp.entries { + if entry.pointer.Contains(at) && (best < 0 || len(entry.pointer) > len(comp.entries[best].pointer)) { + best = i + } + } + switch { + case best < 0: + return positionSite(comp.pointer) + case lowersFrom(principal, comp.entries[best]): + return entrySiteAt(comp, comp.entries[best].pointer, annotation.WritesLoweredFrom) + default: + return entrySiteAt(comp, comp.entries[best].pointer, annotation.WritesBeside) + } +} + +// keyWrittenAlike reports whether a and b write key with one value, as a +// pending keep compares two writings (annotation.RenderedAlike); one that +// cannot render is alike to nothing. +func keyWrittenAlike(a, b *statement.Schema, key string) bool { + if !hasKey(a, key) || !hasKey(b, key) { + return false + } + x, errA := annotation.RawFromNode(keyNode(a, key)) + y, errB := annotation.RawFromNode(keyNode(b, key)) + return errA == nil && errB == nil && annotation.RenderedAlike(x, y) +} + +// discriminatorsKept keeps whole each discriminator within kept, the keywords +// an allOf entry written at pointer keeps apart under its entry's key +// (KeepDiscriminatorsWithin): one kept verbatim is read wherever it is kept. +func discriminatorsKept(loweringContext lowering.Ctx, kept []string, pointer jsontext.Pointer) []ir.Diagnostic { + diags := make([]ir.Diagnostic, 0, len(kept)) + for _, keyword := range kept { + diags = append(diags, KeepDiscriminatorsWithin(loweringContext, nil, pointer+ids.Ptr(keyword))...) + } + return diags +} + +// outcome returns what placement's position keeps, having lowered to the node +// it owns. +func (placement nodePlacement) outcome(loweringContext lowering.Ctx) outcomeKeeps { + return keepsAtOutcome(loweringContext, placement.position, ir.TypeRef{Target: loweringContext.IDs().ForPointer(placement.positionPointer)}, placement.positionPointer) +} + +// keptWhole reports whether placement's position keeps the inline principal +// written at pointer whole, under its entry's key, for a cause read before +// lowering. A type list asks before it builds its variants, before the union +// node exists. +func (placement nodePlacement) keptWhole(loweringContext lowering.Ctx, pointer jsontext.Pointer) bool { + return placement.position != nil && placement.outcome(loweringContext).holdsWhole(pointer) +} + +// holdsWhole reports whether k keeps the entry written at pointer whole. +func (k outcomeKeeps) holdsWhole(pointer jsontext.Pointer) bool { + return slices.ContainsFunc(k.entries, func(keptEntryValue keptEntry) bool { + return keptEntryValue.entry.pointer == pointer && keptEntryValue.keptWhole() + }) +} diff --git a/compilers/openapi/internal/schema/standkept_test.go b/compilers/openapi/internal/schema/placementkept_test.go similarity index 72% rename from compilers/openapi/internal/schema/standkept_test.go rename to compilers/openapi/internal/schema/placementkept_test.go index ad3b0ab4e..7fa7042ed 100644 --- a/compilers/openapi/internal/schema/standkept_test.go +++ b/compilers/openapi/internal/schema/placementkept_test.go @@ -21,7 +21,7 @@ import ( // keptCase is a component whose inline allOf principal and position both keep // keywords: what its node holds verbatim, each entry as "value [reason]", and -// how many reports stand at its entry and at the schema itself. +// how many reports sit at its entry and at the schema itself. type keptCase struct { name, schema string kept map[string]string @@ -32,10 +32,10 @@ type keptCase struct { // "value [reason]". func keptOn(t *testing.T, doc *ir.Document, name string) map[string]string { t.Helper() - td := typeByName(doc, name) - require.NotNil(t, td, name) + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) out := map[string]string{} - for key, unmodeledEntry := range td.Common().Unmodeled { + for key, unmodeledEntry := range typeDef.Common().Unmodeled { out[key] = string(unmodeledEntry.Value) + " [" + string(unmodeledEntry.Reason) + "]" } return out @@ -57,15 +57,15 @@ func reportsAt(diags []ir.Diagnostic, pointer string) []string { func assertKept(t *testing.T, cases []keptCase) []ir.Diagnostic { t.Helper() var lines strings.Builder - for _, tc := range cases { - lines.WriteString(" " + tc.name + ": " + tc.schema + "\n") + for _, testCase := range cases { + lines.WriteString(" " + testCase.name + ": " + testCase.schema + "\n") } doc, diags := parseFull(t, openapitest.ComponentSpec(lines.String())) - for _, tc := range cases { - at := "/components/schemas/" + tc.name - assert.Equal(t, tc.kept, keptOn(t, doc, tc.name), tc.name) - assert.Len(t, reportsAt(diags, at+"/allOf/0"), tc.atEntry, "%s: reports at its entry: %v", tc.name, reportsAt(diags, at+"/allOf/0")) - assert.Len(t, reportsAt(diags, at), tc.atSelf, "%s: reports at the schema: %v", tc.name, reportsAt(diags, at)) + for _, testCase := range cases { + at := "/components/schemas/" + testCase.name + assert.Equal(t, testCase.kept, keptOn(t, doc, testCase.name), testCase.name) + assert.Len(t, reportsAt(diags, at+"/allOf/0"), testCase.atEntry, "%s: reports at its entry: %v", testCase.name, reportsAt(diags, at+"/allOf/0")) + assert.Len(t, reportsAt(diags, at), testCase.atSelf, "%s: reports at the schema: %v", testCase.name, reportsAt(diags, at)) } return diags } @@ -74,18 +74,20 @@ func assertKept(t *testing.T, cases []keptCase) []ir.Diagnostic { // of one inline principal keep that the position writes otherwise: one object // under the entry's key holds each reader's, none overwriting another's, each // reader naming its own in one report at the entry, and the reason is the one -// they share (docs/compilers/openapi.md#allof-inline-residue). +// they share (docs/compilers/openapi.md#allof-inline-residue). A bound on a +// number as text the two write intersects as any bound's conjuncts do, the node +// keeping the value they intersect in, so it is no reader's of the entry. func TestPrincipalKept_EveryReaderKeepsUnderOneEntryKey(t *testing.T) { t.Parallel() diags := assertKept(t, []keptCase{ {name: "TextAndUnread", schema: "{allOf: [{type: string, format: int64, minimum: 1, required: [a]}], minimum: 2, required: [b]}", kept: map[string]string{ - "openapi:allOf/0": `{"minimum":1,"required":["a"]} [degraded_lowering]`, + "openapi:allOf/0": `{"required":["a"]} [degraded_lowering]`, "openapi:minimum": "2 [no_ir_home]", "openapi:required": `["b"] [degraded_lowering]`, - }, atEntry: 2, atSelf: 1}, + }, atEntry: 1, atSelf: 1}, {name: "TextAlone", schema: "{allOf: [{type: string, format: int64, minimum: 1}], minimum: 2}", - kept: map[string]string{"openapi:allOf/0": `{"minimum":1} [no_ir_home]`, "openapi:minimum": "2 [no_ir_home]"}, atEntry: 1}, + kept: map[string]string{"openapi:minimum": "2 [no_ir_home]"}}, {name: "ContentAndUnread", schema: "{allOf: [{type: integer, contentEncoding: a, required: [a]}], contentEncoding: b, required: [b]}", kept: map[string]string{ "openapi:allOf/0": `{"contentEncoding":"a","required":["a"]} [degraded_lowering]`, @@ -99,9 +101,9 @@ func TestPrincipalKept_EveryReaderKeepsUnderOneEntryKey(t *testing.T) { "openapi:minimum": "2 [degraded_lowering]", }, atEntry: 2, atSelf: 1}, }) - entry := reportsAt(diags, "/components/schemas/TextAndUnread/allOf/0") + entry := reportsAt(diags, "/components/schemas/ContentAndUnread/allOf/0") require.Len(t, entry, 2) - assert.Contains(t, entry[0]+entry[1], "write minimum otherwise") + assert.Contains(t, entry[0]+entry[1], "write contentEncoding otherwise") assert.Contains(t, entry[0]+entry[1], "write required otherwise") } @@ -125,10 +127,12 @@ func TestPrincipalKept_AKeywordAlikeIsKeptOnce(t *testing.T) { }) } -// TestPrincipalKept_AKeyOutsideTheReadDomainIsKeptUnderTheEntryKey pins a keyword -// outside readDomain an inline principal and its position keep otherwise, a -// key no dialect defines: the principal is lowered, so it is not kept whole -// for it, as another entry is. +// TestPrincipalKept_AKeyOutsideTheReadDomainIsKeptUnderTheEntryKey pins a +// keyword outside readDomain an inline principal and its position keep +// otherwise, a key no dialect defines: the principal is lowered, so it is not +// kept whole for it, as another entry is. Beside a sibling entry no conjunct +// sits around the other, so each value is kept under its conjunct's entry key +// and none under the plain key. func TestPrincipalKept_AKeyOutsideTheReadDomainIsKeptUnderTheEntryKey(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( @@ -140,8 +144,8 @@ func TestPrincipalKept_AKeyOutsideTheReadDomainIsKeptUnderTheEntryKey(t *testing assert.Len(t, reportsAt(diags, "/components/schemas/Principal/allOf/0"), 1) assert.Equal(t, map[string]string{"openapi:allOf/1": `{"foo":1} [out_of_scope]`, "openapi:foo": "2 [out_of_scope]"}, keptOn(t, doc, "Entry"), "an entry that is no principal stays whole") - assert.Equal(t, map[string]string{"openapi:allOf/1": `{"foo":3} [out_of_scope]`, "openapi:foo": "1 [out_of_scope]"}, - keptOn(t, doc, "Among"), "a key the position leaves free holds the principal's") + assert.Equal(t, map[string]string{"openapi:allOf/0": `{"foo":1} [out_of_scope]`, "openapi:allOf/1": `{"foo":3} [out_of_scope]`}, + keptOn(t, doc, "Among"), "sibling entries each keep their own value under their entry key") } // TestPrincipalKept_ADiscriminatorKeptPlainHoldsItsKeysOnce pins a @@ -215,21 +219,25 @@ func TestPrincipalKept_ADraftsDependenciesBesideAKeyNoDialectDefines(t *testing. // TestPrincipalKept_APatternBesideThePrincipalsKeepsBoth pins two patterns, one // on an inline principal whose node holds a string's bounds and one beside the // allOf: a field holds one pattern, the position's, as the keywords beside an -// allOf stand, and the principal, disagreeing, is kept whole with its own, -// whatever node it builds. A node holding no such bound keeps both verbatim. +// allOf remain, and the principal, disagreeing, is kept whole with its own, +// whatever node it builds. A node holding no such bound keeps both verbatim, +// and one whose value is text of another kind, bytes or an instant, keeps both +// with no IR home, the position's under the plain key and the principal's in +// its entry (docs/ir/constraints.md#constraints). func TestPrincipalKept_APatternBesideThePrincipalsKeepsBoth(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( " Union: {allOf: [{oneOf: [{type: string}, {type: integer}], pattern: '^p$'}], pattern: '^b$'}\n"+ " TypeList: {allOf: [{type: [string, boolean], pattern: '^p$'}], pattern: '^b$'}\n"+ " Scalar: {allOf: [{type: string, format: byte, pattern: '^p$'}], pattern: '^b$'}\n"+ + " Instant: {allOf: [{type: string, format: date-time, pattern: '^p$'}], pattern: '^b$'}\n"+ + " InstantAlike: {allOf: [{type: string, format: date-time, pattern: '^p$'}], pattern: '^p$'}\n"+ " Shared: {allOf: [{type: string, pattern: '^p$'}], pattern: '^b$'}\n"+ " Alike: {allOf: [{oneOf: [{type: string}, {type: integer}], pattern: '^p$'}], pattern: '^p$'}\n"+ " List: {allOf: [{type: array, items: {type: string}, pattern: '^p$'}], pattern: '^b$'}\n")) held := map[string]*ir.Constraints{ "Union": doc.Types[componentID("Union")].(*ir.Union).Constraints, "TypeList": doc.Types["type/anonymous/components/schemas/TypeList/type/0"].(*ir.Scalar).Constraints, - "Scalar": doc.Types[componentID("Scalar")].(*ir.Scalar).Constraints, "Shared": doc.Types[componentID("Shared")].(*ir.Scalar).Constraints, } for name, cons := range held { @@ -245,6 +253,16 @@ func TestPrincipalKept_APatternBesideThePrincipalsKeepsBoth(t *testing.T) { assert.Empty(t, keptOn(t, doc, "Alike")) assert.Equal(t, map[string]string{"openapi:allOf/0": `{"pattern":"^p$"} [degraded_lowering]`, "openapi:pattern": `"^b$" [degraded_lowering]`}, keptOn(t, doc, "List")) + for name, want := range map[string]map[string]string{ + "Scalar": {"openapi:allOf/0": `{"pattern":"^p$"} [no_ir_home]`, "openapi:pattern": `"^b$" [no_ir_home]`}, + "Instant": {"openapi:allOf/0": `{"format":"date-time","pattern":"^p$","type":"string"} [no_ir_home]`, "openapi:pattern": `"^b$" [no_ir_home]`}, + // One writing, kept once. + "InstantAlike": {"openapi:pattern": `"^p$" [no_ir_home]`}, + } { + assert.Nil(t, doc.Types[componentID(name)].(*ir.Scalar).Constraints, name) + assert.Equal(t, want, keptOn(t, doc, name), name) + assert.Len(t, reportsAt(diags, "/components/schemas/"+name+"/pattern"), 1, name) + } } // TestPrincipalKept_AKeywordTheNodeReadsIsNotAlsoKept pins a keyword an inline @@ -276,44 +294,34 @@ func TestPrincipalKept_AKeywordTheNodeReadsIsNotAlsoKept(t *testing.T) { assert.NotContains(t, media[0], "no Encoding field") } -// TestPrincipalKept_AWholeEntryThatCannotRenderIsKeptByKeyword pins an inline -// principal its position would keep whole, holding a value no JSON holds: it -// is not kept whole, and nothing of it is lost for that one value. What it -// keeps is held keyword by keyword against the position's, as any principal's -// is, and the one value is refused where it is written, as written flat. -func TestPrincipalKept_AWholeEntryThatCannotRenderIsKeptByKeyword(t *testing.T) { +// TestPrincipalKept_AWholeEntryIsKeptWithoutAnExtensionNoJSONHolds pins an +// inline principal its position keeps whole, writing an extension that +// converts to no JSON: the extension alone is dropped, with its own warning at +// the entry, and the entry is kept and reported as without it, whatever the +// keywords beside the allOf write, with no error. +func TestPrincipalKept_AWholeEntryIsKeptWithoutAnExtensionNoJSONHolds(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec( - " Free: {allOf: [{type: string, minimum: 1, x-k: 1, x-q: "+unpreservableValue+"}], x-k: 2}\n"+ - " Taken: {allOf: [{type: string, minimum: 1, x-k: 1, x-q: "+unpreservableValue+"}], x-k: 2, minimum: 2}\n"+ - " Shared: {allOf: [{type: string, x-k: 1, x-q: "+unpreservableValue+"}], x-k: 2}\n")) - assert.Equal(t, map[string]string{ - "openapi:allOf/0": `{"x-k":1} [vendor_extension]`, - "openapi:minimum": "1 [degraded_lowering]", - "openapi:x-k": "2 [vendor_extension]", - }, keptOn(t, doc, "Free")) - assert.Equal(t, map[string]string{ - "openapi:allOf/0": `{"minimum":1,"x-k":1} [degraded_lowering]`, - "openapi:minimum": "2 [degraded_lowering]", - "openapi:x-k": "2 [vendor_extension]", - }, keptOn(t, doc, "Taken")) - assert.Equal(t, map[string]string{"openapi:allOf/0": `{"x-k":1} [vendor_extension]`, "openapi:x-k": "2 [vendor_extension]"}, - keptOn(t, doc, "Shared")) - for _, name := range []string{"Free", "Taken", "Shared"} { - at := "/components/schemas/" + name + "/allOf/0" - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnpreservableConstruct, at+"/x-q"), "%s: the value is refused at its keyword", name) - for _, message := range reportsAt(diags, at) { - assert.NotContains(t, message, "in no form at all", "%s: the entry is in the IR", name) - } + const extension = ", x-q: " + unpreservableValue + for name, schema := range map[string]string{ + "Free": "{allOf: [{type: string, minimum: 1, x-k: 1" + extension + "}], x-k: 2}", + "Taken": "{allOf: [{type: string, minimum: 1, x-k: 1" + extension + "}], x-k: 2, minimum: 2}", + "Shared": "{allOf: [{type: string, x-k: 1" + extension + "}], x-k: 2}", + "Whole": "{allOf: [{type: string, minimum: 1, x-k: 1" + extension + "}], minimum: 2, x-k: 2}", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc := requireKeptWithoutExtension(t, parseFull, openapitest.ComponentSpec(" "+name+": "+schema+"\n"), + extension, "/components/schemas/"+name+"/allOf/0") + assert.Contains(t, typeByName(doc, name).Common().Unmodeled, "openapi:allOf/0", "the entry is kept") + }) } - assert.Len(t, reportsAt(diags, "/components/schemas/Free/allOf/0"), 2, "the bound's own report and the extension held otherwise") - assert.Len(t, reportsAt(diags, "/components/schemas/Taken/allOf/0"), 2, "the bound and the extension, each held otherwise") } // TestPrincipalKept_ThePositionNamesTheNodeAsItsPrincipalDoes pins the kind a -// report names where an inline principal's node stands at the position: the +// report names where an inline principal's node sits at the position: the // report of what the position keeps and the principal's own name it alike, as -// the same keywords written flat do, a shared primitive's alias a primitive. +// the same keywords written flat do, a shared primitive's alias the Scalar it +// is. func TestPrincipalKept_ThePositionNamesTheNodeAsItsPrincipalDoes(t *testing.T) { t.Parallel() _, diags := parseFull(t, openapitest.ComponentSpec( @@ -323,7 +331,7 @@ func TestPrincipalKept_ThePositionNamesTheNodeAsItsPrincipalDoes(t *testing.T) { " ScalarFlat: {type: string, format: byte, minimum: 1, maxItems: 3}\n"+ " List: {allOf: [{type: array, items: {type: string}, minimum: 1}], minLength: 3}\n"+ " ListFlat: {type: array, items: {type: string}, minimum: 1, minLength: 3}\n")) - for name, kind := range map[string]string{"Alias": "primitive", "Scalar": "scalar", "List": "list"} { + for name, kind := range map[string]string{"Alias": "scalar", "Scalar": "scalar", "List": "list"} { want := `this position lowered to a node of kind "` + kind + `"` flat := reportsAt(diags, "/components/schemas/"+name+"Flat") require.Len(t, flat, 1, name) @@ -338,9 +346,9 @@ func TestPrincipalKept_ThePositionNamesTheNodeAsItsPrincipalDoes(t *testing.T) { // TestPrincipalKept_EachKeywordHasOneKeeper pins three readers of one inline // principal at once, its keeping of unread keywords, its content reader and -// what the entry keeps as residue, each holding a keyword the position writes -// otherwise: one object under the entry's key holds all three, each keyword is -// named by one report, its reader's, and no reader keeps another's. +// what the entry keeps as unread keywords, each holding a keyword the position +// writes otherwise: one object under the entry's key holds all three, each +// keyword is named by one report, its reader's, and no reader keeps another's. func TestPrincipalKept_EachKeywordHasOneKeeper(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( @@ -374,9 +382,9 @@ func TestPrincipalKept_EachKeywordHasOneKeeper(t *testing.T) { // with no home, read off the two wordings the readers of a principal draw. func keptAndSaid(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, name string) (kept, said []string) { t.Helper() - td := typeByName(doc, name) - require.NotNil(t, td, name) - for key, unmodeledEntry := range td.Common().Unmodeled { + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) + for key, unmodeledEntry := range typeDef.Common().Unmodeled { switch { case unmodeledEntry.Reason == ir.ReasonVendorExtension: case strings.HasPrefix(key, "openapi:allOf/"): @@ -416,9 +424,10 @@ func keptAndSaid(t *testing.T, doc *ir.Document, diags []ir.Diagnostic, name str // TestPrincipalKept_AFailedKeepingLeavesWhatItsReportsName fails each keeping // of an inline principal's keyword in turn, a value no JSON holds in each -// reader's hands and in the whole entry, a discriminator naming no schema, a -// kept object referring to none: what the node holds verbatim is what its -// reports name, no more and no less, and each failure draws its error. +// reader's hands, a discriminator naming no schema, a kept object referring to +// none: what the node holds verbatim is what its reports name, no more and no +// less, and each failure draws its error. An extension no JSON holds fails no +// keeping (TestPrincipalKept_AWholeEntryIsKeptWithoutAnExtensionNoJSONHolds). func TestPrincipalKept_AFailedKeepingLeavesWhatItsReportsName(t *testing.T) { t.Parallel() bad := unpreservableValue @@ -436,8 +445,6 @@ func TestPrincipalKept_AFailedKeepingLeavesWhatItsReportsName(t *testing.T) { diag.UnpreservableConstruct, []string{"allOf:minLength", "contentSchema", "minLength"}}, {"ResidueApart", "{allOf: [{type: string, minimum: 1, foo: " + bad + "}], minimum: 2, foo: 2}", diag.UnpreservableConstruct, []string{"allOf:minimum", "foo", "minimum"}}, - {"Whole", "{allOf: [{type: string, minimum: 1, x-k: 1, x-q: " + bad + "}], minimum: 2, x-k: 2}", diag.UnpreservableConstruct, - []string{"allOf:minimum", "allOf:x-k", "minimum"}}, {"RoutesApart", "{allOf: [{type: string, minimum: 1, discriminator: {propertyName: a, mapping: {x: Nope}}}], " + "minimum: 2, discriminator: {propertyName: b}}", diag.UnresolvedRef, []string{"allOf:discriminator", "allOf:minimum", "discriminator", "minimum"}}, {"RoutesPlain", "{allOf: [{type: string, minimum: 1, discriminator: {propertyName: a, mapping: {x: Nope}}}], minimum: 2}", @@ -446,21 +453,21 @@ func TestPrincipalKept_AFailedKeepingLeavesWhatItsReportsName(t *testing.T) { "minimum: 2, properties: {b: {type: string}}}", "", []string{"allOf:minimum", "allOf:properties", "minimum", "properties"}}, } var lines strings.Builder - for _, tc := range cases { - lines.WriteString(" " + tc.name + ": " + tc.schema + "\n") + for _, testCase := range cases { + lines.WriteString(" " + testCase.name + ": " + testCase.schema + "\n") } doc, diags := parseFull(t, openapitest.ComponentSpec(lines.String())) - for _, tc := range cases { - kept, said := keptAndSaid(t, doc, diags, tc.name) - assert.Equal(t, tc.kept, kept, "%s: what the node holds", tc.name) - assert.Equal(t, kept, said, "%s: what its reports name", tc.name) - if tc.failure == "" { + for _, testCase := range cases { + kept, said := keptAndSaid(t, doc, diags, testCase.name) + assert.Equal(t, testCase.kept, kept, "%s: what the node holds", testCase.name) + assert.Equal(t, kept, said, "%s: what its reports name", testCase.name) + if testCase.failure == "" { continue } failed := slices.ContainsFunc(diags, func(diagnostic ir.Diagnostic) bool { - return diagnostic.Code == tc.failure && strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"+tc.name+"/allOf/0") + return diagnostic.Code == testCase.failure && strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"+testCase.name+"/allOf/0") }) - assert.True(t, failed, "%s: the failure is reported at the entry", tc.name) + assert.True(t, failed, "%s: the failure is reported at the entry", testCase.name) } } @@ -469,7 +476,7 @@ func TestPrincipalKept_AFailedKeepingLeavesWhatItsReportsName(t *testing.T) { // its own: it is kept verbatim, its routes resolved, and reported as kept // beside the discriminator the Union holds, never for want of a home, which a // Union has; a keyword with none is reported apart, and beside a Union holding -// none the discriminator is not said to be beside one. +// none the discriminator sits with it. func TestPrincipalKept_ADiscriminatorBesideAUnionsOwnSaysWhoseItHolds(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( @@ -490,9 +497,13 @@ func TestPrincipalKept_ADiscriminatorBesideAUnionsOwnSaysWhoseItHolds(t *testing assert.Contains(t, said[1], "holds the discriminator its inline allOf entry writes") assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnresolvedRef, "/components/schemas/Two/discriminator/mapping/x"), "the kept discriminator's mapping is resolved") - said = reportsAt(diags, "/components/schemas/None") - require.Len(t, said, 1) - assert.NotContains(t, said[0], "holds the discriminator", "a Union holding none is not said to hold its branch's") + // Beside a union holding none, the discriminator beside the allOf sits + // with it, and nothing is kept or said. + none, ok := doc.Types[componentID("None")].(*ir.Union) + require.True(t, ok) + require.NotNil(t, none.Discriminator) + assert.Equal(t, "b", none.Discriminator.PropertyName) + assert.Empty(t, reportsAt(diags, "/components/schemas/None")) } // TestPrincipalKept_WhatABuildKeepsIsHeldAgainstThePositions pins the keywords @@ -516,25 +527,29 @@ func TestPrincipalKept_WhatABuildKeepsIsHeldAgainstThePositions(t *testing.T) { " Whole: {allOf: [{"+union+", x-k: 1}], anyOf: [{type: number}, {type: string}], x-k: 2}\n"+ " Free: {allOf: [{type: string, format: byte, contentEncoding: base64url}]}\n"+ " WholeFree: {allOf: [{type: string, format: byte, contentEncoding: base64url, x-k: 1}], x-k: 2}\n")) - for _, tc := range []struct{ name, keyword, entry, plain, flat string }{ + for _, testCase := range []struct{ name, keyword, entry, plain, flat string }{ {"Format", "format", `{"format":"byte"} [no_ir_home]`, `"uuid" [degraded_lowering]`, "format is kept verbatim under Unmodeled"}, {"Union", "anyOf", `{"anyOf":[{"type":"string"},{"type":"boolean"}]} [degraded_lowering]`, `[{"type":"number"},{"type":"string"}] [degraded_lowering]`, "with anyOf kept verbatim under Unmodeled"}, {"Prefix", "prefixItems", `{"prefixItems":[{"type":"integer"}]} [degraded_lowering]`, `[{"type":"boolean"}] [degraded_lowering]`, "prefixItems is kept verbatim: this schema's dialect"}, } { - kept := keptOn(t, doc, tc.name) - assert.Equal(t, tc.entry, kept["openapi:allOf/0"], "%s: the principal's under its entry's key", tc.name) - assert.Equal(t, tc.plain, kept["openapi:"+tc.keyword], "%s: the position's under the keyword", tc.name) - at := "/components/schemas/" + tc.name - said := strings.Join(slices.Concat(reportsAt(diags, at+"/allOf/0"), reportsAt(diags, at+"/allOf/0/"+tc.keyword)), "\n") - assert.Equal(t, 1, strings.Count(said, tc.flat), "%s: the build's report, as written flat, once: %s", tc.name, said) - assert.NotContains(t, said, "otherwise than this inline entry", "%s: and no second report of it", tc.name) - assert.Len(t, reportsAt(diags, at), 1, "%s: the position's once", tc.name) + kept := keptOn(t, doc, testCase.name) + assert.Equal(t, testCase.entry, kept["openapi:allOf/0"], "%s: the principal's under its entry's key", testCase.name) + assert.Equal(t, testCase.plain, kept["openapi:"+testCase.keyword], "%s: the position's under the keyword", testCase.name) + at := "/components/schemas/" + testCase.name + said := strings.Join(slices.Concat(reportsAt(diags, at+"/allOf/0"), reportsAt(diags, at+"/allOf/0/"+testCase.keyword)), "\n") + assert.Equal(t, 1, strings.Count(said, testCase.flat), "%s: the build's report, as written flat, once: %s", testCase.name, said) + assert.NotContains(t, said, "otherwise than this inline entry", "%s: and no second report of it", testCase.name) + assert.Len(t, reportsAt(diags, at), 1, "%s: the position's once", testCase.name) } assert.Equal(t, map[string]string{"openapi:format": `"byte" [no_ir_home]`}, keptOn(t, doc, "Alike")) assert.Empty(t, reportsAt(diags, "/components/schemas/Alike"), "one writing, reported at the entry alone") - assert.Equal(t, map[string]string{"openapi:anyOf": `[{"type":"string"},{"type":"boolean"}] [degraded_lowering]`}, keptOn(t, doc, "UnionAlike")) + assert.Equal(t, map[string]string{ + "openapi:anyOf": `[{"type":"string"},{"type":"boolean"}] [degraded_lowering]`, + // Its integer branch shares no kind with the anyOf, so it is dead. + "openapi:oneOf": `[{"type":"string"},{"type":"integer"}] [degraded_lowering]`, + }, keptOn(t, doc, "UnionAlike")) assert.Empty(t, reportsAt(diags, "/components/schemas/UnionAlike")) whole := keptOn(t, doc, "Whole") assert.Contains(t, whole["openapi:allOf/0"], `"anyOf":[{"type":"string"},{"type":"boolean"}]`) @@ -548,12 +563,12 @@ func TestPrincipalKept_WhatABuildKeepsIsHeldAgainstThePositions(t *testing.T) { assert.Equal(t, keptOn(t, doc, "Alike"), keptOn(t, doc, "Free"), "alone, it is kept as written flat") } -// TestPrincipalKept_AFoldedEntriesBuildKeepStaysThePositions pins what the +// TestPrincipalKept_AFlattenedEntriesBuildKeepStaysThePositions pins what the // build of a principal's node keeps of the position's own keywords, read beside // the principal: a 3.0 exclusive modifier with no bound beside it. It is the // position's, held back with nothing of the principal's, and one the principal // writes alike is kept once. -func TestPrincipalKept_AFoldedEntriesBuildKeepStaysThePositions(t *testing.T) { +func TestPrincipalKept_AFlattenedEntriesBuildKeepStaysThePositions(t *testing.T) { t.Parallel() doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.0.3", " Beside: {allOf: [{type: number, format: fixed}], exclusiveMinimum: true}\n"+ @@ -565,10 +580,11 @@ func TestPrincipalKept_AFoldedEntriesBuildKeepStaysThePositions(t *testing.T) { // TestPrincipalKept_ANestedPrincipalKeepsEachLevelOnce pins an entry naming no // type whose own allOf holds the inline principal: a wrapper the position // lowers from, its keywords read as written beside the principal's allOf. Each -// level's keyword is kept once: the outermost writer's under the keyword, each -// writer inside it under its own entry's key, two allOfs deep and three; a -// wrapper kept whole for another cause holds the principal, whose readers then -// keep nothing; and no report names a conjunct that writes nothing. +// level's keyword is kept once: the outermost conjunct's under the keyword, +// each conjunct inside it under its own entry's key, two allOfs deep and three, +// and beside a sibling entry, which no conjunct sits around, none under the +// plain key; a wrapper kept whole for another cause holds the principal, whose +// readers then keep nothing; and no report names a conjunct writing nothing. func TestPrincipalKept_ANestedPrincipalKeepsEachLevelOnce(t *testing.T) { t.Parallel() inner := "allOf: [{type: string, minimum: 3}]" @@ -602,7 +618,7 @@ func TestPrincipalKept_ANestedPrincipalKeepsEachLevelOnce(t *testing.T) { "openapi:allOf/0/allOf/0/allOf/0": `{"minimum":4} [degraded_lowering]`, }, atEntry: 1, atSelf: 1}, {name: "Entry", schema: "{allOf: [{" + inner + ", minimum: 2}, {minimum: 5}]}", kept: map[string]string{ - "openapi:minimum": "2 [degraded_lowering]", + "openapi:allOf/0": `{"minimum":2} [degraded_lowering]`, "openapi:allOf/0/allOf/0": `{"minimum":3} [degraded_lowering]`, "openapi:allOf/1": `{"minimum":5} [degraded_lowering]`, }, atEntry: 1}, @@ -617,19 +633,16 @@ func TestPrincipalKept_ANestedPrincipalKeepsEachLevelOnce(t *testing.T) { "openapi:allOf/0": `{"allOf":[{"foo":3,"minimum":3,"type":"string"}],"foo":2,"x-k":1} [degraded_lowering]`, "openapi:x-k": "2 [vendor_extension]", }, atEntry: 1}, + // A number as text's bound, its conjuncts intersecting at every level, keeps + // the value they intersect in once, the innermost principal's. {name: "Text", schema: "{allOf: [{allOf: [{type: string, format: int64, minimum: 3}], minimum: 2, foo: 2}], minimum: 1, foo: 1}", kept: map[string]string{ - "openapi:minimum": "1 [no_ir_home]", - "openapi:foo": "1 [out_of_scope]", - "openapi:allOf/0": `{"foo":2,"minimum":2} [degraded_lowering]`, - "openapi:allOf/0/allOf/0": `{"minimum":3} [no_ir_home]`, + "openapi:minimum": "3 [no_ir_home]", + "openapi:foo": "1 [out_of_scope]", + "openapi:allOf/0": `{"foo":2} [out_of_scope]`, }, atEntry: 1}, {name: "TextBound", schema: "{allOf: [{allOf: [{type: string, format: int64, minimum: 3}], minimum: 2}], minimum: 1}", - kept: map[string]string{ - "openapi:minimum": "1 [no_ir_home]", - "openapi:allOf/0": `{"minimum":2} [no_ir_home]`, - "openapi:allOf/0/allOf/0": `{"minimum":3} [no_ir_home]`, - }, atEntry: 1}, + kept: map[string]string{"openapi:minimum": "3 [no_ir_home]"}}, {name: "Key", schema: "{allOf: [{allOf: [{type: string, foo: 3}], foo: 2}], foo: 1}", kept: map[string]string{ "openapi:foo": "1 [out_of_scope]", "openapi:allOf/0": `{"foo":2} [out_of_scope]`, @@ -637,13 +650,13 @@ func TestPrincipalKept_ANestedPrincipalKeepsEachLevelOnce(t *testing.T) { }, atEntry: 1}, } diags := assertKept(t, cases) - for _, tc := range cases { - at := "/components/schemas/" + tc.name + for _, testCase := range cases { + at := "/components/schemas/" + testCase.name for _, message := range slices.Concat(reportsAt(diags, at+"/allOf/0"), reportsAt(diags, at+"/allOf/0/allOf/0")) { - assert.NotContains(t, message, "another conjunct", "%s: no entry is kept whole for a keyword the position lowers from", tc.name) + assert.NotContains(t, message, "another conjunct", "%s: no entry is kept whole for a keyword the position lowers from", testCase.name) } - if tc.name != "Alike" && tc.name != "Whole" && tc.name != "WholeAround" { - assert.Len(t, reportsAt(diags, at+"/allOf/0/allOf/0"), 1, "%s: the principal's keyword is named once, at its entry", tc.name) + if testCase.name != "Alike" && testCase.name != "Whole" && testCase.name != "WholeAround" && testCase.name != "Text" && testCase.name != "TextBound" { + assert.Len(t, reportsAt(diags, at+"/allOf/0/allOf/0"), 1, "%s: the principal's keyword is named once, at its entry", testCase.name) } } whole := reportsAt(diags, "/components/schemas/Whole/allOf/0") @@ -672,7 +685,7 @@ func TestPrincipalKept_ALevelAlikeWithOneAroundItIsKeptOnce(t *testing.T) { obj := func(m string) string { return `{"minimum":` + m + `} [degraded_lowering]` } cases := []struct { keptCase - silent []int // levels that report nothing: their value is kept by another's writing + sayingNothing []int // levels that report nothing: their value is kept by another's writing }{ {keptCase{name: "Two", schema: wrap(wrap(stringSchema("802"), "802"), "801"), kept: map[string]string{"openapi:minimum": n("801"), "openapi:allOf/0": obj("802")}, atEntry: 1, atSelf: 1}, []int{2}}, @@ -695,19 +708,21 @@ func TestPrincipalKept_ALevelAlikeWithOneAroundItIsKeptOnce(t *testing.T) { kept: map[string]string{ "openapi:anyOf": `[{"type":"string"},{"type":"number"}] [degraded_lowering]`, "openapi:allOf/0": `{"anyOf":[{"type":"string"},{"type":"boolean"}]} [degraded_lowering]`, + // Its integer branch shares no kind with the anyOfs, so it is dead. + "openapi:oneOf": `[{"type":"string"},{"type":"integer"}] [degraded_lowering]`, }, atEntry: 1, atSelf: 1}, nil}, {keptCase{name: "Refused", schema: "{allOf: [{allOf: [{type: string, foo: 2}], foo: 3}], foo: " + unpreservableValue + "}", kept: map[string]string{"openapi:foo": "3 [out_of_scope]", "openapi:allOf/0/allOf/0": `{"foo":2} [out_of_scope]`}}, nil}, } keptCases := make([]keptCase, 0, len(cases)) - for _, tc := range cases { - keptCases = append(keptCases, tc.keptCase) + for _, testCase := range cases { + keptCases = append(keptCases, testCase.keptCase) } diags := assertKept(t, keptCases) - for _, tc := range cases { - for _, level := range tc.silent { - where := "/components/schemas/" + tc.name + at(level) - assert.Empty(t, reportsAt(diags, where), "%s: level %d keeps nothing of its own", tc.name, level) + for _, testCase := range cases { + for _, level := range testCase.sayingNothing { + where := "/components/schemas/" + testCase.name + at(level) + assert.Empty(t, reportsAt(diags, where), "%s: level %d keeps nothing of its own", testCase.name, level) } } } @@ -718,7 +733,8 @@ func TestPrincipalKept_ALevelAlikeWithOneAroundItIsKeptOnce(t *testing.T) { // extension. It is one writing: kept once and reported once, by the position // where the principal is lowered, and inside the principal's entry, named by // its report, where the position keeps that entry whole, but an extension the -// promotion policy reads, which stays beside it and is promoted. +// promotion policy reads, which stays beside it and is promoted. An entry +// writing an extension no JSON holds is kept as its twin without it. func TestPrincipalKept_AKeywordAlikeIsOneWritingForEveryReader(t *testing.T) { t.Parallel() keywords := map[string]string{ @@ -733,6 +749,7 @@ func TestPrincipalKept_AKeywordAlikeIsOneWritingForEveryReader(t *testing.T) { keyword + ": " + value + "}\n") } lines.WriteString(" Unrendered: {allOf: [{type: string, foo: 1, x-k: 1, x-q: " + unpreservableValue + "}, {x-k: 2}], foo: 1}\n") + lines.WriteString(" UnrenderedTwin: {allOf: [{type: string, foo: 1, x-k: 1}, {x-k: 2}], foo: 1}\n") lines.WriteString(" Promoted: {allOf: [{type: string, x-sensitive: true, x-k: 1}, {x-k: 2}], x-sensitive: true}\n") doc, diags := parseFull(t, openapitest.ComponentSpec(lines.String())) for keyword := range keywords { @@ -767,17 +784,18 @@ func TestPrincipalKept_AKeywordAlikeIsOneWritingForEveryReader(t *testing.T) { assert.Equal(t, "true [vendor_extension]", keptOn(t, doc, "Promoted")["openapi:x-sensitive"], "an extension the promotion policy reads stays where a promotion finds it, beside the whole entry") assert.True(t, doc.Types[componentID("Promoted")].Common().Sensitive, "and is promoted") - assert.Equal(t, "1 [out_of_scope]", keptOn(t, doc, "Unrendered")["openapi:foo"], - "an entry no JSON holds is not whole, so the position keeps its own") + unrendered := keptOn(t, doc, "Unrendered") + assert.Equal(t, keptOn(t, doc, "UnrenderedTwin"), unrendered, "an extension no JSON holds is left out, and the entry kept whole as its twin") + assert.NotContains(t, unrendered, "openapi:foo", "the whole entry holds the one writing") } -// TestPrincipalKept_AnAlikeKeywordStandsWithItsFirstKeeper pins where a keyword +// TestPrincipalKept_AnAlikeKeywordSitsWithItsFirstKeeper pins where a keyword // written alike beside an inline principal is kept, once and reported once: a // content keyword the node holds no field for is the position's, whose reading // keeps it first; a union the principal's build keeps beside its Union is the // principal's, at the entry, with the build's reason and report // (docs/compilers/openapi.md#allof-refinement). -func TestPrincipalKept_AnAlikeKeywordStandsWithItsFirstKeeper(t *testing.T) { +func TestPrincipalKept_AnAlikeKeywordSitsWithItsFirstKeeper(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( " Content: {allOf: [{type: integer, contentMediaType: text/x}], contentMediaType: text/x}\n"+ @@ -785,21 +803,116 @@ func TestPrincipalKept_AnAlikeKeywordStandsWithItsFirstKeeper(t *testing.T) { "anyOf: [{maxLength: 3}]}\n"+ " NullOnly: {allOf: [{oneOf: [{type: 'null'}], anyOf: [{type: 'null', description: q}]}], "+ "anyOf: [{type: 'null', description: q}]}\n")) - for _, tc := range []struct{ name, key, kept, at string }{ + for _, testCase := range []struct{ name, key, kept, at string }{ {"Content", "openapi:contentMediaType", `"text/x" [no_ir_home]`, "/contentMediaType"}, {"Shapeless", "openapi:anyOf", `[{"maxLength":3}] [validation_only]`, "/allOf/0/anyOf"}, {"NullOnly", "openapi:anyOf", `[{"description":"q","type":"null"}] [degraded_lowering]`, "/allOf/0/anyOf"}, } { - at := "/components/schemas/" + tc.name - assert.Equal(t, tc.kept, keptOn(t, doc, tc.name)[tc.key], tc.name) - assert.Equal(t, jsontext.Pointer(at+tc.at), typeByName(doc, tc.name).Common().Unmodeled[tc.key].Provenance.Pointer, tc.name) + at := "/components/schemas/" + testCase.name + assert.Equal(t, testCase.kept, keptOn(t, doc, testCase.name)[testCase.key], testCase.name) + assert.Equal(t, jsontext.Pointer(at+testCase.at), typeByName(doc, testCase.name).Common().Unmodeled[testCase.key].Provenance.Pointer, testCase.name) var said []string for _, diagnostic := range diags { - if strings.HasPrefix(string(diagnostic.Provenance.Pointer), at) && strings.Contains(diagnostic.Message, strings.TrimPrefix(tc.key, "openapi:")) { + if strings.HasPrefix(string(diagnostic.Provenance.Pointer), at) && strings.Contains(diagnostic.Message, strings.TrimPrefix(testCase.key, "openapi:")) { said = append(said, string(diagnostic.Provenance.Pointer)+": "+diagnostic.Message) } } - assert.Len(t, said, 1, "%s: reported once: %v", tc.name, said) + assert.Len(t, said, 1, "%s: reported once: %v", testCase.name, said) + } +} + +// TestPrincipalKept_AKeywordFlattenedEntriesKeepAlikeIsReportedByContent pins +// the one report of a keyword two flattened entries keep alike, no conjunct +// around the other: kept once at the position, it is reported at the +// entry whose entry as written sorts first, the same entry in either order of +// the two (docs/compilers/openapi.md#allof-inline-residue). +func TestPrincipalKept_AKeywordFlattenedEntriesKeepAlikeIsReportedByContent(t *testing.T) { + t.Parallel() + const described, bare = "{not: {required: [a]}, description: d}", "{not: {required: [a]}}" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Written: {type: object, allOf: ["+described+", "+bare+"]}\n"+ + " Reversed: {type: object, allOf: ["+bare+", "+described+"]}\n")) + for name, describedAt := range map[string]string{"Written": "/allOf/0", "Reversed": "/allOf/1"} { + at := "/components/schemas/" + name + kept := typeByName(doc, name).Common().Unmodeled["openapi:not"] + assert.Equal(t, jsontext.Pointer(at), kept.Provenance.Pointer, "%s: kept once, at the position", name) + var reported []string + for _, diagnostic := range withCode(diags, diag.ValidationOnlyKeyword) { + if strings.HasPrefix(string(diagnostic.Provenance.Pointer), at+"/") || diagnostic.Provenance.Pointer == jsontext.Pointer(at) { + reported = append(reported, strings.TrimPrefix(string(diagnostic.Provenance.Pointer), at)) + } + } + assert.Equal(t, []string{describedAt}, reported, "%s: one report, at the entry writing the description", name) + } +} + +// TestPrincipalKept_AValueOnlyOrderTellsApartIsReportedAtThePosition pins the +// one report of a value folded or kept entries keep alike where order alone +// tells the keeper from another conjunct, a keyword binding a use or two +// entries written alike: in either order of the entries it is drawn at the +// position, worded as the same keyword written beside the allOf reports it +// (docs/compilers/openapi.md#allof-inline-residue). +func TestPrincipalKept_AValueOnlyOrderTellsApartIsReportedAtThePosition(t *testing.T) { + t.Parallel() + const array = "{type: array, items: {type: string}}" + for name, row := range map[string]struct { + entries [2]string + code, says string + }{ + "readOnly": {[2]string{"{readOnly: true, title: t}", "{readOnly: true}"}, diag.DegradedConstruct, "readOnly on a type declaration binds a use"}, + "default": {[2]string{"{default: [a], title: t}", "{default: [a]}"}, diag.DegradedConstruct, "default on a type declaration binds a use"}, + "minimum": {[2]string{"{minimum: 1}", "{minimum: 1}"}, diag.DegradedConstruct, "no home for minimum declared beside it"}, + "not": {[2]string{"{not: {minItems: 3}}", "{not: {minItems: 3}}"}, diag.ValidationOnlyKeyword, `validation-only keyword "not"`}, + "unknownKey": {[2]string{"{unknownKey: 1}", "{unknownKey: 1}"}, diag.UnknownSchemaKeyword, `keyword "unknownKey"`}, + } { + written := "{allOf: [" + array + ", " + row.entries[0] + ", " + row.entries[1] + "]}" + reversed := "{allOf: [" + row.entries[1] + ", " + row.entries[0] + ", " + array + "]}" + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Written: "+written+"\n Reversed: "+reversed+"\n")) + for _, schemaName := range []string{"Written", "Reversed"} { + at := "/components/schemas/" + schemaName + var reported []string + for _, diagnostic := range withCode(diags, row.code) { + where := string(diagnostic.Provenance.Pointer) + if (where == at || strings.HasPrefix(where, at+"/")) && strings.Contains(diagnostic.Message, row.says) { + reported = append(reported, where) + } + } + assert.Equal(t, []string{at}, reported, "%s, %s: one report, at the position: %+v", name, schemaName, diags) + } + } +} + +// TestPrincipalKept_ReportsComeInTheOrderTheirReadersKeep pins the order of a +// node's keeping reports, one reader after another whatever the order of the +// entries: a refinement's principal's build, the position's annotations, a +// flattened entry's fold, then what the refinement keeps, the position's unread +// keywords before an entry's, but after it at a value set; a composition's +// build, the position's unread keywords and then its entries, first +// (docs/compilers/openapi.md#allof-inline-residue). +func TestPrincipalKept_ReportsComeInTheOrderTheirReadersKeep(t *testing.T) { + t.Parallel() + const array, folded = "{type: array, items: {type: string}, minimum: 1, otherWord: 5}", "{not: {type: integer}}" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Refined: {allOf: ["+array+", "+folded+"], maxLength: 5, unknownWord: 4}\n"+ + " RefinedReversed: {allOf: ["+folded+", "+array+"], maxLength: 5, unknownWord: 4}\n"+ + " Valued: {allOf: [{const: a, minimum: 1, otherWord: 5}, "+folded+"], maxLength: 5, unknownWord: 4}\n"+ + " Composed: {allOf: [{type: object, maxLength: 3, otherWord: 5}, "+folded+"], minimum: 2, unknownWord: 4}\n")) + require.NotNil(t, doc) + for name, want := range map[string][]string{ + "Refined": {"/allOf/0", "/unknownWord", "/allOf/1", "", "/allOf/0/otherWord"}, + "RefinedReversed": {"/allOf/1", "/unknownWord", "/allOf/0", "", "/allOf/1/otherWord"}, + "Valued": {"/allOf/0", "/unknownWord", "/allOf/1", "/allOf/0/otherWord", ""}, + "Composed": {"", "/allOf/0/otherWord", "/allOf/0", "/unknownWord", "/allOf/1"}, + } { + at := "/components/schemas/" + name + var reported []string + for _, diagnostic := range diags { + where := string(diagnostic.Provenance.Pointer) + if where == at || strings.HasPrefix(where, at+"/") { + reported = append(reported, strings.TrimPrefix(where, at)) + } + } + assert.Equal(t, want, reported, name) } } @@ -809,8 +922,8 @@ func TestPrincipalKept_AnAlikeKeywordStandsWithItsFirstKeeper(t *testing.T) { // a value bound, an array variant a collection bound, that variant's // Constraints hold it, and nothing keeps or reports it, as written flat, a // format another listed type pairs with leaving the string variant its text. -// A bound no variant reads, a string variant carrying a number as text, is -// kept once on the Union, with its report. +// A bound a string variant carrying a number as text reads none of is kept +// once on that variant, with its report, as written flat beside the list. func TestPrincipalKept_ABoundATypeListVariantReadsIsKeptNowhere(t *testing.T) { t.Parallel() bounds := []struct{ keyword, value, field string }{ @@ -833,12 +946,12 @@ func TestPrincipalKept_ABoundATypeListVariantReadsIsKeptNowhere(t *testing.T) { doc, diags := parseFull(t, openapitest.ComponentSpec(lines.String())) nodes := func(name string) (held, kept []string) { at := "/components/schemas/" + name - for _, td := range doc.Types { - if p := string(td.Common().Provenance.Pointer); p == at || strings.HasPrefix(p, at+"/") { - raw, err := json.Marshal(td, json.Deterministic(true)) + for _, typeDef := range doc.Types { + if p := string(typeDef.Common().Provenance.Pointer); p == at || strings.HasPrefix(p, at+"/") { + raw, err := json.Marshal(typeDef, json.Deterministic(true)) require.NoError(t, err) held = append(held, string(raw)) - kept = append(kept, slices.Collect(maps.Keys(td.Common().Unmodeled))...) + kept = append(kept, slices.Collect(maps.Keys(typeDef.Common().Unmodeled))...) } } return held, kept @@ -871,7 +984,11 @@ func TestPrincipalKept_ABoundATypeListVariantReadsIsKeptNowhere(t *testing.T) { } assert.Contains(t, strings.Join(func() []string { h, _ := nodes("PairBoth"); return h }(), "\n"), `"min":"1"`) for _, name := range []string{"Unread", "UnreadEntry"} { - assert.Equal(t, map[string]string{"openapi:minLength": "7 [no_ir_home]"}, keptOn(t, doc, name), "%s: kept once, on the Union", name) + assert.Empty(t, keptOn(t, doc, name), "%s: the Union keeps none", name) + variant := doc.Types[ir.TypeID("type/anonymous/components/schemas/"+name+"/type/0")] + require.NotNil(t, variant, name) + require.Contains(t, variant.Common().Unmodeled, "openapi:minLength", "%s: kept once, on the text variant", name) + assert.Equal(t, ir.ReasonNoIRHome, variant.Common().Unmodeled["openapi:minLength"].Reason, name) assert.Equal(t, 1, said(name, "minLength"), "%s: and reported once", name) } } diff --git a/compilers/openapi/internal/schema/principal_apart_test.go b/compilers/openapi/internal/schema/principal_apart_test.go index b448ebbc9..4a41d9c40 100644 --- a/compilers/openapi/internal/schema/principal_apart_test.go +++ b/compilers/openapi/internal/schema/principal_apart_test.go @@ -14,13 +14,13 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestStand_AKeywordThePositionKeepsOtherwiseIsKeptUnderThePrincipalsEntry pins -// a keyword an inline principal and its position both keep: written otherwise, -// the plain key holds the position's and the entry's key the principal's alone; -// written alike, it is kept once; where the position keeps the principal whole, -// the whole entry holds it; and where the principal's value cannot be kept, it -// is reported lost and announced nowhere. -func TestStand_AKeywordThePositionKeepsOtherwiseIsKeptUnderThePrincipalsEntry(t *testing.T) { +// TestPlacement_AKeywordThePositionKeepsOtherwiseIsKeptUnderThePrincipalsEntry +// pins a keyword an inline principal and its position both keep: written +// otherwise, the plain key holds the position's and the entry's key the +// principal's alone; written alike, it is kept once; where the position keeps +// the principal whole, the whole entry holds it; and where the principal's +// value cannot be kept, it is reported lost and announced nowhere. +func TestPlacement_AKeywordThePositionKeepsOtherwiseIsKeptUnderThePrincipalsEntry(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec( " Apart: {allOf: [{type: string, minItems: 1}], minItems: 2}\n"+ @@ -31,10 +31,10 @@ func TestStand_AKeywordThePositionKeepsOtherwiseIsKeptUnderThePrincipalsEntry(t " List: {allOf: [{type: [string, boolean], format: int64, minimum: 1, x-k: 1}], x-k: 2}\n"+ " Docs: {allOf: [{type: string, minimum: 1, description: a}], description: b}\n")) held := func(name string) map[string]string { - td := typeByName(doc, name) - require.NotNil(t, td, name) + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) out := map[string]string{} - for key, unmodeledEntry := range td.Common().Unmodeled { + for key, unmodeledEntry := range typeDef.Common().Unmodeled { out[key] = string(unmodeledEntry.Value) } return out @@ -62,11 +62,11 @@ func TestStand_AKeywordThePositionKeepsOtherwiseIsKeptUnderThePrincipalsEntry(t "a bound and a disagreeing description share degraded_lowering") } -// TestStand_ADiscriminatorKeptUnderThePrincipalsEntryResolvesItsMapping pins a -// principal's discriminator kept under its entry's key, apart from the +// TestPlacement_ADiscriminatorKeptUnderThePrincipalsEntryResolvesItsMapping +// pins a principal's discriminator kept under its entry's key, apart from the // position's or held whole: its mapping value naming no schema is reported, as // the keeping of unread keywords reports one it keeps. -func TestStand_ADiscriminatorKeptUnderThePrincipalsEntryResolvesItsMapping(t *testing.T) { +func TestPlacement_ADiscriminatorKeptUnderThePrincipalsEntryResolvesItsMapping(t *testing.T) { t.Parallel() for name, schema := range map[string]string{ "apart": "{allOf: [{type: string, discriminator: {propertyName: a, mapping: {x: Nope}}}], discriminator: {propertyName: b}}", diff --git a/compilers/openapi/internal/schema/property.go b/compilers/openapi/internal/schema/property.go index 72fd21cb7..5276bbc24 100644 --- a/compilers/openapi/internal/schema/property.go +++ b/compilers/openapi/internal/schema/property.go @@ -23,17 +23,19 @@ import ( // The property holds the constraints where its schema lowered to no node of // its own, and none where it did: the node holds them, or keeps them verbatim // where its kind takes none, so each is written once (CarrierConstraintsOf). -func FillPropertyDetail(loweringContext lowering.Ctx, ts *compile.Types, property *ir.Property, js *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { - if js.Truth != statement.Stated { +func FillPropertyDetail(loweringContext lowering.Ctx, types *compile.Types, property *ir.Property, schemaStatement *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { + if schemaStatement.Truth != statement.Stated { return nil } - use := UseOf(loweringContext, js, property.Type, pointer) - def, diags := use.Default(loweringContext, js.Schema, pointer) + use := UseOf(loweringContext, schemaStatement, property.Type, pointer) + def, diags := use.Default(loweringContext, schemaStatement.Schema, pointer) property.Default = def - diags = append(diags, fillPropertyVisibility(loweringContext, property, use.Site(js.Schema).Chain(), pointer)...) - diags = append(diags, fillPropertyConstraints(loweringContext, property, js.Schema, use.FoldedAllOfEntries, pointer)...) - diags = append(diags, fillPropertyAnnotations(loweringContext, property, js.Schema, use, pointer)...) - return append(diags, PreserveRefSiteKeywords(loweringContext, ts, &property.Unmodeled, js, property.Type, pointer)...) + diags = append(diags, fillPropertyVisibility(loweringContext, property, use.Site(schemaStatement.Schema).Chain(), pointer)...) + diags = append(diags, fillPropertyConstraints(loweringContext, property, schemaStatement.Schema, use.FlattenedAllOfEntries, pointer)...) + var pendingKeeps annotation.PendingKeeps + diags = append(diags, fillPropertyAnnotations(loweringContext, property, &pendingKeeps, schemaStatement.Schema, use, pointer)...) + diags = append(diags, KeepRefSiteKeywords(loweringContext, types, &pendingKeeps, schemaStatement, property.Type, pointer, nil)...) + return append(diags, SettleCarrier(loweringContext, &property.Unmodeled, &pendingKeeps, pointer)...) } // fillPropertyVisibility lowers readOnly/writeOnly onto the property and reports @@ -61,13 +63,13 @@ func fillPropertyVisibility(loweringContext lowering.Ctx, property *ir.Property, // carrier at this position: a property's schema is read through CarriedRef, so // it hoists no node of its own to hold either. // -// It reads ref and its foldedEntries and never the $ref target, which is why +// It reads ref and its flattenedEntries and never the $ref target, which is why // no referent reaches it: bounds conjoin rather than override, so a referent's // bound merged here under use-site precedence would publish the wider of the // two as the whole truth. It stays on the node the reference points at instead // (docs/ir/annotations.md#what-a-reference-carries-down). -func fillPropertyConstraints(loweringContext lowering.Ctx, property *ir.Property, ref *statement.Schema, foldedEntries []annotation.FoldedAllOfEntry, pointer jsontext.Pointer) []ir.Diagnostic { - cons, diags := CarrierConstraintsOf(loweringContext, &property.Unmodeled, ref, foldedEntries, property.Type, pointer) +func fillPropertyConstraints(loweringContext lowering.Ctx, property *ir.Property, ref *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer) []ir.Diagnostic { + cons, diags := CarrierConstraintsOf(loweringContext, &property.Unmodeled, ref, flattenedEntries, property.Type, pointer) property.Constraints = cons return diags } @@ -84,41 +86,60 @@ func fillPropertyConstraints(loweringContext lowering.Ctx, property *ir.Property // // A $ref position never hoists a node, so annotations written beside a // property's $ref land here (GitHub #114). -func fillPropertyAnnotations(loweringContext lowering.Ctx, property *ir.Property, ref *statement.Schema, use Use, pointer jsontext.Pointer) []ir.Diagnostic { +func fillPropertyAnnotations(loweringContext lowering.Ctx, property *ir.Property, pendingKeeps *annotation.PendingKeeps, ref *statement.Schema, use Use, + pointer jsontext.Pointer, +) []ir.Diagnostic { if LoweredToOwnNode(loweringContext, pointer, property.Type) { return nil } - a, diags := ReadAnnotations(loweringContext, use.SiteAt(loweringContext, ref, pointer), pointer) + annotations, reports := ReadAnnotations(loweringContext, use.SiteAt(loweringContext, ref, pointer), pointer) - property.Docs = a.Docs - if a.Deprecated { + property.Docs = annotations.Docs + if annotations.Deprecated { property.Deprecation = &ir.Deprecation{} } - if a.Sensitive { + if annotations.Sensitive { property.Secret = true } - if a.XML != nil { - property.XML = a.XML + if annotations.XML != nil { + property.XML = annotations.XML } - if len(a.Examples) > 0 { - property.Examples = a.Examples + if len(annotations.Examples) > 0 { + property.Examples = annotations.Examples } - property.Unmodeled = annotation.MergeUnmodeled(property.Unmodeled, a.Unmodeled) - return append(diags, PreserveCarriedKeywords(loweringContext, &property.Unmodeled, ref, pointer)...) + kept := annotations.Unmodeled + reports = append(reports, KeepCarriedKeywords(loweringContext, &kept, ref, pointer)...) + return AddCarrierPendingKeeps(loweringContext, pendingKeeps, ref, pointer, kept, annotations.FlattenedEntries, reports) } -// PreserveCarriedKeywords keeps on unmodeled, a carrier's Unmodeled, what a +// AddCarrierPendingKeeps adds to pendingKeeps, a carrier's, what the schema +// written at pointer keeps there, kept and each of flattenedEntries apart, each +// with its reports, and returns the reports kept with none. +func AddCarrierPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, pointer jsontext.Pointer, + kept ir.Unmodeled, flattenedEntries []annotation.FlattenedEntryKept, reports annotation.KeptReports, +) []ir.Diagnostic { + diags := addPendingKeepsKeptAs(loweringContext, pendingKeeps, positionSite(pointer), kept, reports, annotation.KeptByReader, nil, false) + return append(diags, addFlattenedEntryPendingKeeps(loweringContext, pendingKeeps, schema, pointer, flattenedEntries)...) +} + +// SettleCarrier settles a carrier's pendingKeeps onto unmodeled, its +// Unmodeled, counting what it holds already as its schema's. +func SettleCarrier(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, pendingKeeps *annotation.PendingKeeps, pointer jsontext.Pointer) []ir.Diagnostic { + return settleOn(loweringContext, unmodeled, pendingKeeps, pointer) +} + +// KeepCarriedKeywords keeps on unmodeled, a carrier's Unmodeled, what a // schema that lowered to no node of its own wrote and no field of the carrier // holds: the content vocabulary, an unexpanded $dynamicRef and any keyword // nothing reads, which attachDeclaredAnnotations keeps on a node. It is one // call so that a property, a header and a parameter cannot differ in what they -// keep, and it runs last, as PreserveUnknownKeywords requires. -func PreserveCarriedKeywords(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { +// keep, and it runs last, as KeepUnknownKeywords requires. +func KeepCarriedKeywords(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) annotation.KeptReports { // nil node: only a schema with no node of its own comes here, so nothing here // can be carrying an Encoding. - diags := recordUnplacedContent(loweringContext, unmodeled, schema, nil, pointer) - diags = append(diags, recordUnexpandedDynamicRef(loweringContext, unmodeled, schema, pointer)...) - return append(diags, PreserveUnknownKeywords(loweringContext, unmodeled, schema, pointer, nil)...) + reports := recordUnplacedContent(loweringContext, unmodeled, schema, nil, pointer) + reports = append(reports, recordUnexpandedDynamicRef(loweringContext, unmodeled, schema, pointer)...) + return append(reports, KeepUnknownKeywords(loweringContext, unmodeled, schema, pointer, nil)...) } // PromoteUse reads the vendor extensions into the deprecation and redaction of a @@ -135,15 +156,16 @@ func PromoteUse(loweringContext lowering.Ctx, from promotion.Referent, unmodeled return append(diags, loweringContext.Promoter().Redaction(unmodeled, from, redact, prov)...) } -// FallbackKeysForCarrier returns what the mapped keys of what a carrier of js -// falls back to lend it, js written at pointer and lowered to typeRef -// (Use.fallbackKeys). A position owning a node lends its carrier none, as it -// lends no keyword: the node takes them (attachDeclaredAnnotations). -func FallbackKeysForCarrier(loweringContext lowering.Ctx, js *statement.Statement, typeRef ir.TypeRef, pointer jsontext.Pointer) promotion.Referent { - if js.Truth != statement.Stated || LoweredToOwnNode(loweringContext, pointer, typeRef) { +// FallbackKeysForCarrier returns what the mapped keys of what a carrier of +// schemaStatement falls back to lend it, schemaStatement written at pointer and +// lowered to typeRef (Use.fallbackKeys). A position owning a node lends its +// carrier none, as it lends no keyword: the node takes them +// (attachDeclaredAnnotations). +func FallbackKeysForCarrier(loweringContext lowering.Ctx, schemaStatement *statement.Statement, typeRef ir.TypeRef, pointer jsontext.Pointer) promotion.Referent { + if schemaStatement.Truth != statement.Stated || LoweredToOwnNode(loweringContext, pointer, typeRef) { return promotion.Referent{} } - return readUse(loweringContext, js, typeRef, pointer).fallbackKeys(loweringContext) + return UseOf(loweringContext, schemaStatement, typeRef, pointer).fallbackKeys(loweringContext) } // LoweredToOwnNode reports whether typeRef, what the declaration at pointer in diff --git a/compilers/openapi/internal/schema/property_test.go b/compilers/openapi/internal/schema/property_test.go index 25ae7fe2e..ef23183f0 100644 --- a/compilers/openapi/internal/schema/property_test.go +++ b/compilers/openapi/internal/schema/property_test.go @@ -248,13 +248,13 @@ func TestPropertyAnnotations_KeptWhenAnOutsideRefNamesTheProperty(t *testing.T) t.Parallel() owner := " A: {type: object, properties: {p: " + openapitest.InlineProbeBody + "}}\n" outsider := " Outsider: {$ref: '#/components/schemas/A/properties/p'}\n" - for _, tc := range []struct{ name, spec string }{ + for _, testCase := range []struct{ name, spec string }{ {"reference declared first", openapitest.ComponentSpec(outsider + owner)}, {"reference declared last", openapitest.ComponentSpec(owner + outsider)}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, tc.spec) + doc, diags := parseFull(t, testCase.spec) openapitest.RequireNoErrorDiags(t, diags) model, ok := doc.Types[componentID("A")].(*ir.Model) @@ -335,13 +335,13 @@ func TestPropertyAnnotations_CarriedWhenSchemaOwnsNoNode(t *testing.T) { // documentation merge, keyword by keyword: a property that declares nothing but // a $ref still carries what its referent documents, and the referent's own node // keeps its copy. The rule docs/compilers/openapi.md#ref-use-site asks for that -// merge uniformly, so the three keywords stand or fall together — a fix that +// merge uniformly, so the three keywords hold or fail together — a fix that // inherited only the description would leave the other two behind at every // carrier. func TestPropertyDocs_RefTargetReachesTheCarrier(t *testing.T) { t.Parallel() - for _, kw := range carrierDocKeywords() { - t.Run(kw.name, func(t *testing.T) { + for _, keyword := range carrierDocKeywords() { + t.Run(keyword.name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpec(docTarget()+ " Owner: {type: object, properties: {p: {$ref: '#/components/schemas/Target'}}}\n")) @@ -349,9 +349,9 @@ func TestPropertyDocs_RefTargetReachesTheCarrier(t *testing.T) { property := propertyOf(t, doc, "Owner", "p") assert.Equal(t, componentID("Target"), property.Type.Target, "a bare $ref needs no alias") - assert.Equal(t, "REF-"+kw.name, kw.read(property.Docs), "the carrier reads the referent's %s", kw.name) - assert.Equal(t, "REF-"+kw.name, kw.read(doc.Types[componentID("Target")].Common().Docs), - "and the referent keeps its own %s", kw.name) + assert.Equal(t, "REF-"+keyword.name, keyword.read(property.Docs), "the carrier reads the referent's %s", keyword.name) + assert.Equal(t, "REF-"+keyword.name, keyword.read(doc.Types[componentID("Target")].Common().Docs), + "and the referent keeps its own %s", keyword.name) }) } } @@ -372,12 +372,12 @@ func TestPropertyDocs_UseSiteWinsKeywordByKeyword(t *testing.T) { property := propertyOf(t, doc, "Owner", "p") assert.Equal(t, componentID("Target"), property.Type.Target, "a carrier hoists no alias for its siblings") - for _, kw := range carrierDocKeywords() { - want := "REF-" + kw.name - if kw.name == written.name { + for _, keyword := range carrierDocKeywords() { + want := "REF-" + keyword.name + if keyword.name == written.name { want = "SITE" } - assert.Equal(t, want, kw.read(property.Docs), "%s, with %s written at the site", kw.name, written.name) + assert.Equal(t, want, keyword.read(property.Docs), "%s, with %s written at the site", keyword.name, written.name) } }) } @@ -407,8 +407,8 @@ func TestFillPropertyDetail_SecretFollowsTheReferent(t *testing.T) { // another. func docTarget() string { parts := make([]string, 0, len(carrierDocKeywords())) - for _, kw := range carrierDocKeywords() { - parts = append(parts, kw.write("REF-"+kw.name)) + for _, keyword := range carrierDocKeywords() { + parts = append(parts, keyword.write("REF-"+keyword.name)) } return " Target: {type: string, " + strings.Join(parts, ", ") + "}\n" } diff --git a/compilers/openapi/internal/schema/reads.go b/compilers/openapi/internal/schema/reads.go index 24a8e6b7e..7ad677510 100644 --- a/compilers/openapi/internal/schema/reads.go +++ b/compilers/openapi/internal/schema/reads.go @@ -7,7 +7,6 @@ import ( "slices" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) @@ -80,14 +79,14 @@ func scalarTypeRead(schema *statement.Schema) keySet { // boundsRead returns the value bounds schema writes that a reader of the kinds // held reads: those of its kinds, a count the load phase refuses, which no -// reader holds, and one the reader kept on its node, unmodeled (keepCounts, +// reader holds, and one the reader kept on its node, unmodeled (keptCounts, // keepTextBounds). func boundsRead(schema *statement.Schema, held kindSet, unmodeled ir.Unmodeled) keySet { var out keySet - for _, k := range declaredConstraints(schema) { - _, kept := unmodeled[annotation.EntryKey("", k)] - if taken(held, k) || refusedCount(schema, k) || kept { - out |= keyBit(k) + for _, key := range declaredConstraints(schema) { + _, kept := unmodeled[annotation.EntryKey("", key)] + if taken(held, key) || refusedCount(schema, key) || kept { + out |= keyBit(key) } } return out @@ -95,12 +94,27 @@ func boundsRead(schema *statement.Schema, held kindSet, unmodeled ir.Unmodeled) // nodeBoundsRead is boundsRead for the reader of a node's Constraints, cons: // where it holds none, it read none of its kinds, as no field holds what it -// took, such as an empty pattern, and the node keeps the bound verbatim. +// took, such as an empty pattern, and the node keeps the bound verbatim. A +// count past what a field states it read all the same (countsAttempted). func nodeBoundsRead(schema *statement.Schema, held kindSet, cons *ir.Constraints, unmodeled ir.Unmodeled) keySet { + attempted := countsAttempted(schema, held) if cons == nil { held = 0 } - return boundsRead(schema, held, unmodeled) + return boundsRead(schema, held, unmodeled) | attempted +} + +// countsAttempted returns the counts schema writes past what a field states +// that a reader of the kinds held keeps verbatim or reports, so no other +// keeper attempts one again and each is reported once (GitHub #1895). +func countsAttempted(schema *statement.Schema, held kindSet) keySet { + var out keySet + for _, keyword := range valueCountKeywords { + if keptCount(schema, keyword, countOf(schema, keyword)) && taken(conjunctTakes(held, schema), keyword) { + out |= keyBit(keyword) + } + } + return out } // collectionReads returns the collection bounds schema writes that a List or a @@ -108,19 +122,19 @@ func nodeBoundsRead(schema *statement.Schema, held kindSet, cons *ir.Constraints // count a field states (keptCount). func collectionReads(schema *statement.Schema) keySet { out := keyBit("uniqueItems") - for _, k := range []string{"minItems", "maxItems"} { - if !keptCount(schema, k, countOf(schema, k)) { - out |= keyBit(k) + for _, key := range []string{"minItems", "maxItems"} { + if !keptCount(schema, key, countOf(schema, key)) { + out |= keyBit(key) } } return out } -// readElsewhere returns the keys of readDomain s writes that a reader outside -// the build of the node it lowers to reads: a redaction format, the annotation -// readers'; an additionalItems beside an items that is no list, the rest of -// nothing, the unknown keywords' keeper's (PreserveUnknownKeywords); and a type -// naming null alone, which the nulls reader reads as TypeRef.Nullable +// readElsewhere returns the keys of readDomain schema writes that a reader +// outside the build of the node it lowers to reads: a redaction format, the +// annotation readers'; an additionalItems beside an items that is no list, the +// rest of nothing, the unknown keywords' keeper's (KeepUnknownKeywords); and a +// type naming null alone, which the nulls reader reads as TypeRef.Nullable // (docs/compilers/openapi.md#null-alone). func readElsewhere(schema *statement.Schema) keySet { var out keySet @@ -136,22 +150,25 @@ func readElsewhere(schema *statement.Schema) keySet { return out } -// readBeside is readElsewhere for td, the node a position lowered to: the +// readBeside is readElsewhere for typeDef, the node a position lowered to: the // type of an Enum or a Literal is its own typing's to read (valueSetReads), // which the nulls reader leaves. -func readBeside(schema *statement.Schema, td ir.TypeDef) keySet { +func readBeside(schema *statement.Schema, typeDef ir.TypeDef) keySet { read := readElsewhere(schema) - if isKind(td, ir.KindEnum) || isKind(td, ir.KindLiteral) { + if isKind(typeDef, ir.KindEnum) || isKind(typeDef, ir.KindLiteral) { read &^= keyBit("type") } return read } // referenceReads returns what the alias or carrier of a position schema lowered -// to a reference reads (referenceConstraintsOf, CarrierConstraintsOf): the -// value bounds the types it admits take, and where they admit an array its -// collection bounds (boundHomes.reads). -func referenceReads(loweringContext lowering.Ctx, schema *statement.Schema) keySet { - takes := boundKinds(loweringContext, schema) - return boundHomes{value: takes, collection: takes&kindArray != 0}.reads(schema) +// to a reference reads, of homes, homesAt's for that position: the value bounds +// of homes.value, and the collection bounds schema writes itself, not +// homes.collection's of its flattened entries, where a reference holds them. +func referenceReads(schema *statement.Schema, homes boundHomes) keySet { + out := homes.valueReads(schema) + if referenceHoldsCollection(homes) { + out |= heldCollectionReads(schema) + } + return out } diff --git a/compilers/openapi/internal/schema/reads_internal_test.go b/compilers/openapi/internal/schema/reads_internal_test.go index b8e22b123..26fd3b49a 100644 --- a/compilers/openapi/internal/schema/reads_internal_test.go +++ b/compilers/openapi/internal/schema/reads_internal_test.go @@ -18,8 +18,8 @@ func TestKeySet_HoldsTheReadDomainAlone(t *testing.T) { t.Parallel() all := keySetOf(readDomain...) assert.Equal(t, len(readDomain), bits.OnesCount32(uint32(all)), "each key has a bit of its own") - for _, k := range readDomain { - assert.True(t, keySetOf(k).has(k), "%s has a bit", k) + for _, key := range readDomain { + assert.True(t, keySetOf(key).has(key), "%s has a bit", key) } assert.Zero(t, keyBit("description"), "a key outside the domain has no bit") assert.False(t, all.has("description")) diff --git a/compilers/openapi/internal/schema/reads_test.go b/compilers/openapi/internal/schema/reads_test.go index 8ee5ebe13..3db6e6e23 100644 --- a/compilers/openapi/internal/schema/reads_test.go +++ b/compilers/openapi/internal/schema/reads_test.go @@ -44,8 +44,8 @@ func TestUnread_KeepsWhatNoBuildRead(t *testing.T) { t.Run("every key is read, handled or kept", func(t *testing.T) { domain := schema.ReadDomain() for _, in := range inputs { - for _, js := range in.statements { - assertEveryKeyIsReadOrKept(t, js.Schema, domain) + for _, schemaStatement := range in.statements { + assertEveryKeyIsReadOrKept(t, schemaStatement.Schema, domain) } } }) @@ -54,27 +54,29 @@ func TestUnread_KeepsWhatNoBuildRead(t *testing.T) { // assertNoKeyIsBothReadAndKept holds each node of doc to keeping only what no // build read: no key holding schemas that a node keeps verbatim has a node or // a property built from what it holds. A builder omitting a key it read would -// keep a key it typed. +// keep a key it typed. A model's catch-all over members its own object does not +// declare is the one key typed and kept both, by design +// (docs/compilers/openapi.md#additional-properties). func assertNoKeyIsBothReadAndKept(t *testing.T, doc *ir.Document) { t.Helper() built := map[string]bool{} - for _, td := range doc.Types { - built[string(td.Common().Provenance.Pointer)] = true - if model, ok := td.(*ir.Model); ok { + for _, typeDef := range doc.Types { + built[string(typeDef.Common().Provenance.Pointer)] = true + if model, ok := typeDef.(*ir.Model); ok { for _, property := range model.Properties { built[string(property.Provenance.Pointer)] = true } } } - for id, td := range doc.Types { - for _, k := range applicators { - entry, kept := td.Common().Unmodeled["openapi:"+k] - if !kept { + for id, typeDef := range doc.Types { + for _, key := range applicators { + entry, kept := typeDef.Common().Unmodeled["openapi:"+key] + if _, model := typeDef.(*ir.Model); !kept || model && (key == "additionalProperties" || key == "patternProperties") { continue } prefix := string(entry.Provenance.Pointer) + "/" for at := range built { - assert.False(t, strings.HasPrefix(at, prefix), "%s keeps %s and %s was built from it", id, k, at) + assert.False(t, strings.HasPrefix(at, prefix), "%s keeps %s and %s was built from it", id, key, at) } } } @@ -86,20 +88,20 @@ func assertNoKeyIsBothReadAndKept(t *testing.T, doc *ir.Document) { func assertEveryKeyIsReadOrKept(t *testing.T, statementSchema *statement.Schema, domain []string) { t.Helper() var written []string - for _, k := range domain { - if _, read := statementSchema.Key(k); read { - written = append(written, k) + for _, key := range domain { + if _, read := statementSchema.Key(key); read { + written = append(written, key) } } assert.Equal(t, written, nilIfEmpty(schema.UnreadKeys(statementSchema, nil)), "%s: nothing read keeps every key", statementSchema.At.Pointer) assert.Empty(t, schema.UnreadKeys(statementSchema, domain), "%s: everything read keeps nothing", statementSchema.At.Pointer) even := make([]string, 0, len(written)) var odd []string - for i, k := range written { + for i, key := range written { if i%2 == 0 { - even = append(even, k) + even = append(even, key) } else { - odd = append(odd, k) + odd = append(odd, key) } } assert.Equal(t, odd, nilIfEmpty(schema.UnreadKeys(statementSchema, even)), "%s: a key read is the one not kept", statementSchema.At.Pointer) @@ -139,11 +141,11 @@ func TestUnread_EveryKeyShapesOrIsKept(t *testing.T) { } for _, target := range keyTargets { alone := types(target, "") - for _, k := range schema.ReadDomain() { - if k == "type" || strings.Contains(target, k+":") { + for _, key := range schema.ReadDomain() { + if key == "type" || strings.Contains(target, key+":") { continue } - assert.NotEqual(t, alone, types(target, ", "+k+": "+keyValues[k]), "%s beside %s changes nothing", k, target) + assert.NotEqual(t, alone, types(target, ", "+key+": "+keyValues[key]), "%s beside %s changes nothing", key, target) } } } @@ -195,15 +197,16 @@ func readSources(t *testing.T) []compilers.Source { // TestUnread_EdgesCompileAsTheyDid pins what the documents readEdges adds // compile to, which the keeping of unread keywords decides and the builds' -// reads must keep: the empty pattern no variant holds is kept on the union, and -// the type an enum's members all are values of says nothing the Enum does not. +// reads must keep: the empty pattern, which matches every string, says +// nothing, so neither a variant nor the union holds it, and the type an enum's +// members all are values of says nothing the Enum does not. func TestUnread_EdgesCompileAsTheyDid(t *testing.T) { t.Parallel() doc, _ := schema.LowerSpec(t, string(readEdges()[0].Data)) pattern := doc.Types[ids.DocumentIDNamespace{}.ForPointer(ids.Ptr("components", "schemas", "EmptyPattern"))] require.NotNil(t, pattern) assert.Equal(t, ir.KindUnion, pattern.Kind()) - assert.Contains(t, pattern.Common().Unmodeled, "openapi:pattern", "no variant holds the empty pattern") + assert.NotContains(t, pattern.Common().Unmodeled, "openapi:pattern", "the empty pattern is the keyword left out") enum, ok := doc.Types[ids.DocumentIDNamespace{}.ForPointer(ids.Ptr("components", "schemas", "EnumOfTypes"))].(*ir.Enum) require.True(t, ok, "the members are of one kind") assert.Equal(t, ir.PrimitiveString, enum.ValueType) @@ -211,9 +214,10 @@ func TestUnread_EdgesCompileAsTheyDid(t *testing.T) { } // readEdges returns the documents of what reaches a site keeping unread -// keywords no document under testdata or core case does: an empty pattern -// beside a type list whose string variant is a Scalar of its own, and an enum -// whose members are all values of the several types beside it. +// keywords no document under testdata or core case does: an empty pattern, +// which says nothing, beside a type list whose string variant is a Scalar of +// its own, and an enum whose members are all values of the several types +// beside it. func readEdges() []compilers.Source { const spec = `openapi: 3.1.0 info: {title: t, version: "1"} diff --git a/compilers/openapi/internal/schema/refbounds.go b/compilers/openapi/internal/schema/refbounds.go new file mode 100644 index 000000000..31117810e --- /dev/null +++ b/compilers/openapi/internal/schema/refbounds.go @@ -0,0 +1,129 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/merge" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// referred is what a position reaches through the $refs among its conjuncts +// (referredOf): conjunctList, each schema such a $ref lands on and its inline +// entries, on along every $ref they write; own, the position's own inline +// conjuncts; and cut, whether the walk passed maxAdmissionReads schemas. +type referred struct { + conjunctList, own []*statement.Schema + cut bool +} + +// referredOf returns what position reaches through its $refs, each schema once, +// in the order the source writes the $refs, so the bounds of a $ref's target +// bind the position as an allOf entry's do +// (docs/compilers/openapi.md#constraints). +func referredOf(loweringContext lowering.Ctx, position *statement.Schema) referred { + schemaStatement := loweringContext.Statements().Read(position) + seen := map[*statement.Statement]bool{schemaStatement: true} + var work []*statement.Statement + follow := func(from *statement.Statement) { + if next, _ := declaredOf(loweringContext, from); next != nil && !seen[next] { + seen[next] = true + work = append(work, next) + } + } + conjuncts := func(from *statement.Statement) []*statement.Schema { + follow(from) + for ref := range allOfRefEntries(loweringContext, from.Schema) { + follow(ref) + } + return inlineConjuncts(loweringContext, from.Schema) + } + out := referred{own: conjuncts(schemaStatement)} + reads := budget.New(budget.AtMost(maxAdmissionReads)) + for len(work) > 0 && !out.cut { + next := work[0] + work = work[1:] + out.cut = !reads.Spend(1) + if !out.cut && stated(next.Schema) { + out.conjunctList = append(out.conjunctList, conjuncts(next)...) + } + } + return out +} + +// constraints returns the value bounds of the kinds takes that r's conjuncts +// write, read and intersected as allOf entries' are. What the reading reports +// or keeps is the target's own node's to say. +func (r referred) constraints(loweringContext lowering.Ctx, takes kindSet) *ir.Constraints { + var out *ir.Constraints + for _, conjunctSchema := range r.conjunctList { + var scratch ir.Unmodeled + written, _ := constraintsAt(loweringContext, &scratch, conjunctSchema, conjunctSchema.At.Pointer, boundsFor(conjunctTakes(takes, conjunctSchema))) + out = merge.Constraints(out, written) + } + return out +} + +// textKept keeps verbatim, where it is written, each bound of homes.heldText +// (heldTextKept) that one of r's conjuncts alone writes, reported at pointer. A +// bound several write stays with the $refs kept verbatim, as one several +// entries write keeps each entry whole. +func (r referred) textKept(loweringContext lowering.Ctx, homes boundHomes, pointer jsontext.Pointer) (ir.Unmodeled, annotation.KeptReports) { + var kept ir.Unmodeled + var reports annotation.KeptReports + for _, keyword := range valueConstraintKeywords { + if !homes.heldText.has(keyword) { + continue + } + conjunctSchema, alone := r.soleConjunct(keyword) + if !alone { + continue + } + there, _, _ := placedAt(loweringContext, conjunctSchema) + if ok, keptDiags := keepSchemaKeyword(there, &kept, conjunctSchema, keyword, ir.ReasonNoIRHome, conjunctSchema.At.Pointer); ok { + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), append(keptDiags, + loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, pointer, + "%s, written by a schema a $ref of this one reaches,%s; kept verbatim under Unmodeled", keyword, homes.root.boundsNone(keyword)))...)...) + } + } + return kept, reports +} + +// soleConjunct returns the one conjunct of r writing keyword, and false where +// none or several do, or where a schema of the position's own conjunction +// writes it too. +func (r referred) soleConjunct(keyword string) (*statement.Schema, bool) { + if slices.ContainsFunc(r.own, func(own *statement.Schema) bool { return hasKey(own, keyword) }) { + return nil, false + } + var sole *statement.Schema + for _, conjunctSchema := range r.conjunctList { + if !hasKey(conjunctSchema, keyword) { + continue + } + if sole != nil { + return nil, false + } + sole = conjunctSchema + } + return sole, sole != nil +} + +// walkCutReport is the info drawn at pointer where r's walk was cut, worded as +// a refinement's cut read is (outcomeKeeps.reportCutRead). +func (r referred) walkCutReport(loweringContext lowering.Ctx, pointer jsontext.Pointer) []ir.Diagnostic { + if !r.cut { + return nil + } + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + "the reading of the schemas this schema's $refs reach passed the %d schemas one reading takes in, so the "+ + "bounds of those past it are not held by the node it lowers to", maxAdmissionReads)} +} diff --git a/compilers/openapi/internal/schema/refbounds_test.go b/compilers/openapi/internal/schema/refbounds_test.go new file mode 100644 index 000000000..bfc4fecdc --- /dev/null +++ b/compilers/openapi/internal/schema/refbounds_test.go @@ -0,0 +1,133 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "maps" + "slices" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// refBoundSchemas are the targets the tests below reach by a $ref, each +// writing a length of 3 its own way, and the positions naming them beside a +// value set: through an alias, a $ref with the bound beside it, an allOf +// entry, and, beside a union of value sets, the bounded string. +var refBoundSchemas = []string{ + "T: {type: string, maxLength: 3}", + "Alias: {$ref: '#/components/schemas/T'}", + "U: {type: string}", + "Chain: {$ref: '#/components/schemas/U', maxLength: 3}", + "Entries: {allOf: [{type: string}, {maxLength: 3}]}", + "ByAlias: {$ref: '#/components/schemas/Alias', enum: [a, abcd]}", + "ByChain: {allOf: [{$ref: '#/components/schemas/Chain'}, {enum: [a, abcd]}]}", + "ByEntries: {$ref: '#/components/schemas/Entries', minLength: 2, enum: [a, ab, abcd]}", + "Meet: {$ref: '#/components/schemas/T', oneOf: [{const: a}, {const: abcd}]}", +} + +// TestRefBounds_AValueSetHoldsTheBoundsItsRefsReach pins that a value set +// beside a $ref holds the bounds the $ref reaches, along an alias, a $ref +// with the bound beside it and an allOf's entries, intersected with its own, in +// either order of the components: the Enum's Constraints hold them, each $ref +// kept verbatim, and a union of value sets beside the $ref leaves out the +// member they refuse, reported where it is written. +func TestRefBounds_AValueSetHoldsTheBoundsItsRefsReach(t *testing.T) { + t.Parallel() + for _, schemas := range [][]string{refBoundSchemas, reversedEntries(refBoundSchemas)} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " "+strings.Join(schemas, "\n ")+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + enums := map[string]*ir.Enum{} + for _, name := range []string{"ByAlias", "ByChain", "ByEntries", "Meet"} { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, name) + require.NotNil(t, enum.Constraints, name) + assert.Equal(t, int64(3), *enum.Constraints.MaxLength, name) + assert.Contains(t, enum.Unmodeled, "openapi:$ref", name) + enums[name] = enum + } + assert.Equal(t, new(int64(2)), enums["ByEntries"].Constraints.MinLength, "the set's own bound intersects the target's") + assert.Len(t, enums["Meet"].Members, 1, "the member the target's length refuses is left out") + refused := withCode(diags, diag.UnsatisfiableSchema) + require.Len(t, refused, 1) + assert.Equal(t, "/components/schemas/Meet/oneOf/1/const", string(refused[0].Provenance.Pointer)) + } +} + +// TestRefBounds_ATextBoundReachesTheEnumWhereOneConjunctWritesIt pins a length +// beside an instant, which the Enum keeps verbatim: reached from a $ref's +// target alone, it is kept where it is written, with one info at the +// position; beside the set's own, the Enum keeps that one; and where two +// targets write it, neither, as two allOf entries writing it are each kept +// whole. Each $ref stays kept verbatim, in either order of the components. +func TestRefBounds_ATextBoundReachesTheEnumWhereOneConjunctWritesIt(t *testing.T) { + t.Parallel() + const instant = "enum: ['2020-01-01T00:00:00Z']" + schemas := []string{ + "Instant: {type: string, format: date-time, maxLength: 30}", + "Shorter: {type: string, format: date-time, maxLength: 25}", + "Alone: {$ref: '#/components/schemas/Instant', " + instant + "}", + "Own: {$ref: '#/components/schemas/Instant', maxLength: 25, " + instant + "}", + "Two: {allOf: [{$ref: '#/components/schemas/Instant'}, {$ref: '#/components/schemas/Shorter'}, {" + instant + "}]}", + } + for _, order := range [][]string{schemas, reversedEntries(schemas)} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " "+strings.Join(order, "\n ")+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + kept := func(name string) map[string]string { + out := map[string]string{} + for key, entry := range typeByName(doc, name).Common().Unmodeled { + out[key] = string(entry.Value) + " " + string(entry.Provenance.Pointer) + } + return out + } + assert.Equal(t, "30 /components/schemas/Instant/maxLength", kept("Alone")["openapi:maxLength"]) + assert.Equal(t, "25 /components/schemas/Own/maxLength", kept("Own")["openapi:maxLength"]) + assert.Equal(t, []string{"openapi:$ref/0", "openapi:$ref/1"}, slices.Sorted(maps.Keys(kept("Two")))) + unhomed := withCode(diags, diag.UnhomedConstruct) + at := make([]string, 0, len(unhomed)) + for _, diagnostic := range unhomed { + at = append(at, string(diagnostic.Provenance.Pointer)) + } + slices.Sort(at) + assert.Equal(t, []string{"/components/schemas/Alone", "/components/schemas/Instant/maxLength", + "/components/schemas/Own/maxLength", "/components/schemas/Shorter/maxLength"}, at) + } +} + +// TestRefBounds_AWalkPastItsBoundIsReported pins that the walk of the schemas +// a value set's $refs reach stops past maxAdmissionReads, 256, with one info +// at the position saying so, where a walk within it draws none: the $ref +// reaches an allOf of 257 $refs, or of 255. A deep chain is valid, so the +// cut draws no error. +func TestRefBounds_AWalkPastItsBoundIsReported(t *testing.T) { + t.Parallel() + for _, wide := range []int{255, 257} { + schemas := []string{"Set: {$ref: '#/components/schemas/Wide', enum: [a, abcd]}"} + entries := make([]string, 0, wide) + for i := range wide { + schemas = append(schemas, "W"+strconv.Itoa(i)+": {type: string, maxLength: 3}") + entries = append(entries, "{$ref: '#/components/schemas/W"+strconv.Itoa(i)+"'}") + } + schemas = append(schemas, "Wide: {allOf: ["+strings.Join(entries, ", ")+"]}") + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " "+strings.Join(schemas, "\n ")+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + cut := slices.DeleteFunc(withCode(diags, diag.DegradedConstruct), func(diagnostic ir.Diagnostic) bool { + return !strings.Contains(diagnostic.Message, "this schema's $refs reach passed the 256 schemas") + }) + if wide < 256 { + assert.Empty(t, cut, "a walk of %d schemas", wide+1) + continue + } + require.Len(t, cut, 1, "a walk past its bound") + assert.Equal(t, "/components/schemas/Set", string(cut[0].Provenance.Pointer)) + assert.Equal(t, ir.SeverityInfo, cut[0].Severity) + } +} diff --git a/compilers/openapi/internal/schema/refchain.go b/compilers/openapi/internal/schema/refchain.go new file mode 100644 index 000000000..b1db4d712 --- /dev/null +++ b/compilers/openapi/internal/schema/refchain.go @@ -0,0 +1,158 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "iter" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// refBranchTarget returns the schema the run of $refs from branch, an allOf +// entry or a union branch, ends on (runEnd), and nil where branch writes no +// $ref. Where the run ends on no schema object it returns one that is none +// (stated). +func refBranchTarget(loweringContext lowering.Ctx, branch *statement.Statement) *statement.Schema { + if branch.Ref == nil { + return nil + } + if end, ok := runEnd(loweringContext, branch); ok { + return end.Schema + } + return loweringContext.Statements().Read(nil).Schema +} + +// maxRefHops bounds the $refs a walk reads of a chain the bindings resolve no +// end for, running into a loop or failing at a hop, each reported where it is +// written; one they resolve is read to its end (reftable.Chain.Hops). +const maxRefHops = 64 + +// chainStep is a statement a walk reaches: its start, with no from, or where +// the $ref from writes lands, at at, nil where it lands on none. +type chainStep struct { + statement, from *statement.Statement + at reftable.DocumentPointer +} + +// refChain yields start, then each statement the chain of $refs from it lands +// on, each $ref read alone or beside keywords (referenceOf) through its first +// hop (declaredOf), ending at a statement writing none or after a hop landing +// on none. A reader stops it where its own rule says. +func refChain(loweringContext lowering.Ctx, start *statement.Statement) iter.Seq[chainStep] { + return func(yield func(chainStep) bool) { + from, hops := referenceOf(loweringContext, start), maxRefHops + if from != nil && from.Ref.Bound && from.Ref.Entry.Chain.Status == reftable.Resolved { + hops = from.Ref.Entry.Chain.Hops + } + if !yield(chainStep{statement: start}) { + return + } + for ; from != nil && hops > 0; hops-- { + to, at := declaredOf(loweringContext, from) + if !yield(chainStep{statement: to, from: from, at: at}) || to == nil { + return + } + from = referenceOf(loweringContext, to) + } + } +} + +// runEnd returns the statement the run of $refs from schemaStatement ends on: +// the first schema it reaches writing no $ref, or writing keys beside one, +// which conjoins the two rather than naming one (statement.Schema.BesideRef), +// whether or not the chain the bindings follow past it resolves. It is false +// where a hop before it lands on no schema, and for a loop of $refs. +func runEnd(loweringContext lowering.Ctx, schemaStatement *statement.Statement) (*statement.Statement, bool) { + for step := range refChain(loweringContext, schemaStatement) { + if step.from != nil && (step.statement == nil || step.statement.Ref == nil) { + return step.statement, step.statement != nil + } + } + return nil, false +} + +// declaredOf returns the statement of the schema written where +// schemaStatement's $ref lands, as the bindings resolved its first hop +// (typed.Bindings.DeclaredAt), and the position it lands at; nil and the zero +// position where it lands on none. +func declaredOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) (*statement.Statement, reftable.DocumentPointer) { + if schemaStatement.Ref == nil || !schemaStatement.Ref.Bound || schemaStatement.Ref.Entry.Hop.Status != reftable.Resolved { + return nil, reftable.DocumentPointer{} + } + return loweringContext.Statements().At(schemaStatement.Ref.Entry.Hop.Target), schemaStatement.Ref.Entry.Hop.Target +} + +// declared returns the statement declaredOf does, and an Unwritten one where +// the $ref lands on none. +func declared(loweringContext lowering.Ctx, schemaStatement *statement.Statement) *statement.Statement { + if schemaStatement, _ := declaredOf(loweringContext, schemaStatement); schemaStatement != nil { + return schemaStatement + } + return loweringContext.Statements().Read(nil) +} + +// siteOf returns the position the bindings read schema at, and false for a +// schema they do not place, which the statement reads at the zero position. +func siteOf(schema *statement.Schema) (reftable.DocumentPointer, bool) { + if schema == nil || schema.At == (reftable.DocumentPointer{}) { + return reftable.DocumentPointer{}, false + } + return schema.At, true +} + +// refKeyword returns the keyword schemaStatement is a reference site under +// (typed.Bindings.RefKeyword), "" for one writing no reference. +func refKeyword(schemaStatement *statement.Statement) string { + if schemaStatement.Ref == nil { + return "" + } + return schemaStatement.Ref.Keyword +} + +// writesConjuncts reports whether schema says what an allOf says: it writes +// one, or it is the rest of an object writing a reference beside it, whose +// conjuncts are the reference and the rest (statement.Schema.BesideRef). +func writesConjuncts(schema *statement.Schema) bool { + return schema != nil && (len(schema.AllOf) > 0 || schema.BesideRef != nil) +} + +// conjunctsIn returns the statements of the conjuncts schema writes beside its +// own keywords, unflattened: the reference written beside them +// (writesConjuncts), then each schema its allOf lists. +func conjunctsIn(loweringContext lowering.Ctx, schema *statement.Schema) []*statement.Statement { + if schema == nil { + return nil + } + out := make([]*statement.Statement, 0, 1+len(schema.AllOf)) + if schema.BesideRef != nil { + out = append(out, loweringContext.Statements().Read(schema.BesideRef)) + } + for _, branch := range schema.AllOf { + out = append(out, loweringContext.Statements().Subschema(branch)) + } + return out +} + +// referenceOf returns the statement of the $ref schemaStatement writes, alone +// or beside its keywords (statement.Schema.BesideRef), and nil where it writes +// none. +func referenceOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) *statement.Statement { + switch { + case schemaStatement.Ref != nil: + return schemaStatement + case schemaStatement.BesideRef != nil: + return loweringContext.Statements().Read(schemaStatement.BesideRef) + default: + return nil + } +} + +// refWritten reports whether schema writes `$ref`, as the parser's model holds +// it: a reference site under that keyword, not a $dynamicRef the bindings read +// as one (statement.Reference). +func refWritten(schema *statement.Schema) bool { + return schema != nil && schema.Ref != nil && schema.Ref.Keyword == "$ref" +} diff --git a/compilers/openapi/internal/schema/branch_internal_test.go b/compilers/openapi/internal/schema/refchain_internal_test.go similarity index 97% rename from compilers/openapi/internal/schema/branch_internal_test.go rename to compilers/openapi/internal/schema/refchain_internal_test.go index fdb8300c2..365d1c184 100644 --- a/compilers/openapi/internal/schema/branch_internal_test.go +++ b/compilers/openapi/internal/schema/refchain_internal_test.go @@ -39,8 +39,8 @@ func TestRefKeyword_NamesTheKeywordOfAReferenceSite(t *testing.T) { `)) entries := StatedIn(lowerer, componentSchema(t, lowerer, "M")).AllOf got := make([]string, 0, len(entries)) - for _, b := range entries { - got = append(got, refKeyword(lowerer.Ctx.Statements().Subschema(b))) + for _, branch := range entries { + got = append(got, refKeyword(lowerer.Ctx.Statements().Subschema(branch))) } assert.Equal(t, []string{"$ref", "$dynamicRef", ""}, got) } diff --git a/compilers/openapi/internal/schema/refinement.go b/compilers/openapi/internal/schema/refinement.go index 1e8dcdf27..752409723 100644 --- a/compilers/openapi/internal/schema/refinement.go +++ b/compilers/openapi/internal/schema/refinement.go @@ -14,64 +14,53 @@ import ( "github.com/dexpace/morphic/ir" ) -// lowerPrincipal lowers the entry r uses where s, written at pointer, refines. -// A $ref goes through Ref, as fillRefEntry's does, keeping the alias what is -// written beside it always has, in a frame of its own. An inline entry lowers -// by its own keywords, its node standing at pointer for the whole conjunction, -// finished by fin, its children and the reports on what it writes where they are -// written (docs/compilers/openapi.md#allof-refinement). A $ref the principal beat -// is still resolved: nothing else may lower what it names. -func lowerPrincipal(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, refinementValue refinement, - fin finisher, -) (ir.TypeID, []ir.Diagnostic) { +// lowerPrincipal lowers refinementValue's principal where schema, written at +// pointer, refines (docs/compilers/openapi.md#allof-refinement): an inline +// entry's node stands at pointer for the whole conjunction, its children and +// reports where they are written. +func lowerPrincipal(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, refinementValue refinement, +) (builtPosition, []ir.Diagnostic) { entry := refinementValue.principal - resolveBeaten(loweringContext, ts, refinementValue) + resolvePassedOverRefs(loweringContext, types, refinementValue) if entry.schema.Ref != nil { - ref, diags := schemaRefHomed(loweringContext, ts, depth, entry.schema, entry.pointer, annotation.HomeOwnNode) - return ref.Target, diags - } - // The node keeps the content vocabulary the entry writes where it holds - // none, as the entry's own node would (recordUnplacedContent). - var content, built []ir.Diagnostic - st := stand{of: schema, at: pointer} - // What the principal's build kept on the node itself is held back while - // the position writes, the last of the principal's to leave and the first - // kept again. - outside := fin - position := finisher(func(td ir.TypeDef, read keySet, held *principalKept) { - built = keepBuiltAround(loweringContext, st, td, read, held, entry.schema.Schema, entry.pointer, outside) - }) - fin = func(td ir.TypeDef, read keySet, held *principalKept) { - keeping := unplacedContent(loweringContext, entry.schema.Schema, td, entry.pointer) - content = keepAround(loweringContext, ts, st, td, read, held, entry.schema.Schema, entry.pointer, keeping, position) - } - ref, diags := lowerSchemaBody(loweringContext, ts, depth, entry.schema.Schema, entry.pointer, fin, st) - return ref.Target, slices.Concat(missingArrayItemsConjoined(loweringContext, entry.schema.Schema, entry.pointer), diags, built, content) + ref, diags := schemaRefHomed(loweringContext, types, depth, entry.schema, entry.pointer, annotation.HomeOwnNode) + return builtPosition{id: ref.Target}, diags + } + placement := nodePlacement{position: schema, positionPointer: pointer, homes: boundsHeldAt(loweringContext, schema, pointer), flatSpellingType: refinementValue.besideRef.flatSpellingTypeOf(entry.schema.Schema)} + built, ref, bodyDiags, afterDiags := lowerSchemaBody(loweringContext, types, depth, entry.schema.Schema, entry.pointer, placement) + diags := slices.Concat(bodyDiags, afterDiags) + if built.node != nil { + // The node keeps the content vocabulary the entry writes where it holds + // none, as the entry's own node would (recordUnplacedContent). + keeping := unplacedContent(loweringContext, entry.schema.Schema, built.node, entry.pointer) + diags = append(diags, keepAround(loweringContext, placement, &built, entry.schema.Schema, entry.pointer, keeping)...) + } else { + built.id = ref.Target + } + return built, diags } -// resolveBeaten resolves each $ref of refinementValue but its principal: -// nothing else may lower what a $ref the principal beat names. -func resolveBeaten(loweringContext lowering.Ctx, ts *compile.Types, refinementValue refinement) { +// resolvePassedOverRefs resolves each $ref of refinementValue but its +// principal: nothing else may lower what a $ref the principal was chosen over +// names. +func resolvePassedOverRefs(loweringContext lowering.Ctx, types *compile.Types, refinementValue refinement) { for _, entry := range refinementValue.comp.entries { if entry.schema.Ref != nil && !refinementValue.principalIs(entry) { - resolveSchemaRef(loweringContext, ts, entry.schema) + resolveSchemaRef(loweringContext, types, entry.schema) } } } // refinedShape describes what the position the refinement of comp decides // lowered to, for the reports of what it keeps and of conjuncts sharing no -// value, principal being the entry elected and standing the node the position -// owns, nil for none. Only a $ref principal makes it a use of a conjunct, named -// as comp's subject names them; electing none lowers by the keywords beside -// them (undecidedShape); an inline principal is named as written alone: the -// reference it collapses or expands to (referenceOutcomeKeywords), its node as -// its builder names it (held), else the node standing or the -// shared primitive. -func refinedShape(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, principal *allOfEntry, standing ir.TypeDef, - held *principalKept, +// value: a use of a conjunct for a $ref principal, and for an inline one what +// it lowers to written alone. +func refinedShape(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, principal *allOfEntry, positionNode ir.TypeDef, + named string, ) string { switch { + case principal == nil && decisionOf(loweringContext, schema).outcome == decisionRefinesNullIntersection: + return nodeShape(ir.KindEnum) case principal == nil: return undecidedShape case principal.schema.Ref != nil && comp.subject() == "this schema": @@ -79,47 +68,56 @@ func refinedShape(loweringContext lowering.Ctx, schema *statement.Schema, comp a case principal.schema.Ref != nil: return "a use of one of its allOf conjuncts" } - if electsOneOfPair(loweringContext, schema) { - // The union passed over conjoins, so the elected one collapses no more - // than one schema writing both does (pairedPrincipal). - if _, ok := standing.(*ir.Union); ok { - _, key, _ := unionBranches(loweringContext, schema, principal.schema.Schema) - return "the Union of its " + key + if entryUnionPassesOverAnother(loweringContext, schema) { + // The union passed over conjoins, so the chosen one collapses no more + // than one schema writing both does (passesOverAnother). + if _, ok := positionNode.(*ir.Union); ok { + key := loweredKeyword(loweringContext, schema, principal.schema.Schema) + return "the Union of its " + string(key) } - } else if _, shape := referenceOutcomeKeywords(loweringContext, principal.schema.Schema, principal.pointer); shape != "" { + } else if shape, _ := referenceOutcome(loweringContext, principal.schema.Schema, principal.pointer); shape == expandedShape || + shape == collapsedShape && unionCollapses(loweringContext, schema, principal.schema.Schema) { + // A union the position's conjunction leaves null alone or with a dead + // branch is no collapse there, however it reads alone. return shape } - if named := held.named(); named != "" { + if named != "" { return named } - if standing != nil { - return nodeShape(standing.Kind()) + if positionNode != nil { + return nodeShape(positionNode.Kind()) } - return nodeShape(ir.KindPrimitive) + return nodeShape(ir.KindScalar) } // primitiveKinds are the kinds a primitive holds. const primitiveKinds = kindString | kindNumber | kindBoolean -// undecidedTypes returns the types s lowers by where its allOf refines electing -// no entry: the kinds its conjuncts admit together, null aside (lowersTo), and -// where they state value sets of the members those share (sharedKinds), in one -// order whatever the order written. It returns none where those are none, as -// for sets sharing no member, or hold an object or an array, whose shape no -// entry was elected to give, every kind among them, or the kind-inference -// policy read them, as it reads only those: the position is then the top -// type. The decision turns on no pointer (decisionAt). +// undecidedTypes returns the types schema lowers by where its allOf refines +// choosing no entry: the kinds its conjuncts admit together, null aside, in +// one order whatever the order written. It returns none, the top type, for +// kinds holding an object or an array, or inferred, unless a bound cut named +// them. func undecidedTypes(loweringContext lowering.Ctx, schema *statement.Schema) []statement.JSONSchemaTypeName { decision := decisionOf(loweringContext, schema) - if !decision.refines || decision.principalAt >= 0 { + // A principal the keywords beside the allOf are chooses no entry, so the + // types are read here as where none is chosen. + if _, principalIsEntry := namedEntry(decision.principal()); !decision.refines() || principalIsEntry || decision.outcome == decisionRefinesKeepingAllOfWhole { return nil } kinds, inferred := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) - kinds &= sharedKinds(decision.r.joint) &^ kindNull - if kinds == 0 || kinds&^primitiveKinds != 0 || inferred { + kinds &= sharedKinds(decision.refinement.admittedTogether) &^ kindNull + named := decision.refinement.kindsNamed && kinds != everyKindButNull + if kinds == 0 || !named && (kinds&^primitiveKinds != 0 || inferred) { return nil } var out []statement.JSONSchemaTypeName + if kinds&kindObject != 0 { + out = append(out, statement.KindObject) + } + if kinds&kindArray != 0 { + out = append(out, statement.KindArray) + } if kinds&kindString != 0 { out = append(out, statement.KindString) } @@ -136,22 +134,21 @@ func undecidedTypes(loweringContext lowering.Ctx, schema *statement.Schema) []st return out } -// sharedKinds returns the kinds of what joint, what the conjuncts of a -// refinement admit together as its election reads them, holds: where they -// state value sets, the kinds of the members every set shares, as an instance -// meets each set only as a member of it; else its kinds. -func sharedKinds(joint admitted) kindSet { - if !joint.fixed { - return joint.kinds +// sharedKinds returns the kinds admittedTogether holds: where the conjuncts +// state value sets, the kinds of the members they share, as an instance +// satisfies each set only as a member of it. +func sharedKinds(admittedTogether admitted) kindSet { + if !admittedTogether.fixed { + return admittedTogether.kinds } var out kindSet - for _, kind := range joint.members { + for _, kind := range admittedTogether.members { out |= kind } return out } -// undecidedShape describes what a refinement electing no entry lowers to, for +// undecidedShape describes what a refinement choosing no entry lowers to, for // the report of what an entry of it keeps. const undecidedShape = "what the keywords beside it say, as no entry of it is the one it lowers from " + "(where they name no kind, the primitive kinds its entries admit together, else the top type)" diff --git a/compilers/openapi/internal/schema/refinement_internal_test.go b/compilers/openapi/internal/schema/refinement_internal_test.go index e4da677f9..d0c69054c 100644 --- a/compilers/openapi/internal/schema/refinement_internal_test.go +++ b/compilers/openapi/internal/schema/refinement_internal_test.go @@ -12,7 +12,6 @@ import ( "testing" "github.com/speakeasy-api/openapi/jsonschema/oas3" - "github.com/speakeasy-api/openapi/marshaller" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" yaml "go.yaml.in/yaml/v3" @@ -24,47 +23,31 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestUnionHeld_AReadCutShortSaysNo covers unionHeld's own contract rather than -// its callers', whose refinement declines first wherever a union's read is cut -// short: a branch restating what the position holds says the union only while -// every branch's read finishes. -func TestUnionHeld_AReadCutShortSaysNo(t *testing.T) { - t.Parallel() - js := &oas3.JSONSchema[oas3.Referenceable]{} - valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader("{anyOf: [{type: string}, {type: integer}]}"), js) - require.NoError(t, err) - require.Empty(t, valErrs, "the fixture parses cleanly") - lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " A: {type: string}\n")) - refinementValue := refinement{held: admitted{kinds: kindString}} - - whole := newAdmissionReader(lowerer.Ctx) - assert.True(t, unionHeld(&whole, refinementValue, StandaloneSchema(js.GetSchema()), "anyOf"), "read whole, the string branch says the union") - cut := newAdmissionReader(lowerer.Ctx) - require.True(t, cut.reads.Spend(maxAdmissionReads), "the budget holds what is spent") - assert.False(t, unionHeld(&cut, refinementValue, StandaloneSchema(js.GetSchema()), "anyOf"), "the integer branch's read runs past it") -} - -// TestRecordFoldedEntryResidue_KeepsWhatItsFoldedEntriesWrite pins the -// residue a position's foldedEntries write, kept on the node in hand and -// reported, and nothing where no folded entry speaks. -func TestRecordFoldedEntryResidue_KeepsWhatItsFoldedEntriesWrite(t *testing.T) { +// TestRecordFlattenedEntryKeeps_KeepsWhatItsFlattenedEntriesWrite pins the +// unread keywords a position's flattenedEntries write, added as pending keeps +// for the node in hand and reported once it settles, and nothing where no +// flattened entry speaks. +func TestRecordFlattenedEntryKeeps_KeepsWhatItsFlattenedEntriesWrite(t *testing.T) { t.Parallel() lowerer, schema, at := lowererDeclaringS(t) - foldedEntries := []annotation.FoldedAllOfEntry{{Node: schema, At: at}} + flattenedEntries := []annotation.FlattenedAllOfEntry{{Node: schema, At: at}} beside := StandaloneSchema(&oas3.Schema{}) - assert.Empty(t, recordFoldedEntryResidue(lowerer.Ctx, &ir.Model{}, beside, nil), "no voice keeps nothing") - node := &ir.Model{} - assert.NotEmpty(t, recordFoldedEntryResidue(lowerer.Ctx, node, beside, foldedEntries)) - assert.Contains(t, node.Unmodeled, "openapi:readOnly", "the node in hand keeps what its voice writes") - assert.Empty(t, recordFoldedEntryResidue(lowerer.Ctx, &ir.Model{}, schema, foldedEntries), "what the position writes too is the position's") + var none annotation.PendingKeeps + assert.Empty(t, recordFlattenedEntryKeeps(lowerer.Ctx, &none, beside, at, nil), "no flattened entry keeps nothing") + assert.True(t, none.Empty()) + var pendingKeeps annotation.PendingKeeps + assert.Empty(t, recordFlattenedEntryKeeps(lowerer.Ctx, &pendingKeeps, beside, at, flattenedEntries), "its reports are its pending keeps'") + var node ir.Unmodeled + assert.NotEmpty(t, settleOn(lowerer.Ctx, &node, &pendingKeeps, at)) + assert.Contains(t, node, "openapi:readOnly", "the node in hand keeps what its flattened entry writes") } // componentSchema returns the schema the component name declares. func componentSchema(t *testing.T, lowerer *Lowerer, name string) *oas3.Schema { t.Helper() - js, ok := lowerer.Doc.Components.Schemas.Get(name) + jsonSchema, ok := lowerer.Doc.Components.Schemas.Get(name) require.True(t, ok, name) - return js.GetSchema() + return jsonSchema.GetSchema() } // TestRefinementOf_ReadsASchemaOnce pins that a schema's decision is read once @@ -80,22 +63,22 @@ func TestRefinementOf_ReadsASchemaOnce(t *testing.T) { T: {allOf: [{$ref: '#/components/schemas/Port'}], description: d} `)) const at = "/components/schemas/T" - s := componentSchema(t, lowerer, "T") - refinement, refined := refinementOf(lowerer.Ctx, StatedIn(lowerer, s), at) + schemaObject := componentSchema(t, lowerer, "T") + refinement, refined := refinementOf(lowerer.Ctx, StatedIn(lowerer, schemaObject), at) require.True(t, refined) require.NotNil(t, refinement.principal) require.Equal(t, jsontext.Pointer(at+"/allOf/0"), refinement.principal.pointer) - StatedIn(lowerer, s).Kinds = &statement.Kinds{Types: []statement.JSONSchemaTypeName{statement.KindObject}} - _, refined = refinementOf(lowerer.Ctx, StatedIn(lowerer, s), at) + StatedIn(lowerer, schemaObject).Kinds = &statement.Kinds{Types: []statement.JSONSchemaTypeName{statement.KindObject}} + _, refined = refinementOf(lowerer.Ctx, StatedIn(lowerer, schemaObject), at) assert.True(t, refined, "the second ask reads what the first read") - refinement, refined = refinementOf(lowerer.Ctx, StatedIn(lowerer, s), "/elsewhere") + refinement, refined = refinementOf(lowerer.Ctx, StatedIn(lowerer, schemaObject), "/elsewhere") require.True(t, refined, "another pointer reads the same answer") require.NotNil(t, refinement.principal) - assert.Equal(t, jsontext.Pointer("/elsewhere/allOf/0"), refinement.principal.pointer, "its entries stand at the pointer asked") + assert.Equal(t, jsontext.Pointer("/elsewhere/allOf/0"), refinement.principal.pointer, "its entries sit at the pointer asked") assert.Same(t, refinement.principal, refinement.ref, "the principal is the $ref read through") - assert.True(t, decisionOf(lowerer.Ctx, StatedIn(lowerer, s)).refines, "a reader with no pointer reads it too") + assert.True(t, decisionOf(lowerer.Ctx, StatedIn(lowerer, schemaObject)).refines(), "a reader with no pointer reads it too") } // TestAdmissionReader_ReadsAValueSetOnce pins that an enum is read once a run however @@ -105,77 +88,38 @@ func TestRefinementOf_ReadsASchemaOnce(t *testing.T) { func TestAdmissionReader_ReadsAValueSetOnce(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" E: {type: string, enum: [a, b]}\n")) - s := componentSchema(t, lowerer, "E") + schemaObject := componentSchema(t, lowerer, "E") first := newAdmissionReader(lowerer.Ctx) - require.Contains(t, first.written(StatedIn(lowerer, s), first.nullable).values, "string:a") + require.Contains(t, first.written(StatedIn(lowerer, schemaObject), first.nullable).values, "string:a") - s.GetEnum()[0].Value = "z" + schemaObject.GetEnum()[0].Value = "z" second := newAdmissionReader(lowerer.Ctx) - read := second.written(StatedIn(lowerer, s), second.nullable) + read := second.written(StatedIn(lowerer, schemaObject), second.nullable) assert.Contains(t, read.values, "string:a", "the second read takes what the first remembered") assert.NotContains(t, read.values, "string:z") } -// TestFoldingAllOfEntries_ReadsASchemaOnce pins that what folds is read once a +// TestAllOfEntryFoldingOf_ReadsASchemaOnce pins that what folds is read once a // run however many uses of a schema ask, which keeps a schema's uses times its // entries from being the cost of a wide composition: its allOf goes after the // first read, which no lowering does, so only a remembered answer stays. -func TestFoldingAllOfEntries_ReadsASchemaOnce(t *testing.T) { +func TestAllOfEntryFoldingOf_ReadsASchemaOnce(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Str: {type: string} T: {allOf: [{$ref: '#/components/schemas/Str'}, {description: d}]} `)) - s := componentSchema(t, lowerer, "T") - require.Equal(t, []bool{false, true}, foldingAllOfEntries(lowerer.Ctx, StatedIn(lowerer, s))) - - st := lowerer.Ctx.Statements().Read(StatedIn(lowerer, s)) - st.AllOf, st.Entries = nil, nil - assert.Equal(t, []bool{false, true}, foldingAllOfEntries(lowerer.Ctx, StatedIn(lowerer, s)), "the second ask reads what the first read") -} - -// TestNullableFoldingEntries_ReadsASchemaOnce pins that the entries widening a -// schema are read once a run, as its allOfEntryFolding is, since every use of -// the schema asks: its allOf goes after the first read, so only a remembered -// answer stays. -func TestNullableFoldingEntries_ReadsASchemaOnce(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Str: {type: string} - T: {allOf: [{$ref: '#/components/schemas/Str'}, {nullable: true}]} -`)) - s := componentSchema(t, lowerer, "T") - first := nullableFoldingEntries(lowerer.Ctx, StatedIn(lowerer, s)) - require.Len(t, first, 1) - assert.Equal(t, jsontext.Pointer("/allOf/1"), first[0].pointer, "each entry at its pointer under the schema's") - - st := lowerer.Ctx.Statements().Read(StatedIn(lowerer, s)) - st.AllOf, st.Entries = nil, nil - assert.Equal(t, first, nullableFoldingEntries(lowerer.Ctx, StatedIn(lowerer, s)), "the second ask reads what the first read") -} - -// TestValueNulls_ReadsASchemaOnce pins that what a schema's const, enum and union -// say of null is read once a run, since every $ref to the schema asks and the enum -// and union scan each member: they go after the first read, which no lowering -// does, so only a remembered answer stays. -func TestValueNulls_ReadsASchemaOnce(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` V: {const: null, enum: [a, null]} - U: {oneOf: [{type: string}, {type: 'null'}]} -`)) - v, u := componentSchema(t, lowerer, "V"), componentSchema(t, lowerer, "U") - values := valueVerdicts{constant: nullAdmitted, enum: nullAdmitted} - union := valueVerdicts{union: nullReadingAlikeUnderBothPolicies(nullAdmitted)} - require.Equal(t, values, valueNulls(lowerer.Ctx, StatedIn(lowerer, v))) - require.Equal(t, union, valueNulls(lowerer.Ctx, StatedIn(lowerer, u))) + schemaObject := componentSchema(t, lowerer, "T") + require.Equal(t, []bool{false, true}, allOfEntryFoldingOf(lowerer.Ctx, StatedIn(lowerer, schemaObject)).entryFoldsIntoPosition) - StatedIn(lowerer, v).Values = nil - StatedIn(lowerer, u).Choice = nil - assert.Equal(t, values, valueNulls(lowerer.Ctx, StatedIn(lowerer, v)), "the second ask reads what the first read") - assert.Equal(t, union, valueNulls(lowerer.Ctx, StatedIn(lowerer, u)), "the second ask reads what the first read") + schemaStatement := lowerer.Ctx.Statements().Read(StatedIn(lowerer, schemaObject)) + schemaStatement.AllOf, schemaStatement.Entries = nil, nil + assert.Equal(t, []bool{false, true}, allOfEntryFoldingOf(lowerer.Ctx, StatedIn(lowerer, schemaObject)).entryFoldsIntoPosition, "the second ask reads what the first read") } // TestLendingEntries_LendsEachEntryOnce pins what a use of a wide composition // reads: an entry repeating what s or an entry before it writes lends nothing -// more, so a use pays for each entry once, while one writing a new entry lends it. +// more, so a use pays for each entry once, while one writing a new entry lends it, +// less what its conjuncts write otherwise. func TestLendingEntries_LendsEachEntryOnce(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Obj: {type: object} @@ -191,37 +135,38 @@ func TestLendingEntries_LendsEachEntryOnce(t *testing.T) { got := lendingEntries(lowerer.Ctx, StatedIn(lowerer, componentSchema(t, lowerer, "T"))) require.Len(t, got, 1, "only the entry first writing readOnly lends what T does not") assert.Equal(t, jsontext.Pointer("/allOf/2"), got[0].pointer) - b := statement.ParsedAt(got[0].schema).GetSchema() - require.NotNil(t, b.ReadOnly) - assert.True(t, *b.ReadOnly) - assert.Equal(t, "d", b.GetDescription()) + schemaObject := statement.ParsedAt(got[0].schema).GetSchema() + require.NotNil(t, schemaObject.ReadOnly) + assert.True(t, *schemaObject.ReadOnly) + assert.Equal(t, "d", schemaObject.GetDescription()) split, _ := LoweredFor(t, openapitest.ComponentSpec(` Obj: {type: object} T: {allOf: [{$ref: '#/components/schemas/Obj'}, {title: a, description: d}, {title: b}, {description: d}]} `)) got = lendingEntries(split.Ctx, StatedIn(split, componentSchema(t, split, "T"))) - require.Len(t, got, 1, "an entry kept for disagreeing lends nothing, nor marks what it writes as lent") - assert.Empty(t, statement.ParsedAt(got[0].schema).GetSchema().GetTitle()) - assert.Equal(t, "d", statement.ParsedAt(got[0].schema).GetSchema().GetDescription()) + require.Len(t, got, 1, "an entry kept for disagreeing lends only what its conjuncts agree on, marked as lent") + assert.Equal(t, jsontext.Pointer("/allOf/1"), got[0].pointer) + assert.Empty(t, statement.Parsed(got[0].schema.Schema).GetTitle(), "the title its conjuncts disagree on is not lent") + assert.Equal(t, "d", statement.Parsed(got[0].schema.Schema).GetDescription()) } // TestAnnotationsAUseFallsBackTo_ReadsATargetOnce pins that what a schema lends // is read once a run however many $refs name it, for the reason -// foldingAllOfEntries's answer is: its allOf goes after the first read, so +// allOfEntryFoldingOf's answer is: its allOf goes after the first read, so // only a remembered chain stays. func TestAnnotationsAUseFallsBackTo_ReadsATargetOnce(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Str: {type: string} T: {allOf: [{$ref: '#/components/schemas/Str'}, {description: d}]} `)) - js, ok := lowerer.Doc.Components.Schemas.Get("T") + jsonSchema, ok := lowerer.Doc.Components.Schemas.Get("T") require.True(t, ok) - first := fallbackAnnotationsOf(lowerer.Ctx, lowerer.Ctx.Statements().Of(js)).Referents + first := fallbackAnnotationsOf(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema)).Referents require.Len(t, first, 4, "T, the entry that folds, the $ref and what it names") - st := lowerer.Ctx.Statements().Of(js) - st.AllOf, st.Entries = nil, nil - assert.Equal(t, first, fallbackAnnotationsOf(lowerer.Ctx, lowerer.Ctx.Statements().Of(js)).Referents, "the second ask reads what the first read") + schemaStatement := lowerer.Ctx.Statements().Of(jsonSchema) + schemaStatement.AllOf, schemaStatement.Entries = nil, nil + assert.Equal(t, first, fallbackAnnotationsOf(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema)).Referents, "the second ask reads what the first read") } // TestWrittenText_RendersASchemaOnce pins that a schema's text is rendered once a run @@ -230,16 +175,16 @@ func TestAnnotationsAUseFallsBackTo_ReadsATargetOnce(t *testing.T) { func TestWrittenText_RendersASchemaOnce(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" T: {type: string}\n")) - js, ok := lowerer.Doc.Components.Schemas.Get("T") + jsonSchema, ok := lowerer.Doc.Components.Schemas.Get("T") require.True(t, ok) - text := writtenText(lowerer.Ctx, lowerer.Ctx.Statements().Of(js)) + text := writtenText(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema)) require.NotNil(t, text) - *js.GetCore().GetRootNode() = yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "other"} - assert.Equal(t, text, writtenText(lowerer.Ctx, lowerer.Ctx.Statements().Of(js)), "the second ask reads what the first rendered") + *jsonSchema.GetCore().GetRootNode() = yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "other"} + assert.Equal(t, text, writtenText(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema)), "the second ask reads what the first rendered") } -// TestReadAllOfEntryFolding_RendersEachValueOnce pins what a first writer +// TestReadAllOfEntryFolding_RendersEachValueOnce pins what a first conjunct // costs: every later conjunct compares with it, so rendering it for each // comparison made a document's entries times its longest value the cost of one // composition. It is not parallel, as the count is the process's, and takes the @@ -253,13 +198,13 @@ func TestReadAllOfEntryFolding_RendersEachValueOnce(t *testing.T) { fmt.Fprintf(&src, " - {description: d%d}\n", i) } lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(src.String())) - s := componentSchema(t, lowerer, "T") + schemaObject := componentSchema(t, lowerer, "T") var stats runtime.MemStats least := uint64(math.MaxUint64) for range 3 { runtime.ReadMemStats(&stats) before := stats.TotalAlloc - read := readAllOfEntryFolding(lowerer.Ctx, StatedIn(lowerer, s)) + read := readAllOfEntryFolding(lowerer.Ctx, StatedIn(lowerer, schemaObject)) runtime.ReadMemStats(&stats) least = min(least, stats.TotalAlloc-before) require.Len(t, read.entryFoldsIntoPosition, later+1) @@ -269,23 +214,23 @@ func TestReadAllOfEntryFolding_RendersEachValueOnce(t *testing.T) { assert.Less(t, cost(256), 2*cost(64), "four times the entries, not four times the value") } -// TestRead_AFoldedEntryCostsItsOwnEntries pins what a site's voices cost: each -// adds its own entries, where overlaying what came before on each made the cost -// of a composition its entries squared. It is not parallel, as the count is the -// process's, and takes the least of three counts for the same reason as -// TestReadAllOfEntryFolding_RendersEachValueOnce. -func TestRead_AFoldedEntryCostsItsOwnEntries(t *testing.T) { +// TestRead_AFlattenedEntryCostsItsOwnEntries pins what a site's +// flattenedEntryCount cost: each adds its own entries, where overlaying what +// came before on each made the cost of a composition its entries squared. It is +// not parallel, as the count is the process's, and takes the least of three +// counts for the same reason as TestReadAllOfEntryFolding_RendersEachValueOnce. +func TestRead_AFlattenedEntryCostsItsOwnEntries(t *testing.T) { const at = "/components/schemas/T" - cost := func(voices int) uint64 { + cost := func(flattenedEntryCount int) uint64 { var src strings.Builder src.WriteString(" O: {type: object}\n T:\n allOf:\n - {$ref: '#/components/schemas/O'}\n") - for i := range voices { + for i := range flattenedEntryCount { fmt.Fprintf(&src, " - {x-k%d: 1}\n", i) } lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(src.String())) - s := componentSchema(t, lowerer, "T") - site := Use{FoldedAllOfEntries: positionFoldedEntries(lowerer.Ctx, StatedIn(lowerer, s), at, ir.TypeRef{})}.Site(StatedIn(lowerer, s)) - require.Len(t, site.FoldedAllOfEntries, voices) + schemaObject := componentSchema(t, lowerer, "T") + site := Use{FlattenedAllOfEntries: positionFlattenedEntries(lowerer.Ctx, StatedIn(lowerer, schemaObject), at, ir.TypeRef{})}.Site(StatedIn(lowerer, schemaObject)) + require.Len(t, site.FlattenedAllOfEntries, flattenedEntryCount) var stats runtime.MemStats least := uint64(math.MaxUint64) for range 3 { @@ -305,7 +250,7 @@ func TestRead_AFoldedEntryCostsItsOwnEntries(t *testing.T) { // instance of it is, and what is no instance to none. func TestKindOfValue_NamesEachValuesKind(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { v ir.Value want kindSet }{ @@ -318,7 +263,10 @@ func TestKindOfValue_NamesEachValuesKind(t *testing.T) { {ir.Value{Kind: ir.ValueObject}, kindObject}, {ir.Value{Kind: ir.ValueNumber, Number: "1.0"}, kindInteger}, {ir.Value{Kind: ir.ValueNumber, Number: "1.5"}, kindFraction}, - {ir.Value{Kind: ir.ValueNumber, Number: "1e2"}, kindNumber}, + // 1e2 is an integer and 1e-2 is not, to a JSON Schema validator's + // `type: integer` (Python jsonschema, Draft 2020-12). + {ir.Value{Kind: ir.ValueNumber, Number: "1e2"}, kindInteger}, + {ir.Value{Kind: ir.ValueNumber, Number: "1e-2"}, kindFraction}, {ir.Value{Kind: ir.ValueRefKind}, 0}, {ir.Value{Kind: ir.ValueConstructor}, 0}, {ir.Value{Kind: ir.ValueInfinity}, 0}, @@ -326,7 +274,7 @@ func TestKindOfValue_NamesEachValuesKind(t *testing.T) { {ir.Value{Kind: ir.ValueNaN}, 0}, {ir.Value{Kind: "no kind"}, 0}, } { - assert.Equal(t, tc.want, kindOfValue(tc.v), tc.v.Kind) + assert.Equal(t, testCase.want, kindOfValue(testCase.v), testCase.v.Kind) } } @@ -354,9 +302,10 @@ func TestAdmissionReader_ANullableBesideARefIsReadInItsDialect(t *testing.T) { } } -// TestAdmissionReader_ASchemaIsWithinItself pins the comparison every election makes of -// a conjunct with itself, which needs no rendering: rendering costs the whole -// `items` subtree at each level, and a value that will not render shows it ran. +// TestAdmissionReader_ASchemaIsWithinItself pins the comparison every choice +// makes of a conjunct with itself, which needs no rendering: rendering costs +// the whole `items` subtree at each level, and a value that will not render +// shows it ran. func TestAdmissionReader_ASchemaIsWithinItself(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" E: {type: array, items: {type: string, x-t: .nan}}\n")) @@ -366,38 +315,39 @@ func TestAdmissionReader_ASchemaIsWithinItself(t *testing.T) { } // TestAdmissionReader_ARememberedSetStillSpends pins why a remembered set costs its -// budget: a read's verdict turns on what it spent, so a set a first reader +// budget: a read's answer turns on what it spent, so a set a first reader // read must cut a later one exactly as reading it would, or which position // lowered first would decide what another lowers to. func TestAdmissionReader_ARememberedSetStillSpends(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" E: {type: string, enum: [a, b]}\n")) - s := componentSchema(t, lowerer, "E") + schemaObject := componentSchema(t, lowerer, "E") first := newAdmissionReader(lowerer.Ctx) - first.written(StatedIn(lowerer, s), first.nullable) + first.written(StatedIn(lowerer, schemaObject), first.nullable) require.False(t, first.incomplete()) short := newAdmissionReader(lowerer.Ctx) short.members = budget.New(budget.AtMost(1)) - assert.Empty(t, short.written(StatedIn(lowerer, s), short.nullable).values, "a set past the budget is not read at all") + assert.Empty(t, short.written(StatedIn(lowerer, schemaObject), short.nullable).values, "a set past the budget is not read at all") assert.True(t, short.incomplete()) } -// TestAdmissionReader_AnUnreadableSetIsRememberedAsUnread pins that a set no reader could -// read cuts every read of it, the first and those after. +// TestAdmissionReader_AnUnreadableSetIsRememberedAsUnread pins that a set no +// reader could read is no conjunct of the reading: it cuts no read of it, the +// first or those after, which read the schema by what else it writes. func TestAdmissionReader_AnUnreadableSetIsRememberedAsUnread(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" E: {type: string, enum: [a, b]}\n")) - s := componentSchema(t, lowerer, "E") - s.GetEnum()[0].Kind = 0 + schemaObject := componentSchema(t, lowerer, "E") + schemaObject.GetEnum()[0].Kind = 0 for range 2 { admissionReader := newAdmissionReader(lowerer.Ctx) - admissionReader.written(StatedIn(lowerer, s), admissionReader.nullable) - assert.True(t, admissionReader.incomplete()) + admissionReader.written(StatedIn(lowerer, schemaObject), admissionReader.nullable) + assert.False(t, admissionReader.incomplete(), "the unreadable set cuts nothing") } } -// TestChooseConjunctToLowerFrom_WalksOnlyTheSetItNarrows pins what electing a +// TestChooseConjunctToLowerFrom_WalksOnlyTheSetItNarrows pins what choosing a // narrowing costs: it looks each of the narrowing's members up in what it // narrows, and no more. A set compared with itself, or a larger set searched // for one a smaller lacks, walked the larger set, so each position narrowing a @@ -414,14 +364,14 @@ func TestChooseConjunctToLowerFrom_WalksOnlyTheSetItNarrows(t *testing.T) { } lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" En: {type: string, enum: ["+target.String()+"]}\n"+ " T: {allOf: [{$ref: '#/components/schemas/En'}, {enum: ["+narrowed.String()+"]}]}\n")) - s := componentSchema(t, lowerer, "T") + schemaObject := componentSchema(t, lowerer, "T") admissionReader := newAdmissionReader(lowerer.Ctx) total := 0 admissionReader.walked = func(n int) { total += n } - conjuncts, _ := admissionReader.conjuncts(StatedIn(lowerer, s), allOfEntries(lowerer.Ctx, StatedIn(lowerer, s), "")) + conjuncts, _ := admissionReader.conjuncts(StatedIn(lowerer, schemaObject), allOfEntries(lowerer.Ctx, StatedIn(lowerer, schemaObject), ""), false) principal := admissionReader.chooseConjunctToLowerFrom(conjuncts, []*conjunct{&conjuncts[1]}) require.NotNil(t, principal.entry) - require.Nil(t, statement.ParsedAt(principal.entry.schema).GetSchema().Ref, "the narrowing is elected") + require.Nil(t, statement.ParsedAt(principal.entry.schema).GetSchema().Ref, "the narrowing is chosen") return total } assert.Equal(t, 1, walked(1000, 1)) @@ -429,7 +379,7 @@ func TestChooseConjunctToLowerFrom_WalksOnlyTheSetItNarrows(t *testing.T) { assert.Equal(t, 999, walked(1000, 999), "a narrowing walks its own members") } -// TestChooseConjunctToLowerFrom_ComparesEachPairOnce pins what an election of +// TestChooseConjunctToLowerFrom_ComparesEachPairOnce pins what a choice of // many conjuncts tying with each other costs: one comparison of each conjunct // naming a kind with every conjunct (mostWithin), and breaking the tie at most // one more per conjunct. Unions of one keyword and words admitting alike are @@ -437,7 +387,7 @@ func TestChooseConjunctToLowerFrom_WalksOnlyTheSetItNarrows(t *testing.T) { func TestChooseConjunctToLowerFrom_ComparesEachPairOnce(t *testing.T) { t.Parallel() for _, entry := range []string{ - "{oneOf: [{type: string, maxLength: %d}, {type: integer}]}", + "{type: string, oneOf: [{maxLength: %d}, {minLength: 1}]}", "{type: string, maxLength: %d}", } { for _, n := range []int{16, 32, 64} { @@ -448,7 +398,7 @@ func TestChooseConjunctToLowerFrom_ComparesEachPairOnce(t *testing.T) { lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" T: {allOf: ["+strings.Join(entries, ", ")+"]}\n")) schema := StatedIn(lowerer, componentSchema(t, lowerer, "T")) admissionReader := newAdmissionReader(lowerer.Ctx) - conjuncts, _ := admissionReader.conjuncts(schema, allOfEntries(lowerer.Ctx, schema, "")) + conjuncts, _ := admissionReader.conjuncts(schema, allOfEntries(lowerer.Ctx, schema, ""), false) compared := 0 admissionReader.compared = func() { compared++ } admissionReader.chooseConjunctToLowerFrom(conjuncts, nil) diff --git a/compilers/openapi/internal/schema/refinement_keys_internal_test.go b/compilers/openapi/internal/schema/refinement_keys_internal_test.go index 31cbfd60c..6b92ea2e0 100644 --- a/compilers/openapi/internal/schema/refinement_keys_internal_test.go +++ b/compilers/openapi/internal/schema/refinement_keys_internal_test.go @@ -13,18 +13,31 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" ) -// keptRefEntry is a $ref entry at pointer naming #/T beside x-a, whose value is -// the scalar value. -func keptRefEntry(pointer jsontext.Pointer, value string) wholeRefEntry { +// refEntryBesideExtension is a $ref entry at pointer naming #/T beside x-a, +// whose value is the scalar value. +func refEntryBesideExtension(pointer jsontext.Pointer, value string) keptRefEntry { const text = "#/T" node := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{ {Kind: yaml.ScalarNode, Tag: "!!str", Value: "$ref"}, {Kind: yaml.ScalarNode, Tag: "!!str", Value: text}, {Kind: yaml.ScalarNode, Tag: "!!str", Value: "x-a"}, {Kind: yaml.ScalarNode, Tag: "!!str", Value: value}, }} - st := &statement.Statement{Schema: &statement.Schema{Node: node, Ref: &statement.Reference{Keyword: "$ref", Text: text}}} - return wholeRefEntry{entry: allOfEntry{schema: st, pointer: pointer}} + schemaStatement := &statement.Statement{Schema: &statement.Schema{Node: node, Ref: &statement.Reference{Keyword: "$ref", Text: text}}} + return keptRefEntry{entry: allOfEntry{schema: schemaStatement, pointer: pointer}} +} + +// renderedTexts renders each entry's node, nil where it cannot render, as +// keepRefConjuncts gives keptRefKeys each entry's text. +func renderedTexts(entries []keptRefEntry) []ir.RawValue { + out := make([]ir.RawValue, len(entries)) + for i, refEntry := range entries { + if raw, err := annotation.RawFromNode(refEntry.entry.schema.Node); err == nil { + out[i] = raw + } + } + return out } // TestKeptRefKeys_AnEntryThatCannotRenderIsAlikeToNoOther pins the rank of a @@ -35,16 +48,18 @@ func keptRefEntry(pointer jsontext.Pointer, value string) wholeRefEntry { func TestKeptRefKeys_AnEntryThatCannotRenderIsAlikeToNoOther(t *testing.T) { t.Parallel() const bad = "\xff" - _, err := annotation.RawFromNode(keptRefEntry("", bad).entry.schema.Node) + _, err := annotation.RawFromNode(refEntryBesideExtension("", bad).entry.schema.Node) require.Error(t, err, "the entry must be one that does not render") - keys := keptRefKeys([]wholeRefEntry{keptRefEntry("/S/allOf/0", bad), keptRefEntry("/S/allOf/1", bad)}, "/S") + entries := []keptRefEntry{refEntryBesideExtension("/S/allOf/0", bad), refEntryBesideExtension("/S/allOf/1", bad)} + keys := keptRefKeys(entries, renderedTexts(entries), "/S") assert.Equal(t, map[jsontext.Pointer]keptRef{ "/S/allOf/0": {key: "openapi:$ref/0", at: "/S/allOf/0"}, "/S/allOf/1": {key: "openapi:$ref/1", at: "/S/allOf/1"}, }, keys) - keys = keptRefKeys([]wholeRefEntry{keptRefEntry("/S/allOf/0", "ok"), keptRefEntry("/S/allOf/1", "ok")}, "/S") + entries = []keptRefEntry{refEntryBesideExtension("/S/allOf/0", "ok"), refEntryBesideExtension("/S/allOf/1", "ok")} + keys = keptRefKeys(entries, renderedTexts(entries), "/S") assert.Equal(t, map[jsontext.Pointer]keptRef{ "/S/allOf/0": {key: "openapi:$ref", at: "/S"}, "/S/allOf/1": {key: "openapi:$ref", at: "/S"}, diff --git a/compilers/openapi/internal/schema/refinement_set_union_test.go b/compilers/openapi/internal/schema/refinement_set_union_test.go index 4c76a6051..0d3dc096c 100644 --- a/compilers/openapi/internal/schema/refinement_set_union_test.go +++ b/compilers/openapi/internal/schema/refinement_set_union_test.go @@ -16,17 +16,19 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestRefinementSetUnion_AUnionTheValueSetStandsBesideIsKept pins a oneOf or -// anyOf written with the value set that stands at the position, on an entry +// TestRefinementSetUnion_AUnionTheValueSetSitsBesideIsKept pins a oneOf or +// anyOf written with the value set that sits at the position, on an entry // in either order and beside the allOf: the node the set lowers to holds no // union, so in every spelling it is kept under its keyword with one reason and -// reported, where the entry's was consumed in silence as said by the set. -func TestRefinementSetUnion_AUnionTheValueSetStandsBesideIsKept(t *testing.T) { +// reported, where the entry's was consumed in silence as said by the set. A +// pattern outside the subset ir reads leaves whether the set's member +// satisfies the union unknown, so the union is not said by the set's member. +func TestRefinementSetUnion_AUnionTheValueSetSitsBesideIsKept(t *testing.T) { t.Parallel() const ref = "{$ref: '#/components/schemas/U'}" for _, union := range []string{"oneOf", "anyOf"} { for _, set := range []string{"enum: [a]", "const: a"} { - words := union + ": [{type: string}, {type: boolean}], " + set + words := union + ": [{type: string, pattern: '^(?=a)'}, {type: boolean}], " + set spellings := map[string]struct{ schema, at string }{ "entry": {"{allOf: [" + ref + ", {" + words + "}]}", "/allOf/1/" + union}, "reversed": {"{allOf: [{" + words + "}, " + ref + "]}", "/allOf/0/" + union}, diff --git a/compilers/openapi/internal/schema/refinement_shared_test.go b/compilers/openapi/internal/schema/refinement_shared_test.go index 164ee4299..f560366b8 100644 --- a/compilers/openapi/internal/schema/refinement_shared_test.go +++ b/compilers/openapi/internal/schema/refinement_shared_test.go @@ -4,6 +4,8 @@ package schema_test import ( + "strconv" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -13,29 +15,30 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestRefinementUndecided_ValueSetsAreTypedByTheMembersTheyShare holds the -// one reading of value sets of an allOf electing no entry: an instance meets -// every set only as a member of each, so the position is the kinds of the -// members they share that every other conjunct's kinds leave, the top type -// with the warning that they share no value where none is left, in either -// order of the entries. -func TestRefinementUndecided_ValueSetsAreTypedByTheMembersTheyShare(t *testing.T) { +// TestRefinementUndecided_ValueSetsIntersectAsAFlatEnumOfWhatTheyShare holds +// the one reading of value sets of an allOf choosing no entry: an instance +// satisfies every set only as a member of each, so the position lowers as a +// flat enum of the members they share that every other conjunct's kinds leave, +// every set kept, and is the top type with the warning that they share no value +// where none is left, in either order of the entries. Sets sharing no member at +// all are the closed empty Enum of their value type, each set kept. +func TestRefinementUndecided_ValueSetsIntersectAsAFlatEnumOfWhatTheyShare(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { entries []string - want ir.TypeID - warns int + want []ir.Value + top bool }{ - "no shared member": {[]string{"{enum: [a, b]}", "{enum: [c, d]}"}, ir.PrimitiveTypeID(ir.PrimitiveAny), 1}, - "a shared flag": {[]string{"{enum: [true, a]}", "{enum: [true, b]}"}, ir.PrimitiveTypeID(ir.PrimitiveBool), 0}, - "a kind beside leaves": {[]string{"{enum: [1, true, x]}", "{enum: [1, true, y]}", "{type: [integer, string]}"}, - ir.PrimitiveTypeID(ir.PrimitiveInteger), 0}, - "a kind beside leaves none": {[]string{"{enum: [1, true, x]}", "{enum: [1, true, y]}", "{type: string}"}, - ir.PrimitiveTypeID(ir.PrimitiveAny), 1}, + "a shared flag": {[]string{"{enum: [true, a]}", "{enum: [true, b]}"}, []ir.Value{{Kind: ir.ValueBool, Bool: true}}, false}, + "a kind beside leaves": {[]string{"{enum: [1, true, x]}", "{enum: [1, true, y]}", "{type: [integer, string]}"}, []ir.Value{{Kind: ir.ValueNumber, Number: "1"}}, false}, + "a kind beside leaves none": {[]string{"{enum: [1, true, x]}", "{enum: [1, true, y]}", "{type: string}"}, nil, true}, + "an overlap": {[]string{"{enum: [a, b]}", "{enum: [b, c]}"}, []ir.Value{{Kind: ir.ValueString, String: "b"}}, false}, + "fractions": {[]string{"{enum: [1.5, 2.5]}", "{enum: [2.5, 3.5]}"}, []ir.Value{{Kind: ir.ValueNumber, Number: "2.5"}}, false}, + "an integer among flags": {[]string{"{enum: [1, true, x]}", "{enum: [1, false, y]}"}, []ir.Value{{Kind: ir.ValueNumber, Number: "1"}}, false}, } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, entries := range [][]string{tc.entries, reversedEntries(tc.entries)} { + for _, entries := range [][]string{testCase.entries, reversedEntries(testCase.entries)} { schema := "{allOf: [" for i, e := range entries { if i > 0 { @@ -45,14 +48,39 @@ func TestRefinementUndecided_ValueSetsAreTypedByTheMembersTheyShare(t *testing.T } doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+schema+"]}\n")) openapitest.RequireNoErrorDiags(t, diags) - scalar, ok := typeByName(doc, "S").(*ir.Scalar) + if testCase.top { + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "%s: got %T", schema, typeByName(doc, "S")) + require.NotNil(t, scalar.Base, schema) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveAny), scalar.Base.Target, schema) + assert.Len(t, disjointReports(diags), 1, schema) + continue + } + enum, ok := typeByName(doc, "S").(*ir.Enum) require.True(t, ok, "%s: got %T", schema, typeByName(doc, "S")) - require.NotNil(t, scalar.Base, schema) - assert.Equal(t, tc.want, scalar.Base.Target, schema) - assert.Len(t, disjointReports(diags), tc.warns, schema) + got := make([]ir.Value, 0, len(enum.Members)) + for _, member := range enum.Members { + got = append(got, member.Value) + } + assert.Equal(t, testCase.want, got, schema) + assert.Empty(t, disjointReports(diags), schema) + for i, e := range entries { + if strings.Contains(e, "enum") { + assert.Contains(t, unmodeledKeys(enum.Unmodeled), "openapi:allOf/"+strconv.Itoa(i), "%s: every set is kept", schema) + } + } } }) } + for _, schema := range []string{"{allOf: [{enum: [a, b]}, {enum: [c, d]}]}", "{allOf: [{enum: [c, d]}, {enum: [a, b]}]}"} { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+schema+"\n")) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "%s: got %T", schema, typeByName(doc, "S")) + assert.Empty(t, enum.Members, schema) + assert.Equal(t, ir.PrimitiveString, enum.ValueType, schema) + assert.Subset(t, unmodeledKeys(enum.Unmodeled), []string{"openapi:allOf/0", "openapi:allOf/1"}, schema) + assert.Len(t, disjointReports(diags), 1, schema) + } } // reversedEntries returns entries in the other order. diff --git a/compilers/openapi/internal/schema/refinement_test.go b/compilers/openapi/internal/schema/refinement_test.go index 5960fe81f..ffe37f1a8 100644 --- a/compilers/openapi/internal/schema/refinement_test.go +++ b/compilers/openapi/internal/schema/refinement_test.go @@ -168,9 +168,9 @@ func TestRefinement_AnAnnotationOnlyEntryLandsTyped(t *testing.T) { assert.Empty(t, zone.Unmodeled) } -// TestRefinement_PrimitiveEntriesLowerToTheirMeet is GitHub #1043: every -// entry a kind, the position is the narrowest of them, in either order. -func TestRefinement_PrimitiveEntriesLowerToTheirMeet(t *testing.T) { +// TestRefinement_PrimitiveEntriesLowerToTheirIntersection is GitHub #1043: +// every entry a kind, the position is the narrowest of them, in either order. +func TestRefinement_PrimitiveEntriesLowerToTheirIntersection(t *testing.T) { t.Parallel() for name, entries := range map[string]string{ "narrowest last": "[{type: integer}, {type: integer, format: int32}]", @@ -196,11 +196,11 @@ func TestRefinement_PrimitiveEntriesLowerToTheirMeet(t *testing.T) { // TestRefinement_AUnionEntryIsAConjunct pins a oneOf or anyOf written as an // allOf entry where the conjuncts admit no object, read as // docs/compilers/openapi.md#allof-refinement reads any conjunct. Beside a -// narrower one it lowers to the meet, at a property as at a component, saying -// nothing more where a branch says nothing that conjunct does not and, for a -// oneOf, shares a kind with no other; a branch's bound, pattern or annotation -// says more, so it stays with its branch. Where it is the narrowest, it is the -// principal, standing at the position, and where it shares no value with the +// narrower one it lowers to the intersection, at a property as at a component; +// a branch sharing no kind with that conjunct is dead, so the union holding it +// is kept whole, its dead branches reported; a branch's bound, pattern or +// annotation says more, so it stays with its branch. Where it is the narrowest, +// it is the principal, at the position, and where it shares no value with the // rest, the allOf composes. func TestRefinement_AUnionEntryIsAConjunct(t *testing.T) { t.Parallel() @@ -239,52 +239,67 @@ func TestRefinement_AUnionEntryIsAConjunct(t *testing.T) { require.True(t, ok) assert.Equal(t, want.Base, value.Base, "Value lowers as ValueString does") assert.Equal(t, want.Constraints, value.Constraints) - assert.Empty(t, value.Unmodeled, "the anyOf says nothing the string does not") - for _, at := range []string{"/components/schemas/Value", "/components/schemas/Value/allOf/0", "/components/schemas/Value/allOf/1"} { - assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, at), at) - } + // Its number and boolean branches share no kind with the string, so the + // anyOf is kept whole, its dead branches reported at it. + assert.Equal(t, ir.ReasonDegradedLowering, value.Unmodeled["openapi:anyOf"].Reason) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Value/allOf/0/anyOf")) field := propertyOf(t, doc, "Holder", "value") - assert.Equal(t, ir.TypeID("type/primitive/string"), field.Type.Target, "a property lowers to the meet too") - require.NotNil(t, field.Constraints) - assert.Equal(t, int64(1000), *field.Constraints.MaxLength) - assert.Empty(t, field.Unmodeled) + node, ok := doc.Types[field.Type.Target].(*ir.Scalar) + require.True(t, ok, "a property names the node keeping the union") + assert.Equal(t, ir.TypeID("type/primitive/string"), node.Base.Target, "over the intersection") + assert.Contains(t, node.Unmodeled, "openapi:anyOf") beside, ok := typeByName(doc, "BesideDecides").(*ir.Scalar) require.True(t, ok, "BesideDecides is a scalar, not %T", typeByName(doc, "BesideDecides")) assert.Equal(t, ir.TypeID("type/primitive/string"), beside.Base.Target, "the keywords beside the allOf decide it") - assert.Empty(t, beside.Unmodeled, "with no principal entry, the anyOf is said all the same") + assert.Equal(t, ir.ReasonDegradedLowering, beside.Unmodeled["openapi:anyOf"].Reason, "its integer branch is dead") for _, name := range []string{"SameText", "SameRef"} { - assert.Empty(t, typeByName(doc, name).Common().Unmodeled, "%s: a branch written as the principal says nothing more", name) - assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/"+name+"/allOf/0"), name) + assert.Equal(t, ir.ReasonDegradedLowering, typeByName(doc, name).Common().Unmodeled["openapi:oneOf"].Reason, + "%s: its integer branch is dead", name) } byRef, ok := typeByName(doc, "ByRef").(*ir.Scalar) require.True(t, ok, "ByRef is a use of Str, not %T", typeByName(doc, "ByRef")) assert.Equal(t, componentID("Str"), byRef.Base.Target) - assert.Empty(t, byRef.Unmodeled, "Str lies within one branch and shares no kind with another") + assert.Contains(t, byRef.Unmodeled, "openapi:oneOf", "Str lies within one branch and shares no kind with the others") // The union is kept under its keyword with the reason it has beside the // allOf: validation logic where its branches declare no shape. for name, key := range map[string]string{ "TwoMatch": "openapi:oneOf", "BothWithin": "openapi:oneOf", "FormatNotHeld": "openapi:anyOf", - "Overlapping": "openapi:oneOf", "Bounded": "openapi:anyOf", "BoundedOne": "openapi:oneOf", + "Bounded": "openapi:anyOf", "BoundedOne": "openapi:oneOf", "Patterned": "openapi:anyOf", "Described": "openapi:anyOf", } { reason, code := ir.ReasonDegradedLowering, diag.DegradedConstruct if name == "TwoMatch" || name == "BothWithin" { reason, code = ir.ReasonValidationOnly, diag.ValidationOnlyKeyword } + at := "/components/schemas/" + name + "/allOf/0" + if name == "FormatNotHeld" { + // Its uuid branch is the Union the position lowers to, which + // keeps the union holding the dead integer, reported at it. + code, at = diag.UnsatisfiableSchema, at+"/anyOf" + } kept := typeByName(doc, name).Common().Unmodeled[key] assert.Equal(t, reason, kept.Reason, "%s keeps the union, which says more", name) - assert.True(t, openapitest.HasDiagCodeAt(diags, code, "/components/schemas/"+name+"/allOf/0"), name) + assert.True(t, openapitest.HasDiagCodeAt(diags, code, at), name) } + // A union beside a body that is one $ref is a Union of its branches, each + // conjoined with the $ref as their allOf lowers, as beside its inline + // twin: the restating branch is the $ref's target. + overlapping, ok := typeByName(doc, "Overlapping").(*ir.Union) + require.True(t, ok, "Overlapping is the Union its inline twin is, not %T", typeByName(doc, "Overlapping")) + require.Len(t, overlapping.Variants, 2) + assert.Equal(t, componentID("Str"), overlapping.Variants[0].Type.Target) + assert.True(t, overlapping.Exclusive, "a date matching both is refused") + disjoint, ok := typeByName(doc, "Disjoint").(*ir.Scalar) require.True(t, ok, "a union sharing no kind with a boolean leaves the boolean") assert.Contains(t, disjoint.Unmodeled, "openapi:anyOf") - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Disjoint")) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Disjoint")) widest, ok := typeByName(doc, "Widest").(*ir.Union) require.True(t, ok, "Widest is its principal, the union, not %T", typeByName(doc, "Widest")) @@ -297,23 +312,23 @@ func TestRefinement_AUnionEntryIsAConjunct(t *testing.T) { // component and at a property, in either declaration order, the two spellings // lower alike, but for the key a union the principal does not say is kept under, // and none composes a model (GitHub #1685). The union's branch is written first, -// as the election's tie goes to the keywords beside the allOf before any entry. +// as the choice's tie goes to the keywords beside the allOf before any entry. func TestRefinement_AUnionBesideTheAllOfIsAConjunct(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { allOf, union string kept string // the key the beside spelling keeps its union under, "" for none }{ - "scalars": {allOf: "{type: string, maxLength: 10}", union: "anyOf: [{type: string}, {type: number}]"}, + "scalars": {allOf: "{type: string, maxLength: 10}", union: "anyOf: [{type: string}, {type: number}]", kept: "openapi:anyOf"}, "a union saying more": {allOf: "{type: string, maxLength: 10}", union: "anyOf: [{type: string, minLength: 2}, {type: number}]", kept: "openapi:anyOf"}, - "a $ref principal": {allOf: "{$ref: '#/components/schemas/Str'}", union: "anyOf: [{type: string}, {type: number}]"}, + "a $ref principal": {allOf: "{$ref: '#/components/schemas/Str'}", union: "anyOf: [{type: string}, {type: number}]", kept: "openapi:anyOf"}, "the union winning": {allOf: "{type: [string, number]}", union: "anyOf: [{type: string, format: uuid}, {type: integer}]"}, "a null tie": {allOf: "{type: [string, 'null']}", union: "anyOf: [{type: string}, {type: 'null'}]"}, "a oneOf overlapping": {allOf: "{type: string, maxLength: 10}", union: "oneOf: [{type: string}, {type: string, minLength: 2}, {type: number}]", kept: "openapi:oneOf"}, } { t.Run(name, func(t *testing.T) { t.Parallel() - beside, branch := "{allOf: ["+tc.allOf+"], "+tc.union+"}", "{allOf: [{"+tc.union+"}, "+tc.allOf+"]}" + beside, branch := "{allOf: ["+testCase.allOf+"], "+testCase.union+"}", "{allOf: [{"+testCase.union+"}, "+testCase.allOf+"]}" positions := " Beside: " + beside + "\n Branch: " + branch + "\n Holder:\n type: object\n" + " properties:\n beside: " + beside + "\n branch: " + branch + "\n" for _, doc := range unionConjunctOrders(t, positions) { @@ -321,23 +336,22 @@ func TestRefinement_AUnionBesideTheAllOfIsAConjunct(t *testing.T) { assert.Equal(t, propertyConjunct(t, doc, "branch"), propertyConjunct(t, doc, "beside"), "the property") _, composes := typeByName(doc, "Beside").(*ir.Model) assert.False(t, composes, "no conjunct admits an object") - property := propertyOf(t, doc, "Holder", "beside") - for _, kept := range []ir.Unmodeled{typeByName(doc, "Beside").Common().Unmodeled, property.Unmodeled} { - _, keeps := kept[tc.kept] - assert.Equal(t, tc.kept != "", keeps, "the union is kept under %q", tc.kept) + for _, kept := range []ir.Unmodeled{typeByName(doc, "Beside").Common().Unmodeled, keptAtProperty(t, doc, "beside")} { + _, keeps := kept[testCase.kept] + assert.Equal(t, testCase.kept != "", keeps, "the union is kept under %q", testCase.kept) } } }) } } -// TestRefinement_AUnionThePrincipalSaysIsConsumed pins a oneOf beside an allOf -// of a string whose string branch says nothing the principal does not and -// shares no kind with the other: the principal says the union, which is -// consumed. At 3.1 the component is an alias over the target and the property -// names it, neither keeping anything, and nothing is reported at either -// (docs/compilers/openapi.md#allof-refinement). -func TestRefinement_AUnionThePrincipalSaysIsConsumed(t *testing.T) { +// TestRefinement_AUnionThePrincipalSaysIsKeptWithItsDeadBranch pins a oneOf +// beside an allOf of a string whose string branch says nothing the principal +// does not and whose other branch shares no kind with it: that branch is dead, +// so the union is kept whole on the alias over the target, the dead branch +// reported at the union, and at a property the node over the target keeps it +// (docs/compilers/openapi.md#union-beside-structure). +func TestRefinement_AUnionThePrincipalSaysIsKeptWithItsDeadBranch(t *testing.T) { t.Parallel() const written = "{allOf: [{$ref: '#/components/schemas/Str'}], oneOf: [{type: string}, {type: boolean}]}" for _, doc := range unionConjunctOrders(t, " S: "+written+"\n"+ @@ -345,17 +359,14 @@ func TestRefinement_AUnionThePrincipalSaysIsConsumed(t *testing.T) { scalar, ok := typeByName(doc, "S").(*ir.Scalar) require.True(t, ok, "S is an alias over its principal, not %T", typeByName(doc, "S")) assert.Equal(t, componentID("Str"), scalar.Base.Target) - assert.Empty(t, scalar.Unmodeled, "the alias keeps nothing") - assert.Nil(t, scalar.Constraints, "the alias adds no bound") + assert.Equal(t, ir.ReasonDegradedLowering, scalar.Unmodeled["openapi:oneOf"].Reason, "the alias keeps the union") property := propertyOf(t, doc, "Holder", "f") - assert.Equal(t, componentID("Str"), property.Type.Target, "the property names the target") - assert.Empty(t, property.Unmodeled, "the property keeps nothing") - for _, diagnostic := range doc.Diagnostics { - at := string(diagnostic.Provenance.Pointer) - for _, written := range []string{"/components/schemas/S", "/components/schemas/Holder/properties/f"} { - assert.False(t, strings.HasSuffix(at, written) || strings.Contains(at, written+"/"), - "nothing is reported at %s: %s %s", written, diagnostic.Code, at) - } + node, ok := doc.Types[property.Type.Target].(*ir.Scalar) + require.True(t, ok, "the property names the node keeping the union") + assert.Equal(t, componentID("Str"), node.Base.Target) + assert.Contains(t, node.Unmodeled, "openapi:oneOf") + for _, at := range []string{"/components/schemas/S/oneOf", "/components/schemas/Holder/properties/f/oneOf"} { + assert.True(t, openapitest.HasDiagCodeAt(doc.Diagnostics, diag.UnsatisfiableSchema, at), "the dead branch is reported at %s", at) } } } @@ -363,8 +374,8 @@ func TestRefinement_AUnionThePrincipalSaysIsConsumed(t *testing.T) { // TestRefinement_TheKeywordsBesideWithAUnionLowerAsWithNoAllOf pins an allOf // whose principal is the keywords written beside it, a union among them: the // position lowers by them as if no allOf were written, a union alone as the -// union, one beside a kind as that kind with the union kept, never as a model -// (docs/compilers/openapi.md#allof-refinement). +// union, one of formats beside a string as the Union of its branches conjoined +// with it, never as a model (docs/compilers/openapi.md#allof-refinement). func TestRefinement_TheKeywordsBesideWithAUnionLowerAsWithNoAllOf(t *testing.T) { t.Parallel() for _, doc := range unionConjunctOrders(t, ` Kind: {type: string, allOf: [{maxLength: 3}], anyOf: [{format: uuid}, {format: email}]} @@ -373,19 +384,23 @@ func TestRefinement_TheKeywordsBesideWithAUnionLowerAsWithNoAllOf(t *testing.T) UnionAlone: {anyOf: [{type: string, format: uuid}, {type: integer}]} `) { for _, name := range []string{"Kind", "Union"} { - assert.Equal(t, componentConjunct(doc, name+"Alone"), componentConjunct(doc, name), name) + // A variant minted for the position sits under its name. + alone := strings.ReplaceAll(componentConjunct(doc, name+"Alone"), "/"+name+"Alone/", "/"+name+"/") + assert.Equal(t, alone, componentConjunct(doc, name), name) + } + for _, name := range []string{"Kind", "Union"} { + _, isUnion := typeByName(doc, name).(*ir.Union) + assert.True(t, isUnion, "the union decides %s, got %T", name, typeByName(doc, name)) } - assert.Equal(t, ir.ReasonDegradedLowering, typeByName(doc, "Kind").Common().Unmodeled["openapi:anyOf"].Reason) - _, isUnion := typeByName(doc, "Union").(*ir.Union) - assert.True(t, isUnion, "the union decides the position, got %T", typeByName(doc, "Union")) } } // TestRefinement_AShapelessUnionBesideIsValidationLogic pins a union beside an // allOf that refines to its principal whose branches declare no shape: it narrows // the use, as beside any body, so it is kept under validation_only and reported -// as such, at a component and at a carrier, where on an entry it stays with its -// entry (docs/compilers/openapi.md#allof-refinement). +// as such, at a component and at a property, on the node over the target +// sitting there, where on an entry it stays with its entry +// (docs/compilers/openapi.md#allof-refinement). func TestRefinement_AShapelessUnionBesideIsValidationLogic(t *testing.T) { t.Parallel() const union = "oneOf: [{minLength: 1}, {maxLength: 2}]" @@ -397,8 +412,10 @@ func TestRefinement_AShapelessUnionBesideIsValidationLogic(t *testing.T) { require.True(t, ok, "S is an alias over its principal, not %T", typeByName(doc, "S")) assert.Equal(t, componentID("Str"), scalar.Base.Target) property := propertyOf(t, doc, "Holder", "f") - assert.Equal(t, componentID("Str"), property.Type.Target) - for at, kept := range map[string]ir.Unmodeled{"/components/schemas/S": scalar.Unmodeled, "/components/schemas/Holder/properties/f": property.Unmodeled} { + node, ok := doc.Types[property.Type.Target].(*ir.Scalar) + require.True(t, ok, "the property names a node of its own") + assert.Equal(t, componentID("Str"), node.Base.Target) + for at, kept := range map[string]ir.Unmodeled{"/components/schemas/S": scalar.Unmodeled, "/components/schemas/Holder/properties/f": node.Unmodeled} { assert.Equal(t, ir.ReasonValidationOnly, kept["openapi:oneOf"].Reason, at) assert.Len(t, diagsAtPointer(doc.Diagnostics, diag.ValidationOnlyKeyword, at), 1, at) assert.Empty(t, diagsAtPointer(doc.Diagnostics, diag.DegradedConstruct, at), at) @@ -435,19 +452,36 @@ func componentConjunct(doc *ir.Document, name string) string { return conjunctShape(doc, ir.TypeRef{Target: componentID(name)}, nil, typeByName(doc, name).Common().Unmodeled) } -// propertyConjunct renders what Holder's property wire lowered to. +// propertyConjunct renders what Holder's property wire lowered to: a node +// at the property by what it is over, as a component is. func propertyConjunct(t *testing.T, doc *ir.Document, wire string) string { t.Helper() property := propertyOf(t, doc, "Holder", wire) + if scalar, ok := doc.Types[property.Type.Target].(*ir.Scalar); ok && scalar.Base != nil && scalar.Anonymous { + base := *scalar.Base + base.Nullable = base.Nullable || property.Type.Nullable + return conjunctShape(doc, base, scalar.Constraints, scalar.Unmodeled) + } return conjunctShape(doc, property.Type, property.Constraints, property.Unmodeled) } +// keptAtProperty is what Holder's property wire keeps, on itself or on the +// node at it. +func keptAtProperty(t *testing.T, doc *ir.Document, wire string) ir.Unmodeled { + t.Helper() + property := propertyOf(t, doc, "Holder", wire) + if node, ok := doc.Types[property.Type.Target]; ok && node.Common().Anonymous { + return node.Common().Unmodeled + } + return property.Unmodeled +} + // unionKeptKey matches a key a union is kept under, whichever spelling wrote it. var unionKeptKey = regexp.MustCompile(`^openapi:(oneOf|anyOf|allOf/\d+)$`) // conjunctShape renders a position that lowered to ref, with the bounds and the // kept keys a node or carrier holds beside it, for two spellings of one -// conjunction to compare: a union by its variants, wherever its node stands, and +// conjunction to compare: a union by its variants, wherever its node sits, and // a key a union is kept under by its reason alone. func conjunctShape(doc *ir.Document, ref ir.TypeRef, cons *ir.Constraints, kept ir.Unmodeled) string { target := []ir.TypeID{ref.Target} @@ -469,24 +503,108 @@ func conjunctShape(doc *ir.Document, ref ir.TypeRef, cons *ir.Constraints, kept } // TestRefinement_DisjointConjunctsStayAComposition pins what GitHub #1043 keeps: -// no value satisfies both entries, so the warnings stand on the model. +// no value satisfies both entries, so the warnings sit on the model. func TestRefinement_DisjointConjunctsStayAComposition(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string warns int }{ "two kinds": {"{allOf: [{type: integer}, {type: string}]}", 1}, - "a null alone": {"{allOf: [{type: string, nullable: true}, {type: integer, nullable: true}]}", 2}, "an object beside": {"{allOf: [{$ref: '#/components/schemas/Owner'}, {type: string}]}", 1}, } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", refinementTargets+" Disj: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", refinementTargets+" Disj: "+testCase.schema+"\n")) model, ok := typeByName(doc, "Disj").(*ir.Model) require.True(t, ok, "no value satisfies it, so nothing refines: got %T", typeByName(doc, "Disj")) assert.NotEmpty(t, model.Unmodeled, "each entry is kept") - assert.Equal(t, tc.warns, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning)) + assert.Equal(t, testCase.warns, openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning)) + }) + } +} + +// TestRefinement_AnInlinePrincipalReportsInOrder pins the order of what an +// allOf lowered from an inline entry reports. The entry's own findings, a +// keyword its node has no home for, come before the position's, the null a 3.0 +// nullable infers, whether the nullable is written on another entry or beside +// the allOf. Among the entry's own, what its node's readers keep comes before +// the content vocabulary that node holds none of, and a bound a number written +// as text cannot hold before what the node has no home for; a value set's +// entry reports before the position too, in the settlement's order. +func TestRefinement_AnInlinePrincipalReportsInOrder(t *testing.T) { + t.Parallel() + const entry = "/components/schemas/P/allOf/0" + nullableFindings := func(nullable string) []string { + return []string{ + "warning openapi/validation/validation-no-effect " + nullable, + "info " + diag.DegradedConstruct + " " + entry, + "info " + diag.InferredNullable + " " + nullable, + } + } + for name, testCase := range map[string]struct { + version, schema string + want []string + // messages, where set, names a phrase of each finding's message, in + // order, telling apart two findings want spells alike. + messages []string + }{ + "a nullable on another entry": { + version: "3.0.3", schema: "{allOf: [{type: string, maxItems: 2}, {nullable: true}]}", + want: nullableFindings("/components/schemas/P/allOf/1/nullable"), + }, + "a nullable beside the allOf": { + version: "3.0.3", schema: "{nullable: true, allOf: [{type: string, maxItems: 2}]}", + want: nullableFindings("/components/schemas/P/nullable"), + }, + "items and contentMediaType on an integer entry": { + version: "3.1.0", schema: "{allOf: [{type: integer, contentMediaType: text/plain, items: {type: string}, not: {const: 3}}], description: d}", + want: []string{ + "info " + diag.DegradedConstruct + " " + entry, + "info " + diag.DegradedConstruct + " " + entry + "/contentMediaType", + "info " + diag.ValidationOnlyKeyword + " " + entry, + }, + }, + "a number written as text at items": { + version: "3.1.0", schema: "{type: array, items: {allOf: [{type: string, format: int64, maxLength: 3, required: [a]}], unknownWord: 4}}", + want: []string{ + "info " + diag.UnhomedConstruct + " /components/schemas/P/items/allOf/0/maxLength", + "info " + diag.DegradedConstruct + " /components/schemas/P/items/allOf/0", + "info " + diag.UnknownSchemaKeyword + " /components/schemas/P/items/unknownWord", + }, + }, + "a number written as text with content and items": { + version: "3.1.0", schema: `{allOf: [{type: string, format: int64, maximum: 5, items: {type: string}, contentMediaType: text/plain, not: {const: "3"}}]}`, + want: []string{ + "info " + diag.UnhomedConstruct + " " + entry + "/maximum", + "info " + diag.DegradedConstruct + " " + entry, + "info " + diag.ValidationOnlyKeyword + " " + entry, + }, + }, + "a value set at items": { + // An Enum of strings holds a length (GitHub #2004), so the bounds + // it has no home for are numeric. + version: "3.1.0", schema: "{type: array, items: {allOf: [{enum: [a, b], maximum: 1, minimum: 1}], maximum: 5}}", + want: []string{ + "info " + diag.DegradedConstruct + " /components/schemas/P/items/allOf/0", + "info " + diag.DegradedConstruct + " /components/schemas/P/items/allOf/0", + "info " + diag.DegradedConstruct + " /components/schemas/P/items", + }, + messages: []string{"write maximum otherwise", "no home for minimum", "no home for maximum"}, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer(testCase.version, " P: "+testCase.schema+"\n")) + got := make([]string, 0, len(diags)) + for _, diagnostic := range diags { + got = append(got, fmt.Sprintf("%s %s %s", diagnostic.Severity, diagnostic.Code, diagnostic.Provenance.Pointer)) + } + assert.Equal(t, testCase.want, got) + for i, message := range testCase.messages { + require.Less(t, i, len(diags)) + assert.Contains(t, diags[i].Message, message, "finding %d", i) + } }) } } @@ -496,7 +614,7 @@ func TestRefinement_DisjointConjunctsStayAComposition(t *testing.T) { // names the target, with no node and no diagnostic. func TestRefinement_NamesItsTargetAtEveryPosition(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string target string }{ @@ -522,19 +640,19 @@ func TestRefinement_NamesItsTargetAtEveryPosition(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() targets := refinementTargets + " Maybe: {type: string, nullable: true}\n" - doc, diags := parseFull(t, positionsDoc(targets, tc.schema)) + doc, diags := parseFull(t, positionsDoc(targets, testCase.schema)) noDegradation(t, diags) carriers, nodes := positionRefs(t, doc) for position, ref := range carriers { - assert.Equal(t, componentID(tc.target), ref.Target, position) + assert.Equal(t, componentID(testCase.target), ref.Target, position) } for position, ref := range nodes { - assert.Equal(t, componentID(tc.target), ref.Target, position) + assert.Equal(t, componentID(testCase.target), ref.Target, position) } named, ok := typeByName(doc, "Named").(*ir.Scalar) require.True(t, ok, "a component keeps its name on an alias") require.NotNil(t, named.Base) - assert.Equal(t, componentID(tc.target), named.Base.Target) + assert.Equal(t, componentID(testCase.target), named.Base.Target) }) } } @@ -620,12 +738,50 @@ func TestRefinement_ACollectionBoundLandsAtEveryPosition(t *testing.T) { } } +// TestRefinement_AFormatNarrowingTheTargetSaysWhatEachIs pins the report on a +// $ref kept beside a format narrowing what its target is rooted at: the format +// and where it is written, an entry, beside the allOf or beside the $ref, what +// it makes the position, and what the target is, plain or rooted at a +// primitive of its own. +func TestRefinement_AFormatNarrowingTheTargetSaysWhatEachIs(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Id: {type: string} + Big: {type: integer, format: int64} + InEntry: {allOf: [{$ref: '#/components/schemas/Id'}, {format: uuid}]} + BesideAllOf: {allOf: [{$ref: '#/components/schemas/Id'}], format: uuid} + BesideRef: {$ref: '#/components/schemas/Id', format: uuid} + Narrower: {allOf: [{$ref: '#/components/schemas/Big'}, {format: int32}]} + Blob: {allOf: [{$ref: '#/components/schemas/Id'}, {format: binary}]} + Nested: {allOf: [{allOf: [{$ref: '#/components/schemas/Id'}, {format: date}]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + const plainString = `the $ref target "#/components/schemas/Id" is a plain string` + for position, want := range map[string]string{ + "InEntry/allOf/0": "format: uuid on allOf/1 makes this allOf a uuid, while " + plainString + "; lowered as a uuid", + "BesideAllOf/allOf/0": "format: uuid beside the allOf makes this allOf a uuid, while " + plainString + "; lowered as a uuid", + "BesideRef": "format: uuid beside its $ref makes this schema a uuid, while " + plainString + "; lowered as a uuid", + "Blob/allOf/0": "format: binary on allOf/1 makes this allOf bytes, while " + plainString + "; lowered as bytes", + "Nested/allOf/0/allOf/0": "format: date on allOf/0/allOf/1 makes this allOf a date, while " + plainString + "; lowered as a date", + "Narrower/allOf/0": `format: int32 on allOf/1 makes this allOf an int32, while the $ref target "#/components/schemas/Big" ` + + "is an int64; lowered as an int32", + } { + reports := diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/"+position) + if assert.Len(t, reports, 1, position) { + assert.Equal(t, want+" with the $ref kept under Unmodeled", reports[0].Message, position) + } + } +} + // TestRefinement_KeptKeywordsLandAtEveryPosition pins what no reference can // hold: a narrower keyword beside the allOf or in an entry, kept verbatim under -// its own key where the position keeps what it writes, with one report. +// its own key where the position keeps what it writes, with one report. A +// format narrowing the primitive a $ref's target is rooted at chooses its +// conjunct, so what no node holds is the $ref, kept so. A keyword saying +// nothing narrows nothing and is kept nowhere +// (TestRefinement_AKeywordSayingNothingLowersAsLeftOut). func TestRefinement_KeptKeywordsLandAtEveryPosition(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string key string report string @@ -635,11 +791,13 @@ func TestRefinement_KeptKeywordsLandAtEveryPosition(t *testing.T) { }{ "a narrower type beside": { schema: "{allOf: [{$ref: '#/components/schemas/Port'}], type: integer, format: int32}", - key: "openapi:format", report: "no home for format declared beside it", + key: "openapi:$ref", report: `format: int32 beside the allOf makes this allOf an int32, while the $ref target ` + + `"#/components/schemas/Port" is a plain integer; lowered as an int32 with the $ref kept under Unmodeled`, }, "a format in an entry": { schema: "{allOf: [{$ref: '#/components/schemas/Port'}, {type: integer, format: int32}]}", - key: "openapi:format", report: "no home for format written on this inline entry", + key: "openapi:$ref", report: `format: int32 on allOf/1 makes this allOf an int32, while the $ref target ` + + `"#/components/schemas/Port" is a plain integer; lowered as an int32 with the $ref kept under Unmodeled`, }, "a type narrowing a number": { schema: "{allOf: [{$ref: '#/components/schemas/Num'}, {type: integer}]}", @@ -649,10 +807,6 @@ func TestRefinement_KeptKeywordsLandAtEveryPosition(t *testing.T) { schema: "{allOf: [{$ref: '#/components/schemas/Names'}, {type: array, items: {type: string, minLength: 1}}]}", key: "openapi:items", report: "no home for items written on this inline entry", }, - "a collection bound no field states": { - schema: "{allOf: [{$ref: '#/components/schemas/Names'}, {uniqueItems: false}]}", - key: "openapi:uniqueItems", report: "no home for uniqueItems written on this inline entry", - }, "an overlapping enum": { schema: "{allOf: [{$ref: '#/components/schemas/Mode'}, {enum: [set, put]}]}", key: "openapi:enum", report: "no home for enum written on this inline entry", @@ -666,16 +820,16 @@ func TestRefinement_KeptKeywordsLandAtEveryPosition(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() targets := refinementTargets + " Num: {type: number}\n" - doc, diags := parseFull(t, positionsDoc(targets, tc.schema)) + doc, diags := parseFull(t, positionsDoc(targets, testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) code, reason := diag.DegradedConstruct, ir.ReasonDegradedLowering - if tc.code != "" { - code, reason = tc.code, tc.reason + if testCase.code != "" { + code, reason = testCase.code, testCase.reason } held := func(where string, unmodeled ir.Unmodeled) { t.Helper() - entry, ok := unmodeled[tc.key] - if assert.True(t, ok, "%s keeps %s: got %v", where, tc.key, unmodeled) { + entry, ok := unmodeled[testCase.key] + if assert.True(t, ok, "%s keeps %s: got %v", where, testCase.key, unmodeled) { assert.Equal(t, reason, entry.Reason, where) } } @@ -693,12 +847,12 @@ func TestRefinement_KeptKeywordsLandAtEveryPosition(t *testing.T) { require.True(t, ok) held("a component", named.Unmodeled) for _, target := range []string{"Port", "Num", "Names", "Mode", "Str"} { - assert.NotContains(t, typeByName(doc, target).Common().Unmodeled, tc.key, "%s is shared", target) + assert.NotContains(t, typeByName(doc, target).Common().Unmodeled, testCase.key, "%s is shared", target) } var reports []string for _, diagnostic := range withCode(diags, code) { reports = append(reports, diagnostic.Message) - assert.Contains(t, diagnostic.Message, tc.report) + assert.Contains(t, diagnostic.Message, testCase.report) assert.Equal(t, ir.SeverityInfo, diagnostic.Severity) } assert.NotEmpty(t, reports) @@ -711,6 +865,43 @@ func TestRefinement_KeptKeywordsLandAtEveryPosition(t *testing.T) { } } +// TestRefinement_AKeywordSayingNothingLowersAsLeftOut pins an entry writing +// a keyword at the value OpenAPI 3.0 equates with its absence beside a $ref: +// the entry says nothing, so at every position the document lowers, keeps and +// reports as its twin writing an empty entry does. +func TestRefinement_AKeywordSayingNothingLowersAsLeftOut(t *testing.T) { + t.Parallel() + const ref = "{$ref: '#/components/schemas/Names'}" + equivalent := compiledText(t, positionsDoc(refinementTargets, "{allOf: ["+ref+", {}]}")) + for _, keyword := range []string{ + "nullable: false", "readOnly: false", "writeOnly: false", "deprecated: false", "uniqueItems: false", + "minLength: 0", "minItems: 0", "minProperties: 0", "exclusiveMinimum: false", "exclusiveMaximum: false", + "pattern: ''", + } { + t.Run(keyword, func(t *testing.T) { + t.Parallel() + assert.Equal(t, equivalent, compiledText(t, positionsDoc(refinementTargets, "{allOf: ["+ref+", {"+keyword+"}]}"))) + }) + } +} + +// compiledText is what src compiles to as text: its types as their JSON +// encodes them, then each finding's severity, code, pointer and message, +// sorted. +func compiledText(t *testing.T, src string) string { + t.Helper() + doc, diags := parseFull(t, src) + raw, err := json.Marshal(doc.Types, json.Deterministic(true)) + require.NoError(t, err) + findings := make([]string, 0, len(diags)) + for _, diagnostic := range diags { + findings = append(findings, fmt.Sprintf("%s %s %s %s", diagnostic.Severity, diagnostic.Code, + diagnostic.Provenance.Pointer, diagnostic.Message)) + } + slices.Sort(findings) + return string(raw) + "\n" + strings.Join(findings, "\n") +} + // TestRefinement_SeveralRefsUseTheNarrowest pins two $refs no object can // satisfy: the position is a use of the one lying within more conjuncts, the // enum within the string, and keeps the other with one info, in either order @@ -744,7 +935,7 @@ func TestRefinement_SeveralRefsUseTheNarrowest(t *testing.T) { // composition they were, with nothing dropped. func TestRefinement_ReachesNoFurtherThanItCanRead(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schemas string errs bool }{ @@ -755,35 +946,60 @@ func TestRefinement_ReachesNoFurtherThanItCanRead(t *testing.T) { "a false target": { schemas: " No: false\n S: {allOf: [{$ref: '#/components/schemas/No'}, {type: string}]}\n", }, - "a type no schema defines": {schemas: " S: {allOf: [{type: file}]}\n", errs: true}, - "a false entry": {schemas: " S: {allOf: [{type: string}, false]}\n"}, - "a cycle": {schemas: " S: {allOf: [{$ref: '#/components/schemas/S'}], type: string}\n"}, - "a cycle of two": { - schemas: " S: {allOf: [{$ref: '#/components/schemas/R'}]}\n R: {allOf: [{$ref: '#/components/schemas/S'}]}\n", - }, - "an unresolved $ref": {schemas: " S: {allOf: [{$ref: '#/components/schemas/Gone'}, {type: string}]}\n", errs: true}, + "a false entry": {schemas: " S: {allOf: [{type: string}, false]}\n"}, "a target narrowing an object": { schemas: " S: {allOf: [{$ref: '#/components/schemas/Owner'}, {type: object}]}\n", }, } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+tc.schemas)) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+testCase.schemas)) _, failed := ir.FirstError(diags) - assert.Equal(t, tc.errs, failed, "%+v", diags) + assert.Equal(t, testCase.errs, failed, "%+v", diags) _, ok := typeByName(doc, "S").(*ir.Model) assert.True(t, ok, "got %T", typeByName(doc, "S")) }) } } +// TestRefinement_AReferenceAdmittingEveryKindLeavesTheOthersToDecide pins a +// $ref beside a string that cuts no read: one leading back to the position, a +// loop, and one naming nothing each admit every kind, so the string decides, +// the reference kept verbatim. A cycle of two hops with nothing beside them is +// a reference loop, reported as one, so it is no Model. +func TestRefinement_AReferenceAdmittingEveryKindLeavesTheOthersToDecide(t *testing.T) { + t.Parallel() + for name, testCase := range map[string]struct { + schema string + errs bool + }{ + "a cycle": {"{allOf: [{$ref: '#/components/schemas/S'}], type: string}", false}, + "an unresolved $ref": {"{allOf: [{$ref: '#/components/schemas/Gone'}, {type: string}]}", true}, + } { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+" S: "+testCase.schema+"\n")) + _, failed := ir.FirstError(diags) + assert.Equal(t, testCase.errs, failed, "%s: %+v", name, diags) + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + if assert.True(t, ok, "%s: got %T", name, typeByName(doc, "S")) && assert.NotNil(t, scalar.Base, name) { + assert.Equal(t, primitive(ir.PrimitiveString), scalar.Base.Target, name) + assert.Contains(t, scalar.Unmodeled, "openapi:$ref", name) + } + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+ + " S: {allOf: [{$ref: '#/components/schemas/R'}]}\n R: {allOf: [{$ref: '#/components/schemas/S'}]}\n")) + _, composed := typeByName(doc, "S").(*ir.Model) + assert.False(t, composed, "a reference loop is no Model: got %T", typeByName(doc, "S")) + assert.Equal(t, []string{"/components/schemas/R"}, pointerStrings(openapitest.PointersOf(diags, diag.CyclicRef)), + "the loop is reported once, at its least member") +} + // TestRefinement_KindsBeyondAnObjectAreAUse pins each allOf whose kinds are // more than an object, or another kind a keyword only a model holds speaks of: // none is a model, which would assert an object the source does not, so each // is a use of what decides it, keeping what it cannot hold. func TestRefinement_KindsBeyondAnObjectAreAUse(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schemas string base ir.TypeID }{ @@ -811,11 +1027,11 @@ func TestRefinement_KindsBeyondAnObjectAreAUse(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+tc.schemas)) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+testCase.schemas)) openapitest.RequireNoErrorDiags(t, diags) scalar, ok := typeByName(doc, "S").(*ir.Scalar) require.True(t, ok, "got %T", typeByName(doc, "S")) - assert.Equal(t, tc.base, scalar.Base.Target) + assert.Equal(t, testCase.base, scalar.Base.Target) }) } } @@ -887,10 +1103,10 @@ func TestRefinement_ATypeBesideTheAllOfIsThePosition(t *testing.T) { assert.NotContains(t, listed.Unmodeled, "openapi:minItems", "the list holds what it is written beside") } -// TestRefinement_AValueSetNarrowsTheRefItBeats is GitHub #1042's position-level -// half: an entry's enum is the position's value set, and the $ref it narrows -// still speaks for the field and stays verbatim. -func TestRefinement_AValueSetNarrowsTheRefItBeats(t *testing.T) { +// TestRefinement_AValueSetNarrowsTheRefItIsChosenOver is GitHub #1042's +// position-level half: an entry's enum is the position's value set, and the +// $ref it narrows still speaks for the field and stays verbatim. +func TestRefinement_AValueSetNarrowsTheRefItIsChosenOver(t *testing.T) { t.Parallel() const targets = ` Op: type: string @@ -971,7 +1187,7 @@ func firstDocs(doc *ir.Document, property ir.Property) ir.Docs { } // TestRefinement_ANarrowingKeepsItsTargetOnANode pins the narrowing at a -// position no carrier holds: the enum standing at the position holds the +// position no carrier holds: the enum at the position holds the // $ref's verbatim entry and what the $ref says of the position too. func TestRefinement_ANarrowingKeepsItsTargetOnANode(t *testing.T) { t.Parallel() @@ -991,7 +1207,7 @@ func TestRefinement_ANarrowingKeepsItsTargetOnANode(t *testing.T) { // TestRefinement_ANarrowedRefStillLowersItsTarget pins what a kept $ref names: a // position no component holds is lowered by a reference alone, and a narrowing -// keeps the reference, so the target's node stands as it does beneath a Base. +// keeps the reference, so the target's node is it does beneath a Base. func TestRefinement_ANarrowedRefStillLowersItsTarget(t *testing.T) { t.Parallel() const mode = "{$ref: '#/components/schemas/Host/$defs/Mode'}" @@ -1016,13 +1232,13 @@ func TestRefinement_ANarrowedRefStillLowersItsTarget(t *testing.T) { // TestRefinement_AValueSetIsTypedByEveryConjunct pins GitHub #1641: the value // set a refinement lowers to takes its ValueType from the type and format every // conjunct declares, as one schema writing them all gives it, and keeps none of -// them. Two formats neither of which narrows the other select no one primitive, -// nor does one the value is not of or one written with no type, so each stays -// with its entry. +// them, a format written with no type among them. Two formats neither of which +// narrows the other select no one primitive, so each stays with its entry while +// the type both entries state alike folds; and one the value is not of is kept. func TestRefinement_AValueSetIsTypedByEveryConjunct(t *testing.T) { t.Parallel() const uuid = `"0b5c6f4e-6b9e-4a77-9f0f-5b0b8d5c1a11"` - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { written string want ir.PrimitiveKind kept []string @@ -1044,30 +1260,29 @@ func TestRefinement_AValueSetIsTypedByEveryConjunct(t *testing.T) { "a $ref to a refinement": {"{allOf: [{$ref: '#/components/schemas/Port'}, {enum: [80]}]}", ir.PrimitiveInt32, []string{"openapi:$ref"}}, "two formats": {"{allOf: [{type: integer, format: int8}, {type: integer, format: uint8}, {const: 80}]}", - ir.PrimitiveNumber, []string{"openapi:allOf/0", "openapi:allOf/1"}}, + ir.PrimitiveInteger, []string{"openapi:allOf/0", "openapi:allOf/1"}}, "a format the value is not of": {"{allOf: [{type: integer, format: int8}, {const: 300}]}", ir.PrimitiveInteger, []string{"openapi:format"}}, "a format a member is not of": {"{allOf: [{type: integer, format: int8}, {enum: [1, 300]}]}", ir.PrimitiveInteger, []string{"openapi:format"}}, - "a format with no type": {"{allOf: [{type: integer}, {format: int32}, {const: 80}]}", ir.PrimitiveInteger, - []string{"openapi:format"}}, + "a format with no type": {"{allOf: [{type: integer}, {format: int32}, {const: 80}]}", ir.PrimitiveInt32, nil}, } { t.Run(name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Int32: {type: integer, format: int32}\n Port: {allOf: [{$ref: '#/components/schemas/Int32'}]}\n"+ - " S: "+tc.written+"\n")) + " S: "+testCase.written+"\n")) openapitest.RequireNoErrorDiags(t, diags) node := typeByName(doc, "S") switch n := node.(type) { case *ir.Literal: - assert.Equal(t, tc.want, n.ValueType) + assert.Equal(t, testCase.want, n.ValueType) case *ir.Enum: - assert.Equal(t, tc.want, n.ValueType) + assert.Equal(t, testCase.want, n.ValueType) default: t.Fatalf("lowered to %T", node) } - assert.Equal(t, tc.kept, unmodeledKeys(node.Common().Unmodeled), "the value set stands at the position") + assert.Equal(t, testCase.kept, unmodeledKeys(node.Common().Unmodeled), "the value set sits at the position") }) } } @@ -1100,9 +1315,9 @@ func TestRefinement_ARefToAPrincipalNamesItsTypedNode(t *testing.T) { // a const beside an allOf that refines is one of its conjuncts, not its rival. It // lowers as if no allOf were written where it is the principal, with what the // entries say folded as written beside it, and a narrower entry is the -// principal. An entry writing what the enum has no field for stays whole, though -// the enum holds its format. Beside an allOf that composes, the enum still wins -// and keeps the allOf. +// principal. An entry's bound of the kind the enum lists goes to the Enum's +// Constraints, beside the format its ValueType holds (GitHub #2004). Beside an +// allOf that composes, the enum still wins and keeps the allOf. func TestRefinement_AValueSetBesideTheAllOfIsAConjunct(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", ` Flat: {type: string, enum: [a], description: the level, deprecated: true} @@ -1124,7 +1339,7 @@ func TestRefinement_AValueSetBesideTheAllOfIsAConjunct(t *testing.T) { assert.Empty(t, lit.Unmodeled) en, ok := typeByName(doc, "Narrowed").(*ir.Enum) - require.True(t, ok, "the narrower entry is the principal, standing at the position: got %T", typeByName(doc, "Narrowed")) + require.True(t, ok, "the narrower entry is the principal, sitting at the position: got %T", typeByName(doc, "Narrowed")) assert.Len(t, en.Members, 1) assert.Empty(t, en.Unmodeled, "the wider set beside it says nothing more") for _, at := range []string{"/components/schemas/Noted", "/components/schemas/Const", "/components/schemas/Narrowed"} { @@ -1134,14 +1349,14 @@ func TestRefinement_AValueSetBesideTheAllOfIsAConjunct(t *testing.T) { bounded, ok := typeByName(doc, "Bounded").(*ir.Enum) require.True(t, ok, "got %T", typeByName(doc, "Bounded")) assert.Equal(t, ir.PrimitiveInt64, bounded.ValueType) - assert.Equal(t, []string{"openapi:maximum"}, unmodeledKeys(bounded.Unmodeled)) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, - "/components/schemas/Bounded/allOf/0"), "no home for maximum written on this inline entry") + assert.Equal(t, &ir.Constraints{Max: new(ir.BigVal("10"))}, bounded.Constraints) + assert.Empty(t, bounded.Unmodeled) + assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Bounded/allOf/0")) composes, ok := typeByName(doc, "Composes").(*ir.Enum) require.True(t, ok) assert.Equal(t, []string{"openapi:properties", "openapi:type"}, unmodeledKeys(composes.Unmodeled), - "the election's loser is kept keyword by keyword") + "the one passed over is kept keyword by keyword") assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Composes/allOf/0"), "no home for type, properties written on this inline entry") } @@ -1195,7 +1410,7 @@ func TestRefinement_ACarrierReadsThroughARefinement(t *testing.T) { // (docs/compilers/openapi.md#allof-redeclared-property). func TestRefinement_AHoistingFormatNarrowsItsKind(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { a, b string want func(t *testing.T, doc *ir.Document, id ir.TypeID) }{ @@ -1263,12 +1478,12 @@ func TestRefinement_AHoistingFormatNarrowsItsKind(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, entries := range [][2]string{{tc.a, tc.b}, {tc.b, tc.a}} { + for _, entries := range [][2]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Holder:\n type: object\n"+ " properties:\n f: {allOf: ["+entries[0]+", "+entries[1]+"]}\n")) assert.Empty(t, withCode(diags, diag.DegradedConstruct), entries) property := propertyOf(t, doc, "Holder", "f") - tc.want(t, doc, property.Type.Target) + testCase.want(t, doc, property.Type.Target) assert.Empty(t, property.Unmodeled, "the wider entry says nothing the narrower does not") } }) @@ -1304,50 +1519,55 @@ func TestRefinement_AValueComparesAsAnEnumEntryDoes(t *testing.T) { } } -// TestRefinement_ATieOfKindsNeitherWithinTheOtherElectsNone pins two +// TestRefinement_ATieOfKindsNeitherWithinTheOtherChoosesNone pins two // conjuncts naming kinds neither of which lies within the other, as many // conjuncts lying within each: no rule ranks them, so neither is the // principal, and in either order the position is the primitive of the kinds // they admit together, or the top type where those are an array, keeping both // with a report at each: whole where they write one keyword apart, else each -// keyword under its own key. Beside the allOf, the keywords there decide, as -// they do wherever no entry is elected. -func TestRefinement_ATieOfKindsNeitherWithinTheOtherElectsNone(t *testing.T) { +// keyword under its own key, but a type naming exactly the primitive, which +// the node restates. Beside the allOf, the keywords there decide, as they do +// wherever no entry is chosen. +func TestRefinement_ATieOfKindsNeitherWithinTheOtherChoosesNone(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { a, b string // primitive is what the position is. primitive ir.PrimitiveKind // keys are what it keeps, both entries whole where nil. keys []string + // reported is the one entry drawing a report, both where "". + reported string }{ - "two hoisting formats": {"{type: string, format: email}", "{type: string, format: hostname}", ir.PrimitiveString, nil}, - "two table formats": {"{type: string, format: date}", "{type: string, format: uuid}", ir.PrimitiveString, nil}, + "two hoisting formats": {"{type: string, format: email}", "{type: string, format: hostname}", ir.PrimitiveString, nil, ""}, + "two table formats": {"{type: string, format: date}", "{type: string, format: uuid}", ir.PrimitiveString, nil, ""}, "a format and a bare wider one": {"{type: integer, format: int32}", "{type: integer, format: uint32}", - ir.PrimitiveInteger, nil}, - "an overlap of value sets": {"{enum: [a, b]}", "{enum: [b, c]}", ir.PrimitiveString, nil}, + ir.PrimitiveInteger, nil, ""}, "two element types": {"{type: array, items: {type: string}}", "{type: array, items: {type: integer}}", - ir.PrimitiveAny, nil}, + ir.PrimitiveAny, nil, ""}, "a value set reaching past a type": {"{type: string}", "{enum: [a, 1]}", ir.PrimitiveString, - []string{"openapi:enum", "openapi:type"}}, - "two type lists": {"{type: [string, boolean]}", "{type: [string, integer]}", ir.PrimitiveString, nil}, + []string{"openapi:enum"}, "{enum: [a, 1]}"}, + "two type lists": {"{type: [string, boolean]}", "{type: [string, integer]}", ir.PrimitiveString, nil, ""}, } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, entries := range []string{tc.a + ", " + tc.b, tc.b + ", " + tc.a} { + for _, order := range [][]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { + entries := strings.Join(order, ", ") doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Holder:\n type: object\n"+ " properties:\n f: {allOf: ["+entries+"]}\n")) openapitest.RequireNoErrorDiags(t, diags) property := propertyOf(t, doc, "Holder", "f") - assert.Equal(t, ir.PrimitiveTypeID(tc.primitive), property.Type.Target, entries) - keys := tc.keys + assert.Equal(t, ir.PrimitiveTypeID(testCase.primitive), property.Type.Target, entries) + keys := testCase.keys if keys == nil { keys = []string{"openapi:allOf/0", "openapi:allOf/1"} } assert.Equal(t, keys, slices.Sorted(maps.Keys(property.Unmodeled)), entries) - assert.Equal(t, []jsontext.Pointer{ - "/components/schemas/Holder/properties/f/allOf/0", "/components/schemas/Holder/properties/f/allOf/1", - }, openapitest.PointersOf(diags, diag.DegradedConstruct), entries) + reported := []jsontext.Pointer{"/components/schemas/Holder/properties/f/allOf/0", "/components/schemas/Holder/properties/f/allOf/1"} + if testCase.reported != "" { + reported = []jsontext.Pointer{jsontext.Pointer(fmt.Sprintf("/components/schemas/Holder/properties/f/allOf/%d", slices.Index(order, testCase.reported)))} + } + assert.Equal(t, reported, openapitest.PointersOf(diags, diag.DegradedConstruct), entries) } }) } @@ -1366,14 +1586,15 @@ func TestRefinement_ATieOfKindsNeitherWithinTheOtherElectsNone(t *testing.T) { // TestRefinement_AlikeConjunctsPartOnWhatTheirNodeReads pins ties between // conjuncts admitting alike, in either order: the one writing a keyword its // node reads from it alone is the principal, keeping nothing; two writing such -// keywords otherwise elect neither, the string both admit keeping both; a union written +// keywords otherwise choose neither, the string both admit taking each from its +// conjunct, the type both write kept once; a union written // twice is one, kept nowhere; and words beside the allOf tying with an entry -// stand for the position, the entry folding, so a value set there is the +// name the position, the entry folding, so a value set there is the // position's own node. func TestRefinement_AlikeConjunctsPartOnWhatTheirNodeReads(t *testing.T) { t.Parallel() const union = "{oneOf: [{type: string}, {type: integer}]}" - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { beside, a, b string kept int top bool @@ -1382,10 +1603,10 @@ func TestRefinement_AlikeConjunctsPartOnWhatTheirNodeReads(t *testing.T) { reports int }{ "one writes content": {"", "{type: string}", "{type: string, contentEncoding: base64}", 0, false, "", 0}, - // The type both write alike is kept once; each content keyword is - // reported at itself, and each entry's type at the entry. + // The content vocabulary reaches any conjunct, and the type both write + // the string node they lower to restates: nothing is kept or reported. "each writes other": {"", "{type: string, contentEncoding: base64}", "{type: string, contentMediaType: text/plain}", - 3, false, ir.PrimitiveTypeID(ir.PrimitiveString), 4}, + 0, false, "type/anonymous/components/schemas/Holder/properties/f", 0}, "a union written twice": {"", union, union, 0, false, "", 0}, "words beside the allOf": {"type: string, ", "{type: string, description: d}", "{type: string, minLength: 1}", 0, false, "", 0}, "a set beside the allOf": {"enum: [a, b], ", "{enum: [b, a]}", "{enum: [a, b], description: d}", 0, false, @@ -1393,16 +1614,16 @@ func TestRefinement_AlikeConjunctsPartOnWhatTheirNodeReads(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, entries := range []string{tc.a + ", " + tc.b, tc.b + ", " + tc.a} { + for _, entries := range []string{testCase.a + ", " + testCase.b, testCase.b + ", " + testCase.a} { doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Holder:\n type: object\n"+ - " properties:\n f: {"+tc.beside+"allOf: ["+entries+"]}\n")) + " properties:\n f: {"+testCase.beside+"allOf: ["+entries+"]}\n")) openapitest.RequireNoErrorDiags(t, diags) property := propertyOf(t, doc, "Holder", "f") - assert.Equal(t, tc.top, property.Type.Target == ir.PrimitiveTypeID(ir.PrimitiveAny), entries) - assert.Len(t, property.Unmodeled, tc.kept, entries) - assert.Len(t, withCode(diags, diag.DegradedConstruct), max(tc.kept, tc.reports), entries) - if tc.node != "" { - assert.Equal(t, tc.node, property.Type.Target, entries) + assert.Equal(t, testCase.top, property.Type.Target == ir.PrimitiveTypeID(ir.PrimitiveAny), entries) + assert.Len(t, property.Unmodeled, testCase.kept, entries) + assert.Len(t, withCode(diags, diag.DegradedConstruct), max(testCase.kept, testCase.reports), entries) + if testCase.node != "" { + assert.Equal(t, testCase.node, property.Type.Target, entries) } } }) @@ -1413,11 +1634,11 @@ func TestRefinement_AlikeConjunctsPartOnWhatTheirNodeReads(t *testing.T) { // where a target is declared decide nothing, by two whole documents. func TestRefinement_DecidedByTheSetInEveryOrder(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct{ a, b string }{ + for name, testCase := range map[string]struct{ a, b string }{ "annotations": {"{description: mine}", "{$ref: '#/components/schemas/Str'}"}, "a narrowing": {"{enum: [a]}", "{$ref: '#/components/schemas/Str'}"}, - "a meet": {"{type: integer}", "{type: integer, format: int32}"}, - "two voices": {"{description: mine}", "{minLength: 1}"}, + "an intersection": {"{type: integer}", "{type: integer, format: int32}"}, + "two conjuncts": {"{description: mine}", "{minLength: 1}"}, "a kept one": {"{$ref: '#/components/schemas/Port'}", "{format: int32}"}, "a format with no kind": {"{type: integer}", "{format: int32}"}, "items with no kind": {"{type: array}", "{items: {type: string}}"}, @@ -1438,15 +1659,15 @@ func TestRefinement_DecidedByTheSetInEveryOrder(t *testing.T) { } return doc, out } - after, reportsA := compile(tc.a, tc.b, refinementTargets) - before, reportsB := compile(tc.b, tc.a, refinementTargets) + after, reportsA := compile(testCase.a, testCase.b, refinementTargets) + before, reportsB := compile(testCase.b, testCase.a, refinementTargets) if diff := cmp.Diff(typeShapes(after), typeShapes(before)); diff != "" { t.Errorf("the entries' order decided the node (-a +b):\n%s", diff) } assert.ElementsMatch(t, reportsA, reportsB) first, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+ - " Holder:\n type: object\n properties:\n f: {allOf: ["+tc.a+", "+tc.b+"]}\n")) + " Holder:\n type: object\n properties:\n f: {allOf: ["+testCase.a+", "+testCase.b+"]}\n")) if diff := cmp.Diff(after.Types, first.Types, orderInvariantIR()...); diff != "" { t.Errorf("the declaration order decided the document (-after +before):\n%s", diff) } @@ -1455,28 +1676,29 @@ func TestRefinement_DecidedByTheSetInEveryOrder(t *testing.T) { } // TestRefinement_ANoKindConjunctIsNeverThePrincipal pins that a conjunct naming -// no kind cannot decide what the position is: its `format`, `maxItems` or -// `items` qualifies a kind, so it stays beside the conjunct that names one, in -// either order, and the position is no top type. The kind-inference policy -// reads an `items` as an array where nothing declares a kind, never against a -// conjunct that does. +// no kind cannot decide what the position is: its `maxItems` or `items` +// qualifies a kind it does not hold, so it stays beside the conjunct that +// names one, in either order, and the position is no top type. The +// kind-inference policy reads an `items` as an array where nothing declares a +// kind, never against a conjunct that does. A `format` the kind takes is read +// off the conjunct writing it, as written beside the kind +// (TestRefinement_AFormatOnAnEntryTypesTheKindBesideIt). func TestRefinement_ANoKindConjunctIsNeverThePrincipal(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { kinded, unkinded string want ir.TypeID }{ - "format": {"{type: integer}", "{format: int32}", "type/primitive/integer"}, "maxItems": {"{type: string}", "{maxItems: 2}", "type/primitive/string"}, "items": {"{type: string}", "{items: {type: string}}", "type/primitive/string"}, } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, entries := range []string{tc.kinded + ", " + tc.unkinded, tc.unkinded + ", " + tc.kinded} { + for _, entries := range []string{testCase.kinded + ", " + testCase.unkinded, testCase.unkinded + ", " + testCase.kinded} { doc, diags := parseFull(t, openapitest.ComponentSpec(" T: {allOf: ["+entries+"]}\n")) alias, ok := doc.Types[componentID("T")].(*ir.Scalar) require.True(t, ok, "%s: %#v", entries, doc.Types[componentID("T")]) - assert.Equal(t, tc.want, alias.Base.Target, entries) + assert.Equal(t, testCase.want, alias.Base.Target, entries) assert.Len(t, alias.Unmodeled, 1, "the conjunct naming no kind is kept: %s", entries) assert.Len(t, diags, 1, "and reported once: %s", entries) } @@ -1484,13 +1706,31 @@ func TestRefinement_ANoKindConjunctIsNeverThePrincipal(t *testing.T) { } } +// TestRefinement_AFormatOnAnEntryTypesTheKindBesideIt pins a `format` on an +// entry beside one declaring the kind it qualifies: the node reads the format +// off the conjunct writing it, so the position is the primitive the two select +// written flat, with nothing kept or reported, in either order. +func TestRefinement_AFormatOnAnEntryTypesTheKindBesideIt(t *testing.T) { + t.Parallel() + for _, entries := range []string{"{type: integer}, {format: int32}", "{format: int32}, {type: integer}"} { + doc, diags := parseFull(t, openapitest.ComponentSpec(" T: {allOf: ["+entries+"]}\n")) + alias, ok := doc.Types[componentID("T")].(*ir.Scalar) + require.True(t, ok, "%s: %#v", entries, doc.Types[componentID("T")]) + require.NotNil(t, alias.Base, entries) + assert.Equal(t, primitive(ir.PrimitiveInt32), alias.Base.Target, entries) + assert.Empty(t, alias.Unmodeled, entries) + assert.Empty(t, diags, entries) + } +} + // TestRefinement_BooleanItemsReadAsWhatTheyAdmit pins `items: true`, which says -// nothing, so a list saying more beats it, and `items: false`, which admits no -// element, so it beats a list saying less. Each element type stands in either -// order, and the other entry keeps nothing, since nothing it says is left unsaid. +// nothing, so a list saying more is chosen over it, and `items: false`, which +// admits no element, so it is chosen over a list saying less. Each element type +// holds in either order, and the other entry keeps nothing, since nothing it +// says is left unsaid. func TestRefinement_BooleanItemsReadAsWhatTheyAdmit(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { list, other string element ir.TypeKind }{ @@ -1500,11 +1740,11 @@ func TestRefinement_BooleanItemsReadAsWhatTheyAdmit(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, entries := range []string{tc.list + ", " + tc.other, tc.other + ", " + tc.list} { + for _, entries := range []string{testCase.list + ", " + testCase.other, testCase.other + ", " + testCase.list} { doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " T: {allOf: ["+entries+"]}\n")) list, ok := doc.Types[componentID("T")].(*ir.List) require.True(t, ok, "%s: %#v", entries, doc.Types[componentID("T")]) - assert.Equal(t, tc.element, doc.Types[list.ElementType.Target].Kind(), entries) + assert.Equal(t, testCase.element, doc.Types[list.ElementType.Target].Kind(), entries) assert.NotEqual(t, ir.TypeID("type/primitive/any"), list.ElementType.Target, entries) assert.Empty(t, list.Unmodeled, entries) } @@ -1531,7 +1771,7 @@ func TestRefinement_NoConjunctNamingAKindLeavesTheTopType(t *testing.T) { func typeShapes(doc *ir.Document) string { model := doc.Types[componentID("Holder")].(*ir.Model) property := model.Properties[0] - td := doc.Types[property.Type.Target] + typeDef := doc.Types[property.Type.Target] rendered, err := json.Marshal(struct { Docs ir.Docs Constraints *ir.Constraints @@ -1539,11 +1779,11 @@ func typeShapes(doc *ir.Document) string { Visibility ir.Visibility Kept int Kind string - }{property.Docs, property.Constraints, property.Type.Nullable, property.Visibility, len(property.Unmodeled), fmt.Sprintf("%T", td)}) + }{property.Docs, property.Constraints, property.Type.Nullable, property.Visibility, len(property.Unmodeled), fmt.Sprintf("%T", typeDef)}) if err != nil { return err.Error() } - if _, ok := td.(*ir.Primitive); ok { + if _, ok := typeDef.(*ir.Primitive); ok { return string(rendered) + string(property.Type.Target) } return string(rendered) @@ -1579,20 +1819,20 @@ func TestRefinement_TwinsTheRefSpelling(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() const ref = "$ref: '#/components/schemas/Str'" - twin, twinDiags := parseFull(t, strings.Replace(positionsDoc(refinementTargets, "{"+ref+", "+keyword+"}"), + equivalent, equivalentDiags := parseFull(t, strings.Replace(positionsDoc(refinementTargets, "{"+ref+", "+keyword+"}"), "openapi: 3.0.3", "openapi: 3.1.0", 1)) for spelling, written := range map[string]string{ "beside": "{allOf: [{" + ref + "}], " + keyword + "}", "an entry": "{allOf: [{" + ref + "}, {" + keyword + "}]}", } { doc, diags := parseFull(t, positionsDoc(refinementTargets, written)) - if diff := cmp.Diff(twin.Types, doc.Types, options...); diff != "" { + if diff := cmp.Diff(equivalent.Types, doc.Types, options...); diff != "" { t.Errorf("%s: the types differ from the $ref's (-ref +allOf):\n%s", spelling, diff) } - if diff := cmp.Diff(twin.Services, doc.Services, options...); diff != "" { + if diff := cmp.Diff(equivalent.Services, doc.Services, options...); diff != "" { t.Errorf("%s: the services differ from the $ref's (-ref +allOf):\n%s", spelling, diff) } - assert.Len(t, withCode(diags, diag.DegradedConstruct), len(withCode(twinDiags, diag.DegradedConstruct)), spelling) + assert.Len(t, withCode(diags, diag.DegradedConstruct), len(withCode(equivalentDiags, diag.DegradedConstruct)), spelling) } }) } @@ -1620,9 +1860,9 @@ func TestRefinement_StructuralKeywordsBesideARefAreConsumedAsBesideTheAllOf(t *t } // TestRefinement_AnEntryHoldsWhatItsNodeDoes pins an inline principal: a value -// set's node stands at the position, holding what the entry writes as any -// conjunct's voice, a keyword nothing reads kept with the entry whole, and one -// that reduces to a shared primitive speaks at the position. +// set's node sits at the position, holding what the entry writes as any +// conjunct's flattened entry, a keyword nothing reads kept with the entry +// whole, and one that reduces to a shared primitive speaks at the position. func TestRefinement_AnEntryHoldsWhatItsNodeDoes(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Holder: @@ -1643,7 +1883,7 @@ func TestRefinement_AnEntryHoldsWhatItsNodeDoes(t *testing.T) { owned := propertyOf(t, doc, "Holder", "owned") assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/Holder/properties/owned"), owned.Type.Target, - "the node stands at the position, whichever conjunct decides it") + "the node sits at the position, whichever conjunct decides it") en, ok := doc.Types[owned.Type.Target].(*ir.Enum) require.True(t, ok) assert.Equal(t, "mine", en.Docs.Description) @@ -1751,16 +1991,17 @@ func TestRefinement_ANullOnlyEntryIsTheNull(t *testing.T) { } } -// TestRefinement_MissingItemsIsAskedOfTheEntryThatLowers pins -// docs/compilers/openapi.md#missing-array-items beside a refinement: the entry -// a list lowers from is held to the rule, and one that only restates a $ref's -// type lowers nothing. -func TestRefinement_MissingItemsIsAskedOfTheEntryThatLowers(t *testing.T) { +// TestRefinement_MissingItemsIsAskedOfTheConjunction pins +// docs/compilers/openapi.md#missing-array-items beside a refinement: the rule +// is asked of the conjunction, so an array no conjunct writes `items` for is +// reported once, at its position, and one whose $ref's target writes them is +// not. +func TestRefinement_MissingItemsIsAskedOfTheConjunction(t *testing.T) { t.Parallel() _, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", refinementTargets+` Lowers: {allOf: [{type: array}]} Restates: {allOf: [{$ref: '#/components/schemas/Names'}, {type: array}]} `)) - assert.Equal(t, []string{"/components/schemas/Lowers/allOf/0"}, pointerStrings(openapitest.PointersOf(diags, diag.MissingArrayItems))) + assert.Equal(t, []string{"/components/schemas/Lowers"}, pointerStrings(openapitest.PointersOf(diags, diag.MissingArrayItems))) } // pointerStrings renders pointers for a comparison with literals. @@ -1772,12 +2013,16 @@ func pointerStrings[P ~string](pointers []P) []string { return out } -// TestRefinement_PastItsBudgetStaysAComposition pins the bounds on the reading: a -// target it cannot finish reading leaves a position weighing two conjuncts as it -// was, and one read to the last step refines, while one $ref weighed alone -// refines alike on both sides of each bound -// (docs/compilers/openapi.md#allof-refinement). -func TestRefinement_PastItsBudgetStaysAComposition(t *testing.T) { +// TestRefinement_PastItsBudgetWhatIsLeftDecides pins the bounds on the reading: +// a target it cannot finish reading cuts the comparison of two conjuncts, and +// what the conjuncts say decides, never a Model for a string: beside a type +// saying nothing past its kind the $ref is the position. A format beside it +// reads alike on both sides of a bound: beside the enum the uuid, selecting a +// primitive, is kept on the use, and beside the chain it lowers as its flat +// twin. One read to the +// last step refines, and one $ref weighed alone refines alike on both sides of +// each bound (docs/compilers/openapi.md#allof-refinement). +func TestRefinement_PastItsBudgetWhatIsLeftDecides(t *testing.T) { t.Parallel() assert.Equal(t, 256, schema.MaxAdmissionReads, "docs/compilers/openapi.md#allof-refinement says so") assert.Equal(t, 4096, schema.MaxAdmissionMembers, "docs/compilers/openapi.md#allof-refinement says so") @@ -1790,41 +2035,58 @@ func TestRefinement_PastItsBudgetStaysAComposition(t *testing.T) { " One: {allOf: [{$ref: '#/components/schemas/" + target + "'}], maxLength: 3}\n" } enum := func(members int) string { - var b strings.Builder - b.WriteString(" Big:\n type: string\n enum:\n") + var builder strings.Builder + builder.WriteString(" Big:\n type: string\n enum:\n") for i := range members { - fmt.Fprintf(&b, " - m%d\n", i) + fmt.Fprintf(&builder, " - m%d\n", i) } - return b.String() + uses("Big") - } - // A link reads the $ref naming it and the schema it lands on. - chain := func(links int) string { - var b strings.Builder - b.WriteString(uses("C0")) - for i := range links - 1 { - fmt.Fprintf(&b, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}]}\n", i, i+1) + return builder.String() + uses("Big") + } + // A hop reads the $ref naming it and the schema it lands on. + chain := func(hops int) string { + var builder strings.Builder + builder.WriteString(uses("C0")) + for i := range hops - 1 { + fmt.Fprintf(&builder, " C%d: {allOf: [{$ref: '#/components/schemas/C%d'}]}\n", i, i+1) } - fmt.Fprintf(&b, " C%d: {type: string}\n", links-1) - return b.String() - } - for name, tc := range map[string]struct{ within, past string }{ - "enum members": {enum(schema.MaxAdmissionMembers), enum(schema.MaxAdmissionMembers + 1)}, - "schemas read": {chain(schema.MaxAdmissionReads / 2), chain(schema.MaxAdmissionReads/2 + 1)}, + fmt.Fprintf(&builder, " C%d: {type: string}\n FTwin: {type: string, format: uuid}\n", hops-1) + return builder.String() + } + keeps := func(t *testing.T, doc *ir.Document) { + t.Helper() + f, ok := typeByName(doc, "F").(*ir.Scalar) + require.True(t, ok, "F is a use of the reference: got %T", typeByName(doc, "F")) + require.NotNil(t, f.Base) + assert.Equal(t, componentID("Big"), f.Base.Target) + assert.Nil(t, f.Encoding, "no Encoding is named after a recognized format") + require.Contains(t, f.Unmodeled, "openapi:format") + assert.Equal(t, ir.ReasonDegradedLowering, f.Unmodeled["openapi:format"].Reason) + } + lowersAsItsTwin := func(t *testing.T, doc *ir.Document) { + t.Helper() + assertLowersAsItsEquivalent(t, doc, "F", "FTwin") + } + for name, testCase := range map[string]struct { + within, past, target string + format func(*testing.T, *ir.Document) + }{ + "enum members": {enum(schema.MaxAdmissionMembers), enum(schema.MaxAdmissionMembers + 1), "Big", keeps}, + "schemas read": {chain(schema.MaxAdmissionReads / 2), chain(schema.MaxAdmissionReads/2 + 1), "C0", lowersAsItsTwin}, } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", tc.within)) - for _, name := range []string{"S", "F"} { - _, ok := typeByName(doc, name).(*ir.Scalar) - assert.True(t, ok, "at the bound %s refines: got %T", name, typeByName(doc, name)) - } + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", testCase.within)) + _, ok := typeByName(doc, "S").(*ir.Scalar) + assert.True(t, ok, "at the bound S refines: got %T", typeByName(doc, "S")) + testCase.format(t, doc) within, ok := typeByName(doc, "One").(*ir.Scalar) require.True(t, ok, "at the bound one $ref refines: got %T", typeByName(doc, "One")) - doc, _ = parseFull(t, openapitest.ComponentSpecVer("3.1.0", tc.past)) - for _, name := range []string{"S", "F"} { - _, ok := typeByName(doc, name).(*ir.Model) - assert.True(t, ok, "past it, %s does not: got %T", name, typeByName(doc, name)) + doc, _ = parseFull(t, openapitest.ComponentSpecVer("3.1.0", testCase.past)) + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + if assert.True(t, ok, "past it, S is no Model: got %T", typeByName(doc, "S")) && assert.NotNil(t, scalar.Base) { + assert.Equal(t, componentID(testCase.target), scalar.Base.Target) } + testCase.format(t, doc) past, ok := typeByName(doc, "One").(*ir.Scalar) require.True(t, ok, "past it, one $ref still refines: got %T", typeByName(doc, "One")) assert.Equal(t, within.Base, past.Base) @@ -1833,9 +2095,25 @@ func TestRefinement_PastItsBudgetStaysAComposition(t *testing.T) { } } -// TestRefinement_PastItsConjunctBoundStaysAComposition pins the bound on the -// election, which compares every pair of conjuncts. -func TestRefinement_PastItsConjunctBoundStaysAComposition(t *testing.T) { +// assertLowersAsItsEquivalent holds the component name to the node its flat +// twin lowers to: a Scalar over what the twin's is over, keeping its format +// where the twin does. +func assertLowersAsItsEquivalent(t *testing.T, doc *ir.Document, name, equivalent string) { + t.Helper() + got, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s is a Scalar: got %T", name, typeByName(doc, name)) + want, ok := typeByName(doc, equivalent).(*ir.Scalar) + require.True(t, ok, "%s is a Scalar: got %T", equivalent, typeByName(doc, equivalent)) + assert.Equal(t, want.Base, got.Base, "%s is over what %s is", name, equivalent) + _, keeps := want.Unmodeled["openapi:format"] + _, kept := got.Unmodeled["openapi:format"] + assert.Equal(t, keeps, kept, "%s keeps its format where %s does", name, equivalent) +} + +// TestRefinement_PastItsConjunctBoundTheConjunctsDecide pins the bound on the +// choice, which compares every pair of conjuncts: past it, entries saying +// nothing past their kind leave the string they all name, not a Model. +func TestRefinement_PastItsConjunctBoundTheConjunctsDecide(t *testing.T) { t.Parallel() entries := func(n int) string { return "[" + strings.TrimSuffix(strings.Repeat("{type: string}, ", n), ", ") + "]" @@ -1844,13 +2122,16 @@ func TestRefinement_PastItsConjunctBoundStaysAComposition(t *testing.T) { _, ok := typeByName(doc, "S").(*ir.Scalar) assert.True(t, ok, "at the bound it refines: got %T", typeByName(doc, "S")) doc, _ = parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: "+entries(schema.MaxRefinedConjuncts+1)+"}\n")) - _, ok = typeByName(doc, "S").(*ir.Model) - assert.True(t, ok, "past it, it does not: got %T", typeByName(doc, "S")) + past, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "past it, it is no Model: got %T", typeByName(doc, "S")) + require.NotNil(t, past.Base) + assert.Equal(t, primitive(ir.PrimitiveString), past.Base.Target) } -// TestRefinement_ACappedEntryStaysAComposition pins a wrapper past the -// flattening depth, whose own allOf the reading does not reach. -func TestRefinement_ACappedEntryStaysAComposition(t *testing.T) { +// TestRefinement_ACappedEntryIsTheTopType pins a wrapper past the flattening +// depth, whose own allOf the reading does not reach: the position is the top +// type keeping its allOf whole, not a Model. +func TestRefinement_ACappedEntryIsTheTopType(t *testing.T) { t.Parallel() body := "{type: string}" for range statement.MaxFlattenDepth + 2 { @@ -1858,8 +2139,11 @@ func TestRefinement_ACappedEntryStaysAComposition(t *testing.T) { } doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+body+"\n")) openapitest.RequireNoErrorDiags(t, diags) - _, ok := typeByName(doc, "S").(*ir.Model) - assert.True(t, ok, "got %T", typeByName(doc, "S")) + top, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "S")) + require.NotNil(t, top.Base) + assert.Equal(t, primitive(ir.PrimitiveAny), top.Base.Target) + assert.Contains(t, top.Unmodeled, "openapi:allOf") } // TestRefinement_AKeptEntryTheIRCannotHoldIsNotAnnounced pins the report to what @@ -1874,7 +2158,7 @@ func TestRefinement_AKeptEntryTheIRCannotHoldIsNotAnnounced(t *testing.T) { `)) assert.NotContains(t, propertyOf(t, doc, "Holder", "f").Unmodeled, "openapi:allOf/1") assert.True(t, openapitest.HasDiag(diags, diag.UnpreservableConstruct)) - assert.Empty(t, openapitest.PreservationClaims(diags)) + assert.Empty(t, openapitest.MessagesSayingKept(diags)) } // TestRefinement_RawTextIsComparedWithinADocument pins restated items: a $ref in @@ -1985,7 +2269,7 @@ func TestRefinement_AUnionTargetIsReadByItsBranches(t *testing.T) { // type beside it. func TestRefinement_ValuesCompareAsJSON(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string model bool }{ @@ -2002,24 +2286,27 @@ func TestRefinement_ValuesCompareAsJSON(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+testCase.schema+"\n")) _, isModel := typeByName(doc, "S").(*ir.Model) - assert.False(t, isModel, "a value set is elected before a composition: got %T", typeByName(doc, "S")) - disjoint := openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/S") && - openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning) == 1 - assert.Equal(t, tc.model, disjoint, "the conjuncts share no value exactly where reported: %+v", diags) + assert.False(t, isModel, "a value set is chosen before a composition: got %T", typeByName(doc, "S")) + disjoint := openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/S") && + openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning) == 1 + assert.Equal(t, testCase.model, disjoint, "the conjuncts share no value exactly where reported: %+v", diags) }) } } -// TestRefinement_AConstUnreadableStaysAComposition pins a value set no reading can -// convert: an instance it cannot compare is one it cannot answer for. -func TestRefinement_AConstUnreadableStaysAComposition(t *testing.T) { +// TestRefinement_AConstUnreadableIsNoConjunct pins a value set no reading can +// convert: kept and reported as it is, it is no conjunct of the reading, so an +// allOf of it alone is the top type, not a Model. +func TestRefinement_AConstUnreadableIsNoConjunct(t *testing.T) { t.Parallel() doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: [{const: "+unpreservableValue+"}]}\n")) - _, ok := typeByName(doc, "S").(*ir.Model) - assert.True(t, ok, "got %T", typeByName(doc, "S")) + top, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "S")) + require.NotNil(t, top.Base) + assert.Equal(t, primitive(ir.PrimitiveAny), top.Base.Target) } // TestRefinement_DecidingSchemaIsAskedOfAWholeChain pins the reader of a body's @@ -2036,25 +2323,29 @@ func TestRefinement_DecidingSchemaIsAskedOfAWholeChain(t *testing.T) { `)) schemas := lowerer.Doc.Components.GetSchemas() for name, format := range map[string]string{"Outer": "binary", "Inline": "binary", "Narrowed": "binary", "Bare": ""} { - js, ok := schemas.Get(name) + jsonSchema, ok := schemas.Get(name) require.True(t, ok, name) - assert.Equal(t, format, statement.Parsed(schema.DecidingSchema(lowerer.Ctx, lowerer.Ctx.Statements().Of(js).Schema)).GetFormat(), name) + assert.Equal(t, format, statement.Parsed(schema.DecidingSchema(lowerer.Ctx, lowerer.Ctx.Statements().Of(jsonSchema).Schema)).GetFormat(), name) } } // TestRefinement_ItemsItCannotRenderRestateNothing pins the comparison of two -// `items`, one of which holds what no JSON renders: neither restates the other, -// in either order, and the one elected is the list at the position, its element -// the one written beside what no JSON renders. +// `items`, one of which holds an extension no JSON renders: in either order the +// list at the position takes the string the two write, no alias taking the +// place of what is kept nowhere, and the extension's finding is drawn once, at +// the items writing it. func TestRefinement_ItemsItCannotRenderRestateNothing(t *testing.T) { t.Parallel() bad := "{type: array, items: {type: string, x-t: " + unpreservableValue + "}}" good := "{type: array, items: {type: string}}" for i, entries := range []string{bad + ", " + good, good + ", " + bad} { - doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+entries+"]}\n")) + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: ["+entries+"]}\n")) list, ok := typeByName(doc, "S").(*ir.List) require.True(t, ok, "got %T", typeByName(doc, "S")) - assert.Equal(t, ir.TypeID(fmt.Sprintf("type/anonymous/components/schemas/S/allOf/%d/items", i)), list.ElementType.Target, entries) + assert.Equal(t, ir.TypeID("type/primitive/string"), list.ElementType.Target, entries) + badItems := jsontext.Pointer(fmt.Sprintf("/components/schemas/S/allOf/%d/items", i)) + assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous"+badItems), entries) + assert.Equal(t, []jsontext.Pointer{badItems}, openapitest.PointersOf(diags, diag.DegradedConstruct), entries) } } @@ -2065,14 +2356,14 @@ func TestRefinement_ANullKeywordRestatesNothingMore(t *testing.T) { t.Parallel() doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.0.3", " Arr: {type: array, items: {type: string}}\n"+ " S: {allOf: [{$ref: '#/components/schemas/Arr'}, {items: {type: string, description: null}}]}\n")) - td := typeByName(doc, "S") - require.NotNil(t, td) - assert.Empty(t, td.Common().Unmodeled) + typeDef := typeByName(doc, "S") + require.NotNil(t, typeDef) + assert.Empty(t, typeDef.Common().Unmodeled) } // TestRefinement_ATypeArrayPrincipalKeepsWhatNoVariantHolds pins an inline // principal that lowers as a type array: what none of its variants holds, a -// bound no listed type takes, is kept on the union it lowers to, standing at the +// bound no listed type takes, is kept on the union it lowers to, at the // position, as a type array written alone keeps it, whether the keyword sits on // the entry or beside the allOf, and a bound one takes lands on that variant. func TestRefinement_ATypeArrayPrincipalKeepsWhatNoVariantHolds(t *testing.T) { @@ -2107,7 +2398,7 @@ func TestRefinement_AValueBoundOnAnEntryBesideATypeListLandsOnItsVariant(t *test t.Parallel() stringConstraints := &ir.Constraints{MaxLength: new(int64(2))} number := &ir.Constraints{Min: new(ir.BigVal("1"))} - for _, tc := range []struct { + for _, testCase := range []struct { name, allOf string held [2]*ir.Constraints kept []string @@ -2119,20 +2410,20 @@ func TestRefinement_AValueBoundOnAnEntryBesideATypeListLandsOnItsVariant(t *test {"no listed type takes it", "[{maxLength: 2}, {minProperties: 1}]", [2]*ir.Constraints{stringConstraints, nil}, []string{"openapi:minProperties"}}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", - " OnBranch: {type: [string, integer], format: x-mine, allOf: "+tc.allOf+"}\n")) + " OnBranch: {type: [string, integer], format: x-mine, allOf: "+testCase.allOf+"}\n")) openapitest.RequireNoErrorDiags(t, diags) union, ok := typeByName(doc, "OnBranch").(*ir.Union) require.True(t, ok, "got %T", typeByName(doc, "OnBranch")) - assert.Equal(t, tc.kept, unmodeledKeys(union.Unmodeled)) - for i, want := range tc.held { + assert.Equal(t, testCase.kept, unmodeledKeys(union.Unmodeled)) + for i, want := range testCase.held { scalar, isScalar := doc.Types[union.Variants[i].Type.Target].(*ir.Scalar) require.True(t, isScalar, "got %T", doc.Types[union.Variants[i].Type.Target]) assert.Equal(t, want, scalar.Constraints, "variant %d", i) } - if tc.kept != nil { + if testCase.kept != nil { assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/OnBranch/allOf/1"), "no home for minProperties written on this inline entry") return @@ -2178,12 +2469,12 @@ func TestRefinement_AnEmptyAllOfOnAnEntryIsKept(t *testing.T) { // TestRefinement_KeywordsBesideARefAreNotConjuncts pins where a refinement stops: // an allOf beside a $ref, or beside a $dynamicRef, is no refinement, and an entry -// TestRefinement_AnAllOfBesideARefJoinsItsConjunction pins that an allOf +// TestRefinement_AnAllOfBesideARefCombinesItsConjunction pins that an allOf // beside a $ref adds its entries to the conjunction the $ref is one conjunct // of, so an entry speaks for the position as it would beside no $ref, and that // a $dynamicRef the position does not expand, kept on its carrier, masks no // kind: the conjuncts beside it decide, and nothing makes a model of a string. -func TestRefinement_AnAllOfBesideARefJoinsItsConjunction(t *testing.T) { +func TestRefinement_AnAllOfBesideARefCombinesItsConjunction(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", refinementTargets+` Node: {$dynamicAnchor: node, type: string} Holder: @@ -2216,7 +2507,7 @@ func TestRefinement_AnAllOfBesideARefJoinsItsConjunction(t *testing.T) { } // TestRefinement_DeclaredBeforeItsTarget pins a use lowered before what it names: -// the reference needs no node to stand yet, which it would to hold anything. +// the reference needs no node to sit yet, which it would to hold anything. func TestRefinement_DeclaredBeforeItsTarget(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", ` Items: @@ -2230,14 +2521,15 @@ func TestRefinement_DeclaredBeforeItsTarget(t *testing.T) { assert.Equal(t, componentID("Late"), items.ElementType.Target) } -// TestRefinement_TheValueSetWithinMostOthersWins pins the election past a value set -// within every other: none is here, and the one within the most others wins, in -// either order, what holds it consumed and the one overlapping it kept. -func TestRefinement_TheValueSetWithinMostOthersWins(t *testing.T) { +// TestRefinement_ValueSetsNoneWithinEveryOtherIntersection pins the choice past +// a value set within every other: none is here, so, in either order, the +// position is the Enum of the members every set holds, each set kept, though +// one lies within more of the others than another does. +func TestRefinement_ValueSetsNoneWithinEveryOtherIntersection(t *testing.T) { t.Parallel() - for entries, overlapping := range map[string]string{ - "{enum: [a, b, c]}, {enum: [a, b]}, {enum: [b, c, d]}": "openapi:allOf/2", - "{enum: [b, c, d]}, {enum: [a, b]}, {enum: [a, b, c]}": "openapi:allOf/0", + for _, entries := range []string{ + "{enum: [a, b, c]}, {enum: [a, b]}, {enum: [b, c, d]}", + "{enum: [b, c, d]}, {enum: [a, b]}, {enum: [a, b, c]}", } { doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Holder:\n type: object\n"+ " properties:\n f: {allOf: ["+entries+"]}\n")) @@ -2245,17 +2537,18 @@ func TestRefinement_TheValueSetWithinMostOthersWins(t *testing.T) { property := propertyOf(t, doc, "Holder", "f") en, ok := doc.Types[property.Type.Target].(*ir.Enum) require.True(t, ok, "%s: got %T", entries, doc.Types[property.Type.Target]) - assert.Len(t, en.Members, 2, entries) + require.Len(t, en.Members, 1, entries) + assert.Equal(t, "b", en.Members[0].Value.String, entries) assert.Empty(t, property.Unmodeled, "%s: the node the position owns keeps what it keeps", entries) - assert.Equal(t, []string{overlapping}, slices.Sorted(maps.Keys(en.Unmodeled)), - "%s: it holds the narrower set, and keeps the one overlapping it", entries) + assert.Equal(t, []string{"openapi:allOf/0", "openapi:allOf/1", "openapi:allOf/2"}, slices.Sorted(maps.Keys(en.Unmodeled)), + "%s: it keeps every set", entries) } } // TestRefinement_ANullBothConjunctsAdmitIsAValue pins the reading of OpenAPI 3.0's // nullable: it adds null to a type, so a value set of null alone shares a value // with one, where in 3.1 the keyword reads as nothing and no value is shared. A -// value set is elected before the composition either way, so both lower to it. +// value set is chosen before the composition either way, so both lower to it. func TestRefinement_ANullBothConjunctsAdmitIsAValue(t *testing.T) { t.Parallel() const s = " S: {allOf: [{type: string, nullable: true}, {enum: [null]}]}\n" @@ -2297,7 +2590,7 @@ func TestRefinement_AnEntryDisagreeingStaysWhole(t *testing.T) { items, ok := typeByName(doc, "Items").(*ir.List) require.True(t, ok) alias := aliasAt(t, doc, items.ElementType) - assert.Nil(t, alias.Constraints, "no pattern stands for the two") + assert.Nil(t, alias.Constraints, "no pattern takes the place of the two") assert.Contains(t, alias.Unmodeled, "openapi:allOf/1") assert.Contains(t, alias.Unmodeled, "openapi:allOf/2") } @@ -2322,3 +2615,134 @@ func TestRefinement_AnEntryReadAgainstAnotherBaseFoldsNothing(t *testing.T) { openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Holder/properties/f/allOf/1"), "reads its $refs against another base") } + +// TestRefinement_ALoopBesideAnEntrySayingNothingIsAReferenceLoop pins a +// self-reference beside an inline entry writing only a comment: the entry is +// says nothing, so the allOf is a hop of a reference chain closing on itself, +// the loop its bare twin `{$ref: CY, $comment: c}` is, one openapi/cyclic-ref +// error and the top type keeping nothing, with no report of its own +// (docs/compilers/openapi.md#reference-cycles). +func TestRefinement_ALoopBesideAnEntrySayingNothingIsAReferenceLoop(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " CX: {allOf: [{$ref: '#/components/schemas/CX'}, {$comment: c}]}\n"+ + " CY: {$ref: '#/components/schemas/CY', $comment: c}\n")) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/CX", "/components/schemas/CY"}, openapitest.PointersOf(diags, diag.CyclicRef)) + assert.Empty(t, openapitest.PointersOf(diags, diag.DegradedConstruct), "a loop's member draws no report of its own") + for _, name := range []string{"CX", "CY"} { + scalar, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s: %T", name, typeByName(doc, name)) + require.NotNil(t, scalar.Base) + assert.Equal(t, primitive(ir.PrimitiveAny), scalar.Base.Target, name) + assert.Empty(t, scalar.Unmodeled, name) + } +} + +// TestRefinement_ALoopThroughAHopIsReadByKind pins a loop closing through a hop +// beside an entry saying nothing, no pure hop loop while the other member +// writes a kind: read to its greatest fixpoint by kind, the member writing the +// kind is it, keeping its $ref with the info that the loop admits every kind +// there, and the hop sits over it, so no kind is lost and no loop is reported +// (docs/compilers/openapi.md#reference-cycles). +func TestRefinement_ALoopThroughAHopIsReadByKind(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " NA: {allOf: [{$ref: '#/components/schemas/NB'}, {type: string}]}\n"+ + " NB: {allOf: [{$ref: '#/components/schemas/NA'}, true]}\n")) + assert.Empty(t, openapitest.PointersOf(diags, diag.CyclicRef), "no reference loop") + assert.Equal(t, []jsontext.Pointer{"/components/schemas/NA/allOf/0"}, openapitest.PointersOf(diags, diag.DegradedConstruct)) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/NA/allOf/0"), + "which admits every kind there, so what its other conjuncts say decides") + na, ok := typeByName(doc, "NA").(*ir.Scalar) + require.True(t, ok, "%T", typeByName(doc, "NA")) + assert.Equal(t, primitive(ir.PrimitiveString), na.Base.Target) + assert.Contains(t, na.Unmodeled, "openapi:$ref") + nb, ok := typeByName(doc, "NB").(*ir.Scalar) + require.True(t, ok, "%T", typeByName(doc, "NB")) + assert.Equal(t, componentID("NA"), nb.Base.Target, "the hop sits over NA") +} + +// TestRefinement_AnEntryDisagreeingOnADefaultKeepsItsOwn pins an inline entry +// writing a default otherwise than the keywords beside the allOf, beside a +// primitive principal: the position's default is taken, what the entry writes +// alike folds, its bound reaching the node, and its default is kept on the +// node under its entry's key, with one report naming it +// (docs/compilers/openapi.md#allof-inline-residue). +func TestRefinement_AnEntryDisagreeingOnADefaultKeepsItsOwn(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " D: {default: a, allOf: [{type: string}, {default: b, maxLength: 3}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + scalar, ok := typeByName(doc, "D").(*ir.Scalar) + require.True(t, ok, "%T", typeByName(doc, "D")) + require.NotNil(t, scalar.Constraints) + require.NotNil(t, scalar.Constraints.MaxLength) + assert.EqualValues(t, 3, *scalar.Constraints.MaxLength, "what the entry writes alike folds") + assert.Contains(t, unmodeledKeys(scalar.Unmodeled), "openapi:allOf/1", "the entry's default is kept under its key") + assert.NotEmpty(t, openapitest.PointersOf(diags, diag.DegradedConstruct)) +} + +// TestRefinement_ALoopBesideAnIdentifierIsAReferenceLoop pins a self-reference +// writing an identifier beside its allOf. An identifier says nothing of the +// instance, so the hop is one of a reference chain, as one writing notes is, +// and closes the loop a bare $ref beside the same identifier closes: one +// openapi/cyclic-ref at it, the top type, and nothing it keeps of its own +// (docs/compilers/openapi.md#reference-cycles). It overturns the base's +// reading, where the identifier made the hop a refinement keeping its $ref. +func TestRefinement_ALoopBesideAnIdentifierIsAReferenceLoop(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " CX: {allOf: [{$ref: '#/components/schemas/CX'}], $anchor: cx}\n BX: {$ref: '#/components/schemas/BX', $anchor: bx}\n")) + assert.Equal(t, []jsontext.Pointer{"/components/schemas/BX", "/components/schemas/CX"}, openapitest.PointersOf(diags, diag.CyclicRef)) + for _, name := range []string{"CX", "BX"} { + scalar, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s: %T", name, typeByName(doc, name)) + require.NotNil(t, scalar.Base) + assert.Equal(t, primitive(ir.PrimitiveAny), scalar.Base.Target, name) + assert.Empty(t, scalar.Unmodeled, name) + } + assert.Empty(t, openapitest.PointersOf(diags, diag.DegradedConstruct), "the loop's members report nothing of their own") +} + +// TestRefinement_AnIfBranchNarrowingWithinAKindRemovesNone holds an `if` +// whose `then` writes a keyword narrowing within a kind, a maxLength or a +// required, to the kinds its keywords admit, in every spelling and in either +// order: no kind it admits is read as refused, so a union branch writing it +// beside a string, or beside an enum of strings, is no branch sharing no value +// with the rest, and an allOf entry writing it beside a Model's entry leaves +// the position the Model its flat twin is. +func TestRefinement_AnIfBranchNarrowingWithinAKindRemovesNone(t *testing.T) { + t.Parallel() + const anyOf = "anyOf: [{if: {type: string}, then: {maxLength: 2}}, {type: integer}]" + rows := map[string]struct { + rest, part string + model bool + }{ + "Typed": {rest: "type: string", part: anyOf}, + "Enum": {rest: "enum: [abc, x]", part: anyOf}, + "Object": {rest: "type: object, properties: {a: {type: string}}", part: "if: {type: object}, then: {required: [a]}", model: true}, + } + for name, row := range rows { + t.Run(name, func(t *testing.T) { + t.Parallel() + spellings := openapitest.Spellings(row.rest, row.part) + for spelling, schema := range openapitest.Reversed(row.rest, row.part) { + spellings[spelling+"Reversed"] = schema + } + var written strings.Builder + for spelling, schema := range spellings { + written.WriteString(" " + spelling + ": " + schema + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for spelling := range spellings { + if row.model { + assert.IsType(t, &ir.Model{}, typeByName(doc, spelling), spelling) + assert.Empty(t, warningsUnder(diags, spelling), spelling) + continue + } + warned := warningsUnder(diags, spelling) + require.Len(t, warned, 1, spelling) + assert.Contains(t, warned[0].Message, "(anyOf/1: integer)", "%s: the integer branch alone is dead", spelling) + } + }) + } +} diff --git a/compilers/openapi/internal/schema/refinement_undecided_test.go b/compilers/openapi/internal/schema/refinement_undecided_test.go index 449bea2ca..979dcb88c 100644 --- a/compilers/openapi/internal/schema/refinement_undecided_test.go +++ b/compilers/openapi/internal/schema/refinement_undecided_test.go @@ -49,33 +49,31 @@ func undecidedTargets(t *testing.T, doc *ir.Document) []ir.TypeRef { } // TestRefinementUndecided_ThePositionIsTheKindsItsEntriesAdmit pins an allOf -// electing no entry, with no keyword beside it naming a kind: in either order +// choosing no entry, with no keyword beside it naming a kind: in either order // of its entries, at a component, a property and a parameter, it is the // primitive its entries admit together, where it was the top type, each entry // kept with one report at it, as before. func TestRefinementUndecided_ThePositionIsTheKindsItsEntriesAdmit(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { a, b string primitive ir.PrimitiveKind }{ "two formats": {"{type: string, format: email}", "{type: string, format: uuid}", ir.PrimitiveString}, - "two overlapping enums": {"{enum: [a, b]}", "{enum: [b, c]}", ir.PrimitiveString}, "two type lists sharing a kind": {"{type: [string, integer]}", "{type: [string, boolean]}", ir.PrimitiveString}, "two integer formats": {"{type: integer, format: int32}", "{type: integer, format: uint32}", ir.PrimitiveInteger}, - "two sets of fractions": {"{enum: [1.5, 2.5]}", "{enum: [2.5, 3.5]}", ir.PrimitiveNumber}, + "two type lists sharing a number": {"{type: [number, string], format: a}", "{type: [number, boolean], format: b}", + ir.PrimitiveNumber}, "two type lists sharing a flag": {"{type: [boolean, string], format: a}", "{type: [boolean, integer], format: b}", ir.PrimitiveBool}, - "two enums sharing a flag alone": {"{enum: [true, a]}", "{enum: [true, b]}", ir.PrimitiveBool}, - "two enums sharing an integer": {"{enum: [1, true, x]}", "{enum: [1, false, y]}", ir.PrimitiveInteger}, } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, order := range [][2]string{{tc.a, tc.b}, {tc.b, tc.a}} { + for _, order := range [][2]string{{testCase.a, testCase.b}, {testCase.b, testCase.a}} { doc, diags := parseFull(t, undecidedSpec(order[0], order[1])) openapitest.RequireNoErrorDiags(t, diags) for _, ref := range undecidedTargets(t, doc) { - assert.Equal(t, ir.PrimitiveTypeID(tc.primitive), ref.Target, "%v", order) + assert.Equal(t, ir.PrimitiveTypeID(testCase.primitive), ref.Target, "%v", order) } kept := typeByName(doc, "C").Common().Unmodeled assert.Equal(t, []string{"openapi:allOf/0", "openapi:allOf/1"}, unmodeledKeys(kept), "%v", order) @@ -88,18 +86,16 @@ func TestRefinementUndecided_ThePositionIsTheKindsItsEntriesAdmit(t *testing.T) } // TestRefinementUndecided_SeveralSharedKindsAreTheirUnion pins two type lists -// sharing two kinds, and two value sets holding members of two: the position -// is the Union of those primitives, in one order whichever order the entries -// are written in, holding both entries. +// sharing two kinds: the position is the Union of those primitives, in one +// order whichever order the entries are written in, holding both entries. func TestRefinementUndecided_SeveralSharedKindsAreTheirUnion(t *testing.T) { t.Parallel() - for name, tc := range map[string][2]string{ + for name, testCase := range map[string][2]string{ "type lists": {"{type: [string, integer, boolean], format: a}", "{type: [string, integer, 'null'], format: b}"}, - "value sets": {"{enum: [a, 1, x]}", "{enum: [a, 1, y]}"}, } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, order := range [][2]string{tc, {tc[1], tc[0]}} { + for _, order := range [][2]string{testCase, {testCase[1], testCase[0]}} { doc, diags := parseFull(t, undecidedSpec(order[0], order[1])) openapitest.RequireNoErrorDiags(t, diags) union, ok := typeByName(doc, "C").(*ir.Union) @@ -116,7 +112,7 @@ func TestRefinementUndecided_SeveralSharedKindsAreTheirUnion(t *testing.T) { } // TestRefinementUndecided_ANullTheEntriesAllAdmitStays pins that the kinds a -// position electing no entry is typed by leave null aside: one every entry +// position choosing no entry is typed by leave null aside: one every entry // admits makes its use nullable, and one only an entry admits does not. func TestRefinementUndecided_ANullTheEntriesAllAdmitStays(t *testing.T) { t.Parallel() @@ -128,10 +124,10 @@ func TestRefinementUndecided_ANullTheEntriesAllAdmitStays(t *testing.T) { assert.Equal(t, ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveString)}, propertyOf(t, doc, "Holder", "one").Type) } -// TestRefinementUndecided_AnElectionOrNoSharedValueIsUnchanged pins what is no -// election of none: an integer and a number elect the integer, and two kinds +// TestRefinementUndecided_AChoiceOrNoSharedValueIsUnchanged pins what is no +// choice of none: an integer and a number choose the integer, and two kinds // sharing no value compose with the warning saying so, in either order. -func TestRefinementUndecided_AnElectionOrNoSharedValueIsUnchanged(t *testing.T) { +func TestRefinementUndecided_AChoiceOrNoSharedValueIsUnchanged(t *testing.T) { t.Parallel() for _, order := range [][2]string{{"{type: integer}", "{type: number}"}, {"{type: number}", "{type: integer}"}} { doc, diags := parseFull(t, undecidedSpec(order[0], order[1])) @@ -145,7 +141,7 @@ func TestRefinementUndecided_AnElectionOrNoSharedValueIsUnchanged(t *testing.T) openapitest.RequireNoErrorDiags(t, diags) _, model := typeByName(doc, "C").(*ir.Model) assert.True(t, model, "%v", order) - warned := slices.ContainsFunc(diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/C"), + warned := slices.ContainsFunc(diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/C"), func(diagnostic ir.Diagnostic) bool { return diagnostic.Severity == ir.SeverityWarning }) assert.True(t, warned, "%v", order) } diff --git a/compilers/openapi/internal/schema/refinementdecision.go b/compilers/openapi/internal/schema/refinementdecision.go new file mode 100644 index 000000000..83b346f88 --- /dev/null +++ b/compilers/openapi/internal/schema/refinementdecision.go @@ -0,0 +1,1366 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// maxRefinedConjuncts bounds the conjuncts one choice compares, every pair of +// them: an allOf past it stays a composition, which loses nothing. +const maxRefinedConjuncts = 64 + +// refinement is an allOf whose kinds are not an object alone: one use of the +// conjunct that decides it, its principal, rather than a composition +// (docs/compilers/openapi.md#allof-refinement). +type refinement struct { + comp allOfComposition + // principal is the entry the position is a use of, nil where the keywords + // written beside the allOf decide it or nothing does. + principal *allOfEntry + // ref is the $ref entry a use reads on through: the principal where it is + // one, else the one $ref written, nil where none or several are. + ref *allOfEntry + // refChoiceReasons is how each entry of comp fared in the choice, by index: a + // $ref the position's kinds outvoted, or one another conjunct was chosen over. + refChoiceReasons []refChoiceReason + // admittedTogether is what the conjuncts admit together. + admittedTogether admitted + // loweredAdmits is what the position lowers to admits, which decides what a + // keyword left unread loses. + loweredAdmits admitted + // contradicts marks conjuncts sharing no value: a value set was chosen + // before the composition they would otherwise lower to, or, for value sets + // sharing no member, no conjunct was (decideRefinement). + contradicts bool + // cutBy names the bound that cut the read of a refinement choosing no + // entry, and kindsNamed marks such a refinement, whose position is what + // its kinds name, objects and arrays among them. + cutBy string + kindsNamed bool + // sharesNoMember marks value sets the read shows share no member, of one + // value type: the node is the closed empty Enum of that type (lowerEnum). + sharesNoMember bool + // besideRef is how a format or content keyword written beside the one + // $ref to a scalar reads (besideRefOf), the zero reading for none. + besideRef keywordBesideRef + // emptyEnumType types the `enum: []` chosen beside consts sharing a + // value, by what they share (emptyEnumBeside), "" for no such choice. + emptyEnumType ir.PrimitiveKind + // setsIntersect marks value sets that share members, none lying within every + // other: the node is the Enum of what they share, as a flat enum of + // those members lowers, every set kept (valueSetsIntersect). + setsIntersect bool + // unionPrincipal marks a principal writing the union the position is + // (unionPrincipal), which no value set it writes beside it decides. + unionPrincipal bool +} + +// principalIs reports whether allOfEntryValue is the entry the position lowers +// from: its schema at its pointer, as an entry writing a $ref beside other +// keys is two entries at one pointer. +func (r refinement) principalIs(allOfEntryValue allOfEntry) bool { + return r.principal != nil && r.principal.pointer == allOfEntryValue.pointer && r.principal.schema == allOfEntryValue.schema +} + +// refChoiceReason is how a $ref conjunct fared in the choice of a principal. +type refChoiceReason uint8 + +const ( + // refMayBePrincipal marks a $ref that could be the principal, + // and is, or lost to a value set. + refMayBePrincipal refChoiceReason = iota + // refNarrowed marks one another $ref was chosen over, lying within more + // conjuncts. + refNarrowed + // refInferredApart marks one whose target the kind-inference policy reads + // as a kind the position's declarations exclude. + refInferredApart + // refAdmitsEvery marks one whose target admits every kind beside a + // position declaring its kinds. + refAdmitsEvery + // refOutsideSet marks one whose target admits none of the value set + // chosen before the composition the conjuncts would lower to. + refOutsideSet + // refApart marks one of conjuncts whose value sets share no member, of + // which none is the principal (decideRefinement). + refApart + // refNamesNothing marks one landing on no schema, which admits every kind + // and cuts nothing beside it (refConjunct). + refNamesNothing + // refAround marks one leading round a loop of references back to the + // position: it admits every kind there, so the other conjuncts decide + // (refConjunct). + refAround + // refCut marks one kept by a read a bound cut short, which chose no + // entry (cutRead). + refCut + // refFormatNarrows marks one beside a format that, read over its target's + // type, selects a primitive narrower than the target's + // (besideRefConjunctIsPrincipal). + refFormatNarrows + // refContentEncodesText marks one beside a contentEncoding that makes + // the string its target's root is read from that encoding's text + // (besideRefConjunctIsPrincipal). + refContentEncodesText + // refNullIntersection marks one of conjuncts admitting null alone together: the + // position is the null type, a use of no target (nullIntersectionDecision). + refNullIntersection +) + +// conjunct is one conjunct's reading, for the choice. +type conjunct struct { + // entry is nil for the keywords written beside the allOf, and entryIndex is + // where the conjunct is among the conjuncts: annotation.BesideAllOf for + // those keywords, else its entry's index among the composition's entries. + entry *allOfEntry + entryIndex annotation.ConjunctIndex + read admitted + // schema writes the conjunct's keywords: the entry's, or the position's + // for the keywords beside the allOf. + schema *statement.Schema + // declaresKind marks an inline conjunct writing what kind of value this is. + declaresKind bool + // everyKindReason is how a $ref conjunct admitting every kind fares, a $ref + // naming nothing or leading round a loop of references, and zero for any + // other conjunct (refConjunct). + everyKindReason refChoiceReason +} + +// writesRef reports whether cj is a $ref entry of the allOf. +func (cj conjunct) writesRef() bool { return cj.entry != nil && cj.entry.schema.Ref != nil } + +// refinementDecisionKey keys a schema's decision: nothing decideRefinement +// reads turns on where the schema is written, which only prefixes its entries' +// pointers. +type refinementDecisionKey struct { + schema *statement.Schema +} + +// refinementDecision is what a position's readers share wherever it is +// written: refinementOf fills in the composition, principal and ref at the +// pointer asked. apart holds what each conjunct states where the choice found +// they share no value. +type refinementDecision struct { + refinement refinement + apart []string + principalAt annotation.ConjunctIndex + refAt annotation.ConjunctIndex + outcome decisionOutcome + // hasPrincipal marks a decision choosing a principal, at principalAt, and + // readsThrough one naming the $ref entry a use reads on through, at refAt. + hasPrincipal, readsThrough bool + // inferred marks a composition whose kinds the kind-inference policy read + // off its conjuncts (conjunctionKinds), as the Model they compose names. + inferred bool +} + +// decisionOutcome is what a decision makes of a position's allOf. +type decisionOutcome uint8 + +const ( + // decisionComposes composes the conjuncts. + decisionComposes decisionOutcome = iota + // decisionComposesBottom composes conjuncts whose kinds share none as the + // choice reads them, which bottomAt reads with the null the policy + // adds: the closed Model with no member keeping each (composeBottom). + decisionComposesBottom + // decisionRefines refines: the position is a use of one conjunct, or of + // what the keywords beside the allOf say. + decisionRefines + // decisionRefinesKeepingAllOfWhole refines an allOf nesting past the + // flattening depth: the position is the top type keeping the allOf whole + // (entriesCut). + decisionRefinesKeepingAllOfWhole + // decisionRefinesNullIntersection refines conjuncts admitting null alone + // together: the position is the node `{type: 'null'}` lowers to + // (nullIntersectionDecision). + decisionRefinesNullIntersection +) + +// refines reports whether d refines rather than composes. +func (d refinementDecision) refines() bool { + switch d.outcome { + case decisionRefines, decisionRefinesKeepingAllOfWhole, decisionRefinesNullIntersection: + return true + default: + return false + } +} + +// principal returns where the principal is among the conjuncts, and false +// where the decision chooses none. +func (d refinementDecision) principal() (annotation.ConjunctIndex, bool) { + return d.principalAt, d.hasPrincipal +} + +// ref returns where the $ref entry a use of the position reads on through is +// among the conjuncts, and false where none is (readThrough). +func (d refinementDecision) ref() (annotation.ConjunctIndex, bool) { + return d.refAt, d.readsThrough +} + +// namedEntry returns the flattened entry index of the conjunct at, false where +// named is false or at is annotation.BesideAllOf: a principal the keywords +// beside the allOf are reads as choosing no entry. +func namedEntry(at annotation.ConjunctIndex, named bool) (int, bool) { + if !named { + return 0, false + } + return at.Entry() +} + +// refinementOf decides whether schema, written at pointer, refines rather than +// composes (docs/compilers/openapi.md#allof-refinement). It reads the source and +// the bindings, never the registry, so a decision turns on no lowering order, and +// the many readers of a schema share one reading wherever it is written. +func refinementOf(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (refinement, bool) { + decision := decisionOf(loweringContext, schema) + if !decision.refines() { + return refinement{}, false + } + refinementValue := decision.refinement + refinementValue.comp = allOfEntries(loweringContext, schema, pointer) + if i, isEntry := namedEntry(decision.principal()); isEntry { + refinementValue.principal = &refinementValue.comp.entries[i] + } + if i, isEntry := namedEntry(decision.ref()); isEntry { + refinementValue.ref = &refinementValue.comp.entries[i] + } + refinementValue.unionPrincipal = refinementValue.principal != nil && refinementValue.principal.schema.Schema == unionPrincipal(loweringContext, schema) + return refinementValue, true +} + +// decisionOf returns the decision on schema, read once a run, and none where +// its allOf may not refine. +func decisionOf(loweringContext lowering.Ctx, schema *statement.Schema) refinementDecision { + if !writesConjuncts(schema) || expandsInPlace(loweringContext, schema) { + return refinementDecision{} + } + return lowering.ReadOncePerRun(loweringContext, refinementDecisionKey{schema}, func() refinementDecision { return decideRefinement(loweringContext, schema) }) +} + +// usesOneRef reports whether schema, whose flattened conjuncts are comp, is a +// use of one $ref saying nothing of its target, so it is the reference, as the +// $ref alone is (docs/compilers/openapi.md#allof-classification). Where a +// carrier holds the position, what binds the use says nothing of the target. +func usesOneRef(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) bool { + ref := oneQuietRef(comp) + if ref == nil { + return false + } + // A $ref whose loop leads back to schema, or lies on a loop of $refs, + // admits every kind there, so nothing written beside it restates its + // target: the kinds a loop reads hold what schema itself writes. + loopsBack := refersBackTo(loweringContext, ref, schema) || onLoop(ref) + widened := nullIdiomConjunction(loweringContext, schema) + if loopsBack && !holdsNothing(schema, besideOneRef{nullableDeclares: nullableDeclares(loweringContext, schema, widened)}) { + return false + } + carried := carriedAt(loweringContext, schema) + var refKinds kindSet + if !loopsBack { + refKinds = declaredKinds(loweringContext, ref) + } + quiet := func(statementSchema *statement.Schema, restated bool) bool { + beside := besideOneRef{refKinds: refKinds, restatesProperties: restated, nullableDeclares: nullableDeclares(loweringContext, statementSchema, widened)} + return holdsNothing(statementSchema, beside) || carried && bindsUseOnly(loweringContext, statementSchema, beside) + } + for _, entry := range comp.entries { + if entry.schema.Ref == nil && !quiet(entry.schema.Schema, restatesReferentProperties(loweringContext, ref, entry.schema.Schema)) { + return false + } + } + return quiet(schema, restatesReferentProperties(loweringContext, ref, schema)) +} + +// oneQuietRef returns the statement of comp's one $ref entry, and nil where +// it writes none or several, or one writing something read beside its $ref, as +// an entry read whole may (statement.ReadBeside). +func oneQuietRef(comp allOfComposition) *statement.Statement { + var ref *statement.Statement + for _, entry := range comp.entries { + if entry.schema.Ref == nil { + continue + } + if ref != nil || slices.ContainsFunc(entry.schema.Keys, func(key statement.Key) bool { + return statement.ReadBeside(key, entry.schema.Ref.Keyword) + }) { + return nil + } + ref = entry.schema + } + return ref +} + +// declaredKinds returns the kinds the referent of the $ref statement ref +// declares it lowers to (lowersTo), null aside: none where only the +// kind-inference policy reads them, which are no kinds the referent states. +func declaredKinds(loweringContext lowering.Ctx, ref *statement.Statement) kindSet { + kinds, inferred := lowersTo(loweringContext, ref) + if inferred { + return 0 + } + return kinds &^ kindNull +} + +// besideOneRef is how a conjunct of a use of one $ref is read beside it: +// refKinds, the kinds its referent declares, and whether its `properties` +// restate the referent's and its `nullable` says something of the instance. +type besideOneRef struct { + refKinds kindSet + restatesProperties bool + nullableDeclares bool +} + +// declaresBeside reports whether key, which schema writes, says something of +// the instance beside the $ref, as b reads it. +func (b besideOneRef) declaresBeside(schema *statement.Schema, key statement.Key) bool { + switch { + case key.Name == "allOf" && len(schema.AllOf) > 0, !statement.ReadBeside(key, ""): + return false + case key.Name == "type": + return !typeNamesOnly(schema, b.refKinds) + case key.Name == "properties": + return !b.restatesProperties + case key.Name == "nullable": + return b.nullableDeclares + default: + return true + } +} + +// bindsUseOnly reports whether every key schema writes that says something +// beside the $ref binds the use, which a carrier holds and a node cannot +// (docs/compilers/openapi.md#use-bound-annotations), a `nullable: true` the +// policy reads as widening the reference among them +// (docs/compilers/openapi.md#nullable). +func bindsUseOnly(loweringContext lowering.Ctx, schema *statement.Schema, beside besideOneRef) bool { + beside.nullableDeclares = !loweringContext.NullableInference.Honours() || !nullableTrue(schema) + return schema.Truth == statement.Stated && !slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { + return !slices.Contains(useBoundKeywords, key.Name) && beside.declaresBeside(schema, key) + }) +} + +// typeNamesOnly reports whether schema's `type` names exactly kinds, what a +// $ref's referent declares, so it narrows nothing the $ref admits. Null, an +// inferred kind and a word no dialect defines are never among kinds, so a type +// naming one says something of its own. +func typeNamesOnly(schema *statement.Schema, kinds kindSet) bool { + var named kindSet + for _, typeName := range schema.Types() { + kind := kindsOfTypeName(typeName) + if kind == 0 { + return false + } + named |= kind + } + return named == kinds +} + +// carriedAt reports whether a carrier, a listed property or a parameter's or +// header's schema, holds the position the bindings place schema at. It reads +// the placement, never the lowering reaching schema, so every reader of +// schema's decision reads one answer. +func carriedAt(loweringContext lowering.Ctx, schema *statement.Schema) bool { + at, placed := siteOf(schema) + if !placed { + return false + } + pointer := at.Pointer + if pointer.Parent().LastToken() == "properties" { + owner := loweringContext.Statements().At(reftable.DocumentPointer{Doc: at.Doc, Pointer: pointer.Parent().Parent()}) + return owner.Truth == statement.Stated && slices.ContainsFunc(owner.ObjectKeywords().Properties, func(sub statement.Subschema) bool { + return sub.Name == pointer.LastToken() && loweringContext.Statements().Subschema(sub).Schema == schema + }) + } + if pointer.LastToken() != "schema" { + return false + } + holder := reftable.DocumentPointer{Doc: at.Doc, Pointer: pointer.Parent()} + if holder.Pointer.Parent().LastToken() == "content" { + holder.Pointer = holder.Pointer.Parent().Parent() + } + return loweringContext.Bindings().ObjectAt(holder, reftable.RefParameter) != nil || loweringContext.Bindings().ObjectAt(holder, reftable.RefHeader) != nil +} + +// holdsNothing reports whether a node of schema would hold nothing beside its +// reference: `true`, a value written as no schema +// (docs/compilers/openapi.md#null-schema), or a schema object none of whose +// keys declares something beside the $ref. It is no keySaysNothing: a $id +// bounds no instance, yet the node holds it. +func holdsNothing(schema *statement.Schema, beside besideOneRef) bool { + if schema.Truth == statement.Anything || schema.Truth == statement.Unwritten { + return true + } + return schema.Truth == statement.Stated && !slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { + return beside.declaresBeside(schema, key) + }) +} + +// nullableDeclares reports whether the `nullable` schema writes states +// something of the instance (docs/compilers/openapi.md#nullable). A value but +// `true` its dialect reads says nothing; a `true` the nullable-inference +// policy reads says something only where widened marks the conjunction +// widened by it; any other, kept verbatim or a conjunct of its own, does. +func nullableDeclares(loweringContext lowering.Ctx, schema *statement.Schema, widened bool) bool { + honours := loweringContext.NullableInference.Honours() + switch { + case !definesNullableFor(loweringContext, schema) && (!honours || !nullableTrue(schema)): + return true + case !nullableTrue(schema): + return false + case honours: + return widened + default: + return true + } +} + +// decideBeforeIntersecting returns the decision on schema taken before what +// its conjuncts admit together is read, and false where none is. +func decideBeforeIntersecting(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, conjuncts []conjunct, + admissionReaderValue *admissionReader, one bool, +) (refinementDecision, bool) { + if decision, ok := besideRefDecision(loweringContext, schema, comp, conjuncts); ok { + return decision, true + } + if !one && admissionReaderValue.incomplete() && !pastAlone(loweringContext, conjuncts) { + return cutRead(loweringContext, schema, conjuncts, len(comp.entries), budgetCut(admissionReaderValue)), true + } + return refinementDecision{}, false +} + +// decideRefinement reads what refinementOf remembers: conjuncts sharing no +// value, or admitting an object alone, null aside, compose unless a value set +// is chosen first (docs/compilers/openapi.md#competing-keywords), and anything +// else uses its principal. +func decideRefinement(loweringContext lowering.Ctx, schema *statement.Schema) refinementDecision { + comp := allOfEntries(loweringContext, schema, "") + one := usesOneRef(loweringContext, schema, comp) + if !refinableEntries(comp) { + return entriesCut(loweringContext, schema, comp, one) + } + if readLoweredUnion(loweringContext, schema).besideRest == unionSplitByKind { + // The body is split across the union's branches by kind, each + // variant composing what it takes of it (docs/compilers/openapi.md#union-beside-structure). + return refinementDecision{} + } + admissionReader := newAdmissionReader(loweringContext) + // The decision is remembered by schema alone, so it reads schema's own + // dialect, and the null the nullable-inference policy reads, which the + // readers after the choice share. + admissionReader.nullable = definesNullableFor(loweringContext, schema) || loweringContext.NullableInference.Honours() + conjuncts, principal := admissionReader.conjuncts(schema, comp, one) + if early, decided := decideBeforeIntersecting(loweringContext, schema, comp, conjuncts, &admissionReader, one); decided { + return early + } + admittedTogether := conjuncts[0].read + for _, conjunct := range conjuncts[1:] { + admittedTogether = admittedTogether.and(conjunct.read) + } + kinds, inferred := positionKinds(loweringContext, schema, admittedTogether, conjuncts) + // A use of one target (usesOneRef), or a union no branch of which lives, + // which the reading puts aside, decides otherwise. + if !one && readLoweredUnion(loweringContext, schema).besideRest != unionLeavesNoBranch && intersectionIsNullAlone(schema, admittedTogether, conjuncts) { + return nullIntersectionDecision(loweringContext, conjuncts, admittedTogether, kinds, inferred, len(comp.entries)) + } + emptyEnumType := emptyEnumBeside(conjuncts) + contradicts := !one && principal == nil && emptyEnumType == "" && disjoint(admittedTogether, conjuncts) + if ref := notedRef(conjuncts); contradicts && ref != nil { + // One reference with notes beside it is the reference, whatever its + // target admits, which the target reports. + principal, contradicts = ref, false + } + apart := contradicts && admittedTogether.fixed && admittedTogether.kinds&^kindNull != 0 && kinds != kindObject + var names []string + if contradicts { + names = apartNames(loweringContext, schema, comp, conjuncts, admittedTogether, emptySetApart(admittedTogether, conjuncts)) + } + read := refinementInputs{schema: schema, comp: comp, conjuncts: conjuncts, admittedTogether: admittedTogether, kinds: kinds, inferred: inferred, + one: one, contradicts: contradicts, apart: apart, names: names, emptyEnumType: emptyEnumType} + if principal == nil && (contradicts || kinds == kindObject && !one) { + chosen, settled, done := read.composing(loweringContext, &admissionReader) + if done { + return settled + } + principal = chosen + } + return read.choosePrincipal(loweringContext, &admissionReader, principal) +} + +// positionKinds is the kinds the position of schema lowers to: beside a union +// its conjunction chooses, the body's outside the union, else the union's +// where the body names none. +func positionKinds(loweringContext lowering.Ctx, schema *statement.Schema, admittedTogether admitted, conjuncts []conjunct) (kindSet, bool) { + kinds, inferred := conjunctionKinds(loweringContext, schema, admittedTogether, conjuncts) + if _, lowersUnion := readConjunction(loweringContext, schema).loweredUnion(); !lowersUnion { + return kinds, inferred + } + if rest := readConjunctionRest(loweringContext, schema); rest.ownKinds&^kindNull != everyKindButNull || kinds&^kindNull == 0 { + return rest.ownKinds, rest.ownInferred + } + return kinds, inferred +} + +// intersectionIsNullAlone reports whether the conjuncts of schema admit null +// alone together, though none does alone and none writes a union: the null +// type, which no conjunct contradicts and no Model composes +// (docs/compilers/openapi.md#allof-refinement). +func intersectionIsNullAlone(schema *statement.Schema, admittedTogether admitted, conjuncts []conjunct) bool { + if admittedTogether.fixed || admittedTogether.kinds != kindNull || declaresUnion(schema) { + return false + } + return !slices.ContainsFunc(conjuncts, func(conjunct conjunct) bool { + return conjunct.read.kinds == kindNull || conjunct.entry != nil && conjunct.entry.schema.Ref == nil && declaresUnion(conjunct.schema) + }) +} + +// nullIntersectionDecision is the decision on conjuncts whose intersection is +// null alone: a refinement choosing no entry, lowering to the node of null. +func nullIntersectionDecision(loweringContext lowering.Ctx, conjuncts []conjunct, admittedTogether admitted, kinds kindSet, inferred bool, entries int) refinementDecision { + refChoiceReasons, possiblePrincipals := refChoiceReasonsOf(loweringContext, conjuncts, kinds, inferred, entries) + for _, conjunct := range possiblePrincipals { + refChoiceReasons[conjunct.entryIndex] = refNullIntersection + } + return refinementDecision{refinement: refinement{refChoiceReasons: refChoiceReasons, admittedTogether: admittedTogether, loweredAdmits: admittedTogether}, outcome: decisionRefinesNullIntersection} +} + +// composing returns the value set read chooses where its conjuncts would +// otherwise compose, and, with done, the decision where the read settles +// there instead: a bottom or the composition. +func (read refinementInputs) composing(loweringContext lowering.Ctx, admissionReaderValue *admissionReader) (*conjunct, refinementDecision, bool) { + emptySet := statesEmptySet(read.conjuncts) + if read.contradicts && !emptySet && (setsTypeNoEnum(read.admittedTogether) || pairsBottom(loweringContext, read.conjuncts)) { + return nil, refinementDecision{apart: apartNames(loweringContext, read.schema, read.comp, read.conjuncts, read.admittedTogether, true), outcome: decisionComposesBottom}, true + } + principal := chosenSetConjunct(admissionReaderValue, read.schema, read.conjuncts) + if principal != nil || read.apart { + return principal, refinementDecision{}, false + } + out := refinementDecision{apart: read.names, inferred: read.inferred, outcome: decisionComposes} + if read.contradicts && bodyKinds(admissionReaderValue, read.conjuncts) == 0 && !emptySet { + out.outcome = decisionComposesBottom + } + return nil, out, true +} + +// refinementInputs is what decideRefinement read of a position before it +// chooses the conjunct the position lowers from: its composition and conjuncts, +// what they admit together and lower to, and how they contradict one another. +type refinementInputs struct { + schema *statement.Schema + comp allOfComposition + conjuncts []conjunct + admittedTogether admitted + names []string + emptyEnumType ir.PrimitiveKind + kinds kindSet + inferred, one, contradicts, apart bool +} + +// choosePrincipal returns the refinement read decides, principal being the +// conjunct an earlier step chose, nil for none. A read the choice cuts short +// is decided by what the conjuncts say. +func (read refinementInputs) choosePrincipal(loweringContext lowering.Ctx, admissionReader *admissionReader, principal *conjunct) refinementDecision { + conjuncts := read.conjuncts + refChoiceReasons, possiblePrincipals := refChoiceReasonsOf(loweringContext, conjuncts, read.kinds, read.inferred, len(read.comp.entries)) + undecided, empty := principal == nil && read.apart, read.contradicts && (sharesNoMember(read.admittedTogether) || emptySetApart(read.admittedTogether, conjuncts)) + switch { + case undecided && empty && leastSet(conjuncts) != nil: + principal, undecided = leastSet(conjuncts), false + case undecided: + principal = &conjuncts[0] + case principal == nil: + // Conjuncts intersecting in null alone are the null type the one saying so + // is, whatever a $ref beside it admits besides. + var nullAlone bool + if principal, nullAlone = nullAloneConjunct(conjuncts, read.admittedTogether); !nullAlone { + principal = admissionReader.chooseConjunctToLowerFrom(conjuncts, possiblePrincipals) + } + } + setsIntersect := !read.contradicts && valueSetsIntersect(admissionReader, conjuncts, read.admittedTogether, principal) + if setsIntersect { + // The members the sets share appear in the order the least of them + // writes, so no order of the conjuncts decides it. + principal = leastSet(conjuncts) + } + refinementValue := refinement{refChoiceReasons: refChoiceReasons, admittedTogether: read.admittedTogether, loweredAdmits: loweredAdmitsOf(loweringContext, read.schema, principal), + contradicts: read.contradicts, sharesNoMember: empty, emptyEnumType: read.emptyEnumType, setsIntersect: setsIntersect} + refAt, readsThrough := readThrough(conjuncts, principal) + agreement := conjunctsAgree + switch { + case undecided: + agreement = conjunctsUndecided + case read.contradicts: + agreement = conjunctsContradict + } + markOutranked(admissionReader, refinementValue.refChoiceReasons, possiblePrincipals, principal, agreement) + markNullAlone(admissionReader.loweringContext, read.schema, refinementValue.refChoiceReasons, possiblePrincipals, principal) + if admissionReader.incomplete() && !read.one && !pastAlone(loweringContext, conjuncts) { + return cutRead(loweringContext, read.schema, conjuncts, len(read.comp.entries), budgetCut(admissionReader)) + } + return refinementDecision{refinement: refinementValue, apart: read.names, principalAt: principal.entryIndex, refAt: refAt, outcome: decisionRefines, hasPrincipal: true, + readsThrough: readsThrough} +} + +// nullAloneConjunct returns, where admittedTogether, what conjuncts admit +// together, is null alone, the first of them whose own read admits null alone, +// and false where none does. +func nullAloneConjunct(conjuncts []conjunct, admittedTogether admitted) (*conjunct, bool) { + nullAlone := func(read admitted) bool { return read.reachable() && read.kinds == kindNull } + for i := range conjuncts { + if conjunct := &conjuncts[i]; nullAlone(admittedTogether) && nullAlone(conjunct.read) { + return conjunct, true + } + } + return nil, false +} + +// conjunctionKinds returns the kinds schema lowers to, null aside, and whether +// the kind-inference policy read them. Beside a conjunct admitting every kind, +// a loop or a $ref naming nothing, they are what the others declare or the +// policy reads off them, as for schema without it. +func conjunctionKinds(loweringContext lowering.Ctx, schema *statement.Schema, admittedTogether admitted, conjuncts []conjunct) (kindSet, bool) { + schemaStatement := loweringContext.Statements().Read(schema) + kinds, inferred := lowersTo(loweringContext, schemaStatement) + if !slices.ContainsFunc(conjuncts, func(conjunct conjunct) bool { return conjunct.everyKindReason != 0 }) { + return kinds, inferred + } + if declared := admittedTogether.kinds &^ kindNull; declared != everyKindButNull { + return declared, false + } + if kinds != everyKindButNull { + return kinds, inferred + } + if rest := readConjunctionRest(loweringContext, schema); rest.ownKinds != everyKindButNull { + return rest.ownKinds, rest.ownInferred + } + return kinds, inferred +} + +// bodyKinds returns the kinds conjuncts admit together outside every union, +// null among them: where they share none, the position is the bottom. +func bodyKinds(admissionReaderValue *admissionReader, conjuncts []conjunct) kindSet { + kinds := kindAny + for _, conjunct := range conjuncts { + read := conjunct.read + if conjunct.schema != nil && declaresUnion(conjunct.schema) && !conjunct.writesRef() { + read = admissionReaderValue.written(conjunct.schema, admissionReaderValue.nullable) + } + kinds &= read.kinds + } + return kinds +} + +// bottomAt reports whether the allOf schema writes is the bottom: its +// conjuncts share no kind, nor a null the nullable-inference policy reads. +// That null answer reads the decision, so it is asked here, after it. +func bottomAt(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return decisionOf(loweringContext, schema).outcome == decisionComposesBottom && !nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(schema)).mayAdmit(loweringContext) +} + +// statesEmptySet reports whether an inline conjunct states a value set with +// no member, `enum: []`, which is the closed empty Enum rather than the bottom: +// a const and an enum sharing no member state none (constEnumOverlapOf). +func statesEmptySet(conjuncts []conjunct) bool { + return slices.ContainsFunc(conjuncts, func(conjunct conjunct) bool { + return !conjunct.writesRef() && writesEmptyEnum(conjunct.schema) + }) +} + +// emptySetApart reports whether conjuncts state several value sets, one of +// them `enum: []`, so they share no member: the closed empty Enum keeping +// every set, whatever the others hold. +func emptySetApart(admittedTogether admitted, conjuncts []conjunct) bool { + return setsStated(conjuncts) > 1 && admittedTogether.fixed && admittedTogether.size() == 0 && statesEmptySet(conjuncts) +} + +// setsStated counts the conjuncts stating a value set, a $ref's target's +// among them. +func setsStated(conjuncts []conjunct) int { + sets := 0 + for _, conjunct := range conjuncts { + if conjunct.read.fixed { + sets++ + } + } + return sets +} + +// emptyEnumBeside returns the ValueType of the closed empty Enum conjuncts +// lower to where only an inline `enum: []` among them leaves no shared value: +// typed by the kinds the others share, as `{type: string, enum: []}` is by its +// type (docs/compilers/openapi.md#enum-const). It returns "" otherwise. +func emptyEnumBeside(conjuncts []conjunct) ir.PrimitiveKind { + if !statesEmptySet(conjuncts) { + return "" + } + rest, others := admitted{kinds: kindAny}, 0 + for _, conjunct := range conjuncts { + switch inline := !conjunct.writesRef(); { + case inline && declaresUnion(conjunct.schema): + // A union's branches its own rules weigh. + return "" + case inline && writesEmptyEnum(conjunct.schema): + continue + case !inline && !conjunct.read.fixed && conjunct.read.kinds == kindAny: + // A $ref to a schema stating no kind, one naming nothing or leading + // round a loop among them, says nothing the empty enum lies within. + return "" + case !inline, conjunct.read.fixed: + others++ + case !writesNotesOnly(conjunct.schema): + return "" + } + rest = rest.and(conjunct.read) + } + if others == 0 || !rest.reachable() { + return "" + } + return setsPrimitive(sharedKinds(rest) & rest.kinds) +} + +// writesNotesOnly reports whether schema writes nothing an instance is held +// to but the allOf its statement flattens: keys that say nothing of a value +// (keySaysNothing). +func writesNotesOnly(schema *statement.Schema) bool { + return !slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { + return !keySaysNothing(schema, key) && (key.Name != "allOf" || len(schema.AllOf) == 0) + }) +} + +// setsPrimitive is the primitive an Enum of members of kinds takes, as +// enumMemberForm classifies a member: a string, a boolean, a number whatever +// its kind, and the top type for kinds no one primitive names. +func setsPrimitive(kinds kindSet) ir.PrimitiveKind { + switch { + case kinds == kindString: + return ir.PrimitiveString + case kinds == kindBoolean: + return ir.PrimitiveBool + case kinds != 0 && kinds&^kindNumber == 0: + return ir.PrimitiveNumber + default: + return ir.PrimitiveAny + } +} + +// writesEmptyEnum reports whether schema writes `enum: []`. +func writesEmptyEnum(schema *statement.Schema) bool { + return enumWritten(schema) && len(schema.Enum()) == 0 +} + +// pairsBottom reports whether an inline conjunct writes a const and an enum +// sharing no member that type no Enum (constEnumBottom), which the position is +// the bottom of, as that schema written flat is. +func pairsBottom(loweringContext lowering.Ctx, conjuncts []conjunct) bool { + return slices.ContainsFunc(conjuncts, func(conjunct conjunct) bool { + return !conjunct.writesRef() && constEnumOverlapOf(loweringContext, conjunct.schema) == constEnumBottom + }) +} + +// sharesNoMember reports whether admittedTogether, what the conjuncts admit +// together, is value sets sharing no member, whose members are of one value +// type a primitive names: a list or an object types no Enum. +func sharesNoMember(admittedTogether admitted) bool { + kinds := admittedTogether.kinds &^ kindNull + return admittedTogether.fixed && len(admittedTogether.values) == 0 && len(admittedTogether.unionedSets) == 0 && kinds&(kindArray|kindObject) == 0 && + kindCount(kinds) == 1 +} + +// setsTypeNoEnum reports whether admittedTogether is value sets sharing no +// member that type no Enum, being lists, objects or of several value types: +// the position is then the bottom. +func setsTypeNoEnum(admittedTogether admitted) bool { + return admittedTogether.fixed && admittedTogether.size() == 0 && admittedTogether.kinds&^kindNull != 0 && !sharesNoMember(admittedTogether) +} + +// leastSet returns the conjunct whose value set the position lowers to where +// the sets share no member and none lies within the others: the keywords +// beside the allOf, as competing keywords choose there, else the entry whose +// set renders least, so no order decides; nil where only a $ref states one. +func leastSet(conjuncts []conjunct) *conjunct { + var least *conjunct + var leastText string + for i := range conjuncts { + conjunct := &conjuncts[i] + if !conjunct.read.fixed || conjunct.writesRef() { + continue + } + if conjunct.entry == nil { + return conjunct + } + text, err := annotation.RawFromNode(conjunct.schema.Node) + if least == nil || err == nil && string(text) < leastText { + least, leastText = conjunct, string(text) + } + } + return least +} + +// pastAlone reports whether conjuncts, read past a cap, still refine: the +// choice weighs one $ref to a target of some kind and nothing else, so it +// compares no two readings, which is all a cap stops +// (docs/compilers/openapi.md#allof-refinement). +func pastAlone(loweringContext lowering.Ctx, conjuncts []conjunct) bool { + ref := soleRef(conjuncts) + if ref == nil { + return false + } + kinds, _ := lowersTo(loweringContext, ref.entry.schema) + return kinds != 0 +} + +// notedRef returns soleRef's $ref where every other conjunct writes nothing +// past its kinds but notes and extensions (declaringPastKinds), as a cut read's +// one conjunct left is the position (cutRead), and nil otherwise. +func notedRef(conjuncts []conjunct) *conjunct { + ref := soleRef(conjuncts) + if ref == nil || len(declaringPastKinds(conjuncts)) != 1 { + return nil + } + return ref +} + +// soleRef returns the one $ref of conjuncts where every other names no kind +// and admits everything, nil otherwise. +func soleRef(conjuncts []conjunct) *conjunct { + var ref *conjunct + for i := range conjuncts { + conjunct := &conjuncts[i] + isRef := conjunct.writesRef() + switch { + case isRef && ref == nil: + ref = conjunct + case isRef || conjunct.declaresKind || !conjunct.read.admitsEverything(): + return nil + } + } + return ref +} + +// conjunctAgreement is how the conjuncts a choice weighs relate to one +// another, for marking the $refs its principal was chosen over (markOutranked). +type conjunctAgreement uint8 + +const ( + // conjunctsAgree marks conjuncts sharing a value. + conjunctsAgree conjunctAgreement = iota + // conjunctsContradict marks conjuncts sharing no value, a principal + // chosen for them. + conjunctsContradict + // conjunctsUndecided marks value sets sharing no member that leave no + // conjunct the principal. + conjunctsUndecided +) + +// markOutranked marks in refChoiceReasons how each $ref of possiblePrincipals +// fared once principal was chosen. +func markOutranked(admissionReaderValue *admissionReader, refChoiceReasons []refChoiceReason, possiblePrincipals []*conjunct, principal *conjunct, agreement conjunctAgreement) { + for _, conjunct := range possiblePrincipals { + switch { + case agreement == conjunctsUndecided: + refChoiceReasons[conjunct.entryIndex] = refApart + case conjunct != principal && principal.writesRef(): + refChoiceReasons[conjunct.entryIndex] = refNarrowed + case agreement == conjunctsContradict && !admissionReaderValue.within(principal.read, conjunct.read): + refChoiceReasons[conjunct.entryIndex] = refOutsideSet + } + } +} + +// valueSetsIntersect reports whether conjuncts state inline value sets that +// share members, none within every other, and no $ref states one or is +// principal: the position is then the Enum of what they share, as a flat enum +// lowers (docs/compilers/openapi.md#allof-refinement). +func valueSetsIntersect(admissionReaderValue *admissionReader, conjuncts []conjunct, admittedTogether admitted, principal *conjunct) bool { + if admittedTogether.size() == 0 || principal.writesRef() { + // Sets sharing no member contradict, which decideRefinement reads + // before asking; none is left here but no set or an `enum: []`, which + // lies within every other. + return false + } + var sets []admitted + for _, conjunct := range conjuncts { + switch { + case !conjunct.read.fixed: + case conjunct.writesRef(): + return false + default: + sets = append(sets, conjunct.read) + } + } + return len(sets) > 1 && !slices.ContainsFunc(sets, func(set admitted) bool { + return !slices.ContainsFunc(sets, func(other admitted) bool { return !admissionReaderValue.setWithin(set, other) }) + }) +} + +// markNullAlone marks each of possiblePrincipals refNullIntersection where +// principal writes the union schema's conjunction leaves null alone: the +// position is the null type, a use of no target. +func markNullAlone(loweringContext lowering.Ctx, schema *statement.Schema, refChoiceReasons []refChoiceReason, possiblePrincipals []*conjunct, principal *conjunct) { + if principal.entry == nil || principal.schema != unionPrincipal(loweringContext, schema) || + readLoweredUnion(loweringContext, schema).besideRest != unionLeavesNullAlone { + return + } + for _, conjunct := range possiblePrincipals { + refChoiceReasons[conjunct.entryIndex] = refNullIntersection + } +} + +// chosenSetConjunct returns the inline conjunct stating a value set chosen +// before a composition, one within every other set, nil for none. A set its +// own keywords leave no value is read as competing keywords pick it, so it +// lowers alike beside the allOf and on an entry. +func chosenSetConjunct(admissionReaderValue *admissionReader, schema *statement.Schema, conjuncts []conjunct) *conjunct { + var sets []*conjunct + for i := range conjuncts { + conjunct := &conjuncts[i] + conjunctSchema := schema + if conjunct.entry != nil { + conjunctSchema = conjunct.entry.schema.Schema + } + inline := !conjunct.writesRef() + if !inline || !enumWritten(conjunctSchema) && conjunctSchema.Const() == nil { + continue + } + if !conjunct.read.reachable() { + conjunct.read = competingSet(admissionReaderValue, conjunctSchema) + } + // `enum: []` beside the allOf is a set only beside another set + // (emptySetApart); alone it is the dispatch's (competing keywords). + besideEmpty := conjunct.entry == nil && writesEmptyEnum(conjunctSchema) && setsStated(conjuncts) > 1 + if conjunct.read.fixed && (conjunct.read.reachable() || (conjunct.entry != nil || besideEmpty) && len(conjunct.read.values) == 0) { + sets = append(sets, conjunct) + } + } + within := slices.DeleteFunc(slices.Clone(sets), func(candidate *conjunct) bool { + return slices.ContainsFunc(sets, func(other *conjunct) bool { + return other != candidate && !admissionReaderValue.setWithin(candidate.read, other.read) + }) + }) + if len(within) == 0 { + return nil + } + if chosen := untie(admissionReaderValue, conjuncts, within); slices.Contains(within, chosen) { + return chosen + } + return nil +} + +// competingSet is what the value set schema writes admits read as the dispatch +// of competing keywords lowers it, its `const` before its `enum`, each alone +// (docs/compilers/openapi.md#competing-keywords). +func competingSet(admissionReaderValue *admissionReader, schema *statement.Schema) admitted { + if constant := schema.Const(); constant != nil { + return admissionReaderValue.valueSet(valueSetOf{schema, "const"}, []*yaml.Node{constant}) + } + return admissionReaderValue.valueSet(valueSetOf{schema, "enum"}, schema.Enum()) +} + +// restKinds returns the kinds schema lowers to with every union its +// conjunction writes left out, and whether the kind-inference policy read +// them, settled as the run's admission settles a statement's. +func restKinds(loweringContext lowering.Ctx, schema *statement.Schema) (kindSet, bool) { + var rest admission + rest.firm, rest.inferredKinds = ownKinds(loweringContext, schema) + for _, entry := range allOfEntries(loweringContext, schema, "").entries { + entrySchema := entry.schema.Schema + if entry.schema.Ref == nil && (declaresUnion(entrySchema) || entry.wrapper) { + // An entry's union is the one left out, as schema's own, and a + // wrapper's own keywords are its conjunct, its entries listed apart. + var own admission + own.firm, own.inferredKinds = ownKinds(loweringContext, entrySchema) + rest.conjoinKinds(&own) + continue + } + rest.conjoinKinds(composedEntryAdmission(loweringContext, schema, entry.schema)) + } + rest.settleKinds() + return rest.kinds, rest.inferred +} + +// refChoiceReasonsOf returns how each $ref conjunct fares where the position +// lowers to kinds, declared unless inferred, indexed by entry, and the $refs +// that may be the principal. +func refChoiceReasonsOf(loweringContext lowering.Ctx, conjuncts []conjunct, kinds kindSet, inferred bool, entries int) ([]refChoiceReason, []*conjunct) { + says := !inferred && kinds != everyKindButNull || slices.ContainsFunc(conjuncts, func(conjunct conjunct) bool { return conjunct.declaresKind }) + refChoiceReasons := make([]refChoiceReason, entries) + var possiblePrincipals []*conjunct + for i := range conjuncts { + conjunct := &conjuncts[i] + if !conjunct.writesRef() { + continue + } + refChoiceReasons[conjunct.entryIndex] = conjunct.everyKindReason + if conjunct.everyKindReason == 0 { + refChoiceReasons[conjunct.entryIndex] = refChoiceReasonOf(loweringContext, kinds, says, conjunct) + } + if refChoiceReasons[conjunct.entryIndex] == refMayBePrincipal { + possiblePrincipals = append(possiblePrincipals, conjunct) + } + } + return refChoiceReasons, possiblePrincipals +} + +// refChoiceReasonOf returns how the $ref conjunct ref fares where the position +// lowers to kinds and says, or not, what it is. What the document declares +// outranks a kind the policy infers for the target and a target admitting +// every kind (docs/compilers/openapi.md#policies). +func refChoiceReasonOf(loweringContext lowering.Ctx, kinds kindSet, says bool, ref *conjunct) refChoiceReason { + target, targetInferred := lowersTo(loweringContext, ref.entry.schema) + switch { + case targetInferred && (kinds&^kindNull&^target != 0 || kinds&target == 0): + return refInferredApart + case !targetInferred && target == everyKindButNull && says: + return refAdmitsEvery + default: + return refMayBePrincipal + } +} + +// readThrough returns where the $ref entry a use of the position reads on +// through is among the conjuncts: the principal where it is a $ref, else the +// one $ref written; and false where none or several are. +func readThrough(conjuncts []conjunct, principal *conjunct) (annotation.ConjunctIndex, bool) { + if principal.writesRef() { + return principal.entryIndex, true + } + var ref annotation.ConjunctIndex + found := false + for _, conjunct := range conjuncts { + if !conjunct.writesRef() { + continue + } + if found { + return 0, false + } + ref, found = conjunct.entryIndex, true + } + return ref, found +} + +// loweredAdmitsOf returns what the position schema admits lowering to the +// conjunct principal, an entry's node read as schema's allOf reads it. +func loweredAdmitsOf(loweringContext lowering.Ctx, schema *statement.Schema, principal *conjunct) admitted { + if principal.entry == nil { + return principal.read + } + return asLowered(composedEntryAdmission(loweringContext, schema, principal.entry.schema), principal.read) +} + +// refinableEntries reports whether every entry of comp can be read as a +// conjunct of a refinement: none nests past the flattening depth or is +// `false`, and at most maxRefinedConjuncts state something. +func refinableEntries(comp allOfComposition) bool { + if writing := slices.DeleteFunc(slices.Clone(comp.entries), func(entry allOfEntry) bool { return !stated(entry.schema.Schema) }); len(writing) > maxRefinedConjuncts { + return false + } + return !slices.ContainsFunc(comp.entries, func(allOfEntryValue allOfEntry) bool { + return allOfEntryValue.capped || allOfEntryValue.schema.Truth.ReadsFalse() + }) +} + +// conjuncts reads schema's own keywords, then each entry of comp but a `true`. +// A union chosen alone on an inline entry is that entry's conjunct, returned +// second as the principal; where none is chosen, each union is a conjunct of +// the schema writing it. alone marks a use of one $ref saying nothing more. +func (reader *admissionReader) conjuncts(schema *statement.Schema, comp allOfComposition, alone bool) ([]conjunct, *conjunct) { + out := make([]conjunct, 0, 1+len(comp.entries)) + inferredKinds := inferredConjunctKinds(reader.loweringContext, schema) + // A union the position writes itself says what it is, as its union + // reading lowers it there; one the body's node keeps says nothing of the + // kind, which a conjunct writing it may. + own := conjunct{read: reader.written(schema, reader.nullable), schema: schema, entryIndex: annotation.BesideAllOf, + declaresKind: declaresReadKind(reader.loweringContext, schema) || writesEveryInferredKind(reader.loweringContext, schema, inferredKinds) || declaresUnion(schema) && !readLoweredUnion(reader.loweringContext, schema).besideRest.keptByRest()} + if nullIdiomConsumes(reader.loweringContext, schema, schema) { + // The null is the reference's, which the policy widens (nullIdiomConsumes). + own.read, own.declaresKind = admitted{kinds: kindAny}, false + } + _, lowersUnion := readConjunction(reader.loweringContext, schema).loweredUnion() + if !lowersUnion && declaresUnion(schema) { + // No union chosen, none is read apart: each is a conjunct. + own.read = own.read.and(unionsIn(reader, schema)) + } + out = append(out, own) + holder := unionPrincipal(reader.loweringContext, schema) + principal := -1 + for i := range comp.entries { + entry, at := &comp.entries[i], annotation.ConjunctIndex(i) + entrySchema := entry.schema.Schema + switch { + case !stated(entrySchema): + case entry.schema.Ref != nil: + read, neutral := reader.refConjunct(schema, entry.schema, alone) + out = append(out, conjunct{entry: entry, entryIndex: at, read: read, schema: entrySchema, everyKindReason: neutral}) + case nullIdiomConsumes(reader.loweringContext, schema, entrySchema): + out = append(out, conjunct{entry: entry, entryIndex: at, read: admitted{kinds: kindAny}, schema: entrySchema}) + case entrySchema == holder: + // A union conjoined with the body's kind admits that kind alone. + principal = len(out) + read := inlineConjunct(reader, entrySchema) + if kind := readLoweredUnion(reader.loweringContext, schema).kind; kind != "" { + read = read.and(admitted{kinds: kindsOfTypeName(kind)}) + } + out = append(out, conjunct{entry: entry, entryIndex: at, read: read, schema: entrySchema, declaresKind: true}) + case !lowersUnion: + out = append(out, conjunct{entry: entry, entryIndex: at, read: inlineConjunct(reader, entrySchema), schema: entrySchema, + declaresKind: declaresReadKind(reader.loweringContext, entrySchema) || writesEveryInferredKind(reader.loweringContext, entrySchema, inferredKinds)}) + default: + out = append(out, conjunct{entry: entry, entryIndex: at, read: reader.written(entrySchema, reader.nullable), schema: entrySchema, + declaresKind: declaresReadKind(reader.loweringContext, entrySchema) || writesEveryInferredKind(reader.loweringContext, entrySchema, inferredKinds)}) + } + } + if principal < 0 { + return out, nil + } + return out, &out[principal] +} + +// unionPrincipal returns the inline allOf entry writing the union schema's +// conjunction chooses where that union is the position, nil otherwise or where +// schema writes it itself (docs/compilers/openapi.md#union-beside-structure). +func unionPrincipal(loweringContext lowering.Ctx, schema *statement.Schema) *statement.Schema { + loweredUnion, ok := readConjunction(loweringContext, schema).loweredUnion() + if !ok || loweredUnion.holder == schema || !unionLoweredAlone(loweringContext, schema, loweredUnion.holder) { + return nil + } + return loweredUnion.holder +} + +// inferredConjunctKinds returns the kinds schema lowers to, null aside, where +// the kind-inference policy read them off the claims of its conjuncts, and none +// where schema or a conjunct declares a kind. +func inferredConjunctKinds(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { + kinds, inferred := lowersTo(loweringContext, loweringContext.Statements().Read(schema)) + if !inferred { + return 0 + } + return kinds &^ kindNull +} + +// writesEveryInferredKind reports whether schema's own keywords name every +// kind of inferredKinds, so it says what the position is as a `type` would: +// `{allOf: [{items: X}]}` is a use of its entry's list +// (docs/compilers/openapi.md#shape-applicator). +func writesEveryInferredKind(loweringContext lowering.Ctx, schema *statement.Schema, inferredKinds kindSet) bool { + return inferredKinds != 0 && inferredKinds&^kindsInferredFromShape(loweringContext, schema) == 0 +} + +// inlineConjunct is what entrySchema, an inline entry, admits as +// admissionReaderValue reads it: its own keywords and its unions. Its allOf is +// read apart, its entries being conjuncts of their own. +func inlineConjunct(admissionReaderValue *admissionReader, entrySchema *statement.Schema) admitted { + read := admissionReaderValue.written(entrySchema, admissionReaderValue.nullable) + if declaresUnion(entrySchema) { + read = read.and(unionsIn(admissionReaderValue, entrySchema)) + } + return read +} + +// refConjunct is what the $ref conjunct schemaStatement of position admits in +// a choice: what its target does, or every kind where it loops back to +// position or, not alone, names nothing, since such a $ref cuts nothing +// (docs/compilers/openapi.md#allof-refinement). The second result says which. +func (reader *admissionReader) refConjunct(position *statement.Schema, schemaStatement *statement.Statement, alone bool) (admitted, refChoiceReason) { + switch { + case !namesReferent(reader.loweringContext, schemaStatement): + if !alone { + return admitted{kinds: kindAny}, refNamesNothing + } + case leadsBackTo(reader.loweringContext, schemaStatement, position): + return admitted{kinds: kindAny}, refAround + } + return reader.of(schemaStatement), 0 +} + +// leadsBackTo reports whether schemaStatement's $ref, followed through uses of +// one $ref and hops, lands back on position: a loop admitting, by kind, what +// position writes alone. +func leadsBackTo(loweringContext lowering.Ctx, schemaStatement *statement.Statement, position *statement.Schema) bool { + seen := map[*statement.Statement]bool{} + for target, _ := declaredOf(loweringContext, schemaStatement); target != nil && !seen[target]; target, _ = declaredOf(loweringContext, target) { + if target.Schema == position { + return true + } + seen[target] = true + next := oneRefOf(loweringContext, target) + if next == nil { + next = hopRefOf(loweringContext, target) + } + if target = next; target == nil { + return false + } + } + return false +} + +// refersBackTo reports whether schemaStatement's $ref, followed through each +// target writing a $ref or a hop of one, lands back on position. Unlike +// leadsBackTo it asks no target whether it is a use, since usesOneRef asks it. +func refersBackTo(loweringContext lowering.Ctx, schemaStatement *statement.Statement, position *statement.Schema) bool { + seen := map[*statement.Statement]bool{} + for target, _ := declaredOf(loweringContext, schemaStatement); target != nil && !seen[target]; target, _ = declaredOf(loweringContext, target) { + if target.Schema == position { + return true + } + seen[target] = true + switch hopRef := hopRefOf(loweringContext, target); { + case target.Ref != nil: + case target.BesideRef != nil: + target = loweringContext.Statements().Read(target.BesideRef) + case hopRef != nil: + target = hopRef + default: + return false + } + } + return false +} + +// oneRefOf returns the statement of the $ref schemaStatement is a use of, +// saying nothing more, nil for none. It is read once a run, since a chain of +// such uses asks it of each hop once per position reading the chain. +func oneRefOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) *statement.Statement { + if schemaStatement.Ref != nil { + return schemaStatement + } + return lowering.ReadOncePerRun(loweringContext, oneRefOfKey{schemaStatement}, func() *statement.Statement { + comp := allOfEntries(loweringContext, schemaStatement.Schema, "") + if !usesOneRef(loweringContext, schemaStatement.Schema, comp) { + return nil + } + return oneQuietRef(comp) + }) +} + +// oneRefOfKey keys what oneRefOf read of one statement. +type oneRefOfKey struct{ schemaStatement *statement.Statement } + +// declaresReadKind reports whether schema says what kind of value its instance +// is (schemaDeclaresKind) by what the reading reads: a value set no reading +// converts says nothing (admissionReader.valueSet). +func declaresReadKind(loweringContext lowering.Ctx, schema *statement.Schema) bool { + if writesUnreadValueSet(loweringContext, schema) { + return writesType(schema) + } + return schemaDeclaresKind(schema) +} + +// writesUnreadValueSet reports whether schema writes an enum or a const that +// no reading converts (memberSetOf). +func writesUnreadValueSet(loweringContext lowering.Ctx, schema *statement.Schema) bool { + if enumWritten(schema) && memberSetOf(loweringContext, valueSetOf{schema, "enum"}, schema.Enum()).unread { + return true + } + constant := schema.Const() + return constant != nil && memberSetOf(loweringContext, valueSetOf{schema, "const"}, []*yaml.Node{constant}).unread +} + +// unionsIn is what an instance of each oneOf and anyOf schema writes admits +// together, any of a union's branches, as admissionReaderValue reads them. +func unionsIn(admissionReaderValue *admissionReader, schema *statement.Schema) admitted { + read := admitted{kinds: kindAny} + choice := schema.ChoiceKeywords() + for _, branches := range [][]statement.Subschema{choice.OneOf, choice.AnyOf} { + if len(branches) > 0 { + read = read.and(admissionReaderValue.union(branches)) + } + } + return read +} + +// nullIdiomConjunction reports whether the nullable-inference policy reads +// schema's conjunction as one reference or null, whichever of its objects +// writes the null (docs/compilers/openapi.md#nullable). +func nullIdiomConjunction(loweringContext lowering.Ctx, schema *statement.Schema) bool { + schemaStatement := loweringContext.Statements().Read(schema) + return idiomWidens(loweringContext, schemaStatement, nullExpansionOf(loweringContext, schemaStatement) != nil) +} + +// idiomWidens reports whether the policy reads schemaStatement's conjunction +// as one reference or null by the answer's rule (nullConjunctionRead.widens), +// read from the schemas alone, so it asks no answer. expands marks a dynamic +// reference it expands, a reference of its own. +func idiomWidens(loweringContext lowering.Ctx, schemaStatement *statement.Statement, expands bool) bool { + if !loweringContext.NullableInference.Honours() { + return false + } + read := nullConjunctionRead{own: nullAnswerReadingsAlike(nullSaysNothing)} + if expands { + read.references++ + } + for _, conjunctValue := range nullConjuncts(schemaStatement) { + switch { + case conjunctValue.Ref != nil: + read.references++ + case conjunctValue.Truth.ReadsFalse() || stated(conjunctValue.Schema) && conjunctValue.Capped: + return false + case stated(conjunctValue.Schema): + read.own = read.own.conjoin(writtenNull(loweringContext, conjunctValue.Schema)) + read.union = read.union || declaresUnion(conjunctValue.Schema) + read.structure = read.structure || hasAnyKey(conjunctValue.Schema, structureKeywords) + } + } + return read.widens() +} + +// nullIdiomConsumes reports whether the value keywords schema, a conjunct of +// position's conjunction, writes say nothing but the null the policy widens +// position's one reference by. Beside a target admitting null they narrow it +// to null, as written. +func nullIdiomConsumes(loweringContext lowering.Ctx, position, schema *statement.Schema) bool { + return nullIdiomConjunction(loweringContext, position) && declaresNullAlone(loweringContext, schema) && + idiomTargetForbidsNull(loweringContext, loweringContext.Statements().Read(position)) +} + +// idiomTargetForbidsNull reports whether what schemaStatement's one reference +// lands on, a $ref's target or the position its dynamic reference expands to, +// keeps null out as the policy reads it. +func idiomTargetForbidsNull(loweringContext lowering.Ctx, schemaStatement *statement.Statement) bool { + target := nullExpansionOf(loweringContext, schemaStatement) + for _, conjunctValue := range nullConjuncts(schemaStatement) { + if conjunctValue.Ref != nil { + target = nullTargetOf(loweringContext, conjunctValue.Schema) + } + } + return target != nil && nullAnswerReadingsOf(loweringContext, target).forbids(loweringContext) +} + +// declaresNullAlone reports whether schema's own value keywords admit null and +// no other value, as the policy reads them. +func declaresNullAlone(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return stated(schema) && (typedNull(loweringContext, schema).underInference == nullAdmittedByReference || nullableTrue(schema)) && + writesNullAlone(loweringContext, schema) +} + +// schemaDeclaresKind reports whether schema writes what kind of value it +// admits. +func schemaDeclaresKind(schema *statement.Schema) bool { + return writesType(schema) || enumWritten(schema) || schema.Const() != nil +} + +// disjoint reports whether the conjuncts share no value, a null they all admit +// counting as none unless a conjunct admits nothing else. Such an allOf stays +// a composition, and docs/compilers/openapi.md#allof-refinement says which +// report each contradiction gets. +func disjoint(admittedTogether admitted, conjuncts []conjunct) bool { + if !admittedTogether.reachable() { + return true + } + if admittedTogether.kinds != kindNull { + return false + } + return !slices.ContainsFunc(conjuncts, func(conjunct conjunct) bool { return conjunct.read.kinds == kindNull }) +} diff --git a/compilers/openapi/internal/schema/refinementdecision_internal_test.go b/compilers/openapi/internal/schema/refinementdecision_internal_test.go new file mode 100644 index 000000000..9e9425647 --- /dev/null +++ b/compilers/openapi/internal/schema/refinementdecision_internal_test.go @@ -0,0 +1,156 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/speakeasy-api/openapi/jsonschema/oas3" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// TestRefinementOf_AnUnrefinedSchemaHoldsNothing pins that a schema whose allOf +// composes, or may not refine, gives its readers no refinement to read. +func TestRefinementOf_AnUnrefinedSchemaHoldsNothing(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Obj: {type: object, properties: {a: {type: string}}} + T: {allOf: [{$ref: '#/components/schemas/Obj'}, {properties: {b: {type: string}}}]} + U: {type: string} +`)) + for _, name := range []string{"T", "U"} { + refinement, refined := refinementOf(lowerer.Ctx, StatedIn(lowerer, componentSchema(t, lowerer, name)), jsontext.Pointer("/components/schemas/"+name)) + assert.False(t, refined, name) + assert.Empty(t, refinement.comp.entries, "%s: no entry list is built", name) + assert.Nil(t, refinement.principal, name) + } +} + +// TestAllOfEntries_HoldTheStatementAnIndexReads pins that the statement a +// reader of the decision with no pointer takes for an index is the entry +// allOfEntries holds there. +func TestAllOfEntries_HoldTheStatementAnIndexReads(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(` Port: {type: integer} + T: {allOf: [{description: d}, {$ref: '#/components/schemas/Port'}]} +`)) + schema := StatedIn(lowerer, componentSchema(t, lowerer, "T")) + got := lowerer.Ctx.Statements().Read(lowerer.Ctx.Statements().Read(schema).Entries[1].Schema) + require.NotNil(t, got) + assert.Same(t, allOfEntries(lowerer.Ctx, schema, "").entries[1].schema, got) + assert.NotNil(t, got.Ref, "the entry at 1 is the $ref") +} + +// TestNamedEntry_NamesNoEntryForNoneOrTheKeywordsBesideTheAllOf pins the +// entry a decision's principal or ref names: none where the decision names no +// conjunct, whatever its place says, or the keywords beside the allOf, which +// every reader of a decision's entries reads as choosing no entry. +func TestNamedEntry_NamesNoEntryForNoneOrTheKeywordsBesideTheAllOf(t *testing.T) { + t.Parallel() + tests := []struct { + name string + at annotation.ConjunctIndex + named bool + wantIndex int + wantEntry bool + }{ + {name: "none named", at: 2}, + {name: "the keywords beside the allOf", at: annotation.BesideAllOf, named: true}, + {name: "an entry", at: 2, named: true, wantIndex: 2, wantEntry: true}, + } + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + index, isEntry := namedEntry(testCase.at, testCase.named) + require.Equal(t, testCase.wantEntry, isEntry) + if isEntry { + assert.Equal(t, testCase.wantIndex, index) + } + }) + } +} + +// TestCarriedAt_ReadsWhereASchemaIsWritten pins which positions a carrier +// holds by where the bindings place the schema: a property a schema lists, +// and a parameter's or a header's schema, its content's included, but not a +// component, a list's element, a schema keyed `schema` beneath a component +// named as a carrier's collection is, nor a schema no binding places. +func TestCarriedAt_ReadsWhereASchemaIsWritten(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, `openapi: 3.1.0 +info: {title: t, version: "1"} +paths: + /x: + get: + parameters: + - {name: q, in: query, schema: {type: string}} + - {name: c, in: query, content: {application/json: {schema: {type: string}}}} + responses: {"204": {description: ok, headers: {X-A: {schema: {type: string}}}}} +components: + schemas: + H: {type: object, properties: {p: {type: string}}} + L: {type: array, items: {type: string}} + parameters: {type: object, $defs: {schema: {type: string}}} + headers: {type: object, patternProperties: {schema: {type: string}}} +`) + for at, want := range map[jsontext.Pointer]bool{ + "/components/schemas/H/properties/p": true, + "/paths/~1x/get/parameters/0/schema": true, + "/paths/~1x/get/parameters/1/content/application~1json/schema": true, + "/paths/~1x/get/responses/204/headers/X-A/schema": true, + "/components/schemas/H": false, + "/components/schemas/L/items": false, + "/components/schemas/parameters/$defs/schema": false, + "/components/schemas/headers/patternProperties/schema": false, + } { + schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Pointer: at}) + require.Equal(t, statement.Stated, schemaStatement.Truth, "%s is written", at) + assert.Equal(t, want, carriedAt(lowerer.Ctx, schemaStatement.Schema), at) + } + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + assert.False(t, carriedAt(lowerer.Ctx, StandaloneSchema(jsonSchema.GetSchema())), "a schema no binding places is held by none") +} + +// fixedSet is the value set of string members. +func fixedSet(members ...string) admitted { + values := make(map[string]kindSet, len(members)) + for _, member := range members { + values[member] = kindString + } + return admitted{kinds: kindString, fixed: true, values: values} +} + +// inlineEntryConjunct is a conjunct of an inline allOf entry admitting read. +func inlineEntryConjunct(read admitted) conjunct { + return conjunct{entry: &allOfEntry{schema: &statement.Statement{Schema: &statement.Schema{}}}, read: read} +} + +// TestValueSetsIntersect_ASetAReferenceStatesIntersectsNothing pins that a +// value set a $ref conjunct's target states keeps inline sets sharing members +// from lowering to the Enum of them, the principal an inline set: that Enum is +// the inline sets' alone. +func TestValueSetsIntersect_ASetAReferenceStatesIntersectsNothing(t *testing.T) { + t.Parallel() + ref := conjunct{entry: &allOfEntry{schema: &statement.Statement{Schema: &statement.Schema{ + Ref: &statement.Reference{Keyword: "$ref", Text: "#/components/schemas/T"}, + }}}, read: fixedSet("b", "c", "d")} + conjuncts := []conjunct{inlineEntryConjunct(fixedSet("a", "b")), inlineEntryConjunct(fixedSet("b", "c")), ref} + require.True(t, valueSetsIntersect(&admissionReader{}, conjuncts[:2], fixedSet("b"), &conjuncts[0]), "the inline sets alone intersect") + assert.False(t, valueSetsIntersect(&admissionReader{}, conjuncts, fixedSet("b"), &conjuncts[0])) +} + +// TestValueSetsIntersect_NoInlineSetIntersectsNothing pins that an intersection +// stating members, no inline conjunct stating a set, is no Enum of shared +// members: fewer than two sets share none. +func TestValueSetsIntersect_NoInlineSetIntersectsNothing(t *testing.T) { + t.Parallel() + conjuncts := []conjunct{{read: admitted{kinds: kindAny}}, inlineEntryConjunct(admitted{kinds: kindString})} + assert.False(t, valueSetsIntersect(&admissionReader{}, conjuncts, fixedSet("a"), &conjuncts[1])) +} diff --git a/compilers/openapi/internal/schema/refkept.go b/compilers/openapi/internal/schema/refkept.go index 326eb907e..50839911d 100644 --- a/compilers/openapi/internal/schema/refkept.go +++ b/compilers/openapi/internal/schema/refkept.go @@ -4,6 +4,7 @@ package schema import ( + "bytes" "cmp" "encoding/json/jsontext" "maps" @@ -13,17 +14,20 @@ import ( yaml "go.yaml.in/yaml/v3" - "github.com/dexpace/morphic/compilers/compile" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) // outcomeKeeps is what a position that lowered to a reference keeps verbatim: the // unread keywords it wrote, described by shape where no refinement decided it, -// the value bounds of those a number carried as text holds none of (text), the +// the value bounds of those text of another kind holds none of (text), the // $ref entries of its allOf its lowering left unread, what its inline entries // keep (entryKeeps), the null branches a collapsed union lifts that say more // than their null (nullBranchKeeps), and the union keywords beside the allOf it @@ -33,21 +37,38 @@ type outcomeKeeps struct { text []string shape string comp allOfComposition - refEntries []wholeRefEntry + refEntries []keptRefEntry entries []keptEntry nulls []keptNullBranch validation []string - // refined marks a refinement deciding the position, which electing + // refined marks a refinement deciding the position, which choosing // principal, nil for none, describes it (refinedShape). refined bool principal *allOfEntry + // allOfWhole marks an allOf kept whole, past the flattening depth, each + // entry nesting past it reported where written (entriesCut). + allOfWhole bool + // cutBy names the bound that cut the reading of a refinement choosing no + // entry, reported once at the position for every conjunct kept (cutRead). + cutBy string + // textIntersection is what the conjuncts of the bounds of the node carrying + // text of another kind the position lowers to intersect in + // (boundHomes.textIntersection), and root what that text is of. + textIntersection textBoundIntersection + root boundRoot + // setsApart marks a refinement whose value sets share no member, which its + // one warning reports, so no conjunct keeping one reports it apart, and + // setsBesideEmpty one whose `enum: []` is the one fact beside sets sharing + // a value, each kept as written under the empty enum's one warning + // (emptyEnumBeside). + setsApart, setsBesideEmpty bool } -// wholeRefEntry is one $ref entry of an allOf a refinement keeps whole, the -// position having lost it, and how it stood in the election (voteOf). -type wholeRefEntry struct { - entry allOfEntry - vote refCandidacy +// keptRefEntry is one $ref entry of an allOf a refinement keeps whole, the +// position having lost it, and how it fared in the choice (refChoiceReasonOf). +type keptRefEntry struct { + entry allOfEntry + choiceReason refChoiceReason } // holdsAny reports whether k keeps anything. @@ -56,146 +77,328 @@ func (k outcomeKeeps) holdsAny() bool { slices.ContainsFunc(k.entries, keptEntry.keeps) } -// keepsAtOutcome returns what the position s is written at keeps, having -// lowered to target: what a refinement keeps unread and the entries it left, or -// what any other outcome lowering to a reference keeps unread -// (referenceOutcomeKeywords). +// keepsAtOutcome returns what the position schema is written at keeps, having +// lowered to target: what a refinement keeps (refinedKeeps), or what any +// other outcome lowering to a reference keeps unread (referenceOutcomeKeeps). func keepsAtOutcome(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer) outcomeKeeps { refinement, refined := refinementOf(loweringContext, schema, pointer) if !refined { - keywords, shape := referenceOutcomeKeywords(loweringContext, schema, pointer) - outcomeKeepsValue := outcomeKeeps{keywords: keywords, shape: shape} - if shape == collapsedShape { - outcomeKeepsValue.nulls = nullBranchKeeps(loweringContext, schema, schema, pointer) - } - return outcomeKeepsValue + return referenceOutcomeKeeps(loweringContext, schema, target, pointer) + } + return refinedKeeps(loweringContext, schema, refinement, target, pointer) +} + +// refinedKeeps returns what the position schema, written at pointer and +// lowered to target, keeps where refinement decides it. +func refinedKeeps(loweringContext lowering.Ctx, schema *statement.Schema, refinement refinement, target ir.TypeRef, pointer jsontext.Pointer, +) outcomeKeeps { + keeps := outcomeKeeps{comp: refinement.comp, refined: true, principal: refinement.principal, cutBy: refinement.cutBy, + setsApart: refinement.sharesNoMember, setsBesideEmpty: refinement.emptyEnumType != ""} + if decisionOf(loweringContext, schema).outcome == decisionRefinesKeepingAllOfWhole { + keeps.keywords, keeps.allOfWhole = []string{"allOf"}, true + return keeps } - otherOutcomeKeeps := outcomeKeeps{comp: refinement.comp, refined: true, principal: refinement.principal} typed := refinedValueType(loweringContext, refinement, schema, pointer) homes := homesAt(loweringContext, schema, target, pointer) - standing := standsAtPosition(loweringContext, refinement, target, pointer) + keeps.textIntersection, keeps.root = homes.textIntersection, homes.root + principalBuiltPositionNode := inlinePrincipalBuiltPositionNode(loweringContext, refinement, target, pointer) + admissionReader := newAdmissionReader(loweringContext) + position := refinedPosition{loweringContext: loweringContext, admissionReader: &admissionReader, schema: schema, pointer: pointer, + refinement: refinement, homes: homes, typed: typed, flattenedEntries: allOfEntryFoldingOf(loweringContext, schema), principalBuiltPositionNode: principalBuiltPositionNode, + collapsed: collapsedPrincipal(loweringContext, refinement, schema), constChosen: chosenSetKeyword(refinement, schema) == "const"} if refinement.principal != nil { - degraded, validation := keptUnion(loweringContext, refinement, schema) - if standing { - // A union the position writes as its standing principal does is - // one writing, the principal's (refinedUnread). - bs := refinement.principal.schema.Schema - alike := func(key string) bool { return keyWrittenAlike(schema, bs, key) } + degraded, validation := keptUnion(loweringContext, schema) + if principalBuiltPositionNode { + // A union the position writes as the principal building its node + // does is one writing, the principal's (refinedUnread). + principalSchema := refinement.principal.schema.Schema + alike := func(key string) bool { return keyWrittenAlike(schema, principalSchema, key) } degraded, validation = slices.DeleteFunc(degraded, alike), slices.DeleteFunc(validation, alike) } - otherOutcomeKeeps.text, otherOutcomeKeeps.keywords = textBoundsOf(refinedUnread(loweringContext, refinement, schema, typed, homes, standing), homes.numberText) - otherOutcomeKeeps.keywords, otherOutcomeKeeps.validation = append(otherOutcomeKeeps.keywords, degraded...), validation + keeps.text, keeps.keywords = textBoundsOf(refinedUnread(loweringContext, refinement, schema, typed, homes, principalBuiltPositionNode), homes.otherText) + keeps.keywords = append(keeps.keywords, refinement.besideRef.keptContent(schema)...) + keeps.keywords, keeps.validation = append(keeps.keywords, degraded...), validation + } else { + // The keywords beside the allOf decide, and its own unions, which no + // lowering of them reads, are kept as beside a principal. + keeps.keywords, keeps.validation = keptUnion(loweringContext, schema) } - collapsed := collapsedPrincipal(loweringContext, refinement, schema) - if collapsed { - otherOutcomeKeeps.nulls = nullBranchKeeps(loweringContext, schema, refinement.principal.schema.Schema, refinement.principal.pointer) + if position.collapsed { + keeps.nulls = nullBranchKeeps(loweringContext, schema, refinement.principal.schema.Schema, refinement.principal.pointer) } - foldedEntries := allOfEntryFoldingOf(loweringContext, schema) - admissionReader := newAdmissionReader(loweringContext) - pair := writesUnionPair(schema, refinement.comp) - residues := make([][]string, len(refinement.comp.entries)) + unreadKeywordsByEntry, refEntries := entryUnreadKeywords(position) + keeps.refEntries = refEntries + keeps.entries = entryKeeps(loweringContext, schema, refinement.comp, func(i int) []string { return unreadKeywordsByEntry[i] }, position.flattenedEntries, + isAdditionalProperties) + finishEntryKeeps(position, keeps.entries) + return keeps +} + +// entryUnreadKeywords returns, by index, what each inline entry of position's +// refinement writes that is read nowhere it lowered, and the $ref entries it +// keeps whole, each with how it was weighed for the principal. +func entryUnreadKeywords(position refinedPosition) (unreadKeywordsByEntry [][]string, refEntries []keptRefEntry) { + loweringContext, schema, refinement := position.loweringContext, position.schema, position.refinement + loopHop := hopsALoopAlone(loweringContext, schema, refinement.comp) + undecided := undecidedKinds(loweringContext, refinement, schema) + unreadKeywordsByEntry = make([][]string, len(refinement.comp.entries)) for i, entry := range refinement.comp.entries { // A $ref principal keeps what is written beside it on its alias. An // entry written as the principal is says nothing it does not. An inline - // principal standing at the position had its unread keywords kept on + // principal at the position had its unread keywords kept on // the node, which keeps the rest as any conjunct's. - if refinement.principalIs(entry) && entry.schema.Ref != nil || principalTwin(&admissionReader, refinement, entry) { + if refinement.principalIs(entry) && entry.schema.Ref != nil || principalWrittenTwice(position.admissionReader, refinement, entry) { continue } - standsHere := standing && refinement.principalIs(entry) switch { + case conjoinedEntry(loweringContext, schema, entry): + // Each variant of the union conjoins it, as an allOf of the two. + case keepsRef(refinement, entry, loopHop): + refEntries = append(refEntries, keptRefEntry{entry: entry, choiceReason: refinement.refChoiceReasons[i]}) case entry.schema.Ref != nil: - otherOutcomeKeeps.refEntries = append(otherOutcomeKeeps.refEntries, wholeRefEntry{entry: entry, vote: refinement.votes[i]}) + // The empty enum within its target is the one fact: the target says + // its own (emptyEnumBeside). case stated(entry.schema.Schema): - // The principal's node keeps what it passes over (preserveUnusedCombinator). - read := residueRead(loweringContext, &admissionReader, refinement, typed, entry, foldedEntries.entryFoldsIntoPosition[i], standsHere, collapsed && refinement.principalIs(entry), homes, - pair && !refinement.principalIs(entry)) - residues[i] = unmergedEntryKeys(entry.schema.Schema, lessPattern(read, standsHere && patternBeside(schema, entry.schema.Schema, homes))) + unreadKeywordsByEntry[i] = inlineEntryUnreadKeywords(position, entry, i, undecided) + } + } + return unreadKeywordsByEntry, refEntries +} + +// inlineEntryUnreadKeywords returns what entry, the inline allOf entry of +// position at index at, writes that is read nowhere the position lowered +// (unreadKeywordRead), undecided being the kinds the node of an allOf choosing +// no entry is typed by (undecidedKinds). +func inlineEntryUnreadKeywords(position refinedPosition, entry allOfEntry, at int, undecided kindSet) []string { + entrySchema := entry.schema.Schema + entryBuiltPositionNode := position.principalBuiltPositionNode && position.refinement.principalIs(entry) + read := unreadKeywordRead(position, entry, at) + if !entryBuiltPositionNode && (passesOverEnum(entrySchema) || position.constChosen && !position.refinement.principalIs(entry)) { + // The principal's node keeps what it passes over (keepUnusedCombinatorReports). + // An enum a const passes over, the conjunct's own or one chosen + // elsewhere, is kept as the same schema written alone keeps it, + // whatever the value set says. + read = read.without("enum") + } + if undecided != 0 && writesType(entrySchema) && writtenKinds(entrySchema, position.admissionReader.nullable)&^kindNull == undecided { + // A type naming exactly the kinds the node is typed by, null aside, + // says nothing beyond it: the node is what the type names. A type + // naming more is kept. + read = read.also("type") + } + if entryBuiltPositionNode && patternBeside(position.schema, entrySchema, position.homes) { + // One field holds one pattern, the position's, so the principal's is + // an unread keyword where the two disagree (ConstraintsOf). + read = read.without("pattern") + } + return unmergedEntryKeys(entrySchema, read) +} + +// refinedPosition is the position schema, written at pointer, that refinement +// decides, with the readings what it keeps turns on: typed is the value set +// type its principal lowered to (refinedValueType), and constChosen marks a +// const chosen passing an enum over. +type refinedPosition struct { + loweringContext lowering.Ctx + admissionReader *admissionReader + schema *statement.Schema + pointer jsontext.Pointer + refinement refinement + homes boundHomes + typed setType + flattenedEntries allOfEntryFolding + principalBuiltPositionNode, collapsed, constChosen bool +} + +// keepsRef reports whether the refinement refinementValue keeps the $ref +// entry allOfEntryValue writes: every one it does not lower from, but beside +// an empty enum lying within its target, the one fact (emptyEnumBeside), and +// on a loop's hop saying nothing more, loopHop (hopsALoopAlone). +func keepsRef(refinementValue refinement, allOfEntryValue allOfEntry, loopHop bool) bool { + return allOfEntryValue.schema.Ref != nil && refinementValue.emptyEnumType == "" && !loopHop +} + +// hopsALoopAlone reports whether schema, whose flattened conjuncts are comp, +// is a hop of a loop of references saying nothing more, which keeps none of +// them, as a bare $ref on a loop keeps none +// (docs/compilers/openapi.md#reference-cycles). +func hopsALoopAlone(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition) bool { + return holdsNothing(schema, besideOneRef{nullableDeclares: nullableDeclares(loweringContext, schema, nullIdiomConjunction(loweringContext, schema))}) && + !slices.ContainsFunc(comp.entries, func(entry allOfEntry) bool { return !onLoop(entry.schema) }) +} + +// finishEntryKeeps sets on each of entries, what the refinement of position +// keeps of its conjuncts, what it reads of the position rather than of its own +// entry. +func finishEntryKeeps(position refinedPosition, entries []keptEntry) { + homes := position.homes + pair := writesUnionPair(position.schema, position.refinement.comp) + for i := range entries { + entries[i].text, entries[i].root = homes.otherText|homes.heldText, homes.root + entries[i].contentKeptBeside = position.refinement.besideRef.keepsContentOf(entries[i].entry.schema.Schema) + entries[i].unionWhy = entryUnionWhy(position.loweringContext, position.schema, position.refinement, entries[i], pair) + if position.constChosen { + entries[i].passedOverAt = position.pointer } } - otherOutcomeKeeps.entries = entryKeeps(loweringContext, schema, refinement.comp, func(i int) []string { return residues[i] }, foldedEntries, isAdditionalProperties, refinement.principal) - for i := range otherOutcomeKeeps.entries { - otherOutcomeKeeps.entries[i].numberText = homes.numberText - } - return otherOutcomeKeeps -} - -// residueRead reports whether a key the entry e of r writes is read where the -// position lowered, leaving no residue: a wrapper's allOf, what folds where e -// speaks, what the principal says (said) but a union of a pair (pair, -// writesUnionPair), and a key of readDomain the principal standing at the -// position, e where standsHere says so, reads or keeps on its node (keepUnread). -// A value set's union and content vocabulary are kept, as its node holds -// neither; another principal's union is its node's, or the collapsed -// reference's (collapsedPrincipal), and its content vocabulary its own -// reading's (unplacedContent). -func residueRead(loweringContext lowering.Ctx, admissionReaderValue *admissionReader, refinementValue refinement, typed setType, allOfEntryValue allOfEntry, speaks, standsHere, collapsed bool, - homes boundHomes, pair bool, -) func(string) bool { - bs := allOfEntryValue.schema.Schema +} + +// entryUnionWhy says why a union keptEntryValue, an entry of the allOf schema +// writes, keeps is no variant's where the entry is the value set +// refinementValue lowers to, as the same union written beside that set says +// (lowerCoDeclaredUnion); "" where the entry is no such set or a pair's choice +// passes the union over. +func entryUnionWhy(loweringContext lowering.Ctx, schema *statement.Schema, refinementValue refinement, keptEntryValue keptEntry, pair bool) string { + set, isSet := valueSetPrincipal(refinementValue) + switch { + case readLoweredUnion(loweringContext, schema).besideRest == unionLeavesNoBranch: + return foldedUnionWhy(loweringContext, schema, keptEntryValue.entry.schema.Schema) + case pair || !slices.ContainsFunc(keptEntryValue.own, isUnionKeyword), !isSet || set.pointer != keptEntryValue.entry.pointer: + return "" + default: + return "the body is not a model, so it carries no composition to distribute into" + } +} + +// referenceOutcomeKeeps is keepsAtOutcome for a position no allOf refines: +// where it lowers to a reference (referenceOutcome), what its alias or +// carrier, holding the homes homesAt gives it, reads none of +// (unreadByReference), and a collapsed union's null branches. +func referenceOutcomeKeeps(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer) outcomeKeeps { + shape, handled := referenceOutcome(loweringContext, schema, pointer) + outcomeKeepsValue := outcomeKeeps{shape: shape} + if shape != "" { + outcomeKeepsValue.keywords = unreadByReference(schema, homesAt(loweringContext, schema, target, pointer), handled) + } + if shape == collapsedShape { + outcomeKeepsValue.nulls = nullBranchKeeps(loweringContext, schema, schema, pointer) + } + return outcomeKeepsValue +} + +// keywordRead reports whether a keyword an allOf entry writes is read where +// its position lowered, so the entry does not keep it (unmergedEntryKeys). +type keywordRead func(keyword string) bool + +// without returns r reading keyword no more, so the entry keeps it. +func (r keywordRead) without(keyword string) keywordRead { + return func(key string) bool { return key != keyword && r(key) } +} + +// also returns r reading keyword too, so the entry does not keep it. +func (r keywordRead) also(keyword string) keywordRead { + return func(key string) bool { return key == keyword || r(key) } +} + +// unreadKeywordRead returns which keys entry, the allOf entry of position at +// index at, writes are read where the position lowered, so the entry keeps +// none of them. A value set principal's union and content vocabulary are kept; +// another principal's union is its node's, or the collapsed reference's +// (collapsedPrincipal), its content its own (unplacedContent). +func unreadKeywordRead(position refinedPosition, entry allOfEntry, at int) keywordRead { + loweringContext, refinementValue, schema := position.loweringContext, position.refinement, position.schema + entrySchema := entry.schema.Schema + speaks := position.flattenedEntries.folds(loweringContext, entrySchema, at) + entryBuiltPositionNode := position.principalBuiltPositionNode && refinementValue.principalIs(entry) + collapsed := position.collapsed && refinementValue.principalIs(entry) + typeRead := readLoweredUnion(loweringContext, schema).besideRest.readsType() _, set := valueSetPrincipal(refinementValue) return func(key string) bool { switch { - case key == "allOf" && allOfEntryValue.wrapper, speaks && folds(loweringContext, bs, key, homes), collapsed && unionKeyword(key): + case readUnionKeyOutcome(loweringContext, schema, entrySchema, position.homes, key) != unionKeyByRefinement: + return readUnionKeyOutcome(loweringContext, schema, entrySchema, position.homes, key) == unionKeyRead + case key == "allOf" && entry.wrapper, speaks(key) && folds(loweringContext, entrySchema, key, position.homes), collapsed && isUnionKeyword(key): return true - case pair && unionKeyword(key): - // A union of a pair is kept whatever the principal says, as one - // schema writing both keeps the one it passes over. - return false - case standsHere && unionKeyword(key): + case typeRead && key == "type", key == "discriminator" && routesUnion(loweringContext, schema, entrySchema), + listComposesMembers(loweringContext, refinementValue, schema, key): + return true + case isUnionKeyword(key) && (readLoweredUnion(loweringContext, schema).besideRest.addsNothing() || readLoweredUnion(loweringContext, schema).heldWhole()): + // A union the rest's members all satisfy says nothing, and one the + // node holds whole says nothing more, whichever conjunct writes it. + return true + case entryBuiltPositionNode && isUnionKeyword(key): return !set - case standsHere && slices.Contains(contentKeywords, key): + case isUnionKeyword(key) && readLoweredUnion(loweringContext, schema).membersPastBudget() > 0: + // One listing more members than the enum budget admits is refused + // whole, as an enum past it is (lowerFilteredMembersPastBudget). + return true + case isUnionKeyword(key): + // A union the position does not lower from is kept, as the + // union reading decides it (keptUnionReason), whatever the + // principal says. + return false + case entryBuiltPositionNode && slices.Contains(contentKeywords, key): // The principal's own reading keeps what its node holds no // Encoding for (lowerPrincipal), so the entry keeps none again. return !set - case standsHere: - return keyBit(key) != 0 || said(admissionReaderValue, refinementValue, typed, bs, key) + case entryBuiltPositionNode: + return keyBit(key) != 0 || principalRestates(position.admissionReader, refinementValue, position.typed, schema, entrySchema, key) default: - return said(admissionReaderValue, refinementValue, typed, bs, key) + return principalRestates(position.admissionReader, refinementValue, position.typed, schema, entrySchema, key) } } } +// undecidedKinds returns the kinds the node of schema, whose allOf refinement +// chooses no entry, is typed by where its conjuncts type it (undecidedTypes), +// none otherwise. +func undecidedKinds(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema) kindSet { + if refinementValue.principal != nil { + return 0 + } + typingValue := typingOf(loweringContext, schema) + if typingValue.by != byConjuncts { + return 0 + } + var kinds kindSet + for _, typeName := range typingValue.types { + kinds |= kindsOfTypeNameOrAny(typeName) + } + return kinds +} + +// passesOverEnum reports whether schema's own choice lowers its const and +// passes over the enum it writes beside it (recordSkippedFamilies). +func passesOverEnum(schema *statement.Schema) bool { + dispatchValue := dispatchOf(schema) + return dispatchValue.lowered == "const" && slices.Contains(dispatchValue.skipped, "enum") +} + // lowersFrom reports whether allOfEntryValue is an entry the position lowers -// from, principal being its inline principal, nil or a $ref for none: that +// from, principal being the pointer its inline principal is written at: that // principal, or a wrapper it is an entry of at any depth, out of whose allOf it // is flattened. Each is lowered, the principal as the node and a wrapper as the // keywords beside the principal's allOf, so what it keeps that another conjunct -// writes otherwise is held against the node's keys and never keeps it whole -// (wholePrincipal). -func lowersFrom(principal *allOfEntry, allOfEntryValue allOfEntry) bool { - if principal == nil || principal.schema.Ref != nil { - return false - } - if principal.pointer == allOfEntryValue.pointer { - return true - } - return allOfEntryValue.wrapper && strings.HasPrefix(string(principal.pointer), string(allOfEntryValue.pointer)+"/") +// writes otherwise is kept under its entry's key and never keeps it whole +// (annotation.WritesLoweredFrom). +func lowersFrom(principal jsontext.Pointer, allOfEntryValue allOfEntry) bool { + return allOfEntryValue.pointer == principal || allOfEntryValue.wrapper && allOfEntryValue.pointer.Contains(principal) } -// lessPattern returns read, which keys of an inline principal are read, less -// its pattern where residue says the node holds the position's instead, so the -// principal's is residue, and the two disagree (ConstraintsOf). -func lessPattern(read func(string) bool, residue bool) func(string) bool { - if !residue { - return read +// inlinePrincipal returns the pointer principal, the principal a refinement +// chooses, is written at, and whether it is an inline entry, the one kind the +// position lowers from (lowersFrom): nil and a $ref are none. +func inlinePrincipal(principal *allOfEntry) (jsontext.Pointer, bool) { + if principal == nil || principal.schema.Ref != nil { + return "", false } - return func(key string) bool { return key != "pattern" && read(key) } + return principal.pointer, true } // patternBeside reports whether schema writes a pattern beside its allOf -// otherwise than bs, the inline principal whose node, holding what homes says, -// takes a string's bounds: one field holds one pattern, the position's. -func patternBeside(schema, bs *statement.Schema, homes boundHomes) bool { - if !hasKey(schema, "pattern") || !hasKey(bs, "pattern") || !taken(homes.value, "pattern") { +// otherwise than entrySchema, the inline principal whose node, holding what +// homes says, takes a string's bounds: one field holds one pattern, the +// position's. +func patternBeside(schema, entrySchema *statement.Schema, homes boundHomes) bool { + if !hasKey(schema, "pattern") || !hasKey(entrySchema, "pattern") || !taken(homes.value, "pattern") { return false } - return schema.TextKeywords().Pattern != bs.TextKeywords().Pattern + return schema.TextKeywords().Pattern != entrySchema.TextKeywords().Pattern } // writesUnionPair reports whether schema and the inline entries of comp, the // allOf it writes, write a oneOf and an anyOf between them: two unions -// competing keywords elects between +// competing keywords chooses between // (docs/compilers/openapi.md#competing-keywords), of which a refinement folds // neither into its principal as said, as one schema writing both keeps the one // it passes over whatever the other says. @@ -217,43 +420,45 @@ func writesUnionPair(schema *statement.Schema, comp allOfComposition) bool { // collapsedPrincipal reports whether refinementValue's principal is an inline // union that lowered as the nullable reference to its one non-null branch, the // outcome the same union written alone at a position has -// (referenceOutcomeKeywords): the reference says the union, its target the +// (referenceOutcome): the reference says the union, its target the // branch and its Nullable the null branches, of which one saying more is kept -// apart (nullBranchKeeps). A union schema elects over the other of a pair does -// not collapse (pairedPrincipal). +// apart (nullBranchKeeps). A union schema chooses over the other of a pair, +// or one its conjunction leaves null alone or with a dead branch, does not +// collapse (unionCollapses). func collapsedPrincipal(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema) bool { - if refinementValue.principal == nil || refinementValue.principal.schema.Ref != nil || !declaresUnion(refinementValue.principal.schema.Schema) || electsOneOfPair(loweringContext, schema) { + if refinementValue.principal == nil || refinementValue.principal.schema.Ref != nil || !declaresUnion(refinementValue.principal.schema.Schema) || + !unionCollapses(loweringContext, schema, refinementValue.principal.schema.Schema) { return false } - _, shape := referenceOutcomeKeywords(loweringContext, refinementValue.principal.schema.Schema, refinementValue.principal.pointer) + shape, _ := referenceOutcome(loweringContext, refinementValue.principal.schema.Schema, refinementValue.principal.pointer) return shape == collapsedShape } -// unionKeyword reports whether keyword is oneOf or anyOf. -func unionKeyword(keyword string) bool { return keyword == "oneOf" || keyword == "anyOf" } +// isUnionKeyword reports whether keyword is oneOf or anyOf. +func isUnionKeyword(keyword string) bool { return specrules.SlotOf(keyword) == specrules.SlotChoice } // isAdditionalProperties reports whether keyword is additionalProperties: the // closure no use of a conjunct types, which reads the keywords beside it. func isAdditionalProperties(keyword string) bool { return keyword == "additionalProperties" } -// principalTwin reports whether e, an entry of r other than its principal, is -// written as the principal is (sameText): one schema written twice, -// whose first copy the election takes for both. -func principalTwin(admissionReaderValue *admissionReader, refinementValue refinement, allOfEntryValue allOfEntry) bool { - return refinementValue.principal != nil && !refinementValue.principalIs(allOfEntryValue) && sameText(admissionReaderValue.c, refinementValue.principal.schema, allOfEntryValue.schema) +// principalWrittenTwice reports whether allOfEntryValue, an entry other than +// refinementValue's principal, is written as the principal is (sameText): one +// schema written twice, whose first copy the choice takes for both. +func principalWrittenTwice(admissionReaderValue *admissionReader, refinementValue refinement, allOfEntryValue allOfEntry) bool { + return refinementValue.principal != nil && !refinementValue.principalIs(allOfEntryValue) && sameText(admissionReaderValue.loweringContext, refinementValue.principal.schema, allOfEntryValue.schema) } // textBoundsOf splits unhomed, the keywords a position keeps, into the value -// bounds a node carrying a number as text holds none of, where numberText says -// the node carries one, which it keeps as it keeps them written beside its -// own keywords (keepTextBounds), and the rest. A type list's are kept on its -// Union, where the flat spelling keeps them on the variant carrying the text. -func textBoundsOf(unhomed []string, numberText bool) (text, rest []string) { - if !numberText { +// bounds of keys, those a node carrying text of another kind keeps verbatim, +// which it keeps as it keeps them written beside its own keywords +// (keepTextBounds), and the rest. A type list's are kept on its Union, where +// the flat spelling keeps them on the variant carrying the text. +func textBoundsOf(unhomed []string, keys keySet) (text, rest []string) { + if keys == 0 { return nil, unhomed } for _, key := range unhomed { - if slices.Contains(valueConstraintKeywords, key) { + if keys.has(key) { text = append(text, key) } else { rest = append(rest, key) @@ -262,51 +467,81 @@ func textBoundsOf(unhomed []string, numberText bool) (text, rest []string) { return text, rest } -// refinedUnread returns the readDomain keywords s writes beside an allOf that -// lowered to its principal, but for those the principal already says and the -// bounds the node the position lowered to reads, which homes says +// refinedUnread returns the readDomain keywords schema writes beside an allOf +// that lowered to its principal, but for those the principal already says and +// the bounds the node the position lowered to reads, which homes says // (boundHomes.reads), where a $ref site reads no target and keeps them all // (GitHub #1067). typed is the type of the value set the principal lowered to, // if any (refinedValueType): a value set keeps them in its build -// (lowerPrincipalValueSet). Where standing says an inline principal's node -// stands at the position, a keyword s writes as it does is the principal's -// writing, which its node read or keeps. -func refinedUnread(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, typed setType, homes boundHomes, standing bool) []string { +// (lowerPrincipalValueSet). Where principalBuiltPositionNode says an inline +// principal's node is the position's, a keyword schema writes as it does is +// the principal's writing, which its node read or keeps. +func refinedUnread(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, typed setType, homes boundHomes, principalBuiltPositionNode bool) []string { if _, atPosition := valueSetPrincipal(refinementValue); atPosition { return nil } admissionReader := newAdmissionReader(loweringContext) var held keySet for _, key := range nodeKeywords { - if said(&admissionReader, refinementValue, typed, schema, key) { + if unreadKeywords := readUnionKeyOutcome(loweringContext, schema, schema, homes, key); unreadKeywords == unionKeyRead || + unreadKeywords == unionKeyByRefinement && principalRestates(&admissionReader, refinementValue, typed, schema, schema, key) { held |= keyBit(key) } } + if routesUnion(loweringContext, schema, schema) { + held |= keyBit("discriminator") + } + if readLoweredUnion(loweringContext, schema).besideRest == unionLeavesNullAlone { + // The position is null alone, which a type beside the union admits + // or the policy reads it as admitting: it says nothing more. + held |= keySetOf("type", "nullable") + } + for _, key := range []string{"properties", "required"} { + if listComposesMembers(loweringContext, refinementValue, schema, key) { + held |= keyBit(key) + } + } + if principal := refinementValue.principal; principal.schema.Ref == nil && !collapsedPrincipal(loweringContext, refinementValue, schema) { + if homes.format && writesNone(principal.schema.Schema, "format") { + held |= keyBit("format") + } + if homes.elements && writesNone(principal.schema.Schema, itemsGroup...) { + held |= keySetOf(itemsGroup...) + } + } + held |= homes.textKeeps | homes.textIntersection.consumedFrom(schema) unread := unreadKeys(schema, homes.reads(schema)|readElsewhere(schema)|held) - if !standing { + if !principalBuiltPositionNode { return unread } - bs := refinementValue.principal.schema.Schema - return slices.DeleteFunc(unread, func(key string) bool { return keyWrittenAlike(schema, bs, key) }) + principalSchema := refinementValue.principal.schema.Schema + return slices.DeleteFunc(unread, func(key string) bool { return keyWrittenAlike(schema, principalSchema, key) }) } -// keptUnion returns the union keywords schema writes beside an allOf that -// lowered to its principal refinementValue, a keyword beside a refinement, that -// the position keeps: none the principal says (unionHeld) but a union of a pair -// (writesUnionPair), as validation logic those whose branches declare no shape, -// as the same union beside any body is, and every other one degraded -// (docs/compilers/openapi.md#allof-refinement). -func keptUnion(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema) (degraded, validation []string) { +// writesNone reports whether schema writes none of keywords: an inline +// principal writing none of them takes them off the conjuncts beside it +// (formatConjunct, elementConjunct). +func writesNone(schema *statement.Schema, keywords ...string) bool { + return !slices.ContainsFunc(keywords, func(keyword string) bool { return hasKey(schema, keyword) }) +} + +// keptUnion returns the union keywords schema writes beside a refining allOf +// that the position keeps, by the reason the union reading gives each +// (keptUnionReason): none where schema writes the union its conjunction +// chooses, which its union lowering keeps or lowers +// (docs/compilers/openapi.md#union-beside-structure). +func keptUnion(loweringContext lowering.Ctx, schema *statement.Schema) (degraded, validation []string) { if !declaresUnion(schema) { return nil, nil } - shapeless := !unionBranchesDeclareShape(loweringContext, schema) - pair := writesUnionPair(schema, refinementValue.comp) - admissionReader := newAdmissionReader(loweringContext) - for _, key := range []string{"oneOf", "anyOf"} { + if loweredUnionWrittenBy(loweringContext, schema, schema) { + return nil, nil + } + for _, union := range unionKeywords { + key := string(union) switch { - case !hasKey(schema, key) || !pair && unionHeld(&admissionReader, refinementValue, schema, key): - case shapeless: + case !hasKey(schema, key): + case keptUnionReason(loweringContext, schema, conjunctionUnion{holder: schema, keyword: union}) == ir.ReasonValidationOnly: validation = append(validation, key) default: degraded = append(degraded, key) @@ -315,220 +550,353 @@ func keptUnion(loweringContext lowering.Ctx, refinementValue refinement, schema return degraded, validation } -// said reports whether the principal of refinementValue already says what -// schema's keyword key does: what it admits holds it, a union one of whose -// branches it restates (unionHeld), or it is a format the value set it lowered -// to, typed, holds in its ValueType, that format's primitive or a narrower one, -// or a redaction. A type that ValueType holds, its values hold too. -func said(admissionReaderValue *admissionReader, refinementValue refinement, typed setType, schema *statement.Schema, key string) bool { - if admissionReaderValue.holds(refinementValue.held, schema, key) || unionHeld(admissionReaderValue, refinementValue, schema, key) || key == "type" && nullIdiom(admissionReaderValue.c, schema) { +// principalRestates reports whether the principal of refinementValue already +// says what schema's keyword key, written in position's conjunction, does, so +// the keyword is not kept. Sets sharing no member or intersecting, and a set +// beside a principal admitting no value, are kept as written; a union is the +// union reading's to keep (docs/compilers/openapi.md#allof-refinement). +func principalRestates(admissionReaderValue *admissionReader, refinementValue refinement, typed setType, position, schema *statement.Schema, key string) bool { + if refinementValue.besideRef.consumes(schema, key) { return true } - return typed.ok && key == "format" && (annotation.DeclaresRedaction(schema) || valueTypeHoldsFormat(typed.primitive, schema)) -} - -// unionHeld reports whether every value refinementValue holds satisfies -// schema's oneOf or anyOf, the keyword key names: a branch says nothing -// refinementValue's principal does not (admissionReader.restates), and for a -// oneOf one alone, sharing no kind with any other, so that exactly one admits -// each of its values. A branch is compared keyword by keyword, as what it -// admits leaves its bounds and annotations unread, and one writing what no -// reading compares says more. A read cut short says no. -func unionHeld(admissionReaderValue *admissionReader, refinementValue refinement, schema *statement.Schema, key string) bool { - var branches []statement.Subschema - switch key { - case "oneOf": - branches = schema.ChoiceKeywords().OneOf - case "anyOf": - branches = schema.ChoiceKeywords().AnyOf - default: + if (refinementValue.sharesNoMember || refinementValue.setsIntersect || !refinementValue.loweredAdmits.reachable()) && (key == "enum" || key == "const") { + // Sets sharing no member are each kept, though an empty one, within + // every set, says them all. return false } - principal := admissionReaderValue.c.Statements().Read(nil) - if refinementValue.principal != nil { - principal = refinementValue.principal.schema + if key == "nullable" { + loweredAdmits := refinementValue.loweredAdmits + return !loweredAdmits.fixed && loweredAdmits.kinds == kindNull && nullableRead(admissionReaderValue.loweringContext, schema) } - within, overlaps := 0, 0 - for _, b := range branches { - branch := admissionReaderValue.c.Statements().Subschema(b) - switch { - case admissionReaderValue.restates(refinementValue.held, principal, branch): - within++ - case refinementValue.held.kinds&lowered(admissionReaderValue, branch).kinds != 0: - overlaps++ + if admissionReaderValue.holds(refinementValue.loweredAdmits, schema, key) || declaresTheIdiomsNull(admissionReaderValue.loweringContext, position, schema, key) { + return true + } + if restatedByReferent(admissionReaderValue.loweringContext, refinementValue, schema, key) || restatesReferentKinds(admissionReaderValue.loweringContext, refinementValue, schema, key) { + return true + } + primitive, typesSet := typed.valueType() + if !typesSet || key != "format" { + return false + } + if paired, ok := typelessFormatPrimitive(schema, func(ir.PrimitiveKind) bool { return true }); ok && narrowsOrIs(primitive, paired) { + return true + } + return annotation.DeclaresRedaction(schema) || valueTypeHoldsFormat(primitive, schema) +} + +// declaresTheIdiomsNull reports whether key, a value keyword schema writes in +// the conjunction of position, says the null the nullable-inference policy +// widens position's one reference by (nullIdiomConsumes), which the reference +// holds. +func declaresTheIdiomsNull(loweringContext lowering.Ctx, position, schema *statement.Schema, key string) bool { + return (key == "type" || key == "enum" || key == "const") && nullIdiomConsumes(loweringContext, position, schema) +} + +// restatedByReferent reports whether key, a keyword schema writes as a mapping +// on an entry beside the $ref principal of refinementValue, restates the +// referent's same keyword, its own $ref there resolved once, so the two +// validate alike (restates, docs/compilers/openapi.md#allof-refinement). The +// two are compared as two copies are (sameMeaning.text). +func restatedByReferent(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, key string) bool { + principal := refinementValue.principal + if key == "properties" && principal != nil && principal.schema.Ref != nil { + // A key of properties names a property, no keyword. + return restatesReferentProperties(loweringContext, principal.schema, schema) + } + written := nodeview.Deref(keyNode(schema, key)) + writtenAt, placed := siteOf(schema) + if principal == nil || principal.schema.Ref == nil || written == nil || written.Kind != yaml.MappingNode || !placed { + return false + } + referent, at := declaredOf(loweringContext, principal.schema) + if referent == nil || referent.Truth != statement.Stated || !hasKey(referent.Schema, key) { + return false + } + target := loweringContext.Statements().At(reftable.DocumentPointer{Doc: at.Doc, Pointer: at.Pointer + ids.Ptr(key)}) + if target.Ref != nil && len(target.Keys) == 1 { + if target, _ = declaredOf(loweringContext, target); target == nil { + return false } } - if admissionReaderValue.incomplete() || within == 0 { + targetAt, targetPlaced := siteOf(target.Schema) + keywordAt := reftable.DocumentPointer{Doc: writtenAt.Doc, Pointer: writtenAt.Pointer + ids.Ptr(key)} + writtenSchema := loweringContext.Statements().At(keywordAt).Schema + if target.Truth != statement.Stated || !targetPlaced || !restates(nodeview.New().MappingPairs(written), writtenSchema, target.Schema) { + return false + } + text, err := annotation.RawFromNode(written) + return err == nil && newSameMeaning(loweringContext, noneLowered()).text(keywordAt, targetAt, text) +} + +// restatesReferentProperties reports whether the properties schema writes, on +// an allOf entry or beside it, restate those of the schema ref lands on, so +// they say nothing beside it: each names one of the referent's properties, +// written alike as two copies are (sameText), notes included +// (docs/compilers/openapi.md#allof-refinement). +func restatesReferentProperties(loweringContext lowering.Ctx, ref *statement.Statement, schema *statement.Schema) bool { + written := schema.ObjectKeywords().Properties + if len(written) == 0 { + return false + } + referent, _ := declaredOf(loweringContext, ref) + if referent == nil || referent.Truth != statement.Stated || referent.Schema == schema { + // A schema naming itself restates nothing beside it. return false } - return key == "anyOf" || (within == 1 && overlaps == 0) + held := referent.ObjectKeywords().Properties + byName := make(map[string]statement.Subschema, len(held)) + for _, sub := range held { + byName[sub.Name] = sub + } + statements := loweringContext.Statements() + return !slices.ContainsFunc(written, func(sub statement.Subschema) bool { + other, named := byName[sub.Name] + return !named || !sameText(loweringContext, statements.Subschema(sub), statements.Subschema(other)) + }) +} + +// restatesReferentKinds reports whether key is a type schema writes naming +// exactly the kinds the referent of refinementValue's $ref principal declares +// (typeNamesOnly), which narrows nothing that reference admits, however far +// its read went. +func restatesReferentKinds(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, key string) bool { + principal := refinementValue.principal + if key != "type" || principal == nil || principal.schema.Ref == nil { + return false + } + return typeNamesOnly(schema, declaredKinds(loweringContext, principal.schema)) +} + +// restates reports whether pairs, what a keyword's mapping writes as the +// schema written, say what target does: target writes each alike, and each +// other key it writes says nothing (keySaysNothing). A key either writes as +// the keyword left out says nothing, so it is no pair and no other key. +func restates(pairs []nodeview.Pair, written, target *statement.Schema) bool { + seen := make(map[string]bool, len(pairs)) + for _, pair := range pairs { + if annotation.WritesKeywordLeftOut(written, pair.Key) { + continue + } + seen[pair.Key] = true + raw, err := annotation.RawFromNode(pair.Val) + held, heldErr := annotation.RawFromNode(keyNode(target, pair.Key)) + if err != nil || heldErr != nil || !hasKey(target, pair.Key) || !bytes.Equal(raw, held) { + return false + } + } + return !slices.ContainsFunc(target.Keys, func(key statement.Key) bool { + return !seen[key.Name] && !keySaysNothing(target, key) + }) } -// record keeps k on unmodeled and reports it, standing being the node the -// position owns, nil where it owns none (refinedShape), and held what the -// readers of an inline principal standing there keep after it, which it answers -// where it keeps that principal whole (wholePrincipal). A branch the IR cannot -// hold is reported by the keeper, and nothing here claims it was kept. -func (k outcomeKeeps) record(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, - standing ir.TypeDef, held *principalKept, +// noteKeywords are the keywords a schema writes to document its instance, +// which no validation reads. +var noteKeywords = []string{"title", "description", "example", "examples", "deprecated", "externalDocs", "$comment"} + +// record adds to pendingKeeps what k keeps, positionNode being the node the +// position owns, nil where it owns none (refinedShape), named how the builder +// of an inline principal building positionNode names it, and carried how the +// carrier holding the position keeps what it has no field for, nil at a node. A +// branch the IR cannot hold is reported by the keeper, and nothing here claims +// it was kept. +func (k outcomeKeeps) record(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, pointer jsontext.Pointer, + positionNode ir.TypeDef, named string, carried CarrierKeywordKeeps, ) []ir.Diagnostic { shape := k.shape if k.refined { - shape = refinedShape(loweringContext, schema, k.comp, k.principal, standing, held) + shape = refinedShape(loweringContext, schema, k.comp, k.principal, positionNode, named) } - keywords, tagged := k.besideTag(standing) - diags := recordUnread(loweringContext, ts, unmodeled, schema, keywords, shape, pointer) - diags = append(diags, keepTagBeside(loweringContext, ts, unmodeled, schema, tagged, pointer)...) - diags = append(diags, keepTextBounds(loweringContext, unmodeled, schema, k.text, pointer)...) - for _, key := range k.validation { - diags = append(diags, preserveValidationOnlyKeyword(loweringContext, unmodeled, schema, key, pointer)...) + diags := k.addPositionPendingKeeps(loweringContext, pendingKeeps, schema, pointer, positionNode, shape) + diags = append(diags, k.reportCapped(loweringContext)...) + report := func(keptEntryValue keptEntry) ir.Diagnostic { + return loweringContext.DiagAt(ir.SeverityInfo, wholeCode(keptEntryValue), keptEntryValue.entry.pointer, "%s", + keptEntryWhy(k.comp, keptEntryValue, shape == undecidedShape, shape)) } - diags = append(diags, recordNullBranches(loweringContext, unmodeled, k.nulls)...) - kept, keptDiags := keepRefConjuncts(loweringContext, unmodeled, k.refEntries, pointer) - diags = append(diags, keptDiags...) - for _, b := range k.refEntries { - if kept[b.entry.pointer] { - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, b.entry.pointer, "%s", keptWhy(k.comp, b))) + var entries annotation.PendingKeeps + principal, inline := inlinePrincipal(k.principal) + for _, keptEntryValue := range k.entries { + keptEntryValue.carried, keptEntryValue.setsApart = carried, k.setsApart || k.setsBesideEmpty + role := annotation.WritesBeside + if inline && lowersFrom(principal, keptEntryValue.entry) { + role = annotation.WritesLoweredFrom } + diags = append(diags, addKeptEntryPendingKeeps(loweringContext, &entries, k.comp, keptEntryValue, role, shape, false, report)...) } - report := func(keptEntryValue keptEntry) ir.Diagnostic { - return loweringContext.DiagAt(ir.SeverityInfo, wholeCode(keptEntryValue), keptEntryValue.entry.pointer, "%s", keptEntryWhy(k.comp, keptEntryValue, k.principal == nil, shape)) - } - // The entries the position lowers from are settled first, outermost - // first, each held against what those around it keep; their reports stand - // where the entries do. - lowered := k.lowered() - settled := make([][]ir.Diagnostic, len(lowered)) - whole := false - for j, i := range lowered { - keptEntry, heldDiags := wholePrincipal(loweringContext, ts, unmodeled, schema, k, k.entries[i], held, whole) - whole = whole || keptEntry.keptWhole() - settled[j] = append(heldDiags, recordKeptEntry(loweringContext, ts, unmodeled, k.comp, keptEntry, shape, false, report)...) - } - for i, keptEntry := range k.entries { - if j := slices.Index(lowered, i); j >= 0 { - diags = append(diags, settled[j]...) - continue - } - diags = append(diags, recordKeptEntry(loweringContext, ts, unmodeled, k.comp, keptEntry, shape, false, report)...) + if k.cutBy != "" { + entries.DropReports(k.isCutConjunctReport(pointer)) } - dropFoldedIntoWhole(loweringContext, unmodeled) - return diags + k.keepPastWholePrincipal(loweringContext, &entries, schema, pointer, report) + addWritingPendingKeeps(loweringContext, &entries, schema, k.comp, k.entries, k.principal, k.textIntersection, slices.Concat(pendingKeeps.Keywords(), entries.Keywords())...) + pendingKeeps.AddAll(entries) + return k.reportCutRead(loweringContext, diags, pointer, keptBeside(pendingKeeps, positionNode, pointer)) } -// lowered returns the indices of k's entries the position lowers from -// (lowersFrom), the outermost first: a wrapper before what its allOf holds. -func (k outcomeKeeps) lowered() []int { - var out []int - for i, keptEntry := range k.entries { - if lowersFrom(k.principal, keptEntry.entry) { - out = append(out, i) +// keepPastWholePrincipal adds, where the inline principal's entry is kept +// whole, a pending keep of each writing of a bound whose conjuncts intersect +// in a value none of them writes (textBoundIntersection.values): that value is +// held whole with the principal, so each writing it replaced is kept as +// written, at the position or under its entry. +func (k outcomeKeeps) keepPastWholePrincipal(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, + pointer jsontext.Pointer, report func(keptEntry) ir.Diagnostic, +) { + whole := k.principal != nil && slices.ContainsFunc(k.entries, func(keptEntryValue keptEntry) bool { + return keptEntryValue.entry.pointer == k.principal.pointer && keptEntryValue.keptWhole() + }) + if !whole { + return + } + principal, inline := inlinePrincipal(k.principal) + for _, keyword := range slices.Sorted(maps.Keys(k.textIntersection.values)) { + for _, conjunctSchema := range k.textIntersection.consumed[keyword] { + if conjunctSchema == schema { + addPendingKeeping(loweringContext, pendingKeeps, positionSite(k.comp.pointer), schema, textBounds(loweringContext, schema, []string{keyword}, pointer, k.root)) + continue + } + at := slices.IndexFunc(k.comp.entries, func(allOfEntryValue allOfEntry) bool { + return allOfEntryValue.schema.Schema == conjunctSchema && (!inline || !lowersFrom(principal, allOfEntryValue)) + }) + if at < 0 { + continue + } + entry := k.comp.entries[at] + site := entrySiteAt(k.comp, entry.pointer, annotation.WritesBeside) + kept := keptEntry{entry: entry, unreadKeywords: []string{keyword}, own: []string{keyword}, text: keyBit(keyword), root: k.root} + pendingKeeps.AddEntry(keptEntrySite(loweringContext, k.comp, kept, site, report)) + addPendingKeeping(loweringContext, pendingKeeps, site, conjunctSchema, textBounds(loweringContext, conjunctSchema, []string{keyword}, entry.pointer, k.root)) } } - slices.SortStableFunc(out, func(a, b int) int { - return cmp.Compare(len(k.entries[a].entry.pointer), len(k.entries[b].entry.pointer)) - }) - return out } -// wholePrincipal settles keptEntryValue, what the position schema keeps of an -// entry it lowers from (lowersFrom), with held, what its principal's readers -// keep after the position (principalKept). Kept whole, the entry holds the -// principal and what they said: its report names that too, its reason reads it -// and what the build kept, and held is told, so they keep none; inside says a -// wrapper around keptEntryValue is, which holds keptEntryValue. An entry no -// JSON holds is not kept whole: what it keeps is placed keyword by keyword, as -// keptEntry.apart is, under its own key where unmodeled holds none, else the -// entry's. -func wholePrincipal(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, schema *statement.Schema, outcomeKeepsValue outcomeKeeps, keptEntryValue keptEntry, - held *principalKept, inside bool, -) (keptEntry, []ir.Diagnostic) { - if inside { - return keptEntry{entry: keptEntryValue.entry}, nil - } - if keptEntryValue.keptWhole() { - if _, err := annotation.RawFromNode(keptEntryValue.entry.schema.Node); err != nil { - // The keeper of the keyword no JSON holds refuses it, where written. - keptEntryValue.whole, keptEntryValue.apart = keptApart, keptOf(loweringContext, keptEntryValue) +// keptBeside returns the keywords written beside the allOf at pointer that the +// position keeps, each under its own key, sorted: those pendingKeeps hold of +// its writing and those positionNode, the node it owns, nil where it owns none, +// holds already. +func keptBeside(pendingKeeps *annotation.PendingKeeps, positionNode ir.TypeDef, pointer jsontext.Pointer) []string { + out := pendingKeeps.KeptUnderOwnKeyAt(pointer) + if positionNode != nil { + for key, entry := range positionNode.Common().Unmodeled { + if keyword, kept := annotation.EntryKeyword(key); kept && entry.Provenance.Pointer == pointer+ids.Ptr(keyword) && !slices.Contains(out, keyword) { + out = append(out, keyword) + } } } - if keptEntryValue.keptWhole() { - if held == nil { - // No reader of the principal keeps a keyword after the position. - return keptEntryValue, nil - } - held.whole = true - for _, key := range held.keys { - if !slices.Contains(keptEntryValue.residue, key) { - keptEntryValue.residue = append(slices.Clip(keptEntryValue.residue), key) + slices.Sort(out) + return out +} + +// addPositionPendingKeeps adds as pending keeps what the position schema, +// written at pointer, keeps of its own beside shape, what it lowered to, and +// reports each $ref conjunct it leaves unlowered where written. +func (k outcomeKeeps) addPositionPendingKeeps(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, + pointer jsontext.Pointer, positionNode ir.TypeDef, shape string, +) []ir.Diagnostic { + position := positionSite(pointer) + keywords, tagged := k.besideTag(positionNode) + keepings := []keeping{ + {keys: keywords, reason: ir.ReasonDegradedLowering, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return recordUnread(loweringContext, unmodeled, schema, keys, shape, pointer) + }}, + {keys: tagged, reason: ir.ReasonDegradedLowering, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return keepTagBeside(loweringContext, unmodeled, schema, keys, pointer) + }}, + {keys: k.text, reason: ir.ReasonNoIRHome, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return keepTextBounds(loweringContext, unmodeled, schema, keys, pointer, k.root) + }}, + {keys: k.validation, reason: ir.ReasonValidationOnly, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + diags := make([]ir.Diagnostic, 0, len(keys)) + for _, key := range keys { + diags = append(diags, keepValidationOnlyKeyword(loweringContext, unmodeled, schema, key, pointer)...) } + return diags + }}, + } + for _, keepingValue := range keepings { + addPendingKeeping(loweringContext, pendingKeeps, position, schema, keepingValue) + } + kept, reports := nullBranchesKept(loweringContext, k.nulls) + // A $ref kept writes only its text, which every JSON holds: what keeping it + // reports is of no entry it keeps. + refKept, refDiags := keepRefConjuncts(loweringContext, &kept, k.refEntries, pointer) + reports = append(reports, annotation.ReportsOf("", refDiags...)...) + diags := addPendingKeepsKeptAs(loweringContext, pendingKeeps, position, kept, reports, annotation.KeptByReader, nil, false) + alone := usesOneRef(loweringContext, schema, k.comp) + for _, refEntry := range k.refEntries { + // A $ref naming nothing is reported where the reference is resolved, + // and one a cut read kept once at the position (reportCutRead). + if refKept[refEntry.entry.pointer] && refEntry.choiceReason != refNamesNothing && refEntry.choiceReason != refCut && refEntry.choiceReason != refApart && !k.setsApart { + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, refEntry.entry.pointer, "%s", + keptWhy(loweringContext, schema, k.comp, refEntry, alone))) } - if len(held.keys) > 0 { - keptEntryValue.reason = sharedOf(keptEntryValue.reason, held.reason) - } - if held.built != "" { - keptEntryValue.reason = sharedOf(keptEntryValue.reason, held.built) - } - return keptEntryValue, nil - } - if len(keptEntryValue.apart) == 0 { - return keptEntryValue, nil - } - // The principal's readers add to its entry's object after the position; a - // wrapper's holds what the wrapper alone keeps, held against what the - // position writes even where the principal keeps it after (besideHeld). - into, view := &principalKept{}, besideHeld(*unmodeled, schema, keptEntryValue.apart) - if keptEntryValue.entry.pointer == outcomeKeepsValue.principal.pointer { - held = held.saying(keeping{}) - into, view = held, *unmodeled - } - bs := keptEntryValue.entry.schema.Schema - plain, apart := heldAgainst(view, outcomeKeepsValue.comp, bs, keptEntryValue.entry.pointer, keptEntryValue.apart) - own := slices.Concat(keptEntryValue.own, plain) - keptEntryValue.own = slices.DeleteFunc(slices.Clone(keptEntryValue.residue), func(key string) bool { return !slices.Contains(own, key) }) - i := slices.IndexFunc(outcomeKeepsValue.comp.entries, func(b allOfEntry) bool { return b.pointer == keptEntryValue.entry.pointer }) - return keptEntryValue, keepApart(loweringContext, ts, outcomeKeepsValue.comp, into, unmodeled, bs, keptEntryValue.entry.pointer, apart, apartReason(loweringContext, schema, outcomeKeepsValue.comp, i, keptEntryValue, apart)) -} - -// apartReason is the reason the keywords apart, kept under the entry's key of -// keptEntryValue, the inline entry at index i of comp, share, else -// degraded_lowering: each as it is kept on its own (keywordReason), and a value -// bound where the position's node carries a number as text no_ir_home, as -// recordOwnKeywords keeps one (keepTextBounds). -func apartReason(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, i int, keptEntryValue keptEntry, apart []string) ir.UnmodeledReason { - var shared ir.UnmodeledReason - for n, key := range apart { - reason := keywordReason(loweringContext, schema, comp, i, key) - if keptEntryValue.numberText && slices.Contains(valueConstraintKeywords, key) { - reason = ir.ReasonNoIRHome - } - if n > 0 { - reason = sharedOf(shared, reason) + } + return diags +} + +// reportCutRead reports the conjuncts a refinement whose read a bound cut +// keeps, diags their reports where written, as one info at pointer naming the +// bound and beside, the keywords kept beside the allOf: each is kept because +// the bound stopped their comparison, which is one fact of the position +// (docs/compilers/openapi.md#allof-refinement). +func (k outcomeKeeps) reportCutRead(loweringContext lowering.Ctx, diags []ir.Diagnostic, pointer jsontext.Pointer, beside []string) []ir.Diagnostic { + if k.cutBy == "" { + return diags + } + diags = slices.DeleteFunc(diags, k.isCutConjunctReport(pointer)) + message := "the reading of this allOf's conjuncts passed " + k.cutBy + ", so none is the one it lowers from: it lowered to " + + "what their kinds name, and each conjunct saying more is kept verbatim under Unmodeled" + if len(beside) > 0 { + message += ", " + strings.Join(beside, ", ") + " declared beside it among them" + } + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, "%s", message)) +} + +// isCutConjunctReport reports whether a report is one of what a conjunct of the +// refinement written at pointer keeps, which reportCutRead's one report is +// drawn for. +func (k outcomeKeeps) isCutConjunctReport(pointer jsontext.Pointer) func(ir.Diagnostic) bool { + entries := string(pointer) + "/allOf/" + return func(diagnostic ir.Diagnostic) bool { + return diagnostic.Severity == ir.SeverityInfo && diagnostic.Code == diag.DegradedConstruct && strings.HasPrefix(string(diagnostic.Provenance.Pointer), entries) + } +} + +// reportCapped reports each entry of an allOf k keeps whole that nests past +// the flattening depth, where written, as a composition reports it +// (unmergedWhy), naming what else it writes, which the allOf kept holds. +func (k outcomeKeeps) reportCapped(loweringContext lowering.Ctx) []ir.Diagnostic { + if !k.allOfWhole { + return nil + } + var diags []ir.Diagnostic + for _, entry := range k.comp.entries { + if entry.capped { + written := unmergedEntryKeys(entry.schema.Schema, func(string) bool { return false }) + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, entry.pointer, "%s", unmergedWhy(written, entry))) } - shared = reason } - return shared + return diags } -// besideTag splits k's unread keywords where standing, the node the position -// owns, is the Union its inline principal built holding that principal's -// discriminator: the position's own discriminator is kept beside one the node -// holds, never for want of a home, so it is reported apart (keepTagBeside). -func (k outcomeKeeps) besideTag(standing ir.TypeDef) (keywords, tagged []string) { - union, ok := standing.(*ir.Union) +// besideTag splits k's unread keywords where positionNode, the node the +// position owns, is the Union its inline principal built holding that +// principal's discriminator: the position's own discriminator is kept beside +// one the node holds, never for want of a home, so it is reported apart +// (keepTagBeside). +func (k outcomeKeeps) besideTag(positionNode ir.TypeDef) (keywords, tagged []string) { + union, ok := positionNode.(*ir.Union) if !ok || union.Discriminator == nil || !slices.Contains(k.keywords, "discriminator") { return k.keywords, nil } return slices.DeleteFunc(slices.Clone(k.keywords), func(key string) bool { return key == "discriminator" }), []string{"discriminator"} } -// keepTagBeside keeps on p the discriminator s, written at pointer, writes -// beside an allOf whose inline principal's Union holds its own, tagged naming -// it or nothing: verbatim, its routes resolved, as keepUnreadKeys keeps one, with -// a report saying whose discriminator the Union holds. -func keepTagBeside(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, schema *statement.Schema, tagged []string, pointer jsontext.Pointer, +// keepTagBeside keeps on unmodeled the discriminator schema, written at +// pointer, writes beside an allOf whose inline principal's Union holds its +// own, tagged naming it or nothing: verbatim, its routes resolved, as +// keepUnreadKeys keeps one, with a report saying whose discriminator the Union +// holds. +func keepTagBeside(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, tagged []string, pointer jsontext.Pointer, ) []ir.Diagnostic { - kept, diags := keepUnreadKeys(loweringContext, ts, unmodeled, schema, tagged, pointer) + kept, diags := keepUnreadKeys(loweringContext, unmodeled, schema, tagged, pointer) if len(kept) == 0 { return diags } @@ -544,32 +912,42 @@ type keptRef struct { at jsontext.Pointer } -// keptRefKeys returns, by its pointer, the key each $ref of refEntries is kept -// under: openapi:$ref where one is kept, else openapi:$ref/, i its rank by -// reference text, then by the entry as written, so no order of the entries -// decides (docs/compilers/openapi.md#allof-refinement). Entries written alike -// are one entry, at pointer, the position writing them. -func keptRefKeys(refEntries []wholeRefEntry, pointer jsontext.Pointer) map[jsontext.Pointer]keptRef { - alike := map[[2]string][]jsontext.Pointer{} - for _, b := range refEntries { - raw, err := annotation.RawFromNode(b.entry.schema.Node) - if err != nil { +// keptRefKeys returns, by its pointer, the key each reference of refEntries is +// kept under, named by the keyword it is written with (refKey): openapi:$ref +// where one $ref is kept, else openapi:$ref/, i its rank among those of its +// keyword by reference text, then by the entry as written, so no order of the +// entries decides (docs/compilers/openapi.md#allof-refinement). texts holds +// each entry's text as written, the keywords beside its reference among them +// (entryText), nil where it cannot render; entries written alike are one +// entry, at pointer, the position writing them. +func keptRefKeys(refEntries []keptRefEntry, texts []ir.RawValue, pointer jsontext.Pointer) map[jsontext.Pointer]keptRef { + alike := map[[3]string][]jsontext.Pointer{} + for i, refEntry := range refEntries { + raw := texts[i] + if raw == nil { // An entry that cannot render is alike to no other: its pointer, // which no JSON text spells, ranks it. - raw = ir.RawValue(b.entry.pointer) + raw = ir.RawValue(refEntry.entry.pointer) } - _, text := refSpelling(b.entry.schema) - alike[[2]string{text, string(raw)}] = append(alike[[2]string{text, string(raw)}], b.entry.pointer) + keyword, text := refSpelling(refEntry.entry.schema) + spelt := [3]string{keyword, text, string(raw)} + alike[spelt] = append(alike[spelt], refEntry.entry.pointer) } - written := slices.SortedFunc(maps.Keys(alike), func(a, b [2]string) int { - return cmp.Or(strings.Compare(a[0], b[0]), strings.Compare(a[1], b[1])) + written := slices.SortedFunc(maps.Keys(alike), func(a, b [3]string) int { + return cmp.Or(strings.Compare(a[0], b[0]), strings.Compare(a[1], b[1]), strings.Compare(a[2], b[2])) }) + ofKeyword := map[string]int{} + for _, w := range written { + ofKeyword[w[0]]++ + } out := make(map[jsontext.Pointer]keptRef, len(refEntries)) - for i, w := range written { - key := "openapi:$ref" - if len(written) > 1 { - key += "/" + strconv.Itoa(i) + rank := map[string]int{} + for _, w := range written { + key := refKey(w[0]) + if ofKeyword[w[0]] > 1 { + key += "/" + strconv.Itoa(rank[w[0]]) } + rank[w[0]]++ for _, at := range alike[w] { out[at] = keptRef{key: key, at: at} if len(alike[w]) > 1 { @@ -580,8 +958,16 @@ func keptRefKeys(refEntries []wholeRefEntry, pointer jsontext.Pointer) map[jsont return out } +// refKey is the Unmodeled key a reference written with keyword is kept under, +// a $dynamicRef resolving as the $ref it spells or naming nothing among them: +// verbatim, so under the keyword written, not under openapi:$ref, which +// annotation.KeptReferenceKey reads back. +func refKey(keyword string) string { + return annotation.EntryKey("", keyword) +} + // keptEntryWhy words why a refinement keeps an entry whole, undecided -// saying it elected no entry, naming the schema writing its conjuncts as comp's +// saying it chose no entry, naming the schema writing its conjuncts as comp's // subject does and what it lowered to as shape (refinedShape). func keptEntryWhy(comp allOfComposition, keptEntryValue keptEntry, undecided bool, shape string) string { if why := wholeWhy(keptEntryValue); why != "" { @@ -592,44 +978,55 @@ func keptEntryWhy(comp allOfComposition, keptEntryValue keptEntry, undecided boo return "no conjunct of " + of + " is the one it lowers from, so it lowered by the keywords beside them, " + "where those name no kind by the primitive kinds its entries admit together, else to the top type, and " + "nothing there homes what " + names.this + " adds; " + names.kept + " (" + - strings.Join(keptEntryValue.residue, ", ") + ") is kept verbatim under Unmodeled" + strings.Join(keptEntryValue.unreadKeywords, ", ") + ") is kept verbatim under Unmodeled" } return of + " lowered to " + shape + ", which has no home for what " + names.this + " " + - "adds; " + names.kept + " (" + strings.Join(keptEntryValue.residue, ", ") + ") is kept verbatim under Unmodeled" + "adds; " + names.kept + " (" + strings.Join(keptEntryValue.unreadKeywords, ", ") + ") is kept verbatim under Unmodeled" } -// keepRefConjuncts keeps on p each $ref conjunct of refEntries, one a +// keepRefConjuncts keeps on unmodeled each $ref conjunct of refEntries, one a // refinement, a composition or a failed read leaves unlowered: the reference // as written, its text alone, under the key keptRefKeys ranks it by, at the // entry writing it. What an entry writes beside its $ref is kept apart, as an // inline entry's keywords are. It reports which it kept, by pointer. -func keepRefConjuncts(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, refEntries []wholeRefEntry, pointer jsontext.Pointer, +func keepRefConjuncts(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, refEntries []keptRefEntry, pointer jsontext.Pointer, ) (map[jsontext.Pointer]bool, []ir.Diagnostic) { var keys map[jsontext.Pointer]keptRef if len(refEntries) == 1 { - // One kept $ref is openapi:$ref at its entry, as keptRefKeys ranks it. - keys = map[jsontext.Pointer]keptRef{refEntries[0].entry.pointer: {key: "openapi:$ref", at: refEntries[0].entry.pointer}} + // One kept reference is keyed by its keyword at its entry, as + // keptRefKeys ranks it. + keyword, _ := refSpelling(refEntries[0].entry.schema) + keys = map[jsontext.Pointer]keptRef{refEntries[0].entry.pointer: {key: refKey(keyword), at: refEntries[0].entry.pointer}} } else { - keys = keptRefKeys(refEntries, pointer) + texts := make([]ir.RawValue, len(refEntries)) + for i, refEntry := range refEntries { + texts[i] = entryText(loweringContext, refEntry.entry.schema) + } + keys = keptRefKeys(refEntries, texts, pointer) } kept := make(map[jsontext.Pointer]bool, len(refEntries)) var diags []ir.Diagnostic - for _, b := range refEntries { - _, text := refSpelling(b.entry.schema) - ref := keys[b.entry.pointer] - ok, keptDiags := preserveNode(loweringContext, unmodeled, ref.key, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: text}, + for _, refEntry := range refEntries { + _, text := refSpelling(refEntry.entry.schema) + ref := keys[refEntry.entry.pointer] + ok, keptDiags := keepNode(loweringContext, unmodeled, ref.key, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: text}, ir.ReasonDegradedLowering, ref.at) diags = append(diags, keptDiags...) - kept[b.entry.pointer] = ok + kept[refEntry.entry.pointer] = ok } return kept, diags } -// keptWhy words why a refinement keeps a $ref entry, naming the schema -// writing its conjuncts as comp's subject does. -func keptWhy(comp allOfComposition, b wholeRefEntry) string { +// keptWhy words why a refinement keeps a $ref entry, naming schema, which +// writes its conjuncts, as comp's subject does; alone marks a use of that one +// $ref saying nothing more (usesOneRef). +func keptWhy(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, refEntry keptRefEntry, alone bool) string { of := comp.subject() - switch b.vote { + if refEntry.choiceReason == refAround && alone { + return "this $ref leads round a loop of references back to " + of + ", which admits every kind there, and " + + "nothing beside it says more, so the position is the top type; the $ref is kept verbatim under Unmodeled" + } + switch refEntry.choiceReason { case refInferredApart: return "the kind-inference policy reads this $ref's target as kinds leaving out one the rest of " + of + " admits, so the $ref is kept verbatim under Unmodeled" @@ -643,17 +1040,80 @@ func keptWhy(comp allOfComposition, b wholeRefEntry) string { case refOutsideSet: return "the conjuncts of " + of + " share no value, and its value set is elected before the rest, " + "holding values this $ref's target does not, so the $ref is kept verbatim under Unmodeled" - case refApart: - return "the value sets of " + of + " share no member, so no conjunct is the one it lowers from, and the " + - "$ref is kept verbatim under Unmodeled" + case refAround: + return "this $ref leads round a loop of references back to " + of + ", which admits every kind there, so " + + "what its other conjuncts say decides; the $ref is kept verbatim under Unmodeled" + case refFormatNarrows: + return formatNarrowsWhy(loweringContext, schema, comp, refEntry) + case refContentEncodesText: + return "the contentEncoding another conjunct of " + of + " writes makes the string this $ref's target " + + "reads a value from that encoding's text, its content once decoded binary data, so the position is the " + + "string under the encoding, and the $ref is kept verbatim under Unmodeled" + case refNullIntersection: + return "the conjuncts of " + of + " admit null alone together, so the position is the enum with no member " + + "a schema of null alone lowers to, a use of no target; the $ref is kept verbatim under Unmodeled" default: return "the value set of " + of + " narrows this $ref, and one node holds one value set, so the $ref is " + "kept verbatim under Unmodeled; what its target says of the position still reaches it" } } +// formatNarrowsWhy words why a refinement keeps refEntry, the $ref entry of +// comp, the allOf schema writes, beside a format that, read over the target's +// type as its flat twin reads it (besideRefOf), narrows what the target is +// rooted at (scalarChainOf). +func formatNarrowsWhy(loweringContext lowering.Ctx, schema *statement.Schema, comp allOfComposition, refEntry keptRefEntry) string { + read := besideRefOf(loweringContext, schema) + target, _ := scalarChainOf(loweringContext, refEntry.entry.schema) + keyword, text := refSpelling(refEntry.entry.schema) + lowered := primitiveNoun(read.flatShape.base) + return "format: " + writtenFormat(read.conjunctSchema) + " " + writtenOn(comp, read.conjunctAt, keyword) + " makes " + comp.subject() + " " + + lowered + ", while the " + keyword + " target " + strconv.Quote(text) + " is " + rootNoun(target.root) + "; lowered as " + + lowered + " with the " + keyword + " kept under Unmodeled" +} + +// writtenOn names where the conjunct at at among comp's conjuncts is written, +// from the schema writing them: on its entry, by its path, or, for +// annotation.BesideAllOf, the schema's own keywords, beside its allOf or the +// reference it writes with keyword. +func writtenOn(comp allOfComposition, at annotation.ConjunctIndex, keyword string) string { + i, isEntry := at.Entry() + switch { + case isEntry: + return "on " + comp.entryPath(comp.entries[i].pointer) + case comp.subject() == "this schema": + return "beside its " + keyword + default: + return "beside the allOf" + } +} + +// rootNoun words what root, the scalar a chain of $refs ends on, is: a plain +// value of its JSON type where that type's own primitive roots it, else the +// primitive it is rooted at (primitiveNoun). +func rootNoun(root scalarRoot) string { + if root.root == baseForType(root.jsonType) { + return "a plain " + string(root.jsonType) + } + return primitiveNoun(root.root) +} + +// primitiveNoun words primitive as a noun a report reads, with its article: +// an before a vowel sound, which no u begins among the primitives, and none +// for bytes, a mass noun. +func primitiveNoun(primitive ir.PrimitiveKind) string { + switch { + case primitive == ir.PrimitiveBytes: + return string(primitive) + case strings.IndexAny(string(primitive), "aeio") == 0: + return "an " + string(primitive) + default: + return "a " + string(primitive) + } +} + // keepConjuncts keeps on unmodeled the conjuncts schema, written at pointer, -// writes beside its own keywords, which an election passed over: where they are +// writes beside its own keywords, which a choice passed over: where they are // references alone, beside them or on its allOf's entries, each as a refinement // keeps a $ref it passes over (keepRefConjuncts), so `{allOf: [{$ref: T}], K}` // keeps what `{$ref: T, K}` does; else the $ref written beside them so, and the @@ -668,8 +1128,8 @@ func keepConjuncts(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema written, named = append(written, "$ref"), append(named, "$ref") } entries := 0 - for _, b := range refs { - if b.entry.pointer != pointer && kept[b.entry.pointer] { + for _, refEntry := range refs { + if refEntry.entry.pointer != pointer && kept[refEntry.entry.pointer] { entries++ } } @@ -684,13 +1144,13 @@ func keepConjuncts(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema } if schema.BesideRef != nil { allOfEntryValue := allOfEntry{schema: loweringContext.Statements().Read(schema.BesideRef), pointer: pointer} - kept, keptDiags := keepRefConjuncts(loweringContext, unmodeled, []wholeRefEntry{{entry: allOfEntryValue}}, pointer) + kept, keptDiags := keepRefConjuncts(loweringContext, unmodeled, []keptRefEntry{{entry: allOfEntryValue}}, pointer) diags = append(diags, keptDiags...) if kept[pointer] { written, named = append(written, "$ref"), append(named, "$ref") } } - kept, keptDiags := preserveSchemaKeyword(loweringContext, unmodeled, schema, "allOf", ir.ReasonDegradedLowering, pointer) + kept, keptDiags := keepSchemaKeyword(loweringContext, unmodeled, schema, "allOf", ir.ReasonDegradedLowering, pointer) diags = append(diags, keptDiags...) if kept { written, named = append(written, "allOf"), append(named, "allOf") @@ -700,14 +1160,14 @@ func keepConjuncts(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema // refConjuncts returns the conjuncts schema, written at pointer, writes beside // its own keywords, each a $ref, and false where one is not. -func refConjuncts(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) ([]wholeRefEntry, bool) { +func refConjuncts(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) ([]keptRefEntry, bool) { entries := allOfEntries(loweringContext, schema, pointer).entries - refs := make([]wholeRefEntry, 0, len(entries)) + refs := make([]keptRefEntry, 0, len(entries)) for _, entry := range entries { if entry.schema.Ref == nil { return nil, false } - refs = append(refs, wholeRefEntry{entry: entry}) + refs = append(refs, keptRefEntry{entry: entry}) } return refs, len(refs) > 0 } diff --git a/compilers/openapi/internal/schema/refsite.go b/compilers/openapi/internal/schema/refsite.go index 0693a12fe..dc21cd6da 100644 --- a/compilers/openapi/internal/schema/refsite.go +++ b/compilers/openapi/internal/schema/refsite.go @@ -13,7 +13,6 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/merge" "github.com/dexpace/morphic/compilers/openapi/internal/reftable" "github.com/dexpace/morphic/compilers/openapi/internal/reftable/typed" "github.com/dexpace/morphic/compilers/openapi/internal/statement" @@ -21,36 +20,31 @@ import ( ) // refSiteRef resolves a $ref position, a schema writing its reference beside -// nothing it reads but what a reference leaves silent: any key read beside a +// nothing it reads but what a reference leaves unsaid: any key read beside a // $ref makes a conjunction (statement.MemoizingSchemaReader), lowered as its // allOf spelling is, and an allOf entry whose reference names nothing, read // whole, is no position a reference reaches, as one to it reads on through its // own. So such a site writes nothing beside its target for a node to keep. -func refSiteRef(loweringContext lowering.Ctx, ts *compile.Types, js *statement.Statement, schema *statement.Schema, pointer jsontext.Pointer, home annotation.Home, +func refSiteRef(loweringContext lowering.Ctx, types *compile.Types, schemaStatement *statement.Statement, schema *statement.Schema, pointer jsontext.Pointer, home annotation.Home, ) (ir.TypeRef, []ir.Diagnostic) { - target, diags := refTypeRef(loweringContext, ts, js, pointer) - ref, homeDiags := homeDeclaration(loweringContext, ts, schema, target, pointer, home, false, nil) + target, diags := refTypeRef(loweringContext, types, schemaStatement, pointer) + _, ref, homeDiags := homeDeclaration(loweringContext, types, schema, target, pointer, home, false) return ref, append(diags, homeDiags...) } -// PreserveRefSiteKeywords keeps, on a carrier's own Unmodeled, the keywords a -// position lowered to a reference as a $ref site is declared that the reference -// cannot hold (referenceOutcomeKeywords): a collapsed union, an expanded -// $dynamicRef and a refinement. It is schemaBody's other half, the same unread -// keeping recorded where an annotation.HomeCarrier position keeps everything -// else its schema declared (GitHub #406). A $ref site writes nothing to keep -// (refSiteRef), and a schema that lowered to a node of its own had its unread -// keywords recorded there, so the carrier adds nothing: one home per -// declaration, as fillPropertyAnnotations draws the line. -func PreserveRefSiteKeywords(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, - js *statement.Statement, typeRef ir.TypeRef, pointer jsontext.Pointer, +// KeepRefSiteKeywords adds, to a carrier's pending keeps, the keywords a +// position lowered to a reference declares that the reference cannot hold: a +// collapsed union, an expanded $dynamicRef and a refinement. carried keeps +// what an entry writes that the carrier has no field for. +func KeepRefSiteKeywords(loweringContext lowering.Ctx, types *compile.Types, pendingKeeps *annotation.PendingKeeps, + schemaStatement *statement.Statement, typeRef ir.TypeRef, pointer jsontext.Pointer, carried CarrierKeywordKeeps, ) []ir.Diagnostic { // The one check covers an absent position, a boolean one, a $ref site and a // caller passing nil. - if js == nil || !stated(js.Schema) || js.Ref != nil || LoweredToOwnNode(loweringContext, pointer, typeRef) { + if schemaStatement == nil || !stated(schemaStatement.Schema) || schemaStatement.Ref != nil || LoweredToOwnNode(loweringContext, pointer, typeRef) { return nil } - return keepsAtOutcome(loweringContext, js.Schema, typeRef, pointer).record(loweringContext, ts, unmodeled, js.Schema, pointer, nil, nil) + return keepsAtOutcome(loweringContext, schemaStatement.Schema, typeRef, pointer).record(loweringContext, pendingKeeps, schemaStatement.Schema, pointer, nil, "", carried) } // refTypeRef resolves a $ref position to its target's stable ID, carrying the @@ -61,41 +55,57 @@ func PreserveRefSiteKeywords(loweringContext lowering.Ctx, ts *compile.Types, un // one landing on no schema, is diagnosed and dropped to any. A $ref on a loop of $refs is // dropped to any too, with nothing of its own to report: the load phase reports // the loop once. -func refTypeRef(loweringContext lowering.Ctx, ts *compile.Types, js *statement.Statement, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { - id, ok := resolveSchemaRef(loweringContext, ts, js) +func refTypeRef(loweringContext lowering.Ctx, types *compile.Types, schemaStatement *statement.Statement, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { + id, ok := resolveSchemaRef(loweringContext, types, schemaStatement) if ok { - return refNullRef(loweringContext, id, js, siteAt(pointer)) + return refNullRef(loweringContext, id, schemaStatement, pointer) } - if onLoop(js) { - return ts.PrimitiveRef(ir.PrimitiveAny), nil + if onLoop(schemaStatement) { + return types.PrimitiveRef(ir.PrimitiveAny), nil } - keyword, ref := refSpelling(js) - return ts.PrimitiveRef(ir.PrimitiveAny), []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.UnresolvedRef, pointer, - "unresolved %s %q%s", keyword, ref, unresolvedWhy(loweringContext, js))} + return types.PrimitiveRef(ir.PrimitiveAny), []ir.Diagnostic{unresolvedRefReport(loweringContext, pointer, schemaStatement, "unresolved %s %q%s")} } -// refSpelling is the keyword and the value of the reference js writes, as the -// load phase reports one landing nowhere: the table's entry's, else the -// model's $ref, which the budget left unread. -func refSpelling(js *statement.Statement) (keyword, value string) { +// unresolvedRefKey names the $ref a source writes at a pointer, whose report +// the run draws once (unresolvedRefReport). +type unresolvedRefKey struct { + pointer jsontext.Pointer + source int +} + +// unresolvedRefReport returns the report of the $ref schemaStatement writes at +// pointer, which resolves to nothing: the one its first reader drew, worded by +// format, so every reader returns one report the run holds once (GitHub #1570). +func unresolvedRefReport(loweringContext lowering.Ctx, pointer jsontext.Pointer, schemaStatement *statement.Statement, format string) ir.Diagnostic { + at := loweringContext.Place().At(pointer) + return lowering.ReadOncePerRun(loweringContext, unresolvedRefKey{pointer: at.Pointer, source: at.Source}, func() ir.Diagnostic { + keyword, ref := refSpelling(schemaStatement) + return loweringContext.DiagAt(ir.SeverityError, diag.UnresolvedRef, pointer, format, keyword, ref, unresolvedWhy(loweringContext, schemaStatement)) + }) +} + +// refSpelling is the keyword and the value of the reference schemaStatement +// writes, as the load phase reports one landing nowhere: the table's entry's, +// else the model's $ref, which the budget left unread. +func refSpelling(schemaStatement *statement.Statement) (keyword, value string) { switch { - case js.Ref == nil: + case schemaStatement.Ref == nil: return "$ref", "" - case js.Ref.Bound: - return js.Ref.Entry.Keyword, js.Ref.Entry.Hop.Ref + case schemaStatement.Ref.Bound: + return schemaStatement.Ref.Entry.Keyword, schemaStatement.Ref.Entry.Hop.Ref default: - return "$ref", js.Ref.Text + return "$ref", schemaStatement.Ref.Text } } -// unresolvedWhy is the reason the $ref at js reports when it resolves to no -// type here: why its own hop lands on no schema (reftable.Hop.Why), or why the -// table never read it (unreadWhy). It is empty for any other, a target -// declaring nothing to lower. The position may well exist, so without it the -// report reads as though it named nothing. -func unresolvedWhy(loweringContext lowering.Ctx, js *statement.Statement) string { - if js.Ref != nil && js.Ref.Bound { - return hopWhy(js.Ref.Entry.Hop) +// unresolvedWhy is the reason the $ref at schemaStatement reports when it +// resolves to no type here: why its own hop lands on no schema +// (reftable.Hop.Why), or why the table never read it (unreadWhy). It is empty +// for any other, a target declaring nothing to lower. The position may well +// exist, so without it the report reads as though it named nothing. +func unresolvedWhy(loweringContext lowering.Ctx, schemaStatement *statement.Statement) string { + if schemaStatement.Ref != nil && schemaStatement.Ref.Bound { + return hopWhy(schemaStatement.Ref.Entry.Hop) } return unreadWhy(loweringContext.Bindings()) } @@ -124,40 +134,37 @@ func hopWhy(hop reftable.Hop) string { // names, in whichever document (resolveAt). It returns ok=false for a $ref that // lands on no schema (landsAt) and for a reference to an // undeclared component. -func resolveSchemaRef(loweringContext lowering.Ctx, ts *compile.Types, js *statement.Statement) (ir.TypeID, bool) { - at, ok := landsAt(js) +func resolveSchemaRef(loweringContext lowering.Ctx, types *compile.Types, schemaStatement *statement.Statement) (ir.TypeID, bool) { + at, ok := landsAt(schemaStatement) if !ok { return "", false } - decl, _ := declaredOf(loweringContext, js) - return resolveAt(loweringContext, ts, at, decl) + decl, _ := declaredOf(loweringContext, schemaStatement) + return resolveAt(loweringContext, types, at, decl) } // resolveAt is resolvePointer at a position of the bindings' table, read at // its own document's coordinates (lowering.InDocument). -func resolveAt(loweringContext lowering.Ctx, ts *compile.Types, at reftable.DocumentPointer, decl *statement.Statement) (ir.TypeID, bool) { +func resolveAt(loweringContext lowering.Ctx, types *compile.Types, at reftable.DocumentPointer, decl *statement.Statement) (ir.TypeID, bool) { loweringContext, ok := lowering.InDocument(loweringContext, at.Doc) if !ok { return "", false } - return resolvePointer(loweringContext, ts, at.Pointer, decl) + return resolvePointer(loweringContext, types, at.Pointer, decl) } -// PrunedDiagnostic is a fold drop diagnostic's alternate wording to apply if -// post-settlement pruning actually removes its losing anonymous type. -type PrunedDiagnostic = merge.PrunedDiagnostic - // runTrackers holds run-scoped tracking state for post-lowering attachment and -// seeded pruning: kept verbatim discriminator routes, explicitly reached schema -// positions (hoisted targets and external schemas), the active reference -// reserver, alternate fold diagnostics for anonymous losers, and TypeIDs or -// dropped provenances explicitly superseded during lowering and settlement. +// seeded pruning: kept verbatim discriminator routes, the positions their +// values lead to yet to be promised, explicitly reached schema positions +// (hoisted targets and external schemas), the active reference reserver, and +// TypeIDs or dropped provenances explicitly superseded during lowering and +// settlement. type runTrackers struct { keptDiscriminatorRoutes map[LandingSite][]Landing + keptTargets []chainNode reachedSchemas map[reftable.DocumentPointer]bool pendingReached []reftable.DocumentPointer reserver *refReserver - prunedDiagnostics []merge.PrunedDiagnostic discarded map[ir.TypeID]bool discardedSites []ir.Provenance } @@ -182,12 +189,13 @@ func recordReachedSchema(loweringContext lowering.Ctx, pos reftable.DocumentPoin } } -// RecordReached marks pointer in loweringContext's document as a position -// preserved verbatim by lowering (such as a kept encoding, callback, parameter, -// or content entry) so ReserveNodesAtReferenceTargets reserves schema $ref -// targets reachable beneath it without consulting unvisited components. -func RecordReached(loweringContext lowering.Ctx, pointer jsontext.Pointer) { +// KeptVerbatimAt marks pointer in loweringContext's document as a position +// lowering kept verbatim, so ReserveNodesAtReferenceTargets reserves the $ref +// targets reachable beneath it, and keeps whole each discriminator written +// within it, returning what that reports. +func KeptVerbatimAt(loweringContext lowering.Ctx, pointer jsontext.Pointer) []ir.Diagnostic { recordReachedSchema(loweringContext, loweringContext.Position(pointer)) + return KeepDiscriminatorsWithin(loweringContext, nil, pointer) } // recordDiscarded records id as explicitly superseded or dropped during this @@ -232,12 +240,6 @@ func DiscardedSites(loweringContext lowering.Ctx) []ir.Provenance { return slices.Clone(runTrackersOf(loweringContext).discardedSites) } -// PrunedDiagnostics returns the alternate fold-drop messages collected during -// settlement for anonymous losing types. Call after compile.Types.Finish. -func PrunedDiagnostics(loweringContext lowering.Ctx) []PrunedDiagnostic { - return slices.Clone(runTrackersOf(loweringContext).prunedDiagnostics) -} - // refReserver holds the linear reachability index built by // ReserveNodesAtReferenceTargets so schemas reached later while fulfilling // promised sub-schemas (such as kept discriminator routes or dynamic @@ -257,10 +259,11 @@ type refReserver struct { // visited or kept verbatim by lowering and propagates along a linear worklist // without entering unreferenced $defs or definitions tables, so unvisited // reusable components and unreferenced definitions never mint orphan nodes. -func ReserveNodesAtReferenceTargets(loweringContext lowering.Ctx, ts *compile.Types) { +func ReserveNodesAtReferenceTargets(loweringContext lowering.Ctx, types *compile.Types) { + promiseKeptTargets(loweringContext, types, runTrackersOf(loweringContext)) table := loweringContext.Bindings().Table() var sites []reftable.ReferenceSite - for _, entry := range table.Entries() { + for _, entry := range table.ReferenceSites() { if entry.Lands() { sites = append(sites, entry) } @@ -277,12 +280,12 @@ func ReserveNodesAtReferenceTargets(loweringContext lowering.Ctx, ts *compile.Ty } trackers := runTrackersOf(loweringContext) trackers.reserver = reserver - reserver.drain(loweringContext, ts, trackers) + reserver.drain(loweringContext, types, trackers) } // drain propagates reachability from every position queued in // trackers.pendingReached since the previous drain. -func (r *refReserver) drain(loweringContext lowering.Ctx, ts *compile.Types, trackers *runTrackers) { +func (r *refReserver) drain(loweringContext lowering.Ctx, types *compile.Types, trackers *runTrackers) { pending := trackers.pendingReached trackers.pendingReached = nil worklist := make([]reftable.DocumentPointer, 0, len(pending)) @@ -295,7 +298,7 @@ func (r *refReserver) drain(loweringContext lowering.Ctx, ts *compile.Types, tra if len(worklist) == 0 { return } - slices.SortFunc(worklist, reftable.PositionOrder(r.table)) + reftable.SortPositions(r.table, worklist) for head := 0; head < len(worklist); head++ { for _, i := range r.byAncestor[worklist[head]] { if r.reserved[i] { @@ -303,7 +306,7 @@ func (r *refReserver) drain(loweringContext lowering.Ctx, ts *compile.Types, tra } r.reserved[i] = true target := r.sites[i].Hop.Target - resolveAt(loweringContext, ts, target, loweringContext.Statements().At(target)) + resolveAt(loweringContext, types, target, loweringContext.Statements().At(target)) if !r.visited[target] { r.visited[target] = true worklist = append(worklist, target) @@ -361,9 +364,9 @@ func recordKeptDiscriminatorRoutes(loweringContext lowering.Ctx, pointer jsontex written[entry.Value] = entry.Target } site := LandingSite{Source: loweringContext.Place().Source, Pointer: pointer} - routes := runTrackersOf(loweringContext).keptDiscriminatorRoutes + landings := make([]Landing, 0, len(mapping)+1) for _, tag := range slices.Sorted(maps.Keys(mapping)) { - routes[site] = append(routes[site], Landing{ + landings = append(landings, Landing{ ID: mapping[tag], Path: ids.Ptr("mapping", tag), Ref: written[tag], @@ -371,13 +374,17 @@ func recordKeptDiscriminatorRoutes(loweringContext lowering.Ctx, pointer jsontex }) } if def != "" { - routes[site] = append(routes[site], Landing{ + landings = append(landings, Landing{ ID: def, Path: ids.Ptr("defaultMapping"), Ref: discriminator.DefaultMapping, Discriminator: true, }) } + // Assigned, not appended: a keeper asked twice of one discriminator, as a + // dry run of an alias's keepers asks before the alias is hoisted, records + // its routes once. + runTrackersOf(loweringContext).keptDiscriminatorRoutes[site] = landings } // ReferenceLandings returns every resolved schema $ref landing in the run's @@ -386,7 +393,7 @@ func recordKeptDiscriminatorRoutes(loweringContext lowering.Ctx, pointer jsontex // compile.Types.Finish so every deferred route is recorded. func ReferenceLandings(loweringContext lowering.Ctx) map[LandingSite][]Landing { out := map[LandingSite][]Landing{} - for _, referenceSite := range loweringContext.Bindings().Table().Entries() { + for _, referenceSite := range loweringContext.Bindings().Table().ReferenceSites() { if !referenceSite.Lands() { continue } @@ -420,11 +427,11 @@ func ReferenceLandings(loweringContext lowering.Ctx) map[LandingSite][]Landing { // // A $ref and a discriminator mapping target meet here once each has its // pointer, so they cannot drift apart. -func resolvePointer(loweringContext lowering.Ctx, ts *compile.Types, pointer jsontext.Pointer, decl *statement.Statement) (ir.TypeID, bool) { +func resolvePointer(loweringContext lowering.Ctx, types *compile.Types, pointer jsontext.Pointer, decl *statement.Statement) (ir.TypeID, bool) { id, hoisted, ok := declaredIn(loweringContext, pointer, decl) if hoisted { recordReachedSchema(loweringContext, loweringContext.Position(pointer)) - ts.ReserveNodeAtCoordinate(loweringContext.IDs().Coordinate(pointer), func() []ir.Diagnostic { return hoistSubSchema(loweringContext, ts, decl, pointer) }) + types.ReserveNodeAtCoordinate(loweringContext.IDs().Coordinate(pointer), func() []ir.Diagnostic { return hoistSubSchema(loweringContext, types, decl, pointer) }) } return id, ok } @@ -438,7 +445,7 @@ func declaredIn(loweringContext lowering.Ctx, pointer jsontext.Pointer, decl *st // The source's components alone are lowered whole and named by name; // another document's are hoisted where a reference reaches them, as any // other position of it is. - if loweringContext.IDs() == (ids.DocumentIDNamespace{}) { + if loweringContext.IDs().Source() { if named, state := loweringContext.RefScope().ComponentRef(pointer); state.ByName() { return named, false, state == ids.NamedComponent } @@ -460,10 +467,10 @@ func resolvesAt(loweringContext lowering.Ctx, at reftable.DocumentPointer) bool return ok } -// namesReferent reports whether the reference st writes resolves, as -// resolveSchemaRef resolves it, without promising its node. -func namesReferent(loweringContext lowering.Ctx, st *statement.Statement) bool { - at, ok := landsAt(st) +// namesReferent reports whether the reference schemaStatement writes resolves, +// as resolveSchemaRef resolves it, without promising its node. +func namesReferent(loweringContext lowering.Ctx, schemaStatement *statement.Statement) bool { + at, ok := landsAt(schemaStatement) return ok && resolvesAt(loweringContext, at) } @@ -477,32 +484,36 @@ func namesReferent(loweringContext lowering.Ctx, st *statement.Statement) bool { // It lowers in the position's own context, whichever reference promised it: // from TopLevelDepth, as a walk of its own, in decl's document. A $ref with // siblings is aliased, keeping them. -func hoistSubSchema(loweringContext lowering.Ctx, ts *compile.Types, decl *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { +func hoistSubSchema(loweringContext lowering.Ctx, types *compile.Types, decl *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { defer func() { - if trackers := runTrackersOf(loweringContext); trackers.reserver != nil { - trackers.reserver.drain(loweringContext, ts, trackers) + trackers := runTrackersOf(loweringContext) + promiseKeptTargets(loweringContext, types, trackers) + if trackers.reserver != nil { + trackers.reserver.drain(loweringContext, types, trackers) } }() schemaPositionAnnotationSources := annotation.At(decl) // loweringContext reads the document that declares pointer already // (resolveAt), which is where the bindings place decl. - ref, diags := Ref(loweringContext, ts, TopLevelDepth, decl, pointer) + ref, diags := Ref(loweringContext, types, TopLevelDepth, decl, pointer) if LoweredToOwnNode(loweringContext, pointer, ref) { return diags } // As in lowerComponentSchema: this node is the first the pointer owns, so // the annotations Ref had nowhere to put now have a home, which its build // gives them. - var annotated finished - diags = append(diags, internOwnNode(loweringContext, ts, decl, pointer, ref, annotated.on(func(td ir.TypeDef) []ir.Diagnostic { - return attachDeclaredAnnotations(loweringContext, ts, schemaPositionAnnotationSources.Node, pointer, ref, td) - }))...) - return append(diags, annotated.diags...) -} - -// onLoop reports whether the $ref at b lies on a loop of $refs, which the load -// phase reports once and the lowering drops to any without a report of its -// own. -func onLoop(b *statement.Statement) bool { - return b.Ref != nil && b.Ref.Bound && b.Ref.Entry.Chain.PositionLiesOnReferenceCycle + built, ownDiags := internOwnNode(loweringContext, types, decl, pointer, ref) + diags = append(diags, ownDiags...) + if built.node != nil && stated(schemaPositionAnnotationSources.Node) { + diags = append(diags, attachDeclaredAnnotations(loweringContext, schemaPositionAnnotationSources.Node, pointer, ref, &built)...) + diags = append(diags, settleNode(loweringContext, schemaPositionAnnotationSources.Node, ref, pointer, &built)...) + } + return diags +} + +// onLoop reports whether the $ref at reference lies on a loop of $refs, which +// the load phase reports once and the lowering drops to any without a report of +// its own. +func onLoop(reference *statement.Statement) bool { + return reference.Ref != nil && reference.Ref.Bound && reference.Ref.Entry.Chain.PositionLiesOnReferenceCycle } diff --git a/compilers/openapi/internal/schema/refsite_internal_test.go b/compilers/openapi/internal/schema/refsite_internal_test.go index c1a80a473..4c73c1a9d 100644 --- a/compilers/openapi/internal/schema/refsite_internal_test.go +++ b/compilers/openapi/internal/schema/refsite_internal_test.go @@ -29,9 +29,9 @@ import ( // no schema, as when building one failed, which the load phase reports. func TestRefTypeRef_SaysWhyAnUnboundRefIsUnresolved(t *testing.T) { t.Parallel() - message := func(t *testing.T, lowerer *Lowerer, js *oas3.JSONSchema[oas3.Referenceable]) string { + message := func(t *testing.T, lowerer *Lowerer, jsonSchema *oas3.JSONSchema[oas3.Referenceable]) string { t.Helper() - ref, diags := refTypeRef(lowerer.Ctx, lowerer.Types, lowerer.Ctx.Statements().Of(js), "/components/schemas/A") + ref, diags := refTypeRef(lowerer.Ctx, lowerer.Types, lowerer.Ctx.Statements().Of(jsonSchema), "/components/schemas/A") assert.Equal(t, ir.TypeID("type/primitive/any"), ref.Target) require.Len(t, diags, 1) return diags[0].Message @@ -89,9 +89,9 @@ func TestResolveSchemaRef_UnboundDeepRefDropped(t *testing.T) { lowerer := NewRawLowerer(&soa.OpenAPI{}) // A same-file $ref to a deep pointer no binding read: no interned node and // nothing the bindings know it lands on, so the reference is dropped. - js := oas3.NewJSONSchemaFromReference("#" + deepPointer) + jsonSchema := oas3.NewJSONSchemaFromReference("#" + deepPointer) - _, ok := resolveSchemaRef(lowerer.Ctx, lowerer.Types, Standalone(js)) + _, ok := resolveSchemaRef(lowerer.Ctx, lowerer.Types, Standalone(jsonSchema)) assert.False(t, ok, "an unresolved deep sub-schema $ref is dropped, not synthesized") } @@ -106,9 +106,9 @@ func TestHoistSubSchema_BodyInternsAtPointer(t *testing.T) { assert.Empty(t, hoistSubSchema(lowerer.Ctx, lowerer.Types, Standalone(object), deepPointer), "an object body hoists cleanly") seeded, _ := lowerer.Types.Lookup(deepPointer) assert.Equal(t, ids.DocumentIDNamespace{}.AnonymousType(deepPointer), seeded) - td, ok := lowerer.Types.NodeAt(deepPointer) + typeDef, ok := lowerer.Types.NodeAt(deepPointer) require.True(t, ok) - assert.Equal(t, ir.KindModel, td.Kind(), "the body's own node, not an alias over it") + assert.Equal(t, ir.KindModel, typeDef.Kind(), "the body's own node, not an alias over it") } // unheldLowerer is a lowerer over bindings that know where A's $ref lands but diff --git a/compilers/openapi/internal/schema/refsite_landings_test.go b/compilers/openapi/internal/schema/refsite_landings_test.go index 127319818..e7430ef01 100644 --- a/compilers/openapi/internal/schema/refsite_landings_test.go +++ b/compilers/openapi/internal/schema/refsite_landings_test.go @@ -230,7 +230,7 @@ func TestReserveNodesAtReferenceTargets_SkipsUnreferencedDefs(t *testing.T) { assert.Contains(t, chainPromised.Types, ir.TypeID("type/anonymous/components/schemas/Chain/$defs/D0000")) assert.Contains(t, chainPromised.Types, ir.TypeID(fmt.Sprintf("type/anonymous/components/schemas/Chain/$defs/D%04d", chainLen-1))) - // RecordReached activates sites beneath an explicitly recorded container. + // KeptVerbatimAt activates sites beneath an explicitly recorded container. lowerer, _ := schema.LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` Holder: type: object $defs: @@ -242,7 +242,7 @@ func TestReserveNodesAtReferenceTargets_SkipsUnreferencedDefs(t *testing.T) { schema: {$ref: '#/components/schemas/Holder/$defs/X'} `) lowerer.Diags.AppendAll(schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) - schema.RecordReached(lowerer.Ctx, "/components/parameters/Extra") + assert.Empty(t, schema.KeptVerbatimAt(lowerer.Ctx, "/components/parameters/Extra"), "it holds no discriminator") schema.ReserveNodesAtReferenceTargets(lowerer.Ctx, lowerer.Types) recordedDoc := lowerer.Document(t) assert.Contains(t, recordedDoc.Types, ir.TypeID("type/anonymous/components/schemas/Holder/$defs/X")) @@ -253,20 +253,21 @@ func TestReserveNodesAtReferenceTargets_SkipsUnreferencedDefs(t *testing.T) { schema.RecordDiscardedSite(lowerer.Ctx, prov) assert.True(t, schema.DiscardedTypes(lowerer.Ctx)["type/anonymous/dropped"]) assert.Equal(t, []ir.Provenance{prov}, schema.DiscardedSites(lowerer.Ctx)) - assert.Empty(t, schema.PrunedDiagnostics(lowerer.Ctx)) } // TestUnpreservableValidationOnlyBranch_RecordsDiscardedSite pins that an // unpreservable validation-only combinator (kept via -// preserveValidationOnlyKeyword) records its keyword provenance as a discarded -// site for post-settlement pruning. +// keepValidationOnlyKeyword) records its keyword provenance as a discarded +// site for post-settlement pruning. Its value no JSON holds is under a note, +// since an extension's is left out and keeps the rest, and a key no dialect +// defines declares shape, so its branch is a variant. func TestUnpreservableValidationOnlyBranch_RecordsDiscardedSite(t *testing.T) { t.Parallel() lowerer, _ := schema.LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` BadValOnly: type: string oneOf: - minLength: 1 - x-bad: .inf + examples: [.inf] - maxLength: 5 `)) lowerer.Diags.AppendAll(schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) diff --git a/compilers/openapi/internal/schema/refsite_test.go b/compilers/openapi/internal/schema/refsite_test.go index 77622ac29..2023cac16 100644 --- a/compilers/openapi/internal/schema/refsite_test.go +++ b/compilers/openapi/internal/schema/refsite_test.go @@ -81,7 +81,7 @@ func TestUnresolvedRef_InAnotherDocumentsContentIsReportedOnceWhereItIsWritten(t oneOfOf := func(ref string) string { return "{type: object, properties: {x: {type: string}}, oneOf: [{$ref: '" + ref + "'}]}" } - for _, tc := range []struct { + for _, testCase := range []struct { name, schema, at, ref string why func(dir string) string // nil when the $ref resolves }{ @@ -94,7 +94,7 @@ func TestUnresolvedRef_InAnotherDocumentsContentIsReportedOnceWhereItIsWritten(t {"an allOf entry naming a third document", allOfOf("./third.yaml#/Thing"), allOf, "./third.yaml#/Thing", unread}, {"a union branch naming a third document", oneOfOf("./third.yaml#/Thing"), oneOf, "./third.yaml#/Thing", unread}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags, dir := compileBeside(t, map[string]string{"ext.yaml": `paths: /x: @@ -102,7 +102,7 @@ func TestUnresolvedRef_InAnotherDocumentsContentIsReportedOnceWhereItIsWritten(t responses: "200": description: ok - content: {application/json: {schema: ` + tc.schema + `}} + content: {application/json: {schema: ` + testCase.schema + `}} components: schemas: Thing: {type: object} @@ -116,13 +116,13 @@ components: `) var want []ir.Diagnostic - if tc.why != nil { + if testCase.why != nil { want = []ir.Diagnostic{{Severity: ir.SeverityError, Code: "openapi/unresolved-ref", - Message: `unresolved $ref "` + tc.ref + `": ` + tc.why(dir), - Provenance: ir.Provenance{Source: 1, Pointer: jsontext.Pointer(tc.at)}}} + Message: `unresolved $ref "` + testCase.ref + `": ` + testCase.why(dir), + Provenance: ir.Provenance{Source: 1, Pointer: jsontext.Pointer(testCase.at)}}} } assert.Empty(t, cmp.Diff(want, withCode(diags, "openapi/unresolved-ref"))) - if tc.why == nil { + if testCase.why == nil { thing, ok := doc.Types[ids.In("ext.yaml").NamedType("/components/schemas/Thing")] require.True(t, ok, "ext.yaml's Thing is lowered") assert.Equal(t, ir.Provenance{Source: 1, Pointer: "/components/schemas/Thing"}, @@ -262,11 +262,11 @@ components: schema: {type: string, example: sub-example} `) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types["type/anonymous/components/parameters/P/schema"] + typeDef, ok := doc.Types["type/anonymous/components/parameters/P/schema"] require.True(t, ok, "the referenced sub-schema is hoisted at its own pointer") - require.Len(t, td.Common().Examples, 1) - require.NotNil(t, td.Common().Examples[0].Value) - assert.Equal(t, "sub-example", td.Common().Examples[0].Value.String) + require.Len(t, typeDef.Common().Examples, 1) + require.NotNil(t, typeDef.Common().Examples[0].Value) + assert.Equal(t, "sub-example", typeDef.Common().Examples[0].Value.String) assert.Empty(t, doc.Types["type/primitive/string"].Common().Examples, "the shared primitive carries no per-declaration annotation") } @@ -548,7 +548,7 @@ func TestUndeclaredRegion_TwoReferencesAgreeInBothOrders(t *testing.T) { const preamble = "openapi: 3.1.0\ninfo: {title: O, version: \"1.0.0\"}\npaths:\n" const innerSchema = "{type: array, items: {type: array, items: {type: object, properties: {v: {type: string}}}}}" - for _, tc := range []struct { + for _, testCase := range []struct { name string wrap func(inner string) string // suffix is the RFC 6901 pointer from the schema root to the outer, @@ -564,12 +564,12 @@ func TestUndeclaredRegion_TwoReferencesAgreeInBothOrders(t *testing.T) { return "{type: object, dependentSchemas: {k: " + inner + "}}" }, "dependentSchemas/k"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() bBlock := " /b:\n get:\n operationId: getB\n responses:\n" + " \"200\":\n description: ok\n content:\n" + - " application/json: {schema: " + tc.wrap(innerSchema) + "}\n" - outer := "/paths/~1b/get/responses/200/content/application~1json/schema/" + tc.suffix + " application/json: {schema: " + testCase.wrap(innerSchema) + "}\n" + outer := "/paths/~1b/get/responses/200/content/application~1json/schema/" + testCase.suffix aBlock := " /a:\n get:\n operationId: getA\n responses:\n" + " \"200\":\n description: ok\n content:\n" + @@ -635,13 +635,13 @@ func TestCrossPathReference_ComposedMultipartKeepsItsEncodingKeys(t *testing.T) const components = "components:\n schemas:\n Base:\n type: object\n properties:\n" + " file: {type: string, format: binary}\n" - for _, tc := range []struct{ name, spec string }{ + for _, testCase := range []struct{ name, spec string }{ {"reference declared first", preamble + aBlock + bBlock + components}, {"owner declared first", preamble + bBlock + aBlock + components}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, tc.spec) + doc, diags := parseFull(t, testCase.spec) openapitest.RequireNoErrorDiags(t, diags) base, ok := typeByName(doc, "Base").(*ir.Model) @@ -666,7 +666,7 @@ func TestCrossPathReference_ComposedMultipartKeepsItsEncodingKeys(t *testing.T) // what the position reports lowered alone: the reference leaves lowering it to // its declaration, so it is lowered, and reports, once. The fixture // co-declares oneOf and anyOf at the referenced position, which reports a -// message naming only those keywords (preserveUnusedCombinator). +// message naming only those keywords (keepUnusedCombinatorReports). func TestCrossPathReference_ADiagnosticIsReportedOnce(t *testing.T) { t.Parallel() const preamble = "openapi: 3.1.0\ninfo: {title: O, version: \"1.0.0\"}\npaths:\n" @@ -704,7 +704,7 @@ func TestComponentBody_SubtreeIsNamedByItsDeclaration(t *testing.T) { t.Parallel() const preamble = "openapi: 3.1.0\ninfo: {title: O, version: \"1.0.0\"}\n" const ownerSchema = "{type: array, items: {type: array, items: {type: object, properties: {v: {type: string}}}}}" - for _, tc := range []struct{ name, pointer, paths, owner string }{ + for _, testCase := range []struct{ name, pointer, paths, owner string }{ {"response", "/components/responses/R/content/application~1json/schema", "paths:\n /u:\n get:\n operationId: useR\n responses:\n \"200\": {$ref: '#/components/responses/R'}\n", " responses:\n R: {description: ok, content: {application/json: {schema: " + ownerSchema + "}}}\n"}, @@ -720,21 +720,21 @@ func TestComponentBody_SubtreeIsNamedByItsDeclaration(t *testing.T) { " description: ok\n headers: {X-H: {$ref: '#/components/headers/H'}}\n", " headers:\n H: {schema: " + ownerSchema + "}\n"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - refs := " schemas:\n Out: {$ref: '#" + tc.pointer + "/items'}\n" - alone, diags := parseFull(t, preamble+tc.paths+"components:\n"+tc.owner) + refs := " schemas:\n Out: {$ref: '#" + testCase.pointer + "/items'}\n" + alone, diags := parseFull(t, preamble+testCase.paths+"components:\n"+testCase.owner) openapitest.RequireNoErrorDiags(t, diags) - aloneSub := subtreeAt(alone, tc.pointer) + aloneSub := subtreeAt(alone, testCase.pointer) require.NotEmpty(t, aloneSub, "the owner's declaration hoists a subtree") for _, order := range []struct{ name, comps string }{ - {"owner declared first", tc.owner + refs}, - {"reference declared first", refs + tc.owner}, + {"owner declared first", testCase.owner + refs}, + {"reference declared first", refs + testCase.owner}, } { - doc, diags := parseFull(t, preamble+tc.paths+"components:\n"+order.comps) + doc, diags := parseFull(t, preamble+testCase.paths+"components:\n"+order.comps) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, cmp.Diff(aloneSub, subtreeAt(doc, tc.pointer)), order.name) + assert.Empty(t, cmp.Diff(aloneSub, subtreeAt(doc, testCase.pointer)), order.name) } }) } @@ -776,11 +776,13 @@ func TestRefSiteKeywords_SiblingsWithATypedHomeAreUntouched(t *testing.T) { // allOf entry writes beside its $ref: a conjunct of the position, as the same // keywords on an entry of their own are, never an alias's at the entry. The // $ref is the Base itself; `required` is read by the composition, a format no -// model holds keeps the entry, and a union or an allOf no object satisfies -// draws the warning that the conjuncts share no value. +// model holds keeps the entry, and a union no object satisfies draws the +// warning that the conjuncts share no value. An allOf of a string beside the +// object shares no kind with it: the position is the closed bottom, keeping +// the entry whole, $ref inside, under its entry key. func TestRefSiteKeywords_AnEntrysKeywordsBesideItsRefAreConjuncts(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, sibling, kept, at string requires []string disjoint bool @@ -788,30 +790,48 @@ func TestRefSiteKeywords_AnEntrysKeywordsBesideItsRefAreConjuncts(t *testing.T) {"format and required", "format: email, required: [a]", "openapi:format", "allOf/0/format", []string{"a"}, false}, {"oneOf", "oneOf: [{type: string}, {type: integer}]", "openapi:oneOf", "allOf/0/oneOf", nil, true}, {"anyOf", "anyOf: [{type: string}, {type: integer}]", "openapi:anyOf", "allOf/0/anyOf", nil, true}, - {"allOf", "allOf: [{type: string}]", "openapi:type", "allOf/0/allOf/0/type", nil, true}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, unreadKeywordSpec( - " S: {allOf: [{$ref: '#/components/schemas/BaseObj', "+tc.sibling+"}]}\n")) + " S: {allOf: [{$ref: '#/components/schemas/BaseObj', "+testCase.sibling+"}]}\n")) openapitest.RequireNoErrorDiags(t, diags) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok) require.NotNil(t, model.Base, "the entry still composes") assert.Equal(t, componentID("BaseObj"), model.Base.Target, "its $ref is the Base itself") - assert.Equal(t, tc.requires, model.Requires) + assert.Equal(t, testCase.requires, model.Requires) // Each keyword the entry writes beside its $ref is kept on its own, // as an inline entry's is, at the keyword. - assert.Equal(t, []string{tc.kept}, unmodeledKeys(model.Unmodeled)) - assert.Equal(t, ir.ReasonDegradedLowering, model.Unmodeled[tc.kept].Reason) - assert.Equal(t, jsontext.Pointer("/components/schemas/S/"+tc.at), model.Unmodeled[tc.kept].Provenance.Pointer) + assert.Equal(t, []string{testCase.kept}, unmodeledKeys(model.Unmodeled)) + assert.Equal(t, ir.ReasonDegradedLowering, model.Unmodeled[testCase.kept].Reason) + assert.Equal(t, jsontext.Pointer("/components/schemas/S/"+testCase.at), model.Unmodeled[testCase.kept].Provenance.Pointer) assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/S/allOf/0"), "no node at the entry") - assert.Equal(t, tc.disjoint, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/S") && - openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning) == 1) + assert.Equal(t, testCase.disjoint, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/S") && + openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning) == 1) }) } } +// TestRefSiteKeywords_AStringBesideAnEntrysObjectRefIsTheBottom pins an entry +// writing an allOf of a string beside its $ref to an object: the two share no +// kind, so the position is the closed Model with no member and no Base, +// keeping the entry whole under its entry key, reported as admitting nothing. +func TestRefSiteKeywords_AStringBesideAnEntrysObjectRefIsTheBottom(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, unreadKeywordSpec( + " S: {allOf: [{$ref: '#/components/schemas/BaseObj', allOf: [{type: string}]}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + model, ok := typeByName(doc, "S").(*ir.Model) + require.True(t, ok) + assert.Nil(t, model.Base) + assert.Empty(t, model.Properties) + assert.Equal(t, ir.AdditionalClosed, model.Additional) + assert.Equal(t, []string{"openapi:allOf/0"}, unmodeledKeys(model.Unmodeled), "the entry under its entry key, once") + assert.Contains(t, string(model.Unmodeled["openapi:allOf/0"].Value), "#/components/schemas/BaseObj") + assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning)) +} + // TestSchemaRef_ToAPointerEndingInSlashNamesAnEmptyKey pins a $ref ending in // '/' as RFC 6901 reads it (GitHub #770): naming the member whose key is the // empty string, never the parent. Where there is none it is unresolved; where @@ -927,9 +947,9 @@ func crossPathSchemaRoots() []crossPathSchemaRoot { func subtreeAt(doc *ir.Document, pointer string) map[ir.TypeID]ir.TypeDef { base := "type/anonymous" + pointer out := map[ir.TypeID]ir.TypeDef{} - for id, td := range doc.Types { + for id, typeDef := range doc.Types { if s := string(id); s == base || strings.HasPrefix(s, base+"/") { - out[id] = td + out[id] = typeDef } } return out diff --git a/compilers/openapi/internal/schema/restated_properties_test.go b/compilers/openapi/internal/schema/restated_properties_test.go new file mode 100644 index 000000000..2314603f0 --- /dev/null +++ b/compilers/openapi/internal/schema/restated_properties_test.go @@ -0,0 +1,170 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "slices" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// restatedObj is the referent each row's entry restates, or not. +const restatedObj = ` Obj: {type: object, properties: {a: {type: string}, b: {type: integer}}} +` + +// restatedAt compiles entry as the inline entry beside a $ref to Obj, at a +// component and at a property. +func restatedAt(t *testing.T, entry string) (*ir.Document, []ir.Diagnostic) { + t.Helper() + return restatedAs(t, "{allOf: [{$ref: '#/components/schemas/Obj'}, "+entry+"]}") +} + +// restatedAs compiles schema at a component and at a property. +func restatedAs(t *testing.T, schema string) (*ir.Document, []ir.Diagnostic) { + t.Helper() + return parseFull(t, openapitest.ComponentSpecVer("3.1.0", restatedObj+" S: "+schema+ + "\n H: {type: object, properties: {p: "+schema+"}}\n")) +} + +// TestRestatedProperties_AnEntryRestatingTheReferentsSaysNothing holds an +// entry whose properties restate those of the $ref beside it, written alike in +// either order, or some of them, alone and beside a readOnly the property +// carries: it says +// nothing on the composition, so the position lowers as its twin without the +// properties does, the Model holding its Base alone at the component and the +// reference at the property, and reports what the twin does +// (docs/compilers/openapi.md#allof-refinement). +func TestRestatedProperties_AnEntryRestatingTheReferentsSaysNothing(t *testing.T) { + t.Parallel() + for twinEntry, entries := range map[string][]string{ + "{type: object}": { + "{type: object, properties: {a: {type: string}, b: {type: integer}}}", + "{type: object, properties: {b: {type: integer}, a: {type: string}}}", + "{type: object, properties: {a: {type: string}}}", + }, + "{type: object, readOnly: true}": { + "{type: object, readOnly: true, properties: {a: {type: string}, b: {type: integer}}}", + }, + } { + equivalent, equivalentDiags := restatedAt(t, twinEntry) + property := propertyOf(t, equivalent, "H", "p") + assert.Equal(t, componentID("Obj"), property.Type.Target, "%s: the twin's property is the reference", twinEntry) + for _, entry := range entries { + doc, diags := restatedAt(t, entry) + assert.Empty(t, cmp.Diff(equivalent.Types, doc.Types), entry) + assert.Equal(t, equivalentDiags, diags, entry) + } + } +} + +// TestRestatedProperties_PropertiesBesideTheAllOfSayNothingToo holds the same +// restatement written beside the allOf, in either key order, and on both the +// position and an entry: the keywords beside the allOf are a conjunct as an +// entry is, so each spelling lowers and reports as its twin without the +// properties does. +func TestRestatedProperties_PropertiesBesideTheAllOfSayNothingToo(t *testing.T) { + t.Parallel() + const props = "properties: {a: {type: string}, b: {type: integer}}" + equivalent, equivalentDiags := restatedAs(t, "{allOf: [{$ref: '#/components/schemas/Obj'}], type: object}") + for _, schema := range []string{ + "{allOf: [{$ref: '#/components/schemas/Obj'}], type: object, " + props + "}", + "{type: object, " + props + ", allOf: [{$ref: '#/components/schemas/Obj'}]}", + "{type: object, " + props + ", allOf: [{$ref: '#/components/schemas/Obj'}, {" + props + "}]}", + } { + doc, diags := restatedAs(t, schema) + assert.Empty(t, cmp.Diff(equivalent.Types, doc.Types), schema) + assert.Equal(t, equivalentDiags, diags, schema) + } +} + +// TestRestatedProperties_ASchemaNamingItselfKeepsItsProperties holds a schema +// whose allOf names itself, directly or through a wrapper, beside the +// properties it writes: they are what the $ref names, so they restate nothing +// beside it, and the Model composing itself holds them. +func TestRestatedProperties_ASchemaNamingItselfKeepsItsProperties(t *testing.T) { + t.Parallel() + for _, allOf := range []string{"[{$ref: '#/components/schemas/A'}]", "[{allOf: [{$ref: '#/components/schemas/A'}]}]"} { + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " A: {type: object, properties: {a: {type: string}}, allOf: "+allOf+"}\n")) + model, ok := typeByName(doc, "A").(*ir.Model) + require.True(t, ok, "%s: got %T", allOf, typeByName(doc, "A")) + assert.Len(t, model.Properties, 1, allOf) + } +} + +// TestRestatedProperties_AnEntrySayingMoreComposes holds entries beside the +// $ref whose properties do not restate the referent's: one property of +// another type, one differing by a note, and one the referent lacks, alone or +// beside one it restates. Each says something, so the position composes a +// Model holding the entry's properties beside its Base. +func TestRestatedProperties_AnEntrySayingMoreComposes(t *testing.T) { + t.Parallel() + for _, entry := range []string{ + "{type: object, properties: {a: {type: string}, b: {type: string}}}", + "{type: object, properties: {a: {type: string, description: d}, b: {type: integer}}}", + "{type: object, properties: {c: {type: string}}}", + "{type: object, properties: {a: {type: string}, c: {type: string}}}", + } { + doc, _ := restatedAt(t, entry) + for _, name := range []string{"S", "H"} { + typeDef := typeByName(doc, name) + if name == "H" { + typeDef = doc.Types[propertyOf(t, doc, "H", "p").Type.Target] + } + model, ok := typeDef.(*ir.Model) + require.True(t, ok, "%s %s: got %T", entry, name, typeDef) + require.NotNil(t, model.Base, "%s %s", entry, name) + assert.Equal(t, componentID("Obj"), model.Base.Target, "%s %s", entry, name) + assert.NotEmpty(t, model.Properties, "%s %s: the entry's properties are its own", entry, name) + } + } +} + +// TestRestatedProperties_ACopyInAnotherDocumentRestatesWhereItReadsAlike +// holds an entry restating, as written, the property the schema its $ref names +// declares in another document, in either order of the entries: each read in +// its own document, the copy restates it where the two read alike, its +// references landing on one target, and the position then declares no member +// of its own; it says something where a relative $ref lands on each +// document's own schema, or where the documents read schemas by another +// dialect, and the member is folded there. +func TestRestatedProperties_ACopyInAnotherDocumentRestatesWhereItReadsAlike(t *testing.T) { + t.Parallel() + common := "openapi: 3.1.0\ninfo: {title: c, version: '1'}\npaths: {}\ncomponents:\n schemas:\n X: {type: string, maxLength: 3}\n" + for name, testCase := range map[string]struct { + version, declaration string + restates bool + }{ + "no reference": {"3.1.0", "{type: string}", true}, + "a reference landing alike": {"3.1.0", "{$ref: 'common.yaml#/components/schemas/X'}", true}, + "a relative reference landing apart": {"3.1.0", "{$ref: '#/components/schemas/X'}", false}, + "another dialect": {"3.0.3", "{type: string}", false}, + "a reference alone, another dialect": {"3.0.3", "{$ref: 'common.yaml#/components/schemas/X'}", true}, + } { + other := "openapi: " + testCase.version + "\ninfo: {title: o, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + + " X: {type: integer}\n S: {type: object, properties: {a: " + testCase.declaration + "}}\n" + for _, refFirst := range []bool{true, false} { + entries := []string{"{$ref: 'other.yaml#/components/schemas/S'}", "{type: object, properties: {a: " + testCase.declaration + "}}"} + if !refFirst { + entries[0], entries[1] = entries[1], entries[0] + } + root := openapitest.ComponentSpecVer("3.1.0", " X: {type: boolean}\n M: {allOf: ["+entries[0]+", "+entries[1]+"]}\n") + doc, diags, _ := compileFiles(t, map[string]string{"other.yaml": other, "common.yaml": common}, root, + openapi.Options{AllowExternalRefs: true}) + + openapitest.RequireNoErrorDiags(t, diags) + model, isModel := typeByName(doc, "M").(*ir.Model) + require.True(t, isModel, "%s, $ref first %t", name, refFirst) + declares := slices.ContainsFunc(model.Properties, func(property ir.Property) bool { return property.WireName == "a" }) + assert.Equal(t, !testCase.restates, declares, "%s, $ref first %t: M declares a member of its own", name, refFirst) + } + } +} diff --git a/compilers/openapi/internal/schema/restated_referent_test.go b/compilers/openapi/internal/schema/restated_referent_test.go new file mode 100644 index 000000000..c89d27c9f --- /dev/null +++ b/compilers/openapi/internal/schema/restated_referent_test.go @@ -0,0 +1,161 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// restatedTargets are list targets an entry's items is written beside: each +// list's items a $ref to an element, the element written plainly, with a note +// beside it, with another extension, with a bound, with a keyword written as +// left out, with an anchor or an identifier, or naming nothing. +const restatedTargets = ` Flag: {type: string, x-auditable: true} + Noted: {type: string, x-auditable: true, description: a flag} + Extended: {type: string, x-auditable: true, x-other: 1} + Short: {type: string, x-auditable: true, maxLength: 3} + Unbounded: {type: string, x-auditable: true, minLength: 0, readOnly: false, uniqueItems: false} + Flags: {type: array, items: {$ref: '#/components/schemas/Flag'}} + NotedFlags: {type: array, items: {$ref: '#/components/schemas/Noted'}} + ExtendedFlags: {type: array, items: {$ref: '#/components/schemas/Extended'}} + ShortFlags: {type: array, items: {$ref: '#/components/schemas/Short'}} + UnboundedFlags: {type: array, items: {$ref: '#/components/schemas/Unbounded'}} + GhostFlags: {type: array, items: {$ref: '#/components/schemas/Missing'}} + Anchored: {type: string, x-auditable: true, $anchor: flag} + Identified: {type: string, x-auditable: true, $id: 'https://example.com/flag'} + AnchoredFlags: {type: array, items: {$ref: '#/components/schemas/Anchored'}} + IdentifiedFlags: {type: array, items: {$ref: '#/components/schemas/Identified'}} +` + +// TestRestatedReferent_AnEntryRestatingTheReferentsKeywordSaysNothing pins an +// entry's items beside a $ref principal compared with the referent's items, +// its own $ref resolved once: where the referent's element writes each key the +// entry's does alike, and otherwise notes and extensions alone, the entry says +// nothing and the property keeps and reports nothing, a key either side writes +// as the keyword left out saying nothing; where either writes a bound the +// other lacks, or the referent's $ref names nothing, the entry is kept. A $ref +// naming nothing cuts no read, so none of them is a Model. +func TestRestatedReferent_AnEntryRestatingTheReferentsKeywordSaysNothing(t *testing.T) { + t.Parallel() + const entry = "{type: string, x-auditable: true}" + const unbounded = "{type: string, x-auditable: true, minLength: 0, readOnly: false, uniqueItems: false}" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", restatedTargets+` Holder: + type: object + properties: + same: {allOf: [{$ref: '#/components/schemas/Flags'}, {items: `+entry+`}]} + noted: {allOf: [{$ref: '#/components/schemas/NotedFlags'}, {items: `+entry+`}]} + extended: {allOf: [{$ref: '#/components/schemas/ExtendedFlags'}, {items: `+entry+`}]} + unboundedTarget: {allOf: [{$ref: '#/components/schemas/UnboundedFlags'}, {items: `+entry+`}]} + unboundedEntry: {allOf: [{$ref: '#/components/schemas/Flags'}, {items: `+unbounded+`}]} + unboundedBoth: {allOf: [{$ref: '#/components/schemas/UnboundedFlags'}, {items: `+unbounded+`}]} + narrower: {allOf: [{$ref: '#/components/schemas/Flags'}, {items: {type: string, x-auditable: true, maxLength: 3}}]} + wider: {allOf: [{$ref: '#/components/schemas/ShortFlags'}, {items: `+entry+`}]} + ghost: {allOf: [{$ref: '#/components/schemas/GhostFlags'}, {items: `+entry+`}]} + anchored: {allOf: [{$ref: '#/components/schemas/AnchoredFlags'}, {items: `+entry+`}]} + identified: {allOf: [{$ref: '#/components/schemas/IdentifiedFlags'}, {items: `+entry+`}]} + UnboundedComponent: {allOf: [{$ref: '#/components/schemas/Flags'}, {items: `+unbounded+`}]} +`)) + for wire, kept := range map[string]bool{ + "same": false, "noted": false, "extended": false, "unboundedTarget": false, "unboundedEntry": false, "unboundedBoth": false, + "narrower": true, "wider": true, "ghost": true, "anchored": false, "identified": false, + } { + property := propertyOf(t, doc, "Holder", wire) + at := "/components/schemas/Holder/properties/" + wire + "/allOf/1" + if !kept { + assert.Empty(t, property.Unmodeled, "%s restates its referent's items", wire) + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, at), wire) + continue + } + held := property.Unmodeled + if node, owned := doc.Types[property.Type.Target]; owned && node.Common().Provenance.Pointer == jsontext.Pointer(at[:len(at)-len("/allOf/1")]) { + held = node.Common().Unmodeled + } + assert.Contains(t, held, "openapi:items", "%s says something of its own", wire) + _, composed := doc.Types[property.Type.Target].(*ir.Model) + assert.False(t, composed, "%s: the kinds are an array alone, so no Model", wire) + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, at), 1, wire) + } + component := typeByName(doc, "UnboundedComponent") + require.NotNil(t, component) + assert.Empty(t, component.Common().Unmodeled, "a component restating its referent keeps nothing") + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/UnboundedComponent/allOf/1")) +} + +// TestRestatedReferent_ACopyInAnotherDocumentRestatesWhereItReadsAlike pins +// the comparison across documents: an entry's items written alike with the +// items of a referent in another document, each read in its own document, +// restate them where the two read alike, by one dialect and with no reference +// landing apart, so the entry is consumed, as in one document. +func TestRestatedReferent_ACopyInAnotherDocumentRestatesWhereItReadsAlike(t *testing.T) { + t.Parallel() + doc, diags, _ := compileBeside(t, map[string]string{"other.yaml": openapitest.ComponentSpecVer("3.1.0", restatedTargets)}, + openapitest.ComponentSpecVer("3.1.0", ` Holder: + type: object + properties: + f: {allOf: [{$ref: 'other.yaml#/components/schemas/Flags'}, {items: {type: string, x-auditable: true}}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + assert.NotContains(t, propertyOf(t, doc, "Holder", "f").Unmodeled, "openapi:items") +} + +// TestRestatedReferent_TwoRefsReadAgainstDifferentBasesSayDifferently pins +// the other half of reading alike: in one document, an entry's items writing +// the same $ref text as its referent's restates it only where both read the +// $ref against one base. Under H's $id, `#/$defs/E` names H's integer, not the +// string L's names, so H keeps its entry, while K, under L's base, consumes it. +func TestRestatedReferent_TwoRefsReadAgainstDifferentBasesSayDifferently(t *testing.T) { + t.Parallel() + const items = "{type: array, items: {type: array, items: {$ref: '#/$defs/E'}}}" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` L: + $id: 'https://x.example/l' + type: array + items: {type: array, items: {$ref: '#/$defs/E'}, description: d} + $defs: + E: {type: string} + K: + type: object + properties: + p: {allOf: [{$ref: '#'}, `+items+`]} + H: + $id: 'https://x.example/h' + type: object + properties: + p: {allOf: [{$ref: 'https://x.example/l'}, `+items+`]} + $defs: {E: {type: integer}} + R: {$ref: 'https://x.example/l#/$defs/K'} +`)) + openapitest.RequireNoErrorDiags(t, diags) + assert.Contains(t, propertyOf(t, doc, "H", "p").Unmodeled, "openapi:items", "another base reads another E") + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/H/properties/p/allOf/1"), 1) + k, ok := doc.Types["type/anonymous/components/schemas/L/$defs/K"].(*ir.Model) + require.True(t, ok, "K is a model") + p, ok := openapitest.PropertiesByWire(k.Properties)["p"] + require.True(t, ok) + assert.Empty(t, p.Unmodeled, "under one base the entry restates L's items") + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/L/$defs/K/properties/p/allOf/1")) +} + +// TestCensus_AnAbsentValueBesideAKeptKeywordIsNoSecondWriting pins the census +// of what the conjuncts of a kept keyword write: a position writing it at the +// value its dialect equates with its absence writes nothing, so the entry's +// value is the one writing, kept and reported as with the position saying +// nothing. +func TestCensus_AnAbsentValueBesideAKeptKeywordIsNoSecondWriting(t *testing.T) { + t.Parallel() + const targets = " Str: {type: string}\n" + written, writtenDiags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", targets+ + " S: {allOf: [{$ref: '#/components/schemas/Str'}, {uniqueItems: true}], uniqueItems: false}\n")) + sayingNothing, diagsSayingNothing := parseFull(t, openapitest.ComponentSpecVer("3.1.0", targets+ + " S: {allOf: [{$ref: '#/components/schemas/Str'}, {uniqueItems: true}]}\n")) + assert.Equal(t, typeByName(sayingNothing, "S").Common().Unmodeled, typeByName(written, "S").Common().Unmodeled) + assert.Equal(t, openapitest.PointersOf(diagsSayingNothing, diag.DegradedConstruct), openapitest.PointersOf(writtenDiags, diag.DegradedConstruct)) +} diff --git a/compilers/openapi/internal/schema/samemeaning.go b/compilers/openapi/internal/schema/samemeaning.go new file mode 100644 index 000000000..a5af73f60 --- /dev/null +++ b/compilers/openapi/internal/schema/samemeaning.go @@ -0,0 +1,394 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "bytes" + "encoding/json/jsontext" + "encoding/json/v2" + "iter" + "maps" + "slices" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/merge" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/ir" +) + +// maxMeaningPairs bounds the pairs of nodes one judgment of meaning compares +// (styleguide bounded-everything rule). A judgment past it shows nothing, so +// the two it was asked of are not alike. +const maxMeaningPairs = 1024 + +// sameMeaning judges whether two declarations admit exactly the same values, +// each read in its own document and dialect (docs/compilers/openapi.md#allof-refinement). +// Where that cannot be shown, they are not alike. +type sameMeaning struct { + loweringContext lowering.Ctx + // nodes finds the ID of the node lowered at a coordinate, and the node + // an ID names: before the nodes are lowered it finds none, so a judgment + // then reads two targets alike only where they are one. + nodes loweredNodes + // judged holds each pair of nodes compared, taken as alike while it is + // compared, so a cycle of references ends; comparisonsLeft counts what may + // still be. + judged map[[2]ir.TypeID]bool + comparisonsLeft int + // annotated says the judgment also reads whether the first node of each pair + // carries every annotation the second gives (carries), and firstDropsAnnotation + // that one pair's first does not. + annotated, firstDropsAnnotation bool +} + +// loweredNodes finds the nodes a judgment of meaning reads (sameMeaning). +type loweredNodes struct { + at func(coordinate string) (ir.TypeID, bool) + node func(ir.TypeID) (ir.TypeDef, bool) +} + +// newSameMeaning returns a judgment of meaning reading the nodes found. +func newSameMeaning(loweringContext lowering.Ctx, found loweredNodes) *sameMeaning { + return &sameMeaning{loweringContext: loweringContext, nodes: found, judged: map[[2]ir.TypeID]bool{}, comparisonsLeft: maxMeaningPairs} +} + +// noneLowered finds no node: a judgment before the nodes are lowered. +func noneLowered() loweredNodes { + return loweredNodes{at: func(string) (ir.TypeID, bool) { return "", false }, node: ir.TypeRegistry(nil).Lookup} +} + +// declarations reports whether the declarations at a and at b admit alike: +// their lowered nodes where a node sits at each, else the text each +// writes. A site no document the compile read places is no match. +func (m *sameMeaning) declarations(a, b ir.Provenance) bool { + ina, placedA := lowering.InDocumentOf(m.loweringContext, a) + inb, placedB := lowering.InDocumentOf(m.loweringContext, b) + if !placedA || !placedB { + return false + } + nodeA, heldA := m.nodes.at(ina.IDs().Coordinate(a.Pointer)) + nodeB, heldB := m.nodes.at(inb.IDs().Coordinate(b.Pointer)) + if heldA || heldB { + return heldA && heldB && m.admitAlike([][2]ir.TypeID{{nodeA, nodeB}}) + } + atA, atB := ina.Position(a.Pointer), inb.Position(b.Pointer) + text := writtenText(ina, ina.Statements().At(atA)) + return text != nil && bytes.Equal(text, writtenText(inb, inb.Statements().At(atB))) && m.text(atA, atB, text) +} + +// text reports whether text, written alike at a and at b, says the same at +// both (textPairs), the nodes its references land on admitting alike. +func (m *sameMeaning) text(a, b reftable.DocumentPointer, text ir.RawValue) bool { + pairs, alike := m.textPairs(a, b, text) + return alike && m.admitAlike(pairs) +} + +// textPairs reports whether text, written alike at a and at b, can say the +// same at both, and returns the pairs of nodes its references land on, each of +// which must admit alike for it to. A reference alone reads alike in every +// dialect. Text whose references cannot all be read, or one landing on no +// node, is not alike. +func (m *sameMeaning) textPairs(a, b reftable.DocumentPointer, text ir.RawValue) ([][2]ir.TypeID, bool) { + if !m.loweringContext.Rules().At(a).ReadsAlike(m.loweringContext.Rules().At(b)) && !annotation.ReferenceAlone(text) { + return nil, false + } + if !annotation.WritesReference(text) { + return nil, true + } + // The same text read against one base names what it names alike. + table := m.loweringContext.Bindings().Table() + baseA, knownA := table.Base(a) + baseB, knownB := table.Base(b) + if knownA && knownB && baseA == baseB { + return nil, true + } + sites, read := annotation.ReferenceSites(text) + var pairs [][2]ir.TypeID + for _, site := range sites { + atA, heldA := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: a.Doc, Pointer: a.Pointer + site}) + atB, heldB := table.ReferenceSiteAt(reftable.DocumentPointer{Doc: b.Doc, Pointer: b.Pointer + site}) + pair, lands := m.targets(atA.Hop.Target, atB.Hop.Target) + if !heldA || !heldB || atA.Hop.Status != reftable.Resolved || atB.Hop.Status != reftable.Resolved || + atA.Keyword != atB.Keyword || !lands { + return nil, false + } + pairs = append(pairs, pair) + } + return pairs, read +} + +// targets returns the nodes the schemas two references land on lowered to, +// one node twice for one target, and false where either lowered to none. +func (m *sameMeaning) targets(a, b reftable.DocumentPointer) ([2]ir.TypeID, bool) { + ina, placedA := lowering.InDocument(m.loweringContext, a.Doc) + inb, placedB := lowering.InDocument(m.loweringContext, b.Doc) + nodeA, heldA := m.nodes.at(ina.IDs().Coordinate(a.Pointer)) + nodeB, heldB := m.nodes.at(inb.IDs().Coordinate(b.Pointer)) + if a == b { + return [2]ir.TypeID{nodeA, nodeA}, true + } + return [2]ir.TypeID{nodeA, nodeB}, placedA && placedB && heldA && heldB +} + +// admitAlike reports whether the two nodes of each of pairs admit alike +// (nodePairs). A pair met again is taken as alike, so a cycle ends; past the +// judgment's bound, nothing is shown. An annotated judgment reads each pair's +// annotations too. +func (m *sameMeaning) admitAlike(pairs [][2]ir.TypeID) bool { + for queue := pairs; len(queue) > 0; queue = queue[1:] { + entry := queue[0] + pair := [2]ir.TypeID{m.throughBareAliases(entry[0]), m.throughBareAliases(entry[1])} + if pair[0] != pair[1] && !m.judged[pair] { + more, alike := m.judgePair(pair) + if !alike { + return false + } + queue = append(queue, more...) + } + m.readAnnotations(entry) + } + return true +} + +// judgePair returns the pairs the nodes of pair name where the two can admit +// alike (nodePairs), taking pair as alike from then on, and false past the +// judgment's bound. +func (m *sameMeaning) judgePair(pair [2]ir.TypeID) ([][2]ir.TypeID, bool) { + if m.comparisonsLeft == 0 { + return nil, false + } + m.comparisonsLeft-- + m.judged[pair] = true + return m.nodePairs(pair[0], pair[1]) +} + +// annotationsCarried reports whether kept and other admit alike and, where +// they do, whether kept's nodes carry every annotation other's give. +func (m *sameMeaning) annotationsCarried(kept, other ir.TypeID) merge.AnnotationCarriage { + m.annotated = true + switch { + case !m.admitAlike([][2]ir.TypeID{{kept, other}}): + return merge.TypesAdmitApart + case m.firstDropsAnnotation: + return merge.AlikeAnnotatedApart + default: + return merge.AlikeAnnotationsCarried + } +} + +// readAnnotations notes, in an annotated judgment, a pair whose first node +// does not carry every annotation its second gives (carries). +func (m *sameMeaning) readAnnotations(pair [2]ir.TypeID) { + if m.annotated && !m.firstDropsAnnotation && !m.carries(pair[0], pair[1]) { + m.firstDropsAnnotation = true + } +} + +// nodePairs reports whether the nodes a and b can admit alike, being of one +// kind and encoded alike but for what places and names them, and returns the +// pairs of nodes they do where each pair does: the nodes they name, and those +// the references they keep verbatim land on (textPairs). +func (m *sameMeaning) nodePairs(a, b ir.TypeID) ([][2]ir.TypeID, bool) { + nodeA, heldA := m.nodes.node(a) + nodeB, heldB := m.nodes.node(b) + if !heldA || !heldB || nodeA.Kind() != nodeB.Kind() { + return nil, false + } + edgesA, edgesB := slices.Collect(ir.TypeEdges(nodeA)), slices.Collect(ir.TypeEdges(nodeB)) + textA, encodesA := meaningText(nodeA, edgesA) + textB, encodesB := meaningText(nodeB, edgesB) + if !encodesA || !encodesB || textA != textB || len(edgesA) != len(edgesB) { + return nil, false + } + pairs := make([][2]ir.TypeID, 0, len(edgesA)) + for i := range edgesA { + pairs = append(pairs, [2]ir.TypeID{edgesA[i], edgesB[i]}) + } + keptA, keptB := keptTexts(nodeA), keptTexts(nodeB) + for i := range keptA { + inA, placedA := lowering.InDocumentOf(m.loweringContext, keptA[i].Provenance) + inB, placedB := lowering.InDocumentOf(m.loweringContext, keptB[i].Provenance) + more, alike := m.textPairs(inA.Position(keptA[i].Provenance.Pointer), inB.Position(keptB[i].Provenance.Pointer), keptA[i].Value) + if !placedA || !placedB || !alike { + return nil, false + } + pairs = append(pairs, more...) + } + return pairs, true +} + +// throughBareAliases returns id, or, where it names an alias adding nothing to +// the node it names (bareAlias), the node its chain of such aliases ends on +// (bareAliasChain): an alias adding nothing admits what its chain's end does. +func (m *sameMeaning) throughBareAliases(id ir.TypeID) ir.TypeID { + end := id + for at := range m.bareAliasChain(id) { + end = at + } + return end +} + +// bareAliasChain yields id, then each node its chain of bare aliases +// (bareAlias) reaches, in order. A chain longer than the judgment's bound ends +// where the bound does, after maxMeaningPairs steps. +func (m *sameMeaning) bareAliasChain(id ir.TypeID) iter.Seq[ir.TypeID] { + return func(yield func(ir.TypeID) bool) { + for step := 0; yield(id) && step < maxMeaningPairs; step++ { + base, bare := bareAlias(m.nodes.node(id)) + if !bare { + return + } + id = base + } + } +} + +// bareAlias returns the node node names as its Base, where it is a Scalar or a +// Model saying nothing beside that Base, which admits no null. +func bareAlias(node ir.TypeDef, held bool) (ir.TypeID, bool) { + if !held || ir.IsNilTypeDef(node) { + return "", false + } + var base *ir.TypeRef + var bare, empty ir.TypeDef + switch typed := node.(type) { + case *ir.Scalar: + alone := *typed + base, alone.Base, bare, empty = typed.Base, nil, &alone, &ir.Scalar{} + case *ir.Model: + alone := *typed + base, alone.Base, bare, empty = typed.Base, nil, &alone, &ir.Model{} + default: + return "", false + } + if base == nil || base.Nullable { + return "", false + } + textBare, encodes := meaningText(bare, nil) + textEmpty, _ := meaningText(empty, nil) + return base.Target, encodes && textBare == textEmpty +} + +// keptTexts returns the entries typeDef keeps verbatim that write a reference +// (annotation.WritesReference), its own and then each property's, each set by +// key. +func keptTexts(typeDef ir.TypeDef) []ir.UnmodeledEntry { + sets := []ir.Unmodeled{typeDef.Common().Unmodeled} + if model, isModel := typeDef.(*ir.Model); isModel { + for _, property := range model.Properties { + sets = append(sets, property.Unmodeled) + } + } + var out []ir.UnmodeledEntry + for _, set := range sets { + for _, key := range slices.Sorted(maps.Keys(set)) { + if annotation.WritesReference(set[key].Value) { + out = append(out, set[key]) + } + } + } + return out +} + +// placingMembers are the members of a node's encoding that say where it and +// what it holds were written, how they are named and documented, none of which +// changes what it admits. +var placingMembers = map[string]bool{"id": true, "provenance": true, "name": true, "anonymous": true, "docs": true, "deprecation": true} + +// meaningText is typeDef's encoding as a stream of tokens, less each member +// placingMembers names and with each ID of edges, the nodes it names, spelled +// alike, so two nodes admitting alike but placed apart read alike. A value kept +// verbatim reads as written (encodingTokens). It is false where typeDef does +// not encode. +func meaningText(typeDef ir.TypeDef, edges []ir.TypeID) (string, bool) { + raw, err := json.Marshal(typeDef, json.Deterministic(true)) + if err != nil { + return "", false + } + edgeTexts := make(map[string]bool, len(edges)) + for _, edge := range edges { + edgeTexts[string(edge)] = true + } + tokens := newEncodingTokens(raw) + var out strings.Builder + skipAt := -1 + for token, place, err := tokens.next(); err == nil; token, place, err = tokens.next() { + // A token is read before the decoder moves on, which voids it. + text, tokenKind := token.String(), token.Kind() + depth := tokens.dec.StackDepth() + switch { + case skipAt >= 0: + // The member's value ends with a token back at the member's depth. + if depth == skipAt { + skipAt = -1 + } + case place == encodedName && placingMembers[text] && (text != "name" || tokens.dec.PeekKind() == '{'): + // A name is a node's or a member's Naming, an object; an encoding's + // or XML hint's name, a string, says what it reads. + skipAt = depth + case place != verbatimToken && tokenKind == '"' && edgeTexts[text]: + out.WriteString("\"\x00") + default: + out.WriteString(tokenKind.String() + text + "\x00") + } + } + return out.String(), true +} + +// tokenPlace is where in a node's encoding a token sits (encodingTokens). +type tokenPlace uint8 + +const ( + // encodedToken is a token of the IR's encoding that names no member. + encodedToken tokenPlace = iota + // encodedName names a member of an object the IR's encoding writes. + encodedName + // verbatimToken is a token of a value kept verbatim under Unmodeled, + // which says what the source wrote, whatever the names in it. + verbatimToken +) + +// encodingTokens reads a node's encoding token by token, telling the members +// the IR's encoding names from the tokens of a value kept verbatim under +// Unmodeled, where a member spelt "id" or "docs" is the source's own. +type encodingTokens struct { + dec *jsontext.Decoder + // verbatimAt is the depth of the Unmodeled entry whose value is being + // read, and -1 outside one. + verbatimAt int +} + +// newEncodingTokens reads raw, a node's encoding. +func newEncodingTokens(raw []byte) *encodingTokens { + return &encodingTokens{dec: jsontext.NewDecoder(bytes.NewReader(raw)), verbatimAt: -1} +} + +// next reads the next token, and where it sits. +func (t *encodingTokens) next() (jsontext.Token, tokenPlace, error) { + token, err := t.dec.ReadToken() + depth := t.dec.StackDepth() + if t.verbatimAt >= 0 { + // The value ends with a token back at its entry's depth. + if depth == t.verbatimAt { + t.verbatimAt = -1 + } + return token, verbatimToken, err + } + kind, n := t.dec.StackIndex(depth) + if kind != '{' || n%2 != 1 { + return token, encodedToken, err + } + if token.String() == "value" && keptVerbatimAt(t.dec.StackPointer()) { + t.verbatimAt = depth + } + return token, encodedName, err +} + +// keptVerbatimAt reports whether at is where an Unmodeled entry's value +// sits, which holds the source's own text. +func keptVerbatimAt(at jsontext.Pointer) bool { + return at.LastToken() == "value" && at.Parent().Parent().LastToken() == "unmodeled" +} diff --git a/compilers/openapi/internal/schema/samemeaning_internal_test.go b/compilers/openapi/internal/schema/samemeaning_internal_test.go new file mode 100644 index 000000000..45e8f5c0f --- /dev/null +++ b/compilers/openapi/internal/schema/samemeaning_internal_test.go @@ -0,0 +1,152 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// meaningFixture lowers schemas, one document's components, settles them, and +// returns the walk asking DeclarationsAdmitAlike of them, with its registry, and where each +// named component is written. +func meaningFixture(t *testing.T, schemas string) (modelFields, ir.TypeRegistry, func(string) ir.Provenance) { + t.Helper() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", schemas)) + lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) + doc := lowerer.Document(t) + membersOf(lowerer.Ctx).reg = doc.Types + at := func(name string) ir.Provenance { + return lowerer.Ctx.Place().At(jsontext.Pointer("/components/schemas/" + name)) + } + return modelFields{loweringContext: lowerer.Ctx, types: lowerer.Types}, doc.Types, at +} + +// TestDeclarationsAdmitAlike_DeclarationsAreAlikeWhereTheyAdmitAlike pins Alike read on what +// each declaration admits, in one document, so against one base: two nodes +// alike but for where they sit are alike, as are two texts written alike, +// two models naming themselves alike, and a model, an alias of it adding +// nothing and an inline copy of it; two with different bounds, value sets +// or kinds, an alias adding a bound beside a copy or its base, two keeping +// text apart under a member spelt id or docs, or one lowered beside one +// not, are not, nor is a site no document places. +func TestDeclarationsAdmitAlike_DeclarationsAreAlikeWhereTheyAdmitAlike(t *testing.T) { + t.Parallel() + fields, _, at := meaningFixture(t, ` P3: {type: string, maxLength: 3} + Q3: {type: string, maxLength: 3} + P5: {type: string, maxLength: 5} + E1: {type: string, enum: [a, b]} + E2: {type: string, enum: [a, b]} + E3: {type: string, enum: [a, c]} + L1: {type: object, properties: {next: {$ref: '#/components/schemas/L1'}}} + L2: {type: object, properties: {next: {$ref: '#/components/schemas/L2'}}} + N1: {type: string, not: {$ref: '#/components/schemas/E1'}} + N2: {type: string, not: {$ref: '#/components/schemas/E1'}} + H: {type: object, properties: {a: {type: string, not: {$ref: '#/components/schemas/E1'}}, b: {type: string, not: {$ref: '#/components/schemas/E1'}}}} + M3: {type: object, properties: {p: {$ref: '#/components/schemas/P3'}}} + MQ: {type: object, properties: {p: {$ref: '#/components/schemas/Q3'}}} + M5: {type: object, properties: {p: {$ref: '#/components/schemas/P5'}}} + Obj: {type: object, properties: {x: {type: string}}} + Alias: {$ref: '#/components/schemas/Obj'} + Bounded: {allOf: [{$ref: '#/components/schemas/Obj'}], maxProperties: 3} + Holder: {type: object, properties: {copy: {type: object, properties: {x: {type: string}}}}} + I1: {type: object, not: {properties: {id: {const: 1}}}} + I1b: {type: object, not: {properties: {id: {const: 1}}}} + I2: {type: object, not: {properties: {id: {const: 2}}}} + D1: {type: object, not: {properties: {docs: {const: 1}}}} + D2: {type: object, not: {properties: {docs: {const: 2}}}} +`) + property := func(name string) ir.Provenance { + provenance := at("H") + provenance.Pointer += jsontext.Pointer("/properties/" + name + "/not") + return provenance + } + copied := at("Holder") + copied.Pointer += "/properties/copy" + nowhere := at("P3") + nowhere.Source = 99 + for name, testCase := range map[string]struct { + a, b ir.Provenance + want bool + }{ + "alike nodes placed apart": {at("P3"), at("Q3"), true}, + "one base, different bounds": {at("P3"), at("P5"), false}, + "value sets alike": {at("E1"), at("E2"), true}, + "value sets apart": {at("E1"), at("E3"), false}, + "kinds apart": {at("P3"), at("E1"), false}, + "models naming themselves alike": {at("L1"), at("L2"), true}, + "models naming nodes alike": {at("M3"), at("MQ"), true}, + "models naming nodes apart": {at("M3"), at("M5"), false}, + "a model and an alias adding nothing": {at("Obj"), at("Alias"), true}, + "the alias and an inline copy": {at("Alias"), copied, true}, + "the model and an inline copy": {at("Obj"), copied, true}, + "an alias adding a bound and a copy": {at("Bounded"), copied, false}, + "an alias adding a bound and its base": {at("Bounded"), at("Obj"), false}, + "nodes keeping one reference alike": {at("N1"), at("N2"), true}, + "text written alike, unlowered": {property("a"), property("b"), true}, + "a lowered node beside unlowered text": {at("N1"), property("a"), false}, + "a site no document places": {nowhere, at("P3"), false}, + "kept text alike under a member id": {at("I1"), at("I1b"), true}, + "kept text apart under a member id": {at("I1"), at("I2"), false}, + "kept text apart under a member docs": {at("D1"), at("D2"), false}, + } { + assert.Equal(t, testCase.want, fields.DeclarationsAdmitAlike(testCase.a, testCase.b), name) + } +} + +// TestSameMeaning_ShowsNothingPastItsBoundOrOfANodeThatDoesNotEncode pins the +// limits of a judgment: past the pairs it may compare, and for a node whose +// encoding fails, it shows nothing, so the two are not alike; a node the +// registry does not hold is not alike either. +func TestSameMeaning_ShowsNothingPastItsBoundOrOfANodeThatDoesNotEncode(t *testing.T) { + t.Parallel() + fields, reg, _ := meaningFixture(t, " P3: {type: string, maxLength: 3}\n Q3: {type: string, maxLength: 3}\n") + found := loweredNodes{at: fields.types.Lookup, node: reg.Lookup} + p3, q3 := ir.TypeID("type/openapi/components/schemas/P3"), ir.TypeID("type/openapi/components/schemas/Q3") + + spent := newSameMeaning(fields.loweringContext, found) + spent.comparisonsLeft = 0 + assert.False(t, spent.admitAlike([][2]ir.TypeID{{p3, q3}}), "past the bound") + assert.True(t, newSameMeaning(fields.loweringContext, found).admitAlike([][2]ir.TypeID{{p3, q3}}), "within it") + assert.False(t, newSameMeaning(fields.loweringContext, found).admitAlike([][2]ir.TypeID{{p3, "type/ghost"}}), "a node the registry lacks") + + odd := *reg[q3].(*ir.Scalar) + odd.Unmodeled = ir.Unmodeled{"openapi:x": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue(`{`)}} + reg["type/odd"] = &odd + assert.False(t, newSameMeaning(fields.loweringContext, found).admitAlike([][2]ir.TypeID{{p3, "type/odd"}}), "a node that does not encode") + + stray := *reg[q3].(*ir.Scalar) + stray.Unmodeled = ir.Unmodeled{"openapi:not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{"$ref":"#/x"}`), + Provenance: ir.Provenance{Source: 99, Pointer: "/x"}}} + equivalent := stray + reg["type/stray"], reg["type/twin"] = &stray, &equivalent + assert.False(t, newSameMeaning(fields.loweringContext, found).admitAlike([][2]ir.TypeID{{"type/stray", "type/twin"}}), "an entry kept where no document places it") +} + +// TestBareAliasChain_EndsAtItsEndOrAtTheBound pins the chain of bare aliases a +// judgment reads: from a node, each alias adding nothing to the node it names, +// up to the first node that adds something, and of a chain longer than the +// judgment's bound, the nodes the bound's steps reach. +func TestBareAliasChain_EndsAtItsEndOrAtTheBound(t *testing.T) { + t.Parallel() + reg := ir.TypeRegistry{"type/end": &ir.Scalar{ID: "type/end", Base: &ir.TypeRef{Target: "type/primitive/string", Nullable: true}}} + chainID := func(step int) ir.TypeID { return ir.TypeID("type/alias/" + strconv.Itoa(step)) } + for step := range maxMeaningPairs + 2 { + reg[chainID(step)] = &ir.Scalar{ID: chainID(step), Base: &ir.TypeRef{Target: chainID(step + 1)}} + } + reg["type/short"] = &ir.Scalar{ID: "type/short", Base: &ir.TypeRef{Target: "type/end"}} + judgment := &sameMeaning{nodes: loweredNodes{node: reg.Lookup}} + + assert.Equal(t, []ir.TypeID{"type/short", "type/end"}, slices.Collect(judgment.bareAliasChain("type/short"))) + assert.Equal(t, ir.TypeID("type/end"), judgment.throughBareAliases("type/short")) + assert.Len(t, slices.Collect(judgment.bareAliasChain(chainID(0))), maxMeaningPairs+1, "a chain past the bound") + assert.Equal(t, chainID(maxMeaningPairs), judgment.throughBareAliases(chainID(0)), "a chain past the bound") +} diff --git a/compilers/openapi/internal/schema/samemeaning_test.go b/compilers/openapi/internal/schema/samemeaning_test.go new file mode 100644 index 000000000..bd7ec5e21 --- /dev/null +++ b/compilers/openapi/internal/schema/samemeaning_test.go @@ -0,0 +1,137 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestSameMeaning_ReferencesOfTwoDialectsReadAlikeWhereTheyMeanAlike pins +// the fold's DeclarationsAdmitAlike read as what each declaration admits: two declarations of +// a member, one in a 3.0 document and one in a 3.1 document, whose not writes +// one $ref to each document's own X, keep one entry with no fold report where +// the two X admit exactly the same values, and report the entries given apart +// where the X differ in a bound or a value set. The declaration brought from +// another model stays declared there. +func TestSameMeaning_ReferencesOfTwoDialectsReadAlikeWhereTheyMeanAlike(t *testing.T) { + t.Parallel() + document := func(version, x string) string { + return "openapi: " + version + "\ninfo: {title: o, version: '1'}\npaths: {}\ncomponents:\n schemas:\n" + + " X: " + x + "\n S:\n type: object\n properties:\n a: {type: string, not: {$ref: '#/components/schemas/X'}}\n" + } + root := "openapi: 3.1.0\ninfo: {title: m, version: '1'}\npaths: {}\ncomponents:\n schemas:\n M:\n allOf:\n" + + " - $ref: 'old.yaml#/components/schemas/S'\n - $ref: 'new.yaml#/components/schemas/S'\n" + for name, testCase := range map[string]struct { + oldX, newX string + alike bool + }{ + "meaning alike": {"{type: string, maxLength: 3}", "{type: string, maxLength: 3}", true}, + "bounds apart": {"{type: string, maxLength: 3}", "{type: string, maxLength: 5}", false}, + "value sets alike": {"{type: string, enum: [bad]}", "{type: string, enum: [bad]}", true}, + "value sets apart": {"{type: string, enum: [bad]}", "{type: string, enum: [worse]}", false}, + } { + doc, diags, _ := compileFiles(t, map[string]string{"old.yaml": document("3.0.3", testCase.oldX), "new.yaml": document("3.1.0", testCase.newX)}, + root, openapi.Options{AllowExternalRefs: true}) + + model, isModel := typeByName(doc, "M").(*ir.Model) + require.True(t, isModel, name) + at := slices.IndexFunc(model.Properties, func(property ir.Property) bool { return property.WireName == "a" }) + require.GreaterOrEqual(t, at, 0, "%s: M declares a", name) + var kept []string + for key := range model.Properties[at].Unmodeled { + kept = append(kept, key) + } + assert.Equal(t, []string{"openapi:not"}, kept, "%s: one entry", name) + reported := 0 + for _, diagnostic := range diags { + if strings.Contains(diagnostic.Message, "give its openapi:not differently") { + reported++ + } + } + assert.Equal(t, !testCase.alike, reported == 1, "%s: the entries reported as given apart: %d", name, reported) + } +} + +// TestSameMeaning_AnAliasAndACopyOfItsModelFoldAlikeInEveryOrder pins the +// fold of a member three entries declare as a model, an alias of it adding +// nothing and an inline copy of it, in each of the six orders: the alias, +// read as its chain's end, admits what the copy does, so the three are one +// type, the fold takes the alias in every order, and nothing is lost or +// reported. +func TestSameMeaning_AnAliasAndACopyOfItsModelFoldAlikeInEveryOrder(t *testing.T) { + t.Parallel() + declarations := []string{"{$ref: '#/components/schemas/Obj'}", "{$ref: '#/components/schemas/Alias'}", + "{type: object, properties: {x: {type: string}}}"} + for _, order := range [][]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} { + var entries strings.Builder + for _, at := range order { + entries.WriteString(" - {type: object, properties: {p: " + declarations[at] + "}}\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Obj: {type: object, properties: {x: {type: string}}}\n"+ + " Alias: {$ref: '#/components/schemas/Obj'}\n M:\n allOf:\n"+entries.String())) + + model, isModel := typeByName(doc, "M").(*ir.Model) + require.True(t, isModel, "%v", order) + at := slices.IndexFunc(model.Properties, func(property ir.Property) bool { return property.WireName == "p" }) + require.GreaterOrEqual(t, at, 0, "%v: M declares p", order) + assert.Equal(t, componentID("Alias"), model.Properties[at].Type.Target, "%v", order) + assert.Empty(t, model.Properties[at].Unmodeled, "%v: nothing kept", order) + for _, diagnostic := range diags { + assert.NotContains(t, string(diagnostic.Provenance.Pointer), "/components/schemas/M/allOf", "%v: %s", order, diagnostic.Message) + } + } +} + +// TestSameMeaning_TextKeptVerbatimReadsAsWritten pins a fold of a member two +// entries declare with a not that differs only inside a member spelt as one +// the IR's encoding names: the source wrote each, so the two do not admit +// alike, and both texts are in the document, in either order. +func TestSameMeaning_TextKeptVerbatimReadsAsWritten(t *testing.T) { + t.Parallel() + for _, member := range []string{"id", "name", "docs", "provenance"} { + declarations := []string{"{type: object, not: {properties: {" + member + ": {const: 1}}}}", + "{type: object, not: {properties: {" + member + ": {const: 2}}}}"} + for _, order := range [][]int{{0, 1}, {1, 0}} { + var entries strings.Builder + for _, at := range order { + entries.WriteString(" - {type: object, properties: {p: " + declarations[at] + "}}\n") + } + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " M:\n allOf:\n"+entries.String())) + + kept := keptText(doc) + for _, constant := range []string{`"const":1`, `"const":2`} { + assert.Contains(t, kept, constant, "%s %v", member, order) + } + } + } +} + +// keptText is every value doc's types and their properties keep verbatim +// under Unmodeled, joined. +func keptText(doc *ir.Document) string { + var out strings.Builder + write := func(unmodeled ir.Unmodeled) { + for _, entry := range unmodeled { + out.Write(entry.Value) + } + } + for _, typeDef := range doc.Types { + write(typeDef.Common().Unmodeled) + if model, isModel := typeDef.(*ir.Model); isModel { + for _, property := range model.Properties { + write(property.Unmodeled) + } + } + } + return out.String() +} diff --git a/compilers/openapi/internal/schema/saysnothing_test.go b/compilers/openapi/internal/schema/saysnothing_test.go new file mode 100644 index 000000000..ae29de9b6 --- /dev/null +++ b/compilers/openapi/internal/schema/saysnothing_test.go @@ -0,0 +1,133 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// keysSayingNothing are keys that say nothing of an instance: identifiers and +// meta keywords in each spelling, an anchor, a comment and a keyword written as +// left out. +var keysSayingNothing = []string{ + "$id: 'https://example.com/e'", "id: e", "$schema: 'https://json-schema.org/draft/2020-12/schema'", "$anchor: e", + "$comment: e", "enum: null", +} + +// saysNothingRows are schemas each reader of keys saying nothing reads, each +// written with %s where a key saying nothing may sit: an allOf too long to +// read whole, which cuts its reading (writesPastKinds); an entry of notes +// beside an empty enum (writesNotesOnly); a body beside a union +// (writesBesideUnion); and a union of value sets (writesValueSetOnly). +func saysNothingRows() map[string]string { + long := make([]string, 0, 65) + long = append(long, "{type: string, minLength: 1}", "{type: string, %s}") + for range 63 { + long = append(long, "{type: string}") + } + return map[string]string{ + "Cut": "{allOf: [" + strings.Join(long, ", ") + "]}", + "Notes": "{allOf: [{enum: []}, {const: a}, {description: d, %s}]}", + "Body": "{allOf: [{$ref: '#/components/schemas/B'}], %s, oneOf: [{format: uuid}, {format: date}]}", + "ValueSet": "{type: string, enum: [a, b, c], oneOf: [{const: a, %s}, {const: b}]}", + } +} + +// TestKeysSayingNothing_LowerAsWithout holds each reader of keys saying +// nothing to one reading: each row lowers alike with a key saying nothing +// written where it may sit and without it, but for the identifier kept +// as no part of a type. A $id beside the body's $ref is left out, as it +// moves the base that $ref resolves against. +func TestKeysSayingNothing_LowerAsWithout(t *testing.T) { + t.Parallel() + for name, row := range saysNothingRows() { + for _, key := range keysSayingNothing { + if name == "Body" && strings.HasPrefix(key, "$id") { + continue + } + src := " B: {type: string}\n" + + " Plain: " + strings.Replace(strings.Replace(row, ", %s", "", 1), "%s, ", "", 1) + "\n" + + " Marked: " + strings.Replace(row, "%s", key, 1) + "\n" + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", src)) + label := name + " with " + key + assert.Equal(t, viewSayingNothing(typeByName(doc, "Plain")), viewSayingNothing(typeByName(doc, "Marked")), label) + assert.Equal(t, withoutIdentifiers(findingsBeneath(diags, "/components/schemas/Plain")), + withoutIdentifiers(findingsBeneath(diags, "/components/schemas/Marked")), label) + } + } +} + +// viewSayingNothing is valueSetView of node with its kind's facts beside, the +// keys it keeps for an identifier aside. +func viewSayingNothing(node ir.TypeDef) map[string]any { + view := valueSetView(node) + kept := view["kept"].(map[string]ir.UnmodeledReason) + for key := range kept { + if strings.HasPrefix(key, "openapi:$id") || strings.HasPrefix(key, "openapi:id") || strings.HasPrefix(key, "openapi:$schema") { + delete(kept, key) + } + } + switch typed := node.(type) { + case *ir.Scalar: + view["base"], view["bounds"] = typed.Base, typed.Constraints + case *ir.Union: + view["variants"] = len(typed.Variants) + } + return view +} + +// withoutIdentifiers is findings less what keeping an identifier reports and +// what validating the document reports of a key written as left out. +func withoutIdentifiers(findings []string) []string { + var out []string + for _, finding := range findings { + if !strings.Contains(finding, "$id") && !strings.Contains(finding, "/id") && !strings.Contains(finding, "$schema") && + !strings.Contains(finding, "openapi/validation/") { + out = append(out, finding) + } + } + return out +} + +// TestKeysSayingNothing_ReadAlikeOnAHopAndAReferent holds the readers of a +// hop of a reference chain (saysNothingBeside) and of a mapping restating a +// referent's (restates) to the one reading: a self-reference beside an entry +// writing only a key saying nothing is the loop it is beside an empty entry, +// and an entry restating the items of a referent writing such a key beside +// them restates them still. The loop is read with the keys a hop reads as +// saying nothing: an anchor, a comment and a key written as left out. +func TestKeysSayingNothing_ReadAlikeOnAHopAndAReferent(t *testing.T) { + t.Parallel() + for _, key := range keysSayingNothing { + src := " LoopPlain: {allOf: [{$ref: '#/components/schemas/LoopPlain'}, {}]}\n" + + " RefPlain: {type: array, items: {type: string}}\n" + + " RefMarked: {type: array, items: {type: string, " + key + "}}\n" + + " RestatesPlain: {allOf: [{$ref: '#/components/schemas/RefPlain'}, {items: {type: string}}]}\n" + + " RestatesMarked: {allOf: [{$ref: '#/components/schemas/RefMarked'}, {items: {type: string}}]}\n" + loop := key == "$anchor: e" || key == "$comment: e" || key == "enum: null" + if loop { + src += " LoopMarked: {allOf: [{$ref: '#/components/schemas/LoopMarked'}, {" + key + "}]}\n" + } + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", src)) + if loop { + assert.Equal(t, viewSayingNothing(typeByName(doc, "LoopPlain")), viewSayingNothing(typeByName(doc, "LoopMarked")), "loop with %s", key) + assert.Equal(t, withoutIdentifiers(findingsBeneath(diags, "/components/schemas/LoopPlain")), + withoutIdentifiers(findingsBeneath(diags, "/components/schemas/LoopMarked")), "loop with %s", key) + } + plain, marked := viewSayingNothing(typeByName(doc, "RestatesPlain")), viewSayingNothing(typeByName(doc, "RestatesMarked")) + delete(plain, "base") + delete(marked, "base") + assert.Equal(t, plain, marked, "restating items beside %s", key) + assert.Equal(t, withoutIdentifiers(findingsBeneath(diags, "/components/schemas/RestatesPlain")), + withoutIdentifiers(findingsBeneath(diags, "/components/schemas/RestatesMarked")), + "restating items beside %s", key) + } +} diff --git a/compilers/openapi/internal/schema/scalar.go b/compilers/openapi/internal/schema/scalar.go index 247190fba..8ce3c507d 100644 --- a/compilers/openapi/internal/schema/scalar.go +++ b/compilers/openapi/internal/schema/scalar.go @@ -5,6 +5,7 @@ package schema import ( "encoding/json/jsontext" + "slices" "github.com/dexpace/morphic/compilers/compile" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" @@ -26,16 +27,58 @@ import ( // // byte and a number carried as text put the logical primitive in Base and the // string the value travels as in WireType (docs/compilers/openapi.md#string-formats). -func scalarTypeID(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, kind statement.JSONSchemaTypeName, pointer jsontext.Pointer, - fin finisher, st stand, -) (ir.TypeID, keySet, []ir.Diagnostic) { - shape := scalarShapeOf(schema, kind, writtenFormat(schema)) +func scalarTypeID(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, kind statement.JSONSchemaTypeName, pointer jsontext.Pointer, + homes boundHomes, placement nodePlacement, +) (builtPosition, keySet, []ir.Diagnostic) { + flattenedEntries := placement.flattenedEntries(loweringContext, schema, pointer) + shape := scalarShapeOf(contentConjuncts(schema, pointer, flattenedEntries).encoding.Node, kind, writtenFormat(formatConjunct(schema, "", flattenedEntries).Node)) + shape.shared = shape.shared && !flattenedEntryWritesContent(kind, flattenedEntries) if shape.shared { // The type and the format beside it selected the shared primitive. - return ts.PrimitiveID(shape.base), scalarTypeRead(schema) | shape.read, nil + return builtPosition{id: types.PrimitiveID(shape.base)}, scalarTypeRead(schema) | shape.read, nil } - id, diags := hoistScalar(loweringContext, ts, depth, schema, shape, typeKinds(kind), st.foldedEntries(loweringContext, schema, pointer), pointer, fin, st) - return id, 0, diags + built, diags := hoistScalar(loweringContext, types, depth, schema, shape, takesContent(kindsOfTypeNameOrAny(kind)), homes, flattenedEntries, pointer, placement) + if scalar, ok := built.node.(*ir.Scalar); ok { + // The restriction names the position's schema, where a type list's + // variant names one kind of it, which admits no null of its own. + scalar.Base = new(scalarBase(loweringContext, schema, placement, scalar.Base.Target)) + } + return built, 0, diags +} + +// flattenedEntryWritesContent reports whether a flattened entry writes the +// content vocabulary a Scalar of type typeName takes, so the Scalar is hoisted +// to hold its Encoding. +func flattenedEntryWritesContent(typeName statement.JSONSchemaTypeName, flattenedEntries []annotation.FlattenedAllOfEntry) bool { + return takesContent(kindsOfTypeNameOrAny(typeName)) && slices.ContainsFunc(flattenedEntries, func(flattenedEntry annotation.FlattenedAllOfEntry) bool { + return declaresContentVocabulary(flattenedEntry.Node) + }) +} + +// formatConjunct returns the conjunct whose format the node of schema, written +// at pointer, takes, as a format reaches any conjunct: the narrowest written, +// a redaction aside, else schema (docs/compilers/openapi.md#allof-refinement). +// A flattened entry whose format nests with no other's arrives without it, as +// one its conjuncts write otherwise (foldingNode). +func formatConjunct(schema *statement.Schema, pointer jsontext.Pointer, flattenedEntries []annotation.FlattenedAllOfEntry) annotation.FlattenedAllOfEntry { + narrowest := annotation.FlattenedAllOfEntry{Node: schema, At: pointer} + for _, flattenedEntry := range flattenedEntries { + if writtenFormat(flattenedEntry.Node) == "" { + continue + } + if writtenFormat(narrowest.Node) == "" || narrowerFormat(flattenedEntry.Node, narrowest.Node) { + narrowest = flattenedEntry + } + } + return narrowest +} + +// narrowerFormat reports whether the format a writes selects a primitive +// strictly within the one b's selects (writtenFormatPrimitive). +func narrowerFormat(a, b *statement.Schema) bool { + pa, knownA := writtenFormatPrimitive(a) + pb, knownB := writtenFormatPrimitive(b) + return knownA && knownB && typeformat.Relate(pa, pb) == typeformat.ANarrower } // writtenFormat returns the format schema writes, but for a redaction, which @@ -49,7 +92,7 @@ func writtenFormat(schema *statement.Schema) string { // scalarShape is what a scalar of one type lowers to: the primitive it is over, // the encoding name and wire type a Scalar over that primitive holds, and -// whether the primitive alone says all of it, so the shared one stands for it. +// whether the primitive alone says all of it, so the shared one names it. type scalarShape struct { base ir.PrimitiveKind format string @@ -59,31 +102,63 @@ type scalarShape struct { read keySet } -// scalarShapeOf returns what a scalar of type st that schema writes, with -// format, lowers to: a pairing typeformat.LookupEncoded knows, such as byte, a -// Scalar over the primitive it names with its encoding and wire type; a pairing -// neither table lists a Scalar over the type's base keeping the format as its -// encoding name; and a pairing typeformat.Lookup lists the primitive it -// selects, shared unless schema writes the content vocabulary for a type that -// takes it, a string's (keywordKinds). -func scalarShapeOf(schema *statement.Schema, st statement.JSONSchemaTypeName, format string) scalarShape { - key := string(st) +// scalarShapeOf returns what a scalar of type typeName, with format, lowers to, +// schema writing the contentEncoding beside it, whichever conjunct writes the +// format: a pairing typeformat.LookupEncoded knows, such as byte, a Scalar over +// the primitive it names with its encoding and wire type; a pairing neither +// table lists a Scalar over the type's base keeping the format as its encoding +// name; and a pairing typeformat.Lookup lists the primitive it selects, shared +// unless schema writes the content vocabulary for a type that takes it, a +// string's (typeformat.InstanceKindsKeywordAppliesTo). +func scalarShapeOf(schema *statement.Schema, typeName statement.JSONSchemaTypeName, format string) scalarShape { + key := string(typeName) var read keySet if format != "" { key += "/" + format read = keyBit("format") } + if typeName == statement.KindString && encodedText(schema, format) { + // The string is the encoded text, which the format does not describe: + // the base stays the text, and encodingName keeps the format. + return scalarShape{base: ir.PrimitiveString, format: format, read: read} + } if row, encoded := typeformat.LookupEncoded(key); encoded { return scalarShape{base: row.Primitive, format: row.Encoding, wire: wireOf(row), read: read} } primitive, known := typeformat.Lookup(key) if !known { - if number, carried := numberAsText(schema, st, format); carried { + if number, carried := numberAsText(schema, typeName, format); carried { return scalarShape{base: number, format: numberTextEncoding, wire: new(ir.PrimitiveString), read: read} } - return scalarShape{base: baseForType(st), format: format, read: read} + return scalarShape{base: baseForType(typeName), format: format, read: read} } - return scalarShape{base: primitive, shared: !takesContent(typeKinds(st)) || !declaresContentVocabulary(schema), read: read} + return scalarShape{base: primitive, shared: !takesContent(kindsOfTypeNameOrAny(typeName)) || !declaresContentVocabulary(schema), read: read} +} + +// encodedText reports whether format, written on a string, reads its value +// from the text (formatReadsText), and a contentEncoding beside it names an +// encoding of another name: the string is then that encoding's text, whose +// content once decoded is binary data (JSON Schema Validation 2020-12 §8.3), +// so a format describing the text names no value it holds (§7.3). +func encodedText(schema *statement.Schema, format string) bool { + own, reads := formatReadsText(format) + return reads && contentOverridesFormat(schema, own) +} + +// formatReadsText returns the encoding name format, written on a string, gives +// the value it reads from the text, the format itself where it gives none, and +// whether it reads one: one the tables pair with a string, but over bytes, or +// with a number, written as its text. +func formatReadsText(format string) (string, bool) { + key := string(statement.KindString) + "/" + format + if row, encoded := typeformat.LookupEncoded(key); encoded { + return row.Encoding, row.Primitive != ir.PrimitiveBytes + } + if primitive, known := typeformat.Lookup(key); known { + return format, primitive != ir.PrimitiveBytes + } + _, number := typeformat.Lookup(string(statement.KindNumber) + "/" + format) + return numberTextEncoding, number } // wireOf returns the primitive row's value travels as, the WireType of the @@ -105,8 +180,8 @@ const numberTextEncoding = "string" // number's readers hold may travel. A contentEncoding naming another encoding // says the string is that encoding's text instead, so the format, which // encodingName then keeps verbatim, selects nothing. -func numberAsText(schema *statement.Schema, st statement.JSONSchemaTypeName, format string) (ir.PrimitiveKind, bool) { - if st != statement.KindString || format == "" || contentOverridesFormat(schema, numberTextEncoding) { +func numberAsText(schema *statement.Schema, typeName statement.JSONSchemaTypeName, format string) (ir.PrimitiveKind, bool) { + if typeName != statement.KindString || format == "" || contentOverridesFormat(schema, numberTextEncoding) { return "", false } return typeformat.Lookup(string(statement.KindNumber) + "/" + format) @@ -122,9 +197,10 @@ func formatPrimitive(schema *statement.Schema) (ir.PrimitiveKind, bool) { return typeformat.Lookup(string(types[0]) + "/" + schema.FormatName()) } -// baseForType returns the base primitive for an unknown-format scalar of type st. -func baseForType(st statement.JSONSchemaTypeName) ir.PrimitiveKind { - switch st { +// baseForType returns the base primitive for an unknown-format scalar of type +// typeName. +func baseForType(typeName statement.JSONSchemaTypeName) ir.PrimitiveKind { + switch typeName { case statement.KindInteger: return ir.PrimitiveInteger case statement.KindNumber: @@ -140,32 +216,31 @@ func baseForType(st statement.JSONSchemaTypeName) ir.PrimitiveKind { // position wrote a node of its own: the encoding scalarEncoding builds from the // shape's format name and the wire type it names, if any. // -// The node carries the value constraints schema and foldedEntries, the -// position's, write that apply to the kinds takes, because owning a node is -// what stops hoistDeclarationHome hoisting the alias that would otherwise carry -// them: that fallback resolves to whatever node the pointer already owns. A -// scalar hoisted for its format must not lose the bounds written beside it -// (invariant 2). -// -// fin finishes the Scalar once built. -func hoistScalar(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, shape scalarShape, takes kindSet, - foldedEntries []annotation.FoldedAllOfEntry, pointer jsontext.Pointer, fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { +// The node holds the value constraints schema and flattenedEntries, the +// position's, write of the kinds homes names, and keeps verbatim those of text +// of another kind (keepOwnText): owning a node stops homeDeclaration hoisting +// the alias that would otherwise carry them, resolving to whatever node the +// pointer owns. A scalar hoisted for its format loses no bound written beside +// it (invariant 2). +func hoistScalar(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, shape scalarShape, withContent bool, homes boundHomes, + flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer, placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { var diags []ir.Diagnostic var text []string - if st.of != nil { - // The text bounds of a principal are kept once its position has written. - outer := fin - fin = func(td ir.TypeDef, read keySet, held *principalKept) { - diags = append(diags, keepAround(loweringContext, ts, st, td, read, held, schema, pointer, textBounds(loweringContext, schema, text, pointer), outer)...) + var pendingKeeps annotation.PendingKeeps + keeps := builtKeeps{pendingKeeps: &pendingKeeps, pointer: pointer, placement: placement} + built := internNode(loweringContext, types, placement.pointer(pointer), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + baseRef := types.PrimitiveRef(shape.base) + contentConjuncts := contentConjuncts(schema, pointer, flattenedEntries) + if chain := besideRefOf(loweringContext, placement.positionOrSchema(schema)).chosenEncodingMedia(); chain != nil && !writesMedia(contentConjuncts.media.Node) { + // The contentEncoding chosen beside a $ref reads the target's media + // type and content schema, as its flat twin does. + contentConjuncts.media, contentConjuncts.chained = annotation.FlattenedAllOfEntry{Node: chain}, true } - } - id := internNode(loweringContext, ts, st.pointer(pointer), func(common ir.TypeCommon) (ir.TypeDef, keySet) { - baseRef := ts.PrimitiveRef(shape.base) - enc, encDiags := scalarEncoding(loweringContext, ts, depth, schema, shape.format, takesContent(takes), &common, pointer) + enc, encDiags := scalarEncoding(loweringContext, types, depth, contentConjuncts, shape.format, withContent, &common, keeps) diags = append(diags, encDiags...) if shape.wire != nil { - wireRef := ts.PrimitiveRef(*shape.wire) + wireRef := types.PrimitiveRef(*shape.wire) enc.WireType = &wireRef } if *enc == (ir.Encoding{}) { @@ -173,32 +248,85 @@ func hoistScalar(loweringContext lowering.Ctx, ts *compile.Types, depth int, sch enc = nil } sc := &ir.Scalar{TypeCommon: common, Base: &baseRef, Encoding: enc} - cons, consDiags := ConstraintsOf(loweringContext, &sc.Unmodeled, schema, foldedEntries, pointer, takes) - if carriesNumberAsText(sc) { - cons = nil - switch { - case st.held: - // A variant of a principal held whole keeps none, nor reads them: - // its union keeps them unread for the whole entry. - case st.of != nil: - text = declaredConstraints(schema) - default: - consDiags = append(consDiags, keepTextBounds(loweringContext, &sc.Unmodeled, schema, declaredConstraints(schema), pointer)...) - } + var textDiags []ir.Diagnostic + switch { + case homes.otherText == 0, placement.keptWholeByPosition: + // Its value is text, or it is a variant of a principal held whole, + // which keeps none, nor reads them: its union keeps them unread for + // the whole entry. + case placement.position != nil: + text = writtenKept(schema, homes.otherText) + default: + textDiags = keepOwnText(loweringContext, &sc.Unmodeled, schema, homes, pointer) + } + consDiags := keeps.keep(loweringContext, &sc.Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + cons, kept, reports := boundsKept(loweringContext, *unmodeled, schema, flattenedEntries, pointer, homes.value) + *unmodeled, sc.Constraints = annotation.MergeUnmodeled(*unmodeled, kept), cons + return reports + }) + diags = append(append(diags, textDiags...), consDiags...) + return sc, scalarTypeRead(schema) | shape.read | nodeBoundsRead(schema, homes.value, sc.Constraints, sc.Unmodeled) | keySetOf(text...) | homes.textYields | homes.textIntersection.consumedFrom(schema) + }) + if placement.position != nil && built.node != nil { + // The text bounds of a principal are kept once its position has written. + diags = append(diags, keepTextAround(loweringContext, placement, &built, schema, text, flattenedEntries, pointer, homes)...) + } + // What the build kept on a principal's node is added as pending keeps after + // its readers. + built.pendingKeeps.AddAll(pendingKeeps) + return built, diags +} + +// keepOwnText keeps on unmodeled the value bounds of homes.otherText schema, +// written at pointer, writes on its own Scalar carrying text of another kind, +// but those homes says a flattened entry's value, or the value its conjuncts +// intersect in, replaces, and that value where no conjunct writes it +// (intersectTextBounds). +func keepOwnText(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, homes boundHomes, pointer jsontext.Pointer, +) []ir.Diagnostic { + replaced := homes.textYields | homes.textIntersection.consumedFrom(schema) + own := slices.DeleteFunc(writtenKept(schema, homes.otherText), func(keyword string) bool { return replaced&keyBit(keyword) != 0 }) + diags := keepTextBounds(loweringContext, unmodeled, schema, own, pointer, homes.root) + for _, keyword := range valueConstraintKeywords { + if value, intersected := homes.textIntersection.values[keyword]; intersected { + diags = append(diags, keepIntersectedTextBound(loweringContext, unmodeled, keyword, value, pointer, homes.root)...) + } + } + return diags +} + +// keepTextAround adds pending keeps on built, the node an inline principal +// schema written at pointer builds for placement's position, text, the value +// bounds of homes.otherText schema writes, but those the value its +// flattenedEntries and it intersect in replaces, and that value where none of +// them writes it (intersectTextBounds). A flattened entry writing the +// textIntersection value keeps it where it is read. +func keepTextAround(loweringContext lowering.Ctx, placement nodePlacement, built *builtPosition, schema *statement.Schema, text []string, + flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer, homes boundHomes, +) []ir.Diagnostic { + textIntersection := intersectTextBounds(loweringContext, schema, flattenedEntries, homes.otherText) + replaced := textIntersection.consumedFrom(schema) + own := slices.DeleteFunc(slices.Clone(text), func(keyword string) bool { return replaced&keyBit(keyword) != 0 }) + diags := keepAround(loweringContext, placement, built, schema, pointer, textBounds(loweringContext, schema, own, pointer, homes.root)) + for _, keyword := range valueConstraintKeywords { + value, computed := textIntersection.values[keyword] + if !computed { + continue } - diags = append(diags, consDiags...) - sc.Constraints = cons - return sc, scalarTypeRead(schema) | shape.read | nodeBoundsRead(schema, takes, sc.Constraints, sc.Unmodeled) | keySetOf(text...) - }, fin) - return id, diags + diags = append(diags, keepAround(loweringContext, placement, built, textIntersection.consumed[keyword][0], pointer, keeping{keys: []string{keyword}, reason: ir.ReasonNoIRHome, + keep: func(unmodeled *ir.Unmodeled, _ []string) []ir.Diagnostic { + return keepIntersectedTextBound(loweringContext, unmodeled, keyword, value, pointer, homes.root) + }})...) + } + return diags } // textBounds is the keeping of bounds, the value bounds schema, written at -// pointer, writes on a Scalar carrying a number as text, which holds none of -// them (keepTextBounds). -func textBounds(loweringContext lowering.Ctx, schema *statement.Schema, bounds []string, pointer jsontext.Pointer) keeping { +// pointer, writes on a Scalar carrying text of root's kind, which holds none +// of them (keepTextBounds). +func textBounds(loweringContext lowering.Ctx, schema *statement.Schema, bounds []string, pointer jsontext.Pointer, root boundRoot) keeping { return keeping{keys: bounds, reason: ir.ReasonNoIRHome, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { - return keepTextBounds(loweringContext, unmodeled, schema, keys, pointer) + return keepTextBounds(loweringContext, unmodeled, schema, keys, pointer, root) }} } @@ -208,26 +336,83 @@ func textBounds(loweringContext lowering.Ctx, schema *statement.Schema, bounds [ // encoding name the format contributes — the one typeformat.LookupEncoded names, // as "base64" for format: byte, an unrecognized format verbatim, "" when the // pairing is already captured by the primitive kind. -func scalarEncoding(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, - formatName string, withContent bool, common *ir.TypeCommon, pointer jsontext.Pointer, +func scalarEncoding(loweringContext lowering.Ctx, types *compile.Types, depth int, contentConjuncts contentWriting, + formatName string, withContent bool, common *ir.TypeCommon, keeps builtKeeps, ) (*ir.Encoding, []ir.Diagnostic) { if !withContent { return &ir.Encoding{Name: formatName}, nil } - name, diags := encodingName(loweringContext, schema, formatName, common, pointer) - content, contentDiags := contentSchemaRef(loweringContext, ts, depth, schema, pointer) - enc := &ir.Encoding{Name: name, MediaType: schema.TextKeywords().ContentMediaType, Schema: content} + name := formatName + diags := keeps.keep(loweringContext, &common.Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + var reports annotation.KeptReports + name, reports = encodingName(loweringContext, contentConjuncts, formatName, unmodeled) + return reports + }) + content, contentDiags := contentConjuncts.contentSchema(loweringContext, types, depth) + enc := &ir.Encoding{Name: name, MediaType: contentConjuncts.media.Node.TextKeywords().ContentMediaType, Schema: content} return enc, append(diags, contentDiags...) } -// encodingName elects the one name ir.Encoding holds from the two keywords that -// can name an encoding at a scalar position. +// contentWriting is where a Scalar reads its content vocabulary: the conjunct +// of contentEncoding, and that of contentMediaType with the contentSchema it +// qualifies, one group; the conjunct of the format beside them; and whether +// that group's conjunct is the schema a chain of $refs lands on, read where it +// is written rather than at a conjunct's pointer. +type contentWriting struct { + encoding, media, format annotation.FlattenedAllOfEntry + chained bool +} + +// contentSchema lowers the contentSchema writing's media conjunct writes at +// depth (contentSchemaRef), one a chain of $refs lands on where it is written, +// as its own lowering does, so the two name one node. +func (writing contentWriting) contentSchema(loweringContext lowering.Ctx, types *compile.Types, depth int) (*ir.TypeRef, []ir.Diagnostic) { + if !writing.chained { + return contentSchemaRef(loweringContext, types, depth, writing.media.Node, writing.media.At) + } + cs := loweringContext.Statements().Subschema(writing.media.Node.TextKeywords().ContentSchema) + at, placed := siteOf(writing.media.Node) + inDocument, ok := lowering.InDocument(loweringContext, at.Doc) + if cs.Truth == statement.Unwritten || !placed || !ok { + return nil, nil + } + ref, diags := Ref(inDocument, types, depth, cs, at.Pointer+ids.Ptr("contentSchema")) + return &ref, diags +} + +// contentConjuncts returns the conjuncts of schema's content vocabulary, +// written at pointer: schema where it writes a keyword, else the first of +// flattenedEntries, the conjuncts it is read beside, writing it, as the content +// vocabulary reaches any conjunct (docs/compilers/openapi.md#allof-refinement); +// and of the format (formatConjunct). +func contentConjuncts(schema *statement.Schema, pointer jsontext.Pointer, flattenedEntries []annotation.FlattenedAllOfEntry) contentWriting { + own := annotation.FlattenedAllOfEntry{Node: schema, At: pointer} + flattenedConjunct := func(keywords ...string) annotation.FlattenedAllOfEntry { + writes := func(candidate *statement.Schema) bool { + return slices.ContainsFunc(keywords, func(keyword string) bool { return hasKey(candidate, keyword) }) + } + if writes(schema) { + return own + } + for _, flattenedEntry := range flattenedEntries { + if writes(flattenedEntry.Node) { + return flattenedEntry + } + } + return own + } + return contentWriting{encoding: flattenedConjunct("contentEncoding"), media: flattenedConjunct("contentMediaType", "contentSchema"), format: formatConjunct(schema, pointer, flattenedEntries)} +} + +// encodingName chooses the one name ir.Encoding holds from the two keywords +// that can name an encoding at a scalar position. // // contentEncoding wins: it is the standard keyword, where a format the IR could // not place is only parked there. Encoding holds one name, so a format that // named a *different* encoding is kept verbatim on the node rather than -// overwritten away. -func encodingName(loweringContext lowering.Ctx, schema *statement.Schema, formatName string, common *ir.TypeCommon, pointer jsontext.Pointer) (string, []ir.Diagnostic) { +// overwritten away, where whichever conjunct of conjuncts writes it. +func encodingName(loweringContext lowering.Ctx, contentConjuncts contentWriting, formatName string, unmodeled *ir.Unmodeled) (string, annotation.KeptReports) { + schema := contentConjuncts.encoding.Node content := schema.TextKeywords().ContentEncoding if content == "" || content == formatName { return formatName, nil @@ -235,14 +420,22 @@ func encodingName(loweringContext lowering.Ctx, schema *statement.Schema, format if !contentOverridesFormat(schema, formatName) { return content, nil } - at := pointer + ids.Ptr("format") - kept, diags := preserveSchemaKeyword(loweringContext, &common.Unmodeled, schema, "format", ir.ReasonNoIRHome, pointer) - if kept { - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, + at := contentConjuncts.format.At + ids.Ptr("format") + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, contentConjuncts.format.Node, "format", ir.ReasonNoIRHome, contentConjuncts.format.At) + switch { + case !kept: + // No JSON value holds it, which the keep reported. + case encodedText(schema, formatName): + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, at, + "format %q reads a value from the text, which beside contentEncoding %q is that encoding's text, "+ + "its content once decoded binary data; the base stays string and format is kept verbatim under Unmodeled", + formatName, content)) + default: + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.UnhomedConstruct, at, "format and contentEncoding both name an encoding and ir.Encoding holds one; "+ "contentEncoding %q is lowered and format is kept verbatim under Unmodeled", content)) } - return content, diags + return content, annotation.ReportsOf(annotation.EntryKey("", "format"), diags...) } // contentOverridesFormat reports whether schema's contentEncoding names an @@ -255,19 +448,19 @@ func contentOverridesFormat(schema *statement.Schema, formatName string) bool { // contentSchemaRef lowers contentSchema — the shape the encoded value has once // decoded — to Encoding.Schema. Its value is a schema, so it lowers like every -// other sub-schema position (fillAdditional, patternProperties): hoisted at its +// other sub-schema position (fillCatchAll, patternProperties): hoisted at its // own pointer and referenced by ID, never carried beside the encoding as a raw // blob a consumer would have to re-parse. // // The pointer it hoists at is the one the source wrote it at, which only this // declaration can name, so the node needs no namespace of its own // (docs/ir/identity.md#the-id-grammar). -func contentSchemaRef(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer) (*ir.TypeRef, []ir.Diagnostic) { +func contentSchemaRef(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer) (*ir.TypeRef, []ir.Diagnostic) { cs := loweringContext.Statements().Subschema(schema.TextKeywords().ContentSchema) if cs.Truth == statement.Unwritten { return nil, nil } - ref, diags := Ref(loweringContext, ts, depth, cs, pointer+ids.Ptr("contentSchema")) + ref, diags := Ref(loweringContext, types, depth, cs, pointer+ids.Ptr("contentSchema")) return &ref, diags } @@ -281,7 +474,8 @@ func contentSchemaRef(loweringContext lowering.Ctx, ts *compile.Types, depth int var contentKeywords = []string{"contentEncoding", "contentMediaType", "contentSchema"} // takesContent reports whether a reader of values of the kinds takes reads the -// content vocabulary, which applies to a string alone (keywordKinds). +// content vocabulary, which applies to a string alone +// (typeformat.InstanceKindsKeywordAppliesTo). func takesContent(takes kindSet) bool { return taken(takes, "contentEncoding") } @@ -303,41 +497,46 @@ func declaresContentVocabulary(schema *statement.Schema) bool { // Schema Validation 2020-12 §8 gives these keywords meaning on whatever instance // turns out to be a string, so they are kept rather than dropped. It asks the // node the position lowered to (holdsContent), not lower()'s dispatch. -func recordUnplacedContent(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, td ir.TypeDef, pointer jsontext.Pointer) []ir.Diagnostic { +func recordUnplacedContent(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, typeDef ir.TypeDef, pointer jsontext.Pointer) annotation.KeptReports { // Called directly, never through a keeping: unmodeled is a carrier's field // on most calls, which a call through a function value would move to the // heap. - keys, why := unplacedContentKeys(loweringContext, schema, td, pointer) - return keepContentKeywords(loweringContext, unmodeled, schema, keys, pointer, why) + keys, why := unplacedContentKeys(loweringContext, schema, typeDef, pointer) + reports := make(annotation.KeptReports, 0, len(keys)) + for _, keyword := range keys { + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), keepContentKeyword(loweringContext, unmodeled, schema, keyword, pointer, why)...)...) + } + return reports } // unplacedContent is the keeping of the content keywords schema, written at -// pointer, writes where td, the node it lowered to, holds no ir.Encoding for -// them (unplacedContentKeys): each as no_ir_home, reported at the keyword. -func unplacedContent(loweringContext lowering.Ctx, schema *statement.Schema, td ir.TypeDef, pointer jsontext.Pointer) keeping { - keys, why := unplacedContentKeys(loweringContext, schema, td, pointer) +// pointer, writes where typeDef, the node it lowered to, holds no ir.Encoding +// for them (unplacedContentKeys): each as no_ir_home, reported at the keyword. +func unplacedContent(loweringContext lowering.Ctx, schema *statement.Schema, typeDef ir.TypeDef, pointer jsontext.Pointer) keeping { + keys, why := unplacedContentKeys(loweringContext, schema, typeDef, pointer) return keeping{keys: keys, reason: ir.ReasonNoIRHome, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { return keepContentKeywords(loweringContext, unmodeled, schema, keys, pointer, why) }} } // unplacedContentKeys returns the content keywords schema, written at pointer, -// writes that td, the node it lowered to, holds no ir.Encoding for -// (holdsContent), and why, for their report. Where td holds the Encoding of the -// inline principal schema lowers from (principalEncoding), a keyword schema -// writes as that principal does is read there, and any other is kept beside it, -// the report saying whose the Encoding is. -func unplacedContentKeys(loweringContext lowering.Ctx, schema *statement.Schema, td ir.TypeDef, pointer jsontext.Pointer) (keys []string, why string) { - if !declaresContentVocabulary(schema) || holdsContent(loweringContext, schema, td, pointer) { +// writes that typeDef, the node it lowered to, holds no ir.Encoding for +// (holdsContent), and why, for their report. Where typeDef holds the Encoding +// of the inline principal schema lowers from (principalEncoding), a keyword +// schema writes as that principal does is read there, and any other is kept +// beside it, the report saying whose the Encoding is. +func unplacedContentKeys(loweringContext lowering.Ctx, schema *statement.Schema, typeDef ir.TypeDef, pointer jsontext.Pointer) (keys []string, why string) { + if !declaresContentVocabulary(schema) || holdsContent(loweringContext, schema, typeDef, pointer) || besideRefOf(loweringContext, schema).readsContentOf(schema) { return nil, "" } why = noEncodingField - bs := principalEncoding(loweringContext, schema, td, pointer) - if bs != nil { + encodingConjunct := principalEncoding(loweringContext, schema, typeDef, pointer) + if encodingConjunct != nil { why = encodingOfEntry } for _, keyword := range contentKeywords { - if hasKey(schema, keyword) && (bs == nil || !keyWrittenAlike(schema, bs, keyword)) { + // A keyword the principal writes none of its node read here. + if hasKey(schema, keyword) && (encodingConjunct == nil || hasKey(encodingConjunct, keyword) && !keyWrittenAlike(schema, encodingConjunct, keyword)) { keys = append(keys, keyword) } } @@ -363,16 +562,16 @@ const ( ) // principalEncoding returns the inline principal of the allOf schema writes at -// pointer where td, the node it built for the position, holds the content +// pointer where typeDef, the node it built for the position, holds the content // vocabulary it writes (holdsContent): a Scalar's Encoding, or that of a type // list's string variant. It is nil where schema lowers from no inline principal -// or td holds none. -func principalEncoding(loweringContext lowering.Ctx, schema *statement.Schema, td ir.TypeDef, pointer jsontext.Pointer) *statement.Schema { +// or typeDef holds none. +func principalEncoding(loweringContext lowering.Ctx, schema *statement.Schema, typeDef ir.TypeDef, pointer jsontext.Pointer) *statement.Schema { refinement, refined := refinementOf(loweringContext, schema, pointer) if !refined || refinement.principal == nil || refinement.principal.schema.Ref != nil { return nil } - if entry := refinement.principal; holdsContent(loweringContext, entry.schema.Schema, td, entry.pointer) { + if entry := refinement.principal; holdsContent(loweringContext, entry.schema.Schema, typeDef, entry.pointer) { return entry.schema.Schema } return nil @@ -383,7 +582,7 @@ func principalEncoding(loweringContext lowering.Ctx, schema *statement.Schema, t // the keyword, where no ir.Encoding holds it, for why (noEncodingField). func keepContentKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, pointer jsontext.Pointer, why string, ) []ir.Diagnostic { - kept, diags := preserveSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonNoIRHome, pointer) + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonNoIRHome, pointer) if !kept { return diags } @@ -391,19 +590,19 @@ func keepContentKeyword(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, s "%s is content-vocabulary data the IR holds in ir.Encoding, and %s; kept verbatim under Unmodeled", keyword, why)) } -// holdsContent reports whether td, the node schema lowered to at pointer, holds -// the content vocabulary schema writes: a Scalar carrying an Encoding for a -// type that takes it, or the Union of a type array listing a string, whose -// string variant carries one (lowerTypeVariant). A nil td is the +// holdsContent reports whether typeDef, the node schema lowered to at pointer, +// holds the content vocabulary schema writes: a Scalar carrying an Encoding for +// a type that takes it, or the Union of a type array listing a string, whose +// string variant carries one (lowerTypeVariant). A nil typeDef is the // property-carrier case — no node, so no Encoding. -func holdsContent(loweringContext lowering.Ctx, schema *statement.Schema, td ir.TypeDef, pointer jsontext.Pointer) bool { +func holdsContent(loweringContext lowering.Ctx, schema *statement.Schema, typeDef ir.TypeDef, pointer jsontext.Pointer) bool { if !takesContent(declaredInstanceTypes(schema)) { return false } - switch n := td.(type) { + switch n := typeDef.(type) { case *ir.Scalar: // An inline principal's node reads the Encoding of its entry alone, so - // it holds none that s writes beside its allOf. + // it holds none that schema writes beside its allOf. refinement, refined := refinementOf(loweringContext, schema, pointer) return n.Encoding != nil && (!refined || refinement.principal == nil) case *ir.Union: diff --git a/compilers/openapi/internal/schema/scalar_test.go b/compilers/openapi/internal/schema/scalar_test.go index f747f9114..7ec394df3 100644 --- a/compilers/openapi/internal/schema/scalar_test.go +++ b/compilers/openapi/internal/schema/scalar_test.go @@ -52,7 +52,7 @@ func TestScalar_UnknownFormatPerBaseType(t *testing.T) { // narrower than integer holds, so it hoists as an unknown format does. func TestScalar_NumericFormatPairings(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { typ, format string primitive ir.PrimitiveKind // the primitive the pairing selects; "" = it hoists base ir.PrimitiveKind // the hoisted Scalar's base @@ -88,11 +88,11 @@ func TestScalar_NumericFormatPairings(t *testing.T) { {typ: "number", format: "float16", base: ir.PrimitiveNumber}, // a width no PrimitiveKind names {typ: "string", format: "double-int", base: ir.PrimitiveString}, // no number's format the table pairs } { - t.Run(tc.typ+"/"+tc.format, func(t *testing.T) { + t.Run(testCase.typ+"/"+testCase.format, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf( " H:\n type: object\n properties:\n p: {type: %s, format: %s}\n", - tc.typ, tc.format))) + testCase.typ, testCase.format))) assert.Empty(t, diags, "the format is homed either way, so nothing is reported") model, ok := typeByName(doc, "H").(*ir.Model) require.True(t, ok, "H lowers to a model") @@ -100,22 +100,22 @@ func TestScalar_NumericFormatPairings(t *testing.T) { assert.Empty(t, model.Properties[0].Unmodeled, "the format is homed either way, so nothing is kept") target := model.Properties[0].Type.Target - if tc.primitive != "" { - assert.Equal(t, ir.PrimitiveTypeID(tc.primitive), target, "the position resolves to the shared primitive") + if testCase.primitive != "" { + assert.Equal(t, ir.PrimitiveTypeID(testCase.primitive), target, "the position resolves to the shared primitive") primitive, ok := doc.Types[target].(*ir.Primitive) require.True(t, ok, "the primitive is interned") - assert.Equal(t, tc.primitive, primitive.PrimitiveKind) - for id, td := range doc.Types { - assert.NotEqual(t, ir.KindScalar, td.Kind(), "%s: no node is hoisted for the position", id) + assert.Equal(t, testCase.primitive, primitive.PrimitiveKind) + for id, typeDef := range doc.Types { + assert.NotEqual(t, ir.KindScalar, typeDef.Kind(), "%s: no node is hoisted for the position", id) } return } sc, ok := doc.Types[target].(*ir.Scalar) require.True(t, ok, "the position hoists a Scalar") require.NotNil(t, sc.Base) - assert.Equal(t, ir.PrimitiveTypeID(tc.base), sc.Base.Target) + assert.Equal(t, ir.PrimitiveTypeID(testCase.base), sc.Base.Target) require.NotNil(t, sc.Encoding) - assert.Equal(t, tc.format, sc.Encoding.Name, "the format is kept verbatim") + assert.Equal(t, testCase.format, sc.Encoding.Name, "the format is kept verbatim") }) } } @@ -129,7 +129,7 @@ func TestScalar_NumericFormatPairings(t *testing.T) { // as an unknown format does, over the type's primitive and named as written. func TestScalar_EncodedFormatPairings(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { typ, format string base ir.PrimitiveKind encoding string @@ -150,11 +150,11 @@ func TestScalar_EncodedFormatPairings(t *testing.T) { {typ: "string", format: "unixtimes", base: ir.PrimitiveString, encoding: "unixtimes"}, {typ: "string", format: "HTTP-date", base: ir.PrimitiveString, encoding: "HTTP-date"}, } { - t.Run(tc.typ+"/"+tc.format, func(t *testing.T) { + t.Run(testCase.typ+"/"+testCase.format, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf( " H:\n type: object\n properties:\n p: {type: %s, format: %s}\n", - tc.typ, tc.format))) + testCase.typ, testCase.format))) assert.Empty(t, diags, "the format is homed, so nothing is reported") property := propertyOf(t, doc, "H", "p") assert.Empty(t, property.Unmodeled, "the format is homed, so nothing is kept") @@ -163,11 +163,11 @@ func TestScalar_EncodedFormatPairings(t *testing.T) { require.True(t, ok, "the position hoists a Scalar") assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/H/properties/p"), sc.ID, "at its own pointer") require.NotNil(t, sc.Base) - assert.Equal(t, ir.PrimitiveTypeID(tc.base), sc.Base.Target) + assert.Equal(t, ir.PrimitiveTypeID(testCase.base), sc.Base.Target) assert.Contains(t, doc.Types, sc.Base.Target, "the base is interned") - want := ir.Encoding{Name: tc.encoding} - if tc.wire != "" { - want.WireType = &ir.TypeRef{Target: ir.PrimitiveTypeID(tc.wire)} + want := ir.Encoding{Name: testCase.encoding} + if testCase.wire != "" { + want.WireType = &ir.TypeRef{Target: ir.PrimitiveTypeID(testCase.wire)} assert.Contains(t, doc.Types, want.WireType.Target, "the wire type is interned") } require.NotNil(t, sc.Encoding) @@ -177,68 +177,79 @@ func TestScalar_EncodedFormatPairings(t *testing.T) { } // TestScalar_AnEncodedFormatKeepsTheBoundsWrittenBesideIt pins that a scalar -// hoisted for an encoded pairing carries the bounds written beside its format, -// as one hoisted for byte or an unknown format does: as written, a length of -// the text and a bound of the number the JSON type holds -// (docs/compilers/openapi.md#string-formats). +// hoisted for an encoded pairing keeps the bounds written beside its format +// verbatim with no IR home and one info at each, as a bound binds only the +// kind its node's value is: a length of the text an instant or bytes are +// written as, and a bound of the seconds an instant is written as +// (docs/compilers/openapi.md#string-formats, +// docs/compilers/openapi.md#numeric-formats). func TestScalar_AnEncodedFormatKeepsTheBoundsWrittenBesideIt(t *testing.T) { t.Parallel() - three := int64(3) - for _, tc := range []struct { + for _, testCase := range []struct { schema string - want ir.Constraints + want *ir.Constraints + kept string }{ - {"{type: string, format: http-date, minLength: 3}", ir.Constraints{MinLength: &three}}, - {"{type: integer, format: unixtime, minimum: 0}", ir.Constraints{Min: new(ir.BigVal("0"))}}, - {"{type: number, format: unixtime, exclusiveMaximum: 4102444800.5}", - ir.Constraints{ExclusiveMax: new(ir.BigVal("4102444800.5"))}}, - {"{type: string, format: base64url, maxLength: 9}", ir.Constraints{MaxLength: new(int64(9))}}, + {"{type: string, format: http-date, minLength: 3}", nil, "minLength"}, + {"{type: integer, format: unixtime, minimum: 0}", nil, "minimum"}, + {"{type: number, format: unixtime, exclusiveMaximum: 4102444800.5}", nil, "exclusiveMaximum"}, + {"{type: string, format: base64url, maxLength: 9}", nil, "maxLength"}, } { - t.Run(tc.schema, func(t *testing.T) { + t.Run(testCase.schema, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+tc.schema+"\n")) - assert.Empty(t, diags) + doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+testCase.schema+"\n")) sc, ok := doc.Types[componentID("A")].(*ir.Scalar) require.True(t, ok, "the format hoists a Scalar") require.NotNil(t, sc.Encoding, "carrying the format") - require.NotNil(t, sc.Constraints, "and the bounds beside it") - assert.Empty(t, cmp.Diff(tc.want, *sc.Constraints)) + assert.Empty(t, cmp.Diff(testCase.want, sc.Constraints), "and the bounds beside it it holds") + if testCase.kept == "" { + assert.Empty(t, diags) + assert.Empty(t, sc.Unmodeled) + return + } + assert.Equal(t, ir.ReasonNoIRHome, sc.Unmodeled["openapi:"+testCase.kept].Reason, "a bound of its written form kept with no home") + require.Len(t, diags, 1) + assert.Equal(t, diag.UnhomedConstruct, diags[0].Code) + assert.Equal(t, jsontext.Pointer("/components/schemas/A/"+testCase.kept), diags[0].Provenance.Pointer) }) } } -// TestScalar_AnEncodedFormatBesideContentEncodingKeepsItsPrimitive pins a +// TestScalar_AnEncodedFormatBesideContentEncodingReadsTheText pins a // contentEncoding naming another encoding beside an encoded pairing: on a -// string it takes Encoding.Name, as beside byte, and on an integer, which it -// does not apply to, takes nothing, while the primitive and the wire type the -// format selects stay (docs/compilers/openapi.md#string-formats). +// string it takes Encoding.Name, as beside byte, and a format read from the +// text names the text inside the encoding, not the decoded bytes, so the base +// stays the string with no WireType (GitHub #1908), while byte keeps its bytes; +// on an integer, which it does not apply to, it takes nothing, and the +// primitive and the wire type the format selects stay +// (docs/compilers/openapi.md#string-formats). // TestContentVocabulary_KeptWhereNoEncodingHolds holds what each keeps. -func TestScalar_AnEncodedFormatBesideContentEncodingKeepsItsPrimitive(t *testing.T) { +func TestScalar_AnEncodedFormatBesideContentEncodingReadsTheText(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { schema string base ir.PrimitiveKind want ir.Encoding }{ {"{type: string, format: byte, contentEncoding: base64url}", ir.PrimitiveBytes, ir.Encoding{Name: "base64url", WireType: &ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveString)}}}, - {"{type: string, format: http-date, contentEncoding: base64}", ir.PrimitiveDatetimeOffset, + {"{type: string, format: http-date, contentEncoding: base64}", ir.PrimitiveString, + ir.Encoding{Name: "base64"}}, + {"{type: string, format: unixtime, contentEncoding: base64}", ir.PrimitiveString, ir.Encoding{Name: "base64"}}, - {"{type: string, format: unixtime, contentEncoding: base64}", ir.PrimitiveDatetimeOffset, - ir.Encoding{Name: "base64", WireType: &ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveString)}}}, {"{type: integer, format: unixtime, contentEncoding: base64}", ir.PrimitiveDatetimeOffset, ir.Encoding{Name: "unixTimestamp", WireType: &ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveInteger)}}}, } { - t.Run(tc.schema, func(t *testing.T) { + t.Run(testCase.schema, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) sc, ok := doc.Types[componentID("A")].(*ir.Scalar) require.True(t, ok, "the format hoists a Scalar") require.NotNil(t, sc.Base) - assert.Equal(t, ir.PrimitiveTypeID(tc.base), sc.Base.Target, "the format still selects the primitive") + assert.Equal(t, ir.PrimitiveTypeID(testCase.base), sc.Base.Target, "the base the encoding leaves the format to select") require.NotNil(t, sc.Encoding) - assert.Empty(t, cmp.Diff(tc.want, *sc.Encoding), "contentEncoding names the encoding") + assert.Empty(t, cmp.Diff(testCase.want, *sc.Encoding), "contentEncoding names the encoding") }) } } @@ -250,7 +261,7 @@ func TestScalar_AnEncodedFormatBesideContentEncodingKeepsItsPrimitive(t *testing // (docs/compilers/openapi.md#enum-const). func TestScalar_AnEncodedFormatBesideAValueSetLowersAsByteDoes(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { schema string kind ir.TypeKind value ir.PrimitiveKind @@ -263,18 +274,18 @@ func TestScalar_AnEncodedFormatBesideAValueSetLowersAsByteDoes(t *testing.T) { {`{type: number, format: unixtime, const: 1.5}`, ir.KindLiteral, ir.PrimitiveNumber}, {`{type: string, format: http-date, const: "Sun, 06 Nov 1994 08:49:37 GMT"}`, ir.KindLiteral, ir.PrimitiveString}, } { - t.Run(tc.schema, func(t *testing.T) { + t.Run(testCase.schema, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) node := doc.Types[componentID("A")] require.NotNil(t, node) - require.Equal(t, tc.kind, node.Kind()) + require.Equal(t, testCase.kind, node.Kind()) switch n := node.(type) { case *ir.Enum: - assert.Equal(t, tc.value, n.ValueType, "typed by the JSON type") + assert.Equal(t, testCase.value, n.ValueType, "typed by the JSON type") case *ir.Literal: - assert.Equal(t, tc.value, n.ValueType, "typed by the JSON type") + assert.Equal(t, testCase.value, n.ValueType, "typed by the JSON type") default: t.Fatalf("unexpected node %T", n) } @@ -296,7 +307,7 @@ func TestScalar_AnEncodedFormatBesideAValueSetLowersAsByteDoes(t *testing.T) { // media type or a schema of the content beside it leaves the format lowered. func TestScalar_ANumberAsTextIsItsNumberOnAString(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { format, extra string base ir.PrimitiveKind name string @@ -322,26 +333,26 @@ func TestScalar_ANumberAsTextIsItsNumberOnAString(t *testing.T) { {format: "int64", extra: ", contentMediaType: text/plain", base: ir.PrimitiveInt64, name: "string", wire: true}, {format: "int64", extra: ", contentSchema: {type: integer}", base: ir.PrimitiveInt64, name: "string", wire: true}, } { - t.Run(tc.format+tc.extra, func(t *testing.T) { + t.Run(testCase.format+testCase.extra, func(t *testing.T) { t.Parallel() doc, _ := schema.LowerSpec(t, openapitest.ComponentSpec(fmt.Sprintf( - " H:\n type: object\n properties:\n p: {type: string, format: %s%s}\n", tc.format, tc.extra))) + " H:\n type: object\n properties:\n p: {type: string, format: %s%s}\n", testCase.format, testCase.extra))) model, ok := typeByName(doc, "H").(*ir.Model) require.True(t, ok) sc, ok := doc.Types[model.Properties[0].Type.Target].(*ir.Scalar) require.True(t, ok, "the position hoists a Scalar") require.NotNil(t, sc.Base) - assert.Equal(t, ir.PrimitiveTypeID(tc.base), sc.Base.Target, "the base is the number the format selects, or the string an encoding overrides it with") + assert.Equal(t, ir.PrimitiveTypeID(testCase.base), sc.Base.Target, "the base is the number the format selects, or the string an encoding overrides it with") require.NotNil(t, sc.Encoding) - assert.Equal(t, tc.name, sc.Encoding.Name) - if tc.wire { + assert.Equal(t, testCase.name, sc.Encoding.Name) + if testCase.wire { require.NotNil(t, sc.Encoding.WireType, "the number travels as a string") assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), sc.Encoding.WireType.Target) } else { assert.Nil(t, sc.Encoding.WireType, "the string is the encoded text already") } _, kept := sc.Unmodeled["openapi:format"] - assert.Equal(t, tc.kept, kept) + assert.Equal(t, testCase.kept, kept) }) } } @@ -349,11 +360,11 @@ func TestScalar_ANumberAsTextIsItsNumberOnAString(t *testing.T) { // TestScalar_ANumberAsTextKeepsItsBoundsVerbatim pins the value bounds beside a // number carried as text. Its Constraints speak of the number, and none of them // does: a length or a pattern bounds the text, and a numeric bound no string -// instance. Each is kept verbatim on the Scalar under no_ir_home, with an info -// at it, neither the Scalar nor a property or parameter carrying it holds a -// bound, and the carrier keeps no copy. A format the table pairs with string -// keeps its bounds, and an alias an allOf refinement lowers to loses none of -// its own. +// instance. Each is kept verbatim on the Scalar under no_ir_home, with an +// unhomed-construct info at it, neither the Scalar nor a property or +// parameter carrying it holds a bound, and the carrier keeps no copy. A length +// beside a date, whose value is no text either, its carrier keeps verbatim, +// and an alias an allOf refinement lowers to loses none of its own. func TestScalar_ANumberAsTextKeepsItsBoundsVerbatim(t *testing.T) { t.Parallel() const bounds = `pattern: "^[0-9]+$", minLength: 1, maxLength: 20, minimum: 5, exclusiveMaximum: 100, multipleOf: 5` @@ -397,15 +408,15 @@ components: assert.Equal(t, ir.ReasonNoIRHome, entry.Reason) assert.Equal(t, at+jsontext.Pointer("/"+keyword), entry.Provenance.Pointer) } - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, string(at)+"/"+keyword), + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnhomedConstruct, string(at)+"/"+keyword), "%s: keeping %s is reported at it", at, keyword) } assert.Len(t, sc.Unmodeled, len(keywords), "%s keeps nothing else", at) } assert.Empty(t, properties["p"].Unmodeled, "the property keeps no copy of what its node keeps") assert.Empty(t, params[0].Unmodeled, "the parameter keeps no copy of what its node keeps") - require.NotNil(t, properties["d"].Constraints, "a date keeps the length bound of its text") - assert.Equal(t, new(int64(10)), properties["d"].Constraints.MaxLength) + assert.Nil(t, properties["d"].Constraints, "a date holds no length of its text") + assert.Equal(t, ir.ReasonNoIRHome, properties["d"].Unmodeled["openapi:maxLength"].Reason, "its carrier keeps it verbatim") scalar, ok := typeByName(doc, "R").(*ir.Scalar) require.True(t, ok, "the refinement owns an alias") @@ -415,9 +426,9 @@ components: // nodeAt returns the type node lowered at the source pointer at. func nodeAt(doc *ir.Document, at jsontext.Pointer) ir.TypeDef { - for _, td := range doc.Types { - if td.Common().Provenance.Pointer == at { - return td + for _, typeDef := range doc.Types { + if typeDef.Common().Provenance.Pointer == at { + return typeDef } } return nil @@ -490,19 +501,19 @@ func TestContentVocabulary_LowersToEncoding(t *testing.T) { want: ir.Encoding{Schema: &ir.TypeRef{Target: componentID("B")}}, }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(tc.schemas)) + doc, diags := parseFull(t, openapitest.ComponentSpec(testCase.schemas)) openapitest.RequireNoErrorDiags(t, diags) - sc, ok := doc.Types[tc.at].(*ir.Scalar) - require.True(t, ok, "the content vocabulary needs a Scalar of its own at %s", tc.at) + sc, ok := doc.Types[testCase.at].(*ir.Scalar) + require.True(t, ok, "the content vocabulary needs a Scalar of its own at %s", testCase.at) require.NotNil(t, sc.Encoding) - assert.Empty(t, cmp.Diff(tc.want, *sc.Encoding)) + assert.Empty(t, cmp.Diff(testCase.want, *sc.Encoding)) assert.Empty(t, sc.Unmodeled, "a keyword with a field is lowered, never also kept raw") - if tc.want.Schema != nil { - assert.Contains(t, doc.Types, tc.want.Schema.Target, + if testCase.want.Schema != nil { + assert.Contains(t, doc.Types, testCase.want.Schema.Target, "contentSchema reaches the registry as a type, not a raw blob") } }) @@ -511,7 +522,7 @@ func TestContentVocabulary_LowersToEncoding(t *testing.T) { // TestContentVocabulary_KeepsTheBoundsWrittenBesideIt pins that hoisting a node // for the content vocabulary does not cost the position its value constraints. -// Owning a node is what stops hoistDeclarationHome hoisting the alias that +// Owning a node is what stops homeDeclaration hoisting the alias that // carries them, so the node the content vocabulary lands on has to carry them // itself — otherwise adding contentEncoding to a bounded string deletes its // bounds, which is a lossy lowering nothing reports (invariant 2). @@ -536,17 +547,17 @@ func TestContentVocabulary_KeepsTheBoundsWrittenBesideIt(t *testing.T) { want: ir.Constraints{MinLength: &five}, }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(tc.schemas)) + doc, diags := parseFull(t, openapitest.ComponentSpec(testCase.schemas)) openapitest.RequireNoErrorDiags(t, diags) - sc, ok := doc.Types[tc.at].(*ir.Scalar) - require.True(t, ok, "the content vocabulary hoists a Scalar at %s", tc.at) + sc, ok := doc.Types[testCase.at].(*ir.Scalar) + require.True(t, ok, "the content vocabulary hoists a Scalar at %s", testCase.at) require.NotNil(t, sc.Encoding, "and lowers the keyword onto it") require.NotNil(t, sc.Constraints, "while keeping the bounds written beside it") - assert.Empty(t, cmp.Diff(tc.want, *sc.Constraints)) + assert.Empty(t, cmp.Diff(testCase.want, *sc.Constraints)) }) } } @@ -562,10 +573,10 @@ func TestHoistedScalar_ReportsABoundItCannotConvert(t *testing.T) { {"an unplaced format", "{type: number, format: custom, minimum: .inf}"}, {"the content vocabulary", "{type: string, contentEncoding: base64, minimum: .inf}"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpec(" A: "+testCase.schema+"\n")) sc, ok := doc.Types[componentID("A")].(*ir.Scalar) require.True(t, ok, "the position hoists a Scalar of its own") require.NotNil(t, sc.Encoding, "carrying what it wrote") @@ -628,18 +639,24 @@ func TestContentVocabulary_KeptWhereNoEncodingHolds(t *testing.T) { "oneOf: [{type: string, format: uuid}, {type: string, format: email}]}\n", key: "openapi:contentMediaType", wantJSON: `"application/zip"`, at: componentID("A"), }, + { + name: "a union of one type's branches beside an entry has no Encoding", + schemas: " A: {allOf: [{type: string, contentMediaType: application/zip}], " + + "oneOf: [{type: string, format: uuid}, {type: string, format: email}]}\n", + key: "openapi:contentMediaType", wantJSON: `"application/zip"`, at: componentID("A"), + }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(tc.schemas)) + doc, diags := parseFull(t, openapitest.ComponentSpec(testCase.schemas)) openapitest.RequireNoErrorDiags(t, diags) - td, ok := doc.Types[tc.at] + typeDef, ok := doc.Types[testCase.at] require.True(t, ok) - entry, ok := td.Common().Unmodeled[tc.key] - require.True(t, ok, "%s must be kept verbatim under Unmodeled", tc.key) - assert.JSONEq(t, tc.wantJSON, string(entry.Value)) + entry, ok := typeDef.Common().Unmodeled[testCase.key] + require.True(t, ok, "%s must be kept verbatim under Unmodeled", testCase.key) + assert.JSONEq(t, testCase.wantJSON, string(entry.Value)) assert.Equal(t, ir.ReasonNoIRHome, entry.Reason) openapitest.AssertInfoDiagAt(t, diags, string(entry.Provenance.Pointer)) }) @@ -689,7 +706,7 @@ func TestContentVocabulary_KeptOnACarrierWithNoNode(t *testing.T) { // reported: the format reached its field everywhere (GitHub #579). func TestRedactionFormat_SensitiveOnWhateverNodeThePositionOwns(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string kind ir.TypeKind base ir.TypeID // the alias's base, for a Scalar @@ -705,14 +722,14 @@ func TestRedactionFormat_SensitiveOnWhateverNodeThePositionOwns(t *testing.T) { {"tuple", "{type: array, prefixItems: [{type: string}], format: password}", ir.KindTuple, ""}, {"multi-typed", "{type: [string, integer], format: password}", ir.KindUnion, ""}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, openapitest.ComponentSpec(" Secret: "+tc.schema+"\n")) + doc, diags := parseFull(t, openapitest.ComponentSpec(" Secret: "+testCase.schema+"\n")) assert.Empty(t, diags, "the format reached its field, so nothing is kept or reported") node := typeByName(doc, "Secret") require.NotNil(t, node) - assert.Equal(t, tc.kind, node.Kind()) + assert.Equal(t, testCase.kind, node.Kind()) assert.True(t, node.Common().Sensitive, "whole-type redaction") assert.NotContains(t, node.Common().Unmodeled, "openapi:format") sc, ok := node.(*ir.Scalar) @@ -720,7 +737,7 @@ func TestRedactionFormat_SensitiveOnWhateverNodeThePositionOwns(t *testing.T) { return } require.NotNil(t, sc.Base) - assert.Equal(t, tc.base, sc.Base.Target, "the shape it would have had without the format") + assert.Equal(t, testCase.base, sc.Base.Target, "the shape it would have had without the format") assert.Nil(t, sc.Encoding, "a redaction is no encoding") }) } diff --git a/compilers/openapi/internal/schema/schema.go b/compilers/openapi/internal/schema/schema.go index f53b2b2d9..47103ba90 100644 --- a/compilers/openapi/internal/schema/schema.go +++ b/compilers/openapi/internal/schema/schema.go @@ -32,18 +32,18 @@ import ( // returns what was lowered so far; the caller — run — sees ctx.Err() at the // phase boundary immediately after and refuses the document there, so a partial // registry never becomes a Document. -func LowerComponentSchemas(ctx context.Context, loweringContext lowering.Ctx, ts *compile.Types, +func LowerComponentSchemas(ctx context.Context, loweringContext lowering.Ctx, types *compile.Types, schemas iter.Seq2[string, *statement.Statement], ) []ir.Diagnostic { var diags []ir.Diagnostic // The declared-name index the $ref and discriminator-mapping resolutions read // arrives with the context (lowering.Loaded), so a component declared later // in the document is already a valid target here regardless of source order. - for name, js := range schemas { + for name, schemaStatement := range schemas { if ctx.Err() != nil { return diags } - diags = append(diags, lowerComponentSchema(loweringContext, ts, js, ids.Ptr("components", "schemas", name))...) + diags = append(diags, lowerComponentSchema(loweringContext, types, schemaStatement, ids.Ptr("components", "schemas", name))...) } return diags } @@ -53,9 +53,9 @@ func LowerComponentSchemas(ctx context.Context, loweringContext lowering.Ctx, ts // shared primitive/any or aliases another type. Without this, a component like // `MyId: {type: string, format: uuid}` would leave nothing at its component // pointer and every $ref to it would dangle (invariants 1 and 2). -func lowerComponentSchema(loweringContext lowering.Ctx, ts *compile.Types, js *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { - schemaPositionAnnotationSources := annotation.At(js) - ref, diags := Ref(loweringContext, ts, TopLevelDepth, js, pointer) +func lowerComponentSchema(loweringContext lowering.Ctx, types *compile.Types, schemaStatement *statement.Statement, pointer jsontext.Pointer) []ir.Diagnostic { + schemaPositionAnnotationSources := annotation.At(schemaStatement) + ref, diags := Ref(loweringContext, types, TopLevelDepth, schemaStatement, pointer) // A body that lowered to the component's own node needs no alias, and its // annotations were attached where it was lowered. if LoweredToOwnNode(loweringContext, pointer, ref) { @@ -63,15 +63,13 @@ func lowerComponentSchema(loweringContext lowering.Ctx, ts *compile.Types, js *s } // This node is the first the pointer owns, so the annotations schemaBody // had nowhere to put now have a home, which its build gives them. - var annotated finished - var fin finisher - if stated(schemaPositionAnnotationSources.Node) { - fin = annotated.on(func(td ir.TypeDef) []ir.Diagnostic { - return attachDeclaredAnnotations(loweringContext, ts, schemaPositionAnnotationSources.Node, pointer, ref, td) - }) + built, ownDiags := internOwnNode(loweringContext, types, schemaStatement, pointer, ref) + diags = append(diags, ownDiags...) + if built.node != nil && stated(schemaPositionAnnotationSources.Node) { + diags = append(diags, attachDeclaredAnnotations(loweringContext, schemaPositionAnnotationSources.Node, pointer, ref, &built)...) + diags = append(diags, settleNode(loweringContext, schemaPositionAnnotationSources.Node, ref, pointer, &built)...) } - diags = append(diags, internOwnNode(loweringContext, ts, js, pointer, ref, fin)...) - return append(diags, annotated.diags...) + return diags } // TopLevelDepth is the nesting a schema position outside the walk starts at. @@ -97,68 +95,68 @@ const maxSchemaDepth = 256 // It defaults to annotation.HomeOwnNode deliberately: a position added later // inherits the lossless behaviour, and only a caller that can prove it already // carries the annotations opts out through CarriedRef. -func Ref(loweringContext lowering.Ctx, ts *compile.Types, depth int, js *statement.Statement, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { - return schemaRefHomed(loweringContext, ts, depth, js, pointer, annotation.HomeOwnNode) +func Ref(loweringContext lowering.Ctx, types *compile.Types, depth int, schemaStatement *statement.Statement, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { + return schemaRefHomed(loweringContext, types, depth, schemaStatement, pointer, annotation.HomeOwnNode) } // CarriedRef lowers a schema whose annotations the calling position // already carries — a model property, a header, a parameter. Those callers // copy the declaration onto their own ir.Property/ir.Parameter, so the pointer // must not also hoist a node to hold it: one home per declaration. -func CarriedRef(loweringContext lowering.Ctx, ts *compile.Types, depth int, js *statement.Statement, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { - return schemaRefHomed(loweringContext, ts, depth, js, pointer, annotation.HomeCarrier) +func CarriedRef(loweringContext lowering.Ctx, types *compile.Types, depth int, schemaStatement *statement.Statement, pointer jsontext.Pointer) (ir.TypeRef, []ir.Diagnostic) { + return schemaRefHomed(loweringContext, types, depth, schemaStatement, pointer, annotation.HomeCarrier) } // schemaRefHomed is the shared body of the two entry points above; home only // reaches the two places that can hoist an annotation-holding alias. -func schemaRefHomed(loweringContext lowering.Ctx, ts *compile.Types, depth int, js *statement.Statement, pointer jsontext.Pointer, home annotation.Home, +func schemaRefHomed(loweringContext lowering.Ctx, types *compile.Types, depth int, schemaStatement *statement.Statement, pointer jsontext.Pointer, home annotation.Home, ) (ir.TypeRef, []ir.Diagnostic) { // depth counts the active frames of this function, which is where every // recursive descent re-enters. Incrementing on entry and passing the result // down is the parameter form of a counter that used to live on a shared // struct, back when one held the whole compile. - if js == nil || js.Truth == statement.Unwritten { + if schemaStatement == nil || schemaStatement.Truth == statement.Unwritten { // None, or a null, which states nothing: an entry written so — a // property, a branch, a component, items — lowers as the empty schema. // A keyword whose absence differs from the empty schema reads a null as // left out before it gets here (docs/compilers/openapi.md#null-schema). // It nests nothing, so the depth bound reports none at its pointer, as // a tuple's absent rest would otherwise draw. - return ts.PrimitiveRef(ir.PrimitiveAny), nil + return types.PrimitiveRef(ir.PrimitiveAny), nil } if depth == TopLevelDepth { recordReachedSchema(loweringContext, loweringContext.Position(pointer)) } depth++ if depth > maxSchemaDepth { - return ts.PrimitiveRef(ir.PrimitiveAny), []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.DegradedConstruct, pointer, + return types.PrimitiveRef(ir.PrimitiveAny), []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.DegradedConstruct, pointer, "schema nesting exceeds %d; lowered as any", maxSchemaDepth)} } - switch js.Truth { + switch schemaStatement.Truth { case statement.Unread: // A mapping the parser read as false: the load phase decodes it again // unless it lies past typed.MaxMends // (docs/parser-library.md#failure-beneath-itself), so it says nothing of // the values there. - return ts.PrimitiveRef(ir.PrimitiveAny), []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.DegradedConstruct, pointer, + return types.PrimitiveRef(ir.PrimitiveAny), []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.DegradedConstruct, pointer, "schema read as false, as the parser fails to decode a keyword beneath it under its own name "+ "and the load phase decodes no more than %d such schemas one below another; lowered as any; "+ "moving the schemas below it into a component reads them", typed.MaxMends)} case statement.Nothing: - id, diags := falseSchema(loweringContext, ts, pointer) + id, diags := falseSchema(loweringContext, types, pointer) return ir.TypeRef{Target: id}, diags case statement.Anything: - return ts.PrimitiveRef(ir.PrimitiveAny), nil + return types.PrimitiveRef(ir.PrimitiveAny), nil default: // Stated: a schema object, which a reference site writes too. } - diags := mergedPastBound(loweringContext, js) - if js.Ref != nil { - ref, refDiags := refSiteRef(loweringContext, ts, js, js.Schema, pointer, home) + diags := mergedPastBound(loweringContext, schemaStatement) + if schemaStatement.Ref != nil { + ref, refDiags := refSiteRef(loweringContext, types, schemaStatement, schemaStatement.Schema, pointer, home) return ref, append(diags, refDiags...) } - ref, bodyDiags := schemaBody(loweringContext, ts, depth, js.Schema, pointer, home) + ref, bodyDiags := schemaBody(loweringContext, types, depth, schemaStatement.Schema, pointer, home) return ref, append(diags, bodyDiags...) } @@ -167,15 +165,15 @@ type mergedPastOf struct { schema *statement.Schema } -// mergedPastBound reports each schema object of st, its own and its inline -// allOf entries', whose `<<` merges run past nodeview.MergeDepthLimit -// (pastBoundOnce). -func mergedPastBound(loweringContext lowering.Ctx, st *statement.Statement) []ir.Diagnostic { +// mergedPastBound reports each schema object of schemaStatement, its own and +// its inline allOf entries', whose `<<` merges run past +// nodeview.MergeDepthLimit (pastBoundOnce). +func mergedPastBound(loweringContext lowering.Ctx, schemaStatement *statement.Statement) []ir.Diagnostic { var diags []ir.Diagnostic - if diagnostic, first := pastBoundOnce(loweringContext, st.Schema); first { + if diagnostic, first := pastBoundOnce(loweringContext, schemaStatement.Schema); first { diags = append(diags, diagnostic) } - for _, allOfConjunct := range st.Entries { + for _, allOfConjunct := range schemaStatement.Entries { if diagnostic, first := pastBoundOnce(loweringContext, allOfConjunct.Schema); first { diags = append(diags, diagnostic) } @@ -206,14 +204,14 @@ func pastBoundOnce(loweringContext lowering.Ctx, schema *statement.Schema) (ir.D // falseSchema hoists a boolean `false` schema as a closed empty model (it // matches nothing), returning the interned ID and the one info diagnostic that // announces it. -func falseSchema(loweringContext lowering.Ctx, ts *compile.Types, pointer jsontext.Pointer) (ir.TypeID, []ir.Diagnostic) { +func falseSchema(loweringContext lowering.Ctx, types *compile.Types, pointer jsontext.Pointer) (ir.TypeID, []ir.Diagnostic) { // Captured from inside the build rather than reported around it, which keeps // the report tied to the node actually being constructed. Reporting eagerly // would be indistinguishable today — a second visit produces the identical // diagnostic, which Diags.Append drops — so nothing observable rests on this; // it is the honest place for it, not a load-bearing one. var diags []ir.Diagnostic - id := internNode(loweringContext, ts, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + built := internNode(loweringContext, types, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { // Kept verbatim beside the approximation, which is what // docs/ir/boundaries.md#degraded-constructs asks of every degraded // lowering that loses something, and what the composition half of this @@ -226,144 +224,241 @@ func falseSchema(loweringContext lowering.Ctx, ts *compile.Types, pointer jsonte // The key names the position rather than a keyword, because a boolean // schema writes none. Nothing can collide with it: a schema that is a // boolean has no other keywords to preserve. - annotation.PreserveInto(&common.Unmodeled, "openapi:schema", + annotation.KeepInto(&common.Unmodeled, "openapi:schema", ir.RawValue("false"), ir.ReasonDegradedLowering, loweringContext.Place().At(pointer)) diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.FalseSchema, pointer, "boolean false schema matches nothing; lowered as a closed empty model "+ "with the schema kept verbatim under Unmodeled")) return &ir.Model{TypeCommon: common, Additional: ir.AdditionalClosed}, 0 - }, nil) - return id, diags + }) + return built.id, diags } // schemaBody lowers a concrete (non-reference) schema body to a TypeRef, the -// schema's declaration finishing whatever node the lowering builds at pointer -// (declared), or the home hoisted here where it lowered to a node it does not -// own. Its one caller is schemaRefHomed, the body of Ref and CarriedRef, for a -// position that is no $ref site (refSiteRef takes those). A rule about the -// declaration itself is checked here, above the dispatch that picks what it -// lowers to (missingArrayItems). The findings keep their order: the body's, the -// home's, what the position keeps beside it. -func schemaBody(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, home annotation.Home, +// schema's declaration finishing whatever node the lowering builds at pointer, +// or the home hoisted here where it lowered to a node it does not own. Its one +// caller is schemaRefHomed, the body of Ref and CarriedRef, for a position that +// is no $ref site (refSiteRef takes those). A rule about the declaration itself +// is checked here, above the dispatch that picks what it lowers to +// (missingArrayItems). The findings keep their order: the body's, the home's, +// what the position keeps beside it. +func schemaBody(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, home annotation.Home, ) (ir.TypeRef, []ir.Diagnostic) { - diags := missingArrayItemsConjoined(loweringContext, schema, pointer) - decl := &declaring{c: loweringContext, ts: ts, s: schema, target: ir.TypeRef{Target: loweringContext.IDs().ForPointer(pointer)}, pointer: pointer, home: home} - target, bodyDiags := lowerSchemaBody(loweringContext, ts, depth, schema, pointer, decl.finish, stand{}) + diags := slices.Concat(missingArrayItems(loweringContext, schema, pointer), scalarChainPastBound(loweringContext, schema, pointer)) + built, target, bodyDiags, afterDiags := lowerSchemaBody(loweringContext, types, depth, schema, pointer, nodePlacement{}) diags = append(diags, bodyDiags...) - ref := target + if built.node != nil { + ownTarget := ir.TypeRef{Target: built.id} + declDiags := declarationOn(loweringContext, schema, ownTarget, pointer, home, &built) + keptDiags := keptOn(loweringContext, schema, ownTarget, pointer, &built, 0) + settledDiags := settleNode(loweringContext, schema, ownTarget, pointer, &built) + findings := slices.Concat(diags, settledDiags, afterDiags, declDiags, keptDiags) + if built.pending { + return hoistOneReference(loweringContext, types, pointer, target, home, built.node, findings) + } + return target, findings + } + diags = append(diags, afterDiags...) // A body kept its unread keywords where its node was built, the only thing - // that can say what was read. One lowering to a reference built none, so it - // keeps them as a position lowered to one does, and that verdict homes an - // alias. - if !decl.ran && homesDeclaration(loweringContext, schema, target, pointer, home, - keepsAtOutcome(loweringContext, schema, target, pointer).holdsAny() || declaresScoped(loweringContext, declarationFoldedEntries(loweringContext, schema, target, pointer))) { - var homeDiags []ir.Diagnostic - decl.target = target - ref, homeDiags = hoistUseHome(loweringContext, ts, schema, target, pointer, decl.finish) - diags = append(diags, homeDiags...) - } - return ref, slices.Concat(diags, decl.diags, decl.kept) -} - -// declaring is a body's declaration s, written at pointer under home, on its -// way to the node the position lowered to target stands at: what finishes it -// there (finish), and what it reported. -type declaring struct { - c lowering.Ctx - ts *compile.Types - s *statement.Schema - pointer jsontext.Pointer - target ir.TypeRef - diags []ir.Diagnostic - kept []ir.Diagnostic - home annotation.Home - ran bool -} - -// finish writes the declaration and what the position keeps beside it on td, -// in hand (declarationOn, keptOn). -func (d *declaring) finish(td ir.TypeDef, _ keySet, held *principalKept) { - d.ran = true - d.diags = declarationOn(d.c, d.ts, d.s, d.target, d.pointer, d.home, td) - d.kept = keptOn(d.c, d.ts, d.s, d.target, d.pointer, td, held) -} - -// keptOn keeps on td, in hand, the node the position s, written at pointer, -// lowered to target, stands at, what it keeps there: what a lowering to a -// reference keeps unread and the entries its refinement left (keepsAtOutcome). -// A carrier keeps them where the position owns no node -// (PreserveRefSiteKeywords). -func keptOn(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, td ir.TypeDef, - held *principalKept, + // that can say what was read. A revisit finding the own node already built + // skips keepsAtOutcome and writes nothing. One lowering to a reference + // built none, so it keeps them as a position lowered to one does, and that + // answer homes an alias. + if LoweredToOwnNode(loweringContext, pointer, target) { + return target, diags + } + enc, encDiags := restrictionEncoding(loweringContext, types, depth, schema, pointer) + diags = append(diags, encDiags...) + if home != annotation.HomeOwnNode && enc != nil { + // The carrier holds what else the position declares; the Encoding needs + // a node. + return restrictedUse(loweringContext, types, target, pointer, enc), diags + } + if !homesDeclaration(loweringContext, schema, target, pointer, home, + keepsAtOutcome(loweringContext, schema, target, pointer).holdsAny() || declaresScoped(loweringContext, positionFlattenedEntries(loweringContext, schema, pointer, target))) { + return target, append(diags, unhomedFindings(loweringContext, schema, target, pointer, home)...) + } + ref, homeDiags := hoistUseHome(loweringContext, types, schema, target, pointer, home, enc) + return ref, append(diags, homeDiags...) +} + +// hoistOneReference registers typeDef, the Model the position at pointer +// composes of one reference and what is written beside it, and returns the +// reference the position resolves to: its Base where typeDef holds nothing, as +// the reference alone lowers (hoistHolding). A carrier-held or nullable use +// keeps typeDef as built: the carrier's keywords never fill its node, and a +// Base carries no null. +func hoistOneReference(loweringContext lowering.Ctx, types *compile.Types, pointer jsontext.Pointer, own ir.TypeRef, home annotation.Home, typeDef ir.TypeDef, + findings []ir.Diagnostic, +) (ir.TypeRef, []ir.Diagnostic) { + use := own + if model, isModel := typeDef.(*ir.Model); isModel && model.Base != nil && home == annotation.HomeOwnNode && !own.Nullable { + use.Target = model.Base.Target + } + if use.Target == own.Target { + internNode(loweringContext, types, pointer, func(ir.TypeCommon) (ir.TypeDef, keySet) { return typeDef, 0 }) + return own, findings + } + _, ref, findings := hoistHolding(loweringContext, types, pointer, use, typeDef, findings) + return ref, findings +} + +// keptOn adds pending keeps on built, the node the position schema, written at +// pointer, lowered to target, sits at, what it keeps there: what a lowering to +// a reference keeps unread, but what its node's build read, and the entries its +// refinement left (keepsAtOutcome). A carrier keeps them where the position +// owns no node (KeepRefSiteKeywords). +func keptOn(loweringContext lowering.Ctx, schema *statement.Schema, target ir.TypeRef, pointer jsontext.Pointer, built *builtPosition, + read keySet, ) []ir.Diagnostic { keeps := keepsAtOutcome(loweringContext, schema, target, pointer) + keeps.keywords = slices.DeleteFunc(keeps.keywords, read.has) + if _, composes := built.node.(*ir.Model); composes && target.Target != built.node.Common().ID { + // The Model composing the use is what the position lowered to, as + // its $ref twin's own Model is. + keeps.shape = positionShape(built.node, schema) + } if !keeps.holdsAny() { return nil } - var standing ir.TypeDef + var positionNode ir.TypeDef if LoweredToOwnNode(loweringContext, pointer, target) { - standing = td + positionNode = built.node } - return keeps.record(loweringContext, ts, &td.Common().Unmodeled, schema, pointer, standing, held) + return keeps.record(loweringContext, &built.pendingKeeps, schema, pointer, positionNode, built.shape, nil) } // lowerSchemaBody lowers the body itself, handling the $dynamicRef expansion and -// the oneOf/anyOf dispatch that precede structural lowering. -// -// fin finishes the node the body builds at pointer, and principal the node a -// refinement's principal builds at its own (lower). -func lowerSchemaBody(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, - fin finisher, st stand, -) (ir.TypeRef, []ir.Diagnostic) { +// the oneOf/anyOf dispatch that precede structural lowering. It returns apart +// the findings reported after the position's settlement (settleNode): a +// refinement's disjoint conjuncts, an entry's dead union and the null the +// position admits. +func lowerSchemaBody(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + placement nodePlacement, +) (builtPosition, ir.TypeRef, []ir.Diagnostic, []ir.Diagnostic) { if at, _, expanded := dynamicExpansion(loweringContext, schema, pointer); expanded { // The expansion settled that the target resolves, by what resolveAt // reads in its own document (resolvesAt), so nothing falls through: that // would drop the reference unrecorded, as recordUnexpandedDynamicRef // keeps only one that does not expand, where an empty target fails // irverify. - target, _ := resolveAt(loweringContext, ts, at, loweringContext.Statements().At(at)) - ref, nullDiags := schemaNullRef(loweringContext, target, schema, siteAt(pointer)) - return ref, append([]ir.Diagnostic{dynamicExpanded(loweringContext, schema, pointer, target)}, nullDiags...) - } - if declaresUnion(schema) && (st.of != nil || !refinesToEntry(loweringContext, schema, pointer)) { - if hasUnionSiblings(loweringContext, schema) { - id, unionDiags := lowerCoDeclaredUnion(loweringContext, ts, depth, schema, pointer, fin, st) - ref, nullDiags := schemaNullRef(loweringContext, id, schema, siteAt(pointer)) - return ref, append(unionDiags, nullDiags...) + target, _ := resolveAt(loweringContext, types, at, loweringContext.Statements().At(at)) + ref, nullDiags := schemaNullRef(loweringContext, target, schema, pointer) + return builtPosition{}, ref, []ir.Diagnostic{dynamicExpanded(loweringContext, schema, pointer, target)}, nullDiags + } + if placement.position == nil && readLoweredUnion(loweringContext, schema).besideRest == unionMembersFilteredByRest { + built, diags := lowerMembersFilteredByRest(loweringContext, types, schema, pointer, placement) + ref, nullDiags := schemaNullRef(loweringContext, built.id, schema, pointer) + return built, ref, diags, nullDiags + } + if built, ref, diags, afterDiags, lowered := lowerConjunctionUnion(loweringContext, types, depth, schema, pointer, placement); lowered { + if placement.position == nil { + afterDiags = append(afterDiags, diagNullRefusedTwice(loweringContext, schema, pointer)...) } - return lowerOneOfAnyOf(loweringContext, ts, depth, schema, pointer, fin, st) - } - unionAt, how, ok := entryUnion(loweringContext, schema, pointer) - if ok { - lowerUnion := lowerDistributedUnion - if how == unionRoutedSubtype { - lowerUnion = lowerSubtypeUnion + return built, ref, diags, afterDiags + } + built, bodyDiags, afterDiags := lower(loweringContext, types, depth, schema, pointer, placement) + if placement.position == nil { + bodyDiags = append(bodyDiags, keepLiftedNulls(loweringContext, schema, pointer, placement, &built)...) + } + if placement.position == nil && built.node != nil && !decisionOf(loweringContext, schema).refines() { + // A refinement keeps them as it keeps what its conjuncts leave (keptUnion). + bodyDiags = append(bodyDiags, keepOwnUnions(loweringContext, &built.node.Common().Unmodeled, schema, pointer)...) + } + if placement.position == nil { + afterDiags = append(afterDiags, diagDeadWhereNoUnionChosen(loweringContext, schema, pointer)...) + afterDiags = append(afterDiags, diagNullRefusedTwice(loweringContext, schema, pointer)...) + } + if placement.position == nil && keepsEntryUnion(loweringContext, schema) { + if built.node == nil && !LoweredToOwnNode(loweringContext, pointer, ir.TypeRef{Target: built.id}) { + // The body reduced to a shared target, so an alias the position + // owns keeps the union, as one beside the allOf is kept + // (lowerBesideUnmodeledUnion). + var aliasDiags []ir.Diagnostic + built, aliasDiags = internAlias(loweringContext, types, schema, pointer, scalarBase(loweringContext, schema, placement, built.id), placement) + bodyDiags = append(bodyDiags, aliasDiags...) } - id, unionDiags := lowerUnion(loweringContext, ts, depth, schema, unionAt, pointer, fin) - ref, nullDiags := schemaNullRef(loweringContext, id, schema, siteAt(pointer)) - return ref, append(unionDiags, nullDiags...) - } - if how == unionHierarchyBase || how == unionNoLiveBranch || how == unionSharesNoKind || how == unionPassedApart || - how == unionPassedNull { - // The union stays with its branch, and the discriminator standing with it - // on the model, held to its routes as one beside the union is. - fin = discriminatorBesideUnion(loweringContext, ts, schema, unionAt.holder, pointer).then(fin) - } - id, bodyDiags := lower(loweringContext, ts, depth, schema, pointer, fin, st) - if how == unionNoLiveBranch { - bodyDiags = append(bodyDiags, diagDeadEntryUnion(loweringContext, schema, unionAt, pointer)...) + afterDiags = append(afterDiags, keptEntryUnion(loweringContext, schema, pointer, built)...) + } + ref, nullDiags := schemaNullRef(loweringContext, built.id, schema, pointer) + return built, ref, bodyDiags, append(afterDiags, nullDiags...) +} + +// lowerConjunctionUnion lowers schema, written at pointer, where the union its +// conjunction chooses is its lowering: schema's own, or an entry's distributed +// across the composition or composed as a routed subtype's mixin. It returns +// the findings apart as lowerSchemaBody does; lowered is false where schema +// lowers by its body (lower), as where an entry's union is kept or lowered as +// the principal. +func lowerConjunctionUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + placement nodePlacement, +) (built builtPosition, ref ir.TypeRef, diags, afterDiags []ir.Diagnostic, lowered bool) { + if declaresUnion(schema) && unionLoweredAlone(loweringContext, placement.positionOrSchema(schema), schema) { + if placement.position == nil { + // The union's homes are decided here, the frame dispatching to it, + // as lowerPrincipal decides an inline principal's. + placement.homes = boundsHeldAt(loweringContext, schema, pointer) + } + built, ref, diags = lowerOneOfAnyOf(loweringContext, types, depth, schema, pointer, placement) + return built, ref, diags, nil, true + } + if declaresUnion(schema) && (placement.position != nil || loweredUnionWrittenBy(loweringContext, schema, schema)) { + built, diags = lowerCoDeclaredUnion(loweringContext, types, depth, schema, pointer, placement) + ref, afterDiags = schemaNullRef(loweringContext, built.id, schema, pointer) + return built, ref, diags, afterDiags, true + } + unionSite, how, ok := entryUnion(loweringContext, schema, pointer) + if !ok { + return builtPosition{}, ir.TypeRef{}, nil, nil, false + } + lowerUnion := lowerDistributedUnion + if how == unionRoutedSubtype { + lowerUnion = lowerSubtypeUnion + } + built, diags = lowerUnion(loweringContext, types, depth, schema, unionSite, pointer) + if built.node != nil && how != unionRoutedSubtype { + // A routed subtype's mixin keeps the unions it passes over + // (keepMixinPassedUnions). + diags = append(diags, keepOwnUnions(loweringContext, &built.node.Common().Unmodeled, schema, pointer)...) + } + ref, afterDiags = schemaNullRef(loweringContext, built.id, schema, pointer) + return built, ref, diags, afterDiags, true +} + +// keepsEntryUnion reports whether an inline entry of schema's allOf writes the +// union its conjunction chooses, which the body's node keeps +// (loweredUnionKeptReason). +func keepsEntryUnion(loweringContext lowering.Ctx, schema *statement.Schema) bool { + loweredUnion, ok := readConjunction(loweringContext, schema).loweredUnion() + if !ok || loweredUnion.holder == schema { + return false } - ref, nullDiags := schemaNullRef(loweringContext, id, schema, siteAt(pointer)) - return ref, append(bodyDiags, nullDiags...) + _, kept := loweredUnionKeptReason(loweringContext, schema) + return kept } -// refinesToEntry reports whether s, written at pointer, refines to one of its -// allOf entries, which then decides the position, a union beside the allOf -// being one of the conjuncts it refines (docs/compilers/openapi.md#allof-refinement). -func refinesToEntry(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) bool { - refinement, refines := refinementOf(loweringContext, schema, pointer) - return refines && refinement.principal != nil +// keptEntryUnion finishes built, schema's node, where an inline entry of its +// allOf writes the union its conjunction chooses and keeps it: the +// discriminator written with the union stays on the node, held to its routes, +// and the union's dead branches are reported as beside the allOf. +func keptEntryUnion(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, built builtPosition) []ir.Diagnostic { + unionSite, lowersUnion := loweredUnionAt(loweringContext, schema, pointer) + if !lowersUnion || !unionSite.holderIsAllOfEntry { + return nil + } + besideRest := readLoweredUnion(loweringContext, schema).besideRest + if built.node != nil && besideRest != unionNoneLowered && besideRest != unionAlone { + deferDiscriminatorBesideUnion(loweringContext, schema, unionSite.holder, built.node) + } + switch besideRest { + case unionKeptWithDeadBranch: + return diagDeadAtUnion(loweringContext, schema, pointer, false) + case unionLeavesNoBranch: + return diagDeadEntryUnion(loweringContext, schema, unionSite, pointer, keptBodyShape(built)) + default: + return nil + } } // allOfComposes reports whether schema writes an allOf that composes rather @@ -372,157 +467,197 @@ func allOfComposes(loweringContext lowering.Ctx, schema *statement.Schema) bool if !writesConjuncts(schema) { return false } - return !decisionOf(loweringContext, schema).refines + return !decisionOf(loweringContext, schema).refines() } -// lower interns the inline schema at pointer and returns its TypeID. An allOf -// that refines decides the position +// lower interns the inline schema at pointer and returns its builtPosition. An +// allOf that refines decides the position // (docs/compilers/openapi.md#allof-refinement): its principal, or where no // entry is one, the keywords beside it as if no allOf were written, an enum or // a const there being one of its conjuncts rather than its rival. A value set -// an inline principal writes stands at the position, as one written beside the +// an inline principal writes sits at the position, as one written beside the // allOf does, and either is typed by every conjunct (valueSetSite.valueType). -// Any other schema lowers by its dispatch (lowerDispatched). fin finishes the -// node built at pointer, principal an inline principal's. -func lower(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { - if st.of != nil { - // schema is the inline principal of the refinement st stands for, a +// Any other schema lowers by its dispatch (lowerDispatched). Findings reported +// after the settled ones (settleNode) are returned apart. +func lower(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement, +) (builtPosition, []ir.Diagnostic, []ir.Diagnostic) { + if placement.position != nil { + // schema is the inline principal of the refinement at placement's position, a // wrapper's allOf being the position's conjuncts and no rival of its // keywords (principalDispatch). - return lowerDispatched(loweringContext, ts, depth, schema, pointer, dispatchOf(schema).besideAllOf(), fin, st) + built, diags := lowerDispatched(loweringContext, types, depth, schema, pointer, dispatchOf(schema).besideAllOf(), placement, registeredAtBuild) + return built, diags, nil } dispatch, picked := dispatchAt(loweringContext, schema, pointer) refinement, refines := refinementOf(loweringContext, schema, pointer) if !refines { - return lowerDispatched(loweringContext, ts, depth, schema, pointer, dispatch, fin, st) + // What this position composes is finished by the frame lowering it, + // which registers it where it holds anything (schemaBody). + built, diags := lowerDispatched(loweringContext, types, depth, schema, pointer, dispatch, placement, registeredWhenFinished) + return built, diags, nil } // The node the position owns is reported on by the visit building it, as - // what it keeps unread is (keepingUnread); a node it does not own, by each + // what it keeps unread is (finishUnread); a node it does not own, by each // visit. - var disjoint finished - fin = finisher(func(td ir.TypeDef, _ keySet, held *principalKept) { - disjoint.ran = true - disjoint.diags = refinedDisjoint(loweringContext, schema, refinement, td, held) - }).then(fin) - reported := func(id ir.TypeID, diags []ir.Diagnostic) (ir.TypeID, []ir.Diagnostic) { - if !disjoint.ran && !LoweredToOwnNode(loweringContext, pointer, ir.TypeRef{Target: id}) { - disjoint.diags = refinedDisjoint(loweringContext, schema, refinement, nil, nil) - } - return id, append(diags, disjoint.diags...) - } - if entry, ok := valueSetPrincipal(refinement); ok { - resolveBeaten(loweringContext, ts, refinement) - return reported(lowerPrincipalValueSet(loweringContext, ts, schema, entry, pointer, fin)) + var built builtPosition + var diags, ownDiags []ir.Diagnostic + switch entry, isValueSet := valueSetPrincipal(refinement); { + case isValueSet: + resolvePassedOverRefs(loweringContext, types, refinement) + built, diags, ownDiags = lowerPrincipalValueSet(loweringContext, types, schema, entry, pointer) + case picked && refinement.sharesNoMember && dispatch.lowered == "": + // Only $ref targets state the sets, which share no member. + resolvePassedOverRefs(loweringContext, types, refinement) + built, diags = finishUnread(loweringContext, types, schema, pointer, dispatch, placement, lowerRefSets(loweringContext, types, schema, pointer, refinement.admittedTogether), 0) + case picked: + resolvePassedOverRefs(loweringContext, types, refinement) + built, diags = lowerDispatched(loweringContext, types, depth, schema, pointer, dispatch, placement, registeredAtBuild) + default: + built, diags = lowerPrincipal(loweringContext, types, depth, schema, pointer, refinement) } - if picked { - resolveBeaten(loweringContext, ts, refinement) - return reported(lowerDispatched(loweringContext, ts, depth, schema, pointer, dispatch, fin, st)) + var disjointDiags []ir.Diagnostic + switch { + case built.node != nil: + disjointDiags = refinedDisjoint(loweringContext, schema, refinement, built.node, built.shape, built.id) + case !LoweredToOwnNode(loweringContext, pointer, ir.TypeRef{Target: built.id}): + disjointDiags = refinedDisjoint(loweringContext, schema, refinement, nil, "", built.id) } - return reported(lowerPrincipal(loweringContext, ts, depth, schema, pointer, refinement, fin)) + return built, diags, slices.Concat(ownDiags, disjointDiags) } // refinedDisjoint reports the refinement refinementValue of schema whose union -// beside the allOf shares no kind with the rest (unionAside), or whose -// conjuncts share no value and lowered to the value set elected before them or +// beside the allOf shares no kind with the rest (unionLeavesNoBranch), or whose +// conjuncts share no value and lowered to the value set chosen before them or // to what the keywords beside the allOf say (contradictionShape), at schema, as -// a composition reports conjuncts sharing no value, standing being the node the -// position owns, nil where it owns none, and held how its builder names it +// a composition reports conjuncts sharing no value, positionNode being the node +// the position owns, nil where it owns none, and named how its builder names it // (refinedShape). -func refinedDisjoint(loweringContext lowering.Ctx, schema *statement.Schema, refinementValue refinement, standing ir.TypeDef, held *principalKept) []ir.Diagnostic { - shape := refinedShape(loweringContext, schema, refinementValue.comp, refinementValue.principal, standing, held) +func refinedDisjoint(loweringContext lowering.Ctx, schema *statement.Schema, refinementValue refinement, positionNode ir.TypeDef, named string, + target ir.TypeID, +) []ir.Diagnostic { + comp := refinementValue.comp + comp.disjoint = refinedDisjointNames(loweringContext, schema, refinementValue) + shape := refinedShape(loweringContext, schema, refinementValue.comp, refinementValue.principal, positionNode, named) switch { - case unionAside(loweringContext, schema): + case readLoweredUnion(loweringContext, schema).besideRest == unionLeavesNoBranch: case refinementValue.contradicts: shape = contradictionShape(refinementValue, schema) + default: + shape = unionShape(loweringContext, schema) + } + if shape == undecidedShape { + // The report says what was built, not the rule that built it. + shape = builtShape(positionNode, target) + } + return diagDisjointConjuncts(loweringContext, schema, comp, shape) +} + +// refinedDisjointNames names the conjuncts refinedDisjoint's report of +// refinementValue names: where its union beside the allOf leaves no branch, its +// conjuncts contradict, or an entry's union with no branch dead is the position +// (lowerOneOfAnyOf). Elsewhere it draws no report, and none are named. +func refinedDisjointNames(loweringContext lowering.Ctx, schema *statement.Schema, refinementValue refinement) []string { + switch { + case readLoweredUnion(loweringContext, schema).besideRest == unionLeavesNoBranch, refinementValue.contradicts: + case unionPrincipal(loweringContext, schema) != nil && !slices.Contains(readLoweredUnion(loweringContext, schema).dead, true): default: return nil } - comp := refinementValue.comp - comp.disjoint = disjointAtoms(loweringContext, schema, refinedAtoms(loweringContext, schema, refinementValue)) - if len(comp.disjoint) == 0 { - comp.disjoint = pairApart(loweringContext, schema) + names := disjointAtoms(loweringContext, schema, refinedAtoms(loweringContext, schema, refinementValue)) + if len(names) == 0 { + names = pairReadingOf(loweringContext, schema).apart } - if len(comp.disjoint) == 0 && refinementValue.contradicts { - comp.disjoint = conjunctsApart(loweringContext, schema) + if len(names) == 0 && refinementValue.contradicts { + names = conjunctsApart(loweringContext, schema) } - return diagDisjointConjuncts(loweringContext, comp, shape) + return names } -// dispatchAt returns the dispatch lower lowers s by, written at pointer, and -// false where an allOf refining it has a principal, which decides the position -// instead: the keywords beside the allOf, as if none were written, for one -// refining with none. +// dispatchAt returns the dispatch lower lowers schema by, written at pointer, +// and false where an allOf refining it has a principal, which decides the +// position instead: the keywords beside the allOf, as if none were written, for +// one refining with none. func dispatchAt(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (dispatch, bool) { if refinement, refines := refinementOf(loweringContext, schema, pointer); refines && refinement.principal != nil { return dispatch{}, false } - return ownDispatch(loweringContext, schema), true + return ownDispatch(loweringContext, schema, bottomAt(loweringContext, schema)), true } // ownDispatch returns the dispatch among the keywords schema writes itself: its -// own (dispatchOf), or, where its allOf refines, that of the keywords beside -// the allOf, as if none were written (besideAllOf). It is what lower lowers -// schema by where no entry of the allOf decides the position (dispatchAt), so a -// reader asking ahead of the build what those keywords build asks it too -// (buildsModel). -func ownDispatch(loweringContext lowering.Ctx, schema *statement.Schema) dispatch { +// own (dispatchOf), that of the keywords beside a refining allOf (besideAllOf), +// or the allOf where bottom says it is the bottom (composing). It is what lower +// lowers schema by where no allOf entry decides the position (dispatchAt), so a +// reader asking ahead of the build asks it too. The caller reads bottom once +// (bottomAt) and hands it to every reader of the dispatch. +func ownDispatch(loweringContext lowering.Ctx, schema *statement.Schema, bottom bool) dispatch { dispatchValue := dispatchOf(schema) - if decisionOf(loweringContext, schema).refines { + switch { + case decisionOf(loweringContext, schema).refines(): return dispatchValue.besideAllOf() + case bottom: + return dispatchValue.composing() + default: + return dispatchValue } - return dispatchValue } -// lowersTypeArray reports whether s, written at pointer, lowers by its type list -// (lowerTypeList): its types are those it writes, more than one (typingOf), and -// lower picks no family. Nothing lowerSchemaBody tries first takes such a -// schema: a type is a shape, so no $dynamicRef expands and no union collapses -// beside it, and a union beside it or on an allOf entry distributes only over -// the allOf, which the dispatch picks. +// composing returns d with the allOf picked and every other family passed over, +// as an allOf whose conjuncts' kinds share none is the bottom, which no value +// set beside it decides (docs/compilers/openapi.md#allof-refinement). +func (d dispatch) composing() dispatch { + if d.lowered == "allOf" { + return d + } + return dispatch{lowered: "allOf", skipped: slices.DeleteFunc(append([]string{d.lowered}, d.skipped...), func(family string) bool { return family == "allOf" })} +} + +// lowersTypeArray reports whether schema, written at pointer, lowers by its +// type list (lowerTypeList): its types are those it writes, more than one +// (typingOf), and lower picks no family. Nothing lowerSchemaBody tries first +// takes such a schema: a type is a shape, so no $dynamicRef expands and no +// union collapses beside it, and a union beside it or on an allOf entry +// distributes only over the allOf, which the dispatch picks. func lowersTypeArray(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) bool { if typing := typingOf(loweringContext, schema); typing.by != byType || len(typing.types) < 2 { return false } dispatch, picked := dispatchAt(loweringContext, schema, pointer) - return picked && dispatch.won == "" + return picked && dispatch.lowered == "" } -// lowerDispatched lowers s, at pointer, by the family d picks, which takes -// precedence over the structural type, else by its types (lowerTyping). The -// families are conjoined where a schema writes more than one, so -// picking a winner is a degradation +// lowerDispatched lowers schema, at pointer, by the family dispatchValue picks, +// which takes precedence over the structural type, else by its types +// (lowerTyping). The families are conjoined where a schema writes more than +// one, so picking one is a degradation // (docs/compilers/openapi.md#competing-keywords): the ones passed over are kept // verbatim beside it (recordSkippedFamilies). A keyword the picked lowering // never reads, such as `type: string` beside an allOf, is kept unread -// (keepingUnread), which keeps what the build did not read. fin -// finishes the node built at pointer after that keeping. -func lowerDispatched(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, dispatchValue dispatch, fin finisher, - st stand, -) (ir.TypeID, []ir.Diagnostic) { - kept := func(build func(fin finisher) (ir.TypeID, []ir.Diagnostic)) (ir.TypeID, []ir.Diagnostic) { - return keepingUnread(loweringContext, ts, schema, pointer, dispatchValue, fin, st, func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) { - id, diags := build(fin) - return id, 0, diags - }) - } - switch dispatchValue.won { +// (finishUnread), which keeps what the build did not read. +func lowerDispatched(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, dispatchValue dispatch, + placement nodePlacement, when registration, +) (builtPosition, []ir.Diagnostic) { + var built builtPosition + var diags []ir.Diagnostic + switch dispatchValue.lowered { case "const": - return kept(func(fin finisher) (ir.TypeID, []ir.Diagnostic) { - return lowerConst(loweringContext, ts, standingValueSet(schema, pointer, st).finishedBy(fin)) - }) + built, diags = lowerConst(loweringContext, types, placedValueSet(schema, pointer, placement)) case "enum": - return kept(func(fin finisher) (ir.TypeID, []ir.Diagnostic) { - return lowerEnum(loweringContext, ts, standingValueSet(schema, pointer, st).finishedBy(fin)) - }) + built, diags = lowerEnum(loweringContext, types, placedValueSet(schema, pointer, placement)) case "allOf": - return kept(func(fin finisher) (ir.TypeID, []ir.Diagnostic) { - return lowerAllOf(loweringContext, ts, depth, schema, pointer, !slices.Contains(dispatchValue.said, "discriminator"), dispatchValue.mixin, fin) - }) + built, diags = lowerAllOf(loweringContext, types, depth, schema, pointer, !slices.Contains(dispatchValue.restated, "discriminator"), dispatchValue.mixin, when) + default: + // lowered is "": the schema declares no family, or only an allOf that + // refines with no entry deciding what the position is, so its types + // decide. + homes := placement.homes + if placement.position == nil { + homes = boundsHeldAt(loweringContext, schema, pointer) + } + return lowerTyping(loweringContext, types, depth, schema, pointer, dispatchValue, typingOfFlatSpelling(typingOf(loweringContext, schema), placement.flatSpellingType), homes, placement) } - // won is "": the schema declares no family, or only an allOf that refines - // with no entry deciding what the position is, so its types decide. - return lowerTyping(loweringContext, ts, depth, schema, pointer, dispatchValue, typingOf(loweringContext, schema), fin, st) + built, unreadDiags := finishUnread(loweringContext, types, schema, pointer, dispatchValue, placement, built, 0) + return built, slices.Concat(diags, unreadDiags) } // typedBy is what names the types a schema picking no family lowers by. @@ -533,6 +668,10 @@ const ( byType typedBy = iota // byNull marks a type naming null alone, which leaves no type to build. byNull + // byNullIntersection marks the conjuncts of an allOf admitting null alone + // together (decision.intersectionIsNullAlone), lowering as `{type: 'null'}` + // does. + byNullIntersection // byShape marks an object, an array or both, as the schema's shape keywords // speak of them (untypedKinds). byShape @@ -562,8 +701,11 @@ func (t typing) object() bool { return len(t.types) == 1 && t.types[0] == statem // speak of (untypedKinds), in the order a type array listing both writes // them; else by what the conjuncts of its allOf admit (undecidedTypes). It is // the one reading of that: lowerTyping builds by it, and a reader asking ahead -// of the build what will stand there reads it too (nodeHomes, buildsModel). +// of the build what will sit there reads it too (nodeHomes). func typingOf(loweringContext lowering.Ctx, schema *statement.Schema) typing { + if decisionOf(loweringContext, schema).outcome == decisionRefinesNullIntersection { + return typing{by: byNullIntersection} + } if types := effectiveTypes(schema); len(types) > 0 { return typing{types: types} } @@ -574,7 +716,7 @@ func typingOf(loweringContext lowering.Ctx, schema *statement.Schema) typing { if kinds == 0 { return typing{types: undecidedTypes(loweringContext, schema), by: byConjuncts} } - types := slices.DeleteFunc(slices.Clone(inferredKinds), func(st statement.JSONSchemaTypeName) bool { return typeKinds(st)&kinds == 0 }) + types := slices.DeleteFunc(slices.Clone(inferredKinds), func(typeName statement.JSONSchemaTypeName) bool { return kindsOfTypeNameOrAny(typeName)&kinds == 0 }) return typing{types: types, by: byShape, inferred: inferred} } @@ -584,63 +726,56 @@ func typingOf(loweringContext lowering.Ctx, schema *statement.Schema) typing { // or an array its shape keywords speak of marked where the kind-inference // policy read the kind; a type naming null alone to the value set of null; and // nothing naming a kind to the top type. The keywords the node cannot hold are -// kept beside it (keepingUnread, keepUnreadAcross). fin finishes the node -// standing at pointer. -func lowerTyping(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, dispatchValue dispatch, typingValue typing, - fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { - var mark finisher - if typingValue.inferred { - mark = markKindInferred - } - var build func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) +// kept beside it (finishUnread, keepUnreadAcross). +func lowerTyping(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, dispatchValue dispatch, typingValue typing, + homes boundHomes, placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { + if len(typingValue.types) > 1 { + return lowerTypeList(loweringContext, types, depth, schema, pointer, typingValue, placement) + } + var built builtPosition + var shared keySet + var diags []ir.Diagnostic switch { case typingValue.by == byNull: // Every type schema names is null, so its value space is null and nothing // else, which is no schemaless position's (docs/compilers/openapi.md#null-alone). - build = func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) { - return lowerNullAlone(loweringContext, ts, standingValueSet(schema, pointer, st).finishedBy(fin)), 0, nil - } + built = lowerNullAlone(loweringContext, types, placedValueSet(schema, pointer, placement)) + case typingValue.by == byNullIntersection: + built = lowerNullIntersection(loweringContext, types, placedValueSet(schema, pointer, placement)) case typingValue.top(): - build = func(finisher) (ir.TypeID, keySet, []ir.Diagnostic) { return ts.PrimitiveID(ir.PrimitiveAny), 0, nil } - case len(typingValue.types) > 1: - return lowerTypeList(loweringContext, ts, depth, schema, pointer, typingValue, fin, st) + built = builtPosition{id: types.PrimitiveID(ir.PrimitiveAny)} case typingValue.by == byShape && typingValue.object(): // The node asserts an object, as the bounds beside it read it // (boundKinds): one an object does not take is kept. - build = func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) { - id, diags := lowerModel(loweringContext, ts, depth, schema, pointer, true /* discriminated */, boundKinds(loweringContext, schema), mark.then(fin)) - return id, 0, diags - } + built, diags = lowerModelAt(loweringContext, types, depth, schema, pointer, pointer, lowersDiscriminator, boundKinds(loweringContext, schema), nil, nil) case typingValue.by == byShape: - build = func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) { - id, diags := lowerArray(loweringContext, ts, depth, schema, pointer, st.pointer(pointer), st.foldedEntries(loweringContext, schema, pointer), mark.then(fin)) - return id, 0, diags - } + built, diags = lowerArray(loweringContext, types, depth, schema, pointer, placement, placement.flattenedEntries(loweringContext, schema, pointer), homes) default: - build = func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) { - return lowerTyped(loweringContext, ts, depth, schema, pointer, typingValue.types[0], fin, st) - } + built, shared, diags = lowerTyped(loweringContext, types, depth, schema, pointer, typingValue.types[0], homes, placement) } - return keepingUnread(loweringContext, ts, schema, pointer, dispatchValue, fin, st, build) + if typingValue.inferred && built.node != nil { + markKindInferred(built.node) + } + built, unreadDiags := finishUnread(loweringContext, types, schema, pointer, dispatchValue, placement, built, shared) + return built, slices.Concat(diags, unreadDiags) } -// lowerTyped dispatches a single-typed schema to its structural or scalar form, -// fin finishing the node it builds at pointer, and returns what a lowering to -// a shared primitive read. -func lowerTyped(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, kind statement.JSONSchemaTypeName, - fin finisher, st stand, -) (ir.TypeID, keySet, []ir.Diagnostic) { +// lowerTyped dispatches a single-typed schema to its structural or scalar form +// and returns what a lowering to a shared primitive read. +func lowerTyped(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, kind statement.JSONSchemaTypeName, + homes boundHomes, placement nodePlacement, +) (builtPosition, keySet, []ir.Diagnostic) { switch kind { case statement.KindObject: // An object composes, so no refinement's principal reaches here. - id, diags := lowerModel(loweringContext, ts, depth, schema, pointer, true /* discriminated */, kindObject, fin) - return id, 0, diags + built, diags := lowerModelAt(loweringContext, types, depth, schema, pointer, pointer, lowersDiscriminator, kindObject, nil, nil) + return built, 0, diags case statement.KindArray: - id, diags := lowerArray(loweringContext, ts, depth, schema, pointer, st.pointer(pointer), st.foldedEntries(loweringContext, schema, pointer), fin) - return id, 0, diags + built, diags := lowerArray(loweringContext, types, depth, schema, pointer, placement, placement.flattenedEntries(loweringContext, schema, pointer), homes) + return built, 0, diags default: - return scalarTypeID(loweringContext, ts, depth, schema, kind, pointer, fin, st) + return scalarTypeID(loweringContext, types, depth, schema, kind, pointer, homes, placement) } } @@ -650,14 +785,14 @@ func lowerTyped(loweringContext lowering.Ctx, ts *compile.Types, depth int, sche // the rest — which is why the two are derived together rather than separately. var familyOrder = []string{"const", "enum", "allOf"} -// declaresFamily reports whether s declares the named family. It is the single -// definition of each family's guard: lower() lowers what dispatchOf picks and -// recordSkippedFamilies keeps what the same walk passed over, so the winner and -// the losers can never be read off two tests that disagree. -// A name it does not know declares nothing, rather than falling through to -// another family's guard: a familyOrder entry added without a case here would -// otherwise report whichever guard the default happened to hold, picking that -// name on schemas that never wrote it. +// declaresFamily reports whether schema declares the named family. It is the +// single definition of each family's guard: lower() lowers what dispatchOf +// picks and recordSkippedFamilies keeps what the same walk passed over, so the +// one picked and the ones passed over can never be read off two tests that +// disagree. A name it does not know declares nothing, rather than falling +// through to another family's guard: a familyOrder entry added without a case +// here would otherwise report whichever guard the default happened to hold, +// picking that name on schemas that never wrote it. func declaresFamily(schema *statement.Schema, family string) bool { switch family { case "const": @@ -685,65 +820,56 @@ func enumWritten(schema *statement.Schema) bool { } // dispatch records how lower() resolved a schema's competing keyword families: -// the one it lowered, and the ones it passed over. won is "" when the schema -// declares none of them and the type set decides the lowering instead. said -// names the keywords a union's branches all say already (branchesSay), which -// the position consumes though its node has no field for them. +// the one it lowered, and the ones it passed over. lowered is "" when the +// schema declares none of them and the type set decides the lowering instead. +// restated names the keywords a union's branches all restate +// (keywordsBranchesRestate), which the position consumes though its node has no +// field for them. type dispatch struct { - won string - skipped []string - said []string + lowered string + skipped []string + restated []string // mixin is the union a routed subtype composes (lowerSubtypeUnion), which // the build of its model mints, nil where the position composes none. - mixin *unionAt + mixin *loweredUnionSite } // handled returns the keys of readDomain the dispatch accounted for: the // families it passed over, which recordSkippedFamilies keeps, and the keywords // the branches say. func (d dispatch) handled() keySet { - return keySetOf(d.skipped...) | keySetOf(d.said...) + return keySetOf(d.skipped...) | keySetOf(d.restated...) } -// buildsModel reports whether lowerDispatched, lowering schema by d, builds a -// Model, the only node with composition fields for a union to distribute -// across: d picks an allOf, which composes one (lowerAllOf), or no family, and -// schema lowers as one object (typingOf). So a bare property set, `required`, -// closure or catch-all beside branches each declaring an object builds one, as -// beside `type: object`. -func (d dispatch) buildsModel(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return d.won == "allOf" || d.won == "" && typingOf(loweringContext, schema).object() -} - -// besideAllOf returns the dispatch lower() makes of the keywords beside s's -// allOf, d being s's own: the one of a schema writing no allOf, as a refinement -// whose principal is no entry lowers. allOf is the last of familyOrder, so it -// wins only where no other family is written. +// besideAllOf returns the dispatch lower() makes of the keywords beside a +// schema's allOf, d being that schema's own: the one of a schema writing no +// allOf, as a refinement whose principal is no entry lowers. allOf is the last +// of familyOrder, so it wins only where no other family is written. func (d dispatch) besideAllOf() dispatch { - out := dispatch{skipped: slices.DeleteFunc(slices.Clone(d.skipped), func(f string) bool { return f == "allOf" })} - if d.won != "allOf" { - out.won = d.won + out := dispatch{skipped: slices.DeleteFunc(slices.Clone(d.skipped), func(family string) bool { return family == "allOf" })} + if d.lowered != "allOf" { + out.lowered = d.lowered } return out } // dispatchOf picks the family lower() lowers and collects the rest. A schema -// declaring none leaves won empty and skipped nil. +// declaring none leaves lowered empty and skipped nil. // // familyOrder, declaresFamily and lowerDispatched's switch must name the same -// families. A name declaresFamily does not know is never picked, and a loser -// reaches recordSkippedFamilies whether or not lowerDispatched can lower it, but a -// winner lowerDispatched has no arm for is neither lowered nor skipped: the switch -// falls through to the type-set arms and drops the keyword in silence (GitHub #35). -// Adding a family means adding all three. +// families. A name declaresFamily does not know is never picked, and a family +// passed over reaches recordSkippedFamilies whether or not lowerDispatched can +// lower it, but a family picked that lowerDispatched has no arm for is neither +// lowered nor skipped: the switch falls through to the type-set arms and drops +// the keyword in silence (GitHub #35). Adding a family means adding all three. func dispatchOf(schema *statement.Schema) dispatch { var dispatchValue dispatch for _, family := range familyOrder { if !declaresFamily(schema, family) { continue } - if dispatchValue.won == "" { - dispatchValue.won = family + if dispatchValue.lowered == "" { + dispatchValue.lowered = family continue } dispatchValue.skipped = append(dispatchValue.skipped, family) @@ -751,54 +877,102 @@ func dispatchOf(schema *statement.Schema) dispatch { return dispatchValue } -// recordSkippedFamilies keeps verbatim the keyword families lower()'s dispatch -// passed over, and reports them once. +// recordSkippedFamilies keeps verbatim on unmodeled, typeDef's map, nil for an +// entry owning no node, the keyword families lower()'s dispatch passed over, +// and reports them once. // -// JSON Schema conjoins keywords, so `{const: a, enum: [a, b]}` admits a alone, -// no malformed document. The IR has no intersection combinator +// JSON Schema conjoins keywords, so `{const: a, enum: [a, b]}` admits a alone. +// The IR has no intersection combinator // (docs/ir/boundaries.md#deliberate-exclusions), so only one family can be the -// value; keeping the loser beside it is what the rule -// docs/compilers/openapi.md#competing-keywords asks of an unrepresentable -// conjunction. +// value, the one passed over kept beside it +// (docs/compilers/openapi.md#competing-keywords). // -// It reports what it stored, as the node holds it (keepConjuncts), never what -// it was handed, so the message cannot claim a keyword that failed to convert. -// An allOf whose conjuncts share no value draws its warning, stored or not. -func recordSkippedFamilies(loweringContext lowering.Ctx, td ir.TypeDef, schema *statement.Schema, dispatchValue dispatch, pointer jsontext.Pointer) []ir.Diagnostic { +// It reports what it stored (keepConjuncts), never what it was handed, each +// report paired with its family's key, the first stored's for all. An allOf +// whose conjuncts share no value draws its warning, stored or not. +func recordSkippedFamilies(loweringContext lowering.Ctx, typeDef ir.TypeDef, unmodeled *ir.Unmodeled, schema *statement.Schema, dispatchValue dispatch, + pointer jsontext.Pointer, +) annotation.KeptReports { if len(dispatchValue.skipped) == 0 { return nil } - var diags []ir.Diagnostic - common := td.Common() + var reports annotation.KeptReports written := make([]string, 0, len(dispatchValue.skipped)) named := make([]string, 0, len(dispatchValue.skipped)) + apart := dispatchValue.lowered == "const" && emptySetNode(typeDef) && constEnumDisjointAt(loweringContext, schema) for _, keyword := range dispatchValue.skipped { + if keyword == "enum" && dispatchValue.lowered == "const" && constEnumOverlapOf(loweringContext, schema) == constBesideEmptyEnum { + // The empty enum is the node the const lowered to (lowerConst). + continue + } + if apart && keyword == "enum" { + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), keepSetApart(loweringContext, typeDef, unmodeled, schema, pointer)...)...) + continue + } if keyword == "allOf" { - conjuncts, as, keptDiags := keepConjuncts(loweringContext, &common.Unmodeled, schema, pointer) - diags = append(diags, keptDiags...) + conjuncts, as, keptDiags := keepConjuncts(loweringContext, unmodeled, schema, pointer) + reports = append(reports, annotation.ReportsOf("", keptDiags...)...) written, named = append(written, conjuncts...), append(named, as...) continue } - stored, storedDiags := preserveSchemaKeyword(loweringContext, &common.Unmodeled, schema, keyword, + stored, storedDiags := keepSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonDegradedLowering, pointer) - diags = append(diags, storedDiags...) + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), storedDiags...)...) if stored { written, named = append(written, keyword), append(named, keyword) } } - if len(written) > 0 { - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + // The bottom, which keeps every keyword, reports them in its one warning + // (composeBottom). + if len(written) > 0 && (dispatchValue.lowered != "allOf" || !bottomAt(loweringContext, schema)) { + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", written[0]), loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, "this position declares %s beside its %s, and JSON Schema conjoins them where only "+ "one can be the value; it lowered as the %s, with %s kept verbatim under Unmodeled", - strings.Join(written, " and "), dispatchValue.won, dispatchValue.won, strings.Join(named, " and "))) + strings.Join(written, " and "), dispatchValue.lowered, dispatchValue.lowered, strings.Join(named, " and ")))...) } if !slices.Contains(dispatchValue.skipped, "allOf") { - return diags + return reports } // An allOf that refines is no rival of the value set (lower), so one passed // over composes, and its conjuncts may share no value, as they are read where // it wins (lowerAllOf), whether or not the allOf could be kept. - return append(diags, diagDisjointConjuncts(loweringContext, readAllOf(loweringContext, schema, pointer), "the "+dispatchValue.won+" it lowered as")...) + return append(reports, annotation.ReportsOf("", diagDisjointConjuncts(loweringContext, schema, readAllOf(loweringContext, schema, pointer), "its "+dispatchValue.lowered)...)...) +} + +// constEnumDisjointAt reports whether the const and the enum schema writes +// share no member, and the node they lower to admits no value +// (constEnumOverlapOf). +func constEnumDisjointAt(loweringContext lowering.Ctx, schema *statement.Schema) bool { + apart := constEnumOverlapOf(loweringContext, schema) + return apart == constEnumEmpty || apart == constEnumBottom +} + +// emptySetNode reports whether typeDef admits no value: a closed Enum with no +// member, or the closed Model with no member a false schema lowers to. +func emptySetNode(typeDef ir.TypeDef) bool { + switch node := typeDef.(type) { + case *ir.Enum: + return node.Closed && len(node.Members) == 0 + case *ir.Model: + return node.Additional == ir.AdditionalClosed && len(node.Properties) == 0 + default: + return false + } +} + +// keepSetApart keeps verbatim the enum schema writes beside a const sharing no +// member with it, which the dispatch passed over, and reports that no instance +// satisfies schema: typeDef admits no value, so it holds the members of neither +// set (docs/compilers/openapi.md#enum-const). +func keepSetApart(loweringContext lowering.Ctx, typeDef ir.TypeDef, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + _, diags := keepSchemaKeyword(loweringContext, unmodeled, schema, "enum", ir.ReasonDegradedLowering, pointer) + shape := "a closed enum with no member" + if isKind(typeDef, ir.KindModel) { + shape = "the closed model with no member a false schema lowers to" + } + return append(diags, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, pointer, + "the const and enum this schema writes share no member, so no instance satisfies it; it lowered as %s, "+ + "which holds the members of neither", shape)) } // writesType reports whether schema writes a type. A YAML null, which the diff --git a/compilers/openapi/internal/schema/schema_budgets_test.go b/compilers/openapi/internal/schema/schema_budgets_test.go index b1b0cec2a..a3aeb5b2c 100644 --- a/compilers/openapi/internal/schema/schema_budgets_test.go +++ b/compilers/openapi/internal/schema/schema_budgets_test.go @@ -6,6 +6,7 @@ package schema_test import ( "context" "encoding/json/jsontext" + "strconv" "testing" "github.com/stretchr/testify/assert" @@ -40,17 +41,17 @@ components: {"at the budget", 3, false}, {"one member past the budget", 2, true}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() lowerer, _ := schema.LoweredFor(t, spec) - lowerer.Ctx.Limits = lowering.Limits{MaxEnumMembers: budget.AtMost(tc.limit)} + lowerer.Ctx.Limits = lowering.Limits{MaxEnumMembers: budget.AtMost(testCase.limit)} diags := schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas()) node := typeByName(lowerer.Document(t), "E") require.NotNil(t, node) - if !tc.refused { + if !testCase.refused { openapitest.RequireNoErrorDiags(t, diags) enum, ok := node.(*ir.Enum) require.True(t, ok) @@ -103,3 +104,55 @@ components: assert.Empty(t, finished) assert.Empty(t, reg, "a cancelled walk lowers no component") } + +// TestLowerComponentSchemas_AUnionOfValueSetsTakesTheEnumBudget holds a union +// of value sets beside a body to the budget an enum takes, over the members +// its branches write, in either spelling: at the budget it is the Enum of +// them; one past it, the top type, refused at the position as an enum is, +// the union read and kept nowhere. +func TestLowerComponentSchemas_AUnionOfValueSetsTakesTheEnumBudget(t *testing.T) { + t.Parallel() + const spec = `openapi: 3.1.0 +info: {title: T, version: "1"} +paths: {} +components: + schemas: + Flat: {type: string, oneOf: [{enum: [a, b]}, {const: c}]} + Entry: {type: string, allOf: [{anyOf: [{enum: [a, b]}, {enum: [c]}]}]} +` + for _, limit := range []int{3, 2} { + t.Run(strconv.Itoa(limit), func(t *testing.T) { + t.Parallel() + lowerer, _ := schema.LoweredFor(t, spec) + lowerer.Ctx.Limits = lowering.Limits{MaxEnumMembers: budget.AtMost(limit)} + diags := schema.LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas()) + doc := lowerer.Document(t) + for _, name := range []string{"Flat", "Entry"} { + node := typeByName(doc, name) + at := "/components/schemas/" + name + if limit == 3 { + enum, ok := node.(*ir.Enum) + require.True(t, ok, "%s at the budget is the Enum of its members; got %T", name, node) + assert.Len(t, enum.Members, 3, name) + assert.False(t, openapitest.HasDiagCodeAt(diags, diag.BudgetExceeded, at), name) + continue + } + _, ok := node.(*ir.Any) + assert.True(t, ok, "%s past the budget is the top type; got %T", name, node) + assert.Equal(t, 1, countAt(diags, diag.BudgetExceeded, ir.SeverityError, at), name) + assert.Empty(t, node.Common().Unmodeled, "%s keeps its union nowhere", name) + } + }) + } +} + +// countAt is how many of diags carry code and severity at pointer. +func countAt(diags []ir.Diagnostic, code string, severity ir.Severity, pointer string) int { + count := 0 + for _, diagnostic := range diags { + if diagnostic.Code == code && diagnostic.Severity == severity && string(diagnostic.Provenance.Pointer) == pointer { + count++ + } + } + return count +} diff --git a/compilers/openapi/internal/schema/schema_internal_test.go b/compilers/openapi/internal/schema/schema_internal_test.go index adcd91a4f..7cf0a0d4c 100644 --- a/compilers/openapi/internal/schema/schema_internal_test.go +++ b/compilers/openapi/internal/schema/schema_internal_test.go @@ -20,16 +20,16 @@ import ( func TestLower_DepthCapExceeded(t *testing.T) { t.Parallel() - var b strings.Builder - b.WriteString(" Deep:\n") + var builder strings.Builder + builder.WriteString(" Deep:\n") indent := " " for range maxSchemaDepth + 4 { - b.WriteString(indent + "type: array\n") - b.WriteString(indent + "items:\n") + builder.WriteString(indent + "type: array\n") + builder.WriteString(indent + "items:\n") indent += " " } - b.WriteString(indent + "type: string\n") - doc, diags := LowerSpec(t, openapitest.ComponentSpec(b.String())) + builder.WriteString(indent + "type: string\n") + doc, diags := LowerSpec(t, openapitest.ComponentSpec(builder.String())) require.NotNil(t, doc) var sawCap bool for _, diagnostic := range diags { @@ -74,9 +74,9 @@ func TestLower_ASchemaPastTheMendsIsTheTopType(t *testing.T) { // // It guards the direction the default falls. Answering an unknown name from // another family's guard would let a familyOrder entry added without a case be -// picked on schemas that never wrote it — and a winner lowerDispatched has no arm -// for is dropped in silence (GitHub #35). Declaring nothing keeps such a name out -// of the dispatch entirely. +// picked on schemas that never wrote it — and a family picked that +// lowerDispatched has no arm for is dropped in silence (GitHub #35). Declaring +// nothing keeps such a name out of the dispatch entirely. func TestDeclaresFamily_AnUnknownNameDeclaresNothing(t *testing.T) { t.Parallel() withAllOf := &oas3.Schema{AllOf: []*oas3.JSONSchema[oas3.Referenceable]{ @@ -131,8 +131,8 @@ func TestRef_ASchemaMergingPastTheBoundIsReportedOnce(t *testing.T) { var reports []string for range 2 { for _, name := range []string{"P", "A"} { - st := lowerer.Ctx.Statements().At(lowerer.Ctx.Position(jsontext.Pointer("/components/schemas/" + name))) - _, diags := Ref(lowerer.Ctx, lowerer.Types, 0, st, jsontext.Pointer("/components/schemas/"+name)) + schemaStatement := lowerer.Ctx.Statements().At(lowerer.Ctx.Position(jsontext.Pointer("/components/schemas/" + name))) + _, diags := Ref(lowerer.Ctx, lowerer.Types, 0, schemaStatement, jsontext.Pointer("/components/schemas/"+name)) for _, diagnostic := range diags { if diagnostic.Code == diag.DegradedConstruct && strings.Contains(diagnostic.Message, "deeper than") { reports = append(reports, string(diagnostic.Provenance.Pointer)) diff --git a/compilers/openapi/internal/schema/schema_test.go b/compilers/openapi/internal/schema/schema_test.go index 5f5a4aeb7..1f1ed5fa4 100644 --- a/compilers/openapi/internal/schema/schema_test.go +++ b/compilers/openapi/internal/schema/schema_test.go @@ -305,7 +305,7 @@ const unpreservableValue = ".nan" // schema the IR describes. func TestCoDeclaredFamily_PassedOverKeywordIsKept(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, body, raw string key, at, reportAt, report string lowered ir.TypeKind @@ -327,22 +327,22 @@ func TestCoDeclaredFamily_PassedOverKeywordIsKept(t *testing.T) { raw: `["a","b"]`, lowered: ir.KindLiteral, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec( - " Base: {type: object, properties: {id: {type: string}}}\n S:\n"+tc.body)) + " Base: {type: object, properties: {id: {type: string}}}\n S:\n"+testCase.body)) openapitest.RequireNoErrorDiags(t, diags) - td := typeByName(doc, "S") - require.NotNil(t, td) - assert.Equal(t, tc.lowered, td.Kind(), "the picked family still lowers") - entry, ok := td.Common().Unmodeled[tc.key] - require.True(t, ok, "%s is kept verbatim; got %v", tc.key, td.Common().Unmodeled) + typeDef := typeByName(doc, "S") + require.NotNil(t, typeDef) + assert.Equal(t, testCase.lowered, typeDef.Kind(), "the picked family still lowers") + entry, ok := typeDef.Common().Unmodeled[testCase.key] + require.True(t, ok, "%s is kept verbatim; got %v", testCase.key, typeDef.Common().Unmodeled) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) - assert.JSONEq(t, tc.raw, string(entry.Value)) - assert.Equal(t, jsontext.Pointer(tc.at), entry.Provenance.Pointer, "routable to where it was written") + assert.JSONEq(t, testCase.raw, string(entry.Value)) + assert.Equal(t, jsontext.Pointer(testCase.at), entry.Provenance.Pointer, "routable to where it was written") assert.Contains(t, - openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, tc.reportAt), tc.report) + openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, testCase.reportAt), testCase.report) }) } } @@ -374,42 +374,40 @@ func TestCoDeclaredFamily_EveryPassedOverKeywordIsKept(t *testing.T) { // allOf passed over for an enum with no member to what the node keeps of it: // the allOf whole where an entry is inline, else each entry's $ref under // openapi:$ref, which the report names as the allOf's $refs, not as the allOf. +// A $ref to a schema stating a type, which the empty enum lies within, is kept +// nowhere (TestEmptyEnum_BesideARefIsTheClosedEmptyEnumOfItsTarget), so the +// $refs kept here state no kind. func TestCoDeclaredFamily_TheReportNamesWhatTheNodeKeeps(t *testing.T) { t.Parallel() const obj, obj2 = "{$ref: '#/components/schemas/Obj'}", "{$ref: '#/components/schemas/Obj2'}" - for _, tc := range []struct { + for _, testCase := range []struct { name, body, named string keys []string unresolved bool }{ - {name: "an allOf of one $ref", body: "{enum: [], allOf: [" + obj + "]}", - keys: []string{"openapi:$ref"}, named: "the $ref of its allOf"}, {name: "an allOf of a $ref and an inline entry", body: "{enum: [], allOf: [" + obj + ", {properties: {b: {type: string}}}]}", keys: []string{"openapi:allOf"}, named: "allOf"}, - {name: "an allOf of two $refs", body: "{enum: [], allOf: [" + obj + ", " + obj2 + "]}", - keys: []string{"openapi:$ref/0", "openapi:$ref/1"}, named: "the $refs of its allOf"}, - {name: "an allOf of one $ref written twice", body: "{enum: [], allOf: [" + obj + ", " + obj + "]}", - keys: []string{"openapi:$ref"}, named: "the $refs of its allOf"}, - {name: "a $ref beside an allOf of one", body: "{enum: [], $ref: '#/components/schemas/Obj', allOf: [" + obj2 + "]}", - keys: []string{"openapi:$ref/0", "openapi:$ref/1"}, named: "$ref and the $ref of its allOf"}, - {name: "an allOf of one $ref beside a type", body: "{type: string, enum: [], allOf: [{$ref: '#/components/schemas/Str'}]}", - keys: []string{"openapi:$ref"}, named: "the $ref of its allOf"}, {name: "an allOf of one $ref beside a union", body: "{enum: [], oneOf: [" + obj + "], allOf: [" + obj2 + "]}", keys: []string{"openapi:$ref", "openapi:oneOf"}, named: "the $ref of its allOf"}, {name: "an allOf of one $ref naming nothing", body: "{enum: [], allOf: [{$ref: '#/components/schemas/Missing'}]}", keys: []string{"openapi:$ref"}, named: "the $ref of its allOf", unresolved: true}, + {name: "an allOf of two $refs stating no kind", body: "{enum: [], allOf: [{$ref: '#/components/schemas/Any'}, {$ref: '#/components/schemas/Any2'}]}", + keys: []string{"openapi:$ref/0", "openapi:$ref/1"}, named: "the $refs of its allOf"}, + {name: "a $ref stating no kind beside an allOf of one", body: "{enum: [], $ref: '#/components/schemas/Any', allOf: [{$ref: '#/components/schemas/Any2'}]}", + keys: []string{"openapi:$ref/0", "openapi:$ref/1"}, named: "$ref and the $ref of its allOf"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" Obj: {type: object, properties: {a: {type: string}}}\n"+ - " Obj2: {type: object, properties: {c: {type: string}}}\n Str: {type: string}\n S: "+tc.body+"\n")) - if !tc.unresolved { + " Obj2: {type: object, properties: {c: {type: string}}}\n Str: {type: string}\n"+ + " Any: {}\n Any2: {description: d}\n S: "+testCase.body+"\n")) + if !testCase.unresolved { openapitest.RequireNoErrorDiags(t, diags) } - td := typeByName(doc, "S") - require.NotNil(t, td) - assert.Equal(t, tc.keys, unmodeledKeys(td.Common().Unmodeled)) + typeDef := typeByName(doc, "S") + require.NotNil(t, typeDef) + assert.Equal(t, testCase.keys, unmodeledKeys(typeDef.Common().Unmodeled)) var said []string for _, diagnostic := range diags { if diagnostic.Code == diag.DegradedConstruct && diagnostic.Provenance.Pointer == "/components/schemas/S" && @@ -418,7 +416,7 @@ func TestCoDeclaredFamily_TheReportNamesWhatTheNodeKeeps(t *testing.T) { } } require.Len(t, said, 1, "one report says what the dispatch passed over: %+v", diags) - assert.Contains(t, said[0], "it lowered as the enum, with "+tc.named+" kept verbatim under Unmodeled") + assert.Contains(t, said[0], "it lowered as the enum, with "+testCase.named+" kept verbatim under Unmodeled") }) } } @@ -434,12 +432,12 @@ func TestCoDeclaredFamily_UnpreservableIsNotAnnounced(t *testing.T) { enum: [a, b] `)) - td := typeByName(doc, "S") - require.NotNil(t, td) - assert.Equal(t, []string{"openapi:type"}, unmodeledKeys(td.Common().Unmodeled), "the conversion of x-t failed") + typeDef := typeByName(doc, "S") + require.NotNil(t, typeDef) + assert.Equal(t, []string{"openapi:type"}, unmodeledKeys(typeDef.Common().Unmodeled), "the conversion of x-t failed") assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, "/components/schemas/S/allOf/0"), `extension "x-t" could not be serialized`, "the failure itself is reported") - for _, claim := range openapitest.PreservationClaims(diags) { + for _, claim := range openapitest.MessagesSayingKept(diags) { assert.NotContains(t, claim, "x-t", "nothing claims what was not written under Unmodeled") } } @@ -463,78 +461,78 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { t.Parallel() top := ir.TypeRef{Target: "type/primitive/any"} type nullRow struct { - name string - version string // the OpenAPI version, 3.1.0 where empty - null string // the schemas, with a null written - twin string // the same, as the reading above states it - shape nullShape - kept map[string]string // what A keeps under Unmodeled, by key, as JSON + name string + version string // the OpenAPI version, 3.1.0 where empty + null string // the schemas, with a null written + equivalent string // the same, as the reading above states it + shape nullShape + kept map[string]string // what A keeps under Unmodeled, by key, as JSON } tests := []nullRow{ { - name: "a property", - null: " A:\n type: object\n properties:\n p: null\n", - twin: " A:\n type: object\n properties:\n p: {}\n", - shape: func(t *testing.T, td ir.TypeDef) { - model := asKind[*ir.Model](t, td) + name: "a property", + null: " A:\n type: object\n properties:\n p: null\n", + equivalent: " A:\n type: object\n properties:\n p: {}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + model := asKind[*ir.Model](t, typeDef) require.Len(t, model.Properties, 1) assert.Equal(t, top, model.Properties[0].Type, "the top type, and no node of its own") }, }, { - name: "an allOf entry", - null: " A:\n allOf:\n - null\n - {type: object, properties: {q: {type: string}}}\n", - twin: " A:\n allOf:\n - true\n - {type: object, properties: {q: {type: string}}}\n", - shape: func(t *testing.T, td ir.TypeDef) { - model := asKind[*ir.Model](t, td) + name: "an allOf entry", + null: " A:\n allOf:\n - null\n - {type: object, properties: {q: {type: string}}}\n", + equivalent: " A:\n allOf:\n - true\n - {type: object, properties: {q: {type: string}}}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + model := asKind[*ir.Model](t, typeDef) assert.Empty(t, model.Additional, "the composed model is not closed") require.Len(t, model.Properties, 1) assert.Equal(t, "q", model.Properties[0].WireName, "the other branch still composes") }, }, { - name: "a oneOf branch", - null: " A:\n oneOf:\n - null\n - {type: string}\n", - twin: " A:\n oneOf:\n - {}\n - {type: string}\n", - shape: func(t *testing.T, td ir.TypeDef) { - union := asKind[*ir.Union](t, td) + name: "a oneOf branch", + null: " A:\n oneOf:\n - null\n - {type: string}\n", + equivalent: " A:\n oneOf:\n - {}\n - {type: string}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + union := asKind[*ir.Union](t, typeDef) require.Len(t, union.Variants, 2) assert.Equal(t, top, union.Variants[0].Type) }, }, { - name: "a component", - null: " A: null\n", - twin: " A: {}\n", - shape: func(t *testing.T, td ir.TypeDef) { - scalar := asKind[*ir.Scalar](t, td) + name: "a component", + null: " A: null\n", + equivalent: " A: {}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + scalar := asKind[*ir.Scalar](t, typeDef) assert.Equal(t, &top, scalar.Base, "a scalar alias over the top type") }, }, { - name: "items", - null: " A:\n type: array\n items: null\n", - twin: " A:\n type: array\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Equal(t, top, asKind[*ir.List](t, td).ElementType, "as an absent items") + name: "items", + null: " A:\n type: array\n items: null\n", + equivalent: " A:\n type: array\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Equal(t, top, asKind[*ir.List](t, typeDef).ElementType, "as an absent items") }, }, { - name: "a prefixItems entry", - null: " A:\n type: array\n prefixItems: [{type: string}, null]\n", - twin: " A:\n type: array\n prefixItems: [{type: string}, {}]\n", - shape: func(t *testing.T, td ir.TypeDef) { - tup := asKind[*ir.Tuple](t, td) + name: "a prefixItems entry", + null: " A:\n type: array\n prefixItems: [{type: string}, null]\n", + equivalent: " A:\n type: array\n prefixItems: [{type: string}, {}]\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + tup := asKind[*ir.Tuple](t, typeDef) require.Len(t, tup.ElementTypes, 2) assert.Equal(t, top, tup.ElementTypes[1]) }, }, { - name: "the rest of a tuple, written as items", - null: " A:\n type: array\n prefixItems: [{type: string}]\n items: null\n", - twin: " A:\n type: array\n prefixItems: [{type: string}]\n", - shape: func(t *testing.T, td ir.TypeDef) { - tup := asKind[*ir.Tuple](t, td) + name: "the rest of a tuple, written as items", + null: " A:\n type: array\n prefixItems: [{type: string}]\n items: null\n", + equivalent: " A:\n type: array\n prefixItems: [{type: string}]\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + tup := asKind[*ir.Tuple](t, typeDef) assert.Equal(t, &top, tup.Rest, "an absent items admits anything after; false would admit nothing") }, }, @@ -542,103 +540,103 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { name: "additionalProperties", null: " A:\n type: object\n properties: {a: {type: string}}\n" + " additionalProperties: null\n", - twin: " A:\n type: object\n properties: {a: {type: string}}\n", - shape: func(t *testing.T, td ir.TypeDef) { - model := asKind[*ir.Model](t, td) + equivalent: " A:\n type: object\n properties: {a: {type: string}}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + model := asKind[*ir.Model](t, typeDef) assert.Empty(t, model.Additional, "the model stays open") assert.Nil(t, model.AdditionalProperties, "no catch-all is written") }, }, { - name: "a patternProperties value", - null: " A:\n type: object\n patternProperties:\n '^x': null\n", - twin: " A:\n type: object\n patternProperties:\n '^x': {}\n", - shape: func(t *testing.T, td ir.TypeDef) { - model := asKind[*ir.Model](t, td) + name: "a patternProperties value", + null: " A:\n type: object\n patternProperties:\n '^x': null\n", + equivalent: " A:\n type: object\n patternProperties:\n '^x': {}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + model := asKind[*ir.Model](t, typeDef) require.NotNil(t, model.AdditionalProperties) require.Len(t, model.AdditionalProperties.Patterns, 1) assert.Equal(t, top, model.AdditionalProperties.Patterns[0].Value) }, }, { - name: "contentSchema", - null: " A:\n type: string\n contentMediaType: application/json\n contentSchema: null\n", - twin: " A:\n type: string\n contentMediaType: application/json\n", - shape: func(t *testing.T, td ir.TypeDef) { - scalar := asKind[*ir.Scalar](t, td) + name: "contentSchema", + null: " A:\n type: string\n contentMediaType: application/json\n contentSchema: null\n", + equivalent: " A:\n type: string\n contentMediaType: application/json\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + scalar := asKind[*ir.Scalar](t, typeDef) require.NotNil(t, scalar.Encoding, "the media type is still written") assert.Equal(t, "application/json", scalar.Encoding.MediaType) assert.Nil(t, scalar.Encoding.Schema, "no Encoding.Schema") }, }, { - name: "unevaluatedProperties", - null: " A:\n type: object\n unevaluatedProperties: null\n", - twin: " A:\n type: object\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Empty(t, asKind[*ir.Model](t, td).Additional, "the model stays open") + name: "unevaluatedProperties", + null: " A:\n type: object\n unevaluatedProperties: null\n", + equivalent: " A:\n type: object\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Empty(t, asKind[*ir.Model](t, typeDef).Additional, "the model stays open") }, }, { - name: "unevaluatedItems", - null: " A:\n type: array\n unevaluatedItems: null\n", - twin: " A:\n type: array\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Equal(t, top, asKind[*ir.List](t, td).ElementType) + name: "unevaluatedItems", + null: " A:\n type: array\n unevaluatedItems: null\n", + equivalent: " A:\n type: array\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Equal(t, top, asKind[*ir.List](t, typeDef).ElementType) }, }, { - name: "items beside an unevaluatedItems, which it leaves live", - null: " A:\n type: array\n items: null\n unevaluatedItems: false\n", - twin: " A:\n type: array\n unevaluatedItems: false\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Equal(t, top, asKind[*ir.List](t, td).ElementType) + // The live keyword types the elements (GitHub #1883). + name: "items beside an unevaluatedItems, which it leaves live", + null: " A:\n type: array\n items: null\n unevaluatedItems: {type: string}\n", + equivalent: " A:\n type: array\n unevaluatedItems: {type: string}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), asKind[*ir.List](t, typeDef).ElementType.Target) }, - kept: map[string]string{"openapi:unevaluated": `{"unevaluatedItems":false}`}, }, { - name: "not", - null: " A:\n type: string\n not: null\n", - twin: " A:\n type: string\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Equal(t, &ir.TypeRef{Target: "type/primitive/string"}, asKind[*ir.Scalar](t, td).Base) + name: "not", + null: " A:\n type: string\n not: null\n", + equivalent: " A:\n type: string\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Equal(t, &ir.TypeRef{Target: "type/primitive/string"}, asKind[*ir.Scalar](t, typeDef).Base) }, }, { - name: "propertyNames", - null: " A:\n type: object\n propertyNames: null\n", - twin: " A:\n type: object\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Empty(t, asKind[*ir.Model](t, td).Additional) + name: "propertyNames", + null: " A:\n type: object\n propertyNames: null\n", + equivalent: " A:\n type: object\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Empty(t, asKind[*ir.Model](t, typeDef).Additional) }, }, { - name: "an if beside a then", - null: " A:\n type: string\n if: null\n then: {minLength: 2}\n", - twin: " A:\n type: string\n then: {minLength: 2}\n", - shape: func(*testing.T, ir.TypeDef) {}, - kept: map[string]string{"openapi:if-then-else": `{"then":{"minLength":2}}`}, + name: "an if beside a then", + null: " A:\n type: string\n if: null\n then: {minLength: 2}\n", + equivalent: " A:\n type: string\n then: {minLength: 2}\n", + shape: func(*testing.T, ir.TypeDef) {}, + kept: map[string]string{"openapi:if-then-else": `{"then":{"minLength":2}}`}, }, { - name: "a then beside a real if and else, which alone are kept", - null: " A:\n type: string\n if: {minLength: 2}\n then: null\n else: {maxLength: 9}\n", - twin: " A:\n type: string\n if: {minLength: 2}\n else: {maxLength: 9}\n", - shape: func(*testing.T, ir.TypeDef) {}, - kept: map[string]string{"openapi:if-then-else": `{"if":{"minLength":2},"else":{"maxLength":9}}`}, + name: "a then beside a real if and else, which alone are kept", + null: " A:\n type: string\n if: {minLength: 2}\n then: null\n else: {maxLength: 9}\n", + equivalent: " A:\n type: string\n if: {minLength: 2}\n else: {maxLength: 9}\n", + shape: func(*testing.T, ir.TypeDef) {}, + kept: map[string]string{"openapi:if-then-else": `{"if":{"minLength":2},"else":{"maxLength":9}}`}, }, { - name: "an else beside an if", - null: " A:\n type: string\n if: {minLength: 2}\n else: null\n", - twin: " A:\n type: string\n if: {minLength: 2}\n", - shape: func(*testing.T, ir.TypeDef) {}, - kept: map[string]string{"openapi:if-then-else": `{"if":{"minLength":2}}`}, + name: "an else beside an if", + null: " A:\n type: string\n if: {minLength: 2}\n else: null\n", + equivalent: " A:\n type: string\n if: {minLength: 2}\n", + shape: func(*testing.T, ir.TypeDef) {}, + kept: map[string]string{"openapi:if-then-else": `{"if":{"minLength":2}}`}, }, { - name: "contains beside minContains, which alone is kept", - null: " A:\n type: array\n contains: null\n minContains: 2\n", - twin: " A:\n type: array\n minContains: 2\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Equal(t, top, asKind[*ir.List](t, td).ElementType) + name: "contains beside minContains, which alone is kept", + null: " A:\n type: array\n contains: null\n minContains: 2\n", + equivalent: " A:\n type: array\n minContains: 2\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Equal(t, top, asKind[*ir.List](t, typeDef).ElementType) }, kept: map[string]string{"openapi:contains": `{"minContains":2}`}, }, @@ -646,10 +644,10 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { name: "an allOf entry beside one admitting null", null: " A:\n type: object\n properties:\n p:\n allOf:\n" + " - null\n - {type: [string, 'null']}\n", - twin: " A:\n type: object\n properties:\n p:\n allOf:\n" + + equivalent: " A:\n type: object\n properties:\n p:\n allOf:\n" + " - true\n - {type: [string, 'null']}\n", - shape: func(t *testing.T, td ir.TypeDef) { - model := asKind[*ir.Model](t, td) + shape: func(t *testing.T, typeDef ir.TypeDef) { + model := asKind[*ir.Model](t, typeDef) require.Len(t, model.Properties, 1) assert.True(t, model.Properties[0].Type.Nullable, "a null branch no longer forbids null") }, @@ -658,21 +656,21 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { name: "a conjunct whose $ref lands on a null component, beside one admitting null", null: " N: null\n A:\n type: object\n properties:\n p:\n allOf:\n" + " - {$ref: '#/components/schemas/N'}\n - {type: [string, 'null']}\n", - twin: " N: {}\n A:\n type: object\n properties:\n p:\n allOf:\n" + + equivalent: " N: {}\n A:\n type: object\n properties:\n p:\n allOf:\n" + " - {$ref: '#/components/schemas/N'}\n - {type: [string, 'null']}\n", - shape: func(t *testing.T, td ir.TypeDef) { - model := asKind[*ir.Model](t, td) + shape: func(t *testing.T, typeDef ir.TypeDef) { + model := asKind[*ir.Model](t, typeDef) require.Len(t, model.Properties, 1) assert.True(t, model.Properties[0].Type.Nullable, "what the $ref lands on no longer forbids null") }, }, { - name: "items on an array of 3.0, which still warns that it has none", - version: "3.0.3", - null: " A:\n type: array\n items: null\n", - twin: " A:\n type: array\n", - shape: func(t *testing.T, td ir.TypeDef) { - assert.Equal(t, top, asKind[*ir.List](t, td).ElementType) + name: "items on an array of 3.0, which still warns that it has none", + version: "3.0.3", + null: " A:\n type: array\n items: null\n", + equivalent: " A:\n type: array\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + assert.Equal(t, top, asKind[*ir.List](t, typeDef).ElementType) }, }, } @@ -684,11 +682,11 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { for _, keyword := range keywords { const target = " B: {type: string}\n A:\n type: object\n properties:\n p: " besideRef = append(besideRef, nullRow{ - name: "a " + keyword + " beside a $ref", - null: target + "{$ref: '#/components/schemas/B', " + keyword + ": null}\n", - twin: target + "{$ref: '#/components/schemas/B'}\n", - shape: func(t *testing.T, td ir.TypeDef) { - model := asKind[*ir.Model](t, td) + name: "a " + keyword + " beside a $ref", + null: target + "{$ref: '#/components/schemas/B', " + keyword + ": null}\n", + equivalent: target + "{$ref: '#/components/schemas/B'}\n", + shape: func(t *testing.T, typeDef ir.TypeDef) { + model := asKind[*ir.Model](t, typeDef) require.Len(t, model.Properties, 1) assert.Equal(t, ir.TypeRef{Target: "type/openapi/components/schemas/B"}, model.Properties[0].Type, "the target itself, with no alias over it") @@ -696,34 +694,34 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { }) } tests = slices.Concat(tests, besideRef) - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - version := tc.version + version := testCase.version if version == "" { version = "3.1.0" } - doc, diags := lowerSpecOnly(t, openapitest.ComponentSpecVer(version, tc.null)) - twin, twinDiags := lowerSpecOnly(t, openapitest.ComponentSpecVer(version, tc.twin)) + doc, diags := lowerSpecOnly(t, openapitest.ComponentSpecVer(version, testCase.null)) + equivalent, equivalentDiags := lowerSpecOnly(t, openapitest.ComponentSpecVer(version, testCase.equivalent)) assert.False(t, openapitest.HasDiag(diags, diag.FalseSchema), "a null is no false schema: %+v", diags) a := typeByName(doc, "A") - tc.shape(t, a) + testCase.shape(t, a) kept := a.Common().Unmodeled - assert.Equal(t, slices.Sorted(maps.Keys(tc.kept)), unmodeledKeys(kept), "nothing else is kept") - for key, raw := range tc.kept { + assert.Equal(t, slices.Sorted(maps.Keys(testCase.kept)), unmodeledKeys(kept), "nothing else is kept") + for key, raw := range testCase.kept { assert.JSONEq(t, raw, string(kept[key].Value), key) } - assert.Empty(t, cmp.Diff(twin.Types, doc.Types), "lowers as its twin does") - assert.Empty(t, cmp.Diff(twinDiags, diags, cmpopts.EquateEmpty()), "and reports what its twin does") + assert.Empty(t, cmp.Diff(equivalent.Types, doc.Types), "lowers as its twin does") + assert.Empty(t, cmp.Diff(equivalentDiags, diags, cmpopts.EquateEmpty()), "and reports what its twin does") }) } // Where nothing reads a null keyword, or only a predicate asking whether // the position wrote one, it is as if left out: the position lowers as its // twin does. - type twinRow struct{ name, null, twin string } + type twinRow struct{ name, null, equivalent string } const union = " A:\n oneOf: [{type: string}, {type: integer}]\n" const list = " B: {type: string}\n A:\n type: array\n items: " alone := []twinRow{ @@ -743,14 +741,14 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { list + "{$ref: '#/components/schemas/B', " + keyword + ": null}\n", list + "{$ref: '#/components/schemas/B'}\n"}) } alone = slices.Concat(alone, inItems) - for _, tc := range alone { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range alone { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := lowerSpecOnly(t, openapitest.ComponentSpec(tc.null)) - twin, twinDiags := lowerSpecOnly(t, openapitest.ComponentSpec(tc.twin)) + doc, diags := lowerSpecOnly(t, openapitest.ComponentSpec(testCase.null)) + equivalent, equivalentDiags := lowerSpecOnly(t, openapitest.ComponentSpec(testCase.equivalent)) - assert.Empty(t, cmp.Diff(twin.Types, doc.Types), "lowers as it does with the keyword left out") - assert.Empty(t, cmp.Diff(twinDiags, diags, cmpopts.EquateEmpty()), "and reports what that does") + assert.Empty(t, cmp.Diff(equivalent.Types, doc.Types), "lowers as it does with the keyword left out") + assert.Empty(t, cmp.Diff(equivalentDiags, diags, cmpopts.EquateEmpty()), "and reports what that does") }) } @@ -764,14 +762,14 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { " - {type: object, properties: {p: {type: string}}}\n" + " - {type: object, properties: {p: %s}}\n" doc, diags := lowerSpecOnly(t, openapitest.ComponentSpec(fmt.Sprintf(spec, "null"))) - twin, twinDiags := lowerSpecOnly(t, openapitest.ComponentSpec(fmt.Sprintf(spec, "{}"))) + equivalent, equivalentDiags := lowerSpecOnly(t, openapitest.ComponentSpec(fmt.Sprintf(spec, "{}"))) model := asKind[*ir.Model](t, typeByName(doc, "A")) require.Len(t, model.Properties, 1) assert.Equal(t, ir.TypeRef{Target: "type/primitive/string"}, model.Properties[0].Type) assert.Empty(t, model.Properties[0].Unmodeled, "the top type says nothing the string loses") - assert.Empty(t, cmp.Diff(twin.Types, doc.Types)) - assert.Empty(t, cmp.Diff(twinDiags, diags, cmpopts.EquateEmpty())) + assert.Empty(t, cmp.Diff(equivalent.Types, doc.Types)) + assert.Empty(t, cmp.Diff(equivalentDiags, diags, cmpopts.EquateEmpty())) }) t.Run("a property redeclared as a null keeps the losing declaration as a null", func(t *testing.T) { @@ -785,10 +783,10 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { model := asKind[*ir.Model](t, typeByName(lowerer.Document(t), "A")) require.Len(t, model.Properties, 1) assert.Equal(t, ir.TypeID("type/anonymous/components/schemas/A/allOf/1/properties/p"), model.Properties[0].Type.Target, - "the later declaration stands") - const loser = "openapi:conflicting-redeclaration/components/schemas/A/allOf/0/properties/p" - assert.Equal(t, []string{loser}, unmodeledKeys(model.Properties[0].Unmodeled)) - kept := model.Properties[0].Unmodeled[loser] + "the later declaration remains") + const passedOver = "openapi:conflicting-redeclaration/components/schemas/A/allOf/0/properties/p" + assert.Equal(t, []string{passedOver}, unmodeledKeys(model.Properties[0].Unmodeled)) + kept := model.Properties[0].Unmodeled[passedOver] assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) assert.Equal(t, ir.RawValue("null"), kept.Value, "as written: a null, not the false the parser decodes it as") assert.False(t, openapitest.HasDiag(diags, diag.FalseSchema), "%+v", diags) @@ -796,13 +794,13 @@ func TestNullSchema_AnEntryIsTheEmptySchemaAndAKeywordIsLeftOut(t *testing.T) { } // nullShape asserts what a position lowers to, read off the component A. -type nullShape func(t *testing.T, td ir.TypeDef) +type nullShape func(t *testing.T, typeDef ir.TypeDef) -// asKind returns td as a T, failing the test where it is another kind. -func asKind[T ir.TypeDef](t *testing.T, td ir.TypeDef) T { +// asKind returns typeDef as a T, failing the test where it is another kind. +func asKind[T ir.TypeDef](t *testing.T, typeDef ir.TypeDef) T { t.Helper() - got, ok := td.(T) - require.True(t, ok, "lowered to %T", td) + got, ok := typeDef.(T) + require.True(t, ok, "lowered to %T", typeDef) return got } @@ -852,18 +850,18 @@ func TestLowerComponentSchemas_PercentEncodedRefResolves(t *testing.T) { {"underscore", "Foo_Bar", "Foo%5FBar"}, {"dot", "Foo.Bar", "Foo%2EBar"}, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec( - " "+tc.decl+": {type: string}\n"+ - " User: {type: object, properties: {x: {$ref: '#/components/schemas/"+tc.encoded+"'}}}\n")) + " "+testCase.decl+": {type: string}\n"+ + " User: {type: object, properties: {x: {$ref: '#/components/schemas/"+testCase.encoded+"'}}}\n")) openapitest.RequireNoErrorDiags(t, diags) user, ok := typeByName(doc, "User").(*ir.Model) require.True(t, ok, "User must own a Model node") require.Len(t, user.Properties, 1) - assert.Equal(t, componentID(tc.decl), user.Properties[0].Type.Target, + assert.Equal(t, componentID(testCase.decl), user.Properties[0].Type.Target, "the encoded fragment names the declared component") }) } @@ -923,33 +921,26 @@ func TestLowerComponentSchemas_PercentEncodedDiscriminatorMapping(t *testing.T) "the encoded mapping target names the declared component, and the entry is kept") } -// TestUntypedKinds_ACutReadLeavesTheKeywordsToThePolicy pins a schema writing -// no type whose statement lies on a cycle of conjunct edges, a union branch -// naming it, so the run's admission cannot read what it names: its shape -// keywords decide, under the kind-inference policy and marked by it, and with -// the policy off it is the top type keeping them. -func TestUntypedKinds_ACutReadLeavesTheKeywordsToThePolicy(t *testing.T) { +// TestUntypedKinds_ACycleBesideADeclaredObjectIsThatObject pins a schema +// writing no type whose statement lies on a cycle of conjunct edges, a union +// branch naming it, beside an anyOf declaring an object: the loop admits every +// kind and cuts nothing, so under either kind-inference setting the oneOf +// distributes across the object the anyOf declares, which no policy marks. +func TestUntypedKinds_ACycleBesideADeclaredObjectIsThatObject(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpecVer("3.1.0", " A: {oneOf: [{$ref: '#/components/schemas/A'}], anyOf: [{type: object}], properties: {a: {type: string}}}\n") for _, off := range []bool{false, true} { doc, diags := schema.LowerSpecWith(t, spec, lowering.Policy{KindInference: lowering.KindInference{Disabled: off}}) openapitest.RequireNoErrorDiags(t, diags) - td := typeByName(doc, "A") - marked := td.Common().Provenance.Inferred == lowering.KindInferenceHeuristic - if off { - assert.Equal(t, ir.KindScalar, td.Kind(), "the top type with the policy off") - assert.Contains(t, td.Common().Unmodeled, "openapi:properties") - assert.False(t, marked) - continue - } - union, ok := td.(*ir.Union) - require.True(t, ok, "the policy reads its properties as an object the oneOf distributes across") + typeDef := typeByName(doc, "A") + union, ok := typeDef.(*ir.Union) + require.True(t, ok, "off %v: the oneOf distributes across the declared object, got %T", off, typeDef) require.Len(t, union.Variants, 1) variant := doc.Types[union.Variants[0].Type.Target] - assert.Equal(t, ir.KindModel, variant.Kind()) - assert.Equal(t, lowering.KindInferenceHeuristic, variant.Common().Provenance.Inferred) - assert.Contains(t, variant.Common().Unmodeled, "openapi:anyOf", "the anyOf kept on the variant") - assert.False(t, marked) + assert.Equal(t, ir.KindModel, variant.Kind(), "off %v", off) + assert.Empty(t, variant.Common().Provenance.Inferred, "off %v: the object is declared, not inferred", off) + assert.Contains(t, union.Unmodeled, "openapi:anyOf", "off %v: the anyOf kept once, on the Union", off) + assert.NotEqual(t, lowering.KindInferenceHeuristic, typeDef.Common().Provenance.Inferred, "off %v", off) } } diff --git a/compilers/openapi/internal/schema/siteroot.go b/compilers/openapi/internal/schema/siteroot.go new file mode 100644 index 000000000..6bc8f63ec --- /dev/null +++ b/compilers/openapi/internal/schema/siteroot.go @@ -0,0 +1,209 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// referentRoot returns the boundRoot that reading the schemas alone +// (boundRootOf) leaves out of what starts reference, through their union +// branches too, so a bound beside a reference or a union binds a kind only +// where each referent's value is of it. +func referentRoot(loweringContext lowering.Ctx, starts ...*statement.Statement) boundRoot { + var out boundRoot + reads := budget.New(budget.AtMost(maxAdmissionReads)) + for _, target := range referencedFrom(loweringContext, starts, &reads) { + out |= reachedRoot(loweringContext, target.schemaStatement, target.at) + } + return out +} + +// reachedKey keys reachedRoot's reading of the schema a $ref lands on. +type reachedKey struct { + target *statement.Statement +} + +// reachedRoot returns the boundRoot of target, landed on at at, and of every +// schema its $refs reach, each read where it is written (siteRoot). It is read +// once a run, so the references to one target share it, and reads at most +// maxAdmissionReads schemas. +func reachedRoot(loweringContext lowering.Ctx, target *statement.Statement, at reftable.DocumentPointer) boundRoot { + return lowering.ReadOncePerRun(loweringContext, reachedKey{target}, func() boundRoot { + referentReadCount(loweringContext).reached++ + var out boundRoot + reads := budget.New(budget.AtMost(maxAdmissionReads)) + seen := map[*statement.Statement]bool{target: true} + work := []referenced{{schemaStatement: target, at: at}} + for len(work) > 0 { + next := work[len(work)-1] + work = work[:len(work)-1] + out |= siteRoot(loweringContext, next.schemaStatement.Schema, next.at) + for _, onward := range referencedFrom(loweringContext, []*statement.Statement{next.schemaStatement}, &reads) { + if !seen[onward.schemaStatement] { + seen[onward.schemaStatement] = true + work = append(work, onward) + } + } + } + return out + }) +} + +// referenced is a schema a $ref lands on, and where. +type referenced struct { + schemaStatement *statement.Statement + at reftable.DocumentPointer +} + +// referencedFrom returns what the $refs of starts and of their union branches +// land on, without walking a $ref, reading at most what reads allows. +func referencedFrom(loweringContext lowering.Ctx, starts []*statement.Statement, reads *budget.Budget) []referenced { + var out []referenced + seen := map[*statement.Statement]bool{} + work := slices.Clone(starts) + for len(work) > 0 && reads.Spend(1) { + schemaStatement := work[len(work)-1] + work = work[:len(work)-1] + if seen[schemaStatement] || schemaStatement.Truth != statement.Stated { + continue + } + seen[schemaStatement] = true + if next, at := declaredOf(loweringContext, schemaStatement); next != nil && next.Truth == statement.Stated { + out = append(out, referenced{schemaStatement: next, at: at}) + } + choice := schemaStatement.ChoiceKeywords() + for _, branch := range slices.Concat(choice.OneOf, choice.AnyOf) { + work = append(work, loweringContext.Statements().Subschema(branch)) + } + } + return out +} + +// siteKey keys siteRoot's reading of the schema written at at. +type siteKey struct { + schema *statement.Schema + at reftable.DocumentPointer +} + +// referentReads is how many schemas siteRoot and reachedRoot each read in a +// run, which only the tests read. +type referentReads struct { + sites, reached int +} + +// referentReadsKey keys the run's referentReads. +type referentReadsKey struct{} + +// referentReadCount returns the run's referentReads. +func referentReadCount(loweringContext lowering.Ctx) *referentReads { + return lowering.ReadOncePerRun(loweringContext, referentReadsKey{}, func() *referentReads { return &referentReads{} }) +} + +// siteRoot returns the boundRoot of the node schema, written at at, lowers to +// that a reading of its schemas alone leaves out, read once a run: an Enum's or +// a Literal's ValueType as every conjunct narrows it, and a conjoined union's +// variants. The referents of its $refs are the caller's to walk. +func siteRoot(loweringContext lowering.Ctx, schema *statement.Schema, at reftable.DocumentPointer) boundRoot { + return lowering.ReadOncePerRun(loweringContext, siteKey{schema, at}, func() boundRoot { + referentReadCount(loweringContext).sites++ + inDocument, ok := lowering.InDocument(loweringContext, at.Doc) + if !ok { + return rootIsValue + } + refinementValue, _ := refinementOf(inDocument, schema, at.Pointer) + variants, _, _ := conjoinedVariantsRoot(inDocument, schema) + return valueSetRootAt(inDocument, refinementValue, schema, at.Pointer) | variants + }) +} + +// unionNodeRoot returns the boundRoot of the Union the position lowers to, each +// live variant's, so a bound beside it binds a kind only where every variant of +// that kind is its value. It returns false where the position lowers to another +// node than the union its conjunction chooses (unionLoweredAlone). +func unionNodeRoot(loweringContext lowering.Ctx, position *statement.Schema) (boundRoot, bool) { + if !declaresUnion(position) && !writesConjuncts(position) && position.Ref == nil { + return rootIsValue, false + } + loweredUnion, ok := readConjunction(loweringContext, position).loweredUnion() + if !ok || !unionLoweredAlone(loweringContext, position, loweredUnion.holder) { + return rootIsValue, false + } + if root, conjoined := conjoinedUnionRoot(loweringContext, position); conjoined { + return root, true + } + dead := readLoweredUnion(loweringContext, position).dead + var out boundRoot + for i, branch := range loweredUnion.branches() { + if i < len(dead) && dead[i] { + continue + } + branch := loweringContext.Statements().Subschema(branch) + out |= admissionOf(loweringContext, branch).admitted.root | referentRoot(loweringContext, branch) + } + return out, true +} + +// conjoinedUnionRoot is unionNodeRoot for a union whose live branches are each +// conjoined with the body's one kind (unionConjoined), a $ref branch's +// boundRoot read along its chain; false for any other union. +func conjoinedUnionRoot(loweringContext lowering.Ctx, position *statement.Schema) (boundRoot, bool) { + variants, refs, conjoined := conjoinedVariantsRoot(loweringContext, position) + if !conjoined { + return rootIsValue, false + } + return variants | referentRoot(loweringContext, refs...), true +} + +// conjoinedVariantsRoot returns, for a union conjoined with the body's one kind +// (unionConjoined), the boundRoot of its live variants read without following +// a $ref, and the live branches writing one; false for any other union. +func conjoinedVariantsRoot(loweringContext lowering.Ctx, position *statement.Schema) (boundRoot, []*statement.Statement, bool) { + if !declaresUnion(position) && !writesConjuncts(position) && position.Ref == nil { + return rootIsValue, nil, false + } + reading := readLoweredUnion(loweringContext, position) + loweredUnion, ok := readConjunction(loweringContext, position).loweredUnion() + if !ok || reading.besideRest != unionConjoined { + return rootIsValue, nil, false + } + var ref *statement.Statement + if _, refBodied := oneRefRestOf(loweringContext, position); refBodied { + ref, _ = oneRefEntry(loweringContext, position) + } + var out boundRoot + var refs []*statement.Statement + for i, branch := range loweredUnion.branches() { + if reading.dead[i] { + continue + } + branch := loweringContext.Statements().Subschema(branch) + out |= conjoinedVariantRoot(loweringContext, branch, reading.kind, ref) + if branch.Ref != nil { + refs = append(refs, branch) + } + } + return out, refs, true +} + +// conjoinedVariantRoot returns the boundRoot of the variant conjoinedVariant +// builds over branch, a live branch conjoined with kind, as its schemas read; +// ref, a $ref body, conjoins with branch as refConjoinedVariant reads the two. +func conjoinedVariantRoot(loweringContext lowering.Ctx, branch *statement.Statement, kind statement.JSONSchemaTypeName, ref *statement.Statement) boundRoot { + switch { + case ref != nil: + return admissionOf(loweringContext, ref).admitted.and(admissionOf(loweringContext, branch).admitted).settledRoot(branch.Schema) + case !stated(branch.Schema) || branch.Ref != nil: + return admissionOf(loweringContext, branch).admitted.root + } + if kinds, _ := lowersTo(loweringContext, branch); kinds&^kindNull&^kindsOfTypeName(kind) == 0 { + return admissionOf(loweringContext, branch).admitted.root + } + return formRoot(branch.Schema, writtenFormat(branch.Schema), kindsOfTypeName(kind)) +} diff --git a/compilers/openapi/internal/schema/siteroot_cost_test.go b/compilers/openapi/internal/schema/siteroot_cost_test.go new file mode 100644 index 000000000..853a0fe94 --- /dev/null +++ b/compilers/openapi/internal/schema/siteroot_cost_test.go @@ -0,0 +1,51 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" +) + +// referencesTo writes target, a schema named T, and a model whose uses +// properties are each a $ref to T with a default, as a document naming one +// value set or union from many places does. +func referencesTo(target string, uses int, rest ...string) string { + var builder strings.Builder + builder.WriteString(" T: " + target + "\n Holder:\n type: object\n properties:\n") + for i := range uses { + fmt.Fprintf(&builder, " p%d: {$ref: '#/components/schemas/T', default: 1}\n", i) + } + for _, component := range rest { + builder.WriteString(" " + component + "\n") + } + return openapitest.ComponentSpec(builder.String()) +} + +// TestSiteRoot_ReadsEachReferentOnceARun pins that what a referenced schema's +// node is, read where it is written, is read once a run however many $refs +// name it, and so is all a reference to it reaches: an enum named from 8 or 64 +// properties is read once, and a union of two models with each model once +// more, so a value set's members are not read again at each reference. +func TestSiteRoot_ReadsEachReferentOnceARun(t *testing.T) { + t.Parallel() + models := []string{"M0: {type: integer, format: int32}", "M1: {type: integer, format: int64}"} + union := "{oneOf: [{$ref: '#/components/schemas/M0'}, {$ref: '#/components/schemas/M1'}]}" + for _, uses := range []int{8, 64} { + _, diags, sites, reached := schema.LowerSpecCountingReferentReads(t, referencesTo("{type: integer, enum: [1, 2, 3]}", uses)) + openapitest.RequireNoErrorDiags(t, diags) + assert.Equal(t, 1, sites, "%d references read the enum once", uses) + assert.Equal(t, 1, reached, "%d references read what the enum reaches once", uses) + _, diags, sites, reached = schema.LowerSpecCountingReferentReads(t, referencesTo(union, uses, models...)) + openapitest.RequireNoErrorDiags(t, diags) + assert.Equal(t, 3, sites, "%d references read the union and each model once", uses) + assert.Equal(t, 3, reached, "%d references read what each of them reaches once", uses) + } +} diff --git a/compilers/openapi/internal/schema/stand.go b/compilers/openapi/internal/schema/stand.go deleted file mode 100644 index 42568ba45..000000000 --- a/compilers/openapi/internal/schema/stand.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "encoding/json/jsontext" - - "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" - "github.com/dexpace/morphic/ir" -) - -// stand is where the node a schema lowers to stands where that is not where the -// schema is written: at, the pointer of of, the position whose allOf the schema -// is the inline principal of, as the node the position owns stands for the -// whole conjunction (docs/compilers/openapi.md#allof-refinement). The zero -// stand is the schema's own. It is a parameter, never read off the schema or -// the context, since a $ref to the entry lowers the same schema at its own -// pointer. -type stand struct { - of *statement.Schema - at jsontext.Pointer - // held says the node is a type list's variant whose principal the position - // keeps whole under its entry's key (heldWhole), so it keeps none of its - // bounds verbatim. - held bool -} - -// position returns the schema a union schema writes is elected at -// (docs/compilers/openapi.md#competing-keywords): the position schema is the -// principal of, whose branches declare shape against all it conjoins, else -// schema. -func (st stand) position(schema *statement.Schema) *statement.Schema { - if st.of == nil { - return schema - } - return st.of -} - -// pointer returns where the node of a schema written at written stands. -func (st stand) pointer(written jsontext.Pointer) jsontext.Pointer { - if st.of == nil { - return written - } - return st.at -} - -// foldedEntries returns what the node of schema, written at written, reads -// beside schema: the foldedEntries of its position (positionFoldedEntries), -// where it stands at another, that position's own keywords and each folded -// branch of its allOf but schema, whose keywords the node reads as its own. -func (st stand) foldedEntries(loweringContext lowering.Ctx, schema *statement.Schema, written jsontext.Pointer) []annotation.FoldedAllOfEntry { - if st.of == nil { - return positionFoldedEntries(loweringContext, schema, written, ir.TypeRef{}) - } - foldedEntries := positionFoldedEntries(loweringContext, st.of, st.at, ir.TypeRef{}) - out := make([]annotation.FoldedAllOfEntry, 0, len(foldedEntries)+1) - beside := foldedEntryAt(loweringContext, st.of, st.at) - beside.Beside = true - out = append(out, beside) - for _, foldedAllOfEntry := range foldedEntries { - if foldedAllOfEntry.Node != schema || foldedAllOfEntry.At != written { - out = append(out, foldedAllOfEntry) - } - } - return out -} - -// takes returns the kinds whose value bounds the node of schema takes -// (boundKinds): those its position admits. -func (st stand) takes(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { - if st.of == nil { - return boundKinds(loweringContext, schema) - } - return boundKinds(loweringContext, st.of) -} - -// standsAtPosition reports whether r's principal is inline and built the node -// the position written at pointer owns, having lowered to target: its unread -// keywords were kept on that node (keepsAtOutcome), and what that node holds is -// the principal's (ownHomes). -func standsAtPosition(loweringContext lowering.Ctx, refinementValue refinement, target ir.TypeRef, pointer jsontext.Pointer) bool { - return refinementValue.principal != nil && refinementValue.principal.schema.Ref == nil && LoweredToOwnNode(loweringContext, pointer, target) -} diff --git a/compilers/openapi/internal/schema/standkept.go b/compilers/openapi/internal/schema/standkept.go deleted file mode 100644 index 5276757b4..000000000 --- a/compilers/openapi/internal/schema/standkept.go +++ /dev/null @@ -1,403 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "bytes" - "cmp" - "encoding/json/jsontext" - "encoding/json/v2" - "maps" - "slices" - "strings" - - yaml "go.yaml.in/yaml/v3" - - "github.com/dexpace/morphic/compilers/compile" - "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/promotion" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" - "github.com/dexpace/morphic/ir" -) - -// principalKept is what the readers of an inline principal and the position -// its node stands at tell each other while that node is finished, since two -// schemas keep keywords in its one Unmodeled: the readers say what they will -// keep, the position writes its own and answers, and the readers then keep -// against what it wrote (keepAround, -// docs/compilers/openapi.md#allof-inline-residue). -type principalKept struct { - // shape is how the reader that built the node names it in a report - // (positionShape), which the position's reports say too. - shape string - // keys are the keywords the readers keep verbatim once the position has - // written, in the order said, and reason the one they share (sharedOf). - keys []string - reason ir.UnmodeledReason - // whole is the position's answer: it keeps the principal whole, under its - // entry's key, which holds keys. - whole bool - // apart are the keywords kept under the principal's entry's key so far, - // written otherwise beside the allOf, and apartReason the one they share. - apart []string - apartReason ir.UnmodeledReason - // built is the reason what the principal's build kept on the node shares - // (keepBuiltAround), "" for nothing: an entry kept whole holds that too. - built ir.UnmodeledReason -} - -// keeping is what one reader keeps verbatim of a schema on the node it lowered -// to: keys, for reason, each under its own key by keep, which reports them as -// the same keywords written flat are reported, naming the node shape where the -// reader names one. -type keeping struct { - keys []string - reason ir.UnmodeledReason - shape string - keep func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic -} - -// saying returns h, allocated where nil, having heard that a reader will keep -// keepingValue's keys. -func (h *principalKept) saying(keepingValue keeping) *principalKept { - if h == nil { - h = &principalKept{} - } - h.shape = cmp.Or(keepingValue.shape, h.shape) - if len(keepingValue.keys) == 0 { - return h - } - h.reason = keepingValue.reason - if len(h.keys) > 0 { - h.reason = sharedOf(h.reason, keepingValue.reason) - } - h.keys = append(h.keys, keepingValue.keys...) - return h -} - -// named returns how the principal's readers name the node standing for their -// position, "" where none said. -func (h *principalKept) named() string { - if h == nil { - return "" - } - return h.shape -} - -// sharedOf is the reason an entry holding what a and b are kept for is kept -// under: the one they share, else degraded_lowering, as sharedReason reads it. -func sharedOf(a, b ir.UnmodeledReason) ir.UnmodeledReason { - if a == b { - return a - } - return ir.ReasonDegradedLowering -} - -// keepAround finishes td for one reader of schema, written at pointer, keeping -// keepingValue on it. On the schema's own node it keeps, then runs fin, the -// frames outside. On the node standing for st's position it says what it will -// keep, lets fin, the position's finisher among it, write first, and keeps -// after (keepStanding): neither schema can know what the other keeps before it -// has. -func keepAround(loweringContext lowering.Ctx, ts *compile.Types, st stand, td ir.TypeDef, read keySet, held *principalKept, - schema *statement.Schema, pointer jsontext.Pointer, keepingValue keeping, fin finisher, -) []ir.Diagnostic { - unmodeled := &td.Common().Unmodeled - if st.of == nil { - diags := keepingValue.keep(unmodeled, keepingValue.keys) - fin.run(td, read, held) - return diags - } - held = held.saying(keepingValue) - fin.run(td, read, held) - return keepStanding(loweringContext, ts, allOfEntries(loweringContext, st.of, st.at), held, unmodeled, schema, pointer, keepingValue) -} - -// keepStanding keeps keepingValue, what one reader keeps of schema, the inline -// principal of comp written at pointer, on unmodeled, the Unmodeled of the node -// standing for comp's position, which that position has written: nothing where -// it keeps schema whole, the entry holding them, else each keyword as -// heldAgainst places it, one whose own key is free as keepingValue keeps it, -// and one that key holds otherwise under schema's entry's key (keepApart). This -// is the one way a keyword of schema reaches the node once the position has -// written. A discriminator resolves its routes wherever it is kept -// (routesKept). -func keepStanding(loweringContext lowering.Ctx, ts *compile.Types, comp allOfComposition, held *principalKept, unmodeled *ir.Unmodeled, - schema *statement.Schema, pointer jsontext.Pointer, keepingValue keeping, -) []ir.Diagnostic { - if held.whole { - return routesKept(loweringContext, ts, schema, keepingValue.keys, pointer) - } - plain, apart := heldAgainst(*unmodeled, comp, schema, pointer, keepingValue.keys) - diags := keepingValue.keep(unmodeled, plain) - if slices.Contains(plain, "discriminator") { - // The discriminator kept whole holds what the position read out of it. - promotion.DropContained(loweringContext.Promoter(), unmodeled, annotation.EntryKey("", "discriminator")) - } - return append(diags, keepApart(loweringContext, ts, comp, held, unmodeled, schema, pointer, apart, keepingValue.reason)...) -} - -// heldAgainst splits keys, keywords schema, an entry of comp written at pointer -// that its position lowers from, keeps, by what unmodeled, the Unmodeled the -// position has written, holds: plain where each one's own key is free, apart -// where it holds another value, and neither where it, or the key of an entry -// around schema (aroundOf), holds the same, kept once there. Two values are the -// same where they render to the same JSON, a number's spelling and an array's -// order with them (writtenKeys.note); one that cannot render is plain, its -// keeper's to refuse as written flat. -func heldAgainst(unmodeled ir.Unmodeled, comp allOfComposition, schema *statement.Schema, pointer jsontext.Pointer, keys []string, -) (plain, apart []string) { - around := aroundOf(unmodeled, comp, pointer) - for _, key := range keys { - entry, taken := unmodeled[annotation.EntryKey("", key)] - if !taken && len(around) == 0 { - // The path nearly every keyword takes: nothing to render. - plain = append(plain, key) - continue - } - raw, err := annotation.RawFromNode(keyNode(schema, key)) - switch { - case err != nil: - plain = append(plain, key) - case taken && bytes.Equal(raw, entry.Value), holdsAlike(around, key, raw): - case !taken: - plain = append(plain, key) - default: - apart = append(apart, key) - } - } - return plain, apart -} - -// aroundOf returns the members of what unmodeled holds under the key of each -// entry around the one written at pointer: a wrapper of comp out of whose allOf -// it is flattened, settled before it (outcomeKeeps.lowered). A keyword one of -// them holds alike is that wrapper's writing, the outermost standing. -func aroundOf(unmodeled ir.Unmodeled, comp allOfComposition, pointer jsontext.Pointer) []map[string]ir.RawValue { - var out []map[string]ir.RawValue - for _, b := range comp.entries { - if !b.wrapper || !strings.HasPrefix(string(pointer), string(b.pointer)+"/") { - continue - } - if entry, kept := unmodeled[comp.entryKey(b.pointer)]; kept { - out = append(out, keptMembers(entry.Value)) - } - } - return out -} - -// holdsAlike reports whether one of around holds key with the value raw. -func holdsAlike(around []map[string]ir.RawValue, key string, raw ir.RawValue) bool { - return slices.ContainsFunc(around, func(m map[string]ir.RawValue) bool { - v, held := m[key] - return held && bytes.Equal(v, raw) - }) -} - -// keptMembers returns the members of raw, a JSON object, by name, each as -// written; nil where raw is no object. -func keptMembers(raw ir.RawValue) map[string]ir.RawValue { - var out map[string]ir.RawValue - if json.Unmarshal(raw, &out) != nil { - return nil - } - return out -} - -// besideHeld returns unmodeled with the value the position schema writes under -// each of keys whose own key unmodeled does not hold yet: one a field reads, or -// the inline principal writing it alike keeps after, holds that key all the -// same, so a wrapper around the principal writing it otherwise is kept under -// its own entry's key, the plain key the position's. Where none is, unmodeled -// itself. -func besideHeld(unmodeled ir.Unmodeled, schema *statement.Schema, keys []string) ir.Unmodeled { - view, copied := unmodeled, false - for _, key := range keys { - k := annotation.EntryKey("", key) - if _, taken := unmodeled[k]; taken || !hasKey(schema, key) { - continue - } - raw, err := annotation.RawFromNode(keyNode(schema, key)) - if err != nil { - continue - } - if !copied { - view, copied = make(ir.Unmodeled, len(unmodeled)+len(keys)), true - maps.Copy(view, unmodeled) - } - view[k] = ir.UnmodeledEntry{Value: raw} - } - return view -} - -// keepApart keeps on unmodeled, the Unmodeled of the node standing for the -// position comp is written at, the keywords apart that schema, comp's inline -// principal written at pointer, writes otherwise than the position keeps them: -// under its entry's key, openapi:allOf/, one object holding those and what -// held says readers before kept there, the rest of schema lowered, for the -// reason they share, at the entry, with one report naming apart. A -// discriminator among them resolves its routes, as one kept anywhere does -// (resolveDiscriminatorRoutes). -func keepApart(loweringContext lowering.Ctx, ts *compile.Types, comp allOfComposition, held *principalKept, unmodeled *ir.Unmodeled, - schema *statement.Schema, pointer jsontext.Pointer, apart []string, reason ir.UnmodeledReason, -) []ir.Diagnostic { - if len(apart) == 0 { - return nil - } - kept, diags := holdApart(loweringContext, comp, held, unmodeled, schema, pointer, apart, reason) - if !kept { - return diags - } - // A carrier keeps the key beneath its own scope, so the report names the - // entry's path, which every such key ends in. - diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, - "the keywords beside %s write %s otherwise than this inline entry, and one Unmodeled entry under a keyword holds "+ - "one value; the entry's are kept verbatim under Unmodeled under the key naming it, %s, the rest of it lowered", - comp.subject(), strings.Join(apart, ", "), comp.entryPath(pointer))) - return append(diags, routesKept(loweringContext, ts, schema, apart, pointer)...) -} - -// holdApart writes on unmodeled the object the entry's key of schema, comp's -// inline principal written at pointer, holds: the keywords apart and those held -// says were kept there before, as schema writes them, for the reason they -// share. It reports whether it wrote, and held then counts apart among them. -func holdApart(loweringContext lowering.Ctx, comp allOfComposition, held *principalKept, unmodeled *ir.Unmodeled, schema *statement.Schema, - pointer jsontext.Pointer, apart []string, reason ir.UnmodeledReason, -) (bool, []ir.Diagnostic) { - all, shared := slices.Concat(held.apart, apart), reason - if len(held.apart) > 0 { - shared = sharedOf(held.apartReason, reason) - } - members := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"} - for _, key := range schema.Keys { - if slices.Contains(all, key.Name) { - members.Content = append(members.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key.Name}, key.Node) - } - } - kept, diags := preserveNode(loweringContext, unmodeled, comp.entryKey(pointer), members, shared, pointer) - if kept { - held.apart, held.apartReason = all, shared - } - return kept, diags -} - -// keepBuiltAround finishes td by fin, the frames outside every reader of the -// inline principal schema written at pointer, the position's among them, -// holding back what the principal's build kept on td itself: a keyword kept -// beside the field it could not fill, which no reader keeps after the position. -// Those entries leave the node while the position writes, and are kept after it -// against what it wrote (keepBuilt), so whatever a build keeps reaches the node -// through the one writer too. -func keepBuiltAround(loweringContext lowering.Ctx, st stand, td ir.TypeDef, read keySet, held *principalKept, schema *statement.Schema, - pointer jsontext.Pointer, fin finisher, -) []ir.Diagnostic { - unmodeled := &td.Common().Unmodeled - built := takeBuilt(unmodeled, pointer) - held = held.saying(keeping{}) - for _, entry := range built { - held.built = sharedOf(cmp.Or(held.built, entry.Reason), entry.Reason) - } - fin.run(td, read, held) - return keepBuilt(loweringContext, allOfEntries(loweringContext, st.of, st.at), held, unmodeled, schema, pointer, built) -} - -// takeBuilt removes from unmodeled, and returns, the entries written at pointer -// or beneath it: what the schema written there kept on the node it built. -func takeBuilt(unmodeled *ir.Unmodeled, pointer jsontext.Pointer) ir.Unmodeled { - var built ir.Unmodeled - for key, entry := range *unmodeled { - at := entry.Provenance.Pointer - if at != pointer && !strings.HasPrefix(string(at), string(pointer)+"/") { - continue - } - if built == nil { - built = ir.Unmodeled{} - } - built[key] = entry - delete(*unmodeled, key) - } - return built -} - -// keepBuilt keeps on unmodeled, which the position has written, the entries -// built, what the build of schema, comp's inline principal written at pointer, -// kept: each under its own key where that is free; once where the key holds the -// same value, or the position keeps schema whole, the entry holding it, or an -// entry around schema holds it alike (aroundOf); and under schema's entry's key -// where the position's keyword holds another (holdApart). The build reported -// each where kept, as written flat, which stays true. A key no keyword of -// schema names cannot be held otherwise. -func keepBuilt(loweringContext lowering.Ctx, comp allOfComposition, held *principalKept, unmodeled *ir.Unmodeled, schema *statement.Schema, - pointer jsontext.Pointer, built ir.Unmodeled, -) []ir.Diagnostic { - var diags []ir.Diagnostic - around := aroundOf(*unmodeled, comp, pointer) - for _, key := range slices.Sorted(maps.Keys(built)) { - entry := built[key] - cur, taken := (*unmodeled)[key] - keyword := strings.TrimPrefix(key, annotation.EntryKey("", "")) - switch { - case taken && (held.whole || bytes.Equal(cur.Value, entry.Value)), holdsAlike(around, keyword, entry.Value): - case !taken: - annotation.PreserveInto(unmodeled, key, entry.Value, entry.Reason, entry.Provenance) - case !hasKey(schema, keyword): - diags = append(diags, loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, - "internal: %s, kept by the build of this allOf entry, is held with another value", key)) - default: - _, heldDiags := holdApart(loweringContext, comp, held, unmodeled, schema, pointer, []string{keyword}, entry.Reason) - diags = append(diags, heldDiags...) - } - } - if _, kept := built[annotation.EntryKey("", "discriminator")]; kept || held.whole && len(built) > 0 { - // What the position read out of a discriminator kept whole, and what a - // whole entry holds, is kept once (dropFoldedIntoWhole). - promotion.DropContained(loweringContext.Promoter(), unmodeled, annotation.EntryKey("", "discriminator")) - dropFoldedIntoWhole(loweringContext, unmodeled) - } - return diags -} - -// keyWrittenAlike reports whether a and b write key with one value, as heldAgainst -// compares two; one that cannot render is alike to nothing. -func keyWrittenAlike(a, b *statement.Schema, key string) bool { - if !hasKey(a, key) || !hasKey(b, key) { - return false - } - x, errA := annotation.RawFromNode(keyNode(a, key)) - y, errB := annotation.RawFromNode(keyNode(b, key)) - return errA == nil && errB == nil && bytes.Equal(x, y) -} - -// routesKept resolves the mapping of the discriminator s, written at pointer, -// writes where kept, keywords kept another way than keepUnreadKeys keeps them, -// holds it: a discriminator kept verbatim resolves its routes wherever it is -// kept, as keepUnreadKeys resolves the one it keeps (resolveDiscriminatorRoutes). -func routesKept(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, kept []string, pointer jsontext.Pointer) []ir.Diagnostic { - if !slices.Contains(kept, "discriminator") { - return nil - } - return resolveDiscriminatorRoutes(loweringContext, ts, schema, pointer) -} - -// outcome returns what st's position keeps, having lowered to the node it owns. -func (st stand) outcome(loweringContext lowering.Ctx) outcomeKeeps { - return keepsAtOutcome(loweringContext, st.of, ir.TypeRef{Target: loweringContext.IDs().ForPointer(st.at)}, st.at) -} - -// heldWhole reports whether st's position keeps the inline principal written at -// pointer whole, under its entry's key. A type list asks before it builds its -// variants, which no finisher reaches; every other reader of the principal is -// told (principalKept.whole). -func (st stand) heldWhole(loweringContext lowering.Ctx, pointer jsontext.Pointer) bool { - return st.of != nil && st.outcome(loweringContext).holdsWhole(pointer) -} - -// holdsWhole reports whether k keeps the entry written at pointer whole. -func (k outcomeKeeps) holdsWhole(pointer jsontext.Pointer) bool { - return slices.ContainsFunc(k.entries, func(keptEntryValue keptEntry) bool { - return keptEntryValue.entry.pointer == pointer && keptEntryValue.keptWhole() - }) -} diff --git a/compilers/openapi/internal/schema/standkept_internal_test.go b/compilers/openapi/internal/schema/standkept_internal_test.go deleted file mode 100644 index 6a6c2c3da..000000000 --- a/compilers/openapi/internal/schema/standkept_internal_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" - "github.com/dexpace/morphic/ir" -) - -// TestKeepApart_AnObjectThatCannotRenderIsReportedAndClaimsNothing drives the -// state its callers cannot produce, each handing it keywords it has rendered -// one by one (heldAgainst): an object no JSON holds. It is reported lost, -// nothing is announced as kept, and what readers before kept there stands. -func TestKeepApart_AnObjectThatCannotRenderIsReportedAndClaimsNothing(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" S: {allOf: [{type: string, minimum: .nan}], minimum: 2}\n")) - decl, ok := lowerer.Doc.Components.Schemas.Get("S") - require.True(t, ok) - schema := lowerer.Ctx.Statements().Of(decl).Schema - comp := allOfEntries(lowerer.Ctx, schema, "/components/schemas/S") - require.Len(t, comp.entries, 1) - entry := comp.entries[0] - held := &principalKept{apart: []string{"type"}, apartReason: ir.ReasonNoIRHome} - var unmodeled ir.Unmodeled - - diags := keepApart(lowerer.Ctx, lowerer.Types, comp, held, &unmodeled, entry.schema.Schema, entry.pointer, []string{"minimum"}, ir.ReasonDegradedLowering) - - require.Len(t, diags, 1) - assert.Equal(t, diag.UnpreservableConstruct, diags[0].Code) - assert.Empty(t, unmodeled, "nothing is kept") - assert.Equal(t, []string{"type"}, held.apart, "nor counted as kept under the entry's key") -} - -// TestKeepBuilt_AKeyNoKeywordNamesHeldOtherwiseIsAnInvariantBroken drives the -// state no build produces: an entry a principal's build kept under a key none -// of its keywords names, which the position holds with another value. There is -// no member of the entry's object to keep it as, so it is reported, never -// overwritten. -func TestKeepBuilt_AKeyNoKeywordNamesHeldOtherwiseIsAnInvariantBroken(t *testing.T) { - t.Parallel() - lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" S: {allOf: [{type: string}]}\n")) - decl, ok := lowerer.Doc.Components.Schemas.Get("S") - require.True(t, ok) - comp := allOfEntries(lowerer.Ctx, lowerer.Ctx.Statements().Of(decl).Schema, "/components/schemas/S") - entry := comp.entries[0] - unmodeled := ir.Unmodeled{"openapi:oneOf/0": {Value: ir.RawValue(`1`), Reason: ir.ReasonNoIRHome}} - built := ir.Unmodeled{"openapi:oneOf/0": {Value: ir.RawValue(`2`), Reason: ir.ReasonNoIRHome}} - - diags := keepBuilt(lowerer.Ctx, comp, &principalKept{}, &unmodeled, entry.schema.Schema, entry.pointer, built) - - assertInternalInvariant(t, diags) - assert.Equal(t, `1`, string(unmodeled["openapi:oneOf/0"].Value), "what the position wrote stands") -} - -// TestKeptMembers_OnlyAnObjectHasMembers pins the reading of what an entry -// around a principal's level holds under its key: an object's members, each -// as written, a number's spelling with it, and none of anything else. -func TestKeptMembers_OnlyAnObjectHasMembers(t *testing.T) { - t.Parallel() - assert.Equal(t, map[string]ir.RawValue{"minimum": ir.RawValue("1.0"), "foo": ir.RawValue(`[1,2]`)}, - keptMembers(ir.RawValue(`{"foo":[1,2],"minimum":1.0}`))) - assert.Nil(t, keptMembers(ir.RawValue("false"))) -} diff --git a/compilers/openapi/internal/schema/subtypetag.go b/compilers/openapi/internal/schema/subtypetag.go index e21dd2377..66d0de568 100644 --- a/compilers/openapi/internal/schema/subtypetag.go +++ b/compilers/openapi/internal/schema/subtypetag.go @@ -23,39 +23,39 @@ import ( // every node is interned in answers in any declaration order, so it is a // settlement. A union written beside or on its allOf is one of those it // composes (lowerSubtypeUnion). -func deferSubtypeTag(loweringContext lowering.Ctx, ts *compile.Types, tag subtypeTag, id ir.TypeID, pointer jsontext.Pointer) { +func deferSubtypeTag(loweringContext lowering.Ctx, types *compile.Types, tag subtypeTag, id ir.TypeID, pointer jsontext.Pointer) { if tag.byName == nil || !loweringContext.DiscriminatorInference.Honours() { return } - ts.Defer(subtypeTagReading{c: loweringContext, id: id, pointer: pointer, property: tag.byName.PropertyName, name: tag.value}) + types.Defer(subtypeTagReading{loweringContext: loweringContext, id: id, pointer: pointer, property: tag.byName.PropertyName, name: tag.value}) } // subtypeTagReading settles the tag of the subtype id under the // discriminator-inference policy. What it reads no settlement after it -// changes (tagReadings), so the settling order changes no answer. One is +// changes (tagSetMemo), so the settling order changes no answer. One is // deferred per subtype, and the types they share are read once a run. type subtypeTagReading struct { - c lowering.Ctx - id ir.TypeID - pointer jsontext.Pointer // where the subtype is written - property string // the tag property's wire name - name string // the component name the discriminator routes it by + loweringContext lowering.Ctx + id ir.TypeID + pointer jsontext.Pointer // where the subtype is written + property string // the tag property's wire name + name string // the component name the discriminator routes it by } // Settle reads the strings the subtype admits for its tag and, where they rule // its name out, tags it by the one it admits, or by none where it admits // several or none, as no one tag then routes to it. Either is marked and // reported. -func (t subtypeTagReading) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { +func (t subtypeTagReading) Settle(_ context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { model, ok := reg[t.id].(*ir.Model) if !ok || model == nil || model.DiscriminatorValue != t.name { - return []ir.Diagnostic{t.c.DiagAt(ir.SeverityError, diag.InternalInvariant, t.pointer, + return []ir.Diagnostic{t.loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, t.pointer, "internal: subtype %q is not registered as the model its lowering tagged %q, "+ "so the discriminator inference deferred for it is not taken", t.id, t.name)} } flat := ir.FlattenedProperties(reg, t.id) flatProperty, declared := flatMember(flat, t.property) - got := readingsOf(t.c).object(reg, flat, flatProperty, declared, t.property) + got := tagSetMemoOf(t.loweringContext).object(aliasedTypes{registry: reg, aliases: aliases}, flat, flatProperty, declared, t.property) if got.admits(t.name) { return nil } @@ -68,7 +68,7 @@ func (t subtypeTagReading) Settle(_ context.Context, reg ir.TypeRegistry) []ir.D } else { model.DiscriminatorValue = "" } - return []ir.Diagnostic{t.c.DiagAt(ir.SeverityInfo, diag.InferredDiscriminator, t.pointer, + return []ir.Diagnostic{t.loweringContext.DiagAt(ir.SeverityInfo, diag.InferredDiscriminator, t.pointer, "the discriminator routes this schema by its name, %q, a tag its %q rejects, admitting %s; %s, marked inferred", t.name, t.property, admittedList(tags), outcome)} } diff --git a/compilers/openapi/internal/schema/subtypetag_internal_test.go b/compilers/openapi/internal/schema/subtypetag_internal_test.go index 2f382c67d..cb83fca88 100644 --- a/compilers/openapi/internal/schema/subtypetag_internal_test.go +++ b/compilers/openapi/internal/schema/subtypetag_internal_test.go @@ -41,9 +41,9 @@ func TestSubtypeTagReading_ReportsWhatItCannotSettle(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - reading := subtypeTagReading{c: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, + reading := subtypeTagReading{loweringContext: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, id: "type/s", pointer: "/components/schemas/S", property: "kind", name: "S"} - diags := reading.Settle(t.Context(), reg) + diags := reading.Settle(t.Context(), reg, ir.NewAliasChainIndex(reg.Lookup)) require.Len(t, diags, 1) assert.Equal(t, diag.InternalInvariant, diags[0].Code) assert.Equal(t, ir.SeverityError, diags[0].Severity) @@ -87,9 +87,9 @@ func routesAllocs(t *testing.T, width int) float64 { } lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", spec.String())) schemaNamed := func(name string) *statement.Schema { - js, ok := lowerer.Doc.Components.Schemas.Get(name) + jsonSchema, ok := lowerer.Doc.Components.Schemas.Get(name) require.True(t, ok, name) - return lowerer.Ctx.Statements().Of(js).Schema + return lowerer.Ctx.Statements().Of(jsonSchema).Schema } pet, last := schemaNamed("Pet"), schemaNamed(fmt.Sprintf("S%d", width-1)) require.True(t, routesByName(lowerer.Ctx, pet, last), "a listed subtype is routed by name") diff --git a/compilers/openapi/internal/schema/subtypetag_test.go b/compilers/openapi/internal/schema/subtypetag_test.go index e395a5c0c..a42733803 100644 --- a/compilers/openapi/internal/schema/subtypetag_test.go +++ b/compilers/openapi/internal/schema/subtypetag_test.go @@ -112,8 +112,9 @@ func TestDiscriminatorInference_ReadsAUnionItsSubtypesCompose(t *testing.T) { // TestDiscriminatorValue_AUnionListsTheSchemaItsBranchEndsOn pins what a // union written in another document lists: the schemas its $ref branches end -// on there, as discriminatedAncestors reads a $ref, so a subtype it lists is -// routed by its name and one it does not is not +// on there, as ancestorLevels reads a $ref. A name routes only a +// component of the entry document (GitHub #1829), so neither the subtype it +// lists nor one it does not is tagged by its name // (docs/compilers/openapi.md#discriminator-value), in either declaration order. func TestDiscriminatorValue_AUnionListsTheSchemaItsBranchEndsOn(t *testing.T) { t.Parallel() @@ -134,7 +135,7 @@ components: bird: {$ref: './pets.yaml#/components/schemas/Bird'} `) openapitest.RequireNoErrorDiags(t, diags) - for name, tag := range map[string]string{"Cat": "Cat", "Bird": ""} { + for name, tag := range map[string]string{"Cat": "", "Bird": ""} { model, ok := doc.Types[ir.TypeID("type/openapi@pets.yaml/components/schemas/"+name)].(*ir.Model) require.True(t, ok, "%s lowers to a model", name) assert.Equal(t, tag, model.DiscriminatorValue, name) @@ -176,7 +177,7 @@ func petSubtype(name, properties string) string { // for the tag, every declaration of the member met, and each union it composes, // may rule the name out. One is then its tag, several or none leave it // untagged, either marked inferred and reported at it. A name admitted, a -// member or a union bounding no strings, or a mapping key stands. The member +// member or a union bounding no strings, or a mapping key remains. The member // read is the routing ancestor's, not a nearer one's. Two subtypes admitting // one string carry it both. func TestDiscriminatorInference_ReadsTheTagASubtypeAdmits(t *testing.T) { diff --git a/compilers/openapi/internal/schema/tagreadings.go b/compilers/openapi/internal/schema/tagreadings.go index 6c723e3b1..b80640c5b 100644 --- a/compilers/openapi/internal/schema/tagreadings.go +++ b/compilers/openapi/internal/schema/tagreadings.go @@ -18,83 +18,81 @@ type readKey struct { object bool } -// tagReadings remembers what the policy reads of a settled registry +// tagSetMemo remembers what the policy reads of a settled registry // (lowering.Settled), so a type many settlements ask about is read once a run. // It reads a type's values, an alias's base, a union's variants and closure, // and a model's members and composition. Of the settlements, only a fold // changes any of that, a member's type, and a fold is a completion: it runs // before every reading, and reports one stored before it as a compiler bug -// (modelFields.Settle). A model swapped for its map (besideUnionDiscriminator) -// holds no member and composes nothing, admitting any value either way. -type tagReadings struct { +// (modelFields.Settle). A model swapped for its map +// (modelRouteSettlement.Settle) holds no member and composes nothing, +// admitting any value either way. +type tagSetMemo struct { read map[readKey]tagSet } -// readingsOf returns the run's tagReadings, which every copy of loweringContext -// shares. -func readingsOf(loweringContext lowering.Ctx) *tagReadings { - return lowering.Settled(loweringContext, func() *tagReadings { return &tagReadings{read: map[readKey]tagSet{}} }) +// tagSetMemoOf returns the run's tagSetMemo, which every copy of +// loweringContext shares. +func tagSetMemoOf(loweringContext lowering.Ctx) *tagSetMemo { + return lowering.Settled(loweringContext, func() *tagSetMemo { + return &tagSetMemo{read: map[readKey]tagSet{}} + }) +} + +// aliasedTypes is the registry a reading reads, and the index of its alias +// chains the settlements are handed (compile.Settlement), through which it +// reads each chain once a run. +type aliasedTypes struct { + registry ir.TypeRegistry + aliases *ir.AliasChainIndex } // stored reports whether r holds a reading, which no settlement rewriting // what one reads may follow (modelFields.Settle). -func (r *tagReadings) stored() bool { return len(r.read) > 0 } +func (r *tagSetMemo) stored() bool { return len(r.read) > 0 } // object returns what an instance of the object flat flattens holds at the -// property name: what its member admits (member, or any value where ok is -// false, as it declares none), met with what each union it composes admits -// there (conjunctKeys). -func (r *tagReadings) object(reg ir.TypeRegistry, flat ir.Flattening, member ir.FlatProperty, ok bool, name string) tagSet { +// property name: what its member admits (member, where declared says flat +// declares it, else any value), intersected with what each union it composes +// admits there (conjunctKeys). +func (r *tagSetMemo) object(types aliasedTypes, flat ir.Flattening, member ir.FlatProperty, declared bool, name string) tagSet { got := anything() - if ok { - got = r.member(reg, member) + if declared { + got = r.member(types, member) } - for _, readKey := range conjunctKeys(reg, flat, name) { - got = meet(got, r.fold(reg, readKey)) + for _, readKey := range conjunctKeys(types, flat, name) { + got = intersectTagSets(got, r.fold(types, readKey)) } return got } // member returns what every declaration of flatProperty admits, as an instance -// meets them all: the one it takes and those it overrides. -func (r *tagReadings) member(reg ir.TypeRegistry, flatProperty ir.FlatProperty) tagSet { - for _, readKey := range memberKeys(reg, flatProperty) { - r.fold(reg, readKey) +// satisfies them all: the one it takes and those it overrides. +func (r *tagSetMemo) member(types aliasedTypes, flatProperty ir.FlatProperty) tagSet { + for _, readKey := range memberKeys(types, flatProperty) { + r.fold(types, readKey) } - return r.memberOf(reg, flatProperty) + return r.memberOf(types, flatProperty) } -// fold reads root and each reading it reaches not read yet, once a run, on -// stacks of its own rather than by recursion: Tarjan's strongly connected -// components, each read once the components it reaches are (readComponent), -// so a cycle reads alike from wherever it is entered. Each reading is entered +// fold reads root and each reading it reaches not read yet, once a run, by +// walkComponents rather than by recursion: Tarjan's strongly connected +// components, each read once the components it reaches are (readComponent), so +// a cycle reads alike from wherever it is entered. Each reading is entered // once, which bounds the walk. -func (r *tagReadings) fold(reg ir.TypeRegistry, root readKey) tagSet { +func (r *tagSetMemo) fold(types aliasedTypes, root readKey) tagSet { if got, read := r.read[root]; read { return got } - componentWalkValue := componentWalk{index: map[readKey]int{}, low: map[readKey]int{}, opened: map[readKey]readFrame{}} - componentWalkValue.enter(reg, root) - for len(componentWalkValue.path) > 0 { - readFrame := &componentWalkValue.path[len(componentWalkValue.path)-1] - if readFrame.next < len(readFrame.kids) { - kid := readFrame.kids[readFrame.next] - readFrame.next++ - if _, read := r.read[kid]; read { - continue - } - if _, seen := componentWalkValue.index[kid]; !seen { - componentWalkValue.enter(reg, kid) - continue - } - componentWalkValue.low[readFrame.key] = min(componentWalkValue.low[readFrame.key], componentWalkValue.index[kid]) // on the stack, as no component holding it is read - continue - } - done := componentWalkValue.leave() - if componentWalkValue.low[done.key] == componentWalkValue.index[done.key] { - r.readComponent(reg, &componentWalkValue, done.key) - } - } + flats := map[readKey]ir.Flattening{} + walkComponents(root, + func(key readKey) []readKey { + kids, flat := children(types, key) + flats[key] = flat + return kids + }, + func(key readKey) bool { _, read := r.read[key]; return read }, + func(component closedComponent[readKey]) { r.readComponent(types, flats, component.members) }) return r.read[root] } @@ -104,47 +102,41 @@ func (r *tagReadings) fold(reg ir.TypeRegistry, root readKey) tagSet { // read in a few. const maxComponentSweeps = 64 -// readComponent reads the component whose first reading entered is root, off -// the walk's stack. Value readings name only value readings, so a component -// holds one kind. A union on a cycle of unions bounds nothing, as a value -// another member admits is taken as any. Object readings meet and join, which -// keep their order, so each sweep reads every member off the sweep before, -// from any value down: each is sound, the last is the answer, and none turns -// on the order of the members. -func (r *tagReadings) readComponent(reg ir.TypeRegistry, componentWalkValue *componentWalk, root readKey) { - i := len(componentWalkValue.stack) - 1 - for componentWalkValue.stack[i] != root { - i-- - } - component := componentWalkValue.stack[i:] - if root.object { - r.sweep(reg, componentWalkValue, component) +// readComponent reads the component whose first reading entered is its first +// member, flats holding each member's flattening. Value readings name only +// value readings, so a component holds one kind. A union on a cycle of unions +// bounds nothing, as a value another member admits is taken as any. Object +// readings intersect and union, which keep their order, so each sweep reads +// every member off the sweep before, from any value down: each is sound, the +// last is the answer, and none turns on the order of the members. +func (r *tagSetMemo) readComponent(types aliasedTypes, flats map[readKey]ir.Flattening, component []readKey) { + if component[0].object { + r.sweep(types, flats, component) } else { cycle := make(map[readKey]bool, len(component)) for _, readKey := range component { cycle[readKey] = true } for _, readKey := range component { - r.read[readKey] = r.combine(reg, componentWalkValue.opened[readKey], cycle) + r.read[readKey] = r.combine(types, readKey, flats[readKey], cycle) } } for _, readKey := range component { - delete(componentWalkValue.opened, readKey) + delete(flats, readKey) } - componentWalkValue.stack = componentWalkValue.stack[:i] } // sweep reads each member of the component of object readings off what the // sweep before read, the first off any value, until a sweep changes none or // maxComponentSweeps are made. -func (r *tagReadings) sweep(reg ir.TypeRegistry, componentWalkValue *componentWalk, component []readKey) { +func (r *tagSetMemo) sweep(types aliasedTypes, flats map[readKey]ir.Flattening, component []readKey) { for _, readKey := range component { r.read[readKey] = anything() } next := make([]tagSet, len(component)) for range maxComponentSweeps { for i, readKey := range component { - next[i] = r.combine(reg, componentWalkValue.opened[readKey], nil) + next[i] = r.combine(types, readKey, flats[readKey], nil) } changed := false for i, readKey := range component { @@ -163,150 +155,109 @@ func sameSet(a, b tagSet) bool { return a.closed == b.closed && a.null == b.null && slices.Equal(a.strings, b.strings) } -// combine returns what the reading readFrameValue opened admits, once each -// reading it names is read, or is in its component and read as far as -// readComponent has. A value reading naming a union in cycle, its component, -// bounds nothing. -func (r *tagReadings) combine(reg ir.TypeRegistry, readFrameValue readFrame, cycle map[readKey]bool) tagSet { - if !readFrameValue.key.object { - union := unionNode(reg, readFrameValue.key.id) +// combine returns what the reading key admits, flat being its flattening +// where it is an object reading of a model, once each reading it names is read, +// or is in its component and read as far as readComponent has. A value reading +// naming a union in cycle, its component, bounds nothing. +func (r *tagSetMemo) combine(types aliasedTypes, key readKey, flat ir.Flattening, cycle map[readKey]bool) tagSet { + if !key.object { + union := unionNode(types.registry, key.id) sets := make([]tagSet, len(union.Variants)) for i, variant := range union.Variants { - if id, _ := throughAliases(reg, variant.Type.Target); cycle[readKey{id: id}] { + if id := throughAliases(types.aliases, variant.Type.Target); cycle[readKey{id: id}] { return anything() // a union on a cycle of unions bounds nothing } - sets[i] = r.refOf(reg, variant.Type) + sets[i] = r.refOf(types, variant.Type) } - return closedJoin(union, sets) + return closedUnionTagSets(union, sets) } - if union := unionNode(reg, readFrameValue.key.id); union != nil { + if union := unionNode(types.registry, key.id); union != nil { sets := make([]tagSet, len(union.Variants)) for i, variant := range union.Variants { sets[i] = anything() - if readKey, ok := instanceKey(reg, variant.Type.Target, readFrameValue.key.name); ok { + if readKey, ok := instanceKey(types, variant.Type.Target, key.name); ok { sets[i] = r.read[readKey] } } - return closedJoin(union, sets) + return closedUnionTagSets(union, sets) } got := anything() // a model's, as no object reading keys another node - if flatProperty, ok := flatMember(readFrameValue.flat, readFrameValue.key.name); ok { - got = r.memberOf(reg, flatProperty) + if flatProperty, ok := flatMember(flat, key.name); ok { + got = r.memberOf(types, flatProperty) } - for _, readKey := range conjunctKeys(reg, readFrameValue.flat, readFrameValue.key.name) { - got = meet(got, r.read[readKey]) + for _, readKey := range conjunctKeys(types, flat, key.name) { + got = intersectTagSets(got, r.read[readKey]) } return got } -// closedJoin is join over the variants of union, or any value for a union not -// closed. -func closedJoin(union *ir.Union, sets []tagSet) tagSet { +// closedUnionTagSets is unionTagSets over the variants of union, or any value +// for a union not closed. +func closedUnionTagSets(union *ir.Union, sets []tagSet) tagSet { if !union.Closed { return anything() } - return join(sets) + return unionTagSets(sets) } // refOf returns what a value typeRef names admits, read through alias scalars, -// with the null typeRef or an alias it is read through admits: what the value -// reading of a union holds, which fold must have read, and leaf's for any other -// node, read once a run, as many declarations name one Enum. -func (r *tagReadings) refOf(reg ir.TypeRegistry, typeRef ir.TypeRef) tagSet { - id, null := throughAliases(reg, typeRef.Target) +// with the null typeRef admits: what the value reading of a union holds, which +// fold must have read, and leaf's for any other node, read once a run, as many +// declarations name one Enum. +func (r *tagSetMemo) refOf(types aliasedTypes, typeRef ir.TypeRef) tagSet { + id := throughAliases(types.aliases, typeRef.Target) readKeyValue := readKey{id: id} got, read := r.read[readKeyValue] if !read { // no union, which fold reads first - got = leaf(reg[id]) + got = leaf(types.registry[id]) r.read[readKeyValue] = got } - got.null = got.null || null || typeRef.Nullable + got.null = got.null || typeRef.Nullable return got } // memberOf returns what every declaration of flatProperty admits, each as refOf // reads it. -func (r *tagReadings) memberOf(reg ir.TypeRegistry, flatProperty ir.FlatProperty) tagSet { - got := r.refOf(reg, flatProperty.Property.Type) +func (r *tagSetMemo) memberOf(types aliasedTypes, flatProperty ir.FlatProperty) tagSet { + got := r.refOf(types, flatProperty.Property.Type) for _, propertyDecl := range flatProperty.Overridden { - got = meet(got, r.refOf(reg, propertyDecl.Property.Type)) + got = intersectTagSets(got, r.refOf(types, propertyDecl.Property.Type)) } return got } -// componentWalk is fold's state: Tarjan's index and low link of each reading -// entered, its stack, the path of readings being entered, and what each -// reading entered and not yet read named. -type componentWalk struct { - index, low map[readKey]int - stack []readKey - path []readFrame - opened map[readKey]readFrame -} - -// readFrame is a reading entered: the readings it names, how many of them the -// walk has visited, and, for an object reading of a model, its flattening. -type readFrame struct { - key readKey - kids []readKey - next int - flat ir.Flattening -} - -// enter numbers readKeyValue, stacks it, and puts what it names on the path. -func (w *componentWalk) enter(reg ir.TypeRegistry, readKeyValue readKey) { - w.index[readKeyValue], w.low[readKeyValue] = len(w.index), len(w.index) - w.stack = append(w.stack, readKeyValue) - w.path = append(w.path, readFrame{key: readKeyValue, kids: nil}) - readFrameValue := &w.path[len(w.path)-1] - readFrameValue.kids, readFrameValue.flat = children(reg, readKeyValue) -} - -// leave takes the reading every kid of which is visited off the path, keeps -// what it named for its component, and passes its low link to its parent. -func (w *componentWalk) leave() readFrame { - done := w.path[len(w.path)-1] - w.path = w.path[:len(w.path)-1] - w.opened[done.key] = done - if len(w.path) > 0 { - parent := w.path[len(w.path)-1].key - w.low[parent] = min(w.low[parent], w.low[done.key]) - } - return done -} - // children returns the readings readKeyValue names, and a model's flattening // for an object reading of one: a union's variants that are unions, for a value // reading; and for an object reading, a model's member's declarations that are // unions and the closed unions it composes, or a union's variants that are // models or unions. -func children(reg ir.TypeRegistry, readKeyValue readKey) ([]readKey, ir.Flattening) { +func children(types aliasedTypes, readKeyValue readKey) ([]readKey, ir.Flattening) { var kids []readKey - if union := unionNode(reg, readKeyValue.id); union != nil { + if union := unionNode(types.registry, readKeyValue.id); union != nil { for _, variant := range union.Variants { if !readKeyValue.object { - if id, _ := throughAliases(reg, variant.Type.Target); unionNode(reg, id) != nil { + if id := throughAliases(types.aliases, variant.Type.Target); unionNode(types.registry, id) != nil { kids = append(kids, readKey{id: id}) } - } else if kid, ok := instanceKey(reg, variant.Type.Target, readKeyValue.name); ok { + } else if kid, ok := instanceKey(types, variant.Type.Target, readKeyValue.name); ok { kids = append(kids, kid) } } return kids, ir.Flattening{} } - flat := ir.FlattenedProperties(reg, readKeyValue.id) // a model's, as no other reading keys another node + flat := ir.FlattenedProperties(types.registry, readKeyValue.id) // a model's, as no other reading keys another node if flatProperty, ok := flatMember(flat, readKeyValue.name); ok { - kids = memberKeys(reg, flatProperty) + kids = memberKeys(types, flatProperty) } - return append(kids, conjunctKeys(reg, flat, readKeyValue.name)...), flat + return append(kids, conjunctKeys(types, flat, readKeyValue.name)...), flat } // memberKeys returns the value readings of the unions flatProperty's // declarations name. -func memberKeys(reg ir.TypeRegistry, flatProperty ir.FlatProperty) []readKey { +func memberKeys(types aliasedTypes, flatProperty ir.FlatProperty) []readKey { var keys []readKey for _, typeRef := range append([]ir.TypeRef{flatProperty.Property.Type}, declTypes(flatProperty.Overridden)...) { - if id, _ := throughAliases(reg, typeRef.Target); unionNode(reg, id) != nil { + if id := throughAliases(types.aliases, typeRef.Target); unionNode(types.registry, id) != nil { keys = append(keys, readKey{id: id}) } } @@ -324,12 +275,12 @@ func declTypes(decls []ir.PropertyDecl) []ir.TypeRef { // conjunctKeys returns the object readings at the property name of the unions // flat's composition names, read through alias scalars. One not closed admits -// any value (closedJoin), which bounds nothing it is met with. -func conjunctKeys(reg ir.TypeRegistry, flat ir.Flattening, name string) []readKey { +// any value (closedUnionTagSets), which bounds nothing it is intersected with. +func conjunctKeys(types aliasedTypes, flat ir.Flattening, name string) []readKey { var keys []readKey for _, id := range flat.Unflattened { - target, _ := throughAliases(reg, id) - if unionNode(reg, target) != nil { + target := throughAliases(types.aliases, id) + if unionNode(types.registry, target) != nil { keys = append(keys, readKey{id: target, name: name, object: true}) } } @@ -337,10 +288,10 @@ func conjunctKeys(reg ir.TypeRegistry, flat ir.Flattening, name string) []readKe } // instanceKey returns the object reading at the property name of the type id -// stands for, read through alias scalars, where it is a model or a union, +// names, read through alias scalars, where it is a model or a union, // which an instance of an object can be. -func instanceKey(reg ir.TypeRegistry, id ir.TypeID, name string) (readKey, bool) { - target, _ := throughAliases(reg, id) - td := reg[target] - return readKey{id: target, name: name, object: true}, isKind(td, ir.KindModel) || isKind(td, ir.KindUnion) +func instanceKey(types aliasedTypes, id ir.TypeID, name string) (readKey, bool) { + target := throughAliases(types.aliases, id) + typeDef := types.registry[target] + return readKey{id: target, name: name, object: true}, isKind(typeDef, ir.KindModel) || isKind(typeDef, ir.KindUnion) } diff --git a/compilers/openapi/internal/schema/tags.go b/compilers/openapi/internal/schema/tags.go index 6904a0995..3c6c548ae 100644 --- a/compilers/openapi/internal/schema/tags.go +++ b/compilers/openapi/internal/schema/tags.go @@ -22,60 +22,67 @@ import ( const maxReportedTags = 3 // deferUnionTags queues the discriminator-inference policy's reading of the -// union union, unionAtValue lowered at pointer, where the policy is on: for the -// discriminator standing with it declaring no mapping, or for none at all +// union union, unionSite lowered at pointer, where the policy is on: for the +// discriminator beside it, of the variants its mapping leaves out, all +// of them where it declares none, or for none at all // (docs/compilers/openapi.md#discriminator-inference). It reads what each // variant's type says of its tag, which only a registry every node is interned -// in answers in any declaration order, so it is a settlement. A mapping the -// document declares is read as written, beside the routes it implies -// (spellImplicitRoutes), so one of those its variant rejects stands (#1798). A -// discriminator union cannot hold (tagLocated) leaves union untagged, so -// nothing is read. -func deferUnionTags(loweringContext lowering.Ctx, ts *compile.Types, unionAtValue unionAt, union *ir.Union, pointer jsontext.Pointer) { +// in answers in any declaration order, so it is a settlement. A discriminator +// union cannot hold (tagLocated) leaves union untagged, so nothing is read. +func deferUnionTags(loweringContext lowering.Ctx, types *compile.Types, unionSite loweredUnionSite, union *ir.Union, pointer jsontext.Pointer) { if !loweringContext.DiscriminatorInference.Honours() { return } - if unionAtValue.disc != nil && (len(unionAtValue.disc.Mapping) > 0 || union.Discriminator == nil) { + if unionSite.discriminator != nil && union.Discriminator == nil { return } - tags := unionTags{c: loweringContext, id: union.ID, pointer: pointer} - if unionAtValue.disc != nil { - tags.at = unionAtValue.discAt + ids.Ptr("discriminator") - tags.implicit = implicitRoutes(loweringContext, unionAtValue) + tags := unionTags{loweringContext: loweringContext, id: union.ID, pointer: pointer} + if unionSite.discriminator != nil { + tags.at = unionSite.discriminatorPointer + ids.Ptr("discriminator") + tags.implicit = implicitRoutes(loweringContext, unionSite) + for _, entry := range unionSite.discriminator.Mapping { + tags.entries = append(tags.entries, entry.Value) + } } - ts.Defer(tags) + types.Defer(tags) } // unionTags settles the tag of the union id under the discriminator-inference // policy, from the strings each variant admits for its tag property: a mapping // for the discriminator written at at, which declares none, or, where at is // empty, a discriminator for a union declaring none. What it reads no -// settlement after it changes (tagReadings), so the settling order changes no +// settlement after it changes (tagSetMemo), so the settling order changes no // answer. type unionTags struct { - c lowering.Ctx - id ir.TypeID - pointer jsontext.Pointer // where the union is written - at jsontext.Pointer // the discriminator's, "" for none - implicit []implicitRoute // per variant; nil for no discriminator + loweringContext lowering.Ctx + id ir.TypeID + pointer jsontext.Pointer // where the union is written + at jsontext.Pointer // the discriminator's, "" for none + implicit []implicitRoute // per variant; nil for no discriminator + entries []string // the keys the declared mapping writes } // Settle reads the union's tags, and writes them where the policy reads one. -func (t unionTags) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { +func (t unionTags) Settle(_ context.Context, reg ir.TypeRegistry, aliases *ir.AliasChainIndex) []ir.Diagnostic { union, ok := reg[t.id].(*ir.Union) if !ok || union == nil { return t.invariant("is not registered as one") } - if t.at != "" { - return t.mapDeclared(reg, union) + types := aliasedTypes{registry: reg, aliases: aliases} + switch { + case t.at != "" && len(t.entries) > 0: + return t.mapLeftOut(types, union) + case t.at != "": + return t.mapDeclared(types, union) + default: + return t.inferUndeclared(types, union) } - return t.inferUndeclared(reg, union) } // invariant reports a union the settlement finds otherwise than its lowering // left it, a compiler bug: the reading is not taken. func (t unionTags) invariant(why string) []ir.Diagnostic { - return []ir.Diagnostic{t.c.DiagAt(ir.SeverityError, diag.InternalInvariant, t.pointer, + return []ir.Diagnostic{t.loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, t.pointer, "internal: union %q %s, so the discriminator inference deferred for it is not taken", t.id, why)} } @@ -85,7 +92,7 @@ func (t unionTags) invariant(why string) []ir.Diagnostic { // one rejecting the component name it routes by, one admitting another // string, or one naming no component. Where each admits that name alone, the // implicit mapping already says it. -func (t unionTags) mapDeclared(reg ir.TypeRegistry, union *ir.Union) []ir.Diagnostic { +func (t unionTags) mapDeclared(types aliasedTypes, union *ir.Union) []ir.Diagnostic { discriminator := union.Discriminator if discriminator == nil { return t.invariant("holds no discriminator, though its source declares one") @@ -93,20 +100,151 @@ func (t unionTags) mapDeclared(reg ir.TypeRegistry, union *ir.Union) []ir.Diagno if len(t.implicit) != len(union.Variants) { return t.invariant("has a variant no branch stands for") } - tagReadings := readingsOf(t.c) - tags, ok := pinnedTags(reg, tagReadings, flattenVariants(reg, union.Variants), discriminator.PropertyName, false /* required */) + memo := tagSetMemoOf(t.loweringContext) + tags, ok := pinnedTags(types, memo, flattenVariants(types.registry, union.Variants), discriminator.PropertyName, false /* required */) if !ok || routedByName(tags, t.implicit) { return nil } discriminator.Mapping = tagMapping(tags, union.Variants) + discriminator.DecodeOnlyRoutes = nil + t.replacedNames(discriminator, union.Variants, allVariants(len(union.Variants))) union.Provenance.Inferred = ir.JoinInferred(union.Provenance.Inferred, lowering.DiscriminatorInferenceHeuristic) - return []ir.Diagnostic{t.c.DiagAt(ir.SeverityInfo, diag.InferredDiscriminator, t.at, + return []ir.Diagnostic{t.loweringContext.DiagAt(ir.SeverityInfo, diag.InferredDiscriminator, t.at, "the discriminator declares no mapping, and OpenAPI's implicit mapping routes each variant only by the "+ "name of the component it names, not by what it admits for %q (%s); "+ "mapped by the values each admits, marked inferred", discriminator.PropertyName, disagreements(tags, t.implicit))} } +// mapLeftOut maps the variants the declared mapping of union leaves out by the +// strings each admits for its tag property (GitHub #1798), where leftOutTags +// reads them, replacing their implied routes (replacedNames). +func (t unionTags) mapLeftOut(types aliasedTypes, union *ir.Union) []ir.Diagnostic { + discriminator := union.Discriminator + if discriminator == nil { + return t.invariant("holds no discriminator, though its source declares one") + } + if len(t.implicit) != len(union.Variants) { + return t.invariant("has a variant no branch stands for") + } + leftOut := t.leftOut(discriminator, union.Variants) + if len(leftOut) == 0 { + return nil + } + tags, ok := t.leftOutTags(types, union, leftOut) + if !ok { + return nil + } + for i, variant := range leftOut { + if route := t.implicit[variant]; route.named && discriminator.Mapping[route.name] == union.Variants[variant].Type.Target { + delete(discriminator.Mapping, route.name) + } + for _, tag := range tags[i] { + addRoute(&discriminator.Mapping, tag, union.Variants[variant].Type.Target) + } + } + t.replacedNames(discriminator, union.Variants, leftOut) + union.Provenance.Inferred = ir.JoinInferred(union.Provenance.Inferred, lowering.DiscriminatorInferenceHeuristic) + implicit := make([]implicitRoute, len(leftOut)) + for i, variant := range leftOut { + implicit[i] = t.implicit[variant] + } + return []ir.Diagnostic{t.loweringContext.DiagAt(ir.SeverityInfo, diag.InferredDiscriminator, t.at, + "the discriminator's mapping leaves variants out, which OpenAPI's implicit mapping routes only by the "+ + "name of the component each names, not by what it admits for %q (%s); "+ + "mapped by the values each admits, marked inferred", + discriminator.PropertyName, disagreements(tags, implicit))} +} + +// leftOut returns the index of each variant of variants no entry of the +// declared mapping routes, in variant order. +func (t unionTags) leftOut(discriminator *ir.Discriminator, variants []ir.Variant) []int { + byEntry := map[ir.TypeID]bool{} + for _, key := range t.entries { + if target, ok := discriminator.Mapping[key]; ok { + byEntry[target] = true + } + } + var out []int + for i, variant := range variants { + if !byEntry[variant.Type.Target] { + out = append(out, i) + } + } + return out +} + +// leftOutTags returns the strings each left-out variant pins for the tag, in +// the order of leftOut, and false unless each pins them alone and the implicit +// mapping fails to route one of them by all it admits. +func (t unionTags) leftOutTags(types aliasedTypes, union *ir.Union, leftOut []int) ([][]string, bool) { + memo := tagSetMemoOf(t.loweringContext) + flats := flattenVariants(types.registry, union.Variants) + property := union.Discriminator.PropertyName + read := make([]tagSet, len(flats)) + for i, flat := range flats { + member, declared := flat.byName[property] + read[i] = memo.object(types, flat.flat, member, declared, property) + } + tags := make([][]string, 0, len(leftOut)) + byName := true + for _, variant := range leftOut { + if !read[variant].fixesTags() || !t.pinnedAlone(read, variant) { + return nil, false + } + tags = append(tags, read[variant].strings) + byName = byName && t.implicit[variant].routesExactly(read[variant].strings) + } + return tags, !byName +} + +// pinnedAlone reports whether no variant but the one at variant admits a +// string it pins, and no entry spells one. +func (t unionTags) pinnedAlone(read []tagSet, variant int) bool { + for _, tag := range read[variant].strings { + if slices.Contains(t.entries, tag) { + return false + } + for other, set := range read { + if other != variant && set.admits(tag) { + return false + } + } + } + return true +} + +// replacedNames routes each name the policy's reading replaced, the implied +// route of each variant at replaced, decode-only, unless it is one of the +// strings mapped to its variant, an entry keys it, or two branches name it. +func (t unionTags) replacedNames(discriminator *ir.Discriminator, variants []ir.Variant, replaced []int) { + count := map[string]int{} + for _, route := range t.implicit { + if route.named { + count[route.name]++ + } + } + for _, variant := range replaced { + route := t.implicit[variant] + if !route.named || count[route.name] != 1 || slices.Contains(t.entries, route.name) { + continue + } + if _, mapped := discriminator.Mapping[route.name]; mapped { + continue + } + addRoute(&discriminator.DecodeOnlyRoutes, route.name, variants[variant].Type.Target) + } +} + +// allVariants returns the index of each of n variants. +func allVariants(n int) []int { + out := make([]int, n) + for i := range out { + out[i] = i + } + return out +} + // routedByName reports whether the implicit mapping routes each variant by all // it admits: the name of the component it names, and nothing else. func routedByName(tags [][]string, implicit []implicitRoute) bool { @@ -126,7 +264,7 @@ func routedByName(tags [][]string, implicit []implicitRoute) bool { // any tag. The other variants are flattened once, and only where the first pins // one, each keyed by wire name, so a candidate costs the same however many // members a variant has. -func (t unionTags) inferUndeclared(reg ir.TypeRegistry, union *ir.Union) []ir.Diagnostic { +func (t unionTags) inferUndeclared(types aliasedTypes, union *ir.Union) []ir.Diagnostic { if union.Discriminator != nil { return t.invariant("holds a discriminator, though its source declares none") } @@ -134,18 +272,19 @@ func (t unionTags) inferUndeclared(reg ir.TypeRegistry, union *ir.Union) []ir.Di slices.ContainsFunc(union.Variants, func(variant ir.Variant) bool { return variant.Type.Nullable }) { return nil } - tagReadings := readingsOf(t.c) - first := ir.FlattenedProperties(reg, union.Variants[0].Type.Target) + memo := tagSetMemoOf(t.loweringContext) + first := ir.FlattenedProperties(types.registry, union.Variants[0].Type.Target) var flats []variantFlat for _, flatProperty := range first.Properties { - if !flatProperty.Required || !tagReadings.object(reg, first, flatProperty, true, flatProperty.Property.EffectiveWireName()).pins() { + const declared = true // the flattening lists it + if !flatProperty.Required || !memo.object(types, first, flatProperty, declared, flatProperty.Property.EffectiveWireName()).fixesTags() { continue } if flats == nil { - flats = flattenVariants(reg, union.Variants) + flats = flattenVariants(types.registry, union.Variants) } name := flatProperty.Property.EffectiveWireName() - tags, ok := pinnedTags(reg, tagReadings, flats, name, true /* required */) + tags, ok := pinnedTags(types, memo, flats, name, true /* required */) if !ok { continue } @@ -180,11 +319,11 @@ func flattenVariants(reg ir.TypeRegistry, variants []ir.Variant) []variantFlat { } // pinnedTags returns the strings each variant admits for the property name, in -// variant order, read as tagReadings.object reads them, and false unless every -// one pins a set (tagSet.pins) and no two share a string: a mapping routes a -// tag to one variant. Where required is set, each variant must require the -// property too, as a tag no payload need carry names no variant. -func pinnedTags(reg ir.TypeRegistry, tagReadingsValue *tagReadings, flats []variantFlat, name string, required bool) ([][]string, bool) { +// variant order, read as tagSetMemo.object reads them, and false unless every +// one fixes the tags of a set (tagSet.fixesTags) and no two share a string: a +// mapping routes a tag to one variant. Where required is set, each variant must +// require the property too, as a tag no payload need carry names no variant. +func pinnedTags(types aliasedTypes, tagReadingsValue *tagSetMemo, flats []variantFlat, name string, required bool) ([][]string, bool) { tags := make([][]string, 0, len(flats)) seen := map[string]bool{} for _, variantFlat := range flats { @@ -192,8 +331,8 @@ func pinnedTags(reg ir.TypeRegistry, tagReadingsValue *tagReadings, flats []vari if required && !flatProperty.Required { return nil, false } - got := tagReadingsValue.object(reg, variantFlat.flat, flatProperty, declared, name) - if !got.pins() { + got := tagReadingsValue.object(types, variantFlat.flat, flatProperty, declared, name) + if !got.fixesTags() { return nil, false } for _, tag := range got.strings { diff --git a/compilers/openapi/internal/schema/tags_internal_test.go b/compilers/openapi/internal/schema/tags_internal_test.go index e2e372e1d..82f17e9e8 100644 --- a/compilers/openapi/internal/schema/tags_internal_test.go +++ b/compilers/openapi/internal/schema/tags_internal_test.go @@ -7,6 +7,7 @@ import ( "encoding/json/jsontext" "fmt" "math" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -31,8 +32,8 @@ func TestUnionTags_ReportsWhatItCannotSettle(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - tags := unionTags{c: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, id: "type/u", pointer: "/components/schemas/U"} - diags := tags.Settle(t.Context(), reg) + tags := unionTags{loweringContext: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, id: "type/u", pointer: "/components/schemas/U"} + diags := tags.Settle(t.Context(), reg, ir.NewAliasChainIndex(reg.Lookup)) require.Len(t, diags, 1) assert.Equal(t, diag.InternalInvariant, diags[0].Code) assert.Equal(t, ir.SeverityError, diags[0].Severity) @@ -54,7 +55,7 @@ func TestUnionTags_ReadsOnlyWhatItWasDeferredFor(t *testing.T) { }}} } variants := []ir.Variant{{Type: ir.TypeRef{Target: "type/a"}}, {Type: ir.TypeRef{Target: "type/b"}}} - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { union *ir.Union at jsontext.Pointer implicit []implicitRoute @@ -63,48 +64,55 @@ func TestUnionTags_ReadsOnlyWhatItWasDeferredFor(t *testing.T) { "declared, none held": {&ir.Union{ID: "type/u", Variants: variants, Closed: true}, "/d", []implicitRoute{{name: "A", named: true}, {name: "B", named: true}}, true}, "declared, miscounted": {&ir.Union{ID: "type/u", Variants: variants, Closed: true, Discriminator: &ir.Discriminator{PropertyName: "kind"}}, "/d", []implicitRoute{{name: "A", named: true}}, true}, + "a declared mapping, none held": {&ir.Union{ID: "type/u", Variants: variants, Closed: true}, "/d", + []implicitRoute{{name: "A", named: true}, {name: "B", named: true}}, true}, + "a declared mapping, miscounted": {&ir.Union{ID: "type/u", Variants: variants, Closed: true, + Discriminator: &ir.Discriminator{PropertyName: "kind"}}, "/d", []implicitRoute{{name: "A", named: true}}, true}, "undeclared, tagged": {&ir.Union{ID: "type/u", Variants: variants, Closed: true, WireTagged: true, Discriminator: &ir.Discriminator{PropertyName: "other"}}, "", nil, true}, "undeclared, open": {&ir.Union{ID: "type/u", Variants: variants}, "", nil, false}, } { t.Run(name, func(t *testing.T) { t.Parallel() - before := *tc.union + before := *testCase.union reg := ir.TypeRegistry{ - "type/u": tc.union, "type/a": pinned("type/a", "a"), "type/b": pinned("type/b", "b"), + "type/u": testCase.union, "type/a": pinned("type/a", "a"), "type/b": pinned("type/b", "b"), "type/lit/a": &ir.Literal{ID: "type/lit/a", Value: ir.Value{Kind: ir.ValueString, String: "a"}}, "type/lit/b": &ir.Literal{ID: "type/lit/b", Value: ir.Value{Kind: ir.ValueString, String: "b"}}, } - tags := unionTags{c: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, id: "type/u", - pointer: "/components/schemas/U", at: tc.at, implicit: tc.implicit} - diags := tags.Settle(t.Context(), reg) - if tc.bug { + tags := unionTags{loweringContext: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, id: "type/u", + pointer: "/components/schemas/U", at: testCase.at, implicit: testCase.implicit} + if strings.HasPrefix(name, "a declared mapping") { + tags.entries = []string{"a"} + } + diags := tags.Settle(t.Context(), reg, ir.NewAliasChainIndex(reg.Lookup)) + if testCase.bug { require.Len(t, diags, 1) assert.Equal(t, diag.InternalInvariant, diags[0].Code) assert.Equal(t, ir.SeverityError, diags[0].Severity) } else { assert.Empty(t, diags) } - assert.Equal(t, before.Discriminator, tc.union.Discriminator) - assert.Equal(t, before.WireTagged, tc.union.WireTagged) - assert.Empty(t, tc.union.Provenance.Inferred) + assert.Equal(t, before.Discriminator, testCase.union.Discriminator) + assert.Equal(t, before.WireTagged, testCase.union.WireTagged) + assert.Empty(t, testCase.union.Provenance.Inferred) }) } } -// TestSpellImplicitRoutes_ReportsAVariantNoBranchStandsFor pins the state only +// TestSpellImplicitRoutes_ReportsAVariantNoBranchNames pins the state only // a compiler bug leaves a distributed union in, a variant count its branches // do not match: reported, and no route written, since none can be paired. -func TestSpellImplicitRoutes_ReportsAVariantNoBranchStandsFor(t *testing.T) { +func TestSpellImplicitRoutes_ReportsAVariantNoBranchNames(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", " U: {oneOf: [{$ref: '#/components/schemas/A'}], discriminator: {propertyName: k}}\n A: {type: object}\n")) - js, ok := lowerer.Doc.Components.Schemas.Get("U") + jsonSchema, ok := lowerer.Doc.Components.Schemas.Get("U") require.True(t, ok) union := &ir.Union{Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/a"}}, {Type: ir.TypeRef{Target: "type/b"}}}, Discriminator: &ir.Discriminator{PropertyName: "k"}} - diags := spellImplicitRoutes(lowerer.Ctx, besideUnion(lowerer.Ctx.Statements().Of(js).Schema, ""), union, "/components/schemas/U") + diags := spellImplicitRoutes(lowerer.Ctx, besideUnion(lowerer.Ctx.Statements().Of(jsonSchema).Schema, ""), union, "/components/schemas/U") require.Len(t, diags, 1) assert.Equal(t, diag.InternalInvariant, diags[0].Code) @@ -158,11 +166,12 @@ func settleAllocs(t *testing.T, width, pinned int) float64 { } reg["type/u"] = &ir.Union{ID: "type/u", Variants: variants, Closed: true} - tags := unionTags{c: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, id: "type/u", + tags := unionTags{loweringContext: servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx, id: "type/u", pointer: "/components/schemas/U"} + aliases := ir.NewAliasChainIndex(reg.Lookup) fewest := math.Inf(1) for range 20 { - fewest = min(fewest, testing.AllocsPerRun(1, func() { tags.Settle(t.Context(), reg) })) + fewest = min(fewest, testing.AllocsPerRun(1, func() { tags.Settle(t.Context(), reg, aliases) })) } return fewest } diff --git a/compilers/openapi/internal/schema/tags_test.go b/compilers/openapi/internal/schema/tags_test.go index de0c93fb6..47040e32f 100644 --- a/compilers/openapi/internal/schema/tags_test.go +++ b/compilers/openapi/internal/schema/tags_test.go @@ -99,7 +99,7 @@ func TestDiscriminatorInference_MapsAnUnmappedDiscriminator(t *testing.T) { require.NotNil(t, union.Discriminator) assert.False(t, union.Discriminator.Inferred, "the discriminator is declared") if c.want == nil { - assert.Nil(t, union.Discriminator.Mapping, "the implicit mapping stands") + assert.Nil(t, union.Discriminator.Mapping, "the implicit mapping remains") assert.Empty(t, union.Provenance.Inferred) assert.False(t, openapitest.HasDiagCodeAt(doc.Diagnostics, diag.InferredDiscriminator, unionAt+"/discriminator")) continue @@ -188,10 +188,13 @@ func TestDiscriminatorInference_InfersAnUndeclaredDiscriminator(t *testing.T) { {"absent from a variant", variant("A", "kind: {const: a}", "kind") + variant("B", "other: {const: b}", "other"), "", nil}, {"a variant no model", variant("A", "kind: {const: a}", "kind") + " B: {type: string}\n", "", nil}, } + // drawn holds the codes a row's document draws, by the row's name: a + // constraint ruling a string out of one branch refuses a member it lists. + drawn := map[string][]string{"a oneOf of values two admit": {"pass/enum-member-outside-bounds"}} for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - for _, doc := range taggedOrders(t, union, c.rest) { + for _, doc := range taggedOrders(t, union, c.rest, drawn[c.name]...) { union := taggedUnion(t, doc) if c.want == nil { assert.Nil(t, union.Discriminator) @@ -266,12 +269,12 @@ func TestDiscriminatorInference_DisabledReadsNothing(t *testing.T) { assert.Zero(t, openapitest.CountDiagsAt(diags, diag.InferredDiscriminator, ir.SeverityInfo)) } -// TestDiscriminatorInference_JoinsTheMarksANodeCarries pins that the policy's -// mark joins the marks other heuristics left on the node it reads in, rather -// than replacing them: a union whose mapping it fills, one whose discriminator -// it reads in, and a subtype whose tag it reads, each deprecated by an -// extension the promotion policy reads. -func TestDiscriminatorInference_JoinsTheMarksANodeCarries(t *testing.T) { +// TestDiscriminatorInference_CombinesTheMarksANodeCarries pins that the +// policy's mark adds to the marks other heuristics left on the node it reads +// in, rather than replacing them: a union whose mapping it fills, one whose +// discriminator it reads in, and a subtype whose tag it reads, each deprecated +// by an extension the promotion policy reads. +func TestDiscriminatorInference_CombinesTheMarksANodeCarries(t *testing.T) { t.Parallel() const deprecated = " x-stability: deprecated\n" const variants = "[{$ref: '#/components/schemas/Json'}, {$ref: '#/components/schemas/Text'}]\n" @@ -297,7 +300,7 @@ func TestDiscriminatorInference_JoinsTheMarksANodeCarries(t *testing.T) { // TestDiscriminatorInference_ReadsADistributedUnion pins that the reading // meets a union whose variants compose the body beside it: each variant's tag -// is read across its composition, the branch's pin standing where the body +// is read across its composition, the branch's pin holding where the body // redeclares the tag as a string, and the mapping read off them replaces the // implicit one written out for the composed variants, or tags a union // declaring no discriminator. @@ -339,16 +342,21 @@ func inlinePin(tag string) string { const unionAt = "/components/schemas/U" // taggedOrders compiles union and rest in both declaration orders, requires -// each to validate and the two to agree on their types and on what they -// report, and returns both: the reading runs once every node is interned, so a -// variant lowered after the union must read alike. -func taggedOrders(t *testing.T, union, rest string) []*ir.Document { +// each to validate, drawing a finding of each code drawn names and no other, +// and the two to agree on their types and on what they report, and returns +// both: the reading runs once every node is interned, so a variant lowered +// after the union must read alike. +func taggedOrders(t *testing.T, union, rest string, drawn ...string) []*ir.Document { t.Helper() docs := make([]*ir.Document, 0, 2) for _, src := range []string{union + rest, rest + union} { doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", src)) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc), "the document must validate") + var codes []string + for _, diagnostic := range routeFindings(t, doc) { + codes = append(codes, diagnostic.Code) + } + assert.Equal(t, drawn, codes, "the document must validate") doc.Diagnostics = diags docs = append(docs, doc) } diff --git a/compilers/openapi/internal/schema/tagset.go b/compilers/openapi/internal/schema/tagset.go index c1b585857..0e19c0a3e 100644 --- a/compilers/openapi/internal/schema/tagset.go +++ b/compilers/openapi/internal/schema/tagset.go @@ -9,11 +9,6 @@ import ( "github.com/dexpace/morphic/ir" ) -// maxTagAliasHops bounds how many alias scalars a tag's type is read through -// (styleguide bounded-everything rule), as maxBodyAliasHops bounds a body's. A -// longer chain, or a loop, stops on an alias, which bounds no tag. -const maxTagAliasHops = 64 - // tagSet is what an instance may hold at a tag property, as the // discriminator-inference policy reads it // (docs/compilers/openapi.md#discriminator-inference). @@ -34,9 +29,9 @@ func anyString() tagSet { return tagSet{} } // anything admits any value, null among them. func anything() tagSet { return tagSet{null: true} } -// pins reports whether a admits strings, every one a tag, and nothing else: a -// closed set of one or more, without null. -func (a tagSet) pins() bool { return a.closed && len(a.strings) > 0 && !a.null } +// fixesTags reports whether a admits strings, every one a tag, and nothing +// else: a closed set of one or more, without null. +func (a tagSet) fixesTags() bool { return a.closed && len(a.strings) > 0 && !a.null } // admits reports whether a admits the string tag. func (a tagSet) admits(tag string) bool { @@ -47,9 +42,9 @@ func (a tagSet) admits(tag string) bool { return found } -// meet returns what both a and b admit, as an instance meeting two -// declarations holds: the strings both bound, and null where both admit it. -func meet(a, b tagSet) tagSet { +// intersectTagSets returns what both a and b admit, as an instance satisfying +// two declarations holds: the strings both bound, and null where both admit it. +func intersectTagSets(a, b tagSet) tagSet { switch { case !b.closed: return tagSet{strings: a.strings, closed: a.closed, null: a.null && b.null} @@ -65,12 +60,12 @@ func meet(a, b tagSet) tagSet { return tagSet{strings: both, closed: true, null: a.null && b.null} } -// join returns what a value of one of sets admits: the strings any admits, and -// null where any does. One not closed bounds no string. A oneOf joins so too, -// though a value two of its variants admit matches neither, as a set may admit -// more than its variant holds: what else an object holds tells its variants -// apart, and a constraint kept beside an Enum narrows its members. -func join(sets []tagSet) tagSet { +// unionTagSets returns what a value of one of sets admits: the strings any +// admits, and null where any does. One not closed bounds no string. A oneOf is +// so too, though a value two of its variants admit matches neither, as a set +// may admit more than its variant holds: what else an object holds tells its +// variants apart, and a constraint kept beside an Enum narrows its members. +func unionTagSets(sets []tagSet) tagSet { got := tagSet{closed: true} for _, set := range sets { got.closed = got.closed && set.closed @@ -88,11 +83,11 @@ func join(sets []tagSet) tagSet { return got } -// leaf returns what a value of td, no union, admits: a string Literal's +// leaf returns what a value of typeDef, no union, admits: a string Literal's // string, or the members of a closed Enum marking no flags every one of which // is a string, sorted and once each. Any other node admits any string. -func leaf(td ir.TypeDef) tagSet { - switch n := td.(type) { +func leaf(typeDef ir.TypeDef) tagSet { + switch n := typeDef.(type) { case *ir.Literal: if n == nil || n.Value.Kind != ir.ValueString { return anyString() @@ -116,18 +111,12 @@ func leaf(td ir.TypeDef) tagSet { } } -// throughAliases returns the type the alias scalars from id stand over, at -// most maxTagAliasHops of them read, and whether one of them admits null. -func throughAliases(reg ir.TypeRegistry, id ir.TypeID) (ir.TypeID, bool) { - null := false - for range maxTagAliasHops { - scalar, alias := reg[id].(*ir.Scalar) - if !alias || scalar == nil || scalar.Base == nil { - break - } - id, null = scalar.Base.Target, null || scalar.Base.Nullable - } - return id, null +// throughAliases returns the type the alias scalars from id sit over. A hop's +// null is no value a use of id admits: the use's reference says it +// (docs/ir/scalars.md#aliases). A loop stops on an alias, which bounds no tag. +func throughAliases(aliases *ir.AliasChainIndex, id ir.TypeID) ir.TypeID { + end, _ := aliases.End(id) + return end } // unionNode returns the union the type id is, nil where it is none. diff --git a/compilers/openapi/internal/schema/tagset_internal_test.go b/compilers/openapi/internal/schema/tagset_internal_test.go index 3497b7b36..84ba29cdb 100644 --- a/compilers/openapi/internal/schema/tagset_internal_test.go +++ b/compilers/openapi/internal/schema/tagset_internal_test.go @@ -12,10 +12,11 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestThroughAliases_ReadsAtMostTheBound pins the alias scalars a tag's type -// is read through: a chain of maxTagAliasHops reaches what it stands over, a -// longer one or a loop stops on an alias, which bounds no tag. -func TestThroughAliases_ReadsAtMostTheBound(t *testing.T) { +// TestThroughAliases_ReadsAChainToItsEnd pins the alias scalars a tag's type +// is read through: a chain of any length reaches what it sits over, past the +// 64 aliases a walk once stopped at, while a loop stops on an alias, which +// bounds no tag. +func TestThroughAliases_ReadsAChainToItsEnd(t *testing.T) { t.Parallel() chain := func(hops int) ir.TypeRegistry { reg := ir.TypeRegistry{"type/lit": lit("type/lit", "a")} @@ -28,12 +29,13 @@ func TestThroughAliases_ReadsAtMostTheBound(t *testing.T) { reg["type/x"] = reg[next] return reg } - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { reg ir.TypeRegistry bound bool }{ - "within the bound": {chain(maxTagAliasHops), true}, - "past the bound": {chain(maxTagAliasHops + 1), false}, + "64 aliases": {chain(64), true}, + "65 aliases": {chain(65), true}, + "200 aliases": {chain(200), true}, "a loop": {ir.TypeRegistry{ "type/x": &ir.Scalar{ID: "type/x", Base: &ir.TypeRef{Target: "type/y"}}, "type/y": &ir.Scalar{ID: "type/y", Base: &ir.TypeRef{Target: "type/x"}}, @@ -41,7 +43,7 @@ func TestThroughAliases_ReadsAtMostTheBound(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - assert.Equal(t, tc.bound, valueOf(newReadings(t), tc.reg, to("type/x")).pins()) + assert.Equal(t, testCase.bound, valueOf(newTagSetMemo(t), aliasedTypesOf(testCase.reg), to("type/x")).fixesTags()) }) } } diff --git a/compilers/openapi/internal/schema/tagreadings_internal_test.go b/compilers/openapi/internal/schema/tagsetmemo_internal_test.go similarity index 77% rename from compilers/openapi/internal/schema/tagreadings_internal_test.go rename to compilers/openapi/internal/schema/tagsetmemo_internal_test.go index 828de5ee4..ec85dcde9 100644 --- a/compilers/openapi/internal/schema/tagreadings_internal_test.go +++ b/compilers/openapi/internal/schema/tagsetmemo_internal_test.go @@ -21,11 +21,11 @@ import ( "github.com/dexpace/morphic/ir" ) -// newReadings returns a run's tagReadings over a context of its own, so no +// newTagSetMemo returns a run's tagSetMemo over a context of its own, so no // test shares what another read. -func newReadings(t *testing.T) *tagReadings { +func newTagSetMemo(t *testing.T) *tagSetMemo { t.Helper() - return readingsOf(servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx) + return tagSetMemoOf(servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx) } // lit is a string Literal at id. @@ -45,27 +45,33 @@ func unionOf(id ir.TypeID, exclusive bool, targets ...ir.TypeRef) *ir.Union { // to is a non-nullable reference to id. func to(id ir.TypeID) ir.TypeRef { return ir.TypeRef{Target: id} } +// aliasedTypesOf is reg as a reading reads it, through an alias index of its +// own. +func aliasedTypesOf(reg ir.TypeRegistry) aliasedTypes { + return aliasedTypes{registry: reg, aliases: ir.NewAliasChainIndex(reg.Lookup)} +} + // valueOf returns what a value typeRef names admits, as tagReadingsValue reads // a member declared by typeRef alone. -func valueOf(tagReadingsValue *tagReadings, reg ir.TypeRegistry, typeRef ir.TypeRef) tagSet { - return tagReadingsValue.member(reg, ir.FlatProperty{Property: &ir.Property{Type: typeRef}}) +func valueOf(tagReadingsValue *tagSetMemo, types aliasedTypes, typeRef ir.TypeRef) tagSet { + return tagReadingsValue.member(types, ir.FlatProperty{Property: &ir.Property{Type: typeRef}}) } -// TestTagReadings_ValueReadsAClosedSetOfStrings pins what a type must be to -// bound a tag to strings: a string Literal, a closed Enum marking no flags every -// member of which is a string, its members read sorted and once, or a closed -// union every variant of which bounds them, a oneOf admitting what any variant -// does, as an anyOf does, read through alias scalars. Any other node, a nil one -// included, admits any string, and null where a reference along the way is -// nullable. -func TestTagReadings_ValueReadsAClosedSetOfStrings(t *testing.T) { +// TestTagSetMemo_ValueReadsAClosedSetOfStrings pins what a type must be to +// bound a tag to strings: a string Literal, a closed Enum marking no flags +// every member of which is a string, its members read sorted and once, or a +// closed union every variant of which bounds them, a oneOf admitting what any +// variant does, as an anyOf does, read through alias scalars. Any other node, a +// nil one included, admits any string, and null where the reference read or a +// variant's is nullable, an alias's Base saying nothing of a use's null. +func TestTagSetMemo_ValueReadsAClosedSetOfStrings(t *testing.T) { t.Parallel() stringValue := func(s string) ir.EnumMember { return ir.EnumMember{Value: ir.Value{Kind: ir.ValueString, String: s}} } number := ir.EnumMember{Value: ir.Value{Kind: ir.ValueNumber, Number: "1"}} nullable := func(id ir.TypeID) ir.TypeRef { return ir.TypeRef{Target: id, Nullable: true} } base := ir.TypeRegistry{"type/a": lit("type/a", "a"), "type/b": lit("type/b", "b"), "type/c": lit("type/c", "c"), "type/str": &ir.Primitive{ID: "type/str", PrimitiveKind: ir.PrimitiveString}} - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { node ir.TypeDef want []string // nil where none is bounded null bool @@ -83,7 +89,7 @@ func TestTagReadings_ValueReadsAClosedSetOfStrings(t *testing.T) { "model": {&ir.Model{}, nil, false}, "through alias": {&ir.Scalar{Base: &ir.TypeRef{Target: "type/a"}}, []string{"a"}, false}, "a nullable alias": {&ir.Scalar{Base: &ir.TypeRef{Target: "type/a", Nullable: true}}, - []string{"a"}, true}, + []string{"a"}, false}, "anyOf": {unionOf("type/x", false, to("type/b"), to("type/a"), to("type/b")), []string{"a", "b"}, false}, "oneOf, one shared": {unionOf("type/x", true, to("type/a"), to("type/b"), to("type/a")), []string{"a", "b"}, false}, "a nullable variant": {unionOf("type/x", false, to("type/a"), nullable("type/b")), @@ -99,30 +105,30 @@ func TestTagReadings_ValueReadsAClosedSetOfStrings(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - reg := ir.TypeRegistry{"type/x": tc.node, + reg := ir.TypeRegistry{"type/x": testCase.node, "type/inner": unionOf("type/inner", true, to("type/b"), to("type/c")), "type/aliased": &ir.Scalar{ID: "type/aliased", Base: &ir.TypeRef{Target: "type/inner"}}} maps.Copy(reg, base) - got := valueOf(newReadings(t), reg, to("type/x")) - assert.Equal(t, tc.want != nil, got.closed) - if tc.want != nil { - assert.Equal(t, tc.want, got.strings) + got := valueOf(newTagSetMemo(t), aliasedTypesOf(reg), to("type/x")) + assert.Equal(t, testCase.want != nil, got.closed) + if testCase.want != nil { + assert.Equal(t, testCase.want, got.strings) } - assert.Equal(t, tc.null, got.null) - assert.Equal(t, len(tc.want) > 0 && !tc.null, got.pins()) + assert.Equal(t, testCase.null, got.null) + assert.Equal(t, len(testCase.want) > 0 && !testCase.null, got.fixesTags()) }) } } -// TestTagReadings_AUnionOnACycleAdmitsAnything pins that a union reaching a +// TestTagSetMemo_AUnionOnACycleAdmitsAnything pins that a union reaching a // cycle of unions, or on one, admits any value, null among them, whichever // union the reading meets first, so no answer turns on the order settlements // ask in; a union beside the cycle is read as if it were not there. -func TestTagReadings_AUnionOnACycleAdmitsAnything(t *testing.T) { +func TestTagSetMemo_AUnionOnACycleAdmitsAnything(t *testing.T) { t.Parallel() reg := ir.TypeRegistry{ "type/a": lit("type/a", "a"), "type/b": lit("type/b", "b"), - // p and q name each other; tagReadings reaches them; s is beside them. + // p and q name each other; tagSetMemo reaches them; s is beside them. "type/p": unionOf("type/p", true, to("type/q"), ir.TypeRef{Target: "type/a", Nullable: true}), "type/q": unionOf("type/q", true, to("type/p"), to("type/b")), "type/r": unionOf("type/r", false, to("type/a"), to("type/p")), @@ -132,10 +138,10 @@ func TestTagReadings_AUnionOnACycleAdmitsAnything(t *testing.T) { } ids := []ir.TypeID{"type/p", "type/q", "type/r", "type/s", "type/l"} read := func(order []ir.TypeID) map[ir.TypeID]tagSet { - tagReadings := newReadings(t) + memo := newTagSetMemo(t) out := map[ir.TypeID]tagSet{} for _, id := range order { - out[id] = valueOf(tagReadings, reg, to(id)) + out[id] = valueOf(memo, aliasedTypesOf(reg), to(id)) } return out } @@ -151,12 +157,12 @@ func TestTagReadings_AUnionOnACycleAdmitsAnything(t *testing.T) { } } -// TestTagReadings_ACycleOfCompositionReadsAlikeFromAnyEntry pins what a +// TestTagSetMemo_ACycleOfCompositionReadsAlikeFromAnyEntry pins what a // cycle of unions and the objects composing them reads, the shape of a union // listing subtypes that compose it: each subtype its own pin, the union what // any of them admits, and so a holder composing it, every answer the same // whichever reading the walk enters first. -func TestTagReadings_ACycleOfCompositionReadsAlikeFromAnyEntry(t *testing.T) { +func TestTagSetMemo_ACycleOfCompositionReadsAlikeFromAnyEntry(t *testing.T) { t.Parallel() subtype := func(id, tag ir.TypeID) *ir.Model { return &ir.Model{ID: id, Mixins: []ir.TypeRef{to("type/shape")}, @@ -169,13 +175,13 @@ func TestTagReadings_ACycleOfCompositionReadsAlikeFromAnyEntry(t *testing.T) { "type/holder": &ir.Model{ID: "type/holder", Mixins: []ir.TypeRef{to("type/shape")}}, } read := func(order []ir.TypeID) map[string]tagSet { - tagReadings := newReadings(t) + memo, withAliasIndex := newTagSetMemo(t), aliasedTypesOf(reg) out := map[string]tagSet{} for _, id := range order { flat := ir.FlattenedProperties(reg, id) flatProperty, declared := flatMember(flat, "kind") - out[string(id)] = tagReadings.object(reg, flat, flatProperty, declared, "kind") - out["fold "+string(id)] = tagReadings.fold(reg, readKey{id: id, name: "kind", object: true}) + out[string(id)] = memo.object(withAliasIndex, flat, flatProperty, declared, "kind") + out["fold "+string(id)] = memo.fold(withAliasIndex, readKey{id: id, name: "kind", object: true}) } return out } @@ -191,11 +197,11 @@ func TestTagReadings_ACycleOfCompositionReadsAlikeFromAnyEntry(t *testing.T) { } } -// TestTagReadings_SweepsACycleAtMostTheBound pins the sweeps a cycle of +// TestTagSetMemo_SweepsACycleAtMostTheBound pins the sweeps a cycle of // unions and the objects composing them is read in: a pin carried back a step // a sweep reaches the union it is read from on the last sweep allowed, and // the model it is read from on the sweep after, past the bound, so any value. -func TestTagReadings_SweepsACycleAtMostTheBound(t *testing.T) { +func TestTagSetMemo_SweepsACycleAtMostTheBound(t *testing.T) { t.Parallel() // chain is a cycle of n unions of one model each, every model composing the // next union and the last the first, pinning kind to a: the pin reaches the @@ -221,16 +227,16 @@ func TestTagReadings_SweepsACycleAtMostTheBound(t *testing.T) { {maxComponentSweeps / 2, "type/u0", true}, {maxComponentSweeps/2 + 1, "type/m0", false}, } { - got := newReadings(t).fold(chain(c.n), readKey{id: c.root, name: "kind", object: true}) + got := newTagSetMemo(t).fold(aliasedTypesOf(chain(c.n)), readKey{id: c.root, name: "kind", object: true}) assert.Equal(t, c.closed, got.closed, "%s on a cycle of %d unions", c.root, c.n) } } -// TestTagReadings_SweepsACycleUntilItsNullsSettle pins how a cycle reads null, +// TestTagSetMemo_SweepsACycleUntilItsNullsSettle pins how a cycle reads null, // from any value down: where every model on it lets its tag hold null, so // does each, and where all but the last do, the last's exclusion of null // reaches the first on a sweep changing nothing else, which is not the last. -func TestTagReadings_SweepsACycleUntilItsNullsSettle(t *testing.T) { +func TestTagSetMemo_SweepsACycleUntilItsNullsSettle(t *testing.T) { t.Parallel() const n = 3 for _, lastNullable := range []bool{true, false} { @@ -242,18 +248,18 @@ func TestTagReadings_SweepsACycleUntilItsNullsSettle(t *testing.T) { Properties: []ir.Property{{ID: ir.PropertyID("property/" + m), Name: ir.Naming{Source: "kind"}, Type: ir.TypeRef{Target: "type/a", Nullable: i < n-1 || lastNullable}}}} } - got := newReadings(t).fold(reg, readKey{id: "type/m0", name: "kind", object: true}) + got := newTagSetMemo(t).fold(aliasedTypesOf(reg), readKey{id: "type/m0", name: "kind", object: true}) assert.Equal(t, tagSet{strings: []string{"a"}, closed: true, null: lastNullable}, got, "the last model's tag nullable: %t", lastNullable) } } -// TestTagReadings_MemberMeetsEveryDeclaration pins that a member's tag is read -// off every declaration it conjoins, as an instance meets them all: a set the -// taken declaration overrides stands, two sets meet, null admitted by one -// declaration is excluded by another, and a member every declaration lets hold -// null pins nothing. -func TestTagReadings_MemberMeetsEveryDeclaration(t *testing.T) { +// TestTagSetMemo_MemberIntersectsEveryDeclaration pins that a member's tag is +// read off every declaration it conjoins, as an instance satisfies them all: a +// set the taken declaration overrides remains, two sets intersect, null +// admitted by one declaration is excluded by another, and a member every +// declaration lets hold null pins nothing. +func TestTagSetMemo_MemberIntersectsEveryDeclaration(t *testing.T) { t.Parallel() reg := ir.TypeRegistry{ "type/a": lit("type/a", "a"), "type/b": lit("type/b", "b"), @@ -271,7 +277,7 @@ func TestTagReadings_MemberMeetsEveryDeclaration(t *testing.T) { return ir.FlatProperty{PropertyDecl: taken, Overridden: overridden} } const stringTypeID = "type/primitive/string" - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { p ir.FlatProperty want []string // nil for no pin }{ @@ -287,21 +293,22 @@ func TestTagReadings_MemberMeetsEveryDeclaration(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - got := newReadings(t).member(reg, tc.p) - assert.Equal(t, tc.want != nil, got.pins()) - if tc.want != nil { - assert.Equal(t, tc.want, got.strings) + got := newTagSetMemo(t).member(aliasedTypesOf(reg), testCase.p) + assert.Equal(t, testCase.want != nil, got.fixesTags()) + if testCase.want != nil { + assert.Equal(t, testCase.want, got.strings) } }) } } -// TestTagReadings_ObjectMeetsWhatAComposedUnionAdmits pins what an object -// composing a union admits at a property: what its own member admits, met with -// what any variant's member does, as the instance is one of them. A variant -// declaring none, one admitting any string, and a union not closed bound -// nothing, and an object declaring no such member admits what the union does. -func TestTagReadings_ObjectMeetsWhatAComposedUnionAdmits(t *testing.T) { +// TestTagSetMemo_ObjectIntersectsWhatAComposedUnionAdmits pins what an object +// composing a union admits at a property: what its own member admits, +// intersected with what any variant's member does, as the instance is one of +// them. A variant declaring none, one admitting any string, and a union not +// closed bound nothing, and an object declaring no such member admits what the +// union does. +func TestTagSetMemo_ObjectIntersectsWhatAComposedUnionAdmits(t *testing.T) { t.Parallel() pinned := func(id, tag ir.TypeID) *ir.Model { return &ir.Model{ID: id, Properties: []ir.Property{{ID: ir.PropertyID("property/" + id), Name: ir.Naming{Source: "kind"}, @@ -312,7 +319,7 @@ func TestTagReadings_ObjectMeetsWhatAComposedUnionAdmits(t *testing.T) { "type/va": pinned("type/va", "type/a"), "type/vb": pinned("type/vb", "type/b"), "type/vc": pinned("type/vc", "type/c"), "type/vs": pinned("type/vs", "type/str"), "type/none": &ir.Model{ID: "type/none"}, } - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { own ir.TypeID // the object's own declaration's type, "" for none union *ir.Union want []string // nil for any @@ -333,7 +340,7 @@ func TestTagReadings_ObjectMeetsWhatAComposedUnionAdmits(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - typeRegistry := ir.TypeRegistry{"type/u": tc.union, "type/au": &ir.Scalar{ID: "type/au", Base: &ir.TypeRef{Target: "type/u"}}, + typeRegistry := ir.TypeRegistry{"type/u": testCase.union, "type/au": &ir.Scalar{ID: "type/au", Base: &ir.TypeRef{Target: "type/u"}}, "type/inner": unionOf("type/inner", false, to("type/vb"), to("type/vc")), "type/innerac": unionOf("type/innerac", true, to("type/va"), to("type/vc")), "type/composing": &ir.Model{ID: "type/composing", Mixins: []ir.TypeRef{to("type/innerac")}}, @@ -341,31 +348,31 @@ func TestTagReadings_ObjectMeetsWhatAComposedUnionAdmits(t *testing.T) { "type/avc": &ir.Scalar{ID: "type/avc", Base: &ir.TypeRef{Target: "type/vc"}}} maps.Copy(typeRegistry, reg) composed := ir.TypeID("type/u") - if tc.through { + if testCase.through { composed = "type/au" } model := &ir.Model{ID: "type/m", Mixins: []ir.TypeRef{to(composed)}} - if tc.own != "" { - model.Properties = []ir.Property{{ID: "property/m", Name: ir.Naming{Source: "kind"}, Type: to(tc.own)}} + if testCase.own != "" { + model.Properties = []ir.Property{{ID: "property/m", Name: ir.Naming{Source: "kind"}, Type: to(testCase.own)}} } typeRegistry["type/m"] = model flat := ir.FlattenedProperties(typeRegistry, "type/m") flatProperty, declared := flatMember(flat, "kind") - got := newReadings(t).object(typeRegistry, flat, flatProperty, declared, "kind") - assert.Equal(t, tc.want != nil, got.closed) - if tc.want != nil { - assert.Equal(t, tc.want, got.strings) + got := newTagSetMemo(t).object(aliasedTypesOf(typeRegistry), flat, flatProperty, declared, "kind") + assert.Equal(t, testCase.want != nil, got.closed) + if testCase.want != nil { + assert.Equal(t, testCase.want, got.strings) } }) } } -// TestTagReadings_ReadsASharedTypeOnce pins what reading a type costs once a +// TestTagSetMemo_ReadsASharedTypeOnce pins what reading a type costs once a // reading has asked of it: the same at two widths, so N subtypes composing one // union of N variants, or N members typed by one union or Enum of N values, // read it once a run rather than once each. It is not run in parallel: // AllocsPerRun measures the process. -func TestTagReadings_ReadsASharedTypeOnce(t *testing.T) { +func TestTagSetMemo_ReadsASharedTypeOnce(t *testing.T) { for name, read := range map[string]func(*testing.T, int) float64{ "a composed union": conjunctAllocs, "a union of values": func(t *testing.T, width int) float64 { @@ -405,12 +412,12 @@ func conjunctAllocs(t *testing.T, width int) float64 { } reg["type/u"] = unionOf("type/u", true, variants...) reg["type/m"] = &ir.Model{ID: "type/m", Mixins: []ir.TypeRef{to("type/u")}} - tagReadings := newReadings(t) + memo, withAliasIndex := newTagSetMemo(t), aliasedTypesOf(reg) flat := ir.FlattenedProperties(reg, "type/m") - tagReadings.object(reg, flat, ir.FlatProperty{}, false, "kind") + memo.object(withAliasIndex, flat, ir.FlatProperty{}, false, "kind") fewest := math.Inf(1) for range 20 { - fewest = min(fewest, testing.AllocsPerRun(1, func() { tagReadings.object(reg, flat, ir.FlatProperty{}, false, "kind") })) + fewest = min(fewest, testing.AllocsPerRun(1, func() { memo.object(withAliasIndex, flat, ir.FlatProperty{}, false, "kind") })) } return fewest } @@ -428,30 +435,30 @@ func valueAllocs(t *testing.T, width int, set func(ir.TypeID, []ir.EnumMember) i members[i] = ir.EnumMember{Value: ir.Value{Kind: ir.ValueString, String: fmt.Sprintf("v%d", i)}} } reg["type/u"] = set("type/u", members) - tagReadings := newReadings(t) - valueOf(tagReadings, reg, to("type/u")) - _, kept := tagReadings.read[readKey{id: "type/u"}] + memo, withAliasIndex := newTagSetMemo(t), aliasedTypesOf(reg) + valueOf(memo, withAliasIndex, to("type/u")) + _, kept := memo.read[readKey{id: "type/u"}] assert.True(t, kept, "the reading is kept for the next to ask") fewest := math.Inf(1) for range 20 { - fewest = min(fewest, testing.AllocsPerRun(1, func() { valueOf(tagReadings, reg, to("type/u")) })) + fewest = min(fewest, testing.AllocsPerRun(1, func() { valueOf(memo, withAliasIndex, to("type/u")) })) } return fewest } -// TestReadingsOf_SharesOneStorePerRun pins that every settlement of a run reads -// through one tagReadings, so what one reads another does not read again, +// TestTagSetMemoOf_SharesOneStorePerRun pins that every settlement of a run +// reads through one tagSetMemo, so what one reads another does not read again, // while another run's starts empty. -func TestReadingsOf_SharesOneStorePerRun(t *testing.T) { +func TestTagSetMemoOf_SharesOneStorePerRun(t *testing.T) { t.Parallel() serviceContext := servicetest.Context(t, openapitest.EmptySpec, service.Policy{}) - first, again := readingsOf(serviceContext.Ctx), readingsOf(serviceContext.Ctx) + first, again := tagSetMemoOf(serviceContext.Ctx), tagSetMemoOf(serviceContext.Ctx) assert.Same(t, first, again) - assert.NotSame(t, readingsOf(serviceContext.Ctx), readingsOf(servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx)) + assert.NotSame(t, tagSetMemoOf(serviceContext.Ctx), tagSetMemoOf(servicetest.Context(t, openapitest.EmptySpec, service.Policy{}).Ctx)) } // TestModelFields_ReportsAFoldFollowingAStoredReading pins the order the tag -// readings rest on (tagReadings): a fold, which rewrites a member's type, runs +// readings rest on (tagSetMemo): a fold, which rewrites a member's type, runs // before any reading is stored, and reports nothing. A reading stored ahead of // it, as one would be were the fold deferred behind a union's tags, leaves // the fold reported as a compiler bug at its model, and the fold still taken. @@ -467,7 +474,7 @@ func TestModelFields_ReportsAFoldFollowingAStoredReading(t *testing.T) { require.Empty(t, loaded) lowerer.Diags.AppendAll(LowerComponentSchemas(t.Context(), lowerer.Ctx, lowerer.Types, lowerer.Schemas())) if early { - readingsOf(lowerer.Ctx).refOf(ir.TypeRegistry{}, to("type/elsewhere")) + tagSetMemoOf(lowerer.Ctx).refOf(aliasedTypesOf(ir.TypeRegistry{}), to("type/elsewhere")) } doc := lowerer.Document(t) diags := lowerer.Diags.List() @@ -480,12 +487,12 @@ func TestModelFields_ReportsAFoldFollowingAStoredReading(t *testing.T) { assert.Empty(t, cmp.Diff(models[0], models[1]), "the fold is taken either way") } -// TestTagReadings_ReadAModelAsTheMapItSwapsFor pins what lets a reading stored -// before a settlement swaps a model for its map (besideUnionDiscriminator) +// TestTagSetMemo_ReadAModelAsTheMapItSwapsFor pins what lets a reading stored +// before a settlement swaps a model for its map (modelRouteSettlement.Settle) // answer as one taken after: a model holding only a catch-all, of a pinned // type, admits any value at a property, as a variant or a conjunct, and any // string as a value, as its map does. -func TestTagReadings_ReadAModelAsTheMapItSwapsFor(t *testing.T) { +func TestTagSetMemo_ReadAModelAsTheMapItSwapsFor(t *testing.T) { t.Parallel() reg := ir.TypeRegistry{ "type/lit": lit("type/lit", "x"), @@ -494,10 +501,10 @@ func TestTagReadings_ReadAModelAsTheMapItSwapsFor(t *testing.T) { "type/s": &ir.Model{ID: "type/s", Mixins: []ir.TypeRef{to("type/u"), to("type/m")}}, } read := func() []tagSet { - tagReadings := newReadings(t) + memo, withAliasIndex := newTagSetMemo(t), aliasedTypesOf(reg) flat := ir.FlattenedProperties(reg, "type/s") flatProperty, declared := flatMember(flat, "kind") - return []tagSet{tagReadings.object(reg, flat, flatProperty, declared, "kind"), valueOf(tagReadings, reg, to("type/m"))} + return []tagSet{memo.object(withAliasIndex, flat, flatProperty, declared, "kind"), valueOf(memo, withAliasIndex, to("type/m"))} } before := read() model, ok := reg["type/m"].(*ir.Model) diff --git a/compilers/openapi/internal/schema/twin_internal_test.go b/compilers/openapi/internal/schema/twin_internal_test.go index 2d249a889..68925e9aa 100644 --- a/compilers/openapi/internal/schema/twin_internal_test.go +++ b/compilers/openapi/internal/schema/twin_internal_test.go @@ -21,13 +21,13 @@ func TestTwinKeyword_SpellsADraftsKeywordAs2020Does(t *testing.T) { " D7: {$schema: 'http://json-schema.org/draft-07/schema#'}\n"+ " D19: {$schema: 'https://json-schema.org/draft/2019-09/schema'}\n"+ " D20: {$schema: 'https://json-schema.org/draft/2020-12/schema'}\n")) - for _, tc := range []struct{ schema, key, want string }{ + for _, testCase := range []struct{ schema, key, want string }{ {"D4", "id", "$id"}, {"D7", "id", "id"}, {"D20", "id", "id"}, {"D7", "definitions", "$defs"}, {"D19", "definitions", "definitions"}, {"D4", "dependencies", "dependentSchemas"}, {"D19", "dependencies", "dependencies"}, {"D19", "$recursiveAnchor", "$dynamicAnchor"}, {"D7", "$recursiveAnchor", "$recursiveAnchor"}, {"D4", "type", "type"}, } { - assert.Equal(t, tc.want, TwinKeyword(lowerer.Ctx, StatedIn(lowerer, componentSchema(t, lowerer, tc.schema)), tc.key), "%s in %s", tc.key, tc.schema) + assert.Equal(t, testCase.want, TwinKeyword(lowerer.Ctx, StatedIn(lowerer, componentSchema(t, lowerer, testCase.schema)), testCase.key), "%s in %s", testCase.key, testCase.schema) } } diff --git a/compilers/openapi/internal/schema/typearray.go b/compilers/openapi/internal/schema/typearray.go index 1f11e131b..dbb29d2d1 100644 --- a/compilers/openapi/internal/schema/typearray.go +++ b/compilers/openapi/internal/schema/typearray.go @@ -17,97 +17,180 @@ import ( "github.com/dexpace/morphic/ir" ) -// lowerUnion hoists a multi-typed schema (e.g. type: [string, integer]) as an -// untagged union with one variant per declared type, exclusive unless two of -// them overlap (typesDisjoint). A type array asks for one of its types, not for -// exactly one, so overlapping variants must not exclude each other; with an -// integer width, integer and number name the same primitive, and the two -// variants stay, for an emitter to keep apart (docs/emitters/targets/go/unions.md). -// The Union stands where st says, and each variant, which no source pointer -// names, under it at /type/, built from what the Union reads beside schema. -func lowerUnion(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, list typeArray, - fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { +// lowerTypeArrayUnion hoists a multi-typed schema (e.g. type: [string, +// integer]) as an untagged union with one variant per declared type, exclusive +// unless two of them overlap (typesDisjoint). A type array asks for one of its +// types, not for exactly one, so overlapping variants must not exclude each +// other; with an integer width, integer and number name the same primitive, and +// the two variants stay, for an emitter to keep apart +// (docs/emitters/targets/go/unions.md). The Union is placed where placement +// says, each variant under it (typeVariantAt), reading schema where it is +// written, at pointer. +func lowerTypeArrayUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, list typeArray, + placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { var diags []ir.Diagnostic - types := list.types - at := st.pointer(pointer) - id := internNode(loweringContext, ts, at, func(common ir.TypeCommon) (ir.TypeDef, keySet) { - list.foldedEntries = st.foldedEntries(loweringContext, schema, pointer) - list.held = st.heldWhole(loweringContext, pointer) + var variantCloses bool + listedKinds := list.types + at := placement.pointer(pointer) + built := internNode(loweringContext, types, at, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + list.flattenedEntries = placement.flattenedEntries(loweringContext, schema, pointer) + list.keptWholeByPosition = placement.keptWhole(loweringContext, pointer) + list.objectConjuncts = objectConjunctsBeside(loweringContext, schema, pointer, placement) var read keySet - collect := finisher(func(_ ir.TypeDef, variant keySet, _ *principalKept) { read |= variant }) - variants := make([]ir.Variant, 0, len(types)) - for i, st := range types { - vptr := at + ids.Ptr("type", strconv.Itoa(i)) - vid, shared, vDiags := lowerTypeVariant(loweringContext, ts, depth, schema, vptr, st, list, collect) - read |= shared + variants := make([]ir.Variant, 0, len(listedKinds)) + for i, variantKind := range listedKinds { + vb, shared, vDiags := lowerTypeVariant(loweringContext, types, depth, schema, pointer, typeVariantAt(at, i), variantKind, list) + read |= vb.read | shared + variantCloses = variantCloses || vb.closesAfterComposition diags = append(diags, vDiags...) variants = append(variants, ir.Variant{ - Name: compile.NamingHint(string(st)), - Type: ir.TypeRef{Target: vid}, + Name: compile.NamingHint(string(variantKind)), + Type: ir.TypeRef{Target: vb.id}, }) } return &ir.Union{ TypeCommon: common, Variants: variants, - Exclusive: typesDisjoint(types), + Exclusive: typesDisjoint(listedKinds), Closed: true, }, read - }, fin) - return id, diags + }) + if built.node != nil { + built.closesAfterComposition = variantCloses + } + return built, diags } -// typeArray is what every variant of one type array reads beside its schema: the -// types it lists, the voices of the position it is written at, and the mark an -// object or array variant's build writes, where the kind-inference policy read -// the types (lowerTypeList). +// typeArray is what every variant of one type array reads beside its schema: +// the types it lists, the flattened entries of the position it is written at, +// and whether an object or array variant's build marks kind-inference +// (lowerTypeList). type typeArray struct { - types []statement.JSONSchemaTypeName - foldedEntries []annotation.FoldedAllOfEntry - mark finisher - // held says the position keeps the principal writing the list whole, so a - // variant keeps none of its bounds verbatim (stand.held). - held bool + types []statement.JSONSchemaTypeName + flattenedEntries []annotation.FlattenedAllOfEntry + // inferred marks object and array variants with the kind-inference policy. + inferred bool + // keptWholeByPosition says the position keeps the principal writing the list + // whole, so a variant keeps none of its bounds verbatim + // (nodePlacement.keptWholeByPosition). + keptWholeByPosition bool + // objectConjuncts are the conjuncts beside the list whose members its + // object variant composes (objectConjunctsBeside). + objectConjuncts []objectConjunct +} + +// listComposesMembers reports whether the type list refinementValue lowers +// position by, the inline principal's or else position's own, lists an object +// whose variant composes what the conjuncts beside it write of key, a +// `properties` or a `required` (objectConjunctsBeside). +func listComposesMembers(loweringContext lowering.Ctx, refinementValue refinement, position *statement.Schema, key string) bool { + if key != "properties" && key != "required" { + return false + } + conjunctSchema := position + if principal := refinementValue.principal; principal != nil && principal.schema.Ref == nil { + conjunctSchema = principal.schema.Schema + } + types := typingOf(loweringContext, conjunctSchema).types + return len(types) > 1 && slices.Contains(types, statement.KindObject) } -// lowerTypeVariant lowers the variant of schema's type array that st names, at -// pointer, as lowerTyped lowers st alone, but for what applies to another -// listed type (docs/compilers/openapi.md#type-arrays). An object variant holds -// no discriminator, which no $ref or mapping can name it by: the union keeps -// it. A variant reads, of schema and list's folded entries, the value bounds -// of the kinds of st the position admits (boundKinds), an array one the -// collection bounds. A scalar one holding them, the format or the content -// vocabulary is its own Scalar, else the shared primitive, returning what it -// read; fin finishes one built. -func lowerTypeVariant(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, st statement.JSONSchemaTypeName, - list typeArray, fin finisher, -) (ir.TypeID, keySet, []ir.Diagnostic) { - takes := typeKinds(st) & boundKinds(loweringContext, schema) - switch st { +// objectConjunct is a conjunct beside a type list, schema written at at, whose +// properties and required list the list's object variant composes. +type objectConjunct struct { + schema *statement.Schema + at jsontext.Pointer +} + +// objectConjunctsBeside returns the conjuncts of the type list schema writes at +// pointer that write object members: the position holding it as an entry, where +// placement names one, and the inline entries of the position's allOf but the +// list's own, each as its flat twin would merge them, by kind +// (docs/compilers/openapi.md#type-arrays). +func objectConjunctsBeside(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement) []objectConjunct { + position, at := schema, pointer + var out []objectConjunct + if placement.position != nil { + position, at = placement.position, placement.positionPointer + out = append(out, objectConjunct{schema: placement.position, at: placement.positionPointer}) + } + for _, entry := range allOfEntries(loweringContext, position, at).entries { + if entry.schema.Ref == nil && entry.schema.Schema != schema { + out = append(out, objectConjunct{schema: entry.schema.Schema, at: entry.pointer}) + } + } + return slices.DeleteFunc(out, func(objectConjunct objectConjunct) bool { + keywords := objectConjunct.schema.ObjectKeywords() + return len(keywords.Properties) == 0 && len(keywords.Required) == 0 + }) +} + +// typeVariantAt is where the variant of index i of the type list a position +// at at writes sits, which no source pointer names: its node's own +// pointer, for every reader minting or naming the variant. +func typeVariantAt(at jsontext.Pointer, i int) jsontext.Pointer { + return at + ids.Ptr("type", strconv.Itoa(i)) +} + +// lowerTypeVariant lowers the variant of schema's type array that typeName +// names, at at, reading schema where it is written, at pointer, as lowerTyped +// lowers typeName alone, but for what applies to another listed type +// (docs/compilers/openapi.md#type-arrays). An object variant holds no +// discriminator, which no $ref or mapping can name it by. A variant reads, of +// schema and list's flattened entries, the value bounds of the kinds of +// typeName the position admits (boundKinds), an array one the collection +// bounds. A scalar one holding them, the format or the content vocabulary is a +// Scalar, else the shared primitive, returning what it read. +func lowerTypeVariant(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer, at jsontext.Pointer, typeName statement.JSONSchemaTypeName, + list typeArray, +) (builtPosition, keySet, []ir.Diagnostic) { + takes := kindsOfTypeNameOrAny(typeName) & boundKinds(loweringContext, schema) + contentConjuncts := contentConjuncts(schema, pointer, list.flattenedEntries) + content := contentConjuncts.encoding.Node + variantHomes := typeHome(contentConjuncts, typeName, list.types, takes) + switch typeName { case statement.KindObject: - id, diags := lowerModel(loweringContext, ts, depth, schema, pointer, false /* discriminated */, takes, list.mark.then(fin)) - return id, 0, diags + built, diags := lowerModelAt(loweringContext, types, depth, schema, pointer, at, leavesDiscriminator, takes, list.flattenedEntries, list.objectConjuncts) + if list.inferred && built.node != nil { + markKindInferred(built.node) + } + return built, 0, diags case statement.KindArray: - id, diags := lowerArray(loweringContext, ts, depth, schema, pointer, pointer, list.foldedEntries, list.mark.then(fin)) - return id, 0, diags + built, diags := lowerArray(loweringContext, types, depth, schema, pointer, nodePlacement{positionPointer: at}, list.flattenedEntries, variantHomes) + if list.inferred && built.node != nil { + markKindInferred(built.node) + } + return built, 0, diags default: - shape := scalarShapeOf(schema, st, variantFormat(schema, st, list.types)) - if shape.shared && !statesBounds(loweringContext, schema, list.foldedEntries, pointer, takes) { - return ts.PrimitiveID(shape.base), shape.read, nil + shape := scalarShapeOf(content, typeName, variantFormat(writtenFormat(formatConjunct(schema, "", list.flattenedEntries).Node), typeName, list.types)) + shape.shared = shape.shared && !flattenedEntryWritesContent(typeName, list.flattenedEntries) + if shape.shared && !statesBounds(loweringContext, schema, list.flattenedEntries, pointer, variantHomes) { + return builtPosition{id: types.PrimitiveID(shape.base)}, shape.read, nil + } + var text textBoundIntersection + if variantHomes.otherText != 0 && !list.keptWholeByPosition { + text = intersectTextBounds(loweringContext, schema, list.flattenedEntries, variantHomes.otherText) + variantHomes.textYields = text.yields + } + built, diags := hoistScalar(loweringContext, types, depth, schema, shape, takesContent(kindsOfTypeNameOrAny(typeName)), variantHomes, list.flattenedEntries, pointer, nodePlacement{positionPointer: at, keptWholeByPosition: list.keptWholeByPosition}) + if built.node != nil { + // A variant carrying text of another kind keeps the value its list and + // flattened entries intersect in, as one written flat keeps the list's own. + diags = append(diags, text.keep(loweringContext, &built.node.Common().Unmodeled, list.flattenedEntries, pointer, variantHomes.root)...) } - id, diags := hoistScalar(loweringContext, ts, depth, schema, shape, takes, list.foldedEntries, pointer, fin, stand{held: list.held}) - return id, 0, diags + return built, 0, diags } } -// variantFormat returns the format schema writes, for its type array's variant -// of type st among types: the format where it pairs with st, or with no listed -// type, since nothing then says which type it describes, and a format validates -// only the instances of the types it is defined for (JSON Schema Validation -// 2020-12 §7.1); none where it pairs with another listed type. -func variantFormat(schema *statement.Schema, st statement.JSONSchemaTypeName, types []statement.JSONSchemaTypeName) string { - format := writtenFormat(schema) - if format == "" || pairs(st, format) { +// variantFormat returns format, the one a type array's node takes, for its +// variant of type typeName among types: the format where it pairs with +// typeName, or with no listed type, since nothing then says which type it +// describes, and a format validates only the instances of the types it is +// defined for (JSON Schema Validation 2020-12 §7.1); none where it pairs with +// another listed type. +func variantFormat(format string, typeName statement.JSONSchemaTypeName, types []statement.JSONSchemaTypeName) string { + if format == "" || pairs(typeName, format) { return format } if slices.ContainsFunc(types, func(jsonSchemaTypeName statement.JSONSchemaTypeName) bool { return pairs(jsonSchemaTypeName, format) }) { @@ -116,23 +199,30 @@ func variantFormat(schema *statement.Schema, st statement.JSONSchemaTypeName, ty return format } -// pairs reports whether format pairs with st: typeformat.Lookup lists the +// pairs reports whether format pairs with typeName: typeformat.Lookup lists the // pairing, or typeformat.LookupEncoded does, as it does byte beside a string. -func pairs(st statement.JSONSchemaTypeName, format string) bool { - key := string(st) + "/" + format +func pairs(typeName statement.JSONSchemaTypeName, format string) bool { + key := string(typeName) + "/" + format _, listed := typeformat.Lookup(key) _, encoded := typeformat.LookupEncoded(key) return listed || encoded } -// statesBounds reports whether schema or one of foldedEntries, read at -// pointer, writes a value bound a reader of the kinds takes holds: one -// ConstraintsOf reads into a field or keeps, as an empty pattern or a keyword -// written null is not. It reads apart from the node, so what it reads is -// reported where hoistScalar reads it. -func statesBounds(loweringContext lowering.Ctx, schema *statement.Schema, foldedEntries []annotation.FoldedAllOfEntry, pointer jsontext.Pointer, takes kindSet) bool { +// statesBounds reports whether schema or one of flattenedEntries, read at +// pointer, writes a value bound a reader of the kinds homes.value names holds: +// one ConstraintsOf reads into a field or keeps, as an empty pattern or a +// keyword written null is not; or one the Scalar keeps verbatim, its value +// text of another kind (homes.otherText). It reads apart from the node, so +// what it reads is reported where hoistScalar reads it. +func statesBounds(loweringContext lowering.Ctx, schema *statement.Schema, flattenedEntries []annotation.FlattenedAllOfEntry, pointer jsontext.Pointer, homes boundHomes) bool { + keepsText := func(conjunctSchema *statement.Schema) bool { + return len(writtenKept(conjunctSchema, homes.otherText)) > 0 + } + if keepsText(schema) || slices.ContainsFunc(flattenedEntries, func(flattenedEntry annotation.FlattenedAllOfEntry) bool { return keepsText(flattenedEntry.Node) }) { + return true + } var kept ir.Unmodeled - cons, _ := ConstraintsOf(loweringContext, &kept, schema, foldedEntries, pointer, takes) + cons, _ := ConstraintsOf(loweringContext, &kept, schema, flattenedEntries, pointer, homes.value) return cons != nil || len(kept) > 0 } diff --git a/compilers/openapi/internal/schema/unevaluated.go b/compilers/openapi/internal/schema/unevaluated.go new file mode 100644 index 000000000..10b0a027f --- /dev/null +++ b/compilers/openapi/internal/schema/unevaluated.go @@ -0,0 +1,350 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "slices" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// maxUnevaluatedScope bounds the schemas an unevaluated keyword's scope is read +// across, and the oneOf branches read for exclusive tags; a scope past it is +// read as meeting an untyped evaluator, so the keyword is kept as written. +const maxUnevaluatedScope = 256 + +// unevaluatedScopeKey keys the run's reading of the scope of the unevaluated +// keywords a schema writes (unevaluatedScopeOf). +type unevaluatedScopeKey struct{ schema *statement.Schema } + +// unevaluatedScope is the scope of the unevaluated keywords a schema writes, +// beside it and through each composition. +type unevaluatedScope struct { + // typed says every evaluator reached is one the IR types; an if, a + // dependentSchemas, a contains, an anyOf or an overlapping oneOf evaluates + // locations it does not, so the keyword is kept verbatim + // (docs/compilers/openapi.md#validation-only). + typed bool + // pastTheFlattening says a schema reached evaluates members a catch-all + // beyond the flattening would read too (evaluatesPastTheFlattening). + pastTheFlattening bool +} + +// unevaluatedScopeOf returns the scope of schema's unevaluated keywords, read +// once a run. +func unevaluatedScopeOf(loweringContext lowering.Ctx, schema *statement.Schema) unevaluatedScope { + return lowering.ReadOncePerRun(loweringContext, unevaluatedScopeKey{schema}, func() unevaluatedScope { + return readUnevaluatedScope(loweringContext, schema) + }) +} + +// readUnevaluatedScope walks what the composition brings, each schema once, the +// first way it is reached, within maxUnevaluatedScope. +func readUnevaluatedScope(loweringContext lowering.Ctx, schema *statement.Schema) unevaluatedScope { + var out unevaluatedScope + seen := map[*statement.Schema]bool{schema: true} + queue := []composedReach{{schema: schema}} + for len(queue) > 0 { + at := queue[0] + queue = queue[1:] + if writesUntypedEvaluator(loweringContext, at) { + return unevaluatedScope{} + } + out.pastTheFlattening = out.pastTheFlattening || at.schema != schema && at.evaluatesPastTheFlattening() + for _, next := range at.brought(loweringContext) { + if seen[next.schema] { + continue + } + if len(seen) == maxUnevaluatedScope { + return unevaluatedScope{} + } + seen[next.schema] = true + queue = append(queue, next) + } + } + out.typed = true + return out +} + +// writesUntypedEvaluator reports whether the schema reached writes an evaluator +// of locations the IR does not type: besides those unevaluatedScope.typed +// names, a dynamic reference expanding nowhere the walk reads, whose target it +// cannot see, or an allOf a cut read or the flattening depth keeps whole. +func writesUntypedEvaluator(loweringContext lowering.Ctx, reached composedReach) bool { + schema := reached.schema + if hasKey(schema, "if") || hasKey(schema, "dependentSchemas") || hasKey(schema, "contains") { + return true + } + if declaresDynamicRef(schema) && loweringContext.Statements().Read(schema).Ref == nil { + if _, expanded := reached.expansion(loweringContext); !expanded { + return true + } + } + if len(schema.AllOf) > 0 { + if decision := decisionOf(loweringContext, schema); decision.outcome == decisionRefinesKeepingAllOfWhole || decision.refinement.cutBy != "" { + return true + } + } + choice := schema.ChoiceKeywords() + return len(choice.AnyOf) > 0 || len(choice.OneOf) > 0 && !oneOfExclusive(loweringContext, choice.OneOf) +} + +// oneOfExclusive reports whether a oneOf's branches exclude each other: each +// pair requires one property whose const or enum tags share no value. A +// discriminator alone does not, as every branch is still validated; more +// branches than maxUnevaluatedScope read as overlapping. +func oneOfExclusive(loweringContext lowering.Ctx, branches []statement.Subschema) bool { + if len(branches) > maxUnevaluatedScope { + return false + } + tags := make([]map[string]map[string]kindSet, len(branches)) + for i, branch := range branches { + schema, _ := branchSchema(loweringContext, branch) + tags[i] = requiredTags(loweringContext, schema) + } + for i := range tags { + for j := i + 1; j < len(tags); j++ { + if !tagsApart(tags[i], tags[j]) { + return false + } + } + } + return true +} + +// branchSchema returns the schema a union branch writes, or the one its chain +// of bare references lands on within maxUnevaluatedScope hops, nil for none, +// and whether a reference brought it. +func branchSchema(loweringContext lowering.Ctx, branch statement.Subschema) (*statement.Schema, bool) { + schemaStatement := loweringContext.Statements().Subschema(branch) + if schemaStatement.Ref == nil { + return schemaStatement.Schema, false + } + for range maxUnevaluatedScope { + target, _ := declaredOf(loweringContext, schemaStatement) + if target == nil { + return nil, true + } + if !writesItsReferenceAlone(target) { + return target.Schema, true + } + schemaStatement = target + } + return nil, true +} + +// writesItsReferenceAlone reports whether schemaStatement is a reference its +// schema writes nothing beside, so what it names is what the reference +// lands on. +func writesItsReferenceAlone(schemaStatement *statement.Statement) bool { + return schemaStatement.Ref != nil && stated(schemaStatement.Schema) && !slices.ContainsFunc(schemaStatement.Keys, func(key statement.Key) bool { return key.Name != refKeyword(schemaStatement) }) +} + +// requiredTags returns, for each property schema requires whose own schema +// writes a const or an enum every reading converts, the values it admits, by +// key (memberSetOf). +func requiredTags(loweringContext lowering.Ctx, schema *statement.Schema) map[string]map[string]kindSet { + if !stated(schema) { + return nil + } + object := schema.ObjectKeywords() + out := map[string]map[string]kindSet{} + for _, property := range object.Properties { + if !slices.Contains(object.Required, property.Name) { + continue + } + tag := loweringContext.Statements().Subschema(property).Schema + if !stated(tag) { + continue + } + key, members := valueSetOf{tag, "enum"}, tag.Enum() + if constant := tag.Const(); constant != nil { + key, members = valueSetOf{tag, "const"}, []*yaml.Node{constant} + } + if set := memberSetOf(loweringContext, key, members); len(members) > 0 && !set.unread { + out[property.Name] = set.values + } + } + return out +} + +// tagsApart reports whether two branches' tags (requiredTags) hold one +// property whose values share none. +func tagsApart(a, b map[string]map[string]kindSet) bool { + for name, values := range a { + other, both := b[name] + if !both { + continue + } + shared := false + for value := range values { + if _, in := other[value]; in { + shared = true + break + } + } + if !shared { + return true + } + } + return false +} + +// closesAfterComposition reports whether schema's live `unevaluatedProperties: +// false` closes its model once composition is resolved, every evaluator it +// reaches being typed. +func closesAfterComposition(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return annotation.ClosesAfterComposition(schema) && unevaluatedScopeOf(loweringContext, schema).typed +} + +// unevaluatedTyped says which of schema's unevaluated keywords built, the node +// it lowered to, holds, so its entry keeps neither. +func unevaluatedTyped(loweringContext lowering.Ctx, schema *statement.Schema, built builtPosition) annotation.Typed { + _, model := built.node.(*ir.Model) + _, list := built.node.(*ir.List) + _, tuple := built.node.(*ir.Tuple) + return annotation.Typed{ + Closure: closureTyped(loweringContext, schema, built), + CatchAll: model && catchAllTyped(loweringContext, schema), + Items: (list || tuple) && unevaluatedItemsTyped(loweringContext, schema), + } +} + +// unevaluatedItemsTyped reports whether the array schema writes lowers its +// unevaluatedItems as the elements past its prefixItems. An items beside it +// evaluates every element and leaves it saying nothing, and one reached through +// a composition is kept, as at the base. +func unevaluatedItemsTyped(loweringContext lowering.Ctx, schema *statement.Schema) bool { + array := schema.ArrayKeywords() + if _, listed := listedItems(schema); listed || array.UnevaluatedItems.SchemaValueForm() == statement.Unwritten || + array.Items.SchemaValueForm() != statement.Unwritten || len(effectiveTypes(schema)) > 1 { + return false + } + return len(loweringContext.Statements().Read(schema).Entries) == 0 && unevaluatedScopeOf(loweringContext, schema).typed +} + +// elementsPast returns the schema typing the array's elements past its +// prefixItems, and its keyword: unevaluatedItems where that is typed +// (unevaluatedItemsTyped), else items. +func elementsPast(loweringContext lowering.Ctx, schema *statement.Schema) (statement.Subschema, string) { + if unevaluatedItemsTyped(loweringContext, schema) { + return schema.ArrayKeywords().UnevaluatedItems, "unevaluatedItems" + } + return itemsSchema(schema), "items" +} + +// catchAllTyped reports whether the model schema lowers to holds its +// unevaluatedProperties schema as its catch-all. An additionalProperties beside +// it leaves it saying nothing, and an evaluator reached past the flattening +// (composedReach.evaluatesPastTheFlattening) reads members the model's own +// catch-all does not. The false form is the closure's. +func catchAllTyped(loweringContext lowering.Ctx, schema *statement.Schema) bool { + form := schema.ObjectKeywords().UnevaluatedProperties.SchemaValueForm() + if form == statement.Unwritten || form.ReadsFalse() || schema.ObjectKeywords().AdditionalProperties.SchemaValueForm() != statement.Unwritten { + return false + } + scope := unevaluatedScopeOf(loweringContext, schema) + return scope.typed && !scope.pastTheFlattening +} + +// composedReach is a schema a composition brings, whether a $ref on the way +// brought it, which the model composes rather than flattens, and whether it +// is an allOf entry beside another conjunct, where no position +// expands a dynamic reference it writes (entryAdmissionIn). +type composedReach struct { + schema *statement.Schema + composed bool + entryApart bool +} + +// expansion returns the statement the dynamic reference r's schema writes +// expands to where r is reached, as its $ref twin lands (dynamicExpansionOf), +// and false where it expands to none; an entry apart expands read alone. +func (r composedReach) expansion(loweringContext lowering.Ctx) (*statement.Statement, bool) { + if r.entryApart { + return nil, false + } + at, expanded := dynamicExpansionOf(loweringContext, loweringContext.Statements().Read(r.schema)) + if !expanded { + return nil, false + } + return loweringContext.Statements().At(at), true +} + +// target returns the statement r's own reference lands on: its $ref's first +// hop (declaredOf), else where a dynamic reference it writes expands to +// (expansion); nil for none. +func (r composedReach) target(loweringContext lowering.Ctx) *statement.Statement { + if target, _ := declaredOf(loweringContext, loweringContext.Statements().Read(r.schema)); target != nil { + return target + } + expanded, _ := r.expansion(loweringContext) + return expanded +} + +// evaluatesPastTheFlattening reports whether the schema r reaches evaluates +// members a catch-all beyond the flattening would read too, as an +// additionalProperties or an unevaluatedProperties evaluates every member its +// own schema leaves. +func (r composedReach) evaluatesPastTheFlattening() bool { + object := r.schema.ObjectKeywords() + if object.AdditionalProperties.SchemaValueForm() != statement.Unwritten || + object.UnevaluatedProperties.SchemaValueForm() != statement.Unwritten { + return true + } + return r.composed && (len(object.PatternProperties) > 0 || annotation.ClosesAfterComposition(r.schema)) +} + +// brought returns the stated schemas r brings, each evaluating the instance +// too: what its reference lands on, its conjuncts and its oneOf branches, each +// composed where r is or a reference brings it. +func (r composedReach) brought(loweringContext lowering.Ctx) []composedReach { + var out []composedReach + if target := r.target(loweringContext); target != nil && stated(target.Schema) { + out = append(out, composedReach{schema: target.Schema, composed: true}) + } + for _, branch := range r.schema.ChoiceKeywords().OneOf { + if next, viaRef := branchSchema(loweringContext, branch); stated(next) { + out = append(out, composedReach{schema: next, composed: r.composed || viaRef}) + } + } + for _, conjunct := range loweringContext.Statements().Read(r.schema).Entries { + next := conjunct.Schema + if conjunct.Ref != nil { + next = nil + if target, _ := declaredOf(loweringContext, loweringContext.Statements().Read(conjunct.Schema)); target != nil { + next = target.Schema + } + } + if stated(next) { + apart := conjunct.Ref == nil && !endsInPlaceChain(loweringContext, r.schema, next) + out = append(out, composedReach{schema: next, composed: r.composed || conjunct.Ref != nil, entryApart: apart}) + } + } + return out +} + +// typeUnevaluatedCatchAll gives model, which schema written at pointer lowers +// to, its unevaluatedProperties schema as the catch-all typing every member +// its flattening declares none for (catchAllTyped), beside the patterns it +// holds. +func typeUnevaluatedCatchAll(loweringContext lowering.Ctx, types *compile.Types, depth int, model *ir.Model, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + if !catchAllTyped(loweringContext, schema) { + return nil + } + ref, diags := Ref(loweringContext, types, depth, loweringContext.Statements().Subschema(schema.ObjectKeywords().UnevaluatedProperties), pointer+ids.Ptr("unevaluatedProperties")) + if model.AdditionalProperties == nil { + model.AdditionalProperties = &ir.AdditionalProperties{} + } + model.AdditionalProperties.Value = &ref + return diags +} diff --git a/compilers/openapi/internal/schema/unevaluated_test.go b/compilers/openapi/internal/schema/unevaluated_test.go new file mode 100644 index 000000000..7a76a9d07 --- /dev/null +++ b/compilers/openapi/internal/schema/unevaluated_test.go @@ -0,0 +1,164 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// manyEntries is an allOf list of n inline entries, each naming one property. +func manyEntries(n int) string { + entries := make([]string, n) + for i := range entries { + entries[i] = "{properties: {p" + strings.Repeat("x", i%3) + ": {type: string}}}" + } + return "[" + strings.Join(entries, ", ") + "]" +} + +// manyBranches is a oneOf list of n branches, each requiring its own tag. +func manyBranches(n int) string { + branches := make([]string, n) + for i := range branches { + branches[i] = "{type: object, properties: {t: {const: v" + strings.Repeat("v", i) + "}}, required: [t]}" + } + return "[" + strings.Join(branches, ", ") + "]" +} + +// TestUnevaluated_TheScopeIsReadToItsBound pins the reading of the scope +// of an unevaluated keyword: a schema two entries bring is read once, and a +// scope past maxUnevaluatedScope schemas, a oneOf's branches among them, meets +// an evaluator the IR does not type, keeping the keyword, as do a oneOf whose +// branches share a tag value, require tags of other names or land on nothing, +// a dynamic reference no position expands, an allOf entry beside another +// conjunct among them, or an allOf kept whole past the flattening depth. One +// expanding is read through, and disjoint tags close their variants. +func TestUnevaluated_TheScopeIsReadToItsBound(t *testing.T) { + t.Parallel() + const body = "type: object, properties: {k: {type: string}}, " + for _, testCase := range []struct { + name, schema string + kept bool + }{ + {"one schema two entries bring", "{allOf: [{$ref: '#/components/schemas/O'}, {$ref: '#/components/schemas/O'}], unevaluatedProperties: false}", false}, + {"a reach at the bound", "{allOf: " + manyEntries(255) + ", unevaluatedProperties: false}", false}, + {"a reach past the bound", "{allOf: " + manyEntries(256) + ", unevaluatedProperties: false}", true}, + {"branches at the bound", "{" + body + "oneOf: " + manyBranches(255) + ", unevaluatedProperties: false}", false}, + {"branches past the bound", "{" + body + "oneOf: " + manyBranches(256) + ", unevaluatedProperties: false}", true}, + {"branches past the tag bound", "{" + body + "oneOf: " + manyBranches(257) + ", unevaluatedProperties: false}", true}, + {"branches sharing a tag value", "{" + body + "oneOf: [{type: object, properties: {t: {enum: [a, c]}}, required: [t]}, " + + "{type: object, properties: {t: {enum: [a]}}, required: [t]}], unevaluatedProperties: false}", true}, + {"branches requiring tags of other names", "{" + body + "oneOf: [{type: object, properties: {t: {const: a}}, required: [t]}, " + + "{type: object, properties: {u: {const: b}, t: false}, required: [u, t]}], unevaluatedProperties: false}", true}, + {"an unexpanded dynamic reference", "{allOf: [{$dynamicRef: '#node'}, {type: object, properties: {k: {type: string}}}], unevaluatedProperties: false}", true}, + {"a reference to an expanding dynamic reference", "{allOf: [{$ref: '#/components/schemas/Dyn'}, {type: object, properties: {k: {type: string}}}], unevaluatedProperties: false}", false}, + {"a dynamic reference expanding in place", "{allOf: [{$ref: '#/components/schemas/InPlace'}, {type: object, properties: {k: {type: string}}}], unevaluatedProperties: false}", false}, + {"an allOf past the flattening depth", "{allOf: [{$ref: '#/components/schemas/Deep'}, {type: object, properties: {k: {type: string}}}], unevaluatedProperties: false}", true}, + {"a branch landing on nothing", "{" + body + "oneOf: [{$ref: '#/components/schemas/Missing'}, " + + "{type: object, properties: {t: {const: b}}, required: [t]}], unevaluatedProperties: false}", true}, + {"a branch whose references loop", "{" + body + "oneOf: [{$ref: '#/components/schemas/Loop'}, " + + "{type: object, properties: {t: {const: b}}, required: [t]}], unevaluatedProperties: false}", true}, + } { + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " O: {type: object, properties: {o: {type: string}}}\n"+ + " Loop: {$ref: '#/components/schemas/Pool'}\n Pool: {$ref: '#/components/schemas/Loop'}\n"+ + " N: {$dynamicAnchor: node, type: object, properties: {n: {type: string}}}\n"+ + " Dyn: {$dynamicRef: '#node'}\n InPlace: {allOf: [{$dynamicRef: '#node'}]}\n"+ + " Deep: "+strings.Repeat("{allOf: [", 40)+"{type: object}"+strings.Repeat("]}", 40)+"\n S: "+testCase.schema+"\n")) + node := typeByName(doc, "S") + require.NotNil(t, node) + _, kept := node.Common().Unmodeled["openapi:unevaluated"] + assert.Equal(t, testCase.kept, kept, "%s keeps the keyword", testCase.name) + }) + } +} + +// TestUnevaluated_ACatchAllReadsTheMembersTheCompositionLeaves pins an +// unevaluatedProperties schema as the catch-all: a composition bringing one +// schema twice is read once, and one whose entry writes an additionalProperties +// or an unevaluatedProperties, inline or through a $ref, each evaluating every +// member its own schema leaves, leaves it saying nothing, kept. +func TestUnevaluated_ACatchAllReadsTheMembersTheCompositionLeaves(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` O: {type: object, properties: {o: {type: string}}} + Open: {type: object, unevaluatedProperties: true} + Twice: {allOf: [{$ref: '#/components/schemas/O'}, {$ref: '#/components/schemas/O'}], unevaluatedProperties: {type: integer}} + Entry: {allOf: [{$ref: '#/components/schemas/O'}, {additionalProperties: {type: string}}], unevaluatedProperties: {type: integer}} + Nested: + type: object + properties: {foo: {type: string}} + allOf: [{unevaluatedProperties: true}] + unevaluatedProperties: {type: string, maxLength: 2} + NestedSchema: {type: object, allOf: [{unevaluatedProperties: {type: string}}], unevaluatedProperties: {type: integer}} + Composed: {allOf: [{$ref: '#/components/schemas/Open'}], unevaluatedProperties: {type: integer}} + Wide: {allOf: `+manyEntries(256)+`, unevaluatedProperties: {type: integer}} +`)) + twice, ok := typeByName(doc, "Twice").(*ir.Model) + require.True(t, ok) + require.NotNil(t, twice.AdditionalProperties) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInteger), twice.AdditionalProperties.Value.Target) + assert.NotContains(t, twice.Unmodeled, "openapi:unevaluated") + for _, name := range []string{"Entry", "Nested", "NestedSchema", "Composed", "Wide"} { + assert.Contains(t, typeByName(doc, name).Common().Unmodeled, "openapi:unevaluated", name) + } +} + +// TestUnevaluated_TheScopeReadsThroughEachReferenceAndBranch pins the scope +// of an unevaluated keyword through a schema writing its reference alone, a +// $ref or an expanded $dynamicRef, in the allOf and the beside spellings and +// as a catch-all, and through the branches of a oneOf, a branch's chain of +// references included: an if the scope lands on there keeps the keyword, as +// written directly; branches requiring disjoint tags through a chain close the +// model as written directly. +func TestUnevaluated_TheScopeReadsThroughEachReferenceAndBranch(t *testing.T) { + t.Parallel() + const ref = "$ref: '#/components/schemas/" + conditional := "{type: object, required: [k], properties: {k: {const: a}, x: {type: string}}, if: {required: [x]}, then: {properties: {w: {type: integer}}}}" + plain := "{type: object, required: [k], properties: {k: {const: a}, x: {type: string}}}" + for name, testCase := range map[string]struct { + branch string + kept map[string]bool + }{ + "an if the reach lands on": {conditional, map[string]bool{ + "AllOfRef": true, "BesideRef": true, "CatchAll": true, "DynamicRef": true, "Direct": true, "Branches": true, "BranchChain": true, + }}, + "disjoint tags": {plain, map[string]bool{"Branches": false, "BranchChain": false}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ""+ + " T: "+testCase.branch+"\n"+ + " TB: {type: object, required: [k], properties: {k: {const: b}, y: {type: string}}}\n"+ + " R: {"+ref+"T'}\n RB: {"+ref+"TB'}\n DR: {$dynamicRef: '#/components/schemas/T'}\n"+ + " Base: {type: object, properties: {z: {type: string}}, oneOf: [{"+ref+"T'}, {"+ref+"TB'}]}\n"+ + " BaseChain: {type: object, properties: {z: {type: string}}, oneOf: [{"+ref+"R'}, {"+ref+"RB'}]}\n"+ + " AllOfRef: {allOf: [{"+ref+"R'}], unevaluatedProperties: false}\n"+ + " BesideRef: {"+ref+"R', unevaluatedProperties: false}\n"+ + " CatchAll: {"+ref+"R', unevaluatedProperties: {type: string}}\n"+ + " DynamicRef: {allOf: [{"+ref+"DR'}], unevaluatedProperties: false}\n"+ + " Direct: {allOf: [{"+ref+"T'}], unevaluatedProperties: false}\n"+ + " Branches: {allOf: [{"+ref+"Base'}], unevaluatedProperties: false}\n"+ + " BranchChain: {allOf: [{"+ref+"BaseChain'}], unevaluatedProperties: false}\n")) + for schema, kept := range testCase.kept { + model, ok := typeByName(doc, schema).(*ir.Model) + require.True(t, ok, schema) + _, keeps := model.Unmodeled["openapi:unevaluated"] + assert.Equal(t, kept, keeps, "%s keeps the keyword", schema) + if kept { + assert.Equal(t, ir.AdditionalUnspecified, model.Additional, "%s closes nothing", schema) + assert.Nil(t, model.AdditionalProperties, "%s types no catch-all", schema) + } else { + assert.Equal(t, ir.AdditionalClosedAfterComposition, model.Additional, "%s closes after composition", schema) + } + } + }) + } +} diff --git a/compilers/openapi/internal/schema/union.go b/compilers/openapi/internal/schema/union.go index e1fbbbdc0..006f77902 100644 --- a/compilers/openapi/internal/schema/union.go +++ b/compilers/openapi/internal/schema/union.go @@ -19,111 +19,306 @@ import ( "github.com/dexpace/morphic/ir" ) -// lowerOneOfAnyOf lowers a oneOf/anyOf schema. A set of one non-null branch X -// beside any number of null branches collapses to nullable X -// (docs/ir/type-graph.md#type-references); a set with no non-null branch at all -// has no X to name, so it lowers as a schema of null alone does -// (lowerNullOnlyUnion); everything else becomes a Union with one -// Variant per non-null branch (oneOf exclusive, anyOf not), never collapsing a -// union into optional fields. The Union, standing where st says, holds the -// value bounds written beside it, as a branch's node, shared by every use of -// the branch, cannot (docs/compilers/openapi.md#constraints). fin finishes it. -func lowerOneOfAnyOf(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, fin finisher, - st stand, -) (ir.TypeRef, []ir.Diagnostic) { - at := st.position(schema) - if inner, ip, ok := nullUnionCollapse(loweringContext, schema, pointer); ok && !pairedPrincipal(loweringContext, st) { - ref, diags := Ref(loweringContext, ts, depth, inner, ip) - // The null branches say the null, so the reference admits it whatever - // the branch it names says, and declares it where theirs or that - // branch's own reference does (unionNullReading). - declared := ref.Nullable && ref.Inferred == "" || valueNulls(loweringContext, schema).union.declared == nullAdmitted - return nullRef(loweringContext, ref.Target, declared, true), append(diags, liftedNullFindings(loweringContext, at, schema, pointer)...) - } - if allNullUnion(loweringContext, at, schema) { - ref, diags := lowerNullOnlyUnion(loweringContext, ts, schema, pointer, fin, st) - if st.of == nil { - // The union of null alone is a conjunct like any other, so a pair - // sharing no value is reported here as where it is not null alone. - diags = append(diags, diagUnionsShareNothing(loweringContext, schema, pointer, unionShape)...) +// lowerOneOfAnyOf lowers a oneOf/anyOf schema, or the union its position's +// conjunction chooses (readLoweredUnion): one non-null branch X beside null +// branches collapses to nullable X (docs/ir/type-graph.md#type-references), +// else it is a Union of one Variant per live non-null branch. The Union holds +// the value bounds written beside it, as a branch's shared node cannot +// (docs/compilers/openapi.md#constraints). +func lowerOneOfAnyOf(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + placement nodePlacement, +) (builtPosition, ir.TypeRef, []ir.Diagnostic) { + at := placement.positionOrSchema(schema) + if leavesNullAlone(loweringContext, at, schema) { + return lowerNullOnlyUnion(loweringContext, types, schema, pointer, placement) + } + if unionCollapses(loweringContext, at, schema) { + inner, innerPointer, _ := nullUnionCollapse(loweringContext, schema, pointer) + ref, diags := Ref(loweringContext, types, depth, inner, innerPointer) + diags = append(diags, liftedNullFindings(loweringContext, at, schema, pointer)...) + if placement.position != nil { + // The position the principal names takes its null, and the + // findings on it, from its own answer. + return builtPosition{}, nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(schema)).ref(loweringContext, ref.Target), diags } - return ref, diags - } - owner, diags := keepingUnread(loweringContext, ts, schema, pointer, dispatch{said: branchesSay(loweringContext, schema, schema)}, fin, st, - func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) { - var diags []ir.Diagnostic - tid := internNode(loweringContext, ts, st.pointer(pointer), func(common ir.TypeCommon) (ir.TypeDef, keySet) { - unionAt := besideUnion(schema, pointer) - unionAt.schema, unionAt.dead = at, pairDeadNulls(loweringContext, at, schema, st) - def, unionDiags := buildUnion(loweringContext, ts, unionAt, common, - func(b *statement.Statement, vptr jsontext.Pointer) ir.TypeRef { - ref, refDiags := Ref(loweringContext, ts, depth, b, vptr) - diags = append(diags, refDiags...) - return ref - }) - diags = append(diags, unionDiags...) - if unionAt.dead != nil { - // The report names an entry's union by the entry it is written on, - // and a dead branch by the null the rest keeps out, not by a body. - reported := unionAt - reported.entry, reported.nulls = st.of != nil, true - diags = append(diags, keepDeadBranches(loweringContext, &def.Unmodeled, at, reported, st.pointer(pointer))...) - } - cons, consDiags := ConstraintsOf(loweringContext, &def.Unmodeled, schema, st.foldedEntries(loweringContext, schema, pointer), pointer, st.takes(loweringContext, schema)) - def.Constraints = cons - diags = append(diags, consDiags...) - read := nodeBoundsRead(schema, st.takes(loweringContext, schema), def.Constraints, def.Unmodeled) - if def.Discriminator != nil { - read |= keyBit("discriminator") - } - return def, read - }, fin) - return tid, 0, diags - }) - ref, nullDiags := schemaNullRef(loweringContext, owner, schema, siteAt(pointer)) - if st.of == nil { - // A principal's conjunction is reported at the schema writing it (refinedDisjoint). - diags = append(diags, diagUnionsShareNothing(loweringContext, schema, pointer, unionShape)...) - } - return ref, slices.Concat(diags, nullDiags, liftedNullFindings(loweringContext, at, schema, pointer)) -} - -// pairDeadNulls marks, by index, each branch of the union schema elects at -// position that is a variant admitting null alone, as a $ref to a schema of -// null alone is, where position elects one union of a oneOf and an anyOf and -// what it writes beside that union, the one passed over among it, keeps null -// out (restForbidsNull): no instance is one of both. It is nil where none is, -// where no variant would live, the pair then sharing no value, which its own -// warning says, or where schema elects no union of a pair -// (docs/compilers/openapi.md#union-beside-structure). -func pairDeadNulls(loweringContext lowering.Ctx, position, schema *statement.Schema, st stand) []bool { - if !writesBothUnions(schema) && !pairedPrincipal(loweringContext, st) { - return nil - } - branches, _, _ := unionBranches(loweringContext, position, schema) - var dead []bool - live := false - for i, b := range branches { - bs := loweringContext.Statements().Subschema(b) - if nullBranch(loweringContext, bs) { + // The reference holds the position's answer of null, the one + // branch's among it (branchesNull). + nullable, nullDiags := schemaNullRef(loweringContext, ref.Target, schema, pointer) + return builtPosition{}, nullable, append(diags, nullDiags...) + } + var buildDiags []ir.Diagnostic + var pendingKeeps annotation.PendingKeeps + conjoined := conjoinedKind(loweringContext, at, schema) + built := internNode(loweringContext, types, placement.pointer(pointer), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + def, read, defDiags := buildPlacedUnion(loweringContext, types, depth, schema, pointer, placement, conjoined, common, &pendingKeeps) + buildDiags = append(buildDiags, defDiags...) + return def, read + }) + restated := keywordsBranchesRestate(loweringContext, schema, schema) + if conjoined != "" { + restated = append(restated, "type") + } + built, unreadDiags := finishUnread(loweringContext, types, schema, pointer, dispatch{restated: restated}, placement, built, 0) + // What the build kept on a principal's node is added as pending keeps after + // what its readers keep, as the settlement orders them. + built.pendingKeeps.AddAll(pendingKeeps) + diags := slices.Concat(buildDiags, unreadDiags) + ref, nullDiags := schemaNullRef(loweringContext, built.id, schema, pointer) + if placement.position == nil && !leavesDead(loweringContext, at, schema) { + // A oneOf and an anyOf sharing no value draw one warning, unless a + // branch of the one chosen is dead, whose own warning names it. + diags = append(diags, diagUnionsShareNothing(loweringContext, at, pointer, unionShape(loweringContext, at))...) + } + return built, ref, slices.Concat(diags, nullDiags, liftedNullFindings(loweringContext, at, schema, pointer)) +} + +// buildPlacedUnion builds the node schema's union, written at pointer, lowers +// to where placement places it, conjoined with kind where that names one, and +// returns it with what it read. What it keeps on a principal's node is added to +// pendingKeeps (builtKeeps). +func buildPlacedUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + placement nodePlacement, kind statement.JSONSchemaTypeName, common ir.TypeCommon, pendingKeeps *annotation.PendingKeeps, +) (ir.TypeDef, keySet, []ir.Diagnostic) { + keeps := builtKeeps{pendingKeeps: pendingKeeps, pointer: pointer, placement: placement} + at := placement.positionOrSchema(schema) + unionSite := unionAtPlacement(loweringContext, schema, pointer, placement) + var diags []ir.Diagnostic + variantType := func(branch *statement.Statement, variantPointer jsontext.Pointer) ir.TypeRef { + ref, refDiags := conjoinedVariant(loweringContext, types, depth, branch, variantPointer, kind, composedBody{schema: at, union: unionSite, + comp: allOfComposition{pointer: placement.pointer(pointer)}}) + diags = append(diags, refDiags...) + return ref + } + variants, exclusive, variantDiags := buildVariants(loweringContext, unionSite, &common, variantType, keeps) + if kind != "" && unionSite.discriminator == nil && len(variants) == 1 { + // One live branch conjoined with the body's kind is the choice the + // union leaves, so the position is that branch's node; the Scalar's + // Base, as the reference to the position, holds what it admits of null. + scalar := &ir.Scalar{TypeCommon: common, Base: new(scalarBase(loweringContext, schema, placement, variants[0].Type.Target))} + cons, read, keptDiags := keepBesidePlacedUnion(loweringContext, schema, unionSite, &scalar.Unmodeled, keeps) + scalar.Constraints = cons + return scalar, read, slices.Concat(diags, variantDiags, keptDiags) + } + union, unionDiags := unionOfVariants(loweringContext, types, unionSite, common, variants, exclusive, keeps) + cons, read, keptDiags := keepBesidePlacedUnion(loweringContext, schema, unionSite, &union.Unmodeled, keeps) + union.Constraints = cons + if union.Discriminator != nil { + read |= keyBit("discriminator") + } + return union, read, slices.Concat(diags, variantDiags, unionDiags, keptDiags) +} + +// keepBesidePlacedUnion keeps on unmodeled, where keeps says, what the node +// schema's union lowered to holds no field for, and returns the value bounds +// written beside the union that the node holds, with what it read. +func keepBesidePlacedUnion(loweringContext lowering.Ctx, schema *statement.Schema, unionSite loweredUnionSite, unmodeled *ir.Unmodeled, keeps builtKeeps, +) (*ir.Constraints, keySet, []ir.Diagnostic) { + placement, pointer := keeps.placement, keeps.pointer + diags := keeps.keep(loweringContext, unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepPlacedUnionDeadBranches(loweringContext, unmodeled, placement.positionOrSchema(schema), unionSite, placement) + }) + if placement.position == nil { + diags = append(diags, keeps.keep(loweringContext, unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepEntryUnions(loweringContext, unmodeled, schema, pointer) + })...) + } + var cons *ir.Constraints + var read keySet + diags = append(diags, keeps.keep(loweringContext, unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + var reports annotation.KeptReports + cons, read, reports = placedUnionBounds(loweringContext, unmodeled, schema, pointer, placement) + return reports + })...) + return cons, read, diags +} + +// placedUnionBounds keeps on unmodeled the bounds written beside schema's +// union, written at pointer, that no field of its node holds, and returns the +// value bounds the node holds, what it read and each kept bound's reports. +func placedUnionBounds(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement, +) (*ir.Constraints, keySet, annotation.KeptReports) { + if rest, conjoined := conjoinedOneRefRest(loweringContext, placement.positionOrSchema(schema)); conjoined { + return oneRefRestBounds(loweringContext, unmodeled, schema, placement.positionOrSchema(schema), placement.pointer(pointer), rest) + } + flattenedEntries := placement.flattenedEntries(loweringContext, schema, pointer) + cons, kept, reports := boundsKept(loweringContext, *unmodeled, schema, flattenedEntries, pointer, placement.homes.value) + text, textReports := heldTextKept(loweringContext, schema, flattenedEntries, pointer, placement.homes) + *unmodeled = annotation.MergeUnmodeled(annotation.MergeUnmodeled(*unmodeled, kept), text) + reports = append(reports, textReports...) + if refinementValue, refined := refinementOf(loweringContext, schema, pointer); refined && placement.position == nil && refinementValue.principal != nil { + // An inline principal beside the union, a body, keeps where it is + // written what the Union holds none of, as no entry keeper adds it. + principal := refinementValue.principal + written := writtenKept(principal.schema.Schema, placement.homes.heldText) + reports = append(reports, textBoundsKept(loweringContext, unmodeled, principal.schema.Schema, written, principal.pointer, placement.homes.root)...) + } + return cons, nodeBoundsRead(schema, placement.homes.value, cons, *unmodeled), reports +} + +// keepEntryUnions keeps on unmodeled, that of the node schema, written at +// pointer, lowered its own union to, each union an inline entry of its allOf +// writes, passed over, as the union reading keeps it (keptUnionReason): what +// a refinement keeps of its entries no refinement of schema keeps here. +func keepEntryUnions(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) annotation.KeptReports { + var reports annotation.KeptReports + for _, passed := range readConjunction(loweringContext, schema).passed() { + if passed.holder == schema { continue } - if kinds, inferred := lowersTo(loweringContext, bs); kinds&^kindNull != 0 || inferred { - live = true + at, key := pointer+passed.rel, string(passed.keyword) + if keptUnionReason(loweringContext, schema, passed) == ir.ReasonValidationOnly { + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", key), keepValidationOnlyKeyword(loweringContext, unmodeled, passed.holder, key, at)...)...) continue } - if dead == nil { - if !restForbidsNull(loweringContext, position, schema) { - return nil - } - dead = make([]bool, len(branches)) + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, passed.holder, key, ir.ReasonDegradedLowering, at) + if kept { + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, + "%s written on this inline entry conjoins with the union beside the allOf, and one Union carries one branch set; "+ + "kept verbatim under Unmodeled", passed.keyword)) } - dead[i] = true + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", key), diags...)...) + } + return reports +} + +// leavesNullAlone reports whether the union schema writes leaves position null +// alone. +func leavesNullAlone(loweringContext lowering.Ctx, position, schema *statement.Schema) bool { + if allNullUnion(loweringContext, position, schema) { + return true + } + return loweredUnionWrittenBy(loweringContext, position, schema) && readLoweredUnion(loweringContext, position).besideRest == unionLeavesNullAlone +} + +// leavesDead reports whether schema writes the union position's conjunction +// chooses and some branch of it is dead (readLoweredUnion): its null is then no +// branch to lift onto a reference. +func leavesDead(loweringContext lowering.Ctx, position, schema *statement.Schema) bool { + return loweredUnionWrittenBy(loweringContext, position, schema) && slices.Contains(readLoweredUnion(loweringContext, position).dead, true) +} + +// conjoinedKind returns the body's one kind the live branches of the union +// schema writes are conjoined with (unionConjoined), and "" for none. +func conjoinedKind(loweringContext lowering.Ctx, position, schema *statement.Schema) statement.JSONSchemaTypeName { + if !loweredUnionWrittenBy(loweringContext, position, schema) { + return "" } - if !live { + if reading := readLoweredUnion(loweringContext, position); reading.besideRest == unionConjoined { + return reading.kind + } + return "" +} + +// conjoinedVariant is the type the variant over branch, a live branch written +// at variantPointer, takes: where branch admits more than kind, branch +// conjoined with kind, a shared primitive where branch writes nothing else, +// else a Scalar minted at the branch's key (composedVariantKey) keeping what +// branch written with kind would keep. +func conjoinedVariant(loweringContext lowering.Ctx, types *compile.Types, depth int, branch *statement.Statement, variantPointer jsontext.Pointer, + kind statement.JSONSchemaTypeName, body composedBody, +) (ir.TypeRef, []ir.Diagnostic) { + if kind == "" || !stated(branch.Schema) { + return Ref(loweringContext, types, depth, branch, variantPointer) + } + if rest, isRef := oneRefRestOf(loweringContext, body.schema); isRef { + return refConjoinedVariant(loweringContext, types, depth, branch, variantPointer, body, rest) + } + if branch.Ref != nil { + return Ref(loweringContext, types, depth, branch, variantPointer) + } + if kinds, _ := lowersTo(loweringContext, branch); kinds&^kindNull&^kindsOfTypeName(kind) == 0 { + return Ref(loweringContext, types, depth, branch, variantPointer) + } + shape := scalarShapeOf(branch.Schema, kind, writtenFormat(branch.Schema)) + root := shapeBoundRoot(branch.Schema, kind, shape) + takes := root.heldTakes(kindsOfTypeName(kind)) + if shape.shared && len(unreadKeys(branch.Schema, scalarTypeRead(branch.Schema)|shape.read|readElsewhere(branch.Schema))) == 0 && + !declaresPositionScoped(loweringContext, branch.Schema, variantPointer) { + return types.PrimitiveRef(shape.base), nil + } + key := composedVariantKey(body, variantPointer) + id := loweringContext.IDs().ComposedType(key) + common := commonFor(loweringContext, id, variantPointer) + common.Provenance = loweringContext.Place().At(key, variantPointer) + enc, diags := scalarEncoding(loweringContext, types, depth, contentConjuncts(branch.Schema, variantPointer, nil), shape.format, false, &common, builtKeeps{}) + if shape.wire != nil { + wireRef := types.PrimitiveRef(*shape.wire) + enc.WireType = &wireRef + } + if *enc == (ir.Encoding{}) { + enc = nil + } + baseRef := types.PrimitiveRef(shape.base) + scalar := &ir.Scalar{TypeCommon: common, Base: &baseRef, Encoding: enc} + diags = append(diags, keepTextBounds(loweringContext, &scalar.Unmodeled, branch.Schema, writtenKept(branch.Schema, root.ownKept()), variantPointer, root)...) + cons, consDiags := ConstraintsOf(loweringContext, &scalar.Unmodeled, branch.Schema, nil, variantPointer, takes) + scalar.Constraints = cons + diags = append(diags, consDiags...) + read := scalarTypeRead(branch.Schema) | shape.read | readElsewhere(branch.Schema) | nodeBoundsRead(branch.Schema, takes, cons, scalar.Unmodeled) + return ir.TypeRef{Target: id}, append(diags, registerConjoined(loweringContext, types, scalar, branch, variantPointer, unreadKeys(branch.Schema, read))...) +} + +// registerConjoined keeps on scalar, the node the branch written at +// variantPointer names as a variant, what branch writes unread, and what +// branch declares, as the branch's own node would hold it, and registers it. +func registerConjoined(loweringContext lowering.Ctx, types *compile.Types, scalar *ir.Scalar, branch *statement.Statement, variantPointer jsontext.Pointer, + unread []string, +) []ir.Diagnostic { + diags := recordUnread(loweringContext, &scalar.Unmodeled, branch.Schema, unread, positionShape(scalar, branch.Schema), variantPointer) + built := builtPosition{node: scalar, id: scalar.ID} + diags = append(diags, declarationOn(loweringContext, branch.Schema, ir.TypeRef{Target: scalar.ID}, variantPointer, annotation.HomeOwnNode, &built)...) + diags = append(diags, settleNode(loweringContext, branch.Schema, ir.TypeRef{Target: scalar.ID}, variantPointer, &built)...) + types.Register(scalar.ID, scalar) + return diags +} + +// keepPlacedUnionDeadBranches keeps on unmodeled, the Union's, what the dead +// branches of unionSite leave: beside a rest holding an object each under its +// own key, else the whole union. +func keepPlacedUnionDeadBranches(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, position *statement.Schema, unionSite loweredUnionSite, placement nodePlacement) annotation.KeptReports { + if unionSite.dead == nil { return nil } - return dead + positionPointer := placement.pointer(unionSite.pointer) + if readLoweredUnion(loweringContext, position).restKinds&kindObject != 0 { + // The report names an entry's union by the entry it is written on. + reported := unionSite + reported.holderIsAllOfEntry = placement.position != nil + reported.deadBranchesAdmitOnlyNull = deadAdmitNullAlone(loweringContext, unionSite) + return keepDeadBranches(loweringContext, unmodeled, position, reported, positionPointer) + } + key := string(unionSite.loweredKeyword(loweringContext)) + _, diags := keepSchemaKeyword(loweringContext, unmodeled, unionSite.holder, key, ir.ReasonDegradedLowering, unionSite.pointer) + return append(annotation.ReportsOf(annotation.EntryKey("", key), diags...), + annotation.ReportsOf("", diagDeadAtUnion(loweringContext, position, positionPointer, false)...)...) +} + +// deadAdmitNullAlone reports whether every dead branch of unionSite admits null +// and nothing else, which the rest of its position keeps out. +func deadAdmitNullAlone(loweringContext lowering.Ctx, unionSite loweredUnionSite) bool { + return !slices.ContainsFunc(deadOf(loweringContext, unionSite, unionSite.dead), func(deadBranchAtValue deadBranchAt) bool { + kinds, _ := lowersTo(loweringContext, deadBranchAtValue.schemaStatement) + return kinds&^kindNull != 0 + }) +} + +// unionAtPlacement is the union schema writes, at pointer, as the position +// placement names lowers it, with the discriminator beside it and the branches +// its conjunction leaves dead; else schema's own, as written alone. +func unionAtPlacement(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement) loweredUnionSite { + position, at := placement.positionOrSchema(schema), placement.pointer(pointer) + loweredUnion, ok := readConjunction(loweringContext, position).loweredUnion() + if !ok || loweredUnion.holder != schema { + out := besideUnion(schema, pointer) + out.schema = position + return out + } + out := conjunctionUnionAt(loweringContext, position, at, loweredUnion) + out.pointer = pointer + if dead := readLoweredUnion(loweringContext, position).dead; slices.Contains(dead, true) { + out.dead = dead + } + return out } // nullUnionCollapse detects a oneOf/anyOf with exactly one non-null branch @@ -133,54 +328,53 @@ func pairDeadNulls(loweringContext lowering.Ctx, position, schema *statement.Sch // // A schema declaring both combinators collapses neither: the co-declared anyOf // conjoins, so the position is not nullable X. The Union keeps the unused -// combinator (preserveUnusedCombinator), which X's shared node cannot. +// combinator (keepUnusedCombinatorReports), which X's shared node cannot. func nullUnionCollapse(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (*statement.Statement, jsontext.Pointer, bool) { if choice := schema.ChoiceKeywords(); len(choice.OneOf) > 0 && len(choice.AnyOf) > 0 { return nil, "", false } - variants, key, _ := unionBranches(loweringContext, schema, schema) + key := loweredKeyword(loweringContext, schema, schema) + variants := key.branchesOf(schema) var nonNull *statement.Statement nonNullIdx, nonNullCount, nullCount := -1, 0, 0 for i, subschema := range variants { - st := loweringContext.Statements().Subschema(subschema) - if nullBranch(loweringContext, st) { + schemaStatement := loweringContext.Statements().Subschema(subschema) + if nullBranch(loweringContext, schemaStatement) { nullCount++ continue } - nonNull, nonNullIdx = st, i + nonNull, nonNullIdx = schemaStatement, i nonNullCount++ } if nullCount == 0 || nonNullCount != 1 { return nil, "", false } - return nonNull, pointer + ids.Ptr(key, strconv.Itoa(nonNullIdx)), true + return nonNull, pointer + ids.Ptr(string(key), strconv.Itoa(nonNullIdx)), true } -// pairedPrincipal reports whether the union lowering where st says is the -// principal of a refinement passing over another entry's union -// (electsOneOfPair), which conjoins with it as a co-declared anyOf does, so it -// collapses no more than one schema writing both does. -func pairedPrincipal(loweringContext lowering.Ctx, st stand) bool { - return st.of != nil && electsOneOfPair(loweringContext, st.of) +// passesOverAnother reports whether the conjunction of position, choosing the +// union holder writes, passes over a union another schema writes, which +// conjoins with the chosen one as a co-declared anyOf does, so it collapses no +// more than one schema writing both +// (docs/compilers/openapi.md#union-beside-structure). +func passesOverAnother(loweringContext lowering.Ctx, position, holder *statement.Schema) bool { + return slices.ContainsFunc(readConjunction(loweringContext, position).passed(), func(union conjunctionUnion) bool { + return union.holder != holder + }) } -// electsOneOfPair reports whether schema refines to an inline entry writing one -// union of a oneOf and an anyOf that schema and its entries write between them -// (writesUnionPair), a body beside them or none, the other passed over. -func electsOneOfPair(loweringContext lowering.Ctx, schema *statement.Schema) bool { - decision := decisionOf(loweringContext, schema) - if !decision.refines || decision.principalAt < 0 { - return false - } - schemaStatement := entryStatement(loweringContext, schema, decision.principalAt) - if schemaStatement.Ref != nil || !declaresUnion(schemaStatement.Schema) || writesBothUnions(schemaStatement.Schema) { - return false - } - return writesUnionPair(schema, allOfEntries(loweringContext, schema, "")) +// entryUnionPassesOverAnother reports whether schema refines to the inline +// entry writing the union its conjunction chooses (unionPrincipal), passing +// over another that schema or another entry writes. +func entryUnionPassesOverAnother(loweringContext lowering.Ctx, schema *statement.Schema) bool { + holder := unionPrincipal(loweringContext, schema) + return holder != nil && slices.ContainsFunc(readConjunction(loweringContext, schema).passed(), func(union conjunctionUnion) bool { + return union.holder != holder + }) } // allNullUnion reports whether every branch of the oneOf/anyOf combinator -// unionBranches elects of schema at position is a null branch (nullBranch). +// schema lowers at position (loweredKeyword) is a null branch (nullBranch). // nullUnionCollapse has no non-null branch to collapse a set like this onto, so // without this check lowerOneOfAnyOf's buildUnion fallback strips every branch // as a null marker and interns a Union with none left — the empty value space @@ -188,7 +382,7 @@ func electsOneOfPair(loweringContext lowering.Ctx, schema *statement.Schema) boo // admits exactly one value, the one a schema of null alone at this position // admits, so lowerOneOfAnyOf lowers it the same way instead. func allNullUnion(loweringContext lowering.Ctx, position, schema *statement.Schema) bool { - variants, _, _ := unionBranches(loweringContext, position, schema) + variants := loweredKeyword(loweringContext, position, schema).branchesOf(schema) return len(variants) > 0 && !slices.ContainsFunc(variants, func(subschema statement.Subschema) bool { return !nullBranch(loweringContext, loweringContext.Statements().Subschema(subschema)) }) @@ -197,204 +391,230 @@ func allNullUnion(loweringContext lowering.Ctx, position, schema *statement.Sche // lowerNullOnlyUnion lowers a oneOf/anyOf every one of whose branches admits // null alone (allNullUnion). One such branch or several admit what a schema of // null alone at this position admits, so the position lowers as one does -// (lowerNullAlone), and a body's lowering keeps unread what the node -// cannot hold. The combinator that produced it, and the other one too when both -// are declared, carries no shape the node's fields could hold, so it is kept +// (lowerNullAlone), and a body's lowering keeps unread what the node cannot +// hold. The combinator that produced it, and the other one too when both are +// declared, carries no shape the node's fields could hold, so it is kept // verbatim under Unmodeled instead of dropped -// (docs/compilers/openapi.md#union-null-only). The node stands where st says. -func lowerNullOnlyUnion(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, fin finisher, - st stand, -) (ir.TypeRef, []ir.Diagnostic) { - var branches finished - owner, diags := keepingUnread(loweringContext, ts, schema, pointer, dispatch{}, - branches.on(func(td ir.TypeDef) []ir.Diagnostic { - return preserveNullOnlyUnion(loweringContext, td, schema, pointer) - }).then(fin), st, - func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic) { - return lowerNullAlone(loweringContext, ts, standingValueSet(schema, pointer, st).finishedBy(fin)), 0, nil +// (docs/compilers/openapi.md#union-null-only). The node is placed where +// placement says. +func lowerNullOnlyUnion(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, + placement nodePlacement, +) (builtPosition, ir.TypeRef, []ir.Diagnostic) { + built := lowerNullAlone(loweringContext, types, placedValueSet(schema, pointer, placement)) + read := built.read + built, diags := finishUnread(loweringContext, types, schema, pointer, dispatch{}, placement, built, 0) + var branchDiags []ir.Diagnostic + if built.node != nil { + keeps := builtKeeps{pendingKeeps: &built.pendingKeeps, pointer: pointer, placement: placement} + branchDiags = keeps.keep(loweringContext, &built.node.Common().Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepNullOnlyUnion(loweringContext, unmodeled, placement.positionOrSchema(schema), schema, pointer) }) - ref, nullDiags := schemaNullRef(loweringContext, owner, schema, siteAt(pointer)) - return ref, slices.Concat(diags, branches.diags, nullDiags, liftedNullFindings(loweringContext, st.position(schema), schema, pointer)) + branchDiags = append(branchDiags, diagWidenedDead(loweringContext, placement.positionOrSchema(schema), placement.pointer(pointer))...) + if placement.position == nil { + branchDiags = append(branchDiags, keepEntriesUnread(loweringContext, built.node, schema, pointer, read)...) + branchDiags = append(branchDiags, keeps.keep(loweringContext, &built.node.Common().Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepEntryUnions(loweringContext, unmodeled, schema, pointer) + })...) + } + } + if position := placement.positionOrSchema(schema); !readLoweredUnion(loweringContext, position).widened { + // A union leaving null alone names its dead branches, as every union + // keeping one does; where the policy widens the conjunction, + // diagWidenedDead names them. + branchDiags = append(branchDiags, diagDeadAtUnion(loweringContext, position, placement.pointer(pointer), false)...) + } + ref, nullDiags := schemaNullRef(loweringContext, built.id, schema, pointer) + return built, ref, slices.Concat(diags, branchDiags, nullDiags, liftedNullFindings(loweringContext, placement.positionOrSchema(schema), schema, pointer)) } -// preserveNullOnlyUnion keeps schema's oneOf/anyOf verbatim under the Unmodeled -// of td, in hand, the node lowerNullOnlyUnion built, an Enum with no member, -// which holds no branch set of its own, and reports what it kept. -func preserveNullOnlyUnion(loweringContext lowering.Ctx, td ir.TypeDef, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - kept, diags := preserveBranchSets(loweringContext, &td.Common().Unmodeled, schema, ir.ReasonDegradedLowering, pointer) - if len(kept) == 0 { +// keepEntriesUnread keeps on typeDef, the null-alone node of schema written at +// pointer, what each inline entry of its allOf writes that typeDef reads none +// of, under the keys they would have beside the allOf, so the spellings keep +// alike. +func keepEntriesUnread(loweringContext lowering.Ctx, typeDef ir.TypeDef, schema *statement.Schema, pointer jsontext.Pointer, read keySet, +) []ir.Diagnostic { + var diags []ir.Diagnostic + var refs []keptRefEntry + for _, entry := range allOfEntries(loweringContext, schema, pointer).entries { + if entry.schema.Ref != nil { + refs = append(refs, keptRefEntry{entry: entry}) + continue + } + if !stated(entry.schema.Schema) { + continue + } + if unread := unreadKeys(entry.schema.Schema, read|readElsewhere(entry.schema.Schema)); len(unread) > 0 { + diags = append(diags, recordUnread(loweringContext, &typeDef.Common().Unmodeled, entry.schema.Schema, unread, positionShape(typeDef, schema), entry.pointer)...) + } + } + if len(refs) == 0 { return diags } - // Both keywords land here when both are declared: buildUnion, and its - // preserveUnusedCombinator, are never reached from this arm, so this is the - // only place either combinator gets a home. - return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, - "every branch admits only the null value, so this position lowered as an enum with no member "+ - "behind a nullable reference; %s kept verbatim under Unmodeled", strings.Join(kept, " and "))) + _, refDiags := keepRefConjuncts(loweringContext, &typeDef.Common().Unmodeled, refs, pointer) + return append(diags, refDiags...) } -// preserveBranchSets stores schema's declared oneOf/anyOf verbatim under -// unmodeled, in keyword order, reporting one it cannot convert. +// keepNullOnlyUnion keeps schema's oneOf/anyOf verbatim on unmodeled, for the +// node lowerNullOnlyUnion built, which holds no branch set of its own, and +// reports why as position's union reading says. +func keepNullOnlyUnion(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, position, schema *statement.Schema, pointer jsontext.Pointer, +) annotation.KeptReports { + kept, reports := keepBranchSets(loweringContext, unmodeled, schema, ir.ReasonDegradedLowering, pointer) + if len(kept) == 0 { + return reports + } + // Both keywords land here when both are declared: buildUnion, and its + // keepUnusedCombinatorReports, are never reached from this arm, so this is the + // only place either combinator gets a home. + why := "every branch admits only the null value" + reading := readLoweredUnion(loweringContext, position) + _, lifted := reading.liftedBranch() + switch { + case lifted: + why = "no branch shares a value with the rest of this schema, but the nullable-inference policy reads its null " + + "branch as admitting null over the whole position" + case reading.widened: + why = "no branch shares a value with the rest of this schema, but the nullable-inference policy reads its " + + "nullable: true as admitting null over the whole position" + case slices.Contains(reading.dead, true): + why = "no branch shares a value with the rest of this schema but null" + } + return append(reports, annotation.ReportsOf(annotation.EntryKey("", kept[0]), loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + "%s, so this position lowered as an enum with no member behind a nullable reference; %s kept verbatim under Unmodeled", + why, strings.Join(kept, " and ")))...) +} + +// keepBranchSets stores schema's declared oneOf/anyOf verbatim under +// unmodeled, in keyword order, reporting one it cannot convert, each report +// paired with its keyword's key. // ir.ReasonValidationOnly routes each through the validation-only -// keyword-family reporting (annotation.PreserveValidationOnlyKeyword) and +// keyword-family reporting (annotation.KeepValidationOnlyKeyword) and // returns no keywords. Every other reason keeps each plainly -// (annotation.PreserveSchemaKeyword) and returns the keywords kept, so a caller +// (annotation.KeepSchemaKeyword) and returns the keywords kept, so a caller // with a message of its own knows what to name. // -// preserveUnionSiblingsAt and preserveNullOnlyUnion share this loop: they keep +// keepUnionSiblingsAt and keepNullOnlyUnion share this loop: they keep // the same keywords because the node they attach to has no branch set of its // own, and differ only in the sentence that explains why. -func preserveBranchSets(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, reason ir.UnmodeledReason, pointer jsontext.Pointer) ([]string, []ir.Diagnostic) { - var diags []ir.Diagnostic +func keepBranchSets(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, reason ir.UnmodeledReason, pointer jsontext.Pointer, +) ([]string, annotation.KeptReports) { + var reports annotation.KeptReports var kept []string - for _, kw := range []string{"oneOf", "anyOf"} { + for _, union := range unionKeywords { + keyword := string(union) if reason == ir.ReasonValidationOnly { - diags = append(diags, preserveValidationOnlyKeyword(loweringContext, unmodeled, schema, kw, pointer)...) + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), keepValidationOnlyUnion(loweringContext, unmodeled, schema, keyword, pointer)...)...) continue } - ok, keptDiags := preserveSchemaKeyword(loweringContext, unmodeled, schema, kw, reason, pointer) - diags = append(diags, keptDiags...) + ok, keptDiags := keepSchemaKeyword(loweringContext, unmodeled, schema, keyword, reason, pointer) + reports = append(reports, annotation.ReportsOf(annotation.EntryKey("", keyword), keptDiags...)...) if ok { - kept = append(kept, kw) + kept = append(kept, keyword) } } - return kept, diags -} - -// unionBranches returns the branches of the combinator holder elects at the -// position written by position, holder itself or the schema writing the allOf -// holding it, the keyword's name (for pointers), and whether it is exclusive. -// -// Of both, the oneOf wins unless only the anyOf declares shape against the -// position (anyOfElected), so every caller owns the set it passed over: -// buildUnion keeps it on the Union (preserveUnusedCombinator), nullUnionCollapse -// declines to collapse past it, and the verbatim lowering keeps both keywords -// (preserveUnionSiblingsAt). Reading the preference as one only that last -// lowering could reach is what dropped the anyOf in silence (GitHub #35). -func unionBranches(loweringContext lowering.Ctx, position, holder *statement.Schema) ([]statement.Subschema, string, bool) { - choice := holder.ChoiceKeywords() - if len(choice.OneOf) > 0 && (len(choice.AnyOf) == 0 || !anyOfElected(loweringContext, position, holder)) { - return choice.OneOf, "oneOf", true - } - return choice.AnyOf, "anyOf", false + return kept, reports } -// unionElectionOf keys what anyOfElected read of a holder at a position. -type unionElectionOf struct { +// anyOfChosenKey keys what anyOfChosen read of a holder at a position. +type anyOfChosenKey struct { position, holder *statement.Schema } -// anyOfElected reports whether holder, writing a oneOf and an anyOf, elects its -// anyOf at position: its branches declare shape against the position and the -// oneOf's do not, so the oneOf only narrows what the position declares and -// types nothing (docs/compilers/openapi.md#competing-keywords). Read once a run, -// as every reader of the union asks. -func anyOfElected(loweringContext lowering.Ctx, position, holder *statement.Schema) bool { - return lowering.ReadOncePerRun(loweringContext, unionElectionOf{position, holder}, func() bool { - choice := holder.ChoiceKeywords() - return !setsDeclareShape(loweringContext, position, holder, choice.OneOf) && setsDeclareShape(loweringContext, position, holder, choice.AnyOf) +// anyOfChosen reports whether holder, writing a oneOf and an anyOf, chooses its +// anyOf at position, as position's conjunction chooses. Every reader of the +// union asks, so it is read once a run. +func anyOfChosen(loweringContext lowering.Ctx, position, holder *statement.Schema) bool { + return lowering.ReadOncePerRun(loweringContext, anyOfChosenKey{position, holder}, func() bool { + if loweredUnion, ok := readConjunction(loweringContext, position).loweredUnion(); ok && loweredUnion.holder == holder { + return loweredUnion.keyword == anyOfKeyword + } + unions := unionsOf(holder, "") + at, lowersUnion := chooseLoweredUnion(loweringContext, position, unions) + return lowersUnion && unions[at].keyword == anyOfKeyword }) } -// passedOver returns the branch set unionBranches passes over in holder at -// position, a conjunct of the rest of that position, and its keyword: none -// where holder writes one union. -func passedOver(loweringContext lowering.Ctx, position, holder *statement.Schema) ([]statement.Subschema, string) { +// passedOver returns the keyword of the union holder passes over at position, +// a conjunct of the rest of that position (loweredKeyword), and false where +// holder writes one union. +func passedOver(loweringContext lowering.Ctx, position, holder *statement.Schema) (unionKeyword, bool) { choice := holder.ChoiceKeywords() if len(choice.OneOf) == 0 || len(choice.AnyOf) == 0 { - return nil, "" - } - if _, key, _ := unionBranches(loweringContext, position, holder); key == "oneOf" { - return choice.AnyOf, "anyOf" + return "", false } - return choice.OneOf, "oneOf" + return loweredKeyword(loweringContext, position, holder).other(), true +} + +// loweredKeyword is loweredKeyword for u's holder at its position. +func (u loweredUnionSite) loweredKeyword(loweringContext lowering.Ctx) unionKeyword { + return loweredKeyword(loweringContext, u.schema, u.holder) } -// branches is unionBranches for u's holder at its position. -func (u unionAt) branches(loweringContext lowering.Ctx) ([]statement.Subschema, string, bool) { - return unionBranches(loweringContext, u.schema, u.holder) +// branches returns the branches of the union u's holder lowers at its +// position (loweredKeyword). +func (u loweredUnionSite) branches(loweringContext lowering.Ctx) []statement.Subschema { + return u.loweredKeyword(loweringContext).branchesOf(u.holder) } -// restKeepsNull returns whether what unionAtValue's position writes but -// unionAtValue's own union keeps null out (restForbidsNull), read on first -// asking: most unions hold no variant admitting null. -func restKeepsNull(loweringContext lowering.Ctx, unionAtValue unionAt) func() bool { +// restKeepsNull returns whether what unionSite's position writes but +// unionSite's own union keeps null out (restNull), read on first asking: +// most unions hold no variant admitting null. +func restKeepsNull(loweringContext lowering.Ctx, unionSite loweredUnionSite) func() bool { var read, forbids bool return func() bool { if !read { - read, forbids = true, restForbidsNull(loweringContext, unionAtValue.schema, unionAtValue.holder) + read, forbids = true, restNull(loweringContext, unionSite.schema, unionSite.holder).forbids(loweringContext) } return forbids } } -// restForbidsNull reports whether body keeps null out by what it writes but -// the union of holder, the union holder passes over among it, as -// bodyAdmitsNull reads that rest: a rest saying nothing of null keeps none -// out, and a passed-over union read past the budget decides nothing. -func restForbidsNull(loweringContext lowering.Ctx, body, holder *statement.Schema) bool { - nulls := newNulls(loweringContext) - nulls.variants, nulls.rest = true, holder - if nulls.conjunct(loweringContext.Statements().Read(body), nullSite{}).forbids(loweringContext) { - return true - } - passed, _ := passedOver(loweringContext, body, holder) - if passed == nil { - return false - } - nullsValue := newNulls(loweringContext) - nullsValue.variants = true - return nullsValue.branchesNull(passed).forbids(loweringContext) && !nullsValue.conjuncts.Exhausted() -} - -// otherCombinator names each union keyword's counterpart, so the branch set -// unionBranches passed over is read off the choice it returned rather than -// restated beside it. -var otherCombinator = map[string]string{"oneOf": "anyOf", "anyOf": "oneOf"} - -// preserveUnusedCombinator keeps the branch set unionBranches passed over in -// unionAtValue's holder verbatim on the Union the position lowers to, and +// keepUnusedCombinatorReports keeps the branch set loweredKeyword passed over in +// unionSite's holder verbatim on the Union the position lowers to, and // reports it. A holder declaring only one combinator passes over nothing and is // left alone. // // A schema writing both conjoins them, but one ir.Union carries one branch set, -// so the other stays recoverable beside the elected one +// so the other stays recoverable beside the chosen one // (docs/compilers/openapi.md#competing-keywords), as validation logic where // its branches declare no shape against the schema at the position, an entry -// holding both as much as one written beside the allOf. Beside a body the union -// distributes across, each variant keeps it instead (buildComposedVariant). -func preserveUnusedCombinator(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, unionAtValue unionAt, won string) []ir.Diagnostic { - choice := unionAtValue.holder.ChoiceKeywords() +// holding both as much as one written beside the allOf, and beside a body the +// union distributes across as anywhere: the Union keeps it once. +func keepUnusedCombinatorReports(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, unionSite loweredUnionSite, chosen unionKeyword) annotation.KeptReports { + choice := unionSite.holder.ChoiceKeywords() if len(choice.OneOf) == 0 || len(choice.AnyOf) == 0 { return nil } - unused, set := otherCombinator[won], choice.OneOf - if unused == "anyOf" { - set = choice.AnyOf - } - if !setsDeclareShape(loweringContext, unionAtValue.schema, unionAtValue.holder, set) { + unused := chosen.other() + return annotation.ReportsOf(annotation.EntryKey("", string(unused)), keepUnusedCombinator(loweringContext, unmodeled, unionSite, chosen, unused)...) +} + +// keepUnusedCombinator is keepUnusedCombinatorReports's keeping of unused, the +// combinator the union unionSite writes beside chosen, its lowered one. +func keepUnusedCombinator(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, unionSite loweredUnionSite, chosen, unused unionKeyword) []ir.Diagnostic { + if !setsDeclareShape(loweringContext, unionSite.schema, unused.branchesOf(unionSite.holder)) { // Branches narrowing only what the position declares are validation - // logic, as the same union on an entry of its own is (entryUnionReason). - return preserveValidationOnlyKeyword(loweringContext, unmodeled, unionAtValue.holder, unused, unionAtValue.at) + // logic, as the same union on an entry of its own is (keptUnionReason). + return keepValidationOnlyKeyword(loweringContext, unmodeled, unionSite.holder, string(unused), unionSite.pointer) } - kept, diags := preserveSchemaKeyword(loweringContext, unmodeled, unionAtValue.holder, unused, ir.ReasonDegradedLowering, unionAtValue.at) + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, unionSite.holder, string(unused), ir.ReasonDegradedLowering, unionSite.pointer) if !kept { return diags } - return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, unionAtValue.at, + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, unionSite.pointer, "oneOf and anyOf are both declared here and conjoin, and one Union carries one "+ "branch set; this position lowered as its %s, with %s kept verbatim under Unmodeled", - won, unused)) + chosen, unused)) } // variantTypeFunc lowers one union branch to the type its variant refers to. It // is a parameter so the distributed lowering can conjoin the sibling composition // into each branch while sharing every other rule about union shape — null-branch // stripping, variant hints, exclusivity, pointer derivation. -type variantTypeFunc func(b *statement.Statement, vptr jsontext.Pointer) ir.TypeRef +type variantTypeFunc func(branch *statement.Statement, variantPointer jsontext.Pointer) ir.TypeRef -// buildUnion assembles the Union node for the union unionAtValue, attaching the -// discriminator standing with it, where one does, with the routes it implies +// buildUnion assembles the Union node for the union unionSite, attaching the +// discriminator beside it, where one does, with the routes it implies // (spellImplicitRoutes). common is already built by the caller (internNode), so // buildUnion needs no hint of its own to build one, and it places the union. // @@ -402,23 +622,65 @@ type variantTypeFunc func(b *statement.Statement, vptr jsontext.Pointer) ir.Type // them (indexBranches). A union the discriminator routes is WireTagged, an // anyOf as much as a oneOf: the tag property's value names its variant // (docs/ir/unions.md). -func buildUnion(loweringContext lowering.Ctx, ts *compile.Types, unionAtValue unionAt, common ir.TypeCommon, variantType variantTypeFunc, +func buildUnion(loweringContext lowering.Ctx, types *compile.Types, unionSite loweredUnionSite, common ir.TypeCommon, variantType variantTypeFunc, ) (*ir.Union, []ir.Diagnostic) { - branches, key, exclusive := unionAtValue.branches(loweringContext) - var diags []ir.Diagnostic - if !unionAtValue.distributed { - diags = preserveUnusedCombinator(loweringContext, &common.Unmodeled, unionAtValue, key) + variants, exclusive, diags := buildVariants(loweringContext, unionSite, &common, variantType, builtKeeps{}) + node, nodeDiags := unionOfVariants(loweringContext, types, unionSite, common, variants, exclusive, builtKeeps{}) + return node, append(diags, nodeDiags...) +} + +// unionOfVariants is the Union of variants, the union unionSite's, exclusive +// where it says, with the discriminator beside it (buildUnion), keeping +// where keeps says what of the discriminator reaches no field. +func unionOfVariants(loweringContext lowering.Ctx, types *compile.Types, unionSite loweredUnionSite, common ir.TypeCommon, variants []ir.Variant, exclusive bool, + keeps builtKeeps, +) (*ir.Union, []ir.Diagnostic) { + node := &ir.Union{ + TypeCommon: common, + Variants: variants, + Exclusive: exclusive, + Closed: true, + } + var branchIndexValue *branchIndex + if unionSite.discriminator != nil { + branchIndexValue = indexBranches(loweringContext, unionSite, variants) } - diags = append(diags, recordNullBranches(loweringContext, &common.Unmodeled, nullBranchKeeps(loweringContext, unionAtValue.schema, unionAtValue.holder, unionAtValue.at))...) + disc, diags := lowerDiscriminator(loweringContext, types, unionSite.discriminator, unionSite.discriminatorPointer, nil, branchIndexValue) + node.Discriminator = disc + node.WireTagged = disc != nil + diags = append(diags, keeps.keep(loweringContext, &node.Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepEntryDiscriminatorKeys(loweringContext, unmodeled, node.Provenance.Pointer, unionSite) + })...) + diags = append(diags, keeps.keep(loweringContext, &node.Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepDeadRoutes(loweringContext, unmodeled, node, unionSite) + })...) + diags = append(diags, spellImplicitRoutes(loweringContext, unionSite, node, common.Provenance.Pointer)...) + deferUnionTags(loweringContext, types, unionSite, node, common.Provenance.Pointer) + return node, diags +} + +// buildVariants lowers the variants of the union unionSite, each by +// variantType, keeping on common, where keeps says, what the union says beside +// them. It returns the variants and whether they exclude each other. +func buildVariants(loweringContext lowering.Ctx, unionSite loweredUnionSite, common *ir.TypeCommon, variantType variantTypeFunc, keeps builtKeeps, +) ([]ir.Variant, bool, []ir.Diagnostic) { + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) + diags := keeps.keep(loweringContext, &common.Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepUnusedCombinatorReports(loweringContext, unmodeled, unionSite, key) + }) + diags = append(diags, keeps.keep(loweringContext, &common.Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return recordNullBranches(loweringContext, unmodeled, liveNullBranchKeeps(loweringContext, unionSite)) + })...) variants := make([]ir.Variant, 0, len(branches)) - keepsNull := restKeepsNull(loweringContext, unionAtValue) - for i, b := range branches { - st := loweringContext.Statements().Subschema(b) - if !unionAtValue.variantBranch(loweringContext, i, st) { + keepsNull := restKeepsNull(loweringContext, unionSite) + for i, branch := range branches { + schemaStatement := loweringContext.Statements().Subschema(branch) + if !unionSite.variantBranch(loweringContext, i, schemaStatement) { continue // a null branch lifts to the enclosing ref's Nullable bit; a dead one is kept } - vptr := unionAtValue.at + ids.Ptr(key, strconv.Itoa(i)) - typeRef := variantType(st, vptr) + variantPointer := unionSite.pointer + ids.Ptr(string(key), strconv.Itoa(i)) + typeRef := variantType(schemaStatement, variantPointer) if typeRef.Nullable && keepsNull() { // A null is shared only where every conjunct may admit it, so a // rest keeping it out leaves the variant none, its other values @@ -426,229 +688,162 @@ func buildUnion(loweringContext lowering.Ctx, ts *compile.Types, unionAtValue un typeRef.Nullable, typeRef.Inferred = false, "" } variants = append(variants, ir.Variant{ - Name: compile.NamingHint(variantHint(loweringContext, st, vptr)), + Name: compile.NamingHint(variantHint(loweringContext, schemaStatement, variantPointer)), Type: typeRef, }) } - node := &ir.Union{ - TypeCommon: common, - Variants: variants, - Exclusive: exclusive, - Closed: true, - } - var branchIndexValue *branchIndex - if unionAtValue.disc != nil { - branchIndexValue = indexBranches(loweringContext, unionAtValue, variants) + return variants, key.Exclusive(), diags +} + +// liveNullBranchKeeps is nullBranchKeeps for the union unionSite, but for +// a null branch it marks dead, no null of the union, which its dead branches' +// keeping holds (keepPlacedUnionDeadBranches). +func liveNullBranchKeeps(loweringContext lowering.Ctx, unionSite loweredUnionSite) []keptNullBranch { + kept := nullBranchKeeps(loweringContext, unionSite.schema, unionSite.holder, unionSite.pointer) + if unionSite.dead == nil { + return kept } - disc, discDiags := lowerDiscriminator(loweringContext, ts, unionAtValue.disc, unionAtValue.discAt, nil, branchIndexValue) - node.Discriminator = disc - node.WireTagged = disc != nil - diags = append(diags, discDiags...) - diags = append(diags, keepEntryDiscriminatorKeys(loweringContext, node, unionAtValue)...) - diags = append(diags, keepDeadRoutes(loweringContext, node, unionAtValue)...) - diags = append(diags, spellImplicitRoutes(loweringContext, unionAtValue, node, common.Provenance.Pointer)...) - deferUnionTags(loweringContext, ts, unionAtValue, node, common.Provenance.Pointer) - return node, diags + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) + return slices.DeleteFunc(kept, func(branch keptNullBranch) bool { + index := slices.IndexFunc(branches, func(candidate statement.Subschema) bool { + return unionSite.pointer+ids.Ptr(string(key), strconv.Itoa(candidate.Index)) == branch.at + }) + return index >= 0 && unionSite.dead[index] + }) } -// keepEntryDiscriminatorKeys keeps on n, the Union of u, what the discriminator -// u's allOf entry writes says that reaches no field: its extensions and the -// keys OpenAPI defines for no Discriminator Object. A schema's own are read onto -// its position's node (annotation.Read), and an entry has no node, so they ride -// on the node holding the discriminator, scoped by their path from it where they -// lie beneath it (annotation.SchemaExtensions). -func keepEntryDiscriminatorKeys(loweringContext lowering.Ctx, union *ir.Union, unionAtValue unionAt) []ir.Diagnostic { - if !unionAtValue.entry || unionAtValue.disc == nil || unionAtValue.discAt != unionAtValue.at { +// keepEntryDiscriminatorKeys keeps on unmodeled, the Union of unionSite at +// pointer, what the discriminator unionSite's allOf entry writes says that +// reaches no field: its extensions and the keys OpenAPI defines for no +// Discriminator Object, each report paired with its key. A schema's own are +// read onto its position's node (annotation.Read), and an entry has no node, so +// they ride on the node holding the discriminator, scoped by their path from it +// where they lie beneath it (annotation.SchemaExtensions). An entry the +// position lowers from is read onto its node as a schema's own is, so none is +// kept here. +func keepEntryDiscriminatorKeys(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, pointer jsontext.Pointer, unionSite loweredUnionSite) annotation.KeptReports { + if !unionSite.holderIsAllOfEntry || unionSite.discriminator == nil || unionSite.discriminatorPointer != unionSite.pointer || + unionLoweredAlone(loweringContext, unionSite.schema, unionSite.holder) { return nil } - owner, scope := discriminatorScope(unionAtValue, union.Provenance.Pointer) - // unionAtValue.disc is the holder's, as discAt is at. - kept, diags := annotation.SchemaExtensions(unionAtValue.disc.Extensions, loweringContext.Place(), owner, scope) - diags = append(diags, annotation.UnknownKeysNamed(&kept, unionAtValue.disc.Unknown, unionAtValue.disc.Node, loweringContext.Place(), owner, scope)...) - union.Unmodeled = annotation.MergeUnmodeled(union.Unmodeled, kept) - return diags + owner, scope := discriminatorScope(unionSite, pointer) + // unionSite.discriminator is the holder's, as discriminatorPointer is + // unionSite.pointer. + kept, diags := annotation.SchemaExtensions(unionSite.discriminator.Extensions, loweringContext.Place(), owner, scope) + reports := annotation.ReportsOf("", diags...) + reports = append(reports, annotation.UnknownKeysNamed(&kept, unionSite.discriminator.Unknown, unionSite.discriminator.Node, loweringContext.Place(), owner, scope)...) + *unmodeled = annotation.MergeUnmodeled(*unmodeled, kept) + return reports } -// discriminatorScope is where the discriminator standing with unionAtValue is +// discriminatorScope is where the discriminator beside unionSite is // written, and the scope what a node at pointer keeps of it is keyed by: its // path beneath pointer, or `discriminator` where it is not beneath it. -func discriminatorScope(unionAtValue unionAt, pointer jsontext.Pointer) (jsontext.Pointer, string) { - owner := unionAtValue.discAt + ids.Ptr("discriminator") +func discriminatorScope(unionSite loweredUnionSite, pointer jsontext.Pointer) (jsontext.Pointer, string) { + owner := unionSite.discriminatorPointer + ids.Ptr("discriminator") if rest, beneath := strings.CutPrefix(string(owner), string(pointer)+"/"); beneath { return owner, rest } return owner, "discriminator" } -// unionAt is a union a position lowers: the oneOf or anyOf, whichever -// unionBranches elects, that holder writes at the pointer at, and the -// discriminator standing with it, written by the schema at discAt. holder is the -// schema written at the position, or an inline entry of its allOf, which JSON -// Schema conjoins with the rest of the composition as it would one written +// loweredUnionSite is a union a position lowers: the oneOf or anyOf, whichever +// loweredKeyword chooses, that holder writes at pointer, and the discriminator +// beside it, written by the schema at discriminatorPointer. holder is +// the schema written at the position, or an inline entry of its allOf, which +// JSON Schema conjoins with the rest of the composition as it would one written // beside it (docs/compilers/openapi.md#union-beside-structure). -type unionAt struct { - holder *statement.Schema - at jsontext.Pointer +type loweredUnionSite struct { + holder *statement.Schema + pointer jsontext.Pointer // schema is the schema written at the position, holder itself or the one - // writing the allOf holding it: what each branch the union elects or passes + // writing the allOf holding it: what each branch the union chooses or passes // over conjoins with. schema *statement.Schema - // disc is the discriminator the union is routed by, nil for none: one written - // beside it, else one beside the allOf holding its entry (entryUnion). - disc *statement.Discriminator - discAt jsontext.Pointer - // entry marks a holder that is an allOf entry, no schema at a position. - entry bool - // nulls marks a union whose dead branches admit nothing but a null the - // rest of the position keeps out (pairDeadNulls), beside any body. - nulls bool + // discriminator is the discriminator the union is routed by, nil for none: one + // written beside it, else one beside the allOf holding its entry (entryUnion). + discriminator *statement.Discriminator + discriminatorPointer jsontext.Pointer + // holderIsAllOfEntry marks a holder that is an allOf entry, no schema at a + // position. + holderIsAllOfEntry bool + // deadBranchesAdmitOnlyNull marks a union whose dead branches admit nothing but + // a null the rest of the position keeps out (deadAdmitNullAlone), beside any + // body. + deadBranchesAdmitOnlyNull bool // distributed marks a union a body is distributed across, each of whose - // variants keeps the combinator it does not elect (buildComposedVariant). + // variants keeps the combinator it does not choose (buildComposedVariant). distributed bool // dead marks, by branch index, each branch of a distributed union no // instance of its body satisfies (deadBranches), which is no variant; nil // for a union distributing nothing. dead []bool - // deadRoutes are the routes disc takes to a dead branch (deadRoutesOf), - // which route to no variant. + // deadRoutes are the routes discriminator takes to a dead branch + // (deadRoutesOf), which route to no variant. deadRoutes []deadRoute } -// variantBranch reports whether st, the branch of u at index i, is a variant -// of the Union u lowers to: every branch but a null one, which lifts to the -// reference's Nullable, and one no instance of the body u is distributed over -// satisfies. Each reader aligning branches with variants asks it. -func (u unionAt) variantBranch(loweringContext lowering.Ctx, i int, st *statement.Statement) bool { - return !nullBranch(loweringContext, st) && (u.dead == nil || !u.dead[i]) +// variantBranch reports whether schemaStatement, the branch of u at index i, is +// a variant of the Union u lowers to: every branch but a null one, which lifts +// to the reference's Nullable, and one no instance of the body u is distributed +// over satisfies. Each reader aligning branches with variants asks it. +func (u loweredUnionSite) variantBranch(loweringContext lowering.Ctx, i int, schemaStatement *statement.Statement) bool { + return !nullBranch(loweringContext, schemaStatement) && (u.dead == nil || !u.dead[i]) } // besideUnion is the union schema, written at pointer, writes itself, with the // discriminator written beside it. -func besideUnion(schema *statement.Schema, pointer jsontext.Pointer) unionAt { - return unionAt{holder: schema, at: pointer, schema: schema, disc: schema.Discriminator(), discAt: pointer} -} - -// entryUnionOf keys what entryUnion read of one schema. -type entryUnionOf struct { - schema *statement.Schema -} - -// entryUnionIndex is where in a schema's flattened allOf the entry whose -// union it conjoins is, where one is. -type entryUnionIndex struct { - index int - ok bool -} - -// entryUnion returns the union an inline entry of s's allOf writes that s, -// written at pointer, conjoins with the rest of its composition, as it would -// the same union written beside the allOf -// (docs/compilers/openapi.md#union-beside-structure), with the discriminator -// written on the entry, else beside the allOf, and how the position lowers it: -// unionSharesNoKind where the unions its entries write share no kind with the -// rest (unionApart), else as classifyConjoined says. ok is false where the -// union stays with its entry, as for the base of a hierarchy the -// discriminator routes. -func entryUnion(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (unionAt, unionLowering, bool) { - at := entryUnionIndexOf(loweringContext, schema) - if !at.ok { - return unionAt{}, 0, false - } - comp := allOfEntries(loweringContext, schema, pointer) - entry := comp.entries[at.index] - unionAtValue := unionAt{holder: entry.schema.Schema, at: entry.pointer, schema: schema, disc: schema.Discriminator(), discAt: pointer, entry: true} - if discriminator := unionAtValue.holder.Discriminator(); discriminator != nil { - unionAtValue.disc, unionAtValue.discAt = discriminator, entry.pointer - } - if unionApart(loweringContext, schema, comp, at.index) { - return unionAtValue, unionSharesNoKind, false - } - how := classifyConjoined(loweringContext, schema, unionAtValue, pointer) - return unionAtValue, how, how == unionDistributed || how == unionRoutedSubtype -} - -// entryUnionIndexOf returns findEntryUnion's reading of s, read once a run, as -// every reader of a position s is written at, and of a hierarchy s is the base -// of, asks. -func entryUnionIndexOf(loweringContext lowering.Ctx, schema *statement.Schema) entryUnionIndex { - return lowering.ReadOncePerRun(loweringContext, entryUnionOf{schema}, func() entryUnionIndex { return findEntryUnion(loweringContext, schema) }) -} - -// findEntryUnion is entryUnion's reading of s alone: where s lowers its -// allOf, composing, not refining, the entry whose union declares shape -// against s without any entry's union, within the flattening depth, each $ref -// branch naming a referent. Of several, the one writing a oneOf, each other -// kept on every variant; two writing a oneOf, or several anyOfs, leave none, -// in any order. One declaring no shape stays residue. A discriminator on both -// s and the entry leaves none: nothing says which routes it. A $ref site or a -// union beside the allOf lowers first. -func findEntryUnion(loweringContext lowering.Ctx, schema *statement.Schema) entryUnionIndex { - if declaresUnion(schema) || dispatchOf(schema).won != "allOf" { - return entryUnionIndex{} - } - entries := allOfEntries(loweringContext, schema, "").entries - var shaped, oneOfs []int - for i, entry := range entries { - choice := entry.schema.ChoiceKeywords() - // Judged against the rest of the conjunction, the entry's own unions - // apart, as a union beside the allOf and the election within an entry are. - if entry.schema.Ref != nil || !declaresUnion(entry.schema.Schema) || - !setsDeclareShape(loweringContext, schema, entry.schema.Schema, choice.OneOf, choice.AnyOf) { - continue - } - shaped = append(shaped, i) - if _, key, _ := unionBranches(loweringContext, schema, entry.schema.Schema); key == "oneOf" { - oneOfs = append(oneOfs, i) - } - } - if len(shaped) > 1 { - shaped = oneOfs - } - if len(shaped) != 1 || entries[shaped[0]].capped { - return entryUnionIndex{} - } - index := shaped[0] - if entries[index].schema.Discriminator() != nil && schema.Discriminator() != nil || - !branchesNameReferents(loweringContext, schema, entries[index].schema.Schema) { - return entryUnionIndex{} - } - if decisionOf(loweringContext, schema).refines { - return entryUnionIndex{} - } - return entryUnionIndex{index: index, ok: true} -} - -// variantHint is the hint the union variant for the branch b written at vptr -// takes: the branch's own (lowering.NameAt), unless b is inline, no title -// names it (lowering.NameTitle), and it refines the $ref its conjuncts name, -// or composes one $ref declaring no member of its own (variantNamesTarget), -// when it is the name the $ref suggests (lowering.NameThrough). So a use of -// one target, `{$ref: X, description: …}`, `{allOf: [{$ref: X}], minLength: -// 1}` or an entry of either, names its variant as the bare $ref does, a title -// beside it too (GitHub #1018, #2000). The node the branch owns keeps the -// branch's own. -func variantHint(loweringContext lowering.Ctx, b *statement.Statement, vptr jsontext.Pointer) string { - own := lowering.NameAt(loweringContext, vptr) - if !stated(b.Schema) || b.Ref != nil { +func besideUnion(schema *statement.Schema, pointer jsontext.Pointer) loweredUnionSite { + return loweredUnionSite{holder: schema, pointer: pointer, schema: schema, discriminator: schema.Discriminator(), discriminatorPointer: pointer} +} + +// entryUnion returns the union an inline entry of schema's allOf writes that +// schema's conjunction chooses, which schema, written at pointer, lowers with +// the rest of its composition as it would the same union written beside the +// allOf (docs/compilers/openapi.md#union-beside-structure), and how it is +// placed. ok is false where the union stays with its entry, as for the base of +// a hierarchy the discriminator routes. +func entryUnion(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (loweredUnionSite, unionBesideRest, bool) { + unionSite, lowersUnion := loweredUnionAt(loweringContext, schema, pointer) + if !lowersUnion || !unionSite.holderIsAllOfEntry { + return loweredUnionSite{}, unionNoneLowered, false + } + how := readLoweredUnion(loweringContext, schema).besideRest + return unionSite, how, how == unionDistributed || how == unionRoutedSubtype || how == unionSplitByKind +} + +// variantHint is the hint the union variant for the branch written at +// variantPointer takes: the branch's own (lowering.NameAt), unless branch is +// inline, no title names it (lowering.NameTitle), and it refines the $ref its +// conjuncts name, or composes one $ref declaring no member of its own +// (variantNamesTarget), when it is the name the $ref suggests +// (lowering.NameThrough). So a use of one target, `{$ref: X, description: …}`, +// `{allOf: [{$ref: X}], minLength: 1}` or an entry of either, names its variant +// as the bare $ref does, a title beside it too (GitHub #1018, #2000). The node +// the branch owns keeps the branch's own. +func variantHint(loweringContext lowering.Ctx, branch *statement.Statement, variantPointer jsontext.Pointer) string { + own := lowering.NameAt(loweringContext, variantPointer) + if !stated(branch.Schema) || branch.Ref != nil { return own } - if _, titled := lowering.NameTitle(loweringContext, vptr); titled { + if _, titled := lowering.NameTitle(loweringContext, variantPointer); titled { return own } - if refinement, refines := refinementOf(loweringContext, b.Schema, vptr); refines && refinement.ref != nil { + if refinement, refines := refinementOf(loweringContext, branch.Schema, variantPointer); refines && refinement.ref != nil { return cmp.Or(lowering.NameThrough(loweringContext, refinement.ref.pointer), own) } - // The flattened list, as b lowers: a $ref a nested wrapper holds names the + // The flattened list, as branch lowers: a $ref a nested wrapper holds names the // variant as it would written at the top. - entries := allOfEntries(loweringContext, b.Schema, vptr).entries - base, ok := selectAllOfBase(loweringContext, entries, "") - if !ok || !variantNamesTarget(b.Schema, entries) { + entries := allOfEntries(loweringContext, branch.Schema, variantPointer).entries + base, ok := selectAllOfBase(loweringContext, entries, branch.Schema, "") + if !ok || !variantNamesTarget(branch.Schema, entries) { return own } return cmp.Or(lowering.NameThrough(loweringContext, entries[base].pointer), own) } -// variantNamesTarget reports whether s, a branch composing the base of +// variantNamesTarget reports whether schema, a branch composing the base of // entries, its flattened conjuncts, is a use of that one target: it and no // conjunct writes a member, a catch-all, a discriminator or a union, and no // $ref but the base's is written (docs/compilers/openapi.md#union). @@ -674,12 +869,6 @@ func variantNamesTarget(schema *statement.Schema, entries []allOfEntry) bool { return refs == 1 } -// writesBothUnions reports whether schema writes a oneOf and an anyOf. -func writesBothUnions(schema *statement.Schema) bool { - choice := schema.ChoiceKeywords() - return len(choice.OneOf) > 0 && len(choice.AnyOf) > 0 -} - // declaresUnion reports whether schema writes oneOf or anyOf at all. func declaresUnion(schema *statement.Schema) bool { choice := schema.ChoiceKeywords() diff --git a/compilers/openapi/internal/schema/union_alone_test.go b/compilers/openapi/internal/schema/union_alone_test.go index 187149438..d0ca7ad39 100644 --- a/compilers/openapi/internal/schema/union_alone_test.go +++ b/compilers/openapi/internal/schema/union_alone_test.go @@ -48,12 +48,12 @@ func TestAllOf_AUnionAloneOnAnEntryLowersAsItsBareSpelling(t *testing.T) { } } -// TestAllOf_AUnionBesideTheAllOfKeepsAnEntrysFromStandingAlone holds a union -// on an allOf entry, the schema writing a union of its own beside the allOf, -// to be no principal standing alone (docs/compilers/openapi.md#allof-refinement): +// TestAllOf_AUnionBesideTheAllOfKeepsAnEntryFromBeingAPrincipalAlone holds a +// union on an allOf entry, the schema writing a union of its own beside the +// allOf, to be no principal alone (docs/compilers/openapi.md#allof-refinement): // the two conjoin, so the position is a Union, not the nullable reference to // the entry's one other branch its union alone would be. -func TestAllOf_AUnionBesideTheAllOfKeepsAnEntrysFromStandingAlone(t *testing.T) { +func TestAllOf_AUnionBesideTheAllOfKeepsAnEntryFromBeingAPrincipalAlone(t *testing.T) { t.Parallel() doc, _ := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` X: {type: object, properties: {id: {type: string}}} Y: {type: object, properties: {n: {type: integer}}} diff --git a/compilers/openapi/internal/schema/union_beside_test.go b/compilers/openapi/internal/schema/union_beside_test.go index 61246ad5f..e5f67067e 100644 --- a/compilers/openapi/internal/schema/union_beside_test.go +++ b/compilers/openapi/internal/schema/union_beside_test.go @@ -24,12 +24,12 @@ import ( // TestOneOf_CoDeclaredKeywordsEveryBranchSaysLeaveTheUnionAlone pins the body // that adds nothing to its branches (docs/compilers/openapi.md#union-beside-structure): // a `type` naming every kind they admit, and a `format`, `enum`, `const` or -// `items` each is held to, leave the union alone, lowered as its bare spelling -// is, keeping nothing and reporting nothing, beside a discriminator too. A -// `format` the branches do not all say stays beside the union, and a body -// keyword they do not all say keeps the body: a null the `type` leaves out, a -// branch writing no `type`, branches declaring no shape and a discriminator -// routing to a branch composing the body each keep it. +// `items` each is held to, leave the union alone, keeping and reporting +// nothing, beside a discriminator too. A `format` not every branch says stays +// beside the union; branches declaring no shape and a discriminator routing +// to a branch composing the body keep the body. Beside a string, a null +// branch is dead, the one live branch the position's node keeping its union, +// and branches of a format alone conjoin with it, a Union of the encodings. func TestOneOf_CoDeclaredKeywordsEveryBranchSaysLeaveTheUnionAlone(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` V4: {type: string, format: ipv4} @@ -90,11 +90,15 @@ func TestOneOf_CoDeclaredKeywordsEveryBranchSaysLeaveTheUnionAlone(t *testing.T) assert.Contains(t, formatNotSaid.Unmodeled, "openapi:format", "and the format no branch but one says stays beside it") for name, reading := range map[string]ir.UnmodeledReason{ - "NullLeftOut": ir.ReasonDegradedLowering, "Untyped": ir.ReasonDegradedLowering, "Shapeless": ir.ReasonValidationOnly, "DiscriminatedBase": ir.ReasonDegradedLowering, } { assert.Equal(t, string(reading), unionReading(doc, name), "%s keeps its body", name) } + nullLeftOut, ok := typeByName(doc, "NullLeftOut").(*ir.Scalar) + require.True(t, ok, "the union's one live branch is the position's node") + assert.Equal(t, &ir.TypeRef{Target: componentID("V4")}, nullLeftOut.Base) + assert.Equal(t, string(ir.ReasonDegradedLowering), unionReading(doc, "NullLeftOut"), "the union holding the dead null is kept") + assert.Equal(t, readDistributed, unionReading(doc, "Untyped"), "a Union of the encodings conjoined with the string") } // TestOneOf_CoDeclaredInlineBranchIsConjoinedByItsNode pins that a union @@ -129,7 +133,7 @@ func TestOneOf_CoDeclaredInlineBranchIsConjoinedByItsNode(t *testing.T) { require.Len(t, shape.Variants, 2, "no instance of the body is a string") assert.JSONEq(t, `{"type":"string"}`, string(shape.Unmodeled["openapi:oneOf/2"].Value), "the branch is kept") assert.Equal(t, ir.ReasonDegradedLowering, shape.Unmodeled["openapi:oneOf/2"].Reason) - assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Shape"), 1, "one warning") + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/Shape"), 1, "one warning") branches := []ir.TypeID{"type/anonymous/components/schemas/Shape/oneOf/0", "type/anonymous/components/schemas/Shape/oneOf/1"} for i := range shape.Variants { model, ok := doc.Types[shape.Variants[i].Type.Target].(*ir.Model) @@ -166,9 +170,11 @@ func TestOneOf_CoDeclaredInlineBranchIsConjoinedByItsNode(t *testing.T) { // `required` with no type beside branches that admit only an object or null: // each variant requires the names of its branch, which keeps its null, an // `items` beside it among what the union keeps, and a branch read past the -// reading's caps still names its kind. A branch that may be no object, or one -// on a cycle, leaves the body nothing to compose, and it is the top type -// (docs/compilers/openapi.md#union-beside-structure). +// reading's caps still names its kind. A branch declaring an object over Cyc, +// a loop of one hop and reported as one, distributes, and a branch of another +// kind, which no body keyword applies to, is its own node beside the object's +// composed variant (docs/compilers/openapi.md#union-beside-structure, GitHub +// #2046). func TestOneOf_CoDeclaredBareRequiredConjoinsObjectBranches(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {a: {type: string}}} @@ -182,7 +188,13 @@ func TestOneOf_CoDeclaredBareRequiredConjoinsObjectBranches(t *testing.T) { Cyc: {allOf: [{$ref: '#/components/schemas/Cyc'}]} OnACycle: {required: [a], oneOf: [{$ref: '#/components/schemas/A'}, {type: object, allOf: [{$ref: '#/components/schemas/Cyc'}]}]} `+deepChain(300))) - openapitest.RequireNoErrorDiags(t, diags) + var errs []string + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityError { + errs = append(errs, diagnostic.Code+" "+string(diagnostic.Provenance.Pointer)) + } + } + assert.Equal(t, []string{diag.CyclicRef + " /components/schemas/Cyc"}, errs, "the one error is Cyc's loop of a hop to itself") required, ok := typeByName(doc, "Required").(*ir.Union) require.True(t, ok) @@ -205,15 +217,23 @@ func TestOneOf_CoDeclaredBareRequiredConjoinsObjectBranches(t *testing.T) { assert.Len(t, union.Variants, variants, name) assert.Equal(t, name == "BesideItems", keepsKey(union.Unmodeled, "openapi:items"), name) } - for _, name := range []string{"BesideString", "OnACycle"} { - assert.Equal(t, string(ir.ReasonDegradedLowering), unionReading(doc, name), name) - assert.True(t, slices.ContainsFunc(diags, func(diagnostic ir.Diagnostic) bool { - return diagnostic.Provenance.Pointer == jsontext.Pointer("/components/schemas/"+name) && - strings.Contains(diagnostic.Message, "the body is not a model") - }), "%s: %+v", name, diags) - _, isScalar := typeByName(doc, name).(*ir.Scalar) - assert.True(t, isScalar, "%s: the top type", name) - } + // A branch that is a declared object distributes though it composes a + // reference loop: the loop is the top type and cuts nothing. + assert.Equal(t, "distributed", unionReading(doc, "OnACycle")) + besideString, ok := typeByName(doc, "BesideString").(*ir.Union) + require.True(t, ok, "the body distributes by kind") + require.Len(t, besideString.Variants, 2) + object, ok := doc.Types[besideString.Variants[0].Type.Target].(*ir.Model) + require.True(t, ok, "the object branch composes the body") + require.NotNil(t, object.Base) + assert.Equal(t, componentID("A"), object.Base.Target) + assert.Equal(t, []string{"a"}, object.Requires) + assert.False(t, strings.HasPrefix(string(besideString.Variants[1].Type.Target), "type/composed/"), + "no body keyword applies to the string branch, which is its own node") + assert.False(t, slices.ContainsFunc(diags, func(diagnostic ir.Diagnostic) bool { + return diagnostic.Provenance.Pointer == jsontext.Pointer("/components/schemas/BesideString") && + strings.Contains(diagnostic.Message, "the body is not a model") + }), "%+v", diags) } // keepsKey reports whether unmodeled keeps an entry under key. @@ -225,12 +245,12 @@ func keepsKey(unmodeled ir.Unmodeled, key string) bool { // deepChain declares D0 to Dn, each an allOf naming the next and Dn an object, // a chain whose read runs past what one reading of a schema may read. func deepChain(n int) string { - var b strings.Builder + var builder strings.Builder for i := range n { - fmt.Fprintf(&b, " D%d: {allOf: [{$ref: '#/components/schemas/D%d'}]}\n", i, i+1) + fmt.Fprintf(&builder, " D%d: {allOf: [{$ref: '#/components/schemas/D%d'}]}\n", i, i+1) } - fmt.Fprintf(&b, " D%d: {type: object}\n", n) - return b.String() + fmt.Fprintf(&builder, " D%d: {type: object}\n", n) + return builder.String() } // TestOneOf_CoDeclaredBesideAComposingAllOfDistributes pins that an allOf that @@ -371,30 +391,33 @@ func TestAllOf_AUnionEntryDistributesAsBesideTheAllOf(t *testing.T) { } assert.Equal(t, inline[1].Base.Target, useTargetOf(t, typeByName(doc, "Outside")), "an outside $ref finds the branch node") + withShapeless, ok := typeByName(doc, "WithShapeless").(*ir.Union) + require.True(t, ok) + assert.Equal(t, ir.ReasonValidationOnly, withShapeless.Unmodeled["openapi:anyOf"].Reason, + "the union declaring no shape is kept once, on the Union, as validation logic") for _, model := range variantModels(t, doc, "WithShapeless") { - assert.Equal(t, ir.ReasonValidationOnly, model.Unmodeled["openapi:anyOf"].Reason, "the union declaring no shape is kept as validation logic") - assert.NotContains(t, model.Unmodeled, "openapi:allOf/0") + assert.Empty(t, model.Unmodeled, "a variant keeps nothing of its own") } - capped := "openapi:" + strings.TrimPrefix(strings.Repeat("/allOf/0", statement.MaxFlattenDepth+1), "/") - for name, kept := range map[string][]string{ - "Shapeless": {"openapi:anyOf"}, - "Capped": {capped}, - } { - model, ok := typeByName(doc, name).(*ir.Model) - require.True(t, ok, "%s stays a model; got %T", name, typeByName(doc, name)) - for _, key := range kept { - assert.Contains(t, model.Unmodeled, key, "%s keeps its union", name) - } - } + shapeless, ok := typeByName(doc, "Shapeless").(*ir.Model) + require.True(t, ok, "Shapeless stays a model; got %T", typeByName(doc, "Shapeless")) + assert.Contains(t, shapeless.Unmodeled, "openapi:anyOf", "Shapeless keeps its union") + // Past the flattening depth the kinds' own read is cut, so the position is + // the top type keeping its allOf whole, the union inside it. + capped, ok := typeByName(doc, "Capped").(*ir.Scalar) + require.True(t, ok, "Capped is the top type; got %T", typeByName(doc, "Capped")) + require.NotNil(t, capped.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveAny), capped.Base.Target) + assert.Contains(t, capped.Unmodeled, "openapi:allOf", "Capped keeps its allOf whole") for name, anyOf := range map[string]string{"Two": "openapi:anyOf", "TwoRev": "openapi:anyOf"} { union, ok := typeByName(doc, name).(*ir.Union) require.True(t, ok, "%s distributes its oneOf; got %T", name, typeByName(doc, name)) assert.True(t, union.Exclusive, name) + assert.Equal(t, []string{anyOf}, slices.Sorted(maps.Keys(union.Unmodeled)), "%s keeps its anyOf once, on the Union", name) for _, model := range variantModels(t, doc, name) { require.NotNil(t, model.Base) assert.Equal(t, componentID("A"), model.Base.Target, name) - assert.Equal(t, []string{anyOf}, slices.Sorted(maps.Keys(model.Unmodeled)), "%s keeps its anyOf on each variant", name) + assert.Empty(t, model.Unmodeled, name) } } // An entry's union beside its $ref is the position's, as one on an entry @@ -406,7 +429,7 @@ func TestAllOf_AUnionEntryDistributesAsBesideTheAllOf(t *testing.T) { enum, ok := typeByName(doc, "EnumBeside").(*ir.Enum) require.True(t, ok, "the enum beside the allOf decides it; got %T", typeByName(doc, "EnumBeside")) - assert.Contains(t, enum.Unmodeled, "openapi:oneOf", "each conjunct the value set beat is kept under its keyword") + assert.Contains(t, enum.Unmodeled, "openapi:oneOf", "each conjunct the value set was chosen over is kept under its keyword") annotated, ok := typeByName(doc, "Annotated").(*ir.Union) require.True(t, ok) assert.Equal(t, "mine", annotated.Docs.Description, "another branch folds onto the union, as beside the allOf") @@ -418,20 +441,22 @@ func TestAllOf_AUnionEntryDistributesAsBesideTheAllOf(t *testing.T) { dynamic, ok := typeByName(doc, "DynamicRef").(*ir.Union) require.True(t, ok, "beside a $dynamicRef it keeps unexpanded, the entry union distributes as beside the allOf") assert.Contains(t, dynamic.Unmodeled, "openapi:$dynamicRef") - for _, model := range variantModels(t, doc, "BesideToo") { - assert.Contains(t, model.Unmodeled, "openapi:oneOf", "beside its own union, a branch's is kept under its keyword") - } + besideToo, ok := typeByName(doc, "BesideToo").(*ir.Union) + require.True(t, ok) + assert.True(t, besideToo.Exclusive, "the entry's oneOf is chosen over the anyOf beside the allOf") + assert.Contains(t, besideToo.Unmodeled, "openapi:anyOf", "which is kept once, under its keyword") } // TestAllOf_ADiscriminatedEntryUnionDistributesAsBeside pins a union on an allOf -// entry standing with a discriminator, on its entry or beside the allOf +// entry beside a discriminator, on its entry or beside the allOf // (docs/compilers/openapi.md#union-beside-structure): it distributes as the // same union beside the body does, the discriminator routing the composed // variants, a mapping's entries and the routes implied by name alike, its // branch keeping nothing, in either declaration order. A schema composing it -// that the union does not list carries no tag. Two discriminators, or one -// routing to branches composing the schema, keep the union whole with its -// branch, the model holding the schema's own (GitHub #1698). +// that the union does not list carries no tag. Two discriminators written +// alike are one, routing the union; one routing to branches composing the +// schema keeps the union whole with its branch, the model holding the +// schema's own (GitHub #1698). func TestAllOf_ADiscriminatedEntryUnionDistributesAsBeside(t *testing.T) { t.Parallel() const cardBank = "oneOf: [{$ref: '#/components/schemas/Card'}, {$ref: '#/components/schemas/Bank'}]" @@ -476,12 +501,15 @@ func TestAllOf_ADiscriminatedEntryUnionDistributesAsBeside(t *testing.T) { } assert.Equal(t, map[string]ir.TypeID{"card": componentID("Card"), "Bank": componentID("Bank")}, routedBases(t, doc, "Mapped"), "a mapping entry routes beside the route a name implies") - for _, name := range []string{"Both", "Root"} { - model, ok := typeByName(doc, name).(*ir.Model) - require.True(t, ok, "%s keeps its union; got %T", name, typeByName(doc, name)) - require.NotNil(t, model.Discriminator, name) - assert.Contains(t, model.Unmodeled, "openapi:oneOf", name) - } + // Two discriminators written alike are one writing, beside the + // union beside it. + both, ok := typeByName(doc, "Both").(*ir.Union) + require.True(t, ok, "Both distributes; got %T", typeByName(doc, "Both")) + require.NotNil(t, both.Discriminator) + root, ok := typeByName(doc, "Root").(*ir.Model) + require.True(t, ok, "Root keeps its union; got %T", typeByName(doc, "Root")) + require.NotNil(t, root.Discriminator) + assert.Contains(t, root.Unmodeled, "openapi:oneOf") assert.Equal(t, "Sub1", typeByName(doc, "Sub1").(*ir.Model).DiscriminatorValue, "a subtype the union lists") sub, ok := typeByName(doc, "Sub").(*ir.Model) require.True(t, ok) @@ -492,9 +520,10 @@ func TestAllOf_ADiscriminatedEntryUnionDistributesAsBeside(t *testing.T) { // TestAllOf_AHierarchyBaseEntryUnionHoldsItsDiscriminatorToItsRoutes pins a // union on an allOf entry whose schema's discriminator routes to a branch // composing the schema (docs/compilers/openapi.md#union-beside-structure): the -// union is kept under its keyword, and the discriminator on the model only where -// every type it routes to is a subtype, as beside the union, else kept verbatim -// and reported, so the document validates in either declaration order. +// union is kept under its keyword. Mixed's entry routing to Cat, no subtype, is +// kept alone, its routes to itself and Puppy typed; ByName's route to Cat by +// the name its branch names is set aside alike, its routes to itself and Kitten +// typed. The document validates in either declaration order. func TestAllOf_AHierarchyBaseEntryUnionHoldsItsDiscriminatorToItsRoutes(t *testing.T) { t.Parallel() for _, doc := range discriminatedOrders(t, "3.1.0", ` Mixed: @@ -513,14 +542,22 @@ func TestAllOf_AHierarchyBaseEntryUnionHoldsItsDiscriminatorToItsRoutes(t *testi allOf: [{$ref: '#/components/schemas/ByName'}, {type: object, properties: {age: {type: integer}}}] Cat: {type: object, properties: {kind: {type: string}, meow: {type: boolean}}} `) { - for _, name := range []string{"Mixed", "ByName"} { - model, ok := typeByName(doc, name).(*ir.Model) - require.True(t, ok, "%s is a hierarchy's base; got %T", name, typeByName(doc, name)) - assert.Nil(t, model.Discriminator, "%s routes to Cat, no subtype of it, by a mapping or by name", name) - assert.Contains(t, model.Unmodeled, "openapi:discriminator", name) - assert.Contains(t, model.Unmodeled, "openapi:oneOf", "%s: the union is kept under its keyword", name) - assert.True(t, openapitest.HasDiagCodeAt(doc.Diagnostics, diag.DegradedConstruct, "/components/schemas/"+name+"/discriminator")) - } + mixed, ok := typeByName(doc, "Mixed").(*ir.Model) + require.True(t, ok, "Mixed is a hierarchy's base; got %T", typeByName(doc, "Mixed")) + require.NotNil(t, mixed.Discriminator, "Mixed keeps the routes to itself and Puppy") + assert.Equal(t, map[string]ir.TypeID{"Puppy": componentID("Puppy"), "Mixed": componentID("Mixed")}, mixed.Discriminator.Mapping) + assert.NotContains(t, mixed.Unmodeled, "openapi:discriminator", "the discriminator is not kept whole") + assert.Contains(t, mixed.Unmodeled, "openapi:oneOf", "Mixed: the union is kept under its keyword") + assert.Len(t, diagsAtPointer(doc.Diagnostics, diag.UnhomedConstruct, "/components/schemas/Mixed/discriminator/mapping/cat"), 1, + "the entry routing to Cat, no subtype, is kept alone and reported") + byName, ok := typeByName(doc, "ByName").(*ir.Model) + require.True(t, ok, "ByName is a hierarchy's base; got %T", typeByName(doc, "ByName")) + require.NotNil(t, byName.Discriminator, "ByName keeps the routes to itself and Kitten") + assert.Equal(t, map[string]ir.TypeID{"Kitten": componentID("Kitten"), "ByName": componentID("ByName")}, byName.Discriminator.Mapping) + assert.NotContains(t, byName.Unmodeled, "openapi:discriminator", "the discriminator is not kept whole") + assert.Contains(t, byName.Unmodeled, "openapi:oneOf", "ByName: the union is kept under its keyword") + assert.Len(t, diagsAtPointer(doc.Diagnostics, diag.UnhomedConstruct, "/components/schemas/ByName/allOf/1/oneOf/1"), 1, + "the branch naming Cat, no subtype, routes nothing, and is reported") } } @@ -594,6 +631,61 @@ func routedBases(t *testing.T, doc *ir.Document, name string) map[string]ir.Type return out } +// TestUnion_ARoutedSubtypeKeepsAUnionItPassesOverOnItsMixin pins that a +// subtype a discriminator routes to keeps the union its conjunction passes +// over on the Union it composes as a mixin, wherever that union is written, on +// an entry of its own, beside the allOf, on an entry beside the union the +// allOf chooses or with that union on one entry: degraded with an info where +// its branches declare shape, and +// as validation logic where they restate the body, its provenance and its +// report where it is written, the Model keeping nothing of either +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnion_ARoutedSubtypeKeepsAUnionItPassesOverOnItsMixin(t *testing.T) { + t.Parallel() + const ( + sounds = "oneOf: [{properties: {meow: {type: string}}}, {properties: {purr: {type: string}}}]" + shapes = "anyOf: [{properties: {fins: {type: integer}}}, {properties: {gills: {type: integer}}}]" + restate = "anyOf: [{type: object}, {properties: {kind: {type: string}}}]" + ) + for _, doc := range discriminatedOrders(t, "3.1.0", ` Dog: {allOf: [{$ref: '#/components/schemas/Pet'}, {`+sounds+`}, {`+shapes+`}]} + Cat: {allOf: [{$ref: '#/components/schemas/Pet'}, {`+sounds+`}], `+shapes+`} + Bird: {allOf: [{$ref: '#/components/schemas/Pet'}, {`+restate+`}], `+sounds+`} + Fox: {allOf: [{$ref: '#/components/schemas/Pet'}, {`+sounds+`, `+restate+`}]} +`, ` Pet: + type: object + required: [kind] + properties: {kind: {type: string}} + discriminator: {propertyName: kind} +`) { + for name, testCase := range map[string]struct { + union, kept string + reason ir.UnmodeledReason + }{ + "Dog": {"/components/schemas/Dog/allOf/1/oneOf", "/components/schemas/Dog/allOf/2", ir.ReasonDegradedLowering}, + "Cat": {"/components/schemas/Cat/allOf/1/oneOf", "/components/schemas/Cat", ir.ReasonDegradedLowering}, + "Bird": {"/components/schemas/Bird/oneOf", "/components/schemas/Bird/allOf/1", ir.ReasonValidationOnly}, + "Fox": {"/components/schemas/Fox/allOf/1/oneOf", "/components/schemas/Fox/allOf/1", ir.ReasonValidationOnly}, + } { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s stays a model", name) + assert.Empty(t, model.Unmodeled, "%s keeps nothing of either union", name) + require.NotEmpty(t, model.Mixins, name) + union, ok := doc.Types[model.Mixins[len(model.Mixins)-1].Target].(*ir.Union) + require.True(t, ok, "%s composes its oneOf", name) + assert.Equal(t, jsontext.Pointer(testCase.union), union.Provenance.Pointer, name) + require.Contains(t, union.Unmodeled, "openapi:anyOf", "%s's Union keeps the anyOf", name) + kept := union.Unmodeled["openapi:anyOf"] + assert.Equal(t, testCase.reason, kept.Reason, name) + assert.Equal(t, jsontext.Pointer(testCase.kept+"/anyOf"), kept.Provenance.Pointer, "%s keeps it where it is written", name) + code := diag.DegradedConstruct + if testCase.reason == ir.ReasonValidationOnly { + code = diag.ValidationOnlyKeyword + } + assert.Contains(t, reportedAt(doc.Diagnostics), "info "+code+" "+testCase.kept, "%s reports it where it is written", name) + } + } +} + // TestUnion_ARoutedSubtypeComposesItsUnionAsAMixin pins a union beside or on an // allOf entry of a schema a discriminated ancestor routes to, by a mapping key // or its name (docs/compilers/openapi.md#union-beside-structure). Distributed, @@ -644,7 +736,7 @@ func TestUnion_ARoutedSubtypeComposesItsUnionAsAMixin(t *testing.T) { Collar: {type: object, properties: {tag: {type: string}}} `) { sizes := typeByName(doc, "Sizes").(*ir.Union) - for name, tc := range map[ir.TypeID]struct { + for name, testCase := range map[ir.TypeID]struct { tag, at string own []string }{ @@ -659,17 +751,17 @@ func TestUnion_ARoutedSubtypeComposesItsUnionAsAMixin(t *testing.T) { require.True(t, ok, "%s stays a model; got %T", name, doc.Types[name]) require.NotNil(t, model.Base, name) assert.Equal(t, componentID("Pet"), model.Base.Target, "%s is a subtype of Pet", name) - assert.Equal(t, tc.tag, model.DiscriminatorValue, name) + assert.Equal(t, testCase.tag, model.DiscriminatorValue, name) assert.Empty(t, model.Unmodeled, "%s keeps nothing of its union", name) assert.Nil(t, model.Discriminator, name) - assert.Equal(t, tc.own, wireNames(model.Properties), "%s merges what the branch writes beside its union", name) + assert.Equal(t, testCase.own, wireNames(model.Properties), "%s merges what the branch writes beside its union", name) require.NotEmpty(t, model.Mixins, name) mixin := model.Mixins[len(model.Mixins)-1].Target - assert.Equal(t, ir.TypeID("type/composed"+tc.at), mixin, "%s names its union, minted where the keyword is", name) + assert.Equal(t, ir.TypeID("type/composed"+testCase.at), mixin, "%s names its union, minted where the keyword is", name) union, ok := doc.Types[mixin].(*ir.Union) require.True(t, ok, "%s's mixin is a union; got %T", name, doc.Types[mixin]) - assert.Equal(t, jsontext.Pointer(tc.at), union.Provenance.Pointer, name) - if tc.at != "/components/schemas/Cat/oneOf" && tc.at != "/components/schemas/Fish/allOf/1/anyOf" { + assert.Equal(t, jsontext.Pointer(testCase.at), union.Provenance.Pointer, name) + if testCase.at != "/components/schemas/Cat/oneOf" && testCase.at != "/components/schemas/Fish/allOf/1/anyOf" { assert.Equal(t, sizes.Variants, union.Variants, "%s's union is what a component holding it is", name) } } @@ -754,11 +846,13 @@ func wireNames(properties []ir.Property) []string { // route names it, it distributes as the same union beside the allOf does, in // either declaration order, and where a mapping key or the name of its // component routes to it, it stays a tagged model composing the union as a -// mixin (GitHub #1695). +// mixin (GitHub #1695). Each distributed variant is a subtype of Pet no route +// names, which validation notes. func TestUnion_AnEntryUnionNoRouteNamesDistributesAsBeside(t *testing.T) { t.Parallel() const sizes = "oneOf: [{$ref: '#/components/schemas/Small'}, {$ref: '#/components/schemas/Big'}]" - for _, doc := range discriminatedOrders(t, "3.1.0", ` Pet: + told := slices.Repeat([]string{"pass/discriminator-unrouted-variant"}, 4) + for _, doc := range discriminatedOrdersTold(t, "3.1.0", ` Pet: type: object properties: {kind: {type: string}} discriminator: @@ -774,7 +868,7 @@ func TestUnion_AnEntryUnionNoRouteNamesDistributesAsBeside(t *testing.T) { beside: {allOf: [{$ref: '#/components/schemas/Pet'}], `+sizes+`} branch: {allOf: [{$ref: '#/components/schemas/Pet'}, {`+sizes+`}]} gerbil: {allOf: [{$ref: '#/components/schemas/Pet'}, {`+sizes+`}]} -`) { +`, told) { beside, ok := doc.Types["type/anonymous/components/schemas/Holder/properties/beside"].(*ir.Union) require.True(t, ok, "beside the allOf, the union distributes") branch, ok := doc.Types["type/anonymous/components/schemas/Holder/properties/branch"].(*ir.Union) @@ -811,7 +905,7 @@ func TestUnion_ASchemaNoRouteNamesDistributesBesideItsAllOf(t *testing.T) { const rest = " Small: {type: object, properties: {size: {type: integer}}}\n" + " Big: {type: object, properties: {weight: {type: integer}}}\n" + " Stored:\n allOf: [{$ref: '#/components/schemas/Rule'}, {properties: {id: {type: string}}}]\n" + sizes - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { base string listed bool // whether the union Rule's discriminator is written beside lists Listed }{ @@ -823,7 +917,7 @@ func TestUnion_ASchemaNoRouteNamesDistributesBesideItsAllOf(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - for _, doc := range taggedOrders(t, tc.base, rest) { + for _, doc := range taggedOrders(t, testCase.base, rest) { union, ok := typeByName(doc, "Stored").(*ir.Union) require.True(t, ok, "Stored distributes; got %T", typeByName(doc, "Stored")) for _, model := range variantModels(t, doc, "Stored") { @@ -831,7 +925,7 @@ func TestUnion_ASchemaNoRouteNamesDistributesBesideItsAllOf(t *testing.T) { assert.Empty(t, model.DiscriminatorValue, "and no variant is tagged") } assert.Len(t, union.Variants, 2) - if !tc.listed { + if !testCase.listed { continue } listed, ok := typeByName(doc, "Listed").(*ir.Model) @@ -848,24 +942,28 @@ func TestUnion_ASchemaNoRouteNamesDistributesBesideItsAllOf(t *testing.T) { // TestOneOf_CoDeclaredTypeReadsNullableByItsDialect pins the null a `type` // beside a union is compared with (docs/compilers/openapi.md#union-beside-structure): // a `nullable: true` beside it adds null where the dialect defines the keyword, -// so in 3.0 the type says a branch admitting null and the union is the schema, -// and in 3.1 it adds nothing, so the body is kept beside the union. +// so in 3.0 the type says a branch admitting null, and in 3.1 the policy alone +// reads it in, which it says. In both the branches, each a $ref, declare shape +// against the string, so the union is the Union of the two references. func TestOneOf_CoDeclaredTypeReadsNullableByItsDialect(t *testing.T) { t.Parallel() - for version, tc := range map[string]struct { + for version, testCase := range map[string]struct { nullString string - alone bool + inferred bool }{ - "3.0.3": {"{type: string, nullable: true}", true}, - "3.1.0": {"{type: [string, 'null']}", false}, + "3.0.3": {"{type: string, nullable: true}", false}, + "3.1.0": {"{type: [string, 'null']}", true}, } { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer(version, ` V4: {type: string, format: ipv4} - N: `+tc.nullString+` + N: `+testCase.nullString+` S: {type: string, nullable: true, oneOf: [{$ref: '#/components/schemas/V4'}, {$ref: '#/components/schemas/N'}]} `)) openapitest.RequireNoErrorDiags(t, diags) - _, alone := typeByName(doc, "S").(*ir.Union) - assert.Equal(t, tc.alone, alone, "%s: S lowers to the union alone", version) + union, ok := typeByName(doc, "S").(*ir.Union) + require.True(t, ok, "%s: S is the Union of its branches", version) + assert.Len(t, union.Variants, 2, version) + assert.Equal(t, testCase.inferred, openapitest.HasDiagCodeAt(diags, diag.InferredNullable, "/components/schemas/S/nullable"), + "%s: the null is read in by the policy alone", version) } } @@ -929,7 +1027,7 @@ func TestOneOf_CoDeclaredDiscriminatorRoutesTheComposedVariants(t *testing.T) { for _, src := range []string{union + variants, variants + union} { doc, diags := parseFull(t, openapitest.ComponentSpecVer(c.version, src)) openapitest.RequireNoErrorDiags(t, diags) - assert.Empty(t, validated(t, doc), "every route names a variant") + assert.Empty(t, routeFindings(t, doc), "every route names a variant") union, ok := typeByName(doc, "U").(*ir.Union) require.True(t, ok, "the body distributes; got %T", typeByName(doc, "U")) require.NotNil(t, union.Discriminator) @@ -982,3 +1080,383 @@ components: require.NotNil(t, union.Discriminator) assert.Equal(t, map[string]ir.TypeID{"Dog": union.Variants[1].Type.Target}, union.Discriminator.Mapping) } + +// TestUnionBeside_DeadAndConjoinedBranchesAreKeptAndNamed holds three +// readings of a union beside a body: branches writing formats conjoin with a +// string, a format the IR reads off a string keeping that wire type; a null +// branch an anyOf beside an object keeps null out is dead, kept under its +// index and named as null; and the node of null alone keeps what the allOf +// beside it writes that it reads none of, a $ref among it +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_DeadAndConjoinedBranchesAreKeptAndNamed(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {a: {type: string}}} + B: {type: object, properties: {b: {type: string}}} + Null: {type: 'null'} + Wire: {type: string, oneOf: [{format: int64}, {format: uuid}]} + DeadNull: {type: object, properties: {a: {type: string}}, oneOf: [{$ref: '#/components/schemas/A'}, {type: 'null', title: n}], anyOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]} + NullAlone: {allOf: [{$ref: '#/components/schemas/Null'}, true, {description: d, maxLength: 3}], oneOf: [{type: 'null'}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + wire, ok := typeByName(doc, "Wire").(*ir.Union) + require.True(t, ok, "Wire is the Union of its encodings; got %T", typeByName(doc, "Wire")) + require.Len(t, wire.Variants, 2) + encoded, ok := doc.Types[wire.Variants[0].Type.Target].(*ir.Scalar) + require.True(t, ok) + require.NotNil(t, encoded.Encoding) + require.NotNil(t, encoded.Encoding.WireType) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), encoded.Encoding.WireType.Target) + + dead, ok := typeByName(doc, "DeadNull").(*ir.Union) + require.True(t, ok, "DeadNull distributes its live branch; got %T", typeByName(doc, "DeadNull")) + assert.Len(t, dead.Variants, 1) + assert.Contains(t, dead.Unmodeled, "openapi:oneOf/1") + warned := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/DeadNull") + require.Len(t, warned, 1) + assert.Contains(t, warned[0].Message, "oneOf/1: null") + + alone, ok := typeByName(doc, "NullAlone").(*ir.Enum) + require.True(t, ok, "NullAlone is null alone; got %T", typeByName(doc, "NullAlone")) + for _, key := range []string{"openapi:$ref", "openapi:maxLength", "openapi:oneOf"} { + assert.Contains(t, alone.Unmodeled, key) + } +} + +// TestUnionBeside_ABoundedFormatBranchIsAScalarOfItsPrimitive holds a branch +// writing a format and a bound beside a string: its variant is a Scalar of the +// primitive the format selects, with no Encoding where the format names none, +// keeping a length of the date's text verbatim as the branch written with the +// string does, since a length binds no date +// (docs/compilers/openapi.md#union-beside-structure, +// docs/compilers/openapi.md#constraints). +func TestUnionBeside_ABoundedFormatBranchIsAScalarOfItsPrimitive(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Dates: {type: string, oneOf: [{format: date, maxLength: 10}, {format: uuid}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + union, ok := typeByName(doc, "Dates").(*ir.Union) + require.True(t, ok, "Dates is the Union of its encodings; got %T", typeByName(doc, "Dates")) + require.Len(t, union.Variants, 2) + bounded, ok := doc.Types[union.Variants[0].Type.Target].(*ir.Scalar) + require.True(t, ok, "the bounded branch is a Scalar of its own") + require.NotNil(t, bounded.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveDate), bounded.Base.Target) + assert.Nil(t, bounded.Encoding) + assert.Nil(t, bounded.Constraints) + assert.Equal(t, ir.ReasonNoIRHome, bounded.Unmodeled["openapi:maxLength"].Reason) + assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.UnhomedConstruct, ir.SeverityInfo)) +} + +// TestUnionBeside_AConjoinedBranchKeepsWhatItDeclares holds a branch conjoined +// with the string beside its union to its own node holding what it declares, +// as the branch's node would: its docs, deprecation, examples, extensions and +// a key no dialect defines, and a format's branch writing a description a node +// of its own rather than the shared primitive +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_AConjoinedBranchKeepsWhatItDeclares(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` U: + type: string + oneOf: + - {minLength: 1, description: dd, deprecated: true, examples: [abc], x-y: 2, foo: 1} + - {format: uuid, description: an id} +`)) + openapitest.RequireNoErrorDiags(t, diags) + union, ok := typeByName(doc, "U").(*ir.Union) + require.True(t, ok, "U is the Union of its branches; got %T", typeByName(doc, "U")) + require.Len(t, union.Variants, 2) + bounded, ok := doc.Types[union.Variants[0].Type.Target].(*ir.Scalar) + require.True(t, ok, "the bounded branch is a Scalar of its own") + assert.Equal(t, "dd", bounded.Docs.Description) + assert.NotNil(t, bounded.Deprecation) + assert.Len(t, bounded.Examples, 1) + assert.Contains(t, bounded.Unmodeled, "openapi:x-y") + assert.Contains(t, bounded.Unmodeled, "openapi:foo") + described, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Scalar) + require.True(t, ok, "the described format's branch is a node of its own; got %T", doc.Types[union.Variants[1].Type.Target]) + assert.Equal(t, "an id", described.Docs.Description) + require.NotNil(t, described.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveUUID), described.Base.Target) +} + +// TestUnionBeside_ABodyNamingNoKindGoesToBranchesOfNoObjectByKind holds a body +// naming no kind beside a union of an array and a string, flat, beside an +// allOf and on an entry: each branch takes the body's keywords of its kind, a +// Scalar over the string holding the minLength and the array its own node, +// and the properties, applying to no kind the union admits, is kept verbatim +// once with an info (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_ABodyNamingNoKindGoesToBranchesOfNoObjectByKind(t *testing.T) { + t.Parallel() + const union = "oneOf: [{$ref: '#/components/schemas/Arr'}, {$ref: '#/components/schemas/Str'}]" + const body = "properties: {a: {type: string}}, minLength: 1" + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Arr: {type: array, items: {type: string}} + Str: {type: string} + Flat: {`+body+`, `+union+`} + Beside: {allOf: [{`+body+`}], `+union+`} + Entry: {allOf: [{`+body+`}, {`+union+`}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, at := range map[string]string{"Flat": "", "Beside": "/allOf/0", "Entry": "/allOf/0"} { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s is split by kind; got %T", name, typeByName(doc, name)) + require.Len(t, union.Variants, 2, name) + assert.Equal(t, componentID("Arr"), union.Variants[0].Type.Target, name) + scalar, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Scalar) + require.True(t, ok, "%s: the string's variant is a Scalar", name) + require.NotNil(t, scalar.Base, name) + assert.Equal(t, componentID("Str"), scalar.Base.Target, name) + require.NotNil(t, scalar.Constraints, name) + assert.Equal(t, int64(1), *scalar.Constraints.MinLength, name) + kept, ok := union.Unmodeled["openapi:properties"] + require.True(t, ok, "%s keeps the properties", name) + assert.Equal(t, jsontext.Pointer("/components/schemas/"+name+at+"/properties"), kept.Provenance.Pointer, name) + assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/"+name+at), 1, name) + } +} + +// TestUnionBeside_AnItemsBranchBesideAStringLives holds a branch writing items +// beside a string, which every string satisfies, to a live branch in every +// spelling: the Union of the string and a Scalar of a string keeping the +// items, flat, beside an allOf of the string and on an entry in either order +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_AnItemsBranchBesideAStringLives(t *testing.T) { + t.Parallel() + const union = "oneOf: [{type: string}, {items: {type: integer}}]" + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Flat: {type: string, `+union+`} + Beside: {allOf: [{type: string}], `+union+`} + Entry: {allOf: [{type: string}, {`+union+`}]} + EntryRev: {allOf: [{`+union+`}, {type: string}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Flat", "Beside", "Entry", "EntryRev"} { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s is the Union of its live branches; got %T", name, typeByName(doc, name)) + require.Len(t, union.Variants, 2, name) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), union.Variants[0].Type.Target, name) + scalar, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Scalar) + require.True(t, ok, "%s: the items branch is a string's Scalar", name) + assert.Contains(t, scalar.Unmodeled, "openapi:items", name) + assert.Empty(t, warningsUnder(diags, name), name) + } +} + +// TestUnionBeside_AnEntryObjectOrNullReadsItsNullAsFlat holds an object or +// null on an entry beside a union of a string, which shares no kind with it, +// to the flat spelling's lowering: the Model keeping the union, the string +// dead, with the one warning at the schema, and the reference admitting null +// alike (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_AnEntryObjectOrNullReadsItsNullAsFlat(t *testing.T) { + t.Parallel() + const body = "type: [object, 'null'], properties: {a: {type: string}}" + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Flat: {`+body+`, oneOf: [{type: string}]} + Entry: {allOf: [{`+body+`}], oneOf: [{type: string}]} + Holder: + type: object + properties: + f: {$ref: '#/components/schemas/Flat'} + e: {$ref: '#/components/schemas/Entry'} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Flat", "Entry"} { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s is its body; got %T", name, typeByName(doc, name)) + assert.Equal(t, ir.ReasonDegradedLowering, model.Unmodeled["openapi:oneOf"].Reason, name) + warned := warningsUnder(diags, name) + require.Len(t, warned, 1, name) + assert.Equal(t, "/components/schemas/"+name, string(warned[0].Provenance.Pointer), name) + } + holder, ok := typeByName(doc, "Holder").(*ir.Model) + require.True(t, ok) + properties := openapitest.PropertiesByWire(holder.Properties) + assert.Equal(t, properties["f"].Type.Nullable, properties["e"].Type.Nullable, "the null reads alike") +} + +// TestUnion_SeveralOneOfsReadEachAgainstTheRest holds two oneOfs on one +// conjunction, which no rule chooses between, on two entries in either order +// and one beside the allOf, to the kinds they share, each union kept and each +// naming at its keyword the branch sharing no kind with the other, and two +// sharing no value to the one report that the conjuncts share none +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnion_SeveralOneOfsReadEachAgainstTheRest(t *testing.T) { + t.Parallel() + const integer, boolean = "oneOf: [{type: string}, {type: integer}]", "oneOf: [{type: string}, {type: boolean}]" + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Entries: {allOf: [{"+integer+"}, {"+boolean+"}]}\n"+ + " EntriesRev: {allOf: [{"+boolean+"}, {"+integer+"}]}\n"+ + " Beside: {"+integer+", allOf: [{"+boolean+"}]}\n"+ + " BesideRev: {"+boolean+", allOf: [{"+integer+"}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Entries", "EntriesRev", "Beside", "BesideRev"} { + scalar, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s is the string both admit; got %T", name, typeByName(doc, name)) + require.NotNil(t, scalar.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), scalar.Base.Target, name) + warned := warningsUnder(diags, name) + require.Len(t, warned, 2, "%s: each union names its dead branch", name) + var dead []string + for _, diagnostic := range warned { + assert.True(t, strings.HasSuffix(string(diagnostic.Provenance.Pointer), "/oneOf"), name) + dead = append(dead, diagnostic.Message[strings.Index(diagnostic.Message, "(")+1:strings.Index(diagnostic.Message, ")")]) + } + assert.ElementsMatch(t, []string{"oneOf/1: integer", "oneOf/1: boolean"}, dead, name) + } + _, disjoint := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Disjoint: {allOf: [{"+integer+"}, {oneOf: [{type: boolean}, {type: 'null'}]}]}\n")) + warned := warningsUnder(disjoint, "Disjoint") + require.Len(t, warned, 1, "unions sharing no value draw the one report that the conjuncts share none") + assert.False(t, strings.HasSuffix(string(warned[0].Provenance.Pointer), "/oneOf"), warned[0].Message) +} + +// TestUnionBeside_AnEntrysTypeAndFormatLowerAsTheirFlatTwin holds a body's +// type and format, beside a union its node keeps or conjoins, to what the flat +// spelling makes of them in every spelling, the type alone on an entry among +// them, at 3.0 and 3.1: an array's type is read, keeping the union alone, and +// a string's format no conjoined Union holds is kept with an info, never +// dropped (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_AnEntrysTypeAndFormatLowerAsTheirFlatTwin(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.0.3", "3.1.0"} { + arrays := openapitest.Spellings("type: array, items: {type: integer}", "oneOf: [{type: array, maxItems: 5}, {type: boolean}]") + arrays["KindOnEntry"] = "{items: {type: integer}, oneOf: [{type: array, maxItems: 5}, {type: boolean}], allOf: [{type: array}]}" + formats := openapitest.Spellings("type: string, format: date-time", "oneOf: [{format: uuid}, {format: date}]") + var written strings.Builder + for name, spelled := range arrays { + written.WriteString(" A" + name + ": " + spelled + "\n") + } + for name, spelled := range formats { + written.WriteString(" F" + name + ": " + spelled + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer(version, written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for name := range arrays { + list, ok := typeByName(doc, "A"+name).(*ir.List) + require.True(t, ok, "%s A%s: got %T", version, name, typeByName(doc, "A"+name)) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInteger), list.ElementType.Target, name) + assert.Equal(t, []string{"openapi:oneOf"}, slices.Sorted(maps.Keys(list.Unmodeled)), "%s A%s keeps the union alone", version, name) + } + for name := range formats { + union, ok := typeByName(doc, "F"+name).(*ir.Union) + require.True(t, ok, "%s F%s: got %T", version, name, typeByName(doc, "F"+name)) + require.Len(t, union.Variants, 2, name) + kept, ok := union.Unmodeled["openapi:format"] + require.True(t, ok, "%s F%s keeps the body's format", version, name) + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason, name) + } + } +} + +// TestUnionBeside_ADiscriminatorBesideADistributingAllOfIsKeptAsWhereItDoesNot +// holds a discriminator written beside an allOf whose entry writes the union +// and a discriminator of its own: the Union is routed by the entry's, and the +// one beside the allOf is kept on it verbatim, its route resolved and one info +// said at the schema, whether the union distributes over the allOf, another +// entry declaring members, or is alone, in either declaration order. It was +// dropped where the union distributes, with no report. +func TestUnionBeside_ADiscriminatorBesideADistributingAllOfIsKeptAsWhereItDoesNot(t *testing.T) { + t.Parallel() + const entry = " - oneOf: [{$ref: '#/components/schemas/Cat'}, {$ref: '#/components/schemas/Dog'}]\n" + + " discriminator: {propertyName: kind}\n" + const beside = " discriminator: {propertyName: kind, mapping: {c: '#/components/schemas/Cat'}}\n" + const rest = " Cat: {type: object, properties: {kind: {type: string}, lives: {type: integer}}}\n" + + " Dog: {type: object, properties: {kind: {type: string}, bark: {type: boolean}}}\n" + for _, c := range []struct{ name, members string }{ + {"distributing over the allOf", " - {type: object, properties: {kind: {type: string}}}\n"}, + {"standing alone", ""}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + pet := " Pet:\n allOf:\n" + c.members + entry + beside + for _, doc := range discriminatedOrders(t, "3.1.0", pet, rest) { + union, ok := typeByName(doc, "Pet").(*ir.Union) + require.True(t, ok, "Pet is the Union; got %T", typeByName(doc, "Pet")) + require.NotNil(t, union.Discriminator) + assert.NotContains(t, union.Discriminator.Mapping, "c", "the entry's discriminator routes the Union") + kept, held := union.Unmodeled["openapi:discriminator"] + require.True(t, held, "the discriminator beside the allOf is kept; got %v", union.Unmodeled) + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) + assert.JSONEq(t, `{"propertyName": "kind", "mapping": {"c": "#/components/schemas/Cat"}}`, string(kept.Value)) + assert.Equal(t, map[jsontext.Pointer]ir.TypeID{"/mapping/c": componentID("Cat")}, kept.Targets) + said := reportsAt(doc.Diagnostics, "/components/schemas/Pet") + assert.Equal(t, 1, countContaining(said, "holds the discriminator its inline allOf entry writes"), "%v", said) + } + }) + } +} + +// countContaining counts the messages holding text. +func countContaining(messages []string, text string) int { + count := 0 + for _, message := range messages { + if strings.Contains(message, text) { + count++ + } + } + return count +} + +// TestUnionBeside_ADiscriminatorOnAnEntryIsAsWrittenFlat holds a +// discriminator on an allOf entry, the union beside the allOf or on another +// entry, in either order of the entries, at 3.0 and 3.1, to the flat +// spelling's Union routed by it; two entries writing it alike to that one, and +// two disagreeing to none, each entry kept, in either order alike +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnionBeside_ADiscriminatorOnAnEntryIsAsWrittenFlat(t *testing.T) { + t.Parallel() + const union = "oneOf: [{$ref: '#/components/schemas/X'}, {$ref: '#/components/schemas/Y'}]" + disc := func(name string) string { return "{discriminator: {propertyName: " + name + "}}" } + routed := map[string]string{ + "Flat": "{" + union + ", discriminator: {propertyName: kind}}", + "OnEntry": "{" + union + ", allOf: [{description: d}, " + disc("kind") + "]}", + "OnEntryFirst": "{" + union + ", allOf: [" + disc("kind") + ", {description: d}]}", + "Beside": "{allOf: [{" + union + "}], discriminator: {propertyName: kind}}", + "OnOther": "{allOf: [{" + union + "}, " + disc("kind") + "]}", + "OnOtherFirst": "{allOf: [" + disc("kind") + ", {" + union + "}]}", + "Alike": "{allOf: [{" + union + "}, " + disc("kind") + ", " + disc("kind") + "]}", + } + apart := map[string]string{ + "Apart": "{allOf: [{" + union + "}, " + disc("kind") + ", " + disc("type") + "]}", + "ApartRev": "{allOf: [{" + union + "}, " + disc("type") + ", " + disc("kind") + "]}", + } + for _, version := range []string{"3.0.3", "3.1.0"} { + written := " X: {type: object, properties: {kind: {type: string}, type: {type: string}}}\n" + + " Y: {type: object, properties: {kind: {type: string}, type: {type: string}}}\n" + for name, spelled := range routed { + written += " " + name + ": " + spelled + "\n" + } + for name, spelled := range apart { + written += " " + name + ": " + spelled + "\n" + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer(version, written)) + openapitest.RequireNoErrorDiags(t, diags) + for name := range routed { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s %s: got %T", version, name, typeByName(doc, name)) + require.NotNil(t, union.Discriminator, "%s %s", version, name) + assert.Equal(t, "kind", union.Discriminator.PropertyName, "%s %s", version, name) + assert.Empty(t, union.Unmodeled, "%s %s keeps nothing", version, name) + } + for name := range apart { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s %s: got %T", version, name, typeByName(doc, name)) + assert.Nil(t, union.Discriminator, "%s %s: disagreeing entries route nothing", version, name) + assert.Equal(t, []string{"openapi:allOf/1", "openapi:allOf/2"}, slices.Sorted(maps.Keys(union.Unmodeled)), "%s %s", version, name) + } + } +} + +// TestUnionBeside_ASplitDistributionRefusesKeepsTheBodysBoundsAsItsFlatTwin +// holds a union of an object and another kind beside a body that is no Model, +// which a branch naming nothing resolved keeps from being split by kind: the +// body's bound is no split branch's, so the node keeps it as the same union +// written beside the bound keeps it, on an entry as flat. Read as split by +// kind, the entry's bound was dropped with no report. +func TestUnionBeside_ASplitDistributionRefusesKeepsTheBodysBoundsAsItsFlatTwin(t *testing.T) { + t.Parallel() + const union = "oneOf: [{$ref: '#/components/schemas/Missing'}, {type: object}, {type: string}]" + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Flat: {minLength: 1, properties: {a: {type: string}}, "+union+"}\n"+ + " OnEntry: {allOf: [{minLength: 1, properties: {a: {type: string}}}, {"+union+"}]}\n")) + for _, name := range []string{"Flat", "OnEntry"} { + model, ok := typeByName(doc, name).(*ir.Model) + require.True(t, ok, "%s: got %T", name, typeByName(doc, name)) + assert.Equal(t, []string{"openapi:minLength", "openapi:oneOf"}, slices.Sorted(maps.Keys(model.Unmodeled)), name) + } +} diff --git a/compilers/openapi/internal/schema/union_combinators_test.go b/compilers/openapi/internal/schema/union_combinators_test.go index 3bf4d644f..09aa636b2 100644 --- a/compilers/openapi/internal/schema/union_combinators_test.go +++ b/compilers/openapi/internal/schema/union_combinators_test.go @@ -4,6 +4,7 @@ package schema_test import ( + "encoding/json/jsontext" "maps" "slices" "strings" @@ -22,7 +23,7 @@ import ( // TestUnionCombinators_CoDeclaredKeepsTheBoundsWrittenBesideIt pins that // keeping a union verbatim does not cost the position the value constraints // written beside it. The alias holding the union owns the pointer, so -// hoistDeclarationHome does not hoist the alias that would carry the bounds, +// homeDeclaration does not hoist the alias that would carry the bounds, // and this alias must carry them itself (GitHub #343). Both reasons that keep a // union hoist the same alias, and anyOf takes the same path as oneOf. The last // case pins that a co-declared bound pair adds nothing beside the union. @@ -46,7 +47,7 @@ func TestUnionCombinators_CoDeclaredKeepsTheBoundsWrittenBesideIt(t *testing.T) }, { name: "a union kept as a degraded lowering", - schemas: " A: {type: number, minimum: 10, multipleOf: 5, oneOf: [{type: string}, {type: integer}]}\n", + schemas: " A: {type: number, minimum: 10, multipleOf: 5, oneOf: [{type: string}, {maximum: 99}]}\n", unionKey: "openapi:oneOf", reason: ir.ReasonDegradedLowering, want: ir.Constraints{Min: &ten, MultipleOf: &five}, @@ -71,31 +72,32 @@ func TestUnionCombinators_CoDeclaredKeepsTheBoundsWrittenBesideIt(t *testing.T) wantKept: []string{"openapi:oneOf"}, }, } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(tc.schemas)) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(testCase.schemas)) openapitest.RequireNoErrorDiags(t, diags) sc, ok := typeByName(doc, "A").(*ir.Scalar) require.True(t, ok, "the preserved union hoists an alias over the shared primitive") - entry, ok := sc.Unmodeled[tc.unionKey] + entry, ok := sc.Unmodeled[testCase.unionKey] require.True(t, ok, "and keeps the union on it") - assert.Equal(t, tc.reason, entry.Reason) + assert.Equal(t, testCase.reason, entry.Reason) require.NotNil(t, sc.Constraints, "while keeping the bounds written beside it") - assert.Empty(t, cmp.Diff(tc.want, *sc.Constraints)) - assert.Equal(t, tc.wantKept, unmodeledKeys(sc.Unmodeled), + assert.Empty(t, cmp.Diff(testCase.want, *sc.Constraints)) + assert.Equal(t, testCase.wantKept, unmodeledKeys(sc.Unmodeled), "the union is the only entry kept on the node") }) } } // TestUnionCombinators_PassedOverBranchSetIsKept covers the preference nothing -// used to record (GitHub #35). unionBranches takes oneOf whenever it is written +// used to record (GitHub #35). loweredKeyword takes oneOf whenever it is written // and falls back to anyOf only when it is not, so a schema declaring both lost // the anyOf outright — no variant, no Unmodeled entry, no diagnostic. The two -// conjoin, and one ir.Union carries one branch set, so the elected set stays the -// union and the other is kept beside it. +// conjoin, and one ir.Union carries one branch set, so the chosen set stays the +// union and the other is kept beside it. Its string branch shares no kind +// with the anyOf, so it is dead and the oneOf is kept too. func TestUnionCombinators_PassedOverBranchSetIsKept(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` S: @@ -105,10 +107,11 @@ func TestUnionCombinators_PassedOverBranchSetIsKept(t *testing.T) { openapitest.RequireNoErrorDiags(t, diags) union, ok := typeByName(doc, "S").(*ir.Union) - require.True(t, ok, "the elected branch set still becomes the union") - assert.Len(t, union.Variants, 2, "one variant per oneOf branch") + require.True(t, ok, "the chosen branch set still becomes the union") + assert.Len(t, union.Variants, 1, "one variant per live oneOf branch") + assert.Contains(t, union.Unmodeled, "openapi:oneOf", "the oneOf holding a dead branch is kept") entry, ok := union.Unmodeled["openapi:anyOf"] - require.True(t, ok, "the set unionBranches passed over is kept; got %v", union.Unmodeled) + require.True(t, ok, "the set loweredKeyword passed over is kept; got %v", union.Unmodeled) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) assert.JSONEq(t, `[{"type":"number"},{"type":"boolean"}]`, string(entry.Value)) assert.Contains(t, @@ -118,10 +121,10 @@ func TestUnionCombinators_PassedOverBranchSetIsKept(t *testing.T) { // TestUnionCombinators_NullBranchDoesNotCollapsePastTheAnyOf covers the second // site of the same preference. A {X, null} oneOf normally collapses to nullable -// X, which resolves the position straight to X's own node — the shared string -// primitive here — leaving the co-declared anyOf nowhere of its own to sit; it -// was dropped there too. A schema writing both combinators is not nullable X in -// the first place, so it stays a Union and keeps the loser on it. +// X, which resolves the position straight to X's own node, leaving the +// co-declared anyOf nowhere of its own to sit; it was dropped there too. Here +// the anyOf keeps both the string and the null out, so every branch of the +// oneOf is dead: the position is what nothing else says, keeping both. func TestUnionCombinators_NullBranchDoesNotCollapsePastTheAnyOf(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` S: @@ -130,31 +133,29 @@ func TestUnionCombinators_NullBranchDoesNotCollapsePastTheAnyOf(t *testing.T) { `)) openapitest.RequireNoErrorDiags(t, diags) - union, ok := typeByName(doc, "S").(*ir.Union) + scalar, ok := typeByName(doc, "S").(*ir.Scalar) require.True(t, ok, "the collapse is declined; got %v", typeByName(doc, "S")) - require.Len(t, union.Variants, 1, "the null branch still lifts off the variant list") - assert.Equal(t, ir.TypeID("type/primitive/string"), union.Variants[0].Type.Target) - assert.Contains(t, union.Unmodeled, "openapi:anyOf", - "and the node the position now owns carries the set passed over") + assert.Contains(t, scalar.Unmodeled, "openapi:oneOf") + assert.Contains(t, scalar.Unmodeled, "openapi:anyOf", "and the node the position owns carries the set passed over") + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/S")) } -// TestUnionCombinators_UnpreservableIsNotAnnounced pins the pairing GitHub #144 -// exists for, at this site: a position may only announce what it actually kept. -// The anyOf here fails to convert, so the union lowers, the failure is reported -// at the keyword, and nothing claims the branch set survived. -func TestUnionCombinators_UnpreservableIsNotAnnounced(t *testing.T) { +// TestUnionCombinators_AKeptBranchSetDropsAnExtensionNoJSONHolds pins an anyOf +// kept beside the oneOf a union lowers, one of whose branches writes an +// extension that converts to no JSON: the anyOf is kept and reported as +// without the extension, which alone is dropped with its own warning at the +// branch, and a valid document draws no error. +func TestUnionCombinators_AKeptBranchSetDropsAnExtensionNoJSONHolds(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` S: + doc := requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpec(` S: oneOf: [{type: string}, {type: integer}] - anyOf: [{type: number, x-t: `+unpreservableValue+`}] -`)) + anyOf: [{type: number`+unconvertibleExtension+`}] +`), unconvertibleExtension, "/components/schemas/S/anyOf/0") union, ok := typeByName(doc, "S").(*ir.Union) require.True(t, ok) - assert.NotContains(t, union.Unmodeled, "openapi:anyOf", "the conversion failed, so nothing was kept") - assert.True(t, openapitest.HasDiag(diags, diag.UnpreservableConstruct), "the failure itself is reported") - assert.Empty(t, openapitest.PreservationClaims(diags), - "nothing was written under Unmodeled, so nothing may announce that it was") + require.Contains(t, union.Unmodeled, "openapi:anyOf", "the branch set is kept") + assert.JSONEq(t, `[{"type":"number"}]`, string(union.Unmodeled["openapi:anyOf"].Value)) } // TestUnionCombinators_KeepingIsOrderIndependent states the property over the @@ -182,11 +183,11 @@ func TestUnionCombinators_KeepingIsOrderIndependent(t *testing.T) { openapitest.RequireNoErrorDiags(t, diags) for _, doc := range []*ir.Document{first, last} { - union, ok := typeByName(doc, "S").(*ir.Union) - require.True(t, ok, "the position is the Union that keeps the passed-over set") - require.Len(t, union.Variants, 1, "the null branch still lifts off the variant list") - require.Equal(t, ir.TypeID("type/anonymous/components/schemas/S/oneOf/0"), union.Variants[0].Type.Target, - "the union reaches the branch's own node, or the $ref is the only lowering that does") + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "every branch is dead, so the position keeps both sets") + assert.Contains(t, scalar.Unmodeled, "openapi:anyOf") + require.Contains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/S/oneOf/0"), + "the $ref lowers the branch at its own node") } assert.Empty(t, cmp.Diff(first, last, orderInvariantIR()...), "declaring the reference before or after the union must not change the IR") @@ -245,9 +246,9 @@ func TestCollapsedUnion_KeepsItsDiscriminatorAtEveryPosition(t *testing.T) { // TestCollapsedUnion_KeepsEveryUnreadKeywordItCannotHold pins that the collapse // keeps unread all a $ref site keeps, not a discriminator rule: a format // is no more at home on a nullable reference, nor is a collection bound beside -// a reference to an object, which no array bound reads, while a null type, -// which the reference's Nullable bit carries, is, so the alias keeps nothing -// for it. +// a reference to an object, which no array bound reads. A null type beside +// the union is a body keeping the object out, so the position is null alone, +// keeping the union (docs/compilers/openapi.md#union-null-only). func TestCollapsedUnion_KeepsEveryUnreadKeywordItCannotHold(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(` Cat: {type: object, properties: {kind: {type: string}}} @@ -264,8 +265,49 @@ func TestCollapsedUnion_KeepsEveryUnreadKeywordItCannotHold(t *testing.T) { assert.Regexp(t, "no home for format, maxItems declared", openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Bounded")) - assert.Empty(t, typeByName(doc, "NullTyped").Common().Unmodeled) - assert.False(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/NullTyped")) + nullTyped, ok := typeByName(doc, "NullTyped").(*ir.Enum) + require.True(t, ok, "NullTyped is null alone; got %T", typeByName(doc, "NullTyped")) + assert.Empty(t, nullTyped.Members) + assert.Equal(t, []string{"openapi:oneOf"}, slices.Sorted(maps.Keys(nullTyped.Unmodeled))) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/NullTyped")) +} + +// TestCollapsedUnion_ANullTypeKillsEveryOtherBranch holds a type naming null +// alone beside a union of other kinds, flat or beside an allOf, and the 3.0 +// null written as a value set, to a body every branch shares no kind with: +// the position is the closed empty Enum, keeping the union once, with one +// warning that no instance satisfies it; at 3.0, whose `nullable: true` the +// nullable-inference policy reads as null for the whole conjunction, that +// warning sits at the union and names the dead branches alone +// (docs/compilers/openapi.md#union-beside-structure). +func TestCollapsedUnion_ANullTypeKillsEveryOtherBranch(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.0.3", "3.1.0"} { + null := "type: 'null'" + if version == "3.0.3" { + null = "type: object, enum: [null], nullable: true" + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer(version, ` Flat: {`+null+`, anyOf: [{type: string}, {type: integer}]} + Beside: {allOf: [{`+null+`}], anyOf: [{type: string}, {type: integer}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Flat", "Beside"} { + bottom, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s %s is the closed empty Enum; got %T", version, name, typeByName(doc, name)) + assert.True(t, bottom.Closed, name) + assert.Empty(t, bottom.Members, name) + assert.Equal(t, []string{"openapi:anyOf"}, slices.Sorted(maps.Keys(bottom.Unmodeled)), "%s %s", version, name) + warned := slices.DeleteFunc(diagsUnder(diags, "/components/schemas/"+name), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code != diag.UnsatisfiableSchema + }) + require.Len(t, warned, 1, "%s %s", version, name) + if version == "3.0.3" { + // The policy's null is a value of the position: the branches alone are reported. + assert.Equal(t, jsontext.Pointer("/components/schemas/"+name+"/anyOf"), warned[0].Provenance.Pointer, name) + assert.Contains(t, warned[0].Message, "so no instance satisfies them", name) + } + } + } } // TestCollapsedUnion_WithoutAReadDomainKeywordHoistsNothing pins that the same @@ -329,3 +371,80 @@ components: ` const nullableCat = "oneOf: [{$ref: '#/components/schemas/Cat'}, {type: 'null'}]" + +// TestCollapsedUnion_AWidenedNullReportsEachUnionsDeadBranches holds a 3.0 +// `nullable: true` beside two unions no branch of which lives, which the +// nullable-inference policy reads as null for the whole conjunction: the +// position is that null alone, and each union's dead branches are reported +// once, at its keyword, the position not, as the policy off reports both. +func TestCollapsedUnion_AWidenedNullReportsEachUnionsDeadBranches(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", + " P: {type: object, nullable: true, anyOf: [{type: string}, {type: integer}], oneOf: [{type: boolean}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + _, ok := typeByName(doc, "P").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "P")) + var reported []jsontext.Pointer + for _, diagnostic := range diagsUnder(diags, "/components/schemas/P") { + if diagnostic.Code == diag.UnsatisfiableSchema { + reported = append(reported, diagnostic.Provenance.Pointer) + } + } + assert.ElementsMatch(t, []jsontext.Pointer{"/components/schemas/P/anyOf", "/components/schemas/P/oneOf"}, reported) +} + +// TestCollapsedUnion_APassedBranchSayingNothingOfNullSharesIt holds the +// passed-over union of a conjunction the nullable-inference policy reads as +// admitting null to the branches keeping null out: beside its widening, which +// leaves null alone, one saying nothing of null, {required: [a]}, admits it, +// so it is no dead branch and draws no report, where a string beside it does; +// beside a lifted null branch, the object's Model keeps the union, no branch +// of it reported. +func TestCollapsedUnion_APassedBranchSayingNothingOfNullSharesIt(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Lifted: {allOf: [{type: object, properties: {a: {type: string}}}, {oneOf: [{type: 'null'}], anyOf: [{}, {required: [a]}]}]} + Widened: {type: object, nullable: true, anyOf: [{required: [a]}, {type: string}], oneOf: [{type: boolean}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, want := range map[string]struct { + kind ir.TypeKind + reported []string + }{ + "Lifted": {kind: ir.KindModel}, + "Widened": {ir.KindEnum, []string{"/components/schemas/Widened/anyOf: 1 of the 2 branches", "/components/schemas/Widened/oneOf: 1 of the 1 branches"}}, + } { + require.Equal(t, want.kind, typeByName(doc, name).Kind(), name) + var reported []string + for _, diagnostic := range diagsUnder(diags, "/components/schemas/"+name) { + if diagnostic.Code == diag.UnsatisfiableSchema { + reported = append(reported, string(diagnostic.Provenance.Pointer)+": "+diagnostic.Message[:strings.Index(diagnostic.Message, " branches")+len(" branches")]) + } + } + assert.ElementsMatch(t, want.reported, reported, name) + } +} + +// TestCollapsedUnion_AWidenedNullReportsTheBranchesAClosureRefuses holds a +// `nullable: true` the nullable-inference policy reads as null for the whole +// conjunction beside a closure refusing a member every branch of its union +// requires: the position admits that null alone, keeping the union, and the +// one warning sits at the union, naming each branch's refused member, the +// position not. +func TestCollapsedUnion_AWidenedNullReportsTheBranchesAClosureRefuses(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " W: {type: object, nullable: true, properties: {a: {type: string}}, additionalProperties: false, oneOf: [{required: [z]}, {required: [y]}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "W").(*ir.Enum) + require.True(t, ok, "got %T", typeByName(doc, "W")) + assert.Empty(t, enum.Members) + var warned []ir.Diagnostic + for _, diagnostic := range diagsUnder(diags, "/components/schemas/W") { + if diagnostic.Code == diag.UnsatisfiableSchema { + warned = append(warned, diagnostic) + } + } + require.Len(t, warned, 1) + assert.Equal(t, jsontext.Pointer("/components/schemas/W/oneOf"), warned[0].Provenance.Pointer) + assert.Contains(t, warned[0].Message, "requires a member the additionalProperties beside it refuses (oneOf/0: z; oneOf/1: y)") +} diff --git a/compilers/openapi/internal/schema/union_election_test.go b/compilers/openapi/internal/schema/union_competing_test.go similarity index 75% rename from compilers/openapi/internal/schema/union_election_test.go rename to compilers/openapi/internal/schema/union_competing_test.go index ec245de05..349792e45 100644 --- a/compilers/openapi/internal/schema/union_election_test.go +++ b/compilers/openapi/internal/schema/union_competing_test.go @@ -4,6 +4,8 @@ package schema_test import ( + "maps" + "slices" "strings" "testing" @@ -16,12 +18,12 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestUnion_AnAnyOfAloneDeclaringShapeIsElected pins a oneOf narrowing only +// TestUnion_AnAnyOfAloneDeclaringShapeIsChosen pins a oneOf narrowing only // what the body declares beside an anyOf of objects of their own, beside an -// allOf and on one entry of it: the anyOf is distributed, and each variant -// keeps the oneOf as validation logic, the union passed over being a conjunct +// allOf and on one entry of it: the anyOf is distributed, and the Union keeps +// the oneOf once as validation logic, the union passed over being a conjunct // of the rest. -func TestUnion_AnAnyOfAloneDeclaringShapeIsElected(t *testing.T) { +func TestUnion_AnAnyOfAloneDeclaringShapeIsChosen(t *testing.T) { t.Parallel() const keywords = "oneOf: [{required: [a]}, {maxProperties: 3}], " + "anyOf: [{type: object, properties: {d: {type: string}}}, {type: object, properties: {e: {type: string}}}]" @@ -33,12 +35,12 @@ func TestUnion_AnAnyOfAloneDeclaringShapeIsElected(t *testing.T) { for _, name := range []string{"Beside", "Entry"} { union, ok := typeByName(doc, name).(*ir.Union) require.True(t, ok, "%s distributes", name) - assert.False(t, union.Exclusive, "%s elects its anyOf", name) + assert.False(t, union.Exclusive, "%s chooses its anyOf", name) require.Len(t, union.Variants, 2) + require.Contains(t, union.Unmodeled, "openapi:oneOf", name) + assert.Equal(t, ir.ReasonValidationOnly, union.Unmodeled["openapi:oneOf"].Reason, name) for _, variant := range union.Variants { - kept := doc.Types[variant.Type.Target].Common().Unmodeled - require.Contains(t, kept, "openapi:oneOf", name) - assert.Equal(t, ir.ReasonValidationOnly, kept["openapi:oneOf"].Reason, name) + assert.NotContains(t, doc.Types[variant.Type.Target].Common().Unmodeled, "openapi:oneOf", name) } } } @@ -48,7 +50,7 @@ func TestUnion_AnAnyOfAloneDeclaringShapeIsElected(t *testing.T) { // allOf, nested one or two allOfs deeper, under a wrapper writing a type of // its own, and beside a $ref to the body: each keeps both unions, as the // oneOf declares shape against the body read without them, where read with -// them the body admits nothing and the anyOf was elected. +// them the body admits nothing and the anyOf was chosen. func TestUnion_AnEntryHoldingBothIsReadWithoutThemWhereverListed(t *testing.T) { t.Parallel() const both = "{oneOf: [{type: string}, {type: integer}], " + @@ -93,11 +95,11 @@ func TestUnion_EntriesOneAllOfDeeperJudgeEachOtherByNeither(t *testing.T) { // TestUnion_TwoUnionsAloneLowerAsOneSchemaWritingBoth pins a oneOf of objects // and an anyOf every one of them satisfies, with nothing beside them, on one -// schema, on one allOf entry and on two: each is the Union of the oneOf -// keeping the anyOf as degraded_lowering, the union passed over kept though -// the elected one says it, and an anyOf alone declaring shape is elected over -// a oneOf narrowing nothing it declares. Two oneOfs elect neither, and a keyword beside -// the two that no branch says is a body they distribute over. +// schema, on one allOf entry and on two: each is the Union of the oneOf keeping +// the anyOf as degraded_lowering, the union passed over kept though the chosen +// one says it, and an anyOf alone declaring shape is chosen over a oneOf +// narrowing nothing it declares. Two oneOfs choose neither, and a keyword +// beside the two that no branch says is a body they distribute over. func TestUnion_TwoUnionsAloneLowerAsOneSchemaWritingBoth(t *testing.T) { t.Parallel() const oneOf = "oneOf: [{type: object, properties: {p: {type: string}}}, {type: object, properties: {q: {type: string}}}]" @@ -125,7 +127,7 @@ func TestUnion_TwoUnionsAloneLowerAsOneSchemaWritingBoth(t *testing.T) { require.Contains(t, shapeless.Unmodeled, "openapi:oneOf") assert.Equal(t, ir.ReasonValidationOnly, shapeless.Unmodeled["openapi:oneOf"].Reason) _, isModel := typeByName(doc, "TwoOneOfs").(*ir.Model) - assert.True(t, isModel, "two oneOfs elect neither") + assert.True(t, isModel, "two oneOfs choose neither") required, ok := typeByName(doc, "Required").(*ir.Union) require.True(t, ok, "the oneOf distributes over the body") for _, variant := range required.Variants { @@ -135,9 +137,9 @@ func TestUnion_TwoUnionsAloneLowerAsOneSchemaWritingBoth(t *testing.T) { // TestUnion_TwoUnionsAloneSharingNoValueWarnOnceWhereverWritten pins a oneOf of // objects and an anyOf of strings with nothing beside them, on one schema and -// on two allOf entries: each is the Union of the oneOf keeping the anyOf, and -// draws one warning at the schema that the two share no value, naming the -// union it lowered as. +// on two allOf entries: every branch of the oneOf shares no kind with the +// anyOf, so each lowers as what nothing else says, keeping both, and draws one +// warning at the schema that the two share no value. func TestUnion_TwoUnionsAloneSharingNoValueWarnOnceWhereverWritten(t *testing.T) { t.Parallel() const oneOf = "oneOf: [{type: object, properties: {p: {type: string}}}, {type: object, properties: {q: {type: string}}}]" @@ -148,8 +150,8 @@ func TestUnion_TwoUnionsAloneSharingNoValueWarnOnceWhereverWritten(t *testing.T) var warned []string for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityWarning { - assert.Contains(t, diagnostic.Message, "share no value") - assert.Contains(t, diagnostic.Message, "which the union it lowered as cannot state") + assert.Contains(t, diagnostic.Message, "no value satisfies") + assert.Contains(t, diagnostic.Message, ": object") warned = append(warned, string(diagnostic.Provenance.Pointer)) } } @@ -157,7 +159,7 @@ func TestUnion_TwoUnionsAloneSharingNoValueWarnOnceWhereverWritten(t *testing.T) } // TestUnion_ANullBranchIsReadAgainstTheUnionPassedOver pins the anyOf a schema -// elects over a body admitting an object or null, beside a oneOf of objects +// chooses over a body admitting an object or null, beside a oneOf of objects // alone: its branch naming null is dead, the passed-over oneOf keeping null // out of the rest, beside the allOf as on two entries; beside a body admitting // no null its string branch is dead too. @@ -203,31 +205,35 @@ func TestUnion_TwoUnionsSharingNoValueBesideAScalarKeepBoth(t *testing.T) { } } require.Len(t, warned, 1, name) - assert.Contains(t, warned[0], "share no value", name) + assert.Contains(t, warned[0], "no value satisfies", name) } } -// TestUnion_TwoUnionEntriesBesideABodyElectByCompetingKeywords pins a oneOf +// TestUnion_TwoUnionEntriesBesideABodyChooseByCompetingKeywords pins a oneOf // of an object and a $ref to a string and an anyOf of that $ref alone, beside // a string, beside the allOf and on two entries in either order: the oneOf is -// elected, both declaring shape, though the anyOf's kinds are the body's, and -// the anyOf is kept as degraded_lowering. -func TestUnion_TwoUnionEntriesBesideABodyElectByCompetingKeywords(t *testing.T) { +// chosen, both declaring shape, though the anyOf's kinds are the body's; its +// object branch shares no kind with the string, so it is dead, and the one +// live branch, its $ref, is the position's node, keeping it, with the anyOf +// kept as degraded_lowering. +func TestUnion_TwoUnionEntriesBesideABodyChooseByCompetingKeywords(t *testing.T) { t.Parallel() const oneOf = "oneOf: [{type: object, properties: {x: {type: string}}}, {$ref: '#/components/schemas/Kstr'}]" const anyOf = "anyOf: [{$ref: '#/components/schemas/Kstr'}]" - doc, _ := schema.LowerSpec(t, openapitest.ComponentSpec(` Kstr: {type: string} + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` Kstr: {type: string} Beside: {allOf: [{type: string}], `+oneOf+`, `+anyOf+`} TwoEntries: {allOf: [{type: string}, {`+oneOf+`}, {`+anyOf+`}]} AnyOfFirst: {allOf: [{type: string}, {`+anyOf+`}, {`+oneOf+`}]} `)) - for _, name := range []string{"Beside", "TwoEntries", "AnyOfFirst"} { - union, ok := typeByName(doc, name).(*ir.Union) - require.True(t, ok, "%s is a Union", name) - assert.True(t, union.Exclusive, "%s elects the oneOf", name) - assert.Len(t, union.Variants, 2, name) - require.Contains(t, union.Unmodeled, "openapi:anyOf", name) - assert.Equal(t, ir.ReasonDegradedLowering, union.Unmodeled["openapi:anyOf"].Reason, name) + for name, oneOfAt := range map[string]string{"Beside": "", "TwoEntries": "/allOf/1", "AnyOfFirst": "/allOf/2"} { + node, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s is its one live branch's node; got %T", name, typeByName(doc, name)) + assert.Equal(t, &ir.TypeRef{Target: componentID("Kstr")}, node.Base, name) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name+oneOfAt+"/oneOf"), + "%s chooses the oneOf, whose object branch is dead", name) + assert.Equal(t, ir.ReasonDegradedLowering, node.Unmodeled["openapi:oneOf"].Reason, "%s keeps its dead branch", name) + require.Contains(t, node.Unmodeled, "openapi:anyOf", name) + assert.Equal(t, ir.ReasonDegradedLowering, node.Unmodeled["openapi:anyOf"].Reason, name) } } @@ -254,26 +260,37 @@ func TestUnion_TwoShapelessUnionsSharingNoValueBesideTheirBodyWarn(t *testing.T) } for _, name := range []string{"Flat", "Beside", "Shared", "SharedBeside", "Lists"} { require.Len(t, warned[name], 1, name) - assert.Contains(t, warned[name][0], "share no value", name) + assert.Contains(t, warned[name][0], "no value satisfies", name) } } -// TestUnion_AnEntryElectingAUnionOfNullAloneIsNamedByItsNull holds that the +// TestUnion_AnEntryChoosingAUnionOfNullAloneIsNamedByItsNull holds that the // report of conjuncts sharing no value names an entry writing a oneOf and an -// anyOf, read as its own keywords and the union it elects, by the null that +// anyOf, read as its own keywords and the union it chooses, by the null that // union admits where it admits null alone, whatever the union it passes over -// admits. -func TestUnion_AnEntryElectingAUnionOfNullAloneIsNamedByItsNull(t *testing.T) { +// admits. Beside an object, which keeps null out, the nullable-inference +// policy lifts that null onto the reference to the object's Model, which keeps +// the union passed over and warns of nothing. +func TestUnion_AnEntryChoosingAUnionOfNullAloneIsNamedByItsNull(t *testing.T) { t.Parallel() - _, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Str: {allOf: [{type: string}, {oneOf: [{type: 'null'}], anyOf: [{type: string}]}]} + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Str: {allOf: [{type: string}, {oneOf: [{type: 'null'}], anyOf: [{type: string}]}]} Nest: {allOf: [{type: string}, {allOf: [{oneOf: [{type: 'null'}], anyOf: [{type: string}]}]}]} Obj: {allOf: [{type: object}, {oneOf: [{type: 'null'}], anyOf: [{type: 'null'}, {type: object, required: [x]}]}]} `)) want := map[string]string{ "Str": "(allOf/0: string, allOf/1: null, allOf/1/anyOf: string)", "Nest": "(allOf/0: string, allOf/1/allOf/0: null, allOf/1/allOf/0/anyOf: string)", - "Obj": "(allOf/0: object, allOf/1: null, allOf/1/anyOf: object)", } + obj, ok := typeByName(doc, "Obj").(*ir.Model) + require.True(t, ok, "Obj is its object; got %T", typeByName(doc, "Obj")) + assert.Equal(t, ir.ReasonValidationOnly, obj.Unmodeled["openapi:anyOf"].Reason, "Obj keeps the anyOf it passes over") + var objWarned []string + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityWarning && strings.Contains(string(diagnostic.Provenance.Pointer), "/Obj") { + objWarned = append(objWarned, string(diagnostic.Provenance.Pointer)+": "+diagnostic.Message) + } + } + assert.Empty(t, objWarned, "Obj warns of nothing: its object branch lives beside the object") for name, names := range want { var warned []string for _, diagnostic := range diags { @@ -339,9 +356,9 @@ func TestUnion_TwoUnionsSharingNoMemberWarnOnceWhereverWritten(t *testing.T) { } } require.Len(t, warned, 1, name) - assert.Contains(t, warned[0], "share no value", name) - assert.Contains(t, warned[0], "anyOf: 1 value", name) - assert.Contains(t, warned[0], "oneOf: 1 value", name) + assert.Contains(t, warned[0], "no value satisfies", name) + assert.Contains(t, warned[0], "anyOf: one of [", name) + assert.Contains(t, warned[0], "oneOf: one of [", name) } } @@ -373,8 +390,9 @@ func TestUnion_APairAdmitsNullOnlyWhereBothUnionsMay(t *testing.T) { // TestUnion_TwoUnionsSharingNoMemberBesideAScalarLowerAsTheBody pins a oneOf // and an anyOf whose enums share no member beside a string body, beside its -// keywords, beside an allOf of it, on one entry and on two: each is the -// string keeping both unions, with one warning that they share no value. +// keywords, beside an allOf of it, on one entry and on two: the oneOf's branch +// shares the string, so each is the oneOf's Union keeping the anyOf it passes +// over, with one warning that they share no value. func TestUnion_TwoUnionsSharingNoMemberBesideAScalarLowerAsTheBody(t *testing.T) { t.Parallel() const one, anyOf = "oneOf: [{type: string, enum: [a]}]", "anyOf: [{type: string, enum: [b]}]" @@ -384,10 +402,10 @@ func TestUnion_TwoUnionsSharingNoMemberBesideAScalarLowerAsTheBody(t *testing.T) TwoEntries: {allOf: [{type: string}, {`+one+`}, {`+anyOf+`}]} `)) for _, name := range []string{"Flat", "Beside", "OneEntry", "TwoEntries"} { - scalar, ok := typeByName(doc, name).(*ir.Scalar) - require.True(t, ok, "%s is the string its body gives", name) - assert.Contains(t, scalar.Unmodeled, "openapi:oneOf", name) - assert.Contains(t, scalar.Unmodeled, "openapi:anyOf", name) + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s is the oneOf's Union", name) + assert.Len(t, union.Variants, 1, name) + assert.Contains(t, union.Unmodeled, "openapi:anyOf", name) var warned []string for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityWarning && strings.HasSuffix(string(diagnostic.Provenance.Pointer), "/"+name) { @@ -395,16 +413,16 @@ func TestUnion_TwoUnionsSharingNoMemberBesideAScalarLowerAsTheBody(t *testing.T) } } require.Len(t, warned, 1, name) - assert.Contains(t, warned[0], "share no value", name) + assert.Contains(t, warned[0], "no value satisfies", name) } } -// TestUnion_AnElectedUnionOfAPairIsReportedAsTheUnionItLowersTo pins the report -// of an anyOf kept on the second entry of an allOf whose first elects a oneOf +// TestUnion_AChosenUnionOfAPairIsReportedAsTheUnionItLowersTo pins the report +// of an anyOf kept on the second entry of an allOf whose first chooses a oneOf // of a string and null: the position is the Union of the oneOf, not collapsed, // as one schema writing both is, and the report names that Union, never a // nullable reference to the oneOf's one non-null branch. -func TestUnion_AnElectedUnionOfAPairIsReportedAsTheUnionItLowersTo(t *testing.T) { +func TestUnion_AChosenUnionOfAPairIsReportedAsTheUnionItLowersTo(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` Two: {allOf: [{oneOf: [{type: string}, {type: 'null'}]}, {anyOf: [{type: string}]}]} `)) @@ -422,7 +440,7 @@ func TestUnion_AnElectedUnionOfAPairIsReportedAsTheUnionItLowersTo(t *testing.T) } // TestUnion_ANullBranchOfAPairIsDeadWhereTheOtherKeepsNullOut pins a branch of -// the anyOf an object or null elects that is a $ref to null alone: no variant +// the anyOf an object or null chooses that is a $ref to null alone: no variant // where the oneOf // passed over keeps null out, kept with the warning, an inline null branch // beside it lifted as ever; a variant where the oneOf admits null. @@ -441,12 +459,13 @@ func TestUnion_ANullBranchOfAPairIsDeadWhereTheOtherKeepsNullOut(t *testing.T) { _, kept := union.Unmodeled["openapi:anyOf/"+map[string]string{"Dead": "1", "Both": "2", "Open": "1"}[name]] assert.Equal(t, variants == 1, kept, name) } - assert.True(t, openapitest.HasDiagCodeAt(diags, diag.DegradedConstruct, "/components/schemas/Dead")) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Dead")) } // TestUnion_ADeadNullBranchOfAPairIsReportedByTheNullKeptOut holds that the // warning for a branch of a pair admitting nothing but a null the rest keeps -// out says so, beside a body of strings or none, where no body admits objects. +// out names it so, at the union, beside a body of strings or none, where no +// body admits objects. func TestUnion_ADeadNullBranchOfAPairIsReportedByTheNullKeptOut(t *testing.T) { t.Parallel() const pair = "oneOf: [{type: string}], anyOf: [{type: string, minLength: 1}, {$ref: '#/components/schemas/Null'}]" @@ -456,9 +475,9 @@ func TestUnion_ADeadNullBranchOfAPairIsReportedByTheNullKeptOut(t *testing.T) { Beside: {allOf: [{type: [string, 'null']}], `+pair+`} `)) for name, want := range map[string]string{ - "Flat": "1 of the 2 branches of this oneOf admits nothing but null, which the rest of this schema keeps out (oneOf/0", - "Body": "1 of the 2 branches of this anyOf admits nothing but null, which the rest of this schema keeps out (anyOf/1", - "Beside": "1 of the 2 branches of this anyOf admits nothing but null, which the rest of this schema keeps out (anyOf/1", + "Flat/oneOf": "1 of the 2 branches of this oneOf shares no value with the rest of the schema (oneOf/0: null)", + "Body/anyOf": "1 of the 2 branches of this anyOf shares no value with the rest of the schema (anyOf/1: null)", + "Beside/anyOf": "1 of the 2 branches of this anyOf shares no value with the rest of the schema (anyOf/1: null)", } { var messages []string for _, diagnostic := range diags { @@ -471,12 +490,12 @@ func TestUnion_ADeadNullBranchOfAPairIsReportedByTheNullKeptOut(t *testing.T) { } } -// TestUnion_APairWhoseElectedVariantsAllAdmitNullAloneKeepsThem holds that -// where every variant of the union a position elects admits null alone and -// the other union keeps null out, none is read as dead: the two share no -// value, which their one warning says, and the Union keeps its variants, as -// one with none would hold no value, in every spelling. -func TestUnion_APairWhoseElectedVariantsAllAdmitNullAloneKeepsThem(t *testing.T) { +// TestUnion_APairWhoseChosenVariantsAllAdmitNullAloneKeepsThem holds that +// where every variant of the union a position chooses admits null alone and +// the other union keeps null out, every branch is dead: the two share no +// value, which their one warning says, and the position lowers as what +// nothing else says, keeping both, in every spelling. +func TestUnion_APairWhoseChosenVariantsAllAdmitNullAloneKeepsThem(t *testing.T) { t.Parallel() const null, other = "{$ref: '#/components/schemas/Null'}", "anyOf: [{$ref: '#/components/schemas/P'}, {type: string}]" doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Null: {type: 'null'} @@ -493,17 +512,17 @@ func TestUnion_APairWhoseElectedVariantsAllAdmitNullAloneKeepsThem(t *testing.T) } } for _, name := range []string{"Flat", "WithNull", "One", "Two"} { - union, ok := typeByName(doc, name).(*ir.Union) - require.True(t, ok, name) - assert.Len(t, union.Variants, 1, name) + scalar, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s is the top type; got %T", name, typeByName(doc, name)) + assert.NotEmpty(t, scalar.Unmodeled, "%s keeps both unions", name) assert.Equal(t, 1, warned[name], name) } } // TestUnion_APrincipalEntryWhoseUnionSharesNoKindWithItsTypeWarnsOnce holds -// that an allOf entry writing a type and a oneOf sharing no kind, standing for -// the position alone or beside an annotation, draws the one warning that the -// conjuncts share no value at the position, not a second at the entry. +// that an allOf entry writing a type and a oneOf sharing no kind, taking the +// place of the position alone or beside an annotation, draws the one warning +// that the conjuncts share no value at the position, not a second at the entry. func TestUnion_APrincipalEntryWhoseUnionSharesNoKindWithItsTypeWarnsOnce(t *testing.T) { t.Parallel() _, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Alone: {allOf: [{type: integer, oneOf: [{type: string}, {type: boolean}]}]} @@ -539,12 +558,12 @@ func TestUnion_APairOnTwoEntriesReadsAUnionBranchsNull(t *testing.T) { } } -// TestUnion_APairElectingAValueSetOfNullAloneWarnsWhereItSharesNoValue holds -// that a oneOf of null alone written as a value set, elected over an anyOf +// TestUnion_APairChoosingAValueSetOfNullAloneWarnsWhereItSharesNoValue holds +// that a oneOf of null alone written as a value set, chosen over an anyOf // sharing no value with it, draws the one warning that the conjuncts share no // value on one schema, on entries of an allOf and beside an allOf of an object // body, and that two sharing the null draw none. -func TestUnion_APairElectingAValueSetOfNullAloneWarnsWhereItSharesNoValue(t *testing.T) { +func TestUnion_APairChoosingAValueSetOfNullAloneWarnsWhereItSharesNoValue(t *testing.T) { t.Parallel() _, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Flat: {oneOf: [{enum: [null]}], anyOf: [{type: string}]} Const: {oneOf: [{const: null}], anyOf: [{type: integer}]} @@ -561,16 +580,16 @@ func TestUnion_APairElectingAValueSetOfNullAloneWarnsWhereItSharesNoValue(t *tes } for _, name := range []string{"Flat", "Const", "Entries", "BesideObject"} { require.Len(t, warned[name], 1, name) - assert.Contains(t, warned[name][0], "share no value", name) + assert.Contains(t, warned[name][0], "no value satisfies", name) } assert.Empty(t, warned["Shared"]) } // TestUnion_TwoUnionsSharingNullAloneBesideAnInlineBodyAdmittingNullAreKept // pins a oneOf of an object or null and an anyOf of a string or null, which -// share null alone, beside an inline string or null: beside the allOf, on one -// entry and on two, a use of the body keeping both unions, as beside a $ref -// to such a body, distributing neither; with no body, the oneOf's Union. +// share null alone, beside an inline string or null, beside the allOf, on one +// entry and on two, and with no body: only null survives, so each is the +// closed empty Enum behind a nullable reference, keeping both unions. func TestUnion_TwoUnionsSharingNullAloneBesideAnInlineBodyAdmittingNullAreKept(t *testing.T) { t.Parallel() const one, anyOf = "oneOf: [{type: object, properties: {x: {type: string}}}, {type: 'null'}]", "anyOf: [{type: string}, {type: 'null'}]" @@ -579,14 +598,12 @@ func TestUnion_TwoUnionsSharingNullAloneBesideAnInlineBodyAdmittingNullAreKept(t TwoEntries: {allOf: [{type: [string, 'null']}, {`+one+`}, {`+anyOf+`}]} NoBody: {allOf: [{`+one+`}, {`+anyOf+`}]} `)) - for _, name := range []string{"Beside", "OneEntry", "TwoEntries"} { - scalar, ok := typeByName(doc, name).(*ir.Scalar) - require.True(t, ok, "%s is a use of the body", name) - assert.Contains(t, scalar.Unmodeled, "openapi:oneOf", name) - assert.Contains(t, scalar.Unmodeled, "openapi:anyOf", name) + for _, name := range []string{"Beside", "OneEntry", "TwoEntries", "NoBody"} { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s admits null alone", name) + assert.Empty(t, enum.Members, name) + assert.Len(t, enum.Unmodeled, 2, "%s keeps both unions: %v", name, enum.Unmodeled) } - _, ok := typeByName(doc, "NoBody").(*ir.Union) - assert.True(t, ok, "with no body to use the oneOf is elected") } // TestUnion_AShapelessUnionSharingNoKindWithAScalarWarnsBesideItsKeywords pins @@ -621,9 +638,9 @@ func TestUnion_TwoUnionsApartAreNamedTheOneOfFirst(t *testing.T) { False: {anyOf: [{type: integer}], oneOf: [false]} `)) want := map[string]string{ - "Flat": "(oneOf: 1 value, anyOf: 1 value)", - "Mixed": "(oneOf: 1 value, allOf/0/anyOf: 1 value)", - "Entries": "(allOf/0/anyOf: 1 value, allOf/1/oneOf: 1 value)", + "Flat": `(oneOf: one of ["a"], anyOf: one of ["b"])`, + "Mixed": `(oneOf: one of ["a"], allOf/0/anyOf: one of ["b"])`, + "Entries": `(allOf/0/anyOf: one of ["b"], allOf/1/oneOf: one of ["a"])`, "False": "(oneOf: no value, anyOf: integer)", } for name, names := range want { @@ -646,12 +663,8 @@ func TestUnion_AConstNullPairBesideARefWarnsOnceWhereverWritten(t *testing.T) { t.Parallel() const one = "oneOf: [{const: null}]" const anyOf = "anyOf: [{type: integer}, {type: object, properties: {p: {type: string}}, required: [p]}]" - _, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` T: {type: object, properties: {a: {type: string}}} - Flat: {$ref: '#/components/schemas/T', `+one+`, `+anyOf+`} - Beside: {allOf: [{$ref: '#/components/schemas/T'}], `+one+`, `+anyOf+`} - OneEntry: {allOf: [{$ref: '#/components/schemas/T'}, {`+one+`, `+anyOf+`}]} - TwoEntries: {allOf: [{$ref: '#/components/schemas/T'}, {`+one+`}, {`+anyOf+`}]} -`)) + spellings := openapitest.Spellings("$ref: '#/components/schemas/T'", one, anyOf) + _, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" T: {type: object, properties: {a: {type: string}}}\n"+componentBlock(spellings))) warned := map[string][]string{} for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityWarning { @@ -659,28 +672,34 @@ func TestUnion_AConstNullPairBesideARefWarnsOnceWhereverWritten(t *testing.T) { warned[name] = append(warned[name], diagnostic.Message) } } - for _, name := range []string{"Flat", "Beside", "OneEntry", "TwoEntries"} { + for name := range spellings { require.Len(t, warned[name], 1, name) - assert.Contains(t, warned[name][0], "share no value", name) + assert.Contains(t, warned[name][0], "no value satisfies", name) } } +// componentBlock writes each spelling as a component of its name, in the order +// of the names. +func componentBlock(spellings map[string]string) string { + var block strings.Builder + for _, name := range slices.Sorted(maps.Keys(spellings)) { + block.WriteString(" " + name + ": " + spellings[name] + "\n") + } + return block.String() +} + // nullableBodySpellings writes a oneOf and an anyOf beside an object admitting -// null flat, beside an allOf of it, on one entry and on two. -func nullableBodySpellings(oneOf, anyOf string) string { - const body = "type: [object, 'null'], properties: {a: {type: string}}" - return ` Flat: {` + body + `, ` + oneOf + `, ` + anyOf + `} - Beside: {allOf: [{` + body + `}], ` + oneOf + `, ` + anyOf + `} - OneEntry: {allOf: [{` + body + `}, {` + oneOf + `, ` + anyOf + `}]} - TwoEntries: {allOf: [{` + body + `}, {` + oneOf + `}, {` + anyOf + `}]} -` +// null in every placement openapitest.Spellings gives. +func nullableBodySpellings(oneOf, anyOf string) map[string]string { + return openapitest.Spellings("type: [object, 'null'], properties: {a: {type: string}}", oneOf, anyOf) } // keepsBothOnItsModel asserts that each spelling nullableBodySpellings writes // is the body's Model keeping both unions, and returns its warnings by name. func keepsBothOnItsModel(t *testing.T, oneOf, anyOf string) map[string][]string { t.Helper() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(nullableBodySpellings(oneOf, anyOf))) + spellings := nullableBodySpellings(oneOf, anyOf) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(componentBlock(spellings))) warned := map[string][]string{} for _, diagnostic := range diags { if diagnostic.Severity == ir.SeverityWarning { @@ -688,7 +707,7 @@ func keepsBothOnItsModel(t *testing.T, oneOf, anyOf string) map[string][]string warned[name] = append(warned[name], diagnostic.Message) } } - for _, name := range []string{"Flat", "Beside", "OneEntry", "TwoEntries"} { + for name := range spellings { model, ok := typeByName(doc, name).(*ir.Model) require.True(t, ok, "%s is the body's Model", name) assert.Contains(t, model.Unmodeled, "openapi:oneOf", name) @@ -703,21 +722,36 @@ func keepsBothOnItsModel(t *testing.T, oneOf, anyOf string) map[string][]string // position is the body keeping both, with one warning in each spelling. func TestUnion_AUnionPassedOverLeavingTheBodyNullAloneIsApartWhereverWritten(t *testing.T) { t.Parallel() - warned := keepsBothOnItsModel(t, "oneOf: [{oneOf: [{type: string}, {type: integer}]}]", - "anyOf: [{type: string}, {type: 'null'}]") - for _, name := range []string{"Flat", "Beside", "OneEntry", "TwoEntries"} { + const oneOf, anyOf = "oneOf: [{oneOf: [{type: string}, {type: integer}]}]", "anyOf: [{type: string}, {type: 'null'}]" + warned := keepsBothOnItsModel(t, oneOf, anyOf) + for name := range nullableBodySpellings(oneOf, anyOf) { require.Len(t, warned[name], 1, name) - assert.Contains(t, warned[name][0], "share no value", name) + assert.Contains(t, warned[name][0], "no value satisfies", name) } } -// TestUnion_APairSharingNullAloneWithANullableBodyIsItsModelWhereverWritten +// TestUnion_APairSharingNullAloneWithANullableBodyIsNullAloneWhereverWritten // pins a oneOf of an object or null and an anyOf of a string or null beside -// an object admitting null, all three sharing null alone: the position is the -// body's Model keeping both, with no warning, in each spelling. -func TestUnion_APairSharingNullAloneWithANullableBodyIsItsModelWhereverWritten(t *testing.T) { +// an object admitting null, all three sharing null alone: only null survives, +// so the position is the closed empty Enum behind a nullable reference keeping +// both, in each spelling, the one warning naming at the oneOf its object +// branch, which the rest leaves dead. +func TestUnion_APairSharingNullAloneWithANullableBodyIsNullAloneWhereverWritten(t *testing.T) { t.Parallel() - warned := keepsBothOnItsModel(t, "oneOf: [{type: object, properties: {x: {type: string}}}, {type: 'null'}]", - "anyOf: [{type: string}, {type: 'null'}]") - assert.Empty(t, warned) + spellings := nullableBodySpellings( + "oneOf: [{type: object, properties: {x: {type: string}}}, {type: 'null'}]", "anyOf: [{type: string}, {type: 'null'}]") + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(componentBlock(spellings))) + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityWarning { + assert.True(t, strings.HasSuffix(string(diagnostic.Provenance.Pointer), "/oneOf"), "%s: %s", diagnostic.Provenance.Pointer, diagnostic.Message) + assert.Contains(t, diagnostic.Message, "oneOf/0: object") + } + } + for name := range spellings { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s admits null alone", name) + assert.Empty(t, enum.Members, name) + assert.Contains(t, enum.Unmodeled, "openapi:oneOf", name) + assert.Contains(t, enum.Unmodeled, "openapi:anyOf", name) + } } diff --git a/compilers/openapi/internal/schema/union_dead_fold_test.go b/compilers/openapi/internal/schema/union_dead_fold_test.go new file mode 100644 index 000000000..40ef9ecc1 --- /dev/null +++ b/compilers/openapi/internal/schema/union_dead_fold_test.go @@ -0,0 +1,109 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestUnion_NoLiveBranchDrawsOneFindingSayingWhatItKeeps pins that a position +// whose conjunction chooses a union no branch of which lives draws one +// finding, the warning at the position that no value satisfies it, which +// names the culprits, says what it lowered as and which unions it keeps by +// their paths, and asks for one to be corrected; no union draws an info of +// its own, wherever it is written, a pair written with nothing beside it among +// them (docs/compilers/openapi.md#union-beside-structure). +func TestUnion_NoLiveBranchDrawsOneFindingSayingWhatItKeeps(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Pair: {oneOf: [{type: string}], anyOf: [{type: integer}]} + AllDead: {type: string, oneOf: [{type: integer}, {type: boolean}]} + TwoUnions: {type: string, oneOf: [{type: integer}, {type: boolean}], anyOf: [{type: number}, {type: array}]} + Refused: {type: object, properties: {a: {type: string}}, additionalProperties: false, oneOf: [{required: [b]}, {required: [c]}]} + Principal: {allOf: [{type: string, oneOf: [{type: integer}, {type: boolean}]}]} + Entry: {allOf: [{type: object, properties: {a: {type: string}}}, {oneOf: [{type: object}], anyOf: [{type: string}, {type: integer}]}]} + Undecided: {allOf: [{oneOf: [{type: string}]}, {anyOf: [{type: integer}]}]} + UndecidedTyped: {type: string, format: uuid, allOf: [{oneOf: [{type: integer}]}], anyOf: [{type: boolean}]} + UndecidedList: {type: array, items: {type: string}, allOf: [{oneOf: [{type: integer}]}], anyOf: [{type: boolean}]} +`)) + for name, want := range map[string]string{ + "Pair": `no value satisfies both the oneOf and the anyOf (oneOf: string, anyOf: integer); lowered as a node of kind "scalar", ` + + "its oneOf and anyOf kept verbatim under Unmodeled — remove or correct one of them", + "AllDead": `no value satisfies both the type and the oneOf (type: string, oneOf: integer or boolean); lowered as a node of ` + + `kind "scalar", its oneOf kept verbatim under Unmodeled — remove or correct one of them`, + "TwoUnions": `; lowered as a node of kind "scalar", its oneOf and anyOf kept verbatim under Unmodeled — `, + "Refused": `no value satisfies this schema: every branch of its oneOf requires a member the additionalProperties beside ` + + `it refuses (oneOf/0: b; oneOf/1: c); lowered as a node of kind "model", its oneOf kept verbatim under Unmodeled`, + "Principal": `; lowered as a node of kind "scalar", its allOf/0/oneOf kept verbatim under Unmodeled — `, + "Entry": `; lowered as a node of kind "model", its allOf/1/oneOf and allOf/1/anyOf kept verbatim under Unmodeled — `, + // An allOf choosing no entry is what was built, not the rule. + "Undecided": `; lowered as the top type, its allOf/0/oneOf and allOf/1/anyOf kept verbatim under Unmodeled — `, + "UndecidedTyped": `; lowered as a uuid, its anyOf and allOf/0/oneOf kept verbatim under Unmodeled — `, + "UndecidedList": `; lowered as a node of kind "list", its anyOf and allOf/0/oneOf kept verbatim under Unmodeled — `, + } { + at := "/components/schemas/" + name + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, at), want, name) + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityInfo && diagnostic.Code == diag.DegradedConstruct { + assert.NotContains(t, string(diagnostic.Provenance.Pointer), at+"/", "%s: no union draws an info of its own", name) + assert.NotEqual(t, at, string(diagnostic.Provenance.Pointer), "%s: no info beside the warning", name) + } + } + } +} + +// TestUnion_ABottomKeepingAUnionDrawsOneFindingSayingSo pins that a position +// whose conjuncts share no value and lowers to the bottom, keeping a union it +// writes itself, draws one finding: the warning that no value satisfies it, +// saying it keeps the union, whether the union is kept as validation logic +// or as a degraded lowering, and no info of the union's own at the position, +// at a component and at a property alike +// (docs/compilers/openapi.md#allof-disjoint-conjuncts). +func TestUnion_ABottomKeepingAUnionDrawsOneFindingSayingSo(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Bad: {allOf: [{type: string}, {type: integer}]} + BesideRef: {$ref: '#/components/schemas/Bad', anyOf: [{type: boolean}]} + BesideAllOf: {allOf: [{$ref: '#/components/schemas/Bad'}], oneOf: [{type: boolean}]} + Typed: {type: string, allOf: [{type: integer}], oneOf: [{type: object}, {type: array}]} + Formats: {type: string, allOf: [{type: integer}], oneOf: [{format: uuid}, {format: date}]} + Holder: {type: object, properties: {p: {$ref: '#/components/schemas/Bad', anyOf: [{type: boolean}]}}} +`)) + for at, testCase := range map[string]struct { + keyword string + reason ir.UnmodeledReason + }{ + "/components/schemas/BesideRef": {"anyOf", ir.ReasonValidationOnly}, + "/components/schemas/BesideAllOf": {"oneOf", ir.ReasonValidationOnly}, + "/components/schemas/Typed": {"oneOf", ir.ReasonValidationOnly}, + "/components/schemas/Formats": {"oneOf", ir.ReasonDegradedLowering}, + "/components/schemas/Holder/properties/p": {"anyOf", ir.ReasonValidationOnly}, + } { + want := "; lowered as the closed model with no member a false schema lowers to, its " + testCase.keyword + " kept verbatim under Unmodeled — " + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, at), want, at) + for _, diagnostic := range diags { + if diagnostic.Severity == ir.SeverityInfo { + assert.NotEqual(t, at, string(diagnostic.Provenance.Pointer), "%s: no info beside the warning: %s", at, diagnostic.Message) + } + } + kept, ok := unmodeledAt(doc, at)["openapi:"+testCase.keyword] + if assert.True(t, ok, "%s keeps its %s", at, testCase.keyword) { + assert.Equal(t, testCase.reason, kept.Reason, at) + } + } +} + +// unmodeledAt returns the Unmodeled of the node doc holds at pointer. +func unmodeledAt(doc *ir.Document, pointer string) ir.Unmodeled { + for _, typeDef := range doc.Types { + if string(typeDef.Common().Provenance.Pointer) == pointer { + return typeDef.Common().Unmodeled + } + } + return nil +} diff --git a/compilers/openapi/internal/schema/union_guards_test.go b/compilers/openapi/internal/schema/union_guards_test.go new file mode 100644 index 000000000..cb9f62115 --- /dev/null +++ b/compilers/openapi/internal/schema/union_guards_test.go @@ -0,0 +1,48 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "maps" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestValueSetsIntersect_ARefPrincipalLowersNoIntersection holds the choice to +// the $ref it chooses where value sets beside it share members, none lying +// within the other: the position is a use of the $ref, keeping each set, and no +// Enum of what the sets share, which the intersection of inline sets alone +// lowers to (valueSetsIntersect). +func TestValueSetsIntersect_ARefPrincipalLowersNoIntersection(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Str: {type: string} + S: {allOf: [{$ref: '#/components/schemas/Str'}, {enum: [a, b]}, {enum: [b, c]}]} +`)) + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "a use of the $ref: got %T", typeByName(doc, "S")) + require.NotNil(t, scalar.Base) + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Str"), scalar.Base.Target) + assert.Equal(t, []string{"openapi:allOf/1", "openapi:allOf/2"}, slices.Sorted(maps.Keys(scalar.Unmodeled)), "each set is kept") +} + +// TestUnionCollapses_AUnionLeavingNullAloneCollapsesNot holds a union of one +// branch beside a null one, on an allOf entry, whose branches share nothing +// with the rest but null, none dead, to the null alone it leaves: the +// position is the Enum of null, and a type the rest writes is read by it, +// where read as a collapse to the one non-null branch the type was kept too +// (unionCollapses). +func TestUnionCollapses_AUnionLeavingNullAloneCollapsesNot(t *testing.T) { + t.Parallel() + doc, _ := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " S: {allOf: [{type: [string, 'null'], pattern: '^a'}, {anyOf: [{type: [integer, 'null']}, {type: 'null'}]}]}\n")) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "null alone: got %T", typeByName(doc, "S")) + assert.Equal(t, []string{"openapi:anyOf", "openapi:pattern"}, slices.Sorted(maps.Keys(enum.Unmodeled))) +} diff --git a/compilers/openapi/internal/schema/union_internal_test.go b/compilers/openapi/internal/schema/union_internal_test.go index 9f3e6dc3b..775a5d377 100644 --- a/compilers/openapi/internal/schema/union_internal_test.go +++ b/compilers/openapi/internal/schema/union_internal_test.go @@ -45,26 +45,28 @@ func TestAllNullUnion_NoBranchesFalse(t *testing.T) { // which a reader consuming what the branches say would then drop. func TestBranchesSay_NoBranchesSayNothing(t *testing.T) { t.Parallel() - js := &oas3.JSONSchema[oas3.Referenceable]{} - valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader("{type: string, format: uuid, enum: [a]}"), js) + jsonSchema := &oas3.JSONSchema[oas3.Referenceable]{} + valErrs, err := marshaller.Unmarshal(t.Context(), strings.NewReader("{type: string, format: uuid, enum: [a]}"), jsonSchema) require.NoError(t, err) require.Empty(t, valErrs, "the fixture parses cleanly") lowerer := NewRawLowerer(&soa.OpenAPI{}) - schema := StandaloneSchema(js.GetSchema()) - assert.Empty(t, branchesSay(lowerer.Ctx, schema, schema), "no branch says a keyword the schema writes") + schema := StandaloneSchema(jsonSchema.GetSchema()) + assert.Empty(t, keywordsBranchesRestate(lowerer.Ctx, schema, schema), "no branch says a keyword the schema writes") } -// TestPreserveNullOnlyUnion_NothingToKeep covers a node whose -// schema declares neither oneOf nor anyOf: preserveBranchSets keeps nothing, +// TestKeepNullOnlyUnion_NothingToKeep covers a node whose +// schema declares neither oneOf nor anyOf: keepBranchSets keeps nothing, // so nothing announces a keeping that never happened. lowerNullOnlyUnion never // reaches this — its caller always has one of the two — so only a direct call // drives it, the same way TestAllNullUnion_NoBranchesFalse drives its sibling // guard. -func TestPreserveNullOnlyUnion_NothingToKeep(t *testing.T) { +func TestKeepNullOnlyUnion_NothingToKeep(t *testing.T) { t.Parallel() lowerer := NewRawLowerer(&soa.OpenAPI{}) - diags := preserveNullOnlyUnion(lowerer.Ctx, &ir.Scalar{}, StandaloneSchema(&oas3.Schema{}), "/components/schemas/S") - assert.Empty(t, diags, "nothing was kept, so nothing is announced") + var unmodeled ir.Unmodeled + reports := keepNullOnlyUnion(lowerer.Ctx, &unmodeled, StandaloneSchema(&oas3.Schema{}), StandaloneSchema(&oas3.Schema{}), "/components/schemas/S") + assert.Empty(t, reports, "nothing was kept, so nothing is announced") + assert.Empty(t, unmodeled) } // TestComposeMixin_NeedsAModel drives the state its callers cannot produce, a @@ -76,16 +78,16 @@ func TestComposeMixin_NeedsAModel(t *testing.T) { scalar := &ir.Scalar{ID: "type/anonymous/scalar"} assert.Empty(t, composeMixin(lowerer.Ctx, lowerer.Types, 0, scalar, nil, "/p"), "no union to compose") - assertInternalInvariant(t, composeMixin(lowerer.Ctx, lowerer.Types, 0, scalar, &unionAt{holder: &statement.Schema{}, at: "/p"}, "/p")) + assertInternalInvariant(t, composeMixin(lowerer.Ctx, lowerer.Types, 0, scalar, &loweredUnionSite{holder: &statement.Schema{}, pointer: "/p"}, "/p")) } // TestLowerSubtypeUnion_NeedsItsAllOf drives the state a routed subtype never // reaches, as a discriminator routes to a schema through the allOf naming its -// ancestor: one electing no allOf lowers, and composes no union. +// ancestor: one choosing no allOf lowers, and composes no union. func TestLowerSubtypeUnion_NeedsItsAllOf(t *testing.T) { t.Parallel() lowerer := NewRawLowerer(&soa.OpenAPI{}) schema := &statement.Schema{} - _, diags := lowerSubtypeUnion(lowerer.Ctx, lowerer.Types, TopLevelDepth, schema, unionAt{holder: schema, at: "/components/schemas/S"}, "/components/schemas/S", nil) + _, diags := lowerSubtypeUnion(lowerer.Ctx, lowerer.Types, TopLevelDepth, schema, loweredUnionSite{holder: schema, pointer: "/components/schemas/S"}, "/components/schemas/S") assertInternalInvariant(t, diags) } diff --git a/compilers/openapi/internal/schema/union_null_policy_test.go b/compilers/openapi/internal/schema/union_null_policy_test.go new file mode 100644 index 000000000..4a845f809 --- /dev/null +++ b/compilers/openapi/internal/schema/union_null_policy_test.go @@ -0,0 +1,309 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "fmt" + "maps" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// withUnionAt pairs each spelling with where its placement writes the union. +func withUnionAt(spellings map[string]string) map[string][2]string { + out := map[string][2]string{} + for name, spelling := range spellings { + out[name] = [2]string{spelling, openapitest.PartsAt(name, true)} + } + return out +} + +// warningsUnder returns the warnings drawn at or beneath the schema name. +func warningsUnder(diags []ir.Diagnostic, name string) []ir.Diagnostic { + var out []ir.Diagnostic + for _, diagnostic := range diags { + at := string(diagnostic.Provenance.Pointer) + if diagnostic.Severity == ir.SeverityWarning && (at == "/components/schemas/"+name || strings.HasPrefix(at, "/components/schemas/"+name+"/")) { + out = append(out, diagnostic) + } + } + return out +} + +// TestUnion_ANullOnlyBodyNamesItsDeadBranchesAtTheUnion holds a union every +// branch of which shares no kind with a body admitting null alone, at 3.0 and +// 3.1 and in every spelling, to the closed empty Enum the body is, keeping the +// union once, with the one warning naming each dead branch at the union +// keyword and none at the schema +// (docs/compilers/openapi.md#union-beside-structure). +func TestUnion_ANullOnlyBodyNamesItsDeadBranchesAtTheUnion(t *testing.T) { + t.Parallel() + for version, null := range map[string]string{"3.0.3": "type: object, enum: [null], nullable: true", "3.1.0": "type: 'null'"} { + spellings := withUnionAt(openapitest.Spellings(null, "anyOf: [{type: string}, {type: integer}]")) + var written strings.Builder + for name, spelling := range spellings { + written.WriteString(" " + name + ": " + spelling[0] + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer(version, written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for name, spelling := range spellings { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s %s is the null type; got %T", version, name, typeByName(doc, name)) + assert.Empty(t, enum.Members, name) + assert.Equal(t, ir.ReasonDegradedLowering, enum.Unmodeled["openapi:anyOf"].Reason, "%s %s", version, name) + warned := warningsUnder(diags, name) + require.Len(t, warned, 1, "%s %s", version, name) + assert.Equal(t, "/components/schemas/"+name+spelling[1]+"/anyOf", string(warned[0].Provenance.Pointer), "%s %s", version, name) + assert.Contains(t, warned[0].Message, "2 of the 2 branches of this anyOf share no value", "%s %s", version, name) + } + } +} + +// TestUnion_ThePolicysNullableLeavesNullAloneWhereNoBranchLives holds a +// `nullable: true` the policy reads beside an object and a union no branch of +// which shares a kind with it, flat and on an entry writing no properties, to +// null alone with the dead branch named at the union, and, with the policy +// off at 3.0, where the keyword is the type's, to the object keeping the +// union with the warning at the schema. +func TestUnion_ThePolicysNullableLeavesNullAloneWhereNoBranchLives(t *testing.T) { + t.Parallel() + for _, version := range []string{"3.0.3", "3.1.0"} { + spec := openapitest.ComponentSpecVer(version, ` Flat: {type: object, nullable: true, properties: {a: {type: string}}, oneOf: [{type: string}]} + Entry: {allOf: [{type: object, properties: {a: {type: string}}}, {nullable: true, type: object}], oneOf: [{type: string}]} +`) + for _, off := range []bool{false, true} { + doc, diags := schema.LowerSpecWith(t, spec, lowering.Policy{NullableInference: lowering.NullableInference{Disabled: off}}) + for _, name := range []string{"Flat", "Entry"} { + warned := warningsUnder(diags, name) + require.Len(t, warned, 1, "%s %s %t", version, name, off) + if off { + _, isModel := typeByName(doc, name).(*ir.Model) + assert.True(t, isModel, "%s %s", version, name) + assert.Equal(t, "/components/schemas/"+name, string(warned[0].Provenance.Pointer), "%s %s", version, name) + continue + } + _, isEnum := typeByName(doc, name).(*ir.Enum) + assert.True(t, isEnum, "%s %s is null alone; got %T", version, name, typeByName(doc, name)) + assert.Equal(t, "/components/schemas/"+name+"/oneOf", string(warned[0].Provenance.Pointer), "%s %s", version, name) + } + } + } +} + +// TestUnion_ANullAlonePrincipalIsNamedAsTheNodeItIs holds the report of what an +// entry beside a union principal keeps to what the position lowered to: where +// the conjunction leaves null alone, the enum of null, never the nullable +// reference the union written alone collapses to, and where a branch is dead, +// that union's node. +func TestUnion_ANullAlonePrincipalIsNamedAsTheNodeItIs(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` M: + allOf: + - {type: [string, 'null'], allOf: [{minLength: 1}]} + - {oneOf: [{type: object, properties: {u: {type: string}}}, {type: 'null'}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + _, isEnum := typeByName(doc, "M").(*ir.Enum) + require.True(t, isEnum, "M is null alone") + message := openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/M/allOf/0/allOf/0") + assert.Contains(t, message, `a node of kind "enum"`) + assert.NotContains(t, message, "nullable reference") +} + +// TestUnion_ANullOnlyOutcomeLowersAsItsNullTwin holds a union of an integer +// and null beside a string admitting null, the 3.1 type list and the 3.0 +// nullable, under either policy and in every spelling, to what `{type: +// 'null'}` lowers to: the empty Enum typed by no kind, keeping the union and +// no type, the one warning naming the dead integer branch at the union +// keyword (docs/compilers/openapi.md#union-null-only). +func TestUnion_ANullOnlyOutcomeLowersAsItsNullTwin(t *testing.T) { + t.Parallel() + bodies := map[string][2]string{ + "3.1.0": {"type: [string, 'null']", "{type: 'null'}"}, + "3.0.3": {"type: string, nullable: true", "{type: object, enum: [null], nullable: true}"}, + } + for version, written := range bodies { + spellings := openapitest.Spellings(written[0], "oneOf: [{type: integer}, "+written[1]+"]") + var schemas strings.Builder + for name, spelled := range spellings { + schemas.WriteString(" " + name + ": " + spelled + "\n") + } + for _, off := range []bool{false, true} { + doc, diags := schema.LowerSpecWith(t, openapitest.ComponentSpecVer(version, schemas.String()), + lowering.Policy{NullableInference: lowering.NullableInference{Disabled: off}}) + openapitest.RequireNoErrorDiags(t, diags) + for name := range spellings { + label := fmt.Sprintf("%s %s off=%t", version, name, off) + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s: got %T", label, typeByName(doc, name)) + assert.Empty(t, enum.Members, label) + assert.Equal(t, ir.PrimitiveAny, enum.ValueType, label) + assert.Equal(t, []string{"openapi:oneOf"}, slices.Sorted(maps.Keys(enum.Unmodeled)), label) + warned := warningsUnder(diags, name) + require.Len(t, warned, 1, label) + assert.True(t, strings.HasSuffix(string(warned[0].Provenance.Pointer), "/oneOf"), label) + assert.Contains(t, warned[0].Message, "oneOf/0: integer", label) + } + } + } +} + +// TestUnion_AOneOfRefusesANullItsBranchesShare holds a oneOf of two format +// branches beside a string admitting null, in every spelling, to the Union of +// the two formats behind a reference null matches more than one branch of, +// which the oneOf refuses: at 3.1, and at 3.0 with the policy off, no null, +// with one warning at the oneOf naming both branches; at 3.0 with it on, the +// nullable the policy reads, marked inferred +// (docs/compilers/openapi.md#union-null-only). +func TestUnion_AOneOfRefusesANullItsBranchesShare(t *testing.T) { + t.Parallel() + bodies := map[string]string{"3.1.0": "type: [string, 'null']", "3.0.3": "type: string, nullable: true"} + for version, body := range bodies { + spellings := openapitest.Spellings(body, "oneOf: [{format: uuid}, {format: date}]") + var schemas strings.Builder + holder := " Holder:\n type: object\n properties:\n" + for name, spelled := range spellings { + schemas.WriteString(" " + name + ": " + spelled + "\n") + holder += " p" + name + ": {$ref: '#/components/schemas/" + name + "'}\n" + } + for _, off := range []bool{false, true} { + doc, diags := schema.LowerSpecWith(t, openapitest.ComponentSpecVer(version, schemas.String()+holder), + lowering.Policy{NullableInference: lowering.NullableInference{Disabled: off}}) + openapitest.RequireNoErrorDiags(t, diags) + holderModel, ok := typeByName(doc, "Holder").(*ir.Model) + require.True(t, ok) + properties := openapitest.PropertiesByWire(holderModel.Properties) + widened := version == "3.0.3" && !off + for name := range spellings { + label := fmt.Sprintf("%s %s off=%t", version, name, off) + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s: got %T", label, typeByName(doc, name)) + assert.Len(t, union.Variants, 2, label) + assert.Equal(t, widened, properties["p"+name].Type.Nullable, label) + warned := warningsUnder(diags, name) + if widened { + assert.Empty(t, warned, label) + assert.Equal(t, lowering.NullableInferenceHeuristic, properties["p"+name].Type.Inferred, label) + continue + } + require.Len(t, warned, 1, label) + assert.True(t, strings.HasSuffix(string(warned[0].Provenance.Pointer), "/oneOf"), label) + assert.Contains(t, warned[0].Message, "oneOf/0, oneOf/1", label) + } + } + } +} + +// TestUnion_AOneOfReadsALongBranchToItsEnd holds a oneOf whose third branch +// is a chain of 300 allOf references ending on a string, beside a string +// admitting null, to the null answer, which no depth cuts: the chain keeps +// null out, the two format branches leave it in, so the oneOf refuses it, the +// reference admits none, and the one warning names those two branches. +func TestUnion_AOneOfReadsALongBranchToItsEnd(t *testing.T) { + t.Parallel() + ref := func(name string) string { return "{$ref: '#/components/schemas/" + name + "'}" } + var written strings.Builder + written.WriteString(" Past: {type: [string, 'null'], oneOf: [{format: uuid}, {format: date}, {allOf: [" + ref("B0") + "]}]}\n") + written.WriteString(" Holder: {type: object, properties: {p: " + ref("Past") + "}}\n") + for i := range 300 { + fmt.Fprintf(&written, " B%d: {allOf: [%s]}\n", i, ref(fmt.Sprintf("B%d", i+1))) + } + written.WriteString(" B300: {type: string}\n") + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + holder, ok := typeByName(doc, "Holder").(*ir.Model) + require.True(t, ok) + assert.False(t, openapitest.PropertiesByWire(holder.Properties)["p"].Type.Nullable, "the oneOf refuses the null") + warned := warningsUnder(diags, "Past") + require.Len(t, warned, 1) + assert.Contains(t, warned[0].Message, "null matches 2 of the 3 branches of this oneOf (oneOf/0, oneOf/1)") +} + +// TestUnionBeside_ADeadBranchBesideAnObjectOrAStringIsNamedByWhatTheBodyAdmits +// holds the report of a boolean branch beside an object or a string to the +// kinds the body admits, never objects alone. +func TestUnionBeside_ADeadBranchBesideAnObjectOrAStringIsNamedByWhatTheBodyAdmits(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " A: {type: object, properties: {a: {type: string}}}\n"+ + " OS: {type: [object, string], oneOf: [{$ref: '#/components/schemas/A'}, {type: boolean}]}\n")) + warned := warningsUnder(diags, "OS") + require.Len(t, warned, 1) + assert.Contains(t, warned[0].Message, "admits only an instance of type object or string, and 1 of its branches admits none of them") +} + +// TestUnion_AOneOfLeadingRoundToItselfIsReadOnce holds a oneOf whose branch +// leads back to its own schema, directly, through another such schema and +// through an allOf, beside a string admitting null, to a compile that ends: +// reading whether the oneOf refuses null reads each branch apart from any +// union reading, so no reading enters itself again. +func TestUnion_AOneOfLeadingRoundToItselfIsReadOnce(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` S: {type: [string, 'null'], oneOf: [{format: uuid}, {$ref: '#/components/schemas/S'}]} + A: {type: [string, 'null'], oneOf: [{format: uuid}, {$ref: '#/components/schemas/B'}]} + B: {type: [string, 'null'], oneOf: [{format: date}, {$ref: '#/components/schemas/A'}]} + C: {type: [string, 'null'], oneOf: [{format: uuid}, {allOf: [{$ref: '#/components/schemas/C'}]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"S", "A", "B", "C"} { + assert.NotNil(t, typeByName(doc, name), name) + } +} + +// TestUnion_ANullBranchBesideALiveOneIsDeadWithThePolicyOff holds a null +// branch beside an object branch that lives, the union flat and beside an +// allOf of the body: with the policy off, read as written, the null shares no +// value with the object, so it is no variant, kept under its index with the +// one warning naming it, and the reference admits no null. +func TestUnion_ANullBranchBesideALiveOneIsDeadWithThePolicyOff(t *testing.T) { + t.Parallel() + const union = "oneOf: [{type: 'null'}, {$ref: '#/components/schemas/A'}]" + spec := openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {x: {type: string}}} + Flat: {type: object, properties: {a: {type: string}}, `+union+`} + Beside: {allOf: [{type: object, properties: {a: {type: string}}}], `+union+`} +`) + doc, diags := schema.LowerSpecWith(t, spec, lowering.Policy{NullableInference: lowering.NullableInference{Disabled: true}}) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Flat", "Beside"} { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s: got %T", name, typeByName(doc, name)) + assert.Len(t, union.Variants, 1, name) + assert.Contains(t, union.Unmodeled, "openapi:oneOf/0", "%s keeps the null branch", name) + warned := warningsUnder(diags, name) + require.Len(t, warned, 1, name) + assert.Contains(t, warned[0].Message, "oneOf/0: null", name) + } +} + +// TestUnion_ThePolicysNullIsSaidToBeThePolicys holds the info of a position the +// nullable-inference policy leaves null alone to where its null comes from, a +// 3.0 `nullable: true` over the position, never a branch sharing null with the +// rest, which none does; a null branch the policy lifts onto an object is said +// at the branch, the position no enum. +func TestUnion_ThePolicysNullIsSaidToBeThePolicys(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", ` Nullable: {type: object, nullable: true, properties: {a: {type: string}}, oneOf: [{type: string}]} + Lifted: {type: object, properties: {a: {type: string}}, oneOf: [{type: object, enum: [null], nullable: true}]} +`)) + told := map[string][]string{} + for _, diagnostic := range diags { + if name, ok := strings.CutPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"); ok && strings.Contains(diagnostic.Message, "enum with no member") { + told[name] = append(told[name], diagnostic.Message) + } + } + require.Len(t, told["Nullable"], 1) + assert.Contains(t, told["Nullable"][0], "reads its nullable: true") + assert.NotContains(t, told["Nullable"][0], "but null,") + assert.Empty(t, told["Lifted"], "the lifted null leaves the object its Model") + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.InferredNullable, "/components/schemas/Lifted/oneOf/0")) +} diff --git a/compilers/openapi/internal/schema/union_oneof_test.go b/compilers/openapi/internal/schema/union_oneof_test.go index a6e60ded4..50d858277 100644 --- a/compilers/openapi/internal/schema/union_oneof_test.go +++ b/compilers/openapi/internal/schema/union_oneof_test.go @@ -164,7 +164,7 @@ func TestOneOf_CoDeclaredCompositionDistributes(t *testing.T) { model := doc.Types[union.Variants[i].Type.Target].(*ir.Model) require.NotNil(t, model.Base, "the enclosing allOf's sole $ref stays Base (docs/compilers/openapi.md#allof-classification)") assert.Equal(t, componentID("Base"), model.Base.Target) - require.Len(t, model.Mixins, 1, "the branch joins as a mixin, the composition already having a base") + require.Len(t, model.Mixins, 1, "the branch is added as a mixin, the composition already having a base") assert.Equal(t, componentID(branch), model.Mixins[0].Target) assert.Equal(t, ir.CanonicalWords(branch), union.Variants[i].Name.Hint, "the variant is named after its branch, in the neutral words every name channel carries") @@ -216,7 +216,7 @@ func TestAnyOf_CoDeclaredPropertiesDistributeAsBase(t *testing.T) { // declaration order. func TestOneOf_CoDeclaredVariantNotStolenByRefToBranch(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name string branch int outsiderFirst bool @@ -225,9 +225,9 @@ func TestOneOf_CoDeclaredVariantNotStolenByRefToBranch(t *testing.T) { {"outsider declared last", 0, false}, {"ref to the second branch", 1, true}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, comboRefStealSpec(tc.branch, tc.outsiderFirst)) + doc, diags := schema.LowerSpec(t, comboRefStealSpec(testCase.branch, testCase.outsiderFirst)) openapitest.RequireNoErrorDiags(t, diags) union, ok := typeByName(doc, "Combo").(*ir.Union) @@ -243,11 +243,11 @@ func TestOneOf_CoDeclaredVariantNotStolenByRefToBranch(t *testing.T) { } // The outside reference gets the branch schema, which is what its - // pointer names — never the conjunction the variant stands for. + // pointer names — never the conjunction the variant names. outsider, ok := typeByName(doc, "Outsider").(*ir.Model) require.True(t, ok) require.Len(t, outsider.Properties, 1) - assert.Equal(t, componentID([]string{"A", "B"}[tc.branch]), useTargetOf(t, doc.Types[outsider.Properties[0].Type.Target]), + assert.Equal(t, componentID([]string{"A", "B"}[testCase.branch]), useTargetOf(t, doc.Types[outsider.Properties[0].Type.Target]), "the branch pointer hoists the node a use of the branch's target owns") }) } @@ -264,7 +264,7 @@ func TestOneOf_CoDeclaredVariantNotStolenByRefToBranch(t *testing.T) { // they match. The registry is also compared on its own, with nothing excluded. func TestOneOf_CoDeclaredDistributionIsOrderIndependent(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name string // spec writes the document with the permuted component declared first. spec func(first bool) string @@ -273,11 +273,11 @@ func TestOneOf_CoDeclaredDistributionIsOrderIndependent(t *testing.T) { {"outside ref at the second branch", func(f bool) string { return comboRefStealSpec(1, f) }}, {"discriminated base", comboDiscriminatedSpec}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - first, diags := parseFull(t, tc.spec(true)) + first, diags := parseFull(t, testCase.spec(true)) openapitest.RequireNoErrorDiags(t, diags) - last, diags := parseFull(t, tc.spec(false)) + last, diags := parseFull(t, testCase.spec(false)) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, cmp.Diff(first, last, orderInvariantIR()...), @@ -383,10 +383,10 @@ func TestOneOf_CoDeclaredBranchNoObjectSatisfiesIsNoVariant(t *testing.T) { assert.Equal(t, ir.ReasonDegradedLowering, union.Unmodeled[key].Reason) assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, fmt.Sprintf("/components/schemas/Combo/oneOf/%d", i))) } - reports := diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Combo") + reports := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/Combo") require.Len(t, reports, 1) assert.Equal(t, ir.SeverityWarning, reports[0].Severity) - assert.Contains(t, reports[0].Message, "(oneOf/0: string, oneOf/1: string)") + assert.Contains(t, reports[0].Message, `(oneOf/0: string, oneOf/1: enum ["a", "b"])`) object, ok := doc.Types[union.Variants[0].Type.Target].(*ir.Model) require.True(t, ok) require.NotNil(t, object.Base) @@ -435,17 +435,19 @@ func TestOneOf_CoDeclaredTypeListBranchComposesItsObject(t *testing.T) { } } -// TestOneOf_CoDeclaredUnpreservableBranchIsNotAnnounced pins the pairing -// GitHub #144 exists for at a variant's kept branch: a branch that fails to -// convert is reported as such, and nothing claims it was kept. -func TestOneOf_CoDeclaredUnpreservableBranchIsNotAnnounced(t *testing.T) { +// TestOneOf_CoDeclaredBranchIsKeptWithoutAnExtensionNoJSONHolds pins a branch +// the variant keeps verbatim, being no object alone, that writes an extension +// whose value converts to no JSON: the branch is kept without the extension, +// which draws its own warning at the branch, and the variant is as without it, +// with no error. +func TestOneOf_CoDeclaredBranchIsKeptWithoutAnExtensionNoJSONHolds(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` A: {type: object, properties: {a: {type: string}}} + doc := requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpec(` A: {type: object, properties: {a: {type: string}}} Combo: type: object properties: {kind: {type: string}} - oneOf: [{$ref: '#/components/schemas/A'}, {anyOf: [{type: object}, {type: string}], x-t: `+unpreservableValue+`}] -`)) + oneOf: [{$ref: '#/components/schemas/A'}, {anyOf: [{type: object}, {type: string}]`+unconvertibleExtension+`}] +`), unconvertibleExtension, "/components/schemas/Combo/oneOf/1") union, ok := typeByName(doc, "Combo").(*ir.Union) require.True(t, ok) @@ -453,18 +455,16 @@ func TestOneOf_CoDeclaredUnpreservableBranchIsNotAnnounced(t *testing.T) { model, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Model) require.True(t, ok) assert.Nil(t, model.Base) - assert.NotContains(t, model.Unmodeled, "openapi:oneOf/1", "the conversion failed, so nothing was kept") - assert.True(t, openapitest.HasDiag(diags, diag.UnpreservableConstruct), "the failure itself is reported") - assert.Empty(t, openapitest.PreservationClaims(diags), - "nothing was written under Unmodeled, so nothing may announce that it was") + require.Contains(t, model.Unmodeled, "openapi:oneOf/1", "the branch is kept") + assert.JSONEq(t, `{"anyOf":[{"type":"object"},{"type":"string"}]}`, string(model.Unmodeled["openapi:oneOf/1"].Value)) } -// TestOneOf_CoDeclaredBranchReadCutShortIsComposed pins the one branch a -// variant composes though its kinds are not read as an object: one whose read -// is cut short, here by a loop of $refs, which leaves the composition as it is, -// as an allOf's $ref entry to such a target is composed. The variant holds the -// property count, which the read cannot exclude. -func TestOneOf_CoDeclaredBranchReadCutShortIsComposed(t *testing.T) { +// TestOneOf_CoDeclaredBranchOnALoopKeepsItsRef pins a branch whose $ref enters +// a loop of $refs. The loop reaches no schema, so it admits every kind, as {} +// does: the branch is not an object alone, so the variant takes no Base and +// keeps the $ref verbatim, as it keeps a branch $ref to {}. The variant still +// holds the body and the property count. +func TestOneOf_CoDeclaredBranchOnALoopKeepsItsRef(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` A: {type: object, properties: {a: {type: string}}} Loop1: {$ref: '#/components/schemas/Loop2'} @@ -476,15 +476,21 @@ func TestOneOf_CoDeclaredBranchReadCutShortIsComposed(t *testing.T) { oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/Loop1'}] `)) require.True(t, openapitest.HasDiag(diags, diag.CyclicRef), "the loop is reported where it is") + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/Combo/oneOf/1"), + "not an object alone") union, ok := typeByName(doc, "Combo").(*ir.Union) require.True(t, ok) require.Len(t, union.Variants, 2) model, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Model) require.True(t, ok) - require.NotNil(t, model.Base) - assert.Equal(t, componentID("Loop1"), model.Base.Target) - assert.Empty(t, model.Unmodeled) + assert.Nil(t, model.Base, "a loop is no object to compose") + require.Len(t, model.Properties, 1) + assert.Equal(t, "kind", model.Properties[0].WireName) + require.Contains(t, model.Unmodeled, "openapi:oneOf/1") + kept := model.Unmodeled["openapi:oneOf/1"] + assert.Equal(t, ir.ReasonDegradedLowering, kept.Reason) + assert.JSONEq(t, `{"$ref":"#/components/schemas/Loop1"}`, string(kept.Value)) require.NotNil(t, model.Constraints) require.NotNil(t, model.Constraints.MinProperties) assert.Equal(t, int64(1), *model.Constraints.MinProperties) @@ -584,14 +590,14 @@ func TestOneOf_CoDeclaredBranchAfterASkippedOneIsReported(t *testing.T) { {"after one naming a referent", "{$ref: '#/components/schemas/A'}"}, {"after one on a loop", "{$ref: '#/components/schemas/Z/oneOf/0'}"}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() _, diags := lowerSpecOnly(t, openapitest.ComponentSpec(` A: {type: object, properties: {a: {type: string}}} Z: type: object properties: {kind: {type: string}} - oneOf: [`+tc.skipped+`, {$ref: '#/components/schemas/Ghost'}] + oneOf: [`+testCase.skipped+`, {$ref: '#/components/schemas/Ghost'}] `)) got := make([]report, 0, len(diags)) for _, diagnostic := range diags { @@ -605,16 +611,14 @@ func TestOneOf_CoDeclaredBranchAfterASkippedOneIsReported(t *testing.T) { } // TestOneOf_CoDeclaredNotDistributedReasons pins the shapes distribution -// declines, each kept verbatim under ReasonDegradedLowering with its own reason -// in the diagnostic (docs/compilers/openapi.md#union-beside-structure), and a -// oneOf beside an anyOf, which it does not: the oneOf distributes and each -// variant keeps the anyOf. Two more are pinned elsewhere: +// declines, each kept verbatim under ReasonDegradedLowering +// (docs/compilers/openapi.md#union-beside-structure): a union no branch of +// which shares a kind with a const draws the one report that the conjuncts +// share no value, and a discriminator routing to subtypes says its own +// reason. A oneOf beside an anyOf distributes, the anyOf passed over kept +// once on the Union (GitHub #2054). // TestOneOf_CoDeclaredUnresolvableBranchIsNotDistributed and -// TestUnion_ASubtypeADiscriminatorRoutesToStaysASubtype pin those. -// Half-distributing any of them would leave a Union whose variants disagree -// about whether they carry the body. The messages are asserted, not just the -// code: the reasons are the only thing telling the otherwise identical -// diagnostics apart. +// TestUnion_ASubtypeADiscriminatorRoutesToStaysASubtype pin two more. func TestOneOf_CoDeclaredNotDistributedReasons(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpec(` A: {type: object, properties: {a: {type: string}}} @@ -636,8 +640,17 @@ func TestOneOf_CoDeclaredNotDistributedReasons(t *testing.T) { doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) + notAModel, ok := typeByName(doc, "NotAModel").Common().Unmodeled["openapi:oneOf"] + require.True(t, ok, "NotAModel keeps its union verbatim") + assert.Equal(t, ir.ReasonDegradedLowering, notAModel.Reason) + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/NotAModel"), 1, + "every branch is dead, which the one report says") + for _, diagnostic := range diags { + if diagnostic.Provenance.Pointer == "/components/schemas/NotAModel" { + assert.NotContains(t, diagnostic.Message, "the body is not a model", "the union is kept for its dead branches") + } + } for name, reason := range map[string]string{ - "NotAModel": "the body is not a model, so it carries no composition to distribute into", "Discriminated": "the discriminator beside it routes to branches composing this schema, its subtypes, which distributing them into a union would undo", } { entry, ok := typeByName(doc, name).Common().Unmodeled["openapi:oneOf"] @@ -650,18 +663,25 @@ func TestOneOf_CoDeclaredNotDistributedReasons(t *testing.T) { both, ok := typeByName(doc, "BothCombinators").(*ir.Union) require.True(t, ok, "the oneOf distributes") for _, model := range variantModels(t, doc, "BothCombinators") { - assert.Contains(t, model.Unmodeled, "openapi:anyOf", "each variant keeps the anyOf") + assert.NotContains(t, model.Unmodeled, "openapi:anyOf", "no variant keeps the anyOf") } - assert.NotContains(t, both.Unmodeled, "openapi:anyOf", "and the union does not") + assert.Contains(t, both.Unmodeled, "openapi:anyOf", "the Union keeps it once") // One more is settling's, once the registry is whole: Discriminated's - // discriminator routes to A, no subtype of its model, so it stays beside - // the union it was written for. + // discriminator routes to A, no subtype of its model, by the name its + // branch names, so that route is set aside and the discriminator stays. assert.Contains(t, - openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, - "/components/schemas/Discriminated/discriminator"), - "not a subtype of the model holding it") - assert.Equal(t, 4, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityInfo), - "each declined shape is reported once, and the kept discriminator once; got %+v", diags) + openapitest.DiagMessageAt(t, diags, diag.UnhomedConstruct, ir.SeverityInfo, + "/components/schemas/Discriminated/oneOf/0"), + "neither the model holding the discriminator nor a subtype of it") + assert.NotNil(t, typeByName(doc, "Discriminated").(*ir.Model).Discriminator) + infos := 0 + for _, diagnostic := range diags { + if diagnostic.Code == diag.DegradedConstruct && diagnostic.Severity == ir.SeverityInfo && + diagnostic.Provenance.Pointer != "/components/schemas/NotAModel" { + infos++ + } + } + assert.Equal(t, 2, infos, "the pair and the declined discriminated shape once each; got %+v", diags) } // restatingTargets declares the components the restating cases' $refs name. @@ -679,7 +699,7 @@ const restatingTargets = ` Target: {type: object, properties: {t: {type: stri // an `allOf` or a `$ref` the declarations compose. func TestOneOf_CoDeclaredRestatingBranchDeclaresNoShape(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct{ version, schema, keyword string }{ + for name, testCase := range map[string]struct{ version, schema, keyword string }{ "SameType": {"3.1.0", ` type: object properties: {a: {type: string}, b: {type: string}} oneOf: @@ -868,14 +888,6 @@ func TestOneOf_CoDeclaredRestatingBranchDeclaresNoShape(t *testing.T) { "TrueInBoth": {"3.1.0", ` type: object properties: {a: true} oneOf: [{required: [a], properties: {a: true}}] -`, "openapi:oneOf"}, - "NullTypeBesideRestatement": {"3.1.0", ` type: object - properties: {a: {type: string}} - oneOf: [{type: 'null', properties: {a: {type: string}}}] -`, "openapi:oneOf"}, - "NullTypeListBesideRestatement": {"3.1.0", ` type: object - properties: {a: {type: string}} - oneOf: [{type: ['null'], properties: {a: {type: string}}, not: {required: [a]}}] `, "openapi:oneOf"}, "AliasedBranchNarrowing": {"3.1.0", ` type: object x-branch: &b {required: [a], minProperties: 2, properties: {a: {type: string}}} @@ -962,7 +974,7 @@ func TestOneOf_CoDeclaredRestatingBranchDeclaresNoShape(t *testing.T) { `, "openapi:oneOf"}, "RestatesTheBodysEnum": {"3.1.0", ` type: string enum: [x, y] - oneOf: [{enum: [x, y], minLength: 1}] + oneOf: [{enum: [x, y], minLength: 1, pattern: '^(?=[xy])'}] `, "openapi:oneOf"}, "RestatesTheBodysFormat": {"3.1.0", ` type: string format: uri @@ -1101,11 +1113,11 @@ func TestOneOf_CoDeclaredRestatingBranchDeclaresNoShape(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - spec := openapitest.ComponentSpecVer(tc.version, restatingTargets+" S:\n"+tc.schema) + spec := openapitest.ComponentSpecVer(testCase.version, restatingTargets+" S:\n"+testCase.schema) doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) - entry, ok := typeByName(doc, "S").Common().Unmodeled[tc.keyword] + entry, ok := typeByName(doc, "S").Common().Unmodeled[testCase.keyword] require.True(t, ok, "the union is kept verbatim") assert.Equal(t, ir.ReasonValidationOnly, entry.Reason) // The body's own declarations may draw reports of their own, at their @@ -1135,7 +1147,7 @@ const nodeTwice = " N1: {$dynamicAnchor: node}\n N2: {$dynamicAnchor: node // branch no instance of the body satisfies keeps its union whole. func TestOneOf_CoDeclaredBranchSayingMoreDeclaresShape(t *testing.T) { t.Parallel() - for name, tc := range map[string]struct{ version, schema, reading string }{ + for name, testCase := range map[string]struct{ version, schema, reading string }{ "OtherType": {"3.1.0", ` type: object properties: {a: {type: string}} oneOf: [{required: [a], properties: {a: {type: integer}}}] @@ -1320,11 +1332,11 @@ func TestOneOf_CoDeclaredBranchSayingMoreDeclaresShape(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - spec := openapitest.ComponentSpecVer(tc.version, restatingTargets+" S:\n"+tc.schema) + spec := openapitest.ComponentSpecVer(testCase.version, restatingTargets+" S:\n"+testCase.schema) doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) - assert.Equal(t, tc.reading, unionReading(doc, "S")) + assert.Equal(t, testCase.reading, unionReading(doc, "S")) assert.False(t, openapitest.HasDiagCodeAt(diags, diag.ValidationOnlyKeyword, "/components/schemas/S"), "%+v", diags) }) @@ -1359,17 +1371,12 @@ func TestOneOf_CoDeclaredRestatementReadsReferencesAgainstTheirBase(t *testing.T // TestOneOf_CoDeclaredBranchSayingMoreBesideANonModel holds a branch that // writes a keyword declaring shape the body does not hold, where the body is no -// model to distribute into, to the union alone where every branch says the -// body's `type`, a bare `items` or `prefixItems` saying array as the -// kind-inference policy reads it, and to the degraded lowering where a bare -// branch does not. +// model to distribute into, to the union alone: a branch conjoins with the +// body's kind, so one writing a format alone is its flat twin writing the +// body's `type` too, as a bare `items` or `prefixItems` says array as the +// kind-inference policy reads it (GitHub #2108). func TestOneOf_CoDeclaredBranchSayingMoreBesideANonModel(t *testing.T) { t.Parallel() - alone := map[string]bool{ - "ItemsBesideTheType": true, "FormatBesideTheType": true, "ItemsBesideANot": true, - "FormatBesideANot": true, "ConstBesideANot": true, "ItemsInABareBranch": true, - "PrefixItemsInABareBranch": true, - } for name, schemaText := range map[string]string{ "ItemsBesideTheType": ` type: array oneOf: @@ -1407,28 +1414,23 @@ func TestOneOf_CoDeclaredBranchSayingMoreBesideANonModel(t *testing.T) { spec := openapitest.ComponentSpecVer("3.1.0", restatingTargets+" S:\n"+schemaText) doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) - - if alone[name] { - assert.Equal(t, readAlone, unionReading(doc, "S")) - return - } - assert.Equal(t, string(ir.ReasonDegradedLowering), unionReading(doc, "S")) - assert.Contains(t, - openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S"), - "the body is not a model") + assert.Equal(t, readAlone, unionReading(doc, "S")) }) } } // TestOneOf_CoDeclaredBranchKeywordIsJudgedAloneAsBesideTheType holds every -// keyword of the 2020-12 vocabularies, and OpenAPI's own, to one verdict in a -// branch written alone and in one beside the body's `type`, and that verdict to +// keyword of the 2020-12 vocabularies, and OpenAPI's own, to one answer in a +// branch written alone and in one beside the body's `type`, and that answer to // whether the keyword declares shape. The list below is the decision for each // keyword as the vocabulary table writes it, beside a body writing no element. +// $schema, $vocabulary and an $id with no relative reference beneath it name +// or configure the schema and say nothing of the value, so none is listed +// (GitHub #1859). func TestOneOf_CoDeclaredBranchKeywordIsJudgedAloneAsBesideTheType(t *testing.T) { t.Parallel() declaresShape := []string{ - "$schema", "$vocabulary", "$id", "$ref", "$dynamicRef", "allOf", "anyOf", "oneOf", "prefixItems", + "$ref", "$dynamicRef", "allOf", "anyOf", "oneOf", "prefixItems", "items", "patternProperties", "additionalProperties", "unevaluatedProperties", "enum", "const", "default", "readOnly", "writeOnly", "format", "contentEncoding", "contentMediaType", "contentSchema", "discriminator", "xml", "unknownKeyword", @@ -1444,15 +1446,15 @@ func TestOneOf_CoDeclaredBranchKeywordIsJudgedAloneAsBesideTheType(t *testing.T) {keyword: "unknownKeyword", write: "unknownKeyword: 1", schemas: objectSchema}, } readings := map[bool]string{false: string(ir.ReasonValidationOnly), true: readDistributed} - keywords := slices.DeleteFunc(append(vocabularyCases(), cases...), func(tc vocabCase) bool { - return tc.keyword == "type" // what a branch repeats the body with + keywords := slices.DeleteFunc(append(vocabularyCases(), cases...), func(testCase vocabCase) bool { + return testCase.keyword == "type" // what a branch repeats the body with }) - for _, tc := range keywords { - t.Run(tc.keyword, func(t *testing.T) { + for _, testCase := range keywords { + t.Run(testCase.keyword, func(t *testing.T) { t.Parallel() - _, others, _ := strings.Cut(tc.schemas, "\n") - want := readings[slices.Contains(declaresShape, tc.keyword)] - for _, branch := range []string{"{" + tc.write + "}", "{type: object, " + tc.write + "}"} { + _, others, _ := strings.Cut(testCase.schemas, "\n") + want := readings[slices.Contains(declaresShape, testCase.keyword)] + for _, branch := range []string{"{" + testCase.write + "}", "{type: object, " + testCase.write + "}"} { spec := openapitest.ComponentSpecVer("3.1.0", others+" S:\n"+ " type: object\n properties: {p: {type: string}}\n"+ " oneOf: ["+branch+", {required: [p]}]\n") @@ -1468,7 +1470,7 @@ func TestOneOf_CoDeclaredBranchKeywordIsJudgedAloneAsBesideTheType(t *testing.T) // past a budget, in its body or in value sets its branches write together, to // the degraded lowering: a reading cut short says nothing, and a value set cut // short would otherwise read as admitting nothing, which every keyword restates. -// What a verdict does not need is not read: a branch writing only what is +// What an answer does not need is not read: a branch writing only what is // judged without the body leaves it unread, one restating the body's own // keywords reads nothing it composes, one nesting nothing reads no declarations // below it, and a place many branches restate is read once. @@ -1488,13 +1490,13 @@ func TestOneOf_CoDeclaredUnionReadPastItsBudgetDeclaresShape(t *testing.T) { halfMembers := strings.Join(members[:schema.MaxAdmissionMembers/2+1], ", ") conjuncts := " allOf: [" + strings.Repeat("{description: c}, ", schema.MaxAdmissionReads) + "{description: c}]\n" // 80 conjuncts, 62 declaring `a`: reading what `a` nests would take the - // verdict past the read budget, which reading only what it needs does not. + // answer past the read budget, which reading only what it needs does not. var elsewhere string for i := range 18 { elsewhere += fmt.Sprintf("{properties: {z%d: {type: string}}}, ", i) } validation := string(ir.ReasonValidationOnly) - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { schema string want string why string @@ -1513,7 +1515,7 @@ func TestOneOf_CoDeclaredUnionReadPastItsBudgetDeclaresShape(t *testing.T) { "TypeAgainstAValueSetPastTheMemberBudget": { " type: string\n enum: [" + strings.Join(members, ", ") + "]\n" + " oneOf: [{type: integer}]\n", - string(ir.ReasonDegradedLowering), "the body is not a model", + string(ir.ReasonDegradedLowering), "", }, "PropertyNestingNothingReadsNoNestedDeclarations": { " type: object\n properties: {a: {type: string}}\n allOf: [" + elsewhere + @@ -1561,14 +1563,18 @@ func TestOneOf_CoDeclaredUnionReadPastItsBudgetDeclaresShape(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", " S:\n"+tc.schema)) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", " S:\n"+testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) - assert.Equal(t, tc.want, unionReading(doc, "S")) - if tc.why != "" { + assert.Equal(t, testCase.want, unionReading(doc, "S")) + if name == "TypeAgainstAValueSetPastTheMemberBudget" { + assert.Len(t, diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/S"), 1, + "the integer branch shares no kind with the string, so every branch is dead") + } + if testCase.why != "" { assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S"), - tc.why) + testCase.why) } }) } @@ -1587,16 +1593,16 @@ func TestOneOf_CoDeclaredRestatementOfTheBodyItselfOutlastsItsComposition(t *tes "own type": "{type: object, required: [a]}", "composed": "{required: [b], properties: {b: {type: integer}}}", } - for _, links := range []int{50, 100, 128, 130, 300} { + for _, hops := range []int{50, 100, 128, 130, 300} { for shape, branch := range branches { - t.Run(fmt.Sprintf("%s at %d links", shape, links), func(t *testing.T) { + t.Run(fmt.Sprintf("%s at %d hops", shape, hops), func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", " S:\n type: object\n"+ " properties: {a: {type: string}}\n allOf: [{$ref: '#/components/schemas/C1'}]\n"+ - " oneOf: ["+branch+", {required: [b]}]\n"+chainOf(links, "C"))) + " oneOf: ["+branch+", {required: [b]}]\n"+chainOf(hops, "C"))) openapitest.RequireNoErrorDiags(t, diags) want := string(ir.ReasonValidationOnly) - if shape == "composed" && links > 50 { + if shape == "composed" && hops > 50 { want = readDistributed } assert.Equal(t, want, unionReading(doc, "S")) @@ -1625,7 +1631,7 @@ func TestOneOf_CoDeclaredOwnReadingSettlesInAnyBranchOrder(t *testing.T) { } body := " S:\n type: object\n properties: {b: {type: string}, " + strings.Join(own, ", ") + "}\n" + " allOf: [{$ref: '#/components/schemas/C1'}]\n" - for name, tc := range map[string]struct { + for name, testCase := range map[string]struct { branches [2]string want string }{ @@ -1636,28 +1642,28 @@ func TestOneOf_CoDeclaredOwnReadingSettlesInAnyBranchOrder(t *testing.T) { t.Run(fmt.Sprintf("%s, branch %d first", name, order[0]), func(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", body+ - " oneOf: ["+tc.branches[order[0]]+", "+tc.branches[order[1]]+"]\n"+ + " oneOf: ["+testCase.branches[order[0]]+", "+testCase.branches[order[1]]+"]\n"+ strings.Replace(chainOf(30, "C"), "properties: {b: {type: integer}}", "properties: {c: {type: integer}}", 1))) openapitest.RequireNoErrorDiags(t, diags) - assert.Equal(t, tc.want, unionReading(doc, "S")) + assert.Equal(t, testCase.want, unionReading(doc, "S")) }) } } } -// chainOf declares links schemas named prefix and their index from 1, each +// chainOf declares hops schemas named prefix and their index from 1, each // composing the next, the last an object with an integer property b. -func chainOf(links int, prefix string) string { +func chainOf(hops int, prefix string) string { var out strings.Builder - for i := 1; i < links; i++ { + for i := 1; i < hops; i++ { fmt.Fprintf(&out, " %s%d: {allOf: [{$ref: '#/components/schemas/%s%d'}]}\n", prefix, i, prefix, i+1) } - fmt.Fprintf(&out, " %s%d: {type: object, properties: {b: {type: integer}}}\n", prefix, links) + fmt.Fprintf(&out, " %s%d: {type: object, properties: {b: {type: integer}}}\n", prefix, hops) return out.String() } // TestOneOf_CoDeclaredShapelessBranchesAreValidationLogicAtEachPosition holds -// a union whose branches declare no shape to one verdict at a property, an +// a union whose branches declare no shape to one answer at a property, an // element, a parameter, a request body and a response body, and one whose // branch declares shape to the other: a branch ruling out the other's property, // one narrowing and documenting beside the body's type, one repeating what the diff --git a/compilers/openapi/internal/schema/union_passed_test.go b/compilers/openapi/internal/schema/union_passed_test.go index 487c01e3d..395ea78e3 100644 --- a/compilers/openapi/internal/schema/union_passed_test.go +++ b/compilers/openapi/internal/schema/union_passed_test.go @@ -19,10 +19,11 @@ import ( // TestUnion_APassedOverUnionSharingNoKindWithTheBodyKeepsBoth holds a oneOf // and an anyOf whose union passed over shares no kind with the body to the // Model the body gives, keeping both, and one warning that its conjuncts share -// no value: beside a body writing no allOf, which names its own type and the -// union, beside an allOf, which the composition's report names, and on two of -// its entries. A oneOf of null alone, kept as validation logic, is a conjunct -// admitting null and named so. +// no value: beside a body writing no allOf, which names its own type and both +// unions, every branch of the chosen one being dead, beside an allOf, which +// the composition's report names, and on two of its entries. A oneOf of null +// alone, whose null the passed-over union keeps out, is dead too, kept and +// named as admitting null. func TestUnion_APassedOverUnionSharingNoKindWithTheBodyKeepsBoth(t *testing.T) { t.Parallel() spec := openapitest.ComponentSpecVer("3.1.0", ` T: {type: object, properties: {a: {type: string}}} @@ -52,14 +53,15 @@ func TestUnion_APassedOverUnionSharingNoKindWithTheBodyKeepsBoth(t *testing.T) { words string reason ir.UnmodeledReason }{ - "Flat": {"share no value (type: object, anyOf: string or integer), so no instance satisfies this schema, which its body alone", ir.ReasonDegradedLowering}, - "Beside": {"share no value (anyOf: string or integer, allOf/0: object)", ir.ReasonDegradedLowering}, - "NulBeside": {"share no value (oneOf: null, anyOf: object, allOf/0: object)", ir.ReasonValidationOnly}, - "TwoEntries": {"share no value (allOf/0: object, allOf/1: object or string, allOf/2: string or integer)", - ir.ReasonDegradedLowering}, + "Flat": {"(type: object, oneOf: string or integer, anyOf: string or integer); lowered as " + + `a node of kind "model"`, ir.ReasonDegradedLowering}, + "Beside": {"(oneOf: object, anyOf: string or integer, allOf/0: object)", ir.ReasonDegradedLowering}, + "NulBeside": {"(oneOf: null, anyOf: object, allOf/0: object)", ir.ReasonDegradedLowering}, + "TwoEntries": {"none of the 2 branches of the oneOf on allOf/1 admits a value the rest of the allOf admits " + + "(allOf/1/oneOf/0: object, allOf/1/oneOf/1: string)", ir.ReasonDegradedLowering}, } { var warned []string - for _, diagnostic := range diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/"+name) { + for _, diagnostic := range diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name) { if diagnostic.Severity == ir.SeverityWarning { warned = append(warned, diagnostic.Message) } @@ -75,25 +77,24 @@ func TestUnion_APassedOverUnionSharingNoKindWithTheBodyKeepsBoth(t *testing.T) { } // TestAllOf_ANullReadPastItsBudgetIsDecidedByEachConjunct holds the report of -// conjuncts sharing no value, where the read of null passes the walk's budget, -// to each conjunct read on its own: the keywords beside the allOf keep null -// out by their own `type`, whatever the union of more strings than the walk -// reads admits, so the schema is reported. +// conjuncts sharing no value beside a union of more strings than a budgeted +// walk read: the keywords beside the allOf keep null out by their own `type`, +// whatever the union admits, so the schema is reported. func TestAllOf_ANullReadPastItsBudgetIsDecidedByEachConjunct(t *testing.T) { t.Parallel() - var b strings.Builder - b.WriteString(" S: {type: string}\n T:\n anyOf:\n") + var builder strings.Builder + builder.WriteString(" S: {type: string}\n T:\n anyOf:\n") for range 300 { - b.WriteString(" - {$ref: '#/components/schemas/S'}\n") + builder.WriteString(" - {$ref: '#/components/schemas/S'}\n") } - b.WriteString(" P: {type: object, properties: {u: {type: string}}, allOf: [{$ref: '#/components/schemas/T'}]}\n") - _, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", b.String())) + builder.WriteString(" P: {type: object, properties: {u: {type: string}}, allOf: [{$ref: '#/components/schemas/T'}]}\n") + _, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", builder.String())) var warned []string - for _, diagnostic := range diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/P") { + for _, diagnostic := range diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/P") { if diagnostic.Severity == ir.SeverityWarning { warned = append(warned, diagnostic.Message) } } require.Len(t, warned, 1) - assert.Contains(t, warned[0], "share no value (type: object, allOf/0: string)") + assert.Contains(t, warned[0], "(type: object, allOf/0: string)") } diff --git a/compilers/openapi/internal/schema/union_test.go b/compilers/openapi/internal/schema/union_test.go index 4d07ed259..6007e2ebb 100644 --- a/compilers/openapi/internal/schema/union_test.go +++ b/compilers/openapi/internal/schema/union_test.go @@ -282,25 +282,25 @@ func TestOneOfAnyOf_NullOnlyLowersAsNullAlone(t *testing.T) { doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) - for _, tc := range []struct{ name, key string }{ + for _, testCase := range []struct{ name, key string }{ {"AnyOfNull", "openapi:anyOf"}, {"OneOfNull", "openapi:oneOf"}, {"AnyOfTwoNull", "openapi:anyOf"}, {"OtherSpellings", "openapi:oneOf"}, {"Nil", ""}, } { - enum, ok := doc.Types[componentID(tc.name)].(*ir.Enum) + enum, ok := doc.Types[componentID(testCase.name)].(*ir.Enum) require.True(t, ok, "%s lowers to an Enum, the node a schema of null alone lowers to, got %T", - tc.name, doc.Types[componentID(tc.name)]) - assert.Empty(t, enum.Members, "%s holds no value but the null its references admit", tc.name) + testCase.name, doc.Types[componentID(testCase.name)]) + assert.Empty(t, enum.Members, "%s holds no value but the null its references admit", testCase.name) assert.True(t, enum.Closed) assert.Equal(t, ir.PrimitiveAny, enum.ValueType) - if tc.key == "" { - assert.Empty(t, enum.Unmodeled, "%s keeps nothing", tc.name) + if testCase.key == "" { + assert.Empty(t, enum.Unmodeled, "%s keeps nothing", testCase.name) continue } - entry, ok := enum.Unmodeled[tc.key] - require.True(t, ok, "%s: the union is kept verbatim on the node", tc.name) + entry, ok := enum.Unmodeled[testCase.key] + require.True(t, ok, "%s: the union is kept verbatim on the node", testCase.name) assert.Equal(t, ir.ReasonDegradedLowering, entry.Reason) } for _, wire := range []string{"anyOfNull", "nil"} { @@ -340,7 +340,7 @@ func TestUnion_VariantHints(t *testing.T) { func TestUnion_ADecoratedBranchIsHintedAsItsRef(t *testing.T) { t.Parallel() const pet = "'#/components/schemas/Pet'" - for _, tc := range []struct { + for _, testCase := range []struct { name string version string // 3.0.3 unless the row is a 3.1 spelling keyword string // oneOf unless the row is an anyOf @@ -453,25 +453,25 @@ func TestUnion_ADecoratedBranchIsHintedAsItsRef(t *testing.T) { wantDangling: true, }, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() version, keyword := "3.0.3", "oneOf" - if tc.version != "" { - version = tc.version + if testCase.version != "" { + version = testCase.version } - if tc.keyword != "" { - keyword = tc.keyword + if testCase.keyword != "" { + keyword = testCase.keyword } spec := ` User: {type: object, properties: {id: {type: string}}} Pet: {type: object, properties: {name: {type: string}}} -` + tc.extra + " U:\n " + keyword + ":\n - {$ref: '#/components/schemas/User'}\n - " + tc.branch + "\n" +` + testCase.extra + " U:\n " + keyword + ":\n - {$ref: '#/components/schemas/User'}\n - " + testCase.branch + "\n" wantVariants := 2 - if tc.bare != "" { - spec += " - " + tc.bare + "\n" + if testCase.bare != "" { + spec += " - " + testCase.bare + "\n" wantVariants = 3 } doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer(version, spec)) - if tc.wantDangling { + if testCase.wantDangling { assert.True(t, openapitest.HasDiagAt(diags, diag.UnresolvedRef, ir.SeverityError), "the dangling ref is reported: %+v", diags) } else { @@ -482,20 +482,20 @@ func TestUnion_ADecoratedBranchIsHintedAsItsRef(t *testing.T) { require.True(t, ok, "U should be a union") require.Len(t, union.Variants, wantVariants) assert.Equal(t, "user", union.Variants[0].Name.Hint, "a bare $ref names its variant for its target") - if tc.bare != "" { + if testCase.bare != "" { assert.Equal(t, union.Variants[2].Name.Hint, union.Variants[1].Name.Hint, "the wrapped ref is named as the same ref written bare") assert.NotEqual(t, "variant_1", union.Variants[1].Name.Hint, "and as what it names, not where it sits") } else { - assert.Equal(t, tc.want, union.Variants[1].Name.Hint) + assert.Equal(t, testCase.want, union.Variants[1].Name.Hint) } - assert.Equal(t, tc.wantNullable, union.Variants[1].Type.Nullable) + assert.Equal(t, testCase.wantNullable, union.Variants[1].Type.Nullable) nodeID := ir.TypeID("type/anonymous/components/schemas/U/" + keyword + "/1") assert.Equal(t, nodeID, union.Variants[1].Type.Target, "the variant holds the branch's own node") node, ok := doc.Types[nodeID] require.True(t, ok, "the branch lowers to a node of its own") - wantNode := tc.wantNode + wantNode := testCase.wantNode if wantNode == "" { wantNode = "variant_1" } @@ -576,13 +576,16 @@ func TestLower_ConstraintOnlyUnionIsValidationOnly(t *testing.T) { // logic, not shape — dependentRequired's sibling — so the structural body // survives and the union is preserved under ReasonValidationOnly, the reason // a validation emitter selects on - // (docs/ir/boundaries.md#validation-only-constructs). + // (docs/ir/boundaries.md#validation-only-constructs). The members it + // requires are declared, so the closure refuses neither. spec := openapitest.ComponentSpec(` Thing: type: object additionalProperties: false required: [common] properties: common: {type: string} + a: {type: string} + b: {type: string} oneOf: - {required: [a]} - {required: [b]} @@ -592,7 +595,7 @@ func TestLower_ConstraintOnlyUnionIsValidationOnly(t *testing.T) { model, ok := doc.Types[componentID("Thing")].(*ir.Model) require.True(t, ok, "structural body lowers to a Model, not a bare Union") - require.Len(t, model.Properties, 1) + require.Len(t, model.Properties, 3) assert.Equal(t, "common", model.Properties[0].Name.Source) assert.True(t, model.Properties[0].Required) assert.Equal(t, ir.AdditionalClosed, model.Additional) @@ -641,8 +644,8 @@ func TestLower_BooleanUnionBranchDeclaresNoShape(t *testing.T) { // TestLower_AllOfWithOneOfKeepsBoth pins an allOf composing an object beside a // oneOf none of whose branches can be an object: no instance satisfies the two // together, so no union is distributed into models no value fills. The -// composition stands, the oneOf is kept beside it with one info, and the -// schema draws the warning of conjuncts sharing no value. +// composition remains, the oneOf is kept beside it, and the schema draws the +// one warning of conjuncts sharing no value, which says so, and no info. func TestLower_AllOfWithOneOfKeepsBoth(t *testing.T) { t.Parallel() for _, branches := range []string{"[{type: string}, {type: integer}]", "[{type: array, items: {type: string}}]"} { @@ -662,10 +665,9 @@ func TestLower_AllOfWithOneOfKeepsBoth(t *testing.T) { assert.Equal(t, componentID("Base"), model.Base.Target, branches) assert.Equal(t, []string{"openapi:oneOf"}, unmodeledKeys(model.Unmodeled), branches) assert.Equal(t, ir.ReasonDegradedLowering, model.Unmodeled["openapi:oneOf"].Reason, branches) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityWarning, - "/components/schemas/Combo"), "share no value", branches) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, - "/components/schemas/Combo"), "shares a kind", branches) + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.UnsatisfiableSchema, ir.SeverityWarning, + "/components/schemas/Combo"), `; lowered as a node of kind "model", its oneOf kept verbatim under Unmodeled — `, branches) + assert.Empty(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/Combo"), branches) } } @@ -705,14 +707,14 @@ func TestLower_ATypeArrayIsExclusiveOnlyOverDisjointTypes(t *testing.T) { {"number alone among the numbers", `{type: [number, string]}`, true}, {"no number at all", `{type: [object, array, string, boolean]}`, true}, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" U: "+tc.schema+"\n")) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" U: "+testCase.schema+"\n")) openapitest.RequireNoErrorDiags(t, diags) union, ok := typeByName(doc, "U").(*ir.Union) require.True(t, ok) - assert.Equal(t, tc.want, union.Exclusive) + assert.Equal(t, testCase.want, union.Exclusive) }) } } @@ -733,7 +735,8 @@ func TestLower_ATypeListedTwiceIsNotExclusive(t *testing.T) { // TestLower_ATypeArrayKeepsItsDiscriminatorOnTheUnion pins that a type array's // object variant holds no discriminator (GitHub #853): no type can be its // subtype, so the discriminator is kept unread on the union, whatever it -// routes to and whether or not a union is written beside it. A subtype keeps +// routes to; beside a union of an object and a string, the type list +// distributes by kind and the discriminator routes that Union. A subtype keeps // the tag the discriminator gives it, and composes the union's object variant // as its Base: the union admits a string, which no model composes. func TestLower_ATypeArrayKeepsItsDiscriminatorOnTheUnion(t *testing.T) { @@ -772,10 +775,23 @@ func TestLower_ATypeArrayKeepsItsDiscriminatorOnTheUnion(t *testing.T) { " Cat: {allOf: [{$ref: '#/components/schemas/Holder/properties/pet'}], type: object}\n", `"mapping"`, holder, "type/anonymous" + holder, ir.KindModel, map[string]string{"Cat": "cat"}}, } + // The union routing nothing holds a nil Mapping beside two inline variants + // with no name to be routed by, which validation notes, one each. + told := map[string][]string{"beside a union, no route": {"pass/discriminator-unrouted-variant", "pass/discriminator-unrouted-variant"}} for _, c := range cases { t.Run(c.name, func(t *testing.T) { t.Parallel() - for _, doc := range discriminatedOrders(t, c.version, c.schema, c.rest) { + for _, doc := range discriminatedOrdersTold(t, c.version, c.schema, c.rest, told[c.name]) { + if strings.HasPrefix(c.name, "beside a union") { + // The type list beside a union of an object and a string + // distributes by kind, and the discriminator routes that Union. + union, ok := doc.Types[c.union].(*ir.Union) + require.True(t, ok, "the body distributes by kind; got %T", doc.Types[c.union]) + require.NotNil(t, union.Discriminator) + assert.Equal(t, "kind", union.Discriminator.PropertyName) + assert.NotContains(t, union.Unmodeled, "openapi:discriminator") + continue + } assertKeptOnTheUnion(t, doc, c.union, c.at, c.want, c.variant) for name, tag := range c.tags { sub, ok := typeByName(doc, name).(*ir.Model) @@ -871,13 +887,16 @@ func TestLower_UnionWithStructuralSiblingVariants(t *testing.T) { doc, diags := schema.LowerSpec(t, spec) openapitest.RequireNoErrorDiags(t, diags) // A's body is a model, so its union is distributed across it, a branch - // admitting an object among them; the others' is none, so each keeps its - // union verbatim. + // admitting an object among them; B's and D's is none, so each keeps its + // union verbatim. C's const satisfies its union, which then says nothing. assert.Equal(t, readDistributed, unionReading(doc, "A")) - for _, name := range []string{"B", "C", "D"} { - td := typeByName(doc, name) - require.NotNil(t, td, "type %s present", name) - typeCommon := td.Common() + literal, isLiteral := typeByName(doc, "C").(*ir.Literal) + require.True(t, isLiteral, "C is its const") + assert.NotContains(t, literal.Unmodeled, "openapi:oneOf", "C keeps no union") + for _, name := range []string{"B", "D"} { + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, "type %s present", name) + typeCommon := typeDef.Common() _, hasOneOf := typeCommon.Unmodeled["openapi:oneOf"] _, hasAnyOf := typeCommon.Unmodeled["openapi:anyOf"] assert.True(t, hasOneOf || hasAnyOf, "union preserved for %s", name) @@ -915,29 +934,17 @@ func TestSchema_OneOfWithBoolBranch(t *testing.T) { assert.Len(t, union.Variants, 2, "the boolean branch is a variant, not a null strip") } -// TestUnionSiblings_UnpreservableIsReportedNotClaimed pins the announcement -// pairing at the union-sibling site. A oneOf the lowering keeps beside a -// structural body is kept verbatim when it converts; when it does not, the -// failure is reported at the keyword and nothing claims it was kept. The -// structural sibling here is unconvertible too, so the case has no legitimately -// preserved construct that a claim could be about. -func TestUnionSiblings_UnpreservableIsReportedNotClaimed(t *testing.T) { +// TestUnionSiblings_KeptSiblingsDropAnExtensionNoJSONHolds pins the +// union-sibling site: a structural body beside a oneOf, each writing an +// extension that converts to no JSON. What is kept is kept and reported as +// without the extensions, each alone dropped with its own warning where it is +// written, and a valid document draws no error. +func TestUnionSiblings_KeptSiblingsDropAnExtensionNoJSONHolds(t *testing.T) { t.Parallel() - _, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` S: - items: {type: string, x-t: `+unpreservableValue+`} - oneOf: [{type: string, x-t: `+unpreservableValue+`}, {type: integer}] -`)) - - var at []string - for _, diagnostic := range diags { - if diagnostic.Code == diag.UnpreservableConstruct { - at = append(at, string(diagnostic.Provenance.Pointer)) - } - } - assert.Contains(t, at, "/components/schemas/S/oneOf", - "the union siblings are reported where they are written: %+v", diags) - assert.Empty(t, openapitest.PreservationClaims(diags), - "nothing converted, so nothing may say it was kept") + requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpec(` S: + items: {type: string`+unconvertibleExtension+`} + oneOf: [{type: string`+unconvertibleExtension+`}, {type: integer}] +`), unconvertibleExtension, "/components/schemas/S/items", "/components/schemas/S/oneOf/0") } // TestNullOnlyUnion_ReportsWhatItKeepsUnreadAsABareNullSchemaDoes pins that a diff --git a/compilers/openapi/internal/schema/union_typearray_test.go b/compilers/openapi/internal/schema/union_typearray_test.go index 48eae9709..833ca3a06 100644 --- a/compilers/openapi/internal/schema/union_typearray_test.go +++ b/compilers/openapi/internal/schema/union_typearray_test.go @@ -48,8 +48,10 @@ func typeArrayCases() []typeArrayCase { []typeArrayVariant{node(&ir.Constraints{Min: new(ir.BigVal("1"))}), node(nil)}, nil}, {"a string bound beside an object", "{type: [string, object], properties: {a: {type: string}}, minLength: 2}", []typeArrayVariant{node(&ir.Constraints{MinLength: new(int64(2))}), node(nil)}, nil}, + // The string variant is a date's text, whose length its variant keeps + // verbatim rather than holds (docs/ir/constraints.md#constraints). {"a bound of each group beside a paired format", "{type: [string, integer], format: date, minimum: 1, minLength: 2}", - []typeArrayVariant{node(&ir.Constraints{MinLength: new(int64(2))}), node(&ir.Constraints{Min: new(ir.BigVal("1"))})}, nil}, + []typeArrayVariant{node(nil), node(&ir.Constraints{Min: new(ir.BigVal("1"))})}, nil}, {"a string bound alone", "{type: [string, integer], maxLength: 3}", []typeArrayVariant{node(&ir.Constraints{MaxLength: new(int64(3))}), primitive(ir.PrimitiveInteger)}, nil}, {"a numeric bound both numbers take", "{type: [integer, number], minimum: 1}", @@ -58,8 +60,8 @@ func typeArrayCases() []typeArrayCase { []typeArrayVariant{primitive(ir.PrimitiveString), primitive(ir.PrimitiveBool)}, []string{"openapi:minimum"}}, {"a collection bound and a string bound", "{type: [array, string], items: {type: string}, minItems: 1, maxLength: 4}", []typeArrayVariant{node(&ir.Constraints{MinItems: one}), node(&ir.Constraints{MaxLength: new(int64(4))})}, nil}, - {"an empty pattern, which bounds nothing", "{type: [string, integer], pattern: ''}", - []typeArrayVariant{primitive(ir.PrimitiveString), primitive(ir.PrimitiveInteger)}, []string{"openapi:pattern"}}, + {"an empty pattern, which says nothing", "{type: [string, integer], pattern: ''}", + []typeArrayVariant{primitive(ir.PrimitiveString), primitive(ir.PrimitiveInteger)}, nil}, } } @@ -72,19 +74,19 @@ func typeArrayCases() []typeArrayCase { // (docs/compilers/openapi.md#type-arrays). func TestLower_ATypeArraysBoundLandsOnTheVariantItConstrains(t *testing.T) { t.Parallel() - for _, tc := range typeArrayCases() { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range typeArrayCases() { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, atEverySite("3.1.0", tc.schema)) + doc, diags := parseFull(t, atEverySite("3.1.0", testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) for _, site := range sitesOf(t, doc) { assert.Nil(t, site.held, "%s: a carrier holds no bound of a type array", site.pointer) assert.Empty(t, site.kept, site.pointer) union, ok := site.node.(*ir.Union) require.True(t, ok, "%s: got %T", site.pointer, site.node) - assert.Equal(t, tc.kept, unmodeledKeys(union.Unmodeled), site.pointer) - require.Len(t, union.Variants, len(tc.variants), site.pointer) - for i, want := range tc.variants { + assert.Equal(t, testCase.kept, unmodeledKeys(union.Unmodeled), site.pointer) + require.Len(t, union.Variants, len(testCase.variants), site.pointer) + for i, want := range testCase.variants { got := union.Variants[i].Type.Target if want.primitive != "" { assert.Equal(t, want.primitive, got, "%s variant %d", site.pointer, i) @@ -107,15 +109,15 @@ func TestLower_ATypeArraysBoundLandsOnTheVariantItConstrains(t *testing.T) { // and to nothing else that differs. func TestLower_ATypeArraysVariantsSwapWithItsTypes(t *testing.T) { t.Parallel() - for _, tc := range typeArrayCases() { - t.Run(tc.name, func(t *testing.T) { + for _, testCase := range typeArrayCases() { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - start := strings.Index(tc.schema, "[") + 1 - end := strings.Index(tc.schema, "]") - types := strings.Split(tc.schema[start:end], ", ") + start := strings.Index(testCase.schema, "[") + 1 + end := strings.Index(testCase.schema, "]") + types := strings.Split(testCase.schema[start:end], ", ") require.Len(t, types, 2) - reversed := tc.schema[:start] + types[1] + ", " + types[0] + tc.schema[end:] - want, wantDiags := parseFull(t, atEverySite("3.1.0", tc.schema)) + reversed := testCase.schema[:start] + types[1] + ", " + types[0] + testCase.schema[end:] + want, wantDiags := parseFull(t, atEverySite("3.1.0", testCase.schema)) got, gotDiags := parseFull(t, atEverySite("3.1.0", reversed)) got, gotDiags = swappedTypeIndices(t, got, gotDiags) opts := []cmp.Option{cmpopts.IgnoreFields(ir.Document{}, "Sources"), cmpopts.EquateEmpty()} @@ -142,8 +144,8 @@ func swappedTypeIndices(t *testing.T, doc *ir.Document, diags []ir.Diagnostic) ( Diags []ir.Diagnostic } require.NoError(t, json.Unmarshal([]byte(swap.Replace(string(encoded))), &out)) - for _, td := range out.Doc.Types { - if union, ok := td.(*ir.Union); ok { + for _, typeDef := range out.Doc.Types { + if union, ok := typeDef.(*ir.Union); ok { slices.Reverse(union.Variants) } } @@ -167,7 +169,7 @@ func TestLower_ATypeArraysFormatIsTheVariantsItPairsWith(t *testing.T) { return &ir.Scalar{Base: new(instant), Encoding: &ir.Encoding{Name: "unixTimestamp", WireType: new(ir.TypeRef{Target: ir.PrimitiveTypeID(primitiveKind)})}} } - for _, tc := range []struct { + for _, testCase := range []struct { name, schema string variants []any // an ir.PrimitiveKind for a shared primitive, an *ir.Scalar for a node }{ @@ -182,16 +184,16 @@ func TestLower_ATypeArraysFormatIsTheVariantsItPairsWith(t *testing.T) { []any{unix(ir.PrimitiveString), unix(ir.PrimitiveInteger)}}, {"a redaction names no shape", "{type: [string, integer], format: password}", []any{ir.PrimitiveString, ir.PrimitiveInteger}}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := parseFull(t, atEverySite("3.1.0", tc.schema)) + doc, diags := parseFull(t, atEverySite("3.1.0", testCase.schema)) openapitest.RequireNoErrorDiags(t, diags) assert.Empty(t, diags) for _, site := range sitesOf(t, doc) { union, ok := site.node.(*ir.Union) require.True(t, ok, "%s: got %T", site.pointer, site.node) assert.Empty(t, union.Unmodeled, site.pointer) - for i, want := range tc.variants { + for i, want := range testCase.variants { got := union.Variants[i].Type.Target if primitive, shared := want.(ir.PrimitiveKind); shared { assert.Equal(t, ir.PrimitiveTypeID(primitive), got, "%s variant %d", site.pointer, i) @@ -239,3 +241,44 @@ func TestLower_ATypeArraysContentIsTheStringVariants(t *testing.T) { } assert.Len(t, diags, 4) } + +// TestTypeArray_AnObjectVariantComposesTheMembersBesideTheList holds a type +// list of a string and an object, its properties and required list written +// flat, on an allOf entry beside the list, beside an allOf holding the list, +// and on a second entry in either order, to one lowering: the Union of the +// string and a Model holding the required integer a, nothing kept and nothing +// reported (docs/compilers/openapi.md#type-arrays). +func TestTypeArray_AnObjectVariantComposesTheMembersBesideTheList(t *testing.T) { + t.Parallel() + const list, members = "type: [string, object]", "properties: {a: {type: integer}}, required: [a]" + spellings := map[string]string{ + "Flat": "{" + list + ", " + members + "}", + "Entry": "{" + list + ", allOf: [{" + members + "}]}", + "Beside": "{allOf: [{" + list + "}], " + members + "}", + "Entries": "{allOf: [{" + list + "}, {" + members + "}]}", + "EntriesRev": "{allOf: [{" + members + "}, {" + list + "}]}", + } + var written strings.Builder + for name, spelled := range spellings { + written.WriteString(" " + name + ": " + spelled + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for name := range spellings { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s: got %T", name, typeByName(doc, name)) + assert.Empty(t, union.Unmodeled, name) + require.Len(t, union.Variants, 2, name) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), union.Variants[0].Type.Target, name) + model, ok := doc.Types[union.Variants[1].Type.Target].(*ir.Model) + require.True(t, ok, "%s: the object variant is a Model", name) + require.Len(t, model.Properties, 1, name) + assert.Equal(t, "a", model.Properties[0].WireName, name) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveInteger), model.Properties[0].Type.Target, name) + assert.True(t, model.Properties[0].Required, name) + for _, diagnostic := range diags { + assert.False(t, strings.HasPrefix(string(diagnostic.Provenance.Pointer), "/components/schemas/"+name+"/") || + string(diagnostic.Provenance.Pointer) == "/components/schemas/"+name, "%s: %s", name, diagnostic.Message) + } + } +} diff --git a/compilers/openapi/internal/schema/unionbeside.go b/compilers/openapi/internal/schema/unionbeside.go index 9c38a5b35..5a6a6ea20 100644 --- a/compilers/openapi/internal/schema/unionbeside.go +++ b/compilers/openapi/internal/schema/unionbeside.go @@ -6,67 +6,51 @@ package schema import ( "encoding/json/jsontext" "slices" - "strconv" + "strings" "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" - "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) -// hasUnionSiblings reports whether a oneOf/anyOf schema also carries structural -// keywords (a type, properties, a composing allOf, const/enum, ...) or a keyword -// that narrows an instance without declaring one. When it does, the union alone -// cannot represent the schema, so the sibling body is lowered too (invariant 2, -// docs/ir/models.md#composition-beside-a-union), unless the branches declare -// shape and say every one of those keywords (branchesSay): the schema then means -// the union alone. Branches declaring none narrow the body, whatever they -// repeat, and a discriminator routing to branches composing the body keeps it, -// their base (composedByBranch). A refining allOf is no body -// (docs/compilers/openapi.md#allof-refinement). +// hasUnionSiblings reports whether schema writes a oneOf or an anyOf that its +// position does not lower as its Union alone, so its body is lowered too +// (invariant 2, docs/ir/models.md#composition-beside-a-union). func hasUnionSiblings(loweringContext lowering.Ctx, schema *statement.Schema) bool { - if !declaresUnion(schema) || composedByBranch(loweringContext, schema, besideUnion(schema, "")) { - return writesSiblingKeyword(schema) // no branch says it, or the body is their base - } - siblings := siblingKeywords(schema) - if !allOfComposes(loweringContext, schema) { - siblings = slices.DeleteFunc(siblings, func(k string) bool { return k == "allOf" }) - } - if len(siblings) == 0 { - return false - } - said := branchesSay(loweringContext, schema, schema) - if slices.ContainsFunc(siblings, func(k string) bool { return !slices.Contains(said, k) }) { - return true - } - // A oneOf and an anyOf sharing no value lower as the body beside them - // where it is no Model (unionPairApart), whatever their branches say. - return !unionBranchesDeclareShape(loweringContext, schema) || pairSharesNoValue(loweringContext, schema) && !ownDispatch(loweringContext, schema).buildsModel(loweringContext, schema) + return declaresUnion(schema) && !unionLoweredAlone(loweringContext, schema, schema) +} + +// unionLoweredAlone reports whether the union position's conjunction chooses +// is holder's and the position: alone, leaving null alone, or a +// Union of its live branches conjoined with the body's kind (readLoweredUnion). +func unionLoweredAlone(loweringContext lowering.Ctx, position, holder *statement.Schema) bool { + return loweredUnionWrittenBy(loweringContext, position, holder) && readLoweredUnion(loweringContext, position).besideRest.loweredAlone() } // restatableKeywords are the keywords beside a union that its branches can say // in full, read as an admissionReader reads what a schema admits. var restatableKeywords = []string{"type", "format", "enum", "const", "items"} -// branchesSayOf keys what branchesSay read of one union and the schema -// writing keywords beside it. -type branchesSayOf struct { +// keywordsBranchesRestateKey keys what keywordsBranchesRestate read of one +// union and the schema writing keywords beside it. +type keywordsBranchesRestateKey struct { union, beside *statement.Schema } -// branchesSay returns the keywords of restatableKeywords beside writes that -// every branch of union's oneOf and anyOf already says: a `type` naming each -// kind a branch admits, null included, and a `format`, an `enum`, a `const` or -// an `items` each branch is held to (admissionReader.holds). Such a keyword adds -// nothing to the union, as if it were not written +// keywordsBranchesRestate returns the keywords of restatableKeywords beside +// writes that every branch of union's oneOf and anyOf already says: a `type` +// naming each kind a branch admits, null included, and a `format`, an `enum`, a +// `const` or an `items` each branch is held to (admissionReader.holds). Such a +// keyword adds nothing to the union, as if it were not written // (docs/compilers/openapi.md#union-beside-structure); beside is union, or a // conjunct of the allOf holding it. A read cut short says none, as does a union // of no branch, which every keyword would pass. Every reader asks, so it is // read once a run. -func branchesSay(loweringContext lowering.Ctx, union, beside *statement.Schema) []string { - return lowering.ReadOncePerRun(loweringContext, branchesSayOf{union, beside}, func() []string { +func keywordsBranchesRestate(loweringContext lowering.Ctx, union, beside *statement.Schema) []string { + return lowering.ReadOncePerRun(loweringContext, keywordsBranchesRestateKey{union, beside}, func() []string { choice := union.ChoiceKeywords() branches := slices.Concat(choice.OneOf, choice.AnyOf) if len(branches) == 0 { @@ -74,8 +58,8 @@ func branchesSay(loweringContext lowering.Ctx, union, beside *statement.Schema) } admissionReader := newAdmissionReader(loweringContext) reads := make([]admitted, len(branches)) - for i, b := range branches { - reads[i] = lowered(&admissionReader, loweringContext.Statements().Subschema(b)) + for i, branch := range branches { + reads[i] = lowered(&admissionReader, loweringContext.Statements().Subschema(branch)) } if admissionReader.incomplete() { return nil @@ -85,7 +69,9 @@ func branchesSay(loweringContext lowering.Ctx, union, beside *statement.Schema) if !hasKey(beside, key) { continue } - if !slices.ContainsFunc(reads, func(admittedValue admitted) bool { return !branchSays(&admissionReader, admittedValue, beside, key) }) { + if !slices.ContainsFunc(reads, func(admittedValue admitted) bool { + return !branchRestates(&admissionReader, admittedValue, beside, key) + }) { out = append(out, key) } } @@ -93,13 +79,13 @@ func branchesSay(loweringContext lowering.Ctx, union, beside *statement.Schema) }) } -// branchSays reports whether a branch admitting branch, as admissionReaderValue -// reads it, says all that schema's keyword key does. A `type` is compared with -// null in it, which admissionReader.holds leaves to the nulls reader: a union -// lowered alone lifts a null branch onto the position, so a `type` leaving null -// out says more than a branch admitting it. An `items` list says what no single -// schema does. -func branchSays(admissionReaderValue *admissionReader, branch admitted, schema *statement.Schema, key string) bool { +// branchRestates reports whether a branch admitting branch, as +// admissionReaderValue reads it, says all that schema's keyword key does. A +// `type` is compared with null in it, which admissionReader.holds leaves to the +// nulls reader: a union lowered alone lifts a null branch onto the position, so +// a `type` leaving null out says more than a branch admitting it. An `items` +// list says what no single schema does. +func branchRestates(admissionReaderValue *admissionReader, branch admitted, schema *statement.Schema, key string) bool { switch key { case "type": return branch.kinds&^writtenKinds(schema, admissionReaderValue.nullable) == 0 @@ -111,207 +97,6 @@ func branchSays(admissionReaderValue *admissionReader, branch admitted, schema * } } -// unionLowering names how a oneOf/anyOf co-declared with structural keywords is -// lowered. -type unionLowering int - -const ( - // unionDistributed distributes the sibling composition across the union - // variants: one Model per branch carrying the enclosing Base/Mixins and own - // properties conjoined with that branch. The Union is the value and the - // composition rides on every variant, which is exactly the ∧-of-∨ the source - // wrote. - unionDistributed unionLowering = iota - // unionValidationOnly marks a union whose branches only narrow what the - // sibling body accepts; it is kept verbatim under ReasonValidationOnly. - unionValidationOnly - // unionSharesNoKind marks a union none of whose branches shares a kind with - // what the allOf beside it admits (unionAside): no instance satisfies them - // together, so no variant would hold a value. - unionSharesNoKind - // unionUncomposableBody marks a union beside a body that is not a Model — a - // const, an enum, a scalar, or object keywords with no type where the kinds - // the position lowers to are not an object alone — so there are no - // composition fields to distribute into. - unionUncomposableBody - // unionUnresolvedBranch marks a union with a $ref branch naming nothing this - // compilation can resolve — a target in a document it did not read, an - // undeclared component, a pointer addressing no schema. - unionUnresolvedBranch - // unionHierarchyBase marks a union beside a discriminator routing to - // branches that compose the body through allOf, its subtypes, which a union - // of composed variants would no longer have for a base - // (composedByBranch). - unionHierarchyBase - // unionRoutedSubtype marks a body a discriminator on an ancestor routes to - // (routedSubtype). The route names the type the body lowers to, which as a - // union would be no subtype of that ancestor, so it stays a Model composing - // the union as a mixin (lowerSubtypeUnion). - unionRoutedSubtype - // unionNoLiveBranch marks a union no branch of which an instance of the - // body satisfies (deadBranch), a null branch aside: distributing it would - // build no variant a value inhabits. - unionNoLiveBranch - // unionPassedApart marks a union beside another the position does not - // elect, sharing no kind with the body (passedApart): no instance satisfies - // the two together, whichever branch it takes. - unionPassedApart - // unionPassedNull marks a union beside another the position does not - // elect, the two leaving the body null alone (passedSharesNull): the - // position admits that null and nothing else, so it lowers as the body - // keeping both. - unionPassedNull - // unionPairApart marks a oneOf and an anyOf sharing no value with each - // other (pairSharesNoValue) beside a body that is not a Model: no instance - // satisfies them, whatever it admits. - unionPairApart -) - -// classifyUnionSiblings picks the lowering for a schema whose oneOf/anyOf sits -// beside structural keywords. JSON Schema conjoins keywords, so such a schema -// is an intersection of a structural body and a union, which the IR -// deliberately has no combinator for -// (docs/ir/boundaries.md#deliberate-exclusions). Every outcome keeps both -// sides: classified where the IR can express the conjunction, verbatim where it -// cannot. -// -// What the body does with a union it may distribute is classifyConjoined's. -// docs/compilers/openapi.md#union-beside-structure enumerates the shapes. -func classifyUnionSiblings(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) unionLowering { - if !unionBranchesDeclareShape(loweringContext, schema) { - return unionValidationOnly - } - if unionAside(loweringContext, schema) { - return unionSharesNoKind - } - if !ownDispatch(loweringContext, schema).buildsModel(loweringContext, schema) { - if pairSharesNoValue(loweringContext, schema) { - return unionPairApart - } - return unionUncomposableBody - } - // Of a oneOf and an anyOf written beside the body, the oneOf is elected - // (unionBranches), as on one entry of its allOf or two, and the other is - // kept on each variant (buildComposedVariant). - if !branchesNameReferents(loweringContext, schema, schema) { - return unionUnresolvedBranch - } - return classifyConjoined(loweringContext, schema, besideUnion(schema, pointer), pointer) -} - -// classifyConjoined is how s, written at pointer, lowers the union u it -// conjoins with a composing body, beside it or on an entry of its allOf, once -// u's own shape allows distribution: kept whole where the discriminator standing -// with u routes to branches composing s (composedByBranch), composed as a mixin -// where one on an ancestor routes to s (routedSubtype, lowerSubtypeUnion), kept -// whole where no branch lives beside s (deadBranches); else distributed, the -// discriminator routing the composed variants (indexBranches). -func classifyConjoined(loweringContext lowering.Ctx, schema *statement.Schema, unionAtValue unionAt, pointer jsontext.Pointer) unionLowering { - if passedApart(loweringContext, schema, unionAtValue) { - return unionPassedApart - } - if passedSharesNull(loweringContext, schema, unionAtValue) { - return unionPassedNull - } - if composedByBranch(loweringContext, schema, unionAtValue) { - return unionHierarchyBase - } - if routedSubtype(loweringContext, schema, pointer) { - return unionRoutedSubtype - } - if !hasLiveBranch(loweringContext, unionAtValue, deadBranches(loweringContext, schema, unionAtValue.holder)) { - return unionNoLiveBranch - } - return unionDistributed -} - -// passedApart reports whether a union the position written by schema passes -// over for unionAtValue leaves no value unionAtValue admits beside the rest of -// schema (readPassed): one shares no kind with that rest, one of null alone -// among them where the rest admits no null, or together they leave the rest -// null alone and no branch of unionAtValue admits null. It is a conjunct of the -// rest unionAtValue's branches are read against, so no branch of unionAtValue -// reads as dead though none can be inhabited. A read cut short says no. -func passedApart(loweringContext lowering.Ctx, schema *statement.Schema, unionAtValue unionAt) bool { - passedRead, ok := readPassed(loweringContext, schema, unionAtValue) - if !ok { - return false - } - if slices.ContainsFunc(passedRead.passed, func(admittedValue admitted) bool { - return admittedValue.kinds != 0 && passedRead.rest.kinds&admittedValue.kinds == 0 - }) { - return true - } - // Left null alone, the rest admits no object for deadBranch to read - // unionAtValue's branches against (restAdmitsObjects). - return passedRead.nullLeft() && passedRead.union.kinds&kindNull == 0 -} - -// passedSharesNull reports whether the unions the position written by schema -// passes over for unionAtValue leave the rest of schema null alone -// (readPassed), which unionAtValue admits: the position admits that null and -// nothing else, as on the entries of its allOf -// (docs/compilers/openapi.md#union-beside-structure). -func passedSharesNull(loweringContext lowering.Ctx, schema *statement.Schema, unionAtValue unionAt) bool { - passedRead, ok := readPassed(loweringContext, schema, unionAtValue) - return ok && passedRead.nullLeft() && passedRead.union.kinds&kindNull != 0 -} - -// passedRead is what the position written by s admits beside u: the rest of -// s read without any union, each union the position passes over for u, and -// what u's branches admit. -type passedRead struct { - rest, union admitted - passed []admitted -} - -// nullLeft reports whether the rest, with every union passed over, admits -// null alone. -func (r passedRead) nullLeft() bool { - left := r.rest - for _, admitted := range r.passed { - left = left.and(admitted) - } - return len(r.passed) > 0 && left.reachable() && left.kinds == kindNull -} - -// readPassed reads passedRead for unionAtValue: the other combinator -// unionAtValue's holder writes and the union another inline entry of schema's -// allOf writes are passed over, each other entry a conjunct of the rest. ok is -// false where a read is cut short or the rest admits nothing. -func readPassed(loweringContext lowering.Ctx, schema *statement.Schema, unionAtValue unionAt) (passedRead, bool) { - admissionReader := newAdmissionReader(loweringContext) - var passedReadValue passedRead - if set, _ := passedOver(loweringContext, schema, unionAtValue.holder); set != nil { - passedReadValue.passed = append(passedReadValue.passed, admissionReader.union(set)) - } - passedReadValue.rest = admissionReader.written(schema, admissionReader.nullable) - for _, entry := range allOfEntries(loweringContext, schema, "").entries { - bs := entry.schema.Schema - switch { - case !stated(bs): - case entry.schema.Ref != nil: - passedReadValue.rest = passedReadValue.rest.and(admissionReader.of(entry.schema)) - case bs == unionAtValue.holder || unionAtValue.entry && declaresUnion(bs): - passedReadValue.rest = passedReadValue.rest.and(admissionReader.written(bs, admissionReader.nullable)) - if bs != unionAtValue.holder { - passedReadValue.passed = append(passedReadValue.passed, unionsIn(&admissionReader, bs)) - } - default: - passedReadValue.rest = passedReadValue.rest.and(inlineConjunct(&admissionReader, bs)) - } - } - branches, _, _ := unionAtValue.branches(loweringContext) - passedReadValue.union = admissionReader.union(branches) - return passedReadValue, !admissionReader.incomplete() && passedReadValue.rest.reachable() -} - -// pairSharesNoValue reports whether schema writes a oneOf and an anyOf that -// share no value, as every spelling of the two reads it (pairApart). -func pairSharesNoValue(loweringContext lowering.Ctx, schema *statement.Schema) bool { - return writesBothUnions(schema) && pairApart(loweringContext, schema) != nil -} - // routedSubtype reports whether a discriminator on an ancestor of schema, // written at pointer, routes to schema as its subtype: by a mapping key or by // its name as a component, the tag its lowering takes @@ -330,159 +115,501 @@ func routedSubtype(loweringContext lowering.Ctx, schema *statement.Schema, point // about whether they carry the body, with nothing in the IR saying which. A // branch writing its $ref beside other keywords is read by that $ref. func branchesNameReferents(loweringContext lowering.Ctx, position, schema *statement.Schema) bool { - branches, _, _ := unionBranches(loweringContext, position, schema) - return !slices.ContainsFunc(branches, func(b statement.Subschema) bool { - ref := referenceOf(loweringContext, loweringContext.Statements().Subschema(b)) + branches := loweredKeyword(loweringContext, position, schema).branchesOf(schema) + return !slices.ContainsFunc(branches, func(branch statement.Subschema) bool { + ref := referenceOf(loweringContext, loweringContext.Statements().Subschema(branch)) return ref != nil && !namesReferent(loweringContext, ref) }) } -// coDeclaredUnionWhyPrefix opens every lowerCoDeclaredUnion why string: at -// each of its reasons, a structural body genuinely sits beside the union, so -// the sentence that follows is always true of it. -const coDeclaredUnionWhyPrefix = "oneOf/anyOf co-declared with structural keywords intersects with them, and " - -// lowerCoDeclaredUnion lowers a schema whose oneOf/anyOf sits beside structural -// keywords, per classifyUnionSiblings, fin finishing the node built, where st -// says. A union distributed over its body composes an object, which no -// refinement's principal is, so only the union kept beside the body stands -// elsewhere. -func lowerCoDeclaredUnion(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, fin finisher, - st stand, -) (ir.TypeID, []ir.Diagnostic) { - beside := func(reason ir.UnmodeledReason, why string) (ir.TypeID, []ir.Diagnostic) { - if why != "" { - why = coDeclaredUnionWhyPrefix + why - } - return lowerBesideUnmodeledUnion(loweringContext, ts, depth, schema, pointer, reason, why, fin, st) - } - switch classifyUnionSiblings(loweringContext, schema, pointer) { - case unionDistributed: - return lowerDistributedUnion(loweringContext, ts, depth, schema, besideUnion(schema, pointer), pointer, fin) - case unionValidationOnly: - id, diags := beside(ir.ReasonValidationOnly, "") - switch { - case writesConjuncts(schema): - // The conjuncts' report names them (diagDisjointConjuncts). - return id, diags - case pairSharesNoValue(loweringContext, schema): - return id, append(diags, diagUnionsShareNothing(loweringContext, schema, pointer, "its body alone")...) - case writesBothUnions(schema) || !ownDispatch(loweringContext, schema).buildsModel(loweringContext, schema): - // Two sharing only a null the body keeps out share no value with it, - // and a union sharing no kind with a body that is no Model none. - return id, append(diags, diagUnionApartFromBody(loweringContext, schema, pointer)...) - default: - return id, diags - } - case unionSharesNoKind: - return beside(ir.ReasonDegradedLowering, - "none of its branches shares a kind with the allOf beside it, so no instance satisfies them together") - case unionUncomposableBody: - id, diags := beside(ir.ReasonDegradedLowering, "the body is not a model, so it carries no composition to distribute into") - if st.of != nil { - // A principal's conjunction is reported at the schema writing it (refinedDisjoint). - return id, diags +// coDeclaredUnionWhyPrefix opens the info of a union kept beside the +// structural keywords schema writes (keptUnionsWhy), and unionBesideRestPrefix +// that of one schema writes beside none, whose rest is what the schema writes +// otherwise. +const ( + coDeclaredUnionWhyPrefix = "oneOf/anyOf co-declared with structural keywords intersects with them, and " + unionBesideRestPrefix = "oneOf/anyOf written here intersects with the rest of the schema, and " +) + +// lowerCoDeclaredUnion lowers schema, writing the union its conjunction chooses +// beside its body, as the union reading of its position decides +// (readLoweredUnion). A union distributed over its body composes an object, +// which no refinement's principal is, so only the union kept beside the body +// is placed elsewhere. +func lowerCoDeclaredUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { + position, at := placement.positionOrSchema(schema), placement.pointer(pointer) + beside := func(reason ir.UnmodeledReason, why string) (builtPosition, []ir.Diagnostic) { + if unionsFolded(loweringContext, position) { + // The warning that no value satisfies the position says it keeps + // the union, its one report. + why = "" } - return id, append(diags, diagUnionApartFromBody(loweringContext, schema, pointer)...) + return lowerBesideUnmodeledUnion(loweringContext, types, depth, schema, pointer, reason, keptUnionsWhy(schema, why), placement) + } + unionSite, _ := loweredUnionAt(loweringContext, position, at) + switch readLoweredUnion(loweringContext, position).besideRest { + case unionDistributed, unionSplitByKind: + return lowerDistributedUnion(loweringContext, types, depth, schema, unionSite, pointer) + case unionValidationOnly, unionKeptAsValidation: + return beside(ir.ReasonValidationOnly, "") + case unionKeptByRest: + return beside(ir.ReasonDegradedLowering, "the body is not a model, so it carries no composition to distribute into") + case unionKeptWithDeadBranch: + built, diags := beside(ir.ReasonDegradedLowering, "the body is not a model, so it carries no composition to distribute into") + return built, append(diags, diagDeadAtUnion(loweringContext, position, at, false)...) case unionUnresolvedBranch: - id, diags := beside(ir.ReasonDegradedLowering, + built, diags := beside(ir.ReasonDegradedLowering, "a branch's $ref names no referent this compilation resolves") - return id, append(diagUnresolvedBranches(loweringContext, schema, pointer), diags...) + return built, append(diagUnresolvedBranches(loweringContext, schema, pointer), diags...) case unionRoutedSubtype: - return lowerSubtypeUnion(loweringContext, ts, depth, schema, besideUnion(schema, pointer), pointer, fin) - case unionNoLiveBranch: - id, diags := beside(ir.ReasonDegradedLowering, - "none of its branches admits an object its body admits, so no variant conjoining the two would hold a value") - dead := diagDeadBranches(loweringContext, schema, besideUnion(schema, pointer), deadBranches(loweringContext, schema, schema), pointer, false) - if len(dead) == 0 && pairSharesNoValue(loweringContext, schema) { - // A union of null alone has no branch to mark dead, and the - // conjuncts' report names no union: the pair says it. - dead = diagUnionsShareNothing(loweringContext, schema, pointer, "its body alone") - } - return id, append(diags, dead...) - case unionPairApart: - // A schema writing conjuncts beside them refines past them (entryUnionsApart). - id, diags := beside(ir.ReasonDegradedLowering, "its oneOf and anyOf share no value, so no instance satisfies them together") - return id, append(diags, diagUnionsShareNothing(loweringContext, schema, pointer, "its body alone")...) - case unionPassedNull: - _, passed := passedOver(loweringContext, schema, schema) - return beside(ir.ReasonDegradedLowering, "the "+passed+" beside it leaves the body null alone, which this "+ - "union admits, so the position admits that null and no variant would hold a value") - case unionPassedApart: - _, passed := passedOver(loweringContext, schema, schema) - id, diags := beside(ir.ReasonDegradedLowering, "the "+passed+" beside it leaves the body no value this union "+ - "admits, so no instance satisfies them together") - return id, append(diags, diagUnionsApart(loweringContext, schema, pointer)...) - default: // unionHierarchyBase + return lowerSubtypeUnion(loweringContext, types, depth, schema, unionSite, pointer) + case unionLeavesNoBranch: + return lowerNoLiveUnion(loweringContext, types, depth, schema, pointer, placement) + case unionSaysNothing, unionLiftsNull: + built, bodyDiags, afterDiags := lower(loweringContext, types, depth, schema, pointer, placement) + keptDiags := keepLiftedNulls(loweringContext, schema, pointer, placement, &built) + return built, slices.Concat(bodyDiags, keptDiags, afterDiags) + case unionHierarchyBase: return beside(ir.ReasonDegradedLowering, "the discriminator beside it routes to branches composing this schema, its subtypes, which distributing them into a union would undo") + default: // alone, leaving null alone or conjoined: the union is the position + built, ref, diags := lowerOneOfAnyOf(loweringContext, types, depth, schema, pointer, placement) + if built.node == nil { + built.id = ref.Target + } + return built, diags } } -// diagUnionsApart is the warning schema, written at pointer, draws where a -// union it passes over shares no kind with its body and no allOf it writes -// reports its conjuncts (docs/compilers/openapi.md#allof-disjoint-conjuncts): -// the body's keywords and that union, as that report names them. -func diagUnionsApart(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - if writesConjuncts(schema) { +// lowerNoLiveUnion lowers schema, written at pointer, whose conjunction chooses +// a union no branch of which lives, as its other conjuncts say, keeping its +// unions verbatim. The one warning that no value satisfies the position says +// what it lowered as and keeps (keptDeadUnions), so no info sits beside it +// (unionsFolded); a position drawing no such warning says why in an info +// (keptUnionsWhy). +func lowerNoLiveUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { + why := keptUnionsWhy(schema, noLiveBranchWhy) + if unionsFolded(loweringContext, placement.positionOrSchema(schema)) { + why = "" + } + built, diags := lowerBesideUnmodeledUnion(loweringContext, types, depth, schema, pointer, ir.ReasonDegradedLowering, why, placement) + switch { + case placement.position != nil: + case writesConjuncts(schema): + diags = append(diags, diagNoLiveBeside(loweringContext, schema, pointer, keptBodyShape(built))...) + default: + // The one report of conjuncts sharing no value reads the union as one. + diags = append(diags, diagNoLiveBranch(loweringContext, schema, pointer, keptBodyShape(built))...) + } + return built, diags +} + +// unionsFolded reports whether schema keeps the unions its conjunction writes +// verbatim, no branch of the one it chooses living, and draws the one warning +// that no value satisfies it (reportsNoValue), which says it keeps them +// (keptDeadUnions), so no union of it draws an info of its own wherever it is +// written (docs/compilers/openapi.md#union-beside-structure). +func unionsFolded(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return keptDeadUnions(loweringContext, schema) != "" && reportsNoValue(loweringContext, schema) +} + +// reportsNoValue reports whether schema, whose conjunction chooses a union no +// branch of which lives, draws the warning that no value satisfies it, read as +// each writer of that warning reads it. +func reportsNoValue(loweringContext lowering.Ctx, schema *statement.Schema) bool { + reading := readLoweredUnion(loweringContext, schema) + comp := allOfEntries(loweringContext, schema, "") + refinementValue, refines := refinementOf(loweringContext, schema, "") + switch { + case !writesConjuncts(schema) && (reading.nullTwice || len(disjointAtoms(loweringContext, schema, unionAndBodyAtoms(loweringContext, schema))) > 0): + return true + case refines && len(refinedDisjointNames(loweringContext, schema, refinementValue)) > 0, + !refines && writesConjuncts(schema) && len(disjointNames(loweringContext, schema, comp)) > 0: + return true + default: + names, _, _ := refusedBranches(loweringContext, schema, "") + return len(names) > 0 + } +} + +// keptDeadUnions is what a report that no value satisfies schema adds where +// schema keeps the unions its conjunction writes verbatim, each by its path +// from schema: every one where no branch of the chosen one lives, and at the +// bottom, which keeps each entry whole (composeBottom), those schema writes. +func keptDeadUnions(loweringContext lowering.Ctx, schema *statement.Schema) string { + conjunctionRead := readConjunction(loweringContext, schema) + var paths []string + switch { + case conjunctionRead.lowersUnion && readLoweredUnion(loweringContext, schema).besideRest == unionLeavesNoBranch: + for _, union := range conjunctionRead.unions { + paths = append(paths, strings.TrimPrefix(string(union.rel)+"/"+string(union.keyword), "/")) + } + case bottomAt(loweringContext, schema): + for _, union := range unionKeywords { + if hasKey(schema, string(union)) { + paths = append(paths, string(union)) + } + } + } + if len(paths) == 0 { + return "" + } + return ", its " + strings.Join(paths, " and ") + " kept verbatim under Unmodeled" +} + +// keepValidationOnlyUnion keeps the union schema, written at pointer, writes +// under keyword as validation logic: reported as a validation-only keyword, +// but where the warning that no value satisfies schema says it keeps it +// (unionsFolded), which is its one report. +func keepValidationOnlyUnion(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, keyword string, + pointer jsontext.Pointer, +) []ir.Diagnostic { + if !unionsFolded(loweringContext, schema) { + return keepValidationOnlyKeyword(loweringContext, unmodeled, schema, keyword, pointer) + } + _, diags := keepSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonValidationOnly, pointer) + return diags +} + +// foldedUnionWhy is the why of the unions holder, an inline entry of schema's +// allOf, keeps: unionKeptInReport, which keepEntryUnion keeps with no info, +// where schema's warning says it keeps them (unionsFolded), else "". +func foldedUnionWhy(loweringContext lowering.Ctx, schema, holder *statement.Schema) string { + holds := slices.ContainsFunc(readConjunction(loweringContext, schema).unions, func(union conjunctionUnion) bool { return union.holder == holder }) + if !holds || !unionsFolded(loweringContext, schema) { + return "" + } + return unionKeptInReport +} + +// unionKeptInReport is the why of a union an inline entry keeps where its +// position's warning says so (foldedUnionWhy). +const unionKeptInReport = "kept as its position's warning says" + +// keptUnionsWhy is the sentence the info of a union schema keeps beside its +// body says, opening why with what the union intersects with; none where why +// is none, as a validation-only union's is. +func keptUnionsWhy(schema *statement.Schema, why string) string { + if why == "" { + return "" + } + if !writesSiblingKeyword(schema) { + return unionBesideRestPrefix + why + } + return coDeclaredUnionWhyPrefix + why +} + +// keepLiftedNulls keeps on built, the node schema's body lowered to, where its +// conjunction's union lifts its null branches onto the reference +// (unionLiftsNull), what those branches write beside their null, as a union +// collapsed to a reference keeps them +// (docs/compilers/openapi.md#union-null-variant), and the union schema writes +// beside it, passed over; an entry writing both keeps the other as unread. +func keepLiftedNulls(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement, built *builtPosition) []ir.Diagnostic { + unionSite, ok := loweredUnionAt(loweringContext, schema, pointer) + if !ok || built.node == nil || readLoweredUnion(loweringContext, schema).besideRest != unionLiftsNull { return nil } - comp := allOfComposition{pointer: pointer} - comp.disjoint = disjointAtoms(loweringContext, schema, conjunctAtoms(loweringContext, schema, comp)) - return diagDisjointConjuncts(loweringContext, comp, "its body alone") + var diags []ir.Diagnostic + if unionSite.holder == schema { + key := unionSite.loweredKeyword(loweringContext) + keeps := builtKeeps{pendingKeeps: &built.pendingKeeps, pointer: pointer, placement: placement} + diags = keeps.keep(loweringContext, &built.node.Common().Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepUnusedCombinatorReports(loweringContext, unmodeled, unionSite, key) + }) + } + kept, reports := nullBranchesKept(loweringContext, nullBranchKeeps(loweringContext, schema, unionSite.holder, unionSite.pointer)) + return append(diags, addBuiltPendingKeeps(loweringContext, placement, &built.pendingKeeps, pointer, kept, reports)...) +} + +// noLiveBranchWhy says why no branch of a union lives where an info says so: +// at an inline principal, whose position draws the warning that names what +// it shares no kind with, the reasons a closure or a null give being folded +// into that warning wherever the position draws one itself (lowerNoLiveUnion). +const noLiveBranchWhy = "none of its branches shares a kind with the rest of this schema, so no instance satisfies them together" + +// keepOwnUnions keeps on unmodeled, that of the node schema, written at +// pointer, lowered to, each union schema writes that its conjunction does not +// lower, the union it chooses being an entry's or none: as the union reading +// keeps it (keptUnionReason), and reports those kept degraded once. +func keepOwnUnions(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + if !declaresUnion(schema) || loweredUnionWrittenBy(loweringContext, schema, schema) { + return nil + } + var diags []ir.Diagnostic + var kept []string + for _, union := range unionKeywords { + key := string(union) + if !hasKey(schema, key) { + continue + } + if keptUnionReason(loweringContext, schema, conjunctionUnion{holder: schema, keyword: union}) == ir.ReasonValidationOnly { + diags = append(diags, keepValidationOnlyUnion(loweringContext, unmodeled, schema, key, pointer)...) + continue + } + ok, keptDiags := keepSchemaKeyword(loweringContext, unmodeled, schema, key, ir.ReasonDegradedLowering, pointer) + diags = append(diags, keptDiags...) + if ok { + kept = append(kept, key) + } + } + if len(kept) == 0 || unionsFolded(loweringContext, schema) { + return diags + } + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + "%s written beside the union an allOf entry writes conjoins with it, and one Union carries one branch set; "+ + "kept verbatim under Unmodeled", strings.Join(kept, " and "))) +} + +// diagWidenedDead is the report of the dead branches of each union of a +// conjunction leaving the position, schema written at pointer, the null alone +// the nullable-inference policy reads in for it (unionReading.widened): one +// warning at each union's keyword naming them, beside a rest holding an +// object too, since the Enum keeps each union whole, and none for the +// position, which admits that null. +func diagWidenedDead(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + reading := readLoweredUnion(loweringContext, schema) + if !reading.widened { + return nil + } + out := diagDeadAtUnion(loweringContext, schema, pointer, true) + if names, key, at := refusedBranches(loweringContext, schema, pointer); reading.refused && len(names) > 0 { + out = []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, at, + "every branch of this %s requires a member the additionalProperties beside it refuses (%s), so no instance "+ + "satisfies them: the %s is kept verbatim under Unmodeled", key, strings.Join(names, "; "), key)} + } + for _, passed := range readConjunction(loweringContext, schema).passed() { + branches := passed.branches() + out = append(out, diagDeadBranchesAt(loweringContext, branches, passedDead(loweringContext, branches), passed.keyword, + passed.keyword.keywordAt(pointer+passed.rel))...) + } + return out +} + +// passedDead marks, by index, each of branches, those of a union the +// conjunction passes over, that shares no value with the rest of a +// conjunction no branch of whose chosen union lives, which admits null +// alone: one keeping null out, its read within the caps. A branch saying +// nothing of null, such as {} or {required: [a]}, admits it. +func passedDead(loweringContext lowering.Ctx, branches []statement.Subschema) []bool { + dead := make([]bool, len(branches)) + for i, branch := range branches { + schemaStatement := loweringContext.Statements().Subschema(branch) + dead[i] = admissionOf(loweringContext, schemaStatement).within() && nullAnswerReadingsOf(loweringContext, schemaStatement).forbids(loweringContext) + } + return dead +} + +// diagDeadAtUnion is the one warning the union the conjunction of schema, +// written at pointer, chooses draws at its keyword where some of its branches +// are dead (readLoweredUnion); none beside a rest holding an object unless +// besideObject says the position keeps the union there too, as one the policy +// leaves null alone does (docs/compilers/openapi.md#union-beside-structure). +func diagDeadAtUnion(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, besideObject bool) []ir.Diagnostic { + reading := readLoweredUnion(loweringContext, schema) + unionSite, ok := loweredUnionAt(loweringContext, schema, pointer) + if !ok || reading.restKinds&kindObject != 0 && !besideObject { + return nil + } + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) + return diagDeadBranchesAt(loweringContext, branches, reading.dead, key, key.keywordAt(unionSite.pointer)) +} + +// diagDeadBranchesAt is the one warning at at, the keyword key of a union +// listing branches, naming each branch dead marks by its path from the union +// with the kinds it admits; none where dead marks none. +func diagDeadBranchesAt(loweringContext lowering.Ctx, branches []statement.Subschema, dead []bool, key unionKeyword, at jsontext.Pointer) []ir.Diagnostic { + var names []string + for i, branch := range branches { + if !dead[i] { + continue + } + names = append(names, key.branchPath(i)+": "+deadBranchWords(loweringContext, loweringContext.Statements().Subschema(branch))) + } + if len(names) == 0 { + return nil + } + verb, pronoun := "share", "them" + if len(names) == 1 { + verb, pronoun = "shares", "it" + } + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, at, + "%d of the %d branches of this %s %s no value with the rest of the schema (%s), so no instance satisfies %s: "+ + "the %s is kept verbatim under Unmodeled", len(names), len(branches), key, verb, strings.Join(names, ", "), pronoun, key)} +} + +// diagDeadWhereNoUnionChosen is the warning each union of schema's conjunction, +// written at pointer, draws where the conjunction chooses none of several: the +// branches of it sharing no kind with the rest, the body and the other unions, +// at its keyword, as a passed-over union's are read against the chosen one +// (docs/compilers/openapi.md#union-beside-structure). Where the conjunction +// admits no value the report of conjuncts sharing none says so instead. +func diagDeadWhereNoUnionChosen(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + conjunctionRead := readConjunction(loweringContext, schema) + if conjunctionRead.lowersUnion || len(conjunctionRead.unions) < 2 { + return nil + } + admissionReaderValue := newAdmissionReader(loweringContext) + body := bodyWithoutUnions(&admissionReaderValue, schema) + unions := make([]admitted, len(conjunctionRead.unions)) + whole := body + for i, union := range conjunctionRead.unions { + unions[i] = admissionReaderValue.union(union.branches()) + whole = whole.and(unions[i]) + } + if admissionReaderValue.incomplete() || !whole.reachable() { + return nil + } + var diags []ir.Diagnostic + for i, union := range conjunctionRead.unions { + rest := body + for j := range conjunctionRead.unions { + if j != i { + rest = rest.and(unions[j]) + } + } + dead := deadAgainst(loweringContext, union.branches(), rest) + diags = append(diags, diagDeadBranchesAt(loweringContext, union.branches(), dead, union.keyword, union.keyword.keywordAt(pointer+union.rel))...) + } + return diags +} + +// diagNullRefusedTwice is the one warning schema, written at pointer, draws +// where the oneOf its conjunction chooses refuses the null the rest admits +// (unionReading.refusesNull) and the policy reads no null back in. It names +// at the keyword the branches null matches, as a null shared twice is named +// (docs/compilers/openapi.md#union-null-only). +func diagNullRefusedTwice(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { + reading := readLoweredUnion(loweringContext, schema) + unionSite, ok := loweredUnionAt(loweringContext, schema, pointer) + if !ok || !reading.refusesNull || schemaAdmitsNull(loweringContext, schema) { + return nil + } + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) + var names []string + for _, i := range oneOfLeavesNullTwice(loweringContext, branches, reading.dead) { + names = append(names, key.branchPath(i)) + } + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, key.keywordAt(unionSite.pointer), + "null matches %d of the %d branches of this oneOf (%s), which a oneOf refuses, so no null satisfies this schema "+ + "though the rest of it admits null", len(names), len(branches), strings.Join(names, ", "))} +} + +// deadAgainst marks each of branches whose declared kinds rest admits none of. +func deadAgainst(loweringContext lowering.Ctx, branches []statement.Subschema, rest admitted) []bool { + dead := make([]bool, len(branches)) + for k, branch := range branches { + kinds, inferred := lowersTo(loweringContext, loweringContext.Statements().Subschema(branch)) + dead[k] = !inferred && kinds&rest.kinds == 0 + } + return dead +} + +// diagNoLiveBranch is the one warning schema, written at pointer and writing +// no conjunct, draws where no branch of the union it chooses lives, the schema +// having lowered as shape. +func diagNoLiveBranch(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, shape string) []ir.Diagnostic { + if readLoweredUnion(loweringContext, schema).nullTwice { + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, pointer, + "no value satisfies this schema: no branch of its oneOf shares a value with the rest of it but null, and "+ + "null matches more than one of them, which a oneOf refuses; lowered as %s%s — let one branch alone admit null", + shape, keptDeadUnions(loweringContext, schema))} + } + if diags := diagUnionApartFromBody(loweringContext, schema, pointer, shape); len(diags) > 0 { + return diags + } + // A body admitting null alone, its kinds read alike, keeps the union, its dead + // branches reported there (noLiveBranchBesideRest), so a closure is all else. + return diagRefusedBranches(loweringContext, schema, pointer, shape) +} + +// diagNoLiveBeside is the one warning schema, written at pointer and writing +// an allOf beside the union its conjunction chooses, draws where no branch +// lives, the schema having lowered as shape: none where the conjuncts' report +// names the union, as their kinds share none (diagDisjointConjuncts), else +// the branches a closure refuses. +func diagNoLiveBeside(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, shape string) []ir.Diagnostic { + if len(disjointNames(loweringContext, schema, allOfEntries(loweringContext, schema, pointer))) > 0 { + return nil + } + // A body admitting null alone keeps the union instead (noLiveBranchBesideRest). + return diagRefusedBranches(loweringContext, schema, pointer, shape) +} + +// diagRefusedBranches is the one warning schema, written at pointer and +// lowered as shape, draws where every branch of the union its conjunction +// chooses requires a member the closure the position takes refuses +// (catchAllRejects), each named by its path from the position with the +// members refused. +func diagRefusedBranches(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, shape string) []ir.Diagnostic { + names, key, _ := refusedBranches(loweringContext, schema, pointer) + if len(names) == 0 { + return nil + } + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, pointer, + "no value satisfies this schema: every branch of its %s requires a member the additionalProperties beside it "+ + "refuses (%s); lowered as %s%s — admit those members or correct the branches", key, strings.Join(names, "; "), + shape, keptDeadUnions(loweringContext, schema))} +} + +// refusedBranches names, by path from pointer, each branch of the union the +// conjunction of schema, written at pointer, chooses with the members it +// requires that a closure beside it refuses, with the union's keyword and +// where it is written; none where no closure sits beside it. +func refusedBranches(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) ([]string, unionKeyword, jsontext.Pointer) { + unionSite, ok := loweredUnionAt(loweringContext, schema, pointer) + catchAll := catchAllSourceOf(schema, allOfEntries(loweringContext, schema, pointer)) + if !ok || catchAll.schema == nil { + return nil, "", "" + } + key := unionSite.loweredKeyword(loweringContext) + branches := key.branchesOf(unionSite.holder) + names := make([]string, 0, len(branches)) + for i, branch := range branches { + members := newComposedMembers() + members.add(loweringContext, loweringContext.Statements().Subschema(branch), map[*statement.Schema]bool{}) + if refused := catchAllScopeOf(loweringContext, catchAll, members).rejected; len(refused) > 0 { + names = append(names, pathFrom(pointer, key.branchAt(unionSite.pointer, i))+": "+strings.Join(refused, ", ")) + } + } + return names, key, key.keywordAt(unionSite.pointer) } // diagUnionApartFromBody is the warning schema, written at pointer beside a -// body that is no Model, draws where the unions it writes share no kind with -// that body (unionApartFromBodyNames) and no allOf it writes reports its -// conjuncts. -func diagUnionApartFromBody(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { +// body that is no Model and lowered as shape, draws where the unions it writes +// share no kind with that body (unionAndBodyAtoms) and no allOf it +// writes reports its conjuncts. +func diagUnionApartFromBody(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, shape string) []ir.Diagnostic { if writesConjuncts(schema) { return nil } comp := allOfComposition{pointer: pointer} - comp.disjoint = unionApartFromBodyNames(loweringContext, schema) - return diagDisjointConjuncts(loweringContext, comp, "its body alone") -} - -// unionApartFromBodyNames names the body schema writes and each union beside -// it, as conjunctAtoms names them, where they share no kind, and is nil where -// they share one. -func unionApartFromBodyNames(loweringContext lowering.Ctx, schema *statement.Schema) []string { - return disjointAtoms(loweringContext, schema, unionAndBodyAtoms(loweringContext, schema)) + comp.disjoint = disjointAtoms(loweringContext, schema, unionAndBodyAtoms(loweringContext, schema)) + return diagDisjointConjuncts(loweringContext, schema, comp, shape) } -// unionApartFromBody reports whether the atoms unionApartFromBodyNames reads -// share no kind, a read cut short admitting every kind and a null every one -// may admit being shared, without naming them: naming reads each target that -// admits nothing, which may read schema again. -func unionApartFromBody(loweringContext lowering.Ctx, schema *statement.Schema) bool { - joint := anyInstance - for _, a := range unionAndBodyAtoms(loweringContext, schema) { - joint &= a.admits +// keptBodyShape names built, the node a position keeping its union beside its +// body lowered to, for a report of what it lowered as: by its kind, and as +// what its body lowers to where this visit built no node. +func keptBodyShape(built builtPosition) string { + shape := "what its other keywords lower to" + if built.node != nil { + shape = nodeShape(built.node.Kind()) } - return joint == 0 && !nullShared(loweringContext, schema) + return shape } // unionAndBodyAtoms are the atoms of the body schema writes and of each union // it writes, the union atoms conjunctAtoms adds replaced by both unions'. func unionAndBodyAtoms(loweringContext lowering.Ctx, schema *statement.Schema) []conjunctAtom { - choice := schema.ChoiceKeywords() - atoms := slices.DeleteFunc(conjunctAtoms(loweringContext, schema, allOfComposition{}), func(a conjunctAtom) bool { return a.union != nil }) - return slices.Concat(atoms, unionAtoms(loweringContext, "oneOf", choice.OneOf), unionAtoms(loweringContext, "anyOf", choice.AnyOf)) -} - -// keepsUnionApartFromBody reports whether schema, read at the position its -// bindings place it at, writes a union sharing no kind with a body beside it -// that is no Model, which schema reports where it is written -// (diagUnionApartFromBody), as keepsDeadUnion reads a dead union. -func keepsUnionApartFromBody(loweringContext lowering.Ctx, schema *statement.Schema) bool { - at, placed := siteOf(schema) - if !placed || !declaresUnion(schema) || writesConjuncts(schema) || !hasUnionSiblings(loweringContext, schema) { - return false - } - in, _ := lowering.InDocument(loweringContext, at.Doc) - return classifyUnionSiblings(in, schema, at.Pointer) == unionUncomposableBody && unionApartFromBody(in, schema) + atoms := slices.DeleteFunc(conjunctAtoms(loweringContext, schema, allOfComposition{}), func(atom conjunctAtom) bool { return atom.union != nil }) + return slices.Concat(atoms, writtenUnionAtoms(loweringContext, "", schema)) } // diagUnresolvedBranches returns one diagnostic per union branch whose $ref @@ -493,57 +620,62 @@ func keepsUnionApartFromBody(loweringContext lowering.Ctx, schema *statement.Sch // at the same severity as everywhere else, with the reason refTypeRef's report // gives (unresolvedWhy). func diagUnresolvedBranches(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) []ir.Diagnostic { - branches, key, _ := unionBranches(loweringContext, schema, schema) + key := loweredKeyword(loweringContext, schema, schema) + branches := key.branchesOf(schema) var diags []ir.Diagnostic - for i, b := range branches { - st := referenceOf(loweringContext, loweringContext.Statements().Subschema(b)) - if st == nil || namesReferent(loweringContext, st) || onLoop(st) { + for i, branch := range branches { + schemaStatement := referenceOf(loweringContext, loweringContext.Statements().Subschema(branch)) + if schemaStatement == nil || namesReferent(loweringContext, schemaStatement) || onLoop(schemaStatement) { continue } - keyword, ref := refSpelling(st) - diags = append(diags, loweringContext.DiagAt(ir.SeverityError, diag.UnresolvedRef, - pointer+ids.Ptr(key, strconv.Itoa(i)), - "union branch %s %q is unresolved%s; the branch is kept verbatim", keyword, ref, unresolvedWhy(loweringContext, st))) + diags = append(diags, unresolvedRefReport(loweringContext, key.branchAt(pointer, i), schemaStatement, + "union branch %s %q is unresolved%s; the branch is kept verbatim")) } return diags } // lowerBesideUnmodeledUnion lowers the structural body of a schema that -// co-declares oneOf/anyOf and keeps the union verbatim beside it, so neither the -// structural shape nor the union is dropped. reason says which kind of union it -// is and why says what stopped a classified lowering; lowerCoDeclaredUnion picks -// both from classifyUnionSiblings' verdict. A discriminator the body's model -// holds is settled once every node is interned (discriminatorBesideUnion). The -// node stands where st says. -func lowerBesideUnmodeledUnion(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, - reason ir.UnmodeledReason, why string, fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { - var siblings finished - beside := discriminatorBesideUnion(loweringContext, ts, schema, schema, pointer).then(siblings.on(func(td ir.TypeDef) []ir.Diagnostic { - return preserveUnionSiblingsAt(loweringContext, &td.Common().Unmodeled, schema, pointer, reason, why) - })).then(fin) - inner, diags := lower(loweringContext, ts, depth, schema, pointer, beside, st) - owner := inner - if !siblings.ran && !LoweredToOwnNode(loweringContext, st.pointer(pointer), ir.TypeRef{Target: inner}) { +// co-declares oneOf/anyOf and keeps the union verbatim beside it, so neither +// the structural shape nor the union is dropped. reason says which kind of +// union it is and why says what stopped a classified lowering, empty where the +// warning that no value satisfies the position says it (unionsFolded). A +// discriminator the body's model holds is settled once every node is interned +// (deferDiscriminatorBesideUnion). +func lowerBesideUnmodeledUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, pointer jsontext.Pointer, + reason ir.UnmodeledReason, why string, placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { + built, bodyDiags, disjointDiags := lower(loweringContext, types, depth, schema, pointer, placement) + diags := slices.Concat(bodyDiags, disjointDiags) + if built.node == nil && !LoweredToOwnNode(loweringContext, placement.pointer(pointer), ir.TypeRef{Target: built.id}) { // The structural body reduced to a shared/aliased target; hoist an alias // so the preserved union attaches to a node this pointer owns, never to a // shared primitive. var aliasDiags []ir.Diagnostic - owner, aliasDiags = internAlias(loweringContext, ts, schema, pointer, ir.TypeRef{Target: inner}, beside, st) + built, aliasDiags = internAlias(loweringContext, types, schema, pointer, scalarBase(loweringContext, schema, placement, built.id), placement) diags = append(diags, aliasDiags...) } - return owner, append(diags, siblings.diags...) + if built.node != nil { + deferDiscriminatorBesideUnion(loweringContext, schema, schema, built.node) + keeps := builtKeeps{pendingKeeps: &built.pendingKeeps, pointer: pointer, placement: placement} + diags = append(diags, keeps.keep(loweringContext, &built.node.Common().Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return keepUnionSiblingsAt(loweringContext, unmodeled, schema, pointer, reason, why) + })...) + } + return built, diags } -// preserveUnionSiblingsAt stores the raw oneOf/anyOf of schema under unmodeled, -// the Unmodeled of the node standing at the position. A validation-only union -// joins the validation-only keywords and is reported with it; anything else is -// a degraded lowering and says so. why is the caller's complete sentence. -func preserveUnionSiblingsAt(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, reason ir.UnmodeledReason, why string) []ir.Diagnostic { - kept, diags := preserveBranchSets(loweringContext, unmodeled, schema, reason, pointer) - if reason == ir.ReasonValidationOnly || len(kept) == 0 { - return diags +// keepUnionSiblingsAt stores the raw oneOf/anyOf of schema under unmodeled, the +// Unmodeled of the node at the position. A validation-only union is kept with +// the validation-only keywords and is reported with it; anything else is a +// degraded lowering and says so where why, the caller's complete sentence, says +// why, the report paired with the first set's key. +func keepUnionSiblingsAt(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, pointer jsontext.Pointer, reason ir.UnmodeledReason, + why string, +) annotation.KeptReports { + kept, reports := keepBranchSets(loweringContext, unmodeled, schema, reason, pointer) + if reason == ir.ReasonValidationOnly || len(kept) == 0 || why == "" { + return reports } - return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, - "%s; union branches kept verbatim under Unmodeled", why)) + return append(reports, annotation.ReportsOf(annotation.EntryKey("", kept[0]), loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + "%s; union branches kept verbatim under Unmodeled", why))...) } diff --git a/compilers/openapi/internal/schema/unionbesiderest.go b/compilers/openapi/internal/schema/unionbesiderest.go new file mode 100644 index 000000000..68a017a41 --- /dev/null +++ b/compilers/openapi/internal/schema/unionbesiderest.go @@ -0,0 +1,148 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +// unionBesideRest is how the union a conjunction lowers relates to the rest +// of it, and so how its position lowers it, in the order +// docs/compilers/openapi.md#union-beside-structure decides: dead branches +// read, then null alone, then no live branch, then whether the body says +// anything the union does not and what kind of body says it, then the shape +// judgment of a union the body would keep or compose (judgeShape). The union +// reading decides it once (readLoweredUnion). +type unionBesideRest uint8 + +const ( + // unionNoneLowered marks a conjunction choosing no union. + unionNoneLowered unionBesideRest = iota + // unionAlone marks a union that is the position: the body writes + // nothing a variant would carry that every branch does not say. + unionAlone + // unionLeavesNullAlone marks a union no branch of which shares a value + // with the rest of the conjunction but null, which every conjunct admits: + // the position admits null alone, the closed empty Enum behind a nullable + // reference (docs/compilers/openapi.md#union-null-only). + unionLeavesNullAlone + // unionLeavesNoBranch marks a union every branch of which is dead: no + // choice among shapes, so the position lowers as the rest of it, keeping + // it. + unionLeavesNoBranch + // unionConjoined marks a union beside a body of one kind that is no + // object, a live branch declaring shape against it: the Union of the live + // branches, each conjoined with that kind. + unionConjoined + // unionSaysNothing marks a union beside the rest's value set that says + // nothing the position's node does not hold: every member of the set + // satisfies it, or the node holds the members it shares with the set, each + // holding what its branch says of it (setHoldsUnion). The union is neither + // kept nor reported (readValueSetUnion, judgeSetMembers). + unionSaysNothing + // unionMembersFilteredByRest marks a union of value sets beside a body stating + // no value set: the position is the Enum of its members the body admits + // (readMembersFilteredByRest). + unionMembersFilteredByRest + // unionLiftsNull marks a union of null branches alone beside an object + // body keeping null out, which the nullable-inference policy lifts: the + // position is the body behind a reference admitting null, the union said. + unionLiftsNull + // unionKeptByRest marks a union beside a body that is no object, a live + // branch declaring shape against it and none dead, or one no other + // value takes: the body's node keeps it, degraded, as the body is no + // model to distribute into. The value-set judgments read it before the + // shape judgment tells the kept unions apart. + unionKeptByRest + // unionKeptWithDeadBranch marks a union kept by a body that is no object some + // branch of which is dead: kept degraded, its dead branches reported. + unionKeptWithDeadBranch + // unionKeptAsValidation marks a union kept by a body that is no object no + // live branch of which declares shape against it: kept as validation + // logic. + unionKeptAsValidation + // unionDistributed marks a union beside a body that is a Model, distributed + // across the variants: one Model per branch carrying the body conjoined + // with that branch, the ∧-of-∨ the source wrote. + unionDistributed + // unionSplitByKind marks a union of an object and another kind beside a + // body that is no Model: each branch takes the body's keywords of its + // kinds (composedVariant). + unionSplitByKind + // unionValidationOnly marks a union a body it would compose is beside, + // whose branches only narrow what that body accepts: kept verbatim under + // ReasonValidationOnly. + unionValidationOnly + // unionUnresolvedBranch marks a union a body would compose with a $ref + // branch naming nothing this compilation can resolve: a target in a + // document it did not read, an undeclared component, a pointer addressing + // no schema. + unionUnresolvedBranch + // unionHierarchyBase marks a union beside a discriminator routing to + // branches that compose the body through allOf, its subtypes, which a + // union of composed variants would no longer have for a base + // (composedByBranch). + unionHierarchyBase + // unionRoutedSubtype marks a body a discriminator on an ancestor routes to + // (routedSubtype). The route names the type the body lowers to, which as a + // union would be no subtype of that ancestor, so it stays a Model + // composing the union as a mixin (lowerSubtypeUnion). + unionRoutedSubtype +) + +// loweredAlone reports whether a union so beside its rest is the position, its +// union lowered as written alone. +func (s unionBesideRest) loweredAlone() bool { + switch s { + case unionAlone, unionLeavesNullAlone, unionConjoined: + return true + default: + return false + } +} + +// besideComposedRest reports whether a union so beside its rest is beside a +// body it would be distributed across, a Model or one split by kind, whether +// or not the shape judgment lets it. +func (s unionBesideRest) besideComposedRest() bool { + switch s { + case unionDistributed, unionSplitByKind, unionValidationOnly, unionUnresolvedBranch, unionHierarchyBase, unionRoutedSubtype: + return true + default: + return false + } +} + +// keptByRest reports whether a union so beside its rest is kept by the node of +// a body that is no object. +func (s unionBesideRest) keptByRest() bool { + switch s { + case unionKeptByRest, unionKeptWithDeadBranch, unionKeptAsValidation: + return true + default: + return false + } +} + +// takesWidenedNull reports whether a union so beside its rest takes the null +// the nullable-inference policy reads its conjunction as admitting. +func (s unionBesideRest) takesWidenedNull() bool { + return s == unionLeavesNullAlone || s == unionLiftsNull +} + +// addsNothing reports whether a union so beside its rest says nothing the node +// its position lowers to does not. +func (s unionBesideRest) addsNothing() bool { + return s == unionSaysNothing || s == unionLiftsNull +} + +// holdsNullOnVariants reports whether a union so beside its rest holds null on +// its variants rather than the reference: one beside a body it is distributed +// across, and one leaving null alone, which is it. +func (s unionBesideRest) holdsNullOnVariants() bool { + return s.besideComposedRest() || s == unionLeavesNullAlone +} + +// readsType reports whether a union so beside its rest is lowered with the +// body's kinds, so a `type` the body writes is read wherever it is written, as +// beside the union (docs/compilers/openapi.md#union-beside-structure). +func (s unionBesideRest) readsType() bool { + return s.loweredAlone() || s.besideComposedRest() +} diff --git a/compilers/openapi/internal/schema/unionbesiderest_internal_test.go b/compilers/openapi/internal/schema/unionbesiderest_internal_test.go new file mode 100644 index 000000000..8fa9fcd75 --- /dev/null +++ b/compilers/openapi/internal/schema/unionbesiderest_internal_test.go @@ -0,0 +1,77 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "go/constant" + "go/types" + "slices" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/internal/decls" +) + +// allUnionBesideRest is every unionBesideRest. A value left out fails +// TestUnionBesideRest_HandWrittenListIsComplete. +var allUnionBesideRest = []unionBesideRest{ + unionNoneLowered, unionAlone, unionLeavesNullAlone, unionLeavesNoBranch, unionConjoined, unionSaysNothing, + unionMembersFilteredByRest, unionLiftsNull, unionKeptByRest, unionKeptWithDeadBranch, unionKeptAsValidation, unionDistributed, + unionSplitByKind, unionValidationOnly, unionUnresolvedBranch, unionHierarchyBase, unionRoutedSubtype, +} + +// besideRestOfNoFamily are the values each of which its readers ask for by +// itself, in no family a predicate names. +var besideRestOfNoFamily = []unionBesideRest{ + unionNoneLowered, unionLeavesNoBranch, unionSaysNothing, unionMembersFilteredByRest, unionLiftsNull, +} + +// TestUnionBesideRest_HandWrittenListIsComplete holds allUnionBesideRest to the +// constants the package declares of unionBesideRest, so the family test below +// sees every one. +func TestUnionBesideRest_HandWrittenListIsComplete(t *testing.T) { + t.Parallel() + pkg, err := decls.Load("github.com/dexpace/morphic/compilers/openapi/internal/schema") + require.NoError(t, err) + named, err := pkg.Named("unionBesideRest") + require.NoError(t, err) + var declared []int64 + for declaredConst := range pkg.Objects[*types.Const]() { + if !types.Identical(declaredConst.Type(), named) { + continue + } + value, exact := constant.Int64Val(declaredConst.Val()) + require.True(t, exact, declaredConst.Name()) + declared = append(declared, value) + } + listed := make([]int64, 0, len(allUnionBesideRest)) + for _, besideRest := range allUnionBesideRest { + listed = append(listed, int64(besideRest)) + } + slices.Sort(declared) + slices.Sort(listed) + assert.Empty(t, cmp.Diff(declared, listed), "allUnionBesideRest names every declared value once (-declared +listed)") +} + +// TestUnionBesideRest_EachIsInOneFamily holds every value to exactly one +// family the readers switch on: lowered alone, beside a body it would be +// distributed across, kept by a body that is no object, or asked for by +// itself. A value added in none falls through every reader's switch +// unhandled, and one in two answers two lowerings. +func TestUnionBesideRest_EachIsInOneFamily(t *testing.T) { + t.Parallel() + for _, besideRest := range allUnionBesideRest { + families := 0 + for _, in := range []bool{besideRest.loweredAlone(), besideRest.besideComposedRest(), besideRest.keptByRest(), + slices.Contains(besideRestOfNoFamily, besideRest)} { + if in { + families++ + } + } + assert.Equal(t, 1, families, "unionBesideRest %d", besideRest) + } +} diff --git a/compilers/openapi/internal/schema/unionbesidestructure.go b/compilers/openapi/internal/schema/unionbesidestructure.go new file mode 100644 index 000000000..de5b480a4 --- /dev/null +++ b/compilers/openapi/internal/schema/unionbesidestructure.go @@ -0,0 +1,924 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "bytes" + "encoding/json/jsontext" + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" +) + +// conjunctionUnion is one union a position's conjunction writes: the oneOf or +// anyOf keyword holder writes, holder being the position's schema or an +// inline entry of its flattened allOf, written rel below the position. +type conjunctionUnion struct { + holder *statement.Schema + rel jsontext.Pointer + keyword unionKeyword +} + +// branches returns the branches u's keyword lists. +func (u conjunctionUnion) branches() []statement.Subschema { + return u.keyword.branchesOf(u.holder) +} + +// conjunctionKey keys what readConjunction read of one schema. +type conjunctionKey struct { + schema *statement.Schema +} + +// conjunction is what one position's schema says beside its unions, read once +// per run (docs/compilers/openapi.md#union-beside-structure): the unions its +// conjuncts write that readConjunction lists, the position's own first; where +// lowersUnion says the choice chooses one (chooseLoweredUnion), lowered, the +// one the position lowers, and keptBeside, the others in order, which it passes +// over and keeps. Where it chooses none, each union is a conjunct of the schema +// writing it. +type conjunction struct { + unions []conjunctionUnion + keptBeside []conjunctionUnion + // written are the conjuncts the body writes itself (inlineConjuncts). + written []*statement.Schema + lowered conjunctionUnion + lowersUnion bool +} + +// loweredUnion returns the union c chooses, and false where it chooses none. +func (c conjunction) loweredUnion() (conjunctionUnion, bool) { + return c.lowered, c.lowersUnion +} + +// passed returns the unions c's choice passes over, in order: none where it +// chooses none. +func (c conjunction) passed() []conjunctionUnion { + return c.keptBeside +} + +// readConjunction is schema's conjunction, read once a run: the position's own +// unions, then each inline entry's of its flattened allOf, but for an entry +// writing an unevaluated keyword, whose union holds the instance to what that +// entry alone evaluates, an entry nested past the flattening depth, whose +// conjuncts are not read, and an entry written alike an earlier one writing a +// union, which is that one conjunct written twice (sameText). A $ref entry is a +// conjunct, and its target's unions its own. +func readConjunction(loweringContext lowering.Ctx, schema *statement.Schema) conjunction { + return lowering.ReadOncePerRun(loweringContext, conjunctionKey{schema}, func() conjunction { + conjunctionRead := conjunction{unions: unionsOf(schema, ""), written: inlineConjuncts(loweringContext, schema)} + var holders []*statement.Statement + for _, entry := range loweringContext.Statements().Read(schema).Entries { + if entry.Ref != nil || entry.Capped || !stated(entry.Schema) || writesUnevaluated(entry.Schema) || !declaresUnion(entry.Schema) { + continue + } + schemaStatement := loweringContext.Statements().Read(entry.Schema) + if slices.ContainsFunc(holders, func(holder *statement.Statement) bool { return sameText(loweringContext, holder, schemaStatement) }) { + continue + } + holders = append(holders, schemaStatement) + conjunctionRead.unions = append(conjunctionRead.unions, unionsOf(entry.Schema, entry.Rel)...) + } + if at, lowersUnion := chooseLoweredUnion(loweringContext, schema, conjunctionRead.unions); lowersUnion { + conjunctionRead.lowered, conjunctionRead.lowersUnion = conjunctionRead.unions[at], true + conjunctionRead.keptBeside = slices.Delete(slices.Clone(conjunctionRead.unions), at, at+1) + } + return conjunctionRead + }) +} + +// unionsOf returns the oneOf and the anyOf holder writes, in that order, at rel. +func unionsOf(holder *statement.Schema, rel jsontext.Pointer) []conjunctionUnion { + if !stated(holder) { + return nil + } + choice := holder.ChoiceKeywords() + var out []conjunctionUnion + if len(choice.OneOf) > 0 { + out = append(out, conjunctionUnion{holder: holder, rel: rel, keyword: oneOfKeyword}) + } + if len(choice.AnyOf) > 0 { + out = append(out, conjunctionUnion{holder: holder, rel: rel, keyword: anyOfKeyword}) + } + return out +} + +// writesUnevaluated reports whether schema writes unevaluatedProperties or +// unevaluatedItems. +func writesUnevaluated(schema *statement.Schema) bool { + return hasKey(schema, "unevaluatedProperties") || hasKey(schema, "unevaluatedItems") +} + +// chooseLoweredUnion returns the index among unions, those the position +// schema's conjunction writes, of the one the position lowers: the one there +// is; of a oneOf and an anyOf, wherever each is written, the oneOf, unless only +// the anyOf's branches declare shape against the position's body, so the oneOf +// narrows what it declares and types nothing +// (docs/compilers/openapi.md#competing-keywords); and the one oneOf beside +// several anyOfs. It is the one choice: false for none, several oneOfs, or +// several anyOfs and no oneOf, which no rule ranks. +func chooseLoweredUnion(loweringContext lowering.Ctx, schema *statement.Schema, unions []conjunctionUnion) (int, bool) { + var oneOf, anyOf, oneOfs int + for i, union := range unions { + if union.keyword == oneOfKeyword { + oneOf, oneOfs = i, oneOfs+1 + } else { + anyOf = i + } + } + switch { + case len(unions) == 1: + return 0, true + case oneOfs != 1: + return 0, false + case len(unions) > 2: + return oneOf, true + } + if !setsDeclareShape(loweringContext, schema, unions[oneOf].branches()) && setsDeclareShape(loweringContext, schema, unions[anyOf].branches()) { + return anyOf, true + } + return oneOf, true +} + +// conjunctionUnionAt is the union union of the conjunction of schema, written +// at pointer, as a lowering reads it, with the discriminator beside it: +// the one written beside it, else the one beside the allOf, else the first an +// inline entry of the allOf writes. +func conjunctionUnionAt(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, union conjunctionUnion) loweredUnionSite { + out := loweredUnionSite{holder: union.holder, pointer: pointer + union.rel, schema: schema, holderIsAllOfEntry: union.holder != schema} + out.discriminator, out.discriminatorPointer = discriminatorBesideUnion(loweringContext, schema, pointer, union) + return out +} + +// discriminatorBesideUnion returns the discriminator beside union, a +// union of schema's conjunction written at pointer, and where it is written, +// nil where none is (conjunctionUnionAt). +func discriminatorBesideUnion(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, union conjunctionUnion) (*statement.Discriminator, jsontext.Pointer) { + if disc := union.holder.Discriminator(); disc != nil { + return disc, pointer + union.rel + } + if disc := schema.Discriminator(); disc != nil { + return disc, pointer + } + var found *statement.Discriminator + var at jsontext.Pointer + for _, entry := range loweringContext.Statements().Read(schema).Entries { + if entry.Ref == nil && stated(entry.Schema) && entry.Discriminator() != nil { + disc := entry.Discriminator() + if found != nil && !sameDiscriminator(loweringContext, found, disc) { + // Entries disagreeing on it, none sits with the union: each + // keeps its own, whatever order they are written in. + return nil, "" + } + if found == nil { + found, at = disc, pointer+entry.Rel + } + } + } + return found, at +} + +// sameDiscriminator reports whether a and b, two discriminators, write the +// same JSON in one document, read against one base (sameMeaning.text), so either +// says what the other does. +func sameDiscriminator(loweringContext lowering.Ctx, a, b *statement.Discriminator) bool { + if a == b { + return true + } + text, _ := renderedWhole(a.Node) + other, _ := renderedWhole(b.Node) + return text != nil && bytes.Equal(text, other) && newSameMeaning(loweringContext, noneLowered()).text(a.At, b.At, text) +} + +// loweredUnionWrittenBy reports whether holder, position's schema or an inline +// entry of its flattened allOf, writes the union position's conjunction +// chooses. +func loweredUnionWrittenBy(loweringContext lowering.Ctx, position, holder *statement.Schema) bool { + loweredUnion, ok := readConjunction(loweringContext, position).loweredUnion() + return ok && loweredUnion.holder == holder +} + +// loweredUnionAt is the union the conjunction of schema, written at pointer, +// chooses, as conjunctionUnionAt reads it, and false where it chooses none. +func loweredUnionAt(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (loweredUnionSite, bool) { + loweredUnion, ok := readConjunction(loweringContext, schema).loweredUnion() + if !ok { + return loweredUnionSite{}, false + } + return conjunctionUnionAt(loweringContext, schema, pointer, loweredUnion), true +} + +// unionReadingKey keys what readLoweredUnion read of one schema. +type unionReadingKey struct { + schema *statement.Schema +} + +// unionReading is what a conjunction decides of the union it chooses, read once +// a run: how it is beside the rest (besideRest), by branch which are dead, +// sharing no value with the rest of the conjunction (branchOverlapOf), whether +// the rest holds an object, which keeps each dead branch apart rather than the +// whole union, whether a closure refused every dead branch, and the one kind a +// conjoined branch is read as. What a value-set unionBesideRest holds is apart, +// held by pointer, nil for any other. +type unionReading struct { + dead []bool + kind statement.JSONSchemaTypeName + besideRest unionBesideRest + // restKinds is what the rest of the conjunction admits beside the union. + restKinds kindSet + refused bool + // nullTwice marks a oneOf two branches of which share the rest's null + // and no other value, so it refuses that null too. + nullTwice bool + // refusesNull marks a oneOf beside a rest naming a kind and admitting + // null, more than one live branch of which leaves that null in, so null + // matches each and the oneOf refuses it (oneOfLeavesNullTwice), where the + // reference holds the union's null. + refusesNull bool + // widened marks a conjunction the nullable-inference policy reads as + // admitting null while no branch lives (conjunctionRest.widened, or a + // lifted null branch): the position is null alone, its dead branches + // reported at the union. lifted is the index of the first null branch the + // policy lifts, where lifts marks one, which liftedBranch reads. + widened bool + lifts bool + lifted int + // sharedMembers is what the rest's value set and the union share, the members + // the body's node holds, and nil where the node holds the set whole. + sharedMembers *unionSharedMembers + // admittedMembers is what a union of value sets intersects a body stating none + // in, for unionMembersFilteredByRest alone, and nil for every other value. + admittedMembers *unionAdmittedMembers + // judgedBesideSet marks a union whose members were judged against the + // value set the rest states (readValueSetUnion, judgeSetMembers): the + // node's members hold what its branches say of each (unionNotesBesideSet). + judgedBesideSet bool +} + +// unionSharedMembers is what a union beside a rest stating a value set shares +// with it (readValueSetUnion, judgeSetMembers, judgeReferencedUnions): members, +// those of the set the body's node holds, and refused, those a union of typed +// branches beside it or a $ref names refuses. +type unionSharedMembers struct { + members admitted + refused []refusedMember +} + +// unionAdmittedMembers is what a union of value sets beside a body stating none +// intersects it in (readMembersFilteredByRest): members, those of its branches +// the body admits, refused, those it refuses, and pastBudget, how many its +// branches write where the enum budget admits fewer, none read, and zero +// otherwise. unheld marks a branch saying of its members what none of them +// holds (filteredMemberNotes). +type unionAdmittedMembers struct { + members []unionMember + refused []unionMember + pastBudget int + unheld bool +} + +// heldWhole reports whether r is a union of value sets whose members the body +// filters and the node holds whole: no branch dead, nor saying of its members +// what none holds, so it is kept nowhere (keepFilteredUnion). +func (r unionReading) heldWhole() bool { + return r.besideRest == unionMembersFilteredByRest && r.admittedMembers.pastBudget == 0 && !r.admittedMembers.unheld && !slices.Contains(r.dead, true) +} + +// liftedBranch returns the index of the null branch whose null the +// nullable-inference policy lifts for the whole position, where it reads the +// conjunction as admitting null (widened), and false where it lifts none. +func (r unionReading) liftedBranch() (int, bool) { + return r.lifted, r.widened && r.lifts +} + +// membersPastBudget is how many members a union of value sets beside a body +// stating none writes where the enum budget admits fewer +// (unionAdmittedMembers), and zero for any other union. +func (r unionReading) membersPastBudget() int { + if r.admittedMembers == nil { + return 0 + } + return r.admittedMembers.pastBudget +} + +// readLoweredUnion is schema's unionReading, read once a run: how the union +// its conjunction chooses sits, its shape judged last (judgeShape). +func readLoweredUnion(loweringContext lowering.Ctx, schema *statement.Schema) unionReading { + return lowering.ReadOncePerRun(loweringContext, unionReadingKey{schema}, func() unionReading { + return judgeShape(loweringContext, schema, readUnionBesideRest(loweringContext, schema)) + }) +} + +// readUnionBesideRest is how the union schema's conjunction chooses sits with +// the rest of it, as each value set of the conjunction judges it +// (judgeSetMembers, judgeReferencedUnions), before its shape is judged. +func readUnionBesideRest(loweringContext lowering.Ctx, schema *statement.Schema) unionReading { + conjunctionRead := readConjunction(loweringContext, schema) + loweredUnion, ok := conjunctionRead.loweredUnion() + if !ok { + return judgeReferencedUnions(loweringContext, schema, unionReading{}) + } + rest := readConjunctionRest(loweringContext, schema) + if reading, ok := readValueSetUnion(loweringContext, schema, conjunctionRead, loweredUnion, rest); ok { + return judgeReferencedUnions(loweringContext, schema, reading) + } + if len(conjunctionRead.passed()) > 0 && rest.set.fixed && rest.set.size() == 0 { + // A union passed over leaves the rest's value set no member, so no + // branch shares a value with the rest, as of a union of value sets + // (readValueSetUnion): the node holds none, every branch dead. + dead := make([]bool, len(loweredUnion.branches())) + for i := range dead { + dead[i] = true + } + return unionReading{dead: dead, besideRest: unionKeptByRest, sharedMembers: &unionSharedMembers{members: rest.set}} + } + restAddsToBranches := restAddsToBranches(loweringContext, schema, conjunctionRead, loweredUnion) + // A union nothing conjoins with is read against no rest: each branch is a + // variant, a null one its null. + alone := len(conjunctionRead.passed()) == 0 && !restAddsToBranches && + (rest.kinds&kindNull != 0 || !slices.ContainsFunc(loweredUnion.branches(), func(branch statement.Subschema) bool { + return nullBranch(loweringContext, loweringContext.Statements().Subschema(branch)) + })) + out, overlaps := readBranchOverlaps(loweringContext, schema, loweredUnion, rest, alone) + out.besideRest, out.nullTwice = noLiveBranchBesideRest(overlaps, out, loweredUnion.keyword, alone, rest) + switch { + case out.besideRest != unionNoneLowered: + case alone || !restAddsToBranches: + out.besideRest = unionAlone + default: + out.besideRest, out.kind = besideRestAddingToBranches(loweringContext, schema, loweredUnion, rest, overlaps, out.dead) + } + out.widened = out.widened && out.besideRest.takesWidenedNull() + // A union distributed over a body holds null on its variants, each as its + // branch does, so it refuses none on the reference. + out.refusesNull = loweredUnion.keyword.Exclusive() && !out.besideRest.holdsNullOnVariants() && !out.nullTwice && + rest.kinds&kindNull != 0 && rest.kinds&^kindNull != everyKindButNull && len(oneOfLeavesNullTwice(loweringContext, loweredUnion.branches(), out.dead)) > 1 + return judgeReferencedUnions(loweringContext, schema, judgeSetMembers(loweringContext, schema, conjunctionRead, loweredUnion, rest, out)) +} + +// readBranchOverlaps reads the overlap of each branch of loweredUnion, the +// union schema's conjunction chooses, against rest, alone marking a union +// nothing conjoins with (loweredUnionBranchOverlap): the reading of which are +// dead, which null branch the policy lifts and whether the policy widens the +// conjunction, and the overlaps together. +func readBranchOverlaps(loweringContext lowering.Ctx, schema *statement.Schema, loweredUnion conjunctionUnion, rest conjunctionRest, alone bool, +) (unionReading, branchOverlapTally) { + out := unionReading{dead: make([]bool, len(loweredUnion.branches())), restKinds: rest.kinds} + catchAll := catchAllSourceOf(schema, allOfEntries(loweringContext, schema, "")) + var overlaps branchOverlapTally + for i, branch := range loweredUnion.branches() { + schemaStatement := loweringContext.Statements().Subschema(branch) + overlap, refused := loweredUnionBranchOverlap(loweringContext, schema, schemaStatement, rest, alone, catchAll) + out.refused = out.refused || refused + overlaps.note(loweringContext, schemaStatement, overlap, rest) + out.dead[i] = overlap == branchDisjoint + if overlap == branchNullForPolicy && !out.lifts { + out.lifted, out.lifts = i, true + } + } + out.widened = !overlaps.sharesKind && !alone && (rest.widened || overlaps.nullForPolicy) + return out, overlaps +} + +// judgeShape judges the shape of the union schema's conjunction chooses where +// its body would keep or compose it (docs/compilers/openapi.md#union-beside-structure), +// out being how it sits: one a body that is no object keeps is kept with its +// dead branches reported, as validation logic where no branch declares shape +// against the body, and else degraded; distribution refuses one whose branches +// declare no shape, whose $ref branch names nothing resolved, at the base of a +// hierarchy its discriminator routes, or at a subtype an ancestor's routes. +func judgeShape(loweringContext lowering.Ctx, schema *statement.Schema, out unionReading) unionReading { + loweredUnion, _ := readConjunction(loweringContext, schema).loweredUnion() + switch out.besideRest { + case unionKeptByRest: + switch { + case slices.Contains(out.dead, true): + out.besideRest = unionKeptWithDeadBranch + case !setsDeclareShape(loweringContext, schema, loweredUnion.branches()): + out.besideRest = unionKeptAsValidation + } + case unionDistributed, unionSplitByKind: + unionSite := loweredUnionSite{holder: loweredUnion.holder, schema: schema} + switch { + case !setsDeclareShape(loweringContext, schema, loweredUnion.branches()): + out.besideRest = unionValidationOnly + case !branchesNameReferents(loweringContext, schema, loweredUnion.holder): + out.besideRest = unionUnresolvedBranch + case composedByBranch(loweringContext, schema, unionSite): + out.besideRest = unionHierarchyBase + case routedAtItsSite(loweringContext, schema): + out.besideRest = unionRoutedSubtype + } + } + return out +} + +// routedAtItsSite reports whether a discriminator on an ancestor of schema +// routes to it as its subtype (routedSubtype), read where the bindings place +// schema, in its own document, whoever asks. +func routedAtItsSite(loweringContext lowering.Ctx, schema *statement.Schema) bool { + at, placed := siteOf(schema) + in, found := lowering.InDocument(loweringContext, at.Doc) + return placed && found && routedSubtype(in, schema, at.Pointer) +} + +// oneOfLeavesNullTwice returns the indexes of the branches of a oneOf, those +// dead marks aside, that leave null in, each by its null answer under the +// policy's reading: where two or more do, null matches each, which the oneOf +// refuses. +func oneOfLeavesNullTwice(loweringContext lowering.Ctx, branches []statement.Subschema, dead []bool) []int { + var out []int + for i, branch := range branches { + if !dead[i] && !nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Subschema(branch)).forbids(loweringContext) { + out = append(out, i) + } + } + return out +} + +// noLiveBranchBesideRest returns how a union of keyword whose branches overlap +// the rest as overlaps say sits where no branch of it lives, out holding its +// dead branches and whether the policy widens the conjunction, alone whether +// nothing conjoins with it and rest what does, and unionNoneLowered where a +// branch lives. A union the policy widens to admit null, and one leaving null +// alone, is the null type, but for one of null branches alone, which lifts onto +// the body; a null two branches of a oneOf admit matches both, so the oneOf +// refuses it. +func noLiveBranchBesideRest(overlaps branchOverlapTally, out unionReading, keyword unionKeyword, alone bool, rest conjunctionRest) (unionBesideRest, bool) { + switch { + case overlaps.sharesKind: + return unionNoneLowered, false + case out.widened && overlaps.nullForPolicy && !slices.Contains(out.dead, true): + // Every branch is a null the policy lifts, so none narrows the body: + // the position is the body, its null the reference's. + return unionLiftsNull, false + case out.widened: + // The policy reads the whole conjunction or null, so no live branch + // leaves that null alone, a oneOf's too. + return unionLeavesNullAlone, false + case overlaps.sharesOnlyNull && (overlaps.sharingOnlyNull == 1 || !keyword.Exclusive() || alone): + return unionLeavesNullAlone, false + case overlaps.sharesOnlyNull: + return unionLeavesNoBranch, true + case rest.bodyKinds == kindNull: + // A body admitting null alone is no object, so the body keeps the + // union and its dead branches are reported at it. + return unionKeptByRest, false + default: + // No branch lives, shares null or is lifted: each is dead. + return unionLeavesNoBranch, false + } +} + +// loweredUnionBranchOverlap is the overlap of schemaStatement, a branch of the +// union schema's conjunction chooses, read against rest, and whether the +// catch-all source catchAll rejects it. Of a union lowered alone, a null branch +// shares its null, as does one admitting null alone beside a type naming null; +// another such branch, a union or a $ref of it the reference does not lift, +// stays a variant. A rest admitting no value is reported as its conjuncts +// sharing none, and kills no branch for its own sake. +func loweredUnionBranchOverlap(loweringContext lowering.Ctx, schema *statement.Schema, schemaStatement *statement.Statement, rest conjunctionRest, alone bool, + catchAll catchAllSource, +) (branchOverlap, bool) { + overlap := branchOverlapOf(loweringContext, schemaStatement, rest) + switch { + case alone && (nullBranch(loweringContext, schemaStatement) || overlap == branchSharesOnlyNull && typesNull(loweringContext, schema)): + return branchSharesOnlyNull, false + case alone || rest.bodyKinds == 0: + return branchSharesKind, false + case overlap != branchDisjoint && catchAllRejects(loweringContext, catchAll, schemaStatement): + return branchDisjoint, true + case overlap == branchNullForPolicy && !loweringContext.NullableInference.Honours(): + // Only the policy lifts a null the body keeps out; read as written, + // the branch shares no value with it. + return branchDisjoint, false + default: + return overlap, false + } +} + +// branchOverlapTally is what the branches of a chosen union are, together: +// whether one shares a kind, one shares only null with the rest, one is a null +// the policy lifts beside a body keeping it out, and among the live, whether +// one shares an object with the rest and not every kind, one every kind, and +// one another kind than an object. +type branchOverlapTally struct { + sharesKind, sharesOnlyNull, nullForPolicy, object, every, other bool + // sharingOnlyNull counts the branches sharing only null with the rest. + sharingOnlyNull int +} + +// note adds branch, a branch of overlap, to f, rest being what the conjunction +// admits outside the union. +func (f *branchOverlapTally) note(loweringContext lowering.Ctx, branch *statement.Statement, overlap branchOverlap, rest conjunctionRest) { + switch overlap { + case branchSharesOnlyNull: + f.sharesOnlyNull = true + f.sharingOnlyNull++ + case branchSharesKind: + f.sharesKind = true + kinds, inferred := lowersTo(loweringContext, branch) + if kinds&^kindNull == everyKindButNull || inferred && kinds&rest.kinds&^kindNull == 0 { + // A branch admitting every kind declares none, nor does one the + // policy alone reads as a kind the rest admits none of: it takes + // the body whole. + f.every = true + return + } + shared := kinds & rest.kinds &^ kindNull + f.object = f.object || shared&kindObject != 0 + f.other = f.other || shared&^kindObject != 0 + case branchNullForPolicy: + f.nullForPolicy = true + case branchDisjoint: + } +} + +// besideRestAddingToBranches returns how the chosen union of schema's +// conjunction sits beside a body saying more, its branches overlapping as +// overlaps say: by kind where a live branch admits an object and another +// another kind, or the body is no Model; beside a Model where the body, or the +// live branches where it names no kind, admit objects alone, null aside, and no +// value set, and a live branch admits objects or every kind; conjoined with the +// body's one kind where it declares one, no object, and a live branch declares +// shape; else kept by the body. +func besideRestAddingToBranches(loweringContext lowering.Ctx, schema *statement.Schema, loweredUnion conjunctionUnion, rest conjunctionRest, overlaps branchOverlapTally, + dead []bool, +) (unionBesideRest, statement.JSONSchemaTypeName) { + var live []statement.Subschema + for i, branch := range loweredUnion.branches() { + if !dead[i] { + live = append(live, branch) + } + } + kinds, inferred := rest.ownKinds, rest.ownInferred + var liveKinds kindSet + for _, branch := range live { + branchKinds, _ := lowersTo(loweringContext, loweringContext.Statements().Subschema(branch)) + liveKinds |= branchKinds + } + namesNone := inferred || kinds&^kindNull == everyKindButNull + if kinds&^kindNull == everyKindButNull { + // A body naming no kind lowers to what the live branches admit + // (docs/compilers/openapi.md#shape-applicator). + kinds = liveKinds + } + model := kinds&^kindNull == kindObject && !bodyWritesValueSet(loweringContext, schema) + switch { + case overlaps.object && (overlaps.other || !model): + return unionSplitByKind, "" + case namesNone && !overlaps.object && !overlaps.every && liveKinds&kindObject == 0 && kindCount(liveKinds) > 1 && + bodyKeywordsApplyTo(loweringContext, schema, liveKinds&primitiveKinds): + // Beside branches of several kinds and no object, a body naming none + // and writing a bound a scalar one of them takes goes to each by the + // kinds its keywords apply to. + return unionSplitByKind, "" + case (overlaps.object || overlaps.every) && model: + // A branch of another kind beside one admitting every kind lives + // only where the policy made the body an object; its variant keeps it. + return unionDistributed, "" + } + kind, one := bodyKind(loweringContext, schema) + if one && setsDeclareShape(loweringContext, schema, live) { + return unionConjoined, kind + } + return unionKeptByRest, "" +} + +// bodyKeywordsApplyTo reports whether schema or an inline entry of its +// flattened allOf writes a keyword applying to one of kinds and not to every +// kind (typeformat.InstanceKindsKeywordAppliesTo). +func bodyKeywordsApplyTo(loweringContext lowering.Ctx, schema *statement.Schema, kinds kindSet) bool { + return slices.ContainsFunc(readConjunction(loweringContext, schema).written, func(written *statement.Schema) bool { + return slices.ContainsFunc(written.Keys, func(key statement.Key) bool { + applies := typeformat.InstanceKindsKeywordAppliesTo(key.Name, nil) + return applies&^kindNull != everyKindButNull && applies&kinds != 0 + }) + }) +} + +// bodyWritesValueSet reports whether schema or an inline entry of its +// flattened allOf writes an enum or a const. +func bodyWritesValueSet(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return slices.ContainsFunc(readConjunction(loweringContext, schema).written, func(written *statement.Schema) bool { return enumWritten(written) || written.Const() != nil }) +} + +// bodyKind returns the one kind, null aside, the body of schema's conjunction +// declares where it declares one a primitive is: the type of the scalar its one +// $ref names, where it is that $ref (oneRefRestOf), else the types schema and +// its inline entries write, together, and false where they write none, several, +// an object or an array, or a $ref entry writes the body beside them. A branch +// is conjoined with that kind (conjoinedVariant). +func bodyKind(loweringContext lowering.Ctx, schema *statement.Schema) (statement.JSONSchemaTypeName, bool) { + if rest, isRef := oneRefRestOf(loweringContext, schema); isRef { + return rest.root.jsonType, true + } + declared := declaredInstanceTypes(schema) + for _, entry := range loweringContext.Statements().Read(schema).Entries { + switch { + case !stated(entry.Schema): + case entry.Ref != nil: + return "", false + default: + declared &= declaredInstanceTypes(entry.Schema) + } + } + for _, kind := range []statement.JSONSchemaTypeName{statement.KindString, statement.KindNumber, statement.KindInteger, statement.KindBoolean} { + if declared&^kindNull == kindsOfTypeName(kind) { + return kind, true + } + } + return "", false +} + +// conjunctionRest is what the conjunction of a position admits outside the +// union it chooses, as a dead branch is read against it: its kinds, and +// whether the kind-inference policy read any of them, which then decide +// nothing. +type conjunctionRest struct { + kinds kindSet + // bodyKinds is what the rest admits outside every union. + bodyKinds kindSet + // bodyNull marks a rest whose keywords, outside every union, admit null: + // one keeping null out alone lifts a null branch beside it, which no + // passed union keeps out. + bodyNull bool + // passedNull marks unions passed over each admitting null, as no union + // passed over does. + passedNull bool + // widened marks a conjunction the nullable-inference policy reads as + // admitting null whatever its unions say (policyWidens). + widened bool + inferred bool + // set is what the rest admits outside every union, a value set where it + // states one, which each union passed over narrows (readValueSetUnion). + set admitted + // ownKinds is what the conjunction's own keywords and entries declare, + // every union it writes left out, and ownInferred whether the + // kind-inference policy read them (restKinds). + ownKinds kindSet + ownInferred bool +} + +// conjunctionRestOf keys what readConjunctionRest read of one schema. +type conjunctionRestOf struct { + schema *statement.Schema +} + +// readConjunctionRest is the rest of schema's conjunction, read once a run as +// every reader of its union asks: what it admits (restOfConjunction) and what +// it declares (restKinds). +func readConjunctionRest(loweringContext lowering.Ctx, schema *statement.Schema) conjunctionRest { + return lowering.ReadOncePerRun(loweringContext, conjunctionRestOf{schema}, func() conjunctionRest { + rest := restOfConjunction(loweringContext, schema, readConjunction(loweringContext, schema)) + rest.ownKinds, rest.ownInferred = restKinds(loweringContext, schema) + return rest + }) +} + +// restOfConjunction is what the conjunction conjunctionRead of schema admits +// outside the union it chooses: schema's own keywords and each inline entry's, +// by what they write, each $ref entry by what its target admits, and each union +// conjunctionRead passes over by what its branches admit, the value set the +// rest states among it (docs/compilers/openapi.md#union-beside-structure). A +// read cut short admits every kind there. +func restOfConjunction(loweringContext lowering.Ctx, schema *statement.Schema, conjunctionRead conjunction) conjunctionRest { + admissionReader := newAdmissionReader(loweringContext) + read := admissionReader.written(schema, admissionReader.nullable) + inferred := false + for _, entry := range loweringContext.Statements().Read(schema).Entries { + switch schemaStatement := loweringContext.Statements().Read(entry.Schema); { + case entry.Capped: + // An allOf nested past the flattening depth is read no further, + // and a rest cut short decides nothing. + return conjunctionRest{kinds: kindAny, bodyKinds: kindAny, bodyNull: true, passedNull: true, inferred: inferred} + case !stated(entry.Schema): + case entry.Ref != nil: + _, targetInferred := lowersTo(loweringContext, schemaStatement) + inferred = inferred || targetInferred + read = read.and(admissionReader.of(schemaStatement)) + default: + read = read.and(admissionReader.written(entry.Schema, admissionReader.nullable)) + } + } + // The body's null is its answer, which no read's cap cuts (bodyNull). + bodyAdmitsNull := admitsBodyNull(loweringContext, schema, read.kinds&kindNull != 0) + read.kinds &^= kindNull + if bodyAdmitsNull { + read.kinds |= kindNull + } + bodyKinds, set := read.kinds, read + passedNull := true + for _, passed := range conjunctionRead.passed() { + union := admissionReader.union(passed.branches()) + passedNull = passedNull && union.kinds&kindNull != 0 + read = read.and(union) + if set.fixed { + set = set.and(union) + } + } + if admissionReader.incomplete() { + return cutRest(loweringContext, schema, bodyAdmitsNull, inferred) + } + kinds := read.kinds + if bodyAdmitsNull && len(conjunctionRead.passed()) == 0 { + kinds |= kindNull + } + return conjunctionRest{kinds: kinds, bodyKinds: bodyKinds, bodyNull: bodyAdmitsNull, passedNull: passedNull, + widened: policyWidens(loweringContext, schema), inferred: inferred, set: set} +} + +// admitsBodyNull reports whether schema's body, outside every union, admits +// null as its answer says (bodyNull), and, where that says nothing of null, +// as read says, what the body's keywords admit: an empty enum admits nothing, +// and a schema writing no type admits null. +func admitsBodyNull(loweringContext lowering.Ctx, schema *statement.Schema, read bool) bool { + switch answer := bodyNull(loweringContext, schema).selected(loweringContext); { + case answer == nullForbidden: + return false + case answer.admits(): + return true + default: + return read + } +} + +// cutRest is the rest of schema's conjunction where its read is cut short: the +// kinds its conjuncts declare, and null where the body admits it (bodyNull), +// which no cut reaches. +func cutRest(loweringContext lowering.Ctx, schema *statement.Schema, bodyAdmitsNull, inferred bool) conjunctionRest { + kinds := declaredInstanceTypes(schema) + for _, entry := range loweringContext.Statements().Read(schema).Entries { + switch { + case !stated(entry.Schema): + case entry.Ref != nil: + target, _ := lowersTo(loweringContext, loweringContext.Statements().Read(entry.Schema)) + kinds &= target + default: + kinds &= declaredInstanceTypes(entry.Schema) + } + } + if bodyAdmitsNull { + kinds |= kindNull + } + return conjunctionRest{kinds: kinds, bodyKinds: kinds, bodyNull: bodyAdmitsNull, passedNull: true, + widened: policyWidens(loweringContext, schema), inferred: inferred} +} + +// branchOverlap is how one branch of a lowered union overlaps the rest of its +// conjunction. +type branchOverlap uint8 + +const ( + // branchSharesKind marks a branch sharing a kind but null with the rest. + branchSharesKind branchOverlap = iota + // branchSharesOnlyNull marks one sharing only null with the rest, a null + // branch among them, where the rest admits null. + branchSharesOnlyNull + // branchDisjoint marks one sharing no value with the rest, which no + // instance satisfies together with it. + branchDisjoint + // branchNullForPolicy marks a null branch beside a body keeping null out, which + // is no variant and lifts nothing + // (docs/compilers/openapi.md#union-null-variant). + branchNullForPolicy +) + +// branchOverlapOf returns how branch, a branch of a conjunction's lowered +// union, overlaps rest, what the conjunction admits outside it: by the kinds +// branch lowers to (lowersTo), null among them. Kinds the kind-inference policy +// read, on either side, decide nothing, so such a branch lives; so does one +// whose read is past the admission's caps where the rest admits null, its own +// null unread. A null branch shares the rest's null, is dead where a passed +// union or a body that is no object keeps it out, and is lifted where an object +// body does. +func branchOverlapOf(loweringContext lowering.Ctx, branch *statement.Statement, rest conjunctionRest) branchOverlap { + if nullBranch(loweringContext, branch) { + switch { + case rest.kinds&kindNull != 0: + return branchSharesOnlyNull + case rest.bodyNull || !rest.passedNull || rest.kinds&kindObject == 0: + // A union passed over keeps the null out, or a body that is no + // object shares no kind with it. + return branchDisjoint + default: + return branchNullForPolicy + } + } + kinds, inferred := lowersTo(loweringContext, branch) + if inferred || rest.inferred || kinds&rest.kinds&^kindNull != 0 { + return branchSharesKind + } + if rest.kinds&kindNull == 0 { + return branchDisjoint + } + if !admissionOf(loweringContext, branch).within() || nullAnswerReadingsOf(loweringContext, branch).mayAdmit(loweringContext) { + return branchSharesOnlyNull + } + return branchDisjoint +} + +// routesUnion reports whether conjunct, schema or an inline entry of its allOf, +// writes the discriminator beside the union schema's conjunction +// chooses (discriminatorBesideUnion), which the union's lowering reads where it +// lowers the union (unionBesideRest.readsType). +func routesUnion(loweringContext lowering.Ctx, schema, conjunctSchema *statement.Schema) bool { + loweredUnion, ok := readConjunction(loweringContext, schema).loweredUnion() + if !ok || conjunctSchema.Discriminator() == nil || !readLoweredUnion(loweringContext, schema).besideRest.readsType() || unionCollapses(loweringContext, schema, loweredUnion.holder) { + return false + } + disc, _ := discriminatorBesideUnion(loweringContext, schema, "", loweredUnion) + return disc != nil && sameDiscriminator(loweringContext, disc, conjunctSchema.Discriminator()) +} + +// unionCollapses reports whether the union holder writes, chosen by the +// conjunction of position, lowers as the nullable reference to its one +// non-null branch (nullUnionCollapse): it passes over no union another schema +// writes (passesOverAnother), and no branch of it is dead. +func unionCollapses(loweringContext lowering.Ctx, position, holder *statement.Schema) bool { + _, _, collapses := nullUnionCollapse(loweringContext, holder, "") + return collapses && !passesOverAnother(loweringContext, position, holder) && !leavesDead(loweringContext, position, holder) && + !leavesNullAlone(loweringContext, position, holder) +} + +// splitTakes is the kinds the branches of the union schema's conjunction +// chooses split off by kind take the body's bounds of (splitsOff), none where +// the body is not split by kind. +func splitTakes(loweringContext lowering.Ctx, schema *statement.Schema) kindSet { + loweredUnion, ok := readConjunction(loweringContext, schema).loweredUnion() + if !ok || readLoweredUnion(loweringContext, schema).besideRest != unionSplitByKind { + return 0 + } + var out kindSet + for _, branch := range loweredUnion.branches() { + if schemaStatement := loweringContext.Statements().Subschema(branch); splitsOff(loweringContext, schemaStatement) { + kinds, _ := lowersTo(loweringContext, schemaStatement) + out |= kinds &^ kindNull + } + } + return out +} + +// catchAllRejects reports whether catchAll, the catch-all source the model of a +// position takes, rejects a member the branch requires, branch's own or a $ref +// target's: no instance satisfies the two, so branch is dead +// (docs/compilers/openapi.md#additional-properties). +func catchAllRejects(loweringContext lowering.Ctx, catchAll catchAllSource, branch *statement.Statement) bool { + if catchAll.schema == nil { + return false + } + members := newComposedMembers() + members.add(loweringContext, branch, map[*statement.Schema]bool{}) + return len(catchAllScopeOf(loweringContext, catchAll, members).rejected) > 0 +} + +// typesNull reports whether schema or an inline entry of its allOf writes a +// type naming null, which the reference to the position reads as admitting it. +func typesNull(loweringContext lowering.Ctx, schema *statement.Schema) bool { + return slices.ContainsFunc(readConjunction(loweringContext, schema).written, func(written *statement.Schema) bool { return slices.Contains(written.Types(), statement.KindNull) }) +} + +// restAddsToBranches reports whether the body of schema's conjunction +// conjunctionRead, outside every union, writes what a variant would carry that +// a branch of the union loweredUnion, or one passed over, does not say +// (keywordsBranchesRestate): a sibling keyword of schema or of an inline entry, +// or a $ref entry to a schema writing one or a union. A body every branch says +// all of is no body, where the chosen union's branches declare shape against +// it; one declaring none narrows it +// (docs/compilers/openapi.md#union-beside-structure). +func restAddsToBranches(loweringContext lowering.Ctx, schema *statement.Schema, conjunctionRead conjunction, loweredUnion conjunctionUnion) bool { + if composedByBranch(loweringContext, schema, loweredUnionSite{holder: loweredUnion.holder, schema: schema}) { + // A discriminator routing to branches composing the body keeps it, + // their base, whatever they say. + return writesSiblingKeyword(schema) + } + for ref := range allOfRefEntries(loweringContext, schema) { + // A target is read as an inline conjunct is: by its shape keywords, + // notes and bounds alone naming no body. + target, _ := declaredOf(loweringContext, ref) + if target == nil || !stated(target.Schema) || writesSiblingKeyword(target.Schema) || declaresUnion(target.Schema) { + return true + } + } + wrote := false + for _, conjunctSchema := range conjunctionRead.written { + siblings := slices.DeleteFunc(siblingKeywords(conjunctSchema), func(keyword string) bool { return keyword == "allOf" }) + if writesType(conjunctSchema) && !slices.Contains(siblings, "type") { + // A type naming null alone is a body keeping every other kind out. + siblings = append(siblings, "type") + } + if len(siblings) == 0 { + continue + } + wrote = true + for _, union := range conjunctionRead.unions { + restated := keywordsBranchesRestate(loweringContext, union.holder, conjunctSchema) + if slices.ContainsFunc(siblings, func(keyword string) bool { return !slices.Contains(restated, keyword) }) { + return true + } + } + } + return wrote && !setsDeclareShape(loweringContext, schema, loweredUnion.branches()) +} diff --git a/compilers/openapi/internal/schema/unionbesidestructure_internal_test.go b/compilers/openapi/internal/schema/unionbesidestructure_internal_test.go new file mode 100644 index 000000000..a9a518ceb --- /dev/null +++ b/compilers/openapi/internal/schema/unionbesidestructure_internal_test.go @@ -0,0 +1,147 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "testing" + + soa "github.com/speakeasy-api/openapi/openapi" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/ir" +) + +// conjunctionSchema returns the schema of the component name lowerer read. +func conjunctionSchema(t *testing.T, lowerer *Lowerer, name string) *statement.Schema { + t.Helper() + schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: jsontext.Pointer("/components/schemas/" + name)}) + require.NotNil(t, schemaStatement, name) + return schemaStatement.Schema +} + +// TestConjunction_ReadersOfNoUnionReadNothing holds the readers of a +// conjunction to what they say where it chooses no union, or no schema writes +// one: no union passed over, and none written. +func TestConjunction_ReadersOfNoUnionReadNothing(t *testing.T) { + t.Parallel() + none := conjunction{} + assert.Nil(t, none.passed()) + assert.Nil(t, unionsOf(nil, "")) +} + +// TestConjunction_ACutRestReadsWhatItsEntriesDeclare holds cutRest to the +// kinds a schema's own type and each inline entry's declare, an entry stating +// nothing aside, with null where the body admits it. +func TestConjunction_ACutRestReadsWhatItsEntriesDeclare(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` S: {allOf: [true, {type: [string, integer]}], type: [string, boolean]} +`)) + position := conjunctionSchema(t, lowerer, "S") + for _, bodyAdmitsNull := range []bool{false, true} { + rest := cutRest(lowerer.Ctx, position, bodyAdmitsNull, false) + want := kindsOfTypeName(statement.KindString) + if bodyAdmitsNull { + want |= kindNull + } + assert.Equal(t, want, rest.kinds, bodyAdmitsNull) + assert.Equal(t, rest.kinds, rest.bodyKinds) + assert.Equal(t, bodyAdmitsNull, rest.bodyNull) + } + kind, ok := bodyKind(lowerer.Ctx, position) + assert.True(t, ok) + assert.Equal(t, statement.KindString, kind) +} + +// TestConjunction_AUnionAloneLowersAsWrittenAlone holds lowerCoDeclaredUnion, +// asked of a union its conjunction reads as written alone, to the lowering of +// that union alone, with no finding: a Union for two typed branches, and for a +// $ref beside null the reference itself, which builds no node. It also holds +// deadBranches to marking no branch of a union the body's conjunction does not +// choose. +func TestConjunction_AUnionAloneLowersAsWrittenAlone(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` Plain: {type: string} + U: {oneOf: [{type: string}, {type: integer}]} + N: {oneOf: [{$ref: '#/components/schemas/Plain'}, {type: 'null'}]} +`)) + position := conjunctionSchema(t, lowerer, "U") + built, diags := lowerCoDeclaredUnion(lowerer.Ctx, lowerer.Types, 0, position, "/components/schemas/U", nodePlacement{}) + assert.Empty(t, diags) + _, isUnion := built.node.(*ir.Union) + assert.True(t, isUnion, "the union written alone; got %T", built.node) + collapsed, diags := lowerCoDeclaredUnion(lowerer.Ctx, lowerer.Types, 0, conjunctionSchema(t, lowerer, "N"), "/components/schemas/N", nodePlacement{}) + assert.Empty(t, diags) + assert.Nil(t, collapsed.node, "a union of a $ref and null is the reference to it") + assert.Equal(t, ir.TypeID("type/openapi/components/schemas/Plain"), collapsed.id) + assert.Equal(t, []bool{false, false}, deadBranches(lowerer.Ctx, conjunctionSchema(t, lowerer, "Plain"), position)) +} + +// TestConjunctsIn_ANilSchemaWritesNone pins the guard of the reader of what a +// schema conjoins beside its own keywords: a nil schema writes no reference +// and no allOf. +func TestConjunctsIn_ANilSchemaWritesNone(t *testing.T) { + t.Parallel() + lowerer := NewRawLowerer(&soa.OpenAPI{}) + assert.Empty(t, conjunctsIn(lowerer.Ctx, nil)) +} + +// TestConjunction_AUnionTheConjunctionDoesNotChooseIsReadAsWritten holds the +// readers asked of a union their position's conjunction does not choose, a +// principal's read at another position among them: no kind conjoins it, it +// is written beside its body, and which of its keywords is chosen +// is read off its own branches. +func TestConjunction_AUnionTheConjunctionDoesNotChooseIsReadAsWritten(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` U: {type: string, oneOf: [{format: uuid}, {format: email}]} + V: {oneOf: [{required: [a]}], anyOf: [{type: object}, {type: string}]} +`)) + position, other := conjunctionSchema(t, lowerer, "U"), conjunctionSchema(t, lowerer, "V") + assert.Equal(t, statement.JSONSchemaTypeName(""), conjoinedKind(lowerer.Ctx, position, other)) + at := unionAtPlacement(lowerer.Ctx, other, "/components/schemas/V", nodePlacement{position: position}) + assert.Equal(t, other, at.holder) + assert.Equal(t, position, at.schema, "it sits at the position read") + assert.True(t, anyOfChosen(lowerer.Ctx, position, other), "of V, only the anyOf declares shape") +} + +// TestConjunction_ReportsAskedOfNoSuchUnionSayNothing holds the reports of a +// union's dead or refused branches to saying nothing where asked of a schema +// they do not describe: one choosing no union, one whose branches the +// closure refuses none of, one writing an allOf, whose conjuncts report it, +// and one whose union is written on no entry. +func TestConjunction_ReportsAskedOfNoSuchUnionSayNothing(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` Plain: {type: string} + Kept: {type: object, properties: {a: {type: string}}, additionalProperties: false, oneOf: [{required: [a]}]} + Composed: {allOf: [{type: string}], oneOf: [{type: integer}]} +`)) + plain, kept := conjunctionSchema(t, lowerer, "Plain"), conjunctionSchema(t, lowerer, "Kept") + assert.Empty(t, diagDeadAtUnion(lowerer.Ctx, plain, "/components/schemas/Plain", false)) + assert.Empty(t, diagRefusedBranches(lowerer.Ctx, kept, "/components/schemas/Kept", "a node")) + assert.Empty(t, diagUnionApartFromBody(lowerer.Ctx, conjunctionSchema(t, lowerer, "Composed"), "/components/schemas/Composed", "a node")) + assert.Empty(t, keptEntryUnion(lowerer.Ctx, kept, "/components/schemas/Kept", builtPosition{})) +} + +// TestKeptUnionsWhy_SaysWhatTheUnionIntersectsWith pins the opening of the +// info a union kept beside a schema's body draws: the structural keywords +// beside it where the schema writes one, and the rest of the schema where it +// writes none, as a oneOf and an anyOf alone do, and none where no why is +// given (docs/compilers/openapi.md#union-beside-structure). +func TestKeptUnionsWhy_SaysWhatTheUnionIntersectsWith(t *testing.T) { + t.Parallel() + lowerer, _ := LoweredFor(t, openapitest.ComponentSpecVer("3.1.0", ` Bare: {description: d, oneOf: [{type: string}], anyOf: [{type: integer}]} + Bodied: {type: string, oneOf: [{type: integer}]} +`)) + for name, opening := range map[string]string{ + "Bare": "oneOf/anyOf written here intersects with the rest of the schema, and ", + "Bodied": "oneOf/anyOf co-declared with structural keywords intersects with them, and ", + } { + assert.Equal(t, opening+"why", keptUnionsWhy(conjunctionSchema(t, lowerer, name), "why"), name) + assert.Empty(t, keptUnionsWhy(conjunctionSchema(t, lowerer, name), ""), name) + } +} diff --git a/compilers/openapi/internal/schema/conjunction_test.go b/compilers/openapi/internal/schema/unionbesidestructure_test.go similarity index 50% rename from compilers/openapi/internal/schema/conjunction_test.go rename to compilers/openapi/internal/schema/unionbesidestructure_test.go index c989dd173..9e552cf21 100644 --- a/compilers/openapi/internal/schema/conjunction_test.go +++ b/compilers/openapi/internal/schema/unionbesidestructure_test.go @@ -4,6 +4,7 @@ package schema_test import ( + "encoding/json/jsontext" "testing" "github.com/stretchr/testify/assert" @@ -74,11 +75,12 @@ func TestVariantHint_AUseDeclaringAMemberIsNamedByItsPosition(t *testing.T) { assert.Equal(t, "variant_2", union.Variants[2].Name.Hint, "nor does a member an entry declares") } -// TestValueSet_AnEmptyEnumBesideAReferenceKeepsTheReference pins the value set -// that leaves no value beside a $ref and an allOf, as beside an allOf alone: -// no set to lower, so the election keeps the conjuncts it passed over, each -// $ref by reference text, wherever written, and reports both keywords. -func TestValueSet_AnEmptyEnumBesideAReferenceKeepsTheReference(t *testing.T) { +// TestValueSet_AnEmptyEnumBesideAReferenceKeepsNothing pins the value set that +// leaves no value beside a $ref and an allOf of another, each to an object: +// the empty enum lies within both targets, so it is the one fact, the closed +// empty Enum each target says its own beside, keeping nothing, with the +// empty enum's warning alone (docs/compilers/openapi.md#enum-const). +func TestValueSet_AnEmptyEnumBesideAReferenceKeepsNothing(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {a: {type: string}}} B: {type: object, properties: {b: {type: string}}} @@ -86,19 +88,17 @@ func TestValueSet_AnEmptyEnumBesideAReferenceKeepsTheReference(t *testing.T) { `)) en, ok := typeByName(doc, "S").(*ir.Enum) require.True(t, ok, "got %T", typeByName(doc, "S")) - assert.ElementsMatch(t, []string{"openapi:$ref/0", "openapi:$ref/1"}, unmodeledKeys(en.Unmodeled)) - assert.JSONEq(t, `"#/components/schemas/A"`, string(en.Unmodeled["openapi:$ref/0"].Value)) - assert.JSONEq(t, `"#/components/schemas/B"`, string(en.Unmodeled["openapi:$ref/1"].Value)) - assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, "/components/schemas/S"), - "declares $ref and allOf beside its enum") + assert.Empty(t, en.Unmodeled) + require.Len(t, diags, 1, "%+v", diags) + assert.Equal(t, diag.EmptyEnum, diags[0].Code) } -// useTargetOf is the type td, the node a position owns over what its $ref -// names, is a use of: the Base of the Model over an object, declaring no member, -// or of the Scalar alias over anything else. -func useTargetOf(t *testing.T, td ir.TypeDef) ir.TypeID { +// useTargetOf is the type typeDef, the node a position owns over what its $ref +// names, is a use of: the Base of the Model over an object, declaring no +// member, or of the Scalar alias over anything else. +func useTargetOf(t *testing.T, typeDef ir.TypeDef) ir.TypeID { t.Helper() - switch n := td.(type) { + switch n := typeDef.(type) { case *ir.Model: require.NotNil(t, n.Base) require.Empty(t, n.Properties, "a use declares no member of its own") @@ -153,41 +153,42 @@ func TestComponent_AnAllOfOfOneRefOverAnObjectIsTheModelThatOwnsIt(t *testing.T) assert.NotContains(t, doc.Types, ir.TypeID("type/anonymous/components/schemas/W/allOf/0")) } -// TestAllOf_TwoDiscriminatedBasesElectAndTagAlikeInEitherOrder pins the Base +// TestAllOf_TwoDiscriminatedBasesChooseAndTagAlikeInEitherOrder pins the Base // and the tag of a schema composing two $refs whose discriminators each map // it: the base is one whose mapping routes the schema, of those the least // reference text, and its hierarchy gives the tag, whichever entry and // whichever declaration is written first. A base whose mapping does not route // the schema yields to one whose does, whatever their texts. -func TestAllOf_TwoDiscriminatedBasesElectAndTagAlikeInEitherOrder(t *testing.T) { +func TestAllOf_TwoDiscriminatedBasesChooseAndTagAlikeInEitherOrder(t *testing.T) { t.Parallel() a := " A: {type: object, properties: {k: {type: string}}, discriminator: {propertyName: k, mapping: {sa: '#/components/schemas/S'}}}\n" b := " B: {type: object, properties: {k: {type: string}}, discriminator: {propertyName: k, mapping: {sb: '#/components/schemas/S'}}}\n" quietA := " A: {type: object, properties: {k: {type: string}}, discriminator: {propertyName: k}}\n" ab := " S: {allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}\n" ba := " S: {allOf: [{$ref: '#/components/schemas/B'}, {$ref: '#/components/schemas/A'}]}\n" - for name, tc := range map[string]struct{ src, base, mixin, tag string }{ + for name, testCase := range map[string]struct{ src, base, mixin, tag string }{ "both route, A first": {a + b + ab, "A", "B", "sa"}, "both route, B first": {a + b + ba, "A", "B", "sa"}, "both route, S declared first": {ab + b + a, "A", "B", "sa"}, "only B routes, A first": {quietA + b + ab, "B", "A", "sb"}, } { - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", tc.src)) + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", testCase.src)) openapitest.RequireNoErrorDiags(t, diags) model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok, name) require.NotNil(t, model.Base, name) - assert.Equal(t, componentID(tc.base), model.Base.Target, name) + assert.Equal(t, componentID(testCase.base), model.Base.Target, name) require.Len(t, model.Mixins, 1, name) - assert.Equal(t, componentID(tc.mixin), model.Mixins[0].Target, name) - assert.Equal(t, tc.tag, model.DiscriminatorValue, name) + assert.Equal(t, componentID(testCase.mixin), model.Mixins[0].Target, name) + assert.Equal(t, testCase.tag, model.DiscriminatorValue, name) } } // TestAllOf_AClosureBesideARefClosesAsInEverySpelling pins that a closure // written beside a $ref, beside an allOf of it, beside the $ref in an entry -// or on an entry of its own closes the model over the target alike, keeping -// nothing. +// or on an entry of its own closes the model over the target alike: it also +// applies to the member the target brings, so it is kept verbatim under one +// key, where written, with one info naming that member. func TestAllOf_AClosureBesideARefClosesAsInEverySpelling(t *testing.T) { t.Parallel() doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` T: {type: object, properties: {a: {type: string}}} @@ -203,7 +204,9 @@ func TestAllOf_AClosureBesideARefClosesAsInEverySpelling(t *testing.T) { require.NotNil(t, model.Base, name) assert.Equal(t, componentID("T"), model.Base.Target, name) assert.Equal(t, ir.AdditionalClosed, model.Additional, name) - assert.Empty(t, model.Unmodeled, name) + assert.Equal(t, []string{"openapi:additionalProperties"}, unmodeledKeys(model.Unmodeled), name) + at := model.Unmodeled["openapi:additionalProperties"].Provenance.Pointer + assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, string(at)), "applies to a", name) } } @@ -236,3 +239,144 @@ func TestUnion_ANoteBesideAVariantsRefRidesOnItsBranchNode(t *testing.T) { assert.Equal(t, componentID("Mixed"), useTargetOf(t, branch)) assert.Equal(t, "the mixed variant", branch.Docs.Description) } + +// TestConjunction_AUnionOfNullAloneIsAVariant pins a union lowered alone whose +// one branch is itself a union admitting null alone, inline or named: the +// reference lifts no such branch, so it stays a variant behind a nullable +// reference, and null is admitted (docs/compilers/openapi.md#union-null-only). +func TestConjunction_AUnionOfNullAloneIsAVariant(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` N: {anyOf: [{type: 'null'}]} + Inline: {anyOf: [{anyOf: [{type: 'null'}]}]} + Named: {oneOf: [{$ref: '#/components/schemas/N'}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Inline", "Named"} { + union, ok := typeByName(doc, name).(*ir.Union) + require.True(t, ok, "%s stays a union; got %T", name, typeByName(doc, name)) + require.Len(t, union.Variants, 1, name) + assert.True(t, union.Variants[0].Type.Nullable, "%s admits null through its variant", name) + } +} + +// TestConjunction_ABoundBesideAKeptUnionOverARefIsReadOnce pins a bound +// written beside a union one branch of which shares no kind with the $ref to a +// string it conjoins with, beside the allOf or on its entry: the alias the +// position owns to keep the union holds the bound, which is not also kept. A +// collection bound beside a $ref to an array, which the alias does not hold, +// is kept (docs/compilers/openapi.md#union-beside-structure). +func TestConjunction_ABoundBesideAKeptUnionOverARefIsReadOnce(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` T: {type: string} + Beside: {allOf: [{$ref: '#/components/schemas/T'}], minLength: 1, oneOf: [{type: string, maxLength: 5}, {type: boolean}]} + Entry: {allOf: [{$ref: '#/components/schemas/T'}, {minLength: 1, oneOf: [{type: string, maxLength: 5}, {type: boolean}]}]} + L: {type: array, items: {type: string}} + Listed: {allOf: [{$ref: '#/components/schemas/L'}], maxItems: 3, oneOf: [{type: array, maxItems: 5}, {type: boolean}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Beside", "Entry"} { + node, ok := typeByName(doc, name).(*ir.Scalar) + require.True(t, ok, "%s is the alias of T; got %T", name, typeByName(doc, name)) + require.NotNil(t, node.Constraints, name) + assert.Equal(t, int64(1), *node.Constraints.MinLength, name) + assert.NotContains(t, node.Unmodeled, "openapi:minLength", "%s reads the bound, so keeps none", name) + assert.Contains(t, node.Unmodeled, "openapi:oneOf", name) + } + listed := typeByName(doc, "Listed") + assert.Equal(t, ir.ReasonDegradedLowering, listed.Common().Unmodeled["openapi:maxItems"].Reason, "the bound is kept, not dropped") +} + +// TestConjunction_AnEntryUnionNoBranchOfWhichLivesWarnsOnce holds the one +// warning a union on an allOf entry draws where none of its branches lives: a +// oneOf whose two null branches share the rest's null, which it refuses, its +// other branch dead, names the dead one; and one every branch of which +// requires a member the closure beside the allOf refuses names each branch +// (docs/compilers/openapi.md#union-beside-structure). +func TestConjunction_AnEntryUnionNoBranchOfWhichLivesWarnsOnce(t *testing.T) { + t.Parallel() + _, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` NullTwice: {allOf: [{type: [string, 'null']}, {oneOf: [{type: 'null'}, {enum: [null]}, {type: integer}]}]} + Refused: {allOf: [{type: object, properties: {a: {type: string}}}, {oneOf: [{required: [z]}, {required: [y]}]}], additionalProperties: false} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, words := range map[string]string{ + "NullTwice": "but its null ones admits a value the rest of the allOf admits (allOf/1/oneOf/2: integer)", + "Refused": "(allOf/1/oneOf/0: z; allOf/1/oneOf/1: y)", + } { + warned := diagsAtPointer(diags, diag.UnsatisfiableSchema, "/components/schemas/"+name) + require.Len(t, warned, 1, name) + assert.Contains(t, warned[0].Message, words, name) + } +} + +// TestConjunction_UnionsNoChoicePicksAreKept holds two readings of unions +// the conjunction does not lower: two oneOfs, which choose none, are kept, +// each a conjunct, the position lowering as the keywords beside them say; +// and an anyOf the schema writes beside a oneOf an entry writes, chosen over +// it, narrowing the body, is kept once on the Union as validation logic +// (docs/compilers/openapi.md#competing-keywords). +func TestConjunction_UnionsNoChoicePicksAreKept(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {a: {type: string}}} + B: {type: object, properties: {b: {type: string}}} + TwoOneOfs: {oneOf: [{type: string}, {type: integer}], allOf: [{oneOf: [{type: string}, {type: boolean}]}]} + OwnPassed: {allOf: [{oneOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}]}], type: object, properties: {a: {type: string}}, anyOf: [{required: [a]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + two := typeByName(doc, "TwoOneOfs") + for _, key := range []string{"openapi:oneOf", "openapi:allOf/0"} { + assert.Equal(t, ir.ReasonDegradedLowering, two.Common().Unmodeled[key].Reason, key) + } + passed, ok := typeByName(doc, "OwnPassed").(*ir.Union) + require.True(t, ok, "OwnPassed distributes the oneOf; got %T", typeByName(doc, "OwnPassed")) + assert.Equal(t, ir.ReasonValidationOnly, passed.Unmodeled["openapi:anyOf"].Reason) + for _, variant := range passed.Variants { + assert.NotContains(t, doc.Types[variant.Type.Target].Common().Unmodeled, "openapi:anyOf", "no variant keeps it") + } +} + +// TestConjunction_ANullOnlyConjunctionIsTheNullType holds a conjunction whose +// kinds intersect in null alone, one conjunct writing a union, to the null type +// in every spelling: the closed empty Enum a `type: 'null'` lowers to, never a +// Model, keeping the union once with its one report, an object branch dead +// beside it among them (docs/compilers/openapi.md#union-null-only). +func TestConjunction_ANullOnlyConjunctionIsTheNullType(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Entry: {allOf: [{oneOf: [{type: string}, {type: 'null'}]}, {type: [integer, 'null']}]} + Beside: {allOf: [{type: [integer, 'null']}], oneOf: [{type: string}, {type: 'null'}]} + Flat: {type: [integer, 'null'], oneOf: [{type: string}, {type: 'null'}]} + ObjectEntry: {allOf: [{oneOf: [{type: object, properties: {a: {type: string}}}, {type: 'null'}]}, {type: [integer, 'null']}]} + ObjectBeside: {allOf: [{type: [integer, 'null']}], oneOf: [{type: object, properties: {a: {type: string}}}, {type: 'null'}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, at := range map[string]string{ + "Entry": "/allOf/0/oneOf", "Beside": "/oneOf", "Flat": "/oneOf", "ObjectEntry": "/allOf/0/oneOf", "ObjectBeside": "/oneOf", + } { + node, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s is the null type; got %T", name, typeByName(doc, name)) + assert.True(t, node.Closed, name) + assert.Empty(t, node.Members, name) + kept, ok := node.Unmodeled["openapi:oneOf"] + require.True(t, ok, "%s keeps its union", name) + assert.Equal(t, jsontext.Pointer("/components/schemas/"+name+at), kept.Provenance.Pointer, name) + assert.Len(t, node.Unmodeled, 1, "%s keeps the union once", name) + } +} + +// TestConjunction_ANarrowingUnionNoChoiceLowersIsValidationLogic holds a +// union that narrows what its position declares and that the position does +// not lower from to validation logic: two oneOfs beside a $ref, which choose +// neither, and an anyOf on an entry beside the oneOf a union written alone +// chooses (docs/compilers/openapi.md#competing-keywords). +func TestConjunction_ANarrowingUnionNoChoiceLowersIsValidationLogic(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Str: {type: string} + BesideRef: {allOf: [{$ref: '#/components/schemas/Str'}, {oneOf: [{maxLength: 3}]}], oneOf: [{minLength: 1}]} + OnEntry: {oneOf: [{type: string}, {type: integer}], allOf: [{anyOf: [{minLength: 1}, {maximum: 3}]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, key := range map[string]string{"BesideRef": "openapi:oneOf", "OnEntry": "openapi:anyOf"} { + assert.Equal(t, ir.ReasonValidationOnly, typeByName(doc, name).Common().Unmodeled[key].Reason, name) + } + _, isUnion := typeByName(doc, "OnEntry").(*ir.Union) + assert.True(t, isUnion, "OnEntry is the union written alone") +} diff --git a/compilers/openapi/internal/schema/unionkeyword.go b/compilers/openapi/internal/schema/unionkeyword.go new file mode 100644 index 000000000..77f329b4f --- /dev/null +++ b/compilers/openapi/internal/schema/unionkeyword.go @@ -0,0 +1,77 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "strconv" + + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// unionKeyword is the keyword a union is written under, as it is spelled. +type unionKeyword string + +const ( + // oneOfKeyword is oneOf: an instance matches exactly one branch. + oneOfKeyword unionKeyword = "oneOf" + // anyOfKeyword is anyOf: an instance matches one branch or more. + anyOfKeyword unionKeyword = "anyOf" +) + +// unionKeywords are the union keywords, in the order a schema's are read. +var unionKeywords = []unionKeyword{oneOfKeyword, anyOfKeyword} + +// Exclusive reports whether the branches k lists exclude each other, as a +// oneOf's do. +func (k unionKeyword) Exclusive() bool { return k == oneOfKeyword } + +// other is the union keyword k is not: what a schema writing both passes over +// where it lowers k. +func (k unionKeyword) other() unionKeyword { + if k == oneOfKeyword { + return anyOfKeyword + } + return oneOfKeyword +} + +// branchesOf returns the branches holder lists under k. +func (k unionKeyword) branchesOf(holder *statement.Schema) []statement.Subschema { + choice := holder.ChoiceKeywords() + if k == oneOfKeyword { + return choice.OneOf + } + return choice.AnyOf +} + +// keywordAt is the pointer of the keyword k the schema at at writes. +func (k unionKeyword) keywordAt(at jsontext.Pointer) jsontext.Pointer { + return at + ids.Ptr(string(k)) +} + +// branchAt is the pointer of the branch at index i of the union written +// under k by the schema at at. +func (k unionKeyword) branchAt(at jsontext.Pointer, i int) jsontext.Pointer { + return at + ids.Ptr(string(k), strconv.Itoa(i)) +} + +// branchPath is the path of the branch at index i of the union written under +// k from the schema writing it. +func (k unionKeyword) branchPath(i int) string { + return string(k) + "/" + strconv.Itoa(i) +} + +// loweredKeyword is the keyword of the union holder lowers at position, holder +// itself or the schema writing the allOf holding it. Of both, the oneOf wins +// unless only the anyOf declares shape against the position; every caller +// keeps the set it passed over, which is otherwise dropped in silence. +func loweredKeyword(loweringContext lowering.Ctx, position, holder *statement.Schema) unionKeyword { + choice := holder.ChoiceKeywords() + if len(choice.OneOf) > 0 && (len(choice.AnyOf) == 0 || !anyOfChosen(loweringContext, position, holder)) { + return oneOfKeyword + } + return anyOfKeyword +} diff --git a/compilers/openapi/internal/schema/unionresidue.go b/compilers/openapi/internal/schema/unionresidue.go new file mode 100644 index 000000000..1e6f111c9 --- /dev/null +++ b/compilers/openapi/internal/schema/unionresidue.go @@ -0,0 +1,75 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// unionKeyOutcome is how a key an allOf conjunct writes is read where the union +// the position's conjunction chooses is what the position lowers to. +type unionKeyOutcome uint8 + +const ( + // unionKeyByRefinement leaves the key to the refinement's own reading. + unionKeyByRefinement unionKeyOutcome = iota + // unionKeyRead marks a key the union's lowering reads. + unionKeyRead + // unionKeyKept marks a key the union's lowering reads none of. + unionKeyKept +) + +// readUnionKeyOutcome says how key, written by the conjunct entrySchema, is +// read where position lowers to the union its conjunction chooses: as the same +// key written flat beside that union is +// (docs/compilers/openapi.md#allof-inline-residue). Beside a union leaving null +// alone a value set is read, as its closed empty Enum reads one. +func readUnionKeyOutcome(loweringContext lowering.Ctx, position, entrySchema *statement.Schema, homes boundHomes, key string) unionKeyOutcome { + loweredUnion, lowersUnion := readConjunction(loweringContext, position).loweredUnion() + if !lowersUnion { + return unionKeyByRefinement + } + besideRest := readLoweredUnion(loweringContext, position).besideRest + collapses := unionLoweredAlone(loweringContext, position, loweredUnion.holder) && unionCollapses(loweringContext, position, loweredUnion.holder) + switch { + case collapses && keyBit(key) != 0: + return unionKeyOutcomeOf(keySetOf(keywordsBranchesRestate(loweringContext, loweredUnion.holder, entrySchema)...)|readElsewhere(entrySchema)|referenceReads(entrySchema, homes), key) + case besideRest == unionLeavesNullAlone && (key == "enum" || key == "const"): + return unionKeyRead + case !collapses && loweredUnion.holder == position && entrySchema != position && (besideRest == unionAlone || besideRest == unionConjoined): + return unionKeyBesideOwnUnion(loweringContext, position, entrySchema, key) + default: + return unionKeyByRefinement + } +} + +// unionKeyBesideOwnUnion says how key, written by an allOf entry of position, +// which writes the union alone or conjoined with its body's kind, is read. The +// content vocabulary is kept, as neither the Union nor its one live branch's +// node holds an encoding of the body, and a bound is left to each variant. +func unionKeyBesideOwnUnion(loweringContext lowering.Ctx, position, entrySchema *statement.Schema, key string) unionKeyOutcome { + switch { + case slices.Contains(contentKeywords, key): + return unionKeyKept + case keyBit(key) == 0, slices.Contains(valueConstraintKeywords, key): + return unionKeyByRefinement + } + read := keySetOf(keywordsBranchesRestate(loweringContext, position, entrySchema)...) | readElsewhere(entrySchema) + if conjoinedKind(loweringContext, position, position) != "" { + read |= keyBit("type") + } + return unionKeyOutcomeOf(read, key) +} + +// unionKeyOutcomeOf is unionKeyRead where read holds key, and unionKeyKept +// where it does not. +func unionKeyOutcomeOf(read keySet, key string) unionKeyOutcome { + if read.has(key) { + return unionKeyRead + } + return unionKeyKept +} diff --git a/compilers/openapi/internal/schema/unknowngate_test.go b/compilers/openapi/internal/schema/unknowngate_test.go new file mode 100644 index 000000000..2d19bf973 --- /dev/null +++ b/compilers/openapi/internal/schema/unknowngate_test.go @@ -0,0 +1,435 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "encoding/json/jsontext" + "fmt" + "go/ast" + "go/constant" + "go/types" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/internal/decls" + "github.com/dexpace/morphic/ir" +) + +// gateDialect is a dialect a schema is read in: a minor's own where dialect is +// "", and otherwise the one its document's jsonSchemaDialect names. +type gateDialect struct{ version, dialect string } + +// gateDialects are each minor's own dialect and each the dialect table has rows +// for (specrules' schemaDialects), named in a document of the minor naming it. +// TestGateDialects_AreTheDeclaredOnes holds the list to both. +var gateDialects = []gateDialect{ + {"3.0.3", ""}, {"3.1.0", ""}, {"3.2.0", ""}, + {"3.1.0", "https://spec.openapis.org/oas/3.1/dialect/base"}, + {"3.1.0", "https://spec.openapis.org/oas/3.1/dialect/2024-10-25"}, + {"3.1.0", "https://spec.openapis.org/oas/3.1/dialect/2024-11-10"}, + {"3.2.0", "https://spec.openapis.org/oas/3.2/dialect/2025-09-17"}, + {"3.2.0", "https://spec.openapis.org/oas/3.2/dialect/2026-02-26"}, + {"3.1.0", "https://json-schema.org/draft/2020-12/schema"}, + {"3.1.0", "https://json-schema.org/draft/2019-09/schema"}, + {"3.1.0", "http://json-schema.org/draft-07/schema#"}, + {"3.1.0", "http://json-schema.org/draft-06/schema#"}, + {"3.1.0", "http://json-schema.org/draft-04/schema#"}, +} + +// TestGateDialects_AreTheDeclaredOnes holds gateDialects to what specrules +// declares: a minor's own dialect for each Minor constant, and a named one for +// each id schemaDialects lists, so a dialect added there is written here too. +func TestGateDialects_AreTheDeclaredOnes(t *testing.T) { + t.Parallel() + loadedPackage, err := decls.Load("github.com/dexpace/morphic/compilers/openapi/internal/specrules") + require.NoError(t, err) + minorType, err := loadedPackage.Named("Minor") + require.NoError(t, err) + var declaredMinors, declaredIDs []string + for declared := range loadedPackage.Objects[*types.Const]() { + if !types.Identical(declared.Type(), minorType) { + continue + } + value, exact := constant.Uint64Val(declared.Val()) + require.True(t, exact, declared.Name()) + declaredMinors = append(declaredMinors, specrules.Minor(value).String()) + } + for _, file := range loadedPackage.Syntax { + for _, declaration := range file.Decls { + if function, ok := declaration.(*ast.FuncDecl); ok && function.Name.Name == "schemaDialects" { + declaredIDs = append(declaredIDs, dialectIDs(t, loadedPackage.Info, function.Body)...) + } + } + } + require.NotEmpty(t, declaredMinors, "specrules declares its minors") + require.NotEmpty(t, declaredIDs, "schemaDialects declares the dialects") + + var minors, ids []string + for _, dialect := range gateDialects { + if dialect.dialect != "" { + ids = append(ids, dialect.dialect) + continue + } + minor, ok := specrules.ParseMinor(dialect.version) + require.True(t, ok, dialect.version) + minors = append(minors, minor.String()) + } + assert.ElementsMatch(t, declaredMinors, minors, "a minor's own dialect for each Minor") + assert.ElementsMatch(t, declaredIDs, ids, "a named dialect for each schemaDialects lists") +} + +// dialectIDs returns the value of each id field body writes, as the compiler +// reads the constant. +func dialectIDs(t *testing.T, info *types.Info, body *ast.BlockStmt) []string { + t.Helper() + var ids []string + ast.Inspect(body, func(node ast.Node) bool { + field, ok := node.(*ast.KeyValueExpr) + if !ok { + return true + } + if key, named := field.Key.(*ast.Ident); named && key.Name == "id" { + value := info.Types[field.Value].Value + require.True(t, value != nil && value.Kind() == constant.String, "an id is a string constant") + ids = append(ids, constant.StringVal(value)) + } + return true + }) + return ids +} + +// gatePosition is a position a $ref can be written at: in the component S, S +// itself among them, or as the request body, each spelt around %s. +type gatePosition struct { + name, component, body string + at jsontext.Pointer +} + +// gatePositions are the positions the alias gate decides for. +var gatePositions = []gatePosition{ + {"items", "{type: array, items: %s}", "", "/components/schemas/S/items"}, + {"prefixItems", "{type: array, prefixItems: [%s]}", "", "/components/schemas/S/prefixItems/0"}, + {"an allOf entry", "{allOf: [%s, {description: d}]}", "", "/components/schemas/S/allOf/0"}, + {"additionalProperties", "{type: object, additionalProperties: %s}", "", "/components/schemas/S/additionalProperties"}, + {"a oneOf branch", "{oneOf: [%s, {type: integer}]}", "", "/components/schemas/S/oneOf/0"}, + {"a request body", "{type: integer}", "%s", "/paths/~1p/post/requestBody/content/application~1json/schema"}, + {"the component", "%s", "", "/components/schemas/S"}, +} + +// The targets a gate test's $ref names: a string, which a position lowered to +// a use of it holds an alias over, and an object, which it holds a Model over. +const ( + stringTarget = "{type: string}" + objectTarget = "{type: object, properties: {t: {type: string}}}" +) + +// gateDocument is a document of dialect writing written at position, beside +// the component T, written as target, its $ref names. +func gateDocument(target string, dialect gateDialect, position gatePosition, written string) string { + component, body := position.component, "{type: integer}" + if position.body != "" { + body = fmt.Sprintf(position.body, written) + } else { + component = fmt.Sprintf(position.component, written) + } + var named string + if dialect.dialect != "" { + named = "jsonSchemaDialect: '" + dialect.dialect + "'\n" + } + return "openapi: " + dialect.version + "\ninfo: {title: T, version: \"1\"}\n" + named + + "paths:\n /p:\n post:\n requestBody: {content: {application/json: {schema: " + body + "}}}\n" + + " responses: {'204': {description: d}}\n" + + "components:\n schemas:\n T: " + target + "\n S: " + component + "\n" +} + +// takenSpellings writes each key unknownTaken can return beside a $ref, with +// what it needs beside it: additionalItems is taken only beside a list of items. +var takenSpellings = map[string][]string{ + "additionalItems": {"items: [{type: string}], additionalItems: false"}, + "definitions": {"definitions: {X: {type: string}}"}, + "$recursiveAnchor": {"$recursiveAnchor: true", "$recursiveAnchor: false"}, + "$recursiveRef": {"$recursiveRef: '#'"}, +} + +// TestAliasGate_AgreesWithTheUnknownKeywordKeeper holds the alias gate's +// reading of KeepUnknownKeywords to the keeper, for each key unknownTaken +// returns in each dialect, written beside a $ref at each position +// (holdGateToKeeper). The keys are read off unknownTaken at a schema meeting +// each of its conditions the dialect admits, so a key it comes to return is +// written too, and one takenSpellings cannot write fails here. +func TestAliasGate_AgreesWithTheUnknownKeywordKeeper(t *testing.T) { + t.Parallel() + var written int + for _, dialect := range gateDialects { + for _, key := range takenKeys(t, dialect) { + written++ + spellings, ok := takenSpellings[key] + require.True(t, ok, "takenSpellings writes %s", key) + for _, spelling := range spellings { + for _, position := range gatePositions { + name := strings.Join([]string{dialect.version, dialect.dialect, spelling, position.name}, " ") + t.Run(name, func(t *testing.T) { + t.Parallel() + holdGateToKeeper(t, stringTarget, dialect, position, key, spelling) + }) + } + } + } + } + require.Positive(t, written, "some dialect's unknownTaken returned a key") +} + +// takenKeys returns the keys unknownTaken returns in dialect at a schema +// beside a $ref writing every key it can, a list of items only where the +// dialect reads one, as the drafts do: elsewhere the list is refused. +func takenKeys(t *testing.T, dialect gateDialect) []string { + t.Helper() + const every = "{$ref: '#/components/schemas/T', definitions: {X: {type: string}}, $recursiveAnchor: true, $recursiveRef: '#'" + at := gatePositions[0].at + lowerer, _ := schema.LoweredFor(t, gateDocument(stringTarget, dialect, gatePositions[0], every+"}")) + if lowerer.Ctx.Rules().At(lowerer.Ctx.Position(at)).Takes("items", specrules.List) { + lowerer, _ = schema.LoweredFor(t, gateDocument(stringTarget, dialect, gatePositions[0], every+", items: [{type: string}], additionalItems: false}")) + } + statementValue := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: at}) + return schema.UnknownTaken(lowerer.Ctx, statementValue.Schema, at) +} + +// TestAliasGate_ATakenKeyLowersToTheTarget names the spellings whose gate once +// read a key the keeper takes as one it keeps, hoisting an alias holding +// nothing: a draft's definitions and 2019-09's $recursiveAnchor beside a $ref, +// over a string and over an object, whose component S once lowered to an +// alias where its bare $ref lowers to the Model. +func TestAliasGate_ATakenKeyLowersToTheTarget(t *testing.T) { + t.Parallel() + draft04 := gateDialect{"3.1.0", "http://json-schema.org/draft-04/schema#"} + draft07 := gateDialect{"3.1.0", "http://json-schema.org/draft-07/schema#"} + draft2019 := gateDialect{"3.1.0", "https://json-schema.org/draft/2019-09/schema"} + for _, testCase := range []struct { + name string + dialect gateDialect + key string + spelling string + }{ + {"draft-04 definitions", draft04, "definitions", "definitions: {X: {type: string}}"}, + {"draft-07 definitions", draft07, "definitions", "definitions: {X: {type: string}}"}, + {"2019-09 $recursiveAnchor true", draft2019, "$recursiveAnchor", "$recursiveAnchor: true"}, + {"2019-09 $recursiveAnchor false", draft2019, "$recursiveAnchor", "$recursiveAnchor: false"}, + } { + for _, position := range []gatePosition{gatePositions[0], gatePositions[2], gatePositions[3], gatePositions[6]} { + for _, target := range []string{stringTarget, objectTarget} { + t.Run(testCase.name+" at "+position.name+" over "+target, func(t *testing.T) { + t.Parallel() + holdGateToKeeper(t, target, testCase.dialect, position, testCase.key, testCase.spelling) + doc, _ := parseFull(t, gateDocument(target, testCase.dialect, position, "{$ref: '#/components/schemas/T', "+testCase.spelling+"}")) + assert.False(t, keptFrom(doc, position.at.AppendToken(testCase.key)), "nothing keeps %s", testCase.key) + }) + } + } + } +} + +// holdGateToKeeper compiles spelling, which writes key, beside a $ref to +// target at position and holds the gate to what is kept: keepsUnknownKeywords +// says what KeepUnknownKeywords keeps there, a node hoisted at the +// position, which the bare $ref does not build, keeps something, and where +// nothing of key is kept the position lowers as the bare $ref does. +func holdGateToKeeper(t *testing.T, target string, dialect gateDialect, position gatePosition, key, spelling string) { + t.Helper() + src := gateDocument(target, dialect, position, "{$ref: '#/components/schemas/T', "+spelling+"}") + lowerer, _ := schema.LoweredFor(t, src) + statementValue := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: position.at}) + var keeperKept ir.Unmodeled + schema.KeepUnknownKeywords(lowerer.Ctx, &keeperKept, statementValue.Schema, position.at, nil) + assert.Equal(t, len(keeperKept) > 0, schema.KeepsUnknownKeywords(lowerer.Ctx, statementValue.Schema, position.at), + "the gate reads what the keeper keeps") + + doc, diags := parseFull(t, src) + openapitest.RequireNoErrorDiags(t, diags) + bare, _ := parseFull(t, gateDocument(target, dialect, position, "{$ref: '#/components/schemas/T'}")) + id := lowerer.Ctx.IDs().ForPointer(position.at) + if node, hoisted := doc.Types[id]; hoisted && bare.Types[id] == nil { + assert.NotEmpty(t, node.Common().Unmodeled, "a node hoisted at the position keeps what needed it") + } + if !keptFrom(doc, position.at.AppendToken(key)) { + assert.Empty(t, cmp.Diff(bare.Types, doc.Types), "keeping nothing, the position lowers as its bare $ref does") + } +} + +// TestAliasGate_AFindingAloneHoistsNoAlias holds the gate to what is kept +// rather than what is reported (holdFindingAlone): a value no JSON renders, +// beside a $ref at each gate position, at each minor for a draft's keywords, +// and beside a string's type at items, under an inline principal or not. An +// extension no JSON holds is left out of what holds it, which then lowers as +// its twin without it. +func TestAliasGate_AFindingAloneHoistsNoAlias(t *testing.T) { + t.Parallel() + const ref = "{$ref: '#/components/schemas/T'" + for _, testCase := range []struct{ spelling, kept string }{ + {"example: .nan", ""}, {"unknownWord: .nan", ""}, {"dependentRequired: {a: [.nan]}", ""}, + {"xml: {x-k: .nan}", ", xml: {}"}, {"discriminator: {propertyName: k, x-k: .nan}", ", discriminator: {propertyName: k}"}, + } { + for _, position := range gatePositions { + t.Run(testCase.spelling+" at "+position.name, func(t *testing.T) { + t.Parallel() + document := func(written string) string { + return gateDocument(stringTarget, gateDialect{"3.1.0", ""}, position, written) + } + holdFindingAlone(t, document(ref+", "+testCase.spelling+"}"), document(ref+testCase.kept+"}"), position.at, true) + }) + } + } + for _, spelling := range []string{"definitions: .nan", "$recursiveAnchor: .nan", "definitions: {Q: {const: .nan}}"} { + for _, version := range []string{"3.0.3", "3.1.0", "3.2.0"} { + for _, position := range []gatePosition{gatePositions[0], gatePositions[2], gatePositions[3], gatePositions[4], gatePositions[5]} { + t.Run(version+" "+spelling+" at "+position.name, func(t *testing.T) { + t.Parallel() + document := func(written string) string { + return gateDocument(stringTarget, gateDialect{version, ""}, position, written) + } + holdFindingAlone(t, document(ref+", "+spelling+"}"), document(ref+"}"), position.at, true) + }) + } + } + } + for _, spelling := range []string{"required: [.nan]", "minimum: .nan"} { + for _, version := range []string{"3.0.3", "3.1.0"} { + t.Run(version+" "+spelling+" under an inline principal", func(t *testing.T) { + t.Parallel() + document := func(principal string) string { + return openapitest.ComponentSpecVer(version, " S: {type: array, items: {allOf: [{type: string"+principal+"}]}}\n") + } + holdFindingAlone(t, document(", "+spelling), document(""), "/components/schemas/S/items", true) + }) + t.Run(version+" "+spelling+" at items itself", func(t *testing.T) { + t.Parallel() + document := func(beside string) string { + return openapitest.ComponentSpecVer(version, " S: {type: array, items: {type: string"+beside+"}}\n") + } + holdFindingAlone(t, document(", "+spelling), document(""), "/components/schemas/S/items", true) + }) + } + } +} + +// TestAliasGate_AnObjectTargetHoldsWhatIsKeptAlone holds a position whose +// $ref names an object, which a node of its own would hold as a Model, to the +// gate's rule over a string (holdFindingAlone): a value no JSON renders, or an +// annotation saying nothing, hoists no node. +func TestAliasGate_AnObjectTargetHoldsWhatIsKeptAlone(t *testing.T) { + t.Parallel() + const ref = "{$ref: '#/components/schemas/T'" + own := gateDialect{"3.1.0", ""} + positions := []gatePosition{gatePositions[0], gatePositions[1], gatePositions[3], gatePositions[4], gatePositions[5]} + for _, testCase := range []struct { + spelling string + reported bool + }{ + {"example: .nan", true}, {"unknownWord: .nan", true}, {"dependentRequired: {a: [.nan]}", true}, + {"description: ''", false}, {"deprecated: false", false}, + } { + for _, position := range positions { + t.Run(testCase.spelling+" at "+position.name, func(t *testing.T) { + t.Parallel() + document := func(written string) string { return gateDocument(objectTarget, own, position, written) } + holdFindingAlone(t, document(ref+", "+testCase.spelling+"}"), document(ref+"}"), position.at, testCase.reported) + }) + } + } +} + +// TestAliasGate_AnEmptyXMLIsAHintHeld pins the one reading of an empty xml +// beside a $ref, over a string as over an object: it is a hint, so the +// position hoists a node holding it. +func TestAliasGate_AnEmptyXMLIsAHintHeld(t *testing.T) { + t.Parallel() + positions := []gatePosition{gatePositions[0], gatePositions[1], gatePositions[3], gatePositions[4], gatePositions[5]} + for _, target := range []string{stringTarget, objectTarget} { + for _, position := range positions { + t.Run(position.name+" over "+target, func(t *testing.T) { + t.Parallel() + src := gateDocument(target, gateDialect{"3.1.0", ""}, position, "{$ref: '#/components/schemas/T', xml: {}}") + doc, _ := parseFull(t, src) + lowerer, _ := schema.LoweredFor(t, src) + node, hoisted := doc.Types[lowerer.Ctx.IDs().ForPointer(position.at)] + require.True(t, hoisted, "an empty xml is a hint a node holds") + assert.Equal(t, &ir.XMLHints{}, node.Common().XML) + }) + } + } +} + +// holdFindingAlone compiles src, which writes at the position at a value kept +// nowhere, beside equivalent, src with what a node keeps of that value alone, +// often nothing. src compiles as equivalent does, building no node equivalent +// does not, and draws each finding beyond equivalent's once and within the +// position, some where reported holds. +func holdFindingAlone(t *testing.T, src, equivalent string, at jsontext.Pointer, reported bool) { + t.Helper() + doc, diags := parseFull(t, src) + equivalentDoc, equivalentDiags := parseFull(t, equivalent) + assert.Empty(t, cmp.Diff(equivalentDoc.Types, doc.Types), "the position compiles as it does without what is kept nowhere") + findings := findingsBeyond(diags, equivalentDiags) + assert.Equal(t, reported, len(findings) > 0, "what no JSON renders is reported, and what says nothing is not") + for found, count := range findings { + assert.Equal(t, 1, count, "%+v is drawn once", found) + assert.True(t, strings.HasPrefix(string(found.pointer), string(at)), "%+v sits within the position", found) + } +} + +// finding is a diagnostic as a gate test counts it, without its message. +type finding struct { + severity ir.Severity + code string + pointer jsontext.Pointer +} + +// findingsBeyond counts each finding of diags beyond those of bare, the +// diagnostics of the same document without what one position writes. +func findingsBeyond(diags, bare []ir.Diagnostic) map[finding]int { + counted := map[finding]int{} + for _, diagnostic := range diags { + counted[finding{diagnostic.Severity, diagnostic.Code, diagnostic.Provenance.Pointer}]++ + } + for _, diagnostic := range bare { + key := finding{diagnostic.Severity, diagnostic.Code, diagnostic.Provenance.Pointer} + if counted[key]--; counted[key] == 0 { + delete(counted, key) + } + } + return counted +} + +// keptFrom reports whether a node or a property of doc keeps verbatim what is +// written at pointer. +func keptFrom(doc *ir.Document, pointer jsontext.Pointer) bool { + keeps := func(unmodeled ir.Unmodeled) bool { + for _, entry := range unmodeled { + if entry.Provenance.Pointer == pointer { + return true + } + } + return false + } + for _, typeDef := range doc.Types { + if keeps(typeDef.Common().Unmodeled) { + return true + } + if model, ok := typeDef.(*ir.Model); ok { + for _, property := range model.Properties { + if keeps(property.Unmodeled) { + return true + } + } + } + } + return false +} diff --git a/compilers/openapi/internal/schema/unread.go b/compilers/openapi/internal/schema/unread.go index f96de2a1e..50efe45b2 100644 --- a/compilers/openapi/internal/schema/unread.go +++ b/compilers/openapi/internal/schema/unread.go @@ -10,31 +10,34 @@ import ( "strings" "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/ir" ) -// unreadKeys returns the keys of readDomain s writes that read does not +// unreadKeys returns the keys of readDomain schema writes that read does not // hold, in readDomain order: what the node a position lowered to keeps -// verbatim, as no build read it into a field and no election accounted for it. +// verbatim, as no build read it into a field and no choice accounted for it. +// A key written as it left out says nothing to keep +// (annotation.WritesKeywordLeftOut). func unreadKeys(schema *statement.Schema, read keySet) []string { var out []string - for _, k := range readDomain { - if hasKey(schema, k) && !read.has(k) { - out = append(out, k) + for _, key := range readDomain { + if hasKey(schema, key) && !read.has(key) && !annotation.WritesKeywordLeftOut(schema, key) { + out = append(out, key) } } return out } // unreadByReference is unreadKeys for a position schema lowered to a reference, -// whose alias or carrier reads what referenceReads says, beside what is read -// outside a node's build (readElsewhere) and what the position's lowering -// accounted for itself, handled. -func unreadByReference(loweringContext lowering.Ctx, schema *statement.Schema, handled keySet) []string { - return unreadKeys(schema, referenceReads(loweringContext, schema)|readElsewhere(schema)|handled) +// whose alias or carrier, holding homes, reads what referenceReads says, +// beside what is read outside a node's build (readElsewhere) and what the +// position's lowering accounted for itself, handled. +func unreadByReference(schema *statement.Schema, homes boundHomes, handled keySet) []string { + return unreadKeys(schema, referenceReads(schema, homes)|readElsewhere(schema)|handled) } // What a position lowering to a reference lowered to, for the diagnostic @@ -54,138 +57,186 @@ func expandedShapeOf(schema *statement.Schema) string { return "a reference to the type its $recursiveRef expands to" } -// referenceOutcomeKeywords returns the keys schema writes that the position keeps -// where it lowers to a reference to a node that is not its own, and what it -// lowered to: a collapsed union (lowerOneOfAnyOf), or an expanded $dynamicRef, -// which a lowering of schema decides first. It is nil for any other outcome. The -// target belongs to its declaration as a $ref site's does to the referent, so -// only what the position's alias or carrier reads is homed (unreadByReference). -// Those two write few: neither expands or collapses beside a shape (GitHub #595). -func referenceOutcomeKeywords(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) ([]string, string) { +// referenceOutcome returns what schema, written at pointer, lowered to where it +// lowers to a reference to a node that is not its own: a collapsed union +// (lowerOneOfAnyOf), or an expanded $dynamicRef, which a lowering of schema +// decides first, and what that lowering accounted for itself. The shape is "" +// for any other outcome. The target belongs to its declaration as a $ref +// site's does to the referent, so only what the position's alias or carrier +// reads is homed (unreadByReference). Those two write few: neither expands or +// collapses beside a shape (GitHub #595). +func referenceOutcome(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (shape string, handled keySet) { if _, _, expanded := dynamicExpansion(loweringContext, schema, pointer); expanded { - return unreadByReference(loweringContext, schema, 0), expandedShapeOf(schema) + conjunctSchema, _ := dynamicRefConjunct(loweringContext, schema, pointer) + return expandedShapeOf(conjunctSchema), idiomsNullKeys(loweringContext, schema) } if hasUnionSiblings(loweringContext, schema) { - return nil, "" + return "", 0 } - if _, _, collapses := nullUnionCollapse(loweringContext, schema, ""); !collapses { - return nil, "" + if _, _, collapses := nullUnionCollapse(loweringContext, schema, ""); !collapses || leavesNullAlone(loweringContext, schema, schema) || + leavesDead(loweringContext, schema, schema) { + return "", 0 } - return unreadByReference(loweringContext, schema, keySetOf(branchesSay(loweringContext, schema, schema)...)), collapsedShape + return collapsedShape, keySetOf(keywordsBranchesRestate(loweringContext, schema, schema)...) } -// keepingUnread lowers the position schema, written at pointer, through build, -// the node build interns there finished by keepUnread before fin, the outer -// frames' finisher. One lowering to a shared node keeps what it did not read on -// an alias (keepUnreadShared). It returns the position's resulting ID and the -// build's findings, the keeping's after them, as they always stood. +// idiomsNullKeys is the value keywords schema writes beside the dynamic +// reference it expands that say the null the nullable-inference policy widens +// that reference by (nullIdiomConsumes), which the reference holds: read, so +// kept nowhere, as beside a $ref. +func idiomsNullKeys(loweringContext lowering.Ctx, schema *statement.Schema) keySet { + if !nullIdiomConsumes(loweringContext, schema, schema) { + return 0 + } + return keySetOf("type", "const", "enum") +} + +// finishUnread keeps what the build of schema, written at pointer, did not +// read, on the node it built or on an alias over the shared primitive it +// lowered to; a node another visit built was finished by that visit. // docs/compilers/openapi.md#shape-applicator covers a contradictory schema's -// dropped half and an untyped applicator such as `items`. build returns, beside -// the ID, what a lowering to a shared node read. -func keepingUnread(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, dispatchValue dispatch, fin finisher, st stand, - build func(fin finisher) (ir.TypeID, keySet, []ir.Diagnostic), -) (ir.TypeID, []ir.Diagnostic) { - var kept finished - id, shared, diags := build(func(td ir.TypeDef, read keySet, held *principalKept) { - kept.ran = true - kept.diags = keepUnread(loweringContext, ts, schema, pointer, td, dispatchValue, read, st, held, fin) - }) - if kept.ran || LoweredToOwnNode(loweringContext, st.pointer(pointer), ir.TypeRef{Target: id}) { - // A node the position owns that this visit found built was finished by - // the visit building it. - return id, append(diags, kept.diags...) +// dropped half and an untyped applicator such as `items`. +func finishUnread(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, + dispatchValue dispatch, placement nodePlacement, built builtPosition, shared keySet, +) (builtPosition, []ir.Diagnostic) { + if built.node != nil { + diags := keepUnread(loweringContext, schema, pointer, &built, dispatchValue, placement) + return built, diags } - owner, sharedDiags := keepUnreadShared(loweringContext, ts, schema, pointer, id, dispatchValue, shared, fin, st) - return owner, append(diags, sharedDiags...) + if LoweredToOwnNode(loweringContext, placement.pointer(pointer), ir.TypeRef{Target: built.id}) { + return built, nil + } + return keepUnreadShared(loweringContext, types, schema, pointer, built.id, dispatchValue, shared, placement) } -// keepUnread keeps verbatim on td, the node the position owns, in hand, each -// key of readDomain s, written at pointer, writes that the build of td did -// not read, nor a reader beside it (readElsewhere), nor d's election skipped or -// said, and the families it skipped, then finishes td by fin, as keepAround -// orders the two where the node stands for st's position. +// keepUnread keeps verbatim on built.node, the node the position owns, in hand, +// each key of readDomain schema, written at pointer, writes that the build of +// built.node did not read, nor a reader beside it (readBeside), nor +// dispatchValue's choice skipped or said, and the families it skipped. // // A multipart body keys no part for `properties` the node lacks // (docs/compilers/openapi.md#multipart-encoding). -func keepUnread(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, td ir.TypeDef, dispatchValue dispatch, - read keySet, st stand, held *principalKept, fin finisher, +func keepUnread(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, + built *builtPosition, dispatchValue dispatch, placement nodePlacement, ) []ir.Diagnostic { - unread := unreadKeys(schema, read|readBeside(schema, td)|dispatchValue.handled()) - if st.of == nil { - // The schema's own node, the path every node takes: keep, then finish. + typeDef := built.node + unread := unreadKeys(schema, built.read|readBeside(schema, typeDef)|dispatchValue.handled()) + if placement.position == nil { var diags []ir.Diagnostic if len(unread) > 0 { - diags = recordUnread(loweringContext, ts, &td.Common().Unmodeled, schema, unread, positionShape(td, schema), pointer) + diags = recordUnread(loweringContext, &typeDef.Common().Unmodeled, schema, unread, positionShape(typeDef, schema), pointer) } - diags = append(diags, recordSkippedFamilies(loweringContext, td, schema, dispatchValue, pointer)...) - fin.run(td, read, held) - return diags + return append(diags, recordSkippedFamilies(loweringContext, typeDef, &typeDef.Common().Unmodeled, schema, dispatchValue, pointer).Diagnostics()...) } - var skipped finished - fin = skipped.on(func(td ir.TypeDef) []ir.Diagnostic { - return recordSkippedFamilies(loweringContext, td, schema, dispatchValue, pointer) - }).then(fin) - shape := positionShape(td, schema) + shape := positionShape(typeDef, schema) keepingValue := keeping{keys: unread, reason: ir.ReasonDegradedLowering, shape: shape, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { - return recordUnread(loweringContext, ts, unmodeled, schema, keys, shape, pointer) + return recordUnread(loweringContext, unmodeled, schema, keys, shape, pointer) }} - return append(keepAround(loweringContext, ts, st, td, read, held, schema, pointer, keepingValue, fin), skipped.diags...) + diags := keepAround(loweringContext, placement, built, schema, pointer, keepingValue) + keeps := builtKeeps{pendingKeeps: &built.pendingKeeps, pointer: pointer, placement: placement} + return append(diags, keeps.keep(loweringContext, &typeDef.Common().Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + // What the principal's own choice passed over is reported where + // drawn, whatever the position keeps of it, as written alone. + return annotation.ReportsOf("", recordSkippedFamilies(loweringContext, typeDef, unmodeled, schema, dispatchValue, pointer).Diagnostics()...) + })...) } -// keepUnreadShared is keepUnread for a position that lowered to id, a shared -// primitive, which read shared of schema: the alias hoisted over it where st -// says, finished by the keeping and then fin, holds what neither read, the -// alias reading the bounds the types the position admits take. It returns id -// itself, fin unfinished, where nothing is kept. -func keepUnreadShared(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, id ir.TypeID, dispatchValue dispatch, - shared keySet, fin finisher, st stand, -) (ir.TypeID, []ir.Diagnostic) { - unread := unreadKeys(schema, shared|boundsRead(schema, st.takes(loweringContext, schema), nil)|readElsewhere(schema)|dispatchValue.handled()) - if len(unread) == 0 && len(dispatchValue.skipped) == 0 { - return id, nil +// besideBoundsUntaken reports whether the position principal names +// (placement), beside its allOf or on an entry of it other than principal, +// writes a bound the node, holding homes, neither holds nor keeps itself as +// text of another kind (valueReads): written flat, the bound is the hoisted +// alias's, so the alias sits at the position to hold it there too (#2116). +func besideBoundsUntaken(loweringContext lowering.Ctx, placement nodePlacement, principal *statement.Schema, homes boundHomes) bool { + if placement.position == nil { + return false + } + untaken := func(conjunctSchema *statement.Schema) bool { + return declaresBound(conjunctSchema) && boundsRead(conjunctSchema, everyKindButNull, nil)&^homes.valueReads(conjunctSchema) != 0 } - var kept, skipped finished - fin = skipped.on(func(alias ir.TypeDef) []ir.Diagnostic { - return recordSkippedFamilies(loweringContext, alias, schema, dispatchValue, pointer) - }).then(fin) - keep := keepUnreadOn(loweringContext, ts, schema, unread, nodeShape(ir.KindPrimitive), pointer, st, &kept, fin) - owner, aliasDiags := internAlias(loweringContext, ts, schema, pointer, ir.TypeRef{Target: id}, keep, st) - return owner, slices.Concat(aliasDiags, kept.diags, skipped.diags) + if untaken(placement.position) { + return true + } + return slices.ContainsFunc(allOfEntries(loweringContext, placement.position, placement.positionPointer).entries, func(entry allOfEntry) bool { + entrySchema := entry.schema.Schema + return entry.schema.Ref == nil && entrySchema != principal && stated(entrySchema) && untaken(entrySchema) + }) } -// keepUnreadOn returns the finisher keeping unhomed, the keywords s, written -// at pointer, declares that no build read into the position's node, on that -// node in hand, reporting what the position lowered to as shape and recording -// into kept, then finishing it by fin, as keepAround orders the two where the -// node stands for st's position. -func keepUnreadOn(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, unhomed []string, shape string, pointer jsontext.Pointer, - st stand, kept *finished, fin finisher, -) finisher { - keepingValue := keeping{keys: unhomed, reason: ir.ReasonDegradedLowering, shape: shape, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { - return recordUnread(loweringContext, ts, unmodeled, schema, keys, shape, pointer) - }} - return func(td ir.TypeDef, read keySet, held *principalKept) { - kept.ran = true - kept.diags = append(kept.diags, keepAround(loweringContext, ts, st, td, read, held, schema, pointer, keepingValue, fin)...) +// keepUnreadShared is keepUnread for a position that lowered to id, a shared +// primitive, which read shared of schema: the alias hoisted over it where +// placement says holds what neither read, the alias reading the bounds the +// types the position admits take. It returns builtPosition{id: id} where +// nothing is kept. +func keepUnreadShared(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, id ir.TypeID, + dispatchValue dispatch, shared keySet, placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { + homes := aliasHomes(loweringContext, schema, pointer, ir.TypeRef{Target: id}, placement) + unread := unreadKeys(schema, shared|homes.valueReads(schema)|readElsewhere(schema)|dispatchValue.handled()) + untaken := besideBoundsUntaken(loweringContext, placement, schema, homes) + if len(unread) == 0 && len(dispatchValue.skipped) == 0 && !untaken { + return builtPosition{id: id}, nil + } + // What is kept settles on the Scalar aliasing the primitive, which the + // report names (aliasHolding). + shape := nodeShape(ir.KindScalar) + // Whether the alias is hoisted turns on what it would keep, its keeping + // run on a scratch alias: a finding needs no node, and sits at the + // position. An inline principal's reader keeps what it keeps alike. + cons, kept, reports := aliasBounds(loweringContext, schema, pointer, ir.TypeRef{Target: id}, placement) + at, base := placement.pointer(pointer), scalarBase(loweringContext, schema, placement, id) + scratch := aliasHolding(commonFor(loweringContext, loweringContext.IDs().ForPointer(at), at), cons, base) + // The scratch is judged settled, as a declaration's home is + // (homeDeclaration): what no field holds of its bounds settles on it + // first, reported where it was read. + var scratchPendingKeeps annotation.PendingKeeps + boundsDiags := addBuiltPendingKeeps(loweringContext, placement, &scratchPendingKeeps, pointer, kept, reports) + boundsDiags = append(boundsDiags, settleOn(loweringContext, &scratch.Unmodeled, &scratchPendingKeeps, at)...) + findings := slices.Concat(boundsDiags, recordUnread(loweringContext, &scratch.Unmodeled, schema, unread, shape, pointer), + recordSkippedFamilies(loweringContext, scratch, &scratch.Unmodeled, schema, dispatchValue, pointer).Diagnostics()) + if placement.position == nil { + built, _, diags := hoistHolding(loweringContext, types, at, ir.TypeRef{Target: id}, scratch, findings) + return built, diags + } + // The alias names the position, which keeps on it what the + // principal's discriminator declares that reaches no field + // (principalDiscriminatorKeys), and whose findings remain where none does. + discriminatorKeys, discriminatorDiags := annotation.DiscriminatorKeys(schema, pointer, loweringContext.Place()) + if !nodeHolds(scratch) && len(discriminatorKeys) == 0 && !untaken { + // A bound beside the position no kind of the node takes is the + // alias's, as written flat, though its keeping comes after. + return builtPosition{id: id}, append(findings, discriminatorDiags.Diagnostics()...) + } + // Taking the place of an inline principal's position, the alias keeps what is + // unread once that position has written (keepAround), so the scratch only + // says whether it holds anything, and the alias holds its bounds alone. + built := internAliasHolding(loweringContext, types, cons, at, base) + if built.node == nil { + return built, nil } + keepingValue := keeping{keys: unread, reason: ir.ReasonDegradedLowering, shape: shape, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return recordUnread(loweringContext, unmodeled, schema, keys, shape, pointer) + }} + keptDiags := keepAround(loweringContext, placement, &built, schema, pointer, keepingValue) + boundsDiags = addBuiltPendingKeeps(loweringContext, placement, &built.pendingKeeps, pointer, kept, reports) + keeps := builtKeeps{pendingKeeps: &built.pendingKeeps, pointer: pointer, placement: placement} + skippedDiags := keeps.keep(loweringContext, &built.node.Common().Unmodeled, func(unmodeled *ir.Unmodeled) annotation.KeptReports { + return recordSkippedFamilies(loweringContext, built.node, unmodeled, schema, dispatchValue, pointer) + }) + return built, slices.Concat(boundsDiags, keptDiags, skippedDiags) } -// refSiteShape describes what a $ref position's own declaration lowers to, for -// the diagnostic recordUnread reports. -const refSiteShape = "an alias over its $ref target" - -// nodeShape describes a node of kind k, for that same diagnostic. +// nodeShape describes a node of the kind given, for that same diagnostic. func nodeShape(kind ir.TypeKind) string { return fmt.Sprintf("a node of kind %q", kind) } -// positionShape is nodeShape for the node td, the position's declaration schema -// lowered to. An Enum's ValueType is the home of its type and of any format the -// table pairs, so an enum that left one verbatim says its members are why: its -// kind alone would deny the home. So does a node that reads schema's -// discriminator and holds none (taglessShape): a Model, or a Union schema's -// oneOf or anyOf builds, as the Union an enum lowers to reads none, whatever -// its tag. -func positionShape(td ir.TypeDef, schema *statement.Schema) string { - if enum, ok := td.(*ir.Enum); ok { +// positionShape is nodeShape for the node typeDef, the position's declaration +// schema lowered to. An Enum's ValueType is the home of its type and of any +// format the table pairs, so an enum that left one verbatim says its members +// are why: its kind alone would deny the home. So does a node that reads +// schema's discriminator and holds none (taglessShape): a Model, or a Union +// schema's oneOf or anyOf builds, as the Union an enum lowers to reads none, +// whatever its tag. +func positionShape(typeDef ir.TypeDef, schema *statement.Schema) string { + if enum, ok := typeDef.(*ir.Enum); ok { if !membersTyped(enum.Members, schema) { return "an enum whose members are not all values of its declared type" } @@ -193,11 +244,11 @@ func positionShape(td ir.TypeDef, schema *statement.Schema) string { return fmt.Sprintf("an enum whose members are not all values of %s", primitive) } } - shape := nodeShape(td.Kind()) - if model, ok := td.(*ir.Model); ok { + shape := nodeShape(typeDef.Kind()) + if model, ok := typeDef.(*ir.Model); ok { return taglessShape(model, schema, shape) } - if isKind(td, ir.KindUnion) && declaresUnion(schema) { + if isKind(typeDef, ir.KindUnion) && declaresUnion(schema) { return taglessShape(nil, schema, shape) } return shape @@ -225,77 +276,83 @@ func taglessShape(model *ir.Model, schema *statement.Schema, shape string) strin // lowers to, for that same diagnostic. const distributedShape = "a union of models conjoining its body with each branch" -// keepUnreadAcross returns the keeping of the Union, in hand, that a position's -// own schema schema builds the variants of: a type array's (lowerUnion) and a -// distributed composition's (composedVariant). It keeps on the Union what -// schema writes that neither it nor a variant read, read being what they did, -// nor its lowering accounted for, handled, recording into kept, then finishes -// it by fin, as keepAround orders the two where the Union stands for st's -// position. A discriminator the Union holds is homed there, routing its +// keepUnreadAcross keeps on the Union built.node holds what schema writes that +// neither it nor a variant read (built.read), nor its lowering accounted for +// (handled). A discriminator the Union holds is homed there, routing its // variants. shape describes the Union. -func keepUnreadAcross(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, shape string, handled keySet, pointer jsontext.Pointer, - st stand, kept *finished, fin finisher, -) finisher { - return func(td ir.TypeDef, built keySet, held *principalKept) { - kept.ran = true - union, isUnion := td.(*ir.Union) - if !isUnion { - kept.diags = append(kept.diags, loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, - "internal: type %q is not the union its variants were built for", td.Common().ID)) - fin.run(td, built, held) - return - } - read := built | readElsewhere(schema) | handled - if union.Discriminator != nil { - read |= keyBit("discriminator") - } - keepingValue := keeping{keys: unreadKeys(schema, read), reason: ir.ReasonDegradedLowering, shape: shape, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { - return recordUnread(loweringContext, ts, unmodeled, schema, keys, shape, pointer) - }} - kept.diags = append(kept.diags, keepAround(loweringContext, ts, st, td, built, held, schema, pointer, keepingValue, fin)...) +func keepUnreadAcross(loweringContext lowering.Ctx, schema *statement.Schema, shape string, handled keySet, pointer jsontext.Pointer, + placement nodePlacement, built *builtPosition, +) []ir.Diagnostic { + union, isUnion := built.node.(*ir.Union) + if !isUnion { + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, + "internal: type %q is not the union its variants were built for", built.node.Common().ID)} } + read := built.read | readElsewhere(schema) | handled + if union.Discriminator != nil { + read |= keyBit("discriminator") + } + keepingValue := keeping{keys: unreadKeys(schema, read), reason: ir.ReasonDegradedLowering, shape: shape, keep: func(unmodeled *ir.Unmodeled, keys []string) []ir.Diagnostic { + return recordUnread(loweringContext, unmodeled, schema, keys, shape, pointer) + }} + return keepAround(loweringContext, placement, built, schema, pointer, keepingValue) } -// isKind reports whether td is a live node of kind typeKind. -func isKind(td ir.TypeDef, typeKind ir.TypeKind) bool { - return !ir.IsNilTypeDef(td) && td.Kind() == typeKind +// isKind reports whether typeDef is a live node of kind typeKind. +func isKind(typeDef ir.TypeDef, typeKind ir.TypeKind) bool { + return !ir.IsNilTypeDef(typeDef) && typeDef.Kind() == typeKind } -// recordUnread keeps each unhomed keyword verbatim in p and reports them once -// (keepUnreadKeys), saying what the position lowered to, its shape. -func recordUnread(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, schema *statement.Schema, unhomed []string, shape string, pointer jsontext.Pointer) []ir.Diagnostic { - kept, diags := keepUnreadKeys(loweringContext, ts, unmodeled, schema, unhomed, pointer) - if len(kept) == 0 { +// recordUnread keeps each unhomed keyword verbatim in unmodeled and reports +// them once (keepUnreadKeys), saying what the position lowered to, its shape, +// unless one report already names them: that of a bound cutting the read of +// schema's allOf (outcomeKeeps.reportCutRead), or the warning that no value +// satisfies schema (bottomAt, constEnumBottom, unionsFolded). +func recordUnread(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, unhomed []string, shape string, pointer jsontext.Pointer) []ir.Diagnostic { + kept, diags := keepUnreadKeys(loweringContext, unmodeled, schema, unhomed, pointer) + if unionsFolded(loweringContext, schema) { + // The warning that no value satisfies schema says it keeps them. + kept = slices.DeleteFunc(kept, isUnionKeyword) + } + if len(kept) == 0 || decisionOf(loweringContext, schema).refinement.cutBy != "" || bottomAt(loweringContext, schema) || constEnumOverlapOf(loweringContext, schema) == constEnumBottom { return diags } - return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, - "this position lowered to %s, which has no home for %s declared beside it; kept verbatim under Unmodeled", - shape, strings.Join(kept, ", "))) + if typeExcludesEnumMember(schema) && slices.Contains(kept, "enum") { + // The node is an Enum, but of the null the type decides over the enum. + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, + "the type null beside this enum decides over it, so this position is the null type, and the enum, "+ + "listing members that type excludes, is kept verbatim under Unmodeled")) + if kept = slices.DeleteFunc(kept, func(keyword string) bool { return keyword == "enum" }); len(kept) == 0 { + return diags + } + } + return append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, pointer, unreadReport, shape, strings.Join(kept, ", "))) } -// keepUnreadKeys keeps each unhomed keyword s, the schema at pointer, writes -// verbatim in p as degraded_lowering, reports a collection count no field states -// (keptCount) apart, as keepCounts reports a value count, and returns the rest -// it kept, for its caller to report once. +// unreadReport words the report of keywords a position keeps unread beside +// the shape it lowered to: the shape, then the keywords. +const unreadReport = "this position lowered to %s, which has no home for %s declared beside it; kept verbatim under Unmodeled" + +// keepUnreadKeys keeps each unhomed keyword schema, written at pointer, writes +// verbatim in unmodeled as degraded_lowering, reports a collection count no +// field states (keptCount) apart, as keptCounts reports a value count, and +// returns the rest it kept, for its caller to report once. // // It returns the keywords it stored, never the ones it was handed, so no report -// claims one that failed to convert (GitHub #144). A discriminator it is handed -// is no node's, so its mapping values are resolved here, as references -// (resolveDiscriminatorRoutes): every keeping of one comes through here. -func keepUnreadKeys(loweringContext lowering.Ctx, ts *compile.Types, unmodeled *ir.Unmodeled, schema *statement.Schema, unhomed []string, pointer jsontext.Pointer) ([]string, []ir.Diagnostic) { +// claims one that failed to convert (GitHub #144). A discriminator it keeps, or +// one within a keyword it keeps, is kept whole as it is kept +// (keepSchemaKeyword). +func keepUnreadKeys(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, unhomed []string, pointer jsontext.Pointer) ([]string, []ir.Diagnostic) { var diags []ir.Diagnostic kept := make([]string, 0, len(unhomed)) for _, keyword := range unhomed { - ok, keptDiags := preserveSchemaKeyword(loweringContext, unmodeled, schema, keyword, + ok, keptDiags := keepSchemaKeyword(loweringContext, unmodeled, schema, keyword, ir.ReasonDegradedLowering, pointer) diags = append(diags, keptDiags...) if ok { kept = append(kept, keyword) } } - if slices.Contains(kept, "discriminator") { - diags = append(diags, resolveDiscriminatorRoutes(loweringContext, ts, schema, pointer)...) - } counts := slices.DeleteFunc(slices.Clone(kept), func(keyword string) bool { return keyword != "maxItems" && keyword != "minItems" || !keptCount(schema, keyword, countOf(schema, keyword)) }) diff --git a/compilers/openapi/internal/schema/unread_internal_test.go b/compilers/openapi/internal/schema/unread_internal_test.go index 19c262ccb..6c8cbed71 100644 --- a/compilers/openapi/internal/schema/unread_internal_test.go +++ b/compilers/openapi/internal/schema/unread_internal_test.go @@ -18,8 +18,7 @@ import ( func TestKeepUnreadAcross_NeedsAUnion(t *testing.T) { t.Parallel() lowerer := NewRawLowerer(&soa.OpenAPI{}) - var kept finished - keep := keepUnreadAcross(lowerer.Ctx, lowerer.Types, StandaloneSchema(&oas3.Schema{}), distributedShape, 0, "/p", stand{}, &kept, nil) - keep(&ir.Scalar{ID: "type/anonymous/scalar"}, 0, nil) - assertInternalInvariant(t, kept.diags) + built := builtPosition{node: &ir.Scalar{ID: "type/anonymous/scalar"}, id: "type/anonymous/scalar"} + diags := keepUnreadAcross(lowerer.Ctx, StandaloneSchema(&oas3.Schema{}), distributedShape, 0, "/p", nodePlacement{}, &built) + assertInternalInvariant(t, diags) } diff --git a/compilers/openapi/internal/schema/unread_test.go b/compilers/openapi/internal/schema/unread_test.go index f6e3dc332..ba534491b 100644 --- a/compilers/openapi/internal/schema/unread_test.go +++ b/compilers/openapi/internal/schema/unread_test.go @@ -31,9 +31,9 @@ func TestUnhomedApplicator_KeptOnAListAndAnnounced(t *testing.T) { `)) openapitest.RequireNoErrorDiags(t, diags) - td := typeByName(doc, "Odd") - require.NotNil(t, td, "the array still lowers") - assert.Contains(t, td.Common().Unmodeled, "openapi:properties", + typeDef := typeByName(doc, "Odd") + require.NotNil(t, typeDef, "the array still lowers") + assert.Contains(t, typeDef.Common().Unmodeled, "openapi:properties", "a list has no home for properties, so it is kept") assert.True(t, openapitest.HasDiagAt(diags, diag.DegradedConstruct, ir.SeverityInfo), "and the position says which keywords it could not carry") @@ -77,25 +77,22 @@ func TestUnhomedApplicator_ObjectCarriesNoItemKeyword(t *testing.T) { assert.Len(t, model.Properties, 1, "and the applicators it does have a home for still land") } -// TestUnhomedApplicator_UnpreservableKeywordIsNotAnnounced pins the pairing -// GitHub #144 exists for, at this site: when the only unhomed keyword fails to -// convert, the position must say nothing about keeping it. A diagnostic naming a -// keyword that was never written is worse than silence — it sends a reader -// looking in Unmodeled for something that is not there. -func TestUnhomedApplicator_UnpreservableKeywordIsNotAnnounced(t *testing.T) { +// TestUnhomedApplicator_AKeptKeywordDropsAnExtensionNoJSONHolds pins an unhomed +// keyword whose value writes an extension that converts to no JSON: the keyword +// is kept and reported as without the extension, which alone is dropped, with +// its own warning where it is written, and a valid document draws no error. +func TestUnhomedApplicator_AKeptKeywordDropsAnExtensionNoJSONHolds(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(` Odd: + doc := requireKeptWithoutExtension(t, schema.LowerSpec, openapitest.ComponentSpec(` Odd: type: object properties: {p: {type: string}} - items: {type: string, x-t: `+unpreservableValue+`} -`)) + items: {type: string`+unconvertibleExtension+`} +`), unconvertibleExtension, "/components/schemas/Odd/items") model, ok := typeByName(doc, "Odd").(*ir.Model) require.True(t, ok) - assert.NotContains(t, model.Unmodeled, "openapi:items", "the conversion failed, so nothing was kept") - assert.True(t, openapitest.HasDiag(diags, diag.UnpreservableConstruct), "the failure itself is reported") - assert.Empty(t, openapitest.PreservationClaims(diags), - "nothing was written under Unmodeled, so nothing may announce that it was") + require.Contains(t, model.Unmodeled, "openapi:items", "the keyword is kept") + assert.JSONEq(t, `{"type":"string"}`, string(model.Unmodeled["openapi:items"].Value)) } // TestUnhomedApplicator_FormatWithNoTypeIsKept pins the one keyword the home @@ -111,9 +108,9 @@ func TestUnhomedApplicator_FormatWithNoTypeIsKept(t *testing.T) { doc, diags := schema.LowerSpec(t, openapitest.ComponentSpec(" Odd: {format: date-time}\n")) openapitest.RequireNoErrorDiags(t, diags) - td := typeByName(doc, "Odd") - require.NotNil(t, td, "the position still lowers to something") - assert.Contains(t, td.Common().Unmodeled, "openapi:format", + typeDef := typeByName(doc, "Odd") + require.NotNil(t, typeDef, "the position still lowers to something") + assert.Contains(t, typeDef.Common().Unmodeled, "openapi:format", "a format with no type to pair with reaches no field, so it is kept") assert.True(t, openapitest.HasDiag(diags, diag.DegradedConstruct), "and the position says so") } @@ -130,15 +127,15 @@ func TestUnhomedApplicator_FormatWithNoTypeIsKept(t *testing.T) { // Model restates it and nothing may be recorded. func TestUnhomedKeywords_PickedLoweringKeepsWhatItCannotRead(t *testing.T) { t.Parallel() - for _, tc := range []struct { + for _, testCase := range []struct { name, body string kind ir.TypeKind kept []string }{ - // The conjuncts share only null, so no report names them and the allOf - // composes, as one sharing no value does. - {"non-object type beside allOf", "{allOf: [{type: object, nullable: true, required: [a]}], type: string, nullable: true}", - ir.KindModel, []string{"openapi:type"}}, + // The conjuncts share only null, so the position is the null type, as + // `{type: 'null'}` is, which homes no required. + {"non-object type beside allOf", "{allOf: [{type: object, nullable: true}], type: string, nullable: true, required: [a]}", + ir.KindEnum, []string{"openapi:required"}}, {"object type beside allOf", "{allOf: [{$ref: '#/components/schemas/BaseObj'}], type: object}", ir.KindModel, nil}, // The value fits the type and format, so the literal's ValueType holds both. @@ -166,18 +163,18 @@ func TestUnhomedKeywords_PickedLoweringKeepsWhatItCannotRead(t *testing.T) { {"collection bounds on an array", "{type: array, items: {type: string}, minItems: 3, maxItems: 9, uniqueItems: true}", ir.KindList, nil}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, unreadKeywordSpec(" S: "+tc.body+"\n")) + doc, diags := schema.LowerSpec(t, unreadKeywordSpec(" S: "+testCase.body+"\n")) openapitest.RequireNoErrorDiags(t, diags) - td := typeByName(doc, "S") - require.NotNil(t, td, "the position still lowers") - assert.Equal(t, tc.kind, td.Kind(), "and lowers to the form the election picked") - assert.Equal(t, tc.kept, unmodeledKeys(td.Common().Unmodeled)) + typeDef := typeByName(doc, "S") + require.NotNil(t, typeDef, "the position still lowers") + assert.Equal(t, testCase.kind, typeDef.Kind(), "and lowers to the form the choice picked") + assert.Equal(t, testCase.kept, unmodeledKeys(typeDef.Common().Unmodeled)) want := 1 - if len(tc.kept) == 0 { + if len(testCase.kept) == 0 { want = 0 } assert.Len(t, diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/S"), want, @@ -193,18 +190,18 @@ func TestUnhomedKeywords_PickedLoweringKeepsWhatItCannotRead(t *testing.T) { // the field would double-record both. func TestUnhomedKeywords_BoundsThatLandedAreNotAlsoKept(t *testing.T) { t.Parallel() - for _, tc := range []struct{ name, body, unhomed string }{ + for _, testCase := range []struct{ name, body, unhomed string }{ {"scalar", "{type: string, format: email, minLength: 3, required: [a]}", "openapi:required"}, {"model", "{type: object, properties: {a: {type: string}}, minProperties: 1, items: {type: string}}", "openapi:items"}, } { - t.Run(tc.name, func(t *testing.T) { + t.Run(testCase.name, func(t *testing.T) { t.Parallel() - doc, diags := schema.LowerSpec(t, unreadKeywordSpec(" S: "+tc.body+"\n")) + doc, diags := schema.LowerSpec(t, unreadKeywordSpec(" S: "+testCase.body+"\n")) openapitest.RequireNoErrorDiags(t, diags) - td := typeByName(doc, "S") - require.NotNil(t, td) - assert.Equal(t, []string{tc.unhomed}, unmodeledKeys(td.Common().Unmodeled), + typeDef := typeByName(doc, "S") + require.NotNil(t, typeDef) + assert.Equal(t, []string{testCase.unhomed}, unmodeledKeys(typeDef.Common().Unmodeled), "the bound reached the node's Constraints, so only the homeless keyword is kept") }) } @@ -267,7 +264,8 @@ func TestUnplacedDiscriminator_IsKeptAtEveryUnionSite(t *testing.T) { // keeps any keyword the node has no field for. Each was dropped in silence. // Beside a $ref to an object the discriminator is the composition's, so a // Model over the target holds it, at a component, a property and a parameter -// alike, and on an entry it is kept with the entry, as on any inline entry. +// alike, and on an allOf entry beside its $ref, which is the model's as any +// inline entry's is (GitHub #2052). func TestHomelessDiscriminator_IsKeptBesideEveryOtherNode(t *testing.T) { t.Parallel() doc, diags := parseFull(t, homelessSpec) @@ -293,7 +291,7 @@ func TestHomelessDiscriminator_IsKeptBesideEveryOtherNode(t *testing.T) { require.True(t, ok) operation := doc.Services[0].Groups[0].Operations[0] require.Len(t, operation.Params, 1) - for _, id := range []ir.TypeID{componentID("RefD"), holder.Properties[0].Type.Target, operation.Params[0].Type.Target} { + for _, id := range []ir.TypeID{componentID("RefD"), componentID("Sub"), holder.Properties[0].Type.Target, operation.Params[0].Type.Target} { model, isModel := doc.Types[id].(*ir.Model) require.True(t, isModel, "%s is the model over the object", id) require.NotNil(t, model.Discriminator, id) @@ -301,14 +299,8 @@ func TestHomelessDiscriminator_IsKeptBesideEveryOtherNode(t *testing.T) { require.NotNil(t, model.Base, id) assert.Equal(t, componentID("Cat"), model.Base.Target, id) } - // A discriminator an entry writes beside its $ref is kept on the - // composition under its own key, as on an entry of its own. - sub, ok := typeByName(doc, "Sub").(*ir.Model) - require.True(t, ok) - assertKeptDiscriminator(t, sub.Unmodeled, "/components/schemas/Sub/allOf/0") - marshaled := marshalForTest(t, doc) - assert.Equal(t, len(owners)+1, strings.Count(marshaled, `"openapi:discriminator"`)+ + assert.Equal(t, len(owners), strings.Count(marshaled, `"openapi:discriminator"`)+ strings.Count(marshaled, `"openapi:schema/discriminator"`), "one entry per position, none duplicated") } @@ -532,3 +524,101 @@ func namesDiscriminatorAt(diags []ir.Diagnostic, pointer string) bool { string(diagnostic.Provenance.Pointer) == pointer && strings.Contains(diagnostic.Message, "discriminator") }) } + +// TestKeepUnreadShared_RevisitedParameterHoistsAndReportsOnce pins that a +// shared-primitive schema carrying an unread keyword (items beside string) +// hoists its alias and reports the kept keyword once even when two operations +// visit the same component parameter. +func TestKeepUnreadShared_RevisitedParameterHoistsAndReportsOnce(t *testing.T) { + t.Parallel() + spec := `openapi: 3.1.0 +info: {title: t, version: "1"} +paths: + /a: + get: + operationId: getA + parameters: [{$ref: '#/components/parameters/P'}] + responses: {'200': {description: ok}} + /b: + get: + operationId: getB + parameters: [{$ref: '#/components/parameters/P'}] + responses: {'200': {description: ok}} +components: + parameters: + P: + name: p + in: query + schema: + type: string + items: {type: integer} +` + doc, diags := parseFull(t, spec) + openapitest.RequireNoErrorDiags(t, diags) + assert.Empty(t, validated(t, doc)) + + const id = ir.TypeID("type/anonymous/components/parameters/P/schema") + alias, ok := doc.Types[id].(*ir.Scalar) + require.True(t, ok, "revisited shared-primitive schema with unread items hoists one alias") + require.NotNil(t, alias.Base) + assert.Equal(t, ir.PrimitiveTypeID(ir.PrimitiveString), alias.Base.Target) + assert.Contains(t, alias.Unmodeled, "openapi:items") + assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityInfo), + "unread keyword is reported once across both visits: %+v", diags) +} + +// TestParameterReusedAcrossOperations_FoldsCollectionBounds pins that a +// component parameter whose allOf refines an array with folded collection +// bounds and docs lowers to one list holding the folded bounds and docs when +// visited by two operations, with nothing unmodeled and no diagnostics. +func TestParameterReusedAcrossOperations_FoldsCollectionBounds(t *testing.T) { + t.Parallel() + spec := `openapi: 3.1.0 +info: {title: t, version: "1"} +paths: + /a: + get: + parameters: [{$ref: '#/components/parameters/P'}] + responses: {'200': {description: ok}} + /b: + get: + parameters: [{$ref: '#/components/parameters/P'}] + responses: {'200': {description: ok}} +components: + parameters: + P: + name: p + in: query + schema: {allOf: [{type: array, items: {type: string}}, {minItems: 1, description: d}, {maxItems: 3, title: t}]} +` + doc, diags := parseFull(t, spec) + assert.Empty(t, diags) + assert.Empty(t, validated(t, doc)) + + const id = ir.TypeID("type/anonymous/components/parameters/P/schema") + list, ok := doc.Types[id].(*ir.List) + require.True(t, ok, "reused component parameter lowers to one list") + require.NotNil(t, list.Constraints) + assert.Equal(t, new(int64(1)), list.Constraints.MinItems) + assert.Equal(t, new(int64(3)), list.Constraints.MaxItems) + assert.False(t, list.Constraints.UniqueItems) + assert.Equal(t, "t", list.Docs.Summary) + assert.Equal(t, "d", list.Docs.Description) + assert.Empty(t, list.Unmodeled) +} + +// TestUnhomedKeywords_AKeptFormatIsReportedOnTheScalarItSettlesOn holds an +// empty format beside a string, which no primitive holds: it is kept on the +// Scalar aliasing the string, and its report names that Scalar, the node it +// settled on, not the primitive the type alone would reach. +func TestUnhomedKeywords_AKeptFormatIsReportedOnTheScalarItSettlesOn(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, unreadKeywordSpec(" S: {type: string, format: \"\"}\n")) + openapitest.RequireNoErrorDiags(t, diags) + scalar, ok := typeByName(doc, "S").(*ir.Scalar) + require.True(t, ok, "got %T", typeByName(doc, "S")) + assert.Equal(t, []string{"openapi:format"}, unmodeledKeys(scalar.Unmodeled)) + reports := diagsAtPointer(diags, diag.DegradedConstruct, "/components/schemas/S") + require.Len(t, reports, 1) + assert.Contains(t, reports[0].Message, `a node of kind "scalar"`) +} diff --git a/compilers/openapi/internal/schema/use.go b/compilers/openapi/internal/schema/use.go index da65e079e..1eccffb92 100644 --- a/compilers/openapi/internal/schema/use.go +++ b/compilers/openapi/internal/schema/use.go @@ -31,7 +31,7 @@ const maxFallbackReferenceHops = 64 // Use is what speaks for one position beside the schema written there: the // entries of its allOf read as written beside it, then what it falls back to. type Use struct { - FoldedAllOfEntries []annotation.FoldedAllOfEntry + FlattenedAllOfEntries []annotation.FlattenedAllOfEntry // Referents is what the position falls back to, nearest first // (docs/compilers/openapi.md#ref-use-site). Referents []*statement.Schema @@ -40,10 +40,10 @@ type Use struct { // together. places []referentPlace // narrowed is what the position admits where a referent may say more, and nil - // where every referent's default stands. + // where every referent's default is taken. narrowed *admitted // narrowedFrom is the first of Referents past the value set narrowing the - // position: one before it writes that set or stands beside it, so its default + // position: one before it writes that set or sits beside it, so its default // is the position's own, as a plain enum's is. narrowedFrom int // nullable says the position's reference admits null, whatever narrowed says. @@ -58,7 +58,7 @@ type Use struct { // position. A position that lost its $ref still reads it, so a Site here is a // reference site whatever schema writes. func (u Use) Site(schema *statement.Schema) annotation.SchemaPositionAnnotationSources { - return annotation.SchemaPositionAnnotationSources{Kind: annotation.Reference, Node: schema, FoldedAllOfEntries: u.FoldedAllOfEntries, Referents: u.Referents} + return annotation.SchemaPositionAnnotationSources{Kind: annotation.Reference, Node: schema, FlattenedAllOfEntries: u.FlattenedAllOfEntries, Referents: u.Referents} } // SiteAt is Site for schema written at pointer, saying what the dialect schema @@ -115,17 +115,17 @@ func (u Use) Default(loweringContext lowering.Ctx, schema *statement.Schema, poi } // defaultAt places the default the schema at index i of u.Site's chain writes, -// for the carrier at pointer: the site's own, a folded entry's, or a +// for the carrier at pointer: the site's own, a flattened entry's, or a // referent's where it is written, in whichever document. A referent the // bindings place nowhere is reported at the carrier, which reads it. func (u Use) defaultAt(loweringContext lowering.Ctx, i int, pointer jsontext.Pointer) ir.Provenance { switch v := i - 1; { case i == 0: return loweringContext.Place().At(pointer.AppendToken("default")) - case v < len(u.FoldedAllOfEntries): - return loweringContext.Place().At(u.FoldedAllOfEntries[v].At.AppendToken("default")) + case v < len(u.FlattenedAllOfEntries): + return loweringContext.Place().At(u.FlattenedAllOfEntries[v].At.AppendToken("default")) } - r := i - 1 - len(u.FoldedAllOfEntries) + r := i - 1 - len(u.FlattenedAllOfEntries) if r >= len(u.places) || !u.places[r].known { return loweringContext.Place().At(pointer) } @@ -189,7 +189,7 @@ type readThroughAllOfReference struct { // ref is nil for a refinement writing no $ref. ref *statement.Statement // lost marks a ref the position does not lower to, so no Base reaches it. - lost bool + passedOver bool // narrows reports that the schema admits less than ref admits, so admits // is read. narrows bool @@ -199,10 +199,10 @@ type readThroughAllOfReference struct { // pointer, and false for a schema a use does not read past. func readThroughAllOfReferenceOf(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer) (readThroughAllOfReference, bool) { if refinement, refined := refinementOf(loweringContext, schema, pointer); refined { - readThroughAllOfReferenceValue := readThroughAllOfReference{admits: refinement.joint} + readThroughAllOfReferenceValue := readThroughAllOfReference{admits: refinement.admittedTogether} if refinement.ref != nil { - readThroughAllOfReferenceValue.ref, readThroughAllOfReferenceValue.lost = refinement.ref.schema, !refinement.principalIs(*refinement.ref) - readThroughAllOfReferenceValue.narrows = readThroughAllOfReferenceValue.lost || refinement.held.narrowedTo(refinement.joint) + readThroughAllOfReferenceValue.ref, readThroughAllOfReferenceValue.passedOver = refinement.ref.schema, !refinement.principalIs(*refinement.ref) + readThroughAllOfReferenceValue.narrows = readThroughAllOfReferenceValue.passedOver || refinement.loweredAdmits.narrowedTo(refinement.admittedTogether) } return readThroughAllOfReferenceValue, true } @@ -212,7 +212,7 @@ func readThroughAllOfReferenceOf(loweringContext lowering.Ctx, schema *statement } if slices.Contains(dispatchOf(schema).skipped, "allOf") { admissionReader := newAdmissionReader(loweringContext) - return readThroughAllOfReference{ref: ref, lost: true, admits: admissionReader.written(schema, admissionReader.nullable), narrows: true}, true + return readThroughAllOfReference{ref: ref, passedOver: true, admits: admissionReader.written(schema, admissionReader.nullable), narrows: true}, true } return readThroughAllOfReference{ref: ref}, true } @@ -223,7 +223,7 @@ func readThroughAllOfReferenceOf(loweringContext lowering.Ctx, schema *statement // beside nothing an object holds (decoratesOnly). A union beside a composing // allOf is distributed across it or kept beside it, so that allOf lends // nothing. It reads the source and its bindings alone, since a chain asks it of -// every link. +// every hop. func throughRef(loweringContext lowering.Ctx, schema *statement.Schema) *statement.Statement { refs := slices.Collect(allOfRefEntries(loweringContext, schema)) if slices.Contains(dispatchOf(schema).skipped, "allOf") { @@ -232,10 +232,14 @@ func throughRef(loweringContext lowering.Ctx, schema *statement.Schema) *stateme } return refs[0] } - if decision := decisionOf(loweringContext, schema); decision.refines { - return entryStatement(loweringContext, schema, decision.refAt) + if decision := decisionOf(loweringContext, schema); decision.refines() { + i, readsThrough := namedEntry(decision.ref()) + if !readsThrough { + return nil + } + return loweringContext.Statements().Read(loweringContext.Statements().Read(schema).Entries[i].Schema) } - if len(refs) != 1 || !allOfMayRefine(schema) || declaresUnion(schema) || !decoratesOnly(loweringContext, schema) { + if len(refs) != 1 || !writesConjuncts(schema) || declaresUnion(schema) || !decoratesOnly(loweringContext, schema) { return nil } return refs[0] @@ -255,38 +259,30 @@ func decoratesOnly(loweringContext lowering.Ctx, schema *statement.Schema) bool }) } -// referenceReferentsNearestFirst returns what p's $ref says of a use, nearest -// first, as a Use's referents: what is written beside it, then what it lands on -// lends. -func (p readThroughAllOfReference) referenceReferentsNearestFirst(loweringContext lowering.Ctx) Use { +// referenceReferentsNearestFirst returns what read's $ref says of a use, +// nearest first, as a Use's referents: what is written beside it, then what it +// lands on lends. +func (read readThroughAllOfReference) referenceReferentsNearestFirst(loweringContext lowering.Ctx) Use { var use Use - use.appendFallbackReferent(p.ref.Schema, placeOf(loweringContext, p.ref)) - use.appendFallbackReferents(fallbackAnnotationsOf(loweringContext, declared(loweringContext, p.ref))) + use.appendFallbackReferent(read.ref.Schema, placeOf(loweringContext, read.ref)) + use.appendFallbackReferents(fallbackAnnotationsOf(loweringContext, declared(loweringContext, read.ref))) return use } -// UseOf reads what speaks for a carrier holding js at pointer, which lowered to -// t (readUse), its voices marked where the outcome keeps their entry whole -// (markKeptWhole). -func UseOf(loweringContext lowering.Ctx, js *statement.Statement, typeRef ir.TypeRef, pointer jsontext.Pointer) Use { - use := readUse(loweringContext, js, typeRef, pointer) - use.FoldedAllOfEntries = markKeptWhole(loweringContext, js.Schema, pointer, typeRef, use.FoldedAllOfEntries) - return use -} - -// readUse reads what speaks for a carrier holding js at pointer, which lowered -// to typeRef: what a $ref names, or what readThroughAllOfReferenceOf reads on -// through, an inline principal speaking as a folded entry, as its node stands -// at the position. A composition throughRef reads no $ref through lends -// nothing: its Model holds what it composes as Base and Mixins. -func readUse(loweringContext lowering.Ctx, js *statement.Statement, typeRef ir.TypeRef, pointer jsontext.Pointer) Use { - if js.Ref != nil { - use := fallbackAnnotationsOf(loweringContext, declared(loweringContext, js)) +// UseOf reads what speaks for a carrier holding schemaStatement at pointer, +// which lowered to typeRef: what a $ref names, or what +// readThroughAllOfReferenceOf reads on through, an inline principal speaking as +// a flattened entry, as its node sits at the position. A composition throughRef +// reads no $ref through lends nothing: its Model holds what it composes as Base +// and Mixins. +func UseOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement, typeRef ir.TypeRef, pointer jsontext.Pointer) Use { + if schemaStatement.Ref != nil { + use := fallbackAnnotationsOf(loweringContext, declared(loweringContext, schemaStatement)) use.nullable = typeRef.Nullable return use } - useValue := Use{FoldedAllOfEntries: positionFoldedEntries(loweringContext, js.Schema, pointer, typeRef), nullable: typeRef.Nullable} - readThroughAllOfReference, ok := readThroughAllOfReferenceOf(loweringContext, js.Schema, pointer) + useValue := Use{FlattenedAllOfEntries: positionFlattenedEntries(loweringContext, schemaStatement.Schema, pointer, typeRef), nullable: typeRef.Nullable} + readThroughAllOfReference, ok := readThroughAllOfReferenceOf(loweringContext, schemaStatement.Schema, pointer) if !ok { return useValue } @@ -307,11 +303,11 @@ func readUse(loweringContext lowering.Ctx, js *statement.Statement, typeRef ir.T // whether a keyword or a key along it deprecates the node, which the node's own // member keys then annotate (promotion.Referent.Homes). func nodeUse(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef) Use { - use := Use{FoldedAllOfEntries: markKeptWhole(loweringContext, schema, pointer, target, positionFoldedEntries(loweringContext, schema, pointer, target))} + use := Use{FlattenedAllOfEntries: positionFlattenedEntries(loweringContext, schema, pointer, target)} readThroughAllOfReference, ok := readThroughAllOfReferenceOf(loweringContext, schema, pointer) switch { case !ok: - case readThroughAllOfReference.lost: + case readThroughAllOfReference.passedOver: use.appendFallbackReferents(readThroughAllOfReference.referenceReferentsNearestFirst(loweringContext)) case readThroughAllOfReference.ref != nil: use.deprecatedBase = slices.ContainsFunc(readThroughAllOfReference.referenceReferentsNearestFirst(loweringContext).Referents, func(statementSchema *statement.Schema) bool { @@ -326,24 +322,24 @@ type fallbackReadKey struct { schema *statement.Schema } -// fallbackAnnotationsOf reads what js, the schema a $ref lands on, lends a use -// of it, nearest first: each hop of the chain of $refs from js that writes more -// than its $ref, the schema the chain ends on, the entries of its allOf that -// fold (lendingEntries), and past a refinement, a decorator or a narrowing enum -// whatever its own $ref lends in turn. Only that end is read for what it -// admits, so the narrowing starts past its entries. Every $ref landing on js -// asks, so it is read once a run. -func fallbackAnnotationsOf(loweringContext lowering.Ctx, js *statement.Statement) Use { - return lowering.ReadOncePerRun(loweringContext, fallbackReadKey{js.Schema}, func() Use { return readLent(loweringContext, js) }) +// fallbackAnnotationsOf reads what schemaStatement, the schema a $ref lands on, +// lends a use of it, nearest first: each hop of the chain of $refs from +// schemaStatement that writes more than its $ref, the schema the chain ends on, +// the entries of its allOf that fold (lendingEntries), and past a refinement, a +// decorator or a narrowing enum whatever its own $ref lends in turn. Only that +// end is read for what it admits, so the narrowing starts past its entries. +// Every $ref landing on schemaStatement asks, so it is read once a run. +func fallbackAnnotationsOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) Use { + return lowering.ReadOncePerRun(loweringContext, fallbackReadKey{schemaStatement.Schema}, func() Use { return readLent(loweringContext, schemaStatement) }) } // readLent reads what fallbackAnnotationsOf remembers. A run of aliases is read // within one turn, so only the read-throughs throughRef reads spend // maxFallbackReferenceHops. -func readLent(loweringContext lowering.Ctx, js *statement.Statement) Use { +func readLent(loweringContext lowering.Ctx, schemaStatement *statement.Statement) Use { var use Use for turn := range maxFallbackReferenceHops { - schema, ok := use.appendFallbackChainRun(loweringContext, js) + schema, ok := use.appendFallbackChainRun(loweringContext, schemaStatement) if !ok { break } @@ -355,47 +351,40 @@ func readLent(loweringContext lowering.Ctx, js *statement.Statement) Use { break } use.appendFallbackReferent(through.Schema, placeOf(loweringContext, through)) - js = declared(loweringContext, through) + schemaStatement = declared(loweringContext, through) } return use } // appendFallbackChainRun appends to u.Referents each alias of the run of $refs -// js starts that writes more than its $ref, then the schema the run ends on and -// its lending entries, and returns that schema. It is false, the run lending -// nothing past what it appended, where the run ends on no schema, as a chain -// that loops or fails does. The table's count of the chain's hops bounds the -// run. -func (u *Use) appendFallbackChainRun(loweringContext lowering.Ctx, js *statement.Statement) (*statement.Schema, bool) { - var referenceSite reftable.ReferenceSite - if js.Ref != nil && js.Ref.Bound { - referenceSite = js.Ref.Entry - if referenceSite.Chain.Status != reftable.Resolved { - return nil, false - } +// schemaStatement starts that writes more than its $ref, then the schema the +// run ends on and its lending entries, and returns that schema. It is false, +// the run lending nothing past what it appended, where the run ends on no +// schema, as a chain that loops or fails does. +func (u *Use) appendFallbackChainRun(loweringContext lowering.Ctx, schemaStatement *statement.Statement) (*statement.Schema, bool) { + if ref := schemaStatement.Ref; ref != nil && ref.Bound && ref.Entry.Chain.Status != reftable.Resolved { + return nil, false } - for range referenceSite.Chain.Hops + 1 { - if js.Truth != statement.Stated { - return nil, false + for step := range refChain(loweringContext, schemaStatement) { + written := step.statement + if written == nil || written.Truth != statement.Stated { + break } - at := placeOf(loweringContext, js) - if js.Ref == nil { - u.appendFallbackReferent(js.Schema, at) - u.lendEntries(loweringContext, js.Schema, at) - return js.Schema, true + if written.Ref == nil || writesMoreThanRef(written.Schema) { + at := placeOf(loweringContext, written) + u.appendFallbackReferent(written.Schema, at) + u.lendEntries(loweringContext, written.Schema, at) } - if writesMoreThanRef(js.Schema) { - u.appendFallbackReferent(js.Schema, at) - u.lendEntries(loweringContext, js.Schema, at) + if written.Ref == nil { + return written.Schema, true } - js = declared(loweringContext, js) } return nil, false } // narrowTo has u admit what schema admits where schema, the end of the first // run of a chain, narrows what its own $ref admits: past it, a referent's -// default stands only where schema admits it. +// default is taken only where schema admits it. func (u *Use) narrowTo(loweringContext lowering.Ctx, schema *statement.Schema) { if readThroughAllOfReference, ok := readThroughAllOfReferenceOf(loweringContext, schema, ""); ok && readThroughAllOfReference.narrows { u.narrowed, u.narrowedFrom = &readThroughAllOfReference.admits, len(u.Referents) @@ -403,8 +392,8 @@ func (u *Use) narrowTo(loweringContext lowering.Ctx, schema *statement.Schema) { } // appendFallbackReferent appends schema, written at, to what u falls back to. -// It and appendFallbackReferents are the only writers of Referents and places, -// which keep each referent's place at its index. +// It and appendFallbackReferents are the only conjuncts of Referents and +// places, which keep each referent's place at its index. func (u *Use) appendFallbackReferent(schema *statement.Schema, at referentPlace) { u.Referents = append(u.Referents, schema) u.places = append(u.places, at) @@ -420,8 +409,8 @@ func (u *Use) appendFallbackReferents(from Use) { // lendEntries appends the lending entries of s, written at, each placed // beneath it. func (u *Use) lendEntries(loweringContext lowering.Ctx, schema *statement.Schema, at referentPlace) { - for _, b := range lendingEntries(loweringContext, schema) { - u.appendFallbackReferent(b.schema.Schema, at.beneath(b.pointer)) + for _, entry := range lendingEntries(loweringContext, schema) { + u.appendFallbackReferent(entry.schema.Schema, at.beneath(entry.pointer)) } } @@ -440,19 +429,19 @@ type referentPlace struct { known bool } -// placeOf returns where the bindings read js, unknown for a schema they do not -// know or a document the compile did not read. -func placeOf(loweringContext lowering.Ctx, js *statement.Statement) referentPlace { - documentPointer, known := siteOf(js.Schema) +// placeOf returns where the bindings read schemaStatement, unknown for a schema +// they do not know or a document the compile did not read. +func placeOf(loweringContext lowering.Ctx, schemaStatement *statement.Statement) referentPlace { + documentPointer, known := siteOf(schemaStatement.Schema) in, read := lowering.InDocument(loweringContext, documentPointer.Doc) return referentPlace{doc: in.Place(), pointer: documentPointer.Pointer, known: known && read} } -// beneath returns the place of what is written at below, relative to p, and -// unknown where p is. -func (p referentPlace) beneath(below jsontext.Pointer) referentPlace { - p.pointer += below - return p +// beneath returns the place of what is written at below, relative to referent, +// and unknown where referent is. +func (referent referentPlace) beneath(below jsontext.Pointer) referentPlace { + referent.pointer += below + return referent } // DecidingSchema returns the schema deciding what s lowers to, s itself or, past @@ -461,10 +450,12 @@ func (p referentPlace) beneath(below jsontext.Pointer) referentPlace { func DecidingSchema(loweringContext lowering.Ctx, schema *statement.Schema) *statement.Schema { for range maxFallbackReferenceHops { decision := decisionOf(loweringContext, schema) - if !decision.refines || decision.principalAt < 0 { + i, principalIsEntry := namedEntry(decision.principal()) + if !decision.refines() || !principalIsEntry { + // A principal the keywords beside the allOf are is schema's own. break } - principal := entryStatement(loweringContext, schema, decision.principalAt) + principal := loweringContext.Statements().Read(loweringContext.Statements().Read(schema).Entries[i].Schema) schema = principal.Schema if principal.Ref != nil { schema = refBranchTarget(loweringContext, principal) diff --git a/compilers/openapi/internal/schema/use_chain_test.go b/compilers/openapi/internal/schema/use_chain_test.go index 897dcb82f..02a57b86b 100644 --- a/compilers/openapi/internal/schema/use_chain_test.go +++ b/compilers/openapi/internal/schema/use_chain_test.go @@ -121,19 +121,19 @@ components: // aliasChain returns n aliases, A0 to A(n-1), each naming the next, and the // schema An they end on, which writes a default and a description. A hop at -// index writer, where there is one, writes a description beside its $ref too. -func aliasChain(n, writer int) string { - var b strings.Builder +// index conjunct, where there is one, writes a description beside its $ref too. +func aliasChain(n, writingAt int) string { + var builder strings.Builder for i := range n { - fmt.Fprintf(&b, " A%d: {$ref: '#/components/schemas/A%d'", i, i+1) - if i == writer { - b.WriteString(", description: from-alias") + fmt.Fprintf(&builder, " A%d: {$ref: '#/components/schemas/A%d'", i, i+1) + if i == writingAt { + builder.WriteString(", description: from-alias") } - b.WriteString("}\n") + builder.WriteString("}\n") } - fmt.Fprintf(&b, " A%d: {type: string, default: deep, description: from-end}\n", n) - b.WriteString(" Holder: {type: object, properties: {p: {$ref: '#/components/schemas/A0'}}}\n") - return b.String() + fmt.Fprintf(&builder, " A%d: {type: string, default: deep, description: from-end}\n", n) + builder.WriteString(" Holder: {type: object, properties: {p: {$ref: '#/components/schemas/A0'}}}\n") + return builder.String() } // TestUseOf_AnAliasHopIsNoReadThrough pins that a run of aliases is read within @@ -204,37 +204,37 @@ func TestUseOf_AnAliasHopIsNoReadThroughAcrossTwoDocuments(t *testing.T) { } // readThroughChainSpec returns n schemas that each narrow the next by an enum -// written beside an allOf naming it, so a use passes over one $ref per link, +// written beside an allOf naming it, so a use passes over one $ref per hop, // and the last, whose description is what a use that reached it reads. Where -// aliases is above zero, that many aliases stand between each link and the +// aliases is above zero, that many aliases sit between each hop and the // next. func readThroughChainSpec(n, aliases int) string { - var b strings.Builder + var builder strings.Builder for i := range n { target := fmt.Sprintf("P%d", i+1) for k := range aliases { alias := fmt.Sprintf("X%d_%d", i, k) - fmt.Fprintf(&b, " %s: {$ref: '#/components/schemas/%s'}\n", alias, target) + fmt.Fprintf(&builder, " %s: {$ref: '#/components/schemas/%s'}\n", alias, target) target = alias } - fmt.Fprintf(&b, " P%d: {enum: [a], allOf: [{$ref: '#/components/schemas/%s'}]}\n", i, target) + fmt.Fprintf(&builder, " P%d: {enum: [a], allOf: [{$ref: '#/components/schemas/%s'}]}\n", i, target) } - fmt.Fprintf(&b, " P%d: {type: string, enum: [a], description: from-end}\n", n) - b.WriteString(" Holder: {type: object, properties: {p: {$ref: '#/components/schemas/P0'}}}\n") - return b.String() + fmt.Fprintf(&builder, " P%d: {type: string, enum: [a], description: from-end}\n", n) + builder.WriteString(" Holder: {type: object, properties: {p: {$ref: '#/components/schemas/P0'}}}\n") + return builder.String() } // TestUseOf_ReadThroughsAreBoundedAndAliasesSpendNone pins the bound on the -// read-throughs one use reads on through, which an alias between two links does -// not move: a chain of links under it ends on the schema that describes it, and -// one at or past it stops short, with the same verdict whether or not aliases -// stand between the links. +// read-throughs one use reads on through, which an alias between two hops does +// not move: a chain of hops under it ends on the schema that describes it, and +// one at or past it stops short, with the same answer whether or not aliases +// sit between the hops. func TestUseOf_ReadThroughsAreBoundedAndAliasesSpendNone(t *testing.T) { t.Parallel() const readThroughs = 64 for _, aliases := range []int{0, 3} { for _, n := range []int{1, 2, readThroughs - 1, readThroughs, readThroughs + 1} { - t.Run(fmt.Sprintf("%d links, %d aliases between", n, aliases), func(t *testing.T) { + t.Run(fmt.Sprintf("%d hops, %d aliases between", n, aliases), func(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", readThroughChainSpec(n, aliases))) openapitest.RequireNoErrorDiags(t, diags) @@ -383,16 +383,16 @@ components: k: {$ref: '#/components/schemas/K'} g: {$ref: '#/components/schemas/G'} `) - for _, tc := range []struct{ name, reach string }{ + for _, testCase := range []struct{ name, reach string }{ {"K", "applied to no carrier, as no IR value holds it"}, {"G", "applied to a referencing property, header or parameter wherever that carrier has a field for it"}, } { - at := jsontext.Pointer("/components/schemas/" + tc.name + "/default") + at := jsontext.Pointer("/components/schemas/" + testCase.name + "/default") i := slices.IndexFunc(diags, func(diagnostic ir.Diagnostic) bool { return diagnostic.Code == diag.DegradedConstruct && diagnostic.Provenance.Pointer == at }) - require.GreaterOrEqual(t, i, 0, "%s keeps its default with an info", tc.name) - assert.True(t, strings.HasSuffix(diags[i].Message, tc.reach), "%s: %s", tc.name, diags[i].Message) + require.GreaterOrEqual(t, i, 0, "%s keeps its default with an info", testCase.name) + assert.True(t, strings.HasSuffix(diags[i].Message, testCase.reach), "%s: %s", testCase.name, diags[i].Message) } assert.Nil(t, propertyOf(t, doc, "H", "k").Default) assert.NotNil(t, propertyOf(t, doc, "H", "g").Default) diff --git a/compilers/openapi/internal/schema/use_place_internal_test.go b/compilers/openapi/internal/schema/use_place_internal_test.go index c742026a9..87fbb18c6 100644 --- a/compilers/openapi/internal/schema/use_place_internal_test.go +++ b/compilers/openapi/internal/schema/use_place_internal_test.go @@ -22,8 +22,8 @@ import ( // TestUseDefault_PlacesEachSchemaOfTheChain pins where defaultAt places the // default each schema of a use's chain writes: the site's own at the carrier, a -// folded entry's at the folded entry, a referent's where the bindings place -// it, and one they place nowhere at the carrier, which reads it. +// flattened entry's at the flattened entry, a referent's where the bindings +// place it, and one they place nowhere at the carrier, which reads it. func TestUseDefault_PlacesEachSchemaOfTheChain(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" T: {type: string}\n")) @@ -33,7 +33,7 @@ func TestUseDefault_PlacesEachSchemaOfTheChain(t *testing.T) { assert.False(t, unknown.known, "a schema the bindings do not know is placed nowhere") assert.False(t, unknown.beneath("/allOf/0").known, "nor is an entry beneath it") - use := Use{FoldedAllOfEntries: []annotation.FoldedAllOfEntry{{At: "/v"}}} + use := Use{FlattenedAllOfEntries: []annotation.FlattenedAllOfEntry{{At: "/v"}}} use.appendFallbackReferent(StandaloneSchema(&oas3.Schema{}), referentPlace{doc: loweringContext.Place(), pointer: "/r", known: true}) use.appendFallbackReferent(StandaloneSchema(&oas3.Schema{}), unknown) const carrier = jsontext.Pointer("/p") @@ -73,10 +73,10 @@ func TestUseOf_ARunEndingUnresolvedFallsBackToNothing(t *testing.T) { t.Parallel() lowerer, _ := LoweredFor(t, openapitest.ComponentSpec(" T: {$ref: '#/components/schemas/U'}\n"+ " U: {$ref: '#/components/schemas/Missing'}\n")) - st := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: "/components/schemas/T"}) - require.NotNil(t, st.Ref) + schemaStatement := lowerer.Ctx.Statements().At(reftable.DocumentPointer{Doc: reftable.Source, Pointer: "/components/schemas/T"}) + require.NotNil(t, schemaStatement.Ref) var use Use - schema, ok := use.appendFallbackChainRun(lowerer.Ctx, st) + schema, ok := use.appendFallbackChainRun(lowerer.Ctx, schemaStatement) assert.False(t, ok) assert.Nil(t, schema) assert.Empty(t, use.Referents) diff --git a/compilers/openapi/internal/schema/use_test.go b/compilers/openapi/internal/schema/use_test.go index 3ea94dc2f..61b75271c 100644 --- a/compilers/openapi/internal/schema/use_test.go +++ b/compilers/openapi/internal/schema/use_test.go @@ -16,7 +16,7 @@ import ( // TestUse_ALoopOfNarrowingEnumsEnds pins the bound on what one use reads on // through: enums each passing over a $ref to the next never end on a schema, so -// the walk stops, and what it read stands. +// the walk stops, and what it read remains. func TestUse_ALoopOfNarrowingEnumsEnds(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Holder: @@ -58,23 +58,23 @@ func TestUse_ADefaultReadsOnlyWhereThePositionTakesIt(t *testing.T) { assert.Nil(t, propertyOf(t, unread, "Holder", "f").Default, "a value it cannot read is none it takes") } -// TestUse_ALostRefSpeaksWithWhatIsBesideIt pins a $ref its lowering lost: what is -// written beside it speaks before its target, on the value set's node at a -// property as at a component. -func TestUse_ALostRefSpeaksWithWhatIsBesideIt(t *testing.T) { +// TestUse_APassedOverRefSpeaksWithWhatIsBesideIt pins a $ref its lowering lost: +// what is written beside it speaks before its target, on the value set's node +// at a property as at a component. +func TestUse_APassedOverRefSpeaksWithWhatIsBesideIt(t *testing.T) { t.Parallel() - const lost = "{$ref: '#/components/schemas/Mode', description: beside, deprecated: true}" + const passedOverRef = "{$ref: '#/components/schemas/Mode', description: beside, deprecated: true}" doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Mode: {type: string, enum: [a, b], description: target} - Narrow: {allOf: [`+lost+`, {enum: [a]}]} - Passed: {enum: [a], allOf: [`+lost+`]} + Narrow: {allOf: [`+passedOverRef+`, {enum: [a]}]} + Passed: {enum: [a], allOf: [`+passedOverRef+`]} Holder: type: object properties: - f: {allOf: [`+lost+`, {enum: [a]}]} + f: {allOf: [`+passedOverRef+`, {enum: [a]}]} `)) openapitest.RequireNoErrorDiags(t, diags) typeCommon := doc.Types[propertyOf(t, doc, "Holder", "f").Type.Target].Common() - assert.Equal(t, "beside", typeCommon.Docs.Description, "the node standing at the property") + assert.Equal(t, "beside", typeCommon.Docs.Description, "the node sitting at the property") assert.NotNil(t, typeCommon.Deprecation) for _, name := range []string{"Narrow", "Passed"} { common := typeByName(doc, name).Common() @@ -86,7 +86,8 @@ func TestUse_ALostRefSpeaksWithWhatIsBesideIt(t *testing.T) { // TestUse_ADefaultNoNarrowingExcludesReadsAsBesideARef pins that only a conjunct // narrowing the $ref judges its target's default: one the target's own type leaves // out reads as a plain $ref reads it, where a conjunct excluding it drops it. A -// nullable beside the $ref adds null to what the $ref admits, as 3.0 reads it. +// nullable beside the $ref adds null to what the $ref admits, as 3.0 reads it, +// but beside a conjunct excluding null, which the policy widens nothing past. func TestUse_ADefaultNoNarrowingExcludesReadsAsBesideARef(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", ` Bare: {type: string, default: null} @@ -111,20 +112,22 @@ func TestUse_ADefaultNoNarrowingExcludesReadsAsBesideARef(t *testing.T) { Mode: {type: string, enum: [a, b], default: b} `)) openapitest.RequireNoErrorDiags(t, diags) - for _, wire := range []string{"plain", "wrapped", "widened", "viaRef", "reopened", "viaNarrow", "nullBeside"} { + for _, wire := range []string{"plain", "wrapped", "widened", "viaRef", "viaNarrow", "nullBeside"} { assert.NotNil(t, propertyOf(t, doc, "Holder", wire).Default, wire) } assert.Nil(t, propertyOf(t, doc, "Holder", "narrowed").Default, "a string takes no null its $ref admits") assert.Nil(t, propertyOf(t, doc, "Holder", "byValue").Default, "the conjuncts together leave only a") assert.Nil(t, propertyOf(t, doc, "Holder", "byValueOrNull").Default, "a null is all that nullable adds") - assert.NotNil(t, propertyOf(t, doc, "Holder", "nullBesideNarrowed").Default, - "the nullable beside an entry's $ref is a conjunct of the position, which the policy widens to null") + assert.Nil(t, propertyOf(t, doc, "Holder", "reopened").Default, "a string beside the $ref excludes the null the nullable writes") + assert.Nil(t, propertyOf(t, doc, "Holder", "nullBesideNarrowed").Default, + "the nullable beside an entry's $ref is a conjunct of the position, which a string beside it keeps null out of") } -// TestUse_ADefaultBesideItsValueSetStands pins that a narrowing judges only what -// lies past it: a default written with the value set is the position's own, in or -// out of the set, as a plain enum's is, and it stands ahead of what the $ref says. -func TestUse_ADefaultBesideItsValueSetStands(t *testing.T) { +// TestUse_ADefaultBesideItsValueSetRemains pins that a narrowing judges only +// what lies past it: a default written with the value set is the position's +// own, in or out of the set, as a plain enum's is, and it sits ahead of what +// the $ref says. +func TestUse_ADefaultBesideItsValueSetRemains(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.0.3", ` Mode: {type: string, enum: [a, b], default: a} Plain: {enum: [a], default: other} @@ -205,12 +208,13 @@ func TestUse_ANarrowingOfTwoRefsFallsBackToNothing(t *testing.T) { assert.Empty(t, firstDocs(doc, property).Description) } -// TestUse_ADraftsTupleRestLeavesUnevaluatedItemsInert pins the dialect a site -// reads an unevaluatedItems in (docs/compilers/openapi.md#validation-only): a -// draft reading an `items` list as a tuple leaves the keyword inert beside the -// `additionalItems` past the list, and live with none, and an `items` schema -// leaves it inert in any dialect. -func TestUse_ADraftsTupleRestLeavesUnevaluatedItemsInert(t *testing.T) { +// TestUse_ADraftsTupleRestLeavesUnevaluatedItemsSayingNothing pins the dialect +// a site reads an unevaluatedItems in +// (docs/compilers/openapi.md#validation-only): a draft reading an `items` list +// as a tuple leaves the keyword saying nothing beside the `additionalItems` +// past the list, and live with none, and an `items` schema leaves it saying +// nothing in any dialect. +func TestUse_ADraftsTupleRestLeavesUnevaluatedItemsSayingNothing(t *testing.T) { t.Parallel() const draft = "$schema: 'https://json-schema.org/draft/2019-09/schema', type: array, " doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", @@ -265,7 +269,7 @@ func TestUse_ADecoratorOverADeprecatedBaseReadsItsMembers(t *testing.T) { } // TestUse_AUnionBesideAnAllOfReadsThroughOnlyARefinement pins what a carrier -// reads past an allOf a union stands beside: through one refining to its $ref, +// reads past an allOf a union sits beside: through one refining to its $ref, // at the position and past a $ref to a schema writing it, as past any // refinement, and through none that composes, which the union distributes // across (docs/compilers/openapi.md#allof-refinement). @@ -285,8 +289,10 @@ func TestUse_AUnionBesideAnAllOfReadsThroughOnlyARefinement(t *testing.T) { A: {type: object, properties: {a: {type: string}}} B: {type: object, properties: {b: {type: string}}} `) { + // Its number branch is dead, so the union is kept, on the node sitting + // at the property, which holds what the position writes. refines := propertyOf(t, doc, "Holder", "refines") - assert.Equal(t, "mine", refines.Docs.Description, "what the position writes speaks first") + assert.Equal(t, "mine", doc.Types[refines.Type.Target].Common().Docs.Description, "what the position writes speaks first") for _, wire := range []string{"refines", "viaRefines"} { property := propertyOf(t, doc, "Holder", wire) require.NotNil(t, property.Default, wire) diff --git a/compilers/openapi/internal/schema/valueset.go b/compilers/openapi/internal/schema/valueset.go index 9e73d2f94..b8f0a91be 100644 --- a/compilers/openapi/internal/schema/valueset.go +++ b/compilers/openapi/internal/schema/valueset.go @@ -7,107 +7,205 @@ import ( "encoding/json/jsontext" "slices" + yaml "go.yaml.in/yaml/v3" + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/merge" "github.com/dexpace/morphic/compilers/openapi/internal/statement" "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" "github.com/dexpace/morphic/compilers/openapi/internal/value" "github.com/dexpace/morphic/ir" ) -// valueSetSite is where a value set lowers: set, the schema writing it at -// written, and the node it lowers to, standing where at says: at the position -// for a refinement's inline principal, whose node is the position's while its -// members and reports stay where they are written +// valueSetSite is where a value set lowers: schema, the schema writing it at +// pointer, and the node it lowers to, placed where placement says // (docs/compilers/openapi.md#allof-refinement). member marks a member of an -// enum lowered as a union of literals, which no conjunct types. finish -// finishes the node, nil for a member's. +// enum lowered as a union of literals, which no conjunct types, and +// unionMembers the members of a union of value sets beside a body. type valueSetSite struct { - set *statement.Schema - finish finisher - at stand - written jsontext.Pointer - member bool -} - -// standingValueSet is the site of the value set schema, written at pointer, -// lowers to, its node standing where st says. -func standingValueSet(schema *statement.Schema, pointer jsontext.Pointer, st stand) valueSetSite { - return valueSetSite{set: schema, written: pointer, at: st} + schema *statement.Schema + placement nodePlacement + pointer jsontext.Pointer + member bool + unionMembers bool } -// finishedBy returns vs, its node finished by fin. -func (vs valueSetSite) finishedBy(fin finisher) valueSetSite { - vs.finish = fin - return vs +// placedValueSet is the site of the value set schema, written at pointer, +// lowers to, its node placed where placement says. +func placedValueSet(schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement) valueSetSite { + return valueSetSite{schema: schema, pointer: pointer, placement: placement} } // memberSite is the site of a member of vs's set lowered as a Literal of its // own at at, typed by its value and its set's schema alone. func (vs valueSetSite) memberSite(at jsontext.Pointer) valueSetSite { - return valueSetSite{set: vs.set, written: at, member: true} + return valueSetSite{schema: vs.schema, pointer: at, member: true, unionMembers: vs.unionMembers} } -// pointer returns where the node vs lowers to stands. -func (vs valueSetSite) pointer() jsontext.Pointer { - return vs.at.pointer(vs.written) +// nodePointer returns where the node vs lowers to is placed. +func (vs valueSetSite) nodePointer() jsontext.Pointer { + return vs.placement.pointer(vs.pointer) } // valueType types the node vs lowers to: own, what its set's schema selects, -// narrowed by every conjunct where its position refines (conjunctPrimitive), -// fits saying which primitives the values are of. The position is the stand's, -// else the set's own; a member has none. +// narrowed by every conjunct where its position refines, fits saying which +// primitives the values are of. Conjuncts admitting null alone leave own, and +// a union they choose leaving null alone types it by no kind, as +// `{type: 'null'}` is (docs/compilers/openapi.md#null-alone). func (vs valueSetSite) valueType(loweringContext lowering.Ctx, own ir.PrimitiveKind, fits func(ir.PrimitiveKind) bool) ir.PrimitiveKind { if vs.member { return own } - position := vs.set - if vs.at.of != nil { - position = vs.at.of + position := vs.schema + if vs.placement.position != nil { + position = vs.placement.position + } + if readLoweredUnion(loweringContext, position).besideRest == unionLeavesNullAlone { + // The conjunction admits null alone, as `{type: 'null'}` does, which + // types its node by no kind, whatever kind the body names. + return ir.PrimitiveAny } - refinement, refines := refinementOf(loweringContext, position, vs.pointer()) - if !refines { + refinement, refines := refinementOf(loweringContext, position, vs.nodePointer()) + if !refines || refinement.admittedTogether.reachable() && sharedKinds(refinement.admittedTogether)&refinement.admittedTogether.kinds == kindNull { return own } + if own == ir.PrimitiveAny && refinement.emptyEnumType != "" { + own = refinement.emptyEnumType + } return conjunctPrimitive(loweringContext, refinement, position, own, fits) } -// valueSetPrincipal returns the inline principal of refinementValue that lowers -// to a value set, an enum, a const or a type of null alone, whose node stands -// at the position, and false where refinementValue's principal is none, a $ref, -// or another schema. +// sharesNoMember reports whether vs, no member's site, lowers the value set of +// a position whose conjuncts, or whose own const and enum where it does not +// refine, state sets of one value type sharing no member. +func (vs valueSetSite) sharesNoMember(loweringContext lowering.Ctx) bool { + position := vs.schema + if vs.placement.position != nil { + position = vs.placement.position + } + refinement, refines := refinementOf(loweringContext, position, vs.nodePointer()) + if refines { + return refinement.sharesNoMember + } + return constEnumOverlapOf(loweringContext, vs.schema) == constEnumEmpty +} + +// sharedMembers returns what the value sets vs's position states share where +// none lies within every other, a union of value sets beside its rest first, +// and false where they do not. vs is no member's site. +func (vs valueSetSite) sharedMembers(loweringContext lowering.Ctx) (admitted, bool) { + position := vs.schema + if vs.placement.position != nil { + position = vs.placement.position + } + if shared := readLoweredUnion(loweringContext, position).sharedMembers; shared != nil { + return shared.members, true + } + refinement, refines := refinementOf(loweringContext, position, vs.nodePointer()) + return refinement.admittedTogether, refines && refinement.setsIntersect +} + +// enumMembers returns the members of the enum vs's set writes the node holds: +// each, but where the position's value sets intersect (sharedMembers), those +// they share of the kinds every conjunct leaves. +func (vs valueSetSite) enumMembers(loweringContext lowering.Ctx) []*yaml.Node { + members := vs.schema.Enum() + shared, setsIntersect := vs.sharedMembers(loweringContext) + if !setsIntersect { + return members + } + return slices.DeleteFunc(slices.Clone(members), func(member *yaml.Node) bool { + key, kind, keyed := memberOf(member) + return !keyed || !shared.hasMember(key) || kind&shared.kinds == 0 + }) +} + +// constEnumOverlap is how the const and the enum one schema writes overlap, +// where they share no member (constEnumOverlapOf). +type constEnumOverlap uint8 + +const ( + // constEnumNotDisjoint marks no such pair: a const or an enum alone, a null + // const, sets sharing a member, or one the read cannot answer. + constEnumNotDisjoint constEnumOverlap = iota + // constEnumExcludedByType marks sets of one value type the schema's type + // excludes, which lower as the const as written (enumEntries, lowerConst). + constEnumExcludedByType + // constEnumEmpty marks sets of one value type a primitive names: the closed + // empty Enum of that type (emptyConstSet). + constEnumEmpty + // constBesideEmptyEnum marks `enum: []` beside a const it lies within: the + // closed empty Enum the const's value types, the empty enum the one fact, + // keeping the const (lowerConst). + constBesideEmptyEnum + // constEnumBottom marks sets of lists, of objects or of differing value types, + // which type no Enum: the bottom a false schema lowers to + // (lowerConstEnumBottom). + constEnumBottom +) + +// constEnumOverlapOf returns how the const and the enum schema writes itself +// overlap, read as a refinement reads them, so the two written flat lower as +// on two allOf entries (docs/compilers/openapi.md#enum-const). A set past what +// one read takes is no pair. +func constEnumOverlapOf(loweringContext lowering.Ctx, schema *statement.Schema) constEnumOverlap { + constant := schema.Const() + if constant == nil || !enumWritten(schema) || len(schema.Enum()) >= maxAdmissionMembers { + return constEnumNotDisjoint + } + constSet := memberSetOf(loweringContext, valueSetOf{schema, "const"}, []*yaml.Node{constant}) + enumSet := memberSetOf(loweringContext, valueSetOf{schema, "enum"}, schema.Enum()) + if constSet.unread || enumSet.unread || constSet.kinds&kindNull != 0 { + return constEnumNotDisjoint + } + if len(schema.Enum()) == 0 { + return constBesideEmptyEnum + } + for key := range constSet.values { + if _, shared := enumSet.values[key]; shared { + return constEnumNotDisjoint + } + } + kinds := constSet.kinds & enumSet.kinds + switch { + case kinds == 0 || kinds == kindArray || kinds == kindObject: + return constEnumBottom + case kinds&writtenKinds(schema, false) == 0: + return constEnumExcludedByType + default: + return constEnumEmpty + } +} + +// valueSetPrincipal returns the inline principal of refinementValue that +// lowers to a value set, an enum, a const or a type of null alone, whose node +// sits at the position, and false for any other principal or none. func valueSetPrincipal(refinementValue refinement) (allOfEntry, bool) { allOfEntryValue := refinementValue.principal - if allOfEntryValue == nil || allOfEntryValue.schema.Ref != nil { + if allOfEntryValue == nil || allOfEntryValue.schema.Ref != nil || refinementValue.unionPrincipal { return allOfEntry{}, false } - if won := principalDispatch(*allOfEntryValue).won; won == "const" || won == "enum" || won == "" && nullAlone(allOfEntryValue.schema.Schema) { + if lowered := principalDispatch(*allOfEntryValue).lowered; lowered == "const" || lowered == "enum" || lowered == "" && typeOfNullAlone(allOfEntryValue.schema.Schema) { return *allOfEntryValue, true } return allOfEntry{}, false } -// nullAlone reports whether schema writes a type naming null alone, which -// lowers to the value set of null (lowerNullAlone). -func nullAlone(schema *statement.Schema) bool { - return writesType(schema) && len(effectiveTypes(schema)) == 0 -} - -// electedSet names the keyword of the value set refinementValue, a refinement -// of schema whose conjuncts share no value, is elected for: its inline -// principal's, else the one written beside the allOf, an enum or a const either -// way (setElected). -func electedSet(refinementValue refinement, schema *statement.Schema) string { +// chosenSetKeyword names the keyword of the value set refinementValue, a +// refinement of schema whose conjuncts share no value, is chosen for: its +// inline principal's, else the one written beside the allOf, an enum or a const +// either way (chosenSetConjunct). +func chosenSetKeyword(refinementValue refinement, schema *statement.Schema) string { if entry, ok := valueSetPrincipal(refinementValue); ok { - return principalDispatch(entry).won + return principalDispatch(entry).lowered } - return dispatchOf(schema).besideAllOf().won + return dispatchOf(schema).besideAllOf().lowered } -// principalDispatch is the dispatch of the inline principal e's own keywords: -// a flattened wrapper's allOf is no rival of its value set, its entries being -// conjuncts of the position (allOfEntries). +// principalDispatch is the dispatch of the inline principal allOfEntryValue's +// own keywords: a flattened wrapper's allOf is no rival of its value set, its +// entries being conjuncts of the position (allOfEntries). func principalDispatch(allOfEntryValue allOfEntry) dispatch { dispatchValue := dispatchOf(allOfEntryValue.schema.Schema) if allOfEntryValue.wrapper { @@ -116,108 +214,161 @@ func principalDispatch(allOfEntryValue allOfEntry) dispatch { return dispatchValue } -// lowerPrincipalValueSet lowers the value set allOfEntryValue, r's inline -// principal, writes at pointer, the position schema is written at, so one node -// stands for the position whichever conjunct decides it -// (docs/compilers/openapi.md#allof-refinement). What allOfEntryValue writes -// beside its set that the node has no field for is kept on it, each keyword at -// its own pointer, as on any node a schema lowers to, before fin finishes it. -func lowerPrincipalValueSet(loweringContext lowering.Ctx, ts *compile.Types, schema *statement.Schema, allOfEntryValue allOfEntry, pointer jsontext.Pointer, - fin finisher, -) (ir.TypeID, []ir.Diagnostic) { - bs := allOfEntryValue.schema.Schema +// lowerPrincipalValueSet lowers the value set allOfEntryValue, the inline +// principal of schema's refinement, writes, its node at pointer, where schema +// is written, so one node names the position whichever conjunct decides it +// (docs/compilers/openapi.md#allof-refinement). ownDiags reports what the +// position keeps unread of its own keywords, after what the principal keeps. +func lowerPrincipalValueSet(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, allOfEntryValue allOfEntry, pointer jsontext.Pointer, +) (built builtPosition, diags, ownDiags []ir.Diagnostic) { + entrySchema := allOfEntryValue.schema.Schema dispatch := principalDispatch(allOfEntryValue) - var kept, own finished - st := stand{of: schema, at: pointer} - // The position's own keywords type the value set as a conjunct does, and - // it keeps unread what they leave before the principal keeps its own. - outside := own.on(func(td ir.TypeDef) []ir.Diagnostic { - return keepUnread(loweringContext, ts, schema, pointer, td, dispatchOf(schema).besideAllOf(), valueSetReads(schema, td), stand{}, nil, nil) - }).then(fin) - var heldBack []ir.Diagnostic - position := finisher(func(td ir.TypeDef, read keySet, held *principalKept) { - heldBack = keepBuiltAround(loweringContext, st, td, read, held, bs, allOfEntryValue.pointer, outside) - }) - site := valueSetSite{set: bs, written: allOfEntryValue.pointer, at: st, finish: func(td ir.TypeDef, read keySet, held *principalKept) { - kept.diags = keepUnread(loweringContext, ts, bs, allOfEntryValue.pointer, td, dispatch, read, st, held, position) - }} - var id ir.TypeID - var built []ir.Diagnostic - switch dispatch.won { + placement := nodePlacement{position: schema, positionPointer: pointer} + site := valueSetSite{schema: entrySchema, pointer: allOfEntryValue.pointer, placement: placement} + var builtDiags []ir.Diagnostic + switch dispatch.lowered { case "const": - id, built = lowerConst(loweringContext, ts, site) + built, builtDiags = lowerConst(loweringContext, types, site) case "enum": - id, built = lowerEnum(loweringContext, ts, site) + built, builtDiags = lowerEnum(loweringContext, types, site) default: - id = lowerNullAlone(loweringContext, ts, site) + built = lowerNullAlone(loweringContext, types, site) + } + var keptDiags []ir.Diagnostic + if built.node != nil { + // What the build added as pending keeps for the node follows what its + // readers add, as the settlement orders them. + buildPendingKeeps := built.pendingKeeps + built.pendingKeeps = annotation.PendingKeeps{} + keptDiags = keepUnread(loweringContext, entrySchema, allOfEntryValue.pointer, &built, dispatch, placement) + built.pendingKeeps.AddAll(buildPendingKeeps) + // The position's own keywords type the value set as a conjunct does, and + // it keeps unread what they leave before the principal keeps its own. A + // value set of the other keyword the position writes is one the + // principal's choice passes over, kept as written beside it. + ownBuilt := builtPosition{node: built.node, id: built.id, read: valueSetReadsBeside(loweringContext, schema, entrySchema, built.node) | valueSetBoundsRead(schema, built.node, site.homesOf(loweringContext, built.node))} + ownDispatch := dispatchOf(schema).besideAllOf() + apart := site.sharesNoMember(loweringContext) + refinementValue, _ := refinementOf(loweringContext, schema, pointer) + for _, rival := range []string{"enum", "const"} { + switch { + case !hasKey(schema, rival): + case apart || refinementValue.emptyEnumType != "": + // Sets sharing no member are each kept, the position's as its + // node holds none of their members, and none passed over. + ownDiags = append(ownDiags, keepChosenSet(loweringContext, builtKeeps{}, &built.node.Common().Unmodeled, placedValueSet(schema, pointer, nodePlacement{}), rival)...) + ownBuilt.read |= keyBit(rival) + case rival != dispatch.lowered && dispatch.lowered != "": + ownDispatch.lowered, ownDispatch.skipped = dispatch.lowered, append(ownDispatch.skipped, rival) + ownBuilt.read &^= keyBit(rival) + } + } + ownDiags = append(ownDiags, keepUnread(loweringContext, schema, pointer, &ownBuilt, ownDispatch, nodePlacement{})...) } - // The value set is the position's node, on which its build keeps what it - // did not read. - return id, slices.Concat(built, missingArrayItems(loweringContext, bs, allOfEntryValue.pointer), kept.diags, own.diags, heldBack) + return built, slices.Concat(builtDiags, keptDiags), ownDiags } // setType is the ValueType of the Enum or Literal a refinement's value set -// lowers to, ok false where it lowers to no such node (refinedValueType). +// lowers to, the zero setType where it lowers to no such node. type setType struct { primitive ir.PrimitiveKind - ok bool + lowers bool } +// typedSet is the setType of a value set lowering to a node of primitive. +func typedSet(primitive ir.PrimitiveKind) setType { return setType{primitive: primitive, lowers: true} } + +// valueType returns the ValueType t names, and false where the value set +// lowers to no Enum or Literal. +func (t setType) valueType() (ir.PrimitiveKind, bool) { return t.primitive, t.lowers } + // refinedValueType returns the ValueType of the Enum or Literal the refinement // refinementValue of schema, written at pointer, lowers to, as its build types // it, and none where it lowers to no such node: its principal is a $ref or no // value set, or its set lowers to a union of literals or the top type. It reads // the source alone, so a reader of the position asks no registry. func refinedValueType(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, pointer jsontext.Pointer) setType { - site := standingValueSet(schema, pointer, stand{}) + site := placedValueSet(schema, pointer, nodePlacement{}) dispatch := dispatchOf(schema).besideAllOf() if entry, ok := valueSetPrincipal(refinementValue); ok { - site = valueSetSite{set: entry.schema.Schema, written: entry.pointer, at: stand{of: schema, at: pointer}} + site = valueSetSite{schema: entry.schema.Schema, pointer: entry.pointer, placement: nodePlacement{position: schema, positionPointer: pointer}} dispatch = principalDispatch(entry) } else if refinementValue.principal != nil { return setType{} } - switch dispatch.won { + switch dispatch.lowered { case "enum": return enumSetType(loweringContext, site) case "const": return constSetType(loweringContext, site) + case "": + if refinementValue.sharesNoMember { + return typedSet(refSetsType(loweringContext, site, refinementValue.admittedTogether)) + } + } + if !typeOfNullAlone(site.schema) { + return setType{} + } + return typedSet(site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny)) +} + +// lowerRefSets lowers schema, written at pointer, whose conjuncts' value sets, +// each a $ref target's, share no member: the closed Enum with no member of +// their one value type, typed as an inline set sharing none is. +func lowerRefSets(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, admittedTogether admitted) builtPosition { + site := placedValueSet(schema, pointer, nodePlacement{}) + return internNode(loweringContext, types, site.nodePointer(), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + enum := &ir.Enum{TypeCommon: common, ValueType: refSetsType(loweringContext, site, admittedTogether), Closed: true} + return enum, valueSetReads(loweringContext, schema, enum) + }) +} + +// refSetsType is the ValueType of the closed empty Enum value sets sharing no +// member lower to at site: the primitive an Enum of their members takes, any +// number a number, narrowed as the site types it. +func refSetsType(loweringContext lowering.Ctx, site valueSetSite, admittedTogether admitted) ir.PrimitiveKind { + primitive := ir.PrimitiveNumber + switch admittedTogether.kinds &^ kindNull { + case kindString: + primitive = ir.PrimitiveString + case kindBoolean: + primitive = ir.PrimitiveBool default: - return setType{primitive: site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny), ok: nullAlone(site.set)} } + return site.enumType(loweringContext, admitsEvery, primitive) } // enumSetType is refinedValueType for an enum: the Enum's ValueType, as // lowerEnum gives it, and none where the enum lowers to anything else. func enumSetType(loweringContext lowering.Ctx, site valueSetSite) setType { - written := site.set.Enum() + written := site.schema.Enum() if !loweringContext.Limits.MaxEnumMembers.Admits(len(written)) { return setType{} } - kept := slices.DeleteFunc(readEnum(written), enumEntry.isNull) + kept := slices.DeleteFunc(readEnum(written, site.pointer), enumEntry.isNull) primitive, ok := enumMemberPrimitive(kept) if !ok { return setType{primitive: site.enumType(loweringContext, admitsEvery, primitive)} } - return setType{primitive: site.enumType(loweringContext, func(primitiveKind ir.PrimitiveKind) bool { return entriesAre(kept, primitiveKind) }, primitive), ok: true} + return typedSet(site.enumType(loweringContext, func(primitiveKind ir.PrimitiveKind) bool { return entriesAre(kept, primitiveKind) }, primitive)) } // constSetType is refinedValueType for a const: the Literal's ValueType, or // the ValueType of the Enum with no member a null lowers to, and none where // the value converts to none. func constSetType(loweringContext lowering.Ctx, site valueSetSite) setType { - val, err := value.FromNode(site.set.Const()) + val, err := value.FromNode(site.schema.Const()) if err == nil && val.Kind == ir.ValueNull { - return setType{primitive: site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny), ok: true} + return typedSet(site.enumType(loweringContext, admitsEvery, ir.PrimitiveAny)) } - return setType{primitive: site.literalType(loweringContext, val), ok: err == nil} + return setType{primitive: site.literalType(loweringContext, val), lowers: err == nil} } // enumType is the ValueType an Enum of members classified as memberPrimitive // takes at vs (enumValueType), admits saying whether every member is a value of // a primitive, narrowed where its position refines. func (vs valueSetSite) enumType(loweringContext lowering.Ctx, admits func(ir.PrimitiveKind) bool, memberPrimitive ir.PrimitiveKind) ir.PrimitiveKind { - return vs.valueType(loweringContext, enumValueType(vs.set, admits, memberPrimitive), admits) + return vs.valueType(loweringContext, enumValueType(vs.schema, admits, memberPrimitive), admits) } // admitsEvery is what enumType asks of an Enum with no member: every value of @@ -227,7 +378,9 @@ func admitsEvery(ir.PrimitiveKind) bool { return true } // literalType is the ValueType a Literal of val takes at vs // (literalValueType), narrowed where its position refines. func (vs valueSetSite) literalType(loweringContext lowering.Ctx, val ir.Value) ir.PrimitiveKind { - return vs.valueType(loweringContext, literalValueType(vs.set, val), func(primitiveKind ir.PrimitiveKind) bool { return merge.Admits(primitiveKind, val) }) + return vs.valueType(loweringContext, literalValueType(vs.schema, val), func(primitiveKind ir.PrimitiveKind) bool { + return ir.PrimitiveAdmits(primitiveKind, val) == ir.AdmitsYes + }) } // valueTypeHoldsFormat reports whether a value set typed primitive holds the @@ -238,17 +391,17 @@ func valueTypeHoldsFormat(primitive ir.PrimitiveKind, schema *statement.Schema) return ok && narrowsOrIs(primitive, paired) } -// conjunctPrimitive returns, of own and the primitive each conjunct of r -// selects (declaredPrimitive), the one narrowing every other, and own where -// none does: two formats neither of which narrows the other say no one -// primitive. The conjuncts are s, each inline entry, and what decides what a -// $ref entry lands on (conjunctSchemas). own is "" for a value no primitive -// types, which none fits, so it stands. +// conjunctPrimitive returns, of own and the primitive each conjunct of +// refinementValue selects, the one narrowing every other, and own where none +// does: two formats neither of which narrows the other say no one primitive. +// own is "" for a value no primitive types, which none fits, so it remains. func conjunctPrimitive(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema, own ir.PrimitiveKind, fits func(ir.PrimitiveKind) bool) ir.PrimitiveKind { primitives := []ir.PrimitiveKind{own} for _, cs := range conjunctSchemas(loweringContext, refinementValue, schema) { if primitive, ok := declaredPrimitive(cs, fits); ok { primitives = append(primitives, primitive) + } else if primitive, ok := typelessFormatPrimitive(cs, fits); ok { + primitives = append(primitives, primitive) } } for _, primitiveKind := range primitives { @@ -259,23 +412,43 @@ func conjunctPrimitive(loweringContext lowering.Ctx, refinementValue refinement, return own } -// conjunctSchemas returns the schemas whose keywords r's conjuncts write: s, the -// keywords beside the allOf, then each entry, a $ref's being what decides what -// it lands on, read past a chain of $refs and refinements (DecidingSchema). +// conjunctSchemas returns the schemas whose keywords refinementValue's +// conjuncts write: schema, then each entry, a $ref's being what decides what +// it lands on, and an inline one's less what its conjuncts write otherwise, so +// a type two entries state alike types the set where their formats disagree. func conjunctSchemas(loweringContext lowering.Ctx, refinementValue refinement, schema *statement.Schema) []*statement.Schema { out := []*statement.Schema{schema} - for _, entry := range refinementValue.comp.entries { - bs := entry.schema.Schema + for i, entry := range refinementValue.comp.entries { + entrySchema := entry.schema.Schema if entry.schema.Ref != nil { - bs = DecidingSchema(loweringContext, refBranchTarget(loweringContext, entry.schema)) + entrySchema = DecidingSchema(loweringContext, refBranchTarget(loweringContext, entry.schema)) + } else if stated(entrySchema) { + entrySchema = foldingNode(loweringContext, schema, i, entrySchema) } - if stated(bs) { - out = append(out, bs) + if stated(entrySchema) { + out = append(out, entrySchema) } } return out } +// typelessFormatPrimitive returns the primitive the format schema writes with +// no type selects beside the type it is defined for, where fits says the +// values are of it: a format applies to its type's instances wherever it is +// written (docs/compilers/openapi.md#allof-refinement). +func typelessFormatPrimitive(schema *statement.Schema, fits func(ir.PrimitiveKind) bool) (ir.PrimitiveKind, bool) { + format := writtenFormat(schema) + if format == "" || writesType(schema) { + return "", false + } + for _, kind := range []statement.JSONSchemaTypeName{statement.KindInteger, statement.KindNumber, statement.KindString, statement.KindBoolean} { + if primitive, known := typeformat.Lookup(string(kind) + "/" + format); known && fits(primitive) { + return primitive, true + } + } + return "", false +} + // narrowsOrIs reports whether primitiveKind is irPrimitiveKind or narrower. func narrowsOrIs(primitiveKind, irPrimitiveKind ir.PrimitiveKind) bool { rel := typeformat.Relate(primitiveKind, irPrimitiveKind) @@ -297,3 +470,24 @@ func declaredPrimitive(schema *statement.Schema, fits func(ir.PrimitiveKind) boo } return "", false } + +// withUnionNotes returns entries, the members of vs's enum, each holding what +// the branch of the union beside it writing that member alone says of it +// (unionNotesBesideSet), as the member of a union of value sets filtered by +// the rest holds it. +func (vs valueSetSite) withUnionNotes(loweringContext lowering.Ctx, entries []enumEntry) []enumEntry { + position := vs.schema + if vs.placement.position != nil { + position = vs.placement.position + } + notes := unionNotesBesideSet(loweringContext, position, vs.nodePointer()) + if len(notes) == 0 { + return entries + } + for i := range entries { + if key, _, keyed := memberOf(entries[i].node); keyed { + entries[i].notes = notes[key] + } + } + return entries +} diff --git a/compilers/openapi/internal/schema/valueset_intersection_test.go b/compilers/openapi/internal/schema/valueset_intersection_test.go new file mode 100644 index 000000000..63a95b175 --- /dev/null +++ b/compilers/openapi/internal/schema/valueset_intersection_test.go @@ -0,0 +1,321 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// valueSetUnionSpellings writes union, a union of value sets, beside set in +// every placement openapitest.Spellings gives, and with it on one entry beside +// a string. +func valueSetUnionSpellings(union, set string) map[string]string { + spellings := openapitest.Spellings(set, union) + spellings["EntryBoth"] = "{allOf: [{type: string}, {" + set + ", " + union + "}]}" + return spellings +} + +// enumStrings returns the string members of the Enum typeDef is, failing where +// typeDef is no Enum. +func enumStrings(t *testing.T, typeDef ir.TypeDef, label string) []string { + t.Helper() + enum, ok := typeDef.(*ir.Enum) + require.True(t, ok, "%s: got %T", label, typeDef) + out := make([]string, 0, len(enum.Members)) + for _, member := range enum.Members { + out = append(out, member.Value.String) + } + return out +} + +// TestValueSetUnion_IsOneSetConjunctInEverySpelling holds a union whose +// branches are value sets beside a value set, flat, beside an allOf and on an +// entry in either order, to one set conjunct, its branches' members, a oneOf's +// those one branch alone holds: every member of the set within the union, +// the union says nothing and is neither kept nor reported, but where a branch +// writes a note or an extension, which keeps it; some, the Enum of +// those, the union kept only where a branch shares none, named dead at it; +// none, the closed empty Enum (docs/compilers/openapi.md#allof-refinement). +func TestValueSetUnion_IsOneSetConjunctInEverySpelling(t *testing.T) { + t.Parallel() + for name, testCase := range map[string]struct { + union, set string + want []string + kept, dead bool + }{ + "Some": {"anyOf: [{enum: [a, b]}, {enum: [b, c]}]", "enum: [b, x]", []string{"b"}, false, false}, + "Every": {"anyOf: [{enum: [a, b]}, {enum: [b, c]}]", "enum: [b, a]", []string{"b", "a"}, false, false}, + "None": {"anyOf: [{enum: [a, b]}, {enum: [b, c]}]", "enum: [x, y]", []string{}, true, true}, + "OneDead": {"oneOf: [{enum: [a]}, {const: b}, {enum: [c]}]", "enum: [a, z]", []string{"a"}, true, true}, + "OneTwice": {"oneOf: [{enum: [a, b]}, {enum: [b, c]}]", "enum: [b, c]", []string{"c"}, false, false}, + "NestedSays": {"anyOf: [{enum: [s1, s2]}, {anyOf: [{enum: [p]}, {const: s1}]}]", "enum: [s1, p]", []string{"s1", "p"}, false, false}, + "EveryNoted": {"anyOf: [{enum: [a, b], description: d}, {enum: [b, c]}]", "enum: [b, a]", []string{"b", "a"}, true, false}, + "NestedExtended": {"anyOf: [{enum: [s1, s2]}, {anyOf: [{enum: [p], x-n: 1}, {const: s1}]}]", "enum: [s1, p]", + []string{"s1", "p"}, true, false}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + spellings := valueSetUnionSpellings(testCase.union, testCase.set) + var written strings.Builder + for spelling, schema := range spellings { + written.WriteString(" " + spelling + ": " + schema + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + keyword, _, _ := strings.Cut(testCase.union, ":") + for spelling := range spellings { + typeDef := typeByName(doc, spelling) + assert.Equal(t, testCase.want, enumStrings(t, typeDef, spelling), spelling) + _, kept := typeDef.Common().Unmodeled["openapi:"+keyword] + if strings.HasPrefix(spelling, "Entry") || openapitest.PartsOnEntry(spelling) { + kept = keptUnder(typeDef.Common().Unmodeled, keyword) + } + assert.Equal(t, testCase.kept, kept, "%s: the union is kept where it says something", spelling) + warned := warningsUnder(diags, spelling) + if !testCase.dead { + assert.Empty(t, warned, spelling) + continue + } + require.Len(t, warned, 1, spelling) + assert.Equal(t, diag.UnsatisfiableSchema, warned[0].Code, spelling) + assert.True(t, strings.HasSuffix(string(warned[0].Provenance.Pointer), "/"+keyword), "%s: at the union, %s", spelling, warned[0].Provenance.Pointer) + } + }) + } +} + +// TestValueSetUnion_AnIntersectionOfSeveralKindsKeepsTheSet holds that a union +// of value sets sharing members of several kinds with the enum beside it lowers +// to the Union of the literals of those, keeping the enum, as the Enum of a +// intersection of one kind keeps it, so the member left out stays in the IR. +func TestValueSetUnion_AnIntersectionOfSeveralKindsKeepsTheSet(t *testing.T) { + t.Parallel() + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Mixed: {enum: [a, 1, true], anyOf: [{enum: [a, 1]}, {enum: [x]}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + union, ok := typeByName(doc, "Mixed").(*ir.Union) + require.True(t, ok, "got %T", typeByName(doc, "Mixed")) + values := make([]string, 0, len(union.Variants)) + for _, variant := range union.Variants { + literal, isLiteral := doc.Types[variant.Type.Target].(*ir.Literal) + require.True(t, isLiteral, "%s", variant.Type.Target) + values = append(values, literal.Value.String+string(literal.Value.Number)) + } + assert.Equal(t, []string{"a", "1"}, values) + assert.Equal(t, ir.ReasonDegradedLowering, union.Unmodeled["openapi:enum"].Reason) + assert.Equal(t, ir.ReasonDegradedLowering, union.Unmodeled["openapi:anyOf"].Reason) +} + +// keptUnder reports whether unmodeled keeps keyword under its own key or +// within an entry kept whole. +func keptUnder(unmodeled ir.Unmodeled, keyword string) bool { + for key, entry := range unmodeled { + if key == "openapi:"+keyword || strings.Contains(string(entry.Value), `"`+keyword+`"`) { + return true + } + } + return false +} + +// TestValueSetUnion_PastItsBoundsIsWeighedByKind holds a union of value sets +// read past what the admission reads, its members or its schemas, to the +// reading of its branches' kinds: no set conjunct, so the body's set is +// as written beside the union kept, and a const beside a union of sets +// sharing none of its value to the closed empty Enum keeping the const. +func TestValueSetUnion_PastItsBoundsIsWeighedByKind(t *testing.T) { + t.Parallel() + many := make([]string, 0, 4200) + for i := range 4200 { + many = append(many, "m"+strconv.Itoa(i)) + } + branches := make([]string, 0, 300) + for i := range 300 { + branches = append(branches, "{const: b"+strconv.Itoa(i)+"}") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " Members: {enum: [m1, x], anyOf: [{enum: ["+strings.Join(many, ", ")+"]}, {const: y}]}\n"+ + " Schemas: {enum: [b1, x], anyOf: ["+strings.Join(branches, ", ")+"]}\n"+ + " Const: {const: x, anyOf: [{enum: [a]}, {const: b}]}\n")) + openapitest.RequireNoErrorDiags(t, diags) + for _, name := range []string{"Members", "Schemas"} { + members := enumStrings(t, typeByName(doc, name), name) + assert.Len(t, members, 2, "%s: the set is as written past the bounds", name) + assert.Contains(t, typeByName(doc, name).Common().Unmodeled, "openapi:anyOf", name) + } + assert.Empty(t, enumStrings(t, typeByName(doc, "Const"), "Const"), "no member of the union is the const's") + assert.Contains(t, typeByName(doc, "Const").Common().Unmodeled, "openapi:const") +} + +// TestValueSetUnion_BesideAUnionPassedOverIsReadAgainstTheSet holds a union +// of value sets, or one some branch of which is no value set, chosen over a +// second union, to the reading it takes alone beside the value set the rest +// states, which that second union narrows: in every spelling and in either +// order, the Enum of the members they share, none where no instance satisfies +// them, warned once, as its twin written without the union passed over +// lowers, a typed union too where that one leaves the set no member. A union +// every member satisfies is kept, as the one passed over is beside it. +func TestValueSetUnion_BesideAUnionPassedOverIsReadAgainstTheSet(t *testing.T) { + t.Parallel() + const anyOfB, oneOfAC = "anyOf: [{enum: [b]}, {enum: [c, a]}]", "oneOf: [{const: a}, {const: c}]" + for name, testCase := range map[string]struct { + parts []string + want []string + warned int + }{ + "TwoEntryTwin": {[]string{"const: b", oneOfAC}, []string{}, 1}, + "ConstTyped": {[]string{"const: b", "type: string", anyOfB, oneOfAC}, []string{}, 1}, + "EnumTyped": {[]string{"enum: [b]", "type: string", anyOfB, oneOfAC}, []string{}, 1}, + "ConstUntyped": {[]string{"const: b", anyOfB, oneOfAC}, []string{}, 1}, + "TypedBranch": {[]string{"const: b", "type: string", anyOfB, "oneOf: [{const: a, minLength: 1}, {const: c}]"}, []string{}, 1}, + "NarrowedToOne": {[]string{"enum: [a, b, c]", "anyOf: [{enum: [a]}, {enum: [c]}]", "oneOf: [{const: a}, {const: b}]"}, []string{"a"}, 1}, + "PassedOverApart": {[]string{"const: b", "anyOf: [{enum: [c]}, {enum: [d]}]", "oneOf: [{const: c}, {const: d}]"}, []string{}, 1}, + "PassedOverEmpties": {[]string{"const: b", "anyOf: [{enum: [c]}, {enum: [d]}]", "oneOf: [{const: c}, {const: b}]"}, []string{}, 1}, + "TypedEmptied": {[]string{"const: b", "type: string", "anyOf: [{enum: [c]}, {enum: [d]}]", "oneOf: [{const: c, minLength: 1}, {const: b}]"}, []string{}, 1}, + "EveryMember": {[]string{"enum: [a, b]", "anyOf: [{enum: [a]}, {enum: [b, c]}]", "oneOf: [{const: a}, {const: b}]"}, []string{"a", "b"}, 0}, + "EveryMemberTyped": {[]string{"enum: [a, b]", "anyOf: [{minLength: 1}, {maxLength: 3}]", "oneOf: [{type: string}, {maxLength: 0}]"}, []string{"a", "b"}, 0}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + spellings := openapitest.Spellings("", testCase.parts...) + for spelling, schema := range openapitest.Reversed("", testCase.parts...) { + spellings[spelling+"Reversed"] = schema + } + var written strings.Builder + for spelling, schema := range spellings { + written.WriteString(" " + spelling + ": " + schema + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for spelling := range spellings { + typeDef := typeByName(doc, spelling) + assert.Equal(t, testCase.want, enumStrings(t, typeDef, spelling), spelling) + for _, part := range testCase.parts { + if keyword, _, _ := strings.Cut(part, ":"); keyword == "anyOf" || keyword == "oneOf" { + kept := keptUnder(typeDef.Common().Unmodeled, keyword) + assert.True(t, kept, "%s: the %s is kept", spelling, keyword) + } + } + warned := warningsUnder(diags, spelling) + require.Len(t, warned, testCase.warned, spelling) + for _, warning := range warned { + assert.Equal(t, diag.UnsatisfiableSchema, warning.Code, spelling) + } + } + }) + } +} + +// TestValueSetUnion_BesideAnEnumAMemberHoldsWhatItsBranchSaysOfIt holds a +// union beside an enum, in every spelling and in either order, to the node of +// the members they share, each holding what the branch writing it alone says +// of it, as the union written alone gives it, and the union kept nowhere where +// the node holds all it writes, the members it narrows the enum to among it, +// but once where a branch says of several members what none holds. +func TestValueSetUnion_BesideAnEnumAMemberHoldsWhatItsBranchSaysOfIt(t *testing.T) { + t.Parallel() + const noted = "oneOf: [{const: a, title: A, description: dA, deprecated: true}, {const: b, description: dB}]" + const typed = "oneOf: [{const: a, title: A, description: dA, deprecated: true}, {type: string, minLength: 9}, {const: b, description: dB}]" + for name, row := range map[string]struct { + rest, union string + want []string + enumKept, unionKept bool + }{ + "Same": {rest: "enum: [a, b]", union: noted, want: []string{"a", "b"}}, + "Narrowed": {rest: "enum: [a, b, c]", union: noted, want: []string{"a", "b"}, enumKept: true}, + "Typed": {rest: "enum: [a, b]", union: typed, want: []string{"a", "b"}}, + "TypedNoted": {rest: "enum: [a, b]", union: strings.Replace(typed, "minLength: 9", "minLength: 9, description: long", 1), want: []string{"a", "b"}, unionKept: true}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + spellings := openapitest.Spellings(row.rest, row.union) + for spelling, text := range openapitest.Reversed(row.rest, row.union) { + spellings[spelling+"Reversed"] = text + } + var written strings.Builder + for spelling, text := range spellings { + written.WriteString(" " + spelling + ": " + text + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + docs := map[string]ir.Docs{"a": {Summary: "A", Description: "dA"}, "b": {Description: "dB"}} + for spelling := range spellings { + enum, ok := typeByName(doc, spelling).(*ir.Enum) + require.True(t, ok, "%s: got %T", spelling, typeByName(doc, spelling)) + assert.Equal(t, row.want, enumStrings(t, enum, spelling), spelling) + for _, member := range enum.Members { + assert.Equal(t, docs[member.Value.String], member.Docs, "%s: %s", spelling, member.Value.String) + assert.Equal(t, member.Value.String == "a", member.Deprecation != nil, "%s: %s", spelling, member.Value.String) + } + assert.Equal(t, row.unionKept, keptUnder(enum.Unmodeled, "oneOf"), "%s: the union is kept where the node does not hold it whole", spelling) + _, enumKept := enum.Unmodeled["openapi:enum"] + assert.Equal(t, row.enumKept, enumKept, "%s: the enum is kept where the node narrows it", spelling) + assert.Empty(t, warningsUnder(diags, spelling), spelling) + } + }) + } +} + +// TestValueSetUnion_BesideASetNoEnumWritesTheUnionKeepsItsNotes holds a union +// whose branch says something of the one member it writes, beside a value +// set no inline enum writes, a const or the enum a $ref names, in every +// spelling: no member of the position's own holds the note, so the union is +// kept with it. +func TestValueSetUnion_BesideASetNoEnumWritesTheUnionKeepsItsNotes(t *testing.T) { + t.Parallel() + const union = "anyOf: [{const: a, description: dA}]" + spellings := map[string]string{} + for name, rest := range map[string]string{"Const": "const: a", "Ref": "$ref: '#/components/schemas/E'"} { + for spelling, text := range openapitest.Spellings(rest, union) { + spellings[name+spelling] = text + } + } + var written strings.Builder + written.WriteString(" E: {enum: [a, b]}\n") + for spelling, text := range spellings { + written.WriteString(" " + spelling + ": " + text + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for spelling := range spellings { + var kept bool + for _, entry := range typeByName(doc, spelling).Common().Unmodeled { + kept = kept || strings.Contains(string(entry.Value), "dA") + } + assert.True(t, kept, "%s: the note is kept with its union", spelling) + } +} + +// TestValueSetUnion_BesideAnEnumOfTwoKindsALiteralHoldsWhatItsBranchSaysOfIt +// holds a union beside an enum of two kinds, in every spelling, to the Union +// of the enum's literals, each holding what the branch writing it alone says +// of it, the union kept nowhere. +func TestValueSetUnion_BesideAnEnumOfTwoKindsALiteralHoldsWhatItsBranchSaysOfIt(t *testing.T) { + t.Parallel() + const rest, union = "enum: [a, 1]", "oneOf: [{const: a, description: dA}, {type: integer}]" + spellings := openapitest.Spellings(rest, union) + var written strings.Builder + for spelling, text := range spellings { + written.WriteString(" " + spelling + ": " + text + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for spelling := range spellings { + node, ok := typeByName(doc, spelling).(*ir.Union) + require.True(t, ok, "%s: got %T", spelling, typeByName(doc, spelling)) + var described []string + for _, variant := range node.Variants { + described = append(described, doc.Types[variant.Type.Target].Common().Docs.Description) + } + assert.Equal(t, []string{"dA", ""}, described, spelling) + assert.False(t, keptUnder(node.Unmodeled, "oneOf"), spelling) + } +} diff --git a/compilers/openapi/internal/schema/valueset_keys_test.go b/compilers/openapi/internal/schema/valueset_keys_test.go new file mode 100644 index 000000000..bbf0b7eea --- /dev/null +++ b/compilers/openapi/internal/schema/valueset_keys_test.go @@ -0,0 +1,51 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// TestAllOf_DisjointValueSetsTakeTheirConjunctsKeys holds value sets sharing no +// member, one beside the allOf and one on its entry, to the keys the node's +// settlement gives their conjuncts: a set that alone writes its keyword takes +// the plain key, wherever it is written, and the entry's set takes its entry +// key where the position writes the same keyword. +func TestAllOf_DisjointValueSetsTakeTheirConjunctsKeys(t *testing.T) { + t.Parallel() + for schema, want := range map[string]map[string]string{ + "{enum: [a, b], allOf: [{const: c}]}": {"openapi:enum": `["a","b"]`, "openapi:const": `"c"`}, + "{const: c, allOf: [{enum: [a, b]}]}": {"openapi:const": `"c"`, "openapi:enum": `["a","b"]`}, + } { + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: "+schema+"\n")) + openapitest.RequireNoErrorDiags(t, diags) + enum, ok := typeByName(doc, "S").(*ir.Enum) + require.True(t, ok, "%s: the closed empty enum: got %T", schema, typeByName(doc, "S")) + assert.ElementsMatch(t, keysOf(want), unmodeledKeys(enum.Unmodeled), "%s: the keys kept", schema) + for key, value := range want { + require.Contains(t, enum.Unmodeled, key, schema) + assert.JSONEq(t, value, string(enum.Unmodeled[key].Value), "%s: %s", schema, key) + } + for _, diagnostic := range diags { + assert.NotContains(t, diagnostic.Message, "only one can be the value", "%s: no set is reported as passed over", schema) + } + assert.Equal(t, []ir.Severity{ir.SeverityWarning}, severitiesAt(diags, diag.UnsatisfiableSchema, "/components/schemas/S"), schema) + } +} + +// keysOf returns the keys of m. +func keysOf(m map[string]string) []string { + out := make([]string, 0, len(m)) + for key := range m { + out = append(out, key) + } + return out +} diff --git a/compilers/openapi/internal/schema/valueset_test.go b/compilers/openapi/internal/schema/valueset_test.go index ea206a9ff..6f7283f04 100644 --- a/compilers/openapi/internal/schema/valueset_test.go +++ b/compilers/openapi/internal/schema/valueset_test.go @@ -18,10 +18,12 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestValueSet_AConstNullOnAnEntryStandsAtThePosition pins a const of null an +// TestValueSet_AConstNullOnAnEntrySitsAtThePosition pins a const of null an // entry writes beside a type admitting null: the value set of null alone -// stands at the position, typed by the conjunct declaring a string. -func TestValueSet_AConstNullOnAnEntryStandsAtThePosition(t *testing.T) { +// sits at the position, typed as `{const: null}` is, since the conjunct +// declaring a string admits no string there +// (docs/compilers/openapi.md#null-alone). +func TestValueSet_AConstNullOnAnEntrySitsAtThePosition(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", " S: {allOf: [{type: [string, 'null']}, {const: null}]}\n")) @@ -29,7 +31,7 @@ func TestValueSet_AConstNullOnAnEntryStandsAtThePosition(t *testing.T) { en, ok := typeByName(doc, "S").(*ir.Enum) require.True(t, ok, "got %T", typeByName(doc, "S")) assert.Empty(t, en.Members) - assert.Equal(t, ir.PrimitiveString, en.ValueType) + assert.Equal(t, ir.PrimitiveAny, en.ValueType) assert.Empty(t, en.Unmodeled) } @@ -78,12 +80,12 @@ func TestValueSet_TwoRefsWrittenAlikeAreKeptOnce(t *testing.T) { } } -// TestValueSet_AnEmptyEnumBesideACompositionIsNotElected pins the value set -// whose own keywords leave it no value: it is no set to lower, so the allOf -// beside it composes and the dispatch among competing keywords keeps each $ref -// it passes over by reference text, and a use of the position reads through -// neither $ref. -func TestValueSet_AnEmptyEnumBesideACompositionIsNotElected(t *testing.T) { +// TestValueSet_AnEmptyEnumBesideACompositionIsNotChosen pins the value set +// whose own keywords leave it no value beside an allOf of two $refs to objects: +// the empty enum lies within both targets, so the position is the closed empty +// Enum keeping neither $ref, each target saying its own, and a use of the +// position reads through neither (docs/compilers/openapi.md#enum-const). +func TestValueSet_AnEmptyEnumBesideACompositionIsNotChosen(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` A: {type: object, properties: {a: {type: string}}, description: a} B: {type: object, properties: {b: {type: string}}, description: b} @@ -96,35 +98,35 @@ func TestValueSet_AnEmptyEnumBesideACompositionIsNotElected(t *testing.T) { openapitest.RequireNoErrorDiags(t, diags) en, ok := typeByName(doc, "S").(*ir.Enum) require.True(t, ok, "got %T", typeByName(doc, "S")) - assert.Equal(t, []string{"openapi:$ref/0", "openapi:$ref/1"}, unmodeledKeys(en.Unmodeled)) - assert.JSONEq(t, `"#/components/schemas/B"`, string(en.Unmodeled["openapi:$ref/1"].Value)) + assert.Empty(t, en.Unmodeled) assert.Empty(t, propertyOf(t, doc, "Holder", "f").Docs.Description) } // TestValueSet_ABoundBesideAnEntrysValueSetIsKeptByItsKeyword pins what the // entry writing a value set writes beside it that the node has no field for: a -// bound no value set holds is kept under its keyword, at the entry, once, and -// the entry is not kept whole for it. +// bound of another kind than the values it lists, which no Enum holds (GitHub +// #2004), is kept under its keyword, at the entry, once, and the entry is not +// kept whole for it. func TestValueSet_ABoundBesideAnEntrysValueSetIsKeptByItsKeyword(t *testing.T) { t.Parallel() doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", ` Str: {type: string} - S: {allOf: [{$ref: '#/components/schemas/Str'}, {enum: [a], minLength: 3}]} + S: {allOf: [{$ref: '#/components/schemas/Str'}, {enum: [a], minimum: 3}]} `)) openapitest.RequireNoErrorDiags(t, diags) en, ok := typeByName(doc, "S").(*ir.Enum) require.True(t, ok, "got %T", typeByName(doc, "S")) - assert.Equal(t, []string{"openapi:$ref", "openapi:minLength"}, unmodeledKeys(en.Unmodeled)) - assert.Equal(t, jsontext.Pointer("/components/schemas/S/allOf/1/minLength"), en.Unmodeled["openapi:minLength"].Provenance.Pointer) + assert.Equal(t, []string{"openapi:$ref", "openapi:minimum"}, unmodeledKeys(en.Unmodeled)) + assert.Equal(t, jsontext.Pointer("/components/schemas/S/allOf/1/minimum"), en.Unmodeled["openapi:minimum"].Provenance.Pointer) assert.Contains(t, openapitest.DiagMessageAt(t, diags, diag.DegradedConstruct, ir.SeverityInfo, - "/components/schemas/S/allOf/1"), "no home for minLength") + "/components/schemas/S/allOf/1"), "no home for minimum") } -// TestValueSet_SetsAlikeTheElectionCannotTellApartElectNone pins two value sets +// TestValueSet_SetsAlikeTheChoiceCannotTellApartChooseNone pins two value sets // of one value, beside a $ref they share none with, parting on the `items` -// each lowers its elements by: no rule picks one, so none is elected before +// each lowers its elements by: no rule picks one, so none is chosen before // the composition, which keeps every entry and reports the contradiction, in // either order. -func TestValueSet_SetsAlikeTheElectionCannotTellApartElectNone(t *testing.T) { +func TestValueSet_SetsAlikeTheChoiceCannotTellApartChooseNone(t *testing.T) { t.Parallel() const ints, numbers = "{enum: [[1]], items: {type: integer}}", "{enum: [[1]], items: {type: number}}" for _, entries := range []string{ints + ", " + numbers, numbers + ", " + ints} { @@ -134,6 +136,6 @@ func TestValueSet_SetsAlikeTheElectionCannotTellApartElectNone(t *testing.T) { model, ok := typeByName(doc, "S").(*ir.Model) require.True(t, ok, "%s: got %T", entries, typeByName(doc, "S")) assert.Equal(t, []string{"openapi:$ref", "openapi:allOf/1", "openapi:allOf/2"}, unmodeledKeys(model.Unmodeled), entries) - assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.DegradedConstruct, ir.SeverityWarning), entries) + assert.Equal(t, 1, openapitest.CountDiagsAt(diags, diag.UnsatisfiableSchema, ir.SeverityWarning), entries) } } diff --git a/compilers/openapi/internal/schema/valuesetbranches.go b/compilers/openapi/internal/schema/valuesetbranches.go new file mode 100644 index 000000000..e7693c141 --- /dev/null +++ b/compilers/openapi/internal/schema/valuesetbranches.go @@ -0,0 +1,613 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "cmp" + "slices" + "strconv" + "strings" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/value" + "github.com/dexpace/morphic/ir" +) + +// maxMemberJudgments bounds the judgments one union beside a value set takes, +// a member against a branch each: past it the members are left unjudged, and +// the union is its branches' kinds read it. +const maxMemberJudgments = 4096 + +// setMember is one member of the value set the rest of a conjunction states: +// its value and its key (memberOf). +type setMember struct { + value ir.Value + key string +} + +// judgeSetMembers is out, the reading of loweredUnion, a union of typed +// branches the conjunction conjunctionRead of schema chooses, decided by the +// members of the value set rest states, each judged against it (judgeMembers): +// where every member satisfies it, it says nothing, unless a branch says what +// the set does not (branchesSayNothingBeside) or a union passed over is kept +// beside it; where it refuses some, or all, the position's node holds the +// others, the union kept and each refusal reported +// (docs/compilers/openapi.md#union-beside-structure). Where none is refused, +// or the judgments pass their bound, out, what the branches' kinds read, stands. +func judgeSetMembers(loweringContext lowering.Ctx, schema *statement.Schema, conjunctionRead conjunction, loweredUnion conjunctionUnion, + rest conjunctionRest, out unionReading, +) unionReading { + if !rest.set.fixed || (out.besideRest != unionKeptByRest && out.besideRest != unionConjoined) || + !writesTypedBranch(loweringContext, loweredUnion.branches()) { + return out + } + members, read := restSetMembers(loweringContext, schema, rest) + if !read { + return out + } + judgments, judged := judgeMembers(loweringContext, loweredUnion, members, false) + switch { + case !judged, len(judgments.refused) == 0 && judgments.unknown: + return out + case len(judgments.refused) == 0 && (len(conjunctionRead.passed()) > 0 || !setHoldsUnion(loweringContext, schema, loweredUnion, rest, rest.set)): + // Every member satisfies the union, but a branch says what the node + // does not hold, a note or an extension, or a union passed over is + // kept beside it: the union is kept. + out.besideRest, out.kind, out.judgedBesideSet = unionKeptByRest, "", true + return out + case len(judgments.refused) == 0: + return unionReading{dead: make([]bool, len(out.dead)), besideRest: unionSaysNothing, judgedBesideSet: true} + } + out.besideRest, out.kind, out.judgedBesideSet = unionKeptByRest, "", true + out.sharedMembers = &unionSharedMembers{members: setOfMembers(judgments.kept), refused: judgments.refused} + return out +} + +// branchesSayNothingBeside reports whether a union of branches every member +// of the value set beside it satisfies says nothing that set does not: every +// key each branch, or a union it nests, writes is a kind, a value set, a +// bound, a $ref or a union, which the judgment read, or says nothing +// (keySaysNothing) and is no note and no extension, which the union alone +// holds. A read past maxValueSetSchemas says something. +func branchesSayNothingBeside(loweringContext lowering.Ctx, branches []statement.Subschema) bool { + pending := slices.Clone(branches) + for read := 0; len(pending) > 0; read++ { + if read == maxValueSetSchemas { + return false + } + schemaStatement := loweringContext.Statements().Subschema(pending[len(pending)-1]) + pending = pending[:len(pending)-1] + if !stated(schemaStatement.Schema) { + continue + } + if slices.ContainsFunc(schemaStatement.Keys, func(key statement.Key) bool { + return hasKey(schemaStatement.Schema, key.Name) && !saysNothingBesideTheSet(schemaStatement.Schema, key) + }) { + return false + } + choice := schemaStatement.ChoiceKeywords() + pending = append(pending, choice.OneOf...) + pending = append(pending, choice.AnyOf...) + } + return true +} + +// saysNothingBesideTheSet reports whether key, written on a branch of a union +// every member of the value set beside it satisfies, says nothing that set +// does not (branchesSayNothingBeside). +func saysNothingBesideTheSet(schema *statement.Schema, key statement.Key) bool { + switch { + case key.Slot == specrules.SlotNotes || strings.HasPrefix(key.Name, "x-"): + return false + case key.Slot == specrules.SlotKinds, key.Slot == specrules.SlotValues, key.Slot == specrules.SlotNumber, + key.Slot == specrules.SlotText, key.Slot == specrules.SlotReference, key.Slot == specrules.SlotChoice: + return true + default: + return keySaysNothing(schema, key) + } +} + +// writesTypedBranch reports whether some one of branches is no value set +// (writesValueSetOnly): a union of value sets alone is one value-set conjunct +// (readValueSetUnion), weighed by its branches' kinds past what that reads. +func writesTypedBranch(loweringContext lowering.Ctx, branches []statement.Subschema) bool { + return slices.ContainsFunc(branches, func(branch statement.Subschema) bool { + schemaStatement := loweringContext.Statements().Subschema(branch) + return schemaStatement.Ref != nil || !stated(schemaStatement.Schema) || !writesValueSetOnly(schemaStatement.Schema) + }) +} + +// restSetMembers returns the members of the value set rest states, the +// conjunction of schema, in the order schema and its inline allOf entries +// write them (valueSetConjuncts), each once, and false +// where one is not written inline, is no scalar, converts to no value, or +// where the rest admits null, which no member is but the reference holds. +func restSetMembers(loweringContext lowering.Ctx, schema *statement.Schema, rest conjunctionRest) ([]setMember, bool) { + if rest.kinds&kindNull != 0 || rest.widened { + return nil, false + } + var out []setMember + seen := map[string]bool{} + for _, written := range valueSetConjuncts(loweringContext, schema) { + member, kind, ok := setMemberOf(written) + if !ok || kind&(kindArray|kindObject|kindNull) != 0 { + return nil, false + } + if rest.set.hasMember(member.key) && !seen[member.key] { + seen[member.key] = true + out = append(out, member) + } + } + return out, len(out) > 0 && len(out) == rest.set.size() +} + +// valueSetConjuncts returns each value the enums and consts of schema and its +// inline allOf entries write, in that order. +func valueSetConjuncts(loweringContext lowering.Ctx, schema *statement.Schema) []*yaml.Node { + var out []*yaml.Node + for _, conjunctSchema := range inlineConjuncts(loweringContext, schema) { + out = append(out, conjunctSchema.Enum()...) + if constant := conjunctSchema.Const(); constant != nil { + out = append(out, constant) + } + } + return out +} + +// setMemberOf returns the member node writes with its kind, and false where +// it converts to no value or keys none. +func setMemberOf(node *yaml.Node) (setMember, kindSet, bool) { + val, err := value.FromNode(node) + key, kind, keyed := memberOf(node) + if err != nil || !keyed { + return setMember{}, 0, false + } + return setMember{value: val, key: key}, kind, true +} + +// refusedMember is a member of a value set a union it is conjoined with +// refuses, how many of the union's branches admit it, and that union. +type refusedMember struct { + setMember + admittedBy int + by refusingUnion +} + +// refusingUnion is a union refusing a member of a value set: its keyword, and +// whether a $ref the position conjoins names it rather than the position +// writing it. +type refusingUnion struct { + keyword unionKeyword + referenced bool +} + +// named is how a report names u. +func (u refusingUnion) named() string { + if u.referenced { + return "the " + string(u.keyword) + " a $ref it is conjoined with names" + } + return "the " + string(u.keyword) + " beside it" +} + +// keptAs is how a report says u stays in the IR: the union is kept where it +// is written, and a $ref naming it where the value set narrows it. +func (u refusingUnion) keptAs() string { + if u.referenced { + return "the $ref is kept verbatim under Unmodeled" + } + return "the " + string(u.keyword) + " is kept verbatim under Unmodeled" +} + +// memberJudgments is how the union beside a value set judges its members: +// those it keeps, which it admits or the reader cannot judge, whether one is +// such, and those it refuses. +type memberJudgments struct { + kept []setMember + refused []refusedMember + unknown bool +} + +// judgeMembers returns how loweredUnion, a union members are conjoined with, +// which a $ref names where referenced, judges each, as the value reader judges +// it against a Union of the union's branches (memberJudge), whatever kinds of +// value they are, and false where the judgments pass maxMemberJudgments. +func judgeMembers(loweringContext lowering.Ctx, loweredUnion conjunctionUnion, members []setMember, referenced bool) (memberJudgments, bool) { + spent := budget.New(budget.AtMost(maxMemberJudgments)) + if !spent.Spend(len(members) * len(loweredUnion.branches())) { + return memberJudgments{}, false + } + judge := newMemberJudge(loweringContext, loweredUnion) + var out memberJudgments + for _, member := range members { + switch judge.reader.Admits(judge.union, member.value) { + case ir.AdmitsYes: + out.kept = append(out.kept, member) + case ir.AdmitsUnknown: + // Unknown is no refusal: the member stays. + out.kept, out.unknown = append(out.kept, member), true + case ir.AdmitsNo: + out.refused = append(out.refused, refusedMember{setMember: member, admittedBy: judge.admittedBy(member.value), + by: refusingUnion{keyword: loweredUnion.keyword, referenced: referenced}}) + } + } + return out, true +} + +// memberJudge is a union of branches as the value reader judges a scalar +// against it: its own nodes, which are in no document (judgeLookup), their +// IDs in a space of their own, a Union, exclusive for a oneOf and closed, of +// one node per branch (branchRef). +type memberJudge struct { + nodes []ir.TypeDef + reader *ir.ValueAdmissionReader + union ir.TypeRef + branches []ir.TypeRef +} + +// judgePrimitives are the primitives a memberJudge's nodes name. +var judgePrimitives = []ir.PrimitiveKind{ir.PrimitiveAny, ir.PrimitiveString, ir.PrimitiveInteger, ir.PrimitiveNumber, ir.PrimitiveBool} + +// newJudge returns a judge holding the primitives its nodes name, and no +// branch. +func newJudge() *memberJudge { + judge := &memberJudge{} + for _, primitive := range judgePrimitives { + judge.nodes = append(judge.nodes, &ir.Primitive{ID: ir.PrimitiveTypeID(primitive), PrimitiveKind: primitive}) + } + return judge +} + +// newMemberJudge returns the judge of loweredUnion's branches. +func newMemberJudge(loweringContext lowering.Ctx, loweredUnion conjunctionUnion) *memberJudge { + judge := newJudge() + union := &ir.Union{ID: compile.TypeID("union-judge", "union"), Exclusive: loweredUnion.keyword.Exclusive(), Closed: true} + for i, branch := range loweredUnion.branches() { + ref := judge.branchRef(loweringContext, "branch/"+strconv.Itoa(i), loweringContext.Statements().Subschema(branch)) + judge.branches = append(judge.branches, ref) + union.Variants = append(union.Variants, ir.Variant{Type: ref}) + } + judge.nodes = append(judge.nodes, union) + judge.union = ir.TypeRef{Target: union.ID} + judge.reader = judge.newReader() + return judge +} + +// newReader returns a value reader over j's nodes as they are. +func (j *memberJudge) newReader() *ir.ValueAdmissionReader { + node := judgeLookup(j.nodes) + return ir.NewValueAdmissionReader(node, ir.NewAliasChainIndex(node), nil) +} + +// admittedBy is how many of j's branches admit val. +func (j *memberJudge) admittedBy(val ir.Value) int { + count := 0 + for _, branch := range j.branches { + if j.reader.Admits(branch, val) == ir.AdmitsYes { + count++ + } + } + return count +} + +// branchRef adds the node branch schemaStatement, written at path below the +// judge, is judged as and returns a reference to it: the top type for `true`, +// no value for `false`, and the keywords of the schema object its $refs lead to +// (branchFacts). A branch the judge does not read, one whose kinds the +// kind-inference policy read among them, names a node the judge does not hold, +// which the reader answers unknown for. +func (j *memberJudge) branchRef(loweringContext lowering.Ctx, path string, schemaStatement *statement.Statement) ir.TypeRef { + id := compile.TypeID("union-judge", path) + unread := ir.TypeRef{Target: compile.TypeID("union-judge", path+"/unread")} + if _, inferred := lowersTo(loweringContext, schemaStatement); inferred { + return unread + } + at, written, ok := branchLanding(loweringContext, schemaStatement) + if !ok { + return unread + } + switch written.Truth { + case statement.Anything: + j.nodes = append(j.nodes, &ir.Any{ID: id}) + case statement.Nothing: + j.nodes = append(j.nodes, &ir.Enum{ID: id, Closed: true}) + default: + if !j.branchFacts(at, path, written.Schema) { + return unread + } + } + return ir.TypeRef{Target: id} +} + +// branchLanding returns the schema branch schemaStatement's $refs lead to +// (refChain), with the context of the document holding it, and false where a +// $ref lands on none or loops, or a schema on the way conjoins another, by an +// allOf or by keywords written beside its $ref. +func branchLanding(loweringContext lowering.Ctx, schemaStatement *statement.Statement) (lowering.Ctx, *statement.Statement, bool) { + at := loweringContext + for step := range refChain(loweringContext, schemaStatement) { + landed := step.statement + if step.from != nil { + if landed == nil { + return at, nil, false + } + at, _ = lowering.InDocument(at, step.at.Doc) + } + switch { + case landed.Truth == statement.Anything || landed.Truth == statement.Nothing: + return at, landed, true + case landed.Truth != statement.Stated || landed.Truncated || len(landed.Entries) > 0: + // An allOf, or a $ref written beside other keywords, conjoins + // what the judge reads no node of. + return at, nil, false + case landed.Ref == nil: + return at, landed, true + } + } + return at, nil, false +} + +// saysNothingOfAValue reports whether key, as its dialect reads it, says +// nothing of a scalar a branch admits: a note, a resource keyword, one no +// dialect defines, `nullable`, as no member is null, and a keyword applying +// to objects or arrays alone. +func saysNothingOfAValue(key statement.Key) bool { + switch key.Slot { + case specrules.SlotNotes, specrules.SlotResource, specrules.SlotUnknown, specrules.SlotArray, specrules.SlotObject: + return !key.DefinedOnlyInLaterMinor + case specrules.SlotKinds: + return key.Name == "nullable" + default: + return false + } +} + +// branchFacts adds the node the keywords schema writes, a branch at path +// below the judge, are judged as, read in the context at of the document +// holding it: a Scalar holding their bounds over what their type and value set +// admit (branchCore), and false where branchCore reads none. A keyword +// it reads no node of, a format, a content keyword or one its dialect does not +// define among them, caps what the reader answers, a yes being unknown: the +// keywords of a schema conjoin, so a value the others refuse it refuses too. +func (j *memberJudge) branchFacts(at lowering.Ctx, path string, schema *statement.Schema) bool { + capped := slices.ContainsFunc(schema.Keys, func(key statement.Key) bool { + _, read := schema.Key(key.Name) + judged := !key.DefinedOnlyInLaterMinor && !slices.Contains(contentKeywords, key.Name) && + slices.Contains([]specrules.Slot{specrules.SlotKinds, specrules.SlotValues, specrules.SlotNumber, specrules.SlotText}, key.Slot) + return read && !saysNothingOfAValue(key) && !judged + }) + core, read := j.branchCore(path, schema) + if !read { + return false + } + site, _ := siteOf(schema) + var scratch ir.Unmodeled + cons, _ := ConstraintsOf(at, &scratch, schema, nil, site.Pointer, kindString|kindNumber) + if capped || len(scratch) > 0 { + scratch = ir.Unmodeled{"openapi:unread": {Reason: ir.ReasonDegradedLowering}} + } + j.nodes = append(j.nodes, &ir.Scalar{ID: compile.TypeID("union-judge", path), Unmodeled: scratch, Base: &core, Constraints: cons}) + return true +} + +// branchCore adds the node of what schema's type and value set admit, schema +// being a branch at path below the judge, and returns a reference to it: the +// closed Enum of its enum's or its const's values its type admits, else the +// Union of the primitives its type names, else the top type; false where it +// writes both an enum and a const, or a value the judge reads none of. A +// const its dialect does not define is no value set. +func (j *memberJudge) branchCore(path string, schema *statement.Schema) (ir.TypeRef, bool) { + kinds := j.kindsRef(path, schema.Types()) + nodes := schema.Enum() + if constKey, _ := schema.Key("const"); schema.Const() != nil && !constKey.DefinedOnlyInLaterMinor { + if nodes != nil { + return ir.TypeRef{}, false + } + nodes = []*yaml.Node{schema.Const()} + } + if nodes == nil { + return kinds, true + } + typeReader := j.newReader() + set := &ir.Enum{ID: compile.TypeID("union-judge", path+"/set"), Closed: true} + for _, written := range nodes { + val, err := value.FromNode(written) + if err != nil { + return ir.TypeRef{}, false + } + // The kinds node, primitives the reader judges every value against, + // answers yes or no. + if typeReader.Admits(kinds, val) == ir.AdmitsYes { + set.Members = append(set.Members, ir.EnumMember{Value: val}) + } + } + j.nodes = append(j.nodes, set) + return ir.TypeRef{Target: set.ID}, true +} + +// kindsRef adds the Union of the primitives types, a branch's at path below +// the judge, names that a scalar may be, and returns a reference to it: the +// top type where types names none, and the closed empty Enum, admitting no +// value, where it names only objects, arrays or null. +func (j *memberJudge) kindsRef(path string, types []statement.JSONSchemaTypeName) ir.TypeRef { + if types == nil { + return ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveAny)} + } + common := ir.TypeCommon{ID: compile.TypeID("union-judge", path+"/kinds")} + var variants []ir.Variant + for _, name := range types { + if primitive, scalar := scalarPrimitives[name]; scalar { + variants = append(variants, ir.Variant{Type: ir.TypeRef{Target: ir.PrimitiveTypeID(primitive)}}) + } + } + if len(variants) == 0 { + j.nodes = append(j.nodes, &ir.Enum{TypeCommon: common, Closed: true}) + } else { + j.nodes = append(j.nodes, &ir.Union{TypeCommon: common, Variants: variants, Closed: true}) + } + return ir.TypeRef{Target: common.ID} +} + +// scalarPrimitives maps each JSON type a scalar is to the primitive admitting +// exactly its values. +var scalarPrimitives = map[statement.JSONSchemaTypeName]ir.PrimitiveKind{ + statement.KindString: ir.PrimitiveString, statement.KindInteger: ir.PrimitiveInteger, + statement.KindNumber: ir.PrimitiveNumber, statement.KindBoolean: ir.PrimitiveBool, +} + +// refusedByUnion returns the members of the value set vs lowers that a union +// it is conjoined with refuses (judgeSetMembers, judgeReferencedUnions), and +// whether the unions admit none of them. +func (vs valueSetSite) refusedByUnion(loweringContext lowering.Ctx) ([]refusedMember, bool) { + position := vs.schema + if vs.placement.position != nil { + position = vs.placement.position + } + shared := readLoweredUnion(loweringContext, position).sharedMembers + if shared == nil { + return nil, true + } + return shared.refused, shared.members.size() == 0 +} + +// refusedSetMemberReports reports, once at the position site's value set +// lowers at, wherever the set and the unions are written, the members of the +// set a union conjoined with it refuses: each named, ordered by its key, with +// how many of the refusing union's branches it satisfies, as values no +// instance is, or, where the unions refuse every member, as a schema no +// instance satisfies (docs/compilers/openapi.md#union-beside-structure). +func refusedSetMemberReports(loweringContext lowering.Ctx, site valueSetSite) []ir.Diagnostic { + refused, none := site.refusedByUnion(loweringContext) + if len(refused) == 0 { + return nil + } + refused = slices.SortedFunc(slices.Values(refused), func(a, b refusedMember) int { return strings.Compare(a.key, b.key) }) + by := refused[0].by + several := slices.ContainsFunc(refused, func(member refusedMember) bool { return member.by != by }) + judged := make([]string, 0, len(refused)) + for _, member := range refused { + count := "none" + if member.admittedBy > 0 { + count = strconv.Itoa(member.admittedBy) + } + if several { + count += " of the branches of " + member.by.named() + } + judged = append(judged, describeValue(member.value)+" satisfies "+count) + } + refusing, kept := "every union JSON Schema conjoins with it", "" + if !several { + admits := "one of its branches" + if by.keyword.Exclusive() { + admits = "exactly one of its branches" + } + refusing = by.named() + ", which JSON Schema conjoins with it and which admits a value satisfying " + admits + kept = ", and " + by.keptAs() + } + if none { + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, site.nodePointer(), + "no member of this value set satisfies %s (%s), so no instance satisfies this schema: it lowers to the enum "+ + "with no member%s", refusing, strings.Join(judged, ", "), kept)} + } + return []ir.Diagnostic{loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, site.nodePointer(), + "this value set lists values that do not satisfy %s (%s), so no instance is one of them: what this position "+ + "lowers to leaves them out%s", refusing, strings.Join(judged, ", "), kept)} +} + +// landedUnion is a union a $ref lands on, with the context of the document +// holding it and where the schema writing it sits. +type landedUnion struct { + at lowering.Ctx + union conjunctionUnion + site reftable.DocumentPointer +} + +// referencedUnions returns the union each $ref schema conjoins, beside it or +// as an allOf entry, lands on chooses, read through $refs as a branch is +// (branchLanding), ordered by where each sits, pointer first, so the union +// a report names refusing a member does not turn on the order of the $refs. +func referencedUnions(loweringContext lowering.Ctx, schema *statement.Schema) []landedUnion { + var out []landedUnion + for ref := range allOfRefEntries(loweringContext, schema) { + at, landed, ok := branchLanding(loweringContext, ref) + if !ok || landed.Truth != statement.Stated { + continue + } + if union, lowersUnion := readConjunction(at, landed.Schema).loweredUnion(); lowersUnion { + site, _ := siteOf(landed.Schema) + out = append(out, landedUnion{at: at, union: union, site: site}) + } + } + slices.SortStableFunc(out, func(a, b landedUnion) int { + return cmp.Or(provenance.ComparePointers(a.site.Pointer, b.site.Pointer), cmp.Compare(a.site.Doc, b.site.Doc)) + }) + return out +} + +// judgeReferencedUnions is out, the reading of the union schema's conjunction +// chooses, with the members of the value set its rest states judged against +// each union a $ref it conjoins lands on (referencedUnions), as judgeSetMembers +// judges them against one written beside it: a member one refuses is left out +// of the node and reported. It judges only where the node is the value set's, +// and the members out already keeps. +func judgeReferencedUnions(loweringContext lowering.Ctx, schema *statement.Schema, out unionReading) unionReading { + if !positionIsTheSet(out.besideRest) || len(valueSetConjuncts(loweringContext, schema)) == 0 { + return out + } + unions := referencedUnions(loweringContext, schema) + if len(unions) == 0 { + return out + } + rest := readConjunctionRest(loweringContext, schema) + members, read := restSetMembers(loweringContext, schema, rest) + if !rest.set.fixed || !read || rest.kinds&^kindNull == 0 { + // Conjuncts sharing no kind are reported as such, once. + return out + } + if out.sharedMembers != nil { + members = slices.DeleteFunc(members, func(member setMember) bool { return !out.sharedMembers.members.hasMember(member.key) }) + } + var refused []refusedMember + for _, landed := range unions { + judgments, judged := judgeMembers(landed.at, landed.union, members, true) + if judged { + members, refused = judgments.kept, append(refused, judgments.refused...) + } + } + if len(refused) == 0 { + return out + } + var refusedBefore []refusedMember + if out.sharedMembers != nil { + refusedBefore = out.sharedMembers.refused + } + out.sharedMembers = &unionSharedMembers{members: setOfMembers(members), refused: append(slices.Clone(refusedBefore), refused...)} + return out +} + +// setOfMembers is the value set holding members, each by its key and kind. +func setOfMembers(members []setMember) admitted { + out := admitted{fixed: true, values: map[string]kindSet{}} + for _, member := range members { + kind := kindOfValue(member.value) + out.kinds |= kind + out.values[member.key] = kind + } + return out +} + +// positionIsTheSet reports whether a union so beside its rest leaves the +// position the node its value set lowers to: no union, one saying nothing, or +// one the body keeps. +func positionIsTheSet(besideRest unionBesideRest) bool { + return besideRest == unionNoneLowered || besideRest == unionSaysNothing || besideRest == unionKeptByRest +} diff --git a/compilers/openapi/internal/schema/valuesetbranches_test.go b/compilers/openapi/internal/schema/valuesetbranches_test.go new file mode 100644 index 000000000..aa5b6e113 --- /dev/null +++ b/compilers/openapi/internal/schema/valuesetbranches_test.go @@ -0,0 +1,275 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/ir" +) + +// typedSetRow is a schema writing a union of typed branches beside a value +// set, and what judging the set's members against the union leaves: the +// members the Enum holds, nil where the node is no Enum, whether the union is +// kept, and the member refused, as the report at the position names it, "" +// for none. +type typedSetRow struct { + schema string + members []string + kept bool + refused string +} + +// TestTypedBranches_EachBranchIsReadOrLeftUnjudged holds what judging a value +// set's members against a union of typed branches reads: `true`, `false`, a +// $ref chain, a const, a member two oneOf branches admit and mixed kinds are +// judged. Inferred kinds, an enum beside a const, a value no JSON holds, a $ref +// loop or landing nowhere, a null branch, a list or null member, a second union +// and judgments past their bound leave members unjudged; a keyword the judge +// does not read leaves unjudged only what the branch's others admit. A +// satisfied union stays kept where a branch notes more, or its read is cut. +func TestTypedBranches_EachBranchIsReadOrLeftUnjudged(t *testing.T) { + t.Parallel() + // The judgments are a member against a branch each: 16 by 256 take the + // whole bound, and 17 by 241 one past it. + members := func(count int) []string { + out := make([]string, 0, count) + for i := range count { + out = append(out, "m"+strings.Repeat("x", i)) + } + return out + } + branches := func(count int) string { + return strings.Repeat("{type: string}, ", count-1) + "{type: string}" + } + both := []string{"a", "b"} + for version, rows := range map[string]map[string]typedSetRow{ + "3.1.0": { + "TrueBranch": {"{enum: [a, b], oneOf: [true, {type: integer}]}", both, false, ""}, + "FalseBranch": {"{enum: [a, b], anyOf: [false, {type: string}]}", both, false, ""}, + "RefChain": {"{enum: [a, b], oneOf: [{$ref: '#/components/schemas/StrRef'}, {type: integer}]}", both, false, ""}, + "RefTrue": {"{enum: [a, b], oneOf: [{$ref: '#/components/schemas/Anything'}, {type: integer}]}", both, false, ""}, + "ConstBranch": {"{enum: [a, b], oneOf: [{const: a}, {type: string, maxLength: 0}]}", []string{"a"}, true, `"b"`}, + "TwoBranches": {"{enum: [a, b], oneOf: [{type: string}, {enum: [a]}]}", []string{"b"}, true, `"a"`}, + "Inferred": {"{enum: [a, b], oneOf: [{properties: {p: {}}}, {type: string}]}", both, true, ""}, + "Not": {"{enum: [a, b], oneOf: [{type: string, not: {const: b}}, {type: integer}]}", both, true, ""}, + "NotBeside": {"{enum: [a, bb], oneOf: [{type: string, maxLength: 1, not: {const: b}}, {type: integer}]}", []string{"a"}, true, `"bb"`}, + "Format": {"{enum: [a, b], anyOf: [{type: string, format: uuid}, {type: integer}]}", both, true, ""}, + "Content": {"{enum: [a, b], anyOf: [{type: string, contentMediaType: text/plain}, {type: integer}]}", both, true, ""}, + "BothSets": {"{enum: [a, b], oneOf: [{enum: [a], const: a}, {type: integer}]}", both, true, ""}, + "NanBranch": {"{enum: [a, b], oneOf: [{enum: [a, .nan]}, {type: integer}]}", both, false, ""}, + "NanEntry": {"{enum: [a, b], allOf: [{enum: [.nan]}], oneOf: [{type: string}, {type: integer}]}", both, true, ""}, + "NanConst": {"{enum: [a, b], allOf: [{const: .nan}], oneOf: [{type: string}, {type: integer}]}", both, true, ""}, + "RefLoop": {"{enum: [a, b], oneOf: [{$ref: '#/components/schemas/LoopA'}, {type: string}]}", both, true, ""}, + "Unresolved": {"{enum: [a, b], oneOf: [{$ref: '#/components/schemas/Missing'}, {type: string}]}", both, true, ""}, + "NullBranch": {"{enum: [a, b], oneOf: [null, {type: string}]}", both, true, ""}, + "Mixed": {"{enum: [a, 1, true], anyOf: [{type: string}, {type: integer}]}", nil, true, "true"}, + "ArrayMember": {"{enum: [a, [1]], oneOf: [{type: string}, {type: integer}]}", nil, true, ""}, + "NullMember": {"{enum: [a, null], oneOf: [{type: [string, 'null']}, {type: integer}]}", []string{"a"}, true, ""}, + "Passed": {"{enum: [a, b], oneOf: [{type: string}, {type: integer}], anyOf: [{type: string}]}", both, true, ""}, + "AtBound": {"{enum: [" + strings.Join(members(16), ", ") + "], anyOf: [" + branches(256) + "]}", members(16), false, ""}, + "PastBound": {"{enum: [" + strings.Join(members(17), ", ") + "], anyOf: [" + branches(241) + "]}", members(17), true, ""}, + "Noted": {"{enum: [a, b], oneOf: [{type: string, description: d}, {type: integer}]}", both, true, ""}, + "Anchored": {"{enum: [a, b], oneOf: [{type: string, $anchor: s}, {type: integer}]}", both, false, ""}, + "PastSchemas": {"{enum: [a], anyOf: [" + branches(257) + "]}", []string{"a"}, true, ""}, + }, + "3.0.3": { + "Later": {"{enum: [a, b], oneOf: [{const: a}, {type: integer}]}", both, true, ""}, + "LaterBeside": {"{enum: [abc, d], oneOf: [{type: string, maxLength: 2, const: d}, {type: integer}]}", []string{"d"}, true, `"abc"`}, + "UnreadKeywords": {"{enum: [1, 2], oneOf: [{type: number, exclusiveMinimum: true}, {type: string}]}", nil, true, ""}, + }, + } { + t.Run(version, func(t *testing.T) { + t.Parallel() + var written strings.Builder + written.WriteString(" StrRef: {$ref: '#/components/schemas/Str'}\n Str: {type: string}\n") + written.WriteString(" LoopA: {$ref: '#/components/schemas/LoopB'}\n LoopB: {$ref: '#/components/schemas/LoopA'}\n") + if version == "3.1.0" { + written.WriteString(" Anything: true\n") + } + for name, row := range rows { + written.WriteString(" " + name + ": " + row.schema + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer(version, written.String())) + for name, row := range rows { + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) + if row.members != nil { + assert.Equal(t, row.members, enumStrings(t, typeDef, name), name) + } + _, keptOneOf := typeDef.Common().Unmodeled["openapi:oneOf"] + _, keptAnyOf := typeDef.Common().Unmodeled["openapi:anyOf"] + assert.Equal(t, row.kept, keptOneOf || keptAnyOf, "%s: the union is kept", name) + _, narrowed := typeDef.Common().Unmodeled["openapi:enum"] + assert.Equal(t, row.refused != "", narrowed, "%s: the enum is kept where the node narrows it", name) + refused := refusedMembersOf(diags, name) + if row.refused == "" { + assert.Empty(t, refused, name) + continue + } + require.Len(t, refused, 1, name) + assert.Contains(t, refused[0].Message, row.refused+" satisfies", name) + } + }) + } +} + +// refusedMembersOf returns the unsatisfiable-schema warnings at the component +// name itself, where the members of its value set a union refuses are +// reported, and at a member of its enum or its const, where none is. +func refusedMembersOf(diags []ir.Diagnostic, name string) []ir.Diagnostic { + var out []ir.Diagnostic + for _, diagnostic := range warningsUnder(diags, name) { + at := string(diagnostic.Provenance.Pointer) + if diagnostic.Code == diag.UnsatisfiableSchema && (at == "/components/schemas/"+name || + strings.Contains(at, "/enum/") || strings.HasSuffix(at, "/const")) { + out = append(out, diagnostic) + } + } + return out +} + +// TestTypedBranches_AMemberTwoBranchesOfAOneOfAdmitIsReportedSo holds the +// report of a member a oneOf refuses for satisfying two of its branches to +// that count, and that of one satisfying none to its keyword, and the one +// report of a set the oneOf refuses whole to each member's count. +func TestTypedBranches_AMemberTwoBranchesOfAOneOfAdmitIsReportedSo(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", + " Two: {enum: [a, b], oneOf: [{type: string}, {enum: [a]}]}\n"+ + " None: {enum: [a, b], anyOf: [{enum: [a]}, {type: integer}]}\n"+ + " Every: {enum: [a, bb], oneOf: [{type: string, maxLength: 1}, {maxLength: 1}]}\n")) + two, none := refusedMembersOf(diags, "Two"), refusedMembersOf(diags, "None") + require.Len(t, two, 1) + require.Len(t, none, 1) + assert.Equal(t, "/components/schemas/Two", string(two[0].Provenance.Pointer)) + assert.Contains(t, two[0].Message, `the oneOf beside it, which JSON Schema conjoins with it and which admits a value `+ + `satisfying exactly one of its branches ("a" satisfies 2)`) + assert.Contains(t, none[0].Message, `the anyOf beside it, which JSON Schema conjoins with it and which admits a value `+ + `satisfying one of its branches ("b" satisfies none)`) + every := warningsUnder(diags, "Every") + require.Len(t, every, 1) + assert.Equal(t, "/components/schemas/Every", string(every[0].Provenance.Pointer)) + assert.Contains(t, every[0].Message, `exactly one of its branches ("a" satisfies 2, "bb" satisfies none)`) +} + +// referencedUnionComponents are the components the referenced-union tests name: +// a oneOf refusing a single character, which both its branches admit, a +// string, the top type and an anyOf of 241 branches. +func referencedUnionComponents(t *testing.T) string { + t.Helper() + return " U: {oneOf: [{type: string, maxLength: 1}, {type: string, minLength: 1}]}\n" + + " Str: {type: string}\n Anything: true\n" + + " Wide: {anyOf: [" + strings.Repeat("{type: string}, ", 240) + "{type: string}]}\n" +} + +// TestReferencedUnions_JudgeASetAsOneWrittenBesideIt holds that the members of +// a value set are judged against the union a $ref it is conjoined with lands +// on, beside it or as an allOf entry, a second union passed over among them: +// one it refuses is left out and reported. None is where every member +// satisfies it, the $ref lands on no union, on the top type or nowhere, a +// member is no scalar, or the judgments pass their bound. +func TestReferencedUnions_JudgeASetAsOneWrittenBesideIt(t *testing.T) { + t.Parallel() + refU := "allOf: [{$ref: '#/components/schemas/U'}]" + seventeen := make([]string, 0, 17) + for i := range 17 { + seventeen = append(seventeen, "m"+strings.Repeat("x", i)) + } + rows := map[string]typedSetRow{ + "Beside": {"{$ref: '#/components/schemas/U', enum: [a, bb]}", []string{"bb"}, false, `"a"`}, + "Entry": {"{enum: [a, bb], " + refU + "}", []string{"bb"}, false, `"a"`}, + "Satisfied": {"{enum: [bb], " + refU + "}", []string{"bb"}, false, ""}, + "NoUnion": {"{enum: [a, bb], allOf: [{$ref: '#/components/schemas/Str'}]}", []string{"a", "bb"}, false, ""}, + "Anything": {"{enum: [a, bb], allOf: [{$ref: '#/components/schemas/Anything'}]}", []string{"a", "bb"}, false, ""}, + "Unresolved": {"{enum: [a, bb], allOf: [{$ref: '#/components/schemas/Missing'}]}", []string{"a", "bb"}, false, ""}, + "NotScalar": {"{enum: [a, [1]], " + refU + "}", nil, false, ""}, + "Passed": {"{enum: [a, bb], oneOf: [{type: string}, {type: integer}], anyOf: [{type: string}], " + refU + "}", + []string{"bb"}, true, `"a"`}, + "PastBound": {"{enum: [" + strings.Join(seventeen, ", ") + "], allOf: [{$ref: '#/components/schemas/Wide'}]}", + seventeen, false, ""}, + } + var written strings.Builder + written.WriteString(referencedUnionComponents(t)) + for name, row := range rows { + written.WriteString(" " + name + ": " + row.schema + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + for name, row := range rows { + typeDef := typeByName(doc, name) + require.NotNil(t, typeDef, name) + if row.members != nil { + assert.Equal(t, row.members, enumStrings(t, typeDef, name), name) + } + _, keptOneOf := typeDef.Common().Unmodeled["openapi:oneOf"] + assert.Equal(t, row.kept, keptOneOf, "%s: the union is kept", name) + refused := refusedMembersOf(diags, name) + if row.refused == "" { + assert.Empty(t, refused, name) + continue + } + require.Len(t, refused, 1, name) + assert.Equal(t, "/components/schemas/"+name, string(refused[0].Provenance.Pointer), name) + assert.Contains(t, refused[0].Message, row.refused+" satisfies", name) + assert.Contains(t, refused[0].Message, "the oneOf a $ref it is conjoined with names", name) + assert.Equal(t, ir.ReasonValidationOnly, typeDef.Common().Unmodeled["openapi:enum"].Reason, name) + } +} + +// TestReferencedUnions_AWholeRefusalNamesEachRefusingUnion holds the one +// report of a value set refused whole to the union refusing it, one a $ref +// names among them, and, where several refuse its members, to each member's. +// Conjuncts sharing no kind draw their own report and no second. +func TestReferencedUnions_AWholeRefusalNamesEachRefusingUnion(t *testing.T) { + t.Parallel() + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", referencedUnionComponents(t)+ + " Whole: {$ref: '#/components/schemas/U', enum: [a]}\n"+ + " Several: {enum: [a, ccc], oneOf: [{type: string, maxLength: 2}, {type: integer}], "+ + "allOf: [{$ref: '#/components/schemas/U'}]}\n"+ + " Disjoint: {enum: [a, bb], allOf: [{$ref: '#/components/schemas/U'}, {type: integer}]}\n")) + at := func(name string) []string { + var out []string + for _, diagnostic := range diags { + if diagnostic.Code == diag.UnsatisfiableSchema && string(diagnostic.Provenance.Pointer) == "/components/schemas/"+name { + out = append(out, diagnostic.Message) + } + } + return out + } + whole := at("Whole") + require.Len(t, whole, 1) + assert.Contains(t, whole[0], `satisfies the oneOf a $ref it is conjoined with names, which`) + assert.Contains(t, whole[0], `("a" satisfies 2)`) + assert.Contains(t, whole[0], "the $ref is kept verbatim under Unmodeled") + several := at("Several") + require.Len(t, several, 1) + assert.Contains(t, several[0], `"a" satisfies 2 of the branches of the oneOf a $ref it is conjoined with names`) + assert.Contains(t, several[0], `"ccc" satisfies none of the branches of the oneOf beside it`) + disjoint := at("Disjoint") + require.Len(t, disjoint, 1, "conjuncts sharing no kind draw their own report alone") + assert.Contains(t, disjoint[0], "no value satisfies") +} + +// TestReferencedUnions_ARefusalNamesOneUnionInEitherOrder holds the union a +// member's report names, where two unions $refs name both refuse it, to the +// one written first, whichever $ref the allOf writes first. +func TestReferencedUnions_ARefusalNamesOneUnionInEitherOrder(t *testing.T) { + t.Parallel() + refU, refW := "{$ref: '#/components/schemas/U'}", "{$ref: '#/components/schemas/W'}" + _, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", referencedUnionComponents(t)+ + " W: {anyOf: [{type: string, minLength: 3}, {type: boolean}]}\n"+ + " Written: {enum: [a, bb, ccc], allOf: ["+refU+", "+refW+"]}\n"+ + " Reversed: {enum: [a, bb, ccc], allOf: ["+refW+", "+refU+"]}\n")) + written, reversed := refusedMembersOf(diags, "Written"), refusedMembersOf(diags, "Reversed") + require.Len(t, written, 1) + require.Len(t, reversed, 1) + assert.Equal(t, written[0].Message, reversed[0].Message) + assert.Contains(t, written[0].Message, `"a" satisfies 2 of the branches of the oneOf`) +} diff --git a/compilers/openapi/internal/schema/valuesetfilter.go b/compilers/openapi/internal/schema/valuesetfilter.go new file mode 100644 index 000000000..aa22a1223 --- /dev/null +++ b/compilers/openapi/internal/schema/valuesetfilter.go @@ -0,0 +1,503 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "encoding/json/jsontext" + "maps" + "slices" + "strconv" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/compilers/openapi/internal/annotation" + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/ids" + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" + "github.com/dexpace/morphic/compilers/openapi/internal/value" + "github.com/dexpace/morphic/ir" +) + +// unionMember is one member of a union of value sets: its node, where it is +// written below the position, its key (memberOf), its kind, its value, the +// index of the branch writing it first, and whether another branch writes it +// too. +type unionMember struct { + node *yaml.Node + rel jsontext.Pointer + key string + kind kindSet + value ir.Value + branch int + shared bool +} + +// readMembersFilteredByRest is the reading of loweredUnion, a union of value +// sets schema's conjunction chooses beside rest, a body stating no value set +// (readValueSetUnion): one value-set conjunct whose members the body filters +// (restMemberFilter), a branch holding none dead, and members past the enum +// budget none read (lowerFilteredMembersPastBudget). It returns false where +// nothing but notes sits beside the union, a member converts to no value, or +// the members admitted are null alone +// (docs/compilers/openapi.md#union-null-only). +func readMembersFilteredByRest(loweringContext lowering.Ctx, schema *statement.Schema, loweredUnion conjunctionUnion, rest conjunctionRest) (unionReading, bool) { + if !writesBody(loweringContext, schema, rest) { + return unionReading{}, false + } + sets, written := unionValueSets(loweringContext, loweredUnion) + if !loweringContext.Limits.MaxEnumMembers.Admits(written) { + // No member is converted or judged: the budget bounds that cost. + return unionReading{dead: make([]bool, len(loweredUnion.branches())), besideRest: unionMembersFilteredByRest, admittedMembers: &unionAdmittedMembers{pastBudget: written}}, true + } + members, read := unionMembersOf(loweredUnion.keyword, sets) + if !read { + return unionReading{}, false + } + filter := restMemberFilterOf(loweringContext, schema, rest) + admittedMembers := &unionAdmittedMembers{} + out := unionReading{dead: make([]bool, len(loweredUnion.branches())), besideRest: unionMembersFilteredByRest, admittedMembers: admittedMembers} + live := make([]bool, len(out.dead)) + for _, member := range members { + if filter.rejects(member) { + admittedMembers.refused = append(admittedMembers.refused, member) + continue + } + admittedMembers.members = append(admittedMembers.members, member) + live[member.branch] = true + } + for i := range out.dead { + out.dead[i] = !live[i] + } + if len(admittedMembers.members) > 0 && !slices.ContainsFunc(admittedMembers.members, notNull) { + return unionReading{}, false + } + _, admittedMembers.unheld = filteredMemberNotes(loweringContext, loweredUnion, admittedMembers.members, "") + return out, true +} + +// notNull reports whether member is a value other than null. +func notNull(member unionMember) bool { + return member.value.Kind != ir.ValueNull +} + +// writesBody reports whether schema's conjunction writes a body beside its +// unions that says anything of a scalar: a keyword of schema or of an inline +// entry that is no note (writesBesideUnion), or a $ref entry whose target +// admits less than every value, null aside, rest being what the body admits. +func writesBody(loweringContext lowering.Ctx, schema *statement.Schema, rest conjunctionRest) bool { + set := rest.set + return set.kinds&^kindNull != kindAny&^kindNull || set.fixed || len(set.forms) > 0 || set.items != nil || + slices.ContainsFunc(inlineConjuncts(loweringContext, schema), writesBesideUnion) +} + +// unionValueSets returns the schemas of each branch of loweredUnion, a union of +// value sets (branchSchemas), and how many members they write, read with no +// member converted. +func unionValueSets(loweringContext lowering.Ctx, loweredUnion conjunctionUnion) ([][]valueSetSchema, int) { + sets := make([][]valueSetSchema, 0, len(loweredUnion.branches())) + written := 0 + for i, branch := range loweredUnion.branches() { + rel := loweredUnion.keyword.branchAt(loweredUnion.rel, i) + branch := branchSchemas(loweringContext, loweringContext.Statements().Subschema(branch), rel) + for _, set := range branch { + written += len(set.schemaStatement.Enum()) + if set.schemaStatement.Const() != nil { + written++ + } + } + sets = append(sets, branch) + } + return sets, written +} + +// unionMembersOf returns the members the branches of a union of value sets +// written under keyword list in sets, their schemas (unionValueSets), in the +// order they write them, each once, JSON equality judging two alike +// (memberOf): an anyOf's every one, a oneOf's those one branch alone holds. +// It returns false where a member converts to no value. +func unionMembersOf(keyword unionKeyword, sets [][]valueSetSchema) ([]unionMember, bool) { + var all []unionMember + holders := map[string]map[int]bool{} + for i, branch := range sets { + members, read := branchMembers(branch, i) + if !read { + return nil, false + } + for _, member := range members { + if holders[member.key] == nil { + holders[member.key] = map[int]bool{} + all = append(all, member) + } + holders[member.key][i] = true + } + } + for i := range all { + all[i].shared = len(holders[all[i].key]) > 1 + } + if keyword.Exclusive() { + all = slices.DeleteFunc(all, func(member unionMember) bool { return member.shared }) + } + return all, true +} + +// valueSetSchema is one schema of a branch of a union of value sets, the +// branch or a union it nests, and where it is written below the position. +type valueSetSchema struct { + schemaStatement *statement.Statement + rel jsontext.Pointer +} + +// branchSchemas returns the value-set branch schemaStatement, written at rel, +// and the schemas of the unions it nests, at any depth, in the order a +// breadth-first read meets them, which pureValueSets read whole within +// maxValueSetSchemas. +func branchSchemas(loweringContext lowering.Ctx, schemaStatement *statement.Statement, rel jsontext.Pointer) []valueSetSchema { + out := []valueSetSchema{{schemaStatement: schemaStatement, rel: rel}} + for read := 0; read < len(out) && len(out) < maxValueSetSchemas; read++ { + next := out[read] + for _, union := range unionKeywords { + for i, branch := range union.branchesOf(next.schemaStatement.Schema) { + out = append(out, valueSetSchema{schemaStatement: loweringContext.Statements().Subschema(branch), rel: union.branchAt(next.rel, i)}) + } + } + } + return out[:min(len(out), maxValueSetSchemas)] +} + +// branchMembers returns the members sets, the schemas of the branch of index +// branch (branchSchemas), list in their enums and consts, and false where a +// member converts to no value. +func branchMembers(sets []valueSetSchema, branch int) ([]unionMember, bool) { + var out []unionMember + for _, set := range sets { + for i, node := range set.schemaStatement.Enum() { + out = append(out, unionMember{node: node, rel: set.rel + ids.Ptr("enum", strconv.Itoa(i)), branch: branch}) + } + if constant := set.schemaStatement.Const(); constant != nil { + out = append(out, unionMember{node: constant, rel: set.rel + ids.Ptr("const"), branch: branch}) + } + } + for i := range out { + val, err := value.FromNode(out[i].node) + key, kind, keyed := memberOf(out[i].node) + if err != nil || !keyed { + return nil, false + } + out[i].value, out[i].key, out[i].kind = val, key, kind + } + return out, true +} + +// restMemberFilter filters the members of a union of value sets by the body +// beside it: by the kinds the rest of its conjunction admits, and by schema, +// its inline entries and what its $refs reach (referredOf), each a branch of +// judge, read as a union's branch is (memberJudge.branchFacts). +type restMemberFilter struct { + kinds kindSet + judge *memberJudge +} + +// restMemberFilterOf returns the filter of the body of schema's conjunction, +// rest being what that body admits, each conjunct read in the document +// holding it. +func restMemberFilterOf(loweringContext lowering.Ctx, schema *statement.Schema, rest conjunctionRest) restMemberFilter { + judge := newJudge() + for i, conjunctSchema := range slices.Concat(inlineConjuncts(loweringContext, schema), referredOf(loweringContext, schema).conjunctList) { + at := loweringContext + if site, known := siteOf(conjunctSchema); known { + at, _ = lowering.InDocument(loweringContext, site.Doc) + } + path := "conjunct/" + strconv.Itoa(i) + if judge.branchFacts(at, path, conjunctSchema) { + judge.branches = append(judge.branches, ir.TypeRef{Target: compile.TypeID("union-judge", path)}) + } + } + judge.reader = judge.newReader() + return restMemberFilter{kinds: rest.kinds, judge: judge} +} + +// judgeLookup is the lookup of a judge's own nodes, which are in no +// document and so in no type registry. +func judgeLookup(judgeNodes []ir.TypeDef) func(ir.TypeID) (ir.TypeDef, bool) { + return func(id ir.TypeID) (ir.TypeDef, bool) { + at := slices.IndexFunc(judgeNodes, func(judgeNode ir.TypeDef) bool { return judgeNode.Common().ID == id }) + if at < 0 { + return nil, false + } + return judgeNodes[at], true + } +} + +// rejects reports whether filter rejects member: its kind is none the body +// admits, or, a scalar, a conjunct refuses it. The judge reads scalars alone, +// and no bound it reads says anything of null, an array or an object. +func (filter restMemberFilter) rejects(member unionMember) bool { + return member.kind&filter.kinds == 0 || (member.kind&(kindArray|kindObject|kindNull) == 0 && slices.ContainsFunc(filter.judge.branches, func(conjunct ir.TypeRef) bool { + return filter.judge.reader.Admits(conjunct, member.value) == ir.AdmitsNo + })) +} + +// lowerMembersFilteredByRest lowers schema, written at pointer, whose +// conjunction's union of value sets is one value-set conjunct +// (unionMembersFilteredByRest): what a flat enum of the members the body admits +// lowers to (enumNode), each holding what its branch says of it +// (filteredMemberNotes), with the union kept once where it says more, and each +// member the body refuses reported. +func lowerMembersFilteredByRest(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement, +) (builtPosition, []ir.Diagnostic) { + reading := readLoweredUnion(loweringContext, schema) + loweredUnion, _ := readConjunction(loweringContext, schema).loweredUnion() + admittedMembers := reading.admittedMembers + if admittedMembers.pastBudget > 0 { + return lowerFilteredMembersPastBudget(loweringContext, types, schema, pointer, placement, loweredUnion.keyword, admittedMembers.pastBudget) + } + site := placedValueSet(schema, pointer, placement) + site.unionMembers = true + takes := filteredMembersBoundKinds(loweringContext, schema, admittedMembers.members) + notes, _ := filteredMemberNotes(loweringContext, loweredUnion, admittedMembers.members, pointer) + entries := make([]enumEntry, 0, len(admittedMembers.members)) + for i, member := range admittedMembers.members { + entries = append(entries, enumEntry{node: member.node, val: member.value, at: pointer + member.rel, index: i, notes: notes[i]}) + } + var diags []ir.Diagnostic + built := internNode(loweringContext, types, placement.pointer(pointer), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + typeDef, nodeDiags := enumNode(loweringContext, types, site, common, entries, takes, builtKeeps{}) + diags = append(diags, nodeDiags...) + homes := boundHomes{value: takes}.heldOver(valueSetNodeRoot(loweringContext, site, typeDef, entries), takes) + if enum, isEnum := typeDef.(*ir.Enum); isEnum { + enum.Constraints, diags = withValueSetBounds(loweringContext, site, &enum.Unmodeled, homes, diags, builtKeeps{}) + } + diags = append(diags, keepFilteredUnion(loweringContext, &typeDef.Common().Unmodeled, pointer, loweredUnion, reading)...) + return typeDef, filteredMembersRead(loweringContext, schema, typeDef, homes, keyBit("type")|keyBit(string(loweredUnion.keyword))) + }) + built, unreadDiags := finishUnread(loweringContext, types, schema, pointer, dispatch{}, placement, built, 0) + diags = append(diags, unreadDiags...) + if built.node != nil { + diags = append(diags, keepEntriesUnread(loweringContext, built.node, schema, pointer, built.read)...) + } + return built, append(diags, refusedMembers(loweringContext, pointer, admittedMembers.refused)...) +} + +// lowerFilteredMembersPastBudget lowers schema, written at pointer, whose +// conjunction's union of value sets, written under keyword, lists written +// members, more than the enum budget admits, as an enum past it lowers +// (lowerEnum): to the top type, reported, the union read and kept nowhere, +// since keeping it verbatim costs what the budget refuses. +func lowerFilteredMembersPastBudget(loweringContext lowering.Ctx, types *compile.Types, schema *statement.Schema, pointer jsontext.Pointer, placement nodePlacement, + keyword unionKeyword, written int, +) (builtPosition, []ir.Diagnostic) { + built := internNode(loweringContext, types, placement.pointer(pointer), func(common ir.TypeCommon) (ir.TypeDef, keySet) { + top := &ir.Any{TypeCommon: common} + return top, valueSetReads(loweringContext, schema, top) | keyBit(string(keyword)) + }) + built, diags := finishUnread(loweringContext, types, schema, pointer, dispatch{}, placement, built, 0) + if built.node != nil { + diags = append(diags, keepEntriesUnread(loweringContext, built.node, schema, pointer, built.read)...) + } + return built, append([]ir.Diagnostic{enumPastBudget(loweringContext, pointer, written)}, diags...) +} + +// filteredMembersBoundKinds is the kinds whose value bounds the node a union of +// value sets beside schema lowers to holds, members being those the body +// admits: as a flat enum of them takes them (valueSetSite.boundTakes), those of +// the members, null aside, that schema's position admits, or every scalar kind +// where there is no member. +func filteredMembersBoundKinds(loweringContext lowering.Ctx, schema *statement.Schema, members []unionMember) kindSet { + if len(members) == 0 { + return kindString | kindNumber + } + var listed kindSet + for _, member := range members { + listed |= member.kind + } + return boundKinds(loweringContext, schema) & listed &^ kindNull +} + +// filteredMembersRead adds to read what building typeDef, the node schema's +// union of value sets lowered to holding the bounds homes places, read of +// schema and its inline entries: what a value set's node reads of the schema +// writing it (valueSetReads), and the bounds it holds. +func filteredMembersRead(loweringContext lowering.Ctx, schema *statement.Schema, typeDef ir.TypeDef, homes boundHomes, read keySet) keySet { + read |= valueSetReads(loweringContext, schema, typeDef) + for _, conjunctSchema := range inlineConjuncts(loweringContext, schema) { + read |= valueSetBoundsRead(conjunctSchema, typeDef, homes) + } + return read +} + +// keepFilteredUnion keeps on unmodeled loweredUnion, the union of value sets +// the node written at pointer holds the members of, verbatim once where it says +// what the node does not: as validation logic where a branch says of its +// members what none holds, and degraded where a branch of it is dead, which the +// node holds nothing of. A union the node holds whole is kept nowhere +// (unionReading.heldWhole). +func keepFilteredUnion(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, pointer jsontext.Pointer, + loweredUnion conjunctionUnion, reading unionReading, +) []ir.Diagnostic { + at := pointer + loweredUnion.rel + switch { + case reading.heldWhole(): + return nil + case !slices.Contains(reading.dead, true): + return keepValidationOnlyKeyword(loweringContext, unmodeled, loweredUnion.holder, string(loweredUnion.keyword), at) + } + kept, diags := keepSchemaKeyword(loweringContext, unmodeled, loweredUnion.holder, string(loweredUnion.keyword), ir.ReasonDegradedLowering, at) + if kept { + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, + "a branch of this %s holds no member of the enum this position lowers to, each refused by the rest of the schema "+ + "or, held by another branch too, by the %s itself; kept verbatim under Unmodeled", loweredUnion.keyword, loweredUnion.keyword)) + } + return diags +} + +// refusedMembers reports each of refused, a member of a union of value sets +// the body beside it refuses, written below pointer, as a value no instance of +// the position is. +func refusedMembers(loweringContext lowering.Ctx, pointer jsontext.Pointer, refused []unionMember) []ir.Diagnostic { + out := make([]ir.Diagnostic, 0, len(refused)) + for _, member := range refused { + out = append(out, loweringContext.DiagAt(ir.SeverityWarning, diag.UnsatisfiableSchema, pointer+member.rel, + "member %s of this union is no value the rest of the schema admits, which JSON Schema conjoins with the union, "+ + "so no instance matches it: it is no member of the enum this position lowers to", describeValue(member.value))) + } + return out +} + +// memberNotes is what a branch of a union of value sets writing one member +// alone says of it, which the member holds as that branch written alone holds +// it on its Literal (annotation.Read): its docs, deprecation, examples and +// extensions. +type memberNotes struct { + docs ir.Docs + examples []ir.Example + extensions ir.Unmodeled + deprecated bool +} + +// onMember returns member holding n. +func (n memberNotes) onMember(member ir.EnumMember) ir.EnumMember { + member.Docs, member.Examples, member.Unmodeled = n.docs, n.examples, n.extensions + if n.deprecated { + member.Deprecation = &ir.Deprecation{} + } + return member +} + +// onCommon returns common, a member's Literal's, holding n, where n says +// anything: a Literal no branch says anything of keeps what it holds. +func (n memberNotes) onCommon(common ir.TypeCommon) ir.TypeCommon { + if n.empty() { + return common + } + common.Docs, common.Examples, common.Unmodeled = n.docs, n.examples, n.extensions + if n.deprecated { + common.Deprecation = &ir.Deprecation{} + } + return common +} + +// empty reports whether n says nothing. +func (n memberNotes) empty() bool { + return n.docs.Summary == "" && n.docs.Description == "" && len(n.docs.ExternalDocs) == 0 && len(n.docs.Refs) == 0 && + len(n.examples) == 0 && len(n.extensions) == 0 && !n.deprecated +} + +// filteredMemberNotes returns what each branch of loweredUnion writing one of +// members, the members the body admits, alone says of it (soleMemberNotes), by +// member, and whether a branch says of its members what none of them holds: a +// note or an extension on a branch of several members, of none the body +// admits, or of a member another branch writes, which the union kept holds +// instead (docs/compilers/openapi.md#allof-refinement). What says nothing of a +// value, an identifier or a comment, keeps no union (branchesSayNothingBeside). +func filteredMemberNotes(loweringContext lowering.Ctx, loweredUnion conjunctionUnion, members []unionMember, pointer jsontext.Pointer) ([]memberNotes, bool) { + branches := loweredUnion.branches() + notes, held := make([]memberNotes, len(members)), make([]bool, len(branches)) + for i, member := range members { + notes[i], held[member.branch] = soleMemberNotes(loweringContext, loweredUnion, member, pointer) + } + var unheld []statement.Subschema + for i, branch := range branches { + if !held[i] { + unheld = append(unheld, branch) + } + } + return notes, !branchesSayNothingBeside(loweringContext, unheld) +} + +// soleMemberNotes returns what member's branch of loweredUnion, written below +// pointer, says of it, and true where the branch writes member alone, by its +// own const or an enum of one, no other branch writes it, so no order of the +// branches chooses whose notes it holds, and the branch says nothing of it a +// member cannot hold: no redaction, XML hint or construct kept but an +// extension. +func soleMemberNotes(loweringContext lowering.Ctx, loweredUnion conjunctionUnion, member unionMember, pointer jsontext.Pointer) (memberNotes, bool) { + branch := loweringContext.Statements().Subschema(loweredUnion.branches()[member.branch]) + schema := branch.Schema + sole := schema.Const() != nil && !enumWritten(schema) || enumWritten(schema) && len(schema.Enum()) == 1 && schema.Const() == nil + if !sole || member.shared || declaresUnion(schema) || member.value.Kind == ir.ValueNull { + return memberNotes{}, false + } + site := annotation.At(branch) + site.Dialect = dialectIn(loweringContext.SchemaRules(), schema) + set, reports := annotation.Read(site, pointer+loweredUnion.keyword.branchAt(loweredUnion.rel, member.branch), loweringContext.Place()) + if len(reports) > 0 || set.Sensitive || set.XML != nil || len(set.Unkept) > 0 || slices.ContainsFunc(slices.Collect(maps.Values(set.Unmodeled)), func(entry ir.UnmodeledEntry) bool { + return entry.Reason != ir.ReasonVendorExtension + }) { + return memberNotes{}, false + } + return memberNotes{docs: set.Docs, examples: set.Examples, extensions: set.Unmodeled, deprecated: set.Deprecated}, true +} + +// setHoldsUnion reports whether the node of the value set node, what schema's +// conjunction, rest, admits beside loweredUnion, holds all the union says: no +// branch says anything beside the set (branchesSayNothingBeside), or the set +// is written by inline enums alone, whose node's members each hold what their +// branch says of them (filteredMemberNotes), and none is said of a member the +// node does not hold or of one a const states, which a Literal holds as the +// position's own. +func setHoldsUnion(loweringContext lowering.Ctx, schema *statement.Schema, loweredUnion conjunctionUnion, rest conjunctionRest, node admitted) bool { + if branchesSayNothingBeside(loweringContext, loweredUnion.branches()) { + return true + } + if slices.ContainsFunc(inlineConjuncts(loweringContext, schema), func(conjunctSchema *statement.Schema) bool { return conjunctSchema.Const() != nil }) { + return false + } + if _, written := restSetMembers(loweringContext, schema, rest); !written { + return false + } + // Members no reading converts hold nothing, every branch then unheld. + members, _ := unionMembersOf(loweredUnion.keyword, unionValueSetsOf(loweringContext, loweredUnion)) + held := slices.DeleteFunc(members, func(member unionMember) bool { return !node.hasMember(member.key) }) + _, unheld := filteredMemberNotes(loweringContext, loweredUnion, held, "") + return !unheld +} + +// unionNotesBesideSet returns, by member key, what each branch of the union +// position's conjunction chooses, written at pointer, says of the one member it +// writes alone (soleMemberNotes), where the union's members were judged +// against the value set the rest states (unionReading.judgedBesideSet), and +// none otherwise. +func unionNotesBesideSet(loweringContext lowering.Ctx, position *statement.Schema, pointer jsontext.Pointer) map[string]memberNotes { + loweredUnion, lowersUnion := readConjunction(loweringContext, position).loweredUnion() + if !lowersUnion || !readLoweredUnion(loweringContext, position).judgedBesideSet { + return nil + } + members, _ := unionMembersOf(loweredUnion.keyword, unionValueSetsOf(loweringContext, loweredUnion)) + out := make(map[string]memberNotes, len(members)) + for _, member := range members { + if notes, sole := soleMemberNotes(loweringContext, loweredUnion, member, pointer); sole { + out[member.key] = notes + } + } + return out +} + +// unionValueSetsOf returns the schemas of each branch of loweredUnion +// (unionValueSets), read with no member converted. +func unionValueSetsOf(loweringContext lowering.Ctx, loweredUnion conjunctionUnion) [][]valueSetSchema { + sets, _ := unionValueSets(loweringContext, loweredUnion) + return sets +} diff --git a/compilers/openapi/internal/schema/valuesetfilter_internal_test.go b/compilers/openapi/internal/schema/valuesetfilter_internal_test.go new file mode 100644 index 000000000..c2f53817d --- /dev/null +++ b/compilers/openapi/internal/schema/valuesetfilter_internal_test.go @@ -0,0 +1,36 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/compile" + "github.com/dexpace/morphic/ir" +) + +// TestJudgeLookup_FindsOnlyTheJudgesNodes holds the lookup a member judge reads +// its nodes through to the nodes it was given: each by its own ID, and none for +// an ID no node of the judge has. +func TestJudgeLookup_FindsOnlyTheJudgesNodes(t *testing.T) { + t.Parallel() + anyID := ir.PrimitiveTypeID(ir.PrimitiveAny) + primitive := &ir.Primitive{ID: anyID, PrimitiveKind: ir.PrimitiveAny} + branch := &ir.Scalar{ID: compile.TypeID("union-judge", "branch/0"), Base: &ir.TypeRef{Target: anyID}} + lookup := judgeLookup([]ir.TypeDef{primitive, branch}) + + found, held := lookup(anyID) + assert.True(t, held, "a primitive the branches name") + assert.Same(t, primitive, found) + + found, held = lookup(branch.ID) + assert.True(t, held, "a branch's node") + assert.Same(t, branch, found) + + found, held = lookup(compile.TypeID("union-judge", "branch/1")) + assert.False(t, held, "an ID no node of the judge has") + assert.Nil(t, found) +} diff --git a/compilers/openapi/internal/schema/valuesetfilter_test.go b/compilers/openapi/internal/schema/valuesetfilter_test.go new file mode 100644 index 000000000..6e027a682 --- /dev/null +++ b/compilers/openapi/internal/schema/valuesetfilter_test.go @@ -0,0 +1,235 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema_test + +import ( + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers/openapi/internal/diag" + "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" + "github.com/dexpace/morphic/compilers/openapi/internal/schema" + "github.com/dexpace/morphic/ir" +) + +// TestValueSetUnion_BesideABodyIsTheEnumTheBodyAdmits holds a union of value +// sets beside a body stating none to the Enum of its members the body admits: +// an anyOf's every branch's, consts and nested unions among them, a oneOf's +// those one branch alone holds, 2 and 2.0 one; a member a bound or a pattern +// refuses left out and reported, one only an unread pattern bounds kept; an +// entry's bounds held too. Two kinds make the Union of literals, minted apart, +// and null is the reference's. A member converting to no value leaves the +// union; a body refusing all, the empty Enum. A dead branch keeps the union. +func TestValueSetUnion_BesideABodyIsTheEnumTheBodyAdmits(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Any: {type: string, anyOf: [{enum: [a, b]}, {const: c}, {oneOf: [{const: d}], anyOf: [{const: e}]}]} + EntryBound: {allOf: [{maxLength: 1}], anyOf: [{enum: [a]}, {enum: [bb]}]} + None: {type: string, maxLength: 0, anyOf: [{enum: [a]}]} + Tagged: {type: string, anyOf: [{enum: [a, !acme x]}, {enum: [b]}]} + One: {type: number, oneOf: [{enum: [1, 2]}, {enum: [2.0, 3]}]} + Refused: {type: string, maxLength: 1, oneOf: [{enum: [a]}, {enum: [bb]}]} + Entry: {allOf: [{type: integer, maximum: 2}], anyOf: [{enum: [1, 3]}, {enum: [2]}]} + Pattern: {type: string, pattern: '^a', anyOf: [{enum: [ab]}, {enum: [b]}]} + PatternUnread: {type: string, pattern: '^(?=a)', anyOf: [{enum: [ab]}, {enum: [b]}]} + Mixed: {maxLength: 3, anyOf: [{enum: [a]}, {enum: [1]}]} + Null: {type: [string, 'null'], anyOf: [{enum: [a]}, {enum: [null]}]} +`)) + openapitest.RequireNoErrorDiags(t, diags) + for name, want := range map[string][]string{ + "Any": {"a", "b", "c", "d", "e"}, "One": {"1", "3"}, "Refused": {"a"}, "Entry": {"1", "2"}, "Pattern": {"ab"}, "PatternUnread": {"ab", "b"}, + "EntryBound": {"a"}, "None": nil, "Null": {"a"}, + } { + enum, ok := typeByName(doc, name).(*ir.Enum) + require.True(t, ok, "%s is the Enum of its members; got %T", name, typeByName(doc, name)) + var got []string + for _, member := range enum.Members { + got = append(got, member.Value.String+string(member.Value.Number)) + } + assert.Equal(t, want, got, name) + kept := map[string]bool{"Refused": true, "Pattern": true, "EntryBound": true, "None": true}[name] + assert.Equal(t, kept, len(enum.Unmodeled) == 1, "%s keeps the union once where a branch holds no member", name) + assert.LessOrEqual(t, len(enum.Unmodeled), 1, name) + } + entry := typeByName(doc, "Entry").(*ir.Enum) + require.NotNil(t, entry.Constraints) + assert.Equal(t, ir.BigVal("2"), *entry.Constraints.Max, "the entry's bound is the Enum's") + assert.Equal(t, ir.ReasonDegradedLowering, typeByName(doc, "Refused").Common().Unmodeled["openapi:oneOf"].Reason) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Refused/oneOf/1/enum/0")) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Pattern/anyOf/1/enum/0")) + assert.True(t, openapitest.HasDiagCodeAt(diags, diag.UnsatisfiableSchema, "/components/schemas/Entry/anyOf/0/enum/1")) + mixed, ok := typeByName(doc, "Mixed").(*ir.Union) + require.True(t, ok, "members of two kinds are a Union of literals; got %T", typeByName(doc, "Mixed")) + require.Len(t, mixed.Variants, 2) + for i, at := range []string{"/components/schemas/Mixed/anyOf/0/enum/0", "/components/schemas/Mixed/anyOf/1/enum/0"} { + assert.Equal(t, ir.TypeID("type/composed"+at), mixed.Variants[i].Type.Target, "the Literal is minted apart from its branch") + } + assert.Empty(t, mixed.Unmodeled, "the node holds the union whole") + _, isEnum := typeByName(doc, "Tagged").(*ir.Enum) + assert.False(t, isEnum, "a member converting to no value leaves the union as it was") +} + +// TestValueSetUnion_ANullMemberIsTheFlatEnumsNull holds a null member of a +// union of value sets beside a body to the null a flat enum listing it gives: +// the reference admits it, the policy lifting no branch for it, so no +// inferred-nullable finding is drawn. Members left null alone admit null +// alone, as a union of null branches does. +func TestValueSetUnion_ANullMemberIsTheFlatEnumsNull(t *testing.T) { + t.Parallel() + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", ` Listed: {maxLength: 3, anyOf: [{enum: [a]}, {enum: [1, null]}]} + Alone: {type: ['null'], oneOf: [{enum: [null]}]} + Holder: {type: object, properties: {listed: {$ref: '#/components/schemas/Listed'}}} +`)) + openapitest.RequireNoErrorDiags(t, diags) + holder, ok := typeByName(doc, "Holder").(*ir.Model) + require.True(t, ok) + require.Len(t, holder.Properties, 1) + assert.True(t, holder.Properties[0].Type.Nullable, "the null member is the reference's") + assert.False(t, openapitest.HasDiag(diags, diag.InferredNullable), "no branch is lifted for the null") + alone, ok := typeByName(doc, "Alone").(*ir.Enum) + require.True(t, ok, "null alone is the closed empty Enum; got %T", typeByName(doc, "Alone")) + assert.Empty(t, alone.Members) + assert.Equal(t, ir.ReasonDegradedLowering, alone.Unmodeled["openapi:oneOf"].Reason, "kept as a union of null branches keeps it") +} + +// TestValueSetUnion_AnIdentifierOnABranchSaysNothing holds a union of value +// sets, beside an enum or beside a body stating none, under a oneOf and an +// anyOf, to lowering alike whether or not a branch writes an anchor, an +// identifier or a comment beside its value set: none of them says anything +// of a value, so the branch is a value set still. +func TestValueSetUnion_AnIdentifierOnABranchSaysNothing(t *testing.T) { + t.Parallel() + for _, keyword := range []string{"oneOf", "anyOf"} { + for _, body := range []string{"type: string, enum: [a, b, c]", "type: string, maxLength: 1"} { + for _, beside := range []string{"$anchor: first", "$id: 'https://example.com/first'", "$comment: first"} { + src := " Plain: {" + body + ", " + keyword + ": [{const: a}, {enum: [b, cc]}]}\n" + + " Marked: {" + body + ", " + keyword + ": [{const: a, " + beside + "}, {enum: [b, cc]}]}\n" + doc, diags := schema.LowerSpec(t, openapitest.ComponentSpecVer("3.1.0", src)) + label := keyword + " beside " + body + " with " + beside + assert.Equal(t, valueSetView(typeByName(doc, "Plain")), valueSetView(typeByName(doc, "Marked")), label) + assert.Equal(t, findingsBeneath(diags, "/components/schemas/Plain"), findingsBeneath(diags, "/components/schemas/Marked"), label) + } + } + } +} + +// valueSetView is what a reader of node, a value set's, is given: its kind, +// its members' values, its bounds and the reason of each key it keeps. +func valueSetView(node ir.TypeDef) map[string]any { + view := map[string]any{"kind": node.Kind()} + kept := map[string]ir.UnmodeledReason{} + for key, entry := range node.Common().Unmodeled { + kept[key] = entry.Reason + } + view["kept"] = kept + if enum, isEnum := node.(*ir.Enum); isEnum { + members := make([]ir.Value, 0, len(enum.Members)) + for _, member := range enum.Members { + members = append(members, member.Value) + } + view["members"], view["bounds"] = members, enum.Constraints + } + return view +} + +// findingsBeneath lists the severity and code of each of diags at pointer or beneath +// it, beneath it written relative to pointer, in order. +func findingsBeneath(diags []ir.Diagnostic, pointer string) []string { + var out []string + for _, diagnostic := range diags { + at := string(diagnostic.Provenance.Pointer) + if rest, beneath := strings.CutPrefix(at, pointer); beneath && (rest == "" || strings.HasPrefix(rest, "/")) { + out = append(out, string(diagnostic.Severity)+" "+diagnostic.Code+" "+rest) + } + } + slices.Sort(out) + return out +} + +// TestValueSetUnion_AMemberHoldsWhatItsBranchSaysOfIt holds a union of value +// sets beside a body stating none, in every spelling and in either order, to +// the Enum whose members hold what the branch writing each alone says of it, +// its docs, deprecation, examples and extensions, as the union written alone +// gives them: the union is kept nowhere where the node holds all it writes, +// as validation logic where a branch of several members says something no +// member holds, and degraded where a member two branches write takes the +// notes of neither, so no order of them chooses. +func TestValueSetUnion_AMemberHoldsWhatItsBranchSaysOfIt(t *testing.T) { + t.Parallel() + for name, row := range map[string]struct { + union string + docs map[string]ir.Docs + kept ir.UnmodeledReason + }{ + "Consts": {"oneOf: [{const: a, title: A, description: dA, deprecated: true, examples: [a], x-k: 1}, {const: b, title: B, description: dB}]", + map[string]ir.Docs{"a": {Summary: "A", Description: "dA"}, "b": {Summary: "B", Description: "dB"}}, ""}, + "EnumOfOne": {"anyOf: [{enum: [a], description: dA}, {const: b}]", map[string]ir.Docs{"a": {Description: "dA"}}, ""}, + "SetNoted": {"oneOf: [{enum: [a, b], description: set}, {const: c, description: dC}]", map[string]ir.Docs{"c": {Description: "dC"}}, ir.ReasonValidationOnly}, + "Shared": {"anyOf: [{const: a, description: one}, {const: a, description: two}]", nil, ir.ReasonDegradedLowering}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + spellings := openapitest.Spellings("type: string", row.union) + for spelling, text := range openapitest.Reversed("type: string", row.union) { + spellings[spelling+"Reversed"] = text + } + var written strings.Builder + for spelling, text := range spellings { + written.WriteString(" " + spelling + ": " + text + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + keyword, _, _ := strings.Cut(row.union, ":") + for spelling := range spellings { + enum, ok := typeByName(doc, spelling).(*ir.Enum) + require.True(t, ok, "%s: got %T", spelling, typeByName(doc, spelling)) + for _, member := range enum.Members { + assert.Equal(t, row.docs[member.Value.String], member.Docs, "%s: %s", spelling, member.Value.String) + assert.Equal(t, name == "Consts" && member.Value.String == "a", member.Deprecation != nil, "%s: %s", spelling, member.Value.String) + assert.Equal(t, name == "Consts" && member.Value.String == "a", len(member.Examples) == 1 && member.Unmodeled["openapi:x-k"].Reason == ir.ReasonVendorExtension, + "%s: %s", spelling, member.Value.String) + } + kept := keptUnder(enum.Unmodeled, keyword) + assert.Equal(t, row.kept != "", kept, "%s: the union is kept where it says more than the node", spelling) + if row.kept != "" { + assert.Equal(t, row.kept, enum.Unmodeled["openapi:"+keyword].Reason, spelling) + } + assert.Empty(t, warningsUnder(diags, spelling), spelling) + } + }) + } +} + +// TestValueSetUnion_ALiteralHoldsWhatItsBranchSaysOfIt holds a union of value +// sets of two kinds beside a body stating none, in every spelling, to the +// Union of literals each of which holds what the branch writing it alone says +// of it, its docs and deprecation among it, as the union written alone gives +// its literals, the union kept nowhere. +func TestValueSetUnion_ALiteralHoldsWhatItsBranchSaysOfIt(t *testing.T) { + t.Parallel() + const union = "oneOf: [{const: a, description: dA, deprecated: true}, {const: 1, description: d1}]" + spellings := openapitest.Spellings("type: [string, integer]", union) + var written strings.Builder + for spelling, text := range spellings { + written.WriteString(" " + spelling + ": " + text + "\n") + } + doc, diags := parseFull(t, openapitest.ComponentSpecVer("3.1.0", written.String())) + openapitest.RequireNoErrorDiags(t, diags) + for spelling := range spellings { + node, ok := typeByName(doc, spelling).(*ir.Union) + require.True(t, ok, "%s: got %T", spelling, typeByName(doc, spelling)) + var described []string + var deprecated []bool + for _, variant := range node.Variants { + common := doc.Types[variant.Type.Target].Common() + described, deprecated = append(described, common.Docs.Description), append(deprecated, common.Deprecation != nil) + } + assert.Equal(t, []string{"dA", "d1"}, described, spelling) + assert.Equal(t, []bool{true, false}, deprecated, spelling) + assert.False(t, keptUnder(node.Unmodeled, "oneOf"), spelling) + } +} diff --git a/compilers/openapi/internal/schema/valuesetunion.go b/compilers/openapi/internal/schema/valuesetunion.go new file mode 100644 index 000000000..bc9e2c325 --- /dev/null +++ b/compilers/openapi/internal/schema/valuesetunion.go @@ -0,0 +1,118 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "slices" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// maxValueSetSchemas bounds the schemas pureValueSets reads of one union, its +// branches and the unions they nest. +const maxValueSetSchemas = 256 + +// readValueSetUnion reads loweredUnion, where every branch is a value set +// (pureValueSets), as one value-set conjunct: its branches' members, a oneOf's +// those one branch alone holds (docs/compilers/openapi.md#allof-refinement). +// Beside a union passed over, it reads a rest stating a value set, which that +// union narrows (restOfConjunction), and keeps the union chosen, saying nothing +// or not, as the one passed over is kept beside it. It returns false for any +// other union, which the branches' kinds decide. +func readValueSetUnion(loweringContext lowering.Ctx, schema *statement.Schema, conjunctionRead conjunction, loweredUnion conjunctionUnion, rest conjunctionRest, +) (unionReading, bool) { + passed := len(conjunctionRead.passed()) > 0 + if passed && !rest.set.fixed || !pureValueSets(loweringContext, loweredUnion.branches()) { + return unionReading{}, false + } + if !rest.set.fixed { + return readMembersFilteredByRest(loweringContext, schema, loweredUnion, rest) + } + admissionReaderValue := newAdmissionReader(loweringContext) + union := admissionReaderValue.union(loweredUnion.branches()) + if loweredUnion.keyword.Exclusive() { + union = admissionReaderValue.matchedOnce(loweredUnion.branches(), union) + } + if admissionReaderValue.incomplete() { + // A read past the admission's bounds weighs the branches by kind. + return unionReading{}, false + } + out := unionReading{dead: make([]bool, len(loweredUnion.branches())), judgedBesideSet: true} + // A set the union passed over leaves no member lies within every union + // and holds no value: the node holds none. + within := admissionReaderValue.setWithin(rest.set, union) && (!passed || rest.set.size() > 0) + if within && !passed && branchesSayNothingBeside(loweringContext, loweredUnion.branches()) { + out.besideRest = unionSaysNothing + return out, true + } + for i, branch := range loweredUnion.branches() { + out.dead[i] = admissionReaderValue.of(loweringContext.Statements().Subschema(branch)).and(rest.set).size() == 0 + } + out.besideRest = unionKeptByRest + node := rest.set + if !within { + node = rest.set.and(union) + out.sharedMembers = &unionSharedMembers{members: node} + } + if !passed && !slices.Contains(out.dead, true) && setHoldsUnion(loweringContext, schema, loweredUnion, rest, node) { + out.besideRest = unionSaysNothing + } + return out, true +} + +// pureValueSets reports whether every one of branches is an inline value set: +// an enum, a const or a union of such schemas, beside which nothing says +// anything. A read past maxValueSetSchemas is none. +func pureValueSets(loweringContext lowering.Ctx, branches []statement.Subschema) bool { + pending := slices.Clone(branches) + for read := 0; len(pending) > 0; read++ { + if read == maxValueSetSchemas { + return false + } + schemaStatement := loweringContext.Statements().Subschema(pending[len(pending)-1]) + pending = pending[:len(pending)-1] + if schemaStatement.Ref != nil || !stated(schemaStatement.Schema) || !writesValueSetOnly(schemaStatement.Schema) { + return false + } + choice := schemaStatement.ChoiceKeywords() + pending = append(pending, choice.OneOf...) + pending = append(pending, choice.AnyOf...) + } + return true +} + +// writesValueSetOnly reports whether schema writes an enum, a const or a union, +// and nothing else saying anything of a value. +func writesValueSetOnly(schema *statement.Schema) bool { + sets := false + for _, key := range schema.Keys { + switch { + case key.Name == "enum", key.Name == "const", isUnionKeyword(key.Name): + sets = true + case keySaysNothing(schema, key): + default: + return false + } + } + return sets +} + +// matchedOnce is union, what branches admit together, less each member more +// than one of them holds, which a oneOf refuses. +func (reader *admissionReader) matchedOnce(branches []statement.Subschema, union admitted) admitted { + held := map[string]int{} + for _, branch := range branches { + for key := range reader.of(reader.loweringContext.Statements().Subschema(branch)).members { + held[key]++ + } + } + out := admitted{kinds: union.kinds, fixed: true, values: map[string]kindSet{}} + for key, kind := range union.members { + if held[key] == 1 { + out.values[key] = kind + } + } + return out +} diff --git a/compilers/openapi/internal/schema/variant.go b/compilers/openapi/internal/schema/variant.go index 37ab68e9c..7e9e5f2fe 100644 --- a/compilers/openapi/internal/schema/variant.go +++ b/compilers/openapi/internal/schema/variant.go @@ -6,6 +6,8 @@ package schema import ( "encoding/json/jsontext" "slices" + "strconv" + "strings" "github.com/dexpace/morphic/compilers/compile" "github.com/dexpace/morphic/compilers/openapi/internal/annotation" @@ -18,138 +20,263 @@ import ( // buildsVariants reports whether a Union schema lowers to holds variants schema // builds itself, each conjoining what schema writes: a type array's -// (lowerUnion) or a distributed composition's (lowerDistributedUnion). A union -// of schema's oneOf or anyOf alone (lowerOneOfAnyOf) holds the nodes its -// branches lowered to instead. It reads what lowerSchemaBody dispatches on. +// (lowerTypeArrayUnion) or a distributed composition's (lowerDistributedUnion). +// A union of schema's oneOf or anyOf alone (lowerOneOfAnyOf) holds the nodes +// its branches lowered to instead. It reads what lowerSchemaBody dispatches on. func buildsVariants(loweringContext lowering.Ctx, schema *statement.Schema) bool { return !declaresUnion(schema) || hasUnionSiblings(loweringContext, schema) } -// lowerDistributedUnion emits the Union that is the schema's value, distributing -// the sibling composition across the variants of u: `S ∧ (X | Y)` becomes -// `(S ∧ X) | (S ∧ Y)`. Each variant is a Model classifying S's Base/Mixins and -// own properties (docs/ir/models.md#composition-beside-a-union) alongside its -// branch, so the composition is carried on every variant rather than merged -// into one or dropped. A union an allOf entry writes is the entry's to give, -// not residue each variant keeps (allOfComposition.conjoins). -func lowerDistributedUnion(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, unionAtValue unionAt, pointer jsontext.Pointer, - fin finisher, -) (ir.TypeID, []ir.Diagnostic) { +// lowerDistributedUnion emits the Union that is the schema's value, +// distributing the sibling composition across the variants of unionSite: +// `S ∧ (X | Y)` becomes `(S ∧ X) | (S ∧ Y)`. Each variant is a Model +// classifying S's Base/Mixins and own properties +// (docs/ir/models.md#composition-beside-a-union) alongside its branch, so the +// composition is carried on every variant rather than merged into one or +// dropped. A union an allOf entry writes is the entry's to give, not an unread +// keyword each variant keeps (allOfComposition.conjoins), and what the entries +// keep beside the composition the Union keeps once (keepEntryUnreadKeywords). +func lowerDistributedUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, unionSite loweredUnionSite, pointer jsontext.Pointer, +) (builtPosition, []ir.Diagnostic) { var diags []ir.Diagnostic - var kept finished - unionAtValue.distributed = true - unionAtValue.dead = deadBranches(loweringContext, schema, unionAtValue.holder) - unionAtValue.deadRoutes = deadRoutesOf(loweringContext, unionAtValue) - id := internNode(loweringContext, ts, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { - body := composedBody{schema: schema, comp: readAllOf(loweringContext, schema, pointer), - foldedEntries: positionFoldedEntries(loweringContext, schema, pointer, ir.TypeRef{}), inferred: bodyKindInferred(loweringContext, schema), union: unionAtValue} - diags = append(diags, diagDisjointConjuncts(loweringContext, body.comp, composedShape)...) - diags = append(diags, keepDeadBranches(loweringContext, &common.Unmodeled, schema, unionAtValue, pointer)...) - def, unionDiags := buildUnion(loweringContext, ts, unionAtValue, common, - func(b *statement.Statement, vptr jsontext.Pointer) ir.TypeRef { - ref, variantDiags := composedVariant(loweringContext, ts, depth, body, b, vptr) + var variantCloses bool + var pendingKeeps annotation.PendingKeeps + unionSite.distributed = true + unionSite.dead = deadBranches(loweringContext, schema, unionSite.holder) + unionSite.deadRoutes = deadRoutesOf(loweringContext, unionSite) + built := internNode(loweringContext, types, pointer, func(common ir.TypeCommon) (ir.TypeDef, keySet) { + comp := readAllOf(loweringContext, schema, pointer) + body := composedBody{schema: schema, comp: comp, homes: comp.homes, + flattenedEntries: positionFlattenedEntries(loweringContext, schema, pointer, ir.TypeRef{}), inferred: bodyKindInferred(loweringContext, schema), union: unionSite, + byKind: readLoweredUnion(loweringContext, schema).besideRest == unionSplitByKind} + diags = append(diags, diagDisjointConjuncts(loweringContext, schema, body.comp, distributedShape)...) + diags = append(diags, keepDeadBranches(loweringContext, &common.Unmodeled, schema, unionSite, pointer).Diagnostics()...) + diags = append(diags, keepEntryUnreadKeywords(loweringContext, &pendingKeeps, schema, comp)...) + diags = append(diags, diagDistributedCatchAll(loweringContext, &common.Unmodeled, schema, comp, unionSite)...) + body.comp.kept = unkept(comp) + def, unionDiags := buildUnion(loweringContext, types, unionSite, common, + func(branch *statement.Statement, variantPointer jsontext.Pointer) ir.TypeRef { + ref, closes, variantDiags := composedVariant(loweringContext, types, depth, body, branch, variantPointer) + variantCloses = variantCloses || closes diags = append(diags, variantDiags...) return ref }) diags = append(diags, unionDiags...) - // Each variant composes the body, reading its members and its bounds. - return def, objectKeys | typeReadAs(schema, statement.KindObject) | boundsRead(schema, body.comp.bounds, nil) - }, keepUnreadAcross(loweringContext, ts, schema, taglessShape(nil, schema, distributedShape), 0, pointer, stand{}, &kept, fin)) - // The union read schema's discriminator, so one it cannot hold says why. - diags = append(diags, kept.diags...) + // Each variant composes the body, reading its members and its bounds, + // a variant split by kind those of its kinds, the type split with them. + read := typeReadAs(schema, statement.KindObject) | boundsRead(schema, body.comp.homes.value|splitKinds(loweringContext, body), nil) + if !composesNoObject(loweringContext, schema) { + read |= objectKeys + } + if body.byKind { + read |= keyBit("type") + } + return def, read + }) + built.pendingKeeps.AddAll(pendingKeeps) + if built.node != nil { + built.closesAfterComposition = variantCloses + diags = append(diags, keepPassedTag(loweringContext, schema, unionSite, pointer, built)...) + // The union read schema's discriminator, so one it cannot hold says why. + diags = append(diags, keepUnreadAcross(loweringContext, schema, taglessShape(nil, schema, distributedShape), 0, pointer, nodePlacement{}, &built)...) + } where := "co-declared with structural keywords" - if unionAtValue.holder != schema { + if unionSite.holder != schema { where = "written on an allOf entry conjoins with the rest of the composition" } - return id, append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.CompositionLowering, pointer, + return built, append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.CompositionLowering, pointer, "oneOf/anyOf %s; the composition is distributed across the union variants", where)) } -// lowerSubtypeUnion lowers s, a subtype a discriminator on an ancestor routes to, -// with the union u it conjoins, beside its allOf or on an entry: s stays the -// Model its composition lowers to, a subtype of that ancestor, and names as its -// last Mixin a Union minted for u (mintUnion), as an allOf naming a component -// holding u composes it (docs/ir/models.md#a-union-a-composition-names). A -// discriminator written beside u is the Union's, so the Model neither lowers nor -// keeps it, unless the Union cannot hold it (tagLocated). The Model's build -// composes the union (composeMixin), so only a position's first lowering does. -func lowerSubtypeUnion(loweringContext lowering.Ctx, ts *compile.Types, depth int, schema *statement.Schema, unionAtValue unionAt, pointer jsontext.Pointer, - fin finisher, -) (ir.TypeID, []ir.Diagnostic) { +// keepPassedTag keeps on the Union built holds the discriminator schema, +// written at pointer, writes beside its allOf where the Union holds the entry's +// instead: keepUnreadAcross reads the Union's as schema's, which would leave +// this one unkept. +func keepPassedTag(loweringContext lowering.Ctx, schema *statement.Schema, unionSite loweredUnionSite, pointer jsontext.Pointer, built builtPosition, +) []ir.Diagnostic { + union, isUnion := built.node.(*ir.Union) + if !isUnion || union.Discriminator == nil || schema.Discriminator() == nil || unionSite.discriminatorPointer == pointer { + return nil + } + return keepTagBeside(loweringContext, &union.Unmodeled, schema, []string{"discriminator"}, pointer) +} + +// keepEntryUnreadKeywords adds to pendingKeeps, the Union's, what each inline +// entry of comp, the allOf schema writes, keeps beside the composition the +// Union distributes, once for every variant +// (docs/compilers/openapi.md#allof-inline-residue). +func keepEntryUnreadKeywords(loweringContext lowering.Ctx, pendingKeeps *annotation.PendingKeeps, schema *statement.Schema, comp allOfComposition, +) []ir.Diagnostic { + var diags []ir.Diagnostic + for i, entry := range comp.entries { + if entry.schema.Ref == nil { + diags = append(diags, keepUnmergedEntry(loweringContext, pendingKeeps, comp, i, nodeShape(ir.KindUnion))...) + } + } + addWritingPendingKeeps(loweringContext, pendingKeeps, schema, comp, comp.kept, nil, textBoundIntersection{}) + return diags +} + +// diagDistributedCatchAll keeps and says once, on unmodeled, the Union's, what +// the closure each variant takes reads of the members it brings, and reports a +// model a $ref entry brings closed by its own closure. +func diagDistributedCatchAll(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, schema *statement.Schema, comp allOfComposition, unionSite loweredUnionSite, +) []ir.Diagnostic { + distributedMembers := func() composedMembers { + members := membersOfConjunction(loweringContext, schema) + branches := unionSite.branches(loweringContext) + seen := map[*statement.Schema]bool{} + for i, branch := range branches { + if unionSite.dead == nil || !unionSite.dead[i] { + members.add(loweringContext, loweringContext.Statements().Subschema(branch), seen) + } + } + return members + } + return append(diagClosedTargets(loweringContext, schema, comp), diagCatchAllScope(loweringContext, unmodeled, comp.catchAll, distributedMembers)...) +} + +// unkept is what comp's entries keep where another node keeps their unread +// keywords: nothing, each entry its own. +func unkept(comp allOfComposition) []keptEntry { + out := make([]keptEntry, len(comp.entries)) + for i, entry := range comp.entries { + out[i] = keptEntry{entry: entry} + } + return out +} + +// lowerSubtypeUnion lowers schema, a subtype a discriminator on an ancestor +// routes to, with the union unionSite it conjoins, beside its allOf or on an +// entry: schema stays the Model its composition lowers to, a subtype of that +// ancestor, and names as its last Mixin a Union minted for unionSite +// (mintUnion), as an allOf naming a component holding that union composes it +// (docs/ir/models.md#a-union-a-composition-names). A discriminator written +// beside the union is the Union's, so the Model neither lowers nor keeps it, +// unless the Union cannot hold it (tagLocated). The Model's build composes the +// union (composeMixin), so only a position's first lowering does. +func lowerSubtypeUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, schema *statement.Schema, unionSite loweredUnionSite, pointer jsontext.Pointer, +) (builtPosition, []ir.Diagnostic) { dispatch := dispatchOf(schema) - dispatch.mixin = &unionAtValue - if unionAtValue.disc != nil && unionAtValue.discAt == pointer && tagLocated(unionAtValue.disc, nil) { - dispatch.said = append(dispatch.said, "discriminator") + dispatch.mixin = &unionSite + if unionSite.discriminator != nil && unionSite.discriminatorPointer == pointer && tagLocated(unionSite.discriminator, nil) { + dispatch.restated = append(dispatch.restated, "discriminator") } - id, diags := lowerDispatched(loweringContext, ts, depth, schema, pointer, dispatch, fin, stand{}) - if dispatch.won != "allOf" { + built, diags := lowerDispatched(loweringContext, types, depth, schema, pointer, dispatch, nodePlacement{}, registeredAtBuild) + if dispatch.lowered != "allOf" { // A discriminator routes to schema through the allOf naming its - // ancestor (subtypeDiscriminatorValue), so no other election composes + // ancestor (subtypeDiscriminatorValue), so no other choice composes // it. diags = append(diags, loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, "internal: a routed subtype lowers through its allOf, so its union is composed into no model")) } where := "co-declared with" - if unionAtValue.holder != schema { + if unionSite.holder != schema { where = "written on an allOf entry of" } - return id, append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.CompositionLowering, pointer, + return built, append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.CompositionLowering, pointer, "oneOf/anyOf %s a schema a discriminator routes to as its subtype; the union is composed as a mixin of the model", where)) } -// mintUnion registers the Union unionAtValue, a routed subtype's union +// mintUnion registers the Union unionSite, a routed subtype's union // (lowerSubtypeUnion), at the keyword its holder writes it under, in the -// composed namespace: no schema stands there, and a variant's path ends in an +// composed namespace: no schema sits there, and a variant's path ends in an // index, a field's in a name. Each variant is its branch's own lowering, as a // union written alone lowers it, so the node is what a component holding -// unionAtValue would be. -func mintUnion(loweringContext lowering.Ctx, ts *compile.Types, depth int, unionAtValue unionAt) (ir.TypeID, []ir.Diagnostic) { - _, key, _ := unionAtValue.branches(loweringContext) - at := unionAtValue.at + ids.Ptr(key) +// unionSite would be, keeping every union the subtype, written at pointer, +// passes over (keepMixinPassedUnions). +func mintUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, unionSite loweredUnionSite, pointer jsontext.Pointer) (ir.TypeID, []ir.Diagnostic) { + key := unionSite.loweredKeyword(loweringContext) + at := key.keywordAt(unionSite.pointer) id := loweringContext.IDs().ComposedType(at) common := commonFor(loweringContext, id, at) - common.Name = compile.NamingHint(compile.SubHint(lowering.NameAt(loweringContext, unionAtValue.at), key)) + common.Name = compile.NamingHint(compile.SubHint(lowering.NameAt(loweringContext, unionSite.pointer), string(key))) var diags []ir.Diagnostic - node, unionDiags := buildUnion(loweringContext, ts, unionAtValue, common, func(b *statement.Statement, vptr jsontext.Pointer) ir.TypeRef { - ref, refDiags := Ref(loweringContext, ts, depth, b, vptr) + node, unionDiags := buildUnion(loweringContext, types, unionSite, common, func(branch *statement.Statement, variantPointer jsontext.Pointer) ir.TypeRef { + ref, refDiags := Ref(loweringContext, types, depth, branch, variantPointer) diags = append(diags, refDiags...) return ref }) - ts.Register(id, node) - return id, slices.Concat(diags, unionDiags) + keptDiags := keepMixinPassedUnions(loweringContext, &node.Unmodeled, unionSite, pointer) + types.Register(id, node) + return id, slices.Concat(diags, unionDiags, keptDiags) +} + +// keepMixinPassedUnions keeps on unmodeled, that of the Union a subtype +// written at pointer composes for unionSite, each union the subtype's +// conjunction passes over that unionSite's holder does not write, as it keeps +// the other union its holder writes, so the Model keeps neither +// (docs/compilers/openapi.md#union-beside-structure). +func keepMixinPassedUnions(loweringContext lowering.Ctx, unmodeled *ir.Unmodeled, unionSite loweredUnionSite, pointer jsontext.Pointer) []ir.Diagnostic { + var diags []ir.Diagnostic + chosen := unionSite.loweredKeyword(loweringContext) + for _, passed := range readConjunction(loweringContext, unionSite.schema).passed() { + if passed.holder == unionSite.holder { + continue + } + at := pointer + passed.rel + if keptUnionReason(loweringContext, unionSite.schema, passed) == ir.ReasonValidationOnly { + diags = append(diags, keepValidationOnlyKeyword(loweringContext, unmodeled, passed.holder, string(passed.keyword), at)...) + continue + } + kept, keptDiags := keepSchemaKeyword(loweringContext, unmodeled, passed.holder, string(passed.keyword), ir.ReasonDegradedLowering, at) + diags = append(diags, keptDiags...) + if kept { + diags = append(diags, loweringContext.DiagAt(ir.SeverityInfo, diag.DegradedConstruct, at, + "%s written here conjoins with the %s this subtype composes as a mixin, and one Union carries one branch set; "+ + "kept verbatim under that Union's Unmodeled", passed.keyword, chosen)) + } + } + return diags } -// composeMixin mints the union unionAtValue, where not nil, and appends it to -// the Mixins of td, the node a routed subtype's build has just made, last, so +// composeMixin mints the union unionSite, where not nil, and appends it to the +// Mixins of typeDef, the node a routed subtype's build has just made, last, so // the $ref entries its source writes classify first. Any node but a Model has -// no Mixins to compose it into, and the lowering that builds it elects one only -// for a subtype that composes, so that is a compiler bug. -func composeMixin(loweringContext lowering.Ctx, ts *compile.Types, depth int, td ir.TypeDef, unionAtValue *unionAt, pointer jsontext.Pointer) []ir.Diagnostic { - if unionAtValue == nil { +// no Mixins to compose it into, and the lowering that builds it chooses one +// only for a subtype that composes, so that is a compiler bug. +func composeMixin(loweringContext lowering.Ctx, types *compile.Types, depth int, typeDef ir.TypeDef, unionSite *loweredUnionSite, pointer jsontext.Pointer) []ir.Diagnostic { + if unionSite == nil { return nil } - mixin, diags := mintUnion(loweringContext, ts, depth, *unionAtValue) - model, isModel := td.(*ir.Model) + mixin, diags := mintUnion(loweringContext, types, depth, *unionSite, pointer) + model, isModel := typeDef.(*ir.Model) if !isModel { return append(diags, loweringContext.DiagAt(ir.SeverityError, diag.InternalInvariant, pointer, - "internal: type %q is not the model a routed subtype composes its union into", td.Common().ID)) + "internal: type %q is not the model a routed subtype composes its union into", typeDef.Common().ID)) } model.Mixins = append(model.Mixins, ir.TypeRef{Target: mixin}) return diags } +// mixinPassedUnions returns the unions the conjunction of schema passes over +// where it lowers as a routed subtype, which the Union it composes as a mixin +// keeps, so the Model keeps none of them. +func mixinPassedUnions(loweringContext lowering.Ctx, schema *statement.Schema) []conjunctionUnion { + passed := readConjunction(loweringContext, schema).passed() + if len(passed) == 0 || readLoweredUnion(loweringContext, schema).besideRest != unionRoutedSubtype { + return nil + } + return passed +} + // composedBody is the schema every distributed variant carries: the enclosing // schema and where it is written. type composedBody struct { - schema *statement.Schema - comp allOfComposition // schema's flattened allOf, built once for every variant - foldedEntries []annotation.FoldedAllOfEntry // what comp's folding entries say of the position, read once too + schema *statement.Schema + comp allOfComposition // schema's flattened allOf, built once for every variant + flattenedEntries []annotation.FlattenedAllOfEntry // what comp's folding entries say of the position, read once too + homes boundHomes // bounds the distributing position holds // inferred marks a schema the kind-inference policy made the model its // variants compose (bodyKindInferred), so a variant over a branch that // declares no object names the policy. inferred bool // union is the union distributed across the body. - union unionAt + union loweredUnionSite + // byKind marks a body split by kind (unionSplitByKind): a branch of a kind + // that is no object takes the body's keywords of that kind alone + // (splitVariant). + byKind bool } // bodyKindInferred reports whether the kind-inference policy made schema, a @@ -164,61 +291,225 @@ func bodyKindInferred(loweringContext lowering.Ctx, schema *statement.Schema) bo return !admitsObjectsAlone(loweringContext, loweringContext.Statements().Read(schema)) } -// admitsObjectsAlone reports whether the document itself declares that st -// admits an object and no other kind, null aside: its read is whole and rests -// on no kind the kind-inference policy read. -func admitsObjectsAlone(loweringContext lowering.Ctx, st *statement.Statement) bool { - admission := admissionOf(loweringContext, st) - return !admission.inferred && !admission.cut && admission.kinds&^kindObject == 0 +// admitsObjectsAlone reports whether the document itself declares that +// schemaStatement admits an object and no other kind, null aside: its read is +// whole and rests on no kind the kind-inference policy read. +func admitsObjectsAlone(loweringContext lowering.Ctx, schemaStatement *statement.Statement) bool { + admission := admissionOf(loweringContext, schemaStatement) + return !admission.inferred && admission.kinds&^kindObject == 0 } // composedVariant synthesizes the Model for one distributed variant: the // enclosing schema's composition and own properties conjoined with that -// branch's referent. The branch is conjoined last so the enclosing composition -// classifies first, keeping the "sole $ref becomes Base" reading of -// docs/compilers/openapi.md#allof-classification of the allOf the source -// actually wrote. +// branch's referent, conjoined last so the enclosing composition classifies +// first (docs/compilers/openapi.md#allof-classification). // -// The Model gets an ID of its own (ids.ComposedType), not the branch pointer's, -// which already denotes the branch schema. Interning there made the two race -// for one pointer, so a $ref to the branch could find either the bare branch or -// the full variant, depending on lowering order -// (docs/ir/models.md#composition-beside-a-union). -func composedVariant(loweringContext lowering.Ctx, ts *compile.Types, depth int, body composedBody, - b *statement.Statement, vptr jsontext.Pointer, -) (ir.TypeRef, []ir.Diagnostic) { - id := loweringContext.IDs().ComposedType(vptr) - common := commonFor(loweringContext, id, vptr) - // The Model conjoins the union's body with the branch, so it is named for - // both. - common.Name = compile.NamingHint(compile.SubHint(lowering.NameAt(loweringContext, body.comp.pointer), lowering.NameAt(loweringContext, vptr))) - if body.inferred && !admitsObjectsAlone(loweringContext, b) { +// The Model gets an ID of its own (ids.ComposedType) at composedVariantKey, +// not the branch pointer's, which already denotes the branch schema: sharing +// one pointer made a $ref to the branch find either node, depending on +// lowering order (docs/ir/models.md#composition-beside-a-union). It sits +// where its branch is written. +func composedVariant(loweringContext lowering.Ctx, types *compile.Types, depth int, body composedBody, + branchStatement *statement.Statement, variantPointer jsontext.Pointer, +) (ir.TypeRef, bool, []ir.Diagnostic) { + if body.byKind && splitsOff(loweringContext, branchStatement) { + return splitVariant(loweringContext, types, depth, body, branchStatement, variantPointer) + } + common := composedCommon(loweringContext, body, variantPointer) + id := common.ID + if body.inferred && !admitsObjectsAlone(loweringContext, branchStatement) { common.Provenance.Inferred = ir.JoinInferred(common.Provenance.Inferred, lowering.KindInferenceHeuristic) } - variant, unpacked, composes := branchReferent(loweringContext, b) + variant, unpacked, composes := branchReferent(loweringContext, branchStatement) if !composes { // The variant is the branch's one home, so the branch lowers nowhere and // what it says of null is read off it, reported where the policy reads one. - def, diags := buildComposedVariant(loweringContext, ts, depth, body, b, "", false, common) - ts.Register(id, def) - nulls := newNulls(loweringContext) - nullReading := nulls.conjunct(b, siteAt(vptr)) - ref := composedVariantRef(loweringContext, id, body.schema, nullReading.declared == nullAdmitted, nullReading.lenient == nullAdmitted) - return ref, append(diags, nulls.findings(loweringContext)...) + def, diags := buildComposedVariant(loweringContext, types, depth, body, branchStatement, variantPointer, "", common) + types.Register(id, def) + answer := nullAnswerReadingsOf(loweringContext, branchStatement) + ref := composedVariantRef(loweringContext, id, body.schema, answer.declaredOnReference(loweringContext), answer.underInference == nullAdmittedByReference) + return ref, closedAfterComposition(def), append(diags, nullFindings(loweringContext, branchStatement, variantPointer)...) } // The branch lowers through the ordinary schema path, at its own pointer, so // it keeps whatever it declares beside the $ref and a reference to that // pointer still finds the branch rather than the variant. - branch, diags := Ref(loweringContext, ts, depth, b, vptr) + branch, diags := Ref(loweringContext, types, depth, branchStatement, variantPointer) referent := branch.Target if unpacked { recordDiscarded(loweringContext, referent) referent = variant } - def, variantDiags := buildComposedVariant(loweringContext, ts, depth, body, b, referent, true, common) - ts.Register(id, def) + def, variantDiags := buildComposedVariant(loweringContext, types, depth, body, branchStatement, variantPointer, referent, common) + types.Register(id, def) ref := composedVariantRef(loweringContext, id, body.schema, branch.Nullable && branch.Inferred == "", branch.Nullable) - return ref, append(diags, variantDiags...) + return ref, closedAfterComposition(def), append(diags, variantDiags...) +} + +// composedCommon is the TypeCommon of the variant composed over the branch +// written at variantPointer beside body, keyed at composedVariantKey and named +// for both. +func composedCommon(loweringContext lowering.Ctx, body composedBody, variantPointer jsontext.Pointer) ir.TypeCommon { + key := composedVariantKey(body, variantPointer) + common := commonFor(loweringContext, loweringContext.IDs().ComposedType(key), variantPointer) + common.Provenance = loweringContext.Place().At(key, variantPointer) + common.Name = compile.NamingHint(compile.SubHint(lowering.NameAt(loweringContext, body.comp.pointer), lowering.NameAt(loweringContext, variantPointer))) + return common +} + +// composesNoObject reports whether the union schema's conjunction chooses +// splits its body by kind and every branch splits off admitting no object, so +// the body's object keywords apply to no kind the union admits and are kept. +func composesNoObject(loweringContext lowering.Ctx, schema *statement.Schema) bool { + loweredUnion, ok := readConjunction(loweringContext, schema).loweredUnion() + if !ok || readLoweredUnion(loweringContext, schema).besideRest != unionSplitByKind { + return false + } + return !slices.ContainsFunc(loweredUnion.branches(), func(branch statement.Subschema) bool { + schemaStatement := loweringContext.Statements().Subschema(branch) + kinds, _ := lowersTo(loweringContext, schemaStatement) + return !splitsOff(loweringContext, schemaStatement) || kinds&kindObject != 0 + }) +} + +// splitsOff reports whether the variant over branch, a branch of a union a body +// is split by kind across, takes the body's keywords of its kinds alone. +func splitsOff(loweringContext lowering.Ctx, branch *statement.Statement) bool { + if listsTypes(branch) { + return true + } + kinds, inferred := lowersTo(loweringContext, branch) + kinds &^= kindNull + return !inferred && kinds != 0 && kinds&kindObject == 0 && kinds != everyKindButNull +} + +// listsTypes reports whether branch is an inline branch lowering as a list of +// several types, a node per type (lowerTypeList). +func listsTypes(branch *statement.Statement) bool { + return branch.Ref == nil && stated(branch.Schema) && len(effectiveTypes(branch.Schema)) > 1 && !writesConjuncts(branch.Schema) && + dispatchOf(branch.Schema).lowered == "" +} + +// splitKinds is the kinds of the branches of the union body is split by kind +// across that split off (splitsOff), whose bounds those variants read; none +// for a body not split. +func splitKinds(loweringContext lowering.Ctx, body composedBody) kindSet { + if !body.byKind { + return 0 + } + var out kindSet + branches := body.union.branches(loweringContext) + for _, branch := range branches { + schemaStatement := loweringContext.Statements().Subschema(branch) + if splitsOff(loweringContext, schemaStatement) { + kinds, _ := lowersTo(loweringContext, schemaStatement) + out |= kinds &^ kindNull + } + } + return out +} + +// splitVariant is the variant over branchStatement, a branch written at +// variantPointer of a union body is split by kind across +// (docs/compilers/openapi.md#union-beside-structure), holding the body's +// bounds of its kinds, and whether it closes after composition. +func splitVariant(loweringContext lowering.Ctx, types *compile.Types, depth int, body composedBody, branchStatement *statement.Statement, variantPointer jsontext.Pointer, +) (ir.TypeRef, bool, []ir.Diagnostic) { + if listsTypes(branchStatement) { + return splitKindsUnion(loweringContext, types, depth, body, branchStatement, variantPointer) + } + branch, diags := Ref(loweringContext, types, depth, branchStatement, variantPointer) + kinds, _ := lowersTo(loweringContext, branchStatement) + common := composedCommon(loweringContext, body, variantPointer) + ref, scalarDiags := kindScalar(loweringContext, types, body, ir.TypeRef{Target: branch.Target}, kinds&^kindNull, common) + diags = append(diags, scalarDiags...) + if ref.Target == branch.Target { + return branch, false, diags + } + return composedVariantRef(loweringContext, ref.Target, body.schema, branch.Nullable && branch.Inferred == "", branch.Nullable), false, diags +} + +// kindScalar is the node over own, a node of kinds, holding the body's bounds +// of those kinds: a Scalar over own registered with common, or own itself +// where the body writes none of them. +func kindScalar(loweringContext lowering.Ctx, types *compile.Types, body composedBody, own ir.TypeRef, kinds kindSet, common ir.TypeCommon, +) (ir.TypeRef, []ir.Diagnostic) { + cons, diags := ConstraintsOf(loweringContext, &common.Unmodeled, body.schema, body.flattenedEntries, body.comp.pointer, kinds) + if cons == nil { + return own, diags + } + types.Register(common.ID, &ir.Scalar{TypeCommon: common, Base: &own, Constraints: cons}) + return ir.TypeRef{Target: common.ID}, diags +} + +// splitKindsUnion is splitVariant for branch, written at variantPointer, +// listing types: a Union minted at its key, of a variant per type conjoined +// with the body's keywords of its kind (kindVariant). branch lowers at no other +// pointer of its own, the Union taking its place. No type is left without a +// variant admitting what branch admits of it. +func splitKindsUnion(loweringContext lowering.Ctx, types *compile.Types, depth int, body composedBody, branch *statement.Statement, variantPointer jsontext.Pointer, +) (ir.TypeRef, bool, []ir.Diagnostic) { + common := composedCommon(loweringContext, body, variantPointer) + key := composedVariantKey(body, variantPointer) + listedKinds := effectiveTypes(branch.Schema) + list := typeArray{types: listedKinds} + var diags []ir.Diagnostic + var read keySet + variants := make([]ir.Variant, 0, len(listedKinds)) + closes := false + for i, kind := range listedKinds { + // The type's own node sits under the key too, at "-", which names + // no element of the list, so no source pointer and no lowering of branch + // at variantPointer, which builds its own, spells it. + own, shared, ownDiags := lowerTypeVariant(loweringContext, types, depth, branch.Schema, variantPointer, key+ids.Ptr("type", "-", strconv.Itoa(i)), kind, list) + read |= own.read | shared + at := key + ids.Ptr("type", strconv.Itoa(i)) + kindCommon := commonFor(loweringContext, loweringContext.IDs().ComposedType(at), variantPointer) + kindCommon.Provenance = loweringContext.Place().At(at, variantPointer) + ref, kindCloses, kindDiags := kindVariant(loweringContext, types, depth, body, branch, variantPointer, kind, ir.TypeRef{Target: own.id}, kindCommon) + closes = closes || kindCloses + diags = append(diags, slices.Concat(ownDiags, kindDiags)...) + variants = append(variants, ir.Variant{Name: compile.NamingHint(string(kind)), Type: ref}) + } + built := builtPosition{node: &ir.Union{TypeCommon: common, Variants: variants, Exclusive: typesDisjoint(listedKinds), Closed: true}, id: common.ID, read: read} + diags = append(diags, keepUnreadAcross(loweringContext, branch.Schema, nodeShape(ir.KindUnion), keyBit("type"), variantPointer, nodePlacement{}, &built)...) + diags = append(diags, declarationOn(loweringContext, branch.Schema, ir.TypeRef{Target: common.ID}, variantPointer, annotation.HomeOwnNode, &built)...) + diags = append(diags, settleNode(loweringContext, branch.Schema, ir.TypeRef{Target: common.ID}, variantPointer, &built)...) + types.Register(common.ID, built.node) + answer := nullAnswerReadingsOf(loweringContext, branch) + ref := composedVariantRef(loweringContext, common.ID, body.schema, answer.declaredOnReference(loweringContext), answer.underInference == nullAdmittedByReference) + return ref, closes, append(diags, nullFindings(loweringContext, branch, variantPointer)...) +} + +// kindVariant is the variant of kind of the branch written at variantPointer, a +// list of types, over own, the node branch's list lowers kind to, conjoined +// with the body. It reports whether it closes after composition. +func kindVariant(loweringContext lowering.Ctx, types *compile.Types, depth int, body composedBody, branch *statement.Statement, variantPointer jsontext.Pointer, + kind statement.JSONSchemaTypeName, own ir.TypeRef, common ir.TypeCommon, +) (ir.TypeRef, bool, []ir.Diagnostic) { + if kind != statement.KindObject { + ref, diags := kindScalar(loweringContext, types, body, ir.TypeRef{Target: own.Target}, kindsOfTypeName(kind), common) + return ref, false, diags + } + def, diags := buildComposedVariant(loweringContext, types, depth, body, branch, variantPointer, own.Target, common) + types.Register(common.ID, def) + return ir.TypeRef{Target: common.ID}, closedAfterComposition(def), diags +} + +// composedVariantKey is the pointer the variant composing the branch written at +// variantPointer over body is keyed at: variantPointer where the union is +// written at body's position P, which names both; else P/allOf/-/, as the union an entry of P's allOf writes is also +// distributed at that entry when a $ref names it, keyed at variantPointer +// there. "-" names no element of an array (RFC 6901), so no source pointer, and +// no other key minted, spells the second form +// (docs/ir/identity.md#the-id-grammar). +func composedVariantKey(body composedBody, variantPointer jsontext.Pointer) jsontext.Pointer { + entries := body.comp.pointer + "/allOf" + rest, onEntry := strings.CutPrefix(string(variantPointer), string(entries)+"/") + if body.union.holder == body.schema || !onEntry { + return variantPointer + } + return entries + "/-/" + jsontext.Pointer(rest) } // composedVariantRef returns the reference a union variant naming the @@ -233,44 +524,51 @@ func composedVariantRef(loweringContext lowering.Ctx, id ir.TypeID, body *statem if !declared && !lenient { return ir.TypeRef{Target: id} } - nulls := newNulls(loweringContext) - nullReading := nulls.schema(body, nullSite{}) - return nullRef(loweringContext, id, declared && nullReading.declared != nullForbidden, lenient && nullReading.lenient != nullForbidden) + answer := nullAnswerReadingsOf(loweringContext, loweringContext.Statements().Read(body)) + return nullRef(loweringContext, id, declared && answer.asDeclared != nullForbidden, lenient && answer.underInference != nullForbidden) } // buildComposedVariant assembles the variant Model itself, composing branch, -// b's referent, or keeping b where composes is false. Every fill reads the -// enclosing schema at its pointer, so the properties, their PropIDs and any -// shared additionalProperties node are the one set the source declared. +// the referent of branchStatement, written at variantPointer, or keeping +// branchStatement where branch is none. Every fill reads the enclosing schema +// at its pointer, so the properties, their PropIDs and any shared +// additionalProperties node are the source's. // // The enclosing schema's value constraints, its folding entries' among them, // are read as lowerAllOf reads them (GitHub #407), for the kinds the variant -// admits: those b lowers to among the model's. So a variant over a branch no -// object satisfies holds none, and a bound no variant holds is kept unread -// on the Union (GitHub #1936). -func buildComposedVariant(loweringContext lowering.Ctx, ts *compile.Types, depth int, body composedBody, b *statement.Statement, - branch ir.TypeID, composes bool, common ir.TypeCommon, +// admits: those branchStatement lowers to among the model's. So a variant over +// a branch no object satisfies holds none, and a bound no variant holds is kept +// unread on the Union (GitHub #1936). +func buildComposedVariant(loweringContext lowering.Ctx, types *compile.Types, depth int, body composedBody, branchStatement *statement.Statement, + variantPointer jsontext.Pointer, branch ir.TypeID, common ir.TypeCommon, ) (ir.TypeDef, []ir.Diagnostic) { - kinds, _ := lowersTo(loweringContext, b) - cons, diags := ConstraintsOf(loweringContext, &common.Unmodeled, body.schema, body.foldedEntries, body.comp.pointer, body.comp.bounds&kinds) + composes := branch != "" + kinds, _ := lowersTo(loweringContext, branchStatement) + // The distributing position's homes, carried on body, of the kinds the + // variant admits. + cons, diags := ConstraintsOf(loweringContext, &common.Unmodeled, body.schema, body.flattenedEntries, body.comp.pointer, body.homes.value&kinds) model := &ir.Model{TypeCommon: common, Constraints: cons} - fields := newModelFields(loweringContext, ts, model) + fields := newModelFields(loweringContext, types, model) if composes { // The branch is distributed into the body, whose own declarations are // read after it, as a model's own declarations follow what it composes. fields.compose(branch, model.Provenance.Pointer) } - base, hasBase := selectAllOfBase(loweringContext, body.comp.entries, model.ID) - diags = append(diags, fillAllOf(loweringContext, ts, depth, model, fields, body.comp, base, hasBase)...) - diags = append(diags, fillModelProperties(loweringContext, ts, depth, fields, body.schema, body.comp.pointer)...) + base, hasBase := selectAllOfBase(loweringContext, body.comp.entries, nil, model.ID) + // What the entries keep the Union keeps (keepEntryUnreadKeywords), and the + // variant what its failed $ref entries and its false entries do, settled + // there. + var pendingKeeps annotation.PendingKeeps + diags = append(diags, fillAllOf(loweringContext, types, depth, model, fields, body.comp, nil, base, hasBase, &pendingKeeps)...) + addFalseEntryPendingKeeps(loweringContext, &pendingKeeps, body.comp) + diags = append(diags, settleOn(loweringContext, &model.Unmodeled, &pendingKeeps, body.comp.pointer)...) + diags = append(diags, fillModelProperties(loweringContext, types, depth, fields, body.schema, body.comp.pointer)...) requireMembers(model, compositionRequired(body.schema.ObjectKeywords().Required, body.comp)) - diags = append(diags, fillComposedAdditional(loweringContext, ts, depth, model, body.schema, body.comp)...) + diags = append(diags, fillComposedAdditional(loweringContext, types, depth, model, body.schema, body.comp)...) diags = append(diags, applyFalseEntries(loweringContext, model, body.comp)...) - _, key, _ := body.union.branches(loweringContext) - diags = append(diags, preserveUnusedCombinator(loweringContext, &model.Unmodeled, body.union, key)...) if !composes { // A variant composing nothing over a body that is a map alone is that map. - diags = append(diags, keepUncomposedBranch(loweringContext, model, b)...) + diags = append(diags, keepUncomposedBranch(loweringContext, model, branchStatement, variantPointer)...) return objectNode(model), diags } conjoinBranch(model, branch) @@ -281,37 +579,33 @@ func buildComposedVariant(loweringContext lowering.Ctx, ts *compile.Types, depth return model, diags } -// branchReferent reports whether the variant composed over the union branch b +// branchReferent reports whether the variant composed over the union branch // names a referent as its Base or a Mixin, as an allOf's $ref entry composes -// (composesRef), read before b lowers, so a branch the variant keeps lowers -// nowhere: the node b lowers to where it is an object alone, null aside, or its -// read is cut short; the object variant of a type list b's $ref names, unpacked -// (objectVariant), where b writes nothing beside its $ref, which would bind the -// whole list on no node the variant names; else none, since a model composes -// only models. -func branchReferent(loweringContext lowering.Ctx, b *statement.Statement) (variant ir.TypeID, unpacked, composes bool) { - if admissionOf(loweringContext, b).cut { - return "", false, true - } - if kinds, _ := lowersTo(loweringContext, b); kinds == kindObject { +// (composesRef), read before branch lowers, so a branch the variant keeps +// lowers nowhere: the node branch lowers to where it is an object alone, null +// aside (lowersTo, read whole at any size); the object variant of a type list +// branch's $ref names, unpacked (objectVariant), where branch writes nothing +// beside its $ref, which would bind the whole list on no node the variant +// names; else none, since a model composes only models. +func branchReferent(loweringContext lowering.Ctx, branch *statement.Statement) (variant ir.TypeID, unpacked, composes bool) { + if kinds, _ := lowersTo(loweringContext, branch); kinds == kindObject { return "", false, true } - variant, unpacked = objectVariant(loweringContext, b) - if !unpacked || writesMoreThanRef(b.Schema) { + variant, unpacked = objectVariant(loweringContext, branch) + if !unpacked || writesMoreThanRef(branch.Schema) { return "", false, false } return variant, true, true } -// keepUncomposedBranch keeps the union branch b, which the variant model does -// not compose (branchReferent), verbatim under model's Unmodeled -// (unionBranchKey), and reports it, as keepUncomposedRefs keeps an allOf's $ref -// entries. b lowers nowhere, so this is its one home; the target of a $ref it -// writes lowers where the $ref lands, as every landing does +// keepUncomposedBranch keeps the union branch, which the variant model does not +// compose (branchReferent), verbatim under model's Unmodeled (unionBranchKey), +// and reports it, as keepUncomposedRefs keeps an allOf's $ref entries. branch +// lowers nowhere, so this is its one home; the target of a $ref it writes +// lowers where the $ref lands, as every landing does // (ReserveNodesAtReferenceTargets). -func keepUncomposedBranch(loweringContext lowering.Ctx, model *ir.Model, b *statement.Statement) []ir.Diagnostic { - at := model.Provenance.Pointer - kept, diags := preserveNode(loweringContext, &model.Unmodeled, unionBranchKey(at), b.Node, +func keepUncomposedBranch(loweringContext lowering.Ctx, model *ir.Model, branch *statement.Statement, at jsontext.Pointer) []ir.Diagnostic { + kept, diags := keepNode(loweringContext, &model.Unmodeled, unionBranchKey(at), branch.Node, ir.ReasonDegradedLowering, at) if !kept { return diags diff --git a/compilers/openapi/internal/schema/voices.go b/compilers/openapi/internal/schema/voices.go deleted file mode 100644 index ad30863d7..000000000 --- a/compilers/openapi/internal/schema/voices.go +++ /dev/null @@ -1,373 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package schema - -import ( - "bytes" - "encoding/json/jsontext" - "slices" - "strings" - - "github.com/dexpace/morphic/compilers/openapi/internal/annotation" - "github.com/dexpace/morphic/compilers/openapi/internal/lowering" - "github.com/dexpace/morphic/compilers/openapi/internal/reftable" - "github.com/dexpace/morphic/compilers/openapi/internal/statement" - "github.com/dexpace/morphic/ir" -) - -// foldKeywords are the keywords an inline allOf entry writes for the position -// holding it, each read as if written beside the allOf -// (docs/compilers/openapi.md#allof-inline-residue). foldEntry adds the bounds, -// the extensions and the keywords that fold together. No unevaluated keyword -// folds: each applies to what its own schema evaluates, so on an entry it holds -// the instance to what that entry alone evaluates, and the entry kept whole -// is its record. -var foldKeywords = []string{ - "title", "description", "externalDocs", "deprecated", "xml", "default", "readOnly", "writeOnly", - "nullable", "not", "dependentSchemas", "dependentRequired", "propertyNames", -} - -// foldEntry returns the one entry a position keeps keyword in once s, a schema -// of c, folds, and false for a keyword no fold reads. Keywords one entry holds -// fold as one, so an entry's `then` and another's `if` cannot overwrite each -// other, and a draft's spelling folds as its twin does (TwinKeyword). -func foldEntry(loweringContext lowering.Ctx, schema *statement.Schema, keyword string) (string, bool) { - switch keyword { - case "example", "examples": - return "examples", true - case "if", "then", "else": - return "if", true - case "contains", "minContains", "maxContains": - return "contains", true - case "format": - return keyword, annotation.DeclaresRedaction(schema) - case "minItems", "maxItems", "uniqueItems": - // A collection bound ir.Constraints cannot state keeps its entry whole. - return keyword, referenceHolds(schema, keyword) - } - twin := TwinKeyword(loweringContext, schema, keyword) - fold := strings.HasPrefix(keyword, "x-") || slices.Contains(foldKeywords, twin) || - slices.Contains(valueConstraintKeywords, twin) - return keyword, fold -} - -// foldRendering is what a conjunct writes for an entry, rendered to compare with -// another conjunct's. One that cannot be rendered agrees with nothing, which keeps -// its entry; a keyword may render to nothing, which is no failure. -type foldRendering struct { - raw ir.RawValue - err error -} - -// agrees reports whether r and foldRenderingValue write an entry alike. -func (r foldRendering) agrees(foldRenderingValue foldRendering) bool { - return r.err == nil && foldRenderingValue.err == nil && bytes.Equal(r.raw, foldRenderingValue.raw) -} - -// foldValue renders what schema writes for entry. -func foldValue(schema *statement.Schema, entry string) foldRendering { - var foldRenderingValue foldRendering - switch entry { - case "examples": - foldRenderingValue.raw, _, foldRenderingValue.err = annotation.ExamplesRaw(schema) - case "if": - foldRenderingValue.raw, _, foldRenderingValue.err = annotation.IfThenElseRaw(schema) - case "contains": - foldRenderingValue.raw, _, foldRenderingValue.err = annotation.ContainsRaw(schema) - default: - foldRenderingValue.raw, foldRenderingValue.err = annotation.RawFromNode(keyNode(schema, entry)) - } - return foldRenderingValue -} - -// allOfMayRefine reports whether schema's conjuncts may refine: it writes them -// (writesConjuncts), an allOf or a reference beside other keys -// (docs/compilers/openapi.md#allof-refinement). A union beside them is one -// more conjunct, and a $dynamicRef the position does not expand masks no kind -// (admissionReader.conjuncts). -func allOfMayRefine(schema *statement.Schema) bool { - return writesConjuncts(schema) -} - -// allOfDecides reports whether s's allOf is what its position lowers: one the -// dispatch of competing keywords made the value, or one refining, whose rival -// there, an enum or a const beside it, is one of its conjuncts. An allOf that -// value set beats otherwise stays verbatim -// (docs/compilers/openapi.md#competing-keywords). A union beside the composing -// allOf or on one of its entries leaves it deciding, composed into each variant -// the union distributes across, or into the Model keeping the union verbatim or -// composing it as a mixin, and so does a $dynamicRef it keeps from expanding. -func allOfDecides(loweringContext lowering.Ctx, schema *statement.Schema) bool { - if !writesConjuncts(schema) { - return false - } - if dispatchOf(schema).won == "allOf" { - return true - } - return decisionOf(loweringContext, schema).refines -} - -// allOfEntryFoldingKey keys what foldingAllOfEntries read of one schema. -type allOfEntryFoldingKey struct { - schema *statement.Schema -} - -// foldingAllOfEntries reports, for each entry of s's flattened allOf, whether -// it folds: it is inline, it writes something for the position, and each such -// keyword agrees with every other conjunct writing it, s's own keywords among -// them (agreement). The answer reads the whole set, so no conjunct takes -// precedence and no order decides. A null keyword writes nothing -// (WritesKeywordLeftOut). Every use of s asks, so it is read once a run. -func foldingAllOfEntries(loweringContext lowering.Ctx, schema *statement.Schema) []bool { - return allOfEntryFoldingOf(loweringContext, schema).entryFoldsIntoPosition -} - -// allOfEntryFolding is what a schema's allOf says for the position holding it: -// whether each entry of the flattened list folds, whether it lends a use what s -// and the folding entries before it do not, a keyword none of them writes, and -// whether what it folds writes a relative $ref it reads against another base -// than the position does (readsAtPosition), so nothing it writes folds. -type allOfEntryFolding struct { - entryFoldsIntoPosition []bool - addsKeywordNoEarlierEntryWrites []bool - rebased []bool -} - -// allOfEntryFoldingOf reads schema's folding once a run. -func allOfEntryFoldingOf(loweringContext lowering.Ctx, schema *statement.Schema) allOfEntryFolding { - return lowering.ReadOncePerRun(loweringContext, allOfEntryFoldingKey{schema}, func() allOfEntryFolding { return readAllOfEntryFolding(loweringContext, schema) }) -} - -// readAllOfEntryFolding reads what allOfEntryFoldingOf remembers. -func readAllOfEntryFolding(loweringContext lowering.Ctx, schema *statement.Schema) allOfEntryFolding { - a := newAgreement(loweringContext) - addsKeywordNoEarlierEntryWrites := map[string]bool{} - for _, entry := range a.write(schema) { - addsKeywordNoEarlierEntryWrites[entry] = addsKeywordNoEarlierEntryWrites[entry] || !writesFalseFlag(entry, foldValue(schema, entry)) - } - comp := allOfEntries(loweringContext, schema, "") - n := len(comp.entries) - out := allOfEntryFolding{entryFoldsIntoPosition: make([]bool, n), addsKeywordNoEarlierEntryWrites: make([]bool, n), rebased: make([]bool, n)} - writes := make([][]string, n) - ids := idWrappers(comp) - for i, entry := range comp.entries { - if stated(entry.schema.Schema) && entry.schema.Ref == nil { - if out.rebased[i] = underID(entry, entry.schema.Schema, ids) && foldsReference(loweringContext, entry.schema.Schema) && !readsAtPosition(loweringContext, entry); !out.rebased[i] { - writes[i] = a.write(entry.schema.Schema) - } - } - } - for i, entries := range writes { - out.entryFoldsIntoPosition[i] = len(entries) > 0 && !slices.ContainsFunc(entries, a.apart) - if !out.entryFoldsIntoPosition[i] { - continue - } - for _, entry := range entries { - // A false flag lends nothing: it states nothing a later true would not. - if writesFalseFlag(entry, foldValue(comp.entries[i].schema.Schema, entry)) { - continue - } - out.addsKeywordNoEarlierEntryWrites[i] = out.addsKeywordNoEarlierEntryWrites[i] || !addsKeywordNoEarlierEntryWrites[entry] - addsKeywordNoEarlierEntryWrites[entry] = true - } - } - return out -} - -// idWrappers returns where the flattened wrappers of comp writing an -// identifier are (writesIdentifier), each one that may give what it holds -// another base than the position's. -func idWrappers(comp allOfComposition) map[jsontext.Pointer]bool { - out := map[jsontext.Pointer]bool{} - for _, entry := range comp.entries { - if entry.wrapper && writesIdentifier(entry.schema.Schema) { - out[entry.pointer] = true - } - } - return out -} - -// underID reports whether bs, the inline allOf entry e, or a wrapper holding -// it writes an identifier. Only one can give the entry another base than the -// position holding the allOf, so an entry under none reads at the position -// without a base being looked up. The wrappers holding e are the prefixes of -// its pointer, as many as statement.MaxFlattenDepth allows, so each is looked up. -func underID(allOfEntryValue allOfEntry, bs *statement.Schema, wrappers map[jsontext.Pointer]bool) bool { - if writesIdentifier(bs) { - return true - } - p := string(allOfEntryValue.pointer) - for i := strings.LastIndexByte(p, '/'); i > 0; i = strings.LastIndexByte(p[:i], '/') { - if wrappers[jsontext.Pointer(p[:i])] { - return true - } - } - return false -} - -// writesIdentifier reports whether schema writes `$id`, or `id`, draft 4's -// spelling of it. Either may name a resource, and the base a lookup returns -// says whether it does, so one that names none costs that lookup alone. -func writesIdentifier(schema *statement.Schema) bool { - return hasKey(schema, "$id") || hasKey(schema, "id") -} - -// foldsReference reports whether what bs folds writes a relative $ref, the one -// text a base changes: an entry writing none in it says the same at any base. -func foldsReference(loweringContext lowering.Ctx, bs *statement.Schema) bool { - return slices.ContainsFunc(bs.Keys, func(key statement.Key) bool { - entry, fold := foldEntry(loweringContext, bs, key.Name) - return fold && annotation.WritesReference(foldValue(bs, entry).raw) - }) -} - -// readsAtPosition reports whether the inline allOf entry e reads its $refs -// against the base the position holding the allOf does, so what it writes means -// there what it means where it is written: an identifier at or above it naming -// another URI gives the same spelling another schema. The position is e's site -// less e's path from it, as the allOf may be read where a $ref landed. A base -// the bindings cannot tell is no match. -func readsAtPosition(loweringContext lowering.Ctx, allOfEntryValue allOfEntry) bool { - site, placed := siteOf(allOfEntryValue.schema.Schema) - at := reftable.DocumentPointer{Doc: site.Doc, Pointer: jsontext.Pointer(strings.TrimSuffix(string(site.Pointer), string(allOfEntryValue.pointer)))} - own, known := loweringContext.Bindings().Table().Base(site) - position, knownAt := loweringContext.Bindings().Table().Base(at) - return placed && known && knownAt && own == position -} - -// disagreedWhy words why an entry that would have folded is kept, as n names -// it: its keywords have homes, and what they say is what is in question. -func disagreedWhy(residue []string, entryNamesValue entryNames) string { - return "the conjuncts of this allOf disagree on a keyword " + entryNamesValue.this + " writes, so nothing it writes folds; " + - entryNamesValue.kept + " (" + strings.Join(residue, ", ") + ") is kept verbatim under Unmodeled" -} - -// disagreed reports whether residue, what an entry that did not fold keeps of -// bs, holds a keyword folding reads: foldingAllOfEntries passes over an entry -// for writing none or for a disagreement, and this tells them apart. -func disagreed(loweringContext lowering.Ctx, bs *statement.Schema, residue []string) bool { - return slices.ContainsFunc(residue, func(keyword string) bool { - _, fold := foldEntry(loweringContext, bs, keyword) - return fold - }) -} - -// folds reports whether an entry that folds consumes keyword: homes says which -// bounds the position has a field for, of which a value bound is read where the -// entry's own types take it too (writerTakes), and a `nullable` folds where -// the policy reads it (nullableRead) and foldsNullable says so. -func folds(loweringContext lowering.Ctx, bs *statement.Schema, keyword string, homes boundHomes) bool { - if keyword == "nullable" { - return loweringContext.NullableInference.Honours() && nullableRead(loweringContext, bs) && foldsNullable(bs) - } - if slices.Contains(valueConstraintKeywords, keyword) { - return taken(writerTakes(homes.value, bs), keyword) - } - _, fold := foldEntry(loweringContext, bs, keyword) - if slices.Contains(collectionBoundKeywords, keyword) { - return fold && homes.collection - } - return fold -} - -// foldsNullable reports whether `nullable` on the entry bs speaks for the whole -// composition: an entry writing properties declares a shape of its own, which -// its `nullable` reads as describing, so it stays conjoined with the rest. -func foldsNullable(bs *statement.Schema) bool { - return !hasKey(bs, "properties") -} - -// positionFoldedEntries returns the voices of s, written at pointer, as a -// reader of what the position holds takes them, target being what the position -// lowered to. An entry whose own node that is, the alias a $ref principal -// writing keywords beside it stands at its entry, keeps what it writes there. -func positionFoldedEntries(loweringContext lowering.Ctx, schema *statement.Schema, pointer jsontext.Pointer, target ir.TypeRef) []annotation.FoldedAllOfEntry { - if !allOfDecides(loweringContext, schema) { - return nil - } - comp := allOfEntries(loweringContext, schema, pointer) - var out []annotation.FoldedAllOfEntry - for i, speaks := range foldingAllOfEntries(loweringContext, schema) { - entry := comp.entries[i] - if !speaks || LoweredToOwnNode(loweringContext, entry.pointer, target) { - continue - } - foldedAllOfEntry := foldedEntryAt(loweringContext, entry.schema.Schema, entry.pointer) - // The entry keeps a `dependencies` that does not fold (entryKeeps). - foldedAllOfEntry.Dependencies = foldedAllOfEntry.Dependencies && !foldsNoDependencies(loweringContext, schema, pointer) - out = append(out, foldedAllOfEntry) - } - return out -} - -// foldedEntryAt returns the folded entry of node, written at at, which reads -// its `dependencies` in the dialect node is written in, as a fold of it does -// (TwinKeyword): an allOf entry naming a draft by its own `$schema` keeps the -// draft's keyword beside a position read in 2020-12, as the same schema written -// flat in the draft keeps it (docs/compilers/openapi.md#dialect-keywords). -func foldedEntryAt(loweringContext lowering.Ctx, node *statement.Schema, at jsontext.Pointer) annotation.FoldedAllOfEntry { - return annotation.FoldedAllOfEntry{Node: node, At: at, Dependencies: rulesOf(loweringContext, node).Defines("dependencies")} -} - -// lendingEntries returns the entries of s that fold, each at its pointer below -// s, for a use reading what s lends it, but those writing only what s or such -// an entry before them writes: the writers of a keyword a use reads agree -// (foldingAllOfEntries), so a reader taking the nearest takes the same value -// from any of them, and a use of s pays for each keyword once, not for each -// entry repeating it. Bounds, which agree by meeting, are no such keyword: a -// use never reads them through its $ref. -func lendingEntries(loweringContext lowering.Ctx, schema *statement.Schema) []allOfEntry { - if !allOfDecides(loweringContext, schema) { - return nil - } - comp := allOfEntries(loweringContext, schema, "") - var out []allOfEntry - for i, addsKeyword := range allOfEntryFoldingOf(loweringContext, schema).addsKeywordNoEarlierEntryWrites { - if addsKeyword { - out = append(out, comp.entries[i]) - } - } - return out -} - -// declaresScoped reports whether a folded entry writes what only the position -// can hold, as declaresPositionScoped asks of the schema written there. -func declaresScoped(loweringContext lowering.Ctx, foldedEntries []annotation.FoldedAllOfEntry) bool { - return slices.ContainsFunc(foldedEntries, func(foldedAllOfEntry annotation.FoldedAllOfEntry) bool { - return declaresPositionScoped(loweringContext, foldedAllOfEntry.Node) - }) -} - -// recordFoldedEntryResidue keeps on td, in hand, what binds a use that -// foldedEntries write (recordResidue), each reported at the keyword it wrote, -// in FoldedEntriesInOverwriteOrder' order: an entry several write is the -// nearest folded entry's kept apart, and the schema written at the position -// records after them. -func recordFoldedEntryResidue(loweringContext lowering.Ctx, td ir.TypeDef, schema *statement.Schema, foldedEntries []annotation.FoldedAllOfEntry) []ir.Diagnostic { - diags := make([]ir.Diagnostic, 0, len(foldedEntries)) - for _, foldedAllOfEntry := range FoldedEntriesInOverwriteOrder(foldedEntries) { - // What schema writes too is schema's to keep and report: one writing, - // as the foldedEntries agree. - diags = append(diags, recordResidue(loweringContext, td.Common(), foldedAllOfEntry.Node, foldedAllOfEntry.At, func(keyword string) bool { return hasKey(schema, keyword) })...) - } - return diags -} - -// FoldedEntriesInOverwriteOrder returns voices in the order a keeper -// overwriting what each writes takes them: those kept whole, then the rest, -// each the last first. The nearest voice kept apart holds a keyword several -// write, and one kept whole, whose entry holds it (annotation.Voice.KeptWhole), -// only one no other writes, which that entry then holds alone -// (dropFoldedIntoWhole). -func FoldedEntriesInOverwriteOrder(foldedEntries []annotation.FoldedAllOfEntry) []annotation.FoldedAllOfEntry { - out := make([]annotation.FoldedAllOfEntry, 0, len(foldedEntries)) - for _, whole := range []bool{true, false} { - for _, foldedAllOfEntry := range slices.Backward(foldedEntries) { - if foldedAllOfEntry.KeptWhole == whole { - out = append(out, foldedAllOfEntry) - } - } - } - return out -} diff --git a/compilers/openapi/internal/schema/writtentext.go b/compilers/openapi/internal/schema/writtentext.go index 9b29670f3..ce588585f 100644 --- a/compilers/openapi/internal/schema/writtentext.go +++ b/compilers/openapi/internal/schema/writtentext.go @@ -12,16 +12,14 @@ import ( "github.com/dexpace/morphic/ir" ) -// sameText reports whether a and b, both written in one document, write the -// same JSON, read against one base where it writes a relative $ref: under an -// $id naming another URI, the same spelling resolves elsewhere. A copy in -// another document is read apart: its $refs resolve against that document, and -// its dialect may differ (docs/compilers/openapi.md#openapi-versions). A schema -// placed nowhere, a nil one among them, is written alike with none. +// sameText reports whether a and b write the same JSON and say one thing by +// it, each read in its own document (sameMeaning.text), so copies in two +// documents differ where a reference they write lands apart. A schema placed +// nowhere, a nil one among them, is written alike with none. func sameText(loweringContext lowering.Ctx, a, b *statement.Statement) bool { at, placed := siteOf(a.Schema) bt, placedB := siteOf(b.Schema) - if !placed || !placedB || at.Doc != bt.Doc { + if !placed || !placedB { return false } text := writtenText(loweringContext, a) @@ -30,12 +28,7 @@ func sameText(loweringContext lowering.Ctx, a, b *statement.Statement) bool { } // The texts are remembered, so comparing them first leaves a base, which // walks the document, to the rare pair written alike. - if !annotation.WritesReference(text) { - return true - } - base, known := loweringContext.Bindings().Table().Base(at) - other, knownB := loweringContext.Bindings().Table().Base(bt) - return known && knownB && base == other + return newSameMeaning(loweringContext, noneLowered()).text(at, bt, text) } // textOf keys what writtenText rendered of one schema. @@ -43,11 +36,11 @@ type textOf struct { schema *statement.Statement } -// writtenText renders js, nil where it cannot be rendered. Every position -// restating a shared schema asks, so it is rendered once a run. -func writtenText(loweringContext lowering.Ctx, js *statement.Statement) ir.RawValue { - return lowering.ReadOncePerRun(loweringContext, textOf{js}, func() ir.RawValue { - raw, err := annotation.RawFromNode(js.Node) +// writtenText renders schemaStatement, nil where it cannot be rendered. Every +// position restating a shared schema asks, so it is rendered once a run. +func writtenText(loweringContext lowering.Ctx, schemaStatement *statement.Statement) ir.RawValue { + return lowering.ReadOncePerRun(loweringContext, textOf{schemaStatement}, func() ir.RawValue { + raw, err := annotation.RawFromNode(schemaStatement.Node) if err != nil { return nil } diff --git a/compilers/openapi/internal/schema/writtentext_internal_test.go b/compilers/openapi/internal/schema/writtentext_internal_test.go new file mode 100644 index 000000000..fb43fdfea --- /dev/null +++ b/compilers/openapi/internal/schema/writtentext_internal_test.go @@ -0,0 +1,30 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package schema + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// TestSameText_AStatementPlacedNowhereRestatesNone pins the guard before any +// text is read: a statement holding no schema, or one placed nowhere, is +// written alike with none, whichever side it sits on. +func TestSameText_AStatementPlacedNowhereRestatesNone(t *testing.T) { + t.Parallel() + placed := &statement.Statement{Schema: &statement.Schema{At: reftable.DocumentPointer{Pointer: "/components/schemas/A"}}} + for name, pair := range map[string][2]*statement.Statement{ + "no schema on either side": {{}, {}}, + "no schema on the first": {{}, placed}, + "no schema on the second": {placed, {}}, + "a schema placed nowhere": {{Schema: &statement.Schema{}}, placed}, + } { + assert.False(t, sameText(lowering.Ctx{}, pair[0], pair[1]), name) + } +} diff --git a/compilers/openapi/internal/servers/servers.go b/compilers/openapi/internal/servers/servers.go index e6c077818..435798900 100644 --- a/compilers/openapi/internal/servers/servers.go +++ b/compilers/openapi/internal/servers/servers.go @@ -57,8 +57,8 @@ func Reopen(held map[ir.ServerID]ir.Server) *Registry { // which is minted at ids.DefaultServer with no pointer, since nothing in the // source writes it (GitHub #672). func (r *Registry) Root(serviceContext service.Ctx) ([]ir.ServerID, []ir.Diagnostic) { - // The field, not GetServers, which stands in a "/" server for an empty list: - // the default below is minted as no declaration. + // The field, not GetServers, which puts in a "/" server in place of an + // empty list: the default below is minted as no declaration. if declared := serviceContext.Doc.Servers; len(declared) > 0 { return r.Declared(serviceContext, declared, "") } diff --git a/compilers/openapi/internal/servers/servers_test.go b/compilers/openapi/internal/servers/servers_test.go index d12b5ae35..5b602831c 100644 --- a/compilers/openapi/internal/servers/servers_test.go +++ b/compilers/openapi/internal/servers/servers_test.go @@ -87,8 +87,8 @@ paths: {} // half: servers whose lowered names collide although the document never wrote // one name twice. A hint colliding with a hint, a declared name equal to // another entry's hint, and two names equal only once canonicalized are all -// silent, since an emitter uniquifies them. Each row first proves its collision -// is real. +// unreported, since an emitter uniquifies them. Each row first proves its +// collision is real. func TestDuplicateServerName_CanonicalCollisionsAreNotReported(t *testing.T) { t.Parallel() tests := []struct { diff --git a/compilers/openapi/internal/service/beside.go b/compilers/openapi/internal/service/beside.go index cca69775b..c545a0ee0 100644 --- a/compilers/openapi/internal/service/beside.go +++ b/compilers/openapi/internal/service/beside.go @@ -22,7 +22,7 @@ import ( // nearest first. folds says the use folds summary and description into docs. func Beside[T, S any, R chainable[T, S]](serviceContext Ctx, ref R, usePtr jsontext.Pointer, folds bool) (ir.Unmodeled, []ir.Diagnostic) { if _, isRef := serviceContext.Bindings().Reference(ref); !isRef { - return nil, nil // an inline entry writes no $ref to stand beside + return nil, nil // an inline entry writes no $ref to sit beside } var out ir.Unmodeled diags := keepBeside(&out, serviceContext, writtenRoot(ref.GetCoreAny()), usePtr, 0, folds) @@ -53,7 +53,7 @@ func keepBeside(out *ir.Unmodeled, serviceContext Ctx, node *yaml.Node, at jsont if docs { reason = ir.ReasonNoIRHome } - kept, keptDiags := annotation.PreserveNodeInto(out, annotation.EntryKey(scope, pair.Key), pair.Val, reason, + kept, keptDiags := annotation.KeepNodeInto(out, annotation.EntryKey(scope, pair.Key), pair.Val, reason, serviceContext.Place().At(keyAt)) diags = append(diags, keptDiags...) if kept && docs { diff --git a/compilers/openapi/internal/service/documents_test.go b/compilers/openapi/internal/service/documents_test.go index 0b028e3f6..8fe7b746c 100644 --- a/compilers/openapi/internal/service/documents_test.go +++ b/compilers/openapi/internal/service/documents_test.go @@ -54,7 +54,7 @@ func extDoc(t *testing.T, serviceContext service.Ctx) reftable.DocID { t.Helper() a, ok := serviceContext.Doc.Components.Schemas.Get("A") require.True(t, ok) - referenceSite, ok := serviceContext.Bindings().Entry(a) + referenceSite, ok := serviceContext.Bindings().ReferenceSiteAt(a) require.True(t, ok) require.NotEqual(t, reftable.Source, referenceSite.Hop.Target.Doc, "sanity: A lands in ext.yaml") return referenceSite.Hop.Target.Doc diff --git a/compilers/openapi/internal/service/expansion.go b/compilers/openapi/internal/service/expansion.go index 1423ddff2..1f1e5b4c0 100644 --- a/compilers/openapi/internal/service/expansion.go +++ b/compilers/openapi/internal/service/expansion.go @@ -135,13 +135,12 @@ func readingOf(serviceContext Ctx, usePtr jsontext.Pointer) reftable.Reading { // copied returns the hops a copy of what ref names is lowered from, beside the // declaration its chain ends at: ref's own mapping, then each component alias -// the chain passes through, whose fields beside its own $ref lower at every use -// too (componentlookup.UseDocs, and a path item's every field). What ref writes -// beside its $ref is kept on each node the use lowers to, so it is charged as a -// hop's is, and a bare ref one node. A hop whose core holds no node, as the -// library's own GetRootNode reads one, adds none. -func copied[T, S any, R chainable[T, S]](serviceContext Ctx, ref R) []*yaml.Node { - hops := componentlookup.Hops[T, S](serviceContext.Bindings(), ref) +// the chain passes through (hops), whose fields beside its own $ref lower at +// every use too (componentlookup.UseDocs, and a path item's every field). What +// ref writes beside its $ref is kept on each node the use lowers to, so it is +// charged as a hop's is, and a bare ref one node. A hop whose core holds no +// node, as the library's own GetRootNode reads one, adds none. +func copied[T, S any, R chainable[T, S]](ref R, hops []componentlookup.Hop[R]) []*yaml.Node { nodes := appendRoot(make([]*yaml.Node, 0, 1+len(hops)), ref.GetCoreAny()) for _, hop := range hops { nodes = appendRoot(nodes, hop.Ref.GetCoreAny()) diff --git a/compilers/openapi/internal/service/expansion_hops_test.go b/compilers/openapi/internal/service/expansion_hops_test.go index 6e9b1ae49..8f0a1e52c 100644 --- a/compilers/openapi/internal/service/expansion_hops_test.go +++ b/compilers/openapi/internal/service/expansion_hops_test.go @@ -5,6 +5,9 @@ package service_test import ( "fmt" + "math" + "reflect" + "runtime" "strings" "testing" @@ -13,6 +16,7 @@ import ( "github.com/stretchr/testify/require" "github.com/dexpace/morphic/compilers/openapi/internal/budget" + "github.com/dexpace/morphic/compilers/openapi/internal/componentlookup" "github.com/dexpace/morphic/compilers/openapi/internal/service" ) @@ -94,3 +98,39 @@ func TestDeclared_ChargesEachAliasWhatItWritesBesideItsRef(t *testing.T) { }) } } + +// TestDeclared_ReadsItsChainOnce pins what a use through a chain of aliases +// allocates: the chain's hops read once, into a slice of their count, and the +// nodes they copy. A use through sixteen times the aliases makes as many +// allocations, which growing the hops one at a time would not, and each alias +// more costs less than two hops, which reading the chain again for the copies +// it charges would. Not parallel: both counts are the process's. +func TestDeclared_ReadsItsChainOnce(t *testing.T) { + type cost struct{ allocations, bytes float64 } + costOf := func(aliases int) cost { + serviceContext := loaded(t, chainedParameter(aliases, ""), budget.Unbounded()) + a, ok := serviceContext.Doc.Paths.Get("/a") + require.True(t, ok) + use := a.GetObject().Get().GetParameters()[0] + var declared *soa.Parameter + declare := func() { + declared, _, _ = service.Declared[soa.Parameter](serviceContext, use, "/paths/~1a/get/parameters/0") + } + allocations := testing.AllocsPerRun(20, declare) + require.NotNil(t, declared, "%d aliases", aliases) + var stats runtime.MemStats + least := uint64(math.MaxUint64) + for range 3 { + runtime.ReadMemStats(&stats) + before := stats.TotalAlloc + declare() + runtime.ReadMemStats(&stats) + least = min(least, stats.TotalAlloc-before) + } + return cost{allocations: allocations, bytes: float64(least)} + } + short, long := costOf(16), costOf(256) + assert.Equal(t, short.allocations, long.allocations, "allocations at 16 and 256 aliases") + hop := reflect.TypeFor[componentlookup.Hop[*soa.ReferencedParameter]]().Size() + assert.Less(t, (long.bytes-short.bytes)/(256-16), float64(2*hop), "bytes at 16 and 256 aliases: %v, %v", short.bytes, long.bytes) +} diff --git a/compilers/openapi/internal/service/service.go b/compilers/openapi/internal/service/service.go index e6bee7374..08d57d2aa 100644 --- a/compilers/openapi/internal/service/service.go +++ b/compilers/openapi/internal/service/service.go @@ -228,7 +228,7 @@ func Declared[T, S any, R chainable[T, S], P interface { return nil, serviceContext, usePtr } use := serviceContext.Position(usePtr) - obj, decl := componentlookup.ObjectAt[T, S](serviceContext.RefScope(), ref, use) + obj, decl, hops := componentlookup.ObjectAt[T, S](serviceContext.RefScope(), ref, use) if obj == nil || decl == use { return obj, serviceContext, usePtr } @@ -238,7 +238,7 @@ func Declared[T, S any, R chainable[T, S], P interface { // inline entry is not charged here: a path item's own inline parameters are // charged where its additionalOperations entries take them // (ChargeExpansionAt). - if !serviceContext.expansion.admit(readingOf(serviceContext, usePtr), P(obj).GetRootNode(), copied[T, S](serviceContext, ref)...) { + if !serviceContext.expansion.admit(readingOf(serviceContext, usePtr), P(obj).GetRootNode(), copied[T, S](ref, hops)...) { return nil, serviceContext, usePtr } there, ok := InDocument(serviceContext, decl.Doc) diff --git a/compilers/openapi/internal/sourcetreestats/measure.go b/compilers/openapi/internal/sourcetreestats/measure.go index 51f820bca..303d70da9 100644 --- a/compilers/openapi/internal/sourcetreestats/measure.go +++ b/compilers/openapi/internal/sourcetreestats/measure.go @@ -14,7 +14,7 @@ import ( ) // Measure takes how deeply a subtree nests: the mappings and sequences its -// deepest path passes through, an alias standing for the node it names, as in +// deepest path passes through, an alias naming the node it names, as in // the tree the parser builds, whose cost per node grows with depth (GitHub // #905). // @@ -201,7 +201,7 @@ func Level(node *yaml.Node) int { } // scalarText is the bytes of text a scalar node holds, and nothing for any -// other node: an alias adds what it names, which the shape it stands for holds. +// other node: an alias adds what it names, which the shape it names holds. func scalarText(node *yaml.Node) int { if node.Kind != yaml.ScalarNode { return 0 diff --git a/compilers/openapi/internal/sourcetreestats/sourcetreestats_test.go b/compilers/openapi/internal/sourcetreestats/sourcetreestats_test.go index d1dcbe9e9..b494fbede 100644 --- a/compilers/openapi/internal/sourcetreestats/sourcetreestats_test.go +++ b/compilers/openapi/internal/sourcetreestats/sourcetreestats_test.go @@ -374,7 +374,7 @@ func TestNesting_CountsTheMappingsAndSequencesOnTheDeepestPath(t *testing.T) { } // TestNesting_AnAliasNestsAsItsTarget pins that the nesting is the parser's, -// which builds an alias's target where the alias stands. Each anchor below +// which builds an alias's target where the alias sits. Each anchor below // nests the one before it through an alias, so the tree as written is two // levels deep while the one the parser builds is one level deeper per anchor: // what let a document nested a few hundred levels as written reach thousands. diff --git a/compilers/openapi/internal/specrules/absence.go b/compilers/openapi/internal/specrules/absence.go new file mode 100644 index 000000000..d4195e7dd --- /dev/null +++ b/compilers/openapi/internal/specrules/absence.go @@ -0,0 +1,126 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package specrules + +import ( + "strconv" + "strings" + + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" +) + +// EquatesToAbsence reports whether value, written under the keyword name in a +// schema r reads, holds the value JSON Schema or OpenAPI equates with the +// keyword's absence, in a dialect defining that keyword +// (docs/compilers/openapi.md#null-keywords): a flag false (Validation 2020-12 +// §9.3, §9.4), a count floor 0, an empty `required` where the dialect admits +// one, at 3.0 a false `nullable` or boolean exclusive bound, and an empty +// `pattern`, which matches every string. An applicator never is, nor `format`, +// an annotation whose value is collected. +func (r SchemaRules) EquatesToAbsence(name string, value *yaml.Node) bool { + if slot, _ := r.Slot(name); slot == SlotUnknown || WritesNull(value) { + return false + } + node := nodeview.Deref(value) + switch name { + case "readOnly", "writeOnly", "deprecated", "uniqueItems", "nullable": + return writesFalse(node) + case "exclusiveMinimum", "exclusiveMaximum": + return r.Takes(name, Boolean) && writesFalse(node) + case "minLength", "minItems", "minProperties": + return writesZero(node) + case "required": + return node != nil && node.Kind == yaml.SequenceNode && len(node.Content) == 0 && r.AdmitsEmptyList(name) + case "pattern": + return node != nil && node.Kind == yaml.ScalarNode && node.ShortTag() == "!!str" && node.Value == "" + default: + return false + } +} + +// ValueForm is the form of a key's value that decides, with the keyword it is +// written under, whether the value is read (ValueIsRead). +type ValueForm uint8 + +const ( + // ValueStated is a value neither null nor the one its keyword equates + // with its absence. + ValueStated ValueForm = iota + // ValueNull is a null, which no keyword equates with its absence. + ValueNull + // ValueEquatesToAbsence is the value its keyword equates with its + // absence (SchemaRules.EquatesToAbsence). + ValueEquatesToAbsence +) + +// ReadsValue reports whether value, written under the keyword name in a schema +// r reads, says something of the instance (ValueIsRead). +func (r SchemaRules) ReadsValue(name string, value *yaml.Node) bool { + slot, _ := r.Slot(name) + return ValueIsRead(name, slot != SlotUnknown, r.FormOf(name, value)) +} + +// FormOf returns the form of value, written under the keyword name in a +// schema r reads. +func (r SchemaRules) FormOf(name string, value *yaml.Node) ValueForm { + switch { + case r.EquatesToAbsence(name, value): + return ValueEquatesToAbsence + case WritesNull(value): + return ValueNull + default: + return ValueStated + } +} + +// ValueIsRead reports whether the value of a key named name is read, given +// whether the rows define the keyword and the value's form. One equated with +// the keyword's absence says nothing, and a null is read only where the +// keyword holds an instance, as const, default and example do, or no row +// defines it (docs/compilers/openapi.md#null-keywords). +func ValueIsRead(name string, defined bool, form ValueForm) bool { + switch form { + case ValueEquatesToAbsence: + return false + case ValueNull: + return !defined || name == "const" || name == "default" || name == "example" + default: // ValueStated + return true + } +} + +// WritesNull reports whether value, its alias followed, is a null. +func WritesNull(value *yaml.Node) bool { + value = nodeview.Deref(value) + return value != nil && value.Kind == yaml.ScalarNode && value.ShortTag() == "!!null" +} + +// writesFalse reports whether node is the boolean false. +func writesFalse(node *yaml.Node) bool { + if node == nil || node.Kind != yaml.ScalarNode || node.ShortTag() != "!!bool" { + return false + } + value, err := strconv.ParseBool(node.Value) + return err == nil && !value +} + +// writesZero reports whether node is a number equal to zero, however written: +// `0`, `-0`, `0.0` or `0e3`. +func writesZero(node *yaml.Node) bool { + if node == nil || node.Kind != yaml.ScalarNode { + return false + } + switch node.ShortTag() { + case "!!int": + value, err := strconv.ParseInt(node.Value, 0, 64) + return err == nil && value == 0 + case "!!float": + mantissa, _, _ := strings.Cut(strings.ToLower(strings.TrimLeft(node.Value, "+-")), "e") + return strings.ContainsRune(mantissa, '0') && strings.Trim(mantissa, "0.") == "" + default: + return false + } +} diff --git a/compilers/openapi/internal/specrules/absence_internal_test.go b/compilers/openapi/internal/specrules/absence_internal_test.go new file mode 100644 index 000000000..62ebe38da --- /dev/null +++ b/compilers/openapi/internal/specrules/absence_internal_test.go @@ -0,0 +1,37 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package specrules + +import ( + "testing" + + "github.com/stretchr/testify/assert" + yaml "go.yaml.in/yaml/v3" +) + +// TestWritesZero_ReadsOnlyANumberEqualToZero pins what a count floor equal to +// its absence is written as: a number equal to zero in any spelling the YAML +// resolver types as one, and nothing else, neither the text "0", nor a list +// holding 0, nor no node. The parser's model holds a floor of another type as +// a null, so only this reader's own contract reaches the last three. +func TestWritesZero_ReadsOnlyANumberEqualToZero(t *testing.T) { + t.Parallel() + scalar := func(tag, value string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: tag, Value: value} } + for name, tc := range map[string]struct { + node *yaml.Node + want bool + }{ + "an integer": {scalar("!!int", "0"), true}, + "a hex integer": {scalar("!!int", "0x0"), true}, + "a negative float": {scalar("!!float", "-0.0"), true}, + "an exponent": {scalar("!!float", "0e3"), true}, + "one": {scalar("!!int", "1"), false}, + "a fraction": {scalar("!!float", "0.5"), false}, + "text": {scalar("!!str", "0"), false}, + "a list holding 0": {&yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: []*yaml.Node{scalar("!!int", "0")}}, false}, + "no node": {nil, false}, + } { + assert.Equal(t, tc.want, writesZero(tc.node), name) + } +} diff --git a/compilers/openapi/internal/specrules/absence_test.go b/compilers/openapi/internal/specrules/absence_test.go new file mode 100644 index 000000000..7d81f7392 --- /dev/null +++ b/compilers/openapi/internal/specrules/absence_test.go @@ -0,0 +1,59 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package specrules_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" +) + +// valueOf parses source, one YAML value, into its node. +func valueOf(t *testing.T, source string) *yaml.Node { + t.Helper() + var document yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(source), &document)) + require.Len(t, document.Content, 1) + return document.Content[0] +} + +// TestSchemaRules_ReadEachKeyAsTheLoweringDoes pins the reading of a key's +// value every reader of a schema's keys shares: a value its keyword equates +// with its absence, in a dialect defining the keyword, is not read, nor a null +// of a keyword holding no instance; a null of const, default or example, or of +// a key the rows do not define, is a value (docs/compilers/openapi.md#null-keywords). +func TestSchemaRules_ReadEachKeyAsTheLoweringDoes(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + version, dialect, name, value string + equatesToAbsence, read bool + }{ + {"3.1.0", "", "uniqueItems", "false", true, false}, + {"3.1.0", "", "uniqueItems", "true", false, true}, + {"3.1.0", "", "readOnly", "false", true, false}, + {"3.1.0", "", "minLength", "0", true, false}, + {"3.1.0", "", "minLength", "0.0", true, false}, + {"3.1.0", "", "minLength", "1", false, true}, + {"3.1.0", "", "required", "[]", true, false}, + {"3.1.0", draft04, "required", "[]", false, true}, + {"3.1.0", "", "pattern", "''", true, false}, + {"3.1.0", "", "pattern", "a", false, true}, + {"3.0.3", "", "exclusiveMinimum", "false", true, false}, + {"3.1.0", "", "exclusiveMinimum", "false", false, true}, + {"3.0.3", "", "nullable", "false", true, false}, + {"3.1.0", "", "format", "''", false, true}, + {"3.1.0", "", "maxLength", "null", false, false}, + {"3.1.0", "", "default", "null", false, true}, + {"3.1.0", "", "const", "null", false, true}, + {"3.0.3", "", "example", "null", false, true}, + {"3.1.0", "", "x-a", "null", false, true}, + {"3.0.3", "", "uniqueItems", "!!str false", false, true}, + } { + rules, value := rulesOf(tc.version, tc.dialect), valueOf(t, tc.value) + assert.Equal(t, tc.equatesToAbsence, rules.EquatesToAbsence(tc.name, value), "%s %s: %s: %s", tc.version, tc.dialect, tc.name, tc.value) + assert.Equal(t, tc.read, rules.ReadsValue(tc.name, value), "%s %s: %s: %s", tc.version, tc.dialect, tc.name, tc.value) + } +} diff --git a/compilers/openapi/internal/specrules/build.go b/compilers/openapi/internal/specrules/build.go index 600075846..9a9a609a6 100644 --- a/compilers/openapi/internal/specrules/build.go +++ b/compilers/openapi/internal/specrules/build.go @@ -21,23 +21,23 @@ func field(name string, shape Shape, cites ...Cite) Field { // objectOf returns a field holding one object of kind kind. func objectOf(name string, kind Kind, cites ...Cite) Field { - fieldValue := field(name, Nested, cites...) - fieldValue.Of = kind - return fieldValue + field := field(name, Nested, cites...) + field.Of = kind + return field } // mapOf returns a field holding a map of objects of kind kind. func mapOf(name string, kind Kind, cites ...Cite) Field { - fieldValue := field(name, Map, cites...) - fieldValue.Of = kind - return fieldValue + field := field(name, Map, cites...) + field.Of = kind + return field } // listOf returns a field holding a list of objects of kind kind. func listOf(name string, kind Kind, cites ...Cite) Field { - fieldValue := field(name, List, cites...) - fieldValue.Of = kind - return fieldValue + field := field(name, List, cites...) + field.Of = kind + return field } // during narrows the minors that define the field. @@ -117,8 +117,8 @@ func val(name string) Value { return Value{Name: name, Span: Always()} } // vals returns the values every minor admits. func vals(names ...string) []Value { out := make([]Value, len(names)) - for i, n := range names { - out[i] = val(n) + for i, name := range names { + out[i] = val(name) } return out } diff --git a/compilers/openapi/internal/specrules/code.go b/compilers/openapi/internal/specrules/code.go index 7477415d1..4b640de22 100644 --- a/compilers/openapi/internal/specrules/code.go +++ b/compilers/openapi/internal/specrules/code.go @@ -57,8 +57,8 @@ func standardMethods() []string { // tagParents reports a tag whose parent no tag declares, and a tag nested under // itself through its parents. A name declared twice is nested as its first // declaration says, as the lowering groups it. -func tagParents(rulerValue ruler, rule Rule) { - list := nodeview.Deref(rulerValue.f.byKey["tags"]) +func tagParents(ruler ruler, rule Rule) { + list := nodeview.Deref(ruler.f.byKey["tags"]) if list == nil || list.Kind != yaml.SequenceNode { return } @@ -66,7 +66,7 @@ func tagParents(rulerValue ruler, rule Rule) { parent := map[string]string{} declared := map[string]bool{} for _, item := range list.Content { - kv := rulerValue.keysOf(item) + kv := ruler.keysOf(item) name, ok := textOf(kv["name"]) if !ok || declared[name] { continue @@ -79,16 +79,16 @@ func tagParents(rulerValue ruler, rule Rule) { } onCycle := cycles(names, parent) for i, item := range list.Content { - kv := rulerValue.keysOf(item) + kv := ruler.keysOf(item) name, named := textOf(kv["name"]) up, nested := textOf(kv["parent"]) - ptr := itemPointer(rulerValue.f.at.ptr.AppendToken("tags"), i).AppendToken("parent") + ptr := itemPointer(ruler.f.at.ptr.AppendToken("tags"), i).AppendToken("parent") switch { case !named || !nested: case !declared[up]: - rulerValue.fail(rule, classReference, ptr, "tag "+quote(name)+" is nested under "+quote(up)+", which no tag declares") + ruler.fail(rule, classReference, ptr, "tag "+quote(name)+" is nested under "+quote(up)+", which no tag declares") case parent[name] == up && onCycle[name]: - rulerValue.fail(rule, classCircular, ptr, "tag "+quote(name)+" is nested under itself through its parents") + ruler.fail(rule, classCircular, ptr, "tag "+quote(name)+" is nested under itself through its parents") } } } @@ -108,8 +108,8 @@ func cycles(names []string, parent map[string]string) map[string]bool { break } if i, seen := at[name]; seen { - for _, n := range path[i:] { - on[n] = true + for _, token := range path[i:] { + on[token] = true } break } @@ -121,15 +121,15 @@ func cycles(names []string, parent map[string]string) map[string]bool { } name = up } - for _, n := range path { - done[n] = true + for _, token := range path { + done[token] = true } } return on } // quote spells a name in the double quotes a message uses. -func quote(s string) string { return `"` + s + `"` } +func quote(text string) string { return `"` + text + `"` } // operationAt is one operation of a path item, where it is written. type operationAt struct { @@ -139,15 +139,15 @@ type operationAt struct { // operationsOf lists the operations a path item writes, its own methods and the // entries of additionalOperations. -func operationsOf(rulerValue ruler, item map[string]*yaml.Node, ptr jsontext.Pointer) []operationAt { +func operationsOf(ruler ruler, item map[string]*yaml.Node, ptr jsontext.Pointer) []operationAt { var out []operationAt - for _, m := range standardMethods() { - if operation, ok := item[m]; ok { - out = append(out, operationAt{node: operation, ptr: ptr.AppendToken(m)}) + for _, method := range standardMethods() { + if operation, ok := item[method]; ok { + out = append(out, operationAt{node: operation, ptr: ptr.AppendToken(method)}) } } extra := ptr.AppendToken("additionalOperations") - for _, pair := range rulerValue.w.view.MappingPairs(item["additionalOperations"]) { + for _, pair := range ruler.w.view.MappingPairs(item["additionalOperations"]) { out = append(out, operationAt{node: pair.Val, ptr: extra.AppendToken(pair.Key)}) } return out @@ -174,19 +174,19 @@ func fragmentAt(path string) int { } return len(path) case '{': - if n := strings.IndexAny(path[i+1:], "{}"); n > 0 && path[i+1+n] == '}' { - i += n + 1 + if offset := strings.IndexAny(path[i+1:], "{}"); offset > 0 && path[i+1+offset] == '}' { + i += offset + 1 } } } return len(path) } -// braced returns the text of each {group} s writes, up to the first brace no +// braced returns the text of each {group} text writes, up to the first brace no // group closes. -func braced(s string) []string { +func braced(text string) []string { var out []string - rest := s + rest := text for { _, after, ok := strings.Cut(rest, "{") if !ok { @@ -203,9 +203,9 @@ func braced(s string) []string { // distinctTemplates reports a path that is the same as an earlier one once the // names of its template expressions are set aside. -func distinctTemplates(rulerValue ruler, rule Rule) { +func distinctTemplates(ruler ruler, rule Rule) { first := map[string]string{} - for _, pair := range rulerValue.f.pairs { + for _, pair := range ruler.f.pairs { if strings.HasPrefix(pair.Key, "x-") { continue } @@ -214,7 +214,7 @@ func distinctTemplates(rulerValue ruler, rule Rule) { shape = strings.Replace(shape, "{"+name+"}", "{}", 1) } if earlier, dup := first[shape]; dup { - rulerValue.fail(rule, classDuplicate, rulerValue.f.at.ptr.AppendToken(pair.Key), + ruler.fail(rule, classDuplicate, ruler.f.at.ptr.AppendToken(pair.Key), "path "+quote(pair.Key)+" is identical to "+quote(earlier)+" once the template names are set aside") continue } @@ -244,16 +244,16 @@ func (l paramList) answers(name string) bool { // pathParams reads the path parameters a parameter list writes, a $ref into // the components read there. -func pathParams(rulerValue ruler, list *yaml.Node, ptr jsontext.Pointer) paramList { +func pathParams(ruler ruler, list *yaml.Node, ptr jsontext.Pointer) paramList { node := nodeview.Deref(list) if node == nil || node.Kind != yaml.SequenceNode { return paramList{} } var out paramList for i, entry := range node.Content { - kv := rulerValue.keysOf(entry) + kv := ruler.keysOf(entry) if ref, ok := textOf(kv["$ref"]); ok { - kv = rulerValue.keysOf(localParameter(rulerValue, ref)) + kv = ruler.keysOf(localParameter(ruler, ref)) if _, again := kv["$ref"]; again || len(kv) == 0 { out.unread = true continue @@ -269,25 +269,25 @@ func pathParams(rulerValue ruler, list *yaml.Node, ptr jsontext.Pointer) paramLi // localParameter follows a $ref of the form #/components/parameters/name in the // document being checked, one hop. -func localParameter(rulerValue ruler, ref string) *yaml.Node { +func localParameter(ruler ruler, ref string) *yaml.Node { name, ok := strings.CutPrefix(ref, "#/components/parameters/") - if !ok || rulerValue.w.root == nil || strings.Contains(name, "/") { + if !ok || ruler.w.root == nil || strings.Contains(name, "/") { return nil } name = strings.NewReplacer("~1", "/", "~0", "~").Replace(name) - node := rulerValue.w.view.ChildByToken(nodeview.Deref(rulerValue.w.root), "components") - node = rulerValue.w.view.ChildByToken(nodeview.Deref(node), "parameters") - return rulerValue.w.view.ChildByToken(nodeview.Deref(node), name) + node := ruler.w.view.ChildByToken(nodeview.Deref(ruler.w.root), "components") + node = ruler.w.view.ChildByToken(nodeview.Deref(node), "parameters") + return ruler.w.view.ChildByToken(nodeview.Deref(node), name) } // templateParameters reports a path parameter that names no template expression // of its path, and a template expression that no path parameter answers: one in // the path item itself, or one in each of its operations. -func templateParameters(rulerValue ruler, rule Rule) { - for _, pair := range rulerValue.f.pairs { - item := rulerValue.keysOf(pair.Val) +func templateParameters(ruler ruler, rule Rule) { + for _, pair := range ruler.f.pairs { + item := ruler.keysOf(pair.Val) if !strings.HasPrefix(pair.Key, "x-") && len(item) > 0 { - checkPathItem(rulerValue, rule, pair.Key, item) + checkPathItem(ruler, rule, pair.Key, item) } } } @@ -297,24 +297,24 @@ func templateParameters(rulerValue ruler, rule Rule) { // which the specification allows of an empty item. One that writes a $ref // shares what the item it names holds with the operations written beside it, // as the lowering does, so a path parameter there may answer for any of them. -func checkPathItem(rulerValue ruler, rule Rule, path string, item map[string]*yaml.Node) { - ptr := rulerValue.f.at.ptr.AppendToken(path) +func checkPathItem(ruler ruler, rule Rule, path string, item map[string]*yaml.Node) { + ptr := ruler.f.at.ptr.AppendToken(path) exprs := expressions(path) - shared := pathParams(rulerValue, item["parameters"], ptr.AppendToken("parameters")) + shared := pathParams(ruler, item["parameters"], ptr.AppendToken("parameters")) if _, refers := item["$ref"]; refers { shared.unread = true } - reportStrayParams(rulerValue, rule, path, exprs, shared) - operations := operationsOf(rulerValue, item, ptr) + reportStrayParams(ruler, rule, path, exprs, shared) + operations := operationsOf(ruler, item, ptr) perOperation := make([]paramList, 0, len(operations)) for _, operation := range operations { - own := pathParams(rulerValue, rulerValue.keysOf(operation.node)["parameters"], operation.ptr.AppendToken("parameters")) - reportStrayParams(rulerValue, rule, path, exprs, own) + own := pathParams(ruler, ruler.keysOf(operation.node)["parameters"], operation.ptr.AppendToken("parameters")) + reportStrayParams(ruler, rule, path, exprs, own) perOperation = append(perOperation, own) } for _, name := range exprs { if unanswered(name, shared, perOperation) { - rulerValue.fail(rule, classReference, ptr, + ruler.fail(rule, classReference, ptr, "template expression {"+name+"} of "+quote(path)+" has no path parameter in the path item or in each of its operations") } } @@ -327,10 +327,10 @@ func unanswered(name string, shared paramList, perOperation []paramList) bool { } // reportStrayParams reports each path parameter that names none of exprs. -func reportStrayParams(rulerValue ruler, rule Rule, path string, exprs []string, params paramList) { +func reportStrayParams(ruler ruler, rule Rule, path string, exprs []string, params paramList) { for _, pp := range params.found { if !slices.Contains(exprs, pp.name) { - rulerValue.fail(rule, classReference, pp.ptr, + ruler.fail(rule, classReference, pp.ptr, "path parameter "+quote(pp.name)+" matches no template expression of "+quote(path)) } } @@ -338,28 +338,28 @@ func reportStrayParams(rulerValue ruler, rule Rule, path string, exprs []string, // serverTemplate reports a server URL that is no template: a brace with no // partner, an empty variable name, or a variable written twice. -func serverTemplate(rulerValue ruler, rule Rule) { - url, ok := textOf(rulerValue.f.byKey["url"]) +func serverTemplate(ruler ruler, rule Rule) { + url, ok := textOf(ruler.f.byKey["url"]) if !ok { return } if fault := templateFault(url); fault != "" { - rulerValue.fail(rule, classSyntax, rulerValue.f.at.ptr.AppendToken("url"), "field \"url\" "+fault) + ruler.fail(rule, classSyntax, ruler.f.at.ptr.AppendToken("url"), "field \"url\" "+fault) } } // serverVariables reports a variable a server URL names in braces that its // variables map does not define: the URL has nothing to substitute there. A // group naming no usable variable is the template's fault, not a variable's. -func serverVariables(rulerValue ruler, rule Rule) { - url, ok := textOf(rulerValue.f.byKey["url"]) +func serverVariables(ruler ruler, rule Rule) { + url, ok := textOf(ruler.f.byKey["url"]) if !ok { return } - defined := rulerValue.keysOf(rulerValue.f.byKey["variables"]) + defined := ruler.keysOf(ruler.f.byKey["variables"]) for _, name := range braced(url) { if _, ok := defined[name]; !ok && name != "" && !strings.Contains(name, "{") { - rulerValue.fail(rule, classReference, rulerValue.f.at.ptr.AppendToken("url"), + ruler.fail(rule, classReference, ruler.f.at.ptr.AppendToken("url"), "field \"url\" names the variable "+quote(name)+", which variables does not define") } } @@ -367,8 +367,8 @@ func serverVariables(rulerValue ruler, rule Rule) { // serverURLParts reports a server URL writing a query or a fragment outside // its variables' braces. -func serverURLParts(rulerValue ruler, rule Rule) { - url, ok := textOf(rulerValue.f.byKey["url"]) +func serverURLParts(ruler ruler, rule Rule) { + url, ok := textOf(ruler.f.byKey["url"]) if !ok { return } @@ -378,7 +378,7 @@ func serverURLParts(rulerValue ruler, rule Rule) { } if i := strings.IndexAny(literal, "?#"); i >= 0 { part := map[byte]string{'?': "a query", '#': "a fragment"}[literal[i]] - rulerValue.fail(rule, classSyntax, rulerValue.f.at.ptr.AppendToken("url"), "field \"url\" carries "+part) + ruler.fail(rule, classSyntax, ruler.f.at.ptr.AppendToken("url"), "field \"url\" carries "+part) } } @@ -410,11 +410,11 @@ func templateFault(url string) string { // additionalMethods reports an additionalOperations entry named for a method // that has a field of its own. -func additionalMethods(rulerValue ruler, rule Rule) { - base := rulerValue.f.at.ptr.AppendToken("additionalOperations") - for _, pair := range rulerValue.w.view.MappingPairs(rulerValue.f.byKey["additionalOperations"]) { +func additionalMethods(ruler ruler, rule Rule) { + base := ruler.f.at.ptr.AppendToken("additionalOperations") + for _, pair := range ruler.w.view.MappingPairs(ruler.f.byKey["additionalOperations"]) { if slices.Contains(standardMethods(), strings.ToLower(pair.Key)) { - rulerValue.fail(rule, classValues, base.AppendToken(pair.Key), + ruler.fail(rule, classValues, base.AppendToken(pair.Key), "additionalOperations holds an entry for "+quote(pair.Key)+", which the field "+quote(strings.ToLower(pair.Key))+" defines") } } @@ -429,16 +429,16 @@ func contentOwners() []Kind { return []Kind{RequestBody, Response, Parameter, He // type, prefixEncoding or itemEncoding under one that is not multipart, and, // before 3.2, encoding outside a request body. A Media Type Object held under // any other key, a component's name, names no media type, so it is not judged. -func encodingApplies(rulerValue ruler, rule Rule) { - if !slices.Contains(contentOwners(), rulerValue.f.at.in) { +func encodingApplies(ruler ruler, rule Rule) { + if !slices.Contains(contentOwners(), ruler.f.at.in) { return } // RFC 6838 §4.2: names are case-insensitive, and parameters follow a ';'. - name, _, _ := strings.Cut(rulerValue.f.at.held, ";") + name, _, _ := strings.Cut(ruler.f.at.held, ";") name = strings.ToLower(strings.TrimSpace(name)) multipart := strings.HasPrefix(name, "multipart/") for _, field := range []string{"encoding", "prefixEncoding", "itemEncoding"} { - if !rulerValue.f.writes(field, rulerValue.w.minor) { + if !ruler.f.writes(field, ruler.w.minor) { continue } scope := "" @@ -447,12 +447,12 @@ func encodingApplies(rulerValue ruler, rule Rule) { scope = "to multipart and application/x-www-form-urlencoded media types alone" case field != "encoding" && !multipart: scope = "to multipart media types alone" - case field == "encoding" && rulerValue.w.minor < V32 && rulerValue.f.at.in != RequestBody: + case field == "encoding" && ruler.w.minor < V32 && ruler.f.at.in != RequestBody: scope = "to request bodies alone" } if scope != "" { - rulerValue.fail(rule, classNoEffect, rulerValue.f.at.ptr.AppendToken(field), - "field "+quote(field)+" has no effect under "+quote(rulerValue.f.at.held)+", which the specification applies "+scope) + ruler.fail(rule, classNoEffect, ruler.f.at.ptr.AppendToken(field), + "field "+quote(field)+" has no effect under "+quote(ruler.f.at.held)+", which the specification applies "+scope) } } } @@ -463,46 +463,46 @@ func encodingApplies(rulerValue ruler, rule Rule) { // (docs/compilers/openapi.md#nullable). Beside a `$ref` every key is a later // minor's construct, warned of as one (walker.reference), so it is left alone // there. -func nullableApplies(rulerValue ruler, rule Rule) { - node := nodeview.Deref(rulerValue.f.byKey["nullable"]) +func nullableApplies(ruler ruler, rule Rule) { + node := nodeview.Deref(ruler.f.byKey["nullable"]) if node == nil || !matches(Boolean, node) || !strings.EqualFold(node.Value, "true") || - rulerValue.f.writes("type", rulerValue.w.minor) || rulerValue.f.writes("$ref", rulerValue.w.minor) { + ruler.f.writes("type", ruler.w.minor) || ruler.f.writes("$ref", ruler.w.minor) { return } - rulerValue.fail(rule, classNoEffect, rulerValue.f.at.ptr.AppendToken("nullable"), + ruler.fail(rule, classNoEffect, ruler.f.at.ptr.AppendToken("nullable"), `field "nullable" has no effect without a "type" written in the same Schema Object, to which the specification applies it`) } // dependentRequired reports an entry of dependentRequired that is no list of // strings, and a string an entry lists twice: each lists the properties an // instance holding the entry's key must hold too. -func dependentRequired(rulerValue ruler, rule Rule) { - base := rulerValue.f.at.ptr.AppendToken("dependentRequired") - for _, pair := range rulerValue.w.view.MappingPairs(rulerValue.f.byKey["dependentRequired"]) { +func dependentRequired(ruler ruler, rule Rule) { + base := ruler.f.at.ptr.AppendToken("dependentRequired") + for _, pair := range ruler.w.view.MappingPairs(ruler.f.byKey["dependentRequired"]) { ptr := base.AppendToken(pair.Key) list := nodeview.Deref(pair.Val) if list == nil || !matches(StringList, list) { - rulerValue.fail(rule, classType, ptr, "field \"dependentRequired\" entry "+quote(pair.Key)+" must be a list of strings") + ruler.fail(rule, classType, ptr, "field \"dependentRequired\" entry "+quote(pair.Key)+" must be a list of strings") continue } - repeats(list, textOf, func(i, first int, s string) { - rulerValue.fail(rule, classDuplicate, itemPointer(ptr, i), "field \"dependentRequired\" entry "+quote(pair.Key)+ - " repeats "+quote(s)+" first written at "+string(rulerValue.w.placed(itemPointer(ptr, first)))) + repeats(list, textOf, func(i, first int, text string) { + ruler.fail(rule, classDuplicate, itemPointer(ptr, i), "field \"dependentRequired\" entry "+quote(pair.Key)+ + " repeats "+quote(text)+" first written at "+string(ruler.w.placed(itemPointer(ptr, first)))) }) } } // vocabulary reports a $vocabulary key that is no URI with a scheme, and a // value that is no boolean, which says whether the vocabulary is required. -func vocabulary(rulerValue ruler, rule Rule) { - base := rulerValue.f.at.ptr.AppendToken("$vocabulary") - for _, pair := range rulerValue.w.view.MappingPairs(rulerValue.f.byKey["$vocabulary"]) { +func vocabulary(ruler ruler, rule Rule) { + base := ruler.f.at.ptr.AppendToken("$vocabulary") + for _, pair := range ruler.w.view.MappingPairs(ruler.f.byKey["$vocabulary"]) { ptr := base.AppendToken(pair.Key) if !ValidFormat(AbsoluteURI, pair.Key) { - rulerValue.fail(rule, classFormat, ptr, "field \"$vocabulary\" has the key "+quote(pair.Key)+", which must be "+describeFormat(AbsoluteURI)) + ruler.fail(rule, classFormat, ptr, "field \"$vocabulary\" has the key "+quote(pair.Key)+", which must be "+describeFormat(AbsoluteURI)) } if node := nodeview.Deref(pair.Val); node == nil || !matches(Boolean, node) { - rulerValue.fail(rule, classType, ptr, "field \"$vocabulary\" entry "+quote(pair.Key)+" must be a boolean") + ruler.fail(rule, classType, ptr, "field \"$vocabulary\" entry "+quote(pair.Key)+" must be a boolean") } } } @@ -511,36 +511,36 @@ func vocabulary(rulerValue ruler, rule Rule) { // list is held to distinct strings, and to the entries the rule's Min counts, // any other entry is a schema, read as one, as the binder places it // (reftable.DialectRule.Dependencies), and one that is neither is reported. -func dependencies(rulerValue ruler, rule Rule) { - base := rulerValue.f.at.ptr.AppendToken("dependencies") - for _, pair := range rulerValue.w.view.MappingPairs(rulerValue.f.byKey["dependencies"]) { +func dependencies(ruler ruler, rule Rule) { + base := ruler.f.at.ptr.AppendToken("dependencies") + for _, pair := range ruler.w.view.MappingPairs(ruler.f.byKey["dependencies"]) { ptr := base.AppendToken(pair.Key) entry := nodeview.Deref(pair.Val) switch { case entry != nil && entry.Kind == yaml.SequenceNode: - propertyDependency(rulerValue, rule, pair.Key, entry, ptr) - case entry != nil && (entry.Kind == yaml.MappingNode || rulerValue.f.booleans && matches(Boolean, entry)): - rulerValue.w.object(objectToCheck{kind: Schema, node: pair.Val, ptr: ptr, held: pair.Key, rows: rulerValue.f.rows, in: Schema, - shared: rulerValue.f.shared}, rulerValue.f.depth+1) + propertyDependency(ruler, rule, pair.Key, entry, ptr) + case entry != nil && (entry.Kind == yaml.MappingNode || ruler.f.booleans && matches(Boolean, entry)): + ruler.w.object(objectToCheck{kind: Schema, node: pair.Val, ptr: ptr, held: pair.Key, rows: ruler.f.rows, in: Schema, + shared: ruler.f.shared}, ruler.f.depth+1) default: - rulerValue.fail(rule, classType, ptr, "field \"dependencies\" entry "+quote(pair.Key)+" must be a list of strings or a schema") + ruler.fail(rule, classType, ptr, "field \"dependencies\" entry "+quote(pair.Key)+" must be a list of strings or a schema") } } } // propertyDependency judges list, the entry of `dependencies` keyed key at ptr // that lists the properties an instance holding key must hold too. -func propertyDependency(rulerValue ruler, rule Rule, key string, list *yaml.Node, ptr jsontext.Pointer) { +func propertyDependency(ruler ruler, rule Rule, key string, list *yaml.Node, ptr jsontext.Pointer) { what := "field \"dependencies\" entry " + quote(key) switch { case !matches(StringList, list): - rulerValue.fail(rule, classType, ptr, what+" must be a list of strings or a schema") + ruler.fail(rule, classType, ptr, what+" must be a list of strings or a schema") return case len(list.Content) < rule.Min: - rulerValue.fail(rule, classCount, ptr, what+" must hold at least "+plural(rule.Min)) + ruler.fail(rule, classCount, ptr, what+" must hold at least "+plural(rule.Min)) } - repeats(list, textOf, func(i, first int, s string) { - rulerValue.fail(rule, classDuplicate, itemPointer(ptr, i), what+" repeats "+quote(s)+" first written at "+ - string(rulerValue.w.placed(itemPointer(ptr, first)))) + repeats(list, textOf, func(i, first int, text string) { + ruler.fail(rule, classDuplicate, itemPointer(ptr, i), what+" repeats "+quote(text)+" first written at "+ + string(ruler.w.placed(itemPointer(ptr, first)))) }) } diff --git a/compilers/openapi/internal/specrules/encodingrules.go b/compilers/openapi/internal/specrules/encodingrules.go index 87390da38..43330d84c 100644 --- a/compilers/openapi/internal/specrules/encodingrules.go +++ b/compilers/openapi/internal/specrules/encodingrules.go @@ -20,19 +20,19 @@ type EncodingRules struct{ rows *encodingRows } // media types each takes effect under there. It is built once and never // written. type encodingRows struct { - defaults map[defaultOf]string + defaults map[defaultKey]string limited map[string]bool - within map[withinOf]bool + within map[withinKey]bool } -// defaultOf keys a field's default in one case. -type defaultOf struct { +// defaultKey keys a field's default in one case. +type defaultKey struct { field string k DefaultCase } -// withinOf keys a field taking effect under one media type. -type withinOf struct{ field, mediaType string } +// withinKey keys a field taking effect under one media type. +type withinKey struct{ field, mediaType string } // EncodingRules returns the Encoding Object's rows at the minor version names, // and the zero EncodingRules for a version the table does not cover or a Spec @@ -46,17 +46,17 @@ func (s Spec) EncodingRules(version string) EncodingRules { if !ok { return EncodingRules{} } - rows := &encodingRows{defaults: map[defaultOf]string{}, limited: map[string]bool{}, within: map[withinOf]bool{}} - for _, defaultValue := range obj.Defaults { - if defaultValue.Span.Holds(minor) { - rows.defaults[defaultOf{field: defaultValue.Field, k: defaultValue.Case}] = defaultValue.Value + rows := &encodingRows{defaults: map[defaultKey]string{}, limited: map[string]bool{}, within: map[withinKey]bool{}} + for _, row := range obj.Defaults { + if row.Span.Holds(minor) { + rows.defaults[defaultKey{field: row.Field, k: row.Case}] = row.Value } } for _, field := range obj.Fields { for _, within := range field.Within { rows.limited[field.Name] = true if within.Span.Holds(minor) { - rows.within[withinOf{field: field.Name, mediaType: within.MediaType}] = true + rows.within[withinKey{field: field.Name, mediaType: within.MediaType}] = true } } } @@ -70,8 +70,8 @@ func (r EncodingRules) ContentType(defaultCase DefaultCase) (string, bool) { if r.rows == nil { return "", false } - v, ok := r.rows.defaults[defaultOf{field: "contentType", k: defaultCase}] - return v, ok + defaultRow, ok := r.rows.defaults[defaultKey{field: "contentType", k: defaultCase}] + return defaultRow, ok } // TakesEffect reports whether the Encoding Object's field takes effect under @@ -83,8 +83,8 @@ func (r EncodingRules) TakesEffect(field, mediaType string) bool { return false } typ, _, _ := strings.Cut(mediaType, "/") - return !r.rows.limited[field] || r.rows.within[withinOf{field: field, mediaType: mediaType}] || - r.rows.within[withinOf{field: field, mediaType: typ + "/*"}] + return !r.rows.limited[field] || r.rows.within[withinKey{field: field, mediaType: mediaType}] || + r.rows.within[withinKey{field: field, mediaType: typ + "/*"}] } // Ignores reports whether the table says the Encoding Object's field has no diff --git a/compilers/openapi/internal/specrules/engine.go b/compilers/openapi/internal/specrules/engine.go index a7e2d862b..0ba1cc3aa 100644 --- a/compilers/openapi/internal/specrules/engine.go +++ b/compilers/openapi/internal/specrules/engine.go @@ -34,7 +34,7 @@ type Options struct { // position. Locate Locator // Seen, when set, is told each mapping read as an object of a kind and - // not as a Reference Object standing in its place. The node is the + // not as a Reference Object taking its place. The node is the // mapping itself, its aliases followed. Seen func(kind Kind, node *yaml.Node) // Skip, when set, is asked of each mapping about to be read as an object @@ -48,7 +48,7 @@ type Options struct { // shares, with refused false. The node is the value, its alias followed. Judged func(node *yaml.Node, refused bool) // Referenced, when set, is told each mapping read as a Reference Object - // standing in the place of an object of kind, its aliases followed. + // taking the place of an object of kind, its aliases followed. Referenced func(kind Kind, node *yaml.Node) // Shared, when set, reads the root as an object other places may read as // other kinds, so Judged is told every value the check accepts, not only @@ -73,7 +73,7 @@ type Options struct { Rows SchemaRules // RootRows, when set, returns the rows the schema at a pointer, Root // included, is read with where it roots a dialect of its own, which - // stand over Rows and the rows of a schema holding it. + // sit over Rows and the rows of a schema holding it. RootRows func(at jsontext.Pointer) (SchemaRules, bool) // Later, when set, is handed each Schema Object no schema holds, which // the check then does not read: the rows it is read with are not known @@ -128,8 +128,8 @@ func (c Checker) CheckPending(ctx context.Context, pending []Pending, declared s if !ok { return nil } - for _, pendingValue := range pending { - walker.object(pendingValue.at, pendingValue.depth) + for _, pending := range pending { + walker.object(pending.at, pending.depth) } return walker.diags } @@ -141,18 +141,18 @@ func (c Checker) walker(ctx context.Context, declared string, opts Options) (*wa if !ok { return nil, false } - walkerValue := &walker{ctx: ctx, spec: c.spec, minor: minor, view: nodeview.New(), work: budget.New(opts.Budget)} - walkerValue.locate, walkerValue.declared, walkerValue.seen, walkerValue.rows = opts.Locate, declared, opts.Seen, opts.Rows - walkerValue.readAt, walkerValue.rootAt, walkerValue.said = opts.ReadAt, opts.Root, map[ir.DiagnosticKey]saying{} - walkerValue.rootRows, walkerValue.later, walkerValue.judged, walkerValue.referenced = opts.RootRows, opts.Later, opts.Judged, opts.Referenced - walkerValue.skip = opts.Skip - if walkerValue.rows.rows == nil { - walkerValue.rows, _ = c.spec.SchemaRules(declared, "") + walker := &walker{ctx: ctx, spec: c.spec, minor: minor, view: nodeview.New(), work: budget.New(opts.Budget)} + walker.locate, walker.declared, walker.seen, walker.rows = opts.Locate, declared, opts.Seen, opts.Rows + walker.readAt, walker.rootAt, walker.said = opts.ReadAt, opts.Root, map[ir.DiagnosticKey]saying{} + walker.rootRows, walker.later, walker.judged, walker.referenced = opts.RootRows, opts.Later, opts.Judged, opts.Referenced + walker.skip = opts.Skip + if walker.rows.rows == nil { + walker.rows, _ = c.spec.SchemaRules(declared, "") } - if walkerValue.locate == nil { - walkerValue.locate = func(jsontext.Pointer) ir.Provenance { return ir.Provenance{} } + if walker.locate == nil { + walker.locate = func(jsontext.Pointer) ir.Provenance { return ir.Provenance{} } } - return walkerValue, true + return walker, true } // walker is one check in progress. It holds the context the check runs under @@ -199,7 +199,7 @@ type objectToCheck struct { // frame is a mapping read as an object, how deep it is, and for a Schema // Object the rows it is read with, which its object is. booleans reports that -// true and false stand as the schemas its fields hold: by its rows for a +// true and false are the schemas its fields hold: by its rows for a // Schema Object, which decides for those it holds, else by its minor, where // the rows a schema is read with have the last word (shapeOf). where, // unless empty, names what a finding about it holds it to in place of its @@ -295,141 +295,141 @@ func (w *walker) charge(depth int) (ok, stops bool) { return false, true } -// reportStop reports that walkerValue's check stopped at ptr. -func reportStop(walkerValue *walker, ptr jsontext.Pointer) { - walkerValue.diags = append(walkerValue.diags, diag.Newf(ir.SeverityError, diag.BudgetExceeded, walkerValue.locate(ptr), - "the OpenAPI %s check stopped at this depth or work budget; what lies below is unchecked", walkerValue.minor)) +// reportStop reports that walker's check stopped at ptr. +func reportStop(walker *walker, ptr jsontext.Pointer) { + walker.diags = append(walker.diags, diag.Newf(ir.SeverityError, diag.BudgetExceeded, walker.locate(ptr), + "the OpenAPI %s check stopped at this depth or work budget; what lies below is unchecked", walker.minor)) } -// object checks the mapping objectToCheckValue holds as an object of its kind, +// object checks the mapping objectToCheck holds as an object of its kind, // and what lies below it. -func (w *walker) object(objectToCheckValue objectToCheck, depth int) { - obj, ok := w.spec.Object(objectToCheckValue.kind) - node := nodeview.Deref(objectToCheckValue.node) +func (w *walker) object(objectToCheck objectToCheck, depth int) { + obj, ok := w.spec.Object(objectToCheck.kind) + node := nodeview.Deref(objectToCheck.node) if !ok || node == nil { return } - if objectToCheckValue.kind == Schema && objectToCheckValue.in != Schema && w.later != nil { - w.later(Pending{at: objectToCheckValue, depth: depth}) + if objectToCheck.kind == Schema && objectToCheck.in != Schema && w.later != nil { + w.later(Pending{at: objectToCheck, depth: depth}) return } - if w.skip != nil && node.Kind == yaml.MappingNode && w.skip(objectToCheckValue.kind, node) { + if w.skip != nil && node.Kind == yaml.MappingNode && w.skip(objectToCheck.kind, node) { return } - if !w.spend(depth, objectToCheckValue.ptr) { + if !w.spend(depth, objectToCheck.ptr) { return } - frameValue := frame{obj: obj, at: objectToCheckValue, depth: depth, booleans: w.spec.booleanHeld(Schema, w.minor), - shared: objectToCheckValue.shared || sharedNode(objectToCheckValue.node)} - if objectToCheckValue.kind == Schema { - frameValue.rows = w.rowsAt(objectToCheckValue) - frameValue.obj, frameValue.booleans = frameValue.rows.rows.object, frameValue.rows.Booleans() - if frameValue.rows.rows.draft { - frameValue.where = "this schema's dialect" + frame := frame{obj: obj, at: objectToCheck, depth: depth, booleans: w.spec.booleanHeld(Schema, w.minor), + shared: objectToCheck.shared || sharedNode(objectToCheck.node)} + if objectToCheck.kind == Schema { + frame.rows = w.rowsAt(objectToCheck) + frame.obj, frame.booleans = frame.rows.rows.object, frame.rows.Booleans() + if frame.rows.rows.draft { + frame.where = "this schema's dialect" } } if node.Kind != yaml.MappingNode { - w.notMapping(frameValue, node) + w.notMapping(frame, node) return } - frameValue = frameOf(frameValue, node, w.view) - frameValue.shared = frameValue.shared || writesMerge(node) - w.accept(frameValue.shared, node) - w.repeated(node, objectToCheckValue.ptr, obj.Name) - if w.reference(frameValue, depth) { + frame = frameOf(frame, node, w.view) + frame.shared = frame.shared || writesMerge(node) + w.accept(frame.shared, node) + w.repeated(node, objectToCheck.ptr, obj.Name) + if w.reference(frame, depth) { return } if w.seen != nil { - w.seen(objectToCheckValue.kind, node) + w.seen(objectToCheck.kind, node) } - w.fields(frameValue, depth) - w.patterned(frameValue, depth) - w.unknown(frameValue) - rawKeys(w, frameValue, depth) - w.rules(frameValue) + w.fields(frame, depth) + w.patterned(frame, depth) + w.unknown(frame) + rawKeys(w, frame, depth) + w.rules(frame) } -// rawKeys reads for repeated keys the value of each key frameValue's object +// rawKeys reads for repeated keys the value of each key frame's object // reads as no field and the lowering keeps verbatim: an extension, and a key // the object defines at no minor, which unknown reports. An object taking // patterned keys reads each other key as an entry, as a schema reads a keyword // its dialect added later as a field. -func rawKeys(walkerValue *walker, frameValue frame, depth int) { - _, patterned := frameValue.obj.patternAt(walkerValue.minor) - for _, pair := range frameValue.pairs { - extension := strings.HasPrefix(pair.Key, "x-") && frameValue.obj.Extensible - if !extension && (patterned || frameValue.defines(pair.Key)) { +func rawKeys(walker *walker, frame frame, depth int) { + _, patterned := frame.obj.patternAt(walker.minor) + for _, pair := range frame.pairs { + extension := strings.HasPrefix(pair.Key, "x-") && frame.obj.Extensible + if !extension && (patterned || frame.defines(pair.Key)) { continue } - if _, later := frameValue.addedLater(pair.Key, walkerValue.minor); later { + if _, later := frame.addedLater(pair.Key, walker.minor); later { continue } - rawRepeats(walkerValue, pair.Val, frameValue.at.ptr.AppendToken(pair.Key), depth+1) + rawRepeats(walker, pair.Val, frame.at.ptr.AppendToken(pair.Key), depth+1) } } -// unknown reports each key frameValue's mapping writes that its object neither +// unknown reports each key frame's mapping writes that its object neither // defines at any minor nor admits: no field, no patterned key, no x- extension. // A Schema Object's keywords are its dialect's, and an object taking patterned // keys at the declared minor admits every key, so neither is judged here. A key // merged through `<<` is placed where it is written, as every field is. -func (w *walker) unknown(frameValue frame) { - if frameValue.rows.rows != nil { +func (w *walker) unknown(frame frame) { + if frame.rows.rows != nil { return } - if _, patterned := frameValue.obj.patternAt(w.minor); patterned { + if _, patterned := frame.obj.patternAt(w.minor); patterned { return } - places := newKeyPlacer(w, frameValue.at.node, frameValue.at.ptr) - for _, pair := range frameValue.pairs { - if frameValue.defines(pair.Key) || (frameValue.obj.Extensible && strings.HasPrefix(pair.Key, "x-")) { + places := newKeyPlacer(w, frame.at.node, frame.at.ptr) + for _, pair := range frame.pairs { + if frame.defines(pair.Key) || (frame.obj.Extensible && strings.HasPrefix(pair.Key, "x-")) { continue } message := fmt.Sprintf("key %q is not defined by the %s it is written on and is not an x- extension", - pair.Key, frameValue.obj.Name) - if frameValue.obj.Kind == Reference { + pair.Key, frame.obj.Name) + if frame.obj.Kind == Reference { message = fmt.Sprintf("key %q is written beside a $ref, where the Reference Object defines only $ref, "+ "summary and description, so OpenAPI ignores it", pair.Key) } w.add(diag.Newf(ir.SeverityWarning, diag.UnknownObjectKey, places.place(pair.Key), "%s", message), - frameValue.at.ptr.AppendToken(pair.Key)) + frame.at.ptr.AppendToken(pair.Key)) } } -// rowsAt returns the rows the Schema Object objectToCheckValue names is read +// rowsAt returns the rows the Schema Object objectToCheck names is read // with: a dialect root's own (Options.RootRows), else those of the schema // holding it, else its document's (Options.Rows). -func (w *walker) rowsAt(objectToCheckValue objectToCheck) SchemaRules { +func (w *walker) rowsAt(objectToCheck objectToCheck) SchemaRules { if w.rootRows != nil { - if rows, root := w.rootRows(w.rootAt + objectToCheckValue.ptr); root && rows.rows != nil { + if rows, root := w.rootRows(w.rootAt + objectToCheck.ptr); root && rows.rows != nil { return rows } } - if objectToCheckValue.in == Schema && objectToCheckValue.rows.rows != nil { - return objectToCheckValue.rows + if objectToCheck.in == Schema && objectToCheck.rows.rows != nil { + return objectToCheck.rows } return w.rows } -// frameOf reads node, a mapping, as the object frameValue is. -func frameOf(frameValue frame, node *yaml.Node, view *nodeview.View) frame { - frameValue.pairs = view.MappingPairs(node) - frameValue.byKey = make(map[string]*yaml.Node, len(frameValue.pairs)) - for _, pair := range frameValue.pairs { - frameValue.byKey[pair.Key] = pair.Val +// frameOf reads node, a mapping, as the object frame is. +func frameOf(frame frame, node *yaml.Node, view *nodeview.View) frame { + frame.pairs = view.MappingPairs(node) + frame.byKey = make(map[string]*yaml.Node, len(frame.pairs)) + for _, pair := range frame.pairs { + frame.byKey[pair.Key] = pair.Val } - return frameValue + return frame } -// notMapping reports a node that is no mapping where frameValue's kind needs +// notMapping reports a node that is no mapping where frame's kind needs // one, unless the kind admits a boolean there, and tells Options.Judged which. -func (w *walker) notMapping(frameValue frame, node *yaml.Node) { - if frameValue.obj.Boolean.Holds(w.minor) && matches(Boolean, node) { - w.accept(frameValue.shared, node) +func (w *walker) notMapping(frame frame, node *yaml.Node) { + if frame.obj.Boolean.Holds(w.minor) && matches(Boolean, node) { + w.accept(frame.shared, node) return } w.refuse(node) - w.report(ir.SeverityError, classType, frameValue.at.ptr, "%s must be an object in %s (%s)", frameValue.obj.Name, frameValue.in(w.minor), frameValue.obj.Name) + w.report(ir.SeverityError, classType, frame.at.ptr, "%s must be an object in %s (%s)", frame.obj.Name, frame.in(w.minor), frame.obj.Name) } // reference reads a mapping that writes $ref as a Reference Object where the @@ -439,38 +439,38 @@ func (w *walker) notMapping(frameValue frame, node *yaml.Node) { // $ref takes siblings only from a later minor (RefSiblings) draws it for each // key beside the $ref, which the declared minor ignores and the later one // applies. Options.Referenced is told of each it reads. -func (w *walker) reference(frameValue frame, depth int) bool { - if !frameValue.refers() { +func (w *walker) reference(frame frame, depth int) bool { + if !frame.refers() { return false } switch { - case frameValue.obj.Referenceable.Holds(w.minor): - case frameValue.obj.Referenceable.Later(w.minor): - w.laterField(frameValue.obj, "$ref", "", frameValue.obj.Referenceable.Since, frameValue.at.ptr.AppendToken("$ref")) - case frameValue.obj.RefSiblings.Later(w.minor): - for _, pair := range frameValue.pairs { + case frame.obj.Referenceable.Holds(w.minor): + case frame.obj.Referenceable.Later(w.minor): + w.laterField(frame.obj, "$ref", "", frame.obj.Referenceable.Since, frame.at.ptr.AppendToken("$ref")) + case frame.obj.RefSiblings.Later(w.minor): + for _, pair := range frame.pairs { if pair.Key != "$ref" { - w.laterSibling(frameValue.obj, pair.Key, w.minor, frameValue.obj.RefSiblings.Since, frameValue.at.ptr.AppendToken(pair.Key)) + w.laterSibling(frame.obj, pair.Key, w.minor, frame.obj.RefSiblings.Since, frame.at.ptr.AppendToken(pair.Key)) } } return false - case frameValue.rows.IgnoresRefFields(): - for _, pair := range frameValue.pairs { - if readsBesideRef(frameValue.rows, pair.Key) { - w.ignoredBesideRef(pair.Key, frameValue.at.ptr.AppendToken(pair.Key)) + case frame.rows.IgnoresRefFields(): + for _, pair := range frame.pairs { + if readsBesideRef(frame.rows, pair.Key) { + w.ignoredBesideRef(pair.Key, frame.at.ptr.AppendToken(pair.Key)) } } return false default: return false } - rf := frameValue + rf := frame rf.obj = w.spec.must(Reference) w.fields(rf, depth) w.unknown(rf) rawKeys(w, rf, depth) if w.referenced != nil { - w.referenced(frameValue.at.kind, nodeview.Deref(frameValue.at.node)) + w.referenced(frame.at.kind, nodeview.Deref(frame.at.node)) } return true } @@ -486,33 +486,33 @@ func (f frame) refers() bool { // a Schema Object the dialect the compiler reads natively, added: warned of // once, bar a key beside a 3.0 schema's $ref, which reference warned of, and // read as that minor or dialect reads it. -func (w *walker) fields(frameValue frame, depth int) { - for _, fld := range frameValue.obj.Fields { +func (w *walker) fields(frame frame, depth int) { + for _, fld := range frame.obj.Fields { if !fld.Defined.Holds(w.minor) { continue } - val, present := frameValue.byKey[fld.Name] + val, present := frame.byKey[fld.Name] if !present { - w.missing(frameValue, fld) + w.missing(frame, fld) continue } - w.value(frameValue, fld, val, depth) + w.value(frame, fld, val, depth) } - for _, pair := range frameValue.pairs { - fld, ok := frameValue.addedLater(pair.Key, w.minor) + for _, pair := range frame.pairs { + fld, ok := frame.addedLater(pair.Key, w.minor) if !ok { continue } - ptr := frameValue.at.ptr.AppendToken(pair.Key) - if frameValue.rows.rows == nil { - w.laterField(frameValue.obj, pair.Key, "", fld.Defined.Since, ptr) - w.value(frameValue, fld, pair.Val, depth) + ptr := frame.at.ptr.AppendToken(pair.Key) + if frame.rows.rows == nil { + w.laterField(frame.obj, pair.Key, "", fld.Defined.Since, ptr) + w.value(frame, fld, pair.Val, depth) continue } - if !frameValue.refers() || !frameValue.obj.RefSiblings.Later(w.minor) { - w.laterKeyword(frameValue.rows, pair.Key, frameValue.writesTuple(), ptr) + if !frame.refers() || !frame.obj.RefSiblings.Later(w.minor) { + w.laterKeyword(frame.rows, pair.Key, frame.writesTuple(), ptr) } - w.value(frameValue.asLater(fld, w.minor), fld, pair.Val, depth) + w.value(frame.asLater(fld, w.minor), fld, pair.Val, depth) } } @@ -528,7 +528,7 @@ func (f frame) addedLater(key string, minor Minor) (Field, bool) { } // asLater returns f as it reads fld, a field the dialect the compiler reads -// natively added: true and false stand as schemas there, as from 3.1, and a +// natively added: true and false are schemas there, as from 3.1, and a // finding holds it to that dialect's minor. Only fld's row is that dialect's: // the rules run at the declared minor, so at 3.0 none 3.1 states over the // field holds, such as prefixItems holding an entry. @@ -565,33 +565,33 @@ func (o Object) addedLater(key string, minor Minor) (Field, bool) { } // missing reports a required field the object does not write. -func (w *walker) missing(frameValue frame, fld Field) { +func (w *walker) missing(frame frame, fld Field) { if !fld.Required.Holds(w.minor) || fld.Owner != "" { return } cite := citeFor(fld.Cites, w.minor) - w.report(ir.SeverityError, classRequired, frameValue.at.ptr, "%s field %q is REQUIRED in %s (%s)", - frameValue.obj.Name, fld.Name, frameValue.in(w.minor), cite.Section) + w.report(ir.SeverityError, classRequired, frame.at.ptr, "%s field %q is REQUIRED in %s (%s)", + frame.obj.Name, fld.Name, frame.in(w.minor), cite.Section) } // patterned checks the keys the object admits beside its fixed fields: every // key that is neither a field nor, where the object takes them, an extension. -func (w *walker) patterned(frameValue frame, depth int) { - pat, ok := frameValue.obj.patternAt(w.minor) +func (w *walker) patterned(frame frame, depth int) { + pat, ok := frame.obj.patternAt(w.minor) if !ok { return } - for _, pair := range frameValue.pairs { - if frameValue.defines(pair.Key) || (frameValue.obj.Extensible && strings.HasPrefix(pair.Key, "x-")) { + for _, pair := range frame.pairs { + if frame.defines(pair.Key) || (frame.obj.Extensible && strings.HasPrefix(pair.Key, "x-")) { continue } if pat.Keys != FormatNone && !ValidFormat(pat.Keys, pair.Key) { - w.report(ir.SeverityError, classFormat, frameValue.at.ptr.AppendToken(pair.Key), + w.report(ir.SeverityError, classFormat, frame.at.ptr.AppendToken(pair.Key), "%s has the key %q, which must be %s in %s (%s)", - frameValue.obj.Name, pair.Key, describeFormat(pat.Keys), frameValue.in(w.minor), citeFor(pat.Cites, w.minor).Section) + frame.obj.Name, pair.Key, describeFormat(pat.Keys), frame.in(w.minor), citeFor(pat.Cites, w.minor).Section) } fld := Field{Name: pair.Key, Shape: pat.Shape, Of: pat.Of, Defined: Always(), Cites: pat.Cites} - w.value(frameValue, fld, pair.Val, depth) + w.value(frame, fld, pair.Val, depth) } } diff --git a/compilers/openapi/internal/specrules/engine_check_cancel_test.go b/compilers/openapi/internal/specrules/engine_check_cancel_test.go index 663bba039..e6f477760 100644 --- a/compilers/openapi/internal/specrules/engine_check_cancel_test.go +++ b/compilers/openapi/internal/specrules/engine_check_cancel_test.go @@ -22,10 +22,10 @@ import ( // paramsMissingIn writes n parameter components, each missing its required // `in` and its schema, so a check reading all of them finds 2n things wrong. -func paramsMissingIn(n int) string { +func paramsMissingIn(count int) string { var b strings.Builder b.WriteString("openapi: 3.1.0\ninfo: {title: t, version: '1'}\npaths: {}\ncomponents:\n parameters:\n") - for i := range n { + for i := range count { fmt.Fprintf(&b, " P%d: {name: p%d}\n", i, i) } return b.String() diff --git a/compilers/openapi/internal/specrules/engine_check_code_test.go b/compilers/openapi/internal/specrules/engine_check_code_test.go index 7851b83f4..dfbfcbaa5 100644 --- a/compilers/openapi/internal/specrules/engine_check_code_test.go +++ b/compilers/openapi/internal/specrules/engine_check_code_test.go @@ -147,8 +147,8 @@ func TestCheck_IdenticalTemplatesAreFound(t *testing.T) { // TestCheck_ServerUrlTemplatesAreWellFormed pins the 3.2 template grammar. func TestCheck_ServerUrlTemplatesAreWellFormed(t *testing.T) { - url := func(u string) string { - return `{url: "` + u + `", variables: {host: {default: h}, port: {default: "1"}, a: {default: x}, b: {default: x}}}` + url := func(uri string) string { + return `{url: "` + uri + `", variables: {host: {default: h}, port: {default: "1"}, a: {default: x}, b: {default: x}}}` } verify(t, []scenario{ {"no variables", "3.2.0", specrules.Server, url("https://a.example/v1"), nil}, @@ -182,18 +182,18 @@ func TestCheck_EncodingsApplyWhereTheSpecificationSays(t *testing.T) { body := func(key, fields string) string { return "{content: {'" + key + "': {" + fields + "}}}" } verify(t, []scenario{ {"a JSON body", "3.1.0", specrules.RequestBody, body("application/json", "encoding: {}"), - []finding{findingAtPointer(inert, "/content/application~1json/encoding")}}, + []finding{findingAtPointer(validationNoEffect, "/content/application~1json/encoding")}}, {"a multipart body", "3.1.0", specrules.RequestBody, body("multipart/form-data", "encoding: {}"), nil}, {"a form body", "3.1.0", specrules.RequestBody, body("application/x-www-form-urlencoded", "encoding: {}"), nil}, {"a form body spelled otherwise, with parameters", "3.1.0", specrules.RequestBody, body(" Application/X-WWW-Form-Urlencoded; charset=utf-8", "encoding: {}"), nil}, {"a multipart response before 3.2", "3.1.0", specrules.Response, "{description: d, content: {multipart/mixed: {encoding: {}}}}", - []finding{findingAtPointer(inert, "/content/multipart~1mixed/encoding")}}, + []finding{findingAtPointer(validationNoEffect, "/content/multipart~1mixed/encoding")}}, {"a multipart response in 3.2", "3.2.0", specrules.Response, "{description: d, content: {multipart/mixed: {encoding: {}}}}", nil}, {"positional encodings under a form", "3.2.0", specrules.RequestBody, body("application/x-www-form-urlencoded", "prefixEncoding: [], itemEncoding: {}"), - []finding{findingAtPointer(inert, "/content/application~1x-www-form-urlencoded/prefixEncoding"), - findingAtPointer(inert, "/content/application~1x-www-form-urlencoded/itemEncoding")}}, + []finding{findingAtPointer(validationNoEffect, "/content/application~1x-www-form-urlencoded/prefixEncoding"), + findingAtPointer(validationNoEffect, "/content/application~1x-www-form-urlencoded/itemEncoding")}}, {"positional encodings under multipart", "3.2.0", specrules.RequestBody, body("multipart/mixed", "prefixEncoding: [], itemEncoding: {}"), nil}, {"a component's name is no media type", "3.2.0", specrules.Components, "{mediaTypes: {JSON: {encoding: {}}}}", nil}, }) @@ -211,19 +211,19 @@ func TestCheck_EncodingsApplyWhereTheSpecificationSays(t *testing.T) { func TestCheck_NullableAppliesBesideAType(t *testing.T) { const nullable = "/nullable" verify(t, []scenario{ - {"alone", "3.0.3", specrules.Schema, "{nullable: true}", []finding{findingAtPointer(inert, nullable)}}, - {"spelled True", "3.0.3", specrules.Schema, "{nullable: True}", []finding{findingAtPointer(inert, nullable)}}, - {"beside allOf", "3.0.3", specrules.Schema, "{nullable: true, allOf: [{type: string}]}", []finding{findingAtPointer(inert, nullable)}}, - {"beside oneOf", "3.0.3", specrules.Schema, "{nullable: true, oneOf: [{type: string}]}", []finding{findingAtPointer(inert, nullable)}}, - {"beside enum", "3.0.3", specrules.Schema, "{nullable: true, enum: [a]}", []finding{findingAtPointer(inert, nullable)}}, + {"alone", "3.0.3", specrules.Schema, "{nullable: true}", []finding{findingAtPointer(validationNoEffect, nullable)}}, + {"spelled True", "3.0.3", specrules.Schema, "{nullable: True}", []finding{findingAtPointer(validationNoEffect, nullable)}}, + {"beside allOf", "3.0.3", specrules.Schema, "{nullable: true, allOf: [{type: string}]}", []finding{findingAtPointer(validationNoEffect, nullable)}}, + {"beside oneOf", "3.0.3", specrules.Schema, "{nullable: true, oneOf: [{type: string}]}", []finding{findingAtPointer(validationNoEffect, nullable)}}, + {"beside enum", "3.0.3", specrules.Schema, "{nullable: true, enum: [a]}", []finding{findingAtPointer(validationNoEffect, nullable)}}, {"beside a null type", "3.0.3", specrules.Schema, "{nullable: true, type: null}", - []finding{findingAtPointer(inert, nullable), findingAtPointer(mismatch, "/type")}}, + []finding{findingAtPointer(validationNoEffect, nullable), findingAtPointer(mismatch, "/type")}}, {"beside a type", "3.0.3", specrules.Schema, "{nullable: true, type: string}", nil}, {"false", "3.0.3", specrules.Schema, "{nullable: false}", nil}, {"beside a $ref", "3.0.3", specrules.Schema, "{$ref: '#/components/schemas/A', nullable: true}", []finding{findingAtPointer(later, nullable)}}, {"beside a null $ref", "3.0.3", specrules.Schema, "{$ref: null, nullable: true}", - []finding{findingAtPointer(inert, nullable), findingAtPointer(mismatch, "/$ref")}}, + []finding{findingAtPointer(validationNoEffect, nullable), findingAtPointer(mismatch, "/$ref")}}, {"in 3.1", "3.1.0", specrules.Schema, "{nullable: true}", nil}, }) for _, diagnostic := range run(t, "3.0.3", specrules.Schema, "{nullable: true}") { diff --git a/compilers/openapi/internal/specrules/engine_check_dialect_test.go b/compilers/openapi/internal/specrules/engine_check_dialect_test.go index 5b86e8264..59f401eaa 100644 --- a/compilers/openapi/internal/specrules/engine_check_dialect_test.go +++ b/compilers/openapi/internal/specrules/engine_check_dialect_test.go @@ -39,7 +39,7 @@ func findingsIn(t *testing.T, dialect, doc string) []finding { // TestCheck_ASchemaIsHeldToItsDialectsRows pins a schema read with a JSON // Schema draft's rows: each keyword is held to the draft's row and rules, a -// schema only the draft places is entered, true and false stand as schemas +// schema only the draft places is entered, true and false are schemas // only from draft 6, a keyword only 2020-12 defines is warned of and judged by // its row, and a draft's own tuple is read as one. func TestCheck_ASchemaIsHeldToItsDialectsRows(t *testing.T) { @@ -235,7 +235,7 @@ func TestCheckPending_ReadsWhatACheckHandedBack(t *testing.T) { return ir.Provenance{Pointer: jsontext.Pointer(alias.Replace(string(pointer)))} }, Seen: func(kind specrules.Kind, _ *yaml.Node) { seen[kind]++ }, - Later: func(pendingValue specrules.Pending) { pending = append(pending, pendingValue) }, + Later: func(later specrules.Pending) { pending = append(pending, later) }, } checker := specrules.NewChecker() assert.Empty(t, checker.Check(t.Context(), &node, "3.1.0", opts)) diff --git a/compilers/openapi/internal/specrules/engine_check_fields_test.go b/compilers/openapi/internal/specrules/engine_check_fields_test.go index 0e208ab96..4ed97e171 100644 --- a/compilers/openapi/internal/specrules/engine_check_fields_test.go +++ b/compilers/openapi/internal/specrules/engine_check_fields_test.go @@ -286,7 +286,7 @@ func TestCheck_ObjectsAreReadWhereTheyAreHeld(t *testing.T) { }) } -// TestCheck_BooleanSchemasStartAtThreeOne pins where true and false stand for a +// TestCheck_BooleanSchemasStartAtThreeOne pins where true and false name a // schema. func TestCheck_BooleanSchemasStartAtThreeOne(t *testing.T) { verify(t, []scenario{ diff --git a/compilers/openapi/internal/specrules/engine_check_later_test.go b/compilers/openapi/internal/specrules/engine_check_later_test.go index 429e69633..8353efaec 100644 --- a/compilers/openapi/internal/specrules/engine_check_later_test.go +++ b/compilers/openapi/internal/specrules/engine_check_later_test.go @@ -124,7 +124,7 @@ func laterKeywordValue(fld specrules.Field) string { // TestCheck_AKeywordALaterDialectAddsIsWarnedOf pins each keyword the Schema // Object defines from 3.1 and not at 3.0, written in a 3.0 schema: warned of // once, at the key, as a later minor's construct, and judged as 3.1 judges -// it, so a boolean schema stands where 3.1's admits one. A `$schema` there is +// it, so a boolean schema sits where 3.1's admits one. A `$schema` there is // worded as choosing nothing. A key beside a 3.0 $ref draws the warning every // key there draws, alone. func TestCheck_AKeywordALaterDialectAddsIsWarnedOf(t *testing.T) { @@ -174,7 +174,7 @@ func TestCheck_AKeywordALaterDialectAddsIsWarnedOf(t *testing.T) { } // schemaRefSiblings writes keys beside a schema's $ref at each kind of position -// a schema stands at, one $ref with nothing beside it, and a $ref beside which +// a schema sits at, one $ref with nothing beside it, and a $ref beside which // a schema is written that has a $ref of its own. const schemaRefSiblings = `info: {title: T, version: "1"} paths: diff --git a/compilers/openapi/internal/specrules/engine_check_syntax_test.go b/compilers/openapi/internal/specrules/engine_check_syntax_test.go index 706703e2d..04889b387 100644 --- a/compilers/openapi/internal/specrules/engine_check_syntax_test.go +++ b/compilers/openapi/internal/specrules/engine_check_syntax_test.go @@ -84,7 +84,7 @@ func TestCheck_TheOpenAPIFieldIsAVersionNumber(t *testing.T) { // server URL takes: the characters a URL may hold, a variable's braces aside, // and a percent sign only as an escape. func TestCheck_AServerURLWritesOnlyWhatAURLHolds(t *testing.T) { - url := func(u string) string { return `{url: "` + u + `"}` } + url := func(uri string) string { return `{url: "` + uri + `"}` } verify(t, []scenario{ {"variables in host and port", "3.0.3", specrules.Server, `{url: "https://{host}:{port}/v1", variables: {host: {default: h}, port: {default: "1"}}}`, nil}, @@ -213,8 +213,8 @@ func TestCheck_NullIsReadAsAbsentWhereTheFieldIsOptional(t *testing.T) { } // TestCheck_ANullBesideARequirementsNameListsNoScopes pins that a security -// requirement's null is no field left out: the name stands, as the lowering keeps -// it, while any other value that is no list of strings is an error. +// requirement's null is no field left out: the name remains, as the lowering +// keeps it, while any other value that is no list of strings is an error. func TestCheck_ANullBesideARequirementsNameListsNoScopes(t *testing.T) { diags := run(t, "3.1.0", specrules.SecurityRequirement, `{key: ~}`) require.Len(t, diags, 1) @@ -270,7 +270,7 @@ func TestCheck_ComponentNameAndKeyFindingsAreWarnings(t *testing.T) { // TestCheck_SeenReportsTheObjectsReadAsTheirKind pins the hook that tells a // caller which mappings were checked as which kind: an object read, and not a -// Reference Object standing in its place. +// Reference Object taking its place. func TestCheck_SeenReportsTheObjectsReadAsTheirKind(t *testing.T) { var parsed yaml.Node require.NoError(t, yaml.Unmarshal([]byte( diff --git a/compilers/openapi/internal/specrules/engine_internal_test.go b/compilers/openapi/internal/specrules/engine_internal_test.go index d7a057731..15b220d91 100644 --- a/compilers/openapi/internal/specrules/engine_internal_test.go +++ b/compilers/openapi/internal/specrules/engine_internal_test.go @@ -151,23 +151,6 @@ func TestCiteFor_PicksTheLatestCitationTheMinorHasReached(t *testing.T) { assert.Equal(t, Cite{}, citeFor(nil, V30)) } -// TestLessPointer_OrdersTokenByToken holds the order a finding names the -// position that read it by: token by token, each by its bytes, a prefix first. -func TestLessPointer_OrdersTokenByToken(t *testing.T) { - t.Parallel() - for _, tc := range []struct { - a, b jsontext.Pointer - less bool - }{ - {"/A/x", "/A-/x", true}, - {"/A-/x", "/A/x", false}, - {"/A", "/A/x", true}, - {"/A/x", "/A/x", false}, - } { - assert.Equal(t, tc.less, lessPointer(tc.a, tc.b), "%s < %s", tc.a, tc.b) - } -} - // TestSharedNode_IsTrueForAnAliasAndForAnAnchoredNodeAlone holds the node // another place may read to the two ways it is shared, and an absent node to // none. @@ -208,9 +191,9 @@ func TestKeyPlacer_ReadsTheMappingOnce(t *testing.T) { located := func(pointer jsontext.Pointer) ir.Provenance { return ir.Provenance{Pointer: pointer, Position: ir.Position{Line: 99}} } - walkerValue := &walker{} - walkerValue.locate = located - places := newKeyPlacer(walkerValue, doc.Content[0], "") + walker := &walker{} + walker.locate = located + places := newKeyPlacer(walker, doc.Content[0], "") assert.Equal(t, ir.Provenance{Pointer: "/a", Position: ir.Position{Line: 3, Column: 4}}, places.place("a")) assert.Equal(t, ir.Provenance{Pointer: "/c", Position: ir.Position{Line: 99}}, places.place("c")) @@ -229,13 +212,13 @@ func TestKeyPlacer_ReadsTheMappingOnce(t *testing.T) { func TestKeyPlacer_PlacesAKeyWhoseValueIsAnchoredAtItsOwn(t *testing.T) { t.Parallel() doc := openapitest.YAMLDocument(t, "b: &m 1\na: *m\n") - walkerValue := &walker{} - walkerValue.locate = func(pointer jsontext.Pointer) ir.Provenance { + walker := &walker{} + walker.locate = func(pointer jsontext.Pointer) ir.Provenance { if pointer == "" { return ir.Provenance{} } return ir.Provenance{Pointer: "/a"} } - places := newKeyPlacer(walkerValue, doc.Content[0], "") + places := newKeyPlacer(walker, doc.Content[0], "") assert.Equal(t, ir.Provenance{Pointer: "/b", Position: ir.Position{Line: 1, Column: 4}}, places.place("b")) } diff --git a/compilers/openapi/internal/specrules/format.go b/compilers/openapi/internal/specrules/format.go index fb7ee0309..acd180c26 100644 --- a/compilers/openapi/internal/specrules/format.go +++ b/compilers/openapi/internal/specrules/format.go @@ -11,92 +11,92 @@ import ( "unicode" ) -// ValidFormat reports whether s has the syntax format names. The binder reads +// ValidFormat reports whether text has the syntax format names. The binder reads // an anchor's name through it, so a declaration is checked and resolved by one // grammar. The checks refuse what no reading of the grammar admits and nothing // finer: a URI is judged by the standard library's parser, which takes the // braces real documents write in a path. -func ValidFormat(format Format, s string) bool { +func ValidFormat(format Format, text string) bool { switch format { case URI: - return validURI(s) != nil + return validURI(text) != nil case AbsoluteURI: - u := validURI(s) - return u != nil && u.Scheme != "" + parsed := validURI(text) + return parsed != nil && parsed.Scheme != "" case Email: - return validEmail(s) + return validEmail(text) case ComponentName: - return validComponentName(s) + return validComponentName(text) case Token, FieldName: - return validToken(s) + return validToken(text) case AuthScheme: - return s == "" || validToken(s) + return text == "" || validToken(text) case RuntimeExpression: - return validEmbedding(s) + return validEmbedding(text) case VersionNumber: - return validVersion(s) + return validVersion(text) case ServerURL: - return validServerURL(s) + return validServerURL(text) case MediaRanges: - return validMediaRanges(s) + return validMediaRanges(text) case MediaTypeKey: - return validMediaType(s) + return validMediaType(text) case AnchorName: - return validAnchorName(s) + return validAnchorName(text) case ResourceURI: - u := validURI(s) - return u != nil && u.Fragment == "" + parsed := validURI(text) + return parsed != nil && parsed.Fragment == "" case SelfURI: - return validURI(s) != nil && !strings.Contains(s, "#") + return validURI(text) != nil && !strings.Contains(text, "#") case PlainName: - return validPlainName(s) + return validPlainName(text) case PlainNameURI: - if name, alone := strings.CutPrefix(s, "#"); alone && name != "" && !strings.HasPrefix(name, "/") { + if name, alone := strings.CutPrefix(text, "#"); alone && name != "" && !strings.HasPrefix(name, "/") { return validPlainName(name) } - return validURI(s) != nil + return validURI(text) != nil default: return true } } -// validVersion reports whether s is major.minor.patch, three runs of decimal +// validVersion reports whether text is major.minor.patch, three runs of decimal // digits joined by dots. -func validVersion(s string) bool { - parts := strings.Split(s, ".") - return len(parts) == 3 && !slices.ContainsFunc(parts, func(p string) bool { - return p == "" || strings.ContainsFunc(p, func(r rune) bool { return r < '0' || r > '9' }) +func validVersion(text string) bool { + parts := strings.Split(text, ".") + return len(parts) == 3 && !slices.ContainsFunc(parts, func(part string) bool { + return part == "" || strings.ContainsFunc(part, func(character rune) bool { return character < '0' || character > '9' }) }) } -// validServerURL reports whether s writes only what a URL may hold, its +// validServerURL reports whether text writes only what a URL may hold, its // variables' braces aside, which 3.2's template rule judges: no space, control // or other character RFC 3986 leaves out, and a percent sign only as an escape // of two hex digits. A template is no URL until its variables are substituted, // so nothing finer is judged. -func validServerURL(s string) bool { - for i := range len(s) { - switch c := s[i]; { - case c <= ' ' || c == 0x7f || strings.IndexByte(`"<>\^`+"`"+`|`, c) >= 0: +func validServerURL(text string) bool { + for i := range len(text) { + switch character := text[i]; { + case character <= ' ' || character == 0x7f || strings.IndexByte(`"<>\^`+"`"+`|`, character) >= 0: return false - case c == '%' && (i+2 >= len(s) || !isHex(s[i+1]) || !isHex(s[i+2])): + case character == '%' && (i+2 >= len(text) || !isHex(text[i+1]) || !isHex(text[i+2])): return false } } return true } -// isHex reports whether c is a hexadecimal digit. -func isHex(c byte) bool { - return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' +// isHex reports whether character is a hexadecimal digit. +func isHex(character byte) bool { + return '0' <= character && character <= '9' || 'a' <= character && character <= 'f' || 'A' <= character && character <= 'F' } -// validMediaRanges reports whether s is a comma-separated list of media types +// validMediaRanges reports whether text is a comma-separated list of media types // (RFC 9110 §8.3.1) or ranges of them (§12.5.1). An empty element names // nothing and is read past, as an HTTP list's is, but a list must name one. -func validMediaRanges(s string) bool { +func validMediaRanges(text string) bool { named := false - for element := range strings.SplitSeq(s, ",") { + for element := range strings.SplitSeq(text, ",") { element = strings.TrimSpace(element) if element == "" { continue @@ -109,75 +109,75 @@ func validMediaRanges(s string) bool { return named } -// validMediaType reports whether s is a media type or a media type range, its +// validMediaType reports whether text is a media type or a media type range, its // parameters included: a type and a subtype, each a token, so a wildcard // either side passes and no finer reading of a range is made. -func validMediaType(s string) bool { - mediaType, _, err := mime.ParseMediaType(s) +func validMediaType(text string) bool { + mediaType, _, err := mime.ParseMediaType(text) return err == nil && strings.Contains(mediaType, "/") } -// validURI parses s as a URI reference, or returns nil when it holds a space +// validURI parses text as a URI reference, or returns nil when it holds a space // or a control character, or the parser refuses it. -func validURI(s string) *url.URL { - if strings.ContainsFunc(s, func(r rune) bool { return r <= ' ' || unicode.IsControl(r) }) { +func validURI(text string) *url.URL { + if strings.ContainsFunc(text, func(character rune) bool { return character <= ' ' || unicode.IsControl(character) }) { return nil } - u, err := url.Parse(s) + parsed, err := url.Parse(text) if err != nil { return nil } - return u + return parsed } -// validAnchorName reports whether s is a name a $anchor may declare, by JSON +// validAnchorName reports whether text is a name a $anchor may declare, by JSON // Schema 2020-12 section 8.2.2: a letter or '_', then letters, digits, '-', // '_' and '.'. The binder reads a $ref's plain-name fragment through it. -func validAnchorName(s string) bool { - for i, c := range s { +func validAnchorName(text string) bool { + for i, character := range text { switch { - case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c == '_': - case i > 0 && (c >= '0' && c <= '9' || c == '-' || c == '.'): + case character >= 'a' && character <= 'z', character >= 'A' && character <= 'Z', character == '_': + case i > 0 && (character >= '0' && character <= '9' || character == '-' || character == '.'): default: return false } } - return s != "" + return text != "" } -// validPlainName reports whether s is a plain name JSON Schema drafts 6, 7 and +// validPlainName reports whether text is a plain name JSON Schema drafts 6, 7 and // 2019-09 declare an anchor by (draft-handrews-json-schema-02 §8.2.3): a // letter, then letters, digits, '-', '_', ':' and '.'. The binder reads a // declaration in such a draft through it. -func validPlainName(s string) bool { - for i, c := range s { +func validPlainName(text string) bool { + for i, character := range text { switch { - case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z': - case i > 0 && (c >= '0' && c <= '9' || c == '-' || c == '_' || c == ':' || c == '.'): + case character >= 'a' && character <= 'z', character >= 'A' && character <= 'Z': + case i > 0 && (character >= '0' && character <= '9' || character == '-' || character == '_' || character == ':' || character == '.'): default: return false } } - return s != "" + return text != "" } -// validEmail reports whether s is a name, one @, and a domain, with no space. -func validEmail(s string) bool { - local, domain, ok := strings.Cut(s, "@") +// validEmail reports whether text is a name, one @, and a domain, with no space. +func validEmail(text string) bool { + local, domain, ok := strings.Cut(text, "@") if !ok || local == "" || domain == "" || strings.Contains(domain, "@") { return false } - return !strings.ContainsFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) + return !strings.ContainsFunc(text, func(character rune) bool { return unicode.IsSpace(character) || unicode.IsControl(character) }) } -// validComponentName reports whether s matches ^[a-zA-Z0-9\.\-_]+$. -func validComponentName(s string) bool { - if s == "" { +// validComponentName reports whether text matches ^[a-zA-Z0-9\.\-_]+$. +func validComponentName(text string) bool { + if text == "" { return false } - for _, r := range s { + for _, character := range text { switch { - case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '-', r == '_': + case character >= 'a' && character <= 'z', character >= 'A' && character <= 'Z', character >= '0' && character <= '9', character == '.', character == '-', character == '_': default: return false } @@ -185,15 +185,15 @@ func validComponentName(s string) bool { return true } -// validToken reports whether s is one or more tchar (RFC 9110 §5.6.2). -func validToken(s string) bool { - if s == "" { +// validToken reports whether text is one or more tchar (RFC 9110 §5.6.2). +func validToken(text string) bool { + if text == "" { return false } - for _, r := range s { + for _, character := range text { switch { - case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': - case r < 0x80 && strings.ContainsRune("!#$%&'*+-.^_`|~", r): + case character >= 'a' && character <= 'z', character >= 'A' && character <= 'Z', character >= '0' && character <= '9': + case character < 0x80 && strings.ContainsRune("!#$%&'*+-.^_`|~", character): default: return false } @@ -201,15 +201,15 @@ func validToken(s string) bool { return true } -// validEmbedding reports whether s is a string a callback key may be: text +// validEmbedding reports whether text is a string a callback key may be: text // whose every braced group is a runtime expression, or, with no brace and a // leading $, a runtime expression bare. Text with no brace and no leading $ // holds no expression and is a fixed URL. -func validEmbedding(s string) bool { - if !strings.ContainsAny(s, "{}") { - return !strings.HasPrefix(s, "$") || validExpression(s) +func validEmbedding(text string) bool { + if !strings.ContainsAny(text, "{}") { + return !strings.HasPrefix(text, "$") || validExpression(text) } - rest := s + rest := text for { before, after, open := strings.Cut(rest, "{") if strings.Contains(before, "}") { @@ -226,17 +226,17 @@ func validEmbedding(s string) bool { } } -// validExpression reports whether s is a runtime expression, by the ABNF each +// validExpression reports whether text is a runtime expression, by the ABNF each // specification gives under "Runtime Expressions". A name is any string, so // "$request.query." holds an empty one. -func validExpression(s string) bool { - switch s { +func validExpression(text string) bool { + switch text { case "$url", "$method", "$statusCode": return true } - rest, ok := strings.CutPrefix(s, "$request.") + rest, ok := strings.CutPrefix(text, "$request.") if !ok { - rest, ok = strings.CutPrefix(s, "$response.") + rest, ok = strings.CutPrefix(text, "$response.") } if !ok { return false @@ -254,17 +254,17 @@ func validExpression(s string) bool { return isBody && validPointer(pointer) } -// validPointer reports whether s is a JSON pointer as RFC 6901 writes it: empty, +// validPointer reports whether text is a JSON pointer as RFC 6901 writes it: empty, // or "/"-led tokens in which "~" is followed by 0 or 1. -func validPointer(s string) bool { - if s == "" { +func validPointer(text string) bool { + if text == "" { return true } - if !strings.HasPrefix(s, "/") { + if !strings.HasPrefix(text, "/") { return false } - for i := range len(s) { - if s[i] == '~' && (i+1 == len(s) || (s[i+1] != '0' && s[i+1] != '1')) { + for i := range len(text) { + if text[i] == '~' && (i+1 == len(text) || (text[i+1] != '0' && text[i+1] != '1')) { return false } } diff --git a/compilers/openapi/internal/specrules/helpers_test.go b/compilers/openapi/internal/specrules/helpers_test.go index f43a75434..c63a3c049 100644 --- a/compilers/openapi/internal/specrules/helpers_test.go +++ b/compilers/openapi/internal/specrules/helpers_test.go @@ -22,21 +22,21 @@ import ( // The codes the engine reports under. const ( - required = diag.Validation + "/validation-required-field" - mismatch = diag.Validation + "/validation-type-mismatch" - allowed = diag.Validation + "/validation-allowed-values" - badFormat = diag.Validation + "/validation-invalid-format" - badSyntax = diag.Validation + "/validation-invalid-syntax" - exclusive = diag.Validation + "/validation-mutually-exclusive-fields" - empty = diag.Validation + "/validation-empty-value" - duplicate = diag.Validation + "/validation-duplicate-key" - dangling = diag.Validation + "/validation-invalid-reference" - circular = diag.Validation + "/validation-circular-reference" - entries = diag.Validation + "/validation-entry-count" - forbidden = diag.Validation + "/validation-forbidden-field" - inert = diag.Validation + "/validation-no-effect" - later = diag.LaterVersionConstruct - noEffect = diag.InapplicableLocationKeyword + required = diag.Validation + "/validation-required-field" + mismatch = diag.Validation + "/validation-type-mismatch" + allowed = diag.Validation + "/validation-allowed-values" + badFormat = diag.Validation + "/validation-invalid-format" + badSyntax = diag.Validation + "/validation-invalid-syntax" + exclusive = diag.Validation + "/validation-mutually-exclusive-fields" + empty = diag.Validation + "/validation-empty-value" + duplicate = diag.Validation + "/validation-duplicate-key" + dangling = diag.Validation + "/validation-invalid-reference" + circular = diag.Validation + "/validation-circular-reference" + entries = diag.Validation + "/validation-entry-count" + forbidden = diag.Validation + "/validation-forbidden-field" + validationNoEffect = diag.Validation + "/validation-no-effect" + later = diag.LaterVersionConstruct + noEffect = diag.InapplicableLocationKeyword // misplacedField is a field written at a location that bars it. misplacedField = diag.InvalidLocationKeyword // literal is a bound no decimal spells, form an exclusive bound in the diff --git a/compilers/openapi/internal/specrules/judged_test.go b/compilers/openapi/internal/specrules/judged_test.go index d211f660b..7ce25d458 100644 --- a/compilers/openapi/internal/specrules/judged_test.go +++ b/compilers/openapi/internal/specrules/judged_test.go @@ -5,6 +5,7 @@ package specrules_test import ( "encoding/json/jsontext" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -28,22 +29,22 @@ func judge(t *testing.T, kind specrules.Kind, doc string) judgment { t.Helper() var parsed yaml.Node require.NoError(t, yaml.Unmarshal([]byte(doc), &parsed)) - judgmentValue := judgment{referenced: map[specrules.Kind][]*yaml.Node{}} - judgmentValue.diags = specrules.NewChecker().Check(t.Context(), &parsed, "3.1.0", specrules.Options{ + judgment := judgment{referenced: map[specrules.Kind][]*yaml.Node{}} + judgment.diags = specrules.NewChecker().Check(t.Context(), &parsed, "3.1.0", specrules.Options{ Start: kind, Locate: func(pointer jsontext.Pointer) ir.Provenance { return ir.Provenance{Pointer: pointer} }, Judged: func(node *yaml.Node, refused bool) { if refused { - judgmentValue.refused = append(judgmentValue.refused, node) + judgment.refused = append(judgment.refused, node) return } - judgmentValue.accepted = append(judgmentValue.accepted, node) + judgment.accepted = append(judgment.accepted, node) }, Referenced: func(kind specrules.Kind, node *yaml.Node) { - judgmentValue.referenced[kind] = append(judgmentValue.referenced[kind], node) + judgment.referenced[kind] = append(judgment.referenced[kind], node) }, }) - return judgmentValue + return judgment } // values returns the Value of each node, for a comparison by what was written. @@ -216,3 +217,30 @@ func TestCheck_AFindingNamesTheLeastPositionThatReadIt(t *testing.T) { assert.Equal(t, messages[:2], messages[2:]) assert.Contains(t, messages[0], "; read at /schemas/A/type") } + +// TestCheck_AFindingNamesTheLeastIndexThatReadItByItsNumber pins the order a +// finding names the least position that read it by: an array index by its +// number, as the document writes it (provenance.ComparePointers), so of the +// entries at 9 and 10 mounting one node, 9 is named, where its bytes sort 10 +// first. +func TestCheck_AFindingNamesTheLeastIndexThatReadItByItsNumber(t *testing.T) { + t.Parallel() + entries := make([]string, 11) + for i := range entries { + entries[i] = "{}" + } + entries[9], entries[10] = "*m", "*m" + var node yaml.Node + require.NoError(t, yaml.Unmarshal([]byte("{schemas: {B: &m {type: 7}, A: {allOf: ["+strings.Join(entries, ", ")+"]}}}"), &node)) + + diags := specrules.NewChecker().Check(t.Context(), &node, "3.1.0", specrules.Options{ + Start: specrules.Components, + Locate: func(jsontext.Pointer) ir.Provenance { return ir.Provenance{Pointer: "/placed"} }, + ReadAt: true, + }) + + require.NotEmpty(t, diags) + for _, diagnostic := range diags { + assert.Contains(t, diagnostic.Message, "; read at /schemas/A/allOf/9/") + } +} diff --git a/compilers/openapi/internal/specrules/keyplace.go b/compilers/openapi/internal/specrules/keyplace.go index 98b6385cd..8b4ff44be 100644 --- a/compilers/openapi/internal/specrules/keyplace.go +++ b/compilers/openapi/internal/specrules/keyplace.go @@ -30,8 +30,8 @@ type keyPlacer struct { } // newKeyPlacer returns the placer of the keys mapping, written at at, writes. -func newKeyPlacer(walkerValue *walker, mapping *yaml.Node, at jsontext.Pointer) *keyPlacer { - return &keyPlacer{w: walkerValue, mapping: nodeview.Deref(mapping), at: at} +func newKeyPlacer(walker *walker, mapping *yaml.Node, at jsontext.Pointer) *keyPlacer { + return &keyPlacer{w: walker, mapping: nodeview.Deref(mapping), at: at} } // place returns where a finding about key is placed. A key whose value no diff --git a/compilers/openapi/internal/specrules/mappings.go b/compilers/openapi/internal/specrules/mappings.go index 734118b3c..04d9be967 100644 --- a/compilers/openapi/internal/specrules/mappings.go +++ b/compilers/openapi/internal/specrules/mappings.go @@ -30,25 +30,25 @@ func CheckFormat(ctx context.Context, root *yaml.Node, declared string, opts Opt if !ok { return nil } - formatCheckValue := formatCheck{minor: minor, at: map[*yaml.Node]jsontext.Pointer{}, merged: map[*yaml.Node]bool{}, + formatCheck := formatCheck{minor: minor, at: map[*yaml.Node]jsontext.Pointer{}, merged: map[*yaml.Node]bool{}, locate: opts.Locate, declared: declared, readAt: opts.ReadAt, rootAt: opts.Root, said: map[ir.DiagnosticKey]saying{}} - if formatCheckValue.locate == nil { - formatCheckValue.locate = func(jsontext.Pointer) ir.Provenance { return ir.Provenance{} } + if formatCheck.locate == nil { + formatCheck.locate = func(jsontext.Pointer) ir.Provenance { return ir.Provenance{} } } // Placing a finding costs a pointer per node, and most documents break // neither rule, so a first walk only looks, and stops at the first break. if !BreaksFormat(ctx, root, opts.Budget.Cap()) { return nil } - out := nodeview.Walk{Nodes: opts.Budget.Cap(), Visit: formatCheckValue.visit}.Run(ctx, nodeview.DocumentRoot(root)) + out := nodeview.Walk{Nodes: opts.Budget.Cap(), Visit: formatCheck.visit}.Run(ctx, nodeview.DocumentRoot(root)) if ctx.Err() != nil { return nil } if out.Cut { - formatCheckValue.diags = append(formatCheckValue.diags, diag.Newf(ir.SeverityError, diag.BudgetExceeded, formatCheckValue.locate(""), + formatCheck.diags = append(formatCheck.diags, diag.Newf(ir.SeverityError, diag.BudgetExceeded, formatCheck.locate(""), "the OpenAPI %s check of the document's keys stopped at its work budget; what lies past it is unchecked", minor)) } - return formatCheckValue.diags + return formatCheck.diags } // BreaksFormat reports whether some mapping of the tree root breaks a rule diff --git a/compilers/openapi/internal/specrules/messages.go b/compilers/openapi/internal/specrules/messages.go index 6db029d61..a9c1d9372 100644 --- a/compilers/openapi/internal/specrules/messages.go +++ b/compilers/openapi/internal/specrules/messages.go @@ -6,13 +6,13 @@ package specrules import ( "encoding/json/jsontext" "fmt" - "slices" "strings" yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/provenance" "github.com/dexpace/morphic/ir" ) @@ -52,7 +52,7 @@ type reporter struct { said map[ir.DiagnosticKey]saying } -// saying is where a finding stands in reporter.diags, and the least position +// saying is where a finding is in reporter.diags, and the least position // that read it. type saying struct { at int @@ -67,19 +67,19 @@ func (r *reporter) report(sev ir.Severity, class string, ptr jsontext.Pointer, f // add adds diagnostic, a finding about the node read at ptr, unless it was made // already: a node an alias mounts at two positions is read at each, and a // defect in it is one defect, at one node. Where readAt holds and that node is -// written elsewhere, the message names the least position that read it, -// pointers compared token by token, so the name is the document's and not the -// order a walk met its mounts in. +// written elsewhere, the message names the least position that read it, in +// the order the document writes them (provenance.ComparePointers), so the name +// is the document's and not the order a walk met its mounts in. func (r *reporter) add(diagnostic ir.Diagnostic, ptr jsontext.Pointer) { read, key := r.rootAt+ptr, diagnostic.Key() - sayingValue, made := r.said[key] + said, made := r.said[key] switch { case !made: r.said[key] = saying{at: len(r.diags), read: read} r.diags = append(r.diags, r.readAs(diagnostic, read)) - case lessPointer(read, sayingValue.read): - r.said[key] = saying{at: sayingValue.at, read: read} - r.diags[sayingValue.at] = r.readAs(diagnostic, read) + case provenance.ComparePointers(read, said.read) < 0: + r.said[key] = saying{at: said.at, read: read} + r.diags[said.at] = r.readAs(diagnostic, read) default: } } @@ -104,18 +104,6 @@ func (r *reporter) placed(ptr jsontext.Pointer) jsontext.Pointer { return r.rootAt + ptr } -// lessPointer reports whether a comes before b, token by token, each token -// compared by its bytes, and a pointer that is a prefix of another first. -func lessPointer(a, b jsontext.Pointer) bool { - x, y := slices.Collect(a.Tokens()), slices.Collect(b.Tokens()) - for i := range min(len(x), len(y)) { - if c := strings.Compare(x[i], y[i]); c != 0 { - return c < 0 - } - } - return len(x) < len(y) -} - // readAtClause begins what Options.ReadAt adds to a message. const readAtClause = "; read at " diff --git a/compilers/openapi/internal/specrules/messages_test.go b/compilers/openapi/internal/specrules/messages_test.go index 02ce52873..2e1ebb147 100644 --- a/compilers/openapi/internal/specrules/messages_test.go +++ b/compilers/openapi/internal/specrules/messages_test.go @@ -19,8 +19,8 @@ import ( // TestCheck_AFindingIsMadeOnceWhereItIsPlaced pins that a finding two positions // draw about one node, as an alias mounts it at both, is made once, and that // ReadAt names the position that read it first where that is not where it is -// placed, under Root, where the root is read. The locator stands in for the -// source's, placing both tags at the node an anchor writes. +// placed, under Root, where the root is read. The locator takes the place of +// the source's, placing both tags at the node an anchor writes. func TestCheck_AFindingIsMadeOnceWhereItIsPlaced(t *testing.T) { var node yaml.Node require.NoError(t, yaml.Unmarshal([]byte( diff --git a/compilers/openapi/internal/specrules/rules.go b/compilers/openapi/internal/specrules/rules.go index 65b4ca595..97fbac6b3 100644 --- a/compilers/openapi/internal/specrules/rules.go +++ b/compilers/openapi/internal/specrules/rules.go @@ -73,11 +73,11 @@ func textOf(node *yaml.Node) (string, bool) { // rules applies the object's rules that hold at the declared minor, bar those // another package reports. -func (w *walker) rules(frameValue frame) { - rulerValue := ruler{w: w, f: frameValue} - for _, rule := range frameValue.obj.Rules { +func (w *walker) rules(frame frame) { + ruler := ruler{w: w, f: frame} + for _, rule := range frame.obj.Rules { if rule.Span.Holds(w.minor) && rule.Owner == "" { - rulerValue.apply(rule) + ruler.apply(rule) } } } @@ -132,9 +132,9 @@ func (r ruler) fail(rule Rule, class string, ptr jsontext.Pointer, detail string // present returns those of names the object writes, in the order given. func (r ruler) present(names []string) []string { var out []string - for _, n := range names { - if r.f.writes(n, r.w.minor) { - out = append(out, n) + for _, name := range names { + if r.f.writes(name, r.w.minor) { + out = append(out, name) } } return out @@ -143,8 +143,8 @@ func (r ruler) present(names []string) []string { // quoted spells names as a list of quoted fields. func quoted(names []string) string { parts := make([]string, len(names)) - for i, n := range names { - parts[i] = `"` + n + `"` + for i, name := range names { + parts[i] = `"` + name + `"` } return strings.Join(parts, ", ") } @@ -176,21 +176,21 @@ func (r ruler) anyOf(rule Rule) { // count reports a map or list holding too few or too many entries. The field // "" is the object itself, its extensions aside. func (r ruler) count(rule Rule) { - n, ptr, ok := r.entryCount(rule.Field) + count, ptr, ok := r.entryCount(rule.Field) if !ok { return } switch { - case n < rule.Min: + case count < rule.Min: r.fail(rule, classCount, ptr, r.named(rule.Field)+"must hold at least "+plural(rule.Min)) - case rule.Max > 0 && n > rule.Max: + case rule.Max > 0 && count > rule.Max: r.fail(rule, classCount, ptr, r.named(rule.Field)+"must hold at most "+plural(rule.Max)) } } -// plural spells n entries. -func plural(n int) string { - return strconv.Itoa(n) + map[bool]string{true: " entry", false: " entries"}[n == 1] +// plural spells count entries. +func plural(count int) string { + return strconv.Itoa(count) + map[bool]string{true: " entry", false: " entries"}[count == 1] } // named spells the thing a count rule counts, ready to precede a verb: the @@ -230,13 +230,13 @@ func (r ruler) entryCount(field string) (int, jsontext.Pointer, bool) { // written counts the pairs counted keeps whose value is not null. func written(pairs []nodeview.Pair, counted func(nodeview.Pair) bool) int { - n := 0 + count := 0 for _, pair := range pairs { if counted(pair) && !isNull(nodeview.Deref(pair.Val)) { - n++ + count++ } } - return n + return count } // requiredWhen reports a field missing where the conditions make it required. @@ -313,10 +313,10 @@ func (r ruler) unique(rule Rule) { if rule.Key != "" { text = func(node *yaml.Node) (string, bool) { return textOf(r.keysOf(node)[rule.Key]) } at = func(i int) jsontext.Pointer { return itemPointer(base, i).AppendToken(rule.Key) } - what = func(s string) string { return "the " + rule.Key + " " + strconv.Quote(s) } + what = func(text string) string { return "the " + rule.Key + " " + strconv.Quote(text) } } - repeats(list, text, func(i, first int, s string) { - r.fail(rule, classDuplicate, at(i), `field "`+rule.Field+`" repeats `+what(s)+" first written at "+string(r.w.placed(at(first)))) + repeats(list, text, func(i, first int, text string) { + r.fail(rule, classDuplicate, at(i), `field "`+rule.Field+`" repeats `+what(text)+" first written at "+string(r.w.placed(at(first)))) }) } @@ -326,15 +326,15 @@ func (r ruler) unique(rule Rule) { func repeats(list *yaml.Node, text func(*yaml.Node) (string, bool), repeat func(i, first int, s string)) { first := map[string]int{} for i, item := range list.Content { - s, ok := text(item) + spelling, ok := text(item) if !ok { continue } - if at, seen := first[s]; seen { - repeat(i, at, s) + if at, seen := first[spelling]; seen { + repeat(i, at, spelling) continue } - first[s] = i + first[spelling] = i } } @@ -364,27 +364,27 @@ func (r ruler) inapplicable(rule Rule) { // ignored, and the message says that and stops: the table runs before any // lowering decides what becomes of the definition, so it knows nothing of the // definition's fate, nor of what a later stage does with it. -func reservedNames(rulerValue ruler, rule Rule) { - node := nodeview.Deref(rulerValue.f.byKey[rule.Field]) - if node == nil || rulerValue.f.test(rule.When) != answerYes { +func reservedNames(ruler ruler, rule Rule) { + node := nodeview.Deref(ruler.f.byKey[rule.Field]) + if node == nil || ruler.f.test(rule.When) != answerYes { return } - ptr := rulerValue.f.at.ptr.AppendToken(rule.Field) + ptr := ruler.f.at.ptr.AppendToken(rule.Field) if name, ok := textOf(node); ok { if reserved, is := reservedName(name, rule.Names); is { - place := newKeyPlacer(rulerValue.w, rulerValue.f.at.node, rulerValue.f.at.ptr).place(rule.Field) - rulerValue.w.add(diag.Newf(severity(rule.Level), diag.ReservedHeaderName, place, "header %s %q is reserved: OpenAPI "+ - "says a definition for %s SHALL be ignored", rulerValue.f.obj.noun(), name, reserved), ptr) + place := newKeyPlacer(ruler.w, ruler.f.at.node, ruler.f.at.ptr).place(rule.Field) + ruler.w.add(diag.Newf(severity(rule.Level), diag.ReservedHeaderName, place, "header %s %q is reserved: OpenAPI "+ + "says a definition for %s SHALL be ignored", ruler.f.obj.noun(), name, reserved), ptr) } return } if node.Kind != yaml.MappingNode { return } - places := newKeyPlacer(rulerValue.w, node, ptr) - for _, pair := range rulerValue.w.view.MappingPairs(node) { + places := newKeyPlacer(ruler.w, node, ptr) + for _, pair := range ruler.w.view.MappingPairs(node) { if reserved, is := reservedName(pair.Key, rule.Names); is { - rulerValue.w.add(diag.Newf(severity(rule.Level), diag.ReservedHeaderName, places.place(pair.Key), "header %q is "+ + ruler.w.add(diag.Newf(severity(rule.Level), diag.ReservedHeaderName, places.place(pair.Key), "header %q is "+ "reserved: OpenAPI says a %s entry in a headers map SHALL be ignored", pair.Key, reserved), ptr.AppendToken(pair.Key)) } @@ -418,7 +418,7 @@ func (r ruler) misplaced(rule Rule) { // about one of its fields begins. func (o Object) noun() string { return strings.ToLower(strings.TrimSuffix(o.Name, " Object")) } -// place spells where the object stands as the terms read it: the first term as +// place spells where the object sits as the terms read it: the first term as // the object writes it, the others after "with". A term the object writes with // a value among those the term lists is the only kind a rule that holds has. func (r ruler) place(terms []Term) string { diff --git a/compilers/openapi/internal/specrules/schemarules.go b/compilers/openapi/internal/specrules/schemarules.go index 2b920e051..a2f87f9c9 100644 --- a/compilers/openapi/internal/specrules/schemarules.go +++ b/compilers/openapi/internal/specrules/schemarules.go @@ -4,6 +4,7 @@ package specrules import ( + "maps" "slices" "strings" ) @@ -36,7 +37,7 @@ type schemaRows struct { // ignoresRefFields reports that the dialect, not the minor, ignores the // keywords beside a `$ref`. ignoresRefFields bool - // booleans reports that true and false stand as schemas: not at 3.0, nor + // booleans reports that true and false are schemas: not at 3.0, nor // in draft 4. booleans bool // draft reports rows of a JSON Schema draft rather than the minor's own, @@ -60,15 +61,15 @@ func (s Spec) SchemaRules(version, dialect string) (rules SchemaRules, unread bo if !ok { return SchemaRules{}, false } - dialectValue, unread := dialectOf(minor, dialect) - rows := &schemaRows{minor: minor, ignoresRefFields: dialectValue.ignoresRefFields, draft: dialectValue.keywords != nil, + read, unread := dialectOf(minor, dialect) + rows := &schemaRows{minor: minor, ignoresRefFields: read.ignoresRefFields, draft: read.keywords != nil, booleans: obj.Boolean.Holds(minor)} rows.object = obj - rows.object.Fields = definedAt(obj, minor, dialectValue) + rows.object.Fields = definedAt(obj, minor, read) if rows.draft { - rows.booleans = dialectValue.booleans - if dialectValue.rules != nil { - rows.object.Rules = slices.Concat(obj.Rules, dialectValue.rules()) + rows.booleans = read.booleans + if read.rules != nil { + rows.object.Rules = slices.Concat(obj.Rules, read.rules()) } } rows.object.Boolean = MinorVersionRange{} @@ -89,13 +90,13 @@ func (s Spec) SchemaRules(version, dialect string) (rules SchemaRules, unread bo } // definedAt returns the Schema Object's fields obj defines at minor in dialect -// dialectValue, in table order: every one the minor defines where dialectValue +// dialect, in table order: every one the minor defines where dialect // reads the minor's own keywords, else OpenAPI's own fields and then -// dialectValue's keywords. -func definedAt(obj Object, minor Minor, dialectValue dialect) []Field { +// dialect's keywords. +func definedAt(obj Object, minor Minor, dialect dialect) []Field { var keywords []Field - if dialectValue.keywords != nil { - keywords = readBounds(dialectValue.keywords()) + if dialect.keywords != nil { + keywords = readBounds(dialect.keywords()) } defined := make([]Field, 0, len(obj.Fields)+len(keywords)) for _, field := range obj.Fields { @@ -137,7 +138,7 @@ func laterThan(obj Object, minor Minor, draft bool, fields map[string]Field) map // has rows for, and whether id is an absolute URI the table has no rows for. A // dialect is compared without a trailing empty fragment, which draft 4's id // writes and 2020-12's does not, as `$schema` values spell both. -func dialectOf(minor Minor, id string) (dialectValue dialect, unread bool) { +func dialectOf(minor Minor, id string) (read dialect, unread bool) { if id == "" || minor == V30 { return dialect{}, false } @@ -155,6 +156,20 @@ func dialectOf(minor Minor, id string) (dialectValue dialect, unread bool) { // the JSON Schema drafts before 2019-09 do. func (r SchemaRules) IgnoresRefFields() bool { return r.rows != nil && r.rows.ignoresRefFields } +// ReadsAlike reports whether r and other read every schema alike: rows of one +// minor and one dialect, each defining the fields the other does, so a text +// read by either says one thing. The zero rows read alike only with the zero +// rows. +func (r SchemaRules) ReadsAlike(other SchemaRules) bool { + if r.rows == nil || other.rows == nil { + return r.rows == other.rows + } + a, b := r.rows, other.rows + return a.minor == b.minor && a.draft == b.draft && a.ignoresRefFields == b.ignoresRefFields && a.booleans == b.booleans && + slices.Equal(slices.Sorted(maps.Keys(a.fields)), slices.Sorted(maps.Keys(b.fields))) && + slices.Equal(slices.Sorted(maps.Keys(a.later)), slices.Sorted(maps.Keys(b.later))) +} + // Later reports whether name is a keyword the rows do not define and the // dialect the compiler reads natively does, which it reads as that dialect // does: a keyword 2020-12 added, in a 3.0 schema or in a draft's. @@ -166,7 +181,7 @@ func (r SchemaRules) Later(name string) bool { return ok } -// Booleans reports whether true and false stand as schemas in the rows' +// Booleans reports whether true and false are schemas in the rows' // dialect, as they do from 3.1 bar in JSON Schema draft 4. func (r SchemaRules) Booleans() bool { return r.rows != nil && r.rows.booleans } @@ -209,8 +224,8 @@ func (r SchemaRules) Takes(name string, shape Shape) bool { if !ok { return false } - return field.Shape == shape || slices.ContainsFunc(field.Alts, func(a Alt) bool { - return a.Shape == shape && a.Span.Holds(r.rows.minor) + return field.Shape == shape || slices.ContainsFunc(field.Alts, func(alt Alt) bool { + return alt.Shape == shape && alt.Span.Holds(r.rows.minor) }) } @@ -228,6 +243,18 @@ func (r SchemaRules) RequiredWhen(name, beside, value string) bool { }) } +// AdmitsEmptyList reports whether the field name may hold a list with no entry +// in the rows: no RuleCount holding at their minor requires one, as 3.0's and +// draft 4's do of `required` and 2020-12's does not. +func (r SchemaRules) AdmitsEmptyList(name string) bool { + if r.rows == nil { + return true + } + return !slices.ContainsFunc(r.rows.object.Rules, func(rule Rule) bool { + return rule.Kind == RuleCount && rule.Field == name && rule.Min > 0 && rule.Span.Holds(r.rows.minor) + }) +} + // field returns the field name the Schema Object defines in the rows. func (r SchemaRules) field(name string) (Field, bool) { if r.rows == nil { diff --git a/compilers/openapi/internal/specrules/schemarules_internal_test.go b/compilers/openapi/internal/specrules/schemarules_internal_test.go index 28d21fd57..45216af12 100644 --- a/compilers/openapi/internal/specrules/schemarules_internal_test.go +++ b/compilers/openapi/internal/specrules/schemarules_internal_test.go @@ -117,7 +117,7 @@ func TestSchemaRules_LaterKeywordsAreTheOwnRowsADialectLacks(t *testing.T) { obj, _ := Table().Object(Schema) var at30 []string for _, field := range obj.Fields { - if field.Defined.Holds(V31) && !slices.ContainsFunc(obj.Fields, func(fieldValue Field) bool { return fieldValue.Name == field.Name && fieldValue.Defined.Holds(V30) }) { + if field.Defined.Holds(V31) && !slices.ContainsFunc(obj.Fields, func(candidate Field) bool { return candidate.Name == field.Name && candidate.Defined.Holds(V30) }) { at30 = append(at30, field.Name) } } diff --git a/compilers/openapi/internal/specrules/schemarules_test.go b/compilers/openapi/internal/specrules/schemarules_test.go index de3c24aa9..6d99f9505 100644 --- a/compilers/openapi/internal/specrules/schemarules_test.go +++ b/compilers/openapi/internal/specrules/schemarules_test.go @@ -143,9 +143,9 @@ func TestSchemaRules_ReadEachRowAtItsMinor(t *testing.T) { func TestSchemaRules_EachDraftReadsItsOwnKeywords(t *testing.T) { t.Parallel() for _, tc := range []struct { - dialect string - list, rest, dependencies, id, boolean, inert bool - recursive, defs, constant bool + dialect string + list, rest, dependencies, id, boolean, ignoresRefFields bool + recursive, defs, constant bool }{ {draft04, true, true, true, true, true, true, false, false, false}, {draft06, true, true, true, false, false, true, false, false, true}, @@ -161,7 +161,7 @@ func TestSchemaRules_EachDraftReadsItsOwnKeywords(t *testing.T) { assert.Equal(t, tc.dependencies, schemaRules.Defines("dependencies"), "%s dependencies", tc.dialect) assert.Equal(t, tc.id, schemaRules.Defines("id") && !schemaRules.Defines("$id"), "%s id", tc.dialect) assert.Equal(t, tc.boolean, schemaRules.Takes("exclusiveMinimum", specrules.Boolean), "%s bound", tc.dialect) - assert.Equal(t, tc.inert, schemaRules.IgnoresRefFields(), "%s $ref siblings", tc.dialect) + assert.Equal(t, tc.ignoresRefFields, schemaRules.IgnoresRefFields(), "%s $ref siblings", tc.dialect) assert.Equal(t, tc.recursive, schemaRules.Defines("$recursiveRef"), "%s $recursiveRef", tc.dialect) assert.Equal(t, tc.defs, schemaRules.Defines("$defs"), "%s $defs", tc.dialect) assert.Equal(t, tc.constant, schemaRules.Defines("const"), "%s const", tc.dialect) @@ -192,3 +192,52 @@ func TestSchemaRules_IdentifierNamesTheKeywordADialectSpellsIt(t *testing.T) { assert.Equal(t, "id", rulesOf("3.1.0", draft04).Identifier()) assert.Empty(t, rulesOf("3.0.3", "").Identifier()) } + +// TestSchemaRules_AdmitsEmptyListWhereNoCountRequiresAnEntry pins which rows +// let `required` hold no entry: 2020-12's, at 3.1 and 3.2, do, and 3.0's and +// draft 4's, whose rules require one, do not; a field no count rule names is +// admitted anywhere, as is any field in rows that hold no rules. +func TestSchemaRules_AdmitsEmptyListWhereNoCountRequiresAnEntry(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + version, dialect, field string + admits bool + }{ + {"3.1.0", "", "required", true}, + {"3.2.0", "", "required", true}, + {"3.0.3", "", "required", false}, + {"3.1.0", "http://json-schema.org/draft-04/schema#", "required", false}, + {"3.0.3", "", "enum", true}, + } { + schemaRules, unread := specrules.Table().SchemaRules(tc.version, tc.dialect) + assert.False(t, unread, "%s %s", tc.version, tc.dialect) + assert.Equal(t, tc.admits, schemaRules.AdmitsEmptyList(tc.field), "%s %s %s", tc.version, tc.dialect, tc.field) + } + empty, _ := specrules.Spec{}.SchemaRules("3.0.3", "") + assert.True(t, empty.AdmitsEmptyList("required"), "rows holding no rules require nothing") +} + +// TestSchemaRules_ReadAlikeAtOneMinorInOneDialect pins when two sets of rows +// read a schema alike: built twice for one minor and dialect, or for two +// spellings naming one, they do; across minors, across dialects, and beside +// the zero rows, which read alike only with the zero rows, they do not. +func TestSchemaRules_ReadAlikeAtOneMinorInOneDialect(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + a, b specrules.SchemaRules + want bool + }{ + {"one minor, built twice", rulesOf("3.1.0", ""), rulesOf("3.1.0", ""), true}, + {"one minor, two patches", rulesOf("3.0.3", ""), rulesOf("3.0.0", ""), true}, + {"two minors", rulesOf("3.0.3", ""), rulesOf("3.1.0", ""), false}, + {"the minor's own dialect named", rulesOf("3.1.0", ""), rulesOf("3.1.0", draft2020), true}, + {"two dialects", rulesOf("3.1.0", ""), rulesOf("3.1.0", draft04), false}, + {"two drafts", rulesOf("3.1.0", draft2019), rulesOf("3.1.0", draft04), false}, + {"the zero rows beside rows", specrules.SchemaRules{}, rulesOf("3.1.0", ""), false}, + {"rows beside the zero rows", rulesOf("3.1.0", ""), specrules.SchemaRules{}, false}, + {"the zero rows twice", specrules.SchemaRules{}, specrules.SchemaRules{}, true}, + } { + assert.Equal(t, tc.want, tc.a.ReadsAlike(tc.b), tc.name) + } +} diff --git a/compilers/openapi/internal/specrules/scope.go b/compilers/openapi/internal/specrules/scope.go new file mode 100644 index 000000000..85268e2d7 --- /dev/null +++ b/compilers/openapi/internal/specrules/scope.go @@ -0,0 +1,99 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package specrules + +import "strings" + +// KeywordScope says where a keyword constrains the instance a conjunction +// describes: wherever it is written, beside its group's anchors alone, in its +// own schema object alone, or as a conjunct itself. +type KeywordScope uint8 + +// The scopes a keyword takes (docs/compilers/openapi.md#allof-inline-residue). +const ( + // KeywordScopeAnyConjunct is a keyword constraining the same instance + // wherever it is written, so a conjunct's writing of it is the + // conjunction's. + KeywordScopeAnyConjunct KeywordScope = iota + 1 + // KeywordScopeWithGroup is a keyword its group's anchors in its own object + // qualify, which moves only with them. + KeywordScopeWithGroup + // KeywordScopeOwnObject is a keyword scoped to the schema object writing + // it, as an identifier, a comment, an unevaluated keyword and a key no + // dialect defines are. + KeywordScopeOwnObject + // KeywordScopeConjunct is a reference or an applicator: a conjunct of the + // conjunction itself, not a keyword to fold. + KeywordScopeConjunct +) + +// KeywordScopeOf returns keyword's scope in a conjunction read with the rows: +// an extension's is any conjunct, and a key the rows neither define nor define +// later is its own object's, as unknown keys are kept where written. A keyword +// the rows define later takes the scope the dialect defining it reads it in. +func (r SchemaRules) KeywordScopeOf(keyword string) KeywordScope { + switch { + case strings.HasPrefix(keyword, "x-"): + return KeywordScopeAnyConjunct + case !r.reads(keyword): + return KeywordScopeOwnObject + case len(r.GroupAnchorKeywords(keyword)) > 0: + return KeywordScopeWithGroup + } + switch SlotOf(keyword) { + case SlotReference, SlotConjunction, SlotChoice: + return KeywordScopeConjunct + case SlotResource: + return KeywordScopeOwnObject + } + switch keyword { + case "$comment", "unevaluatedProperties", "unevaluatedItems": + return KeywordScopeOwnObject + default: + return KeywordScopeAnyConjunct + } +} + +// GroupAnchorKeywords returns the anchors keyword moves with where the rows +// read it as qualified by them in its own object, nil for a keyword of any +// other scope: 2020-12's `items` moves with `prefixItems`, a draft's +// `additionalItems` with an array `items`, and a boolean exclusive bound, as +// 3.0 and draft 4 spell it, with the bound it qualifies. +func (r SchemaRules) GroupAnchorKeywords(keyword string) []string { + if !r.reads(keyword) { + return nil + } + switch keyword { + case "additionalProperties": + return []string{"properties", "patternProperties"} + case "items": + if r.Defines("prefixItems") { + return []string{"prefixItems"} + } + case "additionalItems": + return []string{"items"} + case "minContains", "maxContains": + return []string{"contains"} + case "then", "else": + return []string{"if"} + case "contentSchema": + return []string{"contentMediaType"} + case "nullable": + return []string{"type"} + case "exclusiveMaximum": + if r.Takes(keyword, Boolean) { + return []string{"maximum"} + } + case "exclusiveMinimum": + if r.Takes(keyword, Boolean) { + return []string{"minimum"} + } + } + return nil +} + +// reads reports whether the rows define keyword or define it later. +func (r SchemaRules) reads(keyword string) bool { + return r.Defines(keyword) || r.Later(keyword) +} diff --git a/compilers/openapi/internal/specrules/scope_internal_test.go b/compilers/openapi/internal/specrules/scope_internal_test.go new file mode 100644 index 000000000..cedb52e68 --- /dev/null +++ b/compilers/openapi/internal/specrules/scope_internal_test.go @@ -0,0 +1,163 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package specrules + +import ( + "go/constant" + "go/types" + "maps" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/internal/decls" +) + +// rowKeywords returns every keyword schemaRules defines or defines later. +func rowKeywords(schemaRules SchemaRules) []string { + return slices.Concat(slices.Collect(maps.Keys(schemaRules.rows.fields)), slices.Collect(maps.Keys(schemaRules.rows.later))) +} + +// TestKeywordScope_EveryKeywordOfEveryDialectHasOne pins that the scope table +// classes every keyword a row defines, or defines later, so no keyword of any +// dialect takes a scope by being missed; that each keyword moving with a group +// names its anchors, each a keyword of the same row scoped to any conjunct +// where no dependent is written beside it; and that a keyword of any other +// scope names none. +func TestKeywordScope_EveryKeywordOfEveryDialectHasOne(t *testing.T) { + t.Parallel() + classes := []KeywordScope{KeywordScopeAnyConjunct, KeywordScopeWithGroup, KeywordScopeOwnObject, KeywordScopeConjunct} + rows := everySchemaRow(t) + read := 0 + for row, schemaRules := range rows { + inRow := map[string]bool{} + for _, name := range rowKeywords(schemaRules) { + inRow[name] = true + } + for name := range inRow { + read++ + scope := schemaRules.KeywordScopeOf(name) + assert.Contains(t, classes, scope, "%s classes %s", row, name) + anchors := schemaRules.GroupAnchorKeywords(name) + if scope != KeywordScopeWithGroup { + assert.Empty(t, anchors, "%s: %s moves with no group", row, name) + continue + } + assert.NotEmpty(t, anchors, "%s: %s names the anchors it moves with", row, name) + for _, anchor := range anchors { + assert.True(t, inRow[anchor], "%s: %s's anchor %s is a keyword of the same row", row, name, anchor) + assert.Equal(t, KeywordScopeAnyConjunct, schemaRules.KeywordScopeOf(anchor), "%s: %s anchors a group", row, anchor) + } + } + } + require.NotEmpty(t, rows, "read no row") + require.NotZero(t, read, "read no keyword") +} + +// TestKeywordScope_EveryScopeHoldsAKeyword pins the other direction: each +// scope the package declares, read off its constants rather than a list here, +// is the scope of a keyword some row defines, so no class is one no keyword +// lands in. +func TestKeywordScope_EveryScopeHoldsAKeyword(t *testing.T) { + t.Parallel() + pkg, err := decls.Load("github.com/dexpace/morphic/compilers/openapi/internal/specrules") + require.NoError(t, err) + named, err := pkg.Named("KeywordScope") + require.NoError(t, err) + + held := map[KeywordScope]bool{} + for _, schemaRules := range everySchemaRow(t) { + for _, name := range rowKeywords(schemaRules) { + held[schemaRules.KeywordScopeOf(name)] = true + } + } + declared := 0 + for c := range pkg.Objects[*types.Const]() { + if !types.Identical(c.Type(), named) { + continue + } + declared++ + v, exact := constant.Uint64Val(c.Val()) + require.True(t, exact, c.Name()) + assert.True(t, held[KeywordScope(v)], "no keyword of any row is scoped as %s", c.Name()) + } + require.Greater(t, declared, 1, "read no scope") +} + +// TestKeywordScope_ClassesEachKeywordAsItsDialectReadsIt pins the classes a +// keyword takes by the dialect reading it: 3.0's items, a draft's items and a +// numeric exclusive bound are scoped to any conjunct, while 2020-12's items, a draft's +// additionalItems, a boolean exclusive bound and 3.0's nullable move with +// their anchors; the identifiers, the unevaluated keywords and a key no +// dialect defines are their object's own; the references and the applicators +// are conjuncts; and an extension is scoped to any conjunct. +func TestKeywordScope_ClassesEachKeywordAsItsDialectReadsIt(t *testing.T) { + t.Parallel() + const ( + draft04 = "http://json-schema.org/draft-04/schema#" + draft07 = "http://json-schema.org/draft-07/schema#" + draft2019 = "https://json-schema.org/draft/2019-09/schema" + ) + for _, tc := range []struct { + version, dialect, keyword string + scope KeywordScope + anchors []string + }{ + {"3.0.3", "", "items", KeywordScopeAnyConjunct, nil}, + {"3.0.3", "", "nullable", KeywordScopeWithGroup, []string{"type"}}, + {"3.0.3", "", "exclusiveMaximum", KeywordScopeWithGroup, []string{"maximum"}}, + {"3.0.3", "", "exclusiveMinimum", KeywordScopeWithGroup, []string{"minimum"}}, + {"3.0.3", "", "additionalProperties", KeywordScopeWithGroup, []string{"properties", "patternProperties"}}, + {"3.0.3", "", "type", KeywordScopeAnyConjunct, nil}, + {"3.0.3", "", "discriminator", KeywordScopeAnyConjunct, nil}, + {"3.0.3", "", "example", KeywordScopeAnyConjunct, nil}, + {"3.0.3", "", "xml", KeywordScopeAnyConjunct, nil}, + {"3.0.3", "", "not", KeywordScopeAnyConjunct, nil}, + {"3.0.3", "", "$ref", KeywordScopeConjunct, nil}, + {"3.0.3", "", "allOf", KeywordScopeConjunct, nil}, + {"3.0.3", "", "x-a", KeywordScopeAnyConjunct, nil}, + {"3.0.3", "", "unknownKeyword", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "unknownKeyword", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "items", KeywordScopeWithGroup, []string{"prefixItems"}}, + {"3.1.0", "", "prefixItems", KeywordScopeAnyConjunct, nil}, + {"3.1.0", "", "exclusiveMaximum", KeywordScopeAnyConjunct, nil}, + {"3.1.0", "", "additionalProperties", KeywordScopeWithGroup, []string{"properties", "patternProperties"}}, + {"3.1.0", "", "minContains", KeywordScopeWithGroup, []string{"contains"}}, + {"3.1.0", "", "maxContains", KeywordScopeWithGroup, []string{"contains"}}, + {"3.1.0", "", "then", KeywordScopeWithGroup, []string{"if"}}, + {"3.1.0", "", "else", KeywordScopeWithGroup, []string{"if"}}, + {"3.1.0", "", "contentSchema", KeywordScopeWithGroup, []string{"contentMediaType"}}, + {"3.1.0", "", "contentEncoding", KeywordScopeAnyConjunct, nil}, + {"3.1.0", "", "format", KeywordScopeAnyConjunct, nil}, + {"3.1.0", "", "dependentSchemas", KeywordScopeAnyConjunct, nil}, + {"3.1.0", "", "propertyNames", KeywordScopeAnyConjunct, nil}, + {"3.1.0", "", "$comment", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "$defs", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "$id", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "$dynamicAnchor", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "unevaluatedProperties", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "unevaluatedItems", KeywordScopeOwnObject, nil}, + {"3.1.0", "", "$dynamicRef", KeywordScopeConjunct, nil}, + {"3.1.0", "", "oneOf", KeywordScopeConjunct, nil}, + {"3.1.0", "", "anyOf", KeywordScopeConjunct, nil}, + {"3.1.0", draft04, "exclusiveMaximum", KeywordScopeWithGroup, []string{"maximum"}}, + {"3.1.0", draft04, "additionalItems", KeywordScopeWithGroup, []string{"items"}}, + {"3.1.0", draft04, "items", KeywordScopeAnyConjunct, nil}, + {"3.1.0", draft04, "id", KeywordScopeOwnObject, nil}, + {"3.1.0", draft04, "definitions", KeywordScopeOwnObject, nil}, + {"3.1.0", draft04, "dependencies", KeywordScopeAnyConjunct, nil}, + {"3.1.0", draft07, "exclusiveMaximum", KeywordScopeAnyConjunct, nil}, + {"3.1.0", draft07, "additionalItems", KeywordScopeWithGroup, []string{"items"}}, + {"3.1.0", draft2019, "items", KeywordScopeAnyConjunct, nil}, + {"3.1.0", draft2019, "$recursiveRef", KeywordScopeConjunct, nil}, + {"3.1.0", draft2019, "$recursiveAnchor", KeywordScopeOwnObject, nil}, + } { + schemaRules, unread := Table().SchemaRules(tc.version, tc.dialect) + require.False(t, unread, "%s %s", tc.version, tc.dialect) + assert.Equal(t, tc.scope, schemaRules.KeywordScopeOf(tc.keyword), "%s %s: %s", tc.version, tc.dialect, tc.keyword) + assert.ElementsMatch(t, tc.anchors, schemaRules.GroupAnchorKeywords(tc.keyword), "%s %s: %s", tc.version, tc.dialect, tc.keyword) + } +} diff --git a/compilers/openapi/internal/specrules/slots_test.go b/compilers/openapi/internal/specrules/slots_test.go index 95146d37e..55d203d53 100644 --- a/compilers/openapi/internal/specrules/slots_test.go +++ b/compilers/openapi/internal/specrules/slots_test.go @@ -101,11 +101,11 @@ func TestSlots_EveryKeywordReadsIntoItsSlotAndNoOther(t *testing.T) { assert.NotEqual(t, specrules.SlotUnknown, key.Slot, row) assert.Equal(t, slot, key.Slot, row) assert.Equal(t, isLater, key.DefinedOnlyInLaterMinor, row) - for slotValue, holds := range slots(st) { + for slotName, holds := range slots(st) { switch { - case slotValue != slot: - assert.False(t, holds, "%s fills slot %d", row, slotValue) - case slotValue != specrules.SlotReference || field.Name == "$ref": + case slotName != slot: + assert.False(t, holds, "%s fills slot %d", row, slotName) + case slotName != specrules.SlotReference || field.Name == "$ref": assert.True(t, holds, "%s fills its slot", row) } } diff --git a/compilers/openapi/internal/specrules/table_components.go b/compilers/openapi/internal/specrules/table_components.go index 91fe0b8a3..90a424429 100644 --- a/compilers/openapi/internal/specrules/table_components.go +++ b/compilers/openapi/internal/specrules/table_components.go @@ -10,13 +10,13 @@ func componentObjects() []Object { // componentsObject is the Components Object. func componentsObject() Object { - c := sectioned("Components Object") - names := c(V30, "All the fixed fields declared above are objects that MUST use keys that match the regular expression") + cite := sectioned("Components Object") + names := cite(V30, "All the fixed fields declared above are objects that MUST use keys that match the regular expression") keyed := func(name string, kind Kind, sentence string) Field { - return mapOf(name, kind, c(V30, sentence)).keyed(ComponentName, names) + return mapOf(name, kind, cite(V30, sentence)).keyed(ComponentName, names) } added := func(name string, kind Kind, minor Minor, sentence string) Field { - return mapOf(name, kind, c(minor, sentence)).during(From(minor)).keyed(ComponentName, names) + return mapOf(name, kind, cite(minor, sentence)).during(From(minor)).keyed(ComponentName, names) } return Object{ Kind: Components, Name: "Components Object", Extensible: true, @@ -39,15 +39,15 @@ func componentsObject() Object { // referenceObject is the Reference Object. It admits nothing beside its // fields: any property added is ignored. func referenceObject() Object { - c := sectioned("Reference Object") + cite := sectioned("Reference Object") return Object{ Kind: Reference, Name: "Reference Object", Fields: []Field{ - field("$ref", String, c(V30, "**REQUIRED**. The reference string."), c(V31, "**REQUIRED**. The reference identifier. This MUST be in the form of a URI.")). + field("$ref", String, cite(V30, "**REQUIRED**. The reference string."), cite(V31, "**REQUIRED**. The reference identifier. This MUST be in the form of a URI.")). required(Always()).formatted(URI), - field("summary", String, c(V31, "A short summary which by default SHOULD override that of the referenced component.")). + field("summary", String, cite(V31, "A short summary which by default SHOULD override that of the referenced component.")). during(From(V31)), - field("description", String, c(V31, "A description which by default SHOULD override that of the referenced component.")). + field("description", String, cite(V31, "A description which by default SHOULD override that of the referenced component.")). during(From(V31)), }, } diff --git a/compilers/openapi/internal/specrules/table_dialects.go b/compilers/openapi/internal/specrules/table_dialects.go index d3512183b..ad77a2c13 100644 --- a/compilers/openapi/internal/specrules/table_dialects.go +++ b/compilers/openapi/internal/specrules/table_dialects.go @@ -8,7 +8,7 @@ package specrules // it, what builds the keywords it reads in place of the minor's, nil where // they are the minor's own, the rules it states beyond the Schema Object's, // whether it ignores the keywords beside a `$ref`, as the drafts before -// 2019-09 do, and, for a draft, whether true and false stand as schemas, as +// 2019-09 do, and, for a draft, whether true and false are schemas, as // they do from draft 6. The keywords are built only for a dialect a schema // names, so a compile naming none pays for no row of one. type dialect struct { @@ -27,12 +27,12 @@ type dialect struct { // meta-schema is published under for 3.1 and 3.2, as tooling may support // values of `$schema` besides. func schemaDialects() []dialect { - c := sectioned("Schema Object") - defined := c(V31, "in addition to the vocabularies as specified in the JSON Schema Specification Draft 2020-12") - others := c(V31, "This allows use of Schema Objects which comply with other drafts of JSON Schema than the default Draft 2020-12 support.") - published := []Cite{c(V31, "and MAY support additional values of `$schema`.")} + cite := sectioned("Schema Object") + defined := cite(V31, "in addition to the vocabularies as specified in the JSON Schema Specification Draft 2020-12") + others := cite(V31, "This allows use of Schema Objects which comply with other drafts of JSON Schema than the default Draft 2020-12 support.") + published := []Cite{cite(V31, "and MAY support additional values of `$schema`.")} return []dialect{ - {id: "https://spec.openapis.org/oas/3.1/dialect/base", cites: []Cite{c(V31, "The OpenAPI Schema Object dialect for this "+ + {id: "https://spec.openapis.org/oas/3.1/dialect/base", cites: []Cite{cite(V31, "The OpenAPI Schema Object dialect for this "+ "version of the specification is identified by the URI `https://spec.openapis.org/oas/3.1/dialect/base`")}}, {id: "https://spec.openapis.org/oas/3.1/dialect/2024-10-25", cites: published}, {id: "https://spec.openapis.org/oas/3.1/dialect/2024-11-10", cites: published}, @@ -66,47 +66,47 @@ func jsonSchemaText(text Text) func(section, sentence string) Cite { func draft04Keywords() []Field { core := jsonSchemaText(TextDraft04Core) ref := jsonSchemaText(TextJSONReference03)("3. Syntax", "A JSON Reference is a JSON object, which contains a member named") - v := jsonSchemaText(TextDraft04Validation) + validation := jsonSchemaText(TextDraft04Validation) minorVersionRange := From(V31) integer := "The value of this keyword MUST be an integer." return []Field{ keyword("$schema", String, minorVersionRange, core(`6.1. Purpose`, `this URI MUST be both absolute and normalized.`)).formatted(AbsoluteURI), keyword("id", String, minorVersionRange, core(`7.2.1. Valid values`, `The value for this keyword MUST be a string, and MUST be a valid URI.`)).formatted(URI), keyword("$ref", String, minorVersionRange, ref).formatted(URI), - keyword("multipleOf", PositiveNumber, minorVersionRange, v(`5.1.1.1. Valid values`, `The value of "multipleOf" MUST be a JSON number.`)), - keyword("maximum", Number, minorVersionRange, v(`5.1.2.1. Valid values`, `The value of "maximum" MUST be a JSON number.`)), - keyword("exclusiveMaximum", Boolean, minorVersionRange, v(`5.1.2.1. Valid values`, `"exclusiveMaximum" MUST be a boolean.`)), - keyword("minimum", Number, minorVersionRange, v(`5.1.3.1. Valid values`, `The value of "minimum" MUST be a JSON number.`)), - keyword("exclusiveMinimum", Boolean, minorVersionRange, v(`5.1.3.1. Valid values`, `"exclusiveMinimum" MUST be a boolean.`)), - keyword("maxLength", Natural, minorVersionRange, v(`5.2.1.1. Valid values`, integer)), - keyword("minLength", Natural, minorVersionRange, v(`5.2.2.1. Valid values`, integer)), - keyword("pattern", String, minorVersionRange, v(`5.2.3.1. Valid values`, `The value of this keyword MUST be a string.`)), - schemaOf("additionalItems", minorVersionRange, v(`5.3.1.1. Valid values`, `The value of "additionalItems" MUST be either a boolean or an object.`)). + keyword("multipleOf", PositiveNumber, minorVersionRange, validation(`5.1.1.1. Valid values`, `The value of "multipleOf" MUST be a JSON number.`)), + keyword("maximum", Number, minorVersionRange, validation(`5.1.2.1. Valid values`, `The value of "maximum" MUST be a JSON number.`)), + keyword("exclusiveMaximum", Boolean, minorVersionRange, validation(`5.1.2.1. Valid values`, `"exclusiveMaximum" MUST be a boolean.`)), + keyword("minimum", Number, minorVersionRange, validation(`5.1.3.1. Valid values`, `The value of "minimum" MUST be a JSON number.`)), + keyword("exclusiveMinimum", Boolean, minorVersionRange, validation(`5.1.3.1. Valid values`, `"exclusiveMinimum" MUST be a boolean.`)), + keyword("maxLength", Natural, minorVersionRange, validation(`5.2.1.1. Valid values`, integer)), + keyword("minLength", Natural, minorVersionRange, validation(`5.2.2.1. Valid values`, integer)), + keyword("pattern", String, minorVersionRange, validation(`5.2.3.1. Valid values`, `The value of this keyword MUST be a string.`)), + schemaOf("additionalItems", minorVersionRange, validation(`5.3.1.1. Valid values`, `The value of "additionalItems" MUST be either a boolean or an object.`)). also(Boolean, minorVersionRange), - schemaOf("items", minorVersionRange, v(`5.3.1.1. Valid values`, `The value of "items" MUST be either an object or an array.`)).also(List, minorVersionRange), - keyword("maxItems", Natural, minorVersionRange, v(`5.3.2.1. Valid values`, integer)), - keyword("minItems", Natural, minorVersionRange, v(`5.3.3.1. Valid values`, integer)), - keyword("uniqueItems", Boolean, minorVersionRange, v(`5.3.4.1. Valid values`, `The value of this keyword MUST be a boolean.`)), - keyword("maxProperties", Natural, minorVersionRange, v(`5.4.1.1. Valid values`, integer)), - keyword("minProperties", Natural, minorVersionRange, v(`5.4.2.1. Valid values`, integer)), - keyword("required", StringList, minorVersionRange, v(`5.4.3.1. Valid values`, `The value of this keyword MUST be an array.`)), - schemaOf("additionalProperties", minorVersionRange, v(`5.4.4.1. Valid values`, `The value of "additionalProperties" MUST be a boolean or an object.`)). + schemaOf("items", minorVersionRange, validation(`5.3.1.1. Valid values`, `The value of "items" MUST be either an object or an array.`)).also(List, minorVersionRange), + keyword("maxItems", Natural, minorVersionRange, validation(`5.3.2.1. Valid values`, integer)), + keyword("minItems", Natural, minorVersionRange, validation(`5.3.3.1. Valid values`, integer)), + keyword("uniqueItems", Boolean, minorVersionRange, validation(`5.3.4.1. Valid values`, `The value of this keyword MUST be a boolean.`)), + keyword("maxProperties", Natural, minorVersionRange, validation(`5.4.1.1. Valid values`, integer)), + keyword("minProperties", Natural, minorVersionRange, validation(`5.4.2.1. Valid values`, integer)), + keyword("required", StringList, minorVersionRange, validation(`5.4.3.1. Valid values`, `The value of this keyword MUST be an array.`)), + schemaOf("additionalProperties", minorVersionRange, validation(`5.4.4.1. Valid values`, `The value of "additionalProperties" MUST be a boolean or an object.`)). also(Boolean, minorVersionRange), - schemaMapOf("properties", minorVersionRange, v(`5.4.4.1. Valid values`, `The value of "properties" MUST be an object.`)), - schemaMapOf("patternProperties", minorVersionRange, v(`5.4.4.1. Valid values`, `The value of "patternProperties" MUST be an object.`)), - keyword("dependencies", RawMap, minorVersionRange, v(`5.4.5.1. Valid values`, `This keyword's value MUST be an object.`)), - keyword("enum", RawList, minorVersionRange, v(`5.5.1.1. Valid values`, `The value of this keyword MUST be an array.`)), - keyword("type", String, minorVersionRange, v(`5.5.2.1. Valid values`, `The value of this keyword MUST be either a string or an array.`)). + schemaMapOf("properties", minorVersionRange, validation(`5.4.4.1. Valid values`, `The value of "properties" MUST be an object.`)), + schemaMapOf("patternProperties", minorVersionRange, validation(`5.4.4.1. Valid values`, `The value of "patternProperties" MUST be an object.`)), + keyword("dependencies", RawMap, minorVersionRange, validation(`5.4.5.1. Valid values`, `This keyword's value MUST be an object.`)), + keyword("enum", RawList, minorVersionRange, validation(`5.5.1.1. Valid values`, `The value of this keyword MUST be an array.`)), + keyword("type", String, minorVersionRange, validation(`5.5.2.1. Valid values`, `The value of this keyword MUST be either a string or an array.`)). admits(vals("array", "boolean", "integer", "null", "number", "object", "string")...).also(StringList, minorVersionRange), - schemasOf("allOf", minorVersionRange, v(`5.5.3.1. Valid values`, `This keyword's value MUST be an array.`)), - schemasOf("anyOf", minorVersionRange, v(`5.5.4.1. Valid values`, `This keyword's value MUST be an array.`)), - schemasOf("oneOf", minorVersionRange, v(`5.5.5.1. Valid values`, `This keyword's value MUST be an array.`)), - schemaOf("not", minorVersionRange, v(`5.5.6.1. Valid values`, `This keyword's value MUST be an object.`)), - schemaMapOf("definitions", minorVersionRange, v(`5.5.7.1. Valid values`, `This keyword's value MUST be an object.`)), - keyword("title", String, minorVersionRange, v(`6.1.1. Valid values`, `The value of both of these keywords MUST be a string.`)), - keyword("description", String, minorVersionRange, v(`6.1.1. Valid values`, `The value of both of these keywords MUST be a string.`)), - keyword("default", AnyShapeUnchecked, minorVersionRange, v(`6.2.1. Valid values`, `There are no restrictions placed on the value of this keyword.`)), - keyword("format", String, minorVersionRange, v(`7.1. Foreword`, `It MUST be a string.`)), + schemasOf("allOf", minorVersionRange, validation(`5.5.3.1. Valid values`, `This keyword's value MUST be an array.`)), + schemasOf("anyOf", minorVersionRange, validation(`5.5.4.1. Valid values`, `This keyword's value MUST be an array.`)), + schemasOf("oneOf", minorVersionRange, validation(`5.5.5.1. Valid values`, `This keyword's value MUST be an array.`)), + schemaOf("not", minorVersionRange, validation(`5.5.6.1. Valid values`, `This keyword's value MUST be an object.`)), + schemaMapOf("definitions", minorVersionRange, validation(`5.5.7.1. Valid values`, `This keyword's value MUST be an object.`)), + keyword("title", String, minorVersionRange, validation(`6.1.1. Valid values`, `The value of both of these keywords MUST be a string.`)), + keyword("description", String, minorVersionRange, validation(`6.1.1. Valid values`, `The value of both of these keywords MUST be a string.`)), + keyword("default", AnyShapeUnchecked, minorVersionRange, validation(`6.2.1. Valid values`, `There are no restrictions placed on the value of this keyword.`)), + keyword("format", String, minorVersionRange, validation(`7.1. Foreword`, `It MUST be a string.`)), } } @@ -114,13 +114,13 @@ func draft04Keywords() []Field { // beyond the Schema Object's rules: `required` holds an entry, and each entry // of `dependencies` is a list of one or more distinct strings, or a schema. func draft04Rules() []Rule { - v := jsonSchemaText(TextDraft04Validation) + validation := jsonSchemaText(TextDraft04Validation) dependencies := code(From(V31), "dependencies", "", - v(`5.4.5.1. Valid values`, `Each value of this object MUST be either an object or an array.`), - v(`5.4.5.1. Valid values`, `If the value is an array, it MUST have at least one element.`)) + validation(`5.4.5.1. Valid values`, `Each value of this object MUST be either an object or an array.`), + validation(`5.4.5.1. Valid values`, `If the value is an array, it MUST have at least one element.`)) dependencies.Min = 1 return []Rule{ - count(From(V31), Must, "required", 0, v(`5.4.3.1. Valid values`, `This array MUST have at least one element.`)), + count(From(V31), Must, "required", 0, validation(`5.4.3.1. Valid values`, `This array MUST have at least one element.`)), dependencies, } } @@ -129,16 +129,16 @@ func draft04Rules() []Rule { // beyond the Schema Object's rules: each entry of `dependencies` is a list of // distinct strings, or a schema. func draft06Rules() []Rule { - v := jsonSchemaText(TextDraft06Validation) + validation := jsonSchemaText(TextDraft06Validation) return []Rule{code(From(V31), "dependencies", "", - v(`6.21. dependencies`, `Each dependency value MUST be an array or a valid JSON Schema.`), - v(`6.21. dependencies`, `If the dependency value is an array, each element in the array, if any, MUST be a string, and MUST be unique.`))} + validation(`6.21. dependencies`, `Each dependency value MUST be an array or a valid JSON Schema.`), + validation(`6.21. dependencies`, `If the dependency value is an array, each element in the array, if any, MUST be a string, and MUST be unique.`))} } // draft07Rules are draft06Rules as JSON Schema draft 7 states them. func draft07Rules() []Rule { - v := jsonSchemaText(TextDraft07Validation) + validation := jsonSchemaText(TextDraft07Validation) return []Rule{code(From(V31), "dependencies", "", - v(`6.5.7. dependencies`, `Each dependency value MUST be an array or a valid JSON Schema.`), - v(`6.5.7. dependencies`, `If the dependency value is an array, each element in the array, if any, MUST be a string, and MUST be unique.`))} + validation(`6.5.7. dependencies`, `Each dependency value MUST be an array or a valid JSON Schema.`), + validation(`6.5.7. dependencies`, `If the dependency value is an array, each element in the array, if any, MUST be a string, and MUST be unique.`))} } diff --git a/compilers/openapi/internal/specrules/table_document.go b/compilers/openapi/internal/specrules/table_document.go index 36c41ba6f..2836ff9e8 100644 --- a/compilers/openapi/internal/specrules/table_document.go +++ b/compilers/openapi/internal/specrules/table_document.go @@ -14,35 +14,35 @@ func documentObjects() []Object { // openAPIObject is the OpenAPI Object, the root of a document. func openAPIObject() Object { - c := sectioned("OpenAPI Object") + cite := sectioned("OpenAPI Object") return Object{ Kind: Document, Name: "OpenAPI Object", Extensible: true, Fields: []Field{ - field("openapi", String, c(V30, "**REQUIRED**. This string MUST be the"), + field("openapi", String, cite(V30, "**REQUIRED**. This string MUST be the"), sectioned("Versions")(V30, "The OpenAPI Specification is versioned using a `major`.`minor`.`patch` versioning scheme.")). required(Always()).formatted(VersionNumber), - objectOf("info", Info, c(V30, "**REQUIRED**. Provides metadata about the API.")).required(Always()), - field("$self", String, c(V32, "This string MUST be in the form of a URI reference as defined by")). + objectOf("info", Info, cite(V30, "**REQUIRED**. Provides metadata about the API.")).required(Always()), + field("$self", String, cite(V32, "This string MUST be in the form of a URI reference as defined by")). during(From(V32)).formatted(SelfURI), - field("jsonSchemaDialect", String, c(V31, "The default value for the `$schema` keyword within")). + field("jsonSchemaDialect", String, cite(V31, "The default value for the `$schema` keyword within")). during(From(V31)).formatted(AbsoluteURI), - listOf("servers", Server, c(V30, "An array of Server Objects, which provide connectivity information")), - objectOf("paths", Paths, c(V30, "**REQUIRED**. The available paths and operations for the API.")). + listOf("servers", Server, cite(V30, "An array of Server Objects, which provide connectivity information")), + objectOf("paths", Paths, cite(V30, "**REQUIRED**. The available paths and operations for the API.")). required(Only(V30)), - mapOf("webhooks", PathItem, c(V31, "The incoming webhooks that MAY be received as part of this API")). + mapOf("webhooks", PathItem, cite(V31, "The incoming webhooks that MAY be received as part of this API")). during(From(V31)), - objectOf("components", Components, c(V30, "An element to hold various Objects for the OpenAPI Description.")), + objectOf("components", Components, cite(V30, "An element to hold various Objects for the OpenAPI Description.")), listOf("security", SecurityRequirement, - c(V30, "A declaration of which security mechanisms can be used across the API.")), - listOf("tags", Tag, c(V30, "A list of tags used by the OpenAPI Description with additional metadata.")), - objectOf("externalDocs", ExternalDocs, c(V30, "Additional external documentation.")), + cite(V30, "A declaration of which security mechanisms can be used across the API.")), + listOf("tags", Tag, cite(V30, "A list of tags used by the OpenAPI Description with additional metadata.")), + objectOf("externalDocs", ExternalDocs, cite(V30, "Additional external documentation.")), }, Rules: []Rule{ anyOf(Only(V31), fields("paths", "components", "webhooks"), sectioned("OpenAPI Description")(V31, "and MUST contain at least one [paths](#paths-object) field")), anyOf(From(V32), fields("components", "paths", "webhooks"), - c(V32, "at least one of the `components`, `paths`, or `webhooks` fields MUST be present.")), - uniqueNames(Always(), "tags", c(V30, "Each tag name in the list MUST be unique.")), + cite(V32, "at least one of the `components`, `paths`, or `webhooks` fields MUST be present.")), + uniqueNames(Always(), "tags", cite(V30, "Each tag name in the list MUST be unique.")), code(Always(), "operation-ids-unique", ownerOperation, sectioned("Operation Object")(V30, "The id MUST be unique among all operations described in the API.")), uniqueNames(From(V32), "servers", @@ -60,109 +60,109 @@ func openAPIObject() Object { // infoObject is the Info Object. func infoObject() Object { - c := sectioned("Info Object") + cite := sectioned("Info Object") return Object{ Kind: Info, Name: "Info Object", Extensible: true, Fields: []Field{ - field("title", String, c(V30, "**REQUIRED**. The title of the API.")).required(Always()), - field("summary", String, c(V31, "A short summary of the API.")).during(From(V31)), - field("description", String, c(V30, "A description of the API.")), - field("termsOfService", String, c(V30, "This MUST be in the form of a URL.")).formatted(URI), - objectOf("contact", Contact, c(V30, "The contact information for the exposed API.")), - objectOf("license", License, c(V30, "The license information for the exposed API.")), - field("version", String, c(V30, "**REQUIRED**. The version of the OpenAPI Document")).required(Always()), + field("title", String, cite(V30, "**REQUIRED**. The title of the API.")).required(Always()), + field("summary", String, cite(V31, "A short summary of the API.")).during(From(V31)), + field("description", String, cite(V30, "A description of the API.")), + field("termsOfService", String, cite(V30, "This MUST be in the form of a URL.")).formatted(URI), + objectOf("contact", Contact, cite(V30, "The contact information for the exposed API.")), + objectOf("license", License, cite(V30, "The license information for the exposed API.")), + field("version", String, cite(V30, "**REQUIRED**. The version of the OpenAPI Document")).required(Always()), }, } } // contactObject is the Contact Object. func contactObject() Object { - c := sectioned("Contact Object") + cite := sectioned("Contact Object") return Object{ Kind: Contact, Name: "Contact Object", Extensible: true, Fields: []Field{ - field("name", String, c(V30, "The identifying name of the contact person/organization.")), - field("url", String, c(V30, "This MUST be in the form of a URL.")).formatted(URI), - field("email", String, c(V30, "This MUST be in the form of an email address.")).formatted(Email), + field("name", String, cite(V30, "The identifying name of the contact person/organization.")), + field("url", String, cite(V30, "This MUST be in the form of a URL.")).formatted(URI), + field("email", String, cite(V30, "This MUST be in the form of an email address.")).formatted(Email), }, } } // licenseObject is the License Object. func licenseObject() Object { - c := sectioned("License Object") + cite := sectioned("License Object") return Object{ Kind: License, Name: "License Object", Extensible: true, Fields: []Field{ - field("name", String, c(V30, "**REQUIRED**. The license name used for the API.")).required(Always()), - field("identifier", String, c(V31, "An [SPDX](https://spdx.org/licenses/) license expression for the API.")). + field("name", String, cite(V30, "**REQUIRED**. The license name used for the API.")).required(Always()), + field("identifier", String, cite(V31, "An [SPDX](https://spdx.org/licenses/) license expression for the API.")). during(From(V31)), - field("url", String, c(V30, "This MUST be in the form of a URL.")).formatted(URI), + field("url", String, cite(V30, "This MUST be in the form of a URL.")).formatted(URI), }, Rules: []Rule{ exclusive(From(V31), fields("identifier", "url"), - c(V31, "The `identifier` field is mutually exclusive of the `url` field.")), + cite(V31, "The `identifier` field is mutually exclusive of the `url` field.")), }, } } // serverObject is the Server Object. func serverObject() Object { - c := sectioned("Server Object") + cite := sectioned("Server Object") return Object{ Kind: Server, Name: "Server Object", Extensible: true, Fields: []Field{ - field("url", String, c(V30, "**REQUIRED**. A URL to the target host."), - c(V30, "This URL supports Server Variables and MAY be relative")).required(Always()).formatted(ServerURL). + field("url", String, cite(V30, "**REQUIRED**. A URL to the target host."), + cite(V30, "This URL supports Server Variables and MAY be relative")).required(Always()).formatted(ServerURL). nonEmpty(From(V32), sectioned("Server Variable Object")(V32, "server-url-template = 1*( literals / server-variable )")), - field("description", String, c(V30, "An optional string describing the host designated by the URL.")), - field("name", String, c(V32, "An optional unique string to refer to the host designated by the URL.")). + field("description", String, cite(V30, "An optional string describing the host designated by the URL.")), + field("name", String, cite(V32, "An optional unique string to refer to the host designated by the URL.")). during(From(V32)), - mapOf("variables", ServerVariable, c(V30, "A map between a variable name and its value.")), + mapOf("variables", ServerVariable, cite(V30, "A map between a variable name and its value.")), }, Rules: []Rule{ code(From(V32), "server-url-template", "", sectioned("Server Variable Object")(V32, "Each server variable MUST NOT appear more than once in the URL template.")), code(Always(), "server-url-variables", "", - c(V30, "Variable substitutions will be made when a variable is named in"), - c(V30, "The value is used for substitution in the server's URL template.")), - code(From(V31), "server-url-parts", "", c(V31, "Query and fragment MUST NOT be part of this URL.")), + cite(V30, "Variable substitutions will be made when a variable is named in"), + cite(V30, "The value is used for substitution in the server's URL template.")), + code(From(V31), "server-url-parts", "", cite(V31, "Query and fragment MUST NOT be part of this URL.")), }, } } // serverVariableObject is the Server Variable Object. func serverVariableObject() Object { - c := sectioned("Server Variable Object") + cite := sectioned("Server Variable Object") return Object{ Kind: ServerVariable, Name: "Server Variable Object", Extensible: true, Fields: []Field{ - field("enum", StringList, c(V30, "An enumeration of string values to be used if the substitution options are from a limited set.")), - field("default", String, c(V30, "**REQUIRED**. The default value to use for substitution, which SHALL be sent")). + field("enum", StringList, cite(V30, "An enumeration of string values to be used if the substitution options are from a limited set.")), + field("default", String, cite(V30, "**REQUIRED**. The default value to use for substitution, which SHALL be sent")). required(Always()), - field("description", String, c(V30, "An optional description for the server variable.")), + field("description", String, cite(V30, "An optional description for the server variable.")), }, Rules: []Rule{ - count(Only(V30), Should, "enum", 0, c(V30, "The array SHOULD NOT be empty.")), - count(From(V31), Must, "enum", 0, c(V31, "The array MUST NOT be empty.")), - member(Only(V30), Should, "default", "enum", c(V30, "the value SHOULD exist in the enum's values.")), - member(From(V31), Must, "default", "enum", c(V31, "the value MUST exist in the enum's values.")), + count(Only(V30), Should, "enum", 0, cite(V30, "The array SHOULD NOT be empty.")), + count(From(V31), Must, "enum", 0, cite(V31, "The array MUST NOT be empty.")), + member(Only(V30), Should, "default", "enum", cite(V30, "the value SHOULD exist in the enum's values.")), + member(From(V31), Must, "default", "enum", cite(V31, "the value MUST exist in the enum's values.")), }, } } // tagObject is the Tag Object. func tagObject() Object { - c := sectioned("Tag Object") + cite := sectioned("Tag Object") return Object{ Kind: Tag, Name: "Tag Object", Extensible: true, Fields: []Field{ - field("name", String, c(V30, "**REQUIRED**. The name of the tag.")).required(Always()), - field("summary", String, c(V32, "A short summary of the tag, used for display purposes.")).during(From(V32)), - field("description", String, c(V30, "A description for the tag.")), - objectOf("externalDocs", ExternalDocs, c(V30, "Additional external documentation for this tag.")), - field("parent", String, c(V32, "The `name` of a tag that this tag is nested under.")).during(From(V32)), - field("kind", String, c(V32, "A machine-readable string to categorize what sort of tag it is.")). + field("name", String, cite(V30, "**REQUIRED**. The name of the tag.")).required(Always()), + field("summary", String, cite(V32, "A short summary of the tag, used for display purposes.")).during(From(V32)), + field("description", String, cite(V30, "A description for the tag.")), + objectOf("externalDocs", ExternalDocs, cite(V30, "Additional external documentation for this tag.")), + field("parent", String, cite(V32, "The `name` of a tag that this tag is nested under.")).during(From(V32)), + field("kind", String, cite(V32, "A machine-readable string to categorize what sort of tag it is.")). during(From(V32)), }, } @@ -170,12 +170,12 @@ func tagObject() Object { // externalDocsObject is the External Documentation Object. func externalDocsObject() Object { - c := sectioned("External Documentation Object") + cite := sectioned("External Documentation Object") return Object{ Kind: ExternalDocs, Name: "External Documentation Object", Extensible: true, Fields: []Field{ - field("description", String, c(V30, "A description of the target documentation.")), - field("url", String, c(V30, "**REQUIRED**. The URL for the target documentation.")). + field("description", String, cite(V30, "A description of the target documentation.")), + field("url", String, cite(V30, "**REQUIRED**. The URL for the target documentation.")). required(Always()).formatted(URI), }, } diff --git a/compilers/openapi/internal/specrules/table_drafts.go b/compilers/openapi/internal/specrules/table_drafts.go index 0aaa015ad..a92fd7568 100644 --- a/compilers/openapi/internal/specrules/table_drafts.go +++ b/compilers/openapi/internal/specrules/table_drafts.go @@ -7,49 +7,49 @@ package specrules // its validation text's, each defined at every minor that lets a schema // declare a dialect. func draft06Keywords() []Field { - c, v := jsonSchemaText(TextDraft06Core), jsonSchemaText(TextDraft06Validation) + core, validation := jsonSchemaText(TextDraft06Core), jsonSchemaText(TextDraft06Validation) minorVersionRange := From(V31) return []Field{ - keyword("$schema", String, minorVersionRange, c(`7. The "$schema" keyword`, `The value of this keyword MUST be a URI [RFC3986] (containing a scheme) and this URI MUST be normalized.`)).formatted(AbsoluteURI), - keyword("$id", String, minorVersionRange, c(`9.2. The "$id" keyword`, `If present, the value for this keyword MUST be a string, and MUST represent a valid URI-reference [RFC3986].`)). - formatted(PlainNameURI, c(`9.2. The "$id" keyword`, `The fragment identifier MUST begin with a letter ([A-Za-z]), followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), or periods (".").`)), - keyword("$ref", String, minorVersionRange, c(`8. Schema references with $ref`, `An object schema with a "$ref" property MUST be interpreted as a "$ref" reference.`)).formatted(URI), - keyword("multipleOf", PositiveNumber, minorVersionRange, v(`6.1. multipleOf`, `The value of "multipleOf" MUST be a number, strictly greater than 0.`)), - keyword("maximum", Number, minorVersionRange, v(`6.2. maximum`, `The value of "maximum" MUST be a number`)), - keyword("exclusiveMaximum", Number, minorVersionRange, v(`6.3. exclusiveMaximum`, `The value of "exclusiveMaximum" MUST be number`)), - keyword("minimum", Number, minorVersionRange, v(`6.4. minimum`, `The value of "minimum" MUST be a number`)), - keyword("exclusiveMinimum", Number, minorVersionRange, v(`6.5. exclusiveMinimum`, `The value of "exclusiveMinimum" MUST be number`)), - keyword("maxLength", Natural, minorVersionRange, v(`6.6. maxLength`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minLength", Natural, minorVersionRange, v(`6.7. minLength`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("pattern", String, minorVersionRange, v(`6.8. pattern`, `The value of this keyword MUST be a string.`)), - schemaOf("items", minorVersionRange, v(`6.9. items`, `The value of "items" MUST be either a valid JSON Schema or an array of valid JSON Schemas.`)).also(List, minorVersionRange), - schemaOf("additionalItems", minorVersionRange, v(`6.10. additionalItems`, `The value of "additionalItems" MUST be a valid JSON Schema.`)), - keyword("maxItems", Natural, minorVersionRange, v(`6.11. maxItems`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minItems", Natural, minorVersionRange, v(`6.12. minItems`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("uniqueItems", Boolean, minorVersionRange, v(`6.13. uniqueItems`, `The value of this keyword MUST be a boolean.`)), - schemaOf("contains", minorVersionRange, v(`6.14. contains`, `The value of this keyword MUST be a valid JSON Schema.`)), - keyword("maxProperties", Natural, minorVersionRange, v(`6.15. maxProperties`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minProperties", Natural, minorVersionRange, v(`6.16. minProperties`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("required", StringList, minorVersionRange, v(`6.17. required`, `The value of this keyword MUST be an array.`)), - schemaMapOf("properties", minorVersionRange, v(`6.18. properties`, `The value of "properties" MUST be an object.`)), - schemaMapOf("patternProperties", minorVersionRange, v(`6.19. patternProperties`, `The value of "patternProperties" MUST be an object.`)), - schemaOf("additionalProperties", minorVersionRange, v(`6.20. additionalProperties`, `The value of "additionalProperties" MUST be a valid JSON Schema.`)), - keyword("dependencies", RawMap, minorVersionRange, v(`6.21. dependencies`, `This keyword's value MUST be an object.`)), - schemaOf("propertyNames", minorVersionRange, v(`6.22. propertyNames`, `The value of "propertyNames" MUST be a valid JSON Schema.`)), - keyword("enum", RawList, minorVersionRange, v(`6.23. enum`, `The value of this keyword MUST be an array.`)), - keyword("const", AnyShapeUnchecked, minorVersionRange, v(`6.24. const`, `The value of this keyword MAY be of any type, including null.`)), - keyword("type", String, minorVersionRange, v(`6.25. type`, `The value of this keyword MUST be either a string or an array.`)). + keyword("$schema", String, minorVersionRange, core(`7. The "$schema" keyword`, `The value of this keyword MUST be a URI [RFC3986] (containing a scheme) and this URI MUST be normalized.`)).formatted(AbsoluteURI), + keyword("$id", String, minorVersionRange, core(`9.2. The "$id" keyword`, `If present, the value for this keyword MUST be a string, and MUST represent a valid URI-reference [RFC3986].`)). + formatted(PlainNameURI, core(`9.2. The "$id" keyword`, `The fragment identifier MUST begin with a letter ([A-Za-z]), followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), or periods (".").`)), + keyword("$ref", String, minorVersionRange, core(`8. Schema references with $ref`, `An object schema with a "$ref" property MUST be interpreted as a "$ref" reference.`)).formatted(URI), + keyword("multipleOf", PositiveNumber, minorVersionRange, validation(`6.1. multipleOf`, `The value of "multipleOf" MUST be a number, strictly greater than 0.`)), + keyword("maximum", Number, minorVersionRange, validation(`6.2. maximum`, `The value of "maximum" MUST be a number`)), + keyword("exclusiveMaximum", Number, minorVersionRange, validation(`6.3. exclusiveMaximum`, `The value of "exclusiveMaximum" MUST be number`)), + keyword("minimum", Number, minorVersionRange, validation(`6.4. minimum`, `The value of "minimum" MUST be a number`)), + keyword("exclusiveMinimum", Number, minorVersionRange, validation(`6.5. exclusiveMinimum`, `The value of "exclusiveMinimum" MUST be number`)), + keyword("maxLength", Natural, minorVersionRange, validation(`6.6. maxLength`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minLength", Natural, minorVersionRange, validation(`6.7. minLength`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("pattern", String, minorVersionRange, validation(`6.8. pattern`, `The value of this keyword MUST be a string.`)), + schemaOf("items", minorVersionRange, validation(`6.9. items`, `The value of "items" MUST be either a valid JSON Schema or an array of valid JSON Schemas.`)).also(List, minorVersionRange), + schemaOf("additionalItems", minorVersionRange, validation(`6.10. additionalItems`, `The value of "additionalItems" MUST be a valid JSON Schema.`)), + keyword("maxItems", Natural, minorVersionRange, validation(`6.11. maxItems`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minItems", Natural, minorVersionRange, validation(`6.12. minItems`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("uniqueItems", Boolean, minorVersionRange, validation(`6.13. uniqueItems`, `The value of this keyword MUST be a boolean.`)), + schemaOf("contains", minorVersionRange, validation(`6.14. contains`, `The value of this keyword MUST be a valid JSON Schema.`)), + keyword("maxProperties", Natural, minorVersionRange, validation(`6.15. maxProperties`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minProperties", Natural, minorVersionRange, validation(`6.16. minProperties`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("required", StringList, minorVersionRange, validation(`6.17. required`, `The value of this keyword MUST be an array.`)), + schemaMapOf("properties", minorVersionRange, validation(`6.18. properties`, `The value of "properties" MUST be an object.`)), + schemaMapOf("patternProperties", minorVersionRange, validation(`6.19. patternProperties`, `The value of "patternProperties" MUST be an object.`)), + schemaOf("additionalProperties", minorVersionRange, validation(`6.20. additionalProperties`, `The value of "additionalProperties" MUST be a valid JSON Schema.`)), + keyword("dependencies", RawMap, minorVersionRange, validation(`6.21. dependencies`, `This keyword's value MUST be an object.`)), + schemaOf("propertyNames", minorVersionRange, validation(`6.22. propertyNames`, `The value of "propertyNames" MUST be a valid JSON Schema.`)), + keyword("enum", RawList, minorVersionRange, validation(`6.23. enum`, `The value of this keyword MUST be an array.`)), + keyword("const", AnyShapeUnchecked, minorVersionRange, validation(`6.24. const`, `The value of this keyword MAY be of any type, including null.`)), + keyword("type", String, minorVersionRange, validation(`6.25. type`, `The value of this keyword MUST be either a string or an array.`)). admits(vals("array", "boolean", "integer", "null", "number", "object", "string")...).also(StringList, minorVersionRange), - schemasOf("allOf", minorVersionRange, v(`6.26. allOf`, `This keyword's value MUST be a non-empty array.`)), - schemasOf("anyOf", minorVersionRange, v(`6.27. anyOf`, `This keyword's value MUST be a non-empty array.`)), - schemasOf("oneOf", minorVersionRange, v(`6.28. oneOf`, `This keyword's value MUST be a non-empty array.`)), - schemaOf("not", minorVersionRange, v(`6.29. not`, `This keyword's value MUST be a valid JSON Schema.`)), - schemaMapOf("definitions", minorVersionRange, v(`7.1. definitions`, `This keyword's value MUST be an object.`)), - keyword("title", String, minorVersionRange, v(`7.2. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), - keyword("description", String, minorVersionRange, v(`7.2. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), - keyword("default", AnyShapeUnchecked, minorVersionRange, v(`7.3. "default"`, `There are no restrictions placed on the value of this keyword.`)), - keyword("examples", RawList, minorVersionRange, v(`7.4. "examples"`, `The value of this keyword MUST be an array.`)), - keyword("format", String, minorVersionRange, v(`8.1. Foreword`, `It MUST be a string.`)), + schemasOf("allOf", minorVersionRange, validation(`6.26. allOf`, `This keyword's value MUST be a non-empty array.`)), + schemasOf("anyOf", minorVersionRange, validation(`6.27. anyOf`, `This keyword's value MUST be a non-empty array.`)), + schemasOf("oneOf", minorVersionRange, validation(`6.28. oneOf`, `This keyword's value MUST be a non-empty array.`)), + schemaOf("not", minorVersionRange, validation(`6.29. not`, `This keyword's value MUST be a valid JSON Schema.`)), + schemaMapOf("definitions", minorVersionRange, validation(`7.1. definitions`, `This keyword's value MUST be an object.`)), + keyword("title", String, minorVersionRange, validation(`7.2. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), + keyword("description", String, minorVersionRange, validation(`7.2. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), + keyword("default", AnyShapeUnchecked, minorVersionRange, validation(`7.3. "default"`, `There are no restrictions placed on the value of this keyword.`)), + keyword("examples", RawList, minorVersionRange, validation(`7.4. "examples"`, `The value of this keyword MUST be an array.`)), + keyword("format", String, minorVersionRange, validation(`8.1. Foreword`, `It MUST be a string.`)), } } @@ -57,57 +57,57 @@ func draft06Keywords() []Field { // its validation text's, each defined at every minor that lets a schema // declare a dialect. func draft07Keywords() []Field { - c, v := jsonSchemaText(TextDraft07Core), jsonSchemaText(TextDraft07Validation) + core, validation := jsonSchemaText(TextDraft07Core), jsonSchemaText(TextDraft07Validation) minorVersionRange := From(V31) return []Field{ - keyword("$schema", String, minorVersionRange, c(`7. The "$schema" Keyword`, `The value of this keyword MUST be a URI [RFC3986] (containing a scheme) and this URI MUST be normalized.`)).formatted(AbsoluteURI), - keyword("$id", String, minorVersionRange, c(`8.2. The "$id" Keyword`, `If present, the value for this keyword MUST be a string, and MUST represent a valid URI-reference [RFC3986].`)). - formatted(PlainNameURI, c(`8.2.3. Location-independent identifiers`, `This value MUST begin with the number sign that specifies a fragment ("#"), then a letter ([A-Za-z]), followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), or periods (".").`)), - keyword("$ref", String, minorVersionRange, c(`8.3. Schema References With "$ref"`, `The value of the "$ref" property MUST be a URI Reference.`)).formatted(URI), - keyword("$comment", String, minorVersionRange, c(`9. Comments With "$comment"`, `The value of this keyword MUST be a string.`)), - keyword("type", String, minorVersionRange, v(`6.1.1. type`, `The value of this keyword MUST be either a string or an array.`)). + keyword("$schema", String, minorVersionRange, core(`7. The "$schema" Keyword`, `The value of this keyword MUST be a URI [RFC3986] (containing a scheme) and this URI MUST be normalized.`)).formatted(AbsoluteURI), + keyword("$id", String, minorVersionRange, core(`8.2. The "$id" Keyword`, `If present, the value for this keyword MUST be a string, and MUST represent a valid URI-reference [RFC3986].`)). + formatted(PlainNameURI, core(`8.2.3. Location-independent identifiers`, `This value MUST begin with the number sign that specifies a fragment ("#"), then a letter ([A-Za-z]), followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), or periods (".").`)), + keyword("$ref", String, minorVersionRange, core(`8.3. Schema References With "$ref"`, `The value of the "$ref" property MUST be a URI Reference.`)).formatted(URI), + keyword("$comment", String, minorVersionRange, core(`9. Comments With "$comment"`, `The value of this keyword MUST be a string.`)), + keyword("type", String, minorVersionRange, validation(`6.1.1. type`, `The value of this keyword MUST be either a string or an array.`)). admits(vals("array", "boolean", "integer", "null", "number", "object", "string")...).also(StringList, minorVersionRange), - keyword("enum", RawList, minorVersionRange, v(`6.1.2. enum`, `The value of this keyword MUST be an array.`)), - keyword("const", AnyShapeUnchecked, minorVersionRange, v(`6.1.3. const`, `The value of this keyword MAY be of any type, including null.`)), - keyword("multipleOf", PositiveNumber, minorVersionRange, v(`6.2.1. multipleOf`, `The value of "multipleOf" MUST be a number, strictly greater than 0.`)), - keyword("maximum", Number, minorVersionRange, v(`6.2.2. maximum`, `The value of "maximum" MUST be a number`)), - keyword("exclusiveMaximum", Number, minorVersionRange, v(`6.2.3. exclusiveMaximum`, `The value of "exclusiveMaximum" MUST be number`)), - keyword("minimum", Number, minorVersionRange, v(`6.2.4. minimum`, `The value of "minimum" MUST be a number`)), - keyword("exclusiveMinimum", Number, minorVersionRange, v(`6.2.5. exclusiveMinimum`, `The value of "exclusiveMinimum" MUST be number`)), - keyword("maxLength", Natural, minorVersionRange, v(`6.3.1. maxLength`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minLength", Natural, minorVersionRange, v(`6.3.2. minLength`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("pattern", String, minorVersionRange, v(`6.3.3. pattern`, `The value of this keyword MUST be a string.`)), - schemaOf("items", minorVersionRange, v(`6.4.1. items`, `The value of "items" MUST be either a valid JSON Schema or an array of valid JSON Schemas.`)).also(List, minorVersionRange), - schemaOf("additionalItems", minorVersionRange, v(`6.4.2. additionalItems`, `The value of "additionalItems" MUST be a valid JSON Schema.`)), - keyword("maxItems", Natural, minorVersionRange, v(`6.4.3. maxItems`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minItems", Natural, minorVersionRange, v(`6.4.4. minItems`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("uniqueItems", Boolean, minorVersionRange, v(`6.4.5. uniqueItems`, `The value of this keyword MUST be a boolean.`)), - schemaOf("contains", minorVersionRange, v(`6.4.6. contains`, `The value of this keyword MUST be a valid JSON Schema.`)), - keyword("maxProperties", Natural, minorVersionRange, v(`6.5.1. maxProperties`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minProperties", Natural, minorVersionRange, v(`6.5.2. minProperties`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("required", StringList, minorVersionRange, v(`6.5.3. required`, `The value of this keyword MUST be an array.`)), - schemaMapOf("properties", minorVersionRange, v(`6.5.4. properties`, `The value of "properties" MUST be an object.`)), - schemaMapOf("patternProperties", minorVersionRange, v(`6.5.5. patternProperties`, `The value of "patternProperties" MUST be an object.`)), - schemaOf("additionalProperties", minorVersionRange, v(`6.5.6. additionalProperties`, `The value of "additionalProperties" MUST be a valid JSON Schema.`)), - keyword("dependencies", RawMap, minorVersionRange, v(`6.5.7. dependencies`, `This keyword's value MUST be an object.`)), - schemaOf("propertyNames", minorVersionRange, v(`6.5.8. propertyNames`, `The value of "propertyNames" MUST be a valid JSON Schema.`)), - schemaOf("if", minorVersionRange, v(`6.6.1. if`, `This keyword's value MUST be a valid JSON Schema.`)), - schemaOf("then", minorVersionRange, v(`6.6.2. then`, `This keyword's value MUST be a valid JSON Schema.`)), - schemaOf("else", minorVersionRange, v(`6.6.3. else`, `This keyword's value MUST be a valid JSON Schema.`)), - schemasOf("allOf", minorVersionRange, v(`6.7.1. allOf`, `This keyword's value MUST be a non-empty array.`)), - schemasOf("anyOf", minorVersionRange, v(`6.7.2. anyOf`, `This keyword's value MUST be a non-empty array.`)), - schemasOf("oneOf", minorVersionRange, v(`6.7.3. oneOf`, `This keyword's value MUST be a non-empty array.`)), - schemaOf("not", minorVersionRange, v(`6.7.4. not`, `This keyword's value MUST be a valid JSON Schema.`)), - keyword("format", String, minorVersionRange, v(`7.1. Foreword`, `It MUST be a string.`)), - keyword("contentEncoding", String, minorVersionRange, v(`8.3. contentEncoding`, `The value of this property MUST be a string.`)), - keyword("contentMediaType", String, minorVersionRange, v(`8.4. contentMediaType`, `The value of this property MUST be a string.`)), - schemaMapOf("definitions", minorVersionRange, v(`9. Schema Re-Use With "definitions"`, `This keyword's value MUST be an object.`)), - keyword("title", String, minorVersionRange, v(`10.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), - keyword("description", String, minorVersionRange, v(`10.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), - keyword("default", AnyShapeUnchecked, minorVersionRange, v(`10.2. "default"`, `There are no restrictions placed on the value of this keyword.`)), - keyword("readOnly", Boolean, minorVersionRange, v(`10.3. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), - keyword("writeOnly", Boolean, minorVersionRange, v(`10.3. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), - keyword("examples", RawList, minorVersionRange, v(`10.4. "examples"`, `The value of this keyword MUST be an array.`)), + keyword("enum", RawList, minorVersionRange, validation(`6.1.2. enum`, `The value of this keyword MUST be an array.`)), + keyword("const", AnyShapeUnchecked, minorVersionRange, validation(`6.1.3. const`, `The value of this keyword MAY be of any type, including null.`)), + keyword("multipleOf", PositiveNumber, minorVersionRange, validation(`6.2.1. multipleOf`, `The value of "multipleOf" MUST be a number, strictly greater than 0.`)), + keyword("maximum", Number, minorVersionRange, validation(`6.2.2. maximum`, `The value of "maximum" MUST be a number`)), + keyword("exclusiveMaximum", Number, minorVersionRange, validation(`6.2.3. exclusiveMaximum`, `The value of "exclusiveMaximum" MUST be number`)), + keyword("minimum", Number, minorVersionRange, validation(`6.2.4. minimum`, `The value of "minimum" MUST be a number`)), + keyword("exclusiveMinimum", Number, minorVersionRange, validation(`6.2.5. exclusiveMinimum`, `The value of "exclusiveMinimum" MUST be number`)), + keyword("maxLength", Natural, minorVersionRange, validation(`6.3.1. maxLength`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minLength", Natural, minorVersionRange, validation(`6.3.2. minLength`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("pattern", String, minorVersionRange, validation(`6.3.3. pattern`, `The value of this keyword MUST be a string.`)), + schemaOf("items", minorVersionRange, validation(`6.4.1. items`, `The value of "items" MUST be either a valid JSON Schema or an array of valid JSON Schemas.`)).also(List, minorVersionRange), + schemaOf("additionalItems", minorVersionRange, validation(`6.4.2. additionalItems`, `The value of "additionalItems" MUST be a valid JSON Schema.`)), + keyword("maxItems", Natural, minorVersionRange, validation(`6.4.3. maxItems`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minItems", Natural, minorVersionRange, validation(`6.4.4. minItems`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("uniqueItems", Boolean, minorVersionRange, validation(`6.4.5. uniqueItems`, `The value of this keyword MUST be a boolean.`)), + schemaOf("contains", minorVersionRange, validation(`6.4.6. contains`, `The value of this keyword MUST be a valid JSON Schema.`)), + keyword("maxProperties", Natural, minorVersionRange, validation(`6.5.1. maxProperties`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minProperties", Natural, minorVersionRange, validation(`6.5.2. minProperties`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("required", StringList, minorVersionRange, validation(`6.5.3. required`, `The value of this keyword MUST be an array.`)), + schemaMapOf("properties", minorVersionRange, validation(`6.5.4. properties`, `The value of "properties" MUST be an object.`)), + schemaMapOf("patternProperties", minorVersionRange, validation(`6.5.5. patternProperties`, `The value of "patternProperties" MUST be an object.`)), + schemaOf("additionalProperties", minorVersionRange, validation(`6.5.6. additionalProperties`, `The value of "additionalProperties" MUST be a valid JSON Schema.`)), + keyword("dependencies", RawMap, minorVersionRange, validation(`6.5.7. dependencies`, `This keyword's value MUST be an object.`)), + schemaOf("propertyNames", minorVersionRange, validation(`6.5.8. propertyNames`, `The value of "propertyNames" MUST be a valid JSON Schema.`)), + schemaOf("if", minorVersionRange, validation(`6.6.1. if`, `This keyword's value MUST be a valid JSON Schema.`)), + schemaOf("then", minorVersionRange, validation(`6.6.2. then`, `This keyword's value MUST be a valid JSON Schema.`)), + schemaOf("else", minorVersionRange, validation(`6.6.3. else`, `This keyword's value MUST be a valid JSON Schema.`)), + schemasOf("allOf", minorVersionRange, validation(`6.7.1. allOf`, `This keyword's value MUST be a non-empty array.`)), + schemasOf("anyOf", minorVersionRange, validation(`6.7.2. anyOf`, `This keyword's value MUST be a non-empty array.`)), + schemasOf("oneOf", minorVersionRange, validation(`6.7.3. oneOf`, `This keyword's value MUST be a non-empty array.`)), + schemaOf("not", minorVersionRange, validation(`6.7.4. not`, `This keyword's value MUST be a valid JSON Schema.`)), + keyword("format", String, minorVersionRange, validation(`7.1. Foreword`, `It MUST be a string.`)), + keyword("contentEncoding", String, minorVersionRange, validation(`8.3. contentEncoding`, `The value of this property MUST be a string.`)), + keyword("contentMediaType", String, minorVersionRange, validation(`8.4. contentMediaType`, `The value of this property MUST be a string.`)), + schemaMapOf("definitions", minorVersionRange, validation(`9. Schema Re-Use With "definitions"`, `This keyword's value MUST be an object.`)), + keyword("title", String, minorVersionRange, validation(`10.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), + keyword("description", String, minorVersionRange, validation(`10.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), + keyword("default", AnyShapeUnchecked, minorVersionRange, validation(`10.2. "default"`, `There are no restrictions placed on the value of this keyword.`)), + keyword("readOnly", Boolean, minorVersionRange, validation(`10.3. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), + keyword("writeOnly", Boolean, minorVersionRange, validation(`10.3. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), + keyword("examples", RawList, minorVersionRange, validation(`10.4. "examples"`, `The value of this keyword MUST be an array.`)), } } @@ -115,66 +115,66 @@ func draft07Keywords() []Field { // its validation text's, each defined at every minor that lets a schema // declare a dialect. func draft2019Keywords() []Field { - c, v := jsonSchemaText(TextDraft2019Core), jsonSchemaText(TextDraft2019Validation) + core, validation := jsonSchemaText(TextDraft2019Core), jsonSchemaText(TextDraft2019Validation) minorVersionRange := From(V31) return []Field{ - keyword("$schema", String, minorVersionRange, c(`8.1.1. The "$schema" Keyword`, `The value of this keyword MUST be a URI [RFC3986] (containing a scheme) and this URI MUST be normalized.`)).formatted(AbsoluteURI), - keyword("$vocabulary", RawMap, minorVersionRange, c(`8.1.2. The "$vocabulary" Keyword`, `The value of this keyword MUST be an object.`)), - keyword("$id", String, minorVersionRange, c(`8.2.2. The "$id" Keyword`, `Therefore, "$id" MUST NOT contain a non-empty fragment, and SHOULD NOT contain an empty fragment.`)).formatted(ResourceURI), - keyword("$anchor", String, minorVersionRange, c(`8.2.3. Defining location-independent identifiers with "$anchor"`, `If present, the value of this keyword MUST be a string, which MUST start with a letter ([A-Za-z]), followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), or periods (".").`)).formatted(PlainName).nonEmpty(minorVersionRange), - keyword("$ref", String, minorVersionRange, c(`8.2.4.1. Direct References with "$ref"`, `The value of the "$ref" property MUST be a string which is a URI-Reference.`)).formatted(URI), - keyword("$recursiveRef", String, minorVersionRange, c(`8.2.4.2.1. Dynamically recursive references with "$recursiveRef"`, `The value of the "$recursiveRef" property MUST be a string which is a URI-reference.`)).formatted(URI), - keyword("$recursiveAnchor", Boolean, minorVersionRange, c(`8.2.4.2.2. Enabling Recursion with "$recursiveAnchor"`, `The value of the "$recursiveAnchor" property MUST be a boolean.`)), - schemaMapOf("$defs", minorVersionRange, c(`8.2.5. Schema Re-Use With "$defs"`, `This keyword's value MUST be an object.`)), - keyword("$comment", String, minorVersionRange, c(`8.3. Comments With "$comment"`, `The value of this keyword MUST be a string.`)), - schemasOf("allOf", minorVersionRange, c(`9.2.1.1. allOf`, `This keyword's value MUST be a non-empty array.`)), - schemasOf("anyOf", minorVersionRange, c(`9.2.1.2. anyOf`, `This keyword's value MUST be a non-empty array.`)), - schemasOf("oneOf", minorVersionRange, c(`9.2.1.3. oneOf`, `This keyword's value MUST be a non-empty array.`)), - schemaOf("not", minorVersionRange, c(`9.2.1.4. not`, `This keyword's value MUST be a valid JSON Schema.`)), - schemaOf("if", minorVersionRange, c(`9.2.2.1. if`, `This keyword's value MUST be a valid JSON Schema.`)), - schemaOf("then", minorVersionRange, c(`9.2.2.2. then`, `This keyword's value MUST be a valid JSON Schema.`)), - schemaOf("else", minorVersionRange, c(`9.2.2.3. else`, `This keyword's value MUST be a valid JSON Schema.`)), - schemaMapOf("dependentSchemas", minorVersionRange, c(`9.2.2.4. dependentSchemas`, `This keyword's value MUST be an object.`)), - schemaOf("items", minorVersionRange, c(`9.3.1.1. items`, `The value of "items" MUST be either a valid JSON Schema or an array of valid JSON Schemas.`)).also(List, minorVersionRange), - schemaOf("additionalItems", minorVersionRange, c(`9.3.1.2. additionalItems`, `The value of "additionalItems" MUST be a valid JSON Schema.`)), - schemaOf("unevaluatedItems", minorVersionRange, c(`9.3.1.3. unevaluatedItems`, `The value of "unevaluatedItems" MUST be a valid JSON Schema.`)), - schemaOf("contains", minorVersionRange, c(`9.3.1.4. contains`, `The value of this keyword MUST be a valid JSON Schema.`)), - schemaMapOf("properties", minorVersionRange, c(`9.3.2.1. properties`, `The value of "properties" MUST be an object.`)), - schemaMapOf("patternProperties", minorVersionRange, c(`9.3.2.2. patternProperties`, `The value of "patternProperties" MUST be an object.`)), - schemaOf("additionalProperties", minorVersionRange, c(`9.3.2.3. additionalProperties`, `The value of "additionalProperties" MUST be a valid JSON Schema.`)), - schemaOf("unevaluatedProperties", minorVersionRange, c(`9.3.2.4. unevaluatedProperties`, `The value of "unevaluatedProperties" MUST be a valid JSON Schema.`)), - schemaOf("propertyNames", minorVersionRange, c(`9.3.2.5. propertyNames`, `The value of "propertyNames" MUST be a valid JSON Schema.`)), - keyword("type", String, minorVersionRange, v(`6.1.1. type`, `The value of this keyword MUST be either a string or an array.`)). + keyword("$schema", String, minorVersionRange, core(`8.1.1. The "$schema" Keyword`, `The value of this keyword MUST be a URI [RFC3986] (containing a scheme) and this URI MUST be normalized.`)).formatted(AbsoluteURI), + keyword("$vocabulary", RawMap, minorVersionRange, core(`8.1.2. The "$vocabulary" Keyword`, `The value of this keyword MUST be an object.`)), + keyword("$id", String, minorVersionRange, core(`8.2.2. The "$id" Keyword`, `Therefore, "$id" MUST NOT contain a non-empty fragment, and SHOULD NOT contain an empty fragment.`)).formatted(ResourceURI), + keyword("$anchor", String, minorVersionRange, core(`8.2.3. Defining location-independent identifiers with "$anchor"`, `If present, the value of this keyword MUST be a string, which MUST start with a letter ([A-Za-z]), followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), or periods (".").`)).formatted(PlainName).nonEmpty(minorVersionRange), + keyword("$ref", String, minorVersionRange, core(`8.2.4.1. Direct References with "$ref"`, `The value of the "$ref" property MUST be a string which is a URI-Reference.`)).formatted(URI), + keyword("$recursiveRef", String, minorVersionRange, core(`8.2.4.2.1. Dynamically recursive references with "$recursiveRef"`, `The value of the "$recursiveRef" property MUST be a string which is a URI-reference.`)).formatted(URI), + keyword("$recursiveAnchor", Boolean, minorVersionRange, core(`8.2.4.2.2. Enabling Recursion with "$recursiveAnchor"`, `The value of the "$recursiveAnchor" property MUST be a boolean.`)), + schemaMapOf("$defs", minorVersionRange, core(`8.2.5. Schema Re-Use With "$defs"`, `This keyword's value MUST be an object.`)), + keyword("$comment", String, minorVersionRange, core(`8.3. Comments With "$comment"`, `The value of this keyword MUST be a string.`)), + schemasOf("allOf", minorVersionRange, core(`9.2.1.1. allOf`, `This keyword's value MUST be a non-empty array.`)), + schemasOf("anyOf", minorVersionRange, core(`9.2.1.2. anyOf`, `This keyword's value MUST be a non-empty array.`)), + schemasOf("oneOf", minorVersionRange, core(`9.2.1.3. oneOf`, `This keyword's value MUST be a non-empty array.`)), + schemaOf("not", minorVersionRange, core(`9.2.1.4. not`, `This keyword's value MUST be a valid JSON Schema.`)), + schemaOf("if", minorVersionRange, core(`9.2.2.1. if`, `This keyword's value MUST be a valid JSON Schema.`)), + schemaOf("then", minorVersionRange, core(`9.2.2.2. then`, `This keyword's value MUST be a valid JSON Schema.`)), + schemaOf("else", minorVersionRange, core(`9.2.2.3. else`, `This keyword's value MUST be a valid JSON Schema.`)), + schemaMapOf("dependentSchemas", minorVersionRange, core(`9.2.2.4. dependentSchemas`, `This keyword's value MUST be an object.`)), + schemaOf("items", minorVersionRange, core(`9.3.1.1. items`, `The value of "items" MUST be either a valid JSON Schema or an array of valid JSON Schemas.`)).also(List, minorVersionRange), + schemaOf("additionalItems", minorVersionRange, core(`9.3.1.2. additionalItems`, `The value of "additionalItems" MUST be a valid JSON Schema.`)), + schemaOf("unevaluatedItems", minorVersionRange, core(`9.3.1.3. unevaluatedItems`, `The value of "unevaluatedItems" MUST be a valid JSON Schema.`)), + schemaOf("contains", minorVersionRange, core(`9.3.1.4. contains`, `The value of this keyword MUST be a valid JSON Schema.`)), + schemaMapOf("properties", minorVersionRange, core(`9.3.2.1. properties`, `The value of "properties" MUST be an object.`)), + schemaMapOf("patternProperties", minorVersionRange, core(`9.3.2.2. patternProperties`, `The value of "patternProperties" MUST be an object.`)), + schemaOf("additionalProperties", minorVersionRange, core(`9.3.2.3. additionalProperties`, `The value of "additionalProperties" MUST be a valid JSON Schema.`)), + schemaOf("unevaluatedProperties", minorVersionRange, core(`9.3.2.4. unevaluatedProperties`, `The value of "unevaluatedProperties" MUST be a valid JSON Schema.`)), + schemaOf("propertyNames", minorVersionRange, core(`9.3.2.5. propertyNames`, `The value of "propertyNames" MUST be a valid JSON Schema.`)), + keyword("type", String, minorVersionRange, validation(`6.1.1. type`, `The value of this keyword MUST be either a string or an array.`)). admits(vals("array", "boolean", "integer", "null", "number", "object", "string")...).also(StringList, minorVersionRange), - keyword("enum", RawList, minorVersionRange, v(`6.1.2. enum`, `The value of this keyword MUST be an array.`)), - keyword("const", AnyShapeUnchecked, minorVersionRange, v(`6.1.3. const`, `The value of this keyword MAY be of any type, including null.`)), - keyword("multipleOf", PositiveNumber, minorVersionRange, v(`6.2.1. multipleOf`, `The value of "multipleOf" MUST be a number, strictly greater than 0.`)), - keyword("maximum", Number, minorVersionRange, v(`6.2.2. maximum`, `The value of "maximum" MUST be a number`)), - keyword("exclusiveMaximum", Number, minorVersionRange, v(`6.2.3. exclusiveMaximum`, `The value of "exclusiveMaximum" MUST be number`)), - keyword("minimum", Number, minorVersionRange, v(`6.2.4. minimum`, `The value of "minimum" MUST be a number`)), - keyword("exclusiveMinimum", Number, minorVersionRange, v(`6.2.5. exclusiveMinimum`, `The value of "exclusiveMinimum" MUST be number`)), - keyword("maxLength", Natural, minorVersionRange, v(`6.3.1. maxLength`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minLength", Natural, minorVersionRange, v(`6.3.2. minLength`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("pattern", String, minorVersionRange, v(`6.3.3. pattern`, `The value of this keyword MUST be a string.`)), - keyword("maxItems", Natural, minorVersionRange, v(`6.4.1. maxItems`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minItems", Natural, minorVersionRange, v(`6.4.2. minItems`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("uniqueItems", Boolean, minorVersionRange, v(`6.4.3. uniqueItems`, `The value of this keyword MUST be a boolean.`)), - keyword("maxContains", Natural, minorVersionRange, v(`6.4.4. maxContains`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minContains", Natural, minorVersionRange, v(`6.4.5. minContains`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("maxProperties", Natural, minorVersionRange, v(`6.5.1. maxProperties`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("minProperties", Natural, minorVersionRange, v(`6.5.2. minProperties`, `The value of this keyword MUST be a non-negative integer.`)), - keyword("required", StringList, minorVersionRange, v(`6.5.3. required`, `The value of this keyword MUST be an array.`)), - keyword("dependentRequired", RawMap, minorVersionRange, v(`6.5.4. dependentRequired`, `The value of this keyword MUST be an object.`)), - keyword("format", String, minorVersionRange, v(`7.1. Foreword`, `It MUST be a string.`)), - keyword("contentEncoding", String, minorVersionRange, v(`8.3. contentEncoding`, `The value of this property MUST be a string.`)), - keyword("contentMediaType", String, minorVersionRange, v(`8.4. contentMediaType`, `The value of this property MUST be a string`)), - schemaOf("contentSchema", minorVersionRange, v(`8.5. contentSchema`, `this property contains a schema which describes the structure of the string.`)), - keyword("title", String, minorVersionRange, v(`9.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), - keyword("description", String, minorVersionRange, v(`9.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), - keyword("default", AnyShapeUnchecked, minorVersionRange, v(`9.2. "default"`, `There are no restrictions placed on the value of this keyword.`)), - keyword("deprecated", Boolean, minorVersionRange, v(`9.3. "deprecated"`, `The value of this keyword MUST be a boolean.`)), - keyword("readOnly", Boolean, minorVersionRange, v(`9.4. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), - keyword("writeOnly", Boolean, minorVersionRange, v(`9.4. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), - keyword("examples", RawList, minorVersionRange, v(`9.5. "examples"`, `The value of this keyword MUST be an array.`)), + keyword("enum", RawList, minorVersionRange, validation(`6.1.2. enum`, `The value of this keyword MUST be an array.`)), + keyword("const", AnyShapeUnchecked, minorVersionRange, validation(`6.1.3. const`, `The value of this keyword MAY be of any type, including null.`)), + keyword("multipleOf", PositiveNumber, minorVersionRange, validation(`6.2.1. multipleOf`, `The value of "multipleOf" MUST be a number, strictly greater than 0.`)), + keyword("maximum", Number, minorVersionRange, validation(`6.2.2. maximum`, `The value of "maximum" MUST be a number`)), + keyword("exclusiveMaximum", Number, minorVersionRange, validation(`6.2.3. exclusiveMaximum`, `The value of "exclusiveMaximum" MUST be number`)), + keyword("minimum", Number, minorVersionRange, validation(`6.2.4. minimum`, `The value of "minimum" MUST be a number`)), + keyword("exclusiveMinimum", Number, minorVersionRange, validation(`6.2.5. exclusiveMinimum`, `The value of "exclusiveMinimum" MUST be number`)), + keyword("maxLength", Natural, minorVersionRange, validation(`6.3.1. maxLength`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minLength", Natural, minorVersionRange, validation(`6.3.2. minLength`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("pattern", String, minorVersionRange, validation(`6.3.3. pattern`, `The value of this keyword MUST be a string.`)), + keyword("maxItems", Natural, minorVersionRange, validation(`6.4.1. maxItems`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minItems", Natural, minorVersionRange, validation(`6.4.2. minItems`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("uniqueItems", Boolean, minorVersionRange, validation(`6.4.3. uniqueItems`, `The value of this keyword MUST be a boolean.`)), + keyword("maxContains", Natural, minorVersionRange, validation(`6.4.4. maxContains`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minContains", Natural, minorVersionRange, validation(`6.4.5. minContains`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("maxProperties", Natural, minorVersionRange, validation(`6.5.1. maxProperties`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("minProperties", Natural, minorVersionRange, validation(`6.5.2. minProperties`, `The value of this keyword MUST be a non-negative integer.`)), + keyword("required", StringList, minorVersionRange, validation(`6.5.3. required`, `The value of this keyword MUST be an array.`)), + keyword("dependentRequired", RawMap, minorVersionRange, validation(`6.5.4. dependentRequired`, `The value of this keyword MUST be an object.`)), + keyword("format", String, minorVersionRange, validation(`7.1. Foreword`, `It MUST be a string.`)), + keyword("contentEncoding", String, minorVersionRange, validation(`8.3. contentEncoding`, `The value of this property MUST be a string.`)), + keyword("contentMediaType", String, minorVersionRange, validation(`8.4. contentMediaType`, `The value of this property MUST be a string`)), + schemaOf("contentSchema", minorVersionRange, validation(`8.5. contentSchema`, `this property contains a schema which describes the structure of the string.`)), + keyword("title", String, minorVersionRange, validation(`9.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), + keyword("description", String, minorVersionRange, validation(`9.1. "title" and "description"`, `The value of both of these keywords MUST be a string.`)), + keyword("default", AnyShapeUnchecked, minorVersionRange, validation(`9.2. "default"`, `There are no restrictions placed on the value of this keyword.`)), + keyword("deprecated", Boolean, minorVersionRange, validation(`9.3. "deprecated"`, `The value of this keyword MUST be a boolean.`)), + keyword("readOnly", Boolean, minorVersionRange, validation(`9.4. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), + keyword("writeOnly", Boolean, minorVersionRange, validation(`9.4. "readOnly" and "writeOnly"`, `The value of these keywords MUST be a boolean.`)), + keyword("examples", RawList, minorVersionRange, validation(`9.5. "examples"`, `The value of this keyword MUST be an array.`)), } } diff --git a/compilers/openapi/internal/specrules/table_keywords.go b/compilers/openapi/internal/specrules/table_keywords.go index 1e8e195a8..ab176f892 100644 --- a/compilers/openapi/internal/specrules/table_keywords.go +++ b/compilers/openapi/internal/specrules/table_keywords.go @@ -56,9 +56,9 @@ func schemaMapOf(name string, minorVersionRange MinorVersionRange, cite Cite) Fi // keywords30 are the keywords OpenAPI 3.0 takes from JSON Schema, a subset of // its fifth draft with the adjustments the specification lists. func keywords30() []Field { - c := sectioned("Schema Object") - direct := c(V30, "The following keywords are taken directly from the JSON Schema definition and follow the same specifications:") - adjust := func(sentence string) Cite { return c(V30, sentence) } + cite := sectioned("Schema Object") + direct := cite(V30, "The following keywords are taken directly from the JSON Schema definition and follow the same specifications:") + adjust := func(sentence string) Cite { return cite(V30, sentence) } minorVersionRange := Only(V30) composed := adjust("Inline or referenced schema MUST be of a [Schema Object](#schema-object) and not a standard JSON Schema.") return []Field{ @@ -90,9 +90,9 @@ func keywords30() []Field { keyword("description", String, minorVersionRange, adjust("[CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.")), keyword("format", String, minorVersionRange, adjust("See [Data Type Formats](#data-type-format) for further details.")), keyword("default", AnyShapeUnchecked, minorVersionRange, adjust("The default value represents what would be assumed by the consumer of the input")), - keyword("readOnly", Boolean, minorVersionRange, c(V30, "Declares the property as \"read only\".")), - keyword("writeOnly", Boolean, minorVersionRange, c(V30, "Declares the property as \"write only\".")), - keyword("deprecated", Boolean, minorVersionRange, c(V30, "Specifies that a schema is deprecated and SHOULD be transitioned out of usage.")), + keyword("readOnly", Boolean, minorVersionRange, cite(V30, "Declares the property as \"read only\".")), + keyword("writeOnly", Boolean, minorVersionRange, cite(V30, "Declares the property as \"write only\".")), + keyword("deprecated", Boolean, minorVersionRange, cite(V30, "Specifies that a schema is deprecated and SHOULD be transitioned out of usage.")), } } @@ -193,10 +193,10 @@ func dialectAnnotations() []Field { // names required lists, and from 3.1 the types a list gives, differ; and from // 3.1 dependentRequired and $vocabulary hold what their keywords define. func keywordRules() []Rule { - c := sectioned("Schema Object") - composed := c(V30, "Inline or referenced schema MUST be of a [Schema Object](#schema-object) and not a standard JSON Schema.") - direct := c(V30, "The following keywords are taken directly from the JSON Schema definition and follow the same specifications:") - dialect := c(V31, dialectSentence) + cite := sectioned("Schema Object") + composed := cite(V30, "Inline or referenced schema MUST be of a [Schema Object](#schema-object) and not a standard JSON Schema.") + direct := cite(V30, "The following keywords are taken directly from the JSON Schema definition and follow the same specifications:") + dialect := cite(V31, dialectSentence) var rules []Rule for _, name := range []string{"allOf", "anyOf", "oneOf"} { rules = append(rules, count(Always(), Must, name, 0, composed, dialect)) diff --git a/compilers/openapi/internal/specrules/table_params.go b/compilers/openapi/internal/specrules/table_params.go index 8587f9006..3d8a71737 100644 --- a/compilers/openapi/internal/specrules/table_params.go +++ b/compilers/openapi/internal/specrules/table_params.go @@ -35,135 +35,135 @@ func parameterObject() Object { // parameterFields are the fields of the Parameter Object. func parameterFields() []Field { - c := sectioned("Parameter Object") + cite := sectioned("Parameter Object") where := []Value{val("query"), valFrom("querystring", V32), val("header"), val("path"), val("cookie")} return []Field{ - field("name", String, c(V30, "**REQUIRED**. The name of the parameter.")).required(Always()), - field("in", String, c(V30, "**REQUIRED**. The location of the parameter.")).required(Always()).admits(where...), - field("description", String, c(V30, "A brief description of the parameter.")), - field("required", Boolean, c(V30, "Determines whether this parameter is mandatory.")), - field("deprecated", Boolean, c(V30, "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.")), - field("allowEmptyValue", Boolean, c(V30, "If `true`, clients MAY pass a zero-length string value in place of parameters")), - field("style", String, c(V30, "Describes how the parameter value will be serialized depending on the type of the parameter value.")). + field("name", String, cite(V30, "**REQUIRED**. The name of the parameter.")).required(Always()), + field("in", String, cite(V30, "**REQUIRED**. The location of the parameter.")).required(Always()).admits(where...), + field("description", String, cite(V30, "A brief description of the parameter.")), + field("required", Boolean, cite(V30, "Determines whether this parameter is mandatory.")), + field("deprecated", Boolean, cite(V30, "Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.")), + field("allowEmptyValue", Boolean, cite(V30, "If `true`, clients MAY pass a zero-length string value in place of parameters")), + field("style", String, cite(V30, "Describes how the parameter value will be serialized depending on the type of the parameter value.")). admits(styleValues()...), - field("explode", Boolean, c(V30, "When this is true, parameter values of type `array` or `object` generate separate parameters")), - field("allowReserved", Boolean, c(V30, "When this is true, parameter values are serialized using reserved expansion")), - objectOf("schema", Schema, c(V30, "The schema defining the type used for the parameter.")), - field("example", AnyShapeUnchecked, c(V30, "Example of the parameter's potential value; see")), - mapOf("examples", Example, c(V30, "Examples of the parameter's potential value; see")), - mapOf("content", MediaType, c(V30, "A map containing the representations for the parameter.")). - keyed(MediaTypeKey, c(V30, "The key is the media type and the value describes it.")), + field("explode", Boolean, cite(V30, "When this is true, parameter values of type `array` or `object` generate separate parameters")), + field("allowReserved", Boolean, cite(V30, "When this is true, parameter values are serialized using reserved expansion")), + objectOf("schema", Schema, cite(V30, "The schema defining the type used for the parameter.")), + field("example", AnyShapeUnchecked, cite(V30, "Example of the parameter's potential value; see")), + mapOf("examples", Example, cite(V30, "Examples of the parameter's potential value; see")), + mapOf("content", MediaType, cite(V30, "A map containing the representations for the parameter.")). + keyed(MediaTypeKey, cite(V30, "The key is the media type and the value describes it.")), } } // parameterRules are the rules of the Parameter Object. func parameterRules() []Rule { - c := sectioned("Parameter Object") + cite := sectioned("Parameter Object") path := when(term("in", "path")) writes := when(writing("content"), term("in", "query", "header", "path", "cookie")) return []Rule{ exactlyOne(Always(), fields("schema", "content"), - c(V30, "Parameter Objects MUST include either a `content` field or a `schema` field, but not both.")), + cite(V30, "Parameter Objects MUST include either a `content` field or a `schema` field, but not both.")), exclusive(Always(), fields("example", "examples"), - c(V30, "The `example` and `examples` fields are mutually exclusive")), - count(Always(), Must, "content", 1, c(V30, "The map MUST only contain one entry.")), + cite(V30, "The `example` and `examples` fields are mutually exclusive")), + count(Always(), Must, "content", 1, cite(V30, "The map MUST only contain one entry.")), requiredWhen(Always(), "required", path, - c(V30, "this field is **REQUIRED** and its value MUST be `true`.")), + cite(V30, "this field is **REQUIRED** and its value MUST be `true`.")), ruleRequiringFieldValue(Always(), "required", "true", path, - c(V30, "this field is **REQUIRED** and its value MUST be `true`.")), + cite(V30, "this field is **REQUIRED** and its value MUST be `true`.")), syntax(Always(), "name", Token, when(term("in", "header")), - c(V30, "Note that [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2) states header names are case insensitive."), - c(V32, "Note that [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.1) states header names are case-insensitive.")), + cite(V30, "Note that [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2) states header names are case insensitive."), + cite(V32, "Note that [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.1) states header names are case-insensitive.")), syntax(Always(), "name", Token, when(term("in", "cookie")), - c(V30, "cookie - Used to pass a specific cookie value to the API."), - c(V32, "Analogous to `form`, but following [[RFC6265]] `Cookie` syntax rules")), + cite(V30, "cookie - Used to pass a specific cookie value to the API."), + cite(V32, "Analogous to `form`, but following [[RFC6265]] `Cookie` syntax rules")), reserved(Always(), "name", when(term("in", "header")), fields("Accept", "Content-Type", "Authorization"), - c(V30, "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored.")), + cite(V30, "If `in` is `\"header\"` and the `name` field is `\"Accept\"`, `\"Content-Type\"` or `\"Authorization\"`, the parameter definition SHALL be ignored.")), forbiddenWhen(Always(), fields("allowEmptyValue"), when(term("in", "path", "header", "cookie", "querystring")), - c(V30, "This field is valid only for `query` parameters.")), + cite(V30, "This field is valid only for `query` parameters.")), inapplicable(Always(), "allowEmptyValue", when(term("in", "query"), term("style", "spaceDelimited", "pipeDelimited", "deepObject")), "only under a style that can write an empty value", - c(V30, "and if [behavior is _n/a_ (cannot be serialized)](#style-examples), the value of `allowEmptyValue` SHALL be ignored.")), + cite(V30, "and if [behavior is _n/a_ (cannot be serialized)](#style-examples), the value of `allowEmptyValue` SHALL be ignored.")), inapplicable(Through(V31), "allowReserved", when(term("in", "path", "header", "cookie")), "to in=query alone", - c(V30, "This field only applies to parameters with an `in` value of `query`.")), + cite(V30, "This field only applies to parameters with an `in` value of `query`.")), inapplicable(From(V32), "allowReserved", when(term("in", "header")), "only where the value is percent-encoded", - c(V32, "This field only applies to `in` and `style` values that automatically percent-encode.")), + cite(V32, "This field only applies to `in` and `style` values that automatically percent-encode.")), inapplicable(From(V32), "allowReserved", when(term("in", "cookie"), term("style", "cookie")), "only where the value is percent-encoded", - c(V32, "This field only applies to `in` and `style` values that automatically percent-encode.")), + cite(V32, "This field only applies to `in` and `style` values that automatically percent-encode.")), forbiddenWhen(From(V32), fields("schema"), when(term("in", "querystring")), - c(V32, "These fields MUST NOT be used with `in: \"querystring\"`.")), + cite(V32, "These fields MUST NOT be used with `in: \"querystring\"`.")), misplaced(From(V32), fields("style", "explode", "allowReserved"), when(term("in", "querystring")), - c(V32, "These fields MUST NOT be used with `in: \"querystring\"`.")), + cite(V32, "These fields MUST NOT be used with `in: \"querystring\"`.")), // in: querystring is the misplaced row's: 3.2 bars the three there. - besideContent(c, "parameter", "style", writes), besideContent(c, "parameter", "explode", writes), - besideContent(c, "parameter", "allowReserved", writes), + besideContent(cite, "parameter", "style", writes), besideContent(cite, "parameter", "explode", writes), + besideContent(cite, "parameter", "allowReserved", writes), } } // besideContent returns a rule: name, a field a carrier, a parameter or a // header, serializes its value with through its schema, has no effect where // cond, which has the object write content, whose media type serializes it, -// holds, c citing the object's section. -func besideContent(c func(Minor, string) Cite, carrier, name string, cond []Term) Rule { +// holds, cite citing the object's section. +func besideContent(cite func(Minor, string) Cite, carrier, name string, cond []Term) Rule { return inapplicable(Always(), name, cond, "to a "+carrier+" serialized through its schema", - c(V30, "For simpler scenarios, a [`schema`](#parameter-schema) and [`style`](#parameter-style) can describe the structure and syntax of the parameter."), - c(V31, "Fixed Fields for use with `schema`")) + cite(V30, "For simpler scenarios, a [`schema`](#parameter-schema) and [`style`](#parameter-style) can describe the structure and syntax of the parameter."), + cite(V31, "Fixed Fields for use with `schema`")) } // headerObject is the Header Object. func headerObject() Object { - c := sectioned("Header Object") + cite := sectioned("Header Object") return Object{ Kind: Header, Name: "Header Object", Extensible: true, Referenceable: Always(), Fields: []Field{ - field("description", String, c(V30, "A brief description of the header.")), - field("required", Boolean, c(V30, "Determines whether this header is mandatory.")), - field("deprecated", Boolean, c(V30, "Specifies that the header is deprecated and SHOULD be transitioned out of usage.")), - field("style", String, c(V30, "Describes how the header value will be serialized.")).admits(val("simple")), - field("explode", Boolean, c(V30, "When this is true, header values of type `array` or `object` generate a single header")), - objectOf("schema", Schema, c(V30, "The schema defining the type used for the header.")), - field("example", AnyShapeUnchecked, c(V30, "Example of the header's potential value; see")), - mapOf("examples", Example, c(V30, "Examples of the header's potential value; see")), - mapOf("content", MediaType, c(V30, "A map containing the representations for the header.")). - keyed(MediaTypeKey, c(V30, "The key is the media type and the value describes it.")), + field("description", String, cite(V30, "A brief description of the header.")), + field("required", Boolean, cite(V30, "Determines whether this header is mandatory.")), + field("deprecated", Boolean, cite(V30, "Specifies that the header is deprecated and SHOULD be transitioned out of usage.")), + field("style", String, cite(V30, "Describes how the header value will be serialized.")).admits(val("simple")), + field("explode", Boolean, cite(V30, "When this is true, header values of type `array` or `object` generate a single header")), + objectOf("schema", Schema, cite(V30, "The schema defining the type used for the header.")), + field("example", AnyShapeUnchecked, cite(V30, "Example of the header's potential value; see")), + mapOf("examples", Example, cite(V30, "Examples of the header's potential value; see")), + mapOf("content", MediaType, cite(V30, "A map containing the representations for the header.")). + keyed(MediaTypeKey, cite(V30, "The key is the media type and the value describes it.")), }, Rules: []Rule{ exclusive(Always(), fields("schema", "content"), - c(V30, "including determining its serialization strategy based on whether `schema` or `content` is present")), + cite(V30, "including determining its serialization strategy based on whether `schema` or `content` is present")), exclusive(Always(), fields("example", "examples"), - c(V30, "The `example` and `examples` fields are mutually exclusive")), - count(Always(), Must, "content", 1, c(V30, "The map MUST only contain one entry.")), + cite(V30, "The `example` and `examples` fields are mutually exclusive")), + count(Always(), Must, "content", 1, cite(V30, "The map MUST only contain one entry.")), // Each is a key the Header Object does not define, which the engine // reports as an unknown key where it is written (walker.unknown) and the // annotation census keeps verbatim, so the rule draws no second finding. forbiddenWhen(Always(), fields("name", "in"), nil, - c(V30, "`name` MUST NOT be specified, it is given in the corresponding `headers` map.")).owned(ownerAnnotation), + cite(V30, "`name` MUST NOT be specified, it is given in the corresponding `headers` map.")).owned(ownerAnnotation), forbiddenWhen(Through(V31), fields("allowEmptyValue", "allowReserved"), nil, - c(V30, "This means that `allowEmptyValue` and `allowReserved` MUST NOT be used")).owned(ownerAnnotation), + cite(V30, "This means that `allowEmptyValue` and `allowReserved` MUST NOT be used")).owned(ownerAnnotation), forbiddenWhen(From(V32), fields("allowEmptyValue"), nil, - c(V32, "This means that `allowEmptyValue` MUST NOT be used")).owned(ownerAnnotation), - besideContent(c, "header", "style", when(writing("content"))), - besideContent(c, "header", "explode", when(writing("content"))), + cite(V32, "This means that `allowEmptyValue` MUST NOT be used")).owned(ownerAnnotation), + besideContent(cite, "header", "style", when(writing("content"))), + besideContent(cite, "header", "explode", when(writing("content"))), }, } } // requestBodyObject is the Request Body Object. func requestBodyObject() Object { - c := sectioned("Request Body Object") + cite := sectioned("Request Body Object") return Object{ Kind: RequestBody, Name: "Request Body Object", Extensible: true, Referenceable: Always(), Fields: []Field{ - field("description", String, c(V30, "A brief description of the request body.")), - mapOf("content", MediaType, c(V30, "**REQUIRED**. The content of the request body.")).required(Always()). - keyed(MediaTypeKey, c(V30, "The key is a media type or media type range")), - field("required", Boolean, c(V30, "Determines if the request body is required in the request.")), + field("description", String, cite(V30, "A brief description of the request body.")), + mapOf("content", MediaType, cite(V30, "**REQUIRED**. The content of the request body.")).required(Always()). + keyed(MediaTypeKey, cite(V30, "The key is a media type or media type range")), + field("required", Boolean, cite(V30, "Determines if the request body is required in the request.")), }, Rules: []Rule{ count(From(V31), Should, "content", 0, - c(V31, "The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined.")). + cite(V31, "The map SHOULD have at least one entry; if it does not, the behavior is implementation-defined.")). owned(ownerLoad), }, } @@ -171,48 +171,48 @@ func requestBodyObject() Object { // mediaTypeObject is the Media Type Object. func mediaTypeObject() Object { - c := sectioned("Media Type Object") + cite := sectioned("Media Type Object") return Object{ Kind: MediaType, Name: "Media Type Object", Extensible: true, Referenceable: From(V32), Fields: []Field{ // The 3.2.0 text lists no description here; the published 3.2 schema // does, and the compiler has always read it from that schema. - field("description", String, c(V32, "Each Media Type Object describes content structured in accordance with the media type identified by its key.")). + field("description", String, cite(V32, "Each Media Type Object describes content structured in accordance with the media type identified by its key.")). during(From(V32)), - objectOf("schema", Schema, c(V30, "The schema defining the content of the request, response, parameter, or header.")), - objectOf("itemSchema", Schema, c(V32, "A schema describing each item within a [sequential media type]")).during(From(V32)), - field("example", AnyShapeUnchecked, c(V30, "Example of the media type; see")), - mapOf("examples", Example, c(V30, "Examples of the media type; see")), - mapOf("encoding", Encoding, c(V30, "A map between a property name and its encoding information")), - listOf("prefixEncoding", Encoding, c(V32, "An array of positional encoding information")).during(From(V32)), - objectOf("itemEncoding", Encoding, c(V32, "A single Encoding Object that provides encoding information for multiple array items")). + objectOf("schema", Schema, cite(V30, "The schema defining the content of the request, response, parameter, or header.")), + objectOf("itemSchema", Schema, cite(V32, "A schema describing each item within a [sequential media type]")).during(From(V32)), + field("example", AnyShapeUnchecked, cite(V30, "Example of the media type; see")), + mapOf("examples", Example, cite(V30, "Examples of the media type; see")), + mapOf("encoding", Encoding, cite(V30, "A map between a property name and its encoding information")), + listOf("prefixEncoding", Encoding, cite(V32, "An array of positional encoding information")).during(From(V32)), + objectOf("itemEncoding", Encoding, cite(V32, "A single Encoding Object that provides encoding information for multiple array items")). during(From(V32)), }, - Rules: append(mediaTypeRules(c), encodingExclusions(c, V32, + Rules: append(mediaTypeRules(cite), encodingExclusions(cite, V32, "This field MUST NOT be present if `prefixEncoding` or `itemEncoding` are present.")...), } } // mediaTypeRules are the rules of the Media Type Object beside its encodings' // exclusions. -func mediaTypeRules(c func(Minor, string) Cite) []Rule { +func mediaTypeRules(cite func(Minor, string) Cite) []Rule { // What an encoding is written for, the specification says it SHALL only // apply to, so one written elsewhere has no effect, a warning. applies := code(Always(), "encoding-applies", "", - c(V30, "The `encoding` field SHALL only apply to [Request Body Objects](#request-body-object), and only when the media type is `multipart` or `application/x-www-form-urlencoded`."), - c(V32, "The `encoding` field SHALL only apply when the media type is `multipart` or `application/x-www-form-urlencoded`."), - c(V32, "The `prefixEncoding` field SHALL only apply when the media type is `multipart`.")) + cite(V30, "The `encoding` field SHALL only apply to [Request Body Objects](#request-body-object), and only when the media type is `multipart` or `application/x-www-form-urlencoded`."), + cite(V32, "The `encoding` field SHALL only apply when the media type is `multipart` or `application/x-www-form-urlencoded`."), + cite(V32, "The `prefixEncoding` field SHALL only apply when the media type is `multipart`.")) applies.Level = Should // Whether an encoding key names a property needs the body's schema read // through its references and compositions, which the operation package's // part walk does; a warning, as 3.2 gives such an entry no effect. keys := code(Always(), "encoding-keys", ownerOperation, - c(V30, "The key, being the property name, MUST exist in the schema as a property."), + cite(V30, "The key, being the property name, MUST exist in the schema as a property."), sectioned("Encoding By Name")(V32, "each key under the field MUST exist as a property")) keys.Level = Should return []Rule{ exclusive(Always(), fields("example", "examples"), - c(V30, "The `example` and `examples` fields are mutually exclusive")), + cite(V30, "The `example` and `examples` fields are mutually exclusive")), applies, keys, } @@ -220,58 +220,58 @@ func mediaTypeRules(c func(Minor, string) Cite) []Rule { // encodingExclusions are the rules that keep an object's encoding by name from // being written beside its encoding by position. -func encodingExclusions(c func(Minor, string) Cite, minor Minor, sentence string) []Rule { +func encodingExclusions(cite func(Minor, string) Cite, minor Minor, sentence string) []Rule { return []Rule{ - exclusive(From(minor), fields("encoding", "prefixEncoding"), c(minor, sentence)), - exclusive(From(minor), fields("encoding", "itemEncoding"), c(minor, sentence)), + exclusive(From(minor), fields("encoding", "prefixEncoding"), cite(minor, sentence)), + exclusive(From(minor), fields("encoding", "itemEncoding"), cite(minor, sentence)), } } // encodingObject is the Encoding Object. func encodingObject() Object { - c := sectioned("Encoding Object") + cite := sectioned("Encoding Object") query := []Value{val("form"), val("spaceDelimited"), val("pipeDelimited"), val("deepObject")} return Object{ Kind: Encoding, Name: "Encoding Object", Extensible: true, Fields: []Field{ - field("contentType", String, c(V30, "The `Content-Type` for encoding a specific property."), - c(V30, "The value is a comma-separated list, each element of which is either a specific media type")). + field("contentType", String, cite(V30, "The `Content-Type` for encoding a specific property."), + cite(V30, "The value is a comma-separated list, each element of which is either a specific media type")). formatted(MediaRanges).nonEmpty(Always()), - mapOf("headers", Header, c(V30, "A map allowing additional information to be provided as headers.")). - keyed(FieldName, c(V30, "A map allowing additional information to be provided as headers.")). + mapOf("headers", Header, cite(V30, "A map allowing additional information to be provided as headers.")). + keyed(FieldName, cite(V30, "A map allowing additional information to be provided as headers.")). within("multipart/*", Always(), - c(V30, "This field SHALL be ignored if the request body media type is not a `multipart`."), - c(V32, "This field SHALL be ignored if the media type is not a `multipart`.")), - mapOf("encoding", Encoding, c(V32, "Applies nested Encoding Objects in the same manner as the")).during(From(V32)), - listOf("prefixEncoding", Encoding, c(V32, "Applies nested Encoding Objects in the same manner as the")).during(From(V32)), - objectOf("itemEncoding", Encoding, c(V32, "Applies nested Encoding Objects in the same manner as the")).during(From(V32)), - arranging(field("style", String, c(V30, "Describes how a specific property value will be serialized depending on its type.")). - admits(query...), c), - arranging(field("explode", Boolean, c(V30, "When this is true, property values of type `array` or `object` generate separate parameters")), c), - arranging(field("allowReserved", Boolean, c(V30, "When this is true, parameter values are serialized using reserved expansion")), c), + cite(V30, "This field SHALL be ignored if the request body media type is not a `multipart`."), + cite(V32, "This field SHALL be ignored if the media type is not a `multipart`.")), + mapOf("encoding", Encoding, cite(V32, "Applies nested Encoding Objects in the same manner as the")).during(From(V32)), + listOf("prefixEncoding", Encoding, cite(V32, "Applies nested Encoding Objects in the same manner as the")).during(From(V32)), + objectOf("itemEncoding", Encoding, cite(V32, "Applies nested Encoding Objects in the same manner as the")).during(From(V32)), + arranging(field("style", String, cite(V30, "Describes how a specific property value will be serialized depending on its type.")). + admits(query...), cite), + arranging(field("explode", Boolean, cite(V30, "When this is true, property values of type `array` or `object` generate separate parameters")), cite), + arranging(field("allowReserved", Boolean, cite(V30, "When this is true, parameter values are serialized using reserved expansion")), cite), }, // The nested fields apply "in the same manner" as the Media Type Object's, // whose text bars writing them together: a reading by analogy, so a // warning. - Rules: append(softened(encodingExclusions(c, V32, "Applies nested Encoding Objects in the same manner as the")), + Rules: append(softened(encodingExclusions(cite, V32, "Applies nested Encoding Objects in the same manner as the")), reserved(Always(), "headers", nil, fields("Content-Type"), - c(V30, "`Content-Type` is described separately and SHALL be ignored in this section."))), - Defaults: contentTypeDefaults(c), + cite(V30, "`Content-Type` is described separately and SHALL be ignored in this section."))), + Defaults: contentTypeDefaults(cite), } } // arranging returns field, one of the Encoding Object's RFC6570-style fields, // with the media types under which it takes effect, replacing the contentType: // a form body at every minor, and a multipart/form-data body from 3.1. -func arranging(field Field, c func(Minor, string) Cite) Field { +func arranging(field Field, cite func(Minor, string) Cite) Field { return field. within("application/x-www-form-urlencoded", Always(), - c(V30, "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`."), - c(V30, "The value of `contentType`, whether it is explicitly defined or has the default value, is to be ignored"), - c(V31, "If a value is explicitly defined, then the value of [`contentType`](#encoding-content-type) (implicit or explicit) SHALL be ignored.")). + cite(V30, "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`."), + cite(V30, "The value of `contentType`, whether it is explicitly defined or has the default value, is to be ignored"), + cite(V31, "If a value is explicitly defined, then the value of [`contentType`](#encoding-content-type) (implicit or explicit) SHALL be ignored.")). within("multipart/form-data", From(V31), - c(V31, "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`."), - c(V32, "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`.")) + cite(V31, "This field SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`."), + cite(V32, "This field SHALL be ignored if the media type is not `application/x-www-form-urlencoded` or `multipart/form-data`.")) } // contentTypeDefaults are the contentType a part takes where its Encoding @@ -281,7 +281,7 @@ func arranging(field Field, c func(Minor, string) Cite) Field { // inside the array an encoding applies to, whose items' row is read instead. // Raw bytes, which every minor's lowering reads a string of format binary as, // take the row for raw binary. -func contentTypeDefaults(c func(Minor, string) Cite) []Default { +func contentTypeDefaults(cite func(Minor, string) Cite) []Default { const ( table = "The default values for `contentType` are as follows" octet = "application/octet-stream" @@ -290,19 +290,19 @@ func contentTypeDefaults(c func(Minor, string) Cite) []Default { noEffect := sectioned("Considerations for File Uploads")(V31, "the `format` keyword has no effect on the content-encoding of the schema in OAS 3.1") return []Default{ - contentTypeDefault(DefaultUntyped, octet, From(V31), c(V31, table)), - contentTypeDefault(DefaultRawBinary, octet, Always(), c(V30, table), + contentTypeDefault(DefaultUntyped, octet, From(V31), cite(V31, table)), + contentTypeDefault(DefaultRawBinary, octet, Always(), cite(V30, table), sectioned("Example: Basic Multipart Form")(V31, "default for string with binary format is `application/octet-stream`"), sectioned("Working with Binary Data")(V32, "**raw binary** is used where unencoded binary data is allowed")), - contentTypeDefault(DefaultByteFormat, octet, Only(V30), c(V30, table)), - contentTypeDefault(DefaultByteFormat, text, From(V31), noEffect, c(V32, table)), - contentTypeDefault(DefaultEncodedByteFormat, octet, Always(), c(V30, table), c(V31, table)), - contentTypeDefault(DefaultContentEncoded, text, Only(V30), c(V30, table)), - contentTypeDefault(DefaultContentEncoded, octet, From(V31), c(V31, table)), - contentTypeDefault(DefaultString, text, Always(), c(V30, table)), - contentTypeDefault(DefaultScalar, text, Always(), c(V30, table)), - contentTypeDefault(DefaultObject, "application/json", Always(), c(V30, table)), + contentTypeDefault(DefaultByteFormat, octet, Only(V30), cite(V30, table)), + contentTypeDefault(DefaultByteFormat, text, From(V31), noEffect, cite(V32, table)), + contentTypeDefault(DefaultEncodedByteFormat, octet, Always(), cite(V30, table), cite(V31, table)), + contentTypeDefault(DefaultContentEncoded, text, Only(V30), cite(V30, table)), + contentTypeDefault(DefaultContentEncoded, octet, From(V31), cite(V31, table)), + contentTypeDefault(DefaultString, text, Always(), cite(V30, table)), + contentTypeDefault(DefaultScalar, text, Always(), cite(V30, table)), + contentTypeDefault(DefaultObject, "application/json", Always(), cite(V30, table)), contentTypeDefault(DefaultNestedArray, "application/json", From(V32), - c(V32, "Therefore the `array` row in this table applies only to array values inside of a top-level array when encoding by name.")), + cite(V32, "Therefore the `array` row in this table applies only to array values inside of a top-level array when encoding by name.")), } } diff --git a/compilers/openapi/internal/specrules/table_paths.go b/compilers/openapi/internal/specrules/table_paths.go index c0ba2e854..a9822eb1d 100644 --- a/compilers/openapi/internal/specrules/table_paths.go +++ b/compilers/openapi/internal/specrules/table_paths.go @@ -12,17 +12,17 @@ func pathObjects() []Object { // pathsObject is the Paths Object. func pathsObject() Object { - c := sectioned("Paths Object") + cite := sectioned("Paths Object") t := sectioned("Path Templating") return Object{ Kind: Paths, Name: "Paths Object", Extensible: true, Patterned: []Pattern{ - pattern("/{path}", Nested, PathItem, c(V30, "A relative path to an individual endpoint.")), + pattern("/{path}", Nested, PathItem, cite(V30, "A relative path to an individual endpoint.")), }, Rules: []Rule{ - code(Always(), "path-keys", ownerOperation, c(V30, "The field name MUST begin with a forward slash (`/`).")), + code(Always(), "path-keys", ownerOperation, cite(V30, "The field name MUST begin with a forward slash (`/`).")), code(Always(), "path-templates-distinct", "", - c(V30, "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical.")), + cite(V30, "Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical.")), code(Always(), "path-template-parameters", "", t(V30, "Each template expression in the path MUST correspond to a path parameter that is included in the")), }, @@ -31,71 +31,71 @@ func pathsObject() Object { // pathItemObject is the Path Item Object. func pathItemObject() Object { - c := sectioned("Path Item Object") + cite := sectioned("Path Item Object") head := []Field{ - field("$ref", String, c(V30, "Allows for a referenced definition of this path item.")).formatted(URI), - field("summary", String, c(V30, "An optional string summary, intended to apply to all operations in this path.")), - field("description", String, c(V30, "An optional string description, intended to apply to all operations in this path.")), + field("$ref", String, cite(V30, "Allows for a referenced definition of this path item.")).formatted(URI), + field("summary", String, cite(V30, "An optional string summary, intended to apply to all operations in this path.")), + field("description", String, cite(V30, "An optional string description, intended to apply to all operations in this path.")), } methods := []string{"get", "put", "post", "delete", "options", "head", "patch", "trace"} operations := make([]Field, len(methods)) - for i, m := range methods { - operations[i] = objectOf(m, Operation, c(V30, "A definition of a "+upper(m)+" operation on this path.")) + for i, method := range methods { + operations[i] = objectOf(method, Operation, cite(V30, "A definition of a "+upper(method)+" operation on this path.")) } tail := []Field{ - objectOf("query", Operation, c(V32, "A definition of a QUERY operation, as defined in the most recent IETF draft")). + objectOf("query", Operation, cite(V32, "A definition of a QUERY operation, as defined in the most recent IETF draft")). during(From(V32)), - mapOf("additionalOperations", Operation, c(V32, "A map of additional operations on this path.")).during(From(V32)), - listOf("servers", Server, c(V30, "An alternative `servers` array to service all operations in this path.")), - listOf("parameters", Parameter, c(V30, "A list of parameters that are applicable for all the operations described under this path.")), + mapOf("additionalOperations", Operation, cite(V32, "A map of additional operations on this path.")).during(From(V32)), + listOf("servers", Server, cite(V30, "An alternative `servers` array to service all operations in this path.")), + listOf("parameters", Parameter, cite(V30, "A list of parameters that are applicable for all the operations described under this path.")), } return Object{ Kind: PathItem, Name: "Path Item Object", Extensible: true, Fields: slices.Concat(head, operations, tail), Rules: []Rule{ - code(Always(), "parameters-unique", ownerLoad, c(V30, "The list MUST NOT include duplicated parameters.")), + code(Always(), "parameters-unique", ownerLoad, cite(V30, "The list MUST NOT include duplicated parameters.")), uniqueNames(From(V32), "servers", sectioned("Server Object")(V32, "An optional unique string to refer to the host designated by the URL.")). owned(ownerLoad), code(From(V32), "additional-operations-methods", "", - c(V32, "This map MUST NOT contain any entry for the methods that can be defined by other fixed fields")), + cite(V32, "This map MUST NOT contain any entry for the methods that can be defined by other fixed fields")), }, } } // upper spells an HTTP method in capitals. func upper(method string) string { - b := []byte(method) - for i, ch := range b { + letters := []byte(method) + for i, ch := range letters { if ch >= 'a' && ch <= 'z' { - b[i] = ch - 'a' + 'A' + letters[i] = ch - 'a' + 'A' } } - return string(b) + return string(letters) } // operationObject is the Operation Object. func operationObject() Object { - c := sectioned("Operation Object") + cite := sectioned("Operation Object") return Object{ Kind: Operation, Name: "Operation Object", Extensible: true, Fields: []Field{ - field("tags", StringList, c(V30, "A list of tags for API documentation control.")), - field("summary", String, c(V30, "A short summary of what the operation does.")), - field("description", String, c(V30, "A verbose explanation of the operation behavior.")), - objectOf("externalDocs", ExternalDocs, c(V30, "Additional external documentation for this operation.")), - field("operationId", String, c(V30, "Unique string used to identify the operation.")), - listOf("parameters", Parameter, c(V30, "A list of parameters that are applicable for this operation.")), - objectOf("requestBody", RequestBody, c(V30, "The request body applicable for this operation.")), - objectOf("responses", Responses, c(V30, "**REQUIRED**. The list of possible responses as they are returned from executing this operation.")). + field("tags", StringList, cite(V30, "A list of tags for API documentation control.")), + field("summary", String, cite(V30, "A short summary of what the operation does.")), + field("description", String, cite(V30, "A verbose explanation of the operation behavior.")), + objectOf("externalDocs", ExternalDocs, cite(V30, "Additional external documentation for this operation.")), + field("operationId", String, cite(V30, "Unique string used to identify the operation.")), + listOf("parameters", Parameter, cite(V30, "A list of parameters that are applicable for this operation.")), + objectOf("requestBody", RequestBody, cite(V30, "The request body applicable for this operation.")), + objectOf("responses", Responses, cite(V30, "**REQUIRED**. The list of possible responses as they are returned from executing this operation.")). required(Only(V30)), - mapOf("callbacks", Callback, c(V30, "A map of possible out-of band callbacks related to the parent operation.")), - field("deprecated", Boolean, c(V30, "Declares this operation to be deprecated.")), + mapOf("callbacks", Callback, cite(V30, "A map of possible out-of band callbacks related to the parent operation.")), + field("deprecated", Boolean, cite(V30, "Declares this operation to be deprecated.")), listOf("security", SecurityRequirement, - c(V30, "A declaration of which security mechanisms can be used for this operation.")), - listOf("servers", Server, c(V30, "An alternative `servers` array to service this operation.")), + cite(V30, "A declaration of which security mechanisms can be used for this operation.")), + listOf("servers", Server, cite(V30, "An alternative `servers` array to service this operation.")), }, Rules: []Rule{ - code(Always(), "parameters-unique", ownerLoad, c(V30, "The list MUST NOT include duplicated parameters.")), + code(Always(), "parameters-unique", ownerLoad, cite(V30, "The list MUST NOT include duplicated parameters.")), uniqueNames(From(V32), "servers", sectioned("Server Object")(V32, "An optional unique string to refer to the host designated by the URL.")). owned(ownerLoad), @@ -105,11 +105,11 @@ func operationObject() Object { // callbackObject is the Callback Object. func callbackObject() Object { - c := sectioned("Callback Object") + cite := sectioned("Callback Object") return Object{ Kind: Callback, Name: "Callback Object", Extensible: true, Referenceable: Always(), Patterned: []Pattern{ - pattern("{expression}", Nested, PathItem, c(V30, "A Path Item Object used to define a callback request and expected responses."), + pattern("{expression}", Nested, PathItem, cite(V30, "A Path Item Object used to define a callback request and expected responses."), // 3.0 closes the Runtime Expressions examples with this, under a heading of their own. sectioned("Examples")(V30, "Expressions can be embedded into string values by surrounding the expression with `{}` curly braces."), sectioned("Key Expression")(V30, "The key that identifies the [Path Item Object](#path-item-object) is a [runtime expression](#runtime-expressions)")). diff --git a/compilers/openapi/internal/specrules/table_responses.go b/compilers/openapi/internal/specrules/table_responses.go index 98f67916f..661303a53 100644 --- a/compilers/openapi/internal/specrules/table_responses.go +++ b/compilers/openapi/internal/specrules/table_responses.go @@ -10,94 +10,94 @@ func responseObjects() []Object { // responsesObject is the Responses Object. func responsesObject() Object { - c := sectioned("Responses Object") + cite := sectioned("Responses Object") return Object{ Kind: Responses, Name: "Responses Object", Extensible: true, Fields: []Field{ - objectOf("default", Response, c(V30, "The documentation of responses other than the ones declared for specific HTTP response codes.")), + objectOf("default", Response, cite(V30, "The documentation of responses other than the ones declared for specific HTTP response codes.")), }, Patterned: []Pattern{ pattern("[HTTP Status Code]", Nested, Response, - c(V30, "but only one property per code, to describe the expected response for that HTTP status code.")), + cite(V30, "but only one property per code, to describe the expected response for that HTTP status code.")), }, Rules: []Rule{ - count(Always(), Must, "", 0, c(V30, "The Responses Object MUST contain at least one response code")), + count(Always(), Must, "", 0, cite(V30, "The Responses Object MUST contain at least one response code")), code(Always(), "status-keys", ownerOperation, - c(V30, "Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`.")), + cite(V30, "Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`.")), }, } } // responseObject is the Response Object. func responseObject() Object { - c := sectioned("Response Object") + cite := sectioned("Response Object") return Object{ Kind: Response, Name: "Response Object", Extensible: true, Referenceable: Always(), Fields: []Field{ - field("summary", String, c(V32, "A short summary of the meaning of the response.")).during(From(V32)), - field("description", String, c(V30, "**REQUIRED**. A description of the response.")).required(Through(V31)), - mapOf("headers", Header, c(V30, "Maps a header name to its definition.")). - keyed(FieldName, c(V30, "[RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive."), - c(V32, "[RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.1) states header names are case-insensitive.")), - mapOf("content", MediaType, c(V30, "A map containing descriptions of potential response payloads.")). - keyed(MediaTypeKey, c(V30, "The key is a media type or media type range")), - mapOf("links", Link, c(V30, "A map of operations links that can be followed from the response.")). - keyed(ComponentName, c(V30, "following the naming constraints of the names for")), + field("summary", String, cite(V32, "A short summary of the meaning of the response.")).during(From(V32)), + field("description", String, cite(V30, "**REQUIRED**. A description of the response.")).required(Through(V31)), + mapOf("headers", Header, cite(V30, "Maps a header name to its definition.")). + keyed(FieldName, cite(V30, "[RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive."), + cite(V32, "[RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.1) states header names are case-insensitive.")), + mapOf("content", MediaType, cite(V30, "A map containing descriptions of potential response payloads.")). + keyed(MediaTypeKey, cite(V30, "The key is a media type or media type range")), + mapOf("links", Link, cite(V30, "A map of operations links that can be followed from the response.")). + keyed(ComponentName, cite(V30, "following the naming constraints of the names for")), }, Rules: []Rule{ reserved(Always(), "headers", nil, fields("Content-Type"), - c(V30, "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored.")), + cite(V30, "If a response header is defined with the name `\"Content-Type\"`, it SHALL be ignored.")), }, } } // exampleObject is the Example Object. func exampleObject() Object { - c := sectioned("Example Object") + cite := sectioned("Example Object") return Object{ Kind: Example, Name: "Example Object", Extensible: true, Referenceable: Always(), Fields: []Field{ - field("summary", String, c(V30, "Short description for the example.")), - field("description", String, c(V30, "Long description for the example.")), - field("dataValue", AnyShapeUnchecked, c(V32, "An example of the data structure that MUST be valid according to the relevant")). + field("summary", String, cite(V30, "Short description for the example.")), + field("description", String, cite(V30, "Long description for the example.")), + field("dataValue", AnyShapeUnchecked, cite(V32, "An example of the data structure that MUST be valid according to the relevant")). during(From(V32)), - field("serializedValue", String, c(V32, "An example of the serialized form of the value")).during(From(V32)), - field("externalValue", String, c(V30, "A URL that points to the literal example.")).formatted(URI), - field("value", AnyShapeUnchecked, c(V30, "Embedded literal example.")), + field("serializedValue", String, cite(V32, "An example of the serialized form of the value")).during(From(V32)), + field("externalValue", String, cite(V30, "A URL that points to the literal example.")).formatted(URI), + field("value", AnyShapeUnchecked, cite(V30, "Embedded literal example.")), }, - Rules: exampleRules(c), + Rules: exampleRules(cite), } } // exampleRules keep the Example Object from stating its value twice. -func exampleRules(c func(Minor, string) Cite) []Rule { +func exampleRules(cite func(Minor, string) Cite) []Rule { return []Rule{ exclusive(Always(), fields("value", "externalValue"), - c(V30, "The `value` field and `externalValue` field are mutually exclusive.")), - exclusive(From(V32), fields("dataValue", "value"), c(V32, "If this field is present, `value` MUST be absent.")), + cite(V30, "The `value` field and `externalValue` field are mutually exclusive.")), + exclusive(From(V32), fields("dataValue", "value"), cite(V32, "If this field is present, `value` MUST be absent.")), exclusive(From(V32), fields("serializedValue", "value"), - c(V32, "If this field is present, `value`, and `externalValue` MUST be absent.")), + cite(V32, "If this field is present, `value`, and `externalValue` MUST be absent.")), exclusive(From(V32), fields("serializedValue", "externalValue"), - c(V32, "If this field is present, `value`, and `externalValue` MUST be absent.")), + cite(V32, "If this field is present, `value`, and `externalValue` MUST be absent.")), } } // linkObject is the Link Object. func linkObject() Object { - c := sectioned("Link Object") + cite := sectioned("Link Object") return Object{ Kind: Link, Name: "Link Object", Extensible: true, Referenceable: Always(), Fields: []Field{ - field("operationRef", String, c(V30, "A URI reference to an OAS operation.")).formatted(URI), - field("operationId", String, c(V30, "The name of an _existing_, resolvable OAS operation")), - field("parameters", RawMap, c(V30, "A map representing parameters to pass to an operation")), - field("requestBody", AnyShapeUnchecked, c(V30, "A literal value or [{expression}](#runtime-expressions) to use as a request body")), - field("description", String, c(V30, "A description of the link.")), - objectOf("server", Server, c(V30, "A server object to be used by the target operation.")), + field("operationRef", String, cite(V30, "A URI reference to an OAS operation.")).formatted(URI), + field("operationId", String, cite(V30, "The name of an _existing_, resolvable OAS operation")), + field("parameters", RawMap, cite(V30, "A map representing parameters to pass to an operation")), + field("requestBody", AnyShapeUnchecked, cite(V30, "A literal value or [{expression}](#runtime-expressions) to use as a request body")), + field("description", String, cite(V30, "A description of the link.")), + objectOf("server", Server, cite(V30, "A server object to be used by the target operation.")), }, Rules: []Rule{ exactlyOne(Always(), fields("operationRef", "operationId"), - c(V30, "A linked operation MUST be identified using either an `operationRef` or `operationId`.")), + cite(V30, "A linked operation MUST be identified using either an `operationRef` or `operationId`.")), }, } } diff --git a/compilers/openapi/internal/specrules/table_schema.go b/compilers/openapi/internal/specrules/table_schema.go index f395f438c..cb559c099 100644 --- a/compilers/openapi/internal/specrules/table_schema.go +++ b/compilers/openapi/internal/specrules/table_schema.go @@ -18,27 +18,27 @@ func schemaObjects() []Object { // held to 3.0's keywords as written, the $ref among them, and each is warned of // as a later minor's construct (RefSiblings, GitHub #871). func schemaObject() Object { - c := sectioned("Schema Object") - nullable := c(V30, "This keyword only takes effect if `type` is explicitly defined within the same Schema Object.") + cite := sectioned("Schema Object") + nullable := cite(V30, "This keyword only takes effect if `type` is explicitly defined within the same Schema Object.") // A nullable the specification gives no effect is written to no purpose, // which its version still reads, so a finding is a warning. applies := code(Only(V30), "nullable-applies", "", nullable) applies.Level = Should own := []Field{ field("nullable", Boolean, nullable).during(Only(V30)), - objectOf("discriminator", Discriminator, c(V30, "Adds support for polymorphism.")), - objectOf("xml", XML, c(V30, "This MAY be used only on property schemas.")), - objectOf("externalDocs", ExternalDocs, c(V30, "Additional external documentation for this schema.")), - field("example", AnyShapeUnchecked, c(V30, "A free-form field to include an example of an instance for this schema.")), + objectOf("discriminator", Discriminator, cite(V30, "Adds support for polymorphism.")), + objectOf("xml", XML, cite(V30, "This MAY be used only on property schemas.")), + objectOf("externalDocs", ExternalDocs, cite(V30, "Additional external documentation for this schema.")), + field("example", AnyShapeUnchecked, cite(V30, "A free-form field to include an example of an instance for this schema.")), } return Object{ Kind: Schema, Name: "Schema Object", Extensible: true, Boolean: From(V31), RefSiblings: From(V31), Fields: slices.Concat(own, schemaKeywords()), Rules: append([]Rule{ ruleRequiringFieldValue(Only(V30), "writeOnly", "false", when(term("readOnly", "true")), - c(V30, "A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`.")), + cite(V30, "A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`.")), requiredWhen(Only(V30), "items", when(term("type", "array")), - c(V30, "`items` MUST be present if `type` is `\"array\"`.")).owned(ownerSchema), + cite(V30, "`items` MUST be present if `type` is `\"array\"`.")).owned(ownerSchema), applies, }, keywordRules()...), } @@ -46,15 +46,15 @@ func schemaObject() Object { // discriminatorObject is the Discriminator Object. func discriminatorObject() Object { - c := sectioned("Discriminator Object") + cite := sectioned("Discriminator Object") return Object{ Kind: Discriminator, Name: "Discriminator Object", Extensible: true, Fields: []Field{ - field("propertyName", String, c(V30, "**REQUIRED**. The name of the property in the payload that will hold the discriminating value."), - c(V32, "**REQUIRED**. The name of the discriminating property in the payload that will hold the discriminating value.")). + field("propertyName", String, cite(V30, "**REQUIRED**. The name of the property in the payload that will hold the discriminating value."), + cite(V32, "**REQUIRED**. The name of the discriminating property in the payload that will hold the discriminating value.")). required(Always()), - field("mapping", StringMap, c(V30, "An object to hold mappings between payload values and schema names or URI references.")), - field("defaultMapping", String, c(V32, "The schema name or URI reference to a schema that is expected to validate the structure of the model")). + field("mapping", StringMap, cite(V30, "An object to hold mappings between payload values and schema names or URI references.")), + field("defaultMapping", String, cite(V32, "The schema name or URI reference to a schema that is expected to validate the structure of the model")). during(From(V32)), }, } @@ -62,24 +62,24 @@ func discriminatorObject() Object { // xmlObject is the XML Object. func xmlObject() Object { - c := sectioned("XML Object") + cite := sectioned("XML Object") nodeTypes := vals("element", "attribute", "text", "cdata", "none") present := "If `nodeType` is present, this field MUST NOT be present." return Object{ Kind: XML, Name: "XML Object", Extensible: true, Fields: []Field{ - field("nodeType", String, c(V32, "One of `element`, `attribute`, `text`, `cdata`, or `none`")). + field("nodeType", String, cite(V32, "One of `element`, `attribute`, `text`, `cdata`, or `none`")). during(From(V32)).admits(nodeTypes...), - field("name", String, c(V30, "Replaces the name of the element/attribute used for the described schema property."), - c(V32, "Sets the name of the element/attribute corresponding to the schema")), - field("namespace", String, c(V30, "Value MUST be in the form of a non-relative URI.")).formatted(AbsoluteURI), - field("prefix", String, c(V30, "The prefix to be used for the [name](#xml-name).")), - field("attribute", Boolean, c(V30, "Declares whether the property definition translates to an attribute instead of an element.")), - field("wrapped", Boolean, c(V30, "MAY be used only for an array definition.")), + field("name", String, cite(V30, "Replaces the name of the element/attribute used for the described schema property."), + cite(V32, "Sets the name of the element/attribute corresponding to the schema")), + field("namespace", String, cite(V30, "Value MUST be in the form of a non-relative URI.")).formatted(AbsoluteURI), + field("prefix", String, cite(V30, "The prefix to be used for the [name](#xml-name).")), + field("attribute", Boolean, cite(V30, "Declares whether the property definition translates to an attribute instead of an element.")), + field("wrapped", Boolean, cite(V30, "MAY be used only for an array definition.")), }, Rules: []Rule{ - exclusive(From(V32), fields("nodeType", "attribute"), c(V32, present)), - exclusive(From(V32), fields("nodeType", "wrapped"), c(V32, present)), + exclusive(From(V32), fields("nodeType", "attribute"), cite(V32, present)), + exclusive(From(V32), fields("nodeType", "wrapped"), cite(V32, present)), }, } } diff --git a/compilers/openapi/internal/specrules/table_security.go b/compilers/openapi/internal/specrules/table_security.go index dd0d2e521..f3d4a314c 100644 --- a/compilers/openapi/internal/specrules/table_security.go +++ b/compilers/openapi/internal/specrules/table_security.go @@ -20,30 +20,30 @@ func securitySchemeObject() Object { // securitySchemeFields are the fields of the Security Scheme Object. func securitySchemeFields() []Field { - c := sectioned("Security Scheme Object") + cite := sectioned("Security Scheme Object") types := []Value{val("apiKey"), val("http"), valFrom("mutualTLS", V31), val("oauth2"), val("openIdConnect")} return []Field{ - field("type", String, c(V30, "**REQUIRED**. The type of the security scheme.")). + field("type", String, cite(V30, "**REQUIRED**. The type of the security scheme.")). required(Always()).ownedBy(ownerAuth).admits(types...), - field("description", String, c(V30, "A description for security scheme.")), - field("name", String, c(V30, "**REQUIRED**. The name of the header, query or cookie parameter to be used.")), - field("in", String, c(V30, "**REQUIRED**. The location of the API key.")).admits(vals("query", "header", "cookie")...), - field("scheme", String, c(V30, "**REQUIRED**. The name of the HTTP Authentication scheme to be used in the")), - field("bearerFormat", String, c(V30, "A hint to the client to identify how the bearer token is formatted.")), - objectOf("flows", OAuthFlows, c(V30, "**REQUIRED**. An object containing configuration information for the flow types supported.")), - field("openIdConnectUrl", String, c(V30, "**REQUIRED**. [Well-known URL]")).formatted(URI), - field("oauth2MetadataUrl", String, c(V32, "URL to the OAuth2 authorization server metadata")). + field("description", String, cite(V30, "A description for security scheme.")), + field("name", String, cite(V30, "**REQUIRED**. The name of the header, query or cookie parameter to be used.")), + field("in", String, cite(V30, "**REQUIRED**. The location of the API key.")).admits(vals("query", "header", "cookie")...), + field("scheme", String, cite(V30, "**REQUIRED**. The name of the HTTP Authentication scheme to be used in the")), + field("bearerFormat", String, cite(V30, "A hint to the client to identify how the bearer token is formatted.")), + objectOf("flows", OAuthFlows, cite(V30, "**REQUIRED**. An object containing configuration information for the flow types supported.")), + field("openIdConnectUrl", String, cite(V30, "**REQUIRED**. [Well-known URL]")).formatted(URI), + field("oauth2MetadataUrl", String, cite(V32, "URL to the OAuth2 authorization server metadata")). during(From(V32)).formatted(URI), - field("deprecated", Boolean, c(V32, "Declares this security scheme to be deprecated.")).during(From(V32)), + field("deprecated", Boolean, cite(V32, "Declares this security scheme to be deprecated.")).during(From(V32)), } } // securitySchemeRules are the rules of the Security Scheme Object: the fields // each type requires. func securitySchemeRules() []Rule { - c := sectioned("Security Scheme Object") + cite := sectioned("Security Scheme Object") need := func(name, kind, sentence string) Rule { - return requiredWhen(Always(), name, when(term("type", kind)), c(V30, sentence)) + return requiredWhen(Always(), name, when(term("type", kind)), cite(V30, sentence)) } return append(securitySchemeTokens(), []Rule{ need("name", "apiKey", "**REQUIRED**. The name of the header, query or cookie parameter to be used."), @@ -58,34 +58,34 @@ func securitySchemeRules() []Rule { // securitySchemeTokens are the rules that hold the names a scheme sends to the // grammars of the HTTP specifications it points to. func securitySchemeTokens() []Rule { - c := sectioned("Security Scheme Object") - p := sectioned("Parameter Object") + cite := sectioned("Security Scheme Object") + parameterCite := sectioned("Parameter Object") name := "**REQUIRED**. The name of the header, query or cookie parameter to be used." return []Rule{ syntax(Always(), "name", Token, when(term("type", "apiKey"), term("in", "header")), - c(V30, name), - p(V30, "Note that [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2) states header names are case insensitive."), - p(V32, "Note that [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.1) states header names are case-insensitive.")), + cite(V30, name), + parameterCite(V30, "Note that [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2) states header names are case insensitive."), + parameterCite(V32, "Note that [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.1) states header names are case-insensitive.")), syntax(Always(), "name", Token, when(term("type", "apiKey"), term("in", "cookie")), - c(V30, name), p(V30, "cookie - Used to pass a specific cookie value to the API.")), + cite(V30, name), parameterCite(V30, "cookie - Used to pass a specific cookie value to the API.")), syntax(Through(V31), "scheme", AuthScheme, when(term("type", "http")), - c(V30, "The name of the HTTP Authentication scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1).")), + cite(V30, "The name of the HTTP Authentication scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1).")), syntax(From(V32), "scheme", AuthScheme, when(term("type", "http")), - c(V32, "The name of the HTTP Authentication scheme to be used in the [Authorization header as defined in RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-16.4.1).")), + cite(V32, "The name of the HTTP Authentication scheme to be used in the [Authorization header as defined in RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-16.4.1).")), } } // oauthFlowsObject is the OAuth Flows Object. func oauthFlowsObject() Object { - c := sectioned("OAuth Flows Object") + cite := sectioned("OAuth Flows Object") return Object{ Kind: OAuthFlows, Name: "OAuth Flows Object", Extensible: true, Fields: []Field{ - objectOf("implicit", OAuthFlow, c(V30, "Configuration for the OAuth Implicit flow")), - objectOf("password", OAuthFlow, c(V30, "Configuration for the OAuth Resource Owner Password flow")), - objectOf("clientCredentials", OAuthFlow, c(V30, "Configuration for the OAuth Client Credentials flow.")), - objectOf("authorizationCode", OAuthFlow, c(V30, "Configuration for the OAuth Authorization Code flow.")), - objectOf("deviceAuthorization", OAuthFlow, c(V32, "Configuration for the OAuth Device Authorization flow.")). + objectOf("implicit", OAuthFlow, cite(V30, "Configuration for the OAuth Implicit flow")), + objectOf("password", OAuthFlow, cite(V30, "Configuration for the OAuth Resource Owner Password flow")), + objectOf("clientCredentials", OAuthFlow, cite(V30, "Configuration for the OAuth Client Credentials flow.")), + objectOf("authorizationCode", OAuthFlow, cite(V30, "Configuration for the OAuth Authorization Code flow.")), + objectOf("deviceAuthorization", OAuthFlow, cite(V32, "Configuration for the OAuth Device Authorization flow.")). during(From(V32)), }, } @@ -94,29 +94,29 @@ func oauthFlowsObject() Object { // oauthFlowObject is the OAuth Flow Object. The URLs a flow requires depend on // the flow, which is the key its parent holds it under. func oauthFlowObject() Object { - c := sectioned("OAuth Flow Object") + cite := sectioned("OAuth Flow Object") held := func(flows ...string) []Term { return when(term("$key", flows...)) } return Object{ Kind: OAuthFlow, Name: "OAuth Flow Object", Extensible: true, Fields: []Field{ - field("authorizationUrl", String, c(V30, "**REQUIRED**. The authorization URL to be used for this flow.")).formatted(URI), - field("deviceAuthorizationUrl", String, c(V32, "**REQUIRED**. The device authorization URL to be used for this flow.")). + field("authorizationUrl", String, cite(V30, "**REQUIRED**. The authorization URL to be used for this flow.")).formatted(URI), + field("deviceAuthorizationUrl", String, cite(V32, "**REQUIRED**. The device authorization URL to be used for this flow.")). during(From(V32)).formatted(URI), - field("tokenUrl", String, c(V30, "**REQUIRED**. The token URL to be used for this flow.")).formatted(URI), - field("refreshUrl", String, c(V30, "The URL to be used for obtaining refresh tokens.")).formatted(URI), - field("scopes", StringMap, c(V30, "**REQUIRED**. The available scopes for the OAuth2 security scheme.")). + field("tokenUrl", String, cite(V30, "**REQUIRED**. The token URL to be used for this flow.")).formatted(URI), + field("refreshUrl", String, cite(V30, "The URL to be used for obtaining refresh tokens.")).formatted(URI), + field("scopes", StringMap, cite(V30, "**REQUIRED**. The available scopes for the OAuth2 security scheme.")). required(Always()), }, Rules: []Rule{ requiredWhen(Always(), "authorizationUrl", held("implicit", "authorizationCode"), - c(V30, "**REQUIRED**. The authorization URL to be used for this flow.")), + cite(V30, "**REQUIRED**. The authorization URL to be used for this flow.")), requiredWhen(Through(V31), "tokenUrl", held("password", "clientCredentials", "authorizationCode"), - c(V30, "**REQUIRED**. The token URL to be used for this flow.")), + cite(V30, "**REQUIRED**. The token URL to be used for this flow.")), requiredWhen(From(V32), "tokenUrl", held("password", "clientCredentials", "authorizationCode", "deviceAuthorization"), - c(V32, "**REQUIRED**. The token URL to be used for this flow.")), + cite(V32, "**REQUIRED**. The token URL to be used for this flow.")), requiredWhen(From(V32), "deviceAuthorizationUrl", held("deviceAuthorization"), - c(V32, "**REQUIRED**. The device authorization URL to be used for this flow.")), + cite(V32, "**REQUIRED**. The device authorization URL to be used for this flow.")), }, } } @@ -125,15 +125,15 @@ func oauthFlowObject() Object { // pattern: each key names a scheme, each value lists scopes. From 3.2 a key // that is no component name may be a scheme's URI (SecurityRules). func securityRequirementObject() Object { - c := sectioned("Security Requirement Object") + cite := sectioned("Security Requirement Object") return Object{ Kind: SecurityRequirement, Name: "Security Requirement Object", Patterned: []Pattern{ pattern("{name}", StringList, 0, - c(V30, "Each name MUST correspond to a security scheme which is declared in the")).during(Through(V31)), + cite(V30, "Each name MUST correspond to a security scheme which is declared in the")).during(Through(V31)), pattern("{name}", StringList, 0, - c(V32, "Each name or URI MUST correspond to a security scheme as described above."), - c(V32, "Property names that are identical to a component name under the Components Object MUST be treated as a component name.")). + cite(V32, "Each name or URI MUST correspond to a security scheme as described above."), + cite(V32, "Property names that are identical to a component name under the Components Object MUST be treated as a component name.")). during(From(V32)).byURI(), }, } diff --git a/compilers/openapi/internal/specrules/types.go b/compilers/openapi/internal/specrules/types.go index 36c26bde2..6f9141726 100644 --- a/compilers/openapi/internal/specrules/types.go +++ b/compilers/openapi/internal/specrules/types.go @@ -398,11 +398,11 @@ type Object struct { Patterned []Pattern Rules []Rule Defaults []Default - // Referenceable is the minors at which a Reference Object may stand in - // the object's place. - Referenceable MinorVersionRange - // Boolean is the minors at which true or false may stand in the + // Referenceable is the minors at which a Reference Object may take the // object's place. + Referenceable MinorVersionRange + // Boolean is the minors at which true or false may take the object's + // place. Boolean MinorVersionRange // RefSiblings is the minors at which the keys a mapping writes beside a // $ref are the object's own, applied beside the reference. Before it each diff --git a/compilers/openapi/internal/specrules/types_table_test.go b/compilers/openapi/internal/specrules/types_table_test.go index 771b97ce4..59ccc1624 100644 --- a/compilers/openapi/internal/specrules/types_table_test.go +++ b/compilers/openapi/internal/specrules/types_table_test.go @@ -90,10 +90,10 @@ func TestTable_EveryRowCitesTheSpecification(t *testing.T) { "%s.%s: no citation of %s comes from a minor it holds at", object.Name, field.Name, within.MediaType) } } - for _, defaultValue := range object.Defaults { - valid(object.Name+"."+defaultValue.Field+" default", defaultValue.Cites) - assert.True(t, slices.ContainsFunc(defaultValue.Cites, func(cite specrules.Cite) bool { return defaultValue.Span.Holds(cite.Minor) }), - "%s.%s: no citation of a default comes from a minor it holds at", object.Name, defaultValue.Field) + for _, row := range object.Defaults { + valid(object.Name+"."+row.Field+" default", row.Cites) + assert.True(t, slices.ContainsFunc(row.Cites, func(cite specrules.Cite) bool { return row.Span.Holds(cite.Minor) }), + "%s.%s: no citation of a default comes from a minor it holds at", object.Name, row.Field) } for _, pattern := range object.Patterned { valid(object.Name+"."+pattern.Name, pattern.Cites) @@ -105,7 +105,7 @@ func TestTable_EveryRowCitesTheSpecification(t *testing.T) { } // itoa spells a small number for a failure message. -func itoa(n int) string { return string(rune('0' + n)) } +func itoa(count int) string { return string(rune('0' + count)) } // TestTable_SpansAreWellFormed pins every span the table states. func TestTable_SpansAreWellFormed(t *testing.T) { @@ -135,8 +135,8 @@ func TestTable_SpansAreWellFormed(t *testing.T) { defaultsAreWellFormed(t, object) for i, pattern := range object.Patterned { assert.True(t, validSpan(pattern.Span), object.Name+"."+pattern.Name) - for _, patternValue := range object.Patterned[i+1:] { - assert.False(t, overlaps(pattern.Span, patternValue.Span), "%s admits two patterns at one minor", object.Name) + for _, patterned := range object.Patterned[i+1:] { + assert.False(t, overlaps(pattern.Span, patterned.Span), "%s admits two patterns at one minor", object.Name) } } for i, rule := range object.Rules { @@ -177,16 +177,16 @@ func defaultsAreWellFormed(t *testing.T, object specrules.Object) { defined := func(name string, minor specrules.Minor) bool { return slices.ContainsFunc(object.Fields, func(field specrules.Field) bool { return field.Name == name && field.Defined.Holds(minor) }) } - for i, defaultValue := range object.Defaults { - where := object.Name + "." + defaultValue.Field + " default" - assert.True(t, validSpan(defaultValue.Span) && defaultValue.Span != (specrules.MinorVersionRange{}), where) - assert.NotZero(t, defaultValue.Case, where+" names no case") + for i, row := range object.Defaults { + where := object.Name + "." + row.Field + " default" + assert.True(t, validSpan(row.Span) && row.Span != (specrules.MinorVersionRange{}), where) + assert.NotZero(t, row.Case, where+" names no case") for _, minor := range minors() { - if defaultValue.Span.Holds(minor) { - assert.True(t, defined(defaultValue.Field, minor), "%s holds at %s, where the object defines no such field", where, minor) + if row.Span.Holds(minor) { + assert.True(t, defined(row.Field, minor), "%s holds at %s, where the object defines no such field", where, minor) } for _, otherDefault := range object.Defaults[i+1:] { - assert.False(t, otherDefault.Field == defaultValue.Field && otherDefault.Case == defaultValue.Case && otherDefault.Span.Holds(minor) && defaultValue.Span.Holds(minor), + assert.False(t, otherDefault.Field == row.Field && otherDefault.Case == row.Case && otherDefault.Span.Holds(minor) && row.Span.Holds(minor), "%s has two values of one case at %s", where, minor) } } @@ -343,7 +343,7 @@ func laterExtras() []laterRow { } // tableLaterRows reads off the table every construct a minor after 3.0 added: -// a field, a value of one, or a Reference Object standing in an object's place. +// a field, a value of one, or a Reference Object taking an object's place. // A JSON Schema keyword is the schema lowering's to place. func tableLaterRows() []laterRow { var rows []laterRow diff --git a/compilers/openapi/internal/specrules/value.go b/compilers/openapi/internal/specrules/value.go index e73c949c4..643592bc1 100644 --- a/compilers/openapi/internal/specrules/value.go +++ b/compilers/openapi/internal/specrules/value.go @@ -23,18 +23,18 @@ import ( // shape allows, then the objects it holds. A value of a Schema Object field // whose reading its dialect decides beyond its shape is judged as read // instead (dialectShape). -func (w *walker) value(frameValue frame, fld Field, val *yaml.Node, depth int) { +func (w *walker) value(frame frame, fld Field, val *yaml.Node, depth int) { node := nodeview.Deref(val) - ptr := frameValue.at.ptr.AppendToken(fld.Name) - shared := frameValue.shared || sharedNode(val) - if frameValue.rows.rows != nil && dialectShape(w, frameValue, fld, node, ptr) { + ptr := frame.at.ptr.AppendToken(fld.Name) + shared := frame.shared || sharedNode(val) + if frame.rows.rows != nil && dialectShape(w, frame, fld, node, ptr) { w.accept(shared, node) return } - shape, ok := shapeOf(frameValue, fld, node, w.minor) + shape, ok := shapeOf(frame, fld, node, w.minor) if !ok { w.refuse(node) - w.mismatch(frameValue, fld, node, ptr) + w.mismatch(frame, fld, node, ptr) return } // A field of any shape reads no type: its value is the values' to render as @@ -44,27 +44,27 @@ func (w *walker) value(frameValue frame, fld Field, val *yaml.Node, depth int) { w.accept(shared, node) } if shape == String { - w.text(frameValue, fmt.Sprintf("field %q", fld.Name), fld, node, ptr) + w.text(frame, fmt.Sprintf("field %q", fld.Name), fld, node, ptr) } - w.scalar(frameValue, fld, node, ptr) - w.entries(frameValue, fld, shape, node, ptr, depth) + w.scalar(frame, fld, node, ptr) + w.entries(frame, fld, shape, node, ptr, depth) } // dialectShape judges a value of a Schema Object field that the schema lowering -// reads otherwise than its shape says, read with frameValue's rows, and reports +// reads otherwise than its shape says, read with frame's rows, and reports // whether it did: a numeric bound, read as the decimal it spells, quoted or not // (decimalBound), bar a null, read as left out, and a number its range refuses, // such as a multipleOf of 0; and an `items` written as a list where the rows // read no tuple, which a JSON Schema draft reads as one, an error saying what // the document's version writes instead. -func dialectShape(walkerValue *walker, frameValue frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) bool { +func dialectShape(walker *walker, frame frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) bool { switch { case fld.Decimal && !isNull(node) && !outsideRuleset(node) && (matches(fld.Shape, node) || !outOfRange(fld.Shape, node)): - decimalBound(walkerValue, frameValue, fld, node, ptr) + decimalBound(walker, frame, fld, node, ptr) return true - case fld.Name == "items" && node.Kind == yaml.SequenceNode && !frameValue.rows.Takes("items", List): - walkerValue.add(diag.Newf(ir.SeverityError, diag.InvalidItemsList, walkerValue.locate(ptr), - "items must be a schema in this schema's dialect, not a list; %s", itemsListRemedy(frameValue.rows)), ptr) + case fld.Name == "items" && node.Kind == yaml.SequenceNode && !frame.rows.Takes("items", List): + walker.add(diag.Newf(ir.SeverityError, diag.InvalidItemsList, walker.locate(ptr), + "items must be a schema in this schema's dialect, not a list; %s", itemsListRemedy(frame.rows)), ptr) return true default: return false @@ -72,15 +72,15 @@ func dialectShape(walkerValue *walker, frameValue frame, fld Field, node *yaml.N } // decimalBound reports an exclusive bound written in the other form than -// frameValue's rows give it, a boolean modifying the bound beside it or a +// frame's rows give it, a boolean modifying the bound beside it or a // number of its own, and a bound, a boolean exclusive bound aside, no decimal // spells, quoted or not (value.NumericLiteral), each an error at the value. -func decimalBound(walkerValue *walker, frameValue frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) { +func decimalBound(walker *walker, frame frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) { if fld.Name == "exclusiveMinimum" || fld.Name == "exclusiveMaximum" { - boolean := frameValue.rows.Takes(fld.Name, Boolean) + boolean := frame.rows.Takes(fld.Name, Boolean) if written := matches(Boolean, node); written != boolean { want := map[bool]string{true: "a boolean", false: "a number"}[boolean] - walkerValue.add(diag.Newf(ir.SeverityError, diag.ExclusiveBoundForm, walkerValue.locate(ptr), + walker.add(diag.Newf(ir.SeverityError, diag.ExclusiveBoundForm, walker.locate(ptr), "%s must be %s in this schema's dialect", fld.Name, want), ptr) return } @@ -89,7 +89,7 @@ func decimalBound(walkerValue *walker, frameValue frame, fld Field, node *yaml.N } } if _, err := value.NumericLiteral(node); err != nil { - walkerValue.add(diag.Newf(ir.SeverityError, diag.NumericPrecision, walkerValue.locate(ptr), + walker.add(diag.Newf(ir.SeverityError, diag.NumericPrecision, walker.locate(ptr), "%s literal %q: %s", fld.Name, node.Value, err.Error()), ptr) } } @@ -109,21 +109,21 @@ func itemsListRemedy(rules SchemaRules) string { // document breaks its version's typing, which is JSON's, while the text it // writes says what it means, which a string field reads. label names the // value: a field, or an item or entry of one. -func (w *walker) text(frameValue frame, label string, fld Field, node *yaml.Node, ptr jsontext.Pointer) { +func (w *walker) text(frame frame, label string, fld Field, node *yaml.Node, ptr jsontext.Pointer) { what := map[string]string{"!!int": "the number", "!!float": "the number", "!!bool": "the boolean"}[node.Tag] if what == "" { return } w.report(ir.SeverityWarning, classType, ptr, "%s %s must be a string in %s (%s); it is %s %s", - frameValue.obj.Name, label, frameValue.in(w.minor), citeFor(fld.Cites, w.minor).Section, what, node.Value) + frame.obj.Name, label, frame.in(w.minor), citeFor(fld.Cites, w.minor).Section, what, node.Value) } // mismatch reports a value that has none of the shapes its field admits, an // error unless it is a null read otherwise (frame.nullRead). -func (w *walker) mismatch(frameValue frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) { +func (w *walker) mismatch(frame frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) { sev, null := ir.SeverityError, "" if isNull(node) { - switch frameValue.nullRead(fld, w.minor) { + switch frame.nullRead(fld, w.minor) { case leftOut: sev, null = ir.SeverityWarning, "; it is null, which is read as the field left out" case noScopes: @@ -137,7 +137,7 @@ func (w *walker) mismatch(frameValue frame, fld Field, node *yaml.Node, ptr json tagged.Tag, w.minor) } w.report(sev, classType, ptr, "%s field %q must be %s in %s (%s)%s", - frameValue.obj.Name, fld.Name, describeShape(fld), frameValue.in(w.minor), citeFor(fld.Cites, w.minor).Section, null) + frame.obj.Name, fld.Name, describeShape(fld), frame.in(w.minor), citeFor(fld.Cites, w.minor).Section, null) } // taggedOutside returns node, or for a list the first item, that is tagged @@ -182,14 +182,14 @@ func outsideRuleset(node *yaml.Node) bool { type nullReading uint8 const ( - // wrongValue: as a value of the wrong shape, an error. - wrongValue nullReading = iota + // wrong: as a value of the wrong shape, an error. + wrong nullReading = iota // leftOut: as the field left out, a warning. leftOut // missingElsewhere: as a missing field, which another package reports. missingElsewhere // noScopes: as a security requirement's name listing no scopes, a warning. - // The name is no field to leave out: it stands whatever its value + // The name is no field to leave out: it remains whatever its value // (docs/compilers/openapi.md#security-requirements). noScopes ) @@ -201,10 +201,10 @@ const ( // it is the value that is missing, reported by whichever package owns the rule. func (f frame) nullRead(fld Field, minor Minor) nullReading { if fld.Shape == Nested && fld.Of == Schema && f.obj.Kind != Schema { - return wrongValue + return wrong } if fld.Required.Holds(minor) { - return wrongValue + return wrong } for _, rule := range f.obj.Rules { if rule.Kind != RuleRequiredWhen || rule.Field != fld.Name || !rule.Span.Holds(minor) || f.test(rule.When) != answerYes { @@ -213,9 +213,10 @@ func (f frame) nullRead(fld Field, minor Minor) nullReading { if rule.Owner != "" { return missingElsewhere } - return wrongValue + return wrong } - // A requirement's name stands whatever its value, so it is no optional field. + // A requirement's name remains whatever its value, so it is no optional + // field. if f.obj.Kind == SecurityRequirement { return noScopes } @@ -236,7 +237,7 @@ func (f frame) writes(name string, minor Minor) bool { return true } fld := f.fieldAt(name, minor) - return matches(fld.Shape, node) || f.nullRead(fld, minor) == wrongValue + return matches(fld.Shape, node) || f.nullRead(fld, minor) == wrong } // fieldAt returns the field named name f's object defines at minor minor, else @@ -257,7 +258,7 @@ func isNull(node *yaml.Node) bool { // shapeOf finds the shape, among the field's own and the alternatives that hold // at the declared minor, that the node has. A node tagged outside the ruleset // has none, but where the field takes any value (outsideRuleset). -func shapeOf(frameValue frame, fld Field, node *yaml.Node, minor Minor) (Shape, bool) { +func shapeOf(frame frame, fld Field, node *yaml.Node, minor Minor) (Shape, bool) { if fld.Shape != AnyShapeUnchecked && outsideRuleset(node) { return fld.Shape, false } @@ -269,13 +270,13 @@ func shapeOf(frameValue frame, fld Field, node *yaml.Node, minor Minor) (Shape, return alt.Shape, true } } - // Only the Schema Object stands as a boolean, where a field holds one: a + // Only the Schema Object is a boolean, where a field holds one: a // schema decides for the schemas it holds, as for an entry of a list or a // map of them (frame.holdsBoolean), and one no schema holds is read as the // object it is, so the rows it is read with decide (walker.notMapping), // where the minor admits one at all. - if fld.Shape == Nested && fld.Of == Schema && frameValue.booleans && matches(Boolean, node) { - if frameValue.rows.rows != nil { + if fld.Shape == Nested && fld.Of == Schema && frame.booleans && matches(Boolean, node) { + if frame.rows.rows != nil { return Boolean, true } return Nested, true @@ -302,7 +303,7 @@ func (s Spec) booleanHeld(kind Kind, minor Minor) bool { // that, that it is one the field enumerates, and that it has its syntax. The // empty string is judged as any text is, so a format it breaks, as an absolute // URI's, refuses it, and one admitting it says so in ValidFormat. -func (w *walker) scalar(frameValue frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) { +func (w *walker) scalar(frame frame, fld Field, node *yaml.Node, ptr jsontext.Pointer) { if node.Kind != yaml.ScalarNode { return } @@ -310,44 +311,44 @@ func (w *walker) scalar(frameValue frame, fld Field, node *yaml.Node, ptr jsonte switch { case fld.NonEmpty.Holds(w.minor) && node.Value == "": w.report(ir.SeverityError, classEmpty, ptr, "%s field %q must not be empty in %s (%s)", - frameValue.obj.Name, fld.Name, frameValue.in(w.minor), section) + frame.obj.Name, fld.Name, frame.in(w.minor), section) case len(fld.Values) > 0: - w.enumerated(frameValue, fld, node.Value, ptr) + w.enumerated(frame, fld, node.Value, ptr) case fld.Format != FormatNone && !ValidFormat(fld.Format, node.Value): w.report(ir.SeverityError, classFormat, ptr, "%s field %q must be %s in %s (%s)", - frameValue.obj.Name, fld.Name, describeFormat(fld.Format), frameValue.in(w.minor), section) + frame.obj.Name, fld.Name, describeFormat(fld.Format), frame.in(w.minor), section) } } // enumerated checks text against the values the field admits. -func (w *walker) enumerated(frameValue frame, fld Field, text string, ptr jsontext.Pointer) { - for _, valueValue := range fld.Values { - if valueValue.Name != text || frameValue.test(valueValue.When) == answerNo { +func (w *walker) enumerated(frame frame, fld Field, text string, ptr jsontext.Pointer) { + for _, allowed := range fld.Values { + if allowed.Name != text || frame.test(allowed.When) == answerNo { continue } - if valueValue.Span.Holds(w.minor) { + if allowed.Span.Holds(w.minor) { return } - if valueValue.Span.Later(w.minor) { - w.laterField(frameValue.obj, fld.Name, text, valueValue.Span.Since, ptr) + if allowed.Span.Later(w.minor) { + w.laterField(frame.obj, fld.Name, text, allowed.Span.Since, ptr) return } } - admitted := frameValue.admitted(fld, w.minor) + admitted := frame.admitted(fld, w.minor) if admitted == "" { return // the sibling the values depend on names none, which it reports itself } w.report(ir.SeverityError, classValues, ptr, "%s field %q must be one of %s in %s (%s)", - frameValue.obj.Name, fld.Name, admitted, frameValue.in(w.minor), citeFor(fld.Cites, w.minor).Section) + frame.obj.Name, fld.Name, admitted, frame.in(w.minor), citeFor(fld.Cites, w.minor).Section) } // admitted lists the values the field admits at minor minor, as the object's -// own fields stand. +// own fields hold. func (f frame) admitted(fld Field, minor Minor) string { var names []string - for _, valueValue := range fld.Values { - if valueValue.Span.Holds(minor) && f.test(valueValue.When) != answerNo { - names = append(names, strconv.Quote(valueValue.Name)) + for _, allowed := range fld.Values { + if allowed.Span.Holds(minor) && f.test(allowed.When) != answerNo { + names = append(names, strconv.Quote(allowed.Name)) } } return strings.Join(names, ", ") @@ -355,43 +356,43 @@ func (f frame) admitted(fld Field, minor Minor) string { // entries checks what a container value holds: the object, or the objects of a // map or list, each read as the kind the field names. -func (w *walker) entries(frameValue frame, fld Field, shape Shape, node *yaml.Node, ptr jsontext.Pointer, depth int) { +func (w *walker) entries(frame frame, fld Field, shape Shape, node *yaml.Node, ptr jsontext.Pointer, depth int) { switch shape { case Nested: - w.object(objectToCheck{kind: fld.Of, node: node, ptr: ptr, held: fld.Name, rows: frameValue.rows, in: frameValue.obj.Kind, - shared: frameValue.shared}, depth+1) + w.object(objectToCheck{kind: fld.Of, node: node, ptr: ptr, held: fld.Name, rows: frame.rows, in: frame.obj.Kind, + shared: frame.shared}, depth+1) case Map: - w.repeated(node, ptr, "field "+strconv.Quote(fld.Name)+" of the "+frameValue.obj.Name) + w.repeated(node, ptr, "field "+strconv.Quote(fld.Name)+" of the "+frame.obj.Name) pairs := w.view.MappingPairs(node) places := newKeyPlacer(w, node, ptr) - for _, keyFinding := range keyFindings(frameValue.obj, fld, pairs, w.minor) { + for _, keyFinding := range keyFindings(frame.obj, fld, pairs, w.minor) { w.add(diag.Newf(keyFinding.sev, diag.Validation+"/"+keyFinding.class, places.place(keyFinding.key), "%s", keyFinding.message), ptr.AppendToken(keyFinding.key)) } for _, pair := range pairs { - if !frameValue.holdsBoolean(fld, pair.Val) { - w.object(objectToCheck{kind: fld.Of, node: pair.Val, ptr: ptr.AppendToken(pair.Key), held: pair.Key, rows: frameValue.rows, - in: frameValue.obj.Kind, shared: frameValue.shared}, depth+1) + if !frame.holdsBoolean(fld, pair.Val) { + w.object(objectToCheck{kind: fld.Of, node: pair.Val, ptr: ptr.AppendToken(pair.Key), held: pair.Key, rows: frame.rows, + in: frame.obj.Kind, shared: frame.shared}, depth+1) } } case List: for i, item := range node.Content { - if !frameValue.holdsBoolean(fld, item) { - w.object(objectToCheck{kind: fld.Of, node: item, ptr: itemPointer(ptr, i), rows: frameValue.rows, in: frameValue.obj.Kind, - shared: frameValue.shared}, depth+1) + if !frame.holdsBoolean(fld, item) { + w.object(objectToCheck{kind: fld.Of, node: item, ptr: itemPointer(ptr, i), rows: frame.rows, in: frame.obj.Kind, + shared: frame.shared}, depth+1) } } case StringList: for i, item := range node.Content { item = nodeview.Deref(item) - w.text(frameValue, fmt.Sprintf("field %q item %d", fld.Name, i), fld, item, itemPointer(ptr, i)) + w.text(frame, fmt.Sprintf("field %q item %d", fld.Name, i), fld, item, itemPointer(ptr, i)) if len(fld.Values) > 0 { - w.enumerated(frameValue, fld, item.Value, itemPointer(ptr, i)) + w.enumerated(frame, fld, item.Value, itemPointer(ptr, i)) } } case StringMap: for _, pair := range w.view.MappingPairs(node) { - w.text(frameValue, fmt.Sprintf("field %q entry %q", fld.Name, pair.Key), fld, nodeview.Deref(pair.Val), ptr.AppendToken(pair.Key)) + w.text(frame, fmt.Sprintf("field %q entry %q", fld.Name, pair.Key), fld, nodeview.Deref(pair.Val), ptr.AppendToken(pair.Key)) } default: // A scalar, or a container of values the table leaves unread, which the @@ -407,33 +408,33 @@ func (w *walker) entries(frameValue frame, fld Field, shape Shape, node *yaml.No // where the value is, and the one pointer the walk spells unless it places a // finding below (rawPointer): the pointer bound counts such a value by its // root alone (docs/compilers/openapi.md#source-budgets). -func rawRepeats(walkerValue *walker, val *yaml.Node, ptr jsontext.Pointer, depth int) { +func rawRepeats(walker *walker, val *yaml.Node, ptr jsontext.Pointer, depth int) { node := nodeview.Deref(val) if node == nil || node.Kind != yaml.MappingNode && node.Kind != yaml.SequenceNode { return } - ok, stops := walkerValue.charge(depth) + ok, stops := walker.charge(depth) if stops { - reportStop(walkerValue, rawPointer(ptr, walkerValue.raw)) + reportStop(walker, rawPointer(ptr, walker.raw)) } if !ok { return } if node.Kind == yaml.SequenceNode { for i, item := range node.Content { - walkerValue.raw = append(walkerValue.raw, rawStep{index: i, item: true}) - rawRepeats(walkerValue, item, ptr, depth+1) - walkerValue.raw = walkerValue.raw[:len(walkerValue.raw)-1] + walker.raw = append(walker.raw, rawStep{index: i, item: true}) + rawRepeats(walker, item, ptr, depth+1) + walker.raw = walker.raw[:len(walker.raw)-1] } return } if len(nodeview.RepeatedKeys(node)) > 0 { - walkerValue.repeated(node, rawPointer(ptr, walkerValue.raw), "a mapping") + walker.repeated(node, rawPointer(ptr, walker.raw), "a mapping") } - for _, pair := range walkerValue.view.MappingPairs(node) { - walkerValue.raw = append(walkerValue.raw, rawStep{key: pair.Key}) - rawRepeats(walkerValue, pair.Val, ptr, depth+1) - walkerValue.raw = walkerValue.raw[:len(walkerValue.raw)-1] + for _, pair := range walker.view.MappingPairs(node) { + walker.raw = append(walker.raw, rawStep{key: pair.Key}) + rawRepeats(walker, pair.Val, ptr, depth+1) + walker.raw = walker.raw[:len(walker.raw)-1] } } @@ -576,8 +577,8 @@ func numberOf(shape Shape, node *yaml.Node) bool { if node.Kind != yaml.ScalarNode || node.Style&stringStyles != 0 { return false } - sign, integral, ok := parseNumber(node.Value) - return ok && inRange(shape, sign, integral) + number := parseNumber(node.Value) + return number.ok && inRange(shape, number.sign, number.integral) } // outOfRange reports whether the node's text, quoted or not, is a number the @@ -587,8 +588,8 @@ func outOfRange(shape Shape, node *yaml.Node) bool { if node.Kind != yaml.ScalarNode { return false } - sign, integral, ok := parseNumber(node.Value) - return ok && !inRange(shape, sign, integral) + number := parseNumber(node.Value) + return number.ok && !inRange(shape, number.sign, number.integral) } // inRange reports whether a number of the given sign and integrality falls in the @@ -611,18 +612,26 @@ func inRange(shape Shape, sign int, integral bool) bool { // validity does not hang on that range. A based integer is YAML 1.2's core // schema's, 0o17 or 0x10 (docs/parser-library.md#scalar-resolution): 0b1010, // 1_000 and +0x10 are text, as a fraction such as 4/2 or a binary exponent is. -func parseNumber(text string) (sign int, integral, ok bool) { +func parseNumber(text string) yamlNumber { decimal, err := ir.ParseDecimal(text) if err == nil { - return decimal.Sign(), decimal.IsInt(), true + return yamlNumber{sign: decimal.Sign(), integral: decimal.IsInt(), ok: true} } if past, isPast := errors.AsType[*ir.ExponentRangeError](err); isPast { - return past.Sign(), past.IsInt(), true + return yamlNumber{sign: past.Sign(), integral: past.IsInt(), ok: true} } if coreInteger, isCore := nodeview.ParseCoreInteger(text); isCore { - return coreInteger.Sign(), true, true + return yamlNumber{sign: coreInteger.Sign(), integral: true, ok: true} } - return 0, false, false + return yamlNumber{} +} + +// yamlNumber is the sign and integrality of a YAML number (parseNumber), and +// whether the text is a number. +type yamlNumber struct { + sign int + integral bool + ok bool } // describeShape says what a field's value must be. diff --git a/compilers/openapi/internal/specrules/walker_internal_test.go b/compilers/openapi/internal/specrules/walker_internal_test.go index a48e9aa55..6eba17546 100644 --- a/compilers/openapi/internal/specrules/walker_internal_test.go +++ b/compilers/openapi/internal/specrules/walker_internal_test.go @@ -87,14 +87,14 @@ func TestCheck_ASharedRootTellsEveryAcceptance(t *testing.T) { var got []string NewChecker().Check(t.Context(), &doc, "3.1.0", Options{Start: Parameter, Shared: shared, Judged: func(node *yaml.Node, refused bool) { - verdict, text := "accepted", node.Value + answer, text := "accepted", node.Value if refused { - verdict = "refused" + answer = "refused" } if node.Kind == yaml.MappingNode { text = "{" + node.Content[0].Value + "}" } - got = append(got, verdict+" "+text) + got = append(got, answer+" "+text) }}) assert.ElementsMatch(t, want, got, "shared %v", shared) diff --git a/compilers/openapi/internal/statement/identifiers_test.go b/compilers/openapi/internal/statement/identifiers_test.go new file mode 100644 index 000000000..ab1dddcd8 --- /dev/null +++ b/compilers/openapi/internal/statement/identifiers_test.go @@ -0,0 +1,56 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package statement_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestSchema_WritesOnlyIdentifierAndMetaKeywords pins the predicate an +// unreported applicator is read by +// (docs/compilers/openapi.md#shape-applicator): a schema writing only +// identifier and meta keywords, in each dialect's spelling of them, or none at +// all, admits every instance and states nothing a kind is inferred from, while +// a note, an extension, an unevaluated keyword or any other keyword beside them +// states something. +func TestSchema_WritesOnlyIdentifierAndMetaKeywords(t *testing.T) { + t.Parallel() + const ( + draft04 = "http://json-schema.org/draft-04/schema#" + draft07 = "http://json-schema.org/draft-07/schema#" + draft2019 = "https://json-schema.org/draft/2019-09/schema" + ) + for _, tc := range []struct { + named, schema string + only bool + }{ + {"", "{}", true}, + {"", "{$comment: c}", true}, + {"", "{$anchor: a, $defs: {D: {type: string}}}", true}, + {"", "{$id: 'https://example.com/a', $schema: 'https://json-schema.org/draft/2020-12/schema'}", true}, + {"", "{$dynamicAnchor: m, $comment: c}", true}, + {draft04, "{id: 'https://example.com/a'}", true}, + {draft07, "{definitions: {D: {type: string}}, $comment: c}", true}, + {draft2019, "{$recursiveAnchor: true}", true}, + {"", "{description: d}", false}, + {"", "{title: t, $comment: c}", false}, + {"", "{x-a: 1}", false}, + {"", "{unevaluatedProperties: false}", false}, + {"", "{unevaluatedItems: false, $comment: c}", false}, + {"", "{type: string, $comment: c}", false}, + {"", "{items: {}, $anchor: a}", false}, + } { + src := document("3.1.0", "A: "+tc.schema) + if tc.named != "" { + src = "jsonSchemaDialect: '" + tc.named + "'\n" + src + } + table, loweringContext := tableOver(t, src, rulesAt(t, "3.1.0", tc.named)) + schemaStatement := table.At(component(loweringContext, "A")) + require.NotNil(t, schemaStatement, tc.schema) + assert.Equal(t, tc.only, schemaStatement.WritesOnlyIdentifierAndMetaKeywords(), "%s %s", tc.named, tc.schema) + } +} diff --git a/compilers/openapi/internal/statement/model.go b/compilers/openapi/internal/statement/model.go index ccd597ebc..ebc118fe1 100644 --- a/compilers/openapi/internal/statement/model.go +++ b/compilers/openapi/internal/statement/model.go @@ -45,7 +45,7 @@ func Parsed(schema *Schema) *oas3.Schema { if schema == nil { return nil } - if schema.Truncated { + if schema.Truncated || schema.partial { return listedOnly(schema.m.GetSchema(), schema) } return schema.m.GetSchema() @@ -70,30 +70,30 @@ func (t *MemoizingSchemaReader) read(js *model) *Schema { return schema } t.reads++ - schemaValue := &Schema{m: js, Truth: truthOf(js)} - t.schemas[js] = schemaValue + schema := &Schema{m: js, Truth: truthOf(js)} + t.schemas[js] = schema if js == nil { - return schemaValue + return schema } - schemaValue.At, _ = t.src.Bindings.Site(js) - if schemaValue.Truth != Stated { - schemaValue.Node = nodeview.Deref(js.GetCore().GetRootNode()) - return schemaValue + schema.At, _ = t.src.Bindings.Site(js) + if schema.Truth != Stated { + schema.Node = nodeview.Deref(js.GetCore().GetRootNode()) + return schema } - m := js.GetSchema() - schemaValue.Node = nodeview.Deref(nodeview.DocumentRoot(m.GetRootNode())) - schemaValue.Unknown = m.GetCore().GetUnknownProperties() - schemaValue.Extensions = listedExtensions(m.GetExtensions().Len(), m.GetExtensions().All()) - readKeys(schemaValue, t.src.Rules.At(schemaValue.At)) - if schemaValue.Truncated { - dropOutranked(schemaValue, m) + oasSchema := js.GetSchema() + schema.Node = nodeview.Deref(nodeview.DocumentRoot(oasSchema.GetRootNode())) + schema.Unknown = oasSchema.GetCore().GetUnknownProperties() + schema.Extensions = listedExtensions(oasSchema.GetExtensions().Len(), oasSchema.GetExtensions().All()) + readKeys(schema, t.src.Rules.At(schema.At)) + if schema.Truncated { + dropOutranked(schema, oasSchema) } - if kw := t.src.Bindings.RefKeyword(js); kw != "" { - referenceSite, bound := t.src.Bindings.Entry(js) - schemaValue.Ref = &Reference{Keyword: kw, Text: string(m.GetRef()), Entry: referenceSite, Bound: bound} + if keyword := t.src.Bindings.RefKeyword(js); keyword != "" { + referenceSite, bound := t.src.Bindings.ReferenceSiteAt(js) + schema.Ref = &Reference{Keyword: keyword, Text: string(oasSchema.GetRef()), Entry: referenceSite, Bound: bound} } - fill(schemaValue, m) - return schemaValue + fill(schema, oasSchema) + return schema } // SchemaValueForm returns what the schema s names states, as @@ -118,11 +118,11 @@ func (s *Schema) Property(name string) (Subschema, bool) { if s == nil || s.Object == nil || len(s.Object.Properties) == 0 { return Subschema{}, false } - p, ok := s.m.GetSchema().GetProperties().Get(name) + property, ok := s.m.GetSchema().GetProperties().Get(name) if !ok { return Subschema{}, false } - return Subschema{Name: name, m: p}, true + return Subschema{Name: name, m: property}, true } // truthOf returns what js states. The parser reads a value written as no @@ -150,29 +150,29 @@ func truthOf(js *model) SchemaValueForm { } } -// fill reads each slot's values. A typed value is m's, the parser's model, as -// the walk reads the model; for a Truncated schema, only where schema's keys -// list its keyword (listedOnly). A value kept as the node it was written as is -// its key's. Each keyword lands in its own slot (specrules.SlotOf) whatever the -// rows say: a policy reads a 3.0 `nullable` in a 3.1 schema -// (docs/compilers/openapi.md#nullable), and the key's Slot carries the rows' -// verdict. A listed key whose value is not read opens its slot and fills -// nothing. -func fill(schema *Schema, m *oas3.Schema) { +// fill reads each slot's values. A typed value is oasSchema's, the parser's +// model, as the walk reads the model; for a Truncated schema, only where +// schema's keys list its keyword (listedOnly). A value kept as the node it was +// written as is its key's. Each keyword lands in its own slot +// (specrules.SlotOf) whatever the rows say: a policy reads a 3.0 `nullable` in +// a 3.1 schema (docs/compilers/openapi.md#nullable), and the key's Slot carries +// the rows' answer. A listed key whose value is not read opens its slot and +// fills nothing. +func fill(schema *Schema, oasSchema *oas3.Schema) { if schema.Truncated { - m = listedOnly(m, schema) - } - schema.AllOf = listed(m.AllOf) - schema.Kinds = kindsOf(m) - schema.Number = numberOf(m) - schema.Values = valuesOf(m) - schema.Format = formatOf(m) - schema.Text = textOf(m) - schema.Array = arrayOf(m) - schema.Object = objectOf(m, schema.At) - schema.Choice = choiceOf(m) - schema.Logic = logicOf(m) - schema.Notes = notesOf(m) + oasSchema = listedOnly(oasSchema, schema) + } + schema.AllOf = listed(oasSchema.AllOf) + schema.Kinds = kindsOf(oasSchema) + schema.Number = numberOf(oasSchema) + schema.Values = valuesOf(oasSchema) + schema.Format = formatOf(oasSchema) + schema.Text = textOf(oasSchema) + schema.Array = arrayOf(oasSchema) + schema.Object = objectOf(oasSchema, schema.At) + schema.Choice = choiceOf(oasSchema) + schema.Logic = logicOf(oasSchema) + schema.Notes = notesOf(oasSchema) for _, key := range schema.Keys { open(schema, specrules.SlotOf(key.Name)) if key.read() { @@ -181,6 +181,12 @@ func fill(schema *Schema, m *oas3.Schema) { } } +// fillListed fills the slots of schema, a stated schema the parser read, from +// its model less every keyword its keys do not list (listedOnly). +func fillListed(schema *Schema) { + fill(schema, listedOnly(schema.m.GetSchema(), schema)) +} + // fillNode reads key, a key of a slot open in schema, into the field the // statement keeps as the node it was written as, which its row of fillKeywords // sets: a numeric bound, which the model holds as a float, and a keyword the @@ -207,111 +213,111 @@ type fillKeyword struct { // fillKeywords are the keywords fill reads, one row each. var fillKeywords = []fillKeyword{ - {name: "allOf", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().AllOf.ValueNode }, - clear: func(m *oas3.Schema) { m.AllOf = nil }}, - {name: "type", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Type.ValueNode }, - clear: func(m *oas3.Schema) { m.Type = nil }}, - {name: "nullable", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Nullable.ValueNode }, - clear: func(m *oas3.Schema) { m.Nullable = nil }}, - {name: "exclusiveMinimum", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().ExclusiveMinimum.ValueNode }, - clear: func(m *oas3.Schema) { m.ExclusiveMinimum = nil }, + {name: "allOf", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().AllOf.ValueNode }, + clear: func(schema *oas3.Schema) { schema.AllOf = nil }}, + {name: "type", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Type.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Type = nil }}, + {name: "nullable", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Nullable.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Nullable = nil }}, + {name: "exclusiveMinimum", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().ExclusiveMinimum.ValueNode }, + clear: func(schema *oas3.Schema) { schema.ExclusiveMinimum = nil }, set: func(schema *Schema, node *yaml.Node) { schema.Number.ExclusiveMinimum = node }}, - {name: "exclusiveMaximum", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().ExclusiveMaximum.ValueNode }, - clear: func(m *oas3.Schema) { m.ExclusiveMaximum = nil }, + {name: "exclusiveMaximum", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().ExclusiveMaximum.ValueNode }, + clear: func(schema *oas3.Schema) { schema.ExclusiveMaximum = nil }, set: func(schema *Schema, node *yaml.Node) { schema.Number.ExclusiveMaximum = node }}, - {name: "enum", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Enum.ValueNode }, - clear: func(m *oas3.Schema) { m.Enum = nil }}, - {name: "const", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Const.ValueNode }, - clear: func(m *oas3.Schema) { m.Const = nil }}, - {name: "format", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Format.ValueNode }, - clear: func(m *oas3.Schema) { m.Format = nil }}, - {name: "minLength", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MinLength.ValueNode }, - clear: func(m *oas3.Schema) { m.MinLength = nil }}, - {name: "maxLength", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MaxLength.ValueNode }, - clear: func(m *oas3.Schema) { m.MaxLength = nil }}, - {name: "pattern", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Pattern.ValueNode }, - clear: func(m *oas3.Schema) { m.Pattern = nil }}, - {name: "contentEncoding", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().ContentEncoding.ValueNode }, - clear: func(m *oas3.Schema) { m.ContentEncoding = nil }}, - {name: "contentMediaType", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().ContentMediaType.ValueNode }, - clear: func(m *oas3.Schema) { m.ContentMediaType = nil }}, - {name: "contentSchema", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().ContentSchema.ValueNode }, - clear: func(m *oas3.Schema) { m.ContentSchema = nil }}, - {name: "items", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Items.ValueNode }, - clear: func(m *oas3.Schema) { m.Items = nil }}, - {name: "prefixItems", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().PrefixItems.ValueNode }, - clear: func(m *oas3.Schema) { m.PrefixItems = nil }}, - {name: "contains", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Contains.ValueNode }, - clear: func(m *oas3.Schema) { m.Contains = nil }}, - {name: "minContains", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MinContains.ValueNode }, - clear: func(m *oas3.Schema) { m.MinContains = nil }}, - {name: "maxContains", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MaxContains.ValueNode }, - clear: func(m *oas3.Schema) { m.MaxContains = nil }}, - {name: "minItems", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MinItems.ValueNode }, - clear: func(m *oas3.Schema) { m.MinItems = nil }}, - {name: "maxItems", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MaxItems.ValueNode }, - clear: func(m *oas3.Schema) { m.MaxItems = nil }}, - {name: "uniqueItems", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().UniqueItems.ValueNode }, - clear: func(m *oas3.Schema) { m.UniqueItems = nil }}, - {name: "unevaluatedItems", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().UnevaluatedItems.ValueNode }, - clear: func(m *oas3.Schema) { m.UnevaluatedItems = nil }}, - {name: "properties", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Properties.ValueNode }, - clear: func(m *oas3.Schema) { m.Properties = nil }}, - {name: "patternProperties", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().PatternProperties.ValueNode }, - clear: func(m *oas3.Schema) { m.PatternProperties = nil }}, - {name: "additionalProperties", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().AdditionalProperties.ValueNode }, - clear: func(m *oas3.Schema) { m.AdditionalProperties = nil }}, - {name: "propertyNames", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().PropertyNames.ValueNode }, - clear: func(m *oas3.Schema) { m.PropertyNames = nil }}, - {name: "unevaluatedProperties", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().UnevaluatedProperties.ValueNode }, - clear: func(m *oas3.Schema) { m.UnevaluatedProperties = nil }}, - {name: "required", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Required.ValueNode }, - clear: func(m *oas3.Schema) { m.Required = nil }}, - {name: "minProperties", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MinProperties.ValueNode }, - clear: func(m *oas3.Schema) { m.MinProperties = nil }}, - {name: "maxProperties", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MaxProperties.ValueNode }, - clear: func(m *oas3.Schema) { m.MaxProperties = nil }}, - {name: "discriminator", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Discriminator.ValueNode }, - clear: func(m *oas3.Schema) { m.Discriminator = nil }}, - {name: "oneOf", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().OneOf.ValueNode }, - clear: func(m *oas3.Schema) { m.OneOf = nil }}, - {name: "anyOf", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().AnyOf.ValueNode }, - clear: func(m *oas3.Schema) { m.AnyOf = nil }}, - {name: "not", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Not.ValueNode }, - clear: func(m *oas3.Schema) { m.Not = nil }}, - {name: "if", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().If.ValueNode }, - clear: func(m *oas3.Schema) { m.If = nil }}, - {name: "then", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Then.ValueNode }, - clear: func(m *oas3.Schema) { m.Then = nil }}, - {name: "else", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Else.ValueNode }, - clear: func(m *oas3.Schema) { m.Else = nil }}, - {name: "dependentSchemas", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().DependentSchemas.ValueNode }, - clear: func(m *oas3.Schema) { m.DependentSchemas = nil }}, - {name: "title", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Title.ValueNode }, - clear: func(m *oas3.Schema) { m.Title = nil }}, - {name: "description", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Description.ValueNode }, - clear: func(m *oas3.Schema) { m.Description = nil }}, - {name: "default", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Default.ValueNode }, - clear: func(m *oas3.Schema) { m.Default = nil }}, - {name: "example", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Example.ValueNode }, - clear: func(m *oas3.Schema) { m.Example = nil }}, - {name: "examples", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Examples.ValueNode }, - clear: func(m *oas3.Schema) { m.Examples = nil }}, - {name: "deprecated", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Deprecated.ValueNode }, - clear: func(m *oas3.Schema) { m.Deprecated = nil }}, - {name: "readOnly", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().ReadOnly.ValueNode }, - clear: func(m *oas3.Schema) { m.ReadOnly = nil }}, - {name: "writeOnly", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().WriteOnly.ValueNode }, - clear: func(m *oas3.Schema) { m.WriteOnly = nil }}, - {name: "xml", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().XML.ValueNode }, - clear: func(m *oas3.Schema) { m.XML = nil }}, - {name: "externalDocs", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().ExternalDocs.ValueNode }, - clear: func(m *oas3.Schema) { m.ExternalDocs = nil }}, - {name: "minimum", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Minimum.ValueNode }, + {name: "enum", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Enum.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Enum = nil }}, + {name: "const", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Const.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Const = nil }}, + {name: "format", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Format.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Format = nil }}, + {name: "minLength", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MinLength.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MinLength = nil }}, + {name: "maxLength", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MaxLength.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MaxLength = nil }}, + {name: "pattern", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Pattern.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Pattern = nil }}, + {name: "contentEncoding", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().ContentEncoding.ValueNode }, + clear: func(schema *oas3.Schema) { schema.ContentEncoding = nil }}, + {name: "contentMediaType", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().ContentMediaType.ValueNode }, + clear: func(schema *oas3.Schema) { schema.ContentMediaType = nil }}, + {name: "contentSchema", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().ContentSchema.ValueNode }, + clear: func(schema *oas3.Schema) { schema.ContentSchema = nil }}, + {name: "items", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Items.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Items = nil }}, + {name: "prefixItems", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().PrefixItems.ValueNode }, + clear: func(schema *oas3.Schema) { schema.PrefixItems = nil }}, + {name: "contains", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Contains.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Contains = nil }}, + {name: "minContains", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MinContains.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MinContains = nil }}, + {name: "maxContains", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MaxContains.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MaxContains = nil }}, + {name: "minItems", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MinItems.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MinItems = nil }}, + {name: "maxItems", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MaxItems.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MaxItems = nil }}, + {name: "uniqueItems", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().UniqueItems.ValueNode }, + clear: func(schema *oas3.Schema) { schema.UniqueItems = nil }}, + {name: "unevaluatedItems", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().UnevaluatedItems.ValueNode }, + clear: func(schema *oas3.Schema) { schema.UnevaluatedItems = nil }}, + {name: "properties", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Properties.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Properties = nil }}, + {name: "patternProperties", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().PatternProperties.ValueNode }, + clear: func(schema *oas3.Schema) { schema.PatternProperties = nil }}, + {name: "additionalProperties", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().AdditionalProperties.ValueNode }, + clear: func(schema *oas3.Schema) { schema.AdditionalProperties = nil }}, + {name: "propertyNames", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().PropertyNames.ValueNode }, + clear: func(schema *oas3.Schema) { schema.PropertyNames = nil }}, + {name: "unevaluatedProperties", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().UnevaluatedProperties.ValueNode }, + clear: func(schema *oas3.Schema) { schema.UnevaluatedProperties = nil }}, + {name: "required", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Required.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Required = nil }}, + {name: "minProperties", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MinProperties.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MinProperties = nil }}, + {name: "maxProperties", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MaxProperties.ValueNode }, + clear: func(schema *oas3.Schema) { schema.MaxProperties = nil }}, + {name: "discriminator", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Discriminator.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Discriminator = nil }}, + {name: "oneOf", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().OneOf.ValueNode }, + clear: func(schema *oas3.Schema) { schema.OneOf = nil }}, + {name: "anyOf", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().AnyOf.ValueNode }, + clear: func(schema *oas3.Schema) { schema.AnyOf = nil }}, + {name: "not", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Not.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Not = nil }}, + {name: "if", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().If.ValueNode }, + clear: func(schema *oas3.Schema) { schema.If = nil }}, + {name: "then", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Then.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Then = nil }}, + {name: "else", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Else.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Else = nil }}, + {name: "dependentSchemas", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().DependentSchemas.ValueNode }, + clear: func(schema *oas3.Schema) { schema.DependentSchemas = nil }}, + {name: "title", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Title.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Title = nil }}, + {name: "description", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Description.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Description = nil }}, + {name: "default", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Default.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Default = nil }}, + {name: "example", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Example.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Example = nil }}, + {name: "examples", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Examples.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Examples = nil }}, + {name: "deprecated", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Deprecated.ValueNode }, + clear: func(schema *oas3.Schema) { schema.Deprecated = nil }}, + {name: "readOnly", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().ReadOnly.ValueNode }, + clear: func(schema *oas3.Schema) { schema.ReadOnly = nil }}, + {name: "writeOnly", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().WriteOnly.ValueNode }, + clear: func(schema *oas3.Schema) { schema.WriteOnly = nil }}, + {name: "xml", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().XML.ValueNode }, + clear: func(schema *oas3.Schema) { schema.XML = nil }}, + {name: "externalDocs", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().ExternalDocs.ValueNode }, + clear: func(schema *oas3.Schema) { schema.ExternalDocs = nil }}, + {name: "minimum", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Minimum.ValueNode }, set: func(schema *Schema, node *yaml.Node) { schema.Number.Minimum = node }}, - {name: "maximum", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().Maximum.ValueNode }, + {name: "maximum", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().Maximum.ValueNode }, set: func(schema *Schema, node *yaml.Node) { schema.Number.Maximum = node }}, - {name: "multipleOf", node: func(m *oas3.Schema) *yaml.Node { return m.GetCore().MultipleOf.ValueNode }, + {name: "multipleOf", node: func(schema *oas3.Schema) *yaml.Node { return schema.GetCore().MultipleOf.ValueNode }, set: func(schema *Schema, node *yaml.Node) { schema.Number.MultipleOf = node }}, {name: "additionalItems", set: func(schema *Schema, node *yaml.Node) { schema.Array.AdditionalItems = node }}, {name: "dependentRequired", set: func(schema *Schema, node *yaml.Node) { schema.Object.DependentRequired = node }}, @@ -331,17 +337,17 @@ func keywordRow(name string) (fillKeyword, bool) { } // dropOutranked takes out of the keys of schema, a Truncated schema whose model -// is m, each key of a keyword fill reads whose value the parser read from -// another node: a source past nodeview.MergeDepthLimit writes the keyword too -// and comes first, so the key lists the value that loses. A keyword the parser -// holds no node for is kept only where schema writes it itself, as no merge -// outranks that (docs/parser-library.md#merge-keys); one left out leaves +// is oasSchema, each key of a keyword fill reads whose value the parser read +// from another node: a source past nodeview.MergeDepthLimit writes the keyword +// too and comes first, so the key lists the value passed over. A keyword the +// parser holds no node for is kept only where schema writes it itself, as no +// merge outranks that (docs/parser-library.md#merge-keys); one left out leaves // schema.Unknown too, so that no census reads it. -func dropOutranked(schema *Schema, m *oas3.Schema) { +func dropOutranked(schema *Schema, oasSchema *oas3.Schema) { own := nodeview.WrittenChildren(schema.Node) kept := make([]Key, 0, len(schema.Keys)) for _, key := range schema.Keys { - if !outranked(key, own, m) { + if !outranked(key, own, oasSchema) { kept = append(kept, key) continue } @@ -355,26 +361,26 @@ func dropOutranked(schema *Schema, m *oas3.Schema) { } // outranked reports whether the value the parser read for key's keyword is not -// key's: key is no pair s writes itself, own, and the parser read the keyword -// from another node, or holds no node to tell. A key fill does not read is -// never outranked. -func outranked(key Key, own map[string]*yaml.Node, m *oas3.Schema) bool { +// key's: key is no pair the schema writes itself, own, and the parser read the +// keyword from another node, or holds no node to tell. A key fill does not read +// is never outranked. +func outranked(key Key, own map[string]*yaml.Node, schema *oas3.Schema) bool { fillKeyword, reads := keywordRow(key.Name) if !reads || nodeview.Deref(own[key.Name]) == key.Node { return false } - return fillKeyword.node == nil || nodeview.Deref(fillKeyword.node(m)) != key.Node + return fillKeyword.node == nil || nodeview.Deref(fillKeyword.node(schema)) != key.Node } -// listedOnly returns a copy of m holding no keyword schema's keys do not list: -// schema is Truncated, so the model expands merges its keys stop short of, and -// a schema is read from its keys or not at all, never half from each -// (docs/parser-library.md#merge-keys). dropOutranked has left each keyword the -// keys list only where the parser read it from that key. The model's extensions -// and the keys it holds no field for stay, which the census of unknown keys -// reports. -func listedOnly(m *oas3.Schema, schema *Schema) *oas3.Schema { - kept := *m +// listedOnly returns a copy of oasSchema holding no keyword schema's keys do +// not list: schema is Truncated, so the model expands merges its keys stop +// short of, and a schema is read from its keys or not at all, never half from +// each (docs/parser-library.md#merge-keys). dropOutranked has left each keyword +// the keys list only where the parser read it from that key. The model's +// extensions and the keys it holds no field for stay, which the census of +// unknown keys reports. +func listedOnly(oasSchema *oas3.Schema, schema *Schema) *oas3.Schema { + kept := *oasSchema for _, fillKeyword := range fillKeywords { if i, _ := schema.find(fillKeyword.name); i < 0 && fillKeyword.clear != nil { fillKeyword.clear(&kept) @@ -383,167 +389,171 @@ func listedOnly(m *oas3.Schema, schema *Schema) *oas3.Schema { return &kept } -// kindsOf returns what m's type and nullable say, nil where it holds neither. -func kindsOf(m *oas3.Schema) *Kinds { - if m.Type == nil && m.Nullable == nil { +// kindsOf returns what schema's type and nullable say, nil where it holds +// neither. +func kindsOf(schema *oas3.Schema) *Kinds { + if schema.Type == nil && schema.Nullable == nil { return nil } - kinds := &Kinds{Nullable: m.Nullable} - for _, t := range m.GetType() { + kinds := &Kinds{Nullable: schema.Nullable} + for _, t := range schema.GetType() { kinds.Types = append(kinds.Types, JSONSchemaTypeName(t)) } return kinds } -// numberOf returns the forms of m's exclusive bounds, nil where it holds +// numberOf returns the forms of schema's exclusive bounds, nil where it holds // neither: the bounds themselves are the nodes their keys hold (fillNode). -func numberOf(m *oas3.Schema) *Number { - if m.ExclusiveMinimum == nil && m.ExclusiveMaximum == nil { +func numberOf(schema *oas3.Schema) *Number { + if schema.ExclusiveMinimum == nil && schema.ExclusiveMaximum == nil { return nil } - return &Number{ExclusiveMinimumForm: exclusiveOf(m.ExclusiveMinimum), - ExclusiveMaximumForm: exclusiveOf(m.ExclusiveMaximum)} + return &Number{ExclusiveMinimumForm: exclusiveOf(schema.ExclusiveMinimum), + ExclusiveMaximumForm: exclusiveOf(schema.ExclusiveMaximum)} } -// exclusiveOf returns the arm the model read e, either exclusive bound, as. -func exclusiveOf(e oas3.ExclusiveMinimum) Exclusive { +// exclusiveOf returns the arm the model read exclusiveMinimum, either +// exclusive bound, as. +func exclusiveOf(exclusiveMinimum oas3.ExclusiveMinimum) Exclusive { switch { - case e == nil: + case exclusiveMinimum == nil: return NoExclusive - case !e.IsLeft(): + case !exclusiveMinimum.IsLeft(): return ExclusiveBound - case e.GetLeft() != nil && *e.GetLeft(): + case exclusiveMinimum.GetLeft() != nil && *exclusiveMinimum.GetLeft(): return ExclusiveTrue default: return ExclusiveFalse } } -// valuesOf returns what m's enum and const say, nil where it holds neither. -func valuesOf(m *oas3.Schema) *Values { - if m.Enum == nil && m.Const == nil { +// valuesOf returns what schema's enum and const say, nil where it holds +// neither. +func valuesOf(schema *oas3.Schema) *Values { + if schema.Enum == nil && schema.Const == nil { return nil } - return &Values{Enum: m.Enum, Const: m.Const} + return &Values{Enum: schema.Enum, Const: schema.Const} } -// formatOf returns the format m names, nil where it names none. -func formatOf(m *oas3.Schema) *Format { - if m.Format == nil { +// formatOf returns the format schema names, nil where it names none. +func formatOf(schema *oas3.Schema) *Format { + if schema.Format == nil { return nil } - return &Format{Name: *m.Format} + return &Format{Name: *schema.Format} } -// textOf returns what m's keywords asserting about a string say, nil where +// textOf returns what schema's keywords asserting about a string say, nil where // it holds none of them. -func textOf(m *oas3.Schema) *Text { - if m.MinLength == nil && m.MaxLength == nil && m.Pattern == nil && m.ContentEncoding == nil && - m.ContentMediaType == nil && m.ContentSchema == nil { +func textOf(schema *oas3.Schema) *Text { + if schema.MinLength == nil && schema.MaxLength == nil && schema.Pattern == nil && schema.ContentEncoding == nil && + schema.ContentMediaType == nil && schema.ContentSchema == nil { return nil } - return &Text{MinLength: m.MinLength, MaxLength: m.MaxLength, Pattern: m.GetPattern(), - ContentEncoding: m.GetContentEncoding(), ContentMediaType: m.GetContentMediaType(), - ContentSchema: Subschema{m: m.ContentSchema}} + return &Text{MinLength: schema.MinLength, MaxLength: schema.MaxLength, Pattern: schema.GetPattern(), + ContentEncoding: schema.GetContentEncoding(), ContentMediaType: schema.GetContentMediaType(), + ContentSchema: Subschema{m: schema.ContentSchema}} } -// arrayOf returns what m's keywords asserting about an array say, nil where -// it holds none of them. -func arrayOf(m *oas3.Schema) *Array { - if m.Items == nil && m.PrefixItems == nil && m.Contains == nil && m.MinContains == nil && - m.MaxContains == nil && m.MinItems == nil && m.MaxItems == nil && m.UniqueItems == nil && - m.UnevaluatedItems == nil { +// arrayOf returns what schema's keywords asserting about an array say, nil +// where it holds none of them. +func arrayOf(schema *oas3.Schema) *Array { + if schema.Items == nil && schema.PrefixItems == nil && schema.Contains == nil && schema.MinContains == nil && + schema.MaxContains == nil && schema.MinItems == nil && schema.MaxItems == nil && schema.UniqueItems == nil && + schema.UnevaluatedItems == nil { return nil } - return &Array{Items: Subschema{m: m.Items}, PrefixItems: listed(m.PrefixItems), Contains: Subschema{m: m.Contains}, - MinContains: m.MinContains, MaxContains: m.MaxContains, MinItems: m.MinItems, MaxItems: m.MaxItems, - UniqueItems: m.UniqueItems, UnevaluatedItems: Subschema{m: m.UnevaluatedItems}} + return &Array{Items: Subschema{m: schema.Items}, PrefixItems: listed(schema.PrefixItems), Contains: Subschema{m: schema.Contains}, + MinContains: schema.MinContains, MaxContains: schema.MaxContains, MinItems: schema.MinItems, MaxItems: schema.MaxItems, + UniqueItems: schema.UniqueItems, UnevaluatedItems: Subschema{m: schema.UnevaluatedItems}} } -// objectOf returns what m's keywords asserting about an object say, m being -// read at at, nil where it holds none of them. -func objectOf(m *oas3.Schema, at reftable.DocumentPointer) *Object { - if m.Properties == nil && m.PatternProperties == nil && m.AdditionalProperties == nil && - m.PropertyNames == nil && m.UnevaluatedProperties == nil && m.Required == nil && - m.MinProperties == nil && m.MaxProperties == nil && m.Discriminator == nil { +// objectOf returns what schema's keywords asserting about an object say, +// schema being read at schemaPointer, nil where it holds none of them. +func objectOf(schema *oas3.Schema, schemaPointer reftable.DocumentPointer) *Object { + if schema.Properties == nil && schema.PatternProperties == nil && schema.AdditionalProperties == nil && + schema.PropertyNames == nil && schema.UnevaluatedProperties == nil && schema.Required == nil && + schema.MinProperties == nil && schema.MaxProperties == nil && schema.Discriminator == nil { return nil } - return &Object{Properties: named(m.GetProperties().Len(), m.GetProperties().All()), - PatternProperties: named(m.GetPatternProperties().Len(), m.GetPatternProperties().All()), - AdditionalProperties: Subschema{m: m.AdditionalProperties}, PropertyNames: Subschema{m: m.PropertyNames}, - UnevaluatedProperties: Subschema{m: m.UnevaluatedProperties}, Required: m.Required, - MinProperties: m.MinProperties, MaxProperties: m.MaxProperties, Discriminator: discriminatorOf(m.Discriminator, at)} + return &Object{Properties: named(schema.GetProperties().Len(), schema.GetProperties().All()), + PatternProperties: named(schema.GetPatternProperties().Len(), schema.GetPatternProperties().All()), + AdditionalProperties: Subschema{m: schema.AdditionalProperties}, PropertyNames: Subschema{m: schema.PropertyNames}, + UnevaluatedProperties: Subschema{m: schema.UnevaluatedProperties}, Required: schema.Required, + MinProperties: schema.MinProperties, MaxProperties: schema.MaxProperties, Discriminator: discriminatorOf(schema.Discriminator, schemaPointer)} } -// discriminatorOf returns what d says, read where the walk reads it: under -// the schema read at at, a position the bindings know only where at is not -// the zero one. -func discriminatorOf(d *oas3.Discriminator, at reftable.DocumentPointer) *Discriminator { - if d == nil { +// discriminatorOf returns what discriminator says, read where the walk reads +// it: under the schema read at schemaPointer, a position the bindings know +// only where schemaPointer is not the zero one. +func discriminatorOf(discriminator *oas3.Discriminator, schemaPointer reftable.DocumentPointer) *Discriminator { + if discriminator == nil { return nil } - out := &Discriminator{PropertyName: d.GetPropertyName(), DefaultMapping: d.GetDefaultMapping(), - Node: nodeview.Deref(d.GetRootNode()), Unknown: d.GetCore().GetUnknownProperties(), - Extensions: listedExtensions(d.GetExtensions().Len(), d.GetExtensions().All())} - if at != (reftable.DocumentPointer{}) { - out.At = reftable.DocumentPointer{Doc: at.Doc, Pointer: at.Pointer + "/discriminator"} + out := &Discriminator{PropertyName: discriminator.GetPropertyName(), DefaultMapping: discriminator.GetDefaultMapping(), + Node: nodeview.Deref(discriminator.GetRootNode()), Unknown: discriminator.GetCore().GetUnknownProperties(), + Extensions: listedExtensions(discriminator.GetExtensions().Len(), discriminator.GetExtensions().All())} + if schemaPointer != (reftable.DocumentPointer{}) { + out.At = reftable.DocumentPointer{Doc: schemaPointer.Doc, Pointer: schemaPointer.Pointer + "/discriminator"} } - if n := d.GetMapping().Len(); n > 0 { - out.Mapping = make([]MappingEntry, 0, n) - for value, target := range d.GetMapping().All() { + if count := discriminator.GetMapping().Len(); count > 0 { + out.Mapping = make([]MappingEntry, 0, count) + for value, target := range discriminator.GetMapping().All() { out.Mapping = append(out.Mapping, MappingEntry{Value: value, Target: target}) } } return out } -// choiceOf returns what m's oneOf and anyOf say, nil where it holds neither. -func choiceOf(m *oas3.Schema) *Choice { - if m.OneOf == nil && m.AnyOf == nil { +// choiceOf returns what schema's oneOf and anyOf say, nil where it holds +// neither. +func choiceOf(schema *oas3.Schema) *Choice { + if schema.OneOf == nil && schema.AnyOf == nil { return nil } - return &Choice{OneOf: listed(m.OneOf), AnyOf: listed(m.AnyOf)} + return &Choice{OneOf: listed(schema.OneOf), AnyOf: listed(schema.AnyOf)} } -// logicOf returns what m's in-place applicators say, nil where it holds none -// of them. -func logicOf(m *oas3.Schema) *Logic { - if m.Not == nil && m.If == nil && m.Then == nil && m.Else == nil && m.DependentSchemas == nil { +// logicOf returns what schema's in-place applicators say, nil where it holds +// none of them. +func logicOf(schema *oas3.Schema) *Logic { + if schema.Not == nil && schema.If == nil && schema.Then == nil && schema.Else == nil && schema.DependentSchemas == nil { return nil } - return &Logic{Not: Subschema{m: m.Not}, If: Subschema{m: m.If}, Then: Subschema{m: m.Then}, Else: Subschema{m: m.Else}, - DependentSchemas: named(m.GetDependentSchemas().Len(), m.GetDependentSchemas().All())} + return &Logic{Not: Subschema{m: schema.Not}, If: Subschema{m: schema.If}, Then: Subschema{m: schema.Then}, Else: Subschema{m: schema.Else}, + DependentSchemas: named(schema.GetDependentSchemas().Len(), schema.GetDependentSchemas().All())} } -// notesOf returns what m says of itself, nil where it holds none of it. -func notesOf(m *oas3.Schema) *Notes { - if m.Title == nil && m.Description == nil && m.Default == nil && m.Example == nil && m.Examples == nil && - m.Deprecated == nil && m.ReadOnly == nil && m.WriteOnly == nil && m.XML == nil && m.ExternalDocs == nil { +// notesOf returns what schema says of itself, nil where it holds none of it. +func notesOf(schema *oas3.Schema) *Notes { + if schema.Title == nil && schema.Description == nil && schema.Default == nil && schema.Example == nil && schema.Examples == nil && + schema.Deprecated == nil && schema.ReadOnly == nil && schema.WriteOnly == nil && schema.XML == nil && schema.ExternalDocs == nil { return nil } - return &Notes{Title: m.GetTitle(), Description: m.GetDescription(), Default: m.Default, Example: m.Example, - Examples: m.Examples, Deprecated: m.Deprecated, ReadOnly: m.ReadOnly, WriteOnly: m.WriteOnly, - XML: xmlOf(m.XML), ExternalDocs: externalDocsOf(m.ExternalDocs)} + return &Notes{Title: schema.GetTitle(), Description: schema.GetDescription(), Default: schema.Default, Example: schema.Example, + Examples: schema.Examples, Deprecated: schema.Deprecated, ReadOnly: schema.ReadOnly, WriteOnly: schema.WriteOnly, + XML: xmlOf(schema.XML), ExternalDocs: externalDocsOf(schema.ExternalDocs)} } -// xmlOf returns what x says. -func xmlOf(x *oas3.XML) *XML { - if x == nil { +// xmlOf returns what xml says. +func xmlOf(xml *oas3.XML) *XML { + if xml == nil { return nil } - return &XML{Name: x.Name, Namespace: x.Namespace, Prefix: x.Prefix, Attribute: x.Attribute, Wrapped: x.Wrapped, - Node: nodeview.Deref(x.GetRootNode()), Unknown: x.GetCore().GetUnknownProperties(), - Extensions: listedExtensions(x.GetExtensions().Len(), x.GetExtensions().All())} + return &XML{Name: xml.Name, Namespace: xml.Namespace, Prefix: xml.Prefix, Attribute: xml.Attribute, Wrapped: xml.Wrapped, + Node: nodeview.Deref(xml.GetRootNode()), Unknown: xml.GetCore().GetUnknownProperties(), + Extensions: listedExtensions(xml.GetExtensions().Len(), xml.GetExtensions().All())} } -// externalDocsOf returns what d says. -func externalDocsOf(d *oas3.ExternalDocumentation) *ExternalDocs { - if d == nil { +// externalDocsOf returns what externalDocumentation says. +func externalDocsOf(externalDocumentation *oas3.ExternalDocumentation) *ExternalDocs { + if externalDocumentation == nil { return nil } - return &ExternalDocs{Description: d.GetDescription(), URL: d.GetURL(), Node: nodeview.Deref(d.GetRootNode()), - Unknown: d.GetCore().GetUnknownProperties(), - Extensions: listedExtensions(d.GetExtensions().Len(), d.GetExtensions().All())} + return &ExternalDocs{Description: externalDocumentation.GetDescription(), URL: externalDocumentation.GetURL(), Node: nodeview.Deref(externalDocumentation.GetRootNode()), + Unknown: externalDocumentation.GetCore().GetUnknownProperties(), + Extensions: listedExtensions(externalDocumentation.GetExtensions().Len(), externalDocumentation.GetExtensions().All())} } // listed returns the schemas of a list keyword, each at its index. @@ -558,27 +568,28 @@ func listed(list []*model) []Subschema { return out } -// listedExtensions returns the n extensions all yields, in its order, nil for -// none. They are the model's past nodeview.MergeDepthLimit too, which -// listedOnly leaves, so the list names a key merged in there, which Keys lack. -func listedExtensions(n int, all iter.Seq2[string, *yaml.Node]) []Extension { - if n == 0 { +// listedExtensions returns the extensions all yields, count of them, in its +// order, nil for none. They are the model's past nodeview.MergeDepthLimit too, +// which listedOnly leaves, so the list names a key merged in there, which Keys +// lack. +func listedExtensions(count int, all iter.Seq2[string, *yaml.Node]) []Extension { + if count == 0 { return nil } - out := make([]Extension, 0, n) + out := make([]Extension, 0, count) for name, node := range all { out = append(out, Extension{Name: name, Node: node}) } return out } -// named returns the n schemas of a mapping keyword, each under its name, in -// source order. -func named(n int, all iter.Seq2[string, *model]) []Subschema { - if n == 0 { +// named returns the schemas of a mapping keyword all yields, count of them, +// each under its name, in source order. +func named(count int, all iter.Seq2[string, *model]) []Subschema { + if count == 0 { return nil } - out := make([]Subschema, 0, n) + out := make([]Subschema, 0, count) for name, js := range all { out = append(out, Subschema{Name: name, m: js}) } diff --git a/compilers/openapi/internal/statement/model_test.go b/compilers/openapi/internal/statement/model_test.go index 8bfad240e..80f918d1a 100644 --- a/compilers/openapi/internal/statement/model_test.go +++ b/compilers/openapi/internal/statement/model_test.go @@ -36,9 +36,9 @@ func text(node *yaml.Node) string { } // texts returns the scalars ns spell. -func texts(ns []*yaml.Node) []string { - out := make([]string, len(ns)) - for i, node := range ns { +func texts(namespace []*yaml.Node) []string { + out := make([]string, len(namespace)) + for i, node := range namespace { out[i] = text(node) } return out @@ -272,9 +272,9 @@ func TestRead_ANullKeywordIsWrittenAndLeftOut(t *testing.T) { } leftOut := func(st *statement.Statement, key string) { t.Helper() - keyValue, read := st.Key(key) + readKey, read := st.Key(key) assert.False(t, read, key) - assert.True(t, keyValue.Null, key) + assert.True(t, readKey.WritesNull(), key) } described := at("/components/schemas/Described") @@ -305,7 +305,7 @@ func TestRead_ANullKeywordIsWrittenAndLeftOut(t *testing.T) { constant := at("/components/schemas/Values/properties/c") otherKey, read := constant.Key("const") assert.True(t, read, "a null const is the instance it holds") - assert.True(t, otherKey.Null) + assert.True(t, otherKey.WritesNull()) require.NotNil(t, constant.Values) } @@ -355,11 +355,11 @@ func TestRead_AKeywordMergedPastTheBoundHasNoKeyAndNoValue(t *testing.T) { assert.False(t, found, "a property merged past the bound is no property") for _, name := range []string{"L", "N"} { - schemaStatementValue := table.At(component(loweringContext, name)) - assert.True(t, schemaStatementValue.Truncated, name) - require.NotNil(t, schemaStatementValue.Notes, name) - assert.Equal(t, "S", schemaStatementValue.Notes.Title, "%s: a source within the bound is read", name) - assert.Nil(t, schemaStatementValue.Kinds, name) + schemaStatement := table.At(component(loweringContext, name)) + assert.True(t, schemaStatement.Truncated, name) + require.NotNil(t, schemaStatement.Notes, name) + assert.Equal(t, "S", schemaStatement.Notes.Title, "%s: a source within the bound is read", name) + assert.Nil(t, schemaStatement.Kinds, name) } twice := table.At(component(loweringContext, "R")) assert.True(t, twice.Truncated, "one path to the anchor runs past the bound") @@ -495,12 +495,12 @@ func TestRead_ListsExtensionsAsTheModelHoldsThem(t *testing.T) { assert.Equal(t, []string{"x-x"}, extensionNames(schemaStatement.Notes.XML.Extensions), "an xml object's, past the bound") assert.Nil(t, nodeview.Child(schemaStatement.Notes.XML.Node, "x-x"), "which its node does not reach") - schemaStatementValue := table.At(component(loweringContext, "O")) - assert.Equal(t, []string{"x-b", "x-a"}, extensionNames(schemaStatementValue.Extensions), "in source order") - assert.Equal(t, "2", text(schemaStatementValue.Extensions[1].Node)) - assert.Equal(t, []string{"x-y", "x-w"}, extensionNames(schemaStatementValue.Notes.XML.Extensions)) - assert.Equal(t, []string{"x-d"}, extensionNames(schemaStatementValue.Object.Discriminator.Extensions)) - assert.Equal(t, []string{"x-e"}, extensionNames(schemaStatementValue.Notes.ExternalDocs.Extensions)) + lowered := table.At(component(loweringContext, "O")) + assert.Equal(t, []string{"x-b", "x-a"}, extensionNames(lowered.Extensions), "in source order") + assert.Equal(t, "2", text(lowered.Extensions[1].Node)) + assert.Equal(t, []string{"x-y", "x-w"}, extensionNames(lowered.Notes.XML.Extensions)) + assert.Equal(t, []string{"x-d"}, extensionNames(lowered.Object.Discriminator.Extensions)) + assert.Equal(t, []string{"x-e"}, extensionNames(lowered.Notes.ExternalDocs.Extensions)) assert.Nil(t, table.At(component(loweringContext, "Absent")).Extensions) } @@ -617,9 +617,9 @@ func TestRead_AnExclusiveBoundHoldsTheArmTheModelRead(t *testing.T) { assert.Equal(t, statement.ExclusiveTrue, schemaStatement.Number.ExclusiveMinimumForm) assert.Equal(t, statement.ExclusiveFalse, schemaStatement.Number.ExclusiveMaximumForm) assert.Equal(t, "5", text(schemaStatement.Number.Minimum)) - schemaStatementValue := flags.At(component(fc, "M")) - require.NotNil(t, schemaStatementValue.Number, "a key opens the slot") - assert.Equal(t, statement.NoExclusive, schemaStatementValue.Number.ExclusiveMinimumForm) + lowered := flags.At(component(fc, "M")) + require.NotNil(t, lowered.Number, "a key opens the slot") + assert.Equal(t, statement.NoExclusive, lowered.Number.ExclusiveMinimumForm) bounds, bc := tableOver(t, document("3.1.0", `B: {exclusiveMinimum: 5}`), rulesAt(t, "3.1.0", "")) b := bounds.At(component(bc, "B")) diff --git a/compilers/openapi/internal/statement/pastbound_test.go b/compilers/openapi/internal/statement/pastbound_test.go index c636dec0a..197dedc60 100644 --- a/compilers/openapi/internal/statement/pastbound_test.go +++ b/compilers/openapi/internal/statement/pastbound_test.go @@ -34,13 +34,13 @@ const pastBoundReport = "the schema merges through `<<` deeper than" // what beside writes, with the other components extra writes. At n // nodeview.MergeDepthLimit-1, P merges through as many `<<` as the bound // expands; at n nodeview.MergeDepthLimit, one more. -func chained(version string, n int, leaf, beside, extra string) string { +func chained(version string, count int, leaf, beside, extra string) string { var b strings.Builder fmt.Fprintf(&b, "openapi: %s\ninfo: {title: t, version: '1'}\npaths: {}\nx-c0: &c0 %s\n", version, leaf) - for i := 1; i <= n; i++ { + for i := 1; i <= count; i++ { fmt.Fprintf(&b, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) } - fmt.Fprintf(&b, "components:\n schemas:\n P: {<<: *c%d, %s}\n", n, beside) + fmt.Fprintf(&b, "components:\n schemas:\n P: {<<: *c%d, %s}\n", count, beside) if extra != "" { b.WriteString(" " + extra + "\n") } @@ -60,9 +60,9 @@ func compileP(t *testing.T, spec string) compiledP { doc, diags, err := openapi.New().Compile(t.Context(), []compilers.Source{openapitest.SourceOf(spec)}, compilers.Options{}) require.NoError(t, err) types := ir.TypeRegistry{} - for id, td := range doc.Types { + for id, typeDef := range doc.Types { if strings.Contains(string(id), "/components/schemas/P") { - types[id] = td + types[id] = typeDef } } raw, err := json.Marshal(types, json.Deterministic(true)) @@ -93,11 +93,11 @@ func pastBoundReports(diags []ir.Diagnostic, pointer string) int { // withoutReport returns compiledPValue without the warning that P merges past // the bound. -func withoutReport(compiledPValue compiledP) compiledP { - compiledPValue.diags = slices.DeleteFunc(slices.Clone(compiledPValue.diags), func(d string) bool { +func withoutReport(compiledP compiledP) compiledP { + compiledP.diags = slices.DeleteFunc(slices.Clone(compiledP.diags), func(d string) bool { return strings.Contains(d, pastBoundReport) }) - return compiledPValue + return compiledP } // keywordSample is a leaf writing one keyword, what P writes beside the merge @@ -184,8 +184,8 @@ func TestRead_PastTheMergeBoundNoKeywordIsHalfRead(t *testing.T) { for keyword, keywordSample := range keywordSamples { t.Run(keyword, func(t *testing.T) { t.Parallel() - at := func(n int, leaf string) compiledP { - return compileP(t, chained(keywordSample.version, n, leaf, keywordSample.beside, keywordSample.extra)) + at := func(count int, leaf string) compiledP { + return compileP(t, chained(keywordSample.version, count, leaf, keywordSample.beside, keywordSample.extra)) } written := at(0, keywordSample.leaf) require.NotEqual(t, at(0, "{}"), written, "the sample changes what P compiles to") @@ -328,12 +328,12 @@ func TestRead_PastTheMergeBoundEachReaderReadsNeither(t *testing.T) { "type: array, unevaluatedItems: false", ""}}, {"annotation.inertBeside, additionalProperties", keywordSample{"3.1.0", "{additionalProperties: true}", "type: object, unevaluatedProperties: false", ""}}, - {"schema.declaresValidationOnly", keywordSample{"3.1.0", "{not: {type: integer}}", "type: string", ""}}, + {"annotation.ReadKeeps", keywordSample{"3.1.0", "{not: {type: integer}}", "type: string", ""}}, {"schema.bodyReading.keysRestate", keywordSample{"3.1.0", "{properties: {a: {type: string}}}", "allOf: [{$ref: '#/components/schemas/L'}]", "L: {type: object, properties: {a: {type: string}}}"}}, {"schema.keepUnread", keywordSample{"3.1.0", "{required: [a], additionalProperties: false}", "properties: {a: {type: string}}", ""}}, - {"schema.branchesSay", keywordSample{"3.1.0", "{oneOf: [{type: string}, {type: integer}]}", + {"schema.keywordsBranchesRestate", keywordSample{"3.1.0", "{oneOf: [{type: string}, {type: integer}]}", "type: [string, integer]", ""}}, {"schema.nullableTrue, 3.0 true", keywordSample{"3.0.3", "{nullable: true}", "type: string", ""}}, {"schema.nullableTrue, 3.0 a word", keywordSample{"3.0.3", "{nullable: 'yes'}", "type: string", ""}}, @@ -359,8 +359,8 @@ func TestRead_PastTheMergeBoundEachReaderReadsNeither(t *testing.T) { // for outranked. A keyword added to the fill without its node fails here. func TestFillKeywords_EachComparesTheNodeTheParserReadItFrom(t *testing.T) { t.Parallel() - m := &oas3.Schema{} - core := reflect.ValueOf(m.GetCore()).Elem() + schema := &oas3.Schema{} + core := reflect.ValueOf(schema.GetCore()).Elem() fields := map[string]reflect.Value{} for i := range core.NumField() { if key := core.Type().Field(i).Tag.Get("key"); key != "" { @@ -378,7 +378,7 @@ func TestFillKeywords_EachComparesTheNodeTheParserReadItFrom(t *testing.T) { require.NotNil(t, node, "%s: the parser holds the node it read", name) read := &yaml.Node{Kind: yaml.ScalarNode, Value: name} field.FieldByName("ValueNode").Set(reflect.ValueOf(read)) - assert.Same(t, read, node(m), name) + assert.Same(t, read, node(schema), name) } } @@ -402,7 +402,7 @@ func outranking(version, deep, listed, beside string, deepFirst bool) string { // Where the source past the bound comes first, it outranks the listed key, // which is then not read, and the schema compiles as with neither source // writing the keyword; where the listed source comes first, it is read as -// written. A listed key equal to the value it loses to is left out too. +// written. A listed key equal to the value chosen over it is left out too. func TestRead_PastTheMergeBoundAnOutrankedKeyIsLeftOut(t *testing.T) { t.Parallel() type outranks struct { @@ -481,15 +481,15 @@ func TestRead_PastTheMergeBoundAKeyNoParserNodeTellsStaysOnlyWhereWritten(t *tes // bodySpec writes a document whose one operation takes an octet-stream body // merging, beside what beside writes, a chain of n anchors whose first writes // leaf, as chained does for a component. -func bodySpec(n int, leaf, beside string) string { +func bodySpec(count int, leaf, beside string) string { var b strings.Builder fmt.Fprintf(&b, "openapi: 3.1.0\ninfo: {title: t, version: '1'}\nx-c0: &c0 %s\n", leaf) - for i := 1; i <= n; i++ { + for i := 1; i <= count; i++ { fmt.Fprintf(&b, "x-c%d: &c%d {<<: *c%d}\n", i, i, i-1) } fmt.Fprintf(&b, "paths:\n /u:\n post:\n requestBody:\n content:\n"+ " application/octet-stream: {schema: {<<: *c%d, %s}}\n"+ - " responses: {'204': {description: ok}}\n", n, beside) + " responses: {'204': {description: ok}}\n", count, beside) return b.String() } @@ -502,9 +502,9 @@ func compileBody(t *testing.T, spec string) string { operation := openapitest.FirstOperation(t, doc.Services[0]) require.NotNil(t, operation.Request) types := ir.TypeRegistry{} - for id, td := range doc.Types { + for id, typeDef := range doc.Types { if strings.Contains(string(id), "/requestBody/") { - types[id] = td + types[id] = typeDef } } raw, err := json.Marshal(struct { diff --git a/compilers/openapi/internal/statement/statement.go b/compilers/openapi/internal/statement/statement.go index b6604fe55..e4d82120b 100644 --- a/compilers/openapi/internal/statement/statement.go +++ b/compilers/openapi/internal/statement/statement.go @@ -105,6 +105,9 @@ type Schema struct { of *Statement Truth SchemaValueForm + // partial marks a schema read less some of the keys it writes + // (MemoizingSchemaReader.Without), which the parser's model still holds. + partial bool // Truncated marks a schema whose `<<` merges run past // nodeview.MergeDepthLimit: Keys lack what the merges past it bring, and // so does every typed value (docs/parser-library.md#merge-keys). @@ -146,16 +149,16 @@ func (s *Schema) find(name string) (place, compared int) { // Key is one key a schema object writes: its name, its value with its alias // followed, the slot the rows it is read with place it in and whether they -// define it only later (specrules.SchemaRules.Slot), whether its value is null, -// and whether the parser's model holds it. The census of unknown keywords reads -// Schema.Unknown and not this, as a key merged in past nodeview.MergeDepthLimit -// is no Key. +// define it only later (specrules.SchemaRules.Slot), the form its value takes +// (specrules.SchemaRules.FormOf), and whether the parser's model holds it. The +// census of unknown keywords reads Schema.Unknown and not this, as a key +// merged in past nodeview.MergeDepthLimit is no Key. type Key struct { Name string Node *yaml.Node Slot specrules.Slot DefinedOnlyInLaterMinor bool - Null bool + Form specrules.ValueForm Modeled bool } @@ -163,21 +166,27 @@ type Key struct { // they do not for an extension or a keyword of another dialect. func (k Key) Defined() bool { return k.Slot != specrules.SlotUnknown } -// read reports whether the key's value is read: any but a null, which is -// read only where the keyword holds an instance. +// WritesNull reports whether the key's value is a null. +func (k Key) WritesNull() bool { return k.Form == specrules.ValueNull } + +// EquatesToAbsence reports whether the key's value is the one its keyword +// equates with its absence (specrules.SchemaRules.EquatesToAbsence). +func (k Key) EquatesToAbsence() bool { return k.Form == specrules.ValueEquatesToAbsence } + +// read reports whether the key's value is read (specrules.ValueIsRead), as +// every reader of a schema's keys reads it. func (k Key) read() bool { - return !k.Null || k.Name == "const" || k.Name == "default" || k.Name == "example" + return specrules.ValueIsRead(k.Name, k.Defined(), k.Form) } -// ReadBeside reports whether a key named name, holding value, written beside a -// reference under keyword, says something of the instance the schema applies -// to, which makes the object the conjunction of the two -// (MemoizingSchemaReader.Of): any key but keyword's own whose value is read -// (docs/compilers/openapi.md#null-keywords), and none that only names the -// schema, holds schemas a reference reaches or comments, which the lowering -// drops (docs/compilers/openapi.md#dialect-keywords). -func ReadBeside(name string, value *yaml.Node, keyword string) bool { - return name != keyword && !slices.Contains(keysThatConstrainNoInstance, name) && Key{Name: name, Null: isNull(value)}.read() +// ReadBeside reports whether key, written beside a reference under keyword, +// says something of the instance the schema applies to, which makes the object +// the conjunction of the two (MemoizingSchemaReader.Of): any key but keyword's +// own whose value is read (docs/compilers/openapi.md#null-keywords), and none +// that only names the schema, holds schemas a reference reaches or comments, +// which the lowering drops (docs/compilers/openapi.md#dialect-keywords). +func ReadBeside(key Key, keyword string) bool { + return key.Name != keyword && !slices.Contains(keysThatConstrainNoInstance, key.Name) && key.read() } // keysThatConstrainNoInstance are the keys that say nothing of the instance @@ -185,6 +194,22 @@ func ReadBeside(name string, value *yaml.Node, keyword string) bool { // reaches. var keysThatConstrainNoInstance = []string{"$comment", "$anchor", "$dynamicAnchor", "$recursiveAnchor", "$defs", "definitions"} +// WritesOnlyIdentifierAndMetaKeywords reports whether s, a schema object, +// writes no key but identifier and meta keywords its rows define (`$id`, `id`, +// `$schema`, the anchors, `$vocabulary`, `$comment`, `$defs`, `definitions`), +// a key read as left out aside: it admits every instance and states nothing a +// kind is inferred from. A schema whose merges run past their limit may write +// what its keys lack. +func (s *Schema) WritesOnlyIdentifierAndMetaKeywords() bool { + if s == nil || s.Truth != Stated || s.Truncated || len(s.Extensions) > 0 { + return false + } + return !slices.ContainsFunc(s.Keys, func(key Key) bool { + saysNothing := key.Slot == specrules.SlotResource || key.Slot == specrules.SlotNotes && key.Name == "$comment" + return key.read() && !saysNothing + }) +} + // Extension is one x- key an object writes and its value, in the order the // parser's model holds them: in source order, a key written twice once. type Extension struct { diff --git a/compilers/openapi/internal/statement/statement_test.go b/compilers/openapi/internal/statement/statement_test.go index de59a4869..a66686b9a 100644 --- a/compilers/openapi/internal/statement/statement_test.go +++ b/compilers/openapi/internal/statement/statement_test.go @@ -16,9 +16,9 @@ import ( ) // wide returns a component W writing n extension keys, x-0 to x-(n-1). -func wide(n int) string { - keys := make([]string, n) - for i := range n { +func wide(count int) string { + keys := make([]string, count) + for i := range count { keys[i] = fmt.Sprintf("x-%d: %d", i, i) } return document("3.1.0", "W: {"+strings.Join(keys, ", ")+"}") @@ -47,7 +47,7 @@ func TestSchema_KeyOnAWideObjectScansNothing(t *testing.T) { } // TestSchema_KeyReadsANullKeywordAsLeftOut pins the one reading a null keyword -// has, which every keeper goes through, and the three keywords whose value is +// has, which every keep goes through, and the three keywords whose value is // an instance, where a null is that value // (docs/compilers/openapi.md#null-keywords). func TestSchema_KeyReadsANullKeywordAsLeftOut(t *testing.T) { @@ -59,7 +59,7 @@ func TestSchema_KeyReadsANullKeywordAsLeftOut(t *testing.T) { for _, keyword := range []string{"maxLength", "format", "$id"} { key, read := a.Key(keyword) assert.False(t, read, keyword) - assert.True(t, key.Null, "%s is written", keyword) + assert.True(t, key.WritesNull(), "%s is written", keyword) } for _, keyword := range []string{"const", "default", "example"} { key, read := a.Key(keyword) @@ -70,6 +70,56 @@ func TestSchema_KeyReadsANullKeywordAsLeftOut(t *testing.T) { assert.True(t, read) } +// TestSchema_KeyTellsAValueEquatingToAbsence pins the says-nothing reading +// (docs/compilers/openapi.md#null-keywords): a keyword written at the value +// JSON Schema or OpenAPI equates with its absence, in a dialect defining it, +// is read by no reader, as the keyword left out is, and says nothing beside a +// $ref, while any other value, an applicator's among them, is read and does. +// A null on a key no dialect defines is a value. +func TestSchema_KeyTellsAValueEquatingToAbsence(t *testing.T) { + t.Parallel() + const draft04 = "http://json-schema.org/draft-04/schema#" + for _, tc := range []struct { + version, named, schema string + leftOut, read []string + }{ + {"3.1.0", "", "{readOnly: false, writeOnly: false, deprecated: false, uniqueItems: false, minLength: 0, " + + "minItems: 0, minProperties: 0, required: [], pattern: ''}", + []string{"readOnly", "writeOnly", "deprecated", "uniqueItems", "minLength", "minItems", "minProperties", + "required", "pattern"}, nil}, + {"3.1.0", "", "{format: '', additionalProperties: true, readOnly: true, minLength: 1, required: [a], " + + "nullable: false, exclusiveMinimum: 0, foo: null, x-a: null, nullable2: ~}", nil, + []string{"format", "additionalProperties", "readOnly", "minLength", "required", "nullable", + "exclusiveMinimum", "foo", "x-a", "nullable2"}}, + {"3.0.3", "", "{nullable: false, exclusiveMinimum: false, exclusiveMaximum: false, readOnly: false, minItems: 0.0}", + []string{"nullable", "exclusiveMinimum", "exclusiveMaximum", "readOnly", "minItems"}, nil}, + {"3.0.3", "", "{required: [], nullable: true, exclusiveMinimum: true}", nil, + []string{"required", "nullable", "exclusiveMinimum"}}, + {"3.1.0", draft04, "{exclusiveMinimum: false, minimum: 1}", []string{"exclusiveMinimum"}, []string{"minimum"}}, + {"3.1.0", draft04, "{required: []}", nil, []string{"required"}}, + } { + src := document(tc.version, "A: "+tc.schema) + if tc.named != "" { + src = "jsonSchemaDialect: '" + tc.named + "'\n" + src + } + table, loweringContext := tableOver(t, src, rulesAt(t, tc.version, tc.named)) + a := table.At(component(loweringContext, "A")) + for _, keyword := range tc.leftOut { + key, read := a.Key(keyword) + assert.False(t, read, "%s %s: %s is read as left out", tc.version, tc.named, keyword) + assert.Equal(t, keyword, key.Name, "%s %s: %s is written", tc.version, tc.named, keyword) + assert.True(t, key.EquatesToAbsence(), "%s %s: %s says nothing", tc.version, tc.named, keyword) + assert.False(t, statement.ReadBeside(key, "$ref"), "%s %s: %s says nothing beside a $ref", tc.version, tc.named, keyword) + } + for _, keyword := range tc.read { + key, read := a.Key(keyword) + assert.True(t, read, "%s %s: %s is read", tc.version, tc.named, keyword) + assert.False(t, key.EquatesToAbsence(), "%s %s: %s", tc.version, tc.named, keyword) + assert.True(t, statement.ReadBeside(key, "$ref"), "%s %s: %s says something beside a $ref", tc.version, tc.named, keyword) + } + } +} + // TestSchema_KeyReadsAKeywordAsTheParserDoes pins the keys every verbatim // keyword and every bound is read from beside the model: a keyword merged in // through `<<` and one written through an alias key are read (GitHub #395, @@ -121,9 +171,9 @@ func TestKey_DefinedTellsAKeywordTheRowsDefine(t *testing.T) { table, loweringContext := tableOver(t, src, rulesAt(t, "3.1.0", tc.named)) a := table.At(component(loweringContext, "A")) for key, want := range tc.want { - keyValue, read := a.Key(key) + readKey, read := a.Key(key) require.True(t, read, key) - assert.Equal(t, want, keyValue.Defined(), "%q reading %q", key, tc.named) + assert.Equal(t, want, readKey.Defined(), "%q reading %q", key, tc.named) } } } diff --git a/compilers/openapi/internal/statement/table.go b/compilers/openapi/internal/statement/table.go index 9f7adc21a..952ccd5bf 100644 --- a/compilers/openapi/internal/statement/table.go +++ b/compilers/openapi/internal/statement/table.go @@ -39,6 +39,15 @@ type MemoizingSchemaReader struct { // writing a reference beside keys it reads (conjoins), each built once: // the keys as an allOf entry reads them, and the reference. besideRefs, references map[*Schema]*Schema + // without holds each schema read less some of its keys (Without), built + // once per schema and set of keys. + without map[withoutKey]*Schema + // expansions holds the reference each schema object writing a dynamic + // one makes once expanded (Expansion), built once. + expansions map[*Schema]*Schema + // conjoined holds each conjunction of a position with one branch of its + // union (Conjoined), built once. + conjoined map[conjoinedKey]*Statement // reads counts the schema objects read, which the tests hold to one each, // and lookups the statements Of looks up, which they hold Read to none of // for a schema Of has built the statement of. @@ -50,10 +59,90 @@ type MemoizingSchemaReader struct { func NewTable(src Source) *MemoizingSchemaReader { return &MemoizingSchemaReader{ src: src, schemas: map[*model]*Schema{}, statements: map[*model]*Statement{}, - besideRefs: map[*Schema]*Schema{}, references: map[*Schema]*Schema{}, + besideRefs: map[*Schema]*Schema{}, references: map[*Schema]*Schema{}, without: map[withoutKey]*Schema{}, + expansions: map[*Schema]*Schema{}, conjoined: map[conjoinedKey]*Statement{}, } } +// withoutKey names a schema read less some of its keys: the schema, and the +// keys, in the order it writes them, joined by a byte no key can hold. +type withoutKey struct { + schema *Schema + keys string +} + +// Without returns schema read less each key names, schema itself where it +// writes none of them: a copy read as a schema written with the other keys +// alone would be, with a statement of its own listing no entry. A reader handed +// it reads none of the keys left out, as an allOf entry folding only what its +// conjuncts agree on is read (docs/compilers/openapi.md#allof-inline-residue). +// It is built once per schema and set of keys. +func (t *MemoizingSchemaReader) Without(schema *Schema, names []string) *Schema { + var left []string + for _, key := range schema.Keys { + if slices.Contains(names, key.Name) { + left = append(left, key.Name) + } + } + if len(left) == 0 { + return schema + } + key := withoutKey{schema: schema, keys: strings.Join(left, "\x00")} + if held, ok := t.without[key]; ok { + return held + } + less := *schema + less.of, less.Ref, less.BesideRef, less.WrittenBeside = nil, nil, nil, nil + named := func(name string) bool { return slices.Contains(left, name) } + less.Keys = slices.DeleteFunc(slices.Clone(schema.Keys), func(key Key) bool { return named(key.Name) }) + less.Extensions = slices.DeleteFunc(slices.Clone(schema.Extensions), func(extension Extension) bool { return named(extension.Name) }) + less.Unknown = slices.DeleteFunc(slices.Clone(schema.Unknown), named) + less.partial = true + index(&less) + content := make([]*yaml.Node, 0, 2*len(less.Keys)) + for _, key := range less.Keys { + content = append(content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key.Name}, key.Node) + } + less.Node = &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: content} + less.Kinds, less.Values, less.Format, less.Number, less.Text = nil, nil, nil, nil, nil + less.Array, less.Object, less.Choice, less.Logic, less.Notes = nil, nil, nil, nil, nil + fillListed(&less) + less.of = &Statement{Schema: &less} + t.without[key] = &less + return &less +} + +// Expansion returns the statement of the reference schema makes, writing a +// dynamic one under keyword whose value is value, expanded to land on at +// (docs/compilers/openapi.md#dynamic-ref): a schema object writing it alone, +// bound to at as a $ref landing there is, which a composition takes as its +// entry as it takes a $ref's. It is built once for schema. +func (t *MemoizingSchemaReader) Expansion(schema *Schema, keyword string, value *yaml.Node, at reftable.DocumentPointer) *Statement { + if otherSchema, ok := t.expansions[schema]; ok { + return otherSchema.of + } + site := reftable.ReferenceSite{Site: schema.At, Hop: reftable.Hop{Target: at, Ref: value.Value, Status: reftable.Resolved}, Keyword: keyword} + otherSchema := &Schema{At: schema.At, Ref: &Reference{Keyword: keyword, Text: value.Value, Entry: site, Bound: true}, m: schema.m} + if i, _ := schema.find(keyword); i >= 0 { + otherSchema.Keys = []Key{schema.Keys[i]} + } + otherSchema.Node = &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{ + {Kind: yaml.ScalarNode, Tag: "!!str", Value: keyword}, value, + }} + otherSchema.of = &Statement{Schema: otherSchema} + t.expansions[schema] = otherSchema + return otherSchema.of +} + +// ReferenceTargets returns the table of the documents t's bindings read, nil +// for a nil t and for bindings that read none. +func (t *MemoizingSchemaReader) ReferenceTargets() *reftable.ReferenceTargetTable { + if t == nil { + return nil + } + return t.src.Bindings.Table() +} + // At returns the statement of the schema the bindings hold at documentPointer, // an Unwritten one where they hold none. func (t *MemoizingSchemaReader) At(documentPointer reftable.DocumentPointer) *Statement { @@ -65,13 +154,13 @@ func (t *MemoizingSchemaReader) Subschema(subschema Subschema) *Statement { return t.Of(subschema.m) } -// Read returns the statement of the schema object s, for a caller lowering -// an entry as a position of its own: the one Of built over s, which s keeps, -// so that a schema read once more costs no lookup, or, for the keywords beside -// an allOf entry's reference (besideRefOf), one listing its own allOf and no -// reference. A nil s reads as Unwritten, and so does one no table read, which -// holds no value. s is one t read: a schema another table built a statement -// over keeps that statement, whichever table is asked. +// Read returns the statement of the schema object schema, for a caller +// lowering an entry as a position of its own: the one Of built over schema, +// which schema keeps, so that a schema read once more costs no lookup, or, for +// the keywords beside an allOf entry's reference (besideRefOf), one listing its +// own allOf and no reference. A nil schema reads as Unwritten, and so does one +// no table read, which holds no value. schema is one t read: a schema another +// table built a statement over keeps that statement, whichever table is asked. func (t *MemoizingSchemaReader) Read(schema *Schema) *Statement { switch { case schema == nil: @@ -103,7 +192,8 @@ func readKeys(schema *Schema, rules specrules.SchemaRules) { schema.Keys = make([]Key, len(pairs)) for i, pair := range pairs { slot, later := rules.Slot(pair.Key) - schema.Keys[i] = Key{Name: pair.Key, Node: pair.Val, Slot: slot, DefinedOnlyInLaterMinor: later, Null: isNull(pair.Val), Modeled: true} + schema.Keys[i] = Key{Name: pair.Key, Node: pair.Val, Slot: slot, DefinedOnlyInLaterMinor: later, + Form: rules.FormOf(pair.Key, pair.Val), Modeled: true} } index(schema) for _, name := range schema.Unknown { @@ -136,26 +226,38 @@ func index(schema *Schema) { // each entry's schema object and never an entry's statement, so it adds no // recursion. func (t *MemoizingSchemaReader) flatten(st *Statement) { + t.flattenFrom(st, st.AllOf, nil) +} + +// flattenFrom appends to st's entries those of list, each flattened as flatten +// flattens an allOf entry, the first of the lists it walks: its entry i is +// written at rels[i] below st's schema where rels names one each, and at +// /allOf/ where rels is nil. +func (t *MemoizingSchemaReader) flattenFrom(st *Statement, list []Subschema, rels []jsontext.Pointer) { type frame struct { list []Subschema + rels []jsontext.Pointer next int owner *Schema rel jsontext.Pointer } - stack := []frame{{list: st.AllOf}} + stack := []frame{{list: list, rels: rels}} for len(stack) > 0 { - frameValue := &stack[len(stack)-1] - if frameValue.next == len(frameValue.list) { - owner, rel := frameValue.owner, frameValue.rel + top := &stack[len(stack)-1] + if top.next == len(top.list) { + owner, rel := top.owner, top.rel stack = stack[:len(stack)-1] if owner != nil { st.Entries = append(st.Entries, AllOfConjunct{Schema: owner, Rel: rel, Wrapper: true}) } continue } - entry := t.read(frameValue.list[frameValue.next].m) - rel := frameValue.rel + "/allOf/" + jsontext.Pointer(strconv.Itoa(frameValue.next)) - frameValue.next++ + entry := t.read(top.list[top.next].m) + rel := top.rel + "/allOf/" + jsontext.Pointer(strconv.Itoa(top.next)) + if top.rels != nil { + rel = top.rels[top.next] + } + top.next++ if conjoins(entry) { st.Entries = append(st.Entries, AllOfConjunct{Schema: t.reference(entry), Rel: rel, Split: true}) entry = t.besideRefOf(entry) @@ -169,41 +271,76 @@ func (t *MemoizingSchemaReader) flatten(st *Statement) { } } -// conjoins reports whether s writes a reference and a key beside it that it -// reads. JSON Schema applies the keywords beside a $ref to the instance with -// it (Core 2020-12 §8.2.3.1), so s says what an allOf of the two says: the -// reference is one conjunct and the keywords beside it another -// (docs/compilers/openapi.md#ref-use-site). A reference merged in past -// nodeview.MergeDepthLimit, which no key of s names, conjoins as any does. -func conjoins(schema *Schema) bool { - if schema.Truth != Stated || schema.Ref == nil || failedEntry(schema) { - return false +// Conjoined returns the statement of the allOf of position's body, less the +// keys drop names and the keywords at holder writing the union, and branch, +// one branch of that union written at rel below position. Its Rels stay +// position's, so each conjunct is read where it is written. It is built once +// per position and branch. +func (t *MemoizingSchemaReader) Conjoined(position *Schema, drop []string, holder jsontext.Pointer, branch *Statement, rel jsontext.Pointer, +) *Statement { + key := conjoinedKey{position: position, rel: rel} + if st, ok := t.conjoined[key]; ok { + return st + } + conjunction := *t.Without(position, drop) + conjunction.BesideRef, conjunction.AllOf = position.BesideRef, nil + for i, sub := range position.AllOf { + // An entry holding more than the holder stays, its union read once + // more beside the branch it lists, which admits what the branch does. + if entry := t.read(sub.m); "/allOf/"+jsontext.Pointer(strconv.Itoa(i)) != holder || conjoins(entry) || len(entry.AllOf) > 0 { + conjunction.AllOf = append(conjunction.AllOf, sub) + } + } + sub := Subschema{m: branch.m} + conjunction.AllOf = append(conjunction.AllOf, sub) + st := &Statement{Schema: &conjunction} + conjunction.of = st + for _, entry := range t.Read(position).Entries { + if holder != "" && entry.Rel == holder && entry.Ref == nil { + continue + } + if entry.Ref == nil { + entry.Schema = t.withoutBeside(entry.Schema, drop) + } + st.Entries = append(st.Entries, entry) } - return slices.ContainsFunc(schema.Keys, func(key Key) bool { return ReadBeside(key.Name, key.Node, schema.Ref.Keyword) }) + t.flattenFrom(st, []Subschema{sub}, []jsontext.Pointer{rel}) + t.conjoined[key] = st + return st } -// failedEntry reports whether schema, writing a reference, is an allOf entry -// whose reference the bindings read as ending on no schema. Such an entry is -// read whole: nothing reads what it writes beside the reference, which the -// composition keeps as the entry wrote it -// (docs/compilers/openapi.md#allof-inline-residue). Written anywhere else, the -// same object conjoins, as `{allOf: [{$ref: …}], …}` does. -func failedEntry(schema *Schema) bool { - if !schema.Ref.Bound || schema.Ref.Entry.Chain.Status == reftable.Resolved { - return false +// withoutBeside is Without for an allOf entry, which may write its keys beside +// a reference: the keys beside it read less those drop names, still naming +// that reference as written beside them (Schema.WrittenBeside). +func (t *MemoizingSchemaReader) withoutBeside(schema *Schema, drop []string) *Schema { + less := t.Without(schema, drop) + if less == schema || schema.WrittenBeside == nil { + return less } - at := string(schema.At.Pointer) - i := strings.LastIndexByte(at, '/') - if i < 0 || !strings.HasSuffix(at[:i], "/allOf") { + beside := *less + beside.WrittenBeside = schema.WrittenBeside + beside.of = &Statement{Schema: &beside} + return &beside +} + +// conjoinedKey names the conjunction of a position with the branch written at +// rel below it (Conjoined). +type conjoinedKey struct { + position *Schema + rel jsontext.Pointer +} + +// conjoins reports whether schema writes a reference and a key beside it that +// it reads. JSON Schema applies the keywords beside a $ref to the instance with +// it (Core 2020-12 §8.2.3.1), so schema says what an allOf of the two says: the +// reference is one conjunct and the keywords beside it another +// (docs/compilers/openapi.md#ref-use-site). A reference merged in past +// nodeview.MergeDepthLimit, which no key of schema names, conjoins as any does. +func conjoins(schema *Schema) bool { + if schema.Truth != Stated || schema.Ref == nil { return false } - // An entry's last token is its index: an items, a not or a property - // under a property named allOf is no entry. The schema package reads an - // entry off a pointer too, by a parse of its own that takes no signed - // index where this one does (writtenAsEntry). Neither knows how the - // schema is reached; a statement saying so replaces both (GitHub #2058). - _, err := strconv.Atoi(at[i+1:]) - return err == nil + return slices.ContainsFunc(schema.Keys, func(key Key) bool { return ReadBeside(key, schema.Ref.Keyword) }) } // refKey returns the place in schema, which writes a reference, of the key @@ -230,20 +367,20 @@ func (t *MemoizingSchemaReader) own(js *model) *Schema { // reference (lessReference), and the reference as its BesideRef: the // position's statement lists the two. Of builds it once. func (t *MemoizingSchemaReader) wordsOf(schema *Schema) *Schema { - schemaValue := lessReference(schema) - schemaValue.BesideRef = t.reference(schema) - return schemaValue + lessened := lessReference(schema) + lessened.BesideRef = t.reference(schema) + return lessened } -// besideRefOf returns s, an allOf entry that conjoins, less its reference +// besideRefOf returns schema, an allOf entry that conjoins, less its reference // (lessReference): the conjunct its composition lists after that reference, // as `{allOf: [{$ref: …}, {…}]}` lists it. It writes no reference, its node // holding its keys alone, so no reader of the composition's conjuncts reads // the reference twice; it names it WrittenBeside, for a reader of how its // keys are spelt (docs/compilers/openapi.md#ref-use-site). func (t *MemoizingSchemaReader) besideRefOf(schema *Schema) *Schema { - if schemaValue, ok := t.besideRefs[schema]; ok { - return schemaValue + if schema, ok := t.besideRefs[schema]; ok { + return schema } otherSchema := lessReference(schema) otherSchema.WrittenBeside = t.reference(schema) @@ -260,19 +397,19 @@ func (t *MemoizingSchemaReader) besideRefOf(schema *Schema) *Schema { // the one writing its reference, and every slot it fills. It shares schema's // values. func lessReference(schema *Schema) *Schema { - schemaValue := *schema - schemaValue.Ref, schemaValue.of = nil, nil - schemaValue.Keys = slices.DeleteFunc(slices.Clone(schema.Keys), func(key Key) bool { return key.Name == schema.Ref.Keyword }) - index(&schemaValue) - return &schemaValue + copied := *schema + copied.Ref, copied.of = nil, nil + copied.Keys = slices.DeleteFunc(slices.Clone(schema.Keys), func(key Key) bool { return key.Name == schema.Ref.Keyword }) + index(&copied) + return &copied } // reference returns the reference schema, which conjoins, writes, as a schema // object writing it alone, its node too, and its statement, which lists no // entry. A reference no key of schema names is read from its text. func (t *MemoizingSchemaReader) reference(schema *Schema) *Schema { - if schemaValue, ok := t.references[schema]; ok { - return schemaValue + if schema, ok := t.references[schema]; ok { + return schema } otherSchema := &Schema{At: schema.At, Ref: schema.Ref, m: schema.m} value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: schema.Ref.Text} @@ -315,9 +452,3 @@ func open(schema *Schema, slot specrules.Slot) { schema.Notes = &Notes{} } } - -// isNull reports whether node, its alias followed, is a YAML null. -func isNull(node *yaml.Node) bool { - node = nodeview.Deref(node) - return node != nil && node.Kind == yaml.ScalarNode && node.ShortTag() == "!!null" -} diff --git a/compilers/openapi/internal/statement/table_internal_test.go b/compilers/openapi/internal/statement/table_internal_test.go index 3870002ab..9d5090bc5 100644 --- a/compilers/openapi/internal/statement/table_internal_test.go +++ b/compilers/openapi/internal/statement/table_internal_test.go @@ -26,12 +26,12 @@ func TestReference_AReferenceNoKeyNamesIsReadFromItsText(t *testing.T) { require.False(t, named) assert.True(t, conjoins(schema), "the description is beside the reference wherever it was merged from") table := NewTable(Source{}) - var schemaValue *Schema - require.NotPanics(t, func() { schemaValue = table.reference(schema) }) - assert.Empty(t, schemaValue.Keys) - assert.Same(t, schema.Ref, schemaValue.Ref) - require.Len(t, schemaValue.Node.Content, 2) - assert.Equal(t, "$ref", schemaValue.Node.Content[0].Value) - assert.Equal(t, "#/components/schemas/T", schemaValue.Node.Content[1].Value) - assert.Same(t, schemaValue, table.reference(schema), "read once") + var built *Schema + require.NotPanics(t, func() { built = table.reference(schema) }) + assert.Empty(t, built.Keys) + assert.Same(t, schema.Ref, built.Ref) + require.Len(t, built.Node.Content, 2) + assert.Equal(t, "$ref", built.Node.Content[0].Value) + assert.Equal(t, "#/components/schemas/T", built.Node.Content[1].Value) + assert.Same(t, built, table.reference(schema), "read once") } diff --git a/compilers/openapi/internal/statement/table_test.go b/compilers/openapi/internal/statement/table_test.go index ed06b1351..faf5a57f2 100644 --- a/compilers/openapi/internal/statement/table_test.go +++ b/compilers/openapi/internal/statement/table_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" "github.com/dexpace/morphic/compilers/openapi/internal/dialect" "github.com/dexpace/morphic/compilers/openapi/internal/openapitest" @@ -64,8 +65,8 @@ func TestFlatten_FiveSpellingsShareTheirAtoms(t *testing.T) { // nest returns a schema writing n allOf lists one inside another, the // innermost holding leaf. -func nest(n int, leaf string) string { - return strings.Repeat("{allOf: [", n) + leaf + strings.Repeat("]}", n) +func nest(count int, leaf string) string { + return strings.Repeat("{allOf: [", count) + leaf + strings.Repeat("]}", count) } // listing renders each entry of st as its pointer and whether it is a wrapper @@ -86,7 +87,7 @@ func listing(st *statement.Statement) []string { // after its own entries, MaxFlattenDepth lists flattened and the entry one // list deeper capped, a $ref entry writing an allOf beside it listed as its // reference, the allOf's entries and then the rest as their wrapper, a -// boolean entry and one writing an empty allOf listed as they stand. +// boolean entry and one writing an empty allOf listed as they are. func TestFlatten_ListsWhatWalkAllOfLists(t *testing.T) { t.Parallel() table, loweringContext := tableOver(t, document("3.1.0", @@ -96,7 +97,7 @@ func TestFlatten_ListsWhatWalkAllOfLists(t *testing.T) { "Mixed: {allOf: [{$ref: '#/components/schemas/T', allOf: [{type: string}]}, true, {allOf: []}, "+ "{allOf: [{minLength: 1}, {maxLength: 2}], description: w}]}", ), rulesAt(t, "3.1.0", "")) - deepest := func(n int) string { return strings.Repeat("/allOf/0", n) } + deepest := func(count int) string { return strings.Repeat("/allOf/0", count) } var flat []string flat = append(flat, deepest(statement.MaxFlattenDepth+1)+" wrapper=false capped=false") @@ -134,10 +135,10 @@ func TestFlatten_ListsWhatWalkAllOfLists(t *testing.T) { // hierarchy is n models, each composing the one before it and, where wide, the // first too, each redeclaring x and declaring a member of its own. -func hierarchy(n int, wide bool) string { +func hierarchy(count int, wide bool) string { var b strings.Builder b.WriteString(" A0: {type: object, properties: {x: {type: integer}}}\n") - for i := 1; i < n; i++ { + for i := 1; i < count; i++ { entries := fmt.Sprintf("{$ref: '#/components/schemas/A%d'}", i-1) if wide { entries += ", {$ref: '#/components/schemas/A0'}" @@ -149,11 +150,11 @@ func hierarchy(n int, wide bool) string { } // clique is n models each composing every other, each declaring x. -func clique(n int) string { +func clique(count int) string { var b strings.Builder - for i := range n { + for i := range count { var entries []string - for j := range n { + for j := range count { if j != i { entries = append(entries, fmt.Sprintf("{$ref: '#/components/schemas/A%d'}", j)) } @@ -166,11 +167,11 @@ func clique(n int) string { // readAll reads, of the n components A0 to An-1 of spec, each component, each // entry as a position of its own, and each property of either, and returns // the objects that read and a second asking of the same read. -func readAll(t *testing.T, spec string, n int) (first, again int) { +func readAll(t *testing.T, spec string, count int) (first, again int) { t.Helper() table, loweringContext := tableOver(t, spec, rulesAt(t, "3.1.0", "")) ask := func() { - for i := range n { + for i := range count { st := table.At(component(loweringContext, fmt.Sprintf("A%d", i))) require.Equal(t, statement.Stated, st.Truth) for _, schema := range append([]*statement.Schema{st.Schema}, entrySchemas(st)...) { @@ -213,10 +214,10 @@ func TestTable_ReadsEachObjectOnce(t *testing.T) { }{ // A0 and its property, then each model, its entries and its two // properties. - {"a hierarchy", func(n int) string { return hierarchy(n, false) }, 50, func(n int) int { return 2 + 5*(n-1) }}, - {"a wide hierarchy", func(n int) string { return hierarchy(n, true) }, 50, func(n int) int { return 2 + 6*(n-1) }}, + {"a hierarchy", func(count int) string { return hierarchy(count, false) }, 50, func(n int) int { return 2 + 5*(n-1) }}, + {"a wide hierarchy", func(count int) string { return hierarchy(count, true) }, 50, func(n int) int { return 2 + 6*(n-1) }}, // Each model, its n-1 references, its inline entry and its property. - {"a clique", clique, 6, func(n int) int { return n * (n + 2) }}, + {"a clique", clique, 6, func(count int) int { return count * (count + 2) }}, } { for _, n := range []int{tc.n, 2 * tc.n, 4 * tc.n} { first, again := readAll(t, openapitest.ComponentSpecVer("3.1.0", tc.spec(n)), n) @@ -261,6 +262,18 @@ func TestTable_AtFindsWhatOfReads(t *testing.T) { } } +// TestReferenceTargets_IsTheBindingsTable pins that a table answers for the +// documents its bindings read with their own table, and a nil table, as a +// reader that read none, with none. +func TestReferenceTargets_IsTheBindingsTable(t *testing.T) { + t.Parallel() + loweringContext := servicetest.Context(t, document("3.1.0", "A: {type: object}"), service.Policy{}).Ctx + table := statement.NewTable(statement.Source{Bindings: loweringContext.Bindings(), Rules: everywhere(rulesAt(t, "3.1.0", ""))}) + require.NotNil(t, loweringContext.Bindings().Table()) + assert.Same(t, loweringContext.Bindings().Table(), table.ReferenceTargets()) + assert.Nil(t, (*statement.MemoizingSchemaReader)(nil).ReferenceTargets()) +} + // TestTable_ReadsABuiltStatementWithoutALookup pins that a schema keeps the // statement Of built over it: once each of a schema and its three inline // entries has been read, reading them again, a hundred times each, returns @@ -362,21 +375,24 @@ func TestOf_AReferenceMergedPastTheBoundConjoins(t *testing.T) { assert.Same(t, st.BesideRef, st.Entries[0].Schema) } -// TestOf_AnEntryWhoseReferenceEndsNowhereIsReadWhole pins that an allOf entry -// writing a $ref the bindings read as naming nothing beside other keys is -// listed whole, its reference and its keys one entry, while the same spelling -// written as a component is the conjunction of the two. -func TestOf_AnEntryWhoseReferenceEndsNowhereIsReadWhole(t *testing.T) { +// TestOf_AnEntryWhoseReferenceEndsNowhereConjoins pins that an allOf entry +// writing a $ref the bindings read as naming nothing beside other keys is the +// conjunction of the two, as the same spelling written as a component is: the +// reference admits every kind and cuts nothing, so it is no entry read whole +// but two conjuncts at the entry, the reference and the keys beside it. +func TestOf_AnEntryWhoseReferenceEndsNowhereConjoins(t *testing.T) { t.Parallel() spec := document("3.1.0", "S: {allOf: [{$ref: '#/components/schemas/Ghost', description: d}]}", "G: {$ref: '#/components/schemas/Ghost', description: d}") table, loweringContext := tableOver(t, spec, rulesAt(t, "3.1.0", "")) st := table.At(component(loweringContext, "S")) - require.Len(t, st.Entries, 1) - entry := st.Entries[0].Schema - require.NotNil(t, entry.Ref, "the entry is read as written") - assert.Nil(t, entry.BesideRef) - assert.Equal(t, []string{"$ref", "description"}, keyNames(entry)) + require.Len(t, st.Entries, 2, "the reference and the keys beside it") + written := make([][]string, 0, len(st.Entries)) + for _, entry := range st.Entries { + require.NotNil(t, entry.Schema) + written = append(written, keyNames(entry.Schema)) + } + assert.ElementsMatch(t, [][]string{{"$ref"}, {"description"}}, written) schemaStatement := table.At(component(loweringContext, "G")) assert.Nil(t, schemaStatement.Ref) assert.NotNil(t, schemaStatement.BesideRef, "a component conjoins") @@ -394,3 +410,117 @@ func TestOf_ASchemaUnderAPropertyNamedAllOfIsNoEntry(t *testing.T) { assert.Nil(t, st.Ref) assert.NotNil(t, st.BesideRef, "the items conjoins, as under any other property") } + +// TestWithout_ReadsTheSchemaLessTheKeysNamed pins a schema read less some of +// its keys: a copy holding the rest, in the order written, its slots read as +// the parser reads it less those keywords, its extensions less those named, +// its node a mapping of the rest, and a statement of its own listing no +// entry, built once; a schema naming none of its keys is itself. +func TestWithout_ReadsTheSchemaLessTheKeysNamed(t *testing.T) { + t.Parallel() + table, loweringContext := tableOver(t, document("3.1.0", "A: {type: string, minLength: 2, description: d, title: t, x-a: 1}"), + rulesAt(t, "3.1.0", "")) + schema := table.At(component(loweringContext, "A")).Schema + require.NotNil(t, schema) + assert.Same(t, schema, table.Without(schema, []string{"format"}), "a schema writing none of the keys is itself") + + named := []string{"x-a", "description"} + less := table.Without(schema, named) + assert.Same(t, less, table.Without(schema, []string{"description", "x-a"}), "built once") + assert.Equal(t, []string{"type", "minLength", "title"}, keyNames(less)) + assert.Empty(t, statement.Parsed(less).GetDescription(), "the parser's value less the keyword") + assert.Equal(t, "t", statement.Parsed(less).GetTitle()) + assert.Equal(t, "d", statement.Parsed(schema).GetDescription(), "the schema itself is unchanged") + assert.Empty(t, less.Extensions) + assert.Equal(t, []statement.JSONSchemaTypeName{statement.KindString}, less.Types()) + assert.Len(t, less.Node.Content, 6, "a mapping of the three keys left") + st := table.Read(less) + assert.Same(t, less, st.Schema, "its statement is its own") + assert.Empty(t, st.Entries) +} + +// TestConjoined_IsTheAllOfOfTheBodyAndOneBranch holds the conjunction of a +// position with one branch of its union to the allOf of the two: the +// position's keys but those dropped, its $ref beside them, its entries but the +// keywords writing the union, a $ref or an allOf written with them staying, +// and the branch's, flattened as an entry, at the Rels where each is written. +// It is built once. +func TestConjoined_IsTheAllOfOfTheBodyAndOneBranch(t *testing.T) { + t.Parallel() + table, loweringContext := tableOver(t, document("3.1.0", + "B: {type: string}", + "U: {type: string, format: uuid}", + "Flat: {$ref: '#/components/schemas/B', maxLength: 5, description: d, oneOf: [{format: uuid}, {$ref: '#/components/schemas/U', minLength: 1}]}", + "Entry: {allOf: [{$ref: '#/components/schemas/B'}, {oneOf: [{format: uuid}], allOf: [{minLength: 1}]}, {maxLength: 5}]}", + "Noted: {allOf: [{$ref: '#/components/schemas/B', maxLength: 5, description: e}, {minLength: 1, title: t}], oneOf: [{format: uuid}]}", + "OneEntry: {allOf: [{$ref: '#/components/schemas/B', oneOf: [{format: uuid}]}]}", + ), rulesAt(t, "3.1.0", "")) + flat := table.At(component(loweringContext, "Flat")) + branches := flat.ChoiceKeywords().OneOf + require.Len(t, branches, 2) + conjoined := table.Conjoined(flat.Schema, []string{"description", "oneOf"}, "", table.Subschema(branches[1]), "/oneOf/1") + assert.Same(t, conjoined, table.Conjoined(flat.Schema, []string{"description", "oneOf"}, "", table.Subschema(branches[1]), "/oneOf/1"), "built once") + assert.Equal(t, []string{"maxLength"}, keyNames(conjoined.Schema)) + assert.Same(t, flat.BesideRef, conjoined.BesideRef) + assert.Len(t, conjoined.AllOf, 1) + assert.Equal(t, []jsontext.Pointer{"", "/oneOf/1", "/oneOf/1"}, entryRels(conjoined), "the $ref, then the branch's $ref and what it writes beside it") + assert.Same(t, conjoined, table.Read(conjoined.Schema), "its statement is its own") + + entry := table.At(component(loweringContext, "Entry")) + holder := slices.IndexFunc(entry.Entries, func(conjunct statement.AllOfConjunct) bool { return conjunct.Rel == "/allOf/1" }) + require.GreaterOrEqual(t, holder, 0) + union := table.Read(entry.Entries[holder].Schema) + conjoined = table.Conjoined(entry.Schema, nil, "/allOf/1", table.Subschema(union.ChoiceKeywords().OneOf[0]), "/allOf/1/oneOf/0") + assert.Equal(t, []jsontext.Pointer{"/allOf/0", "/allOf/1/allOf/0", "/allOf/2", "/allOf/1/oneOf/0"}, entryRels(conjoined), + "the keywords writing the union are left out, its own entries kept") + assert.Len(t, conjoined.AllOf, 4, "the entry writing an allOf beside the union stays") + + oneEntry := table.At(component(loweringContext, "OneEntry")) + beside := oneEntry.Entries[len(oneEntry.Entries)-1] + require.Nil(t, beside.Ref) + conjoined = table.Conjoined(oneEntry.Schema, []string{"oneOf"}, "/allOf/0", table.Subschema(table.Read(beside.Schema).ChoiceKeywords().OneOf[0]), "/allOf/0/oneOf/0") + assert.Equal(t, []jsontext.Pointer{"/allOf/0", "/allOf/0/oneOf/0"}, entryRels(conjoined), "the $ref written beside the union stays") + assert.NotNil(t, conjoined.Entries[0].Ref) + assert.Len(t, conjoined.AllOf, 2, "the entry writing the $ref beside the union stays") + + noted := table.At(component(loweringContext, "Noted")) + conjoined = table.Conjoined(noted.Schema, []string{"oneOf", "description", "title"}, "", table.Subschema(noted.ChoiceKeywords().OneOf[0]), "/oneOf/0") + require.Len(t, conjoined.Entries, 4) + assert.NotNil(t, conjoined.Entries[0].Ref, "a reference is read whole") + assert.Equal(t, []string{"maxLength"}, keyNames(conjoined.Entries[1].Schema), "the keys beside it less those dropped") + assert.Same(t, noted.Entries[1].WrittenBeside, conjoined.Entries[1].WrittenBeside, "still beside the reference") + assert.Same(t, conjoined.Entries[1].Schema, table.Read(conjoined.Entries[1].Schema).Schema, "with a statement of its own") + assert.Equal(t, []string{"minLength"}, keyNames(conjoined.Entries[2].Schema)) +} + +// entryRels lists the Rel of each entry st lists. +func entryRels(st *statement.Statement) []jsontext.Pointer { + out := make([]jsontext.Pointer, 0, len(st.Entries)) + for _, entry := range st.Entries { + out = append(out, entry.Rel) + } + return out +} + +// TestExpansion_IsAReferenceLandingWhereTheExpansionDoes pins the reference an +// expanded dynamic reference makes: a schema object writing its keyword alone, +// bound to the target as a $ref landing there is, listing no entry, and built +// once for the schema writing it. +func TestExpansion_IsAReferenceLandingWhereTheExpansionDoes(t *testing.T) { + t.Parallel() + table, loweringContext := tableOver(t, document("3.1.0", + "T: {$dynamicAnchor: t, type: object}", + "D: {$dynamicRef: '#t', description: d}", + ), rulesAt(t, "3.1.0", "")) + dynamic := table.At(component(loweringContext, "D")) + target := component(loweringContext, "T") + value := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "#t"} + expansion := table.Expansion(dynamic.Schema, "$dynamicRef", value, target) + require.NotNil(t, expansion.Ref) + assert.True(t, expansion.Ref.Bound) + assert.Equal(t, target, expansion.Ref.Entry.Hop.Target) + assert.True(t, expansion.Ref.Entry.Lands(), "it lands as a resolved $ref does") + assert.Equal(t, []string{"$dynamicRef"}, keyNames(expansion.Schema)) + assert.Empty(t, expansion.Entries) + assert.Same(t, expansion, table.Expansion(dynamic.Schema, "$dynamicRef", value, target), "built once") +} diff --git a/compilers/openapi/internal/statement/written.go b/compilers/openapi/internal/statement/written.go new file mode 100644 index 000000000..6840ed09a --- /dev/null +++ b/compilers/openapi/internal/statement/written.go @@ -0,0 +1,40 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package statement + +import ( + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/nodeview" + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" +) + +// WrittenDiscriminator returns what the discriminator object node, written at +// at, says where no model holds the schema writing it, read as the binding +// reads the values it binds there (reftable.ReferenceTargetTable.Mapping). It +// is nil for a node that is no mapping. +func WrittenDiscriminator(node *yaml.Node, at reftable.DocumentPointer) *Discriminator { + node = nodeview.Deref(node) + if node == nil || node.Kind != yaml.MappingNode { + return nil + } + view := nodeview.New() + out := &Discriminator{PropertyName: scalarText(view.ChildByToken(node, "propertyName")), Node: node, At: at, + DefaultMapping: scalarText(view.ChildByToken(node, "defaultMapping"))} + for _, pair := range view.MappingPairs(view.ChildByToken(node, "mapping")) { + if value := nodeview.Deref(pair.Val); value != nil && value.Kind == yaml.ScalarNode { + out.Mapping = append(out.Mapping, MappingEntry{Value: pair.Key, Target: value.Value}) + } + } + return out +} + +// scalarText is the text of node, a scalar once its alias is followed, and +// empty for any other node. +func scalarText(node *yaml.Node) string { + if node = nodeview.Deref(node); node == nil || node.Kind != yaml.ScalarNode { + return "" + } + return node.Value +} diff --git a/compilers/openapi/internal/statement/written_test.go b/compilers/openapi/internal/statement/written_test.go new file mode 100644 index 000000000..c47cd67ff --- /dev/null +++ b/compilers/openapi/internal/statement/written_test.go @@ -0,0 +1,45 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package statement_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + yaml "go.yaml.in/yaml/v3" + + "github.com/dexpace/morphic/compilers/openapi/internal/reftable" + "github.com/dexpace/morphic/compilers/openapi/internal/statement" +) + +// writtenNode parses src, a YAML document, into its root mapping. +func writtenNode(t *testing.T, src string) *yaml.Node { + t.Helper() + var doc yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(src), &doc)) + return doc.Content[0] +} + +// TestWrittenDiscriminator_ReadsWhatTheBindingReads pins the reading of a +// discriminator no model holds: its property, each mapping entry a scalar +// names, in the order a merge key and the mapping's own pairs give them, and +// its defaultMapping, an alias followed; a value that is no scalar names +// nothing, and a node that is no mapping is no discriminator. +func TestWrittenDiscriminator_ReadsWhatTheBindingReads(t *testing.T) { + t.Parallel() + at := reftable.DocumentPointer{Pointer: "/x/discriminator"} + node := writtenNode(t, "base: &b {m: '#/M'}\nd: {propertyName: k, defaultMapping: &d '#/D', "+ + "mapping: {<<: *b, a: '#/A', bad: [1], again: *d}}\n").Content[3] + assert.Equal(t, &statement.Discriminator{ + PropertyName: "k", DefaultMapping: "#/D", Node: node, At: at, + Mapping: []statement.MappingEntry{{Value: "m", Target: "#/M"}, {Value: "a", Target: "#/A"}, {Value: "again", Target: "#/D"}}, + }, statement.WrittenDiscriminator(node, at)) + + bare := writtenNode(t, "d: {propertyName: [k]}\n").Content[1] + assert.Equal(t, &statement.Discriminator{Node: bare, At: at}, statement.WrittenDiscriminator(bare, at), + "a property that is no scalar reads as none") + assert.Nil(t, statement.WrittenDiscriminator(writtenNode(t, "d: 5\n").Content[1], at)) + assert.Nil(t, statement.WrittenDiscriminator(nil, at)) +} diff --git a/compilers/openapi/internal/stream/stream.go b/compilers/openapi/internal/stream/stream.go index 35ca1cabb..0663f68ff 100644 --- a/compilers/openapi/internal/stream/stream.go +++ b/compilers/openapi/internal/stream/stream.go @@ -173,9 +173,9 @@ func condition(promoter promotion.Promoter, compiledDocumentView *compileddoc.Co return append(diags, promotion.Unpromoted(st.Source.String(), st.At, why, noCondition)) } -// namesBoolean reports whether id stands for the boolean primitive. +// namesBoolean reports whether id names the boolean primitive. func namesBoolean(compiledDocumentView *compileddoc.CompiledDocumentView, id ir.TypeID) bool { - primitive, ok := compiledDocumentView.Stands(id).(*ir.Primitive) + primitive, ok := compiledDocumentView.ChainEndNode(id).(*ir.Primitive) return ok && primitive.PrimitiveKind == ir.PrimitiveBool } diff --git a/compilers/openapi/internal/typeformat/applies.go b/compilers/openapi/internal/typeformat/applies.go new file mode 100644 index 000000000..5bb86fc45 --- /dev/null +++ b/compilers/openapi/internal/typeformat/applies.go @@ -0,0 +1,102 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package typeformat + +import ( + "encoding/json/jsontext" + "encoding/json/v2" + "strings" + + "github.com/dexpace/morphic/compilers/openapi/internal/specrules" +) + +// JSONInstanceKinds is a set of JSON instance kinds: integer, number, string, +// array, object, boolean, null. An integer and a number with a fraction are two +// kinds, as `integer` admits one of them and `number` both. +type JSONInstanceKinds uint8 + +// The JSON instance kinds a set holds. +const ( + // InstanceInteger is a number with no fraction. + InstanceInteger JSONInstanceKinds = 1 << iota + // InstanceNumber is a number with a fraction. + InstanceNumber + // InstanceString is a string. + InstanceString + // InstanceArray is an array. + InstanceArray + // InstanceObject is an object. + InstanceObject + // InstanceBoolean is true or false. + InstanceBoolean + // InstanceNull is null. + InstanceNull + + // EveryInstanceKind holds every kind. + EveryInstanceKind = InstanceInteger | InstanceNumber | InstanceString | InstanceArray | InstanceObject | + InstanceBoolean | InstanceNull +) + +// InstanceKindsKeywordAppliesTo is the kinds a keyword constrains: its +// specrules.SlotOf slot's kind, for format the kinds of the rows listing its +// value (formatAppliesTo), and every kind for any other keyword. An instance +// of another kind satisfies such a keyword (JSON Schema Core 2020-12 §7.6.1). +func InstanceKindsKeywordAppliesTo(keyword string, value jsontext.Value) JSONInstanceKinds { + switch specrules.SlotOf(keyword) { + case specrules.SlotNumber: + return InstanceInteger | InstanceNumber + case specrules.SlotText: + return InstanceString + case specrules.SlotArray: + return InstanceArray + case specrules.SlotObject: + return InstanceObject + case specrules.SlotFormat: + return formatAppliesTo(value) + default: + return EveryInstanceKind + } +} + +// formatAppliesTo returns the kinds of the rows of either table listing the +// format value, text too where an integer or number row lists it, since a +// number may be written as text; every kind where no row lists it, or the +// value is no string. +func formatAppliesTo(value jsontext.Value) JSONInstanceKinds { + var format string + if value == nil || value.Kind() != '"' || json.Unmarshal(value, &format) != nil { + return EveryInstanceKind + } + var kinds JSONInstanceKinds + for key := range formatTable { + kinds |= rowKind(key, format) + } + for key := range encodedTable { + kinds |= rowKind(key, format) + } + if kinds == 0 { + return EveryInstanceKind + } + if kinds&(InstanceInteger|InstanceNumber) != 0 { + kinds |= InstanceString + } + return kinds +} + +// rowTypeKinds maps the JSON type a table row is written on to its kind. +var rowTypeKinds = map[string]JSONInstanceKinds{ + "integer": InstanceInteger, + "number": InstanceNumber, + "string": InstanceString, +} + +// rowKind returns the kind of the JSON type a "type/format" key is written +// on where its format is format, and none for another key. +func rowKind(key, format string) JSONInstanceKinds { + jsonType, rowFormat, ok := strings.Cut(key, "/") + if !ok || rowFormat != format { + return 0 + } + return rowTypeKinds[jsonType] +} diff --git a/compilers/openapi/internal/typeformat/applies_test.go b/compilers/openapi/internal/typeformat/applies_test.go new file mode 100644 index 000000000..25008d7f4 --- /dev/null +++ b/compilers/openapi/internal/typeformat/applies_test.go @@ -0,0 +1,82 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package typeformat_test + +import ( + "encoding/json/jsontext" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" +) + +// appliesTo is the kinds keyword constrains, its value written as JSON text. +func appliesTo(keyword, value string) typeformat.JSONInstanceKinds { + if value == "" { + return typeformat.InstanceKindsKeywordAppliesTo(keyword, nil) + } + return typeformat.InstanceKindsKeywordAppliesTo(keyword, jsontext.Value(value)) +} + +// TestInstanceKindsKeywordAppliesTo_EachSlotAppliesToItsKind holds a keyword +// of the number, text, array or object slot to that slot's kind, every +// keyword of one slot alike and no two slots sharing a kind, and any other +// keyword to every kind, which holds each slot's. +func TestInstanceKindsKeywordAppliesTo_EachSlotAppliesToItsKind(t *testing.T) { + t.Parallel() + slots := map[string][]string{ + "number": {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}, + "text": {"minLength", "maxLength", "pattern", "contentEncoding", "contentMediaType", "contentSchema"}, + "array": {"items", "prefixItems", "contains", "minItems", "maxItems", "uniqueItems", "unevaluatedItems"}, + "object": {"properties", "patternProperties", "additionalProperties", "required", "minProperties", "maxProperties"}, + } + every := appliesTo("title", "") + kinds := map[string]typeformat.JSONInstanceKinds{} + for slot, keywords := range slots { + kinds[slot] = appliesTo(keywords[0], "") + assert.NotZero(t, kinds[slot], slot) + assert.Equal(t, kinds[slot], every&kinds[slot], "every kind holds the %s slot's", slot) + for _, keyword := range keywords[1:] { + assert.Equal(t, kinds[slot], appliesTo(keyword, ""), "%s applies as %s does", keyword, keywords[0]) + } + } + for first, firstKinds := range kinds { + for second, secondKinds := range kinds { + if first != second { + assert.Zero(t, firstKinds&secondKinds, "%s and %s share no kind", first, second) + } + } + } + for _, keyword := range []string{"description", "const", "enum", "type", "oneOf", "not", "$ref", "unknownKeyword"} { + assert.Equal(t, every, appliesTo(keyword, ""), keyword) + } + all := kinds["number"] | kinds["text"] | kinds["array"] | kinds["object"] + assert.NotZero(t, every&^all, "every kind holds more than the four slots': a boolean and null") +} + +// TestInstanceKindsKeywordAppliesTo_AFormatAppliesToItsRowsKinds holds a format +// to the JSON types of the rows listing its value, text too where an integer +// or number row lists it, as a number may be written as text, and to every +// kind where no row lists it or the value is no string. +func TestInstanceKindsKeywordAppliesTo_AFormatAppliesToItsRowsKinds(t *testing.T) { + t.Parallel() + text, number := appliesTo("minLength", ""), appliesTo("minimum", "") + every := appliesTo("title", "") + for _, format := range []string{`"date-time"`, `"uuid"`, `"date"`, `"binary"`, `"byte"`, `"http-date"`} { + assert.Equal(t, text, appliesTo("format", format), format) + } + integral := appliesTo("format", `"int64"`) + assert.Equal(t, integral, appliesTo("format", `"unixtime"`), "integer, number and text rows") + assert.Equal(t, text, integral&text, "a number written as text") + assert.Equal(t, number, integral&number) + float := appliesTo("format", `"float"`) + assert.Equal(t, text, float&text, "a number written as text") + assert.Equal(t, integral, integral|float, "a number row alone lists float") + assert.NotEqual(t, integral, float, "no integer row lists float") + for _, format := range []string{`"email"`, `"x-custom"`} { + assert.Equal(t, every, appliesTo("format", format), "%s: no row lists it", format) + } + assert.Equal(t, every, appliesTo("format", "1"), "a format written as no string names no row") +} diff --git a/compilers/openapi/internal/typeformat/typeformat_test.go b/compilers/openapi/internal/typeformat/typeformat_test.go index dcbad06b8..3872c7b30 100644 --- a/compilers/openapi/internal/typeformat/typeformat_test.go +++ b/compilers/openapi/internal/typeformat/typeformat_test.go @@ -255,11 +255,11 @@ func TestNarrows_HoldsEveryContainment(t *testing.T) { // TestNarrows_OmitsRoundingContainments pins the choice not to take a // containment that holds only by rounding. A narrowing is adopted silently, so -// it must hold of every value and every JSON instance. OpenAPI floats round: -// an int32, uint32, int64 or uint64 sits inside float32 only by losing low bits, an -// int64 or uint64 inside float64 likewise, and integer inside either float -// width has no bound at all. Those pairs overlap: the first declaration is kept -// and the second reported. +// it must hold of every value and every JSON instance. OpenAPI floats round: an +// int32, uint32, int64 or uint64 sits inside float32 only by losing low bits, +// an int64 or uint64 inside float64 likewise, and integer inside either float +// width has no bound at all. Those pairs overlap: the first declaration is +// chosen and the second reported. func TestNarrows_OmitsRoundingContainments(t *testing.T) { t.Parallel() rounding := [][2]ir.PrimitiveKind{ @@ -274,8 +274,8 @@ func TestNarrows_OmitsRoundingContainments(t *testing.T) { } } -// TestRelate_ClassifiesEveryVerdict covers each verdict, both ways round. -func TestRelate_ClassifiesEveryVerdict(t *testing.T) { +// TestRelate_ClassifiesEveryAnswer covers each answer, both ways round. +func TestRelate_ClassifiesEveryAnswer(t *testing.T) { t.Parallel() tests := []struct { name string diff --git a/compilers/openapi/internal/typeformat/values.go b/compilers/openapi/internal/typeformat/values.go new file mode 100644 index 000000000..047b4b888 --- /dev/null +++ b/compilers/openapi/internal/typeformat/values.go @@ -0,0 +1,38 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package typeformat + +import "github.com/dexpace/morphic/ir" + +// KindsOfValue returns the JSON instance kind value is, and false for a value +// no JSON instance spells: a symbol, bytes, a reference or a constructor. A +// number is an integer where its decimal has no fractional part, whatever its +// spelling, so 1.0 and 1e2 are integers, as JSON Schema Validation 2020-12 +// §6.1.1 has them. Any other number is a number with a fraction, an infinity, +// NaN and a literal no Decimal holds among them. +func KindsOfValue(value ir.Value) (JSONInstanceKinds, bool) { + switch value.Kind { + case ir.ValueNull: + return InstanceNull, true + case ir.ValueBool: + return InstanceBoolean, true + case ir.ValueString: + return InstanceString, true + case ir.ValueNumber: + if number, err := value.Number.Decimal(); err == nil && number.IsInt() { + return InstanceInteger, true + } + return InstanceNumber, true + case ir.ValueInfinity, ir.ValueNegativeInfinity, ir.ValueNaN: + return InstanceNumber, true + case ir.ValueList: + return InstanceArray, true + case ir.ValueObject: + return InstanceObject, true + case ir.ValueBytes, ir.ValueSymbol, ir.ValueRefKind, ir.ValueConstructor: + return 0, false + default: + return 0, false + } +} diff --git a/compilers/openapi/internal/typeformat/values_test.go b/compilers/openapi/internal/typeformat/values_test.go new file mode 100644 index 000000000..0d5efd977 --- /dev/null +++ b/compilers/openapi/internal/typeformat/values_test.go @@ -0,0 +1,54 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package typeformat_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/compilers/openapi/internal/typeformat" + "github.com/dexpace/morphic/ir" +) + +// TestKindsOfValue_ReadsTheKindOfEachValue holds each value to the kind a JSON +// instance of it is. The number rows were each checked against a JSON Schema +// validator's `type: integer` (Python jsonschema, Draft 2020-12): 1.0, 1e2, +// 10e-1 and -0.0 are integers there, and 1.5 and 1e-2 are not. +func TestKindsOfValue_ReadsTheKindOfEachValue(t *testing.T) { + t.Parallel() + number := func(text string) ir.Value { return ir.Value{Kind: ir.ValueNumber, Number: ir.BigVal(text)} } + for _, tc := range []struct { + name string + value ir.Value + kinds typeformat.JSONInstanceKinds + ok bool + }{ + {"null", ir.Value{Kind: ir.ValueNull}, typeformat.InstanceNull, true}, + {"bool", ir.Value{Kind: ir.ValueBool}, typeformat.InstanceBoolean, true}, + {"string", ir.Value{Kind: ir.ValueString}, typeformat.InstanceString, true}, + {"list", ir.Value{Kind: ir.ValueList}, typeformat.InstanceArray, true}, + {"object", ir.Value{Kind: ir.ValueObject}, typeformat.InstanceObject, true}, + {"whole number", number("3"), typeformat.InstanceInteger, true}, + {"negative zero", number("-0.0"), typeformat.InstanceInteger, true}, + {"whole number with a zero fraction", number("1.0"), typeformat.InstanceInteger, true}, + {"whole number with an exponent", number("1e2"), typeformat.InstanceInteger, true}, + {"whole number with a negative exponent", number("10e-1"), typeformat.InstanceInteger, true}, + {"number with a fraction", number("1.5"), typeformat.InstanceNumber, true}, + {"number with an exponent and a fraction", number("1e-2"), typeformat.InstanceNumber, true}, + {"number no decimal holds", number("one"), typeformat.InstanceNumber, true}, + {"infinity", ir.Value{Kind: ir.ValueInfinity}, typeformat.InstanceNumber, true}, + {"negative infinity", ir.Value{Kind: ir.ValueNegativeInfinity}, typeformat.InstanceNumber, true}, + {"not a number", ir.Value{Kind: ir.ValueNaN}, typeformat.InstanceNumber, true}, + {"bytes", ir.Value{Kind: ir.ValueBytes}, 0, false}, + {"symbol", ir.Value{Kind: ir.ValueSymbol}, 0, false}, + {"reference", ir.Value{Kind: ir.ValueRefKind}, 0, false}, + {"constructor", ir.Value{Kind: ir.ValueConstructor}, 0, false}, + {"a kind no value holds", ir.Value{Kind: ir.ValueKind("unheard-of")}, 0, false}, + } { + kinds, ok := typeformat.KindsOfValue(tc.value) + assert.Equal(t, tc.kinds, kinds, tc.name) + assert.Equal(t, tc.ok, ok, tc.name) + } +} diff --git a/compilers/openapi/internal/value/scalar.go b/compilers/openapi/internal/value/scalar.go index 8189f8d9d..cc58409db 100644 --- a/compilers/openapi/internal/value/scalar.go +++ b/compilers/openapi/internal/value/scalar.go @@ -115,7 +115,7 @@ func (s Scalar) JSONKind() ScalarKind { // past it is, rather than read as the text it is not. A quoted one, or one // tagged !!str outright, is the string it says. // -// `<<` written as a value, which yaml.v3 tags !!merge wherever it stands, is +// `<<` written as a value, which yaml.v3 tags !!merge wherever it sits, is // the text it spells: only a key merges. func text(node *yaml.Node, scalar Scalar) (Scalar, error) { scalar.Kind = ScalarString diff --git a/compilers/openapi/openapi.go b/compilers/openapi/openapi.go index 958107188..8a8a0e304 100644 --- a/compilers/openapi/openapi.go +++ b/compilers/openapi/openapi.go @@ -23,6 +23,7 @@ import ( "github.com/dexpace/morphic/compilers/openapi/internal/ids" "github.com/dexpace/morphic/compilers/openapi/internal/load" "github.com/dexpace/morphic/compilers/openapi/internal/lowering" + "github.com/dexpace/morphic/compilers/openapi/internal/merge" "github.com/dexpace/morphic/compilers/openapi/internal/operation" "github.com/dexpace/morphic/compilers/openapi/internal/overlay" "github.com/dexpace/morphic/compilers/openapi/internal/pagination" @@ -142,15 +143,14 @@ func (c *Compiler) Compile(ctx context.Context, sources []compilers.Source, opts return out, out.Diagnostics, nil } -// withoutRereported drops each lowering report of an unresolved reference that -// the load phase already reported at the same position. +// withoutRereported drops each lowering report of an unresolved reference +// that the load phase made at the same provenance, or that the lowering made +// there already in the same words. // -// The load phase reports a failure at the $ref, and a cycle once, with the -// reason. The lowering reports a schema $ref it could not follow at that -// pointer, and also where the load phase did not, as at a $ref the binding -// never read. So only a report the load phase made at that exact provenance, -// in whichever document, is dropped; kept, one failure would read as two -// (#385). +// The lowering reports a schema $ref it could not follow, whether or not the +// load phase reported it, as at a $ref the binding never read; kept, one +// failure would read as two (#385). A discriminator's mapping value is read by +// the node holding it and by each node keeping it, each wording it alike. func withoutRereported(lowered, loaded []ir.Diagnostic) []ir.Diagnostic { reported := make(map[ir.Provenance]bool) for _, diagnostic := range loaded { @@ -158,11 +158,22 @@ func withoutRereported(lowered, loaded []ir.Diagnostic) []ir.Diagnostic { reported[diagnostic.Provenance] = true } } + type said struct { + at ir.Provenance + message string + } + saidByLowering := make(map[said]bool) out := make([]ir.Diagnostic, 0, len(lowered)) for _, diagnostic := range lowered { - if diagnostic.Code == diag.UnresolvedRef && reported[diagnostic.Provenance] { + if diagnostic.Code != diag.UnresolvedRef { + out = append(out, diagnostic) + continue + } + key := said{diagnostic.Provenance, diagnostic.Message} + if reported[diagnostic.Provenance] || saidByLowering[key] { continue } + saidByLowering[key] = true out = append(out, diagnostic) } return out @@ -259,8 +270,8 @@ func run(ctx context.Context, serviceContext service.Ctx, infinity inferences, t acc.AppendAll(pruneDiags) return nil, acc.List(), err } - rewritePrunedFoldDiagnostics(settled, out.Types, schema.PrunedDiagnostics(serviceContext.Ctx)) - acc.AppendAll(settled) + // The member fold's reports are said once, over what pruning left. + acc.AppendAll(merge.ReportOnce(settled, out.Types, out.Sources)) acc.AppendAll(pruneDiags) // What is read once the document is whole is read here, in the one order // docs/compilers/openapi.md#policies gives: links, then promotions, then diff --git a/compilers/openapi/openapi_test.go b/compilers/openapi/openapi_test.go index c586ba8be..ca47eece5 100644 --- a/compilers/openapi/openapi_test.go +++ b/compilers/openapi/openapi_test.go @@ -268,10 +268,11 @@ func TestRun_RegistryRefusalsAreSurfaced(t *testing.T) { } // TestWithoutRereported is a unit table over the ways a lowering diagnostic -// and the load phase's diagnostics can relate. Only one drops anything: the key -// withoutRereported dedupes on is the code and the whole Provenance, so another -// code at the same provenance survives, and so does the same code at another -// pointer, or at the same pointer in another source. +// and the load phase's diagnostics can relate. A report the load phase made is +// keyed by the code and the whole Provenance, so another code at the same +// provenance survives, and so does the same code at another pointer, or at the +// same pointer in another source. A report the lowering made already is keyed +// by its words too. func TestWithoutRereported(t *testing.T) { t.Parallel() at := ir.Provenance{Source: 0, Pointer: "/components/schemas/S"} @@ -308,6 +309,27 @@ func TestWithoutRereported(t *testing.T) { loaded: []ir.Diagnostic{{Code: diag.CyclicRef, Provenance: at}}, want: []ir.Diagnostic{}, }, + "unresolved-ref the lowering made already in the same words is dropped": { + lowered: []ir.Diagnostic{ + {Code: diag.UnresolvedRef, Provenance: at, Message: "m"}, + {Code: diag.UnresolvedRef, Provenance: at, Message: "m"}, + }, + want: []ir.Diagnostic{{Code: diag.UnresolvedRef, Provenance: at, Message: "m"}}, + }, + "unresolved-ref the lowering made already in other words is kept": { + lowered: []ir.Diagnostic{ + {Code: diag.UnresolvedRef, Provenance: at, Message: "m"}, + {Code: diag.UnresolvedRef, Provenance: at, Message: "n"}, + {Code: diag.DegradedConstruct, Provenance: at, Message: "m"}, + {Code: diag.DegradedConstruct, Provenance: at, Message: "m"}, + }, + want: []ir.Diagnostic{ + {Code: diag.UnresolvedRef, Provenance: at, Message: "m"}, + {Code: diag.UnresolvedRef, Provenance: at, Message: "n"}, + {Code: diag.DegradedConstruct, Provenance: at, Message: "m"}, + {Code: diag.DegradedConstruct, Provenance: at, Message: "m"}, + }, + }, "an empty loaded list keeps everything": { lowered: []ir.Diagnostic{ {Code: diag.UnresolvedRef, Provenance: at}, diff --git a/compilers/openapi/run_internal_test.go b/compilers/openapi/run_internal_test.go index e73628ed4..ea7555de4 100644 --- a/compilers/openapi/run_internal_test.go +++ b/compilers/openapi/run_internal_test.go @@ -66,15 +66,15 @@ func TestRun_AppendsNothingAfterAFirstAsk(t *testing.T) { compile.NewTypes(), keep) require.NoError(t, err) require.NotNil(t, kept) - assert.Empty(t, staleReadings(kept, compileddoc.New(doc))) + assert.Empty(t, staleAnswers(kept, compileddoc.New(doc))) }) } } -// staleReadings names each answer kept gives, of a parameter's placements, a +// staleAnswers names each answer kept gives, of a parameter's placements, a // response's headers or a model's members, that fresh, a reading of the same // document made afresh, gives otherwise. -func staleReadings(kept, fresh *compileddoc.CompiledDocumentView) []string { +func staleAnswers(kept, fresh *compileddoc.CompiledDocumentView) []string { var stale []string for _, operation := range fresh.Operations { for _, parameter := range operation.Params { diff --git a/compilers/openapi/targets.go b/compilers/openapi/targets.go index 37a892bdb..cead9bbb2 100644 --- a/compilers/openapi/targets.go +++ b/compilers/openapi/targets.go @@ -118,7 +118,7 @@ func (s *sourceLandings) targetsFor(key string, entry ir.UnmodeledEntry) map[jso case '"': return s.matchString(raw, entry.Provenance.Pointer) case '{', '[': - if !mightCarryLanding(raw, s.hasDiscriminator) { + if key != schema.KeptMappingKey && !mightCarryLanding(raw, s.hasDiscriminator) { return nil } var parsed any @@ -435,36 +435,3 @@ func siteDropped(site schema.LandingSite, dropped []ir.Provenance) bool { } return false } - -// rewritePrunedFoldDiagnostics substitutes the alternate location-based wording -// on any fold drop diagnostic whose losing anonymous TypeID was actually -// removed from types by post-settlement pruning, leaving every diagnostic whose -// losing type survived untouched. Matching ignores Provenance.Node because -// ModelPropertyDeclarations.Settle stamps the decided property ID onto Node -// after folding records candidates. -func rewritePrunedFoldDiagnostics(diags []ir.Diagnostic, types ir.TypeRegistry, candidates []schema.PrunedDiagnostic) { - if len(candidates) == 0 { - return - } - type diagKey struct { - code string - source int - pointer jsontext.Pointer - message string - } - rewrites := map[diagKey]string{} - for _, candidate := range candidates { - if _, live := types[candidate.Loser]; !live { - rewrites[diagKey{candidate.Code, candidate.Provenance.Source, candidate.Provenance.Pointer, candidate.Full}] = candidate.Pruned - } - } - if len(rewrites) == 0 { - return - } - for i := range diags { - key := diagKey{diags[i].Code, diags[i].Provenance.Source, diags[i].Provenance.Pointer, diags[i].Message} - if replacement, ok := rewrites[key]; ok { - diags[i].Message = replacement - } - } -} diff --git a/compilers/openapi/targets_test.go b/compilers/openapi/targets_test.go index 0fff9dade..4808d95a6 100644 --- a/compilers/openapi/targets_test.go +++ b/compilers/openapi/targets_test.go @@ -11,15 +11,14 @@ import ( "github.com/stretchr/testify/assert" "github.com/dexpace/morphic/compilers/openapi" - "github.com/dexpace/morphic/compilers/openapi/internal/diag" "github.com/dexpace/morphic/compilers/openapi/internal/schema" "github.com/dexpace/morphic/ir" ) // TestAttachUnmodeledTargets_MatchesEveryEntryForm pins attachUnmodeledTargets // across empty landings, dead landings, string entries, object/array trees, -// discriminator routes, residue objects without the original ref, collapsed -// allOf provenance, and non-matching payloads. +// discriminator routes, objects kept under openapi:residue without the original +// ref, collapsed allOf provenance, and non-matching payloads. func TestAttachUnmodeledTargets_MatchesEveryEntryForm(t *testing.T) { t.Parallel() const ( @@ -192,45 +191,3 @@ func TestSeedDiscardedLandings_SeedsDroppedProvenances(t *testing.T) { droppedRoot: true, }, discarded) } - -// TestRewritePrunedFoldDiagnostics_RewritesOnlyActuallyPrunedLosers pins that -// rewritePrunedFoldDiagnostics substitutes the alternate message only when the -// losing TypeID is absent from Document.Types (including when settlement later -// stamps Provenance.Node for a $ref-brought fold) and leaves surviving losers -// and unrelated diagnostics untouched. -func TestRewritePrunedFoldDiagnostics_RewritesOnlyActuallyPrunedLosers(t *testing.T) { - t.Parallel() - const ( - liveLoser ir.TypeID = "type/anonymous/live-loser" - prunedLoser ir.TypeID = "type/anonymous/pruned-loser" - ) - types := ir.TypeRegistry{liveLoser: anonModel(liveLoser)} - provLive := ir.Provenance{Source: 0, Pointer: "/components/schemas/A/allOf/0/properties/p"} - provPruned := ir.Provenance{Source: 0, Pointer: "/components/schemas/B/allOf/0/properties/p"} - provPrunedNamed := provPruned - provPrunedNamed.Node = "prop/openapi/components/schemas/B/allOf/properties/p" - - diags := []ir.Diagnostic{ - {Code: diag.ConflictingRedecl, Provenance: provLive, Message: "full live"}, - {Code: diag.ConflictingRedecl, Provenance: provPrunedNamed, Message: "full pruned"}, - {Code: diag.DegradedConstruct, Provenance: provPrunedNamed, Message: "unrelated"}, - } - - // Empty candidates and surviving-only candidates leave all messages untouched. - openapi.RewritePrunedFoldDiagnostics(diags, types, nil) - openapi.RewritePrunedFoldDiagnostics(diags, types, []schema.PrunedDiagnostic{ - {Code: diag.ConflictingRedecl, Provenance: provLive, Full: "full live", Pruned: "pruned live", Loser: liveLoser}, - }) - assert.Equal(t, "full live", diags[0].Message) - assert.Equal(t, "full pruned", diags[1].Message) - - // An actually pruned loser rewrites only its matching diagnostic even when - // Provenance.Node was populated after fold candidate recording. - openapi.RewritePrunedFoldDiagnostics(diags, types, []schema.PrunedDiagnostic{ - {Code: diag.ConflictingRedecl, Provenance: provLive, Full: "full live", Pruned: "pruned live", Loser: liveLoser}, - {Code: diag.ConflictingRedecl, Provenance: provPruned, Full: "full pruned", Pruned: "pruned msg", Loser: prunedLoser}, - }) - assert.Equal(t, "full live", diags[0].Message) - assert.Equal(t, "pruned msg", diags[1].Message) - assert.Equal(t, "unrelated", diags[2].Message) -} diff --git a/docs/architecture.md b/docs/architecture.md index 1140092f3..200b7c26e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -184,14 +184,15 @@ cancel waits out is the model build itself, a single call **The contract is checked, not trusted.** Each duty `compilers.Compiler`'s doc comments state is held where its data is. `Registry.Register` refuses a format naming no dialect, and `Registry.Detect` a claim naming none, a decline that indexes a source detection was not handed or -speaks with no error, and a claim of a source past the claimant's `SourceLimit` or a silent decline -of one: a source read no further than the limits allow may be only the first bytes of one. -`Detection.Compile`, which the engine compiles through, refuses a refusal that gives no error, a -document not stamped with the IR version this build reads, a source table that does not open with -the one `SourceTable` names, a source read as a format other than the one it was recognized as or -hashed from other bytes, and a finding indexing no source. Entries past that opening name what else -the compile read, such as a document a reference names, which `SourceTable` reads no input to know -of. Each breach is a Go error wrapping `compilers.ErrContract`: a compiler bug, never the spec's. +speaks with no error, and a claim of a source past the claimant's `SourceLimit` or a decline +of one that reports nothing: a source read no further than the limits allow may be only the first +bytes of one. `Detection.Compile`, which the engine compiles through, refuses a refusal that gives +no error, a document not stamped with the IR version this build reads, a source table that does not +open with the one `SourceTable` names, a source read as a format other than the one it was +recognized as or hashed from other bytes, and a finding indexing no source. Entries past that +opening name what else the compile read, such as a document a reference names, which `SourceTable` +reads no input to know of. Each breach is a Go error wrapping `compilers.ErrContract`: a compiler +bug, never the spec's. A panic is a breach too. Every call the `compilers` package makes of a compiler (`Formats`, `Detect`, configuring it through `DecodeOptions`, `SourceLimit`, `Compile` and `SourceTable`) runs @@ -209,10 +210,12 @@ nothing tells a whole answer from a cut one. `Registry.Detect` treats a `Detect` the engine a pass (§2.2). What a document holds whatever produced it, the namespaces, a service and a well-formed source table -among them, is `irverify`'s, and `compile.Types.Finish` hands a compiler its registry with the -diagnostics it reports, a `compile/registry-refused` error for each entry the registry refused among -them. The engine does not run `irverify` by default: it slows a run, and the harness runs every -compile of the whole corpus verified. `RunOptions.Verify` (`--verify`) runs it for a compiler under +among them, is `irverify`'s. `compile.Types.Finish` hands a compiler its registry with the +diagnostics it reports, among them a `compile/alias-base-rewritten` error for each alias a +settlement changed, itself or the node its `Base` names, in what a reader of the alias chain takes +from it, and a `compile/registry-refused` error for each entry the registry refused. The engine +does not run `irverify` by default: it slows a run, and the harness runs every compile of the whole +corpus verified. `RunOptions.Verify` (`--verify`) runs it for a compiler under development, over the compiler's document and over each document a pass returns, and over the one `RunDocument` is handed, and fails the run with an `engine.VerifyError` carrying every violation, wrapping the contract error of the stage that returned the document. It also fingerprints each @@ -390,7 +393,7 @@ Built, and in the default list: parameter an HTTP binding places twice at one non-host location is an error (`pass/param-binding-mismatch`), one it places nowhere is the warning `pass/param-unbound`, and a `host` binding is additive ([http-binding](./ir/http-binding.md)). It also reports what a source - wrote that no value can meet, each a warning: bounds that admit no value + wrote that no value can satisfy, each a warning: bounds that admit no value ([constraints](./ir/constraints.md)), a default or an example its type does not admit ([values](./ir/values.md)), and a composition cycle or a type with no finite value ([models](./ir/models.md)). Structural problems are errors, which fail the run at the default @@ -509,7 +512,7 @@ outcome, `Retry-After` and **redirects**. Delivery model: versioned defaults + d the policy a document embeds below the project's and the project's below the one it sets for each emitter, each with per-operation overrides (`docs/emitters/contract/runtime-policy.md`). Precedence rule: *declared IR facts win over policy defaults* — `ErrorCase.Retryable/Fault` and -`Operation.Idempotency` come from the spec; policy fills in where the spec is silent, never the +`Operation.Idempotency` come from the spec; policy fills in where the spec says nothing, never the reverse. ### 2.5 Changing the IR @@ -596,6 +599,8 @@ morphic/ ├── barrier/ # Layer 0 — turns a panic in code the caller does not own into an error. ├── scratchstate/ # Layer 0 — scratch state both checkers read collection after collection. ├── pathfold/ # Layer 0 — the path fold, and what makes a path segment portable. +├── stronglyconnected/ # Layer 0 — Tarjan's search for a directed graph's strongly connected components. +├── rfc3339/ # Layer 0 — the RFC 3339 time and date-time texts, read by their grammar. ├── ir/ # Layer 0 — IR node types, IDs, shared traversals, editing, JSON round-trip. │ ├── irfacts/ # Derived facts of a document, never stored (docs/ir/derived-facts.md). │ ├── irtest/ # Golden-snapshot and fixture helpers for IR documents. @@ -651,7 +656,12 @@ git ls-files '*/*.go' | xargs -n1 dirname | sort -u Dependency rules, enforced by an architecture test as in oagen: -- `ir` imports only the standard library. It contains no parsing, no generation, no I/O. +- `ir` imports only the standard library, `stronglyconnected` and `rfc3339`. It contains no + parsing, no generation, no I/O. +- `stronglyconnected` and `rfc3339` import only the standard library: Tarjan's search for the + strongly connected components of a directed graph, and the RFC 3339 time texts read by their + grammar, no morphic concept in either, so they sit below `ir`, and every package that condenses + a graph or reads such a text shares one copy of each. - `barrier` imports only the standard library, and sits below the packages that run code they do not own behind it: `compilers`, which runs a compiler, `engine`, which runs a pass, and the OpenAPI compiler's `diag`, behind which that compiler runs its parser, the JSONPath evaluator it applies @@ -702,7 +712,7 @@ The OpenAPI compiler's `internal/` packages sit in five layers, ordered by what the source, least first, and a package may import its own layer and those below it. **Inference** reads the built document and no tree: its finding codes, its IDs, and what is read off it under a policy. **Document** reads bytes, trees, pointers, budgets and overlays, and reaches the YAML -library alone. **Grammar** holds a format's objects as data, where references stand and which rows +library alone. **Grammar** holds a format's objects as data, where references sit and which rows read a position, and reaches the YAML library and the parser library's reference grammar. **Schema** reads JSON Schema, and may use the parser library whole. **Service** reads OpenAPI's own objects and the load that models them, and reaches any library. Only the service layer is OpenAPI's own, so the @@ -767,7 +777,7 @@ edited, as a line does not. The decisions it rests on: - *A rule that matches nothing is reported.* `Result.UnusedRules` lists it on a run that produced a document, and the CLI names it: unless its pass is off, the finding it was written for has gone, because the spec changed or a later build lowers the construct, and the rule - can go too. That is the decay an approval's expiry stands guard against, found by the run + can go too. That is the decay an approval's expiry guards against, found by the run itself; an expiry by date would make one run's verdict depend on the day it ran, and morphic has no release a rule could name. - *Rules are applied after the run, never stored.* `Result.Diagnostics` and the document keep the diff --git a/docs/cli.md b/docs/cli.md index 476c33327..24c411126 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -48,7 +48,7 @@ completes commands, flags, and spec files by extension. | `--diagnostics-per-code-limit ` | both | In text, write the first `` findings of each code and severity, and count the rest (default `3`); `0` writes every one. Refused beside `--diagnostics-format json`. | | `-o`, `--output ` | `compile` | Write IR JSON to `` instead of stdout, compact rather than indented. | | `--pretty` | `compile` | Indent the JSON `--output` writes; stdout is indented either way. | -| `--explain ` | `compile` | Instead of writing the document, report what compiling produced at this source coordinate: the type node the document holds there, the coordinates beneath it, each construct kept verbatim under `Unmodeled` at or beneath it with the node keeping it and its reason, and the diagnostics stamped at it, as their stages reported them. A pass may replace or remove a node the compiler made, which `--disable-pass` shows. `''` is the whole document. Refused together with `--output`, which it would otherwise ignore. | +| `--explain ` | `compile` | Instead of writing the document, report what compiling produced at this source coordinate: the type node the document holds there, the coordinates beneath it, each construct kept verbatim under `Unmodeled` at or beneath it with the node keeping it and its reason, and the diagnostics stamped at it, as their stages reported them. A node minted at a key naming no construct, as a variant distributed from an `allOf` entry's union (`…/allOf/-//…`), is listed under that key's path. A pass may replace or remove a node the compiler made, which `--disable-pass` shows. `''` is the whole document. Refused together with `--output`, which it would otherwise ignore. | ## Diagnostics @@ -71,7 +71,7 @@ error openapi/unresolved-ref openapi.yaml#/components/schemas/Pet/discriminator/ - the bare IR location for one an IR pass made about the document. A finding that concerns more than its own place, as a conflict between two declarations does, has -one line all the same, at the place it sits: its message names the declaration it kept, and the +one line all the same, at the place it sits: its message names the declaration it chose, and the list of what else it concerns, each with its role, is in the [JSON report](#json-report) and the IR document ([provenance](ir/provenance.md#related-places)). @@ -158,7 +158,7 @@ adds that line after the report, the report staying the first line, whatever sta refused document leaves a run its findings failed at `1`, as [Exit codes](#exit-codes) says. ```json -{"version": 2, "failed": false, +{"version": 3, "failed": false, "sources": [{"format": "openapi@3.1", "path": "openapi.yaml", "hash": "…"}], "findings": [{"diagnostic": {"severity": "error", "code": "openapi/unresolved-security-scheme", "message": "…", "provenance": {"source": 0, "pointer": "/security/0/key"}}, @@ -170,7 +170,7 @@ refused document leaves a run its findings failed at `1`, as [Exit codes](#exit- | Member | Holds | |---|---| -| `version` | the report's schema version, `2` | +| `version` | the report's schema version, `3` | | `failed` | the verdict, the one the exit status reads | | `sources` | the files each `provenance.source` indexes, as an IR document's `sources` | | `findings` | every finding, in the order reported: `diagnostic` as its stage reported it, an IR diagnostic, its `related` list naming what else the finding concerns ([provenance](ir/provenance.md#related-places)), `severity` as it is rated, `accepted` when a rule accepted it, and `rule`, the rule it met | @@ -266,7 +266,7 @@ marks, what it yields to, and what it reports. | Option | Values | Meaning | |---|---|---| -| `nullable-inference` | `true` (default), `false` | Read `nullable: true` as admitting null wherever a schema writes it, and keywords beside a `$ref` that admit null as a nullable reference, marking each reference only that reading makes nullable as inferred. `false` reads them only as the document's OpenAPI version does. | +| `nullable-inference` | `true` (default), `false` | Read `nullable: true`, and keywords admitting null, as widening what they are written on. Beside one `$ref` or expanded dynamic reference, written on the schema or on an inline `allOf` entry, they make the reference nullable only where no other conjunct excludes null. A union, a structure keyword such as `properties` or `items`, or a second reference widens nothing. A `type: "null"`, `const: null` or `enum: [null]` beside the one reference is said by it where its target admits no null. With no reference, `nullable: true` admits null for its whole schema. Each reference only this reading makes nullable is marked as inferred. `false` reads them only as the document's OpenAPI version does. [`nullable`](compilers/openapi.md#nullable) gives the whole rule. | | `discriminator-inference` | `true` (default), `false` | Read a union's tags off the strings each variant pins its tag property to: as the mapping of a `discriminator` declaring none, where OpenAPI's implicit mapping would route a variant by a component name it rejects, or not by every string it admits, and as a discriminator for a closed `oneOf` or `anyOf` declaring none, where every variant requires one property and pins it to strings no other variant admits; and read a subtype's tag off the strings it admits, where they rule out the component name its discriminator routes it by. What it reads is marked as inferred. `false` keeps only what the document declares. | | `kind-inference` | `true` (default), `false` | Lower a schema that names no kind as one writing the `type` its keywords giving a member, an element or a value a type speak of: an object for a `properties` or `patternProperties` naming a member or an `additionalProperties` holding a schema other than `true`, `{}` and `false`, an array for an `items` holding such a schema or a `prefixItems` naming a position, and a union of both where it writes keywords of each, marking each node as inferred. A `required`, a `discriminator`, a closure and a catch-all of `true` or `{}` infer nothing. `false` lowers such a schema to the top type, its shape keywords kept verbatim. | | `pagination-inference` | `true` (default), `false` | Read a `GET`'s or a `QUERY`'s pagination off the names it uses: a `page`, `page_number`, `offset`, `cursor`, `page_token`, `next_token` or `continuation_token` query parameter for where a walk continues and a `per_page`, `page_size` or `limit` one for the page size, and in each success response's body the list of items and, for a cursor or a token, the member handing back the next one. What it reads is marked as inferred, and an operation naming a walk it cannot settle is reported and left with none. An operation whose extensions, read under `extension-promotion`, speak of a pagination, filling one, failing to or stating it has none, is left to them. `false` keeps only what the document declares. | diff --git a/docs/compilers/openapi.md b/docs/compilers/openapi.md index a91fd9abd..6c1944393 100644 --- a/docs/compilers/openapi.md +++ b/docs/compilers/openapi.md @@ -30,6 +30,48 @@ tests in `compilers/openapi/e2e` hold every field to the code and read it both w conformance case is named by a rule, and each code by a rule or by `codesOutsideTheRules`, which gives the reason a code has no rule. [`CONTRIBUTING.md`](../../CONTRIBUTING.md) walks adding a rule. +## Words the rules use + +The rules use each word below in this one sense. The IR's own words, node, admits, answer, alias +chain, chain end, Unmodeled entry, holds and home, chosen and decided, and intersection, mean what +[the IR design's words](../ir/README.md#words) say. A rule that needs a new term adds it here in the +same change. + +| Word | Meaning | +|---|---| +| position | The place a schema is used: a component, a property, an array's items, a union branch, a parameter's or a body's schema. A `$ref`'s own place is its *reference site*. `ir.Position`, a line and column in a source, keeps its own sense. | +| allOf entry | One element of an `allOf`. An *entry* alone is always one; the other sense is always an *Unmodeled entry*. | +| conjunct | One part of what a position says at once: its own keywords, an inline `allOf` entry, a `$ref`, or a union beside them. | +| conjunction | The conjuncts of one position, together. | +| principal | The conjunct that decides a refinement, the others read as said of it ([`allof-refinement`](#allof-refinement)). | +| rest | The conjunction outside the union a position lowers. A *body* is only an HTTP body. | +| flattened entry | An inline `allOf` entry merged into the node its position lowers to. [`allof-inline-residue`](#allof-inline-residue) is the rule for flattened entries and what they keep. | +| keep, kept | Write verbatim into an Unmodeled entry, and nothing else. [`verbatim-preservation`](#verbatim-preservation) is the rule for what is kept. | +| pending keep | One conjunct's keep of one keyword, decided when its node settles. `annotation.PendingKeeps` holds a node's pending keeps. | +| chosen, passed over | What a rule takes over the others, and each it does not take. | +| unread | Read by no lowering. | +| unhomed | Without a field in the IR, and kept under `no_ir_home`. | +| says nothing | Narrows nothing beyond what the rest of the conjunction already says. | +| settle | Decide in a step run once the type registry is whole. | +| reading | How a version or a policy reads a keyword, as the nullable-inference policy reads `nullable: true`. | +| fold | Take one member's declarations into one ([`allof-redeclared-property`](#allof-redeclared-property)). | +| alike | Admitting exactly the same values. | +| reference chain, hop, end, reference cycle | The `$ref`s followed from a position, one hop each, to the schema they lead to, the chain's end. A chain that comes back to where it started is a reference cycle ([`reference-cycles`](#reference-cycles)). | +| link | A hyperlink, or an OpenAPI Link Object ([`links`](#links)), and nothing else. | +| reaches | Graph reachability: one node reaches another along the references between them. | +| keyword scope | The conjuncts a keyword's meaning depends on, as `additionalProperties` depends on the `properties` beside it. | +| branch, variant | A `oneOf` or `anyOf` element in the source, and the element of the `Union` it lowers to. | +| carrier | A property, a parameter or a header: a place that holds a reference to a type and the facts of that use. | +| declaration | One place a schema or a member is written. A member several `allOf` entries write has several declarations, which a fold takes into one. | +| restates | Writes what another conjunct already says, as a `type` naming the kind its `$ref`'s target declares. | +| writer | An overlay action that writes into the document ([`overlays`](#overlays)), and nothing else. | + +Retired from the rules, and renamed where met: *stand*, in every sense, for a literal word; +*voice*; *claim* and *ledger*, for pending keep; *elect*, *beat*, *winner*, *loser* and *keeper*, for +chosen and passed over; *meet* and *join*, for intersection; *silent* and *inert*, for says +nothing; *verdict* outside the harness, for answer; and *reach* in the sense of scope, for keyword +scope. Diagnostic codes, rule keys and code names keep the words they have. + ## 1. Reading a document ### `openapi-versions` @@ -41,11 +83,11 @@ reaches beside the source: its schemas are read in that minor's dialect, where n its Encoding Objects take that minor's defaults, its objects are held to that minor's table, and its `Document.Sources` entry names that minor. One declaring no version, such as a bare schema file, or a version the compiler does not read, such as `3.3.0` or a Swagger 2.0 file, is read at the source's -minor, and the compile stands. A source declaring a version that is not three runs of digits, major, -minor and patch, such as `3.0` or `3.1.0-rc1`, is reported as an `openapi/validation` error, of the -class `validation-invalid-format` ([`validation`](#validation)), and still lowers under the minor it -names; a document a reference reaches is read at the minor such a version names too, with no -finding, since only what a reference reaches is judged. Any other version is not this compiler's. +minor, and the compile proceeds. A source declaring a version that is not three runs of digits, +major, minor and patch, such as `3.0` or `3.1.0-rc1`, is reported as an `openapi/validation` error, +of the class `validation-invalid-format` ([`validation`](#validation)), and still lowers under the +minor it names; a document a reference reaches is read at the minor such a version names too, with +no finding, since only what a reference reaches is judged. Any other version is not this compiler's. The engine refuses a document declaring one before any compiler runs, as it refuses a Swagger 2.0 document ([`swagger-lift`](#swagger-lift)), and the compiler, handed one directly, refuses it with an `openapi/unsupported-version` error and compiles to no Document. @@ -91,7 +133,7 @@ A source, a document a reference reads or an [overlay](#overlays) that is one JS JSON, into the tree the YAML parser builds for the same text ([`json-as-yaml`](../parser-library.md#json-as-yaml)), because that parser refuses or misreads some JSON that RFC 8259 allows. It refuses a character outside the Basic Multilingual Plane written as a -surrogate pair of `\u` escapes, a `\/` escape, a key whose `:` stands more than 1,024 characters +surrogate pair of `\u` escapes, a `\/` escape, a key whose `:` lies more than 1,024 characters past the key's start (a key of more than 1,022 characters written `"key":`), a raw DEL, U+FFFE, U+FFFF or a C1 control other than U+0085 in a string, and a tab before the root value or on a line after the one it ends on, and it reads a raw U+0085 as a space. Each compiles as the same text @@ -206,7 +248,7 @@ scalar under any other tag keeps it. escapes or a `%YAML 1.2` directive (#1768). A plain `0o` or `0x` integer past 64 bits reads as the string the parser tags it, which a bound such as `maximum` refuses and a count such as `maxLength` keeps verbatim (#1975). A text writing every one of the 64 characters from - U+E000 that the reader stands in for what it reads as YAML 1.2, and a UTF-16 or UTF-32 text + U+E000 that the reader uses in place of what it reads as YAML 1.2, and a UTF-16 or UTF-32 text encoding no text, are read as the parser reads them. ### `source-budgets` @@ -449,7 +491,7 @@ are `fields` writing a `target`. A reusable action nothing references has no eff and `extends` is checked as a URI reference and compared with nothing. Every `target` and `copy` is read as an RFC 9535 JSONPath query by the compiler's own evaluator, over -the JSON value the source stands for: a YAML alias reads as the value it names, a member a `<<` +the JSON value the source means: a YAML alias reads as the value it names, a member a `<<` merge key brings in as a member of the mapping merging it, and a scalar as the compiler reads one, so a plain date is the string it spells, `0x10` the number 16, and two objects are equal whatever the order of their members. A selector RFC 9535 does not read is an `openapi/invalid-overlay` error @@ -477,10 +519,10 @@ application spend one budget of `overlay.MaxSteps` steps: a step for each node a compares or returns, each member a mapping's merges expand to and each element two compared arrays pair; a step per 8 bytes of a scalar read, once an evaluation, and per 64 bytes two scalars compare; a match or search its input's length and one more, times its program's weight; and a step for each -link of a target's path the action locates and each member of a mapping it indexes to find one. An +node on a target's path the action locates and each member of a mapping it indexes to find one. An action whose selectors pass the budget, or whose evaluation holds more than `jsonpath.MaxResults` -nodes in its nodelists at once, is an `openapi/budget-exceeded` error and nothing more applies. -A step is a count, not a time: the costliest take some hundreds of nanoseconds, so the budget admits +nodes in its nodelists at once, is an `openapi/budget-exceeded` error and nothing more applies. A +step is a count, not a time: the costliest take some hundreds of nanoseconds, so the budget admits tens of seconds of selection over a hostile overlay, which only the caller's context cuts shorter. The actions apply in order, each to the tree the ones before it left. An action takes the first of @@ -489,13 +531,13 @@ remove, or an action setting none, is an `openapi/overlay-action` warning. An ac `update` and `copy`, each of which the specification gives no effect beside the other, is refused as an `openapi/overlay-failed` error naming both. A remove deletes each node its target selects from the object or array holding it, with every earlier copy of a key the object writes twice, which -would otherwise stand in its place, at Overlay 1.0 a primitive too, since 1.0 has no other spelling for +would otherwise take its place, at Overlay 1.0 a primitive too, since 1.0 has no other spelling for removing a primitive member. A YAML alias elsewhere naming a node it removed, or one an action -copied in its place, keeps the value it stood for, as a copy the source wrote; a copy that -would grow the tree past `MaxSourceNodes` refuses the overlay as an `openapi/budget-exceeded` error, -and one past the attribution walk's node budget as an `openapi/overlay-failed` error. An update -writes its value into each node its target selects, and a copy writes the one node its `copy` -selects, as that node stood when the action began: +copied in its place, keeps the value it named, as a copy the source wrote; a copy that would grow +the tree past `MaxSourceNodes` refuses the overlay as an `openapi/budget-exceeded` error, and one +past the attribution walk's node budget as an `openapi/overlay-failed` error. An update writes its +value into each node its target selects, and a copy writes the one node its `copy` selects, as that +node was when the action began: 1. into an object, an object is merged member by member: a member the object lacks is added, a primitive replaces a primitive, an array is concatenated with an array, an object is merged into @@ -506,7 +548,7 @@ selects, as that node stood when the action began: array's elements are themselves arrays, as in an `examples` list: `[[1, 2]]` updated with `[3, 4]` becomes `[[1, 2], 3, 4]`, where the literal 1.0 reading gives `[[1, 2], [3, 4]]`, which an update of `[[3, 4]]` writes. An array whose elements are not arrays takes no array as one - entry, so 1.0 gives the update no other meaning there; + element, so 1.0 gives the update no other meaning there; 3. a primitive replaces a primitive, which only an Overlay 1.1 target selects. An Overlay 1.0 update selecting one is refused naming both of its spellings: an update of the object holding it, or the overlay declaring 1.1. @@ -516,13 +558,13 @@ all of one kind, as the specification requires, a copy whose `copy` selects more remove of the document's root. Each is an `openapi/overlay-failed` error naming the action, at it in the overlay, and the source compiles to no Document. A target is a position of the value, its normalized path: one selected twice is written once, and what is written holds no alias, a copy -being taken of what each alias names. A primitive an action writes over one the source declares -where it stands, rather than adding a value the source lacks, is an `openapi/overlay-replaced-value` +being taken of what each alias names. A primitive an action writes over one the source declares at +the same place, rather than adding a value the source lacks, is an `openapi/overlay-replaced-value` info naming both values, at the replacing value in the overlay; info, since overriding is a legitimate use, and `--fail-on` is a threshold over every code, so a run failing on this one alone -needs a rating by code. A write over what an earlier action wrote is not reported, nor is one into -a copy of a shared value standing at an alias's or a merge's position, nor an array an action -appends to, which keeps what the source declares in it. An action that changes nothing is an +needs a rating by code. A write over what an earlier action wrote is not reported, nor is one into a +copy of a shared value lying at an alias's or a merge's position, nor an array an action appends to, +which keeps what the source declares in it. An action that changes nothing is an `openapi/overlay-action` warning. An action whose target, or whose `copy`, selects nothing changes nothing, as the specification has it. Application is strict unless `Overlay.Lax` is set, and under strict such an action refuses the overlay as a likely typo, an `openapi/overlay-failed` error at @@ -536,11 +578,11 @@ dropped and the aliases inside it kept, and a mapping a member of which a `<<` m or that is written or removed from, has its merge keys replaced by a copy of each member they bring in that it does not write, in the value's order; a merge key reaching what the source refuses, a merge naming no mapping or a key that is no scalar in a mapping it brings in, stays beside the -copies, so the refusal stands. So an update of an anchored schema leaves each +copies, so the refusal remains. So an update of an anchored schema leaves each alias of it, and each mapping merging it, the value the source wrote, and a write through an alias or a merge writes that position alone; none draws a finding of its own, but one the source draws inside the node copied is drawn again at the copy, at the same line and column. A copy is the size of the subtree the -source writes, not of the value it stands for, keeps the source as the writer of what the source +source writes, not of the value it means, keeps the source as the writer of what the source wrote, and is charged to `MaxSourceNodes` before it is built. Each action is charged the nodes it can build before it runs: one whose charge would carry the tree, @@ -647,7 +689,7 @@ no overlay, reported as an `openapi/overlay-origin-incomplete` warning. as a member name holding `-` after a dot, is refused; an `extends` is compared with nothing; a pattern Go's engine cannot compile, such as a repetition past 1,000, matches nothing; `^` and `$` in a pattern anchor, where RFC 9485's grammar reads them as characters, which an info says; - nested descendant segments hold path links in proportion to their steps, which the nodelist bound + nested descendant segments hold path nodes in proportion to their steps, which the nodelist bound does not count, so an overlay that deepens a chain by copies and selects down it can hold gigabytes (#1960); an overlay over a tree at the node budget's edge counts the tree at each action (#1959); a finding inside a shared node an action copies is repeated at each copy (#1970). @@ -695,7 +737,7 @@ of schemas, is an error, since that lowering reads it as the empty schema, a val counts it among its entries. One written for a field whose requirement another rule reports is left to that rule. A security requirement's name is no field to leave out: its `null` lists no scopes, and the name -stands ([`security-requirements`](#security-requirements)). +remains ([`security-requirements`](#security-requirements)). The source is read as it writes it, an applied overlay's patch included, each object as the kind its position gives it. Each Schema Object is held to the rows of the dialect it is read in @@ -721,7 +763,9 @@ its message naming where in that document it lies. Each finding is made once: a merge key mounts at several positions draws one, naming the least position in that document that read it, by the order below, where that is another place than the one it is placed at. A node aliases share is placed at the least pointer of the places that mount it, where its anchor is written and where each alias of it is, pointers compared -token by token and each token by its bytes, so `/A/…` comes before `/A-/…`; its line and column +token by token as the source writes them, an array index by its number and any other token by its +text, so `/A/…` comes before `/A-/…` and `/A/9` before `/A/10`, the order every least pointer in +this document is read by; its line and column stay where its text is written. A message naming another node, as a repeated entry's names the copy it repeats, names the pointer a finding on that node is placed at, or, where no pointer places it, the position that read it. Which place a document writes first decides nothing, and a document @@ -811,7 +855,7 @@ gives it no effect is [`allow-reserved-locations`](#allow-reserved-locations)' a `e2e.TestCompile_ATypeMismatchOnASharedMountIsPlacedAtTheLeastMount`, `e2e.TestCompile_ANodeInsideTwoMountsIsPlacedByTheirTokens`, `specrules.TestCheck_AFindingNamesTheLeastPositionThatReadIt`, - `specrules.TestLessPointer_OrdersTokenByToken`, + `specrules.TestCheck_AFindingNamesTheLeastIndexThatReadItByItsNumber`, `specrules.TestCheck_ARepeatedEntryNamesItsFirstCopyWhereItIsPlaced`, `e2e.TestCompile_ARepeatedEntryNamesItsFirstCopyWhereItsDocumentHoldsIt`, `scan.TestLeast_OrdersByThePointersTokens`, `scan.TestLeast_AgreesWithSortingEveryPointer`, @@ -832,14 +876,14 @@ Operation's `responses` is required in 3.0 and not from 3.1, and a Response's `d error, of the class `validation-required-field`, at the object ([`validation`](#validation)), and one a rule requires only beside another field's value, such as an oauth2 scheme's `flows`, only where that value is written. A required field written as the empty string, or as an empty map, is -written, since every minor types it as a bare string or map, and stands unless the specification, -or a grammar it cites, refuses the empty value: an enumerated field (a Parameter's `in`, a security -scheme's `type`); a path parameter's `name`, which must match a template expression, none of which -the empty string names; a name sent in a header or a cookie, by a parameter or an API key, and an -HTTP `scheme`, each a token of RFC 9110 or RFC 6265; and a server `url` from 3.2, whose server URL -grammar requires a character. A name sent in the query, or a `querystring` parameter's, which is -never sent, is admitted. A `null` written for a required field is the value missing, an error at -the field. +written, since every minor types it as a bare string or map, and is accepted unless the +specification, or a grammar it cites, refuses the empty value: an enumerated field (a Parameter's +`in`, a security scheme's `type`); a path parameter's `name`, which must match a template +expression, none of which the empty string names; a name sent in a header or a cookie, by a +parameter or an API key, and an HTTP `scheme`, each a token of RFC 9110 or RFC 6265; and a server +`url` from 3.2, whose server URL grammar requires a character. A name sent in the query, or a +`querystring` parameter's, which is never sent, is admitted. A `null` written for a required field +is the value missing, an error at the field. - Cases: `empty-required-values`, `relaxed-required-fields` - Codes: `openapi/validation` @@ -907,15 +951,15 @@ Path Item's `additionalOperations` before 3.2, and a field 3.2 added to a Discri Object, draw the warning as any other construct does. A keyword JSON Schema 2020-12 added, written in a 3.0 schema or in one a draft before it reads ([`dialect-keywords`](#dialect-keywords)), is read as 2020-12 reads it and draws the warning too, at its key, its value held to 2020-12's row, true and -false standing as schemas where that row admits a schema, an entry of its list or map among them: in -a 3.0 schema in the words above, as a field 3.1 added, and in a draft's as a keyword its dialect -does not define. The rules 3.1 states over such a keyword, such as `prefixItems` holding an entry, -hold in a draft's schema and not in a 3.0 one, where the declared minor's rules run. Three such -keywords are not read: a `$schema` in a 3.0 schema, whose dialect is fixed, which the warning says -is kept verbatim and chooses nothing; draft 4's `$id`, which its `id` spells, read for nothing and -warned of by no such warning; and a `prefixItems` beside the `items` list a draft reads as its own -tuple, which is kept verbatim beside it ([`tuples`](#tuples)), as the warning says. The same table -judges a Parameter Object's `allowReserved` against where the declared minor applies it +false read as schemas where that row admits a schema, an entry of its list or map among them: in a +3.0 schema in the words above, as a field 3.1 added, and in a draft's as a keyword its dialect does +not define. The rules 3.1 states over such a keyword, such as `prefixItems` holding an entry, hold +in a draft's schema and not in a 3.0 one, where the declared minor's rules run. Three such keywords +are not read: a `$schema` in a 3.0 schema, whose dialect is fixed, which the warning says is kept +verbatim and chooses nothing; draft 4's `$id`, which its `id` spells, read for nothing and warned of +by no such warning; and a `prefixItems` beside the `items` list a draft reads as its own tuple, +which is kept verbatim beside it ([`tuples`](#tuples)), as the warning says. The same table judges a +Parameter Object's `allowReserved` against where the declared minor applies it ([`allow-reserved-locations`](#allow-reserved-locations)), and its `allowEmptyValue` against the style it is written under ([`allow-empty-value`](#allow-empty-value)). @@ -1002,13 +1046,13 @@ mapped twice, and a URL location ending in no `/` are refused as an option error mapping is applied where a document a URL names is opened, once the URL is spelled one way, before any read judges it, and never to an identifier: an `$id` or a `$self` keeps the URI it writes, so a reference relative to one is resolved against that URI, and the URL it names is then mapped or, out -of every prefix, read as a URL. The longest prefix wins: the rest of the URL is joined to a directory segment by segment, -each decoded, and one decoding to a separator names no location, so the reference fails unread and -no spelling leaves the location; a URL location takes the rest as written. The document is then -read, confined, named and labelled where its bytes are, so a file reached by its path and by a -mapped URL is one document, and a mapped location a document read over http(s) may not reach is -refused as any other. A URL refused as on the network says a mapping would place it. A document outside fails each reference naming it, and with no reader no document -is read. +of every prefix, read as a URL. The longest prefix is the one taken: the rest of the URL is joined +to a directory segment by segment, each decoded, and one decoding to a separator names no location, +so the reference fails unread and no spelling leaves the location; a URL location takes the rest as +written. The document is then read, confined, named and labelled where its bytes are, so a file +reached by its path and by a mapped URL is one document, and a mapped location a document read over +http(s) may not reach is refused as any other. A URL refused as on the network says a mapping would +place it. A document outside fails each reference naming it, and with no reader no document is read. Each document a reference reaches is a `Document.Sources` entry after the source and its overlay, ordered by its location: its path from the directory the source lies in, or where no relative path @@ -1107,44 +1151,45 @@ an absolute `$id` did. Every document a reached reference names is parsed before deemed unresolvable, as OAS 3.1.1 §4.3.1 requires, so a URI a document declares answers as that identifier whichever reference comes first, and is never refused. References are read in passes over the same set, each against the URIs the documents the last one reached declare, and only the -last pass's answers stand, so no declaration order reaches an answer. A document a pass read as a +last pass's answers hold, so no declaration order reaches an answer. A document a pass read as a location before another declared that URI is reached by no later pass, so it declares nothing, lowers nothing and is no `Document.Sources` entry. Where what a pass reaches turns on what those documents declare, so that no pass agrees with the one before it, every document read declares what -it does from the pass that would read against what an earlier one read. A pass reads every -document a reference names for the first time once its walks are done, in two tiers: the files, -which cost no request, then, once what every document open declares is read, each URL no document -open declares to the document that asked for it. A document is reached by the reference that -resolves into it, not by its read, and a reference whose URI a document read and not yet reached -declares waits for that document to be reached; where nothing more is reached, the documents -declaring what waits are reached, and what still waits is read as a location. The pass goes on, -reading again only the references that waited, while what the documents it reached declare changes -no URI whose answer it kept. So a chain of documents, each declaring the URI the one before it asked -for, is read in one pass, its cost growing with its length, and a file declaring a URL answers it -with no request. A pass is read again only where a location's own content leads to a declaration of -its URI; a URL held beside the URL-named document declaring it is read for nothing. A pointer passing a reference object, with tokens left to read, reads on where that -reference's chain ends, in whichever document, save at a path item, where a token naming a field -written beside its `$ref` reads that field ([`path-item-ref-fields`](#path-item-ref-fields)); a -pointer whose read needs a chain that needs that read is unresolved. A pointer into another OpenAPI -document passes the reference objects its grammar places, as one into the source does; a document -with no `openapi` member has no grammar to place one, so a pointer into it passes none. A `$ref` -written in another document's content is read in that document. What a `$ref` lands on lowers where it is declared, at -the position its pointer reaches read through each reference object it passes, in whichever -document, so two spellings reaching one declaration name one node. A use site takes what its schema -`$ref`'s chain ends on — an annotation, a form body's parts, a file body or a discriminator — -whichever documents the chain passes, as its type names that schema. An empty `$ref` names the -document's root, which holds no schema, so a chain reaching one ends on none and lends nothing, as -any chain that fails does, though the schema writing it keeps what it declares beside it. A YAML -alias or merge key is a copy written where it is placed, so what it holds is read at that position, -as the document's JSON places it, and raw YAML a schema `$ref` lands on, under an extension or in -another document, is read as a schema, as is a schema beneath an Encoding Object that another nests -through 3.2's `encoding`, `prefixEncoding` or `itemEncoding`, which no model holds. Every reading -of what the model holds takes such a schema as raw YAML under an extension at its place, the -`#/$defs/...` rule's and the weight of a copy ([`source-budgets`](#source-budgets)) among them, -but a pointer read on past a reference object reads afresh: a schema below the object its chain -ends on is that object's, which the load phase builds where no model holds one, as under an -extension. A `$ref` written beneath such a nested Encoding Object, a schema's or a Reference -Object's, is bound and reported as one anywhere else is, though the object itself is kept verbatim +it does from the pass that would read against what an earlier one read. A pass reads every document +a reference names for the first time once its walks are done, in two tiers: the files, which cost no +request, then, once what every document open declares is read, each URL no document open declares to +the document that asked for it. A document is reached by the reference that resolves into it, not by +its read, and a reference whose URI a document read and not yet reached declares waits for that +document to be reached; where nothing more is reached, the documents declaring what waits are +reached, and what still waits is read as a location. The pass goes on, reading again only the +references that waited, while what the documents it reached declare changes no URI whose answer it +kept. So a chain of documents, each declaring the URI the one before it asked for, is read in one +pass, its cost growing with its length, and a file declaring a URL answers it with no request. A +pass is read again only where a location's own content leads to a declaration of its URI; a URL held +beside the URL-named document declaring it is read for nothing. A pointer passing a reference +object, with tokens left to read, reads on where that reference's chain ends, in whichever document, +save at a path item, where a token naming a field written beside its `$ref` reads that field +([`path-item-ref-fields`](#path-item-ref-fields)); a pointer whose read needs a chain that needs +that read is unresolved. A pointer into another OpenAPI document passes the reference objects its +grammar places, as one into the source does; a document with no `openapi` member has no grammar to +place one, so a pointer into it passes none. A `$ref` written in another document's content is read +in that document. What a `$ref` lands on lowers where it is declared, at the position its pointer +reaches read through each reference object it passes, in whichever document, so two spellings +reaching one declaration name one node. A use site takes what its schema `$ref`'s chain ends on — an +annotation, a form body's parts, a file body or a discriminator — whichever documents the chain +passes, as its type names that schema. An empty `$ref` names the document's root, which holds no +schema, so a chain reaching one ends on none and lends nothing, as any chain that fails does, though +the schema writing it keeps what it declares beside it. A YAML alias or merge key is a copy written +where it is placed, so what it holds is read at that position, as the document's JSON places it, and +raw YAML a schema `$ref` lands on, under an extension or in another document, is read as a schema, +as is a schema beneath an Encoding Object that another nests through 3.2's `encoding`, +`prefixEncoding` or `itemEncoding`, which no model holds. Every reading of what the model holds +takes such a schema as raw YAML under an extension at its place, the `#/$defs/...` rule's and the +weight of a copy ([`source-budgets`](#source-budgets)) among them, but a pointer read on past a +reference object reads afresh: a schema below the object its chain ends on is that object's, which +the load phase builds where no model holds one, as under an extension. A `$ref` written beneath such +a nested Encoding Object, a schema's or a Reference Object's, is bound and reported as one anywhere +else is, though the object itself is kept verbatim ([`unmodeled-dialect-fields`](#unmodeled-dialect-fields)). A schema position of the model holds the schema the parser built there, whatever its YAML, so a `$ref` to a component written as a string names that component, as it lowers. A key written twice in one mapping is read as its last @@ -1158,7 +1203,9 @@ referencing position, with why, and the position lowers without it: a schema pos type, any other position to nothing at all, so the parameter, response or body it would have named is absent. Each is reported once, where it is written, in whichever document, and a `$ref`, a schema's or a reference object's, whose chain ends on another failing `$ref` is not reported for it, -as that one is. A reference object whose hop lands on a position holding no object of its kind, such +as that one is. A schema `$ref` its readers meet several times, as a union branch beside structure, +an `allOf` entry and the `$ref` a position names it by, is one fact: the report the first of them +draws is the one kept, worded as that reader words it. A reference object whose hop lands on a position holding no object of its kind, such as a string or a `null` under an extension, draws that error, worded as a schema `$ref`'s is (`it names a position that holds no parameter`), and nothing is reported at the position, whichever reference reaches it first. @@ -1201,7 +1248,7 @@ read as the parser expands them, and [`unknown-keys`](#unknown-keys) reports the `$dynamicRef` naming no `$dynamicAnchor` is the `$ref` it spells, and is read as one in every respect here, its `openapi/unresolved-ref` worded with the keyword it is written under. A chain of references that closes on itself is [`reference-cycles`](#reference-cycles)', whose message names -each link a `$ref`, whichever keyword wrote it. +each hop, a `$ref`, whichever keyword wrote it. - Cases: `schema-identifiers`, `component-media-types-32`, `reference-object-chains`, `merge-depth-bound` @@ -1210,18 +1257,18 @@ each link a `$ref`, whichever keyword wrote it. A Reference Object whose `$ref` is a null, a list, a mapping or a scalar tagged outside YAML 1.2's JSON schema ruleset, written by the mapping or merged into it by a `<<` key, names nothing: the -entry it stands in is read as left out, its other keys with it, and the rule table's error at the +entry it lies in is read as left out, its other keys with it, and the rule table's error at the `$ref` is the one report of it; a component kept verbatim shows it as written ([`unreferenced-components`](#unreferenced-components)). A `$ref` written as a number or a boolean is read as the text it spells, as such a value is wherever a string belongs, beside the rule table's -warning ([`validation`](#validation)), so `$ref: 5` names the file `5`. The parser's -model faults building such an object, and a 3.2 `additionalOperations` entry that is no mapping -([`nil-populate-panic`](../parser-library.md#nil-populate-panic)), so the load phase sets each -aside for the model's builds and puts it back before anything else reads the tree, in the source -and in what a reference reaches outside its model alike. A Path Item's -`$ref` is the item's own field, read the same way: one that names nothing is read as left out, and -the item as what else it writes. +warning ([`validation`](#validation)), so `$ref: 5` names the file `5`. The parser's model faults +building such an object, and a 3.2 `additionalOperations` entry that is no mapping +([`nil-populate-panic`](../parser-library.md#nil-populate-panic)), so the load phase sets each aside +for the model's builds and puts it back before anything else reads the tree, in the source and in +what a reference reaches outside its model alike. A Path Item's `$ref` is the item's own field, read +the same way: one that names nothing is read as left out, and the item as what else it writes. - Tests: `e2e.TestCompile_ExternalFileRefIsNotReadByDefault`, + `e2e.TestUnresolvedRef_ABranchPastTheMergeBoundIsReportedOnce`, `e2e.TestCompile_AFetchedDocumentMayNotReachAMorePrivateAddress`, `e2e.TestCompile_AnAddressOneDocumentCannotReachIsStillReadForAnother`, `e2e.TestCompile_APrivateDocumentMayReachAPrivateAddressButNotALocalOne`, @@ -1393,15 +1440,38 @@ source's own file name, a pointer read on past a reference object, or another do is reported once, as an `openapi/cyclic-ref` error at its least member, in the document that writes it, the source's members first and another document's by its location, so the report does not move with declaration order. Each member lowers to the top type with no report of its own, and the -document compiles. A YAML anchor recursive in itself would run the parser out of stack, so a source -holding one is refused before the parser reads it, as an `openapi/cyclic-ref` error, and compiles to -no Document; so is an overlay's patched tree. A document an external reference reads that holds one -fails each reference naming it instead, as it fails the source's other refusals +document compiles. An `allOf` writing nothing else but what says nothing of the instance (notes, +`title`, `description` and the other annotations, `$comment` among them, identifiers and meta +keywords, an `$id`, an anchor, `$schema`, `$vocabulary`, `$defs` or `definitions`, extensions, and a +keyword at the value its dialect equates with its absence, as `uniqueItems: false` or +`minLength: 0`, [`null-keywords`](#null-keywords)) is a node on such a chain where its conjunction +is a `$ref` alone, or `$ref`s each lying on the loop: an entry that is itself such a node is read in +place, an entry saying nothing, `true` or one writing only what says nothing, as `{description: x}`, +is set aside, and each `$ref` writes beside it only what says nothing, its siblings read as a 3.0 +`$ref`'s are too. A loop closed through such nodes, `A: {allOf: [{$ref: B}]}`, +`{allOf: [{allOf: [{$ref: B}]}]}` or `{allOf: [{$ref: B}, true]}` beside `B: {allOf: [{$ref: A}]}` +or `B: {$ref: A}`, is the loop a chain of bare `$ref`s is, reported and lowered alike, each member +keeping what the bare spelling's keeps, so `{$ref: B, type: string}` on it is the `string` keeping +its `$ref`, and a node stating nothing beside its `$ref`s keeps none of them, as `{$ref: B}` keeps +none: `{allOf: [{$ref: B}, {$ref: B}]}` is `{$ref: B}`. A loop through a schema writing anything +else, an entry writing a kind or a member beside its `$ref` among them, as +`{allOf: [{$ref: B, type: string}]}`, or composing a `$ref` off the loop, is a composition read to +its fixpoint ([`allof-refinement`](#allof-refinement)), not such a loop. Read by kind, such a loop +through such a node gives each member writing a kind that kind, keeping its `$ref`, and the node is +a use of the member its `$ref` names: `A: {allOf: [{$ref: B}], type: string}` beside +`B: {allOf: [{$ref: A}, {description: d}]}` makes `A` the `string` and `B` a use of `A`, in every +spelling of the node. A YAML anchor recursive in itself would run the parser out of stack, so a +source holding one is refused before the parser reads it, as an `openapi/cyclic-ref` error, and +compiles to no Document; so is an overlay's patched tree. A document an external reference reads +that holds one fails each reference naming it instead, as it fails the source's other refusals ([`source-budgets`](#source-budgets)): each is an `openapi/unresolved-ref` error saying why, and the rest of the document lowers. A loop of Reference Objects is found and reported the same way, its -kind named in the report (`never reaches a request body`), and neither its members nor what leads -into it lower or draw a report of their own. A pointer whose read passes a reference object whose -own read needs the first, as `A: {$ref: '#/components/responses/B/headers/H'}` beside +kind named in the report (`each a request body, refer only to each other by $ref`), and neither its +members nor what leads into it lower or draw a report of their own. The report names the loop's +members, says they refer only to each other, so none of them constrains a value or defines one, and +says to give one of them a definition of its own: for a schema, a type, properties or another +constraint. A pointer whose read passes a reference object whose own read needs the first, as +`A: {$ref: '#/components/responses/B/headers/H'}` beside `B: {$ref: '#/components/responses/A/headers/H'}`, is no loop but a read no order can make: each such `$ref` is an `openapi/unresolved-ref` error ([`references`](#references)). A schema reaching itself through what it declares is recursion, not a cycle ([`recursion`](#recursion)). An alias scan @@ -1420,7 +1490,15 @@ compile proceeds. `reftable.TestBind_ReportsALoopOfDefinitionsAtItsLeastMember`, `e2e.TestCompile_MergeChainPastBoundStillCompiles`, `reftable.TestBind_AnswersAlikeInEitherOrder`, `e2e.TestReferenceObjects_ALoopIsReportedOnceAtItsLeastMember`, - `e2e.TestReferenceObjects_AReadNeedingItselfIsUnresolved` + `e2e.TestReferenceObjects_AReadNeedingItselfIsUnresolved`, + `reftable.TestBind_ALoopOfAllOfPureReferencesIsALoop`, + `e2e.TestKeywordScope_AHopEveryEntryOfWhichIsOnTheCycleIsAHop`, + `e2e.TestKeywordScope_ACycleComposingAReferenceOffItStaysAComposition`, + `e2e.TestKeywordScope_AnEntryWritingBesideItsRefIsNoHop`, + `e2e.TestKeywordScope_ABareRefWritingBesideItOnAHopLoopKeepsWhatItWrites`, + `e2e.TestKeywordScope_ALoopThroughAHopIsReadByKind`, + `schema.TestRefinement_ALoopBesideAnEntrySayingNothingIsAReferenceLoop`, + `schema.TestRefinement_ALoopThroughAHopIsReadByKind` ## 2. The document and what it keeps @@ -1477,7 +1555,7 @@ reads the documents its relative references name from that URL, not from the fil A construct a rule keeps verbatim becomes an `Unmodeled` entry ([unmodeled](../ir/unmodeled.md)) on the node or carrier that owns its position, or on the Document -where the rule says no node stands for it: keyed `openapi:` for a keyword or field, or by +where the rule says no node holds it: keyed `openapi:` for a keyword or field, or by the scoped key the rule names where several objects reach one carrier ([`vendor-extensions`](#vendor-extensions)), under the reason the rule gives, and with a `Provenance` locating the construct itself rather than the node that carries it. @@ -1507,8 +1585,7 @@ extension that converts to no JSON is [`vendor-extensions`](#vendor-extensions)' - Cases: `yaml-merge-keys` - Codes: `openapi/unpreservable-construct` -- Tests: `schema.TestAllOf_UnpreservableEntryIsNotAnnounced`, - `schema.TestCoDeclaredFamily_UnpreservableIsNotAnnounced`, +- Tests: `schema.TestCoDeclaredFamily_UnpreservableIsNotAnnounced`, `schema.TestConstraints_ACountPastTheDecimalRangeIsRefused`, `schema.TestAllOf_TheBindingCountPastTheDecimalRangeIsRefusedInEveryOrder`, `annotation.TestValidationOnlyAt_AnUnconvertibleKeywordIsReportedNotKept`, @@ -1537,9 +1614,9 @@ also kept verbatim, because one declaration gets one structural home ([annotations](../ir/annotations.md#one-structural-home-per-declaration)). A value of another shape, or a non-empty `nodeType` outside the five the specification defines, is kept verbatim at the key and pointer the census itself uses, under `degraded_lowering`, with an -`openapi/degraded-construct` warning at the field, and the census finds the entry and adds nothing. -A key the raw mapping does not present directly — merged in through `<<` — is not read at all, so -the census still reports it, as an `openapi/unknown-key-unreachable` warning +`openapi/degraded-construct` warning at the field, and the census finds the Unmodeled entry and adds +nothing. A key the raw mapping does not present directly — merged in through `<<` — is not read at +all, so the census still reports it, as an `openapi/unknown-key-unreachable` warning ([`unknown-keys`](#unknown-keys)). An empty or null value is read as unset. A reading with no IR home is kept under `no_ir_home`, with an info `openapi/degraded-construct` at the field: the nested Encoding fields, and a Media Type Object's `description` at a parameter's or header's content @@ -1550,8 +1627,9 @@ neither a section nor a reference, and the reference is followed as any other is ([`unreferenced-components`](#unreferenced-components)). Nothing models the nested Encoding fields. The binder places each field the rule table gives an object outside a schema that can hold a schema or a Reference Object, at every minor and whatever the parser's model holds, so a `$ref` written -beneath a nested Encoding Object is bound and reported as any other is, and a schema one lands on -there is built from the raw YAML, as one an extension holds is. +beneath a nested Encoding Object is bound and reported as any other is, and so is a discriminator's +mapping value there ([`discriminator`](#discriminator)), and a schema one lands on there is built +from the raw YAML, as one an extension holds is. - Cases: `response-summary-32`, `xml-nodetype-32`, `nested-encoding-32`, `component-media-types-32` - Codes: `openapi/degraded-construct`, `openapi/unknown-key-unreachable` @@ -1568,7 +1646,9 @@ nowhere — no node, no `Unmodeled` entry, no diagnostic — and a declaration t disappears in silence. Every component section with no registry is therefore kept: each entry no lowering reached is preserved verbatim at `Document.Unmodeled["openapi:components/
/"]` under `no_ir_home`, at the entry's own -pointer, with no diagnostic. The sections are `responses`, `parameters`, `examples`, +pointer, with no diagnostic of its own; a discriminator within a kept entry has its values read as +references, one naming no schema reported as an `openapi/unresolved-ref` error at its entry +([`discriminator`](#discriminator)). The sections are `responses`, `parameters`, `examples`, `requestBodies`, `headers`, `links`, `callbacks`, `pathItems` and 3.2's `mediaTypes`, which is read at every version, as [`unmodeled-dialect-fields`](#unmodeled-dialect-fields) reads a field the parser does not model; `components/schemas` and `components/securitySchemes` are lowered @@ -1602,8 +1682,9 @@ not making a mistake a warning could name. `Reason` is where that decision lives for an oversight. - Cases: `unreferenced-components`, `component-media-types-32` -- Codes: `openapi/degraded-construct` +- Codes: `openapi/degraded-construct`, `openapi/unresolved-ref` - Tests: `document.TestUnreferencedComponents_ReferenceNothingFollowsKeepsItsTarget`, + `schema.TestKeptDiscriminator_ResolvesItsValuesWhereverItIsKept`, `document.TestUnreferencedComponents_ReadAsTheParserReadsThem`, `document.TestUnreferencedComponents_SelfReferenceByFileNameReaches`, `document.TestUnreferencedComponents_MergeDepthBoundIsReported`, @@ -1657,23 +1738,25 @@ name, and the title stays the node's `Docs.Summary`. A schema writing no title t inline conjuncts of its `allOf` write between them, each describing the same instance, where they write one set of words, and none where they write two: a title written beside a branch's `$ref` or `$dynamicRef` is that branch's own, the schema a `$ref` names lends none, and a branch's own `allOf` -is read through, as [`allof-classification`](#allof-classification) flattens it. A title is read -whole, one that is a sentence giving all its words, and as the parser reads a string, so one under -`!!binary` or a local tag names nothing. It names nothing where the document names the schema by a -key: a component schema, and a `$defs` or `definitions` entry, which keep their keys. It names -nothing at an `allOf` entry, named as its holder, and nothing where its words are a component -schema's canonical name in any document read, or another branch's of the same `oneOf` or `anyOf`, -written as its title or as its position (`variant_2`): the position keeps the name it has without -the title, so two branches titled alike are both named by position, whichever is written first. A -title is compared with no name a sibling `$ref` takes from the position it lands on, which the -component names cover where it lands on a component, so a pair meeting elsewhere is the names pass's -to report (`pass/name-collision`), since comparing would resolve every sibling's chain for each -branch. A hint composed from a position is mechanical, while one read from an annotation is a -reading, so policy (invariant 6): JSON Schema declares `title` a label for display, a request body -titled with a sentence under `operationId: createThing` is named by its dozen words where its -position gives `create_thing_request`, and editing a title renames the node. The title-names policy, -on by default, is the Go option `Options.TitleNames`, whose `Disabled` names every anonymous schema -by its position, and the text option `title-names`, which `false` turns off; the title is the node's +is read through, as [`allof-classification`](#allof-classification) flattens it, the schema's +statement listing the conjuncts: a `$ref` entry lends none, one naming nothing among them, and the +keywords written beside it lend their title as an inline entry's do. A title is read whole, one that is a sentence giving all its +words, and as the parser reads a string, so one under `!!binary` or a local tag names nothing. It +names nothing where the document names the schema by a key: a component schema, and a `$defs` or +`definitions` entry, which keep their keys. It names nothing at an `allOf` entry, named as its +holder, and nothing where its words are a component schema's canonical name in any document read, or +another branch's of the same `oneOf` or `anyOf`, written as its title or as its position +(`variant_2`): the position keeps the name it has without the title, so two branches titled alike +are both named by position, whichever is written first. A title is compared with no name a sibling +`$ref` takes from the position it lands on, which the component names cover where it lands on a +component, so a pair meeting elsewhere is the names pass's to report (`pass/name-collision`), since +comparing would resolve every sibling's chain for each branch. A hint composed from a position is +mechanical, while one read from an annotation is a reading, so policy (invariant 6): JSON Schema +declares `title` a label for display, a request body titled with a sentence under +`operationId: createThing` is named by its dozen words where its position gives +`create_thing_request`, and editing a title renames the node. The title-names policy, on by default, +is the Go option `Options.TitleNames`, whose `Disabled` names every anonymous schema by its +position, and the text option `title-names`, which `false` turns off; the title is the node's `Docs.Summary` either way. A hint read under it is marked no `Inferred`, since a `Hint` with no `Source` is a suggestion already. A hint changes no ID. A const branch's title is its member's summary alone ([`string-const-union`](#string-const-union)). @@ -1714,7 +1797,7 @@ timestamp to `string` in the spelling written (`2021-1-1` stays `2021-1-1`, neve number is the literal's exact decimal text in `Number`, never a `float64`: a magnitude past float64 or int64 keeps every digit, `.5`, `+5` and `09` take their JSON spellings (`0.5`, `5`, `9`), `_` separators drop, a YAML integer base resolves (`0644` is `420`, `0x1f` is `31`, `0b1010` is `10`), -and digits, exponent and trailing zeros otherwise stand as written (`10.0`, `1.10e+3`). A plain +and digits, exponent and trailing zeros otherwise stay as written (`10.0`, `1.10e+3`). A plain scalar that YAML resolves to a string only because it is past float64's range is still the number it spells, never its text: a decimal literal a `BigVal` holds (its exponent within `ir.MaxDecimalExp`) is that number, and one past that exponent is a number no `Value` holds, as the @@ -1821,8 +1904,8 @@ Every entry of `components/schemas` (including one keyed `""`, at A schema that reaches itself through `$ref` — directly, through a property, `items`, `additionalProperties`, a union branch or an inline position, or through another component — lowers -to a `TypeRef` to the ID the schema was registered under before its body lowered, so the cycle lives -in the type graph by ID ([design rules](../ir/README.md#design-rules)), whichever declaration +to a `TypeRef` to the ID the schema was registered under before its keywords lowered, so the cycle +lives in the type graph by ID ([design rules](../ir/README.md#design-rules)), whichever declaration lowers first, with no diagnostic. A chain of `$ref`s that never reaches a node without one (`A: {$ref: B}`, `B: {$ref: A}`) is not recursion but a cycle with no schema in it, which [`reference-cycles`](#reference-cycles) reports. @@ -1897,7 +1980,7 @@ the `$ref` would lend written alone, since the visibility and `default` of the u `e2e.TestRefUseBound_AReferenceToACarriedPositionReadsItInEitherOrder`, `schema.TestSchemaExamples_ComponentRefSiblingKeepsThem`, `schema.TestRefinement_ACarrierReadsThroughARefinement`, - `schema.TestUse_ADefaultBesideItsValueSetStands`, + `schema.TestUse_ADefaultBesideItsValueSetRemains`, `schema.TestUse_ADefaultNoNarrowingExcludesReadsAsBesideARef`, `schema.TestUse_ACarrierReadsThroughADecorator`, `schema.TestUse_ALoopOfNarrowingEnumsEnds`, `annotation.TestEffectiveDeprecated_AnySchemaDeprecates`, @@ -1918,31 +2001,31 @@ writes a `$ref` carry `summary` and `description` beside it, and the pair descri the referenced object rather than the object. Where the IR has a docs field at the position — a parameter, a response or error case, a header, an example, a request body, a security scheme, a body's media type, a link — both are read off the entry and folded over the declaration's docs field -by field, a sibling the entry writes winning and one it omits leaving the declaration's value -standing. -A component that is itself +by field, a sibling the entry writes winning and one it omits leaving the declaration's value as it +is. A component that is itself a `$ref` (an alias) is a use of what it names, so the fold runs along the whole chain from the declaration outward: an alias's siblings override the declaration's, and a use site's override the alias's. The fold applies at every version whose parser presents the siblings, which is all of them: -the Reference Object's wrapper is version-independent, and dropping a declared sibling in silence is -the defect the rule fixes. It is a documented departure from OpenAPI's clause that such a sibling -has "no effect" where the referenced object type does not allow one: the IR has a docs field at each -of these positions, keeping it loses nothing, and the alternative is the silent loss the clause -permitted. OpenAPI 3.0 goes further, admitting no key beside a `$ref` and saying one SHALL be +the Reference Object's wrapper is version-independent, and dropping a declared sibling without a +report is the defect the rule fixes. It is a documented departure from OpenAPI's clause that such a +sibling has "no effect" where the referenced object type does not allow one: the IR has a docs field +at each of these positions, keeping it loses nothing, and the alternative is the unreported loss the +clause permitted. OpenAPI 3.0 goes further, admitting no key beside a `$ref` and saying one SHALL be ignored; there the fold is the 3.1 reading, and each sibling it reads is reported with an `openapi/later-version-construct` warning ([`later-version-construct`](#later-version-construct)). Every other key a Reference Object of the chain writes beside its `$ref`, read as the model reads the mapping, a `<<` included, rides on the node the use lowers to, under `openapi:reference//`: `i` is 0 for the use, then counts the aliases the chain passes, -nearest first, so a use and an alias writing one key are two entries. Each is kept `out_of_scope`, -OpenAPI giving it no effect, with its own key's provenance in the document writing it; the rule -table reports it ([`unknown-keys`](#unknown-keys)), and keeping it reports nothing more. Where the -position has no docs field, a callback's and a parameter's or header's content entry's, the use folds -nothing, so the `summary` and `description` each Reference Object writes are kept the same way, -`no_ir_home`, each reported as an info `openapi/unhomed-construct` at its key, and the entry leaves -when a docs field arrives. The Media Type Object's own keys keep `openapi:content//`, which -a key of the chain's never shares: a key is read whole, never by its prefix. +nearest first, so a use and an alias writing one key are two Unmodeled entries. Each is kept +`out_of_scope`, OpenAPI giving it no effect, with its own key's provenance in the document writing +it; the rule table reports it ([`unknown-keys`](#unknown-keys)), and keeping it reports nothing +more. Where the position has no docs field, a callback's and a parameter's or header's content +entry's, the use folds nothing, so the `summary` and `description` each Reference Object writes are +kept the same way, `no_ir_home`, each reported as an info `openapi/unhomed-construct` at its key, +and the Unmodeled entry leaves when a docs field arrives. The Media Type Object's own keys keep +`openapi:content//`, which a key of the chain's never shares: a key is read whole, never by +its prefix. | Use | Node the entries ride on | Scope before `reference//` | Folds docs | |---|---|---|---| @@ -1993,7 +2076,7 @@ declaration that owns it. - Cases: `defaults`, `readonly-writeonly`, `inline-residue` - Codes: `openapi/degraded-construct` - Tests: `e2e.TestAnnotationRetention_OtherDeclarationShapes`, - `schema.TestPropertyPosition_ResidueStaysOutOfTheTypeNode`, + `schema.TestPropertyPosition_UseBoundKeywordsStayOutOfTheTypeNode`, `e2e.TestCompile_AReferenceLeavesItsTargetToItsOwnerInEitherOrder` ### `docs-and-deprecation` @@ -2100,20 +2183,27 @@ and referent the other, or on inline `allOf` entries that redeclare it — admit lowers as declared, to `Visibility{InvisibleInEveryLifecycle: true}` ([properties](../ir/properties.md#visibility)), and is reported once, as an `openapi/disjoint-visibility` warning at the invisible property or at the schema of the invisible -header, or for `allOf` at the redeclaration that empties the set (an entry repeating a field already -invisible reports nothing more). It is not a conflicting redeclaration -([`allof-redeclared-property`](#allof-redeclared-property)), which keeps one declaration over -another, nor a degraded construct: `InvisibleInEveryLifecycle` states the intersection exactly, and -the warning says only that no request or response can carry the field. A flag set `false` states -nothing. A pair written where no `Visibility` can land — an `items` schema, a parameter's schema — -is kept verbatim and not reported ([`parameter-schema-keywords`](#parameter-schema-keywords)); a -component's is reported at each property that references it. +header, or for `allOf` where redeclarations empty the set and none of them is invisible on its own: +one that is, as a schema writing both flags or a part whose own fold emptied the set, is reported by +its own reader, so an entry repeating a field already invisible reports nothing more, in either +order of the entries. That report sits at the first written of the declarations writing +`readOnly: true` or `writeOnly: true`, in the document listed first and then at the pointer written +first ([`allof-redeclared-property`](#allof-redeclared-property)), and its message names each of +them by its pointer in that order, so the order of the entries decides neither. It is not a +conflicting redeclaration ([`allof-redeclared-property`](#allof-redeclared-property)), which chooses +one declaration over another, nor a degraded construct: `InvisibleInEveryLifecycle` states the +intersection exactly, and the warning says only that no request or response can carry the field. A +flag set `false` states nothing. A pair written where no `Visibility` can land — an `items` schema, +a parameter's schema — is kept verbatim and not reported +([`parameter-schema-keywords`](#parameter-schema-keywords)); a component's is reported at each +property that references it. - Cases: `readonly-writeonly` - Codes: `openapi/disjoint-visibility` - Tests: `schema.TestModel_ReadOnlyAndWriteOnlyTogetherAreVisibleNowhere`, `e2e.TestAllOfVisibilityMerge_DisjointRestrictionsAreInvisibleNotAConflict`, - `merge.TestFold_AlreadyInvisibleVisibilityIsNotReAnnounced` + `merge.TestFold_AlreadyInvisibleVisibilityIsNotReAnnounced`, + `openapi.TestFoldReports_DisjointVisibilitySitsAtTheFirstWrittenRestriction` ### `nullable` @@ -2126,11 +2216,24 @@ names `null`, and only where the keywords beside agree: an `enum` admits null on beside it, and one not listing it takes a `type: [string, "null"]` back out; an `allOf` admits null only where every conjunct does, the null sitting on the reference that names the composition rather than on its `Base` or a `Mixin`; a `$ref` admits it only where the keywords beside it and what it -lands on both do, read one hop at a time so that an alias's own keywords count; and a union's -variant that admits null is marked on that variant's reference. Whether a property must be present -is `Property.Required`, apart from this ([properties](../ir/properties.md)), so required and -nullable make four distinct lowerings. A union of one branch and `null` collapses to a nullable -reference ([`union-null-variant`](#union-null-variant)). +lands on both do, read one hop at a time so that an alias's own keywords count, and so does a +`$dynamicRef` or `$recursiveRef` the position expands, by its target; a union admits it where a +branch does and takes it away where none does, its null on the reference where a branch written in +place admits null alone ([`union-null-variant`](#union-null-variant)), and on a variant's reference +where another branch admits it, which a union collapsing to that one variant holds on the reference +(declared where the variant declares it). Each schema has one such answer, read once a run from its +own keywords, in the dialect of the document holding it, and the answers of the schemas it reads, in +dependency order, a cycle settled whole as the null it admits, and no depth cuts it, so a chain of +`allOf`s to null admits null at every level. That is its first stage. In the second, once it is +settled, what the union its conjunction chooses says of null beyond its branches is read into it, +from answers the first stage settled alone: a null branch the policy lifts for the whole schema, a +`oneOf` refusing a null two of its branches leave in ([`union-null-only`](#union-null-only)), and a +union of value sets the rest intersects as the flat `enum` of its members does +([`union-beside-structure`](#union-beside-structure)), so the answer is the same whichever schema +asks first. Whether a property must be present is `Property.Required`, apart from this +([properties](../ir/properties.md)), so required and nullable make four distinct lowerings. A union +of one branch and `null` collapses to a nullable reference +([`union-null-variant`](#union-null-variant)). OpenAPI 3.0's `nullable: true` adds `null` to the `type` written in the same Schema Object, as `type: [T, "null"]` does from 3.1, and then conjoins as that does: 3.0.3 and 3.0.4 state it, as a @@ -2139,17 +2242,43 @@ keyword. Documents written to 3.0.0's looser wording, or carried to 3.1, still use it to say that a schema admits null, and write `{$ref: T, type: [object, "null"]}` for the nullable reference that `{$ref: T, nullable: true}` was meant to be. So the nullable-inference policy, on by default, reads such a null as widening what it is written on rather than conjoining -with it: `nullable: true` admits null for the whole schema it is written on, whatever else that -schema says, and keywords beside a `$ref` that admit null by themselves admit it for the whole -reference, and a `nullable: true` on an inline `allOf` entry writing no `properties` admits it for -the whole schema holding the `allOf`, a `type` beside the `allOf` included, as beside the `allOf` it -does ([`allof-inline-residue`](#allof-inline-residue)). A `type` without `null` beside a `$ref` still -narrows what it lands on, and a `type: [T, "null"]` on a conjunct of an `allOf` conjoins with the -rest. A reference whose null only that reading admits names `nullable-inference` in +with it. Where the conjunction a schema writes, its own keywords and its inline `allOf` entries, +holds exactly one reference, and its other objects admit null together, each read with its own +`nullable: true` admitting null for its type, as OpenAPI 3.0.3 applies it, a `const` or `enum` +beside it conjoining as another object's does, they make it that reference or null, whichever +object writes the null, in every spelling: `{$ref: T, K}`, `{allOf: [{$ref: T}], K}`, +`{allOf: [{$ref: T}, {K}]}` and `{$ref: T, allOf: [{K}]}` alike. Another object excluding null, a +union, or a `properties`, `items`, `prefixItems`, `additionalProperties` or `patternProperties` +that any object of the conjunction writes, the position's own included, conjoins with the +reference and widens nothing, and so do two references; notes, extensions and bounds beside it stop +nothing. The one reference may be a dynamic reference the position expands. A `type: "null"`, a +`const: null` or an `enum: [null]` beside the one reference, on any object of the conjunction, is +then that nullable reference, the keyword said by it and kept nowhere, where what the reference +lands on admits no null; beside a target admitting null it narrows the target to null, as written, +and the position is the null type keeping the reference. A `nullable: true` beside a +reference the policy widens nothing by, which then admits no null, is reported as a warning +`openapi/unwidened-nullable` at the keyword, since the null its author wrote reaches no reference, +naming by its path from the position each conjunct keeping null out, a `$ref` with the target it +names and any other by the keyword that keeps it out, and the reference left without a null. It says +nothing of the instance, as `nullable: false` does ([`null-keywords`](#null-keywords)), so an +`allOf` of one `$ref` beside it is the `$ref` alone ([`allof-classification`](#allof-classification)). Where the conjunction holds no reference, a +`nullable: true` any object of it writes, the schema itself or an inline `allOf` entry, admits null +for the whole conjunction, whatever else it says, a union none of whose branches admits null among +it, as the flat spelling writing them in one object does +([`allof-inline-residue`](#allof-inline-residue)). Where no branch of that union shares a value with +the rest, the position admits that null alone, the closed `Enum` with no member keeping the union, +and its dead branches draw one `openapi/unsatisfiable-schema` at the union's keyword, the position +none. Where no branch lives beside a rest keeping null out, the policy lifts a null branch's null +for the whole schema, which then admits that null alone, as every reference to it does, the info +at the branch ([`union-beside-structure`](#union-beside-structure)). A `type` without `null` +beside a `$ref` still +narrows what it lands on, and a `type: [T, "null"]` on a conjunct of an `allOf` holding no reference +conjoins with the rest. A reference whose null only that reading admits names `nullable-inference` in `TypeRef.Inferred` (invariant 6), so `Nullable` with no marker is the declared reading, and each such null is reported once as an info `openapi/inferred-nullable`, at the `nullable` keyword or, for -keywords beside a `$ref`, at the schema that writes them, saying why its version does not admit it, -whatever references its schema. The policy is the Go option `Options.NullableInference`, whose +keywords beside a `$ref`, at the object that writes them, saying why its version does not admit it, +naming what it is written beside: the type it lacks, an `enum`, a `const`, a union by its keyword, +an `allOf` entry, or the `$ref`, whatever references its schema. The policy is the Go option `Options.NullableInference`, whose `Disabled` reads the keywords only as their version defines them, and the text option `nullable-inference`, which `false` turns off. A `nullable` in a 3.1 or 3.2 schema that the policy does not read is a keyword its dialect does not define, kept verbatim under `openapi:nullable` @@ -2173,12 +2302,10 @@ With the policy on, its info sits at the same pointer. With the policy off nothi `$ref` the keyword is a later minor's construct, warned of as one ([`later-version-construct`](#later-version-construct)), so it draws no second warning there. -- Status: partly built: under the nullable-inference policy a union with a null branch written - beside a `$ref` widens the reference, and the same union beside an `allOf` of the `$ref` does not, - so the two spellings give it a different null (#2109). - Cases: `nullable-30`, `nullable-31-ref`, `nullable-enum-31`, `nullability-four-states`, `nullability-conjunction`, `nullable-keyword-30`, `nullable-keyword-31` -- Codes: `openapi/inferred-nullable`, `openapi/unknown-schema-keyword`, `openapi/validation` +- Codes: `openapi/inferred-nullable`, `openapi/unwidened-nullable`, `openapi/unknown-schema-keyword`, + `openapi/validation` - Tests: `schema.TestSchemaRef_NullableNormalization`, `schema.TestNullableInference_EachShapeReadsByItsVersion`, `e2e.TestNullableInference_AKeywordIsReportedOnceAtItself`, @@ -2193,7 +2320,25 @@ With the policy on, its info sits at the same pointer. With the policy off nothi `schema.TestNullableTrue_PastTheMergeBoundOnlyAListedKeyStates`, `e2e.TestNullable_AValueThePolicyDoesNotReadIsKeptAtOpenAPI31`, `e2e.TestNullable_AValueNoPolicyReadsIsKeptOnANullBranch`, - `e2e.TestNullable_OpenAPI30KeepsNoValueAsAnUnknownKeyword` + `e2e.TestNullable_OpenAPI30KeepsNoValueAsAnUnknownKeyword`, + `e2e.TestNullAnswer_AChainOfAllOfReferencesToNullAdmitsItAtEveryLink`, + `e2e.TestNullAnswer_ACycleKeepsTheNullItAdmits`, + `e2e.TestNullAnswer_OneUnionAdmittingNoNullTakesItAway`, + `e2e.TestNullAnswer_ANullableBesideAUnionAdmittingNoNullIsInferred`, + `e2e.TestNullAnswer_ThePolicyWidensAReferenceAlikeInEverySpelling`, + `e2e.TestNullAnswer_AValueKeywordOfNullAloneBesideAReferenceIsTheNullableReference`, + `e2e.TestNullAnswer_TheIdiomIsTheAnswersWidening`, + `e2e.TestNullAnswer_ThePolicyWidensNothingBesideAUnionOrStructure`, + `e2e.TestNullAnswer_ANullableBesideAReferenceAndAUnionIsNotWidened`, + `e2e.TestNullAnswer_AnExpandedDynamicRefReadsItsTargetsNull`, + `e2e.TestNullAnswer_EachSchemasNullableIsReadInItsOwnDocumentsDialect`, + `e2e.TestNullAnswer_AScalarsBaseIsWhatItsSchemaAdmitsInEverySpelling`, + `e2e.TestCompile_AUnionAndARestShareNullOnlyWhereBothAdmitIt`, + `schema.TestNullable_AUnionBesideAPolicyNullPairLeavesThatNullAlone`, + `schema.TestNullAnswer_ReadsGrowLinearlyWithTheSchemasRead`, + `schema.TestNullableInference_WhyNamesTheUnionOrEntryTheNullIsBeside`, + `schema.TestNullableInference_ANullableBesideAReferenceItWidensNothingIsReported`, + `schema.TestAllOf_ANullableSayingNothingLeavesTheUseOfOneRef` ### `schema-examples` @@ -2233,77 +2378,83 @@ An `allOf` whose kinds are an object alone lowers to the composing `Model`'s `Ba ([models](../ir/models.md#composition)); any other is [`allof-refinement`](#allof-refinement)'s. An `allOf` of one `$ref` saying nothing else is neither: where its other entries and the schema writing it state nothing of the instance (an empty schema, `true`, a comment, an anchor, `$defs`, a -keyword left out), `{allOf: [{$ref: T}]}` admits exactly what `T` does, whatever that is, so it is the -reference, hoisting no node, and a carrier reads the target's documentation as through a bare `$ref` -([`ref-use-site`](#ref-use-site)): over `false` it names `false`'s node, and a reference naming no -schema lowers to the top type with its one `openapi/unresolved-ref`, read or not. Only a read cut -short, by a cycle of such `allOf`s or a value no reading converts, still composes: one past the +keyword left out or written at the value equating with its absence, +[`null-keywords`](#null-keywords), a `type` naming exactly the kinds `T` declares, null aside, which +narrows nothing `T` admits), `{allOf: [{$ref: T}]}` admits exactly what `T` does, whatever that is, +so it is the reference, hoisting no node, and a carrier reads the target's documentation as through +a bare `$ref` ([`ref-use-site`](#ref-use-site)): over `false` it names `false`'s node, and a reference naming no +schema lowers to the top type with its one `openapi/unresolved-ref`, read or not. A loop of such +`allOf`s, as `LA: {allOf: [{$ref: LB}]}` beside `LB: {allOf: [{$ref: LA}]}`, is a loop of +references ([`reference-cycles`](#reference-cycles)): each member is the top type keeping nothing, +and the loop draws one `openapi/cyclic-ref` error, so `morphic compile` exits 1. One past the bounds of [`allof-refinement`](#allof-refinement) is the reference too, as those bounds stop only -what an election compares, and this one compares nothing. A component, or a position a `$ref` names, still owns a node: over -an object alone the `Model` whose `Base` is that object, in this spelling and the bare `$ref`'s; -over any other target, one admitting null, which a `Base` does not carry, or a reference no node -answers, the `Scalar` alias. A -`$ref` entry composes only where the schema it lands on lowers to an object alone, null aside, to -the union of a `type` list holding an object, whose object variant it composes (below), or where its -own read is cut short, as over a schema whose `$ref`s lead round a loop: the sole -such entry becomes `Base`, and of several, of those to a schema taking part in a discriminator -hierarchy (one declaring a `discriminator`, or composing through `allOf`, at any depth, a schema -that does, the ancestors [`discriminator-value`](#discriminator-value) reads a tag off), one whose -hierarchy's mapping names the composing schema before one whose does not, then the one whose -reference text is the least. Every other such `$ref` entry becomes a `Mixin`, so a schema -composing a subtype of a discriminated base beside another `$ref` is a subtype of that base too. A -`$ref` entry whose target +what the choice compares, and this one compares nothing. A component, or a position a `$ref` names, +still owns a node: over an object alone the `Model` whose `Base` is that object, in this spelling +and the bare `$ref`'s; over any other target, one admitting null, which a `Base` does not carry, or +a reference no node answers, the `Scalar` alias. A `$ref` entry composes only where the schema it +lands on lowers to an object alone, null aside, to the union of a `type` list holding an object, +whose object variant it composes (below), or where it names no schema, as a cycle of `$ref`s writing +nothing else does: the sole such entry becomes `Base`, and of several, of those to a schema taking +part in a discriminator hierarchy (one declaring a `discriminator`, or composing through `allOf`, at +any depth, a schema that does, the ancestors [`discriminator-value`](#discriminator-value) reads a +tag off), one whose hierarchy's mapping names the composing schema before one whose does not, then +the one whose reference text is the least. Every other such `$ref` entry becomes a `Mixin`, so a +schema composing a subtype of a discriminated base beside another `$ref` is a subtype of that base +too. A `$ref` entry whose target admits every kind, or another kind than an object, composes nothing, so no `Model` names a base or a mixin known to be no object: its reference is kept under `openapi:$ref`, or `openapi:$ref/` by reference text where several are kept, a failed one's among them (`degraded_lowering`), with an info `openapi/degraded-construct` at the entry, and its target still lowers. What such an entry -writes beside its `$ref` is a conjunct of its own, kept by keyword as an inline entry's is. A composition meets one -only where its read is cut short or its conjuncts share no value, as `{allOf: [{$ref: List}], type: -object}` over an array does. A `$ref` entry naming no schema composes nothing either, and is kept -under `openapi:$ref` ([`allof-inline-residue`](#allof-inline-residue)). The election reads the source, so no declaration order decides it, and a field -redeclared as several models composes them as such an `allOf` does +writes beside its `$ref` is a conjunct of its own, kept by keyword as an inline entry's is. A +composition holds one only where its kinds are an object alone; where the conjuncts' kinds share +none, as `{allOf: [{$ref: List}], type: object}` over an array, the position is the bottom of +[`allof-refinement`](#allof-refinement), point 4, keeping the `$ref`. A `$ref` entry naming no +schema composes nothing either, and is kept under `openapi:$ref` +([`allof-inline-residue`](#allof-inline-residue)). The choice reads the source, so no declaration +order decides it, and a field redeclared as several models composes them as such an `allOf` does ([`allof-redeclared-property`](#allof-redeclared-property)), reading the hierarchy off the discriminator a model or a union holds and each model's supertypes. An inline entry merges into the composing model's own `Properties`, each property keeping its own provenance ([`allof-inline-residue`](#allof-inline-residue), -[`allof-redeclared-property`](#allof-redeclared-property)). So every `$ref` entry stays composed -and a declaration a fold drops stays kept, while what a declaration folded into a field adds lands -on the field without its source. A `$ref` entry naming a union of objects is no exception: the union -is the `Base` or a `Mixin`, never distributed over its variants as one written beside the `allOf` is +[`allof-redeclared-property`](#allof-redeclared-property)). So every `$ref` entry stays composed and +a declaration a fold drops stays kept, while what a declaration folded into a field adds lands on +the field without its source. A `$ref` entry naming a union of objects is no exception: the union is +the `Base` or a `Mixin`, never distributed over its variants as one written beside the `allOf` is ([models](../ir/models.md#a-union-a-composition-names)). One naming a schema whose `type` list holds an object and another kind composes that list's object variant, the one node of that kind its union -holds, standing at `…/type/`: `Cat: {allOf: [{$ref: Pet}, {type: object, …}]}` over +holds, lying at `…/type/`: `Cat: {allOf: [{$ref: Pet}, {type: object, …}]}` over `Pet: {type: [object, string], properties: …}` has the variant as its `Base`, so it inherits what `Pet` declares of an object and keeps the tag `Pet`'s discriminator gives it. A union a `oneOf` or -`anyOf` writes is not unpacked: it -may hold several objects, or none a model is, so one admitting another kind is kept as above. The -list is read only where the entry's `$ref` lands: one landing on another `$ref` to `Pet`, as -`{$ref: Chain}` over `Chain: {$ref: Pet}` does, is kept as above too. +`anyOf` writes is not unpacked: it may hold several objects, or none a model is, so one admitting +another kind is kept as above. The list is read only where the entry's `$ref` lands: one landing on +another `$ref` to `Pet`, as `{$ref: Chain}` over `Chain: {$ref: Pet}` does, is kept as above too. `allOf` is associative, so an inline entry writing a non-empty `allOf` is flattened into the enclosing list before the entries are classified: its own entries take its place, in source order and depth first, each keeping the pointer it was written at, and its `properties` and `required` merge after them, as a composing schema's own merge after its entries'. So `allOf: [{allOf: [A, B]}]` classifies as `allOf: [A, B]`, and nothing is reported. Whatever else the entry writes that -the merge does not consume is kept beside the composition as residue +the merge does not consume is kept beside the composition, as what a flattened entry keeps ([`allof-inline-residue`](#allof-inline-residue)), so `{unevaluatedProperties: false, allOf: [A, B]}` composes `A` and `B` and is also kept whole, for its unevaluated keyword. Flattening stops 32 levels down: an entry nested inside -32 flattened entries is not flattened itself, so its `allOf` is residue, and it is reported as nested -past the flattening depth of 32. This is not the flattening the +32 flattened entries is not flattened itself, so its `allOf` is among what the entry keeps, and it +is reported as nested past the flattening depth of 32. This is not the flattening the [design rules](../ir/README.md#design-rules) leave to emitters: every `$ref` entry still composes as a `Base` or `Mixin`, and all that goes is a grouping no instance can observe, which an inline entry owns no node to keep ([`allof-inline-residue`](#allof-inline-residue)). - Cases: `allof-inheritance`, `allof-mixins`, `allof-inline-merge`, `allof-nested-inline` - Codes: `openapi/degraded-construct` -- Tests: `schema.TestAllOf_DiscriminatorHierarchy`, `schema.TestAllOf_SoleRefBecomesBase`, +- Tests: `schema.TestAllOf_ANullableSayingNothingLeavesTheUseOfOneRef`, + `e2e.TestRestatedConjunct_ATypeSayingMoreIsAConjunct`, + `schema.TestAllOf_DiscriminatorHierarchy`, `schema.TestAllOf_SoleRefBecomesBase`, `schema.TestComponent_AnAllOfOfOneRefOverAnObjectIsTheModelThatOwnsIt`, `e2e.TestRefConjunction_AnAllOfOfOneRefHoistsNoNode`, `e2e.TestRefConjunction_AComponentOverAnObjectIsTheModelThatOwnsIt`, `e2e.TestRefConjunction_ACarrierOfAnAllOfOfOneRefReadsItsTargetsDocs`, `e2e.TestRefConjunction_AUseSayingNothingMoreIsTheBareRefOverAnyTarget`, `e2e.TestRefConjunction_AnAllOfOfOneRefToFalseIsTheReference`, - `e2e.TestRefConjunction_TwoBasesInADiscriminatorHierarchyElectTheLeastReference`, + `e2e.TestRefConjunction_TwoBasesInADiscriminatorHierarchyChooseTheLeastReference`, `e2e.TestAllOfCompose_ObjectsAloneStayAModel`, `e2e.TestAllOfCompose_ABaseThatIsNoModelIsKeptNotComposed`, `e2e.TestAllOfCompose_ConjunctsNoInstanceSatisfiesNameNoPlainBase`, `e2e.TestAllOfCompose_ASubtypeOfATypeListComposesItsObjectVariant`, @@ -2313,7 +2464,7 @@ owns no node to keep ([`allof-inline-residue`](#allof-inline-residue)). `schema.TestAllOf_NestedInlineWrapperFlattens`, `schema.TestAllOf_NestedWrapperBaseSelection`, `schema.TestAllOfEntries_DepthCapKeepsWrapperVerbatim`, `schema.TestAllOfEntries_DepthCapNamesWhatElseTheWrapperWrites`, - `schema.TestAllOf_NestedWrapperWithResidueKeptVerbatim`, `schema.TestAllOf_NestedLowersAsFlat`, + `schema.TestAllOf_NestedWrapperWithUnreadKeywordsKeptVerbatim`, `schema.TestAllOf_NestedLowersAsFlat`, `schema.TestAllOf_AUnionItNamesComposesAsWritten`, `schema.TestAllOf_ARefToAHierarchyMemberIsTheBase`, `merge.TestFold_RedeclaredModelsCompose`, `e2e.TestCompile_SharedCompositionAncestorsDoNotAmplify`, `openapicases.TestCore_SpellingsHoldTheRecord` @@ -2323,12 +2474,11 @@ owns no node to keep ([`allof-inline-residue`](#allof-inline-residue)). ### `allof-refinement` An `allOf` is a composition where the kinds the position lowers to, null aside, are an object -alone and no conjunct states a value set, which is elected first (below), or is a union standing -alone (below), the keywords beside the `allOf` being a conjunct as much as an entry is, and where -its marker -is the kind-inference policy's where that reading is inferred +alone and no conjunct states a value set, which is chosen first (below), or is a union alone +(below), the keywords beside the `allOf` being a conjunct as much as an entry is, and where its +marker is the kind-inference policy's where that reading is inferred ([`shape-applicator`](#shape-applicator)). Those kinds are what the conjuncts declare together, or, -where nothing declares one, what their shape keywords claim, so +where nothing declares one, what their shape keywords imply, so `{allOf: [{$ref: E}], description: d}` over `E: {items: …}` is a use of the list the policy reads `E` as. A `Model` anywhere else asserts an object the source rules out: `{allOf: [{type: integer}, {type: integer, format: int32}]}` would reach a consumer as an object @@ -2344,90 +2494,145 @@ the top type keeping each entry. What the conjuncts admit is read from the source and the bindings, never the registry, so no lowering order decides it. Each conjunct's JSON kinds and value set are read across `$ref`, `allOf`, -`oneOf`, `anyOf`, `type`, `enum` and `const`, a shape keyword written with no `type` claiming no +`oneOf`, `anyOf`, `type`, `enum` and `const`, a shape keyword written with no `type` implying no kind there ([`shape-applicator`](#shape-applicator)), values comparing as an `enum`'s entries do, so -that `1` and `1.0` are one, and the read takes in at most 256 schemas and 4096 `enum` members. An -`allOf` stays the composition it would otherwise be, with nothing lost, where: - -1. the read does not finish: a cycle, a `$ref` landing on no schema or a value it cannot convert, - or either bound, unless the election weighs one `$ref` alone (below); -2. it writes more than 64 conjuncts, which the election below compares pairwise; -3. a conjunct is `false` ([`allof-false-branch`](#allof-false-branch)), or nests past the flattening - depth ([`allof-classification`](#allof-classification)); -4. the conjuncts share no value, a null they all admit being no shared value unless a conjunct - admits nothing else, a `oneOf` and an `anyOf` written one each on two entries read as the one - conjunct a schema writing both is, no value set is elected (below), and the kinds they admit - share none or are an object alone. A warning says so at the schema where their instance types - share none ([`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts)), or their value sets no - member, and otherwise at an entry writing a `type` that excludes an object - ([`allof-inline-residue`](#allof-inline-residue)). Value sets sharing no member whose kinds - share one that is no object alone compose nothing: no conjunct is the principal, so the - position lowers by the keywords beside the `allOf`, and to the top type keeping each entry - where those name no kind, `{allOf: [{enum: [a, b]}, {enum: [c, d]}]}` among them, with the one - warning. A `$ref` among such conjuncts is kept with an info saying so. - -A bound stops only what the election compares, the values and formats each conjunct admits, never +that `1` and `1.0` are one, and the read takes in at most 256 schemas and 4096 `enum` members. A +cycle through any keyword the read follows is read to its greatest fixpoint: a loop admits every +kind there, so its kinds are what its other conjuncts declare, and a cycle of `$ref`s writing +nothing else is the top type, which is no `Base`, so a `$ref` to it is kept as one to `{}` is. A +`$ref` landing on no schema admits every kind and cuts no read. A value set no reading converts is +kept and reported as written and is no conjunct of the reading. An `allOf` composes a `Model` only +where the kinds it reads are an object alone, the kind-inference policy's reading included, marked +as the policy marks it; else: + +1. a read cut short by either bound, or by more than 64 conjuncts, which the choice compares + pairwise, chooses nothing from what the bound let in. A value set an inline conjunct alone states + is chosen by its keyword, before any read. Else a conjunct writing nothing past its kinds, its + notes and extensions aside, says nothing: one conjunct left is the position, as if written alone, + so a chain of `{$ref: C1, description: d}` is one alias for each hop; none left, the position is + what the kinds name, a use of one kind, a `List` for an array, or the `Union` a `type` list + naming them lowers to; several left, the composition where the kinds are an object alone, the + bottom of point 4 where they share none, else what the kinds name, each conjunct left kept + verbatim under its key (`degraded_lowering`) with one info at the schema naming the bound and the + keywords beside the `allOf` it keeps. An `allOf` nesting past the flattening depth + ([`allof-classification`](#allof-classification)) cuts the read of its kinds too, so the position + is the top type keeping the `allOf` whole under `openapi:allOf`, beside the depth's own report; +2. a `$ref` beside other conjuncts that leads round a loop of references back to the position + admits every kind there, so the rest decides: `CY: {allOf: [{$ref: CY}, {type: string, + maxLength: 3}]}` is a `Scalar` over `string` holding `maxLength`, the `$ref` kept under + `openapi:$ref` with one info at its entry. An `allOf` whose one entry is a `$ref`, writing + nothing else but what says nothing of the instance, is a node on the reference chain, and so is + one every entry of which lies on the loop: a loop all of whose nodes are such, bare `$ref`s among + them, is the loop a chain of bare `$ref`s is ([`reference-cycles`](#reference-cycles)); +3. a `$ref` naming nothing beside other conjuncts admits every kind and cuts nothing: the position + lowers as the same schema with the `$ref` removed does, keeping the `$ref` verbatim, a + `$dynamicRef` under `openapi:$dynamicRef` as any `$dynamicRef` is kept, and what its + entry writes beside it as that entry without it does, beside the one `openapi/unresolved-ref`; +4. the conjuncts share no value, a `oneOf` and an `anyOf` written one each on two entries read as + the one conjunct a schema writing both is. Conjuncts admitting null alone together, none of + them null alone and none writing a union, share that null: the position is the null type, as + `{type: 'null'}` is ([`null-alone`](#null-alone)), typed by no conjunct, with no report that + they share no value, each keyword the `Enum` has no field for, a `$ref` among them, kept where + written with an info, and a read `nullable` said by the null it admits. One conjunct of null + alone is the position the choice takes, and conjuncts writing a union are weighed by the + union's own rules, a null they all admit being no shared value there. One `$ref` with notes beside it is the reference whatever + its target admits, which the target reports. Value sets sharing no member, of one value type, + are the closed empty `Enum` of that type, a `const` among them, keeping every set verbatim, the + one chosen, beside the `allOf` or of two inline sets neither within the other, else the one + rendering least, among them, each under its keyword where no other writer writes that keyword, + else under its entry key: `{allOf: [{enum: [a, b]}, {enum: [c, d]}]}` is the closed empty `Enum` + of `string` keeping both, and so are two `$ref`s whose targets state them, each `$ref` kept. + Their one report is the `openapi/unsatisfiable-schema` warning at the schema, as for the flat + twin: no entry reports the set it keeps. A `const` and an `enum` + one schema writes are two such sets, flat or on an entry ([`enum-const`](#enum-const)). The + position is the bottom a `false` schema lowers to + ([`whole-schema-fallbacks`](#whole-schema-fallbacks)), the closed `Model` with no member, in + two cases: the conjuncts share no kind outside every union, value sets of differing value types + among them, or their value sets share no member and are of a type no `Enum` holds (lists, + objects, several value types). Under the nullable-inference policy, a null every conjunct admits + counts as shared. The bottom keeps each keyword beside the `allOf` under its own key, and each + entry once under its entry key, an entry writing a `$ref` beside other keys among them, less an + extension whose value converts to no JSON, which reports itself. A `$ref` an entry writes alone + is kept under `openapi:$ref`. A `false` conjunct ([`allof-false-branch`](#allof-false-branch)) + composes. Each is reported once, as a warning `openapi/unsatisfiable-schema` at the schema + ([`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts)), or at an entry writing a `type` that + excludes an object beside a composed `Model` ([`allof-inline-residue`](#allof-inline-residue)). + The bottom's warning names a conjunct that admits no value by itself, whatever that conjunct + reports where it is written. The warning is drawn only where no + conjunct's read is cut short. + +A bound stops only what the choice compares, the values and formats each conjunct admits, never the kinds, which are read whole at any size. Where it weighs one `$ref` alone, every other conjunct naming no kind and stating no value set, format or `items`, as in `{$ref: T, description: d}`, `{allOf: [{$ref: T}], maxLength: 3}` or `{allOf: [{$ref: T}], properties: …}`, it compares nothing, so past a bound the position is the use of `T` it is within them. Whether such a conjunction admits a value is then read off the kinds `T` lowers to, null aside, as its values are not read: where -they are none it composes, as point 4 says within the bounds, a `T` admitting null alone among -them, which within the bounds is a use, and over a `T` whose value sets alone leave none, which -within the bounds is the top type keeping the `$ref` (point 4), it is a use. An `allOf` of one +they are none, a `$ref` with notes beside it is the reference, as within the bounds, and any other +is the bottom of point 4, a `T` admitting null alone among them, which within the bounds is a use, +and over a `T` whose value sets alone leave none, which within the bounds is the top type keeping +the `$ref` (point 4), it is a use. An `allOf` of one `$ref` saying nothing more is the reference whatever `T` admits -([`allof-classification`](#allof-classification)). A second conjunct the election weighs, as in +([`allof-classification`](#allof-classification)). A second conjunct the choice weighs, as in `{allOf: [{$ref: T}, {type: string, maxLength: 3}]}` or `{allOf: [{$ref: T}], format: uuid}`, or a union beside the `allOf` that past a bound is no longer left out, leaves a read past a bound composing (point 1). A `$dynamicRef` a conjunct writes masks no kind: one the position expands, in what a `$ref` lands on, -is read as the schema it names, and one it does not admits every kind, as one beside the `allOf` and -one on an entry of it, which no position expands, do. So `{allOf: [{$ref: T}], $dynamicRef: '#m'}` -and `{allOf: [{$ref: T}, {$dynamicRef: '#m'}]}` lower alike, whatever schema `#m` names: a `Model` -over `T` where `T` is an object, a use of `T` otherwise, each keeping the `$dynamicRef`. One naming -no schema is the `$ref` it spells ([`references`](#references)), so it lands on none. A union -beside the `allOf` sharing no kind with the rest, as in -`{allOf: [{type: string}], anyOf: [{type: integer}, {type: boolean}]}`, is left out of the reading: -the position lowers as the rest does, the union is kept under `openapi:oneOf` or `openapi:anyOf` -(`degraded_lowering`) with an info, and the warning of +is read as the schema it names, values and kinds alike, and one it does not admits every kind, as +one beside the `allOf` and one on an entry of it beside another conjunct, which no position +expands, do. So `{allOf: [{$ref: T}], $dynamicRef: '#m'}` and +`{allOf: [{$ref: T}, {$dynamicRef: '#m'}]}` lower alike, whatever schema `#m` names: a `Model` over +`T` where `T` is an object, a use of `T` otherwise, each keeping the `$dynamicRef`. An entry is a +fact of the composition listing it, so the `allOf`'s only entry, beside nothing its expansion +cannot carry, takes the `allOf`'s place (Core 2020-12 §10.2.1.1): `{allOf: [{$dynamicRef: '#m'}]}` +expands as `{$dynamicRef: '#m'}` does, with the same report, and so does an entry taking the place +of its `allOf` in such an entry, `{allOf: [{allOf: [{$dynamicRef: '#m'}]}]}`, which beside another +conjunct is kept as the entry it replaces is. Every reader of the composition reads an entry so, and +a `$ref` naming an entry reads its schema alone, so it expands there what the composition listing +the entry keeps, and each report names the reading that drew it: the keyword kept as an entry of the +`allOf`, and expanded as the target of the least `$ref` landing on the entry, or of a reference +where none does, as a discriminator's mapping naming it is. One naming no schema is the `$ref` it +spells ([`references`](#references)), so it lands on none. A union beside the `allOf` sharing no +kind with the rest, as in `{allOf: [{type: string}], anyOf: [{type: integer}, {type: boolean}]}`, is +left out of the reading: the position lowers as the rest does, the union is kept under +`openapi:oneOf` or `openapi:anyOf` (`degraded_lowering`) with an info, and the warning of [`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) names it at the schema, so no union is distributed into models no instance satisfies ([`union-beside-structure`](#union-beside-structure)). An `enum` or a `const` beside an `allOf` is one of its conjuncts, the keywords beside the `allOf` writing a value set, rather than its rival in the dispatch of -[`competing-keywords`](#competing-keywords): `{enum: [a], allOf: [{$ref: Level}]}` elects its +[`competing-keywords`](#competing-keywords): `{enum: [a], allOf: [{$ref: Level}]}` chooses its principal from the same set as `{allOf: [{$ref: Level}, {enum: [a]}]}`, its entries fold and its `$ref` still lowers. Where the conjuncts would compose, their kinds an object alone or sharing no -value, a value set is elected before the composition, as the dispatch picks one beside it, in -every spelling and whatever its members: the one lying within every other value set stated, the one -beside the `allOf` first. A set its own keywords leave no value, a `const` and an `enum` sharing -none, a `const` outside its own `type`, or a value set beside a union of another kind, stands for -the keyword the dispatch of [`competing-keywords`](#competing-keywords) lowers it as, its `const` -before its `enum`, so `{allOf: [{$ref: Str}, {const: z, enum: [a]}]}` is the `Literal` `z` keeping -the `$ref` and the `enum`, as `{$ref: Str, const: z, enum: [a]}` is, where it composed a `Model` -over a string; a set that keyword leaves no value either, as `enum: []`, is elected by none. So -`{allOf: [{$ref: Obj}, -{enum: [{a: x}]}]}` is the `Union` of `Literal`s that enum is, as written beside the `allOf`, and -`{allOf: [{$ref: Level}, {enum: [other]}]}` with `other` outside `Level` an `Enum` of `other`, the -`$ref` kept with an info saying they share no value, and the warning of -[`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) naming the value set it lowered as. Each conjunct the value set beats is kept as below, never the `allOf` whole, but where no value -set is elected, as `enum: []` or two neither lying within the other, -and the `allOf` writes an inline entry: one of `$ref` entries alone keeps each as below then too, as -the `$ref` written beside the value set is kept. +value, a value set is chosen before the composition, as the dispatch picks one beside it, in every +spelling and whatever its members: the one lying within every other value set stated, the one beside +the `allOf` first. A set its own keywords leave no value, a `const` and an `enum` sharing none, a +`const` outside its own `type`, or a value set beside a union of another kind, is taken as the +keyword the dispatch of [`competing-keywords`](#competing-keywords) lowers it as, its `const` before +its `enum`, so `{allOf: [{$ref: Str}, {const: z, enum: [a]}]}` is the `Literal` `z` keeping the +`$ref` and the `enum`, as `{$ref: Str, const: z, enum: [a]}` is, where it composed a `Model` over a +string; a set that keyword leaves no value either, as `enum: []`, is chosen by none. So +`{allOf: [{$ref: Obj}, {enum: [{a: x}]}]}` is the `Union` of `Literal`s that enum is, as written +beside the `allOf`, and `{allOf: [{$ref: Level}, {enum: [other]}]}` with `other` outside `Level` an +`Enum` of `other`, the `$ref` kept with an info saying they share no value, and the warning of +[`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) naming the value set it lowered as. Each +conjunct the value set is chosen over is kept as below, never the `allOf` whole, but where no value +set is chosen, as `enum: []` or two neither lying within the other, and the `allOf` writes an inline +entry: one of `$ref` entries alone keeps each as below then too, as the `$ref` written beside the +value set is kept. Where they would compose a value they share, their kinds an object alone, and no value set is -elected, an inline conjunct writing a `oneOf` or an `anyOf` that nothing else conjoins with is the +chosen, an inline conjunct writing a `oneOf` or an `anyOf` that nothing else conjoins with is the principal: the schema writes no union beside its `allOf`, no conjunct is a `$ref` or writes another union, the union's entry writes no `allOf`, which would compose beside it, none but that entry writes a `discriminator`, which would route a union beside it, and each keyword a conjunct writes -that would make a body beside a union, its `allOf` aside, is one every branch of the union says, +that would make structure beside a union, its `allOf` aside, is one every branch of the union says, the branches declaring shape against the rest where one is written, as -[`union-beside-structure`](#union-beside-structure) reads the keywords beside a union. The -position then lowers as that union written there does: `{allOf: [{oneOf: [{$ref: X}, {type: -'null'}]}], description: d}` is the nullable reference to `X` that `{oneOf: [{$ref: X}, {type: -'null'}], description: d}` is, keeping nothing of the union, the null branch its `Nullable` -([`union-null-variant`](#union-null-variant)). +[`union-beside-structure`](#union-beside-structure) reads the keywords beside a union. The position +then lowers as that union written there does: +`{allOf: [{oneOf: [{$ref: X}, {type: 'null'}]}], description: d}` is the nullable reference to `X` +that `{oneOf: [{$ref: X}, {type: 'null'}], description: d}` is, keeping nothing of the union, the +null branch its `Nullable` ([`union-null-variant`](#union-null-variant)). The principal is chosen from the whole set: @@ -2452,67 +2657,178 @@ The principal is chosen from the whole set: another where its kinds, its values, its `format` and its `items` are. Two formats of the table ([`string-formats`](#string-formats), [`numeric-formats`](#numeric-formats)) compare by what they select, a format narrows the bare kind it applies to, one the table does not list included, - `items` narrow an `array` writing none, and two `items` compare by what each says, so `uuid` beats - `string`, `email` beats `string` and a list of `uuid` beats a list of `string`, in either order, - as a field redeclared the same ways does + `items` narrow an `array` writing none, and two `items` compare by what each says, so `uuid` is + chosen over `string`, `email` over `string` and a list of `uuid` over a list of `string`, in + either order, as a field redeclared the same ways does ([`allof-redeclared-property`](#allof-redeclared-property)). +A `format`, or the content vocabulary, one conjunct writes beside the one `$ref` of a conjunction +whose other conjuncts write no shape but a `type` naming the target's, a `$ref` to a scalar, reads +as its flat twin, the keyword over the target's JSON type, reads. The target is read through its +chain of `$ref`s and of the nodes writing beside one, each such node's own reading moving its root +or its `Encoding`, and no bound of the choice's read cuts that chain. A target whose `allOf` holds +no `$ref` is read as its flat twin, `{allOf: [{type: string}, {maxLength: 3}]}` as +`{type: string, maxLength: 3}`, its format and content vocabulary read off whichever conjuncts write +them, so `{allOf: [{type: string}, {format: date-time}, {contentMediaType: text/plain}]}` is read as +one schema writing all three, and a `type` the target or a conjunct writes is read by its kinds with +`null` set aside, so `{type: [string, 'null']}` reads as `{type: string, nullable: true}`. One +landing on more than 1024 schemas, the nodes on its chain and its end, is not read, so the keyword +is not read against the scalar it ends on, and the position draws one `openapi/budget-exceeded` +error. A format selecting no primitive of its own, as `{type: integer, format: uuid}` selects none, +makes the position a `Scalar` whose `Base` +is the reference and whose `Encoding` is the twin's, as a bound beside a use restricts it, where the +chain carries no `Encoding`: one of the same name restates it, and one of another name is kept as a +format no node holds is, since a nearer `Encoding` would replace the target's +([encodings](../ir/constraints.md#encodings)). A format selecting another primitive over a target +rooted at the plain primitive of its type, `uuid`, `date-time` or `int64` as text over `string` or +`int32` over `integer`, or one narrower than a format root, `int32` beside `int64`, chooses the +conjunct writing it: `{allOf: [{$ref: S}, {format: uuid}]}` over `S: {type: string}` is the `uuid`, +the `$ref` kept under `openapi:$ref`, `degraded_lowering`, with one info at the entry writing it, or +at the position where it is written beside the format. One selecting the root, or one wider, `int64` +beside `int32`, says nothing, and one neither within nor wider, `date-time` beside `date`, is kept. +At a carrier, a property, a parameter or a header, the restriction is a node of the position's own, +as the flat spelling's `Scalar` is. The content vocabulary reads so beside a target rooted at +`string` or `bytes`, and beside one whose value is read from the text as +[`content-vocabulary`](#content-vocabulary) says. Beside a `$ref` to an enum of one type writing no +format or content keyword of its own, a format selecting no primitive of its own restricts the +reference so, its `Encoding` naming the format: the members stay the enum's, and none is copied. One +selecting a primitive, `int32` or `int64` over `integer`, `float` over `number`, `uuid`, `date-time` +or `byte` over `string` among them, is kept as at any use, since no `Encoding` is named after a +format the compiler gives a primitive ([type table](../emitters/contract/type-table.md)) and the +enum's members are not rooted there. One beside an enum writing a format is kept, as at any use, and +the content vocabulary beside an enum as its flat twin keeps it on the enum, which has no `Encoding` +field: under its own key, `no_ir_home`. + No tie goes by the order the conjuncts are written in. Of conjuncts lying within as many others, or of inline value sets holding the same values, a union goes before the words, which then bound it, -and a `oneOf` before an `anyOf`, as [`competing-keywords`](#competing-keywords) elects of one schema -writing both: `{allOf: [{anyOf: [{type: number}, {type: boolean}]}, {oneOf: [{type: string}, {type: -integer}]}]}` is a use of the `oneOf`, keeping the `anyOf`. Two unions of one keyword elect neither, -as no rule ranks their branches, and nor do words neither of which lies within the other: two -formats neither of which narrows the other, two `items` saying different things, or value sets that -only overlap. The position then lowers by the keywords beside the `allOf`, keeping each entry with -an info. Where they name no kind, it is what its conjuncts admit together, null aside, as a `type` -list naming those kinds lowers, where those are a string, a number or a boolean alone or together: -`{allOf: [{type: string, format: email}, {type: string, format: uuid}]}` is a `string`, two type lists -sharing a string and an integer the `Union` of the two, and value sets the kinds of the members -every set holds, as an instance meets each only as a member of it, so `{allOf: [{enum: [true, a]}, -{enum: [true, b]}]}` is a boolean, `true` alone meeting both, `{allOf: [{enum: [1, true, x]}, {enum: -[1, true, y]}, {type: [integer, string]}]}` an integer, the other conjuncts' kinds leaving `1`, and -sets sharing no member, or whose shared members another conjunct's kinds exclude, admit no value: -the top type, with the warning that they share no value -([`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts)). Where they admit an object or an array, every kind among them, it is the top type, as no entry -was elected to give that shape and a node of the kind would assert members or items none states. -Words admitting alike part only where a node reads a -keyword from its principal alone, `items`, `prefixItems`, `additionalItems` and the content -vocabulary: of those writing every such keyword another writes, and alike, one is elected, and -where none does, neither is. Where nothing tells them apart, the keywords beside the `allOf` stand -where they are among them, else the entry whose text, its keys sorted, is the least, so -`{description: d, allOf: [{enum: [b, a]}, {enum: [a, b]}]}` is a use of the second entry. A schema written twice is one conjunct, -its first copy standing for both and the other saying nothing more, so the order written shows only -in the pointer of the node it lowers to. - -A `format` or `items` written with no `type` qualifies a kind and names none, so it decides nothing: -`{allOf: [{type: integer}, {format: int32}]}` lowers to `integer` with the second entry kept, in -either order, since no one conjunct says `int32` and a schema built from two would stand at a -pointer naming neither. Where nothing declares a kind and the kind-inference policy reads the -position's kinds off its conjuncts' claims ([`shape-applicator`](#shape-applicator)), a conjunct -whose own keywords claim every one of them names them, as one writing that `type` would: +and a `oneOf` before an `anyOf`, as [`competing-keywords`](#competing-keywords) chooses of one +schema writing both: +`{allOf: [{anyOf: [{type: number}, {type: boolean}]}, {oneOf: [{type: string}, {type: integer}]}]}` +is a use of the `oneOf`, keeping the `anyOf`. Two unions of one keyword choose neither, as no rule +ranks their branches, and nor do words neither of which lies within the other: two formats neither +of which narrows the other, two `items` saying different things, or value sets that only overlap. +The position then lowers by the keywords beside the `allOf`, keeping each entry with an info. Each +union choosing none names, in one `openapi/unsatisfiable-schema` at its keyword, the branches +sharing no kind with the rest, the rest and the other unions, unless the conjunction admits no +value, which the report of conjuncts sharing none says alone. Where they name no kind, it is what +its conjuncts admit together, null aside, as a `type` list naming those kinds lowers, where those +are a string, a number or a boolean alone or together: +`{allOf: [{type: string, format: email}, {type: string, format: uuid}]}` is a `string` and two type +lists sharing a string and an integer the `Union` of the two. Value sets an instance satisfies only +as a member of each: inline sets none of which lies within every other, a `$ref`'s target stating +none and none the principal, lower as a flat `enum` of the members every set holds and the other +conjuncts' kinds leave lowers, an `Enum` of one kind, a `Union` of `Literal`s of several, its +members in the order of the set point 4 chooses among sets sharing no member, the one beside the +`allOf` else the one rendering least, each set kept verbatim: +`{allOf: [{enum: [true, a]}, {enum: [true, b]}]}` is the `Enum` of `true`, and +`{allOf: [{enum: [1, true, x]}, {enum: [1, true, y]}, {type: [integer, string]}]}` that of `1`, the +other conjuncts' kinds leaving it. Sets whose shared members another conjunct's kinds exclude admit +no value: the top type, with the warning that they share no value +([`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts)), where sets sharing no member are point +4's. A union whose branches write a value set and nothing beside it that says anything of a value, a +note, an extension, an anchor, an identifier or a comment among what says nothing, is one set +conjunct, the members of its branches, a `oneOf`'s those one branch alone holds, beside an `enum` or +`const` in every spelling: where every member of the rest's set lies within it, it says nothing and +is neither kept nor reported, so +`{allOf: [{anyOf: [{enum: [s1, s2]}, {enum: [p]}]}, {enum: [s1, p]}]}` is the `Enum` of `s1` and +`p`, but where a branch, or a union it nests, writes a note or an extension no member holds, which +keeps the union beside the set as written ([`union-beside-structure`](#union-beside-structure)). +A branch writing one member of the set alone, by a `const` or an `enum` of one, gives it its docs, +deprecation, examples and extensions, as the union written alone does, where an inline `enum`, no +`const`, writes the set and no other branch writes the member: `{enum: [a, b], oneOf: [{const: a, +description: d}, {const: b}]}` is the `Enum` of `a`, described, and `b`, keeping nothing. Where +some do, the position is the `Enum` of those, or the `Union` of their literals where they are of +several kinds, keeping the rest's `enum`, the union kept only where a branch holds none of them, +named dead at the union keyword, as beside a rest that is no object +([`union-beside-structure`](#union-beside-structure)), or says of its members what none holds, so +`{allOf: [{anyOf: [{enum: [a, b]}, {enum: [b, c]}]}, {enum: [b, x]}]}` is the `Enum` of `b`; where +none does, the closed empty `Enum`. Beside a second union the conjunction passes over +([`competing-keywords`](#competing-keywords)), it is read so against a rest stating a value set +alone, that set narrowed to the members the union passed over admits where its every branch states +values, though none be left, and it is kept even where every member lies within it, as the one +passed over is: `{allOf: [{const: b}, {type: string}, {anyOf: [{enum: [b]}, {enum: [c, a]}]}, +{oneOf: [{const: a}, {const: c}]}]}` is the closed empty `Enum`, both branches of its `oneOf` named +dead, in every spelling, as it is written without its `anyOf`. Beside a rest stating no value set +but saying anything else, a `type` or a bound, it is one so too: JSON equality judges its members +alike, so `2` is `2.0`, and the rest's keywords judge each through the value reader, its kinds and +each of its conjuncts read as a branch beside a value set is +([`union-beside-structure`](#union-beside-structure)), a member one refuses dropped and reported, a +pattern outside the subset the reader reads ([patterns](../ir/values.md#patterns)) leaving it in. +The position is what a flat `enum` of the members left lowers to beside the rest +([`enum-const`](#enum-const)), each member, or its `Literal`, holding what the branch writing it +alone, by a `const` or an `enum` of one, says of it, its docs, deprecation, examples and extensions, +as that branch written alone gives its `Literal`, but for a member another branch writes too, whose +notes no order chooses. The union is kept nowhere where the node holds all it writes, else once, as +`validation_only` where a branch says of its members what none holds, or `degraded_lowering` where +a branch holds none of them: `{type: string, oneOf: [{const: a, description: d}, {const: b}]}` is +the `Enum` of `a`, described, and `b`, keeping nothing, +`{type: string, oneOf: [{enum: [a, b]}, {enum: [b]}]}` the `Enum` of `a`, and +`{type: string, maxLength: 1, oneOf: [{enum: [a]}, {enum: [bb]}]}` that of `a`, `bb` reported. +Members of two kinds are the `Union` of literals a mixed `enum` is, each `Literal` minted in the +composed namespace where its member is written, which the branch writing it, lowered alone, types by +itself; a null member is the reference's, as an `enum` listing it makes it, under the version and +the policy as they read that `enum`. Where the members left are null alone, the position admits null +alone ([`union-null-only`](#union-null-only)). Where the branches list more members than the enum +budget admits, none is read: the position is the top type an `enum` past it lowers to, with its +error, the union kept nowhere. Where they admit an object or an array, every kind among them, it is +the top type, as no entry was chosen to give that shape and a node of the kind would assert members +or items none states. An entry's `type` naming exactly the kinds the position is then, null aside, +names what its node is, so it says nothing beyond it and is neither kept nor reported: +`{allOf: [{type: string, contentEncoding: base64}, {type: string, contentMediaType: text/plain}]}` +lowers as written flat, and of `{allOf: [{type: string}, {enum: [a, 1]}]}` the `enum` alone is kept; +a `type` naming more, `[string, integer]` beside a `string`, is kept with its entry. Words admitting +alike part only where a node reads a keyword from its principal alone, `items`, `prefixItems`, +`additionalItems` and the content vocabulary: of those writing every such keyword another writes, +and alike, one is chosen, and where none does, neither is. Where nothing tells them apart, the +keywords beside the `allOf` are the principal where they are among them, else the entry whose text, +its keys sorted, is the least, so `{description: d, allOf: [{enum: [b, a]}, {enum: [a, b]}]}` is a +use of the second entry. A schema written twice is one conjunct, its first copy taking the place of +both and the other saying nothing more, so the order written shows only in the pointer of the node +it lowers to. + +A `format` or `items` written with no `type` qualifies a kind and names none, so it chooses no +conjunct, but the node a conjunct builds reads it, as it reads a bound: a `format`, the content +vocabulary and the `items` group (`items`, `prefixItems` and `additionalItems`, one entry) are read +off any conjunct, so a `Scalar` takes the format and a `List` or a `Tuple` its elements off +whichever conjunct writes them, the position's own keywords first, each node they build lying where +it is written. `{allOf: [{type: integer}, {format: int32}]}` lowers to `int32` with nothing kept, in +either order, as `{type: integer, format: int32}` does, and +`{type: array, allOf: [{items: {type: string}}]}` to the `List` of strings, its element at +`…/allOf/0/items`. Formats agree where they nest, the primitive one selects within the other's, and +the narrowest is taken, as `int32` does beside `int64`; two neither of which narrows the other, +`int8` beside `uint8`, part, each entry writing one kept whole while a `type` they state alike types +the node. A bound the node of an inline primitive principal takes none of, written beside the +`allOf` or on another entry, reaches the `Scalar` the position hoists to hold it, as written flat, +and a variant of a `type` list carrying a number as text keeps the value bounds of the list's other +conjuncts as its own. Where nothing declares a kind and the kind-inference policy reads the +position's kinds off its conjuncts' keywords ([`shape-applicator`](#shape-applicator)), a conjunct +whose own keywords imply every one of them names them, as one writing that `type` would: `{allOf: [{items: {type: string}}, {minItems: 1}]}` is a use of the `List` its first entry builds, marked, holding the bound, as `{allOf: [{type: array, items: {type: string}}, {minItems: 1}]}` is a use of its unmarked one, and `{items: {type: string}, allOf: [{items: {minLength: 1}}]}` lowers by the keywords beside the `allOf`. An `allOf` no conjunct names a kind in, `{allOf: [{description: d}]}`, has no principal and is the top type. Where the keywords beside the -`allOf` win, the position lowers by them as if no `allOf` were written. An inline principal lowers -at the position's pointer, as the keywords beside the `allOf` would, so one node stands for the +`allOf` decide, the position lowers by them as if no `allOf` were written. An inline principal +lowers at the position's pointer, as the keywords beside the `allOf` would, so one node is the position whichever conjunct decides it: a value set, a `Union`, a `List`, a `Tuple` or a hoisted `Scalar`, its children and the reports on what it writes where they are written, so `{allOf: [{description: d}, {type: array, items: {type: string}}]}` is the `List` at the position, -as its flat spelling is, and a node its `items` builds stands at `…/allOf/1/items`. A type list's -variants, which no pointer of the source names, and the nodes beneath them stand under the -position's ([`type-arrays`](#type-arrays)). The node holds the bounds of the conjunction, the -position's own and each other conjunct's, as the same keywords written beside each other give it -them, each where the node's builder reads it and one no part of the node reads kept on it under its -keyword, a collection bound beside a `oneOf` as the flat spelling keeps it, and an object bound of a -`type` list's object variant as [`type-arrays`](#type-arrays) says. The node reads the position's -own keywords before the principal's, as the keywords beside an `allOf` stand before an entry's: of -two `pattern`s written otherwise its field holds the position's, and the principal, disagreeing, is -kept whole ([`allof-inline-residue`](#allof-inline-residue)). A keyword written beside the `allOf` -as the inline principal writes it is one writing, whichever reading reads or keeps it: read once, or -kept once and reported once. What the principal's keeping of unread keywords, its bounds on a number +as its flat spelling is, and a node its `items` builds lies at `…/allOf/1/items`. A principal +writing both a value set and the union that is the position +([`union-beside-structure`](#union-beside-structure)), as +`{allOf: [{type: string, enum: [a, b], oneOf: [{format: uuid}, {format: date}]}]}` does, lowers as +that union, keeping and reporting what its flat spelling does. A type list's variants, which no +pointer of the source names, and the nodes beneath them lie under the position's +([`type-arrays`](#type-arrays)). The node holds the bounds of the conjunction, the position's own +and each other conjunct's, as the same keywords written beside each other give it them, each where +the node's builder reads it and one no part of the node reads kept on it under its keyword, a +collection bound beside a `oneOf` as the flat spelling keeps it, and an object bound of a `type` +list's object variant as [`type-arrays`](#type-arrays) says. The node reads the position's own +keywords before the principal's, as the keywords beside an `allOf` come before an entry's: of two +`pattern`s written otherwise its field holds the position's, and the principal, disagreeing, is kept +whole ([`allof-inline-residue`](#allof-inline-residue)). A keyword written beside the `allOf` as the +inline principal writes it is one writing, whichever reading reads or keeps it: read once, or kept +once and reported once. What the principal's keeping of unread keywords, its bounds on a number carried as text or its build keeps is the principal's, kept at the entry, and the position's readers leave it, a `oneOf` or `anyOf` its union does not lower among it, with the build's reason and report; a content keyword the node holds no field for is the position's, whose reading keeps it @@ -2551,8 +2867,8 @@ every value is of it, a `$ref` conjunct by the schema deciding what it lands on, narrows every other, and each `type` and `format` it holds is consumed, a wider one included. So `{allOf: [{type: integer}, {const: 80.0}]}` is an `integer`, as `{type: integer, const: 80.0}` is, and keeps nothing. Where none narrows every other, as of two formats neither of which narrows the -other, the value set keeps the `ValueType` its own schema gives it, and a format that reaches none -stays with its entry. +other, the value set keeps the `ValueType` its own schema gives it, and a format that applies to +none stays with its entry. What the conjuncts say lands where the position keeps what it writes: on the carrier ([`ref-use-site`](#ref-use-site)), else on an alias hoisted at the position only if it writes @@ -2562,10 +2878,37 @@ the IR holds a thing, one idea at two sizes: a keyword's home is the field that declaration's is its carrier or its node. An inline entry's keywords fold as [`allof-inline-residue`](#allof-inline-residue) says. A `type`, a `format`, an `enum`, a `const` or `items`, on an entry or beside the `allOf`, that the principal already says is consumed, -so `{allOf: [{$ref: Port}], type: integer}` keeps nothing. Two schemas written alike in one document -say the same where every relative `$ref` in them reads against one base: under an `$id` naming -another URI, the same spelling may name another schema, while an absolute one names the same -wherever it is read. A copy in another document is read apart. One saying +so `{allOf: [{$ref: Port}], type: integer}` keeps nothing. A principal admitting no value says no +value set and no union beside it, though no value escapes it: an `enum` or a `const` an entry +writes is kept as written, reported at its entry as a keyword its node has no home for, but where +an `enum: []` lies within it, whose warning is the one report ([`enum-const`](#enum-const)), and +a `oneOf` or +`anyOf` on an entry or beside the `allOf` is kept as one the principal does not say is (below). A +keyword holding a mapping on an entry +beside a `$ref` principal restates the referent's same keyword, which says it already, where every +key it writes the referent's writes alike, a list compared whole, and every other key the referent's +writes is a note (`title`, `description`, `example`, `examples`, `deprecated`, `externalDocs`, +`$comment`) or an extension, the referent's keyword being read through its own `$ref` once, and the +two are read as the copies below are: the two validate alike. So `items: {type: string}` beside a `$ref` to a list whose `items` is a `$ref` to +`{description: d, type: string}` is consumed, and an `items` adding a bound is kept. A key of +`properties` names a property, no keyword, so `properties` restate the referent's where each names +a property the referent's name, written alike, notes included, one the referent alone names left as +it says, and the composition reads them so +too: beside the one `$ref` of `{allOf: [{$ref: Obj}, {type: object, properties: …}]}` restating +`Obj`'s, the entry says nothing, and the position lowers as `{allOf: [{$ref: Obj}, {type: +object}]}` does, the reference where a dry run finds its Model holding nothing beside its Base +([`ref-use-site`](#ref-use-site)), and so do the same `properties` beside the `allOf`, wherever +every writer of them restates the referent's, the referent is no schema naming itself nor one +composing the position in turn, on one cycle of compositions with it, whose models fold every +declaration of a name as one unit, and no union beside it is distributed; one property +written otherwise, by a note too, composes. Two schemas written alike say the same where each, +read in its own document, reads alike: both documents read schemas by one minor and one dialect, and +every relative `$ref` in them lands on one target from both, as it does wherever the two read it +against one base. Under an `$id` naming another URI, or in another document, the same spelling may +name another schema, while an absolute one names the same wherever it is read. So a copy in another +document restates what it copies where its references land alike, and not where a relative `$ref` +lands on each document's own schema, nor where one document is 3.0 and the other 3.1, unless the copy +writes a `$ref` alone, which every dialect reads alike. One saying more is kept under its own keyword, `openapi:`, on an entry as beside the `allOf`, each reported as an info `openapi/degraded-construct` at the entry or at the position, naming what the position lowered to as the same keywords written flat would, the position's report and an inline @@ -2574,15 +2917,15 @@ conjuncts only where its principal is a `$ref`, an entry kept whole only where [`allof-inline-residue`](#allof-inline-residue) says. A `$ref` conjunct the position is no use of is kept, its text alone, under `openapi:$ref`, or `openapi:$ref/` where it keeps several, `i` its rank by reference text, then by the entry as written, so no order of the entries decides, two written alike being one entry at the -position. One a value set beats still -speaks for the position ([`ref-use-site`](#ref-use-site)), its `default` only where the value set -takes it, and still lowers, though nothing else names it, as a position no component holds lowers -for a `$ref`. A `oneOf` or `anyOf` written on an entry is a conjunct admitting what any of its -branches admits, naming the kinds they name, so it may be the principal, standing at the position. -The principal says the union where one of its branches says nothing the -principal does not, each keyword the branch writes compared as one written beside the `allOf` is, -and a `oneOf` only where that branch also shares no kind with another, so that exactly one admits -each value the position holds: +position; a `$dynamicRef` read as the `$ref` it spells is kept so under `openapi:$dynamicRef`, the +keyword written, and ranked among those alone. One a value set is chosen over still speaks for the +position ([`ref-use-site`](#ref-use-site)), its `default` only where the value set takes it, and +still lowers, though nothing else names it, as a position no component holds lowers for a `$ref`. A +`oneOf` or `anyOf` written on an entry is a conjunct admitting what any of its branches admits, +naming the kinds they name, so it may be the principal, lying at the position. The principal says +the union where one of its branches says nothing the principal does not, each keyword the branch +writes compared as one written beside the `allOf` is, and a `oneOf` only where that branch also +shares no kind with another, so that exactly one admits each value the position holds: `{allOf: [{anyOf: [{type: string}, {type: number}]}, {type: string, maxLength: 1000}]}` lowers as `{type: string, maxLength: 1000}` does, keeping nothing. A branch writing a bound, a `pattern` or an annotation says more than the principal, so @@ -2595,8 +2938,8 @@ is then the principal, the position is a use of it and the union is a keyword be The principal consumes it where it says it, as on an entry. Otherwise one whose branches declare no shape against the position ([`union-beside-structure`](#union-beside-structure)) is kept under `openapi:oneOf` or `openapi:anyOf` as `validation_only` and reported as an info -`openapi/validation-only-keyword` at the position, as beside any body, and any other is kept there -under `degraded_lowering`, with the report other keywords beside a refinement draw; one the +`openapi/validation-only-keyword` at the position, as beside any structure, and any other is kept +there under `degraded_lowering`, with the report other keywords beside a refinement draw; one the principal's build keeps alike, which its union does not lower, is that one writing, kept at the entry with the build's reason and report (above). So `{allOf: [{type: string, maxLength: 10}], anyOf: [{type: string}, {type: number}]}` lowers as the @@ -2622,21 +2965,41 @@ The IR's rule that compilers leave flattening to emitters keeping such an `allOf` a decorator for emitters to collapse is weighed in [models](../ir/models.md#an-allof-no-object-satisfies). -- Status: partly built: a `format` written beside an `allOf`, or on another entry, whose inline - principal lowers to a `Scalar` or to a `type` list's scalar variants is kept under - `openapi:format`, where the flat spelling gives each scalar its `Encoding` (#2107). - Cases: `allof-refinement`, `allof-entry-infers-array`, `union-joined-value-sets`, `kept-ref-unrenderable` -- Codes: `openapi/degraded-construct`, `openapi/validation-only-keyword` -- Tests: `e2e.TestElection_TwoUnionsKeptBesideABodyAdmittingNullKeepTheirReasonEverywhere`, - `e2e.TestElection_TwoUnionsSharingNullAloneBesideABodyAdmittingNullAreKept`, +- Codes: `openapi/degraded-construct`, `openapi/validation-only-keyword`, `openapi/budget-exceeded`, + `openapi/unsatisfiable-schema` +- Tests: `e2e.TestRestatedConjunct_AnEntryKeywordRestatingTheReferentsSaysNothing`, + `schema.TestValueSetUnion_AMemberHoldsWhatItsBranchSaysOfIt`, + `schema.TestValueSetUnion_ALiteralHoldsWhatItsBranchSaysOfIt`, + `schema.TestValueSetUnion_BesideAnEnumAMemberHoldsWhatItsBranchSaysOfIt`, + `schema.TestValueSetUnion_BesideAnEnumOfTwoKindsALiteralHoldsWhatItsBranchSaysOfIt`, + `schema.TestValueSetUnion_BesideASetNoEnumWritesTheUnionKeepsItsNotes`, + `e2e.TestCompile_ACycleFoldsAsAFlatFoldOfItsDeclarations`, + `schema.TestRestatedProperties_ACopyInAnotherDocumentRestatesWhereItReadsAlike`, + `schema.TestUnion_SeveralOneOfsReadEachAgainstTheRest`, + `schema.TestBesideRef_AChainPastItsBoundIsReportedAtThePosition`, + `e2e.TestKeywordScope_AFormatBesideARefToAScalarReadsAsItsFlatTwin`, + `e2e.TestKeywordScope_AFormatBesideARefToAnEnumRestrictsIt`, + `e2e.TestKeywordScope_AFormatSelectingAPrimitiveBesideARefToAnEnumIsKept`, + `e2e.TestKeywordScope_AFormatBesideARefReadsKindsWithNullAside`, + `e2e.TestKeywordScope_AnEntryReadAloneByAMappingNamesNoRef`, + `e2e.TestKeywordScope_TheContentVocabularyBesideARefToAnEnumLowersAsItsTwin`, + `e2e.TestKeywordScope_AUUIDBesideARefToAStringIsAUUID`, + `e2e.TestChoice_TwoUnionsKeptBesideABodyAdmittingNullKeepTheirReasonEverywhere`, + `e2e.TestChoice_TwoUnionsSharingNullAloneBesideABodyAdmittingNullAreKept`, `schema.TestRefinement_AnAnnotationOnlyEntryLandsTyped`, `e2e.TestKindInference_AnEntryClaimingThePositionsKindIsItsPrincipal`, `e2e.TestKindInference_AnEntryClaimingTheKindIsPickedInEitherOrder`, - `schema.TestRefinementUndecided_ValueSetsAreTypedByTheMembersTheyShare`, + `schema.TestRefinementUndecided_ValueSetsIntersectAsAFlatEnumOfWhatTheyShare`, + `schema.TestValueSetUnion_IsOneSetConjunctInEverySpelling`, + `schema.TestValueSetUnion_BesideABodyIsTheEnumTheBodyAdmits`, + `e2e.TestUnionBesideBody_AUnionOfValueSetsLowersAsItsFlatEnum`, + `schema.TestLowerComponentSchemas_AUnionOfValueSetsTakesTheEnumBudget`, + `schema.TestValueSetUnion_AnIdentifierOnABranchSaysNothing`, `e2e.TestRefConjunction_AnEntrysValueSetLowersAsBesideItsRef`, `e2e.TestRefConjunction_AnEntrysValueSetLowersAlikeInEitherOrder`, - `e2e.TestEntryValueSet_TheNodeStandsAtThePositionInEverySpelling`, + `e2e.TestEntryValueSet_TheNodeIsAtThePositionInEverySpelling`, `e2e.TestEntryValueSet_TheEntryOrderLeavesTheDocumentAlone`, `e2e.TestEntryValueSet_TheWrapAndTheEntrySpellingsCompileAlike`, `e2e.TestEntryValueSet_AReferenceToThePositionReadsItsNode`, @@ -2644,27 +3007,33 @@ keeping such an `allOf` a decorator for emitters to collapse is weighed in `e2e.TestInlinePrincipal_AReferenceToAVariantEntryNamesWhatTheEntryWrites`, `e2e.TestInlinePrincipal_ABoundBesideAUnionShapedPrincipalLandsOnce`, `e2e.TestEntryValueSet_SeveralRefsAreKeptByTheirReferenceText`, - `e2e.TestEntryValueSet_AnObjectValueSetIsElectedBeforeTheComposition`, - `e2e.TestEntryValueSet_AValueSetTheTargetAlreadySaysStandsNowhere`, + `e2e.TestEntryValueSet_AnObjectValueSetIsChosenBeforeTheComposition`, + `e2e.TestEntryValueSet_AValueSetTheTargetAlreadySaysIsPlacedNowhere`, `e2e.TestEntryValueSet_AUseRepeatedLeavesTheNodesOfTheValueSetAlone`, - `schema.TestValueSet_AConstNullOnAnEntryStandsAtThePosition`, + `schema.TestValueSet_AConstNullOnAnEntrySitsAtThePosition`, `schema.TestValueSet_AnEnumPastTheBudgetOnAnEntryIsRefusedWhereWritten`, `schema.TestValueSet_TwoRefsWrittenAlikeAreKeptOnce`, - `schema.TestValueSet_AnEmptyEnumBesideACompositionIsNotElected`, - `schema.TestRefinement_PrimitiveEntriesLowerToTheirMeet`, + `schema.TestValueSet_AnEmptyEnumBesideACompositionIsNotChosen`, + `schema.TestRefinement_PrimitiveEntriesLowerToTheirIntersection`, `schema.TestRefinement_DisjointConjunctsStayAComposition`, + `schema.TestNullIntersection_ConjunctsSharingOnlyNullLowerAsTheirTwin`, + `schema.TestNullIntersection_ARefSharingOnlyNullIsKept`, + `schema.TestRestatedProperties_AnEntryRestatingTheReferentsSaysNothing`, + `schema.TestRestatedProperties_AnEntrySayingMoreComposes`, + `schema.TestRestatedProperties_PropertiesBesideTheAllOfSayNothingToo`, + `schema.TestRestatedProperties_ASchemaNamingItselfKeepsItsProperties`, `schema.TestRefinement_NamesItsTargetAtEveryPosition`, `schema.TestRefinement_KeywordsLandAtEveryPosition`, `schema.TestRefinement_KeptKeywordsLandAtEveryPosition`, `schema.TestRefinement_SeveralRefsUseTheNarrowest`, `schema.TestRefinement_KindsBeyondAnObjectAreAUse`, `schema.TestRefinement_ADynamicRefMasksNoKind`, `schema.TestDynamicRefEntry_OnAnEntryLowersAsBesideTheAllOf`, - `e2e.TestElection_AUnionAndTheWordsItTiesWithAreTheUnionHoldingTheBound`, - `schema.TestRefinementSetUnion_AUnionTheValueSetStandsBesideIsKept`, + `e2e.TestChoice_AUnionAndTheWordsItTiesWithAreTheUnionHoldingTheBound`, + `schema.TestRefinementSetUnion_AUnionTheValueSetSitsBesideIsKept`, `e2e.TestAllOfCompose_ATargetAdmittingEveryKindIsUsedNotComposed`, `e2e.TestAllOfCompose_AModelKeywordOnAKindThatIsNoObjectIsKept`, `e2e.TestAllOfCompose_EntriesClaimingTwoKindsAreNotAModel`, `e2e.TestAllOfCompose_SeveralRefsThatAreNoObjectUseTheNarrower`, - `e2e.TestAllOfCompose_ASelfReferenceStaysACompositionWithItsCycleFinding`, + `e2e.TestAllOfCompose_ASelfReferenceIsAReferenceLoop`, `e2e.TestAllOfCompose_AFormBodyOfAStringBesideMembersIsAString`, `e2e.TestAllOfCompose_ATargetNamingAKindWithAnUnexpandedDynamicRefIsUsed`, `e2e.TestAllOfCompose_APickAmongSeveralReadsNoOrder`, `e2e.TestAllOfCompose_APositionUsedTwiceLowersAsOnce`, @@ -2675,7 +3044,7 @@ keeping such an `allOf` a decorator for emitters to collapse is weighed in `schema.TestRefinement_ReachesNoFurtherThanItCanRead`, `schema.TestRefinement_NothingSaidIsTheTopType`, `schema.TestRefinement_ATypeBesideTheAllOfIsThePosition`, - `schema.TestRefinement_AValueSetNarrowsTheRefItBeats`, + `schema.TestRefinement_AValueSetNarrowsTheRefItIsChosenOver`, `schema.TestRefinement_AValueComparesAsAnEnumEntryDoes`, `schema.TestRefinement_ANarrowingKeepsItsTargetOnANode`, `schema.TestRefinement_ANarrowedRefStillLowersItsTarget`, @@ -2683,23 +3052,23 @@ keeping such an `allOf` a decorator for emitters to collapse is weighed in `schema.TestRefinement_AValueSetIsTypedByEveryConjunct`, `schema.TestRefinement_ARefToAPrincipalNamesItsTypedNode`, `schema.TestRefinement_AHoistingFormatNarrowsItsKind`, - `schema.TestRefinement_ATieOfKindsNeitherWithinTheOtherElectsNone`, + `schema.TestRefinement_ATieOfKindsNeitherWithinTheOtherChoosesNone`, `schema.TestRefinementUndecided_ThePositionIsTheKindsItsEntriesAdmit`, `schema.TestRefinementUndecided_SeveralSharedKindsAreTheirUnion`, `schema.TestRefinementUndecided_ANullTheEntriesAllAdmitStays`, - `schema.TestRefinementUndecided_AnElectionOrNoSharedValueIsUnchanged`, + `schema.TestRefinementUndecided_AChoiceOrNoSharedValueIsUnchanged`, `schema.TestChooseConjunctToLowerFrom_ComparesEachPairOnce`, - `e2e.TestElection_BothKeywordsElectTheOneOfWhicheverIsWrittenFirst`, - `e2e.TestElection_TwoUnionsOfOneKeywordElectNeither`, - `e2e.TestElection_TwoAnyOfEntriesThatDeclareNoShapeAreKeptWhole`, - `e2e.TestElection_ARefIsThePrincipalOverAUnionWhichSaysNothingMoreOfIt`, - `e2e.TestElection_ARefTieGoesByReferenceText`, `e2e.TestElection_TwoRefsWrittenAlikeGoByTheirEntries`, - `e2e.TestElection_TwoInlineEntriesThatDisagreeOnItemsElectNeither`, - `e2e.TestElection_TwoInlineEntriesTieOnTheOneWritingItems`, - `e2e.TestElection_AUnionTyingWithTheWordsIsThePrincipal`, - `e2e.TestElection_ASchemaWrittenTwiceIsOneConjunct`, - `e2e.TestElection_WordsAdmittingAlikePartOnWhatTheirNodeReads`, - `e2e.TestElection_ValueSetsAlikeGoByTheirText`, + `e2e.TestChoice_BothKeywordsChooseTheOneOfWhicheverIsWrittenFirst`, + `e2e.TestChoice_TwoUnionsOfOneKeywordChooseNeither`, + `e2e.TestChoice_TwoAnyOfEntriesThatDeclareNoShapeAreKeptWhole`, + `e2e.TestChoice_ARefIsThePrincipalOverAUnionWhichSaysNothingMoreOfIt`, + `e2e.TestChoice_ARefTieGoesByReferenceText`, `e2e.TestChoice_TwoRefsWrittenAlikeGoByTheirEntries`, + `e2e.TestChoice_TwoInlineEntriesThatDisagreeOnItemsChooseNeither`, + `e2e.TestChoice_TwoInlineEntriesTieOnTheOneWritingItems`, + `e2e.TestChoice_AUnionTyingWithTheWordsIsThePrincipal`, + `e2e.TestChoice_ASchemaWrittenTwiceIsOneConjunct`, + `e2e.TestChoice_WordsAdmittingAlikePartOnWhatTheirNodeReads`, + `e2e.TestChoice_ValueSetsAlikeGoByTheirText`, `e2e.TestAllOfRefine_ATargetInferredNarrowerThanTheDeclaredKindsIsNoPrincipal`, `e2e.TestAllOfUnion_ARefAdmittingEveryKindBesideAUnionIsKeptAsTheInlineSpellingIs`, `e2e.TestAllOfRefine_ARefLosingATieIsReportedAsATie`, @@ -2712,36 +3081,35 @@ keeping such an `allOf` a decorator for emitters to collapse is weighed in `schema.TestRefinement_AnEntryHoldsWhatItsNodeDoes`, `schema.TestRefinement_ATypeArrayPrincipalKeepsWhatNoVariantHolds`, `schema.TestRefinement_FlattensAsItsFlatSpelling`, - `schema.TestRefinement_PastItsBudgetStaysAComposition`, + `schema.TestRefinement_PastItsBudgetWhatIsLeftDecides`, `e2e.TestCompile_AUseOfOneRefLowersAlikeWhateverItsTargetsSize`, `e2e.TestCompile_AUseOfATargetAdmittingNoKindLowersAlikePastTheCaps`, - `schema.TestRefinement_PastItsConjunctBoundStaysAComposition`, - `schema.TestRefinement_ACappedEntryStaysAComposition`, + `schema.TestRefinement_PastItsConjunctBoundTheConjunctsDecide`, + `schema.TestRefinement_ACappedEntryIsTheTopType`, `schema.TestRefinement_RawTextIsComparedAgainstOneBase`, `schema.TestRefinement_AUnionEntryIsAConjunct`, `schema.TestRefinement_AUnionBesideTheAllOfIsAConjunct`, - `schema.TestRefinement_AUnionThePrincipalSaysIsConsumed`, + `schema.TestRefinement_AUnionThePrincipalSaysIsKeptWithItsDeadBranch`, `schema.TestRefinement_TheKeywordsBesideWithAUnionLowerAsWithNoAllOf`, `schema.TestRefinement_AShapelessUnionBesideIsValidationLogic`, `schema.TestUse_AUnionBesideAnAllOfReadsThroughOnlyARefinement`, - `e2e.TestExternalContent_ARefinementReadsACopyInAnotherDocumentApart`, - `e2e.TestInlinePrincipal_TheNodeStandsAtThePositionInEverySpelling`, + `e2e.TestExternalContent_ARefinementReadsACopyInAnotherDocumentInItsOwn`, + `e2e.TestInlinePrincipal_TheNodeIsAtThePositionInEverySpelling`, `e2e.TestInlinePrincipal_TheNodeHoldsTheBoundsOfTheConjunction`, `e2e.TestInlinePrincipal_ChildrenKeepThePointerTheyAreWrittenAt`, `e2e.TestInlinePrincipal_AReferenceToTheEntryNamesTheEntryAlone`, `e2e.TestInlinePrincipal_AWrapperHoldsEachBoundOnce`, - `e2e.TestRefConjunction_AUnionBesideARefToTheTopTypeStandsAtThePosition`, - `schema.TestStand_AUnionKeptBesideAPrincipalsBodyStandsAtThePosition`, - `schema.TestStand_ContentVocabularyIsReadWhereThePrincipalsNodeHoldsIt`, - `e2e.TestInlinePrincipal_AUnionStandingKeepsItsDiscriminatorsKeys`, + `e2e.TestRefConjunction_AUnionBesideARefToTheTopTypeSitsAtThePosition`, + `schema.TestPlacement_AUnionKeptBesideAPrincipalsBodySitsAtThePosition`, + `schema.TestPlacement_ContentVocabularyIsReadWhereThePrincipalsNodeHoldsIt`, + `e2e.TestInlinePrincipal_AUnionAtThePositionKeepsItsDiscriminatorsKeys`, `schema.TestAllOf_AUnionAloneOnAnEntryLowersAsItsBareSpelling`, - `e2e.TestStandingShape_AReportNamesWhatAnInlinePrincipalLoweredTo`, + `e2e.TestPositionShape_AReportNamesWhatAnInlinePrincipalLoweredTo`, `schema.TestPrincipalKept_APatternBesideThePrincipalsKeepsBoth`, `schema.TestPrincipalKept_AKeywordTheNodeReadsIsNotAlsoKept`, `schema.TestPrincipalKept_ThePositionNamesTheNodeAsItsPrincipalDoes`, `schema.TestPrincipalKept_AKeywordAlikeIsOneWritingForEveryReader`, `schema.TestPrincipalKept_ADiscriminatorBesideAUnionsOwnSaysWhoseItHolds`, - `schema.TestPrincipalKept_AnAlikeKeywordStandsWithItsFirstKeeper`, - `annotation.TestRead_AKeywordWrittenAlikeIsKeptAndReportedOnce` + `schema.TestPrincipalKept_AnAlikeKeywordSitsWithItsFirstKeeper` ### `allof-beside-ref` @@ -2756,20 +3124,23 @@ read the same way, with the warning `openapi/later-version-construct` at each su - Cases: `allof-ref-branch-siblings` - Codes: `openapi/later-version-construct` - Tests: `e2e.TestRefConjunction_AUseWritingKeywordsBesideItsRefCompilesAsTheAllOfSpelling`, - `schema.TestRefinement_AnAllOfBesideARefJoinsItsConjunction` + `schema.TestRefinement_AnAllOfBesideARefCombinesItsConjunction` ### `allof-inline-residue` An entry written inline rather than as a `$ref` owns no node, so composition has nowhere to point ([models](../ir/models.md#composition)) and the entry is merged into the composing model in place. -That merge consumes the entry's `properties`, its `required` list, a `type` that is exactly -`object`, which the composed `Model` already restates, its `additionalProperties` and +That merge consumes the entry's `properties`, its `required` list, a `type` naming `object`, `null` +aside, which the composed `Model` already restates, the `null` read as beside the `allOf` +([`nullable`](#nullable)), its `additionalProperties` and `patternProperties` where it is the schema object the model takes its catch-all from ([`additional-properties`](#additional-properties)), for an entry flattened under [`allof-classification`](#allof-classification), its `allOf`, and the `oneOf` or `anyOf` the position lowers, distributing it across its variants or composing it as a mixin, with the `discriminator` the entry writes beside it, which routes it -([`union-beside-structure`](#union-beside-structure)). +([`union-beside-structure`](#union-beside-structure)), and, where no union is part of the +conjunction, the first `discriminator` an entry writes, which the model holds +([`discriminator`](#discriminator)). JSON Schema conjoins an `allOf`'s keywords with those beside it, so what an entry writes for the position reads as written beside the `allOf`, in a composition and in a refinement @@ -2778,9 +3149,13 @@ position reads as written beside the `allOf`, in a composition and in a refineme collection bounds, `format: password` ([`password`](#password)), vendor extensions and validation-only keywords ([`validation-only`](#validation-only)) land where the same keyword beside the `allOf` lands, each read at the entry's own pointer and reported as that keyword is there, -which for most is not at all. A `nullable` folds only from an entry writing no `properties`, under -the nullable-inference policy ([`nullable`](#nullable)). Neither `unevaluatedProperties` nor -`unevaluatedItems` folds, in any form: each applies to what no keyword beside it evaluates (JSON +which for most is not at all. A `nullable: true` an entry writes beside its `type`, where its dialect +defines `nullable`, is a declared fact the null reader reads into the conjunction under either +policy, so it folds from every entry: `{allOf: [{type: string, nullable: true}], description: d}` +admits null, and `{allOf: [{type: string, nullable: true}, {type: string}]}` does not with the policy +off, the second entry excluding it. Any other `nullable` folds from any entry under the +nullable-inference policy, which reads it for the whole conjunction ([`nullable`](#nullable)). +Neither `unevaluatedProperties` nor `unevaluatedItems` folds, in any form: each applies to what no keyword beside it evaluates (JSON Schema 2020-12 §11.2, §11.3), so on an entry it holds the instance to what that entry alone evaluates, where beside the `allOf` it would exempt what the position and the other entries evaluate, and the entry kept whole is its record. A bound does not fold where the position has no @@ -2791,41 +3166,43 @@ admits no value it bounds, or one on a node with no `Constraints` for one, the ` list holding one where a variant whose type takes it does, a value bound but a property count on a `Model` or a `MapT`, and a collection bound on any node but a `List` or a `Tuple`, that `Union` holding one where such a variant does; a collection bound -`Constraints` cannot state, a `uniqueItems` of `false` or a count past 64 bits, never folds. A +`Constraints` cannot state, a count past 64 bits, never folds. A `$dynamicRef` beside the `allOf` is a conjunct masking no kind ([`allof-refinement`](#allof-refinement)), and a union beside it one more conjunct, and neither changes anything else here: where the `allOf` composes, its entries fold into the composition as they do with neither there, beside a `$dynamicRef` it keeps from expanding ([`dynamic-ref`](#dynamic-ref)) or a union kept verbatim ([`union-beside-structure`](#union-beside-structure)). Where a union beside the `allOf` or on one of its entries distributes, an entry's annotations and what a use binds reach the `Union` and its -carriers, and a value bound each variant, as the same keyword beside the `allOf` does, and an entry -with no residue is kept on no variant +carriers, and a value bound each variant, as the same keyword beside the `allOf` does; what an entry +keeps is kept once, on the `Union`, and on no variant ([models](../ir/models.md#composition-beside-a-union)). -Folding needs no precedence, because an entry that disagrees with any conjunct on one of these, the -keywords beside the `allOf` among them, folds nothing, in every order: the keywords beside the -`allOf` stand, and each entry writing that keyword otherwise stays whole, with its report. Two -keywords a position keeps in one entry, `if` and `then` say, are compared as that entry. A -`deprecated`, `readOnly` or `writeOnly` written `false` disagrees with nothing and lends nothing, as -it states nothing a `true` elsewhere does not ([`ref-use-site`](#ref-use-site)). Value -bounds and the counts `minItems` and `maxItems` agree where they meet, as a redeclared field's do -([`allof-redeclared-property`](#allof-redeclared-property)): `maxLength: 3` beside `maxLength: 5` -folds to `3`, `minItems: 1` beside `minItems: 2` to `2`, and `multipleOf: 4` beside `multipleOf: 6` -to `12`, whatever their order; a number written two ways keeps its first spelling here. Two `pattern`s -have no one value, so each disagrees with another written differently. A writer stating no value -parts no other: a 3.0 `exclusiveMinimum` of `false`, or of `true` with no bound beside it, which -fills no field, and a bound the rule table refuses ([`validation`](#validation)) say nothing a value -must meet, so its entry folds where nothing else parts it, and what the writer wrote is read and -reported at its own pointer, and kept where the same keyword beside the `allOf` is. An entry whose -folding keywords write a relative `$ref` it reads against another base than the position does, an -`$id` at or above it naming another URI, folds nothing either, since that `$ref` would name another -schema read at the position; it stays whole, with its report, and is no conjunct the others are -compared with. One writing none -there, or only absolute ones, reads the same at the position, so an `$id` alone keeps nothing it -writes from folding. A `dependencies` an entry naming a draft writes does not fold where the -keywords beside the `allOf` write a `dependencies` their own dialect does not define +Folding needs no precedence, because each keyword folds by its own writers: one every conjunct +writing it, the keywords beside the `allOf` among them, states alike folds, whatever they say of +another keyword, and one they write otherwise folds nothing, in every order: the keywords beside the +`allOf` hold, and each entry writing that keyword otherwise stays whole, with its report, while what +it writes alike folds. Two keywords a position keeps in one entry, `if` and `then` say, are compared +as that entry, so a group folds only whole, and beside what disagrees a value rendering to no JSON, +which reports itself, folds nothing. A `deprecated`, `readOnly` or `writeOnly` written `false` +disagrees with nothing and lends nothing, as it states nothing a `true` elsewhere does not +([`ref-use-site`](#ref-use-site)). Value bounds and the counts `minItems` and `maxItems` intersect, +as a redeclared field's do ([`allof-redeclared-property`](#allof-redeclared-property)): +`maxLength: 3` beside `maxLength: 5` folds to `3`, `minItems: 1` beside `minItems: 2` to `2`, and +`multipleOf: 4` beside `multipleOf: 6` to `12`, whatever their order; a number written two ways +keeps its first spelling here. Two `pattern`s have no one value, so each disagrees with another +written differently. A writer stating no value parts no other: a 3.0 `exclusiveMinimum` of `false`, +or of `true` with no bound beside it, which fills no field, and a bound the rule table refuses +([`validation`](#validation)) say nothing a value must satisfy, so its entry folds where nothing +else parts it, and what the writer wrote is read and reported at its own pointer, and kept where the +same keyword beside the `allOf` is. An entry whose folding keywords write a relative `$ref` it reads +against another base than the position does, an `$id` at or above it naming another URI, folds +nothing either, since that `$ref` would name another schema read at the position; it stays whole, +with its report, and is no conjunct the others are compared with. One writing none there, or only +absolute ones, reads the same at the position, so an `$id` alone keeps nothing it writes from +folding. A `dependencies` an entry naming a draft writes does not fold where the keywords beside the +`allOf` write a `dependencies` their own dialect does not define ([`dialect-keywords`](#dialect-keywords)): both are kept under `openapi:dependencies`, one key -holding one value, so the entry's is residue, held against the other as below. +holding one value, so the entry's is one it keeps, held against the other as below. What an entry writes that no reader consumes is kept as the same keyword beside the `allOf` is: each keyword under its own key, `Unmodeled["openapi:"]`, its provenance the keyword where the @@ -2837,16 +3214,25 @@ reported at the keyword, the last by an `openapi/unknown-schema-keyword`, as is against the position, reported by an `openapi/validation-only-keyword` at the entry, and `degraded_lowering` where they do or where it shares no kind with the rest ([`union-beside-structure`](#union-beside-structure)). The union of an inline principal that -lowered to the nullable reference to its one non-null branch is no residue: the reference says it, -as it says the same union written at the position, and a null branch writing more than its null is -kept whole as [`union-null-variant`](#union-null-variant) keeps one there. A value bound where the +lowered to the nullable reference to its one non-null branch is nothing the entry keeps: the +reference says it, as it says the same union written at the position, and a null branch writing more +than its null is kept whole as [`union-null-variant`](#union-null-variant) keeps one there. What an +entry writes beside the union the position is, or the position beside an entry's, lowers as the same +keywords written flat beside that union: beside one collapsing to that nullable reference, a keyword +no branch says and the reference has no home for is kept, so +`{allOf: [{type: [string, 'null'], enum: [a, null]}], anyOf: [{type: 'null'}, {format: uuid}]}` keeps +its `type` and its `enum`; beside one leaving null alone, a value set is read, as the closed empty +`Enum` reads one; and beside one the position writes itself, a value set no branch says is kept, as +`{allOf: [{type: string, enum: [a, b]}], oneOf: [{format: uuid}, {format: date}]}` keeps its `enum`. +A value bound where the position's own node carries a number as text is `no_ir_home`, reported at the keyword, as one beside it is ([`string-formats`](#string-formats)). An `unevaluatedProperties` or `unevaluatedItems` keeps its entry whole (below), its slot `validation_only` as beside the `allOf` ([`validation-only`](#validation-only)). Every other keyword is `degraded_lowering`, and -those of one entry are reported by one `openapi/degraded-construct` at the entry naming them, an -info, and a warning where the entry declares a `type` that excludes `object`, because the composing -`Model` then asserts a shape the source contradicts. A `$comment`, `$anchor`, `$dynamicAnchor` or +those of one entry are reported by one finding at the entry naming them, an info +`openapi/degraded-construct`, and a warning `openapi/unsatisfiable-schema` where the entry declares a +`type` that excludes `object`, because the composing `Model` then asserts a shape the source +contradicts. A `$comment`, `$anchor`, `$dynamicAnchor` or `$defs`, or a draft's twin of one, is read as it is beside the `allOf` and kept nowhere; one the dialect does not define is a key no dialect defines. Which keywords an entry keeps is derived from its own declared key set rather than from a fixed list, so a keyword the dialect gains later is kept @@ -2866,56 +3252,78 @@ them, writes otherwise, where one `Unmodeled` entry under the keyword holds one consumed keywords included, so the source stays reconstructable rather than having to be reassembled from two places, but for an entry writing a `$ref` beside its keywords: that is two conjuncts, and what is kept whole is the rest, the entry less its `$ref`, which lowers or is kept as any `$ref` -conjunct is, while one whose `$ref` names no schema, read whole, keeps its `$ref` inside. The inline +conjunct is, one whose `$ref` names no schema among them. The inline principal, which the position lowers from, is lowered and not kept whole for this last cause. What it keeps is held against what the position keeps, which is written first, as the flat spelling writes it: a keyword whose own key `openapi:` is free is kept there, as written flat; one that key holds with the same value is kept once; and one it holds with another value is kept on the same node under the principal's entry's key, `openapi:allOf/`, the rest of the entry lowered. That key holds one object of every such keyword, whichever reading of the principal keeps -it, its keeping of unread keywords, its bounds on a number carried as text, its content vocabulary or the entry's -residue, a key no dialect defines among it, under the reason they share, else `degraded_lowering`, -at the entry, and each reading names its own there in one `openapi/degraded-construct` info, by the -entry's path, `allOf/`, which the key ends in on a carrier too. What the principal's build keeps -beside the field it could not fill, a `format` beside a `contentEncoding` -([`content-vocabulary`](#content-vocabulary)), the `oneOf` or `anyOf` its `Union` passes over -([`competing-keywords`](#competing-keywords)), a `prefixItems` beside a listed tuple -([`tuples`](#tuples)), is held against the position's the same way and joins that object, its one -report the one the same keyword written flat draws, where it is written. An entry naming no kind -whose own `allOf` holds the principal, at any depth, is flattened +it, its keeping of unread keywords, its bounds on a number carried as text, its content vocabulary +or what the entry keeps, a key no dialect defines among it, under the reason they share, else +`degraded_lowering`, at the entry, and each reading names its own there in one +`openapi/degraded-construct` info, by the entry's path, `allOf/`, which the key ends in on a +carrier too. What the principal's build keeps beside the field it could not fill, a `format` beside +a `contentEncoding` ([`content-vocabulary`](#content-vocabulary)), the `oneOf` or `anyOf` its +`Union` passes over ([`competing-keywords`](#competing-keywords)), a `prefixItems` beside a listed +tuple ([`tuples`](#tuples)), is held against the position's the same way and goes into that object, +its one report the one the same keyword written flat draws, where it is written. An entry naming no +kind whose own `allOf` holds the principal, at any depth, is flattened ([`allof-classification`](#allof-classification)) and is one the position lowers from too: its -keywords are written beside the principal's `allOf`, so it is not kept whole for this cause -either, and each level is held against the levels around it, the outermost first: +keywords are written beside the principal's `allOf`, so it is not kept whole for this cause either, +and each level is held against the levels around it, the outermost first: `{allOf: [{allOf: [{type: string, minimum: 3}], minimum: 2}], minimum: 1}` keeps `1` under -`openapi:minimum`, `2` under `openapi:allOf/0` and `3` under `openapi:allOf/0/allOf/0`, and with -no `minimum` beside the outer `allOf`, `2` under `openapi:minimum`. A level writing a keyword as a +`openapi:minimum`, `2` under `openapi:allOf/0` and `3` under `openapi:allOf/0/allOf/0`, and with no +`minimum` beside the outer `allOf`, `2` under `openapi:minimum`. A level writing a keyword as a level around it does is that one writing, kept once under the outermost key holding it, and the plain key holds what the position writes though its principal keeps it alike: `{allOf: [{allOf: [{type: string, minimum: 2}], minimum: 3}], minimum: 2}` keeps `2` under -`openapi:minimum` and `3` under `openapi:allOf/0`. Two values are the same where -they render to the same JSON, member order aside, a number's spelling and an array's order -included: `1` and `1.0` are two values, each kept. A value no JSON holds is refused where it is -written, as the flat spelling's is, and kept nowhere. A principal the position keeps whole -for one of the causes above holds there every keyword of it that no field reads: each is kept once, -inside the whole entry, and named once, by that entry's report, or what its build keeps by the -build's own (above), and the entry's reason reads them all as it reads the rest, and the -principal's own reading keeps and reports none of them apart, a type list's variants included. A wrapper kept whole holds the principal inside it the same way, and what is -kept of an entry within one kept whole is kept there alone. One whose entry no JSON holds is not -kept whole: what it keeps is held keyword -by keyword, as above, the value no JSON holds refused where it is written by an -`openapi/unpreservable-construct` error. It is kept -under the reason its kept keywords share where they share one, else -`degraded_lowering`, and reported at the entry by an `openapi/validation-only-keyword` where that -reason is `validation_only`, else by an `openapi/degraded-construct` as above. What such an entry -folds is typed as any entry's is, and what its fold would keep beside it, a vendor extension or a -validation-only keyword, is kept once, inside it, but for a key the promotion policy reads -([unmodeled](../ir/unmodeled.md#keys)). Such an entry writes no keyword for anyone else: one another +`openapi:minimum` and `3` under `openapi:allOf/0`. Two values are the same where they render to the +same JSON, member order aside, a number's spelling and an array's order included: `1` and `1.0` are +two values, each kept. A boolean `exclusiveMinimum` or `exclusiveMaximum`, as draft-04 and 3.0 write +it, is one writing with its `minimum` or `maximum`, so a flag never takes the plain key beside +another writer's bound: at 3.0, +`{allOf: [{type: string, minimum: 1, exclusiveMinimum: true}], minimum: 2, exclusiveMinimum: false}` +keeps `2` under `openapi:minimum` and the entry's pair under `openapi:allOf/0`, the `false` flag +saying nothing (above), and `{allOf: [{type: string, minimum: 1}], exclusiveMinimum: true}` keeps +the flag under `openapi:exclusiveMinimum` and `1` under `openapi:allOf/0`. A value no JSON holds is +refused where it is written, as the flat spelling's is, and kept nowhere, but for a vendor +extension's: wherever an entry or a keyword is kept, whole or apart, the extension alone is left +out, with the `openapi/degraded-construct` warning it draws where it is written, and what held it is +kept and reported as it is without it, with no error. A principal the position keeps whole for one +of the causes above holds there every keyword of it that no field reads: each is kept once, inside +the whole entry, and named once, by that entry's report, or what its build keeps by the build's own +(above), and the entry's reason reads them all as it reads the rest, and the principal's own reading +keeps and reports none of them apart, a type list's variants included. A wrapper kept whole holds +the principal inside it the same way, and what is kept of an entry within one kept whole is kept +there alone. One whose entry no JSON holds, but for a vendor extension it leaves out, is not kept +whole: what it keeps is held keyword by keyword, as above, the value no JSON holds refused where it +is written by an `openapi/unpreservable-construct` error. It is kept under the reason its kept +keywords share where they share one, else `degraded_lowering`, and reported at the entry by an +`openapi/validation-only-keyword` where that reason is `validation_only`, else by an +`openapi/degraded-construct` as above. What such an entry folds is typed as any entry's is, and what +its fold would keep beside it, a vendor extension or a validation-only keyword, is kept once, inside +it, but for a key the promotion policy reads ([unmodeled](../ir/unmodeled.md#keys)), and named by +the entry's report with the rest it holds, though the entry's reason is read from the rest alone, as +what it folds is typed. Such an entry writes no keyword for anyone else: one another entry keeps or folds alike is that entry's, kept at its keyword, so each is kept once. A keyword two entries not kept whole keep alike, and the keywords beside the `allOf` do not write, is kept once, its provenance the position's pointer, as no one writer's is the same in every order of the entries; one the keywords beside the `allOf` write alike is theirs, kept as they keep it. A keyword two such folding entries write alike is the position's the same way, but `default`, `readOnly` -and `writeOnly`, kept at the nearest entry writing them. +and `writeOnly`, and the `xml` a parameter keeps, which holds no field for it, kept at the nearest +entry writing them. Its one report is the entry's whose rendering as written sorts first, but where +nothing but the order of the entries tells its writers apart, as for entries written alike and a +keyword binding a use, it is drawn at the position, worded as the same keyword written beside the +`allOf` is reported: `{type: array, items: {type: string}, allOf: [{minimum: 1}, {minimum: 1}]}` +reports at the schema that it has no home for `minimum` declared beside it. All of this is one settlement of the node, which every writer of it keeps +through: the position, each entry and wrapper level, the principal's build, a `$ref` entry naming +nothing and a carrier alike. One value is one entry and one report, the outermost writer's; several +are the outermost writer's under the plain key and each other writer's under its entry key, whole +for an entry nothing lowers from and its colliding keywords alone for one the position lowers from; +and where no writer lies around the others, as sibling entries do not, each value is kept under +its writer's entry key and none under the plain key: `{type: object, allOf: [{x-foo: 1}, +{x-foo: 2}]}` keeps both entries whole and nothing under `openapi:x-foo`. A position composes beside an entry declaring a `type` that excludes `object` only where the conjuncts share no value but null, as `{allOf: [{type: [object, "null"], …}, {type: [string, "null"], @@ -2925,12 +3333,13 @@ writing no `type` is a use of the string. Where the conjuncts share no value, as writes `type: object`, [`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) reports that once at the schema and the entry's report is an info. Two entry kinds are outside this rule rather than limits of it: a `$ref` entry owns a node, so what is written beside the `$ref` is *modeled* on the -entry alias [models](../ir/models.md#composition-entries) describes rather than kept as residue, and -a boolean entry declares no keywords at all, so there is nothing to keep — it is a decision about the -composed node instead, stated with the `false`-schema rule [`allof-false-branch`](#allof-false-branch). +entry alias [models](../ir/models.md#composition-entries) describes rather than kept as an inline +entry's are, and a boolean entry declares no keywords at all, so there is nothing to keep — it is a +decision about the composed node instead, stated with the `false`-schema rule +[`allof-false-branch`](#allof-false-branch). A `$ref` entry whose reference lands on no schema, an entry lying on a loop of `$ref`s among them, -owns no node, so what it writes is residue as an inline entry's is, but for its `required` list, +owns no node, so what it writes is kept as an inline entry's is, but for its `required` list, which the model's members read, and its folding keywords, which fold nothing and so disagree with nothing: the reference is kept as written under `openapi:$ref`, or `openapi:$ref/` where several are kept, `i` the rank of the reference text, then of the entry as written, so no order of the @@ -2945,13 +3354,29 @@ adds no second report of it. A flattened entry kept whole is whole too, its own entries included, so an entry inside it that is kept on its own account, or a `false` one ([`allof-false-branch`](#allof-false-branch)), is in `Unmodeled` twice: inside the flattened entry's copy and under its own path. A consumer that reads -every entry reads that one twice. An inline principal and the wrappers around it are no such -entries: the position lowers from them, and each of their keywords is kept once (above). +every Unmodeled entry reads that one twice. An inline principal and the wrappers around it are no +such entries: the position lowers from them, and each of their keywords is kept once (above). + +A node's keeping reports come in the order its readers keep, whatever the order of the entries: +what the node's build keeps, a composition's of the keywords beside the `allOf` and then of each +entry it keeps, a refinement's of its inline principal; then what the position's annotations keep; +then what each folded entry keeps as written beside the `allOf`; then what binds a use, the entries' +before the position's; and last what a refinement keeps beside what it lowered to, the position's +unread keywords before each entry it keeps, but after them where its inline principal is a value +set. Of one reader, entries report in the order written, and a report naming several keywords, a +keeping's or that of an entry kept whole or apart, lies where the first of them is kept, as does +one drawn at the position for entries keeping a value alike (above). - Cases: `allof-inline-residue` -- Codes: `openapi/degraded-construct`, `openapi/validation-only-keyword`, `openapi/unknown-schema-keyword`, - `openapi/unresolved-ref`, `openapi/cyclic-ref`, `openapi/unpreservable-construct` +- Codes: `openapi/degraded-construct`, `openapi/unsatisfiable-schema`, `openapi/validation-only-keyword`, + `openapi/unknown-schema-keyword`, `openapi/unresolved-ref`, `openapi/cyclic-ref`, + `openapi/unpreservable-construct` - Tests: `schema.TestAllOfEntryFolding_AFalseFlagAgreesWithATrue`, + `e2e.TestUnionBesideBody_AValueSetBesideThePositionsUnionLowersAsFlat`, + `schema.TestAllOfEntryFolding_ATypedNullableIsReadUnderEitherPolicy`, + `e2e.TestKeywordScope_EntriesAgreeingOnAKeywordFoldItApartFromAnother`, + `e2e.TestKeywordScope_ACommentStaysInItsOwnObject`, + `e2e.TestKeywordScope_AnItemsMovesWithItsPrefixItems`, `e2e.TestPrincipalApart_AKeywordThePrincipalAndThePositionKeepHoldsBoth`, `e2e.TestPrincipalApart_AParameterSchemaHoldsBoth`, `e2e.TestPrincipalApart_AReportNamesTheEntryWhereACarrierKeepsIt`, @@ -2962,38 +3387,34 @@ entries: the position lowers from them, and each of their keywords is kept once `schema.TestPrincipalKept_ADraftsDependenciesBesideAKeyNoDialectDefines`, `schema.TestPrincipalKept_ADiscriminatorKeptPlainHoldsItsKeysOnce`, `schema.TestPrincipalKept_AValueThatCannotRenderIsRefusedAsWrittenFlat`, - `schema.TestPrincipalKept_AWholeEntryThatCannotRenderIsKeptByKeyword`, + `schema.TestPrincipalKept_AWholeEntryIsKeptWithoutAnExtensionNoJSONHolds`, `schema.TestPrincipalKept_AFailedKeepingLeavesWhatItsReportsName`, - `schema.TestKeepApart_AnObjectThatCannotRenderIsReportedAndClaimsNothing`, `schema.TestPrincipalKept_WhatABuildKeepsIsHeldAgainstThePositions`, - `schema.TestPrincipalKept_AFoldedEntriesBuildKeepStaysThePositions`, - `schema.TestKeepBuilt_AKeyNoKeywordNamesHeldOtherwiseIsAnInvariantBroken`, + `schema.TestPrincipalKept_AFlattenedEntriesBuildKeepStaysThePositions`, `schema.TestPrincipalKept_ANestedPrincipalKeepsEachLevelOnce`, `schema.TestPrincipalKept_ALevelAlikeWithOneAroundItIsKeptOnce`, `e2e.TestPrincipalWhole_AKeptValueIsKeptOnceAndReportedOnce`, `e2e.TestPrincipalWhole_TheWholeEntrysReasonReadsEveryKeywordItHolds`, `e2e.TestPrincipalApart_AKeptDiscriminatorResolvesItsMapping`, - `schema.TestStand_ADiscriminatorKeptUnderThePrincipalsEntryResolvesItsMapping`, - `e2e.TestKeptEntryKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndReason`, - `e2e.TestKeptEntryKeyword_AKindKeywordIsKeptUnderItsOwnKey`, - `e2e.TestKeptEntryKeyword_APerKindBoundNoHomeTakesIsKeptUnderItsOwnKey`, - `e2e.TestKeptEntryKeyword_AChoiceIsKeptUnderItsKeywordWithItsReason`, - `e2e.TestKeptEntryKeyword_ADynamicReferenceOnAnEntryOfAnItemIsKeptUnderItsOwnKey`, - `e2e.TestKeptEntryKeyword_AScopedKeywordIsKeptOutOfScopeAndAConsumedOneNowhere`, - `e2e.TestKeptEntryKeyword_ACommentAnchorOrDefsOnAnEntryReachesNoNode`, - `e2e.TestKeptEntryKeyword_AnEntryWritingSeveralKeywordsKeepsEachUnderItsOwnReason`, - `e2e.TestKeptEntryKeyword_AClosureTheEntryCannotTypeKeepsTheEntryWhole`, - `e2e.TestKeptEntryKeyword_ARelativeReferenceMergedInPlaceKeepsTheEntryApart`, - `e2e.TestKeptEntryKeyword_TwoUnionsDeclaringNoShapeAreKeptWholeAsValidationOnly`, - `e2e.TestKeptEntryKeyword_AnEntryDisagreeingWithAnotherKeepsItsKeywordsReasonWhenKeptWhole`, - `e2e.TestKeptEntryKeyword_TwoWritersOfOneKeywordAndValueKeepOneEntryAtThePosition`, - `e2e.TestKeptEntryKeyword_TwoEntriesKeepingOneKeywordAlikeKeepOneEntryAtThePosition`, - `e2e.TestKeptEntryKeyword_AKeywordWrittenAlikeBesideTheAllOfIsKeptAsThere`, + `schema.TestPlacement_ADiscriminatorKeptUnderThePrincipalsEntryResolvesItsMapping`, + `e2e.TestAllOfEntryKeptKeyword_EverySpellingOfAContentOrUnknownKeywordKeepsOneKeyAndReason`, + `e2e.TestAllOfEntryKeptKeyword_AKindKeywordIsKeptUnderItsOwnKey`, + `e2e.TestAllOfEntryKeptKeyword_APerKindBoundNoHomeTakesIsKeptUnderItsOwnKey`, + `e2e.TestAllOfEntryKeptKeyword_AChoiceIsKeptUnderItsKeywordWithItsReason`, + `e2e.TestAllOfEntryKeptKeyword_ADynamicReferenceOnAnEntryOfAnItemIsKeptUnderItsOwnKey`, + `e2e.TestAllOfEntryKeptKeyword_AScopedKeywordIsKeptOutOfScopeAndAConsumedOneNowhere`, + `e2e.TestAllOfEntryKeptKeyword_ACommentAnchorOrDefsOnAnEntryReachesNoNode`, + `e2e.TestAllOfEntryKeptKeyword_AnEntryWritingSeveralKeywordsKeepsEachUnderItsOwnReason`, + `e2e.TestAllOfEntryKeptKeyword_AClosureTheEntryCannotTypeKeepsTheEntryWhole`, + `e2e.TestAllOfEntryKeptKeyword_ARelativeReferenceMergedInPlaceKeepsTheEntryApart`, + `e2e.TestAllOfEntryKeptKeyword_TwoUnionsDeclaringNoShapeAreKeptWholeAsValidationOnly`, + `e2e.TestAllOfEntryKeptKeyword_AnEntryDisagreeingWithAnotherKeepsItsKeywordsReasonWhenKeptWhole`, + `e2e.TestAllOfEntryKeptKeyword_TwoConjunctsOfOneKeywordAndValueKeepOneEntryAtThePosition`, + `e2e.TestAllOfEntryKeptKeyword_TwoEntriesKeepingOneKeywordAlikeKeepOneEntryAtThePosition`, + `e2e.TestAllOfEntryKeptKeyword_AKeywordWrittenAlikeBesideTheAllOfIsKeptAsThere`, `schema.TestEntryKept_AnEntryKeptWholeHoldsWhatItFoldsOnce`, `schema.TestEntryKept_AnEntryOfAnUndecidedAllOfIsReportedAgainstTheKeywordsBesideIt`, - `schema.TestEntryKept_AFailedRefKeepsItsReferenceAndEachKeywordBesideIt`, - `schema.TestEntryKept_FailedRefsAreKeptByTheirReferenceInEitherOrder`, - `schema.TestEntryKept_AFailedRefIsKeptWholeWhereItsKeywordsCannotBeKeptApart`, + `schema.TestEntryKept_AFailedRefLowersAsItsEntryWithoutIt`, `e2e.TestKeptFailedRef_EveryKeyBesideAFailedRefIsKeptAndTheFailureReportedOnce`, `e2e.TestKeptFailedRef_SeveralFailedRefsAreKeptByAscendingReferenceText`, `e2e.TestKeptFailedRef_ARefInsideAnEntryOrAtAnItemIsKept`, @@ -3002,35 +3423,33 @@ entries: the position lowers from them, and each of their keywords is kept once `schema.TestEntryKept_ContentTwoEntriesWriteApartIsKeptWholeAsItsReason`, `schema.TestEntryKeptReason_ABoundOnANumberAsTextIsKeptAsBesideIt`, `schema.TestEntryKeptReason_AnUnevaluatedKeywordKeepsItsEntryValidationOnly`, - `annotation.TestUnderlayAdd_TheSiteOwnsWhatSeveralWrite`, - `annotation.TestUnderlayAdd_AFoldedEntryKeptWholeWritesForNoOne`, `schema.TestEntryKeptOnce_AKeywordAnEntryKeptWholeSharesIsKeptInsideItAlone`, `schema.TestEntryKeptOnce_AtACarrierTheEntryKeptWholeHoldsItsOwn`, `schema.TestEntryKeptOnce_APromotedKeyStaysBesideTheEntryKeptWhole`, `schema.TestEntryKeptOnce_EveryKeywordOfAGridIsKeptOnce`, - `schema.TestAllOf_EntryWrittenByReferenceStillDerivesResidue`, - `schema.TestAllOf_MergedEntryKeywordsAreNotResidue`, - `schema.TestAllOf_UnpreservableEntryIsNotAnnounced`, + `schema.TestAllOf_EntryWrittenByReferenceStillDerivesUnreadKeywords`, + `schema.TestAllOf_MergedEntryKeywordsAreNotUnread`, + `schema.TestAllOf_AnEntryIsKeptWithoutAnExtensionNoJSONHolds`, `schema.TestAllOf_NestedInlineEntryKeyedByPointer`, - `schema.TestAllOf_NestedWrapperWithResidueKeptVerbatim`, + `schema.TestAllOf_NestedWrapperWithUnreadKeywordsKeptVerbatim`, `schema.TestAllOf_NestedEmptyAllOfKeptVerbatim`, `schema.TestAllOf_EmptyAllOfBesideNonObjectTypeNamesBoth`, - `schema.TestAllOf_KeptEntryOfAKeptWrapperIsKeptTwice`, + `schema.TestAllOf_AKeptAllOfEntryOfAKeptWrapperIsKeptTwice`, `schema.TestAllOfEntryFolding_AKeywordFoldsWhereTheAllOfWouldKeepIt`, - `schema.TestFoldedAllOfEntries_AnEntryDisagreeingFoldsNothingInEveryOrder`, - `schema.TestAllOfEntryFolding_BoundsMeetInEveryOrder`, - `schema.TestAllOfEntryFolding_ARefusedBoundPartsNoWriter`, + `schema.TestFlattenedAllOfEntries_AnEntryDisagreeingFoldsNothingInEveryOrder`, + `schema.TestAllOfEntryFolding_BoundsIntersectInEveryOrder`, + `schema.TestAllOfEntryFolding_ARefusedBoundPartsNoConjunct`, `schema.TestAgreement_ReadsABoundInTheDialectOfItsSchemas`, `schema.TestAllOfEntryFolding_KeywordsOneEntryHoldsDisagreeAsOne`, - `schema.TestFoldedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry`, + `schema.TestFlattenedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry`, `schema.TestAllOfEntryFolding_AUseBindingKeywordReachesItsCarrierOrItsNode`, - `schema.TestFoldedAllOfEntries_KeptAndMetEntriesHoldAtEveryOutcome`, - `schema.TestAllOf_EntryResidueRidesEveryDistributedVariant`, + `schema.TestFlattenedAllOfEntries_KeptAndIntersectedEntriesHoldAtEveryOutcome`, + `schema.TestAllOf_EntryUnreadKeywordsAreKeptOnceOnTheDistributedUnion`, `schema.TestAllOf_AnEntryReadAgainstAnotherBaseFoldsNothing`, `schema.TestAllOf_AnEntryWritingNoRelativeReferenceFoldsUnderAnyBase`, `schema.TestRefinement_AnEntryReadAgainstAnotherBaseFoldsNothing`, `schema.TestCollectionBound_OnAnEntryLandsAsItsFlatSpelling`, - `schema.TestCollectionBound_OnAnEntryMeetsInEveryOrder`, + `schema.TestCollectionBound_OnAnEntryIntersectsInEveryOrder`, `schema.TestCollectionBound_OnAnEntryWithNoFieldStaysWithItsEntry`, `schema.TestRefinement_AValueBoundOnAnEntryBesideATypeListLandsOnItsVariant`, `schema.TestRefinement_AnEntryBoundBesideATypeListIsReadAtTheEntry`, @@ -3038,215 +3457,296 @@ entries: the position lowers from them, and each of their keywords is kept once `schema.TestConstraints_AnEntryReadsTheBoundsItsOwnTypeTakes`, `schema.TestConstraints_AnEntryCountItsTypeCannotTakeIsKeptWithIt`, `openapicases.TestCore_SpellingsHoldTheRecord`, - `e2e.TestUnionAlone_OnAnEntryLowersAsWrittenAtThePosition` + `e2e.TestUnionAlone_OnAnEntryLowersAsWrittenAtThePosition`, + `schema.TestPrincipalKept_ReportsComeInTheOrderTheirReadersKeep`, + `schema.TestPrincipalKept_AKeywordFlattenedEntriesKeepAlikeIsReportedByContent`, + `schema.TestPrincipalKept_AValueOnlyOrderTellsApartIsReportedAtThePosition` ### `allof-redeclared-property` `allOf` intersection folds a field declared in more than one entry into one `Property` -([models](../ir/models.md#the-flattening)), which keeps the first declaration's identity unless -another model carries that declaration. The fold reads every declaration of the field at once, -once every type has lowered, and decides each fact from the whole set, so neither the order of the -entries nor where a component is declared decides what the field holds; declaration order breaks +([models](../ir/models.md#the-flattening)), which takes the identity of the declaration whose +pointer, its `allOf` indices erased, is shortest, then least so erased, then least as written, +unless another model carries that declaration. The fold reads every declaration of the field at +once, once every type has lowered, and decides each fact from the whole set, so neither the order of +the entries nor where a component is declared decides what the field holds; declaration order breaks only a tie, and the merge reports each one. One judgment compares two declarations' types and -returns a verdict: the same type, either one narrower, two nodes that meet, an overlap, disjoint, or -unrelated. A disjoint pair is unsatisfiable but for a null both declarations admit: no other value -satisfies both. An overlap shares values and is merely not narrowed to one. The arms are tried in -this order. -`{}` loses to anything but the node a degraded lowering mints (an enum past its member budget, an -unconvertible const), which is unrelated to every type, and so does an alias of `{}` that says -nothing of its values: as a field's own type it may hold the docs, deprecation and redaction a -reference carries down to the field ([annotations](../ir/annotations.md#what-a-reference-carries-down)), -and anywhere else nothing but where it was declared. Two such types lose to neither: what else each -says decides, so an alias of one is narrower than the other it stands for, and two aliases neither -standing for the other are not compared. Where `{}` loses, the winner's own null -admission stands alone, since `{}` admits null yet lowers non-nullable. Two bare primitives compare -by value domain and spelling (`integer` against `number`, `uuid` against `string`, `int32` against -`int64`). A `Scalar` or `Enum` against a bare primitive wins over a kind it equals or narrows -(`string` against `format: byte`, or an unknown format over bare `string`), is disjoint from a kind -of another family, or from another string format where neither is `bytes` (`uuid` against -`format: date`), and overlaps any other kind (`uuid` against `format: byte`); for an `Enum`, that -overlap is disjoint where the kind's judge refuses every member, an enum behind an alias, as a -member written beside a bound is, judged by the members of the enum it stands for, which the alias -can only narrow. A `Scalar`'s kind is that of the values it travels as: its base's, but for a base -its `Encoding`'s `WireType` does not spell, whose values travel as that type, so `format: unixtime` -on an `integer` is narrower than `integer`, overlaps `int64` and is disjoint from `string`, while -`byte` stays `bytes`, which a `string` spells. A string format whose text an `Encoding` names -otherwise, as `http-date` and `contentEncoding` do, has no judge, as `bytes` has none, since the -format's own grammar reads another text: an enum of HTTP-dates beside `format: http-date` overlaps -it. A `Scalar` hoisted for `time`, -whose grammar, RFC 3339's `full-time`, the compiler holds though the table pairs it with no kind -([`string-formats`](#string-formats)), is read wherever a kind is, through an alias too, as a -string format of its own: within `string`, an overlap with `bytes`, and disjoint from every other -kind, `time-local` and `date-time` among them, and from an `Enum` none of whose members it -admits. An enum with no members is refused -vacuously, so it is disjoint from any kind it would otherwise overlap, `bytes` included; an enum -with members against `bytes` stays an overlap. A `const`, or an alias of one, wins when the kind -admits its value; where it does not, it is disjoint from a kind with a judge and overlaps `bytes`, -which has none. Against a -`Scalar` hoisted for `time`, a `const` is disjoint where the node refuses its value, and wins where -the node admits it and says nothing but its base, the format and bounds, so a field typed by the -`const` loses none of it. Where the node also says what a `const` can hold beside its value, a -description or a deprecation, the two meet in a `const` holding that too (below); a node giving -examples overlaps it, since nothing shows the `const` admits them. Two -enums, two `const`s or two `Scalar`s equal in every field but where they were declared (IDs, names, -whether hoisted inline, and the provenance of the node and of what it keeps under `Unmodeled`) are -one type where both were written inline at the field's own declarations, in their document, as the -same declaration written twice; a node declared elsewhere, a component or a schema a `$ref` reaches -in this document or another, wins over an inline copy of itself in either order, and two such nodes -are two types the source declared apart, which overlap. A copy is one type with the other node, or -gives way to it, only where what the two keep under `Unmodeled` writes no relative `$ref`, or both -read it against one base where each is written: under an `$id` naming another URI, or in another -document, a `$ref` spelled alike names another schema, so the two were declared apart and overlap. -Two `const`s of different values share none, so they are disjoint. Two enums of one closedness, -bit-flag reading and fallback, whose members holding one value say the same of it, are judged by -the values they hold: sharing none, they are disjoint, whatever their value types. Of two value -types one within the other, the narrower says more (`integer` against `number`), so one whose -values the other holds every one of, of the same value type or the narrower, is narrower where it -also says all the other does beside its members, and otherwise the two meet, as do two each holding -a value the other lacks, in an enum of the values they share, of the narrower value type (below), -where both list those values in one order. Two listing them in different orders overlap, since an -enum of both would take its order from one declaration. Two holding one set of values of one value -type, or in another order, or saying the rest differently, two of value types neither within the -other (`int32` against `uint32`), and any other pair of enums, are judged by their kind. -Two models alike in every member but where they and what they name were declared (the same -properties in the same order, each with the same wire name, required flag, visibility, docs, -constraints, values and kept text, and the same catch-all, composition and discriminator, its tag -read by position) are judged the same way where every type they name relates to the other's as the -same type, or as that rule relates the two models: a component wins over an inline copy of itself, -a nested object included, in either order, and two inline copies are one type. A property keeping a -relative `$ref` makes them one only under one base, as above. Two components alike were declared -apart, and models alike in all but a type that relates otherwise are no copies, so either pair -composes as two models do (below). One judgment compares at most 64 pairs of models member by -member, since a `$ref` to a sibling position adds width at no cost in document size; past that the -two are unrelated and compose, which loses nothing. -An alias is narrower than the type it stands for, whatever its kind: a reference to it reads all -that type says, and it may say more. One whose chain admits null, as `{anyOf: [E, {type: null}]}` -does, is not, since `E` refuses null: where the chain adds nothing else, docs included, `E` is -narrower and the field holds it, and otherwise the two are judged as below. Against any other type, an alias whose chain ends in an enum, -a `const`, a `Scalar`, a list, a map or a tuple is judged, and a node it meets built, as that node -holding the bounds the chain and the node say together and each detail the nearest of them sets, -documentation field by field, as a reference to the alias reads it +returns one result: the same type, either one narrower, two nodes that combine, an overlap, +disjoint, or unrelated. A disjoint pair is unsatisfiable but for a null both declarations admit: no +other value satisfies both. An overlap shares values and is merely not narrowed to one. The arms are +tried in this order. `{}` loses to anything but the node a degraded lowering mints (an enum past its +member budget, an unconvertible const), which is unrelated to every type, and so does an alias of +`{}` that says nothing of its values: as a field's own type it may hold the docs, deprecation and +redaction a reference carries down to the field +([annotations](../ir/annotations.md#what-a-reference-carries-down)), and anywhere else nothing but +where it was declared. Two such types lose to neither: what else each says decides, so an alias of +one is narrower than the other it names, and two aliases neither naming the other are not compared. +The merged field admits null only where both declarations' uses do, so a null an alias's `Base` +admits never makes two declarations overlap where one use admits none: +`{type: string, nullable: true, format: email}` beside `{type: string}` is the email `Scalar`, its +`Base` admitting its schema's null, named by a use admitting none. Where `{}` loses, the chosen +type's own null admission holds alone, since `{}` admits null yet lowers non-nullable. Two bare +primitives compare by value domain and spelling (`integer` against `number`, `uuid` against +`string`, `int32` against `int64`). A `Scalar` or `Enum` against a bare primitive wins over a kind +it equals or narrows (`string` against `format: byte`, or an unknown format over bare `string`), is +disjoint from a kind of another family, or from another string format where neither is `bytes` +(`uuid` against `format: date`), and overlaps any other kind (`uuid` against `format: byte`); for an +`Enum`, that overlap is disjoint where the kind's judge refuses every member, an enum behind an +alias, as a member written beside a bound is, judged by the members of the enum it names, which the +alias can only narrow. A `Scalar`'s kind is that of the values it travels as: its base's, but for a +base its `Encoding`'s `WireType` does not spell, whose values travel as that type, so +`format: unixtime` on an `integer` is narrower than `integer`, overlaps `int64` and is disjoint from +`string`, while `byte` stays `bytes`, which a `string` spells. A string format whose text an +`Encoding` names otherwise, as `http-date` and `contentEncoding` do, has no judge, as `bytes` has +none, since the format's own grammar reads another text: an enum of HTTP-dates beside +`format: http-date` overlaps it. A `Scalar` hoisted for `time`, whose grammar, RFC 3339's +`full-time`, the compiler holds though the table pairs it with no kind +([`string-formats`](#string-formats)), is read wherever a kind is, through an alias too, as a string +format of its own: within `string`, an overlap with `bytes`, and disjoint from every other kind, +`time-local` and `date-time` among them, and from an `Enum` none of whose members it admits. An enum +with no members is refused vacuously, so it is disjoint from any kind it would otherwise overlap, +`bytes` included; an enum with members against `bytes` stays an overlap. A `const`, or an alias of +one, wins when the kind admits its value; where it does not, it is disjoint from a kind with a judge +and overlaps `bytes`, which has none. Against a `Scalar` hoisted for `time`, a `const` is disjoint +where the node refuses its value, and wins where the node admits it and says nothing but its base, +the format and bounds, so a field typed by the `const` loses none of it. Where the node also says +what a `const` can hold beside its value, a description or a deprecation, the two combine in a +`const` holding that too (below); a node giving examples overlaps it, since nothing shows the +`const` admits them. Two enums, two `const`s or two `Scalar`s equal in every field but where they +were declared (IDs, names, whether hoisted inline, and the provenance of the node and of what it +keeps under `Unmodeled`) are one type where both were written inline at the field's own +declarations, in their document, as the same declaration written twice; a node declared elsewhere, a +component or a schema a `$ref` reaches in this document or another, wins over an inline copy of +itself in either order, and two such nodes, declared apart, are one type too: the field names the +one written first, as below, or the one refusing null where the other admits it, and a declaration +the model holds naming the other, at the field or at a part of it, is kept verbatim beside the field +under its pointer below the schema holding every declaration, with an `openapi/degraded-construct` +info, as one position keeps each `$ref` of its `allOf` it does not name. Two nodes are one type, or +one gives way to the other, only where what the two keep under `Unmodeled` writes no relative +`$ref`, or the two admit exactly the same values, each read in its own document and dialect: on the +nodes they lowered to, their bounds, encodings, members and value sets, the text they keep verbatim +read as written whatever names it spells, and on what each `$ref` they keep lands on, alike where +both read it against one base. Under an `$id` naming another URI, or in another document, a `$ref` +spelled alike may name another schema; where it names one admitting otherwise, or that cannot be +shown, nothing shows the two admit the same values, and they overlap. So is one Unmodeled entry kept +under a key two declarations give alike: two `not`s writing one `$ref`, in a 3.0 and a 3.1 document, +keep one Unmodeled entry where the two schemas it names admit alike, and two where they differ in a +bound. An alias adding nothing to what it names, no bound, encoding, member, value or kept text, nor +null, is read as its chain's end, and one adding something by what it is in full; two nodes no other +rule relates are copies, by the rule above, where they admit alike so read: a model, an alias of it +adding nothing and an inline copy of it are one type, the alias, in every order the three are +written. Admitting alike, two copies may document apart. Where the type the field takes, or the part +of its composition holding a copy, does not give each title, description, external link and +deprecation that copy's nodes give, at the same place, or, for one an alias on its chain says, +anywhere on the chain, that declaration is kept verbatim, as a losing one is (below), with an info +`openapi/degraded-construct` at it naming the type kept, and the docs or deprecation of a type it +holds that it gives apart, which that one info says, the intersection of the field's type then +reporting none of its own there; one giving nothing the kept type lacks is dropped unreported. Docs +written on the declaration itself, as beside a `$ref`, fold by the field's own rule (below). Two +`const`s of different values share none, so they are disjoint. Two enums of one closedness, bit-flag +reading and fallback, whose members holding one value say the same of it, are judged by the values +they hold: sharing none, they are disjoint, whatever their value types. Of two value types one +within the other, the narrower says more (`integer` against `number`), so one whose values the other +holds every one of, of the same value type or the narrower, is narrower where it also says all the +other does beside its members, and otherwise the two combine, as do two each holding a value the +other lacks, in an enum of the values they share, of the narrower value type (below), where both +list those values in one order. Two listing them in different orders overlap, since an enum of both +would take its order from one declaration. Two holding one set of values of one value type, or in +another order, or saying the rest differently, two of value types neither within the other (`int32` +against `uint32`), and any other pair of enums, are judged by their kind. Two models alike in every +member but where they and what they name were declared (the same properties in the same order, each +with the same wire name, required flag, visibility, docs, constraints, values and kept text, and the +same catch-all, composition and discriminator, its tag read by position) are judged the same way +where every type they name relates to the other's as the same type, or as that rule relates the two +models: a component wins over an inline copy of itself, a nested object included, in either order, +and two inline copies are one type. A property keeping a relative `$ref` makes them one only where +they admit alike, as above. Two components alike are one type, as above, and models alike in all but +a type that relates otherwise are no copies, so they compose as two models do (below). One judgment +compares at most 64 pairs of models member by member, since a `$ref` to a sibling position adds +width at no cost in document size; past that the two are unrelated and compose, which loses nothing. +An alias is narrower than the type it names, whatever its kind: a reference to it reads all that +type says, and it may say more. One whose chain admits null, as `{anyOf: [E, {type: null}]}` does, +is not, since `E` refuses null: where the chain adds nothing else, docs included, `E` is narrower +and the field holds it, and otherwise the two are judged as below. Against any other type, an alias +whose chain ends in an enum, a `const`, a `Scalar`, a list, a map or a tuple is judged, and a node +it combines into built, as that node holding the bounds the chain and the node say together and each +detail the nearest of them sets, documentation field by field, as a reference to the alias reads it ([annotations](../ir/annotations.md#what-a-reference-carries-down)). So `{$ref: E, description: d}` -and an `allOf` of `E` alone each meet an enum beside them as `E` would, holding what they add, and -a title over an alias holding a description keeps both. Two aliases of one node are read only down -to it, so they are judged as two `Scalar`s of one base are, and meet in an alias of it. A chain -giving an encoding, bounds no one value states, bounds that a value an enum or a `const` lists fails -or that nothing here judges, such as a `pattern` on one, any bound on an open enum, which bounds the -values it does not list too, or keeping a relative `$ref` under `Unmodeled` is judged as it is +and an `allOf` of `E` alone each combine with an enum beside them as `E` would, holding what they +add, and a title over an alias holding a description keeps both. Two aliases of one node are read +only down to it, so they are judged as two `Scalar`s of one base are, and combine in an alias of it. +A chain giving an encoding, bounds no one value states, bounds that a value an enum or a `const` +lists fails or that nothing here judges, such as a `pattern` outside the subset the value admission +reader reads ([patterns](../ir/values.md#patterns)) on one, any bound on an open enum, which bounds +the values it does not list too, or keeping a relative `$ref` under `Unmodeled` is judged as it is written. Whatever the arm, a type admitting null through its alias chain is narrower than no type whose reference refuses null, since a field holding it would admit null all the same: the two -overlap. The top type, which loses before any arm, refuses no null whatever its reference says. -Two lists, two maps with one key, or two tuples of one length are judged by their parts: each -element, value or position, with what may follow a tuple's last, judged as a pair a level down, null +overlap. The top type, which loses before any arm, refuses no null whatever its reference says. Two +lists, two maps with one key, or two tuples of one length are judged by their parts: each element, +value or position, with what may follow a tuple's last, judged as a pair a level down, null included, nested up to a bound; their bounds, a keyword with no order (`pattern`) given two ways -meeting; and what else each says, read as two `Scalar`s are but where each was declared: encoding, +combining; and what else each says, read as two `Scalar`s are but where each was declared: encoding, documentation, examples, deprecation, XML hints and `Unmodeled`. Two `Scalar`s of one base and encoding are judged by their bounds and what else they say the same way. A node says all another does of a part where its member is the narrower or admits null no more widely, its bounds say all the other's do, or it sets every detail the other sets, alike. Two saying one set of values are judged as two equal enums are where they say the rest alike; where they do not, they are two types declared apart, which overlap, but for two `Scalar`s, then judged by their kind. Otherwise the one -saying all the other does in every part is narrower, and two each saying what the other lacks meet in -a node holding both (below), unless they give one detail differently, or one gives examples the -other does not, since nothing shows that node admits them, which leaves them an overlap. Members that -meet, or that compose as two models or a model and a map or a union do (below), make their -containers meet, so lists of two models stand on a list of a model composing both. Disjoint members -still overlap where both admit null, or where both containers admit the empty one, and members -related otherwise leave their containers so. A tuple that a container or another tuple holds is not -compared, since a tuple has a member per position where any other node has one, and comparing them -nested would cost its width to the power of the depth. A structure is narrower than -one it says it is: a model than what it composes through `Base` or `Mixins`, read through aliases, -up to 64 types for one question. A model, a map or a -`const` object is narrower than a model saying nothing but `type: object`, and two such models are -judged as two equal enums are. That model says nothing at all but where it was declared, and an -alias of it is not one, since an alias may say more: a type composing another still reaches it, -while one narrowing a bare object does not, so a title or an example there would be lost. Any other -pair is judged by what the two types hold, an alias as the -type it stands for and a `const` object or array as a structure of that instance type: disjoint -where their kinds share no value, or a value type meets a structure, or two structures of different -instance types meet; an overlap where their kinds share values or a `const` meets a type that ends -in a kind, but for the `time` node above, or a `const` of its value; and unrelated where nothing says -what they share, as between two +saying all the other does in every part is narrower, and two each saying what the other lacks +combine in a node holding both (below), unless they give one detail differently, or one gives +examples the other does not, since nothing shows that node admits them, which leaves them an +overlap. Members that combine, or that compose as two models or a model and a map or a union do +(below), make their containers combine, so lists of two models combine in a list of a model +composing both. Disjoint members still overlap where both admit null, or where both containers admit +the empty one, and members related otherwise leave their containers so. A tuple that a container or +another tuple holds is not compared, since a tuple has a member per position where any other node +has one, and comparing them nested would cost its width to the power of the depth. A structure is +narrower than one it says it is: a model than what it composes through `Base` or `Mixins`, read +through aliases, up to 64 types for one question. A model, a map or a `const` object is narrower +than a model saying nothing but `type: object`, and two such models are judged as two equal enums +are. That model says nothing at all but where it was declared, and an alias of it is not one, since +an alias may say more: a type composing another still reaches it, while one narrowing a bare object +does not, so a title or an example there would be lost. Any other pair is judged by what the two +types hold, an alias as the type it names and a `const` object or array as a structure of that +instance type: disjoint where their kinds share no value, or a value type and a structure hold +together, or two structures of different instance types hold together; an overlap where their kinds +share values or a `const` and a type that ends in a kind hold together, but for the `time` node +above, or a `const` of its value; and unrelated where nothing says what they share, as between two models neither of which composes the other, a model and a map, a list and a tuple, an opaque scalar and a kind, a union and a type neither holds, or an external and anything else. A type within a -variant of an untagged union is narrower than the union, as is a closed untagged union every -variant of which is within a type than that type, since an open one admits a variant it does not -list; of a `oneOf`, the type must be within one variant alone and disjoint from every other, since -a `oneOf` refuses a value two variants share. A tagged union holds neither: a discriminator routes -by a tag a variant's values need not agree with. Nor is a type within a union holding bounds of its -own, or reached through an alias that holds some, since each bounds the values of its kind -whichever variant holds them, which the variants do not say. One judgment reads at most 64 -variants, past which the two are unrelated. A structure whose source admits every instance of the -other's kind is the exception to the disjoint pairs, as `properties` alone constrains objects and -admits a string, and `{allOf: [{$ref: Obj}], properties: …}` over `Obj: {properties: …}` admits -every integer: what it admits is read as -[`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) reads a conjunct, through its `type`, its -`enum` and `const`, its `allOf`, `oneOf` and `anyOf`, the keywords beside a `$ref` and what each -`$ref` lands on, and for a variant of a union, a distributed one among them, what the schema writing -the union admits too, and each schema holding that one in turn as an `allOf` entry or a union -branch, up to the first that is neither: a union written in an `allOf` entry of `{type: object}` -admits no array, however deep the entry. A schema read as an `allOf` entry and no union's branch is -read alone. It admits a kind whole only where no keyword it takes in refuses some instance -of that kind while admitting others: a value set, a numeric or a string bound, a `format`, and a -keyword applying to arrays or to objects alone, `items` or `required` among them, each admit their -kinds in part, but for one whose schemas, applied to the instance's parts, each state nothing, as -`items: {}` and `additionalProperties: true` do; and a union admits a kind whole where a branch does -and, for a `oneOf`, which refuses what two branches admit, no other branch admits it. So +variant of an untagged union is narrower than the union, as is a closed untagged union every variant +of which is within a type than that type, since an open one admits a variant it does not list; of a +`oneOf`, the type must be within one variant alone and disjoint from every other, since a `oneOf` +refuses a value two variants share. A tagged union holds neither: a discriminator routes by a tag a +variant's values need not agree with. Nor is a type within a union holding a bound of its own kind, +or reached through an alias that holds one, since each bounds the values of its kind whichever +variant holds them, which the variants do not say; a bound of another kind, as `maxLength` is beside +`integer`, says nothing of the type's values. One judgment reads at most 64 variants, past which the +two are unrelated. A structure whose source admits every instance of the other's kind is the +exception to the disjoint pairs, as `properties` alone constrains objects and admits a string, and +`{allOf: [{$ref: Obj}], properties: …}` over `Obj: {properties: …}` admits every integer: what it +admits is read as [`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) reads a conjunct, through +its `type`, its `enum` and `const`, its `allOf`, `oneOf` and `anyOf`, the keywords beside a `$ref` +and what each `$ref` lands on, and for a variant of a union, a distributed one among them, what the +schema writing the union admits too, and each schema holding that one in turn as an `allOf` entry or +a union branch, up to the first that is neither: a union written in an `allOf` entry of +`{type: object}` admits no array, however deep the entry. A schema read as an `allOf` entry and no +union's branch is read alone. It admits a kind whole only where no keyword it takes in refuses some +instance of that kind while admitting others: a value set, a numeric or a string bound, a `format`, +and a keyword applying to arrays or to objects alone, `items` or `required` among them, each admit +their kinds in part, but for one whose schemas, applied to the instance's parts, each state nothing, +as `items: {}` and `additionalProperties: true` do; and a union admits a kind whole where a branch +does and, for a `oneOf`, which refuses what two branches admit, no other branch admits it. So `{minimum: 5}` and `{format: int32}` each admit some integers and not every one, and a structure -composing one of them, as `{allOf: [{minimum: 5}], properties: …}` does, is judged against -`integer` as a structure stating its type is; an `allOf` entry stating a value set, or naming a -union of an object and another kind, makes no structure but a refinement +composing one of them, as `{allOf: [{minimum: 5}], properties: …}` does, is judged against `integer` +as a structure stating its type is; an `allOf` entry stating a value set, or naming a union of an +object and another kind, makes no structure but a refinement ([`allof-refinement`](#allof-refinement)). The conflict is reported and the declaration the field -does not keep is kept verbatim, since a field of either type alone would lose what the other says. -Where that read meets what it does not follow but which could refuse a value of some kind, a -`not`, an `if` or a `dependentSchemas` holding a schema, a `$dynamicRef` or a `$recursiveRef` the -bindings read as no `$ref`, a cycle of conjuncts or a `$ref` landing on no schema, the structure -reads as stating its type; a `not` or an `if` written `null` is the keyword left out -([`null-schema`](#null-schema)) and refuses nothing. A value type or a structure of another instance -type is narrower than it, in either order, where it and each alias -naming it hold no more than an alias of `{}` may to be read as `{}`, and overlaps it otherwise, -since a type replacing it would lose what it holds. So a structure written at the declaration -itself, which keeps its docs, deprecation and redaction on its own node, overlaps a value type or a -structure of another instance type where it holds any of them; one a `$ref` reached carries them -down to the field. Two such structures of different instance types overlap, sharing every value of -a third. The source is read in the document holding the composing model, so a structure another -document declares reads as stating its type. A pair gets the same verdict as a field's types and as two containers' members, -but for tuples, above. - -The field takes the type of the declaration whose type is the same as, narrower than, or meets the -most declarations' types. Of those holding as many, the later wins, where a spec writes the +does not take is kept verbatim, since a field of either type alone would lose what the other says. +Where that read meets what it does not follow but which could refuse a value of some kind, a `not` +holding a schema saying more than a type, an `if` whose `then` or `else` the read does not follow, a +`dependentSchemas` holding a schema, a `$dynamicRef` or a `$recursiveRef` the bindings read as no +`$ref`, a cycle of conjuncts or a `$ref` landing on no schema, the structure reads as stating its +type; a `not` of a schema stating only a type refuses that type's instances alone, and a `not` or an +`if` written `null` is the keyword left out ([`null-schema`](#null-schema)) and refuses nothing. An +`if` is read per kind by that same read of its `if` schema and of its `then` and `else`, each +read as any schema is, one left out admitting every kind: a kind whose every instance the `if` +admits is subject to its `then` alone, as that branch admits it, whole or in part, a kind it admits +no instance of to its `else` alone, so, and any other kind to either branch, admitted only in part. +A keyword narrowing within a kind removes none: `{if: {type: string}, then: {maxLength: 2}}` admits +every kind, strings in part, and a branch the read does not settle, one leading back to the schema +writing it, is not followed. So +`{if: {minimum: 0}, then: false, else: {type: string}}` admits nothing, no number subject to either +branch and every other instance to the `then` alone, and +`{if: {required: [k]}, then: {type: object}, else: {type: integer}}` admits no integer, as +`required` holds for every instance that is no object, and +`{if: {minimum: 3}, then: {type: object}, else: {type: integer}}` some integers. An `if` schema the +read does not settle, one leading back to the schema writing it or one written down an `allOf` entry +whose dynamic reference is read unexpanded beside another conjunct, is read as admitting some +instances of each kind, so each kind is subject to either branch. An alias whose chain ends at the +top type yet says something of its values, as `{not: {type: string}}` lowers to, is judged against a +type ending in a kind by the same read of its source and of each alias below it: disjoint where one +admits no instance of the kind, as `{not: {type: integer}}` beside `integer` is, a conflict; the +other type narrower where each admits every instance and a type replacing the alias loses nothing it +says, what a node declared apart keeps verbatim staying where it is declared, as +`{not: {type: string}}` beside `integer` is; and an overlap otherwise. A value type or a structure +of another instance type is narrower than it, in either order, where it and each alias naming it +hold no more than an alias of `{}` may to be read as `{}`, and overlaps it otherwise, since a type +replacing it would lose what it holds. So a structure written at the declaration itself, which keeps +its docs, deprecation and redaction on its own node, overlaps a value type or a structure of another +instance type where it holds any of them; one a `$ref` reached carries them down to the field. Two +such structures of different instance types overlap, sharing every value of a third. The source is +read in the document holding the composing model, so a structure another document declares reads as +stating its type. A pair gets the same result as a field's types and as two containers' members, but +for tuples, above. + +The field takes the type of the declaration whose type is the same as, narrower than, or combines +with the most declarations' types. Of those holding as many, the later wins, where a spec writes the specialization, as the flattening reads it ([models](../ir/models.md#the-flattening)): a failure response composing a success envelope and then a failure schema takes the failure's `success`. Of -declarations of one type at distinct nodes, as copies of one schema are, the node whose ID sorts -first stands for the rest, so no order decides which the field names. A declaration's type within -every other's is the intersection, and it wins whatever the order. Each declaration whose type the -winner's is the same as or narrower than, or meets, folds into the field, which adopts its shape -detail; every other one is dropped. So `int32`, `uint32` and `uint16` fold to `uint16` with nothing -dropped, in every order, while `int32` and `uint32` alone keep the later declared and report the -other. - -Two nodes that meet say what no declared node says, since each adds what the other lacks. The field -takes a node the merge mints: all the winner's node holds, with what each declaration meeting it -adds. Its bounds fold as a property's do, below; each detail the winner leaves empty is taken as a -reference to that node would read it; an enum's values are cut to those every one holds, in the -order the winner lists them; and each member is built from theirs a level down, composed or meeting -theirs in turn, at a position of its own beneath the field's (`/items`, `/additionalProperties`, -`/prefixItems/`). That position is named beneath the declaration naming the field whether the -declaration writes the container or a `$ref` there reaches it, so it may be one the source does not -write; the member's own position would give one ID to two fields building different members of -it. A `const` meeting a -`Scalar` is the node, holding what the `Scalar` says beside its values. So `minItems: 1` beside -`maxItems: 5` is one list holding both, a described list of `integer` beside a list of `int32` one -list of `int32` holding the description, `[a, b]` beside `[b, c]` the enum `[b]`, and lists of two -models a list of a model composing both, each in either order. Every node it mints is anonymous, in -the `composed` namespace, an enum's members too, and derives from its position: the declaration -naming the field, as a composed model does below, or a position beneath it. Where two declarations -meeting the winner give one detail differently, the later's is kept and the earlier reported and -kept, as a property's detail is. Where no node holds every declaration meeting the winner, as when -three meet in pairs but no member holds all of theirs, or no value is in every enum, the field keeps -the winner's node, and each declaration meeting it is dropped and reported as an overlap. Where the -declarations leave the winner's node as it stands, because only a keyword with no order differs, the -field keeps that node and nothing is minted. +declarations of one type at distinct nodes, as copies of one schema are, the node written first is +taken for the rest: in the document listed first, then at the pointer that sorts first token by +token, an index read as a number, then by ID, so no order of the declarations decides which the +field names, and a declaration the model holds naming another of them, declared apart, is kept as +above whichever declaration won. A node's notes, its examples and a `readOnly` or `writeOnly` it +keeps say nothing of what it admits, and neither does a bound or a `format` it keeps verbatim that +applies to none of the other node's kinds, read by `typeformat.InstanceKindsKeywordAppliesTo` (a +numeric bound to numbers, a length or a `pattern` to strings, an item or property count to arrays or +objects, a `format` to the JSON types the format table lists it on, or every kind where it lists +none), as `minimum` kept beside `type: string` is. So two nodes differing in them alone are one +type, and neither gives way to the other as a copy does, since each keeps what the other lacks; a +copy only the model holds that says a note the node the field takes does not gives it to a node the +merge builds of the two, and one saying a note otherwise is reported and kept verbatim, as a meeting +reports a detail, but for one kept under `Unmodeled`, which the node holds as below. A `format` an +alias of the top type keeps, beside a bare kind it applies to and that the format table pairs it +with, combines with that kind at the format's primitive where the alias keeps nothing else applying +to it, no encoding and no bound: `{format: uuid}` beside `string` is `uuid`, in either order, +holding what else the alias says. A declaration's type within every other's is the intersection, and +it wins whatever the order. Each declaration whose type the chosen declaration's is the same as or +narrower than, or combines with, folds into the field, which adopts its shape detail; every other +one is dropped. So `int32`, `uint32` and `uint16` fold to `uint16` with nothing dropped, in every +order, while `int32` and `uint32` alone keep the later declared and report the other. + +Two nodes that combine say what no declared node says, since each adds what the other lacks. The +field takes a node the merge mints: all the chosen declaration's node holds, with what each +declaration combining with it adds. Its bounds fold as a property's do, below; each detail the +chosen declaration leaves empty is taken as a reference to that node would read it; an enum's values +are cut to those every one holds, in the order the chosen declaration lists them; and each member is +built from theirs a level down, composed or combined with theirs in turn, at a position of its own +beneath the field's (`/items`, `/additionalProperties`, `/prefixItems/`). That position is named +beneath the declaration naming the field whether the declaration writes the container or a `$ref` +there reaches it, so it may be one the source does not write; the member's own position would give +one ID to two fields building different members of it. A `const` combining with a `Scalar` is the +node, holding what the `Scalar` says beside its values. So `minItems: 1` beside `maxItems: 5` is one +list holding both, a described list of `integer` beside a list of `int32` one list of `int32` +holding the description, `[a, b]` beside `[b, c]` the enum `[b]`, and lists of two models a list of +a model composing both, each in either order. Every node it mints is anonymous, in the `composed` +namespace, an enum's members too, and derives from its position: the declaration naming the field, +as a composed model does below, or a position beneath it. Where two declarations combining with the +chosen one give one detail differently, the later's is taken and the earlier reported and kept, as a +property's detail is, but for what they keep verbatim under `Unmodeled`, which the node holds as one +position holds what its `allOf`'s entries keep ([`allof-inline-residue`](#allof-inline-residue)): a +key every node keeping it keeps alike once, as the first written keeps it, under that entry's reason +and with no report of its own, the declaration's own lowering having reported it; and a keyword they +keep apart under one key per declaration the model holds alone, the declaration's pointer below the +schema holding every declaration, holding an object of each keyword that declaration keeps apart, +under `degraded_lowering`, with one info `openapi/degraded-construct` at the declaration. So +`{type: string, minimum: 1}` beside `{type: string, minimum: 2}`, which admit every string alike, is +a `string` alias minted at the fold's key keeping `openapi:allOf/0/properties/p: {minimum: 1}` and +`openapi:allOf/1/properties/p: {minimum: 2}`, in either order. A `minLength` or `maxLength` kept +verbatim on a node of a text kind, as a text bound over a text of another kind is, is read by its +keyword as a bound, as the fold's held reader reads it: two nodes keeping one length at counts apart +each say what the other lacks, so they combine in such a node, which keeps the narrowest, the least +`maxLength` or the greatest `minLength`, under its own key, as the first written giving it keeps it, +and each other declaration's under its key as above, in either order. So a looser length kept +verbatim stays in the document, where a looser bound the IR types is owed nothing. One another model +brings keeps its own on its node there, and the enum of no member below, which keeps each +declaration whole under that key, keeps only the keys kept alike. Where no node holds every +declaration combining with the chosen one, as when three combine in pairs but no member holds all of +theirs, or no value is in every enum, the field keeps the chosen declaration's node, and each +declaration combining with it is dropped and reported as an overlap. Where the declarations leave +the chosen declaration's node as it is, because only a keyword with no order differs, the field +keeps that node and nothing is minted. Two models neither of which holds the other are the exception, and so are a model and a map or a union, since an instance satisfying both is a value of a type neither names. Where the declarations @@ -3255,15 +3755,16 @@ or through an alias, and one of them a model, the field's type is a `Model` the anonymous, holding no property of its own, and composing each of those types once as a written `allOf` of them composes ([`allof-classification`](#allof-classification)). The one written as the only `$ref`, or else the first `$ref` whose type takes part in a discriminator hierarchy, is its -`Base`, and the rest are `Mixins` in declaration order. The fold reads the hierarchy off the types: -a `Model` or a `Union` holding a discriminator its source declares, or a `Model` one of whose -supertypes does, at any depth. So a field declared as `Meeting` and as an inline object +`Base`, and the rest are `Mixins` in declaration order. The fold reads the hierarchy off the source +as a written `allOf` does: the declaration writes a `$ref` whose run ends on a schema declaring a +discriminator or composing, at any depth, one that does, read in the declaration's own document. +Two models composing one set of parts are copies whatever order they list their `Mixins` in. So a field declared as `Meeting` and as an inline object names one type holding both, whichever entry comes first, rather than flattening them into one property list. Whatever another declaration's type holds adds no conjunct: a `{}` or an alias of it read as one, a model saying nothing but `type: object` beside one saying more, and a model another declaration composes. Two -models saying nothing, declared apart, are two types neither of which holds the other, so they -compose, and an object saying anything else composes too, so what it says stays reachable. Two +models saying nothing, declared apart, are one type, as two components alike are, and an object +saying anything else composes, so what it says stays reachable. Two aliases of one model are two types, each able to say more than the model, so they compose, and so does an alias of a bare object beside another model. Any other type beside them (a kind, a list, a degraded node, an alias of `{}` saying something of its values), or maps and unions with no model @@ -3271,19 +3772,21 @@ among them, leaves the choice to the rule above. Every declaration then folds in field, so none is dropped for its type, and each conjunct keeps the node its own pointer denotes. The minted model's ID is in the `composed` namespace ([identity](../ir/identity.md#the-id-grammar), [models](../ir/models.md#composition-beside-a-union)), so no `$ref` reaches it, and derives from the -declaration naming the field, which its provenance records: the last declaration to widen the schema -holding them all, so the first outside the entry holding the first declaration. A model and a -wrapper it flattens can share a first declaration or a last one while folding different -sets, and not this one. Folds of one set share the one node, as the variants of a distributed union -do. +fold's key, which its provenance records: `/allOf/properties/`, the schema the +narrowest holding every declaration, where no schema is written, since an `allOf` holds entries by +index. So the key is a function of the set of declarations, which no order moves, and a model and a +wrapper it flattens folding different sets hold them in different schemas. Folds of one set share +the one node, as the variants of a distributed union do. Every node a fold mints takes the field's +name as its hint, a node beneath it the field's with its position's suffix, and none reads a +declaration's `title`. A `$ref` to an `allOf` entry or wrapper makes a model carrying the declarations under it and not -the others, so one declaration can stand on two models whose fields differ. Where a node stands at a +the others, so one declaration can belong to two models whose fields differ. Where a node lies at a schema inside the one holding every declaration that holds the first, the field is a different property from that node's: it takes a `PropertyID` in the `composed` namespace, derived from the -declaration naming it, and its provenance points at that declaration, and the model's discriminator -follows it. -Every other fold keeps the first declaration's identity, which the walk has already handed out. +fold's key, and its provenance points at that key, and the model's discriminator follows it. Every +other fold keeps the identity of the declaration its pointer chooses, which the walk has already +handed out. The relation between kinds is stated over JSON instances, so that a narrowing, which is adopted silently, holds in every reading. Its value-domain half is `PrimitiveKind.StrictlyWithin` @@ -3299,50 +3802,64 @@ A narrower type wins in either order, the intersection being that type, and is n field admits null only where every declaration folded into it does, and a null any of them writes is judged against that: a `default: null` or a null example is refused where the merged field does not admit null, a declaration of the field's own type included. The top type admits null whatever its -bit says, and one folded under another type says nothing of null. A `default` or `examples` a -broader declaration gives is taken only where the winning type admits it, judged per keyword and all -or nothing. The winning type admits a value by its kind, by the `full-time` grammar where it is a -`Scalar` hoisted for `time`, and by the constraints its node carries: -each bound, `multipleOf`, a length counted in code points, an item or property count and -`uniqueItems`, while a `pattern`, which nothing here evaluates, admits no string. Every -declaration's value is held by the same checks to each bound the field keeps that another -declaration brought, on the property or on a node. A value is its declaration's own to answer for -against a bound it states itself at the value the field keeps, so a default its own bound refuses -stays, and against its own type where that is the field's but for bounds; a node the merge builds -can hold members or values the declaration's own does not, so a value written beside it is judged -against that node. Nothing -judges a value against a model, and no declaration's type is a composed field's own, so a composed -field takes no value but a null it admits. A value the field does not take is reported in an info +bit says, and one folded under another type says nothing of null. A declaration admitting null +alone is within one the value admission reader (`ir.ValueAdmissionReader`) says admits null, +disjoint from one it says does not, and unrelated where it cannot tell; two value sets sharing no +member but null intersect at null alone, the closed `Enum` of no member at the fold's key behind a +nullable reference, which keeps each set a declaration the model holds alone gives verbatim under +the key its pointer below that schema names, with an info `openapi/degraded-construct` each. A +`default` or `examples` a declaration gives is refused only where something shows the field does not +admit it, judged per keyword and all or nothing: the run's value admission reader judges it against +the field's type, a union by its variants, a model by its composition, a kind by its grammar, the +`full-time` grammar where a `Scalar` is hoisted for `time`, and the constraints a node carries, each +bound, `multipleOf`, a length counted in code points, an item or property count, `uniqueItems` and a +`pattern` in the subset the reader reads ([patterns](../ir/values.md#patterns)), while what it +cannot read, a `pattern` outside that subset or a step past the digits it reads, leaves the value +unknown, and unknown refuses nothing. A keyword another declaration keeps verbatim with no IR home +is read by its keyword. Every declaration's value is held by the same checks to each bound the field +keeps that another declaration brought, on the property or on a node, and to the bounds its own +declaration states on the property, which bind it as the same bounds on its type's node do: +`{$ref: T, minLength: 8}` refuses a shorter default as a `T` holding `minLength: 8` does, whether an +`allOf` entry or a part's member writes it, whichever type the field keeps, its own or one narrower. +A node the merge builds can hold members or values the declaration's own does not, so a value +written beside it is judged against that node, and a composed field refuses a value one model it +composes refuses. A value the field does not take is reported in an info `openapi/degraded-construct` at each declaration that wrote it, which is kept verbatim beside the field. Of the values it takes, the -last written is kept, and a declaration giving another is reported and kept; two values are one +last written is chosen, and a declaration giving another is reported and kept; two values are one where they are one JSON value, a number by its magnitude and an object by its members in any order. -Values are refused before one is kept, so a value the field takes is never lost to a refused one +Values are refused before one is chosen, so a value the field takes is never lost to a refused one written after it. Constraint keywords fold over the declarations folded into the field, each taking the value that says what they all do, so no order decides it. A declaration's are those its property holds and, where the fold composes the field's model, those of the node it owns, which its property leaves to -that node ([`constraints`](#constraints)): the composed model stands at no position of its own and +that node ([`constraints`](#constraints)): the composed model lies at no position of its own and holds none, so the field holds them. Where the field's type is one declaration's node, or one the merge builds holding the bounds the nodes say together, the bounds stay on that node. `minimum`, `exclusiveMinimum`, `minLength`, `minItems` and `minProperties` take their largest value and `maximum`, `exclusiveMaximum`, `maxLength`, `maxItems` and `maxProperties` their smallest, by magnitude, a number written two ways -keeping the last spelling; `uniqueItems` holds where any declaration sets it. A bound and its +keeping the spelling of the declaration written first; `uniqueItems` holds where any declaration +sets it. A bound and its exclusive form are two keywords, each folding alone, and both apply. `multipleOf` takes whichever value is a multiple of the other, and otherwise their least common multiple, a number no declaration wrote, whose multiples are exactly those both admit. `pattern`, `patternMessage`, `precision` and `scale` have no order and no one value saying two of them, so the last declaration -to set one keeps it, as does `multipleOf` for two steps past 1,024 significant digits between them -or a multiple past what a `BigVal` holds. The title, description, external links, deprecation, XML +to set one keeps it, as does `multipleOf` for two steps, but for one number spelled two ways, which +is one step whatever its length, where either's numerator in lowest terms, or their common +multiple's, passes 1,024 digits, or where a step's digits carry a power of two or of five past the +4,096th beside that numerator, as `5^5000e-5000` does: bounds every step an intersection folds in +and the intersection itself, so steps intersect alike in every grouping, and a step past them is +refused before its arithmetic is read. The title, description, external links, deprecation, XML hints and each `Unmodeled` key fold over every declaration, the last to give one keeping it, and a declaration giving one differently is reported and kept; of two keeping one `Unmodeled` entry alike, -the one written first is the field's, in the document listed first and then at the pointer sorting -first, since two files each holding one schema write the same pointers. An entry two declarations -write alike is one where it writes no relative `$ref`, or both read it against one base: under an -`$id` naming another URI, a `$ref` spelled alike names another schema. +the one written first is the field's, in the document listed first and then at the pointer written +first, compared token by token with an array index read as its number, so `allOf/9` comes before +`allOf/10`, since two files each holding one schema write the same pointers. An entry two +declarations write alike is one where it writes no relative `$ref`, or both read it against one +base: under an `$id` naming another URI, a `$ref` spelled alike names another schema. -A field keeping the first declaration's identity keeps that declaration's pointer, and either way it +A field keeping a declaration's identity keeps that declaration's pointer, and either way it names the heuristic that promoted its deprecation or its redaction from an extension, wherever the one it keeps came from, and no other. So a field names one source. `Provenance` holds one pointer, and what a folded declaration adds lands on the field with no record of which wrote it, so writing a keyword on @@ -3372,44 +3889,58 @@ Preservation is owed wherever something is dropped, which is wider than the disa warning, and nothing is owed for what the field implies. A broader type and a looser bound say no more than the field does, and a release changing either changes no value the field admits, so neither is kept or reported. Each diagnostic sits at the declaration that lost and names the one -whose say the field kept. A dropped declaration is reported against the winner as an -`openapi/conflicting-redeclaration` -warning where their types are incompatible — disjoint kinds (`string` against `integer`, `uuid` -against `date-time`, `time` against `time-local`), an enum none of whose members the other kind -admits, two `const`s of different values, two enums sharing no value, a scalar against a -structure stating its instance type or admitting the scalar's kind only in part, two structures of different instance types each stating -theirs, or two lists or maps whose members share no -value where one is never empty. Types that share values but that the merge does not narrow to one -(`int32` against `uint32`, an enum of `integer` against an `int32` that admits one of its members, -a `const` against a kind with no judge, against a node that ends in a kind, but for the `time` node -above, or against a `const` of its value saying more, two `Scalar`s of different encodings, such as -`format: hex` against `format: byte`, which no one node holds, two nodes saying one set of values -differently, two enums listing the values they share in different orders, two enums of value types -neither within the other sharing a value, two nodes giving one -detail differently or examples only one gives, or two lists or maps whose members share only null +whose say the field took. A dropped declaration is reported against the chosen declaration as an +`openapi/conflicting-redeclaration` warning where their types are incompatible — disjoint kinds +(`string` against `integer`, `uuid` against `date-time`, `time` against `time-local`), an enum none +of whose members the other kind admits, two `const`s of different values, a `const` against a node +ending in a kind that the value admission reader says refuses its value, two enums sharing no value, +a scalar against a structure or an alias of the top type admitting none of the scalar's kind, as one +stating its instance type does or `{if: {minimum: 0}, then: false, else: {type: string}}` beside +`integer`, two structures of different instance types each stating theirs, or two lists or maps +whose members share no value where one is never empty. Types that share values but that the merge +does not narrow to one (`int32` against `uint32`, an enum of `integer` against an `int32` that +admits one of its members, a `const` against a node that ends in a kind admitting its value, but for +the `time` node above, or against a `const` of its value saying more, two `Scalar`s of different +encodings, such as `format: hex` against `format: byte`, which no one node holds, two nodes saying +one set of values differently, two enums listing the values they share in different orders, two +enums of value types neither within the other sharing a value, two nodes giving one +detail differently or examples only one gives, a structure or an alias of the top type admitting +some instances of a kind beside that kind's bare primitive, `string`, `integer`, `number` or +`boolean`, which holds every one, or two lists or maps whose members share only null or share nothing while both admit the empty one) are named in an info `openapi/degraded-construct`, -and so are two types the judgment does not compare (a list and a tuple, a map or a union with no +and so are two types the merge cannot show to share a value or to share none, saying only that (a +`const` against a kind with no judge or a node whose value the value admission reader cannot judge, +a structure or an alias of the top type whose source the read does not follow, or that admits some +instances of a kind beside a type narrower than that kind, as `int32` or an `email` node, two nodes +each saying of its values what the other lacks where no one node holds both, as two patterns, or two +nodes alike but for references not shown to land alike), lowered as an overlap, and two types the judgment does not compare (a list and a tuple, a map or a union with no model to compose with, an opaque scalar, a node a degraded lowering minted, or models beside a type -that keeps them from composing), since which of them the field keeps then follows declaration -order. No declaration is dropped without a -diagnostic. A dropped declaration's `default`, constraints and examples go with -its type rather than folding onto the winner — they describe the shape that lost, and adopting them +that keeps them from composing), since which of them the field takes then follows declaration order. +No declaration is dropped without a diagnostic. A dropped declaration's `default`, constraints and +examples go with its type rather than folding onto the chosen declaration, and so does each entry +its property keeps verbatim under `Unmodeled` for want of a home on its type, as `properties` beside +an `allOf` lowered to a use of one of its entries is, which the declaration kept verbatim holds; one +saying something of the field, a note, a use-bound keyword or an extension, folds as its docs do. +They describe the shape that lost, and adopting them would leave one field asserting two contradictory things, with nothing downstream comparing a value's kind to its property's type; this is keyed on the type being dropped, not on the drop being called a conflict. A declaration folded into the field is reported as well where no one value says what it and the field say of a constraint keyword, an `openapi/conflicting-redeclaration` warning -naming the declaration the value was kept from, or where it gives a detail differently from the one -kept, an info `openapi/degraded-construct`; differing only in nullability, it takes no entry: the -merged -field admits null only where every folded declaration does, which is the conjunction a single -schema's null verdicts fold under ([`nullable`](#nullable)). +naming the declaration the value was taken from, or where it gives a detail differently from the one +taken, an info `openapi/degraded-construct`; differing only in nullability, it takes no entry: the +merged field admits null only where every folded declaration does, which is the conjunction a single +schema's null answers fold under ([`nullable`](#nullable)). The fold waits for every type to lower because the judgment reads the nodes the declarations name, a component declared after the schema composing it or a node a `$ref` into another document promises among them; it finishes the model before any other decision reads it (`compile.Types.QueueSettlementBeforeDeferredOnes`), so a form part's flags read the merged field. A -fold judges every pair of declarations, so it judges a field's first 64 at most; each later one is -kept verbatim, unjudged, under an `openapi/budget-exceeded` error at the first of them. +fold judges every pair of declarations, so it judges 64 of a field's declarations at most, the first +64 written, in the document listed first and then at the pointer written first, as above, whatever +the order of the entries; each written after them is kept verbatim, unjudged, under an +`openapi/budget-exceeded` error where the first of them is written, which remains where pruning +removes the member the fold decided. The ties among those judged still follow the order the walk +meets them in. A member a model's composition declares more than once folds the same way, wherever the declarations are written, so a `$ref` entry and the schema it names written inline in its place fold alike, but @@ -3421,59 +3952,84 @@ none. Once every lowering has returned, one settlement folds, on each model, eve declarations or its `allOf` entries decide more than once, asking the run's context before each model. Each entry brings the declaration the flattening of what it names takes, which a model settled first holds folded from every other its composition gives the member, and one another -entry's composition holds, however deep, stands within that entry's, so it brings nothing. A +entry's composition holds, however deep, lies within that entry's, so it brings nothing. A declaration an entry brings is judged where its type is written, as an inline one is: a member a part settled keeps its first declaration's identity whichever declaration gave its type, so the part records where the nodes of that type are written: at the declaration whose node the member keeps, -or, for a node the fold built, where it stands and at the declaration writing each node it holds, of +or, for a node the fold built, where it lies and at the declaration writing each node it holds, of which it reads 128 at most. A node written at none of them reads as a schema a `$ref` reached. A value a declaration gives is read against the field's type the same way, at each place the type's -nodes are written, which for a node the fold built is not the winning declaration's alone. Each +nodes are written, which for a node the fold built is not the chosen declaration's alone. Each model settles after every model it composes, however deep a hierarchy nests, so the order components -are declared in decides nothing, nor, off a cycle, their names. A cycle of compositions reads the -model it returns to as it stands, and the models' IDs pick which one that is, so where two -declarations on a cycle admit no value together, the names decide which its models keep, and the tie -is reported. -The declarations are read in the order the source writes them, a `$ref` entry's where the entry is -written and the schema's own `properties` after its `allOf`; a union branch distributed into a -variant reads before the body. A declaration an entry brings stays declared on its own model, so it -is not kept verbatim. A report names a declaration in a document other than the one it stands in -with that document's name, and one in its own by its pointer alone, a member a part settled by the -one place its type is written, or by its first declaration -where its type is written at several places or none, and one that would so be named where nothing is -written, as a member only a part's entries declare, by the entry bringing it. A report about a -declaration an entry brings sits at that entry, naming the member in its `Provenance.Node`, but for -an `openapi/conflicting-redeclaration`, which sits where it names the declaration that lost, in that -declaration's document: every model composing the two draws it alike, so the run reports it once, -saying how many models compose both and naming no member, or naming the member where one model -does. It lists what else it concerns ([provenance](../ir/provenance.md#related-places)): the place -of the declaration it kept, as its message names it, and then every member it decided, one model's -or each of several, in ascending order of their IDs, a conflict among a model's own declarations -included. A consumer counting the warnings counts one per pair of declarations, member and outcome, two -models keeping opposite declarations of one pair reporting one each, where it counted one per model -composing them, each at the entry bringing the declaration that lost. A member the model declares -itself keeps the identity of the first of its own declarations, unless another model holds that -declaration too, as a node interned at the `allOf` entry writing it does, or as the variants of a -distributed union share their body's; that one, and one only entries declare, the model declares in -the `composed` namespace at `/allOf/properties/`, where no schema is written, so it, -and a node its fold mints, name an overlay that wrote every entry and declaration it is assembled -from. A model the merge composes, a distributed variant or a field's composition, shares its pointer -with the schema written there, which may settle a member of that name too, so it declares one an -`allOf` deeper, at `/allOf/allOf/properties/`, and no two models name one member. The -member is required where the model's `required` names it, which the name then leaves, and a -discriminator naming the model's own declaration, or by its name a member only entries declare, -names the member ([`discriminator`](#discriminator)). -The registry does not record which heuristic made a brought declaration secret, so a secret one's -`Provenance.Inferred` marker comes with its redaction, as a deprecation's does. A model the fold -composes for a member lists its parts as the entries bringing them are written, and settles in turn, -through 8 rounds; one nested deeper is left as its entries declare it, with an -`openapi/budget-exceeded` error. What a model's parts bring is read only for the names more than one -model declares, so a hierarchy costs its depth again at each level only where every level adds such -a name, or composes a model redeclaring one it holds, which telling whether that declaration stands -within the hierarchy reads to its base. A run reads at most 16,777,216 of their declarations, a read -of a model not settled yet, as a cycle's are, counting each type and entry its flattening walks too, -as does telling whether one part's declaration stands within another's; past that each model left -folds its own declarations alone, with an `openapi/budget-exceeded` error at the first. Any +are declared in decides nothing, nor their names. The models of a cycle of compositions settle as one +unit: each name's declarations, every model's own and those parts outside the cycle bring, fold +together, every model taking the result at an identity of its own, and each report is said once, +deciding every model's member; a node the fold mints lies at `/allOf/properties/` for +the model of least ID. The declarations fold in one fold, as a model's own do, in the order they are +written, so the cycle keeps and reports what that fold keeps and reports: a declaration the field +combines with, as a number with an integer, is combined, whichever declarations are written between +them, and a ring of models redeclaring a member as objects gives every model one model composing +each declaration. Past the fold's bound of 64 the cycle is cut as a model's fold is: the 64 written +first are judged, the rest kept unjudged with the one `openapi/budget-exceeded` error at the first +of them. The declarations are read in the order the source writes them, a `$ref` entry's where the +entry is written and the schema's own `properties` after its `allOf`; a union branch distributed +into a variant reads before the rest. A declaration an entry brings stays declared on its own model, +so it is not kept verbatim. A report names a declaration in a document other than the one it lies in +with that document's name, and one in its own by its pointer alone. It opens with the field, then +names the declarations, the one whose say the field took first, and what becomes of the other, and a +type as an author wrote it: by the name its source gives it, a primitive by its kind, and any other +by its kind in words, `an object` or `a list`, never by an ID. The fold names no model in it, so +every model composing the declarations draws it alike, and the run names them as it says it once. A +report about a field sits at, and names, the place that writes the value it speaks of: where a +declaration is written, a `$ref` property at the property whatever its value comes through, and, for +a member a part settled, where the declaration it took that field from writes it, for a field it +took from one declaration, its title, description, external docs, default, examples, deprecation, +XML hints or a key kept under `Unmodeled`, the first written of those giving the value. A field +several declarations give together, its type, its bounds or its visibility, belongs to its type: a +report about it sits at the one place that type is written, or else where the member is written, or, +for one written nowhere, as a member only a part's entries declare, at the pointer of the model +whose composition settled it. Every report of the fold sits where it names the declaration it is +about, in that declaration's document, never at the entry bringing it, and names no node beside that +place (`Provenance.Node`). It lists what else it concerns +([provenance](../ir/provenance.md#related-places)). A report about two declarations lists first the +place of the one whose say the field took, as its message names it: of the declarations giving what +that one gives, the one written first, in the document listed first and then at the pointer written +first, as above, so no order of the entries decides which it names. Of a bound, what it gives is the +value every declaration agrees on, though one combined after the conflict moved it, and of a bound +several combined into a value none of them gives alone, as a common step of 6 from 2 and 3, the +place is the first written of those stating the keyword. No report names as chosen the declaration +it parts from. A refusal, about one declaration, lists none. Each then lists every member it +decided, one model's or each of several, in ascending order of their IDs, each at the source and +pointer of the model declaring it. Every model composing the declarations draws a report alike, so +the run says it once, after pruning +([`unreferenced-anonymous-types`](#unreferenced-anonymous-types)): a member pruning removed leaves +the list, a report left deciding none goes, since the document no longer holds what it decided, but +for an error, which stays, so pruning changes no compile's verdict, and reports alike but for the +members they decided are one, naming after the field each model holding it by its pointer, in the +order they are written, `field "x" of M1 and M2`. A consumer counting the warnings counts one per +pair of declarations, member and outcome, two models keeping opposite declarations of one pair +reporting one each. A member the model declares itself keeps the identity of the first of its own +declarations, unless another model holds that declaration too, as a node interned at the `allOf` +entry writing it does, or as the variants of a distributed union share the rest's; that one, and +one only entries declare, the model declares in the `composed` namespace at +`/allOf/properties/`, where no schema is written, so it, and a node its fold mints, +name an overlay that wrote every entry and declaration it is assembled from. A model the merge +composes, a distributed variant or a field's composition, shares its pointer with the schema written +there, which may settle a member of that name too, so it declares one an `allOf` deeper, at +`/allOf/allOf/properties/`, and no two models name one member. The member is required +where the model's `required` names it, which the name then leaves, and a discriminator naming the +model's own declaration, or by its name a member only entries declare, names the member +([`discriminator`](#discriminator)). The registry does not record which heuristic made a brought +declaration secret, so a secret one's `Provenance.Inferred` marker comes with its redaction, as a +deprecation's does. A model the fold composes for a member lists its parts as the entries bringing +them are written, and settles in turn, through 8 rounds; one nested deeper is left as its entries +declare it, with an `openapi/budget-exceeded` error. What a model's parts bring is read only for the +names more than one model declares, so a hierarchy costs its depth again at each level only where +every level adds such a name, or composes a model redeclaring one it holds. Whether that declaration +lies within the hierarchy is read off an index of the composition, built once a round, at any depth. +A run reads at most 16,777,216 of their declarations, a read of a model not settled yet, as one +composing itself is, counting each type and entry its flattening walks too; past that each model +left folds its own declarations alone, with an `openapi/budget-exceeded` error at the first. Any anonymous type node lowered for a declaration a fold superseded or replaced and left unreachable is removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenced-anonymous-types)). @@ -3481,7 +4037,11 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `allof-redeclared-bounds` - Codes: `openapi/conflicting-redeclaration`, `openapi/degraded-construct`, `openapi/budget-exceeded` - Tests: `merge.TestFold_NullabilityIntersectsWhenTargetsAgree`, - `merge.TestReportOnce_SaysEachConflictOnce`, + `schema.TestRefinement_AnIfBranchNarrowingWithinAKindRemovesNone`, + `schema.TestAllOf_ANullableRestrictionNarrowsAPlainRedeclaration`, + `merge.TestReportOnce_SaysEachFoldReportOnce`, + `merge.TestReportOnce_NamesEachModelOnceByItsPlace`, + `merge.TestTypeNamed_NamesATypeAsItsAuthorWroteIt`, `e2e.TestConflictOnce_IsReportedOncePerPairOfDeclarations`, `e2e.TestConflictOnce_AModelsOwnDeclarationsListTheMember`, `e2e.TestConflictOnce_InlineCompositionsAtOperationsAreOneReport`, @@ -3489,8 +4049,8 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `merge.TestFold_ALosingDetailIsKeptAndReported`, `merge.TestFold_TitleAndExternalDocsFoldLikeDescription`, `merge.TestFold_ANarrowingIntersectsNullability`, - `merge.TestFold_ADroppedTargetKeepsTheWinnersNullAdmission`, - `merge.TestFold_TheJudgmentsVerdictIsWhatIsReported`, + `merge.TestFold_ADroppedTargetKeepsTheChosenDeclarationsNullAdmission`, + `merge.TestFold_TheJudgmentsAnswerIsWhatIsReported`, `merge.TestFold_RedeclaredModelsCompose`, `merge.TestFold_OnlyTwoOrMoreModelsCompose`, `merge.TestFold_AComposedFieldIntersectsNull`, @@ -3498,18 +4058,17 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `merge.TestFold_AComposedFieldHoldsTheBoundsOfEachDeclarationsOwnNode`, `merge.TestOwnBounds_ReadsTheNodeADeclarationOwns`, `e2e.TestCompile_AMemberTheRedeclaredPropertyFoldComposesKeepsItsBounds`, - `merge.TestFold_AComposedFieldAdoptsOnlyANull`, + `merge.TestFold_AComposedFieldAdoptsWhatItsCompositionAdmits`, `merge.TestFold_ComposesOnlyTheDeclarationsItJudges`, `merge.TestFieldSpan_NamesEachSetOfDeclarations`, `merge.TestFold_AFieldAnotherModelCarriesTakesAnIdentityOfItsOwn`, `merge.TestPropertyIndex_ADiscriminatorFollowsItsFieldToANewIdentity`, - `e2e.TestAllOf_ACollisionPastTheFlatteningDepthIsRefused`, `merge.TestSelectBase_ChoosesAsTheRuleSays`, `schema.TestAllOf_AFieldRedeclaredAsTwoModelsComposesThem`, `schema.TestAllOf_AComposedFieldKeepsADiscriminatedBase`, - `schema.TestAllOf_AComposedFieldElectsTheBaseAWrittenAllOfDoes`, + `schema.TestAllOf_AComposedFieldChoosesTheBaseAWrittenAllOfDoes`, `schema.TestAllOf_EveryDistributedVariantSharesOneComposedField`, - `schema.TestAllOf_AnAliasIsJudgedAsTheTypeItStandsFor`, + `schema.TestAllOf_AnAliasIsJudgedAsTheTypeItNames`, `schema.TestAllOf_RelatedStructuresAreNotCalledAConflict`, `schema.TestAllOf_ATypeHoldingAnotherTakesTheField`, `schema.TestAllOf_AnObjectSayingMoreThanItsTypeComposes`, @@ -3520,7 +4079,7 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `schema.TestAllOf_ANullNotOrIfIsTheKeywordLeftOut`, `schema.TestAllOf_ADistributedVariantIsReadWithItsUnion`, `e2e.TestCompile_AFieldRedeclaredAsAStructureAdmittingItsKindIsNotAConflict`, - `e2e.TestCompile_AStructureAdmittingPartOfAKindConflictsWithIt`, + `e2e.TestCompile_AStructureAdmittingPartOfAKindSharesItsValues`, `e2e.TestCompile_AVariantIsReadWithEverySchemaHoldingItsUnion`, `schema.TestVariantHolders_ClimbsEverySchemaHoldingAUnionBranch`, `schema.TestAdmissionOf_PartialIsWhatAKeywordRefusesInPart`, @@ -3549,15 +4108,16 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `schema.TestMembers_ARefAndTheSchemaItNamesWrittenInlineFoldAlike`, `schema.TestMembers_ATieAnEntrySettledIsNotCountedAgain`, `schema.TestMembers_AMemberAPartSettledIsJudgedWhereItsTypeIsWritten`, - `schema.TestMembers_AMemberAPartMeetsIsJudgedAtEachDeclarationItHolds`, + `schema.TestMembers_AMemberAPartIntersectsIsJudgedAtEachDeclarationItHolds`, `schema.TestMembers_AMemberOnlyEntriesDeclareIsJudgedWhereItsTypeIsWritten`, - `schema.TestMembers_ABroughtMembersDefaultIsItsOwnTypesWhereThatIsWritten`, + `schema.TestMembers_ABroughtMembersDefaultItsOwnTypeRefusesIsNotAdopted`, `schema.TestMembers_ASettledMembersInlineTypeIsNoBaseOfWhatComposesIt`, `schema.TestMembers_AReportNamesABroughtMemberWhereItSaysWhatItDoes`, + `schema.TestMembers_ASettledMembersDescriptionIsReportedWhereItIsWritten`, `schema.TestMembers_ADeclarationASettledModelHoldsKeepsWhereItsTypeIsWritten`, `schema.TestMembers_TheSettlementAsksItsContextBeforeEachModel`, - `schema.TestAllOf_ADefaultIsItsOwnTypesWhicheverDeclarationTheNodeCopies`, - `merge.TestTypeSites_NamesWhereAFoldedTypesNodesAreWritten`, + `schema.TestAllOf_ADefaultItsOwnTypeRefusesIsNotAdoptedWhicheverDeclarationTheNodeCopies`, + `merge.TestTypeSites_NamesWhereAFieldTypesNodesAreWritten`, `merge.TestBuiltSites_ReadsNoMoreNodesThanItsBound`, `merge.TestHoistedAt_ReadsEachPlaceADeclarationHoldsItsType`, `merge.TestFold_NamesABroughtDeclarationWhereItSaysWhatItDoes`, @@ -3573,34 +4133,43 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `schema.TestMembers_ReadsPastTheBudgetFoldTheirOwnDeclarationsAlone`, `schema.TestMembers_ReadsAPartThroughItsAliasesAndNothingElse`, `schema.TestMembers_ReadingAModelNotSettledChargesItsComposition`, - `schema.TestMembers_ACycleIsChargedTheCompositionsItsReadsWalk`, - `merge.TestOwnership_ReadsEachModelsCompositionOnce`, - `merge.TestOwnership_LeavesOutADeclarationAnotherComposesAtAnyDepth`, - `merge.TestOwnership_StopsOnceItReachesEveryOtherModel`, - `merge.TestOwnership_AWalkReturningToItsModelReadsOnToTheOthers`, - `merge.TestOwnership_ChargesWhatItReadsAndLeavesInWhatACutWalkMisses`, + `schema.TestMembers_ACycleReadsNoMemberAsItIs`, + `schema.TestDeclarationsAdmitAlike_DeclarationsAreAlikeWhereTheyAdmitAlike`, + `schema.TestSameMeaning_ReferencesOfTwoDialectsReadAlikeWhereTheyMeanAlike`, + `schema.TestSameMeaning_AnAliasAndACopyOfItsModelFoldAlikeInEveryOrder`, + `schema.TestSameMeaning_TextKeptVerbatimReadsAsWritten`, + `schema.TestFold_ACopyAnnotatedApartLosesNothing`, + `schema.TestFold_ACopyAnnotatedApartInAHeldTypeIsReportedOnce`, + `merge.TestAnnotationsHeldApart_TakesTheNotesOnAHeldTypesAnnotations`, + `schema.TestAnnotationsOf_ReadsEachDocsMemberAndDeprecation`, + `merge.TestFold_ACopyAnnotatedApartIsKeptVerbatim`, + `e2e.TestCompile_ARingSaysEachLossAgainstWhatItsFieldKeeps`, + `merge.TestSettleCompositionCycle_ALongCycleFoldsAsAModelsFoldPastTheBound`, + `e2e.TestComposition_ALongCycleFoldsAsAModelsFoldPastTheBound`, + `e2e.TestCompile_ACycleFoldsAsAFlatFoldOfItsDeclarations`, + `merge.TestSettle_LeavesOutADeclarationAnotherPartComposesAtAnyDepth`, + `schema.TestMembers_ReadsGrowLinearlyWhereEachLevelBringsAFreshPart`, `schema.TestMembers_ABaseComposedBesideItsHierarchyBringsNothingAtAnyDepth`, - `schema.TestMembers_ACutTellingDeclarationsApartIsReported`, - `schema.TestMembers_ACutTellingDeclarationsApartFallsAlikeInEveryRun`, - `merge.TestOwnership_ReadsPastAPartNamingNoType`, + `schema.TestMembers_ACutIsReportedAtTheModelReadingPastIt`, + `schema.TestMembers_ACutFallsAlikeInEveryRun`, `merge.TestPropertyIndex_ADiscriminatorNamingAnAppendedMemberNamesItsID`, `e2e.TestCompile_OverlayIsCreditedWithAMemberOnlyItsEntriesDeclare`, `merge.TestFold_AnEntryAlikeInTwoDocumentsKeepsOneWhateverTheOrder`, `operation.TestPartEncodings_KeyedOnTheMemberTheBodyDeclares`, `merge.TestFold_EnumsAreJudgedByTheValuesTheyShare`, - `merge.TestFold_EnumsSharingNoValueTogetherKeepTheWinner`, - `merge.TestFold_EnumsListingSharedValuesApartKeepTheWinner`, + `merge.TestFold_EnumsSharingNoValueTogetherKeepTheChosenDeclaration`, + `merge.TestFold_EnumsListingSharedValuesApartKeepTheChosenDeclaration`, `merge.TestFold_TwoEnumsCostTheirWidth`, `merge.TestFold_ANarrowerListAdoptsTheBroadersDetail`, `merge.TestFold_ANarrowerListAdoptsTheBroadersEncoding`, `merge.TestFold_ContainersOfModelsComposeTheirMembers`, - `merge.TestFold_AConstMeetsATimeScalarHoldingDetail`, - `merge.TestFold_AMeetingNoNodeHoldsKeepsTheWinner`, - `merge.TestFold_AFailedMeetingReportsOnlyItsDrops`, - `merge.TestFold_ADetailTwoMeetingDeclarationsGiveDifferentlyIsKept`, + `merge.TestFold_AConstIntersectsATimeScalarHoldingDetail`, + `merge.TestFold_AnIntersectionNoNodeHoldsKeepsTheChosenDeclaration`, + `merge.TestFold_AFailedIntersectionReportsOnlyItsDrops`, + `merge.TestFold_ADetailTwoIntersectingDeclarationsGiveDifferentlyIsKept`, `schema.TestAllOf_EnumsAndListsNarrowToWhatTheyShare`, `schema.TestAllOf_ContainersOfDifferentModelsComposeTheirMembers`, - `schema.TestAllOf_EnumsSharingSomeValuesMeetInAnEnumOfThem`, + `schema.TestAllOf_EnumsSharingSomeValuesIntersectInAnEnumOfThem`, `merge.TestFold_AnEnumWithinAnotherAdoptsItsDetail`, `merge.TestFold_ANarrowerListAdoptsWhatTheBroaderKeeps`, `merge.TestFold_TuplesBuildWhatFollowsTheirPositions`, @@ -3608,20 +4177,20 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `merge.TestFold_AValueIsJudgedByTheNodeTheFieldHolds`, `schema.TestAllOf_ADefaultIsJudgedByTheNodeTheFieldHolds`, `merge.TestFold_EnumsOfDifferentValueTypesAreJudgedByTheirValues`, - `merge.TestFold_ThreeEnumsMeetInTheNarrowestValueType`, + `merge.TestFold_ThreeEnumsIntersectInTheNarrowestValueType`, `schema.TestAllOf_EnumsOfDifferentValueTypesAreJudgedByTheirValues`, - `merge.TestView_ReadsAnAliasAsTheNodeItStandsFor`, + `merge.TestView_ReadsAnAliasAsTheNodeItRepresents`, `merge.TestView_StopsAtTheNodeTheChainsShare`, - `merge.TestSharedLink_NamesTheFirstNodeEveryChainNames`, - `merge.TestAliasedNode_ReadsAChainUpToItsBound`, - `merge.TestStandsFor_ReadsOnlyAnAliasChain`, - `merge.TestFold_AnAliasMeetsAsTheNodeItStandsFor`, - `merge.TestFold_AnAliasIsWithinTheNodeItStandsFor`, - `schema.TestAllOf_AnAliasMeetsAsTheNodeItStandsFor`, - `schema.TestAllOf_AMemberBehindAnAliasIsJudgedByWhatItStandsFor`, + `merge.TestSharedAlias_NamesTheFirstNodeEveryChainNames`, + `merge.TestAliasedNode_ReadsAChainToItsEnd`, + `merge.TestRepresents_ReadsOnlyAnAliasChain`, + `merge.TestFold_AnAliasIntersectsAsTheNodeItRepresents`, + `merge.TestFold_AnAliasIsWithinTheNodeItRepresents`, + `schema.TestAllOf_AnAliasIntersectsAsTheNodeItNames`, + `schema.TestAllOf_AMemberBehindAnAliasIsJudgedByWhatItNames`, `schema.TestAllOf_AnAliasIsJudgedByWhatItAdds`, - `merge.TestUnaliased_ReadsAChainUpToItsBound`, - `merge.TestComposes_ReadsAChainUpToItsBound`, + `merge.TestUnaliased_ReadsAChainToItsEnd`, + `merge.TestComposes_AsksTheWalk`, `merge.TestComposes_ReadsEachPartOnce`, `merge.TestSaysOnlyObject_ReadsEveryFieldThatSaysSomething`, `e2e.TestExternalContent_AComposedFieldIsNamedInItsDocument`, @@ -3635,15 +4204,22 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `merge.TestFold_EnumPairsAreJudgedByKind`, `schema.TestAllOf_EnumPairsAreJudgedByKind`, `merge.TestTypeJudge_RelateArms`, - `merge.TestTypeJudge_AdmitsPerNode`, - `merge.TestAdmitsConstraints_JudgesEachKeyword`, - `merge.TestIsMultipleOf_JudgesExactly`, - `schema.TestAllOf_AWinnersConstraintsRefuseADefaultInEitherOrder`, + `merge.TestFoldValueAdmissionReader_AdmitsPerNode`, + `ir.TestConstraintsAdmit_JudgesEachKeyword`, + `merge.TestFold_AdoptsAValueWhereTheValueAdmissionReaderSaysYes`, + `e2e.TestFoldJudgment_ADefaultItsFieldsEnumBoundRefusesIsNotAdopted`, + `e2e.TestFoldJudgment_AValueItsOwnTypeRefusesIsNotAdopted`, + `e2e.TestFoldJudgment_ABroaderDeclarationsOwnBoundJudgesItsValue`, + `e2e.TestFoldJudgment_AValueInAUnionIsCountedAcrossItsVariants`, + `e2e.TestFoldJudgment_ABroaderValueTheReaderCannotJudgeIsAdopted`, + `ir.TestMultipleOfAdmits_JudgesExactly`, + `e2e.TestSteps_ADefaultPastTheJudgmentsBoundIsAdoptedUnjudged`, + `schema.TestAllOf_AChosenDeclarationsConstraintsRefuseADefaultInEitherOrder`, `merge.TestClassify_ALiteralOverlapsWhatHoldsValues`, `schema.TestAllOf_NonBareNarrowingIsOrderInvariant`, `merge.TestFold_AScalarOverANarrowerKindWins`, `merge.TestFold_TheTopTypeTakesTheOtherSidesNullAdmission`, - `schema.TestAllOf_TheTopTypeAndANullableKindMeetAsNullableInEitherOrder`, + `schema.TestAllOf_TheTopTypeAndANullableKindIntersectAsNullableInEitherOrder`, `schema.TestAllOf_ADefaultTheNarrowerNodeRefusesIsKeptInEitherOrder`, `schema.TestAllOf_TwoEqualListsRefuseANullTheMergeDoesNotAdmit`, `schema.TestAllOf_AnUnknownFormatWinsInEitherOrder`, @@ -3651,16 +4227,16 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `merge.TestFold_AUint8NarrowsInt16InEitherOrder`, `typeformat.TestNarrows_HoldsEveryContainment`, `typeformat.TestNarrows_OmitsRoundingContainments`, - `typeformat.TestRelate_ClassifiesEveryVerdict`, + `typeformat.TestRelate_ClassifiesEveryAnswer`, `typeformat.TestFormatTable_EveryRowNarrowsItsBareType`, - `merge.TestAdmits_JudgesEachKindExactly`, + `ir.TestPrimitiveAdmits_JudgesEachKindExactly`, `merge.TestAdmitsFormat_JudgesTimeAsAFullTime`, `merge.TestAdmitsFormat_SharesNoStringWithAKind`, `merge.TestRelateKinds_ReadsAHeldFormatAsAStringFormat`, `merge.TestKindOf_TheFirstEncodingDecidesTheFormat`, `schema.TestAllOf_ATimeIsJudgedByItsGrammar`, - `merge.TestAdmits_ReadsAHugeExponentWithoutMaterializingIt`, - `merge.TestTypeJudge_NullIsJudgedByNullability`, + `ir.TestPrimitiveAdmits_ReadsAHugeExponentWithoutMaterializingIt`, + `merge.TestFoldValueAdmissionReader_JudgesNullByTheReference`, `merge.TestFold_ExamplesAreJudgedAsOneKeyword`, `merge.TestFold_AnInadmissibleValueIsKeptNotAdopted`, `schema.TestAllOf_ANullOnARefOverTheTopTypeIsKept`, @@ -3671,17 +4247,24 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `merge.TestFold_ATieGoesToTheLaterAndIsReported`, `merge.TestFold_ADroppedFirstDeclarationIsKept`, `merge.TestFold_AConstraintConflictNamesTheDeclarationKeptFrom`, + `merge.TestIntersectConstraints_NamesWhatGivesTheValueIntersected`, + `merge.TestIntersectConstraints_SpellsAValueAsTheFirstWrittenGivingIt`, + `merge.TestIntersectionValueGivers_NeverNamesThePassedOverSet`, + `merge.TestIntersectConstraints_SaysTheDifferenceFromTheIntersection`, + `openapi.TestFoldReports_AStepNamesOneDeclarationInEitherOrder`, `merge.TestFold_ABoundTakesItsTightestValueInEveryOrder`, `merge.TestFold_AKeywordNoOneValueStatesIsKeptAndReported`, - `merge.TestCommonStep_HoldsTheMultiplesOfBoth`, - `merge.TestCommonStep_RefusesWhatItCannotRead`, + `ir.TestConstraintIntersection_IntersectsTwoStepsToTheirCommonMultiple`, + `ir.TestConstraintIntersection_BoundsAStepByItsNumerator`, + `e2e.TestSteps_TwoLongStepsOneTwiceTheOtherIntersectToTheLarger`, + `e2e.TestSteps_AStepWhoseNumeratorPassesTheBoundIsRefused`, `merge.TestBoundsRelation_JudgesWhichSaysAllTheOtherDoes`, - `merge.TestFold_NodesThatMeetStandOnAMintedNode`, - `merge.TestFold_TheBoundsOfEveryDeclarationMeetInEveryOrder`, + `merge.TestFold_NodesThatIntersectSitOnAMintedNode`, + `merge.TestFold_TheBoundsOfEveryDeclarationIntersectInEveryOrder`, `merge.TestFold_ANodeHoldingEveryBoundIsNotMinted`, - `merge.TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheWinner`, - `merge.TestFold_AliasesOfOneModelComposeThoughTheirBoundsMeet`, - `merge.TestFold_AValueIsHeldToTheBoundsOthersBring`, + `merge.TestFold_NodesDifferingInAKeywordNoOneValueStatesKeepTheChosenDeclaration`, + `merge.TestFold_AliasesOfOneModelComposeThoughTheirBoundsIntersect`, + `merge.TestFold_AValueIsHeldToEveryBoundAtItsPosition`, `merge.TestFold_ANodesBoundsJudgeAValueWrittenAgainstItsOwnKind`, `merge.TestFold_AValueOfABroaderMemberIsJudgedByTheField`, `merge.TestFold_AValueOnAListInAnotherDocumentIsJudgedAsItsOwn`, @@ -3707,6 +4290,8 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `merge.TestTypeJudge_AnEncodedScalarRelatesAsItsValues`, `e2e.TestAllOfFold_AnEncodedFormatIsJudgedAsByteIsBesideBinary`, `schema.TestAllOf_ARefToAnInlineNodeIsDeclaredApart`, + `e2e.TestFoldJudgment_AlikeNodesDeclaredApartNameTheOneWrittenFirst`, + `e2e.TestFoldJudgment_AlikeComponentsUnderTwoBasesOverlap`, `schema.TestAllOf_ACopyANarrowingKeptIsStillACopy`, `schema.TestAllOf_AListOfAComponentWinsOverAListOfItsCopy`, `schema.TestAllOf_ARefToASiblingFieldIsDeclaredApart`, @@ -3719,9 +4304,32 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc `schema.TestAllOf_RedeclarationsUnderAnotherBaseStayApart`, `schema.TestAllOf_RedeclarationsWritingNoRelativeReferenceFoldUnderAnyBase`, `schema.TestAllOf_ACopyOfAComponentUnderAnotherBaseStaysApart`, - `e2e.TestExternalContent_ACopyOfAnotherDocumentsComponentStaysApart` -- Status: partly built: a structure that refuses some kinds only through a `not` or an `if` reads - as stating its type, so it conflicts with a kind it admits (#1671); two enums of value types neither within the other (`int32` against `uint32`) overlap, + `e2e.TestExternalContent_ACopyOfAnotherDocumentsComponentStaysApart`, + `merge.TestTypeJudge_AKeptKeywordOfAnotherKindSaysNothing`, + `merge.TestTypeJudge_ACopyKeepingWhatAnotherDoesNotIsNoCopy`, + `merge.TestFormatIntersectionKind_IntersectsAKindAFormatApplyingToItNarrows`, + `merge.TestFold_AFormatIntersectsTheKindItNarrows`, + `merge.TestBoundsBeside_ReadsEveryAliasOfTheChain`, + `merge.TestSourceFormatAdmissions_ReadsAKeptEntryByItsKeyword`, + `schema.TestAllOf_AFormatAloneIntersectsTheKindItNarrows`, + `merge.TestTypeJudge_AnAliasOfTheTopTypeIsJudgedByWhatItsSourceAdmits`, + `merge.TestFold_ADroppedDeclarationsShapeGoesWithIt`, + `schema.TestModelFields_AdmitsReadsEverySomeOrNoneOfAKind`, + `schema.TestAdmissionOf_ReadsAnIfOnItsOwnCycleUnread`, + `e2e.TestFoldJudgment_ReadsNotAndIfAsTheKindsTheyAdmit`, + `merge.TestFold_NodesKeepingAKeywordApartKeepItUnderEachDeclaration`, + `merge.TestIntersectionEntries_KeepsNothingAnotherModelBringsOrTheEnumKeepsWhole`, + `merge.TestFold_ACopyKeepingAUseBoundKeywordApartKeepsItUnderItsDeclaration`, + `e2e.TestFoldJudgment_NotesAndKeywordsSayingNothingDecideNothing`, + `e2e.TestFoldJudgment_ValueSetsSharingNullAloneKeepEachDeclarationOnce`, + `merge.TestFold_KeptTextBoundsIntersectByKeyword`, + `merge.TestKeptLength_ReadsALengthKeptAsACount`, + `merge.TestTypeJudge_KeptLengthsAreReadAsBounds`, + `merge.TestIntersectionEntries_ALengthNotEveryHolderKeepsAsACountIsKeptApart`, + `merge.TestFold_LengthsSayingNothingAreKeptUnderEachDeclaration` +- Status: partly built: an `if` schema leading back to the schema writing it, or written down an + entry whose dynamic reference is read unexpanded, is read as admitting some instances of each kind + (#1671); two enums of value types neither within the other (`int32` against `uint32`) overlap, keeping the later, though they share values, since the IR has no value type for what both admit; an alias adding docs to the null it adds is not read as adding null alone, though a reference carries an alias's docs to its use, since a use site whose `$ref` chain runs on past the alias @@ -3729,15 +4337,10 @@ removed by post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenc different sets only because the model stops at the flattening depth are refused as `compile/registry-refused`, not told apart, since one declaration names both; a member declared at two depths keeps the identity of the one written first, so swapping the entries moves it (#1931); - a hierarchy composing at every level a model redeclaring a name it holds reads its depth again at - each level, until the run's reads run out (#1993); the names of the models on a cycle of - compositions decide which declaration they keep where two admit no value together (#1995); a part - reached through more than 64 alias scalars brings nothing, its member left as the flattening takes - it, as the type judge, a tag's reading and a multipart body read such a chain no further (#1994); - and a model the fold composes for a member is minted at the declaration last to widen the field, + a model the fold composes for a member is minted at the declaration last to widen the field, so swapping two entries renames it, and moves a report on a member it settles (#1921, #1992); and a type within a variant of a union holding a bound is unrelated to it whatever kind the bound - applies to, so the later of the two declarations stands, reported (#2005). + applies to, so the later of the two declarations is taken, reported (#2005). ### `allof-required` @@ -3765,9 +4368,12 @@ appears, composition included. A `false` conjunct (`allOf: [false, …]`) admits composition admits nothing: the composed `Model` is closed and the entry is kept verbatim beside it, under `openapi:` as [`allof-inline-residue`](#allof-inline-residue) keys an entry (`degraded_lowering`), which is what distinguishes it from a model that merely wrote -`additionalProperties: false`, and reported as an info `openapi/false-schema` at the entry. What +`additionalProperties: false`, and reported as an info `openapi/false-schema` at the entry. The +position, which admits no value, reports itself too, as every bottom does: the warning +`openapi/unsatisfiable-schema` of [`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts), naming +the entry as admitting no value. What the other entries contributed stays — closing is the nearest shape the IR has, and emptying the -model would trade one silent loss for another. The model's catch-all keeps only its patterns, as +model would trade one unreported loss for another. The model's catch-all keeps only its patterns, as beside `additionalProperties: false` ([catch-alls](../ir/models.md#catch-alls)), since the closure forbids every key they leave: its value goes, the `additionalProperties` the model took, beside the `allOf` or on the entry closing it ([`additional-properties`](#additional-properties)), being kept @@ -3778,7 +4384,7 @@ nothing is reported. Where a `oneOf` or `anyOf` beside the `allOf` is distribute the entry, and the entry is reported once. - Cases: `allof-boolean-branch`, `allof-nested-inline` -- Codes: `openapi/false-schema` +- Codes: `openapi/false-schema`, `openapi/unsatisfiable-schema` - Tests: `schema.TestAllOf_NestedFalseEntryClosesModel`, `schema.TestAllOf_FalseEntryBesideUnionClosesEveryVariant`, `schema.TestAllOf_FalseEntryClosesTheCatchAllItForbids`, @@ -3790,50 +4396,61 @@ An `allOf` whose conjuncts share no value admits no instance, as `{allOf: [{$ref: List}], type: object}` does over an array and `{allOf: [{$ref: Str}, {$ref: Obj}]}` over a string and an object. Such a schema lowers as any composition does ([`allof-classification`](#allof-classification)), a distributed one included -([`union-beside-structure`](#union-beside-structure)), and draws one `openapi/degraded-construct` -warning at the composing schema, naming each conjunct that narrows the instance types and what it -states. An inline entry that [`allof-inline-residue`](#allof-inline-residue) would warn about -reports its residue as an info there, so the contradiction is reported once however it is spelled. +([`union-beside-structure`](#union-beside-structure)), and draws one `openapi/unsatisfiable-schema` +warning at the composing schema, saying no value satisfies its conjuncts together, naming each one +that narrows the instance types by its path from the schema, with what it states, saying what the +schema lowered as, with the unions it keeps verbatim where no branch of the union its conjunction +chooses lives ([`union-beside-structure`](#union-beside-structure) shape 4), or, where it lowers to +the closed model of the bottom, the `oneOf` and `anyOf` it writes itself, each kept under its +keyword as the union reading keeps it, and asking for one of them to be removed or corrected. A +union so named draws no report of its own there, as validation logic or a degraded lowering. It +lists the keywords beside the `allOf` first, the `type`, the value set, the `$ref`, the `oneOf` and +the `anyOf`, then each entry in pointer order, an entry before its own keywords; a value set is +named by its members, read through each `$ref` it is written behind, an `enum` by its first five and +a count of the rest, a string quoted and a list or an object by its brackets alone, and a union of +value sets by the members its branches write. An inline entry that +[`allof-inline-residue`](#allof-inline-residue) would warn about reports what it keeps as an info +there, so the contradiction is reported once however it is spelled. The reading is of the source, since a `Model` cannot say whether its source wrote `type: object`, and `{properties: …}` alone admits a string. That is where it parts from the reading -[`allof-refinement`](#allof-refinement) elects a principal by, which takes such a `properties` to -claim an object: one chooses a lowering, and this one says what the source admits. Each conjunct -admits a set of JSON instance types, an `integer` within a `number` and named as written, and a -number with a fraction, which no `type` names, named a `number that is no integer`, read once +[`allof-refinement`](#allof-refinement) chooses a principal by, which takes such a `properties` to +say the schema is an object: one chooses a lowering, and this one says what the source admits. Each +conjunct admits a set of JSON instance types, an `integer` within a `number` and named as written, +and a number with a fraction, which no `type` names, named a `number that is no integer`, read once a compile, whatever its size: the `type` beside the `allOf`, and the members of an `enum` or a `const` written there, named by its keyword, as on an entry; an inline entry's `type`, the members -of its `enum` or `const`, the join of what each branch of its `oneOf` or `anyOf` admits, and what -its own `allOf` admits; and for a `$ref` entry, what the schema it lands on admits, read the same -way. The keywords beside a `$ref` entry apply to the instance as the reference does, at 3.0 as from -3.1, since the lowering applies them ([`ref-use-site`](#ref-use-site)), so where they narrow what -it admits they are a conjunct of their own, named `allOf/` beside the reference's -`allOf//$ref`, its name whatever is written beside it, an `allOf` of the entry's own included: -`{allOf: [{$ref: Str, type: object}]}` is reported at every version, beside the later-version -warning 3.0 draws. A `oneOf` or `anyOf` beside the `allOf` none of whose branches -shares a kind with the rest of the schema, or whose branches declare no shape and so are kept beside -it as validation logic, is a conjunct too, named by its keyword and admitting what any branch does -([`union-beside-structure`](#union-beside-structure)). So is the one of a `oneOf` -and an `anyOf` written together that the position does not elect -([`competing-keywords`](#competing-keywords)): beside the `allOf`, named by its keyword, and on an -entry, named `allOf//` beside that entry, which is then its own keywords and the union -it elects. A `oneOf` and an `anyOf` with nothing else conjoining with them are two conjuncts too, -named where they are written, by their keywords on a schema writing both, which is reported though -it writes no `allOf`, and the report names the union the position lowered as. The schema is reported where those sets share no member, every -conjunct admits some value by itself and none is cut short, and they share no null: a null is a -shared value only where every conjunct admits it, as +of its `enum` or `const`, what any branch of its `oneOf` or `anyOf` admits, and what its own `allOf` +admits; and for a `$ref` entry, what the schema it lands on admits, read the same way. The keywords +beside a `$ref` entry apply to the instance as the reference does, at 3.0 as from 3.1, since the +lowering applies them ([`ref-use-site`](#ref-use-site)), so where they narrow what it admits they +are a conjunct of their own, named `allOf/` beside the reference's `allOf//$ref`, its name +whatever is written beside it, an `allOf` of the entry's own included: `{allOf: [{$ref: Str, type: +object}]}` is reported at every version, beside the later-version warning 3.0 draws. A `oneOf` or +`anyOf` beside the `allOf` none of whose branches shares a kind with the rest of the schema, or +whose branches declare no shape and so are kept beside it as validation logic, is a conjunct too, +named by its keyword and admitting what any branch does +([`union-beside-structure`](#union-beside-structure)). So is the one of a `oneOf` and an `anyOf` +written together that the position does not choose ([`competing-keywords`](#competing-keywords)): +beside the `allOf`, named by its keyword, and on an entry, named `allOf//` beside that +entry, which is then its own keywords and the union it chooses. A `oneOf` and an `anyOf` with +nothing else conjoining with them are two conjuncts too, named where they are written, by their +keywords on a schema writing both, which is reported though it writes no `allOf`, and the report +names the union the position lowered as. The schema is reported where those sets share no member, +every conjunct admits some value by itself and none is cut short, and they share no null: a null is +a shared value only where every conjunct admits it, as [`allof-redeclared-property`](#allof-redeclared-property) reads a pair of declarations, each read as -[`nullable`](#nullable) reads one, under the nullable-inference policy where that is on, and wherever -the IR holds it, so a union admits null where one of its branches does and keeps it out where each -does. So `{allOf: [{$ref: ON}], oneOf: [{type: string}, {type: boolean}]}` over an `ON` admitting an -object or null is reported, a null being no value the union admits; with a `{type: 'null'}` branch -beside the two the conjuncts share the null, which -[`union-beside-structure`](#union-beside-structure) then reports as all that satisfies the schema. -A read of null that runs out of its budget reads each conjunct on its own, as which ones it reached +[`nullable`](#nullable) reads one, under the nullable-inference policy where that is on, and +wherever the IR holds it, so a union admits null where one of its branches does and keeps it out +where each does. So `{allOf: [{$ref: ON}], oneOf: [{type: string}, {type: boolean}]}` over an `ON` +admitting an object or null is reported, a null being no value the union admits; with a `{type: +'null'}` branch beside the two the conjuncts share the null, which +[`union-beside-structure`](#union-beside-structure) then reports as all that satisfies the schema. A +read of null that runs out of its budget reads each conjunct on its own, as which ones it reached would follow the order they are written in: one keeping null out within its own budget decides, and -otherwise they share it. Where only one conjunct narrows the instance -types nothing is reported, since one conjunct contradicts nothing, unless it admits no -value by itself and nothing else says so (below). +otherwise they share it. Where only one conjunct narrows the instance types nothing is reported, +since one conjunct contradicts nothing, unless it admits no value by itself and nothing else says so +(below). What writes no `type` and no value set admits every kind, so a report is made only of what the source declares: a `true` entry, a `format` and a `properties` state nothing. A conjunct admitting no @@ -3841,10 +4458,13 @@ value by itself, the null included, that says so where it is written is its own `allOf` composing it draws nothing: a `false` entry, which [`allof-false-branch`](#allof-false-branch) reports, and a `$ref` landing on `false`, on a schema whose value set holds no value its own type admits, an empty `enum` among them ([`enum-const`](#enum-const)), on a schema whose own -conjuncts share no value, or on one writing a union beside its object body no branch of which an -instance of the body satisfies ([`union-beside-structure`](#union-beside-structure)), which is -reported where it is written, each read through a chain of `$ref`s each admitting no value, up to -256 of them. So a schema composing a reported one draws no second report. An inline entry whose +conjuncts share no value, or on one writing a union beside its object rest no branch of which an +instance of the rest satisfies ([`union-beside-structure`](#union-beside-structure)), which is +reported where it is written, each read through a chain of `$ref`s each admitting no value, to its +end where the compiler resolves one, and up to 64 of them where it does not. So a schema composing a +reported one draws no second report, but for the bottom ([`allof-refinement`](#allof-refinement) +point 4), a lowering of its own, which reports it, naming +that conjunct `no value`. An inline entry whose value set the position lowers as ([`allof-refinement`](#allof-refinement)) and whose keywords leave it no kind is read as the same keywords beside the `allOf` are: its `type`, its value set and each union it writes, each a conjunct named below the entry, so `{allOf: [{$ref: T}, {const: 1, enum: @@ -3858,8 +4478,9 @@ nothing: a cycle of `allOf` entries, a value no reading converts, or an entry ne `statement.MaxFlattenDepth`. An entry whose `$ref` lands on no schema, or on `$ref`s leading round a loop, is read as admitting every kind, so the conjuncts beside it are still reported where they share no value. A `$dynamicRef` the bindings read as -no `$ref` masks nothing, and a `not`, an `if` or a `dependentSchemas` is not followed: a conjunct -may admit less than is read, and conjuncts disjoint as read are disjoint. An `allOf` beside a +no `$ref` masks nothing, and a `not`, an `if` or a `dependentSchemas` is followed no further than +[`allof-redeclared-property`](#allof-redeclared-property) reads it: a conjunct may admit less than +is read, and conjuncts disjoint as read are disjoint. An `allOf` beside a `$ref` ([`allof-beside-ref`](#allof-beside-ref)) does not compose and is not read. One passed over for a `const` or an `enum` ([`competing-keywords`](#competing-keywords)) is read as any composition is, the value set beside it among its conjuncts, so `{allOf: [{$ref: Obj}], enum: [a, b]}` warns as @@ -3867,23 +4488,25 @@ is, the value set beside it among its conjuncts, so `{allOf: [{$ref: Obj}], enum lowered as. A value set beside the `allOf` holding no value its own type admits is reported where it is written ([`enum-const`](#enum-const)), so the `allOf` draws nothing more. -Where the kinds the conjuncts admit share one but the election of +Where the kinds the conjuncts admit share one but the choice of [`allof-refinement`](#allof-refinement) reads them sharing no value, the null included, as value sets sharing no member do, or a set none of whose members a `format` it reads as narrowing a number -to an integer admits, the same warning is drawn, read by that election, and names each value set -by its member count and each other conjunct by the kinds and formats it admits, one admitting every -kind left out, listed by what each states and then by name, so no order written orders them: -`{allOf: [{enum: [a, b]}, {enum: [c, d]}]}` draws `allOf/0: 2 values, allOf/1: 2 values`, and +to an integer admits, the same warning is drawn, read by that choice, and names each value set +by its members and each other conjunct by the kinds and formats it admits, one admitting every +kind left out, in the order above: `{allOf: [{enum: [a, b]}, {enum: [c, d]}]}` draws +`allOf/0: enum ["a", "b"], allOf/1: enum ["c", "d"]`, and `{allOf: [{type: number, format: int32}, {type: number, enum: [1.5]}]}` draws -`allOf/1: 1 value, allOf/0: integer of format int32`, the format read as +`allOf/0: integer of format int32, allOf/1: enum [1.5]`, a set no conjunct writes as one value set, +as an `allOf` of sets holds one, being named by its size, the format read as [`numeric-formats`](#numeric-formats) reads it, where JSON Schema asserts none by default. A null every conjunct admits, a conjunct admitting no value by itself and a read cut short draw it nowhere, as above. - Cases: `allof-disjoint-conjuncts` -- Codes: `openapi/degraded-construct` -- Tests: `e2e.TestElection_TwoUnionsOverABodyLowerAlikeWhereverWritten`, - `e2e.TestElection_TwoUnionsAloneLowerAsOneSchemaWritingBoth`, +- Codes: `openapi/unsatisfiable-schema` +- Tests: `schema.TestUnion_ABottomKeepingAUnionDrawsOneFindingSayingSo`, + `e2e.TestChoice_TwoUnionsOverABodyLowerAlikeWhereverWritten`, + `e2e.TestChoice_TwoUnionsAloneLowerAsOneSchemaWritingBoth`, `schema.TestUnion_TwoUnionsAloneSharingNoValueWarnOnceWhereverWritten`, `schema.TestAllOf_AnEntryLoweringAsItsValueSetIsReadAsBesideTheAllOf`, `schema.TestAllOf_ValueSetsSharingNoMemberWarnOnce`, `schema.TestAllOf_ValueSetsSharingAValueDrawNoWarning`, @@ -3891,15 +4514,15 @@ as above. `schema.TestAllOf_ARefAmongValueSetsSharingNoMemberIsKept`, `schema.TestAllOf_DisjointConjunctsReportOnceAtTheSchema`, `e2e.TestEntryValueSet_AValueSetSharingNoKindWithItsRefWarnsInEverySpelling`, `schema.TestAllOf_AValueSetBesideAUnionWarnsOnce`, - `schema.TestAllOf_DisjointReportStaysSilent`, + `schema.TestAllOf_DisjointReportDrawsNothing`, `schema.TestAllOf_AKeywordBesideARefIsReadAtEveryVersion`, `schema.TestAllOf_ComposingADisjointSchemaDrawsNoSecondReport`, - `schema.TestAllOf_DisjointInlineEntryReportsItsResidueAsInfo`, + `schema.TestAllOf_DisjointInlineEntryReportsItsUnreadKeywordsAsInfo`, `schema.TestAllOf_DisjointConjunctsFollowTheNullableReading`, `schema.TestAllOf_DisjointConjunctsIgnoreDeclarationOrder`, `schema.TestAllOf_DisjointConjunctsReportOnModelsAndOperations`, `schema.TestAllOf_DisjointReportNamesWhatThePositionLoweredAs`, - `e2e.TestStandingShape_ConjunctsSharingNoValueNameWhatThePositionLoweredTo`, + `e2e.TestPositionShape_ConjunctsSharingNoValueNameWhatThePositionLoweredTo`, `e2e.TestCompile_AUnionConjunctSharingNoKindWithTheOtherIsReported`, `e2e.TestCompile_AUnionAndARestShareNullOnlyWhereBothAdmitIt`, `e2e.TestCompile_ANullAliasConjunctIsReadAsTheNullItAliases`, @@ -3909,7 +4532,7 @@ as above. `e2e.TestCompile_AnEmptyConjunctIsReportedWhereNothingElseSaysSo`, `schema.TestToldWhereWritten_ReadsWhatSaysASchemaAdmitsNothing`, `e2e.TestCompile_ADisjointReportNamesAFraction`, - `schema.TestInstanceWords_NamesEverySetOfKinds` + `schema.TestInstanceWords_NamesEverySetOfKinds`, `schema.TestAllOf_AValueSetIsNamedByWhatWritesIt` ### `union` @@ -3937,7 +4560,10 @@ its position (`variant_1`). An inline branch no title names that refines a `$ref 3.0 annotates a branch, takes the hint that `$ref` takes as a branch of its own, as 3.1's spelling of the same branch, `{$ref: X, description: …}`, does, and the position's where that names nothing. Its node keeps the positional hint, which an outside `$ref` to the branch derives too; no emitter -renders it, since a decorator collapses into its reference. +renders it, since a decorator collapses into its reference. Two branches naming one type share its +name because they share the type, which `pass/exclusive-union-repeated-variant` reports, so the names +pass leaves the repeat out of the union's name scope, the first of them staying in it to collide with +any other variant's name (`pass/name-collision`). - Cases: `oneof-discriminated`, `anyof-discriminated`, `anyof-untagged`, `union-decorated-branch` - Tests: `schema.TestUnion_ADecoratedBranchIsHintedAsItsRef`, @@ -3950,8 +4576,12 @@ other than `null`, in order, each lowered from the same schema as that type alon applies to it, and named by it: for `object` or `array` a node hoisted at `/type/`, and for a scalar type the shared primitive, or a `Scalar` hoisted at that pointer where the variant holds what the primitive cannot, a value bound, a format naming an encoding or the content -vocabulary. The pointer holds a type's name and no schema, so nothing else is interned there. -Where an `allOf` entry the position lowers from writes the list +vocabulary. The pointer holds a type's name and no schema, so nothing else is interned there, and +a variant reads its schema where the schema is written, in the dialect written there, as a node of +the schema's own does: its properties, the nodes beneath it, what it keeps and what it reports name +the source's places, never one beneath `/type/`, so two variants reading one schema +share its declarations, and a `$ref` to a schema beneath it, a `contentSchema` among them, reads the +node the variant reads. Where an `allOf` entry the position lowers from writes the list ([`allof-refinement`](#allof-refinement)), `` is the position's: the variants are parts of the position's node, built from the whole conjunction, where the same keywords written flat there put them. A `$ref` to the entry builds a `Union` of its own, its variants under the entry's pointer, @@ -3970,16 +4600,22 @@ position admits that type, so `[string, integer]` with `maxLength` and `minimum` `[string, boolean]`, the same list's `integer` variant holds no `minimum`, which is kept on the union. The `array` variant takes the collection bounds. A variant reads its bounds of what the `allOf` beside the list, or the conjunction whose entry writes it, says too, as it reads them of the -list's own schema, but for the `object` variant, which reads none there (Status). The property or -parameter carrying the union holds no value bound, each being the variant's it applies to, which a -bound on the whole value would not say. -A `format` the table pairs with a listed type is that variant's alone: with `date` the list lowers -to `date | integer`, and with `int32` to `string | int32`. One the table pairs with no listed type -is every scalar variant's encoding name, since nothing says which type it describes and a format -validates only the instances of the types it is defined for (JSON Schema Validation 2020-12 §7.1). -What the variants read, not the union, decides a keyword's home: a keyword or bound some variant -reads is homed, and one none reads, a bound no listed type takes among them, is kept on the union -([`shape-applicator`](#shape-applicator)). +list's own schema, the `object` variant its property counts, and a `string` variant carrying a +number as text keeps verbatim each value bound such conjuncts write, as it keeps the list's own. +Writers of one bound, the list among them, intersect as any bound's do +([`string-formats`](#string-formats)), the variant keeping the value of the intersection. The +property or parameter carrying the union holds no value bound, each being the variant's it applies +to, which a bound on the whole value would not say. The `object` variant composes the `properties` +and `required` of every inline conjunct beside the list, the schema holding it as an entry among +them, as its flat twin holds its own: `{type: [string, object], allOf: [{properties: {a: {type: +integer}}}]}` is the `Union` of the string and a `Model` holding `a`, as `{type: [string, object], +properties: {a: {type: integer}}}` is. A `format` the table pairs with a listed type is that +variant's alone: with `date` the list lowers to `date | integer`, and with `int32` to `string | +int32`. One the table pairs with no listed type is every scalar variant's encoding name, since +nothing says which type it describes and a format validates only the instances of the types it is +defined for (JSON Schema Validation 2020-12 §7.1). What the variants read, not the union, decides a +keyword's home: a keyword or bound some variant reads is homed, and one none reads, a bound no +listed type takes among them, is kept on the union ([`shape-applicator`](#shape-applicator)). The `object` variant holds no `discriminator`, so it is kept unread on the union, whether or not a `oneOf` or `anyOf` is written beside it. No `$ref` or `mapping` can name the variant's position, @@ -4004,6 +4640,7 @@ and teaching the relation the step would change what it means for every document `type-array-bounds` - Codes: `openapi/unresolved-ref` - Tests: `schema.TestLower_MultiTypeUnion`, + `schema.TestTypeArray_AnObjectVariantComposesTheMembersBesideTheList`, `schema.TestLower_ATypeArrayIsExclusiveOnlyOverDisjointTypes`, `schema.TestLower_ATypeListedTwiceIsNotExclusive`, `schema.TestLower_ATypeArrayKeepsItsDiscriminatorOnTheUnion`, @@ -4014,46 +4651,54 @@ and teaching the relation the step would change what it means for every document `schema.TestLower_ATypeArraysContentIsTheStringVariants`, `schema.TestConstraints_ACountAVariantKeepsIsKeptOnce`, `e2e.TestInlinePrincipal_AVariantEntryLowersAsItsFlatSpelling` -- Status: built. Limits: an object bound an `allOf` entry writes beside the list, or the position - writes beside an `allOf` whose entry writes the list, reaches no variant and is kept on the - `Union` under its keyword, where the same bound beside the list is the object variant's (#2062). ### `union-null-variant` A null branch of a `oneOf` or `anyOf` is one written inline whose own keywords admit `null` alone -([`null-alone`](#null-alone)), whatever spells it: `type: "null"`, an `enum` of `null` alone, -`const: null`, or 3.0's `{type: object, enum: [null], nullable: true}`. It is no variant, of a union -lowered alone, on an `allOf` entry as at the position, or of one distributed across a body beside it -([`union-beside-structure`](#union-beside-structure)), since it would lower on its own to the `Enum` -with no member whose one value the reference's `Nullable` bit states, so the union's reference -admits `null` instead ([`nullable`](#nullable)). A `oneOf` or `anyOf` with exactly one branch that -is not a null branch, beside one or more that are, lowers to a nullable reference to that branch's -lowering rather than to a `Union` ([type-graph](../ir/type-graph.md#type-references)); one with -several lowers to a `Union` of them behind a nullable reference. A `oneOf` of two null branches -admits no `null` by JSON Schema, which `null` would match twice, yet one null branch or several are -read alike, as the union's `null`: the document contradicts itself, and this rule does not read it -otherwise. A `$ref` branch naming a schema of `null` alone stays a variant, a reference to that -schema's `Enum`, nullable where the rest of the position may admit null (below), which an emitter -reads as the union's `null` ([unions](../emitters/refine/unions.md#a-null-a-variant-admits)): it -names a node the source declares, which lifting it would drop, and reading it would take a distant -declaration. A branch whose `null` only the nullable-inference policy admits is a null branch while -the policy is on, and the reference's `null` then names it in `Inferred`, with its -`openapi/inferred-nullable` info at the branch ([`nullable`](#nullable)); with the policy off, the -branch admits nothing and is a variant. -A variant's own `null`, as `{type: [string, 'null']}` admits, is shared only where every conjunct -may admit it: where what the position writes beside the union keeps null out, the union passed over +([`null-alone`](#null-alone)), whatever spells it: `type: "null"`, beside an `enum` listing `null` +among other values or not, an `enum` of `null` alone, `const: null`, or 3.0's +`{type: object, enum: [null], nullable: true}`. It is no variant, of a union +lowered alone, on an `allOf` entry as at the position, or of one distributed across the rest beside +it ([`union-beside-structure`](#union-beside-structure)), since it would lower on its own to the +`Enum` with no member whose one value the reference's `Nullable` bit states, so the union's +reference admits `null` instead ([`nullable`](#nullable)). A `oneOf` or `anyOf` with exactly one +branch that is not a null branch, beside one or more that are, lowers to a nullable reference to +that branch's lowering rather than to a `Union` ([type-graph](../ir/type-graph.md#type-references)); +one with several lowers to a `Union` of them behind a nullable reference. A `oneOf` of two null +branches admits no `null` by JSON Schema, which `null` would match twice, yet one null branch or +several are read alike, as the union's `null`: the document contradicts itself, and this rule does +not read it otherwise. A `$ref` branch naming a schema of `null` alone stays a variant, a reference +to that schema's `Enum`, nullable where the rest of the position may admit null (below), which an +emitter reads as the union's `null` +([unions](../emitters/refine/unions.md#a-null-a-variant-admits)): it names a node the source +declares, which lifting it would drop, and reading it would take a distant declaration. A branch +whose `null` only the nullable-inference policy admits is a null branch while the policy is on, and +the reference's `null` then names it in `Inferred`, with its `openapi/inferred-nullable` info at the +branch ([`nullable`](#nullable)), unless the one other branch the union collapses to declares `null` +itself, which the reference then holds as declared, at the position and at every `$ref` to it: +`{anyOf: [{type: object, enum: [null], nullable: true}, {type: [string, 'null']}]}` at 3.1 is a +declared nullable string. With the policy off, the branch admits nothing and is a variant, so the +reference to that union of two variants holds no `null`, its string variant holding its own. A +variant's own `null`, as `{type: [string, 'null']}` admits, is shared only where every conjunct may +admit it: where what the position writes beside the union keeps null out, the union passed over among it, the variant's reference is not nullable, and nothing is reported, the branch's other values living. A null branch writing a key beside `type`, `enum`, `const`, and a `nullable` its dialect or the nullable-inference policy reads, such as a `description`, is kept whole under `openapi:/`, the branch's path from the schema, with the reason `no_ir_home`, +or `degraded_lowering` where its `enum` lists members its type excludes ([`null-alone`](#null-alone)), since the `null` is typed exactly and only what the branch says of it has no field: on the `Union` the branches leave, or, where they collapse, where the position keeps what else the collapse cannot hold, below. It is reported as an info `openapi/degraded-construct` at the branch. A `nullable` nothing reads is a keyword the branch's dialect does not define, which keeps the branch as any other does, and a `null` written for one of those keys is the key left out -([`null-keywords`](#null-keywords)), and keeps nothing. An `enum` that repeats its `null` is the +([`null-keywords`](#null-keywords)), and keeps nothing. A vendor extension whose value no JSON +holds keeps nothing either: it is left out with the `openapi/degraded-construct` warning it draws +where it is written, reported at the branch as a variant's lowering reports it, so a branch writing +nothing else beside its null is kept nowhere, and one kept for what else it writes is kept without +it, an extension written deeper in the branch reported by the keep where it is written. An `enum` +that repeats its `null` is the document's whichever path takes the branch, so each repeat is reported as an `openapi/duplicate-enum-value` warning at it, as for that `enum` written alone ([`enum-const`](#enum-const)). @@ -4077,11 +4722,13 @@ carrier of a property, parameter or header, and on an alias hoisted at any other `schema.TestNullBranch_ARefToANullAloneSchemaStaysAVariant`, `schema.TestNullBranch_ADiscriminatorLinesItsVariantsUpPastTheNull`, `schema.TestNullBranch_KeepsWhatTheBranchWrites`, - `schema.TestNullBranch_AKeptBranchTheKeeperCannotConvertIsReportedByIt`, + `schema.TestNullBranch_AKeptBranchIsKeptWithoutAnExtensionNoJSONHolds`, `schema.TestNullBranch_KeepsANullableNothingReads`, `schema.TestNullBranch_ARepeatedNullIsReportedAtTheBranch`, `schema.TestNullableInference_EachShapeReadsByItsVersion`, - `e2e.TestUnionNullVariant_AUnionAloneOnAnEntryIsTheReferenceItsBareSpellingIs` + `e2e.TestUnionNullVariant_AUnionAloneOnAnEntryIsTheReferenceItsBareSpellingIs`, + `e2e.TestNullAnswer_ACollapsedUnionsNullIsInferredWhereThePolicyAloneReadsIt`, + `e2e.TestNullAnswer_AUnionOfSeveralVariantsKeepsAVariantsNullOffItsReference` ### `union-null-only` @@ -4090,18 +4737,37 @@ A `oneOf` or `anyOf` whose every branch is a null branch lowers as one does at that position, to an `Enum` with no member behind a nullable reference ([`null-alone`](#null-alone)). The `Enum` carries no branch set, so the combinator, and the other one too where both are written, is kept verbatim under `openapi:oneOf` or `openapi:anyOf` -(`degraded_lowering`), with an info `openapi/degraded-construct` at the schema, and what else the +(`degraded_lowering`), with an info `openapi/degraded-construct` at the schema. What else the schema writes that the `Enum` has no field for is kept unread, as beside a schema of `null` alone. Wherever the position lowers so, whether the two are written beside an `allOf`, on one of -its entries or one each on two, a body beside them or none, both are kept that way. +its entries or one each on two, the rest beside them or none, both are kept that way. A union whose +branches share no value with the rest of the position but null, shared by one branch of a `oneOf` +or by any of an `anyOf`'s, lowers alike, from the whole conjunction, and the info says so. The +`Enum` is typed by no kind, as `{type: 'null'}`'s is. The position's `type` admitting the null says +nothing more and is kept nowhere. The branches sharing no value are named in one +`openapi/unsatisfiable-schema` at the union keyword, in every spelling. + +Where the rest admits null and several live `oneOf` branches admit it too, null matches more than +one branch, so the `oneOf` refuses it. `{type: [string, 'null'], oneOf: [{format: uuid}, {format: +date}]}` is the `Union` of the two formats behind a reference admitting no null, with one +`openapi/unsatisfiable-schema` warning at the `oneOf` naming those branches. A 3.0 +`{type: string, nullable: true}` in place of the `type` list lowers alike where the +nullable-inference policy is off. Where it is on, the policy reads the null back in: the reference +admits null, marked inferred, and an info `openapi/inferred-nullable` at the `nullable` says so in +place of the warning. Where two branches of a `oneOf` share that null alone, both match it, so the +`oneOf` refuses it and the position admits no instance +([`union-beside-structure`](#union-beside-structure)), with one warning +`openapi/unsatisfiable-schema`. A union of null alone on an `allOf` entry beside that entry's own +`type` is kept so too, `degraded_lowering`, as beside the `type` with no `allOf`. -- Status: partly built: a union of null alone on an `allOf` entry beside that entry's own `type` is - kept as `validation_only`, where its other spellings keep it as `degraded_lowering` (#2106). - Cases: `null-only-union` -- Codes: `openapi/degraded-construct` +- Codes: `openapi/degraded-construct`, `openapi/unsatisfiable-schema` - Tests: `schema.TestOneOfAnyOf_NullOnlyLowersAsNullAlone`, + `schema.TestUnion_ANullOnlyOutcomeLowersAsItsNullTwin`, + `schema.TestUnion_AOneOfRefusesANullItsBranchesShare`, + `schema.TestOneOf_TheWarningOfADeadBranchSaysWhereTheUnionIs`, `schema.TestLowerNullAlone_KeepsWhatTheEnumCannotHold`, - `e2e.TestElection_TwoUnionsOfNullAloneBesideABodyKeepTheirReasonEverywhere` + `e2e.TestChoice_TwoUnionsOfNullAloneBesideABodyKeepTheirReasonEverywhere` ### `union-beside-structure` @@ -4113,7 +4779,7 @@ referent per conjunct, the shape `allOf` writes, and cannot state "conjoined wit [boundaries](../ir/boundaries.md#deliberate-exclusions) records why none was added. Target languages are not the constraint here; TypeScript writes `{a: string} & (X | Y)` directly. Where the conjunction *distributes*, [models](../ir/models.md#composition-beside-a-union) gives the -rule: the body is composed into each variant, and the result is an ordinary `Union` of composed +rule: the rest is composed into each variant, and the result is an ordinary `Union` of composed `Model`s (or a map's `MapT`, below), reported as an info `openapi/composition-lowering` at the schema, since nothing is lost but the IR's shape no longer mirrors the source's, bar one thing: a `false` in the `allOf` states that the composition admits nothing, which every composed variant then holds only as the closed @@ -4126,82 +4792,148 @@ object alone, null aside, or its read is cut short, as an `allOf`'s `$ref` entry ([`allof-classification`](#allof-classification)), and a `$ref` to a schema whose `type` list holds an object composes that list's object variant, unless the branch writes a keyword beside its `$ref`, which binds the whole list and which no node the variant names would hold. Any other branch that -an instance of the body may satisfy, admitting an object among other kinds or every kind, is kept +an instance of the rest may satisfy, admitting an object among other kinds or every kind, is kept verbatim on its variant under its keyword and index, `openapi:oneOf/` or `openapi:anyOf/` -(`degraded_lowering`), beside the body as on an `allOf` entry, its provenance naming where it is +(`degraded_lowering`), beside the rest as on an `allOf` entry, its provenance naming where it is written, as an entry's own keywords are kept ([`allof-inline-residue`](#allof-inline-residue)); a -position distributes one union, so no two such keys meet. It draws an info +position distributes one union, so no two such keys coincide. It draws an info `openapi/degraded-construct` at the branch. That is the branch's one home: it lowers at no pointer of its own, and the target of a `$ref` it writes is the node it is wherever it is named. A schema -writing both a `oneOf` and an `anyOf`, beside the body or as one inline entry of its `allOf`, -distributes the one [`competing-keywords`](#competing-keywords) elects, the one whose branches -declare shape against the position, its `oneOf` where both do, and each variant keeps the other +writing both a `oneOf` and an `anyOf`, beside the rest or as one inline entry of its `allOf`, +distributes the one [`competing-keywords`](#competing-keywords) chooses, the one whose branches +declare shape against the position, its `oneOf` where both do, and the `Union` keeps the other once verbatim under its keyword, its provenance where it is written: as `validation_only` where its branches declare no shape against the position, the rest of the `allOf` and the entry's own keywords among it and neither union, with an info `openapi/validation-only-keyword`, and else as -`degraded_lowering`, drawing that rule's info where the two are written; where the elected union is +`degraded_lowering`, drawing that rule's info where the two are written; where the chosen union is one of the shapes below, the node keeps both as that shape keeps a union, with that shape's findings alone, on one entry or two alike. Wherever it is written, the union passed over is a -conjunct of the rest the elected one's branches are read against, for a dead branch (below) and for -[`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts), whether or not the elected one +conjunct of the rest the chosen one's branches are read against, for a dead branch (below) and for +[`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts), whether or not the chosen one distributes: a variant admitting null alone, as a `$ref` to `{type: 'null'}`, is dead where that rest keeps null out, kept and warned as below, unless every variant would be, the two then sharing no value, which that rule's one warning says, and the `Union` keeping them; one sharing no kind with the rest read without either union, a union of null alone beside a rest admitting no null among them, leaves no instance satisfying the two, whichever branch is taken, so the position keeps both as shape 4 does, and a schema writing no `allOf` draws that rule's warning naming its own keywords and that union. One leaving that rest null alone does the same where no -branch of the elected union admits null; where one does, the position admits that null and nothing -else, so it lowers as the body keeping both as `degraded_lowering`, with no warning, and an `allOf` -of an inline object admitting null composes it, its `Model` standing at the position as the schema -writing all three flat does. A union none of whose branches shares a kind with a body -that is no `Model` (a scalar, a `type` list of scalars, an array) admits nothing with it, so the -position lowers as that body keeping the union as `degraded_lowering`, with that rule's one warning, -beside the body's keywords, beside an `allOf` of it and on an entry alike. Such a -variant composes nothing, so beside a body that is a map and nothing else it is that map's `MapT` -([containers](../ir/containers.md)), the kept branch and the bounds it takes on it. A variant holds -the bounds written beside the union that the kinds it admits take, its branch's within the body's, -and one no variant takes is kept on the `Union` ([`constraints`](#constraints)): beside `type: -object`, a `minLength` bounds no variant. Object keywords written with no `type`, a -`properties`, a `patternProperties`, a `required`, a closure or a catch-all, are a body too where -the kinds the position lowers to are an object alone ([`shape-applicator`](#shape-applicator)): -what the branches declare, each an object, or, where nothing declares a kind, what the -kind-inference policy reads off them. Each variant, a model over its branch, then holds those -keywords, as beside `type: object`: `{oneOf: [{$ref: A}, {$ref: B}], additionalProperties: -false}` is a `Union` of closed models over `A` and `B`, and a bare `required` names the members each -variant requires. A null branch is no variant of a distributed union, as it is none of a plain one -([`union-null-variant`](#union-null-variant)): the reference to the position admits `null` where -the body admits it too, so beside a body writing `type: object` it admits none, and beside one -writing no `type`, or listing `null` in its `type`, it admits the union's -([`nullable`](#nullable)), and a union written on an `allOf` entry beside such a body distributes -past its null branch alike. - -A branch no instance of the body satisfies is no variant either. Every instance of the schema is one -of the body, which admits objects alone, null aside, so a branch is dead where the kinds it lowers +branch of the chosen union admits null; where one does, the position admits that null and nothing +else, so it lowers as the rest keeping both as `degraded_lowering`, with no warning, and an `allOf` +of an inline object admitting null composes it, its `Model` taking the position as the schema +writing all three flat does. + +One reading of the conjunction decides a position, wherever its unions and its rest are written: +the pair choice above; then the chosen union's dead branches, read against all else the +conjunction writes, the union passed over and any rest included; then a union leaving null alone, +which [`union-null-only`](#union-null-only) lowers; then one every branch of which is dead, a +choice among no shapes, so the position lowers as its other conjuncts say, keeping the union as +`degraded_lowering`, with the one warning of +[`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) reading the union as a conjunct, at the +schema; then the shape judgment below. A union nothing conjoins with is read against no rest, each +branch a variant and a null one its null. A `type` naming null alone is part of the rest like any +other keyword, and one admitting null alone is no object: where every branch shares no kind with it, +as in `{type: 'null', anyOf: [{type: string}, {type: integer}]}` or beside the 3.0 null written as +`{type: object, enum: [null], nullable: true}`, the position is the closed empty `Enum` the rest is, +keeping the union once, and the one warning names the dead branches at the union keyword, as beside +any rest that is no object alone (below), at every version and in every spelling. Where every branch +is a null branch beside an object rest keeping null out, the nullable-inference policy lifts its +null onto the rest: `{type: object, properties: …, oneOf: [{type: 'null'}]}` is the `Model` behind a +reference the policy marks, its members its own and the union said, with the info +`openapi/inferred-nullable` at the branch and no warning, keeping what a branch writes beside its +null as [`union-null-variant`](#union-null-variant) keeps it, and a union passed over as beside any +rest. Where no branch lives and the policy reads the conjunction as admitting null otherwise, by +such a null branch beside a dead one or by its widening ([`nullable`](#nullable)), the position is +null alone too, keeping the union: the closed empty `Enum` behind a reference the policy marks, as +every reference to the schema is, a lifted branch drawing that info, and the dead branches of each +union, the one chosen and any passed over, named at its keyword, a branch saying nothing of null, +such as `{}`, sharing that null and living. With the policy off, such a null branch shares no value +with the rest and is dead, so `{type: object, properties: …, oneOf: [{type: 'null'}]}` is the +`Model` keeping the union, with the one warning at the schema. + +Beside a rest that is no object alone (a scalar, an array, a `type` list holding no object), a +branch sharing no kind with the rest, a null one where the rest keeps null out among them, is dead: +no variant, and one warning `openapi/unsatisfiable-schema` at the union keyword names each dead +branch with what it admits. A live branch declares shape unless every keyword it writes past those +of the rest names no shape (bounds, patterns, notes) or restates it, a `$ref` and any `format` +declaring one. Where one does, the live branches are a `Union` of their nodes, each conjoined with +the rest's one kind, a branch writing more than that kind's scalar reads kept on its own node, and +the rest's bounds on `Union.Constraints`: `{type: string, anyOf: [{format: ipv4}, {format: ipv6}]}` +is a `Union` of the two encodings. Where one branch alone lives, it is the choice the union leaves, +so the position is that branch's node so conjoined, a `Scalar` over it holding the rest's bounds, +its `Base` admitting the null the position admits, as every `Scalar`'s does +([scalars](../ir/scalars.md#aliases)), and no `Union` of one variant: `{type: string, oneOf: [{type: +integer}, {format: uuid}]}` is `uuid`, keeping the union as below. A rest holding one `$ref` to a +scalar, beside it of a shape only a `type` naming the scalar's kind and bounds, is conjoined so too, +wherever its `$ref`, its bounds and the union are written: on the position, on one entry together, +as `{allOf: [{$ref: B, oneOf: […], maxLength: 5}]}`, or on entries of their own at any depth, the +union's entry writing the bound or the `$ref` in an `allOf` of its own among them, each spelling +lowering as the flat one does. Each variant is what the `allOf` of the rest's `$ref`, the `type` +beside it, and its branch lowers to, lowered by the conjunction lowering itself +([`allof-refinement`](#allof-refinement)), its node minted at the branch's key: `{allOf: [{$ref: +B}], oneOf: [{format: uuid}, {format: date}]}` over a string `B` is the `Union` of the `uuid` and +the `date`, each keeping the `$ref`, as a recognized format beside a `$ref` to a scalar does, where +an unrecognized one restricts `B`; a `$ref` branch, one writing beside its `$ref` too, is what the +`allOf` of the two `$refs` is; and `{allOf: [{$ref: B}, {maxLength: 5}], oneOf: [{format: uuid}, +{format: date}]}` is the `Union` of the two holding the `maxLength` in its `Constraints`, as beside +a `type` written inline, no variant holding it. `B`'s own bounds stay `B`'s, reached through the +`$ref`; the rest's notes are the position's. Where none does, the node of the rest keeps the union, +at a property a node of its own in every spelling. The union holding a dead branch is kept once, +`degraded_lowering`, and else `validation_only`. Beside a union of an object and another kind the +rest distributes by kind: an object branch's variant composes the rest's keywords that apply to +objects, another kind's is a `Scalar` over its branch holding that kind's bounds, or the branch's +node where no keyword of the rest applies to it, and a branch admitting several kinds is distributed +over its kinds alike. A branch listing several types, an object among them or none, is the `Union` +of a node per type, each the node its list lowers that type to, holding what the list writes of it, +conjoined with the rest's keywords of its kind, the `Union` saying what the list says of itself: +`{properties: {a: …}, minLength: 3, oneOf: [{type: [object, string]}, {type: integer}]}` is the +`Union` of the integer and of a model holding `a` and a string holding the `minLength`, so no string +the schema admits is left without a variant. A rest naming no kind, writing a bound a scalar branch +takes, beside branches of several kinds and no object goes to them so too: `{properties: {a: …}, +minLength: 1, oneOf: [{$ref: Arr}, {$ref: Str}]}` is the `Union` of `Arr` and a `Scalar` over `Str` +holding the `minLength`, and the `properties`, applying to no kind the union admits, is kept +verbatim once with an info, wherever it is written. Such a variant composes nothing, so beside a +rest that is a map and nothing else it is that map's `MapT` ([containers](../ir/containers.md)), the +kept branch and the bounds it takes on it. A variant holds the bounds written beside the union that +the kinds it admits take, its branch's within the rest's, and one no variant takes is kept on the +`Union` ([`constraints`](#constraints)): beside `type: object`, a `minLength` bounds no variant. +Object keywords written with no `type`, a `properties`, a `patternProperties`, a `required`, a +closure or a catch-all, are part of the rest too where the kinds the position lowers to are an +object alone ([`shape-applicator`](#shape-applicator)): what the branches declare, each an object, +or, where nothing declares a kind, what the kind-inference policy reads off them. Each variant, a +model over its branch, then holds those keywords, as beside `type: object`: `{oneOf: [{$ref: A}, +{$ref: B}], additionalProperties: false}` is a `Union` of closed models over `A` and `B`, and a bare +`required` names the members each variant requires. A null branch is no variant of a distributed +union, as it is none of a plain one ([`union-null-variant`](#union-null-variant)): the reference to +the position admits `null` where the rest admits it too, so beside a rest writing `type: object` it +admits none, and beside one writing no `type`, or listing `null` in its `type`, it admits the +union's ([`nullable`](#nullable)), and a union written on an `allOf` entry beside such a rest +distributes past its null branch alike. + +A branch no instance of the rest satisfies is no variant either. Every instance of the schema is one +of the rest, which admits objects alone, null aside, so a branch is dead where the kinds it lowers to, as the admission reads them ([`allof-refinement`](#allof-refinement)), hold no object, and it -or the body admits no null: a string, an array, a value set of strings, `false`, a `type` list +or the rest admits no null: a string, an array, a value set of strings, `false`, a `type` list holding no object. A branch whose kinds the kind-inference policy read, or whose read is cut short, decides nothing and lives, as does one naming a `$dynamicRef` the position does not expand, which -admits every kind, and every branch beside a body the policy made an object; a branch admitting -null lives beside a body that may admit it. Each null is read as [`nullable`](#nullable) reads one, +admits every kind, and every branch beside a rest the policy made an object; a branch admitting +null lives beside a rest that may admit it. Each null is read as [`nullable`](#nullable) reads one, under the nullable-inference policy as it selects, and wherever the IR holds it: a branch admits null where it is or names a union one of whose branches does, as a `$ref` to `{type: 'null'}`, a `{type: [integer, 'null']}` or a further such union does, whose null lies on that variant's reference rather than on one to the union ([`union-null-variant`](#union-null-variant)), and the -body admits it by all it writes but the union, its `allOf` entries among it and the union passed -over for it, which admits null where one of its branches does, in every spelling. That read takes in at -most 256 schemas, and a body or branch whose read passes them, what it read leaving null in, is -read as one that may admit null. The bounds of -[`allof-refinement`](#allof-refinement) cut short only what an election compares: a branch whose +rest admits it by all it writes but the union, its `allOf` entries among it and the union passed +over for it, which admits null where one of its branches does, in every spelling. That read is the +schema's one answer on null, which no depth cuts ([`nullable`](#nullable)). The bounds of +[`allof-refinement`](#allof-refinement) cut short only what the choice compares: a branch whose read passes them keeps its kinds, read whole, so a branch over a union of 300 strings is dead as one -over 100 is; but beside a body that may admit null, whether it admits null is not read, and it +over 100 is; but beside a rest that may admit null, whether it admits null is not read, and it lives. The `Union` keeps each dead branch verbatim under the key a kept branch takes on a variant -(`degraded_lowering`), and the schema draws one warning `openapi/degraded-construct` naming each +(`degraded_lowering`), and the schema draws one warning `openapi/unsatisfiable-schema` naming each with the kinds it admits, the code [`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) gives -conjuncts sharing no value, of which a dead branch and the body are two; no finding is made at the +conjuncts sharing no value, of which a dead branch and the rest are two; no finding is made at the branch, and it lowers nowhere. Leaving out a branch no instance satisfies changes what neither a `oneOf`'s "exactly one" nor an `anyOf`'s "at least one" admits, so `{type: object, anyOf: [{type: object}, {type: array}, {type: string}]}` is a `Union` of one variant, as a union written with one -branch beside a body is. Where the body's own `allOf` conjuncts share no kind, the entry a union is +branch beside a rest is. Where the rest's own `allOf` conjuncts share no kind, the entry a union is written on aside, the warning of that rule already says no instance satisfies the schema, and no branch is read as dead. Nor is one where the rest of the conjunction, what the schema writes but the union, an entry's own `type` and value set kept, admits anything but objects, null aside, as that @@ -4210,7 +4942,7 @@ then a conjunct like any other, a contradiction with the rest is that report's t whose kinds are not known draws neither, so a schema draws one of the two warnings at most. `{allOf: [{$ref: Str}, {oneOf: [{type: boolean}, {$ref: Obj}]}]}` over a string `String` draws the warning that its conjuncts share no value and none naming a dead branch. Where no branch -lives, the union is shape 5 below. A route the discriminator standing with the union takes to a +lives, the union is shape 5 below. A route the discriminator written with the union takes to a dead branch routes to no variant, and the union keeps none: a `mapping` entry whose value's chain a dead branch meets first, as a variant's branch meets one ([`discriminator`](#discriminator)), and a `defaultMapping` doing so, are left out of the `Discriminator` and kept verbatim on the `Union` @@ -4223,10 +4955,10 @@ other branch names it, keys nothing in the `Mapping` either. The warning naming names each such route, the `defaultMapping`, then each `mapping` key and then each component name, each in byte order, so a document whose routes are all the union's own compiles with no error; an entry naming a schema the union does not list still routes to it, which -`pass/validate` reports. Where no branch lives, the discriminator routes nothing and is kept whole -(below). +`pass/validate` reports. Where no branch lives, the discriminator routes no branch, and is settled as +below. -A `discriminator` standing with the union, where no branch composes the schema (shape 3), routes +A `discriminator` written with the union, where no branch composes the schema (shape 3), routes the distributed union ([`discriminator`](#discriminator)): a `mapping` target, or the `defaultMapping`, naming the component a `$ref` branch names routes to the variant composed over that branch. OpenAPI routes a variant no entry names by the name of the component its branch @@ -4242,58 +4974,62 @@ writes no union of its own, its `allOf` composes rather than refines ([`allof-refinement`](#allof-refinement)), and the union is the one entry union whose branches declare shape (below), judged against the rest without any entry's union as two beside the `allOf` judge each other by neither, or of several the one written as a `oneOf`, as -[`competing-keywords`](#competing-keywords) elects the `oneOf` of one schema writing both: each other -is kept on every variant, whichever is written first. An entry writing both is one such union and -lowers as a schema writing both does (above), each variant keeping the union it passes over. Where -the rest of the schema writes nothing a variant would carry, no keyword or only those every branch -says, as beside the union (below), and no `$ref`, other union or `discriminator`, nor an `allOf` on -the union's own entry, the union stands alone and lowers as written at the position, its entry the -principal of a refining `allOf` ([`allof-refinement`](#allof-refinement)): -`{allOf: [{oneOf: [{$ref: X}, {type: 'null'}]}]}` is the nullable reference to `X` and -`{allOf: [{oneOf: [{$ref: X}, {$ref: Y}]}]}` the `Union` of `X` and `Y` ([`union`](#union), +[`competing-keywords`](#competing-keywords) chooses the `oneOf` of one schema writing both: each +other is kept once, on the `Union`, whichever is written first. An entry writing both is one such +union and lowers as a schema writing both does (above), the `Union` keeping the union it passes +over. Where the rest of the schema writes nothing a variant would carry, no keyword or only those +every branch says, as beside the union (below), and no `$ref` or other union, the union is alone and +lowers as written at the position, a `discriminator` or an `allOf` of notes written with it, on its +entry, on another or beside the `allOf`, read with it as written beside the bare union, its entry +the principal of a refining `allOf` ([`allof-refinement`](#allof-refinement)): `{allOf: [{oneOf: +[{$ref: X}, {type: 'null'}]}]}` is the nullable reference to `X` and `{allOf: [{oneOf: [{$ref: X}, +{$ref: Y}]}]}` the `Union` of `X` and `Y` ([`union`](#union), [`union-null-variant`](#union-null-variant), [`union-null-only`](#union-null-only)), keeping of the union what the bare union keeps, and a note, bound or annotation beside it lands where it does -beside the bare union. A `oneOf` and an `anyOf` standing so together, on one entry or one each on +beside the bare union. A `oneOf` and an `anyOf` written so together, on one entry or one each on two, at any depth, lower as one schema writing both with nothing beside them does, whatever kinds -their branches admit ([`competing-keywords`](#competing-keywords)): the entry of the one elected is +their branches admit ([`competing-keywords`](#competing-keywords)): the entry of the one chosen is the principal, its null branch lifted no more than that schema's, and the other is kept on the node it lowers to, a `discriminator` on the other's entry leaving them a composition. A keyword some -branch does not say, as `type: object` beside a null branch, -a property set or a `$ref`, written on the union's entry, on another or beside the `allOf`, is what -a variant carries, so there the union distributes, one variant included, as beside the same -keywords. It distributes beside a `discriminator` on another entry or beside the `allOf` too: one -beside the `allOf` routes the distributed union, though the same union with the `discriminator` -written beside it is the union standing alone, and one on another entry is that entry's residue, -kept on each variant; one on the union's own entry routes the union standing alone. The -`discriminator` standing with it is the one its entry writes, else the one beside the `allOf`: -where both write one, nothing says which routes the union, so it is kept as what an entry writes is -([`allof-inline-residue`](#allof-inline-residue)), under its keyword where the two are written alike -and with its entry whole, under `openapi:allOf/`, where they differ, and the `Model` holds the -schema's own. It routes the union as one beside it does, a `mapping` entry naming no schema -reported at the entry under the schema writing it, and it routes by name the schemas the union -lists ([`discriminator-value`](#discriminator-value)). Its variants take their IDs from the -branch's pointers, its `$ref` and inline branches conjoin as above, and the entry keeps nothing of -the union or of a `discriminator` it writes, whose extensions and keys OpenAPI defines for no -Discriminator Object ride on the `Union` holding it ([`vendor-extensions`](#vendor-extensions)), -what else the entry writes merging as any entry does -([`allof-inline-residue`](#allof-inline-residue)). Whether a route names the schema -is read at the position, as for a union beside the `allOf`, so an inline schema below a -discriminated base no route names distributes. A union on an entry that is one of the shapes below, -one of two entry unions declaring shape and written under one keyword, distributing either of which -would drop the other and no rule ranking them, or one whose branches declare no shape, is kept on each -variant where another union distributes as what an entry writes is -([`allof-inline-residue`](#allof-inline-residue)): under its keyword, or with its entry kept whole -where that rule says, as for one nested past the flattening depth. Distribution cannot -reach these shapes: - -1. the structural body is not a `Model`: a `const`, an `enum`, a scalar, or keywords written with +branch does not say, as `type: object` beside a null branch, a property set or a `$ref`, written on +the union's entry, on another or beside the `allOf`, is what a variant carries, so there the union +distributes, one variant included, as beside the same keywords. A `discriminator` carries nothing a +variant would: on another entry or beside the `allOf` it routes the union alone, as written beside +the union. The `discriminator` written with a union is the one written beside it, else the one +beside the `allOf`, else the one the inline entries write, where one writes it or every one writes +it alike, each routing it as beside it. Entries writing different ones route nothing, each kept +whole, in whichever order they are written. One on the union's own entry routes the union alone. So +where the union's entry and the schema beside the `allOf` each write a different one, the entry's +routes the union, and the one beside the `allOf` is kept on the `Union` under +`openapi:discriminator` (`degraded_lowering`), its values read as every kept discriminator's are, +with an info `openapi/degraded-construct` at the schema, whether the union is alone or distributes +across another entry's members. So `{allOf: [{oneOf: [X, Y], discriminator: {propertyName: k}}], +discriminator: {propertyName: j}}` is the `Union` of `X` and `Y` routed by `k`, keeping `j`. The +`discriminator` routing the union does so as one beside it does, a `mapping` entry naming no schema +reported at the entry under the schema writing it, and it routes by name the schemas the union lists +([`discriminator-value`](#discriminator-value)). Its variants take their IDs from the branch's +pointers, its `$ref` and inline branches conjoin as above, and the entry keeps nothing of the union +or of a `discriminator` it writes, whose extensions and keys OpenAPI defines for no Discriminator +Object ride on the `Union` holding it ([`vendor-extensions`](#vendor-extensions)), what else the +entry writes merging as any entry does ([`allof-inline-residue`](#allof-inline-residue)). Whether a +route names the schema is read at the position, as for a union beside the `allOf`, so an inline +schema below a discriminated base no route names distributes. A union on an entry does not +distribute where it is one of the shapes below, where its branches declare no shape, or where it is +one of two entry unions declaring shape under one keyword, since distributing either would drop the +other and no rule ranks them. It is kept as what an entry writes is +([`allof-inline-residue`](#allof-inline-residue)): once, on the node the position lowers to, under +its keyword, or with its entry kept whole where that rule says, as for one nested past the +flattening depth. Where another union distributes, that node is the distributed `Union`. +Distribution cannot reach these shapes: + +1. the structural rest is not a `Model`: a `const`, an `enum`, a scalar, or keywords written with no `type` where the kinds the position lowers to are not an object alone, beside a branch that may be no object, or where a cycle cuts the read short and the keywords infer no object, so there are no composition fields for the variants to carry; 2. a branch is a `$ref` that names no referent the compilation resolves — a cross-document target it does not intern, an undeclared component, a pointer addressing no schema — so it declines rather than composing a variant whose branch quietly went missing; -3. the schema declares a `discriminator`, the one standing with the union, and a branch composes +3. the schema declares a `discriminator`, the one written with the union, and a branch composes the schema through `allOf`, at any depth (`Cat: {allOf: [{$ref: Pet}, …]}`): the schema is the base of a hierarchy the discriminator routes, which a union of composed variants would no longer be the base of; @@ -4304,10 +5040,10 @@ reach these shapes: [`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) naming the union, and no other; the unions inline entries write are read together as two beside the `allOf` are, and so are a union and the one the position passes over for it (above), and a `oneOf` and an `anyOf` sharing no value with each other, beside - a body that is not a `Model`, leave no instance whatever it admits: the position lowers as its - body does in every spelling, keeping both, with that warning alone; -5. every branch but a null one of a union the body would distribute is dead (above), so no variant - would hold a value: the position lowers as the body does, and the schema draws the warning naming + a rest that is not a `Model`, leave no instance whatever it admits: the position lowers as its + rest does in every spelling, keeping both, with that warning alone; +5. every branch but a null one of a union the rest would distribute is dead (above), so no variant + would hold a value: the position lowers as the rest does, and the schema draws the warning naming the dead branches beside the info, a report a schema composing it through `allOf` takes for its own ([`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts)). Such a union on an `allOf` entry is read against the rest of the `allOf`, its own entry aside, and kept as an entry's keyword is, @@ -4315,25 +5051,86 @@ reach these shapes: ([`allof-inline-residue`](#allof-inline-residue)). Its entry is a conjunct sharing no kind with the rest, so the schema draws that rule's warning, a null the rest admits and no branch does being no value they share; where a null branch takes it, the schema draws the warning naming - the dead branches instead, which says that no instance but null satisfies it. An elected + the dead branches instead, which says that no instance but null satisfies it. A chosen union of null alone has no branch to mark dead, so where it and the union passed over share no value, the schema draws the warning of shape 4 naming the two instead. A dead branch beside a live one on an entry is named as admitting no value the rest of the `allOf` admits, which may hold kinds beside an object that no branch holds. -In each, whatever structural body the schema declares is lowered — `properties` or a declared +In each, whatever structural rest the schema declares is lowered — `properties` or a declared `type` yields a `Model` or typed node — and the union branches are kept verbatim in `Unmodeled["openapi:oneOf"]` / `["openapi:anyOf"]` (`degraded_lowering`), reported as an info -`openapi/degraded-construct` at the schema naming which applied; in case 2 the broken +`openapi/degraded-construct` at the schema naming which applied, the union said to intersect with the +structural keywords beside it, or with the rest of the schema where it writes none. In case 4, where the +schema draws the warning that no value satisfies it, that one warning says instead what it lowered as +and each union of its conjunction it keeps verbatim, by its path from the schema, and no union draws +an info of its own, beside the rest or on an entry, so one defect draws one finding in every +spelling. In case 2 the broken reference is reported as well, as an `openapi/unresolved-ref` error, or, on a loop the compiler reads, by the loop's one `openapi/cyclic-ref` ([`reference-cycles`](#reference-cycles)). Case 1's -body-less sibling leaves nothing to build: it reduces to `any`, and the sibling itself is kept by -[`shape-applicator`](#shape-applicator) rather than dropped, so the union's diagnostic and the -sibling's are both reported. A `null` branch in this shape is **not** lifted to `Nullable`: the -union it belongs to is no longer structural, so lifting one branch out of it would assert something -the lowered type does not say. The degradation is that the generated SDK is *under-constrained* — it -admits values the union would reject — which is why the branches must survive for a validating -emitter to reach. +sibling with no rest of its own leaves nothing to build: it reduces to `any`, and the sibling itself +is kept by [`shape-applicator`](#shape-applicator) rather than dropped, so the union's diagnostic +and the sibling's are both reported. A `null` branch in this shape is **not** lifted to `Nullable`: +the union it belongs to is no longer structural, so lifting one branch out of it would assert +something the lowered type does not say. The degradation is that the generated SDK is +*under-constrained* — it admits values the union would reject — which is why the branches must +survive for a validating emitter to reach. + +Beside a value set the position or an inline entry of its `allOf` writes, an `enum` or a `const`, +where the rest of the conjunction admits no null, a union some branch of which is no value set +([`allof-refinement`](#allof-refinement)), whether the rest would keep it or conjoin its branches +with the rest's kind (above), is judged member by member: the value reader judges each member +against a `Union` of the branches, as the IR judges a value against a type, exclusive for a `oneOf`, +each branch saying yes, no or unknown of it: a `oneOf` admits a member +exactly one branch admits and every other refuses, and refuses one two branches admit or every one +refuses, and an `anyOf` admits a member one admits and refuses one every one refuses, whatever +another leaves unknown; any other member is unknown. A branch is read through its `$ref`s to the +schema object whose `type`, value set and bounds it writes; a `pattern` outside the subset the +reader reads ([patterns](../ir/values.md#patterns)) or a `format` there, or a keyword it does not +read, such as `not` or one its dialect does not define, leave unknown a member the branch's other +keywords admit, and refuse one they refuse, as a schema's keywords conjoin; an `allOf` or keywords +beside a `$ref`, or kinds the kind-inference policy read, leave it unknown of a member. An unknown +member is no refusal: it stays. +So `{enum: [ab, abcd], oneOf: [{maxLength: 3}, {maxLength: 4}, {pattern: '^(?=a)'}]}` refuses `ab`, +which two branches admit, and keeps `abcd`, which one admits and the pattern leaves unknown. The +members are judged whatever kinds of value they are, and against a union a `$ref` the position +conjoins names, beside it or as an `allOf` entry, as against one written beside it, a member that +union refuses left out and reported alike: `{$ref: U, enum: [1, 1.5]}`, `U` being `{oneOf: [{type: +integer}, {type: number}]}`, is the `Enum` of `1.5`, as its flat twin is. There the `$ref` is kept, +as beside any value set narrowing it, and a refusal by several unions names each. Where every member satisfies the union, it says +nothing: it is neither kept nor reported, nor are its dead branches, and the position is the value +set, in every spelling, written flat, bare, beside an `allOf` or on its entry: `{type: string, enum: +[a, b], oneOf: [{type: string}, {type: integer}]}` is the `Enum` of `a` and `b` keeping nothing. +That holds only where every key each branch writes says nothing the set does not: a kind, a value +set, a bound, a `$ref` or a union, which the judgment reads, or a key saying nothing of an instance +that is no note and no extension. A note, an example among them, or an extension on a branch keeps +the union once, as where it refuses a member, its dead branches reported, the position still the +value set: `{enum: [a, b], oneOf: [{type: string, description: d}, {type: integer}]}` is the `Enum` +of `a` and `b` keeping the `oneOf`; but one on a branch writing one member alone is that member's, +as beside a union of value sets ([`allof-refinement`](#allof-refinement)), and keeps no union. +Where the union refuses some, the position is what a flat `enum` of the others lowers to, the `Enum` +of them, or the `Union` of their literals where they are of several kinds +([`enum-const`](#enum-const)). Where it refuses every one, the position is the closed `Enum` with +no member, typed as the value set types it, by no primitive where its members are of several kinds. +Either way the members refused draw one `openapi/unsatisfiable-schema` warning, at the position, +however the set and the union are written, flat, over `allOf` entries or behind a `$ref`, naming +each, how many of the refusing union's branches it satisfies and, where several refuse, that union; +none is drawn where a member is written, so where the report sits turns on no order of entries, as +for value sets sharing no member. Either way the union is kept once, as beside any rest +that is no object, and the `enum` or the `const` as `validation_only`, which holds the members +refused: `{enum: [a, b], oneOf: [{type: string}, {enum: [a]}]}` is the `Enum` of `b`, `a` +satisfying two branches, `{enum: [a, 1, true], anyOf: [{type: string}, {type: integer}]}` the +`Union` of the literals `a` and `1`, and `{const: a, anyOf: [{type: string, minLength: 2}, {type: +integer}]}` the closed `Enum` with no member. Where the union refuses no member and leaves one +unknown, a member is written by no such value set, or the judgments, a member against a branch +each, pass 4096, the union is as its branches' kinds read it. Beside a second union passed over, +a conjunct of the rest (above), the members judged are those of the set that union admits, where +its every branch states values, and a union refusing none is kept as the one passed over is, the +position the value set as written: `{const: b, type: string, anyOf: [{enum: [b]}, {enum: [c, a]}], +oneOf: [{const: a, minLength: 1}, {const: c}]}` is the closed `Enum` with no member, as it is +written without its `anyOf`. Where the union passed over leaves the set no member, no branch of the +union chosen shares a value with the rest: each is named dead, and the position is the closed +`Enum` with no member keeping both, as beside a union of value sets. A schema a `discriminator` on an `allOf` ancestor routes to, by a `mapping` key or by its name as a component ([`discriminator-value`](#discriminator-value)), is not distributed either: the route names @@ -4346,8 +5143,14 @@ its last `Mixin` names a `Union` of the union's branches, each lowered as a unio lowers it. No schema occupies that `Union`, so it is minted at the keyword writing the union, `…/Cat/oneOf` beside the `allOf` or `…/Dog/allOf/1/oneOf` on an entry, in the `composed` namespace, apart from the entry's own node, which an outside `$ref` to the entry still finds. The -`Model` keeps nothing of the union, what an entry writes beside it merging as any entry does, and a -`discriminator` standing with the union is the `Union`'s, routing its variants, so the `Model` +`Model` keeps nothing of the union, what an entry writes beside it merging as any entry does, nor of +a union the conjunction passes over: wherever it is written, on the entry holding the other, on an +entry of its own at any depth or beside the `allOf`, the `Union` keeps it once under its keyword, +as one entry writing both keeps it: as `validation_only` with an info +`openapi/validation-only-keyword` where its branches declare no shape against the position, else as +`degraded_lowering` with an info `openapi/degraded-construct`, its provenance and its info where it +is written, so every spelling of the pair lowers alike. A +`discriminator` written with the union is the `Union`'s, routing its variants, so the `Model` holds none, but for one naming the empty string as its tag, which the `Union` cannot hold and the `Model` lowers and keeps as [`discriminator`](#discriminator) says. It is reported as an info `openapi/composition-lowering` at the schema. Whether a route names the schema is read at its position, and a discriminator written beside a union routes by name @@ -4359,66 +5162,67 @@ kind a branch admits, null included, and a `format`, an `enum`, a `const` or an is held to, read as [`allof-refinement`](#allof-refinement) reads what a conjunct admits and within its bounds, a read cut short saying none. An `items` written as a list, a draft's tuple, is said by no branch. Where the branches declare shape (below) and say every -keyword that makes a body, the schema means the union alone, and it lowers as if those keywords +keyword of the rest, the schema means the union alone, and it lowers as if those keywords were not written: `{type: string, anyOf: [{$ref: V4}, {$ref: V6}]}` as `{anyOf: [{$ref: V4}, {$ref: V6}]}`, and `{type: object, oneOf: [{$ref: A}, {$ref: B}]}` as the union of `A` and `B`, not a union of models composed over each, which a `discriminator` beside it routes. A `nullable` beside such a union reads as it reads beside any union ([`nullable`](#nullable)), and a keyword the branches do not all say, a bound or a `format` among them, is kept unread as beside a -union ([`shape-applicator`](#shape-applicator)). Branches declaring no shape only narrow the body, +union ([`shape-applicator`](#shape-applicator)). Branches declaring no shape only narrow the rest, which stays validation logic beside it whatever they repeat, and a `discriminator` beside the union -keeps the body where a branch composes it (shape 3). +keeps the rest where a branch composes it (shape 3). -A `discriminator` beside any of these shapes whose body lowers to a `Model`, shape 3 written on an -`allOf` entry among them and shape 5 on an entry, stays on that `Model` only when every type it -routes to is a subtype of it -at any depth (`ir.IsSubtype`): each `mapping` target, -the `defaultMapping`, and each component a `$ref` branch names, which it routes to by name — +A `discriminator` beside any of these shapes whose rest lowers to a `Model`, shape 3 written on an +`allOf` entry among them and shape 5 on an entry, stays on that `Model` and routes as a model's does +([`discriminator`](#discriminator)): to the model itself and to its subtypes at any depth +(`ir.Supertypes`, which counts no mixin), each component a `$ref` branch names routed by its name — `oneOf`'s branches where `oneOf` and `anyOf` are both declared, since `oneOf` wins. An inline branch, -or one naming no component, is no route unless the `mapping` names it, and a route to the `Model` -itself is none of its subtypes, though `pass/validate` takes one where the model is concrete. -Otherwise the whole object (`propertyName`, `mapping`, `defaultMapping`) is kept verbatim in -`Unmodeled["openapi:discriminator"]` on the node keeping the union, with an info -`openapi/degraded-construct` at the discriminator; a subtype keeps the `DiscriminatorValue` its -mapping key gives it, since that is still the tag its instances carry, and a body the move leaves -holding a map and nothing else lowers to that map's `MapT` ([containers](../ir/containers.md)). A -union whose branches declare no shape (`validation_only`) is held to the same rule. A multi-typed -body leaves no discriminator to settle: [`type-arrays`](#type-arrays) keeps it on the `Union` the -body lowers to, beside the kept union. The compiler decides once every node is interned -(`compile.Settlement`), because neither the walk nor the source schemas can answer it: a subtype -declared after the `Model` has no `Base` while the `Model` lowers, and a schema whose `allOf` names -the `Model` may still lower to no subtype — an `enum`, a `const`, or an alias over a `$ref` beside -it. +or one naming no component, is no route unless the `mapping` names it. A route to a type that is +neither the model nor a subtype of it is set aside, as on any model: an entry or the `defaultMapping` +kept verbatim, and a branch's route by name left unwritten, with one info `openapi/unhomed-construct` +at the branch, the union already holding the `$ref` verbatim. Where every route is set aside and none +stays typed, as at a position with no name of its own, the whole object (`propertyName`, `mapping`, +`defaultMapping`) is kept verbatim in `Unmodeled["openapi:discriminator"]` on the node keeping the +union, with one info `openapi/degraded-construct` at the discriminator; a subtype keeps the +`DiscriminatorValue` its mapping key gives it, since that is still the tag its instances carry, and a +rest that leaves holding a map and nothing else lowers to that map's `MapT` +([containers](../ir/containers.md)). A union whose branches declare no shape (`validation_only`) is +held to the same rule. A multi-typed rest leaves no discriminator to settle: +[`type-arrays`](#type-arrays) keeps it on the `Union` the rest lowers to, beside the kept union. The +compiler decides once every node is interned (`compile.Settlement`), because neither the walk nor the +source schemas can answer it: a subtype declared after the `Model` has no `Base` while the `Model` +lowers, and a schema whose `allOf` names the `Model` may still lower to no subtype — an `enum` or a +`const` beside it. A union whose branches declare no shape at all (`oneOf: [{required: [a]}, {required: [b]}]`) is not -a degradation and is not one of these shapes: it narrows the body without reshaping it, which is +a degradation and is not one of these shapes: it narrows the rest without reshaping it, which is validation logic, so it is kept under `validation_only` with the keyword family of [boundaries](../ir/boundaries.md#validation-only-constructs) and reported as an info `openapi/validation-only-keyword` at the schema ([`validation-only`](#validation-only)). A `$ref` branch declares shape and a boolean one declares none. An inline branch declares shape where one keyword it writes does, and a keyword is judged alike whether the branch writes it alone or beside -the body's own `type`, so repeating the body never changes a verdict: +the rest's own `type`, so repeating the rest never changes the answer: 1. A keyword that documents the instance (`title`, `description`, `$comment`, `deprecated`, `examples`, `example`, `externalDocs` or an `x-` extension), names the schema (`$anchor`, `$dynamicAnchor`), holds schemas it does not apply (`$defs`), says whether it may be null - (`nullable`), or only narrows what the body shapes declares none, whatever it holds. The + (`nullable`), or only narrows what the rest shapes declares none, whatever it holds. The narrowing keywords are `required`, the value constraints and collection bounds of [`constraints`](#constraints), and the validation-only keywords of [boundaries](../ir/boundaries.md#validation-only-constructs), an `unevaluatedProperties` other than `false` among them. A keyword written `null` is left out ([`null-keywords`](#null-keywords)). -2. `type`, `format`, `enum` and `const` declare none where every value the body admits holds to +2. `type`, `format`, `enum` and `const` declare none where every value the rest admits holds to them, null aside for `type`, read as [`allof-refinement`](#allof-refinement) reads what a - conjunct admits: from the body's own keywords and its `allOf`, across each `$ref`, leaving out - the unions the body itself writes. So `type: object` beside an object body declares none, nor + conjunct admits: from the rest's own keywords and its `allOf`, across each `$ref`, leaving out + the unions the rest itself writes. So `type: object` beside an object rest declares none, nor does `type: [object, 'null']`, a `type` naming only `null` contributes the null and nothing else, and `format: date` beside a bare `type: string` declares shape. `format: password` asks for redaction and names no form ([`password`](#password)), so it declares none, as an `x-sensitive` asking the same declares none by point 1: an SDK reads neither reason's entry, so a secret one branch alone writes is lost to it either way. 3. `properties` and `items` declare none where each property the branch writes, and its element, - restates the body's declarations of it: those in the body's own `properties` or `items`, and in + restates the rest's declarations of it: those in the rest's own `properties` or `items`, and in a schema its `allOf` composes, through any nesting and across `$ref`s, but not in a union's branch. A schema restates its declarations where it is a boolean, which says nothing or only forbids what it is written for; where one of them is written alike against one base, as @@ -4431,7 +5235,7 @@ the body's own `type`, so repeating the body never changes a verdict: `{type: string, format: uri, minLength: 1}`, `{type: string, minLength: 2}` restates `{type: string}`, `{type: string, format: uri}` restates `{type: string}` declared beside `{format: uri}` but not `{type: string}` alone, and `{$ref: X}` restates - `{allOf: [{$ref: X}], description: d}`. A property or element none of the body's declarations + `{allOf: [{$ref: X}], description: d}`. A property or element none of the rest's declarations names is new shape. 4. An `allOf` declares none where each conjunct declares none, judged as the schema writing it is, so `{allOf: [{required: [a]}]}` reads as `{required: [a]}`. A `$ref` conjunct of a branch itself @@ -4441,17 +5245,17 @@ the body's own `type`, so repeating the body never changes a verdict: `discriminator`, `readOnly`, `writeOnly`, `default`, `xml`, the content vocabulary, `$id`, `$schema`, `$vocabulary` and any keyword of no vocabulary. -A branch declaring shape falls to the shapes above. The branches and the body are read within +A branch declaring shape falls to the shapes above. The branches and the rest are read within the bounds of [`allof-refinement`](#allof-refinement), which a union's branches share, an `enum` -a branch writes counting its members, and the body only as far as they need. The body is read +a branch writes counting its members, and the rest only as far as they need. The rest is read twice, each reading within bounds of its own: first what the schema itself writes, its own keywords and its own `properties` and `items`, nothing it composes, which judges every branch; then, for each -branch that reading does not find restating, the whole body as points 2 and 3 read it. A branch +branch that reading does not find restating, the whole rest as points 2 and 3 read it. A branch restating the first restates the second, more declarations admitting less, so the first settles what the schema's own keywords settle however long its composition, and where it does not finish it settles none, so which branches it settles never turns on their order. Within a reading, a branch writing only keywords point 1 names reads none of it, the declarations of what a schema nests are -read only where it nests something, and what the body declares of one property or element is read +read only where it nests something, and what the rest declares of one property or element is read once, however many branches restate it. A read that does not finish says nothing, so its union is judged as one whose branches declare shape. @@ -4459,34 +5263,63 @@ judged as one whose branches declare shape. `discriminated-union-distributed`, `unhomed-keywords`, `keywords-at-every-outcome`, `union-restated-branches`, `union-restated-type`, `union-inline-branches`, `allof-union-branch` -- Codes: `openapi/composition-lowering`, `openapi/degraded-construct`, `openapi/unresolved-ref`, - `openapi/validation-only-keyword` -- Tests: `e2e.TestElection_ANullBranchIsDeadWhereTheUnionPassedOverKeepsNullOut`, +- Codes: `openapi/composition-lowering`, `openapi/degraded-construct`, `openapi/unsatisfiable-schema`, + `openapi/unresolved-ref`, `openapi/validation-only-keyword` +- Tests: `schema.TestUnion_NoLiveBranchDrawsOneFindingSayingWhatItKeeps`, `schema.TestKeptUnionsWhy_SaysWhatTheUnionIntersectsWith`, + `e2e.TestChoice_ANullBranchIsDeadWhereTheUnionPassedOverKeepsNullOut`, + `schema.TestValueSetUnion_BesideAUnionPassedOverIsReadAgainstTheSet`, + `e2e.TestUnionBesideValueSet_TypedBranchesEveryMemberSatisfiesSayNothing`, + `e2e.TestUnionBesideValueSet_AConstSatisfyingTheUnionSaysNothing`, + `e2e.TestUnionBesideValueSet_ABranchSayingMoreThanTheSetIsKept`, + `e2e.TestUnionBesideValueSet_TypedBranchesRefusingSomeMembersNarrowTheEnum`, + `e2e.TestUnionBesideValueSet_TypedBranchesRefusingEveryMemberLeaveNoValue`, + `e2e.TestUnionBesideValueSet_TypedBranchesRefusingTheConstLeaveNoValue`, + `e2e.TestUnionBesideValueSet_AMemberTheReaderCannotJudgeLeavesTheUnion`, + `e2e.TestUnionBesideValueSet_AMixedSetIsJudgedMemberByMember`, + `e2e.TestUnionBesideValueSet_EachBranchIsCountedThreeWays`, + `schema.TestReferencedUnions_JudgeASetAsOneWrittenBesideIt`, + `e2e.TestUnionBesideBody_ADeadBranchBesideObjectsAndStringsIsNamedSo`, + `e2e.TestUnionBesideBody_ALoneNullBranchLiftsOntoTheObject`, + `e2e.TestUnionBesideBody_ATypeListBranchIsSplitByKind`, + `e2e.TestUnionBesideBody_ARefBodyConjoinsEachBranchAsItsAllOf`, + `e2e.TestUnionBesideBody_ARefBodyConjoinsWhereverItsConjunctsNest`, + `schema.TestUnionBeside_ARefBodyConjoinsEachBranchAsItsAllOf`, + `schema.TestUnionBeside_ARefBodysBoundsAreTheUnionsAsInline`, + `schema.TestUnionByKind_ATypeListHoldingAnObjectSplitsOverItsKinds`, + `schema.TestUnionBeside_ADiscriminatorOnAnEntryIsAsWrittenFlat`, + `schema.TestUnionBeside_ADiscriminatorBesideADistributingAllOfIsKeptAsWhereItDoesNot`, + `schema.TestUnionBeside_AnEntrysTypeAndFormatLowerAsTheirFlatTwin`, + `schema.TestUnion_ANullOnlyBodyNamesItsDeadBranchesAtTheUnion`, + `e2e.TestUnionBesideBody_AValueSetBesideThePositionsUnionLowersAsFlat`, + `schema.TestUnion_ThePolicysNullIsSaidToBeThePolicys`, + `schema.TestUnion_ThePolicysNullableLeavesNullAloneWhereNoBranchLives`, + `schema.TestCollapsedUnion_APassedBranchSayingNothingOfNullSharesIt`, + `schema.TestCollapsedUnion_AWidenedNullReportsTheBranchesAClosureRefuses`, `schema.TestUnion_ANullBranchOfAPairIsDeadWhereTheOtherKeepsNullOut`, - `schema.TestUnion_APairWhoseElectedVariantsAllAdmitNullAloneKeepsThem`, + `schema.TestUnion_APairWhoseChosenVariantsAllAdmitNullAloneKeepsThem`, `schema.TestUnion_ADeadNullBranchOfAPairIsReportedByTheNullKeptOut`, `schema.TestUnion_AConstNullPairBesideARefWarnsOnceWhereverWritten`, `schema.TestUnion_AUnionPassedOverLeavingTheBodyNullAloneIsApartWhereverWritten`, - `schema.TestUnion_APairSharingNullAloneWithANullableBodyIsItsModelWhereverWritten`, - `e2e.TestElection_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody`, - `e2e.TestElection_AUnionSharingAKindWithAScalarBodyLowersAsBefore`, - `e2e.TestElection_AnEntryTypeSharingNoKindWithItsUnionLowersAsBesideTheAllOf`, + `schema.TestUnion_APairSharingNullAloneWithANullableBodyIsNullAloneWhereverWritten`, + `e2e.TestChoice_AUnionSharingNoKindWithABodyThatIsNoModelLowersAsTheBody`, + `e2e.TestChoice_AUnionRestatingAScalarBodyIsKeptByTheBody`, + `e2e.TestChoice_AnEntryTypeSharingNoKindWithItsUnionLowersAsBesideTheAllOf`, `e2e.TestCompile_ADeadBranchIsReadAgainstWhatTheRestAdmits`, `e2e.TestCompile_AReadPastTheAdmissionCapsKeepsItsKinds`, `e2e.TestCompile_ABranchPastTheAdmissionCapsBesideANullableBodyLives`, `e2e.TestCompile_ABranchIsDeadWhereItOrItsBodyAdmitsNoNull`, - `e2e.TestCompile_ABodyWhoseNullTheWalkCannotFinishMayAdmitIt`, - `schema.TestAdmission_ACapStopsTheElectionsSummaryAlone`, + `e2e.TestCompile_ABodyKeepsOutTheNullItsChainKeepsOutAtAnyDepth`, + `schema.TestAdmission_ACapStopsTheChoicesSummaryAlone`, `schema.TestDeadBranch_ReadsABranchPastTheCapsByItsKinds`, `e2e.TestCompile_ARestOfAValueSetIsNotSaidToRefuseABranchItAdmits`, - `e2e.TestCompile_AUnionBesideAnyRestDrawsOneWarningAtMost`, `schema.TestOneOf_CoDeclaredNotDistributedReasons`, `schema.TestLower_AllOfWithOneOfKeepsBoth`, + `e2e.TestCompile_AUnionBesideAnyRestDrawsOneWarningPerUnionAtMost`, `schema.TestOneOf_CoDeclaredNotDistributedReasons`, `schema.TestLower_AllOfWithOneOfKeepsBoth`, `e2e.TestAllOfUnion_AUnionSharingNoKindWithTheRestIsKeptNotDistributed`, `schema.TestOneOf_CoDeclaredKeywordsEveryBranchSaysLeaveTheUnionAlone`, `schema.TestOneOf_CoDeclaredTypeReadsNullableByItsDialect`, `schema.TestOneOf_CoDeclaredInlineBranchIsConjoinedByItsNode`, `schema.TestOneOf_CoDeclaredBranchNoObjectSatisfiesIsNoVariant`, - `schema.TestOneOf_CoDeclaredUnpreservableBranchIsNotAnnounced`, - `schema.TestOneOf_CoDeclaredBranchReadCutShortIsComposed`, + `schema.TestOneOf_CoDeclaredBranchIsKeptWithoutAnExtensionNoJSONHolds`, + `schema.TestOneOf_CoDeclaredBranchOnALoopKeepsItsRef`, `e2e.TestVariantBounds_AVariantNamesOnlyAnObjectBranchAsItsBase`, `e2e.TestVariantBounds_AVariantOverATypeListComposesItsObject`, `e2e.TestVariantBounds_AVariantKeepsATypeListOrAUnionHoldingNoLoneObject`, @@ -4502,32 +5335,33 @@ judged as one whose branches declare shape. `e2e.TestCompile_AMappingToADeadBranchIsNoRoute`, `e2e.TestCompile_TheNameOfADeadBranchIsNoRoute`, `e2e.TestCompile_ADefaultMappingToADeadBranchIsNoRoute`, - `e2e.TestCompile_ADiscriminatorBesideAUnionNoBranchOfWhichLivesIsKeptWhole`, + `e2e.TestCompile_ADiscriminatorBesideAUnionNoBranchOfWhichLivesKeepsItsOwnRoute`, `schema.TestDiscriminator_ARouteToADeadBranchRoutesNowhere`, - `e2e.TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureKept`, + `e2e.TestEntryClosure_ADeadBranchDeclaringMembersLeavesTheClosureTyped`, `e2e.TestCompile_TwoUnionsOnEntriesKeepTheirBranchesApart`, `e2e.TestCompile_AnEntryUnionNoBranchOfWhichLivesIsKeptOnTheEntry`, `e2e.TestCompile_AnEntryUnionBesideARestAdmittingNullIsKeptAndWarns`, - `e2e.TestCompile_AnEntryUnionWhoseNullBranchAloneLivesSaysWhatNullMeets`, + `e2e.TestCompile_AnEntryUnionWhoseNullBranchAloneLivesSaysWhatNullIntersects`, `e2e.TestCompile_ABodyBesideANullBranchAndNoLiveOneAdmitsNull`, `schema.TestOneOf_TheWarningOfADeadBranchSaysWhereTheUnionIs`, `e2e.TestCompile_ABranchBesideABodyThePolicyMadeAnObjectLives`, - `schema.TestOneOf_AnUnpreservableDeadBranchIsNotAnnounced`, + `schema.TestOneOf_ADeadBranchIsKeptWithoutAnExtensionNoJSONHolds`, `schema.TestOneOf_ADeadBranchIsReadForTheNullTheBodyAdmits`, `schema.TestOneOf_CoDeclaredBareRequiredConjoinsObjectBranches`, `schema.TestUnion_AListOfItemsBesideTheBranchesIsNotSaid`, `schema.TestAllOf_AUnionEntryDistributesAsBesideTheAllOf`, - `e2e.TestElection_TwoUnionsBesideABodyDistributeTheOneOf`, - `e2e.TestElection_BothKeywordsOnOneEntryDistributeTheOneOf`, - `e2e.TestElection_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf`, - `e2e.TestElection_AnEntryWritingBothBesideAnotherOneOfDistributesNeither`, - `e2e.TestElection_BothKeywordsOnOneEntryOfARoutedSubtypeKeepTheAnyOfAsBeside`, - `e2e.TestElection_TwoUnionsOverABodyLowerAlikeWhereverWritten`, - `e2e.TestElection_AnEntryHoldingBothIsJudgedWithoutThemAtAnyDepth`, + `e2e.TestChoice_TwoUnionsBesideABodyDistributeTheOneOf`, + `e2e.TestChoice_BothKeywordsOnOneEntryDistributeTheOneOf`, + `e2e.TestChoice_BothKeywordsOnOneEntryKeepWhatTheyKeepBesideTheAllOf`, + `e2e.TestChoice_AnEntryWritingBothBesideAnotherOneOfDistributesNeither`, + `e2e.TestChoice_BothKeywordsOnOneEntryOfARoutedSubtypeKeepTheAnyOfAsBeside`, + `e2e.TestChoice_TwoUnionsOverABodyLowerAlikeWhereverWritten`, + `e2e.TestChoice_AnEntryHoldingBothIsJudgedWithoutThemAtAnyDepth`, `schema.TestUnion_AnEntryHoldingBothIsReadWithoutThemWhereverListed`, - `e2e.TestElection_TwoAnyOfUnionsBesideABodyDistributeNeither`, - `e2e.TestElection_TwoOneOfUnionsBesideABodyDistributeNeither`, + `e2e.TestChoice_TwoAnyOfUnionsBesideABodyDistributeNeither`, + `e2e.TestChoice_TwoOneOfUnionsBesideABodyDistributeNeither`, `schema.TestUnion_ARoutedSubtypeComposesItsUnionAsAMixin`, + `schema.TestUnion_ARoutedSubtypeKeepsAUnionItPassesOverOnItsMixin`, `schema.TestUnion_ARoutedSubtypeSharedByTwoOperationsComposesItsUnionOnce`, `schema.TestComposeMixin_NeedsAModel`, `schema.TestUnion_AnEntryUnionNoRouteNamesDistributesAsBeside`, `schema.TestAllOf_ADiscriminatedEntryUnionDistributesAsBeside`, @@ -4540,7 +5374,7 @@ judged as one whose branches declare shape. `schema.TestOneOf_CoDeclaredUnresolvableBranchIsNotDistributed`, `schema.TestOneOf_CoDeclaredBranchAfterASkippedOneIsReported`, `e2e.TestCompile_ABranchOnALoopIsReportedOnlyAsTheLoop`, - `schema.TestDiscriminatorBesideUnion_LeavesAMapWhenItMoves`, + `schema.TestDiscriminatorBesideUnion_AMapKeepingARouteStaysAModel`, `schema.TestOneOf_CoDeclaredRestatingBranchDeclaresNoShape`, `schema.TestOneOf_CoDeclaredBranchSayingMoreDeclaresShape`, `schema.TestOneOf_CoDeclaredBranchSayingMoreBesideANonModel`, @@ -4556,20 +5390,16 @@ judged as one whose branches declare shape. `e2e.TestUnionNullVariant_AUnionAloneOnAnEntryIsTheReferenceItsBareSpellingIs`, `e2e.TestUnionAlone_OnAnEntryLowersAsWrittenAtThePosition`, `e2e.TestUnionAlone_ABodyBesideItStillDistributes`, - `e2e.TestElection_TwoUnionsAloneLowerAsOneSchemaWritingBoth`, - `e2e.TestElection_AUnionOfNullAloneBesideObjectsLowersAsTheOtherUnsatisfiedPairs`, - `e2e.TestElection_UnionsSharingNullAloneWithEachOtherDrawOneWarning`, - `e2e.TestElection_AUnionOfNullAloneBesideAnAllOfDrawsOneWarning`, - `e2e.TestElection_ANullBranchIsReadAgainstTheUnionPassedOver`, + `e2e.TestChoice_TwoUnionsAloneLowerAsOneSchemaWritingBoth`, + `e2e.TestChoice_AUnionOfNullAloneBesideObjectsLowersAsTheOtherUnsatisfiedPairs`, + `e2e.TestChoice_UnionsSharingNullAloneWithEachOtherDrawOneWarning`, + `e2e.TestChoice_AUnionOfNullAloneBesideAnAllOfDrawsOneWarning`, + `e2e.TestChoice_ANullBranchIsReadAgainstTheUnionPassedOver`, `schema.TestUnion_ANullBranchIsReadAgainstTheUnionPassedOver`, - `e2e.TestElection_TwoUnionsSharingNoValueWarnOnceBesideAnyBody`, + `e2e.TestChoice_TwoUnionsSharingNoValueWarnOnceBesideAnyBody`, `schema.TestUnion_TwoUnionsSharingNoValueBesideAScalarKeepBoth` - Status: partly built: a discriminator routing to the model holding it moves though that route is - legal (#1806). A union alone on an inline `allOf` entry distributes beside a `discriminator` - written beside the `allOf`, and beside an `allOf` of notes on its own entry, where the same union - with the `discriminator` or the notes written beside it stands alone (#2104, #2105). A union - sharing a kind with a scalar body is the body's `Scalar` keeping it beside the body's own keywords, - and a `Union` beside an `allOf` of the body or on one of its entries (#2108). + legal (#1806). ### `union-beside-ref` @@ -4592,7 +5422,8 @@ Keywords conjoin, so `{const: a, enum: [a, b]}` admits `a` alone rather than bei document, and `{oneOf: […], anyOf: […]}` demands both, yet a position lowers to one node. Three families compete for it: the value keywords `const`, `enum` and `allOf`, picked in that order; the two union combinators, where the one whose branches declare shape against the position -wins, the `oneOf` where both or neither do; and a parameter's or header's `schema` beside +wins, the `oneOf` where both or neither do, the one `oneOf` beside several `anyOf`s, and none where +one keyword is written several times alone; and a parameter's or header's `schema` beside its `content`, where `content` wins, since a media-type entry names both a schema and the media type serializing it and the IR models both ([`content-parameters`](#content-parameters)). The IR has no intersection combinator ([boundaries](../ir/boundaries.md#deliberate-exclusions), as for @@ -4600,8 +5431,13 @@ intersection combinator ([boundaries](../ir/boundaries.md#deliberate-exclusions) — the most it can express there — and each keyword passed over is kept verbatim in `Unmodeled["openapi:"]` under `degraded_lowering` at that keyword's own pointer, reported as one `openapi/degraded-construct` naming what was picked and what was kept: an info, and a -warning where a parameter's or header's `schema` is passed over for its `content`. Two consequences -are deliberate. The elected combinator still becomes a `Union` rather than degrading to the top +warning where a parameter's or header's `schema` is passed over for its `content`. An `enum` the +`const` a position lowers as passes over is kept and reported so wherever either is written, beside +the `allOf` or on any of its entries: `{allOf: [{enum: [a, b]}, {const: b}]}` keeps the `enum` as +`{enum: [a, b], const: b}` does, with that one info at the schema. A `const` and an +`enum` sharing no member admit no value at all, which [`enum-const`](#enum-const) lowers and reports +in place of that info. Two consequences +are deliberate. The chosen combinator still becomes a `Union` rather than degrading to the top type, because that `Union` is a shape the IR *can* express and discarding it as well would model nothing at all. And a `{X, null}` `oneOf` written beside an `anyOf` does **not** collapse to nullable `X` ([type-graph](../ir/type-graph.md#type-references)), because the collapse @@ -4613,18 +5449,25 @@ and an `anyOf` written on one entry of an `allOf` or one each on two, whether it ([`union-beside-structure`](#union-beside-structure)), whichever is written first and whatever kinds the other entries admit, the one passed over kept with its entry; with nothing else conjoining with them, the two lower as one schema writing both does, wherever their entries are. -Written one each on two entries of an `allOf` that refines, the -elected union collapses no more than it does beside the `allOf`, a body beside them or none: the -elected `anyOf: [{type: 'null'}, {$ref: S}]` stays a `Union` of `S` behind a nullable reference, +Written one each on two entries of an `allOf` that refines, or one beside the `allOf` and the +other on an entry, the +chosen union collapses no more than it does beside the `allOf`, the rest beside them or none: the +chosen `anyOf: [{type: 'null'}, {$ref: S}]` stays a `Union` of `S` behind a nullable reference, not a nullable reference to `S`. Where the two share no value, a null only where both admit it, the schema writing them draws the warning of [`allof-disjoint-conjuncts`](#allof-disjoint-conjuncts) once, beside the info, whether or not it writes an `allOf`, and lowers as it would without it; so -do two sharing only a null that the body beside them keeps out, which leaves them no value with it. -Whether they share a value is read once for the position, as the election reads its conjuncts, +do two sharing only a null that the rest beside them keeps out, which leaves them no value with it. +Whether they share a value is read once for the position, as the choice reads its conjuncts, value sets included, so `oneOf: [{type: string, enum: [a]}]` and `anyOf: [{type: string, enum: [b]}]` -share none, and each is named by what it admits, `oneOf: 1 value`; beside a body that is no -`Model` such a pair lowers as that body in every spelling, keeping both, as two sharing no kind -do. The two are conjuncts for +share none, and each is named by what it admits, `oneOf: one of ["a"]`, the members its branches' +value sets write, or the size of a set some branch holds otherwise. The chosen union's branches +are read against the one passed over and the rest, as +[`union-beside-structure`](#union-beside-structure) reads dead branches: one sharing no kind with +them is dead, where every branch is the position lowers as its other conjuncts say, keeping both, +and where only null survives it is the closed empty `Enum` behind a nullable reference +([`union-null-only`](#union-null-only)); the union passed over is kept once, on the node the +position lowers to, a distributed `Union` included, or on the `Union` a subtype a discriminator +routes to composes as a mixin ([`union-beside-structure`](#union-beside-structure)). The two are conjuncts for null too: the reference to the position admits null only where each may, so `{$ref: T, oneOf: [{type: object, properties: {x: {type: string}}}], anyOf: [{type: object}, {type: 'null'}]}`, over an object `T`, is not nullable and draws no `openapi/inferred-nullable`, @@ -4633,16 +5476,19 @@ refinement folds neither union of such a pair into its principal as said, wherev written: the one passed over is kept as one schema writing both keeps it, though its branches declare nothing, as `anyOf: [{}]` does. Where a *structural* sibling is written as well, beside the two or on another entry of the `allOf` holding them on one entry or two, -[`union-beside-structure`](#union-beside-structure) applies instead, which distributes the one whose -branches declare shape against the position, the `oneOf` where both do, and keeps the other on each -variant, an `allOf` that refines being no such sibling but a -conjunction the unions are conjuncts of ([`allof-refinement`](#allof-refinement)). +[`union-beside-structure`](#union-beside-structure) applies instead. It distributes the one whose +branches declare shape against the position, the `oneOf` where both do, and keeps the other once, +on the distributed `Union`. An `allOf` that refines is no such sibling but a conjunction the unions +are conjuncts of ([`allof-refinement`](#allof-refinement)). Beside a scalar +rest a pair lowers as one union does there, in every spelling, one union beside the rest's keywords +and the other on an `allOf` entry among them: the chosen union's `Union` where its branches declare +shape against the rest, else the rest's `Scalar` keeping both. An `allOf` is no rival of an `enum` or a `const` beside it, which is one of its conjuncts -([`allof-refinement`](#allof-refinement)): the value set is elected before a composition there, -each conjunct it beats kept as that rule keeps it, a set its own keywords leave no value standing for +([`allof-refinement`](#allof-refinement)): the value set is chosen before a composition there, +each conjunct it passes over kept as that rule keeps it, a set its own keywords leave no value for the keyword the dispatch picks of it, each reported apart: the keyword passed over with an info, as -below, and each conjunct the set beats as that rule reports it. So the -dispatch passes over the `allOf` only where no value set is elected, keeping it whole where +below, and each conjunct the set passes over as that rule reports it. So the +dispatch passes over the `allOf` only where no value set is chosen, keeping it whole where it writes an inline entry, and else each `$ref` entry under `openapi:$ref`, or `openapi:$ref/` where several are kept, as the `$ref` beside it is kept. A keyword the *picked* lowering never reads — `type: string` beside an `allOf` composing an object, @@ -4651,37 +5497,34 @@ asks the node that was built: `type: object` beside an `allOf` is one the compos asserts, and keeps nothing, and a `type` beside an `allOf` that refines is [`allof-refinement`](#allof-refinement)'s. -- Status: partly built: whether a pair beside a scalar body lowers to the elected `Union` or to the - body's `Scalar` keeping both is #2108's, as for one union: beside the body's own keywords it is the - `Scalar`, where the `allOf` spellings give a `Union`. A pair written one union beside the body's - keywords and the other on an `allOf` entry is #2110's. - Cases: `codeclared-keywords`, `codeclared-schema-content`, `allof-value-set-beside-entry` - Codes: `openapi/degraded-construct` - Tests: `schema.TestCoDeclaredFamily_EveryPassedOverKeywordIsKept`, + `schema.TestAllOf_AnEnumAConstElsewherePassesOverIsKeptAsFlat`, `schema.TestCoDeclaredFamily_UnpreservableIsNotAnnounced`, - `schema.TestUnionCombinators_UnpreservableIsNotAnnounced`, - `e2e.TestElection_BothKeywordsElectTheOneOfWhicheverIsWrittenFirst`, - `e2e.TestElection_TwoUnionsBesideABodyDistributeTheOneOf`, - `e2e.TestElection_BothKeywordsOnOneEntryDistributeTheOneOf`, - `e2e.TestElection_TwoUnionsOverABodyLowerAlikeWhereverWritten`, - `e2e.TestElection_TwoUnionsNoInstanceSatisfiesLowerAlikeWhereverWritten`, - `e2e.TestElection_TwoUnionsAloneLowerAsOneSchemaWritingBoth`, - `e2e.TestElection_AUnionPassedOverThatSaysNothingIsKeptEverywhere`, - `e2e.TestElection_APrincipalUnionBesideAPairAndABodyCollapsesAsBesideTheAllOf`, - `e2e.TestElection_TwoUnionEntriesElectByCompetingKeywords`, - `e2e.TestElection_AnEntryWritingBothElectsAgainstThePosition`, - `e2e.TestElection_AUnionPairLowersAlikeInEverySpelling`, + `schema.TestUnionCombinators_AKeptBranchSetDropsAnExtensionNoJSONHolds`, + `e2e.TestChoice_BothKeywordsChooseTheOneOfWhicheverIsWrittenFirst`, + `e2e.TestChoice_TwoUnionsBesideABodyDistributeTheOneOf`, + `e2e.TestChoice_BothKeywordsOnOneEntryDistributeTheOneOf`, + `e2e.TestChoice_TwoUnionsOverABodyLowerAlikeWhereverWritten`, + `e2e.TestChoice_TwoUnionsNoInstanceSatisfiesLowerAlikeWhereverWritten`, + `e2e.TestChoice_TwoUnionsAloneLowerAsOneSchemaWritingBoth`, + `e2e.TestChoice_AUnionPassedOverThatSaysNothingIsKeptEverywhere`, + `e2e.TestChoice_APrincipalUnionBesideAPairAndABodyCollapsesAsBesideTheAllOf`, + `e2e.TestChoice_TwoUnionEntriesChooseByCompetingKeywords`, + `e2e.TestChoice_AnEntryWritingBothChoosesAgainstThePosition`, + `e2e.TestChoice_AUnionPairLowersAlikeInEverySpelling`, `schema.TestUnion_TwoUnionsSharingNoMemberWarnOnceWhereverWritten`, `schema.TestUnion_APairAdmitsNullOnlyWhereBothUnionsMay`, `schema.TestUnion_TwoUnionsSharingNoMemberBesideAScalarLowerAsTheBody`, - `schema.TestUnion_AnAnyOfAloneDeclaringShapeIsElected`, - `schema.TestUnion_TwoUnionEntriesBesideABodyElectByCompetingKeywords`, + `schema.TestUnion_AnAnyOfAloneDeclaringShapeIsChosen`, + `schema.TestUnion_TwoUnionEntriesBesideABodyChooseByCompetingKeywords`, `e2e.TestRefConjunction_APassedOverRefIsKeptUnderItsKeyInEverySpelling` ### `discriminator` A `discriminator` on a schema that lowers to a `Model` or a `Union` lowers to its `Discriminator`, -and so does one standing with a union on an entry of a schema's `allOf`, written on that entry or +and so does one written with a union on an entry of a schema's `allOf`, written on that entry or beside the `allOf`, which the `Union` the union lowers to holds ([`union-beside-structure`](#union-beside-structure)). On a `Model` whose own properties include the one `propertyName` names, the tag is that property's @@ -4698,29 +5541,65 @@ its implicit mapping: 3.0.4, 3.1.1 and 3.2.0 say so ("_unless_ a `mapping` is pr value"), and 3.0.3 and 3.1.0, which those patch releases clarify, fail a value only where it matches no "implicit or explicit mapping". Their example maps the value `dog` to `Dog` "rather than the default (implicit) value of `Dog`", which the patch releases correct to "of -`#/components/schemas/dog`", the reading `dog` itself takes with no entry. So the name of the -component a variant's `$ref` branch names routes to the variant whether or not an entry routes it -too. The IR routes by a variant type's name only where a union's `Mapping` is nil -([models](../ir/models.md#discriminator)), so a union's `Mapping` holds the name route to each -variant no entry routes, the name keying its variant, wherever a nil one would not say it: where the -`mapping` holds an entry, or where a variant's type is not the component its branch names, as an +`#/components/schemas/dog`", the reading `dog` itself takes with no entry. So the name of the component a variant's `$ref` branch names routes to the variant whether or not an +entry routes it too, a component of the entry document, as OpenAPI resolves an implicit connection; +a branch naming another document's component, or an inline one, has no name to be routed by. A +`Discriminator` holds every route the source gives: `Mapping` each one a consumer writing an instance +picks the tag from, and `DecodeOnlyRoutes` each one a decoder reads and an encoder never writes +([models](../ir/models.md#discriminator)), so no tag is spelled in both. A decoder routes by +`Mapping`, then `DecodeOnlyRoutes`, then recognition, then `Default`. An encoder picks the tag from +the `Mapping` of the discriminator it writes for. The IR routes by a variant +type's name only where a union's `Mapping` is nil, so a union's `Mapping` holds the name route to +each variant no entry routes, the name keying its variant, wherever a nil one would not say it: where +the `mapping` holds an entry, where a variant's type is not the component its branch names, as an alias for a keyword beside the `$ref` is not, nor a variant composed over its branch -([`union-beside-structure`](#union-beside-structure)). A name two branches name, or one an entry -spells already, keys nothing more, and an inline variant has none. The compiler leaves out the name -of a variant an entry routes, though OpenAPI routes by it: a `Mapping` is what a consumer writing an -instance picks the variant's tag from, and a map cannot mark one of two routes to a variant as read -and never written, so the name written in would give the variant a second tag to write and nothing -to say which. A hierarchy leaves out the name of a subtype a key tags in the same way, its -`DiscriminatorValue` being a key ([`discriminator-value`](#discriminator-value)). A payload carrying -such a name routes nowhere in the IR, or to `Default` where a 3.2 document declares -`defaultMapping`. A variant the `defaultMapping` names and no entry routes is still routed by its -name. With no `mapping`, and each variant whose branch names a component that component itself, the -`Mapping` is nil and a union routes each variant by the name of its type, unless -[`discriminator-inference`](#discriminator-inference) reads it off the tags the variants pin. A -subtype the mapping names under several keys — an alias tag — takes the smallest in byte order as +([`union-beside-structure`](#union-beside-structure)), or where a variant has no name of the entry +document to be routed by. A name two branches name, or one an entry spells already, keys nothing +more, and an inline variant has none. The name of a variant an entry routes under another key is a +decode-only route, since the name written into `Mapping` would give the variant a second tag to write +and nothing to say which, and so is each name +[`discriminator-inference`](#discriminator-inference) replaces. A variant the `defaultMapping` names +and no entry routes is still routed by its name. With no `mapping`, and each variant whose branch +names a component of the entry document that component itself, the `Mapping` is nil and a union +routes each variant by the name of its type, unless +[`discriminator-inference`](#discriminator-inference) reads it off the tags the variants pin. + +A model's `Mapping` holds its whole route table, read once every node is interned by one settlement +of the run's model discriminators against one index of the document's facts (`irfacts.DocumentFacts`, +`compile.Settlement`): each entry that routes to the model itself, which the compiler never makes +`Abstract`, or to a subtype of it (`ir.Supertypes`, which counts no mixin), then the model's own +component name, then each subtype it routes by name — every component of the entry document composing +it at any depth, or, beside a union, each one a branch names ([`discriminator-value`](#discriminator-value)). +A subtype no entry routes takes the strings it pins for the tag, as +[`discriminator-inference`](#discriminator-inference) reads them, each one no other routed type pins +and no entry spells: a routed type that admits a string without pinning it, as a plain `string` tag +does, leaves it to the subtype pinning it. Its name is then decode-only, unless it is one of those +strings; a subtype pinning none is routed by its name, decode-only where its tag refuses it; and a +subtype an entry routes has its name decode-only. A name an entry keys is never another type's +route, so a subtype whose name an entry keys elsewhere and whose pins another type takes has no +route, which `pass/discriminator-unrouted-variant` notes once, at the nearest model above it holding +a discriminator, naming the subtype, and as routing only through its subtypes where that +discriminator routes one below it, as `pass/discriminator-missing-variant` reports at the node +holding the discriminator. Its `DiscriminatorValue` keeps the tag the rule +[`discriminator-value`](#discriminator-value) reads. `DiscriminatorValue` routes nothing. It names +the key that a discriminator on one of the subtype's ancestors routes it by, so it is what an +encoder writes only through that discriminator: a consumer reads a discriminator's routes from its +`Mapping` and `DecodeOnlyRoutes` alone. Every route to a type +that is neither the model nor a subtype of it is set aside, the others staying typed: the entries +kept verbatim in one object, `Unmodeled["openapi:discriminator/mapping"]`, spelled as the source's +`mapping` writes them, the `defaultMapping` in `Unmodeled["openapi:discriminator/defaultMapping"]`, +both `no_ir_home` and each naming in its `Targets` the type it lowered to, and a route by the name a +union's branch names left unwritten; each draws one info `openapi/unhomed-construct`, at the entry's +value, the `defaultMapping` or the branch. A discriminator left with no typed route is kept whole +instead, as [`union-beside-structure`](#union-beside-structure) keeps one. A discriminator an inline +entry of the `allOf` writes, where no union is written with the conjunction, lowers as one written +beside the `allOf`, whether or not the conjunction declares its `propertyName`, and is the model's, +which keeps its extensions and the keys OpenAPI defines for no Discriminator Object under the keys +and reasons one written beside the `allOf` keeps them, each at the pointer it is written at. +A subtype the mapping names under several keys — an alias tag — takes the smallest in byte order as its `DiscriminatorValue` ([`discriminator-value`](#discriminator-value)), since the field holds one and a mapping's key order is not a property of the document, with every key kept in the base's -`Mapping` and the election reported as an info `openapi/degraded-construct` at the subtype. A +`Mapping` and the choice reported as an info `openapi/degraded-construct` at the subtype. A discriminator beside a node that routes by none is kept verbatim by [`shape-applicator`](#shape-applicator), and one beside a union written with structure, or on an `allOf` entry writing a union, is [`union-beside-structure`](#union-beside-structure)'s. @@ -4742,9 +5621,11 @@ shaped like a component's name only as a name would refuse `cat.yaml`, which 3.0 text asks for no `./` prefix on a relative reference, let a document write. From the position a value names, its chain follows each `$ref` in turn, a component's as much as any -other position's, to the first position writing none, at most 64 `$ref`s, a longer chain stopping -where the bound reached. A position writing a `$ref` lowers to an alias over what the `$ref` names, -whatever is written beside it, and an alias is no subtype and no variant, so a route means such a +other position's, to the first position writing none, however long a chain the compiler resolves to +an end; one it resolves no end for, running into a loop or failing at a `$ref`, is read at most 64 +`$ref`s, stopping where the bound reached. A position writing a `$ref` lowers to an alias over what +the `$ref` names, whatever is written beside it, and an alias is no subtype and no variant, so a +route means such a position only where a union's variant is that alias. On a `Model` a value routes to the type declared where its chain ends, and a subtype's tag is read off the same chains ([`discriminator-value`](#discriminator-value)). A union's `Mapping` names variants, which is what @@ -4756,22 +5637,57 @@ in branch order where several do. Several branches each aliasing one type for a first, reported as an info `openapi/degraded-construct` at the entry naming the branches; neither the mapping's key order nor any lowering order decides. A chain no branch meets routes to the type it ends on, as on a model, which `pass/discriminator-missing-variant` reports as no variant, the -compiler reporting nothing. A chain a branch no instance of the union's body satisfies meets first +compiler reporting nothing. A chain a branch no instance of the union's rest satisfies meets first routes nowhere, its entry kept verbatim on the `Union` ([`union-beside-structure`](#union-beside-structure)). Where a position on a chain writes a `$ref` landing on no schema, or on a loop, the value names no type: its entry is left out, unreported, since the failing `$ref` is reported where it is written, and the last position the chain reached is lowered all the same. A union's value naming the failing branch itself still routes to that branch's variant, as the branch -meets the chain before it breaks. A discriminator kept unread, verbatim, has its values read in -the same way, what each chain ends on lowered and a value naming no schema reported, since a value -is a reference wherever its discriminator ends up. +meets the chain before it breaks. + +A discriminator kept verbatim has its values read in the same way wherever it is kept, as a value is +a reference wherever its discriminator ends up: one a node or carrier keeps whole for having no home +for it, and one within what a step keeps verbatim, at any position the binder reads as a schema +([`references`](#references)) — a keyword kept beside a node with no home for it, a validation-only +keyword ([`validation-only`](#validation-only)), an `allOf` entry, a union's branches kept beside a +rest ([`union-beside-structure`](#union-beside-structure)), an OpenAPI object an operation keeps +whole, such as an Encoding Object a 3.2 one nests, whose schemas no model holds and whose +discriminator is read off the YAML as the binder reads it, or a component no reference reaches +([`unreferenced-components`](#unreferenced-components)). A position a value's chain ends on is +lowered and recorded on the kept Unmodeled entry's `UnmodeledEntry.Targets`, as a kept `$ref`'s +landing is ([`validation-only`](#validation-only)), but in such a component, whose `$ref`s are +followed nowhere either. A value naming no schema is reported once at its entry, as an +`openapi/unresolved-ref` error, however many readers read it: the node holding the discriminator and +the step keeping it verbatim word it alike. A value under a keyword the schema's dialect does not +define, such as `dependencies` outside JSON Schema draft 4, 6 and 7, is no reference, as no schema +is written there. The extension and undefined keys a discriminator kept whole writes take no +Unmodeled entry of their own beside it on the node keeping it, which holds them inside the kept one, +but for an extension the promotion policy reads ([`extension-promotion`](#extension-promotion)). - Cases: `oneof-discriminated`, `discriminator-inheritance`, `discriminator-default-mapping`, - `discriminator-alias-mapping`, `nullable-union-discriminator`, `discriminator-aliased-branch` -- Codes: `openapi/degraded-construct`, `openapi/unresolved-ref` + `discriminator-alias-mapping`, `nullable-union-discriminator`, `discriminator-aliased-branch`, + `discriminator-decode-only` +- Codes: `openapi/degraded-construct`, `openapi/unresolved-ref`, `openapi/unhomed-construct` - Tests: `schema.TestHomelessDiscriminator_IsKeptBesideEveryOtherNode`, + `schema.TestAllOf_AnEntrysDiscriminatorKeepsWhatItsFlatTwinKeeps`, `schema.TestUnplacedDiscriminator_IsKeptAtEveryUnionSite`, `schema.TestKeptDiscriminator_ResolvesItsValuesAtEverySite`, + `schema.TestKeptDiscriminator_ResolvesItsValuesWhereverItIsKept`, + `schema.TestKeptDiscriminator_ReadsNoValueUnderAKeywordTheDialectLacks`, + `schema.TestKeptDiscriminator_ResolvesItsValuesAtEveryOtherKeeper`, + `schema.TestKeptDiscriminator_AValueALoweringReadsTooIsReportedOnce`, + `schema.TestKeptDiscriminator_RoutesAValueWhereNoModelHoldsTheSchema`, + `schema.TestKeptDiscriminator_RoutesAValueOfANodeBuiltOnceLoweringReturned`, + `schema.TestKeptDiscriminator_AValueWhoseChainBreaksRoutesNowhere`, + `schema.TestKeepDiscriminatorWhole_KeepsNothingOfASchemaWritingNone`, + `schema.TestKeptDiscriminator_ACollapsedUnionKeepsItsExtensionOnce`, + `schema.TestPrincipalKept_ADiscriminatorKeptPlainHoldsItsKeysOnce`, + `reftable.TestDiscriminators_WithinFindsEachWrittenAtOrBeneath`, + `reftable.TestDiscriminators_KeepsEachDocumentApart`, + `reftable.TestDiscriminators_AreInPointerOrderAtEveryBinding`, + `statement.TestWrittenDiscriminator_ReadsWhatTheBindingReads`, + `promotion.TestDropContainedWithin_DropsOnlyWhatLiesBeneath`, + `openapi.TestWithoutRereported`, `schema.TestDiscriminator_AnEmptyPropertyNameIsKeptVerbatim`, `schema.TestDiscriminator_AnEmptyPropertyNameBesideAnUntaggedUnionIsKeptForItsNode`, `e2e.TestMappingTargets_ADiscriminatorAReferenceReachesIsBoundWhereItSits`, @@ -4790,24 +5706,37 @@ is a reference wherever its discriminator ends up. `schema.TestDiscriminatorMapping_LeavesAValueNamingNoVariantToValidate`, `schema.TestDiscriminatorMapping_ABrokenChainDrawsOnlyItsRefsError`, `schema.TestDiscriminatorMapping_WritesTheRoutesItImplies`, - `schema.TestMappingTagsFor_ReadsTheMappingOnce` -- Status: partly built: a variant whose branch names a component of another document is routed by - its type's name where the `Mapping` is nil, and by nothing where it holds an entry (#1829); and a - payload tagged with the name of a union's variant or a hierarchy's subtype that an entry routes - reaches no variant, or `Default`, though OpenAPI routes it by that name, as the IR has no place - for a route a consumer reads and never writes (#1863). + `schema.TestMappingTagsFor_ReadsTheMappingOnce`, + `schema.TestDiscriminatorRoutes_AHierarchyMapsEveryRouteItGives`, + `schema.TestDiscriminatorRoutes_EachOfTwoDiscriminatorsMapsItsRoutes`, + `schema.TestDiscriminatorRoutes_AUnionRoutesEveryRouteTheSourceGives`, + `schema.TestDiscriminatorRoutes_ANameTheTagRefusesIsNoMappingKey`, + `schema.TestDiscriminatorRoutes_ARouteToItsOwnModelKeepsTheDiscriminator`, + `schema.TestDiscriminatorRoutes_AnEntryRoutingToNoSubtypeIsKeptOnItsModel`, + `schema.TestDiscriminatorRoutes_KeptEntriesShareOneObject`, + `schema.TestDiscriminatorRoutes_AnEntryDiscriminatorLowersAsOneBesideTheAllOf`, + `schema.TestDiscriminatorRoutes_AnEntryDiscriminatorNamingNoMemberLowersAsItsTwin`, + `schema.TestDiscriminatorRoutes_AVariantOfAnotherDocumentIsRoutedAlikeUnderEither`, + `schema.TestDiscriminatorRoutes_TheChecksReachACompiledDocument`, + `schema.TestDiscriminatorSettlement_BuildsOneIndexARun`, + `schema.TestModelRouteSettlement_ReportsWhatItCannotSettle`, + `schema.TestModelRouteSettlement_LeavesASettledMapAlone` +- Status: partly built: a route to a schema composing the model only as a mixin, beside another + discriminated parent its `Base`, is kept verbatim and reaches no type (#2335). ### `discriminator-value` A subtype's wire tag lowers to `Model.DiscriminatorValue`, left empty on the base itself. It is read -off the discriminators of the subtype's `allOf` ancestors — the `$ref` entries' targets, then -theirs, level by level to the walk's depth bound, nearest first, a schema that declares none passed +off the discriminators of the subtype's `allOf` ancestors — the `$ref` entries' targets, and the +target of a component of the entry document writing a `$ref` and nothing beside it, which lowers to a +`Model` with that `Base` and so is a subtype like any other, then theirs, level by level at any depth, +nearest first, each kept at the least distance it is reached at, a schema that declares none passed through and no schema its own ancestor, the hierarchy of the subtype's `Base` before any other, so two discriminated parents mapping it tag it as its `Base`'s does whichever is written first ([`allof-classification`](#allof-classification)) — as the key an ancestor's `mapping` spells for the subtype, the mapping naming it by reference or by schema name, read through each `$ref`, a component's among them, as [`discriminator`](#discriminator) reads it, an inline subtype by its position's -reference, and where several keys name it [`discriminator`](#discriminator) elects one. A key of +reference, and where several keys name it [`discriminator`](#discriminator) chooses one. A key of `""` is a tag, not an absence. Once no ancestor's mapping names it, the tag is the subtype's schema name as declared (`Cat/Dog`, not its pointer token) if it is a component schema that an ancestor's discriminator routes by name, OpenAPI's implicit mapping, unless @@ -4815,8 +5744,11 @@ discriminator routes by name, OpenAPI's implicit mapping, unless OpenAPI's conditions for a discriminator say which schemas it routes by name: one written beside no `oneOf` or `anyOf`, a parent schema, routes every schema building on it through `allOf`, and one beside either routes the schemas that union lists, where "all possible schemas MUST be listed -explicitly": each schema a `$ref` branch, of the `oneOf` where both are written, ends on, in -whichever document, as the ancestors are read. A schema composing a discriminated union that does +explicitly": each schema a `$ref` branch, of the `oneOf` where both are written, ends on, as the +ancestors are read. The ancestors are read once a run for every schema, over the composition edges +condensed where they loop: a schema with two parents takes both answers, each ancestor at its least +distance, and the members of a loop share what lies outside it, each adding the loop's other +discriminated members at their distances from it, never itself. A schema composing a discriminated union that does not list it is a narrowing of that union, every instance of it an instance of one variant and carrying that variant's tag, so no tag routes to it and it carries none, and it composes the union as written ([models](../ir/models.md#a-union-a-composition-names)). Reading what such a schema @@ -4830,18 +5762,21 @@ mapping entry tags it, and a chain with no discriminated ancestor carries no tag subtype a discriminator routes to is never distributed across a union written beside its `allOf` or on one of its entries, since a union would be no subtype: it composes the union as a mixin ([`union-beside-structure`](#union-beside-structure)), so no variant of a distributed union carries -a tag. A discriminator standing with a union on an entry of its schema's `allOf`, written on that +a tag. A discriminator written with a union on an entry of its schema's `allOf`, written on that entry or beside the `allOf`, routes by name the schemas that union lists, as one beside it does. - Cases: `discriminator-transitive`, `discriminator-inline-subtype`, `oneof-discriminated` -- Tests: `schema.TestAllOf_TwoDiscriminatedBasesElectAndTagAlikeInEitherOrder`, +- Tests: `schema.TestAllOf_TwoDiscriminatedBasesChooseAndTagAlikeInEitherOrder`, `schema.TestAllOf_DiscriminatorSubtypeValue`, `schema.TestAllOf_DiscriminatorValueFromNearestAncestor`, `schema.TestAllOf_InlineSubtypeHasNoImplicitDiscriminatorValue`, `schema.TestAllOf_ExtensionSubtypeIsTaggedOnlyByAMapping`, `schema.TestDiscriminatorValue_TheImplicitMappingRoutesWhatAUnionLists`, `schema.TestRoutesByName_ReadsAUnionsListOnce`, - `schema.TestDiscriminatorValue_AUnionListsTheSchemaItsBranchEndsOn` + `schema.TestDiscriminatorValue_AUnionListsTheSchemaItsBranchEndsOn`, + `schema.TestAllOf_DiscriminatorValueTagsAChainOfAnyDepth`, + `schema.TestDiscriminatorValue_ClimbsAHierarchyLinearly`, + `schema.TestDiscriminatorRoutes_EveryLevelOfADeepHierarchyIsRouted` ### `discriminator-inference` @@ -4859,17 +5794,18 @@ a number among them, any string, since a discriminator's tag is the wire string, text spells too. A value admits null where its reference or an alias it is read through does, or one of a union's variants does, and null is no tag. A member admits what every declaration its flattening reads of it admits (`ir.FlattenedProperties`), the one it takes and those it overrides, -as an instance meets them all, and null only where each does. An object admits at a property what -its member of that name admits, any value where it declares none, met with what each closed union it -composes admits there: what any of the union's variants admits as an object in turn, a variant that -is no model or union admitting any value. A cycle of objects and the unions they compose, as a union -listing subtypes that compose it, is read alike from wherever the reading enters it, each member -admitting what it does given what the others admit, from any value down until none changes: so a -subtype pinning its tag admits its pin, and the union what its subtypes admit. A cycle is swept at -most 64 times, each sweep reading every member off the one before; one still changing then is read -as the last sweep left it, which admits no less than its instances hold, so nothing is reported. - -So a body beside a union that redeclares the tag as a string, which its composed variants take, +as an instance satisfies them all, and null only where each does. An object admits at a property +what its member of that name admits, any value where it declares none, intersected with what each +closed union it composes admits there: what any of the union's variants admits as an object in turn, +a variant that is no model or union admitting any value. A cycle of objects and the unions they +compose, as a union listing subtypes that compose it, is read alike from wherever the reading enters +it, each member admitting what it does given what the others admit, from any value down until none +changes: so a subtype pinning its tag admits its pin, and the union what its subtypes admit. A cycle +is swept at most 64 times, each sweep reading every member off the one before; one still changing +then is read as the last sweep left it, which admits no less than its instances hold, so nothing is +reported. + +So the rest beside a union that redeclares the tag as a string, which its composed variants take, leaves each branch's pin in force ([`union-beside-structure`](#union-beside-structure)), and a tag written as a `oneOf` of `const`s reads as one written as an `enum`, the set [`string-const-union`](#string-const-union) later normalizes it to. A variant pins a property where @@ -4889,7 +5825,14 @@ ask. Two unions and a subtype meet it: `openapi/inferred-discriminator` at the discriminator names the first variants it reads otherwise, with the first strings each admits. `Discriminator.Inferred` stays false: the tag property is declared. Variants sharing a string leave the routes to the document, since a - `Mapping` routes a tag to one variant. + `Mapping` routes a tag to one variant. Each name the reading replaces stays a route, in + `DecodeOnlyRoutes`, unless it is one of the strings mapped to its variant, as OpenAPI still + routes a payload carrying it ([`discriminator`](#discriminator)). A `mapping` naming some + variants is read the same way for the variants it leaves out: where each pins + strings no other variant admits and no entry spells, and the implicit mapping routes one by + other than all it admits, their implied routes are replaced by the strings they pin, marked and + reported alike, each name replaced decode-only unless it is one of those strings or an entry + keys it. 2. A closed union of two or more variants declaring no discriminator, no variant admitting null, gets one where every variant requires a property and pins it to strings no other variant admits: the first such property in the first variant's layout order is its `PropertyName`, each string @@ -4905,7 +5848,11 @@ ask. Two unions and a subtype meet it: its `Provenance.Inferred` names `discriminator-inference`, and an info `openapi/inferred-discriminator` at it names what it admits. Each subtype is read alone, so two admitting one string both carry it, as their instances do - ([models](../ir/models.md#discriminator)). + ([models](../ir/models.md#discriminator)). The base's `Mapping` maps each string a subtype it + routes by name pins, where no other routed type pins it and no entry spells it; one that only + admits it, as a plain `string` tag does, leaves it to the subtype pinning it, as an entry or + another name routes that type. The base then names the policy in its `Provenance.Inferred` + ([`discriminator`](#discriminator)). - Cases: `discriminator-inferred` - Codes: `openapi/inferred-discriminator` @@ -4917,22 +5864,21 @@ ask. Two unions and a subtype meet it: `schema.TestDiscriminatorInference_DisabledReadsNothing`, `schema.TestDiscriminatorInference_ReadsADistributedUnion`, `schema.TestUnionTags_ReadsOnlyWhatItWasDeferredFor`, - `schema.TestTagReadings_ValueReadsAClosedSetOfStrings`, - `schema.TestTagReadings_AUnionOnACycleAdmitsAnything`, - `schema.TestTagReadings_MemberMeetsEveryDeclaration`, - `schema.TestTagReadings_ObjectMeetsWhatAComposedUnionAdmits`, - `schema.TestTagReadings_ACycleOfCompositionReadsAlikeFromAnyEntry`, - `schema.TestTagReadings_SweepsACycleAtMostTheBound`, - `schema.TestTagReadings_SweepsACycleUntilItsNullsSettle`, - `schema.TestTagReadings_ReadsASharedTypeOnce`, `schema.TestThroughAliases_ReadsAtMostTheBound`, - `schema.TestTagReadings_ReadAModelAsTheMapItSwapsFor`, + `schema.TestTagSetMemo_ValueReadsAClosedSetOfStrings`, + `schema.TestTagSetMemo_AUnionOnACycleAdmitsAnything`, + `schema.TestTagSetMemo_MemberIntersectsEveryDeclaration`, + `schema.TestTagSetMemo_ObjectIntersectsWhatAComposedUnionAdmits`, + `schema.TestTagSetMemo_ACycleOfCompositionReadsAlikeFromAnyEntry`, + `schema.TestTagSetMemo_SweepsACycleAtMostTheBound`, + `schema.TestTagSetMemo_SweepsACycleUntilItsNullsSettle`, + `schema.TestTagSetMemo_ReadsASharedTypeOnce`, `schema.TestThroughAliases_ReadsAChainToItsEnd`, + `schema.TestTagSetMemo_ReadAModelAsTheMapItSwapsFor`, `schema.TestModelFields_ReportsAFoldFollowingAStoredReading`, `schema.TestDiscriminatorInference_ReadsTheTagASubtypeAdmits`, `schema.TestDiscriminatorInference_ReadsAUnionItsSubtypesCompose`, `schema.TestSubtypeTagReading_ReportsWhatItCannotSettle`, - `schema.TestDiscriminatorInference_JoinsTheMarksANodeCarries` -- Status: partly built: a `mapping` naming some variants is read as written, so a route it implies - by a name its variant rejects stands (#1798). + `schema.TestDiscriminatorInference_CombinesTheMarksANodeCarries`, + `schema.TestDiscriminatorRoutes_ADeclaredMappingInfersWhatItLeavesOut` ### `string-const-union` @@ -4959,13 +5905,19 @@ branches hold, which a `oneOf` rejects and whose two branches may say two things by two primitives; a nullable branch; a construct a branch keeps verbatim for any reason but being a vendor extension, such as a constraint its `Literal` has no home for, which narrows the branch and would not narrow a member; a branch whose `Provenance.Inferred` names a heuristic, whose mark no -member could carry; one fact two places say of one value; and a bound written beside the union, -which its `Constraints` hold ([`constraints`](#constraints)) and an `Enum` has no field for. A union -of numbers, or of values of several kinds, is outside this rule and stays a union. +member could carry; one fact two places say of one value; a bound written beside the union that +binds no string, which no `Enum` of strings holds; and a union holding bounds that another union +names, which reads no member of it in place. A length or a `pattern` a `Union` holds in its +`Constraints` ([`constraints`](#constraints)) moves onto the `Enum` with its values, in the `Enum`'s +own `Constraints` ([enums](../ir/enums.md#bounds)). A union written beside the rest saying anything, +a `type` or a bound, is one value-set conjunct with it, which the compiler itself lowers as the flat +`enum` of the members the rest admits ([`allof-refinement`](#allof-refinement)), so this rule reads +only a union written alone. A union of numbers, or of values of several kinds, is outside this rule +and stays a union. - Cases: `string-const-union` - Tests: `e2e.TestStringConstUnion_NormalizesToItsEnumSpelling`, - `e2e.TestStringConstUnion_ABoundBesideTheSetKeepsTheUnion` + `e2e.TestStringConstUnion_ABoundBesideTheSetFoldsIntoTheEnum` ### `enum-const` @@ -4976,7 +5928,7 @@ no member and no variant: whether the position admits null is its reference's once, and an `enum` listing `null` alone lowers to an `Enum` with no member, which a nullable reference makes a position admitting null and nothing else. A keyword beside the `enum` that excludes null, as `type: string` does, leaves a `null` entry admitting no instance, since JSON -Schema conjoins the two, so it is dropped and reported as an `openapi/degraded-construct` warning at +Schema conjoins the two, so it is dropped and reported as an `openapi/unsatisfiable-schema` warning at it. Its `ValueType` is the primitive one declared `type` and its `format` select, as a scalar's are read ([`string-formats`](#string-formats), [`numeric-formats`](#numeric-formats)), else the primitive of the `type` alone, where every member is a value of that primitive, else the primitive @@ -4985,33 +5937,80 @@ lacks each whose members are a text the value travels as, `byte` and `http-date` member does not fit it, as none is a value of `binary`'s `bytes`, is kept verbatim under `openapi:format` (`degraded_lowering`), with an info `openapi/degraded-construct` at the schema, but for `password`, which is a redaction ([`password`](#password)). A member that no declared `type` -admits, as `"a"` under `type: integer` or under `type: "null"`, matches no instance either, and is -reported as an `openapi/degraded-construct` warning at it; a `!!binary` member is the string of its +admits, as `"a"` under `type: integer`, matches no instance either, and is +reported as an `openapi/unsatisfiable-schema` warning at it; a `!!binary` member is the string of its text to the `type`, as the rest of the compiler reads a value's kind, and `bytes`, a format of string, to the `ValueType`. Such a member is kept, the members lowering as written and the `type` kept verbatim under `openapi:type` (`degraded_lowering`) with the info at the schema: the document contradicts itself, as unquoted numbers under `type: string` do, and keeping either side alone would -guess which statement it means, where keeping both loses nothing. A `type` beside an `Enum` with no -member types no value, and draws nothing. An enumeration an `Enum` cannot hold — a list or object +guess which statement it means, where keeping both loses nothing. A `type` of `null` alone decides +over its `enum` instead ([`null-alone`](#null-alone)). A `type` beside an `Enum` with no member types +no value, and draws nothing. A bound of the members' kind beside the `enum`, written flat, on an +`allOf` entry or beside the `allOf`, or by a schema a `$ref` beside it reaches, the `$ref` kept +verbatim, is held in the `Enum`'s `Constraints` ([`constraints`](#constraints)), which keep every +member as written, one the bound refuses among them: `pass` names such a member +([enums](../ir/enums.md#bounds)), so `{$ref: T, enum: [a, abcd]}`, where `T` writes +`{type: string, maxLength: 3}`, holds and draws what `{type: string, maxLength: 3, enum: [a, abcd]}` +does. Where the bounds refuse every +member the `Enum` lists, as `ir.ConstraintsAdmit` reads them, no instance satisfies the schema, which +is reported once, as for value sets sharing no member, by an `openapi/unsatisfiable-schema` warning +at the position, and `pass` names none of them: `{type: string, enum: [abcd, abcde], maxLength: 3}`. +Bounds admitting no value of the members' kind at all (`ir.ConstraintsAdmitNoValue`), as a +`minLength` past the `maxLength`, are the cause, which `pass/bounds-admit-no-value` reports alone, +so the warning is not drawn ([constraints](../ir/constraints.md#constraints)). A `pattern` outside +the subset ir reads ([patterns](../ir/values.md#patterns)) refuses no member. An enumeration an +`Enum` cannot hold — a list or object member, or members of different kinds — lowers to a `Union` of `Literal`s over its entries but `null` instead, reported as an info `openapi/degraded-construct` at the schema, and a member whose value cannot convert makes the enumeration such a union, its own variant the top type, reported as -an `openapi/degraded-construct` warning at the member. That union is exclusive unless an instance -can match two variants: an entry it holds repeats, or one lowered to the top type. `enum: []` lowers +an `openapi/degraded-construct` warning at the member. A `type` every member is a value of restates +the union and is kept and reported nowhere, written flat, beside an `allOf` or on its entry: +`{type: array, enum: [[1, 2], [3]]}` lowers as `{enum: [[1, 2], [3]]}`; one a member is no value +of, `type: integer` beside `enum: [1, two]`, is kept verbatim with the info at the schema. That union +is exclusive unless an instance can match two variants: an entry it holds repeats, or one lowered to +the top type. `enum: []` lowers to a closed `Enum` with no members, a position accepting no value, reported as an `openapi/empty-enum` warning. An entry repeating an earlier entry's value, compared as JSON Schema compares instances, is kept, each occurrence a member of its own ([enums](../ir/enums.md)), and -reported as an `openapi/duplicate-enum-value` warning at the repeat. An `enum` past +reported as an `openapi/duplicate-enum-value` warning at the repeat; a repeated `null` is reported +there as what holds it, the reference, which admits null once, and where a keyword excludes null, +only the drop is. An `enum` past `Limits.MaxEnumMembers` lowers to the top type, with an `openapi/budget-exceeded` error at the schema. A `const` lowers to a `Literal` of its value, whose `ValueType` is read as an enum's is, from the type and format the value fits, else the type, else the value's own kind ([containers](../ir/containers.md#literals)), so a `type` or `format` the value fits is held and draws nothing, and one it does not fit is kept verbatim with the same info report. A `const` of a value no declared `type` admits matches no instance, keeps its `Literal` and is reported as an -`openapi/degraded-construct` warning at the `const`. A `const: null` lowers as `enum: [null]` does, +`openapi/unsatisfiable-schema` warning at the `const`. A `const` beside an `enum` sharing no member +with it, their members read as the choice reads them, admits no value, flat as on `allOf` entries +([`allof-refinement`](#allof-refinement)): of one value type the `type` admits, a primitive naming +it, the closed `Enum` of that type with no member; of lists, of objects or of differing value +types, which type no `Enum`, the bottom a `false` schema lowers to +([`whole-schema-fallbacks`](#whole-schema-fallbacks)), keeping, written flat, each keyword beside +them under its own key and, on an entry, the entry whole. An `enum: []` beside a `const`, another +`enum`, or a `$ref` to a schema stating a type or a set lies within it, so it is the one fact +wherever each is written: flat, on entries, beside the `allOf` or beside the `$ref`. The position +is the closed `Enum` with no member, typed by the other set's values or by the target's type, as a +`Literal` of a `const` is typed and `{type: string, enum: []}` is, and by the top type where no +primitive types them. It keeps an inline set verbatim under its writer's key +([`allof-inline-residue`](#allof-inline-residue)) and nothing of a `$ref`, whose target states its +own. Its one report is the `openapi/empty-enum` warning where the `enum: []` is written. This +holds where the conjuncts beside it share a value, write no union, and say nothing else but notes. +Each other pair keeps the `const` and the `enum` +verbatim (`degraded_lowering`) and is reported once, as an `openapi/unsatisfiable-schema` warning in +place of the info [`competing-keywords`](#competing-keywords) draws: at the schema writing them, but +where they make the position holding the entry the bottom, the bottom's own, naming the entry as +admitting no value. So +`{type: integer, const: 1, enum: [2]}` is the closed empty `Enum` of `integer`, as +`{allOf: [{type: integer}, {const: 1}, {enum: [2]}]}` is. Where the `type` excludes the one value +type they share, the `const` lowers as above. A `const: null` lowers as `enum: [null]` does, to an `Enum` with no member, its null the reference's, so no `Literal` holds a null ([containers](../ir/containers.md#literals)), and where a keyword beside it excludes null it is -reported as that enum's entry is, at the `const`. A `const` that cannot convert lowers to the top +reported as that enum's entry is, at the `const`. Where only a conjunct beside it excludes null, as +a `$ref` to a schema admitting none does, a `const: null` or an `enum` of `null` alone draws no +finding of its own: the position's report of conjuncts sharing no value says so, as it does of a +value set of any other value; an `enum` some of whose members are left draws its finding at each +`null`. A `const` that cannot convert lowers to the top type, with an `openapi/degraded-construct` warning at the schema. A value set an `allOf` refines is typed by every conjunct ([`allof-refinement`](#allof-refinement)). A `$ref` into a member of such a union names the member's `Literal`, the node the enumeration lowers at that position, whichever is @@ -5020,17 +6019,27 @@ lowered first. - Cases: `enum-string`, `enum-numeric`, `empty-enum`, `enum-member-identity`, `nullable-enum-31`, `enum-null-member`, `literal-const` - Codes: `openapi/empty-enum`, `openapi/duplicate-enum-value`, `openapi/degraded-construct`, - `openapi/budget-exceeded` -- Tests: `schema.TestEnum_HeterogeneousBecomesUnionWithBadValue`, + `openapi/unsatisfiable-schema`, `openapi/budget-exceeded` +- Tests: `e2e.TestNullAnswer_ARepeatedNullIsReportedAsWhatHoldsIt`, + `schema.TestEnum_HeterogeneousBecomesUnionWithBadValue`, `schema.TestEnum_NonScalarAndMidListMismatch`, `schema.TestEnum_NullIsNeverAMember`, `schema.TestEnum_NullAgreesWithTheOneOfSpelling`, `schema.TestEnum_ValueTypeReadsTheFormatItsMembersFit`, `schema.TestEnum_AMemberNoTypeAdmitsIsReportedAndKept`, + `schema.TestEnum_BoundsRefusingEveryMemberDrawOneReport`, + `schema.TestRefBounds_AValueSetHoldsTheBoundsItsRefsReach`, `schema.TestLiteral_ValueTypeReadsTheTypeAndFormatItsValueFits`, `schema.TestConst_NullLowersAsAnEnumOfNullAlone`, `schema.TestEnum_ReportsWhyAFormatStayedVerbatim`, + `schema.TestEnum_ATypeEveryListedMemberHasRestatesTheUnionOfLiterals`, + `e2e.TestLiteralUnion_ATypeAMemberLacksIsKept`, `schema.TestScalar_AnEncodedFormatBesideAValueSetLowersAsByteDoes`, `schema.TestEnum_NarrowsARedeclaredPrimitiveInEitherOrder`, + `schema.TestEmptyEnum_BesideASetIsTheClosedEmptyEnumOfItsValues`, + `schema.TestEmptyEnum_BesideAConstTypedByNoPrimitiveIsTheTopType`, + `schema.TestEmptyEnum_BesideARefIsTheClosedEmptyEnumOfItsTarget`, + `schema.TestEmptyEnum_TheEntrySpellingLowersAsBesideTheAllOf`, + `schema.TestEmptyEnum_BesideARefStatingNoKindKeepsTheRef`, `schema.TestEnumAsUnion_UnconvertibleMemberBecomesAny`, `schema.TestEnumAsUnion_ExclusiveWhereNoInstanceMatchesTwoEntries`, `schema.TestNullableInference_AnEnumsNullMemberFollowsTheReadingInForce`, @@ -5044,18 +6053,38 @@ lowered first. or a schema to `Model.AdditionalProperties`, whose `Value` types every key no property names. An object whose one member fact is that catch-all lowers to a `MapT` instead ([containers](../ir/containers.md)). `unevaluatedProperties: false` lowers to `Additional` closed -after composition where no `additionalProperties` is written beside it. An `additionalProperties` of +after composition where no `additionalProperties` is written beside it and every evaluator it +reaches is one the IR types ([`validation-only`](#validation-only)), and an `unevaluatedProperties` +schema to the catch-all's `Value` where that holds and nothing its composition brings evaluates +members past the flattening's. An `additionalProperties` of any value evaluates every property that `properties` and `patternProperties` leave (JSON Schema 2020-12 §10.3.2.3), which leaves `unevaluatedProperties` nothing to apply to (§11.3), so beside one the object's openness is `additionalProperties`' alone, closed for `false` and a catch-all for -anything else, and the inert keyword is kept verbatim with it +anything else, and the keyword that says nothing is kept verbatim with it ([`validation-only`](#validation-only)); `{type: object, additionalProperties: {…}, unevaluatedProperties: false}` is a `MapT`. + +A closure or a typed catch-all over a `Model` holding members its own schema object does not +declare, a `$ref` target's, an entry's or a branch's, still types the model, the closed subtype its +author means, but applies to those members too, so the keyword is also kept verbatim under +`openapi:additionalProperties` (`degraded_lowering`), with one info `openapi/degraded-construct` at +the keyword naming them; a `patternProperties` is kept so, with its info, only where a declared +member matches one of its patterns. Where another conjunct requires a member the closure refuses, +or the catch-all refuses a required member's type, the position admits no instance: one warning +`openapi/unsatisfiable-schema` at the keyword in place of the info. A union branch requiring such a +member is dead ([`union-beside-structure`](#union-beside-structure)). Of two closures, the +position's own types the model and an entry's is kept under its entry key, with an info. A model a +`$ref` entry brings, closed by its own closure, that declares no member another conjunct requires +leaves the position no instance, which one warning at the position says. `minProperties` and `maxProperties` lower to the `Model`'s `Constraints`, which bound the property set's cardinality as against `Additional`'s openness, or to a `MapT`'s, which bound its entry count, and to the node alone: a property, a parameter or a header naming the node holds neither -([`constraints`](#constraints)). Written with no `type` beside a union whose branches each declare -an object, either is a body the union distributes into +([`constraints`](#constraints)). Each model states its own, and an instance satisfies the counts of +every model it composes, which a reader intersects ([the +flattening](../ir/models.md#the-flattening)); a cycle of models composing one another whose +intersected counts admit no object is `pass.Validate`'s to report, once +([constraints](../ir/constraints.md#constraints)). Written with no `type` beside a union whose +branches each declare an object, either is part of the rest the union distributes into ([`union-beside-structure`](#union-beside-structure)): each variant is a model over its branch holding the closure or the catch-all, as beside `type: object`. @@ -5100,40 +6129,41 @@ cannot mean a model closed over them: typing it would close or type members it n Two entries writing `additionalProperties` beside no closure are both kept, since the catch-all would be what both admit. `patternProperties` beside the `allOf` types the catch-all whatever the entries declare, as a pattern applies to every name it matches and reads no `properties` -(§10.3.2.2). An `unevaluatedProperties: false` beside the `allOf` is inert beside an entry closing -the model with an `additionalProperties`, which evaluates every member, and is kept as validation -logic; beside one writing patterns alone it closes the model after composition. +(§10.3.2.2). An `unevaluatedProperties: false` beside the `allOf` says nothing beside an entry +closing the model with an `additionalProperties`, which evaluates every member, and is kept as +validation logic; beside one writing patterns alone it closes the model after composition. - Cases: `maps`, `constraints`, `allof-position-constraints`, `allof-nested-inline` +- Codes: `openapi/unsatisfiable-schema` - Tests: `schema.TestObject_CatchAllBesideAnotherFactStaysModel`, `schema.TestObject_MapAndNothingElseLowersToMapT`, - `schema.TestObject_AnInertClosureLeavesAMap`, + `schema.TestObject_AClosureSayingNothingLeavesAMap`, `schema.TestModel_UnevaluatedPropertiesClosedAfterComposition`, - `schema.TestAllOf_ACatchAllLeavesAClosureAfterCompositionInert`, - `annotation.TestClosesAfterComposition_OnlyWhereNoAdditionalPropertiesStandsBeside`, - `e2e.TestKindInference_AClosureBesideAUnionOfObjectsDistributes`, + `schema.TestAllOf_ACatchAllLeavesAClosureAfterCompositionSayingNothing`, + `annotation.TestClosesAfterComposition_OnlyWhereNoAdditionalPropertiesSitsBeside`, + `e2e.TestKindInference_AClosureRefusingWhatEveryBranchRequiresAdmitsNothing`, `e2e.TestKindInference_ACatchAllBesideAUnionOfObjectsDistributes`, `schema.TestCloserOf_NamesTheObjectWhoseClosureTypesTheModel`, `schema.TestKeepUnclosing_AClosureBesideAnEntrysMembersIsKeptOnce`, `e2e.TestEntryClosure_AClosureOfTheOnlyEntryDeclaringMembersIsTyped`, `e2e.TestEntryClosure_TheEntryAndTheBesideSpellingsAreOneModel`, - `e2e.TestEntryClosure_AClosureThatIsNotTheOnlyDeclarationOfMembersIsKeptWhole`, - `e2e.TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsKept`, + `schema.TestCatchAllScope_WhatItRefusesOfComposedMembersIsSaid`, + `e2e.TestEntryClosure_ABesideClosureReadingAnotherConjunctsMembersIsTypedAndKept`, `e2e.TestEntryClosure_AClosureBesideTheAllOfOfAnObjectWritingItIsTyped`, `e2e.TestEntryClosure_APatternBesideTheAllOfIsTypedWhateverItsEntriesDeclare`, `e2e.TestEntryClosure_TheClosureBesideTheAllOfIsTheModelsBeforeAnEntrys`, `e2e.TestEntryClosure_TwoEntriesWritingAClosureTypeNeither`, - `e2e.TestEntryClosure_AClosureBesideAUnionsOwnMembersIsKept`, + `e2e.TestEntryClosure_AClosureRefusingEveryBranchsMemberLeavesTheRest`, `e2e.TestEntryClosure_UnevaluatedPropertiesBesideTheClosingEntry`, `e2e.TestEntryClosure_ARefEntrysOwnMembersAreDeclaredBesideTheClosure`, `e2e.TestEntryClosure_AClosureBesideAUnionReadsTheAllOfAlike`, `e2e.TestEntryClosure_AUseRepeatedLeavesTheModelOfTheClosureAlone`, `e2e.TestEntryClosure_TheEntryOrderLeavesTheDocumentAlone` -- Status: partly built: the closure is typed beside an applicator kept verbatim that evaluates a - member, an inline `allOf` entry kept whole for its `additionalProperties` or - `patternProperties`, `then`, `else` or `dependentSchemas`, so the typed members refuse one the - source admits (#1904); and what a target does with a model closed after composition is open, as - no emitter rule reads it yet (#1868). +- Status: partly built: what a target does with a model closed after composition is open, as no + emitter rule reads it yet (#1868). A closure after composition beside an applicator kept verbatim + that evaluates a member, an `if`, a `dependentSchemas` or an inline `allOf` entry kept whole for + its `additionalProperties` among them, is kept with the other unevaluated keywords and closes no + model ([`validation-only`](#validation-only)). ### `required-members` @@ -5176,22 +6206,27 @@ reads it, a `List` over the top type, and is reported once as an `openapi/missin warning at the schema's own pointer, wherever it sits (a property, a parameter's schema, an `items`, a union branch) and whatever it lowers to (a `Tuple`, an enum of arrays), since the report reads the declaration and not the node. Nothing is dropped or degraded, so no `openapi/degraded-construct` -accompanies it. `items: {}` is silent, as is every schema at 3.1 and 3.2, where `items` is optional. -A schema writing a `$ref` is held to the rule by the keywords beside it, which the lowering applies -([`later-version-construct`](#later-version-construct)), where nothing they conjoin with writes an -`items` either: beside a `$ref` landing on a schema that writes one, through an alias or an `allOf` -as well, a `type: array` leaves the elements to it, and `{$ref: X, type: array}` is then as silent as -`{allOf: [{$ref: X}, {type: array}]}`. An `items` written in a union's branches does not count, nor -does `items: true`, which holds the elements to nothing. An inline `allOf` entry, which merges in -place or restates what a refinement names, is not reported, nor is a subschema kept verbatim, such as -one under `not`; the entry a refinement lowers from is reported as the position it is -([`allof-refinement`](#allof-refinement)). +accompanies it. `items: {}` reports nothing, as does every schema at 3.1 and 3.2, where `items` is +optional. A schema writing a `$ref` is held to the rule by the keywords beside it, which the +lowering applies ([`later-version-construct`](#later-version-construct)), where nothing they conjoin +with writes an `items` either: beside a `$ref` landing on a schema that writes one, through an alias +or an `allOf` as well, a `type: array` leaves the elements to it, and `{$ref: X, type: array}` then +reports as little as `{allOf: [{$ref: X}, {type: array}]}`. An `items` written in a union's branches +does not count, nor does `items: true`, which holds the elements to nothing. The rule is asked of +the conjunction, not of an entry: a `type: array` the position or an inline `allOf` entry writes +draws one warning, at the position, where no conjunct, a `$ref`'s target included, writes `items`, +so `{allOf: [{type: array}, {items: …}]}` reports nothing and `{allOf: [{type: array}, {type: +array}]}` is reported once at its schema, whichever entry the refinement lowers from +([`allof-refinement`](#allof-refinement)). A `$ref`'s target is reported where it is written, so a +conjunction over a target that writes none draws its own warning beside the target's. A subschema +kept verbatim, such as one under `not`, is not reported. - Cases: `missing-array-items` - Codes: `openapi/missing-array-items` - Tests: `schema.TestLower_MissingArrayItems`, `schema.TestLower_ListWithoutItems`, `schema.TestLower_MissingArrayItemsAtAReferencedPositionWarnsOnce`, - `schema.TestRefinement_MissingItemsIsAskedOfTheEntryThatLowers` + `schema.TestRefinement_MissingItemsIsAskedOfTheConjunction`, + `e2e.TestKeywordScope_AMissingItemsIsJudgedPerConjunction` ### `tuples` @@ -5200,21 +6235,23 @@ one under `not`; the entry a refinement lowers from is reported as the position `prefixItems`, which 2020-12 applies to every element past them: `items: false` leaves no `Rest`, an absent `items` reads as `true`, the top type, and either of those or a schema lowers exactly as a `List`'s `items` would, at the same pointer and under the same hint. An `unevaluatedItems` beside -them stays the verbatim entry [`validation-only`](#validation-only) keeps, as it does beside a -`List`, reported as an info `openapi/validation-only-keyword`: beside an `items` it is inert and -kept with that `items`, and beside `prefixItems` alone it is live, so `Rest`, the top type an -absent `items` reads as, admits elements the entry refuses unless composition evaluates them, and -the entry is what closes the tuple. The same holds of a `List`'s `ElementType`. +an `items` says nothing and is kept with that `items`, as [`validation-only`](#validation-only) +keeps it, reported as an info `openapi/validation-only-keyword`. Beside `prefixItems` alone it is +live, and where every evaluator it reaches is one the IR types it types the elements past the +prefix, so nothing is kept: `false` leaves no `Rest`, and a schema is the `Rest`, lowered at its own +pointer; a `List` writing neither `items` nor `prefixItems` takes it as its `ElementType` the same +way. Reaching a `contains`, or reached through an `allOf` entry or a `$ref`, it stays that verbatim +entry, beside the `Rest` or `ElementType` an absent `items` reads as. JSON Schema drafts 4, 6 and 7 and 2019-09 write a tuple as `items` holding a list, its rest as the `additionalItems` beside it. In a schema read in one of them where it is written -([`dialect-keywords`](#dialect-keywords)), as a type list's array variant is though its node stands +([`dialect-keywords`](#dialect-keywords)), as a type list's array variant is though its node lies at a pointer of its own ([`type-arrays`](#type-arrays)), the list lowers to a `Tuple`'s `ElementTypes`, one per entry, each a schema whose `$ref` is bound, and `additionalItems` to its `Rest` as 2020-12's `items` does beside `prefixItems`: `false` leaves none, and an absent one reads -as `true`. A written `additionalItems` leaves an `unevaluatedItems` beside the list inert, as that -`items` does, and an absent one leaves it live. Each entry is named as a `prefixItems` entry is, and -the rest as an `items` schema is. Each is judged as its 2020-12 twin is +as `true`. A written `additionalItems` leaves an `unevaluatedItems` beside the list saying nothing, +as that `items` does, and an absent one leaves it live. Each entry is named as a `prefixItems` entry +is, and the rest as an `items` schema is. Each is judged as its 2020-12 twin is ([`validation`](#validation)), whether or not a `$ref` reaches it: an entry no schema spells, such as `5` or `null`, is an `openapi/validation` error at it, and a rest no schema spells an error at it, or for `null` the warning a `null` field draws, read as left out, as `items` is beside @@ -5245,12 +6282,10 @@ saying what a document of its version writes instead, and the lowering reads `it `e2e.TestOlderDrafts_AMalformedTupleIsReportedAsItsTwinIs`, `e2e.TestOlderDrafts_ATypeListsArrayVariantIsTheTupleWritten`, `e2e.TestOlderDrafts_ATupleIsReadInTheDialectWhereItIsWritten`, - `schema.TestPreserveUnknownKeywords_ReadsWhatADraftSpellsOtherwise`, + `schema.TestKeepUnknownKeywords_ReadsWhatADraftSpellsOtherwise`, `reftable.TestTuples_AListOfItemsHoldsSchemas`, `load.TestLandingTargets`, `specrules.TestCheck_AnItemsListFollowsTheSchemasRows`, `schema.TestLower_PrefixItemsBesideAListedTupleIsKept` -- Status: open: whether a `Rest` or an `ElementType` beside a live `unevaluatedItems: false` is - typed rather than left to the entry (#1883). ### `shape-applicator` @@ -5272,7 +6307,7 @@ policy is off, where the position lowers to the top type, which says strictly le applicator does (`{items: {type: string}}` constrains every array instance). A schema naming no kind, one writing no `type` or a null one and no family -[`competing-keywords`](#competing-keywords) elects first, lowers as the same schema writing the +[`competing-keywords`](#competing-keywords) chooses first, lowers as the same schema writing the `type` the keywords giving its instances a type speak of, under the kind-inference policy ([`policies`](#policies)): the Go option `Options.KindInference`, whose zero value is on, and the text option `kind-inference`, which `false` turns off. A keyword JSON Schema applies to instances of @@ -5284,8 +6319,11 @@ an object, `items` and `prefixItems` of an array. A `properties`, a `patternProp null or with no member, an empty `required` and a null `items` speak of none. Only a keyword giving the type of a member, an element or a value infers its kind: a `properties` or a `patternProperties` listing a member, a `prefixItems` listing a position, a list of `items`, and an -`additionalProperties` or an `items` holding a schema that writes a keyword. A `required` and a -`discriminator` type nothing, nor does a closure, `false`, or a `true` or `{}`, of which Core says +`additionalProperties` or an `items` holding a schema that writes a keyword past identifier and +meta keywords (`$id`, `id`, `$schema`, the anchors, `$vocabulary`, `$comment`, `$defs`, +`definitions`), a note or an extension among them. A `required` and a +`discriminator` type nothing, nor does a closure, `false`, or a `true`, a `{}` or a schema writing +only identifier and meta keywords, of which Core says omitting the keyword "has the same assertion behavior as an empty schema" (§10.3.1.2, §10.3.2.3): a schema writing only such keywords lowers as with the policy off, to the top type keeping them, and beside a keyword that infers they bind the node it builds, as a `required` names a member of the @@ -5297,39 +6335,39 @@ property, an element, a body or a union's branch alike, and each variant of such `kind-inference` in its `Provenance.Inferred`, and nothing is reported, as the document leaves the kind unsaid. That node excludes the instances of another kind the schema admits, a string under `{properties: …}` among them, which is why the reading is a policy and can be turned off. A -keyword's kind is a claim of the position, never a narrowing of the schema object writing it: the +keyword's kind is what the position says, never a narrowing of the schema object writing it: the conjuncts of an `allOf`, a `$ref` and a union apply together, and each passes an instance of a kind its keywords do not speak of, so `{allOf: [{type: string}, {items: {type: string}}]}` admits every string. The run's reading of what a schema admits ([`constraints`](#constraints)) conjoins first what the position declares, its `type` and value sets and those of each conjunct, a `$ref`'s target and a union's branches among them, and lowers to that wherever it names a kind; only where nothing -declares one do the claims decide, the keywords' own united with those of each conjunct whose kind -is a claim, and only then is the node marked. So that schema is a use of the string keeping its -entry with an info, as with the policy off, and a `$ref` whose target the policy reads as kinds -leaving out one the declarations name is no principal ([`allof-refinement`](#allof-refinement)). An `allOf` -composed as a model where no conjunct declares a kind, as one over two `$ref`s to schemas writing -`properties` alone, is marked. Split over entries, a keyword infers as in its flat spelling where the -claims of one conjunct name every kind the position lowers to: that conjunct is the principal +declares one do the kinds the keywords say decide, the keywords' own united with those of each +conjunct whose kind is only said so, and only then is the node marked. So that schema is a use of +the string keeping its entry with an info, as with the policy off, and a `$ref` whose target the +policy reads as kinds leaving out one the declarations name is no principal +([`allof-refinement`](#allof-refinement)). An `allOf` composed as a model where no conjunct declares +a kind, as one over two `$ref`s to schemas writing `properties` alone, is marked. Split over +entries, a keyword infers as in its flat spelling where the kinds one conjunct's keywords say name +every kind the position lowers to: that conjunct is the principal ([`allof-refinement`](#allof-refinement)), so `{allOf: [{items: …}]}` is the marked `List` its entry -builds, standing at the position as `{items: …}` is, and a bound of another kind beside a `$ref` to it -is placed by the `List`. Keywords of both kinds part from their flat -spelling: `{allOf: [{properties: …}, {items: …}]}` admits an object and an array, so it is no model -but the top type keeping each entry, where `{properties: …, items: …}` is the marked union. A reader asking whether a position -already says what a keyword does, as a union lowered alone restating the body's `type` or a body -whose union branches restate it, reads the kind what it compares to lowers to, whether its +builds, lying at the position as `{items: …}` does, and a bound of another kind beside a `$ref` to +it is placed by the `List`. Keywords of both kinds part from their flat spelling: `{allOf: +[{properties: …}, {items: …}]}` admits an object and an array, so it is no model but the top type +keeping each entry, where `{properties: …, items: …}` is the marked union. A reader asking whether a +position already says what a keyword does, as a union lowered alone restating the rest's `type` or a +rest whose union branches restate it, reads the kind what it compares to lowers to, whether its conjuncts declare it or the policy reads it: keywords written with no `type` beside branches each -declaring an object are that object, so branches restating it only narrow the body under either -policy, as beside `type: object`. A bound -beside such a schema is placed by the kind it lowers to, and the reading decides whether the schema -names no kind. Where a conjunct beside it names kinds, as a union kept -beside it does ([`union-beside-structure`](#union-beside-structure)), the keywords name a kind only -where every kind the conjuncts admit is one they speak of, and the schema lowers to those: unmarked -where the document declared them, as `{oneOf: [{type: object, …}], additionalProperties: false}` -declares an object, and marked where a conjunct names its own by the policy's reading, as a branch -writing `properties` alone does. Where the conjuncts admit a kind the keywords do not speak of -(`{oneOf: [{type: object, …}, {type: string}], required: [a]}`), the keywords would narrow what the -document declares, so under either policy the schema is the top type keeping them. A union that -distributes across a body the policy read as an object +declaring an object are that object, so branches restating it only narrow the rest under either +policy, as beside `type: object`. A bound beside such a schema is placed by the kind it lowers to, +and the reading decides whether the schema names no kind. Where a conjunct beside it names kinds, as +a union kept beside it does ([`union-beside-structure`](#union-beside-structure)), the keywords name +a kind only where every kind the conjuncts admit is one they speak of, and the schema lowers to +those: unmarked where the document declared them, as `{oneOf: [{type: object, …}], +additionalProperties: false}` declares an object, and marked where a conjunct names its own by the +policy's reading, as a branch writing `properties` alone does. Where the conjuncts admit a kind the +keywords do not speak of (`{oneOf: [{type: object, …}, {type: string}], required: [a]}`), the +keywords would narrow what the document declares, so under either policy the schema is the top type +keeping them. A union that distributes across a rest the policy read as an object ([`union-beside-structure`](#union-beside-structure)) marks each variant it composes over a branch that declares no object, as that variant is a model only by the policy's reading. With the policy off, a schema naming no kind is the top type, its shape keywords kept as any unhomed keyword is. @@ -5369,9 +6407,12 @@ any reads it, a value bound where a variant whose type takes it does: a distribu `properties` are consumed, and a `format` or `maxItems` beside them is kept on the union, under a report naming a union of models. -- Cases: `unhomed-keywords`, `empty-enum`, `keywords-at-every-outcome`, `allof-entry-infers-array` +- Cases: `unhomed-keywords`, `empty-enum`, `keywords-at-every-outcome`, `allof-entry-infers-array`, + `silent-applicator` - Codes: `openapi/degraded-construct` - Tests: `schema.TestObject_ACatchAllBesideARequiredNameStaysAModel`, + `e2e.TestKeywordScope_AnApplicatorHoldingOnlyIdentifiersSaysNothing`, + `statement.TestSchema_WritesOnlyIdentifierAndMetaKeywords`, `e2e.TestKindInference_AnEntryClaimNamesNoKindItDoesNotHoldAlone`, `e2e.TestKindInference_ABoundBesideARefToAnInferredListIsPlacedByTheList`, `e2e.TestKindInference_AnUntypedPropertiesSchemaIsMarked`, @@ -5394,8 +6435,8 @@ report naming a union of models. `e2e.TestKindInference_EachVariantOfATwoKindUnionIsMarked`, `e2e.TestKindInference_ATwoKindUnionIsOneInEitherKeywordOrder`, `e2e.TestKindInference_AKindAConjunctNamesIsDeclared`, - `e2e.TestKindInference_KeywordsNarrowingAKeptUnionNameNoKind`, - `e2e.TestKindInference_APropertySetBesideAUnionOfOtherKindsIsTheTopType`, + `e2e.TestKindInference_ObjectKeywordsBesideAnObjectAndAStringDistributeByKind`, + `e2e.TestKindInference_APropertySetBesideAUnionOfOtherKindsDistributesByKind`, `e2e.TestKindInference_AKindReadThroughAnInferredBranchIsMarked`, `e2e.TestKindInference_AVariantComposedOverAnInferredBodyIsMarked`, `e2e.TestKindInference_ADeclaredKindDecidesBesideAnEntryTheKeywordsClaim`, @@ -5407,7 +6448,7 @@ report naming a union of models. `e2e.TestKindInference_OnlyAKeywordGivingATypeInfersItsKind`, `e2e.TestKindInference_AKeywordTypingNothingStillSpeaksOfItsKind`, `e2e.TestKindInference_ANarrowingBesideATypingKeywordStaysOnItsModel`, - `e2e.TestKindInference_AClosureBesideAUnionOfObjectsDistributes`, + `e2e.TestKindInference_AClosureRefusingWhatEveryBranchRequiresAdmitsNothing`, `e2e.TestKindInference_ACatchAllBesideAUnionOfObjectsDistributes`, `e2e.TestKindInference_AClosureBesideAUnionOfOtherKindsIsTheTopType`, `e2e.TestKindInference_AClosedFormBodyBesideAUnionKeysNoPartItsModelsLack`, @@ -5415,7 +6456,7 @@ report naming a union of models. `schema.TestUnhomedApplicator_KeptOnAListAndAnnounced`, `schema.TestUnhomedApplicator_FormatWithNoTypeIsKept`, `schema.TestUnhomedApplicator_AFormatOnAnArrayIsKeptNotRead`, - `schema.TestPreserveUnknownKeywords_ReadsWhatADraftSpellsOtherwise` + `schema.TestKeepUnknownKeywords_ReadsWhatADraftSpellsOtherwise` ### `string-formats` @@ -5438,51 +6479,84 @@ under `number`, whose `Encoding` is `string`, a number written as the text of it `Encoding.Name` is the format as written, case kept, with no `WireType`, since the compiler knows no registry of formats beyond these, and the table leaves out `time`, RFC 3339's `full-time`, because it carries an offset and the `time` primitive holds none -([primitives](../ir/primitives.md#offsets)). A `contentEncoding` beside such a format, a numeric or -an unknown one names the encoding instead; where the two name different encodings the format is -kept verbatim under `openapi:format` (`no_ir_home`) with an info `openapi/degraded-construct` at it. -A format of the first kind so kept leaves the primitive and the `WireType` it selects in place, -while a numeric format so kept selects no base, since the string is then that encoding's text and -not a number's: -`{type: string, format: int64, contentEncoding: base64}` lowers to a `Scalar` over `string` under +([primitives](../ir/primitives.md#offsets)). A `contentEncoding` beside a format names the encoding +instead; where the format names another encoding, or reads a value from the text, it is kept +verbatim under `openapi:format` (`no_ir_home`) with an info `openapi/unhomed-construct` at it. A +format reading a value from the text, an instant's, a date's, a time's, a duration's, `uuid`'s, +`uri`'s, `http-date`'s, a string `unixtime`'s or a number's written as its text, so kept selects no +base: the string is then that encoding's text, whose content once decoded is binary data (JSON Schema +Validation 2020-12 §8.3), while a format describes the text it is written on (§7.3), so +`{type: string, format: date-time, contentEncoding: base64}` and +`{type: string, format: int64, contentEncoding: base64}` each lower to a `Scalar` over `string` under `base64` with no `WireType`, as the encoding alone does -([`content-vocabulary`](#content-vocabulary)). A scalar hoisted for its format carries the bounds -written beside it, but for a number carried as text, whose `Constraints` speak of the number -([constraints](../ir/constraints.md#constraints)): a length or a `pattern` bounds its text and a -numeric bound no string instance, so each value bound written beside it is kept verbatim under -`openapi:` (`no_ir_home`) on the `Scalar` alone with an info `openapi/degraded-construct` -at it, one an inline `allOf` entry writes, and one beside an `allOf` whose inline principal it is, -the same way ([`allof-inline-residue`](#allof-inline-residue)), both on the `Union` where the -principal is a type list whose `string` variant carries the number, where the flat spelling keeps -them on that variant, and neither the `Scalar` nor a property or parameter carrying it holds one. A -type list whose other listed type pairs with the format leaves its `string` variant the text, -which reads a length or a `pattern` written beside it or beside an `allOf` whose principal the list -is, as each variant reads the bounds of its kind there, and nothing keeps or reports them. The table is the same at every minor, and a pairing of `format` -with another `type` is [`numeric-formats`](#numeric-formats)'. Beside a type array, a format the -table pairs with `string`, `byte` and `http-date` among them, is the `string` variant's alone +([`content-vocabulary`](#content-vocabulary)). A format whose base is `bytes` keeps it, and the +`WireType` it selects: `{type: string, format: byte, contentEncoding: base64url}` is `bytes` under +`base64url`, its format kept. The two may be written on different conjuncts of an `allOf`, each +having any conjunct in its keyword scope, and lower as written flat, the format kept where it is +written. A keyword of the text, a length or a `pattern`, binds only text, as `Constraints` speak of +the value ([constraints](../ir/constraints.md#constraints)): it reaches the `Constraints` of a node +whose value is that text, a `Scalar` whose chain ends on `string` or the top type with no +`WireType`, or on `binary`'s `bytes`, whose length counts octets, an `Enum` whose `ValueType`, its +root, is `string`, or a `Union` whose string variants are such text or `Literal`s whose `ValueType` +is `string` ([`constraints`](#constraints)). Beside a string whose value is of another kind, every +other pairing above (an instant, a date, a time, a duration, a `uuid`, a `url`, `byte`'s or +`base64url`'s bytes, `http-date`'s or a string `unixtime`'s instant) and a number written as its +text, it is kept verbatim under `openapi:` (`no_ir_home`) with an info +`openapi/unhomed-construct` at it, on the node or carrier that wrote it: the `Scalar` hoisted for +the format, the alias over a reference to one, decided from the referent's schema, or a property, +parameter or header over a shared primitive, which keeps it in its own `Unmodeled` with no node +hoisted for it. Where an inline principal speaking for its position writes one that the position +writes otherwise, the position's takes the plain key and the principal's its entry key. A numeric +bound beside a number written as text is kept the same way, as JSON Schema applies it to no string +instance, and the `Scalar` carrying such a number keeps every value bound written beside it so; one +an inline `allOf` entry writes, and one beside an `allOf` whose inline principal it is, is kept the +same way ([`allof-inline-residue`](#allof-inline-residue)), on the `string` variant where the +principal is a type list carrying the value there, as the flat spelling keeps them. Any other bound +of no kind the node takes is kept as [`constraints`](#constraints) keeps one. Writers of one bound +beside a number written as text or a `Scalar`'s text of another kind, the node's own schema among +them, intersect as any bound's do, and the node keeps the writing of the value they intersect to, +its own schema's before a conjunct's and of conjuncts the first, each other writing kept nowhere: +`minimum: 31` on one entry and `minimum: 40` on another keep the `40`. Where none writes that value, +two steps whose common multiple neither writes, the node keeps the value, `6` of `2` and `3`, its +info naming it, but beside an inline principal kept whole, which holds that value with it, each +writer's own is kept as written, the position's under its key and an entry's under the entry's; +writers meeting in none, two patterns, keep their entries whole, reported as conjuncts that disagree +(`openapi/degraded-construct`). A type list whose other listed type pairs with the format leaves its +`string` variant the text, which reads a length or a `pattern` written beside it or beside an +`allOf` whose principal the list is, as each variant reads the bounds of its kind there, and nothing +keeps or reports them. The table is the same at every minor, and a pairing of `format` with another +`type` is [`numeric-formats`](#numeric-formats)'. Beside a type array, a format the table pairs with +`string`, `byte` and `http-date` among them, is the `string` variant's alone ([`type-arrays`](#type-arrays)). - Cases: `encoding-byte`, `scalar-format` -- Codes: `openapi/degraded-construct` +- Codes: `openapi/degraded-construct`, `openapi/unhomed-construct` - Tests: `schema.TestLower_ATypeArraysFormatIsTheVariantsItPairsWith`, + `e2e.TestNumberText_TwoConjunctsOfABoundIntersect`, + `e2e.TestNumberText_TwoConjunctsIntersectingInAValueNoneWritesKeepIt`, + `schema.TestScalar_StepsPastAWholePrincipalKeepEachConjunct`, + `schema.TestScalar_ConjunctsWritingATextVariantsBoundIntersect`, `schema.TestScalar_UnknownFormatPerBaseType`, `schema.TestScalar_EncodedFormatPairings`, `schema.TestScalar_AnEncodedFormatKeepsTheBoundsWrittenBesideIt`, - `schema.TestScalar_AnEncodedFormatBesideContentEncodingKeepsItsPrimitive`, + `schema.TestScalar_AnEncodedFormatBesideContentEncodingReadsTheText`, + `e2e.TestContentEncoding_AFormatReadFromTheTextIsKeptAndTheBaseStaysString`, + `e2e.TestContentEncoding_ABytesFormatKeepsBytes`, + `e2e.TestContentEncoding_OnAnotherConjunctReadsTheFormatAsFlat`, `schema.TestScalar_ANumberAsTextIsItsNumberOnAString`, `schema.TestScalar_ANumberAsTextKeepsItsBoundsVerbatim`, `e2e.TestNumberText_ABoundBesideAPrincipalIsKeptAsFlat`, - `e2e.TestNumberText_TwoWritersOfABoundKeepBoth`, + `e2e.TestTextBounds_AKeywordOfTheTextBindsOnlyText`, + `e2e.TestTextBounds_ACarrierOverASharedPrimitiveKeepsItsOwn`, + `e2e.TestTextBounds_AReferenceToTextOfAnotherKindKeepsItsBounds`, + `e2e.TestTextBounds_AnEnumOrATypeListOfAnotherKindsTextKeepsIt`, + `schema.TestPrincipalKept_APatternBesideThePrincipalsKeepsBoth`, `schema.TestPrincipalKept_ABoundATypeListVariantReadsIsKeptNowhere`, `schema.TestLower_NamedScalarComponentResolves`, `merge.TestKindOf_ANumberAsTextIsAString`, `typeformat.TestFormatTable_EveryRowDistinguishesTheBareType`, `typeformat.TestFormatTable_EveryStringRowLowersToItsPrimitive`, `typeformat.TestEncodedTable_IsApartFromTheFormatTable` -- Status: partly built: a value bound beside a `$ref` to a number carried as text, or beside an - `allOf` refining one, lands in the `Constraints` of the alias over it, and a length or `pattern` - beside `byte`, `base64url` or `http-date` in those of its `bytes` or `datetime_offset`, which - speak of the bytes or the instant, though it bounds the text they travel as (#1851). ### `numeric-formats` @@ -5500,20 +6574,29 @@ hoisted `Scalar` over the type's primitive that keeps the format as `Encoding.Na `contentEncoding` beside a `string`'s `unixtime` takes that field, and the format is kept verbatim under `openapi:format` (`no_ir_home`) with an info `openapi/degraded-construct` at it; beside a number's format it applies to strings alone and takes nothing from it -([`content-vocabulary`](#content-vocabulary)). Beside a type array, a format the table pairs with a +([`content-vocabulary`](#content-vocabulary)). A numeric bound beside `unixtime` on a `number` or an +`integer` bounds the seconds the instant is written as, not the instant the `Scalar`'s +`Constraints` speak of, so it is kept verbatim under `openapi:` (`no_ir_home`) with an +info `openapi/unhomed-construct` at it, on the node or carrier that wrote it, as +[`string-formats`](#string-formats) keeps a length beside an instant written as text: on the +`Scalar` the format hoists, on an alias over a reference to one, decided from the referent's +schema, on a carrier over such a reference, on a type list's variant and on a `Union` a branch of +which is such seconds. The `type` and the `format` may be written on different conjuncts, the +referent's among them, and the bound on either or beside them, and each spelling keeps it as the +flat one does ([`constraints`](#constraints)). Beside a type array, a format the table pairs with a listed number is that variant's alone, so a width beside `integer` and `number` is both variants' ([`type-arrays`](#type-arrays)). - Cases: `scalar-format` -- Codes: `openapi/degraded-construct` +- Codes: `openapi/degraded-construct`, `openapi/unhomed-construct` - Tests: `schema.TestScalar_NumericFormatPairings`, `schema.TestScalar_EncodedFormatPairings`, + `schema.TestScalar_AnEncodedFormatKeepsTheBoundsWrittenBesideIt`, + `schema.TestBoundRoot_ANumericBoundBesideAnInstantsSecondsIsKept`, + `schema.TestBoundRoot_EverySpellingPlacesABoundAsTheFlatOneDoes`, `schema.TestContentVocabulary_KeptWhereNoEncodingHolds`, `schema.TestContentVocabulary_ANumberTakesNone`, `schema.TestLower_ATypeArraysFormatIsTheVariantsItPairsWith` -- Status: partly built: a numeric bound beside `unixtime` on a `number` or an `integer` lands in the - `Scalar`'s `Constraints`, which speak of the instant, though it bounds the seconds it travels as - (#1851). ### `password` @@ -5543,10 +6626,10 @@ its scalars, as `string` or `bytes`. A name's last words decide what it names, s and `passPhrase` name one, and `token` alone names none, since one API calls a credential so and another a unit of text; a value of another type, as `has_password: {type: boolean}` or a `secret` object holding a credential's parts, is none either. Such a name on such a type is the policy's -trigger, and it declines nothing that meets it: the document has spoken where the use is already +trigger, and it declines nothing that matches it: the document has spoken where the use is already `Secret` or its type `Sensitive` ([`password`](#password)), and where a redaction key the promotion maps is written on the use or on a node its type reads through, so `x-sensitive: false` keeps a -credential's name from asking. What it fills the document leaves silent, so nothing is reported. The +credential's name from asking. What it fills the document leaves unsaid, so nothing is reported. The reading waits for the document to be whole, since a `$ref` can name a type built after its use. On the golden spec, of the 123 uses its words and types match, the document redacts 93 itself, and the policy marks the other 30: the 2 `R2-Secret-Access-Key` header parameters and 28 members, 17 @@ -5655,13 +6738,39 @@ vocabulary has no type to break and is kept with the `null` it wrote, as [`unknown-keys`](#unknown-keys) keeps any value. An empty dependency map is read the same way ([`validation-only`](#validation-only)). The load phase reports each such `null` at the node as the warning a field left out draws ([`validation`](#validation)); the lowering reports nothing -of its own, since reading it so loses nothing. +of its own, since reading it so loses nothing. A `null` on a key no dialect defines is a value, +so another writer of the node giving that key another value writes it otherwise +([`allof-inline-residue`](#allof-inline-residue)). + +A keyword written at the value JSON Schema or OpenAPI equates with its absence, in a dialect +defining it, says nothing: `readOnly`, `writeOnly`, `deprecated` and `uniqueItems` `false` +(Validation 2020-12 §9.3, §9.4), `minLength`, `minItems` and `minProperties` `0`, `required: []` +where the dialect admits the empty list, as 3.0's and draft 4's do not, at 3.0 `nullable: false` +and a boolean `exclusiveMinimum` or `exclusiveMaximum` `false`, and `pattern: ""`, which matches +every string. It is read as the keyword left out wherever it is written, so the schema lowers as +it does with the key removed: `{type: string, minLength: 0}` is the `Scalar` holding no bound, and +nothing is kept or reported for it. Beside a `$ref` it is no conjunct, so +`{allOf: [{$ref: Obj}], nullable: false}` lowers as `{allOf: [{$ref: Obj}]}` does +([`allof-classification`](#allof-classification)); it writes nothing another conjunct agrees or +disagrees with ([`allof-inline-residue`](#allof-inline-residue)); and a member one declaration +bounds by such a value and another not at all folds as two bounding it by nothing do +([`allof-redeclared-property`](#allof-redeclared-property)). Any other value says something: +`format: ""` is an annotation whose value is collected, `additionalProperties: true` changes what +an unevaluated keyword beside it admits, and at 3.1 and 3.2 `nullable` is a key no dialect defines, +kept verbatim. - Cases: `null-keywords` - Codes: `openapi/invalid-numeric-literal` - Tests: `e2e.TestCompile_ANullKeywordLowersAsTheKeywordLeftOut`, `e2e.TestCompile_ANullIdentifierLowersAsTheKeywordLeftOut`, `statement.TestSchema_KeyReadsANullKeywordAsLeftOut`, + `statement.TestSchema_KeyTellsAValueEquatingToAbsence`, + `schema.TestRefinement_AKeywordSayingNothingLowersAsLeftOut`, + `schema.TestRestatedReferent_AnEntryRestatingTheReferentsKeywordSaysNothing`, + `specrules.TestSchemaRules_ReadEachKeyAsTheLoweringDoes`, + `e2e.TestAbsentValue_AnEmptyRequiredIsRefusedWhereTheDialectRequiresAnEntry`, + `e2e.TestAbsentValue_AnyOtherValueSaysSomething`, + `e2e.TestPendingKeeps_ANullOnAKeyNoDialectDefinesIsAValue`, `reftable.TestDynamicAnchor_ANullAnchorNamesNothing`, `specrules.TestCheck_NullIsReadAsAbsentWhereTheFieldIsOptional`, `e2e.TestCompile_ANullBeneathItsOwnNameLowersAsTheKeywordLeftOut` @@ -5673,35 +6782,48 @@ A schema whose own keywords leave it no value but `null` lowers, at its own posi the reference naming it admits `null` where the schema does ([`nullable`](#nullable)): a position admitting `null` and nothing else is a nullable reference to that `Enum`, and one admitting nothing is a reference to it that is not. Its own keywords leave it `null` alone where it writes no `$ref`, -`allOf`, `oneOf`, `anyOf` or `$dynamicRef`, an `enum` it writes lists `null` and nothing else, -within the `Limits.MaxEnumMembers` past which an `enum` lowers to the top type, and it writes a -`const`, such an `enum`, or a `type` naming `null` and no other type, as `type: "null"` and -`type: ["null"]` do. An `enum` and a `const` lower so by [`enum-const`](#enum-const). A `type` +`allOf`, `oneOf`, `anyOf`, `$dynamicRef` or `enum: []`, and it writes a `type` naming `null` and no +other type, as `type: "null"` and `type: ["null"]` do, an `enum` listing `null` and nothing else, +within the `Limits.MaxEnumMembers` past which an `enum` lowers to the top type, or a `const`. A +`type` of `null` alone decides over an `enum` beside it: listing `null`, the schema admits `null` +alone, and not listing it, nothing; either way the members the type excludes are kept verbatim, +under `openapi:enum` (`degraded_lowering`) where the schema lowers at its own position and in the +branch kept whole under its entry key where it is a union's null branch, each reported as an +`openapi/unsatisfiable-schema` warning at the member, and the `enum` kept at the schema's own +position draws an info `openapi/degraded-construct` saying the type decides over it. An `enum` and a +`const` lower so by [`enum-const`](#enum-const). A `type` naming only `null`, with neither beside it, lowers so too, not to the top type behind a nullable reference, which admits every value: `{anyOf: [{}, {type: "null"}]}` lowers to that, and a consumer could not tell the two apart. The `Enum`'s `ValueType` is what the schema's `type` and `format` -select, as an enumeration's is, the top type where they select none. A keyword the `Enum` has no +select, as an enumeration's is, the top type where they select none, and no other conjunct of an +`allOf` narrows it, as none admits a value of a type it names: `{allOf: [{type: [string, 'null']}, +{type: 'null'}]}` is the `Enum` `{type: 'null'}` is, written beside the `allOf` or on an entry, and +so is its 3.0 spelling with `enum: [null]`. A keyword the `Enum` has no field for, such as `properties`, `items`, a `format` or a bound, is kept unread ([`shape-applicator`](#shape-applicator)) under `openapi:` (`degraded_lowering`), with an info `openapi/degraded-construct` at the schema, and the `type` draws nothing, an `Enum` with no member typing no value. A schema writing a `$ref`, a union or an `allOf` admits what they say as well as what its own keywords do, so it lowers as they decide: a `$ref` to a schema of `null` alone names that schema's `Enum`, nullable as the reference reads it ([`ref-use-site`](#ref-use-site)), -and an `allOf` of one alone refines to it ([`allof-refinement`](#allof-refinement)). A union's +and an `allOf` of one alone refines to it, as do conjuncts admitting null alone together +([`allof-refinement`](#allof-refinement)). A union's branch of `null` alone, written in place, is that union's `null` rather than a variant ([`union-null-variant`](#union-null-variant)), so each spelling of `null` alone lowers to the one IR -wherever it stands. +wherever it is written. - Cases: `null-alone`, `enum-null-member`, `null-only-union` -- Codes: `openapi/degraded-construct` +- Codes: `openapi/degraded-construct`, `openapi/unsatisfiable-schema` - Tests: `schema.TestNullAlone_ReadsTheSchemasOwnKeywords`, - `schema.TestNullAloneReading_IsTheWholeSchemasReading`, - `schema.TestNullAloneReading_ReadsASchemaOnce`, + `schema.TestNullAlone_IsTheWholeSchemasReading`, + `schema.TestNullAnswerOf_ReadsASchemaOnce`, `schema.TestNullBranch_AnEnumPastTheMemberBudgetIsNoNullBranch`, `schema.TestLowerNullAlone_EveryPositionNamesAnEnumWithNoMember`, `schema.TestLowerNullAlone_IsToldFromTheTopType`, `schema.TestLowerNullAlone_KeepsWhatTheEnumCannotHold`, - `schema.TestRefinement_ANullOnlyEntryIsTheNull` + `schema.TestRefinement_ANullOnlyEntryIsTheNull`, + `schema.TestNullIntersection_A30NullEntryLowersAsItsTwin`, + `schema.TestEnum_ATypeOfNullAloneDecidesOverItsMembers`, + `schema.TestNullAlone_ALiftedBranchKeepsTheMembersItsTypeExcludes` ## 7. Schemas: keywords beyond the shape @@ -5709,8 +6831,8 @@ wherever it stands. `minimum`, `maximum` and `multipleOf` lower to `Min`, `Max` and `MultipleOf`, and `minLength`, `maxLength` and `pattern` to `MinLength`, `MaxLength` and `Pattern` as written, in the `Constraints` -of the node the position owns (a `Scalar`, the `Union` a `oneOf` or `anyOf` lowers to), or of its -carrier, a `Property` or a `Parameter`, where it owns none; `minItems`, `maxItems` and `uniqueItems` +of the node the position owns (a `Scalar`, the `Union` a `oneOf` or `anyOf` lowers to, an `Enum` +or the `Union` of literals a mixed `enum` lowers to), or of its carrier, a `Property` or a `Parameter`, where it owns none; `minItems`, `maxItems` and `uniqueItems` to the `List`'s, and a `Tuple`'s per [`tuples`](#tuples), or, where the position lowers to a reference (a `$ref` site, a collapsed union or an expanded `$dynamicRef`), to the `Constraints` of the alias or carrier it owns where the types the position admits include `array`, as does one on @@ -5721,88 +6843,133 @@ instances of one kind and lets any other through (JSON Schema Validation 2020-12 the numeric bounds, the exclusive ones among them, where it admits `integer` or `number`, `minLength`, `maxLength` and `pattern` where it admits `string`, the collection bounds where it admits `array`, and `minProperties` and `maxProperties` where it admits `object`; `boolean` and -`null` take none. The types a position admits are those its node lowers from: the kinds its own -`type` declares and the members of its `enum` or `const` have, that every schema it names admits -too: what its `$ref` lands on, the keywords beside each `$ref` of the chain read with it, each -`allOf` entry, a `oneOf` or `anyOf`, which admits what any of its branches does, a branch of null -alone, written with a `type` or not, admitting none a bound applies to -([`union-null-variant`](#union-null-variant)), and the target a `$dynamicRef` or `$recursiveRef` -names ([`dynamic-ref`](#dynamic-ref)), read through as many of those as the named schemas write, -from the source and never from what has been lowered, once a compile, so no answer turns on the -order schemas are declared in or on how many the read takes in. Where that leaves every kind, it -admits the kinds the schema's shape keywords speak of under the kind-inference policy, as it lowers -to them ([`shape-applicator`](#shape-applicator)). A read meeting -a cycle of `$ref`s, `allOf` entries or dynamic references, or a `$ref` landing on no schema, -whichever schema of it is read first, leaves the position's own `type` to decide. A schema -declaring no `type` and naming none excludes nothing, so it reads every bound; one declaring `null` -alone reads none, its `Enum` with no member keeping them ([`null-alone`](#null-alone)), and so does -one whose own and named types share no kind. A bound no -type the position admits takes reaches no `Constraints`, the carrier's included, and is kept -verbatim under `openapi:` (`degraded_lowering`) with an info `openapi/degraded-construct` -naming what the position lowered to: on the node it owns, on an alias hoisted where it lowered to a -shared node or a reference, or on the carrier of a reference. A type array's variants each take -their own type's, where the position admits it ([`type-arrays`](#type-arrays)). Each named schema -is read in its own document, an inline one at its own pointer, so a dynamic reference names what it -does where that schema is lowered. A bound is read off the raw node, never the parser's `float64`, so -its `BigVal` keeps every digit the literal wrote ([`values`](#values)), a quoted one as the decimal -it spells; one that is no decimal literal a `BigVal` holds is dropped with an -`openapi/invalid-numeric-literal` error at the keyword. -Exclusive bounds follow the schema's dialect -([`dialect-keywords`](#dialect-keywords)). In 3.0's, and in JSON Schema draft 4's, the boolean -modifies the bound beside it: `true` moves that bound to `ExclusiveMin` or `ExclusiveMax` and clears -`Min` or `Max`, so a 3.0 document and its 3.1 translation lower alike, `false` states nothing, and -`true` with no bound beside it bounds nothing and is kept verbatim under `openapi:exclusiveMinimum` -or `openapi:exclusiveMaximum` (`degraded_lowering`) with an `openapi/degraded-construct` warning. In -2020-12's, the dialect 3.1 and 3.2 name, the keyword is a bound of its own, kept beside `Min`/`Max` -when both are declared, a field apiece and no `Unmodeled` entry -([constraints](../ir/constraints.md)). The other dialect's form (a boolean in 2020-12's, a number in -3.0's or draft 4's) is dropped with an `openapi/invalid-exclusive-bound` error at the keyword. Both -errors are the rule table's, made with the rows of each schema's dialect, at every schema its -[`validation`](#validation) check reads, which judges these keywords as the lowering reads them -rather than by their shape: one under `not`, `if` or `propertyNames`, or beside an `enum`, is -reported as one the lowering reads, and an aliased value once. A bound beside a `oneOf` or an -`anyOf` lowering to a `Union` of its entries ([`union`](#union)), or on an `allOf` entry folding -there, is that `Union`'s: no variant can hold it, each being its branch's node, which every use of -the branch shares. A bound has one home: the node its position owns, else the carrier, which holds -one only where its position owns no node, over a reference or a primitive every use shares, else a -node hoisted there ([one home](../ir/annotations.md#one-structural-home-per-declaration)). A -property, a parameter or a header whose position owns its node holds none of its bounds, which a -`$ref` naming that position reads on the node alone; one naming a position that owns none, a shared -primitive's, reads a `Scalar` hoisted there holding them, while the carrier keeps its own. The -node's kind decides what it holds, whatever the position admits: a `Model` or a `MapT` the property -counts alone, as its instances are objects, a `List` or a `Tuple` the collection bounds, and a -`Union` those its variants take, or its variants where the position builds them, a type list's -([`type-arrays`](#type-arrays)) or a distributed union's, each those of the kinds it admits, its -branch's within the body's ([`union-beside-structure`](#union-beside-structure)). A bound its kind does not take, and one -beside a node with no `Constraints` field (an `Enum`, a `Literal`, the `Union` of literals a mixed -`enum` lowers to), is kept verbatim on the node under `openapi:` (`degraded_lowering`), -once, with an info `openapi/degraded-construct` naming the node it lowered to, as -[`shape-applicator`](#shape-applicator) keeps a collection bound on an object -([unions](../ir/unions.md#bounds-beside-a-union)), and one an inline `allOf` entry writes there is -kept under its own key, reported at the entry ([`allof-inline-residue`](#allof-inline-residue)). A collection bound beside a reference that -`Constraints` cannot state is kept the same way: a `uniqueItems` of `false`, which a bool cannot -tell from one never written, and a count that does not fit in 64 bits. A count, -`minLength`, `maxLength`, `minItems`, `maxItems`, `minProperties` or `maxProperties`, is a -non-negative integer with no upper limit, and its field holds one up to 2^63−1: one past that, at -any node, carrier or `allOf` entry, reaches no field and is kept verbatim under `openapi:` -(`degraded_lowering`) with an info `openapi/degraded-construct` saying so where it is written, and on -an entry it parts no other ([`allof-inline-residue`](#allof-inline-residue)), but for one past what -a `BigVal` holds, which reaches the IR in no form -([`verbatim-preservation`](#verbatim-preservation)). Where several writers -of one position, its schema and the entries folding into it, give one such keyword, the one -binding the rest is kept, the smallest maximum or the largest minimum, compared exactly however -large, the first of one value written twice, with one report. Two declarations of one field are -not such writers: each keeps its own where it is written, and their fold compares the two entries as -it does any kept under `Unmodeled` ([`allof-redeclared-property`](#allof-redeclared-property)), so -of two such counts the later declaration's is kept and the other is reported and kept with its +`null` take none. A bound binds only the kind its node's value is +([constraints](../ir/constraints.md#constraints)): beside a string whose value is of another kind, +written as its text, a length and a `pattern`, beside a number written as text a numeric bound too, +and beside a number whose value is of another kind, an instant's seconds, a numeric bound, reach no +`Constraints`, each kept verbatim under `openapi:` (`no_ir_home`) with an info +`openapi/unhomed-construct` on the node or carrier that wrote it ([`string-formats`](#string-formats), +[`numeric-formats`](#numeric-formats)). What the value is, is the settled node's, whichever +conjunct, `$ref` target or union branch writes the `type`, the `format` or the `contentEncoding` it +is read from, so every spelling places a bound as its flat one does: +`{allOf: [{type: integer, minimum: 0}, {format: unixtime}]}`, and `{$ref: U, minimum: 0}` where `U` +writes `{allOf: [{type: integer}, {format: unixtime}]}`, each keep the `minimum` as +`{type: integer, format: unixtime, minimum: 0}` does. A `Union` reads it per variant, each as it is +built, the branches a type beside the union conjoins with among them: beside +`{type: integer, oneOf: [{format: unixtime}, {format: int32}]}`, one variant of which is seconds, a +`minimum` is kept as beside the union of `{type: integer, format: unixtime}` and +`{type: integer, format: int32}`, and beside widths alone it is held. An `Enum`'s root is its `ValueType`, and a `Union` of +literals' each `Literal`'s, so what its members are, not the `format` beside them, decides: +`{type: string, format: date-time, enum: [abc], maxLength: 3}`, whose member is no instant, is an +`Enum` of `string` holding the length, a reference to it holds one beside it, and an enum an `allOf` +entry's `format` alone types as instants keeps one, as does a reference to it or a union branch +naming it, each read as the set's own node is. A value set beside a `$ref`, which keeps the `$ref` +verbatim, is bounded by what the `$ref` reaches too: its node, the `Enum` or the `Union` of literals, +and the members a union of value sets beside the rest admits, read the bounds of each schema a +`$ref` among the position's conjuncts lands on, and on along its chain of `$ref`s and the inline +entries of its `allOf`, as an inline entry's are read, so they intersect as the same bounds written +flat across `allOf` entries do. Of a kind the root holds, they reach its `Constraints`; one of text +of another kind is kept verbatim on it under `openapi:` (`no_ir_home`), with one info +`openapi/unhomed-construct` at the position, where one schema alone writes it and the position's own +schema and inline entries do not, and otherwise stays with the `$ref`, as one two entries write +keeps each entry whole. What the reading of such a schema reports is its own node's. The walk reads +at most 256 schemas; one past that stops it, with an info `openapi/degraded-construct` at the +position, as the reading of a refinement's conjuncts cut there is reported. The types a position +admits are those its node lowers from: the kinds its own `type` declares and the members of its +`enum` or `const` have, that every schema it names admits too: what its `$ref` lands on, the +keywords beside each `$ref` of the chain read with it, each `allOf` entry, a `oneOf` or `anyOf`, +which admits what any of its branches does, a branch of null alone, written with a `type` or not, +admitting none a bound applies to ([`union-null-variant`](#union-null-variant)), and the target a +`$dynamicRef` or `$recursiveRef` names ([`dynamic-ref`](#dynamic-ref)), read through as many of +those as the named schemas write, from the source and never from what has been lowered, once a +compile, so no answer turns on the order schemas are declared in or on how many the read takes in. +Where that leaves every kind, it admits the kinds the schema's shape keywords speak of under the +kind-inference policy, as it lowers to them ([`shape-applicator`](#shape-applicator)). A read +meeting a cycle of `$ref`s, `allOf` entries or dynamic references, or a `$ref` landing on no schema, +whichever schema of it is read first, leaves the position's own `type` to decide. A schema declaring +no `type` and naming none excludes nothing, so it reads every bound; one declaring `null` alone +reads none, its `Enum` with no member keeping them ([`null-alone`](#null-alone)), and so does one +whose own and named types share no kind. A bound no type the position admits takes reaches no +`Constraints`, the carrier's included, and is kept verbatim under `openapi:` +(`degraded_lowering`) with an info `openapi/degraded-construct` naming what the position lowered to: +on the node it owns, on an alias hoisted where it lowered to a shared node or a reference, or on the +carrier of a reference. A type array's variants each take their own type's, where the position +admits it ([`type-arrays`](#type-arrays)). Each named schema is read in its own document, an inline +one at its own pointer, so a dynamic reference names what it does where that schema is lowered. A +bound is read off the raw node, never the parser's `float64`, so its `BigVal` keeps every digit the +literal wrote ([`values`](#values)), a quoted one as the decimal it spells; one that is no decimal +literal a `BigVal` holds is dropped with an `openapi/invalid-numeric-literal` error at the keyword. +Exclusive bounds follow the schema's dialect ([`dialect-keywords`](#dialect-keywords)). In 3.0's, +and in JSON Schema draft 4's, the boolean modifies the bound beside it: `true` moves that bound to +`ExclusiveMin` or `ExclusiveMax` and clears `Min` or `Max`, so a 3.0 document and its 3.1 +translation lower alike, `false` states nothing, and `true` with no bound beside it bounds nothing +and is kept verbatim under `openapi:exclusiveMinimum` or `openapi:exclusiveMaximum` +(`degraded_lowering`) with an `openapi/degraded-construct` warning. In 2020-12's, the dialect 3.1 +and 3.2 name, the keyword is a bound of its own, kept beside `Min`/`Max` when both are declared, a +field apiece and no `Unmodeled` entry ([constraints](../ir/constraints.md)). The other dialect's +form (a boolean in 2020-12's, a number in 3.0's or draft 4's) is dropped with an +`openapi/invalid-exclusive-bound` error at the keyword. Both errors are the rule table's, made with +the rows of each schema's dialect, at every schema its [`validation`](#validation) check reads, +which judges these keywords as the lowering reads them rather than by their shape: one under `not`, +`if` or `propertyNames`, or beside an `enum`, is reported as one the lowering reads, and an aliased +value once. A bound beside a `oneOf` or an `anyOf` lowering to a `Union` of its entries +([`union`](#union)), or on an `allOf` entry folding there, is that `Union`'s: no variant can hold +it, each being its branch's node, which every use of the branch shares. A bound has one home: the +node its position owns, else the carrier, which holds one only where its position owns no node, over +a reference or a primitive every use shares, else a node hoisted there ([one +home](../ir/annotations.md#one-structural-home-per-declaration)). A property, a parameter or a +header whose position owns its node holds none of its bounds, which a `$ref` naming that position +reads on the node alone; one naming a position that owns none, a shared primitive's, reads a +`Scalar` hoisted there holding them, while the carrier keeps its own. The node's kind decides what +it holds, whatever the position admits: a `Model` or a `MapT` the property counts alone, as its +instances are objects, a `List` or a `Tuple` the collection bounds, and a `Union` those its variants +take, or its variants where the position builds them, a type list's ([`type-arrays`](#type-arrays)) +or a distributed union's, each those of the kinds it admits, its branch's within the rest's +([`union-beside-structure`](#union-beside-structure)), and an `Enum` those of the kinds of the +values it lists, closed or open, as does the `Union` of literals a mixed `enum` lowers to +([enums](../ir/enums.md#bounds)), its position's own beside an `allOf` and an inline entry's folding +there among them, since a closed enum's bound can refuse a member it lists. A bound its kind does +not take, and one beside a `Literal`, which holds none, is kept verbatim on the node under +`openapi:` (`degraded_lowering`), once, with an info `openapi/degraded-construct` naming +the node it lowered to, as [`shape-applicator`](#shape-applicator) keeps a collection bound on an +object ([unions](../ir/unions.md#bounds-beside-a-union)), and one an inline `allOf` entry writes +there is kept under its own key, reported at the entry +([`allof-inline-residue`](#allof-inline-residue)). A collection bound beside a reference that +`Constraints` cannot state, a count that does not fit in 64 bits, is kept the same way, while a +`uniqueItems` of `false` says nothing ([`null-keywords`](#null-keywords)). A count, `minLength`, +`maxLength`, `minItems`, `maxItems`, `minProperties` or `maxProperties`, is a non-negative integer +with no upper limit, and its field holds one up to 2^63−1: one past that, at any node, carrier or +`allOf` entry, reaches no field and is kept verbatim under `openapi:` (`degraded_lowering`) +with an info `openapi/degraded-construct` saying so where it is written, and on an entry it parts no +other ([`allof-inline-residue`](#allof-inline-residue)), but for one past what a `BigVal` holds, +which reaches the IR in no form ([`verbatim-preservation`](#verbatim-preservation)). Where several +writers of one position, its schema and the entries folding into it, give one such keyword, the one +binding the others is chosen, the smallest maximum or the largest minimum, compared exactly however +large, the first of one value written twice, with one report. Two declarations of one field are not +such writers: each keeps its own where it is written, and their fold compares the two entries as it +does any kept under `Unmodeled` ([`allof-redeclared-property`](#allof-redeclared-property)), so of +two such counts the later declaration's is kept and the other is reported and kept with its declaration. A count literal that is no non-negative integer is the rule table's to report ([`validation`](#validation)) and reaches no field, nor is it kept. A number carried as text holds -no bound ([`string-formats`](#string-formats)). +no bound ([`string-formats`](#string-formats)). A `$ref` landing on no schema with a bound beside +it, or as the one entry of an `allOf` with a bound beside the `allOf`, cuts nothing: the position +lowers as the same schema without the `$ref` does, its own `type` deciding the node that holds the +bound, and keeps the `$ref` verbatim ([`allof-refinement`](#allof-refinement)). -- Cases: `constraints`, `numeric-precision`, `ref-collection-bounds`, `reference-bounds` +- Cases: `constraints`, `numeric-precision`, `ref-collection-bounds`, `reference-bounds`, + `enum-bounds` - Codes: `openapi/invalid-numeric-literal`, `openapi/invalid-exclusive-bound`, - `openapi/degraded-construct` + `openapi/degraded-construct`, `openapi/unhomed-construct` - Tests: `schema.TestConstraints_ABoundIsReadWhereItsTypeTakesIt`, + `schema.TestBoundRoot_EverySpellingPlacesABoundAsTheFlatOneDoes`, + `schema.TestBoundRoot_ABoundBesideAUnionBindsEachVariantsRoot`, + `schema.TestBoundRoot_AReferencedSetReadsTheFormatItsConjunctsWrite`, + `schema.TestBoundRoot_AnEnumsRootIsItsValueType`, + `schema.TestBoundRoot_AReferencedValueSetIsReadByItsNodesType`, + `e2e.TestValueAdmission_AValueSetsTextBoundJudgesItsTextMembers`, + `schema.TestRefBounds_AValueSetHoldsTheBoundsItsRefsReach`, + `schema.TestRefBounds_ATextBoundReachesTheEnumWhereOneConjunctWritesIt`, + `schema.TestRefBounds_AWalkPastItsBoundIsReported`, `schema.TestConstraints_SeveralBoundsATypeCannotTakeDrawOneReport`, `schema.TestConstraints_APositionDeclaringNoTypeReadsEveryBound`, `schema.TestConstraints_APositionOfNullAloneReadsNoBound`, @@ -5847,13 +7014,13 @@ no bound ([`string-formats`](#string-formats)). `e2e.TestCompile_ABoundBesideAReferenceToAModelIsHeldOnce`, `e2e.TestCompile_ABoundOfAnotherKindIsKeptOnItsHomeAndBreaksNoInvariant`, `e2e.TestCorpus_NoCarrierRestatesABoundItsOwnNodeHolds`, - `schema.TestFoldedAllOfEntries_ABoundTheComposedModelCannotTakeKeepsItsEntry`, + `schema.TestFlattenedAllOfEntries_ABoundTheComposedModelCannotTakeKeepsItsEntry`, `schema.TestConstraints_ABoundBesideAValueSetOrAUnionHasOneHome`, `schema.TestConstraints_AReferenceLandingOnAPropertyReadsItsNode`, - `e2e.TestStringConstUnion_ABoundBesideTheSetKeepsTheUnion`, + `e2e.TestStringConstUnion_ABoundBesideTheSetFoldsIntoTheEnum`, `schema.TestConstraints_ACountATypeCannotTakeIsKeptUnread`, `schema.TestConstraints_AModifierATypeCannotTakeIsKeptUnread`, - `schema.TestKeywordKinds_ListsEveryValueBoundAndTheContentVocabulary`, + `schema.TestKeywordAppliesTo_ReadsEveryValueBoundAndTheContentVocabularyByItsKind`, `schema.TestBoundsFor_ReadsEachBoundForTheKindsItAppliesTo`, `schema.TestDeclaredInstanceTypes_ReadsTheTypesASchemaDeclares`, `e2e.TestDialectShapes_AreReportedWhereverTheCheckReadsASchema`, @@ -5881,14 +7048,11 @@ no bound ([`string-formats`](#string-formats)). `schema.TestCompareCounts_OrdersLiteralsExactly`, `annotation.TestExactCount_StatesOnlyAnExactCount`, `specrules.TestShape_Admits` -- Status: partly built: two declarations of one field that each keep a bound meet the fold of +- Status: partly built: two declarations of one field that each keep a bound go through the fold of [`allof-redeclared-property`](#allof-redeclared-property) (#1889). A bound left unread is reported at its position, with the other unread keywords, not at the keyword. A bound beside an enum a - promotion opens, which bounds the values it does not list, is kept verbatim as a closed one's is - (#2004). A `$ref` landing on no schema with a keyword beside it, or as the one entry of an `allOf` - with a keyword beside the `allOf`, makes the position a `Model` with no member, keeping the `$ref` - and each keyword a model has no home for, a `type` among them, rather than leaving the position's - own `type` to decide (#2091). + promotion opens, which bounds the values it does not list, is held in the `Enum`'s `Constraints` + as a closed one's is. ### `validation-only` @@ -5898,73 +7062,92 @@ position owns, one entry per family: `not`, `dependentSchemas`, `dependentRequir `propertyNames` each under `openapi:`, at the keyword; and three families each folded into one object, at the schema — `if`, `then` and `else` under `openapi:if-then-else`, `contains` with `minContains` and `maxContains` under `openapi:contains`, and `unevaluatedProperties` with -`unevaluatedItems` under `openapi:unevaluated`, every form of each but an `unevaluatedProperties: -false` the node the position lowered to holds as a model's closure -([`additional-properties`](#additional-properties)): a `Model` closed after composition, or a +`unevaluatedItems` under `openapi:unevaluated`, every form of each but one the node the position +lowered to types: an `unevaluatedProperties: false` it holds as a model's closure +([`additional-properties`](#additional-properties)), a `Model` closed after composition, or a `Union` whose variants the schema builds itself, a type list's or a distributed union's -([`union-beside-structure`](#union-beside-structure)), one of them such a `Model`. Anywhere else, +([`union-beside-structure`](#union-beside-structure)), one of them such a `Model`; an +`unevaluatedProperties` schema a `Model` holds as its catch-all; and an `unevaluatedItems` a `List` +or a `Tuple` holds as its elements past the prefix ([`tuples`](#tuples)). An unevaluated keyword is +typed only where every keyword its evaluation reaches that evaluates a location is one the IR +types: own `properties`, `patternProperties`, a catch-all, `items` and `prefixItems`, every schema +an `allOf` entry brings, inline or through a `$ref`, transitively, and a `oneOf` whose branches +require disjoint `const` or `enum` tags. One reaching an `if`, a `dependentSchemas`, a `contains`, +an `anyOf`, or a `oneOf` whose branches may overlap, a discriminator beside it or not, beside it or +in a schema a composition brings, is kept, closing no model, and that of a distributed union once, +on the `Union`. A dynamic reference it reaches is read through where it expands, as its `$ref` twin +is ([`dynamic-ref`](#dynamic-ref)), and one that does not, an `allOf` entry beside another conjunct +among them, is kept so too. An `unevaluatedProperties` schema is the catch-all only where nothing its +composition brings writes an `additionalProperties` or an `unevaluatedProperties`, nor, through a +`$ref`, a `patternProperties` or a closure after composition, each of which evaluates members the +catch-all would read beyond; an +inline entry's `patternProperties` are the model's own. An `unevaluatedItems` reached through an +`allOf` entry or a `$ref` is kept. Anywhere else, on a scalar, an enum, a list, a `$ref` site's alias or carrier, a plain union, a model a `false` `allOf` entry closed or the top type, that form is kept with the others, so a consumer finds the family under one key whatever the position lowered to. In JSON Schema these two keywords apply -only to what no keyword beside them evaluates (2020-12 §11.2, §11.3), so one is inert beside the +only to what no keyword beside them evaluates (2020-12 §11.2, §11.3), so one says nothing beside the keyword that evaluates every location it could apply to: an `additionalProperties` of any value beside `unevaluatedProperties`, and beside `unevaluatedItems` an `items` schema or, where the dialect reads a list of `items` as a tuple ([`tuples`](#tuples)), the `additionalItems` written -beside the list. An inert keyword is kept with that keyword, written just before it in the entry's -object: `{"additionalProperties": true, "unevaluatedProperties": false}`. The entry's keywords are -read as written in the schema at its position, beside the keywords the IR states there, as what an -unevaluated keyword applies to depends on what stands beside it; read so, the entry means what the -source means, nothing where the keyword is inert, and needs no marker or reason of another kind to -tell the two apart. Read as a schema of its own it means something else: +beside the list. A keyword that says nothing is kept with that keyword, written just before it in +the entry's object: `{"additionalProperties": true, "unevaluatedProperties": false}`. The entry's +keywords are read as written in the schema at its position, beside the keywords the IR states there, +as what an unevaluated keyword applies to depends on what is written beside it; read so, the entry +means what the source means, nothing where the keyword says nothing, and needs no marker or reason +of another kind to tell the two apart. Read as a schema of its own it means something else: `{"additionalProperties": false, "unevaluatedProperties": false}` alone refuses a property the position's `properties` declare, and a live `{"unevaluatedProperties": false}` alone refuses every -property. The keyword the entry repeats beside an inert one is context: the IR holds it already, -typed where the node has a home for it and kept verbatim where it has none +property. The keyword the entry repeats beside one that says nothing is context: the IR holds it +already, typed where the node has a home for it and kept verbatim where it has none ([`shape-applicator`](#shape-applicator)), and read where it was written it repeats a keyword -already there. -`prefixItems`, `contains`, `properties` and `patternProperties` evaluate only what they match and -leave the keyword live, and an entry holding only unevaluated keywords holds live ones. One an -`allOf` entry writes stays with the entry kept whole, whatever its form +already there. `prefixItems`, `contains`, `properties` and `patternProperties` evaluate only what +they match and leave the keyword live, and an entry holding only unevaluated keywords holds live +ones. One an `allOf` entry writes stays with the entry kept whole, whatever its form ([`allof-inline-residue`](#allof-inline-residue)), since at the position it would exempt what the -other conjuncts evaluate. -A keyword whose value is the empty collection JSON Schema equates with its absence states nothing, -and is read as the keyword left out, as [`null-keywords`](#null-keywords) reads a `null`: nothing -is typed, kept or reported for it, and the schema lowers as it does with the key removed. -`dependentSchemas`, `dependentRequired` and a draft's `dependencies` are read so when written as a -mapping with no entry, at every position, an inline `allOf` entry writing only one included, which -says nothing for the position and is no conjunct another entry's keyword disagrees with. Where -the dialect defines no `dependencies`, an empty one is an unknown keyword like any other +other conjuncts evaluate. A keyword whose value is the empty collection JSON Schema equates with its +absence states nothing, and is read as the keyword left out, as [`null-keywords`](#null-keywords) +reads a `null`: nothing is typed, kept or reported for it, and the schema lowers as it does with the +key removed. `dependentSchemas`, `dependentRequired` and a draft's `dependencies` are read so when +written as a mapping with no entry, at every position, an inline `allOf` entry writing only one +included, which says nothing for the position and is no conjunct another entry's keyword disagrees +with. Where the dialect defines no `dependencies`, an empty one is an unknown keyword like any other ([`unknown-keys`](#unknown-keys)), as `definitions` is, and kept whatever it holds. A keyword holding a schema, `not`, `if`, `then`, `else`, `propertyNames`, `contains` and the unevaluated keywords, states something when it holds `{}`, the schema every instance satisfies, and is kept. -Every dialect reads both keywords as 2020-12 does. In a schema read in JSON Schema draft -4, 6 or 7 ([`dialect-keywords`](#dialect-keywords)), `dependencies`, which 2019-09 split into +Every dialect reads both keywords as 2020-12 does. In a schema read in JSON Schema draft 4, 6 or 7 +([`dialect-keywords`](#dialect-keywords)), `dependencies`, which 2019-09 split into `dependentSchemas` and `dependentRequired`, is kept the same way under `openapi:dependencies`, and -elsewhere is an unknown keyword ([`unknown-keys`](#unknown-keys)). Each entry is reported as an -info `openapi/validation-only-keyword` at the schema that wrote it, an `openapi:unevaluated` one -holding an inert keyword naming it and the keyword that leaves it inert. A position a kept keyword's -`$ref` lands on is lowered all the same, recorded in `UnmodeledEntry.Targets`, and kept live across -post-settlement pruning ([`unreferenced-anonymous-types`](#unreferenced-anonymous-types)), and so is -each position a chain of them passes, an alias keeping what it writes beside its `$ref`: the -compiler reserves every position a reachable schema `$ref` lands on, hop by hop, starting from -positions visited or kept verbatim by lowering, without reserving targets reached only from -unreferenced `$defs` tables or unreferenced reusable components. +elsewhere is an unknown keyword ([`unknown-keys`](#unknown-keys)). Each entry is reported as an info +`openapi/validation-only-keyword` at the schema that wrote it, an `openapi:unevaluated` one holding +a keyword that says nothing, naming it and the keyword beside which it says nothing. A position a +kept keyword's `$ref` lands on is lowered all the same, recorded in `UnmodeledEntry.Targets`, and +kept live across post-settlement pruning +([`unreferenced-anonymous-types`](#unreferenced-anonymous-types)), and so is each position a chain +of them passes, an alias keeping what it writes beside its `$ref`: the compiler reserves every +position a reachable schema `$ref` lands on, hop by hop, starting from positions visited or kept +verbatim by lowering, without reserving targets reached only from unreferenced `$defs` tables or +unreferenced reusable components. A discriminator within a kept keyword has its values read in the +same way ([`discriminator`](#discriminator)). - Cases: `negation-not`, `dependent-required`, `schema-drafts`, `maps`, `tuples-prefixitems`, `unevaluated-at-every-outcome`, `kept-ref-landings` - Codes: `openapi/validation-only-keyword` -- Tests: `annotation.TestValidationOnlyAt_KeepsEveryKeywordItClaims`, +- Tests: `annotation.TestValidationOnlyAt_KeepsEveryKeywordOfTheFamily`, + `schema.TestUnevaluated_ACatchAllReadsTheMembersTheCompositionLeaves`, + `e2e.TestUnevaluated_AnUntypedEvaluatorKeepsTheKeyword`, + `e2e.TestUnevaluated_AKeywordSayingNothingOrComposedScopeIsKeptAsAtTheBase`, `e2e.TestOlderDrafts_DependenciesAreValidationOnly`, `e2e.TestEntryDialect_ADraftsDependenciesIsKeptAsFlat`, `schema.TestLower_ValidationOnlyKeywords`, `annotation.TestValidationOnlyAt_AnUnconvertibleKeywordIsReportedNotKept`, - `annotation.TestUnevaluatedRaw_KeepsAnInertKeywordBesideWhatLeavesItInert`, - `annotation.TestValidationOnlyAt_AnInertUnevaluatedKeywordNamesWhatLeavesItInert`, - `annotation.TestValidationOnlyAt_AttributesAnInertEntryByItsUnevaluatedKeyword`, + `annotation.TestUnevaluatedRaw_KeepsAKeywordSayingNothingBesideWhatLeavesItSo`, + `annotation.TestValidationOnlyAt_AnUnevaluatedKeywordSayingNothingNamesWhatLeavesItSo`, + `annotation.TestValidationOnlyAt_AttributesAnEntrySayingNothingByItsUnevaluatedKeyword`, `schema.TestClosureTyped_EveryOutcomeKeepsWhatItDoesNotType`, `schema.TestClosureTyped_ReadsAlikeInEitherEntryOrder`, - `schema.TestFoldedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry`, - `schema.TestUse_ADraftsTupleRestLeavesUnevaluatedItemsInert`, + `schema.TestFlattenedAllOfEntries_AnUnevaluatedKeywordStaysWithItsEntry`, + `schema.TestUse_ADraftsTupleRestLeavesUnevaluatedItemsSayingNothing`, `annotation.TestWritesEmptyDependencyMap_TellsAnEmptyMapFromAnEntry`, `statement.TestKey_DefinedTellsAKeywordTheRowsDefine`, `e2e.TestEmptyDependencyMap_IsTheKeywordLeftOut`, @@ -5990,7 +7173,7 @@ names, one of those declarations a `$dynamicAnchor`, and one a merge past are read as dynamic. What makes the expansion possible is that a document's set of `$dynamicAnchor` declarations is fixed before evaluation: a name declared exactly once, in the reference's own resource, is the only match any dynamic scope containing a match can -hold, so it *is* the outermost matching anchor whatever path evaluation took. The anchor may stand at +hold, so it *is* the outermost matching anchor whatever path evaluation took. The anchor may lie at any position a `$ref` can name: a component, a `$defs` entry, a property, an `items` schema, a response's inline schema, the component keyed `""`, or a draft's `definitions` entry, which the reference lands on as a `$ref` naming the anchor would, so the schema there is built and validated @@ -6019,9 +7202,19 @@ An expanded reference lowers to a `TypeRef` whose `Target` is the ID of the type names, the one a `$ref` to that position resolves to: a named source component's, or the type that position's pointer gives in its document's namespace ([identity](../ir/identity.md#across-documents)), built once, from the declaration there, whichever reference asks for it first. No node is minted or -copied per use, so which reference or declaration lowers first decides nothing. Its `Nullable` is -what the keywords beside the reference admit, as beside a `$ref`; what its target admits is not read -yet. +copied per use, so which reference or declaration lowers first decides nothing, and one at a +position no carrier holds, written alone or beside only keywords no node holds (`$anchor`, +`$comment`, `$defs`, `$dynamicAnchor`, a `nullable` in a 3.1 or 3.2 document, `definitions` under +draft-04, draft-06 or draft-07, `$recursiveAnchor` under 2019-09), is the type of the position it +names, as a `$ref` there would be, with no alias hoisted between, at `items`, `prefixItems`, +`additionalProperties`, a `oneOf` branch or a body. Its `Nullable` is what the keywords beside the +reference admit, as beside a `$ref`, so a `nullable` beside it stays on the reference, and what its +target admits is read through it as through that `$ref` ([`nullable`](#nullable)). A `$ref`, or a +`$dynamicRef` naming a JSON pointer, whose one other keyword is `definitions` under draft-04, +draft-06 or draft-07 or `$recursiveAnchor` under 2019-09 lowers to its target the same way at those +positions and at an `allOf` entry, and a component written so over an object is the `Model` whose +`Base` is its target that a component writing an annotation beside the `$ref` is, where it was a +`Scalar` with that `Base`: its own ID changes kind. A reference is irreducible — and is then kept verbatim under `openapi:$dynamicRef` or `openapi:$recursiveRef` (`degraded_lowering`) with an info `openapi/degraded-construct` at it naming @@ -6029,7 +7222,7 @@ which case it was — when a `$dynamicRef`'s name is declared more than once in target is back under the evaluation path's control), or is declared in another document alone; when a `$recursiveRef`'s value is not `#`, or another resource declaring `$recursiveAnchor: true` reaches its target's; when its value is not a string at all; when a -resource boundary stands between it and its anchor as above; when no schema could be built where it +resource boundary lies between it and its anchor as above; when no schema could be built where it names; when expanding it would close a cycle of aliases (a `$ref` cycle is refused outright for the same reason, and expansion must not mint one the refusal cannot see); or when it is co-declared with a `$ref`, a `oneOf`/`anyOf`, a shape of its own, or one of `items`/`prefixItems`/`required` — an @@ -6062,6 +7255,9 @@ written beside a reference that expands is read as one beside a `$ref` is - Codes: `openapi/dynamic-ref-expanded`, `openapi/degraded-construct`, `openapi/unresolved-ref`, `openapi/cyclic-ref` - Tests: `schema.TestDynamicRef_IrreducibleIsKeptAndSaysWhy`, + `e2e.TestKeywordScope_ALoneDynamicRefEntryExpandsInPlace`, + `e2e.TestKeywordScope_ARefNamingAnEntryReadsTheEntryAlone`, + `schema.TestDynamicRef_AnExpandedReferenceAloneHoistsNoAlias`, `schema.TestDynamicRef_NamingNoDynamicAnchorIsTheRefItSpells`, `schema.TestDynamicRef_AnAnchorOnlyAnotherDocumentDeclaresIsKept`, `reftable.TestBind_ReadsADynamicRefAsTheRefItSpellsUnlessItNamesADynamicAnchor`, @@ -6101,8 +7297,8 @@ written beside a reference that expands is read as one beside a `$ref` is `reftable.TestDynamicAnchor_CountsWhatADocumentDeclares`, `reftable.TestDynamicAnchor_SaysWhenTheCountProvesNothing`, `reftable.TestRecursiveAnchor_CountsWhatADocumentDeclares`, - `reftable.TestResource_NamesTheRootOfAPositionsResource` -- Status: partly built: an expanded reference reads no null from its target (#1967). + `reftable.TestResource_NamesTheRootOfAPositionsResource`, + `e2e.TestNullAnswer_AnExpandedDynamicRefReadsItsTargetsNull` ### `content-vocabulary` @@ -6118,11 +7314,36 @@ whose type is no `string`, such as a number's `Scalar` hoisted for its format, a verbatim under `no_ir_home`, each under `openapi:` and each reported as an info `openapi/degraded-construct` at it ([boundaries](../ir/boundaries.md#validation-only-constructs)). A `contentEncoding` on a string writing no format names what the string already is, the encoded -text, so its `Encoding` names no `WireType` ([encodings](../ir/constraints.md#encodings)). +text, so its `Encoding` names no `WireType` ([encodings](../ir/constraints.md#encodings)). The +vocabulary's keyword scope is any conjunct, so the `Scalar` an `allOf`'s conjunct builds reads it +off whichever conjunct writes it, `contentEncoding` alone and `contentMediaType` with the +`contentSchema` it qualifies, one group, as written flat ([`allof-refinement`](#allof-refinement)). +Beside a `$ref` to a scalar rooted at `string` or `bytes`, in either spelling, the three lower as a +format selecting no primitive does there ([`allof-refinement`](#allof-refinement)): the position is +a `Scalar` over the reference carrying the `Encoding`, keeping nothing. Over a chain carrying an +`Encoding` of another name the position is the use of the reference, keeping each keyword under +`degraded_lowering` with one info at the position, worded as for a kept `format`, as the node is a +`Scalar`. Beside a `$ref` to a scalar whose value is read from the text, an instant, a date, a time, +a duration, a `uuid`, a `uri` or a number written as its text, a `contentEncoding` of another name +makes the string that encoding's text, as written flat ([`string-formats`](#string-formats)): the +conjunct writing it is chosen, so the position is a `Scalar` over `string` under the encoding, and +the `$ref` is kept as a passed-over one is, under `openapi:$ref`, `degraded_lowering`, with one info +at the entry writing it, or at the position where it is written beside the keyword. Without a +`contentEncoding`, the flat spelling keeping the primitive, the vocabulary restricts such a +reference as it does a `string`'s. Beside a `$ref` the vocabulary is read as written flat wherever +it is written: `contentEncoding` on one conjunct and `contentMediaType` with `contentSchema` on +another, or on the target or a node on its chain, build one `Encoding`, the conjuncts' before the +chain's, and a chain's `Encoding` naming no encoding, a media type alone, is none of another name. +Kept beside a target carrying another encoding, an entry's keyword is reported as a kept `format` +is. - Cases: `content-vocabulary` - Codes: `openapi/degraded-construct` - Tests: `schema.TestContentVocabulary_LowersToEncoding`, + `e2e.TestKeywordScope_TheContentVocabularyBesideARefToAStringRestrictsIt`, + `e2e.TestContentEncoding_BesideAReferenceToATextReadScalarLowersAsItsFlatTwin`, + `schema.TestBesideRef_AContentEncodingBesideATextRootIsTheEncodedString`, + `schema.TestBesideRef_ContentIsReadAcrossConjunctsAndTheTargetChain`, `schema.TestContentVocabulary_KeptWhereNoEncodingHolds`, `schema.TestContentVocabulary_ANumberTakesNone`, `schema.TestLower_ATypeArraysContentIsTheStringVariants` @@ -6182,7 +7403,7 @@ too where it writes a `$schema` naming a dialect and no other such schema holds of them decides and no order of reading does; what it holds is read in its dialect from there, and no identifier in it declares anything ([`references`](#references)). -A keyword a schema writes meets one of four outcomes, each taken from the rows of the dialect the +A keyword a schema writes has one of four outcomes, each taken from the rows of the dialect the schema is read in, never from its version or its name alone: 1. The rows define it: it is read as its row says, and a value the row refuses is the rule table's @@ -6251,15 +7472,17 @@ keyword itself, there is no absent form, and the two values are compared alone. `$ref` and `$dynamicRef` in effect: each names components the absent form does not write, and differs from it by them, so one dropped is found as a value discarded. A keyword that stops being carried at any one position or in any one spelling fails there rather than waiting for a -reader to notice, and a finding that stands is listed in the package's `testdata/presence.txt` -with its reason, which names the open issue it stands under. The test asks this of the core cases, which the gate runs; `make cases` -asks it of every case, an entry written before the `$ref` and a second keyword written with the -first among them, and fails on what the records, `testdata/full` among them, do not explain. The guarantee is a floor rather than an inventory: -it compares one pair of values per keyword, so a lowering that carried one value and dropped -another would still pass. It compares compiled documents with each other and never with the value -written, so a value read wrongly in every spelling, a bound one wider than written, passes too. A dependency map with no entry is no value in that sense but the keyword -left out ([`validation-only`](#validation-only)). A keyword kept verbatim keeps its `$ref`s as written, and the positions -they land on are lowered ([`validation-only`](#validation-only)). +reader to notice, and a finding that remains is listed in the package's `testdata/presence.txt` +with its reason, which names the open issue it is filed under. The test asks this of the core cases, +which the gate runs; `make cases` asks it of every case, an entry written before the `$ref` and a +second keyword written with the first among them, and fails on what the records, `testdata/full` +among them, do not explain. The guarantee is a floor rather than an inventory: it compares one pair +of values per keyword, so a lowering that carried one value and dropped another would still pass. It +compares compiled documents with each other and never with the value written, so a value read +wrongly in every spelling, a bound one wider than written, passes too. A dependency map with no +entry is no value in that sense but the keyword left out ([`validation-only`](#validation-only)). A +keyword kept verbatim keeps its `$ref`s as written, and the positions they land on are lowered +([`validation-only`](#validation-only)). - Tests: `e2e.TestCases_CoverTheRuleTable`, `openapicases.TestCore_EveryKeywordIsCarriedEverywhere`, `schema.TestReserveNodesAtReferenceTargets_BuildsNothingTwice`, @@ -6321,16 +7544,16 @@ unusable, but dropping the entry would lose every operation it declares. An `operationId` lowers to `Operation.Name`, as its `Source` and neutral `Canonical` ([`naming`](#naming)), while the `OperationID` is derived from the operation's mount pointer ([identity](../ir/identity.md)) and never from the `operationId`, so a repeated or renamed id -moves no ID. An operation with none, or with `""`, claims no id and is named by a hint of its method +moves no ID. An operation with none, or with `""`, holds no id and is named by a hint of its method and the route's key in neutral words — the path template, a webhook's name, a callback's expression, -or an `additionalOperations` key standing as the method (`get_ping`, `post_new_pet`; +or an `additionalOperations` key used as the method (`get_ping`, `post_new_pet`; [http-binding](../ir/http-binding.md)). Uniqueness is judged once every operation has lowered, across paths, webhooks and callbacks alike, and by declaration, so a finding does not move -with the order the document is lowered in. A second declaration writing a claimed id is reported as -an `openapi/conflicting-operation-id` error at the pointer it is written at, naming the first -declaration, the declarations taken in pointer order; one declaration mounted more than once, by a -path item `$ref`, a YAML alias or a merge key, as an `openapi/duplicate-operation-id` warning at -each mount but the first, naming that mount. Every operation lowers whatever the verdict, repeated +with the order the document is lowered in. A second declaration writing an id already held is +reported as an `openapi/conflicting-operation-id` error at the pointer it is written at, naming the +first declaration, the declarations taken in pointer order; one declaration mounted more than once, +by a path item `$ref`, a YAML alias or a merge key, as an `openapi/duplicate-operation-id` warning +at each mount but the first, naming that mount. Every operation lowers whatever the answer, repeated names included; the rule table ([`validation`](#validation)) states this rule and leaves it to this one. @@ -6665,28 +7888,28 @@ is the media type that serializes the value: `HTTPParamBinding.ContentType` on a `Parameter.Encoding` is written only by [`http-date-inference`](#http-date-inference). Every other entry lowers nothing and is kept whole on the Document under `openapi:`, its own pointer behind a document's qualifier where it is not the source (`degraded_lowering`), once however many references -reach it: such an entry belongs to the declaration, which no node stands for, and a parameter or -header lowers once per reference. Each is reported in one `openapi/degraded-construct` warning at the -`content` map, beside the `openapi/validation` error ([`validation`](#validation)) such a map draws, -which names the lowest `annotation.MaxUnknownKeys` and counts the rest. The media type serializes -the value, so a parameter whose content entry is elected states no style: its binding's `Style` is -the one it writes, and empty where it writes none, where the `schema` spelling takes its -location's default. A `style`, `explode` or `allowReserved` written beside `content`, which OpenAPI -applies to a value serialized through its schema (3.0.4: "For simpler scenarios, a `schema` and -`style` can describe the structure and syntax of the parameter"), has no effect there: it lowers as -declared and is an `openapi/inapplicable-location-keyword` warning at the key, a header's `style` -and `explode` alike ([`header-style`](#header-style)), and `in: querystring`'s are +reach it: such an Unmodeled entry belongs to the declaration, which no node represents, and a +parameter or header lowers once per reference. Each is reported in one `openapi/degraded-construct` +warning at the `content` map, beside the `openapi/validation` error ([`validation`](#validation)) +such a map draws, which names the lowest `annotation.MaxUnknownKeys` and counts the rest. The media +type serializes the value, so a parameter whose content entry is chosen states no style: its +binding's `Style` is the one it writes, and empty where it writes none, where the `schema` spelling +takes its location's default. A `style`, `explode` or `allowReserved` written beside `content`, +which OpenAPI applies to a value serialized through its schema (3.0.4: "For simpler scenarios, a +`schema` and `style` can describe the structure and syntax of the parameter"), has no effect there: +it lowers as declared and is an `openapi/inapplicable-location-keyword` warning at the key, a +header's `style` and `explode` alike ([`header-style`](#header-style)), and `in: querystring`'s are [`querystring`](#querystring)'s alone, as 3.2 bars the three there. Where a location's own row also -holds, as for `allowReserved` at `in: path`, both are reported, each a different statement. -What else the elected entry writes is kept: its `example` and `examples` follow the parameter's or +holds, as for `allowReserved` at `in: path`, both are reported, each a different statement. What +else the chosen entry writes is kept: its `example` and `examples` follow the parameter's or header's own in `Examples`, and the rest goes verbatim under `openapi:content//`, the -key escaped as a pointer segment — its `x-*` extensions under `vendor_extension`; an undeclared -key under `out_of_scope`, with the `openapi/unknown-object-key` warning -[`unknown-keys`](#unknown-keys) gives it; and its `description` and the fields only a body Content -models, `itemSchema`, `itemEncoding`, `prefixEncoding` and `encoding`, under `no_ir_home`, each with -an info `openapi/degraded-construct` at it. A `content` map with no entry elects nothing: a `schema` -beside it stands, and the empty map is kept under `degraded_lowering` with an -`openapi/degraded-construct` warning. The converse, `schema` beside a non-empty `content`, is +key escaped as a pointer segment — its `x-*` extensions under `vendor_extension`; an undeclared key +under `out_of_scope`, with the `openapi/unknown-object-key` warning [`unknown-keys`](#unknown-keys) +gives it; and its `description` and the fields only a body Content models, `itemSchema`, +`itemEncoding`, `prefixEncoding` and `encoding`, under `no_ir_home`, each with an info +`openapi/degraded-construct` at it. A `content` map with no entry chooses nothing: a `schema` beside +it applies, and the empty map is kept under `degraded_lowering` with an `openapi/degraded-construct` +warning. The converse, `schema` beside a non-empty `content`, is [`competing-keywords`](#competing-keywords)'. - Cases: `param-content-fields`, `header-content-schema`, `content-several-entries` @@ -6734,7 +7957,7 @@ operation may lower it, an operation's own parameter may override it ([`paramete and it may be kept verbatim, as a component nothing references is ([`unreferenced-components`](#unreferenced-components)) and a path item mounting no operation keeps its parameters ([`parameters`](#parameters)). So the message states the reservation and stops: it -claims nothing of the definition's fate, nor that a later stage applies the rule. +says nothing of the definition's fate, nor that a later stage applies the rule. - Codes: `openapi/reserved-header-name` - Tests: `operation.TestParams_ReservedHeaderNamesAreReported`, @@ -6758,12 +7981,12 @@ operation bound by `POST`, `PUT`, `PATCH` or `DELETE`, the methods among OpenAPI RFC 9110 does not define as safe (§9.2.1), that states no idempotency of its own and binds exactly one such header takes an `Idempotency` of the `idempotency_token` kind whose `TokenParam` names that parameter ([operations](../ir/operations.md)), with no report, as the document leaves the field -silent. An operation a webhook or a callback declares takes its token too: the API sends that +unsaid. An operation a webhook or a callback declares takes its token too: the API sends that request, and the key tells its receiver a delivery it has seen. A safe method needs no key, and its binding already states what a token would, the plan reading the operation as safe off it, so the document has spoken: `GET`, `HEAD`, `OPTIONS`, `TRACE` and `QUERY` -take no token and draw no report. Two cases meet the trigger and decline it, each reported as an +take no token and draw no report. Two cases match the trigger and decline it, each reported as an info `openapi/undecided-idempotency` at the operation, saying why, the operation keeping the idempotency it states, which is none: a method only an `additionalOperations` entry declares, whose safety the compiler does not know, and two header parameters of that name, which can differ only in @@ -6816,7 +8039,7 @@ A parameter schema's `xml`, and its `readOnly` and `writeOnly`, are kept verbati `Unmodeled` (`no_ir_home`), reported as an info `openapi/degraded-construct` at the keyword, since `ir.Parameter` has no field for either. Everything a parameter's or a header's schema writes that the carrier keeps is keyed beneath the schema's scope, `openapi:schema/`, or -`openapi:content//schema/` for the schema of an elected content entry, and the object's own +`openapi:content//schema/` for the schema of a chosen content entry, and the object's own keys stay unscoped, so a parameter and its schema can each write one key and both are kept ([unmodeled](../ir/unmodeled.md#keys)). A model's property is its schema, and keeps its keys unscoped. An entry another entry of the carrier holds whole is kept once: an `xml` object kept whole @@ -6848,7 +8071,7 @@ did not expand ([`dynamic-ref`](#dynamic-ref)) and a keyword nothing reads ### `media-types` Every media type of a `content` map lowers to one `Content` apiece, in source order and with none -elected primary ([responses](../ir/responses.md)). `Content.MediaType` is the key as written +chosen primary ([responses](../ir/responses.md)). `Content.MediaType` is the key as written — case, parameters and wildcards kept, so `application/json` and `Application/JSON` are two Contents — and its `Type` is the media type's `schema`, hoisted at `/content//schema` with the key escaped as a pointer token, or the top type where it writes none. An entry written as a `$ref` @@ -7058,7 +8281,7 @@ marker, and wins over the media-type reading at its own Content. An element sett registry is whole, since a `$ref` can name a list nothing has built yet. Streaming Contents whose frames differ leave `Events` unset on a direction that still streams, every Content kept, reported as an info `openapi/degraded-construct` at the `requestBody` or `responses` pointer; Contents whose -frames are one element elect it, a list of a type agreeing with that type. Error responses and the +frames are one element choose it, a list of a type agreeing with that type. Error responses and the default set no `StreamDetail`, their Contents marked all the same: whether the default answers a success is the plan's to decide ([`response-conditions`](#response-conditions)). The policy is the Go option `Options.StreamingInference`: `Disabled` turns the media-type reading off, on the Contents @@ -7080,7 +8303,7 @@ text, or a value that is no text, states nothing and is reported at its key. `st with no default source, reads an expression of the request (`$request.body#/stream`, or the shorthand `$request.stream`, read as a pagination input's is) into `Condition`, the input asking for the stream when true, recorded in the operation's `Provenance.Inferred`: only where the input's -type stands for the boolean primitive, the operation streams a response, and a success response +type resolves to the boolean primitive, the operation streams a response, and a success response offers a Content that does not stream beside one that does. Any other key is reported at itself. - Cases: `streaming-media-30`, `streaming-media-31`, `stream-terminator` @@ -7186,11 +8409,11 @@ nothing is not written, and a holder whose parts say nothing gets no key. A body declares no part, so every form body stating a schema is settled, though the walk finds no part. A `multipart/form-data` or `application/x-www-form-urlencoded` body stating a schema that is no -file body, and whose type, read through its unions, stands for no model, no map, no object value and -not the top type, names no part to send, as an array of strings does, where an object `const` names -its parts by its members: it is reported as a warning -`openapi/partless-form-body` at the schema and lowers as declared. A union read past its bound is -not judged, and nor is a type reaching no node, which load reports. +file body, and whose type, read through its unions, resolves to no model, no map, no object value +and not the top type, names no part to send, as an array of strings does, where an object `const` +names its parts by its members: it is reported as a warning `openapi/partless-form-body` at the +schema and lowers as declared. A union read past its bound is not judged, and nor is a type reaching +no node, which load reports. `contentType` lowers to `ContentTypes`, split on `,` and trimmed with empty items dropped, and one naming no media type is an `openapi/validation` error ([`validation`](#validation)); and `headers` @@ -7325,7 +8548,7 @@ in any case. `operation.TestPartEncodings_AnEntryKeptAtSettlementThatCannotBeKeptKeepsItsRecords`, `operation.TestPartEncodings_AUnionPastItsBoundIsReported`, `operation.TestPartWalk_DecidesKeysOnlyWhereItReadsEveryDeclaration`, - `operation.TestPartWalk_ReadsARefChainToItsBound`, + `operation.TestPartWalk_ReadsARefChainToItsEnd`, `operation.TestDeclaredMulti_ReadsEveryDeclaration`, `operation.TestDefaultContentType_ReadsEachValueByItsRow`, `operation.TestDefaultContentType_ReadsUpToItsBound`, @@ -7386,7 +8609,7 @@ an `openapi/invalid-status-key` warning at the operation's entry for it. Two keys of one `responses` map resolving to one status range — `4XX` beside `4xx`, or a `200` a merge key introduces beside a second — reach the IR with one name and one condition, and an `ErrorCase` carries no ID, so nothing else tells them apart. Both are kept, since neither key is -wrong on its own and dropping one would pick a winner on nothing but declaration order, and they are +wrong on its own and dropping one would choose one on nothing but declaration order, and they are reported as one `openapi/duplicate-status-key` warning at the operation's `responses` map, naming every key that collided. @@ -7466,7 +8689,7 @@ lowers to ([`string-formats`](#string-formats)), with no `Encoding` on the heade of one declared by `content` is, and no encoding named along that chain, takes an `Encoding` named `http-date` ([encodings](../ir/constraints.md#encodings)) on the header itself. Such a name on such a type is the policy's trigger, an encoding the document writes being where it has spoken, and it -declines nothing that meets it. A header declared `format: http-date` or `unixtime` carries the +declines nothing that matches it. A header declared `format: http-date` or `unixtime` carries the encoding its format names on its type ([`string-formats`](#string-formats), [`numeric-formats`](#numeric-formats)), so the document has spoken for it. It is an override of that one use, so a component a `$ref` names keeps its own text wherever else it is used. An info @@ -7516,8 +8739,8 @@ is not also kept on the document ([`unreferenced-components`](#unreferenced-comp response declares under that name in any case; and a `body` reference to the body whole, or to the chain of members its pointer walks from the root of every content of that body, which every content must walk alike. A root or a member typed as an alias of a model, as a schema that is a - `$ref` alone lowers, is read as that model, through a chain of at most 64 aliases, as every step - reading the finished document reads one. + `$ref` alone lowers, is read as that model, through a chain of aliases of any length, as every + step reading the finished document reads one. 4. Its `server` registers as a server at the link's own pointer, and its extensions and undeclared keys stay on it. @@ -7649,11 +8872,11 @@ in the words the reference's own report would use, and lowers to a scheme minted document writing it, so one key in two documents is two schemes. Nothing else about the requirement changes: the option keeps its other schemes, its scopes and its place in the list, so an operation stating its own requirement does not read as inheriting, and an option whose -name reaches no mechanism does not vanish from the options beside it. The error stands however the -rest lowers, since the specification requires the name to correspond to a scheme and what it means -is missing ([`validation`](#validation)). A name stands whatever is beside it, whether or not it -reaches a mechanism, since an option demands every scheme it names: a value that reads as no list of -strings lists no scopes, a warning from the rule table for a `null` and an error for any other +name reaches no mechanism does not vanish from the options beside it. The error is reported however +the rest lowers, since the specification requires the name to correspond to a scheme and what it +means is missing ([`validation`](#validation)). A name holds whatever is beside it, whether or not +it reaches a mechanism, since an option demands every scheme it names: a value that reads as no list +of strings lists no scopes, a warning from the rule table for a `null` and an error for any other ([`requirement-scopes`](../parser-library.md#requirement-scopes)). A scope is the text an item writes, so a plain date is one ([`undecoded-scalar`](../parser-library.md#undecoded-scalar)). The scopes an option lists for one scheme are a set: a scope written again is kept once, at its first @@ -7798,7 +9021,9 @@ lowering order ([unmodeled](../ir/unmodeled.md#keys)): on the Document, `openapi item's `openapi:pathItem/x-*`, and `openapi:responses/x-*` and `openapi:externalDocs/x-*`; on the HTTP binding, `openapi:callbacks//x-*`; on a content, `openapi:encoding//x-*` and `openapi:itemEncoding/x-*`; on a schema's node, `openapi:xml/x-*`, `openapi:discriminator/x-*` and -`openapi:externalDocs/x-*`, a discriminator an `allOf` entry writes beside the union the position +`openapi:externalDocs/x-*`, a discriminator an `allOf` entry writes that the position's `Model` +holds keeping its own under `openapi:discriminator/x-*` as well ([`discriminator`](#discriminator)), +and one an `allOf` entry writes beside the union the position lowers keeping its own on the `Union` holding it, `openapi:allOf//discriminator/x-*` at the position and `openapi:discriminator/x-*` on one minted ([`union-beside-structure`](#union-beside-structure)); and on a security scheme, @@ -7817,7 +9042,8 @@ holding it. - Cases: `extensions-x`, `inline-annotations` - Codes: `openapi/degraded-construct` - Tests: `operation.TestOperation_UnserializableExtensionStillWarns`, - `operation.TestEncoding_PartNameWithSlashKeepsItsOwnKey` + `operation.TestEncoding_PartNameWithSlashKeepsItsOwnKey`, + `schema.TestAllOf_AnEntryIsKeptWithoutAnExtensionNoJSONHolds` - Status: partly built: an object kept verbatim also keeps its extensions under a scoped key (#849). ### `unknown-keys` @@ -7839,7 +9065,9 @@ of its own is keyed beneath the scope its extensions use (`openapi:info/`, any other, a value carrying a YAML anchor included. A schema keyword no field of the schema model names is kept the same way, reported as an info `openapi/unknown-schema-keyword`, because JSON Schema obliges an implementation to ignore a keyword it does not know, and a position that lowers to a shared node and carries no -property or parameter hoists an alias for it to land on; `$comment`, `$dynamicAnchor` and +property or parameter hoists an alias for it to land on, or over an object the `Model` composing +it, where that node would keep it, a value no JSON value holds being reported at the position; +`$comment`, `$dynamicAnchor` and `$dynamicRef`, and 2019-09's `$recursiveAnchor` and `$recursiveRef` where the schema's dialect defines them, are decided elsewhere and left out. A keyword the model names and the dialect the schema is read in does not define, which only `nullable` is, where the nullable-inference policy is @@ -7908,11 +9136,11 @@ how operations are arranged rather than filling a fact a node holds. document has spoken wherever it writes a keyword, or a key a promotion maps to the fact's target, whatever its value: a value filled, one that failed to resolve, and an explicit `false` each keep the inference from filling that fact. -4. **Reports.** An inference filling a field the document leaves silent reports nothing. One whose +4. **Reports.** An inference filling a field the document leaves unsaid reports nothing. One whose reading replaces what the document writes, as an HTTP-date replaces the RFC 3339 text a written `date-time` names, reports an info `openapi/inferred-`. One whose trigger, the evidence its - rule reads, is met where the document has not spoken, and which then declines to fill the fact, - reports an info `openapi/undecided-` saying why. +rule reads, is satisfied where the document has not spoken, and which then declines to fill the + fact, reports an info `openapi/undecided-` saying why. 5. **Placement and order.** A fact read once the document is whole is read in a package named for the fact or for the convention, which imports only `ir`, the compiler's `diag`, `ids` and `promotion`, and `compileddoc`, the one reading of the finished document every such step shares, @@ -7950,18 +9178,18 @@ promotion, as is a use its `$ref`'s target lends a field to, and the extension s untouched. A carrier also reads the objects whose keys it keeps beneath a scope: an operation its path item -(`openapi:pathItem/`), and a parameter or a header the content entry it elects (`content//`) and -the schema of its spelling (`schema/` or `content//schema/`). It reads them two ways, as +(`openapi:pathItem/`), and a parameter or a header the content entry it chooses (`content//`) +and the schema of its spelling (`schema/` or `content//schema/`). It reads them two ways, as [annotations](../ir/annotations.md#what-a-reference-carries-down) reads a `$ref` target. A single-sided fact, a redaction or a deprecation, holds where the carrier or any object it carries states it, so a carrier's `x-sensitive: false` withdraws nothing its schema states, as it withdraws nothing a `$ref` target states, and a deprecation's members fill from the nearest object stating them. A valued fact, an operation's tier, a parameter's `allowReserved` or its pagination mark, is -the nearest statement's, the carrier's own first. The entry keeps its own provenance, so a finding -about a carried key sits at that key, and the carrier keeping it is the node marked. A misfit behind -a nearer statement of its key, which no reading takes, is still reported once at its own key, for a -redaction, a deprecation and an operation's tier; a parameter's `allowReserved` and its pagination -mark report only the nearest. +the nearest statement's, the carrier's own first. The Unmodeled entry keeps its own provenance, so a +finding about a carried key sits at that key, and the carrier keeping it is the node marked. A +misfit behind a nearer statement of its key, which no reading takes, is still reported once at its +own key, for a redaction, a deprecation and an operation's tier; a parameter's `allowReserved` and +its pagination mark report only the nearest. A source of a target stating that something is so, a deprecation, an open enum or union, a redaction or a part of a page walk, may list the values that state it. Each is compared with a string's text, @@ -8017,20 +9245,21 @@ A property, header or parameter naming a `$ref` reads the target's mapped keys b field by field and without a report, and the target is the end of the chain, so a schema between the two lends nothing, as it lends no keyword. One holding a refinement ([`allof-refinement`](#allof-refinement)), or a `$ref` to one, reads along the chain its keywords -are read along, nearest first: any link stating a deprecation, by a keyword or a key, deprecates the -use, the nearest deprecated link lends its members, and any link asking for redaction asks it of the -use. A node a `$ref` still speaks on once a value set takes its type reads that `$ref`'s keys the -same way, as it reads its keyword. A key on the target stating a deprecation counts as the target's -`deprecated`, which no `deprecated: false` beside the `$ref` withdraws. A target lends a member only -where it is deprecated itself, by a keyword or a key: on a live target the member annotates -nothing, as it does anywhere, and a use deprecated on its own does not change that. So the target's -`Deprecation` is all a use reads of it, which is what the [fold](../emitters/refine/decorators.md) of -a 3.0 decorator over the same target reads, and what the target's key cannot hold is reported where -that key is written and read, once, with a use reading past it in silence. +are read along, nearest first: any node on it stating a deprecation, by a keyword or a key, +deprecates the use, the nearest deprecated node lends its members, and any node asking for redaction +asks it of the use. A node a `$ref` still speaks on once a value set takes its type reads that +`$ref`'s keys the same way, as it reads its keyword. A key on the target stating a deprecation +counts as the target's `deprecated`, which no `deprecated: false` beside the `$ref` withdraws. A +target lends a member only where it is deprecated itself, by a keyword or a key: on a live target +the member annotates nothing, as it does anywhere, and a use deprecated on its own does not change +that. So the target's `Deprecation` is all a use reads of it, which is what the +[fold](../emitters/refine/decorators.md) of a 3.0 decorator over the same target reads, and what the +target's key cannot hold is reported where that key is written and read, once, with a use reading +past it in silence. A value a member cannot hold, anything but text, is reported as an info `openapi/degraded-construct` at the extension and not coerced, since the document means something else by the key. Empty text -states nothing, and neither fills a member nor stands before a later source. Other text of the right +states nothing, and neither fills a member nor blocks a later source. Other text of the right JSON shape is taken as written: `x-sunset` fills `RemovalDate` and not `RemovalVersion` because the header it echoes ([RFC 8594](https://www.rfc-editor.org/rfc/rfc8594)) is a date by definition, and the mapping is where that reading is stated — the promotion does not then parse the date to confirm @@ -8170,9 +9399,9 @@ saying why. `e2e.TestPromotion_AUseReadsItsReferentsKeys`, `e2e.TestPromotion_ARefinementFallsBackToWhatItRefines`, `e2e.TestPromotion_ALostRefFallsBackToTheNodeItIsWrittenOn`, - `e2e.TestPromotion_ADecoratorMatchesTheRefItStandsFor`, + `e2e.TestPromotion_ADecoratorMatchesTheRefItWraps`, `e2e.TestPromotion_UsesHoldTheirOwnAnswerInEitherOrder`, - `e2e.TestPromotion_AContentCarrierReadsTheEntryItElects`, `promotion.TestCarried_ReturnsOwnWhereNothingIsCarried`, + `e2e.TestPromotion_AContentCarrierReadsTheEntryItChooses`, `promotion.TestCarried_ReturnsOwnWhereNothingIsCarried`, `promotion.TestCarried_TheOwnKeyBeatsTheScopedOne`, `promotion.TestWithOwnCarriedState_ASingleSidedFactHoldsWhereAnyStatesIt`, `e2e.TestCarriedKeys_AnOperationReadsItsPathItemsTier` @@ -8180,7 +9409,7 @@ saying why. object lands on the decorator the use lowers to, whose `Sensitive` keeps it a type of its own, where beside a `$ref` to a string it lands on the carrier (#2061); a schema a use names between it and the end of its chain lends no key, as it lends no keyword (#1029); and a key inside - a `oneOf` kept verbatim beside a body, as the base of a hierarchy keeps the union of its subtypes +a `oneOf` kept verbatim beside the rest, as the base of a hierarchy keeps the union of its subtypes ([`union-beside-structure`](#union-beside-structure)), reaches no field. ### `mutually-exclusive-parameters` @@ -8195,12 +9424,11 @@ name one parameter carries, among the operation's parameters, a path item's incl variants come out sorted by name, whatever order the document writes them in, and a variant's parameters in its list's order. The operation's `Params`, its bindings and every reference to a parameter are untouched, and no parameter or type is made. The first source whose key the operation -writes is read, whatever it holds; a later source's key writing the same value is silent, and one -writing another is reported and not read. The key stays -verbatim, `vendor_extension`, and the operation lists `extension-promotion` in its -`Provenance.Inferred` where a choice is filled. +writes is read, whatever it holds; a later source's key writing the same value reports nothing, and +one writing another is reported and not read. The key stays verbatim, `vendor_extension`, and the +operation lists `extension-promotion` in its `Provenance.Inferred` where a choice is filled. -Each choice is filled whole or not at all, and one written badly leaves the others standing. Each +Each choice is filled whole or not at all, and one written badly leaves the others in place. Each refusal is one info `openapi/unpromoted-extension`, at the most specific coordinate: | The document writes | Reported at | @@ -8338,7 +9566,7 @@ streams, or as a mark on the operation itself, is read by no source, so it speak `pagination.TestInferWalks_LeavesWhatAnExtensionSpeaksOf`, `pagination.TestPromote_FillsTheFlag`, `pagination.TestPromote_ReadsTheRootForTrue`, `pagination.TestPromote_TrueWithNoRootStatement`, `promotion.TestPageStatementOf_ReadsTheRootForTrue`, `pagination.TestPromote_TrueReadsThePathItemFirst`, - `pagination.TestPromote_ASilentOperationReadsNeitherItsPathItemNorTheRoot` + `pagination.TestPromote_AnOperationWritingNoKeyReadsNeitherItsPathItemNorTheRoot` ### `pagination-policy` @@ -8358,7 +9586,7 @@ every operation. A name is compared by its canonical words (`Naming.Canonical`), `offset`, under `offset`; `cursor`, under `cursor`; or `page_token`, `next_token` or `continuation_token`, under `token`. It is `InputCursor`, and a place named `per_page`, `page_size` or `limit` beside it is `InputLimit`. A place is a query parameter; a member of an - object query parameter, one bound in the query or as the query string whose type stands for a + object query parameter, one bound in the query or as the query string whose type resolves to a model, one level down, an `InputPath` naming the parameter and the member; or a member of the request body's root that every content holds, an `InputPath` naming the member alone. An object parameter is read through its members: where one of them names a continuation or the page size, @@ -8407,7 +9635,7 @@ every operation. A name is compared by its canonical words (`Naming.Canonical`), or of a model a member of it holds, of the cursor's own primitive, named as the cursor with `next` before it, or, where no member is so named, as the cursor itself, since a page naming both echoes the cursor it was sent beside the next, or, for a cursor that is no string, `next`. - A plain string `next` beside a string cursor may be the cursor or a link, so where it stands + A plain string `next` beside a string cursor may be the cursor or a link, so where it is alone the walk is undecided. Where the body names none, the next cursor is the response header every success response declares once whose canonical name, a leading `x_` aside, is the cursor's with `next` before it, or the cursor's own, a `NextCursor` whose `In` is `header`; a @@ -8436,7 +9664,7 @@ every operation. A name is compared by its canonical words (`Naming.Canonical`), `previous_link` typed as either, else the one named `prev` or `previous` typed as a `url`, in the body or in a model a member of it holds. Beside a walk an input continues they are facts of the page, which change neither its strategy nor what is reported; a link the contents hold at - different members, or none or several of, is left unset, and the walk stands. `FirstLink`, +different members, or none or several of, is left unset, and the walk is left as it is. `FirstLink`, `LastLink` and a flag for a link walk are not read. 7. **A link walk** is read where no place names a continuation, on a `GET` or a `QUERY`, and the response is the only evidence, so it must look like a page and nothing else: the root of each @@ -8493,7 +9721,7 @@ declaration both mounts share. `pagination.TestInferWalks_ReadsTheBodyMembersEveryContentHolds`, `pagination.TestInferWalks_SaysWhyAPostIsNoWalk`, `pagination.TestInferWalks_ReadsALinkWalkOnlyOffAPage`, `pagination.TestInferWalks_AllocatesLinearInTheBodiesItReads`, - `compileddoc.TestDocument_StandsReadsThroughAliasScalarsToTheCap`, + `compileddoc.TestDocument_ChainEndNodeReadsThroughAliasScalarsToTheEnd`, `compileddoc.TestDocument_ListsEveryOperationOnce`, `pagination.TestInference_TheZeroValueHonoursThePolicy`, `openapi.TestDecodeOptions_TextReachesEveryField` diff --git a/docs/compilers/planned-lowerings.md b/docs/compilers/planned-lowerings.md index 53a08c57a..db9c58e63 100644 --- a/docs/compilers/planned-lowerings.md +++ b/docs/compilers/planned-lowerings.md @@ -163,7 +163,7 @@ highlights, and the list moves to a specification of its own when the compiler l - scalar wire variants → Encoding under the IR's names ([encodings](../ir/constraints.md#encodings)): `sint32`/`sint64` → `zigzag`, `fixed32`/`fixed64`/`sfixed32`/`sfixed64` → `fixed` -- non-finite float defaults (`inf`, `-inf`, `nan`) → Value kinds `inf`, `neginf`, `nan` +- non-finite float defaults (`inf`, `-inf`, `nan`) → Value kinds `infinity`, `negative-infinity`, `nan` - `extend` fields → Property.ExtensionOf, extension ranges → Model.ExtensionRanges - well-known types → External (wrapper types → External or nullable primitive per injectable policy) - custom options → namespaced Unmodeled (proto-JSON), file options keyed by path in diff --git a/docs/emitters/README.md b/docs/emitters/README.md index d7014909f..7d3822bed 100644 --- a/docs/emitters/README.md +++ b/docs/emitters/README.md @@ -211,9 +211,9 @@ while reusing the same `plan` and refine step library. (INV2, INV9). 4. **Wire truth is a separate channel from identifiers.** Serialization always reads `WireName` / `WireID` / `WireNameByFormat`; it never reads a rendered identifier (INV4). -5. **Nothing heuristic is silent, nothing un-lowerable is silent.** Inferred outputs are marked - `Inferred`; un-lowerable constructs emit a coded `Diagnostic`, never a fabricated `any` and never - a panic (INV5, INV6). +5. **Nothing heuristic goes unmarked, nothing un-lowerable goes unreported.** Inferred outputs are + marked `Inferred`; un-lowerable constructs emit a coded `Diagnostic`, never a fabricated `any` + and never a panic (INV5, INV6). ## The first targets diff --git a/docs/emitters/contract/embedded-policy.md b/docs/emitters/contract/embedded-policy.md index 8ffa623c9..1bbf99629 100644 --- a/docs/emitters/contract/embedded-policy.md +++ b/docs/emitters/contract/embedded-policy.md @@ -64,42 +64,43 @@ Two keys of one node conflict only over a leaf both write: runtime policy's leaf writes](runtime-policy.md#what-a-layer-writes)), or a `ShapeHint` field, an `Extra` entry each. A key whose `Path` names a member above leaves writes those its value holds, so one mapped to `["retry"]` beside one mapped to `["retry", "maxAttempts"]` meet at `maxAttempts` alone. Of two -writing one leaf, a key with `Outer` unset beats one with it set, two whose values for the leaf are -equal set it together, to the value of the key whose spelling sorts first, and any other pair is a -warning `emitters/embed/conflict` that sets the leaf from neither, since which to take is no fact -the document states. Values are equal as the leaf reads them: a scalar by its decoded value, a -`Backoff` member by member, and a list as a set, so `[429, 503]` agrees with `[503, 429]`: nothing -reads the order of a list of either tree, the status lists, `Events`, `Keys`, `AgentEnv`, whose -products go out in their names' order ([runtime policy](runtime-policy.md#what-a-layer-writes)), -`ClientParams` and `AlsoMount`, or an entry's second writing. Two generators' keys for one fact -often sit on one operation, and need not agree: of the golden spec's 291 operations carrying both -`x-stability` and `x-fern-availability` (spec @bc6fad24, morphic @fa253fe19), 229 write one value -alike, 2 spell one tier two ways, `stable` and `generally-available`, 52 name two tiers and 8 set -`x-fern-availability` to `deprecated`, which names none. So agreeing keys are no conflict to report, -and disagreeing ones are what a valid document holds, each generator reading its own: the 52 are why -a conflict is a warning, which leaves the SDK's author to name one key or set the leaf in the -project's layer, where an error would fail every run over a document nothing is wrong with. Mapped -to one field of the IR's tiers none of the 291 would conflict: `generally-available` and -`deprecated` lie outside that vocabulary, draw `emitters/embed/invalid-value` and leave -`x-stability` to set the field. - -A key that sets nothing beats no other key: each of a conflicting pair, one whose value draws the -warning below, and one the reader refuses ([the mapping](#the-mapping-is-a-configuration)). So where -an operation's own keys conflict, its path item's key sets the leaf, and where its path item's -conflict, its own key does; where no key of the operation's entry sets it, the field takes the -layer's document-wide value, and without one the layers below. A contradiction in a configuration's -layer resolves alike: one naming a status in both retry lists for one scope gives way to the scope -below ([layers](runtime-policy.md#layers-and-operations)). Skipping the path item's key as well, -since each conflicting key overrides it, was rejected: the document-wide value is overridden just as -much, and a `policy.Layer` cannot say that an operation takes none of its own layer's document-wide -value, so the embedded layer would treat a contradiction as no other layer does. No reading gives -the value a generator reading only its own key would, which is why the conflict is reported. `Read` -returns the layer these rules give whatever severity a report carries, a refused key's error among -them: whether a run fails on one is the engine's verdict (architecture.md §4), and a run it lets -through, or a caller reading a failed run's result, gets this layer and no other. T-33 holds each -case. An operation's own key and its path item's both set the operation's entry, so a status one -names in a retry list and the other in the other list would be one scope's status named twice; it -stays only in the operation's list instead, as it would in a list set higher +writing one leaf, a key with `Outer` unset takes precedence over one with it set, two whose values +for the leaf are equal set it together, to the value of the key whose spelling sorts first, and any +other pair is a warning `emitters/embed/conflict` that sets the leaf from neither, since which to +take is no fact the document states. Values are equal as the leaf reads them: a scalar by its +decoded value, a `Backoff` member by member, and a list as a set, so `[429, 503]` agrees with +`[503, 429]`: nothing reads the order of a list of either tree, the status lists, `Events`, `Keys`, +`AgentEnv`, whose products go out in their names' order ([runtime +policy](runtime-policy.md#what-a-layer-writes)), `ClientParams` and `AlsoMount`, or an entry's +second writing. Two generators' keys for one fact often sit on one operation, and need not agree: of +the golden spec's 291 operations carrying both `x-stability` and `x-fern-availability` (spec +@bc6fad24, morphic @fa253fe19), 229 write one value alike, 2 spell one tier two ways, `stable` and +`generally-available`, 52 name two tiers and 8 set `x-fern-availability` to `deprecated`, which +names none. So agreeing keys are no conflict to report, and disagreeing ones are what a valid +document holds, each generator reading its own: the 52 are why a conflict is a warning, which leaves +the SDK's author to name one key or set the leaf in the project's layer, where an error would fail +every run over a document nothing is wrong with. Mapped to one field of the IR's tiers none of the +291 would conflict: `generally-available` and `deprecated` lie outside that vocabulary, draw +`emitters/embed/invalid-value` and leave `x-stability` to set the field. + +A key that sets nothing takes precedence over no other key: each of a conflicting pair, one whose +value draws the warning below, and one the reader refuses ([the +mapping](#the-mapping-is-a-configuration)). So where an operation's own keys conflict, its path +item's key sets the leaf, and where its path item's conflict, its own key does; where no key of the +operation's entry sets it, the field takes the layer's document-wide value, and without one the +layers below. A contradiction in a configuration's layer resolves alike: one naming a status in both +retry lists for one scope gives way to the scope below +([layers](runtime-policy.md#layers-and-operations)). Skipping the path item's key as well, since +each conflicting key overrides it, was rejected: the document-wide value is overridden just as much, +and a `policy.Layer` cannot say that an operation takes none of its own layer's document-wide value, +so the embedded layer would treat a contradiction as no other layer does. No reading gives the value +a generator reading only its own key would, which is why the conflict is reported. `Read` returns +the layer these rules give whatever severity a report carries, a refused key's error among them: +whether a run fails on one is the engine's verdict (architecture.md §4), and a run it lets through, +or a caller reading a failed run's result, gets this layer and no other. T-33 holds each case. An +operation's own key and its path item's both set the operation's entry, so a status one names in a +retry list and the other in the other list would be one scope's status named twice; it stays only in +the operation's list instead, as it would in a list set higher ([retries](runtime-policy.md#the-canonical-vocabulary)). The value is decoded into the field `Path` names, as the tree's own JSON form reads it, refusing an @@ -112,8 +113,8 @@ count of retries, and a timeout of `30` states no unit, which is why a duration ([what a layer writes](runtime-policy.md#what-a-layer-writes)). The entry stays in `Unmodeled` either way, as a promotion leaves it ([promotion](../../ir/unmodeled.md#promotion)), so a consumer that disagrees with the mapping reads the entry instead. A key whose value draws that warning sets -nothing, as a refused key does (below), so it neither beats another key nor conflicts with one -(above). +nothing, as a refused key does (below), so it neither takes precedence over another key nor +conflicts with one (above). ## The mapping is a configuration @@ -140,8 +141,9 @@ document holds a key the mapping names under one, the key reads nothing and is r The embedded layer sits below the project's and the one the project sets for an emitter, for policy ([layers](runtime-policy.md#layers-and-operations)) and for hints alike: what a document's author embeds is a default the SDK's author can override, and the override is reported as an info -diagnostic, so the document's author can see it was overruled. A declared IR fact still beats every -layer ([precedence](runtime-policy.md#precedence--declared-ir-facts-win-hard-rule)). +diagnostic, so the document's author can see it was overruled. A declared IR fact still takes +precedence over every layer +([precedence](runtime-policy.md#precedence--declared-ir-facts-win-hard-rule)). ## Measured on the golden spec diff --git a/docs/emitters/contract/emitter.md b/docs/emitters/contract/emitter.md index 4dee78ea2..cb9b020f5 100644 --- a/docs/emitters/contract/emitter.md +++ b/docs/emitters/contract/emitter.md @@ -136,8 +136,8 @@ type Artifact struct { // held inside it (../emit/rules.md) Content []byte Kind ArtifactKind // source | test | doc | manifest | dependency-manifest | scaffold - Header HeaderPlacement // where its generated-by line stands: "top", "after-shebang", or - // "none" for a file that can hold no comment (below) + Header HeaderPlacement // where its generated-by line is written: "top", "after-shebang" + // or "none" for a file that can hold no comment (below) SkipIfExists bool // scaffolding written once (config, .gitignore) — never overwritten Overwrite bool // regenerate but preserve ignore-regions (default is additive) Integrate *IntegrateHint // path-prefix stripping / tree-shake root for live-repo merge, and @@ -261,7 +261,7 @@ itself refuses is the target's error, passed on as it is, with no `Bound` and no directory of another under the fold, and no directory spelled two ways under it; none the manifest's own or under it; each segment one every file system writes, and a file's own name short enough for the writer. -- **The header.** The generated-by line stands where `Header` says +- **The header.** The generated-by line is written where `Header` says ([below](#the-generated-by-line)). - **Diagnostics.** Each code is in a namespace the target may report, each severity is one the IR declares, and each provenance names a source the document holds, or none. @@ -351,8 +351,8 @@ the document, which determines it. integrate](../write-integrate.md#what-the-manifest-records)). Maps are walked in sorted-key order, slices in source order ([T-6](../testing/mandatory-tests.md)). - **Diagnostics are the only input-failure channel.** A construct the emitter cannot lower emits - `ir.Diagnostic{Severity, Code:"emitters//…", Message, Provenance}` — never a silent - fallback, never a panic ([T-7](../testing/mandatory-tests.md)). Codes live in a stable + `ir.Diagnostic{Severity, Code:"emitters//…", Message, Provenance}` — never a fallback that + reports nothing, never a panic ([T-7](../testing/mandatory-tests.md)). Codes live in a stable `emitters//…` namespace ([above](#the-codes-a-target-reports)). - **Full document under scope.** Scope gates *emission*, not the plan or naming; global decisions are computed over the whole document so a scoped run is byte-identical to the corresponding slice diff --git a/docs/emitters/contract/options.md b/docs/emitters/contract/options.md index bfbb65875..073272c93 100644 --- a/docs/emitters/contract/options.md +++ b/docs/emitters/contract/options.md @@ -109,9 +109,10 @@ T-77 holds these rules. What an options version fixes is of three kinds, and `Defaults` holds only the first: -- **Settings**, and tables whose entries stand alone, are in `Defaults`. A naming table is one: an - acronym a configuration adds joins the built-in ones, and one it respells replaces that entry - ([naming](../refine/naming.md)). Merging key by key is the right rule for them. +- **Settings**, and tables whose entries are independent of one another, are in `Defaults`. A naming + table is one: an acronym a configuration adds joins the built-in ones, and one it respells + replaces that entry ([naming](../refine/naming.md)). Merging key by key is the right rule for + them. - **A table whose entries are replaced whole** is never in `Defaults`. Decoded over defaults, a user's type-table row stating a `Type` alone kept the built-in row's `Codec` and `Imports` (json/v2, Go 1.27.3), a type beside another type's import. So the configuration holds the user's diff --git a/docs/emitters/contract/registry.md b/docs/emitters/contract/registry.md index 7c4e4a593..5962da50c 100644 --- a/docs/emitters/contract/registry.md +++ b/docs/emitters/contract/registry.md @@ -32,8 +32,8 @@ emitter's: - a nil emitter, and a key already registered (plain errors); - a key that is not one or more segments joined by `/`, each of lowercase ASCII letters, digits and `-`, beginning with a letter or a digit, as `go`, `kotlin-jvm` and `mock/go` are. A key is - written into a diagnostic code, a manifest and a command line, so it holds what each takes as it - stands: a command line reads a word beginning with `-` as a flag (`morphic validate -go` is + written into a diagnostic code, a manifest and a command line, so it holds what each takes as + written: a command line reads a word beginning with `-` as a flag (`morphic validate -go` is refused as the unknown flag `-g`, morphic @cfb366317), and a segment that is empty cannot be told from a separator; - a key whose first segment names a kernel package (the last element of its path, [package @@ -131,7 +131,7 @@ implements already shows each, and a flag beside it could say otherwise: verification](../surface-verification.md)), each an optional interface that lands with M4. A target with none merges nothing and has no surface to compare. -Flags `CrossVersion`, `ReadsSamples`, `WriteIntegrate` and `SurfaceVerify` stood here before. Each +Flags `CrossVersion`, `ReadsSamples`, `WriteIntegrate` and `SurfaceVerify` were here before. Each restated what an interface shows, so the two could disagree. The registry refused `CrossVersion` set without `Router`, and a run refused `ReadsSamples` on a target whose options were no `SampleReader`, while a target that implemented either and left its flag unset ran as if it had diff --git a/docs/emitters/contract/runtime-policy.md b/docs/emitters/contract/runtime-policy.md index 0626a4bda..152065581 100644 --- a/docs/emitters/contract/runtime-policy.md +++ b/docs/emitters/contract/runtime-policy.md @@ -405,12 +405,13 @@ apply](#a-setting-that-cannot-apply)). caller writes. A read that gets no byte for `Idle`, or a write of which the transport takes none, fails with a timeout. The count starts again with each byte moved, not each frame, so a server's keep-alive, the comment line of an event stream among them, holds a quiet stream open and a peer - gone silent ends it. While its caller writes a stream `Request` does not run: it counts from the - stream's close to the response's headers. Each target times both itself and sets no timeout of its - HTTP library, whose own would end a stream with its request and whose messages quote the request - ([Go](../targets/go/operations.md#streaming), [Kotlin](../targets/kotlin/operations.md#timeouts)). - No document says how long its streams stay silent, so the default is a choice, and 60m is the - longest silence a configuration admits. + that has stopped sending ends it. While its caller writes a stream `Request` does not run: it + counts from the stream's close to the response's headers. Each target times both itself and sets + no timeout of its HTTP library, whose own would end a stream with its request and whose messages + quote the request ([Go](../targets/go/operations.md#streaming), + [Kotlin](../targets/kotlin/operations.md#timeouts)). No document says how long its streams may + send nothing, so the default is a choice, and 60m is the longest such stretch a configuration + admits. - `Pagination.MaxPages` is the pages one walk fetches. The fetch after the last is refused unsent and the walk fails naming the member; it never ends as a walk that reached the end does, since a caller told so would act on part of a collection as the whole. It bounds a server whose @@ -590,8 +591,9 @@ the project's, and the one the project sets for one emitter alone. A setting tak highest layer that sets it, for the operation or for the whole document, and within that layer the operation's value over the document's. So a project that turns retries off turns them off everywhere, whatever a document embeds for one operation, and a document's own per-operation setting -still beats its own document-wide one. Ordering by scope first would let a document's per-operation -settings outvote a project-wide choice, which then could not be made without naming every operation. +still takes precedence over its own document-wide one. Ordering by scope first would let a +document's per-operation settings outvote a project-wide choice, which then could not be made +without naming every operation. A key naming no operation of the document configures nothing, and is never ignored, since an operation whose ID changed would otherwise lose its settings in silence: the engine reports it @@ -637,12 +639,12 @@ catch, so a depth is honored there only where a stack was shown to take it. T-63 ## Precedence — declared IR facts win (hard rule) `ErrorCase.Retryable/Throttling/Fault` and `Operation.Idempotency` come from the spec; policy fills -in only where the spec is silent — never the reverse, and at every layer. The refiner enforces +in only where the spec says nothing — never the reverse, and at every layer. The refiner enforces this by reading the IR fact first and consulting policy only on `nil`, or for a `Fault`, on `""`. A -`policy-precedence` test asserts a spec `Retryable:false` beats a policy that lists that status as -retryable, at a document-wide setting and at an operation's ([T-9](../testing/mandatory-tests.md)). -When policy is overridden by a spec fact, an `Inferred`-marked diagnostic is emitted so nothing is -silent. +`policy-precedence` test asserts a spec `Retryable:false` takes precedence over a policy that lists +that status as retryable, at a document-wide setting and at an operation's +([T-9](../testing/mandatory-tests.md)). When policy is overridden by a spec fact, an +`Inferred`-marked diagnostic is emitted so nothing goes unreported. ## A setting that cannot apply diff --git a/docs/emitters/contract/type-table.md b/docs/emitters/contract/type-table.md index 5af1e2f0e..0aa4a42a0 100644 --- a/docs/emitters/contract/type-table.md +++ b/docs/emitters/contract/type-table.md @@ -136,8 +136,8 @@ refine layer](../refine/pipeline.md)), so a table is tested with no plan and no value is read, since an enum the target's constants cannot hold is declared over its members' wire forms ([enums](../refine/enums.md#a-member-on-the-wire)). A constraint on a mapped type is not checked by the SDK, which the server still checks, reported once per key as an info - `emitters//unchecked-constraint`. A row's codec goes with its type, so a declaration - standing over the type keeps it by naming that type again rather than defining a new one + `emitters//unchecked-constraint`. A row's codec goes with its type, so a declaration over + the type keeps it by naming that type again rather than defining a new one ([scalars](../refine/scalars.md)), and a type only a user's row names is taken to have methods and no constants. - **Imports and dependencies.** `ComputeImports` adds a row's `Imports` to every file that spells diff --git a/docs/emitters/docs-and-mock.md b/docs/emitters/docs-and-mock.md index 4ced9a523..db2b5c8c5 100644 --- a/docs/emitters/docs-and-mock.md +++ b/docs/emitters/docs-and-mock.md @@ -24,7 +24,7 @@ plan once: docs and mocks agree with the SDK by construction, not by re-derivati Its README is returned as blocks a user writes around ([write / integrate](write-integrate.md#a-document-the-user-writes-around)). No runtime `Policy` is consulted — proving the IR/policy split pays off. -- **Mock-server emitter (`emitters/mock`).** Reuses `PrimaryResponse`, the content `Return` elects +- **Mock-server emitter (`emitters/mock`).** Reuses `PrimaryResponse`, the content `Return` chooses and each response content's [example set](#one-set-of-examples) for canned responses, synthesizing none of its own, so with `Synthesize` off its streams and page walks hold only values the document declares, bar the links and totals a walk states of itself, sending the whole `Envelope.Body` @@ -63,7 +63,7 @@ The primary response and content are an SDK's ergonomic choice: a method returns the docs needs every answer the API gives, so the docs emitter renders every answer the plan lists, `Return`, `Others` and `Errors`, the last holding the service's `CommonErrors` too ([responses](plan/responses.md)), the `Default` once, with the statuses it answers, wherever the -plan places it, and every `Content` each declares, the primary response first and the elected +plan places it, and every `Content` each declares, the primary response first and the chosen content first within each, and those choices order the page and decide nothing else. A type is rendered once for each projection its `TypePlan.Shapes` gives it ([ModelShape](plan/types.md#modelshape--visibility-projection)), each table holding the members @@ -127,9 +127,9 @@ anchored in the first of the model's tables holding them. A value of the model i member the `Redacted` of any entry admitting it lists, an inclusive value being several of them at once ([a value several variants admit](refine/unions.md#a-value-several-variants-admit)), and whole where a variant such an entry's `Over` lists is sensitive, as a union's variant is. A model adding -nothing to its union, which the SDK targets alias, has no table: it is shown as the union it stands -for, linked, on its page or, where it has none, where it is referenced. One the plan composes no -entry for otherwise, which they degrade, lists its flattening's members and names its union, linked. +nothing to its union, which the SDK targets alias, has no table: it is shown as the union it names, +linked, on its page or, where it has none, where it is referenced. One the plan composes no entry +for otherwise, which they degrade, lists its flattening's members and names its union, linked. One table of the model's own members headed by its union, linked, would be shorter: 107 rows for the golden spec's 23 such models, where a table for each entry holds 1,671 in one shape (spec @bc6fad24, @@ -186,7 +186,7 @@ cannot add an item to the page's own list. No table tag is listed, since a brows table around a description's own in ways no stack of the description's can follow, so a description in a schema table's cell cannot add a cell or a row to it; a description's table renders as text. The contract is that outcome, which T-41 checks by parsing each page as a browser does: the page's -own elements stand as written around every description, however hostile, and every token the +own elements remain as written around every description, however hostile, and every token the description holds stays visible or renders as a listed element. An HTML parser's tree-building fragment mode is no substitute: it drops a stray end tag and turns `` into an element holding the rest of the text. Any other tag or comment renders as text, a custom element such as `` @@ -308,12 +308,12 @@ a way to show one entity across API versions. Each is decided by data, never by alike ([the path fold](emit/rules.md)), are an error `emitters/docs/route-collision` naming both, never a page that overwrites another and never a page dropped. The check runs on the URLs the templates produce, over every route a run plans, its table's and its agent documents' together, so - no template can reintroduce a collision the catalog did not have. A route whose page would stand - at a path of the manifest's own, `morphic.manifest.json`, `morphic.manifest.pending.json` or - `.morphic.manifest.pending.json.tmp` at the output root, or under one, compared by the fold, is the same error, naming the entity and the - manifest: a template routing a page there is the options' fault, which the check of a - generation's paths would otherwise report as a breach of the target's, after every target ran - ([emit rules](emit/rules.md)). + no template can reintroduce a collision the catalog did not have. A route whose page would sit at + a path of the manifest's own, `morphic.manifest.json`, `morphic.manifest.pending.json` or + `.morphic.manifest.pending.json.tmp` at the output root, or under one, compared by the fold, is + the same error, naming the entity and the manifest: a template routing a page there is the + options' fault, which the check of a generation's paths would otherwise report as a breach of the + target's, after every target ran ([emit rules](emit/rules.md)). - **Links are requests.** A renderer never formats a URL. It writes a link request, an entity's ID with the projection it wants (a page, an anchor, a model's table in one shape, the agent document of one target and language), and the route plan answers it. A spec's @@ -490,7 +490,7 @@ member, operation and message: - **Assembled for an operation.** An operation declaring no success scenario, one ending in no `Error`, takes one after those it declares, where every required input's set holds a value, built from the sets of its required parameters and of the optional ones whose set is declared rather - than synthesized, of its body, required or not, from the elected request content's, and of its + than synthesized, of its body, required or not, from the chosen request content's, and of its return content where it returns one: a call shows no optional filter the document gives no value for, and always the body it sends, which 231 of the golden spec's operations, sending an optional body with no example on it, would otherwise lack. Its `Input` is a `ScenarioInput`, the shape a @@ -604,12 +604,13 @@ the API rightly. `Accept` says, since that input is what the API reads. Otherwise it asks by `Accept`: each content of the primary response and of the response declaring `Recv`'s takes the `q` of the most specific range matching it, a media type before `text/*` before `*/*` (RFC 9110 §12.5.1), compared as [one - election](plan/responses.md#one-election) compares, one taking `q=0` is excluded, and the mock - answers with the content of highest `q`, a tie going to the content `Return` elects, else to the - first declared, and with the content `Return` elects where none is left or `Accept` is absent, + choice](plan/responses.md#one-choice) compares, one taking `q=0` is excluded, and the mock + answers with the content of highest `q`, a tie going to the content `Return` chooses, else to the + first declared, and with the content `Return` chooses where none is left or `Accept` is absent, each with the status and headers of the response declaring it. So the value method and the stream method of one operation ([streaming](operations/streaming.md)) each get what they read, and - answering every request with the content `Return` elects would give the stream method a JSON body. + answering every request with the content `Return` chooses would give the stream method a JSON + body. - **What the frames hold.** A side the mock writes sends, in order, its elements; one value of the first variant, in source order, whose `Variant.Event.Terminal` is true, where `Element` is a union with one and the last element holds none; its `Terminator` as one frame's data, where it is set; @@ -617,7 +618,7 @@ the API rightly. ([streams](plan/streams.md)). The elements are the content's declared examples, read through `ContentExamples`: each item of a list value is a frame where `Element` is the `ElementType` of the content's list `Type`, a string value on a side with no `Element` is the body's text and is - written as it stands, since the schema describes the whole body (OpenAPI 3.2 §4.14.3), closed by a + written as it is, since the schema describes the whole body (OpenAPI 3.2 §4.14.3), closed by a line feed under `json_lines` and a blank line under `sse` where it does not end with one, so a frame after it stays apart, and any other value `Element` admits is one frame. With none declared, a side has `MaxItems` frames, the k-th the k-th value of the set of `Element`, or of the content's @@ -693,10 +694,10 @@ the API rightly. either way. Both are [options of the mock](#the-mocks-options). On the golden spec (spec @bc6fad24, morphic @fa253fe19) 13 operations stream. 8 the client reads: 6 -offer `json_lines` text beside JSON, 2 of them declaring a three-line example, one elects it for its -one method beside CSV and Markdown no method asks for, and one offers `sse` frames of a model beside -JSON. 5 the client writes: one `json_lines` text and 4 `bytes` files. None is `bidi` or sets a -`Condition` or a `Terminator`, which no compiler fills yet (#1668). T-66 holds this section. +offer `json_lines` text beside JSON, 2 of them declaring a three-line example, one chooses it for +its one method beside CSV and Markdown no method asks for, and one offers `sse` frames of a model +beside JSON. 5 the client writes: one `json_lines` text and 4 `bytes` files. None is `bidi` or sets +a `Condition` or a `Terminator`, which no compiler fills yet (#1668). T-66 holds this section. ### A page walk on the mock diff --git a/docs/emitters/emit/rules.md b/docs/emitters/emit/rules.md index 65084f9ae..f3321aeaf 100644 --- a/docs/emitters/emit/rules.md +++ b/docs/emitters/emit/rules.md @@ -11,7 +11,7 @@ error wrapping `emitters.ErrContract` that names the target, the path and the ru contract](../contract/emitter.md#the-checked-calls)). It draws no diagnostic: a diagnostic is a finding about the user's document, which a threshold or a triage rule may accept, and no document causes two artifacts on one path. Codes `engine/duplicate-artifact-path`, -`engine/artifact-path-unportable` and `engine/artifact-outside-root` stood here before, and under +`engine/artifact-path-unportable` and `engine/artifact-outside-root` were here before, and under them a run at the `none` threshold, or one whose triage rule rated a code down, would have written the tree the rule exists to prevent. @@ -40,14 +40,14 @@ the tree the rule exists to prevent. same fold, or writes two that fold alike to one path ([collisions](../refine/naming.md#collisions-and-the-names-a-generation-shipped)), so two spec names that fold alike never reach it. -- **No path is a directory of another.** A file cannot stand where a directory must, so an +- **No path is a directory of another.** A file cannot sit where a directory must, so an artifact `a` beside one at `a/b` is a breach, and by the fold so is `Models` beside `models/x.go`, which a file system that ignores case makes the same pair. - **One spelling per directory.** Of the directories the paths pass through, any two that fold alike are spelled alike, so `Models/a.go` beside `models/b.go` is a breach, as it is beside `models/sub/b.go`. A file system that ignores case keeps both files under the spelling written first, where the manifest lists the other, and one that does not holds two directories no other - volume can. A directory standing on disk under another spelling is the writer's to judge, + volume can. A directory on disk under another spelling is the writer's to judge, where a held path passes through it ([write / integrate](../write-integrate.md#a-file-is-judged-by-its-digest)). - **No path is the manifest's own.** The engine keeps the generation's manifest at the output root, @@ -57,7 +57,7 @@ the tree the rule exists to prevent. of the three paths, or under one as a directory, compared by the fold, is a breach: the manifest's own writes would meet it, after the run's verdict. A manifest or pending manifest listing such a path is refused as it is decoded, by the same comparison. A listed path is held to no other - segment rule: a pending manifest lists what stood on disk under another spelling of a held path, + segment rule: a pending manifest lists what was on disk under another spelling of a held path, which may be longer than a segment the engine writes, and a manifest a build with newer Unicode tables wrote may list a character this build's tables leave unassigned, which `Portable` would refuse. No valid document leads a target there: a snapshot label takes a directory other than any diff --git a/docs/emitters/milestones.md b/docs/emitters/milestones.md index 8536a47da..b1cfcfadf 100644 --- a/docs/emitters/milestones.md +++ b/docs/emitters/milestones.md @@ -1,7 +1,7 @@ # Per-target milestone plan -Extends architecture.md §6 milestone 3 (the first emitters) and beyond. The code every target -stands on comes ahead of the first of them ([the foundation](#the-foundation)). +Extends architecture.md §6 milestone 3 (the first emitters) and beyond. The code every target builds +on comes ahead of the first of them ([the foundation](#the-foundation)). 1. **M3a — plan layer + the three first targets' skeletons.** `emitters/plan` with its language-independent golden corpus; `emitters/golang` and both Kotlin targets (`emitters/kotlin`) @@ -50,9 +50,9 @@ enumerations, a `TypeKind` among them. `go test ./cmd/morphic-census` holds the - **A listed fact degrades with a code.** Its dispatch reports a coded `emitters//unsupported-…` diagnostic and takes the nearest lowering it can (T-7), never a - silent fallback, so T-1's dispatch over every kind stays complete. Where an item of M3b or M3c - above names listed facts, such as external types, pagination or LRO, the item is that degrade - until a compiler produces them. + fallback that reports nothing, so T-1's dispatch over every kind stays complete. Where an item of + M3b or M3c above names listed facts, such as external types, pagination or LRO, the item is that + degrade until a compiler produces them. - **A fact enters when a compiler first produces it.** The change that makes a compiler produce one adds the conformance case that witnesses it, which takes its line out of the file in that change, and its lowering lands tested against that compiler's output. A fact only a non-default compiler diff --git a/docs/emitters/open-questions.md b/docs/emitters/open-questions.md index e0015185e..307c6b140 100644 --- a/docs/emitters/open-questions.md +++ b/docs/emitters/open-questions.md @@ -10,7 +10,7 @@ non-goal. The exact granularity is a per-feature judgment that will be litigated as features land. 3. **A target's own content preference.** The `json > form > multipart > binary` default is a shared plan helper (resolves [open question 3](../ir/open-questions.md)), and [one - election](plan/responses.md#one-election) settles how it breaks a tie, but a target that wants a + choice](plan/responses.md#one-choice) settles how it breaks a tie, but a target that wants a different primary needs a clean override path that does not fork the plan. Leaning: an override on `plan.Policy`, since the choice is document-neutral. 4. **Protocol-view neutrality.** The `BindingView` and target-AST `MethodKind` must be designed diff --git a/docs/emitters/operations/client.md b/docs/emitters/operations/client.md index b3d25b0a1..5999277b2 100644 --- a/docs/emitters/operations/client.md +++ b/docs/emitters/operations/client.md @@ -33,9 +33,10 @@ operation whose `Servers` names a server of its own. of its service's, by the same rules: to the first of them a client can reach, each variable at its `Default`. The caller's choice of server and of variable values is a choice among the service's servers, so it does not reach them; a base URL the caller gives replaces every server's URL, an - operation's own included, since a proxy or a test server stands in for the whole API. An operation - none of whose servers a client can reach refuses to be called unless a base URL replaces them, and - refine reports it once as an info `emitters//no-default-server`, naming the operation. + operation's own included, since a proxy or a test server takes the place of the whole API. An + operation none of whose servers a client can reach refuses to be called unless a base URL replaces + them, and refine reports it once as an info `emitters//no-default-server`, naming the + operation. - **Auth.** An HTTP target authenticates as [auth](auth.md) says, from the operation and the service. `Server.Auth` is the placement the messaging formats use, where a broker connection authenticates per server, and a messaging target reads it. diff --git a/docs/emitters/operations/errors.md b/docs/emitters/operations/errors.md index c84f2f07b..d011af57e 100644 --- a/docs/emitters/operations/errors.md +++ b/docs/emitters/operations/errors.md @@ -13,8 +13,8 @@ Retryable:&true, Throttling:&true }`; policy default maps `429 → "TooManyReque `OpPlan.Errors` = `[PlannedError{ Conditions:{429}, Response:{Shape:value, Content:application/json, Type:RateLimited, Headers:[Retry-After]}, Fault:"client", Retryable:true, Throttling:true }]` — -declared IR facts, carried as such, the content elected as a success's is ([one -election](../plan/responses.md#one-election)). +declared IR facts, carried as such, the content chosen as a success's is ([one +choice](../plan/responses.md#one-choice)). ## One value of the runtime @@ -23,7 +23,8 @@ spells it ([Go](../targets/go/errors.md#ratelimited-in-go), [Kotlin](../targets/kotlin/errors.md#how-a-failure-reaches-its-caller)), which the operation's response decoder fills from the entry a response takes. The retry wiring reads `Retryable`/`Throttling` **from the IR fact** and falls back to `Policy.Retry` only where the spec -is silent ([precedence](../contract/runtime-policy.md#precedence--declared-ir-facts-win-hard-rule)); +says nothing +([precedence](../contract/runtime-policy.md#precedence--declared-ir-facts-win-hard-rule)); throttling selects the throttling backoff, `Retry.Throttled`. The error types are runtime boilerplate ([structure and boilerplate](../emit/templates.md)): their kinds come from `Policy.Errors`, so a template renders them and no spec changes them. diff --git a/docs/emitters/operations/inbound.md b/docs/emitters/operations/inbound.md index 09d95fe09..39ab26b2b 100644 --- a/docs/emitters/operations/inbound.md +++ b/docs/emitters/operations/inbound.md @@ -60,29 +60,29 @@ A parse method reads one request as it arrived, in an order a signature needs: itself, comparing in constant time, where the credential sits in the request's text and the receiver was given its value: an `apiKey` with `In` `header`, `query` or `cookie`, after its `Scheme` where it states one, an `http_basic` and an `http_bearer` ([where a credential can be - read](auth.md#where-a-credential-can-be-read)). The caller's check stands in for exactly what the - receiver has no means to compare: any other scheme, one of those whose value the receiver was not - given, and an alternative naming no scheme, which an operation stating no alternative counts as - holding. The check is asked once for each scheme use it stands in for and once for each - alternative naming none, the alternatives read in order to the first satisfied and each one's - schemes to the first that is not, and is told all the IR states of that use: the operation, the - alternative's place in its `Auth`, the scheme and the scopes the use requires of it, or that the - alternative names none. The place is the document's order, which an alternative added before it - moves, so it tells two uses of a request apart and is no name to keep. The check is handed the - request: its method and target, the query in it, its headers, the body's bytes as they arrived, - and the certificates the connection presented where the caller's server exposes them, which a - `mutual_tls` or `x509` scheme is checked against. It is the place to verify a signature, for - which no format the IR is designed against defines a scheme; a caller verifying one beside a - scheme the receiver could compare gives the receiver no value for that scheme, and the check - answers for both. With no check configured, what it would stand in for is unsatisfied: comparing - a key the receiver was never given with an absent one would pass a request carrying none. An - alternative naming no scheme the IR reads as admitting a sender that authenticates nothing, but a - document has no scheme to state a signature with, so one stating none may still sign: the - receiver takes such an alternative as satisfied without the check only where it was built stating - that its operations admit an unauthenticated sender, and one built with no setting parses no - forged body. A request no alternative admits is a verification failure, a value apart from a - decode failure, so a handler answers it as such; it names the scheme or the user's check that - refused and holds nothing the request carried + read](auth.md#where-a-credential-can-be-read)). The caller's check takes the place of exactly + what the receiver has no means to compare: any other scheme, one of those whose value the + receiver was not given, and an alternative naming no scheme, which an operation stating no + alternative counts as holding. The check is asked once for each scheme use it takes the place of + and once for each alternative naming none, the alternatives read in order to the first satisfied + and each one's schemes to the first that is not, and is told all the IR states of that use: the + operation, the alternative's place in its `Auth`, the scheme and the scopes the use requires of + it, or that the alternative names none. The place is the document's order, which an alternative + added before it moves, so it tells two uses of a request apart and is no name to keep. The check + is handed the request: its method and target, the query in it, its headers, the body's bytes as + they arrived, and the certificates the connection presented where the caller's server exposes + them, which a `mutual_tls` or `x509` scheme is checked against. It is the place to verify a + signature, for which no format the IR is designed against defines a scheme; a caller verifying + one beside a scheme the receiver could compare gives the receiver no value for that scheme, and + the check answers for both. With no check configured, what it would take the place of is + unsatisfied: comparing a key the receiver was never given with an absent one would pass a request + carrying none. An alternative naming no scheme the IR reads as admitting a sender that + authenticates nothing, but a document has no scheme to state a signature with, so one stating + none may still sign: the receiver takes such an alternative as satisfied without the check only + where it was built stating that its operations admit an unauthenticated sender, and one built + with no setting parses no forged body. A request no alternative admits is a verification failure, + a value apart from a decode failure, so a handler answers it as such; it names the scheme or the + user's check that refused and holds nothing the request carried ([redaction](../refine/redaction.md#nothing-a-library-wrote-is-shown)). 4. **The parameters** the operation declares are read from their text as their locations' rules say, as the mock server reads a request's ([docs and mocks](../docs-and-mock.md)), a required one @@ -90,9 +90,9 @@ A parse method reads one request as it arrived, in an order a signature needs: pair of its location that its binding owns, in the order they came ([values as text](../refine/text.md#a-value-no-style-arranges)). 5. **The body** decodes through the content whose media type the request's `Content-Type` names - among those the operation declares, compared as [one election](../plan/responses.md#one-election) + among those the operation declares, compared as [one choice](../plan/responses.md#one-choice) compares media types, since the API chooses which it sends. One the operation does not declare is - refused, never decoded as the elected one. Unknown members, variants and enum values are read as + refused, never decoded as the chosen one. Unknown members, variants and enum values are read as a client reads a response's ([plan policy](../plan/policy.md)). What the request's sender controls is its body, its headers and its query. The body is held to the @@ -109,7 +109,7 @@ the document sets. T-71 holds this section. ## What the plan holds for one `OpPlan` keeps its fields' meanings. `Return`, `Others` and `Errors` each plan a response the -receiver may write, its content elected as for one a client reads, which is the content the response +receiver may write, its content chosen as for one a client reads, which is the content the response is written in, and `Errors` holds no `CommonErrors`, which are what the API answers its client. `RequestContent` is the content the mock server sends. `Auth` is the operation's own. `Effects` and the retry settings decide nothing, since nothing sends it again, so the operation's row of the @@ -125,8 +125,8 @@ request the API sends to a URL, so the receiver reads HTTP bindings alone. T-71 ## The mock server and the docs -The mock server stands in for the API, so it sends these requests rather than routing them. After -answering a request of the operation that declares a callback with a success, it resolves the +The mock server takes the place of the API, so it sends these requests rather than routing them. +After answering a request of the operation that declares a callback with a success, it resolves the callback's expression against that request and its answer, as OpenAPI defines runtime expressions, and sends the callback's request once to the URL it names, after the answer is written, its values the callback's first success scenario's `Input` ([one set of diff --git a/docs/emitters/operations/streaming.md b/docs/emitters/operations/streaming.md index ba6a9a37f..3bbf67b46 100644 --- a/docs/emitters/operations/streaming.md +++ b/docs/emitters/operations/streaming.md @@ -16,13 +16,13 @@ framing: the content's `MediaType` does. `OpPlan{ Return:{Shape:value, Content:application/json, Type:MetricsPage}, Stream:&StreamPlan{ Direction:server, Recv:&StreamSide{ Content:text/event-stream, Framing:sse, Element:Metrics } } -}`. The ranking elects JSON for `Return`, and `Recv` holds the stream beside it +}`. The ranking chooses JSON for `Return`, and `Recv` holds the stream beside it ([streams](../plan/streams.md)). ## What a target generates Each shape an operation offers is a method, sending the `Accept` of its content. An operation whose -elected content streams has the one method, under its own name. A frame that does not decode ends +chosen content streams has the one method, under its own name. A frame that does not decode ends the stream with an `OtherResponse` holding that frame ([a body that does not decode](../plan/responses.md#a-body-that-does-not-decode)). What a stream yields follows from `Recv`: diff --git a/docs/emitters/plan/operations.md b/docs/emitters/plan/operations.md index 180ce7b55..d947582f4 100644 --- a/docs/emitters/plan/operations.md +++ b/docs/emitters/plan/operations.md @@ -8,8 +8,8 @@ type OpPlan struct { PrimaryResponse *ir.Response // SDK-ergonomic pick; IR keeps ALL responses Return ResponsePlan // how the primary response is read Others []PlannedResponse // every other response the operation declares (responses.md) - RequestContent *ir.Content // the request content elected; nil = no body - RequestText map[string]TextPlan // by Content.MediaType as written, what of the elected + RequestContent *ir.Content // the request content chosen; nil = no body + RequestText map[string]TextPlan // by Content.MediaType as written, what of the chosen // content, and of every content of an operation the API // sends, holds a value no style arranges (responses.md); // a content holding none has no entry @@ -72,7 +72,7 @@ How `Return`, `Others` and `Errors` read a response is in [responses](responses. `StreamPlan` is in [streams](streams.md). An operation the API sends keeps each field's meaning, its responses written rather than read ([operations the API sends](../operations/inbound.md)). -`PrimaryResponse` and the contents a `ResponsePlan` elects are the *one legitimate home* for the +`PrimaryResponse` and the contents a `ResponsePlan` chooses are the *one legitimate home* for the collapse oagen performs destructively in its compiler and Morphic forbids there (INV2): the IR keeps every response and content type whole; "pick a primary for the ergonomic method" happens here, lowered late. The content ranking (`json > form > multipart > binary`) is a shared, overridable plan diff --git a/docs/emitters/plan/overview.md b/docs/emitters/plan/overview.md index 7bda1c0ae..36bb1159f 100644 --- a/docs/emitters/plan/overview.md +++ b/docs/emitters/plan/overview.md @@ -30,7 +30,7 @@ type Example struct { Example ir.Example // the example, as the IR spells one Inferred ir.Inferred // the steps that made it under Policy.Examples: // synthesized, assembled or filled by Shown; "" = - // declared as it stands + // declared as it is } // MaxExampleValues bounds the values one synthesized example holds; a larger one is reported diff --git a/docs/emitters/plan/plan-or-refine.md b/docs/emitters/plan/plan-or-refine.md index 60fc2101c..5786e2e5e 100644 --- a/docs/emitters/plan/plan-or-refine.md +++ b/docs/emitters/plan/plan-or-refine.md @@ -31,7 +31,7 @@ of the artifact that uses it — how an untagged union's variant is recognized o The procedure decided every existing field: 1. **Choices under `plan.Policy`** stay: `PrimaryResponse`, `RequestContent` and the content each - `ResponsePlan` elects, the unwrap behind `Return.Type`, `Open` on a union, on a model narrowing + `ResponsePlan` chooses, the unwrap behind `Return.Type`, `Open` on a union, on a model narrowing one and on an enum, `Strict`, `Effects`, which a binding sets where the IR states nothing, `Examples`, synthesized where none is declared, and `PagePlan`, an inferred one included. 2. **Derivations several artifacts expose** stay: `Return`, `Others`, `Errors`, `Auth`, `Bindings`, @@ -58,9 +58,9 @@ The procedure decided every existing field: client's servers are stated by the IR as well, so they get no field ([the client](../operations/client.md)). 4. **The parameter-passing shape** fails the first test and moved to refine ([request - shaping](../refine/requests.md)): a dynamic target's keyword arguments are additive as they - stand, where a positional parameter added to a Go or Kotlin function breaks its callers, so the - best default differs by language. + shaping](../refine/requests.md)): a dynamic target's keyword arguments are additive as they are, + where a positional parameter added to a Go or Kotlin function breaks its callers, so the best + default differs by language. 5. **What the derived-fact index states** gets no field either. How a type is used, whether it is recursive and which types share its strongly connected component are `irfacts.DocumentFacts` facts, read through `EmitterInput.Facts`, and a plan copy would be their second home, which is diff --git a/docs/emitters/plan/policy.md b/docs/emitters/plan/policy.md index 5ec6bc2e1..33c37eefb 100644 --- a/docs/emitters/plan/policy.md +++ b/docs/emitters/plan/policy.md @@ -26,7 +26,7 @@ type Policy struct { // what its binding's protocol defines (below) MergePatch bool // default on: a PATCH body sent as a merge patch relaxes // the members its schema requires, and is the content - // elected among those it ties with (below) + // chosen among those it ties with (below) Examples ExamplePolicy // default both on, depth 3, 2 items: what may be made where // no example is declared (../docs-and-mock.md) FirstPage *int // default 1: a page walk's first page where its page input @@ -191,8 +191,8 @@ Under `MergePatch` such a body's shape is a patch shape, every member optional, [precedence](../contract/runtime-policy.md#precedence--declared-ir-facts-win-hard-rule) has a declared fact win: `true` relaxes whatever the media type, unmarked, and `false` relaxes nothing. Turning the policy off leaves every body requiring what its schema requires. Where the operation -offers that content beside others its ranking ties it with, the policy elects it too, marked -`Inferred` ([one election](responses.md#one-election)), so the body an SDK sends is the one relaxed. +offers that content beside others its ranking ties it with, the policy chooses it too, marked +`Inferred` ([one choice](responses.md#one-choice)), so the body an SDK sends is the one relaxed. No other media type is read this way: a JSON Patch (`application/json-patch+json`) is a list of operations, and a `PATCH` sent as `application/json` says nothing about the members it leaves out. T-59 holds this section. @@ -315,7 +315,7 @@ Framings state what a media type means, not a guess about an API, so the table m media types OpenAPI 3.2 names: `text/event-stream` is `sse`; `application/jsonl` and `application/x-ndjson` are `json_lines`; `application/json-seq` and the `+json-seq` structured suffix, which `application/geo+json-seq` carries, are `json_seq`; and `multipart/mixed` is -`multipart`. An entry matches a media type compared as [one election](responses.md#one-election) +`multipart`. An entry matches a media type compared as [one choice](responses.md#one-choice) says, and one starting with `+` every media type with that suffix, as the compiler's streaming policy reads one ([`streaming-media`](../../compilers/openapi.md#streaming-media)), an entry naming the whole media type winning over a suffix. A configuration adds one for a media type its compiler diff --git a/docs/emitters/plan/responses.md b/docs/emitters/plan/responses.md index 162df945f..585460e85 100644 --- a/docs/emitters/plan/responses.md +++ b/docs/emitters/plan/responses.md @@ -5,10 +5,10 @@ declares, read by one `ResponsePlan`. ```go // ResponsePlan is how one response reaches its reader. A success and a failure are read by the -// same rules, so the election, the shapes, the codec and the headers have one home. +// same rules, so the choice, the shapes, the codec and the headers have one home. type ResponsePlan struct { Shape BodyShape // value | void | raw | stream - Content *ir.Content // the content elected from the payload; nil = nothing to read + Content *ir.Content // the content chosen from the payload; nil = nothing to read Type *ir.TypeRef // what a value body gives its reader, of any kind; nil unless // Shape is value Envelope *EnvelopeRead // how an enveloped body is read; nil = the body decodes into @@ -32,7 +32,7 @@ type TextPlan struct { // EnvelopeRead is a body one of plan.Policy.Envelopes matched (policy.md), as it is read here. type EnvelopeRead struct { Name string // the Envelope that matched - Body ir.TypeRef // what the body decodes into: the elected content's type + Body ir.TypeRef // what the body decodes into: the chosen content's type Value *ir.PropertyPath // where Type sits inside Body; nil = Type is Body, read whole Flag *ir.PropertyPath // the member saying whether the call succeeded; nil = none Succeeds []ir.Value // the Flag values meaning it succeeded @@ -59,10 +59,10 @@ type PlannedError struct { } ``` -## One election +## One choice A payload may offer several contents, and `plan.Policy.ContentRanking` ([plan policy](policy.md)) -elects the one a `ResponsePlan` or a `StreamSide` reads and the one `RequestContent` sends. A +chooses the one a `ResponsePlan` or a `StreamSide` reads and the one `RequestContent` sends. A success, a failure, a request and each side of a stream share that helper, so two targets cannot read one 429 as different media types, or send one request as them. An entry is one of four classes — `json` is `application/json` and any `+json` suffix, `form` is @@ -95,7 +95,7 @@ in a second channel. The first rule that applies decides: carry one: a target lowering such a binding reads every response as `void` ([bindings](bindings.md)). An operation with no primary response returns only an error, and "Which entry answers" below says which statuses raise one. -2. **`raw`** — the elected content is a file (`Content.File`, [payloads](../../ir/payloads.md)): the +2. **`raw`** — the chosen content is a file (`Content.File`, [payloads](../../ir/payloads.md)): the body reaches the caller unread, a byte stream beside the media type it arrived as, and nothing decodes it. So does a form or multipart content one of whose fields or parts no style arranges ([values as text](../refine/text.md#a-value-no-style-arranges)), `Text.Content` set: no @@ -103,16 +103,16 @@ in a second channel. The first rule that applies decides: shaping](../refine/requests.md#the-body)), and a part carries bytes and a content type that pairs of strings cannot. The golden spec's 5 multipart response contents, each a map of `bytes` or of a list of them, hold none (spec @bc6fad24, morphic @fa253fe19). -3. **`stream`** — the elected content streams ([streams](streams.md)): frames are read one at a +3. **`stream`** — the chosen content streams ([streams](streams.md)): frames are read one at a time, as `Stream` describes ([streaming](../operations/streaming.md)). -4. **`value`** — otherwise: the elected content's codec decodes the body, and its reader gets +4. **`value`** — otherwise: the chosen content's codec decodes the body, and its reader gets `Type`, whatever its kind — a model, a list, a map, a union, an enum, a scalar, `any`. A paginated operation's `Return.Type` is one page, from which `Page` takes the items. A `text/plain` content whose type is no leaf has no text to decode, so its `Type` is `string`, the body as it arrived, and `Text.Content` is set ([values as text](../refine/text.md#a-value-no-style-arranges)). -`Type` is the elected content's type, lowered through `TypePlan.Alias` as any reference is ([the +`Type` is the chosen content's type, lowered through `TypePlan.Alias` as any reference is ([the plan](overview.md), [decorators](../refine/decorators.md)), so an anonymous `allOf` decorator around a model returns the model. Its `Nullable` is the content's, and a nullable return takes the target's nullable form ([optionality](../refine/models.md#optionality--nullability--presence-inv8)). diff --git a/docs/emitters/plan/streams.md b/docs/emitters/plan/streams.md index e38a75f0d..382ee0de2 100644 --- a/docs/emitters/plan/streams.md +++ b/docs/emitters/plan/streams.md @@ -8,7 +8,7 @@ type StreamPlan struct { } type StreamSide struct { // one direction: its StreamDetail and streaming content - Content *ir.Content // the content that streams, elected as a body's is; nil = none + Content *ir.Content // the content that streams, chosen as a body's is; nil = none Framing Framing // how the wire divides into frames Element *ir.TypeRef // what a frame decodes into, any kind; nil = none is decoded FrameMembers bool // an SSE element's data, event, id, retry are frame fields @@ -27,10 +27,10 @@ type Framing string // "sse" | "json_lines" | "json_seq" | "mu operation may offer `application/json` beside `application/x-ndjson`. A content *streams* where its `Content.Stream` is set ([payloads](../../ir/payloads.md#a-content-that-streams)), as one declaring an `Item` is. The plan reads no media type for it, so a compiler's streaming policy, which a caller -can turn off, is the one reading of a media type as a stream. `Send` elects among the request's +can turn off, is the one reading of a media type as a stream. `Send` chooses among the request's contents that stream, and `Recv` among those of the operation's responses, a primary `Default` included. A content whose `Stream` is nil is one document, so a direction with a `StreamDetail` and -no content that streams elects none, and its `Content` is nil, as for an RPC whose input folds into +no content that streams chooses none, and its `Content` is nil, as for an RPC whose input folds into its parameters. Where `Recv` holds another content than `Return`, or `Send` another than `RequestContent`, the operation offers both, and a target generates a method for each ([streaming](../operations/streaming.md)). `Direction` is `Operation.Streaming`, a primary `Default` diff --git a/docs/emitters/plan/types.md b/docs/emitters/plan/types.md index 83c0add1a..eea27d762 100644 --- a/docs/emitters/plan/types.md +++ b/docs/emitters/plan/types.md @@ -63,18 +63,21 @@ type UnionShape string // "one_of" | "any_of" | "discriminated" | " type ScalarChain struct { // a Scalar's Base chain walked to its root (../refine/scalars.md) Root ir.TypeID // the chain's first node that is not a Scalar: a primitive, or - // what an alias stands over (docs/ir/scalars.md); "" = opaque + // what an alias names (docs/ir/scalars.md); "" = opaque Constraints *ir.Constraints // merged along the chain, decimal throughout (../refine/constraints.md) Encoding *ir.Encoding // the encoding declared nearest this scalar; nil = the root's } -type DiscrimFacts struct { // Mapping/Default resolved to TypeIDs, never names (INV3) +type DiscrimFacts struct { // routes resolved to TypeIDs, never names (INV3) Locator DiscrimLocator // property | property_name | index WireKey string // wire name of the tag property ("" when Locator == index) TupleElementIndex *int // positional tag element (Erlang tagged tuples); nil otherwise - Mapping map[string]ir.TypeID // wire tag value → variant ID: every route, those a union's nil - // Mapping leaves to its variants' type names written out + Mapping map[string]ir.TypeID // wire tag value → variant ID: every route an encoder may + // write, those a union's nil Mapping leaves to its variants' + // type names written out // (../refine/unions.md#the-tag-a-variants-value-carries) + DecodeOnlyRoutes map[string]ir.TypeID // wire tag value → variant ID: each route a decoder reads + // after Mapping and an encoder never writes; nil = none Default ir.TypeID // variant for absent/unrecognized tag; "" = none Envelope string // "" = inline tag | "object" = {kind,value} wrapper EnvelopeValueName string // wire name of the envelope value property (Envelope=="object") @@ -82,6 +85,13 @@ type DiscrimFacts struct { // Mapping/Default resolved to TypeID type DiscrimLocator string // "property" | "property_name" | "index" ``` +`DiscrimFacts` carries both route maps as the IR's `Discriminator` holds them +([discriminator](../../ir/models.md#discriminator)). A decoder routes by `Mapping`, then +`DecodeOnlyRoutes`, then recognition, then `Default`. An encoder picks the tag from the `Mapping` of +the discriminator it writes for. `DiscriminatorValue` routes nothing. It names the key that a +discriminator on one of the subtype's ancestors routes it by, so it is what an encoder writes only +through that discriminator. + Note what `TypePlan` does *not* do: it does not choose Go's sealed interface vs a native union, does not case anything, does not resolve reserved words, and does not copy a fact the IR states outright ([plan or refine](plan-or-refine.md)). `Flattened` is the *computed* flattening; the IR keeps @@ -112,7 +122,7 @@ with the rest of the composition beside it ([the shapes of a model narrowing a union](../../ir/models.md#the-shapes-of-a-model-narrowing-a-union)). The union is read through alias scalars, so where `Unflattened` names an alias, as a 3.1 `$ref` beside a `description` hoists one ([composition entries](../../ir/models.md#composition-entries)), the model narrows the union the -alias stands for, as the bare `$ref` does. `Composed` holds an entry for each shape +alias names, as the bare `$ref` does. `Composed` holds an entry for each shape `ir.NarrowedShapes` lists, in its order: its `Over`, and the `Flattened`, `Required`, `Undeclared`, `Redacted`, `Deprecated` and `Unflattened` read off its flattening as `TypePlan`'s own are read off the model's, never off a walk of the plan's own. So the variant's members are laid out, overridden, @@ -156,7 +166,7 @@ member the entry leaves optional proves nothing, since a value may omit it, nor can leave out, a declaration of it carrying a `Visibility`. The answer is the entry's in every shape, a patch shape among them: what a patch relaxes describes a change to an instance, and an entry with no instance has none to change. Two declarations on one side prove nothing either. A -model redeclaring its own member is read as the flattening takes it wherever it stands, a variant of +model redeclaring its own member is read as the flattening takes it wherever it is, a variant of a union among them, so an error body composing a success shape and then a failure schema, which pins `success` both ways, stays a variant of the union listing it and of a model narrowing that union. So neither side reads a declaration its flattening overrides: under `SelfBody: {allOf: [Env, @@ -202,7 +212,7 @@ it, which the example set holds ([one set of examples](../docs-and-mock.md#one-s Two of them reading the shapes apart would show members another lacks, which is the third test of [plan or refine](plan-or-refine.md), and the example set is the plan's, which imports only `ir`, `ir/irfacts` and `emitters/options` ([packages](../packages.md)), so no refine helper can serve it. -A target with intersection types writes the composition as it stands and need not read `Composed`, +A target with intersection types writes the composition as it is and need not read `Composed`, as a class-based one need not read `Flattened`. On the golden spec (spec @bc6fad24, morphic @ea70eba79), 23 models narrow a union beside a member of their own, in 158 entries: `rulesets_ResponseRule` over the 21 variants of `rulesets_RequestRule`, and @@ -222,7 +232,7 @@ admitting no value in common, by these rules, and a pair none of them separates model or a map, array for a list, a tuple or a `Positional` model, its members' wire forms' for a closed enum ([enums](../refine/enums.md#a-member-on-the-wire)), its values' for a literal, its `ValueType`'s and its members' wire forms' for an open enum, its variants' for a union, its base's - for a model that only stands over one, and every kind for the `Any` type, the `any` primitive, + for a model that only names one, and every kind for the `Any` type, the `any` primitive, which `{}` compiles to, and an `External`, whose wire form is its library type's. Each other primitive's is boolean for `bool`, a number for a numeric kind and a string for the rest. A scalar's are those of the `WireType` its encoding names (`ScalarChain.Encoding`), the type its @@ -353,8 +363,8 @@ than the request: `false` relaxes nothing, whatever the media type. The shape belongs to the content, so an operation offering one type as `application/json` and as a merge patch declares it in two shapes. It sends the -merge patch: under `MergePatch`, a `PATCH` binding leaving the field nil elects a merge-patch -content over the others its ranking places with it ([one election](responses.md#one-election)), so +merge patch: under `MergePatch`, a `PATCH` binding leaving the field nil chooses a merge-patch +content over the others its ranking places with it ([one choice](responses.md#one-choice)), so the request an SDK builds is the one the relaxation was read from. A mock reads a body by the content it arrives as, and accepts either. @@ -382,7 +392,7 @@ refuses. The two merge patches requiring a member reuse the resource's schema, a Worker's, whose operation says omitted properties are left unchanged; keeping what they require would make every edit of a Worker restate six members. Each of the six merge patches sits beside an `application/json` content declaring the same members, two more of the 78 among them, which the -smaller key would elect: without the election above no request would go out relaxed, and an edit of +smaller key would choose: without the choice above no request would go out relaxed, and an edit of a Worker would still restate its six. Four readings lost to this one: - **Every `PATCH` body relaxes.** It drops the required members of the 78, and over all a patch @@ -393,7 +403,7 @@ a Worker would still restate its six. Four readings lost to this one: - **Relax where a schema is shared with another body or a response.** Whether a schema is shared changes as operations are added, so an operation added elsewhere would relax a declaration its callers already build. -- **Relax the `application/json` content beside a merge patch, and keep electing it.** That media +- **Relax the `application/json` content beside a merge patch, and keep choosing it.** That media type says nothing of the members a body leaves out, and which content is the merge patch's twin is a second guess: three of the six pairs are two inline schemas, alike only member by member. @@ -505,7 +515,7 @@ same members, or two aliases. Five other ways of naming lost: request type its callers build, and the prior manifest cannot keep the name, the shape having had no entry of its own. - **A declaration of its own for every shape, coinciding or not.** No name or type would ever move, - for a Swift caller either, at the price of a second declaration wherever an alias now stands and + for a Swift caller either, at the price of a second declaration wherever an alias now sits and of a conversion before a value read can be sent back. - **The lifecycles of the shapes that share it**, the first in sorted order or all of them. Which shapes a document exercises changes with its operations: a model only a `PUT` writes is diff --git a/docs/emitters/refine/constraints.md b/docs/emitters/refine/constraints.md index 7ef79f916..b65bf868c 100644 --- a/docs/emitters/refine/constraints.md +++ b/docs/emitters/refine/constraints.md @@ -6,7 +6,11 @@ kind each applies to whichever variant holds it ([unions](../../ir/unions.md#bou A value is held to the bounds of its carrier and of every node along the reference the carrier names, each written once: a carrier holds a bound only where its use owns no node, so a field over a model or a map finds its counts on that node -([annotations](../../ir/annotations.md#one-structural-home-per-declaration)). It *builds the +([annotations](../../ir/annotations.md#one-structural-home-per-declaration)). A model's counts are +the intersection of those of every model its composition brings, `ir.PropertyCountBounds`, which +`TypePlan` reads ([the flattening](../../ir/models.md#the-flattening)): a model's own `Constraints` +hold only what its schema writes, so a check reading them alone misses a mixin's bound. An enum's bounds are +its `Constraints` ([enums](../../ir/enums.md#bounds)). It *builds the structure* of a per-type `Validate()` method — which checks apply to which fields — as typed AST. That method is the one validator: no field carries validation metadata, a `validate:"…"` struct tag or a registration, since nothing generated reads one and a reflection validator following it is a diff --git a/docs/emitters/refine/decorators.md b/docs/emitters/refine/decorators.md index 9b217edf6..9dadfd8d8 100644 --- a/docs/emitters/refine/decorators.md +++ b/docs/emitters/refine/decorators.md @@ -8,8 +8,8 @@ the position is a use of `Status` as the 3.1 spelling is ([models](../../ir/models.md#an-allof-no-object-satisfies)). 3.1's spelling of the same use, `{$ref: Status, description: …}`, is the same conjunction and lowers as that `allOf` does ([`ref-use-site`](../../compilers/openapi.md#ref-use-site)), to the same `Model` at a property or -parameter too; where no `Model` stands it hoists an anonymous `Scalar` alias over `Status` wherever -no property or parameter holds the annotations +parameter too; where there is no `Model` it hoists an anonymous `Scalar` alias over `Status` +wherever no property or parameter holds the annotations ([annotations](../../ir/annotations.md#one-structural-home-per-declaration)), and so does an annotation alone on a non-carrier position, `items: {type: string, example: x}`. None of these nodes says anything about a value that its `Base` does not. Lowered as written, each would be a type of @@ -36,15 +36,15 @@ decorator it passed collapses nowhere, and each of its nodes lowers as it would alias, once that pass exists, is followed the same way. **What refine does.** `CollapseAliases` runs before every other step. An aliased type emits no -declaration, and each reference to it — a `TypeRef`, a `TypeID` a discriminator's mapping or default -names, an `UnmodeledEntry.Targets` entry, or the type a +declaration, and each reference to it — a `TypeRef`, a `TypeID` a discriminator's mapping, decode-only +routes or default names, an `UnmodeledEntry.Targets` entry, or the type a [`DocRef`](../../ir/annotations.md#references-in-prose) marks — is lowered as a reference to its `Alias`, keeping the referring reference's `Nullable`, which answers for the whole decorator ([type-graph](../../ir/type-graph.md#type-references)). The decorators' annotations fold onto the carrier holding the reference — a property, a parameter, a header or a union variant, each of which -has a field for all three — so the reference documents its input exactly as the 3.1 `$ref` it stands -for does: +has a field for all three — so the reference documents its input exactly as the 3.1 `$ref` it takes +the place of does: - **`Docs` and `Deprecation`**, each field from the first that sets it, a `Description` and its `Refs` counting as one since each span indexes its own description diff --git a/docs/emitters/refine/enums.md b/docs/emitters/refine/enums.md index 44f4f7785..b01134109 100644 --- a/docs/emitters/refine/enums.md +++ b/docs/emitters/refine/enums.md @@ -50,6 +50,16 @@ anonymous enums of `null` alone, each reached only through nullable references, `result` among them ([enum-const](../../compilers/openapi.md#enum-const); spec @86556f6f), and none named. T-36 holds the rule. +## A member the enum's bounds refuse + +An enum's `Constraints` ([enums](../../ir/enums.md#bounds)) can refuse a member it lists, as +`maxLength: 3` refuses `abcd` of `{type: string, enum: [a, abcd], maxLength: 3}`. The IR keeps the +member as written, since `Enum.Constraints` homes the bound, and `pass` reports each such member with +a warning, `pass/enum-member-outside-bounds`. A refiner drops it from the generated type: no valid +instance equals it, so a generated SDK must not offer it. Where every member is refused, the +compiler reports `openapi/unsatisfiable-schema` instead and keeps the members, and the refiner drops +them all: the enum admits nothing, as an [enum with no members](#an-enum-with-no-members) does. + ## A member on the wire A member's wire form is its `WireName` where it has one, else its `Value` as the JSON kind its diff --git a/docs/emitters/refine/models.md b/docs/emitters/refine/models.md index b05a565a3..9d5b94baa 100644 --- a/docs/emitters/refine/models.md +++ b/docs/emitters/refine/models.md @@ -30,7 +30,7 @@ target's forms are its own ([Go](../targets/go/models.md#optionality), `ClientOptional` relaxes the client-side type even when `Required=true`; `DefaultAdded` may be suppressed for back-compat. Where a target's representation would force a *deliberate* collapse of -two states, a `Diagnostic` is emitted — never a silent conflation +two states, a `Diagnostic` is emitted — never a conflation that reports nothing ([T-3](../testing/mandatory-tests.md)). A nullable reference whose `TypeRef.Inferred` names a heuristic renders as nullable like any @@ -69,8 +69,8 @@ base a sealed interface of its subtypes, which Go holds in a struct ([Go unions](../targets/go/unions.md)). A union in `TypePlan.Unflattened`, an entry along the model's composition, or one an alias scalar -there stands for ([TypePlan](../plan/types.md#a-model-narrowing-a-union)), has no members to flatten -in: each instance of the model is an instance of one of the union's variants, with the rest of the +there names ([TypePlan](../plan/types.md#a-model-narrowing-a-union)), has no members to flatten in: +each instance of the model is an instance of one of the union's variants, with the rest of the composition beside it ([models](../../ir/models.md#a-union-a-composition-names)). So each of the three targets lowers the model as the union it narrows, distributing the composition over the union's variants as [models](../../ir/models.md#composition-beside-a-union) distributes a union @@ -81,8 +81,8 @@ variants narrows a union in turn ([TypePlan](../plan/types.md#a-model-narrowing- the union lists as a variant, as `Shape: {oneOf: [Circle, Square]}` lists `Circle: {allOf: [Shape, …]}`, narrows nothing: each of its instances is that variant, so the union adds no member to it and it lowers as a model, one the union's sum holds. A target with intersection -types may write the composition as it stands instead and need not read `Composed`; the plan computes -the entries because the docs and the example set read the same shapes ([plan or +types may write the composition as it is instead and need not read `Composed`; the plan computes the +entries because the docs and the example set read the same shapes ([plan or refine](../plan/plan-or-refine.md)). `LowerModels` declares the variants before the steps projecting shapes and lowering unions and discriminators reach them ([steps](steps.md)). diff --git a/docs/emitters/refine/naming.md b/docs/emitters/refine/naming.md index 4f0f3901e..a56f3d2e1 100644 --- a/docs/emitters/refine/naming.md +++ b/docs/emitters/refine/naming.md @@ -49,7 +49,7 @@ type Role struct { LeadingWord string // the word before an identifier that would begin with what Start // refuses (below) Start StartRule // NoDigitOrMark | UpperCaseLetterOnly - Unwritable RuneSet // what an identifier of the role cannot hold as it stands (below) + Unwritable RuneSet // what an identifier of the role cannot hold as it is (below) WrittenByName bool // write each such character by its name; else keep it, for the // target to quote PathCap Cap // the bytes of UTF-8 a name written into a path may take; the zero @@ -65,7 +65,7 @@ type Rendered struct { // Compose renders words under a convention, after prefix where it is not "": an owner's // identifier the role composes the name after, as Go's enum constant begins with its enum's name. -// When prefix is non-empty, it stands in the first position, so every word of words takes Rest and +// When prefix is non-empty, it takes the first position, so every word of words takes Rest and // the boundary between prefix and the first word follows the same join and break rules. func Compose(prefix string, words []Word, convention Convention, tables Tables) (string, error) @@ -108,7 +108,7 @@ func Resolve(scope Scope, tables CaseTables, members []Member) (symbols map[stri two targets differ by what they hand the package and never by a function it calls back. A naming function frozen in the shared layer, which no target could swap, is the failure the evidence records ([reference learnings](../../reference-learnings.md)), and a `Policy` interface each - target implemented, which stood here before, left the rules two targets must agree on to code + target implemented, which was here before, left the rules two targets must agree on to code each wrote. - **Nothing is accepted in silence.** `Compose`, `Render`, `PathName` and the scope constructors return an error for a value outside their vocabulary — a convention that leaves a break between @@ -374,8 +374,8 @@ $ dollar ? question_mark . period , The word grammar keeps a combining mark in the word of the letter it follows, and takes every letter and decimal digit Go's Unicode tables hold ([the word grammar](../../ir/naming.md#the-word-grammar)), and no first target can write each of them in an -identifier as it stands. Measured over every one past ASCII, the 145,620 letters, 2,543 marks and -760 digits of Unicode 17.0.0: +identifier as it is. Measured over every one past ASCII, the 145,620 letters, 2,543 marks and 760 +digits of Unicode 17.0.0: - **Go** 1.27.3 takes every letter, and every decimal digit after the first character, and no mark: `go/token.IsIdentifier` refuses each of the 2,543 marks, and a field `Café` spelled with U+0301 @@ -403,13 +403,13 @@ identifier as it stands. Measured over every one past ASCII, the 145,620 letters the grammar's words beside their spellings and the tables, the role's convention composes the identifier, and the leading word and the underscore below are decided on that identifier, which still holds the name's own characters. Only then does `Render` act on a character the role cannot -hold as it stands — before the length cap ([below](#a-name-too-long-for-a-path-is-shortened)), so +hold as it is — before the length cap ([below](#a-name-too-long-for-a-path-is-shortened)), so it changes nothing those read — by rewriting it on Go or keeping it on Kotlin, where quoting waits until collisions are resolved ([above](#a-name-is-rendered-bare-and-quoted-last)). `Rendered.HoldsUnwritable` is read last, off the identifier `Render` returns, since the cap can drop every such character with the words it cuts: -- **Go** sets `Role.WrittenByName` and writes each such character where it stands in its word, as +- **Go** sets `Role.WrittenByName` and writes each such character where it lies in its word, as the character-name table writes a character it does not hold: `u`, in lower case wherever it falls, and its code point in lowercase hex, four digits at least (`u0301`, `u10570`). A decomposed `café` is the field `Cafeu0301`, `नाम`, whose `ा` is U+093E DEVANAGARI VOWEL SIGN AA, @@ -432,7 +432,7 @@ every such character with the words it cuts: points above. A unit's name, a package segment and a module's directory too, is rendered as the target's naming document says ([Kotlin](../targets/kotlin/naming.md#reserved-names)). -Which characters a role cannot hold as they stand is a table of the target's options version, read +Which characters a role cannot hold as they are is a table of the target's options version, read from its toolchain and no configuration's to replace: on Go a toolchain that learns a mark would otherwise rename every identifier holding it, and on Kotlin a later table moves only where backticks are written ([target options](../contract/options.md)). The letter case `Compose` gives a @@ -496,7 +496,7 @@ an identifier its owner's role already rendered, and `Render` refuses one that f own words. A hint is held to the same test. A parameter and a package, which Go leaves unexported, and every Kotlin role, which takes `名前` as it is, take a word before a digit or a mark alone. Leaving such a Go name unexported was not taken, since a caller outside its package could neither -set nor read it, nor was writing Kotlin's in backticks as it stands, a name javac cannot write and +set nor read it, nor was writing Kotlin's in backticks as it is, a name javac cannot write and the Objective-C export renames or, before a mark, cannot write. The words are a naming table too, one per role, and like the character names a default of the diff --git a/docs/emitters/refine/pipeline.md b/docs/emitters/refine/pipeline.md index b557293c3..5ae62c49e 100644 --- a/docs/emitters/refine/pipeline.md +++ b/docs/emitters/refine/pipeline.md @@ -40,7 +40,7 @@ func RunSteps[State any](ctx context.Context, state *State, steps []Step[State]) once, as Go's does (below): the trace is in order, so each is pinned by its place. A shared `Refiner` interface, a context struct `Ctx` every target's steps read, and a marker -interface `TargetAST` over the AST roots stood here before. A context struct every target shares +interface `TargetAST` over the AST roots were here before. A context struct every target shares grows a member for each target's need, its options reached a step as a value of a shared interface the step asserted back to its own type, and the marker typed nothing: every step asserted the root to its own AST. A step over the target's own state needs neither assertion. The runner is generic, @@ -55,17 +55,17 @@ caller in a target. **This ordered, named step list IS the IR acceptance test.** Each step of [the list](steps.md) is only implementable because a specific un-lowered IR fact reached it; a missing IR capability shows -up as an unimplementable step, not a silent degrade. Ordering is asserted by a golden *step-trace* -test: collapsing aliases runs first, since every other step lowers references through it; redaction -and the stability and deprecation marks follow every step declaring a value's type or a method an -operation lowers to, since each adds to those; placement follows every structural lowering, and -import computation follows placement, since a file imports what its declarations reference from -wherever those landed; the naming steps run last — casing, then reserved-word escaping, whose scopes -reserve on Go what a file imports ([reserved names](reserved-names.md)), then collision resolution — -so every name, a unit's and an import's among them, is settled once, after everything that names it -exists. On Go a function's scope reserves the names its file's imports are given, so Go's list holds -the escaping and collision steps twice after casing, and its step trace shows both pairs: the first -settles the units' names and, after them, the name each file gives its imports, and the second every -other scope. One run of each could not, since the escaping of a function's scope reads a name the -collision step gave an import. Because each step is idempotent and reads only its state, a -step-trace snapshot pins the whole lowering deterministically. +up as an unimplementable step, not a degrade that reports nothing. Ordering is asserted by a golden +*step-trace* test: collapsing aliases runs first, since every other step lowers references through +it; redaction and the stability and deprecation marks follow every step declaring a value's type or +a method an operation lowers to, since each adds to those; placement follows every structural +lowering, and import computation follows placement, since a file imports what its declarations +reference from wherever those landed; the naming steps run last — casing, then reserved-word +escaping, whose scopes reserve on Go what a file imports ([reserved names](reserved-names.md)), then +collision resolution — so every name, a unit's and an import's among them, is settled once, after +everything that names it exists. On Go a function's scope reserves the names its file's imports are +given, so Go's list holds the escaping and collision steps twice after casing, and its step trace +shows both pairs: the first settles the units' names and, after them, the name each file gives its +imports, and the second every other scope. One run of each could not, since the escaping of a +function's scope reads a name the collision step gave an import. Because each step is idempotent and +reads only its state, a step-trace snapshot pins the whole lowering deterministically. diff --git a/docs/emitters/refine/requests.md b/docs/emitters/refine/requests.md index 6e060a56b..0b53e0b37 100644 --- a/docs/emitters/refine/requests.md +++ b/docs/emitters/refine/requests.md @@ -34,7 +34,7 @@ that type its own way ([Go](../targets/go/operations.md#the-request-type), An operation that gains its first non-path input gains the request argument, a break the surface differ reports ([surface verification](../surface-verification.md)). A dynamic target's default may -differ — Python's keyword arguments are additive as they stand — which is why the shape is +differ — Python's keyword arguments are additive as they are — which is why the shape is per-target rather than a plan fact. A choice among parameters (`Operation.ParamChoices`) changes no field of the request type: each diff --git a/docs/emitters/refine/scalars.md b/docs/emitters/refine/scalars.md index c8fd5e0f8..dd3311282 100644 --- a/docs/emitters/refine/scalars.md +++ b/docs/emitters/refine/scalars.md @@ -13,7 +13,7 @@ - **A declaration over a root keeps the root's codec.** A named scalar, an anonymous one that is no decorator ([decorators](decorators.md)), a named alias over the conjunct deciding an `allOf` no object satisfies ([models](../../ir/models.md#an-allof-no-object-satisfies)) and a `Model` whose - `Base` is no model ([lowering table](lowering-table.md)) each declare a type standing over their + `Base` is no model ([lowering table](lowering-table.md)) each declare a type over their chain's root, and it must code as the root does. So a target defines a new type only over a root whose codec that type keeps, and declares an alias over any other ([Go](../targets/go/types.md#a-declaration-over-a-root), @@ -24,12 +24,15 @@ row names ([type table](../contract/type-table.md)) to have some. An enum is outside this line: it declares its own codec, which writes each member's wire form and compares a value with the members as JSON does ([enums](enums.md#a-member-on-the-wire)), so it is a defined type whatever its value - type maps to. + type maps to. A declaration over a root never embeds null: a use's own reference says whether it + admits null, a `Base`'s `Nullable` along the chain saying nothing of the use + ([aliases](../../ir/scalars.md#aliases)), but a chain ending at the top type, which admits every + value. - **External** ([containers](../../ir/containers.md)): `External{Identity, Package, MinVersion}` becomes the type its type-table row names for `Identity` ([type table](../contract/type-table.md)), imported with the row's `Imports` and required at its `Dependency` — imported, not generated. `Package` and `MinVersion` name what the source format imports, which a built-in row may follow; they cannot name a target's type, so a row is what maps an identity. An identity with no row (`erlang:pid`, - `erlang:fun`) gets the passthrough/opaque strategy and a `warning` diagnostic, never a silent - `any`. + `erlang:fun`) gets the passthrough/opaque strategy and a `warning` diagnostic, never an `any` that + reports nothing. diff --git a/docs/emitters/refine/steps.md b/docs/emitters/refine/steps.md index 6d21b208b..8e126d6f0 100644 --- a/docs/emitters/refine/steps.md +++ b/docs/emitters/refine/steps.md @@ -9,9 +9,9 @@ | `LowerModels` | `TypePlan.Flattened`, `Required`, `Undeclared`, `Unflattened`, `Composed`, `Base`/`Implements`/`Mixins`, `AdditionalProperties`, `Additional`, `Positional` | a declaration over the flattened properties, built and compared so that no value past the nesting limit is recursed into ([how deep a value nests](models.md#how-deep-a-value-nests)), an `Undeclared` member a required field typed as the catch-all types it, the catch-all holding the undeclared members, unknown members rejected on `closed`, a union the model narrows lowered as that union ([inheritance](models.md#inheritance)) and any other `Unflattened` conjunct lowered or degraded with a code | [models](../../ir/models.md) | | `ProjectVisibilityShapes` | `plan.ModelShape` per shape, a variant composed over a union a model narrows taking its `TypePlan.Composed` entry's ([inheritance](models.md#inheritance)) | one declaration per `ModelShape.Name`, such as `User` / `UserCreate` / `UserUpdatePatch`, an alias of the type's own where `ModelShape.Alias` is set, under which each name a caller builds the value with resolves, and none for a kind no shape changes ([TypePlan](../plan/types.md#the-declaration-a-shape-takes)), and one for each type holding a projected one ([TypePlan](../plan/types.md#a-shape-reaches-what-it-holds)) | [properties](../../ir/properties.md#visibility) | | `LowerOptionality` | `TypePlan.Required` (a member's wire presence, [TypePlan](../plan/types.md), a variant composed over a union a model narrows reading its `TypePlan.Composed` entry's) ⊥ `TypeRef.Nullable`, a reference to an untagged union with a variant admitting `null` counting as nullable ([unions](unions.md#a-null-a-variant-admits)) ⊥ `Property.Presence`; `ModelShape.Patch`, under which every member is optional ([TypePlan](../plan/types.md#what-a-patch-relaxes)); `Facts.Component` | the four+ states in the target's forms; a reference on a cycle the target holds by value broken as its type system requires ([recursive references](models.md#recursive-references)) | [properties](../../ir/properties.md); INV8 | -| `LowerConstraints` | `Constraints` on properties/scalars/lists/maps/unions | a refine-built validation method structure, which descends no further than the nesting limits and keeps its first 1,000 failures ([how deep a value nests](models.md#how-deep-a-value-nests)), and no field-level metadata ([constraints](constraints.md)) | [constraints](../../ir/constraints.md) | +| `LowerConstraints` | `Constraints` on properties/scalars/lists/maps/unions/enums, a model's `ir.PropertyCountBounds` | a refine-built validation method structure, which descends no further than the nesting limits and keeps its first 1,000 failures ([how deep a value nests](models.md#how-deep-a-value-nests)), and no field-level metadata ([constraints](constraints.md)) | [constraints](../../ir/constraints.md) | | `LowerUnions` | `Union{Variants, Exclusive, WireTagged, Discriminator}`, the union a model narrows with its variants composed ([inheritance](models.md#inheritance)), a polymorphic base's `Discriminator` or `Abstract` with `Facts.Subtypes`, `TypePlan.Union`, `TypePlan.Open`, `TypePlan.Inclusive`, `TypePlan.Strict` and each shape's `ModelShape.Inclusive` | the target's closed sum, one member per variant or subtype + a fallback on an open one; an inclusive union one optional member per variant, each set when its variant admits the value ([unions](unions.md#a-value-several-variants-admit)) | [unions](../../ir/unions.md); INV2 | -| `LowerDiscriminator` | `Discriminator{Property/PropertyName/Index, Mapping→TypeID, Default, Envelope}` as `TypePlan.Discrim` resolves it; for each variant's own tags, every declaration of the tag member in the variant's flattening, taken and overridden, a subtype's `DiscriminatorValue`, and the `TypePlan.Composed` of a variant narrowing a union | a tag-dispatched decoder comparing a tag as JSON compares values ([unions](unions.md#discriminators)) + typed factories + an encoder writing each variant's tag ([unions](unions.md#the-tag-a-variants-value-carries)) | [models](../../ir/models.md)–[unions](../../ir/unions.md) | +| `LowerDiscriminator` | `Discriminator{Property/PropertyName/Index, Mapping→TypeID, DecodeOnlyRoutes→TypeID, Default, Envelope}` as `TypePlan.Discrim` resolves it: a decoder routes by `Mapping`, then `DecodeOnlyRoutes`, then recognition, then `Default`, and an encoder picks the tag from the `Mapping` of the discriminator it writes for; `DiscriminatorValue` routes nothing, being the key one ancestor's discriminator routes a subtype by, so it is what an encoder writes only through that discriminator; for each variant's own tags, every declaration of the tag member in the variant's flattening, taken and overridden, and the `TypePlan.Composed` of a variant narrowing a union | a tag-dispatched decoder comparing a tag as JSON compares values and reading `DecodeOnlyRoutes` after `Mapping` ([unions](unions.md#discriminators)) + typed factories + an encoder writing each variant's tag ([unions](unions.md#the-tag-a-variants-value-carries)) | [models](../../ir/models.md)–[unions](../../ir/unions.md) | | `LowerOpenEnums` | `Enum.Closed`, `TypePlan.Open`, `ValueType`, `Members`, `Flags`, `FallbackMember`, the merged type table | the target's closed, open and flags forms, over the value type's row or its members' wire forms ([enums](enums.md#a-member-on-the-wire)); an open one keeps an unknown value, and one with no members takes its closed form, refusing every value decoded or encoded, but an anonymous one every reference reaches as nullable, which declares nothing and is the target's type admitting `null` alone at each use ([enums](enums.md#an-enum-with-no-members)) | [enums](../../ir/enums.md) | | `ExtractInterfaces` | `Implements`, `OperationGroup` | interfaces / client interfaces for testability | [models](../../ir/models.md) | | `MapExternalTypes` | `External{Identity, Package, MinVersion}`, the merged type table | the type table's row for the identity ([type table](../contract/type-table.md)): imported library type + dependency-manifest entry; no row → opaque strategy + diagnostic | [containers](../../ir/containers.md) | @@ -31,7 +31,7 @@ | `MarkStability` | `OpPlan.Stability` | the tier in the operation's documentation, and an opt-in requirement where the target has one | [stability](../operations/stability.md); [operations](../../ir/operations.md#stability) | | `PlaceDeclarations` | `Provenance.Source`, `TypePlan.Reach`, the target's placement options, each operation's `ShapeHint.Remount` and `AlsoMount` | the output unit each declaration lands in: the runtime's in a unit of its own, any other in one package unless a partition or a group split moves it ([output units](output-units.md)); on a target naming a file for its declarations' words, the file each lands in ([Go](../targets/go/naming.md#file-names)) | [provenance](../../ir/provenance.md) | | `ComputeImports` | what each file's declarations reference: another unit's declarations, the runtime's among them, its own unit's and the language's default imports, and a type-table row's `Imports` | per-file import sets, each import by its path; the name a file gives it is settled by the naming steps, as every other name is, and one that keeps its own name where the language needs no import is printed as none ([reserved names](reserved-names.md)) | — | -| `RenderCasing` | neutral `Ident` (= `naming.Words`: the canonical words beside their source spellings; a name with none named by its characters) + the options' naming tables + the options version's letter case and the characters each role cannot hold as they stand | bare cased identifiers, the units' among them, each cased, composed and given its leading word and underscores before a character its role cannot hold is handled — written by its name on Go, or kept bare on Kotlin and marked `HoldsUnwritable` where the name as shortened still holds one ([naming](naming.md#a-character-a-target-cannot-write-is-written-by-its-name)) — the ONLY place names get cased ([naming](naming.md)); one of a role a target writes into a path shortened past the options' length cap ([naming](naming.md#a-name-too-long-for-a-path-is-shortened)) | [naming](../../ir/naming.md); INV4 | +| `RenderCasing` | neutral `Ident` (= `naming.Words`: the canonical words beside their source spellings; a name with none named by its characters) + the options' naming tables + the options version's letter case and the characters each role cannot hold as they are | bare cased identifiers, the units' among them, each cased, composed and given its leading word and underscores before a character its role cannot hold is handled — written by its name on Go, or kept bare on Kotlin and marked `HoldsUnwritable` where the name as shortened still holds one ([naming](naming.md#a-character-a-target-cannot-write-is-written-by-its-name)) — the ONLY place names get cased ([naming](naming.md)); one of a role a target writes into a path shortened past the options' length cap ([naming](naming.md#a-name-too-long-for-a-path-is-shortened)) | [naming](../../ir/naming.md); INV4 | | `EscapeReservedWords` | cased `Ident` + each scope's reserved set: keywords, what the generated code binds there, on Go the name its file gives each import, settled after the units' names and before any other scope's ([the refiner contract](pipeline.md)), what a unit or a top-level declaration cannot be named, compared folded in a scope written as paths ([reserved names](reserved-names.md)) | each scope's `naming.Scope`, built over its reserved set and what a reserved name takes there, the target's escape or, in the scope of a file's imports, the collision's suffix, which `naming.Resolve` applies in the collision step, leaving identifiers clear of every reserved set, by the target's escape and, an import's name aside, never a collision's suffix; on Multiplatform the explicit Swift name of a member meeting one of `NSObject`'s or an entry one its enum exports, and the explicit name of a declaration whose exported name meets one the target exports in the namespace every unit shares, escaped again ([Swift](../targets/kotlin/swift.md)); NEVER touches `WireName`/`WireID` | [naming](../../ir/naming.md); INV4 | | `ResolveCollisions` | each scope's members, keyed by ID, and its `naming.Scope` (`naming.Resolve`, which escapes and suffixes a scope's names in one call) | deterministic disambiguation in every scope, the units and each file's imports among them, on Go an import's name settled after the units' names and before any other scope's, an import yielding to what the target binds and, on Kotlin, to every declaration of its file, a nested one included, where on Go a parameter the spec names yields to it ([reserved names](reserved-names.md)), and a warning `emitters/naming/collision` for two names of different words told apart, rendered or folded alike ([naming](naming.md#collisions-and-the-names-a-generation-shipped)); a target whose language quotes a name, as Kotlin's backticks do for a hard keyword or `HoldsUnwritable`, quotes last ([naming](naming.md#a-name-is-rendered-bare-and-quoted-last)); never mutates IR identity | [identity](../../ir/identity.md); INV3 | diff --git a/docs/emitters/refine/text.md b/docs/emitters/refine/text.md index 0cf08666f..37569f33b 100644 --- a/docs/emitters/refine/text.md +++ b/docs/emitters/refine/text.md @@ -342,10 +342,10 @@ on what the position carries: write, and each name extending one of these, the name followed by `[` or `.`. A name several own is the one's that owns it whole, its own name before a member's, else the one's whose name it extends is the longest, and where they still tie the one's whose wire name is the smaller by - bytes, as [one election](../plan/responses.md#one-election) breaks a tie. A map or a catch-all + bytes, as [one choice](../plan/responses.md#one-choice) breaks a tie. A map or a catch-all spread over names of its own, by an exploded style or a `Prefix`, arranged or not, owns the rest: each name nothing else there owns, under a `Prefix` only one starting with it, ties going as - before. So no input claims a name an arranged binding writes, `deep[a]` staying the `deepObject` + before. So no input takes a name an arranged binding writes, `deep[a]` staying the `deepObject` `deep`'s beside an input exploding an object whose member is `deep`; none loses its own, the input named `a` owning `a` beside an exploded object declaring a member `a`; and none holds a name it never writes, so an exploded object `a` declaring `k` leaves `a` to one declaring a member `a`. @@ -382,7 +382,7 @@ is such a value ([body shapes](../plan/responses.md#body-shapes)), and `OpPlan.R request's contents, with their fields and parts ([OpPlan](../plan/operations.md)), which the request type holds in the body's place ([request shaping](requests.md#the-body)). It reports each as a warning `emitters/plan/unarranged-value` at its binding, its header or its content. A content no -election picks is not reported, and no election passes over one. Whether a content holds such a +choice picks is not reported, and no choice passes over one. Whether a content holds such a value is its own fact, however it is chosen: an inbound request is read through the content its `Content-Type` names ([operations the API sends](../operations/inbound.md)), so each such content of its request is reported, and one that arrives is the string it held, as a response a receiver writes @@ -394,7 +394,7 @@ mock answers in such a content with no body and a warning `emitters/mock/example A document that means JSON says so: a parameter declaring `content` with `application/json` in place of `schema` (§4.12.2.3), as an overlay can make it, lowers to `ContentType`, which types the input as the list it is and sends its JSON text, and a body does by offering `application/json`, which the -default ranking elects. A leaf's own value can still hold a list or an object, as an `any`'s and an +default ranking chooses. A leaf's own value can still hold a list or an object, as an `any`'s and an `External`'s can: one that does has no text, and the call fails before anything is sent ([above](#the-text-of-a-value)). A type that gains a list or an object where it held leaves turns its input from typed to text, a break the surface differ reports ([surface @@ -489,7 +489,7 @@ table](../contract/type-table.md#a-row-keyed-by-an-encoding)). a pair of its own, and the type would promise a structure the wire need not have. - **A `text/plain` body of an object sent as JSON**: it labels JSON as plain text on a guess, where the document offering `application/json` already says it. -- **Failing the call, or passing over such a content in the election**: the first fails every call +- **Failing the call, or passing over such a content in the choice**: the first fails every call for a fact fixed at generation, and the second overrides a ranking its user wrote. - **A `datetime_offset` header reading only RFC 3339**: the golden spec's one such header would never be read, for a text that names its instant exactly. diff --git a/docs/emitters/refine/unions.md b/docs/emitters/refine/unions.md index 34c952d41..b5d5d575c 100644 --- a/docs/emitters/refine/unions.md +++ b/docs/emitters/refine/unions.md @@ -31,10 +31,10 @@ variant too, a declaration of its flattened properties. Variant identity (`Variant.Name`) survives for named accessors / constructors; `WireName`/`WireID` survive for (de)serialization. **Unions never degrade to optional-field merges** — flattening a *body* union into method arguments is an opt-in `ShapeHint` ([shaping -hints](../contract/shaping-hints.md)), never a silent loss (the oagen counterexample, prior-art §1). -A future TS/Python target lowers the *same* facts to a native `A | B | C`; the decision differs, the -fact base is identical. What a union holds when several variants of an `anyOf` admit one value is -[below](#a-value-several-variants-admit). +hints](../contract/shaping-hints.md)), never a loss that reports nothing (the oagen counterexample, +prior-art §1). A future TS/Python target lowers the *same* facts to a native `A | B | C`; the +decision differs, the fact base is identical. What a union holds when several variants of an `anyOf` +admit one value is [below](#a-value-several-variants-admit). Within the untagged case, choosing *how* a variant is recognized on decode is refine's job, and ogen's `schema_gen_sum.go` is the battle-tested enumeration to lift: try, in order, explicit @@ -153,12 +153,12 @@ its own value, which a variant decides with its own codec alone: the text, decod type and encoded again, is what the variant itself writes there. A `datetime_offset` variant may write `2025-01-01T00:00:00Z` for a timestamp that arrived as `2025-01-01T00:00:00.000+00:00`, which a `string` variant beside it holds as it arrived: the string's text is the one both read back, so it -is the one written. A position with no such text is an encode error, never a silent pick, as a -member two variants hold at different values is. The merged value is then checked against each set -variant's admission, as a decoded one is: a member one variant writes that a closed one beside it -cannot hold, as after a caller adds it to the open one, is an encode error too, since the closed -variant would no longer read the value back. A union with no variant set refuses to encode and -fails validation, and the fallback is never set beside a variant. +is the one written. A position with no such text is an encode error, never a pick that reports +nothing, as a member two variants hold at different values is. The merged value is then checked +against each set variant's admission, as a decoded one is: a member one variant writes that a closed +one beside it cannot hold, as after a caller adds it to the open one, is an encode error too, since +the closed variant would no longer read the value back. A union with no variant set refuses to +encode and fails validation, and the fallback is never set beside a variant. An inclusive union within the nesting limits ([how deep a value nests](models.md#how-deep-a-value-nests)) is valid when one set variant is, which is all `anyOf` @@ -203,8 +203,11 @@ The designs this was weighed against: ## A value no variant recognizes All four wire shapes decode in one order: the variant the tag or the key names, or the one -recognition finds; then, on a discriminated union, for a tag that names none or no tag at all, the -one recognition finds among the variants no tag routes to +recognition finds. A decoder routes by `Mapping`, then `DecodeOnlyRoutes`, then recognition, then +`Default` ([discriminator](../../ir/models.md#discriminator)): on a discriminated union, a tag is +routed by `Discriminator.Mapping`, or by a variant's type name where a union's `Mapping` is nil, then +by `DecodeOnlyRoutes`, the routes a decoder reads and an encoder never writes; then, for a tag that +names none or no tag at all, the one recognition finds among the variants no tag routes to ([below](#the-tag-a-variants-value-carries)); then `Discriminator.Default`; then, on an `Open` union ([plan policy](../plan/policy.md)), the fallback; and otherwise a coded decode error. A tag that names a variant whose body fails to decode is an error either way: the variant is known, and the @@ -258,17 +261,21 @@ of its variants, which owns the tags of the outer variant its own member admits. property the discriminator names, or the tuple element at its `TupleElementIndex`. Where the tag sits outside the variant's value, in an `Envelope` or as the one key of a key-tagged union, no declaration admits or refuses it, so every tag routing to a variant is its own, a key-tagged -variant's being its wire name. A polymorphic base routes a subtype by its `DiscriminatorValue` as -well as by its `Mapping` ([discriminator](../../ir/models.md#discriminator)), and the subtype owns -each of those its member admits. - -- **Encoding.** A variant with one own tag writes it at the tag's member, whatever the value holds +variant's being its wire name. A polymorphic base routes a subtype by its `Mapping`, which holds its +whole route table, and the subtype owns each of those routes its member admits. +`DiscriminatorValue` routes nothing. It names the key that a discriminator on one of the subtype's +ancestors routes it by, so it is what an encoder writes only through that discriminator +([discriminator](../../ir/models.md#discriminator)). A decode-only route is no tag a variant owns, +since no encoder writes it. + +- **Encoding.** An encoder picks the tag from the `Mapping` of the discriminator it writes for. A + variant with one own tag writes it at the tag's member, whatever the value holds there, and adds the member where the variant declares none: the variant fixes its tag, so a caller need not set it, and a value built with the member unset does not go out with a tag nothing routes. A variant with several, as an alias in the mapping gives one, writes the tag its value holds, and a value holding none of them is a coded encode error, never a pick among them; in an envelope, where no member says which, it writes the first in the byte order of their texts, as the - compiler elects a subtype's `DiscriminatorValue`. A variant with none, one `Default` names or one + compiler chooses a subtype's `DiscriminatorValue`. A variant with none, one `Default` names or one no tag routes to, writes its value as held, and a value whose tag routes to another variant is a coded encode error, since decoding would hand it to that one, as is a value of `Default`'s that a variant no tag routes to admits. So an encoded value decodes back to the variant that wrote it. A @@ -280,7 +287,11 @@ each of those its member admits. A variant no tag routes to is still a variant some value takes, so decoding finds it by recognition, as an untagged union finds a variant ([above](#variant-identity-and-recognition)), among the variants no tag routes to, `Default`'s aside, and before `Default` ([a value no variant -recognizes](#a-value-no-variant-recognizes)). `Default` takes every tag no route names, so tried +recognizes](#a-value-no-variant-recognizes)). A polymorphic base's subtypes are tried by the length of +the longest `ir.Supertypes` chain from the subtype to the base, longest first, then by type ID: a +total order in which a subtype comes before every type it composes, and a type a document adds +changes no other type's place. So `Pet` ← `Cat` ← `Kitten` and `Pet` ← `Dog`, none of them routed, +are tried `Kitten`, `Cat`, `Dog`, `Pet`. `Default` takes every tag no route names, so tried first it would take each value meant for such a variant, and tried after it still takes what none of them admits, recognition holding a value only in a variant that admits it. Without that step no value would decode as one: on the golden spec (spec @bc6fad24, morphic @fa253fe19), 5 of the 145 @@ -295,8 +306,8 @@ variants own several tags, 50 between them. Writing the tag a value holds, as an encoder that only copies the member does, was the rule this replaces: a `nsc_Interconnect` variant built with `type` unset went out as `"type": ""`, which no route reads, and one synthesized from the member's own set carried a string routing nowhere, or, for -`infra_ServiceConfig`, the other variant's tag. Electing one tag among several, the first in byte -order as the compiler elects a subtype's `DiscriminatorValue`, would serve an example but not the +`infra_ServiceConfig`, the other variant's tag. Choosing one tag among several, the first in byte +order as the compiler chooses a subtype's `DiscriminatorValue`, would serve an example but not the encoder of a value whose member says which, which would send a tag the caller did not choose. T-56 holds the rule. diff --git a/docs/emitters/targets/go/lowering.md b/docs/emitters/targets/go/lowering.md index 064c6a7f2..a726cb006 100644 --- a/docs/emitters/targets/go/lowering.md +++ b/docs/emitters/targets/go/lowering.md @@ -34,7 +34,7 @@ Go's normative lowering of each construct of the [lowering table](../../refine/l | `Streaming` + `StreamDetail` | a method per shape offered; `Stream[T, H].Recv()`/`Send()` over an element of any kind, `string` where frames go unread, and `Header()` returning `H`, the response's declared headers in a struct named for the method; a `bytes` side as a file; terminal ends; no frame for an `Initial` over HTTP, its response members read through `Header()`; direction from core, framing from plan | | `LongRunning` | poller type + `Poll()`/`PollUntilDone()`; result from `ResultPath`; pacing from policy | | `OneWay` | fire-and-forget method, no response binding | -| `HTTPBinding.Inbound` ([operations the API sends](../../operations/inbound.md)) | no client method; a `Receiver` beside the client, built from a `ReceiverConfig`, with a `Parse(*http.Request)` method each, the config's `Verify` handed the whole request and what it stands in for and its `Unauthenticated` admitting an operation declaring no security and an alternative naming no scheme, its request type in the `read` projection, and a type per declared response with `WriteTo(http.ResponseWriter)` ([operations](operations.md#operations-the-api-sends)) | +| `HTTPBinding.Inbound` ([operations the API sends](../../operations/inbound.md)) | no client method; a `Receiver` beside the client, built from a `ReceiverConfig`, with a `Parse(*http.Request)` method each, the config's `Verify` handed the whole request and what it takes the place of and its `Unauthenticated` admitting an operation declaring no security and an alternative naming no scheme, its request type in the `read` projection, and a type per declared response with `WriteTo(http.ResponseWriter)` ([operations](operations.md#operations-the-api-sends)) | | `Channel`/`Message`/`MessageBinding` | the plan's `Message` binding → channel client + send/receive + reply routing (messaging target) | | `ErrorCase{Fault, Retryable}` | one runtime `*APIError` holding the status, fault, kind, raw body and typed `Body` and `Headers`; `errors.Is` by fault and kind, `runtime.Body[T]` for the body ([failures](errors.md)); declared facts win over policy | | `Response` beside the primary (`OpPlan.Others`) | one read as `Return` returned as the primary; no body → a nullable return, or a pager or stream that ends; another body, or a body that does not decode → `*OtherResponse` on the `error` path, with no fault and no retry; a 2xx the document does not list read as `Return` ([return shapes](returns.md)) | diff --git a/docs/emitters/targets/go/models.md b/docs/emitters/targets/go/models.md index 43105b93b..c82a2094a 100644 --- a/docs/emitters/targets/go/models.md +++ b/docs/emitters/targets/go/models.md @@ -17,7 +17,7 @@ serialized. Presence is stated in `encoding/json/v2` terms, and `omitempty` never keeps a presence state. v2 defines `omitempty` by the encoded JSON — a field is dropped when it would encode as `null`, `""`, `{}` or `[]` — so it keeps a zero number or `false` and drops a pointer to an empty struct: a set -but empty value turns into an absent one, the silent conflation [the shared +but empty value turns into an absent one, the conflation that reports nothing [the shared rule](../../refine/models.md#optionality--nullability--presence-inv8) forbids. `omitzero` is defined by the Go value and asks the type's `IsZero` method when it has one. The boxes implement `IsZero` as "not set" beside their own `MarshalJSONTo`/`UnmarshalJSONFrom`, so a box field tagged `omitzero` is @@ -213,7 +213,7 @@ inclusive ([unions](unions.md)) — already do; a model, a tuple's positional st above hold their contents by value, and do not. So a reference is held through a pointer when it lies on a cycle of references Go holds by value, read after `Base` and `Mixins` are flattened into the declarations they land in. The [shared refine -helper](../../refine/models.md#recursive-references) finds those cycles. The pointer stands for a +helper](../../refine/models.md#recursive-references) finds those cycles. The pointer carries a box's state where it can: a required reference is `*T`, which `Validate` reports when nil; an optional or a nullable one is `*T`, nil meaning absent or null; and an optional nullable one is `Opt[*T]`. diff --git a/docs/emitters/targets/go/operations.md b/docs/emitters/targets/go/operations.md index 0e461d092..7823fff28 100644 --- a/docs/emitters/targets/go/operations.md +++ b/docs/emitters/targets/go/operations.md @@ -102,8 +102,8 @@ its operations name that the receiver can compare, named for the scheme, its zer check; and `Unauthenticated bool`, stating that an operation declaring no security, or an alternative naming no scheme, admits any sender. The check reads the method, the target, the headers and `req.TLS.PeerCertificates` from `req`, the bytes from `body`, `req.Body` having been read, and -from `check` what it stands in for: `Operation`, the parse method as the SDK names it, as an event -names a call's ([what an event holds](../../contract/runtime-policy.md#what-an-event-holds)), +from `check` what it takes the place of: `Operation`, the parse method as the SDK names it, as an +event names a call's ([what an event holds](../../contract/runtime-policy.md#what-an-event-holds)), `Alternative`, the alternative's place in the operation's `Auth`, from 0, `Scheme`, the name the document gives the scheme, empty for an alternative naming none, and `Scopes`, the scopes that use requires of it, a slice of the check's own. The fields are a scope of the struct's own, where a diff --git a/docs/emitters/targets/go/types.md b/docs/emitters/targets/go/types.md index 8b7e1d8e1..0a8def6f1 100644 --- a/docs/emitters/targets/go/types.md +++ b/docs/emitters/targets/go/types.md @@ -25,8 +25,8 @@ predeclared type, a slice, a map — so the new type codes as the root does and of its own. Over any other root it declares an alias, `type Created = time.Time` or `type Owner = User`. A defined type has none of its root's methods: json/v2 refuses `type Created time.Time` outright, writes `type Key uuid.UUID` and `type Blob jsontext.Value` as -base64, and never runs a closed model's strict decoder or an open enum's keeper of unknown values -for one. +base64, and never runs a closed model's strict decoder or an open enum's reader that keeps unknown +values for one. A defined type over a sensitive chain, and a sensitive enum's named type ([enums](#enums)), declare `String`, `GoString`, `Format` and `LogValue`, each showing `[REDACTED]` @@ -53,7 +53,7 @@ an integer, a scalar's or an enum's, declares the pair itself, since a function or a list or map of them, under the same readers. A name reaches a reader as a string token, where a value's reader refuses a string. So each reader, -and each defined type's pair, asks the decoder where it stands (`jsontext.Decoder.StackIndex`: in an +and each defined type's pair, asks the decoder where it is (`jsontext.Decoder.StackIndex`: in an object, an even count of tokens read) and reads a name as [a map's key](../../contract/type-table.md#a-maps-key-is-text) is read; a `bool` key and a defined integer type's, which json/v2 refuses to write, go out through a writer that asks the encoder the same. With diff --git a/docs/emitters/targets/go/unions.md b/docs/emitters/targets/go/unions.md index 0ef9bb6ce..66b3c4b43 100644 --- a/docs/emitters/targets/go/unions.md +++ b/docs/emitters/targets/go/unions.md @@ -112,7 +112,7 @@ its copy and writes that straight to the encoder. For any other variant with one its wrapper holds through a pointer, which a copy would write through to the caller's value, or one declaring no such member, it encodes the variant under `enc.Options()` and writes the object out again with the tag at its member, or first where the object has none, reading it once and decoding -nothing beneath it. A variant with several own tags, or with none, is written as it stands once its +nothing beneath it. A variant with several own tags, or with none, is written as it is once its tag is checked. ## `Payment` in Go @@ -124,8 +124,8 @@ The IR and the plan are in [unions](../../refine/unions.md#a-discriminated-union `PaymentBankTransfer` implementing an unexported marker. `LowerDiscriminator` reads `Mapping` (keyed by **TypeID**) and generates, on the struct, an `UnmarshalJSONFrom` that peeks the `"type"` wire key and dispatches; a tag that selects no variant, with no `Default`, lands in - `PaymentUnknown` on an open union and is a coded decode error on a closed one, never a silent nil. - Variant identity survives → `NewPaymentCard(...)`. + `PaymentUnknown` on an open union and is a coded decode error on a closed one, never a nil that + reports nothing. Variant identity survives → `NewPaymentCard(...)`. - **emit.** Printer emits the struct, the interface, the wrappers and markers, and the `UnmarshalJSONFrom`/`MarshalJSONTo` pair keyed on the **wire** name `"type"`. The switch-completeness test guarantees every variant is handled. diff --git a/docs/emitters/targets/kotlin/lowering.md b/docs/emitters/targets/kotlin/lowering.md index 11e9c1c22..14bb83b86 100644 --- a/docs/emitters/targets/kotlin/lowering.md +++ b/docs/emitters/targets/kotlin/lowering.md @@ -36,7 +36,7 @@ where Multiplatform differs from the JVM ([Multiplatform common code](multiplatf | `Streaming` + `StreamDetail` | a method per shape offered; `Flow` of elements received, a send channel for a client stream, and an `onHeaders` callback given the response's declared headers before the first element; no frame for an `Initial` over HTTP, its response members reaching `onHeaders`; direction from core, framing from plan | | `LongRunning` | poller with `suspend` `poll()`/`pollUntilDone()`; result from `ResultPath`; pacing from policy | | `OneWay` | `suspend` function returning `Unit`, no response binding | -| `HTTPBinding.Inbound` ([operations the API sends](../../operations/inbound.md)) | no client method; a `Receiver` class with a `@Throws` parse method each over the runtime's `InboundRequest`, its target, headers, body and peer certificates all handed to `verify` beside the `InboundCheck` saying what it stands in for, `allowUnauthenticated` admitting an operation declaring no security and an alternative naming no scheme, `maxBodyBytes` the bound the caller's server reads a body to, and a type per declared response whose `encode()` returns an `OutboundResponse` ([operations](operations.md#operations-the-api-sends)) | +| `HTTPBinding.Inbound` ([operations the API sends](../../operations/inbound.md)) | no client method; a `Receiver` class with a `@Throws` parse method each over the runtime's `InboundRequest`, its target, headers, body and peer certificates all handed to `verify` beside the `InboundCheck` saying what it takes the place of, `allowUnauthenticated` admitting an operation declaring no security and an alternative naming no scheme, `maxBodyBytes` the bound the caller's server reads a body to, and a type per declared response whose `encode()` returns an `OutboundResponse` ([operations](operations.md#operations-the-api-sends)) | | `Channel`/`Message`/`MessageBinding` | the plan's `Message` binding → channel client + send/receive + reply routing (messaging target), over `Flow` | | `ErrorCase{Fault, Retryable}` | `ApiException` carrying an `ApiFailure`, a runtime tree by fault then kind (`ClientException` → `NotFoundException`), `e.body(T::class)` for the body; declared facts win over policy | | `Response` beside the primary (`OpPlan.Others`) | one read as `Return` returned as the primary; no body → `T?`, or a `Flow` that ends; another body, or a body that does not decode → `OtherResponseException`, outside `ApiException`; a 2xx the document does not list read as `Return` | diff --git a/docs/emitters/targets/kotlin/naming.md b/docs/emitters/targets/kotlin/naming.md index 09b75b84f..6ea11e796 100644 --- a/docs/emitters/targets/kotlin/naming.md +++ b/docs/emitters/targets/kotlin/naming.md @@ -192,7 +192,7 @@ and a unit `con_`. With Kotlin 2.4.0, classes `Error_`, `Result_`, `System_` and a caller importing their package with `*` still printed `java.lang.Error: boom` from `Error("boom")` and reached `System`, `Result` and `List`. An explicit Swift name takes the underscore too, bar one in an Objective-C method family ([Swift](swift.md)). An identifier holding a character -the lexer refuses as it stands, a mark or a letter or digit newer than its tables, is written in +the lexer refuses as it is, a mark or a letter or digit newer than its tables, is written in backticks too and keeps the character, wherever a file writes it, an import and a KDoc link among them ([naming](../../refine/naming.md#a-character-a-target-cannot-write-is-written-by-its-name)). diff --git a/docs/emitters/targets/kotlin/operations.md b/docs/emitters/targets/kotlin/operations.md index 0bcf83a8b..f9962b659 100644 --- a/docs/emitters/targets/kotlin/operations.md +++ b/docs/emitters/targets/kotlin/operations.md @@ -29,7 +29,7 @@ The runtime times each attempt, and each read or write of a body it does not buf `withTimeout`, and sets none of Ktor's timeouts ([runtime policy](../../contract/runtime-policy.md#what-a-layer-writes)). Measured with Ktor 3.2.3's CIO engine on Kotlin 2.4.0: the library's request timeout of 300ms ended a server stream 300ms after its -request, a frame already read, so it cannot stand for `Timeout.Request`, which ends with the +request, a frame already read, so it cannot take the place of `Timeout.Request`, which ends with the headers; a read of that stream under `withTimeout(300)` failed at 300ms with nothing of the request in its text, which is `Timeout.Idle`; and each of the library's timeouts wrote the request's URL into its message ([a transport's failure](errors.md#a-transports-failure)). T-37 holds this section. diff --git a/docs/emitters/targets/kotlin/unions.md b/docs/emitters/targets/kotlin/unions.md index e3016fe94..f39128740 100644 --- a/docs/emitters/targets/kotlin/unions.md +++ b/docs/emitters/targets/kotlin/unions.md @@ -23,7 +23,7 @@ The serializer writes a variant's tag as [the shared rule](../../refine/unions.md#the-tag-a-variants-value-carries) says. A model's properties are `val`s, so it encodes a variant with one own tag to a `JsonObject` under the encoder's `Json` and writes that object with the tag at its member, in the member's place or first where the object has -none, and a variant with several or none as it stands once its tag is checked. T-56 holds this +none, and a variant with several or none as it is once its tag is checked. T-56 holds this section. ## An inclusive union diff --git a/docs/emitters/testing/mandatory-tests.md b/docs/emitters/testing/mandatory-tests.md index ad08ed23c..50cf8c6cd 100644 --- a/docs/emitters/testing/mandatory-tests.md +++ b/docs/emitters/testing/mandatory-tests.md @@ -18,21 +18,21 @@ throughout these documents. no float parsing, including any constraint-merge path. 6. **T-6 · Determinism / golden IR→artifact** — identical inputs, the prior manifest among them ⇒ identical bytes; a scoped run equals the corresponding slice of a full run. -7. **T-7 · Diagnostic-not-silence** — every un-lowerable construct emits a coded diagnostic, never a - silent `any` and never a panic, a fact outside M3's scope included ([what M3 +7. **T-7 · Diagnostic-not-silence** — every un-lowerable construct emits a coded diagnostic, never + an `any` that reports nothing and never a panic, a fact outside M3's scope included ([what M3 lowers](../milestones.md#what-m3-lowers)). 8. **T-8 · Manifest ID-keying** — the entity→symbol map survives a rename of what an ID is not built from, such as an `operationId`, and, through the correlation key, a renamed path variable. 9. **T-9 · Policy precedence** — declared `Retryable`/`Fault`/`Idempotency` override policy defaults at a document-wide setting and at an operation's, in every layer. A project's document-wide - setting beats a per-operation one the document embeds, an operation's own setting beats its - layer's document-wide one, an operation ID no operation has is reported, an embedded value a - higher layer replaces, or a status a higher layer's retry list takes from an embedded one, draws - an info naming both, a value a configuration writes outside a field's vocabulary or range, a - `MaxAttempts` of 0 and a status both of one layer's retry lists name at one scope among them, is - an error, an operation's giving way to its layer's document-wide value, and a status both - resolved retry lists name stays only in the one a higher layer set, while one a layer moves into - a list a higher layer replaces stays in the other + setting takes precedence over a per-operation one the document embeds, an operation's own setting + takes precedence over its layer's document-wide one, an operation ID no operation has is + reported, an embedded value a higher layer replaces, or a status a higher layer's retry list + takes from an embedded one, draws an info naming both, a value a configuration writes outside a + field's vocabulary or range, a `MaxAttempts` of 0 and a status both of one layer's retry lists + name at one scope among them, is an error, an operation's giving way to its layer's document-wide + value, and a status both resolved retry lists name stays only in the one a higher layer set, + while one a layer moves into a list a higher layer replaces stays in the other ([layers](../contract/runtime-policy.md#layers-and-operations), [retries](../contract/runtime-policy.md#the-canonical-vocabulary)). Every leaf of the record has a value it takes and, each an error naming the leaf's path and leaving the layers below to set @@ -68,7 +68,7 @@ throughout these documents. contract](../refine/pipeline.md)). 11. **T-11 · Architecture import-graph** — the layering in [package layout](../packages.md). 12. **T-12 · Wire-conformance (milestone 3)** — expected request shapes derived from `Doc + Plan` - alone, the elected media type among them, diffed against the generated SDK under HTTP + alone, the chosen media type among them, diffed against the generated SDK under HTTP interception; request-side mismatches block, response-side inform. 13. **T-13 · Runtime determinism** — the retry, backoff and timeout templates run inside a `testing/synctest` bubble against `httptest.NewTestServer`, whose in-memory network works within @@ -218,8 +218,8 @@ throughout these documents. reachable through the accessors; a body that does not decode raises it with the bytes read and the decode error; a body past the bound stops there; an entry whose declared `Fault` contradicts its status raises that fault's class with its kind still stated; and cases whose contents - disagree elect one content on every target, by the entries' classes and the compared media type - ([one election](../plan/responses.md#one-election), [failures](../operations/errors.md)). + disagree choose one content on every target, by the entries' classes and the compared media type + ([one choice](../plan/responses.md#one-choice), [failures](../operations/errors.md)). 24. **T-24 · Streams** — each framing, under an `Item` and by media type where the framing admits both, with an element of each kind, decodes on every target. An operation offering a value and a stream gets a method for each, each sending its own `Accept`, and so does one whose stream a @@ -269,7 +269,7 @@ throughout these documents. (`nul .txt`); each character Windows refuses, U+001F among them; a trailing dot or space, where a space inside a segment is admitted; a file's name of 236 bytes, where one of 235 is admitted; an empty path, an absolute one, one holding `\`, a `.` or `..` segment or an empty one (`a//b`, - `a/./b`); a header line that lacks the marker where `Header` says it stands, and a placement + `a/./b`); a header line that lacks the marker where `Header` says it is written, and a placement outside the three; and no artifact with neither an error diagnostic nor a `no-artifacts` warning (where a generation carrying an error diagnostic alone is admitted). The checks' work grows as the artifacts do, over paths nested three directories deep. A template that fails the formatter @@ -293,13 +293,13 @@ throughout these documents. one of another type, and a body beside a `void` primary, reach the caller as `OtherResponse` with its typed `Body`, `Headers` and raw bytes, a body that does not decode as `BodyErr` and one past the bound stopped there, and neither fault, kind nor retry answers it. An exact `200` is - primary over a `2XX` written first; an exact `202` beats a `default` catch-all; a `4XX` beside a - primary `Default` is a failure; a `201` the document does not list reads as `Return`, beside a - `default` catch-all too; a `200` whose body does not decode, an unlisted `204` under a `value` - and a frame that does not decode reach the caller as `OtherResponse` with `BodyErr`, and nothing - retries them; a `HEAD` reads no body; a poller's start reads each response by its `LROPlan`; an - RPC operation's one response is its primary, leaving `Others` empty; and no golden operation's - declared status is left to no entry ([which entry + primary over a `2XX` written first; an exact `202` takes precedence over a `default` catch-all; + a `4XX` beside a primary `Default` is a failure; a `201` the document does not list reads as + `Return`, beside a `default` catch-all too; a `200` whose body does not decode, an unlisted + `204` under a `value` and a frame that does not decode reach the caller as `OtherResponse` with + `BodyErr`, and nothing retries them; a `HEAD` reads no body; a poller's start reads each + response by its `LROPlan`; an RPC operation's one response is its primary, leaving `Others` + empty; and no golden operation's declared status is left to no entry ([which entry answers](../plan/responses.md#which-entry-answers), [return shapes](../operations/returns.md)). 28. **T-28 · Unresolved schemes** — on every target, an operation whose only option names a scheme of kind `unresolved` sends what the caller's `Authenticator` writes, and with none configured is @@ -392,21 +392,22 @@ throughout these documents. its one service, and one reading an `out_of_scope` entry reads it as a `vendor_extension` one; a path item's key read under its own spelling with `Outer` set, a mapping naming the operation's spelling alone reading none of it and none of a responses object's key; an operation's own key - beats its path item's for one leaf, and for a status their retry lists both name, a key mapped - to `["retry"]` and one to `["retry", "maxAttempts"]` meeting at that leaf alone, two keys of one - node whose values for a leaf are equal setting it with no report, to the value of the key whose - spelling sorts first, a list in two orders among them, a status list, `Events`, `Keys`, - `AgentEnv`, `ClientParams` and `AlsoMount` each, and two other keys setting one leaf set it from - neither, an operation's conflicting keys leaving its path item's key to set it and a path item's - conflicting keys its operation's own key or the layer's document-wide value, under every order - of the keys and of the mapping's entries; a key on a node it cannot configure, a tag's key the - document holds, a value of the wrong shape or outside its field's vocabulary or range, a - duration written as a bare number, which is read in no unit, a group named by words rather than - its ID, a conflict, as a warning, and a key the document holds under a reason the reader - refuses, as an error, are each reported under their codes, `Read` returning the layer these - rules give under either, the entry staying in `Unmodeled` and an operation's key whose value is - invalid, or which the reader refuses, leaving its path item's to set the field; and the default - mapping, which is empty, reads nothing ([embedded policy](../contract/embedded-policy.md)). + takes precedence over its path item's for one leaf, and for a status their retry lists both + name, a key mapped to `["retry"]` and one to `["retry", "maxAttempts"]` meeting at that leaf + alone, two keys of one node whose values for a leaf are equal setting it with no report, to the + value of the key whose spelling sorts first, a list in two orders among them, a status list, + `Events`, `Keys`, `AgentEnv`, `ClientParams` and `AlsoMount` each, and two other keys setting + one leaf set it from neither, an operation's conflicting keys leaving its path item's key to set + it and a path item's conflicting keys its operation's own key or the layer's document-wide + value, under every order of the keys and of the mapping's entries; a key on a node it cannot + configure, a tag's key the document holds, a value of the wrong shape or outside its field's + vocabulary or range, a duration written as a bare number, which is read in no unit, a group + named by words rather than its ID, a conflict, as a warning, and a key the document holds under + a reason the reader refuses, as an error, are each reported under their codes, `Read` returning + the layer these rules give under either, the entry staying in `Unmodeled` and an operation's key + whose value is invalid, or which the reader refuses, leaving its path item's to set the field; + and the default mapping, which is empty, reads nothing ([embedded + policy](../contract/embedded-policy.md)). 34. **T-34 · Client settings** — on every target, a service hint naming a path parameter makes it a client setting, which every operation declaring it in that wire form sends unless the call gives its own; a call with neither is refused unsent; an operation declaring it at another wire form @@ -415,13 +416,14 @@ throughout these documents. at a location a setting cannot fill, such as `body`; a `host` label setting fills the host; no parameter becomes a setting unless a hint names it, and the plan reports every candidate in one info, the most used first ([client settings](../operations/client.md#client-settings)). -35. **T-35 · Effects** — a declared `Idempotency` of each kind beats the binding, a `GET` with none - is safe and idempotent, a `PUT` and a `DELETE` idempotent, a `POST` neither, a `QUERY` safe and - idempotent, a method `additionalOperations` declares as the method registry records it and one - the registry does not list neither, a GraphQL `query` safe and idempotent and a `mutation` - neither, each derived one marked `Inferred`; turning `ProtocolEffects` off leaves every - undeclared operation neither; and on every target a request that got no response is sent again - for an idempotent operation and never for a `POST`, under the default `Retry.WhenUncertain` +35. **T-35 · Effects** — a declared `Idempotency` of each kind takes precedence over the binding, a + `GET` with none is safe and idempotent, a `PUT` and a `DELETE` idempotent, a `POST` neither, a + `QUERY` safe and idempotent, a method `additionalOperations` declares as the method registry + records it and one the registry does not list neither, a GraphQL `query` safe and idempotent and + a `mutation` neither, each derived one marked `Inferred`; turning `ProtocolEffects` off leaves + every undeclared operation neither; and on every target a request that got no response is sent + again for an idempotent operation and never for a `POST`, under the default + `Retry.WhenUncertain` ([effects](../plan/policy.md#an-operations-effects-come-from-its-binding)). 36. **T-36 · Open enums and overlapping oneOfs** — on every target, a closed enum a response carries decodes a value it does not list and re-encodes it as it came, its constants naming only the @@ -550,7 +552,7 @@ throughout these documents. and is `engine/artifact-would-overwrite` where its owner edited the old spelling, on a volume that ignores case and one that does not, and where that rename was cut short and the next generation drops the file or renames it again, a file both spellings name is pruned once and - none is reported edited; a file standing under another spelling of a held path that nothing + none is reported edited; a file under another spelling of a held path that nothing lists, of its name or of a directory it passes through, `readme.md` where a generation adds `README.md` and `Models/user.go` where it holds `models/user.go`, is pruned and the held spelling written where its digest is fresh or it carries the marker, its bytes changed or not, @@ -560,9 +562,9 @@ throughout these documents. under a directory a write replaces, or a kept edited listed path whose folded path is a directory prefix of a held path or vice versa (`Models` beside `models/user.go`, `Models/user.go` beside `models`), on a volume that ignores case and one that does not, is - `engine/artifact-would-overwrite` before any write; a directory standing under another spelling + `engine/artifact-would-overwrite` before any write; a directory under another spelling of a directory a held path passes through, an unchanged file's too, is the same error unless the - run's prunes and directory removals remove it first, and so is a file standing there, `Models` + run's prunes and directory removals remove it first, and so is a file there, `Models` beside `models/user.go`, on either volume, one a volume lists decomposed being the same name on a volume that joins the two and another spelling on one that does not; a directory at a dropped listed spelling of a held path, `Setup.kt/notes.txt` beside `SetUp.kt`, is the same error where @@ -574,7 +576,7 @@ throughout these documents. directory or a link at its path, is `engine/manifest-unreadable` with nothing written; a write cut between its temporary file and the rename leaves that file beside its destination, under the name the pending manifest records, and the next run removes it, one the pending manifest's own - write left being written over, while a file standing at the name a write would take gives that + write left being written over, while a file at the name a write would take gives that write's temporary file another; a root holding another target's manifest, or its pending manifest alone, is `engine/manifest-foreign`, and nothing there is pruned; two targets whose roots are one directory, or one inside the other, by the path fold, are refused before any @@ -617,7 +619,7 @@ throughout these documents. integrate](../write-integrate.md)). 41. **T-41 · Docs** — the docs emitter renders every answer the plan lists, `Return`, `Others` and `Errors` with the service's `CommonErrors` among them, the `Default` once wherever the plan - places it, and every content, the primary response and the elected content first; a table for + places it, and every content, the primary response and the chosen content first; a table for each projection a type's `TypePlan.Shapes` gives it, marking the members it requires, a write-only property in no read shape's, a model created by one operation and patched by another given a table for each, a model whose members and those of the models it holds carry no @@ -777,7 +779,7 @@ throughout these documents. tests and the mock. A synthesized model holds for each member the first value, of its own set and then of the sets of the declarations its flattening overrides, that every declaration of it admits, else its own set's first, so a member a later conjunct redeclares as a plain string - keeps the value an earlier one pins and a failure schema's `success: false` stands over the + keeps the value an earlier one pins and a failure schema's `success: false` is taken over the success shape's `true`, a model narrowing a union a value of one of its entries, chosen as a variant is and the same in both declaration orders, so `rulesets_ResponseRule` has one carrying the tag routing to its variant, and a model adding nothing to its union its union's set where it @@ -992,7 +994,7 @@ throughout these documents. sent as `text/plain` as the string it held. The same parameter declaring `content` as `application/json` is typed as its list and sends that JSON text, a `string | list of string` parameter keeps both arrangements, an `any` parameter holding a list fails before anything is - sent, a `text/plain` content of an object beside an `application/json` one the ranking elects + sent, a `text/plain` content of an object beside an `application/json` one the ranking chooses draws no diagnostic, and a declared example of such a parameter is refused as `emitters/plan/example-refused`, none being synthesized in its place ([values as text](../refine/text.md#a-value-no-style-arranges), [request @@ -1169,7 +1171,10 @@ throughout these documents. such member; and a variant no tag routes to decodes by recognition, before `Default`, in a union declaring a `Default` too, where a value no such variant admits decodes as `Default`, and refuses to encode a value carrying another variant's tag, as `Default`'s variant refuses one - such a variant admits. Every example the plan synthesizes for a variant, and every member + such a variant admits; a payload carrying a tag `DecodeOnlyRoutes` alone holds decodes as the + variant it routes to, after `Mapping` and before recognition, and no encoder writes that tag, + nor, through a base whose `Mapping` keys a subtype under another tag, the subtype's + `DiscriminatorValue`. Every example the plan synthesizes for a variant, and every member `plan.Shown` fills, carries one of that variant's own tags and decodes as the variant it was made from, one whose member's set lists another variant's tag first among them, and a declared example that the variant its tag routes to does not admit is `emitters/plan/example-refused` @@ -1206,14 +1211,14 @@ throughout these documents. members the `application/json` schema requires going out under that media type and accepted by the mock, with `RequestContent` marked `Inferred`, and sends `application/json`, requiring them, where the ranking names that media type by itself, the policy is off, or the binding's - `PatchImplicitOptionality` points at `true` or at `false`, either of which elects nothing; + `PatchImplicitOptionality` points at `true` or at `false`, either of which chooses nothing; turning `plan.Policy.MergePatch` off removes the patch shape and its mark; in a merge patch a member whose reference admits null sends `null`, nothing and a value as three requests, a map and a catch-all whose value admits null send `{"k": null}` for an entry and read it back, a null marked `Inferred` as one declared, and a member or a value admitting none has no form that sends `null`, on Go and on both Kotlin targets; and a `POST` sent as a merge patch relaxes nothing ([TypePlan](../plan/types.md#what-a-patch-relaxes), [one - election](../plan/responses.md#one-election)). + choice](../plan/responses.md#one-choice)). 60. **T-60 · The declaration a shape takes** — a model with a `readOnly` and a `writeOnly` member, read by one operation and written by a `POST`, a `PUT`, a `PATCH` and a merge patch, is declared as `User`, `UserCreate`, `UserCreateUpdate`, `UserUpdate` and `UserUpdatePatch` on every target, @@ -1251,10 +1256,10 @@ throughout these documents. as 1, writes `"1"`, refuses the name `"1.5"` and refuses an object holding two of them, through the client and a caller's own decoder call, a boolean, an enum over a number, one over a string and a date each written and read as a key by their text; refuses `1.5`, `15e-1`, `1e-400`, the - string `"1"` where a value stands, the first value past each kind's range in plain digits and in - exponent form, and a negative number into an unsigned kind; reads each kind's least and greatest - value and 9007199254740993, in plain digits and in exponent form, to that exact value, which no - reader passing through a float does, and `0e99999999999999999999` as zero; refuses + string `"1"` where a value is expected, the first value past each kind's range in plain digits + and in exponent form, and a negative number into an unsigned kind; reads each kind's least and + greatest value and 9007199254740993, in plain digits and in exponent form, to that exact value, + which no reader passing through a float does, and `0e99999999999999999999` as zero; refuses `1e1000000000` and reads a literal a megabyte long that names 1, each within a time bound a literal's expansion would pass; writes plain digits; reads a parameter's and a header's text by the same table, in an SDK and in a mock; and leaves a caller's own decoder for an integer type @@ -1539,27 +1544,27 @@ throughout these documents. ones with none; of two schemes in one alternative both must hold; for an operation requiring one scheme with two sets of scopes, `[{oauth2: [read], api_key}, {oauth2: [admin]}]`, a check comparing a token's scopes with those it is told passes a `read` token with the key, refuses it - without and passes an `admin` token without, asked once for each scheme use it stands in for and - told that use's alternative and scopes, which a check asked once for the scheme fails; a check - standing in for a scheme the receiver was given no value for is told that scheme, and one for an - operation declaring no security is told none; a Go check changing the `Scopes` it is handed - leaves what the next check is told unchanged; the check reads the body's bytes as they arrived, - so an HMAC over them verifies, and the request's target and, over TLS, the client certificate, - so a `mutual_tls` check and a query key verify; a query input no style arranges is read as the - pairs its binding owns, in the order sent, and no pair another parameter owns; on Go, the - receiver's unit also declares a client whose schemes are named for each of the config's fields, - `verify` among them, and builds, a caller in another package building both; each declared - response writes its status, headers and body with no envelope, a range's refusing a status - outside it and a `Default`'s one another response declares, none of them a `CommonErrors` entry; - a Swift caller builds a receiver, reads its `maxBodyBytes`, passes a check that is told the - scheme, its alternative and its scopes, and catches a refusal; the mock server sends a callback - once, after its answer, to the URL its expression resolves to, follows no redirect and gives up - past `SendTimeout`, never dials an address outside `SendTo`, a name resolving outside it - included, nor sends through a proxy `HTTP_PROXY` names on loopback, and with 200 requests naming - one loopback URL has no more than `MaxSends` sends in flight, and sends a webhook only through - its control route, which the API's listener does not answer; and the docs give each a page - naming its event or its declaring operation and expression, with no sample ([operations the API - sends](../operations/inbound.md)). + without and passes an `admin` token without, asked once for each scheme use it takes the place + of and told that use's alternative and scopes, which a check asked once for the scheme fails; a + check taking the place of a scheme the receiver was given no value for is told that scheme, and + one for an operation declaring no security is told none; a Go check changing the `Scopes` it is + handed leaves what the next check is told unchanged; the check reads the body's bytes as they + arrived, so an HMAC over them verifies, and the request's target and, over TLS, the client + certificate, so a `mutual_tls` check and a query key verify; a query input no style arranges is + read as the pairs its binding owns, in the order sent, and no pair another parameter owns; on + Go, the receiver's unit also declares a client whose schemes are named for each of the config's + fields, `verify` among them, and builds, a caller in another package building both; each + declared response writes its status, headers and body with no envelope, a range's refusing a + status outside it and a `Default`'s one another response declares, none of them a `CommonErrors` + entry; a Swift caller builds a receiver, reads its `maxBodyBytes`, passes a check that is told + the scheme, its alternative and its scopes, and catches a refusal; the mock server sends a + callback once, after its answer, to the URL its expression resolves to, follows no redirect and + gives up past `SendTimeout`, never dials an address outside `SendTo`, a name resolving outside + it included, nor sends through a proxy `HTTP_PROXY` names on loopback, and with 200 requests + naming one loopback URL has no more than `MaxSends` sends in flight, and sends a webhook only + through its control route, which the API's listener does not answer; and the docs give each a + page naming its event or its declaring operation and expression, with no sample ([operations the + API sends](../operations/inbound.md)). 72. **T-72 · What a target cannot lower** — a document holding a construct a target degrades draws that construct's code from `Generate`; a run of two targets that fails on one's code, at a threshold or by a triage rule, writes neither's files, in either order the targets finish, and @@ -1580,7 +1585,7 @@ throughout these documents. past its `Timeout` is ended with the processes it started and has failed; a failing check leaves the written files in place, and one reported under `check-failed` fails the run at the default threshold; and a run that does not ask for the check, or that failed before it, starts no - process, and a run that stands starts none in a root whose plan drew an error + process, and a run that goes on starts none in a root whose plan drew an error ([verification](../verification.md#the-output-builds)). 74. **T-74 · The manifest checked** — an operation with neither an entry nor a diagnostic, an entry naming no entity of the document, a declaration written under an `Origin` with no entry, a diff --git a/docs/emitters/verification.md b/docs/emitters/verification.md index a9b4036af..07b7302d2 100644 --- a/docs/emitters/verification.md +++ b/docs/emitters/verification.md @@ -9,7 +9,7 @@ and the engine decides which of them fail the run (INV5, architecture.md §4). ## What a target cannot lower A construct a target cannot lower draws a diagnostic of a code of its own from `Generate`, never a -silent fallback (T-7, [what M3 lowers](milestones.md#what-m3-lowers)): a binding +fallback that reports nothing (T-7, [what M3 lowers](milestones.md#what-m3-lowers)): a binding (`emitters//unsupported-binding`), a constraint its runtime cannot check (`unchecked-constraint`), an enum member its constants cannot hold (`unrepresentable-enum-member`), an encoding its type table has no row for (`unmapped-encoding`). `Generate` writes nothing, so the @@ -125,9 +125,9 @@ type Check struct { So a failing check does not undo the write: whatever its finding is rated, the files stay for their owner to read. It runs whenever a run that has not failed asks for it, in the root of each target whose plan drew no error, one whose plan held nothing to write among them, since the tree - holds its owner's edits too. A root whose plan drew an error was not written, whatever let the - run stand ([write / integrate](write-integrate.md#every-write-is-planned-before-the-verdict)), - and is not built: it does not hold this generation. + holds its owner's edits too. A root whose plan drew an error was not written, whatever let the run + go on ([write / integrate](write-integrate.md#every-write-is-planned-before-the-verdict)), and is + not built: it does not hold this generation. - **Asked for, never the default.** The check starts the target's toolchain on code generated from the spec, a build script and tests among it, with the caller's privileges, environment and network, which resolving dependencies needs. A spec is untrusted input diff --git a/docs/emitters/write-integrate.md b/docs/emitters/write-integrate.md index 18230414b..0e0d50c11 100644 --- a/docs/emitters/write-integrate.md +++ b/docs/emitters/write-integrate.md @@ -162,7 +162,7 @@ type Entry struct { written, pruned or checked for an edit, and a file integrated as blocks is checked by its blocks alone ([below](#a-document-the-user-writes-around)). - **Nothing to do.** A file whose bytes on disk are what this run generated is not written, and - where no file is written or pruned, no pending manifest stands and the manifest the run would + where no file is written or pruned, no pending manifest exists and the manifest the run would write is the one the root holds, its `Options` and every `Inputs` field included, nothing is written, so a regeneration that changes nothing touches nothing and leaves every modification time. A file written once or marked `@morphic:ignore-file` is set aside. `Emitter` is a version, @@ -264,30 +264,30 @@ stays listed and the next generation judges it the same way. earlier generation wrote and this one drops stays, since nothing lists it. - **A first generation says so.** A root holding no manifest is a first generation, and the run reports an info `engine/first-generation`. Nothing is pruned there but what a pending manifest - lists, as a first generation cut short leaves one, and a file of the generation's standing under + lists, as a first generation cut short leaves one, and a file of the generation's under another spelling of a path it holds (below). - **Spellings a disk may not tell apart are judged together, on every volume.** A path's spellings - are the paths folding as it that the generation holds or a manifest lists, and what stands on - disk under another spelling of a held path, read off the listing of each directory it passes - through, a name in another normalization being the same name where the volume answers with it - (below). Where a listed path the generation drops folds as a path it holds, `Setup.kt` and then - `SetUp.kt`, a volume that ignores case answers the new spelling with the old file, and a run cut - short there leaves both spellings listed, whatever the next generation holds; and a spelling - nothing lists, `Setup.kt` in a root whose manifest was deleted or an owner's `readme.md` where a - generation adds `README.md`, is the file such a volume answers the held path with. So what is - known of one listed spelling is known of every spelling, whether the generation holds one of them - or none, and a file that answers several of them is pruned once. Where the generation holds one, - a file under any spelling is the generation's where its digest is fresh or known, or where it - carries the marker and nothing lists it. Where any holds another file, or a directory the run's - prunes and directory removals leave standing, what stands there is its owner's and the write is + are the paths folding as it that the generation holds or a manifest lists, and what is on disk + under another spelling of a held path, read off the listing of each directory it passes through, a + name in another normalization being the same name where the volume answers with it (below). Where + a listed path the generation drops folds as a path it holds, `Setup.kt` and then `SetUp.kt`, a + volume that ignores case answers the new spelling with the old file, and a run cut short there + leaves both spellings listed, whatever the next generation holds; and a spelling nothing lists, + `Setup.kt` in a root whose manifest was deleted or an owner's `readme.md` where a generation adds + `README.md`, is the file such a volume answers the held path with. So what is known of one listed + spelling is known of every spelling, whether the generation holds one of them or none, and a file + that answers several of them is pruned once. Where the generation holds one, a file under any + spelling is the generation's where its digest is fresh or known, or where it carries the marker + and nothing lists it. Where any holds another file, or a directory the run's prunes and directory + removals leave in place, what is there is its owner's and the write is `engine/artifact-would-overwrite` on every volume: on one that ignores case the write would replace the file or meet the directory, and on one that does not it would replace the file at the new spelling, or leave beside an edited old one, or beside the directory, a second name no volume that ignores case can hold. Otherwise, where another spelling holds a file, it is pruned and the held one written, whatever the held spelling answers, since the old file may be what answers, so a file of the generation's under another spelling of its name or of a directory it passes through is - written again under the generation's, its bytes fresh or not; where none does, the held spelling is - judged by the table. Where the generation holds none of them, each listed spelling is judged by + written again under the generation's, its bytes fresh or not; where none does, the held spelling + is judged by the table. Where the generation holds none of them, each listed spelling is judged by the table, so a file that is kept is kept under each listed spelling it answers: on a volume that ignores case a saved file two listed spellings name is reported `engine/file-edited` at each and keeps both entries, where a volume that tells case apart keeps one entry and drops the other. @@ -302,11 +302,11 @@ stays listed and the next generation judges it the same way. path draws `engine/artifact-would-overwrite` on a volume that tells case apart as on one that does not, so no run writes a tree or manifest a volume that ignores case cannot hold. - **A directory a held path passes through keeps the spelling the generation gives it.** A directory - or a file standing under another spelling of a directory a held path passes through, `Models` for + or a file under another spelling of a directory a held path passes through, `Models` for `models`, is `engine/artifact-would-overwrite` unless the run's prunes and directory removals remove it: a file the run prunes, or a directory holding only files it prunes, the generation's own under that spelling among them (above), or only empty directories it removes, at any depth. - Under a directory left standing, a write on a volume that ignores case would land under the old + Under a directory left in place, a write on a volume that ignores case would land under the old spelling, and the manifest would list a path another volume lacks; beside a file, a volume that ignores case meets it where the directory must go, and one that does not holds two names no volume that ignores case can. Planning lists each directory every held path passes through, an unchanged @@ -314,17 +314,17 @@ stays listed and the next generation judges it the same way. no further read. A name a volume lists in another normalization, a composed `é` decomposed, is the same name where the volume answers the held spelling with it (`os.SameFile` holds of the two), as APFS does; on a volume that keeps the two apart, as ext4 stores a name's bytes, it is another - spelling, judged as one, since left there it would stand beside a second directory no volume that + spelling, judged as one, since left there it would sit beside a second directory no volume that joins them can hold. - **An emptied directory does not outlive its files.** A prune removes each directory above the - file that it leaves empty. An empty directory standing at a listed path the generation drops is + file that it leaves empty. An empty directory at a listed path the generation drops is removed: a run cut before it replaced one with a file leaves it there, where an uninterrupted run would have written the file a later generation prunes. So is an empty directory under another spelling of a path held or listed, or of a directory one of those passes through, which a volume - that ignores case would answer that path with. A listed path the generation drops where no file stands has the - empty directories above it removed too. Each removal goes up from the path, passes over a + that ignores case would answer that path with. A listed path the generation drops where no file is + has the empty directories above it removed too. Each removal goes up from the path, passes over a directory already gone and ends at the first that is no empty directory, one holding something or - a file standing in a directory's place, which it leaves, so a run cut between a prune and the + a file in a directory's place, which it leaves, so a run cut between a prune and the removal of its directory, or between the removals of two directories above one file, is finished by the next. `os.Root` removes a file and an empty directory by one call, `Remove`, so each is read without following a link (`os.Root.Lstat`) before it is removed: a run cut once it had @@ -354,7 +354,7 @@ would be planned and applied by these same rules, under the same manifest ([the README](README.md#a-renderer-outside-morphic)). A plan that draws an error holds no write and no prune, so applying it changes nothing, whatever the -verdict. Where the `none` threshold or a triage rule lets such a run stand, the other targets' roots +verdict. Where the `none` threshold or a triage rule lets such a run go on, the other targets' roots are written and that one is left as it was: no rating writes over a file its owner wrote, or into a root holding another target's manifest or a newer Morphic's. @@ -386,16 +386,16 @@ Applying a plan, in order: removes: the other spelling of a file renamed in letter case alone, or a file where a directory must go. Written first on a volume that ignores case, the new file is the one the prune of the old then removes, or it lands under the old spelling of a directory an interrupted run emptied - and left standing. -4. **Each file is replaced atomically**, in byte order of path, after an empty directory standing at - its path is removed: written to its temporary file beside it, under the name the pending manifest - records, created where nothing stands, then renamed over it, under a root opened at the file's own - directory (`os.Root.OpenRoot`) ([emit rules](emit/rules.md)). `renameio`, the atomic replace the - engine's other writes go through, picks the temporary name at random (v2.0.2), which no record made - before the write could name, so the writer makes the temporary file itself. A directory no - longer empty there, a file or subdirectory added under it since the plan, is the root moved as - well, met after the prunes and the writes before it: the run stops as an interrupted one does, - and the next plan finds it in the write's way. + and left in place. +4. **Each file is replaced atomically**, in byte order of path, after an empty directory at its path + is removed: written to its temporary file beside it, under the name the pending manifest records, + created where nothing is, then renamed over it, under a root opened at the file's own directory + (`os.Root.OpenRoot`) ([emit rules](emit/rules.md)). `renameio`, the atomic replace the engine's + other writes go through, picks the temporary name at random (v2.0.2), which no record made before + the write could name, so the writer makes the temporary file itself. A directory no longer empty + there, a file or subdirectory added under it since the plan, is the root moved as well, met after + the prunes and the writes before it: the run stops as an interrupted one does, and the next plan + finds it in the write's way. 5. **The manifest is written last**, and then the pending manifest is removed. - **An interrupted write heals.** A run killed once it has begun to write leaves the pending @@ -416,7 +416,7 @@ Applying a plan, in order: While two spellings of a path are listed, as the pending manifest of such a run lists them, a file saved under either is `engine/artifact-would-overwrite` to a generation holding either ([above](#a-file-is-judged-by-its-digest)). That holds for the generation whose spelling the file - stands under too, where an uninterrupted run keeps the file and reports `engine/file-edited`. The + is under too, where an uninterrupted run keeps the file and reports `engine/file-edited`. The refused plan holds nothing, so what the cut run left, its pending manifest and its half-written tree, stays until the save is undone or the file moved away. - **What a killed write leaves heals too.** A write killed between its temporary file and the @@ -438,19 +438,19 @@ held to the history without it. Each rule taken out failed sequences of its own: writes, a pending manifest that keeps every earlier digest and temporary name, planning that reads the pending manifest, spellings judged together, a spelling nothing lists read off the disk, the digest read at an unlisted file the plan overwrites or prunes, each temporary name recorded, an -empty directory at a dropped listed path removed, the removal above a dropped path where no file -stands, passing over a directory already gone, a removal going up that stops at a file, a directory -at a dropped spelling read, a file under another spelling of a directory, another normalization the -same name only where the volume answers with it, and an owner's empty subdirectory refused. The -orders steps 3 and 4 fix, taken another way, failed none. Two rules change a verdict and not a tree, -which probes beside the model show: an empty directory under another spelling is removed where it -would else refuse the write on every volume, and, on a volume that tells case apart, an owner's -directory under another spelling of an unchanged file's is refused before a write passes through it, -so the verdict does not turn on whether a file's bytes changed. Recording no new digest at a path -kept as its owner's needs an owner's save the sequences do not make, which a trace beside the model -shows: with that digest recorded, a run cut once its pending manifest is written, and its owner then -saving exactly those bytes, the next generation replaces a save an uninterrupted run keeps. With an -owner's save or delete between two runs, each cut anywhere, the saved bytes stood, no other file was +empty directory at a dropped listed path removed, the removal above a dropped path where no file is, +passing over a directory already gone, a removal going up that stops at a file, a directory at a +dropped spelling read, a file under another spelling of a directory, another normalization the same +name only where the volume answers with it, and an owner's empty subdirectory refused. The orders +steps 3 and 4 fix, taken another way, failed none. Two rules change a verdict and not a tree, which +probes beside the model show: an empty directory under another spelling is removed where it would +else refuse the write on every volume, and, on a volume that tells case apart, an owner's directory +under another spelling of an unchanged file's is refused before a write passes through it, so the +verdict does not turn on whether a file's bytes changed. Recording no new digest at a path kept as +its owner's needs an owner's save the sequences do not make, which a trace beside the model shows: +with that digest recorded, a run cut once its pending manifest is written, and its owner then saving +exactly those bytes, the next generation replaces a save an uninterrupted run keeps. With an owner's +save or delete between two runs, each cut anywhere, the saved bytes remained, no other file was reported, and every finished run healed, but where this document says otherwise: a saved file two listed spellings name keeps both entries on a volume that joins them, and a rename cut short is refused over the save (above). Links and an unreadable manifest are not modelled. T-40 holds the @@ -474,12 +474,12 @@ whole length. A `@morphic:keep ` region belongs to an entity: the one whose declaration encloses it, or, at a file's top level, the one whose declaration it follows, else the file's first origin, whose declaration it precedes. The manifest records each as a `Region`, keyed by that entity's ID, its -correlation key and the region's name, with the region's text and where it stood against the +correlation key and the region's name, with the region's text and where it lay against the declaration. A second region of one name in one entity is a warning, and the two stay where they are, their file kept, since the key cannot tell which goes where. So a region follows its entity, to the one whose prior entry is the region's ([the names a generation shipped](refine/naming.md#collisions-and-the-names-a-generation-shipped)): when a rename moves the -entity to another file, the next generation writes the region where it stood against the entity's +entity to another file, the next generation writes the region where it lay against the entity's declaration there, at the end of the declaration's body when the declaration enclosed it, so a member a user added stays a member, and before or after the declaration otherwise. The old file, emptied of generated symbols, is pruned as any other, unless its user edited it outside its regions: @@ -490,7 +490,7 @@ type Region struct { Entity string // the entity ID it belongs to Key string // that entity's correlation key Name string // the name its marker gives it, unique within the entity - Place string // where it stood against the entity's declaration: "inside" its + Place string // where it lay against the entity's declaration: "inside" its // body, or "before" or "after" it at the file's top level File string // where it was found Text string // what it held, markers excluded @@ -539,7 +539,7 @@ marker. The engine's integrate step then rewrites only those blocks in the file - a block marked `` is the user's, and kept as it is; - a block built from an entity's ID follows the entity as [a region does](#regions-follow-their-entity): after a rename the entity's new block takes its old one's - place, and one frozen before it stands for the entity, no second block added beside it; + place, and one frozen before it is the entity's block, no second block added beside it; - a block new to this generation goes after the nearest block before it in the generated order that the file holds, else before the nearest one after it, else at the end, so a section first in the generated order is not written last; diff --git a/docs/ir/README.md b/docs/ir/README.md index c2e05433a..3892abffc 100644 --- a/docs/ir/README.md +++ b/docs/ir/README.md @@ -37,8 +37,8 @@ spec — field names and shapes in them are normative, receiver methods and help | [containers](./containers.md) | `List`, `MapT`, `Tuple`, `Literal`, `External`, `Any` | | [properties](./properties.md) | `Property` and `Visibility` | | [constraints](./constraints.md) | `Constraints`, `Encoding`, `XMLHints` | -| [values](./values.md) | `Value`, `BigVal` and the typed-data channel | -| [derived-facts](./derived-facts.md) | What `ir/irfacts` derives: subtypes, exposed properties, usage, recursion, correlation keys | +| [values](./values.md) | `Value`, `BigVal`, the typed-data channel and the answers a value is admitted by | +| [derived-facts](./derived-facts.md) | What `ir/irfacts` derives: subtypes, exposed properties, composition reach, usage, recursion, correlation keys | **The service layer** @@ -75,6 +75,24 @@ spec — field names and shapes in them are normative, receiver methods and help [open-questions](./open-questions.md) records what is undecided. The lowering each format without a compiler is planned to follow is [`planned-lowerings.md`](../compilers/planned-lowerings.md). +## Words + +These documents, and the compilers' rules that cite them, use each word below in this one sense. A +change that needs a new term adds it here, or to a compiler's own list, such as the table of words +the rules use that opens the [OpenAPI compiler's rules](../compilers/openapi.md). + +| Word | Meaning | +|---|---| +| node | A type the document's `Types` registry holds, of any kind. A node of a parsed YAML source is always a *YAML node*. | +| admits | A type admits a value that is valid against it. | +| answer | The result of asking whether a type admits a value, an `ir.Admission`: yes, no, or unknown where a fact the reader could not read might decide. | +| alias chain | The nodes met from a `Scalar` by following `Base` while each node is a `Scalar` with a `Base` ([scalars](./scalars.md#aliases)). | +| chain end | The first node on an alias chain that is no such `Scalar`: the type the chain names. | +| Unmodeled entry | One key of an `Unmodeled` map, with the value written verbatim under it, its reason and its provenance ([unmodeled](./unmodeled.md#what-an-entry-carries)). It is always written in full: in a compiler's rules, an *entry* alone is an `allOf` element. | +| holds, home | A field holds a fact, and that field is the fact's home. A fact the IR has no field for is *unhomed*, and is kept under `no_ir_home`. | +| chosen, decided | Where declarations disagree, a finding names the one taken over the others, the *chosen* one, under the role `chosen` (`ir.RelatedChosen`), and each node whose outcome it fixed under the role `decided` (`ir.RelatedDecided`). | +| intersection | Constraints holding together, as JSON Schema's `allOf` conjoins them. The IR has no intersection node ([boundaries](./boundaries.md#deliberate-exclusions)). | + ## Design rules 1. **Union of capabilities.** The IR is designed against everything any supported spec can express diff --git a/docs/ir/annotations.md b/docs/ir/annotations.md index 70c6291e6..914a53f5d 100644 --- a/docs/ir/annotations.md +++ b/docs/ir/annotations.md @@ -195,11 +195,11 @@ the carrier every bound in one place, but wrote each twice, so a consumer valida and its type checked the bound twice, and one spelling of a use built a node holding a count that another left on its carrier. A field the redeclared-property fold builds is the one carrier that can hold a bound a node it reaches holds too. Where the fold composes the field's model, the model -it mints stands at no position and holds none, so the field holds what its declarations' own nodes +it mints sits at no position and holds none, so the field holds what its declarations' own nodes bound, which those nodes, the model's mixins, still hold. Where the field's type is one declaration's node, the field holds the bounds of the declarations owning no node, which that node -may state as well. A reader joining the field's bounds with its type's meets the tightest of them -either way ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). +may state as well. A reader intersecting the field's bounds with its type's takes the tightest of +them either way ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). ## What a reference carries down diff --git a/docs/ir/auth.md b/docs/ir/auth.md index 22fe83cd4..ba7712a7e 100644 --- a/docs/ir/auth.md +++ b/docs/ir/auth.md @@ -101,7 +101,7 @@ an inbound operation any `Auth` would drop what a document says of how the API s ## Unresolved schemes A requirement names its schemes, and a name can reach no mechanism: nothing declares it, what -declares it names none, or the compiler cannot read what it names. The requirement still stands, +declares it names none, or the compiler cannot read what it names. The requirement still holds, so the option keeps its place in the list, its other schemes and its scopes, and names a scheme of kind `unresolved`, one per name. An SDK asks its caller for that credential, and never sends the service's in its place, or nothing at all unless the list offers the empty option diff --git a/docs/ir/boundaries.md b/docs/ir/boundaries.md index 32c5837d9..2d966fbb0 100644 --- a/docs/ir/boundaries.md +++ b/docs/ir/boundaries.md @@ -18,15 +18,15 @@ than sifting vendor metadata out of the same bag ([unmodeled](./unmodeled.md#rea structural carve-back: a live `unevaluatedProperties: false` is *shape* (a closed model after composition) and lowers to `Model.Additional = closed_after_composition` where a model holds it. Every other `unevaluated*` form stays verbatim: `unevaluatedProperties` with a schema value, a -`false` no model holds, and one a keyword beside it leaves inert, as `additionalProperties` leaves -`unevaluatedProperties` and `items` leaves `unevaluatedItems`, each evaluating every location the -other could apply to. An inert one is kept with that keyword, so the entry, read beside what its -position states, means what the source means: nothing. Read as a schema of its own an `unevaluated*` -entry means something else, as what it applies to depends on the keywords beside it. `propertyNames` -is not a second carve-back onto `AdditionalProperties.Key`: it constrains *every* key of the object, -including the ones `properties` declares — where there is no `AdditionalProperties` to hold a key -type at all — and it is a whole schema rather than a type, so only its degenerate `{type: string}` -form names one. +`false` no model holds, and one a keyword beside it leaves saying nothing, as `additionalProperties` +leaves `unevaluatedProperties` and `items` leaves `unevaluatedItems`, each evaluating every location +the other could apply to. One saying nothing is kept with that keyword, so the entry, read beside +what its position states, means what the source means: nothing. Read as a schema of its own an +`unevaluated*` entry means something else, as what it applies to depends on the keywords beside it. +`propertyNames` is not a second carve-back onto `AdditionalProperties.Key`: it constrains *every* +key of the object, including the ones `properties` declares — where there is no +`AdditionalProperties` to hold a key type at all — and it is a whole schema rather than a type, so +only its degenerate `{type: string}` form names one. Two neighbouring keyword groups are *not* part of this boundary — the content vocabulary (`contentEncoding`, `contentMediaType`, `contentSchema`) and the keywords that identify a schema diff --git a/docs/ir/constraints.md b/docs/ir/constraints.md index b39139ddf..61be162f5 100644 --- a/docs/ir/constraints.md +++ b/docs/ir/constraints.md @@ -27,59 +27,82 @@ type Constraints struct { ``` Constraints speak of the value, the instance of the node's logical type, and never of its wire form -([the type table](../emitters/contract/type-table.md#a-row-keyed-by-an-encoding)). Under an -[encoding](#encodings) that turns the value into another primitive, a bound the source wrote of the -wire form is no bound of the value: the length or the pattern of the text an `int64` travels as -bounds no `int64`, and a source's numeric bound written beside that text, which JSON Schema applies -to no string, bounds nothing it says. A compiler keeps such a bound verbatim -([boundaries](./boundaries.md)) rather than move it onto the value, as the OpenAPI compiler does for -a number carried as text ([`string-formats`](../compilers/openapi.md#string-formats)); it still -holds a length or pattern written beside `format: byte` or `base64url` as a bound of the bytes, one -written beside `format: http-date`, or a numeric bound beside `format: unixtime`, as a bound of the -instant, and one written beside a reference to a number carried as text as a bound of the number -(#1851). +([the type table](../emitters/contract/type-table.md#a-row-keyed-by-an-encoding)). So a bound binds +only the kind its node's value is: it is held in a node's `Constraints` only where the node's root +kind is the bound's wire kind, the kind of instance the bound applies to. A length or a pattern is +held there where the value is that text: a `Scalar` whose chain's root is `string` or `any` and +whose encodings name no `WireType`, or `bytes` no encoding names, whose length counts octets. A +numeric bound is held there where the value is that JSON number: a `Scalar` whose chain's root is a +numeric primitive no `WireType` carries, or `any`. An `Enum`'s root is its `ValueType`, so an `Enum` +of `string` or `bytes` takes the length and pattern, one of a numeric type the numeric bounds, and +one of `any` both. A `Union` takes a bound where each variant of the bound's kind is such a value or +a `Literal` whose `ValueType` is such a root. Wherever the instance is the written form of a value +of another kind, the bound says nothing of the value, for every such root: one written as text (an +instant, a date, a time, a duration, a `uuid`, a `url`, bytes written as base64, a number written as +its text) and one written as a number (an instant's seconds since the epoch). The length of the text +an `int64` or an instant travels as bounds no `int64` and no instant, and a minimum of the seconds +an instant travels as bounds no instant. A compiler keeps such a bound verbatim +([boundaries](./boundaries.md)), with `ReasonNoIRHome`, on the node or carrier that wrote it, rather +than move it onto the value, and keeps so a numeric bound written beside a number written as text, +which JSON Schema applies to no string. The OpenAPI compiler does so for every root +([`string-formats`](../compilers/openapi.md#string-formats), +[`numeric-formats`](../compilers/openapi.md#numeric-formats)). A count field, `MinLength`, `MaxLength`, `MinItems`, `MaxItems`, `MinProperties` or `MaxProperties`, holds a count from 0 to 2^63−1. A source may write a larger one, as JSON Schema's counts have no -upper limit: it reaches no field and is kept verbatim under `Unmodeled` with +upper limit: it fits no field and is kept verbatim under `Unmodeled` with `ReasonDegradedLowering` ([degraded constructs](./boundaries.md#degraded-constructs)), so an absent count beside such an entry bounds nothing less than the entry does. Each bound applies to values of one kind and admits every value of another, as JSON Schema's do: `Min`, `Max`, `ExclusiveMin`, `ExclusiveMax`, `MultipleOf`, `Precision` and `Scale` to numbers, -`MinLength`, `MaxLength` and `Pattern` to strings and bytes, `MinItems`, `MaxItems` and -`UniqueItems` to lists and tuples, and `MinProperties` and `MaxProperties` to objects. A compiler +`MinLength`, `MaxLength` and `Pattern` to strings, to symbols, which are judged as the text they +hold, and to bytes, `MinItems`, `MaxItems` and `UniqueItems` to lists and tuples, and `MinProperties` +and `MaxProperties` to objects. A compiler writes one only where a type the source admits at that use applies to it: the type the use declares, narrowed by what every schema it names admits, a reference's target, each part of a composition, a union, which admits what any of its branches does, and a set of values, which admits its members' kinds, and every type where none of them declares one. It keeps one written beside other types verbatim under `Unmodeled` with `ReasonDegradedLowering`: beside them, it bounds nothing they admit, so a length written beside a reference to a list bounds nothing the reference names, and a numeric -bound beside a set of strings nothing the set holds. An encoded value holds those its source type -takes, where the paragraph above places them: a length or pattern beside a `string` written as bytes -or an instant, and a numeric bound beside a number written as an instant. +bound beside a set of strings nothing the set holds. An encoded value holds none the paragraph +above keeps: none of the text or the number a value of another kind is written as. A bound has one home, the node a use owns, else its carrier -([annotations](./annotations.md#one-structural-home-per-declaration)), and stands only on a node +([annotations](./annotations.md#one-structural-home-per-declaration)), and is held only on a node whose kind takes it: a `Model` or a `MapT` holds `MinProperties` and `MaxProperties` alone, whatever -the source admits at that use, as its instances are objects, and a `List` or a `Tuple` `MinItems`, -`MaxItems` and `UniqueItems` alone. A compiler keeps any other written there verbatim, as above. -`irverify` reports a structural node holding a bound of another kind (`ir/bound-of-another-kind`). -It stops at structural nodes on purpose: a `Scalar`'s bounds turn on its encoding, a `Union`'s on -its variants and a carrier's on what it names, which a compiler's placement holds. +the source admits at that use, as its instances are objects, a `List` or a `Tuple` `MinItems`, +`MaxItems` and `UniqueItems` alone, and an `Enum` those of the values its `ValueType` holds +([enums](./enums.md#bounds)). A compiler keeps any other written there verbatim, as above. +`irverify` reports a structural node or an enum holding a bound of another kind +(`ir/bound-of-another-kind`). It reads no other node on purpose: a `Scalar`'s bounds turn on its +encoding, a `Union`'s on its variants and a carrier's on what it names, which a compiler's placement +holds. -**Bounds that admit no value.** `pass.Validate` reports a position or a type whose bounds, joined +**Bounds that admit no value.** `pass.Validate` reports a position or a type whose bounds, combined with those of the alias scalars its reference reaches, admit no value of the kind they apply to, -`pass/bounds-admit-no-value`, a warning: a `Min` above a `Max`, an exclusive bound that meets the -other end exactly, a `MinLength` above a `MaxLength`, and the same for items and members. It is told -once, at the type or position where the contradiction completes. A union's own bounds are judged -kind by kind, the first kind of number, string, list and object they admit none of named, and a -chain that reaches a union reads it no further ([unions](./unions.md#bounds-beside-a-union)). A -nullable position is still reported: the message names the kind of value that has none, and null -stays admitted. Not judged: an exclusive pair with no integer between its ends, and a `MultipleOf` -with no multiple in range, since `ir.Decimal` compares and does no arithmetic. A bound a schema's -type does not apply to never reaches the IR, so `{type: integer, minLength: 6, maxLength: 5}` keeps -neither and draws `openapi/degraded-construct` instead. +`pass/bounds-admit-no-value`, a warning: a `Min` above a `Max`, an exclusive bound that equals the +other end exactly, a `MinLength` above a `MaxLength`, and the same for items and members, as +`ir.ConstraintsAdmitNoValue` reads them, the one reading of the fact a compiler asks too. It is told +once, at the type or position where the contradiction completes, and an enum's members refused by +such bounds draw no finding of their own ([enums](./enums.md#bounds)). A union's own bounds are +judged kind by kind, the first kind of number, string, list and object they admit none of named, and +a chain that reaches a union reads it no further ([unions](./unions.md#bounds-beside-a-union)). A +model's member counts are judged across its composition, the intersection +[`ir.PropertyCountBounds`](./models.md#the-flattening) reads, and told at the first model whose +intersection admits none, not again at one composing it. Every model of a cycle of models composing +one another is held to one intersection and composes a crossed part, so a cycle whose intersection +admits none is told once, at its model of least provenance (by `Source`, then by `Pointer` compared +as bytes), unless a model it composes outside it admits none already and tells it. An enum's bounds +are judged against the kind of value its `ValueType` holds ([enums](./enums.md#bounds)). A value is +held to the same: a default or example of a model to the intersection, and one of an enum to its +bounds, a value an open enum does not list judged by its kind and its bounds and refused for nothing +else. A nullable position is still reported: the message names the kind of value that has none, and +null stays admitted. Not judged: an exclusive pair with no integer between its ends, and a +`MultipleOf` with no multiple in range, since `ir.Decimal` compares and does no arithmetic. A bound +a schema's type does not apply to never reaches the IR, so +`{type: integer, minLength: 6, maxLength: 5}` keeps neither and draws `openapi/degraded-construct` +instead. ## Encodings @@ -115,14 +138,16 @@ header, a `bytes` position under `base64`, was weighed and not taken: the header type of its own where it binds the string shape every other use names, and only the position's own `Encoding`, overriding the shape's, says how it travels there. `MediaType` and `Schema` sit beside it because they answer the same question one level in: what the encoded value -*is*. `Schema` is a `TypeRef` like any other schema position — the decoded shape is hoisted into -the registry at its own source pointer, never carried here as a raw payload. Encoding attaches -at the scalar definition and overrides at the property field by field: a field the property sets -replaces the scalar's, and one it leaves unset, an empty string or a nil reference, takes the -scalar's, so a property renaming the encoding keeps the scalar's `Schema` and `MediaType`. A -compiler writes only what the position declared, as JSON Schema applies the keywords at both places; -a parameter carries one the same way (`Parameter.Encoding`), as its type may be a `$ref`'d or shared -one that cannot carry what one use writes; +*is*. So a value is encoded where an `Encoding` on it, or on an alias of its chain, names a scheme +(`Name`): one stating only a `MediaType` or a `Schema` says what the value holds, not how it is +written, and encodes nothing (`ir.Encoding.Encodes`). `Schema` is a `TypeRef` like any other schema +position — the decoded shape is hoisted into the registry at its own source pointer, never carried +here as a raw payload. Encoding attaches at the scalar definition and overrides at the property +field by field: a field the property sets replaces the scalar's, and one it leaves unset, an empty +string or a nil reference, takes the scalar's, so a property renaming the encoding keeps the +scalar's `Schema` and `MediaType`. A compiler writes only what the position declared, as JSON Schema +applies the keywords at both places; a parameter carries one the same way (`Parameter.Encoding`), as +its type may be a `$ref`'d or shared one that cannot carry what one use writes; the alternative, the property's `Encoding` replacing the scalar's whole, would make a compiler copy every field it did not mean to change, and lose them where it forgot one. Protobuf editions features lower here per element after the compiler resolves the feature cascade (descriptors expose @@ -139,7 +164,7 @@ and emitters must act on it. Hints attach at both levels: `TypeCommon.XML` (root name/namespace of the shape itself) and `Property.XML`, overriding the type's field by field, as an encoding does: a field the property sets replaces the type's, and one it leaves unset takes it. So each field keeps what its source declared, a declared `false` included, and nothing a compiler -writes stands for a value the source left unstated. +writes takes the place of a value the source left unstated. `NodeType` and `Attribute` spell one fact, the node's kind: `NodeType` as OpenAPI 3.2 names it, and `Attribute` as a flag says it, OpenAPI's `attribute` or Smithy's `xmlAttribute`, the field a format diff --git a/docs/ir/derived-facts.md b/docs/ir/derived-facts.md index 7785ed2cf..a565f7182 100644 --- a/docs/ir/derived-facts.md +++ b/docs/ir/derived-facts.md @@ -7,7 +7,8 @@ What a document implies and does not state is derived by one per-document index, none goes stale after a transform. Each of its indexes is built whole the first time one of its facts needs it and never written again, so a `DocumentFacts` is safe for concurrent use; a caller that changes the document builds a new one. The package imports only `ir`, which keeps the -definitions it indexes: `Supertypes`, `IsSubtype`, `ExposedProperties` and `AliasBase`. +definitions it indexes (`Supertypes`, `IsSubtype`, `ExposedProperties`, `ComposedOf` and +`AliasBase`), and `stronglyconnected`, which finds the type graph's cycles. The two relations `ir` walks, subtypes and exposed properties, are walked rather than indexed while that is cheaper. A `DocumentFacts` answers a relation's first questions by `ir`'s own walk, limited @@ -38,11 +39,23 @@ reaches it. A pair the numbering leaves open, and a property several models decl by the walk. A mixin is a second parent, so this relation leaves pairs open more often than the subtype relation does. +## Composition reach + +`CompositionReaches(from, to)` reports whether a path of one edge or more along the edges +`ir.ComposedOf` names leads from `from` to `to`: a model's `Base` and `Mixins` and an alias scalar's +`Base`, no `Implements`, so a type reaches itself only along a cycle and an ID the document does not +hold reaches nothing. The relation is numbered the way the subtype relation is, a pair its +intervals leave open being searched from both ends. `CompositionStronglyConnectedComponents(types, +ids)` is the one derivation here that takes a registry rather than a `DocumentFacts`: it returns the +components of the composition among `ids`, each after every one its edges reach, reading an alias +scalar `ids` leaves out through to the first type `ids` holds. The OpenAPI compiler reads both while +it lowers a composition ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). + ## The type graph Usage and recursion read one graph with two vertices per declared type: its *shape*, what a value of exactly that type holds, and its *range*, every shape a value declared as -that type may take. A type is *polymorphic* when the model it stands for, read through its alias +that type may take. A type is *polymorphic* when the model it names, read through its alias scalars, has a `Discriminator` or is `Abstract`; a value declared as any other type is of exactly its shape. @@ -50,7 +63,7 @@ its shape. |---|---|---| | a shape | the target's range when it is polymorphic, its shape otherwise | what a value holds: a model's properties and catch-all (value, key, patterns), a union's variants, a list's element, a map's key and value, a tuple's elements and rest, and what an encoded value holds once decoded (`Encoding.Schema` on a property, a scalar or a list, [constraints](./constraints.md)) | | a shape | the target's shape | what a model composes: `Base`, `Implements`, `Mixins` | -| a shape, a range | the target's shape, its range | what a scalar stands for: its `Base` | +| a shape, a range | the target's shape, its range | what a scalar names: its `Base` | | a range | its own shape, and each direct subtype's range | the shapes a declared value may take | Composition reaches a shape and never a range, so a subtype that includes its discriminated base's @@ -79,7 +92,7 @@ binding marks `Inbound`, or one a binding names among its callbacks — swaps `I its errors included. A flag spreads from a root's vertex along every edge, and a property's field arguments (`Property.Args`) make the types they name `Input`, since a client writes them to select the field whatever it reads back. `Multipart` marks only a multipart body's own type and the types -its alias scalars stand for, not the types nested in it. An operation's `Default` is classed neither +its alias scalars name, not the types nested in it. An operation's `Default` is classed neither a success nor a failure ([responses](./responses.md)), so its types are not marked `Error`. An operation past the bounds of `ir.ForEachOperation`, nested deeper than `ir.MaxGroupDepth` or past `ir.MaxWalkSteps` groups and operations, is not read, and `DocumentFacts.Partial` says so for the @@ -111,7 +124,7 @@ An entity named for itself takes a key of its own: | Entity | Key | |---|---| -| operation, other than a callback | its method and route, each path variable written `{}`, a webhook's event name standing for the route; one no HTTP binding places, or that shares its route with another operation, its declared name (`Naming.Source`, an OpenAPI `operationId`) | +| operation, other than a callback | its method and route, each path variable written `{}`, a webhook's event name taking the place of the route; one no HTTP binding places, or that shares its route with another operation, its declared name (`Naming.Source`, an OpenAPI `operationId`) | | named type | its declared namespace (`TypeCommon.Namespace`) and its declared name; a primitive, its kind | | service, auth scheme | its declared name | | group | its ID, which a rule mints from a name and never from a position ([groups](./identity.md#operation-groups)) | diff --git a/docs/ir/enums.md b/docs/ir/enums.md index b257d362e..4777d5c55 100644 --- a/docs/ir/enums.md +++ b/docs/ir/enums.md @@ -1,7 +1,7 @@ # Enums -Part of the [IR design](./README.md). Enumerations, how a member is identified, why a count never -decides the kind, and the union of strings that becomes one. +Part of the [IR design](./README.md). Enumerations, how a member is identified, the bounds an enum +holds, why a count never decides the kind, and the union of strings that becomes one. ```go type Enum struct { @@ -12,6 +12,7 @@ type Enum struct { Flags bool // bitfield semantics FallbackMember string // wire name of the member to substitute when an unknown value is read // (Avro enum `default` symbol); "" = none + Constraints *Constraints // the bounds written of the kind ValueType holds (below); nil = none } type EnumMember struct { @@ -72,6 +73,28 @@ value. A value type no `PrimitiveKind` declares has no row, and is reported as `ir/unknown-primitive-kind` alone. +## Bounds + +`Constraints` holds the bounds the enum's schema writes, and those a schema it names by a `$ref` +writes, of the kinds of value its `ValueType` holds, by the row above, its `ValueType` being its root +([constraints](./constraints.md#constraints)): +`MinLength`, `MaxLength`, `Pattern` and `PatternMessage` where it is `string` or `bytes`, `Min`, +`Max`, `ExclusiveMin`, `ExclusiveMax`, `MultipleOf`, `Precision` and `Scale` where it is a number, +both where it is `any`, and none where it holds booleans. An enum of a value written as text, an +instant or a `uuid`, holds none of a length or a pattern, which bounds the text and not the value, +and a compiler keeps one verbatim with `ReasonNoIRHome`. A closed enum's bound can refuse a member it lists, as `maxLength: 2` refuses +`abc` of `[ab, abc]`, so the members alone do not say what it says, and an open enum's bounds the +values it does not list too. The enum keeps such a member as written, and `pass.Validate` names it +(`pass/enum-member-outside-bounds`, [values](./values.md#values-held-to-their-type)), unless the +bounds refuse every member, which its compiler reports as the position admitting no value. Bounds +admitting no value of its kind at all are the cause of either, and draw `pass/bounds-admit-no-value` +alone ([constraints](./constraints.md#constraints)). A bound of another kind, as a `maxItems` beside an enum of strings, +bounds no value the enum holds, so a compiler keeps it verbatim +([degraded constructs](./boundaries.md#degraded-constructs)) and `irverify` reports one on the node +(`ir/bound-of-another-kind`). A value set mixing kinds lowers to a `Union` of literals, whose +bounds are the union's own ([unions](./unions.md#bounds-beside-a-union)). The OpenAPI compiler fills +the field, and keeps a bound beside a `const` verbatim, since a `Literal` holds none. + ## The empty enum A **closed** Enum with **no members** is the empty value space — it admits its members and has diff --git a/docs/ir/identity.md b/docs/ir/identity.md index 198d009d2..aaa9d92f3 100644 --- a/docs/ir/identity.md +++ b/docs/ir/identity.md @@ -28,7 +28,18 @@ path as an RFC 6901 pointer, and the ID's path is that pointer without its leadi full name is one segment, so `acme.v1.UserId` is recorded as `/acme.v1.UserId`. A node a lowering *mints* rather than finds takes a namespace of its own, so no pointer a reference can spell ever reaches it — the general form of the rule [models](./models.md#composition-beside-a-union) -states for distributed unions and for the union a routed subtype composes. +states for distributed unions and for the union a routed subtype composes. A minted key's path may +name no construct of the source: the variant a position `P` distributes from the union an inline +entry `k` of its `allOf` writes takes `P/allOf/-/k/` and the rest of its branch's path, and `-` +names no element of an array (RFC 6901 §4), so no pointer and no other minted key spells it. The +OpenAPI compiler's fold of a field's declarations mints at `/allOf/properties/` in the +`composed` namespace, the schema the narrowest holding every declaration, a path no schema is written +at, so the ID is a function of the set of declarations +([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). The node a +branch listing several types lowers each type to, where a body split by kind is distributed over +them, sits at its variant's key and `/type/-/` in the namespace of a node found there, as no +pointer names a node beneath `type`, a string or a list of strings: a `$ref` to it resolves to +nothing. ## Across documents @@ -249,6 +260,6 @@ an empty reference, which names nothing, resolves to nothing, and the node filed ## Why IDs -This is the direct answer to oagen's name-keyed registry (silent collision merging, string-rewrite -ref fixing) and Kiota's name-keyed children (collision reconciliation logic), and adopts the -intent of TCGC's `crossLanguageDefinitionId`. +This is the direct answer to oagen's name-keyed registry (collision merging that reports nothing, +string-rewrite ref fixing) and Kiota's name-keyed children (collision reconciliation logic), and +adopts the intent of TCGC's `crossLanguageDefinitionId`. diff --git a/docs/ir/interaction-patterns.md b/docs/ir/interaction-patterns.md index fac12fdf3..b83ff2471 100644 --- a/docs/ir/interaction-patterns.md +++ b/docs/ir/interaction-patterns.md @@ -125,7 +125,7 @@ such an operation encodes no member; a `"none"` spelling would add one to nearly say nothing `RequestStream` and `ResponseStream` do not. `Streaming` summarizes an operation, and a stream belongs to one content of its payload, so an OpenAPI operation can offer `application/json` beside `application/x-ndjson`: `Content.Stream` marks each content that streams -([payloads](./payloads.md#a-content-that-streams)), and the plan elects among them +([payloads](./payloads.md#a-content-that-streams)), and the plan chooses among them ([streams](../emitters/plan/streams.md)). The wire mechanism (SSE vs JSON Lines vs WS frames vs length-prefixed events) has no field of its own: over HTTP the streaming content's `MediaType` states it, another binding frames its own messages, and the plan derives which diff --git a/docs/ir/ir-version.md b/docs/ir/ir-version.md index 9ad8ea73c..9d685ad18 100644 --- a/docs/ir/ir-version.md +++ b/docs/ir/ir-version.md @@ -47,8 +47,8 @@ MAJOR is written here until that decision is taken. obligation: a compiler never emits an older generation, and there is no option to ask it to. - *Emitters* and any other consumer are built against exactly one generation. A bump is a change they must be updated for; there is no "read it anyway" mode, because the failure a stale - consumer produces is silent — it finds no key it recognizes where a renamed one used to be and - drops the construct rather than reporting it. + consumer produces reports nothing — it finds no key it recognizes where a renamed one used to be + and drops the construct rather than reporting it. **What a consumer does on mismatch: refuse.** `ir.CompatibleVersion(v)` is the predicate, and it is exact equality with the `ir.IRVersion` the consumer was compiled against. A differing patch, a diff --git a/docs/ir/models.md b/docs/ir/models.md index b33dd91ba..6858ad0f6 100644 --- a/docs/ir/models.md +++ b/docs/ir/models.md @@ -17,9 +17,11 @@ type Model struct { AdditionalProperties *AdditionalProperties // catch-all beside the declared structure; a catch-all // with nothing beside it is a MapT, never a Model (docs/ir/containers.md) Additional AdditionalMode // openness beyond declared + the catch-all's patterns - Constraints *Constraints // cardinality of the property set (minProperties/maxProperties); - // Additional says whether undeclared properties are allowed at all, - // this says how many an instance may carry + Constraints *Constraints // cardinality of the property set (minProperties/maxProperties) + // this model's own schema writes; Additional says whether + // undeclared properties are allowed at all, this how many an + // instance may carry, intersected across Base and Mixins by a + // reader (ir.PropertyCountBounds) Abstract bool // cannot be instantiated directly; fields may be typed by it and // resolve to a conforming concrete model (GraphQL interface types) Positional bool // properties serialize positionally as a tuple ordered by WireID @@ -28,7 +30,8 @@ type Model struct { ExtensionRanges []WireIDRange // wire-ID ranges reserved for third-party extension fields // (protobuf `extensions 100 to 199`) Discriminator *Discriminator // set on the polymorphic base - DiscriminatorValue string // set on each subtype one tag routes to: that wire tag value + DiscriminatorValue string // set on each subtype one tag routes to: the key one ancestor's + // discriminator routes it by; it routes nothing InputOnly bool // GraphQL input types; distinct identity from output types } @@ -37,7 +40,8 @@ type AdditionalMode string // "closed" — no properties beyond the declared set and the catch-all's patterns // (additionalProperties: false, closed-by-construction records) // "closed_after_composition" — closed once composition is resolved (unevaluatedProperties: false -// with no additionalProperties beside it, which would leave it inert) +// with no additionalProperties beside it, which would leave it +// saying nothing) type WireIDRange struct { From, To int } @@ -66,8 +70,12 @@ type Discriminator struct { Mapping map[string]TypeID // wire value → the type it routes to: a union's variant, or a // hierarchy's base or subtype; nil on a union = infer by type // name, else the routes declared or inferred and the one the - // source implies to each variant they leave out; a hierarchy - // routes to each subtype by its DiscriminatorValue + // source implies to each variant they leave out; on a model, + // its whole route table + DecodeOnlyRoutes map[string]TypeID // wire value → the type it routes to, for each route the + // source gives that Mapping leaves out: a decoder reads it + // after Mapping, an encoder never writes it; nil or + // empty = none Default TypeID // variant to use when the tag is absent/unrecognized // (OpenAPI 3.2 defaultMapping); zero = none Envelope string // "" = tag inline in the variant object; @@ -99,15 +107,46 @@ consumer would merge entries and names itself. A `Mapping` is also what a consumer writing an instance picks the variant's tag from. A source can imply a second route to a variant an entry routes: OpenAPI reads every value no entry keys as a -component name, so a payload tagged `Dog` selects `Dog` beside an entry `dog: Dog`. A map cannot -mark one of a variant's routes as read and never written, and written in unmarked, the name would -give the variant a second tag with nothing to say which to write, so a compiler leaves it out, of a -union's `Mapping` and a hierarchy's alike. A payload carrying it then routes nowhere, or to -`Default`: the IR has no place yet for a route a consumer reads and never writes (#1863). - -A subtype's `DiscriminatorValue` is the tag by which a discriminator on one of its ancestors routes -to it: a key that discriminator's `Mapping` names it under, or else the name the source routes it -by. It is empty on a model no one tag routes to, such as one no discriminator routes, as none routes +component name, so a payload tagged `Dog` selects `Dog` beside an entry `dog: Dog`. Written into +`Mapping`, the name would give the variant a second tag with nothing to say which to write, so it +is a route of `DecodeOnlyRoutes`, of a union's discriminator and a hierarchy's alike, which holds +every route the source's rule gives that `Mapping` leaves out, whether or not the variant admits +the tag: left out, a payload carrying it would route to `Default`, which takes only a value the +source routes nowhere. A decoder routes by `Mapping`, then `DecodeOnlyRoutes`, then recognition, +then `Default`, a union's empty `Mapping` routing each variant by its type's name. An encoder picks +the tag from the `Mapping` of the discriminator it writes for, as an example and `irfacts`' variant +keys read `Mapping` alone. Each tag has one route, so +`irverify` reports a decode-only key `Mapping` holds, or, beside a union's empty `Mapping`, one that +is a variant's type name (`ir/discriminator-route-duplicate`). A mark inside `Mapping` was rejected: +a consumer ignoring the mark writes the name, where one ignoring the second map only decodes less. + +A variant or subtype no route reaches, no `Mapping` entry, decode-only route or `Default` naming its +type, nor beside a union's empty `Mapping` the name of its type, which a type with no name lacks, is +one a decoder reaches only by recognizing it. `pass.Validate` reports each as an info, +`pass/discriminator-unrouted-variant`, at the union or model holding the discriminator: a union's +variant, and each model below a base along `ir.Supertypes` once, judged by the discriminator on the +nearest model above it holding one (#1844), of two at one distance the one a breadth-first walk down +from every discriminator, in ID order, reaches it from first. So a chain of discriminators draws one +finding a model, not one a pair of discriminator and model below it. A subtype that discriminator +routes no tag to, though it routes a model below it that no nearer discriminator judges, is +abstract: the finding says it routes only through its subtypes, since it has no route of its own. A +variant admitting `null` alone carries no tag and draws none. A variant with no name beside an empty +`Mapping` is a fact of the source, which validation notes and `irverify` accepts, both reading the +name route by `ir.VariantNameRoute`. + +A model's discriminator holds its whole route table: `Mapping` routes the model and each subtype it +routes by every tag a writer may use, and `DecodeOnlyRoutes` each other tag the source routes by, so +a consumer reads a base's routes from those two maps alone, never from its subtypes. +`DiscriminatorValue` routes nothing. It names the key that a discriminator on one of the subtype's +ancestors routes it by, so it is what an encoder writes only through that discriminator: a key that +discriminator's `Mapping` names it under, or else the name the source routes it by. Another +discriminator above the subtype may route it by another tag. With `Pet` and `Dog` each holding a +discriminator, `Dog` mapping `lab` to `Labrador`, which composes `Dog`, `Labrador.DiscriminatorValue` +is `lab`, while `Pet`'s `Mapping` keys `Labrador` under `Labrador` and routes no `lab`: an encoder +writing a `Labrador` as a `Pet` writes `Labrador`, and one writing it as a `Dog` writes `lab` +(`TestDiscriminatorRoutes_EachOfTwoDiscriminatorsMapsItsRoutes`, +`compilers/openapi/internal/schema/discriminator_routes_test.go`). +It is empty on a model no one tag routes to, such as one no discriminator routes, as none routes a schema composing a discriminated union that does not list it, each of its instances carrying the tag of the variant it is ([below](#a-union-a-composition-names)). Where the subtype admits no instance carrying the name it is routed by, a heuristic may read the tag off the strings it admits @@ -122,11 +161,12 @@ the instances of a concrete base are a payload as its subtypes' are, as an OpenA name the schema declaring the `discriminator`, and the base's own shape is a variant of every reference to it ([a polymorphic base](../emitters/refine/unions.md#a-polymorphic-base)). An `Abstract` model has no instance of its own, so `pass.Validate` refuses a route to it from its own -`Mapping` or `Default` as one to a type that is no variant (`pass/discriminator-missing-variant`). -The base carries no `DiscriminatorValue` for its own route: that field is the tag a discriminator on -an ancestor routes a model by, which no ancestor of the base holds, and the base's route is its -`Mapping` entry, so the fact has one home. `ir.IsSubtype` stays irreflexive: this is a clause of the -route, not of the subtype relation every other reader of it asks. +`Mapping`, `DecodeOnlyRoutes` or `Default` as one to a type that is no variant +(`pass/discriminator-missing-variant`). The base carries no `DiscriminatorValue` for its own route: +that field is the tag a discriminator on an ancestor routes a model by, which no ancestor of the +base holds, and the base's route is its `Mapping` entry, so the fact has one home. `ir.IsSubtype` +stays irreflexive: this is a clause of the route, not of the subtype relation every other reader of +it asks. ## Composition @@ -198,6 +238,12 @@ would admit different payloads: `irverify` reports that too (`ir/catch-all-close only after composition (`closed_after_composition`) may keep a value, since a catch-all the source writes is itself what evaluates a key in JSON Schema. +A model's closure and catch-all apply to the members its flattening holds: the closed subtype the +source's author means. Where the source's own closure or catch-all was written beside members it +does not declare, a `$ref` target's, an entry's or a branch's, which JSON Schema has it apply to as +well, it is stricter than that, and the compiler keeps the keyword verbatim under `Unmodeled` as +`degraded_lowering` to say where ([boundaries](./boundaries.md#degraded-constructs)). + ## The flattening `ir.FlattenedProperties(types, id)` returns a model's full shape: its members, one per wire name, @@ -257,6 +303,21 @@ lists that no member declares and the composition entries that name no model. It union there is one the model narrows, `ir.NarrowedShapes` flattens each shape an instance takes by this walk too, with a variant read in the union's place ([below](#the-shapes-of-a-model-narrowing-a-union)). +- *Member counts.* `ir.PropertyCountBounds` reads, beside the flattening, the intersection of the + `MinProperties` and `MaxProperties` of the model and of every model it composes along `Base` and + `Mixins`, read through alias scalars: the largest minimum and the smallest maximum, as an + instance is held to the bounds of each, and nil where none of them writes one. `Implements` is no + part, and a union the composition names intersects none; for a shape `ir.NarrowedShapes` lists, + the counts intersect too those of each variant its `Over` reads in a union's place and of every + model that one composes ([below](#the-shapes-of-a-model-narrowing-a-union)). One reader reads + each strongly connected component of the composition once, every model of a cycle sharing one + intersection, so it answers every model of a document in time linear in its models and entries, + where a walk per model grows with the square of a deep hierarchy. Each model's `Constraints` keep + what its own schema writes, so a mixin's bound is stated once and a model's own stays + recoverable, and a reader intersects: `TypePlan` and `pass.Validate`'s model check read the + intersection, never the model's own alone. Writing the intersection into each model was weighed + and rejected: it restates a mixin's bound on every model composing it and loses each model's + own. - *What it leaves.* A catch-all, `AdditionalProperties` and `Additional`, is not flattened: a consumer reads the model's own ([TypePlan](../emitters/plan/types.md)), so a conjunct closing its property set is the consumer's to weigh. A property marked `Flatten` is one member like any other, @@ -321,11 +382,11 @@ together: a `$ref` entry that also writes keywords beside the `$ref` is the refe straight to the target, and an inline entry of those keywords at the same pointer, writing no reference of its own, as `allOf: [{$ref: T}, {K}]` writes them, and a `$ref` written beside the composition's own keywords is one more such reference. Those keywords bind the composition, never -the shared node, and no node stands at the entry for its reference, so every `$ref` entry composes -the schema it names; where they decide an `allOf` no object satisfies, the node they build stands at -the position, as any inline principal's does ([below](#an-allof-no-object-satisfies)). An `allOf` of one `$ref` -saying nothing else is that reference, and a position needing a node of its own over it, a -component or one a `$ref` names, owns the `Model` over an object or the alias over anything else +the shared node, and no node sits at the entry for its reference, so every `$ref` entry composes +the schema it names; where they decide an `allOf` no object satisfies, the node they build sits at +the position, as any inline principal's does ([below](#an-allof-no-object-satisfies)). An `allOf` of +one `$ref` saying nothing else is that reference, and a position needing a node of its own over it, +a component or one a `$ref` names, owns the `Model` over an object or the alias over anything else ([`allof-classification`](../compilers/openapi.md#allof-classification)). A node a use hoists is hinted by its position, a function of the documents and the position alone, so an outside `$ref` naming that pointer gives the same one, whichever lowering interns the node. @@ -333,8 +394,8 @@ naming that pointer gives the same one, whichever lowering interns the node. `Base` and `Mixins` name the referents a composition of objects composes: a `$ref` entry is one only where the schema it lands on lowers to an object alone, null aside, or, where that schema's `type` list holds an object, through the object variant its union holds, so no `Model` names a base -or a mixin known to be no object: one whose own read is cut short, as over `$ref`s leading round a -loop, composes as written. In JSON Schema any schema may be a conjunct: `allOf: [{$ref: Pet}, +or a mixin known to be no object: one naming no schema, as a cycle of `$ref`s writing nothing else +does, composes as written, its reference kept. In JSON Schema any schema may be a conjunct: `allOf: [{$ref: Pet}, {$ref: Tags}]` is legal and, `Tags` being a list, admits no instance, so it composes `Pet` and keeps the `$ref` to `Tags` verbatim under `openapi:$ref` with an info, as it keeps one to a `Scalar`, an `Enum`, a union admitting another kind or the top type: no entry the source wrote is dropped, @@ -350,12 +411,19 @@ conjuncts. A `Model` says its value is an object, and `allOf: [{type: integer}, {type: integer, format: int32}]` admits none, so it is no composition, nor is `allOf: [{$ref: AnyT}]` over a schema admitting every kind, which admits strings a `Model` excludes. An `allOf` whose kinds are not an object alone, or -one of whose conjuncts states a value set, which is elected before a composition as beside the +one of whose conjuncts states a value set, which is chosen before a composition as beside the `allOf`, lowers to one use of the conjunct that decides it, short of the cases the OpenAPI compiler's rule [`allof-refinement`](../compilers/openapi.md#allof-refinement) keeps composing: a reference to its `$ref`, of several the one lying within more conjuncts, the node an inline entry -lowers to, a value set's or any other, standing at the position's own pointer and holding the -bounds of the conjunction, and an alias only where the position writes what no carrier holds. A union written beside the +lowers to, a value set's or any other, sitting at the position's own pointer and holding the +bounds of the conjunction, and an alias only where the position writes what no carrier holds. A +read the compiler cuts short at a bound chooses nothing from what it let in: what the conjuncts +say decides, and the position is what their kinds name, never a `Model` unless those are an object +alone. Value sets sharing no member are the closed empty `Enum` of their one value type keeping +every set verbatim, and conjuncts whose kinds share none, value sets sharing no member that type +no `Enum` among them, the closed `Model` with no member a `false` schema lowers to, keeping each +conjunct verbatim, as the OpenAPI compiler's rule says; a `const` and an `enum` one schema writes +are two such sets. A union written beside the `allOf` is one more conjunct, as one on an entry is, unless it shares no kind with the rest, when it is kept beside what the rest lowers to. At `cloudflare/api-schemas` @`319dc756` that is 517 of the 3,654 positions lowering an `allOf`, 408 of @@ -390,7 +458,7 @@ The designs this was weighed against: - **An alias for a narrowing**, as `{$ref: Op, enum: [set]}` lowered beside a 3.1 `$ref`: the field then kept its value set only under `Unmodeled`, where the position has a typed `Enum` to hold it. - **The inline principal's node at the entry writing it**: its ID then follows the entry's index - and the spelling, a component or `items` stands as an alias over it, the `$ref` it narrows is + and the spelling, a component or `items` is an alias over it, the `$ref` it narrows is kept on another node, and a bound another conjunct writes is held by the alias or the carrier rather than the node, so a reader of a `Union` alone meets it in one spelling and not the other ([`allof-refinement`](../compilers/openapi.md#allof-refinement)). @@ -416,14 +484,14 @@ to nothing, so it is no variant: a variant would be a type no value inhabits, wh still have to declare and dispatch to. The OpenAPI compiler keeps such a branch on the `Union`, which leaves `oneOf` and `anyOf` admitting what they did, and where no branch is left the node is what `S` lowers to alone, the union kept beside it, whether `S` writes it beside its body or on an -entry of its `allOf`, whose other entries are then the body. A route the discriminator standing -with the union takes to such a branch keys nothing in the `Mapping`, which names variants, and the -compiler keeps what the source writes of it beside the branch: a document routing a tag to a type -no value inhabits is no less valid for it. Keeping the variant and reporting it was -weighed: it leaves a `Union` member every emitter must render for no payload. +entry of its `allOf`, whose other entries are then the body. A route the discriminator sitting with +the union takes to such a branch keys nothing in the `Mapping`, which names variants, and the +compiler keeps what the source writes of it beside the branch: a document routing a tag to a type no +value inhabits is no less valid for it. Keeping the variant and reporting it was weighed: it leaves +a `Union` member every emitter must render for no payload. What `S` says of the position rather than of its shape, its docs, deprecation, examples and what a -use binds, is said once, on the `Union` that stands there and the carriers using it, and a value +use binds, is said once, on the `Union` that sits there and the carriers using it, and a value bound, which constrains both sides of the disjunction, on each variant whose kinds it bounds: a property count on each variant, each admitting an object, and a string's bound on none, which `S` beside `type: object` leaves no instance of. That holds whether `S` writes it beside the `allOf` or on an @@ -528,13 +596,13 @@ since a model a union lists is that variant ([above](#a-union-a-composition-name `ir.NarrowedShapes(types, id, limit)` returns that union and the shapes an instance takes, each the model's flattening with a variant of the union in its place: -- *A variant in a union's place.* Wherever the walk meets the union, at every entry standing for - it, it reads the variant there instead, as that entry's target, read through alias scalars. So the +- *A variant in a union's place.* Wherever the walk meets the union, at every entry naming it, it + reads the variant there instead, as that entry's target, read through alias scalars. So the variant's members are laid out, overridden, required, redacted and deprecated as any conjunct's - are ([the flattening](#the-flattening)), and a variant composing its own union reads itself in - its place there too. A variant naming no model is listed in `Unflattened` as the union's - `Variants` write it. `Stored` above takes two shapes: over `Block`, `action` and `status` and then - `id`, and over `Log`, `action` and then `id`. + are ([the flattening](#the-flattening)), and a variant composing its own union reads itself in its + place there too. A variant naming no model is listed in `Unflattened` as the union's `Variants` + write it. `Stored` above takes two shapes: over `Block`, `action` and `status` and then `id`, and + over `Log`, `action` and then `id`. - *Unions in turn.* Where the composition over a variant narrows a union in turn, as a variant that is a union, or composes one, makes it, that shape gives way to one for each of that union's variants, and `NarrowedShape.Over` lists the variants read, outermost first. So no shape narrows diff --git a/docs/ir/naming.md b/docs/ir/naming.md index 71a645927..76cca40c7 100644 --- a/docs/ir/naming.md +++ b/docs/ir/naming.md @@ -113,9 +113,9 @@ What is left is decidable without any grammar, and `irverify` holds an alias to `Hint` are names the IR derived for an emitter to render, never names a writer schema could have spelled. -That such an entry is inert is also why a *source* declaring one is recorded once with a diagnostic -rather than carried through: dropping it is not the lossy direction, since the same set of names -resolves to the entity either way. +That such an entry says nothing is also why a *source* declaring one is recorded once with a +diagnostic rather than carried through: dropping it is not the lossy direction, since the same set +of names resolves to the entity either way. An alias can also collide with *another* entity's name, and that is not a rule of the list: @@ -210,7 +210,10 @@ case, the pass also reports names whose words join alike (below). that does, so each is named by its index, and the finding says a target tells two named alike apart only by position. - **An exact repeat is reported** like any other collision: two documents each declaring a - component `Pet` give two types that render alike, which nothing else reports. A repeat may also + component `Pet` give two types that render alike, which nothing else reports. A union's variant + naming the type an earlier one names is the exception, left out of the union's scope: the two + share their name because they share their type, which the repeated-variant finding reports + ([unions](./unions.md#a-type-listed-twice), #1828). A repeat may also draw a finding of the compiler's, such as `openapi/duplicate-enum-value`, which says what the source repeats, where this one says what a target does with it. - **A name with no word character** has no neutral name at all, and a target names it from its diff --git a/docs/ir/open-questions.md b/docs/ir/open-questions.md index a860287aa..f6bda98f1 100644 --- a/docs/ir/open-questions.md +++ b/docs/ir/open-questions.md @@ -7,8 +7,8 @@ Part of the [IR design](./README.md). Tracked for implementation. 2. **Dedup aliasing mechanics** — alias table on Document vs ID rewriting with a redirect map; leaning alias table (IDs immutable, always). 3. **Content negotiation in the plan layer** — settled: the IR keeps all media types, and one - shared plan helper elects among them for a success, a failure and a stream alike, by a ranking - the plan's policy holds ([one election](../emitters/plan/responses.md#one-election)). + shared plan helper chooses among them for a success, a failure and a stream alike, by a ranking + the plan's policy holds ([one choice](../emitters/plan/responses.md#one-choice)). 4. **Whether `UsageFlags` is stored or always recomputed** — settled: derived by `ir/irfacts`, not stored ([derived-facts](./derived-facts.md)). On the golden spec (`cloudflare/api-schemas` at `843eae2f`) deriving usage for every type, the subtype index and the type graph included, takes diff --git a/docs/ir/payloads.md b/docs/ir/payloads.md index c37ef3509..bdcd33d18 100644 --- a/docs/ir/payloads.md +++ b/docs/ir/payloads.md @@ -12,7 +12,7 @@ type Payload struct { // nil = the source format does not express body optionality. // Three states, not two: a format that expresses it treats an // unstated body as optional, so folding that onto nil would make - // "the format is silent" read as "the document says no". + // "the format says nothing" read as "the document says no". // Response and message payloads leave it nil — only a request // body can be omitted — and pass/validate reports one set // anywhere else (ir/payload-required-outside-request) @@ -182,7 +182,7 @@ Four other homes were weighed: - **No field, the consumer reading the media type.** A consumer re-runs a heuristic the compiler already ran, under a table of its own, and the two disagree wherever the tables do. With the compiler told that `application/x-acme` streams, a response offering it beside `application/json` - has a `StreamDetail` and no content the plan's table names, so the plan elects among all its + has a `StreamDetail` and no content the plan's table names, so the plan chooses among all its contents and streams the JSON one. And a media type is read only beside a `StreamDetail`, so a `Default` offering `text/event-stream` alone, which no `StreamDetail` summarizes, would reach the plan as one document. diff --git a/docs/ir/provenance.md b/docs/ir/provenance.md index c2aec7e07..7b367e8b7 100644 --- a/docs/ir/provenance.md +++ b/docs/ir/provenance.md @@ -33,7 +33,7 @@ type Diagnostic struct { } type Related struct { - Role RelatedRole // kept | decided; irverify reports another (ir/unknown-related-role) + Role RelatedRole // chosen | decided; irverify reports another (ir/unknown-related-role) Provenance Provenance } ``` @@ -90,47 +90,52 @@ each kind has its own field. `Pointer` is the structural locator into a source a but an RFC 6901 pointer, which is what lets a consumer walk it with `jsontext.Pointer`'s methods. `Position` is for a finding made on a raw node the parser hands back, and is the form editors turn into a link. Such a finding carries the node's `Pointer` beside it whenever the parsed tree holds -the node, so it is placed where a lowering finding about the same construct is. The position stands -alone for a part of the source no pointer reaches, such as a later document of a YAML stream or a -pair a `<<` merge key brings in, which the merged document holds at another pointer; and for the -document's top-level mapping, whose pointer is the empty one, which beside a position reads as none. -`Node` is where an IR pass reports a finding about the document itself, or, beside a source -location, the node a compiler's finding decided, as the member the OpenAPI compiler folds a report's -declaration into; its spelling is the producer's, and nothing parses it. A verifier holds a `Pointer` to RFC 6901 and a `Position` to -1-based values, and refuses either one on `NoSource`, where there is no file for it to be inside. -Nothing requires exactly one locator: a finding may carry a `Node` beside a source location, and a -node the lowering reached may carry both a pointer and a position. The two need not name one place: -a node YAML aliases share is one node at several pointers, so its `Pointer` is the least of the -places that mount it, compared token by token, while its `Position` is where its text is written, -which may be another of them. +the node, so it is placed where a lowering finding about the same construct is. A node minted at a +key naming no construct ([identity](./identity.md#the-id-grammar)) takes that key's path as its +`Pointer`, and its source position from what it was assembled from. The position alone names a part +of the source no pointer reaches, such as a later document of a YAML stream or a pair a `<<` merge +key brings in, which the merged document holds at another pointer; and for the document's top-level +mapping, whose pointer is the empty one, which beside a position reads as none. `Node` is where an +IR pass reports a finding about the document itself, or, beside a source location, the node a +compiler's finding decided, as the member the OpenAPI compiler folds a report's declaration into; +its spelling is the producer's, and nothing parses it. A verifier holds a `Pointer` to RFC 6901 and +a `Position` to 1-based values, and refuses either one on `NoSource`, where there is no file for it +to be inside. Nothing requires exactly one locator: a finding may carry a `Node` beside a source +location, and a node the lowering reached may carry both a pointer and a position. The two need not +name one place: a node YAML aliases share is one node at several pointers, so its `Pointer` is the +least of the places that mount it, compared token by token, while its `Position` is where its text +is written, which may be another of them. ## Related places A finding sits at one place, its `Provenance`, and some concern more than one: two declarations -that disagree are two places, and a conflict said once for every model composing them decides a +that disagree are two places, and a report said once for every model composing them decides a member on each. `Related` lists the others, each with the role it plays, so a consumer annotates both declarations or lists what a finding reached without reading its message. The alternative weighed was a single field naming one other place, which holds a pair and nothing more: the nodes a -finding decided would stay a count in prose, and telling the models that kept one declaration of a -pair from those that kept the other would stay a guess. A message per entry, the form editor +finding decided would stay a count in prose, and telling the models that took one declaration of a +pair from those that took the other would stay a guess. A message per entry, the form editor protocols give related information, was weighed too: a consumer would key on prose again. | Role | The entry's `Provenance` | |---|---| -| `kept` | the place whose say the finding kept over the one it sits at: a source location, as the finding's own is | -| `decided` | a node the finding decided, by its ID in `Node` on `NoSource`, as an IR pass names one; every such node is listed, one or many | +| `chosen` | the place whose say the finding chose over the one it sits at: a source location, as the finding's own is | +| `decided` | a node the finding decided, by its ID in `Node`: on `NoSource`, as an IR pass names one, or, from the OpenAPI member fold, at the source and pointer of the model declaring the member; every such node is listed, one or many | `Role` is a closed set a consumer switches on, so a new role is a change of the IR's version ([ir-version](./ir-version.md)). An entry's `Provenance` answers to every rule a finding's own does, names a place or a node, whatever its role (`ir/empty-related`: on `NoSource`, where no -pointer or position stands, a node), and one saying `decided` names a node -(`ir/related-names-no-node`). The entries' order is their producer's convention, never the order a -map was read in, and no check of the IR holds it: the OpenAPI compiler's conflict report, the one -report filling the list so far, gives its one `kept` place and then each member it decided by -ascending ID ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)), -which `merge.TestReportOnce_AConflictListsWhatItKeptAndThenWhatItDecided` holds. An empty list and -an absent one say the same, that the finding concerns its own place alone, so the member is left -out when empty. +pointer or position is given, a node), and one saying `decided` names a node +(`ir/related-names-no-node`) the document holds, a type of its registry or a property one of its +models declares (`ir/dangling-decided-node`): a consumer listing what a finding decided finds each. +The entries' order is their producer's convention, never the order a map was read in, and no check +of the IR holds it: the OpenAPI compiler's member fold reports, the ones filling the list so far, +give their one `chosen` place, where a report is about two declarations, and then each member they +decided by ascending ID +([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)), which +`merge.TestReportOnce_AConflictListsWhatItChoseAndThenWhatItDecided` holds. An empty list and an +absent one say the same, that the finding concerns its own place alone, so the member is left out +when empty. A finding holding a list is not comparable as a Go value, so what dedupes findings keys on `Diagnostic.Key`, the whole value, `Related` entry by entry. diff --git a/docs/ir/responses.md b/docs/ir/responses.md index b44d27519..5fd9e0ac6 100644 --- a/docs/ir/responses.md +++ b/docs/ir/responses.md @@ -109,7 +109,7 @@ is the resource the `resource-hierarchy` row plans, not this shape. ## Prefix headers -A header can stand for every field whose name starts with a prefix rather than for one field, as +A header can cover every field whose name starts with a prefix rather than for one field, as Smithy's `@httpPrefixHeaders` binds a map of strings on a member of an operation's output or error, and an object store returns its user metadata under one prefix that way. On a request a binding holds the prefix ([prefix bindings](./http-binding.md#prefix-bindings)); on a response's, an diff --git a/docs/ir/scalars.md b/docs/ir/scalars.md index 63e0c18cd..4ae74fb00 100644 --- a/docs/ir/scalars.md +++ b/docs/ir/scalars.md @@ -24,7 +24,20 @@ nearest representable base and accumulate constraints/encoding along the way. `Base` is also the edge an *alias* uses, and there it names a node of any kind: the [one-home rule](./annotations.md#one-structural-home-per-declaration) gives a position that declares something a node of its own, and where that position resolved to a shared target — a `$ref` to a model, a -union, an enum — the node it owns is a `Scalar` standing over it. So a consumer following `Base` +union, an enum — the node it owns is a `Scalar` over it. So a consumer following `Base` must expect a non-scalar and stop there rather than assume a restriction chain; `Constraints` and annotations on such a node bind the position, not the target. `pass/validate` reads composition and discriminator subtyping through exactly this edge. + +A use's bit decides its null. A reference's `Nullable` is the null of the position it sits at, and +a scalar's `Base.Nullable` is what the scalar's own schema admits, an alias's and a restriction's +alike, so a consumer reads whether a use admits null from the reference alone and never from a +`Base` along the chain it names: a use of a scalar whose `Base` admits null excludes null where its +own bit is false. One exception holds: a reference whose chain ends at the top type admits null +whatever its bit, the top type admitting every value +([type graph](./type-graph.md#type-references)). + +No pass and no emitter reads `Base.Nullable` yet. Its one reader is the OpenAPI compiler's fold +(`compilers/openapi/internal/merge`), which keeps the null a conjunction admits +(`git grep -n 'Base\.Nullable' -- ':!*_test.go' ':!docs'` names only that package). An emitter reads +a use's null from its reference, as above. diff --git a/docs/ir/unions.md b/docs/ir/unions.md index e926478ae..993cb9189 100644 --- a/docs/ir/unions.md +++ b/docs/ir/unions.md @@ -67,7 +67,10 @@ validation admits, exactly one variant or one or more. An OpenAPI discriminator is the payload-tagged mode, not a fourth one. The tag property's value names the schema the payload is expected to validate against. A value no mapping names selects none, and OpenAPI says validation should then fail, unless 3.2's `defaultMapping` names one, which -`Discriminator.Default` holds and which also answers for a payload carrying no tag. OpenAPI also +`Discriminator.Default` holds and which also answers for a payload carrying no tag. A value the +source routes that no mapping entry keys, as a component's name beside an entry routing that +component under another, is a route a decoder reads and an encoder never writes +(`DecodeOnlyRoutes`, [models](./models.md#discriminator)). OpenAPI also says the discriminator must not change the validation outcome, but that binds validators, not the wire: what validation admits stays in `Exclusive`, and on an `anyOf` the tag picks one of the several schemas a payload may satisfy. A mode for "tag plus validation" would spell the same wire @@ -79,8 +82,14 @@ OpenAPI asks that the payload hold the property and says only that a schema shou a variant typing it as a number owns the tags whose text is that number's literal ([the tag a variant's value carries](../emitters/refine/unions.md#the-tag-a-variants-value-carries)). So `pass.Validate` holds a union's discriminator to its routes, each naming a variant, and reports -nothing a variant declares of the tag, nor yet a closed variant declaring no such property, which no -tagged payload can be (#1807). A rule refusing a variant that does not declare the tag would +nothing a variant declares of the tag. It warns, `pass/discriminator-variant-refuses-tag`, only at +a variant no payload carrying the tag can be, where the tag is a property inline: the variant's +flattening holds no member of the tag's name, and a model or map of its composition along `Base` +and `Mixins` refuses one by its closure ([catch-alls](./models.md#catch-alls)). A closed model +refuses it; a catch-all writing no pattern refuses it where its key type refuses the tag's name, or +its value type every tag a route names the variant by, which none does where `Default` routes to +it; and a model closed after composition refuses it where nothing its own composition holds, a +catch-all or a union, evaluates it (#1807). A rule refusing a variant that does not declare the tag would refuse OpenAPI's own shape, a `oneOf` of schemas a `discriminator` beside it tags, and warning where one leaves it optional or a number would report documents the compiler lowers as written: on the golden spec (spec @`86556f6f`, morphic @`0cd087ff6`), of the 551 variants of the 145 unions a @@ -105,7 +114,9 @@ keeps both variants, as it keeps every branch, and `pass.Validate` reports the l `pass/exclusive-union-repeated-variant` where the union is exclusive, which then admits less than the source seems to say, and as an info `pass/inclusive-union-redundant-variant` where it is not. Each case has a code of its own, so a consumer selecting findings by code can take the redundant -repeat without the one that narrows what the union admits. +repeat without the one that narrows what the union admits. The two variants share their name +because they share their type, so the names pass leaves the later out of the union's scope rather +than report the pair as a collision ([naming](./naming.md#names-one-scope-shares), #1828). ## Bounds beside a union @@ -127,12 +138,11 @@ bound. Three other homes were weighed. The carrier alone loses the bound for every reference naming the position, the carrier restating the node's writes it twice (#1988), and `Unmodeled` alone leaves a -bound a check reads untyped. An `Enum` and a `Literal` have -no such field: every value a closed one admits is one the source lists, so a bound beside one only -says which of those values it admits, which its members would say themselves. A compiler keeps such -a bound verbatim ([degraded constructs](./boundaries.md#degraded-constructs)), an open enum's too, -though it bounds the values that one does not list (#2004). A union whose variants are such value -sets holds a bound beside it all the same, as it holds every bound written there. +bound a check reads untyped. An `Enum` holds the bounds of its value kind in a field of its own +([enums](./enums.md#bounds)), and a `Literal` holds none: its one value is what the source writes, +so a bound beside it says only whether that value is admitted, and a compiler keeps such a bound +verbatim ([degraded constructs](./boundaries.md#degraded-constructs)). A union whose variants are +such value sets holds a bound beside it all the same, as it holds every bound written there. ## Open unions diff --git a/docs/ir/unmodeled.md b/docs/ir/unmodeled.md index d7f8234de..b45584f56 100644 --- a/docs/ir/unmodeled.md +++ b/docs/ir/unmodeled.md @@ -61,7 +61,7 @@ and no single node addresses it (`openapi:if-then-else`, `openapi:contains`, `op Such an entry's `WrittenBy` names an overlay that wrote every keyword it combines: one that wrote the whole construct is its writer, and one that only added to it leaves it with the document that declares it ([provenance](./provenance.md)). An `openapi:unevaluated` entry may also hold the -keyword that leaves an unevaluated one inert, written just before it +keyword that leaves an unevaluated one saying nothing, written just before it ([boundaries](./boundaries.md#validation-only-constructs)): that is context the entry holds whoever wrote it, so it is not among the keywords `WrittenBy` asks after. @@ -72,7 +72,7 @@ more than one source object, the path between them. `openapi:x-rate-limit` is th node's own object; `openapi:info/contact/x-id` is the contact block's, kept on the document; `openapi:encoding//x-vendor` is one form part's, kept on the content; `openapi:schema/x-a` is a parameter's or a header's schema's, kept on the carrier beside the object's own `openapi:x-a`, and -`openapi:content//x-a` and `openapi:content//schema/x-a` the content entry's it elects and +`openapi:content//x-a` and `openapi:content//schema/x-a` the content entry's it chooses and that entry's schema's, `` its media type as one escaped segment; and `openapi:reference//x-a` is what a Reference Object writes beside its `$ref`, kept on the node its use lowers to, `i` counting the use and then each alias of its chain, beneath @@ -121,11 +121,11 @@ a `$ref` entry a `Model` does not compose keeps its reference's text under `open write alike is one entry, its provenance the position's pointer, as no one writer's is the same in every order of the entries; an entry kept whole is no such writer, as it holds its own. -An entry that belongs to a declaration no node stands for has no carrier to scope it, so it is the +An entry that belongs to a declaration no node represents has no carrier to scope it, so it is the document's, keyed by the declaration's coordinate rather than a scope: `openapi:/components/parameters/P/content/text~1plain`. A coordinate is a pointer, behind a qualifier naming the document where that is not the source, so one pointer in two documents is two keys, and -every use of the declaration reaches one entry. It opens with no keyword, so it meets no scope. +every use of the declaration reaches one entry. It opens with no keyword, so no scope applies to it. ## What a key promises diff --git a/docs/ir/values.md b/docs/ir/values.md index 25d0d017a..fdc6a4ba7 100644 --- a/docs/ir/values.md +++ b/docs/ir/values.md @@ -41,30 +41,146 @@ not accidentally. `constructor` captures values built by named scalar constructo (`utcDateTime.now()`, `plainDate.fromISO("2024-05-06")`) — inherently non-literal, so compilers must not fold them. -`inf`, `neginf` and `nan` are the IEEE 754 values no `BigVal` holds, each a kind of its own with no -payload. A protobuf field may default to `inf`, `-inf` or `nan`, and every target language with an -IEEE float type has a constant for each, so a source stating one is lossless only if the value -channel can too. They are kinds rather than a flag on `number`, so a consumer switching on `Kind` -meets them as kinds it must handle, never as a `number` whose `Number` is empty; a NaN keeps no -payload bits, which no source format states. Keeping the decimal channel finite is still the rule: -`BigVal` stays a JSON number, and `ir.Decimal` never reads one of these. No JSON instance is -non-finite, so no OpenAPI or AsyncAPI document lowers to them. +`infinity`, `negative-infinity` and `nan` are the IEEE 754 values no `BigVal` holds, each a kind of +its own with no payload. A protobuf field may default to `inf`, `-inf` or `nan`, and every target +language with an IEEE float type has a constant for each, so a source stating one is lossless only +if the value channel can too. They are kinds rather than a flag on `number`, so a consumer switching +on `Kind` meets them as kinds it must handle, never as a `number` whose `Number` is empty; a NaN +keeps no payload bits, which no source format states. Keeping the decimal channel finite is still +the rule: `BigVal` stays a JSON number, and `ir.Decimal` never reads one of these. No JSON instance +is non-finite, so no OpenAPI or AsyncAPI document lowers to them. + +## Admission answers + +Whether a type admits a value is answered by one value admission reader +(`ir.ValueAdmissionReader`), in one of three answers (`ir.Admission`): + +- **yes** (`AdmitsYes`): the reader read every fact the IR holds about the type that bears on the + value, and each admits it. A consumer may act on a yes. +- **no** (`AdmitsNo`): a fact the reader read refuses the value, whatever the facts it did not read + say. `pass.Validate` reports a value the reader judges only on a no, and the OpenAPI fold refuses + a default only on one, adopting it on a yes or an unknown. +- **unknown** (`AdmitsUnknown`): no fact read refuses the value, and one the reader does not read + might, such as a `Pattern` outside the subset it reads ([patterns](#patterns)), a `Precision` or a + `Scale`, an entry `Unmodeled` keeps for validation or from a degraded lowering, a type no lookup + finds, a cycle, a value nested past the reader's depth bound, or a fact the source format holds. + Unknown is neither: a consumer acting on a yes or on a no does nothing on an unknown. + +One reader reads each node, alias chain, model composition, union's variants and enum's members once +for its life, so a change to one it has read goes unread. `pass.Validate` asks one for its run, the +document it reads being final. A caller whose types change between calls judges each span of them +through a reader of its own (`ir.ValueAdmissionReader.Fresh`): each fold of the OpenAPI compiler, as +a settlement places members between two folds, and the discriminator route settlement for each +model's table. A variant whose model requires a member an object lacks, and composes no entry +the flattening leaves unflattened, is refused without that model opened, as opening it would refuse +it. Every judgment of one type against one node of a value is counted, and so is each pattern the +reader reads for the first time, and `AdmitsAtPositionWithin` stops at a limit, unknown. + +The same three answers say whether a primitive kind admits a value (`ir.PrimitiveAdmits`, the +one judge of a kind's grammar) and whether a value is a multiple of a `MultipleOf` +(`ir.MultipleOfAdmits`). A kind with no judge answers unknown: `bytes`, whose values an encoding +writes, and a kind ir does not declare. The IEEE 754 kinds (`float32`, `float64`, `float` and +`decimal128`) admit a value of kind `infinity`, `negative-infinity` or `nan`, which no other kind +but `any` admits ([containment](./primitives.md#containment)). Against a type's or a position's +numeric bounds an infinity lies past every limit on its side: `infinity` satisfies every minimum and +exclusive minimum and fails every maximum and exclusive maximum, and `negative-infinity` the +reverse. `nan` is ordered against no limit, so it fails every bound and is admitted only where none +applies. Neither is a multiple of a `MultipleOf` step, no division by one making it an integer, and +beside a `Precision` or a `Scale` a yes is unknown, as it is for a number. + +Two facts are in the terms of the source format the IR was compiled from, which ir holds no grammar +of: an `Encoding` naming a format, and an `Unmodeled` entry kept under `no_ir_home`, a keyword with +no field. The reader asks the source format's reading (`ir.SourceFormatAdmissions`), which the +format's compiler supplies, to judge a value against each, and counts its yes and its no as facts +read. A reader given none, as `pass` builds its own, answers unknown wherever it would have asked: +such a fact is then unread, so it never makes a yes, and a value only it would refuse is not +refused. + +### Patterns + +A `Pattern` is an ECMA-262 regular expression, and a text satisfies it where the expression, written +without flags, finds a match anywhere in it, as ECMA-262's `RegExp.prototype.test` does: `b` admits +`abc` and `^b` refuses it. ir holds no ECMA-262 engine, only the standard library's RE2, which reads +much of the same grammar alike and some of it otherwise. So the reader answers yes or no only for a +pattern in the subset both read alike, which it checks on the pattern's text before Go's regexp +compiles it, and only for a text of characters in the Basic Multilingual Plane, since ECMA-262 reads +a character past it as two code units where Go reads one. Every other pattern, and a text holding +such a character or no UTF-8, is unknown, as is bytes beside any pattern, which bounds them as it +does text ([constraints](./constraints.md#constraints)) but which the reader does not read against +octets. + +The subset is characters, `\` before ASCII punctuation, `\t`, `\n`, `\v`, `\f`, `\r` and `\x` before +two hex digits of either case; classes and ranges; `\d`, `\D`, `\w`, `\W`, `\b` and `\B`; `^` and `$`; +groups, capturing and `(?:…)`; alternation; and `*`, `+`, `?`, `{n}`, `{n,}` and `{n,m}`, greedy or +lazy. Outside it, so unknown: + +- what Go's regexp lacks: lookaround, backreferences and named groups, `\u` escapes, and a `\x` + before anything but two hex digits, `\x{41}` being an `x` repeated 41 times to ECMA-262; +- what the two read otherwise: `.`, which ECMA-262 refuses for `\r`, U+2028 and U+2029 too; `\s` + and `\S`, whose spaces differ; `\a`, a bell to Go and an `a` to ECMA-262, and any escape of + another letter, a digit, a space or a character past ASCII; `[\b]`, a backspace to ECMA-262; `[` + inside a class, which Go reads as opening `[:alpha:]`; an empty class, `[]` matching nothing and + `[^]` anything to ECMA-262, where Go reads the `]` as a member; a range with a class escape at an + end, which ECMA-262 reads as its members and a `-`; and a `{` opening no count, `{01}` being a + count to ECMA-262 and text to Go; +- what one of them refuses: a flag group, a quantifier with nothing to repeat, after another or + after an assertion (`^*` and `\b+` compile in Go), a range out of order, an unbalanced group, a + trailing `\`, a count past 1,000 or a nesting Go's regexp refuses, and a pattern holding a + character past the Basic Multilingual Plane, which a quantifier after it repeats only half of in + ECMA-262. + +Inside the subset the two read alike, including where a reader might expect otherwise: `$` matches +only at the end of the text, never before a final newline; a negated class matches a newline; `\b` +and `\w` read ASCII word characters alone; a `-` first or last in a class, or after a range, is a +member; and a `]` or `}` outside a class is text. Laziness and the empty-iteration check of +ECMA-262's quantifiers change where a match lies, never whether one exists. The reader compiles each +pattern once for its life, and `ir.ConstraintsAdmit`, which holds no reader, once for each call. ## Values held to their type `pass.Validate` reports a default a position's type does not admit, `pass/default-outside-type`, and an example it does not admit, `pass/example-outside-type`, each a warning. They are two codes because a default is written into the code an emitter generates and an example reaches its documentation. The -reading is shallow: the value's kind against the shape of the type, an enum's members, a literal's -value, null where the position is not nullable, whole numbers for an integer, and the bounds the -position declares with those of the alias scalars it reaches. A value that is a reference or a -constructor, a type holding anything, a union, an external type, an unknown type and a position written -in an encoding are not judged. The sites are a property's, a parameter's and a header's default and +reading is an enum's members, a literal's value and null where the position is not nullable, in that +order, and past those the value is judged as the one value admission reader judges it at the position +(`ir.ValueAdmissionReader.AdmitsAtPosition`), against the type and the bounds the position declares +beside it, and reported only where it says no. That reads the value's kind and each primitive's +grammar (a fixed-width integer's range, whole numbers for an integer, a date's, a time's, a `uuid`'s), +the bounds of the type, of the alias scalars it reaches and of the position, `MultipleOf`, +`UniqueItems` and a `Pattern` the reader reads ([patterns](#patterns)) among them, an enum's bounds +over a member it lists, a union by its variants, a `Model` by its composition, a list's elements and +an object's members. These readings stay `pass`'s own, the +reader's being another and which is not yet settled: a value of another kind than bytes or a +string is refused at a `bytes` type, a string there is not measured, a number no `Decimal` holds, +which `irverify` reports, is not judged, and a symbol at a string type is judged as the text it +holds. The reader asks no source format here, +so a value only an entry kept verbatim would refuse is not reported. Nor does it refuse a value a fact +it cannot read may admit: one of another kind than a container or a `Model` a heuristic shaped +(`Provenance.Inferred`), here at the position too; a member a `Model` closed after composition does +not evaluate where a model of its composition keeps an entry it cannot read, which may evaluate it; +and an object an `anyOf` refuses only through members its variants, each closed after composition, +leave unevaluated, which another variant matching it may evaluate. A member a map the composition +names is evaluated, the map judging its value. A value that is a reference or a +constructor, a type holding anything (an alias chain ending at the top type included), an external +type, an unknown type and a position written in an encoding are not judged. The sites are a property's, a parameter's and a header's default and examples, a type's own examples (a null one says the example is absent and is not judged), and in an operation's examples each input parameter against the parameter it names, and the error content -against the error's type. +against the error's type. One run judges its values in at most `maxValueJudgments` judgments: the +value they run out at draws the error `pass/budget-exceeded`, and it and every value after it go +unjudged. + +An enum's members are values its own bounds hold too. `pass.Validate` reports an `Enum` whose +`Constraints` refuse some of its members, `pass/enum-member-outside-bounds`, a warning at the enum +naming each such member and each bound refusing it, as the value admission reader judges the member +against the enum: a member only a `Pattern` outside the subset the reader reads may refuse is not +named, as it answers unknown ([patterns](#patterns)). An enum whose bounds refuse every member holds +no value of its set, one defect of the position, which the compiler that wrote it reports (the +OpenAPI compiler's `openapi/unsatisfiable-schema`), so `pass` draws nothing of it +([enums](./enums.md#bounds)). Nor does an enum whose bounds admit no value of its kind at all, which +draws `pass/bounds-admit-no-value` alone, the bounds being the cause +([constraints](./constraints.md#constraints)). Not judged: a content's and a message's examples, which are in a media type's format, not the type's value (whether a JSON content's are held is #1949); a scenario's `Body` and `Output`, which are one -content and one response, so no single type; a variant's and an enum member's examples; the elements -of a list and the members of an object; and `Pattern`, `MultipleOf`, `Precision` and `Scale`. +content and one response, so no single type; a variant's and an enum member's examples; and +`Precision`, `Scale` and a `Pattern` outside the subset the reader reads. diff --git a/docs/ir/version-history.md b/docs/ir/version-history.md index c147a1264..606f03857 100644 --- a/docs/ir/version-history.md +++ b/docs/ir/version-history.md @@ -81,8 +81,8 @@ it sees. Changes made together in one bump are listed together under it. leaves open, read as closed, and one writing `items: false` was reported as open. That entry is no longer written. A consumer pinned to 0.9.0 finds no `rest` and reads every tuple as closed. - `Tuple` gained `Constraints`, the field `List` already had, so `minItems`, `maxItems` and - `uniqueItems` beside `prefixItems` reach it rather than `Unmodeled`, where a consumer pinned to - 0.9.0 looks for them. + `uniqueItems` beside `prefixItems` land in it rather than `Unmodeled`, where a consumer pinned + to 0.9.0 looks for them. - **0.11.0** — `HTTPBinding` gained `WebhookName`, the OpenAPI `webhooks`-map key that declared a webhook operation, and a webhook binding stopped writing `uriTemplate`. The key names an event, not an RFC 6570 template, so a `{tenant}` in it read as a variable nothing binds. A consumer @@ -216,12 +216,12 @@ it sees. Changes made together in one bump are listed together under it. declares under `idSpaces.auth`, whether or not it mints there. The OpenAPI compiler had dropped such a requirement, so an `Auth` left with no option read as inheriting and one left with others lost the option. It also read a name whose value reads as no list of strings as not written, so - `{name: null}` read as the empty option, and such a name now stands. A `securitySchemes` entry + `{name: null}` read as the empty option, and such a name now holds. A `securitySchemes` entry yielding no mechanism had lowered to nothing, and now lowers to that kind whether or not a requirement names it. A consumer pinned to 0.24.0 finds those operations naming a kind it has no reading for, where it read them as inheriting the service's credentials. - **0.26.0** — `MinItems`, `MaxItems` and a true `UniqueItems` written for one use of a shared - schema reach the `Constraints` of the `Property`, `Parameter` or alias `Scalar` holding that use + schema land in the `Constraints` of the `Property`, `Parameter` or alias `Scalar` holding that use ([annotations](./annotations.md#one-structural-home-per-declaration)), where a position that lowers to a reference had kept them verbatim under `Unmodeled`. No key changed. A consumer pinned to 0.25.0 that reads those entries no longer finds them, and a consumer that reads `ir.Decorated` @@ -331,18 +331,19 @@ it sees. Changes made together in one bump are listed together under it. reading what an `allOf` conjunct writes as the OpenAPI compiler reads it written beside the `allOf` ([`allof-inline-residue`](../compilers/openapi.md#allof-inline-residue), [`allof-refinement`](../compilers/openapi.md#allof-refinement)): - - A `minItems`, `maxItems` or true `uniqueItems` on an inline branch reaches the `Constraints` one - written beside the `allOf` reaches: of the `Property`, `Parameter` or alias `Scalar` holding a - refinement's use of its principal, or of the `List` or `Tuple` the position lowers to. The branch - had been kept whole under `Unmodeled`. A collection bound on a branch beside a type list lands - on its `List` or `Tuple` variant. + - A `minItems`, `maxItems` or true `uniqueItems` on an inline branch lands in the `Constraints` + one written beside the `allOf` lands in: of the `Property`, `Parameter` or alias `Scalar` + holding a refinement's use of its principal, or of the `List` or `Tuple` the position lowers to. + The branch had been kept whole under `Unmodeled`. A collection bound on a branch beside a type + list lands on its `List` or `Tuple` variant. - An `enum` or a `const` beside an `allOf` that refines is one of its conjuncts rather than the - winner of the election of competing keywords, so the `allOf` is no longer kept whole under + one chosen among competing keywords, so the `allOf` is no longer kept whole under `Unmodeled`: its branches fold, a `$ref` it writes lowers, and a narrower branch is what the - position uses. One beside an `allOf` that composes still wins it, and conjuncts sharing no value - there draw the warning a composition's do. A union variant written as such a value set narrowing - a `$ref` takes the hint the `$ref` suggests, as the same conjunction written in its branches - does, where it took `variant_N`, so the symbol an emitter generates from it is renamed. + position uses. One beside an `allOf` that composes is still the one chosen, and conjuncts + sharing no value there draw the warning a composition's do. A union variant written as such a + value set narrowing a `$ref` takes the hint the `$ref` suggests, as the same conjunction written + in its branches does, where it took `variant_N`, so the symbol an emitter generates from it is + renamed. - The `ValueType` of the `Enum` or `Literal` a refinement lowers to reads the type and format every conjunct declares, where it read its own schema's alone, and a branch whose format it holds is no longer kept. @@ -383,9 +384,9 @@ it sees. Changes made together in one bump are listed together under it. `Unmodeled["openapi:allOf/"]` ([`allof-inline-residue`](../compilers/openapi.md#allof-inline-residue)). Where a union distributes ([models](./models.md#composition-beside-a-union)), the branch's docs, deprecation, - examples, secrecy and XML hints reach the `Union`, what a use binds its carriers, and a value - bound each composed variant, and a branch with no residue left is kept on no variant; beside a - union or a `$dynamicRef` kept verbatim they reach the `Model`, as in a composition with neither + examples, secrecy and XML hints go to the `Union`, what a use binds its carriers, and a value + bound each composed variant, and a branch with nothing left to keep is kept on no variant; beside + a union or a `$dynamicRef` kept verbatim they go to the `Model`, as in a composition with neither beside it. A consumer pinned to 0.37.0 that read the branch under that key no longer finds it, and refuses the document as another generation's. - **0.39.0** — no shape change. The OpenAPI compiler lowers four spellings of a union it had kept @@ -528,8 +529,8 @@ it sees. Changes made together in one bump are listed together under it. ([`discriminator-inference`](../compilers/openapi.md#discriminator-inference)): a variant pinning its tag to several strings no other variant admits maps each to it, in a declared discriminator's `Mapping` and in an inferred one; a tag written as a union of string values bounds them as an - `enum` does; and what a schema composes as a union, its variants read as objects in turn, meets - what it declares. A consumer pinned to 0.49.0 that routed a variant a mapping left out by its + `enum` does; and what a schema composes as a union, its variants read as objects in turn, combines + with what it declares. A consumer pinned to 0.49.0 that routed a variant a mapping left out by its type's name finds the route in the `Mapping`, reads unions it read as untagged, or as routed by component names, as routed by the strings their variants pin, and finds no `DiscriminatorValue` on a subtype whose composed union rules its name out. @@ -598,18 +599,18 @@ it sees. Changes made together in one bump are listed together under it. no `Constraints` field, where it wrote `0` or a number the source does not state, and keeps it verbatim under `openapi:` (`degraded_lowering`) on the node or carrier the position owns ([`constraints`](../compilers/openapi.md#constraints)); a count literal that is no non-negative - integer, which the load phase refuses, reaches no field either. An inline `allOf` branch whose + integer, which the load phase refuses, lands in no field either. An inline `allOf` branch whose bound keyword states no value, a 3.0 `exclusiveMinimum` with no bound beside it, one of `false` or one the load phase refuses, parts no other branch, so it folds where nothing else parts it ([`allof-inline-residue`](../compilers/openapi.md#allof-inline-residue)), what it keeps landing under its keyword rather than under `openapi:allOf/`. A field several `allOf` conjuncts declare ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)) now - holds two enums' shared values of the narrower value type, where it kept the first enum of - different value types, and holds what an alias of an enum, a `const`, a `Scalar`, a list, a map - or a tuple meets beside the node it stands for, where it kept the first; an alias adding only - null to a type beside it gives that type. A consumer pinned to 0.54.0 that read such a count's - field finds none there, one reading such a branch under `openapi:allOf/` finds its keywords at - the position instead, and one reading such a field may find a node minted for it. + holds two enums' shared values of the narrower value type, where it took the first enum of + different value types, and holds what an alias of an enum, a `const`, a `Scalar`, a list, a map or + a tuple intersects with the node it names, where it took the first; an alias adding only null to a + type beside it gives that type. A consumer pinned to 0.54.0 that read such a count's field finds + none there, one reading such a branch under `openapi:allOf/` finds its keywords at the position + instead, and one reading such a field may find a node minted for it. - **0.56.0** — three changes of meaning, the shape kept: - A schema admitting `null` and nothing else is a closed `Enum` with no member behind a nullable reference, whatever spells it ([enums](./enums.md#the-empty-enum)). The OpenAPI compiler had @@ -662,16 +663,16 @@ it sees. Changes made together in one bump are listed together under it. [`validation-only`](../compilers/openapi.md#validation-only), [`allof-inline-residue`](../compilers/openapi.md#allof-inline-residue)): - `Model.Additional` is `closed_after_composition` only where no `additionalProperties` is written - beside the `unevaluatedProperties: false`, which would leave it inert. Beside one the model is - `closed` for `false`, and otherwise open with its catch-all, so `{type: object, - additionalProperties: {…}, unevaluatedProperties: false}` is a `MapT`. A consumer pinned to - 0.58.0 read such a model as closed. + beside the `unevaluatedProperties: false`, which would leave it saying nothing. Beside one the + model is `closed` for `false`, and otherwise open with its catch-all, so + `{type: object, additionalProperties: {…}, unevaluatedProperties: false}` is a `MapT`. A + consumer pinned to 0.58.0 read such a model as closed. - A catch-all beside `closed_after_composition` holds its patterns and no `Value`, where it held the top type: a key no pattern matches is allowed only where composition evaluates it. - `openapi:unevaluated` holds an `unevaluatedProperties: false` wherever no model holds it as its - closure, where it was dropped, and holds an inert keyword together with the - `additionalProperties`, `items` or `additionalItems` beside it that leaves it inert. A consumer - pinned to 0.58.0 applying the entry read every keyword in it as live. + closure, where it was dropped, and holds a keyword that says nothing together with the + `additionalProperties`, `items` or `additionalItems` beside it that leaves it saying nothing. A + consumer pinned to 0.58.0 applying the entry read every keyword in it as live. - Neither keyword an inline `allOf` branch writes folds into the position's `openapi:unevaluated` any more: the branch is kept whole under `openapi:allOf/`, as a branch writing `unevaluatedProperties: false` already was. At the position the keyword exempted what the other @@ -712,7 +713,7 @@ it sees. Changes made together in one bump are listed together under it. beside `object` ([`constraints`](../compilers/openapi.md#constraints)). One beside another type is kept verbatim under `openapi:` (`degraded_lowering`), on an alias hoisted where the position lowered to a shared primitive, which then holds the docs its property held, and the - content vocabulary beside a type other than `string` reaches no `Encoding` + content vocabulary beside a type other than `string` is held by no `Encoding` ([`content-vocabulary`](../compilers/openapi.md#content-vocabulary)). A type array's scalar variant holding a bound, an encoding or the content vocabulary is a `Scalar` at `/type/`, each bound and a format the table pairs with one listed type land on @@ -762,7 +763,7 @@ it sees. Changes made together in one bump are listed together under it. names another, through a `$ref`, an `allOf` entry, a `oneOf` or `anyOf`, or an expanded dynamic reference, by the types the position admits, its own and those of every schema it names ([`constraints`](../compilers/openapi.md#constraints)). A value or collection bound none of them - takes, a `minLength` beside a reference to an array say, no longer reaches the `Constraints` of + takes, a `minLength` beside a reference to an array say, no longer lands in the `Constraints` of the alias, carrier, composition or variant holding it, and is kept verbatim under `openapi:` (`degraded_lowering`) instead. No bound that was kept becomes typed. A consumer pinned to 0.65.0 that read such a bound as constraining the reference applied it to @@ -794,7 +795,7 @@ it sees. Changes made together in one bump are listed together under it. ([`pagination-policy`](../compilers/openapi.md#pagination-policy)). `Parameter.Encoding`, a parameter's own encoding, overriding its type's field by field as `Property.Encoding` does ([encodings](./constraints.md#encodings)); the OpenAPI compiler writes `http-date` there on a - header parameter its HTTP-date reading reaches + header parameter its HTTP-date reading applies to ([`http-date-inference`](../compilers/openapi.md#http-date-inference)). `Content.Inferred`, the heuristics that filled a field from a key the content keeps, the marker a promotion from a content records ([promotion](./unmodeled.md#promotion)); the OpenAPI compiler writes for the first time a @@ -810,7 +811,7 @@ it sees. Changes made together in one bump are listed together under it. `OperationGroup.Inferred`, the marker a promotion from a key the group keeps records ([carriers](./unmodeled.md#carriers), [promotion](./unmodeled.md#promotion)). What a parameter's or a header's schema writes is keyed beneath the schema's scope, `openapi:schema/`, or - `openapi:content//schema/` under an elected content entry, where it was unscoped beside the + `openapi:content//schema/` under a chosen content entry, where it was unscoped beside the object's own keys ([keys](./unmodeled.md#keys)). What a Reference Object writes beside its `$ref`, dropped before, is kept on the node its use lowers to under `openapi:reference//`; the `summary` and `description` a content entry's chain writes, kept under @@ -865,7 +866,7 @@ it sees. Changes made together in one bump are listed together under it. the order the source writes them ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). A tie goes to the later declaration, as the flattening's override does, where the fold of two inline - declarations kept the first, and so does each detail and bound two declarations give differently. + declarations took the first, and so does each detail and bound two declarations give differently. A member an entry brings a declaration of is the model's own property, which the flattening takes: one it declares itself keeps that declaration's identity, and one only entries declare, or whose declaration another model holds too, takes one in the `composed` namespace; a name it carries as @@ -896,12 +897,12 @@ it sees. Changes made together in one bump are listed together under it. composition, over an object too: `{allOf: [{$ref: Obj}, {enum: [{a: x}]}]}` is the `Union` of its `Literal`s keeping the `$ref`, where it was a `Model` over `Obj`. One its own keywords leave no value, a `const` outside its `type` say, lowers as - [`competing-keywords`](../compilers/openapi.md#competing-keywords) elects, keeping the `$ref` + [`competing-keywords`](../compilers/openapi.md#competing-keywords) chooses, keeping the `$ref` and the rest, each reported apart. Value sets sharing no member, whose kinds share one that is not an object alone, compose nothing: the keywords beside the `allOf` decide, else the top type - keeps each entry, and a warning names each set by its member count, where an empty `Model` stood + keeps each entry, and a warning names each set by its member count, where an empty `Model` went unreported. - - **An `allOf` electing no entry**, with no keyword beside it naming a kind, is the primitive its + - **An `allOf` choosing no entry**, with no keyword beside it naming a kind, is the primitive its entries admit together, or the `Union` of several where they are strings, numbers or booleans, of value sets the kinds of the members every set holds, and the top type keeping each entry where they admit an object or an array. It was a use of the entry written first, keeping the @@ -910,7 +911,7 @@ it sees. Changes made together in one bump are listed together under it. `anyOf`, a union before words admitting as much, and among conjuncts admitting alike the least text, so an `Enum`'s member order can follow; among `$ref`s none of which is an object, the one within more conjuncts is the use, then the least reference text, the others kept. Two unions of - one keyword, or two conjuncts neither within the other, elect none, and a schema written twice + one keyword, or two conjuncts neither within the other, choose none, and a schema written twice is one conjunct. Each tie went to the first written. - **A `$ref` with keywords beside it** is one conjunction, lowered as the `allOf` of the two ([`ref-use-site`](../compilers/openapi.md#ref-use-site), @@ -986,10 +987,10 @@ it sees. Changes made together in one bump are listed together under it. union kept whole whose branches each declare the kind the keywords speak of, such a schema lowers to that kind, unmarked. - **Type IDs and nodes.** The `Enum`, `Literal` or `Union` of `Literal`s an inline `allOf` entry's - value set lowers to stands at the position's pointer and ID, where it stood at the entry's + value set lowers to sits at the position's pointer and ID, where it sat at the entry's (`…/allOf/`) behind an alias or a carrier. The node an `allOf` of one `$ref` hoisted, the alias a `$ref` with notes on an entry hoisted, and each dead variant with its branch's nodes are - gone; an anonymous `Model` stands where a `$ref` to an object has something beside it. A schema + gone; an anonymous `Model` appears where a `$ref` to an object has something beside it. A schema a reference lands on beneath a nested Encoding Object (OpenAPI 3.2) lowers to a node, where it was never lowered, and a pointer into another document that passes a Reference Object is read on to where that reference's chain ends, where it was unresolved @@ -1008,7 +1009,7 @@ it sees. Changes made together in one bump are listed together under it. ([`allof-inline-residue`](../compilers/openapi.md#allof-inline-residue)). `openapi:$ref`, or `openapi:$ref/` by reference text where a node keeps several, holds the reference's text: a `$ref` the position does not lower from, one a `Model` does not compose, and one naming no - schema, each keyword beside it under its own key. These stood under `openapi:allOf/` or + schema, each keyword beside it under its own key. These were under `openapi:allOf/` or `openapi:allOf` whole, a refinement's as the object `{$ref: …}`, and an unresolved entry's not at all. A `$dynamicRef` an entry writes, naming an anchor, is kept under `openapi:$dynamicRef`. `openapi:nullable` (`out_of_scope`) holds a `nullable` at OpenAPI 3.1 or 3.2 the @@ -1023,9 +1024,9 @@ it sees. Changes made together in one bump are listed together under it. one that lost, saying how many models compose both, where each composing model drew it ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). A member one entry declares as a kind and another as a structure admitting only part of it, a `Model` over a - target bounding that kind say, is such a conflict keeping the loser, where the fold took the - kind and dropped the structure. `openapi/degraded-construct` warns where the conjuncts share no - value and one is a union, or is a `type` beside a `$ref` at OpenAPI 3.0 + target bounding that kind say, is such a conflict keeping the one passed over, where the fold + took the kind and dropped the structure. `openapi/degraded-construct` warns where the conjuncts + share no value and one is a union, or is a `type` beside a `$ref` at OpenAPI 3.0 ([`allof-disjoint-conjuncts`](../compilers/openapi.md#allof-disjoint-conjuncts)), where a union beside a body has a dead branch, and at a schema merging through more than 64 `<<`. An `allOf` beside a value set with an entry no JSON renders keeps each `$ref` by its text, where it drew @@ -1033,10 +1034,10 @@ it sees. Changes made together in one bump are listed together under it. at each `nullable` kept, and an entry kept whole as `validation_only` draws `openapi/validation-only-keyword` where it drew `openapi/degraded-construct`. - **0.71.0** — `Diagnostic.Related` is the one change of shape. The OpenAPI compiler changes where - the node of an inline `allOf` principal stands, what a `oneOf` and an `anyOf` written together - lower to, which nulls conjuncts share, what a schema no instance satisfies lowers to and draws, - and what a node keeps beside an inline principal; a consumer pinned to 0.70.0 refuses the - document. By what a consumer meets: + the node of an inline `allOf` principal sits, what a `oneOf` and an `anyOf` written together lower + to, which nulls conjuncts share, what a schema no instance satisfies lowers to and draws, and what + a node keeps beside an inline principal; a consumer pinned to 0.70.0 refuses the document. By what + a consumer meets: - **`Diagnostic.Related`**, new ([provenance](./provenance.md#related-places)): the other places and nodes a finding concerns, each a `Role` (`kept`, `decided`) and a `Provenance`, left out when empty. A consumer decoding a diagnostic strictly meets a member it does not know, and one @@ -1051,11 +1052,11 @@ it sees. Changes made together in one bump are listed together under it. - **Type IDs move to the position** ([`allof-refinement`](../compilers/openapi.md#allof-refinement)). The node an inline `allOf` entry the position lowers from builds, a `Union`, a `type` list's union, a `List`, a `Tuple` or - a `Scalar`, stands at the position's pointer and ID, as a value set's already did, where it - stood at the entry's (`…/allOf/`) behind an alias or a carrier; its children keep their + a `Scalar`, sits at the position's pointer and ID, as a value set's already did, where it + sat at the entry's (`…/allOf/`) behind an alias or a carrier; its children keep their pointers. A `type` list's variants, which no pointer of the source names, and the nodes beneath - them stand under the position's (`/type/`), where the same keywords written flat - put them, where they stood under the entry's. The node holds the bounds, notes and kept keywords + them sit under the position's (`/type/`), where the same keywords written flat + put them, where they sat under the entry's. The node holds the bounds, notes and kept keywords written beside the `allOf`, which the alias, the property or the parameter held, a wrapper's once: each variant of a `type` list the bounds its type takes, its array variant the collection bounds, and a bound no part of the node reads, a collection bound beside a `oneOf` or an object @@ -1070,7 +1071,7 @@ it sees. Changes made together in one bump are listed together under it. nodes, where each was a `Model` composed over its branch with an `openapi/composition-lowering` info: `{allOf: [{oneOf: [{$ref: X}, {type: 'null'}]}]}` is the nullable reference to `X`, where it was a nullable `Union` of one `Model` composed over `X`. The discriminator keys the compiler - does not read are kept under `openapi:discriminator/`, where they stood under + does not read are kept under `openapi:discriminator/`, where they were under `openapi:allOf//discriminator/`. A union that collapses to a reference keeps no `openapi:oneOf`, and a null branch writing more than null is still kept under `openapi:oneOf/`. @@ -1079,7 +1080,7 @@ it sees. Changes made together in one bump are listed together under it. [`union-beside-structure`](../compilers/openapi.md#union-beside-structure)) lower alike on one schema, beside an `allOf`, on one of its inline entries, one each on two in either order and one `allOf` deeper, so kinds and variants change where they are written on entries. With nothing - beside them they are the `Union` of the one the election picks, keeping the other: `{allOf: + beside them they are the `Union` of the one chosen, keeping the other: `{allOf: [{oneOf: [P, Q]}, {anyOf: [X, Y]}]}` over objects is the `Union` of `P` and `Q` keeping the `anyOf`, where it was a `Union` of composed `Model`s each keeping it, and a `oneOf` of a string and null on one entry beside an `anyOf` of a string on another is a one-variant `Union` keeping @@ -1091,16 +1092,17 @@ it sees. Changes made together in one bump are listed together under it. `Model` keeping both and the `oneOf` beside the body was distributed whatever its branches declared; where neither declares shape, both are kept as validation logic, as before. Shape is judged against the position, and between two union entries of an `allOf` that refines, that - preference elects whatever the kinds of the other entries: beside a string entry, `oneOf: - [{type: object, properties: {x}}, {$ref: S}]` on one entry and `anyOf: [{$ref: S}]` on another - are the `Union` of both `oneOf` branches keeping the `anyOf`, where the position was a use of - the `anyOf`'s entry keeping the `oneOf`. An elected union collapses no more on an entry than on - one schema writing both: `oneOf: [{required: [a]}]` on one entry and `anyOf: [{type: 'null'}, - {$ref: S}]` on another, `S` a string, are a `Union` of `S` behind a nullable reference keeping - the `oneOf`, where they were a `Scalar` keeping both. Neither union is folded into a - refinement's principal: `{allOf: [{type: string}, {oneOf: [{type: string}]}, {anyOf: [{}]}]}` - keeps the `anyOf` as `validation_only`, where nothing kept it. The union passed over is a - conjunct of the rest wherever it is written (below). + preference chooses whatever the kinds of the other entries: beside a string entry, + `oneOf: [{type: object, properties: {x}}, {$ref: S}]` on one entry and `anyOf: [{$ref: S}]` on + another are the `Union` of both `oneOf` branches keeping the `anyOf`, where the position was a + use of the `anyOf`'s entry keeping the `oneOf`. A chosen union collapses no more on an entry + than on one schema writing both: `oneOf: [{required: [a]}]` on one entry and + `anyOf: [{type: 'null'}, {$ref: S}]` on another, `S` a string, are a `Union` of `S` behind a + nullable reference keeping the `oneOf`, where they were a `Scalar` keeping both. Neither union + is folded into a refinement's principal: + `{allOf: [{type: string}, {oneOf: [{type: string}]}, {anyOf: [{}]}]}` keeps the `anyOf` as + `validation_only`, where nothing kept it. The union passed over is a conjunct of the rest + wherever it is written (below). - **Nulls** ([`nullable`](../compilers/openapi.md#nullable), [`union-beside-structure`](../compilers/openapi.md#union-beside-structure)). `TypeRef.Nullable` is false at positions it was true at, and a union branch dropped as dead is a variant: conjuncts @@ -1148,7 +1150,7 @@ it sees. Changes made together in one bump are listed together under it. and beside an `allOf` of the string or on its entries, each is the string keeping both, the two pairs holding a null as `validation_only`, where it was an empty `Model` keeping both and the body's `type`, the `enum` pair the top type keeping them on entries and the `Enum` of `a` beside - the `allOf`. The warning names an entry electing a union of null alone by what it admits, + the `allOf`. The warning names an entry choosing a union of null alone by what it admits, `allOf/1: null`, and its other union apart. With nothing beside them, such a pair draws the warning on the one schema writing both too, where that drew an info alone. Over a `Model`, a union of null alone beside a rest admitting no null shares no kind with it: `{allOf: [T], oneOf: @@ -1163,8 +1165,8 @@ it sees. Changes made together in one bump are listed together under it. of null alone among them, the pair lowers, beside the body, beside its `allOf` or on its entries, to the body's `Model` keeping both, as `degraded_lowering` where one of them declares shape against the body and as validation logic where neither does, where two entries, and such a - pair beside the body, distributed the elected union; beside a body admitting null, where the - union passed over leaves it null alone and no branch of the elected one admits null, the pair + pair beside the body, distributed the chosen union; beside a body admitting null, where the + union passed over leaves it null alone and no branch of the chosen one admits null, the pair lowers so too, with the warning: beside `{type: [object, 'null'], properties: {a: …}}`, `oneOf: [{type: object, properties: {x: …}}]` and `anyOf: [{type: 'null'}]` are the body's `Model` keeping both, where written so, beside an `allOf` of the body and on two entries the `oneOf` was @@ -1191,7 +1193,7 @@ it sees. Changes made together in one bump are listed together under it. under `openapi:` and the principal's under the entry's key, one object holding every such keyword whichever reading of the principal keeps it, each reading naming its own in one report: `{allOf: [{type: string, format: int64, minimum: 1, required: [a]}], minimum: 2, - required: [b]}` holds `openapi:allOf/0: {"minimum": 1, "required": ["a"]}`, where both stood on + required: [b]}` holds `openapi:allOf/0: {"minimum": 1, "required": ["a"]}`, where both were on the entry's node `…/allOf/0`. What the principal's build keeps beside a field it could not fill is held the same way, as `openapi:allOf/0: {"format": "byte"}` beside `openapi:format: "uuid"` for `{allOf: [{type: string, format: byte, contentEncoding: base64url}], format: uuid}`, and so @@ -1203,7 +1205,7 @@ it sees. Changes made together in one bump are listed together under it. writing, kept under the outermost key holding it. Written alike on both, a keyword is one writing whichever reading keeps it, read once, or kept once and reported once: one the principal's census, its build or its bounds on a number carried as text keeps is kept at the - entry's pointer, where it stood on the entry's node and, but the build's, on the position's too; + entry's pointer, where it was on the entry's node and, but the build's, on the position's too; a content keyword the node's `Encoding` holds is read there, where the position kept it too; a `default`, `readOnly`, `writeOnly` or validation-only keyword is kept at the position, where the entry reported it too; and where the position keeps the principal whole the entry holds it @@ -1227,7 +1229,7 @@ it sees. Changes made together in one bump are listed together under it. ([`allof-refinement`](../compilers/openapi.md#allof-refinement)) is that use, where it was a `Model` keeping the `$ref`: an `allOf` whose read passes 256 schemas or 4,096 `enum` members but weighs one `$ref` alone, every other conjunct naming no kind and stating no value set, format or - `items`, is the use of its target it is within those bounds; with a second conjunct the election + `items`, is the use of its target it is within those bounds; with a second conjunct the choice weighs, it still composes. - **0.72.0** — names only: members, ID kinds, ID namespaces and values are spelled out, and nothing means anything it did not. A consumer pinned to 0.71.0 refuses the document; one that read the old @@ -1278,3 +1280,200 @@ it sees. Changes made together in one bump are listed together under it. `Document.Types` (`ir/unreferenced-anonymous-type`, [type-graph](./type-graph.md#reachability-of-anonymous-types)). A consumer pinned to 0.72.0 refuses the document on the new `targets` member. +- **0.74.0** — two members and one role's spelling, and the values and IDs the OpenAPI compiler + writes change with them. A consumer pinned to 0.73.0 refuses a document carrying either member or + the role. Each count is of the 301 + documents compiled from `testdata` (corpus) or of the golden spec (cloudflare/api-schemas + @904c5434, which @fc15c3b6 counts alike), compiled by morphic @4a7a384c9 and @0c457e650 with types + paired by source pointer and kind. By what a consumer does about it: + - **Shape**, to decode: + - `Discriminator.DecodeOnlyRoutes` (`decodeOnlyRoutes`, omitted when empty) maps a wire value to + the type a payload carrying it routes to, for each route the source gives that `Mapping` + leaves out ([models](./models.md#discriminator)). A decoder routes by `Mapping`, then + `DecodeOnlyRoutes`, then recognition, then `Default`; an encoder takes the tag from the + `Mapping` of the discriminator it writes for. + - `Enum.Constraints` (`constraints`, omitted when nil) holds the bounds of the kinds of value + its `ValueType` holds, closed or open ([enums](./enums.md#bounds)). A closed enum's bound can + refuse a member it lists, which is kept and reported by `pass/enum-member-outside-bounds`, a + warning (`{type: string, enum: [a, abcd], maxLength: 3}`). + - `RelatedRole`'s `kept` is spelled `chosen` (`ir.RelatedChosen`), the place whose say a finding + chose over the one it sits at ([provenance](./provenance.md#related-places)), since *kept* + means written verbatim into an Unmodeled entry ([words](./README.md#words)). A consumer + switching on the role reads `chosen` where it read `kept`, and the JSON report moves to + `version` 3 with it ([cli](../cli.md#json-report)). Golden spec: 394 entries; the committed + goldens: 11, in 3 conformance documents. + - **Meaning**, at an unchanged shape: + - A model's discriminator holds its whole route table: `Mapping` the model's own name and each + subtype it routes, `DecodeOnlyRoutes` each other route. `Model.DiscriminatorValue` keeps its + value and routes nothing; it is what an encoder writes only through the discriminator on an + ancestor. An entry routing to neither the model nor a subtype is typed in no map and kept + verbatim under `openapi:discriminator/mapping` (`no_ir_home`; corpus: 4 in 3 documents) + ([models](./models.md#discriminator), + [`discriminator`](../compilers/openapi.md#discriminator)). Golden spec: 245 decode-only routes + under 45 unions. Corpus: 35 under 22 discriminators. + - `Model.Constraints` holds the member counts the model's own schema writes. A reader + intersects them across `Base` and `Mixins` with `ir.PropertyCountBounds` + ([models](./models.md#the-flattening)); no document differs. + - A bound binds only the kind its node's value is. A length or `pattern` beside a value written + as text (an instant, a `uuid`, bytes as base64, a number as its text), or a numeric bound + beside a number written as text or an instant, is kept verbatim `no_ir_home` on the node or + carrier that wrote it ([constraints](./constraints.md#constraints), + [`string-formats`](../compilers/openapi.md#string-formats)). Golden spec: 48 keywords (32 + `maxLength`, 15 `pattern`, 1 `minLength`) are kept so, with 51 `openapi/unhomed-construct`. + `Enum.Constraints` takes the bounds an enum's values hold in place of `openapi:` + entries (corpus 3 enums, golden spec 1). + - A value set beside a `$ref` is bounded by what the `$ref` reaches, along its chain of `$ref`s + and `allOf` entries, as by the same bounds written flat: an `Enum`, or the `Union` of literals + a mixed `enum` lowers to, holds them in `Constraints`, a length beside an instant is kept + verbatim `no_ir_home` on it, and a union of value sets beside the `$ref` leaves out a member + they refuse. The `$ref` stays kept verbatim (`{$ref: T, enum: [a, abcd]}`, `T` being + `{type: string, maxLength: 3}`, holds the length and draws `pass/enum-member-outside-bounds`, + as `{type: string, maxLength: 3, enum: [a, abcd]}` does; corpus and golden spec: none). + - An enum's bounds admitting no value of its kind (`ir.ConstraintsAdmitNoValue`) are the cause + of every member they refuse, and draw `pass/bounds-admit-no-value` alone: neither + `pass/enum-member-outside-bounds` nor the all-refused `openapi/unsatisfiable-schema` + (`{type: string, enum: [abcd], minLength: 5, maxLength: 3}`; corpus and golden spec: none). + - A `pattern` is read: the value admission reader judges a text against one in the subset of + ECMA-262 that Go's regexp reads alike, as a search for a match, yes or no, where it answered + unknown ([values](./values.md#patterns)). A pattern outside the subset, a text holding a + character past the Basic Multilingual Plane and a judgment past the reader's work bound stay + unknown. So `pass` reports a default or an example a pattern refuses, the fold adopts a value + beside a pattern it matches and refuses one it does not, a value set's member a pattern + refuses is left out and reported, and an `Enum` whose pattern refuses every member it lists is + unsatisfiable. Golden spec: of the 1,018 strings written beside a `pattern`, 999 are judged + and 2 refused, both an example `2024-01-15T00:00:00Z` beside `^\d{4}-\d{2}-\d{2}$`. + - A scalar's `Base.Nullable` is what its own schema admits, and a use's null is its reference's + bit alone ([scalars](./scalars.md#aliases)). Golden spec: 30 references gain `inferred: + nullable-inference`, 2 turn nullable and 3 non-nullable. + - A closure or catch-all written beside members it does not declare, a `$ref` target's, an + entry's or a branch's, applies to the members the flattening holds and is kept verbatim under + `openapi:additionalProperties` as `degraded_lowering` to say so + ([models](./models.md#catch-alls), [boundaries](./boundaries.md#degraded-constructs)). Golden + spec: 2; corpus: 4 documents, `allof-inheritance` among them. + - A position that holds nothing hoists no node: a `type` restating its `$ref`'s kind (`allOf: + [{$ref: R}], type: object`) leaves the reference where an anonymous `Model` whose `Base` is + `R` was. Golden spec: 56 such `Model`s are gone, their positions naming `R`; a `$ref` or an + expanded `$dynamicRef` beside keywords no node holds is the target + ([`allof-classification`](../compilers/openapi.md#allof-classification), + [`dynamic-ref`](../compilers/openapi.md#dynamic-ref)). A property a model restates as its + `Base` declares it is no longer repeated, its requiredness moving to `Requires` (golden spec: + one model, 3 properties). + - The kind at an ID follows what the conjunction reads, not the construct written: an `allOf` is + a `Model` only where its kinds are an object alone, and one whose kinds or value sets share no + value is the closed `Enum` or `Model` with no member + ([`allof-refinement`](../compilers/openapi.md#allof-refinement)). Corpus: 14 types change kind + at their ID (`model`->`enum` 2, `union`->`scalar` 2, `scalar`->`model` 3, `list`->`scalar` 2, + `map`->`scalar` 1, `union`->`enum` 1, `scalar`->`union` 1, `model`->`scalar` 1); golden spec: + none. `type/primitive/any` is newly named in 5 corpus documents. + - An unevaluated keyword is typed where every evaluator it applies to is one the IR types: + `unevaluatedItems: false` beside `prefixItems` alone is a closed `Tuple` with no `Rest`, where + `Rest` was the top type and the keyword kept + ([`validation-only`](../compilers/openapi.md#validation-only); corpus `tuples-prefixitems`). + An `items` or `additionalProperties` writing only notes is no `List` or `MapT`, but a `Scalar` + over the top type keeping it (corpus `silent-applicator`, counted above as kind changes). + - `Unmodeled` entries change by key and reason, base to head. Golden spec: `openapi:type` + `degraded_lowering` 9 to 2, `openapi:anyOf` `degraded_lowering` 5 to 13 and `validation_only` + 13 to 12, `openapi:nullable` 2 to 0, `openapi:allOf` 2 to 0, `openapi:schema` `no_ir_home` 20 + to 26. Corpus: `openapi:discriminator` `degraded_lowering` 10 to 7, `openapi:uniqueItems` 2 to + 0, `openapi:anyOf` `validation_only` 5 to 3. + - A `decided` entry the OpenAPI member fold lists in a report's `Related` carries, beside the + member's ID in `Node`, the source and pointer of the model declaring it, which the report's + message names, where it was on `NoSource` ([provenance](./provenance.md#related-places)). + - **ID paths**, to rekey what is keyed by an ID or `Provenance.Pointer` + ([identity](./identity.md#the-id-grammar), [provenance](./provenance.md)); each type's + properties and enum members follow it: + - The fold of a field's declarations mints at `/allOf/properties/`, where it + minted beneath the entry that brought a declaration (`.../allOf/1/properties/result`). Golden + spec: 137 types and 45 properties; corpus: 41 types, 3 properties and 10 enum members + ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). + - A variant a position distributes from the union an inline entry `k` writes sits at + `/allOf/-/k/...`, where it sat at `/allOf/k/...`; `-` names no array + element. Golden spec: 35 types; corpus: 16 (`allof-union-branch`). + - A type list's variant reads its schema where it is written: 9 corpus properties move from + beneath `/type/` to the places the source writes them, and 1 type from + `type/anonymous/.../Vehicle/type/0` to `type/composed/.../Vehicle/oneOf/0` + (`discriminated-union-beside-model`). A split body's object sits at `.../type/-/`, + which a `$ref` cannot name ([`type-arrays`](../compilers/openapi.md#type-arrays)); the + committed corpus holds none, so the witness is `{properties: {a: {type: string}}, minLength: + 3, oneOf: [{type: [object, string]}, {type: integer}]}`, a `Scalar` at 4a7a384c9 and a `Union` + whose first variant holds that object at 97b71d9c1. + - A node minted at a key naming no construct takes the key's path as `Provenance.Pointer`. + Golden spec: 169 `Model`s, 3 `List`s and 45 properties. + - **Codes**, to rekey what is keyed by a diagnostic code. At one pointer: + - `openapi/degraded-construct` becomes `openapi/unsatisfiable-schema` where no instance + satisfies the schema. Golden spec: 13, and 1 where two findings become one; corpus: 15, and 1. + - `openapi/degraded-construct` becomes `openapi/conflicting-redeclaration` where a fold's + declarations disagree (golden spec: 5), and two become one `openapi/composition-lowering` + (corpus: 1). + - `openapi/degraded-construct`, a bound kept beside an enum, becomes + `pass/enum-member-outside-bounds` where the bound refuses a member (golden spec: 1; corpus: + 1). + - `pass/default-outside-type` becomes `openapi/degraded-construct` where a default the fold + refuses is kept at its declaration (corpus: 1). + - `openapi/validation-only-keyword` becomes `openapi/degraded-construct` (corpus: 1). + - `openapi/conflicting-redeclaration` becomes `openapi/degraded-construct` where a fold reported + two types incompatible though only part of one's kind, or nothing it could read, showed it, + and `openapi/degraded-construct` becomes `openapi/conflicting-redeclaration` where an `if` + whose `then` or `else` is `false` admits none of the other's kind + ([`allof-redeclared-property`](../compilers/openapi.md#allof-redeclared-property)). + - An `openapi/degraded-construct` a fold reported for a value it could not judge, beside a + `pattern` or a step past the digits it reads, is gone: the value is adopted. Golden spec: 2, + an `errors` example 14 response types now carry. + - `openapi/degraded-construct` is an info where it was a warning, at 3 corpus pointers + (`allof-inline-residue`, `codeclared-keywords`, `merge-depth-bound`). + - `openapi/unpreservable-construct`, an error, becomes `openapi/degraded-construct`, a warning, + where a construct kept whole holds a vendor extension whose value converts to no JSON: the + construct is kept without the extension, which the warning names at the object holding it, + where 4a7a384c9 kept nothing of the construct, so the compile exits 0 where it exited 1 + ([`vendor-extensions`](../compilers/openapi.md#vendor-extensions)). Probe: `not: {type: + string, x-bad: .nan}` keeps `openapi:not` `{"type":"string"}` at cf8eb74e0 and nothing at + 4a7a384c9. + - `pass/composition-cycle`, a warning, becomes `openapi/cyclic-ref`, an error, at a schema whose + `allOf` names only itself, `A: {allOf: [{$ref: A}]}`: it is a reference cycle, lowered to the + top type, a `Scalar` over `any` where it was a `Model`, so the compile exits 1 where it exited + 0 ([`reference-cycles`](../compilers/openapi.md#reference-cycles)). + - **Codes**, by count, base to head: + - Golden spec: `openapi/conflicting-redeclaration` 20 to 202, `openapi/unsatisfiable-schema` 0 + to 28, `openapi/unhomed-construct` 0 to 51, `openapi/unwidened-nullable` 0 to 2, + `openapi/inferred-nullable` 212 to 222, `pass/enum-member-outside-bounds` 0 to 1, + `pass/default-outside-type` 1 to 34, `pass/example-outside-type` 2,159 to 2,188, + `openapi/degraded-construct` 1,766 to 1,225. + - Corpus: `openapi/unsatisfiable-schema` 0 to 31, `openapi/unhomed-construct` 4 to 17, + `pass/discriminator-unrouted-variant` 0 to 14, `pass/enum-member-outside-bounds` 0 to 1, + `pass/default-outside-type` 3 to 1, `openapi/degraded-construct` 327 to 297. + - `openapi/unsatisfiable-schema`, `openapi/unwidened-nullable` (a warning), + `pass/enum-member-outside-bounds`, `pass/discriminator-unrouted-variant`, + `pass/discriminator-variant-refuses-tag`, `ir/discriminator-route-duplicate` and + `ir/dangling-decided-node` are new codes. The last three draw nowhere in the corpus or the + golden spec, and each is held by its own test; the last two are `irverify` violations, not + findings of a compile. A fold's reports sit at, and name, a place writing what they speak of + and carry the places they decided in `Related` ([provenance](./provenance.md#related-places)). + - `pass/budget-exceeded`, an error, is new too: where a run's defaults and examples take more + than `maxValueJudgments` judgments, the value they run out at draws it, and it and every value + after it go unjudged ([values](./values.md#values-held-to-their-type)). + - `pass/default-outside-type` and `pass/example-outside-type` draw where a `pattern` refuses + the value, `openapi/unsatisfiable-schema` where it refuses every member an `Enum` lists, and + `pass/enum-member-outside-bounds` where it refuses some. Golden spec: 2 examples, the ones + above. + - `pass/bounds-admit-no-value` draws where a model's member counts admit no object across its + composition, as `Many: {allOf: [{$ref: Few}], minProperties: 3}` beside `Few: {type: object, + maxProperties: 1}`, and once, at its least model, where a cycle of models composing one + another does ([constraints](./constraints.md#constraints)). 4a7a384c9 draws neither. + - **Codes**, disappearing: + - `pass/discriminator-missing-variant` for a route to a type that is no variant: corpus 3 to 0, + the route kept verbatim as above. + - `pass/name-collision` between a union's variant and an earlier one naming the same type: the + repeated-variant finding reports the pair ([unions](./unions.md#a-type-listed-twice), + [naming](./naming.md#names-one-scope-shares)). Probe: `oneOf: [{$ref: A}, {$ref: A}, {type: + string}]` draws it at 4a7a384c9 and not at 97b71d9c1. + - **Messages**, to rematch what reads a finding's text: + - A report of the member fold opens with the field and the models holding it, names the two + declarations by place, the chosen one first, and each type as its source writes it, never by + its ID: `field "id" of /components/schemas/Identified: .../allOf/1/properties/id and + .../allOf/0/properties/id disagree: incompatible types string and integer; chose what the + first says; the second is kept verbatim under Unmodeled`, where 4a7a384c9 wrote `declarations + of field "id" disagree: incompatible types type/primitive/string and type/primitive/integer; + kept what the declaration at .../allOf/1/properties/id says over the one at + .../allOf/0/properties/id, which is kept verbatim under Unmodeled`. A report several models + draw is said once, naming them, where it ended `; the same holds at each of N models + composing both` (conformance `allof-conflicting-type`). diff --git a/docs/micro-compiler-design.md b/docs/micro-compiler-design.md index b07788237..7b67f8478 100644 --- a/docs/micro-compiler-design.md +++ b/docs/micro-compiler-design.md @@ -108,7 +108,7 @@ today `example.v1` canonicalizes to `example_v1` from one compiler and `example. and an emitter reading `Canonical` cannot tell which grammar produced it. Nothing caught this: `irverify.checkNaming` tested lowercase-idempotence — the "never cased" half -of invariant 4 — and was silent on the "neutral canonical word sequence" half. Both spellings are +of invariant 4 — and said nothing on the "neutral canonical word sequence" half. Both spellings are lowercase, so both passed. **The grammar and its check landed ahead of this plan** (#161), because the divergence is a live @@ -432,7 +432,7 @@ Those four were not the whole of it. `facets.go` and `schema.go` were mutually d readers `schema.go` declared — the raw-node and JSON-object helpers, the docs, flag, XML and extension readers, and the keyword combinations kept verbatim — had to move as well, along with the site-home constants and the one-hop reference resolution the site model was then built on. What is -left in `resolve.go` is the methods; to see the split as it stands rather than trust this sentence: +left in `resolve.go` is the methods; to see the split as it is rather than trust this sentence: ```bash grep -cE '^func ' compilers/openapi/resolve.go compilers/openapi/internal/annotation/annotation.go @@ -465,7 +465,8 @@ compilers/openapi/ the public face, and nothing else nodeview/ the raw source read the way the resolver reads it ids/ OpenAPI pointer arithmetic and ID derivation value/ value and BigVal lowering - annotation/ the site model and the facet readers (+ constraints, from 3.2) + annotation/ the site model, the facet readers (+ constraints, from 3.2), and the + pending keeps a node holds until it settles (PendingKeeps) merge/ allOf property reconciliation resolve/ reference resolution schema/ schema ⇄ compose (⇄ hoist) — the recursive core @@ -565,7 +566,8 @@ some reordering is expected and each instance must be understood rather than abs it:** what it lowers to, the hint it is named by, where its annotations live (its own node, or the property, parameter or header carrying it) and the depth the schema bound counts from. Whichever path reaches a coordinate first builds the node that role gives it, so `Intern`'s first build -stands for every later one and no answer follows declaration order. Three mechanisms keep it. +is the build every later one takes and no answer follows declaration order. Three mechanisms keep +it. 1. A `$ref` never lowers what it names. It takes the ID the target's pointer derives in the target's document and promises the node (`compile.Types.ReserveNodeAtCoordinate`). The declaration owning @@ -690,7 +692,7 @@ Primitives are excluded from both: `type/primitive/` is shared and derives position. What holds them instead is `ir/primitive-id-not-derived`, which asks the ID to agree with the `PrimitiveKind` it keys rather than with a pointer there is none of — see §3.4. -`irverify` cannot host this as things stand — it is Layer 0 and imports only `ir`, while the grammar +`irverify` cannot host this as things are — it is Layer 0 and imports only `ir`, while the grammar is headed for `compilers/compile`. `internal/harness` is outside the pipeline and can, which is the fallback. The better answer, to be settled when the grammar moves, is whether the ID *shape* belongs in `ir` with compilers choosing only the namespace — in which case `irverify` enforces it for every @@ -703,9 +705,9 @@ permanently, for every consumer of a `Document`, rather than only under test. Injectivity went the other way, to `compile.Types`, because it is not decidable from a finished document: a derivation that collapses two coordinates overwrites one node with the other, and the -survivor is well-formed, carries its own provenance, and satisfies the agreement check the loser is -no longer present to fail. Only the registry that saw both interns can see the collision, and it -refuses the second through the same channel as its other refusals. +survivor is well-formed, carries its own provenance, and satisfies the agreement check the +overwritten node is no longer present to fail. Only the registry that saw both interns can see the +collision, and it refuses the second through the same channel as its other refusals. Both oracles landed before Tier 1, proven against the current code first. diff --git a/docs/parser-library.md b/docs/parser-library.md index 9ce3d0af8..4527fdc9c 100644 --- a/docs/parser-library.md +++ b/docs/parser-library.md @@ -58,7 +58,7 @@ To bump the library: pins in `internal/archtest` name a change to what in the library resolves a reference. 3. For each entry, measure the new behaviour, then rewrite the entry and its pin. Decide what the code it names still needs: a guard against a defect the library fixed can go, and code relying on - a behaviour the library dropped has to change. Settle each other red test where it stands: an + a behaviour the library dropped has to change. Settle each other red test where it lies: an oracle's golden or list of disagreements is regenerated with `-update` once each is read again. 4. Set every entry's **Verified at** to the new version. @@ -567,7 +567,7 @@ two share and none overriding a key the mapping writes itself; the mapping's own source that writes a key twice gives its first copy, where the mapping itself gives its last ([`duplicate-key`](#duplicate-key)). A `<<` naming anything but a mapping or a list of mappings merges nothing, and nothing reports it. A key merges when it is a scalar `<<` the YAML reader tags -`!!merge`, so a quoted `"<<"` and an alias standing for `<<` name an ordinary key. +`!!merge`, so a quoted `"<<"` and an alias for `<<` name an ordinary key. ```yaml x-base: &base {k: {type: string}, z: {type: string}} @@ -649,7 +649,7 @@ components: The parser reads a JSON text with its YAML scanner, which refuses some JSON that RFC 8259 allows and misreads some it does not refuse. It refuses a character outside the Basic Multilingual Plane written as a pair of `\u` escapes, since YAML spells one `\U` and eight digits; a `\/` escape; a key -whose `:` stands more than 1,024 characters past the key's start (a key of more than 1,022 +whose `:` lies more than 1,024 characters past the key's start (a key of more than 1,022 characters written `"key":`); a raw DEL, U+FFFE, U+FFFF or a C1 control other than U+0085 in a string; and a tab before the root value or on a line after the one it ends on. It refuses half of a pair as it refuses a whole one, and every message names no position within the line. It reads a raw @@ -708,10 +708,10 @@ width, and reads back what it wrote by each scalar's style, so the tree is YAML The model decodes a string from a scalar the YAML decoder takes for one: a string, or a number or boolean, as its text. A `!!timestamp`, which any plain date is -([`scalar-resolution`](#scalar-resolution)), a `!!merge`, which a plain `<<` is wherever it stands, -a `!!binary` and a local tag are none of these. A string field so written reads as empty, and a -Reference Object's `$ref` as no reference, its wrapper holding no object, and the model holds no -`summary` or `description` beside it either. The compiler binds reference objects itself, reading +([`scalar-resolution`](#scalar-resolution)), a `!!merge`, which a plain `<<` is wherever it is +written, a `!!binary` and a local tag are none of these. A string field so written reads as empty, +and a Reference Object's `$ref` as no reference, its wrapper holding no object, and the model holds +no `summary` or `description` beside it either. The compiler binds reference objects itself, reading the `$ref` as its text, so the reference is followed all the same. The validator, which the compiler does not call, reports a type mismatch at each; the compiler's table reads any scalar as a string and reports neither. The core keeps the node, and what is written beside it. diff --git a/docs/reference-learnings.md b/docs/reference-learnings.md index 1b5f44ece..a2ec9ae55 100644 --- a/docs/reference-learnings.md +++ b/docs/reference-learnings.md @@ -178,9 +178,9 @@ touches some slice of it: operations: Record}`. **Header-gated pruning**: delete a stale file *only if its content starts with the auto-generated header*, else preserve + report as hand-edited; **skip pruning entirely on first adoption**. Adopt this schema directly, but for the gate: Morphic - prunes a file by the digest its manifest records, since a header cannot stand in a file with no - comment syntax and outlives its owner's edit, and the header gates only the overwrite of a file no - manifest lists ([write / + prunes a file by the digest its manifest records, since a header cannot be written in a file with + no comment syntax and outlives its owner's edit, and the header gates only the overwrite of a file + no manifest lists ([write / integrate](./emitters/write-integrate.md#a-file-is-judged-by-its-digest)). Morphic's other improvement (already specced): key the entity→symbol map by **IR stable ID**, not oagen's `"METHOD /path"` string, so it survives a rename of anything the ID is not built from, and record @@ -207,7 +207,7 @@ touches some slice of it: - **Barrel/re-export file** (`__init__.py`/`mod.rs`/`index.ts`) is a recurring explicit artifact. - Tree-sitter-per-language merge (oagen) silently no-ops on missing grammar — Morphic (Go) must decide deliberately: bundle grammars, shell to the target toolchain, or whole-file overwrite — and make the - fallback **explicit, not silent**. + fallback **explicit, not unreported**. TypeSpec adds the emit-layout primitive: model output as a **scope tree** (source-file → namespace → declarations) with per-file `imports`, resolve cross-file refs by common-ancestor diff @@ -530,7 +530,7 @@ losing the base/mixin composition entirely. - **ogen** — AND-merges allOf **sibling** keywords when composition co-occurs (`hasSiblingConstraints`: "allOf with sibling keywords must be AND-merged"), and collects oneOf as sum variants; genuinely complex allOf+oneOf combinations it can't reconcile hit `ErrNotImplemented` rather than silently - dropping — a hard stop, not silent loss. + dropping — a hard stop, not a loss that reports nothing. **Fix for Morphic (lossless, per [models](./ir/models.md)/[unions](./ir/unions.md)):** when allOf and oneOf/anyOf co-occur, the compiler must process **both** — never return early on the diff --git a/emitters/manifest/pending_test.go b/emitters/manifest/pending_test.go index 05ac4f73f..c9d7e7314 100644 --- a/emitters/manifest/pending_test.go +++ b/emitters/manifest/pending_test.go @@ -104,8 +104,9 @@ func TestPending_RoundTrips(t *testing.T) { { // A pending manifest holds each temporary file's name "with those // any earlier pending manifest records", while a later generation - // may hold .a1 as a file of its own (docs/emitters/write-integrate.md, - // apply step 2), so a temporary file that is a known path stands. + // may hold .a1 as a file of its own + // (docs/emitters/write-integrate.md, apply step 2), so a temporary + // file that is a known path is admitted. name: "admits a temporary file that is a known path", input: manifest.Pending{ Schema: manifest.Schema, diff --git a/engine/cache_test.go b/engine/cache_test.go index bb34cdd10..c7fbe1677 100644 --- a/engine/cache_test.go +++ b/engine/cache_test.go @@ -168,7 +168,7 @@ var sameRun = cmp.Options{ func assertSameRun(t *testing.T, want, got *engine.Result) { t.Helper() if diff := cmp.Diff(want, got, sameRun); diff != "" { - t.Errorf("a hit differs from the compile it stands for (-compiled +cached):\n%s", diff) + t.Errorf("a hit differs from the compile it holds (-compiled +cached):\n%s", diff) } } diff --git a/engine/engine_document_test.go b/engine/engine_document_test.go index 9496e5c62..2ff2d1073 100644 --- a/engine/engine_document_test.go +++ b/engine/engine_document_test.go @@ -48,10 +48,10 @@ func roundTrip(t *testing.T, doc *ir.Document) *ir.Document { } // TestEngine_RunDocumentRunsThePasses pins that a document already compiled -// goes through the passes as a compiled one does: the validate pass reports -// its dangling reference, the document's own findings come first, and its -// sources stand as the table the findings index. No compiler ran, so the -// Result names no format. +// goes through the passes as a compiled one does: the validate pass reports its +// dangling reference, the document's own findings come first, and its sources +// are the table the findings index. No compiler ran, so the Result names no +// format. func TestEngine_RunDocumentRunsThePasses(t *testing.T) { t.Parallel() eng, err := engine.New() diff --git a/engine/engine_spec_test.go b/engine/engine_spec_test.go index 55ef6ee0c..2217f5e94 100644 --- a/engine/engine_spec_test.go +++ b/engine/engine_spec_test.go @@ -94,9 +94,9 @@ func TestEngine_RunSpecCompilesTheHeldBytesBesideFilesOnDisk(t *testing.T) { } // TestEngine_RunSpecServesTheHeldSpecWhereverItsPathIsRead pins that the held -// bytes stand for the file through the whole run: a compiler reading the -// spec's path again is served them, and so is a setting naming that path, dot -// segments or none, while a setting naming another file reads it from disk. +// bytes name the file through the whole run: a compiler reading the spec's path +// again is served them, and so is a setting naming that path, dot segments or +// none, while a setting naming another file reads it from disk. func TestEngine_RunSpecServesTheHeldSpecWhereverItsPathIsRead(t *testing.T) { t.Parallel() eng, err := engine.New(engine.WithCompilers(rereadCompiler{})) @@ -125,10 +125,10 @@ func TestEngine_RunSpecServesTheHeldSpecWhereverItsPathIsRead(t *testing.T) { } } -// TestEngine_RunSpecNamesTheHeldSpecLexically pins that the held bytes stand -// for spec.Path as it is spelt, as reader.Memory names a document: another -// spelling of the same file, here the path a symbolic link leads to, names -// another document, which is read from disk. +// TestEngine_RunSpecNamesTheHeldSpecLexically pins that the held bytes name +// spec.Path as it is spelt, as reader.Memory names a document: another spelling +// of the same file, here the path a symbolic link leads to, names another +// document, which is read from disk. func TestEngine_RunSpecNamesTheHeldSpecLexically(t *testing.T) { t.Parallel() spec := writeNamed(t, "spec.yaml", "on disk") diff --git a/engine/engine_test.go b/engine/engine_test.go index 72de27a3a..e76f0fa79 100644 --- a/engine/engine_test.go +++ b/engine/engine_test.go @@ -391,8 +391,8 @@ func TestEngine_RunCompileError(t *testing.T) { // reporting what reported holds — a legal outcome that must skip the validate // pass and surface a nil Document. // -// It is not a stand-in for a compiler whose two diagnostic channels disagree: -// a nil Document short-circuits the validate step entirely, so this stub never +// It is no substitute for a compiler whose two diagnostic channels disagree: a +// nil Document short-circuits the validate step entirely, so this stub never // reaches the code that folds the two together. splitDiagCompiler is what // covers that. type nilDocCompiler struct { @@ -522,8 +522,8 @@ func hasDiagCode(diags []ir.Diagnostic, code string) bool { func TestEngine_ValidateRuns(t *testing.T) { t.Parallel() // A stub compiler yields a Document with a dangling type ref. The validate - // pass must surface it when enabled and stay silent when skipped — so removing - // the pass.Validate call from Run would break this test. + // pass must surface it when enabled and report nothing when skipped — so + // removing the pass.Validate call from Run would break this test. eng, err := engine.New(engine.WithCompilers(danglingCompiler{})) require.NoError(t, err) path := writeSpec(t, testspec.Tiny) @@ -562,9 +562,9 @@ func (*smithyCompiler) Detect(_ context.Context, src compilers.Source, _ compile }, nil, true } -// smithyParse stands in for what a compiler parses while recognizing a source. -// Its only job is to be a type of this compiler's own, so a test can assert -// that it reaches this compiler's Compile and no other's. +// smithyParse takes the place of what a compiler parses while recognizing a +// source. Its only job is to be a type of this compiler's own, so a test can +// assert that it reaches this compiler's Compile and no other's. type smithyParse struct{} func (s *smithyCompiler) DecodeOptions(set compilers.OptionSet) (any, error) { diff --git a/engine/reader/disk_test.go b/engine/reader/disk_test.go index f76c51787..28a14e443 100644 --- a/engine/reader/disk_test.go +++ b/engine/reader/disk_test.go @@ -4,6 +4,7 @@ package reader_test import ( + "cmp" "context" "errors" "fmt" @@ -280,7 +281,7 @@ func TestDisk_ReadDocumentHTTP(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() srv, hits := countingServer(t, tc.handler) - location := cmpOr(tc.location, "{srv}/doc.yaml") + location := cmp.Or(tc.location, "{srv}/doc.yaml") got, err := reader.Disk{}.ReadDocument(t.Context(), compilers.DocumentRequest{Location: expander("", srv.URL)(location)}) @@ -299,14 +300,6 @@ func TestDisk_ReadDocumentHTTP(t *testing.T) { } } -// cmpOr returns s, or fallback where s is empty. -func cmpOr(s, fallback string) string { - if s == "" { - return fallback - } - return s -} - // TestDisk_ReadDocumentHoldsTheLimit pins the size limit for every kind of // location a Disk reads: exactly the limit is read, one byte more fails with // ErrDocumentTooLarge, and zero, a negative limit and math.MaxInt read the diff --git a/engine/reader/layered_test.go b/engine/reader/layered_test.go index 1689ba518..e83369c36 100644 --- a/engine/reader/layered_test.go +++ b/engine/reader/layered_test.go @@ -17,8 +17,9 @@ import ( "github.com/dexpace/morphic/engine/reader" ) -// recordingReader answers every request with "under" and records it, standing -// for the reader beneath a Layered. Each test reads through its own, in turn. +// recordingReader answers every request with "under" and records it, taking the +// place of the reader beneath a Layered. Each test reads through its own, in +// turn. type recordingReader struct { reqs []compilers.DocumentRequest } diff --git a/engine/reader/netguard_internal_test.go b/engine/reader/netguard_internal_test.go index 29834378f..b99b84b9f 100644 --- a/engine/reader/netguard_internal_test.go +++ b/engine/reader/netguard_internal_test.go @@ -67,9 +67,9 @@ func (p *probeServer) port(t *testing.T) uint16 { return ap.Port() } -// placing is a classifier standing the given ports for the given spaces, as -// two ports of 127.0.0.1 cannot differ in space by themselves; any other -// address is public. +// placing is a classifier giving the given ports the given spaces, as two ports +// of 127.0.0.1 cannot differ in space by themselves; any other address is +// public. func placing(spaces map[uint16]compilers.AddressSpace) func(netip.AddrPort) compilers.AddressSpace { return func(ap netip.AddrPort) compilers.AddressSpace { if addressSpace, ok := spaces[ap.Port()]; ok { diff --git a/engine/report/diagnostics_test.go b/engine/report/diagnostics_test.go index 51192caa4..ebf0a4e1d 100644 --- a/engine/report/diagnostics_test.go +++ b/engine/report/diagnostics_test.go @@ -178,10 +178,10 @@ func TestWriteText_NamesTheWriterBesideTheSource(t *testing.T) { } } -// TestWriteText_WritesOneLinePerDiagnosticInOrder pins the line's fields -// and their order, severity then code then location then message, over -// diagnostics of different severities. A message holding format verbs is -// written as it stands, never read as a format. +// TestWriteText_WritesOneLinePerDiagnosticInOrder pins the line's fields and +// their order, severity then code then location then message, over diagnostics +// of different severities. A message holding format verbs is written as it is, +// never read as a format. func TestWriteText_WritesOneLinePerDiagnosticInOrder(t *testing.T) { t.Parallel() sources := []ir.SourceInfo{{Path: "spec.yaml"}} diff --git a/engine/report/explain.go b/engine/report/explain.go index f213c1eba..e0eba80e6 100644 --- a/engine/report/explain.go +++ b/engine/report/explain.go @@ -37,8 +37,8 @@ type Explanation struct { // Diagnostics holds the diagnostics stamped at Pointer, in reported order. Diagnostics []ir.Diagnostic `json:"diagnostics,omitempty"` // Unmodeled holds the Unmodeled entries written at or beneath Pointer, in - // pointer and then key order, and an entry kept on several nodes in the - // order the document holds them. + // pointer and then key order, and an Unmodeled entry kept on several nodes + // in the order the document holds them. Unmodeled []Kept `json:"unmodeled,omitempty"` // Truncated reports that the document nests past ir.MaxWalkDepth, so // Unmodeled can lack an entry held deeper. diff --git a/engine/report/explain_test.go b/engine/report/explain_test.go index d66359578..963f3876f 100644 --- a/engine/report/explain_test.go +++ b/engine/report/explain_test.go @@ -536,13 +536,13 @@ func kept(key string, source int, pointer jsontext.Pointer) ir.Unmodeled { Provenance: ir.Provenance{Source: source, Pointer: pointer}}} } -// TestExplain_ListsWhatIsKeptAtAndBelow is the table over the Unmodeled -// entries an explanation lists: those written at the coordinate or beneath a -// pointer token of it, on whatever node holds them, the document's own and an +// TestExplain_ListsWhatIsKeptAtAndBelow is the table over the Unmodeled entries +// an explanation lists: those written at the coordinate or beneath a pointer +// token of it, on whatever node holds them, the document's own and an // operation's among them, and none written beside it under a shared prefix of // text, or in another document. Entries at one pointer list by key, and one -// entry kept on several nodes, as a path item's on each operation, in the -// order the document holds them, the eleventh operation after the tenth. +// Unmodeled entry kept on several nodes, as a path item's on each operation, in +// the order the document holds them, the eleventh operation after the tenth. func TestExplain_ListsWhatIsKeptAtAndBelow(t *testing.T) { t.Parallel() const pet = jsontext.Pointer("/components/schemas/Pet") diff --git a/engine/report/json.go b/engine/report/json.go index 319d498e0..34d72a50a 100644 --- a/engine/report/json.go +++ b/engine/report/json.go @@ -12,7 +12,7 @@ import ( // SchemaVersion numbers the shape of the report WriteJSON writes. It moves // with any change to that shape, a field of a finding's diagnostic included, // so a consumer reading the version knows every member it will meet. -const SchemaVersion = 2 +const SchemaVersion = 3 // versioned is the report WriteJSON encodes: r's members after the version. type versioned struct { diff --git a/engine/report/json_test.go b/engine/report/json_test.go index b9833378e..670d359eb 100644 --- a/engine/report/json_test.go +++ b/engine/report/json_test.go @@ -35,6 +35,7 @@ type schema struct { var schemas = []schema{ {version: 1, shape: "1de2889715ac89ffec00b148cadd3ec6970c254c3d846018328ce5a50166903a"}, {version: 2, shape: "e35f5c68b09abec85416e398a2c766d9a215c808751d42f929a0605d0e2cf75d"}, + {version: 3, shape: "fd8b04f9e57b2c19769ae256d6df5ca78b9bbb35a447d5979132716e38926d25"}, } // schemaGolden holds the description of the newest row's shape, so a change @@ -124,7 +125,7 @@ func TestWriteJSON_WritesTheReportAsData(t *testing.T) { assert.Contains(t, out, `{"diagnostic":{"severity":"error","code":"openapi/x","message":"esc \u001b[31m",`+ `"provenance":{"source":0,"pointer":"/b"}},"severity":"warning","rule":{"code":"openapi/x","severity":"warning","reason":"rated"}}`) assert.Contains(t, out, `"accepted":true`) - assert.True(t, strings.HasPrefix(out, `{"version":2,"failed":true,`), "%s", out) + assert.True(t, strings.HasPrefix(out, `{"version":3,"failed":true,`), "%s", out) } // TestWriteJSON_WritesEveryListWhenEmpty pins an empty report's lists as empty @@ -133,7 +134,7 @@ func TestWriteJSON_WritesEveryListWhenEmpty(t *testing.T) { t.Parallel() var w strings.Builder require.NoError(t, report.WriteJSON(&w, report.Report{})) - assert.Equal(t, `{"version":2,"failed":false,"sources":[],"findings":[],"unusedRules":[],"warnings":[]}`+"\n", w.String()) + assert.Equal(t, `{"version":3,"failed":false,"sources":[],"findings":[],"unusedRules":[],"warnings":[]}`+"\n", w.String()) } // TestWriteJSON_RefusesWhatJSONCannotCarry pins a string that is not UTF-8 as diff --git a/engine/report/testdata/schema.golden.txt b/engine/report/testdata/schema.golden.txt index ad01431d3..1f98f8d42 100644 --- a/engine/report/testdata/schema.golden.txt +++ b/engine/report/testdata/schema.golden.txt @@ -49,8 +49,8 @@ type github.com/dexpace/morphic/ir.Related struct "role" github.com/dexpace/morphic/ir.RelatedRole type github.com/dexpace/morphic/ir.RelatedRole string + const "chosen" const "decided" - const "kept" type github.com/dexpace/morphic/ir.Severity string const "error" diff --git a/engine/verify_test.go b/engine/verify_test.go index 6085b65a2..74e90795d 100644 --- a/engine/verify_test.go +++ b/engine/verify_test.go @@ -95,10 +95,11 @@ var brokenDocuments = []struct { name string breakIt func(*ir.Document) codes []string - // silent is whether the validate pass says nothing of the break. It says - // nothing of a duplicate ID or a cased name, and remarks on a mismatched key - // only as a consequence: a reference to the node's own ID resolves to nothing. - silent bool + // reportsNothing is whether the validate pass says nothing of the break. It + // says nothing of a duplicate ID or a cased name, and remarks on a + // mismatched key only as a consequence: a reference to the node's own ID + // resolves to nothing. + reportsNothing bool }{ {"a duplicate operation ID", func(document *ir.Document) { group := &document.Services[0].Groups[0] @@ -128,7 +129,7 @@ func TestEngine_RunLeavesStructuralBreachesToVerify(t *testing.T) { res, err := via.run(t, eng, engine.RunOptions{}) require.NoError(t, err, "no verification is asked for") require.NotNil(t, res.Document) - if tt.silent { + if tt.reportsNothing { assert.Empty(t, res.Diagnostics, "and validate has nothing to say of it") } diff --git a/internal/archtest/arch_test.go b/internal/archtest/arch_test.go index 800522e00..4bc571f1f 100644 --- a/internal/archtest/arch_test.go +++ b/internal/archtest/arch_test.go @@ -50,9 +50,18 @@ var rules = map[string][]string{ // The path fold and a portable segment, which name no morphic concept, so // it sits beside barrier and below the engine, naming and the manifest, // which compare by it. - "pathfold": {"golang.org/x/text/cases", "golang.org/x/text/unicode/norm"}, - "ir": {}, - "ir/irfacts": {module + "/ir"}, + "pathfold": {"golang.org/x/text/cases", "golang.org/x/text/unicode/norm"}, + // Tarjan's search for the strongly connected components of a directed + // graph, which names no morphic concept, so ir and every package above it + // that condenses a graph share one copy of it from below ir. + "stronglyconnected": {}, + // The RFC 3339 time and date-time texts, read by their grammar, which name + // no morphic concept, so ir's time primitives and the compiler's time + // format share one reading of them from below ir. + "rfc3339": {}, + // The IR reaches the standard library and the two packages below it alone. + "ir": {module + "/rfc3339", module + "/stronglyconnected"}, + "ir/irfacts": {module + "/ir", module + "/stronglyconnected"}, "ir/irtest": {module + "/ir", "github.com/google/go-cmp" + subtreeSuffix}, "ir/irverify": {module + "/ir", module + "/scratchstate"}, "compilers": {module + "/barrier", module + "/ir"}, @@ -93,12 +102,11 @@ var rules = map[string][]string{ // literal means. "compilers/openapi/internal/value": {module + "/ir", module + "/compilers/openapi/internal/nodeview", "go.yaml.in/yaml/v3"}, - // The compiler's RFC 9535 query evaluator, over the value a tree stands - // for. It reaches nodeview for a mapping's members as the parser reads - // them, value for a scalar's reading, ir for the decimal a number compares - // by, budget for the steps a query spends and yaml for the tree, and - // nothing that reports or lowers: a query selects, and its caller says - // what that means. + // The compiler's RFC 9535 query evaluator, over the value a tree names. It + // reaches nodeview for a mapping's members as the parser reads them, value + // for a scalar's reading, ir for the decimal a number compares by, budget + // for the steps a query spends and yaml for the tree, and nothing that + // reports or lowers: a query selects, and its caller says what that means. "compilers/openapi/internal/jsonpath": {module + "/ir", module + "/compilers/openapi/internal/budget", module + "/compilers/openapi/internal/nodeview", @@ -112,12 +120,14 @@ var rules = map[string][]string{ // The OpenAPI Specification's rules as data, and the engine that checks a // source tree against them at the minor it declares. It reads the tree // through nodeview, reports through diag, counts its work through budget, - // judges a bound's decimal as the lowering reads it through value, and - // reaches nothing that loads or lowers: the table is the compiler's own + // judges a bound's decimal as the lowering reads it through value, orders + // pointers as a document writes them through provenance, and reaches + // nothing that loads or lowers: the table is the compiler's own // authority on the specification, so it depends on no parser library. "compilers/openapi/internal/specrules": {module + "/ir", module + "/compilers/openapi/internal/budget", module + "/compilers/openapi/internal/diag", module + "/compilers/openapi/internal/nodeview", + module + "/compilers/openapi/internal/provenance", module + "/compilers/openapi/internal/value", "go.yaml.in/yaml/v3"}, // The one reading of a $ref fragment, and the spelling the resolver is handed // for it (GitHub #911). It reaches the library's reference type for the @@ -137,12 +147,12 @@ var rules = map[string][]string{ // into a table over the decoded trees, never through the library's resolver // (GitHub #558). It reads a tree through nodeview, a fragment through // fragment and each object's fields off specrules' rule table, counts its - // work through budget, and reaches nothing of the library's model or of - // what loads or lowers. + // work through budget, condenses a loop of links through stronglyconnected, + // and reaches nothing of the library's model or of what loads or lowers. "compilers/openapi/internal/reftable": {module + "/compilers/openapi/internal/budget", - module + "/compilers/openapi/internal/fragment", + module + "/compilers/openapi/internal/fragment", module + "/compilers/openapi/internal/provenance", module + "/compilers/openapi/internal/nodeview", module + "/compilers/openapi/internal/specrules", - "go.yaml.in/yaml/v3"}, + module + "/stronglyconnected", "go.yaml.in/yaml/v3"}, // The typed side of a reftable.ReferenceTargetTable: each schema of the // parsed model known by the position it was read at, located through the // library's walk, and one the library's decoder builds from raw YAML where @@ -220,9 +230,8 @@ var rules = map[string][]string{ // The rows each schema of a compile is read with, by where it is, by its // node and by its document: one table the load phase fills and every reader // asks. It reaches reftable for where a schema is and the roots naming a - // dialect, nodeview for the node an alias stands for, specrules for the - // rows, and yaml for the trees a root governs, and nothing that judges or - // lowers. + // dialect, nodeview for the node an alias names, specrules for the rows, + // and yaml for the trees a root governs, and nothing that judges or lowers. "compilers/openapi/internal/dialect": {module + "/compilers/openapi/internal/reftable", module + "/compilers/openapi/internal/nodeview", module + "/compilers/openapi/internal/specrules", "go.yaml.in/yaml/v3"}, @@ -314,8 +323,9 @@ var rules = map[string][]string{ // allOf property reconciliation. It reaches annotation for the one field a // redeclaration unions rather than intersects, budget for the model pairs a // judgment compares, diag for what a fold reports, ids for the identity a - // field takes of its own, provenance to place what it reports, and - // typeformat for how two primitive kinds relate. The registry and the walk + // field takes of its own, provenance to place what it reports, typeformat + // for how two primitive kinds relate, and rfc3339 for the time format's + // text, which no primitive kind holds. The registry and the walk // that declared the field reach it as values, which is what keeps the // conflict lattice drivable without a walk. "compilers/openapi/internal/merge": {module + "/ir", @@ -324,13 +334,13 @@ var rules = map[string][]string{ module + "/compilers/openapi/internal/diag", module + "/compilers/openapi/internal/ids", module + "/compilers/openapi/internal/provenance", - module + "/compilers/openapi/internal/typeformat"}, + module + "/compilers/openapi/internal/typeformat", module + "/rfc3339"}, // The table that maps a (type, format) pair to a primitive kind, and the // relation between two kinds that table and ir's value domains give. It is its // own package because merge reads the relation and may not import schema, // whose walk reads the table, and the table is no part of merge's fold. It - // reaches ir alone. - "compilers/openapi/internal/typeformat": {module + "/ir"}, + // reaches ir, and specrules for the kinds each keyword's slot applies to. + "compilers/openapi/internal/typeformat": {module + "/ir", module + "/compilers/openapi/internal/specrules"}, // The vendor-extension promotion policy: which extension fills which typed // field. It reads what a node keeps in Unmodeled, never the source, so it // reaches diag for what it reports and ids for the scope a key is kept under, @@ -431,11 +441,10 @@ var rules = map[string][]string{ module + "/compilers/openapi/internal/diag", module + "/compilers/openapi/internal/promotion", module + "/compilers/openapi/internal/compileddoc"}, - // A compiled document as the steps after the walks read it: its - // operations listed, and its members, parameters and headers indexed. It - // reaches ir alone, so it holds only what the document states, behind an - // IR ID: never a step's verdict, a policy, a source's context or the - // document itself. + // A compiled document as the steps after the walks read it: its operations + // listed, and its members, parameters and headers indexed. It reaches ir + // alone, so it holds only what the document states, behind an IR ID: never + // a step's answer, a policy, a source's context or the document itself. "compilers/openapi/internal/compileddoc": {module + "/ir"}, // What a runtime expression names in a compiled service: its grammar, and // the body members it resolves to. It is its own package because the link @@ -485,11 +494,12 @@ var rules = map[string][]string{ // The schema walk, and everything that recurses with it: composition, // reference following, and the preservation that hangs off both. It is one // package because they are one cycle (micro-compiler-design §5), and it + // condenses the graphs it settles through stronglyconnected. It // reaches every part of the compiler below it — but nothing above: an import // of the compiler package from here is the cycle the extraction removed. It // reads each schema from its statement and imports none of the library's // schema model, which modelHolders holds it to by type. - "compilers/openapi/internal/schema": {module + "/ir", module + "/compilers/compile", + "compilers/openapi/internal/schema": {module + "/ir", module + "/ir/irfacts", module + "/compilers/compile", module + "/compilers/openapi/internal/annotation", module + "/compilers/openapi/internal/reftable", module + "/compilers/openapi/internal/reftable/typed", @@ -505,7 +515,7 @@ var rules = map[string][]string{ module + "/compilers/openapi/internal/componentlookup", module + "/compilers/openapi/internal/typeformat", module + "/compilers/openapi/internal/statement", - module + "/compilers/openapi/internal/value", "go.yaml.in/yaml/v3"}, + module + "/compilers/openapi/internal/value", module + "/stronglyconnected", "go.yaml.in/yaml/v3"}, // The operation walk: path items, webhooks and callbacks, the parameters // merged onto them, and the content of every body, response and header. It // reaches the schema walk for the positions it hoists, auth for the @@ -537,12 +547,14 @@ var rules = map[string][]string{ // What a document says about itself: its info, and what the objects around // it write that lowers to no node of its own. It runs after both walks and // reaches neither: the compiler hands it the context and assigns what it - // returns onto the Document. + // returns onto the Document. It asks schema only to keep whole each + // discriminator within a component it keeps verbatim. "compilers/openapi/internal/document": {module + "/ir", module + "/compilers/openapi/internal/annotation", module + "/compilers/openapi/internal/diag", module + "/compilers/openapi/internal/ids", module + "/compilers/openapi/internal/nodeview", + module + "/compilers/openapi/internal/schema", module + "/compilers/openapi/internal/service", "github.com/speakeasy-api/openapi/extensions", "github.com/speakeasy-api/openapi/openapi"}, @@ -565,6 +577,7 @@ var rules = map[string][]string{ "github.com/speakeasy-api/openapi/marshaller", "github.com/speakeasy-api/openapi/openapi", "github.com/speakeasy-api/openapi/references", + "github.com/google/go-cmp" + subtreeSuffix, "github.com/speakeasy-api/openapi/sequencedmap", "github.com/stretchr/testify/assert", "github.com/stretchr/testify/require", "go.yaml.in/yaml/v3"}, @@ -616,7 +629,7 @@ var rules = map[string][]string{ "engine/output": {module + "/ir", module + "/engine/internal/atomicfile"}, // The atomic replace every file the engine writes goes through. It reaches // renameio, which creates, syncs and renames the file, and nothing of the - // module, so each writer the engine grows can stand on it. + // module, so each writer the engine grows can build on it. "engine/internal/atomicfile": {"github.com/google/renameio/v2"}, // The CLI. Beyond the pipeline it reaches its command framework: cobra // dispatches the commands and renders help, on pflag's parse. What it prints @@ -1089,7 +1102,8 @@ func writeImporter(t *testing.T, file, imp string) { // A package in neither is audited by nothing, and looks no different from one // deliberately left out: the layering gate stays green while that package // imports whatever it likes. Requiring the choice to be recorded is what makes -// the next package added an explicit decision rather than a silent omission. +// the next package added an explicit decision rather than an unrecorded +// omission. func TestImportGraph_EveryPackageIsRuledOrExempt(t *testing.T) { t.Parallel() root := irtest.RepoRoot(t) diff --git a/internal/archtest/assertion_test.go b/internal/archtest/assertion_test.go index e5ea512fb..f4511bd5f 100644 --- a/internal/archtest/assertion_test.go +++ b/internal/archtest/assertion_test.go @@ -152,29 +152,20 @@ func (P) String() string { return "" } // type-check. func checkPlanted(t *testing.T, base *decls.Package, planted, src string) *decls.Package { t.Helper() - f, err := parser.ParseFile(base.Fset, planted, src, parser.SkipObjectResolution) - require.NoError(t, err) + f := parsePlant(t, base.Fset, planted, src, parser.SkipObjectResolution) files := append(slices.Clone(base.Syntax), f) imports := map[string]*types.Package{} for _, imp := range base.Types.Imports() { imports[imp.Path()] = imp } - conf := types.Config{Importer: importerFunc(func(path string) (*types.Package, error) { - imp, ok := imports[path] - if !ok { - return nil, fmt.Errorf("%s does not import %s", base.Types.Path(), path) - } - return imp, nil - })} // TypeOf's documentation asks for all three. info := &types.Info{ Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}, } - pkg, err := conf.Check(base.Types.Path(), base.Fset, files, info) - require.NoError(t, err, "the plant must type-check, or it proves nothing") + pkg := typeCheckPlant(t, base.Fset, base.Types.Path(), files, info, imports, nil) return &decls.Package{Types: pkg, Info: info, Syntax: files, Fset: base.Fset} } diff --git a/internal/archtest/callshape_test.go b/internal/archtest/callshape_test.go index f11688e42..74aef3e0f 100644 --- a/internal/archtest/callshape_test.go +++ b/internal/archtest/callshape_test.go @@ -64,20 +64,31 @@ var callShapeBaseline = map[string]map[string]int{ "engine": 2, "engine/reader": 6, }, + "compilers/openapi/internal/annotation": { + // A node settles its pending keeps and calls back each conjunct's + // keeping of what it keeps plain, as written or for the position to + // report, and each entry's report of what its key holds, whole or + // apart: designed seams, one kind. + "compilers/openapi/internal/schema": 16, + }, "compilers/openapi/internal/lowering": { - // ReadOncePerRun and Settled each call the function they are handed before - // they return: immediate callbacks. operation's are a union's file reading - // and the store of what parts read of unions. - "compilers/openapi/internal/operation": 2, - "compilers/openapi/internal/schema": 26, + // ReadOncePerRun and Settled each call the function they are handed + // before they return: immediate callbacks. operation's are a union's + // file reading, the store of what parts read of unions, and the store + // of the run's memo of its alias chains. + "compilers/openapi/internal/operation": 3, + "compilers/openapi/internal/schema": 35, }, "compilers/openapi/internal/merge": { // What a fold asks the walk that declared the field, through - // merge.FieldDeclarationContext: Alike three times, Admits once, Mint - // once and Interned once. merge.DeclarationConstructRenderer, a lazy - // render of a declaration nobody may keep. And the predicate SelectBase - // calls before it returns, an immediate callback. - "compilers/openapi/internal/schema": 8, + // merge.FieldDeclarationContext: IsComposedOf three times, DeclarationsAdmitAlike three + // times, and Mint, Admits, NodesAdmitAlike, AnnotationsCarried, Interned, + // InDiscriminatorHierarchy and Primitive, which interns the primitive a + // format meets a kind at, once each. + // merge.DeclarationConstructRenderer, a lazy render of a declaration + // nobody may keep. The predicate SelectBase calls before it returns, an + // immediate callback. Each is a designed seam (GitHub #1478). + "compilers/openapi/internal/schema": 15, }, "compilers/openapi/internal/nodeview": { // What nodeview.Walk calls as it visits and leaves a node: traversal @@ -118,8 +129,18 @@ var callShapeBaseline = map[string]map[string]int{ "compilers/openapi/internal/schema": { // LowerComponentSchemas ranges over the statements of the component // schemas the run hands it, read as it asks for each: a traversal - // callback. - "compilers/openapi": 1, + // callback. A parameter's CarrierKeywordKeeps keep what an entry of its + // schema writes that the parameter has no field for: a designed seam. + "compilers/openapi": 1, + "compilers/openapi/internal/operation": 1, + }, + "stronglyconnected": { + // What a Search asks of the graph its Visitor reads and tells of each + // vertex it leaves and each component it closes, ir's composition walk, + // value admission walk and property-count search, and the schema + // package's one component walk, the visitors: traversal callbacks. + "compilers/openapi/internal/schema": 3, + "ir": 9, }, "engine/internal/atomicfile": { // Replace calls the fill it is handed before it returns: an immediate @@ -139,15 +160,24 @@ var callShapeBaseline = map[string]map[string]int{ "internal/harness/openapicases": 12, }, "ir": { - // ir.Visitor and the ForEach walks: traversal callbacks. - "compilers/openapi": 2, - "compilers/openapi/internal/promotion": 1, - "engine/report": 1, - "internal/census": 1, - "internal/harness": 1, - "ir/irfacts": 4, - "ir/irverify": 2, - "pass": 18, + // ir.Visitor and the ForEach walks: traversal callbacks. The lookup an + // ir.AliasChainIndex and an ir.ValueAdmissionReader read their types + // through, and the steps an ir.AliasChainAnswers is built of, + // operation's and pass's run memos among them: designed seams (GitHub + // #1478). And the fold's ir.SourceFormatAdmissions, which the reader + // asks what ir cannot read: an immediate callback (GitHub #2208). + "compilers/openapi": 2, + "compilers/openapi/internal/convention": 2, + "compilers/openapi/internal/merge": 12, + "compilers/openapi/internal/operation": 2, + "compilers/openapi/internal/promotion": 1, + "compilers/openapi/internal/schema": 3, + "engine/report": 1, + "internal/census": 1, + "internal/harness": 1, + "ir/irfacts": 4, + "ir/irverify": 2, + "pass": 20, }, } @@ -385,17 +415,9 @@ func plantedPackages(t *testing.T, srcs ...plantedPackage) program { programValue := program{ssa: prog, own: map[*ssa.Package]string{}} built := map[string]*types.Package{} for _, src := range srcs { - f, err := parser.ParseFile(fset, src.path+".go", src.src, parser.SkipObjectResolution) - require.NoError(t, err) + f := parsePlant(t, fset, src.path+".go", src.src, parser.SkipObjectResolution) files, info := []*ast.File{f}, newInfo() - conf := types.Config{Importer: importerFunc(func(path string) (*types.Package, error) { - if imported, ok := built[path]; ok { - return imported, nil - } - return nil, fmt.Errorf("%s imports %s, which is not planted before it", src.path, path) - })} - checked, err := conf.Check(src.path, fset, files, info) - require.NoError(t, err, "the plant must type-check, or it proves nothing") + checked := typeCheckPlant(t, fset, src.path, files, info, built, nil) built[src.path] = checked programValue.own[prog.CreatePackage(checked, files, info, true /* importable */)] = src.path funcs, err := declaredFuncs(prog, src.path, files, info) diff --git a/internal/archtest/doccomment_test.go b/internal/archtest/doccomment_test.go index 55873aa8c..07b796128 100644 --- a/internal/archtest/doccomment_test.go +++ b/internal/archtest/doccomment_test.go @@ -129,7 +129,9 @@ func TestDocCommentViolations_ExceptionsAreExact(t *testing.T) { } want := []string{ - fmt.Sprintf("x.go:2: Over: doc comment is %d words; the cap is %d", limit+1, limit), + fmt.Sprintf("x.go:2: Over: doc comment is %d words; the cap is %d: shorten it, or record a justified "+ + "exception in longDocComments (internal/archtest/doccomment_test.go) with its word ceiling and reason", + limit+1, limit), fmt.Sprintf("x.go:4: PastCeiling: doc comment is %d words; its longDocComments entry allows %d", limit+10, limit+9), `longDocComments["x.go:Gone"]: excuses nothing; no doc comment by that name is over the cap`, @@ -321,7 +323,8 @@ func docCommentViolations(docs []measuredDoc, allowed map[string]longDoc) []stri needed[measuredDoc.key()] = excused switch { case !excused: - out = append(out, fmt.Sprintf("%s:%d: %s: doc comment is %d words; the cap is %d", + out = append(out, fmt.Sprintf("%s:%d: %s: doc comment is %d words; the cap is %d: shorten it, or record a justified exception "+ + "in longDocComments (internal/archtest/doccomment_test.go) with its word ceiling and reason", measuredDoc.file, measuredDoc.line, measuredDoc.name, measuredDoc.words, maxDocCommentWords)) case measuredDoc.words > entry.words: out = append(out, fmt.Sprintf("%s:%d: %s: doc comment is %d words; its longDocComments entry allows %d", diff --git a/internal/archtest/emitterdocs_test.go b/internal/archtest/emitterdocs_test.go index 3a397efd2..99204f371 100644 --- a/internal/archtest/emitterdocs_test.go +++ b/internal/archtest/emitterdocs_test.go @@ -44,9 +44,9 @@ var commonDocumentList = regexp.MustCompile(`documents every target has \(([^)]* // TestEmitterDocs_EveryTargetAnswersEveryConstruct holds each target's lowering // table to the shared one. One table with a column per target kept every row // answered by every target at a glance; divided by target, a construct added -// for one would leave the others silent, which is the gap the rule "a missing -// row is an IR bug" exists to surface. A row with an empty answer answers -// nothing. +// for one would leave the others saying nothing, which is the gap the rule "a +// missing row is an IR bug" exists to surface. A row with an empty answer +// answers nothing. func TestEmitterDocs_EveryTargetAnswersEveryConstruct(t *testing.T) { t.Parallel() docs := filepath.Join(irtest.RepoRoot(t), filepath.FromSlash(emitterDocs)) diff --git a/internal/archtest/modelread_test.go b/internal/archtest/modelread_test.go index da83da68c..90c7d759a 100644 --- a/internal/archtest/modelread_test.go +++ b/internal/archtest/modelread_test.go @@ -7,7 +7,6 @@ import ( "fmt" "go/ast" "go/importer" - "go/parser" "go/token" "go/types" "maps" @@ -59,7 +58,7 @@ var modelReadBaseline = map[string]map[string]int{ "GetType": 6, "GetUnevaluatedProperties": 2, "IsSchema": 2, - "statement.Parsed": 12, + "statement.Parsed": 10, }, } @@ -127,9 +126,8 @@ func bridgeUses(loadedPackage *decls.Package) []token.Position { return out } -// schemaModel names the parser library's schema types: a package and the -// names it declares them by, a generic one standing for each of its -// instances. +// schemaModel names the parser library's schema types: a package and the names +// it declares them by, a generic one naming each of its instances. type schemaModel struct { pkg string names []string @@ -372,23 +370,11 @@ func use(js *wrapper, s *lib.Schema, o lib.Other, m *lib.Model, e embeds, g inte func TestModelSelections_PlantedSpellingsAreCounted(t *testing.T) { t.Parallel() fset := token.NewFileSet() - parse := func(name, src string) *ast.File { - f, err := parser.ParseFile(fset, name, src, 0) - require.NoError(t, err) - return f - } - lib, err := (&types.Config{}).Check("lib", fset, []*ast.File{parse("lib.go", plantedModel)}, nil) - require.NoError(t, err) + parse := func(name, src string) *ast.File { return parsePlant(t, fset, name, src, 0) } + lib := typeCheckPlant(t, fset, "lib", []*ast.File{parse("lib.go", plantedModel)}, nil, nil, nil) info := &types.Info{Selections: map[*ast.SelectorExpr]*types.Selection{}} - imports := importerFunc(func(path string) (*types.Package, error) { - if path == "lib" { - return lib, nil - } - return importer.Default().Import(path) - }) files := []*ast.File{parse("model.go", plantedAdapter), parse("use.go", plantedReads)} - pkg, err := (&types.Config{Importer: imports}).Check("p", fset, files, info) - require.NoError(t, err) + pkg := typeCheckPlant(t, fset, "p", files, info, map[string]*types.Package{"lib": lib}, importer.Default()) const marker = "// counts " var want []string @@ -536,21 +522,10 @@ func use() { func TestHoldingExpressions_PlantedHoldersAreFound(t *testing.T) { t.Parallel() fset := token.NewFileSet() - parse := func(name, src string) *ast.File { - f, err := parser.ParseFile(fset, name, src, 0) - require.NoError(t, err) - return f - } + parse := func(name, src string) *ast.File { return parsePlant(t, fset, name, src, 0) } checked := map[string]*types.Package{} - imports := importerFunc(func(path string) (*types.Package, error) { - if pkg, ok := checked[path]; ok { - return pkg, nil - } - return importer.Default().Import(path) - }) check := func(path string, files []*ast.File, info *types.Info) *types.Package { - pkg, err := (&types.Config{Importer: imports}).Check(path, fset, files, info) - require.NoError(t, err) + pkg := typeCheckPlant(t, fset, path, files, info, checked, importer.Default()) checked[path] = pkg return pkg } diff --git a/internal/archtest/plant_test.go b/internal/archtest/plant_test.go new file mode 100644 index 000000000..911bcfab6 --- /dev/null +++ b/internal/archtest/plant_test.go @@ -0,0 +1,44 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package archtest_test + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "go/types" + "testing" + + "github.com/stretchr/testify/require" +) + +// parsePlant parses src as the file name, which a plant is written in. +func parsePlant(t *testing.T, fset *token.FileSet, name, src string, mode parser.Mode) *ast.File { + t.Helper() + f, err := parser.ParseFile(fset, name, src, mode) + require.NoError(t, err) + return f +} + +// typeCheckPlant type-checks files as the package path, reading what each +// imports from imported and then from fallback, where there is one, and fails +// the test where they cannot: a plant that does not type-check proves nothing. +func typeCheckPlant(t *testing.T, fset *token.FileSet, path string, files []*ast.File, info *types.Info, + imported map[string]*types.Package, fallback types.Importer, +) *types.Package { + t.Helper() + conf := types.Config{Importer: importerFunc(func(imports string) (*types.Package, error) { + if pkg, ok := imported[imports]; ok { + return pkg, nil + } + if fallback != nil { + return fallback.Import(imports) + } + return nil, fmt.Errorf("%s imports %s, which is not planted before it", path, imports) + })} + pkg, err := conf.Check(path, fset, files, info) + require.NoError(t, err, "the plant must type-check, or it proves nothing") + return pkg +} diff --git a/internal/archtest/reachability_test.go b/internal/archtest/reachability_test.go index b117e9dd0..d09456a76 100644 --- a/internal/archtest/reachability_test.go +++ b/internal/archtest/reachability_test.go @@ -34,7 +34,6 @@ const ( manifestAPI = "the manifest docs/emitters/write-integrate.md records, which the write plan " + "reads (GitHub #2246) and the writer writes (GitHub #2247)" relationAPI = "a relation docs/ir/models.md#composition defines for the IR's consumers, which no shipped one reads yet" - factAPI = "a fact docs/ir/derived-facts.md derives for emitters, which are not built yet" typeTableAPI = "the type table every target decodes, merges and looks up (docs/emitters/contract/type-table.md), " + "which the first target's types slice calls (GitHub #2141)" ) @@ -48,45 +47,40 @@ var apiRoots = map[string]string{ "compilers/openapi.DefaultStreamingMediaTypes": compilerAPI, "compilers/openapi.DefaultBinaryMediaTypes": compilerAPI, "compilers/openapi.DefaultExtensionPromotions": compilerAPI, - "ir.Editor.Type": transformAPI, - "ir.Editor.UpdateType": transformAPI, - "ir.Editor.Service": transformAPI, - "ir.Editor.UpdateService": transformAPI, - "ir.Editor.RemoveService": transformAPI, - "ir.Editor.Group": transformAPI, - "ir.Editor.UpdateGroup": transformAPI, - "ir.Editor.RemoveGroup": transformAPI, - "ir.Editor.Operation": transformAPI, - "ir.Editor.UpdateOperation": transformAPI, - "ir.Editor.RemoveOperation": transformAPI, - "ir.Editor.Server": transformAPI, - "ir.Editor.UpdateServer": transformAPI, - "ir.Editor.Channel": transformAPI, - "ir.Editor.UpdateChannel": transformAPI, - "ir.Editor.Message": transformAPI, - "ir.Editor.UpdateMessage": transformAPI, - "ir.Editor.AuthScheme": transformAPI, - "ir.Editor.UpdateAuthScheme": transformAPI, - "ir.Editor.UpdateDocument": transformAPI, - "ir.ExposedProperties": relationAPI, - "ir/irfacts.DocumentFacts.Subtypes": factAPI, - "ir/irfacts.DocumentFacts.Usage": factAPI, - "ir/irfacts.DocumentFacts.Recursive": factAPI, - "ir/irfacts.DocumentFacts.Component": factAPI, - "ir/irfacts.DocumentFacts.Correlation": factAPI, - "ir/irfacts.DocumentFacts.Correlated": factAPI, - "pathfold.Portable": segmentAPI, - "emitters/manifest.Decode": manifestAPI, - "emitters/manifest.Encode": manifestAPI, - "emitters/manifest.DecodePending": manifestAPI, - "emitters/manifest.EncodePending": manifestAPI, - "emitters/manifest.Digest": manifestAPI, - "emitters/typemap.Decode": typeTableAPI, - "emitters/typemap.Merge": typeTableAPI, - "emitters/typemap.Moved": typeTableAPI, - "emitters/typemap.Missing": typeTableAPI, - "emitters/typemap.Lookup": typeTableAPI, - "emitters/typemap.LookupExternal": typeTableAPI, + "ir.Editor.Type": transformAPI, + "ir.Editor.UpdateType": transformAPI, + "ir.Editor.Service": transformAPI, + "ir.Editor.UpdateService": transformAPI, + "ir.Editor.RemoveService": transformAPI, + "ir.Editor.Group": transformAPI, + "ir.Editor.UpdateGroup": transformAPI, + "ir.Editor.RemoveGroup": transformAPI, + "ir.Editor.Operation": transformAPI, + "ir.Editor.UpdateOperation": transformAPI, + "ir.Editor.RemoveOperation": transformAPI, + "ir.Editor.Server": transformAPI, + "ir.Editor.UpdateServer": transformAPI, + "ir.Editor.Channel": transformAPI, + "ir.Editor.UpdateChannel": transformAPI, + "ir.Editor.Message": transformAPI, + "ir.Editor.UpdateMessage": transformAPI, + "ir.Editor.AuthScheme": transformAPI, + "ir.Editor.UpdateAuthScheme": transformAPI, + "ir.Editor.UpdateDocument": transformAPI, + "ir.ExposedProperties": relationAPI, + "ir.Supertypes": relationAPI, + "pathfold.Portable": segmentAPI, + "emitters/manifest.Decode": manifestAPI, + "emitters/manifest.Encode": manifestAPI, + "emitters/manifest.DecodePending": manifestAPI, + "emitters/manifest.EncodePending": manifestAPI, + "emitters/manifest.Digest": manifestAPI, + "emitters/typemap.Decode": typeTableAPI, + "emitters/typemap.Merge": typeTableAPI, + "emitters/typemap.Moved": typeTableAPI, + "emitters/typemap.Missing": typeTableAPI, + "emitters/typemap.Lookup": typeTableAPI, + "emitters/typemap.LookupExternal": typeTableAPI, } // testSupport names each package whose production files exist for tests, with @@ -364,7 +358,7 @@ func unreached(programValue program, roots, spared map[string]string) []string { } // reachedFrom returns where each function roots reach is declared. A position -// stands for the function, so an instance of a generic one counts for it. +// names the function, so an instance of a generic one counts for it. func reachedFrom(fset *token.FileSet, roots []*ssa.Function) map[token.Position]bool { out := map[token.Position]bool{} for fn := range rta.Analyze(roots, false).Reachable { diff --git a/internal/archtest/recursion_test.go b/internal/archtest/recursion_test.go index 4591f15b3..51531ccb9 100644 --- a/internal/archtest/recursion_test.go +++ b/internal/archtest/recursion_test.go @@ -14,6 +14,7 @@ import ( "maps" "path/filepath" "slices" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -39,28 +40,22 @@ var loweringRecursions = [][]string{ // records this as the reason schema, compose and resolve cannot be separated // into packages. schemaRecursion, - // The nullability predicate. JSON Schema conjoins keywords, so whether a - // schema admits null is decided by its allOf conjuncts as much as by its own - // type set, and a conjunct or a $ref lands on a schema asked the same - // question. These are not lowerings — they build no node, and their caller - // reports what they find — but they live in the same package and the call - // graph reads it whole, so the cycle is pinned here with the rest. It is - // bounded by an explicit budget (maxNullConjuncts), which is what stops a - // self-referential allOf rather than anything in this shape. A $ref's hops - // are walked in a loop its chain's length bounds, and a loop of $refs has no - // end to walk to. A union's null branch counts only where the union is - // distributed, and a branch no instance of an object body satisfies is one - // that admits no null, so the walk and that classification ask each other. - // That classification reads null on variants (mayAdmitNull), which asks no - // union whether it is distributed, so it nests once; so does a oneOf and - // an anyOf asked whether each may admit null (pairMayAdmitNull), whose - // walk reads variants, and on entries it is read by the walk asking. + // The null answer and the union reading. A schema's answer is settled by a + // walk of its own stack (walkComponents), but where the nullable-inference + // policy may lift a null branch of its union, or its oneOf may refuse a + // null two branches leave in, the schema reads that union + // (settleUnionNull), which reads the answers of what its conjunction holds, + // settled before it, through nullAnswerReadingsOf and the settled reading + // of its conjunction (settledNullRead), and so does the reading of a value + // set against a union a $ref names (judgeReferencedUnions). A union reading + // asked while another is under way is not read and is reported + // (nullAnswerMemo.readingUnionNull), so the walk nests once. { - "bodyAdmitsNull", "classifyConjoined", "classifyUnionSiblings", "deadBranch", "deadBranches", - "distributesUnion", "mayAdmitNull", "nulls.allOf", "nulls.branchesNull", "nulls.conjunct", "nulls.keywords", - "nulls.lands", "nulls.ref", "nulls.schema", "nulls.usage", "nulls.valueParts", "nulls.variantsNull", - "nulls.widenByEntry", "pairForbidsNull", "pairKeepsNullOut", "pairMayAdmitNull", "unionNullReading", - "valueNulls", + "NullAlone", "admitsBodyNull", "bodyNull", "branchOverlapOf", "cutRest", "judgeReferencedUnions", + "loweredUnionBranchOverlap", "nullAnswerReadingsOf", "nullBranch", "oneOfLeavesNullTwice", + "policyWidens", "readBranchOverlaps", "readConjunctionRest", "readLoweredUnion", + "readUnionBesideRest", "restOfConjunction", "schemaAdmitsNull", "settleNullComponent", + "settleUnionNull", "settledNullRead", }, // Callbacks. An operation may declare callbacks, each of which is a path item // holding operations of its own (docs/ir/http-binding.md), so the operation @@ -84,29 +79,27 @@ var loweringRecursions = [][]string{ // schemaRecursion is the largest of them, named because the design refers to it // directly and #176's package split is sized by it. Its exported names are how // operation lowering enters; the rest stays unexported. Scalar hoisters and -// encoding readers join via contentSchema, and discriminator lowering, keeping -// (keepUnreadKeys, keepAround), and refReserver.drain join because targets can -// hoist sub-schemas. +// encoding readers join via contentSchema, as does the Encoding a restriction +// of a reference carries (restrictionEncoding), and discriminator lowering, +// refReserver.drain and promiseKeptTargets join because targets can hoist +// sub-schemas. The step keeping a discriminator whole hoists nothing itself, +// queueing what its values name for promiseKeptTargets, so keeping is out. var schemaRecursion = []string{ - "CarriedRef", "FillPropertyDetail", "PreserveRefSiteKeywords", "Ref", "buildComposedVariant", - "buildListedTuple", "buildTuple", "buildUnion", - "composeMixin", "composeModel", "composedVariant", "contentSchemaRef", "declaring.finish", "discriminatorDefault", - "discriminatorMapping", "fillAdditional", "fillAllOf", "fillCatchAll", "fillComposedAdditional", - "fillModelProperties", "fillRefEntry", "hierarchyRoute", "hoistScalar", "hoistSubSchema", "hoistUseHome", "internOwnNode", - "keepApart", "keepAround", "keepFailedRefs", "keepStanding", "keepTagBeside", - "keepUncomposedRefs", "keepUnread", "keepUnreadAcross", "keepUnreadKeys", "keepUnreadOn", "keepUnreadShared", - "keepingUnread", "keptOn", "lower", - "lowerAllOf", - "lowerArray", "lowerBesideUnmodeledUnion", "lowerCoDeclaredUnion", - "lowerDiscriminator", "lowerDispatched", "lowerDistributedUnion", "lowerModel", "lowerNullOnlyUnion", - "lowerOneOfAnyOf", "lowerPrincipal", "lowerPrincipalValueSet", "lowerSchemaBody", "lowerSubtypeUnion", "lowerTypeList", - "lowerTypeVariant", "lowerTyped", "lowerTyping", "lowerUnion", - "mintUnion", "outcomeKeeps.record", "patternProperties", - "preserveUnmergedEntry", "recordEntryUnhomed", - "recordKeptEntry", "recordOwnKeywords", "recordUnread", "refReserver.drain", "refSiteRef", "refTypeRef", - "resolveAt", "resolveBeaten", "resolveDiscriminatorRoutes", - "resolvePointer", "resolveSchemaRef", "routeEntry", "routesKept", - "scalarEncoding", "scalarTypeID", "schemaBody", "schemaRefHomed", "wholePrincipal", + "CarriedRef", "Ref", "buildComposedVariant", "buildListedTuple", "buildOwnNode", "buildPlacedUnion", + "buildTuple", "buildUnion", "composeExpansion", "composeMixin", "composeModel", "composeOneReference", + "composedVariant", "conjoinedVariant", "contentSchemaRef", "contentWriting.contentSchema", + "discriminatorDefault", "discriminatorMapping", "fillAllOf", "fillCatchAll", + "fillComposedAdditional", "fillModelProperties", "fillRefEntry", "hierarchyRoute", "hoistScalar", + "hoistSubSchema", "hoistUseHome", "internOwnNode", "keepUncomposedRefs", "kindVariant", "lower", + "lowerAllOf", "lowerArray", "lowerBesideUnmodeledUnion", "lowerCoDeclaredUnion", + "lowerConjunctionUnion", "lowerDiscriminator", "lowerDispatched", "lowerDistributedUnion", + "lowerModelAt", "lowerNoLiveUnion", "lowerOneOfAnyOf", "lowerPrincipal", "lowerSchemaBody", + "lowerSubtypeUnion", "lowerTypeArrayUnion", "lowerTypeList", "lowerTypeVariant", "lowerTyped", + "lowerTyping", "mintUnion", "patternProperties", "promiseKeptTargets", "refConjoinedVariant", + "refReserver.drain", "refSiteRef", "refTypeRef", "resolveAt", "resolvePassedOverRefs", "resolvePointer", + "resolveSchemaRef", "restrictionEncoding", "routeEntry", "scalarEncoding", "scalarTypeID", "schemaBody", + "schemaRefHomed", "splitKindsUnion", "splitVariant", "typeUnevaluatedCatchAll", "unionOfVariants", + "useHome", } // loweringPackages are the directories whose sources the call graph reads, @@ -146,8 +139,85 @@ func TestLoweringRecursion_IsOnlyTheKnownCycles(t *testing.T) { }) require.NotEmpty(t, cycles, "the schema walk is mutually recursive; finding none means the graph is wrong") - assert.Equal(t, loweringRecursions, cycles, - "the lowering call graph's recursion changed; anything joining one of these sets can no longer be moved alone") + if !slices.EqualFunc(loweringRecursions, cycles, slices.Equal[[]string]) { + t.Error(recursionChangeMessage(loweringRecursions, cycles)) + } +} + +// recursionChangeMessage says how the recursion found differs from the one +// pinned: the cycles found and not pinned, those pinned and not found, each on +// a line of its own and sorted, and what to do about either. Equal sets that +// differ only in order are said to, because they have no cycle to list. +func recursionChangeMessage(pinned, found [][]string) string { + asLines := func(cycles [][]string) map[string]bool { + lines := map[string]bool{} + for _, cycle := range cycles { + lines["{"+strings.Join(cycle, ", ")+"}"] = true + } + return lines + } + pinnedLines, foundLines := asLines(pinned), asLines(found) + added := slices.Sorted(maps.Keys(foundLines)) + added = slices.DeleteFunc(added, func(line string) bool { return pinnedLines[line] }) + removed := slices.Sorted(maps.Keys(pinnedLines)) + removed = slices.DeleteFunc(removed, func(line string) bool { return foundLines[line] }) + + var message strings.Builder + message.WriteString("the lowering call graph's recursion changed in compilers/openapi:\n") + if len(added) == 0 && len(removed) == 0 { + message.WriteString(" the cycles are the pinned ones, listed in another order; list them in loweringRecursions " + + "longest first, ties by first member\n") + } + for _, line := range added { + message.WriteString(" new cycle: " + line + "\n") + } + for _, line := range removed { + message.WriteString(" cycle now gone: " + line + "\n") + } + message.WriteString("what to do: a new recursion is allowed only against a depth counter checked against a " + + "named cap, so bound it that way, then update loweringRecursions in internal/archtest/recursion_test.go " + + "(this file), with the reason the cycle is allowed; for a cycle now gone, delete its entry there") + return message.String() +} + +// TestRecursionChangeMessage_ListsOnlyTheDifference holds the failure text to +// the cycles that differ, each on its own line, and to the instruction. +func TestRecursionChangeMessage_ListsOnlyTheDifference(t *testing.T) { + t.Parallel() + pinned := [][]string{{"a", "b"}, {"c"}} + tests := []struct { + name string + found [][]string + lines []string + not []string + }{ + { + name: "one added, one gone", + found: [][]string{{"a", "b"}, {"d", "e"}}, + lines: []string{" new cycle: {d, e}\n", " cycle now gone: {c}\n"}, + not: []string{"{a, b}", "listed in another order"}, + }, + { + name: "the same cycles in another order", + found: [][]string{{"c"}, {"a", "b"}}, + lines: []string{"listed in another order"}, + not: []string{"new cycle:", "cycle now gone:"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + message := recursionChangeMessage(pinned, tt.found) + for _, line := range tt.lines { + assert.Contains(t, message, line) + } + for _, absent := range tt.not { + assert.NotContains(t, message, absent) + } + assert.Contains(t, message, "depth counter checked against a named cap") + assert.Contains(t, message, "loweringRecursions in internal/archtest/recursion_test.go") + }) + } } // cyclesOf returns graph's recursions, each sorted: every strongly connected @@ -400,11 +470,9 @@ func plantedGraph(t *testing.T, src string) map[string]map[string]bool { func plantedPkg(t *testing.T, src string) typedPkg { t.Helper() fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "planted.go", src, 0) - require.NoError(t, err) + f := parsePlant(t, fset, "planted.go", src, 0) info := &types.Info{Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}} - _, err = (&types.Config{}).Check("p", fset, []*ast.File{f}, info) - require.NoError(t, err) + typeCheckPlant(t, fset, "p", []*ast.File{f}, info, nil, nil) return typedPkg{files: []*ast.File{f}, info: info} } @@ -609,7 +677,7 @@ func TestLoweringCallGraph_RecordsAHandoffAsAnEdge(t *testing.T) { graph := loweringCallGraph(t) handoffs := map[string]string{ - "enumNullVerdict": "isNullValue", + "enumNullAnswer": "isNullValue", "setsDeclareShape": "branchDeclaresShape", } for from, to := range handoffs { @@ -619,23 +687,21 @@ func TestLoweringCallGraph_RecordsAHandoffAsAnEdge(t *testing.T) { } } -// TestLoweringCallGraph_RecordsAMethodEdge holds the graph to the fix for GitHub -// #224 on the tree rather than on a planted source. The nullability reader's -// methods call each other through their receiver, round the cycle pinned -// above, and a graph built from free functions alone described every one of -// those edges as absent. -// -// It names widen as well, which closes no cycle: an edge the graph cannot see -// is unheld whether or not it currently changes an answer. +// TestLoweringCallGraph_RecordsAMethodEdge holds the graph to the fix for +// GitHub #224 on the tree rather than on a planted source. The null answer's +// walk calls its own methods through its receiver, and a graph built from free +// functions alone described every one of those edges as absent. None closes a +// cycle: an edge the graph cannot see is unheld whether or not it currently +// changes an answer. func TestLoweringCallGraph_RecordsAMethodEdge(t *testing.T) { t.Parallel() graph := loweringCallGraph(t) edges := [][2]string{ - {"nulls.schema", "nulls.keywords"}, - {"nulls.keywords", "nulls.allOf"}, - {"nulls.allOf", "nulls.conjunct"}, - {"nulls.schema", "nulls.widen"}, + {"admissionWalk.settle", "admissionWalk.readOne"}, + {"admissionWalk.settle", "admissionWalk.narrowCycleKinds"}, + {"admissionWalk.narrowCycleKinds", "admissionWalk.readOne"}, + {"admissionWalk.settle", "admissionWalk.conditionalRead"}, } for _, e := range edges { // Membership is read with a comma-ok rather than require.Contains, which @@ -662,7 +728,7 @@ func TestLoweringCallGraph_ResolvesAMethodOnAValue(t *testing.T) { graph := loweringCallGraph(t) edges := [][2]string{ - {"composedVariantRef", "nulls.schema"}, // n := newNulls(c) + {"settleNullCycle", "nullCycle.fixpoint"}, // cycle := newNullCycle(c, members) {"LowerService", "serviceGroups.finalize"}, // groups := newServiceGroups() {"lowerPathItem", "serviceGroups.place"}, // a *serviceGroups parameter {"lowerWebhooks", "serviceGroups.group"}, // the same, in the other caller diff --git a/internal/archtest/registryread_test.go b/internal/archtest/registryread_test.go index 4ccf7e409..529519070 100644 --- a/internal/archtest/registryread_test.go +++ b/internal/archtest/registryread_test.go @@ -25,7 +25,7 @@ import ( // lowered to match, so the map only shrinks as decisions move onto what the // source states (GitHub #1991). var registryReadBaseline = map[string]map[string]int{ - "compilers/openapi/internal/schema": {"Lookup": 1, "Node": 1}, + "compilers/openapi/internal/schema": {"Lookup": 1}, } // registryReadRatchet is how a difference from registryReadBaseline reads. @@ -91,7 +91,7 @@ func TestRegistryReads_HeldToTheBaseline(t *testing.T) { // package no longer holds fails too, so the list follows the package. var registryFreeFiles = []string{ "admission.go", "admissionreader.go", "admitted.go", "agreement.go", "allof_disjoint.go", "branchshape.go", "keywordkinds.go", - "kinds.go", "nullbranch.go", "nulls.go", "writtentext.go", + "kinds.go", "nullbranch.go", "nullverdict.go", "writtentext.go", } // TestRegistryFreeFiles_NameNoRegistry holds each of registryFreeFiles to diff --git a/internal/archtest/resolution_test.go b/internal/archtest/resolution_test.go index 7b5768d92..8d6efe32a 100644 --- a/internal/archtest/resolution_test.go +++ b/internal/archtest/resolution_test.go @@ -7,7 +7,6 @@ import ( "cmp" "fmt" "go/ast" - "go/parser" "go/token" "go/types" "maps" @@ -700,14 +699,12 @@ func (d *Doc) Promoted() bool { return d.cache != nil } // touches cache, promot func TestResolutionAPI_DerivesThePlantedLibrarysMembers(t *testing.T) { t.Parallel() fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "planted.go", plantedLibrary, 0) - require.NoError(t, err) + f := parsePlant(t, fset, "planted.go", plantedLibrary, 0) info := &types.Info{ Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}, Selections: map[*ast.SelectorExpr]*types.Selection{}, } - _, err = (&types.Config{}).Check("p", fset, []*ast.File{f}, info) - require.NoError(t, err) + typeCheckPlant(t, fset, "p", []*ast.File{f}, info, nil, nil) libGraphValue := libGraph{} libGraphValue.addFuncs([]*ast.File{f}, info) diff --git a/internal/archtest/sharedlists_test.go b/internal/archtest/sharedlists_test.go new file mode 100644 index 000000000..f31b5ef8a --- /dev/null +++ b/internal/archtest/sharedlists_test.go @@ -0,0 +1,478 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package archtest_test + +import ( + "go/ast" + "go/token" + "go/types" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/internal/decls" + "github.com/dexpace/morphic/ir/irtest" +) + +// TestExportedLists_AreNotShared holds every production package to handing out +// no list it holds (GitHub #1316), as sharedLists reads one. A list a package +// exports is one value every importer shares, so a caller that sorts or +// appends to it changes what every other reader sees; a package hands out a +// predicate or a copy instead. +func TestExportedLists_AreNotShared(t *testing.T) { + t.Parallel() + pkgs, err := productionLoad() + require.NoError(t, err) + root := irtest.RepoRoot(t) + var found []string + for _, loadedPackage := range pkgs { + for _, shared := range sharedLists(loadedPackage) { + found = append(found, relPosition(loadedPackage.Fset.Position(shared.pos), root)+": "+shared.name) + } + } + if len(found) > 0 { + t.Errorf("each of these hands out a list its package holds, which every importer then shares:\n %s\n"+ + "hand out a predicate that answers what callers ask of the list, or a copy of it (slices.Clone, "+ + "maps.Clone), instead of the list itself", + strings.Join(found, "\n ")) + } +} + +// plantedLists hands out a list it holds in each way sharedLists finds one, +// above the values it does not: a copy, an array returned by value, a received +// value, a closure's return, another package's call, a recursion with no list +// in it, an unexported function and one declared without a body. Cycle meets +// two locals assigned each other before the one assigned the list. +const plantedLists = `package planted + +import "lib" + +var ( + list = [...]string{"a"} + table = map[string]bool{"a": true} + lists = map[string][]string{"a": {"b"}} + words = Keywords{"a"} + held = struct{ list []string }{list: []string{"a"}} + pointer = &table + channel = make(chan []string, 1) +) + +type Keywords []string + +type Chain struct { + Next *Chain + Name string +} + +type inner struct{ List []string } + +type wrapper struct{ inner } + +type Settings struct{ List []string } + +var ( + settings = Settings{List: []string{"a"}} + arrayed = struct{ Names [1]string }{} +) + +var ( + SliceList = []string{"a"} + ArrayList = [...]string{"a"} + KeywordSet = map[string]bool{"a": true} + PointerToList = &list + Count = len(list) + Planted = struct{ List []string }{List: []string{"a"}} + Nested = struct{ Inner struct{ List []string } }{} + Pointed = &struct{ List []string }{} + Embedded = wrapper{} + Arrayed = struct{ Names [1]string }{} + Hidden = struct{ list []string }{} + Linked = Chain{} +) + +func Sliced() []string { return list[:] } + +func Shared() Settings { return settings } + +func Table() map[string]bool { return table } + +func Field() []string { return held.list } + +func Imported() []string { return lib.Shared } + +func Indexed() []string { return lists["a"] } + +func Dereferenced() map[string]bool { return *pointer } + +func Address() *[1]string { return &list } + +func Converted() []string { return []string(words) } + +func Appended() []string { return append(list[:0], "c") } + +func ThroughCall() []string { return unexported() } + +func ThroughMethod() []string { return Holder{}.helper() } + +func Several() (int, []string) { return pair() } + +func ThroughLocal() []string { + each := list[:] + return each +} + +func Declared() []string { + var each = list[:] + return each +} + +func Named() (each []string) { + each = list[:] + return +} + +func Looked() []string { + each, _ := lists["a"] + return each +} + +func Taken() []string { + _, each := pair() + return each +} + +func Ranged() []string { + for _, each := range lists { + return each + } + return nil +} + +func Cycle() []string { + var each []string + other := each + each = other + each = list[:] + return each +} + +type Holder struct{} + +func (Holder) Method() (int, []string) { return 0, list[:] } + +// None below is found. + +func (Holder) helper() []string { return list[:] } + +func pair() (int, []string) { return 0, list[:] } + +func unexported() []string { return list[:] } + +func Copied() []string { return append([]string(nil), list[:]...) } + +func Array() [1]string { return list } + +func Built() Settings { return Settings{List: []string{"a"}} } + +func ArrayInside() struct{ Names [1]string } { return arrayed } + +func Received() []string { return <-channel } + +func Inner() []string { + inner := func() []string { return list[:] } + return inner() +} + +func Library() []string { return lib.Fresh() } + +func Recursive() []string { + if len(list) > 1 { + return Recursive() + } + return nil +} + +func Ext() []string +` + +// TestSharedLists_FindsEachPlant holds sharedLists to plantedLists: each way it +// hands out a list it holds is found, and nothing else is. +func TestSharedLists_FindsEachPlant(t *testing.T) { + t.Parallel() + fset := token.NewFileSet() + libraryFile := parsePlant(t, fset, "lib.go", + "package lib\n\nvar Shared = []string{\"a\"}\n\nfunc Fresh() []string { return []string{\"a\"} }\n", 0) + library := typeCheckPlant(t, fset, "lib", []*ast.File{libraryFile}, nil, nil, nil) + file := parsePlant(t, fset, "planted.go", plantedLists, 0) + info := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}} + planted := typeCheckPlant(t, fset, "planted", []*ast.File{file}, info, map[string]*types.Package{"lib": library}, nil) + assert.Equal(t, []string{ + "func Address", "func Appended", "func Converted", "func Cycle", "func Declared", "func Dereferenced", + "func Field", "func Holder.Method", "func Imported", "func Indexed", "func Looked", "func Named", + "func Ranged", "func Several", "func Shared", "func Sliced", "func Table", "func Taken", + "func ThroughCall", "func ThroughLocal", "func ThroughMethod", + "var ArrayList", "var Arrayed", "var Embedded", "var KeywordSet", "var Nested", "var Planted", + "var Pointed", "var PointerToList", "var SliceList", + }, sharedListNames(sharedLists(&decls.Package{Types: planted, Info: info, Syntax: []*ast.File{file}, Fset: fset}))) +} + +// sharedListNames returns the name of each of shared. +func sharedListNames(shared []sharedList) []string { + names := make([]string, len(shared)) + for i, list := range shared { + names[i] = list.name + } + return names +} + +// sharedList is one thing a package exports that hands out a list it holds: +// what it is ("var Name", "func Name") and where it is declared. +type sharedList struct { + name string + pos token.Pos +} + +// sharedLists returns, sorted by name, what loadedPackage exports that hands out a list +// it holds: each package-level variable of a list type (listType), and each +// function or method a result of which is package-level storage +// (sharedReader.result). +func sharedLists(loadedPackage *decls.Package) []sharedList { + var found []sharedList + for variable := range loadedPackage.Objects[*types.Var]() { + if variable.Exported() && listType(variable.Type(), true) { + found = append(found, sharedList{"var " + variable.Name(), variable.Pos()}) + } + } + reader := &sharedReader{info: loadedPackage.Info, declarations: map[*types.Func]*ast.FuncDecl{}, assigned: map[*types.Var][]assignment{}} + for _, file := range loadedPackage.Syntax { + for _, declaration := range file.Decls { + if function, ok := declaration.(*ast.FuncDecl); ok && function.Body != nil { + if object, ok := reader.info.Defs[function.Name].(*types.Func); ok { + reader.declarations[object] = function + } + reader.record(function.Body) + } + } + } + shares := func(function *types.Func) bool { + results := function.Signature().Results() + for i := range results.Len() { + reader.followed = map[any]bool{} + if listType(results.At(i).Type(), false) && reader.result(function, i) { + return true + } + } + return false + } + for function, declaration := range reader.declarations { + if function.Exported() && shares(function) { + name := declaration.Name.Name + if declaration.Recv != nil { + name = types.ExprString(declaration.Recv.List[0].Type) + "." + name + } + found = append(found, sharedList{"func " + name, declaration.Pos()}) + } + } + slices.SortFunc(found, func(a, b sharedList) int { return strings.Compare(a.name, b.name) }) + return found +} + +// listType reports whether a value of type held shares a list it points at: a +// slice, a map, an array where stored holds, as it does for a variable or a +// pointee rather than a returned value, which copies one, a struct with such a +// field another package can reach, or a pointer to any of them. A struct is +// read once for each stored, which bounds a recursive type. +func listType(held types.Type, stored bool) bool { + type read struct { + structure *types.Struct + stored bool + } + seen := map[read]bool{} + var shares func(types.Type, bool) bool + shares = func(held types.Type, stored bool) bool { + if pointer, ok := held.Underlying().(*types.Pointer); ok { + held, stored = pointer.Elem(), true + } + switch value := held.Underlying().(type) { + case *types.Slice, *types.Map: + return true + case *types.Array: + return stored + case *types.Struct: + if seen[read{value, stored}] { + return false + } + seen[read{value, stored}] = true + for field := range value.Fields() { + if (field.Exported() || field.Embedded()) && shares(field.Type(), stored) { + return true + } + } + return false + default: + return false + } + } + return shares(held, stored) +} + +// assignment is one value a local variable is assigned: value, or where value +// is a call whose results several variables take, its result at index. +type assignment struct { + value ast.Expr + index int +} + +// resultOf is one result of a function, the one at index. +type resultOf struct { + function *types.Func + index int +} + +// sharedReader reads whether a value is storage a package-level variable +// holds, through the functions the package declares and the values assigned +// each local variable. followed records each local and result read, so each is +// read once, which bounds the walk. +type sharedReader struct { + info *types.Info + declarations map[*types.Func]*ast.FuncDecl + assigned map[*types.Var][]assignment + followed map[any]bool +} + +// record records each value body assigns a variable, a closure's included: by +// an assignment, a declaration, or a range, which assigns each element of what +// it ranges over. +func (r *sharedReader) record(body *ast.BlockStmt) { + pair := func(targets, values []ast.Expr) { + for i, target := range targets { + name, isName := target.(*ast.Ident) + variable, isVariable := r.info.ObjectOf(name).(*types.Var) + switch { + case !isName || !isVariable: + case len(values) == len(targets): + r.assigned[variable] = append(r.assigned[variable], assignment{values[i], 0}) + case len(values) == 1: + r.assigned[variable] = append(r.assigned[variable], assignment{values[0], i}) + } + } + } + ast.Inspect(body, func(node ast.Node) bool { + switch statement := node.(type) { + case *ast.AssignStmt: + pair(statement.Lhs, statement.Rhs) + case *ast.ValueSpec: + names := make([]ast.Expr, 0, len(statement.Names)) + for _, name := range statement.Names { + names = append(names, name) + } + pair(names, statement.Values) + case *ast.RangeStmt: + pair([]ast.Expr{statement.Key, statement.Value}, []ast.Expr{statement.X, statement.X}) + default: + } + return true + }) +} + +// result reports whether a return of function, not a closure's, gives its +// result at index storage a package-level variable holds: a bare return its +// named result, and a return of one call that call's result. A function the +// package does not declare gives none. +func (r *sharedReader) result(function *types.Func, index int) bool { + declaration, declared := r.declarations[function] + if !declared || r.followed[resultOf{function, index}] { + return false + } + r.followed[resultOf{function, index}] = true + shared := false + ast.Inspect(declaration.Body, func(node ast.Node) bool { + returned, isReturn := node.(*ast.ReturnStmt) + _, closure := node.(*ast.FuncLit) + switch { + case shared || closure: + return false + case !isReturn: + case len(returned.Results) == 0: + shared = r.variable(function.Signature().Results().At(index)) + case len(returned.Results) > index: + shared = r.storage(returned.Results[index]) + default: + shared = r.called(returned.Results[0], index) + } + return true + }) + return shared +} + +// storage reports whether expression is storage a package-level variable of +// any package holds: the variable, a field, an index, a slice, an address or +// the pointee of one, a conversion of one or a builtin's first argument, of +// which only append's is a value, or a result of a function the package +// declares. +func (r *sharedReader) storage(expression ast.Expr) bool { + switch value := ast.Unparen(expression).(type) { + case *ast.Ident: + variable, ok := r.info.Uses[value].(*types.Var) + return ok && r.variable(variable) + case *ast.SelectorExpr: + return r.storage(value.Sel) || r.storage(value.X) + case *ast.IndexExpr: + return r.storage(value.X) + case *ast.SliceExpr: + return r.storage(value.X) + case *ast.StarExpr: + return r.storage(value.X) + case *ast.UnaryExpr: + return value.Op == token.AND && r.storage(value.X) + case *ast.CallExpr: + if called := r.info.Types[value.Fun]; called.IsType() || called.IsBuiltin() { + return r.storage(value.Args[0]) + } + return r.called(value, 0) + default: + return false + } +} + +// called reports whether expression calls, by name, a function the package +// declares whose result at index is storage a package-level variable holds. +func (r *sharedReader) called(expression ast.Expr, index int) bool { + call, isCall := ast.Unparen(expression).(*ast.CallExpr) + if !isCall { + return false + } + var name *ast.Ident + switch function := ast.Unparen(call.Fun).(type) { + case *ast.Ident: + name = function + case *ast.SelectorExpr: + name = function.Sel + default: + return false + } + callee, ok := r.info.Uses[name].(*types.Func) + return ok && r.result(callee, index) +} + +// variable reports whether variable is one a package scope declares, or a +// local one assigned storage such a variable holds. +func (r *sharedReader) variable(variable *types.Var) bool { + if variable.Parent() == variable.Pkg().Scope() { + return true + } + if r.followed[variable] { + return false + } + r.followed[variable] = true + return slices.ContainsFunc(r.assigned[variable], func(assigned assignment) bool { + if assigned.index == 0 { + return r.storage(assigned.value) + } + return r.called(assigned.value, assigned.index) + }) +} diff --git a/internal/archtest/suppression_test.go b/internal/archtest/suppression_test.go index ae67e31d8..2da6b95f6 100644 --- a/internal/archtest/suppression_test.go +++ b/internal/archtest/suppression_test.go @@ -18,7 +18,7 @@ import ( ) // suppressionDirectives are the comment forms that silence a linter from inside -// the source. None may stand: a suppression is a rule in .golangci.yml's +// the source. None may remain: a suppression is a rule in .golangci.yml's // exclusions, where every one is found in a single place with its reason beside // it. A directive naming a linter the config leaves off is read by nothing yet // reads as a live constraint, and refusing the whole class closes that without @@ -34,13 +34,14 @@ var suppressionDirectives = []struct { // revive's own directive, which golangci-lint passes through and nolintlint // never saw. {"revive", regexp.MustCompile(`^//\s*revive:(?:enable|disable)`)}, - // staticcheck's own directive. Its unused analyzer honours it for U1000, and - // golangci-lint did not for SA1012 (v2.14.0), so it may suppress or stand inert. + // staticcheck's own directive. Its unused analyzer honours it for U1000, + // and golangci-lint did not for SA1012 (v2.14.0), so it may suppress or do + // nothing. {"lint:ignore", regexp.MustCompile(`^//\s*lint:(?:file-)?ignore`)}, // exhaustive's own: an ignore on a switch, a map literal or an enum's // declaration takes it out of the check. It wants "//exhaustive:" with no // space (v0.13.0); the spellings it ignores are refused too. Its enforce - // directive only adds a check, so it stands. + // directive only adds a check, so it is allowed. {"exhaustive:ignore", regexp.MustCompile(`(?i)^(?://|/\*)\s*exhaustive:ignore`)}, } @@ -55,12 +56,12 @@ func suppressionOf(text string) (string, bool) { return "", false } -// TestSuppressions_NoDirectiveStandsInTheSource reads every comment of every Go -// file the go tool would build, tests included, and fails on one that spells a -// suppression directive. It reads comments rather than text, so a string +// TestSuppressions_NoDirectiveRemainsInTheSource reads every comment of every +// Go file the go tool would build, tests included, and fails on one that spells +// a suppression directive. It reads comments rather than text, so a string // literal, or a sentence that mentions a directive without opening a comment // with it, is not one. -func TestSuppressions_NoDirectiveStandsInTheSource(t *testing.T) { +func TestSuppressions_NoDirectiveRemainsInTheSource(t *testing.T) { t.Parallel() violations, files, err := suppressionViolations(irtest.RepoRoot(t)) require.NoError(t, err) diff --git a/internal/archtest/testhelper_test.go b/internal/archtest/testhelper_test.go index 1bc37094f..a3456701a 100644 --- a/internal/archtest/testhelper_test.go +++ b/internal/archtest/testhelper_test.go @@ -260,12 +260,12 @@ func use(t *testing.T) { check(t) } } } -// TestTestHelperViolations_ReadsTheModulesTestingInterfaces plants helpers -// that take a type the module declares in place of a testing type, as -// openapitest.TB stands in for *testing.T, or a type parameter constrained by -// either. Each that takes a module type is planted beside one it must not be -// taken for, and a name is read in the scope that declares it: a type -// parameter's, or a package's beside its external test package. +// TestTestHelperViolations_ReadsTheModulesTestingInterfaces plants helpers that +// take a type the module declares in place of a testing type, as openapitest.TB +// takes the place of *testing.T, or a type parameter constrained by either. +// Each that takes a module type is planted beside one it must not be taken for, +// and a name is read in the scope that declares it: a type parameter's, or a +// package's beside its external test package. func TestTestHelperViolations_ReadsTheModulesTestingInterfaces(t *testing.T) { t.Parallel() const tb = `package a @@ -631,11 +631,11 @@ func isEntryPoint(name string) bool { } // testingTypes returns, keyed by declKey, each type a file under root declares -// at top level that a helper can take in place of *testing.T, as -// openapitest.TB stands in for it: one isTesting reads as a testing type, such -// as an interface naming Helper or an alias or definition of testing.TB. One -// declared through a module type, by embedding it or as its alias or -// definition, is not read, as one walk reads them all. +// at top level that a helper can take in place of *testing.T, as openapitest.TB +// takes the place of it: one isTesting reads as a testing type, such as an +// interface naming Helper or an alias or definition of testing.TB. One declared +// through a module type, by embedding it or as its alias or definition, is not +// read, as one walk reads them all. func testingTypes(root string) (map[string]bool, error) { out := map[string]bool{} err := walkGoFiles(root, func(rel string, _ *token.FileSet, f *ast.File) { diff --git a/internal/archtest/testnames_test.go b/internal/archtest/testnames_test.go index 4f090a43a..d0e60d161 100644 --- a/internal/archtest/testnames_test.go +++ b/internal/archtest/testnames_test.go @@ -38,7 +38,7 @@ var ( tableRow = regexp.MustCompile(`^ {0,3}\|`) ) -// testNamePlaceholders are the names written as a test's that stand for no +// testNamePlaceholders are the names written as a test's that refer to no // test, each with the reason. var testNamePlaceholders = map[string]string{ "TestFunc_Scenario": "the root guidance's naming convention, spelled as a shape", diff --git a/internal/archtest/walkcallers_test.go b/internal/archtest/walkcallers_test.go index a5359c1b4..7d8dbf552 100644 --- a/internal/archtest/walkcallers_test.go +++ b/internal/archtest/walkcallers_test.go @@ -57,7 +57,7 @@ var walkCallers = map[string]walkCaller{ "pass.Visit", "pass.dangling"}, }, "pass.Run": {answer: "reads the stop, as before"}, - "pass.checkGroupWalkTruncated": {answer: "reads the stop through the facts' Partial, silent where the reference walk reported", optional: true}, + "pass.checkGroupWalkTruncated": {answer: "reads the stop through the facts' Partial, reporting nothing where the reference walk reported", optional: true}, "pass.forEachPayload": {answer: validateReports}, "pass.checkIdempotency": {answer: validateReports}, "pass.checkResponseIndices": {answer: validateReports}, @@ -99,6 +99,12 @@ var walkCallers = map[string]walkCaller{ "compilers/openapi.pruneUnreferencedTypes": { answer: "a stopped walk removes no type, so no live anonymous type is dropped", }, + "compilers/openapi/internal/schema.nodePairs": { + answer: "a stopped walk leaves the IDs past it in the encodings compared, so two nodes naming others there read apart and none shows alike falsely", + }, + "compilers/openapi/internal/schema.annotationsOf": { + answer: "one node lies far within the walk's bounds, its values nesting no deeper than the compiler's own limit, so no walk of one stops", + }, } // walkNames returns ir's walks, read off ir: its exported functions that name diff --git a/internal/exectest/exectest_test.go b/internal/exectest/exectest_test.go index 056eec968..f54be8537 100644 --- a/internal/exectest/exectest_test.go +++ b/internal/exectest/exectest_test.go @@ -17,8 +17,8 @@ import ( "github.com/dexpace/morphic/internal/exectest" ) -// fatal is what a fatalTB's Fatal panics with, standing in for the goroutine -// exit a real Fatal makes. +// fatal is what a fatalTB's Fatal panics with, taking the place of the +// goroutine exit a real Fatal makes. type fatal string // fatalTB is a test whose Fatal panics with a fatal, so a test can catch the diff --git a/internal/harness/annotations.go b/internal/harness/annotations.go index 728be425d..c617e9599 100644 --- a/internal/harness/annotations.go +++ b/internal/harness/annotations.go @@ -52,7 +52,7 @@ type SiteKind string // to appear in SiteKinds(), the same way it does for Annotations() above. const ( // SiteDeclarationModel is an annotation on an object-shaped component, - // which lowers through the compiler's model path (lowerModel). + // which lowers through the compiler's model path (lowerModelAt). SiteDeclarationModel SiteKind = "declaration-model" // SiteDeclarationScalar is an annotation on a scalar-shaped component, // which lowers through the compiler's alias path (internAlias in diff --git a/internal/harness/canon.go b/internal/harness/canon.go index fb6b92af9..f1634bea6 100644 --- a/internal/harness/canon.go +++ b/internal/harness/canon.go @@ -42,7 +42,7 @@ var errCycle = errors.New("canonical form meets a cycle of digests") // unorderedMark names the one member of the object markedArray writes. const unorderedMark = "\x00unordered" -// markedArray writes elements as they stand, inside an object marking them as a +// markedArray writes elements as they are, inside an object marking them as a // collection whose order the comparison forgives, so the rewrite sorts them // once it has rewritten them. No member of the IR is so named. func markedArray(elements [][]byte) []byte { @@ -58,7 +58,7 @@ type canonical struct { // canonicalForm is doc as the sequence-order oracle compares it, where seqs // are the sequences reversed, in doc's source's coordinates, and ties what -// the reports that moved decided. It forgives an index of +// the ties decided. It forgives an index of // a reversed sequence a string names, an ID beneath one told apart by its // owners' digest; the order of what orderFree lists, mixins, requires and an // array kept verbatim at a reversed sequence's pointer; and each node a tie @@ -85,7 +85,7 @@ func newRewriter(doc *ir.Document, seqs sequences, ties tieSites) (*rewriter, er return nil, err } rewriterValue := &rewriter{ - seqs: seqs, ties: ties.pointers, members: ties.members, nodes: map[string]bool{}, stated: map[string]bool{}, + seqs: seqs, members: ties.members, nodes: map[string]bool{}, stated: map[string]bool{}, owners: map[string][]map[string]any{}, digests: map[string]string{}, visiting: map[string]bool{}, } @@ -100,7 +100,7 @@ func newRewriter(doc *ir.Document, seqs sequences, ties tieSites) (*rewriter, er return rewriterValue, nil } -// number is a JSON number's text, which the rewrite writes as it stands. +// number is a JSON number's text, which the rewrite writes as it is. type number string // rawNumber decodes a JSON number as its text, which no Go number type holds @@ -143,14 +143,13 @@ type place struct { } // rewriter is the state of a document's forms: the sequences, the document's -// encoding decoded, the tie sites, tied members' pointers and tied nodes it +// encoding decoded, the tied members' pointers and tied nodes it // reads, the owners of each // ID erasing changes, the digests computed so far, the IDs whose digest is // being computed and the innermost of them, and the first error met. type rewriter struct { seqs sequences tree any - ties []string members []string nodes map[string]bool stated map[string]bool @@ -269,27 +268,25 @@ func (r *rewriter) object(o map[string]any, placeValue place, depth int) []byte return append(out, '}') } -// foldedOf writes what o, a tied node, holds that its fold settles from every -// declaration alike, where it is a property: whether it is required, where -// any declaration or its model says so, or secret, where any declaration does, -// and where it is visible, the lifecycles every declaration admits +// foldedOf writes what o, a tied property, the one kind of tied node the form +// writes in place (tied), holds that its fold settles from every declaration +// alike: whether it is required, where any declaration or its model says so, +// or secret, where any declaration does, and where it is visible, the +// lifecycles every declaration admits // (docs/compilers/openapi.md#allof-redeclared-property). No tie between two of // them decides these, so they are compared where nothing else of the member is. func (r *rewriter) foldedOf(o map[string]any, depth int) []byte { - required, isProperty := o["required"].(bool) - if _, named := o["wireName"]; !named || !isProperty { - return nil - } + required, _ := o["required"].(bool) secret, _ := o["secret"].(bool) out := []byte(`,"required":` + strconv.FormatBool(required) + `,"secret":` + strconv.FormatBool(secret) + `,"visibility":`) return append(out, r.rewrite(o["visibility"], place{}, depth+1)...) } // statedOf writes what else of o, a tied node, folds over every declaration, -// where a stated tie alone decided it (tieSites.stated): its deprecation, docs, -// name and XML hints. Such a tie decides none of them; two declarations giving -// one differently draw a report of their own, which moves with the order and so -// reaches the member as another tie. +// where conflicts alone tied it (tieSites.stated): its deprecation, docs, name +// and XML hints. A conflict decides none of them; two declarations giving one +// differently draw a report of their own, a tie that decides them +// (tiedByConflictsAlone). func (r *rewriter) statedOf(o map[string]any, depth int) []byte { id, _ := o["id"].(string) if !r.stated[erase(id, r.seqs)] { @@ -404,13 +401,6 @@ func (r *rewriter) quote(s string) []byte { return b } -// tiedAt returns a provenance's pointer erased, and whether it is at or -// beneath a tie site. -func (r *rewriter) tiedAt(pointer string) (string, bool) { - erased := erase(pointer, r.seqs) - return erased, atSite(r.ties, erased) -} - // leftOut reports whether an object at placeValue leaves its member name, // holding v, out of its form: an identity a place reads without, or a node it // keys by its ID that a tie decided, as a registry does, since a tie decides @@ -428,15 +418,15 @@ func (r *rewriter) leftOut(name string, v any, placeValue place) bool { } // tied returns how a tie reads o, and whether one decided it: o's pointer -// erased where it is at or beneath a tie site, o is a node a tied member's -// fold minted (minted), or a tie names o where a tied member stands, and its -// ID erased where a tie names it anywhere else. +// erased where o is a node a tied member's fold minted (minted), or a tie names +// o where a tied member sits, and its ID erased where a tie names it anywhere +// else. func (r *rewriter) tied(o map[string]any) (string, bool) { - erased, atSite := r.tiedAt(provenancePointer(o)) + erased := erase(provenancePointer(o), r.seqs) id, hasID := o["id"].(string) named := hasID && r.nodes[erase(id, r.seqs)] switch { - case atSite, hasID && minted(r.members, id, erased), named && r.atMember(erased): + case hasID && minted(r.members, id, erased), named && r.atMember(erased): return erased, true case named: return erase(id, r.seqs), true @@ -446,36 +436,59 @@ func (r *rewriter) tied(o map[string]any) (string, bool) { } // atMember reports whether erased, an erased pointer, is where a tied member -// stands. +// sits. func (r *rewriter) atMember(erased string) bool { _, at := slices.BinarySearch(r.members, erased) return at } -// tiedNode reports whether a tie decided the node td, identified by id: it sits -// at or beneath a tie site, a tied member's fold minted it, or a tie names it. +// tiedNode reports whether a tie decided the node td, identified by id: a +// tied member's fold minted it, or a tie names it. func (r *rewriter) tiedNode(id ir.TypeID, td ir.TypeDef) bool { - erased, atSite := r.tiedAt(string(td.Common().Provenance.Pointer)) - return atSite || minted(r.members, string(id), erased) || r.nodes[erase(string(id), r.seqs)] + erased := erase(string(td.Common().Provenance.Pointer), r.seqs) + return minted(r.members, string(id), erased) || r.nodes[erase(string(id), r.seqs)] } // minted reports whether the node or member id, at erased, an erased pointer, -// is one the fold of a tied member, standing at one of members, minted: in the -// composed namespace, at the member's pointer or beneath it at a position the -// fold builds a member at (docs/compilers/openapi.md#allof-redeclared-property), -// so which declaration won decides it. A node written in the source beneath -// the member, alike in either order, is not. The oracle reads one source, so -// no space is qualified. +// is one the fold of a tied member, sitting at one of members, minted: in the +// composed namespace, at the member's pointer or beneath it, or at the fold's +// key, /allOf/properties/ for a schema holding the member, or +// beneath that, at a position the fold builds a member at +// (docs/compilers/openapi.md#allof-redeclared-property), so which declaration +// won decides it. A node written in the source beneath the member, alike in +// either order, is not. The oracle reads one source, so no space is qualified. func minted(members []string, id, erased string) bool { if !composed(id) { return false } return slices.ContainsFunc(members, func(member string) bool { - rest, beneath := strings.CutPrefix(erased, member) - return beneath && mintedPosition(rest) + if rest, beneath := strings.CutPrefix(erased, member); beneath && mintedPosition(rest) { + return true + } + return atFoldKey(member, erased) }) } +// atFoldKey reports whether erased is at the key the fold of the member at +// member mints under, or beneath it at a position the fold builds a member at: +// a schema holding the member, then allOf, properties and the member's name. +func atFoldKey(member, erased string) bool { + name := member[strings.LastIndex(member, "/")+1:] + key := "/allOf/properties/" + name + for at := strings.Index(erased, key); at >= 0; { + schema, rest := erased[:at], erased[at+len(key):] + if strings.HasPrefix(member, schema+"/") && mintedPosition(rest) { + return true + } + next := strings.Index(erased[at+1:], key) + if next < 0 { + return false + } + at += next + 1 + } + return false +} + // composed reports whether id is in the composed namespace, where a fold mints // what it builds (docs/compilers/openapi.md#allof-redeclared-property). func composed(id string) bool { @@ -601,11 +614,11 @@ func (r *rewriter) shape(doc *ir.Document) []string { func (r *rewriter) memberShape(flatProperty ir.FlatProperty) string { prov := flatProperty.Property.Provenance id := erase(string(flatProperty.Property.ID), r.seqs) - erased, atSite := r.tiedAt(string(prov.Pointer)) + erased := erase(string(prov.Pointer), r.seqs) byFold := minted(r.members, string(flatProperty.Property.ID), erased) - if atSite || byFold || r.nodes[id] { + if byFold || r.nodes[id] { tie := "reported tie " + id - if atSite || byFold || r.atMember(erased) { + if byFold || r.atMember(erased) { tie = "reported tie at " + erased } visibility, err := json.Marshal(&flatProperty.Property.Visibility, json.Deterministic(true)) diff --git a/internal/harness/canon_internal_test.go b/internal/harness/canon_internal_test.go index 7582fa05c..6d6bbc5eb 100644 --- a/internal/harness/canon_internal_test.go +++ b/internal/harness/canon_internal_test.go @@ -266,9 +266,11 @@ func TestDiffSequenceInvariants_ForgivesOnlyWhatTheReversalMoves(t *testing.T) { return kept("x-ext", pointer, []string{`{"allOf":[1,2]}`, `{"allOf":[2,1]}`}[i])(doc, i) } } - // tied reports at one index in either order, which the reversal moves, so - // the site is a tie, and changes what a model says there. - tied := func(doc *ir.Document, i int) []ir.Diagnostic { + // besideMoved reports at one index in either order, which the reversal + // moves, and changes what a model says there. A moved report ties + // nothing, and no stated tie decides what it sits at, so untied does not + // forgive it: the report and the model's docs are found. + besideMoved := func(doc *ir.Document, i int) []ir.Diagnostic { model := declaring("C", "type/primitive/string") model.Provenance = ir.Provenance{Pointer: ab + "/0/properties/p"} model.Docs.Description = strconv.Itoa(i) @@ -300,7 +302,7 @@ func TestDiffSequenceInvariants_ForgivesOnlyWhatTheReversalMoves(t *testing.T) { {"an unmodeled name indexing an allOf", keptAt("openapi:allOf/"), false}, {"a verbatim allOf array off the reversed sequences", keptArray("/components/schemas/A/x-ext"), true}, {"a verbatim allOf array at a reversed sequence", keptArray("/components/schemas/AB"), false}, - {"a node at a tie", tied, false}, + {"a node beside a moved report", besideMoved, true}, {"a provenance in a sequence left as written", model(cd), true}, {"a provenance in a reversed sequence", model(ab), false}, {"a diagnostic in a sequence left as written", reported(cd), true}, diff --git a/internal/harness/cases.go b/internal/harness/cases.go index 2ca7872e0..cafa0eb5b 100644 --- a/internal/harness/cases.go +++ b/internal/harness/cases.go @@ -19,7 +19,7 @@ import ( // maxCases bounds a product: CaseCount refuses one of more cases, so an index // fits an int and a run over every case ends. -const maxCases = 1 << 22 +const maxCases = 1 << 24 // shardAxes is how many leading axes a shard shares (CheckCases): a case and // every neighbour an oracle compares it with differ past them alone. @@ -64,6 +64,11 @@ type CaseDocument struct { // Reason says why not, required when Carried is false and Absent is set // (presence). Reason string + // RelocateAbsent is true where the case at Absent is written in another + // spelling than this one, whose coordinates Equal.Relocate maps this + // case's into: the presence oracle then compares the documents relocated, + // as the spelling oracle compares a spelling with its partner (presence). + RelocateAbsent bool // Replaces is true where the construct replaces a member the case's target // writes, so the case at Absent still writes the keyword and is no case // without it: the construct is held to Other alone (presence). diff --git a/internal/harness/cases_internal_test.go b/internal/harness/cases_internal_test.go index 32385ecfe..57216ecb3 100644 --- a/internal/harness/cases_internal_test.go +++ b/internal/harness/cases_internal_test.go @@ -18,7 +18,7 @@ import ( ) // fake is a product of cases: its axes, each case a tiny spec, and write, when -// set, standing for Write. +// set, naming Write. type fake struct { axes []Axis write func(at []int) (CaseDocument, bool) diff --git a/internal/harness/cases_test.go b/internal/harness/cases_test.go index 00d80ce72..0f60ce2d9 100644 --- a/internal/harness/cases_test.go +++ b/internal/harness/cases_test.go @@ -75,9 +75,9 @@ func TestCaseCount_IsTheProductOfTheAxes(t *testing.T) { require.NoError(t, err) assert.Equal(t, 12, n) - n, err = harness.CaseCount(grid{axes: []harness.Axis{numbered("a", 1<<11), numbered("b", 1<<11)}}) + n, err = harness.CaseCount(grid{axes: []harness.Axis{numbered("a", 1<<12), numbered("b", 1<<12)}}) require.NoError(t, err, "a product of exactly the bound is admitted") - assert.Equal(t, 1<<22, n) + assert.Equal(t, 1<<24, n) } // TestCaseCount_RefusesWhatNoProductHolds holds each guard of CaseCount to @@ -102,7 +102,7 @@ func TestCaseCount_RefusesWhatNoProductHolds(t *testing.T) { {"a value named with a tab", grid{axes: []harness.Axis{axis("a", "x\ty")}}, `"x\ty"`}, {"a like naming no value", grid{axes: []harness.Axis{like("y", "z")}}, `is like "z", no core value`}, {"a like naming a value like another", grid{axes: []harness.Axis{like("y", "y")}}, `is like "y", no core value`}, - {"a product past the bound", grid{axes: []harness.Axis{numbered("a", 5), numbered("b", 838861)}}, "past 4194304 cases"}, + {"a product past the bound", grid{axes: []harness.Axis{numbered("a", 97), numbered("b", 172961)}}, "past 16777216 cases"}, } { t.Run(tc.name, func(t *testing.T) { _, err := harness.CaseCount(tc.cases) @@ -110,7 +110,7 @@ func TestCaseCount_RefusesWhatNoProductHolds(t *testing.T) { assert.Contains(t, err.Error(), tc.want) }) } - assert.Equal(t, 1<<22+1, 5*838861, "the last row is one case past the bound") + assert.Equal(t, 1<<24+1, 97*172961, "the last row is one case past the bound") } func TestCoordinates_NameEachCaseByItsIndices(t *testing.T) { diff --git a/internal/harness/corpus_test.go b/internal/harness/corpus_test.go index 9fd26a858..cbeeff700 100644 --- a/internal/harness/corpus_test.go +++ b/internal/harness/corpus_test.go @@ -165,17 +165,15 @@ func knownInvalid() map[string]bool { // names compare in any case; the case pins that the idempotency policy // then infers no token. filepath.FromSlash("../../testdata/conformance/openapi/idempotency-inference.yaml"): true, - // Discriminator mappings naming a schema that is not a variant of the - // base: a sub-schema (f08, f13), a component named "" (f31), and a - // $defs entry mapped from a base with no composition (defs_at_root, - // defs_mapping_unreferenced_target). Each pins where a mapping resolves, - // not polymorphism: the compiler lowers the target as a $ref to it would - // (#530), and the validate pass reports pass/discriminator-missing-variant. - filepath.FromSlash("../../testdata/dangling/openapi/f08-discriminator.yaml"): true, + // Discriminator mappings on a union naming a schema that is not a variant + // of it: a sub-schema (f13) and a component named "" (f31). Each pins + // where a mapping resolves, not polymorphism: the compiler lowers the + // target as a $ref to it would (#530), and the validate pass reports + // pass/discriminator-missing-variant. A model's entry naming no subtype is + // kept verbatim apart, so its reproducers (f08, defs_at_root, + // defs_mapping_unreferenced_target) compile clean. filepath.FromSlash("../../testdata/dangling/openapi/f13-refs.yaml"): true, filepath.FromSlash("../../testdata/dangling/openapi/f31-discriminator-empty-name.yaml"): true, - filepath.FromSlash("../../testdata/openapi/defs_at_root.yaml"): true, - filepath.FromSlash("../../testdata/openapi/defs_mapping_unreferenced_target.yaml"): true, // The other dangling reproducers (f07, f10, f11, f28) intern their // targets and compile clean, so they are absent. } @@ -185,14 +183,10 @@ func knownInvalid() map[string]bool { // makes on a committed fixture: a defect in the compiler, each beside the issue // that holds it. TestHarness_InRepoCorpus fails a fixture whose findings are // not exactly these, so a fix takes its entry out. An entry names an outcome, -// not what differs, so until then it also stands for any other finding of its -// oracle on that fixture. +// not what differs, so until then it also names any other finding of its oracle +// on that fixture. func knownFindings() map[string][]harness.Outcome { - return map[string][]harness.Outcome{ - // A model composed from a field's declarations takes the last one's - // name hint, so swapping allOf entries renames it (#1921). - filepath.FromSlash("../../testdata/conformance/openapi/allof-redeclared-models.yaml"): {harness.OutcomeSequenceOrderDependent}, - } + return map[string][]harness.Outcome{} } // knownDeclines lists the fixtures some oracle asks nothing of, each beside the diff --git a/internal/harness/fold.go b/internal/harness/fold.go index bfce5a199..2f51597a0 100644 --- a/internal/harness/fold.go +++ b/internal/harness/fold.go @@ -17,12 +17,12 @@ import ( ) // folded returns doc with its decorators (ir.Decorated) left out of Types, and -// the marshalers that write each reference to one as a reference to the type -// it stands for, what the chain holds beside it, and at a carrier what -// carried.write merges. Two spellings of one use then encode alike. An ID -// naming a decorator is written as the type's alone and a decorator nothing -// names is left out, so what one holds is compared only where a reference -// names it. It is a second implementation of the emitter's collapse +// the marshalers that write each reference to one as a reference to the type it +// names, what the chain holds beside it, and at a carrier what carried.write +// merges. Two spellings of one use then encode alike. An ID naming a decorator +// is written as the type's alone and a decorator nothing names is left out, so +// what one holds is compared only where a reference names it. It is a second +// implementation of the emitter's collapse // (docs/emitters/refine/decorators.md), until emitters/refine holds that one, // which replaces it. func folded(doc *ir.Document) (*ir.Document, *json.Marshalers) { @@ -85,8 +85,8 @@ func withoutTypes(doc *ir.Document, ids []ir.TypeID) *ir.Document { return own } -// use is what a decorator stands for: the first type along its Base chain that -// is no decorator, the chain's annotations, merged nearest first, and +// use is what a decorator names: the first type along its Base chain that is no +// decorator, the chain's annotations, merged nearest first, and // fallbackAnnotations, the Docs and Deprecation of that type, which a property, // parameter or header takes after the chain's, as a reference to the type lends // them (docs/ir/annotations.md#what-a-reference-carries-down). @@ -96,9 +96,9 @@ type use struct { fallbackAnnotations annotations } -// decoratorUses returns, for each decorator of types, what it stands for. A -// chain that returns to a decorator it passed collapses nowhere, so it is left -// out and its nodes kept. +// decoratorUses returns, for each decorator of types, what it names. A chain +// that returns to a decorator it passed collapses nowhere, so it is left out +// and its nodes kept. func decoratorUses(types ir.TypeRegistry) map[ir.TypeID]use { uses := map[ir.TypeID]use{} for id, td := range types { diff --git a/internal/harness/fold_internal_test.go b/internal/harness/fold_internal_test.go index c8c90f823..f0d9ba49c 100644 --- a/internal/harness/fold_internal_test.go +++ b/internal/harness/fold_internal_test.go @@ -223,12 +223,12 @@ func carrierSlots(doc *ir.Document, kind string) slots { } } -// TestFolded_ACarrierTakesTheDocsOfWhatItsDecoratorStandsFor pins the last -// step of the merge: a property, parameter or header takes the Docs and -// Deprecation of the type its decorator stands for where the carrier and the -// decorator set none, as a reference naming that type is lent them, and never -// its Examples. A union variant takes none of them. -func TestFolded_ACarrierTakesTheDocsOfWhatItsDecoratorStandsFor(t *testing.T) { +// TestFolded_ACarrierTakesTheDocsOfWhatItsDecoratorNames pins the last step of +// the merge: a property, parameter or header takes the Docs and Deprecation of +// the type its decorator names where the carrier and the decorator set none, as +// a reference naming that type is lent them, and never its Examples. A union +// variant takes none of them. +func TestFolded_ACarrierTakesTheDocsOfWhatItsDecoratorNames(t *testing.T) { for _, c := range []struct { kind string takesFallback bool @@ -271,8 +271,8 @@ func TestMergeDocs_TakesEveryField(t *testing.T) { } // TestMergeDeprecation_TakesEveryField holds mergeDeprecation to -// ir.Deprecation's fields: each is taken from the second where the first -// leaves it empty, and either stands where the other is nil. +// ir.Deprecation's fields: each is taken from the second where the first leaves +// it empty, and either is taken where the other is nil. func TestMergeDeprecation_TakesEveryField(t *testing.T) { fields := reflect.VisibleFields(reflect.TypeFor[ir.Deprecation]()) names := make([]string, 0, len(fields)) @@ -328,12 +328,12 @@ func TestDecoratorUses_FollowsAChainAndLeavesACycle(t *testing.T) { _, more := folded(&ir.Document{Types: types}) b, err := json.Marshal(types["type/x/a"], json.WithMarshalers(more)) require.NoError(t, err) - assert.Contains(t, string(b), `"target":"type/x/b"`, "a cycle's reference is written as it stands") + assert.Contains(t, string(b), `"target":"type/x/b"`, "a cycle's reference is written as it is") } -// TestFolded_AnIDNamingADecoratorNamesWhatItStandsFor pins the TypeID -// marshaler: a discriminator's mapping naming a decorator names its target. -func TestFolded_AnIDNamingADecoratorNamesWhatItStandsFor(t *testing.T) { +// TestFolded_AnIDNamingADecoratorNamesWhatItNames pins the TypeID marshaler: a +// discriminator's mapping naming a decorator names its target. +func TestFolded_AnIDNamingADecoratorNamesWhatItNames(t *testing.T) { doc := listOf(&ir.Scalar{TypeCommon: annotated(decID, "d"), Base: &ir.TypeRef{Target: objID}}) doc.Types["type/x/U"] = &ir.Union{ID: "type/x/U", Discriminator: &ir.Discriminator{Mapping: map[string]ir.TypeID{"a": decID}}} @@ -382,10 +382,10 @@ func TestFolded_ADocumentOfNoDecoratorIsItself(t *testing.T) { assert.Nil(t, more) } -// TestFolded_WhatNamesNoDecoratorIsWrittenAsItStands pins the fold's reach: a -// carrier naming no decorator is written as it stands beside one that does, -// and a use of a decorator holding nothing is a bare reference. -func TestFolded_WhatNamesNoDecoratorIsWrittenAsItStands(t *testing.T) { +// TestFolded_WhatNamesNoDecoratorIsWrittenAsItIs pins the fold's reach: a +// carrier naming no decorator is written as it is beside one that does, and a +// use of a decorator holding nothing is a bare reference. +func TestFolded_WhatNamesNoDecoratorIsWrittenAsItIs(t *testing.T) { plain := carrying("property", false) holder := func(text string) any { var doc struct { @@ -400,7 +400,7 @@ func TestFolded_WhatNamesNoDecoratorIsWrittenAsItStands(t *testing.T) { got := foldedText(t, plain) - assert.Empty(t, cmp.Diff(want, holder(got)), "the carrier is written as it stands") + assert.Empty(t, cmp.Diff(want, holder(got)), "the carrier is written as it is") assert.NotContains(t, got, `"use"`, "a use of a decorator holding nothing is a bare reference") assert.Contains(t, got, `"elementType": {`+"\n"+` "target": "type/x/Obj",`+"\n"+` "nullable": false`+"\n"+` }`) } diff --git a/internal/harness/harness_test.go b/internal/harness/harness_test.go index 196b51064..a67115d8b 100644 --- a/internal/harness/harness_test.go +++ b/internal/harness/harness_test.go @@ -182,10 +182,10 @@ func columnStart(t *testing.T, line, column string) int { // TestReport_OutcomeColumnIsSizedOnlyByLinesThatUseIt pins what the second // column is measured against. A result with no Detail has nothing to the right // of its outcome, so sizing the column to it pads every line that does carry a -// Detail out to a column standing empty on the line that set its width — the +// Detail out to a column left empty on the line that set its width — the // padding this report exists to stop emitting. The longest outcome the harness -// has goes on the line showing no detail, so widening the column is the only way -// the assertion below can fail. +// has goes on the line showing no detail, so widening the column is the only +// way the assertion below can fail. func TestReport_OutcomeColumnIsSizedOnlyByLinesThatUseIt(t *testing.T) { t.Parallel() lines := reportLines(t, harness.Report([]harness.Result{ diff --git a/internal/harness/helpers_internal_test.go b/internal/harness/helpers_internal_test.go index c6a8f2e41..28b7a0913 100644 --- a/internal/harness/helpers_internal_test.go +++ b/internal/harness/helpers_internal_test.go @@ -32,7 +32,7 @@ func tables() ([]ir.SourceInfo, []ir.Service, map[string][]string) { var stubFormat = compilers.SourceFormat{Name: "stub", Version: "1.0"} // stubCompiler is a compiler the engine does not register. It takes any source -// that mentions its marker, and lower stands for its lowering. +// that mentions its marker, and lower names its lowering. type stubCompiler struct { lower func(sources []compilers.Source) (*ir.Document, []ir.Diagnostic, error) } diff --git a/internal/harness/instance.go b/internal/harness/instance.go index 3b9aef721..3d0088244 100644 --- a/internal/harness/instance.go +++ b/internal/harness/instance.go @@ -7,7 +7,6 @@ import ( "context" "fmt" "reflect" - "slices" "strconv" "strings" @@ -18,11 +17,6 @@ import ( // type does not admit (docs/ir/values.md), which judges each instance. const codeOutsideType = "pass/default-outside-type" -// kindInference names the heuristic that reads a kind off a schema naming -// none (docs/compilers/openapi.md#policies), as a node's Provenance.Inferred -// lists it. -const kindInference = "kind-inference" - // admitted is the instance oracle: each valid instance the case at writes as a // default must draw no codeOutsideType at its carrier. The validate pass is the // judge; nothing here reads a value but its kind. It declines a case writing no @@ -54,7 +48,7 @@ func admitted(ctx context.Context, shardValue *shard, at []int, doc CaseDocument return declined(OracleInstance, DeclineNotJudged) } } - return excluded(valid, got.diags, held, got.doc) + return excluded(valid, got.diags) } // carrier is a place that holds a default as a value: the type it declares @@ -81,54 +75,15 @@ func carriers(doc *ir.Document) map[string]carrier { return held } -// excused reports whether a finding on carrierValue is the kind inference's -// known cost: the node carrierValue is checked against, past any alias of it -// (aliased), names kind-inference in its Provenance.Inferred, which narrows a -// schema admitting every kind to one, and the default is of another kind. A -// finding of what the default holds, a bound or a member, is the node's own and -// is never excused, nor is one on a node that carries no such mark or against a -// default of the node's kind. -func excused(doc *ir.Document, carrierValue carrier) bool { - td := aliased(doc, carrierValue.typ.Target) - var kind ir.ValueKind - switch td.(type) { - case *ir.Model, *ir.MapT: - kind = ir.ValueObject - case *ir.List, *ir.Tuple: - kind = ir.ValueList - default: - return false // a node of no one kind is not narrowed to a kind - } - inferred := strings.Split(string(td.Common().Provenance.Inferred), ",") - return slices.Contains(inferred, kindInference) && carrierValue.def.Kind != kind -} - -// aliased returns the node target names, past each scalar whose base is -// another node, as the validate pass judges a default against what an alias -// names: a use of an inferred node beside a bound or a description is such an -// alias. The chain holds at most one scalar per node of doc. -func aliased(doc *ir.Document, target ir.TypeID) ir.TypeDef { - td := doc.Types[target] - for range len(doc.Types) { - scalar, ok := td.(*ir.Scalar) - if !ok || scalar.Base == nil { - break - } - td = doc.Types[scalar.Base.Target] - } - return td -} - // excluded is the verdict on instances, each held at its carrier, given what // the run reported: found, naming each instance a codeOutsideType at its -// carrier excludes, and the message, or passed where none is. A finding excused -// is none. -func excluded(instances []Instance, diags []ir.Diagnostic, held map[string]carrier, doc *ir.Document) Verdict { +// carrier excludes, and the message, or passed where none is. The validate +// pass leaves alone a value of another kind than a node a heuristic shaped, +// the kind-inference policy's among them, so the suite's groups, which compile +// under it, need no excuse. +func excluded(instances []Instance, diags []ir.Diagnostic) Verdict { var names, lines []string for _, in := range instances { - if excused(doc, held[in.Node]) { - continue - } for _, diagnostic := range diags { if diagnostic.Code == codeOutsideType && diagnostic.Provenance.Node == in.Node { names = append(names, strconv.Quote(in.Name)) diff --git a/internal/harness/instance_internal_test.go b/internal/harness/instance_internal_test.go index f94ced2ae..2194cf130 100644 --- a/internal/harness/instance_internal_test.go +++ b/internal/harness/instance_internal_test.go @@ -130,15 +130,14 @@ const ( kindM = "property/openapi/components/schemas/O/properties/m" ) -// TestAdmitted_ExcusesAnOtherKindOnlyWhereTheKindWasInferred holds the verdict -// on a property of C defaulting to def under its schema to what the node it is -// checked against and the default's kind decide: a default of another kind -// than a node marked kind-inference is excused, and every other finding -// stands, among them one of a member, an element or a bound of a marked node, -// and any of an unmarked one. The validate pass judges no member, no element -// and no bound of the node a decorator names, so a row asking one has the -// finding drawn at the carrier. -func TestAdmitted_ExcusesAnOtherKindOnlyWhereTheKindWasInferred(t *testing.T) { +// TestAdmitted_AnInferredKindRefusesNothingAndEveryOtherFindingRemains holds +// the verdict on a property of C defaulting to def under its schema: a value of +// another kind than a node marked kind-inference, the default or one at any +// depth below it, draws nothing from the validate pass, and every other finding +// remains, among them one of a member, an element or a bound of a marked node, +// one beside a member of another kind, and any of an unmarked node. A row +// asking what the pass may not judge has the finding drawn. +func TestAdmitted_AnInferredKindRefusesNothingAndEveryOtherFindingRemains(t *testing.T) { const ( model = `"M": {"properties": {"a": {"type": "string"}}, "required": ["a"], "maxProperties": 1}` list = `"L": {"items": {"type": "string"}, "maxItems": 1}` @@ -146,6 +145,10 @@ func TestAdmitted_ExcusesAnOtherKindOnlyWhereTheKindWasInferred(t *testing.T) { nested = `"O": {"type": "object", "properties": {"m": {"properties": {"a": {"type": "string"}}, "default": "s"}}}` alias = `"A": {"allOf": [{"$ref": "#/components/schemas/L"}], "description": "d"}` aliasU = `"AU": {"allOf": [{"$ref": "#/components/schemas/U"}], "description": "d"}` + self = `"N": {"minimum": 30, "properties": {"foo": {"$ref": "#/components/schemas/N"}, "a": {"type": "string"}}}` + listOf = `"LN": {"type": "array", "items": {"$ref": "#/components/schemas/N"}}, ` + self + root = `"R": {"properties": {"foo": {"$ref": "#/components/schemas/R"}}, "additionalProperties": false}` + typedN = `"UN": {"type": "object", "properties": {"foo": {"$ref": "#/components/schemas/UN"}}}` ) tests := []struct { name string @@ -166,6 +169,14 @@ func TestAdmitted_ExcusesAnOtherKindOnlyWhereTheKindWasInferred(t *testing.T) { {"marked node nested in an unmarked one", nested, "O", `"s"`, false, kindM, `"t"`}, {"alias of a marked list against an object", list + ", " + alias, "A", `{"a": 1}`, false, "", ""}, {"alias of an unmarked model against a string", typed + ", " + aliasU, "AU", `"s"`, false, "", `"t"`}, + {"a member of another kind than the marked node it names", self, "N", `{"foo": 37}`, false, "", ""}, + {"a member's member refused by its type", self, "N", `{"foo": {"a": 1}}`, false, "", `"t"`}, + {"an excused member beside one refused by its type", self, "N", `{"foo": 37, "a": 1}`, false, "", `"t"`}, + {"an element of another kind than a marked node", listOf, "LN", `[37, {"a": "x"}]`, false, "", ""}, + {"an element refused by its member's type", listOf, "LN", `[37, {"a": 1}]`, false, "", `"t"`}, + {"a member of another kind than a closed marked node", root, "R", `{"foo": false}`, false, "", ""}, + {"a member a closed marked node does not declare", root, "R", `{"bar": false}`, false, "", `"t"`}, + {"a member of another kind than the unmarked node it names", typedN, "UN", `{"foo": 37}`, false, "", `"t"`}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/harness/openapicases/cases.go b/internal/harness/openapicases/cases.go index 7459546a1..2e48b4f7c 100644 --- a/internal/harness/openapicases/cases.go +++ b/internal/harness/openapicases/cases.go @@ -47,7 +47,11 @@ func versions() []version { // spellings returns the spellings, in the order the spelling axis lists them. func spellings() []string { - return []string{inline, beside, wrap, entry, entryFirst, nested, besideEntry} + return []string{ + inline, beside, wrap, entry, entryFirst, nested, besideEntry, + keywordOnEntry, bothOnEntries, kindOnEntry, + secondOnEntry, constructOnEntry, inlineSecondOnEntry, inlineConstructOnEntry, + } } // cases is the OpenAPI product: the tables each axis lists the values of. @@ -113,15 +117,19 @@ func coreValues(of []string) []harness.Value { } // spellingValues returns a value of each spelling, the gate running all but -// an entry written first, which lowers as the entry written last does -// (docs/compilers/openapi.md#allof-classification) and so repeats its -// findings: a nightly run records them under that entry. +// entryFirst, which repeats entry's findings, and the apart spellings, which +// write two constructs at full alone. func spellingValues(of []string) []harness.Value { values := coreValues(of) + like := map[string]string{ + entryFirst: entry, + secondOnEntry: wrap, + constructOnEntry: entry, + inlineSecondOnEntry: keywordOnEntry, + inlineConstructOnEntry: keywordOnEntry, + } for i, n := range of { - if n == entryFirst { - values[i].Like = entry - } + values[i].Like = like[n] } return values } @@ -144,13 +152,13 @@ func (c cases) Write(at []int) (harness.CaseDocument, bool) { if !ok { return harness.CaseDocument{}, false } - use, ok := c.spelt(written, s, target) + use, ok := c.spelt(written, s, target, version) if !ok { return harness.CaseDocument{}, false } paths, schemas := position.place(use) - if s != inline { + if !isBodySpelling(s) { schemas = append(schemas, member{targetSchema, target.body}) } data, err := encode(object{ @@ -170,7 +178,7 @@ func (c cases) Write(at []int) (harness.CaseDocument, bool) { if doc.Equal != nil && at[2] > 0 && at[3] > 0 { doc.Equal.Parts = c.parts(at) } - c.neighbours(&doc, version, target, at) + c.neighbours(&doc, version, target, written, at) return doc, true } @@ -191,14 +199,25 @@ func optionsFor(writtenValue written) map[string]string { } // parts returns the cases writing alone each keyword the case at writes in one -// unit, the rest alike: its construct with no second, and its second with no -// construct, which for a second named as a construct row is that row's case. +// unit or apart, the rest alike: its construct with no second, and its second +// with no construct, which for a second named as a construct row is that row's +// case. func (c cases) parts(at []int) [][]int { first := slices.Concat(at[:3], []int{0}, at[4:]) second := slices.Concat(at[:2], []int{0}, at[3:]) if row := c.rowOf(at[3]); row >= 0 { second[2], second[3] = 1+2*row, 0 } + switch c.spellings[at[5]] { + case secondOnEntry: + first[5], second[5] = slices.Index(c.spellings, wrap), slices.Index(c.spellings, entry) + case constructOnEntry: + first[5], second[5] = slices.Index(c.spellings, entry), slices.Index(c.spellings, wrap) + case inlineSecondOnEntry: + first[5], second[5] = slices.Index(c.spellings, inline), slices.Index(c.spellings, keywordOnEntry) + case inlineConstructOnEntry: + first[5], second[5] = slices.Index(c.spellings, keywordOnEntry), slices.Index(c.spellings, inline) + } return [][]int{first, second} } @@ -221,36 +240,61 @@ func (c cases) unit(at []int, versionValue version, targetValue target) (written components: slices.Concat(components, sec.components), entries: sec.entries, row: -1, + firstCount: len(members), stays: max(c.staysAt(at[2]), sec.stays), }, true } -// neighbours names, in doc, the cases the presence oracle compares the case at -// with: the case leaving the construct out, and, for a keyword something -// carries, the case writing its other value. The none construct and a -// keyword's other value name none: the latter is asked through its keyword. -// Left out of a unit whose second writes no member, the construct leaves an -// entry spelling wrap's document; left beside a row's second, it leaves that -// row's case. A keyword the target's body writes already is replaced by the -// construct, so no case leaves it out (CaseDocument.Replaces). -func (c cases) neighbours(doc *harness.CaseDocument, versionValue version, targetValue target, at []int) { +// neighbours names, in doc, the cases the presence oracle compares the case at, +// writing unit, with: the case leaving the construct out, and, for a keyword +// something carries there or one the target's body writes already, which it +// replaces (CaseDocument.Replaces), its other value. The none construct and a +// keyword's other value name none. Leaving the construct out maps apart +// spellings to the remaining construct's spelling, empty entry spellings to +// wrap, body-split spellings without a row second to inline, and row seconds to +// that row's case; one in another spelling is compared relocated +// (CaseDocument.RelocateAbsent). +func (c cases) neighbours(doc *harness.CaseDocument, versionValue version, targetValue target, unit written, at []int) { if at[2] == 0 || (at[2]-1)%2 != 0 { return } construct := c.constructs[(at[2]-1)/2] doc.Absent = slices.Concat(at[:2], []int{0}, at[3:]) - if row := c.rowOf(at[3]); row >= 0 { + row := c.rowOf(at[3]) + if row >= 0 { doc.Absent[2], doc.Absent[3] = 1+2*row, 0 // the row's second alone is the row's case - } else if writesWrapEmpty(c.spellings[at[5]]) { - if sec, _ := c.secondAt(at[3], versionValue, targetValue); len(sec.members) == 0 { - doc.Absent[5] = slices.Index(c.spellings, wrap) // an entry saying nothing writes wrap's document - } } - doc.Carried, doc.Reason = construct.reason == "", construct.reason - if doc.Carried { - doc.Other = slices.Concat(at[:2], []int{at[2] + 1}, at[3:]) + doc.Absent[5] = c.absentSpelling(c.spellings[at[5]], at[3], row, versionValue, targetValue) + reason := construct.reason + if reason == "" && construct.saysNothingIn != nil { + reason = construct.saysNothingIn(targetValue, unit, c.spellings[at[5]]) } + doc.Carried, doc.Reason = reason == "", reason doc.Replaces = slices.ContainsFunc(targetValue.body, func(memberValue member) bool { return memberValue.name == construct.keyword }) + if doc.Carried || doc.Replaces { + doc.Other = slices.Concat(at[:2], []int{at[2] + 1}, at[3:]) + } + doc.RelocateAbsent = doc.Absent[5] != at[5] && doc.Equal != nil && !doc.Replaces +} + +// absentSpelling returns the spelling index of the case leaving the construct +// out of a case written in spelling beside secondIndex (row >= 0 when +// secondIndex names a construct row). +func (c cases) absentSpelling(spelling string, secondIndex, row int, versionValue version, targetValue target) int { + facts := spellingTable[spelling] + switch { + case facts.absent != "": + return slices.Index(c.spellings, facts.absent) + case row >= 0: + return slices.Index(c.spellings, spelling) + case facts.kind == bodySplitKind: + return slices.Index(c.spellings, inline) + case facts.writesWrapEmpty: + if secondWritten, _ := c.secondAt(secondIndex, versionValue, targetValue); len(secondWritten.members) == 0 { + return slices.Index(c.spellings, wrap) // an entry saying nothing writes wrap's document + } + } + return slices.Index(c.spellings, spelling) } // holds reports whether at names a case of c: one index per axis, each within diff --git a/internal/harness/openapicases/cases_test.go b/internal/harness/openapicases/cases_test.go index 451daaf45..b1599b29c 100644 --- a/internal/harness/openapicases/cases_test.go +++ b/internal/harness/openapicases/cases_test.go @@ -18,6 +18,18 @@ import ( "github.com/dexpace/morphic/ir" ) +// Advice for a record line the tests refuse, named once so each says the same: +// a line's reason is a key of Reasons, in export_test.go, which cites the open +// issue its finding is recorded under. +const ( + unreasonedAdvice = "a line whose reason Reasons does not name: give it a reason key from Reasons " + + "(internal/harness/openapicases/export_test.go) that cites the open issue its finding is recorded under, " + + "or fix the finding" + changedAdvice = "a line whose finding changed: fix the finding, or run -update and give the line a reason " + + "key from Reasons (internal/harness/openapicases/export_test.go) that cites the open issue the " + + "changed finding is recorded under" +) + // shards returns the coordinates of every case of cases pick admits, by the // case's version and target. func shards(t *testing.T, cases harness.Cases, pick func([]int) bool) map[[2]int][][]int { @@ -109,8 +121,8 @@ func eachCoreCaseCompilesWithNoError(t *testing.T, cases harness.Cases) { // version and target, as the harness's first three oracles hold a spec: // verified, so a broken invariant or a panic fails the run, and with no error // diagnostic. Each case is a valid document of its version, so a case the -// compiler refuses is the writer's defect. An info or a warning stands: it is -// the compiler's account of a valid construct, which the case oracles judge. +// compiler refuses is the writer's defect. An info or a warning is allowed: it +// is the compiler's account of a valid construct, which the case oracles judge. func compilesWithNoError(t *testing.T, harnessCases harness.Cases, byShard map[[2]int][][]int) { t.Helper() axes := harnessCases.Axes() @@ -207,8 +219,8 @@ func eachCaseWritesADocumentOfItsOwn(t *testing.T, cases harness.Cases, minSourc } // TestNew_TheAxesInTheirOrder pins the axes' order and the values a later -// version, a narrowed target, a second construct or an entry written first is -// recorded under. +// version, a narrowed target, a second construct, a reordered entry, or an +// apart placement is recorded under. func TestNew_TheAxesInTheirOrder(t *testing.T) { axes := openapicases.New().Axes() names := make([]string, len(axes)) @@ -226,8 +238,13 @@ func TestNew_TheAxesInTheirOrder(t *testing.T) { for _, value := range axes[3].Values[1:] { assert.Equal(t, "none", value.Like, "a second construct, %s, is recorded under none", value.Name) } - assert.Equal(t, []harness.Value{{Name: "inline"}, {Name: "beside"}, {Name: "wrap"}, {Name: "entry"}, - {Name: "entryFirst", Like: "entry"}, {Name: "nested"}, {Name: "besideEntry"}}, axes[5].Values) + assert.Equal(t, []harness.Value{ + {Name: "inline"}, {Name: "beside"}, {Name: "wrap"}, {Name: "entry"}, + {Name: "entryFirst", Like: "entry"}, {Name: "nested"}, {Name: "besideEntry"}, + {Name: "keywordOnEntry"}, {Name: "bothOnEntries"}, {Name: "kindOnEntry"}, + {Name: "secondOnEntry", Like: "wrap"}, {Name: "constructOnEntry", Like: "entry"}, + {Name: "inlineSecondOnEntry", Like: "keywordOnEntry"}, {Name: "inlineConstructOnEntry", Like: "keywordOnEntry"}, + }, axes[5].Values) assert.Equal(t, []harness.Value{{Name: "component"}, {Name: "property"}, {Name: "items"}, {Name: "additionalProperties"}, {Name: "branch"}, {Name: "anyOfBranch"}, {Name: "prefixItem"}, {Name: "patternProperty"}, {Name: "contentSchema"}, {Name: "parameter"}, {Name: "requestBody"}, {Name: "responseBody"}, {Name: "header"}}, axes[4].Values) @@ -235,7 +252,7 @@ func TestNew_TheAxesInTheirOrder(t *testing.T) { func TestNew_WritesNothingOutsideTheProduct(t *testing.T) { cases := openapicases.New() - for _, at := range [][]int{nil, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 6}, {0, -1, 0, 0, 0, 0}} { + for _, at := range [][]int{nil, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 14}, {0, -1, 0, 0, 0, 0}} { _, ok := cases.Write(at) assert.False(t, ok, "%v", at) } @@ -251,7 +268,7 @@ func TestRecord_ReadsEachCaseOraclesRecord(t *testing.T) { recorded, err := openapicases.Record(oracle) require.NoError(t, err, oracle) _, _, _, unreasoned := recorded.Judge(nil, openapicases.Reasons()) - assert.Empty(t, unreasoned, oracle) + assert.Empty(t, unreasoned, "%s: %s", oracle, unreasonedAdvice) every, err := openapicases.FullRecord(oracle) require.NoError(t, err, oracle) for name := range recorded { diff --git a/internal/harness/openapicases/constructs.go b/internal/harness/openapicases/constructs.go index 2381c2b98..1be071432 100644 --- a/internal/harness/openapicases/constructs.go +++ b/internal/harness/openapicases/constructs.go @@ -27,6 +27,10 @@ type construct struct { components object // reason says why nothing carries the keyword; empty for one carried. reason string + // saysNothingIn says why the keyword carries nothing in the unit a case + // writes it in, on a target in a spelling, and "" where it carries + // something; nil for a keyword reason decides alone. + saysNothingIn func(targetValue target, unit written, spelling string) string // stays is where the spellings write a keyword none moves; the comment on // each such row of the table says why. stays stays @@ -113,6 +117,15 @@ func exclusive(keyword, bound string) func(target, version) [2]object { } } +// formats is the values of a format: two the target's type gives meaning to, +// the integer widths for an integer and a date and an instant for a string. +func formats(targetValue target, _ version) [2]object { + if targetValue.name == integerTarget { + return [2]object{{{"format", raw(`"int32"`)}}, {{"format", raw(`"int64"`)}}} + } + return [2]object{{{"format", raw(`"date"`)}}, {{"format", raw(`"date-time"`)}}} +} + // narrowing is the values of a union keyword: two branches, one of which // says more than the target, or for an object two shapes, so writing the union // is observable. A union whose branches the target already says changes @@ -176,8 +189,8 @@ func sharedConstructs() []construct { {keyword: "allOf", targets: []string{objectTarget}, values: fixed("allOf", `[{"type": "object", "properties": {"q": {"type": "integer"}}}]`, `[{"type": "object", "properties": {"q": {"type": "boolean"}}}]`)}, - {keyword: "oneOf", values: narrowing("oneOf")}, - {keyword: "anyOf", values: narrowing("anyOf")}, + {keyword: "oneOf", values: narrowing("oneOf"), saysNothingIn: unionSaidBySet}, + {keyword: "anyOf", values: narrowing("anyOf"), saysNothingIn: unionSaidBySet}, {keyword: "not", values: fixed("not", `{"enum": ["n"]}`, `{"enum": ["z"]}`)}, {keyword: "items", targets: arrayTargets(), values: fixed("items", `{"type": "integer"}`, `{"type": "boolean"}`)}, {keyword: "properties", targets: objectTargets(), values: fixed("properties", @@ -187,7 +200,7 @@ func sharedConstructs() []construct { {keyword: "description", values: fixed("description", `"D"`, `"Z"`)}, // Not of the formatted target: its body writes format already, so there // the construct would write the string target's documents again. - {keyword: "format", targets: []string{stringTarget}, values: fixed("format", `"date"`, `"date-time"`)}, + {keyword: "format", targets: []string{stringTarget, integerTarget}, values: formats}, {keyword: "default", values: instances("default", "%s")}, {keyword: "readOnly", values: fixed("readOnly", "true", "false")}, {keyword: "writeOnly", values: fixed("writeOnly", "true", "false")}, @@ -195,10 +208,81 @@ func sharedConstructs() []construct { } } +// nullableWidensNothing says why a 3.0 nullable: true carries nothing in unit, +// written on targetValue in spelling: where the conjunction holds a reference +// and a second one, or a conjunct beside it writing a union, structure or a +// value set, the nullable-inference policy widens nothing, and the conjunct +// conjoins the null the keyword adds to its type back out +// (docs/compilers/openapi.md#nullable). It is "" where the keyword widens. +func nullableWidensNothing(targetValue target, unit written, spelling string) string { + references, beside := len(unit.entries), unit.members + if isBodySpelling(spelling) { + beside = slices.Concat(beside, targetValue.body) + } else { + references++ + } + if references == 0 || references == 1 && !slices.ContainsFunc(beside, stopsWidening) { + return "" + } + return "a conjunct beside it excludes null; the nullable-inference policy reads only a lone reference, " + + "beside which no conjunct writes a union, structure or value set, as widening (docs/compilers/openapi.md#nullable)" +} + +// stopsWidening reports whether memberValue, a keyword beside a reference, +// keeps the nullable-inference policy from widening it: a union, a keyword +// applying to an instance's members or elements, or a value set, none of +// whose values in a case is null. +func stopsWidening(memberValue member) bool { + switch memberValue.name { + case "oneOf", "anyOf", "enum", "const", "properties", "items", "prefixItems", "additionalProperties", "patternProperties": + return true + default: + return false + } +} + +// unionSaidBySet says why a oneOf or an anyOf carries nothing in unit, written +// on targetValue in spelling: beside a value set written at the use, and no +// other union there, each member of which narrowing's union admits by exactly +// one branch (narrowingAdmitsSetMembers), the union says nothing, and the +// position is the value set (docs/compilers/openapi.md#union-beside-structure). +// It is "" where the union carries something: no such value set is written at +// the use, or a second union sits beside it, which leaves it as before. +func unionSaidBySet(targetValue target, unit written, spelling string) string { + atUse := unit.members + if isBodySpelling(spelling) { + atUse = targetValue.body.with(unit.members) + } + unions := slices.DeleteFunc(slices.Clone(atUse), func(memberValue member) bool { + return memberValue.name != "oneOf" && memberValue.name != "anyOf" + }) + if !narrowingAdmitsSetMembers(targetValue) || len(unions) > 1 || + !slices.ContainsFunc(atUse, func(memberValue member) bool { return memberValue.name == "enum" || memberValue.name == "const" }) { + return "" + } + return "every member of the value set beside it satisfies it, so it says nothing: the position is the value set " + + "(docs/compilers/openapi.md#union-beside-structure)" +} + +// narrowingAdmitsSetMembers reports whether each value narrowing writes on +// targetValue admits, by exactly one branch, every member of a value set a case +// writes beside it: the target's first instance, which the enum row's first +// value writes, and the members of an enum its body writes. A formatted +// string's instances are longer than the first branch's maxLength, and an +// object's, an array's or a map's are no scalar, which no member is judged as. +func narrowingAdmitsSetMembers(targetValue target) bool { + switch targetValue.name { + case stringTarget, enumTarget, integerTarget, unionTarget: + return true + default: + return false + } +} + // openAPIConstructs are the fields OpenAPI itself defines on a Schema Object. func openAPIConstructs() []construct { return []construct{ - {keyword: "nullable", span: only30, values: fixed("nullable", "true", "false")}, + {keyword: "nullable", span: only30, values: fixed("nullable", "true", "false"), saysNothingIn: nullableWidensNothing}, // It routes the union written beside it (docs/compilers/openapi.md#allof-inline-residue). {keyword: "discriminator", targets: []string{objectTarget}, values: fixed("discriminator", `{"propertyName": "a"}`, `{"propertyName": "b"}`), stays: besideToo}, diff --git a/internal/harness/openapicases/doc.go b/internal/harness/openapicases/doc.go index d927b7ebb..43488b605 100644 --- a/internal/harness/openapicases/doc.go +++ b/internal/harness/openapicases/doc.go @@ -5,8 +5,8 @@ // product of version, target, construct, second construct, position and // spelling, each case one document for the harness's case oracles. FullRecord // holds what each case oracle is known to find, at the core cases and at those -// outside it that the core does not explain, each finding with the reason it -// stands, which names the open issue tracking it. It is test/tooling +// outside it that the core does not explain, each finding with the reason it is +// recorded, which names the open issue tracking it. It is test/tooling // infrastructure, not part of the compile pipeline: the harness reaches the // compiler through the engine alone. package openapicases diff --git a/internal/harness/openapicases/document.go b/internal/harness/openapicases/document.go index fefb04cbf..be11fdf93 100644 --- a/internal/harness/openapicases/document.go +++ b/internal/harness/openapicases/document.go @@ -24,7 +24,7 @@ type member struct { // iteration decides a document's text. type object []member -// raw is JSON text written as it stands, such as a construct's value. +// raw is JSON text written as it is, such as a construct's value. type raw string // with returns o with each member of more set: one o names already takes its diff --git a/internal/harness/openapicases/export_test.go b/internal/harness/openapicases/export_test.go index 0f43567e3..8df27417f 100644 --- a/internal/harness/openapicases/export_test.go +++ b/internal/harness/openapicases/export_test.go @@ -15,18 +15,17 @@ func Record(oracle harness.Oracle) (harness.Recorded, error) { return harness.ReadRecorded([]byte(core)) } -// Reasons maps each reason a record's line may give to the issue saying why -// its finding stands, which the tests holding each record judge it by. +// Reasons maps each reason a record's line may give to the issue saying why its +// finding is recorded, which the tests holding each record judge it by. func Reasons() map[string]string { return map[string]string{ - "entry-missing-items": "#2048: a 3.0 type: array on an allOf entry writing no items is warned of, where " + - "beside the allOf the conjunction's items answers it", - "entry-type-list": "#2039: a type list on an inline allOf entry over an object composition is kept " + - "verbatim, where beside the allOf it is read", - "closure-beside-union": "#2047: an additionalProperties or patternProperties beside a oneOf or anyOf on " + - "one inline allOf entry keeps the entry whole, where beside the allOf each variant takes it", - "residue-per-variant": "#2054: a keyword kept verbatim beside a union on an inline allOf entry is " + - "copied onto each variant the union distributes into, where beside the allOf it is kept once on " + - "the Union", + "split-degraded-reports": "#2072: unread keywords split across the outer schema and an allOf entry " + + "draw two openapi/degraded-construct reports, where written together they draw one", + "entry-value-set": "#2119: an enum or const split from its body's type or sibling keywords across " + + "allOf entries keeps or reports unread keywords differently from when written flat", + "entry-competing-value-set": "#2118: a const and enum, or a union and enum over a union target, " + + "placed apart across allOf entries drops or keeps the passed-over keyword differently", + "custom-vocabulary": "#2376: a schema naming a custom meta-schema is read with every vocabulary its " + + "OpenAPI version's dialect holds, so a keyword of one the meta-schema leaves out still asserts", } } diff --git a/internal/harness/openapicases/full_test.go b/internal/harness/openapicases/full_test.go index 83cda4432..549c4ba80 100644 --- a/internal/harness/openapicases/full_test.go +++ b/internal/harness/openapicases/full_test.go @@ -74,9 +74,9 @@ func TestFull_EveryCaseHoldsTheRecords(t *testing.T) { } unlisted, changed, stale, unreasoned := record.Judge(found, openapicases.Reasons()) report(t, path, "a finding no record explains: fix the compiler, or list it with its reason (-full -update)", unlisted) - report(t, path, "a line whose finding changed", changed) + report(t, path, changedAdvice, changed) report(t, path, "a line whose finding is gone: delete it (-full -update)", stale) - report(t, path, "a line whose reason Reasons does not name", unreasoned) + report(t, path, unreasonedAdvice, unreasoned) } } @@ -184,7 +184,7 @@ func TestFull_EachLineNamesACaseOutsideTheCore(t *testing.T) { } unlisted, changed, _, unreasoned := every.Judge(nil, openapicases.Reasons()) assert.Empty(t, slices.Concat(unlisted, changed)) - assert.Empty(t, unreasoned, "a line whose reason Reasons does not name: give it the reason of its issue") + assert.Empty(t, unreasoned, unreasonedAdvice) } } diff --git a/internal/harness/openapicases/groups.go b/internal/harness/openapicases/groups.go index 1d2029fd1..986cd6526 100644 --- a/internal/harness/openapicases/groups.go +++ b/internal/harness/openapicases/groups.go @@ -51,7 +51,7 @@ func Groups() harness.Cases { versions: slices.DeleteFunc(versions(), func(versionValue version) bool { return !versionValue.dialect }), groups: groups, positions: slices.DeleteFunc(positions(), func(positionValue position) bool { return positionValue.carry == nil }), - spellings: slices.DeleteFunc(spellings(), func(s string) bool { return s == inline }), + spellings: useSpellings(), suite: err, } } diff --git a/internal/harness/openapicases/groups_test.go b/internal/harness/openapicases/groups_test.go index 19d6b8444..80a8674a3 100644 --- a/internal/harness/openapicases/groups_test.go +++ b/internal/harness/openapicases/groups_test.go @@ -28,8 +28,8 @@ func TestGroups_TheAxesInTheirOrder(t *testing.T) { assert.Equal(t, []harness.Value{{Name: "3.1.0"}, {Name: "3.2.0", Like: "3.1.0"}}, axes[0].Values) assert.Equal(t, []harness.Value{{Name: "property"}, {Name: "parameter", Like: "property"}, {Name: "header", Like: "property"}}, axes[2].Values) - assert.Equal(t, openapicases.New().Axes()[5].Values[1:], axes[3].Values, - "the spellings the schema cases list but inline: a group's target is named by $ref alone") + assert.Equal(t, openapicases.New().Axes()[5].Values[1:7], axes[3].Values, + "the single-unit $ref spellings: a group's target is named by $ref alone") groups, err := openapicases.SuiteGroups() require.NoError(t, err) diff --git a/internal/harness/openapicases/instances_test.go b/internal/harness/openapicases/instances_test.go index 1f3654ac9..29ad27f23 100644 --- a/internal/harness/openapicases/instances_test.go +++ b/internal/harness/openapicases/instances_test.go @@ -26,9 +26,9 @@ const ( // TestCore_ValidInstancesAreAdmitted holds each valid instance of the test // suite's groups, written as a default at each core position, to the type its // carrier compiles to. An instance the type excludes, and a group the oracle -// cannot ask, is the record's, each line with the reason it stands, so a group -// that starts to decline fails as a new exclusion does. The presence oracle -// declines each case: a group writes no construct. +// cannot ask, is the record's, each line with the reason it is recorded, so a +// group that starts to decline fails as a new exclusion does. The presence +// oracle declines each case: a group writes no construct. func TestCore_ValidInstancesAreAdmitted(t *testing.T) { t.Parallel() results := groupResults(t) @@ -48,7 +48,7 @@ func TestCore_ValidInstancesAreAdmitted(t *testing.T) { } unlisted, changed, stale, unreasoned := record.Judge(found, openapicases.Reasons()) assert.Empty(t, unlisted, "a finding the record does not list: fix the compiler, or list it with its reason (-update)") - assert.Empty(t, changed) + assert.Empty(t, changed, changedAdvice) assert.Empty(t, stale, "a line whose finding is gone: delete it (-update)") - assert.Empty(t, unreasoned) + assert.Empty(t, unreasoned, unreasonedAdvice) } diff --git a/internal/harness/openapicases/presence_test.go b/internal/harness/openapicases/presence_test.go index 903b70548..32105f2ad 100644 --- a/internal/harness/openapicases/presence_test.go +++ b/internal/harness/openapicases/presence_test.go @@ -41,7 +41,7 @@ func presence(t *testing.T, result harness.Result) harness.Verdict { // table, at every core position, to the document: written it changes what // compiles, and again when its value changes, and a keyword nothing carries // changes nothing. What the oracle finds is the record's, each line with the -// reason it stands; the four keywords nothing carries are asked at every +// reason it is recorded; the four keywords nothing carries are asked at every // position and found equal to the case leaving them out. No case faults: a // fault gives no verdict, so -update would delete the line of a case it ended. func TestCore_EveryKeywordIsCarriedEverywhere(t *testing.T) { @@ -59,9 +59,9 @@ func TestCore_EveryKeywordIsCarriedEverywhere(t *testing.T) { } unlisted, changed, stale, unreasoned := record.Judge(found, openapicases.Reasons()) assert.Empty(t, unlisted, "a finding the record does not list: fix the compiler, or list it with its reason (-update)") - assert.Empty(t, changed) + assert.Empty(t, changed, changedAdvice) assert.Empty(t, stale, "a line whose finding is gone: delete it (-update)") - assert.Empty(t, unreasoned) + assert.Empty(t, unreasoned, unreasonedAdvice) askedAt := map[string]map[string]int{} for _, result := range results { @@ -126,14 +126,13 @@ func keywords(t *testing.T) []string { } // TestWrite_NamesTheNeighboursOfEachKeyword holds each case the presence -// oracle asks to its neighbours: the case leaving the keyword out, which -// differs in the construct alone, or beside a second named as a construct is -// that construct's case, or in a spelling writing the keywords on an entry, -// beside a second writing no member, none or a second $ref, which is an allOf -// entry, is wrap's; and for a -// keyword something carries the case writing its other value, one construct -// on. The case writing nothing and a keyword's other value name none. A second -// is held at one position (alone). +// oracle asks to its neighbours: the case leaving the construct out (remapping +// apart spellings to the remaining construct's spelling, empty entry spellings +// to wrap, body-split spellings without a row second to inline, and row seconds +// to that row's case), compared relocated where so remapped, and for a carried +// keyword or one replacing a member of the target's body the case writing its +// other value. The none construct and a keyword's other value name none. A +// second is held at one position (alone). func TestWrite_NamesTheNeighboursOfEachKeyword(t *testing.T) { cases := openapicases.New() axes := cases.Axes() @@ -158,19 +157,42 @@ func TestWrite_NamesTheNeighboursOfEachKeyword(t *testing.T) { absent := with([]int{0}) second := axes[3].Values[at[3]].Name row := slices.IndexFunc(axes[2].Values, func(value harness.Value) bool { return value.Name == second }) + spellingIndex := func(spelling string) int { + return slices.IndexFunc(axes[5].Values, func(value harness.Value) bool { return value.Name == spelling }) + } switch s := axes[5].Values[at[5]].Name; { case second != "none" && row >= 0: absent[2], absent[3] = row, 0 // a second named as a construct, alone, is that construct's case + switch s { + case "secondOnEntry": + absent[5] = spellingIndex("entry") + case "constructOnEntry": + absent[5] = spellingIndex("wrap") + case "inlineSecondOnEntry": + absent[5] = spellingIndex("keywordOnEntry") + case "inlineConstructOnEntry": + absent[5] = spellingIndex("inline") + } + case s == "secondOnEntry": + absent[5] = spellingIndex("entry") + case s == "constructOnEntry": + absent[5] = spellingIndex("wrap") + case s == "keywordOnEntry" || s == "bothOnEntries" || s == "kindOnEntry": + absent[5] = spellingIndex("inline") case (second == "none" || second == "secondRef") && (s == "entry" || s == "entryFirst" || s == "besideEntry"): - absent[5] = slices.IndexFunc(axes[5].Values, func(value harness.Value) bool { return value.Name == "wrap" }) + absent[5] = spellingIndex("wrap") } assert.Equal(t, absent, doc.Absent, "%v", at) + assert.Equal(t, absent[5] != at[5] && doc.Equal != nil && !doc.Replaces, doc.RelocateAbsent, + "%v: a neighbour in another spelling is compared relocated", at) assert.Equal(t, doc.Carried, doc.Reason == "", "%v: a keyword nothing carries says why", at) if doc.Replaces { replaced = append(replaced, axes[1].Values[at[1]].Name+"/"+name) } if !doc.Carried { kept = append(kept, name) + } + if !doc.Carried && !doc.Replaces { assert.Nil(t, doc.Other, "%v", at) continue } @@ -178,8 +200,82 @@ func TestWrite_NamesTheNeighboursOfEachKeyword(t *testing.T) { assert.Equal(t, name+"~", axes[2].Values[doc.Other[2]].Name, "%v", at) } slices.Sort(kept) - assert.Equal(t, notCarried, slices.Compact(kept)) + assert.Equal(t, slices.Concat(notCarried, []string{"anyOf", "nullable", "oneOf"}), slices.Compact(kept), + "the controls, nullable where the policy widens nothing (TestWrite_ANullableCarriesNothingWhereItWidensNothing), "+ + "and a union beside a value set it admits (TestWrite_AUnionCarriesNothingBesideAValueSetItAdmits)") slices.Sort(replaced) assert.Equal(t, []string{"array/items", "enum/enum", "map/additionalProperties", "object/properties", "union/oneOf"}, slices.Compact(replaced), "the keyword a target writes already is replaced, not added") } + +// TestWrite_AUnionCarriesNothingBesideAValueSetItAdmits pins the contexts a +// oneOf or an anyOf carries nothing in, each saying why: beside a value set +// written at the use, every member of which it admits, and no other union +// there, it says nothing. Beside a value set written behind the target's +// reference or of members no scalar, with a second union beside it, or with +// no value set, it is carried. A oneOf the union target writes already is +// replaced, and names its other value. +func TestWrite_AUnionCarriesNothingBesideAValueSetItAdmits(t *testing.T) { + cases := openapicases.New() + for _, tc := range []struct { + name string + carried bool + }{ + {"3.1.0/string/anyOf/enum/component/beside", false}, + {"3.0.3/integer/oneOf/enum/property/inlineSecondOnEntry", false}, + {"3.1.0/enum/anyOf/none/component/inline", false}, + {"3.2.0/enum/oneOf/none/items/kindOnEntry", false}, + {"3.1.0/union/anyOf/enum/component/wrap", false}, + {"3.1.0/union/oneOf/enum/component/inline", false}, + {"3.1.0/union/anyOf/enum/component/inline", true}, + {"3.1.0/enum/anyOf/none/component/beside", true}, + {"3.1.0/array/oneOf/enum/component/inline", true}, + {"3.1.0/object/anyOf/enum/component/beside", true}, + {"3.1.0/formatted/anyOf/none/component/inline", true}, + {"3.1.0/string/oneOf/none/component/inline", true}, + } { + i, ok := indexIn(cases.Axes(), strings.Split(tc.name, "/")) + require.True(t, ok, tc.name) + at, err := harness.Coordinates(cases, i) + require.NoError(t, err) + doc, ok := cases.Write(at) + require.True(t, ok, tc.name) + assert.Equal(t, tc.carried, doc.Carried, tc.name) + assert.Equal(t, tc.carried, doc.Reason == "", tc.name) + assert.Equal(t, tc.carried || doc.Replaces, doc.Other != nil, tc.name) + } +} + +// TestWrite_ANullableCarriesNothingWhereItWidensNothing pins the contexts a 3.0 +// nullable: true carries nothing in, each saying why: a conjunction holding a +// reference, the target's or a second's, beside which a conjunct writes a +// union, a value set or structure, or which holds two. Where the policy +// widens the one reference, or the conjunction holds none, it is carried. +func TestWrite_ANullableCarriesNothingWhereItWidensNothing(t *testing.T) { + cases := openapicases.New() + for _, tc := range []struct { + name string + carried bool + }{ + {"3.0.3/string/nullable/oneOf/component/beside", false}, + {"3.0.3/string/nullable/enum/property/wrap", false}, + {"3.0.3/string/nullable/secondRef/items/entry", false}, + {"3.0.3/object/nullable/properties/component/secondOnEntry", false}, + {"3.0.3/object/nullable/additionalProperties/component/besideEntry", false}, + {"3.0.3/object/nullable/secondRef/component/kindOnEntry", false}, + {"3.0.3/string/nullable/secondRef/component/inline", true}, + {"3.0.3/string/nullable/oneOf/component/inline", true}, + {"3.0.3/string/nullable/none/component/beside", true}, + {"3.0.3/string/nullable/description/component/beside", true}, + {"3.0.3/string/nullable/targetType/component/entry", true}, + } { + i, ok := indexIn(cases.Axes(), strings.Split(tc.name, "/")) + require.True(t, ok, tc.name) + at, err := harness.Coordinates(cases, i) + require.NoError(t, err) + doc, ok := cases.Write(at) + require.True(t, ok, tc.name) + assert.Equal(t, tc.carried, doc.Carried, tc.name) + assert.Equal(t, tc.carried, doc.Reason == "", tc.name) + } +} diff --git a/internal/harness/openapicases/seconds.go b/internal/harness/openapicases/seconds.go index e687f87db..e44be96a4 100644 --- a/internal/harness/openapicases/seconds.go +++ b/internal/harness/openapicases/seconds.go @@ -11,7 +11,8 @@ import ( // secondSchema is the component the secondRef second construct names. const secondSchema = "S" -// second is a keyword a case writes beside its construct, in the same unit. +// second is a keyword a case writes beside its construct, in the same unit, or +// apart under an apart spelling. // One named as a construct row writes that row's first value, said of the // row's targets and written at its versions and spellings, so the case // writing it beside no construct is the row's own case and writes nothing. @@ -89,17 +90,18 @@ func secondRef(targetValue target, _ version) (written, bool) { // written is what a second writes beside a construct, or a case in one unit: // its members, the components they name, the index of the construct row whose -// first value it is, -1 for a second of no row, and where that row is written. +// first value it is, -1 for a second of no row, how many members a case's +// construct writes before its second's, and where that row is written. // entries are allOf entries naming schemas by $ref, which every spelling -// writes right after the target's reference: moved with the members, an entry -// written first would also move them before that reference, reordering the -// composition's mixins, which the order written decides -// (docs/compilers/openapi.md#allof-classification), so the two spellings would -// differ by more than the spelling. +// writes right after the target's reference: written first, they would reorder +// the composition's mixins, which the order written decides +// (docs/compilers/openapi.md#allof-classification), so two spellings would +// differ by more than their spelling. type written struct { members, components object entries []any row int + firstCount int stays stays } @@ -146,9 +148,11 @@ func (c cases) secondAt(j int, versionValue version, targetValue target) (writte // fits reports whether the case at can write sec, its second, beside first, its // construct's members, on targetValue: not beside a construct the second -// excludes, nor writing a keyword first writes; and at inline neither restating -// targetValue's body nor, as a row's value, replacing a member of it, so that -// the merged document would no longer say which keyword is the second. +// excludes, nor writing a keyword first writes, nor writing the document the +// case swapping the two writes (duplicatesSwapped); and at a spelling writing +// the body neither restating targetValue's body nor, as a row's value, +// replacing a member of it, so the merged document still says which keyword is +// the second. func (c cases) fits(at []int, sec written, first object, targetValue target) bool { if at[2] > 0 { if _, excluded := c.seconds[at[3]].excludes[c.constructs[(at[2]-1)/2].keyword]; excluded { @@ -158,13 +162,45 @@ func (c cases) fits(at []int, sec written, first object, targetValue target) boo if slices.ContainsFunc(sec.names(), func(name string) bool { return slices.ContainsFunc(first, named(name)) }) { return false } - if c.spellings[at[5]] != inline { + s := c.spellings[at[5]] + if c.duplicatesSwapped(at, s, sec, first, targetValue) { + return false + } + if !isBodySpelling(s) { return true } replaces := slices.ContainsFunc(sec.members, func(memberValue member) bool { return slices.ContainsFunc(targetValue.body, sameName(memberValue)) }) return !c.seconds[at[3]].restates && (sec.row < 0 || !replaces) } +// duplicatesSwapped reports whether the case at would write the same document +// as the case swapping construct and second: in constructOnEntry and +// inlineConstructOnEntry where both are row seconds at first value (unless +// inline's replacement filter excludes the swapped case), and in 3.0 +// kindOnEntry where nullable moves into the entry beside type. +func (c cases) duplicatesSwapped(at []int, spelling string, secondWritten written, firstMembers object, targetValue target) bool { + if at[2] == 0 || (at[2]-1)%2 != 0 || secondWritten.row < 0 { + return false + } + keyword := c.constructs[(at[2]-1)/2].keyword + if spelling == kindOnEntry && keyword == "nullable" { + return true + } + if spelling != constructOnEntry && spelling != inlineConstructOnEntry { + return false + } + isRowSecond := slices.ContainsFunc(c.seconds, func(other second) bool { return other.own == nil && other.name == keyword }) + if !isRowSecond { + return false + } + if spelling == inlineConstructOnEntry && slices.ContainsFunc(firstMembers, func(memberValue member) bool { + return slices.ContainsFunc(targetValue.body, sameName(memberValue)) + }) { + return false + } + return true +} + // rowOf returns the index in c.constructs of the row the second at index j // is named as, -1 for none or a second writing its own members. A second // naming no row and writing nothing of its own panics, which CheckCase reports diff --git a/internal/harness/openapicases/seconds_internal_test.go b/internal/harness/openapicases/seconds_internal_test.go index 4023af1af..268928482 100644 --- a/internal/harness/openapicases/seconds_internal_test.go +++ b/internal/harness/openapicases/seconds_internal_test.go @@ -132,6 +132,74 @@ func TestWrite_NamesTheTwoPartsOfAUnit(t *testing.T) { assert.Nil(t, parts("3.1.0", "string", "minLength", "none", "items", "beside")) assert.Nil(t, parts("3.1.0", "string", "none", "typeNull", "items", "beside")) assert.Nil(t, parts("3.1.0", "string", "minLength", "typeNull", "items", "inline")) + assert.Equal(t, [][]int{at("3.1.0/object/anyOf/none/component/wrap"), at("3.1.0/object/oneOf/none/component/entry")}, + parts("3.1.0", "object", "anyOf", "oneOf", "component", "secondOnEntry")) + assert.Equal(t, [][]int{at("3.1.0/object/anyOf/none/component/entry"), at("3.1.0/object/oneOf/none/component/wrap")}, + parts("3.1.0", "object", "anyOf", "oneOf", "component", "constructOnEntry")) + assert.Equal(t, [][]int{at("3.1.0/object/anyOf/none/component/inline"), at("3.1.0/object/oneOf/none/component/keywordOnEntry")}, + parts("3.1.0", "object", "anyOf", "oneOf", "component", "inlineSecondOnEntry")) + assert.Equal(t, [][]int{at("3.1.0/object/anyOf/none/component/keywordOnEntry"), at("3.1.0/object/oneOf/none/component/inline")}, + parts("3.1.0", "object", "anyOf", "oneOf", "component", "inlineConstructOnEntry")) +} + +// TestSeconds_TheSecondConstructIsWrittenApartAtFull pins the full-only +// placements writing one construct beside an allOf and the other on an entry, +// and that none parts a group's keywords or moves a keyword that stays beside +// the use onto an entry. +func TestSeconds_TheSecondConstructIsWrittenApartAtFull(t *testing.T) { + casesValue, ok := New().(cases) + require.True(t, ok) + for _, s := range []string{secondOnEntry, constructOnEntry, inlineSecondOnEntry, inlineConstructOnEntry} { + i := slices.Index(casesValue.spellings, s) + require.GreaterOrEqual(t, i, 0, s) + assert.NotEmpty(t, casesValue.Axes()[5].Values[i].Like, "%s is full-only", s) + } + for _, tc := range []struct { + name string + want string + }{ + {"3.1.0/object/anyOf/oneOf/component/secondOnEntry", + `{"allOf":[{"$ref":"#/components/schemas/T"},{"oneOf":[{"type":"object","properties":{"b":{"type":"string"}}},{"type":"object","properties":{"c":{"type":"string"}}}]}],"anyOf":[{"type":"object","properties":{"b":{"type":"string"}}},{"type":"object","properties":{"c":{"type":"string"}}}]}`}, + {"3.1.0/object/anyOf/oneOf/component/constructOnEntry", + `{"allOf":[{"$ref":"#/components/schemas/T"},{"anyOf":[{"type":"object","properties":{"b":{"type":"string"}}},{"type":"object","properties":{"c":{"type":"string"}}}]}],"oneOf":[{"type":"object","properties":{"b":{"type":"string"}}},{"type":"object","properties":{"c":{"type":"string"}}}]}`}, + {"3.1.0/string/minLength/description/component/inlineSecondOnEntry", + `{"type":"string","minLength":1,"allOf":[{"description":"D"}]}`}, + {"3.1.0/string/minLength/description/component/inlineConstructOnEntry", + `{"type":"string","description":"D","allOf":[{"minLength":1}]}`}, + {"3.1.0/object/additionalProperties/description/component/inlineSecondOnEntry", + `{"type":"object","properties":{"a":{"type":"string"}},"additionalProperties":{"type":"integer"},"allOf":[{"description":"D"}]}`}, + {"3.1.0/object/additionalProperties/description/component/inlineConstructOnEntry", ""}, // parts additionalProperties from body's properties + {"3.1.0/object/properties/additionalProperties/component/secondOnEntry", ""}, // parts additionalProperties from properties + {"3.1.0/object/properties/additionalProperties/component/constructOnEntry", ""}, // parts additionalProperties from properties + {"3.0.3/string/nullable/targetType/component/secondOnEntry", ""}, // parts 3.0 nullable from type + {"3.0.3/string/nullable/targetType/component/constructOnEntry", ""}, // parts 3.0 nullable from type + {"3.1.0/object/unevaluatedProperties/description/component/constructOnEntry", ""}, // a keyword that stays beside the use, onto an entry + {"3.1.0/object/unevaluatedProperties/description/component/inlineConstructOnEntry", ""}, // a keyword that stays beside the use, onto an entry + {"3.1.0/string/title/secondRef/component/secondOnEntry", ""}, // secondRef writes no member + {"3.1.0/string/minLength/none/component/secondOnEntry", ""}, // no second + {"3.1.0/string/none/targetType/component/secondOnEntry", ""}, // no construct + {"3.1.0/object/enum/oneOf/component/constructOnEntry", ""}, // written by oneOf/enum/secondOnEntry + {"3.1.0/object/enum~/oneOf/component/constructOnEntry", + `{"allOf":[{"$ref":"#/components/schemas/T"},{"enum":[{"a":"y"}]}],"oneOf":[{"type":"object","properties":{"b":{"type":"string"}}},{"type":"object","properties":{"c":{"type":"string"}}}]}`}, + {"3.1.0/object/properties/enum/component/inlineConstructOnEntry", + `{"type":"object","enum":[{"a":"x"}],"allOf":[{"properties":{"p":{"type":"string"}}}]}`}, + } { + doc, writes := casesValue.Write(caseAt(t, casesValue, strings.Split(tc.name, "/")...)) + if tc.want == "" { + assert.False(t, writes, tc.name) + continue + } + require.True(t, writes, tc.name) + var spec struct { + Components struct { + Schemas map[string]jsontext.Value `json:"schemas"` + } `json:"components"` + } + require.NoError(t, json.Unmarshal(doc.Sources[0].Data, &spec), tc.name) + got := spec.Components.Schemas[caseSchema] + require.NoError(t, got.Compact(), tc.name) + assert.Equal(t, tc.want, string(got), tc.name) + } } // TestWrite_ATypeAdmittingNullCompilesWithoutTheNullablePolicy pins the diff --git a/internal/harness/openapicases/spelling_test.go b/internal/harness/openapicases/spelling_test.go index 3eec9b58c..1e00aee33 100644 --- a/internal/harness/openapicases/spelling_test.go +++ b/internal/harness/openapicases/spelling_test.go @@ -13,6 +13,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/dexpace/morphic/compilers" + "github.com/dexpace/morphic/engine" "github.com/dexpace/morphic/internal/harness" "github.com/dexpace/morphic/internal/harness/openapicases" "github.com/dexpace/morphic/ir/irtest" @@ -46,9 +48,9 @@ func TestCore_SpellingsHoldTheRecord(t *testing.T) { } unlisted, changed, stale, unreasoned := record.Judge(found, openapicases.Reasons()) assert.Empty(t, unlisted, "a finding the record does not list: fix the compiler, or list it with its reason (-update)") - assert.Empty(t, changed) + assert.Empty(t, changed, changedAdvice) assert.Empty(t, stale, "a line whose finding is gone: delete it (-update)") - assert.Empty(t, unreasoned) + assert.Empty(t, unreasoned, unreasonedAdvice) } // colliding are the groups whose own schema keeps two entries of an allOf @@ -83,3 +85,21 @@ func TestCore_ARelocationCollidesAtTheListedGroupsAlone(t *testing.T) { } assert.Equal(t, colliding, slices.Sorted(maps.Keys(groups))) } + +// TestKindOnEntry_ClosureWithPropertiesEqualsFlat pins that keeping a body's +// properties beside additionalProperties: false while moving type: object to an +// allOf entry lowers to the same model as the flat schema. +func TestKindOnEntry_ClosureWithPropertiesEqualsFlat(t *testing.T) { + t.Parallel() + eng, err := engine.New(engine.WithCompilers(engine.Compilers()...), engine.WithPasses(engine.Passes()...)) + require.NoError(t, err) + const flat = `{"openapi":"3.1.0","info":{"title":"t","version":"1"},"paths":{},"components":{"schemas":{"C":{"type":"object","properties":{"a":{"type":"string"}},"additionalProperties":false}}}}` + const split = `{"openapi":"3.1.0","info":{"title":"t","version":"1"},"paths":{},"components":{"schemas":{"C":{"properties":{"a":{"type":"string"}},"additionalProperties":false,"allOf":[{"type":"object"}]}}}}` + flatResult, err := eng.RunSources(t.Context(), []compilers.Source{{Path: "openapi.json", Data: []byte(flat)}}, engine.RunOptions{Verify: true}) + require.NoError(t, err) + splitResult, err := eng.RunSources(t.Context(), []compilers.Source{{Path: "openapi.json", Data: []byte(split)}}, engine.RunOptions{Verify: true}) + require.NoError(t, err) + assert.Empty(t, flatResult.Diagnostics) + assert.Empty(t, splitResult.Diagnostics) + assert.Equal(t, flatResult.Document.Types, splitResult.Document.Types) +} diff --git a/internal/harness/openapicases/spellings.go b/internal/harness/openapicases/spellings.go index f5fb98664..465e09eab 100644 --- a/internal/harness/openapicases/spellings.go +++ b/internal/harness/openapicases/spellings.go @@ -5,16 +5,20 @@ package openapicases import ( "encoding/json/jsontext" + "fmt" "slices" "strconv" "strings" + "sync" "github.com/dexpace/morphic/internal/harness" "github.com/dexpace/morphic/ir" ) // The spellings of a use of a named target T saying K, every keyword the case -// writes beside the use, moved as one unit. +// writes beside the use, moved as one unit; then those writing K beside the +// target's typed body B, split across allOf entries, and those writing a case's +// construct and second apart. const ( // beside writes {$ref: T, K}. beside = "beside" @@ -28,44 +32,189 @@ const ( nested = "nested" // besideEntry writes {allOf: [{$ref: T, K}]}, beside as an allOf's entry. besideEntry = "besideEntry" + + // keywordOnEntry writes {B, allOf: [{K}]}. + keywordOnEntry = "keywordOnEntry" + // bothOnEntries writes {allOf: [{B}, {K}]}. + bothOnEntries = "bothOnEntries" + // kindOnEntry writes {K, allOf: [{B}]}, a member of B grouped with K + // staying beside it. + kindOnEntry = "kindOnEntry" + + // secondOnEntry writes {allOf: [{$ref: T}, {second}], construct}, at full + // alone, as the other apart spellings are. + secondOnEntry = "secondOnEntry" + // constructOnEntry writes {allOf: [{$ref: T}, {construct}], second}. + constructOnEntry = "constructOnEntry" + // inlineSecondOnEntry writes {B, construct, allOf: [{second}]}. + inlineSecondOnEntry = "inlineSecondOnEntry" + // inlineConstructOnEntry writes {B, second, allOf: [{construct}]}. + inlineConstructOnEntry = "inlineConstructOnEntry" +) + +// useSpellings returns the spellings writing a single-unit use of a named +// target, which the suite's group cases use. +func useSpellings() []string { + return []string{beside, wrap, entry, entryFirst, nested, besideEntry} +} + +// spellingKind is what a spelling writes at the position. +type spellingKind uint8 + +// The kinds of spelling. +const ( + // useKind writes a use of the named target. + useKind spellingKind = iota + // bodyKind writes the target's body directly. + bodyKind + // bodySplitKind splits a typed target body across allOf entries. + bodySplitKind + // inlineApartKind writes a typed target body with a case's construct and + // second construct placed apart, one beside the allOf and the other on an + // entry. + inlineApartKind + // apartKind writes a use of the target with those two placed apart. + apartKind ) -// targetSchema is the component every spelling but inline writes the target -// as, and the use names. +// spellingFacts is everything the product knows of one spelling, in one place: +// what it writes, the spelling it must equal and the rule making the two one, +// and where the case leaving a construct out is written. +type spellingFacts struct { + kind spellingKind + // partner and rule are the spelling this one must equal and the rule that + // makes the two one; empty for wrap and inline, the two the others equal. + partner, rule string + // absent is the spelling the case leaving the construct out is written + // in, where it is the same for every case; empty where it is not. + absent string + // writesWrapEmpty says that, given no keyword, the spelling writes wrap's + // document: the spellings writing the keywords in an entry of their own or + // beside the reference's entry. + writesWrapEmpty bool +} + +// spellingTable holds the facts of every spelling. A spelling added is added +// here, and nowhere else says what it is. +var spellingTable = map[string]spellingFacts{ + beside: {kind: useKind, partner: wrap, rule: "ref-use-site"}, + wrap: {kind: useKind}, + entry: {kind: useKind, partner: wrap, rule: "allof-inline-residue", writesWrapEmpty: true}, + entryFirst: {kind: useKind, partner: entry, rule: "allof-classification", writesWrapEmpty: true}, + nested: {kind: useKind, partner: entry, rule: "allof-classification"}, + besideEntry: {kind: useKind, partner: entry, rule: "ref-use-site", writesWrapEmpty: true}, + + inline: {kind: bodyKind}, + keywordOnEntry: {kind: bodySplitKind, partner: inline, rule: "allof-inline-residue"}, + bothOnEntries: {kind: bodySplitKind, partner: inline, rule: "allof-refinement"}, + kindOnEntry: {kind: bodySplitKind, partner: inline, rule: "allof-refinement"}, + + secondOnEntry: {kind: apartKind, partner: wrap, rule: "allof-inline-residue", absent: entry}, + constructOnEntry: {kind: apartKind, partner: wrap, rule: "allof-inline-residue", absent: wrap}, + inlineSecondOnEntry: {kind: inlineApartKind, partner: inline, rule: "allof-inline-residue", absent: keywordOnEntry}, + inlineConstructOnEntry: {kind: inlineApartKind, partner: inline, rule: "allof-inline-residue", absent: inline}, +} + +// isBodySplit reports whether spelling splits a typed target body across allOf entries. +func isBodySplit(spelling string) bool { return spellingTable[spelling].kind == bodySplitKind } + +// isInlineApart reports whether spelling writes a typed target body with its two +// constructs placed apart, one beside the allOf and the other on an entry. +func isInlineApart(spelling string) bool { return spellingTable[spelling].kind == inlineApartKind } + +// isApart reports whether spelling places a case's construct and second construct +// apart, one beside the allOf and the other on an entry. +func isApart(spelling string) bool { + return spellingTable[spelling].kind == apartKind || isInlineApart(spelling) +} + +// isBodySpelling reports whether spelling writes the target's body directly rather +// than referencing a named target component. +func isBodySpelling(spelling string) bool { + return spellingTable[spelling].kind == bodyKind || isBodySplit(spelling) || isInlineApart(spelling) +} + +// GroupAnchorKeywords returns, for each keyword of versionName that depends on +// an anchor within the same schema object by JSON Schema or OpenAPI 3.0, the +// anchor keywords it moves with. versionName is an OpenAPI minor or patch +// version ("3.0", "3.0.x", "3.1", "3.1.x", "3.2", "3.2.x"); any other value +// panics. +func GroupAnchorKeywords(versionName string) map[string][]string { + switch { + case versionName == "3.0" || strings.HasPrefix(versionName, "3.0."): + return map[string][]string{ + "additionalProperties": {"properties"}, + "exclusiveMaximum": {"maximum"}, + "exclusiveMinimum": {"minimum"}, + "nullable": {"type"}, + } + case versionName == "3.1" || strings.HasPrefix(versionName, "3.1.") || + versionName == "3.2" || strings.HasPrefix(versionName, "3.2."): + return map[string][]string{ + "additionalProperties": {"properties", "patternProperties"}, + "items": {"prefixItems"}, + "minContains": {"contains"}, + "maxContains": {"contains"}, + "then": {"if"}, + "else": {"if"}, + "contentSchema": {"contentMediaType"}, + } + default: + panic(fmt.Sprintf("openapicases: unknown OpenAPI version %q for GroupAnchorKeywords", versionName)) + } +} + +// besideOnly is the keywords the constructs table says stay beside the use, +// which no spelling moves onto an allOf entry: the keyword changes what the +// use names, or identifies or configures the schema it is written in +// (docs/compilers/openapi.md#allof-inline-residue). It is the table's own +// classification, read once. +var besideOnly = sync.OnceValue(func() map[string]bool { + out := map[string]bool{} + for _, construct := range constructs() { + out[construct.keyword] = construct.stays != moved + } + return out +}) + +// hasBesideOnlyKeyword reports whether any member in members is a keyword that +// stays beside the use. +func hasBesideOnlyKeyword(members object) bool { + return slices.ContainsFunc(members, func(memberValue member) bool { return besideOnly()[memberValue.name] }) +} + +// targetSchema is the component every non-body spelling writes the target as, +// and the use names. const targetSchema = "T" // rulePrefix is how a rule making two spellings one is cited. const rulePrefix = "docs/compilers/openapi.md#" // partnerOf returns the spelling s must equal and the rule making the two one, -// and false for wrap, the spelling the others equal, and inline, which names no -// target. +// and false for wrap and inline, the two the others equal: inline, which names +// no target, is the partner of the spellings writing the body. func partnerOf(s string) (partner, rule string, ok bool) { - switch s { - case beside: - return wrap, "ref-use-site", true - case entry: - return wrap, "allof-inline-residue", true - case entryFirst, nested: - return entry, "allof-classification", true - case besideEntry: - return entry, "ref-use-site", true - default: - return "", "", false - } + facts := spellingTable[s] + return facts.partner, facts.rule, facts.partner != "" } // spelt returns the schema a case writes at its position: for inline, -// targetValue's body with writtenValue's members and entries merged in; -// otherwise the use of the target saying writtenValue in spelling s. It is -// false where s writes no such use: the unit stays where inline writes it, s -// would write a key twice, or an entry spelling saying nothing writes wrap's -// document. -func (c cases) spelt(writtenValue written, s string, targetValue target) (object, bool) { - if s == inline { +// targetValue's body with writtenValue's members and entries merged in; for a +// body-split spelling (docs/compilers/openapi.md#allof-inline-residue, +// docs/compilers/openapi.md#allof-refinement), that body split across allOf +// entries without parting a group from its anchor or moving a keyword that +// stays beside the use; for an apart spelling, the two constructs placed beside and on an +// entry under the same rule; otherwise a use of the target in spelling s. +func (c cases) spelt(writtenValue written, s string, targetValue target, versionValue version) (object, bool) { + switch { + case s == inline: return targetValue.body.with(slices.Concat(writtenValue.members, allOfOf(writtenValue.entries))), true + case isBodySplit(s): + return speltBodySplit(writtenValue, s, targetValue, versionValue) + case isApart(s): + return speltApart(writtenValue, s, targetValue, versionValue) } - if len(writtenValue.members) == 0 && writesWrapEmpty(s) { + if len(writtenValue.members) == 0 && spellingTable[s].writesWrapEmpty { return nil, false } switch writtenValue.stays { @@ -80,10 +229,146 @@ func (c cases) spelt(writtenValue written, s string, targetValue target) (object return spell(s, object{{"$ref", "#/components/schemas/" + targetSchema}}, writtenValue.members, writtenValue.entries) } -// writesWrapEmpty reports whether s, given no keyword, writes wrap's document, -// which wrap writes: the spellings writing the keywords in an entry of their -// own or beside the reference's entry. -func writesWrapEmpty(s string) bool { return s == entry || s == entryFirst || s == besideEntry } +// speltBodySplit writes a typed target body split across allOf entries without +// parting a group keyword from its anchor or moving a keyword that stays +// beside the use. +func speltBodySplit(writtenValue written, spelling string, targetValue target, versionValue version) (object, bool) { + if writtenValue.firstCount == 0 || writtenValue.stays == inlineAlone || hasBesideOnlyKeyword(writtenValue.members) { + return nil, false + } + bodyLeft := withoutReplaced(targetValue.body, writtenValue.members) + if !slices.ContainsFunc(bodyLeft, named("type")) { + return nil, false + } + anchors := GroupAnchorKeywords(versionValue.name) + var use object + switch spelling { + case keywordOnEntry: + if partedGroup(anchors, bodyLeft, writtenValue.members) { + return nil, false + } + use = slices.Concat(bodyLeft, allOfOf(slices.Concat(writtenValue.entries, []any{writtenValue.members}))) + case bothOnEntries: + if partedGroup(anchors, bodyLeft, writtenValue.members) { + return nil, false + } + entries := slices.Concat([]any{bodyLeft}, writtenValue.entries, []any{writtenValue.members}) + // inline merges nested allOf entries' properties before the outer schema's + // own properties, so place an allOf construct ahead of bodyLeft to keep + // Model.Properties in the same order. + if slices.ContainsFunc(writtenValue.members, named("allOf")) { + entries = slices.Concat(writtenValue.entries, []any{writtenValue.members, bodyLeft}) + } + use = object{{"allOf", entries}} + case kindOnEntry: + entryMembers, outerMembers := splitKindOnEntry(anchors, bodyLeft, writtenValue.members, versionValue) + use = slices.Concat(outerMembers, allOfOf(slices.Concat([]any{entryMembers}, writtenValue.entries))) + } + return use, !repeats(use) +} + +// splitKindOnEntry partitions bodyLeft and writtenMembers for kindOnEntry: a +// non-type body member tied by a group to writtenMembers stays beside it on +// the outer object, and a 3.0 nullable moves with type into the entry. +func splitKindOnEntry(anchors map[string][]string, bodyLeft, writtenMembers object, versionValue version) (entryMembers, outerMembers object) { + var stayed object + for _, memberValue := range bodyLeft { + if memberValue.name != "type" && partedGroup(anchors, object{memberValue}, writtenMembers) { + stayed = append(stayed, memberValue) + continue + } + entryMembers = append(entryMembers, memberValue) + } + outerMembers = slices.Concat(stayed, writtenMembers) + if !versionValue.dialect { + if i := slices.IndexFunc(outerMembers, named("nullable")); i >= 0 { + entryMembers = append(entryMembers, outerMembers[i]) + outerMembers = slices.Delete(slices.Clone(outerMembers), i, i+1) + } + } + return entryMembers, outerMembers +} + +// speltApart writes a construct and a second construct placed apart, one +// beside the allOf and the other on an entry, without parting a group from its +// anchor, and only where the unit stays moved: no keyword that stays beside +// the use is written onto an entry. +func speltApart(writtenValue written, spelling string, targetValue target, versionValue version) (object, bool) { + firstMembers := writtenValue.members[:writtenValue.firstCount] + secondMembers := writtenValue.members[writtenValue.firstCount:] + if len(firstMembers) == 0 || len(secondMembers) == 0 { + return nil, false + } + anchors := GroupAnchorKeywords(versionValue.name) + if isInlineApart(spelling) { + return speltInlineApart(writtenValue, spelling, targetValue, anchors, firstMembers, secondMembers) + } + if writtenValue.stays != moved || partedGroup(anchors, firstMembers, secondMembers) { + return nil, false + } + ref := object{{"$ref", "#/components/schemas/" + targetSchema}} + var outer, inner object + if spelling == secondOnEntry { + outer, inner = firstMembers, secondMembers + } else { + outer, inner = secondMembers, firstMembers + } + use := slices.Concat(object{{"allOf", []any{ref, inner}}}, outer) + return use, !repeats(use) +} + +// speltInlineApart writes a typed target body with one construct beside the +// allOf and the other on an entry. +func speltInlineApart(writtenValue written, spelling string, targetValue target, anchors map[string][]string, firstMembers, secondMembers object) (object, bool) { + if writtenValue.stays == inlineAlone { + return nil, false + } + bodyLeft := withoutReplaced(targetValue.body, writtenValue.members) + if !slices.ContainsFunc(bodyLeft, named("type")) { + return nil, false + } + var outer, inner object + if spelling == inlineSecondOnEntry { + outer, inner = slices.Concat(bodyLeft, firstMembers), secondMembers + } else { + outer, inner = slices.Concat(bodyLeft, secondMembers), firstMembers + } + if hasBesideOnlyKeyword(inner) || partedGroup(anchors, outer, inner) { + return nil, false + } + use := slices.Concat(outer, allOfOf([]any{inner})) + return use, !repeats(use) +} + +// withoutReplaced returns body without any member whose name override writes. +func withoutReplaced(body, override object) object { + out := make(object, 0, len(body)) + for _, memberValue := range body { + if !slices.ContainsFunc(override, named(memberValue.name)) { + out = append(out, memberValue) + } + } + return out +} + +// partedGroup reports whether a and b place a dependent keyword of anchors +// apart from one of its anchors. +func partedGroup(anchors map[string][]string, a, b object) bool { + return hasAnchorIn(anchors, a, b) || hasAnchorIn(anchors, b, a) +} + +// hasAnchorIn reports whether any member of dependents depends on an anchor +// named in others. +func hasAnchorIn(anchors map[string][]string, dependents, others object) bool { + for _, memberValue := range dependents { + for _, anchor := range anchors[memberValue.name] { + if slices.ContainsFunc(others, named(anchor)) { + return true + } + } + } + return false +} // staysAt is where the construct at index i of the construct axis is written; // none, saying nothing, is moved. @@ -173,7 +458,7 @@ func (c cases) equal(at []int, writtenValue written) *harness.Equal { if readApart(s, writtenValue.members) { return nil } - if _, writes := c.spelt(writtenValue, partner, c.targets[at[1]]); !writes { + if _, writes := c.spelt(writtenValue, partner, c.targets[at[1]], c.versions[at[0]]); !writes { return nil } to := slices.Clone(at) @@ -270,11 +555,16 @@ func relocation(use string) func(string) string { } // eraseAllOf returns path, a pointer, with each "/allOf/" pair of its -// tokens left out. +// tokens left out, and each "/allOf/-/", the entry a composed key +// minted for a variant that entry distributes names. func eraseAllOf(path string) string { tokens := strings.Split(path, "/") out := tokens[:0:0] for i := 0; i < len(tokens); i++ { + if tokens[i] == "allOf" && i+2 < len(tokens) && tokens[i+1] == "-" && isIndex(tokens[i+2]) { + i += 2 + continue + } if tokens[i] == "allOf" && i+1 < len(tokens) && isIndex(tokens[i+1]) { i++ continue diff --git a/internal/harness/openapicases/spellings_internal_test.go b/internal/harness/openapicases/spellings_internal_test.go index de6eca8e7..f90668c31 100644 --- a/internal/harness/openapicases/spellings_internal_test.go +++ b/internal/harness/openapicases/spellings_internal_test.go @@ -67,6 +67,25 @@ func TestRelocation_ErasesEachAllOfIndexAfterTheUse(t *testing.T) { assert.Equal(t, "property/openapi/components/schemas/C/properties/t1", beneath("property/openapi/components/schemas/C/properties/t1/allOf/0")) } +// TestRelocation_ReadsAnEntryDistributedKeyAsItsEntry holds the relocation to +// a composed key minted for a union an entry of the use's allOf distributes: +// "allOf/-/" names entry k, and is erased as "allOf/" is, so the +// variant a spelling writing the union on an entry keys apart lands on the +// one the spelling beside the allOf keys at the branch (GitHub #2101). +func TestRelocation_ReadsAnEntryDistributedKeyAsItsEntry(t *testing.T) { + use := "/components/schemas/C" + relocate := relocation(use) + for in, want := range map[string]string{ + "type/composed/components/schemas/C/allOf/-/1/oneOf/0": "type/composed/components/schemas/C/oneOf/0", + "type/composed/components/schemas/C/allOf/-/0/allOf/0/oneOf/1": "type/composed/components/schemas/C/oneOf/1", + use + "/allOf/-/2/anyOf/0": use + "/anyOf/0", + "type/composed/components/schemas/CX/allOf/-/1/oneOf/0": "type/composed/components/schemas/CX/allOf/-/1/oneOf/0", + "type/composed/components/schemas/C/allOf/-/x/oneOf/0": "type/composed/components/schemas/C/allOf/-/x/oneOf/0", + } { + assert.Equal(t, want, relocate(in), in) + } +} + // caseAt returns the coordinates of the case naming each axis's value by name. func caseAt(t *testing.T, casesValue cases, names ...string) []int { t.Helper() @@ -208,6 +227,110 @@ func TestGroups_EachSpellingNamesItsPartner(t *testing.T) { assert.False(t, ok, "a spelling writing no use of a group's target writes nothing") } +// TestSpellings_ABodySplitAcrossEntriesIsWrittenThreeWays pins the three body-split +// spellings of a typed target: keyword on an entry, both on entries, and kind +// on an entry, and that none is written for the union target or for none. +func TestSpellings_ABodySplitAcrossEntriesIsWrittenThreeWays(t *testing.T) { + casesValue, ok := New().(cases) + require.True(t, ok) + for _, tc := range []struct { + name string + want string + }{ + {"3.1.0/string/minLength/none/component/keywordOnEntry", + `{"type":"string","allOf":[{"minLength":1}]}`}, + {"3.1.0/string/minLength/none/component/bothOnEntries", + `{"allOf":[{"type":"string"},{"minLength":1}]}`}, + {"3.1.0/string/minLength/none/component/kindOnEntry", + `{"minLength":1,"allOf":[{"type":"string"}]}`}, + {"3.1.0/object/minProperties/none/component/keywordOnEntry", + `{"type":"object","properties":{"a":{"type":"string"}},"allOf":[{"minProperties":1}]}`}, + {"3.1.0/object/minProperties/none/component/bothOnEntries", + `{"allOf":[{"type":"object","properties":{"a":{"type":"string"}}},{"minProperties":1}]}`}, + {"3.1.0/object/minProperties/none/component/kindOnEntry", + `{"minProperties":1,"allOf":[{"type":"object","properties":{"a":{"type":"string"}}}]}`}, + {"3.1.0/array/items/none/component/keywordOnEntry", + `{"type":"array","allOf":[{"items":{"type":"integer"}}]}`}, + {"3.1.0/array/items/none/component/bothOnEntries", + `{"allOf":[{"type":"array"},{"items":{"type":"integer"}}]}`}, + {"3.1.0/array/items/none/component/kindOnEntry", + `{"items":{"type":"integer"},"allOf":[{"type":"array"}]}`}, + {"3.1.0/object/allOf/none/component/keywordOnEntry", + `{"type":"object","properties":{"a":{"type":"string"}},"allOf":[{"allOf":[{"type":"object","properties":{"q":{"type":"integer"}}}]}]}`}, + {"3.1.0/object/allOf/none/component/bothOnEntries", + `{"allOf":[{"allOf":[{"type":"object","properties":{"q":{"type":"integer"}}}]},{"type":"object","properties":{"a":{"type":"string"}}}]}`}, + {"3.1.0/object/allOf/none/component/kindOnEntry", ""}, + {"3.1.0/union/title/none/component/keywordOnEntry", ""}, + {"3.1.0/union/title/none/component/bothOnEntries", ""}, + {"3.1.0/union/title/none/component/kindOnEntry", ""}, + {"3.1.0/string/none/none/component/keywordOnEntry", ""}, + {"3.1.0/string/none/none/component/bothOnEntries", ""}, + {"3.1.0/string/none/none/component/kindOnEntry", ""}, + {"3.1.0/string/title/typeNull/component/keywordOnEntry", ""}, + } { + doc, writes := casesValue.Write(caseAt(t, casesValue, strings.Split(tc.name, "/")...)) + if tc.want == "" { + assert.False(t, writes, tc.name) + continue + } + require.True(t, writes, tc.name) + var spec struct { + Components struct { + Schemas map[string]jsontext.Value `json:"schemas"` + } `json:"components"` + } + require.NoError(t, json.Unmarshal(doc.Sources[0].Data, &spec), tc.name) + got := spec.Components.Schemas[caseSchema] + require.NoError(t, got.Compact(), tc.name) + assert.Equal(t, tc.want, string(got), tc.name) + assert.NotContains(t, spec.Components.Schemas, targetSchema, "%s writes no named target", tc.name) + } +} + +// TestPartnerOf_EachSplitSpellingNamesItsPartner holds the partner and +// rule of every body-split and apart spelling. +func TestPartnerOf_EachSplitSpellingNamesItsPartner(t *testing.T) { + for _, tc := range []struct { + spelling, partner, rule string + }{ + {keywordOnEntry, inline, "allof-inline-residue"}, + {bothOnEntries, inline, "allof-refinement"}, + {kindOnEntry, inline, "allof-refinement"}, + {secondOnEntry, wrap, "allof-inline-residue"}, + {constructOnEntry, wrap, "allof-inline-residue"}, + {inlineSecondOnEntry, inline, "allof-inline-residue"}, + {inlineConstructOnEntry, inline, "allof-inline-residue"}, + } { + partner, rule, ok := partnerOf(tc.spelling) + require.True(t, ok, tc.spelling) + assert.Equal(t, tc.partner, partner, tc.spelling) + assert.Equal(t, tc.rule, rule, tc.spelling) + } +} + +// TestGroupAnchorKeywords_MatchesVersionAndRejectsUnknown pins the group +// anchor maps for OpenAPI 3.0, 3.1 and 3.2 (both minor and patch strings) and +// confirms unknown versions panic rather than silently returning another dialect. +func TestGroupAnchorKeywords_MatchesVersionAndRejectsUnknown(t *testing.T) { + t.Parallel() + anchors30 := GroupAnchorKeywords("3.0") + assert.Equal(t, anchors30, GroupAnchorKeywords("3.0.3")) + assert.Equal(t, []string{"type"}, anchors30["nullable"]) + assert.Equal(t, []string{"properties"}, anchors30["additionalProperties"]) + assert.NotContains(t, anchors30, "items") + + anchors31 := GroupAnchorKeywords("3.1") + assert.Equal(t, anchors31, GroupAnchorKeywords("3.1.0")) + assert.Equal(t, anchors31, GroupAnchorKeywords("3.2")) + assert.Equal(t, anchors31, GroupAnchorKeywords("3.2.0")) + assert.Equal(t, []string{"properties", "patternProperties"}, anchors31["additionalProperties"]) + assert.Equal(t, []string{"prefixItems"}, anchors31["items"]) + assert.NotContains(t, anchors31, "nullable") + + assert.Panics(t, func() { GroupAnchorKeywords("") }) + assert.Panics(t, func() { GroupAnchorKeywords("2.0") }) +} + // TestWrite_TwoSpellingsDifferInTheUseAlone holds each case naming a partner, // at the component position, to that partner: the two documents differ in the // case's own schema alone, and each says there the same conjuncts, the @@ -252,9 +375,9 @@ func nameOf(axes []harness.Axis, at []int) string { return strings.Join(names, "/") } -// said is what a document says, read for TestWrite_TwoSpellingsDifferInTheUseAlone: -// everything but the case's schema as it stands, and that schema as the -// conjuncts it says. +// said is what a document says, read for +// TestWrite_TwoSpellingsDifferInTheUseAlone: everything but the case's schema +// as it is, and that schema as the conjuncts it says. type said struct { Rest any Refs, Unit []string diff --git a/internal/harness/openapicases/testdata/full/presence.txt b/internal/harness/openapicases/testdata/full/presence.txt index e4bd881bd..e310d2ea3 100644 --- a/internal/harness/openapicases/testdata/full/presence.txt +++ b/internal/harness/openapicases/testdata/full/presence.txt @@ -1,3 +1,120 @@ # What the presence oracle finds at the cases outside the core that what the core # cases find does not explain, and the reason each finding stands: case name, # what was found, reason (Reasons). +3.1.0/array/const/enum/additionalProperties/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/additionalProperties/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/anyOfBranch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/anyOfBranch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/branch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/branch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/component/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/component/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/contentSchema/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/contentSchema/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/header/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/header/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/items/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/items/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/parameter/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/parameter/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/patternProperty/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/patternProperty/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/prefixItem/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/prefixItem/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/property/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/property/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/requestBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/requestBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/responseBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/array/const/enum/responseBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/additionalProperties/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/additionalProperties/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/anyOfBranch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/anyOfBranch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/branch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/branch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/component/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/component/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/contentSchema/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/contentSchema/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/header/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/header/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/items/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/items/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/parameter/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/parameter/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/patternProperty/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/patternProperty/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/prefixItem/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/prefixItem/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/property/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/property/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/requestBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/requestBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/responseBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/integer/const/enum/responseBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/additionalProperties/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/additionalProperties/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/anyOfBranch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/anyOfBranch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/branch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/branch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/component/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/component/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/contentSchema/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/contentSchema/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/header/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/header/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/items/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/items/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/parameter/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/parameter/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/patternProperty/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/patternProperty/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/prefixItem/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/prefixItem/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/property/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/property/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/requestBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/requestBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/responseBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/object/const/enum/responseBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/additionalProperties/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/additionalProperties/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/anyOfBranch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/anyOfBranch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/branch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/branch/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/component/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/component/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/contentSchema/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/contentSchema/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/header/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/header/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/items/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/items/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/parameter/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/parameter/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/patternProperty/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/patternProperty/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/prefixItem/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/prefixItem/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/property/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/property/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/requestBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/requestBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/responseBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/string/const/enum/responseBody/inlineConstructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/additionalProperties/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/anyOfBranch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/branch/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/component/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/contentSchema/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/header/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/items/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/parameter/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/patternProperty/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/prefixItem/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/property/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/requestBody/constructOnEntry changes nothing entry-competing-value-set +3.1.0/union/const/enum/responseBody/constructOnEntry changes nothing entry-competing-value-set diff --git a/internal/harness/openapicases/testdata/full/spelling.txt b/internal/harness/openapicases/testdata/full/spelling.txt index f0d2c9da0..5bf223b5e 100644 --- a/internal/harness/openapicases/testdata/full/spelling.txt +++ b/internal/harness/openapicases/testdata/full/spelling.txt @@ -1,468 +1,2640 @@ # What the spelling oracle finds at the cases outside the core that what the core # cases find does not explain, and the reason each finding stands: case name, # what was found, reason (Reasons). -3.0.3/array/enum/targetType/additionalProperties/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/anyOfBranch/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/branch/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/component/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/header/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/items/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/parameter/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/property/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/requestBody/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum/targetType/responseBody/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/additionalProperties/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/anyOfBranch/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/branch/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/component/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/header/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/items/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/parameter/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/property/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/requestBody/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/array/enum~/targetType/responseBody/entry diagnostics:openapi/missing-array-items entry-missing-items -3.0.3/object/additionalProperties/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties/oneOf/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/additionalProperties~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/anyOf~/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.0.3/object/oneOf~/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/$dynamicRef/oneOf/additionalProperties/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/anyOfBranch/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/branch/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/component/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/contentSchema/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/header/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/items/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/parameter/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/patternProperty/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/prefixItem/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/property/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/requestBody/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef/oneOf/responseBody/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/additionalProperties/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/anyOfBranch/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/branch/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/component/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/contentSchema/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/header/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/items/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/parameter/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/patternProperty/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/prefixItem/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/property/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/requestBody/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$dynamicRef~/oneOf/responseBody/entry types.unmodeled.openapi:$dynamicRef.provenance.pointer,types.unmodeled.openapi:$dynamicRef.provenance.source,types.unmodeled.openapi:$dynamicRef.reason,types.unmodeled.openapi:$dynamicRef.value residue-per-variant -3.1.0/object/$vocabulary/oneOf/additionalProperties/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/anyOfBranch/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/branch/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/component/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/contentSchema/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/header/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/items/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/parameter/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/patternProperty/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/prefixItem/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/property/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/requestBody/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary/oneOf/responseBody/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/core residue-per-variant -3.1.0/object/$vocabulary~/oneOf/additionalProperties/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/anyOfBranch/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/branch/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/component/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/contentSchema/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/header/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/items/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/parameter/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/patternProperty/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/prefixItem/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/property/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/requestBody/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/$vocabulary~/oneOf/responseBody/entry types.unmodeled.openapi:$vocabulary.provenance.pointer,types.unmodeled.openapi:$vocabulary.provenance.source,types.unmodeled.openapi:$vocabulary.reason,types.unmodeled.openapi:$vocabulary.value.https://json-schema.org/draft/2020-12/vocab/validation residue-per-variant -3.1.0/object/additionalProperties/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/oneOf/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/additionalProperties~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/additionalProperties~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.anyOf.properties.b.type,types.unmodeled.openapi:.value.anyOf.properties.c.type,types.unmodeled.openapi:.value.anyOf.type closure-beside-union -3.1.0/object/anyOf~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/anyOf~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/maxProperties~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/minProperties~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.value.use.unmodeled.openapi:type.provenance.pointer,types.value.use.unmodeled.openapi:type.provenance.source,types.value.use.unmodeled.openapi:type.reason,types.value.use.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.variants.decorator.unmodeled.openapi:type.provenance.pointer,types.variants.decorator.unmodeled.openapi:type.provenance.source,types.variants.decorator.unmodeled.openapi:type.reason,types.variants.decorator.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.variants.decorator.unmodeled.openapi:type.provenance.pointer,types.variants.decorator.unmodeled.openapi:type.provenance.source,types.variants.decorator.unmodeled.openapi:type.reason,types.variants.decorator.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/component/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.encoding.schema.use.unmodeled.openapi:type.provenance.pointer,types.encoding.schema.use.unmodeled.openapi:type.provenance.source,types.encoding.schema.use.unmodeled.openapi:type.reason,types.encoding.schema.use.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/header/entry diagnostics:openapi/degraded-construct,services.groups.operations.responses.headers.decorator.unmodeled.openapi:type.provenance.pointer,services.groups.operations.responses.headers.decorator.unmodeled.openapi:type.provenance.source,services.groups.operations.responses.headers.decorator.unmodeled.openapi:type.reason,services.groups.operations.responses.headers.decorator.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/items/entry diagnostics:openapi/degraded-construct,types.elementType.use.unmodeled.openapi:type.provenance.pointer,types.elementType.use.unmodeled.openapi:type.provenance.source,types.elementType.use.unmodeled.openapi:type.reason,types.elementType.use.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/parameter/entry diagnostics:openapi/degraded-construct,services.groups.operations.params.decorator.unmodeled.openapi:type.provenance.pointer,services.groups.operations.params.decorator.unmodeled.openapi:type.provenance.source,services.groups.operations.params.decorator.unmodeled.openapi:type.reason,services.groups.operations.params.decorator.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.value.use.unmodeled.openapi:type.provenance.pointer,types.additionalProperties.patterns.value.use.unmodeled.openapi:type.provenance.source,types.additionalProperties.patterns.value.use.unmodeled.openapi:type.reason,types.additionalProperties.patterns.value.use.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.elementTypes.use.unmodeled.openapi:type.provenance.pointer,types.elementTypes.use.unmodeled.openapi:type.provenance.source,types.elementTypes.use.unmodeled.openapi:type.reason,types.elementTypes.use.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/property/entry diagnostics:openapi/degraded-construct,types.properties.decorator.unmodeled.openapi:type.provenance.pointer,types.properties.decorator.unmodeled.openapi:type.provenance.source,types.properties.decorator.unmodeled.openapi:type.reason,types.properties.decorator.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,services.groups.operations.request.contents.type.use.unmodeled.openapi:type.provenance.pointer,services.groups.operations.request.contents.type.use.unmodeled.openapi:type.provenance.source,services.groups.operations.request.contents.type.use.unmodeled.openapi:type.reason,services.groups.operations.request.contents.type.use.unmodeled.openapi:type.value entry-type-list -3.1.0/object/none/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,services.groups.operations.responses.payload.contents.type.use.unmodeled.openapi:type.provenance.pointer,services.groups.operations.responses.payload.contents.type.use.unmodeled.openapi:type.provenance.source,services.groups.operations.responses.payload.contents.type.use.unmodeled.openapi:type.reason,services.groups.operations.responses.payload.contents.type.use.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/additionalProperties/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/additionalProperties/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type closure-beside-union -3.1.0/object/oneOf~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/oneOf~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/oneOf/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/branch/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/component/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/header/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/items/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/parameter/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/property/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct,types.additionalProperties.patterns.pattern,types.additionalProperties.patterns.value.nullable,types.additionalProperties.patterns.value.target,types.additionalProperties.value.nullable,types.additionalProperties.value.target,types.anonymous,types.id,types.kind,types.primitiveKind,types.provenance.source,types.sensitive,types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.oneOf.properties.b.type,types.unmodeled.openapi:.value.oneOf.properties.c.type,types.unmodeled.openapi:.value.oneOf.type,types.unmodeled.openapi:.value.patternProperties.^a.type closure-beside-union -3.1.0/object/patternProperties~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/patternProperties~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/properties~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/required~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/additionalProperties/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/anyOfBranch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/branch/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/contentSchema/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/header/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/items/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/parameter/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/patternProperty/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/prefixItem/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/property/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/requestBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list -3.1.0/object/xml~/typeNull/responseBody/entry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-type-list +3.0.3/array/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/items~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/maxItems~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/maxItems~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/minItems~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/minItems~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/array/uniqueItems/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/array/uniqueItems/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/branch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/component/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/component/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/component/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/header/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/header/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/header/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/items/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/items/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/items/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/parameter/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/property/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/property/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/property/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/requestBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/responseBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/branch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/component/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/header/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/items/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/parameter/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/property/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/requestBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/responseBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.0.3/integer/format~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/integer/format~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/map/enum/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/map/enum~/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/additionalProperties/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/anyOfBranch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/branch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/component/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/header/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/items/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/parameter/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/property/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/requestBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/additionalProperties~/enum/responseBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum/additionalProperties/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/enum~/additionalProperties/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.0.3/object/required/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.0.3/object/required~/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/object/required~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.0.3/string/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/string/format~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.0.3/union/type/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/contentSchema/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/patternProperty/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/prefixItem/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/contentSchema/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/patternProperty/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/prefixItem/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/const/enum/additionalProperties/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/additionalProperties/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/anyOfBranch/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/anyOfBranch/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/branch/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/branch/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/component/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/component/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/contentSchema/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/contentSchema/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/header/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/header/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/items/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/items/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/parameter/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/parameter/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/patternProperty/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/patternProperty/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/prefixItem/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/prefixItem/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/property/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/property/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/requestBody/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/requestBody/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/responseBody/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const/enum/responseBody/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.list.kind,types.value.list.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/array/const~/enum/additionalProperties/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/additionalProperties/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/additionalProperties/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/additionalProperties/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/additionalProperties/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/additionalProperties/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/additionalProperties/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/anyOfBranch/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/anyOfBranch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/anyOfBranch/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/anyOfBranch/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/anyOfBranch/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/anyOfBranch/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/anyOfBranch/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/branch/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/branch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/branch/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/branch/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/branch/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/branch/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/branch/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/component/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/component/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/component/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/component/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/component/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/component/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/component/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/contentSchema/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/contentSchema/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/contentSchema/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/contentSchema/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/contentSchema/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/contentSchema/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/contentSchema/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/contentSchema/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/header/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/header/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/header/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/header/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/header/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/header/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/header/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/items/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/items/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/items/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/items/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/items/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/items/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/items/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/parameter/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/parameter/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/parameter/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/parameter/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/parameter/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/parameter/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/parameter/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/patternProperty/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/patternProperty/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/patternProperty/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/patternProperty/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/patternProperty/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/patternProperty/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/patternProperty/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/patternProperty/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/prefixItem/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/prefixItem/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/prefixItem/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/prefixItem/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/prefixItem/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/prefixItem/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/prefixItem/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/prefixItem/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/property/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/property/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/property/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/property/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/property/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/property/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/property/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/requestBody/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/requestBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/requestBody/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/requestBody/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/requestBody/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/requestBody/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/requestBody/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/responseBody/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/array/const~/enum/responseBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/responseBody/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/responseBody/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/array/const~/enum/responseBody/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/const~/enum/responseBody/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/array/const~/enum/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.items.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:items.provenance.pointer,types.unmodeled.openapi:items.provenance.source,types.unmodeled.openapi:items.reason,types.unmodeled.openapi:items.value.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/array/const~/enum/responseBody/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/array/const~/enum/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/array/items/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/items~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/maxItems~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/maxItems~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/minItems~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/minItems~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/prefixItems~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/array/uniqueItems/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/array/uniqueItems/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/contentSchema/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/patternProperty/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/prefixItem/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/contentSchema/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/patternProperty/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/prefixItem/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/const/enum/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/branch/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/component/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/header/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/items/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/parameter/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/property/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/requestBody/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/responseBody/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/const/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.number,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.number entry-competing-value-set +3.1.0/integer/format/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/branch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/component/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/component/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/component/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/header/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/header/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/header/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/items/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/items/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/items/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/parameter/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/property/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/property/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/property/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/requestBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/responseBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/branch/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/component/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/header/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/items/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/parameter/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/property/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/requestBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/responseBody/constructOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct,types.unmodeled.openapi:format.provenance.pointer,types.unmodeled.openapi:format.provenance.source,types.unmodeled.openapi:format.reason,types.unmodeled.openapi:format.value entry-value-set +3.1.0/integer/format~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/integer/format~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/map/const/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/const~/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/map/enum~/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/additionalProperties/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/anyOfBranch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/branch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/component/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/contentSchema/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/header/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/items/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/parameter/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/patternProperty/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/prefixItem/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/property/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/requestBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/additionalProperties~/enum/responseBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/contentSchema/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/patternProperty/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/prefixItem/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/additionalProperties/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const/enum/additionalProperties/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/additionalProperties/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/anyOfBranch/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/anyOfBranch/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/branch/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/branch/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/component/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/component/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/contentSchema/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/contentSchema/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/header/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/header/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/items/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/items/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/parameter/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/parameter/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/patternProperty/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/patternProperty/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/prefixItem/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/prefixItem/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/property/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/property/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/requestBody/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/requestBody/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/responseBody/constructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const/enum/responseBody/inlineConstructOnEntry types.anonymous,types.closed,types.exclusive,types.id,types.inputOnly,types.kind,types.name.hint,types.provenance.pointer,types.provenance.source,types.sensitive,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a,types.value.kind,types.value.object.name,types.value.object.value.kind,types.value.object.value.string,types.variants.name.hint,types.variants.type.nullable,types.variants.type.target,types.wireTagged entry-competing-value-set +3.1.0/object/const~/additionalProperties/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/contentSchema/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/patternProperty/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/prefixItem/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/additionalProperties/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/const~/enum/additionalProperties/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/additionalProperties/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/additionalProperties/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/additionalProperties/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/additionalProperties/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/additionalProperties/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/additionalProperties/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/anyOfBranch/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/anyOfBranch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/anyOfBranch/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/anyOfBranch/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/anyOfBranch/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/anyOfBranch/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/anyOfBranch/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/branch/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/branch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/branch/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/branch/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/branch/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/branch/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/branch/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/component/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/component/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/component/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/component/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/component/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/component/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/component/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/contentSchema/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/contentSchema/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/contentSchema/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/contentSchema/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/contentSchema/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/contentSchema/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/contentSchema/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/contentSchema/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/header/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/header/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/header/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/header/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/header/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/header/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/header/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/items/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/items/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/items/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/items/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/items/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/items/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/items/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/parameter/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/parameter/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/parameter/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/parameter/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/parameter/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/parameter/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/parameter/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/patternProperty/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/patternProperty/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/patternProperty/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/patternProperty/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/patternProperty/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/patternProperty/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/patternProperty/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/patternProperty/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/prefixItem/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/prefixItem/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/prefixItem/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/prefixItem/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/prefixItem/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/prefixItem/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/prefixItem/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/prefixItem/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/property/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/property/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/property/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/property/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/property/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/property/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/property/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/requestBody/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/requestBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/requestBody/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/requestBody/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/requestBody/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/requestBody/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/requestBody/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/responseBody/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/object/const~/enum/responseBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/responseBody/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/responseBody/inlineConstructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a entry-competing-value-set +3.1.0/object/const~/enum/responseBody/inlineSecondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/const~/enum/responseBody/keywordOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-value-set +3.1.0/object/const~/enum/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.properties.a.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:properties.provenance.pointer,types.unmodeled.openapi:properties.provenance.source,types.unmodeled.openapi:properties.reason,types.unmodeled.openapi:properties.value.a.type,types.unmodeled.openapi:type.provenance.pointer,types.unmodeled.openapi:type.provenance.source,types.unmodeled.openapi:type.reason,types.unmodeled.openapi:type.value entry-value-set +3.1.0/object/const~/enum/responseBody/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const.a,types.unmodeled.openapi:.value.allOf.enum.a,types.unmodeled.openapi:.value.const.a,types.unmodeled.openapi:.value.enum.a entry-value-set +3.1.0/object/const~/enum/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum.a,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value.a entry-competing-value-set +3.1.0/object/enum/additionalProperties/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/contentSchema/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/patternProperty/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/prefixItem/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum/additionalProperties/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/contentSchema/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/patternProperty/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/prefixItem/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/enum~/additionalProperties/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.1.0/object/patternProperties/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/patternProperties~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/additionalProperties/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/additionalProperties/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/additionalProperties/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/anyOfBranch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/anyOfBranch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/anyOfBranch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/branch/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/branch/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/branch/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/component/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/component/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/component/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/contentSchema/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/contentSchema/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/contentSchema/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/header/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/header/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/header/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/items/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/items/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/items/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/parameter/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/parameter/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/parameter/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/patternProperty/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/patternProperty/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/patternProperty/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/prefixItem/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/prefixItem/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/prefixItem/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/property/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/property/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/property/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/requestBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/requestBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/requestBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/responseBody/bothOnEntries diagnostics:openapi/degraded-construct entry-value-set +3.1.0/object/required~/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/responseBody/keywordOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/object/required~/enum/responseBody/kindOnEntry diagnostics:openapi/degraded-construct entry-value-set +3.1.0/string/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/contentSchema/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/patternProperty/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/prefixItem/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/additionalProperties/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/anyOfBranch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/branch/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/component/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/contentSchema/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/header/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/items/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/parameter/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/patternProperty/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/prefixItem/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/property/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/requestBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/responseBody/inlineSecondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/const/enum/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/additionalProperties/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/anyOfBranch/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/branch/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/branch/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/component/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/component/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/contentSchema/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/header/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/header/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/items/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/items/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/parameter/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/parameter/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/patternProperty/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/prefixItem/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/property/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/property/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/requestBody/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/requestBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/responseBody/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/const/enum/responseBody/inlineConstructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/string/format/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/string/format~/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/additionalProperties/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/anyOfBranch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/branch/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/branch/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/component/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/component/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/contentSchema/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/header/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/header/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/items/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/items/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/parameter/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/parameter/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/patternProperty/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/prefixItem/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/property/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/property/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/requestBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/requestBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/responseBody/constructOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/anyOf~/oneOf/responseBody/secondOnEntry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/const/enum/additionalProperties/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/anyOfBranch/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/branch/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/component/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/contentSchema/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/header/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/items/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/parameter/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/patternProperty/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/prefixItem/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/property/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/requestBody/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const/enum/responseBody/constructOnEntry diagnostics:openapi/degraded-construct,types.closed,types.flags,types.kind,types.members.id,types.members.name.canonical,types.members.name.source,types.members.value.kind,types.members.value.string,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value,types.value.kind,types.value.string entry-competing-value-set +3.1.0/union/const~/enum/additionalProperties/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/additionalProperties/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/additionalProperties/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/additionalProperties/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/additionalProperties/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/anyOfBranch/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/anyOfBranch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/anyOfBranch/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/anyOfBranch/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/anyOfBranch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/branch/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/branch/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/branch/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/branch/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/branch/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/component/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/component/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/component/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/component/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/component/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/contentSchema/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/contentSchema/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/contentSchema/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/contentSchema/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/contentSchema/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/header/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/header/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/header/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/header/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/header/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/items/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/items/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/items/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/items/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/items/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/parameter/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/parameter/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/parameter/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/parameter/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/parameter/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/patternProperty/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/patternProperty/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/patternProperty/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/patternProperty/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/patternProperty/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/prefixItem/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/prefixItem/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/prefixItem/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/prefixItem/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/prefixItem/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/property/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/property/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/property/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/property/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/property/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/requestBody/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/requestBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/requestBody/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/requestBody/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/requestBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/const~/enum/responseBody/besideEntry types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./$ref,types.unmodeled.openapi:.value.$ref entry-value-set +3.1.0/union/const~/enum/responseBody/constructOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value entry-competing-value-set +3.1.0/union/const~/enum/responseBody/entry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:const.provenance.pointer,types.unmodeled.openapi:const.provenance.source,types.unmodeled.openapi:const.reason,types.unmodeled.openapi:const.value,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-value-set +3.1.0/union/const~/enum/responseBody/nested types.unmodeled.openapi:$ref.provenance.pointer,types.unmodeled.openapi:$ref.provenance.source,types.unmodeled.openapi:$ref.reason,types.unmodeled.openapi:$ref.targets.,types.unmodeled.openapi:$ref.value,types.unmodeled.openapi:.targets./allOf/0/$ref,types.unmodeled.openapi:.value.allOf.$ref,types.unmodeled.openapi:.value.allOf.const,types.unmodeled.openapi:.value.allOf.enum,types.unmodeled.openapi:.value.const,types.unmodeled.openapi:.value.enum entry-value-set +3.1.0/union/const~/enum/responseBody/secondOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.enum,types.unmodeled.openapi:enum.provenance.pointer,types.unmodeled.openapi:enum.provenance.source,types.unmodeled.openapi:enum.reason,types.unmodeled.openapi:enum.value entry-competing-value-set +3.1.0/union/type/oneOf/additionalProperties/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/anyOfBranch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/branch/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/component/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/contentSchema/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/header/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/items/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/parameter/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/patternProperty/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/prefixItem/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/property/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/requestBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.1.0/union/type/oneOf/responseBody/entry diagnostics:openapi/degraded-construct split-degraded-reports +3.2.0/map/const/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/const~/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/additionalProperties/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/additionalProperties/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/anyOfBranch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/anyOfBranch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/branch/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/branch/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/component/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/component/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/contentSchema/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/contentSchema/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/header/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/header/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/items/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/items/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/parameter/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/parameter/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/patternProperty/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/patternProperty/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/prefixItem/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/prefixItem/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/property/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/property/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/requestBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/requestBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/responseBody/bothOnEntries types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set +3.2.0/map/enum~/none/responseBody/kindOnEntry types.unmodeled.openapi:.provenance.pointer,types.unmodeled.openapi:.provenance.source,types.unmodeled.openapi:.reason,types.unmodeled.openapi:.value.additionalProperties.type,types.unmodeled.openapi:.value.type,types.unmodeled.openapi:additionalProperties.provenance.pointer,types.unmodeled.openapi:additionalProperties.provenance.source,types.unmodeled.openapi:additionalProperties.reason,types.unmodeled.openapi:additionalProperties.value.type entry-value-set diff --git a/internal/harness/openapicases/testdata/instances.txt b/internal/harness/openapicases/testdata/instances.txt index 32eb2d787..bf1860e30 100644 --- a/internal/harness/openapicases/testdata/instances.txt +++ b/internal/harness/openapicases/testdata/instances.txt @@ -1,2 +1,7 @@ # What the instance oracle finds at the core cases, and the reason each finding # stands: case name, what was found, reason (Reasons). +3.1.0/vocabulary.json%2Fschema that uses custom metaschema with no validation vocabulary/property/beside "no validation: invalid number, but it still validates" custom-vocabulary +3.1.0/vocabulary.json%2Fschema that uses custom metaschema with no validation vocabulary/property/besideEntry "no validation: invalid number, but it still validates" custom-vocabulary +3.1.0/vocabulary.json%2Fschema that uses custom metaschema with no validation vocabulary/property/entry "no validation: invalid number, but it still validates" custom-vocabulary +3.1.0/vocabulary.json%2Fschema that uses custom metaschema with no validation vocabulary/property/nested "no validation: invalid number, but it still validates" custom-vocabulary +3.1.0/vocabulary.json%2Fschema that uses custom metaschema with no validation vocabulary/property/wrap "no validation: invalid number, but it still validates" custom-vocabulary diff --git a/internal/harness/order.go b/internal/harness/order.go index b9ee9031a..ca01bc6df 100644 --- a/internal/harness/order.go +++ b/internal/harness/order.go @@ -88,9 +88,9 @@ func comparePermuted(ctx context.Context, oracle Oracle, spec string, baseline, // // IDs derive from pointers, so a permutation leaves every ID and registry key // unchanged, while an interning collision shows as a difference: a node minted -// at the wrong pointer, a hint kept from whichever lowering came first, a body -// that lost what a second declaration wrote. What the permutation reorders by -// design is compared regardless of order (canonicalJSON). +// at the wrong pointer, a hint chosen from whichever lowering came first, a +// body that dropped what a second declaration wrote. What the permutation +// reorders by design is compared regardless of order (canonicalJSON). func diffOrderInvariants(first *ir.Document, firstDiags []ir.Diagnostic, second *ir.Document, secondDiags []ir.Diagnostic) (string, bool) { if refused := oneRefusal(first, second); refused != "" { return refused, false @@ -221,8 +221,8 @@ func comparableOptions(arrange func(elements [][]byte) []byte, more *json.Marsha // orderFree writes the collections a mapping's entry order decides, each one // the corpus's two orders tell apart by design, as arrange writes their -// elements' own encodings: sorted, or as they stand for a later rewrite to -// sort. Sorting needs no key, so elements carrying none unique compare as the +// elements' own encodings: sorted, or as they are, for a later rewrite to sort. +// Sorting needs no key, so elements carrying none unique compare as the // multiset they are: an element's encoding sorts its own collections first, so // two whose members the permutation reversed still pair up (#683). Examples // alone hold both a mapping's entries and a sequence's elements @@ -303,7 +303,7 @@ func sortedArray(elements [][]byte) []byte { return array(elements) } -// array is an array of elements as they stand. +// array is an array of elements as they are. func array(elements [][]byte) []byte { return append(append([]byte{'['}, bytes.Join(elements, []byte{','})...), ']') } @@ -538,12 +538,13 @@ func reversedPairs(content []*yaml.Node) []*yaml.Node { } // duplicateKeys reports whether a mapping declares one key twice, each key read -// as the parser reads it: an alias stands for the node it names, whose Value is -// empty when that is no scalar (docs/parser-library.md#non-scalar-key). Reversing -// such a mapping changes which declaration wins (#95), so the two compiles would -// differ for a reason that is not a defect. It compares text alone, so a `<<` -// merge key beside a quoted or aliased `<<`, which the parser reads apart, is -// declined too, leaving that source unchecked rather than misjudged. +// as the parser reads it: an alias reads as the node it names, whose Value is +// empty when that is no scalar (docs/parser-library.md#non-scalar-key). +// Reversing such a mapping changes which declaration wins (#95), so the two +// compiles would differ for a reason that is not a defect. It compares text +// alone, so a `<<` merge key beside a quoted or aliased `<<`, which the parser +// reads apart, is declined too, leaving that source unchecked rather than +// misjudged. func duplicateKeys(node *yaml.Node) bool { seen := make(map[string]bool, len(node.Content)/2) for i := 0; i+1 < len(node.Content); i += 2 { diff --git a/internal/harness/path.go b/internal/harness/path.go index 34fcd705d..616e86421 100644 --- a/internal/harness/path.go +++ b/internal/harness/path.go @@ -168,8 +168,8 @@ var readSpecFile = os.ReadFile // isSpec reads the file at p and reports whether reg has a claim on it: a // compiler takes it, one recognizes a format it names but none serves, or one // declines it with a diagnostic, which is how a compiler reports a source that -// is its own and broken. Detection of a source no compiler recognizes is -// silent, and such a file is something else. +// is its own and broken. Detection of a source no compiler recognizes reports +// nothing, and such a file is something else. func isSpec(ctx context.Context, reg *compilers.Registry, p string) (bool, error) { data, err := readSpecFile(p) if err != nil { diff --git a/internal/harness/path_internal_test.go b/internal/harness/path_internal_test.go index e6bec33b4..7fce23e9b 100644 --- a/internal/harness/path_internal_test.go +++ b/internal/harness/path_internal_test.go @@ -47,9 +47,9 @@ func TestListDir_WalkErrorPropagates(t *testing.T) { } func TestCheckPath_UnreadableSpecInADirectoryErrors(t *testing.T) { - // A broken symlink cannot be read to decide whether a compiler takes it. The - // sweep aborts with that error rather than a silent skip, since a file it - // passed over would be one it never checked. + // A broken symlink cannot be read to decide whether a compiler takes it. + // The sweep aborts with that error rather than an unreported skip, since a + // file it passed over would be one it never checked. dir := t.TempDir() link := filepath.Join(dir, "spec.yaml") require.NoError(t, os.Symlink(filepath.Join(dir, "no-such-target"), link)) diff --git a/internal/harness/presence.go b/internal/harness/presence.go index bb424cc74..a363c5dca 100644 --- a/internal/harness/presence.go +++ b/internal/harness/presence.go @@ -7,6 +7,8 @@ import ( "context" "encoding/json/v2" "fmt" + + gocmp "github.com/google/go-cmp/cmp" ) // The What of each finding the presence oracle makes, which a record lists. @@ -17,13 +19,13 @@ const ( ) // present is the presence oracle: it holds a case writing a construct to the -// case leaving it out and, for a construct the format carries, to the case -// writing its other value. A carried construct changes the compiled document -// when written and again when its value changes; one nothing carries changes -// nothing, and Reason says why. Documents compare less their diagnostics, which -// a dropped construct can still draw, and their source table, whose hash -// differs with any text. A construct replacing a member its target writes has -// no case leaving it out, so its two values are compared alone. +// case leaving it out and, for a carried construct, to the case writing its +// other value. A carried construct changes the document when written and +// again with its value; one nothing carries changes nothing, and Reason says +// why. Documents compare less their diagnostics, which a dropped construct can +// still draw, and their source table, which any text changes, relocated where +// RelocateAbsent says. A construct replacing a member its target writes is +// held to its other value alone, which it differs from only where carried. func present(ctx context.Context, shardValue *shard, at []int, doc CaseDocument) Verdict { if doc.Absent == nil { return declined(OraclePresence, DeclineNoConstruct) @@ -31,15 +33,18 @@ func present(ctx context.Context, shardValue *shard, at []int, doc CaseDocument) if !doc.Carried && doc.Reason == "" { panic(fmt.Sprintf("harness: case %v is carried by nothing and says not why", at)) } - if doc.Replaces && (!doc.Carried || doc.Other == nil) { + if doc.Replaces && doc.Other == nil { panic(fmt.Sprintf("harness: case %v replaces a member of its target and names no other value", at)) } + if doc.RelocateAbsent && (doc.Replaces || doc.Equal == nil) { + panic(fmt.Sprintf("harness: case %v relocates a neighbour it does not compare, or names no relocation", at)) + } neighbours := [][]int{at} if !doc.Replaces { neighbours = append(neighbours, doc.Absent) } - if doc.Carried && doc.Other != nil { + if doc.Other != nil && (doc.Carried || doc.Replaces) { neighbours = append(neighbours, doc.Other) } texts := make([]string, len(neighbours)) @@ -50,28 +55,61 @@ func present(ctx context.Context, shardValue *shard, at []int, doc CaseDocument) } texts[i] = text } - return judgePresence(shardValue.axes, doc, texts) + alike := func(i, j int) bool { return texts[i] == texts[j] } + if doc.RelocateAbsent { + trees, why := relocatedTrees(texts, doc.Equal.Relocate) + if why != "" { + return declined(OraclePresence, why) + } + alike = func(i, j int) bool { return gocmp.Equal(trees[i], trees[j]) } + } + return judgePresence(shardValue.axes, doc, len(texts), alike) +} + +// relocatedTrees returns each of texts, an encoded document, read with every +// string relocated as the spelling oracle relocates a spelling's +// (relocatedSide), so documents compiled in two spellings compare by what they +// say, not where; and why one cannot be read so. A text that is no JSON is the +// harness's mistake, and a panic. +func relocatedTrees(texts []string, relocate func(string) string) ([]any, Decline) { + out := make([]any, len(texts)) + for i, text := range texts { + tree, why, err := relocatedSide([]byte(text), relocate) + if err != nil { + panic(fmt.Sprintf("harness: an encoded document does not read back: %v", err)) + } + if why != "" { + return nil, why + } + out[i] = tree + } + return out, "" } -// judgePresence is the verdict of a case whose documents compiled to texts: -// the case's, then the case leaving its construct out unless doc replaces a -// member, then the case writing its other value, when it names one. -func judgePresence(axes []Axis, doc CaseDocument, texts []string) Verdict { +// judgePresence is the verdict of a case whose count documents compiled alike +// where alike says, by index: the case's, then the case leaving its construct +// out unless doc replaces a member, then the case writing its other value, +// when it names one and the construct is carried or replaces a member. +func judgePresence(axes []Axis, doc CaseDocument, count int, alike func(i, j int) bool) Verdict { if doc.Replaces { - if texts[0] == texts[1] { - return found(OraclePresence, whatDiscarded+"\nequal to "+caseName(axes, doc.Other)) + other := caseName(axes, doc.Other) + switch { + case !doc.Carried && !alike(0, 1): + return found(OraclePresence, whatCarried+"\n"+doc.Reason+"\ndiffers from "+other) + case doc.Carried && alike(0, 1): + return found(OraclePresence, whatDiscarded+"\nequal to "+other) } return passed(OraclePresence) } absent := caseName(axes, doc.Absent) switch { - case !doc.Carried && texts[0] != texts[1]: + case !doc.Carried && !alike(0, 1): return found(OraclePresence, whatCarried+"\n"+doc.Reason+"\ndiffers from "+absent) case !doc.Carried: return passed(OraclePresence) - case texts[0] == texts[1]: + case alike(0, 1): return found(OraclePresence, whatChangesNothing+"\nequal to "+absent) - case len(texts) == 3 && texts[0] == texts[2]: + case count == 3 && alike(0, 2): return found(OraclePresence, whatDiscarded+"\nequal to "+caseName(axes, doc.Other)) } return passed(OraclePresence) diff --git a/internal/harness/presence_internal_test.go b/internal/harness/presence_internal_test.go index 232047a6c..7114311a5 100644 --- a/internal/harness/presence_internal_test.go +++ b/internal/harness/presence_internal_test.go @@ -5,6 +5,7 @@ package harness import ( "context" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -16,8 +17,8 @@ import ( ) // The cases of a three-case product: nothing written, a keyword, and its other -// value. A case's source holds its name, which stands in below for what the -// case compiles to. +// value. A case's source holds its name, which takes the place of what the case +// compiles to. const ( caseNone = 0 caseWrite = 1 @@ -81,8 +82,8 @@ func presenceOf(t *testing.T, fakeValue fake) Verdict { } // TestPresent_JudgesAKeywordAgainstItsNeighbours holds each outcome of the -// oracle to the three documents a case compiles to, as fake compiles stand -// for them: a name written is a document of that name. +// oracle to the three documents a case compiles to, as fake compiles name them: +// a name written is a document of that name. func TestPresent_JudgesAKeywordAgainstItsNeighbours(t *testing.T) { for _, tc := range []struct { name string @@ -108,6 +109,10 @@ func TestPresent_JudgesAKeywordAgainstItsNeighbours(t *testing.T) { map[string]string{"none": "b", "kw": "b", "kw~": "c"}, OutcomeOK, ""}, {"replacing and equal to its other value", replacingDocs, map[string]string{"none": "a", "kw": "b", "kw~": "b"}, OutcomeNotCarried, "value discarded\nequal to kw~"}, + {"replacing, nothing carrying it, and equal to its other value", replacingNotCarriedDocs, + map[string]string{"none": "a", "kw": "b", "kw~": "b"}, OutcomeOK, ""}, + {"replacing, nothing carrying it, and differing from its other value", replacingNotCarriedDocs, + map[string]string{"none": "b", "kw": "b", "kw~": "c"}, OutcomeNotCarried, "carried\nwhy not\ndiffers from kw~"}, {"not carried and equal to absent", notCarriedDocs, map[string]string{"none": "a", "kw": "a", "kw~": "c"}, OutcomeOK, ""}, {"not carried and differing from absent", notCarriedDocs, @@ -138,6 +143,16 @@ func replacingDocs(i int) CaseDocument { return doc } +// replacingNotCarriedDocs writes the keyword as one replacing a member its +// target writes that nothing carries: it is held to its other value alone. +func replacingNotCarriedDocs(i int) CaseDocument { + doc := notCarriedDocs(i) + if i == caseWrite { + doc.Replaces, doc.Other = true, []int{caseOther} + } + return doc +} + // notCarriedDocs writes the keyword as one nothing carries, with a reason. func notCarriedDocs(i int) CaseDocument { if i != caseWrite { @@ -254,6 +269,12 @@ func TestPresent_AssertsWhatACaseMustSay(t *testing.T) { }, map[string]*ir.Document{"none": named("a"), "kw": named("a")}, "names no other value"}, {"a document that does not encode", carriedDocs, map[string]*ir.Document{"none": named("a"), "kw": badExtDoc(), "kw~": named("c")}, "does not encode"}, + {"a relocation naming no partner", func(i int) CaseDocument { + doc := relocatedDocs(notCarriedDocs)(i) + doc.Equal = nil + return doc + }, map[string]*ir.Document{"none": named("a"), "kw": named("a")}, "names no relocation"}, + {"a relocation of a neighbour a replacement does not compare", relocatedDocs(replacingDocs), map[string]*ir.Document{"none": named("a"), "kw": named("b"), "kw~": named("c")}, "does not compare"}, } { t.Run(tc.name, func(t *testing.T) { swapDocuments(t, tc.docs, nil, "") @@ -316,3 +337,99 @@ func TestPresent_ANeighbourTheCasesWriteNothingForIsAPanic(t *testing.T) { assert.Equal(t, OutcomePanic, res.Outcome) assert.Contains(t, res.Detail, "writes nothing") } + +// entryErased is the relocation of a spelling writing the keyword on an allOf +// entry into the coordinates of one writing it flat: it leaves "/allOf/0" out. +func entryErased(s string) string { return strings.ReplaceAll(s, "/allOf/0", "") } + +// relocatedDocs writes the keyword as write does, its case written in another +// spelling than the case leaving it out, which entryErased relocates into. +func relocatedDocs(write func(i int) CaseDocument) func(i int) CaseDocument { + return func(i int) CaseDocument { + doc := write(i) + if i == caseWrite { + doc.Equal = &Equal{To: []int{caseNone}, Rule: "rule", Relocate: entryErased} + doc.RelocateAbsent = true + } + return doc + } +} + +// TestPresent_ComparesAnotherSpellingRelocated holds a case whose neighbour +// leaving the keyword out is written in another spelling to the documents +// relocated: what relocation makes one is no difference, and a difference it +// leaves, as a keyword that changes the document draws, is found. The same +// documents compared as written differ by where they say it. +func TestPresent_ComparesAnotherSpellingRelocated(t *testing.T) { + for _, tc := range []struct { + name string + write func(i int) CaseDocument + docs map[string]string + outcome Outcome + detail string + }{ + {"not carried, alike once relocated", relocatedDocs(notCarriedDocs), + map[string]string{"none": "c", "kw": "c/allOf/0"}, OutcomeOK, ""}, + {"not carried, a difference relocation leaves", relocatedDocs(notCarriedDocs), + map[string]string{"none": "c", "kw": "d/allOf/0"}, OutcomeNotCarried, "carried\nwhy not\ndiffers from none"}, + {"not carried, compared as written", notCarriedDocs, + map[string]string{"none": "c", "kw": "c/allOf/0"}, OutcomeNotCarried, "carried\nwhy not\ndiffers from none"}, + {"carried, alike once relocated", relocatedDocs(carriedDocs), + map[string]string{"none": "c", "kw": "c/allOf/0", "kw~": "e/allOf/0"}, OutcomeNotCarried, "changes nothing\nequal to none"}, + {"carried, a value alike once relocated", relocatedDocs(carriedDocs), + map[string]string{"none": "c", "kw": "d/allOf/0", "kw~": "d"}, OutcomeNotCarried, "value discarded\nequal to kw~"}, + {"carried, differing from both", relocatedDocs(carriedDocs), + map[string]string{"none": "c", "kw": "d/allOf/0", "kw~": "e/allOf/0"}, OutcomeOK, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + docs := map[string]*ir.Document{} + for n, title := range tc.docs { + docs[n] = named(title) + } + swapDocuments(t, docs, nil, "") + + verdict := presenceOf(t, presenceProduct(tc.write)) + + assert.True(t, verdict.Asked()) + assert.Equal(t, tc.outcome, verdict.Outcome) + assert.Equal(t, tc.detail, verdict.Detail) + }) + } +} + +// TestRelocatedTrees_DeclinesWhatItCannotCompare holds a relocated read to +// the spelling oracle's declines: two names of one object relocating to one, +// and a tree nesting past the bound. A text that is no JSON is a panic. +func TestRelocatedTrees_DeclinesWhatItCannotCompare(t *testing.T) { + deep := strings.Repeat("[", maxSpellingDepth+2) + strings.Repeat("]", maxSpellingDepth+2) + for _, tc := range []struct { + name, text string + want Decline + }{ + {"two names relocating to one", `{"c": 1, "c/allOf/0": 2}`, DeclineRelocationCollides}, + {"a tree nesting past the bound", deep, DeclineTooDeep}, + } { + t.Run(tc.name, func(t *testing.T) { + trees, why := relocatedTrees([]string{`{"c": 1}`, tc.text}, entryErased) + assert.Nil(t, trees) + assert.Equal(t, tc.want, why) + }) + } + assert.Panics(t, func() { relocatedTrees([]string{"{"}, entryErased) }, "a text that is no JSON") +} + +// TestPresent_DeclinesWhereRelocationCollides holds a case whose document +// names two places one once relocated to the spelling oracle's decline: the +// two cannot be compared by what they say. +func TestPresent_DeclinesWhereRelocationCollides(t *testing.T) { + colliding := named("c") + colliding.Unmodeled = ir.Unmodeled{ + "openapi:c": {Reason: ir.ReasonVendorExtension, Value: ir.RawValue("1")}, + "openapi:c/allOf/0": {Reason: ir.ReasonVendorExtension, Value: ir.RawValue("2")}, + } + swapDocuments(t, map[string]*ir.Document{"none": named("c"), "kw": colliding}, nil, "") + + verdict := presenceOf(t, presenceProduct(relocatedDocs(notCarriedDocs))) + + assert.Equal(t, declined(OraclePresence, DeclineRelocationCollides), verdict) +} diff --git a/internal/harness/recorded.go b/internal/harness/recorded.go index 56f67da1a..f5d91d96d 100644 --- a/internal/harness/recorded.go +++ b/internal/harness/recorded.go @@ -19,8 +19,8 @@ const unclassified = "unclassified" // first line of the verdict's Detail, its signature. type Finding struct{ Name, What string } -// Recorded is an oracle's known findings at the core cases, by name, each -// with what was found and the reason it stands: a file of lines +// Recorded is an oracle's known findings at the core cases, by name, each with +// what was found and the reason it is recorded: a file of lines // "namewhatreason", a line starting "#" a comment. type Recorded map[string]recordLine @@ -195,7 +195,7 @@ func byName(results []Result) map[string]Result { // verdict is a spelling of a case writing two keywords whose every place it // differs at, a part of its What, is a place a spelling of either part differs // at in run. Each part is held to the records itself, so a place forgiven here -// is one already recorded or reported where it stands alone. +// is one already recorded or reported where it sits alone. func explained(rec Recorded, run map[string]Result, result Result, verdict Verdict) bool { finding := findingOf(result, verdict) if rec.Explains(finding, result.Spec) || rec.Explains(finding, result.Like) { diff --git a/internal/harness/recorded_test.go b/internal/harness/recorded_test.go index e9cc77350..878115c42 100644 --- a/internal/harness/recorded_test.go +++ b/internal/harness/recorded_test.go @@ -163,7 +163,7 @@ func TestUnexplained_KeepsWhatNoRecordExplains(t *testing.T) { assert.Contains(t, harness.Report(got), "presence exploded", "the report names the fault beside the finding") bare := harness.Unexplained(results, nil) - require.Len(t, bare, 3, "with no record, every finding stands") + require.Len(t, bare, 3, "with no record, every finding remains") assert.Equal(t, harness.OutcomeSpellingDependent, bare[0].Outcome) assert.Equal(t, results[1].Verdicts[:2], bare[0].Verdicts) } @@ -228,7 +228,7 @@ func TestFindings_ListTheDeclinesARecordHolds(t *testing.T) { assert.Equal(t, "g/q declined declined: not judged\ng/s declined declined: error diagnostic\n", harness.Report(got)) got = harness.Unexplained(results, map[harness.Oracle]harness.Recorded{harness.OracleInstance: record}) - require.Len(t, got, 3, "the presence oracle's decline stands where its record does not list it") + require.Len(t, got, 3, "the presence oracle's decline remains where its record does not list it") assert.Equal(t, "g/p", got[0].Spec) assert.Equal(t, harness.OraclePresence, got[0].Verdicts[0].Oracle) } diff --git a/internal/harness/sequence.go b/internal/harness/sequence.go index 40d7d51f2..7a1a27e56 100644 --- a/internal/harness/sequence.go +++ b/internal/harness/sequence.go @@ -235,8 +235,8 @@ func (w *sequenceWalk) held(pointer string) bool { return false } -// keyText is a mapping key as the parser reads it: an alias stands for the -// node it names. +// keyText is a mapping key as the parser reads it: an alias reads as the node +// it names. func keyText(key *yaml.Node) string { if key.Kind == yaml.AliasNode { return key.Alias.Value @@ -344,9 +344,12 @@ func mayNameAnIndex(s string) bool { } // rewriteFrom is rewriteIndices' walk from the '/' at start, and whether it -// rewrote an index. +// rewrote an index. A "-" right after a sequence's pointer is the marker of a +// key minted for a variant an entry of that sequence distributes, which names +// the entry by the index after it, so the walk reads that index as the +// sequence's and leaves the marker out of the pointer it keeps. func rewriteFrom(s string, start int, seqs sequences, write func(n, i int) string) (string, bool) { - var b strings.Builder + var b, walked strings.Builder b.WriteString(s[:start]) applied := false for at := start; at < len(s); { @@ -356,8 +359,15 @@ func rewriteFrom(s string, start int, seqs sequences, write func(n, i int) strin } token := s[at+1 : end] b.WriteByte('/') - if i, ok := indexIn(token, seqs[s[start:at]]); ok { - token, applied = write(seqs[s[start:at]], i), true + n, sequence := seqs[walked.String()] + if sequence && token == "-" { + b.WriteString(token) + at = end + continue + } + walked.WriteString(s[at:end]) + if i, ok := indexIn(token, n); ok { + token, applied = write(n, i), true } b.WriteString(token) at = end diff --git a/internal/harness/sequence_internal_test.go b/internal/harness/sequence_internal_test.go index e13cabdc0..8ac988198 100644 --- a/internal/harness/sequence_internal_test.go +++ b/internal/harness/sequence_internal_test.go @@ -408,3 +408,27 @@ func TestRewriteIndices_RewritesTheIndicesOfReversedSequences(t *testing.T) { }) } } + +// TestRewriteIndices_ReadsAnEntryDistributedKeyAsItsEntry holds the walk to a +// composed key minted for a union an entry of a reversed allOf distributes: +// "allOf/-/" names index k of that allOf, which is erased and rebased as +// an index written plainly is, the marker kept (GitHub #2101). +func TestRewriteIndices_ReadsAnEntryDistributedKeyAsItsEntry(t *testing.T) { + t.Parallel() + written := sequences{"/c/X/allOf": 2, "/c/X/allOf/0/allOf": 2} + moved := sequences{"/c/X/allOf": 2, "/c/X/allOf/1/allOf": 2} + for _, tc := range []struct{ name, in, erased, rebased string }{ + {"a variant an entry distributes", "type/composed/c/X/allOf/-/1/oneOf/0", + "type/composed/c/X/allOf/-/-/oneOf/0", "type/composed/c/X/allOf/-/0/oneOf/0"}, + {"a variant a nested entry distributes", "type/composed/c/X/allOf/-/0/allOf/1/oneOf/0", + "type/composed/c/X/allOf/-/-/allOf/-/oneOf/0", "type/composed/c/X/allOf/-/1/allOf/1/oneOf/0"}, + {"its provenance pointer", "/c/X/allOf/-/1/oneOf/0", "/c/X/allOf/-/-/oneOf/0", "/c/X/allOf/-/0/oneOf/0"}, + {"a marker past the sequence's length", "/c/X/allOf/-/2/oneOf/0", "/c/X/allOf/-/2/oneOf/0", "/c/X/allOf/-/2/oneOf/0"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.erased, erase(tc.in, written)) + assert.Equal(t, tc.rebased, rebase(tc.in, moved)) + }) + } +} diff --git a/internal/harness/sequenceorder.go b/internal/harness/sequenceorder.go index acdded3f1..a1bdd3f28 100644 --- a/internal/harness/sequenceorder.go +++ b/internal/harness/sequenceorder.go @@ -49,23 +49,23 @@ func sequenceOrderInvariant(ctx context.Context, spec string, data []byte, compi // leave untouched: the diagnostics, the document and the flattened shapes, // in their sources' coordinates. A tie is a member two reports alike but // for their places decide between two declarations, the other way round in -// each order (tiedBy), or what a moved report decided. Of a node a tie names, -// or one at or beneath a moved report's site or a tied member's fold mints -// (rewriter.minted), only what a property's fold settles from every -// declaration alike is compared (rewriter.foldedOf, rewriter.statedOf). It -// declines as compareForms does, and several files. +// each order (tiedBy); a report the reversal moves ties nothing (untied). Of +// a node a tie names, or one a tied member's fold mints (rewriter.minted), +// only what a property's fold settles from every declaration alike is +// compared (rewriter.foldedOf, rewriter.statedOf). It declines as +// compareForms does, and several files. func diffSequenceInvariants(first *ir.Document, firstDiags []ir.Diagnostic, second *ir.Document, secondDiags []ir.Diagnostic, perm permutation) (string, bool, Decline) { if first != nil && len(first.Sources) > 1 { return "", false, DeclineReadsAnotherFile } stated, a := factsOf(reportsOf(firstDiags, nil, perm.written), perm.written) restated, b := factsOf(reportsOf(secondDiags, perm.moved, perm.written), perm.written) - ties, left, right := movedReports(a, b, perm.written) - tied, moved := tiedBy(stated, restated), ties - ties.nodes = slices.Compact(slices.Sorted(slices.Values(slices.Concat(ties.nodes, tied)))) - ties = settledFrom(settledFrom(ties, first, perm.written), second, perm.moved) + tied := tiedBy(stated, restated) + left, right := difference(a, b) + ties := settledFrom(settledFrom(tieSites{nodes: tied}, first, perm.written), second, perm.moved) ties = prunedByTie(ties, first, second, perm) - ties.stated = statedAlone(statedAlone(tied, moved, ties.nodes, first, perm.written), moved, ties.nodes, second, perm.moved) + conflicted := tiedByConflictsAlone(tied, stated, restated) + ties.stated = statedAlone(statedAlone(conflicted, ties.nodes, first, perm.written), ties.nodes, second, perm.moved) left, right = untied(left, ties, perm.written), untied(right, ties, perm.written) refused := oneRefusal(first, second) var forms []string @@ -77,7 +77,7 @@ func diffSequenceInvariants(first *ir.Document, firstDiags []ir.Diagnostic, seco } } written, reversed := heldBy(first, perm.written, nil), heldBy(second, perm.moved, perm.moved) - onlyStated, onlyRestated := unpairedFacts(keptTypes(stated, written), keptTypes(restated, reversed), ties.nodes) + onlyStated, onlyRestated := unpairedFacts(chosenPlaces(stated, written), chosenPlaces(restated, reversed), ties.nodes) var found []string if unpaired := renderUnpaired(append(left, onlyStated...), append(right, onlyRestated...)); unpaired != "" { found = append(found, "diagnostics depend on sequence order (-as-written +reversed):\n"+unpaired) @@ -89,6 +89,9 @@ func diffSequenceInvariants(first *ir.Document, firstDiags []ir.Diagnostic, seco if wrong := contradicted(written, reversed, stated, tied); len(wrong) > 0 { found = append(found, "a tie's reports name the declaration the member takes as the one that lost:\n"+strings.Join(wrong, "\n")) } + if alike := alikeByOrder(first, second, written, reversed, tied, ties.members, perm.written); len(alike) > 0 { + found = append(found, "a member names one of two nodes alike by sequence order:\n"+strings.Join(alike, "\n")) + } return strings.Join(found, "\n"), len(found) == 0, "" } @@ -161,24 +164,36 @@ func sameNodes(left, right []report, first, second func(string) (string, bool)) return keptLeft, keptRight } -// nodeKey is reportValue's key with its node as identify writes it and no -// pointer, as a report naming a node is erased (reportsOf), or empty, pairing -// with nothing, where reportValue names no node or identify cannot tell the -// node by what it holds. +// nodeKey is reportValue's key with the node it is about (memberOf) as +// identify writes it, where it names it or lists it as decided, and no +// pointer, its own or that of the model declaring a member it decided, or +// empty, pairing with nothing, where reportValue is about no node or identify +// cannot tell the node by what it holds. func nodeKey(reportValue report, identify func(string) (string, bool)) string { - if reportValue.raw.Provenance.Node == "" { + member := memberOf(reportValue.raw) + if member == "" { return "" } - node, ok := identify(reportValue.raw.Provenance.Node) + node, ok := identify(member) if !ok { return "" } diagnostic := reportValue.raw - diagnostic.Provenance.Pointer, diagnostic.Provenance.Node = "", node + diagnostic.Provenance.Pointer = "" + if diagnostic.Provenance.Node != "" { + diagnostic.Provenance.Node = node + return diagnosticKey(diagnostic) + } + diagnostic.Related = slices.Clone(diagnostic.Related) + for i, related := range diagnostic.Related { + if isDecided(related) { + diagnostic.Related[i].Provenance.Node, diagnostic.Related[i].Provenance.Pointer = node, "" + } + } return diagnosticKey(diagnostic) } -// formDecline is the decline a canonical form's error stands for, if any. +// formDecline is the decline a canonical form's error names, if any. func formDecline(err error) Decline { switch { case errors.Is(err, errTooDeep): @@ -191,102 +206,120 @@ func formDecline(err error) Decline { } // report is one diagnostic as the comparison reads it, in the coordinates of -// the source as written: as diagnosticKey renders it, the same with every -// index of a reversed sequence erased, and with no pointer where it names a -// node, its pointer and its node; rebased, the diagnostic in those -// coordinates, what else it concerns too; and raw, the diagnostic in its own -// compile's coordinates. A report naming the node it decided is told apart by that -// node: it sits at the declaration the order made lose, which a nested allOf -// can place at another depth. +// the source as written: as diagnosticKey renders it, each member it decided +// erased (decidedErased), its pointer, and the node it is about (memberOf); +// rebased, the diagnostic in those coordinates, what else it concerns too; and +// raw, the diagnostic in its own compile's coordinates. type report struct { - key, erased, pointer, node string - rebased, raw ir.Diagnostic + key, pointer, node string + rebased, raw ir.Diagnostic } -// tieSites is what the reports a reversal moved decided: the erased pointer of -// each, at or beneath which nothing is compared, the erased node of each naming -// one (ir.Provenance's Node) or of each member a report states a tie decided -// (tiedBy), which is not compared wherever it sits, the erased pointer of each -// tied member (settledFrom), at or beneath which only what its fold mints is -// left out (rewriter.minted), the models holding a member a tie decided, whose -// reports follow it, and the tied members a stated tie alone decided -// (statedAlone), whose docs are compared. -type tieSites struct{ pointers, nodes, members, holders, stated []string } +// tieSites is what the ties decided: the erased node of each member a report +// states a tie decided (tiedBy), which is not compared wherever it sits, the +// erased pointer of each tied member (settledFrom), at or beneath which only +// what its fold mints is left out (rewriter.minted), the models holding a +// member a tie decided, whose reports follow it, and the tied members conflicts +// alone decided (tiedByConflictsAlone, statedAlone), whose docs are compared. +type tieSites struct{ nodes, members, holders, stated []string } -// reportsOf reads diags, rebasing each pointer and node from the coordinates -// of from, when given, to those of the source as written, where written lists -// the reversed sequences. +// reportsOf reads diags, each as every member it is about draws it +// (byMember), rebasing each pointer and node from the coordinates of from, +// when given, to those of the source as written, where written lists the +// reversed sequences. func reportsOf(diags []ir.Diagnostic, from, written sequences) []report { out := make([]report, 0, len(diags)) for _, diagnostic := range diags { - raw := diagnostic - diagnostic.Provenance.Pointer = jsontext.Pointer(rebase(string(diagnostic.Provenance.Pointer), from)) - diagnostic.Provenance.Node = rebase(diagnostic.Provenance.Node, from) - diagnostic.Related = slices.Clone(diagnostic.Related) - for i := range diagnostic.Related { - provenance := &diagnostic.Related[i].Provenance - provenance.Pointer, provenance.Node = jsontext.Pointer(rebase(string(provenance.Pointer), from)), rebase(provenance.Node, from) - } - irDiagnostic := diagnostic - irDiagnostic.Provenance.Pointer = jsontext.Pointer(erase(string(diagnostic.Provenance.Pointer), written)) - irDiagnostic.Provenance.Node = erase(diagnostic.Provenance.Node, written) - if irDiagnostic.Provenance.Node != "" { - irDiagnostic.Provenance.Pointer = "" - } - irDiagnostic.Related = slices.Clone(diagnostic.Related) - for i := range irDiagnostic.Related { - provenance := &irDiagnostic.Related[i].Provenance - provenance.Pointer, provenance.Node = jsontext.Pointer(erase(string(provenance.Pointer), written)), erase(provenance.Node, written) + for _, said := range byMember(diagnostic) { + out = append(out, reportOf(said, from, written)) } - out = append(out, report{key: diagnosticKey(diagnostic), erased: diagnosticKey(irDiagnostic), pointer: string(diagnostic.Provenance.Pointer), - node: diagnostic.Provenance.Node, rebased: diagnostic, raw: raw}) } return out } -// movedReports pairs what one compile reports, a, and the other, b, does not, a -// report of each equal as report.erased reads them and differing in their -// pointers, which is a report the reversal moved: its erased pointer is a tie -// site, and its erased node, where it names one, a tied node. Pairs match -// greedily, in key order; it returns what stays unpaired as written and -// reversed. -func movedReports(a, b []report, written sequences) (ties tieSites, left, right []report) { - onlyFirst, onlySecond := difference(a, b) - candidates := map[string][]report{} - for _, b := range onlySecond { - candidates[b.erased] = append(candidates[b.erased], b) - } - for _, a := range onlyFirst { - i := slices.IndexFunc(candidates[a.erased], func(b report) bool { return b.pointer != a.pointer }) - if i < 0 { - left = append(left, a) - continue - } - candidates[a.erased] = slices.Delete(candidates[a.erased], i, i+1) - ties.pointers = append(ties.pointers, erase(a.pointer, written)) - if a.node != "" { - ties.nodes = append(ties.nodes, erase(a.node, written)) +// byMember is diagnostic as each member it is about draws it: a member fold's +// report about one declaration, naming no node and no chosen place, is a report +// per member it decided (ir.RelatedDecided), listing that member alone, since +// each model composing the declaration drew it of its own member and the run +// said them once. Any other diagnostic is itself. +func byMember(diagnostic ir.Diagnostic) []ir.Diagnostic { + others := slices.DeleteFunc(slices.Clone(diagnostic.Related), isDecided) + if diagnostic.Provenance.Node != "" || slices.ContainsFunc(others, isChosen) || len(diagnostic.Related)-len(others) < 2 { + return []ir.Diagnostic{diagnostic} + } + var out []ir.Diagnostic + for _, member := range diagnostic.Related { + if isDecided(member) { + said := diagnostic + said.Related = append(slices.Clone(others), member) + out = append(out, said) } } - for _, rest := range candidates { - right = append(right, rest...) + return out +} + +// memberOf is the node diagnostic, a report byMember gave, is about: the one +// its place names (ir.Provenance's Node), or else, where it names no chosen +// place, the member it lists as decided, or none. +func memberOf(diagnostic ir.Diagnostic) string { + if diagnostic.Provenance.Node != "" || slices.ContainsFunc(diagnostic.Related, isChosen) { + return diagnostic.Provenance.Node + } + if i := slices.IndexFunc(diagnostic.Related, isDecided); i >= 0 { + return diagnostic.Related[i].Provenance.Node + } + return "" +} + +// isChosen reports whether related names a place a report chose +// (ir.RelatedChosen). +func isChosen(related ir.Related) bool { return related.Role == ir.RelatedChosen } + +// isDecided reports whether related names a node a report decided +// (ir.RelatedDecided). +func isDecided(related ir.Related) bool { return related.Role == ir.RelatedDecided } + +// reportOf is diagnostic as the comparison reads it (report), rebased from the +// coordinates of from, when given, where written lists the reversed sequences. +func reportOf(diagnostic ir.Diagnostic, from, written sequences) report { + raw := diagnostic + diagnostic.Provenance.Pointer = jsontext.Pointer(rebase(string(diagnostic.Provenance.Pointer), from)) + diagnostic.Provenance.Node = rebase(diagnostic.Provenance.Node, from) + diagnostic.Related = slices.Clone(diagnostic.Related) + for i := range diagnostic.Related { + provenance := &diagnostic.Related[i].Provenance + provenance.Pointer, provenance.Node = jsontext.Pointer(rebase(string(provenance.Pointer), from)), rebase(provenance.Node, from) + } + return report{key: diagnosticKey(decidedErased(diagnostic, written)), pointer: string(diagnostic.Provenance.Pointer), + node: rebase(memberOf(raw), from), rebased: diagnostic, raw: raw} +} + +// decidedErased is diagnostic with each member it lists as decided +// (ir.RelatedDecided) named with every index of a reversed sequence, written, +// erased. A member a model brings is named by its first declaration, which the +// reversal moves to another entry of that model's allOf (GitHub #1931), so +// only the erased node names it in both orders. +func decidedErased(diagnostic ir.Diagnostic, written sequences) ir.Diagnostic { + diagnostic.Related = slices.Clone(diagnostic.Related) + for i, related := range diagnostic.Related { + if isDecided(related) { + diagnostic.Related[i].Provenance.Node = erase(related.Provenance.Node, written) + } } - slices.Sort(ties.pointers) - slices.Sort(ties.nodes) - ties.pointers, ties.nodes = slices.Compact(ties.pointers), slices.Compact(ties.nodes) - return ties, left, right + return diagnostic } -// untied returns the reports of rs no tie decided: one naming a tied node or a -// model holding one, or sitting at or beneath a tie site or a tied member's -// pointer, says what a tie decided, in the one order it decided it. +// untied returns the reports of rs no tie decided: one about a tied node +// (memberOf) or a model holding one, or sitting at or beneath a tied member's +// pointer, says what a tie decided, in the one order it decided it, a report +// the reversal moves among them. func untied(rs []report, ties tieSites, written sequences) []report { return slices.DeleteFunc(rs, func(reportValue report) bool { node := erase(reportValue.node, written) _, tied := slices.BinarySearch(ties.nodes, node) _, holds := slices.BinarySearch(ties.holders, node) at := erase(reportValue.pointer, written) - return reportValue.node != "" && (tied || holds) || atSite(ties.pointers, at) || atSite(ties.members, at) + return reportValue.node != "" && (tied || holds) || atSite(ties.members, at) }) } @@ -314,16 +347,15 @@ func renderUnpaired(left, right []report) string { return strings.Join(append(lines, reversed...), "\n") } -// settledFrom returns ties with every member doc settles from a tied one: a -// member a moved report names, one declared at or beneath where a moved report -// sits, as a fold of inline declarations reports where they are written, or at -// a tied member's pointer or minted beneath it, and a model's own member whose -// flattening overrides a tied declaration (ir.FlatProperty.Overridden), which -// reads what that tie decided, to a fixpoint (tieSettled). -// Each tied member's pointer joins ties.members. IDs are erased in seqs, doc's -// coordinates; a nil doc, as a refused compile leaves, adds none. +// settledFrom returns ties with every member doc settles from a tied one: one +// declared at a tied member's pointer or minted beneath it, and a model's own +// member whose flattening overrides a tied declaration +// (ir.FlatProperty.Overridden), which reads what that tie decided, to a +// fixpoint (tieSettled). Each tied member's pointer joins ties.members. IDs are +// erased in seqs, doc's coordinates; a nil doc, as a refused compile leaves, +// adds none. func settledFrom(ties tieSites, doc *ir.Document, seqs sequences) tieSites { - if len(ties.nodes)+len(ties.pointers)+len(ties.members) == 0 || doc == nil { + if len(ties.nodes)+len(ties.members) == 0 || doc == nil { return ties } tied := map[string]bool{} @@ -346,22 +378,21 @@ func settledFrom(ties tieSites, doc *ir.Document, seqs sequences) tieSites { return ties } -// tieSettled ties each own member of models declared at or beneath where a -// moved report sits (ties.pointers), at a tied member's pointer (ties.members), -// or overriding a tied declaration, and each union whose inferred -// discriminator reads a tied member (inferenceTied), adds each tied member's -// pointer to sites and its model to holders, and reports whether it tied any -// or found a tied member's pointer. A member declared beneath a tied member's -// pointer is written there in either order, so it is not tied for that, unless -// the tied member's fold minted it (minted), as a model it composes declares -// one. +// tieSettled ties each own member of models declared at a tied member's pointer +// (ties.members) or overriding a tied declaration, and each union whose +// inferred discriminator reads a tied member (inferenceTied), adds each tied +// member's pointer to sites and its model to holders, and reports whether it +// tied any or found a tied member's pointer. A member declared beneath a tied +// member's pointer is written there in either order, so it is not tied for +// that, unless the tied member's fold minted it (minted), as a model it +// composes declares one. func tieSettled(doc *ir.Document, models []ir.TypeID, seqs sequences, ties tieSites, tied, sites, holders map[string]bool) bool { grew := false members := slices.Concat(ties.members, slices.Collect(maps.Keys(sites))) isTied := func(propertyDecl ir.PropertyDecl) bool { at := erase(string(propertyDecl.Property.Provenance.Pointer), seqs) _, atMember := slices.BinarySearch(ties.members, at) - return tied[erase(string(propertyDecl.Property.ID), seqs)] || atSite(ties.pointers, at) || atMember || + return tied[erase(string(propertyDecl.Property.ID), seqs)] || atMember || minted(members, string(propertyDecl.Property.ID), at) } for _, id := range models { @@ -404,13 +435,13 @@ func inferenceTied(doc *ir.Document, union *ir.Union, isTied func(ir.PropertyDec return false } -// prunedByTie returns ties with each anonymous type node present in only one -// of first and second that is reachable from a tied property in the document +// prunedByTie returns ties with each anonymous type node present in only one of +// first and second that is reachable from a tied property in the document // holding it: when a tie trades which declaration wins, seeded pruning removes -// the losing declaration's unreferenced anonymous node and its unreachable +// the passed-over declaration's unreferenced anonymous node and its unreachable // descendants, so those nodes exist only in the order where that declaration -// won. Nodes present at the same rebased ID in both documents, and any node -// not reachable from a tied property, stay compared. +// won. Nodes present at the same rebased ID in both documents, and any node not +// reachable from a tied property, stay compared. func prunedByTie(ties tieSites, first, second *ir.Document, perm permutation) tieSites { if first == nil || second == nil || len(ties.nodes) == 0 { return ties @@ -477,8 +508,11 @@ func appendPruned(dst []string, doc *ir.Document, rebaseFrom, eraseSeqs sequence return dst } -// difference returns the reports of a that b does not hold and those of b -// that a does not, as multisets of their keys, each sorted by key. +// difference returns the reports of a that b does not hold and those of b that +// a does not, as multisets of their keys, each sorted by key. A key holds no +// message, which alone says what a fold report's declarations disagree over, so +// two reports of one place, chosen place and member, one over a type and one +// over a bound, are one here (GitHub #2340). func difference(a, b []report) (onlyA, onlyB []report) { return without(a, b), without(b, a) } diff --git a/internal/harness/sequenceorder_internal_test.go b/internal/harness/sequenceorder_internal_test.go index f0d85716c..6f0b5158f 100644 --- a/internal/harness/sequenceorder_internal_test.go +++ b/internal/harness/sequenceorder_internal_test.go @@ -53,7 +53,15 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { } common := "Common: {type: object, properties: {success: {type: boolean, enum: [true]}}}" failure := "Failure: {type: object, properties: {success: {type: boolean, enum: [false]}}}" - const merged = "the same holds at each of 2 models composing both" + // merged is how a report said once for the components models composing + // field opens, as the document's JSON writes it. + merged := func(field string, models ...string) string { + for i, model := range models { + models[i] = s + "/" + model + } + listed := strings.Join(models[:len(models)-1], ", ") + " and " + models[len(models)-1] + return `field \"` + field + `\" of ` + listed + } tests := []struct { name string src string @@ -70,6 +78,92 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { codes: map[string]string{"openapi/degraded-construct": s + "/AB/allOf/0/properties/p"}, want: passed(OracleSequenceOrder), }, + { + // The refusal names the member it decided, which takes the ID of + // its first declaration, so the member's ID follows the order + // while the refusal does not move. + name: "a default the narrower declaration refuses, of a member its first declaration names", + src: schemas("AB: {allOf: [{type: object, properties: {p: {type: number, default: 1.5}}}, " + + "{type: object, properties: {p: {type: integer}}}]}"), + codes: map[string]string{"openapi/degraded-construct": s + "/AB/allOf/0/properties/p"}, + want: passed(OracleSequenceOrder), + }, + { + // D1's and D2's lists, set apart by D2's deprecation, overlap and + // hold as many declarations, so the later wins: D1 is passed over + // as written, its default with it, and D2 reversed, where D1 gives + // its default up to D0's. So D1 holds the tie's report in one order + // and the default's in the other, which agree but for what each + // chose and says, and p takes [a] in either order. + name: "a tie whose report leaves a declaration that reports its default reversed", + src: schemas("D0: {type: object, properties: {p: {type: array, items: {type: string}, default: [a]}}}", + "D1: {type: object, properties: {p: {type: array, maxItems: 5, items: {type: string}, default: [b]}}}", + "D2: {type: object, properties: {p: {type: array, maxItems: 5, items: {type: string}, deprecated: true}}}", + composes("M0", "D0", "D1", "D2")), + kept: []string{`"default":{"kind":"list","list":[{"kind":"string","string":"a"}]}`}, + codes: map[string]string{"openapi/degraded-construct": s + "/D1/properties/p"}, + want: passed(OracleSequenceOrder), + }, + { + // Two declarations give a list and two a string, so the later wins: + // p takes D3's list as written and D0's string reversed, a tie its + // conflicts state. As written D1's default is refused, in a report + // naming p only in its decided entry, and reversed D1 is passed + // over with its default, so that report is the tie's to forgive. + name: "a refusal of a default, in one order, at a member a tie decided", + src: schemas("D0: {type: object, properties: {p: {type: string}}}", + "D1: {type: object, properties: {p: {type: array, items: {type: string}, default: ab}}}", + "D2: {type: object, properties: {p: {type: string}}}", + "D3: {type: object, properties: {p: {type: array, items: {type: string, maxLength: 3}}}}", + composes("M0", "D0", "D1", "D2", "D3")), + codes: map[string]string{"openapi/degraded-construct": s + "/D1/properties/p", "openapi/conflicting-redeclaration": s + "/D0/properties/p"}, + want: passed(OracleSequenceOrder), + }, + { + // The refusal moves from the list entry to the string one, and a + // mirrored tie decides its member in either order: the refusal + // forgives itself, and nothing else differs. + name: "a refusal the reversal moves, at a member a mirrored tie decided", + src: fixtureMovedRefusal, + codes: map[string]string{"openapi/degraded-construct": s + "/AB/allOf/2/properties/p", + "openapi/conflicting-redeclaration": s + "/AB/allOf/0/properties/p"}, + want: passed(OracleSequenceOrder), + }, + { + // M0 composes 66 declarations of p, past the 64 one fold judges: + // the first 64 written are judged in either order, D00's + // description among them, and the cut is reported where D64 is + // written. + name: "a member declared past the fold's budget", + src: schemas(budgetCutSchemas()...), + kept: []string{`"description":"zero"`}, + codes: map[string]string{"openapi/budget-exceeded": s + "/D64/properties/p"}, + want: passed(OracleSequenceOrder), + }, + { + // Each declaration restricts p to one lifecycle, so p is visible + // in none in either order, reported once, at the first written of + // the declarations restricting it. + name: "two declarations restricting a member to disjoint lifecycles", + src: schemas("D0: {type: object, properties: {p: {type: string, readOnly: true}}}", + "D1: {type: object, properties: {p: {type: string, writeOnly: true}}}", composes("M0", "D0", "D1")), + kept: []string{`"visibility":{"invisibleInEveryLifecycle":true}`}, + codes: map[string]string{"openapi/disjoint-visibility": s + "/D0/properties/p"}, + want: passed(OracleSequenceOrder), + }, + { + // C is restricted both ways and reported by its own reader, so + // the fold of A, B and C finds the lifecycles already empty and + // reports nothing of its own in either order. + name: "a declaration restricted both ways beside two restricted one way", + src: schemas("A: {type: object, properties: {p: {type: string, readOnly: true}}}", + "B: {type: object, properties: {p: {type: string, writeOnly: true}}}", + "C: {type: object, properties: {p: {type: string, readOnly: true, writeOnly: true}}}", + composes("M0", "A", "B", "C")), + kept: []string{`"visibility":{"invisibleInEveryLifecycle":true}`}, + codes: map[string]string{"openapi/disjoint-visibility": s + "/C/properties/p"}, + want: passed(OracleSequenceOrder), + }, { name: "a redeclared property whose types disagree", src: schemas("AB: {allOf: [{properties: {p: {type: string}, q: {type: object, properties: {x: {type: string}}}}}, " + @@ -79,7 +173,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { }, { // The base's tie flips its member with the order, and the member a - // model composing it declares again folds with what the tie kept. + // model composing it declares again folds with what the tie chose. name: "a tie among inline declarations decides what overrides it", src: schemas("Base: {allOf: [{type: object, properties: {x: {type: integer}}}, {type: object, properties: {x: {type: string}}}]}", "Sub: {allOf: [{$ref: '#/components/schemas/Base'}, {type: object, properties: {x: {type: string, description: d}}}]}"), @@ -88,18 +182,18 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { }, { // The models composing both components draw one report, at the - // declaration that lost, which a reversal moves to the other + // declaration passed over, which a reversal moves to the other // declaration rather than to another entry. name: "a tie between two components several models compose", src: schemas(composes("Both", "Common", "Failure"), composes("Both2", "Common", "Failure"), common, failure), - kept: []string{merged}, + kept: []string{merged("success", "Both", "Both2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/Common/properties/success"}, want: passed(OracleSequenceOrder), }, { name: "the same tie with the components composed in the other order", src: schemas(composes("Both", "Failure", "Common"), composes("Both2", "Failure", "Common"), common, failure), - kept: []string{merged}, + kept: []string{merged("success", "Both", "Both2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/Failure/properties/success"}, want: passed(OracleSequenceOrder), }, @@ -110,7 +204,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { src: schemas(composes("Both", "A", "B", "C"), composes("Both2", "A", "B", "C"), "A: {type: object, properties: {p: {type: string}}}", "B: {type: object, properties: {p: {type: integer}}}", "C: {type: object, properties: {p: {type: boolean}}}"), - kept: []string{merged}, + kept: []string{merged("p", "Both", "Both2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/A/properties/p"}, want: passed(OracleSequenceOrder), }, @@ -121,7 +215,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { "Common: {type: object, properties: {success: {$ref: '#/components/schemas/True'}}}", "Failure: {type: object, properties: {success: {$ref: '#/components/schemas/False'}}}", "True: {type: boolean, enum: [true]}", "False: {type: boolean, enum: [false]}"), - kept: []string{merged}, + kept: []string{merged("success", "Both", "Both2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/Common/properties/success"}, want: passed(OracleSequenceOrder), }, @@ -133,7 +227,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { src: schemas(composes("Both", "FailureX", "Other"), composes("Both2", "FailureX", "Other"), common, "FailureX: {allOf: [{$ref: '#/components/schemas/Common'}, {type: object, properties: {success: {type: string}}}]}", "Other: {type: object, properties: {success: {type: integer}}}"), - kept: []string{merged}, + kept: []string{merged("success", "Both", "Both2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/FailureX/allOf/1/properties/success"}, want: passed(OracleSequenceOrder), }, @@ -143,7 +237,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { "Both3: {allOf: [{$ref: '#/components/schemas/Common'}, {$ref: '#/components/schemas/Failure'}, "+ "{type: object, properties: {extra: {type: string}}}]}", "Holder: {type: object, properties: {b: {$ref: '#/components/schemas/Both'}}}", common, failure), - kept: []string{"the same holds at each of 3 models composing both"}, + kept: []string{merged("success", "Both", "Both2", "Both3")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/Common/properties/success"}, want: passed(OracleSequenceOrder), }, @@ -154,7 +248,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { src: schemas(composes("Both", "Common", "Failure"), composes("Both2", "Common", "Failure"), "Common: {type: object, properties: {success: {type: boolean, enum: [true]}, code: {type: integer}, same: {type: string}}}", "Failure: {type: object, properties: {success: {type: boolean, enum: [false]}, code: {type: string}, same: {type: string}}}"), - kept: []string{merged}, + kept: []string{merged("success", "Both", "Both2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/Common/properties/code"}, want: passed(OracleSequenceOrder), }, @@ -166,7 +260,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { name: "two ties whose reports trade declarations", src: schemas(composes("AB1", "A", "B"), composes("AB2", "A", "B"), composes("BA1", "B", "A"), composes("BA2", "B", "A"), "A: {type: object, properties: {p: {type: string}}}", "B: {type: object, properties: {p: {type: integer}}}"), - kept: []string{merged}, + kept: []string{merged("p", "AB1", "AB2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/B/properties/p"}, want: passed(OracleSequenceOrder), }, @@ -178,7 +272,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { src: schemas(composes("AB1", "A", "B"), composes("AB2", "A", "B"), composes("BA1", "B", "A"), composes("BA2", "B", "A"), composes("BA3", "B", "A"), "A: {type: object, properties: {p: {type: string}}}", "B: {type: object, properties: {p: {type: integer}}}"), - kept: []string{"the same holds at each of 3 models composing both"}, + kept: []string{merged("p", "BA1", "BA2", "BA3")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/A/properties/p"}, want: passed(OracleSequenceOrder), }, @@ -189,7 +283,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { src: schemas(composes("AB1", "A", "B"), composes("AB2", "A", "B"), composes("BC1", "B", "C"), composes("BC2", "B", "C"), "A: {type: object, properties: {p: {type: string}}}", "B: {type: object, properties: {p: {type: integer}}}", "C: {type: object, properties: {p: {type: boolean}}}"), - kept: []string{merged}, + kept: []string{merged("p", "AB1", "AB2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/B/properties/p"}, want: passed(OracleSequenceOrder), }, @@ -202,15 +296,15 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { src: schemas(composes("AB1", "A", "B"), composes("AB2", "A", "B"), composes("ABC1", "A", "B", "C"), composes("ABC2", "A", "B", "C"), "A: {type: object, properties: {p: {type: string}}}", "B: {type: object, properties: {p: {type: integer}}}", "C: {type: object, properties: {p: {type: boolean}}}"), - kept: []string{merged}, + kept: []string{merged("p", "AB1", "AB2")}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/B/properties/p"}, want: passed(OracleSequenceOrder), }, { - // M1's tie keeps B over A as written and A over B reversed, and M2, - // whose A and C agree, keeps them over B in either order: reversed, - // the two models say one conflict at B, once for both, and as - // written each says its own, naming its member. + // M1's tie chooses B over A as written and A over B reversed, and + // M2, whose A and C agree, chooses them over B in either order: + // reversed, the two models say one conflict at B, once for both, + // and as written each says its own, naming its member. name: "a conflict said for one model in one order and for two in the other", src: schemas(composes("M1", "A", "B"), composes("M2", "A", "B", "C"), "A: {type: object, properties: {p: {type: string}}}", "B: {type: object, properties: {p: {type: integer}}}", @@ -225,7 +319,7 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { src: schemas(composes("M1", "A", "B"), "M2: {allOf: [{$ref: '#/components/schemas/A'}, {$ref: '#/components/schemas/B'}], required: [p]}", composes("N1", "B", "A"), composes("N2", "B", "A"), "A: {type: object, properties: {p: {type: string}}}", "B: {type: object, properties: {p: {type: integer}}}"), - kept: []string{merged, `"required":true`}, + kept: []string{merged("p", "N1", "N2"), `"required":true`}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/B/properties/p"}, want: passed(OracleSequenceOrder), }, @@ -235,14 +329,14 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { // declaration says alone, and M2's requires p besides. name: "two ties trading declarations, one giving a description both keep", src: fixtureDescTrade, - kept: []string{merged, `"description":"da"`, `"required":true`}, + kept: []string{merged("p", "N1", "N2"), `"description":"da"`, `"required":true`}, codes: map[string]string{"openapi/conflicting-redeclaration": s + "/A/properties/p"}, want: passed(OracleSequenceOrder), }, { - // C2 loses to the booleans in either order, and which boolean its - // report names as kept, and so which models say it together, - // follows the order; no member differs. + // C2 is passed over for the booleans in either order, and which + // boolean its report names as chosen, and so which models say it + // together, follows the order; no member differs. name: "a conflict regrouped at a declaration that loses in either order", src: schemas("M0: {allOf: [{type: object, properties: {p: {type: boolean}}}, {allOf: [{$ref: '#/components/schemas/C2'}]}, "+ "{allOf: [{$ref: '#/components/schemas/C1'}]}]}", @@ -253,9 +347,9 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { want: passed(OracleSequenceOrder), }, { - // As written C0 loses in M1 and C1 in M3 and M4; reversed C1 loses - // in all four: the report at C1 is in both orders, and C0's has its - // counterpart there. + // As written C0 is passed over in M1 and C1 in M3 and M4; reversed + // C1 is passed over in all four: the report at C1 is in both + // orders, and C0's has its counterpart there. name: "a conflict at one declaration in one order and at another of its class in both", src: schemas(composes("M1", "C0", "C1"), "M3: {allOf: [{allOf: [{$ref: '#/components/schemas/C1'}]}, {$ref: '#/components/schemas/C0'}, "+ "{$ref: '#/components/schemas/C1'}]}", composes("M4", "C1", "ViaC0", "C1"), composes("M5", "C0", "WrapC1"), @@ -306,7 +400,8 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { want: passed(OracleSequenceOrder), }, { - // The kept entry is named by its index, which reversing moves. + // The kept Unmodeled entry is named by its index, which reversing + // moves. name: "a false entry kept under a name carrying its index", src: schemas("Never: {allOf: [{type: object, properties: {a: {type: string}}}, false]}"), kept: []string{`"openapi:allOf/1"`}, @@ -367,9 +462,10 @@ func TestCheck_SequenceOrderOracleHoldsOnTheRealCompiler(t *testing.T) { want: passed(OracleSequenceOrder), }, { - // D0's and D1's lists meet, each holding as many declarations, so the - // later wins and D2's report keeps it: D1 as written, D0 reversed. - // The member takes the list the fold mints in either order. + // D0's and D1's lists meet, each holding as many declarations, so + // the later wins and D2's report chooses it: D1 as written, D0 + // reversed. The member takes the list the fold mints in either + // order. name: "a conflict kept by whichever of two meeting lists is written later", src: schemas(composes("M", "D0", "D1", "D2"), "D0: {type: object, properties: {p: {type: array, minItems: 1, items: {type: string}}}}", @@ -463,6 +559,23 @@ func listsOfModels(xq, yq string) string { }, "\n ") } +// budgetCutSchemas writes D00 to D65, each declaring p a string and D00 alone +// describing it, and M0 composing them in the order they are written. +func budgetCutSchemas() []string { + schemas := make([]string, 0, 67) + refs := make([]string, 0, 66) + for i := range 66 { + name := fmt.Sprintf("D%02d", i) + description := "" + if i == 0 { + description = ", description: zero" + } + schemas = append(schemas, name+": {type: object, properties: {p: {type: string"+description+"}}}") + refs = append(refs, "{$ref: '#/components/schemas/"+name+"'}") + } + return append(schemas, "M0: {allOf: ["+strings.Join(refs, ", ")+"]}") +} + // TestCheck_SequenceOrderOracleDeclinesASpecOfTwoFiles pins that a source // whose compile reads another file is declined: that file names the first // entry of N's allOf by its index, which the walk does not read, so reversing @@ -548,9 +661,9 @@ func TestCheck_SequenceOrderOracleAsksOfAStreamWithADroppedDocument(t *testing.T assert.True(t, got.Asked(), "declined: %s", got.Declined) } -// planted is a change the compile seam makes to the document a compile -// returns, standing for a defect the real compiler does not have on a fixture -// this package can pin. +// planted is a change the compile seam makes to the document a compile returns, +// naming a defect the real compiler does not have on a fixture this package can +// pin. type planted func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) // plant makes every compile return what the real compile returns, changed by @@ -638,27 +751,49 @@ var ( composesAll("BA1", "beta", "alpha"), composesAll("BA2", "beta", "alpha"), "alpha: {type: object, properties: {p: {type: string}}}", "beta: {type: object, properties: {p: {type: integer}}}") // fixtureAgreeing: W composing alpha, beta and gamma, where gamma agrees - // with alpha, so beta's p loses in either order and no other model reports. + // with alpha, so beta's p is passed over in either order and no other model + // reports. fixtureAgreeing = schemas(composesAll("W", "alpha", "beta", "gamma"), "alpha: {type: object, properties: {p: {type: string}}}", "beta: {type: object, properties: {p: {type: integer}}}", "gamma: {type: object, properties: {p: {type: string}}}") + // fixtureDocsBeside: AB composing alpha and beta, whose p disagree in + // their types and in their descriptions, so two reports tie the member + // alike: one over the types, a conflict, and one over the docs. + fixtureDocsBeside = schemas(composesAll("AB", "alpha", "beta"), + "alpha: {type: object, properties: {p: {type: string, description: a}}}", + "beta: {type: object, properties: {p: {type: integer, description: b}}}") + // fixtureMovedRefusal: AB composing, inline, a uuid, a string giving a list + // default, a list giving a string default and a list of bounded strings. + // The uuid and the bounded list each hold two declarations, so the later + // wins, a tie the conflicts state, and the wider declaration folding into + // the chosen one has its default refused: the list's as written, the + // string's reversed, so the refusal moves to another entry. + fixtureMovedRefusal = schemas("AB: {allOf: [{type: object, properties: {p: {type: string, format: uuid}}}, " + + "{type: object, properties: {p: {type: string, default: [x]}}}, " + + "{type: object, properties: {p: {type: array, items: {type: string}, default: ab}}}, " + + "{type: object, properties: {p: {type: array, items: {type: string, maxLength: 3}}}}]}") + // fixtureComponentTie: AB composing alpha and beta, whose p disagree in + // their types alone, so their conflicts tie the member's type and not its + // docs. + fixtureComponentTie = schemas(composesAll("AB", "alpha", "beta"), + "alpha: {type: object, properties: {p: {type: string}}}", "beta: {type: object, properties: {p: {type: integer}}}") // fixtureMeeting: W composing alpha, beta and gamma, where alpha's and - // gamma's lists meet in one the fold mints, so beta's p loses in either - // order, and its report keeps whichever list is written later. + // gamma's lists meet in one the fold mints, so beta's p is passed over in + // either order, and its report chooses whichever list is written later. fixtureMeeting = schemas(composesAll("W", "alpha", "beta", "gamma"), "alpha: {type: object, properties: {p: {type: array, minItems: 1, items: {type: string}}}}", "beta: {type: object, properties: {p: {type: integer}}}", "gamma: {type: object, properties: {p: {type: array, maxItems: 5, items: {type: string}}}}") - // fixtureOutvoted: fixtureTrade's two families, and W composing beta, - // alpha and gamma, where gamma agrees with alpha, so beta's p loses in + // fixtureOutvoted: fixtureTrade's two families, and W composing beta, alpha + // and gamma, where gamma agrees with alpha, so beta's p is passed over in // either order. fixtureOutvoted = schemas(composesAll("AB1", "alpha", "beta"), composesAll("AB2", "alpha", "beta"), composesAll("BA1", "beta", "alpha"), composesAll("BA2", "beta", "alpha"), composesAll("W", "beta", "alpha", "gamma"), "alpha: {type: object, properties: {p: {type: string}}}", "beta: {type: object, properties: {p: {type: integer}}}", "gamma: {type: object, properties: {p: {type: string}}}") // fixtureGroup: a tie one model decides between alpha and beta, beside a - // model composing them and gamma, which agrees with alpha, so beta's p - // loses there in either order: reversed, one report speaks for both. + // model composing them and gamma, which agrees with alpha, so beta's p is + // passed over there in either order: reversed, one report speaks for both. fixtureGroup = schemas(composesAll("AB", "alpha", "beta"), composesAll("ABG", "alpha", "beta", "gamma"), "alpha: {type: object, properties: {p: {type: string}}}", "beta: {type: object, properties: {p: {type: integer}}}", "gamma: {type: object, properties: {p: {type: string}}}") @@ -670,11 +805,11 @@ var ( "{type: object, properties: {p: {type: boolean}}}, {$ref: '#/components/schemas/alpha'}]}", composesAll("M", "X", "beta"), "alpha: {type: object, properties: {p: {type: string}}}", "beta: {type: object, properties: {p: {type: integer}}}") - // fixtureLoser: fixtureSwap's tie over alpha and beta, a tie over beta and - // delta, so beta's p loses as written and reversed, a model composing beta - // alone, which holds that declaration as beta does, and one composing beta - // and gamma, whose p agree. - fixtureLoser = schemas("AB: {allOf: [{$ref: '#/components/schemas/alpha'}, {$ref: '#/components/schemas/beta'}]}", + // fixturePassedOver: fixtureSwap's tie over alpha and beta, a tie over beta + // and delta, so beta's p is passed over as written and reversed, a model + // composing beta alone, which holds that declaration as beta does, and one + // composing beta and gamma, whose p agree. + fixturePassedOver = schemas("AB: {allOf: [{$ref: '#/components/schemas/alpha'}, {$ref: '#/components/schemas/beta'}]}", "AB2: {allOf: [{$ref: '#/components/schemas/alpha'}, {$ref: '#/components/schemas/beta'}]}", "BD: {allOf: [{$ref: '#/components/schemas/beta'}, {$ref: '#/components/schemas/delta'}]}", "BD2: {allOf: [{$ref: '#/components/schemas/beta'}, {$ref: '#/components/schemas/delta'}]}", @@ -736,6 +871,21 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { return inner(t, reversed, doc, diags) } } + // refusalMoved adds, in either order, a report carrying no pair that + // decides AB's p and sits at AB's first entry, which the reversal moves + // to its second, as a refusal of one declaration's default in each order + // would. + refusalMoved := func(inner planted) planted { + return func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { + diags = append(slices.Clip(diags), ir.Diagnostic{Severity: ir.SeverityInfo, Code: "openapi/degraded-construct", + Message: "refused", Provenance: ir.Provenance{Pointer: "/components/schemas/AB/allOf/0"}, + Related: []ir.Related{{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: -1, Node: "property/composed/components/schemas/AB/allOf/properties/p"}}}}) + return inner(t, reversed, doc, diags) + } + } + unchanged := func(_ *testing.T, _ bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { + return doc, diags, nil + } tests := []struct { name string src string @@ -771,9 +921,12 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"diagnostics depend on sequence order", "x/planted"}, }, { - // The report moves with the order, so p is a tie site and what the - // document holds beneath it is not compared. - name: "a reported tie is forgiven", + // The report moves with the order but carries no pair and decides + // no member, so no mirrored tie decides its member: it forgives + // nothing, itself included, and p, which both entries declare + // alike, is compared, so a description in one order alone is + // found beside the report. + name: "a moved report deciding no member forgives nothing", src: fixtureY, edit: tied(func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { if reversed { @@ -781,9 +934,13 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { } return doc, diags, nil }), + found: true, + contains: []string{"diagnostics depend on sequence order", "x/tie", + "document depends on sequence order", `"description": "reversed"`}, }, { - // The tie covers p alone: a difference elsewhere is still one. + // The moved report forgives nothing beside it either: a + // difference elsewhere is found. name: "a reported tie forgives nothing outside its site", src: fixtureY, edit: tied(integer("alpha")), @@ -921,7 +1078,7 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"document depends on sequence order", `"wireName":"r"`}, }, { - // A declaration stands on its own model, which no tie decides. + // A declaration lies on its own model, which no tie decides. name: "a report a tie moves between declarations forgives neither declaration", src: fixtureSwap, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { @@ -979,8 +1136,8 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"diagnostics depend on sequence order", "x/other"}, }, { - // W composes beta, alpha and gamma, where alpha and gamma agree, - // so no tie decides its p, which the report says lost beta in + // W composes beta, alpha and gamma, where alpha and gamma agree, so + // no tie decides its p, which the report says passed over beta in // either order. The ties the other models trade forgive none of it. name: "a member no tie decides taking another type beside ties two models trade", src: fixtureOutvoted, @@ -997,8 +1154,8 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"document depends on sequence order", `W member "p"`}, }, { - // AB's p takes alpha's type where its report says alpha lost, and - // beta's where it says beta did. + // AB's p takes alpha's type where its report says passed over + // alpha, and beta's where it says beta did. name: "a tied member taking in each order the type its report says lost", src: fixtureSwap, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { @@ -1077,10 +1234,11 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"document depends on sequence order", `"message": "reversed"`, "flattened shape depends on sequence order"}, }, { - // W's p loses beta's declaration in either order, and its report - // keeps gamma's as written and alpha's reversed, which name one - // type. Naming beta's, of another type, in one order is found. - name: "a report naming as kept, in one order, a declaration of another type", + // W's p passes over beta's declaration in either order, and its + // report chooses alpha's, the first written of the two agreeing, in + // either order. Naming beta's, of another type, in one order is + // found. + name: "a report naming as chosen, in one order, a declaration of another type", src: fixtureAgreeing, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { if !reversed { @@ -1099,14 +1257,81 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { return doc, out, nil }, found: true, - contains: []string{"diagnostics depend on sequence order", `kept\x00/components/schemas/beta/properties/p`}, + contains: []string{"diagnostics depend on sequence order", `chosen\x00/components/schemas/beta/properties/p`}, not: []string{"document depends on sequence order"}, }, + { + // Naming gamma's, which names the type alpha's does, in one order + // is found too: the place chosen is compared, not its type. + name: "a report naming as chosen, in one order, another declaration of the type chosen", + src: fixtureAgreeing, + edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { + if !reversed { + return doc, diags, nil + } + out := slices.Clone(diags) + renamed := 0 + for i, diagnostic := range out { + if len(diagnostic.Related) == 2 && strings.Contains(diagnostic.Related[1].Provenance.Node, "/W/") { + out[i].Related = slices.Clone(diagnostic.Related) + out[i].Related[0].Provenance.Pointer = "/components/schemas/gamma/properties/p" + renamed++ + } + } + require.Equal(t, 1, renamed, "the fixture must report W's p alone") + return doc, out, nil + }, + found: true, + contains: []string{"diagnostics depend on sequence order", `chosen\x00/components/schemas/gamma/properties/p`}, + not: []string{"document depends on sequence order"}, + }, + { + // AB's p takes the description of the declaration whose type it + // takes in each order, which a report other than the conflict + // states. Without it the conflict alone ties the member, which + // decides its type and not its docs, so the docs are compared. + name: "a docs tie one order does not state", + src: fixtureDocsBeside, + edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { + if !reversed { + return doc, diags, nil + } + out := slices.DeleteFunc(slices.Clone(diags), func(diagnostic ir.Diagnostic) bool { + return diagnostic.Code == "openapi/degraded-construct" + }) + require.Len(t, out, len(diags)-1, "the fixture must report the docs once") + return doc, out, nil + }, + found: true, + contains: []string{"document depends on sequence order", `"description": "a"`, "flattened shape depends on sequence order"}, + }, + { + // The moved report decides p, which the conflicts tie in either + // order, so it forgives itself, and nothing else differs. + name: "a report the reversal moves, of a member a mirrored tie decided", + src: fixtureComponentTie, + edit: refusalMoved(unchanged), + }, + { + // The conflicts tie p's type, and no report states a tie over its + // docs: a description in one order alone is found, not forgiven + // with the moved report. + name: "a description beside a report the reversal moves", + src: fixtureComponentTie, + edit: refusalMoved(func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { + if reversed { + property(t, doc, "p").Docs.Description = "reversed" + } + return doc, diags, nil + }), + found: true, + contains: []string{"document depends on sequence order", `"description": "reversed"`}, + }, { // The stated limit: where W's p takes the list the fold mints, its - // report's kept place is read as that list, so naming beta's + // report's chosen place is read as that list, so naming beta's // declaration, which the fold dropped, in one order passes. - name: "a report naming as kept, in one order, a dropped declaration where the fold mints", + name: "a report naming as chosen, in one order, a dropped declaration where the fold mints", src: fixtureMeeting, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { if !reversed { @@ -1130,7 +1355,7 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { // The object AB writes for p is referenced in either order (by the // composed p model), while p's description ties, so what it says // is compared. - name: "a node written where a tied member stands, differing", + name: "a node written where a tied member sits, differing", src: fixtureBeneathKept, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { const written = "type/anonymous/components/schemas/AB/allOf/0/properties/p" @@ -1199,8 +1424,9 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"document depends on sequence order", `member "q"`}, }, { - // A tie moves the report at the declaration that lost: AB.q differs - // while the report beside it sits at alpha's q in either order. + // A tie moves the report at the declaration passed over: AB.q + // differs while the report beside it sits at alpha's q in either + // order. name: "a member differing where the report at its declarations stays put", src: fixtureSwap, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { @@ -1235,7 +1461,7 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { // beta's own p is one declaration, which two models' flattenings // hold and the ties report at in either order: no tie decides it. name: "a member of one declaration differing where ties report at it in either order", - src: fixtureLoser, + src: fixturePassedOver, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { beta, ok := doc.Types["type/openapi/components/schemas/beta"].(*ir.Model) require.True(t, ok, "the fixture must lower beta to a model") @@ -1253,7 +1479,7 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { // either order, and gamma's, which says the same and at which no // order reports: no tie moves a report between BG.p's declarations. name: "a member folding a declaration ties report at in either order differing", - src: fixtureLoser, + src: fixturePassedOver, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { bg, ok := doc.Types["type/openapi/components/schemas/BG"].(*ir.Model) require.True(t, ok, "the fixture must lower BG to a model") @@ -1286,8 +1512,8 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"document depends on sequence order", `BG member "p"`}, }, { - // Each order reports the tie at the declaration p takes, not at - // the one it lost. + // Each order reports the tie at the declaration p takes, not at the + // one it passed over. name: "a conflict reported at the declaration that won", src: fixtureSwap, edit: func(t *testing.T, _ bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { @@ -1309,9 +1535,9 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { contains: []string{"document depends on sequence order", `member "p"`}, }, { - // The AB models' and BA models' ties trade declarations; as - // written the BA models' report at beta is missing, though AB's - // at alpha stands for it by its key. + // The AB models' and BA models' ties trade declarations; as written + // the BA models' report at beta is missing, though AB's at alpha + // names it by its key. name: "a conflict two ties trading declarations miss in one order", src: fixtureTrade, edit: func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { @@ -1415,8 +1641,11 @@ func TestSequenceOrderInvariant_FindsWhatDiffers(t *testing.T) { // passes, so a finding above is the plant's. func TestSequenceOrderInvariant_UnplantedFixturesPass(t *testing.T) { for name, src := range map[string]string{"X": fixtureX, "Y": fixtureY, "Z": fixtureZ, "Beneath": fixtureBeneath, "BeneathKept": fixtureBeneathKept, "Agreeing": fixtureAgreeing, "Meeting": fixtureMeeting, - "mixins": fixtureMixins, "kept": fixtureKept, "swap": fixtureSwap, "beside": fixtureBeside, - "three": fixtureThree, "trade": fixtureTrade, "far": fixtureFar, "loser": fixtureLoser, + "docs beside": fixtureDocsBeside, + "moved refusal": fixtureMovedRefusal, + "component tie": fixtureComponentTie, + "mixins": fixtureMixins, "kept": fixtureKept, "swap": fixtureSwap, "beside": fixtureBeside, + "three": fixtureThree, "trade": fixtureTrade, "far": fixtureFar, "passed over": fixturePassedOver, "outvoted": fixtureOutvoted, "group": fixtureGroup, "brought": fixtureBrought} { t.Run(name, func(t *testing.T) { got := sequenceOrderInvariant(context.Background(), "spec.yaml", []byte(src), true) diff --git a/internal/harness/sequenceorder_node_internal_test.go b/internal/harness/sequenceorder_node_internal_test.go index de838d3c3..7ab322928 100644 --- a/internal/harness/sequenceorder_node_internal_test.go +++ b/internal/harness/sequenceorder_node_internal_test.go @@ -16,32 +16,32 @@ import ( "github.com/dexpace/morphic/ir" ) -// TestSequenceOrderInvariant_ATieIsHeldToTheNodeItsReportNames plants a +// TestSequenceOrderInvariant_AMovedReportNamingItsNodeForgivesNothing adds a // report that moves with the order and names, in its node, the property it -// decided: the oracle forgives any difference in that property and finds one -// in another member of the model. -func TestSequenceOrderInvariant_ATieIsHeldToTheNodeItsReportNames(t *testing.T) { - const tie = "/components/schemas/AB/allOf/1/properties/p" - type change func(doc *ir.Document) +// decided. A moved report ties nothing, and no stated tie decides p, which +// both entries declare alike, so untied forgives nothing here: a difference in +// p, in any fact of it, or in another member is found. Where p differs, the +// report naming it pairs with nothing and is found too; where p is alike, the +// two orders' reports name one node and pair (sameNodes). +func TestSequenceOrderInvariant_AMovedReportNamingItsNodeForgivesNothing(t *testing.T) { + const moved = "/components/schemas/AB/allOf/1/properties/p" retype := func(doc *ir.Document) { property(t, doc, "p").Type.Target = "type/primitive/integer" } exemplify := func(doc *ir.Document) { property(t, doc, "p").Examples = []ir.Example{{Value: &ir.Value{Kind: ir.ValueString, String: "x"}}} } other := func(doc *ir.Document) { property(t, doc, "alpha").Docs.Description = "reversed" } - tests := []struct { - name string - change change - found bool + for name, tc := range map[string]struct { + change func(doc *ir.Document) + reportFound bool }{ - {name: "a difference in the type of the property it names is forgiven", change: retype}, - {name: "a difference in any other fact of that property is forgiven", change: exemplify}, - {name: "a difference in another member is found", change: other, found: true}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + "a difference in the type of the property it names": {change: retype, reportFound: true}, + "a difference in any other fact of that property": {change: exemplify, reportFound: true}, + "a difference in another member": {change: other}, + } { + t.Run(name, func(t *testing.T) { plant(t, func(t *testing.T, reversed bool, doc *ir.Document, diags []ir.Diagnostic) (*ir.Document, []ir.Diagnostic, error) { irProperty := property(t, doc, "p") - diags = append(slices.Clip(diags), diagnostic(ir.SeverityWarning, "x/tie", tie, string(irProperty.ID))) + diags = append(slices.Clip(diags), diagnostic(ir.SeverityWarning, "x/tie", moved, string(irProperty.ID))) if reversed { tc.change(doc) } @@ -50,12 +50,9 @@ func TestSequenceOrderInvariant_ATieIsHeldToTheNodeItsReportNames(t *testing.T) got := sequenceOrderInvariant(context.Background(), "spec.yaml", []byte(fixtureY), true) - if !tc.found { - assert.Equal(t, passed(OracleSequenceOrder), got) - return - } - require.True(t, got.Found(), "the oracle must find a difference the report does not name: %+v", got) + require.True(t, got.Found(), "the oracle must find the difference: %+v", got) assert.Contains(t, got.Detail, "document depends on sequence order") + assert.Equal(t, tc.reportFound, strings.Contains(got.Detail, "diagnostics depend on sequence order"), got.Detail) }) } } @@ -124,11 +121,11 @@ func settledDoc() *ir.Document { // TestSettledFrom_TiesWhatATiedMemberDecides pins the closure of a tie: a // member whose flattening overrides a tied one is tied, its pointer joining // the tied members', and so is a union whose discriminator was inferred from -// it, and the model holding it holds a tied member; a member declared beneath -// where a moved report sits, or at a tied member's pointer, is tied, and one -// declared beneath a tied member's pointer is not. A declared discriminator, -// one inferred from a member apart, a member apart, and a document with no -// tie add nothing. +// it, and the model holding it holds a tied member; a member declared at a +// tied member's pointer is tied, and one declared beneath it, or at a pointer +// no member is declared at, is not. A declared discriminator, one inferred +// from a member apart, a member apart, and a document with no tie add +// nothing. func TestSettledFrom_TiesWhatATiedMemberDecides(t *testing.T) { t.Parallel() doc := settledDoc() @@ -136,31 +133,27 @@ func TestSettledFrom_TiesWhatATiedMemberDecides(t *testing.T) { got := settledFrom(tieSites{nodes: []string{"property/AB/p"}}, doc, nil) assert.Equal(t, []string{"property/AB/p", "property/M/p", "type/inferred"}, got.nodes) - assert.Equal(t, []string{"/AB/p", "/M/allOf/properties/p"}, got.members, "where the tied members stand") - assert.Empty(t, got.pointers, "no report moved") + assert.Equal(t, []string{"/AB/p", "/M/allOf/properties/p"}, got.members, "where the tied members sit") assert.Equal(t, []string{"type/AB", "type/M"}, got.holders, "the models holding a tied member") - bySite := settledFrom(tieSites{pointers: []string{"/AB"}}, doc, nil) - assert.Equal(t, []string{"property/AB/p", "property/M/p", "type/inferred"}, bySite.nodes, - "a member declared beneath a tie site is tied, as a fold of inline declarations reports where they are") atMember := settledFrom(tieSites{members: []string{"/AB/p"}}, doc, nil) - assert.Equal(t, []string{"property/AB/p", "property/M/p", "type/inferred"}, atMember.nodes, "a member declared where a tied member stands is tied") + assert.Equal(t, []string{"property/AB/p", "property/M/p", "type/inferred"}, atMember.nodes, "a member declared where a tied member sits is tied") assert.Equal(t, tieSites{members: []string{"/AB"}}, settledFrom(tieSites{members: []string{"/AB"}}, doc, nil), "a member declared beneath a tied member's pointer is written there in either order") - assert.Equal(t, tieSites{pointers: []string{"/x"}}, settledFrom(tieSites{pointers: []string{"/x"}}, doc, nil), - "a site no member is declared at ties none") + assert.Equal(t, tieSites{members: []string{"/x"}}, settledFrom(tieSites{members: []string{"/x"}}, doc, nil), + "a pointer no member is declared at ties none") assert.Equal(t, tieSites{nodes: []string{"property/AB/p"}}, settledFrom(tieSites{nodes: []string{"property/AB/p"}}, nil, nil), "a refused compile adds none") } -// TestCanonicalForm_LeavesOutANodeATieMints pins a node a registry keys by its -// ID beneath a tie site: whether a fold mints it follows the tie, so a document +// TestCanonicalForm_LeavesOutANodeATieMints pins a node a fold mints where a +// tied member sits: whether the fold mints it follows the tie, so a document // holding it reads as one that does not, and without the tie it differs. func TestCanonicalForm_LeavesOutANodeATieMints(t *testing.T) { t.Parallel() minted := &ir.Model{ID: "type/composed/M/allOf/properties/p", Provenance: ir.Provenance{Pointer: "/M/allOf/properties/p"}} with := settledDoc() with.Types[minted.ID] = minted - ties := tieSites{pointers: []string{"/M/allOf/properties/p"}} + ties := tieSites{nodes: []string{"property/M/p"}, members: []string{"/M/allOf/properties/p"}} a, err := canonicalForm(with, nil, ties) require.NoError(t, err) @@ -175,11 +168,11 @@ func TestCanonicalForm_LeavesOutANodeATieMints(t *testing.T) { } // TestCanonicalForm_LeavesOutBeneathATiedMemberOnlyWhatItsFoldMints pins what -// is compared where a tied member stands: a node in the composed namespace at -// its pointer, or beneath it where a fold builds a member, follows the tie and -// is left out, while a node the source writes there, or one minted beneath it -// at another position, as a fold of the member's own type's declarations -// mints one, is compared. +// is compared where a tied member sits: a node in the composed namespace at its +// pointer, or beneath it where a fold builds a member, follows the tie and is +// left out, while a node the source writes there, or one minted beneath it at +// another position, as a fold of the member's own type's declarations mints +// one, is compared. func TestCanonicalForm_LeavesOutBeneathATiedMemberOnlyWhatItsFoldMints(t *testing.T) { t.Parallel() const at = "/M/allOf/properties/p" @@ -195,9 +188,9 @@ func TestCanonicalForm_LeavesOutBeneathATiedMemberOnlyWhatItsFoldMints(t *testin pointer string compared bool }{ - "written where the member stands": {id: "type/anonymous/M/allOf/properties/p", pointer: at, compared: true}, + "written where the member sits": {id: "type/anonymous/M/allOf/properties/p", pointer: at, compared: true}, "written beneath the member": {id: "type/anonymous/M/allOf/properties/p/items", pointer: at + "/items", compared: true}, - "minted where the member stands": {id: "type/composed/M/allOf/properties/p", pointer: at}, + "minted where the member sits": {id: "type/composed/M/allOf/properties/p", pointer: at}, "minted for its items": {id: "type/composed/M/allOf/properties/p/items", pointer: at + "/items"}, "minted for a tuple's position's map value": {id: "type/composed/x", pointer: at + "/prefixItems/2/additionalProperties"}, "minted beneath the member by another fold": {id: "type/composed/x", pointer: at + "/allOf/properties/x", compared: true}, @@ -240,6 +233,28 @@ func TestMintedPosition_ReadsThePositionsAFoldBuildsAMemberAt(t *testing.T) { } } +// TestAtFoldKey_ReadsEachPlaceTheKeyIsWritten pins the fold's key read in a +// minted node's pointer: a schema holding the member, then allOf, properties +// and its name, at the key or at a position a fold builds a member at beneath +// it, wherever in the pointer it sits, so a key a schema not holding the member +// writes first passes on to the next. +func TestAtFoldKey_ReadsEachPlaceTheKeyIsWritten(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + member, erased string + want bool + }{ + {"/X/allOf/0/properties/p", "/X/allOf/properties/p", true}, + {"/X/allOf/0/properties/p", "/X/allOf/properties/p/items", true}, + {"/X/allOf/properties/p/allOf/0/properties/p", "/X/allOf/properties/p/allOf/properties/p", true}, + {"/X/allOf/0/properties/p", "/X/allOf/properties/p/allOf/properties/p", false}, + {"/Y/properties/p", "/X/allOf/properties/p", false}, + {"/X/allOf/0/properties/p", "/X/properties/p", false}, + } { + assert.Equal(t, tc.want, atFoldKey(tc.member, tc.erased), "%s at %s", tc.member, tc.erased) + } +} + // TestCanonicalForm_ForgivesANodeATieNamesWhereverItSits pins a node a moved // report names, away from any tie site: a document whose member differs there // reads as one that does not, in its own form and in its flattened shape, and @@ -264,17 +279,18 @@ func TestCanonicalForm_ForgivesANodeATieNamesWhereverItSits(t *testing.T) { // TestUntied_LeavesOutWhatATieDecided pins which reports one order alone makes // are no difference: one naming a tied node or a model holding one, or one at -// or beneath a tie site, says what a tie decided; any other is a difference. +// or beneath a tied member's pointer, says what a tie decided; any other is a +// difference. func TestUntied_LeavesOutWhatATieDecided(t *testing.T) { t.Parallel() - ties := tieSites{pointers: []string{"/M/allOf/properties/p"}, nodes: []string{"property/M/p"}, members: []string{"/N/q"}, holders: []string{"type/M"}} + ties := tieSites{nodes: []string{"property/M/p"}, members: []string{"/M/allOf/properties/p", "/N/q"}, holders: []string{"type/M"}} rs := []report{ {key: "tied node", node: "property/M/p", pointer: "/elsewhere"}, {key: "holder", node: "type/M", pointer: "/elsewhere"}, - {key: "at a site", pointer: "/M/allOf/properties/p/items"}, - {key: "beneath a tied member", pointer: "/N/q/items"}, + {key: "at a tied member", pointer: "/N/q"}, + {key: "beneath a tied member", pointer: "/M/allOf/properties/p/items"}, {key: "another node", node: "type/Q", pointer: "/Q"}, - {key: "beside a site", pointer: "/M/allOf/properties/pq"}, + {key: "beside a tied member", pointer: "/M/allOf/properties/pq"}, } got := untied(rs, ties, nil) @@ -283,7 +299,7 @@ func TestUntied_LeavesOutWhatATieDecided(t *testing.T) { for _, report := range got { keys = append(keys, report.key) } - assert.Equal(t, []string{"another node", "beside a site"}, keys) + assert.Equal(t, []string{"another node", "beside a tied member"}, keys) } // fixtureMinted: both entries declare r as an object of their own, each with a @@ -325,7 +341,8 @@ func TestSequenceOrderInvariant_AReportOnANodeAReversalMovesPairsByWhatItHolds(t // TestNodeKey_PairsOnlyANodeItsFormTellsByWhatItHolds pins what a report's // node key is: none for a report naming no node, none where the form cannot // tell the node by what it holds, so the report pairs with nothing and stays -// a difference, and otherwise the node as the form writes it, with no pointer. +// a difference, and otherwise the node as the form writes it, with no pointer, +// the report's own or that of the model declaring a member it decided. func TestNodeKey_PairsOnlyANodeItsFormTellsByWhatItHolds(t *testing.T) { t.Parallel() named := report{raw: diagnostic(ir.SeverityWarning, "x/node", "/a/allOf/0", "type/anonymous/a/allOf/0")} @@ -337,6 +354,67 @@ func TestNodeKey_PairsOnlyANodeItsFormTellsByWhatItHolds(t *testing.T) { want := named.raw want.Provenance = ir.Provenance{Node: "type/anonymous/a/allOf/0#held"} assert.Equal(t, diagnosticKey(want), nodeKey(named, tells)) + + decided := diagnostic(ir.SeverityInfo, "x/refused", "/a/allOf/0/properties/p", "") + decided.Related = []ir.Related{{Role: ir.RelatedDecided, Provenance: ir.Provenance{Pointer: "/a/allOf/0", Node: "property/a/allOf/0/properties/p"}}} + want = decided + want.Provenance = ir.Provenance{} + want.Related = []ir.Related{{Role: ir.RelatedDecided, Provenance: ir.Provenance{Node: "property/a/allOf/0/properties/p#held"}}} + assert.Equal(t, diagnosticKey(want), nodeKey(report{raw: decided}, tells), "a member a report lists as decided") +} + +// TestReportsOf_ReadsAReportAboutOneDeclarationPerMember pins which node a +// report is about: the one its place names, else, for a report naming no chosen +// place, the member it decided, read once per member where it decided several, +// each listing that member alone; a report naming a chosen place is about none +// beside its place, whatever it decided. +func TestReportsOf_ReadsAReportAboutOneDeclarationPerMember(t *testing.T) { + t.Parallel() + decided := func(node string) ir.Related { + return ir.Related{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: node}} + } + refusal := diagnostic(ir.SeverityInfo, "x/refused", "/D/properties/p", "") + refusal.Related = []ir.Related{decided("property/M/allOf/1/properties/p"), decided("property/N/allOf/0/properties/p")} + pair := refusal + pair.Related = append([]ir.Related{{Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: "/K/properties/p"}}}, refusal.Related...) + named := diagnostic(ir.SeverityWarning, "x/node", "/a", "type/M/allOf/1") + seqs := sequences{"/M/allOf": 2} + + got := reportsOf([]ir.Diagnostic{refusal, pair, named}, seqs, seqs) + + nodes := make([]string, len(got)) + for i, reportValue := range got { + nodes[i] = reportValue.node + } + assert.Equal(t, []string{"property/M/allOf/0/properties/p", "property/N/allOf/0/properties/p", "", "type/M/allOf/0"}, nodes, + "each member rebased, none for a report naming a chosen place, and a named node") + assert.Equal(t, []ir.Related{decided("property/M/allOf/1/properties/p")}, got[0].raw.Related, "a member alone") + assert.Equal(t, []ir.Related{decided("property/N/allOf/0/properties/p")}, got[1].raw.Related) + assert.Equal(t, pair.Related, got[2].raw.Related, "a report naming a chosen place is read once") + assert.Len(t, refusal.Related, 2, "the diagnostics handed in are left as they were") +} + +// TestUntied_ComparesTheUntiedModelsPieceOfAReportSaidForTwo pins a report +// about one declaration, naming no chosen place, that the run said once for two +// models: read a piece per member it decided, a tie deciding one model's member +// leaves out that model's piece alone, and the other's is compared. +func TestUntied_ComparesTheUntiedModelsPieceOfAReportSaidForTwo(t *testing.T) { + t.Parallel() + decided := func(node string) ir.Related { + return ir.Related{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: node}} + } + const ( + tiedMember = "property/composed/components/schemas/M/allOf/properties/p" + untiedMember = "property/composed/components/schemas/N/allOf/properties/p" + ) + refusal := diagnostic(ir.SeverityInfo, "x/refused", "/components/schemas/D/properties/p", "") + refusal.Related = []ir.Related{decided(tiedMember), decided(untiedMember)} + + got := untied(reportsOf([]ir.Diagnostic{refusal}, nil, nil), tieSites{nodes: []string{tiedMember}}, nil) + + require.Len(t, got, 1, "the untied model's piece alone") + assert.Equal(t, untiedMember, got[0].node) + assert.Equal(t, []ir.Related{decided(untiedMember)}, got[0].raw.Related) } // TestCanonicalForm_ComparesWhatATiedMembersFoldSettlesFromEveryDeclaration @@ -369,9 +447,8 @@ func TestCanonicalForm_ComparesWhatATiedMembersFoldSettlesFromEveryDeclaration(t sensitive.Types["type/S"] = &ir.Scalar{ID: "type/S", Base: &ir.TypeRef{Target: "type/primitive/string"}, Sensitive: true} sensitive.Types["type/M"].(*ir.Model).Properties[0].Type.Target = "type/S" for how, ties := range map[string]tieSites{ - "by its ID": {nodes: []string{"property/M/p"}}, - "at a tie site": {pointers: []string{"/M/allOf/properties/p"}}, - "by its ID where it stands": {nodes: []string{"property/M/p"}, members: []string{"/M/allOf/properties/p"}}, + "by its ID": {nodes: []string{"property/M/p"}}, + "by its ID where it sits": {nodes: []string{"property/M/p"}, members: []string{"/M/allOf/properties/p"}}, } { a, err := canonicalForm(settledDoc(), nil, ties) require.NoError(t, err) @@ -396,20 +473,18 @@ func TestCanonicalForm_ComparesWhatATiedMembersFoldSettlesFromEveryDeclaration(t } } -// TestCanonicalForm_ComparesWhetherATiedMemberIsRequired pins the one thing -// of a tied member the forms compare: a member is required where any of its +// TestCanonicalForm_ComparesWhetherATiedMemberIsRequired pins the one thing of +// a tied member the forms compare: a member is required where any of its // declarations or its model says so, which no tie decides, so two documents -// differing there differ, in the document and in the shape, by the member's -// ID and by a tie site alike. A tied node that is no property, as what a -// member keeps verbatim at a tie site is, is written as the tie alone. +// differing there differ, in the document and in the shape, by the member's ID +// alone and where it sits alike. func TestCanonicalForm_ComparesWhetherATiedMemberIsRequired(t *testing.T) { t.Parallel() required := settledDoc() required.Types["type/M"].(*ir.Model).Properties[0].Required = true for name, ties := range map[string]tieSites{ - "by its ID": {nodes: []string{"property/M/p"}}, - "at a tie site": {pointers: []string{"/M/allOf/properties/p"}}, - "by its ID where it stands": {nodes: []string{"property/M/p"}, members: []string{"/M/allOf/properties/p"}}, + "by its ID": {nodes: []string{"property/M/p"}}, + "by its ID where it sits": {nodes: []string{"property/M/p"}, members: []string{"/M/allOf/properties/p"}}, } { a, err := canonicalForm(settledDoc(), nil, ties) require.NoError(t, err) @@ -419,19 +494,4 @@ func TestCanonicalForm_ComparesWhetherATiedMemberIsRequired(t *testing.T) { assert.NotEqual(t, a.shape, b.shape, name) assert.Contains(t, strings.Join(b.document, "\n"), `"required": true`, name) } - - kept := func(value string) *ir.Document { - doc := settledDoc() - doc.Types["type/Q"].(*ir.Model).Unmodeled = ir.Unmodeled{"bytes:kept": { - Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(value), Provenance: ir.Provenance{Pointer: "/M/allOf/properties/p/items"}, - }} - return doc - } - ties := tieSites{pointers: []string{"/M/allOf/properties/p"}} - a, err := canonicalForm(kept(`1`), nil, ties) - require.NoError(t, err) - b, err := canonicalForm(kept(`2`), nil, ties) - require.NoError(t, err) - assert.Equal(t, a.document, b.document) - assert.Contains(t, strings.Join(a.document, "\n"), `"reportedTie": "/M/allOf/properties/p/items"`) } diff --git a/internal/harness/spelling.go b/internal/harness/spelling.go index 19b3fab65..fa77b51d0 100644 --- a/internal/harness/spelling.go +++ b/internal/harness/spelling.go @@ -113,6 +113,13 @@ func comparableSide(doc *ir.Document, relocate func(string) string) (any, Declin if err != nil { return nil, "", err } + return relocatedSide(encoded, relocate) +} + +// relocatedSide is encoded read as relocatedTree reads it, and why it cannot +// be compared: two names of one object relocating to one, or a tree nesting +// too deep. +func relocatedSide(encoded []byte, relocate func(string) string) (any, Decline, error) { tree, err := relocatedTree(encoded, relocate) switch { case errors.Is(err, errCollides): diff --git a/internal/harness/ties.go b/internal/harness/ties.go index feb878b83..281916056 100644 --- a/internal/harness/ties.go +++ b/internal/harness/ties.go @@ -5,6 +5,7 @@ package harness import ( "encoding/json/jsontext" + "maps" "slices" "strconv" "strings" @@ -12,44 +13,44 @@ import ( "github.com/dexpace/morphic/ir" ) -// decision is one thing a report carrying a pair states: the member it -// decided, by its ID, lost what the declaration at lost says and kept what -// the one at kept says (placeOf), each with every index of a reversed -// sequence erased, and what the report says beside those places (sayingOf). -// A member a model brings is named by its first declaration where its type is +// decision is one thing a report carrying a pair states: the member it decided, +// by its ID, passed over what the declaration at passedOver says and chose what +// the one at chosen says (placeOf), each with every index of a reversed +// sequence erased, and what the report says beside those places (sayingOf). A +// member a model brings is named by its first declaration where its type is // written at several places // (docs/compilers/openapi.md#allof-redeclared-property), which the reversal -// moves to another entry of that model's allOf, so only the erased place -// names it in both orders. -type decision struct{ member, lost, kept, says string } +// moves to another entry of that model's allOf, so only the erased place names +// it in both orders. +type decision struct{ member, passedOver, chosen, says string } // fact is a decision, the report stating it, its two places as written, not -// erased, which tell two entries of one allOf apart, and keptBy, the node the -// declaration at keptAt names as its compile holds it (keptTypes), empty where -// it reads none. A conflict between two declarations is such a report -// (ir.RelatedKept, ir.RelatedDecided), said once for every model composing -// them, so it states a fact per member it lists. +// erased, which tell two entries of one allOf apart, and chosenBy, what an +// untied member's fact is compared by beside its passed-over place +// (chosenPlaces). A member fold's report about two declarations is such a +// report (ir.RelatedChosen, ir.RelatedDecided), said once for every model +// composing them, so it states a fact per member it lists. type fact struct { decision - lostAt, keptAt, keptBy string - report report + passedOverAt, chosenAt, chosenBy string + report report } // factsOf splits rs into the facts its reports carrying a pair state and the -// reports carrying none, in order: one naming one kept place, a member at +// reports carrying none, in order: one naming one chosen place, a member at // least and nothing of another role. written erases the IDs and the places. func factsOf(rs []report, written sequences) (facts []fact, rest []report) { for _, report := range rs { - kept, decided, known := report.concerns() - if !known || len(kept) != 1 || len(decided) == 0 { + chosen, decided, known := report.concerns() + if !known || len(chosen) != 1 || len(decided) == 0 { rest = append(rest, report) continue } - lostAt, keptAt := placeOf(report.rebased.Provenance), placeOf(kept[0]) + passedOverAt, chosenAt := placeOf(report.rebased.Provenance), placeOf(chosen[0]) for _, member := range decided { facts = append(facts, fact{ - member: erase(member.Node, written), lost: erase(lostAt, written), kept: erase(keptAt, written), - says: sayingOf(report.rebased, member, written), lostAt: lostAt, keptAt: keptAt, report: report, + member: erase(member.Node, written), passedOver: erase(passedOverAt, written), chosen: erase(chosenAt, written), + says: sayingOf(report.rebased, member, written), passedOverAt: passedOverAt, chosenAt: chosenAt, report: report, }) } } @@ -57,21 +58,21 @@ func factsOf(rs []report, written sequences) (facts []fact, rest []report) { } // concerns reads what r concerns besides its place, as rebased: the places it -// says were kept, the entries listing the nodes it says it decided, and +// says were chosen, the entries listing the nodes it says it decided, and // whether it names nothing of another role. -func (r report) concerns() (kept, decided []ir.Provenance, known bool) { +func (r report) concerns() (chosen, decided []ir.Provenance, known bool) { known = true for _, related := range r.rebased.Related { switch related.Role { - case ir.RelatedKept: - kept = append(kept, related.Provenance) + case ir.RelatedChosen: + chosen = append(chosen, related.Provenance) case ir.RelatedDecided: decided = append(decided, related.Provenance) default: known = false } } - return kept, decided, known + return chosen, decided, known } // placeOf is where provenance locates a declaration, as one string: its @@ -94,22 +95,22 @@ func sayingOf(diagnostic ir.Diagnostic, member ir.Provenance, written sequences) }) } -// tiedBy returns, sorted, the members a tie decided: each one a fact of a, -// the source as written, says lost one place and kept another, while a fact -// of b, the source reversed, says it lost that other and kept the first, the -// two reports saying the same beside those places. Two places only an erased -// index tells apart, entries of one allOf, are mirrored where they are as -// written. Nothing else of the two compiles is read: a tie is what the -// compiler reports as one in both orders. +// tiedBy returns, sorted, the members a tie decided: each one a fact of a, the +// source as written, says it passed over one place and chose another, while a +// fact of b, the source reversed, says it passed over that other and chose the +// first, the two reports saying the same beside those places. Entries of one +// allOf, which only an erased index tells apart, are mirrored where they are as +// written. A tie is what the compiler reports as one in both orders, and only a +// message, not read, says what it is over (GitHub #2340). func tiedBy(a, b []fact) []string { mirrored, exactly := make(map[decision]bool, len(b)), make(map[decision]bool, len(b)) for _, fact := range b { - mirrored[decision{member: fact.member, lost: fact.kept, kept: fact.lost, says: fact.says}] = true - exactly[decision{member: fact.member, lost: fact.keptAt, kept: fact.lostAt, says: fact.says}] = true + mirrored[decision{member: fact.member, passedOver: fact.chosen, chosen: fact.passedOver, says: fact.says}] = true + exactly[decision{member: fact.member, passedOver: fact.chosenAt, chosen: fact.passedOverAt, says: fact.says}] = true } var tied []string for _, fact := range a { - apart := fact.lost != fact.kept || exactly[decision{member: fact.member, lost: fact.lostAt, kept: fact.keptAt, says: fact.says}] + apart := fact.passedOver != fact.chosen || exactly[decision{member: fact.member, passedOver: fact.passedOverAt, chosen: fact.chosenAt, says: fact.says}] if mirrored[fact.decision] && apart { tied = append(tied, fact.member) } @@ -118,38 +119,54 @@ func tiedBy(a, b []fact) []string { return slices.Compact(tied) } -// unpairedFacts returns the reports of a and of b stating a fact the other -// side does not, of a member no tie decided (tied, sorted): facts pair one to -// one by member, lost place, what the report says, and the node kept -// (keptTypes), since of agreeing declarations of one node a report names the -// one written last, while copies at distinct nodes keep the declaration of the -// node sorting first in either order -// (docs/compilers/openapi.md#allof-redeclared-property); one read as none pairs -// with any. A tied member's facts are not compared, so a third declaration's -// report dropped in one order passes. +// codeConflictingRedeclaration is the code of a member fold's report of two +// declarations that cannot both hold (tiedByConflictsAlone). +const codeConflictingRedeclaration = "openapi/conflicting-redeclaration" + +// tiedByConflictsAlone returns the members of tied, sorted, that no tie a +// report other than a conflict states decides (tiedBy over a and b without +// their conflicts). A conflict decides what a member takes of two declarations +// that cannot both hold. Any other report carrying a pair is about what the +// member folds over every declaration, its docs, deprecation and XML hints +// among them, which such a tie decides (statedOf). Only its message says which +// detail it is about, so a tie over a default, an example or a type the two +// declarations share values of decides those too (GitHub #2340). +func tiedByConflictsAlone(tied []string, a, b []fact) []string { + isConflict := func(factValue fact) bool { return factValue.report.rebased.Code == codeConflictingRedeclaration } + byOthers := tiedBy(slices.DeleteFunc(slices.Clone(a), isConflict), slices.DeleteFunc(slices.Clone(b), isConflict)) + return slices.DeleteFunc(slices.Clone(tied), func(member string) bool { + _, decided := slices.BinarySearch(byOthers, member) + return decided + }) +} + +// unpairedFacts returns the reports of a and of b stating a fact the other side +// does not, of a member no tie decided (tied, sorted): facts pair one to one by +// member, passed-over place, what the report says, and the place chosen or the +// node a fold minted (chosenPlaces). A tied member's facts are not compared, so +// a third declaration's report dropped in one order passes. func unpairedFacts(a, b []fact, tied []string) (left, right []report) { return factsWithout(a, b, tied), factsWithout(b, a, tied) } -// factsWithout returns, once each and in order, the reports of a stating a -// fact of an untied member left once each fact of b takes one of a of its -// member, lost place and what its report says beside its places, kept by a -// declaration naming the same node, or where either reads none (pairing). +// factsWithout returns, once each and in order, the reports of a stating a fact +// of an untied member left once each fact of b takes one of a of its member, +// passed-over place and what its report says beside its places, and chosenBy. func factsWithout(a, b []fact, tied []string) []report { - type lost struct{ member, at, says string } - open := map[lost][]string{} + type openKey struct{ member, at, says string } + open := map[openKey][]string{} for _, fact := range b { - key := lost{fact.member, fact.lost, fact.says} - open[key] = append(open[key], fact.keptBy) + key := openKey{fact.member, fact.passedOver, fact.says} + open[key] = append(open[key], fact.chosenBy) } var out []report seen := map[string]bool{} for _, fact := range a { - key := lost{fact.member, fact.lost, fact.says} + key := openKey{fact.member, fact.passedOver, fact.says} if _, isTied := slices.BinarySearch(tied, fact.member); isTied { continue } - if i := pairing(open[key], fact.keptBy); i >= 0 { + if i := slices.Index(open[key], fact.chosenBy); i >= 0 { open[key] = slices.Delete(open[key], i, i+1) continue } @@ -161,43 +178,34 @@ func factsWithout(a, b []fact, tied []string) []report { return out } -// pairing returns the index, in kept, the nodes the other side's open facts -// were kept by, of the one a fact kept by keptBy pairs with: that node, or -// else one where either side reads none, or -1 for none. -func pairing(kept []string, keptBy string) int { - if i := slices.Index(kept, keptBy); i >= 0 { - return i - } - return slices.IndexFunc(kept, func(t string) bool { return t == "" || keptBy == "" }) -} - -// keptTypes returns facts, each with keptBy set to the node the declaration at -// its kept place names, as held, its compile's members, reads it, or the node -// the member takes where the fold minted it: of declarations that meet, each -// holding as many, the later wins, so which one a report names follows the -// order (docs/compilers/openapi.md#allof-redeclared-property). So a report on -// such a member naming a declaration it dropped as kept passes. Whether a node -// admits null is not read: the field admits null where every declaration -// folded into it does, whichever the report names. -func keptTypes(facts []fact, held map[string]held) []fact { +// chosenPlaces returns facts, each with chosenBy set to its chosen place, +// erased: of the declarations agreeing with the one chosen, a report names the +// first written, in either order, which only the index of an entry of a +// reversed allOf tells apart +// (docs/compilers/openapi.md#allof-redeclared-property). Where the fold minted +// the node the member takes, as held, its compile's members, reads it, chosenBy +// is that node: of declarations that meet, each holding as many, the later +// wins, so which one a report names follows the order, and a report there +// naming as chosen a declaration the fold dropped passes. +func chosenPlaces(facts []fact, held map[string]held) []fact { out := slices.Clone(facts) for i := range out { - heldValue := held[out[i].member] - out[i].keptBy = heldValue.named[pointerOf(out[i].keptAt)] - if takes, _, _ := strings.Cut(heldValue.takes, " "); out[i].keptBy != "" && composed(takes) { - out[i].keptBy = takes + out[i].chosenBy = out[i].chosen + if takes, _, _ := strings.Cut(held[out[i].member].takes, " "); composed(takes) { + out[i].chosenBy = takes } } return out } // held is what a document shows of one member that folds declarations: the -// type it takes, the type each declaration it overrides names, by that -// declaration's pointer, and the node each names, by the same. A type is its -// target, erased, and whether it admits null. +// type it takes, and the type each declaration it overrides names, by that +// declaration's pointer. A type is its target, erased, and whether it admits +// null. target is the member's target as its document names it. type held struct { - takes string - said, named map[string]string + takes string + target ir.TypeID + said map[string]string } // heldBy maps the ID, erased in seqs, of each member of doc's models' shapes @@ -209,9 +217,8 @@ func heldBy(doc *ir.Document, seqs, from sequences) map[string]held { if doc == nil { return out } - nodeOf := func(property *ir.Property) string { return erase(string(property.Type.Target), seqs) } typeOf := func(property *ir.Property) string { - return nodeOf(property) + " " + strconv.FormatBool(property.Type.Nullable) + return erase(string(property.Type.Target), seqs) + " " + strconv.FormatBool(property.Type.Nullable) } for id, td := range doc.Types { if _, isModel := td.(*ir.Model); !isModel { @@ -221,11 +228,12 @@ func heldBy(doc *ir.Document, seqs, from sequences) map[string]held { if flatProperty.Owner != id || len(flatProperty.Overridden) == 0 { continue } - heldValue := held{takes: typeOf(flatProperty.Property), said: make(map[string]string, len(flatProperty.Overridden)), - named: make(map[string]string, len(flatProperty.Overridden))} + heldValue := held{ + takes: typeOf(flatProperty.Property), target: flatProperty.Property.Type.Target, + said: make(map[string]string, len(flatProperty.Overridden)), + } for _, propertyDecl := range flatProperty.Overridden { - at := rebase(string(propertyDecl.Property.Provenance.Pointer), from) - heldValue.said[at], heldValue.named[at] = typeOf(propertyDecl.Property), nodeOf(propertyDecl.Property) + heldValue.said[rebase(string(propertyDecl.Property.Provenance.Pointer), from)] = typeOf(propertyDecl.Property) } out[erase(string(flatProperty.Property.ID), seqs)] = heldValue } @@ -234,13 +242,13 @@ func heldBy(doc *ir.Document, seqs, from sequences) map[string]held { } // contradicted returns a line for each tied member (tied, sorted) that holds, -// in each order, exactly the type of the declaration its report says lost -// there: as written the type the declaration at lost names, and reversed the -// one at kept, the two differing. A tie trades one declaration's say for the -// other's, so such a member took the loser's in both orders. It reads the two -// declarations as written and each compile's members (heldBy), so it checks a -// member only where both are declarations its flattening overrides, named by -// their own pointers. +// in each order, exactly the type of the declaration its report says it passed +// over there: as written the type the declaration at passedOver names, and +// reversed the one at chosen, the two differing. A tie trades one declaration's +// say for the other's, so such a member took the passed-over one's in both +// orders. It reads the two declarations as written and each compile's members +// (heldBy), so it checks a member only where both are declarations its +// flattening overrides, named by their own pointers. func contradicted(written, reversed map[string]held, stated []fact, tied []string) []string { if len(tied) == 0 { return nil @@ -251,40 +259,120 @@ func contradicted(written, reversed map[string]held, stated []fact, tied []strin continue } held, heldValue := written[fact.member], reversed[fact.member] - lost, saysLost := held.said[pointerOf(fact.lostAt)] - kept, saysKept := held.said[pointerOf(fact.keptAt)] - if saysLost && saysKept && lost != kept && held.takes == lost && heldValue.takes == kept { + passedOverType, saysPassedOver := held.said[pointerOf(fact.passedOverAt)] + chosenType, saysChosen := held.said[pointerOf(fact.chosenAt)] + if saysPassedOver && saysChosen && passedOverType != chosenType && held.takes == passedOverType && heldValue.takes == chosenType { out = append(out, fact.member+" takes in each order the type of the declaration its report says lost: "+ - strconv.Quote(lost)+" as written, at "+pointerOf(fact.lostAt)+", and "+strconv.Quote(kept)+" reversed, at "+pointerOf(fact.keptAt)) + strconv.Quote(passedOverType)+" as written, at "+pointerOf(fact.passedOverAt)+", and "+strconv.Quote(chosenType)+" reversed, at "+pointerOf(fact.chosenAt)) } } slices.Sort(out) return slices.Compact(out) } +// alikeByOrder returns a line for each member of written, the compile as +// written (first), taking in reversed (second) another node saying the same +// (contentOf): a choice among alike nodes by order. A tie explains +// it only where it decided the member (tied, sorted), as contentOf reads no +// bound, default or note a report may set two nodes apart by, or where the +// member's declarations differ only where a tied or settled member is +// declared (cascaded): a model composing a tied member's model takes the +// member as the tie settled it. members are those members' pointers, erased +// in seqs and sorted. +func alikeByOrder(first, second *ir.Document, written, reversed map[string]held, tied, members []string, seqs sequences) []string { + var out []string + for _, member := range slices.Sorted(maps.Keys(written)) { + asWritten, reversedValue := written[member], reversed[member] + _, isTied := slices.BinarySearch(tied, member) + if isTied || reversedValue.target == "" || asWritten.takes == reversedValue.takes || + contentOf(first, asWritten.target, 0) != contentOf(second, reversedValue.target, 0) || + cascaded(asWritten, reversedValue, members, seqs) { + continue + } + out = append(out, member+" takes "+strconv.Quote(asWritten.takes)+" as written and "+strconv.Quote(reversedValue.takes)+ + " reversed, two nodes saying the same, and no tie changed what its declarations name") + } + return out +} + +// cascaded reports whether the declarations a member overrides, as written and +// reversed (held.said, each by its pointer as written), name the same types +// in both orders but where a member a tie decided or settled is declared +// (members, erased in seqs and sorted), one at least: the member's choice +// among them follows that tie. One whose declarations name the same in both +// is no cascade, so a choice that differs is the order's. +func cascaded(written, reversed held, members []string, seqs sequences) bool { + declarations := maps.Clone(written.said) + maps.Copy(declarations, reversed.said) + differs := false + for _, at := range slices.Sorted(maps.Keys(declarations)) { + writtenSays, inWritten := written.said[at] + reversedSays, inReversed := reversed.said[at] + if inWritten && inReversed && writtenSays == reversedSays { + continue + } + if !atMemberOf(members, at, seqs) { + return false + } + differs = true + } + return differs +} + +// atMemberOf reports whether the declaration at pointer, as written, is a +// member a tie decided or settled, by its pointer erased in seqs (members, +// sorted). +func atMemberOf(members []string, pointer string, seqs sequences) bool { + _, found := slices.BinarySearch(members, erase(pointer, seqs)) + return found +} + +// maxContentDepth bounds contentOf's descent through what a model's members +// and a list's elements name. +const maxContentDepth = 8 + +// contentOf is what the node id of doc says, without where it is written: a +// model's members and a list's elements read through, to maxContentDepth, and +// any other node by its ID, which a primitive and a component share between +// the two compiles. +func contentOf(doc *ir.Document, id ir.TypeID, depth int) string { + if depth > maxContentDepth { + return "deep" + } + switch td := doc.Types[id].(type) { + case *ir.Model: + members := make([]string, len(td.Properties)) + for i, property := range td.Properties { + members[i] = property.WireName + ":" + contentOf(doc, property.Type.Target, depth+1) + } + slices.Sort(members) + return "model{" + strings.Join(members, ",") + "}" + case *ir.List: + return "list<" + contentOf(doc, td.ElementType.Target, depth+1) + ">" + default: + return string(id) + } +} + // pointerOf is the pointer of a place placeOf wrote. func pointerOf(place string) string { pointer, _, _ := strings.Cut(place, "\x00") return pointer } -// statedAlone returns the members of stated, sorted, that no other tie -// reaches in doc: none a moved report names or sits over (moved), and none -// overriding a declaration a tie decided (tied, every tied node, sorted), -// which reads what that tie decided. A tie between two declarations that -// disagree decides what the member takes of them, not its docs, deprecation, -// name or XML hints (rewriter.statedOf), which fold over every declaration, two -// giving one differently drawing a report of their own -// (docs/compilers/openapi.md#allof-redeclared-property). IDs are erased in -// seqs, doc's coordinates; a nil doc removes none. -func statedAlone(stated []string, moved tieSites, tied []string, doc *ir.Document, seqs sequences) []string { +// statedAlone returns the members of stated, sorted, that no other tie reaches +// in doc: none overriding a declaration a tie decided (tied, every tied node, +// sorted), which reads what that tie decided. A conflict decides what the +// member takes of two declarations, not its docs, deprecation, name or XML +// hints (rewriter.statedOf), which fold over every declaration, two giving one +// differently drawing a report of their own, a tie of another code +// (tiedByConflictsAlone, docs/compilers/openapi.md#allof-redeclared-property). +// IDs are erased in seqs, doc's coordinates; a nil doc removes none. +func statedAlone(stated, tied []string, doc *ir.Document, seqs sequences) []string { if len(stated) == 0 || doc == nil { return stated } reached := map[string]bool{} - for _, node := range moved.nodes { - reached[node] = true - } for id, td := range doc.Types { if _, isModel := td.(*ir.Model); !isModel { continue @@ -294,7 +382,7 @@ func statedAlone(stated []string, moved tieSites, tied []string, doc *ir.Documen _, isTied := slices.BinarySearch(tied, erase(string(propertyDecl.Property.ID), seqs)) return isTied }) - if flatProperty.Owner == id && (settled || atSite(moved.pointers, erase(string(flatProperty.Property.Provenance.Pointer), seqs))) { + if flatProperty.Owner == id && settled { reached[erase(string(flatProperty.Property.ID), seqs)] = true } } diff --git a/internal/harness/ties_internal_test.go b/internal/harness/ties_internal_test.go index e9b8facb0..bec488171 100644 --- a/internal/harness/ties_internal_test.go +++ b/internal/harness/ties_internal_test.go @@ -20,13 +20,13 @@ import ( "github.com/dexpace/morphic/ir" ) -// conflictAt is a report at lost saying it kept what the declaration at each -// of kept says and decided each of members, as reportsOf reads one of a +// conflictAt is a report at passedOver saying it chose what the declaration at +// each of chosen says and decided each of members, as reportsOf reads one of a // source whose reversed sequences are seqs. -func conflictAt(seqs sequences, lost string, kept []string, members ...string) report { - irDiagnostic := diagnostic(ir.SeverityWarning, "x/conflict", lost, "") - for _, at := range kept { - irDiagnostic.Related = append(irDiagnostic.Related, ir.Related{Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: jsontext.Pointer(at)}}) +func conflictAt(seqs sequences, passedOver string, chosen []string, members ...string) report { + irDiagnostic := diagnostic(ir.SeverityWarning, "x/conflict", passedOver, "") + for _, at := range chosen { + irDiagnostic.Related = append(irDiagnostic.Related, ir.Related{Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: jsontext.Pointer(at)}}) } for _, member := range members { irDiagnostic.Related = append(irDiagnostic.Related, ir.Related{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: member}}) @@ -50,16 +50,16 @@ func decisionsOf(facts []fact) []decision { } // TestFactsOf_ReadsAFactPerMemberAReportDecided pins what states a fact: a -// report naming one kept place and the members it decided, one fact for each, -// its member and both places with a reversed sequence's index erased, and -// what the report says beside them. A report naming no kept place, two, no -// member, or an entry of a role the reading does not know, beside a pair or -// alone, states none and stays a report. +// report naming one chosen place and the members it decided, one fact for each, +// its member and both places with a reversed sequence's index erased, and what +// the report says beside them. A report naming no chosen place, two, no member, +// or an entry of a role the reading does not know, beside a pair or alone, +// states none and stays a report. func TestFactsOf_ReadsAFactPerMemberAReportDecided(t *testing.T) { t.Parallel() seqs := sequences{"/M/allOf": 2} plain := conflictAt(seqs, "/A/p", nil) - twoKept := conflictAt(seqs, "/A/p", []string{"/B/p", "/C/p"}, "property/M/p") + twoChosen := conflictAt(seqs, "/A/p", []string{"/B/p", "/C/p"}, "property/M/p") noMember := conflictAt(seqs, "/A/p", []string{"/B/p"}) unknown := conflictAt(seqs, "/A/p", nil) unknown.rebased.Related = []ir.Related{{Role: "other", Provenance: ir.Provenance{Pointer: "/B/p"}}} @@ -67,16 +67,16 @@ func TestFactsOf_ReadsAFactPerMemberAReportDecided(t *testing.T) { beside.rebased.Related = append(beside.rebased.Related, ir.Related{Role: "other", Provenance: ir.Provenance{Pointer: "/C/p"}}) pair := conflictAt(seqs, "/M/allOf/0/properties/p", []string{"/B/p"}, "property/M/allOf/1/p", "property/N/p") - facts, rest := factsOf([]report{plain, twoKept, pair, noMember, unknown, beside}, seqs) + facts, rest := factsOf([]report{plain, twoChosen, pair, noMember, unknown, beside}, seqs) - assert.Equal(t, []report{plain, twoKept, noMember, unknown, beside}, rest) - lost, kept := placeOf(ir.Provenance{Pointer: "/M/allOf/-/properties/p"}), placeOf(ir.Provenance{Pointer: "/B/p"}) + assert.Equal(t, []report{plain, twoChosen, noMember, unknown, beside}, rest) + passedOver, chosen := placeOf(ir.Provenance{Pointer: "/M/allOf/-/properties/p"}), placeOf(ir.Provenance{Pointer: "/B/p"}) says := sayingOf(pair.rebased, ir.Provenance{Source: ir.NoSource}, seqs) assert.Equal(t, []decision{ - {member: "property/M/allOf/-/p", lost: lost, kept: kept, says: says}, - {member: "property/N/p", lost: lost, kept: kept, says: says}, + {member: "property/M/allOf/-/p", passedOver: passedOver, chosen: chosen, says: says}, + {member: "property/N/p", passedOver: passedOver, chosen: chosen, says: says}, }, decisionsOf(facts)) - assert.Equal(t, "/M/allOf/0/properties/p", pointerOf(facts[0].lostAt), "the place as written tells one entry from another") + assert.Equal(t, "/M/allOf/0/properties/p", pointerOf(facts[0].passedOverAt), "the place as written tells one entry from another") assert.Equal(t, pair, facts[1].report) } @@ -92,7 +92,7 @@ func TestSayingOf_ReadsWhatAReportSaysBesideItsPlaces(t *testing.T) { want := sayingOf(base, member, seqs) moved := diagnostic(ir.SeverityWarning, "x/conflict", "/B/p", "property/N/p") - moved.Related = []ir.Related{{Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: "/A/p"}}} + moved.Related = []ir.Related{{Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: "/A/p"}}} assert.Equal(t, want, sayingOf(moved, ir.Provenance{Source: ir.NoSource, Node: "property/N/p"}, seqs), "places and the member are not read") assert.Equal(t, sayingOf(base, ir.Provenance{Source: ir.NoSource, Pointer: "/M/allOf/0"}, seqs), sayingOf(base, ir.Provenance{Source: ir.NoSource, Pointer: "/M/allOf/1"}, seqs), "an index of a reversed sequence is erased") @@ -132,8 +132,8 @@ func TestPlaceOf_ReadsWhatDescribesAPlace(t *testing.T) { } // TestTiedBy_TiesAMemberBothOrdersDecideTheOtherWayRound pins the one thing a -// tie is: a member one order says lost a place and kept another, and the -// other order says lost that other and kept the first. +// tie is: a member one order says passed over a place and chose another, and +// the other order says passed over that other and chose the first. func TestTiedBy_TiesAMemberBothOrdersDecideTheOtherWayRound(t *testing.T) { t.Parallel() seqs := sequences{"/M/allOf": 3, "/X/allOf": 2} @@ -159,7 +159,7 @@ func TestTiedBy_TiesAMemberBothOrdersDecideTheOtherWayRound(t *testing.T) { written: facts(conflictAt(seqs, "/A/p", []string{"/B/p"}, "property/M/p")), reversed: facts(conflictAt(seqs, "/B/p", []string{"/A/p"}, "property/N/p")), }, - "another place kept": { + "another place chosen": { written: facts(conflictAt(seqs, "/A/p", []string{"/B/p"}, "property/M/p")), reversed: facts(conflictAt(seqs, "/B/p", []string{"/C/p"}, "property/M/p")), }, @@ -176,7 +176,7 @@ func TestTiedBy_TiesAMemberBothOrdersDecideTheOtherWayRound(t *testing.T) { reversed: facts(conflictAt(seqs, "/M/allOf/1/properties/p", []string{"/M/allOf/0/properties/p"}, "property/M/p")), want: []string{"property/M/p"}, }, - "two entries of one allOf, the same one lost in both orders": { + "two entries of one allOf, the same one passed over in both orders": { written: facts(conflictAt(seqs, "/M/allOf/0/properties/p", []string{"/M/allOf/2/properties/p"}, "property/M/p")), reversed: facts(conflictAt(seqs, "/M/allOf/0/properties/p", []string{"/M/allOf/1/properties/p"}, "property/M/p")), }, @@ -193,12 +193,12 @@ func TestTiedBy_TiesAMemberBothOrdersDecideTheOtherWayRound(t *testing.T) { } } -// TestUnpairedFacts_PairsAnUntiedMembersFactsByWhatLost pins what of the -// facts is a difference: a fact of a member no tie decided that the other -// order does not state, by its member and the place that lost, one to one. The -// place kept is not compared there, a tied member's facts are none, and a +// TestUnpairedFacts_PairsAnUntiedMembersFactsByWhatWasPassedOver pins what of +// the facts is a difference: a fact of a member no tie decided that the other +// order does not state, by its member and the place passed over, one to one. +// The place chosen is not compared there, a tied member's facts are none, and a // report stating two unpaired facts is one report. -func TestUnpairedFacts_PairsAnUntiedMembersFactsByWhatLost(t *testing.T) { +func TestUnpairedFacts_PairsAnUntiedMembersFactsByWhatWasPassedOver(t *testing.T) { t.Parallel() seqs := sequences{} lone := conflictAt(seqs, "/A/p", []string{"/B/p"}, "property/M/p", "property/N/p", "property/T/p") @@ -209,7 +209,7 @@ func TestUnpairedFacts_PairsAnUntiedMembersFactsByWhatLost(t *testing.T) { left, right := unpairedFacts(written, reversed, []string{"property/T/p"}) - assert.Equal(t, []report{lone, twice}, left, "N's fact has no pair, T is tied, M's pairs though it kept another place, and q is said once more") + assert.Equal(t, []report{lone, twice}, left, "N's fact has no pair, T is tied, M's pairs though it chose another place, and q is said once more") assert.Empty(t, right) left, right = unpairedFacts(written, written, nil) @@ -225,72 +225,69 @@ func TestUnpairedFacts_PairsAnUntiedMembersFactsByWhatLost(t *testing.T) { assert.Equal(t, []report{info}, right) } -// TestUnpairedFacts_ComparesThePlaceKeptByTheTypeItsDeclarationNames pins how -// an untied member's kept place is compared: two facts kept by declarations -// naming one type pair, whichever declarations they are; two naming types -// that differ do not; and where either compile reads no type at the place, -// the place is not compared. -func TestUnpairedFacts_ComparesThePlaceKeptByTheTypeItsDeclarationNames(t *testing.T) { +// TestUnpairedFacts_ComparesWhatAFactWasChosenBy pins how an untied member's +// chosen place is compared: two facts chosen by one place, or by one node a +// fold minted, pair; two chosen by places that differ do not, whatever types +// their declarations name. +func TestUnpairedFacts_ComparesWhatAFactWasChosenBy(t *testing.T) { t.Parallel() seqs := sequences{} - keptBy := func(kept, by string) ([]fact, report) { - reportValue := conflictAt(seqs, "/B/p", []string{kept}, "property/W/p") + chosenBy := func(chosen, by string) ([]fact, report) { + reportValue := conflictAt(seqs, "/B/p", []string{chosen}, "property/W/p") facts, _ := factsOf([]report{reportValue}, seqs) - facts[0].keptBy = by + facts[0].chosenBy = by return facts, reportValue } - string1, _ := keptBy("/A/p", "type/primitive/string false") - string2, _ := keptBy("/C/p", "type/primitive/string false") - integer, wrong := keptBy("/B/p", "type/primitive/integer false") - unread, _ := keptBy("/D/p", "") - - left, right := unpairedFacts(string1, string2, nil) - assert.Empty(t, left, "two declarations alike") + atA, _ := chosenBy("/A/p", "/A/p") + againAtA, _ := chosenBy("/A/p", "/A/p") + atC, wrong := chosenBy("/C/p", "/C/p") + mintedAtA, _ := chosenBy("/A/p", "type/composed/W/p") + mintedAtC, _ := chosenBy("/C/p", "type/composed/W/p") + + left, right := unpairedFacts(atA, againAtA, nil) + assert.Empty(t, left, "one place") assert.Empty(t, right) - left, right = unpairedFacts(string1, integer, nil) - assert.Equal(t, []report{string1[0].report}, left, "a declaration of another type") + left, right = unpairedFacts(atA, atC, nil) + assert.Equal(t, []report{atA[0].report}, left, "another place") assert.Equal(t, []report{wrong}, right) - left, right = unpairedFacts(integer, unread, nil) - assert.Empty(t, left, "a place read as no type") + left, right = unpairedFacts(mintedAtA, mintedAtC, nil) + assert.Empty(t, left, "one node a fold minted, chosen at two places") assert.Empty(t, right) } -// TestKeptTypes_ReadsTheTypeTheDeclarationKeptNames pins where a fact's kept -// type comes from: the node the declaration at its kept place names, among -// those its member overrides, as its compile holds them, whether it admits null -// aside; the node the member takes where the fold minted it; and none where its -// member overrides nothing there or holds no declaration. The facts handed in -// are left as they were. -func TestKeptTypes_ReadsTheTypeTheDeclarationKeptNames(t *testing.T) { +// TestChosenPlaces_ReadsThePlaceChosenOrTheNodeAFoldMinted pins what a fact's +// chosen place is compared by: the place itself, erased, whatever the member +// takes, and the node the member takes where the fold minted it. The facts +// handed in are left as they were. +func TestChosenPlaces_ReadsThePlaceChosenOrTheNodeAFoldMinted(t *testing.T) { t.Parallel() + seqs := sequences{"/W/allOf": 3} facts, _ := factsOf([]report{ - conflictAt(nil, "/B/p", []string{"/A/p"}, "property/W/p"), - conflictAt(nil, "/B/p", []string{"/X/p"}, "property/W/p"), - conflictAt(nil, "/B/p", []string{"/A/p"}, "property/V/p"), - conflictAt(nil, "/B/p", []string{"/A/p"}, "property/M/p"), - conflictAt(nil, "/B/p", []string{"/X/p"}, "property/M/p"), - }, nil) + conflictAt(seqs, "/B/p", []string{"/A/p"}, "property/W/p"), + conflictAt(seqs, "/B/p", []string{"/W/allOf/2/properties/p"}, "property/W/p"), + conflictAt(seqs, "/B/p", []string{"/A/p"}, "property/V/p"), + conflictAt(seqs, "/B/p", []string{"/A/p"}, "property/M/p"), + conflictAt(seqs, "/B/p", []string{"/X/p"}, "property/M/p"), + }, seqs) held := map[string]held{ - "property/W/p": { - takes: "type/primitive/string false", said: map[string]string{"/A/p": "type/primitive/string true"}, named: map[string]string{"/A/p": "type/primitive/string"}, - }, - "property/M/p": { - takes: "type/composed/M/p false", said: map[string]string{"/A/p": "type/anonymous/A/p false"}, named: map[string]string{"/A/p": "type/anonymous/A/p"}, - }, + "property/W/p": {takes: "type/primitive/string false", said: map[string]string{"/A/p": "type/primitive/string true"}}, + "property/M/p": {takes: "type/composed/M/p false", said: map[string]string{"/A/p": "type/anonymous/A/p false"}}, } - got := keptTypes(facts, held) + got := chosenPlaces(facts, held) - assert.Equal(t, []string{"type/primitive/string", "", "", "type/composed/M/p", ""}, - []string{got[0].keptBy, got[1].keptBy, got[2].keptBy, got[3].keptBy, got[4].keptBy}) - assert.Empty(t, facts[0].keptBy) + assert.Equal(t, []string{placeOf(ir.Provenance{Pointer: "/A/p"}), placeOf(ir.Provenance{Pointer: "/W/allOf/-/properties/p"}), + placeOf(ir.Provenance{Pointer: "/A/p"}), "type/composed/M/p", "type/composed/M/p"}, + []string{got[0].chosenBy, got[1].chosenBy, got[2].chosenBy, got[3].chosenBy, got[4].chosenBy}) + assert.Empty(t, facts[0].chosenBy) } // TestHeldBy_ReadsWhatAMemberTakesAndWhatItsDeclarationsSay pins the reading -// the winner check rests on: a member its model declares over declarations it -// overrides, by its erased ID, with its type and each overridden one's by -// pointer; no member a model only inherits or declares alone, no node that is -// no model, and nothing of a document that did not compile. +// the contradiction check rests on: a member its model declares over +// declarations it overrides, by its erased ID, with its type, its target as +// named, and each overridden one's by pointer; no member a model only inherits +// or declares alone, no node that is no model, and nothing of a document that +// did not compile. func TestHeldBy_ReadsWhatAMemberTakesAndWhatItsDeclarationsSay(t *testing.T) { t.Parallel() first, _, perm := bothWays(t, fixtureSwap) @@ -299,13 +296,11 @@ func TestHeldBy_ReadsWhatAMemberTakesAndWhatItsDeclarationsSay(t *testing.T) { alphaP, betaP := "/components/schemas/alpha/properties/p", "/components/schemas/beta/properties/p" alphaQ, betaQ := "/components/schemas/alpha/properties/q", "/components/schemas/beta/properties/q" - heldValue := held{takes: "type/primitive/integer false", - said: map[string]string{alphaP: "type/primitive/string false", betaP: "type/primitive/integer false"}, - named: map[string]string{alphaP: "type/primitive/string", betaP: "type/primitive/integer"}, + heldValue := held{takes: "type/primitive/integer false", target: "type/primitive/integer", + said: map[string]string{alphaP: "type/primitive/string false", betaP: "type/primitive/integer false"}, } - otherHeld := held{takes: "type/primitive/string false", - said: map[string]string{alphaQ: "type/primitive/string false", betaQ: "type/primitive/string false"}, - named: map[string]string{alphaQ: "type/primitive/string", betaQ: "type/primitive/string"}, + otherHeld := held{takes: "type/primitive/string false", target: "type/primitive/string", + said: map[string]string{alphaQ: "type/primitive/string false", betaQ: "type/primitive/string false"}, } assert.Equal(t, map[string]held{ "property/composed/components/schemas/AB/allOf/properties/p": heldValue, @@ -335,18 +330,17 @@ func TestHeldBy_RebasesAReversedCompilesDeclarations(t *testing.T) { got := heldBy(doc, moved, moved) assert.Equal(t, map[string]held{"property/M/p": { - takes: "type/primitive/string true", - said: map[string]string{"/M/allOf/0/properties/p": "type/primitive/integer true"}, - named: map[string]string{"/M/allOf/0/properties/p": "type/primitive/integer"}, + takes: "type/primitive/string true", target: "type/primitive/string", + said: map[string]string{"/M/allOf/0/properties/p": "type/primitive/integer true"}, }}, got) } -// TestContradicted_FindsATiedMemberTakingWhatItsReportsSayLost pins the winner -// check's one finding and each thing it needs before it speaks: a tied member, -// two declarations its flattening overrides at the report's two places, naming -// different types, the one that lost taken as written and the one kept taken -// reversed. -func TestContradicted_FindsATiedMemberTakingWhatItsReportsSayLost(t *testing.T) { +// TestContradicted_FindsATiedMemberTakingWhatItsReportsSayWasPassedOver pins +// the contradiction check's one finding and each thing it needs before it +// speaks: a tied member, two declarations its flattening overrides at the +// report's two places, naming different types, the one passed over taken as +// written and the one chosen taken reversed. +func TestContradicted_FindsATiedMemberTakingWhatItsReportsSayWasPassedOver(t *testing.T) { t.Parallel() const ( member = "property/composed/components/schemas/AB/allOf/properties/p" @@ -369,8 +363,8 @@ func TestContradicted_FindsATiedMemberTakingWhatItsReportsSayLost(t *testing.T) return &out } wrongWritten, wrongReversed := swapped(first, "type/primitive/string"), swapped(second, "type/primitive/integer") - stated := func(lost, kept, of string) []fact { - facts, _ := factsOf([]report{conflictAt(perm.written, lost, []string{kept}, of)}, perm.written) + stated := func(passedOver, chosen, of string) []fact { + facts, _ := factsOf([]report{conflictAt(perm.written, passedOver, []string{chosen}, of)}, perm.written) return facts } tied := []string{member} @@ -380,13 +374,13 @@ func TestContradicted_FindsATiedMemberTakingWhatItsReportsSayLost(t *testing.T) tied []string found bool }{ - "the loser's type in each order": {first: wrongWritten, second: wrongReversed, stated: stated(alpha, beta, member), tied: tied, found: true}, - "the kept type in each order": {first: first, second: second, stated: stated(alpha, beta, member), tied: tied}, - "the loser's type as written only": {first: wrongWritten, second: second, stated: stated(alpha, beta, member), tied: tied}, - "no tie": {first: wrongWritten, second: wrongReversed, stated: stated(alpha, beta, member)}, - "a member no tie decided": {first: wrongWritten, second: wrongReversed, stated: stated(alpha, beta, member), tied: []string{"property/other"}}, - "a place no declaration is at": {first: wrongWritten, second: wrongReversed, stated: stated("/elsewhere", beta, member), tied: tied}, - "a kept place no declaration is at": { + "the passed-over type in each order": {first: wrongWritten, second: wrongReversed, stated: stated(alpha, beta, member), tied: tied, found: true}, + "the chosen type in each order": {first: first, second: second, stated: stated(alpha, beta, member), tied: tied}, + "the passed-over type as written only": {first: wrongWritten, second: second, stated: stated(alpha, beta, member), tied: tied}, + "no tie": {first: wrongWritten, second: wrongReversed, stated: stated(alpha, beta, member)}, + "a member no tie decided": {first: wrongWritten, second: wrongReversed, stated: stated(alpha, beta, member), tied: []string{"property/other"}}, + "a place no declaration is at": {first: wrongWritten, second: wrongReversed, stated: stated("/elsewhere", beta, member), tied: tied}, + "a chosen place no declaration is at": { first: wrongWritten, second: wrongReversed, stated: stated(alpha, "/elsewhere", member), tied: tied, }, "two declarations of one type": { @@ -424,23 +418,22 @@ func bothWays(t *testing.T, src string) (first, second *ir.Document, perm permut } // generatedRedeclarations is how many documents -// TestSequenceOrderInvariant_FindsOnlyARealDependenceInGeneratedRedeclarations +// TestSequenceOrderInvariant_FindsNoDependenceInGeneratedRedeclarations // writes, and generatedSeed the seed it writes them from. const ( generatedRedeclarations = 200 generatedSeed = 1996 ) -// TestSequenceOrderInvariant_FindsOnlyARealDependenceInGeneratedRedeclarations -// holds the oracle, over documents several models redeclare members in -// (redeclarations), to finding only what a second reading of the two compiles -// shows is no reported tie: a member naming, by the order of its entries, one -// of two nodes written alike (namesAlikeNodesByOrder), which no rule lets -// follow that order (GitHub #2099). Every other document passes, the ties -// their conflicts report forgiven. It also holds that most documents draw a -// conflict and that some write a member alike at two nodes, so they reach -// both readings. -func TestSequenceOrderInvariant_FindsOnlyARealDependenceInGeneratedRedeclarations(t *testing.T) { +// TestSequenceOrderInvariant_FindsNoDependenceInGeneratedRedeclarations holds +// documents several models redeclare members in (redeclarations) to no order +// dependence: the oracle passes each, the ties their conflicts report +// forgiven, among them a member naming, by the order of its entries, one of +// two nodes written alike only where a tie upstream changed what its +// declarations name (alikeByOrder), since a member names the least of them +// (GitHub #2099). It also holds that most documents draw a conflict and that +// some write a member alike at two nodes, so they reach both readings. +func TestSequenceOrderInvariant_FindsNoDependenceInGeneratedRedeclarations(t *testing.T) { rng := rand.New(rand.NewPCG(generatedSeed, generatedSeed)) conflicting, alike := 0, 0 for i := range generatedRedeclarations { @@ -459,65 +452,131 @@ func TestSequenceOrderInvariant_FindsOnlyARealDependenceInGeneratedRedeclaration got := sequenceOrderInvariant(context.Background(), "spec.json", data, true) // A document reading the same reversed has nothing to permute. - if got == passed(OracleSequenceOrder) || got == declined(OracleSequenceOrder, DeclineNothingToPermute) { + if got == declined(OracleSequenceOrder, DeclineNothingToPermute) { continue } - require.True(t, got.Found(), "document %d: %+v", i, got) - first, second, perm := bothWays(t, string(data)) - assert.True(t, namesAlikeNodesByOrder(first, second, perm), "document %d is found and holds no member naming alike nodes by order: %s\n%s", - i, got.Detail, data) + assert.Equal(t, passed(OracleSequenceOrder), got, "document %d: %s\n%s", i, got.Detail, data) } assert.Greater(t, conflicting, generatedRedeclarations/2, "most documents must draw a conflict between declarations") assert.Greater(t, alike, generatedRedeclarations/10, "the documents must write members alike at two nodes") } -// namesAlikeNodesByOrder reports whether a member of one of first's models -// names, in second, the reversed compile, another node than in first, the two -// saying the same (said): an order dependence no tie between declarations -// that disagree explains. -func namesAlikeNodesByOrder(first, second *ir.Document, perm permutation) bool { - for id, td := range first.Types { - model, isModel := td.(*ir.Model) - other, alsoModel := second.Types[id].(*ir.Model) - if !isModel || !alsoModel { - continue - } - for _, property := range model.Properties { - i := slices.IndexFunc(other.Properties, func(irProperty ir.Property) bool { return irProperty.WireName == property.WireName }) - if i < 0 { - continue - } - a, b := property.Type.Target, other.Properties[i].Type.Target - if erase(string(a), perm.written) != erase(string(b), perm.moved) && said(first, a, 0) == said(second, b, 0) { - return true - } - } +// TestAlikeByOrder_ForgivesOnlyACascade holds the oracle's reading of a member +// naming one of two nodes alike by order on the generated document 115, where +// M2 composes M0, whose p a tie settles as Obj written and as Alias0p +// reversed, so M2's p names Obj in one order and C1's copy of it in the +// other: forgiven as the tie's cascade. With M0's p naming Obj in both orders +// nothing upstream explains the choice, which only this reading finds; nor +// where another declaration of M2's p, one no tie decides, names something +// else reversed. +func TestAlikeByOrder_ForgivesOnlyACascade(t *testing.T) { + t.Parallel() + rng := rand.New(rand.NewPCG(generatedSeed, generatedSeed)) + var src map[string]any + for i := range 116 { + src, _ = redeclarations(rng, i) + } + data, err := json.Marshal(src, json.Deterministic(true)) + require.NoError(t, err) + const found = "a member names one of two nodes alike by sequence order:\n" + + `property/composed/components/schemas/M2/allOf/properties/p takes "type/openapi/components/schemas/Obj false" as written ` + + `and "type/anonymous/components/schemas/C1/properties/p false" reversed, two nodes saying the same, ` + + "and no tie changed what its declarations name" + model := func(doc *ir.Document, name string) *ir.Model { + model, ok := doc.Types[ir.TypeID("type/openapi/components/schemas/"+name)].(*ir.Model) + require.True(t, ok, name) + require.Equal(t, "p", model.Properties[0].WireName, name) + return model + } + for name, tc := range map[string]struct { + plant func(second *ir.Document) + detail func(t *testing.T, detail string) + }{ + "a tie upstream": {plant: func(*ir.Document) {}, detail: func(t *testing.T, detail string) { assert.Empty(t, detail) }}, + "no tie upstream": { + plant: func(second *ir.Document) { + model(second, "M0").Properties[0].Type.Target = "type/openapi/components/schemas/Obj" + }, + detail: func(t *testing.T, detail string) { assert.Equal(t, found, detail, "nothing else is found") }, + }, + "an untied declaration too": { + plant: func(second *ir.Document) { model(second, "C1").Properties[0].Type.Target = "type/primitive/string" }, + detail: func(t *testing.T, detail string) { assert.Contains(t, detail, found) }, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + baseline, why := reencodeMappings(data) + require.Empty(t, why) + reversed, perm, why := reverseSequences(data) + require.Empty(t, why) + first, firstDiags, err := compile(context.Background(), "spec.json", baseline, passes()) + require.NoError(t, err) + second, secondDiags, err := compile(context.Background(), "spec.json", reversed, passes()) + require.NoError(t, err) + tc.plant(second) + + detail, _, decline := diffSequenceInvariants(first, firstDiags, second, secondDiags, perm) + + require.Empty(t, decline) + tc.detail(t, detail) + }) } - return false } -// said is what the node id names says, without where it is written: a -// model's members and a list's elements read through, any other node by its -// ID, which a primitive and a component share between declarations. -func said(doc *ir.Document, id ir.TypeID, depth int) string { - if depth > 8 { - return "deep" - } - switch td := doc.Types[id].(type) { - case *ir.Model: - members := make([]string, len(td.Properties)) - for i, property := range td.Properties { - members[i] = property.WireName + ":" + said(doc, property.Type.Target, depth+1) +// TestCascaded_NeedsADeclarationATieDecidedToDiffer pins when a member's +// declarations, written and reversed, show a tie's cascade: one naming +// another type in the other order, or written in one order alone, where a +// member a tie decided or settled is declared, erased; never where none +// differs, and never where one an untied declaration gives differs too. +func TestCascaded_NeedsADeclarationATieDecidedToDiffer(t *testing.T) { + t.Parallel() + seqs := sequences{"/M0/allOf": 2} + members := []string{"/M0/allOf/-/properties/p"} + tied, untied := "/M0/allOf/1/properties/p", "/C1/properties/p" + says := func(declarations ...string) held { + heldValue := held{said: map[string]string{}} + for i := 0; i < len(declarations); i += 2 { + heldValue.said[declarations[i]] = declarations[i+1] } - slices.Sort(members) - return "model{" + strings.Join(members, ",") + "}" - case *ir.List: - return "list<" + said(doc, td.ElementType.Target, depth+1) + ">" - default: - return string(id) + return heldValue + } + for name, tc := range map[string]struct { + written, reversed held + want bool + }{ + "nothing differs": {says(tied, "obj", untied, "copy"), says(tied, "obj", untied, "copy"), false}, + "a tied declaration differs": {says(tied, "obj", untied, "copy"), says(tied, "list", untied, "copy"), true}, + "an untied one differs too": {says(tied, "obj", untied, "copy"), says(tied, "list", untied, "text"), false}, + "a tied one written in one order": {says(tied, "obj", untied, "copy"), says(untied, "copy"), true}, + "an untied one written in one only": {says(tied, "obj"), says(tied, "list", untied, "copy"), false}, + } { + assert.Equal(t, tc.want, cascaded(tc.written, tc.reversed, members, seqs), name) } } +// TestContentOf_ReadsMembersAndElementsToItsBound pins what contentOf compares +// of a node: a model's members by wire name, sorted, and a list's elements, +// each read through to maxContentDepth, past which it says "deep", so a +// model naming itself ends; any other node is its ID. +func TestContentOf_ReadsMembersAndElementsToItsBound(t *testing.T) { + t.Parallel() + text := ir.TypeRef{Target: "type/primitive/string"} + doc := &ir.Document{Types: ir.TypeRegistry{ + "type/M": &ir.Model{ID: "type/M", Properties: []ir.Property{ + {WireName: "self", Type: ir.TypeRef{Target: "type/M"}}, {WireName: "x", Type: text}, + }}, + "type/L": &ir.List{ID: "type/L", ElementType: text}, + }} + + got := contentOf(doc, "type/M", 0) + + assert.Equal(t, strings.Repeat("model{self:", maxContentDepth+1)+"deep,x:deep"+ + strings.Repeat("},x:type/primitive/string", maxContentDepth)+"}", got) + assert.Equal(t, "list", contentOf(doc, "type/L", 0)) + assert.Equal(t, "type/primitive/string", contentOf(doc, "type/primitive/string", 0)) +} + // redeclarations writes the i-th generated document, and whether it writes a // member alike at two nodes: two to five components declaring p, some q and r // too, each of a random kind (kindOf), some through an alias and some @@ -635,27 +694,23 @@ func refTo(name string) map[string]any { return map[string]any{"$ref": "#/compon // TestStatedAlone_LeavesOutWhatAnotherTieReaches pins which tied members keep // their docs compared: one a stated tie decided and nothing else reaches. A -// member a moved report names or sits over, or one overriding a declaration a -// tie decided, follows that tie too, and a document that did not compile -// removes none. +// member overriding a declaration a tie decided follows that tie too, and a +// document that did not compile removes none. func TestStatedAlone_LeavesOutWhatAnotherTieReaches(t *testing.T) { t.Parallel() stated := []string{"property/M/p", "property/Q/q"} for name, tc := range map[string]struct { - moved tieSites - tied []string - doc *ir.Document - want []string + tied []string + doc *ir.Document + want []string }{ "nothing else": {tied: stated, doc: settledDoc(), want: stated}, - "a moved report names one": {moved: tieSites{nodes: []string{"property/Q/q"}}, tied: stated, doc: settledDoc(), want: []string{"property/M/p"}}, - "a moved report sits over one": {moved: tieSites{pointers: []string{"/Q"}}, tied: stated, doc: settledDoc(), want: []string{"property/M/p"}}, "one overrides a tied member": {tied: []string{"property/AB/p", "property/M/p", "property/Q/q"}, doc: settledDoc(), want: []string{"property/Q/q"}}, - "a document that did not compile": {moved: tieSites{nodes: []string{"property/Q/q"}}, tied: stated, want: stated}, + "a document that did not compile": {tied: []string{"property/AB/p", "property/M/p", "property/Q/q"}, want: stated}, } { - assert.Equal(t, tc.want, statedAlone(stated, tc.moved, tc.tied, tc.doc, nil), name) + assert.Equal(t, tc.want, statedAlone(stated, tc.tied, tc.doc, nil), name) } - assert.Empty(t, statedAlone(nil, tieSites{}, nil, settledDoc(), nil)) + assert.Empty(t, statedAlone(nil, nil, settledDoc(), nil)) assert.Equal(t, []string{"property/M/p", "property/Q/q"}, stated, "the members handed in are left as they were") } @@ -668,7 +723,7 @@ func TestDiagnosticKey_ReadsWhatElseADiagnosticConcerns(t *testing.T) { base := func() ir.Diagnostic { irDiagnostic := diagnostic(ir.SeverityWarning, "x/conflict", "/A/p", "") irDiagnostic.Related = []ir.Related{ - {Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: "/B/p"}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: "/B/p"}}, {Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/M/p"}}, } return irDiagnostic diff --git a/internal/leakcheck/leakcheck.go b/internal/leakcheck/leakcheck.go index 26f305535..38a51c2ab 100644 --- a/internal/leakcheck/leakcheck.go +++ b/internal/leakcheck/leakcheck.go @@ -48,10 +48,10 @@ func Main(runner Runner) { } // profile is the subset of *pprof.Profile that verdict reads. A small -// consumer-defined interface stands in for *pprof.Profile itself because +// consumer-defined interface takes the place of *pprof.Profile itself because // nothing outside runtime/pprof can construct one carrying a chosen sample -// count, which is what verdict's own tests need in order to drive every -// branch without an actual leaked goroutine. +// count, which is what verdict's own tests need in order to drive every branch +// without an actual leaked goroutine. type profile interface { // Count reports how many stacks the profile currently holds. Count() int diff --git a/internal/leakcheck/main_test.go b/internal/leakcheck/main_test.go index 00f50f757..81ccc87bc 100644 --- a/internal/leakcheck/main_test.go +++ b/internal/leakcheck/main_test.go @@ -25,10 +25,10 @@ func TestMain(m *testing.M) { leakcheck.Main(m) } -// leakCheckChildEnv gates TestMain_ReportsALeak_Child: unset, it skips; set, -// it leaks on purpose. TestMain_ReportsALeak re-executes this test binary with -// and without it, which is the permanent reach test for this whole package — -// standing in for the plant-a-leak-and-delete-it cycle a one-off proof would +// leakCheckChildEnv gates TestMain_ReportsALeak_Child: unset, it skips; set, it +// leaks on purpose. TestMain_ReportsALeak re-executes this test binary with and +// without it, which is the permanent reach test for this whole package — taking +// the place of the plant-a-leak-and-delete-it cycle a one-off proof would // otherwise leave no record of. const leakCheckChildEnv = "LEAKCHECK_CHILD" diff --git a/internal/lintrules/ids.go b/internal/lintrules/ids.go index fe929db8a..76d69e670 100644 --- a/internal/lintrules/ids.go +++ b/internal/lintrules/ids.go @@ -32,13 +32,26 @@ func (l layout) idDerivations() *analysis.Analyzer { } const ( - convertedID = "converts a value to ir.%s outside compilers/compile; derive the ID through the framework" - spelledID = "spells an ir.%s as a constant outside compilers/compile; derive the ID through the framework" - gluedID = "glues an ir.%s together outside compilers/compile; derive the ID through the framework" + convertedID = "converts a value to ir.%s outside compilers/compile; %s" + spelledID = "spells an ir.%s as a constant outside compilers/compile; %s" + gluedID = "glues an ir.%s together outside compilers/compile; %s" spaceMessage = "builds a compile.Space from something other than one string literal; a namespace is a literal, or the path glued onto it loses its separator" - paramMessage = "builds a value of the type parameter %s, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive the ID through the framework" + paramMessage = "builds a value of the type parameter %s, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive each ID with the compile function of its kind, such as compile.TypeID(space, path), and take it as an argument" ) +// derivation says what to do instead of building the ir ID type named kind: +// the function of compilers/compile that derives it, or, for a kind none +// derives yet, that one is to be added there. It is held to compilers/compile +// by TestDerivation_NamesTheFunctionsCompileDeclares. +func derivation(kind string) string { + switch kind { + case "ChannelID", "MessageID": + return "compilers/compile has no function for ir." + kind + " yet; add one there rather than building it here" + default: + return "derive it with compile." + kind + "(space, path)" + } +} + func (l layout) runIDDerivations(pass *analysis.Pass) (any, error) { path := pass.Pkg.Path() if !l.within(path, "compilers") || l.within(path, "compilers/compile") { @@ -107,7 +120,7 @@ func (c idCheck) conversion(call *ast.CallExpr) bool { // or a namespace's, nor a type parameter's that a string type satisfies. tv := c.pass.TypesInfo.Types[call.Fun] if name, isID := c.idType(tv.Type); isID { - c.pass.Reportf(call.Pos(), convertedID, name) + c.pass.Reportf(call.Pos(), convertedID, name, derivation(name)) return true } if c.isSpace(tv.Type) && !stringLiteral(call.Args[0]) { @@ -126,7 +139,7 @@ func (c idCheck) conversion(call *ast.CallExpr) bool { // a string. func (c idCheck) glued(pos token.Pos, t types.Type) bool { if name, isID := c.idType(t); isID { - c.pass.Reportf(pos, gluedID, name) + c.pass.Reportf(pos, gluedID, name, derivation(name)) return true } if c.isSpace(t) { @@ -151,7 +164,7 @@ func (c idCheck) constant(e ast.Expr) bool { return false } if name, isID := c.idType(tv.Type); isID && constant.StringVal(tv.Value) != "" { - c.pass.Reportf(e.Pos(), spelledID, name) + c.pass.Reportf(e.Pos(), spelledID, name, derivation(name)) return true } if c.isSpace(tv.Type) && !stringLiteral(e) { diff --git a/internal/lintrules/lintrules.go b/internal/lintrules/lintrules.go index 534f1d0ff..1a0ab1a4a 100644 --- a/internal/lintrules/lintrules.go +++ b/internal/lintrules/lintrules.go @@ -99,8 +99,8 @@ func imported(pkg *types.Package, path string) *types.Package { return nil } -// satisfies reports whether t satisfies the constraint of the type parameter -// p, so that an instantiation can make p stand for t. +// satisfies reports whether t satisfies the constraint of the type parameter p, +// so that an instantiation can make p name t. func satisfies(t types.Type, p *types.TypeParam) bool { iface, _ := p.Underlying().(*types.Interface) // a type parameter's always is return types.Satisfies(t, iface) diff --git a/internal/lintrules/lintrules_internal_test.go b/internal/lintrules/lintrules_internal_test.go index 3f8d4b472..293d001e4 100644 --- a/internal/lintrules/lintrules_internal_test.go +++ b/internal/lintrules/lintrules_internal_test.go @@ -220,3 +220,40 @@ func TestRegistryOf_TakesAMapKeyedByANamedString(t *testing.T) { }) } } + +// TestDerivation_NamesTheFunctionsCompileDeclares holds derivation to the +// module: each ID type ir declares is named by the function of that name +// compilers/compile declares, and one it declares none for is said to have +// none, so a function added or removed there reddens the message that names it. +func TestDerivation_NamesTheFunctionsCompileDeclares(t *testing.T) { + t.Parallel() + load := func(path string) *types.Package { + cfg := &packages.Config{ + Mode: packages.NeedName | packages.NeedTypes | packages.NeedImports | packages.NeedDeps, + Env: append(os.Environ(), "GOPACKAGESDRIVER=off"), + } + pkgs, err := packages.Load(cfg, path) + require.NoError(t, err) + require.Len(t, pkgs, 1) + require.Zero(t, packages.PrintErrors(pkgs)) + return pkgs[0].Types + } + ir := load(irPath) + compile := load(compilePath) + + kinds := idTypes(ir) + require.NotEmpty(t, kinds) + for _, kind := range kinds { + if !token.IsExported(kind) { + continue // a compiler cannot name it, so no message does + } + function, declared := compile.Scope().Lookup(kind).(*types.Func) + if declared { + assert.Equal(t, "derive it with compile."+kind+"(space, path)", derivation(kind)) + assert.Equal(t, kind, function.Signature().Results().At(0).Type().(*types.Named).Obj().Name(), + "compile.%s must return the ID type it is named for", kind) + continue + } + assert.Contains(t, derivation(kind), "has no function for ir."+kind, "compile declares no %s", kind) + } +} diff --git a/internal/lintrules/testdata/mod/compilers/compilers.go b/internal/lintrules/testdata/mod/compilers/compilers.go index eb7744755..6052ddfd8 100644 --- a/internal/lintrules/testdata/mod/compilers/compilers.go +++ b/internal/lintrules/testdata/mod/compilers/compilers.go @@ -6,7 +6,7 @@ import "github.com/dexpace/morphic/ir" // Root converts an ID. func Root(name string) ir.TypeID { - return ir.TypeID(name) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive the ID through the framework" + return ir.TypeID(name) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive it with compile.TypeID(space, path)" } // Number converts to a type parameter no ID satisfies, where no compile.Space diff --git a/internal/lintrules/testdata/mod/compilers/compilex/compilex.go b/internal/lintrules/testdata/mod/compilers/compilex/compilex.go index 674b6c91c..9669c8f90 100644 --- a/internal/lintrules/testdata/mod/compilers/compilex/compilex.go +++ b/internal/lintrules/testdata/mod/compilers/compilex/compilex.go @@ -7,6 +7,6 @@ import "github.com/dexpace/morphic/ir" // Edge builds a registry, converts an ID and fills a name channel. func Edge(name string) (ir.TypeRegistry, ir.TypeID, ir.Naming) { reg := ir.TypeRegistry{} // want "registrywrites: builds a type registry (a map from ir.TypeID to ir.TypeDef) outside ir and compilers/compile; go through compile.Types" - id := ir.TypeID(name) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive the ID through the framework" + id := ir.TypeID(name) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive it with compile.TypeID(space, path)" return reg, id, ir.Naming{Canonical: name} // want "namechannels: ir.Naming.Canonical is filled by something other than a call into ir or compilers/compile; use ir.NamingFor, compile.NamingHint or ir.CanonicalWords" } diff --git a/internal/lintrules/testdata/mod/compilers/graphql/ids.go b/internal/lintrules/testdata/mod/compilers/graphql/ids.go index 73e2869e8..134134483 100644 --- a/internal/lintrules/testdata/mod/compilers/graphql/ids.go +++ b/internal/lintrules/testdata/mod/compilers/graphql/ids.go @@ -7,13 +7,13 @@ import ( irx "github.com/dexpace/morphic/ir" ) -const anyTypeID ir.TypeID = "type/graphql/any" // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" +const anyTypeID ir.TypeID = "type/graphql/any" // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" -const aliasedID irx.OperationID = "o/aliased" // want "idderivations: spells an ir.OperationID as a constant outside compilers/compile; derive the ID through the framework" +const aliasedID irx.OperationID = "o/aliased" // want "idderivations: spells an ir.OperationID as a constant outside compilers/compile; derive it with compile.OperationID(space, path)" const untyped = "type/graphql/untyped" -const gluedConst ir.TypeID = "type/" + "graphql" // want "idderivations: glues an ir.TypeID together outside compilers/compile; derive the ID through the framework" +const gluedConst ir.TypeID = "type/" + "graphql" // want "idderivations: glues an ir.TypeID together outside compilers/compile; derive it with compile.TypeID(space, path)" const fixedSpace compile.Space = "graphql" @@ -32,33 +32,33 @@ func lookupType(ir.TypeID) {} // as converts to its type parameter, which an ID or compile.Space satisfies. func as[T ~string](s string) T { - return T(s) // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive the ID through the framework" + return T(s) // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive each ID with the compile function of its kind, such as compile.TypeID(space, path), and take it as an argument" } // glue joins two values of its type parameter. func glue[T ~string](a, b T) T { - return a + b // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive the ID through the framework" + return a + b // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive each ID with the compile function of its kind, such as compile.TypeID(space, path), and take it as an argument" } // extend glues onto a value of its type parameter in place. func extend[T ~string](t T) T { - t += "/x" // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive the ID through the framework" + t += "/x" // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive each ID with the compile function of its kind, such as compile.TypeID(space, path), and take it as an argument" return t } // spell spells a value of its type parameter as a constant. func spell[T ~string]() T { - return "type/graphql/generic" // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive the ID through the framework" + return "type/graphql/generic" // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive each ID with the compile function of its kind, such as compile.TypeID(space, path), and take it as an argument" } // operationID converts to a type parameter only an ID satisfies. func operationID[T interface{ ir.OperationID }](s string) T { - return T(s) // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive the ID through the framework" + return T(s) // want "idderivations: builds a value of the type parameter T, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive each ID with the compile function of its kind, such as compile.TypeID(space, path), and take it as an argument" } // namespace converts to a type parameter only compile.Space satisfies. func namespace[S interface{ compile.Space }](s string) S { - return S(s) // want "idderivations: builds a value of the type parameter S, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive the ID through the framework" + return S(s) // want "idderivations: builds a value of the type parameter S, which an ir ID or a compile.Space satisfies, outside compilers/compile; derive each ID with the compile function of its kind, such as compile.TypeID(space, path), and take it as an argument" } // blank, same and number build nothing an ID can be: an empty constant, a @@ -68,21 +68,23 @@ func same[T ~string](t T) T { return T(t) } func number[N ~int](i int) N { return N(i) } func plantIDs(doc *ir.Document, pointer string, existing ir.OperationID, s compile.Space) ir.TypeID { - _ = ir.TypeID("type/graphql" + pointer) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive the ID through the framework" - _ = ir.PropertyID(pointer) // want "idderivations: converts a value to ir.PropertyID outside compilers/compile; derive the ID through the framework" - _ = irx.EnumMemberID(pointer) // want "idderivations: converts a value to ir.EnumMemberID outside compilers/compile; derive the ID through the framework" - _ = ir.OperationID(existing) // want "idderivations: converts a value to ir.OperationID outside compilers/compile; derive the ID through the framework" - _ = typeID(pointer) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive the ID through the framework" - _ = ir.TypeRef{Target: "type/graphql/ref"} // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" - _ = doc.Types["type/graphql/key"] // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" - lookupType("type/graphql/arg") // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" - var fromUntyped ir.TypeID = untyped // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" - var fromFramework ir.TypeID = frame.Untyped // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" - var aliasedType typeID = "type/graphql/a" // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" - parent := fromUntyped + "/items" // want "idderivations: glues an ir.TypeID together outside compilers/compile; derive the ID through the framework" - parent += "/0" // want "idderivations: glues an ir.TypeID together outside compilers/compile; derive the ID through the framework" + _ = ir.TypeID("type/graphql" + pointer) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive it with compile.TypeID(space, path)" + _ = ir.PropertyID(pointer) // want "idderivations: converts a value to ir.PropertyID outside compilers/compile; derive it with compile.PropertyID(space, path)" + _ = irx.EnumMemberID(pointer) // want "idderivations: converts a value to ir.EnumMemberID outside compilers/compile; derive it with compile.EnumMemberID(space, path)" + _ = ir.OperationID(existing) // want "idderivations: converts a value to ir.OperationID outside compilers/compile; derive it with compile.OperationID(space, path)" + _ = ir.ChannelID(pointer) // want "idderivations: converts a value to ir.ChannelID outside compilers/compile; compilers/compile has no function for ir.ChannelID yet; add one there rather than building it here" + _ = ir.MessageID(pointer) // want "idderivations: converts a value to ir.MessageID outside compilers/compile; compilers/compile has no function for ir.MessageID yet; add one there rather than building it here" + _ = typeID(pointer) // want "idderivations: converts a value to ir.TypeID outside compilers/compile; derive it with compile.TypeID(space, path)" + _ = ir.TypeRef{Target: "type/graphql/ref"} // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" + _ = doc.Types["type/graphql/key"] // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" + lookupType("type/graphql/arg") // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" + var fromUntyped ir.TypeID = untyped // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" + var fromFramework ir.TypeID = frame.Untyped // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" + var aliasedType typeID = "type/graphql/a" // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" + parent := fromUntyped + "/items" // want "idderivations: glues an ir.TypeID together outside compilers/compile; derive it with compile.TypeID(space, path)" + parent += "/0" // want "idderivations: glues an ir.TypeID together outside compilers/compile; derive it with compile.TypeID(space, path)" switch parent { - case "type/graphql/case": // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" + case "type/graphql/case": // want "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" } _ = compile.Space(pointer) // want "idderivations: builds a compile.Space from something other than one string literal; a namespace is a literal, or the path glued onto it loses its separator" _ = compile.Space('A') // want "idderivations: builds a compile.Space from something other than one string literal; a namespace is a literal, or the path glued onto it loses its separator" diff --git a/internal/lintrules/testdata/mod/compilers/graphql/settle.go b/internal/lintrules/testdata/mod/compilers/graphql/settle.go index bd70670a2..577eeef52 100644 --- a/internal/lintrules/testdata/mod/compilers/graphql/settle.go +++ b/internal/lintrules/testdata/mod/compilers/graphql/settle.go @@ -20,7 +20,7 @@ type rewrite struct { // Settle rewrites a node of reg, which is its to rewrite, and writes others, // which are not. It also leaves a write to reg in a function literal, which // can run after Settle returns. -func (r *rewrite) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { +func (r *rewrite) Settle(_ context.Context, reg ir.TypeRegistry, _ *ir.AliasChainIndex) []ir.Diagnostic { id := r.id reg[id] = reg[id] delete(reg, r.id) // want "registrywrites: writes a type registry outside ir and compilers/compile; go through compile.Types, or rewrite a node in a compile.Settlement" @@ -55,27 +55,27 @@ type ( } ) -func (r *rebound) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { +func (r *rebound) Settle(_ context.Context, reg ir.TypeRegistry, _ *ir.AliasChainIndex) []ir.Diagnostic { reg[r.id] = nil // want "registrywrites: writes through the registry parameter Settle rebinds, which may name a registry it was not handed; leave the parameter bound" (reg) = r.other reg[r.id] = nil // want "registrywrites: writes through the registry parameter Settle rebinds, which may name a registry it was not handed; leave the parameter bound" return nil } -func (a *addressed) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { +func (a *addressed) Settle(_ context.Context, reg ir.TypeRegistry, _ *ir.AliasChainIndex) []ir.Diagnostic { _ = ® reg[a.id] = nil // want "registrywrites: writes through the registry parameter Settle rebinds, which may name a registry it was not handed; leave the parameter bound" return nil } -func (r *ranged) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { +func (r *ranged) Settle(_ context.Context, reg ir.TypeRegistry, _ *ir.AliasChainIndex) []ir.Diagnostic { for _, reg = range r.all { reg[r.id] = nil // want "registrywrites: writes through the registry parameter Settle rebinds, which may name a registry it was not handed; leave the parameter bound" } return nil } -func (f *fed) Settle(_ context.Context, reg ir.TypeRegistry) []ir.Diagnostic { +func (f *fed) Settle(_ context.Context, reg ir.TypeRegistry, _ *ir.AliasChainIndex) []ir.Diagnostic { for reg = range f.feed { reg[f.id] = nil // want "registrywrites: writes through the registry parameter Settle rebinds, which may name a registry it was not handed; leave the parameter bound" } @@ -87,7 +87,7 @@ type notASettlement struct{} // Settle takes a registry it was not handed by compile.Types.Finish. func (notASettlement) Settle(reg ir.TypeRegistry) { - reg["a"] = nil // want "registrywrites: writes a type registry outside ir and compilers/compile; go through compile.Types, or rewrite a node in a compile.Settlement" "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive the ID through the framework" + reg["a"] = nil // want "registrywrites: writes a type registry outside ir and compilers/compile; go through compile.Types, or rewrite a node in a compile.Settlement" "idderivations: spells an ir.TypeID as a constant outside compilers/compile; derive it with compile.TypeID(space, path)" } // Settle is a function, not a method, whatever its name and what it takes. diff --git a/internal/lintrules/testdata/mod/compilers/indirect/indirect.go b/internal/lintrules/testdata/mod/compilers/indirect/indirect.go index f0003d9d7..9f55dfe71 100644 --- a/internal/lintrules/testdata/mod/compilers/indirect/indirect.go +++ b/internal/lintrules/testdata/mod/compilers/indirect/indirect.go @@ -9,5 +9,5 @@ import "github.com/dexpace/morphic/compilers/compile" func Indirect() bool { n := compile.NamingHint("a") n.Hint = "b" // want "namechannels: ir.Naming.Hint is filled by something other than a call into ir or compilers/compile; use ir.NamingFor, compile.NamingHint or ir.CanonicalWords" - return compile.OperationID(compile.Space("x"), "/p") == "operation/x/p" // want "idderivations: spells an ir.OperationID as a constant outside compilers/compile; derive the ID through the framework" + return compile.OperationID(compile.Space("x"), "/p") == "operation/x/p" // want "idderivations: spells an ir.OperationID as a constant outside compilers/compile; derive it with compile.OperationID(space, path)" } diff --git a/ir/admission.go b/ir/admission.go new file mode 100644 index 000000000..38100a1da --- /dev/null +++ b/ir/admission.go @@ -0,0 +1,45 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "strconv" + +// Admission is a reader's answer to whether a type admits a value: yes or no +// where the facts it read decide, and unknown where a fact it could not read +// might (docs/ir/values.md#admission-answers). +type Admission uint8 + +const ( + // AdmitsUnknown is the answer where a fact the reader did not read might + // decide. + AdmitsUnknown Admission = iota + // AdmitsYes is the answer where every fact the reader read about the type + // admits the value, and none is left unread. + AdmitsYes + // AdmitsNo is the answer where a fact the reader read refuses the value. + AdmitsNo +) + +// AdmissionOf is a judged answer: yes where holds, no otherwise. +func AdmissionOf(holds bool) Admission { + if holds { + return AdmitsYes + } + return AdmitsNo +} + +// String names the answer: yes, no or unknown, and admission(n) for a value +// n no constant names. +func (admission Admission) String() string { + switch admission { + case AdmitsYes: + return "yes" + case AdmitsNo: + return "no" + case AdmitsUnknown: + return "unknown" + default: + return "admission(" + strconv.Itoa(int(admission)) + ")" + } +} diff --git a/ir/admission_answer.go b/ir/admission_answer.go new file mode 100644 index 000000000..550f5a6cf --- /dev/null +++ b/ir/admission_answer.go @@ -0,0 +1,366 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "maps" + "slices" + "strconv" + "strings" + "unicode/utf8" +) + +// admissionAnswer is one judgment a [ValueAdmissionReader] makes: its answer, and for +// a no whether it rests only on members a model closed after composition does +// not evaluate, which an anyOf's other variants may (unevaluatedOnly). +type admissionAnswer struct { + admission Admission + unevaluatedOnly bool +} + +// admitted, refused and undecided are the three answers. +func admitted() admissionAnswer { return admissionAnswer{admission: AdmitsYes} } +func refused() admissionAnswer { return admissionAnswer{admission: AdmitsNo} } +func undecided() admissionAnswer { return admissionAnswer{admission: AdmitsUnknown} } + +// answerOf is a yes or a no as ok says. +func answerOf(ok bool) admissionAnswer { + return admissionAnswer{admission: AdmissionOf(ok)} +} + +// and is both judgments at once, a no resting only on members left +// unevaluated where every no does. +func (judged admissionAnswer) and(other admissionAnswer) admissionAnswer { + switch { + case judged.admission == AdmitsNo || other.admission == AdmitsNo: + return admissionAnswer{admission: AdmitsNo, + unevaluatedOnly: judged.leftUnevaluatedOrNotNo() && other.leftUnevaluatedOrNotNo()} + case judged.admission == AdmitsUnknown || other.admission == AdmitsUnknown: + return undecided() + default: + return admitted() + } +} + +// leftUnevaluatedOrNotNo reports whether judged is no refusal, or one resting +// only on members left unevaluated. +func (judged admissionAnswer) leftUnevaluatedOrNotNo() bool { + return judged.admission != AdmitsNo || judged.unevaluatedOnly +} + +// yesToUnknown is the judgment where a fact the reader cannot read bears on it: a +// yes is unknown, and a no stays a no. +func (judged admissionAnswer) yesToUnknown() admissionAnswer { + if judged.admission == AdmitsYes { + return undecided() + } + return judged +} + +// keptEntryAnswer judges value against the entries unmodeled keeps, in key +// order: a validation-only or degraded entry makes a yes unknown, a no_ir_home +// entry is sourceFormats' to judge, and any other asserts nothing of a value. +func keptEntryAnswer(unmodeled Unmodeled, sourceFormats SourceFormatAdmissions, value *Value) admissionAnswer { + judged := admitted() + if len(unmodeled) == 0 { + return judged + } + for _, key := range slices.Sorted(maps.Keys(unmodeled)) { + entry := unmodeled[key] + switch entry.Reason { + case ReasonValidationOnly, ReasonDegradedLowering: + judged = judged.yesToUnknown() + case ReasonNoIRHome: + judged = judged.and(askKeptEntry(sourceFormats, key, entry, value)) + case ReasonVendorExtension, ReasonOutOfScope: + } + } + return judged +} + +// askKeptEntry is sourceFormats' judgment of value against a kept no_ir_home +// entry, unknown where there is no source format to ask. +func askKeptEntry(sourceFormats SourceFormatAdmissions, key string, entry UnmodeledEntry, value *Value) admissionAnswer { + if sourceFormats == nil { + return undecided() + } + return admissionAnswer{admission: sourceFormats.AdmitsUnderUnmodeledEntry(key, entry, *value)} +} + +// askEncoding is sourceFormats' judgment of value against an encoding, unknown +// where there is no source format to ask. +func askEncoding(sourceFormats SourceFormatAdmissions, encoding *Encoding, value *Value) admissionAnswer { + if sourceFormats == nil { + return undecided() + } + return admissionAnswer{admission: sourceFormats.AdmitsUnderEncoding(encoding, *value)} +} + +// intersectionAnswer judges value against an intersection of bounds: a +// disagreeing keyword binding a value of its kind makes a yes unknown. +// patterns holds the patterns read before. +func intersectionAnswer(bounds ConstraintIntersection, value *Value, depth int, patterns patternMatchers) admissionAnswer { + if bounds.disagreeing == 0 { + return constraintsAnswer(bounds.constraints, value, depth, patterns) + } + judged := constraintsAnswer(bounds.AgreedConstraints(), value, depth, patterns) + for _, keyword := range bounds.DisagreeingKeywords() { + if keyword.Binds(value.Kind) { + judged = judged.yesToUnknown() + } + } + return judged +} + +// ConstraintsAdmit judges value against the keywords of constraints alone, as +// a [ValueAdmissionReader] judges the bounds beside a type: no where a bound, +// a count or a pattern binding a value of its kind excludes it, unknown where +// a pattern outside the subset ir reads or beside bytes, a precision or a +// scale would otherwise admit it, and yes otherwise, a keyword of another +// kind saying nothing. Nil constraints admit every value. It compiles a +// pattern for each call. +func ConstraintsAdmit(constraints *Constraints, value Value) Admission { + return constraintsAnswer(constraints, &value, 0, nil).admission +} + +// constraintsAnswer is ConstraintsAdmit's judgment, depth levels into a +// value. patterns holds the patterns read before, nil where none are held. +func constraintsAnswer(constraints *Constraints, value *Value, depth int, patterns patternMatchers) admissionAnswer { + if constraints == nil { + return admitted() + } + switch value.Kind { + case ValueNumber, ValueInfinity, ValueNegativeInfinity, ValueNaN: + return numberAnswer(constraints, value) + case ValueString, ValueSymbol: + judged := answerOf(within(int64(utf8.RuneCountInString(value.String)), constraints.MinLength, constraints.MaxLength)) + if constraints.Pattern != "" { + judged = judged.and(patternAnswer(constraints.Pattern, value.String, patterns)) + } + return judged + case ValueBytes: + judged := answerOf(within(int64(len(value.Bytes)), constraints.MinLength, constraints.MaxLength)) + if constraints.Pattern != "" { + judged = judged.and(undecided()) + } + return judged + case ValueList: + judged := answerOf(within(int64(len(value.List)), constraints.MinItems, constraints.MaxItems)) + if constraints.UniqueItems { + judged = judged.and(distinctAnswer(value.List, depth)) + } + return judged + case ValueObject: + return answerOf(within(int64(len(value.Object)), constraints.MinProperties, constraints.MaxProperties)) + case ValueNull, ValueBool, ValueRefKind, ValueConstructor: + return admitted() + default: + return admitted() + } +} + +// numberAnswer judges a number, an infinity or NaN against the numeric +// keywords of constraints. A precision or a scale, which ir does not read, and +// a bound or a number no Decimal holds answer unknown. +func numberAnswer(constraints *Constraints, value *Value) admissionAnswer { + var decimal Decimal + if value.Kind == ValueNumber { + read, err := value.Number.Decimal() + if err != nil { + return undecided() + } + decimal = read + } + judged := admitted() + for _, bound := range []struct { + value *BigVal + holds func(order int) bool + }{ + {constraints.Min, func(order int) bool { return order >= 0 }}, + {constraints.ExclusiveMin, func(order int) bool { return order > 0 }}, + {constraints.Max, func(order int) bool { return order <= 0 }}, + {constraints.ExclusiveMax, func(order int) bool { return order < 0 }}, + } { + if bound.value == nil { + continue + } + limit, err := bound.value.Decimal() + if err != nil { + judged = judged.and(undecided()) + continue + } + order, ordered := numericOrder(value.Kind, decimal, limit) + judged = judged.and(answerOf(ordered && bound.holds(order))) + } + if constraints.MultipleOf != nil { + judged = judged.and(multipleOfAnswer(*constraints.MultipleOf, value.Kind, decimal)) + } + if constraints.Precision != nil || constraints.Scale != nil { + judged = judged.yesToUnknown() + } + return judged +} + +// numericOrder is how a value of kind, decimal where it is a number, compares +// with a finite limit, as Decimal.Cmp answers: an infinity lies past every +// limit on its side, and NaN is ordered against none, so ordered is false and +// no bound holds it. +func numericOrder(kind ValueKind, decimal, limit Decimal) (order int, ordered bool) { + switch kind { + case ValueNumber: + return decimal.Cmp(limit), true + case ValueInfinity: + return 1, true + case ValueNegativeInfinity: + return -1, true + case ValueNaN, ValueNull, ValueBool, ValueString, ValueBytes, ValueSymbol, ValueList, ValueObject, ValueRefKind, ValueConstructor: + // numberAnswer asks of a number, an infinity or NaN alone. + return 0, false + default: + return 0, false + } +} + +// multipleOfAnswer judges a value of kind, decimal where it is a number, +// against the step multipleOf: an infinity or NaN, which no division by a +// step makes an integer, is refused, and a step no Decimal holds is unknown. +func multipleOfAnswer(multipleOf BigVal, kind ValueKind, decimal Decimal) admissionAnswer { + step, err := multipleOf.Decimal() + switch { + case err != nil: + return undecided() + case kind != ValueNumber: + return refused() + default: + return admissionAnswer{admission: MultipleOfAdmits(step, decimal)} + } +} + +// within reports whether count lies between the inclusive counts low and +// high, either of which may be absent. +func within(count int64, low, high *int64) bool { + return (low == nil || count >= *low) && (high == nil || count <= *high) +} + +// distinctAnswer judges whether no two of values are one JSON value: unknown +// where one cannot be spelled canonically (canonicalValue). +func distinctAnswer(values []Value, depth int) admissionAnswer { + seen := make(map[string]bool, len(values)) + for i := range values { + spelled, ok := canonicalValue(&values[i], depth+1) + if !ok { + return undecided() + } + if seen[spelled] { + return refused() + } + seen[spelled] = true + } + return admitted() +} + +// sameValueAnswer judges whether a and b are one JSON value, as their +// canonical spellings say: unknown where either has none. Two scalars compare +// without being spelled (sameScalar). +func sameValueAnswer(a, b *Value, depth int) admissionAnswer { + if same, compared := sameScalar(a, b); compared { + return answerOf(same) + } + x, okX := canonicalValue(a, depth) + y, okY := canonicalValue(b, depth) + if !okX || !okY { + return undecided() + } + return answerOf(x == y) +} + +// CanonicalValueSpelling spells value as one JSON text whatever its spelling, +// the one reading of whether two values are one JSON value: a number by its +// Decimal, so 1 and 1.0 spell alike, and an object's members sorted by name, +// so their order does not count. It reports false for a value JSON does not +// spell (bytes, a symbol, a reference, a constructor, a non-finite number), a +// number no Decimal holds, and one nested past maxAdmitsDepth. +func CanonicalValueSpelling(value Value) (string, bool) { + return canonicalValue(&value, 0) +} + +// sameScalar reports whether a and b are one value, as their canonical +// spellings say. compared is false where either is no JSON scalar or is a +// number no Decimal holds, which only spelling them decides. +func sameScalar(a, b *Value) (same, compared bool) { + if !spelledAlone(a.Kind) || !spelledAlone(b.Kind) { + return false, false + } + switch { + case a.Kind != b.Kind: + return false, true + case a.Kind == ValueBool: + return a.Bool == b.Bool, true + case a.Kind == ValueString: + return a.String == b.String, true + case a.Kind == ValueNumber: + x, errX := a.Number.Decimal() + y, errY := b.Number.Decimal() + return x.Cmp(y) == 0, errX == nil && errY == nil + default: + return true, true // two nulls + } +} + +// spelledAlone reports whether a value of kind is a JSON scalar: a null, a +// bool, a string or a number. +func spelledAlone(kind ValueKind) bool { + return kind == ValueNull || kind == ValueBool || kind == ValueString || kind == ValueNumber +} + +// canonicalValue is CanonicalValueSpelling, depth levels into a value. +func canonicalValue(value *Value, depth int) (string, bool) { + if depth > maxAdmitsDepth { + return "", false + } + switch value.Kind { + case ValueNull: + return "null", true + case ValueBool: + return strconv.FormatBool(value.Bool), true + case ValueString: + return strconv.Quote(value.String), true + case ValueNumber: + decimal, err := value.Number.Decimal() + if err != nil { + return "", false + } + return decimal.String(), true + case ValueList: + parts := make([]string, len(value.List)) + for i := range value.List { + part, ok := canonicalValue(&value.List[i], depth+1) + if !ok { + return "", false + } + parts[i] = part + } + return "[" + strings.Join(parts, ",") + "]", true + case ValueObject: + return canonicalObject(value.Object, depth) + case ValueBytes, ValueSymbol, ValueRefKind, ValueConstructor, ValueInfinity, ValueNegativeInfinity, ValueNaN: + return "", false + default: + return "", false + } +} + +// canonicalObject spells an object's members sorted by name. +func canonicalObject(fields []Field, depth int) (string, bool) { + parts := make([]string, len(fields)) + for i := range fields { + member, ok := canonicalValue(&fields[i].Value, depth+1) + if !ok { + return "", false + } + parts[i] = strconv.Quote(fields[i].Name) + ":" + member + } + slices.Sort(parts) + return "{" + strings.Join(parts, ",") + "}", true +} diff --git a/ir/admission_answer_test.go b/ir/admission_answer_test.go new file mode 100644 index 000000000..170d9ddd3 --- /dev/null +++ b/ir/admission_answer_test.go @@ -0,0 +1,190 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// nestedListValue is an empty list nested depth lists deep. +func nestedListValue(depth int) ir.Value { + nested := listValueOf() + for range depth { + nested = listValueOf(nested) + } + return nested +} + +// TestConstraintsAdmit_JudgesEachKeyword pins each constraint keyword at its +// boundary, the last value in and the first out, a keyword that does not apply +// to the value's kind, a pattern by whether the text holds a match, and what ir +// does not read, which answers unknown where it applies. +func TestConstraintsAdmit_JudgesEachKeyword(t *testing.T) { + t.Parallel() + bytes := ir.Value{Kind: ir.ValueBytes, Bytes: []byte("abc")} + for _, tc := range []struct { + name string + constraints *ir.Constraints + value ir.Value + want ir.Admission + }{ + {"no constraints", nil, textValue("anything"), ir.AdmitsYes}, + {"minimum, at it", &ir.Constraints{Min: new(ir.BigVal("5"))}, numberValue("5.0"), ir.AdmitsYes}, + {"minimum, below it", &ir.Constraints{Min: new(ir.BigVal("5"))}, numberValue("4.9"), ir.AdmitsNo}, + {"exclusiveMinimum, at it", &ir.Constraints{ExclusiveMin: new(ir.BigVal("5"))}, numberValue("5"), ir.AdmitsNo}, + {"exclusiveMinimum, above it", &ir.Constraints{ExclusiveMin: new(ir.BigVal("5"))}, numberValue("5.01"), ir.AdmitsYes}, + {"maximum, at it", &ir.Constraints{Max: new(ir.BigVal("1e2"))}, numberValue("100"), ir.AdmitsYes}, + {"maximum, above it", &ir.Constraints{Max: new(ir.BigVal("1e2"))}, numberValue("100.5"), ir.AdmitsNo}, + {"exclusiveMaximum, at it", &ir.Constraints{ExclusiveMax: new(ir.BigVal("10"))}, numberValue("10"), ir.AdmitsNo}, + {"exclusiveMaximum, below it", &ir.Constraints{ExclusiveMax: new(ir.BigVal("10"))}, numberValue("9"), ir.AdmitsYes}, + {"a bound outside the grammar", &ir.Constraints{Max: new(ir.BigVal("1p4"))}, numberValue("1"), ir.AdmitsUnknown}, + {"multipleOf, a multiple", &ir.Constraints{MultipleOf: new(ir.BigVal("0.1"))}, numberValue("0.3"), ir.AdmitsYes}, + {"multipleOf, off the step", &ir.Constraints{MultipleOf: new(ir.BigVal("0.1"))}, numberValue("0.35"), ir.AdmitsNo}, + {"multipleOf, a multiple past what a rational builds", &ir.Constraints{MultipleOf: new(ir.BigVal("2"))}, numberValue("1e5000"), ir.AdmitsYes}, + {"multipleOf, a step far below the value", &ir.Constraints{MultipleOf: new(ir.BigVal("1e-5000"))}, numberValue("1"), ir.AdmitsYes}, + {"multipleOf, a step outside the grammar", &ir.Constraints{MultipleOf: new(ir.BigVal("2p1"))}, numberValue("4"), ir.AdmitsUnknown}, + {"multipleOf, a value outside the grammar", &ir.Constraints{MultipleOf: new(ir.BigVal("2"))}, numberValue("1p4"), ir.AdmitsUnknown}, + {"precision, which ir does not read", &ir.Constraints{Precision: new(int64(5))}, numberValue("1"), ir.AdmitsUnknown}, + {"scale, which ir does not read", &ir.Constraints{Scale: new(int64(2))}, numberValue("1"), ir.AdmitsUnknown}, + {"a numeric bound on a string", &ir.Constraints{Max: new(ir.BigVal("1"))}, textValue("hello"), ir.AdmitsYes}, + {"maxLength in code points, at it", &ir.Constraints{MaxLength: new(int64(3))}, textValue("héé"), ir.AdmitsYes}, + {"maxLength, past it", &ir.Constraints{MaxLength: new(int64(3))}, textValue("hello"), ir.AdmitsNo}, + {"minLength, short of it", &ir.Constraints{MinLength: new(int64(2))}, textValue("a"), ir.AdmitsNo}, + {"a length on a number", &ir.Constraints{MaxLength: new(int64(1))}, numberValue("12345"), ir.AdmitsYes}, + {"a pattern the text matches", &ir.Constraints{Pattern: "^a"}, textValue("a"), ir.AdmitsYes}, + {"a pattern the text does not match", &ir.Constraints{Pattern: "^a"}, textValue("b"), ir.AdmitsNo}, + {"a pattern outside the subset ir reads", &ir.Constraints{Pattern: "^(?=a)"}, textValue("a"), ir.AdmitsUnknown}, + {"a pattern beside a length the text breaks", &ir.Constraints{Pattern: "^a", MaxLength: new(int64(1))}, textValue("ab"), ir.AdmitsNo}, + {"a pattern on a number", &ir.Constraints{Pattern: "^a"}, numberValue("1"), ir.AdmitsYes}, + {"maxLength on bytes", &ir.Constraints{MaxLength: new(int64(2))}, bytes, ir.AdmitsNo}, + {"maxLength on a symbol, past it", &ir.Constraints{MaxLength: new(int64(2))}, ir.Value{Kind: ir.ValueSymbol, String: "abc"}, ir.AdmitsNo}, + {"a pattern a symbol matches", &ir.Constraints{Pattern: "^a"}, ir.Value{Kind: ir.ValueSymbol, String: "abc"}, ir.AdmitsYes}, + {"a pattern a symbol does not match", &ir.Constraints{Pattern: "^b"}, ir.Value{Kind: ir.ValueSymbol, String: "abc"}, ir.AdmitsNo}, + {"maxItems, at it", &ir.Constraints{MaxItems: new(int64(2))}, listValueOf(numberValue("1"), numberValue("2")), ir.AdmitsYes}, + {"maxItems, past it", &ir.Constraints{MaxItems: new(int64(2))}, listValueOf(numberValue("1"), numberValue("2"), numberValue("3")), ir.AdmitsNo}, + {"minItems, short of it", &ir.Constraints{MinItems: new(int64(1))}, listValueOf(), ir.AdmitsNo}, + {"uniqueItems, distinct", &ir.Constraints{UniqueItems: true}, listValueOf(numberValue("1"), textValue("1"), nullValue()), ir.AdmitsYes}, + {"uniqueItems, one number spelled twice", &ir.Constraints{UniqueItems: true}, listValueOf(numberValue("1"), numberValue("1.0")), ir.AdmitsNo}, + {"uniqueItems, one object in two member orders", &ir.Constraints{UniqueItems: true}, + listValueOf(objectOf("a", numberValue("1"), "b", boolValue(true)), objectOf("b", boolValue(true), "a", numberValue("1"))), ir.AdmitsNo}, + {"uniqueItems, two lists", &ir.Constraints{UniqueItems: true}, listValueOf(listValueOf(numberValue("1")), listValueOf(numberValue("2"))), ir.AdmitsYes}, + {"uniqueItems, a member no JSON text spells", &ir.Constraints{UniqueItems: true}, listValueOf(ir.Value{Kind: ir.ValueSymbol}), ir.AdmitsUnknown}, + {"uniqueItems, nesting within ir's bound", &ir.Constraints{UniqueItems: true}, listValueOf(nestedListValue(9)), ir.AdmitsYes}, + {"uniqueItems, nesting past ir's bound", &ir.Constraints{UniqueItems: true}, listValueOf(nestedListValue(70)), ir.AdmitsUnknown}, + {"maxProperties, past it", &ir.Constraints{MaxProperties: new(int64(1))}, objectOf("a", numberValue("1"), "b", numberValue("2")), ir.AdmitsNo}, + {"minProperties, at it", &ir.Constraints{MinProperties: new(int64(1))}, objectOf("a", numberValue("1")), ir.AdmitsYes}, + {"a count on a bool", &ir.Constraints{MaxItems: new(int64(0))}, boolValue(false), ir.AdmitsYes}, + {"a value of no kind ir declares, which no keyword binds", &ir.Constraints{MaxLength: new(int64(0))}, ir.Value{Kind: "unknown"}, ir.AdmitsYes}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, ir.ConstraintsAdmit(tc.constraints, tc.value)) + }) + } +} + +// TestConstraintsAdmit_JudgesAnInfinityOrNaNByTheNumericKeywords pins the +// non-finite values against each numeric keyword: an infinity lies past every +// limit on its side, so it passes each bound below it and fails each above, +// NaN is ordered against no limit, so it fails every bound, and neither is a +// multiple of a step. NaN under no numeric keyword is admitted, a precision or +// a scale leaves a yes unknown, and a bound no Decimal reads is unknown. +func TestConstraintsAdmit_JudgesAnInfinityOrNaNByTheNumericKeywords(t *testing.T) { + t.Parallel() + infinity, negativeInfinity, nan := ir.Value{Kind: ir.ValueInfinity}, ir.Value{Kind: ir.ValueNegativeInfinity}, ir.Value{Kind: ir.ValueNaN} + minimum, exclusiveMinimum := &ir.Constraints{Min: new(ir.BigVal("-1e300"))}, &ir.Constraints{ExclusiveMin: new(ir.BigVal("-1e300"))} + maximum, exclusiveMaximum := &ir.Constraints{Max: new(ir.BigVal("1e300"))}, &ir.Constraints{ExclusiveMax: new(ir.BigVal("1e300"))} + step := &ir.Constraints{MultipleOf: new(ir.BigVal("1e-300"))} + for _, tc := range []struct { + name string + constraints *ir.Constraints + value ir.Value + want ir.Admission + }{ + {"an infinity, above a minimum", minimum, infinity, ir.AdmitsYes}, + {"an infinity, above an exclusive minimum", exclusiveMinimum, infinity, ir.AdmitsYes}, + {"an infinity, past a maximum", maximum, infinity, ir.AdmitsNo}, + {"an infinity, past an exclusive maximum", exclusiveMaximum, infinity, ir.AdmitsNo}, + {"an infinity, off a step", step, infinity, ir.AdmitsNo}, + {"a negative infinity, below a minimum", minimum, negativeInfinity, ir.AdmitsNo}, + {"a negative infinity, below an exclusive minimum", exclusiveMinimum, negativeInfinity, ir.AdmitsNo}, + {"a negative infinity, within a maximum", maximum, negativeInfinity, ir.AdmitsYes}, + {"a negative infinity, within an exclusive maximum", exclusiveMaximum, negativeInfinity, ir.AdmitsYes}, + {"a negative infinity, off a step", step, negativeInfinity, ir.AdmitsNo}, + {"NaN, against a minimum", minimum, nan, ir.AdmitsNo}, + {"NaN, against an exclusive minimum", exclusiveMinimum, nan, ir.AdmitsNo}, + {"NaN, against a maximum", maximum, nan, ir.AdmitsNo}, + {"NaN, against an exclusive maximum", exclusiveMaximum, nan, ir.AdmitsNo}, + {"NaN, off a step", step, nan, ir.AdmitsNo}, + {"NaN, under no numeric keyword", &ir.Constraints{MaxLength: new(int64(0)), MaxItems: new(int64(0))}, nan, ir.AdmitsYes}, + {"an infinity, beside a precision ir does not read", &ir.Constraints{Precision: new(int64(5))}, infinity, ir.AdmitsUnknown}, + {"an infinity, past a maximum beside a scale", &ir.Constraints{Max: new(ir.BigVal("1")), Scale: new(int64(2))}, infinity, ir.AdmitsNo}, + {"an infinity, against a bound outside the grammar", &ir.Constraints{Max: new(ir.BigVal("1p4"))}, infinity, ir.AdmitsUnknown}, + {"NaN, against a step outside the grammar", &ir.Constraints{MultipleOf: new(ir.BigVal("2p1"))}, nan, ir.AdmitsUnknown}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, ir.ConstraintsAdmit(tc.constraints, tc.value)) + }) + } +} + +// TestCanonicalValueSpelling_SpellsOneJSONValueOneWay pins the one spelling +// two values are compared by: a number by its value, an object whatever the +// order of its members, duplicate names among them, a string apart from the +// number it spells, and no spelling for a value JSON does not write, a number +// outside the grammar or nesting past ir's bound. +func TestCanonicalValueSpelling_SpellsOneJSONValueOneWay(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + value ir.Value + spelling string + }{ + {"a number by its value", numberValue("1500"), "1.5e3"}, + {"another spelling of it", numberValue("15e2"), "1.5e3"}, + {"every zero", numberValue("-0.0"), "0"}, + {"a string apart from the number it spells", textValue("1"), `"1"`}, + {"an object's members by name", objectOf("b", nullValue(), "a", boolValue(true)), `{"a":true,"b":null}`}, + {"duplicate names, whatever their order", objectOf("a", numberValue("2"), "a", numberValue("1")), `{"a":1e0,"a":2e0}`}, + {"a list in its order", listValueOf(numberValue("2"), numberValue("1")), "[2e0,1e0]"}, + {"nesting within ir's bound", nestedListValue(2), "[[[]]]"}, + } { + spelling, ok := ir.CanonicalValueSpelling(tc.value) + assert.True(t, ok, tc.name) + assert.Equal(t, tc.spelling, spelling, tc.name) + } + for _, tc := range []struct { + name string + value ir.Value + }{ + {"a number outside the grammar", numberValue("1p4")}, + {"bytes", ir.Value{Kind: ir.ValueBytes, Bytes: []byte("a")}}, + {"a symbol", ir.Value{Kind: ir.ValueSymbol, String: "a"}}, + {"a non-finite number", ir.Value{Kind: ir.ValueNaN}}, + {"nesting past ir's bound", nestedListValue(70)}, + } { + spelling, ok := ir.CanonicalValueSpelling(tc.value) + assert.False(t, ok, tc.name) + assert.Empty(t, spelling, tc.name) + } +} + +// TestAdmission_StringNamesEachAnswer pins the word each answer prints as, and +// the plain number a value no constant names prints with. +func TestAdmission_StringNamesEachAnswer(t *testing.T) { + t.Parallel() + for admission, want := range map[ir.Admission]string{ + ir.AdmitsYes: "yes", + ir.AdmitsNo: "no", + ir.AdmitsUnknown: "unknown", + ir.Admission(7): "admission(7)", + } { + assert.Equal(t, want, admission.String()) + } +} diff --git a/ir/admission_enum.go b/ir/admission_enum.go new file mode 100644 index 000000000..c791f37cd --- /dev/null +++ b/ir/admission_enum.go @@ -0,0 +1,134 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "math" + "sort" +) + +// enumMembers is an enum's members read once, so a value is looked up among +// them rather than compared with each as sameValueAnswer compares two. +type enumMembers struct { + strings map[string]bool + numbers map[Decimal]bool + // composite holds each list and object member by its canonical spelling. + // A value spelled alike is spelled at the same depths, so one spelled at + // the depth judged finds it. shallowest is the least depth a composite + // member is spelled to (spelledTo), math.MaxInt where none is: past it a + // lookup answers unknown. + composite map[string]bool + shallowest int + count int + null bool + holdsFalse bool + holdsTrue bool + // foreign reports a member spelled at no depth, which makes every miss + // unknown, and unparsed a number no Decimal holds, which makes a number's + // or a spelled value's miss unknown. + foreign bool + unparsed bool +} + +// readEnumMembers reads members once for every value looked up among them. +func readEnumMembers(members []EnumMember) *enumMembers { + read := &enumMembers{strings: map[string]bool{}, numbers: map[Decimal]bool{}, composite: map[string]bool{}, + shallowest: math.MaxInt, count: len(members)} + for i := range members { + read.add(&members[i].Value) + } + return read +} + +// add reads one member. +func (read *enumMembers) add(value *Value) { + switch value.Kind { + case ValueNull: + read.null = true + case ValueBool: + read.holdsTrue = read.holdsTrue || value.Bool + read.holdsFalse = read.holdsFalse || !value.Bool + case ValueString: + read.strings[value.String] = true + case ValueNumber: + decimal, err := value.Number.Decimal() + if err != nil { + read.unparsed = true + return + } + read.numbers[decimal] = true + case ValueList, ValueObject: + spelled, ok := canonicalValue(value, 0) + if !ok { + read.foreign = true + return + } + read.composite[spelled] = true + read.shallowest = min(read.shallowest, spelledTo(value)) + case ValueBytes, ValueSymbol, ValueRefKind, ValueConstructor, ValueInfinity, ValueNegativeInfinity, ValueNaN: + read.foreign = true + default: + read.foreign = true + } +} + +// spelledTo is the greatest depth canonicalValue spells value at, given it +// spells it at depth 0: it spells it at every depth up to that one and at +// none past it. +func spelledTo(value *Value) int { + return sort.Search(maxAdmitsDepth+1, func(depth int) bool { + _, deeper := canonicalValue(value, depth+1) + return !deeper + }) +} + +// judge is whether value, depth levels into the value judged, is a member, +// answering as comparing it with each by sameValueAnswer would. +func (read *enumMembers) judge(value *Value, depth int) admissionAnswer { + if read.count == 0 { + return refused() + } + switch value.Kind { + case ValueNull: + return read.found(read.null, false, depth) + case ValueBool: + return read.found(value.Bool && read.holdsTrue || !value.Bool && read.holdsFalse, false, depth) + case ValueString: + return read.found(read.strings[value.String], false, depth) + case ValueNumber: + decimal, err := value.Number.Decimal() + if err != nil { + return read.found(false, len(read.numbers) > 0 || read.unparsed || len(read.composite) > 0, depth) + } + return read.found(read.numbers[decimal], read.unparsed, depth) + case ValueList, ValueObject, ValueBytes, ValueSymbol, ValueRefKind, ValueConstructor, ValueInfinity, + ValueNegativeInfinity, ValueNaN: + return read.foundSpelled(value, depth) + default: + return read.foundSpelled(value, depth) + } +} + +// foundSpelled is judge for a value only its canonical spelling compares. +func (read *enumMembers) foundSpelled(value *Value, depth int) admissionAnswer { + spelled, ok := canonicalValue(value, depth) + if !ok { + return undecided() + } + return read.found(read.composite[spelled], read.unparsed, depth) +} + +// found is judge once the value's own lookup has answered listed: unknown +// rather than no where a member cannot be compared with it, which +// unknownBesides reports beside the members read. +func (read *enumMembers) found(listed, unknownBesides bool, depth int) admissionAnswer { + switch { + case listed: + return admitted() + case read.foreign || unknownBesides || read.shallowest < depth: + return undecided() + default: + return refused() + } +} diff --git a/ir/admission_internal_test.go b/ir/admission_internal_test.go new file mode 100644 index 000000000..7401b4423 --- /dev/null +++ b/ir/admission_internal_test.go @@ -0,0 +1,207 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestConstraintKeyword_BindsTheKindsOfItsTable pins which values each keyword +// bounds, the arms no conflict reaches among them, since a length or a count +// intersects any other: a conflicting one would cap only a value of its own +// kind. Every keyword has a row, and a value no constant names has none. +func TestConstraintKeyword_BindsTheKindsOfItsTable(t *testing.T) { + t.Parallel() + numbers := []ValueKind{ValueNumber, ValueInfinity, ValueNegativeInfinity, ValueNaN} + text := []ValueKind{ValueString, ValueSymbol, ValueBytes} + want := map[ConstraintKeyword][]ValueKind{ + ConstraintKeywordMin: numbers, + ConstraintKeywordExclusiveMin: numbers, + ConstraintKeywordMax: numbers, + ConstraintKeywordExclusiveMax: numbers, + ConstraintKeywordMultipleOf: numbers, + ConstraintKeywordPrecision: numbers, + ConstraintKeywordScale: numbers, + ConstraintKeywordMinLength: text, + ConstraintKeywordMaxLength: text, + ConstraintKeywordPattern: text, + ConstraintKeywordPatternMessage: text, + ConstraintKeywordMinItems: {ValueList}, + ConstraintKeywordMaxItems: {ValueList}, + ConstraintKeywordMinProperties: {ValueObject}, + ConstraintKeywordMaxProperties: {ValueObject}, + ConstraintKeywordPatternMessage + 1: nil, + } + for keyword := range ConstraintKeywords() { + assert.Contains(t, want, keyword, "the test lists %s", keyword) + } + for keyword, kinds := range want { + for _, kind := range []ValueKind{ValueNumber, ValueInfinity, ValueNegativeInfinity, ValueNaN, ValueString, ValueSymbol, + ValueBytes, ValueList, ValueObject, ValueNull, ValueBool, ValueRefKind, ValueConstructor, ValueKind("unheard-of")} { + assert.Equal(t, slices.Contains(kinds, kind), keyword.Binds(kind), "keyword %d on %s", keyword, kind) + } + } +} + +// TestIntersectionAnswer_CapsAValueEachConflictingKeywordBinds pins that a +// conflicting pattern or scale, which no one value holds, leaves unknown a yes +// for every kind of value it bounds, a symbol and bytes beside a string, and +// leaves a value of another kind admitted. +func TestIntersectionAnswer_CapsAValueEachConflictingKeywordBinds(t *testing.T) { + t.Parallel() + patterns := ConstraintIntersectionOf(&Constraints{Pattern: "^a"}).Intersect(ConstraintIntersectionOf(&Constraints{Pattern: "^b"})) + scales := ConstraintIntersectionOf(&Constraints{Scale: new(int64(2))}).Intersect(ConstraintIntersectionOf(&Constraints{Scale: new(int64(3))})) + require.NotZero(t, patterns.disagreeing) + require.NotZero(t, scales.disagreeing) + for _, tc := range []struct { + name string + bounds ConstraintIntersection + value Value + want Admission + }{ + {"a pattern, a string", patterns, Value{Kind: ValueString}, AdmitsUnknown}, + {"a pattern, a symbol", patterns, Value{Kind: ValueSymbol}, AdmitsUnknown}, + {"a pattern, bytes", patterns, Value{Kind: ValueBytes}, AdmitsUnknown}, + {"a pattern, a number", patterns, Value{Kind: ValueNumber, Number: "1"}, AdmitsYes}, + {"a scale, a number", scales, Value{Kind: ValueNumber, Number: "1"}, AdmitsUnknown}, + {"a scale, a symbol", scales, Value{Kind: ValueSymbol}, AdmitsYes}, + } { + assert.Equal(t, tc.want, intersectionAnswer(tc.bounds, &tc.value, 0, nil).admission, tc.name) + } +} + +// TestNumericOrder_OrdersNoValueBesideANumberAnInfinityOrNaN pins numericOrder's +// answers: a number by its decimal, each infinity past every limit on its side, +// and NaN, any other kind and a kind no Value holds ordered against none. +func TestNumericOrder_OrdersNoValueBesideANumberAnInfinityOrNaN(t *testing.T) { + t.Parallel() + two, err := ParseDecimal("2") + require.NoError(t, err) + three, err := ParseDecimal("3") + require.NoError(t, err) + for _, tc := range []struct { + kind ValueKind + order int + ordered bool + }{ + {ValueNumber, -1, true}, {ValueInfinity, 1, true}, {ValueNegativeInfinity, -1, true}, + {ValueNaN, 0, false}, {ValueString, 0, false}, {ValueKind("unheard-of"), 0, false}, + } { + order, ordered := numericOrder(tc.kind, two, three) + assert.Equal(t, tc.order, order, "%s", tc.kind) + assert.Equal(t, tc.ordered, ordered, "%s", tc.kind) + } +} + +// membersByScan is the comparison of value with each member in turn that +// enumMembers replaces, kept as the oracle it is held to. +func membersByScan(members []EnumMember, value *Value, depth int) admissionAnswer { + member := refused() + for i := range members { + switch sameValueAnswer(&members[i].Value, value, depth).admission { + case AdmitsYes: + return admitted() + case AdmitsUnknown: + member = undecided() + case AdmitsNo: + } + } + return member +} + +// nestedList is a list holding one number levels lists down: the number at +// levels nesting. +func nestedList(levels int) Value { + value := Value{Kind: ValueNumber, Number: "1"} + for range levels { + value = Value{Kind: ValueList, List: []Value{value}} + } + return value +} + +// TestEnumMembers_AnswerAsEachMemberComparedInTurn holds a lookup among an +// enum's members to the comparison with each that it replaces, over every set +// of at most three of a pool of values of each kind, a kind no Value holds, +// numbers spelled alike and apart and lists nested to either side of +// maxAdmitsDepth among them, each judged at depths either side of it. +func TestEnumMembers_AnswerAsEachMemberComparedInTurn(t *testing.T) { + t.Parallel() + pool := []Value{ + {Kind: ValueNull}, {Kind: ValueBool, Bool: true}, {Kind: ValueBool}, {Kind: ValueString, String: "1"}, + {Kind: ValueNumber, Number: "1"}, {Kind: ValueNumber, Number: "1.0"}, {Kind: ValueNumber, Number: "2"}, + {Kind: ValueNumber, Number: "1p4"}, {Kind: ValueList}, nestedList(1), nestedList(2), + nestedList(maxAdmitsDepth - 1), nestedList(maxAdmitsDepth + 1), + {Kind: ValueObject, Object: []Field{{Name: "a", Value: Value{Kind: ValueNumber, Number: "1e0"}}}}, + {Kind: ValueList, List: []Value{{Kind: ValueBytes, Bytes: []byte("b")}}}, + {Kind: ValueBytes, Bytes: []byte("1")}, {Kind: ValueSymbol, String: "1"}, {Kind: ValueInfinity}, {Kind: ValueNaN}, + {Kind: ValueKind("unheard-of")}, + } + var sets [][]EnumMember + for i := -1; i < len(pool); i++ { + for j := i; j < len(pool); j++ { + for k := j; k < len(pool); k++ { + var set []EnumMember + for _, at := range []int{i, j, k} { + if at >= 0 { + set = append(set, EnumMember{Value: pool[at]}) + } + } + sets = append(sets, set) + } + } + } + compared := 0 + for _, set := range sets { + members := readEnumMembers(set) + for v := range pool { + for _, depth := range []int{0, 1, 2, maxAdmitsDepth - 1, maxAdmitsDepth, maxAdmitsDepth + 1} { + want := membersByScan(set, &pool[v], depth) + if got := members.judge(&pool[v], depth); got != want { + t.Fatalf("members %v, value %v at depth %d: lookup %v, scan %v", set, pool[v], depth, got.admission, want.admission) + } + compared++ + } + } + } + require.Positive(t, compared) +} + +// TestLacksOwnRequired_AnswersAsTheFlatteningRequires holds a model composing +// nothing, its members read alone, to its flattening's required members, over +// objects holding each member and none: a property each declaration requires, +// one redeclared and required by one declaration of it, and names Requires +// lists, declared and not. +func TestLacksOwnRequired_AnswersAsTheFlatteningRequires(t *testing.T) { + t.Parallel() + property := func(wire string, required bool) Property { + return Property{ID: PropertyID("property/m/" + wire), WireName: wire, Required: required, + Type: TypeRef{Target: PrimitiveTypeID(PrimitiveString)}} + } + holding := func(names ...string) Value { + object := Value{Kind: ValueObject} + for _, name := range names { + object.Object = append(object.Object, Field{Name: name, Value: Value{Kind: ValueNull}}) + } + return object + } + objects := []Value{holding(), holding("a"), holding("b"), holding("z"), holding("a", "z")} + for _, model := range []*Model{ + {ID: "type/m"}, + {ID: "type/m", Properties: []Property{property("a", true), property("b", false)}}, + {ID: "type/m", Properties: []Property{property("a", false), property("a", true)}}, + {ID: "type/m", Properties: []Property{property("a", false)}, Requires: []string{"a", "z"}}, + } { + types := TypeRegistry{model.ID: model} + reader := NewValueAdmissionReader(types.Lookup, NewAliasChainIndex(types.Lookup), nil) + required := reader.modelFactsOf(model.ID).required + for i := range objects { + want := requiredAnswer(required, &objectMembers{value: &objects[i]}).admission == AdmitsNo + assert.Equal(t, want, lacksOwnRequired(model, &objectMembers{value: &objects[i]}), "%+v over %+v", model, objects[i]) + } + } +} diff --git a/ir/admission_kinds_test.go b/ir/admission_kinds_test.go new file mode 100644 index 000000000..eb13e9d6c --- /dev/null +++ b/ir/admission_kinds_test.go @@ -0,0 +1,326 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// listValueOf is a list value holding values. +func listValueOf(values ...ir.Value) ir.Value { return ir.Value{Kind: ir.ValueList, List: values} } + +// admissionRow is one value judged against one reference. +type admissionRow struct { + name string + ref ir.TypeRef + value ir.Value + want ir.Admission +} + +// assertAdmissions judges each row with a reader over registry and no source +// format. +func assertAdmissions(t *testing.T, registry ir.TypeRegistry, rows []admissionRow) { + t.Helper() + reader := readerOver(registry, nil) + for _, row := range rows { + assert.Equal(t, row.want, reader.Admits(row.ref, row.value), "%s", row.name) + } +} + +// TestValueAdmissionReader_JudgesEachKindOfContainer pins a list, a tuple and +// a map by their elements, members and keys, each held to its bounds: an +// element or a member its type refuses refuses the value, a tuple refuses an +// element past its positions where it has no rest, and a map judges each key +// against its key type. +func TestValueAdmissionReader_JudgesEachKindOfContainer(t *testing.T) { + t.Parallel() + integer, text := primitiveRef(ir.PrimitiveInteger), primitiveRef(ir.PrimitiveString) + registry := admissionTypes( + &ir.List{ID: "type/list", ElementType: integer, + Constraints: &ir.Constraints{MaxItems: new(int64(2)), UniqueItems: true}}, + &ir.Tuple{ID: "type/pair", ElementTypes: []ir.TypeRef{integer, text}}, + &ir.Tuple{ID: "type/headed", ElementTypes: []ir.TypeRef{text}, Rest: &integer}, + &ir.MapT{ID: "type/map", Value: integer, Constraints: &ir.Constraints{MinProperties: new(int64(1))}}, + &ir.MapT{ID: "type/keyed", Key: new(refTo("type/shortKey")), Value: integer}, + aliasOf("type/shortKey", text, &ir.Constraints{MaxLength: new(int64(2))}), + ) + assertAdmissions(t, registry, []admissionRow{ + {"a list of integers", refTo("type/list"), listValueOf(numberValue("1"), numberValue("2")), ir.AdmitsYes}, + {"a list holding a string", refTo("type/list"), listValueOf(textValue("x")), ir.AdmitsNo}, + {"a list past its maximum", refTo("type/list"), listValueOf(numberValue("1"), numberValue("2"), numberValue("3")), ir.AdmitsNo}, + {"a list repeating a value", refTo("type/list"), listValueOf(numberValue("1"), numberValue("1.0")), ir.AdmitsNo}, + {"no list at all", refTo("type/list"), numberValue("1"), ir.AdmitsNo}, + {"a pair", refTo("type/pair"), listValueOf(numberValue("1"), textValue("x")), ir.AdmitsYes}, + {"a pair with an element past its positions", refTo("type/pair"), listValueOf(numberValue("1"), textValue("x"), numberValue("2")), ir.AdmitsNo}, + {"a pair out of order", refTo("type/pair"), listValueOf(textValue("x"), numberValue("1")), ir.AdmitsNo}, + {"no tuple at all", refTo("type/pair"), textValue("x"), ir.AdmitsNo}, + {"a head and its rest", refTo("type/headed"), listValueOf(textValue("x"), numberValue("1"), numberValue("2")), ir.AdmitsYes}, + {"a map of integers", refTo("type/map"), objectOf("a", numberValue("1")), ir.AdmitsYes}, + {"a map below its minimum", refTo("type/map"), objectOf(), ir.AdmitsNo}, + {"a map holding a string", refTo("type/map"), objectOf("a", textValue("x")), ir.AdmitsNo}, + {"no map at all", refTo("type/map"), listValueOf(), ir.AdmitsNo}, + {"a key its key type admits", refTo("type/keyed"), objectOf("ab", numberValue("1")), ir.AdmitsYes}, + {"a key its key type refuses", refTo("type/keyed"), objectOf("abc", numberValue("1")), ir.AdmitsNo}, + }) +} + +// TestValueAdmissionReader_JudgesEnumsAndLiterals pins a value set: a closed +// enum admits a listed member, one magnitude spelled two ways among them, and +// refuses any other; an open one judges another by its value kind; both hold +// a value to their bounds; a flags enum may combine its members, so another +// value is unknown; and a literal admits its value alone. +func TestValueAdmissionReader_JudgesEnumsAndLiterals(t *testing.T) { + t.Parallel() + members := []ir.EnumMember{{Value: numberValue("1")}, {Value: numberValue("20")}} + registry := admissionTypes( + &ir.Enum{ID: "type/closed", ValueType: ir.PrimitiveInteger, Closed: true, Members: members, + Constraints: &ir.Constraints{Max: new(ir.BigVal("10"))}}, + &ir.Enum{ID: "type/open", ValueType: ir.PrimitiveInteger, Members: members}, + &ir.Enum{ID: "type/flags", ValueType: ir.PrimitiveInteger, Closed: true, Flags: true, Members: members}, + &ir.Enum{ID: "type/symbols", ValueType: ir.PrimitiveString, Closed: true, + Members: []ir.EnumMember{{Value: ir.Value{Kind: ir.ValueSymbol, String: "ok"}}}}, + &ir.Literal{ID: "type/literal", Value: objectOf("a", listValueOf(numberValue("1"), nullValue(), boolValue(true)))}, + ) + assertAdmissions(t, registry, []admissionRow{ + {"a listed member", refTo("type/closed"), numberValue("1.0"), ir.AdmitsYes}, + {"a listed member past the bound", refTo("type/closed"), numberValue("20"), ir.AdmitsNo}, + {"a value the closed enum does not list", refTo("type/closed"), numberValue("2"), ir.AdmitsNo}, + {"a value the open enum's kind admits", refTo("type/open"), numberValue("2"), ir.AdmitsYes}, + {"a value the open enum's kind refuses", refTo("type/open"), textValue("2"), ir.AdmitsNo}, + {"a value a flags enum might combine", refTo("type/flags"), numberValue("21"), ir.AdmitsUnknown}, + {"a member no JSON value spells", refTo("type/symbols"), textValue("ok"), ir.AdmitsUnknown}, + {"the literal's value, its members in another spelling", refTo("type/literal"), + objectOf("a", listValueOf(numberValue("1e0"), nullValue(), boolValue(true))), ir.AdmitsYes}, + {"the literal's value but for a member", refTo("type/literal"), + objectOf("a", listValueOf(numberValue("1"), nullValue(), boolValue(false))), ir.AdmitsNo}, + {"another value", refTo("type/literal"), objectOf("a", listValueOf()), ir.AdmitsNo}, + {"a value JSON does not spell", refTo("type/literal"), ir.Value{Kind: ir.ValueBytes, Bytes: []byte("x")}, ir.AdmitsUnknown}, + }) +} + +// TestValueAdmissionReader_JudgesEveryKeywordByItsKind pins each keyword on +// the value it bounds and on one it does not: a number's bounds and step, a +// precision ir does not read, a length on text and on bytes, a member count, a +// keyword of another kind admitting, and a value of no kind ir declares +// admitted by bounds and refused by every type. +func TestValueAdmissionReader_JudgesEveryKeywordByItsKind(t *testing.T) { + t.Parallel() + number := primitiveRef(ir.PrimitiveNumber) + registry := admissionTypes( + &ir.Primitive{ID: ir.PrimitiveTypeID(ir.PrimitiveNumber), PrimitiveKind: ir.PrimitiveNumber}, + &ir.Primitive{ID: ir.PrimitiveTypeID(ir.PrimitiveBytes), PrimitiveKind: ir.PrimitiveBytes}, + aliasOf("type/range", number, &ir.Constraints{ExclusiveMin: new(ir.BigVal("0")), ExclusiveMax: new(ir.BigVal("10")), MultipleOf: new(ir.BigVal("0.5"))}), + aliasOf("type/unreadBound", number, &ir.Constraints{Min: new(ir.BigVal("1p4"))}), + aliasOf("type/unreadStep", number, &ir.Constraints{MultipleOf: new(ir.BigVal("1p4"))}), + aliasOf("type/digits", number, &ir.Constraints{Precision: new(int64(3))}), + aliasOf("type/octets", primitiveRef(ir.PrimitiveBytes), &ir.Constraints{MaxLength: new(int64(1))}), + aliasOf("type/anyBounded", primitiveRef(ir.PrimitiveAny), &ir.Constraints{MaxLength: new(int64(1)), MaxProperties: new(int64(0))}), + ) + assertAdmissions(t, registry, []admissionRow{ + {"inside the range on a step", refTo("type/range"), numberValue("2.5"), ir.AdmitsYes}, + {"at the exclusive minimum", refTo("type/range"), numberValue("0"), ir.AdmitsNo}, + {"at the exclusive maximum", refTo("type/range"), numberValue("10"), ir.AdmitsNo}, + {"off the step", refTo("type/range"), numberValue("2.25"), ir.AdmitsNo}, + {"a number no Decimal holds", refTo("type/range"), numberValue("1p4"), ir.AdmitsNo}, + {"a bound no Decimal holds", refTo("type/unreadBound"), numberValue("2"), ir.AdmitsUnknown}, + {"a step no Decimal holds", refTo("type/unreadStep"), numberValue("2"), ir.AdmitsUnknown}, + {"a precision ir does not read", refTo("type/digits"), numberValue("2"), ir.AdmitsUnknown}, + {"bytes ir holds no judge of", refTo("type/octets"), ir.Value{Kind: ir.ValueBytes, Bytes: []byte("ab")}, ir.AdmitsNo}, + {"bytes within their length, of a kind with no judge", refTo("type/octets"), ir.Value{Kind: ir.ValueBytes, Bytes: []byte("a")}, ir.AdmitsUnknown}, + {"a member count on an object", refTo("type/anyBounded"), objectOf("a", nullValue()), ir.AdmitsNo}, + {"a length on a number, which it does not bound", refTo("type/anyBounded"), numberValue("123"), ir.AdmitsYes}, + {"a value of no kind ir declares", refTo("type/anyBounded"), ir.Value{Kind: "unknown"}, ir.AdmitsYes}, + {"that value against a primitive", primitiveRef(ir.PrimitiveInteger), ir.Value{Kind: "unknown"}, ir.AdmitsNo}, + }) +} + +// TestValueAdmissionReader_JudgesWhatACompositionKeeps pins the facts of a +// composition beside its models' own: an alias between two models holds the +// object to its bounds, a member the composing model redeclares is admitted by +// the composed declaration too, a declaration's encoding and a model's kept +// no_ir_home entry answer unknown with no source format to ask, a catch-all +// of patterns alone in a composition closed after it might evaluate a member, +// and a closure of no mode ir declares decides nothing. +func TestValueAdmissionReader_JudgesWhatACompositionKeeps(t *testing.T) { + t.Parallel() + integer, text := primitiveRef(ir.PrimitiveInteger), primitiveRef(ir.PrimitiveString) + encoded := propertyOf("type/Encoded", "at", text, false) + encoded.Encoding = &ir.Encoding{Name: "x-unread"} + registry := admissionTypes( + &ir.Model{ID: "type/Small"}, + &ir.Scalar{ID: "type/toSmall", Base: new(refTo("type/Small")), + Constraints: &ir.Constraints{MaxProperties: new(int64(1))}}, + &ir.Model{ID: "type/Via", Base: new(refTo("type/toSmall"))}, + &ir.Model{ID: "type/Integral", Properties: []ir.Property{propertyOf("type/Integral", "a", integer, false)}}, + &ir.Model{ID: "type/Redeclared", Base: new(refTo("type/Integral")), + Properties: []ir.Property{propertyOf("type/Redeclared", "a", primitiveRef(ir.PrimitiveAny), false)}}, + &ir.Model{ID: "type/Encoded", Properties: []ir.Property{encoded}}, + &ir.Model{ID: "type/Noted", Unmodeled: ir.Unmodeled{ + "openapi:x": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue(`1`)}, + "x-note": {Reason: ir.ReasonVendorExtension, Value: ir.RawValue(`1`)}, + }}, + &ir.Model{ID: "type/Patterns", Additional: ir.AdditionalClosed, + AdditionalProperties: &ir.AdditionalProperties{Patterns: []ir.PatternProperties{{Pattern: "^x", Value: integer}}}}, + &ir.Model{ID: "type/AfterPatterns", Additional: ir.AdditionalClosedAfterComposition, + Base: new(refTo("type/Patterns"))}, + &ir.Model{ID: "type/Odd", Additional: "odd"}, + ) + assertAdmissions(t, registry, []admissionRow{ + {"within the bound an alias between models writes", refTo("type/Via"), objectOf("a", numberValue("1")), ir.AdmitsYes}, + {"past it", refTo("type/Via"), objectOf("a", numberValue("1"), "b", numberValue("2")), ir.AdmitsNo}, + {"a member both declarations admit", refTo("type/Redeclared"), objectOf("a", numberValue("1")), ir.AdmitsYes}, + {"one the composed declaration refuses", refTo("type/Redeclared"), objectOf("a", textValue("x")), ir.AdmitsNo}, + {"a member under an encoding no source format reads", refTo("type/Encoded"), objectOf("at", textValue("x")), ir.AdmitsUnknown}, + {"an object under a kept entry no source format reads", refTo("type/Noted"), objectOf(), ir.AdmitsUnknown}, + {"a member patterns alone might evaluate", refTo("type/AfterPatterns"), objectOf("y", numberValue("1")), ir.AdmitsUnknown}, + {"a member a closure of no declared mode governs", refTo("type/Odd"), objectOf("y", numberValue("1")), ir.AdmitsUnknown}, + }) +} + +// TestValueAdmissionReader_AnswersUnknownWhereNoTypeIsRead pins the types ir +// reads nothing of, and the references it cannot follow: an opaque scalar, an +// external type, a primitive of no kind ir declares, a reference naming no +// type, a cyclic alias chain, and a node the reader's lookup does not hold +// though its index does; and the top type and a variant keeping an entry +// beside its type. +func TestValueAdmissionReader_AnswersUnknownWhereNoTypeIsRead(t *testing.T) { + t.Parallel() + text := primitiveRef(ir.PrimitiveString) + registry := admissionTypes( + &ir.Scalar{ID: "type/opaque"}, + &ir.External{ID: "type/external", Identity: "erlang:pid"}, + &ir.Primitive{ID: "type/primitive/nope", PrimitiveKind: "nope"}, + aliasOf("type/loopA", refTo("type/loopB"), nil), aliasOf("type/loopB", refTo("type/loopA"), nil), + &ir.Any{ID: "type/any"}, + &ir.Union{ID: "type/keptVariant", Closed: true, Variants: []ir.Variant{{Type: text, + Unmodeled: ir.Unmodeled{"openapi:not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{}`)}}}}}, + aliasOf("type/twoPatterns", refTo("type/patternA"), &ir.Constraints{Pattern: "^b"}), + aliasOf("type/patternA", primitiveRef(ir.PrimitiveAny), &ir.Constraints{Pattern: "^a", MaxLength: new(int64(1))}), + &ir.List{ID: "type/encodedList", ElementType: text, Encoding: &ir.Encoding{Name: "packed"}, + Constraints: &ir.Constraints{UniqueItems: true}}, + aliasOf("type/patternedShort", text, &ir.Constraints{Pattern: "^a", MaxLength: new(int64(1))}), + &ir.Literal{ID: "type/deep", Value: nestedList(70)}, + ) + assertAdmissions(t, registry, []admissionRow{ + {"an opaque scalar", refTo("type/opaque"), textValue("x"), ir.AdmitsUnknown}, + {"an external type", refTo("type/external"), textValue("x"), ir.AdmitsUnknown}, + {"a primitive of no kind ir declares", refTo("type/primitive/nope"), textValue("x"), ir.AdmitsUnknown}, + {"a reference naming no type", refTo("type/ghost"), textValue("x"), ir.AdmitsUnknown}, + {"a cyclic alias chain", refTo("type/loopA"), textValue("x"), ir.AdmitsUnknown}, + {"null against the top type's own node", refTo("type/any"), nullValue(), ir.AdmitsYes}, + {"a value against it", refTo("type/any"), textValue("x"), ir.AdmitsYes}, + {"a variant keeping a validation-only entry", refTo("type/keptVariant"), textValue("x"), ir.AdmitsUnknown}, + {"a text two patterns bound", refTo("type/twoPatterns"), textValue("a"), ir.AdmitsUnknown}, + {"a text past a length beside them", refTo("type/twoPatterns"), textValue("ab"), ir.AdmitsNo}, + {"a number two patterns do not bound", refTo("type/twoPatterns"), numberValue("1"), ir.AdmitsYes}, + {"a list under an encoding no source format reads", refTo("type/encodedList"), listValueOf(textValue("x")), ir.AdmitsUnknown}, + {"a list whose uniqueness cannot be read, holding a symbol its element type refuses", refTo("type/encodedList"), + listValueOf(textValue("x"), ir.Value{Kind: ir.ValueSymbol, String: "x"}), ir.AdmitsNo}, + {"a text past a length beside a pattern", refTo("type/patternedShort"), textValue("ab"), ir.AdmitsNo}, + {"a literal nested past the bound", refTo("type/deep"), nestedList(70), ir.AdmitsUnknown}, + {"a literal against a list holding a value JSON does not spell", refTo("type/deep"), + listValueOf(ir.Value{Kind: ir.ValueBytes}), ir.AdmitsUnknown}, + {"a literal against an object holding one", refTo("type/deep"), + objectOf("a", ir.Value{Kind: ir.ValueBytes}), ir.AdmitsUnknown}, + {"a literal against a value of no kind ir declares", refTo("type/deep"), ir.Value{Kind: "unknown"}, ir.AdmitsUnknown}, + }) + + lookup := admissionLookupOf(registry, nil) + unheld := ir.NewValueAdmissionReader(func(ir.TypeID) (ir.TypeDef, bool) { return nil, false }, ir.NewAliasChainIndex(lookup), nil) + assert.Equal(t, ir.AdmitsUnknown, unheld.Admits(text, textValue("x")), "a node the reader's own lookup does not hold") +} + +// countingSourceFormat answers yes for every encoding, counting how often it is +// asked. +type countingSourceFormat struct{ asked *int } + +// AdmitsUnderEncoding is ir.SourceFormatAdmissions.AdmitsUnderEncoding. +func (sourceFormat countingSourceFormat) AdmitsUnderEncoding(*ir.Encoding, ir.Value) ir.Admission { + *sourceFormat.asked++ + return ir.AdmitsYes +} + +// AdmitsUnderUnmodeledEntry is ir.SourceFormatAdmissions.AdmitsUnderUnmodeledEntry. +func (sourceFormat countingSourceFormat) AdmitsUnderUnmodeledEntry(string, ir.UnmodeledEntry, ir.Value) ir.Admission { + return ir.AdmitsYes +} + +// TestValueAdmissionReader_JudgesEachTypeOncePerValueNode pins the memo of a +// closed component's answers by what is judged rather than read: nested +// unions whose every variant reaches one encoded leaf ask the source format of +// it once for each of the two references naming it, at every depth, where +// judging each path again doubles the asks at every level. +func TestValueAdmissionReader_JudgesEachTypeOncePerValueNode(t *testing.T) { + t.Parallel() + var asks [3]int + for i, d := range []int{4, 8, 16} { + registry := nestedUnionTypes(d) + leaf, ok := registry[ir.TypeID(fmt.Sprintf("type/L%d", d))].(*ir.Scalar) + require.True(t, ok) + leaf.Encoding = &ir.Encoding{Name: "x-leaf"} + value := textValue("leaf") + for range d { + value = objectOf("x", value, "A", textValue("a")) + } + reader := readerOver(registry, countingSourceFormat{asked: &asks[i]}) + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/L0"), value)) + } + assert.Equal(t, [3]int{2, 2, 2}, asks, "the leaf is one value node, its type judged once beside each reference") +} + +// TestValueAdmissionReader_AsksTheSourceFormatOnlyOfAnEncodingThatEncodes pins +// that an encoding naming no scheme, one stating only a media type, says what +// the value holds and not how it is written, so a scalar or a list under it asks +// the source format nothing, and one naming a scheme asks it once. +func TestValueAdmissionReader_AsksTheSourceFormatOnlyOfAnEncodingThatEncodes(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + encoding *ir.Encoding + asks int + }{ + {"a media type alone", &ir.Encoding{MediaType: "application/json"}, 0}, + {"a scheme", &ir.Encoding{Name: "base64", MediaType: "application/json"}, 1}, + } { + registry := admissionTypes() + registry["type/S"] = &ir.Scalar{ID: "type/S", Base: new(primitiveRef(ir.PrimitiveString)), Encoding: tc.encoding} + registry["type/L"] = &ir.List{ID: "type/L", ElementType: primitiveRef(ir.PrimitiveString), Encoding: tc.encoding} + for id, value := range map[ir.TypeID]ir.Value{"type/S": textValue("x"), "type/L": listValueOf()} { + var asked int + reader := readerOver(registry, countingSourceFormat{asked: &asked}) + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo(id), value), "%s: %s", tc.name, id) + assert.Equal(t, tc.asks, asked, "%s: %s", tc.name, id) + } + } +} + +// TestValueAdmissionReader_AMemberOfACycleAnswersUnknownWhateverItsOwnAnswer +// pins that a type reaching itself answers unknown, though what it decides of +// the value itself is no: a union naming itself as a variant, held to a +// length the text breaks, is no more refused than a pair of unions naming each +// other. +func TestValueAdmissionReader_AMemberOfACycleAnswersUnknownWhateverItsOwnAnswer(t *testing.T) { + t.Parallel() + registry := admissionTypes() + short := &ir.Union{ID: "type/Self", Closed: true, Constraints: &ir.Constraints{MinLength: new(int64(5))}, + Variants: []ir.Variant{{Type: refTo("type/Self")}}} + registry[short.ID] = short + for _, id := range []ir.TypeID{"type/Left", "type/Right"} { + other := ir.TypeID("type/Right") + if id == "type/Right" { + other = "type/Left" + } + registry[id] = &ir.Union{ID: id, Closed: true, Constraints: &ir.Constraints{MinLength: new(int64(5))}, + Variants: []ir.Variant{{Type: refTo(other)}}} + } + for _, id := range []ir.TypeID{"type/Self", "type/Left"} { + assert.Equal(t, ir.AdmitsUnknown, readerOver(registry, nil).Admits(refTo(id), textValue("ab")), id) + } +} diff --git a/ir/admission_models.go b/ir/admission_models.go new file mode 100644 index 000000000..43706e83a --- /dev/null +++ b/ir/admission_models.go @@ -0,0 +1,234 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "slices" + +// modelFacts is what a [ValueAdmissionReader] reads of a model's composition, +// once for its life. +type modelFacts struct { + flat Flattening + declared map[string]*FlatProperty + // required lists the members the flattening requires, a name only a + // Requires lists among them. + required []string + // composition holds the model, first, and every model it composes along + // Base and Mixins through alias scalars, each once. + composition []TypeID + // aliases holds what each alias chain between them adds. + aliases []*aliasChainFacts + // holdsUnion reports that the composition names a union, whose variants + // may evaluate a member no model of it declares. + holdsUnion bool + // holdsMap reports that the composition names a map, whose catch-all + // evaluates every member, the map judging its value. + holdsMap bool +} + +// modelFactsOf returns the facts of the model at id, read once for the +// reader's life. +func (reader *ValueAdmissionReader) modelFactsOf(id TypeID) *modelFacts { + if facts, read := reader.models[id]; read { + return facts + } + facts := &modelFacts{flat: flattenedPropertiesOver(reader.lookup, reader.aliasChains, id), declared: map[string]*FlatProperty{}} + for i := range facts.flat.Properties { + member := &facts.flat.Properties[i] + facts.declared[member.Property.EffectiveWireName()] = member + if member.Required { + facts.required = append(facts.required, member.Property.EffectiveWireName()) + } + } + facts.required = append(facts.required, facts.flat.Undeclared...) + seen := map[TypeID]bool{id: true} + for queue := []TypeID{id}; len(queue) > 0; queue = queue[1:] { + facts.composition = append(facts.composition, queue[0]) + model, _ := reader.nodeOf(queue[0]).(*Model) + for _, part := range ComposedOf(model) { + chain, held := reader.chains.AnswerFor(part) + end, _ := reader.aliasChains.End(part) + if held && end != part { + facts.aliases = append(facts.aliases, chain) + } + switch reader.nodeOf(end).(type) { + case *Model: + if !seen[end] { + seen[end] = true + queue = append(queue, end) + } + case *Union: + facts.holdsUnion = true + case *MapT: + facts.holdsMap = true + default: + } + } + } + reader.models[id] = facts + return facts +} + +// modelAnswer is what the model at id decides of value itself, judged as JSON +// Schema judges its composition, and its edges, the composition entries naming +// no model, each of which must admit value too. +func (call *admissionCall) modelAnswer(id TypeID, value *Value, depth int) (admissionAnswer, []admissionEdge) { + if value.Kind != ValueObject { + return kindRefused(call.reader.nodeOf(id)), nil + } + reader := call.reader + facts := reader.modelFactsOf(id) + judged := constraintsAnswer(reader.propertyCounts.Of(id), value, depth, reader.patterns) + for _, model := range facts.composition { + judged = judged.and(keptEntryAnswer(reader.nodeOf(model).Common().Unmodeled, reader.sourceFormats, value)) + } + for _, chain := range facts.aliases { + judged = judged.and(chain.judge(reader, value, depth)) + } + judged = judged.and(requiredAnswer(facts.required, &objectMembers{value: value})) + for i := range value.Object { + judged = judged.and(call.memberAnswer(facts, &value.Object[i], depth)) + } + edges := make([]admissionEdge, len(facts.flat.Unflattened)) + for i, target := range facts.flat.Unflattened { + edges[i] = admissionEdge{ref: TypeRef{Target: target}} + } + return judged, edges +} + +// requiredAnswer refuses an object, whose members are members, missing one +// of required. +func requiredAnswer(required []string, members *objectMembers) admissionAnswer { + for _, name := range required { + if !members.holds(name) { + return refused() + } + } + return admitted() +} + +// smallObject is the most members an objectMembers scans for a name before +// it reads them into a set. +const smallObject = 8 + +// objectMembers answers whether an object value holds a member of a name: a +// small object by a scan of its members, a larger one by a set of their names +// read at its first question. +type objectMembers struct { + value *Value + names map[string]bool +} + +// holds reports whether the object holds a member named name. +func (members *objectMembers) holds(name string) bool { + if len(members.value.Object) <= smallObject { + return slices.ContainsFunc(members.value.Object, func(field Field) bool { return field.Name == name }) + } + if members.names == nil { + members.names = make(map[string]bool, len(members.value.Object)) + for i := range members.value.Object { + members.names[members.value.Object[i].Name] = true + } + } + return members.names[name] +} + +// memberAnswer judges one member of an object a model judges: against every +// declaration of it, and against the closure of each model of the composition +// whose own flattening declares none. +func (call *admissionCall) memberAnswer(facts *modelFacts, field *Field, depth int) admissionAnswer { + judged := admitted() + if member, declared := facts.declared[field.Name]; declared { + judged = judged.and(call.declarationAnswer(member.Property, &field.Value, depth)) + for _, overridden := range member.Overridden { + judged = judged.and(call.declarationAnswer(overridden.Property, &field.Value, depth)) + } + } + for _, model := range facts.composition { + own := call.reader.modelFactsOf(model) + if _, declared := own.declared[field.Name]; !declared { + judged = judged.and(call.closureAnswer(model, own, field, depth)) + } + } + return judged +} + +// declarationAnswer judges a member's value against one declaration of it: its +// type, and its own bounds, encoding and kept Unmodeled entries. +func (call *admissionCall) declarationAnswer(property *Property, value *Value, depth int) admissionAnswer { + sourceFormats := call.reader.sourceFormats + judged := call.judgeRef(property.Type, value, depth+1) + judged = judged.and(constraintsAnswer(property.Constraints, value, depth+1, call.reader.patterns)) + if property.Encoding != nil { + judged = judged.and(askEncoding(sourceFormats, property.Encoding, value)) + } + return judged.and(keptEntryAnswer(property.Unmodeled, sourceFormats, value)) +} + +// closureAnswer judges a member the model at id's own flattening declares +// none for by that model's closure. A pattern catch-all answers unknown, as a +// pattern might match the name. +func (call *admissionCall) closureAnswer(id TypeID, own *modelFacts, field *Field, depth int) admissionAnswer { + model, _ := call.reader.nodeOf(id).(*Model) + catchAll := model.AdditionalProperties + switch { + case catchAll != nil && len(catchAll.Patterns) > 0: + return undecided() + case catchAll != nil && catchAll.Value != nil: + return call.keyAnswer(catchAll.Key, field.Name, depth).and(call.judgeRef(*catchAll.Value, &field.Value, depth+1)) + } + switch model.Additional { + case AdditionalUnspecified: + return admitted() + case AdditionalClosed: + return refused() + case AdditionalClosedAfterComposition: + return call.evaluatedAnswer(own) + default: + return undecided() + } +} + +// evaluatedAnswer is whether a member a model closed after composition +// declares none for is one its own composition evaluates. A catch-all with a +// value or a map evaluates it and judges it itself, so the answer is yes; +// patterns alone, an entry ir cannot read or a union's variants may, so it is +// unknown. +func (call *admissionCall) evaluatedAnswer(own *modelFacts) admissionAnswer { + if own.holdsMap { + return admitted() + } + judged := refused() + for _, id := range own.composition { + model, _ := call.reader.nodeOf(id).(*Model) + if keepsUnreadAssertion(model.Unmodeled) { + judged = undecided() + } + switch catchAll := model.AdditionalProperties; { + case catchAll == nil: + case catchAll.Value != nil: + return admitted() + default: + judged = undecided() + } + } + if own.holdsUnion { + return undecided() + } + if judged.admission == AdmitsNo { + judged.unevaluatedOnly = true + } + return judged +} + +// keepsUnreadAssertion reports whether unmodeled keeps an Unmodeled entry +// validating what the IR does not model, or a degraded one, which ir reads no +// further. +func keepsUnreadAssertion(unmodeled Unmodeled) bool { + for _, entry := range unmodeled { + if entry.Reason == ReasonValidationOnly || entry.Reason == ReasonDegradedLowering { + return true + } + } + return false +} diff --git a/ir/admission_nodes.go b/ir/admission_nodes.go new file mode 100644 index 000000000..4075a1467 --- /dev/null +++ b/ir/admission_nodes.go @@ -0,0 +1,232 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "maps" + "slices" +) + +// aliasChainFacts is what an alias chain adds to the type it ends on, nearest +// alias first. +type aliasChainFacts struct { + bounds ConstraintIntersection + encodings *encodingLink + entries *keptEntryLink + // unreadAssertion reports a validation_only or degraded_lowering entry. + unreadAssertion bool + // rewritesWire reports an encoding whose WireType names another type than + // its alias's Base, so a value is in a form the types below do not read. + rewritesWire bool +} + +// encodingLink is one encoding an alias chain keeps, and the ones beyond it. +type encodingLink struct { + encoding *Encoding + next *encodingLink +} + +// keptEntryLink is one no_ir_home Unmodeled entry an alias chain keeps, and the +// ones beyond it. +type keptEntryLink struct { + key string + entry UnmodeledEntry + next *keptEntryLink +} + +// addAliasFacts is what an alias chain adds from scalar, given what the chain +// beyond scalar's Base adds: scalar's own facts before those. +func addAliasFacts(scalar *Scalar, next *aliasChainFacts) *aliasChainFacts { + facts := &aliasChainFacts{ + bounds: ConstraintIntersectionOf(scalar.Constraints).Intersect(next.bounds), + encodings: next.encodings, entries: next.entries, + unreadAssertion: next.unreadAssertion, rewritesWire: next.rewritesWire, + } + if scalar.Encoding.Encodes() { + facts.encodings = &encodingLink{encoding: scalar.Encoding, next: facts.encodings} + wire := scalar.Encoding.WireType + facts.rewritesWire = facts.rewritesWire || wire != nil && wire.Target != scalar.Base.Target + } + keys := slices.Sorted(maps.Keys(scalar.Unmodeled)) + for _, key := range slices.Backward(keys) { + switch entry := scalar.Unmodeled[key]; entry.Reason { + case ReasonValidationOnly, ReasonDegradedLowering: + facts.unreadAssertion = true + case ReasonNoIRHome: + facts.entries = &keptEntryLink{key: key, entry: entry, next: facts.entries} + case ReasonVendorExtension, ReasonOutOfScope: + } + } + return facts +} + +// judge is what the facts decide of value as reader judges it. A yes is +// unknown where an alias keeps an entry ir cannot read or an encoding writes +// another type on the wire, as the value is then not one the types below read. +func (facts *aliasChainFacts) judge(reader *ValueAdmissionReader, value *Value, depth int) admissionAnswer { + sourceFormats := reader.sourceFormats + judged := intersectionAnswer(facts.bounds, value, depth, reader.patterns) + for link := facts.encodings; link != nil; link = link.next { + judged = judged.and(askEncoding(sourceFormats, link.encoding, value)) + } + for link := facts.entries; link != nil; link = link.next { + judged = judged.and(askKeptEntry(sourceFormats, link.key, link.entry, value)) + } + if facts.unreadAssertion || facts.rewritesWire { + judged = judged.yesToUnknown() + } + return judged +} + +// localAnswer is what the node at id decides of value itself, and the edges +// to the types judged against the same value node: a union's variants, a +// model's unflattened composition entries. A node the registry does not hold, +// an opaque scalar and an external type decide nothing ir reads. +func (call *admissionCall) localAnswer(id TypeID, node TypeDef, value *Value, depth int) (admissionAnswer, []admissionEdge) { + if node == nil { + return undecided(), nil + } + if _, isModel := node.(*Model); isModel { + return call.modelAnswer(id, value, depth) + } + if judged, leaf := call.reader.leafAnswer(node, value, depth); leaf { + return judged, nil + } + kept := keptEntryAnswer(node.Common().Unmodeled, call.reader.sourceFormats, value) + switch typed := node.(type) { + case *List: + return kept.and(call.listAnswer(typed, value, depth)), nil + case *Tuple: + return kept.and(call.tupleAnswer(typed, value, depth)), nil + case *MapT: + return kept.and(call.mapAnswer(typed, value, depth)), nil + case *Union: + return kept.and(constraintsAnswer(typed.Constraints, value, depth, call.reader.patterns)), call.reader.unionEdges(id, typed) + default: + // An opaque scalar or an external type: no alias chain ends on an + // alias but a cyclic one, which is never judged. + return kept.and(undecided()), nil + } +} + +// leafAnswer is what node decides of value where it is a leaf, a node no +// other type is judged through, and false for any other node. +func (reader *ValueAdmissionReader) leafAnswer(node TypeDef, value *Value, depth int) (admissionAnswer, bool) { + var local admissionAnswer + switch typed := node.(type) { + case *Primitive: + local = primitiveAnswer(typed.PrimitiveKind, value) + case *Any: + local = admitted() + case *Enum: + local = reader.enumAnswer(typed, value, depth) + case *Literal: + local = sameValueAnswer(&typed.Value, value, depth) + default: + return admissionAnswer{}, false + } + return keptEntryAnswer(node.Common().Unmodeled, reader.sourceFormats, value).and(local), true +} + +// primitiveAnswer judges value against a primitive kind as PrimitiveAdmits +// does, null admitted only by the top type. +func primitiveAnswer(kind PrimitiveKind, value *Value) admissionAnswer { + switch { + case kind == PrimitiveAny: + return admitted() + case value.Kind == ValueNull: + return refused() + default: + return admissionAnswer{admission: PrimitiveAdmits(kind, *value)} + } +} + +// enumAnswer judges value against an enum and its bounds. A flags enum may +// combine members, so a value it does not list is unknown, and an open enum +// judges one by its value kind. +func (reader *ValueAdmissionReader) enumAnswer(enum *Enum, value *Value, depth int) admissionAnswer { + bounds := constraintsAnswer(enum.Constraints, value, depth, reader.patterns) + members, read := reader.enums[enum] + if !read { + members = readEnumMembers(enum.Members) + reader.enums[enum] = members + } + member := members.judge(value, depth) + switch { + case member.admission == AdmitsYes: + return bounds + case enum.Flags: + return bounds.and(undecided()) + case enum.Closed: + return bounds.and(member) + default: + return bounds.and(primitiveAnswer(enum.ValueType, value)) + } +} + +// listAnswer judges value against a list. +func (call *admissionCall) listAnswer(list *List, value *Value, depth int) admissionAnswer { + if value.Kind != ValueList { + return kindRefused(list) + } + judged := constraintsAnswer(list.Constraints, value, depth, call.reader.patterns) + if list.Encoding.Encodes() { + judged = judged.and(askEncoding(call.reader.sourceFormats, list.Encoding, value)) + } + for i := range value.List { + judged = judged.and(call.judgeRef(list.ElementType, &value.List[i], depth+1)) + } + return judged +} + +// tupleAnswer judges value against a tuple. +func (call *admissionCall) tupleAnswer(tuple *Tuple, value *Value, depth int) admissionAnswer { + if value.Kind != ValueList { + return kindRefused(tuple) + } + judged := constraintsAnswer(tuple.Constraints, value, depth, call.reader.patterns) + for i := range value.List { + element := tuple.Rest + if i < len(tuple.ElementTypes) { + element = &tuple.ElementTypes[i] + } + if element == nil { + return refused() + } + judged = judged.and(call.judgeRef(*element, &value.List[i], depth+1)) + } + return judged +} + +// mapAnswer judges value against a map. +func (call *admissionCall) mapAnswer(mapType *MapT, value *Value, depth int) admissionAnswer { + if value.Kind != ValueObject { + return kindRefused(mapType) + } + judged := constraintsAnswer(mapType.Constraints, value, depth, call.reader.patterns) + for i := range value.Object { + judged = judged.and(call.keyAnswer(mapType.Key, value.Object[i].Name, depth)) + judged = judged.and(call.judgeRef(mapType.Value, &value.Object[i].Value, depth+1)) + } + return judged +} + +// keyAnswer judges a member's name against the key type key, admitted where +// it is nil, the one spelling of string keys. +func (call *admissionCall) keyAnswer(key *TypeRef, name string, depth int) admissionAnswer { + if key == nil { + return admitted() + } + return call.judgeRef(*key, &Value{Kind: ValueString, String: name}, depth+1) +} + +// kindRefused is a container's or a model's answer on a value of another +// kind: no, but unknown where a heuristic gave the node its shape +// (Provenance.Inferred), since the source may admit values of every kind. +func kindRefused(node TypeDef) admissionAnswer { + if node.Common().Provenance.Inferred != "" { + return undecided() + } + return refused() +} diff --git a/ir/admission_pattern.go b/ir/admission_pattern.go new file mode 100644 index 000000000..be9fb77d2 --- /dev/null +++ b/ir/admission_pattern.go @@ -0,0 +1,384 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "regexp" + "strings" + "unicode/utf8" +) + +// maxPatternWork bounds judging one text against one pattern: the pattern's +// size, each count's operand written out as often as it counts, times the +// text's length plus one, which Go's regexp matches in time proportional to. +// A pattern past it is not compiled, and a judgment past it answers unknown. +const maxPatternWork = 1 << 20 + +// patternMatcher is a pattern as compileReadAlike reads it: its matcher, nil +// where none is compiled, and its size. +type patternMatcher struct { + matcher *regexp.Regexp + size int +} + +// patternMatchers holds each pattern a reader has read, for its life. +type patternMatchers map[string]patternMatcher + +// patternAnswer judges text against an ECMA-262 pattern as a RegExp written +// without flags tests it (docs/ir/values.md#patterns): unknown where the +// pattern lies outside the subset Go's regexp reads alike, text holds a +// character past the Basic Multilingual Plane, or the work passes +// maxPatternWork. A nil matchers compiles the pattern afresh. +func patternAnswer(pattern, text string, matchers patternMatchers) admissionAnswer { + if !basicMultilingual(text) { + return undecided() + } + read := matchers.matcher(pattern) + if read.matcher == nil || read.size > maxPatternWork/(len(text)+1) { + return undecided() + } + return answerOf(read.matcher.MatchString(text)) +} + +// matcher returns what is held of pattern, reading each pattern once for the +// matchers' life. +func (matchers patternMatchers) matcher(pattern string) patternMatcher { + if matchers == nil { + return compileReadAlike(pattern) + } + read, held := matchers[pattern] + if !held { + read = compileReadAlike(pattern) + matchers[pattern] = read + } + return read +} + +// compileReadAlike compiles pattern where scanPattern reads it alike within +// maxPatternWork, and holds no matcher otherwise or where Go's regexp refuses +// it, as it does an unclosed group or a count past 1,000. +func compileReadAlike(pattern string) patternMatcher { + size, alike := scanPattern(pattern) + if !alike || size > maxPatternWork { + return patternMatcher{size: size} + } + matcher, err := regexp.Compile(pattern) + if err != nil { + return patternMatcher{size: size} + } + return patternMatcher{matcher: matcher, size: size} +} + +// basicMultilingual reports whether text is UTF-8 holding no character past +// U+FFFF. +func basicMultilingual(text string) bool { + if !utf8.ValidString(text) { + return false + } + for _, char := range text { + if char > 0xFFFF { + return false + } + } + return true +} + +// patternItem is what a pattern's scan read last, which says whether a +// quantifier may follow it. +type patternItem uint8 + +const ( + // itemNone is the start of the pattern, of a group or of an + // alternative, which holds nothing to repeat. + itemNone patternItem = iota + // itemAtom is a character, a class or a group, which a quantifier may + // repeat. + itemAtom + // itemAssertion is ^, $, \b or \B, which ECMA-262 refuses to repeat and + // Go's regexp repeats. + itemAssertion + // itemRepeated is a quantified atom, which a ? makes lazy. + itemRepeated + // itemLazy is a lazy quantified atom, which nothing more may follow as a + // quantifier. + itemLazy +) + +// patternScan is one scan of a pattern. sizes holds the size read so far, +// counts written out, of the pattern and of each group open in it; lastSize is +// the last item's, which a count repeats; total is the whole. +type patternScan struct { + rest string + sizes []int + lastSize int + total int + last patternItem + alike bool +} + +// scanPattern returns pattern's size, stopping once it passes maxPatternWork, +// and reports whether pattern lies in the subset of ECMA-262, read without +// flags, that Go's regexp reads alike (docs/ir/values.md#patterns). +func scanPattern(pattern string) (size int, alike bool) { + if !basicMultilingual(pattern) { + return 0, false + } + scan := patternScan{rest: pattern, sizes: []int{0}, alike: true} + for scan.alike && scan.rest != "" && scan.total <= maxPatternWork { + scan.step() + } + return scan.total, scan.alike +} + +// step reads the item the scan is at, and marks the pattern not read alike +// where that item is outside the subset. +func (scan *patternScan) step() { + switch scan.rest[0] { + case '\\': + scan.escape() + case '[': + scan.class() + case '(': + scan.openGroup() + case ')': + scan.closeGroup() + case '|': + scan.read(1, itemNone) + case '^', '$': + scan.read(1, itemAssertion) + case '*', '+': + scan.quantifier(1, 0) + case '?': + scan.questionMark() + case '{': + scan.braced() + case '.': + scan.alike = false // ECMA-262's . refuses \r, U+2028 and U+2029 too + default: + _, width := utf8.DecodeRuneInString(scan.rest) + scan.read(width, itemAtom) + } +} + +// read moves past an item width bytes long, adding it to the size of the group +// it is in. +func (scan *patternScan) read(width int, last patternItem) { + scan.rest = scan.rest[width:] + scan.grow(width) + scan.lastSize, scan.last = width, last +} + +// grow adds added to the size of the innermost group open, and to the total. +func (scan *patternScan) grow(added int) { + scan.sizes[len(scan.sizes)-1] += added + scan.total += added +} + +// escape reads an escape outside a class. +func (scan *patternScan) escape() { + if len(scan.rest) < 2 { + scan.alike = false + return + } + switch scan.rest[1] { + case 'd', 'D', 'w', 'W': + scan.read(2, itemAtom) + case 'b', 'B': + scan.read(2, itemAssertion) + default: + if width, ok := characterEscape(scan.rest); ok { + scan.read(width, itemAtom) + return + } + scan.alike = false + } +} + +// openGroup reads a group's opening, ( or (?:. Any other (? is outside the +// subset. +func (scan *patternScan) openGroup() { + width := 1 + if strings.HasPrefix(scan.rest, "(?") { + if !strings.HasPrefix(scan.rest, "(?:") { + scan.alike = false + return + } + width = 3 + } + scan.rest = scan.rest[width:] + scan.sizes = append(scan.sizes, width) + scan.total += width + scan.last = itemNone +} + +// closeGroup reads a group's closing, which some opening must match, the +// group's size, its closing included, adding to the group it is in. +func (scan *patternScan) closeGroup() { + if len(scan.sizes) == 1 { + scan.alike = false + return + } + group := scan.sizes[len(scan.sizes)-1] + 1 + scan.sizes = scan.sizes[:len(scan.sizes)-1] + scan.rest = scan.rest[1:] + scan.sizes[len(scan.sizes)-1] += group + scan.total++ + scan.lastSize, scan.last = group, itemAtom +} + +// quantifier reads a quantifier width bytes long, which must follow an atom, +// as ECMA-262 refuses one anywhere else. copies is how many more times than +// once a count writes the atom out. +func (scan *patternScan) quantifier(width, copies int) { + if scan.last != itemAtom { + scan.alike = false + return + } + scan.rest = scan.rest[width:] + scan.grow(width + copies*scan.lastSize) + scan.last = itemRepeated +} + +// questionMark reads ?, which makes a quantifier it follows lazy and +// quantifies anything else. +func (scan *patternScan) questionMark() { + if scan.last == itemRepeated { + scan.rest = scan.rest[1:] + scan.grow(1) + scan.last = itemLazy + return + } + scan.quantifier(1, 0) +} + +// braced reads a { opening a count, {n}, {n,} or {n,m} with n at most m. Any +// other { is outside the subset: Go's regexp reads {01} as characters and +// ECMA-262 as a count. +func (scan *patternScan) braced() { + closing := strings.IndexByte(scan.rest, '}') + if closing < 0 { + scan.alike = false + return + } + low, high, bounded := strings.Cut(scan.rest[1:closing], ",") + least, okLeast := repeatCount(low) + most, okMost := least, true + switch { + case bounded && high == "": + most = least + 1 // {n,} writes its operand out n times, then repeats it + case bounded: + most, okMost = repeatCount(high) + } + if !okLeast || !okMost || least > most { + scan.alike = false + return + } + scan.quantifier(closing+1, max(most-1, 0)) +} + +// repeatCount reads a quantifier's count: at most four decimal digits with no +// leading zero. +func repeatCount(digits string) (int, bool) { + if digits == "" || len(digits) > 4 || len(digits) > 1 && digits[0] == '0' { + return 0, false + } + count := 0 + for i := range len(digits) { + if digits[i] < '0' || digits[i] > '9' { + return 0, false + } + count = count*10 + int(digits[i]-'0') + } + return count, true +} + +// characterEscape returns the width of the escape text starts with where both +// dialects read it as one character, and false for any other escape, which +// the two read differently or one refuses. +func characterEscape(text string) (width int, ok bool) { + if len(text) < 2 { + return 0, false + } + switch escaped := text[1]; { + case strings.IndexByte(`!"#$%&'()*+,-./:;<=>?@[\]^_`+"`"+`{|}~`, escaped) >= 0: + return 2, true + case strings.IndexByte("tnvfr", escaped) >= 0: + return 2, true + case escaped == 'x' && len(text) >= 4 && isHexDigit(text[2]) && isHexDigit(text[3]): + return 4, true + default: + return 0, false + } +} + +// isHexDigit reports whether digit is a hex digit in either case. +func isHexDigit(digit byte) bool { + return '0' <= digit && digit <= '9' || 'a' <= digit && digit <= 'f' || 'A' <= digit && digit <= 'F' +} + +// class reads a class, [...] or [^...]. An empty class is outside the subset: +// ECMA-262 reads [] as matching nothing and [^] anything, where Go's regexp +// reads the ] as a member. +func (scan *patternScan) class() { + rest := strings.TrimPrefix(scan.rest[1:], "^") + if strings.HasPrefix(rest, "]") { + scan.alike = false + return + } + for rest == "" || rest[0] != ']' { + width, ok := classItem(rest) + if !ok { + scan.alike = false + return + } + rest = rest[width:] + } + scan.read(len(scan.rest)-len(rest)+1, itemAtom) +} + +// classItem returns the width of the class item text starts with, a member or +// a range, and false where it is outside the subset, as a range with a class +// escape at an end is: ECMA-262 reads it as its members and a -. A range out +// of order is left to Go's regexp, which refuses it as ECMA-262 does. +func classItem(text string) (int, bool) { + low := classAtom(text) + if !low.ok { + return 0, false + } + rest := text[low.width:] + if !strings.HasPrefix(rest, "-") || strings.HasPrefix(rest, "-]") { + return low.width, true + } + high := classAtom(rest[1:]) + if !high.ok || !low.single || !high.single { + return 0, false + } + return low.width + 1 + high.width, true +} + +// classAtom reads the member text starts with. A [ is outside the subset, as +// Go's regexp reads [:alpha:] as a named class, and so is \b, a backspace to +// ECMA-262 that Go's regexp refuses. +func classAtom(text string) classMember { + switch { + case text == "", text[0] == '[': + return classMember{} + case len(text) >= 2 && text[0] == '\\' && strings.IndexByte("dDwW", text[1]) >= 0: + return classMember{width: 2, ok: true} + case text[0] == '\\': + width, ok := characterEscape(text) + return classMember{width: width, single: true, ok: ok} + default: + _, width := utf8.DecodeRuneInString(text) + return classMember{width: width, single: true, ok: true} + } +} + +// classMember is the member a class starts with (classAtom): its width, +// whether it is one character, and whether it is inside the subset. +type classMember struct { + width int + single bool + ok bool +} diff --git a/ir/admission_pattern_test.go b/ir/admission_pattern_test.go new file mode 100644 index 000000000..a6a326d7d --- /dev/null +++ b/ir/admission_pattern_test.go @@ -0,0 +1,663 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// ecmaAnswer is what ECMA-262's RegExp, written without flags, answers of a +// text: a match somewhere in it, none, or a refusal of the pattern. +type ecmaAnswer uint8 + +const ( + ecmaMatches ecmaAnswer = iota + ecmaMatchesNot + ecmaRefuses +) + +// patternRows hold patterns and texts with ECMA-262's answer, recorded from +// node v26's new RegExp(pattern).test(text), and whether ir reads the pattern: +// rows matching and not for each construct of the subset ir reads, and one for +// each construct outside it, at a text Go's regexp answers otherwise where +// the recording found one. +var patternRows = []struct { + construct, pattern, text string + ecma ecmaAnswer + read bool +}{ + {"a character", "a", "a", ecmaMatches, true}, + {"a character", "a", "", ecmaMatchesNot, true}, + {"a character", "abc", "abc", ecmaMatches, true}, + {"a character", "abc", "", ecmaMatchesNot, true}, + {"a character", "\u00e9", "\u00e9", ecmaMatches, true}, + {"a character", "\u00e9", "", ecmaMatchesNot, true}, + {"a character", "\u4e2d", "\u4e2d", ecmaMatches, true}, + {"a character", "\u4e2d", "", ecmaMatchesNot, true}, + {"a character", "\uffff", "\uffff", ecmaMatches, true}, + {"a character", "\uffff", "", ecmaMatchesNot, true}, + {"a character", "\u2028", "\u2028", ecmaMatches, true}, + {"a character", "\u2028", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\!", "!", ecmaMatches, true}, + {"escaped punctuation", "\\!", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\\"", "\"", ecmaMatches, true}, + {"escaped punctuation", "\\\"", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\#", "#c", ecmaMatches, true}, + {"escaped punctuation", "\\#", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\$", "$", ecmaMatches, true}, + {"escaped punctuation", "\\$", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\%", "%", ecmaMatches, true}, + {"escaped punctuation", "\\%", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\&", "&", ecmaMatches, true}, + {"escaped punctuation", "\\&", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\'", "'", ecmaMatches, true}, + {"escaped punctuation", "\\'", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\(", "(", ecmaMatches, true}, + {"escaped punctuation", "\\(", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\)", ")", ecmaMatches, true}, + {"escaped punctuation", "\\)", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\*", "*", ecmaMatches, true}, + {"escaped punctuation", "\\*", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\+", "+", ecmaMatches, true}, + {"escaped punctuation", "\\+", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\,", "a{,3}", ecmaMatches, true}, + {"escaped punctuation", "\\,", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\-", "-", ecmaMatches, true}, + {"escaped punctuation", "\\-", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\.", ".", ecmaMatches, true}, + {"escaped punctuation", "\\.", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\/", "/", ecmaMatches, true}, + {"escaped punctuation", "\\/", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\:", ":alpha", ecmaMatches, true}, + {"escaped punctuation", "\\:", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\;", ";", ecmaMatches, true}, + {"escaped punctuation", "\\;", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\<", "<", ecmaMatches, true}, + {"escaped punctuation", "\\<", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\=", "=", ecmaMatches, true}, + {"escaped punctuation", "\\=", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\>", ">", ecmaMatches, true}, + {"escaped punctuation", "\\>", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\?", "?", ecmaMatches, true}, + {"escaped punctuation", "\\?", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\@", "@", ecmaMatches, true}, + {"escaped punctuation", "\\@", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\[", "[", ecmaMatches, true}, + {"escaped punctuation", "\\[", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\\\", "\\", ecmaMatches, true}, + {"escaped punctuation", "\\\\", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\]", "a]", ecmaMatches, true}, + {"escaped punctuation", "\\]", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\^", "^", ecmaMatches, true}, + {"escaped punctuation", "\\^", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\_", "_", ecmaMatches, true}, + {"escaped punctuation", "\\_", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\`", "`", ecmaMatches, true}, + {"escaped punctuation", "\\`", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\{", "{", ecmaMatches, true}, + {"escaped punctuation", "\\{", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\|", "|", ecmaMatches, true}, + {"escaped punctuation", "\\|", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\}", "}", ecmaMatches, true}, + {"escaped punctuation", "\\}", "", ecmaMatchesNot, true}, + {"escaped punctuation", "\\~", "~", ecmaMatches, true}, + {"escaped punctuation", "\\~", "", ecmaMatchesNot, true}, + {"a control escape", "\\t", "\x09", ecmaMatches, true}, + {"a control escape", "\\t", "", ecmaMatchesNot, true}, + {"a control escape", "\\n", "\x0a", ecmaMatches, true}, + {"a control escape", "\\n", "", ecmaMatchesNot, true}, + {"a control escape", "\\v", "\x0b", ecmaMatches, true}, + {"a control escape", "\\v", "", ecmaMatchesNot, true}, + {"a control escape", "\\f", "\x0c", ecmaMatches, true}, + {"a control escape", "\\f", "", ecmaMatchesNot, true}, + {"a control escape", "\\r", "\x0d", ecmaMatches, true}, + {"a control escape", "\\r", "", ecmaMatchesNot, true}, + {"a hex escape, either case", "\\x41", "A", ecmaMatches, true}, + {"a hex escape, either case", "\\x41", "", ecmaMatchesNot, true}, + {"a hex escape, either case", "\\x4a", "J", ecmaMatches, true}, + {"a hex escape, either case", "\\x4a", "", ecmaMatchesNot, true}, + {"a hex escape, either case", "\\x4A", "J", ecmaMatches, true}, + {"a hex escape, either case", "\\x4A", "", ecmaMatchesNot, true}, + {"a hex escape, either case", "\\x00", "\x00", ecmaMatches, true}, + {"a hex escape, either case", "\\x00", "", ecmaMatchesNot, true}, + {"a hex escape, either case", "\\xff", "", ecmaMatchesNot, true}, + {"a hex escape, either case", "\\xFF", "", ecmaMatchesNot, true}, + {"a class", "[abc]", "a", ecmaMatches, true}, + {"a class", "[abc]", "", ecmaMatchesNot, true}, + {"a class", "[^abc]", "A", ecmaMatches, true}, + {"a class", "[^abc]", "", ecmaMatchesNot, true}, + {"a class", "[a^]", "a", ecmaMatches, true}, + {"a class", "[a^]", "", ecmaMatchesNot, true}, + {"a class", "[^^]", "a", ecmaMatches, true}, + {"a class", "[^^]", "", ecmaMatchesNot, true}, + {"a class", "[.]", ".", ecmaMatches, true}, + {"a class", "[.]", "", ecmaMatchesNot, true}, + {"a class", "[$]", "$", ecmaMatches, true}, + {"a class", "[$]", "", ecmaMatchesNot, true}, + {"a class", "[*+?]", "*", ecmaMatches, true}, + {"a class", "[*+?]", "", ecmaMatchesNot, true}, + {"a class", "[{}]", "}", ecmaMatches, true}, + {"a class", "[{}]", "", ecmaMatchesNot, true}, + {"a class", "[(|)]", "|", ecmaMatches, true}, + {"a class", "[(|)]", "", ecmaMatchesNot, true}, + {"a class", "[\\]]", "a]", ecmaMatches, true}, + {"a class", "[\\]]", "", ecmaMatchesNot, true}, + {"a class", "[\\[]", "[", ecmaMatches, true}, + {"a class", "[\\[]", "", ecmaMatchesNot, true}, + {"a class", "[\\\\]", "\\", ecmaMatches, true}, + {"a class", "[\\\\]", "", ecmaMatchesNot, true}, + {"a class", "[\\^]", "^", ecmaMatches, true}, + {"a class", "[\\^]", "", ecmaMatchesNot, true}, + {"a class", "[\\n]", "\x0a", ecmaMatches, true}, + {"a class", "[\\n]", "", ecmaMatchesNot, true}, + {"a class", "[^\\n]", "a", ecmaMatches, true}, + {"a class", "[^\\n]", "", ecmaMatchesNot, true}, + {"a class", "[^a]", "A", ecmaMatches, true}, + {"a class", "[^a]", "", ecmaMatchesNot, true}, + {"a range", "[a-z]", "a", ecmaMatches, true}, + {"a range", "[a-z]", "", ecmaMatchesNot, true}, + {"a range", "[^a-z]", "A", ecmaMatches, true}, + {"a range", "[^a-z]", "", ecmaMatchesNot, true}, + {"a range", "[A-Za-z0-9_]", "a", ecmaMatches, true}, + {"a range", "[A-Za-z0-9_]", "", ecmaMatchesNot, true}, + {"a range", "[\\x41-\\x5a]", "A", ecmaMatches, true}, + {"a range", "[\\x41-\\x5a]", "", ecmaMatchesNot, true}, + {"a range", "[\\x00-\\x1f]", "\x09", ecmaMatches, true}, + {"a range", "[\\x00-\\x1f]", "", ecmaMatchesNot, true}, + {"a range", "[\\--\\/]", "-", ecmaMatches, true}, + {"a range", "[\\--\\/]", "", ecmaMatchesNot, true}, + {"a range", "[!--]", "-", ecmaMatches, true}, + {"a range", "[!--]", "", ecmaMatchesNot, true}, + {"a range", "[---]", "-", ecmaMatches, true}, + {"a range", "[---]", "", ecmaMatchesNot, true}, + {"a range", "[a-a]", "a", ecmaMatches, true}, + {"a range", "[a-a]", "", ecmaMatchesNot, true}, + {"a range", "[\u00e9-\u00fc]", "\u00e9", ecmaMatches, true}, + {"a range", "[\u00e9-\u00fc]", "", ecmaMatchesNot, true}, + {"a range", "[ -~]", "a", ecmaMatches, true}, + {"a range", "[ -~]", "", ecmaMatchesNot, true}, + {"a range", "[A-z]", "a", ecmaMatches, true}, + {"a range", "[A-z]", "", ecmaMatchesNot, true}, + {"a range", "[\\t\\x20-\\x7E]*", "", ecmaMatches, true}, + {"a - at a class edge or after a range", "[-a]", "a", ecmaMatches, true}, + {"a - at a class edge or after a range", "[-a]", "", ecmaMatchesNot, true}, + {"a - at a class edge or after a range", "[a-]", "a", ecmaMatches, true}, + {"a - at a class edge or after a range", "[a-]", "", ecmaMatchesNot, true}, + {"a - at a class edge or after a range", "[a-z-]", "a", ecmaMatches, true}, + {"a - at a class edge or after a range", "[a-z-]", "", ecmaMatchesNot, true}, + {"a - at a class edge or after a range", "[-a-z]", "a", ecmaMatches, true}, + {"a - at a class edge or after a range", "[-a-z]", "", ecmaMatchesNot, true}, + {"a - at a class edge or after a range", "[a-z-9]", "a", ecmaMatches, true}, + {"a - at a class edge or after a range", "[a-z-9]", "", ecmaMatchesNot, true}, + {"a - at a class edge or after a range", "[--/]", "-", ecmaMatches, true}, + {"a - at a class edge or after a range", "[--/]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[\\d]", "0", ecmaMatches, true}, + {"a class escape in a class", "[\\d]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[\\D]", "a", ecmaMatches, true}, + {"a class escape in a class", "[\\D]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[\\w]", "a", ecmaMatches, true}, + {"a class escape in a class", "[\\w]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[\\W]", "-", ecmaMatches, true}, + {"a class escape in a class", "[\\W]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[^\\d]", "a", ecmaMatches, true}, + {"a class escape in a class", "[^\\d]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[^\\D]", "0", ecmaMatches, true}, + {"a class escape in a class", "[^\\D]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[^\\w]", "-", ecmaMatches, true}, + {"a class escape in a class", "[^\\w]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[\\w-]", "a", ecmaMatches, true}, + {"a class escape in a class", "[\\w-]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[-\\w]", "a", ecmaMatches, true}, + {"a class escape in a class", "[-\\w]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[\\w\\-.]", "a", ecmaMatches, true}, + {"a class escape in a class", "[\\w\\-.]", "", ecmaMatchesNot, true}, + {"a class escape in a class", "[\\d\\w]", "a", ecmaMatches, true}, + {"a class escape in a class", "[\\d\\w]", "", ecmaMatchesNot, true}, + {"a class escape", "\\d", "0", ecmaMatches, true}, + {"a class escape", "\\d", "", ecmaMatchesNot, true}, + {"a class escape", "\\D", "a", ecmaMatches, true}, + {"a class escape", "\\D", "", ecmaMatchesNot, true}, + {"a class escape", "\\w", "a", ecmaMatches, true}, + {"a class escape", "\\w", "", ecmaMatchesNot, true}, + {"a class escape", "\\W", "-", ecmaMatches, true}, + {"a class escape", "\\W", "", ecmaMatchesNot, true}, + {"a class escape", "\\d+", "0", ecmaMatches, true}, + {"a class escape", "\\d+", "", ecmaMatchesNot, true}, + {"a class escape", "^\\w+$", "a", ecmaMatches, true}, + {"a class escape", "^\\w+$", "", ecmaMatchesNot, true}, + {"a class escape", "^\\W*$", "", ecmaMatches, true}, + {"a class escape", "^\\W*$", "a", ecmaMatchesNot, true}, + {"a word boundary", "\\b", "a", ecmaMatches, true}, + {"a word boundary", "\\b", "", ecmaMatchesNot, true}, + {"a word boundary", "\\B", "", ecmaMatches, true}, + {"a word boundary", "\\B", "a", ecmaMatchesNot, true}, + {"a word boundary", "^\\b", "a", ecmaMatches, true}, + {"a word boundary", "^\\b", "", ecmaMatchesNot, true}, + {"a word boundary", "\\b$", "a", ecmaMatches, true}, + {"a word boundary", "\\b$", "", ecmaMatchesNot, true}, + {"a word boundary", "a\\b", "a", ecmaMatches, true}, + {"a word boundary", "a\\b", "", ecmaMatchesNot, true}, + {"a word boundary", "\\ba\\b", "a", ecmaMatches, true}, + {"a word boundary", "\\ba\\b", "", ecmaMatchesNot, true}, + {"a word boundary", "\\Ba", "ba", ecmaMatches, true}, + {"a word boundary", "\\Ba", "", ecmaMatchesNot, true}, + {"a word boundary", "a\\B", "ab", ecmaMatches, true}, + {"a word boundary", "a\\B", "", ecmaMatchesNot, true}, + {"a word boundary", "^\\B$", "", ecmaMatches, true}, + {"a word boundary", "^\\B$", "a", ecmaMatchesNot, true}, + {"an anchor", "^", "", ecmaMatches, true}, + {"an anchor", "$", "", ecmaMatches, true}, + {"an anchor", "^$", "", ecmaMatches, true}, + {"an anchor", "^$", "a", ecmaMatchesNot, true}, + {"an anchor", "^a", "a", ecmaMatches, true}, + {"an anchor", "^a", "", ecmaMatchesNot, true}, + {"an anchor", "a$", "a", ecmaMatches, true}, + {"an anchor", "a$", "", ecmaMatchesNot, true}, + {"an anchor", "^a$", "a", ecmaMatches, true}, + {"an anchor", "^a$", "", ecmaMatchesNot, true}, + {"an anchor", "a^", "", ecmaMatchesNot, true}, + {"an anchor", "$a", "", ecmaMatchesNot, true}, + {"an anchor", "^^a", "a", ecmaMatches, true}, + {"an anchor", "^^a", "", ecmaMatchesNot, true}, + {"an anchor", "a$$", "a", ecmaMatches, true}, + {"an anchor", "a$$", "", ecmaMatchesNot, true}, + {"a group", "(a)", "a", ecmaMatches, true}, + {"a group", "(a)", "", ecmaMatchesNot, true}, + {"a group", "(?:a)", "a", ecmaMatches, true}, + {"a group", "(?:a)", "", ecmaMatchesNot, true}, + {"a group", "()", "", ecmaMatches, true}, + {"a group", "(?:)", "", ecmaMatches, true}, + {"a group", "()a", "a", ecmaMatches, true}, + {"a group", "()a", "", ecmaMatchesNot, true}, + {"a group", "(a)(b)", "ab", ecmaMatches, true}, + {"a group", "(a)(b)", "", ecmaMatchesNot, true}, + {"a group", "((a))", "a", ecmaMatches, true}, + {"a group", "((a))", "", ecmaMatchesNot, true}, + {"a group", "(?:(?:a))", "a", ecmaMatches, true}, + {"a group", "(?:(?:a))", "", ecmaMatchesNot, true}, + {"a group", "^(?:ab|cd)+$", "ab", ecmaMatches, true}, + {"a group", "^(?:ab|cd)+$", "", ecmaMatchesNot, true}, + {"an alternation", "ab|cd", "ab", ecmaMatches, true}, + {"an alternation", "ab|cd", "", ecmaMatchesNot, true}, + {"an alternation", "(a|b)", "a", ecmaMatches, true}, + {"an alternation", "(a|b)", "", ecmaMatchesNot, true}, + {"an alternation", "(?:a|b)c", "abc", ecmaMatches, true}, + {"an alternation", "(?:a|b)c", "", ecmaMatchesNot, true}, + {"an alternation", "|", "", ecmaMatches, true}, + {"an alternation", "a|", "", ecmaMatches, true}, + {"an alternation", "|a", "", ecmaMatches, true}, + {"an alternation", "a||b", "", ecmaMatches, true}, + {"an alternation", "(|a)", "", ecmaMatches, true}, + {"an alternation", "(a|)", "", ecmaMatches, true}, + {"an alternation", "^(a|b)$", "a", ecmaMatches, true}, + {"an alternation", "^(a|b)$", "", ecmaMatchesNot, true}, + {"a quantifier", "a*", "", ecmaMatches, true}, + {"a quantifier", "a+", "a", ecmaMatches, true}, + {"a quantifier", "a+", "", ecmaMatchesNot, true}, + {"a quantifier", "a?", "", ecmaMatches, true}, + {"a quantifier", "a{2}", "aa", ecmaMatches, true}, + {"a quantifier", "a{2}", "", ecmaMatchesNot, true}, + {"a quantifier", "a{2,}", "aa", ecmaMatches, true}, + {"a quantifier", "a{2,}", "", ecmaMatchesNot, true}, + {"a quantifier", "a{2,3}", "aa", ecmaMatches, true}, + {"a quantifier", "a{2,3}", "", ecmaMatchesNot, true}, + {"a quantifier", "^a{0}$", "", ecmaMatches, true}, + {"a quantifier", "^a{0}$", "a", ecmaMatchesNot, true}, + {"a quantifier", "^a{0,0}$", "", ecmaMatches, true}, + {"a quantifier", "^a{0,0}$", "a", ecmaMatchesNot, true}, + {"a quantifier", "^a{1,1}$", "a", ecmaMatches, true}, + {"a quantifier", "^a{1,1}$", "", ecmaMatchesNot, true}, + {"a quantifier", "^a{2,3}$", "aa", ecmaMatches, true}, + {"a quantifier", "^a{2,3}$", "", ecmaMatchesNot, true}, + {"a quantifier", "^(?:ab){2}$", "abab", ecmaMatches, true}, + {"a quantifier", "^(?:ab){2}$", "", ecmaMatchesNot, true}, + {"a quantifier", "\u00e9+", "\u00e9", ecmaMatches, true}, + {"a quantifier", "\u00e9+", "", ecmaMatchesNot, true}, + {"a quantifier", "[a-c]{2}", "ab", ecmaMatches, true}, + {"a quantifier", "[a-c]{2}", "", ecmaMatchesNot, true}, + {"a quantifier", "\\d{3}", "123", ecmaMatches, true}, + {"a quantifier", "\\d{3}", "", ecmaMatchesNot, true}, + {"a lazy quantifier", "a*?", "", ecmaMatches, true}, + {"a lazy quantifier", "a+?", "a", ecmaMatches, true}, + {"a lazy quantifier", "a+?", "", ecmaMatchesNot, true}, + {"a lazy quantifier", "a??", "", ecmaMatches, true}, + {"a lazy quantifier", "a{2}?", "aa", ecmaMatches, true}, + {"a lazy quantifier", "a{2}?", "", ecmaMatchesNot, true}, + {"a lazy quantifier", "a{2,}?", "aa", ecmaMatches, true}, + {"a lazy quantifier", "a{2,}?", "", ecmaMatchesNot, true}, + {"a lazy quantifier", "a{2,3}?", "aa", ecmaMatches, true}, + {"a lazy quantifier", "a{2,3}?", "", ecmaMatchesNot, true}, + {"a lazy quantifier", "\\w*?", "", ecmaMatches, true}, + {"a lazy quantifier", "(?:a?)*?b", "b", ecmaMatches, true}, + {"a lazy quantifier", "(?:a?)*?b", "", ecmaMatchesNot, true}, + {"a quantified group", "(a*)*", "", ecmaMatches, true}, + {"a quantified group", "(a*)+b", "b", ecmaMatches, true}, + {"a quantified group", "(a*)+b", "", ecmaMatchesNot, true}, + {"a quantified group", "(?:a|())*b", "b", ecmaMatches, true}, + {"a quantified group", "(?:a|())*b", "", ecmaMatchesNot, true}, + {"a quantified group", "(?:)+", "", ecmaMatches, true}, + {"a quantified group", "(?:)*", "", ecmaMatches, true}, + {"a quantified group", "(?:^)*a", "a", ecmaMatches, true}, + {"a quantified group", "(?:^)*a", "", ecmaMatchesNot, true}, + {"a quantified group", "(?:\\b)+", "a", ecmaMatches, true}, + {"a quantified group", "(?:\\b)+", "", ecmaMatchesNot, true}, + {"a quantified group", "(?:$)?a", "a", ecmaMatches, true}, + {"a quantified group", "(?:$)?a", "", ecmaMatchesNot, true}, + {"a quantified group", "(a{1,2}){1,2}", "a", ecmaMatches, true}, + {"a quantified group", "(a{1,2}){1,2}", "", ecmaMatchesNot, true}, + {"a quantified group", "(?:a+)?", "", ecmaMatches, true}, + {"a count at Go's bound", "a{1000}", "", ecmaMatchesNot, true}, + {"a count at Go's bound", "^a{1000}$", "", ecmaMatchesNot, true}, + {"a count at Go's bound", "^a{0,1000}$", "", ecmaMatches, true}, + {"a count at Go's bound", "^a{0,1000}$", "A", ecmaMatchesNot, true}, + {"a ] or } alone", "a]", "a]", ecmaMatches, true}, + {"a ] or } alone", "a]", "", ecmaMatchesNot, true}, + {"a ] or } alone", "]", "a]", ecmaMatches, true}, + {"a ] or } alone", "]", "", ecmaMatchesNot, true}, + {"a ] or } alone", "a}", "a}", ecmaMatches, true}, + {"a ] or } alone", "a}", "", ecmaMatchesNot, true}, + {"a ] or } alone", "}", "}", ecmaMatches, true}, + {"a ] or } alone", "}", "", ecmaMatchesNot, true}, + {"a ] or } alone", "a{2}}", "aa}", ecmaMatches, true}, + {"a ] or } alone", "a{2}}", "", ecmaMatchesNot, true}, + {"a search, not anchored", "b", "b", ecmaMatches, true}, + {"a search, not anchored", "b", "", ecmaMatchesNot, true}, + {"a search, not anchored", "bc", "abc", ecmaMatches, true}, + {"a search, not anchored", "bc", "", ecmaMatchesNot, true}, + {"a search, not anchored", "^b", "b", ecmaMatches, true}, + {"a search, not anchored", "^b", "", ecmaMatchesNot, true}, + {"a search, not anchored", "c$", "abc", ecmaMatches, true}, + {"a search, not anchored", "c$", "", ecmaMatchesNot, true}, + {"a search, not anchored", "xyz", "xyz", ecmaMatches, true}, + {"a search, not anchored", "xyz", "", ecmaMatchesNot, true}, + {"a lookaround", "(?=a)", "", ecmaMatchesNot, false}, + {"a lookaround", "(?!a)", "", ecmaMatches, false}, + {"a lookaround", "(?<=a)b", "", ecmaMatchesNot, false}, + {"a lookaround", "(?a)\\k", "", ecmaMatchesNot, false}, + {"a backreference", "\\k", "", ecmaMatchesNot, false}, + {"a named group", "(?a)", "a", ecmaMatches, false}, + {"a named group", "(?Pa)", "", ecmaRefuses, false}, + {"\\s or \\S", "\\s", "\x0b", ecmaMatches, false}, + {"\\s or \\S", "\\S", "\x0b", ecmaMatchesNot, false}, + {"\\s or \\S", "[\\s]", "\x0b", ecmaMatches, false}, + {"\\s or \\S", "[^\\S]", "\x0b", ecmaMatches, false}, + {"a dot", ".", "\x0d", ecmaMatchesNot, false}, + {"a dot", "a.c", "a", ecmaMatchesNot, false}, + {"a dot", ".*", "a", ecmaMatches, false}, + {"an escape of Go's alone", "\\A", "", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\z", "", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\Z", "", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\p{L}", "a", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\P{L}", "0", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\pL", "a", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\Q.\\E", ".", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\a", "a", ecmaMatches, false}, + {"an escape of Go's alone", "\\e", "", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\h", "", ecmaMatchesNot, false}, + {"an escape of Go's alone", "\\R", "", ecmaMatchesNot, false}, + {"a flag", "(?i)a", "", ecmaRefuses, false}, + {"a flag", "(?s).", "", ecmaRefuses, false}, + {"a flag", "(?m)^a", "", ecmaRefuses, false}, + {"a flag", "(?i:a)", "a", ecmaMatches, false}, + {"a control letter, NUL or octal escape", "\\cJ", "", ecmaMatchesNot, false}, + {"a control letter, NUL or octal escape", "\\c", "", ecmaMatchesNot, false}, + {"a control letter, NUL or octal escape", "\\0", "a", ecmaMatchesNot, false}, + {"a control letter, NUL or octal escape", "\\01", "a", ecmaMatchesNot, false}, + {"a control letter, NUL or octal escape", "\\012", "a", ecmaMatchesNot, false}, + {"a control letter, NUL or octal escape", "\\7", "", ecmaMatchesNot, false}, + {"a Unicode escape", "\\u0041", "", ecmaMatchesNot, false}, + {"a Unicode escape", "\\u{41}", "", ecmaMatchesNot, false}, + {"a Unicode escape", "\\uD83D\\uDE00", "", ecmaMatchesNot, false}, + {"a hex escape not of two digits", "\\x4", "", ecmaMatchesNot, false}, + {"a hex escape not of two digits", "\\x", "", ecmaMatchesNot, false}, + {"a hex escape not of two digits", "\\xg1", "", ecmaMatchesNot, false}, + {"a hex escape not of two digits", "\\x{41}", "A", ecmaMatchesNot, false}, + {"a hex escape not of two digits", "[\\x4]", "", ecmaMatchesNot, false}, + {"an escape of a letter, a space or past ASCII", "\\X41", "", ecmaMatchesNot, false}, + {"an escape of a letter, a space or past ASCII", "\\U00000041", "", ecmaMatchesNot, false}, + {"an escape of a letter, a space or past ASCII", "\\g", "", ecmaMatchesNot, false}, + {"an escape of a letter, a space or past ASCII", "\\N", "", ecmaMatchesNot, false}, + {"an escape of a letter, a space or past ASCII", "\\\u00e9", "", ecmaMatchesNot, false}, + {"an escape of a letter, a space or past ASCII", "\\ ", "a", ecmaMatchesNot, false}, + {"an empty class", "[]", "", ecmaMatchesNot, false}, + {"an empty class", "[^]", "", ecmaMatchesNot, false}, + {"an empty class", "[]a]", "a", ecmaMatchesNot, false}, + {"an empty class", "[^]a]", "A", ecmaMatchesNot, false}, + {"\\b or \\B in a class", "[\\b]", "", ecmaMatchesNot, false}, + {"\\b or \\B in a class", "[\\B]", "", ecmaMatchesNot, false}, + {"a [ in a class", "[[:alpha:]]", "a", ecmaMatchesNot, false}, + {"a [ in a class", "[[]", "a", ecmaMatchesNot, false}, + {"a [ in a class", "[a[]", "a", ecmaMatches, false}, + {"a class escape at a range's end", "[\\d-z]", "a", ecmaMatchesNot, false}, + {"a class escape at a range's end", "[a-\\d]", "", ecmaMatchesNot, false}, + {"a class escape at a range's end", "[\\w-.]", "a", ecmaMatches, false}, + {"a class escape at a range's end", "[.-\\w]", "", ecmaMatchesNot, false}, + {"a range out of order", "[z-a]", "a", ecmaRefuses, false}, + {"a range out of order", "[\\x5a-\\x41]", "a", ecmaRefuses, false}, + {"a { that opens no count", "a{01}", "a", ecmaMatches, false}, + {"a { that opens no count", "a{00}", "", ecmaMatches, false}, + {"a { that opens no count", "a{1,02}", "a", ecmaMatches, false}, + {"a { that opens no count", "a{,3}", "a", ecmaMatchesNot, false}, + {"a { that opens no count", "a{", "a", ecmaMatchesNot, false}, + {"a { that opens no count", "a{1", "a", ecmaMatchesNot, false}, + {"a { that opens no count", "a{1,", "a", ecmaMatchesNot, false}, + {"a { that opens no count", "a{a}", "a", ecmaMatchesNot, false}, + {"a { that opens no count", "a{ 1}", "a", ecmaMatchesNot, false}, + {"a { that opens no count", "{", "a", ecmaMatchesNot, false}, + {"a { that opens no count", "{1}", "a", ecmaRefuses, false}, + {"a count Go's regexp refuses", "a{1001}", "", ecmaMatchesNot, false}, + {"a count Go's regexp refuses", "a{2,1}", "a", ecmaRefuses, false}, + {"a count Go's regexp refuses", "a{99999}", "", ecmaMatchesNot, false}, + {"a count Go's regexp refuses", "(a{1000}){1000}", "", ecmaMatchesNot, false}, + {"a count Go's regexp refuses", strings.Repeat("(", 1001) + "a" + strings.Repeat(")", 1001), "", ecmaMatchesNot, false}, + {"a quantifier with nothing to repeat", "*a", "a", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "+a", "a", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "?a", "a", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "a|*b", "a", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "(*a)", "a", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "^*", "", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "$+", "", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "\\b+", "", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "\\B*", "", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "^?a", "", ecmaRefuses, false}, + {"a quantifier with nothing to repeat", "x{2}{3}", "a", ecmaRefuses, false}, + {"a quantifier on a quantifier", "a**", "a", ecmaRefuses, false}, + {"a quantifier on a quantifier", "a*+", "a", ecmaRefuses, false}, + {"a quantifier on a quantifier", "a+*", "a", ecmaRefuses, false}, + {"a quantifier on a quantifier", "a???", "a", ecmaRefuses, false}, + {"a quantifier on a quantifier", "a{2}*", "a", ecmaRefuses, false}, + {"a quantifier on a quantifier", "a?+", "a", ecmaRefuses, false}, + {"an unbalanced group", "(a", "a", ecmaRefuses, false}, + {"an unbalanced group", "a)", "a", ecmaRefuses, false}, + {"an unbalanced group", ")", "a", ecmaRefuses, false}, + {"an unbalanced group", "((a)", "a", ecmaRefuses, false}, + {"an unbalanced group", "(?", "a", ecmaRefuses, false}, + {"an unbalanced group", "(?a)", "a", ecmaRefuses, false}, + {"an unbalanced group", "(?#c)", "a", ecmaRefuses, false}, + {"an unclosed class", "[a", "a", ecmaRefuses, false}, + {"an unclosed class", "[", "a", ecmaRefuses, false}, + {"an unclosed class", "[\\", "a", ecmaRefuses, false}, + {"an unclosed class", "[a-", "a", ecmaRefuses, false}, + {"an unclosed class", "[^", "a", ecmaRefuses, false}, + {"an unclosed class", "[a\\", "a", ecmaRefuses, false}, + {"a trailing backslash", "\\", "a", ecmaRefuses, false}, + {"a trailing backslash", "a\\", "a", ecmaRefuses, false}, + {"a character past the BMP", "\U0001f600", "a", ecmaMatchesNot, false}, + {"a character past the BMP", "a\U0001f600?b", "ab", ecmaMatchesNot, false}, + {"a character past the BMP", "[\U0001f600]", "a", ecmaMatchesNot, false}, + {"a character past the BMP", "^\U0001f600$", "a", ecmaMatchesNot, false}, + {"a text past the BMP", "^[^a]{2}$", "\U0001f600", ecmaMatches, false}, + {"a text past the BMP", "^[^a]$", "\U0001f600", ecmaMatchesNot, false}, + {"a text past the BMP", "^\\W\\W$", "\U0001f600", ecmaMatches, false}, + {"a text past the BMP", "a", "a\U0001f600", ecmaMatches, false}, + {"a text past the BMP", "^a", "\U0001f600a", ecmaMatchesNot, false}, +} + +// TestConstraintsAdmit_ReadsAPatternAsECMA262Does holds ir's answer to +// ECMA-262's for each row of patternRows: yes on a match and no on none where +// ir reads the pattern, and unknown where it does not, whatever ECMA-262 +// answers. +func TestConstraintsAdmit_ReadsAPatternAsECMA262Does(t *testing.T) { + t.Parallel() + for _, row := range patternRows { + want := ir.AdmitsUnknown + if row.read { + require.NotEqual(t, ecmaRefuses, row.ecma, "a pattern ECMA-262 refuses is read: %q", row.pattern) + want = map[ecmaAnswer]ir.Admission{ecmaMatches: ir.AdmitsYes, ecmaMatchesNot: ir.AdmitsNo}[row.ecma] + } + got := ir.ConstraintsAdmit(&ir.Constraints{Pattern: row.pattern}, textValue(row.text)) + assert.Equal(t, want, got, "%s: %q against %q", row.construct, row.pattern, row.text) + } +} + +// TestConstraintsAdmit_AnswersUnknownForTextOrAPatternNotUTF8 pins a text or a +// pattern that is no UTF-8, which ECMA-262's code units do not spell, as +// unknown. +func TestConstraintsAdmit_AnswersUnknownForTextOrAPatternNotUTF8(t *testing.T) { + t.Parallel() + assert.Equal(t, ir.AdmitsUnknown, ir.ConstraintsAdmit(&ir.Constraints{Pattern: "^a"}, textValue("a\xff")), "a text") + assert.Equal(t, ir.AdmitsUnknown, ir.ConstraintsAdmit(&ir.Constraints{Pattern: "^a\xff"}, textValue("a")), "a pattern") +} + +// TestConstraintsAdmit_AnswersUnknownForBytesBesideAPattern pins bytes beside +// a pattern, which bounds bytes as it does text but which ir does not read +// against octets, as unknown, and as no where a length refuses them anyway. +func TestConstraintsAdmit_AnswersUnknownForBytesBesideAPattern(t *testing.T) { + t.Parallel() + octets := ir.Value{Kind: ir.ValueBytes, Bytes: []byte("b")} + assert.Equal(t, ir.AdmitsUnknown, ir.ConstraintsAdmit(&ir.Constraints{Pattern: "^a"}, octets), "a pattern alone") + assert.Equal(t, ir.AdmitsNo, ir.ConstraintsAdmit(&ir.Constraints{Pattern: "^a", MaxLength: new(int64(0))}, octets), + "a length refusing them") +} + +// patternedTypes holds a pattern ^a at each place a value admission reader +// reads one: an alias's bounds, an enum's, a union's and a property's. +func patternedTypes() ir.TypeRegistry { + startsWithA := &ir.Constraints{Pattern: "^a"} + return admissionTypes( + aliasOf("type/alias", primitiveRef(ir.PrimitiveString), startsWithA), + &ir.Enum{ID: "type/enum", ValueType: ir.PrimitiveString, Constraints: startsWithA, + Members: []ir.EnumMember{{Value: textValue("ab")}, {Value: textValue("b")}}}, + &ir.Union{ID: "type/union", Closed: true, Constraints: startsWithA, + Variants: []ir.Variant{{Type: primitiveRef(ir.PrimitiveString)}}}, + &ir.Model{ID: "type/model", Properties: []ir.Property{{ID: "property/type/model/p", WireName: "p", + Type: primitiveRef(ir.PrimitiveString), Constraints: startsWithA}}}, + ) +} + +// TestValueAdmissionReader_JudgesAPatternWhereverItIsWritten pins a pattern +// on an alias, an enum, a union, a property and a position judging a text: yes +// where it matches and no where not, an enum's listed member included. +func TestValueAdmissionReader_JudgesAPatternWhereverItIsWritten(t *testing.T) { + t.Parallel() + reader := readerOver(patternedTypes(), nil) + for _, tc := range []struct { + name string + ref ir.TypeRef + own *ir.Constraints + value ir.Value + want ir.Admission + }{ + {"an alias, matched", refTo("type/alias"), nil, textValue("ab"), ir.AdmitsYes}, + {"an alias, unmatched", refTo("type/alias"), nil, textValue("b"), ir.AdmitsNo}, + {"an enum, a member matched", refTo("type/enum"), nil, textValue("ab"), ir.AdmitsYes}, + {"an enum, a member unmatched", refTo("type/enum"), nil, textValue("b"), ir.AdmitsNo}, + {"a union, matched", refTo("type/union"), nil, textValue("ab"), ir.AdmitsYes}, + {"a union, unmatched", refTo("type/union"), nil, textValue("b"), ir.AdmitsNo}, + {"a property, matched", refTo("type/model"), nil, objectOf("p", textValue("ab")), ir.AdmitsYes}, + {"a property, unmatched", refTo("type/model"), nil, objectOf("p", textValue("b")), ir.AdmitsNo}, + {"a position, matched", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^a"}, textValue("ab"), ir.AdmitsYes}, + {"a position, unmatched", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^a"}, textValue("b"), ir.AdmitsNo}, + {"a position, matched past a length it breaks", primitiveRef(ir.PrimitiveString), + &ir.Constraints{Pattern: "^a", MaxLength: new(int64(1))}, textValue("ab"), ir.AdmitsNo}, + {"a position, an unread pattern beside a length it breaks", primitiveRef(ir.PrimitiveString), + &ir.Constraints{Pattern: "^(?=a)", MaxLength: new(int64(1))}, textValue("ab"), ir.AdmitsNo}, + } { + assert.Equal(t, tc.want, reader.AdmitsAtPosition(tc.ref, tc.own, tc.value), "%s", tc.name) + } +} + +// TestValueAdmissionReader_ChargesAPatternItReadsOnce pins what +// AdmitsAtPositionWithin spends on a pattern: one judgment the first time the +// reader, or a reader Fresh relates, reads it, wherever it is written, a +// pattern outside the subset included, and none after, so a limit one short +// of the first judgment's needs answers unknown. +func TestValueAdmissionReader_ChargesAPatternItReadsOnce(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + ref ir.TypeRef + own *ir.Constraints + value ir.Value + // first is what the first judgment spends, a pattern read among it. + first int + }{ + {"an alias", refTo("type/alias"), nil, textValue("ab"), 2}, + {"an enum", refTo("type/enum"), nil, textValue("ab"), 2}, + {"a union", refTo("type/union"), nil, textValue("ab"), 3}, + {"a property", refTo("type/model"), nil, objectOf("p", textValue("ab")), 3}, + {"a position", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^a"}, textValue("ab"), 2}, + {"a position, outside the subset", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^(?=a)"}, textValue("ab"), 2}, + } { + reader := readerOver(patternedTypes(), nil) + admission, spent, ok := reader.AdmitsAtPositionWithin(tc.ref, tc.own, tc.value, tc.first-1) + assert.Equal(t, []any{ir.AdmitsUnknown, tc.first - 1, false}, []any{admission, spent, ok}, "%s: one short", tc.name) + + reader = readerOver(patternedTypes(), nil) + _, spent, ok = reader.AdmitsAtPositionWithin(tc.ref, tc.own, tc.value, tc.first) + assert.Equal(t, []any{tc.first, true}, []any{spent, ok}, "%s: enough", tc.name) + _, again, _ := reader.AdmitsAtPositionWithin(tc.ref, tc.own, tc.value, tc.first) + _, fresh, _ := reader.Fresh().AdmitsAtPositionWithin(tc.ref, tc.own, tc.value, tc.first) + assert.Equal(t, []int{tc.first - 1, tc.first - 1}, []int{again, fresh}, "%s: read already", tc.name) + } +} + +// TestValueAdmissionReader_ReadsAPatternAsASearch pins a pattern as a search +// for a match anywhere in the text, as ECMA-262's RegExp test makes, not one +// the whole text must match. +func TestValueAdmissionReader_ReadsAPatternAsASearch(t *testing.T) { + t.Parallel() + reader := readerOver(admissionTypes(), nil) + for _, tc := range []struct { + pattern, text string + want ir.Admission + }{ + {"b", "abc", ir.AdmitsYes}, + {"^b", "abc", ir.AdmitsNo}, + {"b$", "abc", ir.AdmitsNo}, + {"[0-9]+", "v12", ir.AdmitsYes}, + {"^[0-9]+$", "v12", ir.AdmitsNo}, + } { + got := reader.AdmitsAtPosition(primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: tc.pattern}, textValue(tc.text)) + assert.Equal(t, tc.want, got, "%q against %q", tc.pattern, tc.text) + } +} + +// TestConstraintsAdmit_AnswersUnknownPastTheWorkBound pins the bound on one +// judgment's work: a pattern's size, each count's operand written out, times +// the text's length plus one, at most 1 << 20. a, of size 1, judges a text of +// 1,048,575 bytes and not one of 1,048,576, and a pattern whose counts write +// out more than the bound judges no text. +func TestConstraintsAdmit_AnswersUnknownPastTheWorkBound(t *testing.T) { + t.Parallel() + holdsA := &ir.Constraints{Pattern: "a"} + within := strings.Repeat("b", 1<<20-2) + "a" + assert.Equal(t, ir.AdmitsYes, ir.ConstraintsAdmit(holdsA, textValue(within)), "at the bound") + assert.Equal(t, ir.AdmitsUnknown, ir.ConstraintsAdmit(holdsA, textValue("b"+within)), "one past it") + + thousand := "a{1000}" // 7 bytes and 999 more copies of a: 1,006 + assert.Equal(t, ir.AdmitsNo, ir.ConstraintsAdmit(&ir.Constraints{Pattern: strings.Repeat(thousand, 1042)}, textValue("")), + "1,048,252 written out") + assert.Equal(t, ir.AdmitsUnknown, ir.ConstraintsAdmit(&ir.Constraints{Pattern: strings.Repeat(thousand, 1043)}, textValue("")), + "1,049,258 written out") +} diff --git a/ir/admission_primitive_test.go b/ir/admission_primitive_test.go new file mode 100644 index 000000000..1ef8afb4d --- /dev/null +++ b/ir/admission_primitive_test.go @@ -0,0 +1,278 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +func numberValue(text string) ir.Value { + return ir.Value{Kind: ir.ValueNumber, Number: ir.BigVal(text)} +} +func textValue(text string) ir.Value { return ir.Value{Kind: ir.ValueString, String: text} } + +// TestPrimitiveAdmits_JudgesEachKindExactly pins the boundary of every +// primitive's judge, the one primitive admission check every reader asks: the +// last value in and the first value out, the near misses of each grammar, and +// unknown for a kind it holds no judge of. +func TestPrimitiveAdmits_JudgesEachKindExactly(t *testing.T) { + t.Parallel() + digits35 := "12345678901234567890123456789012345" + for _, tc := range []struct { + name string + kind ir.PrimitiveKind + v ir.Value + want ir.Admission + }{ + {"int8 min", ir.PrimitiveInt8, numberValue("-128"), ir.AdmitsYes}, + {"int8 max", ir.PrimitiveInt8, numberValue("127"), ir.AdmitsYes}, + {"int8 above", ir.PrimitiveInt8, numberValue("128"), ir.AdmitsNo}, + {"int8 below", ir.PrimitiveInt8, numberValue("-129"), ir.AdmitsNo}, + {"int8 fraction", ir.PrimitiveInt8, numberValue("1.5"), ir.AdmitsNo}, + {"int8 integral fraction", ir.PrimitiveInt8, numberValue("5.0"), ir.AdmitsYes}, + {"int16 max", ir.PrimitiveInt16, numberValue("32767"), ir.AdmitsYes}, + {"int16 above", ir.PrimitiveInt16, numberValue("32768"), ir.AdmitsNo}, + {"int32 max", ir.PrimitiveInt32, numberValue("2147483647"), ir.AdmitsYes}, + {"int32 above", ir.PrimitiveInt32, numberValue("2147483648"), ir.AdmitsNo}, + {"int32 below", ir.PrimitiveInt32, numberValue("-2147483649"), ir.AdmitsNo}, + {"int64 max", ir.PrimitiveInt64, numberValue("9223372036854775807"), ir.AdmitsYes}, + {"int64 above", ir.PrimitiveInt64, numberValue("9223372036854775808"), ir.AdmitsNo}, + {"int64 huge exponent", ir.PrimitiveInt64, numberValue("1e1000001"), ir.AdmitsNo}, + {"int64 tiny exponent", ir.PrimitiveInt64, numberValue("1e-1000001"), ir.AdmitsNo}, + {"uint8 max", ir.PrimitiveUint8, numberValue("255"), ir.AdmitsYes}, + {"uint8 above", ir.PrimitiveUint8, numberValue("256"), ir.AdmitsNo}, + {"uint8 negative", ir.PrimitiveUint8, numberValue("-1"), ir.AdmitsNo}, + {"uint16 max", ir.PrimitiveUint16, numberValue("65535"), ir.AdmitsYes}, + {"uint16 above", ir.PrimitiveUint16, numberValue("65536"), ir.AdmitsNo}, + {"uint32 max", ir.PrimitiveUint32, numberValue("4294967295"), ir.AdmitsYes}, + {"uint32 above", ir.PrimitiveUint32, numberValue("4294967296"), ir.AdmitsNo}, + {"uint64 max", ir.PrimitiveUint64, numberValue("18446744073709551615"), ir.AdmitsYes}, + {"uint64 above", ir.PrimitiveUint64, numberValue("18446744073709551616"), ir.AdmitsNo}, + {"integer huge", ir.PrimitiveInteger, numberValue("1e1000001"), ir.AdmitsYes}, + {"integer fraction", ir.PrimitiveInteger, numberValue("0.5"), ir.AdmitsNo}, + {"integer zero", ir.PrimitiveInteger, numberValue("0.0"), ir.AdmitsYes}, + {"integer string", ir.PrimitiveInteger, textValue("1"), ir.AdmitsNo}, + {"number fraction", ir.PrimitiveNumber, numberValue("1.5"), ir.AdmitsYes}, + {"number bool", ir.PrimitiveNumber, ir.Value{Kind: ir.ValueBool}, ir.AdmitsNo}, + {"float any number", ir.PrimitiveFloat, numberValue("1e1000001"), ir.AdmitsYes}, + {"decimal any number", ir.PrimitiveDecimal, numberValue("1e1000001"), ir.AdmitsYes}, + {"float32 in range", ir.PrimitiveFloat32, numberValue("3.4e38"), ir.AdmitsYes}, + {"float32 out of range", ir.PrimitiveFloat32, numberValue("3.5e38"), ir.AdmitsNo}, + {"float32 negative out of range", ir.PrimitiveFloat32, numberValue("-3.5e38"), ir.AdmitsNo}, + {"float32 rounds to max", ir.PrimitiveFloat32, numberValue("3.40282356e38"), ir.AdmitsYes}, + {"float32 huge exponent", ir.PrimitiveFloat32, numberValue("1e1000001"), ir.AdmitsNo}, + {"float32 string", ir.PrimitiveFloat32, textValue("1"), ir.AdmitsNo}, + {"float64 in range", ir.PrimitiveFloat64, numberValue("1.7e308"), ir.AdmitsYes}, + {"float64 out of range", ir.PrimitiveFloat64, numberValue("1.8e308"), ir.AdmitsNo}, + {"decimal128 34 digits", ir.PrimitiveDecimal128, numberValue(digits35[:34]), ir.AdmitsYes}, + {"decimal128 35 digits", ir.PrimitiveDecimal128, numberValue(digits35), ir.AdmitsNo}, + {"decimal128 zero", ir.PrimitiveDecimal128, numberValue("0"), ir.AdmitsYes}, + {"decimal128 top exponent", ir.PrimitiveDecimal128, numberValue("1e6144"), ir.AdmitsYes}, + {"decimal128 above exponent", ir.PrimitiveDecimal128, numberValue("1e6145"), ir.AdmitsNo}, + {"decimal128 lowest exponent", ir.PrimitiveDecimal128, numberValue("1e-6176"), ir.AdmitsYes}, + {"decimal128 below exponent", ir.PrimitiveDecimal128, numberValue("1e-6177"), ir.AdmitsNo}, + {"decimal128 string", ir.PrimitiveDecimal128, textValue("1"), ir.AdmitsNo}, + {"decimal128 34 digits ending at the lowest exponent", ir.PrimitiveDecimal128, + numberValue("1.234567890123456789012345678901234e-6143"), ir.AdmitsYes}, + {"decimal128 34 digits ending one below it", ir.PrimitiveDecimal128, + numberValue("1.234567890123456789012345678901234e-6144"), ir.AdmitsNo}, + {"float32 last in", ir.PrimitiveFloat32, numberValue("340282356779733661637539395458142568447"), ir.AdmitsYes}, + {"float32 first out", ir.PrimitiveFloat32, numberValue("340282356779733661637539395458142568448"), ir.AdmitsNo}, + {"float32 negative last in", ir.PrimitiveFloat32, numberValue("-340282356779733661637539395458142568447"), ir.AdmitsYes}, + {"float32 negative first out", ir.PrimitiveFloat32, numberValue("-340282356779733661637539395458142568448"), ir.AdmitsNo}, + {"float64 last in", ir.PrimitiveFloat64, numberValue("179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791"), ir.AdmitsYes}, + {"float64 first out", ir.PrimitiveFloat64, numberValue("179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792"), ir.AdmitsNo}, + {"float64 negative last in", ir.PrimitiveFloat64, numberValue("-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791"), ir.AdmitsYes}, + {"float64 negative first out", ir.PrimitiveFloat64, numberValue("-179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792"), ir.AdmitsNo}, + {"float64 zero", ir.PrimitiveFloat64, numberValue("0"), ir.AdmitsYes}, + {"url space", ir.PrimitiveURL, textValue("mailto:a b"), ir.AdmitsNo}, + {"url space in path", ir.PrimitiveURL, textValue("http://x/a b"), ir.AdmitsNo}, + {"url braces", ir.PrimitiveURL, textValue("bytes:{}"), ir.AdmitsNo}, + {"url non ascii", ir.PrimitiveURL, textValue("http://x/é"), ir.AdmitsNo}, + {"url control byte", ir.PrimitiveURL, textValue("http://x/a\x01"), ir.AdmitsNo}, + {"url backslash", ir.PrimitiveURL, textValue("http://x/a\\b"), ir.AdmitsNo}, + {"url percent octet", ir.PrimitiveURL, textValue("http://x/a%20b"), ir.AdmitsYes}, + {"url bad percent octet", ir.PrimitiveURL, textValue("http://x/a%2"), ir.AdmitsNo}, + {"url bad percent digit", ir.PrimitiveURL, textValue("http://x/a%2g"), ir.AdmitsNo}, + {"url delimiters", ir.PrimitiveURL, textValue("a+b-c.d://u@[::1]:1/p?q=1&r=!$'()*,;~_#f"), ir.AdmitsYes}, + {"url second fragment delimiter", ir.PrimitiveURL, textValue("http://x/#a#b"), ir.AdmitsNo}, + {"url bracket in path", ir.PrimitiveURL, textValue("http://x/a[b"), ir.AdmitsNo}, + {"url bracket without authority", ir.PrimitiveURL, textValue("bytes:a]"), ir.AdmitsNo}, + {"url ip literal host", ir.PrimitiveURL, textValue("http://[::1]/"), ir.AdmitsYes}, + {"url bracket ends a reg-name host", ir.PrimitiveURL, textValue("http://x]/"), ir.AdmitsNo}, + {"url bracket ends a host before the port", ir.PrimitiveURL, textValue("http://x]:80/"), ir.AdmitsNo}, + {"url bracket ends a userinfo host", ir.PrimitiveURL, textValue("http://u@x]/"), ir.AdmitsNo}, + {"url bracket inside a reg-name host", ir.PrimitiveURL, textValue("http://a]b/"), ir.AdmitsNo}, + {"url second @ in the authority", ir.PrimitiveURL, textValue("http://a@b@x/"), ir.AdmitsNo}, + {"url second @ before an IP-literal", ir.PrimitiveURL, textValue("http://a@b@[::1]/"), ir.AdmitsNo}, + {"url @ after the authority is a path or query byte", ir.PrimitiveURL, textValue("http://u@x/a@b?c@d"), ir.AdmitsYes}, + {"url @ in a path with no authority", ir.PrimitiveURL, textValue("mailto:a@b@c"), ir.AdmitsYes}, + {"url @ in a query right after the host", ir.PrimitiveURL, textValue("http://u@x?a@b"), ir.AdmitsYes}, + {"url @ in a fragment right after the host", ir.PrimitiveURL, textValue("http://u@x#a@b"), ir.AdmitsYes}, + {"url two closing brackets", ir.PrimitiveURL, textValue("http://[::1]]/"), ir.AdmitsNo}, + {"url text after the literal", ir.PrimitiveURL, textValue("http://[::1]a/"), ir.AdmitsNo}, + {"url opening bracket ends a host", ir.PrimitiveURL, textValue("http://x[/"), ir.AdmitsNo}, + {"url opening bracket in the userinfo", ir.PrimitiveURL, textValue("http://u[@x/"), ir.AdmitsNo}, + {"url ipvfuture host is refused as url.Parse refuses it", ir.PrimitiveURL, textValue("http://[v1.x]/"), ir.AdmitsNo}, + {"url ip literal with a port, path, query and fragment", ir.PrimitiveURL, textValue("http://[::1]:80/a?b#c"), ir.AdmitsYes}, + {"url ip literal with userinfo", ir.PrimitiveURL, textValue("http://u@[::1]/"), ir.AdmitsYes}, + {"url ip literal without a path", ir.PrimitiveURL, textValue("bytes://[::1]"), ir.AdmitsYes}, + {"url ip literal with a zone", ir.PrimitiveURL, textValue("http://[fe80::1%25en0]/"), ir.AdmitsYes}, + {"url query then fragment", ir.PrimitiveURL, textValue("http://x?a#b"), ir.AdmitsYes}, + {"url empty", ir.PrimitiveURL, textValue(""), ir.AdmitsNo}, + {"url no colon", ir.PrimitiveURL, textValue("abc"), ir.AdmitsNo}, + {"url scheme only", ir.PrimitiveURL, textValue("a:"), ir.AdmitsYes}, + {"url bad scheme byte", ir.PrimitiveURL, textValue("a_b:c"), ir.AdmitsNo}, + {"time comma fraction", ir.PrimitiveTime, textValue("23:59:59,5"), ir.AdmitsNo}, + {"time dot fraction", ir.PrimitiveTime, textValue("23:59:59.5"), ir.AdmitsYes}, + {"time empty fraction", ir.PrimitiveTime, textValue("23:59:59."), ir.AdmitsNo}, + {"time with a Z offset", ir.PrimitiveTime, textValue("23:59:59Z"), ir.AdmitsNo}, + {"time with a numeric offset", ir.PrimitiveTime, textValue("23:59:59.5+01:00"), ir.AdmitsNo}, + {"time short", ir.PrimitiveTime, textValue("23:59"), ir.AdmitsNo}, + {"time bad separator", ir.PrimitiveTime, textValue("23-59:59"), ir.AdmitsNo}, + {"time bad digit", ir.PrimitiveTime, textValue("2a:59:59"), ir.AdmitsNo}, + {"time hour 24", ir.PrimitiveTime, textValue("24:00:00"), ir.AdmitsNo}, + {"time minute 60", ir.PrimitiveTime, textValue("23:60:00"), ir.AdmitsNo}, + {"time leap second at any minute", ir.PrimitiveTime, textValue("12:34:60"), ir.AdmitsYes}, + {"time second 61", ir.PrimitiveTime, textValue("23:59:61"), ir.AdmitsNo}, + {"time number", ir.PrimitiveTime, numberValue("1"), ir.AdmitsNo}, + {"datetime", ir.PrimitiveDatetime, textValue("2024-02-29T23:59:59"), ir.AdmitsYes}, + {"datetime dot fraction", ir.PrimitiveDatetime, textValue("2024-02-29T23:59:59.5"), ir.AdmitsYes}, + {"datetime lower case t", ir.PrimitiveDatetime, textValue("2024-02-29t23:59:59"), ir.AdmitsYes}, + {"datetime with a Z offset", ir.PrimitiveDatetime, textValue("2024-02-29T23:59:59Z"), ir.AdmitsNo}, + {"datetime with a numeric offset", ir.PrimitiveDatetime, textValue("2024-02-29T23:59:59+01:00"), ir.AdmitsNo}, + {"datetime space separator", ir.PrimitiveDatetime, textValue("2024-01-01 00:00:00"), ir.AdmitsNo}, + {"datetime short", ir.PrimitiveDatetime, textValue("2024-01-01"), ir.AdmitsNo}, + {"datetime bad calendar", ir.PrimitiveDatetime, textValue("2023-02-29T00:00:00"), ir.AdmitsNo}, + {"datetime hour 24", ir.PrimitiveDatetime, textValue("2024-01-01T24:00:00"), ir.AdmitsNo}, + {"datetime leap second at any minute", ir.PrimitiveDatetime, textValue("2024-01-01T05:29:60"), ir.AdmitsYes}, + {"datetime second 61", ir.PrimitiveDatetime, textValue("2016-12-31T23:59:61"), ir.AdmitsNo}, + {"datetime number", ir.PrimitiveDatetime, numberValue("1"), ir.AdmitsNo}, + {"datetime offset max", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T23:59:59-23:59"), ir.AdmitsYes}, + {"datetime offset bad digit", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T23:59:59+0a:00"), ir.AdmitsNo}, + {"datetime offset bad sign", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T23:59:59*05:00"), ir.AdmitsNo}, + {"datetime offset no colon", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T23:59:59+0500"), ir.AdmitsNo}, + {"datetime offset empty fraction", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T23:59:59.Z"), ir.AdmitsNo}, + {"datetime offset leap second behind utc", ir.PrimitiveDatetimeOffset, textValue("2016-12-31T15:59:60-08:00"), ir.AdmitsYes}, + {"datetime offset leap second wrong minute", ir.PrimitiveDatetimeOffset, textValue("2016-12-31T23:58:60Z"), ir.AdmitsNo}, + {"datetime offset second 61", ir.PrimitiveDatetimeOffset, textValue("2016-12-31T23:59:61Z"), ir.AdmitsNo}, + {"datetime offset leap second", ir.PrimitiveDatetimeOffset, textValue("2016-12-31T23:59:60Z"), ir.AdmitsYes}, + {"datetime offset leap second wrong hour", ir.PrimitiveDatetimeOffset, textValue("2016-12-31T22:59:60Z"), ir.AdmitsNo}, + {"datetime offset comma fraction", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T00:00:00,5Z"), ir.AdmitsNo}, + {"datetime offset dot fraction", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T00:00:00.5Z"), ir.AdmitsYes}, + {"datetime offset hour 24 offset", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T00:00:00+24:00"), ir.AdmitsNo}, + {"datetime offset minute 60 offset", ir.PrimitiveDatetimeOffset, textValue("2024-01-01T00:00:00+05:60"), ir.AdmitsNo}, + {"datetime offset lower case", ir.PrimitiveDatetimeOffset, textValue("2024-01-01t00:00:00z"), ir.AdmitsYes}, + {"datetime offset lower case t", ir.PrimitiveDatetimeOffset, textValue("2024-01-01t00:00:00Z"), ir.AdmitsYes}, + {"datetime offset space separator", ir.PrimitiveDatetimeOffset, textValue("2024-01-01 00:00:00Z"), ir.AdmitsNo}, + {"datetime offset short", ir.PrimitiveDatetimeOffset, textValue("2024-01-01"), ir.AdmitsNo}, + {"datetime offset bad calendar", ir.PrimitiveDatetimeOffset, textValue("2024-02-30T00:00:00Z"), ir.AdmitsNo}, + {"bool", ir.PrimitiveBool, ir.Value{Kind: ir.ValueBool, Bool: true}, ir.AdmitsYes}, + {"bool number", ir.PrimitiveBool, numberValue("1"), ir.AdmitsNo}, + {"string", ir.PrimitiveString, textValue("x"), ir.AdmitsYes}, + {"string symbol", ir.PrimitiveString, ir.Value{Kind: ir.ValueSymbol, String: "x"}, ir.AdmitsNo}, + {"date", ir.PrimitiveDate, textValue("2024-02-29"), ir.AdmitsYes}, + {"date invalid calendar", ir.PrimitiveDate, textValue("2023-02-29"), ir.AdmitsNo}, + {"date short", ir.PrimitiveDate, textValue("2024-2-9"), ir.AdmitsNo}, + {"time", ir.PrimitiveTime, textValue("23:59:59"), ir.AdmitsYes}, + {"datetime offset", ir.PrimitiveDatetimeOffset, textValue("2024-02-29T23:59:59Z"), ir.AdmitsYes}, + {"datetime offset none", ir.PrimitiveDatetimeOffset, textValue("2024-02-29T23:59:59"), ir.AdmitsNo}, + {"datetime offset hour", ir.PrimitiveDatetimeOffset, textValue("2024-02-29T24:00:00Z"), ir.AdmitsNo}, + {"uuid", ir.PrimitiveUUID, textValue("123e4567-e89b-12d3-a456-426614174000"), ir.AdmitsYes}, + {"uuid upper", ir.PrimitiveUUID, textValue("123E4567-E89B-12D3-A456-426614174000"), ir.AdmitsYes}, + {"uuid short", ir.PrimitiveUUID, textValue("123e4567-e89b-12d3-a456-42661417400"), ir.AdmitsNo}, + {"uuid no dash", ir.PrimitiveUUID, textValue("123e4567xe89b-12d3-a456-426614174000"), ir.AdmitsNo}, + {"uuid non hex", ir.PrimitiveUUID, textValue("123e4567-e89b-12d3-a456-42661417400g"), ir.AdmitsNo}, + {"uuid word", ir.PrimitiveUUID, textValue("hello"), ir.AdmitsNo}, + {"url", ir.PrimitiveURL, textValue("https://example.com/a?b=c"), ir.AdmitsYes}, + {"url mailto", ir.PrimitiveURL, textValue("mailto:a@example.com"), ir.AdmitsYes}, + {"url relative", ir.PrimitiveURL, textValue("/a/b"), ir.AdmitsNo}, + {"url bad", ir.PrimitiveURL, textValue("1http://x"), ir.AdmitsNo}, + {"url number", ir.PrimitiveURL, numberValue("1"), ir.AdmitsNo}, + {"duration", ir.PrimitiveDuration, textValue("P1Y2M3DT4H5M6S"), ir.AdmitsYes}, + {"duration weeks", ir.PrimitiveDuration, textValue("P2W"), ir.AdmitsYes}, + {"duration time only", ir.PrimitiveDuration, textValue("PT5M"), ir.AdmitsYes}, + {"duration skipped designator", ir.PrimitiveDuration, textValue("P1Y3D"), ir.AdmitsNo}, + {"duration date from months", ir.PrimitiveDuration, textValue("P2M3D"), ir.AdmitsYes}, + {"duration out of order", ir.PrimitiveDuration, textValue("P3D2M"), ir.AdmitsNo}, + {"duration empty", ir.PrimitiveDuration, textValue("P"), ir.AdmitsNo}, + {"duration empty time", ir.PrimitiveDuration, textValue("P1DT"), ir.AdmitsNo}, + {"duration bare T", ir.PrimitiveDuration, textValue("PT"), ir.AdmitsNo}, + {"duration no prefix", ir.PrimitiveDuration, textValue("1D"), ir.AdmitsNo}, + {"duration weeks mixed", ir.PrimitiveDuration, textValue("P1W2D"), ir.AdmitsNo}, + {"duration no digits", ir.PrimitiveDuration, textValue("PD"), ir.AdmitsNo}, + {"duration trailing digits", ir.PrimitiveDuration, textValue("P1"), ir.AdmitsNo}, + {"duration repeated", ir.PrimitiveDuration, textValue("P1D1D"), ir.AdmitsNo}, + {"duration unknown", ir.PrimitiveDuration, textValue("P1X"), ir.AdmitsNo}, + {"duration date after time", ir.PrimitiveDuration, textValue("PT1H1D"), ir.AdmitsNo}, + {"date number", ir.PrimitiveDate, numberValue("1"), ir.AdmitsNo}, + {"bytes, which no judge reads", ir.PrimitiveBytes, ir.Value{Kind: ir.ValueBytes, Bytes: []byte("x")}, ir.AdmitsUnknown}, + {"any", ir.PrimitiveAny, ir.Value{Kind: ir.ValueObject}, ir.AdmitsYes}, + {"list against integer", ir.PrimitiveInteger, ir.Value{Kind: ir.ValueList, List: []ir.Value{numberValue("1")}}, ir.AdmitsNo}, + {"a kind ir does not declare", ir.PrimitiveKind("nope"), textValue("x"), ir.AdmitsUnknown}, + } { + assert.Equal(t, tc.want, ir.PrimitiveAdmits(tc.kind, tc.v), "%s: %s of %v", tc.name, tc.kind, tc.v) + } +} + +// TestPrimitiveAdmits_ReadsAHugeExponentWithoutMaterializingIt pins that a +// literal no machine type holds is refused promptly rather than built. +func TestPrimitiveAdmits_ReadsAHugeExponentWithoutMaterializingIt(t *testing.T) { + t.Parallel() + start := time.Now() + for _, primitiveKind := range []ir.PrimitiveKind{ir.PrimitiveInt64, ir.PrimitiveUint64, ir.PrimitiveFloat32, ir.PrimitiveFloat64, ir.PrimitiveDecimal128} { + assert.Equal(t, ir.AdmitsNo, ir.PrimitiveAdmits(primitiveKind, numberValue("1e1000001")), "%s", primitiveKind) + assert.Equal(t, ir.AdmitsNo, ir.PrimitiveAdmits(primitiveKind, numberValue("1e99999999999999999999")), "%s", primitiveKind) + } + assert.Less(t, time.Since(start), 5*time.Second) +} + +// TestPrimitiveAdmits_AnIEEEKindAdmitsTheInfinitiesAndNaN pins the values the +// IEEE 754 kinds alone hold (docs/ir/primitives.md#containment): each binary +// float and decimal128 admits both infinities and NaN, and every other numeric +// kind, and a string, refuses them, as no decimal holds one. +func TestPrimitiveAdmits_AnIEEEKindAdmitsTheInfinitiesAndNaN(t *testing.T) { + t.Parallel() + ieee := []ir.PrimitiveKind{ir.PrimitiveFloat32, ir.PrimitiveFloat64, ir.PrimitiveFloat, ir.PrimitiveDecimal128} + others := []ir.PrimitiveKind{ir.PrimitiveNumber, ir.PrimitiveDecimal, ir.PrimitiveInteger, ir.PrimitiveInt32, ir.PrimitiveUint64, ir.PrimitiveString} + for _, valueKind := range []ir.ValueKind{ir.ValueInfinity, ir.ValueNegativeInfinity, ir.ValueNaN} { + for _, primitiveKind := range ieee { + assert.Equal(t, ir.AdmitsYes, ir.PrimitiveAdmits(primitiveKind, ir.Value{Kind: valueKind}), "%s of %s", primitiveKind, valueKind) + } + for _, primitiveKind := range others { + assert.Equal(t, ir.AdmitsNo, ir.PrimitiveAdmits(primitiveKind, ir.Value{Kind: valueKind}), "%s of %s", primitiveKind, valueKind) + } + } +} + +// TestValueAdmissionReader_HoldsTheInfinitiesAndNaNToTheBoundsOfAFloat pins +// the reader over a float64 that an alias chain bounds and over one a position +// bounds: each judges an infinity and NaN by the numeric keywords +// (ConstraintsAdmit), and a maximum the chain states no one value of leaves +// what would be a yes unknown, an infinity being a value it binds. +func TestValueAdmissionReader_HoldsTheInfinitiesAndNaNToTheBoundsOfAFloat(t *testing.T) { + t.Parallel() + float64Ref := primitiveRef(ir.PrimitiveFloat64) + reader := readerOver(admissionTypes( + &ir.Primitive{ID: float64Ref.Target, PrimitiveKind: ir.PrimitiveFloat64}, + aliasOf("type/positive", float64Ref, &ir.Constraints{Min: new(ir.BigVal("0"))}), + aliasOf("type/near", refTo("type/far"), &ir.Constraints{Max: new(ir.BigVal("5"))}), + aliasOf("type/far", float64Ref, &ir.Constraints{Max: new(ir.BigVal("1p4"))}), + ), nil) + infinity, negativeInfinity, nan := ir.Value{Kind: ir.ValueInfinity}, ir.Value{Kind: ir.ValueNegativeInfinity}, ir.Value{Kind: ir.ValueNaN} + atMost := &ir.Constraints{Max: new(ir.BigVal("4"))} + + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/positive"), infinity), "above the chain's minimum") + assert.Equal(t, ir.AdmitsNo, reader.Admits(refTo("type/positive"), negativeInfinity), "below it") + assert.Equal(t, ir.AdmitsNo, reader.Admits(refTo("type/positive"), nan), "NaN against it") + assert.Equal(t, ir.AdmitsNo, reader.AdmitsAtPosition(float64Ref, atMost, infinity), "past the position's maximum") + assert.Equal(t, ir.AdmitsYes, reader.AdmitsAtPosition(float64Ref, atMost, negativeInfinity), "within it") + assert.Equal(t, ir.AdmitsNo, reader.AdmitsAtPosition(float64Ref, atMost, nan), "NaN against it") + assert.Equal(t, ir.AdmitsUnknown, reader.Admits(refTo("type/near"), negativeInfinity), "beside a maximum no one value states") +} diff --git a/ir/admission_reader.go b/ir/admission_reader.go new file mode 100644 index 000000000..045f80273 --- /dev/null +++ b/ir/admission_reader.go @@ -0,0 +1,232 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "math" + +// SourceFormatAdmissions answers what ir cannot read, in the terms of the +// source format the IR was compiled from: an encoding names a format ir holds +// no grammar of, and a kept no_ir_home entry a keyword ir has no field for +// (docs/ir/values.md#admission-answers). +type SourceFormatAdmissions interface { + // AdmitsUnderEncoding judges value against an encoding ir does not read. + AdmitsUnderEncoding(encoding *Encoding, value Value) Admission + // AdmitsUnderUnmodeledEntry judges value against a no_ir_home Unmodeled + // entry a node keeps. + AdmitsUnderUnmodeledEntry(key string, entry UnmodeledEntry, value Value) Admission +} + +// maxAdmitsDepth bounds how deep into a value a [ValueAdmissionReader] +// judges, its one recursion: a member or an element nested deeper answers +// unknown. +const maxAdmitsDepth = 64 + +// ValueAdmissionReader judges values against the types one lookup finds, each +// answer an [Admission] (docs/ir/values.md#admission-answers). It reads each +// node, alias chain, model composition, union's variants and enum's members +// once for its life, so a change to one it has read goes unread: a caller +// whose types change between calls judges each span of them through its own +// (Fresh). It is not safe for concurrent use, nor are two readers Fresh +// relates, as an [AliasChainIndex] is not. +type ValueAdmissionReader struct { + node func(TypeID) (TypeDef, bool) + aliasChains *AliasChainIndex + sourceFormats SourceFormatAdmissions + // chains holds what each alias chain adds to the type it ends on. + chains *AliasChainAnswers[*aliasChainFacts] + // propertyCounts reads the property counts of each model's composition + // through the lookup, so it lives as long as the models it reads. + propertyCounts *PropertyCountBounds + // nodes holds each node the reader has read, nil where the lookup found + // none, models what each model judged reads of its composition, and + // unions the edges to each union's variants (unionEdges). + nodes map[TypeID]TypeDef + models map[TypeID]*modelFacts + unions map[TypeID][]admissionEdge + // enums holds each enum's members as a value is looked up among them, by + // node: a caller changes no enum's members once it is built. + enums map[*Enum]*enumMembers + // patterns holds each pattern the reader has read. + patterns patternMatchers +} + +// NewValueAdmissionReader returns a reader over the types node finds, reading +// alias chains through aliasChains, an index over the same types, and asking +// sourceFormats, which may be nil, what ir cannot read. Where it is nil, what +// it would be asked answers unknown. +func NewValueAdmissionReader(node func(TypeID) (TypeDef, bool), aliasChains *AliasChainIndex, + sourceFormats SourceFormatAdmissions) *ValueAdmissionReader { + reader := &ValueAdmissionReader{node: node, aliasChains: aliasChains, sourceFormats: sourceFormats, + nodes: map[TypeID]TypeDef{}, models: map[TypeID]*modelFacts{}, unions: map[TypeID][]admissionEdge{}, + enums: map[*Enum]*enumMembers{}, patterns: patternMatchers{}} + reader.chains = NewAliasChainAnswers(aliasChains, + func(TypeID, TypeDef) *aliasChainFacts { return &aliasChainFacts{} }, addAliasFacts) + reader.propertyCounts = NewPropertyCountBounds(reader.lookup, aliasChains) + return reader +} + +// Fresh returns a reader over the same types that has read no node and no +// model, for the next span of calls of a caller whose models change between +// spans. It shares what reader holds of alias chains, enums' members and +// patterns, which settling no model changes. +func (reader *ValueAdmissionReader) Fresh() *ValueAdmissionReader { + fresh := &ValueAdmissionReader{node: reader.node, aliasChains: reader.aliasChains, sourceFormats: reader.sourceFormats, + chains: reader.chains, nodes: map[TypeID]TypeDef{}, models: map[TypeID]*modelFacts{}, + unions: map[TypeID][]admissionEdge{}, enums: reader.enums, patterns: reader.patterns} + fresh.propertyCounts = NewPropertyCountBounds(fresh.lookup, fresh.aliasChains) + return fresh +} + +// Admits judges value against the type ref names. Null is read from ref and +// from a union's variant, never from a Base on an alias chain, and the top +// type a chain ends on admits it whatever ref says. +func (reader *ValueAdmissionReader) Admits(ref TypeRef, value Value) Admission { + return reader.AdmitsAtPosition(ref, nil, value) +} + +// AdmitsAtPosition judges value at a position typed ref that declares the +// bounds own beside its type, nil where it declares none: against the type, +// as Admits does, and against own, each bound binding a value of its kind +// (ConstraintsAdmit). +func (reader *ValueAdmissionReader) AdmitsAtPosition(ref TypeRef, own *Constraints, value Value) Admission { + admission, _, _ := reader.AdmitsAtPositionWithin(ref, own, value, math.MaxInt) + return admission +} + +// AdmitsAtPositionWithin answers AdmitsAtPosition in at most limit +// judgments, one for each type judged against one node of value and one for +// each pattern the reader reads for the first time. spent is the judgments it +// took, and ok is false where it needed more than limit and stopped, +// answering unknown. +func (reader *ValueAdmissionReader) AdmitsAtPositionWithin(ref TypeRef, own *Constraints, value Value, + limit int) (admission Admission, spent int, ok bool) { + limit = max(limit, 0) + patternsRead := len(reader.patterns) + judged, took, leaf := reader.judgeLeaf(ref, &value) + judgmentsLeft := limit - took + if !leaf { + judged, judgmentsLeft = reader.judgeWhole(ref, value, limit) + } + judged = judged.and(constraintsAnswer(own, &value, 0, reader.patterns)) + judgmentsLeft -= len(reader.patterns) - patternsRead + if judgmentsLeft < 0 { + return AdmitsUnknown, limit, false + } + return judged.admission, limit - judgmentsLeft, true +} + +// judgeLeaf judges value against the type ref names where its alias chain +// ends on a leaf (leafAnswer), which no walk of the value's nodes needs, +// taking one judgment where it judges that type, and reports false for any +// other type. It keeps no state of its own, so it allocates nothing but an +// enum's members and a pattern's matcher, each read once a reader, and what +// Go's regexp takes to match. +func (reader *ValueAdmissionReader) judgeLeaf(ref TypeRef, value *Value) (judged admissionAnswer, took int, leaf bool) { + if value.Kind == ValueNull && ref.Nullable { + return admitted(), 0, true + } + facts, held := reader.chains.AnswerFor(ref.Target) + if !held { + return undecided(), 0, true + } + end, _ := reader.aliasChains.End(ref.Target) + node := reader.nodeOf(end) + if node == nil { + return admissionAnswer{}, 0, false + } + local, leaf := reader.leafAnswer(node, value, 0) + if !leaf { + return admissionAnswer{}, 0, false + } + return facts.judge(reader, value, 0).and(local), 1, true +} + +// judgeWhole judges value against the type ref names by a walk of the +// value's nodes in at most limit judgments, holding what the walk settles for +// this call alone, and returns the judgments left, negative where it needed +// more. +func (reader *ValueAdmissionReader) judgeWhole(ref TypeRef, value Value, limit int) (admissionAnswer, int) { + call := admissionCall{reader: reader, memo: map[admissionKey]admissionAnswer{}, judgmentsLeft: limit} + judged := call.judgeRef(ref, &value, 0) + return judged, call.judgmentsLeft +} + +// nodeOf returns the node the lookup finds at id, reading it once for the +// reader's life, nil where there is none. +func (reader *ValueAdmissionReader) nodeOf(id TypeID) TypeDef { + if typeDef, read := reader.nodes[id]; read { + return typeDef + } + typeDef := reader.read(id) + reader.nodes[id] = typeDef + return typeDef +} + +// read returns the node the lookup finds at id, nil where there is none, +// holding it nowhere. +func (reader *ValueAdmissionReader) read(id TypeID) TypeDef { + typeDef, held := reader.node(id) + if !held || IsNilTypeDef(typeDef) { + return nil + } + return typeDef +} + +// lookup is nodeOf in the form a flattening reads. +func (reader *ValueAdmissionReader) lookup(id TypeID) (TypeDef, bool) { + typeDef := reader.nodeOf(id) + return typeDef, typeDef != nil +} + +// admissionKey is one type judged against one node of the value an Admits +// call judges. +type admissionKey struct { + id TypeID + value *Value +} + +// admissionCall is one Admits call's state: the answers its walks have +// settled, by type and value node, so a type reached by two paths is judged +// once against each node, and the judgments it may still take. +type admissionCall struct { + reader *ValueAdmissionReader + memo map[admissionKey]admissionAnswer + // judgmentsLeft is the judgments the call may still take, negative once it needed + // one past them. + judgmentsLeft int +} + +// take spends one judgment, and reports false where none was left. +func (call *admissionCall) take() bool { + call.judgmentsLeft-- + return call.judgmentsLeft >= 0 +} + +// judgeRef judges the value node value, depth levels into the value, against +// the type ref names. +func (call *admissionCall) judgeRef(ref TypeRef, value *Value, depth int) admissionAnswer { + judged, end, endLeftToJudge := call.throughChain(ref, value, depth) + if !endLeftToJudge { + return judged + } + return judged.and(call.judgeNode(end, value, depth)) +} + +// throughChain judges what ref and its alias chain decide of value, and +// returns the type the chain ends on and whether that type is left to judge. +// The top type, at the end, admits null whatever ref says. +func (call *admissionCall) throughChain(ref TypeRef, value *Value, depth int) (admissionAnswer, TypeID, bool) { + if depth > maxAdmitsDepth { + return undecided(), "", false + } + if value.Kind == ValueNull && ref.Nullable { + return admitted(), "", false + } + facts, held := call.reader.chains.AnswerFor(ref.Target) + if !held { + return undecided(), "", false + } + end, _ := call.reader.aliasChains.End(ref.Target) + return facts.judge(call.reader, value, depth), end, true +} diff --git a/ir/admission_unions.go b/ir/admission_unions.go new file mode 100644 index 000000000..bc460763f --- /dev/null +++ b/ir/admission_unions.go @@ -0,0 +1,63 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "slices" + +// unionEdges returns the edges to the variants of union, the node at id, read +// once for the reader's life. +func (reader *ValueAdmissionReader) unionEdges(id TypeID, union *Union) []admissionEdge { + if edges, read := reader.unions[id]; read { + return edges + } + edges := make([]admissionEdge, len(union.Variants)) + for i := range union.Variants { + variant := &union.Variants[i] + edges[i] = admissionEdge{ref: variant.Type, unmodeled: variant.Unmodeled} + edges[i].requires, edges[i].alone = reader.requiredBy(variant.Type.Target) + } + reader.unions[id] = edges + return edges +} + +// requiredBy returns what the model the alias chain from target ends on +// requires, where that model has no unflattened composition entry, so an +// object lacking a member it requires is refused there whatever else holds. +// A model composing nothing is returned alone, read at each judgment +// (lacksOwnRequired) rather than flattened. Both are nil otherwise. +func (reader *ValueAdmissionReader) requiredBy(target TypeID) (requires []string, alone *Model) { + end := target + typeDef := reader.read(target) + if _, alias := typeDef.(*Scalar); alias { + if _, read := reader.chains.AnswerFor(target); !read { + return nil, nil + } + end, _ = reader.aliasChains.End(target) + typeDef = reader.read(end) + } + model, isModel := typeDef.(*Model) + if !isModel { + return nil, nil + } + if len(ComposedOf(model)) == 0 { + return nil, model + } + facts := reader.modelFactsOf(end) + if len(facts.flat.Unflattened) > 0 { + return nil, nil + } + return facts.required, nil +} + +// lacksOwnRequired reports whether an object, whose members are members, lacks +// a member a model composing nothing requires, read as its flattening reads +// them (modelFacts.required). +func lacksOwnRequired(model *Model, members *objectMembers) bool { + for i := range model.Properties { + if model.Properties[i].Required && !members.holds(model.Properties[i].EffectiveWireName()) { + return true + } + } + return slices.ContainsFunc(model.Requires, func(name string) bool { return !members.holds(name) }) +} diff --git a/ir/admission_value_test.go b/ir/admission_value_test.go new file mode 100644 index 000000000..a68323dca --- /dev/null +++ b/ir/admission_value_test.go @@ -0,0 +1,846 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// admissionTypes is a registry holding the primitives the admission rows read +// and the given nodes, each under its own ID. +func admissionTypes(nodes ...ir.TypeDef) ir.TypeRegistry { + registry := ir.TypeRegistry{} + for _, kind := range []ir.PrimitiveKind{ir.PrimitiveString, ir.PrimitiveInteger, ir.PrimitiveBool, ir.PrimitiveAny} { + registry[ir.PrimitiveTypeID(kind)] = &ir.Primitive{ID: ir.PrimitiveTypeID(kind), PrimitiveKind: kind} + } + for _, node := range nodes { + registry[node.Common().ID] = node + } + return registry +} + +// admissionLookupOf is registry's lookup, counting each call in reads where +// reads is not nil. +func admissionLookupOf(registry ir.TypeRegistry, reads *int) func(ir.TypeID) (ir.TypeDef, bool) { + return func(id ir.TypeID) (ir.TypeDef, bool) { + if reads != nil { + *reads++ + } + node, ok := registry[id] + return node, ok + } +} + +// readerOver is a value admission reader over registry and an alias index of +// its own, asking sourceFormats what ir cannot read. +func readerOver(registry ir.TypeRegistry, sourceFormats ir.SourceFormatAdmissions) *ir.ValueAdmissionReader { + lookup := admissionLookupOf(registry, nil) + return ir.NewValueAdmissionReader(lookup, ir.NewAliasChainIndex(lookup), sourceFormats) +} + +func refTo(id ir.TypeID) ir.TypeRef { return ir.TypeRef{Target: id} } +func nullableTo(id ir.TypeID) ir.TypeRef { return ir.TypeRef{Target: id, Nullable: true} } +func primitiveRef(kind ir.PrimitiveKind) ir.TypeRef { return refTo(ir.PrimitiveTypeID(kind)) } + +func boolValue(b bool) ir.Value { return ir.Value{Kind: ir.ValueBool, Bool: b} } +func nullValue() ir.Value { return ir.Value{Kind: ir.ValueNull} } + +// objectOf is an object value holding each name beside the value after it. +func objectOf(namesAndValues ...any) ir.Value { + object := ir.Value{Kind: ir.ValueObject} + for i := 0; i+1 < len(namesAndValues); i += 2 { + name, _ := namesAndValues[i].(string) + value, _ := namesAndValues[i+1].(ir.Value) + object.Object = append(object.Object, ir.Field{Name: name, Value: value}) + } + return object +} + +// admissionUnion is a closed union of the variants, exclusive where oneOf. +func admissionUnion(id ir.TypeID, oneOf bool, variants ...ir.TypeRef) *ir.Union { + union := &ir.Union{ID: id, Exclusive: oneOf, Closed: true} + for _, variant := range variants { + union.Variants = append(union.Variants, ir.Variant{Type: variant}) + } + return union +} + +// aliasOf is an alias scalar over base holding constraints. +func aliasOf(id ir.TypeID, base ir.TypeRef, constraints *ir.Constraints) *ir.Scalar { + return &ir.Scalar{ID: id, Base: &base, Constraints: constraints} +} + +// propertyOf is a property of the model owner, named and typed, required where +// required. +func propertyOf(owner ir.TypeID, name string, typ ir.TypeRef, required bool) ir.Property { + return ir.Property{ID: ir.PropertyID("property/" + string(owner) + "/" + name), WireName: name, Type: typ, Required: required} +} + +// TestValueAdmissionReader_CountsAUnionsVariants pins how a union answers from +// its variants: anyOf yes on any yes and no where every variant says no, oneOf +// yes where exactly one says yes and the rest no, and no where two say yes or +// none does, and unknown wherever a variant's unknown could decide. +func TestValueAdmissionReader_CountsAUnionsVariants(t *testing.T) { + t.Parallel() + short := aliasOf("type/short", primitiveRef(ir.PrimitiveString), &ir.Constraints{MaxLength: new(int64(3))}) + patterned := aliasOf("type/patterned", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^(?=a)"}) + registry := admissionTypes(short, patterned, + admissionUnion("type/anyOf", false, primitiveRef(ir.PrimitiveString), primitiveRef(ir.PrimitiveInteger)), + admissionUnion("type/oneOf", true, primitiveRef(ir.PrimitiveString), primitiveRef(ir.PrimitiveInteger)), + admissionUnion("type/overlap", true, primitiveRef(ir.PrimitiveString), refTo("type/short")), + admissionUnion("type/unread", true, primitiveRef(ir.PrimitiveString), refTo("type/patterned")), + admissionUnion("type/unreadAny", false, refTo("type/patterned"), primitiveRef(ir.PrimitiveInteger)), + ) + reader := readerOver(registry, nil) + for _, tc := range []struct { + name string + union ir.TypeID + value ir.Value + want ir.Admission + }{ + {"anyOf, one variant admitting", "type/anyOf", textValue("x"), ir.AdmitsYes}, + {"anyOf, none admitting", "type/anyOf", boolValue(true), ir.AdmitsNo}, + {"oneOf, exactly one admitting", "type/oneOf", numberValue("3"), ir.AdmitsYes}, + {"oneOf, none admitting", "type/oneOf", boolValue(true), ir.AdmitsNo}, + {"oneOf, two admitting", "type/overlap", textValue("ab"), ir.AdmitsNo}, + {"oneOf, one admitting and one refusing by its bound", "type/overlap", textValue("abcd"), ir.AdmitsYes}, + {"oneOf, an unread pattern beside a yes", "type/unread", textValue("ab"), ir.AdmitsUnknown}, + {"anyOf, an unread pattern beside a no", "type/unreadAny", textValue("ab"), ir.AdmitsUnknown}, + {"anyOf, a yes beside an unread pattern", "type/unreadAny", numberValue("3"), ir.AdmitsYes}, + } { + assert.Equal(t, tc.want, reader.Admits(refTo(tc.union), tc.value), "%s", tc.name) + } +} + +// TestValueAdmissionReader_ReadsNullFromTheReferenceJudged pins where null is +// read: from the reference judged and a union's variant, never from a Base on +// an alias chain, and a chain ending at the top type admits null whatever the +// reference's bit says. +func TestValueAdmissionReader_ReadsNullFromTheReferenceJudged(t *testing.T) { + t.Parallel() + registry := admissionTypes( + aliasOf("type/nullableBase", nullableTo(ir.PrimitiveTypeID(ir.PrimitiveString)), &ir.Constraints{MaxLength: new(int64(9))}), + aliasOf("type/topAlias", primitiveRef(ir.PrimitiveAny), &ir.Constraints{MinLength: new(int64(5))}), + admissionUnion("type/variantNull", true, nullableTo(ir.PrimitiveTypeID(ir.PrimitiveString)), primitiveRef(ir.PrimitiveInteger)), + ) + reader := readerOver(registry, nil) + for _, tc := range []struct { + name string + ref ir.TypeRef + want ir.Admission + }{ + {"a string", primitiveRef(ir.PrimitiveString), ir.AdmitsNo}, + {"a nullable string", nullableTo(ir.PrimitiveTypeID(ir.PrimitiveString)), ir.AdmitsYes}, + {"an alias whose Base admits null", refTo("type/nullableBase"), ir.AdmitsNo}, + {"a nullable reference to that alias", nullableTo("type/nullableBase"), ir.AdmitsYes}, + {"an alias of the top type", refTo("type/topAlias"), ir.AdmitsYes}, + {"a union one of whose variants admits null", refTo("type/variantNull"), ir.AdmitsYes}, + } { + assert.Equal(t, tc.want, reader.Admits(tc.ref, nullValue()), "%s", tc.name) + } +} + +// TestValueAdmissionReader_JudgesAValueByItsConstraints pins a bound or a +// pattern that excludes the value as a no, and a pattern outside the subset +// ir reads as unknown, which never refuses. +func TestValueAdmissionReader_JudgesAValueByItsConstraints(t *testing.T) { + t.Parallel() + registry := admissionTypes( + aliasOf("type/short", primitiveRef(ir.PrimitiveString), &ir.Constraints{MaxLength: new(int64(3))}), + aliasOf("type/patterned", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^a"}), + aliasOf("type/lookahead", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^(?=a)"}), + aliasOf("type/atLeast3", primitiveRef(ir.PrimitiveInteger), &ir.Constraints{Min: new(ir.BigVal("3"))}), + ) + reader := readerOver(registry, nil) + for _, tc := range []struct { + name string + ref ir.TypeRef + value ir.Value + want ir.Admission + }{ + {"a length within", refTo("type/short"), textValue("abc"), ir.AdmitsYes}, + {"a length past", refTo("type/short"), textValue("abcd"), ir.AdmitsNo}, + {"a pattern the value matches", refTo("type/patterned"), textValue("ab"), ir.AdmitsYes}, + {"a pattern the value does not match", refTo("type/patterned"), textValue("b"), ir.AdmitsNo}, + {"a pattern outside the subset, matched", refTo("type/lookahead"), textValue("ab"), ir.AdmitsUnknown}, + {"a pattern outside the subset, unmatched", refTo("type/lookahead"), textValue("b"), ir.AdmitsUnknown}, + {"a minimum met", refTo("type/atLeast3"), numberValue("3"), ir.AdmitsYes}, + {"a minimum missed", refTo("type/atLeast3"), numberValue("2"), ir.AdmitsNo}, + {"another kind", refTo("type/atLeast3"), textValue("3"), ir.AdmitsNo}, + } { + assert.Equal(t, tc.want, reader.Admits(tc.ref, tc.value), "%s", tc.name) + } +} + +// compositionTypes is the composition the model rows judge: B, an open object +// typing a and every other member as a string; C composing it with c; D +// requiring an integer z; CB, closed after composition over B; BU, closed +// after composition declaring a; CB2, closed after composition over BU, +// declaring b; DB requiring an integer b; CM, closed after composition over a +// map of strings; CK, closed after composition keeping a dependentSchemas; +// VBar and VBaz, closed after composition over a part requiring bar or baz, +// and their anyOf and oneOf; and a model a heuristic shaped. +func compositionTypes() []ir.TypeDef { + integer := primitiveRef(ir.PrimitiveInteger) + text := primitiveRef(ir.PrimitiveString) + model := func(id ir.TypeID, mode ir.AdditionalMode, base *ir.TypeRef, properties ...ir.Property) *ir.Model { + return &ir.Model{ID: id, Base: base, Additional: mode, Properties: properties} + } + b := model("type/B", ir.AdditionalUnspecified, nil, propertyOf("type/B", "a", integer, false)) + b.AdditionalProperties = &ir.AdditionalProperties{Value: &text} + return []ir.TypeDef{ + b, + model("type/C", ir.AdditionalUnspecified, new(refTo("type/B")), propertyOf("type/C", "c", primitiveRef(ir.PrimitiveBool), false)), + model("type/D", ir.AdditionalUnspecified, nil, propertyOf("type/D", "z", integer, true)), + model("type/DB", ir.AdditionalUnspecified, nil, propertyOf("type/DB", "b", integer, true)), + model("type/CB", ir.AdditionalClosedAfterComposition, new(refTo("type/B"))), + model("type/BU", ir.AdditionalClosedAfterComposition, nil, propertyOf("type/BU", "a", integer, false)), + model("type/CB2", ir.AdditionalClosedAfterComposition, new(refTo("type/BU")), propertyOf("type/CB2", "b", integer, false)), + model("type/Closed", ir.AdditionalClosed, nil, propertyOf("type/Closed", "a", integer, false)), + &ir.MapT{ID: "type/MapS", Value: text}, + model("type/CM", ir.AdditionalClosedAfterComposition, new(refTo("type/MapS"))), + &ir.Model{ID: "type/CK", Additional: ir.AdditionalClosedAfterComposition, Properties: []ir.Property{propertyOf("type/CK", "a", integer, false)}, + Unmodeled: ir.Unmodeled{"openapi:dependentSchemas": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{"a":{"properties":{"z":{}}}}`)}}}, + model("type/BarPart", ir.AdditionalUnspecified, nil, propertyOf("type/BarPart", "bar", text, true)), + model("type/BazPart", ir.AdditionalUnspecified, nil, propertyOf("type/BazPart", "baz", text, true)), + model("type/VBar", ir.AdditionalClosedAfterComposition, new(refTo("type/BarPart")), propertyOf("type/VBar", "foo", text, false)), + model("type/VBaz", ir.AdditionalClosedAfterComposition, new(refTo("type/BazPart")), propertyOf("type/VBaz", "foo", text, false)), + admissionUnion("type/AnyV", false, refTo("type/VBar"), refTo("type/VBaz")), + admissionUnion("type/OneV", true, refTo("type/VBar"), refTo("type/VBaz")), + &ir.Model{ID: "type/Inferred", Provenance: ir.Provenance{Inferred: "kind-inference"}, + Properties: []ir.Property{propertyOf("type/Inferred", "a", integer, false)}}, + admissionUnion("type/CorD", true, refTo("type/C"), refTo("type/D")), + admissionUnion("type/CB2orDB", true, refTo("type/CB2"), refTo("type/DB")), + } +} + +// TestValueAdmissionReader_JudgesAModelByItsComposition pins a Model judged as +// JSON Schema judges its composition: every model it composes along Base +// admits the object, each by its own closure over the members its own +// flattening declares none for, and a model closed after composition admits +// the members some model or map of its own composition evaluates. +func TestValueAdmissionReader_JudgesAModelByItsComposition(t *testing.T) { + t.Parallel() + reader := readerOver(admissionTypes(compositionTypes()...), nil) + for _, tc := range []struct { + name string + model ir.TypeID + value ir.Value + want ir.Admission + }{ + {"C refuses a member B's catch-all types as a string", "type/C", objectOf("z", numberValue("1")), ir.AdmitsNo}, + {"C refuses its own member by B's catch-all", "type/C", objectOf("c", boolValue(true)), ir.AdmitsNo}, + {"C admits a member B declares", "type/C", objectOf("a", numberValue("1")), ir.AdmitsYes}, + {"oneOf [C, D] admits what D alone admits", "type/CorD", objectOf("z", numberValue("1")), ir.AdmitsYes}, + {"D refuses an object missing its required member", "type/D", objectOf(), ir.AdmitsNo}, + {"CB admits a member B's catch-all evaluates", "type/CB", objectOf("a", numberValue("1"), "z", textValue("x")), ir.AdmitsYes}, + {"CB refuses one B's catch-all refuses", "type/CB", objectOf("z", numberValue("1")), ir.AdmitsNo}, + {"CB2 refuses a member BU's own composition does not evaluate", "type/CB2", objectOf("b", numberValue("1")), ir.AdmitsNo}, + {"so oneOf [CB2, DB] admits it, DB alone matching", "type/CB2orDB", objectOf("b", numberValue("1")), ir.AdmitsYes}, + {"and beside a member BU declares", "type/CB2orDB", objectOf("a", numberValue("1"), "b", numberValue("1")), ir.AdmitsYes}, + {"a closed model refuses a member it does not declare", "type/Closed", objectOf("x", numberValue("1")), ir.AdmitsNo}, + {"CM admits a member the map it composes evaluates", "type/CM", objectOf("z", textValue("s")), ir.AdmitsYes}, + {"and refuses one the map's catch-all refuses", "type/CM", objectOf("z", numberValue("1")), ir.AdmitsNo}, + {"BU, composing no catch-all, refuses a member it does not declare", "type/BU", objectOf("z", textValue("s")), ir.AdmitsNo}, + {"CK, keeping an applicator that may evaluate it, cannot tell", "type/CK", objectOf("a", numberValue("1"), "z", textValue("s")), ir.AdmitsUnknown}, + {"a model refuses what is no object", "type/D", numberValue("1"), ir.AdmitsNo}, + {"a model a heuristic shaped cannot tell of another kind", "type/Inferred", textValue("s"), ir.AdmitsUnknown}, + {"or of null", "type/Inferred", nullValue(), ir.AdmitsUnknown}, + {"nor of its own kind where a member is refused", "type/Inferred", objectOf("a", textValue("s")), ir.AdmitsNo}, + {"an anyOf whose variants each leave a member unevaluated cannot tell", "type/AnyV", + objectOf("foo", textValue("f"), "bar", textValue("b"), "baz", textValue("z")), ir.AdmitsUnknown}, + {"a oneOf of them refuses it", "type/OneV", objectOf("foo", textValue("f"), "bar", textValue("b"), "baz", textValue("z")), ir.AdmitsNo}, + {"an anyOf every variant of which refuses another way refuses", "type/AnyV", objectOf("foo", textValue("f")), ir.AdmitsNo}, + {"an anyOf a variant of which evaluates every member admits", "type/AnyV", objectOf("foo", textValue("f"), "bar", textValue("b")), ir.AdmitsYes}, + } { + assert.Equal(t, tc.want, reader.Admits(refTo(tc.model), tc.value), "%s", tc.name) + } +} + +// TestValueAdmissionReader_ReadsRequiredNamesAndCounts pins the members an +// object must hold, a declared one and one only Requires names, and the member +// counts the model's composition intersects (PropertyCountBounds). +func TestValueAdmissionReader_ReadsRequiredNamesAndCounts(t *testing.T) { + t.Parallel() + undeclared := &ir.Model{ID: "type/Undeclared", Requires: []string{"q"}} + counted := &ir.Model{ID: "type/Counted", Constraints: &ir.Constraints{MaxProperties: new(int64(1))}} + composing := &ir.Model{ID: "type/Composing", Base: new(refTo("type/Counted")), + Constraints: &ir.Constraints{MinProperties: new(int64(1))}} + reader := readerOver(admissionTypes(undeclared, counted, composing), nil) + for _, tc := range []struct { + name string + model ir.TypeID + value ir.Value + want ir.Admission + }{ + {"a name only Requires lists, absent", "type/Undeclared", objectOf(), ir.AdmitsNo}, + {"that name present", "type/Undeclared", objectOf("q", numberValue("1")), ir.AdmitsYes}, + {"more members than a count admits", "type/Counted", objectOf("a", numberValue("1"), "b", numberValue("2")), ir.AdmitsNo}, + {"a composed model's count intersected with its own, met", "type/Composing", objectOf("a", numberValue("1")), ir.AdmitsYes}, + {"the composed model's maximum, past", "type/Composing", objectOf("a", numberValue("1"), "b", numberValue("2")), ir.AdmitsNo}, + {"its own minimum, missed", "type/Composing", objectOf(), ir.AdmitsNo}, + } { + assert.Equal(t, tc.want, reader.Admits(refTo(tc.model), tc.value), "%s", tc.name) + } +} + +// TestValueAdmissionReader_AnswersUnknownWhereAFactIsUnread pins the yes that +// becomes unknown: a member only a pattern's catch-all could match, a member a +// union in a composition closed after it might evaluate, and a validation-only +// or degraded entry kept by a composed model or by a member's declaration, so +// a oneOf beside them refuses nothing they alone would decide. +func TestValueAdmissionReader_AnswersUnknownWhereAFactIsUnread(t *testing.T) { + t.Parallel() + integer := primitiveRef(ir.PrimitiveInteger) + kept := func(reason ir.UnmodeledReason) ir.Unmodeled { + return ir.Unmodeled{"openapi:not": {Reason: reason, Value: ir.RawValue(`{"required":["b"]}`)}} + } + patterned := &ir.Model{ID: "type/Patterned", Additional: ir.AdditionalClosed, + AdditionalProperties: &ir.AdditionalProperties{Patterns: []ir.PatternProperties{{Pattern: "^x", Value: integer}}}} + m1 := &ir.Model{ID: "type/M1", Properties: []ir.Property{propertyOf("type/M1", "m", integer, false)}} + m2 := &ir.Model{ID: "type/M2", Properties: []ir.Property{propertyOf("type/M2", "n", integer, false)}} + overUnion := &ir.Model{ID: "type/OverUnion", Additional: ir.AdditionalClosedAfterComposition, + Mixins: []ir.TypeRef{refTo("type/M1orM2")}} + notB := &ir.Model{ID: "type/NotB", Unmodeled: kept(ir.ReasonValidationOnly), + Properties: []ir.Property{propertyOf("type/NotB", "a", integer, false), propertyOf("type/NotB", "b", integer, false)}} + overNotB := &ir.Model{ID: "type/OverNotB", Base: new(refTo("type/NotB"))} + requiresB := &ir.Model{ID: "type/RequiresB", Properties: []ir.Property{propertyOf("type/RequiresB", "b", integer, true)}} + carried := propertyOf("type/Carrier", "p", primitiveRef(ir.PrimitiveString), true) + carried.Unmodeled = ir.Unmodeled{"openapi:not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{"const":"bad"}`)}} + carrier := &ir.Model{ID: "type/Carrier", Properties: []ir.Property{carried}} + plain := &ir.Model{ID: "type/Plain", Properties: []ir.Property{propertyOf("type/Plain", "p", primitiveRef(ir.PrimitiveString), true)}} + degraded := aliasOf("type/Degraded", primitiveRef(ir.PrimitiveString), nil) + degraded.Unmodeled = ir.Unmodeled{"openapi:maxLength": {Reason: ir.ReasonDegradedLowering, Value: ir.RawValue(`3`)}} + reader := readerOver(admissionTypes(patterned, m1, m2, overUnion, notB, overNotB, requiresB, carrier, plain, degraded, + admissionUnion("type/M1orM2", false, refTo("type/M1"), refTo("type/M2")), + admissionUnion("type/OverNotBorRequiresB", true, refTo("type/OverNotB"), refTo("type/RequiresB")), + admissionUnion("type/CarrierOrPlain", true, refTo("type/Carrier"), refTo("type/Plain")), + ), nil) + for _, tc := range []struct { + name string + ref ir.TypeID + value ir.Value + want ir.Admission + }{ + {"a member only a pattern matches", "type/Patterned", objectOf("xa", numberValue("1")), ir.AdmitsUnknown}, + {"a member only a variant of a composed union declares", "type/OverUnion", objectOf("m", numberValue("1")), ir.AdmitsUnknown}, + {"a validation-only entry on the model composed", "type/OverNotB", objectOf("b", numberValue("1")), ir.AdmitsUnknown}, + {"so oneOf beside it does not refuse", "type/OverNotBorRequiresB", objectOf("b", numberValue("1")), ir.AdmitsUnknown}, + {"a validation-only entry on a member's declaration", "type/Carrier", objectOf("p", textValue("bad")), ir.AdmitsUnknown}, + {"so oneOf beside that does not refuse", "type/CarrierOrPlain", objectOf("p", textValue("bad")), ir.AdmitsUnknown}, + {"a degraded entry on the node", "type/Degraded", textValue("abcd"), ir.AdmitsUnknown}, + {"a degraded entry still refuses another kind", "type/Degraded", numberValue("1"), ir.AdmitsNo}, + } { + assert.Equal(t, tc.want, reader.Admits(refTo(tc.ref), tc.value), "%s", tc.name) + } +} + +// TestValueAdmissionReader_ReadsATopTypedMemberByItsAliasBounds pins a member of +// a type whose chain ends at the top type, read inside a judged value by its +// alias's bounds, so oneOf counts no false yes, and null under a member of the +// top type admitted. +func TestValueAdmissionReader_ReadsATopTypedMemberByItsAliasBounds(t *testing.T) { + t.Parallel() + registry := admissionTypes( + aliasOf("type/P", primitiveRef(ir.PrimitiveAny), &ir.Constraints{MinLength: new(int64(5))}), + &ir.Model{ID: "type/M1", Properties: []ir.Property{propertyOf("type/M1", "p", refTo("type/P"), true)}}, + &ir.Model{ID: "type/M2", Properties: []ir.Property{propertyOf("type/M2", "p", primitiveRef(ir.PrimitiveString), true)}}, + &ir.Model{ID: "type/Top", Properties: []ir.Property{propertyOf("type/Top", "p", primitiveRef(ir.PrimitiveAny), true)}}, + admissionUnion("type/M1orM2", true, refTo("type/M1"), refTo("type/M2")), + ) + reader := readerOver(registry, nil) + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/M1orM2"), objectOf("p", textValue("ab"))), "M1 refuses ab by P's minimum length") + assert.Equal(t, ir.AdmitsNo, reader.Admits(refTo("type/M1orM2"), objectOf("p", textValue("abcdef"))), "both admit abcdef") + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/Top"), objectOf("p", nullValue())), "null under a member of the top type") +} + +// TestValueAdmissionReader_HoldsAValueToTheBoundsAnAliasChainAgreesOn pins an +// alias chain whose maximums no one value states, the nearer alias's 5 and the +// farther one's, which no Decimal reads: neither refuses a number, which the +// bound may still exclude, so one within the type answers unknown, past the +// nearer maximum or not, and one the type refuses answers no. +func TestValueAdmissionReader_HoldsAValueToTheBoundsAnAliasChainAgreesOn(t *testing.T) { + t.Parallel() + small := ir.PrimitiveTypeID(ir.PrimitiveUint8) + reader := readerOver(admissionTypes( + &ir.Primitive{ID: small, PrimitiveKind: ir.PrimitiveUint8}, + aliasOf("type/near", refTo("type/far"), &ir.Constraints{Max: new(ir.BigVal("5"))}), + aliasOf("type/far", refTo(small), &ir.Constraints{Max: new(ir.BigVal("1p4"))}), + ), nil) + + assert.Equal(t, ir.AdmitsUnknown, reader.Admits(refTo("type/near"), numberValue("100")), "past the nearer maximum") + assert.Equal(t, ir.AdmitsUnknown, reader.Admits(refTo("type/near"), numberValue("3")), "within it") + assert.Equal(t, ir.AdmitsNo, reader.Admits(refTo("type/near"), numberValue("300")), "past the type") +} + +// recordingSourceFormat is a source format answering answer for every kept +// entry and encoding, counting what it was asked. +type recordingSourceFormat struct { + answer ir.Admission + entries, codes *int +} + +// AdmitsUnderEncoding is ir.SourceFormatAdmissions.AdmitsUnderEncoding. +func (sourceFormat recordingSourceFormat) AdmitsUnderEncoding(*ir.Encoding, ir.Value) ir.Admission { + *sourceFormat.codes++ + return sourceFormat.answer +} + +// AdmitsUnderUnmodeledEntry is ir.SourceFormatAdmissions.AdmitsUnderUnmodeledEntry. +func (sourceFormat recordingSourceFormat) AdmitsUnderUnmodeledEntry(string, ir.UnmodeledEntry, ir.Value) ir.Admission { + *sourceFormat.entries++ + return sourceFormat.answer +} + +// TestValueAdmissionReader_AsksTheSourceFormatWhatItCannotRead pins a kept +// no_ir_home entry and an encoding ir does not read as the source format's: +// its yes and its no are facts read, and with no source format to ask each +// answers unknown, alone and as a variant of an anyOf or a oneOf, since no +// fact read says yes. +func TestValueAdmissionReader_AsksTheSourceFormatWhatItCannotRead(t *testing.T) { + t.Parallel() + keptLength := aliasOf("type/keptLength", primitiveRef(ir.PrimitiveString), nil) + keptLength.Unmodeled = ir.Unmodeled{"openapi:maxLength": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue(`3`)}} + encoded := aliasOf("type/encoded", primitiveRef(ir.PrimitiveString), nil) + encoded.Encoding = &ir.Encoding{Name: "x-unread", WireType: new(primitiveRef(ir.PrimitiveString))} + registry := admissionTypes(keptLength, encoded, + admissionUnion("type/keptOrInteger", true, refTo("type/keptLength"), primitiveRef(ir.PrimitiveInteger)), + admissionUnion("type/keptOrIntegerAny", false, refTo("type/keptLength"), primitiveRef(ir.PrimitiveInteger))) + value := textValue("abcd") + + unasked := readerOver(registry, nil) + assert.Equal(t, ir.AdmitsUnknown, unasked.Admits(refTo("type/keptLength"), value), "an entry no source format reads") + assert.Equal(t, ir.AdmitsUnknown, unasked.Admits(refTo("type/encoded"), textValue("zzz")), "an encoding no source format reads") + assert.Equal(t, ir.AdmitsUnknown, unasked.Admits(refTo("type/keptOrInteger"), value), "a oneOf of the entry") + assert.Equal(t, ir.AdmitsUnknown, unasked.Admits(refTo("type/keptOrIntegerAny"), value), "an anyOf of the entry") + + for _, answer := range []ir.Admission{ir.AdmitsYes, ir.AdmitsNo} { + entries, codes := 0, 0 + reader := readerOver(registry, recordingSourceFormat{answer: answer, entries: &entries, codes: &codes}) + assert.Equal(t, answer, reader.Admits(refTo("type/keptLength"), value), "the source format's %v on the entry", answer) + assert.Equal(t, answer, reader.Admits(refTo("type/keptOrInteger"), value), "counted by the oneOf as read") + assert.Equal(t, answer, reader.Admits(refTo("type/encoded"), value), "the source format's %v on the encoding", answer) + assert.Positive(t, entries, "the kept entry is asked") + assert.Positive(t, codes, "the encoding is asked") + } +} + +// nestedList is a value of depth lists, each holding the next, the innermost +// holding a string. +func nestedList(depth int) ir.Value { + value := textValue("leaf") + for range depth { + value = ir.Value{Kind: ir.ValueList, List: []ir.Value{value}} + } + return value +} + +// TestValueAdmissionReader_JudgesNoDeeperThanItsBound pins the value's depth +// as the reader's only recursion, held to 64 levels: a value nested 64 lists +// deep is judged and one 65 deep answers unknown. +func TestValueAdmissionReader_JudgesNoDeeperThanItsBound(t *testing.T) { + t.Parallel() + nested := &ir.List{ID: "type/nested", ElementType: refTo("type/listOrText")} + registry := admissionTypes(nested, + admissionUnion("type/listOrText", false, refTo("type/nested"), primitiveRef(ir.PrimitiveString))) + reader := readerOver(registry, nil) + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/listOrText"), nestedList(64))) + assert.Equal(t, ir.AdmitsUnknown, reader.Admits(refTo("type/listOrText"), nestedList(65))) + assert.Equal(t, ir.AdmitsNo, reader.Admits(refTo("type/nested"), boolValue(true)), "a shallow value is still refused") +} + +// TestValueAdmissionReader_AnswersACycleOfUnionsAlikeInEveryOrder pins the +// cycle A anyOf [B, C], B anyOf [A, integer], C anyOf [B, string]: every member +// of a component holding a cycle answers unknown, whichever variant order or +// entry the walk takes, and a union outside it reads that answer. +func TestValueAdmissionReader_AnswersACycleOfUnionsAlikeInEveryOrder(t *testing.T) { + t.Parallel() + registry := admissionTypes( + admissionUnion("type/A", false, refTo("type/B"), refTo("type/C")), + admissionUnion("type/B", false, refTo("type/A"), primitiveRef(ir.PrimitiveInteger)), + admissionUnion("type/C", false, refTo("type/B"), primitiveRef(ir.PrimitiveString)), + admissionUnion("type/AC", false, refTo("type/A"), refTo("type/C")), + admissionUnion("type/CA", false, refTo("type/C"), refTo("type/A")), + ) + for _, value := range []ir.Value{textValue("x"), numberValue("1"), boolValue(true)} { + answers := map[ir.TypeID]ir.Admission{} + for _, id := range []ir.TypeID{"type/AC", "type/CA", "type/A", "type/B", "type/C"} { + answers[id] = readerOver(registry, nil).Admits(refTo(id), value) + } + assert.Equal(t, answers["type/AC"], answers["type/CA"], "anyOf [A, C] and anyOf [C, A] on %v", value) + for _, id := range []ir.TypeID{"type/A", "type/B", "type/C"} { + assert.Equal(t, ir.AdmitsUnknown, answers[id], "%s on %v", id, value) + } + } +} + +// chainTypes is a chain of n aliases over a bounded integer, I1 over I0 and +// each next over the one before, the shape many defaults over one chain read. +func chainTypes(count int) ir.TypeRegistry { + registry := admissionTypes(aliasOf("type/I0", primitiveRef(ir.PrimitiveInteger), &ir.Constraints{Max: new(ir.BigVal("5"))})) + for i := 1; i <= count; i++ { + id := ir.TypeID(fmt.Sprintf("type/I%d", i)) + registry[id] = aliasOf(id, refTo(ir.TypeID(fmt.Sprintf("type/I%d", i-1))), nil) + } + return registry +} + +// marginalGrowthHolds reports whether costs at n, 2n and 4n grow no faster than +// linearly: the second increment at most 2.5 times the first. +func marginalGrowthHolds(costs [3]int) bool { + return float64(costs[2]-costs[1]) <= 2.5*float64(costs[1]-costs[0]) +} + +// TestValueAdmissionReader_ReadsEachChainOnceForManyValues pins one reader +// judging a default on every link of a long chain: its lookups, the alias +// index's included, grow linearly in the chain, each link read once for the +// life of the reader. +func TestValueAdmissionReader_ReadsEachChainOnceForManyValues(t *testing.T) { + t.Parallel() + var costs [3]int + for i, n := range []int{1000, 2000, 4000} { + registry := chainTypes(n) + reads := 0 + lookup := admissionLookupOf(registry, &reads) + reader := ir.NewValueAdmissionReader(lookup, ir.NewAliasChainIndex(lookup), nil) + for link := 1; link <= n; link++ { + id := ir.TypeID(fmt.Sprintf("type/I%d", link)) + assert.Equal(t, ir.AdmitsNo, reader.Admits(refTo(id), numberValue("7")), "%s refuses 7 by I0's maximum", id) + } + costs[i] = reads + } + assert.True(t, marginalGrowthHolds(costs), "lookups at 1,000, 2,000 and 4,000 links: %v", costs) +} + +// unionOfModels is the oneOf type/U of n models, M_i requiring k_i, which +// the object holding k_i alone matches. +func unionOfModels(count int) ir.TypeRegistry { + registry := admissionTypes() + union := &ir.Union{ID: "type/U", Exclusive: true, Closed: true} + for i := range count { + id := ir.TypeID(fmt.Sprintf("type/M%d", i)) + registry[id] = &ir.Model{ID: id, Properties: []ir.Property{propertyOf(id, fmt.Sprintf("k%d", i), primitiveRef(ir.PrimitiveString), true)}} + union.Variants = append(union.Variants, ir.Variant{Type: refTo(id)}) + } + registry[union.ID] = union + return registry +} + +// TestValueAdmissionReader_ReadsEachModelOnceForManyValues pins one reader +// judging many values against a oneOf of many models: its lookups do not grow +// with the values, each model read once for the reader's life, where reading +// them again for each value would grow with the values times the models. +func TestValueAdmissionReader_ReadsEachModelOnceForManyValues(t *testing.T) { + t.Parallel() + const models = 50 + var costs [3]int + for i, values := range []int{models, 2 * models, 4 * models} { + reads := 0 + lookup := admissionLookupOf(unionOfModels(models), &reads) + reader := ir.NewValueAdmissionReader(lookup, ir.NewAliasChainIndex(lookup), nil) + for j := range values { + value := objectOf(fmt.Sprintf("k%d", j%models), textValue("x")) + require.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/U"), value), "value %d", j) + } + costs[i] = reads + } + assert.Equal(t, costs[0], costs[2], "lookups for 50, 100 and 200 values over 50 models: %v", costs) +} + +// TestValueAdmissionReader_RefusesAVariantLackingARequiredMemberAsItsModelWould +// pins a union's variant refused for a required member an object lacks +// (requiredBy) to the answer opening its model gives: the variant matching +// admits, an object lacking both is refused, as is one lacking a member a +// composed model's base requires, a variant read through an alias of its model +// refuses alike, a model whose composition holds +// an unflattened entry closing a cycle answers unknown, a model a heuristic +// shaped answers a string unknown, and a cyclic alias chain beside a refused +// variant leaves the union unknown; an object of more members than a scan +// reads is read alike. +func TestValueAdmissionReader_RefusesAVariantLackingARequiredMemberAsItsModelWould(t *testing.T) { + t.Parallel() + requiring := func(id ir.TypeID, member string) *ir.Model { + return &ir.Model{ID: id, Properties: []ir.Property{propertyOf(id, member, primitiveRef(ir.PrimitiveString), true)}} + } + composed := requiring("type/C", "c") + composed.Base = new(refTo("type/A")) + cyclic := requiring("type/cyclic", "a") + cyclic.Mixins = []ir.TypeRef{refTo("type/through-cycle")} + inferred := requiring("type/inferred", "a") + inferred.Provenance.Inferred = "kind-inference" + assertAdmissions(t, admissionTypes( + requiring("type/A", "a"), requiring("type/B", "b"), + admissionUnion("type/A-or-B", true, refTo("type/A"), refTo("type/B")), + composed, admissionUnion("type/C-or-B", true, refTo("type/C"), refTo("type/B")), + aliasOf("type/A-alias", refTo("type/A"), nil), admissionUnion("type/A-alias-or-B", true, refTo("type/A-alias"), refTo("type/B")), + cyclic, admissionUnion("type/through-cycle", false, refTo("type/cyclic")), + inferred, admissionUnion("type/of-inferred", true, refTo("type/inferred")), + aliasOf("type/loop-a", refTo("type/loop-b"), nil), aliasOf("type/loop-b", refTo("type/loop-a"), nil), + admissionUnion("type/loop-or-A", true, refTo("type/loop-a"), refTo("type/A")), + ), []admissionRow{ + {"the variant whose member the object holds", refTo("type/A-or-B"), objectOf("a", textValue("x")), ir.AdmitsYes}, + {"an object lacking both", refTo("type/A-or-B"), objectOf(), ir.AdmitsNo}, + {"one lacking a member a composed model's base requires", refTo("type/C-or-B"), objectOf("c", textValue("x")), ir.AdmitsNo}, + {"one holding it", refTo("type/C-or-B"), objectOf("a", textValue("x"), "c", textValue("x")), ir.AdmitsYes}, + {"one A refuses through an alias of it", refTo("type/A-alias-or-B"), objectOf("b", textValue("x")), ir.AdmitsYes}, + {"a model closing a cycle", refTo("type/through-cycle"), objectOf(), ir.AdmitsUnknown}, + {"a string, at a model a heuristic shaped", refTo("type/of-inferred"), textValue("x"), ir.AdmitsUnknown}, + {"an object A refuses, beside a cyclic chain", refTo("type/loop-or-A"), objectOf(), ir.AdmitsUnknown}, + {"a larger object holding a", refTo("type/A-or-B"), manyMembers("a"), ir.AdmitsYes}, + {"a larger object holding neither", refTo("type/A-or-B"), manyMembers("z"), ir.AdmitsNo}, + }) +} + +// manyMembers is an object of more members than an object's scan reads, +// named m0 to m8, and name, each a string. +func manyMembers(name string) ir.Value { + value := objectOf(name, textValue("x")) + for i := range 9 { + value.Object = append(value.Object, ir.Field{Name: fmt.Sprintf("m%d", i), Value: textValue("x")}) + } + return value +} + +// TestValueAdmissionReader_JudgesAOneOfOfModelsInAllocationsItsVariantsDoNotGrow +// pins a variant refused for a required member an object lacks without its +// model opened: judging an object against a oneOf of 64 models, each requiring +// a member of its own, allocates no more than against one of 2, where opening +// each model grows the walk's state with the variants. It is not run in +// parallel: AllocsPerRun measures the process. +func TestValueAdmissionReader_JudgesAOneOfOfModelsInAllocationsItsVariantsDoNotGrow(t *testing.T) { + var allocations [2]float64 + for i, models := range []int{2, 64} { + reader := readerOver(unionOfModels(models), nil) + value := objectOf("k1", textValue("x")) + require.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/U"), value)) + allocations[i] = testing.AllocsPerRun(20, func() { reader.Admits(refTo("type/U"), value) }) + } + assert.Equal(t, allocations[0], allocations[1], "allocations against 2 and 64 variants") +} + +// TestValueAdmissionReader_TakesAJudgmentForEachTypeAndValueNode pins what +// AdmitsAtPositionWithin counts: one judgment for a leaf, three for a oneOf +// of two primitives, the union and each variant, and three for a list of two +// integers, the list and each element. Within that many it answers as +// AdmitsAtPosition does, spending them all, and one fewer stops it, unknown, +// as does a negative limit. +func TestValueAdmissionReader_TakesAJudgmentForEachTypeAndValueNode(t *testing.T) { + t.Parallel() + registry := admissionTypes( + admissionUnion("type/int-or-text", true, primitiveRef(ir.PrimitiveInteger), primitiveRef(ir.PrimitiveString)), + &ir.List{ID: "type/integers", ElementType: primitiveRef(ir.PrimitiveInteger)}, + ) + reader := readerOver(registry, nil) + for _, tc := range []struct { + row admissionRow + judgments int + }{ + {admissionRow{"a leaf", primitiveRef(ir.PrimitiveString), textValue("a"), ir.AdmitsYes}, 1}, + {admissionRow{"a union", refTo("type/int-or-text"), numberValue("3"), ir.AdmitsYes}, 3}, + {admissionRow{"a list", refTo("type/integers"), listValueOf(numberValue("1"), textValue("2")), ir.AdmitsNo}, 3}, + } { + admission, spent, ok := reader.AdmitsAtPositionWithin(tc.row.ref, nil, tc.row.value, tc.judgments+2) + assert.Equal(t, []any{tc.row.want, tc.judgments, true}, []any{admission, spent, ok}, "%s, with judgments to spare", tc.row.name) + admission, spent, ok = reader.AdmitsAtPositionWithin(tc.row.ref, nil, tc.row.value, tc.judgments) + assert.Equal(t, []any{tc.row.want, tc.judgments, true}, []any{admission, spent, ok}, "%s, within them", tc.row.name) + admission, spent, ok = reader.AdmitsAtPositionWithin(tc.row.ref, nil, tc.row.value, tc.judgments-1) + assert.Equal(t, []any{ir.AdmitsUnknown, tc.judgments - 1, false}, []any{admission, spent, ok}, "%s, one short", tc.row.name) + admission, spent, ok = reader.AdmitsAtPositionWithin(tc.row.ref, nil, tc.row.value, -1) + assert.Equal(t, []any{ir.AdmitsUnknown, 0, false}, []any{admission, spent, ok}, "%s, below none", tc.row.name) + } +} + +// TestValueAdmissionReader_ReadsAnEnumsMembersOnce pins an enum's members +// read once for every value judged: a member listed after a first judgment is +// read neither by that reader nor by one it makes Fresh, which shares what it +// read of them, and a new reader reads it. +func TestValueAdmissionReader_ReadsAnEnumsMembersOnce(t *testing.T) { + t.Parallel() + enum := &ir.Enum{ID: "type/E", ValueType: ir.PrimitiveString, Closed: true, Members: []ir.EnumMember{{Value: textValue("red")}}} + registry := admissionTypes(enum) + reader := readerOver(registry, nil) + require.Equal(t, ir.AdmitsNo, reader.Admits(refTo("type/E"), textValue("green"))) + + enum.Members = append(enum.Members, ir.EnumMember{Value: textValue("green")}) + assert.Equal(t, ir.AdmitsNo, reader.Admits(refTo("type/E"), textValue("green")), "the members as the reader first read them") + assert.Equal(t, ir.AdmitsNo, reader.Fresh().Admits(refTo("type/E"), textValue("green")), "and as a Fresh reader shares them") + assert.Equal(t, ir.AdmitsYes, readerOver(registry, nil).Admits(refTo("type/E"), textValue("green")), "a new reader reads them anew") +} + +// nestedUnionTypes is the nesting of d unions, L_j oneOf [A_j, B_j], each a +// closed model declaring x of L_j+1 and a member named for its side, L_d an +// alias of string. +func nestedUnionTypes(d int) ir.TypeRegistry { + registry := admissionTypes() + for j := range d { + next := refTo(ir.TypeID(fmt.Sprintf("type/L%d", j+1))) + for _, side := range []string{"A", "B"} { + id := ir.TypeID(fmt.Sprintf("type/%s%d", side, j)) + registry[id] = &ir.Model{ID: id, Additional: ir.AdditionalClosed, Properties: []ir.Property{ + propertyOf(id, "x", next, false), propertyOf(id, side, primitiveRef(ir.PrimitiveString), false), + }} + } + union := admissionUnion(ir.TypeID(fmt.Sprintf("type/L%d", j)), true, + refTo(ir.TypeID(fmt.Sprintf("type/A%d", j))), refTo(ir.TypeID(fmt.Sprintf("type/B%d", j)))) + registry[union.ID] = union + } + id := ir.TypeID(fmt.Sprintf("type/L%d", d)) + registry[id] = aliasOf(id, primitiveRef(ir.PrimitiveString), nil) + return registry +} + +// TestValueAdmissionReader_JudgesNestedUnionsInLinearSteps pins the memo of a +// closed component's answers: nested unions over a nested value, every variant +// judged, which without it doubles the judgments at each level, read the +// registry linearly in the depth, and A_j alone admitting each level. +func TestValueAdmissionReader_JudgesNestedUnionsInLinearSteps(t *testing.T) { + t.Parallel() + var costs [3]int + for i, d := range []int{4, 8, 16} { + value := textValue("leaf") + for range d { + value = objectOf("x", value, "A", textValue("a")) + } + reads := 0 + lookup := admissionLookupOf(nestedUnionTypes(d), &reads) + reader := ir.NewValueAdmissionReader(lookup, ir.NewAliasChainIndex(lookup), nil) + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/L0"), value), "B_j refuses the member A at each level") + costs[i] = reads + } + assert.True(t, marginalGrowthHolds(costs), "lookups at depths 4, 8 and 16: %v", costs) +} + +// TestValueAdmissionReader_HoldsAModelAsItReadItUntilFresh pins what one reader +// holds between calls: a model as it first read it, so a member required since +// goes unread by the next call, while a Fresh reader reads it as it is, as it +// does an Unmodeled entry kept on the model since and a model registered in its +// place since. +func TestValueAdmissionReader_HoldsAModelAsItReadItUntilFresh(t *testing.T) { + t.Parallel() + model := &ir.Model{ID: "type/M", Properties: []ir.Property{propertyOf("type/M", "a", primitiveRef(ir.PrimitiveString), false)}} + registry := admissionTypes(model, aliasOf("type/M-alias", refTo("type/M"), nil)) + reader := readerOver(registry, nil) + value := objectOf("a", textValue("x")) + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/M-alias"), value)) + + model.Properties = append(model.Properties, propertyOf("type/M", "b", primitiveRef(ir.PrimitiveString), true)) + assert.Equal(t, ir.AdmitsYes, reader.Admits(refTo("type/M-alias"), value), "the model as the reader first read it") + assert.Equal(t, ir.AdmitsNo, reader.Fresh().Admits(refTo("type/M-alias"), value), "a member required since") + + model.Properties = model.Properties[:1] + model.Unmodeled = ir.Unmodeled{"not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{}`)}} + assert.Equal(t, ir.AdmitsUnknown, reader.Fresh().Admits(refTo("type/M-alias"), value), "an entry kept since") + + registry["type/M"] = &ir.Model{ID: "type/M", Properties: []ir.Property{propertyOf("type/M", "b", primitiveRef(ir.PrimitiveString), true)}} + assert.Equal(t, ir.AdmitsNo, reader.Fresh().Admits(refTo("type/M-alias"), value), "a model registered in its place since") +} + +// TestValueAdmissionReader_JudgesAPositionsOwnBoundsBesideItsType pins +// AdmitsAtPosition: a value is judged against the type, as Admits judges it, +// and against the bounds the position declares beside it, each binding a +// value of its kind, a pattern outside the subset ir reads leaving a yes +// unknown, over a leaf, an enum whose own bound refuses one of its members, +// and a list a walk of the value judges. +func TestValueAdmissionReader_JudgesAPositionsOwnBoundsBesideItsType(t *testing.T) { + t.Parallel() + registry := admissionTypes( + &ir.Enum{ID: "type/capped", ValueType: ir.PrimitiveInteger, Closed: true, + Members: []ir.EnumMember{{Value: numberValue("1")}, {Value: numberValue("2")}}, Constraints: &ir.Constraints{Max: new(ir.BigVal("1"))}}, + &ir.List{ID: "type/list", ElementType: primitiveRef(ir.PrimitiveInteger)}, + &ir.List{ID: "type/list-of-ghosts", ElementType: refTo("type/ghost")}, + ) + reader := readerOver(registry, nil) + atMostOne := &ir.Constraints{Max: new(ir.BigVal("1"))} + for _, tc := range []struct { + name string + ref ir.TypeRef + own *ir.Constraints + value ir.Value + want ir.Admission + }{ + {"within the position's bound", primitiveRef(ir.PrimitiveInteger), atMostOne, numberValue("1"), ir.AdmitsYes}, + {"past it, though the type admits it", primitiveRef(ir.PrimitiveInteger), atMostOne, numberValue("2"), ir.AdmitsNo}, + {"of a kind the type refuses, within it", primitiveRef(ir.PrimitiveInteger), atMostOne, textValue("1"), ir.AdmitsNo}, + {"a pattern the value matches", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^a"}, textValue("a"), ir.AdmitsYes}, + {"a pattern the value does not match", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^a"}, textValue("b"), ir.AdmitsNo}, + {"a pattern outside the subset ir reads", primitiveRef(ir.PrimitiveString), &ir.Constraints{Pattern: "^(?=a)"}, textValue("a"), ir.AdmitsUnknown}, + {"null at a nullable reference, which no bound binds", nullableTo(ir.PrimitiveTypeID(ir.PrimitiveString)), + &ir.Constraints{MinLength: new(int64(1))}, nullValue(), ir.AdmitsYes}, + {"an enum's member its own bound refuses", refTo("type/capped"), nil, numberValue("2"), ir.AdmitsNo}, + {"the member it admits", refTo("type/capped"), nil, numberValue("1"), ir.AdmitsYes}, + {"a list within the position's count", refTo("type/list"), &ir.Constraints{MaxItems: new(int64(1))}, + listValueOf(numberValue("1")), ir.AdmitsYes}, + {"a list past it", refTo("type/list"), &ir.Constraints{MaxItems: new(int64(1))}, + listValueOf(numberValue("1"), numberValue("2")), ir.AdmitsNo}, + {"repeated items where the position holds them distinct", refTo("type/list"), &ir.Constraints{UniqueItems: true}, + listValueOf(numberValue("1"), numberValue("1e0")), ir.AdmitsNo}, + {"an element of a type the registry does not hold", refTo("type/list-of-ghosts"), nil, + listValueOf(numberValue("1")), ir.AdmitsUnknown}, + {"a value of that type", refTo("type/ghost"), nil, numberValue("1"), ir.AdmitsUnknown}, + } { + assert.Equal(t, tc.want, reader.AdmitsAtPosition(tc.ref, tc.own, tc.value), tc.name) + if tc.own == nil { + assert.Equal(t, tc.want, reader.Admits(tc.ref, tc.value), "Admits is a position declaring no bounds: %s", tc.name) + } + } +} + +// TestValueAdmissionReader_JudgesALeafWithoutAllocating holds the claim that +// judging a value of a primitive, an alias bounding one, an enum or a literal +// allocates nothing of the reader's own, the path every scalar default of a +// document takes; a number spelled with a point is left out, as reading it +// (ir.BigVal.Decimal) allocates. It is not run in parallel: AllocsPerRun +// measures the process. +func TestValueAdmissionReader_JudgesALeafWithoutAllocating(t *testing.T) { + registry := admissionTypes( + aliasOf("type/short", primitiveRef(ir.PrimitiveString), &ir.Constraints{MaxLength: new(int64(5))}), + &ir.Enum{ID: "type/colors", ValueType: ir.PrimitiveString, Closed: true, + Members: []ir.EnumMember{{Value: textValue("red")}, {Value: textValue("green")}}}, + &ir.Literal{ID: "type/one", Value: numberValue("1")}, + ) + reader := readerOver(registry, nil) + own := &ir.Constraints{MinLength: new(int64(1)), MaxLength: new(int64(10))} + for _, row := range []admissionRow{ + {"a primitive", primitiveRef(ir.PrimitiveString), textValue("d"), ir.AdmitsYes}, + {"an alias bounding one", refTo("type/short"), textValue("d"), ir.AdmitsYes}, + {"an enum", refTo("type/colors"), textValue("green"), ir.AdmitsYes}, + {"a literal", refTo("type/one"), numberValue("1e0"), ir.AdmitsYes}, + } { + require.Equal(t, row.want, reader.AdmitsAtPosition(row.ref, own, row.value), row.name) + allocations := testing.AllocsPerRun(20, func() { reader.AdmitsAtPosition(row.ref, own, row.value) }) + assert.Zero(t, allocations, row.name) + } +} + +// TestValueAdmissionReader_ComparesTwoScalarsAsTheirSpellingsWould pins the +// comparison of a literal's or an enum member's scalar value with the value +// judged, made without spelling either: one kind and value alike, a number by +// its magnitude, and two kinds or two values apart, a number no Decimal holds +// left unknown. +func TestValueAdmissionReader_ComparesTwoScalarsAsTheirSpellingsWould(t *testing.T) { + t.Parallel() + registry := admissionTypes( + &ir.Literal{ID: "type/text", Value: textValue("red")}, + &ir.Literal{ID: "type/number", Value: numberValue("1")}, + &ir.Literal{ID: "type/true", Value: boolValue(true)}, + &ir.Literal{ID: "type/null", Value: nullValue()}, + ) + assertAdmissions(t, registry, []admissionRow{ + {"the text", refTo("type/text"), textValue("red"), ir.AdmitsYes}, + {"another text", refTo("type/text"), textValue("green"), ir.AdmitsNo}, + {"the number spelled otherwise", refTo("type/number"), numberValue("1e0"), ir.AdmitsYes}, + {"another number", refTo("type/number"), numberValue("2"), ir.AdmitsNo}, + {"the text the number spells", refTo("type/number"), textValue("1"), ir.AdmitsNo}, + {"a number no Decimal holds", refTo("type/number"), numberValue("1p4"), ir.AdmitsUnknown}, + {"the bool", refTo("type/true"), boolValue(true), ir.AdmitsYes}, + {"the other bool", refTo("type/true"), boolValue(false), ir.AdmitsNo}, + {"null, the literal's value", refTo("type/null"), nullValue(), ir.AdmitsYes}, + }) +} diff --git a/ir/admission_walk.go b/ir/admission_walk.go new file mode 100644 index 000000000..e52c623e1 --- /dev/null +++ b/ir/admission_walk.go @@ -0,0 +1,243 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "github.com/dexpace/morphic/stronglyconnected" + +// admissionFrame is one type a value node's walk has opened: its edges to the +// types judged against the same value node (a union's variants, a model's +// unflattened composition entries), and what is read off them so far. +type admissionFrame struct { + node TypeDef + edges []admissionEdge + // outcomes holds each edge's answer as it was judged before the type it + // ends on, one for each edge followed. + outcomes []edgeOutcome + // opened lists, in order, the types the edges that open one end on, whose + // answers the type reads once each is judged. + opened []TypeID + // local is what the type itself decides, beside its edges. + local admissionAnswer + // selfEdge reports that an edge ends on the type itself. + selfEdge bool +} + +// edgeOutcome is what one edge of a frame decided before the type it ends on +// was judged, and whether that type is judged through it. +type edgeOutcome struct { + judged admissionAnswer + // opens reports that the edge's end is judged beside it, whose answer + // joins judged once it is. + opens bool +} + +// admissionEdge is one edge of a frame: the reference it follows, and what a +// union's variant keeps beside it. +type admissionEdge struct { + ref TypeRef + unmodeled Unmodeled + // requires lists the members the model the edge's alias chain ends on + // requires, where that model composes models and has no edges of its own, + // and alone is that model where it composes nothing (requiredBy); both are + // nil where the edge reads none. + requires []string + alone *Model +} + +// admissionSearch is the state of one value node's walk, the visitor of a +// stronglyconnected.Search over the types its edges reach, each answer +// committed once its component closes. +type admissionSearch struct { + call *admissionCall + value *Value + // members answers which members value holds, where it is an object. + members objectMembers + depth int + // frames holds each type met whose component is not closed. + frames map[TypeID]*admissionFrame +} + +// judgeNode judges value against the type id names, an end no alias chain +// passes, by a walk over the types its edges reach at the same value node, +// committing answers by strongly connected component. Every edge is judged +// with no early exit, no answer is read before its component closes, and a +// component holding a cycle answers unknown. Each type opened takes a +// judgment, and one with none left answers unknown. +func (call *admissionCall) judgeNode(id TypeID, value *Value, depth int) admissionAnswer { + if judged, settled := call.memo[admissionKey{id, value}]; settled { + return judged + } + if !call.take() { + return undecided() + } + search := &admissionSearch{call: call, value: value, members: objectMembers{value: value}, depth: depth, + frames: map[TypeID]*admissionFrame{}} + stronglyconnected.NewSearch[TypeID](search).From(id) + return call.memo[admissionKey{id, value}] +} + +// Edge returns the type from's edge at index ends on, which the search follows +// where it is judged beside the edge, and false past from's last edge. The +// first ask of a type opens it: its own answer and its edges. +func (search *admissionSearch) Edge(from TypeID, index int) (to TypeID, follow, more bool) { + frame := search.frames[from] + if index == 0 { + frame = search.openFrame(from) + } + if index == len(frame.edges) { + return "", false, false + } + to, follow = search.followEdge(from, frame, &frame.edges[index]) + return to, follow, true +} + +// openFrame opens the type id: its own answer and its edges. +func (search *admissionSearch) openFrame(id TypeID) *admissionFrame { + node := search.call.reader.nodeOf(id) + local, edges := search.call.localAnswer(id, node, search.value, search.depth) + frame := &admissionFrame{node: node, edges: edges, outcomes: make([]edgeOutcome, 0, len(edges)), local: local} + search.frames[id] = frame + return frame +} + +// followEdge judges edge of the frame of the type from, records what it +// decides, and returns the type it ends on and whether the search is to follow +// it: a type opened for the first time, which takes a judgment, or one on the +// stack, which joins the cycle and is unknown meanwhile. +func (search *admissionSearch) followEdge(from TypeID, frame *admissionFrame, edge *admissionEdge) (TypeID, bool) { + if search.lacksRequired(edge) { + search.call.take() // spent as opening the model would; a call past its limit answers unknown + frame.record(refused(), false) + return "", false + } + judged, end, endLeftToJudge := search.call.throughChain(edge.ref, search.value, search.depth) + if edge.unmodeled != nil { + judged = judged.and(keptEntryAnswer(edge.unmodeled, search.call.reader.sourceFormats, search.value)) + } + if !endLeftToJudge { + frame.record(judged, false) + return "", false + } + if settled, closed := search.call.memo[admissionKey{end, search.value}]; closed { + frame.record(judged.and(settled), false) + return "", false + } + if _, onStack := search.frames[end]; onStack { + frame.selfEdge = frame.selfEdge || end == from + frame.record(undecided(), false) + return end, true + } + if !search.call.take() { + frame.record(undecided(), false) + return "", false + } + frame.record(judged, true) + frame.opened = append(frame.opened, end) + return end, true +} + +// record keeps what an edge decided, and whether its end is judged beside it. +func (frame *admissionFrame) record(judged admissionAnswer, opens bool) { + frame.outcomes = append(frame.outcomes, edgeOutcome{judged: judged, opens: opens}) +} + +// lacksRequired reports whether the value, an object, lacks a member edge +// requires. Opening the model the edge ends on would then judge it no whatever +// else holds, as no edge of its own can place it in a cycle. A frame is open +// only within the depth a walk judges at (throughChain). +func (search *admissionSearch) lacksRequired(edge *admissionEdge) bool { + switch { + case search.value.Kind != ValueObject: + return false + case edge.alone != nil: + return lacksOwnRequired(edge.alone, &search.members) + default: + return edge.requires != nil && requiredAnswer(edge.requires, &search.members).admission == AdmitsNo + } +} + +// LeaveVertex has nothing to keep of a type left: its component's answer is +// committed as the component closes. +func (*admissionSearch) LeaveVertex(TypeID) {} + +// CloseComponent commits the answers of the component whose first member is +// members[0]: that type's own, where it is alone and reaches itself by no edge, +// and unknown for every member of one holding a cycle. +func (search *admissionSearch) CloseComponent(members []TypeID) { + root := search.frames[members[0]] + if len(members) > 1 || root.selfEdge { + for _, id := range members { + search.call.memo[admissionKey{id, search.value}] = undecided() + } + } else { + search.call.memo[admissionKey{members[0], search.value}] = search.combineEdges(root) + } + for _, id := range members { + delete(search.frames, id) + } +} + +// edgeAnswers returns the answer of each edge of frame, a type its edge +// opened joined by what that type was judged. A component alone has judged +// each type its edges opened before it closes; an answer not held is the zero +// one, which is unknown. +func (search *admissionSearch) edgeAnswers(frame *admissionFrame) []admissionAnswer { + answers := make([]admissionAnswer, len(frame.outcomes)) + opened := frame.opened + for i, outcome := range frame.outcomes { + answers[i] = outcome.judged + if !outcome.opens { + continue + } + answers[i] = outcome.judged.and(search.call.memo[admissionKey{opened[0], search.value}]) + opened = opened[1:] + } + return answers +} + +// combineEdges is a closed frame's answer from its own and its edges': a +// union counts its variants (unionAnswer), and any other node holds each edge +// beside its own. +func (search *admissionSearch) combineEdges(done *admissionFrame) admissionAnswer { + edgeAnswers := search.edgeAnswers(done) + if union, isUnion := done.node.(*Union); isUnion { + return done.local.and(unionAnswer(union, edgeAnswers)) + } + judged := done.local + for _, edge := range edgeAnswers { + judged = judged.and(edge) + } + return judged +} + +// unionAnswer counts a union's variants as anyOf or, where Exclusive, oneOf +// does. Every variant refusing is unknown where the union is open, which may +// hold a variant it does not list, and for an anyOf where one refuses only +// members it leaves unevaluated, which another matching variant may evaluate. +func unionAnswer(union *Union, variants []admissionAnswer) admissionAnswer { + var yes, no int + unevaluated := false + for _, judged := range variants { + switch judged.admission { + case AdmitsYes: + yes++ + case AdmitsNo: + no++ + unevaluated = unevaluated || judged.unevaluatedOnly + case AdmitsUnknown: + } + } + switch { + case no == len(variants) && union.Closed && (!unevaluated || union.Exclusive): + return refused() + case !union.Exclusive && yes > 0: + return admitted() + case union.Exclusive && yes > 1: + return refused() + case union.Exclusive && yes == 1 && no == len(variants)-1: + return admitted() + default: + return undecided() + } +} diff --git a/ir/aliaschain.go b/ir/aliaschain.go new file mode 100644 index 000000000..3af05d8f2 --- /dev/null +++ b/ir/aliaschain.go @@ -0,0 +1,195 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "slices" + +// AliasChainIndex answers, for every alias a run reads, the type its chain +// names, how deep the alias sits above it, and the node at a distance up it. +// It reads each type once and settles each alias once, keeping jumps to its +// ancestors at powers of two: a chain end costs O(1), and a node at a +// distance O(log n). It is not safe for concurrent use. +type AliasChainIndex struct { + node func(TypeID) (TypeDef, bool) + // at places each type read in entries. + at map[TypeID]int + entries []aliasChainEntry +} + +// aliasChainEntry is one type an index has read: an alias scalar, or a type +// that is none, which ends every chain reaching it. +type aliasChainEntry struct { + id TypeID + // scalar is the alias, nil for a type that is none. + scalar *Scalar + // typeDef is a type that is no alias, nil where the registry holds no node + // at id, a typed nil among them. + typeDef TypeDef + // jumps holds, for a settled alias on no cycle, the entry 2^k hops up its + // chain at k: its Base target at 0, and nothing past the chain's end. + jumps []int + // end is, for a settled alias, the entry of the type its chain names, or on + // a cyclic chain the first one its walk meets twice. + end int + // depth is how many aliases a settled alias on no cycle is above its end: + // 1 for one whose Base names the end. It is 0 for a type that is no alias. + depth int + state aliasChainState + // cyclic reports that a settled alias's chain meets one ID twice. + cyclic bool +} + +// aliasChainState is how far an index has read one entry. +type aliasChainState uint8 + +const ( + // chainUnsettled is an alias no walk has settled. + chainUnsettled aliasChainState = iota + // chainOnPath is an alias on the path the walk is settling. + chainOnPath + // chainSettled is an alias whose chain is read, or a type that is no + // alias. + chainSettled +) + +// NewAliasChainIndex returns an index over the types node finds. It reads +// nothing until asked. +func NewAliasChainIndex(node func(TypeID) (TypeDef, bool)) *AliasChainIndex { + return &AliasChainIndex{node: node, at: map[TypeID]int{}} +} + +// End returns the type id's chain names: id itself where id names no alias, +// else its chain end, which a Base naming a type the registry does not hold +// ends at that ID. A cyclic chain has no end: cyclic is true, and the ID +// returned is the first its walk from id meets twice. +func (index *AliasChainIndex) End(id TypeID) (end TypeID, cyclic bool) { + entry := &index.entries[index.settled(id)] + if entry.scalar == nil { + return id, false + } + return index.entries[entry.end].id, entry.cyclic +} + +// Depth returns how many aliases lie from id to its chain's end, 1 for an +// alias whose Base names the end and 0 for a type that is no alias, and false +// for an alias whose chain is cyclic, which has no end to count to. +func (index *AliasChainIndex) Depth(id TypeID) (int, bool) { + entry := &index.entries[index.settled(id)] + return entry.depth, !entry.cyclic +} + +// Ancestor returns the node distance Bases up id's chain: id itself at 0, its +// Base target at 1, its chain's end at its depth (Depth). It is false where +// distance is negative or past the depth, or the chain is cyclic. It follows +// one jump per bit of distance, so a power of two costs one step. +func (index *AliasChainIndex) Ancestor(id TypeID, distance int) (TypeID, bool) { + at := index.settled(id) + entry := &index.entries[at] + if entry.cyclic || distance < 0 || distance > entry.depth { + return "", false + } + return index.entries[index.ancestor(at, distance)].id, true +} + +// ancestor returns the entry distance hops up the chain of the acyclic entry +// at, distance at most its depth. +func (index *AliasChainIndex) ancestor(at, distance int) int { + for k := 0; distance > 0; k++ { + if distance&1 != 0 { + at = index.entries[at].jumps[k] + } + distance >>= 1 + } + return at +} + +// entryOf returns the entry of id, reading id's node the first time it is +// asked. +func (index *AliasChainIndex) entryOf(id TypeID) int { + if at, read := index.at[id]; read { + return at + } + entry := aliasChainEntry{id: id} + if typeDef, held := index.node(id); held && !IsNilTypeDef(typeDef) { + if scalar, alias := typeDef.(*Scalar); alias && scalar.Base != nil { + entry.scalar = scalar + } else { + entry.typeDef = typeDef + } + } + if entry.scalar == nil { + entry.state = chainSettled + } + at := len(index.entries) + index.at[id] = at + index.entries = append(index.entries, entry) + return at +} + +// settled returns the entry of id with its chain settled: every alias on the +// way to the first type that is no alias, one settled already, or one the walk +// met before, which closes a cycle, is settled from the one above it. +func (index *AliasChainIndex) settled(id TypeID) int { + start := index.entryOf(id) + var path []int + at := start + for index.entries[at].state == chainUnsettled { + index.entries[at].state = chainOnPath + path = append(path, at) + at = index.entryOf(index.entries[at].scalar.Base.Target) + } + if index.entries[at].state == chainOnPath { + path = index.settleCycle(path, at) + } + for _, above := range slices.Backward(path) { + index.settleAbove(above, at) + at = above + } + return start +} + +// settleCycle settles the aliases of path from closing, which path holds and +// the last of path names again, to path's end: each is the first ID its own +// walk meets twice, so it names itself. It returns the aliases before the +// cycle, left for settleAbove. +func (index *AliasChainIndex) settleCycle(path []int, closing int) []int { + first := len(path) - 1 + for path[first] != closing { + first-- + } + for _, at := range path[first:] { + entry := &index.entries[at] + entry.state, entry.end, entry.cyclic = chainSettled, at, true + } + return path[:first] +} + +// settleAbove settles the alias at from next, the settled entry its Base +// names. +func (index *AliasChainIndex) settleAbove(at, next int) { + entry, below := &index.entries[at], index.entries[next] + entry.state = chainSettled + if below.scalar == nil { + entry.end, entry.depth, entry.jumps = next, 1, []int{next} + return + } + entry.end, entry.cyclic = below.end, below.cyclic + if below.cyclic { + return + } + entry.depth = below.depth + 1 + entry.jumps = append(make([]int, 0, bitLength(entry.depth)), next) + for k := 0; 2< 0; value >>= 1 { + length++ + } + return length +} diff --git a/ir/aliaschain_answers.go b/ir/aliaschain_answers.go new file mode 100644 index 000000000..d0f8386ae --- /dev/null +++ b/ir/aliaschain_answers.go @@ -0,0 +1,67 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "slices" + +// AliasChainAnswers holds a per-alias answer over an [AliasChainIndex]: a step +// from the alias's own scalar and its Base target's answer, the type a chain +// ends on answering for itself. Each alias steps once, and each end answers +// once, however many questions reach them. It is not safe for concurrent use. +type AliasChainAnswers[T any] struct { + index *AliasChainIndex + answerAtEnd func(TypeID, TypeDef) T + answerFromNext func(*Scalar, T) T + // answers holds each entry's answer once settled, by its place in the + // index. + answers map[int]T +} + +// NewAliasChainAnswers answers answerAtEnd for the type a chain ends on, and +// answerFromNext for an alias from its scalar and its Base target's answer. +// Each answer is held for the life of the answers, so both read only what +// stays as it is while they are asked: a fact of the end that may change +// between questions is the caller's to read when asked. +func NewAliasChainAnswers[T any](index *AliasChainIndex, answerAtEnd func(TypeID, TypeDef) T, + answerFromNext func(*Scalar, T) T) *AliasChainAnswers[T] { + return &AliasChainAnswers[T]{index: index, answerAtEnd: answerAtEnd, answerFromNext: answerFromNext, answers: map[int]T{}} +} + +// AnswerFor is id's answer, and false where its chain is cyclic or ends on a +// type the registry does not hold, a typed nil among them. An id naming no +// alias answers as an end. +func (answers *AliasChainAnswers[T]) AnswerFor(id TypeID) (T, bool) { + var none T + start := answers.index.settled(id) + entry := &answers.index.entries[start] + end := start + if entry.scalar != nil { + end = entry.end + } + if entry.cyclic || answers.index.entries[end].typeDef == nil { + return none, false + } + if answer, settled := answers.answers[start]; settled { + return answer, true + } + var path []int + at := start + for at != end { + if _, settled := answers.answers[at]; settled { + break + } + path = append(path, at) + at = answers.index.entries[at].jumps[0] + } + answer, settled := answers.answers[at] + if !settled { + answer = answers.answerAtEnd(answers.index.entries[end].id, answers.index.entries[end].typeDef) + answers.answers[end] = answer + } + for _, at := range slices.Backward(path) { + answer = answers.answerFromNext(answers.index.entries[at].scalar, answer) + answers.answers[at] = answer + } + return answer, true +} diff --git a/ir/aliaschain_cost_test.go b/ir/aliaschain_cost_test.go new file mode 100644 index 000000000..73227daaf --- /dev/null +++ b/ir/aliaschain_cost_test.go @@ -0,0 +1,85 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" +) + +// chainSizes are the lengths a cost row reads a chain at: each past the 64 +// hops a walk once stopped at, and doubling, so the marginal growth shows a +// quadratic term apart from what every size spends alike. +var chainSizes = [3]int{100, 200, 400} + +// assertMarginalGrowth holds three counts taken at n, 2n and 4n to linear +// growth: the third step adds at most two and a half times what the second +// does, where a linear count adds twice and a quadratic one four times. +func assertMarginalGrowth(t *testing.T, counts [3]int, what string) { + t.Helper() + require.Less(t, counts[0], counts[1], "%s grows with the chain: %v", what, counts) + assert.LessOrEqual(t, float64(counts[2]-counts[1]), 2.5*float64(counts[1]-counts[0]), + "%s at %v: %v", what, chainSizes, counts) +} + +// manyUsesOfOneChain is aliasChain(n) with n uses of its head: an alias over +// each node, as the fields of many models typed by one chain read it. +func manyUsesOfOneChain(count int) ir.TypeRegistry { + types := aliasChain(count) + for i := range count { + use := ir.TypeID(fmt.Sprintf("type/use%d", i)) + types[use] = irtest.ScalarOf(use, aliasAbove(i)) + } + return types +} + +// TestAliasChainIndex_ReadsGrowLinearlyInTheAliasesAsked pins the index's cost: +// asking every use of one chain its end, its depth and the node above its end +// reads each alias a bounded number of times, so the reads grow linearly where +// a walk per question would read n²/2. +func TestAliasChainIndex_ReadsGrowLinearlyInTheAliasesAsked(t *testing.T) { + t.Parallel() + var reads [3]int + for k, n := range chainSizes { + index := ir.NewAliasChainIndex(countingLookupOf(manyUsesOfOneChain(n), &reads[k])) + for i := range n { + use := ir.TypeID(fmt.Sprintf("type/use%d", i)) + end, _ := index.End(use) + require.Equal(t, integerID, end) + depth, acyclic := index.Depth(use) + require.True(t, acyclic) + far, ok := index.Ancestor(use, depth-1) + require.True(t, ok) + require.Equal(t, aliasAbove(0), far, "use%d reaches the far alias", i) + } + } + assertMarginalGrowth(t, reads, "the lookups") +} + +// TestAliasChainAnswers_ReadsGrowLinearlyInTheAliasesAsked pins the memo's +// cost: an answer for every use of one chain steps each alias once and reads +// a bounded number of nodes per alias. +func TestAliasChainAnswers_ReadsGrowLinearlyInTheAliasesAsked(t *testing.T) { + t.Parallel() + var reads, steps [3]int + for k, n := range chainSizes { + index := ir.NewAliasChainIndex(countingLookupOf(manyUsesOfOneChain(n), &reads[k])) + answers := ir.NewAliasChainAnswers(index, + func(ir.TypeID, ir.TypeDef) int { return 0 }, + func(_ *ir.Scalar, next int) int { steps[k]++; return next + 1 }) + for i := range n { + depth, ok := answers.AnswerFor(ir.TypeID(fmt.Sprintf("type/use%d", i))) + require.True(t, ok) + require.Equal(t, i+2, depth) + } + assert.Equal(t, 2*n, steps[k], "each of the %d aliases steps once", 2*n) + } + assertMarginalGrowth(t, reads, "the lookups") +} diff --git a/ir/aliaschain_oracle_test.go b/ir/aliaschain_oracle_test.go new file mode 100644 index 000000000..539391100 --- /dev/null +++ b/ir/aliaschain_oracle_test.go @@ -0,0 +1,112 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "fmt" + "math/rand/v2" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" +) + +// walkedChain is the reference reading of id's chain, apart from the index: the +// Base targets its walk names, each alias's Base target in turn, until a type +// that is no alias or the first ID met twice, and whether it met one twice. +func walkedChain(types ir.TypeRegistry, id ir.TypeID) (aliases, bases []ir.TypeID, cyclic bool) { + seen := map[ir.TypeID]bool{} + for { + base, alias := ir.AliasBase(types, id) + if !alias { + return aliases, bases, false + } + if seen[id] { + return aliases, bases, true + } + seen[id] = true + aliases = append(aliases, id) + bases = append(bases, base) + id = base + } +} + +// randomAliasForest is a registry of up to sixty aliases over two models, a +// primitive, an opaque scalar and an ID it does not hold, each alias's Base an +// earlier alias or one of those, so its chains branch at every depth, and a few +// aliases naming a later one, which closes cycles. +func randomAliasForest(rng *rand.Rand) (ir.TypeRegistry, []ir.TypeID) { + types := irtest.DocOf( + &ir.Primitive{ID: integerID, PrimitiveKind: ir.PrimitiveInteger}, + irtest.ModelOf("type/m1", nil), irtest.ModelOf("type/m2", nil), irtest.ScalarOf("type/opaque", ""), + ).Types + ends := []ir.TypeID{integerID, "type/m1", "type/m2", "type/opaque", "type/ghost"} + n := 1 + rng.IntN(60) + ids := make([]ir.TypeID, n, n+len(ends)) + for i := range ids { + ids[i] = ir.TypeID(fmt.Sprintf("type/a%02d", i)) + } + for i, id := range ids { + var base ir.TypeID + switch r := rng.IntN(20); { + case r == 0 && i+1 < n: + base = ids[i+1+rng.IntN(n-i-1)] + case r < 4 || i == 0: + base = ends[rng.IntN(len(ends))] + default: + base = ids[rng.IntN(i)] + } + types[id] = irtest.ScalarOf(id, base) + } + return types, append(ids, ends...) +} + +// TestAliasChainIndex_AnswersAsTheReferenceWalkDoes holds the index's depths +// and nodes at a distance to a walk of each chain on random forests of aliases, +// branching at every depth, with cycles, dangling Bases and every kind of end, +// each question asked of a fresh index and of one asked everything before. +func TestAliasChainIndex_AnswersAsTheReferenceWalkDoes(t *testing.T) { + t.Parallel() + deep := 0 + for seed := range uint64(200) { + types, ids := randomAliasForest(rand.New(rand.NewPCG(seed, seed+7))) + warm := ir.NewAliasChainIndex(types.Lookup) + for _, a := range ids { + _, links, cyclic := walkedChain(types, a) + for _, index := range []*ir.AliasChainIndex{warm, ir.NewAliasChainIndex(types.Lookup)} { + at := fmt.Sprintf("seed %d: %s", seed, a) + depth, acyclic := index.Depth(a) + require.Equal(t, !cyclic, acyclic, at) + if cyclic { + _, ok := index.Ancestor(a, 0) + require.False(t, ok, at) + continue + } + require.Equal(t, len(links), depth, at) + for distance := range depth + 2 { + want, wantOK := slices.Concat([]ir.TypeID{a}, links), distance <= depth + got, ok := index.Ancestor(a, distance) + require.Equal(t, wantOK, ok, "%s at %d", at, distance) + if wantOK { + require.Equal(t, want[distance], got, "%s at %d", at, distance) + } + } + deep = max(deep, depth) + } + } + } + require.Greater(t, deep, 4, "no chain was deep enough to read a jump past the first") +} + +// TestComposedOf_ATypedNilComposesNothing pins a typed nil, which a registry +// may hold: whatever its kind, it names no edge. +func TestComposedOf_ATypedNilComposesNothing(t *testing.T) { + t.Parallel() + assert.Nil(t, ir.ComposedOf((*ir.Model)(nil))) + assert.Nil(t, ir.ComposedOf((*ir.Scalar)(nil))) +} diff --git a/ir/aliaschain_test.go b/ir/aliaschain_test.go new file mode 100644 index 000000000..68495a1b3 --- /dev/null +++ b/ir/aliaschain_test.go @@ -0,0 +1,178 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "fmt" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" +) + +// integerID is the primitive an alias chain of these tests ends on. +var integerID = ir.PrimitiveTypeID(ir.PrimitiveInteger) + +// aliasAbove is the ID of the alias i hops above a chain's far end. +func aliasAbove(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("type/I%d", i)) } + +// aliasChain returns a registry holding the integer primitive and the aliases +// I0 to I(n-1), each over the one below it and I0 over integer, and the model +// type/m, the opaque scalar type/opaque, the cycle type/A ⇄ type/B entered from +// type/X, the self-naming type/self, type/dangling naming no type, and the +// scalars type/P and type/Q over type/m. +func aliasChain(count int) ir.TypeRegistry { + types := irtest.DocOf( + &ir.Primitive{ID: integerID, PrimitiveKind: ir.PrimitiveInteger}, + irtest.ModelOf("type/m", nil), + irtest.ScalarOf("type/opaque", ""), + irtest.ScalarOf("type/A", "type/B"), irtest.ScalarOf("type/B", "type/A"), irtest.ScalarOf("type/X", "type/A"), + irtest.ScalarOf("type/self", "type/self"), + irtest.ScalarOf("type/dangling", "type/ghost"), + irtest.ScalarOf("type/P", "type/m"), irtest.ScalarOf("type/Q", "type/m"), + ).Types + below := integerID + for i := range count { + types[aliasAbove(i)] = irtest.ScalarOf(aliasAbove(i), below) + below = aliasAbove(i) + } + return types +} + +// countingLookupOf is types.Lookup, counting each read in reads. +func countingLookupOf(types ir.TypeRegistry, reads *int) func(ir.TypeID) (ir.TypeDef, bool) { + return func(id ir.TypeID) (ir.TypeDef, bool) { + *reads++ + typeDef, ok := types[id] + return typeDef, ok + } +} + +// chainEnd is one End answer. +type chainEnd struct { + end ir.TypeID + cyclic bool +} + +// TestAliasChainIndex_EndIsWhatAChainNames pins End: a type that is no alias +// names itself; a chain for the type it ends on, however long; one stopping on +// an alias for that alias's Base target, the first type met twice on a cycle +// and the ID a Base names where the registry holds nothing. +func TestAliasChainIndex_EndIsWhatAChainNames(t *testing.T) { + t.Parallel() + types := aliasChain(200) + nilScalar := (*ir.Scalar)(nil) + types["type/nil"] = nilScalar + types["type/overNil"] = irtest.ScalarOf("type/overNil", "type/nil") + types["type/overOpaque"] = irtest.ScalarOf("type/overOpaque", "type/opaque") + index := ir.NewAliasChainIndex(types.Lookup) + + for id, want := range map[ir.TypeID]chainEnd{ + "type/m": {end: "type/m"}, + "type/opaque": {end: "type/opaque"}, + integerID: {end: integerID}, + aliasAbove(0): {end: integerID}, + aliasAbove(5): {end: integerID}, + aliasAbove(199): {end: integerID}, + "type/P": {end: "type/m"}, + "type/overOpaque": {end: "type/opaque"}, + "type/overNil": {end: "type/nil"}, + "type/dangling": {end: "type/ghost"}, + "type/A": {end: "type/A", cyclic: true}, + "type/B": {end: "type/B", cyclic: true}, + "type/X": {end: "type/A", cyclic: true}, + "type/self": {end: "type/self", cyclic: true}, + } { + end, cyclic := index.End(id) + assert.Equal(t, want, chainEnd{end, cyclic}, "%s", id) + } +} + +// TestAliasChainIndex_DepthAndAncestorReadTheChainsNodes pins Depth and +// Ancestor: an alias's depth counts the aliases down to its end, the node at a +// distance is that many Bases up, the alias itself at 0 and its end at its +// depth, past 64 hops; a type that is no alias is at depth 0, its own ancestor +// alone; a cyclic chain has neither. +func TestAliasChainIndex_DepthAndAncestorReadTheChainsNodes(t *testing.T) { + t.Parallel() + index := ir.NewAliasChainIndex(aliasChain(200).Lookup) + for _, tc := range []struct { + id ir.TypeID + depth int + acyclic bool + distance int + ancestor ir.TypeID // "" where there is none at distance + }{ + {aliasAbove(5), 6, true, 0, aliasAbove(5)}, + {aliasAbove(5), 6, true, 1, aliasAbove(4)}, + {aliasAbove(5), 6, true, 3, aliasAbove(2)}, + {aliasAbove(5), 6, true, 6, integerID}, + {aliasAbove(5), 6, true, 7, ""}, + {aliasAbove(5), 6, true, -1, ""}, + {aliasAbove(199), 200, true, 199, aliasAbove(0)}, + {aliasAbove(199), 200, true, 128, aliasAbove(71)}, + {"type/P", 1, true, 1, "type/m"}, + {"type/m", 0, true, 0, "type/m"}, + {"type/m", 0, true, 1, ""}, + {"type/dangling", 1, true, 1, "type/ghost"}, + {"type/A", 0, false, 0, ""}, + {"type/X", 0, false, 1, ""}, + {"type/self", 0, false, 0, ""}, + {"type/never", 0, true, 0, "type/never"}, + } { + depth, acyclic := index.Depth(tc.id) + assert.Equal(t, tc.depth, depth, "%s", tc.id) + assert.Equal(t, tc.acyclic, acyclic, "%s", tc.id) + ancestor, ok := index.Ancestor(tc.id, tc.distance) + assert.Equal(t, tc.ancestor != "", ok, "%s at %d", tc.id, tc.distance) + assert.Equal(t, tc.ancestor, ancestor, "%s at %d", tc.id, tc.distance) + } +} + +// TestAliasChainAnswers_StepsFromTheNextNodesAnswer pins the per-alias answer: +// the end's answer for the type a chain ends on, and each alias's from its own +// scalar and its Base target's answer, read past 64 hops; none for a cyclic +// chain or one naming a type the registry does not hold. +func TestAliasChainAnswers_StepsFromTheNextNodesAnswer(t *testing.T) { + t.Parallel() + types := aliasChain(300) + types["type/branch"] = irtest.ScalarOf("type/branch", aliasAbove(3)) + index := ir.NewAliasChainIndex(types.Lookup) + var ends []ir.TypeID + answers := ir.NewAliasChainAnswers(index, + func(id ir.TypeID, typeDef ir.TypeDef) []ir.TypeID { + ends = append(ends, id) + assert.Equal(t, id, typeDef.Common().ID, "the end's own node") + return []ir.TypeID{id} + }, + func(scalar *ir.Scalar, next []ir.TypeID) []ir.TypeID { + return append(slices.Clone(next), scalar.ID) + }) + + for id, want := range map[ir.TypeID][]ir.TypeID{ + integerID: {integerID}, + "type/m": {"type/m"}, + aliasAbove(0): {integerID, aliasAbove(0)}, + aliasAbove(2): {integerID, aliasAbove(0), aliasAbove(1), aliasAbove(2)}, + "type/branch": {integerID, aliasAbove(0), aliasAbove(1), aliasAbove(2), aliasAbove(3), "type/branch"}, + "type/P": {"type/m", "type/P"}, + } { + got, ok := answers.AnswerFor(id) + assert.True(t, ok, "%s", id) + assert.Equal(t, want, got, "%s", id) + } + deep, ok := answers.AnswerFor(aliasAbove(299)) + require.True(t, ok) + assert.Len(t, deep, 301, "every alias of a 300-alias chain and its end") + assert.Equal(t, aliasAbove(299), deep[300]) + + for _, id := range []ir.TypeID{"type/A", "type/B", "type/X", "type/self", "type/dangling", "type/ghost"} { + _, ok := answers.AnswerFor(id) + assert.False(t, ok, "%s", id) + } +} diff --git a/ir/auth_test.go b/ir/auth_test.go index 5337d3cb6..89d73d217 100644 --- a/ir/auth_test.go +++ b/ir/auth_test.go @@ -57,7 +57,7 @@ func TestAuthScheme_JSONContract(t *testing.T) { // TestAuthKind_Constants pins the on-disk spelling of every AuthKind value. // AuthKind strings are the wire format compilers write into Document.Auth; a -// typo fix later would be a silent breaking change to every golden IR +// typo fix later would be an unannounced breaking change to every golden IR // snapshot, exactly like the PrimitiveKind/PresenceKind constants in types.go. func TestAuthKind_Constants(t *testing.T) { t.Parallel() diff --git a/ir/bigval.go b/ir/bigval.go index 501ec6da9..023110175 100644 --- a/ir/bigval.go +++ b/ir/bigval.go @@ -19,33 +19,33 @@ import ( // untouched — so a stored value round-trips through JSON unchanged. type BigVal string -// NewBigVal validates s as a decimal or scientific-notation numeric literal and -// returns it in canonical JSON form. It rejects the empty string, hex, a +// NewBigVal validates text as a decimal or scientific-notation numeric literal +// and returns it in canonical JSON form. It rejects the empty string, hex, a // binary (p/P) exponent, NaN and infinities with [ErrNotDecimal], and a nonzero // value whose leading digit carries a power of ten past [MaxDecimalExp] with // [ErrExponentRange]. It never rounds or reformats the significant digits: a -// high-precision decimal and an exponential literal are preserved verbatim, -// and only JSON-invalid affixes are normalized. A literal in JSON form already -// is returned as it is, allocating nothing. -func NewBigVal(s string) (BigVal, error) { - decimalLiteral, _, err := readDecimal(s) +// high-precision decimal and an exponential literal are preserved verbatim, and +// only JSON-invalid affixes are normalized. A literal in JSON form already is +// returned as it is, allocating nothing. +func NewBigVal(text string) (BigVal, error) { + decimalLiteral, _, err := readDecimal(text) if err != nil { - return "", fmt.Errorf("bigval: %q: %w", s, err) + return "", fmt.Errorf("bigval: %q: %w", text, err) } - if decimalLiteral.spelledForJSON(s) { - return BigVal(s), nil + if decimalLiteral.spelledForJSON(text) { + return BigVal(text), nil } return BigVal(jsonSpelling(decimalLiteral)), nil } -// spelledForJSON reports whether s, the text l was scanned from, is what +// spelledForJSON reports whether text, the text l was scanned from, is what // jsonSpelling makes of l already: no leading "+", an integer part that is "0" // or opens with another digit, and a point only where digits follow it. Those // are the only affixes jsonSpelling rewrites, and it keeps every other part as // written. -func (l decimalLiteral) spelledForJSON(s string) bool { +func (l decimalLiteral) spelledForJSON(text string) bool { whole := l.intPart == "0" || (l.intPart != "" && l.intPart[0] != '0') - return whole && s[0] != '+' && l.point == (l.frac != "") + return whole && text[0] != '+' && l.point == (l.frac != "") } // jsonSpelling rewrites the JSON-invalid affixes of a scanned literal into JSON @@ -54,22 +54,22 @@ func (l decimalLiteral) spelledForJSON(s string) bool { // dot ("5." → "5", "5.e3" → "5e3"). Significant digits, the exponent and its // case are left as written. A leading zero is JSON-invalid rather than merely // unusual, so keeping it would break BigVal's round-trip guarantee. -func jsonSpelling(decimalLiteralValue decimalLiteral) string { - var b strings.Builder - if decimalLiteralValue.neg { - b.WriteByte('-') +func jsonSpelling(decimalLiteral decimalLiteral) string { + var builder strings.Builder + if decimalLiteral.neg { + builder.WriteByte('-') } - if whole := strings.TrimLeft(decimalLiteralValue.intPart, "0"); whole != "" { - b.WriteString(whole) + if whole := strings.TrimLeft(decimalLiteral.intPart, "0"); whole != "" { + builder.WriteString(whole) } else { - b.WriteByte('0') + builder.WriteByte('0') } - if decimalLiteralValue.frac != "" { - b.WriteByte('.') - b.WriteString(decimalLiteralValue.frac) + if decimalLiteral.frac != "" { + builder.WriteByte('.') + builder.WriteString(decimalLiteral.frac) } - b.WriteString(decimalLiteralValue.exponent) - return b.String() + builder.WriteString(decimalLiteral.exponent) + return builder.String() } // Decimal reads v as a [Decimal]. A BigVal built by [NewBigVal] always reads; diff --git a/ir/bigval_property_test.go b/ir/bigval_property_test.go index 22baaa916..128c1a58c 100644 --- a/ir/bigval_property_test.go +++ b/ir/bigval_property_test.go @@ -59,13 +59,13 @@ func FuzzNewBigVal_AcceptedFormsAreJSONValid(f *testing.F) { f.Add(form) } - f.Fuzz(func(t *testing.T, s string) { - bigVal, err := ir.NewBigVal(s) + f.Fuzz(func(t *testing.T, text string) { + bigVal, err := ir.NewBigVal(text) if err != nil { return // NewBigVal rejected s; it makes no promise about a rejection. } if !jsontext.Value(bigVal.String()).IsValid() { - t.Fatalf("NewBigVal(%q) = %q, which jsontext.Value.IsValid rejects", s, bigVal.String()) + t.Fatalf("NewBigVal(%q) = %q, which jsontext.Value.IsValid rejects", text, bigVal.String()) } }) } diff --git a/ir/bindings_test.go b/ir/bindings_test.go index ccdab46d4..02276e574 100644 --- a/ir/bindings_test.go +++ b/ir/bindings_test.go @@ -83,8 +83,8 @@ func TestHTTPBinding_SuccessStatusDeterministic(t *testing.T) { } // TestHTTPLocation_Constants pins the on-disk spelling of every HTTPLocation -// value: these strings are read back by every emitter that dispatches on -// param location, so a typo fix later would be a silent breaking change. +// value: these strings are read back by every emitter that dispatches on param +// location, so a typo fix later would be an unannounced breaking change. func TestHTTPLocation_Constants(t *testing.T) { t.Parallel() assertConstantSpellings(t, map[ir.HTTPLocation]string{ diff --git a/ir/boundkinds.go b/ir/boundkinds.go new file mode 100644 index 000000000..376b97e17 --- /dev/null +++ b/ir/boundkinds.go @@ -0,0 +1,45 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "slices" + +// The kinds of value a group of keywords bounds. +var ( + // numberValueKinds are the values a numeric bound orders: a number, and + // each infinity and NaN, which the IEEE 754 kinds alone hold. + numberValueKinds = []ValueKind{ValueNumber, ValueInfinity, ValueNegativeInfinity, ValueNaN} + // textValueKinds are the values a length or a pattern bounds: a string, a + // symbol, which is judged as the text it holds, and bytes, whose length + // counts octets. + textValueKinds = []ValueKind{ValueString, ValueSymbol, ValueBytes} +) + +// keywordValueKinds is the one table of the kinds of value each keyword of +// [Constraints] bounds (docs/ir/constraints.md#constraints). A value of any +// other kind it admits, as JSON Schema's keywords do. A keyword with no row +// bounds none. +var keywordValueKinds = map[ConstraintKeyword][]ValueKind{ + ConstraintKeywordMin: numberValueKinds, + ConstraintKeywordExclusiveMin: numberValueKinds, + ConstraintKeywordMax: numberValueKinds, + ConstraintKeywordExclusiveMax: numberValueKinds, + ConstraintKeywordMultipleOf: numberValueKinds, + ConstraintKeywordPrecision: numberValueKinds, + ConstraintKeywordScale: numberValueKinds, + ConstraintKeywordMinLength: textValueKinds, + ConstraintKeywordMaxLength: textValueKinds, + ConstraintKeywordPattern: textValueKinds, + ConstraintKeywordPatternMessage: textValueKinds, + ConstraintKeywordMinItems: {ValueList}, + ConstraintKeywordMaxItems: {ValueList}, + ConstraintKeywordMinProperties: {ValueObject}, + ConstraintKeywordMaxProperties: {ValueObject}, +} + +// Binds reports whether keyword bounds a value of kind. A [Constraints] +// UniqueItems is no keyword, and a list's alone. +func (keyword ConstraintKeyword) Binds(kind ValueKind) bool { + return slices.Contains(keywordValueKinds[keyword], kind) +} diff --git a/ir/catchall.go b/ir/catchall.go index 81115a6c9..f66f89282 100644 --- a/ir/catchall.go +++ b/ir/catchall.go @@ -42,16 +42,17 @@ func CatchAllHolders(types TypeRegistry, root TypeID) []TypeID { return holders } -// throughAliases returns the type the alias scalars from id stand for, marking -// each in seen, and stops at one seen already, which ends a cyclic chain. +// throughAliases returns the type the alias scalars from id name (aliasChain), +// marking each in seen, and stops at one seen already, which ends a cyclic +// chain or one another entry's walk read. func throughAliases(types TypeRegistry, id TypeID, seen map[TypeID]bool) TypeID { - for !seen[id] { - base, alias := AliasBase(types, id) - if !alias { - return id + end := id + for typeID, scalar := range aliasChain(types.Lookup, id) { + if seen[typeID] || scalar == nil { + return typeID } - seen[id] = true - id = base + seen[typeID] = true + end = scalar.Base.Target } - return id + return end } diff --git a/ir/clone.go b/ir/clone.go index e41a39498..b2388118f 100644 --- a/ir/clone.go +++ b/ir/clone.go @@ -15,12 +15,12 @@ import "reflect" // of one length node reaches twice is copied once, and a cycle comes out as the // same cycle. func cloneNode[N any](node N, ranging *entryStack) (N, bool) { - clonerValue := cloner{copies: map[refKey]reflect.Value{}, ranging: ranging} - v := reflect.ValueOf(node) - out := reflect.New(v.Type()).Elem() - clonerValue.fill(out, v, 0) + cloner := cloner{copies: map[refKey]reflect.Value{}, ranging: ranging} + nodeValue := reflect.ValueOf(node) + out := reflect.New(nodeValue.Type()).Elem() + cloner.fill(out, nodeValue, 0) var cloned N - if clonerValue.truncated { + if cloner.truncated { return cloned, false } reflect.ValueOf(&cloned).Elem().Set(out) // out has node's concrete type @@ -39,86 +39,86 @@ type cloner struct { truncated bool } -// fill sets dst, a settable value of v's type, to a copy of v sharing no -// reference with it. depth counts the steps from the root as [WalkValues] +// fill sets dst, a settable value of value's type, to a copy of value sharing +// no reference with it. depth counts the steps from the root as [WalkValues] // counts them, and maps are copied in the walk's key order, so which path // copies a shared reference, and so whether the cap cuts a copy, is fixed. // // No interface sits below a node an edit copies, which // TestEditor_CopiesEveryIRTypeWhole holds the IR to, so one would be shared // rather than copied. -func (c *cloner) fill(dst, v reflect.Value, depth int) { +func (c *cloner) fill(dst, value reflect.Value, depth int) { if depth > MaxWalkDepth { c.truncated = true return } - switch v.Kind() { + switch value.Kind() { case reflect.Pointer: - c.pointer(dst, v, depth) + c.pointer(dst, value, depth) case reflect.Struct: - c.fields(dst, v, depth) + c.fields(dst, value, depth) case reflect.Slice: - c.slice(dst, v, depth) + c.slice(dst, value, depth) case reflect.Map: - c.entries(dst, v, depth) + c.entries(dst, value, depth) default: - dst.Set(v) // a value of any other kind the IR declares holds no reference + dst.Set(value) // a value of any other kind the IR declares holds no reference } } // pointer copies what a non-nil pointer points at, once per pointer. The copy // is recorded before its target is filled in, so a cycle back to it ends. -func (c *cloner) pointer(dst, v reflect.Value, depth int) { - if v.IsNil() { - dst.Set(v) +func (c *cloner) pointer(dst, value reflect.Value, depth int) { + if value.IsNil() { + dst.Set(value) return } - key := refKey{typ: v.Type(), ptr: v.Pointer()} + key := refKey{typ: value.Type(), ptr: value.Pointer()} if made, met := c.copies[key]; met { dst.Set(made) return } - out := reflect.New(v.Type().Elem()) + out := reflect.New(value.Type().Elem()) c.copies[key] = out dst.Set(out) - c.fill(out.Elem(), v.Elem(), depth+1) + c.fill(out.Elem(), value.Elem(), depth+1) } // fields copies a struct. Assigning it whole copies every field holding no // reference, so only the others are filled again. Every field can be set, // since TestEditor_CopiesEveryIRTypeWhole holds the IR to exporting each. -func (c *cloner) fields(dst, v reflect.Value, depth int) { - dst.Set(v) +func (c *cloner) fields(dst, value reflect.Value, depth int) { + dst.Set(value) // Indexed: ranging over v.Fields() puts the loop body on the heap for every // struct copied. - for i := range v.NumField() { - if f := dst.Field(i); holdsReference(f.Kind()) { - c.fill(f, v.Field(i), depth+1) + for i := range value.NumField() { + if field := dst.Field(i); holdsReference(field.Kind()) { + c.fill(field, value.Field(i), depth+1) } } } // slice copies a non-nil slice into a new backing array of its length, once // per slice the walk would key as one. -func (c *cloner) slice(dst, v reflect.Value, depth int) { - if v.IsNil() { - dst.Set(v) +func (c *cloner) slice(dst, value reflect.Value, depth int) { + if value.IsNil() { + dst.Set(value) return } - key := refKey{typ: v.Type(), ptr: v.Pointer(), n: v.Len()} + key := refKey{typ: value.Type(), ptr: value.Pointer(), n: value.Len()} if made, met := c.copies[key]; met { dst.Set(made) return } - out := reflect.MakeSlice(v.Type(), v.Len(), v.Len()) + out := reflect.MakeSlice(value.Type(), value.Len(), value.Len()) c.copies[key] = out dst.Set(out) - if !holdsReference(v.Type().Elem().Kind()) { - reflect.Copy(out, v) + if !holdsReference(value.Type().Elem().Kind()) { + reflect.Copy(out, value) return } - for i := range v.Len() { - c.fill(out.Index(i), v.Index(i), depth+1) + for i := range value.Len() { + c.fill(out.Index(i), value.Index(i), depth+1) } } @@ -127,21 +127,21 @@ func (c *cloner) slice(dst, v reflect.Value, depth int) { // filled into one holder, which SetMapIndex copies into the map: fill // overwrites it whole, unless the depth cap cuts the copy, which is then // discarded. -func (c *cloner) entries(dst, v reflect.Value, depth int) { - if v.IsNil() { - dst.Set(v) +func (c *cloner) entries(dst, source reflect.Value, depth int) { + if source.IsNil() { + dst.Set(source) return } - key := refKey{typ: v.Type(), ptr: v.Pointer()} + key := refKey{typ: source.Type(), ptr: source.Pointer()} if made, met := c.copies[key]; met { dst.Set(made) return } - out := reflect.MakeMapWithSize(v.Type(), v.Len()) + out := reflect.MakeMapWithSize(source.Type(), source.Len()) c.copies[key] = out dst.Set(out) - entryFrame := c.ranging.push(v) - value := reflect.New(v.Type().Elem()).Elem() + entryFrame := c.ranging.push(source) + value := reflect.New(source.Type().Elem()).Elem() for i := entryFrame.base; i < entryFrame.end; i++ { // Indexed afresh: a nested map can move the stack while stacking its own. mapEntry := c.ranging.entries[i] diff --git a/ir/clone_internal_test.go b/ir/clone_internal_test.go index 55cbdcf3b..3d9e6d7fa 100644 --- a/ir/clone_internal_test.go +++ b/ir/clone_internal_test.go @@ -23,9 +23,9 @@ type cloneProbe struct { } // chainTo returns a chain of n links ending at tail. -func chainTo(n int, tail *cloneLink) *cloneLink { +func chainTo(count int, tail *cloneLink) *cloneLink { link := tail - for range n { + for range count { link = &cloneLink{Next: link} } return link @@ -53,11 +53,11 @@ func TestCloner_CopiesMapEntriesInKeyOrder(t *testing.T) { v := reflect.ValueOf(probe) for range 64 { - clonerValue := cloner{copies: map[refKey]reflect.Value{}, ranging: &entryStack{}} + cloner := cloner{copies: map[refKey]reflect.Value{}, ranging: &entryStack{}} out := reflect.New(v.Type()).Elem() - clonerValue.fill(out, v, 0) + cloner.fill(out, v, 0) - require.False(t, clonerValue.truncated, "the copy took the deep entry first") + require.False(t, cloner.truncated, "the copy took the deep entry first") cp, _ := reflect.TypeAssert[cloneProbe](out) assert.Same(t, cp.Entries["a"].Next, chainEnd(cp.Entries["b"], deep), "the shared chain is copied once") @@ -65,8 +65,8 @@ func TestCloner_CopiesMapEntriesInKeyOrder(t *testing.T) { } // chainEnd returns the link n steps along from link. -func chainEnd(link *cloneLink, n int) *cloneLink { - for range n { +func chainEnd(link *cloneLink, count int) *cloneLink { + for range count { link = link.Next } return link @@ -81,8 +81,8 @@ func chainEnd(link *cloneLink, n int) *cloneLink { // process. func TestCloneNode_CopyingANodeWithNoMapAllocatesOnlyTheCopy(t *testing.T) { var ranging entryStack - td := TypeDef(&Primitive{ID: "type/p"}) - assert.Equal(t, 3.0, testing.AllocsPerRun(10, func() { _, _ = cloneNode(td, &ranging) })) + typeDef := TypeDef(&Primitive{ID: "type/p"}) + assert.Equal(t, 3.0, testing.AllocsPerRun(10, func() { _, _ = cloneNode(typeDef, &ranging) })) } // TestCloneNode_LeavesTheEntryStackAsItFoundIt holds a copy to releasing @@ -92,10 +92,10 @@ func TestCloneNode_CopyingANodeWithNoMapAllocatesOnlyTheCopy(t *testing.T) { func TestCloneNode_LeavesTheEntryStackAsItFoundIt(t *testing.T) { t.Parallel() var ranging entryStack - td := TypeDef(&Model{ID: "type/m", WireNameByFormat: map[string]string{"json": "m", "xml": "M"}, + typeDef := TypeDef(&Model{ID: "type/m", WireNameByFormat: map[string]string{"json": "m", "xml": "M"}, Properties: []Property{{ID: "property/a", WireNameByFormat: map[string]string{"json": "a"}}}}) for range 3 { - _, copied := cloneNode(td, &ranging) + _, copied := cloneNode(typeDef, &ranging) require.True(t, copied) assert.Empty(t, ranging.entries, "entries left on the stack") for typ, st := range ranging.stores { diff --git a/ir/composedof_test.go b/ir/composedof_test.go new file mode 100644 index 000000000..433a6cf75 --- /dev/null +++ b/ir/composedof_test.go @@ -0,0 +1,45 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" +) + +// TestComposedOf_NamesBaseThenMixinsAndAnAliasBase pins the one definition of +// a type's composition edges: a model's Base first and then its Mixins in +// order, an alias scalar's Base, and nothing else. Implements is no edge, since +// conformance to an interface says nothing of the values a model composes. +func TestComposedOf_NamesBaseThenMixinsAndAnAliasBase(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + typeDef ir.TypeDef + want []ir.TypeID + }{ + "a model's base, then its mixins": {irtest.ModelOf("type/m", func(model *ir.Model) { + model.Mixins = irtest.RefsTo("type/x", "type/y") + model.Base = &ir.TypeRef{Target: "type/b"} + model.Implements = irtest.RefsTo("type/i") + }), []ir.TypeID{"type/b", "type/x", "type/y"}}, + "a model with mixins alone": {irtest.ModelOf("type/m", func(model *ir.Model) { + model.Mixins = irtest.RefsTo("type/y", "type/x") + }), []ir.TypeID{"type/y", "type/x"}}, + "a model implementing alone": {irtest.ModelOf("type/m", func(model *ir.Model) { + model.Implements = irtest.RefsTo("type/i") + }), nil}, + "an alias scalar": {irtest.ScalarOf("type/s", "type/t"), []ir.TypeID{"type/t"}}, + "an opaque scalar": {irtest.ScalarOf("type/s", ""), nil}, + "a primitive": {&ir.Primitive{ID: "type/primitive/integer", PrimitiveKind: ir.PrimitiveInteger}, nil}, + "a list": {&ir.List{ID: "type/l", ElementType: ir.TypeRef{Target: "type/t"}}, nil}, + "a union": {&ir.Union{ID: "type/u", Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/t"}}}}, nil}, + "a model of no part": {irtest.ModelOf("type/m", nil), nil}, + } { + assert.Equal(t, tc.want, ir.ComposedOf(tc.typeDef), name) + } +} diff --git a/ir/composition.go b/ir/composition.go index b6eea5c74..af27a0192 100644 --- a/ir/composition.go +++ b/ir/composition.go @@ -4,28 +4,29 @@ package ir import ( + "iter" "math" "slices" ) // Supertypes returns the immediate supertypes of the model id names: its Base, -// then each Implements entry, each read through the alias scalars standing in -// for it, since a $ref carrying siblings composes the branch's own alias node, -// not the schema it points at (docs/ir/models.md#composition-entries). Mixins -// are absent on purpose: a mixin contributes members without making the model a +// then each Implements entry, each read through the alias scalars naming it, +// since a $ref carrying siblings composes the branch's own alias node, not the +// schema it points at (docs/ir/models.md#composition-entries). Mixins are +// absent on purpose: a mixin contributes members without making the model a // member of anything, so it belongs to [ExposedProperties], not to subtype // identity. An id naming no live model yields nil, and an unset reference is // skipped. func Supertypes(doc *Document, id TypeID) []TypeID { - left := math.MaxInt - supers, _ := supertypes(nil, doc, id, &left) + stepsLeft := math.MaxInt + supers, _ := supertypes(nil, doc, id, &stepsLeft) return supers } // supertypes appends to dst the supertypes [Supertypes] returns, taking a step -// from *left for each alias scalar it reads a reference through, and reports -// false when *left ran out first. -func supertypes(dst []TypeID, doc *Document, id TypeID, left *int) ([]TypeID, bool) { +// from *stepsLeft for each alias scalar it reads a reference through, and +// reports false when *stepsLeft ran out first. +func supertypes(dst []TypeID, doc *Document, id TypeID, stepsLeft *int) ([]TypeID, bool) { if doc == nil { return dst, true } @@ -34,42 +35,41 @@ func supertypes(dst []TypeID, doc *Document, id TypeID, left *int) ([]TypeID, bo return dst, true } if model.Base != nil { - if dst, ok = appendSupertype(dst, doc, model.Base.Target, left); !ok { + if dst, ok = appendSupertype(dst, doc, model.Base.Target, stepsLeft); !ok { return dst, false } } for _, typeRef := range model.Implements { - if dst, ok = appendSupertype(dst, doc, typeRef.Target, left); !ok { + if dst, ok = appendSupertype(dst, doc, typeRef.Target, stepsLeft); !ok { return dst, false } } return dst, true } -// appendSupertype appends the type target stands for, read through its alias -// scalars, unless that is no type at all. It reports false when *left ran out -// first. -func appendSupertype(dst []TypeID, doc *Document, target TypeID, left *int) ([]TypeID, bool) { - typeID, ok := aliasTarget(doc, target, left) +// appendSupertype appends the type target names, read through its alias +// scalars, unless that is no type at all. It reports false when *stepsLeft ran +// out first. +func appendSupertype(dst []TypeID, doc *Document, target TypeID, stepsLeft *int) ([]TypeID, bool) { + typeID, ok := aliasTarget(doc, target, stepsLeft) if ok && typeID != "" { dst = append(dst, typeID) } return dst, ok } -// take spends a step of *left, and reports false when none is left. -func take(left *int) bool { - if *left <= 0 { +// take spends a step of *stepsLeft, and reports false when none is left. +func take(stepsLeft *int) bool { + if *stepsLeft <= 0 { return false } - *left-- + *stepsLeft-- return true } // AliasBase returns the type the alias scalar id names, and false when id names -// no alias scalar: no Scalar, a typed nil, or one with no Base. An alias stands -// for its Base, and a chain of them for the type at its end -// (docs/ir/scalars.md). +// no alias scalar: no Scalar, a typed nil, or one with no Base. An alias names +// its Base, and a chain of them for the type at its end (docs/ir/scalars.md). func AliasBase(types TypeRegistry, id TypeID) (TypeID, bool) { scalar, ok := types[id].(*Scalar) if !ok || scalar == nil || scalar.Base == nil { @@ -78,23 +78,94 @@ func AliasBase(types TypeRegistry, id TypeID) (TypeID, bool) { return scalar.Base.Target, true } -// aliasTarget follows a chain of alias scalars to the type it stands for, -// returning id unchanged when it names no alias, and taking a step from *left -// for each scalar it reads through. The IR permits a cyclic chain, so a visited -// set ends the walk, at the first type it meets twice. It reports false when -// *left ran out first. -func aliasTarget(doc *Document, id TypeID, left *int) (TypeID, bool) { - seen := make(map[TypeID]bool) - for { - base, alias := AliasBase(doc.Types, id) - if !alias || seen[id] { - return id, true +// ComposedOf returns the composition edges of typeDef: a model's Base and then +// its Mixins, in order, and an alias scalar's Base. Implements is none, since +// conforming to an interface composes none of its values. Any other node, and a +// typed nil, composes nothing. +func ComposedOf(typeDef TypeDef) []TypeID { + var parts []TypeID + switch node := typeDef.(type) { + case *Scalar: + if node != nil && node.Base != nil { + parts = append(parts, node.Base.Target) + } + case *Model: + if node == nil { + return nil + } + for index := range len(node.Mixins) + 1 { + if part, more := composedPart(node, index); more { + parts = append(parts, part) + } + } + default: + // No other kind composes another. + } + return parts +} + +// composedPart returns the target of model's part at index, in the order +// [ComposedOf] lists them, and false past the last. +func composedPart(model *Model, index int) (TypeID, bool) { + if model.Base != nil { + if index == 0 { + return model.Base.Target, true + } + index-- + } + if index < len(model.Mixins) { + return model.Mixins[index].Target, true + } + return "", false +} + +// aliasTarget follows a chain of alias scalars to the type it names +// (aliasChain), returning id unchanged when it names no alias, and taking a +// step from *stepsLeft for each scalar it reads through. A chain ending before +// an ID the registry lacks, or before the first type it meets twice, names that +// ID. It reports false when *stepsLeft ran out first. +func aliasTarget(doc *Document, id TypeID, stepsLeft *int) (TypeID, bool) { + end := id + for typeID, scalar := range aliasChain(doc.Types.Lookup, id) { + if scalar == nil { + return typeID, true } - if !take(left) { + if !take(stepsLeft) { return "", false } - seen[id] = true - id = base + end = scalar.Base.Target + } + return end, true +} + +// aliasChain yields the types a chain from id passes, id first, each alias +// scalar with a Base beside its node, then the first type that is none, +// beside nil. It stops before an ID node finds nothing for, a typed nil among +// them, and before the first ID it meets twice, so a chain ending there ends +// on an alias, whose Base names that ID; its seen-set bounds it by the +// registry's size. +func aliasChain(node func(TypeID) (TypeDef, bool), id TypeID) iter.Seq2[TypeID, *Scalar] { + return func(yield func(TypeID, *Scalar) bool) { + var seen map[TypeID]bool + for { + typeDef, held := node(id) + if !held || IsNilTypeDef(typeDef) || seen[id] { + return + } + scalar, alias := typeDef.(*Scalar) + if !alias || scalar.Base == nil { + yield(id, nil) + return + } + if !yield(id, scalar) { + return + } + if seen == nil { + seen = map[TypeID]bool{} + } + seen[id] = true + id = scalar.Base.Target + } } } @@ -116,20 +187,20 @@ func IsSubtype(doc *Document, target, base TypeID) bool { // scalar it reads a supertype through. spent is the steps it took, and ok is // false when the walk needed more than limit and stopped without an answer. func IsSubtypeWithin(doc *Document, target, base TypeID, limit int) (sub bool, spent int, ok bool) { - left := limit - sub, ok = isSubtype(doc, target, base, &left) - return sub, limit - left, ok + stepsLeft := limit + sub, ok = isSubtype(doc, target, base, &stepsLeft) + return sub, limit - stepsLeft, ok } // walkedLists is how many type IDs a walked question's lists hold on the stack // before they move to the heap: a hierarchy a few types deep and wide. const walkedLists = 8 -// isSubtype walks up from target, taking steps from *left, until it meets base -// or runs out of supertypes or steps. Its lists start in arrays on the stack, -// and its set is a map that does not escape, which Go keeps there too while it -// is small, so a question about a shallow hierarchy allocates nothing. -func isSubtype(doc *Document, target, base TypeID, left *int) (sub, ok bool) { +// isSubtype walks up from target, taking steps from *stepsLeft, until it meets +// base or runs out of supertypes or steps. Its lists start in arrays on the +// stack, and its set is a map that does not escape, which Go keeps there too +// while it is small, so a question about a shallow hierarchy allocates nothing. +func isSubtype(doc *Document, target, base TypeID, stepsLeft *int) (sub, ok bool) { var queued, found [walkedLists]TypeID seen := map[TypeID]bool{} queue := append(queued[:0], target) @@ -137,14 +208,14 @@ func isSubtype(doc *Document, target, base TypeID, left *int) (sub, ok bool) { for len(queue) > 0 { id := queue[len(queue)-1] queue = queue[:len(queue)-1] - if !take(left) { + if !take(stepsLeft) { return false, false } if seen[id] { continue } seen[id] = true - if supers, ok = supertypes(supers[:0], doc, id, left); !ok { + if supers, ok = supertypes(supers[:0], doc, id, stepsLeft); !ok { return false, false } if slices.Contains(supers, base) { @@ -158,16 +229,16 @@ func isSubtype(doc *Document, target, base TypeID, left *int) (sub, ok bool) { // ExposedProperties returns the property IDs the type root names exposes: its // own plus those it composes in through Base, Implements and Mixins // (docs/ir/models.md), the flat set an emitter renders. A root naming an alias -// scalar exposes the parts of the model the alias stands for, and one naming -// neither that nor a live model exposes none. A visited set ends the walk on a -// cyclic hierarchy. +// scalar exposes the parts of the model the alias names, and one naming neither +// that nor a live model exposes none. A visited set ends the walk on a cyclic +// hierarchy. // // It is the relation's definition, walked afresh for one root. A caller asking // many of one document asks irfacts.DocumentFacts, which is held to it. func ExposedProperties(doc *Document, root TypeID) map[PropertyID]bool { properties := map[PropertyID]bool{} - left := math.MaxInt - exposedWalk(doc, root, &left, func(propertyID PropertyID) bool { + stepsLeft := math.MaxInt + exposedWalk(doc, root, &stepsLeft, func(propertyID PropertyID) bool { properties[propertyID] = true return false }) @@ -180,18 +251,18 @@ func ExposedProperties(doc *Document, root TypeID) map[PropertyID]bool { // property it reads. spent is the steps it took, and ok is false when the walk // needed more than limit and stopped without an answer. func ExposesWithin(doc *Document, root TypeID, property PropertyID, limit int) (exposed bool, spent int, ok bool) { - left := limit - ok = exposedWalk(doc, root, &left, func(propertyID PropertyID) bool { + stepsLeft := limit + ok = exposedWalk(doc, root, &stepsLeft, func(propertyID PropertyID) bool { exposed = propertyID == property return exposed }) - return exposed, limit - left, ok + return exposed, limit - stepsLeft, ok } // exposedWalk hands visit each property the types root leads to declare, taking -// steps from *left, and stops when visit returns true. It reports false when -// *left ran out first. -func exposedWalk(doc *Document, root TypeID, left *int, visit func(PropertyID) bool) bool { +// steps from *stepsLeft, and stops when visit returns true. It reports false +// when *stepsLeft ran out first. +func exposedWalk(doc *Document, root TypeID, stepsLeft *int, visit func(PropertyID) bool) bool { if doc == nil { return true } @@ -202,35 +273,35 @@ func exposedWalk(doc *Document, root TypeID, left *int, visit func(PropertyID) b for len(queue) > 0 { id := queue[len(queue)-1] queue = queue[:len(queue)-1] - if !take(left) { + if !take(stepsLeft) { return false } if seen[id] { continue } seen[id] = true - td := doc.Types[id] - if IsNilTypeDef(td) { + typeDef := doc.Types[id] + if IsNilTypeDef(typeDef) { continue // undeclared, or a typed nil. } var stop, ok bool - if queue, stop, ok = partSources(queue, td, left, visit); stop || !ok { + if queue, stop, ok = partSources(queue, typeDef, stepsLeft, visit); stop || !ok { return ok } } return true } -// partSources hands visit td's own properties, taking a step from *left for -// each, and appends the nodes the rest come from: a model's composition -// parents, an alias scalar's base. No other kind carries parts or says where -// to find them. stop reports that visit returned true, and ok false that *left -// ran out first. -func partSources(dst []TypeID, td TypeDef, left *int, visit func(PropertyID) bool) (sources []TypeID, stop, ok bool) { - switch t := td.(type) { +// partSources hands visit typeDef's own properties, taking a step from +// *stepsLeft for each, and appends the nodes the rest come from: a model's +// composition parents, an alias scalar's base. No other kind carries parts or +// says where to find them. stop reports that visit returned true, and ok false +// that *stepsLeft ran out first. +func partSources(dst []TypeID, typeDef TypeDef, stepsLeft *int, visit func(PropertyID) bool) (sources []TypeID, stop, ok bool) { + switch t := typeDef.(type) { case *Model: for _, property := range t.Properties { - if !take(left) { + if !take(stepsLeft) { return dst, false, false } if visit(property.ID) { @@ -249,7 +320,7 @@ func partSources(dst []TypeID, td TypeDef, left *int, visit func(PropertyID) boo return dst, false, true case *Scalar: if t.Base == nil { - return dst, false, true // an opaque scalar stands for nothing. + return dst, false, true // an opaque scalar names nothing. } return append(dst, t.Base.Target), false, true default: diff --git a/ir/composition_test.go b/ir/composition_test.go index d801944e2..45cc5f34c 100644 --- a/ir/composition_test.go +++ b/ir/composition_test.go @@ -48,7 +48,7 @@ func TestSupertypes_TypedNilAliasEndsTheChain(t *testing.T) { assert.Equal(t, []ir.TypeID{"z"}, ir.Supertypes(doc, "m")) } -func TestSupertypes_AnOpaqueScalarStandsForItself(t *testing.T) { +func TestSupertypes_AnOpaqueScalarNamesItself(t *testing.T) { t.Parallel() doc := irtest.DocOf( irtest.ModelOf("m", func(model *ir.Model) { model.Implements = irtest.RefsTo("opaque") }), diff --git a/ir/constraintintersection.go b/ir/constraintintersection.go new file mode 100644 index 000000000..d1049da51 --- /dev/null +++ b/ir/constraintintersection.go @@ -0,0 +1,185 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +// ConstraintIntersection is the intersection of sets of [Constraints]: each +// keyword's intersection where its values agree, and the keywords whose values +// disagree, which stay disagreeing whatever is intersected after and keep the +// receiver's value. Intersecting writes to neither side, and the zero value +// says nothing. Every intersection of bounds goes through it, so the same sets +// intersect alike in every grouping, through an alias chain or written flat. +type ConstraintIntersection struct { + // constraints holds the keywords intersected so far, nil where none. It is + // never written through once built, so intersections share its pointers. + constraints *Constraints + // disagreeing holds the disagreementBit of each ConstraintKeyword whose + // values disagree. + disagreeing uint16 +} + +// The last keyword's disagreementBit is a constant, so a keyword past the +// sixteen that disagreeing holds fails to compile here rather than losing its +// bit. +const _ uint16 = 1 << (ConstraintKeywordPatternMessage - ConstraintKeywordMin) + +// disagreementBit is keyword's bit in a ConstraintIntersection's disagreeing. +func disagreementBit(keyword ConstraintKeyword) uint16 { + return uint16(1) << (keyword - ConstraintKeywordMin) +} + +// ConstraintIntersectionOf is constraints as an intersection of one; nil says +// nothing. It copies constraints, which a later change to them leaves alone. +func ConstraintIntersectionOf(constraints *Constraints) ConstraintIntersection { + return ConstraintIntersection{constraints: constraints.copied()} +} + +// Intersect is the intersection of intersection and other, modifying neither: +// associative, and commutative but for the value a disagreeing keyword takes, +// which is the receiver's. A bound intersects to the tighter of two, a step to +// their common multiple (stepIntersection), and a keyword with no order to one +// value; uniqueItems holds where either side holds it. +func (intersection ConstraintIntersection) Intersect(other ConstraintIntersection) ConstraintIntersection { + disagreeing := intersection.disagreeing | other.disagreeing + switch { + case other.constraints == nil: + return ConstraintIntersection{constraints: intersection.constraints, disagreeing: disagreeing} + case intersection.constraints == nil: + return ConstraintIntersection{constraints: other.constraints, disagreeing: disagreeing} + } + intersected := *intersection.constraints + for keyword := range ConstraintKeywords() { + bit := disagreementBit(keyword) + mine, theirs := intersected.slotOf(keyword), other.constraints.slotOf(keyword) + switch { + case !theirs.holdsValue(): + case !mine.holdsValue(): + mine.adopt(theirs) + case disagreeing&bit == 0 && !mine.intersectWith(theirs): + disagreeing |= bit + } + } + intersected.UniqueItems = intersected.UniqueItems || other.constraints.UniqueItems + return ConstraintIntersection{constraints: &intersected, disagreeing: disagreeing} +} + +// AgreedConstraints is a new value holding every keyword the intersected sets +// agree on, a disagreeing one left out, as no one value states it, and nil +// where it holds none: what a value is held to. +func (intersection ConstraintIntersection) AgreedConstraints() *Constraints { + agreed := intersection.constraints.WithoutKeywords(intersection.DisagreeingKeywords()...) + if agreed.holdsNothing() { + return nil + } + return agreed +} + +// ConstraintsKeepingReceiverOnDisagreement is a new value holding every +// keyword, a disagreeing one at the receiver's value, and nil where it holds +// none: what a node keeping the receiver's value holds. A value is held to +// AgreedConstraints instead. +func (intersection ConstraintIntersection) ConstraintsKeepingReceiverOnDisagreement() *Constraints { + if intersection.constraints.holdsNothing() { + return nil + } + return intersection.constraints.copied() +} + +// DisagreeingKeywords is the keywords whose values the intersected sets +// disagree on, which no one value of the keyword states, in ConstraintKeyword +// order, and nil where there are none. +func (intersection ConstraintIntersection) DisagreeingKeywords() []ConstraintKeyword { + var keywords []ConstraintKeyword + for keyword := range ConstraintKeywords() { + if intersection.disagreeing&disagreementBit(keyword) != 0 { + keywords = append(keywords, keyword) + } + } + return keywords +} + +// adopt takes other's value into the unset slot, sharing its pointer, which +// neither writes through. +func (slot keywordSlot) adopt(other keywordSlot) { + switch { + case slot.number != nil: + *slot.number = *other.number + case slot.count != nil: + *slot.count = *other.count + default: + *slot.text = *other.text + } +} + +// intersectWith writes into the slot the value saying what it and other, both +// set, say, and reports false, leaving its own value, where no one value does. +func (slot keywordSlot) intersectWith(other keywordSlot) bool { + switch { + case slot.number != nil: + intersected, ok := slot.numberIntersection(*slot.number, *other.number) + *slot.number = intersected + return ok + case slot.count != nil: + intersected, ok := slot.countIntersection(*slot.count, *other.count) + *slot.count = intersected + return ok + default: + return *slot.text == *other.text + } +} + +// largerNumber returns the larger of two bounds, the first of one number +// written twice, and false, with the first, where they have no order. +func largerNumber(x, y *BigVal) (*BigVal, bool) { + order, ordered := compareNumbers(*x, *y) + if ordered && order < 0 { + return y, true + } + return x, ordered +} + +// smallerNumber returns the smaller of two bounds, the first of one number +// written twice, and false, with the first, where they have no order. +func smallerNumber(x, y *BigVal) (*BigVal, bool) { + order, ordered := compareNumbers(*x, *y) + if ordered && order > 0 { + return y, true + } + return x, ordered +} + +// commonStep returns the step two multipleOf values intersect to (stepIntersection), +// and false, with the first, where they intersect to none. +func commonStep(x, y *BigVal) (*BigVal, bool) { + step, intersected := stepIntersection(*x, *y) + switch { + case !intersected: + return x, false + case step == *x: + return x, true + case step == *y: + return y, true + default: + return &step, true + } +} + +// largerCount returns the larger of two counts. +func largerCount(x, y *int64) (*int64, bool) { + if *y > *x { + return y, true + } + return x, true +} + +// smallerCount returns the smaller of two counts. +func smallerCount(x, y *int64) (*int64, bool) { + if *y < *x { + return y, true + } + return x, true +} + +// equalCount returns the first of two counts of a keyword with no order, and +// whether they are one. +func equalCount(x, y *int64) (*int64, bool) { return x, *x == *y } diff --git a/ir/constraintintersection_bounds_test.go b/ir/constraintintersection_bounds_test.go new file mode 100644 index 000000000..9165fd536 --- /dev/null +++ b/ir/constraintintersection_bounds_test.go @@ -0,0 +1,127 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "math/big" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// TestConstraintKeyword_AnUndeclaredKeywordIsSetByNone pins the keywords a set +// can hold: one ir declares no constant for is set by no set, is the same in +// any two, and taking it out changes nothing, so a caller iterating past the +// last keyword reads nothing. +func TestConstraintKeyword_AnUndeclaredKeywordIsSetByNone(t *testing.T) { + t.Parallel() + undeclared := ir.ConstraintKeywordPatternMessage + 1 + populated := populatedConstraints() + + assert.False(t, populated.SetsKeyword(undeclared)) + assert.True(t, ir.SameKeywordValue(populated, &ir.Constraints{}, undeclared)) + assert.Equal(t, populatedConstraints(), populated.WithoutKeywords(undeclared)) + assert.Nil(t, (*ir.Constraints)(nil).WithoutKeywords(ir.ConstraintKeywordMin), "a nil set less a keyword is nil") +} + +// TestConstraintIntersection_HoldsUniqueItemsAlone pins what an intersection +// holding no keyword gives: nil for an empty set, which says nothing, and the +// set for one holding uniqueItems alone, which says something. +func TestConstraintIntersection_HoldsUniqueItemsAlone(t *testing.T) { + t.Parallel() + assert.Nil(t, ir.ConstraintIntersectionOf(&ir.Constraints{}).ConstraintsKeepingReceiverOnDisagreement()) + assert.Equal(t, &ir.Constraints{UniqueItems: true}, + intersectionOf(&ir.Constraints{}, &ir.Constraints{UniqueItems: true}).ConstraintsKeepingReceiverOnDisagreement()) +} + +// TestConstraintIntersection_RefusesLiteralsNoDecimalHolds pins a bound or a +// step no Decimal reads: two of them intersect only where they are one text, +// and otherwise conflict, keeping the receiver's, since reading one as zero +// would intersect two bounds into one the source never wrote. +func TestConstraintIntersection_RefusesLiteralsNoDecimalHolds(t *testing.T) { + t.Parallel() + unread, other := ir.BigVal("1p4"), ir.BigVal("2") + for name, tc := range map[string]struct { + keyword ir.ConstraintKeyword + set func(value ir.BigVal) *ir.Constraints + }{ + "a minimum": {ir.ConstraintKeywordMin, func(value ir.BigVal) *ir.Constraints { return &ir.Constraints{Min: &value} }}, + "a maximum": {ir.ConstraintKeywordMax, func(value ir.BigVal) *ir.Constraints { return &ir.Constraints{Max: &value} }}, + "a step": {ir.ConstraintKeywordMultipleOf, func(value ir.BigVal) *ir.Constraints { return &ir.Constraints{MultipleOf: &value} }}, + } { + keyword, set := tc.keyword, tc.set + assert.Empty(t, intersectionOf(set(unread), set(unread)).DisagreeingKeywords(), "%s written twice", name) + assert.True(t, ir.SameKeywordValue(set(unread), set(unread), keyword), "%s written twice", name) + assert.False(t, ir.SameKeywordValue(set(unread), set(other), keyword), name) + for _, pair := range [][2]ir.BigVal{{unread, other}, {other, unread}} { + intersected := intersectionOf(set(pair[0]), set(pair[1])) + assert.Equal(t, []ir.ConstraintKeyword{keyword}, intersected.DisagreeingKeywords(), "%s: %s and %s", name, pair[0], pair[1]) + assert.True(t, ir.SameKeywordValue(set(pair[0]), intersected.ConstraintsKeepingReceiverOnDisagreement(), keyword), "%s: the receiver's is chosen", name) + } + } +} + +// TestConstraintIntersection_ReadsAStepsNumeratorInLowestTerms pins a step of +// more significant digits than the bound reads: its numerator in lowest terms, +// not its coefficient, is held to 1,024 digits, so a coefficient of 1,049 +// digits naming 2^-1500 intersects a unit, as does 2^4000 over 10^1300 to +// 2^2700, and one of 1,026 digits whose numerator keeps them all intersects +// none. +func TestConstraintIntersection_ReadsAStepsNumeratorInLowestTerms(t *testing.T) { + t.Parallel() + fivesOverTen := new(big.Int).Exp(big.NewInt(5), big.NewInt(1500), nil).String() + "e-1500" + twosOverTen := new(big.Int).Exp(big.NewInt(2), big.NewInt(4000), nil).String() + "e-1300" + twos := new(big.Int).Exp(big.NewInt(2), big.NewInt(2700), nil).String() + long := "1." + strings.Repeat("0", 1024) + "1" + require.Greater(t, len(fivesOverTen), 1024+len("e-1500"), "the coefficient passes the bound") + for name, tc := range map[string]struct { + x, y, want string // want "" where refused + }{ + "a power of one half, which a unit is a multiple of": {fivesOverTen, "1", "1"}, + "a power of two over a power of ten it outweighs": {twosOverTen, "1", twos}, + "a long numerator": {long, "2", ""}, + } { + got, intersects := intersectSteps(t, tc.x, tc.y) + require.Equal(t, tc.want != "", intersects, name) + if intersects { + assert.True(t, ir.SameKeywordValue(&ir.Constraints{MultipleOf: bigValOf(t, tc.want)}, got, + ir.ConstraintKeywordMultipleOf), name) + } + } +} + +// TestConstraintIntersection_RefusesALongCoefficientInBoundedWork pins the work +// a step intersection reads, counted in coefficient digits made integers and +// divisions by five: a step far below a unit spelled in one digit intersects +// another reading nothing; a coefficient of 100,000 digits is refused unread; +// and 2^-5000, spelled 5^5000e-5000, carries a power of five past the 4,096th +// and is refused after at most that many divisions, where stripping every five +// the exponent allows costs one division per unit of it; 5^-5000, spelled +// 2^5000e-5000, is refused as a power of two past it. +func TestConstraintIntersection_RefusesALongCoefficientInBoundedWork(t *testing.T) { + t.Parallel() + const mostWork = 4096 + 4097 // a coefficient at the bound and one division past the power's + fivesOverTen := new(big.Int).Exp(big.NewInt(5), big.NewInt(5000), nil).String() + "e-5000" + twosOverTen := new(big.Int).Exp(big.NewInt(2), big.NewInt(5000), nil).String() + "e-5000" + for name, tc := range map[string]struct { + step, beside string + refused bool + }{ + "a step far below a unit, in one digit": {step: "1e-1000000", beside: "3"}, + "a coefficient of 100,000 digits": {step: "0." + strings.Repeat("1", 100_000), refused: true, beside: "3"}, + "a power of five past the bound": {step: fivesOverTen, refused: true, beside: "1"}, + "a power of two past the bound": {step: twosOverTen, refused: true, beside: "1"}, + } { + refused, work, err := ir.StepBoundWork(tc.step) + require.NoError(t, err, name) + assert.Equal(t, tc.refused, refused, name) + assert.LessOrEqual(t, work, mostWork, "%s: the work a refusal reads", name) + _, intersects := intersectSteps(t, tc.step, tc.beside) + assert.Equal(t, !tc.refused, intersects, "%s: whether it intersects %s", name, tc.beside) + } +} diff --git a/ir/constraintintersection_test.go b/ir/constraintintersection_test.go new file mode 100644 index 000000000..72a8ad3d7 --- /dev/null +++ b/ir/constraintintersection_test.go @@ -0,0 +1,486 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "fmt" + "go/constant" + "go/types" + "maps" + "math/big" + "reflect" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// declaredConstraintKeywordsByName returns every ConstraintKeyword constant +// the ir package declares, keyed by its name. +func declaredConstraintKeywordsByName(t *testing.T) map[string]ir.ConstraintKeyword { + t.Helper() + keywords := map[string]ir.ConstraintKeyword{} + for c := range irDecls(t).Objects[*types.Const]() { + named, isNamed := c.Type().(*types.Named) + if !c.Exported() || !isNamed || named.Obj().Name() != "ConstraintKeyword" { + continue + } + value, exact := constant.Uint64Val(c.Val()) + require.True(t, exact, "%s is an unsigned constant", c.Name()) + keywords[c.Name()] = ir.ConstraintKeyword(value) + } + require.NotEmpty(t, keywords, "the ir sources declare the keywords Constraints holds") + return keywords +} + +// declaredConstraintKeywords returns every ConstraintKeyword the ir package +// declares, in value order, which is the order an intersection tries them. +func declaredConstraintKeywords(t *testing.T) []ir.ConstraintKeyword { + t.Helper() + return slices.Sorted(maps.Values(declaredConstraintKeywordsByName(t))) +} + +// bigValOf is text as a BigVal the test owns. +func bigValOf(t *testing.T, text string) *ir.BigVal { + t.Helper() + bigVal, err := ir.NewBigVal(text) + require.NoError(t, err, "%q is a numeric literal", text) + return &bigVal +} + +// intersectionOf intersects each of constraints into the first, left to right. +func intersectionOf(constraints ...*ir.Constraints) ir.ConstraintIntersection { + out := ir.ConstraintIntersectionOf(constraints[0]) + for _, next := range constraints[1:] { + out = out.Intersect(ir.ConstraintIntersectionOf(next)) + } + return out +} + +// assertSameConstraints holds got to want keyword by keyword, a magnitude +// spelled two ways counting as one value, and UniqueItems beside them. +func assertSameConstraints(t *testing.T, keywords []ir.ConstraintKeyword, want, got *ir.Constraints, msg string) { + t.Helper() + for _, keyword := range keywords { + assert.True(t, ir.SameKeywordValue(want, got, keyword), "%s: keyword %d, want %+v, got %+v", msg, keyword, want, got) + } + assert.Equal(t, want != nil && want.UniqueItems, got != nil && got.UniqueItems, "%s: uniqueItems", msg) +} + +// TestConstraintKeyword_EveryKeywordIsOneAPopulatedSetSets holds the +// declared keywords to the fields Constraints holds: a set with every field +// set sets each, one with none sets none, and the set less every keyword +// keeps UniqueItems alone, which is no keyword since it has no absent state. +func TestConstraintKeyword_EveryKeywordIsOneAPopulatedSetSets(t *testing.T) { + t.Parallel() + keywords := declaredConstraintKeywords(t) + populated := populatedConstraints() + + for _, keyword := range keywords { + assert.True(t, populated.SetsKeyword(keyword), "keyword %d", keyword) + assert.False(t, (&ir.Constraints{}).SetsKeyword(keyword), "keyword %d", keyword) + } + + without := populated.WithoutKeywords(keywords...) + assert.Equal(t, &ir.Constraints{UniqueItems: true}, without, "every keyword gone, uniqueItems kept") + assert.Equal(t, populatedConstraints(), populated, "WithoutKeywords returns a new value") +} + +// TestConstraintKeywords_YieldsEveryDeclaredKeywordInOrder holds the +// iterator to every ConstraintKeyword the ir sources declare, in value order, +// and the zero value to none of them, so a keyword ir adds is skipped by no +// walk of the keywords, and an unset one is never taken for a keyword. +func TestConstraintKeywords_YieldsEveryDeclaredKeywordInOrder(t *testing.T) { + t.Parallel() + declared := declaredConstraintKeywords(t) + + assert.Equal(t, declared, slices.Collect(ir.ConstraintKeywords())) + assert.NotContains(t, declared, ir.ConstraintKeyword(0), "the zero value names no keyword") +} + +// TestConstraintKeyword_StringIsItsFieldsJSONMember holds each declared +// keyword's String to the IR JSON member of the Constraints field its +// constant names, ConstraintKeywordMin naming Min, and a value no constant +// names to its number. +func TestConstraintKeyword_StringIsItsFieldsJSONMember(t *testing.T) { + t.Parallel() + fields := reflect.TypeFor[ir.Constraints]() + for name, keyword := range declaredConstraintKeywordsByName(t) { + field, declared := fields.FieldByName(strings.TrimPrefix(name, "ConstraintKeyword")) + require.True(t, declared, "%s names no field of Constraints", name) + member, _, _ := strings.Cut(field.Tag.Get("json"), ",") + assert.Equal(t, member, keyword.String(), name) + } + + pastTheLast := slices.Max(declaredConstraintKeywords(t)) + 1 + assert.Equal(t, "ConstraintKeyword(0)", ir.ConstraintKeyword(0).String()) + assert.Equal(t, fmt.Sprintf("ConstraintKeyword(%d)", uint8(pastTheLast)), pastTheLast.String()) +} + +// TestConstraintKeyword_WithoutKeywordsLeavesTheOthers pins that a keyword +// taken out goes alone: the set less pattern keeps its bounds and steps. +func TestConstraintKeyword_WithoutKeywordsLeavesTheOthers(t *testing.T) { + t.Parallel() + populated := populatedConstraints() + + without := populated.WithoutKeywords(ir.ConstraintKeywordPattern) + + want := populatedConstraints() + want.Pattern = "" + assert.Equal(t, want, without) + assert.False(t, without.SetsKeyword(ir.ConstraintKeywordPattern)) + assert.True(t, without.SetsKeyword(ir.ConstraintKeywordPatternMessage)) +} + +// TestSameKeywordValue_ReadsOneMagnitudeSpelledTwoWaysAsOne pins what saying +// one thing of a keyword is: neither set, or one value, 10 and 1e1 included, +// and never a keyword one side sets and the other leaves out. +func TestSameKeywordValue_ReadsOneMagnitudeSpelledTwoWaysAsOne(t *testing.T) { + t.Parallel() + ten, tenSpelledAsPower, eleven := bigValOf(t, "10"), bigValOf(t, "1e1"), bigValOf(t, "11") + for name, tc := range map[string]struct { + a, b *ir.Constraints + same bool + }{ + "neither sets it": {&ir.Constraints{}, &ir.Constraints{}, true}, + "a nil set says nothing": {nil, &ir.Constraints{}, true}, + "one value": {&ir.Constraints{Min: ten}, &ir.Constraints{Min: ten}, true}, + "one magnitude, two ways": {&ir.Constraints{Min: ten}, &ir.Constraints{Min: tenSpelledAsPower}, true}, + "two magnitudes": {&ir.Constraints{Min: ten}, &ir.Constraints{Min: eleven}, false}, + "one side alone": {&ir.Constraints{Min: ten}, &ir.Constraints{}, false}, + "another keyword set": {&ir.Constraints{Max: ten}, &ir.Constraints{}, true}, + } { + assert.Equal(t, tc.same, ir.SameKeywordValue(tc.a, tc.b, ir.ConstraintKeywordMin), name) + assert.Equal(t, tc.same, ir.SameKeywordValue(tc.b, tc.a, ir.ConstraintKeywordMin), "%s, swapped", name) + } +} + +// TestConstraintIntersection_IntersectsEachKeywordAsTheFoldDoes pins the +// intersection of two sets: the largest minimum, the smallest maximum, a length +// or count the same way, uniqueItems where either says so, a keyword one side +// sets adopted, and one value of a keyword with no order, with nothing +// conflicting. +func TestConstraintIntersection_IntersectsEachKeywordAsTheFoldDoes(t *testing.T) { + t.Parallel() + keywords := declaredConstraintKeywords(t) + a := &ir.Constraints{ + Min: bigValOf(t, "1"), ExclusiveMax: bigValOf(t, "100"), MinLength: new(int64(2)), MaxItems: new(int64(9)), + Pattern: "^a", Precision: new(int64(5)), MinProperties: new(int64(1)), + } + b := &ir.Constraints{ + Min: bigValOf(t, "3"), Max: bigValOf(t, "50"), ExclusiveMax: bigValOf(t, "70"), MinLength: new(int64(1)), + MaxItems: new(int64(4)), Pattern: "^a", Precision: new(int64(5)), UniqueItems: true, MaxProperties: new(int64(8)), + } + want := &ir.Constraints{ + Min: bigValOf(t, "3"), Max: bigValOf(t, "50"), ExclusiveMax: bigValOf(t, "70"), MinLength: new(int64(2)), + MaxItems: new(int64(4)), Pattern: "^a", Precision: new(int64(5)), UniqueItems: true, + MinProperties: new(int64(1)), MaxProperties: new(int64(8)), + } + + for name, intersected := range map[string]ir.ConstraintIntersection{ + "a then b": intersectionOf(a, b), + "b then a": intersectionOf(b, a), + } { + assert.Empty(t, intersected.DisagreeingKeywords(), name) + assertSameConstraints(t, keywords, want, intersected.ConstraintsKeepingReceiverOnDisagreement(), name) + } +} + +// TestConstraintIntersection_ANilSetSaysNothing pins the intersection of one +// and of none: nil holds no keyword, so it is the identity, and an +// intersection holding none gives nil. +func TestConstraintIntersection_ANilSetSaysNothing(t *testing.T) { + t.Parallel() + keywords := declaredConstraintKeywords(t) + some := &ir.Constraints{Max: bigValOf(t, "5"), Pattern: "^p"} + + assert.Nil(t, ir.ConstraintIntersectionOf(nil).ConstraintsKeepingReceiverOnDisagreement()) + assert.Empty(t, ir.ConstraintIntersectionOf(nil).DisagreeingKeywords()) + assertSameConstraints(t, keywords, some, intersectionOf(nil, some).ConstraintsKeepingReceiverOnDisagreement(), "nil, then a set") + assertSameConstraints(t, keywords, some, intersectionOf(some, nil).ConstraintsKeepingReceiverOnDisagreement(), "a set, then nil") +} + +// TestConstraintIntersection_KeepsTheReceiversValueOfAConflict pins a keyword +// no one value holds: it is listed, in keyword order, and the set keeps the +// receiver's value, while the keywords that agree still intersect. +func TestConstraintIntersection_KeepsTheReceiversValueOfAConflict(t *testing.T) { + t.Parallel() + first := &ir.Constraints{Pattern: "^a", Precision: new(int64(3)), MaxLength: new(int64(9))} + second := &ir.Constraints{Pattern: "^b", Precision: new(int64(4)), MaxLength: new(int64(5))} + + intersected := intersectionOf(first, second) + + assert.Equal(t, []ir.ConstraintKeyword{ir.ConstraintKeywordPrecision, ir.ConstraintKeywordPattern}, + intersected.DisagreeingKeywords(), "in keyword order") + constraints := intersected.ConstraintsKeepingReceiverOnDisagreement() + require.NotNil(t, constraints) + assert.Equal(t, "^a", constraints.Pattern, "the receiver's pattern") + assert.Equal(t, int64(3), *constraints.Precision, "the receiver's precision") + assert.Equal(t, int64(5), *constraints.MaxLength, "an agreeing keyword intersects") + assert.Equal(t, "^b", intersectionOf(second, first).ConstraintsKeepingReceiverOnDisagreement().Pattern, "swapped, the other receiver's") +} + +// TestConstraintIntersection_AgreedConstraintsLeaveAConflictOut pins what a +// value is held to: the keywords the sets agree on, in either order, a +// conflicting one left out rather than taken at either side's value, and nil +// where every keyword conflicts. +func TestConstraintIntersection_AgreedConstraintsLeaveAConflictOut(t *testing.T) { + t.Parallel() + keywords := declaredConstraintKeywords(t) + first := &ir.Constraints{Pattern: "^a", Precision: new(int64(3)), MaxLength: new(int64(9))} + second := &ir.Constraints{Pattern: "^b", Precision: new(int64(4)), MaxLength: new(int64(5))} + + for name, intersected := range map[string]ir.ConstraintIntersection{ + "first then second": intersectionOf(first, second), + "second then first": intersectionOf(second, first), + } { + assertSameConstraints(t, keywords, &ir.Constraints{MaxLength: new(int64(5))}, intersected.AgreedConstraints(), name) + } + assert.Nil(t, intersectionOf(&ir.Constraints{Pattern: "^a"}, &ir.Constraints{Pattern: "^b"}).AgreedConstraints()) + assertSameConstraints(t, keywords, first, ir.ConstraintIntersectionOf(first).AgreedConstraints(), "a set alone") +} + +// TestConstraintIntersection_AConflictAbsorbs pins that a refused keyword +// stays refused whatever is intersected after, the receiver's value too, and +// that the summary of many distinct patterns lists one keyword, so a chain's +// summary is one bounded value however many it writes. +func TestConstraintIntersection_AConflictAbsorbs(t *testing.T) { + t.Parallel() + intersected := intersectionOf(&ir.Constraints{Pattern: "^a"}, &ir.Constraints{Pattern: "^b"}) + for name, next := range map[string]*ir.Constraints{ + "nothing": nil, + "the receiver's value": {Pattern: "^a"}, + "the other value": {Pattern: "^b"}, + "a third": {Pattern: "^c"}, + "another keyword alone": {MinLength: new(int64(1))}, + } { + after := intersected.Intersect(ir.ConstraintIntersectionOf(next)) + assert.Equal(t, []ir.ConstraintKeyword{ir.ConstraintKeywordPattern}, after.DisagreeingKeywords(), name) + assert.Equal(t, "^a", after.ConstraintsKeepingReceiverOnDisagreement().Pattern, name) + } + + many := ir.ConstraintIntersectionOf(nil) + for i := range 200 { + many = many.Intersect(ir.ConstraintIntersectionOf(&ir.Constraints{Pattern: fmt.Sprintf("^p%d", i)})) + } + assert.Equal(t, []ir.ConstraintKeyword{ir.ConstraintKeywordPattern}, many.DisagreeingKeywords()) + assert.Equal(t, "^p0", many.ConstraintsKeepingReceiverOnDisagreement().Pattern) +} + +// TestConstraintIntersection_ModifiesNeitherSide pins that an intersection is +// a value: intersecting reads both sides and writes neither, and the set it +// gives is a copy its caller may change. +func TestConstraintIntersection_ModifiesNeitherSide(t *testing.T) { + t.Parallel() + first := &ir.Constraints{Min: bigValOf(t, "1"), Pattern: "^a", MaxLength: new(int64(9))} + second := &ir.Constraints{Min: bigValOf(t, "4"), Pattern: "^b", MaxLength: new(int64(3))} + left, right := ir.ConstraintIntersectionOf(first), ir.ConstraintIntersectionOf(second) + + intersected := left.Intersect(right) + given := intersected.ConstraintsKeepingReceiverOnDisagreement() + given.Pattern = "changed" + *given.MaxLength = 100 + + assert.Equal(t, &ir.Constraints{Min: bigValOf(t, "1"), Pattern: "^a", MaxLength: new(int64(9))}, first) + assert.Equal(t, &ir.Constraints{Min: bigValOf(t, "4"), Pattern: "^b", MaxLength: new(int64(3))}, second) + assert.Equal(t, first, left.ConstraintsKeepingReceiverOnDisagreement(), "the receiver holds what it held") + assert.Equal(t, "^a", intersected.ConstraintsKeepingReceiverOnDisagreement().Pattern, "the intersection holds what it held") + assert.Equal(t, int64(3), *intersected.ConstraintsKeepingReceiverOnDisagreement().MaxLength) + assert.Empty(t, left.DisagreeingKeywords(), "the receiver gained no conflict") +} + +// intersectionPool is sets drawn on every keyword an intersection reads +// differently: bounds, a magnitude spelled two ways, steps whose common +// multiple neither writes, two patterns, two precisions, uniqueItems, nil. +func intersectionPool(t *testing.T) []*ir.Constraints { + t.Helper() + return []*ir.Constraints{ + nil, + {Min: bigValOf(t, "1"), MaxLength: new(int64(9))}, + {Min: bigValOf(t, "1e0"), Max: bigValOf(t, "5"), UniqueItems: true}, + {MultipleOf: bigValOf(t, "4"), Pattern: "^a"}, + {MultipleOf: bigValOf(t, "6"), Precision: new(int64(3))}, + {MultipleOf: bigValOf(t, "1e1"), Pattern: "^b", MinLength: new(int64(2))}, + {MultipleOf: bigValOf(t, "0.4"), Precision: new(int64(4)), MaxLength: new(int64(4))}, + {Pattern: "^a", ExclusiveMin: bigValOf(t, "-2")}, + } +} + +// TestConstraintIntersection_IsAssociativeAndCommutativeButForAConflict holds +// the intersection to the laws a range's combination over jumps needs: every +// grouping of three sets gives one result, its conflicting values included, and +// either order of two gives one result but for a conflicting keyword's value. +func TestConstraintIntersection_IsAssociativeAndCommutativeButForAConflict(t *testing.T) { + t.Parallel() + keywords := declaredConstraintKeywords(t) + pool := intersectionPool(t) + for i, a := range pool { + for j, b := range pool { + ab, ba := intersectionOf(a, b), intersectionOf(b, a) + assert.Equal(t, ab.DisagreeingKeywords(), ba.DisagreeingKeywords(), "%d∩%d against %d∩%d", i, j, j, i) + agreeing := slices.DeleteFunc(slices.Clone(keywords), func(keyword ir.ConstraintKeyword) bool { + return slices.Contains(ab.DisagreeingKeywords(), keyword) + }) + assertSameConstraints(t, agreeing, ab.ConstraintsKeepingReceiverOnDisagreement(), ba.ConstraintsKeepingReceiverOnDisagreement(), fmt.Sprintf("%d∩%d against %d∩%d", i, j, j, i)) + for k, c := range pool { + left := ab.Intersect(ir.ConstraintIntersectionOf(c)) + right := ir.ConstraintIntersectionOf(a).Intersect(intersectionOf(b, c)) + at := fmt.Sprintf("(%d∩%d)∩%d against %d∩(%d∩%d)", i, j, k, i, j, k) + assert.Equal(t, left.DisagreeingKeywords(), right.DisagreeingKeywords(), at) + assertSameConstraints(t, keywords, left.ConstraintsKeepingReceiverOnDisagreement(), right.ConstraintsKeepingReceiverOnDisagreement(), at) + } + } + } +} + +// TestConstraintIntersection_ThreeStepsIntersectAlikeInEveryOrderAndGrouping pins +// a step three distinct multipleOf keywords make: their least common multiple, +// which none writes, in each of the six orders and both groupings. +func TestConstraintIntersection_ThreeStepsIntersectAlikeInEveryOrderAndGrouping(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + steps [3]string + want string + }{ + "integers": {[3]string{"4", "6", "10"}, "60"}, + "fractions and a power": {[3]string{"0.4", "0.6", "1e1"}, "30"}, + "steps far below a unit": {[3]string{"1e-2000", "3e-2000", "7e-2000"}, "21e-2000"}, + } { + want := &ir.Constraints{MultipleOf: bigValOf(t, tc.want)} + for _, order := range [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} { + sets := [3]*ir.Constraints{} + for k, at := range order { + sets[k] = &ir.Constraints{MultipleOf: bigValOf(t, tc.steps[at])} + } + left := intersectionOf(sets[0], sets[1], sets[2]) + right := ir.ConstraintIntersectionOf(sets[0]).Intersect(intersectionOf(sets[1], sets[2])) + for grouping, intersected := range map[string]ir.ConstraintIntersection{"left": left, "right": right} { + at := fmt.Sprintf("%s, order %v, grouped %s", name, order, grouping) + assert.Empty(t, intersected.DisagreeingKeywords(), at) + assert.True(t, ir.SameKeywordValue(want, intersected.ConstraintsKeepingReceiverOnDisagreement(), ir.ConstraintKeywordMultipleOf), + "%s: %+v", at, intersected.ConstraintsKeepingReceiverOnDisagreement()) + } + } + } +} + +// TestConstraintIntersection_BoundsAStepByItsNumerator pins the step +// intersection's bound: two 600-digit steps, one twice the other, intersect to +// the larger, as do they beside a third dividing it, in every grouping; steps +// whose multiple's numerator in lowest terms passes 1,024 digits are refused, +// 1e2000 beside 3e2000 among them, while 1e2000 written twice is one step. +func TestConstraintIntersection_BoundsAStepByItsNumerator(t *testing.T) { + t.Parallel() + ones, twos := strings.Repeat("1", 600), strings.Repeat("2", 600) + coprimeA := new(big.Int).Exp(big.NewInt(2), big.NewInt(1730), nil).String() + coprimeB := new(big.Int).Exp(big.NewInt(3), big.NewInt(1100), nil).String() + require.Greater(t, len(coprimeA)+len(coprimeB), 1025, "their product passes the bound") + for name, tc := range map[string]struct { + steps []string + want string // "" where the step is refused + }{ + "one 600-digit step twice another": {[]string{ones, twos}, twos}, + "the same, the larger first": {[]string{twos, ones}, twos}, + "the same, beside a step dividing both": {[]string{ones, "3", twos}, twos}, + "the same, grouped the other way": {[]string{"3", twos, ones}, twos}, + "two steps whose multiple passes": {[]string{coprimeA, coprimeB}, ""}, + "the same, beside one": {[]string{coprimeA, "1", coprimeB}, ""}, + "a step whose numerator passes": {[]string{"1e2000", "3e2000"}, ""}, + "that step written twice": {[]string{"1e2000", "1e2000"}, "1e2000"}, + "one numerator digit past the bound": {[]string{"1e1024", "3e1024"}, ""}, + "a multiple of 1,024 numerator digits": {[]string{"1e1023", "3e1023"}, "3e1023"}, + } { + sets := make([]*ir.Constraints, len(tc.steps)) + for i, step := range tc.steps { + sets[i] = &ir.Constraints{MultipleOf: bigValOf(t, step)} + } + groupings := map[string]ir.ConstraintIntersection{"left": intersectionOf(sets...)} + if len(sets) == 3 { + groupings["right"] = ir.ConstraintIntersectionOf(sets[0]).Intersect(intersectionOf(sets[1], sets[2])) + } + for grouping, intersected := range groupings { + at := name + ", grouped " + grouping + if tc.want == "" { + assert.Equal(t, []ir.ConstraintKeyword{ir.ConstraintKeywordMultipleOf}, intersected.DisagreeingKeywords(), at) + assert.True(t, ir.SameKeywordValue(sets[0], intersected.ConstraintsKeepingReceiverOnDisagreement(), ir.ConstraintKeywordMultipleOf), + "%s: the receiver's step is chosen", at) + continue + } + assert.Empty(t, intersected.DisagreeingKeywords(), at) + assert.True(t, ir.SameKeywordValue(&ir.Constraints{MultipleOf: bigValOf(t, tc.want)}, intersected.ConstraintsKeepingReceiverOnDisagreement(), + ir.ConstraintKeywordMultipleOf), at) + } + } +} + +// intersectSteps is the step two multipleOf keywords intersect to, and whether +// they intersect. +func intersectSteps(t *testing.T, x, y string) (*ir.Constraints, bool) { + t.Helper() + intersected := intersectionOf(&ir.Constraints{MultipleOf: bigValOf(t, x)}, &ir.Constraints{MultipleOf: bigValOf(t, y)}) + return intersected.ConstraintsKeepingReceiverOnDisagreement(), len(intersected.DisagreeingKeywords()) == 0 +} + +// TestConstraintIntersection_IntersectsTwoStepsToTheirCommonMultiple pins the step +// two multipleOf keywords make, in both orders: one step that is a multiple of +// the other, or their least common multiple, at scales far below a unit too; +// and a refusal for a step that is not positive and for one whose numerator in +// lowest terms, or whose multiple's, passes 1,024 digits, a step 10^1000001 +// times a digit among them. +func TestConstraintIntersection_IntersectsTwoStepsToTheirCommonMultiple(t *testing.T) { + t.Parallel() + threes := func(count int) string { return strings.Repeat("3", count) } + for _, tc := range []struct { + name, x, y string + want string // "" where the pair is refused + }{ + {"one step", "3", "3", "3"}, + {"one step spelled two ways", "10", "1e1", "10"}, + {"a multiple of the other", "6", "2", "6"}, + {"a decimal multiple of the other", "0.25", "0.01", "0.25"}, + {"two primes", "3", "5", "15"}, + {"sharing a factor", "4", "6", "12"}, + {"two decimals", "0.4", "0.6", "1.2"}, + {"a decimal beside an integer", "0.4", "3", "6"}, + {"trailing zeros on one side", "30", "4", "60"}, + {"a shift past the cap", "3e100", "7", "21e100"}, + {"a shift past the cap, with powers of two to cover", "3e100", "7168", "21e100"}, + {"far below one", "3e-1000001", "7e-1000002", "21e-1000001"}, + {"at the bottom of the range", "3e-999999999999999999", "7e-999999999999999999", "21e-999999999999999999"}, + {"a multiple of 1,024 digits", threes(1023), "7", "2" + threes(1022) + "1"}, + {"a multiple past 1,024 digits", threes(1024), "7", ""}, + {"a numerator past 1,024 digits", "3e1000001", "7", ""}, + {"far apart on either side of one", "3e1000001", "7e-1000001", ""}, + {"a shift no integer could hold", "3e999999999999999998", "7e-999999999999999999", ""}, + {"a multiple past what a Decimal holds", "9e999999999999999999", "7", ""}, + {"a zero step", "0", "2", ""}, + {"a negative step", "-3", "2", ""}, + } { + for _, pair := range [][2]string{{tc.x, tc.y}, {tc.y, tc.x}} { + got, intersects := intersectSteps(t, pair[0], pair[1]) + at := fmt.Sprintf("%s: %.40s and %.40s", tc.name, pair[0], pair[1]) + require.Equal(t, tc.want != "", intersects, at) + if intersects { + assert.True(t, ir.SameKeywordValue(&ir.Constraints{MultipleOf: bigValOf(t, tc.want)}, got, + ir.ConstraintKeywordMultipleOf), "%s: %+v", at, got.MultipleOf) + } + } + } +} + +// TestConstraintIntersection_KeepsAStepItChoseAsWritten pins that a step the +// other divides is the literal a declaration wrote, so only a number no +// declaration wrote is spelled by the intersection. +func TestConstraintIntersection_KeepsAStepItChoseAsWritten(t *testing.T) { + t.Parallel() + for _, pair := range [][2]string{{"6.0", "2"}, {"2", "6.0"}} { + got, intersects := intersectSteps(t, pair[0], pair[1]) + require.True(t, intersects) + assert.Equal(t, ir.BigVal("6.0"), *got.MultipleOf) + } +} diff --git a/ir/constraintkeyword.go b/ir/constraintkeyword.go new file mode 100644 index 000000000..6538a2f20 --- /dev/null +++ b/ir/constraintkeyword.go @@ -0,0 +1,286 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "iter" + "strconv" +) + +// ConstraintKeyword is one keyword [Constraints] holds, named by its IR JSON +// member, in the fixed order an intersection and its reports try them. Its +// zero value names none. UniqueItems is none: it has no absent state, and an +// intersection holds it wherever either side does. +type ConstraintKeyword uint8 + +// The keywords of [Constraints], in the order an intersection tries them. +const ( + // ConstraintKeywordMin is Constraints.Min. + ConstraintKeywordMin ConstraintKeyword = iota + 1 + // ConstraintKeywordExclusiveMin is Constraints.ExclusiveMin. + ConstraintKeywordExclusiveMin + // ConstraintKeywordMax is Constraints.Max. + ConstraintKeywordMax + // ConstraintKeywordExclusiveMax is Constraints.ExclusiveMax. + ConstraintKeywordExclusiveMax + // ConstraintKeywordMultipleOf is Constraints.MultipleOf. + ConstraintKeywordMultipleOf + // ConstraintKeywordPrecision is Constraints.Precision. + ConstraintKeywordPrecision + // ConstraintKeywordScale is Constraints.Scale. + ConstraintKeywordScale + // ConstraintKeywordMinLength is Constraints.MinLength. + ConstraintKeywordMinLength + // ConstraintKeywordMaxLength is Constraints.MaxLength. + ConstraintKeywordMaxLength + // ConstraintKeywordMinItems is Constraints.MinItems. + ConstraintKeywordMinItems + // ConstraintKeywordMaxItems is Constraints.MaxItems. + ConstraintKeywordMaxItems + // ConstraintKeywordMinProperties is Constraints.MinProperties. + ConstraintKeywordMinProperties + // ConstraintKeywordMaxProperties is Constraints.MaxProperties. + ConstraintKeywordMaxProperties + // ConstraintKeywordPattern is Constraints.Pattern. + ConstraintKeywordPattern + // ConstraintKeywordPatternMessage is Constraints.PatternMessage. + ConstraintKeywordPatternMessage +) + +// ConstraintKeywords yields every [ConstraintKeyword] once, in their fixed +// order. +func ConstraintKeywords() iter.Seq[ConstraintKeyword] { + return func(yield func(ConstraintKeyword) bool) { + for keyword := ConstraintKeywordMin; keyword <= ConstraintKeywordPatternMessage; keyword++ { + if !yield(keyword) { + return + } + } + } +} + +// String is the IR JSON member of the [Constraints] field keyword names, as +// min or patternMessage, and ConstraintKeyword(n) for a value n no constant +// names. +func (keyword ConstraintKeyword) String() string { + switch keyword { + case ConstraintKeywordMin: + return "min" + case ConstraintKeywordExclusiveMin: + return "exclusiveMin" + case ConstraintKeywordMax: + return "max" + case ConstraintKeywordExclusiveMax: + return "exclusiveMax" + case ConstraintKeywordMultipleOf: + return "multipleOf" + case ConstraintKeywordPrecision: + return "precision" + case ConstraintKeywordScale: + return "scale" + case ConstraintKeywordMinLength: + return "minLength" + case ConstraintKeywordMaxLength: + return "maxLength" + case ConstraintKeywordMinItems: + return "minItems" + case ConstraintKeywordMaxItems: + return "maxItems" + case ConstraintKeywordMinProperties: + return "minProperties" + case ConstraintKeywordMaxProperties: + return "maxProperties" + case ConstraintKeywordPattern: + return "pattern" + case ConstraintKeywordPatternMessage: + return "patternMessage" + default: + return "ConstraintKeyword(" + strconv.Itoa(int(keyword)) + ")" + } +} + +// keywordSlot is where a [Constraints] stores one keyword, exactly one of a +// number's, a count's or a text's, and how two values of it intersect: a +// number or a count by its function, false where no one value says what both +// do, and a text only where both are one. +type keywordSlot struct { + number **BigVal + count **int64 + text *string + numberIntersection func(x, y *BigVal) (*BigVal, bool) + countIntersection func(x, y *int64) (*int64, bool) +} + +// slotOf returns where constraints stores keyword. A value no constant names +// has no slot, so it is set nowhere and clearing it clears nothing. +func (constraints *Constraints) slotOf(keyword ConstraintKeyword) keywordSlot { + switch keyword { + case ConstraintKeywordMin: + return keywordSlot{number: &constraints.Min, numberIntersection: largerNumber} + case ConstraintKeywordExclusiveMin: + return keywordSlot{number: &constraints.ExclusiveMin, numberIntersection: largerNumber} + case ConstraintKeywordMax: + return keywordSlot{number: &constraints.Max, numberIntersection: smallerNumber} + case ConstraintKeywordExclusiveMax: + return keywordSlot{number: &constraints.ExclusiveMax, numberIntersection: smallerNumber} + case ConstraintKeywordMultipleOf: + return keywordSlot{number: &constraints.MultipleOf, numberIntersection: commonStep} + case ConstraintKeywordPrecision: + return keywordSlot{count: &constraints.Precision, countIntersection: equalCount} + case ConstraintKeywordScale: + return keywordSlot{count: &constraints.Scale, countIntersection: equalCount} + case ConstraintKeywordMinLength: + return keywordSlot{count: &constraints.MinLength, countIntersection: largerCount} + case ConstraintKeywordMaxLength: + return keywordSlot{count: &constraints.MaxLength, countIntersection: smallerCount} + case ConstraintKeywordMinItems: + return keywordSlot{count: &constraints.MinItems, countIntersection: largerCount} + case ConstraintKeywordMaxItems: + return keywordSlot{count: &constraints.MaxItems, countIntersection: smallerCount} + case ConstraintKeywordMinProperties: + return keywordSlot{count: &constraints.MinProperties, countIntersection: largerCount} + case ConstraintKeywordMaxProperties: + return keywordSlot{count: &constraints.MaxProperties, countIntersection: smallerCount} + case ConstraintKeywordPattern: + return keywordSlot{text: &constraints.Pattern} + case ConstraintKeywordPatternMessage: + return keywordSlot{text: &constraints.PatternMessage} + default: + return keywordSlot{} + } +} + +// holdsValue reports whether the slot holds a value. +func (slot keywordSlot) holdsValue() bool { + switch { + case slot.number != nil: + return *slot.number != nil + case slot.count != nil: + return *slot.count != nil + case slot.text != nil: + return *slot.text != "" + default: + return false + } +} + +// clear removes the slot's value. +func (slot keywordSlot) clear() { + switch { + case slot.number != nil: + *slot.number = nil + case slot.count != nil: + *slot.count = nil + case slot.text != nil: + *slot.text = "" + } +} + +// SetsKeyword reports whether constraints sets keyword. A nil set sets none. +func (constraints *Constraints) SetsKeyword(keyword ConstraintKeyword) bool { + return constraints != nil && constraints.slotOf(keyword).holdsValue() +} + +// KeywordText returns the value constraints sets keyword to as written, a +// count in decimal, "" where it sets none, and whether keyword holds a text +// rather than a number or a count. A nil set sets none. +func (constraints *Constraints) KeywordText(keyword ConstraintKeyword) (written string, isText bool) { + if constraints == nil { + constraints = &Constraints{} + } + slot := constraints.slotOf(keyword) + switch { + case slot.text != nil: + return *slot.text, true + case !slot.holdsValue(): + return "", false + case slot.number != nil: + return string(**slot.number), false + default: + return strconv.FormatInt(**slot.count, 10), false + } +} + +// SameKeywordValue reports whether a and b say one thing of keyword: neither +// sets it, or both set one value, one magnitude spelled two ways (10, 1e1) +// included. A literal no Decimal holds is the same as another only by its +// text. A nil set sets nothing. +func SameKeywordValue(a, b *Constraints, keyword ConstraintKeyword) bool { + aSets, bSets := a.SetsKeyword(keyword), b.SetsKeyword(keyword) + if !aSets || !bSets { + return aSets == bSets + } + x, y := a.slotOf(keyword), b.slotOf(keyword) + switch { + case x.number != nil: + order, ordered := compareNumbers(**x.number, **y.number) + return ordered && order == 0 + case x.count != nil: + return **x.count == **y.count + default: + return *x.text == *y.text + } +} + +// WithoutKeywords is a new value: constraints less each of keywords, nil for a +// nil set. It writes nothing to constraints. +func (constraints *Constraints) WithoutKeywords(keywords ...ConstraintKeyword) *Constraints { + out := constraints.copied() + if out == nil { + return nil + } + for _, keyword := range keywords { + out.slotOf(keyword).clear() + } + return out +} + +// copied returns a copy of constraints sharing no pointer with it, nil for a +// nil set. +func (constraints *Constraints) copied() *Constraints { + if constraints == nil { + return nil + } + out := *constraints + for keyword := range ConstraintKeywords() { + slot := out.slotOf(keyword) + switch { + case slot.number != nil && *slot.number != nil: + number := **slot.number + *slot.number = &number + case slot.count != nil && *slot.count != nil: + count := **slot.count + *slot.count = &count + } + } + return &out +} + +// holdsNothing reports whether constraints sets no keyword and no UniqueItems. +func (constraints *Constraints) holdsNothing() bool { + if constraints == nil { + return true + } + for keyword := range ConstraintKeywords() { + if constraints.SetsKeyword(keyword) { + return false + } + } + return !constraints.UniqueItems +} + +// compareNumbers orders a and b by magnitude, and returns false where either is +// a literal no Decimal holds, unless they are one text. Reading such a literal +// as zero would intersect two bounds into one the source never wrote. +func compareNumbers(a, b BigVal) (int, bool) { + if a == b { + return 0, true + } + x, errX := a.Decimal() + y, errY := b.Decimal() + if errX != nil || errY != nil { + return 0, false + } + return x.Cmp(y), true +} diff --git a/ir/constraintkeyword_test.go b/ir/constraintkeyword_test.go new file mode 100644 index 000000000..a91fd5ace --- /dev/null +++ b/ir/constraintkeyword_test.go @@ -0,0 +1,55 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// TestConstraints_KeywordTextSpellsEachKeyword pins KeywordText over every +// keyword: a number as written, a count in decimal and a text as it is, "" from +// an empty or a nil set, and whether the keyword holds a text either way. A +// value no constant names is set by none and holds no text. +func TestConstraints_KeywordTextSpellsEachKeyword(t *testing.T) { + t.Parallel() + type text struct { + written string + isText bool + } + want := map[ir.ConstraintKeyword]text{ + ir.ConstraintKeywordMin: {"1", false}, + ir.ConstraintKeywordExclusiveMin: {"0", false}, + ir.ConstraintKeywordMax: {"100", false}, + ir.ConstraintKeywordExclusiveMax: {"101", false}, + ir.ConstraintKeywordMultipleOf: {"5", false}, + ir.ConstraintKeywordPrecision: {"10", false}, + ir.ConstraintKeywordScale: {"2", false}, + ir.ConstraintKeywordMinLength: {"1", false}, + ir.ConstraintKeywordMaxLength: {"255", false}, + ir.ConstraintKeywordMinItems: {"1", false}, + ir.ConstraintKeywordMaxItems: {"10", false}, + ir.ConstraintKeywordMinProperties: {"1", false}, + ir.ConstraintKeywordMaxProperties: {"20", false}, + ir.ConstraintKeywordPattern: {"^[a-z]+$", true}, + ir.ConstraintKeywordPatternMessage: {"lowercase letters only", true}, + ir.ConstraintKeywordPatternMessage + 1: {"", false}, + } + keywords := append(slices.Collect(ir.ConstraintKeywords()), ir.ConstraintKeywordPatternMessage+1) + for _, keyword := range keywords { + expected, ok := want[keyword] + require.True(t, ok, "keyword %s has a row", keyword) + written, isText := populatedConstraints().KeywordText(keyword) + assert.Equal(t, expected, text{written, isText}, "%s", keyword) + for _, unset := range []*ir.Constraints{{}, nil} { + written, isText := unset.KeywordText(keyword) + assert.Equal(t, text{"", expected.isText}, text{written, isText}, "%s unset in %v", keyword, unset) + } + } +} diff --git a/ir/constraints.go b/ir/constraints.go index 44676279a..078149a28 100644 --- a/ir/constraints.go +++ b/ir/constraints.go @@ -93,6 +93,14 @@ type Encoding struct { Schema *TypeRef `json:"schema,omitzero"` } +// Encodes reports whether encoding names the scheme a value is written in +// (Name), which makes a value under it, and a chain holding it, encoded +// (docs/ir/constraints.md#encodings). A MediaType or a Schema alone says what +// the value holds, not how it is written. +func (encoding *Encoding) Encodes() bool { + return encoding != nil && encoding.Name != "" +} + // XMLHints describes an XML wire shape that diverges from the JSON-implied one // (docs/ir/constraints.md#xml-hints). Hints attach at TypeCommon (root shape) // and Property, whose hints override the type's field by field: a field the diff --git a/ir/constraintsempty.go b/ir/constraintsempty.go new file mode 100644 index 000000000..9309eae8c --- /dev/null +++ b/ir/constraintsempty.go @@ -0,0 +1,92 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +// ConstraintsAdmitNoValue reports whether constraints, read alone, admit no +// value of kind (docs/ir/constraints.md#constraints): numeric ends that cross, +// or meet where either is exclusive, or a minimum count past its maximum. A +// bound no Decimal holds is passed over. An exclusive pair with no integer +// between, and a MultipleOf with no multiple in range, are not judged: Decimal +// compares and does no arithmetic. +func ConstraintsAdmitNoValue(constraints *Constraints, kind ValueKind) bool { + if constraints == nil { + return false + } + switch { + case kind == ValueNumber: + return numberRangeEmpty(constraints) + case ConstraintKeywordMinLength.Binds(kind): + return countsCross(constraints.MinLength, constraints.MaxLength) + case ConstraintKeywordMinItems.Binds(kind): + return countsCross(constraints.MinItems, constraints.MaxItems) + case ConstraintKeywordMinProperties.Binds(kind): + return countsCross(constraints.MinProperties, constraints.MaxProperties) + default: + return false + } +} + +// numberRangeEmpty reports whether the numeric ends constraints set leave no +// number between them (ConstraintsAdmitNoValue). +func numberRangeEmpty(constraints *Constraints) bool { + low, lowSet := tighterEnd(constraints.Min, constraints.ExclusiveMin, lowerSide) + high, highSet := tighterEnd(constraints.Max, constraints.ExclusiveMax, upperSide) + if !lowSet || !highSet { + return false + } + order := low.value.Cmp(high.value) + return order > 0 || order == 0 && (low.exclusive || high.exclusive) +} + +// rangeSide is the side of a numeric range an end bounds. +type rangeSide uint8 + +// The sides of a numeric range. +const ( + // lowerSide is the side Min and ExclusiveMin bound. + lowerSide rangeSide = iota + // upperSide is the side Max and ExclusiveMax bound. + upperSide +) + +// rangeEnd is one end of a numeric range: its value, and whether the range +// leaves that value out. +type rangeEnd struct { + value Decimal + exclusive bool +} + +// tighterEnd returns, of inclusive and exclusive, two ends of side, the one +// admitting fewer numbers, and false where neither is set. Of two equal ends +// the exclusive one is tighter. An end no Decimal holds is passed over. +func tighterEnd(inclusive, exclusive *BigVal, side rangeSide) (rangeEnd, bool) { + var end rangeEnd + set := false + for _, candidate := range [...]struct { + bound *BigVal + exclusive bool + }{{inclusive, false}, {exclusive, true}} { + if candidate.bound == nil { + continue + } + decimal, err := candidate.bound.Decimal() + if err != nil { + continue + } + order := decimal.Cmp(end.value) + if side == upperSide { + order = -order + } + if !set || order > 0 || order == 0 && candidate.exclusive { + end, set = rangeEnd{value: decimal, exclusive: candidate.exclusive}, true + } + } + return end, set +} + +// countsCross reports whether a minimum and a maximum count are both set and +// no count lies between them. +func countsCross(minimum, maximum *int64) bool { + return minimum != nil && maximum != nil && *minimum > *maximum +} diff --git a/ir/constraintsempty_test.go b/ir/constraintsempty_test.go new file mode 100644 index 000000000..a21325b58 --- /dev/null +++ b/ir/constraintsempty_test.go @@ -0,0 +1,59 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestConstraintsAdmitNoValue_ReadsEachKindsEnds holds the one reading of +// bounds that admit no value: a number's ends, the tighter of a bound and its +// exclusive form on each side, crossing or meeting where either is exclusive, +// a bound no Decimal holds passed over; a count's minimum past its maximum for +// text and bytes, lists and objects; and no other kind, an unknown one among +// them, nor a nil set, nor a pair with no integer between, judged. +func TestConstraintsAdmitNoValue_ReadsEachKindsEnds(t *testing.T) { + t.Parallel() + big := func(text string) *ir.BigVal { return new(ir.BigVal(text)) } + count := func(count int64) *int64 { return new(count) } + crossedCounts := &ir.Constraints{MinLength: count(3), MaxLength: count(1), MinItems: count(3), MaxItems: count(1), + MinProperties: count(3), MaxProperties: count(1)} + for _, tc := range []struct { + name string + constraints *ir.Constraints + kind ir.ValueKind + want bool + }{ + {"a nil set", nil, ir.ValueNumber, false}, + {"a minimum above a maximum", &ir.Constraints{Min: big("5"), Max: big("3")}, ir.ValueNumber, true}, + {"a minimum at a maximum", &ir.Constraints{Min: big("5"), Max: big("5.0")}, ir.ValueNumber, false}, + {"an exclusive maximum at the minimum", &ir.Constraints{Min: big("5"), ExclusiveMax: big("5")}, ir.ValueNumber, true}, + {"an exclusive minimum at the maximum", &ir.Constraints{ExclusiveMin: big("5"), Max: big("5")}, ir.ValueNumber, true}, + {"the tighter of a minimum and an exclusive one", &ir.Constraints{Min: big("1"), ExclusiveMin: big("6"), Max: big("5")}, ir.ValueNumber, true}, + {"an exclusive minimum below the minimum", &ir.Constraints{Min: big("5"), ExclusiveMin: big("1"), Max: big("5")}, ir.ValueNumber, false}, + {"the tighter of a maximum and an exclusive one", &ir.Constraints{Min: big("5"), Max: big("9"), ExclusiveMax: big("5")}, ir.ValueNumber, true}, + {"an exclusive maximum above the maximum", &ir.Constraints{Min: big("5"), Max: big("5"), ExclusiveMax: big("9")}, ir.ValueNumber, false}, + {"one end alone", &ir.Constraints{Min: big("5")}, ir.ValueNumber, false}, + {"an end no Decimal holds", &ir.Constraints{Min: big("five"), Max: big("3")}, ir.ValueNumber, false}, + {"an exclusive pair with no integer between", &ir.Constraints{ExclusiveMin: big("1"), ExclusiveMax: big("2")}, ir.ValueNumber, false}, + {"lengths crossing, of a string", crossedCounts, ir.ValueString, true}, + {"lengths crossing, of bytes", crossedCounts, ir.ValueBytes, true}, + {"lengths crossing, of a symbol", crossedCounts, ir.ValueSymbol, true}, + {"items crossing", crossedCounts, ir.ValueList, true}, + {"members crossing", crossedCounts, ir.ValueObject, true}, + {"lengths meeting", &ir.Constraints{MinLength: count(2), MaxLength: count(2)}, ir.ValueString, false}, + {"a count of another kind", crossedCounts, ir.ValueNumber, false}, + {"a kind no bound applies to", crossedCounts, ir.ValueBool, false}, + {"a kind ir does not declare", crossedCounts, ir.ValueKind("no-such-kind"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, ir.ConstraintsAdmitNoValue(tc.constraints, tc.kind)) + }) + } +} diff --git a/ir/decimal.go b/ir/decimal.go index 7606a6669..b3f2bf0b1 100644 --- a/ir/decimal.go +++ b/ir/decimal.go @@ -88,85 +88,85 @@ type decimalLiteral struct { point bool } -// ParseDecimal reads s as a [Decimal]. It refuses text outside the decimal +// ParseDecimal reads text as a [Decimal]. It refuses text outside the decimal // numeric grammar with [ErrNotDecimal], and a nonzero value whose leading digit // carries a power of ten outside ±[MaxDecimalExp] with an [ExponentRangeError]. // Zero is accepted at any written exponent. The result is the zero Decimal on // error, which reads as the number zero, so a caller must check the error. -func ParseDecimal(s string) (Decimal, error) { - decimalLiteral, exp, err := readDecimal(s) +func ParseDecimal(text string) (Decimal, error) { + decimalLiteral, exp, err := readDecimal(text) if err != nil { - return Decimal{}, fmt.Errorf("decimal: %q: %w", s, err) + return Decimal{}, fmt.Errorf("decimal: %q: %w", text, err) } return decimalLiteral.decimal(exp), nil } -// readDecimal splits s and reads the power of ten its leading digit carries, so -// [NewBigVal] spells the literal from the split that [ParseDecimal] reads the -// value from. The split is substrings of s, so reading it allocates nothing. -// Its error is bare, for each of them to name itself in. -func readDecimal(s string) (decimalLiteral, int64, error) { - decimalLiteralValue, ok := scanDecimal(s) +// readDecimal splits text and reads the power of ten its leading digit carries, +// so [NewBigVal] spells the literal from the split that [ParseDecimal] reads +// the value from. The split is substrings of text, so reading it allocates +// nothing. Its error is bare, for each of them to name itself in. +func readDecimal(text string) (decimalLiteral, int64, error) { + literal, ok := scanDecimal(text) if !ok { return decimalLiteral{}, 0, ErrNotDecimal } - exp, err := decimalLiteralValue.leadExponent() + exp, err := literal.leadExponent() if err != nil { return decimalLiteral{}, 0, err } - return decimalLiteralValue, exp, nil + return literal, exp, nil } -// scanDecimal splits s by the grammar sign? (digits ("." digits*)? | "." digits) -// ((e|E) sign? digits)? over ASCII and nothing else, and reports false for any -// other text. math/big's base-10 parser reads a wider grammar, a p/P binary -// exponent among it ("1p4" is 16), so none of it decides membership. -func scanDecimal(s string) (decimalLiteral, bool) { - var decimalLiteralValue decimalLiteral +// scanDecimal splits text by the grammar sign? (digits ("." digits*)? | "." +// digits) ((e|E) sign? digits)? over ASCII and nothing else, and reports false +// for any other text. math/big's base-10 parser reads a wider grammar, a p/P +// binary exponent among it ("1p4" is 16), so none of it decides membership. +func scanDecimal(text string) (decimalLiteral, bool) { + var literal decimalLiteral i := 0 - if i < len(s) && (s[i] == '+' || s[i] == '-') { - decimalLiteralValue.neg = s[i] == '-' + if i < len(text) && (text[i] == '+' || text[i] == '-') { + literal.neg = text[i] == '-' i++ } - end := scanDigits(s, i) - decimalLiteralValue.intPart, i = s[i:end], end - if i < len(s) && s[i] == '.' { - end = scanDigits(s, i+1) - decimalLiteralValue.frac, decimalLiteralValue.point, i = s[i+1:end], true, end + end := scanDigits(text, i) + literal.intPart, i = text[i:end], end + if i < len(text) && text[i] == '.' { + end = scanDigits(text, i+1) + literal.frac, literal.point, i = text[i+1:end], true, end } - if decimalLiteralValue.intPart == "" && decimalLiteralValue.frac == "" { + if literal.intPart == "" && literal.frac == "" { return decimalLiteral{}, false // no digit anywhere: "", "+", ".", "Inf" } - if i < len(s) && (s[i] == 'e' || s[i] == 'E') { + if i < len(text) && (text[i] == 'e' || text[i] == 'E') { start := i i++ - if i < len(s) && (s[i] == '+' || s[i] == '-') { + if i < len(text) && (text[i] == '+' || text[i] == '-') { i++ } - end = scanDigits(s, i) + end = scanDigits(text, i) if end == i { return decimalLiteral{}, false // an e with no exponent digits } - decimalLiteralValue.exponent, i = s[start:end], end + literal.exponent, i = text[start:end], end } - if i != len(s) { + if i != len(text) { return decimalLiteral{}, false // unconsumed text: "0x10", "1p4", "5 " } - return decimalLiteralValue, true + return literal, true } // scanDigits returns the index past the run of ASCII digits that starts at -// s[i]. -func scanDigits(s string, i int) int { - for i < len(s) && isASCIIDigit(s[i]) { +// text[i]. +func scanDigits(text string, i int) int { + for i < len(text) && isASCIIDigit(text[i]) { i++ } return i } -// isASCIIDigit reports whether b is a decimal digit. The grammar is ASCII only, -// so a byte scan is exact here and needs no rune decoding. -func isASCIIDigit(b byte) bool { return b >= '0' && b <= '9' } +// isASCIIDigit reports whether character is a decimal digit. The grammar is +// ASCII only, so a byte scan is exact here and needs no rune decoding. +func isASCIIDigit(character byte) bool { return character >= '0' && character <= '9' } // exponentValue reads the exponent text scanDecimal vouched for: empty, or an // e or E, an optional sign and at least one digit. It saturates at @@ -181,18 +181,18 @@ func exponentValue(exponent string) int64 { if neg || body[0] == '+' { body = body[1:] } - var e int64 + var magnitude int64 for i := range len(body) { - if e >= expSaturation/10 { - e = expSaturation + if magnitude >= expSaturation/10 { + magnitude = expSaturation break } - e = e*10 + int64(body[i]-'0') + magnitude = magnitude*10 + int64(body[i]-'0') } if neg { - return -e + return -magnitude } - return e + return magnitude } // leadExponent returns the power of ten l's leading significant digit carries, @@ -202,7 +202,7 @@ func exponentValue(exponent string) int64 { // // The sum below stays inside int64: exponentValue is at most 4·10¹⁸ in // magnitude and the digit term at most len(s), which is below Go's largest -// allocation. Saturating an exponent never changes a verdict, since a saturated +// allocation. Saturating an exponent never changes an answer, since a saturated // exponent plus any string's digit count is still past the bound. func (l decimalLiteral) leadExponent() (int64, error) { zeros := l.leadingZeros() @@ -294,16 +294,16 @@ func (d Decimal) String() string { if d.digits == "" { return "0" } - var b strings.Builder + var builder strings.Builder if d.neg { - b.WriteByte('-') + builder.WriteByte('-') } - b.WriteByte(d.digits[0]) + builder.WriteByte(d.digits[0]) if len(d.digits) > 1 { - b.WriteByte('.') - b.WriteString(d.digits[1:]) + builder.WriteByte('.') + builder.WriteString(d.digits[1:]) } - b.WriteByte('e') - b.WriteString(strconv.FormatInt(d.exp, 10)) - return b.String() + builder.WriteByte('e') + builder.WriteString(strconv.FormatInt(d.exp, 10)) + return builder.String() } diff --git a/ir/decimal_property_test.go b/ir/decimal_property_test.go index 39f4d2d98..d7d572217 100644 --- a/ir/decimal_property_test.go +++ b/ir/decimal_property_test.go @@ -37,27 +37,27 @@ func FuzzParseDecimal_ReadsWhatNewBigValKeeps(f *testing.F) { f.Add(seed) } - f.Fuzz(func(t *testing.T, s string) { - bigVal, newErr := ir.NewBigVal(s) - decimal, parseErr := ir.ParseDecimal(s) + f.Fuzz(func(t *testing.T, text string) { + bigVal, newErr := ir.NewBigVal(text) + decimal, parseErr := ir.ParseDecimal(text) if (newErr == nil) != (parseErr == nil) { - t.Fatalf("NewBigVal(%q) error %v, ParseDecimal error %v", s, newErr, parseErr) + t.Fatalf("NewBigVal(%q) error %v, ParseDecimal error %v", text, newErr, parseErr) } if newErr != nil { for _, sentinel := range []error{ir.ErrNotDecimal, ir.ErrExponentRange} { if errors.Is(newErr, sentinel) != errors.Is(parseErr, sentinel) { - t.Fatalf("%q: NewBigVal says %v, ParseDecimal says %v", s, newErr, parseErr) + t.Fatalf("%q: NewBigVal says %v, ParseDecimal says %v", text, newErr, parseErr) } } return } kept, err := ir.ParseDecimal(string(bigVal)) if err != nil || kept != decimal { - t.Fatalf("NewBigVal(%q) = %q reads to %v (%v), but the input reads to %v", s, bigVal, kept, err, decimal) + t.Fatalf("NewBigVal(%q) = %q reads to %v (%v), but the input reads to %v", text, bigVal, kept, err, decimal) } again, err := ir.NewBigVal(string(bigVal)) if err != nil || again != bigVal { - t.Fatalf("NewBigVal(%q) = %q, and storing it again gives %q (%v)", s, bigVal, again, err) + t.Fatalf("NewBigVal(%q) = %q, and storing it again gives %q (%v)", text, bigVal, again, err) } }) } diff --git a/ir/decimal_test.go b/ir/decimal_test.go index 57ce2031a..3a561c5cc 100644 --- a/ir/decimal_test.go +++ b/ir/decimal_test.go @@ -24,10 +24,10 @@ var decimalSpellings = []string{ } // mustParseDecimal reads a literal the caller knows is a decimal in range. -func mustParseDecimal(t *testing.T, s string) ir.Decimal { +func mustParseDecimal(t *testing.T, text string) ir.Decimal { t.Helper() - decimal, err := ir.ParseDecimal(s) - require.NoError(t, err, "%q is a decimal literal in range", s) + decimal, err := ir.ParseDecimal(text) + require.NoError(t, err, "%q is a decimal literal in range", text) return decimal } @@ -100,7 +100,7 @@ func TestParseDecimal_RefusesWhatIsNotADecimalLiteral(t *testing.T) { // power of ten the leading significant digit carries, not on the exponent as // written. 0.01e1000000000000000000 is in range and 10e999999999999999999 is // not, though their written exponents say the opposite, and zero is held at any -// exponent. A saturated exponent never changes a verdict. +// exponent. A saturated exponent never changes an answer. func TestParseDecimal_HoldsTheExponentRange(t *testing.T) { t.Parallel() for _, tc := range []struct { @@ -207,7 +207,7 @@ func TestDecimal_CmpOrdersEveryDecimalSpellingExactly(t *testing.T) { want int }{ {name: "one value, one spelling", a: "1", b: "1", want: 0}, - {name: "an exponent against the digits it stands for", a: "1e2", b: "100", want: 0}, + {name: "an exponent against the digits it names", a: "1e2", b: "100", want: 0}, {name: "a trailing zero the exponent moved", a: "5e1", b: "50", want: 0}, {name: "a fraction against its exponent form", a: "0.001", b: "1e-3", want: 0}, {name: "zero however it is written", a: "0", b: "-0.0", want: 0}, @@ -262,11 +262,11 @@ func TestDecimal_EqualityIsOneValue(t *testing.T) { } } - byValue := map[ir.Decimal]bool{} + by := map[ir.Decimal]bool{} for _, s := range []string{"1500", "15e2", "1.5e3", "1500.000"} { - byValue[mustParseDecimal(t, s)] = true + by[mustParseDecimal(t, s)] = true } - assert.Len(t, byValue, 1, "four spellings of one value are one key") + assert.Len(t, by, 1, "four spellings of one value are one key") } // TestDecimal_ZeroValueIsZero pins what a caller that drops ParseDecimal's diff --git a/ir/declarations.go b/ir/declarations.go index 1606a0596..2192cdd68 100644 --- a/ir/declarations.go +++ b/ir/declarations.go @@ -41,9 +41,10 @@ type IDDeclarations struct { paths PathLog } -// Visit records the identity v declares, if any, and asks for v's children. -func (d *IDDeclarations) Visit(v reflect.Value, at WalkPath) bool { - if class, id, declares := d.ids.DeclaredIDOf(v); declares && id != "" { +// Visit records the identity value declares, if any, and asks for value's +// children. +func (d *IDDeclarations) Visit(value reflect.Value, at WalkPath) bool { + if class, id, declares := d.ids.DeclaredIDOf(value); declares && id != "" { d.list = appendGrowing(d.list, IDDeclaration{Class: class, ID: id}) d.paths.Record(at) } @@ -75,23 +76,23 @@ type IDReader struct { fieldOf func(reflect.Type) idField } -// DeclaredIDOf returns the class of ID v declares for itself, that ID, and -// whether v declares one at all: a field named ID that v's own struct type -// declares, of a named string type. A field an embedded struct promotes is that -// struct's declaration, not v's. +// DeclaredIDOf returns the class of ID value declares for itself, that ID, and +// whether value declares one at all: a field named ID that value's own struct +// type declares, of a named string type. A field an embedded struct promotes is +// that struct's declaration, not value's. // // An empty ID is reported with declares true, so a checker can flag it where // [IDDeclarations] drops it. A value that is no such struct, a pointer, a // non-struct and the zero [reflect.Value] included, declares nothing. -func (r *IDReader) DeclaredIDOf(v reflect.Value) (class reflect.Type, id string, declares bool) { - if v.Kind() != reflect.Struct { +func (r *IDReader) DeclaredIDOf(value reflect.Value) (class reflect.Type, id string, declares bool) { + if value.Kind() != reflect.Struct { return nil, "", false } - idField := r.field(v.Type()) + idField := r.field(value.Type()) if !idField.declares() { return nil, "", false } - return idField.class, idField.of(v), true + return idField.class, idField.of(value), true } // field returns where struct type t declares its identity, reading t only the @@ -104,12 +105,12 @@ func (r *IDReader) field(t reflect.Type) idField { if read == nil { read = declaredIDField } - idFieldValue := read(t) + idFound := read(t) if r.fields == nil { r.fields = map[reflect.Type]idField{} } - r.fields[t] = idFieldValue - return idFieldValue + r.fields[t] = idFound + return idFound } // idField is where a struct type declares its own identity: the index of the @@ -125,9 +126,9 @@ func (f idField) declares() bool { return f.class != nil } -// of returns the identity v, a value of the type f was read off, declares. -func (f idField) of(v reflect.Value) string { - return v.Field(f.index).String() +// of returns the identity value, a value of the type f was read off, declares. +func (f idField) of(value reflect.Value) string { + return value.Field(f.index).String() } // declaredIDField returns the field through which struct type t declares its @@ -141,8 +142,8 @@ func (f idField) of(v reflect.Value) string { // not a named string type settles no class of reference. func declaredIDField(t reflect.Type) idField { for i := range t.NumField() { - if f := t.Field(i); f.Name == idFieldName && namedString(f.Type) { - return idField{index: i, class: f.Type} + if field := t.Field(i); field.Name == idFieldName && namedString(field.Type) { + return idField{index: i, class: field.Type} } } return idField{} @@ -201,8 +202,8 @@ func appendIDClasses(dst []reflect.Type, classes map[reflect.Type]bool, t reflec if idField := declaredIDField(t); idField.declares() { classes[idField.class] = true } - for f := range t.Fields() { - dst = append(dst, f.Type) + for field := range t.Fields() { + dst = append(dst, field.Type) } return dst default: diff --git a/ir/declarations_test.go b/ir/declarations_test.go index 54fda3c4e..41fe87106 100644 --- a/ir/declarations_test.go +++ b/ir/declarations_test.go @@ -212,10 +212,10 @@ func TestIDReader_ReadsEachStructTypeOnce(t *testing.T) { doc.Services[0].Groups[0].Operations = append(doc.Services[0].Groups[0].Operations, ir.Operation{ID: "operation/y"}, ir.Operation{ID: "operation/z"}) structs, types := 0, map[reflect.Type]bool{} - ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, _ ir.WalkPath) bool { - if v.Kind() == reflect.Struct { + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, _ ir.WalkPath) bool { + if value.Kind() == reflect.Struct { structs++ - types[v.Type()] = true + types[value.Type()] = true } return true })) @@ -224,8 +224,8 @@ func TestIDReader_ReadsEachStructTypeOnce(t *testing.T) { reads := 0 idReader := ir.CountingIDReader(&reads) var operations []string - ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, _ ir.WalkPath) bool { - if class, id, _ := idReader.DeclaredIDOf(v); class == reflect.TypeFor[ir.OperationID]() { + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, _ ir.WalkPath) bool { + if class, id, _ := idReader.DeclaredIDOf(value); class == reflect.TypeFor[ir.OperationID]() { operations = append(operations, id) } return true @@ -291,8 +291,8 @@ func TestIDDeclarations_GrowsTheListGeometrically(t *testing.T) { recording := testing.AllocsPerRun(3, func() { var ids ir.IDReader var log ir.PathLog - ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if _, id, declares := ids.DeclaredIDOf(v); declares && id != "" { + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if _, id, declares := ids.DeclaredIDOf(value); declares && id != "" { log.Record(at) } return true diff --git a/ir/decodeonlyroutes_test.go b/ir/decodeonlyroutes_test.go new file mode 100644 index 000000000..f07d37bd7 --- /dev/null +++ b/ir/decodeonlyroutes_test.go @@ -0,0 +1,68 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "slices" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestDiscriminator_DecodeOnlyRoutesOmittedWhereNilOrEmpty pins that nil and +// empty mean the same, no route a decoder reads beyond Mapping, and encode +// alike: the field is left out. +func TestDiscriminator_DecodeOnlyRoutesOmittedWhereNilOrEmpty(t *testing.T) { + t.Parallel() + for name, routes := range map[string]map[string]ir.TypeID{"nil": nil, "empty": {}} { + t.Run(name, func(t *testing.T) { + t.Parallel() + got := assertDeterministicMarshal(t, ir.Discriminator{DecodeOnlyRoutes: routes}) + assert.Equal(t, `{"inferred":false}`, got) + }) + } +} + +// TestDiscriminator_DecodeOnlyRoutesDeterministic pins Class C for the field: +// it marshals with its keys in sorted order on every run, beside Mapping. +func TestDiscriminator_DecodeOnlyRoutesDeterministic(t *testing.T) { + t.Parallel() + discriminator := ir.Discriminator{ + Mapping: map[string]ir.TypeID{"m": "type/M"}, + DecodeOnlyRoutes: map[string]ir.TypeID{"Z": "type/Z", "M": "type/M2", "A": "type/A", "Q": "type/Q"}, + } + + got := assertDeterministicMarshal(t, discriminator) + + assert.Contains(t, got, `"decodeOnlyRoutes":{"A":"type/A","M":"type/M2","Q":"type/Q","Z":"type/Z"}`) +} + +// TestTypeEdges_DiscriminatorDecodeOnlyRoutesAreEdges holds a decode-only +// route's target to the edges a mapping's is, a reference a consumer must +// follow: yielded in sorted key order, after Mapping's and before Default. +func TestTypeEdges_DiscriminatorDecodeOnlyRoutesAreEdges(t *testing.T) { + t.Parallel() + alone := &ir.Union{Discriminator: &ir.Discriminator{ + DecodeOnlyRoutes: map[string]ir.TypeID{"b": "type/b", "a": "type/a", "c": "type/c"}, + }} + assert.Equal(t, []ir.TypeID{"type/a", "type/b", "type/c"}, slices.Collect(ir.TypeEdges(alone))) + + beside := &ir.Model{Discriminator: &ir.Discriminator{ + Mapping: map[string]ir.TypeID{"y": "type/y", "x": "type/x"}, + DecodeOnlyRoutes: map[string]ir.TypeID{"Z": "type/z", "W": "type/w"}, + Default: "type/default", + }} + assert.Equal(t, []ir.TypeID{"type/x", "type/y", "type/w", "type/z", "type/default"}, + slices.Collect(ir.TypeEdges(beside))) +} + +// TestTypeEdges_AnEmptyDecodeOnlyRouteIsNoEdge holds that a route naming no +// type yields none, as an empty mapping target does. +func TestTypeEdges_AnEmptyDecodeOnlyRouteIsNoEdge(t *testing.T) { + t.Parallel() + model := &ir.Model{Discriminator: &ir.Discriminator{DecodeOnlyRoutes: map[string]ir.TypeID{"x": ""}}} + assert.Empty(t, slices.Collect(ir.TypeEdges(model))) +} diff --git a/ir/decorator.go b/ir/decorator.go index c9488f8d8..17369ec56 100644 --- a/ir/decorator.go +++ b/ir/decorator.go @@ -3,26 +3,26 @@ package ir -// Decorated returns the reference td decorates, and false when td is no -// decorator (docs/ir/annotations.md#decorators): an anonymous Model or Scalar -// whose Base is set and which says nothing about a value that its Base does -// not. Beside its identity it may set only the annotations a use site can hold, -// Availability and Unmodeled, so any other field it sets, one the IR gains -// included, keeps it a type of its own. -func Decorated(td TypeDef) (TypeRef, bool) { +// Decorated returns the reference typeDef decorates, and false when typeDef is +// no decorator (docs/ir/annotations.md#decorators): an anonymous Model or +// Scalar whose Base is set and which says nothing about a value that its Base +// does not. Beside its identity it may set only the annotations a use site can +// hold, Availability and Unmodeled, so any other field it sets, one the IR +// gains included, keeps it a type of its own. +func Decorated(typeDef TypeDef) (TypeRef, bool) { var base *TypeRef var common *TypeCommon - switch n := td.(type) { + switch node := typeDef.(type) { case *Model: - if n == nil || !modelAddsNothing(n) { + if node == nil || !modelAddsNothing(node) { return TypeRef{}, false } - base, common = n.Base, &n.TypeCommon + base, common = node.Base, &node.TypeCommon case *Scalar: - if n == nil || n.Constraints != nil || n.Encoding != nil { + if node == nil || node.Constraints != nil || node.Encoding != nil { return TypeRef{}, false } - base, common = n.Base, &n.TypeCommon + base, common = node.Base, &node.TypeCommon default: return TypeRef{}, false } diff --git a/ir/decorator_test.go b/ir/decorator_test.go index 0033b30b5..4ad94397e 100644 --- a/ir/decorator_test.go +++ b/ir/decorator_test.go @@ -52,10 +52,10 @@ func decoratorScalar() *ir.Scalar { // kinds: each returns its Base, Nullable included, unchanged. func TestDecorated_ReturnsTheReferenceADecoratorDecorates(t *testing.T) { t.Parallel() - for name, td := range map[string]ir.TypeDef{"model": decoratorModel(), "scalar": decoratorScalar()} { + for name, typeDef := range map[string]ir.TypeDef{"model": decoratorModel(), "scalar": decoratorScalar()} { t.Run(name, func(t *testing.T) { t.Parallel() - got, ok := ir.Decorated(td) + got, ok := ir.Decorated(typeDef) require.True(t, ok) assert.Empty(t, cmp.Diff(decoratorBase, got)) }) @@ -76,7 +76,7 @@ func TestDecorated_RefusesWhatIsNoDecorator(t *testing.T) { namedScalar := decoratorScalar() namedScalar.Anonymous = false base := decoratorBase - for name, td := range map[string]ir.TypeDef{ + for name, typeDef := range map[string]ir.TypeDef{ "nil": nil, "typed nil model": (*ir.Model)(nil), "typed nil scalar": (*ir.Scalar)(nil), @@ -88,7 +88,7 @@ func TestDecorated_RefusesWhatIsNoDecorator(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - got, ok := ir.Decorated(td) + got, ok := ir.Decorated(typeDef) assert.False(t, ok) assert.Empty(t, cmp.Diff(ir.TypeRef{}, got)) }) @@ -112,17 +112,17 @@ func TestDecorated_EveryOtherFieldMakesATypeOfItsOwn(t *testing.T) { typ reflect.Type of func(ir.TypeDef) reflect.Value }{ - {reflect.TypeFor[ir.Model](), func(td ir.TypeDef) reflect.Value { return reflect.ValueOf(td).Elem() }}, - {reflect.TypeFor[ir.Scalar](), func(td ir.TypeDef) reflect.Value { return reflect.ValueOf(td).Elem() }}, - {reflect.TypeFor[ir.TypeCommon](), func(td ir.TypeDef) reflect.Value { - return reflect.ValueOf(td).Elem().FieldByName("TypeCommon") + {reflect.TypeFor[ir.Model](), func(typeDef ir.TypeDef) reflect.Value { return reflect.ValueOf(typeDef).Elem() }}, + {reflect.TypeFor[ir.Scalar](), func(typeDef ir.TypeDef) reflect.Value { return reflect.ValueOf(typeDef).Elem() }}, + {reflect.TypeFor[ir.TypeCommon](), func(typeDef ir.TypeDef) reflect.Value { + return reflect.ValueOf(typeDef).Elem().FieldByName("TypeCommon") }}, } { for field := range s.typ.Fields() { if allowed[field.Name] { continue } - for kind, td := range map[string]func() ir.TypeDef{ + for kind, typeDef := range map[string]func() ir.TypeDef{ "model": func() ir.TypeDef { return decoratorModel() }, "scalar": func() ir.TypeDef { return decoratorScalar() }, } { @@ -133,7 +133,7 @@ func TestDecorated_EveryOtherFieldMakesATypeOfItsOwn(t *testing.T) { name := kind + "/" + s.typ.Name() + "." + field.Name t.Run(name, func(t *testing.T) { t.Parallel() - node := td() + node := typeDef() setNonZero(t, s.of(node).FieldByName(field.Name)) _, ok := ir.Decorated(node) diff --git a/ir/descent.go b/ir/descent.go index 90b0352cb..de214a0e8 100644 --- a/ir/descent.go +++ b/ir/descent.go @@ -22,16 +22,17 @@ type descentRef struct { n int } -// enter records that the traversal is inside ptr, with the slice length n, and -// reports true. It reports false without recording when the traversal already -// is: the reference contains itself, and entering it again would never end. -func (d *descent) enter(ptr any, n int) bool { +// enter records that the traversal is inside ptr, whose slice length is length, +// and reports true. It reports false without recording when the traversal +// already is: the reference contains itself, and entering it again would never +// end. +func (d *descent) enter(ptr any, length int) bool { for _, descentRef := range d.inside { - if descentRef.ptr == ptr && descentRef.n == n { + if descentRef.ptr == ptr && descentRef.n == length { return false } } - d.inside = append(d.inside, descentRef{ptr: ptr, n: n}) + d.inside = append(d.inside, descentRef{ptr: ptr, n: length}) return true } diff --git a/ir/discriminator.go b/ir/discriminator.go new file mode 100644 index 000000000..4059f4c95 --- /dev/null +++ b/ir/discriminator.go @@ -0,0 +1,17 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +// VariantNameRoute returns the tag the discriminator of union routes a variant +// of type typeDef by where its Mapping is empty: the source name of the type +// (docs/ir/models.md#discriminator). It is false where union holds no +// discriminator, its Mapping holds an entry, or typeDef is nil or carries no +// name. Every reader of a variant's name route asks it. +func VariantNameRoute(union *Union, typeDef TypeDef) (string, bool) { + if union == nil || union.Discriminator == nil || len(union.Discriminator.Mapping) > 0 || IsNilTypeDef(typeDef) { + return "", false + } + name := typeDef.Common().Name.Source + return name, name != "" +} diff --git a/ir/discriminator_test.go b/ir/discriminator_test.go new file mode 100644 index 000000000..a5ff36778 --- /dev/null +++ b/ir/discriminator_test.go @@ -0,0 +1,49 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestVariantNameRoute_ReadsANameBesideAnEmptyMappingAlone holds the one rule +// validation and the verifier read a variant's name route by: a union whose +// discriminator's Mapping is empty, nil or not, routes a variant by its +// type's source name, and nothing routes by name beside a Mapping holding an +// entry, on a union with no discriminator, or to a type that is missing or +// carries no name. +func TestVariantNameRoute_ReadsANameBesideAnEmptyMappingAlone(t *testing.T) { + t.Parallel() + named := &ir.Model{ID: "type/cat", Name: ir.Naming{Source: "Cat", Canonical: "cat"}} + tagged := func(mapping map[string]ir.TypeID) *ir.Union { + return &ir.Union{ID: "type/u", Discriminator: &ir.Discriminator{PropertyName: "kind", Mapping: mapping}} + } + var missing *ir.Model + for _, c := range []struct { + name string + union *ir.Union + typeDef ir.TypeDef + want string + }{ + {"a named type beside a nil mapping", tagged(nil), named, "Cat"}, + {"a named type beside an empty mapping", tagged(map[string]ir.TypeID{}), named, "Cat"}, + {"a named type beside a mapping holding an entry", tagged(map[string]ir.TypeID{"c": "type/cat"}), named, ""}, + {"a type with no name", tagged(nil), &ir.Model{ID: "type/anonymous"}, ""}, + {"a type the registry does not hold", tagged(nil), nil, ""}, + {"a typed nil", tagged(nil), missing, ""}, + {"a union with no discriminator", &ir.Union{ID: "type/u"}, named, ""}, + {"no union", nil, named, ""}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + name, byName := ir.VariantNameRoute(c.union, c.typeDef) + assert.Equal(t, c.want, name) + assert.Equal(t, c.want != "", byName) + }) + } +} diff --git a/ir/doc.go b/ir/doc.go index 708d3f33c..355050978 100644 --- a/ir/doc.go +++ b/ir/doc.go @@ -2,19 +2,19 @@ // Licensed under the MIT License. See LICENSE in the repository root for details. // Package ir defines Morphic's spec-agnostic intermediate representation: the -// single contract between compilers and emitters. +// contract between compilers and emitters. // // docs/ir specifies the shapes: field names and struct layouts must match it. // Named entities live in flat registries on [Document], keyed and // cross-referenced by ID, and a Document round-trips through JSON -// deterministically. Passes edit documents with an [Editor]. +// deterministically. Passes edit through an [Editor]. // -// It also owns shared traversals and helpers: [WalkValues], the bounded, +// It owns shared traversals and helpers: [WalkValues], the bounded, // cycle-guarded, deterministic reflection walk; [IDReferences]; typed // [ForEachGroup], [ForEachOperation] and [TypeEdges]; [AliasBase], // [Supertypes], [IsSubtype], [ExposedProperties], [FlattenedProperties] and // [NarrowedShapes] over composition; [AsMap]. // -// It imports only the standard library and does no I/O; its plain-data types -// are safe for concurrent reads. +// It imports the standard library, stronglyconnected and rfc3339 alone, and +// does no I/O; its plain-data types are safe for concurrent reads. package ir diff --git a/ir/document.go b/ir/document.go index 301d2c7b7..0874434d7 100644 --- a/ir/document.go +++ b/ir/document.go @@ -12,7 +12,7 @@ package ir // docs/ir/ir-version.md holds that policy, docs/ir/version-history.md what each // bump changed, and TestIRVersion_PinsTheEncodedShape and // TestIRVersion_PinsTheNames hold it to the shape and the names. -const IRVersion = "0.73.0" +const IRVersion = "0.74.0" // CompatibleVersion reports whether a document stamped version can be read by // this build: exact equality with IRVersion, per docs/ir/ir-version.md. A @@ -34,6 +34,14 @@ func CompatibleVersion(version string) bool { // rest of the sum-type codec. type TypeRegistry map[TypeID]TypeDef +// Lookup returns the type r holds at id, and false where it holds none, in +// the form an index or a reader takes as its lookup. A typed nil r holds comes +// back held, as indexing r returns it. +func (r TypeRegistry) Lookup(id TypeID) (TypeDef, bool) { + typeDef, held := r[id] + return typeDef, held +} + // Document is the root of a Morphic IR document (docs/ir/document.md). It is // self-contained: no node references anything outside it. type Document struct { diff --git a/ir/document_test.go b/ir/document_test.go index 68afa9b60..e9f2cd762 100644 --- a/ir/document_test.go +++ b/ir/document_test.go @@ -79,10 +79,10 @@ func TestDocument_ConstructRepresentative(t *testing.T) { // literal left behind once asserted that a build rejects its own documents. func TestCompatibleVersion(t *testing.T) { t.Parallel() - semverValue, ok := parseVersion(ir.IRVersion) + version, ok := parseVersion(ir.IRVersion) require.True(t, ok, "IRVersion %q is not MAJOR.MINOR.PATCH", ir.IRVersion) - require.NotEqual(t, semver{}, semverValue, "IRVersion 0.0.0 has no earlier version to refuse") - earlier := semverValue + require.NotEqual(t, semver{}, version, "IRVersion 0.0.0 has no earlier version to refuse") + earlier := version for i := len(earlier) - 1; i >= 0; i-- { if earlier[i] > 0 { earlier[i]-- @@ -99,7 +99,7 @@ func TestCompatibleVersion(t *testing.T) { {"absent", "", false}, {"an earlier version", earlier.String(), false}, {"the next generation", nextGeneration(ir.IRVersion), false}, - {"a differing patch", semver{semverValue[0], semverValue[1], semverValue[2] + 1}.String(), false}, + {"a differing patch", semver{version[0], version[1], version[2] + 1}.String(), false}, {"a prerelease of this version", ir.IRVersion + "-rc.1", false}, {"padded with whitespace", " " + ir.IRVersion + " ", false}, {"not a version at all", "99.99.99-bogus", false}, diff --git a/ir/edges.go b/ir/edges.go index 8d6a27041..f79190347 100644 --- a/ir/edges.go +++ b/ir/edges.go @@ -9,27 +9,27 @@ import ( "slices" ) -// TypeEdges returns the type IDs td refers to, in the order [WalkValues] -// reaches them, apart from td's own ID. A self-reference counts and an empty -// target does not. It yields bare IDs, inventing no Nullable bit, and covers -// discriminator targets and a value's ref and constructor types, but no -// [DocRef] or [EntityRef]. A nil or typed-nil td yields nothing. +// TypeEdges returns the type IDs typeDef refers to, in the order [WalkValues] +// reaches them, apart from typeDef's own ID. A self-reference counts and an +// empty target does not. It yields bare IDs, inventing no Nullable bit, and +// covers discriminator targets and a value's ref and constructor types, but no +// [DocRef] or [EntityRef]. A nil or typed-nil typeDef yields nothing. // // A pointer two fields share is followed from each, as in WalkValues, and a // cycle is cut. It enters values no deeper than [MaxWalkDepth] and no more than // [MaxWalkSteps], so it is cut only where the reflection walk is. -func TypeEdges(td TypeDef) iter.Seq[TypeID] { - return typeEdges(MaxWalkSteps, td) +func TypeEdges(typeDef TypeDef) iter.Seq[TypeID] { + return typeEdges(MaxWalkSteps, typeDef) } // typeEdges is TypeEdges entering at most limit values. -func typeEdges(limit int, td TypeDef) iter.Seq[TypeID] { +func typeEdges(limit int, typeDef TypeDef) iter.Seq[TypeID] { return func(yield func(TypeID) bool) { - if IsNilTypeDef(td) { + if IsNilTypeDef(typeDef) { return } - edgeWalkValue := edgeWalk{yield: yield, steps: stepLimit{left: limit}} - edgeWalkValue.def(td) + edgeWalk := edgeWalk{yield: yield, steps: stepLimit{stepsLeft: limit}} + edgeWalk.def(typeDef) } } @@ -70,11 +70,11 @@ func (w *edgeWalk) refs(rs []TypeRef) { } } -// def yields td's edges: the part common to every kind, then the kind's own -// fields. -func (w *edgeWalk) def(td TypeDef) { - w.common(td.Common()) - switch t := td.(type) { +// def yields typeDef's edges: the part common to every kind, then the kind's +// own fields. +func (w *edgeWalk) def(typeDef TypeDef) { + w.common(typeDef.Common()) + switch t := typeDef.(type) { case *Scalar: w.ref(t.Base) w.encoding(t.Encoding) @@ -137,9 +137,9 @@ func (w *edgeWalk) value(value *Value, depth int) { if value.Ref != nil { w.id(value.Ref.Type) } - if constructorValue := value.Constructor; constructorValue != nil && w.path.enter(constructorValue, 0) { - w.id(constructorValue.Scalar) - w.values(constructorValue.Args, depth+1) + if constructor := value.Constructor; constructor != nil && w.path.enter(constructor, 0) { + w.id(constructor.Scalar) + w.values(constructor.Args, depth+1) w.path.leave() } } @@ -197,12 +197,12 @@ func (w *edgeWalk) input(in *ScenarioInput) { } // availability yields the prior types a versioning timeline records. -func (w *edgeWalk) availability(a *Availability) { - if a == nil { +func (w *edgeWalk) availability(availability *Availability) { + if availability == nil { return } - for i := range a.TypeChangedFrom { - w.ref(&a.TypeChangedFrom[i].Type) + for i := range availability.TypeChangedFrom { + w.ref(&availability.TypeChangedFrom[i].Type) } } @@ -269,19 +269,19 @@ func (w *edgeWalk) parameter(parameter *Parameter) { // additional yields the catch-all value and key types and each pattern's value // type. -func (w *edgeWalk) additional(a *AdditionalProperties) { - if a == nil { +func (w *edgeWalk) additional(additional *AdditionalProperties) { + if additional == nil { return } - w.ref(a.Value) - w.ref(a.Key) - for i := range a.Patterns { - w.ref(&a.Patterns[i].Value) + w.ref(additional.Value) + w.ref(additional.Key) + for i := range additional.Patterns { + w.ref(&additional.Patterns[i].Value) } } -// discriminator yields the mapping targets in sorted key order, then the -// default target. +// discriminator yields the mapping targets and then the decode-only routes' +// targets, each in sorted key order, then the default target. func (w *edgeWalk) discriminator(discriminator *Discriminator) { if discriminator == nil { return @@ -289,6 +289,9 @@ func (w *edgeWalk) discriminator(discriminator *Discriminator) { for _, k := range slices.Sorted(maps.Keys(discriminator.Mapping)) { w.id(discriminator.Mapping[k]) } + for _, k := range slices.Sorted(maps.Keys(discriminator.DecodeOnlyRoutes)) { + w.id(discriminator.DecodeOnlyRoutes[k]) + } w.id(discriminator.Default) } diff --git a/ir/edges_test.go b/ir/edges_test.go index 1853090a1..a45e435d4 100644 --- a/ir/edges_test.go +++ b/ir/edges_test.go @@ -27,23 +27,23 @@ var nameReflects = map[reflect.Type]bool{reflect.TypeFor[ir.DocRef](): true, ref // newFilled returns a TypeDef of kind with every field filled. func newFilled(t *testing.T, kind ir.TypeKind) ir.TypeDef { t.Helper() - td, ok := ir.NewTypeDef(kind) + typeDef, ok := ir.NewTypeDef(kind) require.True(t, ok, "no concrete type for kind %q", kind) - irtest.Fill(t, td) - return td + irtest.Fill(t, typeDef) + return typeDef } // reflectedEdges is the oracle: every non-empty TypeID the reflection walk // reaches from td except td's own ID and a DocRef's or an EntityRef's, in the // order it reaches them, with the path of each. -func reflectedEdges(td ir.TypeDef) (ids []ir.TypeID, paths []string) { - ir.WalkValues(td, "", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if nameReflects[v.Type()] { +func reflectedEdges(typeDef ir.TypeDef) (ids []ir.TypeID, paths []string) { + ir.WalkValues(typeDef, "", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if nameReflects[value.Type()] { return false } path := at.String() - if v.Kind() == reflect.String && v.Type() == typeIDReflect && v.String() != "" && path != ".ID" { - ids = append(ids, ir.TypeID(v.String())) + if value.Kind() == reflect.String && value.Type() == typeIDReflect && value.String() != "" && path != ".ID" { + ids = append(ids, ir.TypeID(value.String())) paths = append(paths, path) } return true @@ -54,9 +54,9 @@ func reflectedEdges(td ir.TypeDef) (ids []ir.TypeID, paths []string) { // edgeDiff compares the IDs TypeEdges yields for td with the oracle, ID for ID // and in order, and returns "" or a line naming the first disagreement and the // walk path it concerns. -func edgeDiff(td ir.TypeDef) string { - want, paths := reflectedEdges(td) - got := slices.Collect(ir.TypeEdges(td)) +func edgeDiff(typeDef ir.TypeDef) string { + want, paths := reflectedEdges(typeDef) + got := slices.Collect(ir.TypeEdges(typeDef)) if slices.Equal(want, got) { return "" } @@ -66,11 +66,11 @@ func edgeDiff(td ir.TypeDef) string { } switch { case i == len(got): - return fmt.Sprintf("%s: edge %d missing: the walk reaches %q at %s", td.Kind(), i, want[i], paths[i]) + return fmt.Sprintf("%s: edge %d missing: the walk reaches %q at %s", typeDef.Kind(), i, want[i], paths[i]) case i == len(want): - return fmt.Sprintf("%s: edge %d extra: TypeEdges yields %q, the walk reaches nothing more", td.Kind(), i, got[i]) + return fmt.Sprintf("%s: edge %d extra: TypeEdges yields %q, the walk reaches nothing more", typeDef.Kind(), i, got[i]) default: - return fmt.Sprintf("%s: edge %d is %q, but the walk reaches %q there, at %s", td.Kind(), i, got[i], want[i], paths[i]) + return fmt.Sprintf("%s: edge %d is %q, but the walk reaches %q there, at %s", typeDef.Kind(), i, got[i], want[i], paths[i]) } } @@ -79,9 +79,9 @@ func TestTypeEdges_EveryKindHasAnArm(t *testing.T) { for _, typeKind := range allKinds { t.Run(string(typeKind), func(t *testing.T) { t.Parallel() - td := newFilled(t, typeKind) - assert.Empty(t, edgeDiff(td)) - assert.NotEmpty(t, slices.Collect(ir.TypeEdges(td)), "a filled %s yields at least its common edges", typeKind) + typeDef := newFilled(t, typeKind) + assert.Empty(t, edgeDiff(typeDef)) + assert.NotEmpty(t, slices.Collect(ir.TypeEdges(typeDef)), "a filled %s yields at least its common edges", typeKind) }) } } @@ -101,11 +101,11 @@ func corpusTypeDefs(t *testing.T) []ir.TypeDef { files = append(files, matches...) } defs := make([]ir.TypeDef, 0, len(files)) - for _, f := range files { - doc, err := irtest.ReadGolden(f) + for _, file := range files { + doc, err := irtest.ReadGolden(file) require.NoError(t, err) - for _, td := range doc.Types { - defs = append(defs, td) + for _, typeDef := range doc.Types { + defs = append(defs, typeDef) } } return defs @@ -114,9 +114,9 @@ func corpusTypeDefs(t *testing.T) []ir.TypeDef { func TestTypeEdges_MatchesTheReflectionWalk(t *testing.T) { t.Parallel() total := 0 - for _, td := range corpusTypeDefs(t) { - assert.Empty(t, edgeDiff(td), "type %s", td.Common().ID) - total += len(slices.Collect(ir.TypeEdges(td))) + for _, typeDef := range corpusTypeDefs(t) { + assert.Empty(t, edgeDiff(typeDef), "type %s", typeDef.Common().ID) + total += len(slices.Collect(ir.TypeEdges(typeDef))) } require.Positive(t, total, "the corpus must exercise at least one edge") } @@ -156,12 +156,12 @@ func TestTypeEdges_StopsWhenTheConsumerBreaks(t *testing.T) { for _, typeKind := range allKinds { t.Run(string(typeKind), func(t *testing.T) { t.Parallel() - td := newFilled(t, typeKind) - full := slices.Collect(ir.TypeEdges(td)) + typeDef := newFilled(t, typeKind) + full := slices.Collect(ir.TypeEdges(typeDef)) for n := 1; n <= len(full); n++ { var got []ir.TypeID stopped := false - ir.TypeEdges(td)(func(id ir.TypeID) bool { + ir.TypeEdges(typeDef)(func(id ir.TypeID) bool { require.False(t, stopped, "yield called again after it returned false") got = append(got, id) stopped = len(got) == n diff --git a/ir/edit.go b/ir/edit.go index 119eb9017..614044571 100644 --- a/ir/edit.go +++ b/ir/edit.go @@ -56,7 +56,7 @@ type ownership struct { } // NewEditor starts an edit of doc. A nil doc is refused, and the edit then -// stands for an empty document, so Finish still returns one. +// holds an empty document, so Finish still returns one. func NewEditor(doc *Document) *Editor { if doc == nil { editor := &Editor{doc: &Document{}, out: &Document{}} @@ -131,9 +131,9 @@ func (e *Editor) apply(method string, change func()) { change() } -// open reports whether the edit takes a write verb names, at the node at names, +// acceptsWrite reports whether the edit takes a write verb names, at the node at names, // refusing one after Finish and one from inside a change. -func (e *Editor) open(verb string, at subject) bool { +func (e *Editor) acceptsWrite(verb string, at subject) bool { switch { case e.finished: e.refuse("%s rejected: the edit is finished (%s)", verb, at) diff --git a/ir/edit_document.go b/ir/edit_document.go index 6262fc6ce..6d73a2fa3 100644 --- a/ir/edit_document.go +++ b/ir/edit_document.go @@ -14,7 +14,7 @@ package ir // document as it was. func (e *Editor) UpdateDocument(change func(*Document)) { at := subject{document: true} - if !e.open("update", at) { + if !e.acceptsWrite("update", at) { return } own := *e.out diff --git a/ir/edit_ids.go b/ir/edit_ids.go index d4b5ddc6d..97793c865 100644 --- a/ir/edit_ids.go +++ b/ir/edit_ids.go @@ -60,39 +60,40 @@ func (c *idCounts) scan(list []declaredID, root any) []declaredID { } c.pending = append(c.pending[:0], reflect.ValueOf(root)) for len(c.pending) > 0 { - v := c.pending[len(c.pending)-1] + last := c.pending[len(c.pending)-1] c.pending = c.pending[:len(c.pending)-1] - list = c.enter(list, v) + list = c.enter(list, last) } return list } -// enter appends to list the ID v declares, if any, and queues what v holds that -// can declare one. No IR type holds an array, or an interface below a node an -// edit copies, which TestEditor_CopiesEveryIRTypeWhole holds the IR to. -func (c *idCounts) enter(list []declaredID, v reflect.Value) []declaredID { +// enter appends to list the ID value declares, if any, and queues what value +// holds that can declare one. No IR type holds an array, or an interface below +// a node an edit copies, which TestEditor_CopiesEveryIRTypeWhole holds the IR +// to. +func (c *idCounts) enter(list []declaredID, value reflect.Value) []declaredID { c.entered++ - switch v.Kind() { + switch value.Kind() { case reflect.Pointer: - if !v.IsNil() { - c.pending = append(c.pending, v.Elem()) + if !value.IsNil() { + c.pending = append(c.pending, value.Elem()) } case reflect.Struct: - if class, id, declares := c.ids.DeclaredIDOf(v); declares && id != "" { + if class, id, declares := c.ids.DeclaredIDOf(value); declares && id != "" { list = append(list, declaredID{class: class, id: id}) } - for _, i := range c.fieldsOf(v.Type()) { - c.pending = append(c.pending, v.Field(i)) + for _, i := range c.fieldsOf(value.Type()) { + c.pending = append(c.pending, value.Field(i)) } case reflect.Slice: - if c.canDeclare(v.Type().Elem()) { - for i := range v.Len() { - c.pending = append(c.pending, v.Index(i)) + if c.canDeclare(value.Type().Elem()) { + for i := range value.Len() { + c.pending = append(c.pending, value.Index(i)) } } case reflect.Map: - if c.canDeclare(v.Type().Elem()) { - for entry := v.MapRange(); entry.Next(); { + if c.canDeclare(value.Type().Elem()) { + for entry := value.MapRange(); entry.Next(); { c.pending = append(c.pending, entry.Value()) } } @@ -141,17 +142,17 @@ func (c *idCounts) excess() (declaredID, idCount, bool) { c.sorted += 2 i := 0 for j := 0; j < len(c.change); { - declaredID, idCountValue := c.change[j], idCount{} + declaredID, idCount := c.change[j], idCount{} for ; j < len(c.change) && c.change[j] == declaredID; j++ { - idCountValue.change++ + idCount.change++ } for ; i < len(c.node) && compareDeclared(c.node[i], declaredID) < 0; i++ { } for ; i < len(c.node) && c.node[i] == declaredID; i++ { - idCountValue.node++ + idCount.node++ } - if idCountValue.change > idCountValue.node { - return declaredID, idCountValue, true + if idCount.change > idCount.node { + return declaredID, idCount, true } } return declaredID{}, idCount{}, false @@ -165,13 +166,13 @@ func compareDeclared(a, b declaredID) int { return cmp.Compare(a.id, b.id) } -// clause says how often the node an update ends with declares declaredIDValue, +// clause says how often the node an update ends with declares declaredID, // against how often from, the node it is held to, does. -func (n idCount) clause(declaredIDValue declaredID, from string) string { +func (n idCount) clause(declaredID declaredID, from string) string { if n.node == 0 { - return fmt.Sprintf("the %s %q, which %s does not", declaredIDValue.class, declaredIDValue.id, from) + return fmt.Sprintf("the %s %q, which %s does not", declaredID.class, declaredID.id, from) } - return fmt.Sprintf("the %s %q %d times, where %s does %d times", declaredIDValue.class, declaredIDValue.id, n.change, from, n.node) + return fmt.Sprintf("the %s %q %d times, where %s does %d times", declaredID.class, declaredID.id, n.change, from, n.node) } // withOwnMembers appends to list, the IDs a node is held to, the ID of each of @@ -202,9 +203,9 @@ func (e *Editor) withOwnMembers(list []declaredID, node any) []declaredID { } occurrences[key]++ own, placed := EnumMemberIDFor(enum.ID, key, occurrences[key]) - declaredIDValue := declaredID{class: class, id: string(own)} - if placed && own == enumMember.ID && !held[declaredIDValue] { - list = append(list, declaredIDValue) + declaredID := declaredID{class: class, id: string(own)} + if placed && own == enumMember.ID && !held[declaredID] { + list = append(list, declaredID) } } return list diff --git a/ir/edit_ids_internal_test.go b/ir/edit_ids_internal_test.go index 51f28c544..24f6a1949 100644 --- a/ir/edit_ids_internal_test.go +++ b/ir/edit_ids_internal_test.go @@ -15,10 +15,10 @@ import ( // ID check costs an update its values alone. It is not run in parallel: // AllocsPerRun measures the process. func TestIDCounts_ScanReadsEachTypeOnce(t *testing.T) { - td := &Model{ID: "type/m", Properties: []Property{{ID: "property/a", Args: []Parameter{{ID: "q/a"}}}, {ID: "property/b"}}} - var idCountsValue idCounts - list := idCountsValue.scan(nil, td) + typeDef := &Model{ID: "type/m", Properties: []Property{{ID: "property/a", Args: []Parameter{{ID: "q/a"}}}, {ID: "property/b"}}} + var idCounts idCounts + list := idCounts.scan(nil, typeDef) require.Len(t, list, 4) - assert.Zero(t, testing.AllocsPerRun(10, func() { list = idCountsValue.scan(list[:0], td) })) + assert.Zero(t, testing.AllocsPerRun(10, func() { list = idCounts.scan(list[:0], typeDef) })) } diff --git a/ir/edit_ids_test.go b/ir/edit_ids_test.go index 19747eab9..d6e490b30 100644 --- a/ir/edit_ids_test.go +++ b/ir/edit_ids_test.go @@ -34,11 +34,11 @@ func idsDoc() *ir.Document { } // model returns the model td is, failing the test when it is none. -func model(t *testing.T, td ir.TypeDef) *ir.Model { +func model(t *testing.T, typeDef ir.TypeDef) *ir.Model { t.Helper() - modelValue, ok := td.(*ir.Model) - require.True(t, ok, "%T is no model", td) - return modelValue + model, ok := typeDef.(*ir.Model) + require.True(t, ok, "%T is no model", typeDef) + return model } // TestEditor_UpdateRefusesAChangeAddingAnID pins that a change may declare no @@ -54,34 +54,34 @@ func TestEditor_UpdateRefusesAChangeAddingAnID(t *testing.T) { want string }{ {"a property added", func(t *testing.T, editor *ir.Editor) { - editor.UpdateType("type/m", func(td ir.TypeDef) { - modelValue := model(t, td) - modelValue.Properties = append(modelValue.Properties, ir.Property{ID: "property/new"}) + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { + model := model(t, typeDef) + model.Properties = append(model.Properties, ir.Property{ID: "property/new"}) }) }, `the change of "type/m" declares the ir.PropertyID "property/new", which the node does not`}, {"a property's ID changed", func(t *testing.T, editor *ir.Editor) { - editor.UpdateType("type/m", func(td ir.TypeDef) { model(t, td).Properties[1].ID = "property/c" }) + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { model(t, typeDef).Properties[1].ID = "property/c" }) }, `the change of "type/m" declares the ir.PropertyID "property/c", which the node does not`}, {"a property repeated", func(t *testing.T, editor *ir.Editor) { - editor.UpdateType("type/m", func(td ir.TypeDef) { model(t, td).Properties[1].ID = "property/a" }) + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { model(t, typeDef).Properties[1].ID = "property/a" }) }, `the change of "type/m" declares the ir.PropertyID "property/a" 2 times, where the node does 1 times`}, {"an enum member added", func(t *testing.T, editor *ir.Editor) { - editor.UpdateType("type/e", func(td ir.TypeDef) { - enum, _ := td.(*ir.Enum) + editor.UpdateType("type/e", func(typeDef ir.TypeDef) { + enum, _ := typeDef.(*ir.Enum) enum.Members = append(enum.Members, ir.EnumMember{ID: "enum-member/b"}) }) }, `the change of "type/e" declares the ir.EnumMemberID "enum-member/b", which the node does not`}, {"the least of several added", func(t *testing.T, editor *ir.Editor) { - editor.UpdateType("type/m", func(td ir.TypeDef) { - modelValue := model(t, td) - modelValue.Properties = append(modelValue.Properties, ir.Property{ID: "property/z", Args: []ir.Parameter{{ID: "q/z"}}}, + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { + model := model(t, typeDef) + model.Properties = append(model.Properties, ir.Property{ID: "property/z", Args: []ir.Parameter{{ID: "q/z"}}}, ir.Property{ID: "property/y"}) }) }, `the change of "type/m" declares the ir.ParameterID "q/z", which the node does not`}, {"the least of several of one class added", func(t *testing.T, editor *ir.Editor) { - editor.UpdateType("type/m", func(td ir.TypeDef) { - modelValue := model(t, td) - modelValue.Properties = append(modelValue.Properties, ir.Property{ID: "property/z"}, ir.Property{ID: "property/y"}) + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { + model := model(t, typeDef) + model.Properties = append(model.Properties, ir.Property{ID: "property/z"}, ir.Property{ID: "property/y"}) }) }, `the change of "type/m" declares the ir.PropertyID "property/y", which the node does not`}, {"a parameter added", func(t *testing.T, editor *ir.Editor) { @@ -117,9 +117,9 @@ func TestEditor_UpdateRefusesAChangeAddingAnID(t *testing.T) { func TestEditor_UpdateTakesAChangeAddingNoID(t *testing.T) { t.Parallel() editor := ir.NewEditor(idsDoc()) - editor.UpdateType("type/m", func(td ir.TypeDef) { - modelValue := model(t, td) - modelValue.Properties = []ir.Property{modelValue.Properties[1], {}} + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { + model := model(t, typeDef) + model.Properties = []ir.Property{model.Properties[1], {}} }) editor.UpdateOperation("o/a", func(operation *ir.Operation) { operation.Params = nil }) out, diags := editor.Finish() @@ -192,8 +192,8 @@ func TestEditor_TakesAnEnumMembersOwnID(t *testing.T) { }} editor := ir.NewEditor(membersDoc()) editor.ReplaceType(enum) - editor.UpdateType("type/x/e", func(td ir.TypeDef) { - added, _ := td.(*ir.Enum) + editor.UpdateType("type/x/e", func(typeDef ir.TypeDef) { + added, _ := typeDef.(*ir.Enum) added.Members = append(added.Members, member("enum-member/x/e/string:c", "c")) }) out, diags := editor.Finish() @@ -240,8 +240,8 @@ func TestEditor_RefusesAMemberIDNotItsOwn(t *testing.T) { doc.Types["type/x/v"] = &ir.Enum{ID: "type/x/v"} editor := ir.NewEditor(doc) editor.ReplaceType(&ir.Enum{ID: "type/x/u", Members: tc.members}) - editor.UpdateType("type/x/v", func(td ir.TypeDef) { - enum, _ := td.(*ir.Enum) + editor.UpdateType("type/x/v", func(typeDef ir.TypeDef) { + enum, _ := typeDef.(*ir.Enum) enum.Members = slices.Clone(tc.members) for i := range enum.Members { enum.Members[i].ID = ir.EnumMemberID(strings.Replace(string(enum.Members[i].ID), "/u/", "/v/", 1)) @@ -268,8 +268,8 @@ func TestEditor_RefusesAMemberIDNotItsOwn(t *testing.T) { func TestEditor_RefusesAMemberIDItsNodeDeclaresAlready(t *testing.T) { t.Parallel() editor := ir.NewEditor(membersDoc()) - editor.UpdateType("type/x/e", func(td ir.TypeDef) { - enum, _ := td.(*ir.Enum) + editor.UpdateType("type/x/e", func(typeDef ir.TypeDef) { + enum, _ := typeDef.(*ir.Enum) enum.Members = append(enum.Members, member("enum-member/x/e/string:a", "a")) }) editor.ReplaceType(&ir.Enum{ID: "type/x/e", Members: []ir.EnumMember{member("enum-member/x/e/string:a", "a"), member("enum-member/x/e/string:a", "b")}}) @@ -336,7 +336,9 @@ func TestEditor_ChecksIDsWhereverTheyNestAndOnlyThere(t *testing.T) { part := irOperation.Request.Contents[0].Encoding["property/part"] irOperation.Request.Contents[0].Encoding["property/other"] = part }) - editor.UpdateType("type/m", func(td ir.TypeDef) { model(t, td).Properties = append(model(t, td).Properties[:0], deep...) }) + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { + model(t, typeDef).Properties = append(model(t, typeDef).Properties[:0], deep...) + }) editor.ReplaceType(&ir.Model{ID: "type/m", Properties: deep}) out, diags := editor.Finish() @@ -379,9 +381,9 @@ func TestEditor_IDCheckEntersOnlyWhatCanDeclare(t *testing.T) { func TestEditor_IDCheckSortsOnlyWhatChangedOrder(t *testing.T) { t.Parallel() editor := ir.NewEditor(idsDoc()) - editor.UpdateType("type/m", func(td ir.TypeDef) { td.Common().Docs.Summary = "kept in order" }) + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { typeDef.Common().Docs.Summary = "kept in order" }) untouched := ir.IDListsSorted(editor) - editor.UpdateType("type/m", func(td ir.TypeDef) { slices.Reverse(model(t, td).Properties) }) + editor.UpdateType("type/m", func(typeDef ir.TypeDef) { slices.Reverse(model(t, typeDef).Properties) }) _, diags := editor.Finish() require.Empty(t, diags) @@ -450,9 +452,9 @@ func TestEditor_IDCheckReadsABoundedPartOfANode(t *testing.T) { reflect.TypeFor[ir.OperationGroup](), reflect.TypeFor[ir.Operation](), reflect.TypeFor[ir.Server](), reflect.TypeFor[ir.Channel](), reflect.TypeFor[ir.Message](), reflect.TypeFor[ir.AuthScheme]()) for _, typeKind := range allKinds { - td, ok := ir.NewTypeDef(typeKind) + typeDef, ok := ir.NewTypeDef(typeKind) require.True(t, ok) - roots = append(roots, reflect.TypeOf(td)) + roots = append(roots, reflect.TypeOf(typeDef)) } for _, root := range roots { walk(root) diff --git a/ir/edit_registries.go b/ir/edit_registries.go index d392ba629..e9e95c091 100644 --- a/ir/edit_registries.go +++ b/ir/edit_registries.go @@ -56,7 +56,7 @@ func (e *Editor) authSchemes() registry[AuthID, AuthScheme] { // authSchemeKind is what an update knows of an auth scheme. func authSchemeKind() nodeKind[*AuthScheme] { - return nodeKind[*AuthScheme]{method: "UpdateAuthScheme", id: func(a *AuthScheme) string { return string(a.ID) }} + return nodeKind[*AuthScheme]{method: "UpdateAuthScheme", id: func(scheme *AuthScheme) string { return string(scheme.ID) }} } // Server returns the server the edit holds at id. It is shared, so it is read @@ -122,8 +122,8 @@ func (e *Editor) RemoveMessage(id MessageID) { // AuthScheme returns the auth scheme the edit holds at id. It is shared, so it // is read and never changed; UpdateAuthScheme changes a copy. func (e *Editor) AuthScheme(id AuthID) (AuthScheme, bool) { - a, held := e.out.Auth[id] - return a, held + scheme, held := e.out.Auth[id] + return scheme, held } // UpdateAuthScheme hands change a deep copy of the auth scheme at id, to alter @@ -140,10 +140,10 @@ func (e *Editor) RemoveAuthScheme(id AuthID) { } // updateEntry is UpdateServer, UpdateChannel, UpdateMessage and -// UpdateAuthScheme over registryValue, and refuses a node off its own ID's key +// UpdateAuthScheme over registry, and refuses a node off its own ID's key // besides what updated refuses. -func updateEntry[K ~string, V any](editor *Editor, registryValue registry[K, V], kind nodeKind[*V], id K, change func(*V)) { - current, ok := entryAt(editor, registryValue, "update", id) +func updateEntry[K ~string, V any](editor *Editor, registry registry[K, V], kind nodeKind[*V], id K, change func(*V)) { + current, ok := entryAt(editor, registry, "update", id) if !ok { return } @@ -152,35 +152,35 @@ func updateEntry[K ~string, V any](editor *Editor, registryValue registry[K, V], return } if next, taken := updated(editor, kind, string(id), subjectAt(id), ¤t, change); taken { - registryValue.write()[id] = *next + registry.write()[id] = *next } } -// removeEntry removes the node the edit holds at id in registryValue. -func removeEntry[K ~string, V any](editor *Editor, registryValue registry[K, V], id K) { - if _, ok := entryAt(editor, registryValue, "remove", id); !ok { +// removeEntry removes the node the edit holds at id in registry. +func removeEntry[K ~string, V any](editor *Editor, registry registry[K, V], id K) { + if _, ok := entryAt(editor, registry, "remove", id); !ok { return } - held := registryValue.write() + held := registry.write() delete(held, id) if len(held) == 0 { - *registryValue.held = nil + *registry.held = nil } } -// entryAt returns the node the edit holds at id in registryValue for a write -// verb names. It refuses one the edit does not take (open), and an id it holds -// no node at: an edit adds no ID. -func entryAt[K ~string, V any](editor *Editor, registryValue registry[K, V], verb string, id K) (V, bool) { - if !editor.open(verb, subjectAt(id)) { +// entryAt returns the node the edit holds at id in registry for a write +// verb names. It refuses one the edit does not take (acceptsWrite), and an id +// it holds no node at: an edit adds no ID. +func entryAt[K ~string, V any](editor *Editor, registry registry[K, V], verb string, id K) (V, bool) { + if !editor.acceptsWrite(verb, subjectAt(id)) { var none V return none, false } - v, held := (*registryValue.held)[id] + node, held := (*registry.held)[id] if !held { - editor.refuse("%s rejected: no %s %q to %s; an edit adds no %s", verb, registryValue.noun, id, verb, registryValue.noun) + editor.refuse("%s rejected: no %s %q to %s; an edit adds no %s", verb, registry.noun, id, verb, registry.noun) } - return v, held + return node, held } // write returns the map r views, copying it at the first write so the edited diff --git a/ir/edit_registries_test.go b/ir/edit_registries_test.go index 7a9c2b287..cf6cbd418 100644 --- a/ir/edit_registries_test.go +++ b/ir/edit_registries_test.go @@ -69,13 +69,13 @@ func TestEditor_ARegistryReadIsNotChangedByWhatFollows(t *testing.T) { doc := registriesDoc() doc.Types = ir.TypeRegistry{"type/a": &ir.Any{ID: "type/a", Docs: ir.Docs{Summary: "type/a"}}} editor := ir.NewEditor(doc) - td, _ := editor.Type("type/a") + typeDef, _ := editor.Type("type/a") server, _ := editor.Server("v/a") channel, _ := editor.Channel("c/a") message, _ := editor.Message("m/a") scheme, _ := editor.AuthScheme("a/a") - editor.UpdateType("type/a", func(td ir.TypeDef) { changed(&td.Common().Docs) }) + editor.UpdateType("type/a", func(typeDef ir.TypeDef) { changed(&typeDef.Common().Docs) }) editor.UpdateServer("v/a", func(server *ir.Server) { changed(&server.Description) server.Tags[0] = "changed" @@ -92,7 +92,7 @@ func TestEditor_ARegistryReadIsNotChangedByWhatFollows(t *testing.T) { _, diags := editor.Finish() require.Empty(t, diags) - assert.Equal(t, "type/a", td.Common().Docs.Summary) + assert.Equal(t, "type/a", typeDef.Common().Docs.Summary) assert.Equal(t, "v/a", server.Description.Summary) assert.Equal(t, []string{"kept"}, server.Tags) assert.Equal(t, "c/a", channel.Docs.Summary) @@ -217,24 +217,24 @@ func TestEditor_ReadsTheRegistriesAsTheEditHoldsThem(t *testing.T) { editor.RemoveMessage("m/a") editor.UpdateAuthScheme("a/b", func(a *ir.AuthScheme) { changed(&a.Docs) }) - serverValue, sHeld := editor.Server("v/a") + server, sHeld := editor.Server("v/a") _, gone := editor.Server("v/b") - channelValue, cHeld := editor.Channel("c/a") + channel, cHeld := editor.Channel("c/a") _, mHeld := editor.Message("m/a") message, otherHeld := editor.Message("m/b") - a, aHeld := editor.AuthScheme("a/b") + authScheme, aHeld := editor.AuthScheme("a/b") _, absent := editor.AuthScheme("a/x") assert.True(t, sHeld) - assert.Equal(t, "changed", serverValue.Description.Summary) + assert.Equal(t, "changed", server.Description.Summary) assert.False(t, gone) assert.True(t, cHeld) - assert.Equal(t, "changed", channelValue.Docs.Summary) + assert.Equal(t, "changed", channel.Docs.Summary) assert.False(t, mHeld) assert.True(t, otherHeld) assert.Equal(t, doc.Messages["m/b"].Docs, message.Docs) assert.True(t, aHeld) - assert.Equal(t, "changed", a.Docs.Summary) + assert.Equal(t, "changed", authScheme.Docs.Summary) assert.False(t, absent) } @@ -283,15 +283,15 @@ func TestEditor_RefusesRegistryWritesOnlyABugMakes(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() doc, control := registriesDoc(), registriesDoc() - editor, editorValue := ir.NewEditor(doc), ir.NewEditor(control) + editor, controlEditor := ir.NewEditor(doc), ir.NewEditor(control) if tt.before != nil { tt.before(editor) - tt.before(editorValue) + tt.before(controlEditor) } tt.refused(editor) out, diags := editor.Finish() - want, ctrl := editorValue.Finish() + want, ctrl := controlEditor.Finish() require.Empty(t, ctrl, "a write before the refused one was refused as well, so the case tests the wrong write") got := refusals(t, diags) diff --git a/ir/edit_test.go b/ir/edit_test.go index f9e48c1a2..400c92c24 100644 --- a/ir/edit_test.go +++ b/ir/edit_test.go @@ -79,8 +79,8 @@ func TestEditor_WritesTheEditedRegistryAndNotTheDocument(t *testing.T) { assert.Equal(t, ir.KindPrimitive, types["type/scalar"].Kind()) }}, {"update", func(editor *ir.Editor) { - editor.UpdateType("type/model", func(td ir.TypeDef) { - model, _ := td.(*ir.Model) + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { + model, _ := typeDef.(*ir.Model) model.Docs.Summary = strings.TrimSpace(model.Docs.Summary) model.Properties[0].Type.Target = "type/scalar" }) @@ -93,7 +93,7 @@ func TestEditor_WritesTheEditedRegistryAndNotTheDocument(t *testing.T) { }}, {"update twice", func(editor *ir.Editor) { for _, tag := range []string{"first", "second"} { - editor.UpdateType("type/list", func(td ir.TypeDef) { td.Common().Tags = append(td.Common().Tags, tag) }) + editor.UpdateType("type/list", func(typeDef ir.TypeDef) { typeDef.Common().Tags = append(typeDef.Common().Tags, tag) }) } }, func(t *testing.T, types ir.TypeRegistry) { t.Helper() @@ -101,9 +101,9 @@ func TestEditor_WritesTheEditedRegistryAndNotTheDocument(t *testing.T) { }}, {"update reading the edit", func(editor *ir.Editor) { editor.RemoveType("type/scalar") - editor.UpdateType("type/model", func(td ir.TypeDef) { + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { _, held := editor.Type("type/scalar") - td.Common().Docs.Summary = fmt.Sprint("scalar held: ", held) + typeDef.Common().Docs.Summary = fmt.Sprint("scalar held: ", held) }) }, func(t *testing.T, types ir.TypeRegistry) { t.Helper() @@ -111,7 +111,7 @@ func TestEditor_WritesTheEditedRegistryAndNotTheDocument(t *testing.T) { }}, {"update a replaced node", func(editor *ir.Editor) { editor.ReplaceType(&ir.List{ID: "type/list", ElementType: ir.TypeRef{Target: "type/model"}}) - editor.UpdateType("type/list", func(td ir.TypeDef) { td.Common().Access = "internal" }) + editor.UpdateType("type/list", func(typeDef ir.TypeDef) { typeDef.Common().Access = "internal" }) }, func(t *testing.T, types ir.TypeRegistry) { t.Helper() list, ok := types["type/list"].(*ir.List) @@ -134,11 +134,11 @@ func TestEditor_WritesTheEditedRegistryAndNotTheDocument(t *testing.T) { tt.want(t, out.Types) assert.Equal(t, before, irtest.Encoded(t, doc), "the edited document changed") require.Len(t, doc.Types, len(nodes), "the edited document holds other types") - for id, td := range nodes { - assert.Same(t, td, doc.Types[id], "the edited document holds another node at %s", id) + for id, typeDef := range nodes { + assert.Same(t, typeDef, doc.Types[id], "the edited document holds another node at %s", id) } - for id, td := range out.Types { - assert.Equal(t, id, td.Common().ID, "a node sits at a key its ID does not name") + for id, typeDef := range out.Types { + assert.Equal(t, id, typeDef.Common().ID, "a node sits at a key its ID does not name") } }) } @@ -246,7 +246,7 @@ func TestEditor_RefusesWritesOnlyABugMakes(t *testing.T) { editor.ReplaceType(doc.Types["type/scalar"]) }, `replace rejected: "type/scalar" is the edited document's own node, which an edit never changes`}, {"replace with the document's own node after an update", func(editor *ir.Editor, _ *ir.Document) { - editor.UpdateType("type/scalar", func(td ir.TypeDef) { td.Common().Access = "internal" }) + editor.UpdateType("type/scalar", func(typeDef ir.TypeDef) { typeDef.Common().Access = "internal" }) }, func(editor *ir.Editor, doc *ir.Document) { editor.ReplaceType(doc.Types["type/scalar"]) }, `replace rejected: "type/scalar" is the edited document's own node`}, @@ -263,28 +263,28 @@ func TestEditor_RefusesWritesOnlyABugMakes(t *testing.T) { {"update with no change", nil, func(editor *ir.Editor, _ *ir.Document) { editor.UpdateType("type/model", nil) }, `update rejected: no change for "type/model"`}, {"update moving the type", nil, func(editor *ir.Editor, _ *ir.Document) { - editor.UpdateType("type/model", func(td ir.TypeDef) { - td.Common().ID = "type/moved" - td.Common().Docs.Summary = "moved" + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { + typeDef.Common().ID = "type/moved" + typeDef.Common().Docs.Summary = "moved" }) }, `update rejected: the change moved "type/model" to "type/moved"; a node keeps its ID`}, {"update emptying the ID", nil, func(editor *ir.Editor, _ *ir.Document) { - editor.UpdateType("type/model", func(td ir.TypeDef) { *td.Common() = ir.TypeCommon{} }) + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { *typeDef.Common() = ir.TypeCommon{} }) }, `update rejected: the change moved "type/model" to ""`}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() doc, control := editedDoc(), editedDoc() - editor, editorValue := ir.NewEditor(doc), ir.NewEditor(control) + editor, controlEditor := ir.NewEditor(doc), ir.NewEditor(control) if tt.before != nil { tt.before(editor, doc) - tt.before(editorValue, control) + tt.before(controlEditor, control) } tt.refused(editor, doc) out, diags := editor.Finish() - want, ctrl := editorValue.Finish() + want, ctrl := controlEditor.Finish() require.Empty(t, ctrl, "a write before the refused one was refused as well, so the case tests the wrong write") got := refusals(t, diags) @@ -315,7 +315,7 @@ func TestEditor_UpdateRefusesAChangeWritingOrEndingTheEdit(t *testing.T) { {"a replace refused for itself", func(editor *ir.Editor) { editor.ReplaceType(nil) }, `replace rejected: nil type definition`}, {"an update", func(editor *ir.Editor) { - editor.UpdateType("type/list", func(td ir.TypeDef) { td.Common().Access = "internal" }) + editor.UpdateType("type/list", func(typeDef ir.TypeDef) { typeDef.Common().Access = "internal" }) }, `update rejected: ` + inside + ` ("type/list")`}, {"finish", func(editor *ir.Editor) { editor.Finish() }, `finish rejected: ` + inside + `; a change alters its node alone`}, @@ -324,19 +324,19 @@ func TestEditor_UpdateRefusesAChangeWritingOrEndingTheEdit(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() doc := editedDoc() - editor, editorValue := ir.NewEditor(doc), ir.NewEditor(editedDoc()) + editor, controlEditor := ir.NewEditor(doc), ir.NewEditor(editedDoc()) editor.RemoveType("type/absent") - editor.UpdateType("type/model", func(td ir.TypeDef) { - td.Common().Docs.Summary = "changed" + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { + typeDef.Common().Docs.Summary = "changed" tt.call(editor) }) - for _, ed := range []*ir.Editor{editor, editorValue} { + for _, ed := range []*ir.Editor{editor, controlEditor} { ed.RemoveType("type/scalar") - ed.UpdateType("type/list", func(td ir.TypeDef) { td.Common().Tags = append(td.Common().Tags, "after") }) + ed.UpdateType("type/list", func(typeDef ir.TypeDef) { typeDef.Common().Tags = append(typeDef.Common().Tags, "after") }) } out, diags := editor.Finish() - want, ctrl := editorValue.Finish() + want, ctrl := controlEditor.Finish() require.Empty(t, ctrl) got := refusals(t, diags) @@ -494,8 +494,8 @@ func TestEditor_UpdateLeavesTheEditUsableAfterAPanickingChange(t *testing.T) { doc := editedDoc() editor := ir.NewEditor(doc) assert.PanicsWithValue(t, "change failed", func() { - editor.UpdateType("type/model", func(td ir.TypeDef) { - td.Common().Docs.Summary = "changed" + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { + typeDef.Common().Docs.Summary = "changed" panic("change failed") }) }) @@ -562,15 +562,15 @@ func TestEditor_FinishRefusesANodeMovedAfterTheEditTookIt(t *testing.T) { want string }{ {"one value replaced at two IDs", func(editor *ir.Editor) { - anyValue := &ir.Any{ID: "type/list"} - editor.ReplaceType(anyValue) - anyValue.ID = "type/scalar" - editor.ReplaceType(anyValue) + anyType := &ir.Any{ID: "type/list"} + editor.ReplaceType(anyType) + anyType.ID = "type/scalar" + editor.ReplaceType(anyType) }, "type/list", `finish: "type/list" holds a node moved to "type/scalar" after the edit took it, ` + `so the edited document's node stays; a type keeps its ID`}, {"an updated node kept", func(editor *ir.Editor) { var kept ir.TypeDef - editor.UpdateType("type/model", func(td ir.TypeDef) { kept = td }) + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { kept = typeDef }) kept.Common().ID = "type/moved" }, "type/model", `finish: "type/model" holds a node moved to "type/moved" after the edit took it, ` + `so the edited document's node stays`}, @@ -590,8 +590,8 @@ func TestEditor_FinishRefusesANodeMovedAfterTheEditTookIt(t *testing.T) { assert.Contains(t, got[0], "internal: edit: "+tt.want) assert.Empty(t, again, "a moved node is reported once") assert.Same(t, doc.Types[tt.moved], out.Types[tt.moved], "the moved node stayed in the edit's document") - for id, td := range out.Types { - assert.Equal(t, id, td.Common().ID, "a node sits at a key its ID does not name") + for id, typeDef := range out.Types { + assert.Equal(t, id, typeDef.Common().ID, "a node sits at a key its ID does not name") } assert.Equal(t, irtest.Encoded(t, editedDoc()), irtest.Encoded(t, doc), "the edited document changed") }) @@ -634,7 +634,7 @@ func TestEditor_FinishReportsEachRefusalOnce(t *testing.T) { editor.RemoveType("type/scalar") editor.ReplaceType(&ir.Any{ID: "type/list"}) - editor.UpdateType("type/model", func(td ir.TypeDef) { td.Common().Access = "internal" }) + editor.UpdateType("type/model", func(typeDef ir.TypeDef) { typeDef.Common().Access = "internal" }) second, secondDiags := editor.Finish() third, thirdDiags := editor.Finish() @@ -706,10 +706,10 @@ func references(v any) map[uintptr]string { // updatedCopy returns the node an edit holds at td's own ID after an update // that changes nothing, which is the copy UpdateType made of td. -func updatedCopy(t *testing.T, td ir.TypeDef) ir.TypeDef { +func updatedCopy(t *testing.T, typeDef ir.TypeDef) ir.TypeDef { t.Helper() - id := td.Common().ID - editor := ir.NewEditor(&ir.Document{Types: ir.TypeRegistry{id: td}}) + id := typeDef.Common().ID + editor := ir.NewEditor(&ir.Document{Types: ir.TypeRegistry{id: typeDef}}) editor.UpdateType(id, func(ir.TypeDef) {}) out, diags := editor.Finish() require.Empty(t, diags) @@ -724,15 +724,15 @@ func TestEditor_UpdateCopiesEveryKindWhole(t *testing.T) { for _, typeKind := range allKinds { t.Run(string(typeKind), func(t *testing.T) { t.Parallel() - td := newFilled(t, typeKind) - typeCommon := td.Common() + typeDef := newFilled(t, typeKind) + typeCommon := typeDef.Common() typeCommon.Examples = append(typeCommon.Examples, ir.Example{Value: &ir.Value{Kind: ir.ValueBytes, Bytes: []byte("raw")}}) typeCommon.Unmodeled = ir.Unmodeled{"x-raw": {Reason: ir.ReasonVendorExtension, Value: ir.RawValue(`{"a":1}`)}} - cp := updatedCopy(t, td) + cp := updatedCopy(t, typeDef) - assert.Empty(t, cmp.Diff(td, cp), "the copy differs from the node") - original := references(td) + assert.Empty(t, cmp.Diff(typeDef, cp), "the copy differs from the node") + original := references(typeDef) require.NotEmpty(t, original) for addr, path := range references(cp) { if at, shared := original[addr]; shared { @@ -753,9 +753,9 @@ func TestEditor_CopiesEveryIRTypeWhole(t *testing.T) { t.Parallel() queue := make([]reflect.Type, 0, len(allKinds)+1) for _, typeKind := range allKinds { - td, ok := ir.NewTypeDef(typeKind) + typeDef, ok := ir.NewTypeDef(typeKind) require.True(t, ok) - queue = append(queue, reflect.TypeOf(td)) + queue = append(queue, reflect.TypeOf(typeDef)) } queue = append(queue, reflect.TypeFor[ir.Document]()) seen := map[reflect.Type]bool{} @@ -975,7 +975,7 @@ func TestEditor_UpdateRefusesANodeTooDeepToCopy(t *testing.T) { doc := &ir.Document{Types: ir.TypeRegistry{"type/deep": node}} editor := ir.NewEditor(doc) - editor.UpdateType("type/deep", func(td ir.TypeDef) { td.Common().Access = "internal" }) + editor.UpdateType("type/deep", func(typeDef ir.TypeDef) { typeDef.Common().Access = "internal" }) out, diags := editor.Finish() walkCut := ir.WalkValues(node, "node", ir.VisitFunc(func(reflect.Value, ir.WalkPath) bool { return true })) @@ -1002,8 +1002,8 @@ func ExampleNewEditor() { "type/lost": &ir.Any{ID: "type/lost"}, }} referenced := map[ir.TypeID]bool{"type/kept": true} // say an operation names it - for _, td := range doc.Types { - for id := range ir.TypeEdges(td) { + for _, typeDef := range doc.Types { + for id := range ir.TypeEdges(typeDef) { referenced[id] = true } } @@ -1025,9 +1025,9 @@ func ExampleNewEditor() { // wireNames returns n wire-name overrides, a map whose entries the copy keeps // nothing of its own for. -func wireNames(n int) map[string]string { +func wireNames(count int) map[string]string { names := map[string]string{} - for i := range n { + for i := range count { names["format"+strconv.Itoa(i)] = "name" } return names diff --git a/ir/edit_tree.go b/ir/edit_tree.go index 88a9509b7..fe174a332 100644 --- a/ir/edit_tree.go +++ b/ir/edit_tree.go @@ -162,19 +162,19 @@ func (e *Editor) RemoveOperation(id OperationID) { } // nodeAt returns the node of class the edit holds at id for a write verb -// names. It refuses one the edit does not take (open), an id the edit holds no -// such node at, as an edit adds none, and one it holds several at, as which to -// write is unknown. +// names. It refuses one the edit does not take (acceptsWrite), an id the edit +// holds no such node at, as an edit adds none, and one it holds several at, as +// which to write is unknown. func (e *Editor) nodeAt(verb string, class treeClass, id string) (*treeNode, bool) { at := subjectAt(id) - if !e.open(verb, at) { + if !e.acceptsWrite(verb, at) { return nil, false } - treeNodeValue, held := e.indexed().find(class, id) + treeNode, held := e.indexed().find(class, id) noun := string(class) switch { case held == 1: - return treeNodeValue, true + return treeNode, true case held > 1: e.refuse("%s rejected: %d %ss have the ID %s, so the edit cannot tell which to %s", verb, held, noun, at, verb) case e.tree.cut: diff --git a/ir/edit_tree_nodes.go b/ir/edit_tree_nodes.go index 389d459e2..7722f3a5a 100644 --- a/ir/edit_tree_nodes.go +++ b/ir/edit_tree_nodes.go @@ -73,13 +73,13 @@ type treeList struct { // index reads the tree out of services, taking at most limit steps. func (t *serviceTree) index(services []Service, limit int) { t.read, t.byID = true, map[treeKey][]*treeNode{} - treeReadValue := treeRead{steps: stepLimit{left: limit}} + treeRead := treeRead{steps: stepLimit{stepsLeft: limit}} for i := range services { treeNode := t.add(nil, &t.services, serviceNode, string(services[i].ID)) treeNode.service = &services[i] - t.indexGroups(treeNode, services[i].Groups, 0, &treeReadValue) + t.indexGroups(treeNode, services[i].Groups, 0, &treeRead) } - t.cut = treeReadValue.steps.cut + t.cut = treeRead.steps.cut } // treeRead is one read of the tree: the group slices it is inside, and the @@ -92,46 +92,46 @@ type treeRead struct { // indexGroups reads groups, held by parent at depth levels below a service, // with what they hold, as ForEachOperation walks them: a step per group and // per operation, in its order. -func (t *serviceTree) indexGroups(parent *treeNode, groups []OperationGroup, depth int, treeReadValue *treeRead) { +func (t *serviceTree) indexGroups(parent *treeNode, groups []OperationGroup, depth int, treeRead *treeRead) { if len(groups) == 0 { return } if depth > MaxGroupDepth { - treeReadValue.steps.cut = true + treeRead.steps.cut = true return } - if !treeReadValue.path.enter(&groups[0], len(groups)) { + if !treeRead.path.enter(&groups[0], len(groups)) { return } for i := range groups { - if !treeReadValue.steps.take() { + if !treeRead.steps.take() { break } treeNode := t.add(parent, &parent.groups, groupNode, string(groups[i].ID)) treeNode.group = &groups[i] - t.indexOperations(treeNode, groups[i].Operations, treeReadValue) - t.indexGroups(treeNode, groups[i].Groups, depth+1, treeReadValue) + t.indexOperations(treeNode, groups[i].Operations, treeRead) + t.indexGroups(treeNode, groups[i].Groups, depth+1, treeRead) } - treeReadValue.path.leave() + treeRead.path.leave() } -// indexOperations reads the operations of the group treeNodeValue, a step each. -func (t *serviceTree) indexOperations(treeNodeValue *treeNode, operations []Operation, treeReadValue *treeRead) { +// indexOperations reads the operations of the group treeNode, a step each. +func (t *serviceTree) indexOperations(treeNode *treeNode, operations []Operation, treeRead *treeRead) { for j := range operations { - if !treeReadValue.steps.take() { + if !treeRead.steps.take() { return } - t.add(treeNodeValue, &treeNodeValue.operations, operationNode, string(operations[j].ID)).operation = &operations[j] + t.add(treeNode, &treeNode.operations, operationNode, string(operations[j].ID)).operation = &operations[j] } } // add records a node of class with id, held by parent in the list in. func (t *serviceTree) add(parent *treeNode, in *treeList, class treeClass, id string) *treeNode { - treeNodeValue := &treeNode{parent: parent, in: in} - in.nodes = append(in.nodes, treeNodeValue) + treeNode := &treeNode{parent: parent, in: in} + in.nodes = append(in.nodes, treeNode) key := treeKey{class: class, id: id} - t.byID[key] = append(t.byID[key], treeNodeValue) - return treeNodeValue + t.byID[key] = append(t.byID[key], treeNode) + return treeNode } // find returns the node of class the edit holds at id, when it holds one, and @@ -161,20 +161,20 @@ func (n *treeNode) held() bool { return true } -// touch records that the edit wrote treeNodeValue: the list holding it, and +// touch records that the edit wrote treeNode: the list holding it, and // each list on the path to it, no longer shows what the edit holds. -func (t *serviceTree) touch(treeNodeValue *treeNode) { - for treeNode := treeNodeValue; treeNode != nil; treeNode = treeNode.parent { // no deeper than index reads, which MaxGroupDepth bounds +func (t *serviceTree) touch(treeNode *treeNode) { + for treeNode := treeNode; treeNode != nil; treeNode = treeNode.parent { // no deeper than index reads, which MaxGroupDepth bounds treeNode.in.stale = true t.work++ } } -// remove records that the edit removed treeNodeValue, which the next build of +// remove records that the edit removed treeNode, which the next build of // the list holding it drops. -func (t *serviceTree) remove(treeNodeValue *treeNode) { - treeNodeValue.removed = true - t.touch(treeNodeValue) +func (t *serviceTree) remove(treeNode *treeNode) { + treeNode.removed = true + t.touch(treeNode) } // settle brings out's services up to what the edit holds. @@ -184,42 +184,42 @@ func (t *serviceTree) settle(out *Document) { } } -// serviceOf returns treeNodeValue's service as the edit holds it, building what +// serviceOf returns treeNode's service as the edit holds it, building what // is stale in it first. -func (t *serviceTree) serviceOf(treeNodeValue *treeNode) Service { - if treeNodeValue.groups.stale { - service := *treeNodeValue.service - service.Groups = built(t, &treeNodeValue.groups, t.groupOf) - treeNodeValue.service = &service +func (t *serviceTree) serviceOf(treeNode *treeNode) Service { + if treeNode.groups.stale { + service := *treeNode.service + service.Groups = built(t, &treeNode.groups, t.groupOf) + treeNode.service = &service } - return *treeNodeValue.service + return *treeNode.service } -// groupOf returns treeNodeValue's group as the edit holds it, building what is +// groupOf returns node's group as the edit holds it, building what is // stale in it first. It recurses no deeper than index read, which MaxGroupDepth // bounds. -func (t *serviceTree) groupOf(treeNodeValue *treeNode) OperationGroup { - if !treeNodeValue.groups.stale && !treeNodeValue.operations.stale { - return *treeNodeValue.group +func (t *serviceTree) groupOf(node *treeNode) OperationGroup { + if !node.groups.stale && !node.operations.stale { + return *node.group } - operationGroup := *treeNodeValue.group - if treeNodeValue.groups.stale { - operationGroup.Groups = built(t, &treeNodeValue.groups, t.groupOf) + operationGroup := *node.group + if node.groups.stale { + operationGroup.Groups = built(t, &node.groups, t.groupOf) } - if treeNodeValue.operations.stale { - operationGroup.Operations = built(t, &treeNodeValue.operations, func(otherTreeNode *treeNode) Operation { return *otherTreeNode.operation }) + if node.operations.stale { + operationGroup.Operations = built(t, &node.operations, func(otherTreeNode *treeNode) Operation { return *otherTreeNode.operation }) } - treeNodeValue.group = &operationGroup + node.group = &operationGroup return operationGroup } // built drops from list the nodes the edit removed and returns a new slice of // what element reads off each one left, or nil for none, as the document // decodes a slice that was empty. -func built[T any](serviceTreeValue *serviceTree, list *treeList, element func(*treeNode) T) []T { - serviceTreeValue.work += len(list.nodes) +func built[T any](serviceTree *serviceTree, list *treeList, element func(*treeNode) T) []T { + serviceTree.work += len(list.nodes) list.stale = false - list.nodes = slices.DeleteFunc(list.nodes, func(treeNodeValue *treeNode) bool { return treeNodeValue.removed }) + list.nodes = slices.DeleteFunc(list.nodes, func(treeNode *treeNode) bool { return treeNode.removed }) if len(list.nodes) == 0 { return nil } diff --git a/ir/edit_tree_test.go b/ir/edit_tree_test.go index 08888f182..f6eb2dc0a 100644 --- a/ir/edit_tree_test.go +++ b/ir/edit_tree_test.go @@ -540,15 +540,15 @@ func TestEditor_RefusesTreeWritesOnlyABugMakes(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() doc, control := treeDoc(), treeDoc() - editor, editorValue := ir.NewEditor(doc), ir.NewEditor(control) + editor, controlEditor := ir.NewEditor(doc), ir.NewEditor(control) if tt.before != nil { tt.before(editor) - tt.before(editorValue) + tt.before(controlEditor) } tt.refused(editor) out, diags := editor.Finish() - want, ctrl := editorValue.Finish() + want, ctrl := controlEditor.Finish() got := refusals(t, diags) require.Len(t, got, len(refusals(t, ctrl))+1, "one refused write, one refusal: %v", got) @@ -729,17 +729,17 @@ func TestEditor_ReadsAGroupSliceTwoGroupsShareFromEach(t *testing.T) { // groupOf returns a document of one service holding groups groups of n // operations each, and the operations' IDs in order. -func groupOf(groups, n int) (*ir.Document, []ir.OperationID) { +func groupOf(groups, count int) (*ir.Document, []ir.OperationID) { svc := treeService("service/a") - ids := make([]ir.OperationID, 0, groups*n) - for g := range groups { - operations := make([]ir.Operation, 0, n) - for i := range n { - id := ir.OperationID(fmt.Sprint("o/", g, "/", i)) + ids := make([]ir.OperationID, 0, groups*count) + for group := range groups { + operations := make([]ir.Operation, 0, count) + for i := range count { + id := ir.OperationID(fmt.Sprint("o/", group, "/", i)) operations = append(operations, treeOperation(id)) ids = append(ids, id) } - svc.Groups = append(svc.Groups, treeGroup(ir.GroupID(fmt.Sprint("operation-group/", g)), operations)) + svc.Groups = append(svc.Groups, treeGroup(ir.GroupID(fmt.Sprint("operation-group/", group)), operations)) } return &ir.Document{Services: []ir.Service{svc}}, ids } @@ -764,44 +764,44 @@ func TestEditor_TreeWorkIsLinear(t *testing.T) { edit func(editor *ir.Editor, ids []ir.OperationID) floor func(n int) int }{ - {"empty one group", func(n int) (int, int) { return 1, n }, removeEach, func(n int) int { return n }}, - {"empty one group from its end", func(n int) (int, int) { return 1, n }, func(editor *ir.Editor, ids []ir.OperationID) { + {"empty one group", func(count int) (int, int) { return 1, count }, removeEach, func(n int) int { return n }}, + {"empty one group from its end", func(count int) (int, int) { return 1, count }, func(editor *ir.Editor, ids []ir.OperationID) { for _, id := range slices.Backward(ids) { editor.RemoveOperation(id) } - }, func(n int) int { return n }}, - {"remove every other operation", func(n int) (int, int) { return 1, n }, func(editor *ir.Editor, ids []ir.OperationID) { + }, func(count int) int { return count }}, + {"remove every other operation", func(count int) (int, int) { return 1, count }, func(editor *ir.Editor, ids []ir.OperationID) { for i, id := range ids { if i%2 == 0 { editor.RemoveOperation(id) } } - }, func(n int) int { return n + n/2 }}, - {"update every operation", func(n int) (int, int) { return 1, n }, func(editor *ir.Editor, ids []ir.OperationID) { + }, func(count int) int { return count + count/2 }}, + {"update every operation", func(count int) (int, int) { return 1, count }, func(editor *ir.Editor, ids []ir.OperationID) { for _, id := range ids { editor.UpdateOperation(id, func(operation *ir.Operation) { changed(&operation.Docs) }) } - }, func(n int) int { return n }}, - {"empty many groups", func(n int) (int, int) { return n, 2 }, removeEach, func(n int) int { return 2 * n }}, - {"empty many groups, reading each after each removal", func(n int) (int, int) { return n, 2 }, + }, func(count int) int { return count }}, + {"empty many groups", func(count int) (int, int) { return count, 2 }, removeEach, func(n int) int { return 2 * n }}, + {"empty many groups, reading each after each removal", func(count int) (int, int) { return count, 2 }, func(editor *ir.Editor, ids []ir.OperationID) { for i, id := range ids { editor.RemoveOperation(id) _, _ = editor.Group(ir.GroupID(fmt.Sprint("operation-group/", i/2))) } - }, func(n int) int { return 2 * n }}, + }, func(count int) int { return 2 * count }}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - work := func(n int) int { - doc, ids := groupOf(tt.groups(n)) + work := func(count int) int { + doc, ids := groupOf(tt.groups(count)) editor := ir.NewEditor(doc) tt.edit(editor, ids) _, diags := editor.Finish() require.Empty(t, diags) w := ir.TreeWork(editor) - require.GreaterOrEqual(t, w, tt.floor(n), "at %d operations the count misses what any edit builds", n) + require.GreaterOrEqual(t, w, tt.floor(count), "at %d operations the count misses what any edit builds", count) return w } w1, w2, w4 := work(128), work(256), work(512) @@ -947,7 +947,7 @@ type treeID struct { // randomTree returns a tree of up to three services, each group holding up to // three operations and up to two groups, three levels deep at most, every ID // distinct. -func randomTree(r *rand.Rand) *ir.Document { +func randomTree(random *rand.Rand) *ir.Document { next := 0 id := func(prefix string) string { next++ @@ -959,9 +959,9 @@ func randomTree(r *rand.Rand) *ir.Document { return nil } var out []ir.OperationGroup - for range r.IntN(3) { + for range random.IntN(3) { var operations []ir.Operation - for range r.IntN(4) { + for range random.IntN(4) { operations = append(operations, treeOperation(ir.OperationID(id("o/")))) } out = append(out, treeGroup(ir.GroupID(id("operation-group/")), operations, groups(depth+1)...)) @@ -969,7 +969,7 @@ func randomTree(r *rand.Rand) *ir.Document { return out } doc := &ir.Document{} - for range 1 + r.IntN(3) { + for range 1 + random.IntN(3) { s := id("service/") doc.Services = append(doc.Services, treeService(ir.ServiceID(s), groups(0)...)) } diff --git a/ir/edit_types.go b/ir/edit_types.go index 2d5db13e2..24839fa75 100644 --- a/ir/edit_types.go +++ b/ir/edit_types.go @@ -13,8 +13,8 @@ import ( // the edited document's own. The node is shared, so it is read and never // changed; UpdateType changes a copy. func (e *Editor) Type(id TypeID) (TypeDef, bool) { - td, held := e.out.Types[id] - return td, held + typeDef, held := e.out.Types[id] + return typeDef, held } // UpdateType hands change a deep copy of the node at id, to alter in any part @@ -44,49 +44,49 @@ func (e *Editor) UpdateType(id TypeID, change func(TypeDef)) { func typeKind() nodeKind[TypeDef] { return nodeKind[TypeDef]{ method: "UpdateType", - id: func(td TypeDef) string { return string(td.Common().ID) }, + id: func(typeDef TypeDef) string { return string(typeDef.Common().ID) }, } } -// ReplaceType holds td at its own ID, in place of the node there. td is a node -// built afresh, of any kind, which the edit takes as it is: it shares nothing -// anyone changes with the edited document, and is not changed once taken. -// UpdateType changes a node instead. +// ReplaceType holds typeDef at its own ID, in place of the node there. typeDef +// is a node built afresh, of any kind, which the edit takes as it is: it shares +// nothing anyone changes with the edited document, and is not changed once +// taken. UpdateType changes a node instead. // -// It refuses a nil td, an ID the edit holds no node at, the edited document's -// own node at that ID, which is either unchanged or changed in place, and a td -// declaring an ID the node it replaces does not but an enum member's own -// ([Editor]). -func (e *Editor) ReplaceType(td TypeDef) { - if IsNilTypeDef(td) { +// It refuses a nil typeDef, an ID the edit holds no node at, the edited +// document's own node at that ID, which is either unchanged or changed in +// place, and a typeDef declaring an ID the node it replaces does not but an +// enum member's own ([Editor]). +func (e *Editor) ReplaceType(typeDef TypeDef) { + if IsNilTypeDef(typeDef) { e.refuse("replace rejected: nil type definition") return } - id := td.Common().ID + id := typeDef.Common().ID current, ok := entryAt(e, e.types(), "replace", id) switch { case !ok: - case e.doc.Types[id] == td: + case e.doc.Types[id] == typeDef: e.refuse("replace rejected: %q is the edited document's own node, which an edit never changes; "+ "change a copy with UpdateType", id) - case e.replaceable(id, current, td): - e.types().write()[id] = td + case e.replaceable(id, current, typeDef): + e.types().write()[id] = typeDef } } -// replaceable reports whether td declares no ID current, the node the edit +// replaceable reports whether typeDef declares no ID current, the node the edit // holds at id, does not, refusing a replacement that does. Its own ID, which // its key holds to it, is not among them: current may be nil or off its key. // Nor is a member's own (withOwnMembers). -func (e *Editor) replaceable(id TypeID, current, td TypeDef) bool { +func (e *Editor) replaceable(id TypeID, current, typeDef TypeDef) bool { idCounts := &e.declared idCounts.node = idCounts.scan(idCounts.node[:0], current) - idCounts.change = idCounts.scan(idCounts.change[:0], td) + idCounts.change = idCounts.scan(idCounts.change[:0], typeDef) own := declaredID{class: reflect.TypeFor[TypeID](), id: string(id)} if i := slices.Index(idCounts.change, own); i >= 0 { idCounts.change = slices.Delete(idCounts.change, i, i+1) } - idCounts.node = e.withOwnMembers(idCounts.node, td) + idCounts.node = e.withOwnMembers(idCounts.node, typeDef) if added, idCount, found := idCounts.excess(); found { e.refuse("replace rejected: the node for %q declares %s; an edit adds no ID", id, idCount.clause(added, "the node it replaces")) @@ -112,11 +112,11 @@ func (e *Editor) refuseMoved() { return } for _, id := range slices.Sorted(maps.Keys(e.out.Types)) { - td := e.out.Types[id] - if td == e.doc.Types[id] { + typeDef := e.out.Types[id] + if typeDef == e.doc.Types[id] { continue } - if moved := td.Common().ID; moved != id { + if moved := typeDef.Common().ID; moved != id { e.refuse("finish: %q holds a node moved to %q after the edit took it, so the edited document's node "+ "stays; a type keeps its ID", id, moved) e.out.Types[id] = e.doc.Types[id] // an edit adds no ID, so doc holds one here diff --git a/ir/emptyrefs.go b/ir/emptyrefs.go index fe7ea1499..518aaa806 100644 --- a/ir/emptyrefs.go +++ b/ir/emptyrefs.go @@ -52,22 +52,22 @@ type EmptyReferences struct { found []EmptyReference } -// Visit records each empty reference a field of v holds, where v is a struct, -// and asks for v's children either way. -func (e *EmptyReferences) Visit(v reflect.Value, at WalkPath) bool { - if v.Kind() != reflect.Struct { +// Visit records each empty reference a field of value holds, where value is a +// struct, and asks for value's children either way. +func (e *EmptyReferences) Visit(value reflect.Value, at WalkPath) bool { + if value.Kind() != reflect.Struct { return true } - byType, seen := e.fields[v.Type()] + byType, seen := e.fields[value.Type()] if !seen { if e.fields == nil { e.fields = map[reflect.Type][]refField{} } - byType = idFieldsOf(v.Type(), idClasses) - e.fields[v.Type()] = byType + byType = idFieldsOf(value.Type(), idClasses) + e.fields[value.Type()] = byType } for _, refField := range byType { - e.appendEmpty(v, refField, at) + e.appendEmpty(value, refField, at) } return true } @@ -78,58 +78,58 @@ func (e *EmptyReferences) List() []EmptyReference { return slices.Clone(e.found) } -// appendEmpty records each empty ID the field refFieldValue of owner holds; at +// appendEmpty records each empty ID the field refField of owner holds; at // is where owner sits. -func (e *EmptyReferences) appendEmpty(owner reflect.Value, refFieldValue refField, at WalkPath) { - v := owner.Field(refFieldValue.index) - switch refFieldValue.shape { +func (e *EmptyReferences) appendEmpty(owner reflect.Value, refField refField, at WalkPath) { + field := owner.Field(refField.index) + switch refField.shape { case idScalar: - if v.String() == "" && !emptyAllowed(owner, refFieldValue.rule) { - e.record(refFieldValue, fieldPath(at, refFieldValue), refFieldValue.rule == idLocator) + if field.String() == "" && !emptyAllowed(owner, refField.rule) { + e.record(refField, fieldPath(at, refField), refField.rule == idLocator) } case idPointer: - if !v.IsNil() && v.Elem().String() == "" { - e.record(refFieldValue, fieldPath(at, refFieldValue), false) + if !field.IsNil() && field.Elem().String() == "" { + e.record(refField, fieldPath(at, refField), false) } case idSlice: - for i := range v.Len() { - if v.Index(i).String() == "" { - e.record(refFieldValue, fieldPath(at, refFieldValue)+"["+strconv.Itoa(i)+"]", false) + for i := range field.Len() { + if field.Index(i).String() == "" { + e.record(refField, fieldPath(at, refField)+"["+strconv.Itoa(i)+"]", false) } } case idMapKey: - if v.MapIndex(reflect.Zero(v.Type().Key())).IsValid() { - e.record(refFieldValue, fieldPath(at, refFieldValue)+"[]"+MapKeySuffix, false) + if field.MapIndex(reflect.Zero(field.Type().Key())).IsValid() { + e.record(refField, fieldPath(at, refField)+"[]"+MapKeySuffix, false) } - case idMapValue: - e.appendEmptyValues(v, refFieldValue, at) + case idMap: + e.appendEmptyValues(field, refField, at) } } -// appendEmptyValues records each empty ID the map m, the field refFieldValue of +// appendEmptyValues records each empty ID the map value, the field refField of // the struct at at, holds as a value, in key order, as the walk ranges the map. -func (e *EmptyReferences) appendEmptyValues(m reflect.Value, refFieldValue refField, at WalkPath) { - if m.Len() == 0 { +func (e *EmptyReferences) appendEmptyValues(value reflect.Value, refField refField, at WalkPath) { + if value.Len() == 0 { return } - frame := e.ranging.push(m) + frame := e.ranging.push(value) for _, entry := range e.ranging.entries[frame.base:frame.end] { if entry.value.String() == "" { - e.record(refFieldValue, fieldPath(at, refFieldValue)+"["+string(entry.appendLabel(nil))+"]", false) + e.record(refField, fieldPath(at, refField)+"["+string(entry.appendLabel(nil))+"]", false) } } e.ranging.pop(frame) } -// record keeps one empty reference of refFieldValue's class at path. -func (e *EmptyReferences) record(refFieldValue refField, path string, locator bool) { - e.found = append(e.found, EmptyReference{Class: refFieldValue.class, Path: path, locator: locator}) +// record keeps one empty reference of refField's class at path. +func (e *EmptyReferences) record(refField refField, path string, locator bool) { + e.found = append(e.found, EmptyReference{Class: refField.class, Path: path, locator: locator}) } -// fieldPath spells the field refFieldValue of the struct at at, as the walk -// spells it. -func fieldPath(at WalkPath, refFieldValue refField) string { - return at.String() + "." + refFieldValue.name +// fieldPath spells the field refField of the struct at structPath, as the +// walk spells it. +func fieldPath(structPath WalkPath, refField refField) string { + return structPath.String() + "." + refField.name } // emptyAllowed reports whether an empty scalar at a position under rule is the diff --git a/ir/encoding_test.go b/ir/encoding_test.go new file mode 100644 index 000000000..95448681f --- /dev/null +++ b/ir/encoding_test.go @@ -0,0 +1,35 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestEncoding_EncodesWhereItNamesAScheme pins what makes a value encoded: an +// encoding naming a scheme, whatever else it states, and not one stating only +// what the value holds, a media type or a decoded shape, nor none at all. +func TestEncoding_EncodesWhereItNamesAScheme(t *testing.T) { + t.Parallel() + wire := &ir.TypeRef{Target: "type/string"} + for _, tc := range []struct { + name string + encoding *ir.Encoding + want bool + }{ + {"no encoding", nil, false}, + {"an empty encoding", &ir.Encoding{}, false}, + {"a media type alone", &ir.Encoding{MediaType: "application/json"}, false}, + {"a decoded shape alone", &ir.Encoding{Schema: &ir.TypeRef{Target: "type/m"}}, false}, + {"a wire type with no scheme", &ir.Encoding{WireType: wire}, false}, + {"a scheme", &ir.Encoding{Name: "base64"}, true}, + {"a scheme beside a media type", &ir.Encoding{Name: "base64", MediaType: "image/png", WireType: wire}, true}, + } { + assert.Equal(t, tc.want, tc.encoding.Encodes(), tc.name) + } +} diff --git a/ir/entries.go b/ir/entries.go index 6587fba25..e2b3048a6 100644 --- a/ir/entries.go +++ b/ir/entries.go @@ -46,21 +46,21 @@ const ( unsignedKey // number holds an unsigned key ) -// appendKey renders a key held in form onto b, as fmt's %v spells it. -func appendKey(b []byte, form keyForm, number uint64, label string) []byte { +// appendKey renders a key held in form onto buffer, as fmt's %v spells it. +func appendKey(buffer []byte, form keyForm, number uint64, label string) []byte { switch form { case signedKey: - return strconv.AppendInt(b, int64(number), 10) + return strconv.AppendInt(buffer, int64(number), 10) case unsignedKey: - return strconv.AppendUint(b, number, 10) + return strconv.AppendUint(buffer, number, 10) case labelledKey: } - return append(b, label...) + return append(buffer, label...) } -// appendLabel renders e's key onto b, as a path spells it. -func (e mapEntry) appendLabel(b []byte) []byte { - return appendKey(b, e.form, e.number, e.label) +// appendLabel renders e's key onto buffer, as a path spells it. +func (e mapEntry) appendLabel(buffer []byte) []byte { + return appendKey(buffer, e.form, e.number, e.label) } // compareEntries orders two entries of one map by their keys' spellings, byte @@ -83,8 +83,9 @@ type entryFrame struct { slot int } -// push stacks the entries of map v and returns where they sit, valid until the -// frame is popped; a map pushed above holds its own, even one of v's type. +// push stacks the entries of map value and returns where they sit, valid until +// the frame is popped; a map pushed above holds its own, even one of value's +// type. // // They are ordered by rendered key, not Go's randomized map order: a visitor is // shown values, and keeps what it finds, in walk order, which a random order @@ -92,44 +93,44 @@ type entryFrame struct { // distinct keys of every type the IR declares render distinctly. A map behind // an unexported field is copied entry by entry, as SetIterKey refuses to read // one. -func (s *entryStack) push(v reflect.Value) entryFrame { - entryFrameValue := entryFrame{base: len(s.entries)} - n := v.Len() - if n > 0 && v.CanInterface() { - entryFrameValue.store = s.storeFor(v.Type()) - entryFrameValue.slot = entryFrameValue.store.reserve(n) +func (s *entryStack) push(value reflect.Value) entryFrame { + entryFrame := entryFrame{base: len(s.entries)} + length := value.Len() + if length > 0 && value.CanInterface() { + entryFrame.store = s.storeFor(value.Type()) + entryFrame.slot = entryFrame.store.reserve(length) } - form := formOf(v.Type().Key()) + form := formOf(value.Type().Key()) // MapRange rather than v.Seq2(), which puts the loop body on the heap. - for iter := v.MapRange(); iter.Next(); { - k, val := entryFrameValue.copyEntry(iter, len(s.entries)-entryFrameValue.base) + for iter := value.MapRange(); iter.Next(); { + k, val := entryFrame.copyEntry(iter, len(s.entries)-entryFrame.base) s.entries = append(s.entries, entryOf(k, val, form)) } - entryFrameValue.end = len(s.entries) - slices.SortFunc(s.entries[entryFrameValue.base:], compareEntries) - return entryFrameValue + entryFrame.end = len(s.entries) + slices.SortFunc(s.entries[entryFrame.base:], compareEntries) + return entryFrame } // entryOf pairs the key k and value val of a map whose keys are held in form. func entryOf(k, val reflect.Value, form keyForm) mapEntry { - mapEntryValue := mapEntry{key: k, value: val, form: form} + mapEntry := mapEntry{key: k, value: val, form: form} switch form { case signedKey: - mapEntryValue.number = uint64(k.Int()) + mapEntry.number = uint64(k.Int()) case unsignedKey: - mapEntryValue.number = k.Uint() + mapEntry.number = k.Uint() case labelledKey: - mapEntryValue.label = keyLabel(k) + mapEntry.label = keyLabel(k) } - return mapEntryValue + return mapEntry } -// pop takes entryFrameValue's entries off the stack, which must hold no frame -// above entryFrameValue, and frees its slots for the next map of its type. -func (s *entryStack) pop(entryFrameValue entryFrame) { - s.entries = s.entries[:entryFrameValue.base] - if entryFrameValue.store != nil { - entryFrameValue.store.used = entryFrameValue.slot +// pop takes entryFrame's entries off the stack, which must hold no frame +// above entryFrame, and frees its slots for the next map of its type. +func (s *entryStack) pop(entryFrame entryFrame) { + s.entries = s.entries[:entryFrame.base] + if entryFrame.store != nil { + entryFrame.store.used = entryFrame.slot } } @@ -173,17 +174,17 @@ type entryStore struct { used int } -// reserve claims n slots after those in use and returns the first. When they -// do not fit, it moves to new slices twice the size or more: an entry already -// copied keeps reading the old ones, which nothing writes again. -func (st *entryStore) reserve(n int) int { +// reserve claims count slots after those in use and returns the first. When +// they do not fit, it moves to new slices twice the size or more: an entry +// already copied keeps reading the old ones, which nothing writes again. +func (st *entryStore) reserve(count int) int { first := st.used - if size := st.keys.Len(); first+n > size { - size = max(2*size, first+n) + if size := st.keys.Len(); first+count > size { + size = max(2*size, first+count) st.keys = reflect.MakeSlice(st.keys.Type(), size, size) st.values = reflect.MakeSlice(st.values.Type(), size, size) } - st.used = first + n + st.used = first + count return first } diff --git a/ir/enums_valid_test.go b/ir/enums_valid_test.go index 26018f76e..6b889ca8b 100644 --- a/ir/enums_valid_test.go +++ b/ir/enums_valid_test.go @@ -26,12 +26,12 @@ func TestEnumValid_TiesToConstBlock(t *testing.T) { valid func(string) bool emptyValid bool }{ - {"AdditionalMode", func(s string) bool { return ir.AdditionalMode(s).Valid() }, true}, - {"HTTPLocation", func(s string) bool { return ir.HTTPLocation(s).Valid() }, false}, - {"IdempotencyKind", func(s string) bool { return ir.IdempotencyKind(s).Valid() }, true}, - {"MessageDirection", func(s string) bool { return ir.MessageDirection(s).Valid() }, false}, - {"PageStrategy", func(s string) bool { return ir.PageStrategy(s).Valid() }, false}, - {"PresenceKind", func(s string) bool { return ir.PresenceKind(s).Valid() }, true}, + {"AdditionalMode", func(text string) bool { return ir.AdditionalMode(text).Valid() }, true}, + {"HTTPLocation", func(text string) bool { return ir.HTTPLocation(text).Valid() }, false}, + {"IdempotencyKind", func(text string) bool { return ir.IdempotencyKind(text).Valid() }, true}, + {"MessageDirection", func(text string) bool { return ir.MessageDirection(text).Valid() }, false}, + {"PageStrategy", func(text string) bool { return ir.PageStrategy(text).Valid() }, false}, + {"PresenceKind", func(text string) bool { return ir.PresenceKind(text).Valid() }, true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/ir/export_test.go b/ir/export_test.go index 6d2d3ed89..5bc45f60e 100644 --- a/ir/export_test.go +++ b/ir/export_test.go @@ -35,12 +35,12 @@ func CountingIDReader(reads *int) *IDReader { // JSONSpelling returns what jsonSpelling makes of s and whether spelledForJSON // reads s as that already, or false for ok when s is no decimal literal. -func JSONSpelling(s string) (spelling string, spelled, ok bool) { - decimalLiteral, ok := scanDecimal(s) +func JSONSpelling(text string) (spelling string, spelled, ok bool) { + decimalLiteral, ok := scanDecimal(text) if !ok { return "", false, false } - return jsonSpelling(decimalLiteral), decimalLiteral.spelledForJSON(s), true + return jsonSpelling(decimalLiteral), decimalLiteral.spelledForJSON(text), true } // IDClasses returns idClasses, for the external tests. @@ -92,9 +92,9 @@ func DeclaredIDField(t reflect.Type) (int, reflect.Type) { // reads through, each property and Requires name it reads, and each type it // reads a redaction off. func FlattenSteps(types TypeRegistry, root TypeID) int { - flattenerValue := flattener{types: types} - flattenerValue.flatten(root) - return flattenerValue.steps + flattener := flattener{types: types} + flattener.flatten(root) + return flattener.steps } // TreeWork returns how many nodes editor has stepped through and elements of @@ -134,8 +134,8 @@ func ForEachOperationWithin(limit int, doc *Document, fn func(Operation)) bool { } // TypeEdgesWithin is TypeEdges entering at most limit values. -func TypeEdgesWithin(limit int, td TypeDef) iter.Seq[TypeID] { - return typeEdges(limit, td) +func TypeEdgesWithin(limit int, typeDef TypeDef) iter.Seq[TypeID] { + return typeEdges(limit, typeDef) } // NewEditorWithin is NewEditor with its service tree read within limit steps, @@ -145,3 +145,16 @@ func NewEditorWithin(limit int, doc *Document) *Editor { editor.tree.index(editor.out.Services, limit) return editor } + +// StepBoundWork is stepBound over text, for the cost rows that hold a step +// intersection's refusal to bounded work: whether an intersection refuses the +// step unread, and +// the digits and divisions it read to say so. +func StepBoundWork(text string) (passes bool, work int, err error) { + decimal, err := ParseDecimal(text) + if err != nil { + return false, 0, err + } + passes, work = stepBound(decimal) + return passes, work, nil +} diff --git a/ir/flatten.go b/ir/flatten.go index 071783670..e9dc0752c 100644 --- a/ir/flatten.go +++ b/ir/flatten.go @@ -3,13 +3,15 @@ package ir +import "github.com/dexpace/morphic/stronglyconnected" + // Flattening is the shape of a model across its composition, as // [FlattenedProperties] computes it (docs/ir/models.md#the-flattening), and // [NarrowedShapes] for each shape over a union: its properties, and which of -// them are required, redacted or deprecated, while each model's catch-all -// stays its own. It points into the registry it was computed from and copies -// no property, so it describes that registry as it stood; a caller that -// changes the registry flattens again. +// them are required, redacted or deprecated, while each model's catch-all stays +// its own. It points into the registry it was computed from and copies no +// property, so it describes that registry as it was; a caller that changes the +// registry flattens again. type Flattening struct { // Properties are the members, one per wire name, each at the place the walk // first reads its wire name. @@ -70,29 +72,32 @@ type PropertyDecl struct { // place. A root naming no model has an empty shape; a cyclic composition is // read to its fixpoint. It writes nothing to types. func FlattenedProperties(types TypeRegistry, root TypeID) Flattening { - flattenerValue := flattener{types: types} - return flattenerValue.flatten(root) + flattener := flattener{types: types} + return flattener.flatten(root) } -// What a flattener's met holds for a type that is not a model on the walk's -// way: a model it has read, and an entry's target that names no model. -const ( - metRead = -1 - metUnflattened = -2 -) - -// aliasOnChain is what a flattener's aliasOf holds for an alias scalar on the -// chain being read. -const aliasOnChain = -1 +// flattenedPropertiesOver is [FlattenedProperties] over the types node finds, +// read through the alias chains aliases holds, so a run reading many +// flattenings over one lookup reads each chain once. +func flattenedPropertiesOver(node func(TypeID) (TypeDef, bool), aliases *AliasChainIndex, root TypeID) Flattening { + flattener := flattener{node: node, aliases: aliases} + return flattener.flatten(root) +} // flattener is the state of one [FlattenedProperties] walk. type flattener struct { types TypeRegistry - // met numbers each model the walk has met in the order it met them, until - // it reads the model, and marks each entry target naming no model. - met map[TypeID]int - // finished are the models the walk is done composing but has yet to read, - // in the order it finished them. + // node is the lookup a flattening over no registry reads in its place, nil + // in a walk of a registry, and aliases the index it reads alias chains + // through: the caller's, or in a walk of a registry its own, built on first + // use (resolve), which counts in aliasReads the alias scalars it reads. + node func(TypeID) (TypeDef, bool) + aliases *AliasChainIndex + aliasReads *int + // met marks each entry target naming no model the walk has recorded. + met map[TypeID]bool + // finished are the models the walk has left, every entry of theirs + // followed, but has yet to read, in the order it left them. finished []frame // members are the wire names read so far, in layout order, and index // places each name among them. @@ -103,11 +108,6 @@ type flattener struct { required map[string]bool // unflattened are the entry targets naming no model, in walk order. unflattened []TypeID - // aliasOf places each alias scalar read through in aliasEnds, which holds - // the type its chain stands for, so a chain is read once however many - // entries name it. - aliasOf map[TypeID]int - aliasEnds []TypeID // sensitivity holds, for each type a redaction is read through, whether // its Base reaches a Sensitive type, false while the type is on the chain // being read, so a chain is read once however many declarations name it. @@ -129,17 +129,10 @@ type member struct { reads []PropertyDecl } -// frame is a model the walk has met: the next of its composition entries to -// follow, the number met gives it, its low-link as Tarjan's algorithm keeps -// it, equal to number only for the first model of a component the walk met, and -// how many models were finished when it was met. +// frame is a model the walk has met, a vertex of the composition it searches. type frame struct { - id TypeID - m *Model - next int - number int - low int - since int + id TypeID + m *Model } // flatten is [FlattenedProperties] over f's registry. @@ -150,11 +143,11 @@ func (f *flattener) flatten(root TypeID) Flattening { return f.result() } -// read walks the model root names, read through alias scalars, and reports +// read walks the model root names, read through alias scalars, and returns // false where it names no model, which has no member to read. func (f *flattener) read(root TypeID) bool { id := f.resolve(root) - model, ok := f.types[id].(*Model) + model, ok := f.typeAt(id).(*Model) if !ok || model == nil { return false } @@ -165,60 +158,60 @@ func (f *flattener) read(root TypeID) bool { return true } +// typeAt returns the node the registry, or the lookup in its place, holds at +// id, nil where it holds none. +func (f *flattener) typeAt(id TypeID) TypeDef { + if f.node == nil { + return f.types[id] + } + typeDef, _ := f.node(id) + return typeDef +} + // walk reads the model id names and every model it composes in layout order. -// It finds the composition's strongly connected components as Tarjan's -// algorithm does, and reads each when its first model finishes, so a model is -// read after every model it composes, unless that one composes it too; the -// models of one component are read in the order they finished. Each model is -// met once, so the walk follows at most every entry of the models it meets. +// It reads each strongly connected component of the composition as it closes, +// so a model is read after every model it composes, unless that one composes +// it too; the models of one component are read in the order the walk left +// them. Each model is met once, so the walk follows at most every entry of the +// models it meets. func (f *flattener) walk(id TypeID, model *Model) { - f.met = map[TypeID]int{} + f.met = map[TypeID]bool{} f.index = map[string]int{} - stack := []frame{f.meet(id, model)} - for len(stack) > 0 { - f.steps++ - top := &stack[len(stack)-1] - if target, more := entry(top.m, top.next); more { - top.next++ - if pid, pm, fresh := f.parent(target, top); fresh { - stack = append(stack, f.meet(pid, pm)) - } - continue - } - done := *top - stack = stack[:len(stack)-1] - if len(stack) > 0 { - below := &stack[len(stack)-1] - below.low = min(below.low, done.low) - } - f.finish(done) + stronglyconnected.NewSearch[frame](f).From(frame{id: id, m: model}) +} + +// Edge returns the model from's composition entry at index composes in, which +// the search follows, an entry naming no model leading to none (parent), and +// false past from's last entry. Each call is a step. +func (f *flattener) Edge(from frame, index int) (to frame, follow, more bool) { + f.steps++ + target, more := entry(from.m, index) + if !more { + return frame{}, false, false } + id, model, isModel := f.parent(target) + return frame{id: id, m: model}, isModel, true } -// meet numbers the model id names as the next the walk meets. -func (f *flattener) meet(id TypeID, model *Model) frame { - number := len(f.met) - f.met[id] = number - return frame{id: id, m: model, number: number, low: number, since: len(f.finished)} +// LeaveVertex records that the walk has followed every entry of left, which it +// reads once its component closes. +func (f *flattener) LeaveVertex(leftFrame frame) { + f.finished = append(f.finished, leftFrame) } -// finish records that the walk is done composing fr. When fr is the first -// model of its component the walk met, the component is every model finished -// since then and not yet read, and they are read now, in the order they -// finished. -func (f *flattener) finish(fr frame) { - f.finished = append(f.finished, fr) - if fr.low < fr.number { - return - } - if f.narrow != nil && fr.number == 0 { - f.narrow.readRoot(f.finished[fr.since:]) +// CloseComponent reads the models of a component as it closes: the last of the +// models the walk has left and not read, as many as members holds, in the +// order it left them. A narrowing walk records first the component holding its +// root, the first model met, which is the last to close. +func (f *flattener) CloseComponent(members []frame) { + since := len(f.finished) - len(members) + if f.narrow != nil && members[0].id == f.narrow.root { + f.narrow.readRoot(f.finished[since:]) } - for _, frame := range f.finished[fr.since:] { - f.met[frame.id] = metRead - f.emit(frame.id, frame.m) + for _, model := range f.finished[since:] { + f.emit(model.id, model.m) } - f.finished = f.finished[:fr.since] + f.finished = f.finished[:since] } // entry returns the target of model's i-th composition entry, counting its Base @@ -241,14 +234,13 @@ func entry(model *Model, i int) (TypeID, bool) { return "", false } -// parent returns the model an entry of from naming target composes in, read -// through alias scalars and, in a [NarrowedShapes] walk, through the variant -// it reads in a union's place, and whether the walk is yet to meet it. One met -// and not yet read shares a component with from, which from's low then says. -// An entry naming no model is recorded as unflattened, as written or as the -// variant standing in its place writes it, the first time the walk reads it, -// and an unset one names nothing at all. -func (f *flattener) parent(target TypeID, from *frame) (TypeID, *Model, bool) { +// parent returns the model an entry naming target composes in, read through +// alias scalars and, in a [NarrowedShapes] walk, through the variant it reads +// in a union's place, and false where it names none. An entry naming no model +// is recorded as unflattened, as written or as the variant taking its place +// writes it, the first time the walk reads it, and an unset one names nothing +// at all. +func (f *flattener) parent(target TypeID) (TypeID, *Model, bool) { if target == "" { return "", nil, false } @@ -256,10 +248,10 @@ func (f *flattener) parent(target TypeID, from *frame) (TypeID, *Model, bool) { if f.narrow != nil { target, id = f.substitute(target, id) } - model, ok := f.types[id].(*Model) + model, ok := f.typeAt(id).(*Model) if !ok || model == nil { - if _, marked := f.met[target]; !marked { - f.met[target] = metUnflattened + if !f.met[target] { + f.met[target] = true f.unflattened = append(f.unflattened, target) } if f.narrow != nil { @@ -267,49 +259,44 @@ func (f *flattener) parent(target TypeID, from *frame) (TypeID, *Model, bool) { } return "", nil, false } - number, met := f.met[id] - if !met { - return id, model, true - } - if number != metRead { - from.low = min(from.low, number) - } - return "", nil, false + return id, model, true } -// resolve returns the type id stands for: id itself unless it names an alias -// scalar, else the type at the end of its chain, or on a cyclic chain one of -// the cycle's scalars, which is no model either way. Each scalar is read once -// per walk. +// resolve returns the type id names: id itself unless it names an alias scalar, +// else the type at the end of its chain, or on a cyclic chain one of the +// cycle's scalars, which is no model either way. A walk of a registry reads +// each scalar once, through an index of its own, and takes a step for each +// alias that index reads beside the one for id, as a walk reading each chain +// one hop at a time, and each once, would. func (f *flattener) resolve(id TypeID) TypeID { - var path []TypeID - cur := id - for { - f.steps++ - if at, seen := f.aliasOf[cur]; seen { - if at != aliasOnChain { - cur = f.aliasEnds[at] - } - break - } - base, alias := AliasBase(f.types, cur) - if !alias { - break - } - if f.aliasOf == nil { - f.aliasOf = map[TypeID]int{} - } - f.aliasOf[cur] = aliasOnChain - path = append(path, cur) - cur = base + f.steps++ + if f.node != nil { + end, _ := f.aliases.End(id) + return end } - if len(path) > 0 { - for _, typeID := range path { - f.aliasOf[typeID] = len(f.aliasEnds) - } - f.aliasEnds = append(f.aliasEnds, cur) + if _, alias := AliasBase(f.types, id); !alias { + return id + } + if f.aliases == nil { + f.aliases, f.aliasReads = registryAliasIndex(f.types) } - return cur + read := *f.aliasReads + end, _ := f.aliases.End(id) + f.steps += *f.aliasReads - read + return end +} + +// registryAliasIndex returns an index over types and the count of the alias +// scalars it has read. +func registryAliasIndex(types TypeRegistry) (*AliasChainIndex, *int) { + reads := new(int) + return NewAliasChainIndex(func(id TypeID) (TypeDef, bool) { + typeDef, held := types[id] + if _, alias := AliasBase(types, id); alias { + *reads++ + } + return typeDef, held + }), reads } // emit reads the model id names: each of its own properties, in source order, @@ -411,17 +398,17 @@ func (f *flattener) sensitive(id TypeID) bool { break } - td := f.types[id] - if IsNilTypeDef(td) { + typeDef := f.typeAt(id) + if IsNilTypeDef(typeDef) { break } - if td.Common().Sensitive { + if typeDef.Common().Sensitive { found = true break } var base *TypeRef - switch t := td.(type) { + switch t := typeDef.(type) { case *Scalar: base = t.Base case *Model: diff --git a/ir/flatten_member.go b/ir/flatten_member.go index 6ea6ea503..868ad1758 100644 --- a/ir/flatten_member.go +++ b/ir/flatten_member.go @@ -5,11 +5,11 @@ package ir // MemberReader reads single members of the flattenings of one registry's // models, for a reader asking a model for a name or two rather than for its -// whole shape. It runs the walk [FlattenedProperties] runs, so the two take -// the same declaration, but reads each model's own properties through an -// index of them by wire name, made at the model's first read and kept. A read -// costs the root's composition, and each model's properties once per reader. -// Like a [Flattening], it describes the registry as it stood when it read it. +// whole shape. It runs the walk [FlattenedProperties] runs, so the two take the +// same declaration, but reads each model's own properties through an index of +// them by wire name, made at the model's first read and kept. A read costs the +// root's composition, and each model's properties once per reader. Like a +// [Flattening], it describes the registry as it was when it read it. type MemberReader struct { types TypeRegistry // own places, for each model read, each wire name among its own @@ -30,14 +30,14 @@ func NewMemberReader(types TypeRegistry) *MemberReader { // names no model, read through alias scalars, or none it composes declares // the name. func (r *MemberReader) Member(root TypeID, wire string) (PropertyDecl, bool) { - memberQueryValue := memberQuery{reader: r, wire: wire} - flattenerValue := flattener{types: r.types, query: &memberQueryValue} - flattenerValue.read(root) - r.steps += flattenerValue.steps - if len(memberQueryValue.reads) == 0 { + memberQuery := memberQuery{reader: r, wire: wire} + flattener := flattener{types: r.types, query: &memberQuery} + flattener.read(root) + r.steps += flattener.steps + if len(memberQuery.reads) == 0 { return PropertyDecl{}, false } - return taken(memberQueryValue.reads), true + return taken(memberQuery.reads), true } // memberQuery is the one wire name a MemberReader's walk reads, and the diff --git a/ir/flatten_reference_test.go b/ir/flatten_reference_test.go index fe8160116..06a7e25c8 100644 --- a/ir/flatten_reference_test.go +++ b/ir/flatten_reference_test.go @@ -65,12 +65,12 @@ func cyclic(types ir.TypeRegistry, models map[ir.TypeID]*ir.Model) bool { // stating a deprecation is. func reference(t *testing.T, types ir.TypeRegistry, root ir.TypeID) (lines, undeclared []string, unflattened []ir.TypeID) { t.Helper() - referenceWalkValue := referenceWalk{t: t, types: types, seen: map[ir.TypeID]bool{}, marked: map[ir.TypeID]bool{}} - if model, ok := types[standsFor(types, root)].(*ir.Model); !ok || model == nil { + referenceWalk := referenceWalk{t: t, types: types, seen: map[ir.TypeID]bool{}, marked: map[ir.TypeID]bool{}} + if model, ok := types[aliasChainEnd(types, root)].(*ir.Model); !ok || model == nil { return []string{}, nil, nil } - referenceWalkValue.visit(standsFor(types, root), 0) - return referenceWalkValue.result() + referenceWalk.visit(aliasChainEnd(types, root), 0) + return referenceWalk.result() } // referenceWalk is one reference walk: the models in the order it read them, @@ -91,7 +91,7 @@ func (r *referenceWalk) visit(id ir.TypeID, depth int) { require.Less(r.t, depth, 64, "an acyclic registry of at most twenty types nests no deeper") r.seen[id] = true for _, target := range entries(r.types[id].(*ir.Model)) { - end := standsFor(r.types, target) + end := aliasChainEnd(r.types, target) if model, ok := r.types[end].(*ir.Model); !ok || model == nil { if !r.marked[target] { r.marked[target] = true diff --git a/ir/flatten_test.go b/ir/flatten_test.go index 1b8011874..09401f8dc 100644 --- a/ir/flatten_test.go +++ b/ir/flatten_test.go @@ -433,8 +433,8 @@ func TestFlattenedProperties_ReadsThroughAliasScalars(t *testing.T) { ) flattening := ir.FlattenedProperties(doc.Types, "root") assert.Equal(t, []string{"m.a@m < b.a@b", "b.b@b"}, flatLines(flattening), - "a root, a Base and a Mixin naming an alias scalar each read the model it stands for") - assert.Empty(t, flattening.Unflattened, "an alias read a second time still stands for its model") + "a root, a Base and a Mixin naming an alias scalar each read the model it names") + assert.Empty(t, flattening.Unflattened, "an alias read a second time still names its model") } func TestFlattenedProperties_Unflattened(t *testing.T) { @@ -557,13 +557,13 @@ func TestFlattenedProperties_WorkGrowsLinearly(t *testing.T) { t.Parallel() shapes := map[string]func(n int) (ir.TypeRegistry, ir.TypeID){ // n entries each naming the head of one alias chain n long. - "a chain of aliases named by every entry": func(n int) (ir.TypeRegistry, ir.TypeID) { + "a chain of aliases named by every entry": func(count int) (ir.TypeRegistry, ir.TypeID) { doc := irtest.DocOf(owning("end", nil, wired("end.p", "p"))) - for i := range n { + for i := range count { doc.Types[scalarAt(i)] = irtest.ScalarOf(scalarAt(i), scalarAt(i+1)) } - doc.Types[scalarAt(n)] = irtest.ScalarOf(scalarAt(n), "end") - heads := make([]ir.TypeID, n) + doc.Types[scalarAt(count)] = irtest.ScalarOf(scalarAt(count), "end") + heads := make([]ir.TypeID, count) for i := range heads { heads[i] = scalarAt(0) } @@ -572,25 +572,25 @@ func TestFlattenedProperties_WorkGrowsLinearly(t *testing.T) { }, // n declarations each typed at the head of one scalar chain n long, // ending at a Sensitive scalar. - "a chain to a sensitive type every declaration's type heads": func(n int) (ir.TypeRegistry, ir.TypeID) { - return redactionChain(n, sensitiveScalar(scalarAt(n))) + "a chain to a sensitive type every declaration's type heads": func(count int) (ir.TypeRegistry, ir.TypeID) { + return redactionChain(count, sensitiveScalar(scalarAt(count))) }, // The same, the chain's end leading back to its head. - "a cycle of scalars every declaration's type enters": func(n int) (ir.TypeRegistry, ir.TypeID) { - return redactionChain(n, irtest.ScalarOf(scalarAt(n), scalarAt(0))) + "a cycle of scalars every declaration's type enters": func(count int) (ir.TypeRegistry, ir.TypeID) { + return redactionChain(count, irtest.ScalarOf(scalarAt(count), scalarAt(0))) }, // n levels of two models, each composing both of the level below. - "a lattice every path of which reaches the bottom": func(n int) (ir.TypeRegistry, ir.TypeID) { + "a lattice every path of which reaches the bottom": func(count int) (ir.TypeRegistry, ir.TypeID) { doc := irtest.DocOf() level := func(i int, side string) ir.TypeID { return ir.TypeID(fmt.Sprintf("l%04d%s", i, side)) } - for i := range n { + for i := range count { for _, side := range []string{"a", "b"} { doc.Types[level(i, side)] = owning(level(i, side), mixing(level(i+1, "a"), level(i+1, "b")), wired(ir.PropertyID(level(i, side)), "x")) } } - doc.Types[level(n, "a")] = owning(level(n, "a"), nil) - doc.Types[level(n, "b")] = owning(level(n, "b"), nil) + doc.Types[level(count, "a")] = owning(level(count, "a"), nil) + doc.Types[level(count, "b")] = owning(level(count, "b"), nil) return doc.Types, level(0, "a") }, } @@ -625,18 +625,39 @@ func TestFlattenedProperties_StepsCountEachTypeARedactionReads(t *testing.T) { assert.Equal(t, steps("missing")+10, steps(scalarAt(0)), "each scalar a redaction reads through is a step") } +// TestFlattenedProperties_StepsCountEachAliasAnEntryReadsOnce holds +// FlattenSteps to a step for each alias scalar an entry is read through, each +// once a walk: a Base at the head of n aliases costs n steps more than one +// naming the end, and a second entry naming the head again costs what one +// naming the end does, past the 64 hops a walk once read. +func TestFlattenedProperties_StepsCountEachAliasAnEntryReadsOnce(t *testing.T) { + t.Parallel() + steps := func(count int, entries ...ir.TypeID) int { + doc := irtest.DocOf(owning("end", nil, wired("end.p", "p")), owning("m", mixing(entries...))) + for i := range count { + doc.Types[scalarAt(i)] = irtest.ScalarOf(scalarAt(i), scalarAt(i+1)) + } + doc.Types[scalarAt(count)] = irtest.ScalarOf(scalarAt(count), "end") + return ir.FlattenSteps(doc.Types, "m") + } + for _, n := range []int{0, 1, 5, 70} { + assert.Equal(t, steps(n, "end")+n+1, steps(n, scalarAt(0)), "%d aliases above the last: each a step", n) + assert.Equal(t, steps(n, scalarAt(0), "end"), steps(n, scalarAt(0), scalarAt(0)), "%d: a chain read twice costs it once", n) + } +} + // scalarAt is the ID of the i-th scalar of a chain. func scalarAt(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("s%04d", i)) } // redactionChain returns the registry and root of a model declaring n // properties, each typed at the head of a chain of n scalars leading to end. -func redactionChain(n int, end *ir.Scalar) (ir.TypeRegistry, ir.TypeID) { +func redactionChain(count int, end *ir.Scalar) (ir.TypeRegistry, ir.TypeID) { doc := irtest.DocOf(end) - for i := range n { + for i := range count { doc.Types[scalarAt(i)] = irtest.ScalarOf(scalarAt(i), scalarAt(i+1)) } - properties := make([]ir.Property, n) + properties := make([]ir.Property, count) for i := range properties { properties[i] = typed(ir.PropertyID(fmt.Sprintf("p%04d", i)), fmt.Sprintf("w%04d", i), scalarAt(0)) } diff --git a/ir/formats.go b/ir/formats.go new file mode 100644 index 000000000..98ab2bb19 --- /dev/null +++ b/ir/formats.go @@ -0,0 +1,182 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "net/url" + "strings" + "time" +) + +// isAbsoluteURI reports whether text is an RFC 3986 URI with a scheme. The +// bytes are scanned first, since url.Parse accepts what the grammar does not (a +// space, a brace, a non-ASCII byte). The scan and ipLiteralPlaced own the +// characters and where brackets sit; url.Parse owns the structure and the +// IP-literal's content. An IPvFuture host ([v1.x]) is refused, since url.Parse +// refuses it, though RFC 3986 allows one: the url primitive admits no such +// value. +func isAbsoluteURI(text string) bool { + if !uriBytesValid(text) { + return false + } + parsed, err := url.Parse(text) + return err == nil && parsed.Scheme != "" +} + +// uriBytesValid reports whether text is a scheme, a colon and then a tail +// uriTailValid admits. +func uriBytesValid(text string) bool { + if text == "" || !isLetter(text[0]) { + return false + } + i := 1 + for i < len(text) && (isLetter(text[i]) || isDigit(text[i]) || strings.IndexByte("+-.", text[i]) >= 0) { + i++ + } + if i == len(text) || text[i] != ':' { + return false + } + return uriTailValid(text[i+1:]) +} + +// uriTailValid reports whether rest, what follows a URI's scheme colon, holds +// only bytes RFC 3986 allows: unreserved, a gen-delim, a sub-delim or a +// percent-encoded octet. A bracket is allowed only in the authority (an +// IP-literal host), an "@" at most once there, and a fragment delimiter only +// once. +func uriTailValid(rest string) bool { + authorityEnd := 0 + if strings.HasPrefix(rest, "//") { + authorityEnd = 2 + strings.IndexAny(rest[2:]+"/", "/?#") + } + if !ipLiteralPlaced(rest[:authorityEnd]) || strings.Count(rest[:authorityEnd], "@") > 1 { + return false + } + fragments := 0 + for i := 0; i < len(rest); i++ { + switch character := rest[i]; { + case character == '%': + if i+2 >= len(rest) || !isHex(rest[i+1]) || !isHex(rest[i+2]) { + return false + } + i += 2 + case character == '[' || character == ']': + if i >= authorityEnd { + return false + } + case character == '#': + if fragments++; fragments > 1 { + return false + } + case !isLetter(character) && !isDigit(character) && strings.IndexByte("-._~:/?@!$&'()*+,;=", character) < 0: + return false + } + } + return true +} + +// ipLiteralPlaced reports whether authority's brackets, if it has any, enclose +// its whole host, which RFC 3986 allows only for an IP-literal: one "[" right +// after "//" or the userinfo's "@", and one "]" ending the authority or +// followed by the port's ":". +func ipLiteralPlaced(authority string) bool { + if !strings.ContainsAny(authority, "[]") { + return true + } + host := authority[2:] + if at := strings.LastIndexByte(host, '@'); at >= 0 { + host = host[at+1:] + } + end := strings.IndexByte(host, ']') + return strings.HasPrefix(host, "[") && end > 0 && + strings.Count(authority, "[") == 1 && strings.Count(authority, "]") == 1 && + (end == len(host)-1 || host[end+1] == ':') +} + +// isLetter reports whether character is an ASCII letter. +func isLetter(character byte) bool { + return character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' +} + +// isDigit reports whether character is an ASCII decimal digit. +func isDigit(character byte) bool { return character >= '0' && character <= '9' } + +// parses reports whether text is a time in layout. Calendar fields are +// checked, so 2024-02-30 is refused. +func parses(layout, text string) bool { + _, err := time.Parse(layout, text) + return err == nil +} + +// uuidLength is the length of the 8-4-4-4-12 form isUUID reads: 32 +// hexadecimal digits and four hyphens. +const uuidLength = 36 + +// isUUID reports whether text is the 8-4-4-4-12 hexadecimal form. +func isUUID(text string) bool { + if len(text) != uuidLength { + return false + } + for i := range len(text) { + switch i { + case 8, 13, 18, 23: + if text[i] != '-' { + return false + } + default: + if !isHex(text[i]) { + return false + } + } + } + return true +} + +// isHex reports whether character is a hexadecimal digit. +func isHex(character byte) bool { + return isDigit(character) || character >= 'a' && character <= 'f' || character >= 'A' && character <= 'F' +} + +// isDuration reports whether text is an ISO 8601 duration as RFC 3339 Appendix +// A writes it: P, then a week count alone, or a date part and a time part, each +// a run of consecutive designators from years to days and from hours to +// seconds, at least one present. +func isDuration(text string) bool { + rest, ok := strings.CutPrefix(text, "P") + if !ok || rest == "" { + return false + } + if weeks, found := strings.CutSuffix(rest, "W"); found { + return isDigitRun(weeks) + } + datePart, timePart, hasTime := strings.Cut(rest, "T") + if hasTime && timePart == "" || !hasTime && datePart == "" { + return false + } + return consecutiveDesignators(datePart, "YMD") && consecutiveDesignators(timePart, "HMS") +} + +// consecutiveDesignators reports whether text is empty or a run of digit-led +// designators each following the previous in order, starting anywhere. +func consecutiveDesignators(text, order string) bool { + next := 0 + for text != "" { + end := strings.IndexFunc(text, func(character rune) bool { return character < '0' || character > '9' }) + if end <= 0 || end == len(text) { + return false + } + at := strings.IndexByte(order[next:], text[end]) + if at < 0 || (next > 0 && at != 0) { + return false + } + next += at + 1 + text = text[end+1:] + } + return true +} + +// isDigitRun reports whether text is a non-empty run of decimal digits. +func isDigitRun(text string) bool { + return text != "" && strings.IndexFunc(text, func(character rune) bool { return character < '0' || character > '9' }) < 0 +} diff --git a/ir/helpers_test.go b/ir/helpers_test.go index cc4229123..f95224088 100644 --- a/ir/helpers_test.go +++ b/ir/helpers_test.go @@ -67,12 +67,12 @@ func (v semver) String() string { return fmt.Sprintf("%d.%d.%d", v[0], v[1], v[2 // parseVersion reads s as MAJOR.MINOR.PATCH: three decimal numbers with no sign // and no leading zero (semver 2.0.0 §2), and nothing more. Each has at most // nine digits, so a successor computed from one cannot overflow an int. -func parseVersion(s string) (semver, bool) { - parts := strings.Split(s, ".") +func parseVersion(text string) (semver, bool) { + parts := strings.Split(text, ".") if len(parts) != len(semver{}) { return semver{}, false } - var semverValue semver + var version semver for i, part := range parts { if part == "" || len(part) > 9 || (len(part) > 1 && part[0] == '0') || strings.Trim(part, "0123456789") != "" { return semver{}, false @@ -81,9 +81,9 @@ func parseVersion(s string) (semver, bool) { if err != nil { return semver{}, false } - semverValue[i] = n + version[i] = n } - return semverValue, true + return version, true } // compareVersions orders two versions by precedence. One that does not parse @@ -440,26 +440,26 @@ type testingT interface { // zero, and is asserted in both directions, so it cannot outlive its reason. // The walk reads the struct's own fields alone, not the fields of a value one // of them holds. -func assertNoFieldZero(testingTValue testingT, v any, zeroOK ...zeroField) { - testingTValue.Helper() +func assertNoFieldZero(testingT testingT, v any, zeroOK ...zeroField) { + testingT.Helper() rv := reflect.Indirect(reflect.ValueOf(v)) - require.Equal(testingTValue, reflect.Struct, rv.Kind(), "a populated value must be a struct or a pointer to one") - require.Positive(testingTValue, rv.NumField(), "a struct with no fields witnesses nothing") + require.Equal(testingT, reflect.Struct, rv.Kind(), "a populated value must be a struct or a pointer to one") + require.Positive(testingT, rv.NumField(), "a struct with no fields witnesses nothing") exempt := make(map[string]string, len(zeroOK)) for _, zeroField := range zeroOK { field, ok := rv.Type().FieldByName(zeroField.name) - require.Truef(testingTValue, ok && len(field.Index) == 1, "%s declares no field %s of its own", rv.Type().Name(), zeroField.name) + require.Truef(testingT, ok && len(field.Index) == 1, "%s declares no field %s of its own", rv.Type().Name(), zeroField.name) exempt[zeroField.name] = zeroField.why } - require.Len(testingTValue, exempt, len(zeroOK), "each field is listed once") + require.Len(testingT, exempt, len(zeroOK), "each field is listed once") for field, value := range rv.Fields() { if why, ok := exempt[field.Name]; ok { - assert.Truef(testingTValue, value.IsZero(), + assert.Truef(testingT, value.IsZero(), "%s.%s is listed as deliberately zero (%s) but the value sets it; drop the entry", rv.Type().Name(), field.Name, why) continue } - assert.Falsef(testingTValue, value.IsZero(), "%s.%s is left zero, so a round trip of the value says nothing of it", + assert.Falsef(testingT, value.IsZero(), "%s.%s is left zero, so a round trip of the value says nothing of it", rv.Type().Name(), field.Name) } } @@ -636,13 +636,13 @@ func flatRandom(seed uint64) (*ir.Document, []ir.TypeID) { } for _, id := range types { - if td := doc.Types[id]; !ir.IsNilTypeDef(td) && facets.IntN(4) == 0 { - td.Common().Sensitive = true + if typeDef := doc.Types[id]; !ir.IsNilTypeDef(typeDef) && facets.IntN(4) == 0 { + typeDef.Common().Sensitive = true } } - for _, td := range doc.Types { - model, ok := td.(*ir.Model) + for _, typeDef := range doc.Types { + model, ok := typeDef.(*ir.Model) if !ok || model == nil { continue } @@ -670,16 +670,16 @@ func reachesSensitive(types ir.TypeRegistry, id ir.TypeID) bool { seen := map[ir.TypeID]bool{} for !seen[id] { seen[id] = true - td := types[id] - if ir.IsNilTypeDef(td) { + typeDef := types[id] + if ir.IsNilTypeDef(typeDef) { return false } - if td.Common().Sensitive { + if typeDef.Common().Sensitive { return true } var base *ir.TypeRef - switch t := td.(type) { + switch t := typeDef.(type) { case *ir.Scalar: base = t.Base case *ir.Model: @@ -702,7 +702,7 @@ func reachesSensitive(types ir.TypeRegistry, id ir.TypeID) bool { func composition(types ir.TypeRegistry, root ir.TypeID) (map[ir.TypeID]*ir.Model, map[ir.TypeID]bool) { models := map[ir.TypeID]*ir.Model{} unflattened := map[ir.TypeID]bool{} - queue := []ir.TypeID{standsFor(types, root)} + queue := []ir.TypeID{aliasChainEnd(types, root)} if model, ok := types[queue[0]].(*ir.Model); !ok || model == nil { return models, unflattened } @@ -715,7 +715,7 @@ func composition(types ir.TypeRegistry, root ir.TypeID) (map[ir.TypeID]*ir.Model model := types[id].(*ir.Model) models[id] = model for _, target := range entries(model) { - end := standsFor(types, target) + end := aliasChainEnd(types, target) if pm, ok := types[end].(*ir.Model); ok && pm != nil { queue = append(queue, end) continue @@ -753,7 +753,7 @@ func entriesOf(types ir.TypeRegistry, model *ir.Model) []ir.TypeID { } var out []ir.TypeID for _, target := range entries(model) { - end := standsFor(types, target) + end := aliasChainEnd(types, target) if pm, ok := types[end].(*ir.Model); ok && pm != nil { out = append(out, end) } @@ -775,9 +775,9 @@ func entries(model *ir.Model) []ir.TypeID { return out } -// standsFor follows id's alias scalars to the first type that is none, or to +// aliasChainEnd follows id's alias scalars to the first type that is none, or to // the first met twice. -func standsFor(types ir.TypeRegistry, id ir.TypeID) ir.TypeID { +func aliasChainEnd(types ir.TypeRegistry, id ir.TypeID) ir.TypeID { seen := map[ir.TypeID]bool{} for { base, alias := ir.AliasBase(types, id) diff --git a/ir/idpositions.go b/ir/idpositions.go index 8848526c2..e93da9245 100644 --- a/ir/idpositions.go +++ b/ir/idpositions.go @@ -73,6 +73,7 @@ var idPositions = map[string]idRule{ "Content.Encoding": idRequired, "ConstructorValue.Scalar": idRequired, "Discriminator.Mapping": idRequired, + "Discriminator.DecodeOnlyRoutes": idRequired, "DocRef.Type": idRequired, "HTTPParamBinding.BodyPath": idRequired, "HTTPParamBinding.Param": idRequired, @@ -114,8 +115,6 @@ var idPositions = map[string]idRule{ "flattener.types": idElsewhere, "flattener.met": idRequired, "flattener.unflattened": idRequired, - "flattener.aliasOf": idRequired, - "flattener.aliasEnds": idRequired, "flattener.sensitivity": idRequired, "frame.id": idRequired, // A MemberReader runs that walk, and keeps the models it has read by the ID @@ -123,6 +122,11 @@ var idPositions = map[string]idRule{ "MemberReader.types": idElsewhere, "MemberReader.own": idRequired, + // A PropertyCountBounds' own state, which no Document holds: each model + // whose component has closed, by the ID an entry or a question read through + // alias scalars to it, never an empty one. + "countedComponents.of": idRequired, + // NarrowedShapes' result and its walks' own state, which no Document holds // either. Narrowing.Union is "" where the composition narrows no one union, // as its comment says, narrowState.root before the walk meets its root @@ -139,17 +143,34 @@ var idPositions = map[string]idRule{ "substitution.variant": idRequired, "variantEnd.target": idOptional, "variantEnd.id": idOptional, + + // An AliasChainIndex's own state, which no Document holds: each type it has + // read, keyed and placed by the ID a question or a Base target named, + // never an empty one, since an index is asked of a set reference. + "AliasChainIndex.at": idRequired, + "aliasChainEntry.id": idRequired, + + // A ValueAdmissionReader's own state and its walks', which no Document + // holds: each keyed or listed by an ID a reference or a composition entry + // named, never an empty one. + "ValueAdmissionReader.nodes": idRequired, + "ValueAdmissionReader.models": idRequired, + "ValueAdmissionReader.unions": idRequired, + "modelFacts.composition": idRequired, + "admissionKey.id": idRequired, + "admissionFrame.opened": idRequired, + "admissionSearch.frames": idRequired, } // idShape is how a field holds its IDs. type idShape int const ( - idScalar idShape = iota // an ID held directly - idPointer // *ID: nil is the absent reference - idSlice // []ID: every element a reference - idMapKey // map[ID]V: every key a reference - idMapValue // map[K]ID: every value a reference + idScalar idShape = iota // an ID held directly + idPointer // *ID: nil is the absent reference + idSlice // []ID: every element a reference + idMapKey // map[ID]V: every key a reference + idMap // map[K]ID: every value a reference ) // refField is one ID-typed field of a struct type: where it sits, how it holds @@ -191,7 +212,7 @@ func idShapeOf(t reflect.Type, classes map[reflect.Type]bool) (idShape, reflect. case t.Kind() == reflect.Map && classes[t.Key()]: return idMapKey, t.Key(), true case t.Kind() == reflect.Map && classes[t.Elem()]: - return idMapValue, t.Elem(), true + return idMap, t.Elem(), true default: return 0, nil, false } diff --git a/ir/ids_test.go b/ir/ids_test.go index 0bb1abfb7..a284e29e2 100644 --- a/ir/ids_test.go +++ b/ir/ids_test.go @@ -133,7 +133,7 @@ func TestWellFormedID_Shape(t *testing.T) { // TestPrimitiveTypeID_IsTheSharedScheme pins the spelling every compiler must // reach for a primitive. These IDs are written into every golden IR snapshot // and are the one identity two documents lowered from different formats have to -// agree on, so a change here is a silent breaking change across formats. +// agree on, so a change here is an unannounced breaking change across formats. func TestPrimitiveTypeID_IsTheSharedScheme(t *testing.T) { t.Parallel() assert.Equal(t, ir.TypeID("type/primitive/string"), ir.PrimitiveTypeID(ir.PrimitiveString)) diff --git a/ir/inferred_test.go b/ir/inferred_test.go index 4d1b55afc..bbe72361b 100644 --- a/ir/inferred_test.go +++ b/ir/inferred_test.go @@ -56,8 +56,8 @@ func TestJoinInferred_ListsEachNameOnceInFirstWrittenOrder(t *testing.T) { const stackNames = 8 // distinctNames returns a list of n distinct names, n0 to n(n-1). -func distinctNames(n int) ir.Inferred { - out := make([]string, n) +func distinctNames(count int) ir.Inferred { + out := make([]string, count) for i := range out { out[i] = fmt.Sprintf("n%d", i) } diff --git a/ir/irfacts/alias.go b/ir/irfacts/alias.go index b3dfb6db6..dfed6aad3 100644 --- a/ir/irfacts/alias.go +++ b/ir/irfacts/alias.go @@ -5,67 +5,40 @@ package irfacts import "github.com/dexpace/morphic/ir" -// aliasTargets holds, for each alias scalar of a registry, the type it stands -// for, as ir.Supertypes reads a reference: along ir.AliasBase to a type that is -// no alias, or on a cyclic chain to the first type the walk meets twice. Each -// scalar is resolved once, so a chain named from many places costs its length -// once rather than once per reference. -type aliasTargets map[ir.TypeID]ir.TypeID +// aliasTargets answers, for each alias scalar of a registry, the type it names, +// as ir.Supertypes reads a reference: along ir.AliasBase to a type that is no +// alias, or on a cyclic chain to the first type the walk meets twice. One +// newAliasTargets builds has settled every alias, so reading it writes nothing +// and is safe for concurrent use. +type aliasTargets struct { + types ir.TypeRegistry + index *ir.AliasChainIndex +} -// newAliasTargets resolves every alias scalar of types. A walk from a scalar -// stops at a type already resolved, at one that is no alias, or at one on its -// own path, which closes a cycle; each type it passed is then settled. So a -// later walk finds a type an earlier one left in walked resolved first. +// newAliasTargets settles the chain of every alias scalar of types. func newAliasTargets(types ir.TypeRegistry) aliasTargets { - a := aliasTargets{} - walked := map[ir.TypeID]int{} // each type's position on the walk that met it - var path []ir.TypeID + aliases := lazyAliasTargets(types) for id := range types { - path = path[:0] - for cur := id; ; { - if typeID, done := a[cur]; done { - a.settle(path, typeID) - break - } - if at, cyclic := walked[cur]; cyclic { - a.settleCycle(path, at) - break - } - base, alias := ir.AliasBase(types, cur) - if !alias { - a.settle(path, cur) - break - } - walked[cur] = len(path) - path = append(path, cur) - cur = base + if _, alias := ir.AliasBase(types, id); alias { + aliases.index.End(id) } } - return a + return aliases } -// settle records target for every scalar on path. -func (a aliasTargets) settle(path []ir.TypeID, target ir.TypeID) { - for _, id := range path { - a[id] = target - } -} - -// settleCycle records the scalars of a path whose last one names path[at] -// again. Each scalar on the cycle is the first type its own walk meets twice, -// so it stands for itself; each before the cycle meets path[at] twice first. -func (a aliasTargets) settleCycle(path []ir.TypeID, at int) { - a.settle(path[:at], path[at]) - for _, id := range path[at:] { - a[id] = id - } +// lazyAliasTargets reads the chains of types as it is asked, each once, writing +// to its index, so it is not safe for concurrent use. +func lazyAliasTargets(types ir.TypeRegistry) aliasTargets { + return aliasTargets{types: types, index: ir.NewAliasChainIndex(types.Lookup)} } -// target returns the type id stands for, which is id itself when it names no -// alias scalar. +// target returns the type id names, which is id itself when it names no alias +// scalar, answered without reading the index, which settled the registry's +// aliases alone. func (a aliasTargets) target(id ir.TypeID) ir.TypeID { - if typeID, ok := a[id]; ok { - return typeID + if _, alias := ir.AliasBase(a.types, id); !alias { + return id } - return id + end, _ := a.index.End(id) + return end } diff --git a/ir/irfacts/components.go b/ir/irfacts/components.go index 1dcc45f4b..a910d5a86 100644 --- a/ir/irfacts/components.go +++ b/ir/irfacts/components.go @@ -7,6 +7,7 @@ import ( "slices" "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/stronglyconnected" ) // Recursive reports whether a value of exactly the type id names can hold, at @@ -34,28 +35,28 @@ type components struct { recursive map[ir.TypeID]bool // types whose shape lies on a cycle } -// newComponents condenses typeGraphValue. A shape lies on a cycle when its +// newComponents condenses typeGraph. A shape lies on a cycle when its // component has another vertex, or it has an edge to itself. -func newComponents(typeGraphValue *typeGraph) *components { - componentsValue := &components{of: make(map[ir.TypeID][]ir.TypeID, len(typeGraphValue.ids)), recursive: map[ir.TypeID]bool{}} - for _, vertices := range newTarjan(typeGraphValue.next).run() { +func newComponents(typeGraph *typeGraph) *components { + components := &components{of: make(map[ir.TypeID][]ir.TypeID, len(typeGraph.ids)), recursive: map[ir.TypeID]bool{}} + for _, vertices := range stronglyconnected.Components(typeGraph.next) { var shapes []int - for _, v := range vertices { - if v%2 == 0 { - shapes = append(shapes, v) + for _, vertex := range vertices { + if vertex%2 == 0 { + shapes = append(shapes, vertex) } } slices.Sort(shapes) // shape order is ID order. members := make([]ir.TypeID, len(shapes)) - for k, v := range shapes { - members[k] = typeGraphValue.typeOf(v) + for k, vertex := range shapes { + members[k] = typeGraph.typeOf(vertex) } - for k, v := range shapes { - componentsValue.of[members[k]] = members - if len(vertices) > 1 || typeGraphValue.loops[v] { - componentsValue.recursive[members[k]] = true + for k, vertex := range shapes { + components.of[members[k]] = members + if len(vertices) > 1 || typeGraph.loops[vertex] { + components.recursive[members[k]] = true } } } - return componentsValue + return components } diff --git a/ir/irfacts/components_test.go b/ir/irfacts/components_test.go index 1437bfa27..6b2536d1a 100644 --- a/ir/irfacts/components_test.go +++ b/ir/irfacts/components_test.go @@ -69,7 +69,7 @@ var notPartFields = map[string]string{ // partWalk is what filling a value of one kind shows of its parts. type partWalk struct { - td ir.TypeDef + typeDef ir.TypeDef want map[string][]ir.TypeID // the parts of the value by role, as the tables read them undecided []string // positions naming a type that no table decides roles map[string]bool // the keys of roles the walk read @@ -80,15 +80,15 @@ type partWalk struct { // name a type, by roles and notFields. func walkParts(t *testing.T, typeKind ir.TypeKind, roles, notFields map[string]string) partWalk { t.Helper() - td, ok := ir.NewTypeDef(typeKind) + typeDef, ok := ir.NewTypeDef(typeKind) require.True(t, ok, "no concrete type for kind %q", typeKind) - irtest.Fill(t, td) - positionWalkValue := &positionWalk{types: notParts, fields: notFields, out: map[ir.TypeID]position{}} - positionWalkValue.walk(reflect.ValueOf(td).Elem(), nil, "") - delete(positionWalkValue.out, td.Common().ID) + irtest.Fill(t, typeDef) + positionWalk := &positionWalk{types: notParts, fields: notFields, out: map[ir.TypeID]position{}} + positionWalk.walk(reflect.ValueOf(typeDef).Elem(), nil, "") + delete(positionWalk.out, typeDef.Common().ID) - out := partWalk{td: td, want: map[string][]ir.TypeID{}, roles: map[string]bool{}, steps: positionWalkValue.read} - for id, at := range positionWalkValue.out { + out := partWalk{typeDef: typeDef, want: map[string][]ir.TypeID{}, roles: map[string]bool{}, steps: positionWalk.read} + for id, at := range positionWalk.out { if at.excluded != "" { continue } @@ -111,14 +111,14 @@ type readKeys struct { } // add records what one walk read. -func (r *readKeys) add(partWalkValue partWalk) { +func (r *readKeys) add(partWalk partWalk) { r.mu.Lock() defer r.mu.Unlock() if r.roles == nil { r.roles, r.steps = map[string]bool{}, map[string]bool{} } - maps.Copy(r.roles, partWalkValue.roles) - maps.Copy(r.steps, partWalkValue.steps) + maps.Copy(r.roles, partWalk.roles) + maps.Copy(r.steps, partWalk.steps) } // TestIndex_EveryKindNamesItsPartsByRole fills every field of each kind and @@ -137,7 +137,7 @@ func TestIndex_EveryKindNamesItsPartsByRole(t *testing.T) { partWalk := walkParts(t, typeKind, partRoles, notPartFields) assert.Empty(t, partWalk.undecided, "these name a type: give each a role in partRoles or say why it is none") read.add(partWalk) - held, composed, alias, args := irfacts.Parts(partWalk.td) + held, composed, alias, args := irfacts.Parts(partWalk.typeDef) got := map[string][]ir.TypeID{"held": held, "composed": composed, "args": args} if alias != "" { got["alias"] = []ir.TypeID{alias} @@ -175,27 +175,27 @@ func TestIndex_SelfContainmentIsRecursive(t *testing.T) { func TestIndex_ReferencesThatAreNoPartAreNotRecursive(t *testing.T) { t.Parallel() self := ir.TypeRef{Target: "x"} - selfValue := &ir.Value{Kind: ir.ValueRefKind, Ref: &ir.ValueRef{Type: "x"}} - for name, td := range map[string]ir.TypeDef{ + selfReference := &ir.Value{Kind: ir.ValueRefKind, Ref: &ir.ValueRef{Type: "x"}} + for name, typeDef := range map[string]ir.TypeDef{ "model discriminator mapping": irtest.ModelOf("x", func(model *ir.Model) { model.Discriminator = &ir.Discriminator{Mapping: map[string]ir.TypeID{"a": "x"}, Default: "x"} }), "union discriminator mapping": &ir.Union{ID: "x", Discriminator: &ir.Discriminator{Mapping: map[string]ir.TypeID{"a": "x"}}}, - "property default": irtest.ModelOf("x", func(model *ir.Model) { model.Properties = []ir.Property{{Default: selfValue}} }), + "property default": irtest.ModelOf("x", func(model *ir.Model) { model.Properties = []ir.Property{{Default: selfReference}} }), "property wire type": irtest.ModelOf("x", func(model *ir.Model) { model.Properties = []ir.Property{{Encoding: &ir.Encoding{WireType: &self}}} }), "field argument": irtest.ModelOf("x", func(model *ir.Model) { model.Properties = []ir.Property{{Args: []ir.Parameter{{Type: self}}}} }), "scalar wire type": &ir.Scalar{ID: "x", Encoding: &ir.Encoding{WireType: &self}}, "list wire type": &ir.List{ID: "x", Encoding: &ir.Encoding{WireType: &self}}, - "literal value": &ir.Literal{ID: "x", Value: *selfValue}, - "example value": &ir.Any{ID: "x", Examples: []ir.Example{{Value: selfValue}}}, + "literal value": &ir.Literal{ID: "x", Value: *selfReference}, + "example value": &ir.Any{ID: "x", Examples: []ir.Example{{Value: selfReference}}}, "template argument": &ir.Any{ID: "x", Instantiation: &ir.TemplateInstantiation{Args: []ir.TemplateArg{{Type: &self}}}}, "availability history": &ir.Any{ID: "x", Availability: &ir.Availability{TypeChangedFrom: []ir.VersionedType{{Type: self}}}}, } { t.Run(name, func(t *testing.T) { t.Parallel() - facts := irfacts.New(irtest.DocOf(td)) + facts := irfacts.New(irtest.DocOf(typeDef)) assert.False(t, facts.Recursive("x"), "the reference names a type without making a value hold one") assert.Equal(t, []ir.TypeID{"x"}, facts.Component("x")) }) @@ -318,11 +318,11 @@ func TestIndex_ComponentIsSortedAndTheCallersOwn(t *testing.T) { // factsLongContainment builds n models, t000000 first, each holding the next // through a property, and the last holding nothing. -func factsLongContainment(n int) *ir.Document { - defs := make([]ir.TypeDef, 0, n) - for i := range n { +func factsLongContainment(count int) *ir.Document { + defs := make([]ir.TypeDef, 0, count) + for i := range count { defs = append(defs, irtest.ModelOf(factsLongID(i), func(model *ir.Model) { - if i+1 < n { + if i+1 < count { model.Properties = []ir.Property{useProperty(factsLongID(i + 1))} } })) diff --git a/ir/irfacts/composition.go b/ir/irfacts/composition.go new file mode 100644 index 000000000..ceddaff21 --- /dev/null +++ b/ir/irfacts/composition.go @@ -0,0 +1,162 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package irfacts + +import ( + "maps" + "slices" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/stronglyconnected" +) + +// CompositionReaches reports whether a path of one edge or more along the +// edges ir.ComposedOf returns leads from from to to, so a type reaches itself +// only along a cycle, and an interface a model implements is no part. It is +// false for an ID the document neither declares nor composes. +func (x *DocumentFacts) CompositionReaches(from, to ir.TypeID) bool { + return x.compositionIndex().reaches(from, to) +} + +// compositionIndex returns the index of composition reach, built once. +func (x *DocumentFacts) compositionIndex() *composition { + x.compositionOnce.Do(func() { x.composition = newComposition(x.registry()) }) + return x.composition +} + +// composition indexes the relation [DocumentFacts.CompositionReaches] answers. +// Its vertices are the types the registry holds and every ID their edges +// name, each type's edges those ir.ComposedOf returns, and each vertex's +// composers are the vertices with an edge to it. +type composition struct { + vertex map[ir.TypeID]int + edges [][]int + composers [][]int + reach *intervals +} + +// newComposition indexes the composition edges of the types in types. +func newComposition(types ir.TypeRegistry) *composition { + ids := slices.Sorted(maps.Keys(types)) + index := &composition{vertex: make(map[ir.TypeID]int, len(ids))} + for _, id := range ids { + index.vertexOf(id) + } + for _, id := range ids { + from := index.vertex[id] + for _, part := range ir.ComposedOf(types[id]) { + to := index.vertexOf(part) + index.edges[from] = append(index.edges[from], to) + } + } + index.composers = make([][]int, len(index.edges)) + for from, out := range index.edges { + for _, to := range out { + index.composers[to] = append(index.composers[to], from) + } + } + index.reach = newIntervals(index.edges) + return index +} + +// vertexOf returns id's vertex, numbering it the first time it is named. +func (c *composition) vertexOf(id ir.TypeID) int { + if index, named := c.vertex[id]; named { + return index + } + index := len(c.edges) + c.vertex[id] = index + c.edges = append(c.edges, nil) + return index +} + +// reaches answers [DocumentFacts.CompositionReaches] from the intervals, and +// searches the pair they leave open (searchBetween). +func (c *composition) reaches(from, to ir.TypeID) bool { + fromIndex, fromNamed := c.vertex[from] + t, toNamed := c.vertex[to] + if !fromNamed || !toNamed { + return false + } + if reached, settled := c.reach.below(fromIndex, t); settled { + return reached + } + return c.searchBetween(fromIndex, t) +} + +// searchBetween searches a pair the intervals leave open from both ends in +// turn, down from source along the edges and up from destination along the +// composers, until the sides meet or either runs out: a pair where source +// reaches few vertices, or few reach destination, costs that few steps. +func (c *composition) searchBetween(source, destination int) bool { + down := frontier{met: map[int]bool{source: true}, stack: []int{source}} + up := frontier{met: map[int]bool{destination: true}, stack: []int{destination}} + reachesDestination := func(vertex int) (bool, bool) { return c.reach.below(vertex, destination) } + reachedFromSource := func(vertex int) (bool, bool) { return c.reach.below(source, vertex) } + for len(down.stack) > 0 && len(up.stack) > 0 { + if down.step(c.edges, up.met, reachesDestination) || up.step(c.composers, down.met, reachedFromSource) { + return true + } + } + return false +} + +// frontier is one side of searchBetween: the vertices it has met, each on its +// side of a path, and those it has yet to step from. +type frontier struct { + met map[int]bool + stack []int +} + +// step steps from the last vertex queued to its neighbours along adjacency, +// and reports true at one the other side met or onPath settles as on a path. +func (s *frontier) step(adjacency [][]int, other map[int]bool, onPath func(int) (reached, settled bool)) bool { + vertex := s.stack[len(s.stack)-1] + s.stack = s.stack[:len(s.stack)-1] + for _, neighbour := range adjacency[vertex] { + if other[neighbour] { + return true + } + reached, settled := onPath(neighbour) + if settled && reached { + return true + } + if settled || s.met[neighbour] { + continue + } + s.met[neighbour] = true + s.stack = append(s.stack, neighbour) + } + return false +} + +// CompositionStronglyConnectedComponents returns the strongly connected +// components of the composition among ids, in Tarjan's order: a component +// after every one its edges reach. An edge is one ir.ComposedOf returns, read +// through alias scalars (aliasTargets), and leads nowhere where the type it +// names is not among ids. +func CompositionStronglyConnectedComponents(types ir.TypeRegistry, ids []ir.TypeID) [][]ir.TypeID { + vertex := make(map[ir.TypeID]int, len(ids)) + for i, id := range ids { + vertex[id] = i + } + aliases := lazyAliasTargets(types) + edges := make([][]int, len(ids)) + for i, id := range ids { + for _, part := range ir.ComposedOf(types[id]) { + if to, among := vertex[aliases.target(part)]; among { + edges[i] = append(edges[i], to) + } + } + } + components := stronglyconnected.Components(edges) + out := make([][]ir.TypeID, len(components)) + for component, members := range components { + out[component] = make([]ir.TypeID, len(members)) + for k, vertex := range members { + out[component][k] = ids[vertex] + } + } + return out +} diff --git a/ir/irfacts/composition_aliases_test.go b/ir/irfacts/composition_aliases_test.go new file mode 100644 index 000000000..b4e2b2373 --- /dev/null +++ b/ir/irfacts/composition_aliases_test.go @@ -0,0 +1,40 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package irfacts_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" + "github.com/dexpace/morphic/ir/irtest" +) + +// TestCompositionStronglyConnectedComponents_ReadsAChainManyEdgesNameOnce pins +// the aliases outside the IDs given: a chain two models name leads both to the +// model at its end, however it is first entered, and a cycle of aliases leads +// nowhere, so the model composing it is alone. +func TestCompositionStronglyConnectedComponents_ReadsAChainManyEdgesNameOnce(t *testing.T) { + t.Parallel() + doc := irtest.DocOf( + irtest.ModelOf("type/A", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/top"} }), + irtest.ModelOf("type/B", func(model *ir.Model) { model.Mixins = irtest.RefsTo("type/middle") }), + irtest.ScalarOf("type/top", "type/middle"), + irtest.ScalarOf("type/middle", "type/C"), + irtest.ModelOf("type/C", func(model *ir.Model) { model.Mixins = irtest.RefsTo("type/A", "type/B") }), + irtest.ModelOf("type/D", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/loop1"} }), + irtest.ScalarOf("type/loop1", "type/loop2"), + irtest.ScalarOf("type/loop2", "type/loop1"), + ) + for _, ids := range [][]ir.TypeID{ + {"type/A", "type/B", "type/C", "type/D"}, + {"type/D", "type/C", "type/B", "type/A"}, + } { + components := irfacts.CompositionStronglyConnectedComponents(doc.Types, ids) + + assert.Equal(t, [][]ir.TypeID{{"type/A", "type/B", "type/C"}, {"type/D"}}, sortedComponents(components), "ids %v", ids) + } +} diff --git a/ir/irfacts/composition_test.go b/ir/irfacts/composition_test.go new file mode 100644 index 000000000..708d60818 --- /dev/null +++ b/ir/irfacts/composition_test.go @@ -0,0 +1,330 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package irfacts_test + +import ( + "fmt" + "math/rand/v2" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" + "github.com/dexpace/morphic/ir/irtest" +) + +// compositionEdges is what a type composes, read here apart from +// ir.ComposedOf so the oracle shares no code with the index: a model's Base and +// Mixins, and an alias scalar's Base. Implements is no edge. +func compositionEdges(typeDef ir.TypeDef) []ir.TypeID { + var out []ir.TypeID + switch node := typeDef.(type) { + case *ir.Model: + if node == nil { + return nil + } + if node.Base != nil { + out = append(out, node.Base.Target) + } + for _, mixin := range node.Mixins { + out = append(out, mixin.Target) + } + case *ir.Scalar: + if node != nil && node.Base != nil { + out = append(out, node.Base.Target) + } + default: + } + return out +} + +// composesByWalk is the reference answer: whether a path of one edge or more +// leads from from to to. +func composesByWalk(types ir.TypeRegistry, from, to ir.TypeID) bool { + seen := map[ir.TypeID]bool{} + queue := compositionEdges(types[from]) + for len(queue) > 0 { + next := queue[len(queue)-1] + queue = queue[:len(queue)-1] + if next == to { + return true + } + if !seen[next] { + seen[next] = true + queue = append(queue, compositionEdges(types[next])...) + } + } + return false +} + +// compositionRandom builds a registry of up to thirty types: models naming any +// type, an undeclared ID or an alias as Base, Implements and Mixins; alias +// scalars in chains and cycles; opaque scalars; enums; and one typed nil. It +// returns the document and every declared type ID. +func compositionRandom(rng *rand.Rand) (*ir.Document, []ir.TypeID) { + n := 1 + rng.IntN(30) + declared := make([]ir.TypeID, 0, n+1) + for i := range n { + declared = append(declared, ir.TypeID(fmt.Sprintf("type/t%02d", i))) + } + targets := append(slices.Clone(declared), "type/ghost", "type/nil") + pick := func() ir.TypeID { return targets[rng.IntN(len(targets))] } + doc := irtest.DocOf() + for _, id := range declared { + switch r := rng.IntN(10); { + case r < 6: + model := irtest.ModelOf(id, nil) + if rng.IntN(2) == 0 { + model.Base = &ir.TypeRef{Target: pick()} + } + for range rng.IntN(2) { + model.Implements = append(model.Implements, ir.TypeRef{Target: pick()}) + } + for range rng.IntN(3) { + model.Mixins = append(model.Mixins, ir.TypeRef{Target: pick()}) + } + doc.Types[id] = model + case r < 8: + doc.Types[id] = irtest.ScalarOf(id, pick()) + case r == 8: + doc.Types[id] = irtest.ScalarOf(id, "") + default: + doc.Types[id] = &ir.Enum{ID: id} + } + } + doc.Types["type/nil"] = (*ir.Model)(nil) + return doc, append(declared, "type/nil") +} + +// TestDocumentFacts_CompositionReachesAsTheReferenceWalkDoes holds the reach +// index to a walk over Base, Mixins and an alias's Base on random registries, +// cycles and dangling references among them: every pair of declared types +// answers alike, a type reaching itself only along a cycle. +func TestDocumentFacts_CompositionReachesAsTheReferenceWalkDoes(t *testing.T) { + t.Parallel() + var reached, cyclic int + for seed := range uint64(300) { + doc, ids := compositionRandom(rand.New(rand.NewPCG(seed, seed+11))) + facts := irfacts.New(doc) + for _, from := range ids { + for _, to := range ids { + want := composesByWalk(doc.Types, from, to) + require.Equal(t, want, facts.CompositionReaches(from, to), "seed %d: CompositionReaches(%q, %q)", seed, from, to) + if want { + reached++ + } + if want && from == to { + cyclic++ + } + } + } + } + require.Positive(t, reached, "no random registry composed anything, so this compared nothing") + require.Positive(t, cyclic, "no random registry held a cycle, so reaching oneself went unasked") +} + +// TestDocumentFacts_CompositionReachesNoInterfaceAndNothingOutside pins the +// edges the index reads: an interface a model implements is no part of its +// composition, and an ID the document does not hold reaches nothing. +func TestDocumentFacts_CompositionReachesNoInterfaceAndNothingOutside(t *testing.T) { + t.Parallel() + doc := irtest.DocOf( + irtest.ModelOf("type/m", func(model *ir.Model) { + model.Implements = irtest.RefsTo("type/i") + model.Mixins = irtest.RefsTo("type/alias") + }), + irtest.ModelOf("type/i", nil), + irtest.ScalarOf("type/alias", "type/end"), + irtest.ModelOf("type/end", nil), + ) + facts := irfacts.New(doc) + + assert.False(t, facts.CompositionReaches("type/m", "type/i"), "an interface is no part") + assert.True(t, facts.CompositionReaches("type/m", "type/alias")) + assert.True(t, facts.CompositionReaches("type/m", "type/end"), "through the alias") + assert.False(t, facts.CompositionReaches("type/end", "type/m")) + assert.False(t, facts.CompositionReaches("type/m", "type/m"), "no cycle leads back") + assert.False(t, facts.CompositionReaches("type/ghost", "type/end"), "an ID outside the index") +} + +// TestDocumentFacts_CompositionReachesAnyDepth pins that the index keeps no +// walk's cap: a model 1,000 levels above a base and an alias 1,000 links above +// a model each reach the far end, where the walk it replaces stopped at 64. +func TestDocumentFacts_CompositionReachesAnyDepth(t *testing.T) { + t.Parallel() + doc := irtest.DocOf(irtest.ModelOf("type/C0", nil), irtest.ModelOf("type/end", nil)) + for i := 1; i <= 1000; i++ { + id := ir.TypeID(fmt.Sprintf("type/C%d", i)) + doc.Types[id] = irtest.ModelOf(id, func(model *ir.Model) { + model.Base = &ir.TypeRef{Target: ir.TypeID(fmt.Sprintf("type/C%d", i-1))} + }) + } + below := ir.TypeID("type/end") + for i := range 1000 { + id := ir.TypeID(fmt.Sprintf("type/S%d", i)) + doc.Types[id] = irtest.ScalarOf(id, below) + below = id + } + facts := irfacts.New(doc) + + for _, depth := range []int{64, 65, 1000} { + assert.True(t, facts.CompositionReaches(ir.TypeID(fmt.Sprintf("type/C%d", depth)), "type/C0"), "a hierarchy %d deep", depth) + assert.True(t, facts.CompositionReaches(ir.TypeID(fmt.Sprintf("type/S%d", depth-1)), "type/end"), "%d aliases", depth) + } + assert.False(t, facts.CompositionReaches("type/C0", "type/C1000")) +} + +// componentOf indexes each ID by the component holding it. +func componentOf(components [][]ir.TypeID) map[ir.TypeID]int { + out := map[ir.TypeID]int{} + for k, component := range components { + for _, id := range component { + out[id] = k + } + } + return out +} + +// sortedComponents is components with each one's IDs sorted and the +// components sorted by their first ID: the partition, order apart. +func sortedComponents(components [][]ir.TypeID) [][]ir.TypeID { + out := make([][]ir.TypeID, 0, len(components)) + for _, component := range components { + out = append(out, slices.Sorted(slices.Values(component))) + } + slices.SortFunc(out, slices.Compare[[]ir.TypeID]) + return out +} + +// assertCondensationOrder holds components to Tarjan's order: every ID of ids +// in exactly one, and a component after every other one an edge among ids +// leads to. +func assertCondensationOrder(t *testing.T, types ir.TypeRegistry, ids []ir.TypeID, components [][]ir.TypeID, msg string) { + t.Helper() + at := componentOf(components) + var count int + for _, component := range components { + count += len(component) + } + require.Equal(t, len(ids), count, "%s: each ID in one component", msg) + for _, id := range ids { + require.Contains(t, at, id, msg) + for _, part := range compositionEdges(types[id]) { + if partAt, among := at[part]; among { + assert.LessOrEqual(t, partAt, at[id], "%s: %s composes %s, whose component closes first", msg, id, part) + } + } + } +} + +// TestCompositionStronglyConnectedComponents_CondensesTheNotedModels pins the +// condensation a settlement takes in order: a two-model cycle is one +// component, a model composing itself one of its own, and each component +// closes after every one it composes, whatever order the IDs are given in. +func TestCompositionStronglyConnectedComponents_CondensesTheNotedModels(t *testing.T) { + t.Parallel() + doc := irtest.DocOf( + irtest.ModelOf("type/A", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/B"} }), + irtest.ModelOf("type/B", func(model *ir.Model) { model.Mixins = irtest.RefsTo("type/C") }), + irtest.ModelOf("type/C", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/B"} }), + irtest.ModelOf("type/D", func(model *ir.Model) { model.Mixins = irtest.RefsTo("type/A", "type/E") }), + irtest.ModelOf("type/E", nil), + irtest.ModelOf("type/S", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/S"} }), + ) + want := [][]ir.TypeID{{"type/A"}, {"type/B", "type/C"}, {"type/D"}, {"type/E"}, {"type/S"}} + ids := []ir.TypeID{"type/A", "type/B", "type/C", "type/D", "type/E", "type/S"} + reversed := slices.Clone(ids) + slices.Reverse(reversed) + for _, order := range [][]ir.TypeID{ids, reversed} { + components := irfacts.CompositionStronglyConnectedComponents(doc.Types, order) + + assert.Equal(t, want, sortedComponents(components), "ids %v", order) + assertCondensationOrder(t, doc.Types, order, components, fmt.Sprintf("ids %v", order)) + } +} + +// TestCompositionStronglyConnectedComponents_HoldsToMutualReach holds the +// components to their definition on random registries of models naming one +// another: two IDs share a component exactly where each reaches the other. +func TestCompositionStronglyConnectedComponents_HoldsToMutualReach(t *testing.T) { + t.Parallel() + var cycles int + for seed := range uint64(300) { + rng := rand.New(rand.NewPCG(seed, seed+13)) + n := 1 + rng.IntN(20) + ids := make([]ir.TypeID, n) + for i := range ids { + ids[i] = ir.TypeID(fmt.Sprintf("type/m%02d", i)) + } + doc := irtest.DocOf() + for _, id := range ids { + doc.Types[id] = irtest.ModelOf(id, func(model *ir.Model) { + if rng.IntN(3) == 0 { + model.Base = &ir.TypeRef{Target: ids[rng.IntN(n)]} + } + for range rng.IntN(2) { + model.Mixins = append(model.Mixins, ir.TypeRef{Target: ids[rng.IntN(n)]}) + } + }) + } + + components := irfacts.CompositionStronglyConnectedComponents(doc.Types, ids) + + assertCondensationOrder(t, doc.Types, ids, components, fmt.Sprintf("seed %d", seed)) + at := componentOf(components) + for _, a := range ids { + for _, b := range ids { + mutual := a == b || (composesByWalk(doc.Types, a, b) && composesByWalk(doc.Types, b, a)) + require.Equal(t, mutual, at[a] == at[b], "seed %d: %s and %s", seed, a, b) + if mutual && a != b { + cycles++ + } + } + } + } + require.Positive(t, cycles, "no random registry held a cycle of two models") +} + +// TestCompositionStronglyConnectedComponents_ReadsThroughAliasesAlone pins the +// edges among the IDs given: a model composing another through an alias +// scalar the IDs leave out composes it, as the settlement's own reading of a +// part does, while a model outside the IDs leads nowhere. +func TestCompositionStronglyConnectedComponents_ReadsThroughAliasesAlone(t *testing.T) { + t.Parallel() + doc := irtest.DocOf( + irtest.ModelOf("type/A", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/alias"} }), + irtest.ScalarOf("type/alias", "type/B"), + irtest.ModelOf("type/B", func(model *ir.Model) { model.Mixins = irtest.RefsTo("type/A") }), + irtest.ModelOf("type/C", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/outside"} }), + irtest.ModelOf("type/outside", func(model *ir.Model) { model.Base = &ir.TypeRef{Target: "type/C"} }), + ) + + components := irfacts.CompositionStronglyConnectedComponents(doc.Types, []ir.TypeID{"type/A", "type/B", "type/C"}) + + assert.Equal(t, [][]ir.TypeID{{"type/A", "type/B"}, {"type/C"}}, sortedComponents(components)) +} + +// TestCompositionStronglyConnectedComponents_CondensesALongCycle pins the +// explicit stack: a cycle of 20,000 models, as long as a document may write, +// is one component, found without exhausting the goroutine stack. +func TestCompositionStronglyConnectedComponents_CondensesALongCycle(t *testing.T) { + t.Parallel() + const n = 20_000 + doc := irtest.DocOf() + ids := make([]ir.TypeID, n) + for i := range ids { + ids[i] = ir.TypeID(fmt.Sprintf("type/m%05d", i)) + } + for i, id := range ids { + doc.Types[id] = irtest.ModelOf(id, func(model *ir.Model) { model.Base = &ir.TypeRef{Target: ids[(i+1)%n]} }) + } + + components := irfacts.CompositionStronglyConnectedComponents(doc.Types, ids) + + require.Len(t, components, 1) + assert.Len(t, components[0], n) +} diff --git a/ir/irfacts/correlation.go b/ir/irfacts/correlation.go index c9f754782..64e298cb1 100644 --- a/ir/irfacts/correlation.go +++ b/ir/irfacts/correlation.go @@ -77,14 +77,14 @@ func newCorrelations(doc *ir.Document) *correlations { if doc == nil { return out } - correlatorValue := &correlator{ + correlator := &correlator{ doc: doc, settled: map[string]bool{}, out: out, inline: inlineConjuncts(doc.Types), operations: map[ir.OperationID]*ir.Operation{}, } - correlatorValue.seedLayer() - correlatorValue.seedTypes() - for correlatorValue.pending.Len() > 0 { - correlatorValue.settle(correlatorValue.popLeast()) + correlator.seedLayer() + correlator.seedTypes() + for correlator.pending.Len() > 0 { + correlator.settle(correlator.popLeast()) } return out } @@ -157,8 +157,8 @@ func (h candidateHeap) Less(i, j int) bool { func (h candidateHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *candidateHeap) Push(v any) { - cand, _ := v.(candidate) +func (h *candidateHeap) Push(item any) { + cand, _ := item.(candidate) *h = append(*h, cand) } diff --git a/ir/irfacts/correlation_layer.go b/ir/irfacts/correlation_layer.go index 04751dd70..7dde420ed 100644 --- a/ir/irfacts/correlation_layer.go +++ b/ir/irfacts/correlation_layer.go @@ -17,9 +17,9 @@ func (c *correlator) seedLayer() { operations := c.seedGroups() for i := range c.doc.Services { svc := &c.doc.Services[i] - c.offer(named("service", svc.Name), string(svc.ID), func(correlatorValue *correlator, key string) { - correlatorValue.errorCases(key, svc.CommonErrors) - correlatorValue.servers(key, svc.Servers) + c.offer(named("service", svc.Name), string(svc.ID), func(correlator *correlator, key string) { + correlator.errorCases(key, svc.CommonErrors) + correlator.servers(key, svc.Servers) }) } c.partHeaders = indexPartHeaders(c.doc.Services, operations) @@ -37,8 +37,8 @@ func (c *correlator) seedLayer() { } for id, scheme := range c.doc.Auth { credentials := scheme.Credentials - c.offer(named("auth", scheme.Name), string(id), func(correlatorValue *correlator, key string) { - correlatorValue.ref(part(key, "credentials"), credentials) + c.offer(named("auth", scheme.Name), string(id), func(correlator *correlator, key string) { + correlator.ref(part(key, "credentials"), credentials) }) } } @@ -82,23 +82,23 @@ func operationKey(operation *ir.Operation, routes map[string]int) string { } // routeKey is operation's method and route, each variable written {}, a -// webhook's event name standing for the route, and "" when no HTTP binding -// places operation. +// webhook's event name naming the route, and "" when no HTTP binding places +// operation. func routeKey(operation *ir.Operation) string { if len(operation.Bindings.HTTP) == 0 { return "" } - b := &operation.Bindings.HTTP[0] - if b.Inbound == ir.HTTPInboundWebhook { - return segment("webhook", b.Method+" "+b.WebhookName) + binding := &operation.Bindings.HTTP[0] + if binding.Inbound == ir.HTTPInboundWebhook { + return segment("webhook", binding.Method+" "+binding.WebhookName) } - return segment("route", b.Method+" "+eraseVariables(b.URITemplate)) + return segment("route", binding.Method+" "+eraseVariables(binding.URITemplate)) } // eraseVariables writes each expression of an RFC 6570 template as {}, so a // route keeps its key when a variable is renamed. func eraseVariables(template string) string { - var b strings.Builder + var builder strings.Builder for { open := strings.IndexByte(template, '{') if open < 0 { @@ -108,18 +108,18 @@ func eraseVariables(template string) string { if end < 0 { break } - b.WriteString(template[:open]) - b.WriteString("{}") + builder.WriteString(template[:open]) + builder.WriteString("{}") template = template[open+end+1:] } - b.WriteString(template) - return b.String() + builder.WriteString(template) + return builder.String() } // offerOperation offers key to operation, and, when operation takes it, keys // what operation names. func (c *correlator) offerOperation(key string, operation *ir.Operation) { - c.offer(key, string(operation.ID), func(correlatorValue *correlator, key string) { correlatorValue.operation(key, operation) }) + c.offer(key, string(operation.ID), func(correlator *correlator, key string) { correlator.operation(key, operation) }) } // operation offers the keys of what operation names: its parameters, request, @@ -186,8 +186,8 @@ type callbackTarget struct { // document declares with an HTTP binding, in the order operation lists them. func (c *correlator) callbackTargets(operation *ir.Operation) []callbackTarget { var targets []callbackTarget - for _, b := range operation.Bindings.HTTP { - for _, cb := range b.Callbacks { + for _, binding := range operation.Bindings.HTTP { + for _, cb := range binding.Callbacks { for _, id := range cb.Operations { target, ok := c.operations[id] if !ok || len(target.Bindings.HTTP) == 0 { @@ -207,9 +207,9 @@ func (c *correlator) callbackTargets(operation *ir.Operation) []callbackTarget { func (c *correlator) params(key string, operation *ir.Operation) { for i := range operation.Params { parameter := &operation.Params[i] - c.offer(paramKey(key, operation, parameter), string(parameter.ID), func(correlatorValue *correlator, key string) { - correlatorValue.ref(part(key, "schema"), ¶meter.Type) - correlatorValue.decoded(key, parameter.Encoding) + c.offer(paramKey(key, operation, parameter), string(parameter.ID), func(correlator *correlator, key string) { + correlator.ref(part(key, "schema"), ¶meter.Type) + correlator.decoded(key, parameter.Encoding) }) } } @@ -221,8 +221,8 @@ func (c *correlator) params(key string, operation *ir.Operation) { // by where it travels and its prefix, in a segment of another kind than a wire // name's (docs/ir/http-binding.md#prefix-bindings). func paramKey(key string, operation *ir.Operation, parameter *ir.Parameter) string { - for _, b := range operation.Bindings.HTTP { - for _, pb := range b.ParamBindings { + for _, binding := range operation.Bindings.HTTP { + for _, pb := range binding.ParamBindings { if pb.Param != parameter.ID || pb.Location == ir.HTTPLocationHost { continue } @@ -367,9 +367,9 @@ func indexPartHeaders(services []ir.Service, operations []*ir.Operation) map[ir. func (c *correlator) headers(key string, hs []ir.Header) { for i := range hs { property := &hs[i].Property - c.offer(headerKey(key, &hs[i]), string(property.ID), func(correlatorValue *correlator, key string) { - correlatorValue.ref(part(key, "type"), &property.Type) - correlatorValue.decoded(key, property.Encoding) + c.offer(headerKey(key, &hs[i]), string(property.ID), func(correlator *correlator, key string) { + correlator.ref(part(key, "type"), &property.Type) + correlator.decoded(key, property.Encoding) }) } } diff --git a/ir/irfacts/correlation_types.go b/ir/irfacts/correlation_types.go index ca071a8aa..d03179fc1 100644 --- a/ir/irfacts/correlation_types.go +++ b/ir/irfacts/correlation_types.go @@ -15,20 +15,20 @@ import ( // primitive its kind. An anonymous type is keyed only by the positions that // name it. func (c *correlator) seedTypes() { - for id, td := range c.doc.Types { - if ir.IsNilTypeDef(td) { + for id, typeDef := range c.doc.Types { + if ir.IsNilTypeDef(typeDef) { continue } - if primitive, ok := td.(*ir.Primitive); ok { - c.offerType(segment("prim", string(primitive.PrimitiveKind)), id, td) + if primitive, ok := typeDef.(*ir.Primitive); ok { + c.offerType(segment("prim", string(primitive.PrimitiveKind)), id, typeDef) continue } - common := td.Common() + common := typeDef.Common() if common.Anonymous { continue } if key := named("type", common.Name); key != "" { - c.offerType(namespaced(common.Namespace, key), id, td) + c.offerType(namespaced(common.Namespace, key), id, typeDef) } } } @@ -41,10 +41,10 @@ func namespaced(namespace []string, key string) string { return key } -// offerType offers key to the type id, and, when it takes it, keys what td +// offerType offers key to the type id, and, when it takes it, keys what typeDef // names. -func (c *correlator) offerType(key string, id ir.TypeID, td ir.TypeDef) { - c.offer(key, string(id), func(correlatorValue *correlator, key string) { correlatorValue.typeParts(key, td) }) +func (c *correlator) offerType(key string, id ir.TypeID, typeDef ir.TypeDef) { + c.offer(key, string(id), func(correlator *correlator, key string) { correlator.typeParts(key, typeDef) }) } // ref offers key to the type ref names, when the type is anonymous: a named @@ -53,18 +53,18 @@ func (c *correlator) ref(key string, ref *ir.TypeRef) { if ref == nil { return } - td, ok := c.doc.Types[ref.Target] - if !ok || ir.IsNilTypeDef(td) || !td.Common().Anonymous { + typeDef, ok := c.doc.Types[ref.Target] + if !ok || ir.IsNilTypeDef(typeDef) || !typeDef.Common().Anonymous { return } - c.offerType(key, ref.Target, td) + c.offerType(key, ref.Target, typeDef) } -// typeParts offers the keys of what td, keyed key, names: a model's members, a -// union's tagged or named variants, an enum's members, a container's elements -// and a scalar's base, and what an encoding decodes to. -func (c *correlator) typeParts(key string, td ir.TypeDef) { - switch t := td.(type) { +// typeParts offers the keys of what typeDef, keyed key, names: a model's +// members, a union's tagged or named variants, an enum's members, a container's +// elements and a scalar's base, and what an encoding decodes to. +func (c *correlator) typeParts(key string, typeDef ir.TypeDef) { + switch t := typeDef.(type) { case *ir.Model: if !c.inline[t.ID] { c.model(key, t) @@ -153,8 +153,8 @@ func composed(model *ir.Model) []ir.TypeRef { // allOf member written in place, whose members are the composing model's. func inlineConjuncts(types ir.TypeRegistry) map[ir.TypeID]bool { inline := map[ir.TypeID]bool{} - for _, td := range types { - model, ok := td.(*ir.Model) + for _, typeDef := range types { + model, ok := typeDef.(*ir.Model) if !ok || model == nil { continue } @@ -188,13 +188,13 @@ func (c *correlator) members(key string, enum *ir.Enum) { // property's type, what its encoding decodes to, the headers of a multipart // part encoding it and its field arguments. func (c *correlator) property(key string, property *ir.Property) { - c.offer(child(key, "prop", property.EffectiveWireName()), string(property.ID), func(correlatorValue *correlator, key string) { - correlatorValue.ref(part(key, "type"), &property.Type) - correlatorValue.decoded(key, property.Encoding) - correlatorValue.headers(key, correlatorValue.partHeaders[property.ID]) + c.offer(child(key, "prop", property.EffectiveWireName()), string(property.ID), func(inner *correlator, key string) { + inner.ref(part(key, "type"), &property.Type) + inner.decoded(key, property.Encoding) + inner.headers(key, inner.partHeaders[property.ID]) for i := range property.Args { arg := &property.Args[i] - correlatorValue.offer(child(key, "arg", arg.Name.Source), string(arg.ID), func(otherCorrelator *correlator, key string) { + inner.offer(child(key, "arg", arg.Name.Source), string(arg.ID), func(otherCorrelator *correlator, key string) { otherCorrelator.ref(part(key, "schema"), &arg.Type) otherCorrelator.decoded(key, arg.Encoding) }) diff --git a/ir/irfacts/doc.go b/ir/irfacts/doc.go index 6d1f80c50..3e1a1f1ed 100644 --- a/ir/irfacts/doc.go +++ b/ir/irfacts/doc.go @@ -2,13 +2,14 @@ // Licensed under the MIT License. See LICENSE in the repository root for details. // Package irfacts derives what an ir.Document implies and does not state: -// subtypes, exposed properties, usage, recursion and each entity's name across -// revisions (docs/ir/derived-facts.md). A [DocumentFacts] builds each index the -// first time a fact needs it, walking a relation instead while that costs less, -// and writes nothing back, so no pass orders the derivations and none goes -// stale after a transform. +// subtypes, exposed properties, composition reach, usage, recursion and each +// entity's name across revisions (docs/ir/derived-facts.md). A [DocumentFacts] +// builds each index the first time a fact needs it, walking a relation instead +// while that costs less, and writes nothing back, so no pass orders the +// derivations and none goes stale after a transform. // // The relations it indexes are defined in ir: [DocumentFacts.IsSubtype] and // [DocumentFacts.Exposes] answer what ir.IsSubtype and ir.ExposedProperties -// answer, for many questions at once. It imports only ir. +// answer, for many questions at once. It imports only ir and +// stronglyconnected. package irfacts diff --git a/ir/irfacts/export_test.go b/ir/irfacts/export_test.go index 0ea67852b..db1d5e3e6 100644 --- a/ir/irfacts/export_test.go +++ b/ir/irfacts/export_test.go @@ -31,13 +31,22 @@ func (x *DocumentFacts) WalkStepsLeft() (subtype, exposure int64) { } // AliasTargetsOf exposes the registry-wide alias index to the external tests: -// what each alias scalar of types stands for. -func AliasTargetsOf(types ir.TypeRegistry) map[ir.TypeID]ir.TypeID { return newAliasTargets(types) } +// what each alias scalar of types names. +func AliasTargetsOf(types ir.TypeRegistry) map[ir.TypeID]ir.TypeID { + targets := newAliasTargets(types) + out := map[ir.TypeID]ir.TypeID{} + for id := range types { + if _, alias := ir.AliasBase(types, id); alias { + out[id] = targets.target(id) + } + } + return out +} // Parts exposes how the type graph reads td: the types it holds, composes, // aliases and names as field arguments. -func Parts(td ir.TypeDef) (held, composed []ir.TypeID, alias ir.TypeID, args []ir.TypeID) { - var typePartsValue typeParts - typePartsValue.read(td) - return typePartsValue.held, typePartsValue.composed, typePartsValue.alias, typePartsValue.args +func Parts(typeDef ir.TypeDef) (held, composed []ir.TypeID, alias ir.TypeID, args []ir.TypeID) { + var typeParts typeParts + typeParts.read(typeDef) + return typeParts.held, typeParts.composed, typeParts.alias, typeParts.args } diff --git a/ir/irfacts/exposure.go b/ir/irfacts/exposure.go index be6178622..cf65edc18 100644 --- a/ir/irfacts/exposure.go +++ b/ir/irfacts/exposure.go @@ -49,30 +49,30 @@ type exposure struct { // newExposure indexes the parts of the types in types. func newExposure(types ir.TypeRegistry) *exposure { ids := slices.Sorted(maps.Keys(types)) - exposureValue := &exposure{vertex: make(map[ir.TypeID]int, len(ids)), owner: map[ir.PropertyID]int{}} + exposure := &exposure{vertex: make(map[ir.TypeID]int, len(ids)), owner: map[ir.PropertyID]int{}} for i, id := range ids { - exposureValue.vertex[id] = i + exposure.vertex[id] = i } edges := pairsOf[int](mostSources(types)) var sources []ir.TypeID for i, id := range ids { - sources = exposureValue.read(sources[:0], i, types[id]) + sources = exposure.read(sources[:0], i, types[id]) for _, source := range sources { - if v, declared := exposureValue.vertex[source]; declared { - edges.add(i, v) + if index, declared := exposure.vertex[source]; declared { + edges.add(i, index) } } } - exposureValue.reach = newIntervals(edges.grouped(len(ids))) - return exposureValue + exposure.reach = newIntervals(edges.grouped(len(ids))) + return exposure } // mostSources returns how many part sources the types of types name at most: // a model's Base, Implements and Mixins entries and an alias scalar's Base. func mostSources(types ir.TypeRegistry) int { most := 0 - for _, td := range types { - switch t := td.(type) { + for _, typeDef := range types { + switch t := typeDef.(type) { case *ir.Model: if t != nil { most += 1 + len(t.Implements) + len(t.Mixins) @@ -86,15 +86,15 @@ func mostSources(types ir.TypeRegistry) int { return most } -// read records the properties td declares as vertex i's, and appends to dst the -// types the rest of its parts come from, as ir.ExposedProperties reads them: a -// model's Base, Implements and Mixins and an alias scalar's Base. A typed nil -// and every other kind have none. -func (e *exposure) read(dst []ir.TypeID, i int, td ir.TypeDef) []ir.TypeID { - if ir.IsNilTypeDef(td) { +// read records the properties typeDef declares as vertex i's, and appends to +// dst the types the rest of its parts come from, as ir.ExposedProperties reads +// them: a model's Base, Implements and Mixins and an alias scalar's Base. A +// typed nil and every other kind have none. +func (e *exposure) read(dst []ir.TypeID, i int, typeDef ir.TypeDef) []ir.TypeID { + if ir.IsNilTypeDef(typeDef) { return dst } - switch t := td.(type) { + switch t := typeDef.(type) { case *ir.Model: for j := range t.Properties { e.own(t.Properties[j].ID, i) @@ -132,16 +132,16 @@ func (e *exposure) own(property ir.PropertyID, i int) { // false when they cannot: several models declare property, or the intervals // leave open whether id reaches the one that does. func (e *exposure) exposes(id ir.TypeID, property ir.PropertyID) (exposed, settled bool) { - v, declared := e.vertex[id] + index, declared := e.vertex[id] owner, owned := e.owner[property] switch { case !declared || !owned: return false, true case owner == sharedProperty: return false, false - case owner == v: + case owner == index: return true, true default: - return e.reach.below(v, owner) + return e.reach.below(index, owner) } } diff --git a/ir/irfacts/grouped.go b/ir/irfacts/grouped.go index 830d14724..97ce26f1d 100644 --- a/ir/irfacts/grouped.go +++ b/ir/irfacts/grouped.go @@ -22,26 +22,26 @@ func (p *pairs[T]) add(key int, value T) { p.values = append(p.values, value) } -// grouped returns, for each key from 0 to n, the values added under it in the -// order added, each list a slice of one backing array sized by a counting pass: -// a build allocates per index rather than per list. A key added nothing has an -// empty list. -func (p *pairs[T]) grouped(n int) [][]T { - start := make([]int, n+1) +// grouped returns, for each key from 0 to count, the values added under it in +// the order added, each list a slice of one backing array sized by a counting +// pass: a build allocates per index rather than per list. A key added nothing +// has an empty list. +func (p *pairs[T]) grouped(count int) [][]T { + start := make([]int, count+1) for _, k := range p.keys { start[k+1]++ } - for k := range n { + for k := range count { start[k+1] += start[k] } backing := make([]T, len(p.values)) - filled := make([]int, n) + filled := make([]int, count) for i, k := range p.keys { backing[start[k]+filled[k]] = p.values[i] filled[k]++ } - out := make([][]T, n) - for k := range n { + out := make([][]T, count) + for k := range count { out[k] = backing[start[k]:start[k+1]:start[k+1]] } return out diff --git a/ir/irfacts/hierarchy.go b/ir/irfacts/hierarchy.go index 025cb6c47..c50454bba 100644 --- a/ir/irfacts/hierarchy.go +++ b/ir/irfacts/hierarchy.go @@ -17,23 +17,23 @@ type hierarchy struct { vertex map[ir.TypeID]int // declared types in sorted order, then supertypes the registry lacks reach *intervals // what each vertex is a subtype of children [][]ir.TypeID // by vertex, the declared models naming it among their supertypes - aliases aliasTargets // what each alias scalar stands for + aliases aliasTargets // what each alias scalar names } // newHierarchy indexes the subtype relation of the models in types. func newHierarchy(types ir.TypeRegistry) *hierarchy { - hierarchyValue := &hierarchy{ + hierarchy := &hierarchy{ vertex: make(map[ir.TypeID]int, len(types)), aliases: newAliasTargets(types), } - hierarchyValue.reach = newIntervals(hierarchyValue.supertypeEdges(types)) - return hierarchyValue + hierarchy.reach = newIntervals(hierarchy.supertypeEdges(types)) + return hierarchy } // childrenOf returns the declared models naming id among their supertypes. func (h *hierarchy) childrenOf(id ir.TypeID) []ir.TypeID { - if v, named := h.vertex[id]; named { - return h.children[v] + if index, named := h.vertex[id]; named { + return h.children[index] } return nil } @@ -70,13 +70,13 @@ func (h *hierarchy) supertypeEdges(types ir.TypeRegistry) [][]int { } supers = h.supertypes(supers[:0], model) for _, super := range supers { - v, named := h.vertex[super] + index, named := h.vertex[super] if !named { - v = len(h.vertex) - h.vertex[super] = v + index = len(h.vertex) + h.vertex[super] = index } - edges.add(i, v) - children.add(v, id) + edges.add(i, index) + children.add(index, id) } } h.children = children.grouped(len(h.vertex)) @@ -87,8 +87,8 @@ func (h *hierarchy) supertypeEdges(types ir.TypeRegistry) [][]int { // a Base and each Implements entry, before any is read through its aliases. func mostSupertypes(types ir.TypeRegistry) int { most := 0 - for _, td := range types { - if model, ok := td.(*ir.Model); ok && model != nil { + for _, typeDef := range types { + if model, ok := typeDef.(*ir.Model); ok && model != nil { most += len(model.Implements) if model.Base != nil { most++ @@ -102,11 +102,11 @@ func mostSupertypes(types ir.TypeRegistry) int { // false where they leave the pair open. func (h *hierarchy) subtype(target, base ir.TypeID) (sub, settled bool) { t, named := h.vertex[target] - b, alsoNamed := h.vertex[base] + baseIndex, alsoNamed := h.vertex[base] if !named || !alsoNamed { return false, true } - return h.reach.below(t, b) + return h.reach.below(t, baseIndex) } // descendants returns the sorted declared types with base above them, walking diff --git a/ir/irfacts/index.go b/ir/irfacts/index.go index aaf5fbf64..4df40da7e 100644 --- a/ir/irfacts/index.go +++ b/ir/irfacts/index.go @@ -35,6 +35,8 @@ type DocumentFacts struct { usage map[ir.TypeID]UsageFlags componentsOnce sync.Once components *components + compositionOnce sync.Once + composition *composition correlationOnce sync.Once correlation *correlations partialOnce sync.Once @@ -79,6 +81,14 @@ func (x *DocumentFacts) Subtypes(base ir.TypeID) []ir.TypeID { return x.hierarchyIndex().descendants(base) } +// DirectSubtypes returns the declared models naming base among their +// supertypes, as ir.Supertypes reads them, in sorted order, each once for +// every time it names base. The slice is the index's own: the caller must +// not modify it. +func (x *DocumentFacts) DirectSubtypes(base ir.TypeID) []ir.TypeID { + return x.hierarchyIndex().childrenOf(base) +} + // Partial reports whether the facts the index reads from the document's // operations, Usage and Correlation, may answer for part of it: whether // ir.ForEachOperation, which reads at least what they read, stopped at a bound. diff --git a/ir/irfacts/index_cost_test.go b/ir/irfacts/index_cost_test.go index b02063133..188f59e35 100644 --- a/ir/irfacts/index_cost_test.go +++ b/ir/irfacts/index_cost_test.go @@ -16,9 +16,9 @@ import ( // hierarchyOf returns a registry of n models, each the base of twelve subtypes, // each base declaring one property. -func hierarchyOf(n int) *ir.Document { +func hierarchyOf(count int) *ir.Document { doc := &ir.Document{Types: ir.TypeRegistry{}} - for i := range n { + for i := range count { base := ir.TypeID(fmt.Sprintf("type/x/M%d", i)) doc.Types[base] = &ir.Model{ID: base, Properties: []ir.Property{{ID: ir.PropertyID(fmt.Sprintf("property/x/M%d/a", i))}}} for j := range 12 { diff --git a/ir/irfacts/index_test.go b/ir/irfacts/index_test.go index ef522af45..9ca91b24f 100644 --- a/ir/irfacts/index_test.go +++ b/ir/irfacts/index_test.go @@ -5,6 +5,7 @@ package irfacts_test import ( "fmt" + "maps" "math" "math/rand/v2" "runtime" @@ -106,6 +107,16 @@ func factsCompare(t *testing.T, seed uint64, doc *ir.Document, universe []ir.Typ } slices.Sort(want) require.Equal(t, want, facts.Subtypes(base), "seed %d: Subtypes(%q)", seed, base) + var direct []ir.TypeID + for _, target := range slices.Sorted(maps.Keys(doc.Types)) { + for _, super := range ir.Supertypes(doc, target) { + if super == base { + direct = append(direct, target) + } + } + } + got := facts.DirectSubtypes(base) + require.True(t, slices.Equal(direct, got), "seed %d: DirectSubtypes(%q) = %v, want %v", seed, base, got, direct) } } @@ -163,8 +174,8 @@ func factsRandomAliases(rng *rand.Rand) (*ir.Document, []ir.TypeID) { } // aliasRead returns what ir.Supertypes reads the reference id as, by asking it -// of a model whose Base is id: the type id's alias scalars stand for, or "" -// when that names no type. +// of a model whose Base is id: the type id's alias scalars name, or "" when +// that names no type. func aliasRead(doc *ir.Document, id ir.TypeID) ir.TypeID { const probe = "probe/model" doc.Types[probe] = irtest.ModelOf(probe, func(model *ir.Model) { model.Base = &ir.TypeRef{Target: id} }) @@ -238,9 +249,9 @@ func factsBaseID(k int) ir.TypeID { return ir.TypeID(fmt.Sprintf("m%06d", k)) } // factsChain returns n+1 models chained by Base, factsChainID(0) at the top, // each shaped by mutate. -func factsChain(n int, mutate func(i int, model *ir.Model)) []ir.TypeDef { - defs := make([]ir.TypeDef, 0, n+1) - for i := 0; i <= n; i++ { +func factsChain(count int, mutate func(i int, model *ir.Model)) []ir.TypeDef { + defs := make([]ir.TypeDef, 0, count+1) + for i := 0; i <= count; i++ { defs = append(defs, irtest.ModelOf(factsChainID(i), func(model *ir.Model) { if i > 0 { model.Base = &ir.TypeRef{Target: factsChainID(i - 1)} @@ -271,11 +282,11 @@ type factsIDs struct { } // newFactsIDs makes the IDs of size n. -func newFactsIDs(n int) factsIDs { - ids := factsIDs{chain: make([]ir.TypeID, n+1), bases: make([]ir.TypeID, n), properties: make([]ir.PropertyID, n+1)} - for i := range n + 1 { +func newFactsIDs(count int) factsIDs { + ids := factsIDs{chain: make([]ir.TypeID, count+1), bases: make([]ir.TypeID, count), properties: make([]ir.PropertyID, count+1)} + for i := range count + 1 { ids.chain[i], ids.properties[i] = factsChainID(i), factsPropertyID(i) - if i < n { + if i < count { ids.bases[i] = factsBaseID(i) } } @@ -287,74 +298,96 @@ func newFactsIDs(n int) factsIDs { // whose models routes to the next (a closure per target is quadratic there), a // base routing to every model below it, alone and beside an unrelated model // naming two supertypes, a chain's properties asked of the models below them, -// and usage on a chain of discriminated bases. +// usage on a chain of discriminated bases, and GitHub #1993's chain mixing in +// a fresh model at every level, asked whether the level below composes it. func factsWorkShapes() map[string]factsWorkShape { return map[string]factsWorkShape{ + "each level of a chain asked of the fresh mixin above it": { + doc: func(count int) *ir.Document { + defs := factsChain(count, func(i int, model *ir.Model) { + if i > 0 { + model.Mixins = []ir.TypeRef{{Target: factsBaseID(i - 1)}} + } + }) + for k := range count { + defs = append(defs, irtest.ModelOf(factsBaseID(k), nil)) + } + return irtest.DocOf(defs...) + }, + ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, count int) (yes int) { + for i := 1; i <= count; i++ { + yes += factsCount(documentFacts.CompositionReaches(ids.chain[i-1], ids.bases[i-1])) + } + return yes + }, + }, "many bases routing to the bottom of one chain": { - doc: func(n int) *ir.Document { - defs := factsChain(n, nil) - for k := range n { + doc: func(count int) *ir.Document { + defs := factsChain(count, nil) + for k := range count { defs = append(defs, irtest.ModelOf(factsBaseID(k), nil)) } return irtest.DocOf(defs...) }, - ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, n int) (yes int) { - for k := range n { - yes += factsCount(documentFacts.IsSubtype(ids.chain[n], ids.bases[k])) + ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, count int) (yes int) { + for k := range count { + yes += factsCount(documentFacts.IsSubtype(ids.chain[count], ids.bases[k])) } return yes }, }, "each model of a chain routing to the next": { - doc: func(n int) *ir.Document { return irtest.DocOf(factsChain(n, nil)...) }, - ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, n int) (yes int) { - for i := range n { + doc: func(count int) *ir.Document { return irtest.DocOf(factsChain(count, nil)...) }, + ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, count int) (yes int) { + for i := range count { yes += factsCount(documentFacts.IsSubtype(ids.chain[i+1], ids.chain[i])) } return yes }, }, "the top of a chain routing to every model below it": { - doc: func(n int) *ir.Document { return irtest.DocOf(factsChain(n, nil)...) }, + doc: func(count int) *ir.Document { return irtest.DocOf(factsChain(count, nil)...) }, ask: factsAskTopOfChain, }, "the same beside an unrelated model naming two supertypes": { - doc: func(n int) *ir.Document { return irtest.DocOf(append(factsChain(n, nil), factsDiamond("x")...)...) }, + doc: func(count int) *ir.Document { + return irtest.DocOf(append(factsChain(count, nil), factsDiamond("x")...)...) + }, ask: factsAskTopOfChain, }, "the top's tag asked of every model of a chain": { - doc: func(n int) *ir.Document { - return irtest.DocOf(factsChain(n, func(i int, model *ir.Model) { + doc: func(count int) *ir.Document { + return irtest.DocOf(factsChain(count, func(i int, model *ir.Model) { if i == 0 { model.Properties = []ir.Property{{ID: factsPropertyID(0)}} } })...) }, - ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, n int) (yes int) { - for i := 1; i <= n; i++ { + ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, count int) (yes int) { + for i := 1; i <= count; i++ { yes += factsCount(documentFacts.Exposes(ids.chain[i], ids.properties[0])) } return yes }, }, "every model's property asked of the bottom of a chain": { - doc: func(n int) *ir.Document { - return irtest.DocOf(factsChain(n, func(i int, model *ir.Model) { model.Properties = []ir.Property{{ID: factsPropertyID(i)}} })...) + doc: func(count int) *ir.Document { + return irtest.DocOf(factsChain(count, func(i int, model *ir.Model) { model.Properties = []ir.Property{{ID: factsPropertyID(i)}} })...) }, - ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, n int) (yes int) { - for i := range n { - yes += factsCount(documentFacts.Exposes(ids.chain[n], ids.properties[i])) + ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, count int) (yes int) { + for i := range count { + yes += factsCount(documentFacts.Exposes(ids.chain[count], ids.properties[i])) } return yes }, }, "usage of a chain of discriminated bases": { - doc: func(n int) *ir.Document { - defs := factsChain(n, func(_ int, model *ir.Model) { model.Discriminator = &ir.Discriminator{PropertyName: "k"} }) + doc: func(count int) *ir.Document { + defs := factsChain(count, func(_ int, model *ir.Model) { model.Discriminator = &ir.Discriminator{PropertyName: "k"} }) return useDoc(ir.Operation{Responses: []ir.Response{{Payload: useBody("application/json", factsChainID(0))}}}, defs...) }, - ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, n int) (yes int) { - for i := 0; i <= n; i++ { + ask: func(documentFacts *irfacts.DocumentFacts, ids factsIDs, count int) (yes int) { + for i := 0; i <= count; i++ { yes += factsCount(documentFacts.Usage(ids.chain[i]) == irfacts.UsageOutput) } return yes - 1 @@ -365,8 +398,8 @@ func factsWorkShapes() map[string]factsWorkShape { // factsAskTopOfChain asks whether each model of a chain of n below its top is // a subtype of the top. -func factsAskTopOfChain(documentFacts *irfacts.DocumentFacts, ids factsIDs, n int) (yes int) { - for i := 1; i <= n; i++ { +func factsAskTopOfChain(documentFacts *irfacts.DocumentFacts, ids factsIDs, count int) (yes int) { + for i := 1; i <= count; i++ { yes += factsCount(documentFacts.IsSubtype(ids.chain[i], ids.chain[0])) } return yes diff --git a/ir/irfacts/index_walk_test.go b/ir/irfacts/index_walk_test.go index e685f11cb..1a7eca864 100644 --- a/ir/irfacts/index_walk_test.go +++ b/ir/irfacts/index_walk_test.go @@ -16,8 +16,8 @@ import ( // walkChain is a chain of n+1 models, each declaring one property, beside // extra models nothing relates to it. -func walkChain(n, extra int) *ir.Document { - defs := factsChain(n, func(i int, model *ir.Model) { model.Properties = []ir.Property{{ID: factsPropertyID(i)}} }) +func walkChain(count, extra int) *ir.Document { + defs := factsChain(count, func(i int, model *ir.Model) { model.Properties = []ir.Property{{ID: factsPropertyID(i)}} }) for k := range extra { defs = append(defs, irtest.ModelOf(factsBaseID(k), nil)) } diff --git a/ir/irfacts/intervals.go b/ir/irfacts/intervals.go index 6118f6064..0b7799d38 100644 --- a/ir/irfacts/intervals.go +++ b/ir/irfacts/intervals.go @@ -3,6 +3,8 @@ package irfacts +import "github.com/dexpace/morphic/stronglyconnected" + // intervals indexes what each vertex of a directed graph reaches, a vertex // lying below every one it reaches. The strongly connected components are // numbered in post-order, searching down from each component that reaches no @@ -21,20 +23,20 @@ type intervals struct { // newIntervals indexes the graph whose vertex v has an edge to each vertex in // edges[v]. func newIntervals(edges [][]int) *intervals { - intervalsValue := &intervals{} - intervalsValue.number(intervalsValue.condense(edges)) - return intervalsValue + intervals := &intervals{} + intervals.number(intervals.condense(edges)) + return intervals } // condense records each vertex's component and whether each component holds a // cycle, and returns each component's child components, the ones with an edge // to it, a child once for each such edge. func (r *intervals) condense(edges [][]int) [][]int { - comps := newTarjan(edges).run() + comps := stronglyconnected.Components(edges) r.comp = make([]int, len(edges)) - for c, members := range comps { - for _, v := range members { - r.comp[v] = c + for component, members := range comps { + for _, vertex := range members { + r.comp[vertex] = component } } r.cyclic = make([]bool, len(comps)) @@ -43,15 +45,15 @@ func (r *intervals) condense(edges [][]int) [][]int { most += len(out) } kids := pairsOf[int](most) - for c, members := range comps { - for _, v := range members { - for _, w := range edges[v] { - p := r.comp[w] - if p == c { - r.cyclic[c] = true // a member reaching itself, or another: a component of two has such an edge. + for component, members := range comps { + for _, vertex := range members { + for _, next := range edges[vertex] { + parent := r.comp[next] + if parent == component { + r.cyclic[component] = true // a member reaching itself, or another: a component of two has such an edge. continue } - kids.add(p, c) + kids.add(parent, component) } } } @@ -92,20 +94,27 @@ func (r *intervals) number(kids [][]int) { } continue } - c := top.vertex + component := top.vertex path = path[:len(path)-1] - r.close(c, kids[c], next) + r.close(component, kids[component], next) next++ } } } -// close numbers component c, whose kids are all numbered already: the +// frame is one vertex on a depth-first path and the next of its edges to +// follow. +type frame struct { + vertex int + next int +} + +// close numbers component, whose kids are all numbered already: the // condensation has no cycle, so a kid the search met before has been closed. -func (r *intervals) close(c int, kids []int, number int) { - r.hi[c], r.lo[c] = number, number +func (r *intervals) close(component int, kids []int, number int) { + r.hi[component], r.lo[component] = number, number for _, k := range kids { - r.lo[c] = min(r.lo[c], r.lo[k]) + r.lo[component] = min(r.lo[component], r.lo[k]) } } diff --git a/ir/irfacts/parts.go b/ir/irfacts/parts.go index 4cce2e0fc..04064a36d 100644 --- a/ir/irfacts/parts.go +++ b/ir/irfacts/parts.go @@ -8,7 +8,7 @@ import "github.com/dexpace/morphic/ir" // typeParts is what one type names, by what each named type is to a value of it // (docs/ir/derived-facts.md): held, the types of the values it holds, encoded // ones included; composed, those whose members it includes; alias, the type a -// scalar stands for; and args, its properties' field arguments, which a client +// scalar names; and args, its properties' field arguments, which a client // writes to select a field. // // A discriminator, a default or example value, an encoding's wire type, a @@ -21,14 +21,14 @@ type typeParts struct { args []ir.TypeID } -// read replaces p with the parts of td, keeping the storage of its slices. A nil -// or typed-nil td has none. -func (p *typeParts) read(td ir.TypeDef) { +// read replaces p with the parts of typeDef, keeping the storage of its slices. +// A nil or typed-nil typeDef has none. +func (p *typeParts) read(typeDef ir.TypeDef) { p.held, p.composed, p.args, p.alias = p.held[:0], p.composed[:0], p.args[:0], "" - if ir.IsNilTypeDef(td) { + if ir.IsNilTypeDef(typeDef) { return } - switch t := td.(type) { + switch t := typeDef.(type) { case *ir.Model: p.model(t) case *ir.Union: diff --git a/ir/irfacts/scc.go b/ir/irfacts/scc.go deleted file mode 100644 index 84d96e4a9..000000000 --- a/ir/irfacts/scc.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) 2026 dexpace. -// Licensed under the MIT License. See LICENSE in the repository root for details. - -package irfacts - -// tarjan finds the strongly connected components of a directed graph given as -// adjacency lists, with Tarjan's algorithm run on an explicit stack: a chain of -// types as long as a registry must not exhaust the goroutine stack. Both the -// subtype relation and the type graph are condensed with it. -type tarjan struct { - adj [][]int - order []int // discovery number of each vertex, unvisited until reached - low []int // lowest discovery number reachable from the vertex's subtree - onStack []bool - stack []int // vertices of components not yet closed - frames []frame // the depth-first path, innermost last - found int // vertices discovered so far - // members holds the vertices of the components found, back to back, and - // ends where each component's end in it. - members []int - ends []int -} - -// frame is one vertex on the depth-first path and the next edge to follow. -type frame struct { - vertex int - next int -} - -// unvisited marks a vertex the search has not reached. -const unvisited = -1 - -// newTarjan returns a search over adj. -func newTarjan(adj [][]int) *tarjan { - tarjanValue := &tarjan{ - adj: adj, - order: make([]int, len(adj)), - low: make([]int, len(adj)), - onStack: make([]bool, len(adj)), - members: make([]int, 0, len(adj)), - ends: make([]int, 0, len(adj)), - } - for v := range tarjanValue.order { - tarjanValue.order[v] = unvisited - } - return tarjanValue -} - -// run searches from each vertex in turn and returns the components in the -// order they close, which puts a component after every one its edges reach. -// Every vertex is opened once and every edge followed once. Each component is -// a slice of one backing array, so the search allocates per index and not per -// component. -func (t *tarjan) run() [][]int { - for root := range t.adj { - if t.order[root] == unvisited { - t.search(root) - } - } - out := make([][]int, len(t.ends)) - start := 0 - for c, end := range t.ends { - out[c] = t.members[start:end:end] - start = end - } - return out -} - -// search explores everything reachable from root that is not yet visited. -func (t *tarjan) search(root int) { - t.open(root) - for len(t.frames) > 0 { - top := &t.frames[len(t.frames)-1] - if top.next == len(t.adj[top.vertex]) { - t.finish() - continue - } - v, w := top.vertex, t.adj[top.vertex][top.next] - top.next++ - switch { - case t.order[w] == unvisited: - t.open(w) - case t.onStack[w]: - t.low[v] = min(t.low[v], t.order[w]) - } - } -} - -// open discovers v and pushes it on the path and on the component stack. -func (t *tarjan) open(v int) { - t.order[v] = t.found - t.low[v] = t.found - t.found++ - t.stack = append(t.stack, v) - t.onStack[v] = true - t.frames = append(t.frames, frame{vertex: v}) -} - -// finish leaves the innermost vertex once its edges are followed. A vertex that -// reaches no earlier one roots a component, which is everything above it on -// the component stack; either way it hands its low link to its parent. -func (t *tarjan) finish() { - v := t.frames[len(t.frames)-1].vertex - t.frames = t.frames[:len(t.frames)-1] - if t.low[v] == t.order[v] { - t.pop(v) - } - if len(t.frames) > 0 { - parent := t.frames[len(t.frames)-1].vertex - t.low[parent] = min(t.low[parent], t.low[v]) - } -} - -// pop moves the component rooted at v from the component stack to members. -func (t *tarjan) pop(v int) { - i := len(t.stack) - 1 - for t.stack[i] != v { - i-- - } - for _, w := range t.stack[i:] { - t.onStack[w] = false - } - t.members = append(t.members, t.stack[i:]...) - t.ends = append(t.ends, len(t.members)) - t.stack = t.stack[:i] -} diff --git a/ir/irfacts/stale_entries_test.go b/ir/irfacts/stale_entries_test.go index fb2903d10..6e18c84ec 100644 --- a/ir/irfacts/stale_entries_test.go +++ b/ir/irfacts/stale_entries_test.go @@ -44,7 +44,7 @@ func walkEveryKind(t *testing.T, roles, notFields map[string]string) (*readKeys, // TestStaleEntries_AreNamedByTheirTable plants, one at a time, a key no // position reads in each hand-kept table of the type graph and of usage: the // walk of the real IR leaves it unread, and the check names the table and the -// key. The tables as they stand, beside it, report nothing. +// key. The tables as they are, beside it, report nothing. func TestStaleEntries_AreNamedByTheirTable(t *testing.T) { t.Parallel() t.Run("partRoles", func(t *testing.T) { diff --git a/ir/irfacts/typegraph.go b/ir/irfacts/typegraph.go index 43527bec3..775f274c6 100644 --- a/ir/irfacts/typegraph.go +++ b/ir/irfacts/typegraph.go @@ -28,10 +28,10 @@ type typeGraph struct { } // newTypeGraph builds the graph over types, reading subtypes and alias targets -// from hierarchyValue, which indexes the same registry. -func newTypeGraph(types ir.TypeRegistry, hierarchyValue *hierarchy) *typeGraph { +// from hierarchy, which indexes the same registry. +func newTypeGraph(types ir.TypeRegistry, hierarchy *hierarchy) *typeGraph { ids := slices.Sorted(maps.Keys(types)) - typeGraphValue := &typeGraph{ + typeGraph := &typeGraph{ ids: ids, index: make(map[ir.TypeID]int, len(ids)), poly: make([]bool, len(ids)), @@ -40,15 +40,15 @@ func newTypeGraph(types ir.TypeRegistry, hierarchyValue *hierarchy) *typeGraph { loops: make([]bool, 2*len(ids)), } for i, id := range ids { - typeGraphValue.index[id] = i - typeGraphValue.poly[i] = polymorphic(types, hierarchyValue.aliases.target(id)) + typeGraph.index[id] = i + typeGraph.poly[i] = polymorphic(types, hierarchy.aliases.target(id)) } - var typePartsValue typeParts + var typeParts typeParts for i, id := range ids { - typePartsValue.read(types[id]) - typeGraphValue.addType(i, &typePartsValue, hierarchyValue.childrenOf(id)) + typeParts.read(types[id]) + typeGraph.addType(i, &typeParts, hierarchy.childrenOf(id)) } - return typeGraphValue + return typeGraph } // polymorphic reports whether a value declared as the type id names may hold @@ -62,23 +62,23 @@ func polymorphic(types ir.TypeRegistry, id ir.TypeID) bool { // addType adds the edges out of type i's two vertices. Its shape reaches what // it holds, the shapes it composes and the shape it aliases; its range reaches // its own shape, the range it aliases and its direct subtypes' ranges. -func (g *typeGraph) addType(i int, typePartsValue *typeParts, children []ir.TypeID) { +func (g *typeGraph) addType(i int, typeParts *typeParts, children []ir.TypeID) { shape, whole := 2*i, 2*i+1 - for _, id := range typePartsValue.held { + for _, id := range typeParts.held { g.linkReference(shape, id) } - for _, id := range typePartsValue.composed { + for _, id := range typeParts.composed { g.linkTo(shape, id, false) } - g.linkTo(shape, typePartsValue.alias, false) - g.linkTo(whole, typePartsValue.alias, true) + g.linkTo(shape, typeParts.alias, false) + g.linkTo(whole, typeParts.alias, true) g.link(whole, shape) for _, id := range children { g.linkTo(whole, id, true) } - for _, id := range typePartsValue.args { - if v, ok := g.reference(id); ok { - g.args[shape] = append(g.args[shape], v) + for _, id := range typeParts.args { + if vertex, ok := g.reference(id); ok { + g.args[shape] = append(g.args[shape], vertex) } } } @@ -123,9 +123,9 @@ func (g *typeGraph) reference(id ir.TypeID) (int, bool) { return g.vertex(id, g.poly[i]) } -// typeOf returns the type vertex v belongs to. -func (g *typeGraph) typeOf(v int) ir.TypeID { - return g.ids[v/2] +// typeOf returns the type vertex belongs to. +func (g *typeGraph) typeOf(vertex int) ir.TypeID { + return g.ids[vertex/2] } // link adds an edge from one vertex to another. diff --git a/ir/irfacts/usage.go b/ir/irfacts/usage.go index f4867a31a..79cfd5fb5 100644 --- a/ir/irfacts/usage.go +++ b/ir/irfacts/usage.go @@ -27,8 +27,8 @@ const ( // UsageError marks a type reached from the payload or headers of an error. UsageError // UsageMultipart marks the type of a multipart body itself, and the types - // its alias scalars stand for. The types nested in it travel as ordinary - // encoded parts and are not marked. + // its alias scalars name. The types nested in it travel as ordinary encoded + // parts and are not marked. UsageMultipart ) @@ -56,19 +56,19 @@ type usageStep struct { flags UsageFlags } -// newUsage derives the usage of every type of doc over typeGraphValue, the +// newUsage derives the usage of every type of doc over typeGraph, the // graph of its registry. A vertex passes on only the flags it had not reached // before, so it is expanded at most once per flag and a cycle ends. -func newUsage(doc *ir.Document, typeGraphValue *typeGraph) map[ir.TypeID]UsageFlags { +func newUsage(doc *ir.Document, typeGraph *typeGraph) map[ir.TypeID]UsageFlags { roots := usageRoots{} roots.document(doc) var pending []usageStep for id, flags := range roots { - if v, ok := typeGraphValue.reference(id); ok && flags&spreadingUsage != 0 { - pending = append(pending, usageStep{vertex: v, flags: flags & spreadingUsage}) + if vertex, ok := typeGraph.reference(id); ok && flags&spreadingUsage != 0 { + pending = append(pending, usageStep{vertex: vertex, flags: flags & spreadingUsage}) } } - reached := make([]UsageFlags, len(typeGraphValue.next)) + reached := make([]UsageFlags, len(typeGraph.next)) for len(pending) > 0 { step := pending[len(pending)-1] pending = pending[:len(pending)-1] @@ -77,17 +77,17 @@ func newUsage(doc *ir.Document, typeGraphValue *typeGraph) map[ir.TypeID]UsageFl continue } reached[step.vertex] |= fresh - for _, w := range typeGraphValue.next[step.vertex] { - pending = append(pending, usageStep{vertex: w, flags: fresh}) + for _, next := range typeGraph.next[step.vertex] { + pending = append(pending, usageStep{vertex: next, flags: fresh}) } - for _, w := range typeGraphValue.args[step.vertex] { - pending = append(pending, usageStep{vertex: w, flags: UsageInput}) + for _, next := range typeGraph.args[step.vertex] { + pending = append(pending, usageStep{vertex: next, flags: UsageInput}) } } usage := map[ir.TypeID]UsageFlags{} - for v, flags := range reached { + for vertex, flags := range reached { if flags != 0 { - usage[typeGraphValue.typeOf(v)] |= flags + usage[typeGraph.typeOf(vertex)] |= flags } } for id, flags := range roots { @@ -98,9 +98,9 @@ func newUsage(doc *ir.Document, typeGraphValue *typeGraph) map[ir.TypeID]UsageFl return usage } -// markMultipart marks id, and each type its alias scalars stand for, as the -// type of a multipart body. It stops at a type already marked, so a chain named -// by many bodies is followed once, and a cycle ends. +// markMultipart marks id, and each type its alias scalars name, as the type of +// a multipart body. It stops at a type already marked, so a chain named by many +// bodies is followed once, and a cycle ends. func markMultipart(types ir.TypeRegistry, usage map[ir.TypeID]UsageFlags, id ir.TypeID) { for { if _, declared := types[id]; !declared || usage[id]&UsageMultipart != 0 { @@ -147,8 +147,8 @@ func (r usageRoots) document(doc *ir.Document) { func callbackOperations(doc *ir.Document) map[ir.OperationID]bool { callbacks := map[ir.OperationID]bool{} ir.ForEachOperation(doc, func(operation ir.Operation) { - for _, b := range operation.Bindings.HTTP { - for _, cb := range b.Callbacks { + for _, binding := range operation.Bindings.HTTP { + for _, cb := range binding.Callbacks { for _, id := range cb.Operations { callbacks[id] = true } @@ -162,7 +162,7 @@ func callbackOperations(doc *ir.Document) map[ir.OperationID]bool { // sends: a webhook or a callback. Its WebhookName may be empty, since an empty // webhooks key is legal. func isInbound(operation *ir.Operation) bool { - return slices.ContainsFunc(operation.Bindings.HTTP, func(b ir.HTTPBinding) bool { return b.Inbound != "" }) + return slices.ContainsFunc(operation.Bindings.HTTP, func(binding ir.HTTPBinding) bool { return binding.Inbound != "" }) } // operation records what operation sends and what comes back. The client writes @@ -203,12 +203,12 @@ func (r usageRoots) operation(doc *ir.Document, operation *ir.Operation, inbound // messages records the messages a messaging binding sends or receives, and its // reply's, which travel the other way. A direction other than send or receive // says neither, so its messages are taken to travel both ways. -func (r usageRoots) messages(doc *ir.Document, b *ir.MessageBinding) { - if b == nil { +func (r usageRoots) messages(doc *ir.Document, binding *ir.MessageBinding) { + if binding == nil { return } own, reply := UsageInput|UsageOutput, UsageInput|UsageOutput - switch b.Direction { + switch binding.Direction { case ir.MessageDirectionSend: own, reply = UsageInput, UsageOutput case ir.MessageDirectionReceive: @@ -216,11 +216,11 @@ func (r usageRoots) messages(doc *ir.Document, b *ir.MessageBinding) { default: // An unknown direction leaves both sides marked. } - for _, id := range b.Messages { + for _, id := range binding.Messages { r.message(doc, id, own) } - if b.Reply != nil { - for _, id := range b.Reply.Messages { + if binding.Reply != nil { + for _, id := range binding.Reply.Messages { r.message(doc, id, reply) } } diff --git a/ir/irfacts/usage_positions_test.go b/ir/irfacts/usage_positions_test.go index ef1543055..a463dd7ee 100644 --- a/ir/irfacts/usage_positions_test.go +++ b/ir/irfacts/usage_positions_test.go @@ -134,28 +134,28 @@ func (w *positionWalk) note(step string) { } // walk records the type IDs v holds, under path. -func (w *positionWalk) walk(v reflect.Value, path []string, excluded string) { - if reason, ok := w.types[v.Type()]; ok && excluded == "" { +func (w *positionWalk) walk(value reflect.Value, path []string, excluded string) { + if reason, ok := w.types[value.Type()]; ok && excluded == "" { excluded = reason } - switch v.Kind() { + switch value.Kind() { case reflect.Pointer: - if !v.IsNil() { - w.walk(v.Elem(), path, excluded) + if !value.IsNil() { + w.walk(value.Elem(), path, excluded) } case reflect.Slice, reflect.Array: - for i := range v.Len() { - w.walk(v.Index(i), path, excluded) + for i := range value.Len() { + w.walk(value.Index(i), path, excluded) } case reflect.Map: - for _, key := range v.MapKeys() { + for _, key := range value.MapKeys() { w.walk(key, path, excluded) - w.walk(v.MapIndex(key), path, excluded) + w.walk(value.MapIndex(key), path, excluded) } case reflect.Struct: - w.fieldsOf(v, path, excluded) + w.fieldsOf(value, path, excluded) case reflect.String: - if id := ir.TypeID(v.String()); v.Type() == typeIDReflect && id != "" { + if id := ir.TypeID(value.String()); value.Type() == typeIDReflect && id != "" { w.out[id] = position{path: strings.Join(path, "/"), excluded: excluded} } default: @@ -164,13 +164,13 @@ func (w *positionWalk) walk(v reflect.Value, path []string, excluded string) { } // fieldsOf walks the exported fields of the struct v. -func (w *positionWalk) fieldsOf(v reflect.Value, path []string, excluded string) { - for i := range v.NumField() { - f := v.Type().Field(i) +func (w *positionWalk) fieldsOf(value reflect.Value, path []string, excluded string) { + for i := range value.NumField() { + f := value.Type().Field(i) if !f.IsExported() { continue } - step := v.Type().Name() + "." + f.Name + step := value.Type().Name() + "." + f.Name fieldExcluded := excluded if reason, ok := w.fields[step]; ok { w.note(step) @@ -186,7 +186,7 @@ func (w *positionWalk) fieldsOf(v reflect.Value, path []string, excluded string) if !skipped && !f.Anonymous && step != "TypeRef.Target" { next = append(slices.Clip(path), step) } - w.walk(v.Field(i), next, fieldExcluded) + w.walk(value.Field(i), next, fieldExcluded) } } @@ -203,9 +203,9 @@ var usageSkippedSteps = map[string]bool{ func usagePositions( doc *ir.Document, notRootFields map[string]string, skip map[string]bool, ) (positions map[ir.TypeID]position, read map[string]bool) { - positionWalkValue := &positionWalk{types: usageNotRoots, fields: notRootFields, skip: skip, out: map[ir.TypeID]position{}} - positionWalkValue.walk(reflect.ValueOf(doc).Elem(), nil, "") - return positionWalkValue.out, positionWalkValue.read + positionWalk := &positionWalk{types: usageNotRoots, fields: notRootFields, skip: skip, out: map[ir.TypeID]position{}} + positionWalk.walk(reflect.ValueOf(doc).Elem(), nil, "") + return positionWalk.out, positionWalk.read } // usageFilledDocument fills every field of a document outside its registry, diff --git a/ir/irtest/encode.go b/ir/irtest/encode.go index 956e10174..3389a1973 100644 --- a/ir/irtest/encode.go +++ b/ir/irtest/encode.go @@ -20,11 +20,11 @@ func Encoded(t *testing.T, doc *ir.Document) string { // encoded holds Encoded's logic against the minimal testingT surface, so its // failure is testable. -func encoded(testingTValue testingT, doc *ir.Document) string { - testingTValue.Helper() +func encoded(testingT testingT, doc *ir.Document) string { + testingT.Helper() raw, err := json.Marshal(doc) if err != nil { - testingTValue.Fatalf("encode the document: %v", err) + testingT.Fatalf("encode the document: %v", err) return "" } return string(raw) diff --git a/ir/irtest/encode_test.go b/ir/irtest/encode_test.go index f1bf00daf..0951c20a9 100644 --- a/ir/irtest/encode_test.go +++ b/ir/irtest/encode_test.go @@ -46,9 +46,9 @@ func TestEncoded_FailsTheTestOnADocumentThatDoesNotEncode(t *testing.T) { // nor one refused for another reason is. func TestRefusedAsCyclic_ReadsOnlyTheCycleRefusal(t *testing.T) { t.Parallel() - constructorValue := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} - self := ir.Value{Kind: ir.ValueConstructor, Constructor: constructorValue} - constructorValue.Args = []ir.Value{self} + constructor := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} + self := ir.Value{Kind: ir.ValueConstructor, Constructor: constructor} + constructor.Args = []ir.Value{self} cyclic := irtest.DocOf(irtest.ModelOf("type/x/M", func(model *ir.Model) { model.Examples = []ir.Example{{Value: &self}} })) diff --git a/ir/irtest/fill.go b/ir/irtest/fill.go index 092d9ad85..6fd45525a 100644 --- a/ir/irtest/fill.go +++ b/ir/irtest/fill.go @@ -20,21 +20,21 @@ const fillDepth = 3 // allocated, and every slice and string-keyed map gets one element. Numbers, // bools, byte slices, other maps and other strings are left zero. It fails the // test unless v is a non-nil pointer. -func Fill(t *testing.T, v any) { +func Fill(t *testing.T, target any) { t.Helper() - fill(t, v) + fill(t, target) } // fill holds Fill's logic against the minimal testingT surface, so its refusal // can be driven by a stub. -func fill(testingTValue testingT, v any) { - testingTValue.Helper() - rv := reflect.ValueOf(v) +func fill(testingT testingT, target any) { + testingT.Helper() + rv := reflect.ValueOf(target) if rv.Kind() != reflect.Pointer || rv.IsNil() { - testingTValue.Fatalf("irtest: fill: want a non-nil pointer, got %T", v) + testingT.Fatalf("irtest: fill: want a non-nil pointer, got %T", target) } - fillerValue := &filler{stack: map[reflect.Type]int{}} - fillerValue.fill(rv.Elem()) + filler := &filler{stack: map[reflect.Type]int{}} + filler.fill(rv.Elem()) } // typeIDType is the reflect.Type of ir.TypeID. @@ -54,25 +54,25 @@ func (f *filler) id() string { } // fill populates v by its kind. -func (f *filler) fill(v reflect.Value) { - switch v.Kind() { +func (f *filler) fill(value reflect.Value) { + switch value.Kind() { case reflect.String: - if v.Type() == typeIDType { - v.SetString(f.id()) + if value.Type() == typeIDType { + value.SetString(f.id()) } case reflect.Pointer: - v.Set(reflect.New(v.Type().Elem())) - f.fill(v.Elem()) + value.Set(reflect.New(value.Type().Elem())) + f.fill(value.Elem()) case reflect.Struct: - f.fillStruct(v) + f.fillStruct(value) case reflect.Slice: - if v.Type().Elem().Kind() == reflect.Uint8 { + if value.Type().Elem().Kind() == reflect.Uint8 { return } - v.Set(reflect.MakeSlice(v.Type(), 1, 1)) - f.fill(v.Index(0)) + value.Set(reflect.MakeSlice(value.Type(), 1, 1)) + f.fill(value.Index(0)) case reflect.Map: - f.fillMap(v) + f.fillMap(value) default: // Numbers, bools and the like carry no TypeID. } @@ -80,35 +80,35 @@ func (f *filler) fill(v reflect.Value) { // fillStruct populates v's exported fields, unless its type is already entered // fillDepth times on this path. -func (f *filler) fillStruct(v reflect.Value) { - t := v.Type() +func (f *filler) fillStruct(value reflect.Value) { + t := value.Type() if f.stack[t] >= fillDepth { return } f.stack[t]++ defer func() { f.stack[t]-- }() - for i := range v.NumField() { + for i := range value.NumField() { if t.Field(i).IsExported() { - f.fill(v.Field(i)) + f.fill(value.Field(i)) } } } // fillMap gives v one entry when its keys are strings, under a key no other map // of the fill uses: a type ID when the key is one, and otherwise "keyN". -func (f *filler) fillMap(v reflect.Value) { - if v.Type().Key().Kind() != reflect.String { +func (f *filler) fillMap(value reflect.Value) { + if value.Type().Key().Kind() != reflect.String { return } - key := reflect.New(v.Type().Key()).Elem() + key := reflect.New(value.Type().Key()).Elem() if key.Type() == typeIDType { key.SetString(f.id()) } else { f.keys++ key.SetString(fmt.Sprintf("key%d", f.keys)) } - element := reflect.New(v.Type().Elem()).Elem() + element := reflect.New(value.Type().Elem()).Elem() f.fill(element) - v.Set(reflect.MakeMap(v.Type())) - v.SetMapIndex(key, element) + value.Set(reflect.MakeMap(value.Type())) + value.SetMapIndex(key, element) } diff --git a/ir/irtest/fill_test.go b/ir/irtest/fill_test.go index da09f4d99..19e13f6b9 100644 --- a/ir/irtest/fill_test.go +++ b/ir/irtest/fill_test.go @@ -20,14 +20,14 @@ func TestFill_GivesEveryTypeIDOneOfItsOwn(t *testing.T) { irtest.Fill(t, doc) seen := map[string]string{} - ir.WalkValues(doc, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + ir.WalkValues(doc, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { path := at.String() - if v.Kind() == reflect.String && v.Type() == reflect.TypeFor[ir.TypeID]() { - require.NotEmpty(t, v.String(), "%s was left empty", path) - if first, met := seen[v.String()]; met { - assert.Failf(t, "a type ID is shared", "%s and %s both hold %q", first, path, v.String()) + if value.Kind() == reflect.String && value.Type() == reflect.TypeFor[ir.TypeID]() { + require.NotEmpty(t, value.String(), "%s was left empty", path) + if first, met := seen[value.String()]; met { + assert.Failf(t, "a type ID is shared", "%s and %s both hold %q", first, path, value.String()) } - seen[v.String()] = path + seen[value.String()] = path } return true })) diff --git a/ir/irtest/golden.go b/ir/irtest/golden.go index d2ce3c037..5373ab69e 100644 --- a/ir/irtest/golden.go +++ b/ir/irtest/golden.go @@ -42,9 +42,9 @@ func encodeGolden(doc *ir.Document) ([]byte, error) { return append(raw, '\n'), nil } -// stampError reports a document a golden cannot stand for: one not stamped -// with ir.IRVersion. A golden leaves the stamp out, so this check is what -// still asserts it. +// stampError reports a document a golden cannot hold: one not stamped with +// ir.IRVersion. A golden leaves the stamp out, so this check is what still +// asserts it. func stampError(doc *ir.Document) error { if doc.IRVersion != ir.IRVersion { return fmt.Errorf("document stamped irVersion %q, not ir.IRVersion %s", doc.IRVersion, ir.IRVersion) @@ -111,22 +111,22 @@ func CompareGolden(t *testing.T, goldenPath string, doc *ir.Document) { // compareGolden holds the comparison logic against the minimal testingT surface. // The preconditions precede the -update branch, so a bad call is refused the // same way whether the golden is being compared or rewritten. -func compareGolden(testingTValue testingT, goldenPath string, doc *ir.Document) { - testingTValue.Helper() +func compareGolden(testingT testingT, goldenPath string, doc *ir.Document) { + testingT.Helper() if goldenPath == "" { - testingTValue.Fatalf("irtest: compare golden: empty golden path") + testingT.Fatalf("irtest: compare golden: empty golden path") } if doc == nil { - testingTValue.Fatalf("irtest: compare golden: nil document") + testingT.Fatalf("irtest: compare golden: nil document") } if err := stampError(doc); err != nil { - testingTValue.Fatalf("irtest: compare golden %s: %v", goldenPath, err) + testingT.Fatalf("irtest: compare golden %s: %v", goldenPath, err) } raw, err := encodeGolden(doc) if err != nil { - testingTValue.Fatalf("marshal document: %v", err) + testingT.Fatalf("marshal document: %v", err) } - compareBytes(testingTValue, goldenPath, raw) + compareBytes(testingT, goldenPath, raw) } // CompareBytes compares got against the golden file at path, or rewrites it @@ -143,33 +143,33 @@ func CompareBytes(t *testing.T, path string, got []byte) { } // compareBytes is CompareBytes against the minimal testingT surface. -func compareBytes(testingTValue testingT, path string, got []byte) { - testingTValue.Helper() +func compareBytes(testingT testingT, path string, got []byte) { + testingT.Helper() if path == "" { - testingTValue.Fatalf("irtest: compare golden: empty golden path") + testingT.Fatalf("irtest: compare golden: empty golden path") } if Update() { - if testingTValue.Failed() { - testingTValue.Fatalf("irtest: update golden %s: the test has already failed, so the golden is left as it was", path) + if testingT.Failed() { + testingT.Fatalf("irtest: update golden %s: the test has already failed, so the golden is left as it was", path) } if err := writeBytes(path, got); err != nil { - testingTValue.Fatalf("update golden: %v", err) + testingT.Fatalf("update golden: %v", err) } return } want, err := os.ReadFile(path) if err != nil { - testingTValue.Fatalf("read golden %s (run with -update to create): %v", path, err) + testingT.Fatalf("read golden %s (run with -update to create): %v", path, err) } if diff := cmp.Diff(string(want), string(got)); diff != "" { - testingTValue.Errorf("golden mismatch for %s (-golden +got); -update rewrites it:\n%s", path, diff) + testingT.Errorf("golden mismatch for %s (-golden +got); -update rewrites it:\n%s", path, diff) } } -// ReadGolden decodes the golden at path into the document it stands for, -// stamped with ir.IRVersion, which the golden leaves out. The Document decoder -// reads the result, so a golden that stores a stamp of its own is refused as -// a duplicate member, like anything else that decoder refuses. +// ReadGolden decodes the golden at path into the document it holds, stamped +// with ir.IRVersion, which the golden leaves out. The Document decoder reads +// the result, so a golden that stores a stamp of its own is refused as a +// duplicate member, like anything else that decoder refuses. func ReadGolden(path string) (*ir.Document, error) { raw, err := os.ReadFile(path) if err != nil { diff --git a/ir/irtest/lineendings_test.go b/ir/irtest/lineendings_test.go index 827cda2e6..aa84df91f 100644 --- a/ir/irtest/lineendings_test.go +++ b/ir/irtest/lineendings_test.go @@ -17,8 +17,8 @@ import ( "github.com/dexpace/morphic/ir/irtest" ) -// eolProbes are paths whose line endings the golden comparison depends on: an IR -// snapshot, the spec it was compiled from, and a Go source file standing for the +// eolProbes are paths whose line endings the golden comparison depends on: an +// IR snapshot, the spec it was compiled from, and a Go source file naming the // rest of the tree. Each is required to exist, so a rename cannot quietly turn // the checks below into assertions about nothing. var eolProbes = []string{ diff --git a/ir/irtest/repo.go b/ir/irtest/repo.go index 16888f689..7af079fdb 100644 --- a/ir/irtest/repo.go +++ b/ir/irtest/repo.go @@ -20,16 +20,16 @@ func RepoRoot(t *testing.T) string { // rootFrom is RepoRoot with the working directory's lookup injected, so a test // can drive both of its failures. -func rootFrom(testingTValue testingT, getwd func() (string, error)) string { - testingTValue.Helper() +func rootFrom(testingT testingT, getwd func() (string, error)) string { + testingT.Helper() dir, err := getwd() if err != nil { - testingTValue.Fatalf("irtest: reading the working directory: %v", err) + testingT.Fatalf("irtest: reading the working directory: %v", err) } for !holdsGoMod(dir) { parent := filepath.Dir(dir) if parent == dir { - testingTValue.Fatalf("irtest: no go.mod in or above the working directory") + testingT.Fatalf("irtest: no go.mod in or above the working directory") } dir = parent } diff --git a/ir/irtest/spaces_test.go b/ir/irtest/spaces_test.go index bdc8cb642..ee09d87d2 100644 --- a/ir/irtest/spaces_test.go +++ b/ir/irtest/spaces_test.go @@ -15,11 +15,12 @@ import ( func model(id string) *ir.Model { return &ir.Model{ID: ir.TypeID(id)} } -// TestSpacesUsed_ReadsEveryKindSortedWithoutRepeats holds the result to the form -// Document.IDSpaces takes: each kind's namespaces sorted, and each once however -// many IDs live in it. The kinds are spread over a registry, a map and nested -// nodes so that no one way of reaching an ID stands in for the rest, and the -// services are declared out of order because walk order is not sorted order. +// TestSpacesUsed_ReadsEveryKindSortedWithoutRepeats holds the result to the +// form Document.IDSpaces takes: each kind's namespaces sorted, and each once +// however many IDs live in it. The kinds are spread over a registry, a map and +// nested nodes so that no one way of reaching an ID takes the place of the +// rest, and the services are declared out of order because walk order is not +// sorted order. func TestSpacesUsed_ReadsEveryKindSortedWithoutRepeats(t *testing.T) { t.Parallel() doc := &ir.Document{ diff --git a/ir/irtest/visits.go b/ir/irtest/visits.go index 21477bfef..fd9b81273 100644 --- a/ir/irtest/visits.go +++ b/ir/irtest/visits.go @@ -49,9 +49,9 @@ type measuredVisitor struct { // Visit shows v to the visitor, then measures the visit, and asks for v's // children as the visitor does. -func (m measuredVisitor) Visit(v reflect.Value, at ir.WalkPath) bool { - children := m.visitor.Visit(v, at) - if fewestAllocs(func() { m.visitor.Visit(v, at) }) > 0 { +func (m measuredVisitor) Visit(value reflect.Value, at ir.WalkPath) bool { + children := m.visitor.Visit(value, at) + if fewestAllocs(func() { m.visitor.Visit(value, at) }) > 0 { *m.paths = append(*m.paths, at.String()) } return children diff --git a/ir/irtest/visits_test.go b/ir/irtest/visits_test.go index 39e7b9bb5..172eda145 100644 --- a/ir/irtest/visits_test.go +++ b/ir/irtest/visits_test.go @@ -24,8 +24,8 @@ func TestAllocatingVisits_FindsEachVisitRenderingItsPath(t *testing.T) { Operations: []ir.Operation{{ID: "operation/x/A"}, {ID: "operation/x/B"}}, }}}}} var last string - renderOperationIDs := ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() == reflect.TypeFor[ir.OperationID]() { + renderOperationIDs := ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() == reflect.TypeFor[ir.OperationID]() { last = at.String() } return true @@ -75,11 +75,11 @@ func TestAllocatingVisits_ListsAValueForEachVisitorAllocating(t *testing.T) { doc := &ir.Document{Services: []ir.Service{{ID: "service/x"}}} var kept []string rendering := func(prune bool) ir.Visitor { - return ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() == reflect.TypeFor[ir.ServiceID]() || v.Type() == reflect.TypeFor[ir.Service]() { + return ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() == reflect.TypeFor[ir.ServiceID]() || value.Type() == reflect.TypeFor[ir.Service]() { kept = append(kept[:0], at.String()) } - return !prune || v.Type() != reflect.TypeFor[ir.Service]() + return !prune || value.Type() != reflect.TypeFor[ir.Service]() }) } @@ -97,8 +97,8 @@ func TestAllocatingVisits_MeasuresACleanVisitOnce(t *testing.T) { var kept []byte counting := func(allocate bool) (ir.Visitor, *int) { calls := 0 - return ir.VisitFunc(func(v reflect.Value, _ ir.WalkPath) bool { - if v.Kind() == reflect.String && v.String() == "api" { + return ir.VisitFunc(func(value reflect.Value, _ ir.WalkPath) bool { + if value.Kind() == reflect.String && value.String() == "api" { calls++ if allocate { kept = make([]byte, 64) diff --git a/ir/irverify/bigval.go b/ir/irverify/bigval.go index 7191c61a5..4f5d9bfd0 100644 --- a/ir/irverify/bigval.go +++ b/ir/irverify/bigval.go @@ -30,15 +30,15 @@ var ( func checkBigVals(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - switch v.Type() { + visit: func(value reflect.Value, at ir.WalkPath) bool { + switch value.Type() { case bigValPtrType: // A bound carried by pointer is present because something set it, // so an empty literal there is a defect rather than an absence. // Reading it here rather than descending is what tells the two // apart. - if !v.IsNil() { - vs = appendBigVal(vs, v.Elem().String(), at) + if !value.IsNil() { + vs = appendBigVal(vs, value.Elem().String(), at) } return false case bigValType: @@ -49,7 +49,7 @@ func checkBigVals(*ir.Document) walkCheck { // non-number Value: an empty Number on one whose Kind is number // is checkValues' to report (ir/value-missing-payload), not this // check's. - if literal := v.String(); literal != "" { + if literal := value.String(); literal != "" { vs = appendBigVal(vs, literal, at) } return false diff --git a/ir/irverify/bigval_test.go b/ir/irverify/bigval_test.go index ee9fee53a..d6a6e3ae5 100644 --- a/ir/irverify/bigval_test.go +++ b/ir/irverify/bigval_test.go @@ -118,11 +118,11 @@ func TestVerify_NonCanonicalBigValIsAViolation(t *testing.T) { } } -// TestVerify_CanonicalBigValIsClean is the silent half: a check that cannot stay -// quiet reports every document that carries a number. The values span what -// BigVal exists to carry — a magnitude and a precision no float64 holds, an -// exponent, and a signed zero — so the rule cannot be passing them by narrowing -// what a number is. +// TestVerify_CanonicalBigValIsClean is the report-nothing half: a check that +// cannot stay quiet reports every document that carries a number. The values +// span what BigVal exists to carry — a magnitude and a precision no float64 +// holds, an exponent, and a signed zero — so the rule cannot be passing them by +// narrowing what a number is. func TestVerify_CanonicalBigValIsClean(t *testing.T) { t.Parallel() for _, literal := range []string{ diff --git a/ir/irverify/boundkinds.go b/ir/irverify/boundkinds.go index f391a3787..951ce9a18 100644 --- a/ir/irverify/boundkinds.go +++ b/ir/irverify/boundkinds.go @@ -4,20 +4,22 @@ package irverify import ( + "slices" + "github.com/dexpace/morphic/ir" ) -// checkBoundKinds asserts each structural node holds only the bounds of its kind -// (docs/ir/constraints.md#constraints): a Model or a MapT the property counts, -// a List or a Tuple the item counts and uniqueness. Any other bound applies to -// instances no such node admits, so it bounds nothing there, and a consumer -// reading it would hold a value to a rule its source does not state. A Scalar's, -// a Union's and a carrier's bounds turn on an encoding, variants or what is -// named, which only a compiler judges, so none is read here. +// checkBoundKinds asserts each structural node and each enum holds only the +// bounds of its kind (docs/ir/constraints.md#constraints): a Model or a MapT +// the property counts, a List or a Tuple the item counts and uniqueness, an +// Enum those of the values its ValueType holds. Any other bound bounds nothing +// such a node admits, and a consumer reading it would hold a value to a rule +// its source does not state. A Scalar's, a Union's and a carrier's bounds turn +// on an encoding, variants or what is named, which only a compiler judges. func checkBoundKinds(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - kind, foreign := foreignBounds(td) + for id, typeDef := range doc.Types { + kind, foreign := foreignBounds(typeDef) if !foreign { continue } @@ -30,19 +32,21 @@ func checkBoundKinds(doc *ir.Document) []Violation { return vs } -// foreignBounds reports whether td, a Model, a MapT, a List or a Tuple, holds a -// bound its kind does not take, and the kind's name. Any other node, a nil one -// among them, which checkRegistryKeys reports, is not asked. -func foreignBounds(td ir.TypeDef) (string, bool) { - switch n := td.(type) { +// foreignBounds reports whether typeDef, a Model, a MapT, a List, a Tuple or an +// Enum, holds a bound its kind does not take, and the kind's name. Any other +// node, a nil one among them, which checkRegistryKeys reports, is not asked. +func foreignBounds(typeDef ir.TypeDef) (string, bool) { + switch node := typeDef.(type) { case *ir.Model: - return "model", n != nil && beyondProperties(n.Constraints) + return "model", node != nil && beyondProperties(node.Constraints) case *ir.MapT: - return "map", n != nil && beyondProperties(n.Constraints) + return "map", node != nil && beyondProperties(node.Constraints) case *ir.List: - return "list", n != nil && beyondItems(n.Constraints) + return "list", node != nil && beyondItems(node.Constraints) case *ir.Tuple: - return "tuple", n != nil && beyondItems(n.Constraints) + return "tuple", node != nil && beyondItems(node.Constraints) + case *ir.Enum: + return "enum", node != nil && hasBoundBeyondMemberValues(node.ValueType, node.Constraints) default: return "", false } @@ -70,3 +74,21 @@ func beyondItems(constraints *ir.Constraints) bool { rest.MinItems, rest.MaxItems, rest.UniqueItems = nil, nil, false return rest != ir.Constraints{} } + +// hasBoundBeyondMemberValues reports whether constraints holds a bound that +// applies to no kind of value memberKinds lets an enum of valueType hold +// (ir.ConstraintKeyword.Binds), uniqueness among them, as an enum holds no +// list. An undeclared valueType is not asked, as checkPrimitiveKinds reports +// it. +func hasBoundBeyondMemberValues(valueType ir.PrimitiveKind, constraints *ir.Constraints) bool { + if constraints == nil || !valueType.Valid() { + return false + } + admitted := memberKinds[valueType] + for keyword := range ir.ConstraintKeywords() { + if constraints.SetsKeyword(keyword) && !slices.ContainsFunc(admitted, keyword.Binds) { + return true + } + } + return constraints.UniqueItems +} diff --git a/ir/irverify/boundkinds_table_test.go b/ir/irverify/boundkinds_table_test.go index 811f32166..aa8be7b1d 100644 --- a/ir/irverify/boundkinds_table_test.go +++ b/ir/irverify/boundkinds_table_test.go @@ -6,6 +6,7 @@ package irverify_test import ( "reflect" "slices" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -40,15 +41,22 @@ func oneBound(t *testing.T, name string) *ir.Constraints { // TestVerify_EachBoundIsHeldToTheKindsThatTakeIt crosses every field of // ir.Constraints with every kind of node holding one. A Model and a MapT take // the property counts alone, a List and a Tuple the item counts and uniqueness -// alone, each as JSON Schema applies them to an object and an array, and a -// Scalar and a Union are not judged, whichever field they hold. The fields are -// read off the struct, so one added later is refused on a structural node until -// a row here says a kind takes it. +// alone, and an Enum the bounds of the values its ValueType holds, each as JSON +// Schema applies them; a Scalar, a Union and an Enum of an undeclared value +// type are not judged. The fields are read off the struct, so one added later +// is refused until a row here says a kind takes it. func TestVerify_EachBoundIsHeldToTheKindsThatTakeIt(t *testing.T) { t.Parallel() leafRef := ir.TypeRef{Target: "type/x/Leaf"} properties := []string{"MinProperties", "MaxProperties"} items := []string{"MinItems", "MaxItems", "UniqueItems"} + text := []string{"MinLength", "MaxLength", "Pattern", "PatternMessage"} + numbers := []string{"Min", "Max", "ExclusiveMin", "ExclusiveMax", "MultipleOf", "Precision", "Scale"} + enumOf := func(valueType ir.PrimitiveKind) func(*ir.Constraints) ir.TypeDef { + return func(constraints *ir.Constraints) ir.TypeDef { + return &ir.Enum{ValueType: valueType, Constraints: constraints} + } + } kinds := []struct { name string node func(*ir.Constraints) ir.TypeDef @@ -71,6 +79,14 @@ func TestVerify_EachBoundIsHeldToTheKindsThatTakeIt(t *testing.T) { {name: "union", node: func(constraints *ir.Constraints) ir.TypeDef { return &ir.Union{Variants: []ir.Variant{{Type: leafRef}}, Constraints: constraints} }, unasked: true}, + {name: "enum of string", node: enumOf(ir.PrimitiveString), takes: text}, + {name: "enum of uuid", node: enumOf(ir.PrimitiveUUID), takes: text}, + {name: "enum of bytes", node: enumOf(ir.PrimitiveBytes), takes: text}, + {name: "enum of int32", node: enumOf(ir.PrimitiveInt32), takes: numbers}, + {name: "enum of decimal", node: enumOf(ir.PrimitiveDecimal), takes: numbers}, + {name: "enum of bool", node: enumOf(ir.PrimitiveBool)}, + {name: "enum of any", node: enumOf(ir.PrimitiveAny), takes: slices.Concat(text, numbers)}, + {name: "enum of an undeclared value type", node: enumOf("color"), unasked: true}, } fields := reflect.TypeFor[ir.Constraints]() for _, kind := range kinds { @@ -82,16 +98,16 @@ func TestVerify_EachBoundIsHeldToTheKindsThatTakeIt(t *testing.T) { field := declared.Name t.Run(kind.name+"/"+field, func(t *testing.T) { t.Parallel() - td := kind.node(oneBound(t, field)) - td.Common().ID = "type/x/N" - got := boundViolations(stamped(closedDoc(td))) + typeDef := kind.node(oneBound(t, field)) + typeDef.Common().ID = "type/x/N" + got := boundViolations(stamped(closedDoc(typeDef))) if kind.unasked || slices.Contains(kind.takes, field) { assert.Empty(t, got) return } require.Len(t, got, 1) assert.Equal(t, "types[type/x/N].Constraints", got[0].Path) - assert.Contains(t, got[0].Message, kind.name) + assert.Contains(t, got[0].Message, strings.Fields(kind.name)[0]) }) } } diff --git a/ir/irverify/boundkinds_test.go b/ir/irverify/boundkinds_test.go index 6f603e4dc..8456cf639 100644 --- a/ir/irverify/boundkinds_test.go +++ b/ir/irverify/boundkinds_test.go @@ -41,16 +41,17 @@ func TestVerify_AScalarOrUnionHoldingAnyBoundIsNotChecked(t *testing.T) { // TestVerify_ABoundOnANodeWhoseKindCannotTakeItIsAViolation holds that a model // holding a string bound, a list holding a property count, a map holding a -// numeric bound and a tuple holding a pattern each draw one violation at the -// node, and that the bounds each of those kinds takes draw none. +// numeric bound, a tuple holding a pattern and an enum of strings holding a +// numeric bound or an item count each draw one violation at the node, and that +// the bounds each of those kinds takes draw none. func TestVerify_ABoundOnANodeWhoseKindCannotTakeItIsAViolation(t *testing.T) { t.Parallel() count, lower := new(int64(1)), ir.BigVal("1") stringType := ir.TypeRef{Target: "type/x/Leaf"} for _, tc := range []struct { - name string - td ir.TypeDef - bad bool + name string + typeDef ir.TypeDef + bad bool }{ {"a model's string bound", &ir.Model{Constraints: &ir.Constraints{MinLength: count}}, true}, {"a model's pattern", &ir.Model{Constraints: &ir.Constraints{Pattern: "a"}}, true}, @@ -68,12 +69,22 @@ func TestVerify_ABoundOnANodeWhoseKindCannotTakeItIsAViolation(t *testing.T) { {"a tuple's item bounds", &ir.Tuple{ElementTypes: []ir.TypeRef{stringType}, Constraints: &ir.Constraints{ MinItems: count, MaxItems: count, UniqueItems: true, }}, false}, + {"a string enum's numeric bound", &ir.Enum{ValueType: ir.PrimitiveString, Constraints: &ir.Constraints{Max: &lower}}, true}, + {"a string enum's item count", &ir.Enum{ValueType: ir.PrimitiveString, Constraints: &ir.Constraints{MaxItems: count}}, true}, + {"a string enum's text bounds", &ir.Enum{ValueType: ir.PrimitiveString, Constraints: &ir.Constraints{ + MinLength: count, MaxLength: count, Pattern: "a", + }}, false}, + {"an integer enum's text bound", &ir.Enum{ValueType: ir.PrimitiveInt64, Constraints: &ir.Constraints{MaxLength: count}}, true}, + {"an integer enum's numeric bounds", &ir.Enum{ValueType: ir.PrimitiveInt64, Constraints: &ir.Constraints{ + Min: &lower, Max: &lower, MultipleOf: &lower, + }}, false}, + {"a boolean enum's empty bounds", &ir.Enum{ValueType: ir.PrimitiveBool, Constraints: &ir.Constraints{}}, false}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - td := tc.td - td.Common().ID = "type/x/N" - got := boundViolations(stamped(closedDoc(td))) + typeDef := tc.typeDef + typeDef.Common().ID = "type/x/N" + got := boundViolations(stamped(closedDoc(typeDef))) if !tc.bad { assert.Empty(t, got) return diff --git a/ir/irverify/catchall.go b/ir/irverify/catchall.go index 9530ae563..bfa41d50e 100644 --- a/ir/irverify/catchall.go +++ b/ir/irverify/catchall.go @@ -22,11 +22,11 @@ import ( func checkCatchAllEncodings(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != contentType { - return operationPath[v.Type()] || contentPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != contentType { + return operationPath[value.Type()] || contentPath[value.Type()] } - if content, ok := reflect.TypeAssert[ir.Content](v); ok && len(content.CatchAllEncoding) > 0 { + if content, ok := reflect.TypeAssert[ir.Content](value); ok && len(content.CatchAllEncoding) > 0 { vs = appendEmptyCatchAlls(vs, content.CatchAllEncoding, at) } return false diff --git a/ir/irverify/cycles_internal_test.go b/ir/irverify/cycles_internal_test.go index e91a5dbb9..f324cb60b 100644 --- a/ir/irverify/cycles_internal_test.go +++ b/ir/irverify/cycles_internal_test.go @@ -30,9 +30,9 @@ func concreteTypeDefs(t *testing.T) []reflect.Type { out := make([]reflect.Type, 0, len(kinds)) for _, declaredConst := range kinds { - td, known := ir.NewTypeDef(ir.TypeKind(declaredConst.Value)) + typeDef, known := ir.NewTypeDef(ir.TypeKind(declaredConst.Value)) require.True(t, known, "kind %q has no constructor", declaredConst.Value) - out = append(out, reflect.TypeOf(td)) + out = append(out, reflect.TypeOf(typeDef)) } return out } diff --git a/ir/irverify/cycles_test.go b/ir/irverify/cycles_test.go index 51c41761d..d5bfbaaef 100644 --- a/ir/irverify/cycles_test.go +++ b/ir/irverify/cycles_test.go @@ -33,8 +33,8 @@ func examplesDoc(values ...ir.Value) *ir.Document { } // constructorValueOf returns a constructor value over constructorValue. -func constructorValueOf(constructorValue *ir.ConstructorValue) ir.Value { - return ir.Value{Kind: ir.ValueConstructor, Constructor: constructorValue} +func constructorValueOf(constructor *ir.ConstructorValue) ir.Value { + return ir.Value{Kind: ir.ValueConstructor, Constructor: constructor} } // listValue returns a list value over values. @@ -74,9 +74,9 @@ var cyclicDocs = []struct { { name: "a constructor that is both of its arguments", doc: func() *ir.Document { - constructorValue := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} - constructorValue.Args = []ir.Value{constructorValueOf(constructorValue), constructorValueOf(constructorValue)} - return examplesDoc(constructorValueOf(constructorValue)) + constructor := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} + constructor.Args = []ir.Value{constructorValueOf(constructor), constructorValueOf(constructor)} + return examplesDoc(constructorValueOf(constructor)) }, want: []string{ "document.Types[type/x/M].Examples[0].Value.Constructor.Args[0].Constructor", @@ -158,9 +158,9 @@ var cyclicDocs = []struct { // selfArgumentDoc is GitHub #573's reproducer: a constructor whose one argument // is a value holding the same constructor, as the first example of a model. func selfArgumentDoc() *ir.Document { - constructorValue := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} - constructorValue.Args = []ir.Value{constructorValueOf(constructorValue)} - return examplesDoc(constructorValueOf(constructorValue)) + constructor := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} + constructor.Args = []ir.Value{constructorValueOf(constructor)} + return examplesDoc(constructorValueOf(constructor)) } // groupsDoc returns a document whose one service holds operationGroups as its @@ -210,8 +210,8 @@ var sharedDocs = []struct { { name: "a constructor two examples share", doc: func() *ir.Document { - constructorValue := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} - return examplesDoc(constructorValueOf(constructorValue), constructorValueOf(constructorValue)) + constructor := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} + return examplesDoc(constructorValueOf(constructor), constructorValueOf(constructor)) }, }, { diff --git a/ir/irverify/declared.go b/ir/irverify/declared.go index 59d3b8aa0..8fe895e46 100644 --- a/ir/irverify/declared.go +++ b/ir/irverify/declared.go @@ -23,15 +23,15 @@ func checkDeclaredIDs(*ir.Document) walkCheck { var ids ir.IDReader var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - class, id, declares := ids.DeclaredIDOf(v) + visit: func(value reflect.Value, at ir.WalkPath) bool { + class, id, declares := ids.DeclaredIDOf(value) if !declares { return true } if keyed[class] { return true // the registry key is where these classes are read } - vs = appendDeclaredIDViolations(vs, v, class, id, at) + vs = appendDeclaredIDViolations(vs, value, class, id, at) return true }, report: reporting(&vs), diff --git a/ir/irverify/declared_internal_test.go b/ir/irverify/declared_internal_test.go index f2999034b..844e739a1 100644 --- a/ir/irverify/declared_internal_test.go +++ b/ir/irverify/declared_internal_test.go @@ -99,9 +99,9 @@ func TestCheckDeclaredIDs_ReachesEveryIDDeclaringNode(t *testing.T) { "this check and ir.IDDeclarations must find the same declarations (-ir +irverify)") } -// TestCheckDeclaredIDs_PopulatedIDsAreClean is the silent half. The fixture -// differs from the one above only in whether the identities are there, so -// nothing but the identity can be what the check reads. +// TestCheckDeclaredIDs_PopulatedIDsAreClean is the report-nothing half. The +// fixture differs from the one above only in whether the identities are there, +// so nothing but the identity can be what the check reads. func TestCheckDeclaredIDs_PopulatedIDsAreClean(t *testing.T) { t.Parallel() assert.Empty(t, declaredIDViolations(idBearingDoc(true))) diff --git a/ir/irverify/discriminators.go b/ir/irverify/discriminators.go new file mode 100644 index 000000000..d12d716a4 --- /dev/null +++ b/ir/irverify/discriminators.go @@ -0,0 +1,87 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package irverify + +import ( + "strconv" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/scratchstate" +) + +// checkDiscriminatorRoutes asserts no decode-only route spells a tag the +// discriminator already routes: by a Mapping entry or, on a union whose Mapping +// is empty, by a variant's type name (docs/ir/models.md#discriminator). A +// decoder takes the first spelling, so the second is dead, and a lowering +// wrote it. +func checkDiscriminatorRoutes(doc *ir.Document) []Violation { + var vs []Violation + var names scratchstate.Map[string, bool] + for id, typeDef := range doc.Types { + discriminator, union := discriminatorOf(typeDef) + if discriminator == nil || len(discriminator.DecodeOnlyRoutes) == 0 { + continue + } + var typeNames map[string]bool + if union != nil { + typeNames = variantTypeNames(doc, union, names.Emptied()) + } + for key := range discriminator.DecodeOnlyRoutes { + first, repeated := firstSpelling(discriminator, typeNames, key) + if !repeated { + continue + } + vs = append(vs, Violation{ + Code: "ir/discriminator-route-duplicate", + Message: "discriminator routes the tag " + strconv.Quote(key) + + " in DecodeOnlyRoutes, a second spelling of the route " + first, + Path: typePath(id) + ".Discriminator.DecodeOnlyRoutes[" + key + "]", + }) + } + } + return vs +} + +// discriminatorOf returns typeDef's discriminator, and typeDef itself where it +// is a union, whose empty Mapping routes by type name. +func discriminatorOf(typeDef ir.TypeDef) (*ir.Discriminator, *ir.Union) { + switch node := typeDef.(type) { + case *ir.Union: + if node == nil { + return nil, nil + } + return node.Discriminator, node + case *ir.Model: + if node == nil { + return nil, nil + } + return node.Discriminator, nil + default: + return nil, nil + } +} + +// variantTypeNames fills names, empty, with the tags union routes a variant by +// its type's name (ir.VariantNameRoute), and returns it. +func variantTypeNames(doc *ir.Document, union *ir.Union, names map[string]bool) map[string]bool { + for _, variant := range union.Variants { + if name, byName := ir.VariantNameRoute(union, doc.Types[variant.Type.Target]); byName { + names[name] = true + } + } + return names +} + +// firstSpelling reports whether discriminator already routes key before its +// DecodeOnlyRoutes do, and says by what: a Mapping entry, or one of typeNames, +// the variants' type names an empty Mapping on a union routes by. +func firstSpelling(discriminator *ir.Discriminator, typeNames map[string]bool, key string) (string, bool) { + if _, mapped := discriminator.Mapping[key]; mapped { + return "Mapping gives it", true + } + if typeNames[key] { + return "a variant's type name gives it beside an empty Mapping", true + } + return "", false +} diff --git a/ir/irverify/discriminators_test.go b/ir/irverify/discriminators_test.go new file mode 100644 index 000000000..0c499018e --- /dev/null +++ b/ir/irverify/discriminators_test.go @@ -0,0 +1,120 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package irverify_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// codeRouteDuplicate is the code of a tag one discriminator routes by two +// spellings. +const codeRouteDuplicate = "ir/discriminator-route-duplicate" + +// TestVerify_ARouteSpeltTwiceIsAViolation holds a union's discriminator to one +// spelling of each tag's route. A decoder routes by Mapping, or by a variant's +// type name where Mapping is empty, then by DecodeOnlyRoutes, so a tag either +// of the first already routes makes its decode-only route a second spelling. +// unionOf's variants name types whose name is "Leaf". +func TestVerify_ARouteSpeltTwiceIsAViolation(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + mapping map[string]ir.TypeID + decodeOnly map[string]ir.TypeID + repeated []string // the keys reported, in order + }{ + {name: "disjoint keys", mapping: map[string]ir.TypeID{"cat": "type/x/Leaf"}, decodeOnly: map[string]ir.TypeID{"Cat": "type/x/Leaf"}}, + {name: "a key beside no mapping naming no variant's type", decodeOnly: map[string]ir.TypeID{"Cat": "type/x/Leaf"}}, + {name: "a key in both", mapping: map[string]ir.TypeID{"cat": "type/x/Leaf"}, decodeOnly: map[string]ir.TypeID{"cat": "type/x/Leaf"}, repeated: []string{"cat"}}, + { + name: "two keys in both, one apart", + mapping: map[string]ir.TypeID{"a": "type/x/Leaf", "b": "type/x/Leaf", "c": "type/x/Leaf"}, + decodeOnly: map[string]ir.TypeID{"a": "type/x/Leaf", "b": "type/x/Leaf", "d": "type/x/Leaf"}, + repeated: []string{"a", "b"}, + }, + {name: "a variant's type name beside no mapping", decodeOnly: map[string]ir.TypeID{"Leaf": "type/x/Leaf"}, repeated: []string{"Leaf"}}, + {name: "a variant's type name beside an empty mapping", mapping: map[string]ir.TypeID{}, decodeOnly: map[string]ir.TypeID{"Leaf": "type/x/Leaf"}, repeated: []string{"Leaf"}}, + {name: "a variant's type name routed elsewhere", decodeOnly: map[string]ir.TypeID{"Leaf": "type/x/U"}, repeated: []string{"Leaf"}}, + {name: "a variant's type name beside a mapping keying others", mapping: map[string]ir.TypeID{"cat": "type/x/Leaf"}, decodeOnly: map[string]ir.TypeID{"Leaf": "type/x/Leaf"}}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + doc := unionOf("type/x/Leaf") + union, ok := doc.Types["type/x/U"].(*ir.Union) + require.True(t, ok) + union.WireTagged = true + union.Discriminator = &ir.Discriminator{PropertyName: "kind", Mapping: tc.mapping, DecodeOnlyRoutes: tc.decodeOnly} + + got := unionViolations(t, doc, codeRouteDuplicate) + + require.Len(t, got, len(tc.repeated), "one violation for each tag spelt twice") + for i, key := range tc.repeated { + assert.Equal(t, "types[type/x/U].Discriminator.DecodeOnlyRoutes["+key+"]", got[i].Path, "the violation locates the second spelling") + assert.Contains(t, got[i].Message, `"`+key+`"`) + } + }) + } +} + +// TestVerify_AVariantWhoseTypeIsUnnamedOrMissingRoutesNoName holds the +// type-name reading to the names a decoder can route by: a variant whose type +// has no name, or names no type of the registry, routes no tag, so the empty +// key and the key spelling the missing type's ID are each a route of their own. +func TestVerify_AVariantWhoseTypeIsUnnamedOrMissingRoutesNoName(t *testing.T) { + t.Parallel() + doc := unionOf("type/x/Leaf") + union, ok := doc.Types["type/x/U"].(*ir.Union) + require.True(t, ok) + doc.Types["type/x/Leaf"].Common().Name = ir.Naming{} + union.Variants = append(union.Variants, ir.Variant{Type: ir.TypeRef{Target: "type/x/Missing"}}) + union.WireTagged = true + union.Discriminator = &ir.Discriminator{PropertyName: "kind", DecodeOnlyRoutes: map[string]ir.TypeID{ + "": "type/x/Leaf", "type/x/Missing": "type/x/Leaf", "Missing": "type/x/Leaf", + }} + + assert.Empty(t, unionViolations(t, doc, codeRouteDuplicate)) +} + +// TestVerify_AModelDiscriminatorsRoutesAreHeldToo holds a model's +// discriminator to one spelling of each tag too: a key both maps hold. A +// hierarchy routes by its Mapping alone, never by a type name, so beside no +// mapping a key spelling one is a route of its own. +func TestVerify_AModelDiscriminatorsRoutesAreHeldToo(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + mapping map[string]ir.TypeID + repeated bool + }{ + {name: "a key in both", mapping: map[string]ir.TypeID{"Leaf": "type/x/Leaf"}, repeated: true}, + {name: "a type name beside no mapping"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + doc := closedDoc(&ir.Model{ + ID: "type/x/Base", + Name: named("Base"), + Discriminator: &ir.Discriminator{ + Property: "property/x/Base/kind", + Mapping: tc.mapping, + DecodeOnlyRoutes: map[string]ir.TypeID{"Leaf": "type/x/Leaf"}, + }, + }) + + got := unionViolations(t, doc, codeRouteDuplicate) + + if !tc.repeated { + assert.Empty(t, got) + return + } + require.Len(t, got, 1) + assert.Equal(t, "types[type/x/Base].Discriminator.DecodeOnlyRoutes[Leaf]", got[0].Path) + }) + } +} diff --git a/ir/irverify/docrefs.go b/ir/irverify/docrefs.go index 025c626b9..e23343509 100644 --- a/ir/irverify/docrefs.go +++ b/ir/irverify/docrefs.go @@ -25,11 +25,11 @@ var docsType = reflect.TypeFor[ir.Docs]() func checkDocRefs(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() != reflect.Struct || v.Type() != docsType { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() != reflect.Struct || value.Type() != docsType { return true } - docs, ok := reflect.TypeAssert[ir.Docs](v) + docs, ok := reflect.TypeAssert[ir.Docs](value) if !ok || len(docs.Refs) == 0 { return false // a Docs holds nothing else this check looks for } diff --git a/ir/irverify/document.go b/ir/irverify/document.go index fa778838c..41d6d2c0e 100644 --- a/ir/irverify/document.go +++ b/ir/irverify/document.go @@ -85,8 +85,8 @@ func isSHA256Hex(hash string) bool { return false } for i := range len(hash) { - c := hash[i] - if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + digit := hash[i] + if (digit < '0' || digit > '9') && (digit < 'a' || digit > 'f') { return false } } diff --git a/ir/irverify/duplicates.go b/ir/irverify/duplicates.go index b10afb7c3..c6f1fb472 100644 --- a/ir/irverify/duplicates.go +++ b/ir/irverify/duplicates.go @@ -54,11 +54,11 @@ func checkDuplicateIDs(*ir.Document) walkCheck { first := map[string]firstProperty{} differs := map[occurrence]bool{} return walkCheck{ - visit: func(v reflect.Value, _ ir.WalkPath) bool { - if v.Kind() != reflect.Struct || v.Type() != propertyType { + visit: func(value reflect.Value, _ ir.WalkPath) bool { + if value.Kind() != reflect.Struct || value.Type() != propertyType { return true } - id, got := v.FieldByName("ID").String(), fingerprintOf(v) + id, got := value.FieldByName("ID").String(), fingerprintOf(value) met, seen := first[id] if !seen { first[id] = firstProperty{fingerprint: got, met: 1} diff --git a/ir/irverify/duplicates_internal_test.go b/ir/irverify/duplicates_internal_test.go index 3a54631ec..f61c671d1 100644 --- a/ir/irverify/duplicates_internal_test.go +++ b/ir/irverify/duplicates_internal_test.go @@ -33,7 +33,7 @@ func TestCheckDuplicateIDs_TwoOperationsOnOneID(t *testing.T) { doc := docWithOperations(ir.Operation{ID: "operation/x"}, ir.Operation{ID: "operation/x"}) got := duplicateViolations(doc) - require.Len(t, got, 1, "the first declaration stands and only the second is reported") + require.Len(t, got, 1, "the first declaration holds and only the second is reported") assert.Equal(t, "ir/duplicate-operation-id", got[0].Code) assert.Equal(t, "document.Services[0].Groups[0].Operations[1]", got[0].Path) assert.Contains(t, got[0].Message, "document.Services[0].Groups[0].Operations[0]", @@ -101,7 +101,7 @@ func TestCheckDuplicateIDs_TwoRegistryEntriesOnOneNodeID(t *testing.T) { } // TestCheckDuplicateIDs_DistinctIDsAreClean is the other half of the proof: a -// check that cannot stay silent is no better than one that cannot fire. The +// check that cannot report nothing is no better than one that cannot fire. The // operations differ only in their IDs, so nothing but the ID can be what the // check reads. func TestCheckDuplicateIDs_DistinctIDsAreClean(t *testing.T) { @@ -162,7 +162,7 @@ func TestCheckDuplicateIDs_TwoDifferentPropertiesOnOnePropertyID(t *testing.T) { }} got := duplicateViolations(doc) - require.Len(t, got, 1, "the first declaration stands and only the second is reported") + require.Len(t, got, 1, "the first declaration holds and only the second is reported") assert.Equal(t, "ir/duplicate-property-id", got[0].Code) assert.Equal(t, "document.Types[type/x/B].Properties[0]", got[0].Path) assert.Contains(t, got[0].Message, string(dup)) diff --git a/ir/irverify/emptyrefs_test.go b/ir/irverify/emptyrefs_test.go index 1727c8c1a..40465339d 100644 --- a/ir/irverify/emptyrefs_test.go +++ b/ir/irverify/emptyrefs_test.go @@ -160,6 +160,19 @@ func TestVerify_EmptyRequiredReferenceIsAViolation(t *testing.T) { code: "ir/empty-type-ref", path: "document.Types[type/x/Base].Discriminator.Mapping[x]", }, + { + name: "Discriminator.DecodeOnlyRoutes, an empty value", + doc: closedDoc(&ir.Model{ + ID: "type/x/Base", + Name: named("base"), + Discriminator: &ir.Discriminator{ + Property: "property/x/Base/kind", + DecodeOnlyRoutes: map[string]ir.TypeID{"x": ""}, + }, + }), + code: "ir/empty-type-ref", + path: "document.Types[type/x/Base].Discriminator.DecodeOnlyRoutes[x]", + }, { name: "ResourceInfo.Lifecycle, an empty value", doc: &ir.Document{Services: []ir.Service{{ @@ -260,12 +273,14 @@ func TestVerify_AllowedEmptyReferencesAreClean(t *testing.T) { }, }, { - name: "empty maps: Service.Renames, Discriminator.Mapping, ResourceInfo.Lifecycle", + name: "empty maps: Service.Renames, Discriminator.Mapping and DecodeOnlyRoutes, ResourceInfo.Lifecycle", doc: &ir.Document{ Types: ir.TypeRegistry{"type/x/M": &ir.Model{ - ID: "type/x/M", - Name: named("m"), - Discriminator: &ir.Discriminator{PropertyName: "kind", Mapping: map[string]ir.TypeID{}}, + ID: "type/x/M", + Name: named("m"), + Discriminator: &ir.Discriminator{ + PropertyName: "kind", Mapping: map[string]ir.TypeID{}, DecodeOnlyRoutes: map[string]ir.TypeID{}, + }, }}, Services: []ir.Service{{ ID: "service/x/S", diff --git a/ir/irverify/entityrefs.go b/ir/irverify/entityrefs.go index 0af2e56d1..9f2a4d56b 100644 --- a/ir/irverify/entityrefs.go +++ b/ir/irverify/entityrefs.go @@ -50,8 +50,8 @@ func carriersOf(types ...reflect.Type) map[reflect.Type]replacementCarrier { // fieldIndex is the index of t's field name, which t declares itself. func fieldIndex(t reflect.Type, name string) int { - f, _ := t.FieldByName(name) - return f.Index[0] + field, _ := t.FieldByName(name) + return field.Index[0] } // checkEntityRefs asserts every ir.EntityRef names one entity, setting exactly @@ -62,16 +62,16 @@ func fieldIndex(t reflect.Type, name string) int { func checkEntityRefs(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() != reflect.Struct { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() != reflect.Struct { return true } - if v.Type() == entityRefType { - vs = appendEntityRefShape(vs, v, at) + if value.Type() == entityRefType { + vs = appendEntityRefShape(vs, value, at) return false } - if replacementCarrier, carries := replacementCarriers[v.Type()]; carries { - vs = appendSelfReplacement(vs, v, replacementCarrier, at) + if replacementCarrier, carries := replacementCarriers[value.Type()]; carries { + vs = appendSelfReplacement(vs, value, replacementCarrier, at) } return true }, @@ -105,17 +105,17 @@ func appendEntityRefShape(vs []Violation, ref reflect.Value, at ir.WalkPath) []V } // appendSelfReplacement reports each replacement the Deprecation of node, a -// carrier replacementCarrierValue indexes, names that is node itself: of its +// carrier replacementCarrier indexes, names that is node itself: of its // ID's class and value. -func appendSelfReplacement(vs []Violation, node reflect.Value, replacementCarrierValue replacementCarrier, at ir.WalkPath) []Violation { - dep := node.Field(replacementCarrierValue.deprecation) - own := node.Field(replacementCarrierValue.id).String() +func appendSelfReplacement(vs []Violation, node reflect.Value, replacementCarrier replacementCarrier, at ir.WalkPath) []Violation { + dep := node.Field(replacementCarrier.deprecation) + own := node.Field(replacementCarrier.id).String() if dep.IsNil() || own == "" { return vs } refs := dep.Elem().Field(replacedByIndex) for i := range refs.Len() { - if refs.Index(i).Field(replacementCarrierValue.ref).String() == own { + if refs.Index(i).Field(replacementCarrier.ref).String() == own { vs = append(vs, Violation{ Code: "ir/replaced-by-itself", Message: "deprecation names " + strconv.Quote(own) + ", the entity it deprecates, as its replacement", diff --git a/ir/irverify/entries.go b/ir/irverify/entries.go index bf944b484..65e1b3dca 100644 --- a/ir/irverify/entries.go +++ b/ir/irverify/entries.go @@ -12,8 +12,8 @@ import "reflect" // ready to use. // // A caller ranges with MapRange and reads each entry through what heldFor -// returns: no closure stands between them, so nothing escapes however the -// build inlines. +// returns: no closure sits between them, so nothing escapes however the build +// inlines. type entryReader struct { held map[reflect.Type]heldEntry } @@ -27,22 +27,22 @@ type heldEntry struct { apart bool } -// heldFor returns where r copies the entries of map m, making the key and value -// it keeps for m's type the first time that type is met. -func (r *entryReader) heldFor(m reflect.Value) heldEntry { - if !m.CanInterface() { +// heldFor returns where r copies the entries of map value, making the key and +// value it keeps for value's type the first time that type is met. +func (r *entryReader) heldFor(value reflect.Value) heldEntry { + if !value.CanInterface() { return heldEntry{apart: true} } - t := m.Type() + t := value.Type() if heldEntry, kept := r.held[t]; kept { return heldEntry } if r.held == nil { r.held = map[reflect.Type]heldEntry{} } - heldEntryValue := heldEntry{key: reflect.New(t.Key()).Elem(), value: reflect.New(t.Elem()).Elem()} - r.held[t] = heldEntryValue - return heldEntryValue + heldEntry := heldEntry{key: reflect.New(t.Key()).Elem(), value: reflect.New(t.Elem()).Elem()} + r.held[t] = heldEntry + return heldEntry } // read copies iter's current entry and returns its key and value, which the diff --git a/ir/irverify/entries_test.go b/ir/irverify/entries_test.go index da604e636..529d9eaa7 100644 --- a/ir/irverify/entries_test.go +++ b/ir/irverify/entries_test.go @@ -15,10 +15,10 @@ import ( // readEntries returns what entryReader reads of map m, key by key, ranging over // it as a check does. -func readEntries(entryReader *irverify.EntryReader, m reflect.Value) map[string]int64 { +func readEntries(entryReader *irverify.EntryReader, value reflect.Value) map[string]int64 { read := map[string]int64{} - held := entryReader.HeldFor(m) - for iter := m.MapRange(); iter.Next(); { + held := entryReader.HeldFor(value) + for iter := value.MapRange(); iter.Next(); { key, value := held.Read(iter) read[key.String()] = value.Int() } diff --git a/ir/irverify/enums.go b/ir/irverify/enums.go index 2ad231b9c..7c9f7617e 100644 --- a/ir/irverify/enums.go +++ b/ir/irverify/enums.go @@ -54,7 +54,7 @@ type enumRule struct { // wireEnum is the rule of enum E, declared by valid. func wireEnum[E ~string](valid func(E) bool, code, what string) enumRule { - return enumRule{valid: func(s string) bool { return valid(E(s)) }, code: code, what: what} + return enumRule{valid: func(text string) bool { return valid(E(text)) }, code: code, what: what} } // walkEnums are the enums checkEnums holds, each at the one type that carries @@ -98,12 +98,12 @@ var enumPath = func() map[reflect.Type]bool { func checkEnums(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - rule, held := walkEnums[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + rule, held := walkEnums[value.Type()] if !held { - return enumPath[v.Type()] + return enumPath[value.Type()] } - if value := v.String(); !rule.valid(value) { + if value := value.String(); !rule.valid(value) { vs = append(vs, Violation{ Code: rule.code, Message: rule.what + " " + strconv.Quote(value), @@ -121,9 +121,9 @@ func checkEnums(*ir.Document) walkCheck { // the walk prunes to, so these are read from the registry. func checkModelEnums(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - model, isModel := td.(*ir.Model) - if !isModel || ir.IsNilTypeDef(td) { + for id, typeDef := range doc.Types { + model, isModel := typeDef.(*ir.Model) + if !isModel || ir.IsNilTypeDef(typeDef) { continue } if !model.Additional.Valid() { diff --git a/ir/irverify/enums_internal_test.go b/ir/irverify/enums_internal_test.go index 8c778eff8..261370324 100644 --- a/ir/irverify/enums_internal_test.go +++ b/ir/irverify/enums_internal_test.go @@ -44,7 +44,7 @@ func declaredEnums(t *testing.T) []string { } // tableKeys returns the keys of table, a map keyed by a type name or by a -// reflect.Type, as the names of the types they stand for. +// reflect.Type, as the names of the types they name. func tableKeys(t *testing.T, table any) map[string]bool { t.Helper() v := reflect.ValueOf(table) @@ -170,9 +170,9 @@ func TestPrunedChecks_SeeOnlyTheirPathWhateverTheDocumentHolds(t *testing.T) { t.Parallel() shown := func(doc *ir.Document) int { visitor, count := check(doc), 0 - ir.WalkValues(doc, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + ir.WalkValues(doc, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { count++ - return visitor.visit(v, at) + return visitor.visit(value, at) })) return count } diff --git a/ir/irverify/enums_test.go b/ir/irverify/enums_test.go index d508281fb..7fca4143c 100644 --- a/ir/irverify/enums_test.go +++ b/ir/irverify/enums_test.go @@ -114,7 +114,7 @@ func enumCases() map[string]enumCase { }, code: "ir/unknown-related-role", path: "document.Diagnostics[0].Related[0].Role", - valid: []string{string(ir.RelatedKept), string(ir.RelatedDecided)}, + valid: []string{string(ir.RelatedChosen), string(ir.RelatedDecided)}, invalid: []string{"bogus", ""}, }, "Severity": { diff --git a/ir/irverify/examples.go b/ir/irverify/examples.go index a99885120..cf825e435 100644 --- a/ir/irverify/examples.go +++ b/ir/irverify/examples.go @@ -23,13 +23,13 @@ var examplesType = reflect.TypeFor[[]ir.Example]() func checkExampleArms(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != examplesType { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != examplesType { return true } owner, _, _ := at.Field() - for i := range v.Len() { - if ex, ok := reflect.TypeAssert[*ir.Example](v.Index(i).Addr()); ok { + for i := range value.Len() { + if ex, ok := reflect.TypeAssert[*ir.Example](value.Index(i).Addr()); ok { vs = appendExampleViolations(vs, ex, owner == operationType, exampleSite{list: at, index: i}) } } diff --git a/ir/irverify/examples_test.go b/ir/irverify/examples_test.go index 502799641..eebf963bc 100644 --- a/ir/irverify/examples_test.go +++ b/ir/irverify/examples_test.go @@ -33,7 +33,7 @@ func exampleFindings(doc *ir.Document) []string { // scenarioErrorExample is the error a scenario ends in. func scenarioErrorExample() *ir.ErrorExample { - return &ir.ErrorExample{Type: ir.TypeRef{Target: "type/x/M"}, Content: scenarioValue} + return &ir.ErrorExample{Type: ir.TypeRef{Target: "type/x/M"}, Content: scenario} } // TestVerify_ExampleArms holds an example to the arms its carrier takes. Only an @@ -53,7 +53,7 @@ func TestVerify_ExampleArms(t *testing.T) { want []string }{ {"a model's example with a scenario's three arms", modelExamples, ir.Example{ - Name: "ex", Input: &ir.ScenarioInput{}, Output: &scenarioValue, Error: scenarioErrorExample(), + Name: "ex", Input: &ir.ScenarioInput{}, Output: &scenario, Error: scenarioErrorExample(), }, []string{ armMisplaced + " " + model + ".Error: example holds a scenario's error, and only an operation's example may", armMisplaced + " " + model + ".Input: example holds a scenario's input, and only an operation's example may", @@ -61,22 +61,22 @@ func TestVerify_ExampleArms(t *testing.T) { outcomeTwice + " " + model + ".Error: example ends in both an output and an error", }}, {"an operation's example with a value and headers", operationExamples, ir.Example{ - Value: &scenarioValue, Headers: &scenarioValue, Output: &scenarioValue, + Value: &scenario, Headers: &scenario, Output: &scenario, }, []string{ armMisplaced + " " + operation + ".Headers: operation's example holds headers, and a scenario states its input and its outcome", armMisplaced + " " + operation + ".Value: operation's example holds a value, and a scenario states its input and its outcome", }}, {"an operation's example ending in both", operationExamples, ir.Example{ - Input: &ir.ScenarioInput{}, Output: &scenarioValue, Error: scenarioErrorExample(), + Input: &ir.ScenarioInput{}, Output: &scenario, Error: scenarioErrorExample(), }, []string{ outcomeTwice + " " + operation + ".Error: example ends in both an output and an error", }}, // The valid twins: each is what its carrier takes, and draws nothing. {"a model's example holding a value and headers", modelExamples, ir.Example{ - Name: "ex", Value: &scenarioValue, Headers: &scenarioValue, + Name: "ex", Value: &scenario, Headers: &scenario, }, nil}, {"an operation's scenario ending in an output", operationExamples, ir.Example{ - Input: &ir.ScenarioInput{}, Output: &scenarioValue, + Input: &ir.ScenarioInput{}, Output: &scenario, }, nil}, {"an operation's scenario ending in an error", operationExamples, ir.Example{ Input: &ir.ScenarioInput{}, Error: scenarioErrorExample(), @@ -109,7 +109,7 @@ func operationExamples(doc *ir.Document) *[]ir.Example { // struct alone misses the rest. func TestVerify_ExampleArmsAreHeldAtEveryCarrier(t *testing.T) { t.Parallel() - example := []ir.Example{{Output: &scenarioValue}} + example := []ir.Example{{Output: &scenario}} plant := map[string]func(doc *ir.Document){ "document.Types[type/x/M].Examples[0].Output": func(document *ir.Document) { document.Types["type/x/M"].Common().Examples = example @@ -157,15 +157,15 @@ func TestVerify_ExampleArmsAreHeldAtEveryCarrier(t *testing.T) { // exampleGrowth is a document of n models, each with the two examples a clean // document carries, and a property with one. -func exampleGrowth(n int) *ir.Document { +func exampleGrowth(count int) *ir.Document { doc := scenarioBase() - for i := range n { + for i := range count { id := ir.TypeID(fmt.Sprintf("type/x/G%d", i)) model := &ir.Model{ID: id, Name: named("g"), Properties: []ir.Property{{ ID: ir.PropertyID(fmt.Sprintf("property/x/G%d/a", i)), Name: named("a"), Type: ir.TypeRef{Target: "type/primitive/string"}, - Examples: []ir.Example{{Value: &scenarioValue}}, + Examples: []ir.Example{{Value: &scenario}}, }}} - model.Examples = []ir.Example{{Name: "a", Value: &scenarioValue}, {Name: "b", Value: &scenarioValue, Headers: &scenarioValue}} + model.Examples = []ir.Example{{Name: "a", Value: &scenario}, {Name: "b", Value: &scenario, Headers: &scenario}} doc.Types[id] = model } return doc diff --git a/ir/irverify/export_test.go b/ir/irverify/export_test.go index 79dbe9ddb..02ab48045 100644 --- a/ir/irverify/export_test.go +++ b/ir/irverify/export_test.go @@ -18,7 +18,7 @@ type EntryReader = entryReader type HeldEntry = heldEntry // HeldFor is heldFor, for this package's external tests. -func (r *entryReader) HeldFor(m reflect.Value) HeldEntry { return r.heldFor(m) } +func (r *entryReader) HeldFor(value reflect.Value) HeldEntry { return r.heldFor(value) } // Read is read, for this package's external tests. func (h heldEntry) Read(iter *reflect.MapIter) (key, value reflect.Value) { return h.read(iter) } diff --git a/ir/irverify/headers.go b/ir/irverify/headers.go index c939dd039..7283e77be 100644 --- a/ir/irverify/headers.go +++ b/ir/irverify/headers.go @@ -51,11 +51,11 @@ var headerPath = map[reflect.Type]bool{ func checkPrefixHeaders(doc *ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != headerType { - return operationPath[v.Type()] || headerPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != headerType { + return operationPath[value.Type()] || headerPath[value.Type()] } - if header, ok := reflect.TypeAssert[ir.Header](v); ok && header.Prefix != nil { + if header, ok := reflect.TypeAssert[ir.Header](value); ok && header.Prefix != nil { vs = appendPrefixHeaderViolations(vs, doc, &header, at) } return false @@ -91,14 +91,14 @@ func appendPrefixHeaderViolations(vs []Violation, doc *ir.Document, header *ir.H // map, ends and reports false. func reachesMap(types ir.TypeRegistry, ref ir.TypeRef) bool { for range len(types) + 1 { - td, ok := types[ref.Target] - if !ok || ir.IsNilTypeDef(td) { + typeDef, ok := types[ref.Target] + if !ok || ir.IsNilTypeDef(typeDef) { return true } - if _, isMap := td.(*ir.MapT); isMap { + if _, isMap := typeDef.(*ir.MapT); isMap { return true } - base, decorates := ir.Decorated(td) + base, decorates := ir.Decorated(typeDef) if !decorates { return false } diff --git a/ir/irverify/headers_test.go b/ir/irverify/headers_test.go index b7154dfc5..ed47ba353 100644 --- a/ir/irverify/headers_test.go +++ b/ir/irverify/headers_test.go @@ -24,14 +24,14 @@ func prefixHeaderTypes() ir.TypeRegistry { return &ir.Model{ID: id, Anonymous: true, Base: &ir.TypeRef{Target: base}} } types := ir.TypeRegistry{"type/x/Nil": (*ir.Model)(nil)} - for _, td := range []ir.TypeDef{ + for _, typeDef := range []ir.TypeDef{ &ir.MapT{ID: "type/x/Meta", Name: named("meta"), Value: stringType}, decorates("type/x/Meta/decorated", "type/x/Meta"), &ir.Model{ID: "type/x/Name", Name: named("name")}, decorates("type/x/loop/a", "type/x/loop/b"), decorates("type/x/loop/b", "type/x/loop/a"), } { - types[td.Common().ID] = td + types[typeDef.Common().ID] = typeDef } return types } diff --git a/ir/irverify/idempotency.go b/ir/irverify/idempotency.go index 46a74bf66..ab6947ec2 100644 --- a/ir/irverify/idempotency.go +++ b/ir/irverify/idempotency.go @@ -21,11 +21,11 @@ var idempotencyType = reflect.TypeFor[ir.Idempotency]() func checkIdempotency(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != idempotencyType { - return operationPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != idempotencyType { + return operationPath[value.Type()] } - idem, ok := reflect.TypeAssert[ir.Idempotency](v) + idem, ok := reflect.TypeAssert[ir.Idempotency](value) if !ok || (idem.TokenParam != "") == (idem.Kind == ir.IdempotencyToken) { return false } diff --git a/ir/irverify/ids.go b/ir/irverify/ids.go index 8763d2afd..d69808812 100644 --- a/ir/irverify/ids.go +++ b/ir/irverify/ids.go @@ -25,11 +25,11 @@ import ( // kind derives. func checkIDs(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - if ir.IsNilTypeDef(td) { + for id, typeDef := range doc.Types { + if ir.IsNilTypeDef(typeDef) { continue // checkRegistryKeys reports the nil entry itself } - vs = appendRegistryIDDefect(vs, ir.IDKindType, "types", string(id), string(td.Common().ID), td.Common().Provenance) + vs = appendRegistryIDDefect(vs, ir.IDKindType, "types", string(id), string(typeDef.Common().ID), typeDef.Common().Provenance) } for id, scheme := range doc.Auth { vs = appendRegistryIDDefect(vs, ir.IDKindAuth, "auth", string(id), string(scheme.ID), scheme.Provenance) @@ -162,13 +162,13 @@ func recordedPointer(node reflect.Value) jsontext.Pointer { // elsewhere is held by this alone. func checkPrimitiveIDs(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - if ir.IsNilTypeDef(td) || !keyedByOwnID(string(id), string(td.Common().ID)) { + for id, typeDef := range doc.Types { + if ir.IsNilTypeDef(typeDef) || !keyedByOwnID(string(id), string(typeDef.Common().ID)) { continue // checkRegistryKeys reports the entry itself } - primitive, isPrimitive := td.(*ir.Primitive) + primitive, isPrimitive := typeDef.(*ir.Primitive) if !isPrimitive { - vs = appendReservedSpace(vs, id, td.Kind()) + vs = appendReservedSpace(vs, id, typeDef.Kind()) continue } if want := ir.PrimitiveTypeID(primitive.PrimitiveKind); id != want { diff --git a/ir/irverify/indices.go b/ir/irverify/indices.go index 9e1a101cf..0f390d2db 100644 --- a/ir/irverify/indices.go +++ b/ir/irverify/indices.go @@ -28,9 +28,9 @@ func checkIndices(*ir.Document) walkCheck { var vs []Violation var reader entryReader return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() == reflect.Struct && v.Type() == operationType { - vs = appendResponseIndexViolations(vs, &reader, v, at) + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() == reflect.Struct && value.Type() == operationType { + vs = appendResponseIndexViolations(vs, &reader, value, at) } return true }, @@ -40,15 +40,15 @@ func checkIndices(*ir.Document) walkCheck { // appendResponseIndexViolations appends to vs a violation per SuccessStatus key // on one operation's HTTP bindings that addresses no response it declares; -// entryReaderValue reads each SuccessStatus map. Keys need no sorting first: +// entryReader reads each SuccessStatus map. Keys need no sorting first: // every violation carries its own key in Path, and Verify orders the whole // result by (Code, Path) before returning it. -func appendResponseIndexViolations(vs []Violation, entryReaderValue *entryReader, operation reflect.Value, at ir.WalkPath) []Violation { +func appendResponseIndexViolations(vs []Violation, entryReader *entryReader, operation reflect.Value, at ir.WalkPath) []Violation { declared := operation.FieldByName("Responses").Len() bindings := operation.FieldByName("Bindings").FieldByName("HTTP") for i := range bindings.Len() { status := bindings.Index(i).FieldByName("SuccessStatus") - held := entryReaderValue.heldFor(status) + held := entryReader.heldFor(status) for iter := status.MapRange(); iter.Next(); { key, _ := held.read(iter) if index := int(key.Int()); index < 0 || index >= declared { diff --git a/ir/irverify/indices_internal_test.go b/ir/irverify/indices_internal_test.go index 6493babe6..6f3275128 100644 --- a/ir/irverify/indices_internal_test.go +++ b/ir/irverify/indices_internal_test.go @@ -145,43 +145,63 @@ var integerFields = map[string]string{ // The ir package's own traversal machinery, which is not IR data at all: the // scan reaches every integer field the package declares, and classifying one // costs less than a filter that could hide a real index behind it. - "refKey.ptr": "address that identifies a reference the walk has met, not a position", - "refKey.n": "slice length that identifies a reference the walk has met, not a position", - "descentRef.n": "slice length that identifies a reference a traversal is inside, not a position", - "insideRef.depth": "how many steps led the walk into a reference, not a position in any IR slice", - "WalkPath.depth": "how many of the walk's steps lead to a value, not a position in any IR slice", - "pathStep.kind": "how a step reaches its value, an enumeration rather than a position", - "pathStep.n": "the field, element or integer map key a step took, set by the walk as it took it, not IR data", - "pathStep.form": "how a step holds the map key it took, an enumeration rather than a position", - "mapEntry.number": "an integer map key the walk copied to order and spell it, not IR data", - "mapEntry.form": "how an entry holds its map key, an enumeration rather than a position", - "valueWalk.all": "the set of a walk's visitors, one bit each, not a position", - "valueWalk.limit": "how many values a walk may show each visitor, a count", - "valueWalk.count": "how many values a traversal has shown any visitor, a count", - "valueWalk.pruned": "how many values a traversal showed beneath each visitor's pruning, counts", - "valueWalk.cut": "the set of a walk's visitors shown their limit, one bit each, not a position", - "stepLimit.left": "how many steps a typed walk may still take, a count", - "valueWalk.shown": "how many values a walk has shown, which spaces its asks of a context, not a position", - "entryFrame.base": "where a map's entries start on the traversal's own stack, not a position in any IR slice", - "entryFrame.end": "where a map's entries end on the traversal's own stack, not a position in any IR slice", - "entryFrame.slot": "the first of a map's slots in the traversal's own copy storage, not a position in any IR slice", - "entryStore.used": "how many slots of the traversal's own copy storage are in use, not a position in any IR slice", - "flattener.met": "the order a flattening met each model in, or a mark, not a position in any IR slice", - "flattener.index": "where a wire name sits among a flattening's own members, not a position in any IR slice", - "flattener.aliasOf": "where an alias scalar's chain end sits in a flattening's own aliasEnds, " + - "not a position in any IR slice", - "flattener.steps": "how much a flattening has read, not a position", + "refKey.ptr": "address that identifies a reference the walk has met, not a position", + "refKey.n": "slice length that identifies a reference the walk has met, not a position", + "descentRef.n": "slice length that identifies a reference a traversal is inside, not a position", + "insideRef.depth": "how many steps led the walk into a reference, not a position in any IR slice", + "WalkPath.depth": "how many of the walk's steps lead to a value, not a position in any IR slice", + "pathStep.kind": "how a step reaches its value, an enumeration rather than a position", + "pathStep.n": "the field, element or integer map key a step took, set by the walk as it took it, not IR data", + "pathStep.form": "how a step holds the map key it took, an enumeration rather than a position", + "mapEntry.number": "an integer map key the walk copied to order and spell it, not IR data", + "mapEntry.form": "how an entry holds its map key, an enumeration rather than a position", + "valueWalk.all": "the set of a walk's visitors, one bit each, not a position", + "valueWalk.limit": "how many values a walk may show each visitor, a count", + "valueWalk.count": "how many values a traversal has shown any visitor, a count", + "valueWalk.pruned": "how many values a traversal showed beneath each visitor's pruning, counts", + "valueWalk.cut": "the set of a walk's visitors shown their limit, one bit each, not a position", + "stepLimit.stepsLeft": "how many steps a typed walk may still take, a count", + "valueWalk.shown": "how many values a walk has shown, which spaces its asks of a context, not a position", + "entryFrame.base": "where a map's entries start on the traversal's own stack, not a position in any IR slice", + "entryFrame.end": "where a map's entries end on the traversal's own stack, not a position in any IR slice", + "entryFrame.slot": "the first of a map's slots in the traversal's own copy storage, not a position in any IR slice", + "entryStore.used": "how many slots of the traversal's own copy storage are in use, not a position in any IR slice", + "flattener.index": "where a wire name sits among a flattening's own members, not a position in any IR slice", + "flattener.aliasReads": "how many alias scalars a flattening's own alias index has read, a count", + "flattener.steps": "how much a flattening has read, not a position", "MemberReader.own": "where each declaration of a wire name sits in a model's own Properties, read off " + "that slice by the reader, not IR data", "MemberReader.steps": "how much a member reader's walks have read, not a position", - "frame.next": "the next composition entry a flattening follows, counted across Base, Implements and Mixins", - "frame.number": "the order a flattening met a model in, not a position in any IR slice", - "frame.low": "Tarjan's low-link of a model a flattening met, not a position in any IR slice", - "frame.since": "how many models a flattening had finished, a length of its own list, not a position", - "narrowState.at": "where a union sits in a narrowing walk's own list of variants to read, not a position in any IR slice", - "walked.steps": "how much a narrowing walk has read, not a position", - "loggedPath.shared": "how many steps a kept path shares with the one kept before it, not a position in any IR slice", - "loggedPath.end": "where a kept path's own steps end in its log's storage, not a position in any IR slice", + "countedComponents.of": "where a model's composition component sits in a property-count reader's own lists, " + + "not a position in any IR slice", + "narrowState.at": "where a union sits in a narrowing walk's own list of variants to read, not a position in any IR slice", + "walked.steps": "how much a narrowing walk has read, not a position", + "loggedPath.shared": "how many steps a kept path shares with the one kept before it, not a position in any IR slice", + "loggedPath.end": "where a kept path's own steps end in its log's storage, not a position in any IR slice", + + // An alias chain index's own state, and what its readers keep beside it: + // places in the index's own list of the types it has read, never IR data. + "AliasChainIndex.at": "where each type an index has read sits in its own entries, not a position in any IR slice", + "aliasChainEntry.end": "where an alias's chain end sits in its index's own entries, not a position in any IR slice", + "aliasChainEntry.jumps": "where an alias's ancestors sit in its index's own entries, not a position in any IR slice", + "aliasChainEntry.depth": "how many aliases lie above a chain's end, a count", + "aliasChainEntry.state": "how far an index has read a type, not a position", + "ConstraintIntersection.disagreeing": "the keywords no one value holds, one bit each, not a position", + "keywordSlot.count": "where a Constraints holds a count keyword, the keyword's own value, not a position", + "AliasChainAnswers.answers": "keyed by where a type sits in its index's own entries, not a position in any IR slice", + + // A value admission reader's walks, which no document holds either. + "admissionSearch.depth": "how deep into the value its node lies, a count", + "admissionAnswer.admission": "a reader's answer, an enumeration, not a position", + "admissionCall.judgmentsLeft": "how many judgments an Admits call may still take, a count", + "patternMatcher.size": "the work a compiled pattern weighs, counts written out, not a position", + "patternScan.sizes": "the work each open group of a scanned pattern weighs, not a position", + "patternScan.lastSize": "the work the item a quantifier would repeat weighs, not a position", + "patternScan.total": "the work a scanned pattern weighs so far, not a position", + "patternScan.last": "what a scan read last, an enumeration rather than a position", + "enumMembers.shallowest": "the least depth a list or object member is spelled at, a count of levels", + "classMember.width": "how many bytes of a pattern a class member spans, a count", + "enumMembers.count": "how many members an enum lists, a count", // An ir.Editor's own state, which is no part of a document either. "serviceTree.work": "how many nodes an edit has stepped through, and elements it has built, in the service tree, a count", diff --git a/ir/irverify/inferred.go b/ir/irverify/inferred.go index eddcabd3c..55bf6d2d3 100644 --- a/ir/irverify/inferred.go +++ b/ir/irverify/inferred.go @@ -27,15 +27,15 @@ var ( func checkInferred(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() == partEncodingType { - vs = append(vs, partMarkerViolations(v, at)...) + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() == partEncodingType { + vs = append(vs, partMarkerViolations(value, at)...) return true } - if v.Type() != inferredType { + if value.Type() != inferredType { return true } - if list := ir.Inferred(v.String()); !list.IsCanonical() { + if list := ir.Inferred(value.String()); !list.IsCanonical() { vs = append(vs, Violation{ Code: "ir/inferred-not-canonical", Message: "inferred marker " + strconv.Quote(string(list)) + " is not the list " + diff --git a/ir/irverify/interactions.go b/ir/irverify/interactions.go index 1f1c536c5..cca20cd38 100644 --- a/ir/irverify/interactions.go +++ b/ir/irverify/interactions.go @@ -58,33 +58,33 @@ func checkInteractions(*ir.Document) walkCheck { var stops scratchstate.Map[ir.PageStop, int] bodyless := false // the operation the walk is in sends no request body return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - switch v.Type() { + visit: func(value reflect.Value, at ir.WalkPath) bool { + switch value.Type() { case operationType: - operation, ok := reflect.TypeAssert[ir.Operation](v) + operation, ok := reflect.TypeAssert[ir.Operation](value) bodyless = ok && operation.Request == nil if ok { vs = appendScenarioViolations(vs, &operation, at) } return true case inputPathType: - if in, ok := reflect.TypeAssert[ir.InputPath](v); ok { + if in, ok := reflect.TypeAssert[ir.InputPath](value); ok { vs = appendInputViolation(vs, in, bodyless, at) } return false case paginationType: - if pg, ok := reflect.TypeAssert[ir.Pagination](v); ok { + if pg, ok := reflect.TypeAssert[ir.Pagination](value); ok { vs = appendStopViolations(vs, pg.Stop, at, &stops) vs = appendFlagViolation(vs, pg, at) } return true case streamDetailType: - if sd, ok := reflect.TypeAssert[ir.StreamDetail](v); ok { + if sd, ok := reflect.TypeAssert[ir.StreamDetail](value); ok { vs = appendTerminatorViolation(vs, sd.Terminator, at) } return true default: - return operationPath[v.Type()] || interactionPath[v.Type()] + return operationPath[value.Type()] || interactionPath[value.Type()] } }, report: reporting(&vs), @@ -141,8 +141,8 @@ func appendScenarioViolations(vs []Violation, operation *ir.Operation, at ir.Wal // bindsIntoBody reports whether any HTTP binding of operation binds a parameter // into the request body, whole or by property. func bindsIntoBody(operation *ir.Operation) bool { - for _, b := range operation.Bindings.HTTP { - for _, pb := range b.ParamBindings { + for _, binding := range operation.Bindings.HTTP { + for _, pb := range binding.ParamBindings { if pb.Location == ir.HTTPLocationBody || pb.Location == ir.HTTPLocationBodyProperty { return true } diff --git a/ir/irverify/irverify.go b/ir/irverify/irverify.go index 6137a8372..78321c79f 100644 --- a/ir/irverify/irverify.go +++ b/ir/irverify/irverify.go @@ -60,6 +60,8 @@ func verify(doc *ir.Document, walk walkFunc) []Violation { vs = append(vs, checkUnresolvedSchemes(doc)...) vs = append(vs, checkOAuthScopes(doc)...) vs = append(vs, checkUnions(doc)...) + vs = append(vs, checkDiscriminatorRoutes(doc)...) + vs = append(vs, checkDecidedNodes(doc)...) vs = append(vs, checkMaps(doc)...) vs = append(vs, checkMapKeys(doc)...) vs = append(vs, checkCatchAlls(doc)...) @@ -146,8 +148,8 @@ type walkCheck struct { } // Visit calls c.visit, so a walkCheck is an ir.Visitor. -func (c walkCheck) Visit(v reflect.Value, at ir.WalkPath) bool { - return c.visit != nil && c.visit(v, at) +func (c walkCheck) Visit(value reflect.Value, at ir.WalkPath) bool { + return c.visit != nil && c.visit(value, at) } // Cycle calls c.cycle, so a walkCheck is an ir.CycleVisitor. @@ -266,8 +268,8 @@ func walkVisitors(doc *ir.Document, checks []func(*ir.Document) walkCheck) (*ir. // a malformed document. The walk-based checks already tolerate nil entries. func checkRegistryKeys(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - if ir.IsNilTypeDef(td) { + for id, typeDef := range doc.Types { + if ir.IsNilTypeDef(typeDef) { vs = append(vs, Violation{ Code: "ir/nil-type", Message: "types registry has a nil type definition", @@ -275,7 +277,7 @@ func checkRegistryKeys(doc *ir.Document) []Violation { }) continue } - vs = registryKey(vs, "type", "types", string(id), string(td.Common().ID)) + vs = registryKey(vs, "type", "types", string(id), string(typeDef.Common().ID)) } for id, ch := range doc.Channels { vs = registryKey(vs, "channel", "channels", string(id), string(ch.ID)) diff --git a/ir/irverify/irverify_corpus_test.go b/ir/irverify/irverify_corpus_test.go index 5382f7842..9ba9366d4 100644 --- a/ir/irverify/irverify_corpus_test.go +++ b/ir/irverify/irverify_corpus_test.go @@ -126,11 +126,11 @@ func TestVerify_ACleanComponentCostsNothing(t *testing.T) { // scaledDocument compiles a spec of n components, each an operation and the // schema it returns, which reach every walking check, and requires the // document to be clean. -func scaledDocument(t *testing.T, n int) *ir.Document { +func scaledDocument(t *testing.T, count int) *ir.Document { t.Helper() var spec strings.Builder spec.WriteString("openapi: 3.1.0\ninfo: {title: scaled, version: '1'}\npaths:\n") - for i := range n { + for i := range count { fmt.Fprintf(&spec, ` /pets%[1]d/{id}: get: operationId: getPet%[1]d @@ -146,7 +146,7 @@ func scaledDocument(t *testing.T, n int) *ir.Document { } spec.WriteString("components:\n responses:\n Missing:\n description: missing\n" + " headers: {X-Rate: {schema: {type: integer}}}\n schemas:\n") - for i := range n { + for i := range count { fmt.Fprintf(&spec, ` Pet%d: type: object x-kept: {a: [1, b]} @@ -236,8 +236,8 @@ func unmodeledKeys(doc *ir.Document) []string { } } } - for _, td := range doc.Types { - collect(td.Common().Unmodeled) + for _, typeDef := range doc.Types { + collect(typeDef.Common().Unmodeled) } slices.Sort(keys) return keys diff --git a/ir/irverify/irverify_cut_sweep_internal_test.go b/ir/irverify/irverify_cut_sweep_internal_test.go index 7ed323413..a67eed619 100644 --- a/ir/irverify/irverify_cut_sweep_internal_test.go +++ b/ir/irverify/irverify_cut_sweep_internal_test.go @@ -25,21 +25,21 @@ const cutVerifyPoints = 16 // then none, recording in cut that one went unshown; it tells inner of the // cycles the walk meets while inner is shown values. type cuttingVisitor struct { - inner ir.Visitor - left int - cut *bool + inner ir.Visitor + valuesLeft int + cut *bool } var _ ir.CycleVisitor = (*cuttingVisitor)(nil) // Visit shows v to the inner visitor while the limit lasts. -func (c *cuttingVisitor) Visit(v reflect.Value, at ir.WalkPath) bool { - if c.left == 0 { +func (c *cuttingVisitor) Visit(value reflect.Value, at ir.WalkPath) bool { + if c.valuesLeft == 0 { *c.cut = true return false } - c.left-- - return c.inner.Visit(v, at) + c.valuesLeft-- + return c.inner.Visit(value, at) } // Cycle tells the inner visitor of a cycle, if it asks to be told. @@ -51,12 +51,12 @@ func (c *cuttingVisitor) Cycle(at, entered ir.WalkPath, ref reflect.Type) { // cutAt returns a walk that shows each visitor at most n values, as a walk cut // short by the limit does, and says it stopped once one went unshown. -func cutAt(n int) walkFunc { +func cutAt(count int) walkFunc { return func(root any, path string, visitors ...ir.Visitor) bool { cut := false held := make([]ir.Visitor, len(visitors)) for i, visitor := range visitors { - held[i] = &cuttingVisitor{inner: visitor, left: n, cut: &cut} + held[i] = &cuttingVisitor{inner: visitor, valuesLeft: count, cut: &cut} } return ir.WalkValues(root, path, held...) || cut } @@ -81,8 +81,8 @@ func violationKeys(vs []Violation) map[string]int { func TestVerify_ACutWalkClaimsNothingTheWholeRunLacks(t *testing.T) { t.Parallel() var docs int - err := filepath.WalkDir("../../testdata", func(path string, d fs.DirEntry, err error) error { - if err != nil || d.IsDir() || !strings.HasSuffix(path, ".golden.json") { + err := filepath.WalkDir("../../testdata", func(path string, dirEntry fs.DirEntry, err error) error { + if err != nil || dirEntry.IsDir() || !strings.HasSuffix(path, ".golden.json") { return err } doc, err := irtest.ReadGolden(path) diff --git a/ir/irverify/irverify_messages_test.go b/ir/irverify/irverify_messages_test.go index 2cf6c6e81..9bd110f9d 100644 --- a/ir/irverify/irverify_messages_test.go +++ b/ir/irverify/irverify_messages_test.go @@ -21,8 +21,8 @@ const illFormed = "caf\xe9" // typesDoc returns a document holding types, keyed by their own IDs. func typesDoc(types ...ir.TypeDef) *ir.Document { doc := &ir.Document{IRVersion: ir.IRVersion, Types: ir.TypeRegistry{}} - for _, td := range types { - doc.Types[td.Common().ID] = td + for _, typeDef := range types { + doc.Types[typeDef.Common().ID] = typeDef } return doc } @@ -291,16 +291,45 @@ func messageCases() []messageCase { return typesDoc(model) }, "ir/value-missing-payload", `value of kind "number" leaves Number empty, which is no value of that kind`}, {"cyclic structure", func() *ir.Document { - constructorValue := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} - constructorValue.Args = []ir.Value{constructorValueOf(constructorValue)} + constructor := &ir.ConstructorValue{Scalar: "type/x/S", Name: "from"} + constructor.Args = []ir.Value{constructorValueOf(constructor)} model := namedModel(ir.TypeID("type/x/" + illFormed)) - model.Examples = []ir.Example{{Value: new(constructorValueOf(constructorValue))}} + model.Examples = []ir.Example{{Value: new(constructorValueOf(constructor))}} return typesDoc(model, &ir.Scalar{ID: "type/x/S", Name: named("s"), Base: &ir.TypeRef{Target: "type/primitive/string"}}, &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}) }, "ir/cyclic-structure", fmt.Sprintf( "document reaches the *ir.ConstructorValue it is already inside (entered at %q), so it cannot be encoded", "document.Types[type/x/"+illFormed+"].Examples[0].Value.Constructor")}, + {"discriminator route repeated", func() *ir.Document { + model := namedModel("type/x/A") + model.Discriminator = &ir.Discriminator{ + Property: "property/x/A/kind", + Mapping: map[string]ir.TypeID{illFormed: "type/x/A"}, + DecodeOnlyRoutes: map[string]ir.TypeID{illFormed: "type/x/A"}, + } + return typesDoc(model) + }, "ir/discriminator-route-duplicate", fmt.Sprintf( + "discriminator routes the tag %q in DecodeOnlyRoutes, a second spelling of the route Mapping gives it", illFormed)}, + {"discriminator route repeated by a type name", func() *ir.Document { + leafType := namedModel("type/x/Leaf") + leafType.Name = ir.Naming{Source: illFormed, Canonical: "leaf"} + union := &ir.Union{ID: "type/x/U", Name: named("u"), WireTagged: true, + Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/x/Leaf"}}}, + Discriminator: &ir.Discriminator{PropertyName: "kind", DecodeOnlyRoutes: map[string]ir.TypeID{illFormed: "type/x/Leaf"}}, + } + return typesDoc(leafType, union) + }, "ir/discriminator-route-duplicate", fmt.Sprintf( + "discriminator routes the tag %q in DecodeOnlyRoutes, a second spelling of the route a variant's type name "+ + "gives it beside an empty Mapping", illFormed)}, + {"related decided unresolved", func() *ir.Document { + doc := typesDoc(namedModel("type/x/A")) + finding := ir.NewDiagnostic(ir.SeverityInfo, "x/finding", "m", ir.Provenance{Source: ir.NoSource}) + finding.Related = []ir.Related{{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/" + illFormed}}} + doc.Diagnostics = []ir.Diagnostic{finding} + return doc + }, "ir/dangling-decided-node", fmt.Sprintf( + "diagnostic says it decided node %q, which the document does not hold", "property/x/"+illFormed)}, {"irVersion", func() *ir.Document { doc := typesDoc(namedModel("type/x/A")) doc.IRVersion = illFormed diff --git a/ir/irverify/irverify_test.go b/ir/irverify/irverify_test.go index a03cea85c..84f80e2ff 100644 --- a/ir/irverify/irverify_test.go +++ b/ir/irverify/irverify_test.go @@ -115,14 +115,14 @@ func TestVerify_NilTypeDefIsAViolation(t *testing.T) { // guard as much as one reading Common(). func TestVerify_TypedNilTypeDefIsAViolation(t *testing.T) { t.Parallel() - for _, td := range []ir.TypeDef{ + for _, typeDef := range []ir.TypeDef{ (*ir.Primitive)(nil), (*ir.Scalar)(nil), (*ir.Model)(nil), (*ir.Union)(nil), (*ir.Enum)(nil), (*ir.List)(nil), (*ir.MapT)(nil), (*ir.Tuple)(nil), (*ir.Literal)(nil), (*ir.External)(nil), (*ir.Any)(nil), } { - doc := &ir.Document{Types: ir.TypeRegistry{"type/x/typednil": td}} + doc := &ir.Document{Types: ir.TypeRegistry{"type/x/typednil": typeDef}} var got []irverify.Violation - require.NotPanics(t, func() { got = verifyDeclared(doc) }, "%T", td) - assert.Contains(t, codesOf(got), "ir/nil-type", "%T", td) + require.NotPanics(t, func() { got = verifyDeclared(doc) }, "%T", typeDef) + assert.Contains(t, codesOf(got), "ir/nil-type", "%T", typeDef) } } diff --git a/ir/irverify/kinds.go b/ir/irverify/kinds.go index f084e893e..aaadd81c0 100644 --- a/ir/irverify/kinds.go +++ b/ir/irverify/kinds.go @@ -24,18 +24,18 @@ import ( // ID. func checkPrimitiveKinds(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - if ir.IsNilTypeDef(td) { + for id, typeDef := range doc.Types { + if ir.IsNilTypeDef(typeDef) { continue // checkRegistryKeys reports the nil entry itself } - switch n := td.(type) { + switch node := typeDef.(type) { case *ir.Primitive: - vs = append(vs, undeclaredKind(n.PrimitiveKind, "primitive carries", id, "")...) + vs = append(vs, undeclaredKind(node.PrimitiveKind, "primitive carries", id, "")...) case *ir.Enum: - vs = append(vs, undeclaredKind(n.ValueType, "enum's value type is", id, ".ValueType")...) + vs = append(vs, undeclaredKind(node.ValueType, "enum's value type is", id, ".ValueType")...) case *ir.Literal: - if n.ValueType != "" { // a list or an object has no primitive - vs = append(vs, undeclaredKind(n.ValueType, "literal's value type is", id, ".ValueType")...) + if node.ValueType != "" { // a list or an object has no primitive + vs = append(vs, undeclaredKind(node.ValueType, "literal's value type is", id, ".ValueType")...) } default: // No other node names a PrimitiveKind. @@ -83,11 +83,11 @@ var operationPath = map[reflect.Type]bool{ func checkStreamingModes(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != streamingModeType { - return operationPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != streamingModeType { + return operationPath[value.Type()] } - mode, ok := reflect.TypeAssert[ir.StreamingMode](v) + mode, ok := reflect.TypeAssert[ir.StreamingMode](value) if !ok || mode.Valid() { return false } @@ -138,11 +138,11 @@ var stabilityType = reflect.TypeFor[ir.Stability]() func checkStability(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != stabilityType { - return operationPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != stabilityType { + return operationPath[value.Type()] } - if tier := ir.Stability(v.String()); !tier.Valid() { + if tier := ir.Stability(value.String()); !tier.Valid() { vs = append(vs, Violation{ Code: "ir/unknown-stability", Message: "stability names undeclared tier " + strconv.Quote(string(tier)), diff --git a/ir/irverify/kinds_internal_test.go b/ir/irverify/kinds_internal_test.go index 1e10c3f8b..1cebf4110 100644 --- a/ir/irverify/kinds_internal_test.go +++ b/ir/irverify/kinds_internal_test.go @@ -76,9 +76,9 @@ func TestOperationPathChecks_SeeOnlyThePathToTheField(t *testing.T) { t.Parallel() shown := func(doc *ir.Document) int { visitor, count := check(doc), 0 - ir.WalkValues(doc, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + ir.WalkValues(doc, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { count++ - return visitor.visit(v, at) + return visitor.visit(value, at) })) return count } diff --git a/ir/irverify/kinds_test.go b/ir/irverify/kinds_test.go index 2f773503f..dc46f8fc7 100644 --- a/ir/irverify/kinds_test.go +++ b/ir/irverify/kinds_test.go @@ -84,7 +84,7 @@ func TestVerify_NilTypeBesideAPrimitiveDoesNotPanic(t *testing.T) { } // TestVerify_DeclaredPrimitiveKindIsClean is the other half of the proof: a -// check that cannot stay silent is no better than one that cannot fire. The +// check that cannot report nothing is no better than one that cannot fire. The // documents differ from the ones above only in the kind, so nothing but the // kind can be what the check reads. func TestVerify_DeclaredPrimitiveKindIsClean(t *testing.T) { @@ -163,8 +163,9 @@ func TestVerify_UndeclaredStreamingModeIsAViolation(t *testing.T) { } } -// TestVerify_DeclaredStreamingModesAreClean is the silent half: every declared -// mode verifies, the empty one included, since most operations do not stream. +// TestVerify_DeclaredStreamingModesAreClean is the report-nothing half: every +// declared mode verifies, the empty one included, since most operations do not +// stream. func TestVerify_DeclaredStreamingModesAreClean(t *testing.T) { t.Parallel() for _, mode := range []ir.StreamingMode{ir.StreamingNone, ir.StreamingClient, ir.StreamingServer, ir.StreamingBidirectional} { @@ -172,8 +173,8 @@ func TestVerify_DeclaredStreamingModesAreClean(t *testing.T) { } } -// TestVerify_DeclaredAuthKindIsClean holds the silent half: the same document -// with a mechanism ir declares must yield nothing. +// TestVerify_DeclaredAuthKindIsClean holds the report-nothing half: the same +// document with a mechanism ir declares must yield nothing. func TestVerify_DeclaredAuthKindIsClean(t *testing.T) { t.Parallel() for _, kind := range []ir.AuthKind{ir.AuthKindOAuth2, ir.AuthKindAPIKey, ir.AuthKindX509, ir.AuthKindCustom} { diff --git a/ir/irverify/links.go b/ir/irverify/links.go index c4abf6362..c4c8c2db5 100644 --- a/ir/irverify/links.go +++ b/ir/irverify/links.go @@ -31,8 +31,8 @@ var linkPayloads = map[ir.LinkValueKind]string{ func checkLinkValues(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if lv, ok := reflect.TypeAssert[ir.LinkValue](v); ok { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if lv, ok := reflect.TypeAssert[ir.LinkValue](value); ok { vs = appendLinkValueViolations(vs, &lv, at) } return true diff --git a/ir/irverify/maps.go b/ir/irverify/maps.go index a1e6597cb..02a0250a1 100644 --- a/ir/irverify/maps.go +++ b/ir/irverify/maps.go @@ -14,8 +14,8 @@ import ( // it is the same reading a compiler converts by, so the two cannot disagree. func checkMaps(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - model, isModel := td.(*ir.Model) + for id, typeDef := range doc.Types { + model, isModel := typeDef.(*ir.Model) if !isModel { continue // a nil entry is checkRegistryKeys's to report } @@ -39,8 +39,8 @@ func checkMaps(doc *ir.Document) []Violation { // ID decides. func checkMapKeys(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - key, field := catchAllKey(td) + for id, typeDef := range doc.Types { + key, field := catchAllKey(typeDef) if key == nil || key.Nullable || key.Target != ir.PrimitiveTypeID(ir.PrimitiveString) { continue } @@ -61,8 +61,8 @@ func checkMapKeys(doc *ir.Document) []Violation { // different payloads (ir/catch-all-closed). func checkCatchAlls(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - model, isModel := td.(*ir.Model) + for id, typeDef := range doc.Types { + model, isModel := typeDef.(*ir.Model) if !isModel || model == nil || model.AdditionalProperties == nil { continue } @@ -85,18 +85,18 @@ func checkCatchAlls(doc *ir.Document) []Violation { return vs } -// catchAllKey returns the key td types its members under and the field -// holding it, or nil when td types none: a MapT's Key, or the Key of a Model's -// AdditionalProperties. -func catchAllKey(td ir.TypeDef) (*ir.TypeRef, string) { - switch n := td.(type) { +// catchAllKey returns the key typeDef types its members under and the field +// holding it, or nil when typeDef types none: a MapT's Key, or the Key of a +// Model's AdditionalProperties. +func catchAllKey(typeDef ir.TypeDef) (*ir.TypeRef, string) { + switch node := typeDef.(type) { case *ir.MapT: - if n != nil { - return n.Key, "Key" + if node != nil { + return node.Key, "Key" } case *ir.Model: - if n != nil && n.AdditionalProperties != nil { - return n.AdditionalProperties.Key, "AdditionalProperties.Key" + if node != nil && node.AdditionalProperties != nil { + return node.AdditionalProperties.Key, "AdditionalProperties.Key" } default: // No other kind types its members under a key. diff --git a/ir/irverify/maps_test.go b/ir/irverify/maps_test.go index c36eedefb..9445abc61 100644 --- a/ir/irverify/maps_test.go +++ b/ir/irverify/maps_test.go @@ -20,9 +20,9 @@ func TestCheckMaps_ReportsAModelThatIsAMap(t *testing.T) { t.Parallel() stringType := ir.TypeRef{Target: "type/primitive/string"} for _, tc := range []struct { - name string - td ir.TypeDef - want []string + name string + typeDef ir.TypeDef + want []string }{ {"a model that is a map", &ir.Model{AdditionalProperties: &ir.AdditionalProperties{Value: &stringType}}, []string{"types[type/x]"}}, @@ -35,8 +35,8 @@ func TestCheckMaps_ReportsAModelThatIsAMap(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - tc.td.Common().ID = "type/x" - doc := &ir.Document{Types: ir.TypeRegistry{"type/x": tc.td}} + tc.typeDef.Common().ID = "type/x" + doc := &ir.Document{Types: ir.TypeRegistry{"type/x": tc.typeDef}} assert.Equal(t, tc.want, violationPaths(irverify.Verify(doc), "ir/map-as-model")) }) @@ -51,9 +51,9 @@ func TestCheckMapKeys_ReportsAStringKeySpelledOut(t *testing.T) { t.Parallel() stringType := ir.TypeRef{Target: "type/primitive/string"} for _, tc := range []struct { - name string - td ir.TypeDef - want []string + name string + typeDef ir.TypeDef + want []string }{ {"a map spelling its string key", &ir.MapT{Key: &stringType, Value: stringType}, []string{"types[type/x].Key"}}, {"a catch-all spelling its string key", &ir.Model{ @@ -69,10 +69,10 @@ func TestCheckMapKeys_ReportsAStringKeySpelledOut(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - if !ir.IsNilTypeDef(tc.td) { - tc.td.Common().ID = "type/x" + if !ir.IsNilTypeDef(tc.typeDef) { + tc.typeDef.Common().ID = "type/x" } - doc := &ir.Document{Types: ir.TypeRegistry{"type/x": tc.td}} + doc := &ir.Document{Types: ir.TypeRegistry{"type/x": tc.typeDef}} assert.Equal(t, tc.want, violationPaths(irverify.Verify(doc), "ir/map-key-string")) }) @@ -90,7 +90,7 @@ func TestCheckCatchAlls_ReportsACatchAllSayingTwoThings(t *testing.T) { var typedNil *ir.Model for _, tc := range []struct { name string - td ir.TypeDef + typeDef ir.TypeDef empty, close []string }{ {"neither a value nor a pattern", &ir.Model{AdditionalProperties: &ir.AdditionalProperties{}}, @@ -109,10 +109,10 @@ func TestCheckCatchAlls_ReportsACatchAllSayingTwoThings(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - if !ir.IsNilTypeDef(tc.td) { - tc.td.Common().ID = "type/x" + if !ir.IsNilTypeDef(tc.typeDef) { + tc.typeDef.Common().ID = "type/x" } - doc := &ir.Document{Types: ir.TypeRegistry{"type/x": tc.td}} + doc := &ir.Document{Types: ir.TypeRegistry{"type/x": tc.typeDef}} vs := irverify.Verify(doc) assert.Equal(t, tc.empty, violationPaths(vs, "ir/catch-all-empty")) assert.Equal(t, tc.close, violationPaths(vs, "ir/catch-all-closed")) diff --git a/ir/irverify/memberids.go b/ir/irverify/memberids.go index f56374dda..8bcc2f6d1 100644 --- a/ir/irverify/memberids.go +++ b/ir/irverify/memberids.go @@ -21,8 +21,8 @@ import ( // report whatever order the registry is ranged in. func checkMemberIDs(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - enum, isEnum := td.(*ir.Enum) + for id, typeDef := range doc.Types { + enum, isEnum := typeDef.(*ir.Enum) if !isEnum || enum == nil || !keyedByOwnID(string(id), string(enum.ID)) { continue // a key that is not the enum's ID is checkRegistryKeys' report } diff --git a/ir/irverify/memberkinds.go b/ir/irverify/memberkinds.go index 9058b40c4..2085ff071 100644 --- a/ir/irverify/memberkinds.go +++ b/ir/irverify/memberkinds.go @@ -45,9 +45,9 @@ var memberKinds = func() map[ir.PrimitiveKind][]ir.ValueKind { // members are left. func checkEnumMemberKinds(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - enum, isEnum := td.(*ir.Enum) - if !isEnum || ir.IsNilTypeDef(td) || !enum.ValueType.Valid() { + for id, typeDef := range doc.Types { + enum, isEnum := typeDef.(*ir.Enum) + if !isEnum || ir.IsNilTypeDef(typeDef) || !enum.ValueType.Valid() { continue } admitted := memberKinds[enum.ValueType] diff --git a/ir/irverify/naming.go b/ir/irverify/naming.go index 5d142ec87..42e1c0e89 100644 --- a/ir/irverify/naming.go +++ b/ir/irverify/naming.go @@ -18,8 +18,8 @@ var namingType = reflect.TypeFor[ir.Naming]() // nameField is the field through which a node holds the ir.Naming that names // it. A node in nameOptional renamed out of this spelling stops matching, which -// reports a violation on a document that has none rather than going silent — -// TestVerify_OptionalNameOwnersAreClean is what reddens. +// reports a violation on a document that has none rather than reporting nothing +// — TestVerify_OptionalNameOwnersAreClean is what reddens. // // Only the exemptions are addressed this way. The rule itself holds every // ir.Naming the walk reaches, including the ones no Name field owns, such as the @@ -32,7 +32,7 @@ const nameField = "Name" // ir.Primitive is the only one, exempt by design: its PrimitiveKind identifies // it, so there is no source name to record. An entry added for a gap a compiler // has yet to fill hides every genuinely nameless node of that type while it -// stands, so it belongs on a tracked issue too. +// remains, so it belongs on a tracked issue too. // // Keyed by node type rather than path so a new node type is held to the rule at // once. @@ -58,11 +58,11 @@ func checkNaming(*ir.Document) walkCheck { // own however long it is. var aliases scratchstate.Map[string, int] return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() != reflect.Struct || v.Type() != namingType { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() != reflect.Struct || value.Type() != namingType { return true } - vs = appendNamingChecks(vs, v, at, &aliases) + vs = appendNamingChecks(vs, value, at, &aliases) return false // a Naming holds no Naming nested in it }, report: reporting(&vs), @@ -253,28 +253,28 @@ func appendGrammarViolation(vs []Violation, source, canon string, at ir.WalkPath // It overlaps appendGrammarViolation wherever a Source is present, and is kept // because it does not need one: a Canonical carried without a Source is measured // by this and by nothing else. -func isSegmented(s string) bool { - for word := range strings.SplitSeq(s, "_") { +func isSegmented(text string) bool { + for word := range strings.SplitSeq(text, "_") { var prev rune - for i, r := range word { - if i > 0 && straddlesLetterDigit(prev, r) { + for i, character := range word { + if i > 0 && straddlesLetterDigit(prev, character) { return false } - prev = r + prev = character } } return true } -// straddlesLetterDigit reports whether prev and r sit either side of a boundary -// the grammar splits on. A combining mark is transparent: it belongs to the -// letter it follows rather than starting a run of its own. -func straddlesLetterDigit(prev, r rune) bool { - return (unicode.IsLetter(prev) && unicode.IsDigit(r)) || - (unicode.IsDigit(prev) && unicode.IsLetter(r)) +// straddlesLetterDigit reports whether prev and character sit either side of a +// boundary the grammar splits on. A combining mark is transparent: it belongs +// to the letter it follows rather than starting a run of its own. +func straddlesLetterDigit(prev, character rune) bool { + return (unicode.IsLetter(prev) && unicode.IsDigit(character)) || + (unicode.IsDigit(prev) && unicode.IsLetter(character)) } -// isWordSequence reports whether s is the shape a neutral name channel +// isWordSequence reports whether text is the shape a neutral name channel // promises: words joined by single underscores, each word made of the runes // the grammar keeps in one (ir.IsWordRune). The empty string // qualifies — a Naming fills one channel or the other, and a source name with no @@ -283,16 +283,16 @@ func straddlesLetterDigit(prev, r rune) bool { // It says nothing about where the boundaries fall inside a run of word // characters: "foo2bar" and "foo_2_bar" are both word sequences by this test. // isSegmented is what holds that line. -func isWordSequence(s string) bool { - if s == "" { +func isWordSequence(text string) bool { + if text == "" { return true } - for word := range strings.SplitSeq(s, "_") { + for word := range strings.SplitSeq(text, "_") { if word == "" { return false // a leading, trailing, or doubled separator } - for _, r := range word { - if !ir.IsWordRune(r) { + for _, character := range word { + if !ir.IsWordRune(character) { return false } } @@ -300,9 +300,9 @@ func isWordSequence(s string) bool { return true } -// isBlankName reports whether s holds no rune a name could be made of. It takes -// as invisible only the runes isInvisible reads from Unicode's own properties, -// needing no format's grammar. +// isBlankName reports whether text holds no rune a name could be made of. It +// takes as invisible only the runes isInvisible reads from Unicode's own +// properties, needing no format's grammar. // // strings.TrimSpace is not that test: IsSpace misses the zero-width joiners, // the soft hyphen and the BOM (all Cf), and space, control and Cf all miss @@ -311,27 +311,28 @@ func isWordSequence(s string) bool { // // U+2800 BRAILLE PATTERN BLANK is outside that set, so it is left alone: // judging it would need the grammar the name is read under. -func isBlankName(s string) bool { - for _, r := range s { - if !isInvisible(r) { +func isBlankName(text string) bool { + for _, character := range text { + if !isInvisible(character) { return false } } return true } -// isInvisible reports whether r is white space, a control, or +// isInvisible reports whether character is white space, a control, or // default-ignorable (ir.IsDefaultIgnorable), the set the blank rules take as // carrying no visible mark. U+1680 OGHAM SPACE MARK renders a line and stays // in, as white space (GitHub #832). -func isInvisible(r rune) bool { - return unicode.IsSpace(r) || unicode.IsControl(r) || ir.IsDefaultIgnorable(r) +func isInvisible(character rune) bool { + return unicode.IsSpace(character) || unicode.IsControl(character) || ir.IsDefaultIgnorable(character) } -// isCased reports whether s still carries casing an emitter should own. The test -// is lowercase-idempotence, not unicode.IsUpper: a compiler neutralizes names -// with strings.ToLower, so a rune that has no lowercase form (double-struck ℤ, -// Mathematical Bold 𝐀) is already neutral though IsUpper reports true for it. -func isCased(s string) bool { - return strings.ToLower(s) != s +// isCased reports whether text still carries casing an emitter should own. The +// test is lowercase-idempotence, not unicode.IsUpper: a compiler neutralizes +// names with strings.ToLower, so a rune that has no lowercase form +// (double-struck ℤ, Mathematical Bold 𝐀) is already neutral though IsUpper +// reports true for it. +func isCased(text string) bool { + return strings.ToLower(text) != text } diff --git a/ir/irverify/naming_alias_test.go b/ir/irverify/naming_alias_test.go index 1e2ad8a0d..c273a1c55 100644 --- a/ir/irverify/naming_alias_test.go +++ b/ir/irverify/naming_alias_test.go @@ -359,10 +359,10 @@ func TestVerify_AliasPathIsSpelledAsTheWalkWould(t *testing.T) { doc := modelNamed(ir.Naming{Source: "m", Canonical: "m", Aliases: aliases}) walked := map[string]string{} // alias → the path the walk renders for it - ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { path := at.String() - if v.Kind() == reflect.String && v.String() != "" { - walked[v.String()] = path + if value.Kind() == reflect.String && value.String() != "" { + walked[value.String()] = path } return true })) diff --git a/ir/irverify/naming_internal_test.go b/ir/irverify/naming_internal_test.go index 7af52b6e3..bae0d7c0c 100644 --- a/ir/irverify/naming_internal_test.go +++ b/ir/irverify/naming_internal_test.go @@ -64,8 +64,8 @@ func TestNameExempt_IsTheOptionalNodesOwnNameAlone(t *testing.T) { } optional := map[reflect.Type]bool{reflect.TypeFor[twoNamings](): true} got := map[string]bool{} - ir.WalkValues(holder{}, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() == namingType { + ir.WalkValues(holder{}, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() == namingType { got[at.String()] = nameExempt(at, optional) } return true diff --git a/ir/irverify/naming_test.go b/ir/irverify/naming_test.go index 4c79f35bb..a368539e3 100644 --- a/ir/irverify/naming_test.go +++ b/ir/irverify/naming_test.go @@ -334,7 +334,7 @@ func TestVerify_OptionalNameOwnersAreClean(t *testing.T) { } // TestVerify_NamelessServerAndResponseAreViolations is the reach the exemptions -// cost while they stood. Both nodes are named entities the OpenAPI compiler now +// cost while they held. Both nodes are named entities the OpenAPI compiler now // names — a server by its URL template, a response by its status-code key — so // one arriving nameless is a compiler defect and no longer the expected shape // (GitHub #258, #259). Re-exempting either type reddens this. diff --git a/ir/irverify/paramchoices.go b/ir/irverify/paramchoices.go index 7de9a3928..570ef3173 100644 --- a/ir/irverify/paramchoices.go +++ b/ir/irverify/paramchoices.go @@ -27,11 +27,11 @@ func checkParamChoices(*ir.Document) walkCheck { var seen scratchstate.Map[ir.ParameterID, int] var named scratchstate.Map[string, int] return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != operationType { - return operationPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != operationType { + return operationPath[value.Type()] } - if operation, ok := reflect.TypeAssert[ir.Operation](v); ok && len(operation.ParamChoices) > 0 { + if operation, ok := reflect.TypeAssert[ir.Operation](value); ok && len(operation.ParamChoices) > 0 { names := make([]ir.Naming, len(operation.ParamChoices)) for i, choice := range operation.ParamChoices { where := at.String() + ".ParamChoices[" + strconv.Itoa(i) + "]" diff --git a/ir/irverify/prefixbindings.go b/ir/irverify/prefixbindings.go index 2af7675ce..aaafb6de4 100644 --- a/ir/irverify/prefixbindings.go +++ b/ir/irverify/prefixbindings.go @@ -23,11 +23,11 @@ import ( func checkPrefixBindings(doc *ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != operationType { - return operationPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != operationType { + return operationPath[value.Type()] } - if operation, ok := reflect.TypeAssert[ir.Operation](v); ok { + if operation, ok := reflect.TypeAssert[ir.Operation](value); ok { vs = appendPrefixBindingViolations(vs, doc.Types, &operation, at) } return false diff --git a/ir/irverify/provenance.go b/ir/irverify/provenance.go index 09e954c08..c0f48527b 100644 --- a/ir/irverify/provenance.go +++ b/ir/irverify/provenance.go @@ -31,14 +31,14 @@ func checkProvenance(doc *ir.Document) walkCheck { var vs []Violation declared := len(doc.Sources) return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() == reflect.Struct && v.Type() == relatedType { - vs = appendRelatedViolations(vs, v, at) + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() == reflect.Struct && value.Type() == relatedType { + vs = appendRelatedViolations(vs, value, at) } - if v.Kind() != reflect.Struct || v.Type() != provenanceType { + if value.Kind() != reflect.Struct || value.Type() != provenanceType { return true } - src := int(v.FieldByName("Source").Int()) + src := int(value.FieldByName("Source").Int()) if sourceOutOfRange(src, declared) { vs = append(vs, Violation{ Code: "ir/provenance-source-out-of-range", @@ -47,8 +47,8 @@ func checkProvenance(doc *ir.Document) walkCheck { Path: at.String(), }) } - vs = appendLocatorViolations(vs, v, src, at) - vs = appendWriterViolation(vs, doc.Sources, src, int(v.FieldByName("WrittenBy").Int()), at) + vs = appendLocatorViolations(vs, value, src, at) + vs = appendWriterViolation(vs, doc.Sources, src, int(value.FieldByName("WrittenBy").Int()), at) return false // Provenance holds no nested Provenance }, report: reporting(&vs), @@ -57,11 +57,11 @@ func checkProvenance(doc *ir.Document) walkCheck { // appendRelatedViolations reports a related entry whose Provenance names // nothing, whatever its role: no node, on ir.NoSource, where no pointer or -// position may stand either, so the finding concerns no other place at all; +// position may be set either, so the finding concerns no other place at all; // and one of role ir.RelatedDecided naming no node, wherever it points, since // the role says the finding decided one, and a consumer listing what a finding -// decided reads the node and nothing else. An entry of that role naming -// neither draws both. +// decided reads the node and nothing else. An entry of that role naming neither +// draws both. func appendRelatedViolations(vs []Violation, related reflect.Value, at ir.WalkPath) []Violation { prov := related.FieldByName("Provenance") named := prov.FieldByName("Node").String() != "" @@ -82,6 +82,54 @@ func appendRelatedViolations(vs []Violation, related reflect.Value, at ir.WalkPa }) } +// checkDecidedNodes asserts each related entry of a document's findings saying +// the finding decided a node names one the document holds: a type of its +// registry, or a property one of its models declares +// (docs/ir/provenance.md#related-places). A node pruning removed or no stage +// minted leaves a consumer listing what a finding decided with nothing to +// read. An entry naming no node is ir/related-names-no-node's. +func checkDecidedNodes(doc *ir.Document) []Violation { + var vs []Violation + var held map[string]bool + for i, diagnostic := range doc.Diagnostics { + for j, related := range diagnostic.Related { + node := related.Provenance.Node + if related.Role != ir.RelatedDecided || node == "" { + continue + } + if held == nil { + held = heldNodes(doc) + } + if held[node] { + continue + } + vs = append(vs, Violation{ + Code: "ir/dangling-decided-node", + Message: "diagnostic says it decided node " + strconv.Quote(node) + ", which the document does not hold", + Path: ir.DocumentPath + ".Diagnostics[" + strconv.Itoa(i) + "].Related[" + strconv.Itoa(j) + "].Provenance", + }) + } + } + return vs +} + +// heldNodes is the set of the nodes a finding may decide that doc holds: each +// type of its registry, and each property its models declare. +func heldNodes(doc *ir.Document) map[string]bool { + held := make(map[string]bool, len(doc.Types)) + for id, typeDef := range doc.Types { + held[string(id)] = true + model, isModel := typeDef.(*ir.Model) + if !isModel || ir.IsNilTypeDef(typeDef) { + continue + } + for _, property := range model.Properties { + held[string(property.ID)] = true + } + } + return held +} + // appendWriterViolation reports a WrittenBy that names no overlay writing into // src (docs/ir/provenance.md): 0 says src wrote it, and any other index must be // an overlay entry of sources other than src itself, since only an overlay diff --git a/ir/irverify/provenance_test.go b/ir/irverify/provenance_test.go index c537ef009..3ccb8d872 100644 --- a/ir/irverify/provenance_test.go +++ b/ir/irverify/provenance_test.go @@ -281,9 +281,9 @@ func TestVerify_ARelatedEntryIsHeldAsAProvenanceIs(t *testing.T) { doc.Sources = oneSource() diagnostic := ir.NewDiagnostic(ir.SeverityWarning, "openapi/x", "m", ir.Provenance{}) diagnostic.Related = []ir.Related{ - {Role: ir.RelatedKept, Provenance: ir.Provenance{Source: 9}}, - {Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: "no-slash"}}, - {Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: "/a"}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Source: 9}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: "no-slash"}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: "/a"}}, } doc.Diagnostics = []ir.Diagnostic{diagnostic} @@ -304,11 +304,11 @@ func TestVerify_ARelatedEntryNamesSomething(t *testing.T) { doc.Sources = oneSource() diagnostic := ir.NewDiagnostic(ir.SeverityWarning, "openapi/x", "m", ir.Provenance{}) diagnostic.Related = []ir.Related{ - {Role: ir.RelatedKept, Provenance: ir.Provenance{Source: ir.NoSource}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Source: ir.NoSource}}, {Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource}}, {Role: ir.RelatedDecided, Provenance: ir.Provenance{Pointer: "/a"}}, - {Role: ir.RelatedKept, Provenance: ir.Provenance{}}, - {Role: ir.RelatedKept, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/a"}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/a"}}, {Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/a"}}, } doc.Diagnostics = []ir.Diagnostic{diagnostic} @@ -337,7 +337,7 @@ func TestVerify_ADecidedEntryNamesItsNode(t *testing.T) { diagnostic.Related = []ir.Related{ {Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/a"}}, {Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource}}, - {Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: "/a"}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: "/a"}}, } doc.Diagnostics = []ir.Diagnostic{diagnostic} @@ -349,3 +349,40 @@ func TestVerify_ADecidedEntryNamesItsNode(t *testing.T) { } } } + +// TestVerify_ADecidedEntryNamesANodeTheDocumentHolds holds a related entry +// saying the finding decided a node to one the document holds: a type of its +// registry, or a property a model of it declares. One naming a node pruning +// removed, or never minted, sends a consumer listing what the finding decided +// to nothing. Every other role, and a decided entry naming no node, which +// ir/related-names-no-node reports, is left to the checks of its own. +func TestVerify_ADecidedEntryNamesANodeTheDocumentHolds(t *testing.T) { + t.Parallel() + doc := validDoc() + model, ok := doc.Types["type/x/Model"].(*ir.Model) + require.True(t, ok) + model.Properties = []ir.Property{{ID: "property/x/Model/a", Name: named("a"), WireName: "a", + Type: ir.TypeRef{Target: "type/x/Model"}}} + decided := func(node string) ir.Related { + return ir.Related{Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: node}} + } + first := ir.NewDiagnostic(ir.SeverityInfo, "openapi/x", "m", ir.Provenance{Source: ir.NoSource}) + first.Related = []ir.Related{decided("property/x/Model/a"), decided("type/x/Model"), decided("property/x/Gone/a")} + second := ir.NewDiagnostic(ir.SeverityInfo, "openapi/x", "m", ir.Provenance{Source: ir.NoSource}) + second.Related = []ir.Related{ + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/Kept/a"}}, + decided("type/x/Gone"), decided(""), + } + doc.Diagnostics = []ir.Diagnostic{first, second} + + got := verifyDeclared(doc) + + assert.Equal(t, []string{"document.Diagnostics[0].Related[2].Provenance", "document.Diagnostics[1].Related[1].Provenance"}, + violationPaths(got, "ir/dangling-decided-node")) + for _, violation := range got { + if violation.Code == "ir/dangling-decided-node" { + assert.Contains(t, violation.Message, `"property/x/Gone/a"`) + break + } + } +} diff --git a/ir/irverify/rawpayloads.go b/ir/irverify/rawpayloads.go index 01676b986..0246109da 100644 --- a/ir/irverify/rawpayloads.go +++ b/ir/irverify/rawpayloads.go @@ -36,15 +36,15 @@ func checkRawPayloads(*ir.Document) walkCheck { var reader entryReader var payloads payloadReader return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() != reflect.Map { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() != reflect.Map { return true } - switch v.Type() { + switch value.Type() { case unmodeledType: - vs = appendEntries(vs, &reader, &payloads, v, at, unmodeledEntry) + vs = appendEntries(vs, &reader, &payloads, value, at, unmodeledEntry) case rawConfigType: - vs = appendEntries(vs, &reader, &payloads, v, at, rawConfigEntry) + vs = appendEntries(vs, &reader, &payloads, value, at, rawConfigEntry) default: return true // any other map may still hold one of these below it } @@ -54,17 +54,17 @@ func checkRawPayloads(*ir.Document) walkCheck { } } -// appendEntries appends check's verdict on every entry of the payload map m, at -// at, to vs, reading the entries through entryReaderValue and their payloads -// through payloadReaderValue. Both callers key on a plain string, so the key -// spells the entry's path. -func appendEntries(vs []Violation, entryReaderValue *entryReader, payloadReaderValue *payloadReader, m reflect.Value, at ir.WalkPath, - check func(reader *entryReader, otherPayloadReader *payloadReader, key string, entry reflect.Value, at ir.WalkPath) []Violation, +// appendEntries appends check's answer on every entry of the payload map value, +// at mapPath, to vs, reading the entries through entryReader and their payloads +// through payloadReader. Both callers key on a plain string, so the key spells +// the entry's path. +func appendEntries(vs []Violation, entryReader *entryReader, payloadReader *payloadReader, value reflect.Value, mapPath ir.WalkPath, + check func(reader *entryReader, otherPayloadReader *payloadReader, key string, entry reflect.Value, mapPath ir.WalkPath) []Violation, ) []Violation { - held := entryReaderValue.heldFor(m) - for iter := m.MapRange(); iter.Next(); { + held := entryReader.heldFor(value) + for iter := value.MapRange(); iter.Next(); { key, entry := held.read(iter) - vs = append(vs, check(entryReaderValue, payloadReaderValue, key.String(), entry, at)...) + vs = append(vs, check(entryReader, payloadReader, key.String(), entry, mapPath)...) } return vs } @@ -79,7 +79,7 @@ func appendEntries(vs []Violation, entryReaderValue *entryReader, payloadReaderV // // The defects are checked independently so a doubly-broken entry names each of // its defects rather than stopping at the first. -func unmodeledEntry(reader *entryReader, payloadReaderValue *payloadReader, key string, entry reflect.Value, at ir.WalkPath) []Violation { +func unmodeledEntry(reader *entryReader, payloadReader *payloadReader, key string, entry reflect.Value, at ir.WalkPath) []Violation { var vs []Violation if key == "" { vs = append(vs, Violation{ @@ -88,8 +88,8 @@ func unmodeledEntry(reader *entryReader, payloadReaderValue *payloadReader, key }) } valueField := entry.FieldByName("Value") - var validValue bool - vs, validValue = appendRawValue(vs, payloadReaderValue, valueField, "unmodeled entry") + var valid bool + vs, valid = appendRawValue(vs, payloadReader, valueField, "unmodeled entry") switch reason := ir.UnmodeledReason(entry.FieldByName("Reason").String()); { case reason == "": @@ -104,7 +104,7 @@ func unmodeledEntry(reader *entryReader, payloadReaderValue *payloadReader, key }) } vs = placeEntry(vs, at, key, `[""]`) - return appendTargetPointerViolations(vs, reader, payloadReaderValue, entry.FieldByName("Targets"), valueField.Bytes(), validValue, at, key) + return appendTargetPointerViolations(vs, reader, payloadReader, entry.FieldByName("Targets"), valueField.Bytes(), valid, at, key) } // appendTargetPointerViolations reports any key of UnmodeledEntry.Targets that @@ -112,7 +112,7 @@ func unmodeledEntry(reader *entryReader, payloadReaderValue *payloadReader, key // Value; empty or dangling values are checkEmptyRefs' and // checkReferentialIntegrity's own reports, and invalid UTF-8 is checkUTF8's. func appendTargetPointerViolations(vs []Violation, reader *entryReader, payloads *payloadReader, targets reflect.Value, - raw []byte, validValue bool, at ir.WalkPath, key string, + raw []byte, valid bool, at ir.WalkPath, key string, ) []Violation { if targets.Len() == 0 { return vs @@ -136,7 +136,7 @@ func appendTargetPointerViolations(vs []Violation, reader *entryReader, payloads }) continue } - if validValue && utf8.ValidString(ptr) && !payloads.resolves(raw, jsontext.Pointer(ptr)) { + if valid && utf8.ValidString(ptr) && !payloads.resolves(raw, jsontext.Pointer(ptr)) { vs = append(vs, Violation{ Code: "ir/unmodeled-target-pointer-unresolved", Message: "unmodeled target pointer " + strconv.Quote(ptr) + " does not resolve inside Value", @@ -150,8 +150,8 @@ func appendTargetPointerViolations(vs []Violation, reader *entryReader, payloads // rawConfigEntry checks one entry of a RawConfig map. Unlike an Unmodeled entry // it carries no reason to check — the source declared it where the IR expects it // — so the payload is all there is to hold it to. -func rawConfigEntry(_ *entryReader, payloadReaderValue *payloadReader, key string, entry reflect.Value, at ir.WalkPath) []Violation { - vs, _ := appendRawValue(nil, payloadReaderValue, entry, "protocol config") +func rawConfigEntry(_ *entryReader, payloadReader *payloadReader, key string, entry reflect.Value, at ir.WalkPath) []Violation { + vs, _ := appendRawValue(nil, payloadReader, entry, "protocol config") return placeEntry(vs, at, key, "[]") } @@ -179,7 +179,7 @@ func placeEntry(vs []Violation, at ir.WalkPath, key, empty string) []Violation { } // appendRawValue appends a violation to vs when the payload at value is not a -// JSON value, as payloadReaderValue reads it, naming its carrier in what, and +// JSON value, as payloadReader reads it, naming its carrier in what, and // reports whether the payload is valid JSON. // // Reading through reflect.Value.Bytes rather than Interface() keeps Verify a @@ -189,9 +189,9 @@ func placeEntry(vs []Violation, at ir.WalkPath, key, empty string) []Violation { // Nil is reported with malformed and empty bytes: a nil jsontext.Value encodes // as null but decodes back as the four bytes "null", so the document stops // round-tripping to an equal one. -func appendRawValue(vs []Violation, payloadReaderValue *payloadReader, value reflect.Value, what string) ([]Violation, bool) { +func appendRawValue(vs []Violation, payloadReader *payloadReader, value reflect.Value, what string) ([]Violation, bool) { raw := value.Bytes() - if payloadReaderValue.valid(raw) { + if payloadReader.valid(raw) { return vs, true } message := what + " value is not a JSON value, so the document cannot be marshaled" diff --git a/ir/irverify/rawpayloads_internal_test.go b/ir/irverify/rawpayloads_internal_test.go index 0bad1be0b..b7bf2c73b 100644 --- a/ir/irverify/rawpayloads_internal_test.go +++ b/ir/irverify/rawpayloads_internal_test.go @@ -84,9 +84,9 @@ func TestPayloadReader_ReadsAsIsValidDoes(t *testing.T) { } var reader payloadReader var valid int - for _, p := range payloads { - want := jsontext.Value(p).IsValid() - require.Equal(t, want, reader.valid([]byte(p)), "%q", p[:min(len(p), 40)]) + for _, payload := range payloads { + want := jsontext.Value(payload).IsValid() + require.Equal(t, want, reader.valid([]byte(payload)), "%q", payload[:min(len(payload), 40)]) if want { valid++ } diff --git a/ir/irverify/registrychecks_internal_test.go b/ir/irverify/registrychecks_internal_test.go index b1bf81c7d..800c0a608 100644 --- a/ir/irverify/registrychecks_internal_test.go +++ b/ir/irverify/registrychecks_internal_test.go @@ -21,7 +21,7 @@ import ( // tables themselves rather than through the walk. var registryChecks = []func(*ir.Document) []Violation{ checkRegistryKeys, checkIDs, checkMemberIDs, checkPrimitiveIDs, checkPrimitiveKinds, checkAuthKinds, checkModelEnums, checkVersions, checkEnumMemberKinds, - checkUnresolvedSchemes, checkOAuthScopes, checkUnions, checkMaps, checkMapKeys, checkCatchAlls, + checkUnresolvedSchemes, checkOAuthScopes, checkUnions, checkDiscriminatorRoutes, checkDecidedNodes, checkMaps, checkMapKeys, checkCatchAlls, checkBoundKinds, checkRequires, checkVersion, checkDocument, } @@ -89,13 +89,14 @@ func TestRegistryChecks_ACleanEntryCostsNothing(t *testing.T) { } // cleanRegistry returns a sound document holding n of each entry a registry -// check ranges over, beside a primitive of each of a few kinds: a model with -// more properties and Requires entries than a map holds unallocated, a union, a -// map, a model and a map each holding a bound of its kind, an enum whose members -// sit beneath a path longer than a string built on the stack holds, an OAuth -// scheme with more scopes than a map holds unallocated, a server, a declared -// namespace and a source. -func cleanRegistry(n int) *ir.Document { +// check ranges over, beside a few primitives and named scalars: a model with +// more properties and Requires entries than a map holds unallocated, unions, a +// map, a model, a map and an enum each holding a bound of its kind, an enum +// whose members sit beneath a path longer than a string built on the stack +// holds, discriminators spelling no route twice, one over more type names than +// a map holds unallocated, an OAuth scheme with as many scopes, a server, a +// declared namespace and a source. +func cleanRegistry(count int) *ir.Document { doc := &ir.Document{ IRVersion: ir.IRVersion, Types: ir.TypeRegistry{}, @@ -109,9 +110,18 @@ func cleanRegistry(n int) *ir.Document { ID: ir.PrimitiveTypeID(kind), PrimitiveKind: kind, Provenance: ir.Provenance{Source: ir.NoSource}, } } - for i := range n { + tagged := make([]ir.Variant, 0, 12) + for j := range 12 { + named := &ir.Scalar{ID: ir.TypeID(fmt.Sprintf("type/x/Named%d", j)), Name: ir.Naming{Source: fmt.Sprintf("Named%d", j)}} + doc.Types[named.ID] = named + tagged = append(tagged, ir.Variant{Type: ir.TypeRef{Target: named.ID}}) + } + for i := range count { suffix := fmt.Sprintf("%04d", i) model := &ir.Model{ID: ir.TypeID("type/x/M" + suffix), Constraints: &ir.Constraints{MinProperties: new(int64(1))}} + model.Discriminator = &ir.Discriminator{ + Mapping: map[string]ir.TypeID{"m": model.ID}, DecodeOnlyRoutes: map[string]ir.TypeID{"M": model.ID}, + } for j := range 12 { model.Properties = append(model.Properties, ir.Property{WireName: fmt.Sprintf("own%d", j)}) model.Requires = append(model.Requires, fmt.Sprintf("inherited%d", j)) @@ -120,13 +130,17 @@ func cleanRegistry(n int) *ir.Document { enum := &ir.Enum{ID: ir.TypeID("type/x/" + enumPath), ValueType: ir.PrimitiveString, Members: []ir.EnumMember{ {ID: ir.EnumMemberID("enum-member/x/" + enumPath + "/a"), Value: ir.Value{Kind: ir.ValueString, String: "a"}}, {ID: ir.EnumMemberID("enum-member/x/" + enumPath + "/b"), Value: ir.Value{Kind: ir.ValueString, String: "b"}}, - }} - for _, td := range []ir.TypeDef{ + }, Constraints: &ir.Constraints{MaxLength: new(int64(1))}} + for _, typeDef := range []ir.TypeDef{ model, enum, &ir.Union{ID: ir.TypeID("type/x/U" + suffix), Variants: []ir.Variant{{}}}, + &ir.Union{ + ID: ir.TypeID("type/x/Tagged" + suffix), WireTagged: true, Variants: tagged, + Discriminator: &ir.Discriminator{PropertyName: "kind", DecodeOnlyRoutes: map[string]ir.TypeID{"e": "type/x/Named0"}}, + }, &ir.MapT{ID: ir.TypeID("type/x/Map" + suffix), Constraints: &ir.Constraints{MaxProperties: new(int64(1))}}, } { - doc.Types[td.Common().ID] = td + doc.Types[typeDef.Common().ID] = typeDef } flow := ir.OAuthFlow{Kind: "client_credentials"} for j := range 12 { diff --git a/ir/irverify/requires.go b/ir/irverify/requires.go index b874788bc..16c368b17 100644 --- a/ir/irverify/requires.go +++ b/ir/irverify/requires.go @@ -21,8 +21,8 @@ func checkRequires(doc *ir.Document) []Violation { // own however many properties and entries it has. var owned scratchstate.Map[string, bool] var listed scratchstate.Map[string, int] - for id, td := range doc.Types { - model, isModel := td.(*ir.Model) + for id, typeDef := range doc.Types { + model, isModel := typeDef.(*ir.Model) if !isModel || model == nil || len(model.Requires) == 0 { continue // a nil entry is checkRegistryKeys's to report } diff --git a/ir/irverify/requires_test.go b/ir/irverify/requires_test.go index b5e06bc63..591629212 100644 --- a/ir/irverify/requires_test.go +++ b/ir/irverify/requires_test.go @@ -108,15 +108,15 @@ func TestVerify_RequiresHoldsNoOwnPropertyAndNoRepeat(t *testing.T) { } for _, tc := range []struct { - name string - td ir.TypeDef + name string + typeDef ir.TypeDef }{ {"a type that is no model", &ir.Scalar{ID: "type/x/M", Name: named("m")}}, {"a nil model", (*ir.Model)(nil)}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - doc := &ir.Document{Types: ir.TypeRegistry{"type/x/M": tc.td}} + doc := &ir.Document{Types: ir.TypeRegistry{"type/x/M": tc.typeDef}} for _, violation := range irverify.Verify(doc) { assert.False(t, strings.HasPrefix(violation.Code, "ir/requires-"), "unexpected %+v", violation) diff --git a/ir/irverify/scenario_input_test.go b/ir/irverify/scenario_input_test.go index 47709e901..de49ca152 100644 --- a/ir/irverify/scenario_input_test.go +++ b/ir/irverify/scenario_input_test.go @@ -11,8 +11,8 @@ import ( "github.com/dexpace/morphic/ir" ) -// scenarioValue is the string value a scenario's parameters and body hold. -var scenarioValue = ir.Value{Kind: ir.ValueString, String: "v"} +// scenario is the string value a scenario's parameters and body hold. +var scenario = ir.Value{Kind: ir.ValueString, String: "v"} // scenarioOperationPath is the path of the first operation of scenarioBase. const scenarioOperationPath = "document.Services[0].Groups[0].Operations[0]" @@ -77,14 +77,14 @@ func TestVerify_ScenarioKeyNamesADeclaredParameter(t *testing.T) { const code = "ir/dangling-parameter-ref" doc := scenarioBase() scenarioOperation(doc).Examples = []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{ - Params: map[ir.ParameterID]ir.Value{"parameter/x/none": scenarioValue}, + Params: map[ir.ParameterID]ir.Value{"parameter/x/none": scenario}, }}} assert.Equal(t, []string{scenarioOperationPath + ".Examples[0].Input.Params[parameter/x/none].key"}, scenarioCodes(doc, code)) valid := scenarioBase() scenarioOperation(valid).Examples = []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{ - Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenarioValue}, + Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenario}, }}} assert.Empty(t, scenarioCodes(valid, code)) } @@ -97,14 +97,14 @@ func TestVerify_ScenarioKeyIsNeverEmpty(t *testing.T) { const code = "ir/empty-parameter-ref" doc := scenarioBase() scenarioOperation(doc).Examples = []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{ - Params: map[ir.ParameterID]ir.Value{"": scenarioValue}, + Params: map[ir.ParameterID]ir.Value{"": scenario}, }}} assert.Equal(t, []string{scenarioOperationPath + ".Examples[0].Input.Params[].key"}, scenarioCodes(doc, code)) valid := scenarioBase() scenarioOperation(valid).Examples = []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{ - Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenarioValue}, + Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenario}, }}} assert.Empty(t, scenarioCodes(valid, code)) } @@ -115,7 +115,7 @@ func TestVerify_ScenarioKeyIsNeverEmpty(t *testing.T) { func TestVerify_ScenarioBodyNeedsARequest(t *testing.T) { t.Parallel() const code = "ir/input-body-absent" - body := scenarioValue + body := scenario input := func() []ir.Example { return []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{Body: &body}}} } @@ -141,8 +141,8 @@ func TestVerify_ScenarioBodyNeedsARequest(t *testing.T) { func TestVerify_ScenarioBodyIsStatedOneWay(t *testing.T) { t.Parallel() const code = "ir/input-body-twice" - object := ir.Value{Kind: ir.ValueObject, Object: []ir.Field{{Name: "a", Value: scenarioValue}}} - stringValue := scenarioValue + object := ir.Value{Kind: ir.ValueObject, Object: []ir.Field{{Name: "a", Value: scenario}}} + text := scenario for _, tc := range []struct { name string bind ir.HTTPParamBinding @@ -158,7 +158,7 @@ func TestVerify_ScenarioBodyIsStatedOneWay(t *testing.T) { { name: "a parameter bound as the whole body, valued beside the Body", bind: ir.HTTPParamBinding{Param: "parameter/x/o/q", Location: ir.HTTPLocationBody}, - input: ir.ScenarioInput{Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenarioValue}, Body: &stringValue}, + input: ir.ScenarioInput{Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenario}, Body: &text}, }, } { t.Run(tc.name, func(t *testing.T) { @@ -196,7 +196,7 @@ func TestVerify_ScenarioParamValueIsHeldAsAnyValue(t *testing.T) { valid := scenarioBase() scenarioOperation(valid).Examples = []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{ - Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenarioValue}, + Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": scenario}, }}} assert.Empty(t, scenarioCodes(valid, code)) } @@ -209,7 +209,7 @@ func TestVerify_ScenarioKeyOfAnotherOperationIsNotIrverifys(t *testing.T) { t.Parallel() doc := scenarioBase() scenarioOperation(doc).Examples = []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{ - Params: map[ir.ParameterID]ir.Value{"parameter/x/p/z": scenarioValue}, + Params: map[ir.ParameterID]ir.Value{"parameter/x/p/z": scenario}, }}} got := verifyDeclared(doc) diff --git a/ir/irverify/streams.go b/ir/irverify/streams.go index bba17d03b..c67b2184d 100644 --- a/ir/irverify/streams.go +++ b/ir/irverify/streams.go @@ -41,15 +41,15 @@ var contentPath = map[reflect.Type]bool{ func checkContentStreams(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - switch v.Type() { + visit: func(value reflect.Value, at ir.WalkPath) bool { + switch value.Type() { case operationType: - if operation, ok := reflect.TypeAssert[ir.Operation](v); ok { + if operation, ok := reflect.TypeAssert[ir.Operation](value); ok { vs = appendUnsummarizedStreams(vs, &operation, at) } return true case contentType: - if content, ok := reflect.TypeAssert[ir.Content](v); ok && content.Item != nil && content.Stream == nil { + if content, ok := reflect.TypeAssert[ir.Content](value); ok && content.Item != nil && content.Stream == nil { vs = append(vs, Violation{ Code: "ir/content-item-without-stream", Message: "content declares a stream item and is not marked as streaming", @@ -58,7 +58,7 @@ func checkContentStreams(*ir.Document) walkCheck { } return false default: - return operationPath[v.Type()] || contentPath[v.Type()] + return operationPath[value.Type()] || contentPath[value.Type()] } }, report: reporting(&vs), diff --git a/ir/irverify/streams_test.go b/ir/irverify/streams_test.go index 2a1511d07..d6a4e3fc9 100644 --- a/ir/irverify/streams_test.go +++ b/ir/irverify/streams_test.go @@ -56,10 +56,10 @@ func TestVerify_AContentDeclaringAnItemStreams(t *testing.T) { } // TestVerify_AStreamingContentHasItsSidesDetail pins -// ir/content-stream-without-detail on each side apart: a request's or a -// success response's content that streams needs that side's StreamDetail, the -// other side's standing for nothing. An error's or the default's content -// streams with none, and a side may stream with no content that does. +// ir/content-stream-without-detail on each side apart: a request's or a success +// response's content that streams needs that side's StreamDetail, the other +// side's naming nothing. An error's or the default's content streams with none, +// and a side may stream with no content that does. func TestVerify_AStreamingContentHasItsSidesDetail(t *testing.T) { t.Parallel() const operationPath = "document.Services[0].Groups[0].Operations[0]" diff --git a/ir/irverify/stringlists.go b/ir/irverify/stringlists.go index e24dab20c..cf0ba907b 100644 --- a/ir/irverify/stringlists.go +++ b/ir/irverify/stringlists.go @@ -80,6 +80,10 @@ var stringLists = map[string]listRule{ // Document holds: names Requires lists, each once. "Flattening.Undeclared": listMembers, "flattener.requires": listMembers, + // A value admission reader's own state, which no Document holds either: + // the members a model requires, by wire name, each once. + "modelFacts.required": listMembers, + "admissionEdge.requires": listMembers, "Availability.Added": listVersions, "Availability.Removed": listVersions, @@ -110,23 +114,23 @@ func checkStringLists(doc *ir.Document) walkCheck { // own however long it is. var entries scratchstate.Map[string, int] return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() != reflect.Struct { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() != reflect.Struct { return true } - if v.Type() == availabilityType { - if a, ok := reflect.TypeAssert[ir.Availability](v); ok { - vs = appendAvailabilityViolations(vs, a, at, positions) + if value.Type() == availabilityType { + if availability, ok := reflect.TypeAssert[ir.Availability](value); ok { + vs = appendAvailabilityViolations(vs, availability, at, positions) } return true } - byType, seen := fields[v.Type()] + byType, seen := fields[value.Type()] if !seen { - byType = heldListsOf(v.Type()) - fields[v.Type()] = byType + byType = heldListsOf(value.Type()) + fields[value.Type()] = byType } for _, heldList := range byType { - vs = appendListViolations(vs, v.Field(heldList.index), at, heldList, &entries) + vs = appendListViolations(vs, value.Field(heldList.index), at, heldList, &entries) } return true }, @@ -150,10 +154,10 @@ func heldListsOf(t reflect.Type) []heldList { return out } -// appendListViolations reports each entry of the held list heldListValue that +// appendListViolations reports each entry of the held list heldList that // breaks its rule, at the entry itself; owner is where the struct holding it // sits, and entries is what the list is read through. -func appendListViolations(vs []Violation, list reflect.Value, owner ir.WalkPath, heldListValue heldList, +func appendListViolations(vs []Violation, list reflect.Value, owner ir.WalkPath, heldList heldList, entries *scratchstate.Map[string, int], ) []Violation { first := entries.Emptied() @@ -161,14 +165,14 @@ func appendListViolations(vs []Violation, list reflect.Value, owner ir.WalkPath, entry := list.Index(i).String() switch earlier, repeated := first[entry]; { case isBlankName(entry): - vs = append(vs, blankEntry(heldListValue.rule, entryPath(owner, heldListValue, i))) + vs = append(vs, blankEntry(heldList.rule, entryPath(owner, heldList, i))) case !utf8.ValidString(entry): // checkUTF8 reports it. - case heldListValue.rule == listSet && repeated: + case heldList.rule == listSet && repeated: vs = append(vs, Violation{ Code: "ir/set-entry-duplicate", Message: "set entry " + strconv.Quote(entry) + " is listed here and at index " + strconv.Itoa(earlier), - Path: entryPath(owner, heldListValue, i), + Path: entryPath(owner, heldList, i), }) default: first[entry] = i @@ -177,10 +181,10 @@ func appendListViolations(vs []Violation, list reflect.Value, owner ir.WalkPath, return vs } -// entryPath spells entry i of the held list heldListValue of the struct at +// entryPath spells entry i of the held list heldList of the struct at // owner, as the walk spells the entry itself. -func entryPath(owner ir.WalkPath, heldListValue heldList, i int) string { - return owner.String() + "." + heldListValue.name + "[" + strconv.Itoa(i) + "]" +func entryPath(owner ir.WalkPath, heldList heldList, i int) string { + return owner.String() + "." + heldList.name + "[" + strconv.Itoa(i) + "]" } // blankEntry is the violation a blank entry of a held list draws. diff --git a/ir/irverify/stringlists_test.go b/ir/irverify/stringlists_test.go index 255ca0a74..27f41dc2e 100644 --- a/ir/irverify/stringlists_test.go +++ b/ir/irverify/stringlists_test.go @@ -184,10 +184,10 @@ func TestVerify_ListEntryIsSpelledAsTheWalkWould(t *testing.T) { doc := heldListDoc() list.set(doc, entries) walked := map[string]string{} // entry → the path the walk renders for it - ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { path := at.String() - if v.Kind() == reflect.String { - walked[v.String()] = path + if value.Kind() == reflect.String { + walked[value.String()] = path } return true })) diff --git a/ir/irverify/typerefs.go b/ir/irverify/typerefs.go index 74c61f05b..5195d99e2 100644 --- a/ir/irverify/typerefs.go +++ b/ir/irverify/typerefs.go @@ -24,18 +24,18 @@ var typeRefType = reflect.TypeFor[ir.TypeRef]() func checkTypeRefs(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() != reflect.Struct || v.Type() != typeRefType { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() != reflect.Struct || value.Type() != typeRefType { return true } - if v.FieldByName("Target").String() == "" { + if value.FieldByName("Target").String() == "" { vs = append(vs, Violation{ Code: "ir/type-ref-no-target", Message: "type reference names no target", Path: at.String() + ".Target", }) } - if inferred := v.FieldByName("Inferred").String(); inferred != "" && !v.FieldByName("Nullable").Bool() { + if inferred := value.FieldByName("Inferred").String(); inferred != "" && !value.FieldByName("Nullable").Bool() { vs = append(vs, Violation{ Code: "ir/type-ref-inferred-not-nullable", Message: "type reference is marked inferred by " + strconv.Quote(inferred) + " but admits no null", diff --git a/ir/irverify/typerefs_test.go b/ir/irverify/typerefs_test.go index ced0b771c..a9d3a4bb1 100644 --- a/ir/irverify/typerefs_test.go +++ b/ir/irverify/typerefs_test.go @@ -27,8 +27,8 @@ func leaf() *ir.Scalar { func closedDoc(tds ...ir.TypeDef) *ir.Document { scalar := leaf() reg := ir.TypeRegistry{scalar.ID: scalar} - for _, td := range tds { - reg[td.Common().ID] = td + for _, typeDef := range tds { + reg[typeDef.Common().ID] = typeDef } return &ir.Document{Types: reg} } diff --git a/ir/irverify/unions.go b/ir/irverify/unions.go index 0b791fa0c..380d1d2c3 100644 --- a/ir/irverify/unions.go +++ b/ir/irverify/unions.go @@ -19,11 +19,11 @@ import ( // naming one target, degenerate rather than impossible. func checkUnions(doc *ir.Document) []Violation { var vs []Violation - for id, td := range doc.Types { - if ir.IsNilTypeDef(td) { + for id, typeDef := range doc.Types { + if ir.IsNilTypeDef(typeDef) { continue // checkRegistryKeys reports the nil entry itself } - union, isUnion := td.(*ir.Union) + union, isUnion := typeDef.(*ir.Union) if !isUnion { continue } diff --git a/ir/irverify/unreferenced.go b/ir/irverify/unreferenced.go index 191d54396..7988e39fc 100644 --- a/ir/irverify/unreferenced.go +++ b/ir/irverify/unreferenced.go @@ -33,13 +33,13 @@ func noUnreferencedReports(declarations) []Violation { return nil } // Targets). A truncated walk reports nothing here, as ir/walk-truncated // already notes the incomplete check. func checkUnreferencedAnonymousTypes(doc *ir.Document) walkCheck { - g := newAnonGraph(doc.Types) - if g == nil { + graph := newAnonGraph(doc.Types) + if graph == nil { return walkCheck{report: noUnreferencedReports} } return walkCheck{ - visit: g.visit, - report: g.report, + visit: graph.visit, + report: graph.report, } } @@ -58,40 +58,40 @@ type anonGraph struct { // newAnonGraph indexes the anonymous types of types, or returns nil when none // exist. func newAnonGraph(types ir.TypeRegistry) *anonGraph { - var n int - for _, td := range types { - if !ir.IsNilTypeDef(td) && td.Common().Anonymous { - n++ + var count int + for _, typeDef := range types { + if !ir.IsNilTypeDef(typeDef) && typeDef.Common().Anonymous { + count++ } } - if n == 0 { + if count == 0 { return nil } - ids := make([]ir.TypeID, 0, n) - for id, td := range types { - if !ir.IsNilTypeDef(td) && td.Common().Anonymous { + ids := make([]ir.TypeID, 0, count) + for id, typeDef := range types { + if !ir.IsNilTypeDef(typeDef) && typeDef.Common().Anonymous { ids = append(ids, id) } } slices.Sort(ids) - index := make(map[ir.TypeID]int, n) + index := make(map[ir.TypeID]int, count) for i, id := range ids { index[id] = i } return &anonGraph{ anonIDs: ids, anonIndex: index, - reached: make([]bool, n), - stack: make([]int, 0, n), - edges: make([]anonEdge, 0, max(16, 4*n)), + reached: make([]bool, count), + stack: make([]int, 0, count), + edges: make([]anonEdge, 0, max(16, 4*count)), ownerIndex: -1, } } // visit tracks whether the shared walk is inside Document.Types and records // every typed ir.TypeID edge reaching an anonymous type. -func (g *anonGraph) visit(v reflect.Value, at ir.WalkPath) bool { - t := v.Type() +func (g *anonGraph) visit(value reflect.Value, at ir.WalkPath) bool { + t := value.Type() if t == typeRegistryType { g.inTypes = true g.ownerIndex = -1 @@ -102,7 +102,7 @@ func (g *anonGraph) visit(v reflect.Value, at ir.WalkPath) bool { g.ownerIndex = -1 } if g.inTypes && at.IsMapKey() && t == typeIDType { - key, _ := reflect.TypeAssert[ir.TypeID](v) + key, _ := reflect.TypeAssert[ir.TypeID](value) if index, ok := g.anonIndex[key]; ok { g.ownerIndex = index } else { @@ -116,7 +116,7 @@ func (g *anonGraph) visit(v reflect.Value, at ir.WalkPath) bool { if _, field, ok := at.Field(); ok && field == "ID" { return false } - id, _ := reflect.TypeAssert[ir.TypeID](v) + id, _ := reflect.TypeAssert[ir.TypeID](value) g.record(id) return false } @@ -143,11 +143,11 @@ func (g *anonGraph) record(id ir.TypeID) { // report propagates reachability across anonymous-to-anonymous edges and // returns a violation for every anonymous type left unreachable. func (g *anonGraph) report(decls declarations) []Violation { - n := len(g.anonIDs) - if decls.truncated || len(g.stack) == n { + count := len(g.anonIDs) + if decls.truncated || len(g.stack) == count { return nil } - if g.propagate() == n { + if g.propagate() == count { return nil } var vs []Violation @@ -170,19 +170,19 @@ func (g *anonGraph) propagate() int { if reachedCount == 0 || len(g.edges) == 0 { return reachedCount } - n := len(g.anonIDs) - offsets := make([]int, n+1) - for _, e := range g.edges { - offsets[e.from+1]++ + count := len(g.anonIDs) + offsets := make([]int, count+1) + for _, edge := range g.edges { + offsets[edge.from+1]++ } - for i := 1; i <= n; i++ { + for i := 1; i <= count; i++ { offsets[i] += offsets[i-1] } adj := make([]int, len(g.edges)) - cursor := slices.Clone(offsets[:n]) - for _, e := range g.edges { - adj[cursor[e.from]] = e.to - cursor[e.from]++ + cursor := slices.Clone(offsets[:count]) + for _, edge := range g.edges { + adj[cursor[edge.from]] = edge.to + cursor[edge.from]++ } for len(g.stack) > 0 { cur := g.stack[len(g.stack)-1] diff --git a/ir/irverify/unresolved_test.go b/ir/irverify/unresolved_test.go index 8c76dca53..da85ae524 100644 --- a/ir/irverify/unresolved_test.go +++ b/ir/irverify/unresolved_test.go @@ -21,8 +21,8 @@ func schemeDoc(scheme ir.AuthScheme) *ir.Document { return &ir.Document{IRVersion: ir.IRVersion, Auth: map[ir.AuthID]ir.AuthScheme{scheme.ID: scheme}} } -// TestVerify_AnUnresolvedSchemeInItsSpaceIsClean holds the silent half of both -// rules: what the rules allow beside a name must verify. +// TestVerify_AnUnresolvedSchemeInItsSpaceIsClean holds the report-nothing half +// of both rules: what the rules allow beside a name must verify. func TestVerify_AnUnresolvedSchemeInItsSpaceIsClean(t *testing.T) { t.Parallel() scheme := ir.AuthScheme{ diff --git a/ir/irverify/utf8.go b/ir/irverify/utf8.go index 1b04f0662..a2e11db43 100644 --- a/ir/irverify/utf8.go +++ b/ir/irverify/utf8.go @@ -25,8 +25,8 @@ import ( func checkUTF8(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() == reflect.String && !utf8.ValidString(v.String()) { + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() == reflect.String && !utf8.ValidString(value.String()) { // The message quotes nothing: the bytes would be repeated into the // report. vs = append(vs, Violation{ diff --git a/ir/irverify/utf8_test.go b/ir/irverify/utf8_test.go index 1315755c6..8bcf77e69 100644 --- a/ir/irverify/utf8_test.go +++ b/ir/irverify/utf8_test.go @@ -45,8 +45,8 @@ func utf8Carriers() []utf8Carrier { return []utf8Carrier{ { name: "type registry key and its node ID", - plant: func(s string) (*ir.Document, []string) { - id := ir.TypeID("type/x/" + s) + plant: func(text string) (*ir.Document, []string) { + id := ir.TypeID("type/x/" + text) model := &ir.Model{ID: id, Name: ir.Naming{Source: "Model", Canonical: "model"}} doc := &ir.Document{IRVersion: ir.IRVersion, Types: ir.TypeRegistry{id: model}} path := "document.Types[" + string(id) + "]" @@ -56,21 +56,21 @@ func utf8Carriers() []utf8Carrier { }, { name: "Docs.Description", - plant: func(s string) (*ir.Document, []string) { + plant: func(text string) (*ir.Document, []string) { doc := validDoc() - doc.Docs.Description = s + doc.Docs.Description = text return doc, []string{"document.Docs.Description"} }, repair: "fine", }, { name: "a string Value.Str", - plant: func(s string) (*ir.Document, []string) { + plant: func(text string) (*ir.Document, []string) { doc := validDoc() doc.Types["type/x/L"] = &ir.Literal{ ID: "type/x/L", Name: ir.Naming{Source: "l", Canonical: "l"}, - Value: ir.Value{Kind: ir.ValueString, String: s}, + Value: ir.Value{Kind: ir.ValueString, String: text}, } return doc, []string{"document.Types[type/x/L].Value.String"} }, @@ -78,23 +78,23 @@ func utf8Carriers() []utf8Carrier { }, { name: "Document.Name", - plant: func(s string) (*ir.Document, []string) { + plant: func(text string) (*ir.Document, []string) { doc := validDoc() - doc.Name = s + doc.Name = text return doc, []string{"document.Name"} }, repair: "Fine API", }, { name: "a diagnostic message", - plant: func(s string) (*ir.Document, []string) { + plant: func(text string) (*ir.Document, []string) { doc := validDoc() doc.Diagnostics = []ir.Diagnostic{ // A leading, clean diagnostic built through the constructor pins // that the path addresses this entry by its own index rather than // the slice as a whole. ir.NewDiagnostic(ir.SeverityWarning, "openapi/validation", "clean", ir.Provenance{}), - {Severity: ir.SeverityError, Code: "openapi/validation", Message: s}, + {Severity: ir.SeverityError, Code: "openapi/validation", Message: text}, } return doc, []string{"document.Diagnostics[1].Message"} }, @@ -102,9 +102,9 @@ func utf8Carriers() []utf8Carrier { }, { name: "a diagnostic's provenance pointer", - plant: func(s string) (*ir.Document, []string) { + plant: func(text string) (*ir.Document, []string) { doc := validDoc() - pointer := jsontext.Pointer("/components/schemas/" + s) + pointer := jsontext.Pointer("/components/schemas/" + text) doc.Diagnostics = []ir.Diagnostic{ ir.NewDiagnostic(ir.SeverityError, "openapi/validation", "message", ir.Provenance{Pointer: pointer}), } @@ -118,11 +118,11 @@ func utf8Carriers() []utf8Carrier { }, { name: "a diagnostic's provenance node", - plant: func(s string) (*ir.Document, []string) { + plant: func(text string) (*ir.Document, []string) { doc := validDoc() doc.Diagnostics = []ir.Diagnostic{ ir.NewDiagnostic(ir.SeverityError, "ir/dangling-type-ref", "message", - ir.Provenance{Source: ir.NoSource, Node: s}), + ir.Provenance{Source: ir.NoSource, Node: text}), } return doc, []string{"document.Diagnostics[0].Provenance.Node"} }, @@ -132,42 +132,42 @@ func utf8Carriers() []utf8Carrier { }, { name: "an Unmodeled map key", - plant: func(s string) (*ir.Document, []string) { + plant: func(text string) (*ir.Document, []string) { doc := docWithUnmodeled(ir.Unmodeled{ - "openapi:" + s: {Reason: ir.ReasonVendorExtension, Value: ir.RawValue(`1`)}, + "openapi:" + text: {Reason: ir.ReasonVendorExtension, Value: ir.RawValue(`1`)}, }) - return doc, []string{"document.Types[type/x/Model].Unmodeled[openapi:" + s + "].key"} + return doc, []string{"document.Types[type/x/Model].Unmodeled[openapi:" + text + "].key"} }, repair: "x-rate-limit", }, { name: "Naming.Source", - plant: func(s string) (*ir.Document, []string) { - doc := modelNamed(ir.Naming{Source: s, Canonical: ir.CanonicalWords(s)}) + plant: func(text string) (*ir.Document, []string) { + doc := modelNamed(ir.Naming{Source: text, Canonical: ir.CanonicalWords(text)}) return doc, []string{"document.Types[type/x/M].Name.Source"} }, repair: "good", }, { name: "Naming.Canonical", - plant: func(s string) (*ir.Document, []string) { - return canonicalOnly(s), []string{"document.Types[type/x/M].Name.Canonical"} + plant: func(text string) (*ir.Document, []string) { + return canonicalOnly(text), []string{"document.Types[type/x/M].Name.Canonical"} }, repair: "good", others: []string{"ir/naming-cased", "ir/naming-not-words"}, }, { name: "Naming.Hint", - plant: func(s string) (*ir.Document, []string) { - return hintOnly(s), []string{"document.Types[type/x/M].Name.Hint"} + plant: func(text string) (*ir.Document, []string) { + return hintOnly(text), []string{"document.Types[type/x/M].Name.Hint"} }, repair: "good", others: []string{"ir/naming-cased", "ir/naming-not-words"}, }, { name: "a Naming alias", - plant: func(s string) (*ir.Document, []string) { - doc := modelNamed(ir.Naming{Source: "m", Canonical: "m", Aliases: []string{"ok", s}}) + plant: func(text string) (*ir.Document, []string) { + doc := modelNamed(ir.Naming{Source: "m", Canonical: "m", Aliases: []string{"ok", text}}) return doc, []string{"document.Types[type/x/M].Name.Aliases[1]"} }, repair: "good", diff --git a/ir/irverify/values.go b/ir/irverify/values.go index 81955d998..d10e1fa86 100644 --- a/ir/irverify/values.go +++ b/ir/irverify/values.go @@ -59,9 +59,9 @@ var valuePayloads = map[ir.ValueKind]payloadRule{ func checkValues(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() == valueType { - vs = appendValueViolations(vs, v, at) + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() == valueType { + vs = appendValueViolations(vs, value, at) } return true }, @@ -72,8 +72,8 @@ func checkValues(*ir.Document) walkCheck { // appendValueViolations reports one value's defects. An undeclared kind selects // nothing, so its payloads are not judged: every one would be reported as stray // when the repair is the kind. -func appendValueViolations(vs []Violation, v reflect.Value, at ir.WalkPath) []Violation { - kind := v.FieldByName("Kind").String() +func appendValueViolations(vs []Violation, value reflect.Value, at ir.WalkPath) []Violation { + kind := value.FieldByName("Kind").String() rule, declared := valuePayloads[ir.ValueKind(kind)] if !declared { return append(vs, Violation{ @@ -82,13 +82,13 @@ func appendValueViolations(vs []Violation, v reflect.Value, at ir.WalkPath) []Vi Path: at.String() + ".Kind", }) } - t := v.Type() + t := value.Type() for i := range t.NumField() { name := t.Field(i).Name if name == "Kind" { continue } - set := payloadSet(v.Field(i)) + set := payloadSet(value.Field(i)) switch { case name != rule.field && set: vs = append(vs, Violation{ diff --git a/ir/irverify/values_internal_test.go b/ir/irverify/values_internal_test.go index 55c1fec75..e8526ca24 100644 --- a/ir/irverify/values_internal_test.go +++ b/ir/irverify/values_internal_test.go @@ -4,6 +4,7 @@ package irverify import ( + "go/token" "go/types" "slices" "testing" @@ -77,6 +78,8 @@ func TestValuePayloads_NameValueFields(t *testing.T) { // named "Type.Field", sorted. Value, Field and ConstructorValue are left out: // they are a value's own payload, reached only below a value the walk has // already found, which TestVerify_NestedStrayPayloadIsReportedAtItsPath covers. +// So is a field of an unexported type, a reader's own state, which no Document +// holds, since one encodes exported types alone. func valueCarriers(t *testing.T) []string { t.Helper() value, err := irDecls(t).Named("Value") @@ -85,7 +88,8 @@ func valueCarriers(t *testing.T) []string { var out []string for _, declaredField := range declaredFields(t) { - if payloadTypes[declaredField.owner] || !holdsValue(t, value, declaredField.field.Type(), 0) { + if payloadTypes[declaredField.owner] || !token.IsExported(declaredField.owner) || + !holdsValue(t, value, declaredField.field.Type(), 0) { continue } out = append(out, declaredField.key()) diff --git a/ir/irverify/values_test.go b/ir/irverify/values_test.go index 7949a2d61..d81e3a544 100644 --- a/ir/irverify/values_test.go +++ b/ir/irverify/values_test.go @@ -337,9 +337,9 @@ func TestVerify_NullValueWithPayloadIsAViolation(t *testing.T) { } } -// TestVerify_NullValueWithNoPayloadIsClean is the silent half: null is a value -// in its own right, so an empty payload beside it raises no question at all, -// stray or missing. +// TestVerify_NullValueWithNoPayloadIsClean is the report-nothing half: null is +// a value in its own right, so an empty payload beside it raises no question at +// all, stray or missing. func TestVerify_NullValueWithNoPayloadIsClean(t *testing.T) { t.Parallel() locs, _ := valueViolations(valueDoc(ir.Value{Kind: ir.ValueNull})) diff --git a/ir/irverify/versions.go b/ir/irverify/versions.go index fc48316cc..1756db289 100644 --- a/ir/irverify/versions.go +++ b/ir/irverify/versions.go @@ -81,28 +81,27 @@ func (s labelSite) path(owner string) string { return path + s.sub } -// labelSites returns every version label a, written by Availability, names, in -// field order. -func labelSites(a *ir.Availability) []labelSite { - sites := make([]labelSite, 0, len(a.Added)+len(a.Removed)+1+len(a.RenamedFrom)+len(a.TypeChangedFrom)+ - len(a.RequiredChanged)) - for i, label := range a.Added { +// labelSites returns every version label availability names, in field order. +func labelSites(availability *ir.Availability) []labelSite { + sites := make([]labelSite, 0, len(availability.Added)+len(availability.Removed)+1+len(availability.RenamedFrom)+len(availability.TypeChangedFrom)+ + len(availability.RequiredChanged)) + for i, label := range availability.Added { sites = append(sites, labelSite{".Added", i, label, ""}) } - for i, label := range a.Removed { + for i, label := range availability.Removed { sites = append(sites, labelSite{".Removed", i, label, ""}) } - if a.Deprecated != "" { - sites = append(sites, labelSite{".Deprecated", -1, a.Deprecated, ""}) + if availability.Deprecated != "" { + sites = append(sites, labelSite{".Deprecated", -1, availability.Deprecated, ""}) } - for i, versionedName := range a.RenamedFrom { + for i, versionedName := range availability.RenamedFrom { sites = append(sites, labelSite{".RenamedFrom", i, versionedName.Version, ".Version"}) } - for i, versionedType := range a.TypeChangedFrom { + for i, versionedType := range availability.TypeChangedFrom { sites = append(sites, labelSite{".TypeChangedFrom", i, versionedType.Version, ".Version"}) } - for i, b := range a.RequiredChanged { - sites = append(sites, labelSite{".RequiredChanged", i, b.Version, ".Version"}) + for i, change := range availability.RequiredChanged { + sites = append(sites, labelSite{".RequiredChanged", i, change.Version, ".Version"}) } return sites } @@ -113,12 +112,12 @@ func labelSites(a *ir.Availability) []labelSite { // follow: each ascends in Versions order, and merged they alternate. Either // may come first, so a Removed first says the entity is there from the first // version. -func appendAvailabilityViolations(vs []Violation, a ir.Availability, owner ir.WalkPath, +func appendAvailabilityViolations(vs []Violation, availability ir.Availability, owner ir.WalkPath, positions map[string]int, ) []Violation { at := owner.String() undeclared := false - for _, site := range labelSites(&a) { + for _, site := range labelSites(&availability) { if _, declared := positions[site.label]; declared { continue } @@ -132,7 +131,7 @@ func appendAvailabilityViolations(vs []Violation, a ir.Availability, owner ir.Wa if undeclared { return vs } - if broken, ok := firstOrderBreak(a, positions); ok { + if broken, ok := firstOrderBreak(availability, positions); ok { vs = append(vs, Violation{ Code: "ir/availability-out-of-order", Message: strconv.Quote(broken.label) + " does not follow " + strconv.Quote(broken.prev) + @@ -150,18 +149,18 @@ type orderBreak struct { prev string } -// firstOrderBreak returns the first entry of a that breaks the order Added and -// Removed follow, given the position of every label in Versions: an entry that -// does not come after the one before it in its own list, else one that does not -// alternate in the two lists merged by position. -func firstOrderBreak(a ir.Availability, positions map[string]int) (orderBreak, bool) { - if broken, ok := ascendingBreak(".Added", a.Added, positions); ok { +// firstOrderBreak returns the first entry of availability that breaks the order +// Added and Removed follow, given the position of every label in Versions: an +// entry that does not come after the one before it in its own list, else one +// that does not alternate in the two lists merged by position. +func firstOrderBreak(availability ir.Availability, positions map[string]int) (orderBreak, bool) { + if broken, ok := ascendingBreak(".Added", availability.Added, positions); ok { return broken, true } - if broken, ok := ascendingBreak(".Removed", a.Removed, positions); ok { + if broken, ok := ascendingBreak(".Removed", availability.Removed, positions); ok { return broken, true } - return alternationBreak(a, positions) + return alternationBreak(availability, positions) } // ascendingBreak returns the first entry of labels, the entries of field, at @@ -178,18 +177,18 @@ func ascendingBreak(field string, labels []string, positions map[string]int) (or // alternationBreak merges Added and Removed by position, an Added placed before // a Removed of its version, and returns the first entry that is of the same // list as the one before it or at its position. -func alternationBreak(a ir.Availability, positions map[string]int) (orderBreak, bool) { +func alternationBreak(availability ir.Availability, positions map[string]int) (orderBreak, bool) { var prev labelSite added, removed := 0, 0 - for added < len(a.Added) || removed < len(a.Removed) { + for added < len(availability.Added) || removed < len(availability.Removed) { var next labelSite - takeAdded := removed == len(a.Removed) || - (added < len(a.Added) && positions[a.Added[added]] <= positions[a.Removed[removed]]) + takeAdded := removed == len(availability.Removed) || + (added < len(availability.Added) && positions[availability.Added[added]] <= positions[availability.Removed[removed]]) if takeAdded { - next = labelSite{".Added", added, a.Added[added], ""} + next = labelSite{".Added", added, availability.Added[added], ""} added++ } else { - next = labelSite{".Removed", removed, a.Removed[removed], ""} + next = labelSite{".Removed", removed, availability.Removed[removed], ""} removed++ } if prev.label != "" && (next.field == prev.field || positions[next.label] == positions[prev.label]) { diff --git a/ir/irverify/webhooks.go b/ir/irverify/webhooks.go index e4bec988e..297bb6e0e 100644 --- a/ir/irverify/webhooks.go +++ b/ir/irverify/webhooks.go @@ -40,12 +40,12 @@ var webhookPath = func() map[reflect.Type]bool { func checkWebhookRoutes(*ir.Document) walkCheck { var vs []Violation return walkCheck{ - visit: func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != httpBindingType { - return webhookPath[v.Type()] + visit: func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != httpBindingType { + return webhookPath[value.Type()] } - if b, ok := reflect.TypeAssert[ir.HTTPBinding](v); ok { - vs = appendStrayRoute(vs, b, at) + if binding, ok := reflect.TypeAssert[ir.HTTPBinding](value); ok { + vs = appendStrayRoute(vs, binding, at) } return false }, @@ -54,29 +54,29 @@ func checkWebhookRoutes(*ir.Document) walkCheck { } // appendStrayRoute reports an Inbound ir does not declare, or else the route -// field b fills that its Inbound does not select. A binding draws one at most: -// the two route fields exclude each other, and an undeclared kind selects +// field binding fills that its Inbound does not select. A binding draws one at +// most: the two route fields exclude each other, and an undeclared kind selects // neither. -func appendStrayRoute(vs []Violation, b ir.HTTPBinding, at ir.WalkPath) []Violation { - webhook := b.Inbound == ir.HTTPInboundWebhook +func appendStrayRoute(vs []Violation, binding ir.HTTPBinding, at ir.WalkPath) []Violation { + webhook := binding.Inbound == ir.HTTPInboundWebhook switch { - case !b.Inbound.Valid(): + case !binding.Inbound.Valid(): return append(vs, Violation{ Code: "ir/unknown-http-inbound", - Message: "binding carries undeclared inbound kind " + strconv.Quote(string(b.Inbound)), + Message: "binding carries undeclared inbound kind " + strconv.Quote(string(binding.Inbound)), Path: at.String() + ".Inbound", }) - case webhook && b.URITemplate != "": + case webhook && binding.URITemplate != "": return append(vs, Violation{ Code: "ir/webhook-route", - Message: "webhook binding carries URI template " + strconv.Quote(b.URITemplate) + + Message: "webhook binding carries URI template " + strconv.Quote(binding.URITemplate) + "; a webhook names its event in WebhookName and has no template", Path: at.String() + ".URITemplate", }) - case !webhook && b.WebhookName != "": + case !webhook && binding.WebhookName != "": return append(vs, Violation{ Code: "ir/webhook-route", - Message: "binding that is not a webhook carries webhook name " + strconv.Quote(b.WebhookName) + + Message: "binding that is not a webhook carries webhook name " + strconv.Quote(binding.WebhookName) + "; only a webhook binding names an event", Path: at.String() + ".WebhookName", }) @@ -96,14 +96,14 @@ func checkCallbacks(*ir.Document) walkCheck { marked := map[ir.OperationID]string{} listed := map[ir.OperationID]string{} return walkCheck{ - visit: func(v reflect.Value, path ir.WalkPath) bool { - if operation, ok := reflect.TypeAssert[ir.Operation](v); ok { + visit: func(value reflect.Value, path ir.WalkPath) bool { + if operation, ok := reflect.TypeAssert[ir.Operation](value); ok { noteCallbacks(&operation, path, marked, listed) } return true }, - report: func(declarationsValue declarations) []Violation { - return callbackDisagreements(declarationsValue, marked, listed) + report: func(declarations declarations) []Violation { + return callbackDisagreements(declarations, marked, listed) }, } } @@ -112,11 +112,11 @@ func checkCallbacks(*ir.Document) walkCheck { // and where each operation its bindings list among their Callbacks is first // listed. func noteCallbacks(operation *ir.Operation, path ir.WalkPath, marked, listed map[ir.OperationID]string) { - for i, b := range operation.Bindings.HTTP { - if _, seen := marked[operation.ID]; b.Inbound == ir.HTTPInboundCallback && !seen { + for i, binding := range operation.Bindings.HTTP { + if _, seen := marked[operation.ID]; binding.Inbound == ir.HTTPInboundCallback && !seen { marked[operation.ID] = path.String() + ".Bindings.HTTP" } - for j, cb := range b.Callbacks { + for j, cb := range binding.Callbacks { for k, id := range cb.Operations { if _, seen := listed[id]; !seen { listed[id] = path.String() + ".Bindings.HTTP[" + strconv.Itoa(i) + "].Callbacks[" + @@ -131,8 +131,8 @@ func noteCallbacks(operation *ir.Operation, path ir.WalkPath, marked, listed map // binding lists, then each listed operation the walk declared that is not // marked, each in byte order of its ID. A walk cut short read part of the // bindings, so it claims neither, and the cut is reported. -func callbackDisagreements(declarationsValue declarations, marked, listed map[ir.OperationID]string) []Violation { - if declarationsValue.truncated { +func callbackDisagreements(declarations declarations, marked, listed map[ir.OperationID]string) []Violation { + if declarations.truncated { return nil } var vs []Violation @@ -149,7 +149,7 @@ func callbackDisagreements(declarationsValue declarations, marked, listed map[ir return vs } held := map[ir.OperationID]bool{} - for _, decl := range declarationsValue.list() { + for _, decl := range declarations.list() { if decl.Class == operationIDType { held[ir.OperationID(decl.ID)] = true } diff --git a/ir/irversion_names_test.go b/ir/irversion_names_test.go index 052f05e8a..a5dba145d 100644 --- a/ir/irversion_names_test.go +++ b/ir/irversion_names_test.go @@ -61,7 +61,7 @@ func TestIRVersion_PinsTheNames(t *testing.T) { // // The grammar decides at each rune from that rune and its two neighbours, so // those names reach every decision it makes over the classes the witnesses -// stand for. The ASCII runes pin which runes separate, which one class hides. +// represent. The ASCII runes pin which runes separate, which one class hides. // canonicalCases stays out: a row added there changes no name, so it moves no // hash. func describeNames(witnesses []rune, hints []string) string { @@ -88,8 +88,8 @@ func writeCanonical(b *strings.Builder, name string) { // namesOver returns every string of up to three of witnesses, shortest first. func namesOver(witnesses []rune) []string { - n := len(witnesses) - names := make([]string, 1, 1+n+n*n+n*n*n) + count := len(witnesses) + names := make([]string, 1, 1+count+count*count+count*count*count) last := names for range 3 { next := make([]string, 0, len(last)*len(witnesses)) @@ -110,11 +110,11 @@ const runeClasses = 1 << 8 // classOf returns r's class: everything the grammar can ask of a rune, one bit a // question, whichever of these it asks today, so a change to which it asks is // seen. -func classOf(r rune) uint8 { +func classOf(character rune) uint8 { var class uint8 for i, holds := range [...]bool{ - unicode.IsLetter(r), unicode.IsDigit(r), unicode.IsMark(r), unicode.IsLower(r), - unicode.IsUpper(r), unicode.IsTitle(r), unicode.ToLower(r) != r, ir.IsWordRune(r), + unicode.IsLetter(character), unicode.IsDigit(character), unicode.IsMark(character), unicode.IsLower(character), + unicode.IsUpper(character), unicode.IsTitle(character), unicode.ToLower(character) != character, ir.IsWordRune(character), } { if holds { class |= 1 << i @@ -157,11 +157,11 @@ func TestRuneScan_WitnessesEveryClass(t *testing.T) { // beside the hint, so a line names the position it pins. func hintsOf(doc *ir.Document) []string { var hints []string - ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != namingType { + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != namingType { return true } - if hint := v.FieldByName("Hint").String(); hint != "" { + if hint := value.FieldByName("Hint").String(); hint != "" { hints = append(hints, at.String()+" "+hint) } return false diff --git a/ir/irversion_test.go b/ir/irversion_test.go index 309b63e06..6a2a557dd 100644 --- a/ir/irversion_test.go +++ b/ir/irversion_test.go @@ -189,6 +189,8 @@ var generations = []generation{ names: "5cb6b5124f5093bf15f2026e532b1bd8a469ca64b4dd5649af02999fbfa474fb"}, {version: "0.73.0", format: 1, shape: "d568f0c9e05d7537efea8bc519c912e2133c97607e263d9ff0480540ef07feff", names: "03158da13271f5f4eec495eba7d55adc8443bb7824386df57fb00c9a200902cc"}, + {version: "0.74.0", format: 1, shape: "8b7059b97018283cf44ecb82f52468584c7760b5fb85e10ab5ff08720a4cdb52", + names: "03158da13271f5f4eec495eba7d55adc8443bb7824386df57fb00c9a200902cc"}, } // shapeGolden holds the description the newest row's shape hashes, so a change @@ -316,41 +318,41 @@ func rowFindings(rows []generation, format int) []string { } // isDigest reports whether s is a lower-case hex SHA-256. -func isDigest(s string) bool { - b, err := hex.DecodeString(s) - return err == nil && len(b) == sha256.Size && strings.ToLower(s) == s +func isDigest(text string) bool { + b, err := hex.DecodeString(text) + return err == nil && len(b) == sha256.Size && strings.ToLower(text) == text } // stepFinding returns what is wrong with generationValue following prev, or "" // if nothing. -func stepFinding(prev, generationValue generation) string { - order := compareVersions(prev.version, generationValue.version) +func stepFinding(prev, generation generation) string { + order := compareVersions(prev.version, generation.version) switch { - case prev.names != "" && generationValue.names == "": + case prev.names != "" && generation.names == "": return fmt.Sprintf("%s records no names after %s did: the pin holds from the row that began it", - generationValue.version, prev.version) - case order == 0 && generationValue.names != prev.names: - return fmt.Sprintf("%s is described anew with other names: a change of names is a bump", generationValue.version) + generation.version, prev.version) + case order == 0 && generation.names != prev.names: + return fmt.Sprintf("%s is described anew with other names: a change of names is a bump", generation.version) case order > 0: - return fmt.Sprintf("%s follows %s, but rows ascend by version", generationValue.version, prev.version) - case order == 0 && generationValue.format <= prev.format: + return fmt.Sprintf("%s follows %s, but rows ascend by version", generation.version, prev.version) + case order == 0 && generation.format <= prev.format: return fmt.Sprintf("%s is described again in format %d after format %d: "+ - "a generation is described anew only in a later format", generationValue.version, generationValue.format, prev.format) - case order == 0 && generationValue.meaning != "": + "a generation is described anew only in a later format", generation.version, generation.format, prev.format) + case order == 0 && generation.meaning != "": return fmt.Sprintf("%s in format %d describes a generation anew, which is no bump, "+ - "so it states no meaning", generationValue.version, generationValue.format) + "so it states no meaning", generation.version, generation.format) case order == 0: return "" - case generationValue.format != prev.format: + case generation.format != prev.format: return fmt.Sprintf("%s is described in format %d and %s in format %d: describe %s anew "+ - "in format %d first, so the bump compares with it", generationValue.version, generationValue.format, prev.version, - prev.format, prev.version, generationValue.format) - case generationValue.shape == prev.shape && generationValue.meaning == "": + "in format %d first, so the bump compares with it", generation.version, generation.format, prev.version, + prev.format, prev.version, generation.format) + case generation.shape == prev.shape && generation.meaning == "": return fmt.Sprintf("%s has %s's shape: a bump that changes no shape states the meaning it "+ - "changes (docs/ir/ir-version.md); without one, revert the bump", generationValue.version, prev.version) - case generationValue.shape != prev.shape && generationValue.meaning != "": + "changes (docs/ir/ir-version.md); without one, revert the bump", generation.version, prev.version) + case generation.shape != prev.shape && generation.meaning != "": return fmt.Sprintf("%s changes %s's shape, so it states no meaning: "+ - "its version history entry says what changed", generationValue.version, prev.version) + "its version history entry says what changed", generation.version, prev.version) default: return "" } @@ -466,9 +468,9 @@ func TestRowFindings(t *testing.T) { t.Parallel() a := generation{version: "0.3.0", format: 1, shape: shapeA} b := generation{version: "0.4.0", format: 1, shape: shapeB} - with := func(generationValue generation, edit func(*generation)) generation { - edit(&generationValue) - return generationValue + with := func(generation generation, edit func(*generation)) generation { + edit(&generation) + return generation } for _, tc := range []struct { name string @@ -476,48 +478,48 @@ func TestRowFindings(t *testing.T) { want string // "" means no finding }{ {"a bump that changes the shape", []generation{a, b}, ""}, - {"a bump for a changed meaning", []generation{a, with(b, func(generationValue *generation) { generationValue.shape, generationValue.meaning = shapeA, "x" })}, ""}, - {"a generation described anew", []generation{a, with(a, func(generationValue *generation) { generationValue.format, generationValue.shape = 2, shapeB })}, ""}, + {"a bump for a changed meaning", []generation{a, with(b, func(generation *generation) { generation.shape, generation.meaning = shapeA, "x" })}, ""}, + {"a generation described anew", []generation{a, with(a, func(generation *generation) { generation.format, generation.shape = 2, shapeB })}, ""}, {"an empty table", nil, "generations is empty"}, - {"a version that is no version", []generation{with(a, func(generationValue *generation) { generationValue.version = "0.3" })}, + {"a version that is no version", []generation{with(a, func(generation *generation) { generation.version = "0.3" })}, `row 0: version "0.3" is not MAJOR.MINOR.PATCH`}, - {"no format", []generation{with(a, func(generationValue *generation) { generationValue.format = 0 })}, "row 0: format 0 is no jsonshape.Format up to 2"}, - {"a format jsonshape has not reached", []generation{with(a, func(generationValue *generation) { generationValue.format = 3 })}, + {"no format", []generation{with(a, func(generation *generation) { generation.format = 0 })}, "row 0: format 0 is no jsonshape.Format up to 2"}, + {"a format jsonshape has not reached", []generation{with(a, func(generation *generation) { generation.format = 3 })}, "row 0: format 3 is no jsonshape.Format up to 2"}, - {"a short shape", []generation{with(a, func(generationValue *generation) { generationValue.shape = "aa" })}, + {"a short shape", []generation{with(a, func(generation *generation) { generation.shape = "aa" })}, `row 0: shape "aa" is not a lower-case hex SHA-256`}, - {"a shape that is not hex", []generation{with(a, func(generationValue *generation) { generationValue.shape = strings.Repeat("g", 64) })}, + {"a shape that is not hex", []generation{with(a, func(generation *generation) { generation.shape = strings.Repeat("g", 64) })}, `row 0: shape "` + strings.Repeat("g", 64) + `" is not a lower-case hex SHA-256`}, - {"an upper-case shape", []generation{with(a, func(generationValue *generation) { generationValue.shape = strings.ToUpper(shapeA) })}, + {"an upper-case shape", []generation{with(a, func(generation *generation) { generation.shape = strings.ToUpper(shapeA) })}, `row 0: shape "` + strings.ToUpper(shapeA) + `" is not a lower-case hex SHA-256`}, - {"a first row claiming a predecessor's shape", []generation{with(a, func(generationValue *generation) { generationValue.meaning = "x" })}, + {"a first row claiming a predecessor's shape", []generation{with(a, func(generation *generation) { generation.meaning = "x" })}, "row 0: 0.3.0 has no generation before it to share a shape with"}, {"rows out of order", []generation{b, a}, "row 1: 0.3.0 follows 0.4.0, but rows ascend by version"}, - {"a version listed twice", []generation{a, with(a, func(generationValue *generation) { generationValue.shape = shapeB })}, + {"a version listed twice", []generation{a, with(a, func(generation *generation) { generation.shape = shapeB })}, "row 1: 0.3.0 is described again in format 1 after format 1: a generation is described anew only in a later format"}, - {"a description anew claiming a meaning", []generation{a, with(a, func(generationValue *generation) { generationValue.format, generationValue.meaning = 2, "x" })}, + {"a description anew claiming a meaning", []generation{a, with(a, func(generation *generation) { generation.format, generation.meaning = 2, "x" })}, "row 1: 0.3.0 in format 2 describes a generation anew, which is no bump, so it states no meaning"}, - {"a bump in a new format", []generation{a, with(b, func(generationValue *generation) { generationValue.format = 2 })}, + {"a bump in a new format", []generation{a, with(b, func(generation *generation) { generation.format = 2 })}, "row 1: 0.4.0 is described in format 2 and 0.3.0 in format 1: describe 0.3.0 anew in format 2 first, so the bump compares with it"}, - {"a bump that changes no shape", []generation{a, with(b, func(generationValue *generation) { generationValue.shape = shapeA })}, + {"a bump that changes no shape", []generation{a, with(b, func(generation *generation) { generation.shape = shapeA })}, "row 1: 0.4.0 has 0.3.0's shape: a bump that changes no shape states the meaning it changes (docs/ir/ir-version.md); without one, revert the bump"}, - {"a meaning claimed by a shape change", []generation{a, with(b, func(generationValue *generation) { generationValue.meaning = "x" })}, + {"a meaning claimed by a shape change", []generation{a, with(b, func(generation *generation) { generation.meaning = "x" })}, "row 1: 0.4.0 changes 0.3.0's shape, so it states no meaning: its version history entry says what changed"}, - {"the row that begins the names pin", []generation{a, with(b, func(generationValue *generation) { generationValue.names = shapeA })}, ""}, + {"the row that begins the names pin", []generation{a, with(b, func(generation *generation) { generation.names = shapeA })}, ""}, {"a bump for changed names", []generation{ - with(a, func(generationValue *generation) { generationValue.names = shapeA }), - with(b, func(generationValue *generation) { - generationValue.shape, generationValue.names, generationValue.meaning = shapeA, shapeB, "x" + with(a, func(generation *generation) { generation.names = shapeA }), + with(b, func(generation *generation) { + generation.shape, generation.names, generation.meaning = shapeA, shapeB, "x" }), }, ""}, - {"names that are no digest", []generation{with(a, func(generationValue *generation) { generationValue.names = "aa" })}, + {"names that are no digest", []generation{with(a, func(generation *generation) { generation.names = "aa" })}, `row 0: names "aa" is not a lower-case hex SHA-256`}, - {"a pin that lapses", []generation{with(a, func(generationValue *generation) { generationValue.names = shapeA }), b}, + {"a pin that lapses", []generation{with(a, func(generation *generation) { generation.names = shapeA }), b}, "row 1: 0.4.0 records no names after 0.3.0 did: the pin holds from the row that began it"}, {"a generation described anew with other names", []generation{ - with(a, func(generationValue *generation) { generationValue.names = shapeA }), - with(a, func(generationValue *generation) { - generationValue.format, generationValue.shape, generationValue.names = 2, shapeB, shapeB + with(a, func(generation *generation) { generation.names = shapeA }), + with(a, func(generation *generation) { + generation.format, generation.shape, generation.names = 2, shapeB, shapeB }), }, "row 1: 0.3.0 is described anew with other names: a change of names is a bump"}, } { diff --git a/ir/json.go b/ir/json.go index 4ae6cbcc0..2cc105250 100644 --- a/ir/json.go +++ b/ir/json.go @@ -44,13 +44,13 @@ func (d *Document) MarshalJSONTo(enc *jsontext.Encoder) error { } // canonicalOptions fixes every choice but whitespace that decides a document's -// bytes (invariant 7): map entries sorted by key, the minimal string escaping of RFC 8785, and a -// refusal to write a string that is not UTF-8 or an object that repeats a name, -// where the alternatives are a silent U+FFFD and an ambiguous document. The rest -// pin v2's defaults, so once MarshalJSONTo runs no caller option can stringify a -// number, drop a zero struct, respell or reorder a raw value, substitute a -// marshaler, or write null for a nil list or map held as a map's value, which is -// [] or {}. +// bytes (invariant 7): map entries sorted by key, the minimal string escaping +// of RFC 8785, and a refusal to write a string that is not UTF-8 or an object +// that repeats a name, where the alternatives are an unreported U+FFFD and an +// ambiguous document. The rest pin v2's defaults, so once MarshalJSONTo runs no +// caller option can stringify a number, drop a zero struct, respell or reorder +// a raw value, substitute a marshaler, or write null for a nil list or map held +// as a map's value, which is [] or {}. func canonicalOptions() json.Options { return json.JoinOptions( json.Deterministic(true), @@ -93,15 +93,15 @@ func (d *Document) UnmarshalJSONFrom(dec *jsontext.Decoder) error { // document from another generation is refused as one, not for whichever of its // members this build fails to recognize first. func checkVersionOf(raw jsontext.Value) error { - v, found, err := stringMember(raw, "irVersion") + version, found, err := stringMember(raw, "irVersion") switch { case err != nil: return fmt.Errorf("ir: document: %w", err) case !found: return fmt.Errorf("ir: this build reads irVersion %s: %w", IRVersion, ErrVersionAbsent) - case !CompatibleVersion(v): + case !CompatibleVersion(version): return fmt.Errorf("ir: document declares irVersion %.32q, this build reads %s: %w", - v, IRVersion, ErrVersionIncompatible) + version, IRVersion, ErrVersionIncompatible) } return nil } @@ -124,12 +124,12 @@ func marshalKinded[P, T any](enc *jsontext.Encoder, typeKind TypeKind, body *T) // unmarshalKinded reads a kind-tagged object into body, an alias of the public // kind P, refusing a tag that names any other kind. func unmarshalKinded[P, T any](dec *jsontext.Decoder, typeKind TypeKind, body *T) error { - kindedValue := kinded[T]{Body: body} - if err := json.UnmarshalDecode(dec, &kindedValue); err != nil { + wrapped := kinded[T]{Body: body} + if err := json.UnmarshalDecode(dec, &wrapped); err != nil { return named[P](err, reflect.TypeFor[kinded[T]]()) } - if kindedValue.Kind != typeKind { - return fmt.Errorf("ir: %s carries the kind tag %q", typeKind, kindedValue.Kind) + if wrapped.Kind != typeKind { + return fmt.Errorf("ir: %s carries the kind tag %q", typeKind, wrapped.Kind) } return nil } @@ -296,11 +296,11 @@ func (r *TypeRegistry) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } out := make(TypeRegistry, len(rawByID)) for _, id := range slices.Sorted(maps.Keys(rawByID)) { - td, err := decodeTypeDef(id, rawByID[id], dec.Options()) + typeDef, err := decodeTypeDef(id, rawByID[id], dec.Options()) if err != nil { return err } - out[id] = td + out[id] = typeDef } *r = out return nil @@ -316,14 +316,14 @@ func decodeTypeDef(id TypeID, raw jsontext.Value, opts json.Options) (TypeDef, e if !found { return nil, fmt.Errorf("ir: type %s: reading kind tag: no \"kind\" member", id) } - td, ok := NewTypeDef(TypeKind(k)) + typeDef, ok := NewTypeDef(TypeKind(k)) if !ok { return nil, fmt.Errorf("ir: type %s: unknown kind %q", id, k) } - if err := json.Unmarshal(raw, td, opts); err != nil { + if err := json.Unmarshal(raw, typeDef, opts); err != nil { return nil, fmt.Errorf("ir: type %s (%s): %w", id, k, err) } - return td, nil + return typeDef, nil } // stringMember reads the string member name of the JSON object raw without @@ -350,14 +350,14 @@ func stringMember(raw jsontext.Value, name string) (string, bool, error) { } continue } - v, err := dec.ReadToken() + token, err := dec.ReadToken() if err != nil { return "", false, err } - if v.Kind() != '"' { - return "", false, fmt.Errorf("%q is a JSON %s, not a string", name, v.Kind()) + if token.Kind() != '"' { + return "", false, fmt.Errorf("%q is a JSON %s, not a string", name, token.Kind()) } - return v.String(), true, nil + return token.String(), true, nil } // The scan stops at the object's close or at whatever PeekKind could not // read; reading that token reports an object that never ended instead of diff --git a/ir/json_internal_test.go b/ir/json_internal_test.go index ba38200e9..1509556dd 100644 --- a/ir/json_internal_test.go +++ b/ir/json_internal_test.go @@ -151,52 +151,52 @@ func TestDecodeTypeDef(t *testing.T) { t.Run("decodes a known kind", func(t *testing.T) { t.Parallel() - td, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":"primitive","primitiveKind":"string"}`), nil) + typeDef, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":"primitive","primitiveKind":"string"}`), nil) require.NoError(t, err) - require.NotNil(t, td) - assert.Equal(t, KindPrimitive, td.Kind()) - primitive, ok := td.(*Primitive) + require.NotNil(t, typeDef) + assert.Equal(t, KindPrimitive, typeDef.Kind()) + primitive, ok := typeDef.(*Primitive) require.True(t, ok) assert.Equal(t, PrimitiveString, primitive.PrimitiveKind) }) t.Run("refuses an entry with no kind member", func(t *testing.T) { t.Parallel() - td, err := decodeTypeDef("type/x", jsontext.Value(`{}`), nil) + typeDef, err := decodeTypeDef("type/x", jsontext.Value(`{}`), nil) require.Error(t, err) - assert.Nil(t, td) + assert.Nil(t, typeDef) assert.ErrorContains(t, err, `no "kind" member`) }) t.Run("refuses a non-string kind", func(t *testing.T) { t.Parallel() - td, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":123}`), nil) + typeDef, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":123}`), nil) require.Error(t, err) - assert.Nil(t, td) + assert.Nil(t, typeDef) assert.ErrorContains(t, err, `is a JSON number, not a string`) }) t.Run("refuses a non-object entry", func(t *testing.T) { t.Parallel() - td, err := decodeTypeDef("type/x", jsontext.Value(`123`), nil) + typeDef, err := decodeTypeDef("type/x", jsontext.Value(`123`), nil) require.Error(t, err) - assert.Nil(t, td) + assert.Nil(t, typeDef) assert.ErrorContains(t, err, "reading kind tag:") }) t.Run("refuses an unknown kind", func(t *testing.T) { t.Parallel() - td, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":"nope"}`), nil) + typeDef, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":"nope"}`), nil) require.Error(t, err) - assert.Nil(t, td) + assert.Nil(t, typeDef) assert.ErrorContains(t, err, `unknown kind "nope"`) }) t.Run("prefixes a body mismatch with the id and kind", func(t *testing.T) { t.Parallel() - td, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":"primitive","primitiveKind":123}`), nil) + typeDef, err := decodeTypeDef("type/x", jsontext.Value(`{"kind":"primitive","primitiveKind":123}`), nil) require.Error(t, err) - assert.Nil(t, td) + assert.Nil(t, typeDef) assert.ErrorContains(t, err, "type/x (primitive):") }) diff --git a/ir/json_test.go b/ir/json_test.go index 6f9705ca7..96dbbde8a 100644 --- a/ir/json_test.go +++ b/ir/json_test.go @@ -32,10 +32,10 @@ func versioned(body string) string { // sampleDocument builds one document that touches every TypeDef kind. func sampleDocument(t *testing.T) ir.Document { t.Helper() - mk := func(id string, td ir.TypeDef) (ir.TypeID, ir.TypeDef) { + mk := func(id string, typeDef ir.TypeDef) (ir.TypeID, ir.TypeDef) { typeID := ir.TypeID(id) - td.Common().ID = typeID - return typeID, td + typeDef.Common().ID = typeID + return typeID, typeDef } types := ir.TypeRegistry{} for _, entry := range []ir.TypeDef{ @@ -51,8 +51,8 @@ func sampleDocument(t *testing.T) ir.Document { &ir.External{Identity: "erlang:pid"}, &ir.Any{}, } { - id, td := mk("type/k/"+string(entry.Kind()), entry) - types[id] = td + id, typeDef := mk("type/k/"+string(entry.Kind()), entry) + types[id] = typeDef } return ir.Document{ IRVersion: ir.IRVersion, diff --git a/ir/mapform.go b/ir/mapform.go index a446d445e..a12025287 100644 --- a/ir/mapform.go +++ b/ir/mapform.go @@ -29,8 +29,8 @@ func AsMap(model *Model) (*MapT, bool) { // member, composition, closure, discriminator or other model-only fact beside // it. Each field of Model is either carried by AsMap or required empty here. func mapOnly(model *Model) bool { - ap := model.AdditionalProperties - if ap == nil || ap.Value == nil || len(ap.Patterns) > 0 { + additionalProperties := model.AdditionalProperties + if additionalProperties == nil || additionalProperties.Value == nil || len(additionalProperties.Patterns) > 0 { return false } return len(model.Properties) == 0 && len(model.Requires) == 0 && diff --git a/ir/mapform_test.go b/ir/mapform_test.go index 90e52c60b..07ccbfb3e 100644 --- a/ir/mapform_test.go +++ b/ir/mapform_test.go @@ -58,10 +58,10 @@ func TestAsMap_RefusesWhatIsNoMap(t *testing.T) { patterned.AdditionalProperties.Patterns = []ir.PatternProperties{{Pattern: "^x-", Value: ir.TypeRef{Target: "type/primitive/string"}}} noCatchAll := mapModel() noCatchAll.AdditionalProperties = nil - noValue := mapModel() - noValue.AdditionalProperties.Value = nil + no := mapModel() + no.AdditionalProperties.Value = nil for name, model := range map[string]*ir.Model{ - "nil": nil, "no catch-all": noCatchAll, "patterned": patterned, "no value": noValue, + "nil": nil, "no catch-all": noCatchAll, "patterned": patterned, "no value": no, } { t.Run(name, func(t *testing.T) { t.Parallel() @@ -109,22 +109,22 @@ func TestAsMap_EveryUncarriedFieldIsMoreThanAMap(t *testing.T) { // setNonZero gives v a value other than its zero value, failing on a kind it // has no value for so a new field cannot pass the sweep unset. -func setNonZero(t *testing.T, v reflect.Value) { +func setNonZero(t *testing.T, value reflect.Value) { t.Helper() - switch v.Kind() { + switch value.Kind() { case reflect.Bool: - v.SetBool(true) + value.SetBool(true) case reflect.String: - v.SetString("set") + value.SetString("set") case reflect.Pointer: - v.Set(reflect.New(v.Type().Elem())) + value.Set(reflect.New(value.Type().Elem())) case reflect.Slice: - v.Set(reflect.MakeSlice(v.Type(), 1, 1)) + value.Set(reflect.MakeSlice(value.Type(), 1, 1)) case reflect.Map: - v.Set(reflect.MakeMapWithSize(v.Type(), 1)) - v.SetMapIndex(reflect.Zero(v.Type().Key()), reflect.Zero(v.Type().Elem())) + value.Set(reflect.MakeMapWithSize(value.Type(), 1)) + value.SetMapIndex(reflect.Zero(value.Type().Key()), reflect.Zero(value.Type().Elem())) default: - require.Failf(t, "no non-zero value", "field of kind %s; extend setNonZero", v.Kind()) + require.Failf(t, "no non-zero value", "field of kind %s; extend setNonZero", value.Kind()) } - require.False(t, v.IsZero(), "the field was set") + require.False(t, value.IsZero(), "the field was set") } diff --git a/ir/multiple.go b/ir/multiple.go new file mode 100644 index 000000000..93e4bff3b --- /dev/null +++ b/ir/multiple.go @@ -0,0 +1,185 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "math/big" + "strconv" +) + +// maxMultipleDigits bounds the digits the multipleOf arithmetic reads: the +// significant digits of a value and a step between them in +// [MultipleOfAdmits], and the numerator in lowest terms of each step and of +// their common multiple in a step intersection. Its cost grows with their +// square. +const maxMultipleDigits = 1024 + +// stepFactorsPerDigit bounds the powers of two and of five in a step's +// coefficient: a number of n decimal digits has fewer than 4n of either. +const stepFactorsPerDigit = 4 + +// maxStrippedExponent bounds the power of two or of five a step's coefficient +// carries beyond its numerator in lowest terms, as 2^-1500, written +// 5^1500e-1500, carries 5^1500. A common multiple carries no more of either +// than one of its steps, so this bound, like the numerator's, keeps a step +// intersection associative. +const maxStrippedExponent = stepFactorsPerDigit * maxMultipleDigits + +// maxStepCoefficientDigits bounds the coefficient a step intersection reads +// before any big-integer arithmetic. A numerator within maxMultipleDigits +// times a power of two or five within maxStrippedExponent has fewer digits, so +// a longer coefficient passes one of those bounds and is refused unread. +const maxStepCoefficientDigits = stepFactorsPerDigit * maxMultipleDigits + +// MultipleOfAdmits judges value against a multipleOf of step, exactly. It +// answers unknown for a step that is not positive, which divides nothing, and +// for literals of more than 1,024 significant digits between them. +func MultipleOfAdmits(step, value Decimal) Admission { + if step.Sign() <= 0 || len(value.Digits())+len(step.Digits()) > maxMultipleDigits { + return AdmitsUnknown + } + if isMultipleOf(value, step) { + return AdmitsYes + } + return AdmitsNo +} + +// isMultipleOf reports whether decimal is an integral multiple of the positive +// step. Read decimal as vc·10^vl and step as mc·10^ml: the coefficients are the +// digits, and vl and ml the exponents of their last digits. +// +// If vl < ml, decimal is never a multiple, since mc·10^(ml−vl) divides vc only +// if 10 divides vc, and it does not. Otherwise decimal is a multiple iff mc +// divides vc·10^k, with k = min(vl−ml, 4·len(step.Digits())): mc's powers of 2 +// and 5 are each below 4 per digit, and the cofactor coprime to 10 is +// unaffected by the shift. +func isMultipleOf(decimal, step Decimal) bool { + if decimal.Sign() == 0 { + return true + } + shift := lowestExponent(decimal) - lowestExponent(step) + if shift < 0 { + return false + } + k := min(shift, int64(stepFactorsPerDigit*len(step.Digits()))) + return new(big.Int).Rem(scaled(decimal, k), coefficient(step)).Sign() == 0 +} + +// stepIntersection returns the step whose multiples are exactly the multiples +// of both x and y: whichever is a multiple of the other, as written, or else +// their least common multiple. It returns false for a literal no Decimal +// holds, a step that is not positive, and a step or common multiple stepBound +// refuses, the bound every step an intersection takes in is held to, so the +// intersection is associative. +func stepIntersection(x, y BigVal) (BigVal, bool) { + if x == y { + return x, true + } + a, errA := x.Decimal() + b, errB := y.Decimal() + switch { + case errA != nil || errB != nil: + return "", false + case a == b: + return x, true + case a.Sign() <= 0 || b.Sign() <= 0 || stepExceedsBound(a) || stepExceedsBound(b): + return "", false + case isMultipleOf(a, b): + return x, true + case isMultipleOf(b, a): + return y, true + } + lcm, err := NewBigVal(leastCommonMultiple(a, b)) + leastCommonMultipleDecimal, errLeastCommonMultipleDecimal := lcm.Decimal() + if err != nil || errLeastCommonMultipleDecimal != nil || stepExceedsBound(leastCommonMultipleDecimal) { + return "", false + } + return lcm, true +} + +// stepExceedsBound reports whether a step intersection refuses the positive +// decimal unread (stepBound). +func stepExceedsBound(decimal Decimal) bool { + passes, _ := stepBound(decimal) + return passes +} + +// stepBound reports whether the positive decimal's numerator in lowest terms +// has more than maxMultipleDigits digits, or its coefficient carries a power of +// two or five past maxStrippedExponent beyond it, and the work it took: each +// coefficient digit made an integer and each division by five. A coefficient +// within the numerator's bound needs no division, and one past +// maxStepCoefficientDigits passes unread, so the work is bounded whatever the +// exponent. +func stepBound(decimal Decimal) (exceeds bool, work int) { + low, digits := lowestExponent(decimal), len(decimal.Digits()) + switch { + case low >= 0: + return decimal.Exponent() >= maxMultipleDigits, 0 + case digits <= maxMultipleDigits: + return false, 0 + case digits > maxStepCoefficientDigits: + return true, 0 + } + numerator, work := coefficient(decimal), digits + twos := min(int64(numerator.TrailingZeroBits()), -low) + if twos > maxStrippedExponent { + return true, work + } + numerator.Rsh(numerator, uint(twos)) + five, quotient, remainder := big.NewInt(5), new(big.Int), new(big.Int) + fives := int64(0) + for ; fives < min(-low, maxStrippedExponent+1); fives++ { + quotient.QuoRem(numerator, five, remainder) + work++ + if remainder.Sign() != 0 { + break + } + numerator.Set(quotient) + } + if fives > maxStrippedExponent { + return true, work + } + return len(numerator.String()) > maxMultipleDigits, work +} + +// leastCommonMultiple spells the least common multiple of two positive numbers. +// Read each as a coefficient and the exponent of its last digit, and count both +// in units of the lower exponent: a's coefficient grows by 10^shift. Past the +// powers of 2 and 5 in b's coefficient, fewer than 4 per digit, a further power +// of ten only scales the result, so k of them are multiplied out and the other +// shift-k stay in the exponent, which keeps a wide shift from being built. +func leastCommonMultiple(a, b Decimal) string { + if lowestExponent(a) < lowestExponent(b) { + a, b = b, a + } + shift := lowestExponent(a) - lowestExponent(b) + k := min(shift, int64(stepFactorsPerDigit*len(b.Digits()))) + x, y := scaled(a, k), coefficient(b) + gcd := new(big.Int).GCD(nil, nil, x, y) + lcm := x.Mul(x.Quo(x, gcd), y).String() + if exp := lowestExponent(a) - k; exp != 0 { + lcm += "e" + strconv.FormatInt(exp, 10) + } + return lcm +} + +// scaled returns decimal's coefficient times 10^k. +func scaled(decimal Decimal, k int64) *big.Int { + scaled := coefficient(decimal) + return scaled.Mul(scaled, new(big.Int).Exp(big.NewInt(10), big.NewInt(k), nil)) +} + +// coefficient returns decimal's significant digits as an integer. +func coefficient(decimal Decimal) *big.Int { + parsed, _ := new(big.Int).SetString(decimal.Digits(), 10) // Digits is a digit run, by Decimal's invariant + return parsed +} + +// lowestExponent returns the power of ten decimal's last significant digit +// carries. decimal is not zero, and the result stays inside int64 because +// Decimal bounds the leading digit's exponent by MaxDecimalExp. +func lowestExponent(decimal Decimal) int64 { + return decimal.Exponent() - int64(len(decimal.Digits())) + 1 +} diff --git a/ir/multipleof_test.go b/ir/multipleof_test.go new file mode 100644 index 000000000..74c649398 --- /dev/null +++ b/ir/multipleof_test.go @@ -0,0 +1,89 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// decimalOf is text as a Decimal the test owns. +func decimalOf(t *testing.T, text string) ir.Decimal { + t.Helper() + decimal, err := ir.ParseDecimal(text) + require.NoError(t, err, "%q is a decimal in range", text) + return decimal +} + +// TestMultipleOfAdmits_JudgesExactly pins the multipleOf judgment a value is held +// to. Each row is one a float division gets wrong, or one where no answer is +// claimed: a decimal step float64 cannot hold, values far apart in scale, +// magnitudes no rational builds, steps whose powers of two and five outrun the +// shift, and a step that is not positive, which divides nothing. +func TestMultipleOfAdmits_JudgesExactly(t *testing.T) { + t.Parallel() + tests := []struct { + name string + value, step string + want ir.Admission + }{ + {"an integer multiple", "10", "5", ir.AdmitsYes}, + {"an integer that is not one", "7", "2", ir.AdmitsNo}, + {"a decimal step float64 cannot hold", "0.3", "0.1", ir.AdmitsYes}, + {"a last digit finer than the step's", "0.35", "0.1", ir.AdmitsNo}, + {"a fraction against an integral step", "2.5", "2", ir.AdmitsNo}, + {"a fraction against a fractional step", "2.5", "0.5", ir.AdmitsYes}, + {"zero, a multiple of anything", "0", "3", ir.AdmitsYes}, + {"a negative multiple", "-6", "3", ir.AdmitsYes}, + {"a step larger than the value", "2", "5", ir.AdmitsNo}, + {"magnitudes far apart", "1e100", "5", ir.AdmitsYes}, + {"a step far below the value", "1", "1e-100", ir.AdmitsYes}, + {"magnitudes past what a rational builds", "1e5000", "2", ir.AdmitsYes}, + {"a value far above a step it is not a multiple of", "1e1000001", "3", ir.AdmitsNo}, + {"a value at the top of the range", "1e999999999999999999", "2", ir.AdmitsYes}, + {"a value and step at the bottom of the range", "3e-999999999999999999", "1e-999999999999999999", ir.AdmitsYes}, + {"a value below its step's lowest digit", "1e-999999999999999999", "1", ir.AdmitsNo}, + {"a power of two the shift covers", "1e3", "8", ir.AdmitsYes}, + {"a power of two the shift falls short of", "1e2", "8", ir.AdmitsNo}, + {"a coefficient's own powers of two and five", "5e10", "1024", ir.AdmitsYes}, + {"one power of two short", "5e9", "1024", ir.AdmitsNo}, + {"a shift past the cap", "1e100", "1125899906842624", ir.AdmitsYes}, + {"a shift under the cap, one power short", "1e49", "1125899906842624", ir.AdmitsNo}, + {"a zero step, which divides nothing", "4", "0", ir.AdmitsUnknown}, + {"a negative step, which is not positive", "6", "-3", ir.AdmitsUnknown}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, ir.MultipleOfAdmits(decimalOf(t, tc.step), decimalOf(t, tc.value))) + }) + } +} + +// TestMultipleOfAdmits_ReadsAtMost1024DigitsBetweenItsLiterals pins the judgment's +// bound: literals of 1,024 significant digits between them are judged, and +// one more answers unknown, a default of 1,024 sevens under a step of 7 among +// them, a multiple the judgment does not read. Each row past the bound has +// another answer without it. +func TestMultipleOfAdmits_ReadsAtMost1024DigitsBetweenItsLiterals(t *testing.T) { + t.Parallel() + for name, tc := range map[string]struct { + value, step string + want ir.Admission + }{ + "1,023 sevens and a step of 7": {strings.Repeat("7", 1023), "7", ir.AdmitsYes}, + "1,024 sevens and a step of 7": {strings.Repeat("7", 1024), "7", ir.AdmitsUnknown}, + "1,016 digits and 8 between them": {strings.Repeat("6", 1016), strings.Repeat("3", 8), ir.AdmitsYes}, + "1,017 digits and 8 between them": {strings.Repeat("6", 1017), strings.Repeat("3", 8), ir.AdmitsUnknown}, + "1,016 digits and 8, not a multiple": {strings.Repeat("6", 1015) + "7", strings.Repeat("3", 8), ir.AdmitsNo}, + "a long step and a short value": {"6", strings.Repeat("3", 1024), ir.AdmitsUnknown}, + } { + assert.Equal(t, tc.want, ir.MultipleOfAdmits(decimalOf(t, tc.step), decimalOf(t, tc.value)), name) + } +} diff --git a/ir/naming.go b/ir/naming.go index f70a23a4b..a45084e7e 100644 --- a/ir/naming.go +++ b/ir/naming.go @@ -99,8 +99,8 @@ func CanonicalWords(name string) string { // Rendered on the stack, so the string is the one allocation. var buf [stackRendering]byte words := buf[:0] - for r := range canonicalRunes(name) { - words = utf8.AppendRune(words, r) + for character := range canonicalRunes(name) { + words = utf8.AppendRune(words, character) } if string(words) == name { return name @@ -123,15 +123,15 @@ func canonicalWordsExactly(name string) string { return name } size := 0 - for r := range canonicalRunes(name) { - size += utf8.RuneLen(r) + for character := range canonicalRunes(name) { + size += utf8.RuneLen(character) } - var b strings.Builder - b.Grow(size) - for r := range canonicalRunes(name) { - b.WriteRune(r) + var builder strings.Builder + builder.Grow(size) + for character := range canonicalRunes(name) { + builder.WriteRune(character) } - return b.String() + return builder.String() } // HasCanonicalWords reports whether words is CanonicalWords(name). It compares @@ -139,11 +139,11 @@ func canonicalWordsExactly(name string) string { // irverify asks it of every Naming that carries a source. func HasCanonicalWords(name, words string) bool { rest := words - for r := range canonicalRunes(name) { + for character := range canonicalRunes(name) { // An empty or undecodable rest reads as RuneError, which no canonical // rune is: it is no letter, digit or mark, nor any one's lowercase. got, size := utf8.DecodeRuneInString(rest) - if got != r { + if got != character { return false } rest = rest[size:] @@ -164,8 +164,8 @@ func canonicalRunes(name string) iter.Seq[rune] { return } first = false - for _, r := range word { - if !yield(unicode.ToLower(r)) { + for _, character := range word { + if !yield(unicode.ToLower(character)) { return } } @@ -188,22 +188,22 @@ func SourceWords(name string) iter.Seq[string] { for i := 0; i < len(name); { // A byte that does not decode reads as RuneError, which is no word // rune, so it separates. - r, size := utf8.DecodeRuneInString(name[i:]) + character, size := utf8.DecodeRuneInString(name[i:]) switch { - case !IsWordRune(r): + case !IsWordRune(character): if inWord && !yield(name[start:i]) { return } inWord = false case !inWord: start, inWord = i, true - case wordBoundary(prev, r, name[i+size:]): + case wordBoundary(prev, character, name[i+size:]): if !yield(name[start:i]) { return } start = i } - prev = r + prev = character i += size } if inWord { @@ -212,24 +212,25 @@ func SourceWords(name string) iter.Seq[string] { } } -// IsWordRune reports whether r belongs to a word rather than separating two. -// Letters and digits are word characters, and a combining mark belongs to the -// letter it follows: a decomposed "é" is one letter written as two runes. One -// that is default-ignorable (IsDefaultIgnorable), such as a variation selector -// or the Hangul filler U+3164, renders as nothing, so it separates too. +// IsWordRune reports whether character belongs to a word rather than separating +// two. Letters and digits are word characters, and a combining mark belongs to +// the letter it follows: a decomposed "é" is one letter written as two runes. +// One that is default-ignorable (IsDefaultIgnorable), such as a variation +// selector or the Hangul filler U+3164, renders as nothing, so it separates +// too. // // So the result is a word sequence whatever the source spelled the boundary // as: a dot, a slash, brackets, _, - or a space. No ASCII rune is // default-ignorable, which spares the common case the tables. -func IsWordRune(r rune) bool { - return (unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsMark(r)) && - (r < utf8.RuneSelf || !IsDefaultIgnorable(r)) +func IsWordRune(character rune) bool { + return (unicode.IsLetter(character) || unicode.IsDigit(character) || unicode.IsMark(character)) && + (character < utf8.RuneSelf || !IsDefaultIgnorable(character)) } -// IsDefaultIgnorable reports whether r is a Default_Ignorable_Code_Point: a -// character that renders as nothing where a renderer does not support it. The -// word grammar separates on one (IsWordRune), and irverify's blank rules take -// one as invisible. +// IsDefaultIgnorable reports whether character is a +// Default_Ignorable_Code_Point: a character that renders as nothing where a +// renderer does not support it. The word grammar separates on one (IsWordRune), +// and irverify's blank rules take one as invisible. // // Package unicode has no table for the property, so it is built from its // terms as DerivedCoreProperties.txt defines it: Other_Default_Ignorable_Code_Point, @@ -237,7 +238,7 @@ func IsWordRune(r rune) bool { // ranges unicode lacks a table for, the interlinear annotation characters and // the Egyptian hieroglyph format controls, which are Cf and render. White_Space // is subtracted too, and no rune of it is in any term (GitHub #832). -func IsDefaultIgnorable(r rune) bool { +func IsDefaultIgnorable(character rune) bool { // The Cf ranges Unicode 17.0.0 takes out of Default_Ignorable_Code_Point that // package unicode has no table for: U+FFF9..U+FFFB and U+13430..U+1343F. // DerivedCoreProperties.txt's header writes the second as 13430..13440, but @@ -251,32 +252,33 @@ func IsDefaultIgnorable(r rune) bool { egyptianFormatFirst, egyptianFormatLast = '\U00013430', '\U0001343F' ) - interlinear := r >= interlinearFirst && r <= interlinearLast - egyptianFormat := r >= egyptianFormatFirst && r <= egyptianFormatLast - if interlinear || egyptianFormat || unicode.Is(unicode.Prepended_Concatenation_Mark, r) { + interlinear := character >= interlinearFirst && character <= interlinearLast + egyptianFormat := character >= egyptianFormatFirst && character <= egyptianFormatLast + if interlinear || egyptianFormat || unicode.Is(unicode.Prepended_Concatenation_Mark, character) { return false } - return unicode.Is(unicode.Cf, r) || unicode.Is(unicode.Other_Default_Ignorable_Code_Point, r) || - unicode.Is(unicode.Variation_Selector, r) + return unicode.Is(unicode.Cf, character) || unicode.Is(unicode.Other_Default_Ignorable_Code_Point, character) || + unicode.Is(unicode.Variation_Selector, character) } -// wordBoundary reports whether a new word starts at word rune r, which follows -// word rune prev and comes before rest, the remainder of the name. -func wordBoundary(prev, r rune, rest string) bool { +// wordBoundary reports whether a new word starts at word rune character, which +// follows word rune prev and comes before rest, the remainder of the name. +func wordBoundary(prev, character rune, rest string) bool { switch { - case carriesCase(r) && (unicode.IsLower(prev) || unicode.IsDigit(prev)): + case carriesCase(character) && (unicode.IsLower(prev) || unicode.IsDigit(prev)): return true // lower/digit -> Upper: "userID" -> user|ID - case acronymTail(prev, r, rest): + case acronymTail(prev, character, rest): return true // acronym tail: "HTTPServer" -> HTTP|Server - case unicode.IsLetter(prev) && unicode.IsDigit(r), unicode.IsDigit(prev) && unicode.IsLetter(r): + case unicode.IsLetter(prev) && unicode.IsDigit(character), unicode.IsDigit(prev) && unicode.IsLetter(character): return true // letter<->digit: "APIKey2" -> ...Key|2 default: return false } } -// acronymTail reports whether r ends a run of capitals and opens the next word, -// the S of "HTTPServer": two capitals followed by a lowercase letter. +// acronymTail reports whether character ends a run of capitals and opens the +// next word, the S of "HTTPServer": two capitals followed by a lowercase +// letter. // // At least one capital must be one lowercasing changes, or the rule splits its // own output: a boundary between runes lowercasing leaves alone survives into @@ -285,32 +287,32 @@ func wordBoundary(prev, r rune, rest string) bool { // until lowercasing supplies one — so the source runes cannot settle it. // Requiring case of both would lose ℤ_server and http_ℤerver; canonicalCases // pins both. -func acronymTail(prev, r rune, rest string) bool { - if !isCapital(prev) || !isCapital(r) { +func acronymTail(prev, character rune, rest string) bool { + if !isCapital(prev) || !isCapital(character) { return false } - if !carriesCase(prev) && !carriesCase(r) { + if !carriesCase(prev) && !carriesCase(character) { return false // neither is lowercased, so the split would reappear } next, _ := utf8.DecodeRuneInString(rest) // RuneError, no lowercase letter, at the end return unicode.IsLower(next) } -// carriesCase reports whether lowercasing changes r, as irverify.isCased asks -// of a whole canonical; the two must agree (GitHub #187). A rune the grammar -// splits on but lowercasing leaves alone survives into the output still looking -// like a boundary, and re-canonicalizing would split it again. Double-struck ℤ -// and ϒ are IsUpper with no lowercase form; titlecase letters are not IsUpper -// but do change. +// carriesCase reports whether lowercasing changes character, as +// irverify.isCased asks of a whole canonical; the two must agree (GitHub #187). +// A rune the grammar splits on but lowercasing leaves alone survives into the +// output still looking like a boundary, and re-canonicalizing would split it +// again. Double-struck ℤ and ϒ are IsUpper with no lowercase form; titlecase +// letters are not IsUpper but do change. // // That makes the grammar a fixed point: one pass lowercases every rune that // carries case, leaving the two case rules nothing to fire on, and the // letter/digit rule is case-independent. -func carriesCase(r rune) bool { return unicode.ToLower(r) != r } +func carriesCase(character rune) bool { return unicode.ToLower(character) != character } -// isCapital reports whether r is a capital letter form — uppercase or +// isCapital reports whether character is a capital letter form — uppercase or // titlecase. It asks about the letter's form, not a transition: ℤ belongs to a // run of capitals whether or not lowercasing changes it, and so does a // titlecase letter, though IsUpper reports false. acronymTail pairs it with // carriesCase. -func isCapital(r rune) bool { return unicode.IsUpper(r) || unicode.IsTitle(r) } +func isCapital(character rune) bool { return unicode.IsUpper(character) || unicode.IsTitle(character) } diff --git a/ir/naming_property_test.go b/ir/naming_property_test.go index 8394c263b..811c9f57e 100644 --- a/ir/naming_property_test.go +++ b/ir/naming_property_test.go @@ -189,9 +189,9 @@ func assertWordRunesPreserved(t *testing.T, name, got string) { // wordRunesOf returns the lowercased word characters of s, in order, with // everything the grammar treats as a separator removed. -func wordRunesOf(s string) string { +func wordRunesOf(text string) string { var b strings.Builder - for _, r := range strings.ToLower(s) { + for _, r := range strings.ToLower(text) { if isWordRune(r) { b.WriteRune(r) } @@ -203,7 +203,7 @@ func wordRunesOf(s string) string { // restated from Unicode's tables rather than from the implementation: a letter, // digit or mark that is not default-ignorable. Of the terms that property is // built from, only these two hold a letter, a digit or a mark, Cf holding none. -func isWordRune(r rune) bool { - return (unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsMark(r)) && - !unicode.Is(unicode.Other_Default_Ignorable_Code_Point, r) && !unicode.Is(unicode.Variation_Selector, r) +func isWordRune(character rune) bool { + return (unicode.IsLetter(character) || unicode.IsDigit(character) || unicode.IsMark(character)) && + !unicode.Is(unicode.Other_Default_Ignorable_Code_Point, character) && !unicode.Is(unicode.Variation_Selector, character) } diff --git a/ir/narrowing.go b/ir/narrowing.go index 86f47d89b..62d760c0a 100644 --- a/ir/narrowing.go +++ b/ir/narrowing.go @@ -165,10 +165,10 @@ type walked struct { // read in its union's place, and reads off it the unions the composition // narrows and whether no distribution ends it. func narrowedWalk(types TypeRegistry, root TypeID, over []substitution) walked { - flattenerValue := flattener{types: types, narrow: &narrowState{over: over}} - flat := flattenerValue.flatten(root) - narrowed := flattenerValue.narrowed() - return walked{flat: flat, narrowed: narrowed, unending: flattenerValue.narrow.unending, steps: flattenerValue.steps} + flattener := flattener{types: types, narrow: &narrowState{over: over}} + flat := flattener.flatten(root) + narrowed := flattener.narrowed() + return walked{flat: flat, narrowed: narrowed, unending: flattener.narrow.unending, steps: flattener.steps} } // narrowState is what a [NarrowedShapes] walk reads beside the flattening. @@ -181,14 +181,14 @@ type narrowState struct { over []substitution at map[TypeID]int // ends holds, at each union's place in over, what the chain of variants - // read from that union ends at, so the walk reads a chain once however - // many entries stand for its unions. + // read from that union ends at, so the walk reads a chain once however many + // entries name its unions. ends []variantEnd // unions are the unions the walk met that over reads no variant of, read // through alias scalars, once each in the order it met them. unions []metUnion seen map[TypeID]bool - // placed are the models a variant read in a union's place stands for. + // placed are the models a variant read in a union's place names. placed map[TypeID]bool // unending reports that no distribution ends the composition: a chain of // variants read in unions' places reached a union twice, or a placed model @@ -197,8 +197,8 @@ type narrowState struct { } // variantEnd is what a chain of variants read in unions' places ends at: the -// last variant as its union writes it and the type that one stands for -// through alias scalars, both "" until the walk reads the chain. +// last variant as its union writes it and the type that one names through alias +// scalars, both "" until the walk reads the chain. type variantEnd struct { target, id TypeID read bool @@ -210,13 +210,13 @@ type metUnion struct { union *Union } -// substitute returns what stands where an entry writes target, which stands -// for id: the two themselves unless id is a union the walk reads a variant of, -// else that variant as its union writes it and the type it stands for through -// alias scalars, and so on along a chain of them. Each meeting reads the -// variant, a step, and the walk reads a chain once, as it does an alias chain, -// each variant along it a step. One longer than over has reached a union -// twice, so the walk substitutes nothing more. A model it ends at is placed. +// substitute returns what is where an entry writes target, which names id: the +// two themselves unless id is a union the walk reads a variant of, else that +// variant as its union writes it and the type it names through alias scalars, +// and so on along a chain of them. Each meeting reads the variant, a step, and +// the walk reads a chain once, as it does an alias chain, each variant along it +// a step. One longer than over has reached a union twice, so the walk +// substitutes nothing more. A model it ends at is placed. func (f *flattener) substitute(target, id TypeID) (TypeID, TypeID) { narrowState := f.narrow if len(narrowState.over) == 0 || narrowState.unending { @@ -260,9 +260,8 @@ func (f *flattener) substitute(target, id TypeID) (TypeID, TypeID) { return target, id } -// meet records id, a type an entry stands for that names no model, as a union -// the walk met that it reads no variant of, unless it is no union or met -// already. +// meet records id, a type an entry names that names no model, as a union the +// walk met that it reads no variant of, unless it is no union or met already. func (n *narrowState) meet(types TypeRegistry, id TypeID) { union, ok := types[id].(*Union) if !ok || union == nil || n.seen[id] { @@ -301,8 +300,8 @@ func (f *flattener) narrowed() []metUnion { return out } -// lists reports whether the union union has a variant standing for the walk's -// root, read through alias scalars, each variant it reads a step. +// lists reports whether the union union has a variant naming the walk's root, +// read through alias scalars, each variant it reads a step. func (f *flattener) lists(union *Union) bool { for _, variant := range union.Variants { f.steps++ diff --git a/ir/narrowing_reference_test.go b/ir/narrowing_reference_test.go index 86c9e4656..5c33458d6 100644 --- a/ir/narrowing_reference_test.go +++ b/ir/narrowing_reference_test.go @@ -18,12 +18,12 @@ import ( "github.com/dexpace/morphic/ir/irtest" ) -// TestNarrowedShapes_MatchesACopyOfTheRegistry holds every narrowing of -// random registries holding unions to narrowingReference, which builds each -// shape as a copy of the registry with every composition entry standing for -// a union rewritten to the variant read there, and flattens the copy: the -// union, each shape's Over and flattening in order, and why none is listed. -// It covers each way the rules end, and every root of each registry. +// TestNarrowedShapes_MatchesACopyOfTheRegistry holds every narrowing of random +// registries holding unions to narrowingReference, which builds each shape as a +// copy of the registry with every composition entry naming a union rewritten to +// the variant read there, and flattens the copy: the union, each shape's Over +// and flattening in order, and why none is listed. It covers each way the rules +// end, and every root of each registry. func TestNarrowedShapes_MatchesACopyOfTheRegistry(t *testing.T) { t.Parallel() seen := map[string]int{} @@ -148,7 +148,7 @@ func randomModel(rng *rand.Rand, id ir.TypeID, pick func() ir.TypeID) *ir.Model // result as renderNarrowing does. func narrowingReference(t *testing.T, types ir.TypeRegistry, root ir.TypeID) []string { t.Helper() - nr := narrowingRef{t: t, types: types, root: standsFor(types, root)} + nr := narrowingRef{t: t, types: types, root: aliasChainEnd(types, root)} unions, _ := nr.composition(types, nil) head := func(union ir.TypeID, why ir.Undistributed) []string { return []string{fmt.Sprintf("union %q undistributed %q", union, why)} @@ -183,11 +183,11 @@ type narrowingRef struct { func (nr *narrowingRef) distribute(over []sub, union ir.TypeID, depth int) ir.Undistributed { nr.t.Helper() require.Less(nr.t, depth, 32, "no union repeats along a distribution") - unionValue := nr.types[union].(*ir.Union) - if unionValue.WireTagged && (unionValue.Discriminator == nil || unionValue.Discriminator.Envelope != "" || unionValue.Discriminator.TupleElementIndex != nil) { + unionNode := nr.types[union].(*ir.Union) + if unionNode.WireTagged && (unionNode.Discriminator == nil || unionNode.Discriminator.Envelope != "" || unionNode.Discriminator.TupleElementIndex != nil) { return ir.UndistributedNotValues } - for _, variant := range unionValue.Variants { + for _, variant := range unionNode.Variants { if variant.Type.Target == "" { continue } @@ -220,17 +220,17 @@ func (nr *narrowingRef) distribute(over []sub, union ir.TypeID, depth int) ir.Un type sub struct{ union, variant ir.TypeID } // rewrite copies the registry with every composition entry of the root's -// composition standing for a union over reads a variant of rewritten to that -// variant, read along a chain of them, and reports whether a chain reached a -// union twice. Only the root's composition is rewritten, since only its -// entries are read. +// composition naming a union over reads a variant of rewritten to that variant, +// read along a chain of them, and reports whether a chain reached a union +// twice. Only the root's composition is rewritten, since only its entries are +// read. func (nr *narrowingRef) rewrite(over []sub) (ir.TypeRegistry, bool) { copied := maps.Clone(nr.types) var unending bool fix := func(typeRef ir.TypeRef) ir.TypeRef { seen := map[ir.TypeID]bool{} for typeRef.Target != "" { - end := standsFor(nr.types, typeRef.Target) + end := aliasChainEnd(nr.types, typeRef.Target) i := indexOf(over, end) if i < 0 { break @@ -244,36 +244,36 @@ func (nr *narrowingRef) rewrite(over []sub) (ir.TypeRegistry, bool) { } return typeRef } - for id, td := range nr.types { - model, ok := td.(*ir.Model) + for id, typeDef := range nr.types { + model, ok := typeDef.(*ir.Model) if !ok || model == nil { continue } - modelValue := *model + modelCopy := *model if model.Base != nil { b := fix(*model.Base) - modelValue.Base = &b + modelCopy.Base = &b } - modelValue.Implements, modelValue.Mixins = nil, nil + modelCopy.Implements, modelCopy.Mixins = nil, nil for _, typeRef := range model.Implements { - modelValue.Implements = append(modelValue.Implements, fix(typeRef)) + modelCopy.Implements = append(modelCopy.Implements, fix(typeRef)) } for _, typeRef := range model.Mixins { - modelValue.Mixins = append(modelValue.Mixins, fix(typeRef)) + modelCopy.Mixins = append(modelCopy.Mixins, fix(typeRef)) } - copied[id] = &modelValue + copied[id] = &modelCopy } return copied, unending && nr.reachesRewrite(copied, over) } // reachesRewrite reports whether the root's composition in copied holds an -// entry whose chain of variants reached a union twice: one still standing for -// a union over reads a variant of, where rewrite leaves such an entry. +// entry whose chain of variants reached a union twice: one still naming a union +// over reads a variant of, where rewrite leaves such an entry. func (nr *narrowingRef) reachesRewrite(copied ir.TypeRegistry, over []sub) bool { models, _ := composition(copied, nr.root) for _, model := range models { for _, target := range entries(model) { - if target != "" && indexOf(over, standsFor(copied, target)) >= 0 { + if target != "" && indexOf(over, aliasChainEnd(copied, target)) >= 0 { return true } } @@ -291,17 +291,17 @@ func indexOf(over []sub, id ir.TypeID) int { return -1 } -// composition returns the unions the root's composition in types narrows, -// each a union an entry stands for that over reads no variant of and that -// does not list the root, in the order of first sight, and whether a model a -// variant over reads stands for composes the root. +// composition returns the unions the root's composition in types narrows, each +// a union an entry names that over reads no variant of and that does not list +// the root, in the order of first sight, and whether a model a variant over +// reads names composes the root. func (nr *narrowingRef) composition(types ir.TypeRegistry, over []sub) ([]ir.TypeID, bool) { models, _ := composition(types, nr.root) var unions []ir.TypeID listed := map[ir.TypeID]bool{} for _, id := range slices.Sorted(maps.Keys(models)) { for _, target := range entries(models[id]) { - end := standsFor(types, target) + end := aliasChainEnd(types, target) union, ok := types[end].(*ir.Union) if !ok || union == nil || listed[end] || indexOf(over, end) >= 0 { continue @@ -315,11 +315,11 @@ func (nr *narrowingRef) composition(types ir.TypeRegistry, over []sub) ([]ir.Typ return unions, nr.placedReachesRoot(types, models, over) } -// placedReachesRoot reports whether a model one of over's variants stands for -// in the root's composition composes the root in turn. +// placedReachesRoot reports whether a model one of over's variants names in the +// root's composition composes the root in turn. func (nr *narrowingRef) placedReachesRoot(types ir.TypeRegistry, models map[ir.TypeID]*ir.Model, over []sub) bool { for _, sub := range over { - end := standsFor(types, sub.variant) + end := aliasChainEnd(types, sub.variant) if _, in := models[end]; in && composedBelow(types, end)[nr.root] { return true } @@ -327,10 +327,10 @@ func (nr *narrowingRef) placedReachesRoot(types ir.TypeRegistry, models map[ir.T return false } -// listsRoot reports whether union has a variant standing for root. +// listsRoot reports whether union has a variant naming root. func listsRoot(types ir.TypeRegistry, union *ir.Union, root ir.TypeID) bool { for _, variant := range union.Variants { - if standsFor(types, variant.Type.Target) == root { + if aliasChainEnd(types, variant.Type.Target) == root { return true } } diff --git a/ir/narrowing_test.go b/ir/narrowing_test.go index 2b7dc2e7a..2a28fd7e4 100644 --- a/ir/narrowing_test.go +++ b/ir/narrowing_test.go @@ -72,7 +72,7 @@ func TestNarrowedShapes_ReadsAVariantInTheUnionsPlace(t *testing.T) { assert.Equal(t, []string{ "over [block]: [block.action@block required block.status@block own.id@own required] undeclared [] unflattened []", "over [log]: [log.action@log required own.id@own required] undeclared [] unflattened []", - }, shapeLines(narrowing), "each variant is read where the union stands, laid out as the conjunct it replaces") + }, shapeLines(narrowing), "each variant is read where the union is, laid out as the conjunct it replaces") assert.Empty(t, cmp.Diff(narrowing, narrowed(t, doc.Types, "stored")), "a second call agrees") } @@ -99,7 +99,7 @@ func TestNarrowedShapes_AVariantIsAConjunctLikeAnyOther(t *testing.T) { assert.Nil(t, narrowing.Shapes[1].Properties[2].Deprecation) } -func TestNarrowedShapes_ReadsTheUnionWhereverItStands(t *testing.T) { +func TestNarrowedShapes_ReadsTheUnionWhereverItIs(t *testing.T) { t.Parallel() cases := []struct { name string @@ -213,9 +213,9 @@ func TestNarrowedShapes_NarrowsNone(t *testing.T) { assert.Equal(t, ir.Narrowing{}, narrowing, "root %q: a model its union lists is that variant, and nothing else narrows", root) assert.Positive(t, spent, "root %q: finding so is a walk", root) } - narrowingValue, _, ok := ir.NarrowedShapes(nil, "m", math.MaxInt) + narrowing, _, ok := ir.NarrowedShapes(nil, "m", math.MaxInt) assert.True(t, ok) - assert.Equal(t, ir.Narrowing{}, narrowingValue, "no registry narrows nothing") + assert.Equal(t, ir.Narrowing{}, narrowing, "no registry narrows nothing") } func TestNarrowedShapes_NoVariantGivesNoShape(t *testing.T) { @@ -381,7 +381,7 @@ func TestNarrowedShapes_StepsCountWhatEachWalkReads(t *testing.T) { listing := 2 // a variant read and resolved to tell whether the union lists the model inPlace := 2 // the variant read in the union's place, and resolved assert.Equal(t, ir.FlattenSteps(narrow.Types, "m")+listing+ir.FlattenSteps(copied.Types, "m")+inPlace+1, spent(narrow), - "the walk finding the union, the shape's walk, which reads the variant where the union stands, and the shape") + "the walk finding the union, the shape's walk, which reads the variant where the union is, and the shape") wide := irtest.DocOf(unionOf("u", "v", "w"), owning("v", nil), owning("w", nil), owning("m", based("u"))) shape := spent(narrow) - ir.FlattenSteps(narrow.Types, "m") - listing @@ -391,7 +391,7 @@ func TestNarrowedShapes_StepsCountWhatEachWalkReads(t *testing.T) { listsFirst := irtest.DocOf(unionOf("u", "m"), owning("m", based("u"))) listsFirstOfMore := irtest.DocOf(unionOf("u", "m", "v", "w"), owning("v", nil), owning("w", nil), owning("m", based("u"))) assert.Equal(t, spent(listsFirst), spent(listsFirstOfMore), - "a union reads no variant past the one standing for the model") + "a union reads no variant past the one naming the model") selfOnly := irtest.DocOf(unionOf("u", "u"), owning("m", based("u"))) selfAndMore := irtest.DocOf(unionOf("u", "u", "v", "w"), owning("v", nil), owning("w", nil), owning("m", based("u"))) @@ -417,12 +417,12 @@ func TestNarrowedShapes_StepsCountWhatEachWalkReads(t *testing.T) { // contrast, cost linear steps. func TestNarrowedShapes_CountsWhatNestedUnionsMultiply(t *testing.T) { t.Parallel() - nested := func(n int) ir.TypeRegistry { + nested := func(count int) ir.TypeRegistry { doc := irtest.DocOf(owning("m", based(unionAt(0)), wired("m.a", "a"))) - for i := range n { + for i := range count { leaf := ir.TypeID(fmt.Sprintf("leaf%04d", i)) doc.Types[leaf] = owning(leaf, nil, wired(ir.PropertyID(leaf), "b")) - if i == n-1 { + if i == count-1 { doc.Types[unionAt(i)] = unionOf(unionAt(i), leaf) continue } @@ -444,20 +444,20 @@ func TestNarrowedShapes_CountsWhatNestedUnionsMultiply(t *testing.T) { _, _, ok := ir.NarrowedShapes(nested(1000), "m", 100_000) assert.False(t, ok, "unions nested 1,000 deep pass a limit their entries and members alone stay under") - wide := func(n int) ir.TypeRegistry { + wide := func(count int) ir.TypeRegistry { union := unionOf("u") doc := irtest.DocOf(union, owning("m", based("u"), wired("m.a", "a"))) - for i := range n { + for i := range count { typeID := ir.TypeID(fmt.Sprintf("v%04d", i)) doc.Types[typeID] = owning(typeID, nil, wired(ir.PropertyID(typeID), "b")) union.Variants = append(union.Variants, ir.Variant{Type: ir.TypeRef{Target: typeID}}) } return doc.Types } - fanIn := func(n int) ir.TypeRegistry { + fanIn := func(count int) ir.TypeRegistry { doc := irtest.DocOf(unionOf("u", "v", "w"), owning("v", nil, wired("v.a", "a")), owning("w", nil, wired("w.a", "a"))) - names := make([]ir.TypeID, n) + names := make([]ir.TypeID, count) for i := range names { names[i] = ir.TypeID(fmt.Sprintf("x%04d", i)) doc.Types[names[i]] = owning(names[i], based("u"), wired(ir.PropertyID(names[i]), "b")) @@ -476,11 +476,11 @@ func TestNarrowedShapes_CountsWhatNestedUnionsMultiply(t *testing.T) { } } -// TestNarrowedShapes_ReadsAChainOncePerWalk holds an entry standing for a union -// to the same cost however long the chain of variants read in its place: a -// walk reads a chain once, as it reads an alias chain, so a model at the end -// of a deep chain that names its first union, and one halfway along, many -// times costs no product of the two. +// TestNarrowedShapes_ReadsAChainOncePerWalk holds an entry naming a union to +// the same cost however long the chain of variants read in its place: a walk +// reads a chain once, as it reads an alias chain, so a model at the end of a +// deep chain that names its first union, and one halfway along, many times +// costs no product of the two. func TestNarrowedShapes_ReadsAChainOncePerWalk(t *testing.T) { t.Parallel() chained := func(deep, entries int) ir.TypeRegistry { diff --git a/ir/nofloat_test.go b/ir/nofloat_test.go index 150642442..01d225833 100644 --- a/ir/nofloat_test.go +++ b/ir/nofloat_test.go @@ -50,9 +50,9 @@ func TestIR_NoFloatFields(t *testing.T) { // seeded from the kinds the ir sources declare so a new variant is float-checked // the day it is added, not the day someone remembers to extend a list here. for _, kc := range declaredTypeKinds(t) { - td, ok := ir.NewTypeDef(kc.kind) + typeDef, ok := ir.NewTypeDef(kc.kind) require.True(t, ok, "no concrete type registered for kind %q", kc.kind) - rt := reflect.TypeOf(td) + rt := reflect.TypeOf(typeDef) require.Equal(t, reflect.Pointer, rt.Kind(), "NewTypeDef must return a pointer for %q", kc.kind) walk(rt.Elem(), rt.Elem().Name()) } diff --git a/ir/operation.go b/ir/operation.go index f944f28fd..28c5eff9f 100644 --- a/ir/operation.go +++ b/ir/operation.go @@ -162,7 +162,7 @@ type Payload struct { // mandatory, false = it may be omitted. nil = the source format does not // express body optionality at all, which is why this is a pointer — for a // format that does, an unstated body is optional, and collapsing that onto - // nil would make "the format is silent" indistinguishable from "the + // nil would make "the format says nothing" indistinguishable from "the // document says no". A response or message payload leaves it nil: only a // request body can be omitted, and pass/validate reports one that is set // anywhere else (ir/payload-required-outside-request). diff --git a/ir/parameter_encoding_test.go b/ir/parameter_encoding_test.go index 4da096ab5..fc905bbe3 100644 --- a/ir/parameter_encoding_test.go +++ b/ir/parameter_encoding_test.go @@ -44,8 +44,8 @@ func TestParameter_EncodingJSONContract(t *testing.T) { // parameter's own type, and TypeEdges agrees with the reflection walk. func TestTypeEdges_ReadsAParametersEncoding(t *testing.T) { t.Parallel() - model := irtest.ModelOf("type/m", func(modelValue *ir.Model) { - modelValue.Properties = []ir.Property{{ID: "property/f", Type: ir.TypeRef{Target: "type/f"}, Args: []ir.Parameter{{ + model := irtest.ModelOf("type/m", func(model *ir.Model) { + model.Properties = []ir.Property{{ID: "property/f", Type: ir.TypeRef{Target: "type/f"}, Args: []ir.Parameter{{ ID: "q/a", Type: ir.TypeRef{Target: "type/arg"}, Encoding: &ir.Encoding{WireType: &ir.TypeRef{Target: "type/x"}, Schema: &ir.TypeRef{Target: "type/y"}}, }}}} diff --git a/ir/pathlog.go b/ir/pathlog.go index d39a6318f..b45107c79 100644 --- a/ir/pathlog.go +++ b/ir/pathlog.go @@ -72,25 +72,25 @@ func (l *PathLog) All() iter.Seq2[int, WalkPath] { // sharedSteps returns how many steps a and b open with alike. func sharedSteps(a, b []pathStep) int { - n := min(len(a), len(b)) - for i := range n { + shared := min(len(a), len(b)) + for i := range shared { if a[i] != b[i] { return i } } - return n + return shared } -// appendGrowing appends vs to s, growing s's capacity five halves whenever it -// fills. append grows a large slice by a quarter at a time, so a slice built -// one entry at a time is copied several times over, where this copies each -// entry less than once on average. slices.Grow grows about as far, but a race -// build makes two allocations for each of its growths. -func appendGrowing[T any](s []T, vs ...T) []T { - if need := len(s) + len(vs); need > cap(s) { - grown := make([]T, len(s), max(need, cap(s)*5/2)) - copy(grown, s) - s = grown +// appendGrowing appends vs to slice, growing slice's capacity five halves +// whenever it fills. append grows a large slice by a quarter at a time, so a +// slice built one entry at a time is copied several times over, where this +// copies each entry less than once on average. slices.Grow grows about as far, +// but a race build makes two allocations for each of its growths. +func appendGrowing[T any](slice []T, vs ...T) []T { + if need := len(slice) + len(vs); need > cap(slice) { + grown := make([]T, len(slice), max(need, cap(slice)*5/2)) + copy(grown, slice) + slice = grown } - return append(s, vs...) + return append(slice, vs...) } diff --git a/ir/primitive_admits.go b/ir/primitive_admits.go new file mode 100644 index 000000000..0f7625d88 --- /dev/null +++ b/ir/primitive_admits.go @@ -0,0 +1,163 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "strconv" + + "github.com/dexpace/morphic/rfc3339" +) + +// Bounds of the fixed-width integers, as the decimal literals inRange compares. +const ( + int8Min = "-128" + int8Max = "127" + int16Min = "-32768" + int16Max = "32767" + int32Min = "-2147483648" + int32Max = "2147483647" + int64Min = "-9223372036854775808" + int64Max = "9223372036854775807" + uint8Max = "255" + uint16Max = "65535" + uint32Max = "4294967295" + uint64Max = "18446744073709551615" +) + +// The IEEE 754 formats PrimitiveAdmits judges against: decimal128's digit +// budget and exponent range, and the width of each binary float. +const ( + decimal128Digits = 34 + decimal128MaxMsdExp = 6144 + decimal128MinLowExp = -6176 + float32Bits = 32 + float64Bits = 64 +) + +// PrimitiveAdmits judges whether value is a value of the primitive kind +// primitiveKind, exactly: a bounded read of a number rather than a conversion, +// so an exponent no machine type holds is refused, not overflowed. An IEEE 754 +// kind admits the infinities and NaN too. It answers unknown for bytes, whose +// values an encoding writes, and a kind ir does not declare. A null is not +// judged here: the reference's nullability decides it. +func PrimitiveAdmits(primitiveKind PrimitiveKind, value Value) Admission { + switch primitiveKind { + case PrimitiveAny: + return AdmitsYes + case PrimitiveBool: + return AdmissionOf(value.Kind == ValueBool) + case PrimitiveString: + return AdmissionOf(value.Kind == ValueString) + case PrimitiveInt8: + return AdmissionOf(inRange(value, int8Min, int8Max)) + case PrimitiveInt16: + return AdmissionOf(inRange(value, int16Min, int16Max)) + case PrimitiveInt32: + return AdmissionOf(inRange(value, int32Min, int32Max)) + case PrimitiveInt64: + return AdmissionOf(inRange(value, int64Min, int64Max)) + case PrimitiveUint8: + return AdmissionOf(inRange(value, "0", uint8Max)) + case PrimitiveUint16: + return AdmissionOf(inRange(value, "0", uint16Max)) + case PrimitiveUint32: + return AdmissionOf(inRange(value, "0", uint32Max)) + case PrimitiveUint64: + return AdmissionOf(inRange(value, "0", uint64Max)) + case PrimitiveInteger: + decimal, ok := decimalOf(value) + return AdmissionOf(ok && decimal.IsInt()) + case PrimitiveNumber, PrimitiveDecimal: + _, ok := decimalOf(value) + return AdmissionOf(ok) + case PrimitiveFloat: + _, ok := decimalOf(value) + return AdmissionOf(ok || isNonFinite(value.Kind)) + case PrimitiveDecimal128: + return AdmissionOf(admitsDecimal128(value)) + case PrimitiveFloat32: + return AdmissionOf(admitsFloat(value, float32Bits)) + case PrimitiveFloat64: + return AdmissionOf(admitsFloat(value, float64Bits)) + case PrimitiveDate: + return AdmissionOf(value.Kind == ValueString && parses("2006-01-02", value.String)) + case PrimitiveTime: + return AdmissionOf(value.Kind == ValueString && rfc3339.Parses(value.String, rfc3339.PartialTime)) + case PrimitiveDatetime: + return AdmissionOf(value.Kind == ValueString && rfc3339.Parses(value.String, rfc3339.LocalDateTime)) + case PrimitiveDatetimeOffset: + return AdmissionOf(value.Kind == ValueString && rfc3339.Parses(value.String, rfc3339.DateTime)) + case PrimitiveUUID: + return AdmissionOf(value.Kind == ValueString && isUUID(value.String)) + case PrimitiveURL: + return AdmissionOf(value.Kind == ValueString && isAbsoluteURI(value.String)) + case PrimitiveDuration: + return AdmissionOf(value.Kind == ValueString && isDuration(value.String)) + case PrimitiveBytes: + return AdmitsUnknown + default: + return AdmitsUnknown + } +} + +// decimalOf reads value as a number, reporting false for any other kind of +// value and for a number no Decimal holds: reading that as zero would admit it +// everywhere. +func decimalOf(value Value) (Decimal, bool) { + if value.Kind != ValueNumber { + return Decimal{}, false + } + decimal, err := value.Number.Decimal() + return decimal, err == nil +} + +// inRange reports whether value is an integral number from lo to hi inclusive. +// An end that reads as no number admits nothing. +func inRange(value Value, lo, hi BigVal) bool { + decimal, ok := decimalOf(value) + low, lowErr := lo.Decimal() + high, highErr := hi.Decimal() + return ok && lowErr == nil && highErr == nil && decimal.IsInt() && decimal.Cmp(low) >= 0 && decimal.Cmp(high) <= 0 +} + +// isNonFinite reports whether a value of kind is an infinity or NaN +// (docs/ir/primitives.md#containment). +func isNonFinite(kind ValueKind) bool { + return kind == ValueInfinity || kind == ValueNegativeInfinity || kind == ValueNaN +} + +// admitsDecimal128 reports whether value fits IEEE 754 decimal128: an infinity +// or NaN, or a number of at most 34 significant digits, the leading one no +// higher than 10^6144 and the last no lower than 10^-6176. +func admitsDecimal128(value Value) bool { + if isNonFinite(value.Kind) { + return true + } + decimal, ok := decimalOf(value) + if !ok { + return false + } + if decimal.Sign() == 0 { + return true + } + digits := int64(len(decimal.Digits())) + lowest := decimal.Exponent() - (digits - 1) + return digits <= decimal128Digits && decimal.Exponent() <= decimal128MaxMsdExp && lowest >= decimal128MinLowExp +} + +// admitsFloat reports whether value is an infinity or NaN, or a number that +// rounds to a finite value of a binary float of the given width: rounding is +// allowed, as OpenAPI floats round. The float strconv returns is not kept, so +// no value passes through one. +func admitsFloat(value Value, bits int) bool { + if isNonFinite(value.Kind) { + return true + } + decimal, ok := decimalOf(value) + if !ok { + return false + } + _, err := strconv.ParseFloat(decimal.String(), bits) + return err == nil +} diff --git a/ir/primitive_admits_internal_test.go b/ir/primitive_admits_internal_test.go new file mode 100644 index 000000000..4cf87b523 --- /dev/null +++ b/ir/primitive_admits_internal_test.go @@ -0,0 +1,40 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// numberOf is s as a number value. +func numberOf(text string) Value { return Value{Kind: ValueNumber, Number: BigVal(text)} } + +// TestDecimalOf_DeclinesWhatIsNoReadableNumber pins that a value with no number +// to read is declined rather than read as zero: a literal outside the grammar, one +// past the exponent range a BigVal holds, and a value that is no number at all. +func TestDecimalOf_DeclinesWhatIsNoReadableNumber(t *testing.T) { + t.Parallel() + for _, value := range []Value{numberOf("1p4"), numberOf("1e1000000000000000000"), {Kind: ValueString, String: "1"}} { + _, ok := decimalOf(value) + + assert.False(t, ok, "%v", value) + } + + decimal, ok := decimalOf(numberOf("1e1000001")) + assert.True(t, ok) + assert.Equal(t, int64(1000001), decimal.Exponent()) +} + +// TestInRange_DeclinesABoundThatReadsAsNoNumber pins the second half of the +// judge: a range whose end is no number admits nothing, where reading it as zero +// would admit everything above it. +func TestInRange_DeclinesABoundThatReadsAsNoNumber(t *testing.T) { + t.Parallel() + assert.True(t, inRange(numberOf("5"), "0", "10")) + assert.False(t, inRange(numberOf("5"), "1p4", "10"), "a low end outside the grammar") + assert.False(t, inRange(numberOf("5"), "0", "1p4"), "a high end outside the grammar") + assert.False(t, inRange(numberOf("-1"), "-5", "1p4"), "a high end that would read as zero, above this value") +} diff --git a/ir/propertycounts.go b/ir/propertycounts.go new file mode 100644 index 000000000..f241ba89e --- /dev/null +++ b/ir/propertycounts.go @@ -0,0 +1,138 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir + +import "github.com/dexpace/morphic/stronglyconnected" + +// PropertyCountBounds reads the property counts an instance of a model is held +// to (docs/ir/models.md#the-flattening): the intersection of the MinProperties +// and MaxProperties of the model and of every model it composes ([ComposedOf]) +// at any distance, through alias scalars. It reads each strongly connected +// component of the composition once, so reading every model of a registry +// costs time linear in its models and entries. It reads each node as its +// lookup first finds it, and is not safe for concurrent use. +type PropertyCountBounds struct { + components *countedComponents + search *stronglyconnected.Search[frame] +} + +// countedComponents is what a [PropertyCountBounds] has read of the +// composition: its components, closed by the search it visits. +type countedComponents struct { + node func(TypeID) (TypeDef, bool) + aliases *AliasChainIndex + // of holds, for each model whose component has closed, that component's + // place in intersections and in agreed. + of map[TypeID]int + // intersections holds each closed component's intersection, and agreed what + // it holds an instance to (ConstraintIntersection.AgreedConstraints): nil + // where no model it brings writes a count. + intersections []ConstraintIntersection + agreed []*Constraints +} + +// NewPropertyCountBounds returns a reader of the models node finds, reading +// each reference through aliases, an index over the same types. It has read +// none of them. +func NewPropertyCountBounds(node func(TypeID) (TypeDef, bool), aliases *AliasChainIndex) *PropertyCountBounds { + components := &countedComponents{node: node, aliases: aliases, of: map[TypeID]int{}} + return &PropertyCountBounds{components: components, search: stronglyconnected.NewSearch[frame](components)} +} + +// Of returns the property counts an instance of the model root names is held +// to, root read through alias scalars: nil where root names no model, or no +// model its composition brings writes a count. For a shape [NarrowedShapes] +// lists, over is its Over, and the counts intersect too those of each variant +// read in a union's place and of every model it composes. A union, or another +// type an entry names that is no model, intersects none. A caller writes +// nothing to the value returned, which later calls share. +func (bounds *PropertyCountBounds) Of(root TypeID, over ...TypeID) *Constraints { + component, isModel := bounds.componentOf(root) + if !isModel { + return nil + } + if len(over) == 0 { + return bounds.components.agreed[component] + } + intersection := bounds.components.intersections[component] + for _, variant := range over { + if variantComponent, variantIsModel := bounds.componentOf(variant); variantIsModel { + intersection = intersection.Intersect(bounds.components.intersections[variantComponent]) + } + } + return intersection.AgreedConstraints() +} + +// componentOf returns the place of the component of the model id names, read +// through alias scalars, searching the composition from it where no search +// has met it, and false where it names no model. +func (bounds *PropertyCountBounds) componentOf(id TypeID) (int, bool) { + model, isModel := bounds.components.modelAt(id) + if !isModel { + return 0, false + } + if component, closed := bounds.components.of[model.id]; closed { + return component, true + } + bounds.search.From(model) + return bounds.components.of[model.id], true +} + +// modelAt returns the model target names, read through alias scalars, and +// false where it names none: a cyclic chain ends at a scalar. +func (components *countedComponents) modelAt(target TypeID) (frame, bool) { + end, _ := components.aliases.End(target) + typeDef, _ := components.node(end) + model, isModel := typeDef.(*Model) + if !isModel || model == nil { + return frame{}, false + } + return frame{id: end, m: model}, true +} + +// Edge returns the model from's part at index names, read through alias +// scalars, which the search follows, a part naming no model leading to none, +// and false past from's last part. +func (components *countedComponents) Edge(from frame, index int) (to frame, follow, more bool) { + target, more := composedPart(from.m, index) + if !more { + return frame{}, false, false + } + to, follow = components.modelAt(target) + return to, follow, true +} + +// LeaveVertex keeps nothing of a model left: its component is read as it +// closes. +func (*countedComponents) LeaveVertex(frame) {} + +// CloseComponent intersects, as a component closes, the counts its models +// write and the intersection of each component a part of theirs names, which +// has closed before it, the component's own aside. +func (components *countedComponents) CloseComponent(members []frame) { + component := len(components.intersections) + for _, member := range members { + components.of[member.id] = component + } + var intersection ConstraintIntersection + for _, member := range members { + if own := member.m.Constraints; own != nil { + intersection = intersection.Intersect(ConstraintIntersectionOf(&Constraints{ + MinProperties: own.MinProperties, MaxProperties: own.MaxProperties, + })) + } + for index := range len(member.m.Mixins) + 1 { + target, more := composedPart(member.m, index) + if !more { + break + } + reached, isModel := components.modelAt(target) + if other, closed := components.of[reached.id]; isModel && closed && other != component { + intersection = intersection.Intersect(components.intersections[other]) + } + } + } + components.intersections = append(components.intersections, intersection) + components.agreed = append(components.agreed, intersection.AgreedConstraints()) +} diff --git a/ir/propertycounts_test.go b/ir/propertycounts_test.go new file mode 100644 index 000000000..4bb15e5f9 --- /dev/null +++ b/ir/propertycounts_test.go @@ -0,0 +1,211 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package ir_test + +import ( + "fmt" + "maps" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" +) + +// counted sets a model's member counts, nil leaving one unset. +func counted(minimum, maximum *int64) func(*ir.Model) { + return func(model *ir.Model) { + model.Constraints = &ir.Constraints{MinProperties: minimum, MaxProperties: maximum} + } +} + +// both applies each of mutates in turn. +func both(mutates ...func(*ir.Model)) func(*ir.Model) { + return func(model *ir.Model) { + for _, mutate := range mutates { + mutate(model) + } + } +} + +// propertyCountsOf is a reader of the property counts of the models types +// holds, reading alias chains through an index of its own. +func propertyCountsOf(types ir.TypeRegistry) *ir.PropertyCountBounds { + return ir.NewPropertyCountBounds(types.Lookup, ir.NewAliasChainIndex(types.Lookup)) +} + +// TestPropertyCountBounds_IntersectsTheCountsOfWhatAModelComposes holds +// PropertyCountBounds to the intersection of the member counts of the model +// and of every model it composes along Base and Mixins, read through alias +// scalars: the largest minimum and the smallest maximum. A model composing +// none states its own, an interface it implements binds through its own +// check, a cycle intersects every model on it, and a root writing none +// anywhere, or naming no model, holds nil. A reader asking the roots in either +// order answers alike, and writes nothing to the models it reads. +func TestPropertyCountBounds_IntersectsTheCountsOfWhatAModelComposes(t *testing.T) { + t.Parallel() + two, three, five, one := new(int64(2)), new(int64(3)), new(int64(5)), new(int64(1)) + doc := irtest.DocOf( + owning("obj", counted(two, nil)), + owning("cap", counted(nil, one)), + owning("wide", counted(three, five)), + owning("plain", nil), + owning("b", both(based("obj"), counted(nil, five))), + owning("empty", both(based("obj"), counted(nil, one))), + owning("mixed", both(based("obj"), mixing("wide", "cap"))), + owning("aliased", based("alias")), + irtest.ScalarOf("alias", "obj"), + owning("implementer", func(model *ir.Model) { model.Implements = irtest.RefsTo("wide") }), + owning("deep", based("b")), + owning("loopA", both(based("loopB"), counted(two, nil))), + owning("loopB", both(based("loopA"), counted(nil, five))), + owning("above", both(based("loopA"), counted(three, nil))), + owning("free", based("plain")), + irtest.ScalarOf("ring", "ring"), + owning("onRing", both(based("ring"), counted(one, nil))), + ) + want := map[ir.TypeID]*ir.Constraints{ + "obj": {MinProperties: two}, + "b": {MinProperties: two, MaxProperties: five}, + "empty": {MinProperties: two, MaxProperties: one}, + "mixed": {MinProperties: three, MaxProperties: one}, + "aliased": {MinProperties: two}, + "implementer": nil, + "deep": {MinProperties: two, MaxProperties: five}, + "loopA": {MinProperties: two, MaxProperties: five}, + "loopB": {MinProperties: two, MaxProperties: five}, + "above": {MinProperties: three, MaxProperties: five}, + "plain": nil, + "free": nil, + "alias": {MinProperties: two}, + "ring": nil, + "onRing": {MinProperties: one}, + "absent": nil, + } + roots := slices.Sorted(maps.Keys(want)) + backward := slices.Clone(roots) + slices.Reverse(backward) + for _, order := range [][]ir.TypeID{roots, backward} { + bounds := propertyCountsOf(doc.Types) + for _, root := range order { + assert.Equal(t, want[root], bounds.Of(root), "root %q, first asked %q", root, order[0]) + } + } + obj, isModel := doc.Types["obj"].(*ir.Model) + require.True(t, isModel) + assert.Equal(t, &ir.Constraints{MinProperties: two}, obj.Constraints, "the intersection writes nothing to the models it reads") +} + +// TestPropertyCountBounds_ReadsTheVariantsAShapeIsOver holds the counts of a +// shape NarrowedShapes lists to its composition: the model's, and those of +// each variant read in a union's place and of every model that one composes, +// a variant over an alias read through it, one naming no model intersecting +// none, and a union in turn adding the variant read in its place. +func TestPropertyCountBounds_ReadsTheVariantsAShapeIsOver(t *testing.T) { + t.Parallel() + one, two, three, four, five := new(int64(1)), new(int64(2)), new(int64(3)), new(int64(4)), new(int64(5)) + doc := irtest.DocOf( + unionOf("union", "composing", "viaAlias", "type/string", "nesting"), + owning("root", both(mixing("union"), counted(one, nil))), + owning("composing", both(based("composed"), counted(nil, three))), + owning("composed", counted(two, nil)), + irtest.ScalarOf("viaAlias", "aliased"), + owning("aliased", counted(nil, five)), + &ir.Primitive{ID: "type/string", PrimitiveKind: ir.PrimitiveString}, + owning("nesting", both(mixing("inner"), counted(nil, four))), + unionOf("inner", "innerVariant"), + owning("innerVariant", counted(three, nil)), + ) + bounds := propertyCountsOf(doc.Types) + shapes := map[string]*ir.Constraints{} + for _, shape := range narrowed(t, doc.Types, "root").Shapes { + shapes[fmt.Sprint(shape.Over)] = bounds.Of("root", shape.Over...) + } + assert.Equal(t, map[string]*ir.Constraints{ + "[composing]": {MinProperties: two, MaxProperties: three}, + "[viaAlias]": {MinProperties: one, MaxProperties: five}, + "[type/string]": {MinProperties: one}, + "[nesting innerVariant]": {MinProperties: three, MaxProperties: four}, + }, shapes) + assert.Equal(t, &ir.Constraints{MinProperties: one}, bounds.Of("root"), "the model's own, whose union intersects none") +} + +// chainedCounts are the compositions TestPropertyCountBounds_ReadsEveryModelInLinearWork +// reads at a size: n models, each writing a minimum, composed in a chain of +// bases, in a chain of mixins each named through an alias, and in one cycle. +func chainedCounts() map[string]func(n int) ir.TypeRegistry { + model := func(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("m%05d", i)) } + build := func(count int, compose func(composer *ir.Model, i int, types ir.TypeRegistry)) ir.TypeRegistry { + types := ir.TypeRegistry{} + for i := range count { + composer := owning(model(i), counted(new(int64(i)), nil)) + compose(composer, i, types) + types[composer.ID] = composer + } + return types + } + return map[string]func(n int) ir.TypeRegistry{ + "a chain of bases": func(count int) ir.TypeRegistry { + return build(count, func(composer *ir.Model, i int, _ ir.TypeRegistry) { + if i > 0 { + composer.Base = &ir.TypeRef{Target: model(i - 1)} + } + }) + }, + "a chain of mixins through aliases": func(count int) ir.TypeRegistry { + return build(count, func(composer *ir.Model, i int, types ir.TypeRegistry) { + if i > 0 { + alias := ir.TypeID(fmt.Sprintf("a%05d", i)) + types[alias] = irtest.ScalarOf(alias, model(i-1)) + composer.Mixins = irtest.RefsTo(alias) + } + }) + }, + "a cycle": func(count int) ir.TypeRegistry { + return build(count, func(composer *ir.Model, i int, _ ir.TypeRegistry) { + composer.Base = &ir.TypeRef{Target: model((i + 1) % count)} + }) + }, + } +} + +// TestPropertyCountBounds_ReadsEveryModelInLinearWork holds one reader asking +// the counts of every model of each chainedCounts composition, first the +// chain's start and then its end, to node lookups growing linearly in the +// models at 250, 500 and 1,000: a reading of each model's composition of its +// own grows with the square of the chain. +func TestPropertyCountBounds_ReadsEveryModelInLinearWork(t *testing.T) { + t.Parallel() + for name, build := range chainedCounts() { + for _, fromTheEnd := range []bool{false, true} { + var lookups [3]int + for k, n := range []int{250, 500, 1000} { + types := build(n) + lookup := func(id ir.TypeID) (ir.TypeDef, bool) { + lookups[k]++ + return types.Lookup(id) + } + bounds := ir.NewPropertyCountBounds(lookup, ir.NewAliasChainIndex(lookup)) + order := make([]int, n) + for i := range n { + order[i] = i + if fromTheEnd { + order[i] = n - 1 - i + } + } + for _, i := range order { + bounds.Of(ir.TypeID(fmt.Sprintf("m%05d", i))) + } + end := bounds.Of(ir.TypeID(fmt.Sprintf("m%05d", n-1))) + require.Equal(t, &ir.Constraints{MinProperties: new(int64(n - 1))}, end, + "%s at %d: the chain's end is held to the largest minimum, every model read", name, n) + } + assert.LessOrEqual(t, float64(lookups[2]-lookups[1]), 2.5*float64(lookups[1]-lookups[0]), + "%s, from the end %t: lookups at 250, 500 and 1,000 models: %v", name, fromTheEnd, lookups) + } + } +} diff --git a/ir/provenance.go b/ir/provenance.go index 2b0758fbb..c65c5f32b 100644 --- a/ir/provenance.go +++ b/ir/provenance.go @@ -64,12 +64,12 @@ type Provenance struct { Inferred Inferred `json:"inferred,omitempty"` } -// InTable reports whether p.Source addresses one of a source table's n entries, -// or is NoSource, the one value outside every table the IR declares. It is the -// test each holder of a table applies to what indexes it, so none reads the -// sentinel apart from the others. -func (p Provenance) InTable(n int) bool { - return p.Source == NoSource || 0 <= p.Source && p.Source < n +// InTable reports whether p.Source addresses one of a source table's count +// entries, or is NoSource, the one value outside every table the IR declares. +// It is the test each holder of a table applies to what indexes it, so none +// reads the sentinel apart from the others. +func (p Provenance) InTable(count int) bool { + return p.Source == NoSource || 0 <= p.Source && p.Source < count } // Position is a 1-based line and column inside a source. The zero value is no @@ -151,9 +151,9 @@ type RelatedRole string // The roles of a related entry. const ( - // RelatedKept is the place whose say the finding kept over the one it + // RelatedChosen is the place whose say the finding chose over the one it // sits at. - RelatedKept RelatedRole = "kept" + RelatedChosen RelatedRole = "chosen" // RelatedDecided is a node the finding decided, named by its // Provenance.Node: every one of them, where a finding said once speaks // for several. @@ -163,7 +163,7 @@ const ( // RelatedRoles returns every RelatedRole declared above, in the order a // finding lists its entries by. func RelatedRoles() []RelatedRole { - return []RelatedRole{RelatedKept, RelatedDecided} + return []RelatedRole{RelatedChosen, RelatedDecided} } // Valid reports whether r is one of the roles declared above. @@ -237,11 +237,11 @@ func HasError(diags []Diagnostic) bool { } // FirstOutsideTable returns the first diagnostic in diags whose provenance -// indexes none of a source table's n entries (Provenance.InTable) and true, or -// the zero Diagnostic and false if each indexes one. A holder of a table asks -// it of the findings that will be read against the table. -func FirstOutsideTable(diags []Diagnostic, n int) (Diagnostic, bool) { - i := slices.IndexFunc(diags, func(diagnostic Diagnostic) bool { return !diagnostic.Provenance.InTable(n) }) +// indexes none of a source table's count entries (Provenance.InTable) and true, +// or the zero Diagnostic and false if each indexes one. A holder of a table +// asks it of the findings that will be read against the table. +func FirstOutsideTable(diags []Diagnostic, count int) (Diagnostic, bool) { + i := slices.IndexFunc(diags, func(diagnostic Diagnostic) bool { return !diagnostic.Provenance.InTable(count) }) if i < 0 { return Diagnostic{}, false } diff --git a/ir/provenance_test.go b/ir/provenance_test.go index 29ab37a4a..7c4f9400e 100644 --- a/ir/provenance_test.go +++ b/ir/provenance_test.go @@ -402,7 +402,7 @@ func TestSourceInfo_IsOverlayReadsTheFormatTag(t *testing.T) { func relatedDiagnostic() ir.Diagnostic { diagnostic := ir.NewDiagnostic(ir.SeverityWarning, "x/conflict", "m", ir.Provenance{Pointer: "/a"}) diagnostic.Related = []ir.Related{ - {Role: ir.RelatedKept, Provenance: ir.Provenance{Pointer: "/b", WrittenBy: 1, Position: ir.Position{Line: 2, Column: 3}}}, + {Role: ir.RelatedChosen, Provenance: ir.Provenance{Pointer: "/b", WrittenBy: 1, Position: ir.Position{Line: 2, Column: 3}}}, {Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/m"}}, {Role: ir.RelatedDecided, Provenance: ir.Provenance{Source: ir.NoSource, Node: "property/x/n", Inferred: "h"}}, } @@ -417,7 +417,7 @@ func TestDiagnostic_RelatedRoundTripsAndIsAbsentWhenEmpty(t *testing.T) { want := relatedDiagnostic() encoded, err := json.Marshal(want, json.Deterministic(true)) require.NoError(t, err) - assert.Contains(t, string(encoded), `"related":[{"role":"kept","provenance":{"source":0,"pointer":"/b","writtenBy":1,`) + assert.Contains(t, string(encoded), `"related":[{"role":"chosen","provenance":{"source":0,"pointer":"/b","writtenBy":1,`) var back ir.Diagnostic require.NoError(t, json.Unmarshal(encoded, &back)) assert.Equal(t, want, back) @@ -434,7 +434,7 @@ func TestDiagnostic_RelatedRoundTripsAndIsAbsentWhenEmpty(t *testing.T) { // on, in the order a finding lists its entries by. func TestRelatedRole_ValidHoldsTheDeclaredRoles(t *testing.T) { t.Parallel() - assert.Equal(t, []ir.RelatedRole{ir.RelatedKept, ir.RelatedDecided}, ir.RelatedRoles()) + assert.Equal(t, []ir.RelatedRole{ir.RelatedChosen, ir.RelatedDecided}, ir.RelatedRoles()) for _, role := range ir.RelatedRoles() { assert.True(t, role.Valid(), "%q", role) } diff --git a/ir/references.go b/ir/references.go index e3bc3420e..682e60846 100644 --- a/ir/references.go +++ b/ir/references.go @@ -83,8 +83,8 @@ func NewIDReferences(doc *Document) *IDReferences { return idReferences } -// Visit records the identity v declares, if any, and keeps v if it is a -// reference that may not resolve, asking for v's children either way. +// Visit records the identity value declares, if any, and keeps value if it is a +// reference that may not resolve, asking for value's children either way. // // A reference resolving as the walk reaches it, in a map-keyed registry or to // an identity already declared, is not kept. A map-keyed node's own ID is its @@ -92,22 +92,22 @@ func NewIDReferences(doc *Document) *IDReferences { // path unspelled, since a declared class's registry is complete only once the // walk is over. An empty ID is no reference: some positions spell "none" with // one (Discriminator.Default). -func (r *IDReferences) Visit(v reflect.Value, at WalkPath) bool { - switch v.Kind() { +func (r *IDReferences) Visit(value reflect.Value, at WalkPath) bool { + switch value.Kind() { case reflect.Struct: - r.declare(v) + r.declare(value) case reflect.String: - r.refer(v, at) + r.refer(value, at) default: // no other kind is a reference or declares an identity } return true } -// declare records the identity struct v declares, if any, unless a Document map -// keys its class: those resolve against the map, whatever a node declares. -func (r *IDReferences) declare(v reflect.Value) { - class, id, declares := r.ids.DeclaredIDOf(v) +// declare records the identity struct value declares, if any, unless a Document +// map keys its class: those resolve against the map, whatever a node declares. +func (r *IDReferences) declare(value reflect.Value) { + class, id, declares := r.ids.DeclaredIDOf(value) if !declares || id == "" { return } @@ -122,14 +122,14 @@ func (r *IDReferences) declare(v reflect.Value) { ids[id] = true } -// refer keeps string v, reached at at, if it is a reference that may not +// refer keeps string value, reached at path, if it is a reference that may not // resolve. -func (r *IDReferences) refer(v reflect.Value, at WalkPath) { - id := v.String() +func (r *IDReferences) refer(value reflect.Value, path WalkPath) { + id := value.String() if id == "" { return } - t := v.Type() + t := value.Type() if _, isRef := r.labels[t]; !isRef { return } @@ -140,11 +140,11 @@ func (r *IDReferences) refer(v reflect.Value, at WalkPath) { if ids[id] { return } - if _, name, ok := at.Field(); keyed && ok && name == ownIDField { + if _, name, ok := path.Field(); keyed && ok && name == ownIDField { return } r.sites = append(r.sites, IDReference{Class: t, ID: id}) - r.paths.Record(at) + r.paths.Record(path) } // Unresolved returns, in walk order, the references the walk reached that @@ -224,11 +224,11 @@ func keyedRegistries() []keyedRegistry { var regs []keyedRegistry doc := reflect.TypeFor[Document]() for i := range doc.NumField() { - f := doc.Field(i) - if f.Type.Kind() != reflect.Map || !namedString(f.Type.Key()) { + field := doc.Field(i) + if field.Type.Kind() != reflect.Map || !namedString(field.Type.Key()) { continue } - regs = append(regs, keyedRegistry{index: i, class: f.Type.Key(), label: strings.ToLower(f.Name)}) + regs = append(regs, keyedRegistry{index: i, class: field.Type.Key(), label: strings.ToLower(field.Name)}) } return regs } @@ -241,10 +241,10 @@ func registryKeys(doc *Document, index int) map[string]bool { if doc == nil { return nil } - m := reflect.ValueOf(doc).Elem().Field(index) - ids := make(map[string]bool, m.Len()) - key := reflect.New(m.Type().Key()).Elem() - for entries := m.MapRange(); entries.Next(); { + member := reflect.ValueOf(doc).Elem().Field(index) + ids := make(map[string]bool, member.Len()) + key := reflect.New(member.Type().Key()).Elem() + for entries := member.MapRange(); entries.Next(); { key.SetIterKey(entries) ids[key.String()] = true } diff --git a/ir/steps_limit_test.go b/ir/steps_limit_test.go index 3044fc421..6b34c9faa 100644 --- a/ir/steps_limit_test.go +++ b/ir/steps_limit_test.go @@ -93,12 +93,12 @@ func TestForEachOperation_ChargesOperationsAndGroups(t *testing.T) { // taking the level below twice as arguments, so it holds 2^(depth+1)-1 // constructors and yields as many edges. func constructorFork(depth int) *ir.Literal { - constructorValue := &ir.ConstructorValue{Scalar: "type/s"} + constructor := &ir.ConstructorValue{Scalar: "type/s"} for range depth { - cv := ir.Value{Kind: ir.ValueConstructor, Constructor: constructorValue} - constructorValue = &ir.ConstructorValue{Scalar: "type/s", Args: []ir.Value{cv, cv}} + cv := ir.Value{Kind: ir.ValueConstructor, Constructor: constructor} + constructor = &ir.ConstructorValue{Scalar: "type/s", Args: []ir.Value{cv, cv}} } - lit := &ir.Literal{Value: ir.Value{Kind: ir.ValueConstructor, Constructor: constructorValue}} + lit := &ir.Literal{Value: ir.Value{Kind: ir.ValueConstructor, Constructor: constructor}} lit.ID = "type/x/L" return lit } diff --git a/ir/tags_test.go b/ir/tags_test.go index 00dfb788b..c5e3f9fc5 100644 --- a/ir/tags_test.go +++ b/ir/tags_test.go @@ -49,9 +49,9 @@ func reachableStructs(t *testing.T) []reflect.Type { t.Helper() queue := []reflect.Type{reflect.TypeFor[ir.Document]()} for _, typeKind := range allKinds { - td, ok := ir.NewTypeDef(typeKind) + typeDef, ok := ir.NewTypeDef(typeKind) require.True(t, ok, "NewTypeDef(%s)", typeKind) - queue = append(queue, reflect.TypeOf(td)) + queue = append(queue, reflect.TypeOf(typeDef)) } seen := map[reflect.Type]bool{} var out []reflect.Type diff --git a/ir/testdata/shape.golden.txt b/ir/testdata/shape.golden.txt index a57b2c6a0..acd56b72f 100644 --- a/ir/testdata/shape.golden.txt +++ b/ir/testdata/shape.golden.txt @@ -150,6 +150,7 @@ type Diagnostic struct "severity" Severity type Discriminator struct + "decodeOnlyRoutes" map[string]TypeID omitempty "default" TypeID omitempty "envelope" string omitempty "envelopeValueName" string omitempty @@ -215,6 +216,7 @@ type EntityRef struct type Enum struct embed TypeCommon "closed" bool + "constraints" *Constraints omitzero "fallbackMember" string omitempty "flags" bool "members" []EnumMember omitempty @@ -745,8 +747,8 @@ type Related struct "role" RelatedRole type RelatedRole string + const "chosen" const "decided" - const "kept" type Reply struct "address" *PropertyPath omitzero diff --git a/ir/traverse.go b/ir/traverse.go index 34b709881..abca3757a 100644 --- a/ir/traverse.go +++ b/ir/traverse.go @@ -20,17 +20,17 @@ const MaxWalkSteps = MaxWalkValues / 8 // stepLimit is what a typed walk may still take of its limit, and whether it // met the end of it with more to read. type stepLimit struct { - left int - cut bool + stepsLeft int + cut bool } // take takes one step if one is left, and otherwise records the cut. func (s *stepLimit) take() bool { - if s.left <= 0 { + if s.stepsLeft <= 0 { s.cut = true return false } - s.left-- + s.stepsLeft-- return true } @@ -80,11 +80,11 @@ func groupsWithin(limit int, doc *Document, fn func(OperationGroup, *stepLimit)) if doc == nil { return false } - groupWalkValue := groupWalk{steps: stepLimit{left: limit}, fn: fn} + groupWalk := groupWalk{steps: stepLimit{stepsLeft: limit}, fn: fn} for _, svc := range doc.Services { - groupWalkValue.groups(svc.Groups, 0) + groupWalk.groups(svc.Groups, 0) } - return groupWalkValue.steps.cut + return groupWalk.steps.cut } // groupWalk is one walk of a document's groups: the steps it may still take, diff --git a/ir/typedef.go b/ir/typedef.go index c55fa6a1c..514394664 100644 --- a/ir/typedef.go +++ b/ir/typedef.go @@ -43,18 +43,18 @@ type TypeDef interface { Common() *TypeCommon } -// IsNilTypeDef reports whether td is a nil TypeDef — an untyped nil interface or -// a typed nil pointer. +// IsNilTypeDef reports whether typeDef is a nil TypeDef — an untyped nil +// interface or a typed nil pointer. // // A typed nil satisfies a type switch case and a comma-ok assertion alike, so // matching a kind is no evidence the value is safe to dereference; // [TypeDef.Kind] and [TypeDef.Common] both panic on one. Every walk over a type // registry screens entries through this before reading them. -func IsNilTypeDef(td TypeDef) bool { - if td == nil { +func IsNilTypeDef(typeDef TypeDef) bool { + if typeDef == nil { return true } - rv := reflect.ValueOf(td) + rv := reflect.ValueOf(typeDef) return rv.Kind() == reflect.Pointer && rv.IsNil() } diff --git a/ir/typedef_completeness_test.go b/ir/typedef_completeness_test.go index 164d3962a..ce8a9da0f 100644 --- a/ir/typedef_completeness_test.go +++ b/ir/typedef_completeness_test.go @@ -30,14 +30,14 @@ func TestTypeDef_EveryDeclaredKindIsRegistered(t *testing.T) { t.Parallel() byConcrete := map[string]string{} for _, kc := range declaredTypeKinds(t) { - td, ok := ir.NewTypeDef(kc.kind) + typeDef, ok := ir.NewTypeDef(kc.kind) require.True(t, ok, "ir.%s (%q) has no newTypeDefByKind entry: NewTypeDef "+ "cannot build it, so TypeRegistry can never decode it", kc.name, kc.kind) - assert.Equal(t, kc.kind, td.Kind(), + assert.Equal(t, kc.kind, typeDef.Kind(), "ir.%s (%q) is registered to a type whose Kind() disagrees", kc.name, kc.kind) - assert.NotNil(t, td.Common(), "ir.%s (%q) must embed a TypeCommon", kc.name, kc.kind) + assert.NotNil(t, typeDef.Common(), "ir.%s (%q) must embed a TypeCommon", kc.name, kc.kind) - name := concreteName(t, td) + name := concreteName(t, typeDef) assert.NotContains(t, byConcrete, name, "ir.%s and ir.%s are both registered to ir.%s: one concrete struct per kind", kc.name, byConcrete[name], name) @@ -57,14 +57,14 @@ func TestTypeDef_EveryDeclaredKindTagsItsJSON(t *testing.T) { for _, kc := range declaredTypeKinds(t) { t.Run(string(kc.kind), func(t *testing.T) { t.Parallel() - td, ok := ir.NewTypeDef(kc.kind) + typeDef, ok := ir.NewTypeDef(kc.kind) require.True(t, ok, "ir.%s (%q) has no newTypeDefByKind entry", kc.name, kc.kind) - raw, err := json.Marshal(ir.TypeRegistry{id: td}) + raw, err := json.Marshal(ir.TypeRegistry{id: typeDef}) require.NoError(t, err) assert.Contains(t, string(raw), `"kind":"`+string(kc.kind)+`"`, "ir.%s (%q) marshals without its adjacent kind tag: give %T a MarshalJSONTo "+ - "calling marshalKinded, the way every other kind does (json.go)", kc.name, kc.kind, td) + "calling marshalKinded, the way every other kind does (json.go)", kc.name, kc.kind, typeDef) var back ir.TypeRegistry require.NoError(t, json.Unmarshal(raw, &back), @@ -88,9 +88,9 @@ func TestTypeDef_EverySealedImplementationHasAKind(t *testing.T) { kinds := declaredTypeKinds(t) registered := make([]string, 0, len(kinds)) for _, kc := range kinds { - td, ok := ir.NewTypeDef(kc.kind) + typeDef, ok := ir.NewTypeDef(kc.kind) require.True(t, ok, "ir.%s (%q) has no newTypeDefByKind entry", kc.name, kc.kind) - registered = append(registered, concreteName(t, td)) + registered = append(registered, concreteName(t, typeDef)) } slices.Sort(registered) @@ -101,13 +101,13 @@ func TestTypeDef_EverySealedImplementationHasAKind(t *testing.T) { // TestTypeDef_HandWrittenConcreteListIsComplete guards allConcreteTypeDefs // (typedef_test.go), the one hand-written list naming the sum's members as -// concrete types. The kind lists below cannot stand in for it: a variant absent +// concrete types. The kind lists below cannot take its place: a variant absent // from every list is absent from nothing they compare against each other. func TestTypeDef_HandWrittenConcreteListIsComplete(t *testing.T) { t.Parallel() listed := make([]string, 0, len(allConcreteTypeDefs)) - for _, td := range allConcreteTypeDefs { - listed = append(listed, concreteName(t, td)) + for _, typeDef := range allConcreteTypeDefs { + listed = append(listed, concreteName(t, typeDef)) } slices.Sort(listed) @@ -155,8 +155,8 @@ func sampleDocumentKinds(t *testing.T) []ir.TypeKind { t.Helper() registry := sampleDocument(t).Types out := make([]ir.TypeKind, 0, len(registry)) - for _, td := range registry { - out = append(out, td.Kind()) + for _, typeDef := range registry { + out = append(out, typeDef.Kind()) } return out } @@ -166,7 +166,7 @@ func zeroShapeKinds() []ir.TypeKind { tests := typeDefZeroShapeTests() out := make([]ir.TypeKind, 0, len(tests)) for _, tt := range tests { - out = append(out, tt.td.Kind()) + out = append(out, tt.typeDef.Kind()) } return out } @@ -184,9 +184,9 @@ func declaredKindValues(t *testing.T) []string { } // concreteName returns the struct name behind a TypeDef pointer. -func concreteName(t *testing.T, td ir.TypeDef) string { +func concreteName(t *testing.T, typeDef ir.TypeDef) string { t.Helper() - rt := reflect.TypeOf(td) + rt := reflect.TypeOf(typeDef) require.Equal(t, reflect.Pointer, rt.Kind(), "NewTypeDef must return a pointer, got %s", rt) return rt.Elem().Name() } diff --git a/ir/typedef_internal_test.go b/ir/typedef_internal_test.go index 43075c702..95d552586 100644 --- a/ir/typedef_internal_test.go +++ b/ir/typedef_internal_test.go @@ -23,13 +23,13 @@ func TestTypeDef_MarkerMethods(t *testing.T) { &External{}, &Any{}, } - for _, td := range defs { - t.Run(string(td.Kind()), func(t *testing.T) { + for _, typeDef := range defs { + t.Run(string(typeDef.Kind()), func(t *testing.T) { t.Parallel() // typeDef is the unexported sealing marker on the TypeDef interface; // invoking it keeps the sealed-sum contract observable. The bodies are // empty (zero statements), so this documents rather than covers them. - td.typeDef() + typeDef.typeDef() }) } } diff --git a/ir/typedef_test.go b/ir/typedef_test.go index e39e98774..a2bb1a216 100644 --- a/ir/typedef_test.go +++ b/ir/typedef_test.go @@ -26,10 +26,10 @@ func TestTypeDef_KindDispatchIsComplete(t *testing.T) { for _, typeKind := range allKinds { t.Run(string(typeKind), func(t *testing.T) { t.Parallel() - td, ok := ir.NewTypeDef(typeKind) + typeDef, ok := ir.NewTypeDef(typeKind) require.True(t, ok, "no concrete type registered for kind %q", typeKind) - assert.Equal(t, typeKind, td.Kind()) - require.NotNil(t, td.Common()) + assert.Equal(t, typeKind, typeDef.Kind()) + require.NotNil(t, typeDef.Common()) }) } } @@ -52,8 +52,8 @@ var allConcreteTypeDefs = []ir.TypeDef{ func TestTypeDef_ConcreteTypesImplementInterface(t *testing.T) { t.Parallel() - for _, td := range allConcreteTypeDefs { - assert.Contains(t, allKinds, td.Kind()) + for _, typeDef := range allConcreteTypeDefs { + assert.Contains(t, allKinds, typeDef.Kind()) } } @@ -65,8 +65,8 @@ func TestIsNilTypeDef_ScreensBothSpellingsOfNil(t *testing.T) { t.Parallel() assert.True(t, ir.IsNilTypeDef(nil), "an untyped nil interface holds no definition") assert.True(t, ir.IsNilTypeDef((*ir.Model)(nil)), "a typed nil pointer holds none either") - for _, td := range allConcreteTypeDefs { - assert.False(t, ir.IsNilTypeDef(td), "%T is a live definition", td) + for _, typeDef := range allConcreteTypeDefs { + assert.False(t, ir.IsNilTypeDef(typeDef), "%T is a live definition", typeDef) } } @@ -134,7 +134,7 @@ func TestTypeDef_ZeroValueShapeWithKindTag(t *testing.T) { for _, tt := range typeDefZeroShapeTests() { t.Run(tt.name, func(t *testing.T) { t.Parallel() - raw, err := json.Marshal(tt.td) + raw, err := json.Marshal(tt.typeDef) require.NoError(t, err) assert.Equal(t, tt.want, string(raw)) }) @@ -156,10 +156,10 @@ func TestTypeDef_CommonIsAnAliasNotACopy(t *testing.T) { for _, typeKind := range allKinds { t.Run(string(typeKind), func(t *testing.T) { t.Parallel() - td, ok := ir.NewTypeDef(typeKind) + typeDef, ok := ir.NewTypeDef(typeKind) require.True(t, ok, "no concrete type registered for kind %q", typeKind) - td.Common().ID = "type/y" - raw, err := json.Marshal(td) + typeDef.Common().ID = "type/y" + raw, err := json.Marshal(typeDef) require.NoError(t, err) assert.Contains(t, string(raw), `"id":"type/y"`) }) diff --git a/ir/types.go b/ir/types.go index fe9f1eb72..fa333833f 100644 --- a/ir/types.go +++ b/ir/types.go @@ -273,8 +273,10 @@ type Model struct { ExtensionRanges []WireIDRange `json:"extensionRanges,omitempty"` // Discriminator is set on the polymorphic base. Discriminator *Discriminator `json:"discriminator,omitzero"` - // DiscriminatorValue is set on each subtype one tag routes to: that wire tag - // value (docs/ir/models.md#discriminator). + // DiscriminatorValue is set on each subtype one tag names: the key a + // discriminator on one of its ancestors routes it by, which an encoder + // writes only through that discriminator. It routes nothing itself + // (docs/ir/models.md#discriminator). DiscriminatorValue string `json:"discriminatorValue,omitempty"` // InputOnly marks GraphQL input types, which have distinct identity from // output types. @@ -332,9 +334,16 @@ type Discriminator struct { // Mapping maps a wire value to the type it routes to, a union's variant or // a hierarchy's base or subtype, and no value is empty. Nil on a union, it // routes by type name; otherwise it holds the routes declared or inferred - // and the one the source implies to each variant they leave out. In a model - // hierarchy, each subtype's DiscriminatorValue routes to it too. + // and the one the source implies to each variant they leave out. On a + // model it is the whole route table. An encoder picks the tag from the + // Mapping of the discriminator it writes for. Mapping map[string]TypeID `json:"mapping,omitempty"` + // DecodeOnlyRoutes maps a wire value to the type a payload carrying it + // routes to, for each route the source gives that Mapping leaves out, + // which an encoder never writes. A decoder routes by Mapping, then + // DecodeOnlyRoutes, then recognition, then Default + // (docs/ir/models.md#discriminator). Nil and empty both mean none. + DecodeOnlyRoutes map[string]TypeID `json:"decodeOnlyRoutes,omitempty"` // Default is the variant to use when the tag is absent/unrecognized (OpenAPI // 3.2 defaultMapping); zero = none. Default TypeID `json:"default,omitempty"` @@ -442,6 +451,10 @@ type Enum struct { // FallbackMember is the wire name of the member to substitute for an unknown // value (Avro enum default symbol); "" = none. FallbackMember string `json:"fallbackMember,omitempty"` + // Constraints are the bounds the enum's schema writes of the kind its + // ValueType holds, closed or open (docs/ir/enums.md#bounds); nil = none + // written. + Constraints *Constraints `json:"constraints,omitzero"` } // EnumMember is one member of an Enum (docs/ir/enums.md). diff --git a/ir/types_test.go b/ir/types_test.go index 565418ab0..0ee327a71 100644 --- a/ir/types_test.go +++ b/ir/types_test.go @@ -5,6 +5,7 @@ package ir_test import ( "maps" + "reflect" "slices" "testing" @@ -19,69 +20,69 @@ import ( // followed by TypeCommon's shared fields and then its own fields in // declaration order (json.go's kinded wrapper). func typeDefZeroShapeTests() []struct { - name string - td ir.TypeDef - want string + name string + typeDef ir.TypeDef + want string } { return []struct { - name string - td ir.TypeDef - want string + name string + typeDef ir.TypeDef + want string }{ { - name: "primitive", - td: &ir.Primitive{}, - want: `{"kind":"primitive","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"primitiveKind":""}`, + name: "primitive", + typeDef: &ir.Primitive{}, + want: `{"kind":"primitive","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"primitiveKind":""}`, }, { - name: "scalar", - td: &ir.Scalar{}, - want: `{"kind":"scalar","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0}}`, + name: "scalar", + typeDef: &ir.Scalar{}, + want: `{"kind":"scalar","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0}}`, }, { - name: "model", - td: &ir.Model{}, - want: `{"kind":"model","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"abstract":false,"positional":false,"inputOnly":false}`, + name: "model", + typeDef: &ir.Model{}, + want: `{"kind":"model","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"abstract":false,"positional":false,"inputOnly":false}`, }, { - name: "union", - td: &ir.Union{}, - want: `{"kind":"union","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"exclusive":false,"wireTagged":false,"closed":false,"inputOnly":false}`, + name: "union", + typeDef: &ir.Union{}, + want: `{"kind":"union","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"exclusive":false,"wireTagged":false,"closed":false,"inputOnly":false}`, }, { - name: "enum", - td: &ir.Enum{}, - want: `{"kind":"enum","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"valueType":"","closed":false,"flags":false}`, + name: "enum", + typeDef: &ir.Enum{}, + want: `{"kind":"enum","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"valueType":"","closed":false,"flags":false}`, }, { - name: "list", - td: &ir.List{}, - want: `{"kind":"list","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"elementType":{"target":"","nullable":false}}`, + name: "list", + typeDef: &ir.List{}, + want: `{"kind":"list","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"elementType":{"target":"","nullable":false}}`, }, { - name: "map", - td: &ir.MapT{}, - want: `{"kind":"map","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"value":{"target":"","nullable":false}}`, + name: "map", + typeDef: &ir.MapT{}, + want: `{"kind":"map","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"value":{"target":"","nullable":false}}`, }, { - name: "tuple", - td: &ir.Tuple{}, - want: `{"kind":"tuple","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0}}`, + name: "tuple", + typeDef: &ir.Tuple{}, + want: `{"kind":"tuple","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0}}`, }, { - name: "literal", - td: &ir.Literal{}, - want: `{"kind":"literal","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"value":{"kind":""}}`, + name: "literal", + typeDef: &ir.Literal{}, + want: `{"kind":"literal","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"value":{"kind":""}}`, }, { - name: "external", - td: &ir.External{}, - want: `{"kind":"external","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"identity":""}`, + name: "external", + typeDef: &ir.External{}, + want: `{"kind":"external","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0},"identity":""}`, }, { - name: "any", - td: &ir.Any{}, - want: `{"kind":"any","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0}}`, + name: "any", + typeDef: &ir.Any{}, + want: `{"kind":"any","id":"","name":{},"anonymous":false,"docs":{},"sensitive":false,"provenance":{"source":0}}`, }, } } @@ -136,8 +137,9 @@ func TestModel_PopulatedRoundTrip(t *testing.T) { Positional: true, ExtensionRanges: []ir.WireIDRange{{From: 100, To: 199}}, Discriminator: &ir.Discriminator{ - Property: "property/kind", - Mapping: map[string]ir.TypeID{"dog": "type/Dog", "cat": "type/Cat"}, + Property: "property/kind", + Mapping: map[string]ir.TypeID{"dog": "type/Dog", "cat": "type/Cat"}, + DecodeOnlyRoutes: map[string]ir.TypeID{"Dog": "type/Dog"}, }, DiscriminatorValue: "user", InputOnly: true, @@ -160,8 +162,9 @@ func TestUnion_PopulatedRoundTrip(t *testing.T) { Closed: true, InputOnly: true, Discriminator: &ir.Discriminator{ - PropertyName: "petType", - Mapping: map[string]ir.TypeID{"dog": "type/Dog"}, + PropertyName: "petType", + Mapping: map[string]ir.TypeID{"dog": "type/Dog"}, + DecodeOnlyRoutes: map[string]ir.TypeID{"Dog": "type/Dog"}, }, Constraints: &ir.Constraints{MinProperties: new(int64(1))}, } @@ -181,10 +184,50 @@ func TestEnum_PopulatedRoundTrip(t *testing.T) { Closed: true, Flags: true, FallbackMember: "UNKNOWN", + Constraints: &ir.Constraints{MinLength: new(int64(1)), MaxLength: new(int64(8)), Pattern: "^[a-z]+$"}, } assertTypeDefRoundTrip(t, want) } +// TestEnum_ConstraintsJSONContract pins the field's encoding: an enum whose +// schema writes no bound omits it, and a present but empty Constraints is kept, +// since it is not the same enum as none. +func TestEnum_ConstraintsJSONContract(t *testing.T) { + t.Parallel() + none := assertDeterministicMarshal(t, ir.Enum{ValueType: ir.PrimitiveString}) + assert.NotContains(t, none, "constraints", "an enum with no bounds omits the field") + + empty := assertDeterministicMarshal(t, ir.Enum{ValueType: ir.PrimitiveString, Constraints: &ir.Constraints{}}) + assert.Contains(t, empty, `"constraints":{"uniqueItems":false}`, "an empty Constraints is kept") + assertTypeDefRoundTrip(t, &ir.Enum{ + TypeCommon: populatedTypeCommon("type/enum/Empty"), + ValueType: ir.PrimitiveString, + Members: []ir.EnumMember{{Name: ir.Naming{Source: "A"}, Value: ir.Value{Kind: ir.ValueString, String: "a"}}}, + Closed: true, + Flags: true, + FallbackMember: "A", + Constraints: &ir.Constraints{}, + }) +} + +// TestEnum_ConstraintsReachTheWalks holds that a walk over a document meets an +// enum's Constraints as it meets a scalar's: a bound the document holds there +// is reached by WalkValues, which is how every check of a bound finds it. +func TestEnum_ConstraintsReachTheWalks(t *testing.T) { + t.Parallel() + doc := &ir.Document{Types: ir.TypeRegistry{"type/e": &ir.Enum{ + ID: "type/e", + ValueType: ir.PrimitiveInt32, + Constraints: &ir.Constraints{Min: new(ir.BigVal("1"))}, + }}} + var seen []string + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(_ reflect.Value, at ir.WalkPath) bool { + seen = append(seen, at.String()) + return true + })) + assert.Contains(t, seen, `document.Types[type/e].Constraints.Min`) +} + // TestList_PopulatedRoundTrip pins that a fully populated List round-trips. func TestList_PopulatedRoundTrip(t *testing.T) { t.Parallel() @@ -291,7 +334,7 @@ var primitiveKindSpellings = map[ir.PrimitiveKind]string{ // TestPrimitiveKind_Constants pins the on-disk spelling of every PrimitiveKind // value. These strings are the primitive-scalar vocabulary written into every -// golden IR snapshot; a typo fix later would be a silent breaking change. +// golden IR snapshot; a typo fix later would be an unannounced breaking change. func TestPrimitiveKind_Constants(t *testing.T) { t.Parallel() assertConstantSpellings(t, primitiveKindSpellings, "unspecified") @@ -446,8 +489,8 @@ func TestPrimitiveKind_LongestDomainChainFitsTheCap(t *testing.T) { longest = func(primitiveKind ir.PrimitiveKind, depth int) int { require.LessOrEqual(t, int64(depth), limit, "a chain past maxDomainDepth: a cycle or a cap too low") best := 0 - for _, primitiveKindValue := range primitiveKind.DomainParents() { - best = max(best, 1+longest(primitiveKindValue, depth+1)) + for _, primitiveKind := range primitiveKind.DomainParents() { + best = max(best, 1+longest(primitiveKind, depth+1)) } return best } @@ -516,6 +559,7 @@ func TestDiscriminator_JSONContract(t *testing.T) { PropertyName: "kind", TupleElementIndex: new(0), Mapping: map[string]ir.TypeID{"dog": "type/Dog", "cat": "type/Cat"}, + DecodeOnlyRoutes: map[string]ir.TypeID{"Dog": "type/Dog"}, Default: "type/Unknown", Envelope: "object", EnvelopeValueName: "value", diff --git a/ir/walk.go b/ir/walk.go index 7341c0c33..22b281bd2 100644 --- a/ir/walk.go +++ b/ir/walk.go @@ -60,8 +60,8 @@ type Visitor interface { type VisitFunc func(v reflect.Value, at WalkPath) bool // Visit calls f. -func (f VisitFunc) Visit(v reflect.Value, at WalkPath) bool { - return f != nil && f(v, at) +func (f VisitFunc) Visit(value reflect.Value, at WalkPath) bool { + return f != nil && f(value, at) } // CycleVisitor is a [Visitor] that is also told where its walk meets a pointer, @@ -116,12 +116,12 @@ type walkEnd struct { // them, showing each at most limit values, and asking ask whether to stop as // WalkValuesContext says, or never for a nil ask. func walkValues(ask func() error, limit int, root any, path string, visitors []Visitor) walkEnd { - v := reflect.ValueOf(root) + rootValue := reflect.ValueOf(root) var out walkEnd for group := range slices.Chunk(visitors, maxSharedVisitors) { valueWalk := newValueWalk(path, group) valueWalk.ask, valueWalk.limit = ask, limit - valueWalk.walk(v, 0, valueWalk.all) + valueWalk.walk(rootValue, 0, valueWalk.all) out.truncated = out.truncated || valueWalk.truncated if valueWalk.refusal != nil { out.err = valueWalk.refusal @@ -164,17 +164,17 @@ func (p WalkPath) String() string { return string(p.AppendTo(buf[:0])) } -// AppendTo appends the rendered path to b and returns the extended buffer, so a -// caller can look a path up without allocating one. -func (p WalkPath) AppendTo(b []byte) []byte { +// AppendTo appends the rendered path to buffer and returns the extended buffer, +// so a caller can look a path up without allocating one. +func (p WalkPath) AppendTo(buffer []byte) []byte { if p.walk == nil { - return b + return buffer } - b = append(b, p.walk.root...) + buffer = append(buffer, p.walk.root...) for _, pathStep := range p.walk.steps[:p.depth] { - b = pathStep.appendTo(b) + buffer = pathStep.appendTo(buffer) } - return b + return buffer } // Field reports the struct field the path ends in, as String spells it: the @@ -214,10 +214,10 @@ func (p WalkPath) IsMapKey() bool { type stepKind uint8 const ( - stepField stepKind = iota // a struct field - stepElement // a slice or array element - stepMapKey // a map entry's key - stepMapValue // a map entry's value + stepField stepKind = iota // a struct field + stepElement // a slice or array element + stepMapKey // a map entry's key + stepMap // a map entry's value ) // pathStep is one step of a walk's path, held as what it was taken through @@ -234,23 +234,24 @@ type pathStep struct { form keyForm } -// appendTo renders the step onto b. A field read through an embedded struct is -// promoted by Go and inlined by JSON, so the embedded field itself renders -// nothing: "….TypeCommon.Examples[0]" would name a step neither encoding has. -func (s pathStep) appendTo(b []byte) []byte { +// appendTo renders the step onto buffer. A field read through an embedded +// struct is promoted by Go and inlined by JSON, so the embedded field itself +// renders nothing: "….TypeCommon.Examples[0]" would name a step neither +// encoding has. +func (s pathStep) appendTo(buffer []byte) []byte { switch s.kind { case stepField: - if f := s.owner.Field(int(s.n)); !f.Anonymous { - b = append(append(b, '.'), f.Name...) + if field := s.owner.Field(int(s.n)); !field.Anonymous { + buffer = append(append(buffer, '.'), field.Name...) } case stepElement: - b = append(strconv.AppendUint(append(b, '['), s.n, 10), ']') + buffer = append(strconv.AppendUint(append(buffer, '['), s.n, 10), ']') case stepMapKey: - b = append(append(appendKey(append(b, '['), s.form, s.n, s.label), ']'), MapKeySuffix...) - case stepMapValue: - b = append(appendKey(append(b, '['), s.form, s.n, s.label), ']') + buffer = append(append(appendKey(append(buffer, '['), s.form, s.n, s.label), ']'), MapKeySuffix...) + case stepMap: + buffer = append(appendKey(append(buffer, '['), s.form, s.n, s.label), ']') } - return b + return buffer } // embedded reports whether s is a step into an embedded struct, which a path @@ -311,7 +312,7 @@ type valueWalk struct { // of which there are at most maxSharedVisitors. The step stack is sized up front // so that a walk deeper than a struct or two costs no allocation per level. func newValueWalk(root string, visitors []Visitor) *valueWalk { - valueWalkValue := &valueWalk{ + valueWalk := &valueWalk{ root: root, visitors: visitors, cycles: make([]CycleVisitor, len(visitors)), @@ -321,10 +322,10 @@ func newValueWalk(root string, visitors []Visitor) *valueWalk { if visitor == nil { continue } - valueWalkValue.all |= 1 << i - valueWalkValue.cycles[i], _ = visitor.(CycleVisitor) + valueWalk.all |= 1 << i + valueWalk.cycles[i], _ = visitor.(CycleVisitor) } - return valueWalkValue + return valueWalk } // here is the path to the value the walk is at. @@ -332,13 +333,13 @@ func (w *valueWalk) here() WalkPath { return WalkPath{walk: w, depth: len(w.steps)} } -// walk shows v to the visitors in active and descends into what it holds for -// those that ask. A visitor shown its limit is shown nothing more, which cuts -// the walk short. The invalid zero Value — a nil root, a nil interface's +// walk shows value to the visitors in active and descends into what it holds +// for those that ask. A visitor shown its limit is shown nothing more, which +// cuts the walk short. The invalid zero Value — a nil root, a nil interface's // dynamic value — is not shown, so no visitor has to guard against calling // Type() on one. -func (w *valueWalk) walk(v reflect.Value, depth int, active visitorSet) { - if !v.IsValid() || w.refused() { +func (w *valueWalk) walk(value reflect.Value, depth int, active visitorSet) { + if !value.IsValid() || w.refused() { return } if active &^= w.cut; active != 0 && w.count >= w.limit { @@ -352,7 +353,7 @@ func (w *valueWalk) walk(v reflect.Value, depth int, active visitorSet) { var asking visitorSet for set := active; set != 0; set &= set - 1 { i := bits.TrailingZeros64(uint64(set)) - if w.visitors[i].Visit(v, at) { + if w.visitors[i].Visit(value, at) { asking |= 1 << i } } @@ -360,7 +361,7 @@ func (w *valueWalk) walk(v reflect.Value, depth int, active visitorSet) { return } before := w.count - w.children(v, depth, asking) + w.children(value, depth, asking) if pruning := active &^ asking; pruning != 0 && w.count > before { w.prune(pruning, w.count-before) } @@ -380,11 +381,11 @@ func (w *valueWalk) cutAt(active visitorSet) visitorSet { return active &^ w.cut } -// prune adds n, the values shown beneath a value the visitors in pruning were -// shown and pruned, to what each of them was not shown. -func (w *valueWalk) prune(pruning visitorSet, n int) { +// prune adds count, the values shown beneath a value the visitors in pruning +// were shown and pruned, to what each of them was not shown. +func (w *valueWalk) prune(pruning visitorSet, count int) { for set := pruning; set != 0; set &= set - 1 { - w.pruned[bits.TrailingZeros64(uint64(set))] += n + w.pruned[bits.TrailingZeros64(uint64(set))] += count } } @@ -403,9 +404,9 @@ func (w *valueWalk) refused() bool { return false } -// step descends into child, reached from its parent by pathStepValue. -func (w *valueWalk) step(pathStepValue pathStep, child reflect.Value, depth int, active visitorSet) { - w.steps = append(w.steps, pathStepValue) +// step descends into child, reached from its parent by pathStep. +func (w *valueWalk) step(pathStep pathStep, child reflect.Value, depth int, active visitorSet) { + w.steps = append(w.steps, pathStep) w.descend(child, depth, active) w.steps = w.steps[:len(w.steps)-1] } @@ -422,29 +423,29 @@ func (w *valueWalk) descend(child reflect.Value, depth int, active visitorSet) { w.walk(child, depth, active) } -// children descends into every child of v. It is where the walk's shape lives — -// what counts as a child of a pointer, an interface, a struct, a sequence and a -// map, and which step reaches each child. Numbers, bools, strings, funcs and -// channels have none. -func (w *valueWalk) children(v reflect.Value, depth int, active visitorSet) { - switch v.Kind() { +// children descends into every child of value. It is where the walk's shape +// lives — what counts as a child of a pointer, an interface, a struct, a +// sequence and a map, and which step reaches each child. Numbers, bools, +// strings, funcs and channels have none. +func (w *valueWalk) children(value reflect.Value, depth int, active visitorSet) { + switch value.Kind() { case reflect.Pointer: - w.pointer(v, depth, active) + w.pointer(value, depth, active) case reflect.Interface: - if !v.IsNil() { - w.descend(v.Elem(), depth+1, active) + if !value.IsNil() { + w.descend(value.Elem(), depth+1, active) } case reflect.Struct: // Indexed: ranging over v.Fields() puts the loop body on the heap for // every struct the walk enters. - t := v.Type() - for i := range v.NumField() { - w.step(pathStep{kind: stepField, owner: t, n: uint64(i)}, v.Field(i), depth+1, active) + t := value.Type() + for i := range value.NumField() { + w.step(pathStep{kind: stepField, owner: t, n: uint64(i)}, value.Field(i), depth+1, active) } case reflect.Slice, reflect.Array: - w.sequence(v, depth, active) + w.sequence(value, depth, active) case reflect.Map: - w.mapping(v, depth, active) + w.mapping(value, depth, active) } } @@ -452,16 +453,16 @@ func (w *valueWalk) children(v reflect.Value, depth int, active visitorSet) { // into a slice and a map: a value two holders share is read from each, as // root's encoding writes it at each. One met again while the walk is still // inside it closes a cycle, which closesCycle reports. -func (w *valueWalk) pointer(v reflect.Value, depth int, active visitorSet) { - if v.IsNil() { +func (w *valueWalk) pointer(value reflect.Value, depth int, active visitorSet) { + if value.IsNil() { return } - key := refKey{typ: v.Type(), ptr: v.Pointer()} + key := refKey{typ: value.Type(), ptr: value.Pointer()} if w.closesCycle(key, active) { return } w.enter(key) - w.descend(v.Elem(), depth+1, active) + w.descend(value.Elem(), depth+1, active) w.leave() } @@ -507,54 +508,54 @@ func (w *valueWalk) closesCycle(key refKey, active visitorSet) bool { // counting what the walk reaches can notice the skip going missing. // // A slice is a reference; an array is a value, with no address of its own. -func (w *valueWalk) sequence(v reflect.Value, depth int, active visitorSet) { - if v.Type().Elem().Kind() == reflect.Uint8 || v.Len() == 0 { +func (w *valueWalk) sequence(value reflect.Value, depth int, active visitorSet) { + if value.Type().Elem().Kind() == reflect.Uint8 || value.Len() == 0 { return } - if v.Kind() != reflect.Slice { - w.elements(v, depth, active) + if value.Kind() != reflect.Slice { + w.elements(value, depth, active) return } - key := refKey{typ: v.Type(), ptr: v.Pointer(), n: v.Len()} + key := refKey{typ: value.Type(), ptr: value.Pointer(), n: value.Len()} if w.closesCycle(key, active) { return } w.enter(key) - w.elements(v, depth, active) + w.elements(value, depth, active) w.leave() } // elements descends into each element of a slice or array. -func (w *valueWalk) elements(v reflect.Value, depth int, active visitorSet) { - for i := range v.Len() { - w.step(pathStep{kind: stepElement, n: uint64(i)}, v.Index(i), depth+1, active) +func (w *valueWalk) elements(value reflect.Value, depth int, active visitorSet) { + for i := range value.Len() { + w.step(pathStep{kind: stepElement, n: uint64(i)}, value.Index(i), depth+1, active) } } // mapping descends into a map's keys and values. A map is a reference. -func (w *valueWalk) mapping(v reflect.Value, depth int, active visitorSet) { - if v.Len() == 0 { +func (w *valueWalk) mapping(value reflect.Value, depth int, active visitorSet) { + if value.Len() == 0 { return } - key := refKey{typ: v.Type(), ptr: v.Pointer()} + key := refKey{typ: value.Type(), ptr: value.Pointer()} if w.closesCycle(key, active) { return } w.enter(key) - w.entries(v, depth, active) + w.entries(value, depth, active) w.leave() } // entries descends into each key and value of a map, in rendered-key order. // The entries sit on one stack the walk reuses: a map nested inside an entry // stacks its own above them and takes them off again. -func (w *valueWalk) entries(v reflect.Value, depth int, active visitorSet) { - entryFrame := w.ranging.push(v) +func (w *valueWalk) entries(value reflect.Value, depth int, active visitorSet) { + entryFrame := w.ranging.push(value) for i := entryFrame.base; i < entryFrame.end; i++ { // Indexed afresh: a nested map can move the stack while stacking its own. mapEntry := w.ranging.entries[i] w.step(pathStep{kind: stepMapKey, form: mapEntry.form, n: mapEntry.number, label: mapEntry.label}, mapEntry.key, depth+1, active) - w.step(pathStep{kind: stepMapValue, form: mapEntry.form, n: mapEntry.number, label: mapEntry.label}, mapEntry.value, depth+1, active) + w.step(pathStep{kind: stepMap, form: mapEntry.form, n: mapEntry.number, label: mapEntry.label}, mapEntry.value, depth+1, active) } w.ranging.pop(entryFrame) } diff --git a/ir/walk_cycle_test.go b/ir/walk_cycle_test.go index ab1ec8fc2..1073dde2a 100644 --- a/ir/walk_cycle_test.go +++ b/ir/walk_cycle_test.go @@ -43,9 +43,9 @@ type valueCycle struct { // and returns the cycles it was told of, in walk order, with whether the depth // cap truncated the walk. func valueCycles(root any) ([]valueCycle, bool) { - var recorderValue recorder - truncated := ir.WalkValues(root, "document", &recorderValue) - return recorderValue.cycles, truncated + var recorder recorder + truncated := ir.WalkValues(root, "document", &recorder) + return recorder.cycles, truncated } // kidTree is a struct whose slice of itself can hold the slice that holds it. @@ -77,12 +77,12 @@ func TestWalkValues_SelfContainingSliceIsNotEnteredAgain(t *testing.T) { // the third kind of reference the encoder follows. func TestWalkValues_SelfContainingMapIsNotEnteredAgain(t *testing.T) { t.Parallel() - kidMapValue := kidMap{} - kidMapValue["a"], kidMapValue["b"] = kidMapValue, kidMapValue + kidMap := kidMap{} + kidMap["a"], kidMap["b"] = kidMap, kidMap assert.Equal(t, []string{ "document", "document[a].key", "document[a]", "document[b].key", "document[b]", - }, walkBounded(kidMapValue)) + }, walkBounded(kidMap)) } // TestWalkValues_ASliceReachedTwiceIsWalkedFromEach pins what stays as it was: a @@ -162,8 +162,8 @@ func TestCycleVisitor_IsToldWhereAReferenceWasMetAgainAndEntered(t *testing.T) { loop.Next = loop kids := make([]kidTree, 1) kids[0].Kids = kids - kidMapValue := kidMap{} - kidMapValue["a"] = kidMapValue + kidMap := kidMap{} + kidMap["a"] = kidMap for _, tt := range []struct { name string @@ -172,7 +172,7 @@ func TestCycleVisitor_IsToldWhereAReferenceWasMetAgainAndEntered(t *testing.T) { }{ {"a pointer", loop, []valueCycle{{Path: "document.Next", Entered: "document", Type: "*ir_test.ptrNode"}}}, {"a slice", kidTree{Kids: kids}, []valueCycle{{Path: "document.Kids[0].Kids", Entered: "document.Kids", Type: "[]ir_test.kidTree"}}}, - {"a map", kidMapValue, []valueCycle{{Path: "document[a]", Entered: "document", Type: "ir_test.kidMap"}}}, + {"a map", kidMap, []valueCycle{{Path: "document[a]", Entered: "document", Type: "ir_test.kidMap"}}}, } { t.Run(tt.name, func(t *testing.T) { t.Parallel() @@ -216,9 +216,9 @@ func TestCycleVisitor_IsToldNothingOfAnAcyclicGraph(t *testing.T) { func TestCycleVisitor_IsToldInADeterministicOrder(t *testing.T) { t.Parallel() mkLoop := func() *ptrNode { - ptrNodeValue := &ptrNode{} - ptrNodeValue.Next = ptrNodeValue - return ptrNodeValue + ptrNode := &ptrNode{} + ptrNode.Next = ptrNode + return ptrNode } root := map[string]*ptrNode{"a": mkLoop(), "b": mkLoop(), "c": mkLoop()} @@ -247,8 +247,8 @@ func TestCycleVisitor_WalkReportsTruncation(t *testing.T) { t.Parallel() root := irtest.NestedListValue(ir.MaxWalkDepth) - deep := walkDeepList(func(listVisitsValue *listVisits) bool { - return ir.WalkValues(root, "document", ir.CycleVisitor(deepListCycles{listVisitsValue})) + deep := walkDeepList(func(listVisits *listVisits) bool { + return ir.WalkValues(root, "document", ir.CycleVisitor(deepListCycles{listVisits})) }) assert.True(t, deep.truncated, "WalkValues with a CycleVisitor must report truncation at ir.MaxWalkDepth") @@ -381,12 +381,12 @@ func unfoldedConstructors(nodes []graphNode) int { // randomGraph draws up to five nodes, each a constructor, a list or an object // pointing at up to two nodes. It is small so that a graph without a cycle // unfolds into few enough values for the encoder to write it out. -func randomGraph(r *rand.Rand) []graphNode { - nodes := make([]graphNode, 1+r.IntN(5)) +func randomGraph(random *rand.Rand) []graphNode { + nodes := make([]graphNode, 1+random.IntN(5)) for i := range nodes { - nodes[i].kind = nodeKind(r.IntN(3)) - for range r.IntN(3) { - nodes[i].out = append(nodes[i].out, r.IntN(len(nodes))) + nodes[i].kind = nodeKind(random.IntN(3)) + for range random.IntN(3) { + nodes[i].out = append(nodes[i].out, random.IntN(len(nodes))) } } return nodes @@ -394,9 +394,9 @@ func randomGraph(r *rand.Rand) []graphNode { // countEdges counts what TypeEdges yields from td, stopping one past limit, so // that a missing guard fails a count rather than hanging the run. -func countEdges(td ir.TypeDef, limit int) int { +func countEdges(typeDef ir.TypeDef, limit int) int { n := 0 - for range ir.TypeEdges(td) { + for range ir.TypeEdges(typeDef) { if n++; n > limit { break } diff --git a/ir/walk_intkeys_test.go b/ir/walk_intkeys_test.go index dcc60480c..0de99b560 100644 --- a/ir/walk_intkeys_test.go +++ b/ir/walk_intkeys_test.go @@ -17,9 +17,9 @@ import ( ) // intKeys returns a map of n integer keys from first, each holding its own. -func intKeys(first, n int) map[int]int { - m := make(map[int]int, n) - for k := first; k < first+n; k++ { +func intKeys(first, count int) map[int]int { + m := make(map[int]int, count) + for k := first; k < first+count; k++ { m[k] = k } return m @@ -99,8 +99,8 @@ func TestWalkValues_IntegerKeysAreVisitedInTheOrderOfTheirLabels(t *testing.T) { func TestWalkValues_IntegerKeyValuesAreVisitedInKeyOrder(t *testing.T) { t.Parallel() var got []string - ir.WalkValues(map[int]bool{-1: true, 9: true, 10: true}, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() == reflect.Bool { + ir.WalkValues(map[int]bool{-1: true, 9: true, 10: true}, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() == reflect.Bool { got = append(got, at.String()) } return true diff --git a/ir/walk_limit_test.go b/ir/walk_limit_test.go index d1ae0b03d..e3a7cfe15 100644 --- a/ir/walk_limit_test.go +++ b/ir/walk_limit_test.go @@ -16,8 +16,8 @@ import ( ) // stringValues returns n string values, each its own. -func stringValues(n int) []ir.Value { - list := make([]ir.Value, n) +func stringValues(count int) []ir.Value { + list := make([]ir.Value, count) for i := range list { list[i] = ir.Value{Kind: ir.ValueString, String: "s"} } @@ -62,8 +62,8 @@ func skipsHeaders(_ reflect.Value, at ir.WalkPath) bool { // valueOrHeaders returns false for every ir.Value and for a path ending // ".Headers", true elsewhere. -func valueOrHeaders(v reflect.Value, at ir.WalkPath) bool { - return v.Type() != reflect.TypeFor[ir.Value]() && skipsHeaders(v, at) +func valueOrHeaders(value reflect.Value, at ir.WalkPath) bool { + return value.Type() != reflect.TypeFor[ir.Value]() && skipsHeaders(value, at) } // shownBy returns how many values a walk of root shows a counting visitor with @@ -145,11 +145,11 @@ func TestWalkValues_ASharedPointerIsReadFromEveryHolder(t *testing.T) { // the other in Value, each a constructor whose arguments are a list of 300 // strings and the constructor itself, both through one pointer. func cycleExamples() []ir.Example { - constructorValue := &ir.ConstructorValue{Scalar: "type/s", Args: []ir.Value{{Kind: ir.ValueList, List: stringValues(300)}}} - constructorValue.Args = append(constructorValue.Args, ir.Value{Kind: ir.ValueConstructor, Constructor: constructorValue}) + constructor := &ir.ConstructorValue{Scalar: "type/s", Args: []ir.Value{{Kind: ir.ValueList, List: stringValues(300)}}} + constructor.Args = append(constructor.Args, ir.Value{Kind: ir.ValueConstructor, Constructor: constructor}) return []ir.Example{ - {Name: "h", Headers: &ir.Value{Kind: ir.ValueConstructor, Constructor: constructorValue}}, - {Name: "v", Value: &ir.Value{Kind: ir.ValueConstructor, Constructor: constructorValue}}, + {Name: "h", Headers: &ir.Value{Kind: ir.ValueConstructor, Constructor: constructor}}, + {Name: "v", Value: &ir.Value{Kind: ir.ValueConstructor, Constructor: constructor}}, } } @@ -205,9 +205,9 @@ func (p *pruneAtRoot) Visit(reflect.Value, ir.WalkPath) bool { // countersOf returns n counting visitors, each its own, and the same as // visitors. -func countersOf(n int) ([]*shownCounter, []ir.Visitor) { - counters := make([]*shownCounter, n) - visitors := make([]ir.Visitor, n) +func countersOf(count int) ([]*shownCounter, []ir.Visitor) { + counters := make([]*shownCounter, count) + visitors := make([]ir.Visitor, count) for i := range counters { counters[i] = &shownCounter{} visitors[i] = counters[i] diff --git a/ir/walk_path_test.go b/ir/walk_path_test.go index 744379963..ef139d713 100644 --- a/ir/walk_path_test.go +++ b/ir/walk_path_test.go @@ -18,8 +18,8 @@ import ( // listOf returns a document whose one example is a list of n string values, so // a walk of it reaches n elements, each by an index. -func listOf(n int) *ir.Document { - list := make([]ir.Value, n) +func listOf(count int) *ir.Document { + list := make([]ir.Value, count) for i := range list { list[i] = ir.Value{Kind: ir.ValueString, String: "s"} } @@ -190,8 +190,8 @@ func TestWalkPath_LongPathsRenderWhole(t *testing.T) { t.Parallel() long := strings.Repeat("k", 600) var got string - ir.WalkValues(map[string]int{long: 1}, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() == reflect.Int { + ir.WalkValues(map[string]int{long: 1}, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() == reflect.Int { got = at.String() } return true @@ -213,7 +213,7 @@ func (k stringerKey) String() string { return "<" + string(k) + ">" } func (k keyError) Error() string { return "error " + string(k) } -func (k formatterKey) Format(f fmt.State, _ rune) { _, _ = fmt.Fprintf(f, "#%d", int(k)) } +func (k formatterKey) Format(state fmt.State, _ rune) { _, _ = fmt.Fprintf(state, "#%d", int(k)) } // TestWalkPath_MapKeysAreSpelledAsFmtSpellsThem holds a key's path segment to // fmt's %v of the key, which is what the walk spelled before it rendered keys @@ -245,8 +245,8 @@ func TestWalkPath_MapKeysAreSpelledAsFmtSpellsThem(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() var got []string - ir.WalkValues(tt.root, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() == reflect.Int && v.Int() == 1 { + ir.WalkValues(tt.root, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() == reflect.Int && value.Int() == 1 { got = append(got, at.String()) } return true @@ -268,8 +268,8 @@ func (k countdownKey) String() string { return fmt.Sprint(100 - int(k)) } func TestWalkPath_EntriesAreOrderedByTheirSpelling(t *testing.T) { t.Parallel() var got []string - ir.WalkValues(map[countdownKey]int{1: 1, 2: 1}, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() == reflect.Int && v.Type() != reflect.TypeFor[countdownKey]() { + ir.WalkValues(map[countdownKey]int{1: 1, 2: 1}, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() == reflect.Int && value.Type() != reflect.TypeFor[countdownKey]() { got = append(got, at.String()) } return true diff --git a/ir/walk_test.go b/ir/walk_test.go index 02454c49f..2a1c2f738 100644 --- a/ir/walk_test.go +++ b/ir/walk_test.go @@ -73,9 +73,9 @@ func TestWalkValues_MapEntriesAreVisitedInRenderedKeyOrder(t *testing.T) { paths, _ := walkPaths(doc) var entries []string - for _, p := range paths { - if strings.HasPrefix(p, "document.Types[") && strings.HasSuffix(p, ir.MapKeySuffix) { - entries = append(entries, p) + for _, path := range paths { + if strings.HasPrefix(path, "document.Types[") && strings.HasSuffix(path, ir.MapKeySuffix) { + entries = append(entries, path) } } require.Len(t, entries, 4) @@ -108,8 +108,8 @@ type listVisits struct { first, second, deepest string } -func (l *listVisits) Visit(v reflect.Value, at ir.WalkPath) bool { - if v.Type() != reflect.TypeFor[[]ir.Value]() { +func (l *listVisits) Visit(value reflect.Value, at ir.WalkPath) bool { + if value.Type() != reflect.TypeFor[[]ir.Value]() { return true } l.seen++ @@ -180,7 +180,7 @@ func TestWalkValues_DeepValueTreeIsTruncated(t *testing.T) { ID: "type/m", Examples: []ir.Example{{Value: &value}}, }}} - return walkDeepList(func(listVisitsValue *listVisits) bool { return ir.WalkValues(doc, "document", listVisitsValue) }) + return walkDeepList(func(listVisits *listVisits) bool { return ir.WalkValues(doc, "document", listVisits) }) } deep := walkDoc(ir.MaxWalkDepth) @@ -207,11 +207,11 @@ func TestWalkValuesContext_WalksAsWalkValuesUnderALiveContext(t *testing.T) { doc := &ir.Document{Types: ir.TypeRegistry{"type/m": &ir.Model{ID: "type/m", Examples: []ir.Example{{Value: &value}}}}} var want, got []string record := func(into *[]string) ir.Visitor { - return ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + return ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { if tc.paths { *into = append(*into, at.String()) } else { - *into = append(*into, v.Kind().String()) + *into = append(*into, value.Kind().String()) } return true }) @@ -320,9 +320,9 @@ func TestWalkValues_SharedPointerIsDescendedIntoFromEachHolder(t *testing.T) { paths, truncated := walkPaths(doc) require.False(t, truncated, "two template arguments are not deep") var reached []string - for _, p := range paths { - if strings.HasSuffix(p, ".Target") { - reached = append(reached, p) + for _, path := range paths { + if strings.HasSuffix(path, ".Target") { + reached = append(reached, path) } } assert.Len(t, reached, 2, "each argument holds the pointer, and the walk reads it from both: %v", reached) @@ -381,9 +381,9 @@ func TestWalkValues_VisitorPrunesChildren(t *testing.T) { }} var pruned []string - ir.WalkValues(doc, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + ir.WalkValues(doc, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { pruned = append(pruned, at.String()) - return v.Type() != reflect.TypeFor[ir.TypeRegistry]() + return value.Type() != reflect.TypeFor[ir.TypeRegistry]() })) assert.Contains(t, pruned, "document.Types") @@ -483,8 +483,8 @@ type ( ) // walkHolders returns n holders, each map of three entries. -func walkHolders(n int) []walkHolder { - holders := make([]walkHolder, n) +func walkHolders(count int) []walkHolder { + holders := make([]walkHolder, count) for i := range holders { holders[i] = walkHolder{Structs: map[string]walkEntry{}, Boxed: map[string]any{}} for _, k := range []string{"a", "b", "c"} { @@ -517,9 +517,9 @@ type walkNode struct { } // walkKids returns n nodes keyed "k00" on, numbered from first. -func walkKids(first, n int) map[string]walkNode { +func walkKids(first, count int) map[string]walkNode { kids := map[string]walkNode{} - for i := range n { + for i := range count { kids[fmt.Sprintf("k%02d", i)] = walkNode{N: first + i} } return kids @@ -527,9 +527,9 @@ func walkKids(first, n int) map[string]walkNode { // nodeNumbers records under each node's path the number it holds, read by // plain Go rather than by the walk. -func nodeNumbers(path string, walkNodeValue walkNode, into map[string]int64) { - into[path+".N"] = int64(walkNodeValue.N) - for key, kid := range walkNodeValue.Kids { +func nodeNumbers(path string, walkNode walkNode, into map[string]int64) { + into[path+".N"] = int64(walkNode.N) + for key, kid := range walkNode.Kids { nodeNumbers(path+".Kids["+key+"]", kid, into) } } @@ -560,9 +560,9 @@ func TestWalkValues_NestedMapsOfOneTypeKeepTheirEntries(t *testing.T) { nodeNumbers("document.Grown", root.Grown, want) got := map[string]int64{} - truncated := ir.WalkValues(root, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + truncated := ir.WalkValues(root, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { if path := at.String(); strings.HasSuffix(path, ".N") { - got[path] = v.Int() + got[path] = value.Int() } return true })) @@ -582,13 +582,13 @@ func TestWalkValues_MapEntriesAreTheWalksCopies(t *testing.T) { } m := map[string]entry{"a": {Name: "x", Items: []int{1}}} copies := 0 - ir.WalkValues(m, "document", ir.VisitFunc(func(v reflect.Value, _ ir.WalkPath) bool { + ir.WalkValues(m, "document", ir.VisitFunc(func(value reflect.Value, _ ir.WalkPath) bool { switch { - case v.Kind() == reflect.String && v.CanSet(): - v.SetString("changed") + case value.Kind() == reflect.String && value.CanSet(): + value.SetString("changed") copies++ - case v.Kind() == reflect.Int && v.CanSet(): - v.SetInt(2) + case value.Kind() == reflect.Int && value.CanSet(): + value.SetInt(2) } return true })) @@ -606,12 +606,12 @@ func TestWalkValues_InterfaceInAMapEntryLeadsToTheDocumentsOwn(t *testing.T) { t.Parallel() root := []map[string]any{{"a": walkEntry{Name: "first"}}, {"a": walkEntry{Name: "second"}}} var copies, held []reflect.Value - ir.WalkValues(root, "document", ir.VisitFunc(func(v reflect.Value, _ ir.WalkPath) bool { - switch v.Kind() { + ir.WalkValues(root, "document", ir.VisitFunc(func(value reflect.Value, _ ir.WalkPath) bool { + switch value.Kind() { case reflect.Interface: - copies = append(copies, v) + copies = append(copies, value) case reflect.Struct: - held = append(held, v) + held = append(held, value) default: // The slice, the maps and the strings carry nothing this case reads. } @@ -632,12 +632,12 @@ func TestWalkValues_MapBehindAnUnexportedFieldIsReached(t *testing.T) { t.Parallel() holder := struct{ hidden map[string]int }{hidden: map[string]int{"b": 2, "a": 1}} var got []string - ir.WalkValues(holder, "document", ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { - switch v.Kind() { + ir.WalkValues(holder, "document", ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { + switch value.Kind() { case reflect.String: - got = append(got, at.String()+"="+v.String()) + got = append(got, at.String()+"="+value.String()) case reflect.Int: - got = append(got, at.String()+"="+strconv.FormatInt(v.Int(), 10)) + got = append(got, at.String()+"="+strconv.FormatInt(value.Int(), 10)) default: got = append(got, at.String()) } @@ -653,12 +653,12 @@ func TestWalkValues_MapBehindAnUnexportedFieldIsReached(t *testing.T) { // growingMaps returns maps of one type sized 1 to n, smallest first, so each // needs more storage than any before it. Keys are strings, which label // themselves; an integer key from 100 up allocates its label. -func growingMaps(n int) []map[string]int { - keys := make([]string, n) +func growingMaps(count int) []map[string]int { + keys := make([]string, count) for k := range keys { keys[k] = strconv.Itoa(k) } - sized := make([]map[string]int, n) + sized := make([]map[string]int, count) for i := range sized { sized[i] = map[string]int{} for k := range i + 1 { @@ -676,8 +676,8 @@ func growingMaps(n int) []map[string]int { // AllocsPerRun measures the process. func TestWalkValues_MapStorageGrowsByDoubling(t *testing.T) { visit := ir.VisitFunc(func(reflect.Value, ir.WalkPath) bool { return true }) - allocs := func(n int) float64 { - sized := growingMaps(n) + allocs := func(count int) float64 { + sized := growingMaps(count) return testing.AllocsPerRun(5, func() { _ = ir.WalkValues(sized, "document", visit) }) } small, medium, large := allocs(32), allocs(64), allocs(128) diff --git a/ir/walk_visitors_test.go b/ir/walk_visitors_test.go index 886acb4da..c13b2e0d0 100644 --- a/ir/walk_visitors_test.go +++ b/ir/walk_visitors_test.go @@ -57,15 +57,15 @@ func pruneOneIn(n uint32, salt string) func(string) bool { func sharedAndAlone(root any, rules []func(string) bool) (shared, alone []*recorder, sharedCut, aloneCut bool) { visitors := make([]ir.Visitor, len(rules)) for i, rule := range rules { - recorderValue := &recorder{prune: rule} - shared = append(shared, recorderValue) - visitors[i] = recorderValue + recorder := &recorder{prune: rule} + shared = append(shared, recorder) + visitors[i] = recorder } sharedCut = ir.WalkValues(root, "document", visitors...) for _, rule := range rules { - recorderValue := &recorder{prune: rule} - alone = append(alone, recorderValue) - aloneCut = ir.WalkValues(root, "document", recorderValue) || aloneCut + recorder := &recorder{prune: rule} + alone = append(alone, recorder) + aloneCut = ir.WalkValues(root, "document", recorder) || aloneCut } return shared, alone, sharedCut, aloneCut } @@ -209,9 +209,9 @@ func TestWalkValues_TruncationReachesPastOneTraversal(t *testing.T) { func TestWalkValues_NilVisitorsAreSkipped(t *testing.T) { t.Parallel() doc := &ir.Document{Name: "api"} - recorderValue := &recorder{} - assert.False(t, ir.WalkValues(doc, "document", nil, recorderValue, ir.VisitFunc(nil))) - assert.Contains(t, recorderValue.paths, "document.Name", "a nil visitor beside it does not stop the others") + recorder := &recorder{} + assert.False(t, ir.WalkValues(doc, "document", nil, recorder, ir.VisitFunc(nil))) + assert.Contains(t, recorder.paths, "document.Name", "a nil visitor beside it does not stop the others") deep := irtest.NestedListValue(ir.MaxWalkDepth) assert.False(t, ir.WalkValues(deep, "document"), "no visitor, no walk") diff --git a/pass/constunions.go b/pass/constunions.go index c4eff458c..3967bd0a9 100644 --- a/pass/constunions.go +++ b/pass/constunions.go @@ -66,12 +66,12 @@ func (ConstUnions) Run(ctx context.Context, doc *ir.Document) (*ir.Document, []i // several values only where refs shows the union naming it is its one // reference, and none where refs is nil. func readingOf(doc *ir.Document, refs *typeRefs) *unionReading { - unionReadingValue := &unionReading{types: doc.Types, spaces: doc.IDSpaces[ir.IDKindEnumMember], refs: refs, + unionReading := &unionReading{types: doc.Types, spaces: doc.IDSpaces[ir.IDKindEnumMember], refs: refs, values: map[ir.TypeID]*unionValues{}, opened: map[ir.TypeID]bool{}, read: map[ir.TypeID]bool{}} for id := range doc.Types { - unionReadingValue.settle(id) + unionReading.settle(id) } - return unionReadingValue + return unionReading } // unionReading reads each union of a registry as valuesOf does, after the diff --git a/pass/constunions_enum.go b/pass/constunions_enum.go index 906e565e0..15d2525e8 100644 --- a/pass/constunions_enum.go +++ b/pass/constunions_enum.go @@ -42,7 +42,7 @@ type valuePart struct { // instance matches one variant at most, so union's Exclusive says nothing lost. func (r *unionReading) valuesOf(union *ir.Union) (*unionValues, bool) { space, spaced := ir.IDSpace(ir.IDKindType, string(union.ID)) - if len(union.Variants) == 0 || !union.Closed || !plainUnion(*union) || !spaced || !slices.Contains(r.spaces, space) { + if len(union.Variants) == 0 || !union.Closed || !plainUnion(*union) || !boundsAreTextAlone(union.Constraints) || !spaced || !slices.Contains(r.spaces, space) { return nil, false } vs := &unionValues{union: union, parts: make([]valuePart, 0, len(union.Variants))} @@ -57,14 +57,27 @@ func (r *unionReading) valuesOf(union *ir.Union) (*unionValues, bool) { } // plainUnion reports whether union says nothing beside its common part, its -// variants, whether it is closed and whether it is exclusive: no tag, no -// discriminator, no input-only identity, nor a field ir adds later, none of -// which an Enum holds. +// variants, whether it is closed, whether it is exclusive and its bounds: no +// tag, no discriminator, no input-only identity, nor a field ir adds later, +// none of which an Enum holds. func plainUnion(union ir.Union) bool { - union.TypeCommon, union.Variants, union.Exclusive, union.Closed = ir.TypeCommon{}, nil, false, false + union.TypeCommon, union.Variants, union.Exclusive, union.Closed, union.Constraints = ir.TypeCommon{}, nil, false, false, nil return reflect.ValueOf(union).IsZero() } +// boundsAreTextAlone reports whether constraints, a union's bounds, are none or +// bound text alone, a length or a pattern, which an Enum of strings holds in +// its own Constraints (docs/ir/enums.md#bounds); any other bounds no string, +// so the union keeps it. +func boundsAreTextAlone(constraints *ir.Constraints) bool { + if constraints == nil { + return true + } + rest := *constraints + rest.MinLength, rest.MaxLength, rest.Pattern, rest.PatternMessage = nil, nil, "", "" + return rest == ir.Constraints{} +} + // appendValues appends to parts the values variant names, and returns them with // the primitive typing them, where variant says nothing but what it says of a // value (variantFacts) and names an anonymous type of strings saying nothing @@ -135,7 +148,9 @@ func (r *unionReading) branchValues(id ir.TypeID) ([]valuePart, ir.PrimitiveKind case *ir.Union: vs, read := r.values[id] switch { - case !read: + case !read || vs.union.Constraints != nil: + // A union holding bounds is an Enum of its own, which a union + // naming it reads no member of in place. return nil, "", ir.TypeCommon{}, false case vs.n == 1: return vs.parts, vs.primitive, vs.union.TypeCommon, true @@ -182,16 +197,16 @@ func (r *unionReading) distinct(vs *unionValues) bool { return true } -// addPart adds to keys the key of each value valuePartValue holds, bar those of +// addPart adds to keys the key of each value valuePart holds, bar those of // taken, whose keys keys holds already, and reports whether none was there. -func (r *unionReading) addPart(keys map[string]bool, valuePartValue valuePart, taken *unionValues) bool { - switch valuePartValue.of { +func (r *unionReading) addPart(keys map[string]bool, valuePart valuePart, taken *unionValues) bool { + switch valuePart.of { case nil: - return r.addKey(keys, valuePartValue.key) + return r.addKey(keys, valuePart.key) case taken: return true } - for key := range valuePartValue.of.keys { + for key := range valuePart.of.keys { if !r.addKey(keys, key) { return false } @@ -237,7 +252,7 @@ func (r *unionReading) enum(vs *unionValues) *ir.Enum { enumMember.ID, _ = ir.EnumMemberIDFor(vs.union.ID, valuePart.key, 1 /* occurrence */) members = append(members, enumMember) } - return &ir.Enum{TypeCommon: vs.union.TypeCommon, ValueType: vs.primitive, Members: members, Closed: true} + return &ir.Enum{TypeCommon: vs.union.TypeCommon, ValueType: vs.primitive, Members: members, Closed: true, Constraints: vs.union.Constraints} } // commonFacts returns what typeCommon, the common part of a variant's type, @@ -246,14 +261,14 @@ func (r *unionReading) enum(vs *unionValues) *ir.Enum { // extensions, and no heuristic inferred it, whose mark no member could carry. // Its provenance goes with the type. func commonFacts(typeCommon ir.TypeCommon) (memberFacts, bool) { - memberFactsValue := memberFacts{docs: typeCommon.Docs, deprecation: typeCommon.Deprecation, availability: typeCommon.Availability, + memberFacts := memberFacts{docs: typeCommon.Docs, deprecation: typeCommon.Deprecation, availability: typeCommon.Availability, examples: typeCommon.Examples, unmodeled: typeCommon.Unmodeled} if !typeCommon.Anonymous || !declaresNoName(typeCommon.Name) || !extensionsOnly(typeCommon.Unmodeled) || typeCommon.Provenance.Inferred != "" { - return memberFactsValue, false + return memberFacts, false } typeCommon.ID, typeCommon.Anonymous, typeCommon.Name, typeCommon.Provenance = "", false, ir.Naming{}, ir.Provenance{} typeCommon.Docs, typeCommon.Deprecation, typeCommon.Availability, typeCommon.Examples, typeCommon.Unmodeled = ir.Docs{}, nil, nil, nil, nil - return memberFactsValue, reflect.ValueOf(typeCommon).IsZero() + return memberFacts, reflect.ValueOf(typeCommon).IsZero() } // variantFacts returns what variant says of its value, and whether it says @@ -261,14 +276,14 @@ func commonFacts(typeCommon ir.TypeCommon) (memberFacts, bool) { // extensions, no nullable reference, no wire tag or number, XML hint or event, // nor a field ir adds later. func variantFacts(variant ir.Variant) (memberFacts, bool) { - memberFactsValue := memberFacts{docs: variant.Docs, deprecation: variant.Deprecation, availability: variant.Availability, + memberFacts := memberFacts{docs: variant.Docs, deprecation: variant.Deprecation, availability: variant.Availability, examples: variant.Examples, unmodeled: variant.Unmodeled} if !declaresNoName(variant.Name) || !extensionsOnly(variant.Unmodeled) { - return memberFactsValue, false + return memberFacts, false } variant.Name, variant.Type.Target = ir.Naming{}, "" variant.Docs, variant.Deprecation, variant.Availability, variant.Examples, variant.Unmodeled = ir.Docs{}, nil, nil, nil, nil - return memberFactsValue, reflect.ValueOf(variant).IsZero() + return memberFacts, reflect.ValueOf(variant).IsZero() } // declaresNoName reports whether naming names nothing a source declared, only @@ -316,15 +331,15 @@ func (f memberFacts) onto(enumMember ir.EnumMember) ir.EnumMember { return enumMember } -// with returns f joined with memberFactsValue, and whether no fact is said by +// with returns f joined with memberFacts, and whether no fact is said by // both: a member holds one of each, so choosing between two would drop one. -func (f memberFacts) with(memberFactsValue memberFacts) (memberFacts, bool) { +func (f memberFacts) with(memberFacts memberFacts) (memberFacts, bool) { var ok [5]bool - f.docs, ok[0] = either(f.docs, memberFactsValue.docs) - f.deprecation, ok[1] = either(f.deprecation, memberFactsValue.deprecation) - f.availability, ok[2] = either(f.availability, memberFactsValue.availability) - f.examples, ok[3] = either(f.examples, memberFactsValue.examples) - f.unmodeled, ok[4] = either(f.unmodeled, memberFactsValue.unmodeled) + f.docs, ok[0] = either(f.docs, memberFacts.docs) + f.deprecation, ok[1] = either(f.deprecation, memberFacts.deprecation) + f.availability, ok[2] = either(f.availability, memberFacts.availability) + f.examples, ok[3] = either(f.examples, memberFacts.examples) + f.unmodeled, ok[4] = either(f.unmodeled, memberFacts.unmodeled) return f, !slices.Contains(ok[:], false) } diff --git a/pass/constunions_refs.go b/pass/constunions_refs.go index 8bb382577..7d37bd60a 100644 --- a/pass/constunions_refs.go +++ b/pass/constunions_refs.go @@ -26,7 +26,7 @@ var ( // Enum names, and each member of one that is an Enum, beside how many variants // of the registry's unions name each such type. func refsTo(types ir.TypeRegistry) *typeRefs { - typeRefsValue := &typeRefs{ + typeRefs := &typeRefs{ watched: map[ir.TypeID]bool{}, members: map[ir.EnumMemberID]ir.TypeID{}, held: map[ir.TypeID]int{}, @@ -34,21 +34,21 @@ func refsTo(types ir.TypeRegistry) *typeRefs { keys: map[ir.TypeID]int{}, carries: map[reflect.Type]bool{}, } - for id, td := range types { - union, isUnion := td.(*ir.Union) + for id, typeDef := range types { + union, isUnion := typeDef.(*ir.Union) if !isUnion || union == nil { continue } for _, variant := range union.Variants { - typeRefsValue.held[variant.Type.Target]++ + typeRefs.held[variant.Type.Target]++ } if union.ID == id && mayBeEnum(types, union) { for _, variant := range union.Variants { - typeRefsValue.watch(types, variant.Type.Target) + typeRefs.watch(types, variant.Type.Target) } } } - return typeRefsValue + return typeRefs } // mayBeEnum reports whether union may be read as an Enum: a closed union saying @@ -59,10 +59,10 @@ func mayBeEnum(types ir.TypeRegistry, union *ir.Union) bool { return false } for _, variant := range union.Variants { - td := types[variant.Type.Target] - switch td.(type) { + typeDef := types[variant.Type.Target] + switch typeDef.(type) { case *ir.Literal, *ir.Enum, *ir.Union: - if ir.IsNilTypeDef(td) || !td.Common().Anonymous { + if ir.IsNilTypeDef(typeDef) || !typeDef.Common().Anonymous { return false } default: @@ -129,18 +129,18 @@ func (r *typeRefs) onlyVariants(id ir.TypeID, variants int) bool { return r != nil && r.held[id] == variants && r.sites[id] == variants } -// Visit records a reference v makes to a watched type, and asks for what v -// holds where it can hold one. -func (r *typeRefs) Visit(v reflect.Value, at ir.WalkPath) bool { - switch v.Type() { +// Visit records a reference value makes to a watched type, and asks for what +// value holds where it can hold one. +func (r *typeRefs) Visit(value reflect.Value, at ir.WalkPath) bool { + switch value.Type() { case typeIDType: - r.typeID(ir.TypeID(v.String()), at) + r.typeID(ir.TypeID(value.String()), at) case memberIDType: - if owner, watched := r.members[ir.EnumMemberID(v.String())]; watched && !ownMemberID(at) { + if owner, watched := r.members[ir.EnumMemberID(value.String())]; watched && !ownMemberID(at) { r.sites[owner]++ } default: - return r.canCarry(v.Type()) + return r.canCarry(value.Type()) } return false } diff --git a/pass/constunions_test.go b/pass/constunions_test.go index b1a5f76e1..451902d03 100644 --- a/pass/constunions_test.go +++ b/pass/constunions_test.go @@ -22,7 +22,7 @@ import ( ) // stringValue is the string value s. -func stringValue(s string) ir.Value { return ir.Value{Kind: ir.ValueString, String: s} } +func stringValue(text string) ir.Value { return ir.Value{Kind: ir.ValueString, String: text} } // lit is the anonymous string Literal at id holding value, as a compiler // lowers a const branch. @@ -231,9 +231,24 @@ func TestConstUnions_KeepsTheValueTypeEveryBranchShares(t *testing.T) { assert.Same(t, apart, collapsed(t, apart)) } +// TestConstUnions_FoldsAUnionsBoundsIntoItsEnum pins a union of strings +// holding bounds: an Enum holds the bounds of its value kind (GitHub #2004), so +// the union becomes its Enum as any other does, the bounds in the Enum's +// Constraints. +func TestConstUnions_FoldsAUnionsBoundsIntoItsEnum(t *testing.T) { + t.Parallel() + irUnion := union("type/x/U", "type/x/U/0", "type/x/U/1") + irUnion.Constraints = &ir.Constraints{MinLength: new(int64(1)), MaxLength: new(int64(3)), Pattern: "^[a-z]+$"} + out := collapsed(t, constDoc(irUnion, lit("type/x/U/0", "red"), lit("type/x/U/1", "green"))) + want := enumFor(irUnion, member(irUnion.ID, "red"), member(irUnion.ID, "green")) + want.Constraints = &ir.Constraints{MinLength: new(int64(1)), MaxLength: new(int64(3)), Pattern: "^[a-z]+$"} + assert.Empty(t, cmp.Diff(want, out.Types[irUnion.ID])) + assert.NotContains(t, out.Types, ir.TypeID("type/x/U/0"), "the branch types go with the union") +} + // TestConstUnions_KeepsAUnionAnEnumCannotSay pins each union the pass leaves: -// one saying what an Enum has no field for, a variant or branch saying more -// than its value, a branch of another kind or none, values of different types +// one holding a bound binding no string (GitHub #2004), a variant or branch +// saying more than its value, a branch of another kind or none, values of different types // or a value twice, a fact two places say of one value, and a branch of // several values that another node, or a member of it, names, or that it or // its variant says something of them all. Each sits beside a union the pass @@ -251,8 +266,8 @@ func TestConstUnions_KeepsAUnionAnEnumCannotSay(t *testing.T) { union.Discriminator = &ir.Discriminator{PropertyName: "kind"} }}, {"an input-only union", func(union *ir.Union, _ *ir.Literal, _ *ir.Enum, _ ir.TypeRegistry) { union.InputOnly = true }}, - {"a union's bounds", func(union *ir.Union, _ *ir.Literal, _ *ir.Enum, _ ir.TypeRegistry) { - union.Constraints = &ir.Constraints{MaxLength: new(int64(3))} + {"a bound binding no string", func(union *ir.Union, _ *ir.Literal, _ *ir.Enum, _ ir.TypeRegistry) { + union.Constraints = &ir.Constraints{MaxLength: new(int64(3)), Max: new(ir.BigVal("3"))} }}, {"no variant", func(union *ir.Union, _ *ir.Literal, _ *ir.Enum, _ ir.TypeRegistry) { union.Variants = nil }}, {"a nullable variant", func(union *ir.Union, _ *ir.Literal, _ *ir.Enum, _ ir.TypeRegistry) { @@ -407,8 +422,8 @@ func TestConstUnions_KeepsAUnionAnEnumCannotSay(t *testing.T) { doc.Types["type/x/R"], doc.Types["type/x/R/0"] = union("type/x/R", "type/x/R/0"), lit("type/x/R/0", "beside") out := collapsed(t, doc) - for id, td := range kept { - assert.Same(t, td, out.Types[id], "%s is kept", id) + for id, typeDef := range kept { + assert.Same(t, typeDef, out.Types[id], "%s is kept", id) } assert.Equal(t, ir.KindEnum, out.Types["type/x/R"].Kind(), "the union beside it is read and rewritten") assert.Len(t, out.Types, len(kept)+1, "only the branch of the union beside it goes") @@ -418,9 +433,9 @@ func TestConstUnions_KeepsAUnionAnEnumCannotSay(t *testing.T) { // TestConstUnions_RewritesAUnionOfSeveralValuesItsUnionCannotTake pins a union // naming a union of several values it cannot take, as another node names that -// union or it says something of all its values: the union stays, naming the -// Enum the union it names becomes, whose branches go, and a second run finds -// nothing left to rewrite. +// union, it says something of all its values or it holds bounds, which only +// its own Enum holds: the union stays, naming the Enum the union it names +// becomes, whose branches go, and a second run finds nothing left to rewrite. func TestConstUnions_RewritesAUnionOfSeveralValuesItsUnionCannotTake(t *testing.T) { t.Parallel() for name, write := range map[string]func(doc *ir.Document, nested *ir.Union){ @@ -430,6 +445,9 @@ func TestConstUnions_RewritesAUnionOfSeveralValuesItsUnionCannotTake(t *testing. "it says something of them all": func(_ *ir.Document, nested *ir.Union) { nested.Docs = ir.Docs{Description: "Either way."} }, + "it holds bounds": func(_ *ir.Document, nested *ir.Union) { + nested.Constraints = &ir.Constraints{MaxLength: new(int64(4))} + }, } { nested := anonymousUnion("type/x/U/1", "type/x/U/1/0", "type/x/U/1/1") doc := constDoc(union("type/x/U", "type/x/U/0", "type/x/U/1"), lit("type/x/U/0", "left"), @@ -438,8 +456,9 @@ func TestConstUnions_RewritesAUnionOfSeveralValuesItsUnionCannotTake(t *testing. once := collapsed(t, doc) assert.Same(t, doc.Types["type/x/U"], once.Types["type/x/U"], "%s: the union naming it stays", name) - assert.Empty(t, cmp.Diff(enumFor(nested, member(nested.ID, "up"), member(nested.ID, "down")), - once.Types[nested.ID]), name) + want := enumFor(nested, member(nested.ID, "up"), member(nested.ID, "down")) + want.Constraints = nested.Constraints + assert.Empty(t, cmp.Diff(want, once.Types[nested.ID]), name) assert.NotContains(t, once.Types, ir.TypeID("type/x/U/1/0"), name) assert.Same(t, once, collapsed(t, once), "%s: a second run rewrites nothing", name) } @@ -741,9 +760,9 @@ func TestConstUnions_IsDeterministic(t *testing.T) { // chain is a document of n unions, each naming the next and a value of its // own, the value first where valueFirst, and the last naming a value of its // own and the value last. -func chain(n int, valueFirst bool) *ir.Document { - types := make([]ir.TypeDef, 0, 2*n+1) - for i := range n { +func chain(count int, valueFirst bool) *ir.Document { + types := make([]ir.TypeDef, 0, 2*count+1) + for i := range count { id, next := ir.TypeID(fmt.Sprintf("type/x/X%d", i)), ir.TypeID(fmt.Sprintf("type/x/X%d", i+1)) value := id + "/v" irUnion := union(id, next, value) @@ -755,15 +774,15 @@ func chain(n int, valueFirst bool) *ir.Document { } types = append(types, irUnion, lit(value, fmt.Sprintf("a%d", i))) } - return constDoc(append(types, lit(ir.TypeID(fmt.Sprintf("type/x/X%d", n)), "last"))...) + return constDoc(append(types, lit(ir.TypeID(fmt.Sprintf("type/x/X%d", count)), "last"))...) } -// caterpillar is chain(n, valueFirst) with each link's value a union of two -// values, so each link takes two unions of several values, the next link the +// caterpillar is chain(n, valueFirst) with each node's value a union of two +// values, so each node takes two unions of several values, the next node the // larger. -func caterpillar(n int, valueFirst bool) *ir.Document { - doc := chain(n, valueFirst) - for i := range n { +func caterpillar(count int, valueFirst bool) *ir.Document { + doc := chain(count, valueFirst) + for i := range count { value := ir.TypeID(fmt.Sprintf("type/x/X%d/v", i)) doc.Types[value] = anonymousUnion(value, value+"/0", value+"/1") doc.Types[value+"/0"], doc.Types[value+"/1"] = lit(value+"/0", fmt.Sprintf("b%d", i)), lit(value+"/1", fmt.Sprintf("c%d", i)) @@ -771,11 +790,11 @@ func caterpillar(n int, valueFirst bool) *ir.Document { return doc } -// TestConstUnions_TakesEveryLinkOfAChain pins a chain of unions, each naming +// TestConstUnions_TakesEveryNodeOfAChain pins a chain of unions, each naming // the next once: the first becomes the Enum of every value the chain holds, in -// variant order, whichever side of each union the next link is on, and every -// other link and branch goes. -func TestConstUnions_TakesEveryLinkOfAChain(t *testing.T) { +// variant order, whichever side of each union the next node is on, and every +// other node and branch goes. +func TestConstUnions_TakesEveryNodeOfAChain(t *testing.T) { t.Parallel() const n = 4 for _, valueFirst := range []bool{true, false} { @@ -802,12 +821,12 @@ func TestConstUnions_TakesEveryLinkOfAChain(t *testing.T) { } } -// TestConstUnions_ReadsAChainInWorkLinearInItsLength holds what reading a -// chain of unions costs to the values it holds, each link beside a value or a -// union of two: the keys set apart and the members built grow by about as much -// from 2n links to 4n as from n to 2n, where building each link's Enum from -// the next, or copying the larger union's keys into the one taking them rather -// than the smaller's, grows with the square of the chain. +// TestConstUnions_ReadsAChainInWorkLinearInItsLength holds what reading a chain +// of unions costs to the values it holds, each node beside a value or a union +// of two: the keys set apart and the members built grow by about as much from +// 2n nodes to 4n as from n to 2n, where building each node's Enum from the +// next, or copying the larger union's keys into the one taking them rather than +// the smaller's, grows with the square of the chain. func TestConstUnions_ReadsAChainInWorkLinearInItsLength(t *testing.T) { t.Parallel() const n = 200 @@ -837,14 +856,14 @@ func TestConstUnions_ReadsASetManyUnionsNameOnce(t *testing.T) { // fanIn is a document of n unions, each naming one Enum of n values they all // share and a value of its own. -func fanIn(n int) *ir.Document { - values := make([]string, n) +func fanIn(count int) *ir.Document { + values := make([]string, count) for i := range values { values[i] = fmt.Sprintf("s%d", i) } - types := make([]ir.TypeDef, 0, 1+2*n) + types := make([]ir.TypeDef, 0, 1+2*count) types = append(types, pinned("type/x/S", values...)) - for i := range n { + for i := range count { id := ir.TypeID(fmt.Sprintf("type/x/U%d", i)) types = append(types, union(id, "type/x/S", id+"/v"), lit(id+"/v", fmt.Sprintf("u%d", i))) } diff --git a/pass/export_test.go b/pass/export_test.go index a72bf4da6..c651f001a 100644 --- a/pass/export_test.go +++ b/pass/export_test.go @@ -51,9 +51,9 @@ func WalkVisitors(tb testing.TB, doc *ir.Document) []ir.Visitor { // failing tb unless the walk finishes. func walkedFor(tb testing.TB, doc *ir.Document) walked { tb.Helper() - walkedValue, err := walkDocument(tb.Context(), doc, ir.WalkValuesContext) + walked, err := walkDocument(tb.Context(), doc, ir.WalkValuesContext) require.NoError(tb, err) - return walkedValue + return walked } // AppendTypeIDs is appendTypeIDs, for the external tests. @@ -70,8 +70,8 @@ func Families() int { return len(families(&ir.Document{}, walked{}, nil)) } // NameFamilies is how many families of scopes Names reads, each after a check // of its context. func NameFamilies() int { - var nameReaderValue nameReader - return len(nameReaderValue.families()) + var nameReader nameReader + return len(nameReader.families()) } // FamilyAllocs returns the allocations one run of each rule family Validate @@ -141,11 +141,11 @@ func Watched(doc *ir.Document) int { return len(refsTo(doc.Types).watched) } // watching returns the typeRefs of ids alone. func watching(ids []ir.TypeID) *typeRefs { - typeRefsValue := refsTo(nil) + typeRefs := refsTo(nil) for _, id := range ids { - typeRefsValue.watched[id] = true + typeRefs.watched[id] = true } - return typeRefsValue + return typeRefs } // TypeReads is how many Go types a walk of doc for the references to ids @@ -160,9 +160,9 @@ func TypeReads(doc *ir.Document, ids ...ir.TypeID) int { // shows its visitor, which pruning holds to what can hold a TypeID. func TypeRefVisits(doc *ir.Document, ids ...ir.TypeID) int { typeRefs, n := watching(ids), 0 - ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(v reflect.Value, at ir.WalkPath) bool { + ir.WalkValues(doc, ir.DocumentPath, ir.VisitFunc(func(value reflect.Value, at ir.WalkPath) bool { n++ - return typeRefs.Visit(v, at) + return typeRefs.Visit(value, at) })) return n } @@ -174,3 +174,15 @@ func NarrowedHolds(types ir.TypeRegistry, target ir.TypeID, key ir.PropertyID, l // WithoutEmptyKeys is withoutEmptyKeys, for the external tests. var WithoutEmptyKeys = withoutEmptyKeys + +// MaxValueJudgments is maxValueJudgments, the judgments a Validate run's value +// admission reader may take. +const MaxValueJudgments = maxValueJudgments + +// ValueFindingsWithin is checkValues over doc with the run's value admission +// reader held to judgments, for the external tests that spend them. +func ValueFindingsWithin(doc *ir.Document, judgments int) []ir.Diagnostic { + chains := newAliasChains(doc) + chains.judgments = judgments + return checkValues(doc, chains, liveTypeIDs(doc)) +} diff --git a/pass/irverify_codes_test.go b/pass/irverify_codes_test.go index af62491e0..0b5cc2519 100644 --- a/pass/irverify_codes_test.go +++ b/pass/irverify_codes_test.go @@ -18,7 +18,7 @@ import ( // verifyOnlyBase is a small document with a model, an enum and one operation // bound once, which the cases below plant a value irverify refuses on. func verifyOnlyBase() *ir.Document { - name := func(s string) ir.Naming { return ir.Naming{Source: s, Canonical: s} } + name := func(text string) ir.Naming { return ir.Naming{Source: text, Canonical: text} } primitive := &ir.Primitive{ID: "type/primitive/string", Name: name("string"), PrimitiveKind: ir.PrimitiveString} primitive.Provenance = ir.Provenance{Source: ir.NoSource} return &ir.Document{ @@ -62,11 +62,11 @@ func validateCodes(t *testing.T, doc *ir.Document) []string { return codes } -// TestValidate_StaysSilentOnWhatIrverifyHolds drives each document irverify -// refuses under a code of its own through pass.Validate beside the nearest valid -// document: the two draw the same diagnostics, so each defect has one reporter, -// and the code is irverify's. -func TestValidate_StaysSilentOnWhatIrverifyHolds(t *testing.T) { +// TestValidate_ReportsNothingOnWhatIrverifyHolds drives each document irverify +// refuses under a code of its own through pass.Validate beside the nearest +// valid document: the two draw the same diagnostics, so each defect has one +// reporter, and the code is irverify's. +func TestValidate_ReportsNothingOnWhatIrverifyHolds(t *testing.T) { t.Parallel() model := func(document *ir.Document) *ir.Model { return document.Types["type/x/M"].(*ir.Model) } operation := func(document *ir.Document) *ir.Operation { return &document.Services[0].Groups[0].Operations[0] } diff --git a/pass/names.go b/pass/names.go index 49b8de727..65e10d13a 100644 --- a/pass/names.go +++ b/pass/names.go @@ -49,8 +49,8 @@ func checkNames(ctx context.Context, doc *ir.Document) ([]ir.Diagnostic, error) if doc == nil { return nil, nil } - var nameReaderValue nameReader - for _, family := range nameReaderValue.families() { + var nameReader nameReader + for _, family := range nameReader.families() { if err := ctx.Err(); err != nil { return nil, err } @@ -59,7 +59,7 @@ func checkNames(ctx context.Context, doc *ir.Document) ([]ir.Diagnostic, error) if err := ctx.Err(); err != nil { return nil, err } - return nameReaderValue.diags, nil + return nameReader.diags, nil } // families returns the families of scopes r reads, in the order they report. @@ -147,12 +147,12 @@ func (r *nameReader) types(doc *ir.Document) { declared := ids[:0] r.parties = r.parties[:0] for _, id := range ids { - td := doc.Types[id] - if td.Common().Anonymous || builtIn(td) { + typeDef := doc.Types[id] + if typeDef.Common().Anonymous || builtIn(typeDef) { continue } declared = append(declared, id) - r.parties = append(r.parties, partyOf(td.Common().Name)) + r.parties = append(r.parties, partyOf(typeDef.Common().Name)) } if r.read(byJoinedWords) { r.report(scope{one: "type", many: "types", @@ -160,11 +160,11 @@ func (r *nameReader) types(doc *ir.Document) { } } -// builtIn reports whether td is a type a target resolves through its type +// builtIn reports whether typeDef is a type a target resolves through its type // table, by its primitive or identity, rather than declares: a primitive, an // any node or an external (docs/emitters/contract/type-table.md). -func builtIn(td ir.TypeDef) bool { - switch td.(type) { +func builtIn(typeDef ir.TypeDef) bool { + switch typeDef.(type) { case *ir.Primitive, *ir.Any, *ir.External: return true default: @@ -174,9 +174,12 @@ func builtIn(td ir.TypeDef) bool { // typeParts reads the named parts of the type at id, its properties, members // or variants, as one scope, a union's variants compared joined. A model's are -// its own properties; inherited reads the rest. -func (r *nameReader) typeParts(id ir.TypeID, td ir.TypeDef) { - switch t := td.(type) { +// its own properties; inherited reads the rest. A variant naming the type an +// earlier one names is read as naming nothing, which read passes over: the two +// share a name because they share a type, which the repeated-variant finding +// reports (docs/ir/unions.md#a-type-listed-twice). +func (r *nameReader) typeParts(id ir.TypeID, typeDef ir.TypeDef) { + switch t := typeDef.(type) { case *ir.Model: if r.readScope(byWords, len(t.Properties), func(i int) ir.Naming { return t.Properties[i].Name }) { r.report(scope{in: "model", id: string(id), one: "property", many: "properties"}) @@ -186,7 +189,13 @@ func (r *nameReader) typeParts(id ir.TypeID, td ir.TypeDef) { r.report(scope{in: "enum", id: string(id), one: "member", many: "members"}) } case *ir.Union: - if r.readScope(byJoinedWords, len(t.Variants), func(i int) ir.Naming { return t.Variants[i].Name }) { + first := r.firstVariants(t) + if r.readScope(byJoinedWords, len(t.Variants), func(i int) ir.Naming { + if first[t.Variants[i].Type.Target] != i { + return ir.Naming{} + } + return t.Variants[i].Name + }) { r.report(scope{in: "union", id: string(id), one: "variant", many: "variants", ids: idsOf(len(t.Variants), func(i int) string { return string(t.Variants[i].Type.Target) })}) } @@ -195,6 +204,16 @@ func (r *nameReader) typeParts(id ir.TypeID, td ir.TypeDef) { } } +// firstVariants maps each type a variant of union names to the first variant +// naming it, in a map r reuses for every union. +func (r *nameReader) firstVariants(union *ir.Union) map[ir.TypeID]int { + first := r.variants.Emptied() + for i, variant := range slices.Backward(union.Variants) { + first[variant.Type.Target] = i + } + return first +} + // auth reads the document's auth schemes as one scope, in ID order. func (r *nameReader) auth(doc *ir.Document) { ids := slices.Sorted(maps.Keys(doc.Auth)) diff --git a/pass/names_headers.go b/pass/names_headers.go index 6977e5ffa..51f4afa0d 100644 --- a/pass/names_headers.go +++ b/pass/names_headers.go @@ -51,9 +51,9 @@ func (r *nameReader) headerScope(in, id string, headers []ir.Header, of func() s // nameLabel quotes the first of naming's source, canonical and hint spellings // that is set, and the empty string where none is. func nameLabel(naming ir.Naming) string { - for _, s := range []string{naming.Source, naming.Canonical, naming.Hint} { - if s != "" { - return strconv.Quote(s) + for _, spelling := range []string{naming.Source, naming.Canonical, naming.Hint} { + if spelling != "" { + return strconv.Quote(spelling) } } return `""` diff --git a/pass/names_inherited.go b/pass/names_inherited.go index b8b31b28c..d80a483b7 100644 --- a/pass/names_inherited.go +++ b/pass/names_inherited.go @@ -89,11 +89,11 @@ func (r *nameReader) spelledTwoWays(first int) bool { // entries counts the composition entries of model: its base, the interfaces it // implements and its mixins. func entries(model *ir.Model) int { - n := len(model.Implements) + len(model.Mixins) + composedCount := len(model.Implements) + len(model.Mixins) if model.Base != nil { - n++ + composedCount++ } - return n + return composedCount } // exposed reads the members the model id exposes as one scope and reports each diff --git a/pass/names_inherited_test.go b/pass/names_inherited_test.go index 5b88782d0..6049b0458 100644 --- a/pass/names_inherited_test.go +++ b/pass/names_inherited_test.go @@ -95,10 +95,10 @@ func TestNames_ReadsAPropertyMeetingOneItsModelInherits(t *testing.T) { // chainOf is n models, each extending the one before it and declaring one // property of a name of its own, so none meets another spelling of a name. -func chainOf(n int) *ir.Document { +func chainOf(count int) *ir.Document { doc := &ir.Document{Types: ir.TypeRegistry{}} base := "" - for i := range n { + for i := range count { id := fmt.Sprintf("M%03d", i) doc.Types[ir.TypeID(id)] = extending(id, base, spelled("property/"+id, fmt.Sprintf("prop%d", i), fmt.Sprintf("prop%d", i))) base = id diff --git a/pass/names_reader.go b/pass/names_reader.go index 35e69b8e4..b11878344 100644 --- a/pass/names_reader.go +++ b/pass/names_reader.go @@ -26,10 +26,12 @@ type nameReader struct { // than the name, since a name compared joined is not a string the scope // holds. seen scratchstate.Map[uint64, int] + // variants maps each type a union's variants name to the first naming it. + variants scratchstate.Map[ir.TypeID, int] // hash makes the keys of seen, under one seed for the whole run, and - // joined holds the words it hashes with their separators left out. - hash maphash.Hash - joined []byte + // hashedWords holds the words it hashes with their separators left out. + hash maphash.Hash + hashedWords []byte // later holds, for each party, the next party named alike, or -1 where // none is. later []int @@ -111,10 +113,10 @@ func (sc scope) at() string { return sc.id } -// idsOf lists n IDs, the ith read through id, for a scope's report, and only -// for one. -func idsOf(n int, id func(i int) string) []string { - ids := make([]string, n) +// idsOf lists count IDs, the ith read through id, for a scope's report, and +// only for one. +func idsOf(count int, id func(i int) string) []string { + ids := make([]string, count) for i := range ids { ids[i] = id(i) } @@ -131,23 +133,23 @@ func (sc scope) label(i int) string { // writeMessagePrefix writes what holds sc, as a message about it begins, or // nothing for a scope the document holds. -func (sc scope) writeMessagePrefix(b *strings.Builder) { +func (sc scope) writeMessagePrefix(builder *strings.Builder) { if sc.in == "" { return } - fmt.Fprintf(b, "in %s %s, ", sc.in, sc.id) + fmt.Fprintf(builder, "in %s %s, ", sc.in, sc.id) if sc.of != "" { - fmt.Fprintf(b, "%s, ", sc.of) + fmt.Fprintf(builder, "%s, ", sc.of) } } -// readScope reads n names, the ith through name, as one scope whose names +// readScope reads count names, the ith through name, as one scope whose names // compare under by, and reports whether it found anything to report. A name is // read by index, never through an element's address or a generic over the // service tree, which servicetreewrites refuses outside ir and the compilers. -func (r *nameReader) readScope(by comparison, n int, name func(i int) ir.Naming) bool { +func (r *nameReader) readScope(by comparison, count int, name func(i int) ir.Naming) bool { r.parties = r.parties[:0] - for i := range n { + for i := range count { r.parties = append(r.parties, partyOf(name(i))) } return r.read(by) @@ -159,8 +161,8 @@ func (r *nameReader) readScope(by comparison, n int, name func(i int) ir.Naming) // nothing, which irverify reports as ir/naming-absent, so it is passed over // here. func (r *nameReader) read(by comparison) bool { - seen, n := r.seen.Emptied(), len(r.parties) - r.later, r.last, r.other = sized(r.later, n), sized(r.last, n), sized(r.other, n) + seen, partyCount := r.seen.Emptied(), len(r.parties) + r.later, r.last, r.other = sized(r.later, partyCount), sized(r.last, partyCount), sized(r.other, partyCount) r.shared, r.bare = r.shared[:0], r.bare[:0] for i, party := range r.parties { r.later[i] = -1 @@ -175,28 +177,28 @@ func (r *nameReader) read(by comparison) bool { return len(r.shared) > 0 || len(r.bare) > 0 } -// sized returns s holding n elements, reusing its array where it can. -func sized(s []int, n int) []int { - return slices.Grow(s[:0], n)[:n] +// sized returns slice holding length elements, reusing its array where it can. +func sized(slice []int, length int) []int { + return slices.Grow(slice[:0], length)[:length] } -// sum hashes the name by compares partyValue by: its words, joined where by +// sum hashes the name by compares party by: its words, joined where by // joins them, or else its spelling. -func (r *nameReader) sum(by comparison, partyValue party) uint64 { +func (r *nameReader) sum(by comparison, party party) uint64 { r.hash.Reset() switch { - case partyValue.words == "": - r.hash.WriteString(partyValue.source) + case party.words == "": + r.hash.WriteString(party.source) case by == byJoinedWords: - r.joined = r.joined[:0] - for i := range len(partyValue.words) { - if partyValue.words[i] != '_' { - r.joined = append(r.joined, partyValue.words[i]) + r.hashedWords = r.hashedWords[:0] + for i := range len(party.words) { + if party.words[i] != '_' { + r.hashedWords = append(r.hashedWords, party.words[i]) } } - r.hash.Write(r.joined) + r.hash.Write(r.hashedWords) default: - r.hash.WriteString(partyValue.words) + r.hash.WriteString(party.words) } return r.hash.Sum64() } @@ -268,11 +270,11 @@ func (r *nameReader) report(sc scope) { r.diags = append(r.diags, diag(ir.SeverityWarning, "pass/name-collision", r.collision(sc, first), sc.at())) } for _, i := range r.bare { - var b strings.Builder - sc.writeMessagePrefix(&b) - fmt.Fprintf(&b, "%s %s (%q) has no word character, so it has no neutral name, and a target names it "+ + var builder strings.Builder + sc.writeMessagePrefix(&builder) + fmt.Fprintf(&builder, "%s %s (%q) has no word character, so it has no neutral name, and a target names it "+ "from its characters", sc.one, sc.label(i), r.parties[i].source) - r.diags = append(r.diags, diag(ir.SeverityInfo, "pass/name-without-words", b.String(), sc.at())) + r.diags = append(r.diags, diag(ir.SeverityInfo, "pass/name-without-words", builder.String(), sc.at())) } } @@ -281,34 +283,34 @@ func (r *nameReader) report(sc scope) { // name they share or, in a scope that compares names joined, the neutral names // that differ only where their words break. func (r *nameReader) collision(sc scope, first int) string { - var b strings.Builder - sc.writeMessagePrefix(&b) - b.WriteString(sc.many) - b.WriteByte(' ') + var builder strings.Builder + sc.writeMessagePrefix(&builder) + builder.WriteString(sc.many) + builder.WriteByte(' ') for i := first; i >= 0; i = r.later[i] { - b.WriteString(separator(i == first, r.later[i] < 0)) - b.WriteString(sc.label(i)) + builder.WriteString(separator(i == first, r.later[i] < 0)) + builder.WriteString(sc.label(i)) if src := r.parties[i].source; src != "" { - fmt.Fprintf(&b, " (%q)", src) + fmt.Fprintf(&builder, " (%q)", src) } } who := "a target" switch words := r.wordsOf(first); len(words) { case 0: - fmt.Fprintf(&b, " share the spelling %q, which has no word character", r.parties[first].source) + fmt.Fprintf(&builder, " share the spelling %q, which has no word character", r.parties[first].source) case 1: - fmt.Fprintf(&b, " share the neutral name %q", words[0]) + fmt.Fprintf(&builder, " share the neutral name %q", words[0]) default: - b.WriteString(" have the neutral names ") - for k, w := range words { - b.WriteString(separator(k == 0, k == len(words)-1)) - fmt.Fprintf(&b, "%q", w) + builder.WriteString(" have the neutral names ") + for k, word := range words { + builder.WriteString(separator(k == 0, k == len(words)-1)) + fmt.Fprintf(&builder, "%q", word) } - b.WriteString(", which differ only where their words break") + builder.WriteString(", which differ only where their words break") who = "a target that joins words or ignores letter case" } - fmt.Fprintf(&b, ", so %s can tell them apart only by %s", who, cmp.Or(sc.apart, "ID")) - return b.String() + fmt.Fprintf(&builder, ", so %s can tell them apart only by %s", who, cmp.Or(sc.apart, "ID")) + return builder.String() } // wordsOf lists the neutral words of the parties named alike from first, each @@ -319,9 +321,9 @@ func (r *nameReader) wordsOf(first int) []string { var words []string listed := map[string]bool{} for i := first; i >= 0; i = r.later[i] { - if w := r.parties[i].words; w != "" && !listed[w] { - listed[w] = true - words = append(words, w) + if partyWords := r.parties[i].words; partyWords != "" && !listed[partyWords] { + listed[partyWords] = true + words = append(words, partyWords) } } return words diff --git a/pass/names_reader_internal_test.go b/pass/names_reader_internal_test.go index 26d1eaa36..88feab8b6 100644 --- a/pass/names_reader_internal_test.go +++ b/pass/names_reader_internal_test.go @@ -36,16 +36,16 @@ func TestNameReader_PlacesANameByItselfWhereOnlyItsHashAgrees(t *testing.T) { } { t.Run(tt.name, func(t *testing.T) { t.Parallel() - n := len(tt.parties) - nameReaderValue := nameReader{parties: tt.parties, later: make([]int, n), last: make([]int, n), other: make([]int, n)} + count := len(tt.parties) + nameReader := nameReader{parties: tt.parties, later: make([]int, count), last: make([]int, count), other: make([]int, count)} seen := map[uint64]int{} for i := range tt.parties { - nameReaderValue.later[i] = -1 - nameReaderValue.place(tt.by, seen, 7, i) + nameReader.later[i] = -1 + nameReader.place(tt.by, seen, 7, i) } - assert.Empty(t, cmp.Diff(tt.wantLater, nameReaderValue.later), "each party's next party named alike") - assert.Empty(t, cmp.Diff(tt.wantShared, nameReaderValue.shared), "each set's first party, by its second") + assert.Empty(t, cmp.Diff(tt.wantLater, nameReader.later), "each party's next party named alike") + assert.Empty(t, cmp.Diff(tt.wantShared, nameReader.shared), "each set's first party, by its second") }) } } diff --git a/pass/names_test.go b/pass/names_test.go index 6551fa932..da001688f 100644 --- a/pass/names_test.go +++ b/pass/names_test.go @@ -70,8 +70,8 @@ func inGroup(operationGroup ir.OperationGroup) *ir.Document { // withTypes is a document holding types. func withTypes(types ...ir.TypeDef) *ir.Document { doc := &ir.Document{Types: ir.TypeRegistry{}} - for _, td := range types { - doc.Types[td.Common().ID] = td + for _, typeDef := range types { + doc.Types[typeDef.Common().ID] = typeDef } return doc } @@ -151,6 +151,10 @@ func TestNames_ReportsEachScope(t *testing.T) { byPosition("op", `in parameter choice 0 of operation op, variants 0 ("fromTo") and 1 ("from_to") share the `+ `neutral name "from_to"`), }}, + {"a union's variants, a type listed twice read once and kept first", withTypes(&ir.Union{ID: "type/u", Name: named("U"), + Variants: []ir.Variant{{Name: hinted("apple"), Type: ir.TypeRef{Target: "type/a"}}, + {Name: hinted("apple"), Type: ir.TypeRef{Target: "type/b"}}, {Name: hinted("apple"), Type: ir.TypeRef{Target: "type/a"}}}}), + []ir.Diagnostic{collision("type/u", `in union type/u, variants type/a and type/b share the neutral name "apple"`)}}, {"a union's variants whose words break apart", withTypes(&ir.Union{ID: "type/u", Name: named("U"), Variants: []ir.Variant{{Name: hinted("credit_card"), Type: ir.TypeRef{Target: "type/a"}}, {Name: hinted("creditcard"), Type: ir.TypeRef{Target: "type/b"}}}}), @@ -291,14 +295,14 @@ func TestNames_RunReportsNothingOnceItsContextIsDone(t *testing.T) { require.NotEmpty(t, diags, "the last family has a finding a cut run could leak") require.Equal(t, pass.NameFamilies()+1, whole.Calls, "a check before each family and after the last") - for left := range whole.Calls { - ctx := &ctxtest.Countdown{Context: t.Context(), Left: left} + for baseCountsToDrop := range whole.Calls { + ctx := &ctxtest.Countdown{Context: t.Context(), Left: baseCountsToDrop} out, diags := pass.Names{}.Run(ctx, doc) assert.Same(t, doc, out) - require.Nil(t, diags, "check %d", left+1) - require.Equal(t, left+1, ctx.Calls, "check %d: asked on after the refusal", left+1) + require.Nil(t, diags, "check %d", baseCountsToDrop+1) + require.Equal(t, baseCountsToDrop+1, ctx.Calls, "check %d: asked on after the refusal", baseCountsToDrop+1) } } @@ -312,15 +316,15 @@ func TestNames_NameIsStable(t *testing.T) { // group, the group's operation and the operation's parameter, a model with a // property, an enum with a member, a union with a variant, and an auth scheme, // no two names of a scope alike. -func soundNames(n int) *ir.Document { +func soundNames(count int) *ir.Document { doc := &ir.Document{Types: ir.TypeRegistry{}, Auth: map[ir.AuthID]ir.AuthScheme{}} - for i := range n { + for i := range count { word := fmt.Sprintf("n%d", i) doc.Services = append(doc.Services, ir.Service{ID: ir.ServiceID("service/" + word), Name: named(word), Groups: []ir.OperationGroup{{ID: ir.GroupID("operation-group/" + word), Name: named(word), Operations: []ir.Operation{{ID: ir.OperationID("operation/" + word), Name: named(word), Params: []ir.Parameter{{ID: ir.ParameterID("parameter/" + word), Name: named(word)}}}}}}}) - for _, td := range []ir.TypeDef{ + for _, typeDef := range []ir.TypeDef{ &ir.Model{ID: ir.TypeID("type/m/" + word), Name: named("m" + word), Properties: []ir.Property{{ID: ir.PropertyID("property/" + word), Name: named(word)}}}, &ir.Enum{ID: ir.TypeID("type/e/" + word), Name: named("e" + word), @@ -328,7 +332,7 @@ func soundNames(n int) *ir.Document { &ir.Union{ID: ir.TypeID("type/u/" + word), Name: named("u" + word), Variants: []ir.Variant{{Name: hinted(word)}}}, } { - doc.Types[td.Common().ID] = td + doc.Types[typeDef.Common().ID] = typeDef } doc.Auth[ir.AuthID("auth/"+word)] = ir.AuthScheme{ID: ir.AuthID("auth/" + word), Name: named(word)} } diff --git a/pass/validate.go b/pass/validate.go index 61ce523be..e9740ec91 100644 --- a/pass/validate.go +++ b/pass/validate.go @@ -126,6 +126,7 @@ func withoutEmptyKeys(doc *ir.Document) (*ir.Document, []ir.Diagnostic) { func families(doc *ir.Document, read walked, facts *irfacts.DocumentFacts) []func() []ir.Diagnostic { // Sorted once for the run, and written by no family. live := liveTypeIDs(doc) + chains := newAliasChains(doc) // A family that ranges a map sorts its keys first. A new family takes a row of // twoFindings in validate_determinism_test.go, which holds it to one order. return []func() []ir.Diagnostic{ @@ -134,11 +135,11 @@ func families(doc *ir.Document, read walked, facts *irfacts.DocumentFacts) []fun func() []ir.Diagnostic { return checkEmptyRefs(read.empty) }, func() []ir.Diagnostic { return checkGroupWalkTruncated(facts, read.truncated) }, func() []ir.Diagnostic { return checkResponseIndices(doc) }, - func() []ir.Diagnostic { return checkEncodingKeys(doc, facts) }, - func() []ir.Diagnostic { return checkCatchAllEncodingKeys(doc) }, + func() []ir.Diagnostic { return checkEncodingKeys(doc, facts, chains) }, + func() []ir.Diagnostic { return checkCatchAllEncodingKeys(doc, chains) }, func() []ir.Diagnostic { return checkPayloadRequired(doc) }, func() []ir.Diagnostic { return checkPropertyIDRefs(read.properties, read.refs, read.truncated) }, - func() []ir.Diagnostic { return checkDiscriminators(doc, live, facts) }, + func() []ir.Diagnostic { return checkDiscriminators(doc, live, facts, chains) }, func() []ir.Diagnostic { return checkRepeatedVariants(doc, live) }, func() []ir.Diagnostic { return checkDuplicateWireNames(doc, live) }, func() []ir.Diagnostic { return checkAmbiguousAliases(doc, live) }, @@ -149,9 +150,10 @@ func families(doc *ir.Document, read walked, facts *irfacts.DocumentFacts) []fun func() []ir.Diagnostic { return checkOneWay(doc) }, func() []ir.Diagnostic { return checkDefaultResponses(doc) }, func() []ir.Diagnostic { return checkArgsOutsideGraphQL(doc, live) }, - func() []ir.Diagnostic { return checkBounds(doc, live) }, - func() []ir.Diagnostic { return checkValues(doc, live) }, - func() []ir.Diagnostic { return checkCompositionCyclesAndInfiniteTypes(doc, live) }, + func() []ir.Diagnostic { return checkBounds(doc, chains, live) }, + func() []ir.Diagnostic { return checkMembersOutsideBounds(doc, chains, live) }, + func() []ir.Diagnostic { return checkValues(doc, chains, live) }, + func() []ir.Diagnostic { return checkCompositionCyclesAndInfiniteTypes(doc, chains, live) }, } } @@ -169,11 +171,11 @@ type walked struct { // ctx's error alone if the walk stopped at it. func walkDocument(ctx context.Context, doc *ir.Document, walk walkFunc) (walked, error) { refs := ir.NewIDReferences(doc) - walkedValue := walked{refs: refs, properties: &propertyIDSites{refs: refs}, empty: &ir.EmptyReferences{}} - truncated, err := walk(ctx, doc, ir.DocumentPath, walkedValue.refs, walkedValue.properties, walkedValue.empty) + state := walked{refs: refs, properties: &propertyIDSites{refs: refs}, empty: &ir.EmptyReferences{}} + truncated, err := walk(ctx, doc, ir.DocumentPath, state.refs, state.properties, state.empty) if err != nil { return walked{}, err } - walkedValue.truncated = truncated - return walkedValue, nil + state.truncated = truncated + return state, nil } diff --git a/pass/validate_admission_test.go b/pass/validate_admission_test.go new file mode 100644 index 000000000..9c15ecee0 --- /dev/null +++ b/pass/validate_admission_test.go @@ -0,0 +1,378 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass_test + +import ( + "encoding/json/jsontext" + "fmt" + "slices" + "strconv" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irtest" + "github.com/dexpace/morphic/pass" +) + +// budgetCode is the error a value draws where the run's value judgments run +// out at it. +const budgetCode = "pass/budget-exceeded" + +// object is an object value holding each name beside the value after it. +func object(namesAndValues ...any) *ir.Value { + value := &ir.Value{Kind: ir.ValueObject} + for i := 0; i+1 < len(namesAndValues); i += 2 { + name, _ := namesAndValues[i].(string) + member, _ := namesAndValues[i+1].(*ir.Value) + value.Object = append(value.Object, ir.Field{Name: name, Value: *member}) + } + return value +} + +// admissionTypes are the types the admission rows judge values against: +// unions of primitives, models judged by their composition (B typing every +// member beside a as a string, C composing it, D requiring z, CB closed after +// composition over B), a model composing one that keeps a validation-only +// entry, models whose member is of an alias of the top type, an alias whose +// Base admits null, a list and a map of integers, and a step. +func admissionTypes() []ir.TypeDef { + text, integer := stringT, intT + model := func(id ir.TypeID, set func(*ir.Model), properties ...ir.Property) *ir.Model { + model := &ir.Model{ID: id, Properties: properties, Provenance: provAt(string(id))} + if set != nil { + set(model) + } + return model + } + member := func(owner, name string, typ ir.TypeRef, required bool) ir.Property { + return ir.Property{ID: ir.PropertyID("property/" + owner + "/" + name), WireName: name, Type: typ, Required: required, + Provenance: provAt("property/" + owner + "/" + name)} + } + union := func(id ir.TypeID, oneOf bool, variants ...ir.TypeRef) *ir.Union { + union := &ir.Union{ID: id, Exclusive: oneOf, Closed: true, Provenance: provAt(string(id))} + for _, variant := range variants { + union.Variants = append(union.Variants, ir.Variant{Type: variant}) + } + return union + } + ref := func(id ir.TypeID) ir.TypeRef { return ir.TypeRef{Target: id} } + return []ir.TypeDef{ + union("type/oneOfIntString", true, integer, text), + union("type/anyOfIntString", false, integer, text), + &ir.Scalar{ID: "type/short", Base: &text, Constraints: lengths(0, 3), Provenance: provAt("type/short")}, + union("type/oneOfOverlap", true, text, ref("type/short")), + model("type/Bars", nil, member("Bars", "bar", integer, true)), + model("type/Foos", nil, member("Foos", "foo", text, true)), + union("type/S", true, ref("type/Bars"), ref("type/Foos")), + model("type/B", func(model *ir.Model) { model.AdditionalProperties = &ir.AdditionalProperties{Value: &text} }, member("B", "a", integer, false)), + model("type/C", func(model *ir.Model) { model.Base = new(ref("type/B")) }, member("C", "c", boolT, false)), + model("type/D", nil, member("D", "z", integer, true)), + model("type/CB", func(model *ir.Model) { + model.Base = new(ref("type/B")) + model.Additional = ir.AdditionalClosedAfterComposition + }), + union("type/CorD", true, ref("type/C"), ref("type/D")), + model("type/NotB", func(model *ir.Model) { + model.Unmodeled = ir.Unmodeled{"openapi:not": {Reason: ir.ReasonValidationOnly, Value: ir.RawValue(`{"required":["b"]}`)}} + }, member("NotB", "b", integer, false)), + model("type/OverNotB", func(model *ir.Model) { model.Base = new(ref("type/NotB")) }), + model("type/RequiresB", nil, member("RequiresB", "b", integer, true)), + union("type/OverNotBorRequiresB", true, ref("type/OverNotB"), ref("type/RequiresB")), + &ir.Scalar{ID: "type/P", Base: &anyT, Constraints: lengths(5, 100), Provenance: provAt("type/P")}, + model("type/M1", nil, member("M1", "p", ref("type/P"), true)), + model("type/M2", nil, member("M2", "p", text, true)), + union("type/M1orM2", true, ref("type/M1"), ref("type/M2")), + &ir.Scalar{ID: "type/nullableBase", Base: &ir.TypeRef{Target: text.Target, Nullable: true}, Constraints: lengths(0, 9), + Provenance: provAt("type/nullableBase")}, + &ir.List{ID: "type/integers", ElementType: integer, Provenance: provAt("type/integers")}, + &ir.MapT{ID: "type/integerMap", Value: integer, Provenance: provAt("type/integerMap")}, + &ir.Scalar{ID: "type/threes", Base: &integer, Constraints: withMultiple(&ir.Constraints{}, "3"), Provenance: provAt("type/threes")}, + } +} + +// admissionDoc is a document whose one property, typed typ, writes value as +// its default, beside every type admissionTypes holds. +func admissionDoc(typ ir.TypeRef, value *ir.Value) *ir.Document { + return admissionDocOf(property("property/a/v", typ, defaulted(value))) +} + +// admissionDocOf is a document holding properties on one model, beside every +// type admissionTypes holds. +func admissionDocOf(properties ...ir.Property) *ir.Document { + doc := modelOf(properties...) + doc.Types[ir.PrimitiveTypeID(ir.PrimitiveString)] = &ir.Primitive{ID: ir.PrimitiveTypeID(ir.PrimitiveString), PrimitiveKind: ir.PrimitiveString} + for _, typeDef := range admissionTypes() { + doc.Types[typeDef.Common().ID] = typeDef + } + return doc +} + +// TestValidate_ADefaultIsJudgedByTheOneValueAdmissionReader holds a default to +// what the one value admission reader says of its type, reported where it says +// no: a union by its variants, a Model by its composition, a list's elements, a +// map's members and a step, and nothing where a fact it cannot read, a +// validation-only Unmodeled entry on a composed model among them, leaves it +// unknown. The message is the reader's to word; the row holds where. +func TestValidate_ADefaultIsJudgedByTheOneValueAdmissionReader(t *testing.T) { + t.Parallel() + ref := func(id ir.TypeID) ir.TypeRef { return ir.TypeRef{Target: id} } + two, abcd := number("2"), text("abcd") + for _, tc := range []struct { + name string + typ ir.TypeRef + value *ir.Value + refused bool + }{ + {"true for oneOf [integer, string]", ref("type/oneOfIntString"), &ir.Value{Kind: ir.ValueBool, Bool: true}, true}, + {"true for anyOf [integer, string]", ref("type/anyOfIntString"), &ir.Value{Kind: ir.ValueBool, Bool: true}, true}, + {"a number one variant admits", ref("type/oneOfIntString"), number("3"), false}, + {"a string two variants of a oneOf admit", ref("type/oneOfOverlap"), text("ab"), true}, + {"a string only one of them admits", ref("type/oneOfOverlap"), abcd, false}, + {"the suite's oneOf complex types, one variant matching", ref("type/S"), object("bar", two), false}, + {"neither matching", ref("type/S"), object(), true}, + {"both matching", ref("type/S"), object("foo", text("x"), "bar", two), true}, + {"a member B's catch-all types as a string, on C", ref("type/C"), object("z", number("1")), true}, + {"C's own member, refused by B's catch-all", ref("type/C"), object("c", &ir.Value{Kind: ir.ValueBool, Bool: true}), true}, + {"that member for oneOf [C, D], which D admits", ref("type/CorD"), object("z", number("1")), false}, + {"a member B's catch-all evaluates, on CB", ref("type/CB"), object("a", number("1"), "z", text("x")), false}, + {"a member a validation-only entry on a composed model could refuse", ref("type/OverNotBorRequiresB"), object("b", number("1")), false}, + {"a member of an alias of the top type, read by its bounds", ref("type/M1orM2"), object("p", text("ab")), false}, + {"one both variants then admit", ref("type/M1orM2"), object("p", text("abcdef")), true}, + {"null on a reference to an alias whose Base admits null", ref("type/nullableBase"), null(), true}, + {"a list holding what is no integer", ref("type/integers"), &ir.Value{Kind: ir.ValueList, List: []ir.Value{*text("a")}}, true}, + {"a list of integers", ref("type/integers"), &ir.Value{Kind: ir.ValueList, List: []ir.Value{*two}}, false}, + {"a map holding what is no integer", ref("type/integerMap"), object("k", text("a")), true}, + {"a number off its step", ref("type/threes"), number("4"), true}, + {"a number on it", ref("type/threes"), number("6"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := found(t, admissionDoc(tc.typ, tc.value), defaultCode) + if !tc.refused { + assert.Empty(t, got) + return + } + if assert.Len(t, got, 1) { + assert.Equal(t, "property/a/v", got[0].node) + } + }) + } +} + +// TestValidate_AnExampleIsJudgedByTheOneValueAdmissionReader holds an example +// to the same reader as a default, at a union and at a model's composition. +func TestValidate_AnExampleIsJudgedByTheOneValueAdmissionReader(t *testing.T) { + t.Parallel() + doc := admissionDoc(ir.TypeRef{Target: "type/oneOfIntString"}, nil) + model, ok := doc.Types["type/a"].(*ir.Model) + if !assert.True(t, ok) { + return + } + exampled(&ir.Value{Kind: ir.ValueBool, Bool: true}, number("3"))(&model.Properties[0]) + got := found(t, doc, exampleCode) + if assert.Len(t, got, 1, "the bool alone is refused") { + assert.Equal(t, "property/a/v", got[0].node) + } +} + +// TestValidate_AValueOnlyAKeptEntryRefusesDrawsNothing pins what pass gives up +// by holding no source format: a bound kept verbatim beside a type it +// does not type is unread, so an over-long instant draws nothing, alone or as +// a variant beside a string, until the bound is typed. +func TestValidate_AValueOnlyAKeptEntryRefusesDrawsNothing(t *testing.T) { + t.Parallel() + instant := ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveDatetimeOffset)} + kept := &ir.Scalar{ID: "type/instant", Base: &instant, Provenance: provAt("type/instant"), + Unmodeled: ir.Unmodeled{"openapi:maxLength": {Reason: ir.ReasonNoIRHome, Value: ir.RawValue(`5`)}}} + either := &ir.Union{ID: "type/either", Exclusive: true, Closed: true, Provenance: provAt("type/either"), + Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/instant"}}, {Type: stringT}}} + for _, typ := range []ir.TypeRef{{Target: "type/instant"}, {Target: "type/either"}} { + doc := admissionDoc(typ, text("2024-01-01T00:00:00Z")) + doc.Types[instant.Target] = &ir.Primitive{ID: instant.Target, PrimitiveKind: ir.PrimitiveDatetimeOffset} + doc.Types[kept.ID], doc.Types[either.ID] = kept, either + assert.Empty(t, found(t, doc, defaultCode), "%s", typ.Target) + } +} + +// TestValidate_AStringBoundJudgesTheTextMembersOfAValueSet holds a member of a +// value set to the bound the set holds of its text: a string enum's and a +// union of literals' maxLength refuses a default too long, as each lowers +// from {type: string, enum: [ab, abc], maxLength: 2} and {enum: [ab, abc, 1], +// maxLength: 2}, and judges no member of another kind, so 1 is admitted. +func TestValidate_AStringBoundJudgesTheTextMembersOfAValueSet(t *testing.T) { + t.Parallel() + bound := lengths(0, 2) + literal := func(id ir.TypeID, value *ir.Value) *ir.Literal { + return &ir.Literal{ID: id, Value: *value, Provenance: provAt(string(id))} + } + enum := &ir.Enum{ID: "type/texts", ValueType: ir.PrimitiveString, Closed: true, Constraints: bound, Provenance: provAt("type/texts"), + Members: []ir.EnumMember{{ID: "enummember/texts/ab", Value: *text("ab")}, {ID: "enummember/texts/abc", Value: *text("abc")}}} + literals := []ir.TypeDef{literal("type/ab", text("ab")), literal("type/abc", text("abc")), literal("type/one", number("1"))} + union := &ir.Union{ID: "type/mixed", Exclusive: true, Closed: true, Constraints: bound, Provenance: provAt("type/mixed")} + for _, member := range literals { + union.Variants = append(union.Variants, ir.Variant{Type: ir.TypeRef{Target: member.Common().ID}}) + } + for _, tc := range []struct { + name string + target ir.TypeID + nullable bool + value *ir.Value + refused bool + }{ + {"a string enum's member past its maxLength", enum.ID, false, text("abc"), true}, + {"a string enum's member within it", enum.ID, false, text("ab"), false}, + {"null where the reference to the enum admits it", enum.ID, true, null(), false}, + {"a union of literals' text member past its maxLength", union.ID, false, text("abc"), true}, + {"a union of literals' text member within it", union.ID, false, text("ab"), false}, + {"a union of literals' number member, which no length bounds", union.ID, false, number("1"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + doc := admissionDoc(ir.TypeRef{Target: tc.target, Nullable: tc.nullable}, tc.value) + doc.Types[enum.ID], doc.Types[union.ID] = enum, union + for _, member := range literals { + doc.Types[member.Common().ID] = member + } + got := found(t, doc, defaultCode) + if !tc.refused { + assert.Empty(t, got) + return + } + if assert.Len(t, got, 1) { + assert.Equal(t, "property/a/v", got[0].node) + } + }) + } +} + +// TestValidate_AnExternalTypeIsNotJudged pins that a value of an external type, +// which the IR describes by an identity alone, draws nothing, null included. +func TestValidate_AnExternalTypeIsNotJudged(t *testing.T) { + t.Parallel() + for _, value := range []*ir.Value{null(), {Kind: ir.ValueBool, Bool: true}} { + doc := admissionDoc(ir.TypeRef{Target: "type/external"}, value) + doc.Types["type/external"] = &ir.External{ID: "type/external", Identity: "erlang:pid", Provenance: provAt("type/external")} + assert.Empty(t, found(t, doc, defaultCode), "%v", value.Kind) + } +} + +// TestValidate_NullIsJudgedByAUnionsVariants pins null under a union: admitted +// where a variant's reference admits it, though the reference to the union +// does not, and reported where none does. +func TestValidate_NullIsJudgedByAUnionsVariants(t *testing.T) { + t.Parallel() + nullableText := ir.TypeRef{Target: stringT.Target, Nullable: true} + for _, tc := range []struct { + name string + variant ir.TypeRef + refused bool + }{ + {"a variant admitting null", nullableText, false}, + {"no variant admitting null", stringT, true}, + } { + doc := admissionDoc(ir.TypeRef{Target: "type/nullUnion"}, null()) + doc.Types["type/nullUnion"] = &ir.Union{ID: "type/nullUnion", Exclusive: true, Closed: true, Provenance: provAt("type/nullUnion"), + Variants: []ir.Variant{{Type: tc.variant}, {Type: intT}}} + got := found(t, doc, defaultCode) + assert.Equal(t, tc.refused, len(got) == 1, tc.name) + } +} + +// TestValidate_AValueOfAnotherKindThanAHeuristicShapeDrawsNothing pins a +// default of another kind than a model or list a heuristic shaped +// (Provenance.Inferred): the source may admit every kind, so it draws nothing, +// while the same node unmarked refuses it, and one of the node's own kind is +// still judged. +func TestValidate_AValueOfAnotherKindThanAHeuristicShapeDrawsNothing(t *testing.T) { + t.Parallel() + shaped := ir.Provenance{Pointer: "/shaped", Inferred: "kind-inference"} + for _, tc := range []struct { + name string + node ir.TypeDef + value *ir.Value + refused bool + }{ + {"a string against a shaped model", &ir.Model{ID: "type/n", Provenance: shaped}, text("s"), false}, + {"a string against a shaped list", &ir.List{ID: "type/n", ElementType: stringT, Provenance: shaped}, text("s"), false}, + {"null against a shaped model", &ir.Model{ID: "type/n", Provenance: shaped}, null(), false}, + {"null against an unmarked model", &ir.Model{ID: "type/n", Provenance: provAt("type/n")}, null(), true}, + {"a string against an unmarked model", &ir.Model{ID: "type/n", Provenance: provAt("type/n")}, text("s"), true}, + {"a list holding no string against a shaped list", &ir.List{ID: "type/n", ElementType: stringT, Provenance: shaped}, + &ir.Value{Kind: ir.ValueList, List: []ir.Value{*number("1")}}, true}, + } { + doc := admissionDoc(ir.TypeRef{Target: "type/n"}, tc.value) + doc.Types["type/n"] = tc.node + got := found(t, doc, defaultCode) + assert.Equal(t, tc.refused, len(got) == 1, tc.name) + } +} + +// TestValidate_ValuesPastTheJudgmentBudgetGoUnjudged holds the run's value +// judgments to their budget, over three defaults typed by a oneOf of two +// models, the last of which it refuses, at every budget up to the one judging +// them all: the value a budget runs out at draws one pass/budget-exceeded +// error, the values before it are judged and those after it are not, the +// refused one among them. Validate's own budget judges every one. +func TestValidate_ValuesPastTheJudgmentBudgetGoUnjudged(t *testing.T) { + t.Parallel() + union := ir.TypeRef{Target: "type/S"} + doc := admissionDocOf(property("property/a/1", union, defaulted(object("bar", number("2")))), + property("property/a/2", union, defaulted(object("foo", text("x")))), property("property/a/3", union, defaulted(object()))) + whole := pass.ValueFindingsWithin(doc, pass.MaxValueJudgments) + require.Equal(t, []string{defaultCode}, irtest.DiagCodes(whole)) + require.Equal(t, "property/a/3", whole[0].Provenance.Node) + assert.Equal(t, whole, withCode(validated(t, doc), defaultCode), "Validate judges every value") + assert.Empty(t, withCode(validated(t, doc), budgetCode)) + + var ranOut []string + for judgments := 0; ; judgments++ { + require.Less(t, judgments, 64, "three defaults judged in so few judgments") + findings := pass.ValueFindingsWithin(doc, judgments) + if cmp.Diff(whole, findings) == "" { + break + } + require.Equal(t, []string{budgetCode}, irtest.DiagCodes(findings), "at %d judgments", judgments) + finding := findings[0] + assert.Equal(t, ir.SeverityError, finding.Severity) + assert.Equal(t, ir.Provenance{Pointer: jsontext.Pointer("/" + finding.Provenance.Node), Node: finding.Provenance.Node}, + finding.Provenance, "the finding carries its value's provenance, with the node set") + assert.Contains(t, finding.Message, strconv.Itoa(pass.MaxValueJudgments)) + ranOut = append(ranOut, finding.Provenance.Node) + } + assert.Equal(t, []string{"property/a/1", "property/a/2", "property/a/3"}, slices.Compact(slices.Clone(ranOut)), + "each budget runs out at a value no earlier than a smaller one does: %v", ranOut) +} + +// TestValidate_ManyDefaultsOverAOneOfOfManyModelsStayWithinTheBudget holds +// the run's value judgments to a bound valid documents do not meet: 1,000 +// defaults, each typed by a oneOf of 2,000 models, each model requiring a +// member of its own and each default holding one, are judged whole, every one +// admitted and none past the budget. +func TestValidate_ManyDefaultsOverAOneOfOfManyModelsStayWithinTheBudget(t *testing.T) { + t.Parallel() + const models, defaults = 2000, 1000 + union := &ir.Union{ID: "type/U", Exclusive: true, Closed: true, Provenance: provAt("type/U")} + properties := make([]ir.Property, 0, defaults) + for j := range defaults { + member := fmt.Sprintf("k%d", j%models) + properties = append(properties, property(fmt.Sprintf("property/a/p%d", j), ir.TypeRef{Target: union.ID}, + defaulted(object(member, text("x"))))) + } + doc := modelOf(properties...) + doc.Types[ir.PrimitiveTypeID(ir.PrimitiveString)] = &ir.Primitive{ID: ir.PrimitiveTypeID(ir.PrimitiveString), PrimitiveKind: ir.PrimitiveString} + for i := range models { + id := ir.TypeID(fmt.Sprintf("type/M%d", i)) + name := fmt.Sprintf("k%d", i) + doc.Types[id] = &ir.Model{ID: id, Provenance: provAt(string(id)), Properties: []ir.Property{{ + ID: ir.PropertyID("property/M" + strconv.Itoa(i) + "/" + name), WireName: name, Type: stringT, Required: true, + Provenance: provAt("property/M" + strconv.Itoa(i) + "/" + name)}}} + union.Variants = append(union.Variants, ir.Variant{Type: ir.TypeRef{Target: id}}) + } + doc.Types[union.ID] = union + assert.Empty(t, pass.ValueFindingsWithin(doc, pass.MaxValueJudgments)) +} diff --git a/pass/validate_bounds.go b/pass/validate_bounds.go index ac87eb8bc..16ce972a7 100644 --- a/pass/validate_bounds.go +++ b/pass/validate_bounds.go @@ -14,9 +14,9 @@ import ( type shape uint8 const ( - // shapeNotChecked is a type the checks read no further: an enum, a literal, - // a union, an external type, a scalar with no base, and one nothing - // declares. + // shapeNotChecked is a type the checks read no further: an enum, whose + // values enumRefusal judges, a literal, a union, an external type, a scalar + // with no base, and one nothing declares. shapeNotChecked shape = iota shapeNumber shapeInteger @@ -28,10 +28,6 @@ const ( shapeAnything ) -// maxAliasHops bounds how many alias scalars settle follows, so a cycle of -// aliases ends. -const maxAliasHops = 64 - // primitiveShape is the shape of a primitive of kind primitiveKind. Every kind // has one: TestPrimitiveShapes_EveryPrimitiveKindHasARow holds the cases to the // kinds ir declares. @@ -56,38 +52,45 @@ func primitiveShape(primitiveKind ir.PrimitiveKind) shape { } } -// bounds holds the tightest of each bound the positions of a chain of types -// declare together, so a value must meet every one. The numeric ends are held -// as numbers and as written, for a message to quote; the counts point at the -// document's own fields, so holding them allocates nothing. +// bounds is what one set of bounds holds a value to, the intersection of every +// set the value is held to (boundSets.bounds), read off source. The numeric +// ends are held as numbers and as written, for a message to quote; the counts +// and the step point at the set's own fields, so holding them allocates +// nothing. type bounds struct { + source *ir.Constraints lo, hi ir.Decimal loText, hiText ir.BigVal loSet, hiSet bool - loOpen, hiOpen bool + loExclusive, hiExclusive bool minLen, maxLen *int64 minItems, maxItems *int64 minProperties, maxProperties *int64 + step *ir.BigVal } -// and conjoins the bounds constraints declares into b. A numeric bound that -// does not parse is passed over: irverify reports it. -func (b *bounds) and(constraints *ir.Constraints) { +// boundsOf reads the bounds constraints declares, a nil set declaring none: +// of a bound and its exclusive form, the tighter. A numeric bound that does +// not parse is passed over: irverify reports it. +func boundsOf(constraints *ir.Constraints) bounds { + read := bounds{source: constraints} if constraints == nil { - return + return read } - b.raise(constraints.Min, false) - b.raise(constraints.ExclusiveMin, true) - b.lower(constraints.Max, false) - b.lower(constraints.ExclusiveMax, true) - b.minLen, b.maxLen = greater(b.minLen, constraints.MinLength), lesser(b.maxLen, constraints.MaxLength) - b.minItems, b.maxItems = greater(b.minItems, constraints.MinItems), lesser(b.maxItems, constraints.MaxItems) - b.minProperties, b.maxProperties = greater(b.minProperties, constraints.MinProperties), lesser(b.maxProperties, constraints.MaxProperties) + read.raise(constraints.Min, false) + read.raise(constraints.ExclusiveMin, true) + read.lower(constraints.Max, false) + read.lower(constraints.ExclusiveMax, true) + read.minLen, read.maxLen = constraints.MinLength, constraints.MaxLength + read.minItems, read.maxItems = constraints.MinItems, constraints.MaxItems + read.minProperties, read.maxProperties = constraints.MinProperties, constraints.MaxProperties + read.step = constraints.MultipleOf + return read } // raise takes bigVal as the lower end where it is greater than the one held, or // equal to it and exclusive. -func (b *bounds) raise(bigVal *ir.BigVal, open bool) { +func (b *bounds) raise(bigVal *ir.BigVal, exclusive bool) { if bigVal == nil { return } @@ -95,14 +98,14 @@ func (b *bounds) raise(bigVal *ir.BigVal, open bool) { if err != nil { return } - if c := decimal.Cmp(b.lo); !b.loSet || c > 0 || (c == 0 && open) { - b.lo, b.loText, b.loSet, b.loOpen = decimal, *bigVal, true, open + if order := decimal.Cmp(b.lo); !b.loSet || order > 0 || (order == 0 && exclusive) { + b.lo, b.loText, b.loSet, b.loExclusive = decimal, *bigVal, true, exclusive } } // lower takes bigVal as the upper end where it is less than the one held, or // equal to it and exclusive. -func (b *bounds) lower(bigVal *ir.BigVal, open bool) { +func (b *bounds) lower(bigVal *ir.BigVal, exclusive bool) { if bigVal == nil { return } @@ -110,101 +113,40 @@ func (b *bounds) lower(bigVal *ir.BigVal, open bool) { if err != nil { return } - if c := decimal.Cmp(b.hi); !b.hiSet || c < 0 || (c == 0 && open) { - b.hi, b.hiText, b.hiSet, b.hiOpen = decimal, *bigVal, true, open + if order := decimal.Cmp(b.hi); !b.hiSet || order < 0 || (order == 0 && exclusive) { + b.hi, b.hiText, b.hiSet, b.hiExclusive = decimal, *bigVal, true, exclusive } } -// greater returns the greater of two minimums, either of which may be unset. -func greater(a, b *int64) *int64 { - if a == nil || (b != nil && *b > *a) { - return b - } - return a +// empty reports whether the bounds b holds admit no value of the given shape, +// as ir reads them (ir.ConstraintsAdmitNoValue). +func (b *bounds) empty(shape shape) bool { + return ir.ConstraintsAdmitNoValue(b.source, shapeKind(shape)) } -// lesser returns the lesser of two maximums, either of which may be unset. -func lesser(a, b *int64) *int64 { - if a == nil || (b != nil && *b < *a) { - return b - } - return a -} - -// settle follows alias scalars from target for at most maxAliasHops hops, -// conjoining what each declares into b, and returns the shape the value is, the -// type the chain ends at, and whether a scalar or list on the way holds an -// encoding. The type is nil where the chain meets nothing declared or runs past -// the hops, and the shape then is shapeNotChecked. -func settle(doc *ir.Document, target ir.TypeID, b *bounds) (shape, ir.TypeDef, bool) { - encoded := false - for range maxAliasHops { - td := doc.Types[target] - if ir.IsNilTypeDef(td) { - return shapeNotChecked, nil, encoded - } - switch t := td.(type) { - case *ir.Scalar: - b.and(t.Constraints) - encoded = encoded || t.Encoding != nil - if t.Base == nil { - return shapeNotChecked, td, encoded - } - target = t.Base.Target - case *ir.Primitive: - return primitiveShape(t.PrimitiveKind), td, encoded - case *ir.List: - b.and(t.Constraints) - return shapeList, td, encoded || t.Encoding != nil - case *ir.Tuple: - b.and(t.Constraints) - return shapeList, td, encoded - case *ir.Model: - b.and(t.Constraints) - return shapeObject, td, encoded - case *ir.MapT: - b.and(t.Constraints) - return shapeObject, td, encoded - case *ir.Any: - return shapeAnything, td, encoded - default: - return shapeNotChecked, td, encoded - } - } - return shapeNotChecked, nil, encoded -} - -// empty reports whether the bounds b holds admit no value of shape shapeValue. -// A bound that does not apply to shapeValue is not judged. -func (b *bounds) empty(shapeValue shape) bool { - switch shapeValue { +// shapeKind is the kind of value a type of the given shape holds, of those +// bounds are written for, and none for any other shape. +func shapeKind(shape shape) ir.ValueKind { + switch shape { case shapeNumber, shapeInteger: - if !b.loSet || !b.hiSet { - return false - } - c := b.lo.Cmp(b.hi) - return c > 0 || (c == 0 && (b.loOpen || b.hiOpen)) - case shapeText, shapeBytes: - return crossed(b.minLen, b.maxLen) + return ir.ValueNumber + case shapeText: + return ir.ValueString + case shapeBytes: + return ir.ValueBytes case shapeList: - return crossed(b.minItems, b.maxItems) + return ir.ValueList case shapeObject: - return crossed(b.minProperties, b.maxProperties) + return ir.ValueObject default: - return false + return "" } } -// crossed reports whether the minimum and maximum are both set and no count -// lies between them. -func crossed(minimum, maximum *int64) bool { - return minimum != nil && maximum != nil && *minimum > *maximum -} - -// describe says which values b admits none of, for a shape shapeValue that -// b.empty holds. -func (b *bounds) describe(shapeValue shape) string { - switch shapeValue { +// describe says which values b admits none of, for a shape that b.empty +// holds. +func (b *bounds) describe(shape shape) string { + switch shape { case shapeText: return fmt.Sprintf("bounds admit no string: none has at least %d characters and at most %d", *b.minLen, *b.maxLen) case shapeBytes: @@ -215,10 +157,10 @@ func (b *bounds) describe(shapeValue shape) string { return fmt.Sprintf("bounds admit no object: none has at least %d members and at most %d", *b.minProperties, *b.maxProperties) default: lo, hi := "at least", "at most" - if b.loOpen { + if b.loExclusive { lo = "above" } - if b.hiOpen { + if b.hiExclusive { hi = "below" } return fmt.Sprintf("bounds admit no number: none is %s %s and %s %s", lo, b.loText, hi, b.hiText) @@ -231,57 +173,107 @@ func (b *bounds) describe(shapeValue shape) string { // has none of its own (a list, a tuple, a model, a map). It is told where the // contradiction completes: the chain alone already admitting no value is the // type that holds the first part's to tell, so it is left to it. -func unsatisfiable(doc *ir.Document, own *ir.Constraints, target ir.TypeID, self shape) string { +func (chains *aliasChains) unsatisfiable(own *ir.Constraints, target ir.TypeID, self shape) string { if own == nil { return "" } - var b bounds - shapeValue := self - if shapeValue == shapeNotChecked { - shapeValue, _, _ = settle(doc, target, &b) + var chain boundSets + shape := self + if shape == shapeNotChecked { + reading := chains.settle(target) + shape, chain = reading.shape, reading.bounds } - if b.empty(shapeValue) { + if alone := chain.bounds(); alone.empty(shape) { return "" } - b.and(own) - if !b.empty(shapeValue) { + bounds := chain.then(boundSetsOf(own)).bounds() + if !bounds.empty(shape) { return "" } - return b.describe(shapeValue) + return bounds.describe(shape) } // checkBounds reports each position and type whose bounds, together with those // of the alias scalars its reference reaches, admit no value of the kind they -// apply to (pass/bounds-admit-no-value, docs/ir/constraints.md). It does not -// judge an exclusive pair with no integer between, nor a multiple none of the -// range holds: ir.Decimal compares and does no arithmetic. -func checkBounds(doc *ir.Document, live []ir.TypeID) []ir.Diagnostic { +// apply to, and each cycle of models composing one another whose member +// counts admit no object (pass/bounds-admit-no-value, docs/ir/constraints.md). +// It does not judge an exclusive pair with no integer between, nor a multiple +// none of the range holds: ir.Decimal compares and does no arithmetic. +func checkBounds(doc *ir.Document, chains *aliasChains, live []ir.TypeID) []ir.Diagnostic { var diags []ir.Diagnostic for _, id := range live { - td := doc.Types[id] - if why := typeUnsatisfiable(doc, td); why != "" { + typeDef := doc.Types[id] + if why := chains.typeUnsatisfiable(id, typeDef); why != "" { diags = append(diags, diagAt("pass/bounds-admit-no-value", why, - string(id), td.Common().Provenance)) + string(id), typeDef.Common().Provenance)) } } + diags = append(diags, chains.crossedCompositionCycles(live)...) var keys []ir.PropertyID - eachPosition(doc, live, &keys, func(positionValue *position) { - if why := unsatisfiable(doc, positionValue.own, positionValue.typ.Target, shapeNotChecked); why != "" { - diags = append(diags, diagAt("pass/bounds-admit-no-value", why, positionValue.node, positionValue.from)) + eachPosition(doc, live, &keys, func(position *position) { + if why := chains.unsatisfiable(position.own, position.typ.Target, shapeNotChecked); why != "" { + diags = append(diags, diagAt("pass/bounds-admit-no-value", why, position.node, position.from)) } }) return diags } -// typeUnsatisfiable is unsatisfiable for the bounds td declares itself: read -// with the chain typeBounds names, or, for a union, kind by kind -// (unionUnsatisfiable). -func typeUnsatisfiable(doc *ir.Document, td ir.TypeDef) string { - if union, isUnion := td.(*ir.Union); isUnion { - return unionUnsatisfiable(union.Constraints) +// typeUnsatisfiable is unsatisfiable for the bounds typeDef, the type id +// names, declares itself: read with the chain typeBounds names, for a union +// kind by kind (unionUnsatisfiable), and for a model across its composition +// (modelUnsatisfiable). +func (chains *aliasChains) typeUnsatisfiable(id ir.TypeID, typeDef ir.TypeDef) string { + switch t := typeDef.(type) { + case *ir.Union: + return unionUnsatisfiable(t.Constraints) + case *ir.Model: + return chains.modelUnsatisfiable(id, t) + default: + own, target, self := typeBounds(typeDef) + return chains.unsatisfiable(own, target, self) + } +} + +// memberCounts returns the member counts an instance of model, the type id +// names, is held to: the intersection of those of every model its composition +// brings, read through alias scalars (ir.PropertyCountBounds). Where it +// composes none or no model writes one, that intersection is its own. +func (chains *aliasChains) memberCounts(id ir.TypeID, model *ir.Model) *ir.Constraints { + if !chains.writesMemberCount || model.Base == nil && len(model.Mixins) == 0 { + return model.Constraints + } + return chains.propertyCounts.Of(id) +} + +// modelUnsatisfiable returns what the member counts an instance of model, the +// type id names, intersects to (memberCounts) leave no object of, or "" where +// they leave one, or where a model it composes, read through alias scalars, +// already leaves none, which that model tells, as a chain's first part is left +// to the type holding it. +func (chains *aliasChains) modelUnsatisfiable(id ir.TypeID, model *ir.Model) string { + bounds := boundsOf(chains.memberCounts(id, model)) + if !bounds.empty(shapeObject) { + return "" + } + for _, part := range ir.ComposedOf(model) { + composed := boundsOf(chains.partCounts(part)) + if composed.empty(shapeObject) { + return "" + } + } + return bounds.describe(shapeObject) +} + +// partCounts returns the member counts an instance of the model part names, +// through alias scalars, intersects to, nil where it names none. +func (chains *aliasChains) partCounts(part ir.TypeID) *ir.Constraints { + reading := chains.settle(part) + model, isModel := reading.end.(*ir.Model) + if !isModel || model == nil { + return nil } - own, target, self := typeBounds(td) - return unsatisfiable(doc, own, target, self) + bounds := reading.bounds.bounds() + return &ir.Constraints{MinProperties: bounds.minProperties, MaxProperties: bounds.maxProperties} } // unionShapes are the shapes a union's own bounds are judged for, one per kind @@ -290,27 +282,26 @@ func typeUnsatisfiable(doc *ir.Document, td ir.TypeDef) string { var unionShapes = [...]shape{shapeNumber, shapeText, shapeList, shapeObject} // unionUnsatisfiable returns what own, a union's bounds, which no alias chain -// joins, leave no value of, for the first kind in unionShapes they admit none -// of, or "" where they admit a value of each kind. +// intersects with, leave no value of, for the first kind in unionShapes they +// admit none of, or "" where they admit a value of each kind. func unionUnsatisfiable(own *ir.Constraints) string { if own == nil { return "" } - var b bounds - b.and(own) + bounds := boundsOf(own) for _, shape := range unionShapes { - if b.empty(shape) { - return b.describe(shape) + if bounds.empty(shape) { + return bounds.describe(shape) } } return "" } -// typeBounds returns the bounds td declares, and the chain they are read with: -// the base of a scalar, or the shape of a list, tuple, model or map, whose -// bounds apply to it alone. -func typeBounds(td ir.TypeDef) (*ir.Constraints, ir.TypeID, shape) { - switch t := td.(type) { +// typeBounds returns the bounds typeDef declares, and the chain they are read +// with: the base of a scalar, or the shape of a list, tuple, map or enum, +// whose bounds apply to it alone, an enum's to the values its ValueType holds. +func typeBounds(typeDef ir.TypeDef) (*ir.Constraints, ir.TypeID, shape) { + switch t := typeDef.(type) { case *ir.Scalar: if t.Base != nil { return t.Constraints, t.Base.Target, shapeNotChecked @@ -319,13 +310,14 @@ func typeBounds(td ir.TypeDef) (*ir.Constraints, ir.TypeID, shape) { return t.Constraints, "", shapeList case *ir.Tuple: return t.Constraints, "", shapeList - case *ir.Model: - return t.Constraints, "", shapeObject case *ir.MapT: return t.Constraints, "", shapeObject + case *ir.Enum: + return t.Constraints, "", primitiveShape(t.ValueType) default: // no other type declares bounds a value is read against with a chain; - // a union's are judged kind by kind (typeUnsatisfiable) + // a union's are judged kind by kind and a model's across its + // composition (typeUnsatisfiable) } return nil, "", shapeNotChecked } diff --git a/pass/validate_bounds_test.go b/pass/validate_bounds_test.go index 53c8d01c1..96ca48a73 100644 --- a/pass/validate_bounds_test.go +++ b/pass/validate_bounds_test.go @@ -57,7 +57,7 @@ func modelOf(properties ...ir.Property) *ir.Document { } // big is the decimal s as written. -func big(s string) *ir.BigVal { return new(ir.BigVal(s)) } +func big(text string) *ir.BigVal { return new(ir.BigVal(text)) } // numeric is the Constraints of the numeric bounds that are not empty. func numeric(minimum, exclusiveMin, maximum, exclusiveMax string) *ir.Constraints { @@ -74,8 +74,8 @@ func numeric(minimum, exclusiveMin, maximum, exclusiveMax string) *ir.Constraint } // withMultiple sets the multiple constraints is a multiple of. -func withMultiple(constraints *ir.Constraints, s string) *ir.Constraints { - constraints.MultipleOf = big(s) +func withMultiple(constraints *ir.Constraints, text string) *ir.Constraints { + constraints.MultipleOf = big(text) return constraints } @@ -121,9 +121,9 @@ const boundsCode = "pass/bounds-admit-no-value" // not look for. func TestValidate_BoundsThatAdmitNoValueAreReported(t *testing.T) { t.Parallel() - typed := func(id string, td func(constraints *ir.Constraints) ir.TypeDef, irConstraints *ir.Constraints) *ir.Document { + typed := func(id string, typeDef func(constraints *ir.Constraints) ir.TypeDef, irConstraints *ir.Constraints) *ir.Document { doc := valueDoc() - doc.Types[ir.TypeID(id)] = td(irConstraints) + doc.Types[ir.TypeID(id)] = typeDef(irConstraints) return doc } list := func(constraints *ir.Constraints) ir.TypeDef { @@ -229,11 +229,11 @@ func TestValidate_BoundsAreJudgedOnlyForTheValueTheyApply(t *testing.T) { assert.Empty(t, found(t, doc, boundsCode)) } -// TestValidate_BoundsAreJoinedWithThoseOfTheAliasesAPositionReaches holds a -// contradiction to be told once, where it completes: at the property whose own -// bounds meet the alias's, and at the alias alone when it contradicts itself, -// whatever a property of it adds. -func TestValidate_BoundsAreJoinedWithThoseOfTheAliasesAPositionReaches(t *testing.T) { +// TestValidate_BoundsAreIntersectedWithThoseOfTheAliasesAPositionReaches holds +// a contradiction to be told once, where it completes: at the property whose +// own bounds intersect the alias's, and at the alias alone when it contradicts +// itself, whatever a property of it adds. +func TestValidate_BoundsAreIntersectedWithThoseOfTheAliasesAPositionReaches(t *testing.T) { t.Parallel() alias := func(constraints *ir.Constraints) *ir.Scalar { return &ir.Scalar{ID: "type/s", Base: &stringT, Constraints: constraints, Provenance: provAt("type/s")} @@ -314,7 +314,7 @@ func TestValidate_BoundsAreJudgedAtEverySiteAPositionSits(t *testing.T) { number := finding{message: "bounds admit no number: none is at least 10 and at most 5"} obj := finding{message: "bounds admit no object: none has at least 2 members and at most 1"} list := finding{message: "bounds admit no list: none has at least 2 items and at most 1"} - at := func(findingValue finding, node string) finding { findingValue.node = node; return findingValue } + at := func(finding finding, node string) finding { finding.node = node; return finding } assert.Equal(t, []finding{ at(list, "type/l"), at(obj, "type/o"), diff --git a/pass/validate_chains.go b/pass/validate_chains.go new file mode 100644 index 000000000..783224324 --- /dev/null +++ b/pass/validate_chains.go @@ -0,0 +1,190 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass + +import "github.com/dexpace/morphic/ir" + +// aliasChains is what a Validate run reads of a document's alias chains, each +// read once for the run however many values and positions read it: an index +// over the document's types, and for each alias the bounds and encodings of +// the aliases from it to its chain's end. Like its index, it is not safe for +// concurrent use. +type aliasChains struct { + types ir.TypeRegistry + index *ir.AliasChainIndex + aliasBounds *ir.AliasChainAnswers[aliasChainBounds] + // admission judges a value against a type over the same index, asking no + // source format: pass holds none. judgments is what it may still take for + // the run's values, and unjudged the finding at the first value it had + // none left for, nil until one comes (valueSite.admitted). + admission *ir.ValueAdmissionReader + judgments int + unjudged *ir.Diagnostic + // propertyCounts reads the member counts of each model's composition + // (memberCounts) over the same index; writesMemberCount says a model of types writes + // a member count, where none doing so leaves every intersection its + // model's own, so no composition is read. + propertyCounts *ir.PropertyCountBounds + writesMemberCount bool +} + +// aliasChainBounds is what the aliases of a chain from one of them to its end +// bound: their bound sets, nearest first, and whether one holds an encoding +// that names a scheme (ir.Encoding.Encodes). +type aliasChainBounds struct { + bounds boundSets + encoded bool +} + +// newAliasChains returns the run's memo of doc's alias chains. +func newAliasChains(doc *ir.Document) *aliasChains { + return newAliasChainsOver(doc.Types, doc.Types.Lookup) +} + +// newAliasChainsOver returns the memo of the alias chains of types, which the +// index reads through lookup, a lookup of types. +func newAliasChainsOver(types ir.TypeRegistry, lookup func(ir.TypeID) (ir.TypeDef, bool)) *aliasChains { + index := ir.NewAliasChainIndex(lookup) + aliasBounds := ir.NewAliasChainAnswers(index, func(ir.TypeID, ir.TypeDef) aliasChainBounds { return aliasChainBounds{} }, + func(scalar *ir.Scalar, next aliasChainBounds) aliasChainBounds { + return aliasChainBounds{bounds: boundSetsOf(scalar.Constraints).then(next.bounds), encoded: next.encoded || scalar.Encoding.Encodes()} + }) + writesMemberCount := false + for _, typeDef := range types { + model, isModel := typeDef.(*ir.Model) + if isModel && model != nil && model.Constraints != nil && (model.Constraints.MinProperties != nil || model.Constraints.MaxProperties != nil) { + writesMemberCount = true + break + } + } + return &aliasChains{types: types, index: index, aliasBounds: aliasBounds, admission: ir.NewValueAdmissionReader(lookup, index, nil), + judgments: maxValueJudgments, propertyCounts: ir.NewPropertyCountBounds(lookup, index), writesMemberCount: writesMemberCount} +} + +// chainAnswer is what the chain of alias scalars from one type to its end says +// of a value of it: the node the chain ends at, nil where it reaches nothing +// declared or repeats a scalar; the bound sets of every alias from the type and +// of the end; the shape a value of it is; and whether a value of it is encoded: +// an alias on the way names a scheme, or the list it ends at holds an encoding. +type chainAnswer struct { + end ir.TypeDef + bounds boundSets + shape shape + encoded bool +} + +// settle reads the chain of alias scalars from target to its end, however long. +// The shape is shapeNotChecked where the chain reaches nothing declared or +// repeats a scalar. +func (chains *aliasChains) settle(target ir.TypeID) chainAnswer { + said, held := chains.aliasBounds.AnswerFor(target) + if !held { + return chainAnswer{} + } + endID := chains.end(target) + end := chains.types[endID] + reading := chainAnswer{end: end, bounds: said.bounds, encoded: said.encoded} + switch t := end.(type) { + case *ir.Scalar: + reading.bounds = said.bounds.then(boundSetsOf(t.Constraints)) + case *ir.Primitive: + reading.shape = primitiveShape(t.PrimitiveKind) + case *ir.List: + reading.shape, reading.encoded = shapeList, said.encoded || t.Encoding != nil + reading.bounds = said.bounds.then(boundSetsOf(t.Constraints)) + case *ir.Tuple: + reading.shape, reading.bounds = shapeList, said.bounds.then(boundSetsOf(t.Constraints)) + case *ir.Model: + reading.shape, reading.bounds = shapeObject, said.bounds.then(boundSetsOf(chains.memberCounts(endID, t))) + case *ir.MapT: + reading.shape, reading.bounds = shapeObject, said.bounds.then(boundSetsOf(t.Constraints)) + case *ir.Enum: + reading.bounds = said.bounds.then(boundSetsOf(t.Constraints)) + case *ir.Any: + reading.shape = shapeAnything + default: + // any other node is a shape the checks read no further, bound by the + // chain's aliases alone + } + return reading +} + +// end returns the type id's chain of alias scalars names, id where it names no +// alias (ir.AliasChainIndex.End). +func (chains *aliasChains) end(id ir.TypeID) ir.TypeID { + end, _ := chains.index.End(id) + return end +} + +// unionAt returns the union id names, read through its chain of alias scalars +// however long, and nil where it names none: a cyclic chain ends at one of its +// scalars. +func (chains *aliasChains) unionAt(id ir.TypeID) *ir.Union { + union, _ := chains.types[chains.end(id)].(*ir.Union) + return union +} + +// leadsToUnion reports whether id is a union, or an alias scalar whose chain +// ends at one (unionAt). +func (chains *aliasChains) leadsToUnion(id ir.TypeID) bool { + return chains.unionAt(id) != nil +} + +// boundSets is the sets of bounds a value is held to, intersected as +// ir.ConstraintIntersection intersects them: one set as it is, or the +// intersection of two or more, of which a value is judged by the keywords they +// agree on. Holding one set allocates nothing. +type boundSets struct { + intersected ir.ConstraintIntersection + one *ir.Constraints + count int +} + +// boundSetsOf is constraints alone, or no set where it is nil. +func boundSetsOf(constraints *ir.Constraints) boundSets { + if constraints == nil { + return boundSets{} + } + return boundSets{one: constraints, count: 1} +} + +// then is sets and later together, sets first: a value one of them spells two +// ways keeps sets' spelling. +func (sets boundSets) then(later boundSets) boundSets { + switch { + case later.count == 0: + return sets + case sets.count == 0: + return later + default: + return boundSets{intersected: sets.intersection().Intersect(later.intersection()), count: sets.count + later.count} + } +} + +// intersection is sets as an ir.ConstraintIntersection. +func (sets boundSets) intersection() ir.ConstraintIntersection { + if sets.count == 1 { + return ir.ConstraintIntersectionOf(sets.one) + } + return sets.intersected +} + +// refuse reports whether ir refuses value by the keywords the sets agree on +// (ir.ConstraintsAdmit); no set refuses nothing. +func (sets boundSets) refuse(value *ir.Value) bool { + if sets.count == 0 { + return false + } + return ir.ConstraintsAdmit(sets.intersection().AgreedConstraints(), *value) == ir.AdmitsNo +} + +// bounds returns what the sets bound a value by: every keyword one set +// states, and of several, each keyword they agree on, a keyword no one value +// holds being judged by none. +func (sets boundSets) bounds() bounds { + if sets.count == 1 { + return boundsOf(sets.one) + } + return boundsOf(sets.intersected.AgreedConstraints()) +} diff --git a/pass/validate_chains_internal_test.go b/pass/validate_chains_internal_test.go new file mode 100644 index 000000000..b5c2ee5f4 --- /dev/null +++ b/pass/validate_chains_internal_test.go @@ -0,0 +1,114 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// defaultsDownAChain is a chain of n aliases over integer, the far one +// bounding it by a maximum of 5, and a model holding a property of each alias +// defaulting to 7, which every alias's bound refuses. +func defaultsDownAChain(count int) *ir.Document { + integer := ir.PrimitiveTypeID(ir.PrimitiveInteger) + types := ir.TypeRegistry{integer: &ir.Primitive{ID: integer, PrimitiveKind: ir.PrimitiveInteger}} + model := &ir.Model{ID: "type/M"} + base := integer + for i := range count { + id := ir.TypeID(fmt.Sprintf("type/I%d", i)) + alias := &ir.Scalar{ID: id, Base: &ir.TypeRef{Target: base}} + if i == 0 { + alias.Constraints = &ir.Constraints{Max: new(ir.BigVal("5"))} + } + types[id], base = alias, id + model.Properties = append(model.Properties, ir.Property{ + ID: ir.PropertyID(fmt.Sprintf("property/M/p%d", i)), WireName: fmt.Sprintf("p%d", i), + Type: ir.TypeRef{Target: id}, Default: &ir.Value{Kind: ir.ValueNumber, Number: "7"}, + }) + } + types[model.ID] = model + return &ir.Document{IRVersion: ir.IRVersion, Types: types} +} + +// TestCheckValues_ReadsEachChainOnceAcrossManyDefaults pins the run's memo of a +// document's alias chains: a default on every alias of a chain of 1,000, 2,000 +// and 4,000 aliases, each refused by the far alias's maximum, reads the chain's +// aliases in lookups growing linearly, each read once for the run however many +// defaults reach it. +func TestCheckValues_ReadsEachChainOnceAcrossManyDefaults(t *testing.T) { + t.Parallel() + var counts [3]int + for i, n := range []int{1000, 2000, 4000} { + doc := defaultsDownAChain(n) + reads := 0 + chains := newAliasChainsOver(doc.Types, func(id ir.TypeID) (ir.TypeDef, bool) { + reads++ + typeDef, held := doc.Types[id] + return typeDef, held + }) + + diags := checkValues(doc, chains, liveTypeIDs(doc)) + + require.Len(t, diags, n, "%d aliases: every default lies outside the far alias's maximum", n) + for _, diagnostic := range diags { + require.Equal(t, "pass/default-outside-type", diagnostic.Code) + } + counts[i] = reads + } + assert.LessOrEqual(t, float64(counts[2]-counts[1]), 2.5*float64(counts[1]-counts[0]), + "lookups at 1,000, 2,000 and 4,000 aliases: %v", counts) +} + +// TestAliasChains_JudgeTheKeywordsTheirSetsAgreeOn pins what a position over a +// chain of two aliases is held to, three sets of bounds intersected as +// ir.ConstraintIntersection intersects them: the lengths they agree on, +// whatever their patterns, which no one value states. Its own maximum crossing +// the far alias's minimum admits no string, and a default too long for its own +// maximum lies outside its bounds; its own pattern refuses a default, worded by +// the type as the patterns disagree, and the chain's judge nothing. +func TestAliasChains_JudgeTheKeywordsTheirSetsAgreeOn(t *testing.T) { + t.Parallel() + text := ir.PrimitiveTypeID(ir.PrimitiveString) + doc := &ir.Document{IRVersion: ir.IRVersion, Types: ir.TypeRegistry{ + text: &ir.Primitive{ID: text, PrimitiveKind: ir.PrimitiveString}, + "type/A1": &ir.Scalar{ID: "type/A1", Base: &ir.TypeRef{Target: text}, Constraints: &ir.Constraints{MinLength: new(int64(3)), Pattern: "^a"}}, + "type/A2": &ir.Scalar{ID: "type/A2", Base: &ir.TypeRef{Target: "type/A1"}, Constraints: &ir.Constraints{Pattern: "^c"}}, + }} + chains := newAliasChains(doc) + + crossing := &ir.Constraints{MaxLength: new(int64(2)), Pattern: "^b"} + assert.Equal(t, "bounds admit no string: none has at least 3 characters and at most 2", + chains.unsatisfiable(crossing, "type/A2", shapeNotChecked)) + site := valueSite{chains: chains, node: "property/p", ref: ir.TypeRef{Target: "type/A2"}, own: &ir.Constraints{MaxLength: new(int64(4)), Pattern: "^b"}} + assert.Equal(t, "lies outside the bounds declared for it", site.fits(&ir.Value{Kind: ir.ValueString, String: "abcde"})) + assert.Equal(t, "is no value type/A2 admits", site.fits(&ir.Value{Kind: ir.ValueString, String: "zzz"}), + "the position's own pattern") + assert.Empty(t, site.fits(&ir.Value{Kind: ir.ValueString, String: "bzz"}), "the chain's patterns, which disagree") +} + +// TestAliasChains_LeaveAKeywordTheirSetsConflictOnOut pins both readings pass +// makes of a chain's bounds, each of the keywords its sets agree on: two +// maximums no one value states, the nearer alias's 5 and the farther one's, +// which no Decimal reads, neither intersect a position's minimum of 10 into +// bounds admitting no number nor word the finding on a number the type refuses. +func TestAliasChains_LeaveAKeywordTheirSetsConflictOnOut(t *testing.T) { + t.Parallel() + small := ir.PrimitiveTypeID(ir.PrimitiveUint8) + doc := &ir.Document{IRVersion: ir.IRVersion, Types: ir.TypeRegistry{ + small: &ir.Primitive{ID: small, PrimitiveKind: ir.PrimitiveUint8}, + "type/near": &ir.Scalar{ID: "type/near", Base: &ir.TypeRef{Target: "type/far"}, Constraints: &ir.Constraints{Max: new(ir.BigVal("5"))}}, + "type/far": &ir.Scalar{ID: "type/far", Base: &ir.TypeRef{Target: small}, Constraints: &ir.Constraints{Max: new(ir.BigVal("1p4"))}}, + }} + chains := newAliasChains(doc) + + assert.Empty(t, chains.unsatisfiable(&ir.Constraints{Min: new(ir.BigVal("10"))}, "type/near", shapeNotChecked)) + site := valueSite{chains: chains, node: "property/p", ref: ir.TypeRef{Target: "type/near"}} + assert.Equal(t, "is no value type/near admits", site.fits(&ir.Value{Kind: ir.ValueNumber, Number: "300"})) +} diff --git a/pass/validate_corpus_test.go b/pass/validate_corpus_test.go index cca38334f..ba13c1de1 100644 --- a/pass/validate_corpus_test.go +++ b/pass/validate_corpus_test.go @@ -31,13 +31,13 @@ func TestValidate_Corpus(t *testing.T) { files, err := filepath.Glob("../testdata/conformance/openapi/*.yaml") require.NoError(t, err) require.NotEmpty(t, files, "corpus directory must contain spec files") - for _, f := range files { - t.Run(filepath.Base(f), func(t *testing.T) { + for _, file := range files { + t.Run(filepath.Base(file), func(t *testing.T) { t.Parallel() - data, err := os.ReadFile(f) + data, err := os.ReadFile(file) require.NoError(t, err) doc, _, err := openapi.New().Compile(t.Context(), - []compilers.Source{{Path: filepath.Base(f), Data: data}}, compilers.Options{}) + []compilers.Source{{Path: filepath.Base(file), Data: data}}, compilers.Options{}) require.NoError(t, err) require.NotNil(t, doc) before, err := json.Marshal(doc) @@ -45,7 +45,7 @@ func TestValidate_Corpus(t *testing.T) { for _, diagnostic := range validatedOnce(t, doc) { assert.NotEqual(t, ir.SeverityError, diagnostic.Severity, - "%s: unexpected validate error: %+v", filepath.Base(f), diagnostic) + "%s: unexpected validate error: %+v", filepath.Base(file), diagnostic) } after, err := json.Marshal(doc) diff --git a/pass/validate_cost_test.go b/pass/validate_cost_test.go index 0b8ea22c7..4845094e4 100644 --- a/pass/validate_cost_test.go +++ b/pass/validate_cost_test.go @@ -26,7 +26,7 @@ const wide = 12 // union, an enum, a channel on a server with its messages, and an operation // binding parameters, paginating, with payloads, headers, a scenario and a // message binding with a reply. -func soundDocument(n int) *ir.Document { +func soundDocument(count int) *ir.Document { doc := &ir.Document{ IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: ir.TypeRegistry{"type/primitive/string": &ir.Primitive{ID: "type/primitive/string", PrimitiveKind: ir.PrimitiveString}}, @@ -35,8 +35,8 @@ func soundDocument(n int) *ir.Document { Servers: map[ir.ServerID]ir.Server{"server/x/a": {ID: "server/x/a", Name: ir.Naming{Source: "api"}, URLTemplate: "https://api.example.com"}}, } group := ir.OperationGroup{ID: "operation-group/x"} - commonErrors := make([]ir.ErrorCase, 0, n) - for i := range n { + commonErrors := make([]ir.ErrorCase, 0, count) + for i := range count { model := addEntityTypes(doc, i) messages := addEntityMessages(doc, i) group.Operations = append(group.Operations, entityOperation(i, model, messages)) @@ -73,8 +73,8 @@ func addEntityTypes(doc *ir.Document, i int) *ir.Model { } model.Discriminator.Property = model.Properties[0].ID model.Discriminator.Default = model.Discriminator.Mapping["w0"] - for _, td := range []ir.TypeDef{model, union, enum} { - doc.Types[td.Common().ID] = td + for _, typeDef := range []ir.TypeDef{model, union, enum} { + doc.Types[typeDef.Common().ID] = typeDef } return model } diff --git a/pass/validate_count_cycles.go b/pass/validate_count_cycles.go new file mode 100644 index 000000000..b56c74eaf --- /dev/null +++ b/pass/validate_count_cycles.go @@ -0,0 +1,98 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass + +import ( + "cmp" + "fmt" + "slices" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" +) + +// crossedCompositionCycles reports, once each, the cycles of live models +// composing one another along Base and Mixins, read through alias scalars, +// whose intersected member counts admit no object (crossedCycle). Every model +// of such a cycle is held to the one intersection and composes a crossed part, +// so modelUnsatisfiable tells it at none; it is told at the model of least +// provenance (leastProvenance). A document no model of which writes a count +// holds no such cycle, and its composition is not read. +func (chains *aliasChains) crossedCompositionCycles(live []ir.TypeID) []ir.Diagnostic { + if !chains.writesMemberCount { + return nil + } + var composing []ir.TypeID + for _, id := range live { + if model, isModel := chains.types[id].(*ir.Model); isModel && (model.Base != nil || len(model.Mixins) > 0) { + composing = append(composing, id) + } + } + var diags []ir.Diagnostic + for _, component := range irfacts.CompositionStronglyConnectedComponents(chains.types, composing) { + if why := chains.crossedCycle(component); why != "" { + site := leastProvenance(chains.types, component) + diags = append(diags, diagAt("pass/bounds-admit-no-value", why, string(site), chains.types[site].Common().Provenance)) + } + } + return diags +} + +// crossedCycle returns what the intersected member counts of component, a +// strongly connected component of the composition, leave no object of, or "" +// where it is no cycle, where they leave one, or where a model it composes +// outside it already leaves none, which that model tells, as a chain's first +// part is left to the type holding it. +func (chains *aliasChains) crossedCycle(component []ir.TypeID) string { + if !chains.isCycle(component) { + return "" + } + bounds := boundsOf(chains.propertyCounts.Of(component[0])) + if !bounds.empty(shapeObject) || chains.composesCrossedOutside(component) { + return "" + } + return fmt.Sprintf("composes itself, alone or through other models, and the intersected member counts of that "+ + "cycle admit no object: none has at least %d members and at most %d", *bounds.minProperties, *bounds.maxProperties) +} + +// isCycle reports whether component holds two models or more, or one +// composing itself, an entry of its read through alias scalars naming it. +func (chains *aliasChains) isCycle(component []ir.TypeID) bool { + if len(component) > 1 { + return true + } + return slices.ContainsFunc(ir.ComposedOf(chains.types[component[0]]), func(part ir.TypeID) bool { + return chains.end(part) == component[0] + }) +} + +// composesCrossedOutside reports whether a model of component composes one +// outside it whose member counts (partCounts) already admit no object. +func (chains *aliasChains) composesCrossedOutside(component []ir.TypeID) bool { + inside := make(map[ir.TypeID]bool, len(component)) + for _, id := range component { + inside[id] = true + } + for _, id := range component { + for _, part := range ir.ComposedOf(chains.types[id]) { + if inside[chains.end(part)] { + continue + } + if composed := boundsOf(chains.partCounts(part)); composed.empty(shapeObject) { + return true + } + } + } + return false +} + +// leastProvenance returns the type of ids, which holds one at least, whose +// provenance is least: by Source, then by Pointer compared as bytes, then by +// ID, an order no declaration order moves. +func leastProvenance(types ir.TypeRegistry, ids []ir.TypeID) ir.TypeID { + return slices.MinFunc(ids, func(a, b ir.TypeID) int { + at, bt := types[a].Common().Provenance, types[b].Common().Provenance + return cmp.Or(cmp.Compare(at.Source, bt.Source), cmp.Compare(at.Pointer, bt.Pointer), cmp.Compare(a, b)) + }) +} diff --git a/pass/validate_determinism_test.go b/pass/validate_determinism_test.go index fe26665ce..ede99a752 100644 --- a/pass/validate_determinism_test.go +++ b/pass/validate_determinism_test.go @@ -187,6 +187,13 @@ var twoFindings = []twoFinding{ return &ir.List{ID: id, ElementType: stringT, Constraints: &ir.Constraints{MinItems: new(int64(2)), MaxItems: new(int64(1))}} }, "type/z", "type/b") }}, + {family: "checkMembersOutsideBounds", code: memberBoundsCode, want: []string{"type/b", "type/z"}, + doc: func() *ir.Document { + return typesOf(func(id ir.TypeID) ir.TypeDef { + return &ir.Enum{ID: id, ValueType: ir.PrimitiveString, Closed: true, Constraints: &ir.Constraints{MaxLength: new(int64(1))}, + Members: []ir.EnumMember{{Value: *text("a")}, {Value: *text("bb")}}} + }, "type/z", "type/b") + }}, {family: "checkValues", code: exampleCode, want: []string{"type/b", "type/z"}, doc: func() *ir.Document { return typesOf(func(id ir.TypeID) ir.TypeDef { @@ -271,7 +278,7 @@ func TestReadRepeatedly_ReadsATwoFindingDocumentUntilItHasSaidSoEveryTime(t *tes t.Run("a reading that differs", func(t *testing.T) { t.Parallel() - reads, failuresValue := 0, &failures{} + reads, failures := 0, &failures{} flip := func() []ir.Diagnostic { reads++ if reads == determinismRuns { @@ -280,8 +287,8 @@ func TestReadRepeatedly_ReadsATwoFindingDocumentUntilItHasSaidSoEveryTime(t *tes return []ir.Diagnostic{finding("a"), finding("b")} } - assert.PanicsWithValue(t, failuresValue, func() { readRepeatedly(failuresValue, flip) }) + assert.PanicsWithValue(t, failures, func() { readRepeatedly(failures, flip) }) assert.Equal(t, determinismRuns, reads, "the last reading is the one that differs") - assert.Len(t, failuresValue.told, 1) + assert.Len(t, failures.told, 1) }) } diff --git a/pass/validate_discriminator_routes.go b/pass/validate_discriminator_routes.go new file mode 100644 index 000000000..0f152f178 --- /dev/null +++ b/pass/validate_discriminator_routes.go @@ -0,0 +1,255 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass + +import ( + "fmt" + "slices" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/ir/irfacts" + "github.com/dexpace/morphic/scratchstate" +) + +// routeReads is what the route checks read every discriminator through, kept +// for the run: the targets a union's routes reach, and the walk down the +// hierarchy. +type routeReads struct { + routed scratchstate.Map[ir.TypeID, bool] + walk hierarchyWalk +} + +// hierarchyWalk is the breadth-first walk down a run's hierarchy from every +// model holding a discriminator, over the run's live types: whether each +// holds one, how the walk reached each vertex, whether the nearest holder's +// discriminator routes it, and whether it routes a vertex reached through it +// below the same holder, with the vertices in the order reached. +type hierarchyWalk struct { + holds []bool + arrivals []arrival + routed []bool + below []bool + order []int32 +} + +// arrival is how the walk reached a vertex: the nearest holder above it and +// the parent it was reached through. The zero arrival is a vertex the walk +// has not reached. +type arrival struct { + nearest, through int32 + reached bool +} + +// checkUnroutedVariants reports, as an info, each variant of union no route +// of its discriminator reaches: no Mapping entry, decode-only route or Default +// names its type, nor does the name an empty Mapping routes it by +// (ir.VariantNameRoute, docs/ir/models.md#discriminator). A decoder reaches +// such a variant only by recognizing it. A variant admitting null alone +// carries no tag, and is left alone. +func checkUnroutedVariants(chains *aliasChains, union *ir.Union, read *routeReads) []ir.Diagnostic { + if union.Discriminator == nil { + return nil + } + var diags []ir.Diagnostic + routed := read.routedBy(union.Discriminator) + for _, variant := range union.Variants { + target := variant.Type.Target + if routed[target] || admitsNullAlone(chains, variant.Type) { + continue + } + routed[target] = true // a type two variants name is reported once + if _, byName := ir.VariantNameRoute(union, chains.types[target]); !byName { + diags = append(diags, unroutedVariant("union", union.ID, "variant", target)) + } + } + return diags +} + +// checkUnroutedSubtypes reports, as an info, each subtype, a model below one +// holding a discriminator along ir.Supertypes, that no route of the +// discriminator on its nearest such ancestor names. Each is judged once, by +// the holder a breadth-first walk down from every holder, in ID order, +// reaches it from first, so a chain of discriminators costs one walk. live is +// the run's sorted live types, and facts indexes the same document. +func checkUnroutedSubtypes(chains *aliasChains, live []ir.TypeID, facts *irfacts.DocumentFacts, read *routeReads) []ir.Diagnostic { + walk := &read.walk + walk.start(len(live)) + for vertex, id := range live { + walk.holds[vertex] = discriminatorOfModel(chains.types[id]) != nil + } + if !slices.Contains(walk.holds, true) { + return nil + } + walk.down(facts, live) + walk.markRouted(chains.types, live) + walk.markRoutedBelow() + var diags []ir.Diagnostic + for vertex, arrived := range walk.arrivals { + switch { + case !arrived.reached || walk.routed[vertex]: + case walk.below[vertex]: + diags = append(diags, routedThroughSubtypes(live[arrived.nearest], live[vertex])) + default: + diags = append(diags, unroutedVariant("model", live[arrived.nearest], "subtype", live[vertex])) + } + } + return diags +} + +// discriminatorOfModel returns the discriminator typeDef holds where it is a +// model, and nil otherwise. +func discriminatorOfModel(typeDef ir.TypeDef) *ir.Discriminator { + if model, isModel := typeDef.(*ir.Model); isModel && model != nil { + return model.Discriminator + } + return nil +} + +// start readies the walk for count vertices, none reached. +func (walk *hierarchyWalk) start(count int) { + walk.holds = filled(walk.holds, count, false) + walk.routed = filled(walk.routed, count, false) + walk.below = filled(walk.below, count, false) + walk.arrivals = filled(walk.arrivals, count, arrival{}) + walk.order = walk.order[:0] +} + +// filled returns values holding length copies of value, reusing its array. +func filled[T any](values []T, length int, value T) []T { + values = slices.Grow(values[:0], length)[:length] + for i := range values { + values[i] = value + } + return values +} + +// down walks the hierarchy breadth-first from every vertex holding a +// discriminator, in vertex order: each holder's children first, then each +// vertex reached hands its nearest holder on to its own children, but a +// holder, whose children are its own. No holder is its own nearest, so a +// cycle back to one ends there. Each vertex is reached once. +func (walk *hierarchyWalk) down(facts *irfacts.DocumentFacts, live []ir.TypeID) { + for vertex, holds := range walk.holds { + if holds { + walk.reach(facts, live, int32(vertex), int32(vertex)) + } + } + // order grows as the walk reaches more, so it is read as a queue. + for head := 0; head < len(walk.order); { + vertex := walk.order[head] + head++ + if !walk.holds[vertex] { + walk.reach(facts, live, vertex, walk.arrivals[vertex].nearest) + } + } +} + +// reach records each direct subtype of parent the walk has not reached, but +// holder itself, as reached through parent, holder the nearest above it. A +// direct subtype is a declared model, so a live vertex. +func (walk *hierarchyWalk) reach(facts *irfacts.DocumentFacts, live []ir.TypeID, parent, holder int32) { + for _, subtype := range facts.DirectSubtypes(live[parent]) { + found, _ := slices.BinarySearch(live, subtype) + child := int32(found) + if child == holder || walk.arrivals[child].reached { + continue + } + walk.arrivals[child] = arrival{nearest: holder, through: parent, reached: true} + walk.order = append(walk.order, child) + } +} + +// markRouted marks each vertex the walk reached that a route of its nearest +// holder's discriminator names: a Mapping entry, a decode-only route or its +// Default. +func (walk *hierarchyWalk) markRouted(types ir.TypeRegistry, live []ir.TypeID) { + for vertex, holds := range walk.holds { + if !holds { + continue + } + discriminator := discriminatorOfModel(types[live[vertex]]) + for _, target := range discriminator.Mapping { + walk.markRoute(live, int32(vertex), target) + } + for _, target := range discriminator.DecodeOnlyRoutes { + walk.markRoute(live, int32(vertex), target) + } + if discriminator.Default != "" { + walk.markRoute(live, int32(vertex), discriminator.Default) + } + } +} + +// markRoute marks target routed where it is a live vertex whose nearest holder +// is holder. +func (walk *hierarchyWalk) markRoute(live []ir.TypeID, holder int32, target ir.TypeID) { + vertex, isLive := slices.BinarySearch(live, target) + if !isLive { + return + } + if arrived := walk.arrivals[vertex]; arrived.reached && arrived.nearest == holder { + walk.routed[vertex] = true + } +} + +// markRoutedBelow marks each vertex the walk reached another through, below +// the same holder, where that other is routed or itself so marked. It reads +// the vertices in reverse of the order reached, so each is read after every +// vertex reached through it. +func (walk *hierarchyWalk) markRoutedBelow() { + for _, vertex := range slices.Backward(walk.order) { + arrived := walk.arrivals[vertex] + if arrived.through != arrived.nearest && (walk.routed[vertex] || walk.below[vertex]) { + walk.below[arrived.through] = true + } + } +} + +// routedBy returns the set of the types a route of discriminator names: a +// Mapping entry, a decode-only route or its Default. +func (read *routeReads) routedBy(discriminator *ir.Discriminator) map[ir.TypeID]bool { + routed := read.routed.Emptied() + for _, target := range discriminator.Mapping { + routed[target] = true + } + for _, target := range discriminator.DecodeOnlyRoutes { + routed[target] = true + } + if discriminator.Default != "" { + routed[discriminator.Default] = true + } + return routed +} + +// routedThroughSubtypes reports that the discriminator on the model at id +// routes no tag to its subtype, whose own subtypes it routes: an abstract +// subtype, which has no route of its own. +func routedThroughSubtypes(id, subtype ir.TypeID) ir.Diagnostic { + return diag(ir.SeverityInfo, "pass/discriminator-unrouted-variant", + fmt.Sprintf("discriminator on model %s routes no tag to its subtype %s itself, which routes only through "+ + "its subtypes: no mapping entry, decode-only route or default names it, so a decoder reaches it only "+ + "as one of them or by recognizing it", id, subtype), + string(id)) +} + +// unroutedVariant reports that the discriminator on the holder at id, a +// union or model, routes no tag to its part target, a variant or subtype. +func unroutedVariant(holder string, id ir.TypeID, part string, target ir.TypeID) ir.Diagnostic { + return diag(ir.SeverityInfo, "pass/discriminator-unrouted-variant", + fmt.Sprintf("discriminator on %s %s routes no tag to its %s %s: no mapping entry, decode-only route "+ + "or default names it, so a decoder reaches it only by recognizing it", holder, id, part, target), + string(id)) +} + +// admitsNullAlone reports whether ref admits null and nothing else: a +// nullable reference to a closed Enum with no member, read through its alias +// scalars, which is how the IR spells such a position +// (docs/ir/enums.md#the-empty-enum). +func admitsNullAlone(chains *aliasChains, ref ir.TypeRef) bool { + if !ref.Nullable { + return false + } + enum, isEnum := chains.types[chains.end(ref.Target)].(*ir.Enum) + return isEnum && enum != nil && enum.Closed && len(enum.Members) == 0 +} diff --git a/pass/validate_discriminator_routes_test.go b/pass/validate_discriminator_routes_test.go new file mode 100644 index 000000000..20363b9b7 --- /dev/null +++ b/pass/validate_discriminator_routes_test.go @@ -0,0 +1,263 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/compilers" + "github.com/dexpace/morphic/compilers/openapi" + "github.com/dexpace/morphic/ir" +) + +// The codes of the two discriminator checks a variant's own reading draws. +const ( + refusesTag = "pass/discriminator-variant-refuses-tag" + unroutedVariant = "pass/discriminator-unrouted-variant" +) + +// compiledSchemas compiles schemas as the components of a minimal 3.1 +// document, requiring the compile to finish. +func compiledSchemas(t *testing.T, schemas string) *ir.Document { + t.Helper() + src := "openapi: 3.1.0\ninfo: {title: t, version: \"1\"}\npaths: {}\ncomponents:\n schemas:\n" + schemas + doc, _, err := openapi.New().Compile(t.Context(), []compilers.Source{{Path: "spec.yaml", Data: []byte(src)}}, compilers.Options{}) + require.NoError(t, err) + require.NotNil(t, doc) + return doc +} + +// TestValidate_AVariantRefusingItsTagIsWarnedAsAWarning pins the finding's +// severity on GitHub #1807's own document. +func TestValidate_AVariantRefusingItsTagIsWarnedAsAWarning(t *testing.T) { + t.Parallel() + found := withCode(validated(t, compiledSchemas(t, ` Pet: + oneOf: [{$ref: '#/components/schemas/Cat'}, {$ref: '#/components/schemas/Dog'}] + discriminator: {propertyName: kind} + Cat: {type: object, required: [kind], properties: {kind: {const: Cat}}} + Dog: {type: object, additionalProperties: false, properties: {bark: {type: boolean}}} +`)), refusesTag) + require.Len(t, found, 1) + assert.Equal(t, ir.SeverityWarning, found[0].Severity) +} + +// TestValidate_AVariantNoRouteReachesIsReported pins GitHub #1844: an info at +// each union variant, or hierarchy subtype, that no route of its +// discriminator reaches: no Mapping entry, no type name beside a nil Mapping, +// no decode-only route and no Default. A variant whose type has no name +// beside a nil Mapping is routed by none, which the verifier accepts as a fact +// of the source (TestVerify_AVariantWhoseTypeIsUnnamedOrMissingRoutesNoName). +// A variant admitting null alone carries no tag and draws none. +func TestValidate_AVariantNoRouteReachesIsReported(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + doc func() (*ir.Document, ir.TypeID) + reported bool + }{ + {"a variant no entry routes", func() (*ir.Document, ir.TypeID) { return routedUnion(nil, ""), "type/y" }, true}, + {"a variant a decode-only route reaches", func() (*ir.Document, ir.TypeID) { + return routedUnion(map[string]ir.TypeID{"y": "type/y"}, ""), "type/y" + }, false}, + {"a variant the default reaches", func() (*ir.Document, ir.TypeID) { return routedUnion(nil, "type/y"), "type/y" }, false}, + {"a nil mapping routing by type name", func() (*ir.Document, ir.TypeID) { return besideNilMapping("Y"), "type/y" }, false}, + {"a variant whose type has no name beside a nil mapping", func() (*ir.Document, ir.TypeID) { + return besideNilMapping(""), "type/y" + }, true}, + {"a variant admitting null alone", func() (*ir.Document, ir.TypeID) { + doc := routedUnion(nil, "") + // An empty closed enum behind a nullable reference admits null + // alone, as the IR spells such a variant. + doc.Types["type/y"] = &ir.Enum{ID: "type/y", ValueType: ir.PrimitiveString, Closed: true} + union := doc.Types["type/u"].(*ir.Union) + union.Variants[1].Type.Nullable = true + return doc, "type/y" + }, false}, + {"a subtype no entry routes", func() (*ir.Document, ir.TypeID) { return routedHierarchy(), "type/b" }, true}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + doc, variant := c.doc() + found := withCode(validated(t, doc), unroutedVariant) + if !c.reported { + assert.Empty(t, found) + return + } + require.Len(t, found, 1) + assert.Equal(t, ir.SeverityInfo, found[0].Severity) + assert.True(t, found[0].Provenance.Node == string(variant) || strings.Contains(found[0].Message, string(variant)), + "the finding names the variant: %+v", found[0]) + }) + } +} + +// routedUnion is a union over the models type/x and type/y whose Mapping routes +// x alone, beside decodeOnly and defaultRoute. +func routedUnion(decodeOnly map[string]ir.TypeID, defaultRoute ir.TypeID) *ir.Document { + doc := validDoc() + for _, id := range []ir.TypeID{"type/x", "type/y"} { + doc.Types[id] = &ir.Model{ID: id, Properties: []ir.Property{{ + ID: ir.PropertyID("property/" + id + "/kind"), WireName: "kind", Required: true, + Type: ir.TypeRef{Target: "type/primitive/string"}, + }}} + } + doc.Types["type/u"] = &ir.Union{ID: "type/u", Exclusive: true, WireTagged: true, Closed: true, + Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/x"}}, {Type: ir.TypeRef{Target: "type/y"}}}, + Discriminator: &ir.Discriminator{PropertyName: "kind", Mapping: map[string]ir.TypeID{"x": "type/x"}, + DecodeOnlyRoutes: decodeOnly, Default: defaultRoute}} + return doc +} + +// besideNilMapping is routedUnion with a nil Mapping, type/x named X and +// type/y named name. +func besideNilMapping(name string) *ir.Document { + doc := routedUnion(nil, "") + doc.Types["type/u"].(*ir.Union).Discriminator.Mapping = nil + doc.Types["type/x"].Common().Name = ir.Naming{Source: "X", Canonical: "x"} + doc.Types["type/y"].Common().Name = ir.Naming{Source: name, Canonical: strings.ToLower(name)} + return doc +} + +// routedHierarchy is a base model type/base, abstract, whose discriminator +// routes its subtype type/a and not its subtype type/b. +func routedHierarchy() *ir.Document { + doc := validDoc() + tag := ir.Property{ID: "property/base/kind", WireName: "kind", Required: true, Type: ir.TypeRef{Target: "type/primitive/string"}} + doc.Types["type/base"] = &ir.Model{ID: "type/base", Abstract: true, Properties: []ir.Property{tag}, + Discriminator: &ir.Discriminator{Property: tag.ID, Mapping: map[string]ir.TypeID{"a": "type/a"}}} + for _, id := range []ir.TypeID{"type/a", "type/b"} { + doc.Types[id] = &ir.Model{ID: id, Base: &ir.TypeRef{Target: "type/base"}} + } + return doc +} + +// level is a model of a hierarchy: its supertypes, Base first, then each +// Implements entry, whether it holds a discriminator, and the subtypes that +// discriminator routes, each under its ID as the tag. +type level struct { + supertypes []ir.TypeID + holds bool + routes []ir.TypeID +} + +// hierarchyOf is a document of the models levels names. +func hierarchyOf(levels map[ir.TypeID]level) *ir.Document { + doc := validDoc() + for id, model := range levels { + node := &ir.Model{ID: id} + for i, supertype := range model.supertypes { + if i == 0 { + node.Base = &ir.TypeRef{Target: supertype} + continue + } + node.Implements = append(node.Implements, ir.TypeRef{Target: supertype}) + } + if model.holds { + mapping := map[string]ir.TypeID{} + for _, route := range model.routes { + mapping[string(route)] = route + } + node.Discriminator = &ir.Discriminator{PropertyName: "kind", Mapping: mapping} + } + doc.Types[id] = node + } + return doc +} + +// unroutedSubtypes returns, for each subtype pass/discriminator-unrouted-variant +// reports in diags, the model holding the discriminator it is reported at, and +// whether it is worded as routing only through its subtypes. +func unroutedSubtypes(t *testing.T, diags []ir.Diagnostic) (at map[ir.TypeID]ir.TypeID, throughSubtypes map[ir.TypeID]bool) { + t.Helper() + at, throughSubtypes = map[ir.TypeID]ir.TypeID{}, map[ir.TypeID]bool{} + for _, diagnostic := range withCode(diags, unroutedVariant) { + _, rest, found := strings.Cut(diagnostic.Message, "its subtype ") + require.True(t, found, diagnostic.Message) + subtype := ir.TypeID(strings.FieldsFunc(rest, func(character rune) bool { return character == ' ' || character == ':' })[0]) + require.NotContains(t, at, subtype, "one finding a subtype") + at[subtype] = ir.TypeID(diagnostic.Provenance.Node) + throughSubtypes[subtype] = strings.Contains(diagnostic.Message, "routes only through its subtypes") + assert.Equal(t, ir.SeverityInfo, diagnostic.Severity) + } + return at, throughSubtypes +} + +// TestValidate_ASubtypeIsJudgedOnceByItsNearestDiscriminator holds the +// hierarchy's finding to one a subtype, at the discriminator nearest above it, +// not one a pair of discriminator and subtype: a model below two +// discriminators routing nothing draws one finding, at the nearer, one the +// nearer routes draws none though the farther does not route it, and one the +// farther routes draws one at the nearer. Of two at one distance, the first in +// ID order judges. +func TestValidate_ASubtypeIsJudgedOnceByItsNearestDiscriminator(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + levels map[ir.TypeID]level + want map[ir.TypeID]ir.TypeID + }{ + {"a chain of discriminators routing nothing", map[ir.TypeID]level{ + "type/base": {holds: true}, "type/mid": {supertypes: []ir.TypeID{"type/base"}, holds: true}, + "type/leaf": {supertypes: []ir.TypeID{"type/mid"}}, + }, map[ir.TypeID]ir.TypeID{"type/mid": "type/base", "type/leaf": "type/mid"}}, + {"the nearer routing it", map[ir.TypeID]level{ + "type/base": {holds: true}, "type/mid": {supertypes: []ir.TypeID{"type/base"}, holds: true, routes: []ir.TypeID{"type/leaf"}}, + "type/leaf": {supertypes: []ir.TypeID{"type/mid"}}, + }, map[ir.TypeID]ir.TypeID{"type/mid": "type/base"}}, + {"the farther routing it", map[ir.TypeID]level{ + "type/base": {holds: true, routes: []ir.TypeID{"type/mid", "type/leaf"}}, + "type/mid": {supertypes: []ir.TypeID{"type/base"}, holds: true}, "type/leaf": {supertypes: []ir.TypeID{"type/mid"}}, + }, map[ir.TypeID]ir.TypeID{"type/leaf": "type/mid"}}, + {"two at one distance", map[ir.TypeID]level{ + "type/a": {holds: true}, "type/b": {holds: true, routes: []ir.TypeID{"type/leaf"}}, + "type/leaf": {supertypes: []ir.TypeID{"type/b", "type/a"}}, + }, map[ir.TypeID]ir.TypeID{"type/leaf": "type/a"}}, + {"a cycle back to the discriminator", map[ir.TypeID]level{ + "type/base": {supertypes: []ir.TypeID{"type/leaf"}, holds: true}, "type/leaf": {supertypes: []ir.TypeID{"type/base"}}, + }, map[ir.TypeID]ir.TypeID{"type/leaf": "type/base"}}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + at, _ := unroutedSubtypes(t, validated(t, hierarchyOf(c.levels))) + assert.Equal(t, c.want, at) + }) + } +} + +// TestValidate_ASubtypeRoutedOnlyThroughItsSubtypesIsWordedSo holds an +// abstract subtype, one its discriminator routes no tag to while routing a +// model below it, to a finding worded as routing only through its subtypes: +// it has no route of its own. A route by another discriminator below it makes +// no subtype of the first abstract. +func TestValidate_ASubtypeRoutedOnlyThroughItsSubtypesIsWordedSo(t *testing.T) { + t.Parallel() + for _, c := range []struct { + name string + levels map[ir.TypeID]level + throughSubtypes map[ir.TypeID]bool + }{ + {"a subtype whose subtype is routed", map[ir.TypeID]level{ + "type/pet": {holds: true, routes: []ir.TypeID{"type/kitten"}}, + "type/cat": {supertypes: []ir.TypeID{"type/pet"}}, "type/kitten": {supertypes: []ir.TypeID{"type/cat"}}, + }, map[ir.TypeID]bool{"type/cat": true}}, + {"two levels above the routed one", map[ir.TypeID]level{ + "type/pet": {holds: true, routes: []ir.TypeID{"type/kitten"}}, "type/cat": {supertypes: []ir.TypeID{"type/pet"}}, + "type/young": {supertypes: []ir.TypeID{"type/cat"}}, "type/kitten": {supertypes: []ir.TypeID{"type/young"}}, + }, map[ir.TypeID]bool{"type/cat": true, "type/young": true}}, + {"a subtype routed by a discriminator below it", map[ir.TypeID]level{ + "type/pet": {holds: true}, "type/cat": {supertypes: []ir.TypeID{"type/pet"}, holds: true, routes: []ir.TypeID{"type/kitten"}}, + "type/kitten": {supertypes: []ir.TypeID{"type/cat"}}, + }, map[ir.TypeID]bool{"type/cat": false}}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + _, throughSubtypes := unroutedSubtypes(t, validated(t, hierarchyOf(c.levels))) + assert.Equal(t, c.throughSubtypes, throughSubtypes) + }) + } +} diff --git a/pass/validate_discriminator_tags.go b/pass/validate_discriminator_tags.go new file mode 100644 index 000000000..7a2c51af5 --- /dev/null +++ b/pass/validate_discriminator_tags.go @@ -0,0 +1,292 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass + +import ( + "fmt" + "slices" + + "github.com/dexpace/morphic/ir" + "github.com/dexpace/morphic/scratchstate" +) + +// variantTagReads is what checkVariantTags reads every union through, kept for +// the run: the variants of the union read so far, the walks over a composition +// and their marks, each variant's answer for each tag, made once, and the +// member reader made at the first variant needing one. +type variantTagReads struct { + listed scratchstate.Map[ir.TypeID, bool] + reached visits + evaluating visits + parts []ir.TypeID + evaluators []ir.TypeID + memo map[taggedVariant]*tagReading + members *ir.MemberReader +} + +// taggedVariant is a variant read for the member named tag. +type taggedVariant struct { + variant ir.TypeID + tag string +} + +// tagReading is what the composition of a variant whose flattening holds no +// member of a tag's name says of one: the first type refusing it whatever tag +// it carries, and why, and the types whose catch-all value types the tags +// routing to the variant are judged by, in walk order. +type tagReading struct { + refuser ir.TypeID + why string + catchAlls []ir.TypeID +} + +// refuse records part as the reading's refuser, for why, unless an earlier +// type of the walk refused first. +func (reading *tagReading) refuse(part ir.TypeID, why string) { + if reading.refuser == "" { + reading.refuser, reading.why = part, why + } +} + +// checkVariantTags warns at each variant of a union locating its tag by +// property name, inline, that no payload carrying the tag can be +// (docs/ir/unions.md#tag-modes): its flattening holds no member of the tag's +// name, and a model of its composition refuses one by its closure. Each type +// is read once however many variants name it. live is the run's sorted live +// types. +func checkVariantTags(chains *aliasChains, live []ir.TypeID, union *ir.Union, read *variantTagReads) []ir.Diagnostic { + discriminator := union.Discriminator + if discriminator == nil || discriminator.PropertyName == "" || discriminator.Envelope != "" { + return nil + } + var diags []ir.Diagnostic + listed := read.listed.Emptied() + for _, variant := range union.Variants { + target := variant.Type.Target + if listed[target] { + continue + } + listed[target] = true + reading := read.readingOf(chains, live, target, discriminator.PropertyName) + if reading == nil { + continue + } + refuser, why := reading.refuser, reading.why + if refuser == "" { + refuser, why = read.routedRefuser(chains, union, target, reading.catchAlls) + } + if refuser != "" { + diags = append(diags, diag(ir.SeverityWarning, "pass/discriminator-variant-refuses-tag", + fmt.Sprintf("variant %s of union %s holds no member %q, where its discriminator reads the tag, "+ + "and %s %s, so no payload carrying the tag is a value of it", + target, union.ID, discriminator.PropertyName, refuser, why), + string(union.ID))) + } + } + return diags +} + +// readingOf returns the reading of variant for tag, read once for the run, nil +// where its composition holds no closure that could refuse a member, or its +// flattening holds one named tag. The composition is screened first, so a +// variant composing no closure is never flattened. +func (read *variantTagReads) readingOf(chains *aliasChains, live []ir.TypeID, variant ir.TypeID, tag string) *tagReading { + if read.memo == nil { + read.memo, read.members = map[taggedVariant]*tagReading{}, ir.NewMemberReader(chains.types) + } + key := taggedVariant{variant: variant, tag: tag} + if reading, readBefore := read.memo[key]; readBefore { + return reading + } + var reading *tagReading + read.parts = composition(chains, live, variant, &read.reached, read.parts) + if slices.ContainsFunc(read.parts, func(part ir.TypeID) bool { return holdsClosure(chains.types[part]) }) { + if _, holds := read.members.Member(variant, tag); !holds { + reading = read.readParts(chains, live, tag) + } + } + read.memo[key] = reading + return reading +} + +// readParts reads the closure of each type of read.parts for a member named +// tag none of them declares, as docs/ir/models.md#catch-alls states it, and +// returns the reading, nil where none could refuse one. A catch-all with a +// pattern is not read, as the pattern might match the name. +func (read *variantTagReads) readParts(chains *aliasChains, live []ir.TypeID, tag string) *tagReading { + reading := &tagReading{} + for _, part := range read.parts { + catchAll, additional := closureOf(chains.types[part]) + switch { + case catchAll != nil && len(catchAll.Patterns) > 0: + case catchAll != nil && catchAll.Value != nil: + if catchAll.Key != nil && admitsText(chains, *catchAll.Key, tag) == ir.AdmitsNo { + reading.refuse(part, "types its catch-all's keys so that none is the tag's name") + continue + } + reading.catchAlls = append(reading.catchAlls, part) + case additional == ir.AdditionalClosed: + reading.refuse(part, "is closed") + case additional == ir.AdditionalClosedAfterComposition && !read.evaluated(chains, live, part): + reading.refuse(part, "is closed after composition, and nothing it composes evaluates a member of that name") + default: + } + } + if reading.refuser == "" && len(reading.catchAlls) == 0 { + return nil + } + return reading +} + +// routedRefuser returns the first of catchAlls whose catch-all's value type +// refuses every tag the discriminator of union routes to variant, and why, or +// nothing where each admits one or no tag is listed. +func (read *variantTagReads) routedRefuser(chains *aliasChains, union *ir.Union, + variant ir.TypeID, catchAlls []ir.TypeID, +) (ir.TypeID, string) { + tags := routedTags(chains, union, variant) + if len(tags) == 0 { + return "", "" + } + for _, part := range catchAlls { + catchAll, _ := closureOf(chains.types[part]) + if !slices.ContainsFunc(tags, func(tag string) bool { return admitsText(chains, *catchAll.Value, tag) != ir.AdmitsNo }) { + return part, "types its catch-all's values so that none is a tag routing to the variant" + } + } + return "", "" +} + +// admitsText judges text, as a string value, against the type ref names, +// through the run's admission reader. +func admitsText(chains *aliasChains, ref ir.TypeRef, text string) ir.Admission { + return chains.admission.Admits(ref, ir.Value{Kind: ir.ValueString, String: text}) +} + +// routedTags lists the tags the discriminator of union routes to variant: +// each key of its Mapping or DecodeOnlyRoutes naming it, and the name its type +// routes it by (ir.VariantNameRoute). It is empty where Default names the +// variant, which takes every tag no route lists. +func routedTags(chains *aliasChains, union *ir.Union, variant ir.TypeID) []string { + discriminator := union.Discriminator + if discriminator.Default == variant { + return nil + } + var tags []string + for _, routes := range []map[string]ir.TypeID{discriminator.Mapping, discriminator.DecodeOnlyRoutes} { + for tag, target := range routes { + if target == variant { + tags = append(tags, tag) + } + } + } + if name, byName := ir.VariantNameRoute(union, chains.types[variant]); byName { + tags = append(tags, name) + } + return tags +} + +// composition returns parts holding the types the composition of root reaches +// along Base and Mixins, each read through its alias scalars, root's first, +// marking each live one in marks so it is listed once. Only a live model is +// walked further, so the walk ends within the registry, a cyclic composition +// included. +func composition(chains *aliasChains, live []ir.TypeID, root ir.TypeID, marks *visits, parts []ir.TypeID) []ir.TypeID { + marks.start(len(live)) + parts = appendPart(chains, live, marks, parts[:0], root) + for i := 0; i < len(parts); i++ { + model, isModel := chains.types[parts[i]].(*ir.Model) + if !isModel || model == nil { + continue + } + if model.Base != nil { + parts = appendPart(chains, live, marks, parts, model.Base.Target) + } + for _, mixin := range model.Mixins { + parts = appendPart(chains, live, marks, parts, mixin.Target) + } + } + return parts +} + +// appendPart appends the type target names, its alias chain's end, to parts +// unless it is a live type marks holds. +func appendPart(chains *aliasChains, live []ir.TypeID, marks *visits, parts []ir.TypeID, target ir.TypeID) []ir.TypeID { + target = chains.end(target) + if vertex, isLive := slices.BinarySearch(live, target); isLive && !marks.first(vertex) { + return parts + } + return append(parts, target) +} + +// holdsClosure reports whether typeDef can refuse a member it does not +// declare: a map, or a model with a catch-all or a closure. +func holdsClosure(typeDef ir.TypeDef) bool { + switch t := typeDef.(type) { + case *ir.MapT: + return t != nil + case *ir.Model: + return t != nil && (t.AdditionalProperties != nil || t.Additional != ir.AdditionalUnspecified) + default: + return false + } +} + +// closureOf returns what bounds the members typeDef does not declare: a map's +// key and value types as a catch-all, and a model's catch-all and openness. +func closureOf(typeDef ir.TypeDef) (*ir.AdditionalProperties, ir.AdditionalMode) { + switch t := typeDef.(type) { + case *ir.MapT: + if t != nil { + return &ir.AdditionalProperties{Key: t.Key, Value: &t.Value}, ir.AdditionalUnspecified + } + case *ir.Model: + if t != nil { + return t.AdditionalProperties, t.Additional + } + default: + } + return nil, ir.AdditionalUnspecified +} + +// evaluated reports whether the composition of the model at id, it and what +// it composes along Base and Mixins, holds what evaluates a member none of it +// declares: a catch-all, which a map is, or a union, a variant of which may. +func (read *variantTagReads) evaluated(chains *aliasChains, live []ir.TypeID, id ir.TypeID) bool { + read.evaluators = composition(chains, live, id, &read.evaluating, read.evaluators) + for _, part := range read.evaluators { + if _, isUnion := chains.types[part].(*ir.Union); isUnion { + return true + } + if catchAll, _ := closureOf(chains.types[part]); catchAll != nil { + return true + } + } + return false +} + +// visits marks the live types a walk reaches with the walk's number, so no +// walk clears what the one before it marked. +type visits struct { + marks []int32 + walk int32 +} + +// start begins a walk over count live types. +func (v *visits) start(count int) { + if len(v.marks) != count { + v.marks = make([]int32, count) + } + v.walk++ +} + +// first marks vertex reached by the walk, and reports whether the walk had +// not reached it before. +func (v *visits) first(vertex int) bool { + if v.marks[vertex] == v.walk { + return false + } + v.marks[vertex] = v.walk + return true +} diff --git a/pass/validate_discriminator_tags_test.go b/pass/validate_discriminator_tags_test.go new file mode 100644 index 000000000..20c562243 --- /dev/null +++ b/pass/validate_discriminator_tags_test.go @@ -0,0 +1,246 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// The types the hand-built tag cases share beside validDoc's. +const ( + integerType ir.TypeID = "type/primitive/integer" + uuidType ir.TypeID = "type/primitive/uuid" +) + +// taggedUnion is validDoc holding the union type/u, which tags its variants by +// the property kind, inline, and routes each variant of the variants list +// under the key of its ID, beside the types listed. +func taggedUnion(types []ir.TypeDef, variants ...ir.TypeID) *ir.Document { + doc := validDoc() + doc.Types[integerType] = &ir.Primitive{ID: integerType, PrimitiveKind: ir.PrimitiveInteger} + doc.Types[uuidType] = &ir.Primitive{ID: uuidType, PrimitiveKind: ir.PrimitiveUUID} + for _, typeDef := range types { + doc.Types[typeDef.Common().ID] = typeDef + } + union := &ir.Union{ID: "type/u", Exclusive: true, WireTagged: true, Closed: true, + Discriminator: &ir.Discriminator{PropertyName: "kind", Mapping: map[string]ir.TypeID{}}} + for _, id := range variants { + union.Variants = append(union.Variants, ir.Variant{Type: ir.TypeRef{Target: id}}) + union.Discriminator.Mapping[string(id)] = id + } + doc.Types[union.ID] = union + return doc +} + +// catchAllOf is a reference to target, as a catch-all's value or key types. +func catchAllOf(target ir.TypeID) *ir.TypeRef { return &ir.TypeRef{Target: target} } + +// TestValidate_AVariantsClosureIsReadAsItsCatchAllsTypesSay holds the +// variant-refuses-tag warning to the closure as docs/ir/models.md#catch-alls +// reads it, past the compiled cases of GitHub #1807: a catch-all is judged by +// its key type against the tag's name and by its value type against the tags +// routing to the variant, a pattern might match the name, and a closure after +// composition leaves a member a composed union or catch-all may evaluate. +func TestValidate_AVariantsClosureIsReadAsItsCatchAllsTypesSay(t *testing.T) { + t.Parallel() + stringOf := func(text string) ir.Value { return ir.Value{Kind: ir.ValueString, String: text} } + for _, c := range []struct { + name string + doc func() *ir.Document + warned bool + }{ + {"a map whose key type refuses the tag's name", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.MapT{ID: "type/v", Key: catchAllOf(uuidType), Value: ir.TypeRef{Target: "type/primitive/string"}}}, "type/v") + }, true}, + {"a map whose key and value types admit the tag", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.MapT{ID: "type/v", Value: ir.TypeRef{Target: "type/primitive/string"}}}, "type/v") + }, false}, + {"a closed model whose catch-all writes a pattern", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Additional: ir.AdditionalClosed, + AdditionalProperties: &ir.AdditionalProperties{Patterns: []ir.PatternProperties{{Pattern: "^x", Value: ir.TypeRef{Target: integerType}}}}}}, "type/v") + }, false}, + {"a catch-all refusing every tag routing to the variant", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", AdditionalProperties: &ir.AdditionalProperties{Value: catchAllOf("type/one")}}, + &ir.Literal{ID: "type/one", Value: stringOf("one"), ValueType: ir.PrimitiveString}}, "type/v") + }, true}, + {"a catch-all admitting one tag routing to the variant", func() *ir.Document { + doc := taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", AdditionalProperties: &ir.AdditionalProperties{Value: catchAllOf("type/one")}}, + &ir.Literal{ID: "type/one", Value: stringOf("one"), ValueType: ir.PrimitiveString}}, "type/v") + doc.Types["type/u"].(*ir.Union).Discriminator.DecodeOnlyRoutes = map[string]ir.TypeID{"one": "type/v"} + return doc + }, false}, + {"a catch-all refusing every tag of the variant the default routes to", func() *ir.Document { + doc := taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", AdditionalProperties: &ir.AdditionalProperties{Value: catchAllOf(integerType)}}}, "type/v") + doc.Types["type/u"].(*ir.Union).Discriminator.Default = "type/v" + return doc + }, false}, + {"a catch-all beside an empty mapping, routing a nameless variant by no tag", func() *ir.Document { + doc := taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", AdditionalProperties: &ir.AdditionalProperties{Value: catchAllOf(integerType)}}}, "type/v") + doc.Types["type/u"].(*ir.Union).Discriminator.Mapping = nil + return doc + }, false}, + {"a catch-all beside an empty mapping, refusing the variant's type name", func() *ir.Document { + doc := taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Name: ir.Naming{Source: "V"}, + AdditionalProperties: &ir.AdditionalProperties{Value: catchAllOf(integerType)}}}, "type/v") + doc.Types["type/u"].(*ir.Union).Discriminator.Mapping = nil + return doc + }, true}, + {"closed after composing a union", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Additional: ir.AdditionalClosedAfterComposition, + Mixins: []ir.TypeRef{{Target: "type/either"}}}, + &ir.Union{ID: "type/either", Closed: true, Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/m"}}}}}, "type/v") + }, false}, + {"closed after composing a model that evaluates nothing", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Additional: ir.AdditionalClosedAfterComposition, + Base: &ir.TypeRef{Target: "type/m"}}}, "type/v") + }, true}, + {"closed after composing a map, which evaluates every member", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Additional: ir.AdditionalClosedAfterComposition, + Base: &ir.TypeRef{Target: "type/strings"}}, &ir.MapT{ID: "type/strings", Value: ir.TypeRef{Target: "type/primitive/string"}}}, "type/v") + }, false}, + {"closed, holding the tag through what it implements", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Additional: ir.AdditionalClosed, Implements: []ir.TypeRef{{Target: "type/i"}}}, + &ir.Model{ID: "type/i", Abstract: true, Properties: []ir.Property{{ID: "property/i/kind", WireName: "kind", + Type: ir.TypeRef{Target: "type/primitive/string"}}}}}, "type/v") + }, false}, + {"closed, reached through an alias scalar", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/closed", Additional: ir.AdditionalClosed}, + &ir.Scalar{ID: "type/v", Base: &ir.TypeRef{Target: "type/closed"}}}, "type/v") + }, true}, + {"composing types the registry holds as nil, before a closed one", func() *ir.Document { + doc := taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Base: &ir.TypeRef{Target: "type/gone"}, + Mixins: []ir.TypeRef{{Target: "type/void"}, {Target: "type/closed"}}}, + &ir.Model{ID: "type/closed", Additional: ir.AdditionalClosed}}, "type/v") + doc.Types["type/gone"], doc.Types["type/void"] = (*ir.Model)(nil), (*ir.MapT)(nil) + return doc + }, true}, + {"composing one closed model twice, along a cycle", func() *ir.Document { + return taggedUnion([]ir.TypeDef{&ir.Model{ID: "type/v", Base: &ir.TypeRef{Target: "type/closed"}, + Mixins: []ir.TypeRef{{Target: "type/closed"}}}, + &ir.Model{ID: "type/closed", Additional: ir.AdditionalClosed, Base: &ir.TypeRef{Target: "type/v"}}}, "type/v") + }, true}, + } { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + found := withCode(validated(t, c.doc()), refusesTag) + if !c.warned { + assert.Empty(t, found) + return + } + require.Len(t, found, 1) + assert.Equal(t, "type/u", found[0].Provenance.Node, "at the union holding the discriminator") + assert.Contains(t, found[0].Message, "variant type/v ", "naming the variant") + }) + } +} + +// TestValidate_AVariantRefusingItsTagIsWarnedOnceWhereverItIsListed holds the +// warning to one per type a union lists, and to none where the tag rides in an +// envelope, whose value no closure of the variant reads. +func TestValidate_AVariantRefusingItsTagIsWarnedOnceWhereverItIsListed(t *testing.T) { + t.Parallel() + closed := []ir.TypeDef{&ir.Model{ID: "type/v", Additional: ir.AdditionalClosed}} + twice := taggedUnion(closed, "type/v", "type/v") + assert.Len(t, withCode(validated(t, twice), refusesTag), 1, "a type listed twice") + + inTwoUnions := taggedUnion(closed, "type/v") + second := *inTwoUnions.Types["type/u"].(*ir.Union) + second.ID = "type/u2" + inTwoUnions.Types[second.ID] = &second + found := withCode(validated(t, inTwoUnions), refusesTag) + require.Len(t, found, 2, "a type two unions list, its flattening read once") + assert.Equal(t, []string{"type/u", "type/u2"}, []string{found[0].Provenance.Node, found[1].Provenance.Node}) + + enveloped := taggedUnion(closed, "type/v") + enveloped.Types["type/u"].(*ir.Union).Discriminator.Envelope = "object" + assert.Empty(t, withCode(validated(t, enveloped), refusesTag), "a tag in an envelope") +} + +// TestValidate_AnUnroutedVariantIsReportedOnceAndNullAloneIsReadExactly holds +// the unrouted-variant info to one per type a union lists, and its exception +// to a variant admitting null and nothing else: a nullable reference to an +// enum with a member, or a reference to the empty enum that is not nullable, +// carries a tag. +func TestValidate_AnUnroutedVariantIsReportedOnceAndNullAloneIsReadExactly(t *testing.T) { + t.Parallel() + twice := routedUnion(nil, "") + union := twice.Types["type/u"].(*ir.Union) + union.Variants = append(union.Variants, union.Variants[1]) + assert.Len(t, withCode(validated(t, twice), unroutedVariant), 1, "a type listed twice") + + for name, enum := range map[string]struct { + members []ir.EnumMember + nullable bool + }{ + "a nullable reference to an enum with a member": {members: []ir.EnumMember{{ID: "enum-member/y/a", Value: ir.Value{Kind: ir.ValueString, String: "a"}}}, nullable: true}, + "a reference to the empty enum": {}, + } { + doc := routedUnion(nil, "") + doc.Types["type/y"] = &ir.Enum{ID: "type/y", ValueType: ir.PrimitiveString, Closed: true, Members: enum.members} + doc.Types["type/u"].(*ir.Union).Variants[1].Type.Nullable = enum.nullable + assert.Len(t, withCode(validated(t, doc), unroutedVariant), 1, name) + } +} + +// TestValidate_AnUnroutedSubtypeIsFoundAtAnyDepth holds the unrouted-variant +// info on a hierarchy to every model below the base along ir.Supertypes: a +// grandchild, one below an alias of an alias of a subtype, and one conforming through +// Implements, each reported in ID order, while a cycle leading back to the base +// leaves the base, which is no subtype of itself here, unreported. +func TestValidate_AnUnroutedSubtypeIsFoundAtAnyDepth(t *testing.T) { + t.Parallel() + doc := routedHierarchy() + doc.Types["type/b"] = &ir.Model{ID: "type/b", Base: &ir.TypeRef{Target: "type/a/alias/alias"}} + doc.Types["type/a/alias/alias"] = &ir.Scalar{ID: "type/a/alias/alias", Base: &ir.TypeRef{Target: "type/a/alias"}} + doc.Types["type/a/alias"] = &ir.Scalar{ID: "type/a/alias", Base: &ir.TypeRef{Target: "type/a"}} + doc.Types["type/c"] = &ir.Model{ID: "type/c", Base: &ir.TypeRef{Target: "type/b"}} + doc.Types["type/d"] = &ir.Model{ID: "type/d", Implements: []ir.TypeRef{{Target: "type/base"}}} + doc.Types["type/base"].(*ir.Model).Base = &ir.TypeRef{Target: "type/c"} + + found := withCode(validated(t, doc), unroutedVariant) + named := make([]string, 0, len(found)) + for _, diagnostic := range found { + assert.Equal(t, "type/base", diagnostic.Provenance.Node, "at the base holding the discriminator") + named = append(named, strings.Fields(strings.SplitAfter(diagnostic.Message, "its subtype ")[1])[0]) + } + assert.Equal(t, []string{"type/b:", "type/c:", "type/d:"}, named) +} + +// unionsOfOneClosedVariant is n unions, each tagging by the property kind and +// listing one closed variant that composes a chain of n models, none of which +// declares the tag. +func unionsOfOneClosedVariant(count int) *ir.Document { + types, bottom := chainedProperties(count) + types["type/v"] = &ir.Model{ID: "type/v", Additional: ir.AdditionalClosed, Base: &ir.TypeRef{Target: bottom}} + for i := range count { + id := ir.TypeID(fmt.Sprintf("type/u%05d", i)) + types[id] = &ir.Union{ID: id, Exclusive: true, WireTagged: true, Closed: true, + Variants: []ir.Variant{{Type: ir.TypeRef{Target: "type/v"}}}, + Discriminator: &ir.Discriminator{PropertyName: "kind", Mapping: map[string]ir.TypeID{"v": "type/v"}}} + } + return &ir.Document{IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: types} +} + +// TestValidate_AVariantManyUnionsListIsFlattenedOnce holds the bytes the +// variant-refuses-tag check allocates to linear growth, as +// TestValidate_DiscriminatorRoutesCostLinearWork does for routes, where n +// unions list one variant whose composition is n models deep: its flattening +// is read once for the run, where reading it per union would grow with the +// square of n. It does not run in parallel, since the count is process-wide. +func TestValidate_AVariantManyUnionsListIsFlattenedOnce(t *testing.T) { + var bytes [3]float64 + for k, n := range []int{250, 500, 1000} { + _, bytes[k] = costAround(t, n, unionsOfOneClosedVariant, func(t *testing.T, size int, diags []ir.Diagnostic) { + require.Len(t, withCode(diags, refusesTag), size, "each union must reach the variant's closure, or the sizes compare nothing") + }) + } + assert.LessOrEqual(t, bytes[2]-bytes[1], 2.5*(bytes[1]-bytes[0]), "bytes around 250, 500, 1000: %v", bytes) +} diff --git a/pass/validate_discriminators.go b/pass/validate_discriminators.go index d3a296aec..20a94e2b5 100644 --- a/pass/validate_discriminators.go +++ b/pass/validate_discriminators.go @@ -13,15 +13,19 @@ import ( ) // checkDiscriminators reports discriminator mappings whose target either does -// not exist or is not a legal variant/subtype, and a model discriminator whose -// tag property the model does not expose. facts indexes doc. -func checkDiscriminators(doc *ir.Document, live []ir.TypeID, facts *irfacts.DocumentFacts) []ir.Diagnostic { +// not exist or is not a legal variant/subtype, a model discriminator whose tag +// property the model does not expose, a union variant no payload carrying its +// tag can be, and a variant or subtype no route reaches. facts indexes doc, +// live is its sorted live types, and chains the run's memo of its alias chains. +func checkDiscriminators(doc *ir.Document, live []ir.TypeID, facts *irfacts.DocumentFacts, chains *aliasChains) []ir.Diagnostic { var diags []ir.Diagnostic - var read mappingReads + var read discriminatorReads for _, id := range live { switch t := doc.Types[id].(type) { case *ir.Union: diags = append(diags, checkUnionDiscriminator(doc, t, &read)...) + diags = append(diags, checkVariantTags(chains, live, t, &read.tags)...) + diags = append(diags, checkUnroutedVariants(chains, t, &read.routes)...) case *ir.Model: diags = append(diags, checkModelDiscriminator(doc, facts, t, &read)...) default: @@ -30,22 +34,23 @@ func checkDiscriminators(doc *ir.Document, live []ir.TypeID, facts *irfacts.Docu // kind must add a case above rather than fall through here. } } - return diags + return append(diags, checkUnroutedSubtypes(chains, live, facts, &read.routes)...) } -// mappingReads is what checkDiscriminators reads each discriminator through, -// so none costs a collection of its own: a union's variant targets, and a -// mapping's keys, sorted. -type mappingReads struct { +// discriminatorReads is what checkDiscriminators reads each discriminator +// through, so none costs a collection of its own: a union's variant targets, +// a mapping's keys, sorted, and what the tag and route checks read. +type discriminatorReads struct { variants scratchstate.Map[ir.TypeID, bool] keys []string + tags variantTagReads + routes routeReads } // checkUnionDiscriminator requires each mapping target to be one of the union's // variant targets. It asks nothing of what a variant declares of the tag -// (docs/ir/unions.md#tag-modes), so a closed variant declaring no tag member, -// which no tagged payload can be, passes (GitHub #1807). -func checkUnionDiscriminator(doc *ir.Document, union *ir.Union, read *mappingReads) []ir.Diagnostic { +// (docs/ir/unions.md#tag-modes), which checkVariantTags reads. +func checkUnionDiscriminator(doc *ir.Document, union *ir.Union, read *discriminatorReads) []ir.Diagnostic { if union.Discriminator == nil { return nil } @@ -63,7 +68,7 @@ func checkUnionDiscriminator(doc *ir.Document, union *ir.Union, read *mappingRea // Abstract, whose own instances are a payload too // (docs/ir/models.md#discriminator), and the tag property to be one this model // exposes. Its routes and tag are asked of facts, the one index of the run. -func checkModelDiscriminator(doc *ir.Document, facts *irfacts.DocumentFacts, model *ir.Model, read *mappingReads) []ir.Diagnostic { +func checkModelDiscriminator(doc *ir.Document, facts *irfacts.DocumentFacts, model *ir.Model, read *discriminatorReads) []ir.Diagnostic { if model.Discriminator == nil { return nil } @@ -95,42 +100,52 @@ func checkDiscriminatorProperty(facts *irfacts.DocumentFacts, model *ir.Model) [ } // checkMapping validates every routing target a discriminator names — each -// wire-value mapping entry and the Default an unrecognized tag falls back to. -// All of them must resolve in the registry and satisfy member. Default names -// the type an instance deserializes into, so it is held to the same claim as a -// mapping entry. +// wire-value mapping entry, each decode-only route, and the Default an +// unrecognized tag falls back to. Each names the type an instance +// deserializes into, so each must resolve in the registry and satisfy member. // // A target that resolves nowhere is reported here and again by // checkDanglingRefs, deliberately: ir/dangling-type-ref says the document is // not referentially closed, while pass/discriminator-missing-variant says this // discriminator cannot route that wire value, which a polymorphic decoder's // emitter subscribes to. Neither consumer should need the other's code. -func checkMapping(doc *ir.Document, discriminator *ir.Discriminator, where string, read *mappingReads, +func checkMapping(doc *ir.Document, discriminator *ir.Discriminator, where string, read *discriminatorReads, + member func(ir.TypeID) bool, +) []ir.Diagnostic { + diags := checkRoutes(doc, discriminator.Mapping, "mapping", where, read, member) + diags = append(diags, checkRoutes(doc, discriminator.DecodeOnlyRoutes, "decode-only route", where, read, member)...) + if discriminator.Default == "" { + return diags + } + if legal, why := mappingTarget(doc, discriminator.Default, member); !legal { + diags = append(diags, missingVariant("default", where, discriminator.Default, why)) + } + return diags +} + +// checkRoutes reports each target routes maps a wire value to that is no legal +// target (mappingTarget), labelling its position as a route of kind, such as +// "mapping", keyed by its wire value. +func checkRoutes(doc *ir.Document, routes map[string]ir.TypeID, kind, where string, read *discriminatorReads, member func(ir.TypeID) bool, ) []ir.Diagnostic { var diags []ir.Diagnostic // Asked in ascending key order, sorted in read's list, so map iteration // reaches neither the output nor the questions member asks. read.keys = read.keys[:0] - for key := range discriminator.Mapping { + for key := range routes { read.keys = append(read.keys, key) } slices.Sort(read.keys) for _, key := range read.keys { - target := discriminator.Mapping[key] + target := routes[key] if target == "" { continue // it names nothing to route to, which checkEmptyRefs reports alone } if legal, why := mappingTarget(doc, target, member); !legal { - diags = append(diags, missingVariant(fmt.Sprintf("mapping %q", key), where, target, why)) + diags = append(diags, missingVariant(fmt.Sprintf("%s %q", kind, key), where, target, why)) } } - if discriminator.Default == "" { - return diags - } - if legal, why := mappingTarget(doc, discriminator.Default, member); !legal { - diags = append(diags, missingVariant("default", where, discriminator.Default, why)) - } return diags } diff --git a/pass/validate_discriminators_test.go b/pass/validate_discriminators_test.go index 2f27833a3..bb1cd8604 100644 --- a/pass/validate_discriminators_test.go +++ b/pass/validate_discriminators_test.go @@ -32,7 +32,7 @@ func TestValidate_DiscriminatorMissingVariant(t *testing.T) { } // TestValidate_ModelDiscriminator drives checkModelDiscriminator over the ways -// a mapping target can stand to the base: a subtype through Base and one +// a mapping target can relate to the base: a subtype through Base and one // through Implements, which are legal, and a non-model target and a model that // is neither, which are not. TestValidate_SubtypeThroughAliasChain covers a // base reached through an alias. @@ -288,8 +288,8 @@ func discriminatorArms() []struct { // so a Default outside the discriminated set has an emitter deserializing into a // type the discriminator does not admit. // -// The target here resolves, which is the whole point: the reference walk stays -// silent on it, so nothing but the membership claim can catch it. +// The target here resolves, which is the whole point: the reference walk +// reports nothing on it, so nothing but the membership claim can catch it. func TestValidate_DiscriminatorDefaultIsHeldToVariantMembership(t *testing.T) { t.Parallel() for _, tc := range discriminatorArms() { @@ -306,10 +306,10 @@ func TestValidate_DiscriminatorDefaultIsHeldToVariantMembership(t *testing.T) { } } -// TestValidate_LegalDiscriminatorDefaultIsClean is the silent half: a Default -// naming a legal member reports nothing, and neither does the zero value, which -// is how every discriminator without a declared fallback arrives. A check that -// cannot stay silent is no better than one that cannot fire. +// TestValidate_LegalDiscriminatorDefaultIsClean is the report-nothing half: a +// Default naming a legal member reports nothing, and neither does the zero +// value, which is how every discriminator without a declared fallback arrives. +// A check that cannot report nothing is no better than one that cannot fire. func TestValidate_LegalDiscriminatorDefaultIsClean(t *testing.T) { t.Parallel() for _, tc := range discriminatorArms() { @@ -338,6 +338,122 @@ func TestValidate_DanglingDiscriminatorDefaultIsReportedTwice(t *testing.T) { } } +// decodeOnlyArms pairs each kind that can declare a discriminator with the +// node holding it, the one target that is a legal member, and a builder of a +// document whose discriminator there maps the wire value "a" legally. +func decodeOnlyArms() []struct { + name, where string + legal ir.TypeID + doc func() *ir.Document +} { + return []struct { + name, where string + legal ir.TypeID + doc func() *ir.Document + }{ + {"union", "type/u", "type/m", func() *ir.Document { return discriminatedUnion("type/m") }}, + {"model", "type/base", "type/sub", func() *ir.Document { return discriminatedModel("type/sub") }}, + } +} + +// discriminatorAt returns the discriminator the union or model at id in doc +// declares, failing t where id holds neither. +func discriminatorAt(t *testing.T, doc *ir.Document, id ir.TypeID) *ir.Discriminator { + t.Helper() + switch node := doc.Types[id].(type) { + case *ir.Union: + return node.Discriminator + case *ir.Model: + return node.Discriminator + default: + require.FailNow(t, "no union or model declares a discriminator", "at %s: %T", id, node) + return nil + } +} + +// routeMessage is the finding a discriminator on where draws for routing the +// decode-only key to target, which why says is no legal target. +func routeMessage(key, where string, target ir.TypeID, why string) string { + return fmt.Sprintf("discriminator decode-only route %q on %s references %q, which %s", key, where, target, why) +} + +// missingVariantMessages returns the message of each +// pass/discriminator-missing-variant finding Validate draws on doc, in order. +func missingVariantMessages(t *testing.T, doc *ir.Document) []string { + t.Helper() + found := withCode(validated(t, doc), "pass/discriminator-missing-variant") + messages := make([]string, 0, len(found)) + for _, diagnostic := range found { + messages = append(messages, diagnostic.Message) + } + return messages +} + +// TestValidate_DecodeOnlyRoutesAreHeldToVariantMembership pins that each +// decode-only route is held to the claim a mapped wire value is: a decoder +// routes a payload carrying its tag there, so a target no type declares, or +// one the discriminator does not admit, is reported, the first beside its +// dangling reference. A legal target beside them draws nothing, nor does an +// empty one, which ir/empty-type-ref reports alone. +func TestValidate_DecodeOnlyRoutesAreHeldToVariantMembership(t *testing.T) { + t.Parallel() + const undeclared, notVariant = "no type in the document declares", "is not a variant of it" + for _, arm := range decodeOnlyArms() { + for _, tc := range []struct { + name string + routes map[string]ir.TypeID + want []string + dangling, empty int + }{ + { + name: "a target no type declares", routes: map[string]ir.TypeID{"x": "type/ghost"}, + want: []string{routeMessage("x", arm.where, "type/ghost", undeclared)}, dangling: 1, + }, + { + name: "a target that is no variant", routes: map[string]ir.TypeID{"x": "type/primitive/string"}, + want: []string{routeMessage("x", arm.where, "type/primitive/string", notVariant)}, + }, + { + name: "a legal target beside one that is not", routes: map[string]ir.TypeID{"x": arm.legal, "y": "type/primitive/string"}, + want: []string{routeMessage("y", arm.where, "type/primitive/string", notVariant)}, + }, + { + name: "an empty target beside one that is not", routes: map[string]ir.TypeID{"x": "", "y": "type/primitive/string"}, + want: []string{routeMessage("y", arm.where, "type/primitive/string", notVariant)}, empty: 1, + }, + } { + t.Run(arm.name+"/"+tc.name, func(t *testing.T) { + t.Parallel() + doc := arm.doc() + discriminatorAt(t, doc, ir.TypeID(arm.where)).DecodeOnlyRoutes = tc.routes + assert.Equal(t, tc.want, missingVariantMessages(t, doc)) + diags := validated(t, doc) + assert.Equal(t, tc.dangling, countCode(t, diags, "ir/dangling-type-ref")) + assert.Equal(t, tc.empty, countCode(t, diags, "ir/empty-type-ref")) + }) + } + } +} + +// TestValidate_DecodeOnlyRoutesAreReportedAfterTheMappingAndBeforeTheDefault +// pins where a discriminator's decode-only routes are asked: after every +// Mapping entry, a key sorting after theirs included, each in ascending key +// order, and before the Default. +func TestValidate_DecodeOnlyRoutesAreReportedAfterTheMappingAndBeforeTheDefault(t *testing.T) { + t.Parallel() + doc := discriminatedUnion("type/m") + discriminator := discriminatorAt(t, doc, "type/u") + discriminator.Mapping["z"] = "type/ghost" + discriminator.DecodeOnlyRoutes = map[string]ir.TypeID{"c": "type/primitive/string", "b": "type/ghost"} + discriminator.Default = "type/primitive/string" + assert.Equal(t, []string{ + `discriminator mapping "z" on type/u references "type/ghost", which no type in the document declares`, + `discriminator decode-only route "b" on type/u references "type/ghost", which no type in the document declares`, + `discriminator decode-only route "c" on type/u references "type/primitive/string", which is not a variant of it`, + `discriminator default on type/u references "type/primitive/string", which is not a variant of it`, + }, missingVariantMessages(t, doc)) +} + // TestValidate_MappingDiagnosticsAreDeterministic pins invariant 7 for a // discriminator's Mapping, whose keys Go ranges in randomized order: they are // asked in sorted order, so the reports within one discriminator, all placed at diff --git a/pass/validate_emptyrefs_sweep_test.go b/pass/validate_emptyrefs_sweep_test.go index 0398a38bc..1a2c7343b 100644 --- a/pass/validate_emptyrefs_sweep_test.go +++ b/pass/validate_emptyrefs_sweep_test.go @@ -51,28 +51,28 @@ func isIDClass(t reflect.Type) bool { } // value finds the sites below v; commit writes v back where it was copied from. -func (c *siteCollector) value(v reflect.Value, commit func(), depth int) { +func (c *siteCollector) value(value reflect.Value, commit func(), depth int) { require.Less(c.t, depth, maxSiteDepth, "the document nests deeper than the sweep reads") - switch v.Kind() { + switch value.Kind() { case reflect.Pointer, reflect.Interface: - if !v.IsNil() { - c.value(v.Elem(), commit, depth+1) + if !value.IsNil() { + c.value(value.Elem(), commit, depth+1) } case reflect.Struct: - if !v.CanSet() { + if !value.CanSet() { return } - for i := range v.NumField() { - if v.Type().Field(i).IsExported() { - c.field(v, i, commit, depth) + for i := range value.NumField() { + if value.Type().Field(i).IsExported() { + c.field(value, i, commit, depth) } } case reflect.Slice: - for i := range v.Len() { - c.value(v.Index(i), commit, depth+1) + for i := range value.Len() { + c.value(value.Index(i), commit, depth+1) } case reflect.Map: - c.entries(v, commit, depth) + c.entries(value, commit, depth) default: } } @@ -108,23 +108,23 @@ func (c *siteCollector) field(owner reflect.Value, i int, commit func(), depth i // entries finds the sites below each value of m, a map's struct value through a // copy written back by its commit. -func (c *siteCollector) entries(m reflect.Value, commit func(), depth int) { - for _, k := range sortedKeys(m) { - val := m.MapIndex(k) +func (c *siteCollector) entries(value reflect.Value, commit func(), depth int) { + for _, k := range sortedKeys(value) { + val := value.MapIndex(k) if val.Kind() != reflect.Struct { c.value(val, commit, depth+1) continue } held := reflect.New(val.Type()).Elem() held.Set(val) - c.value(held, func() { m.SetMapIndex(k, held); commit() }, depth+1) + c.value(held, func() { value.SetMapIndex(k, held); commit() }, depth+1) } } // sortedKeys returns m's keys in the order their spellings sort, so the sweep // blanks the same sites on every run. -func sortedKeys(m reflect.Value) []reflect.Value { - keys := m.MapKeys() +func sortedKeys(value reflect.Value) []reflect.Value { + keys := value.MapKeys() slices.SortFunc(keys, func(a, b reflect.Value) int { return strings.Compare(fmt.Sprint(a.Interface()), fmt.Sprint(b.Interface())) }) @@ -133,44 +133,44 @@ func sortedKeys(m reflect.Value) []reflect.Value { // scalar records the ID v, held by owner at position, unless the position is // another check's: an entity's own ID and a TypeRef's target. -func (c *siteCollector) scalar(owner reflect.Value, position string, v reflect.Value, commit func()) { - if v.String() == "" || strings.HasSuffix(position, ".ID") || position == "TypeRef.Target" { +func (c *siteCollector) scalar(owner reflect.Value, position string, value reflect.Value, commit func()) { + if value.String() == "" || strings.HasSuffix(position, ".ID") || position == "TypeRef.Target" { return } - c.sites = append(c.sites, blankSite{position: position, class: v.Type(), emptyForm: hasEmptyForm(owner, position), + c.sites = append(c.sites, blankSite{position: position, class: value.Type(), emptyForm: hasEmptyForm(owner, position), blank: func() func() { - was := v.String() - v.SetString("") + was := value.String() + value.SetString("") commit() - return func() { v.SetString(was); commit() } + return func() { value.SetString(was); commit() } }}) } // mapValue records the ID map m holds under key k. -func (c *siteCollector) mapValue(position string, m, k reflect.Value, commit func()) { - was := m.MapIndex(k) +func (c *siteCollector) mapValue(position string, value, k reflect.Value, commit func()) { + was := value.MapIndex(k) if was.String() == "" { return } c.sites = append(c.sites, blankSite{position: position, class: was.Type(), blank: func() func() { - m.SetMapIndex(k, reflect.Zero(was.Type())) + value.SetMapIndex(k, reflect.Zero(was.Type())) commit() - return func() { m.SetMapIndex(k, was); commit() } + return func() { value.SetMapIndex(k, was); commit() } }}) } // mapKey records the ID map m holds as the key k. -func (c *siteCollector) mapKey(position string, m, k reflect.Value, commit func()) { +func (c *siteCollector) mapKey(position string, value, k reflect.Value, commit func()) { if k.String() == "" { return } empty := reflect.Zero(k.Type()) c.sites = append(c.sites, blankSite{position: position, class: k.Type(), blank: func() func() { - val := m.MapIndex(k) - m.SetMapIndex(k, reflect.Value{}) - m.SetMapIndex(empty, val) + val := value.MapIndex(k) + value.SetMapIndex(k, reflect.Value{}) + value.SetMapIndex(empty, val) commit() - return func() { m.SetMapIndex(empty, reflect.Value{}); m.SetMapIndex(k, val); commit() } + return func() { value.SetMapIndex(empty, reflect.Value{}); value.SetMapIndex(k, val); commit() } }}) } @@ -227,8 +227,8 @@ type sweepDocument struct { func sweepDocuments(t *testing.T) []sweepDocument { t.Helper() var out []sweepDocument - err := filepath.WalkDir("../testdata", func(path string, d fs.DirEntry, err error) error { - if err != nil || d.IsDir() || !strings.HasSuffix(path, ".golden.json") { + err := filepath.WalkDir("../testdata", func(path string, dirEntry fs.DirEntry, err error) error { + if err != nil || dirEntry.IsDir() || !strings.HasSuffix(path, ".golden.json") { return err } doc, err := irtest.ReadGolden(path) @@ -297,9 +297,9 @@ func TestValidate_BlankingAReferenceDrawsOneFindingFromBothCheckers(t *testing.T for _, sweepDocument := range sweepDocuments(t) { baseEmpty, baseOther := emptyRefFindings(validated(t, sweepDocument.doc)) require.Empty(t, baseEmpty, "%s holds no empty reference before the sweep", sweepDocument.name) - siteCollectorValue := siteCollector{t: t} - siteCollectorValue.value(reflect.ValueOf(sweepDocument.doc), func() {}, 0) - for _, blankSite := range siteCollectorValue.sites { + siteCollector := siteCollector{t: t} + siteCollector.value(reflect.ValueOf(sweepDocument.doc), func() {}, 0) + for _, blankSite := range siteCollector.sites { if blanked[blankSite.position] >= sitesPerPosition { continue } @@ -315,18 +315,18 @@ func TestValidate_BlankingAReferenceDrawsOneFindingFromBothCheckers(t *testing.T // assertBlankedFindings blanks blankSiteValue in sweepDocumentValue and holds // what each checker reports to the position's form; baseOther are the errors // sweepDocumentValue drew before. -func assertBlankedFindings(t *testing.T, sweepDocumentValue sweepDocument, blankSiteValue blankSite, baseOther []string) { +func assertBlankedFindings(t *testing.T, sweepDocument sweepDocument, blankSite blankSite, baseOther []string) { t.Helper() - restore := blankSiteValue.blank() - empty, other := emptyRefFindings(validated(t, sweepDocumentValue.doc)) - verified := verifiedEmptyRefs(sweepDocumentValue.doc) + restore := blankSite.blank() + empty, other := emptyRefFindings(validated(t, sweepDocument.doc)) + verified := verifiedEmptyRefs(sweepDocument.doc) restore() - where := sweepDocumentValue.name + ": " + blankSiteValue.position - if blankSiteValue.emptyForm { + where := sweepDocument.name + ": " + blankSite.position + if blankSite.emptyForm { assert.Empty(t, empty, "%s has an empty form", where) } else if assert.Len(t, empty, 1, "%s has no empty form", where) { - assert.True(t, strings.HasPrefix(empty[0], "ir/empty-"+ir.RefNoun(blankSiteValue.class)+"-ref @ "), "%s drew %s", where, empty[0]) + assert.True(t, strings.HasPrefix(empty[0], "ir/empty-"+ir.RefNoun(blankSite.class)+"-ref @ "), "%s drew %s", where, empty[0]) for _, finding := range other { if !slices.Contains(baseOther, finding) { assert.NotContains(t, finding, `""`, "%s: an empty reference draws no second error", where) diff --git a/pass/validate_enum_bounds_test.go b/pass/validate_enum_bounds_test.go new file mode 100644 index 000000000..7113df7a8 --- /dev/null +++ b/pass/validate_enum_bounds_test.go @@ -0,0 +1,80 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/ir" +) + +// TestValidate_AnEnumsBoundsAreRead holds pass.Validate to the bounds an Enum +// holds (GitHub #2004): a default an open enum does not list is judged by its +// kind and against the enum's bounds, refused only past them or of another +// kind; a closed enum refuses one it does not list, within its bounds or not, +// and a listed value past its bounds, as the IR's admission reader does; a +// flags enum's unlisted value is not judged; and an enum whose own bounds +// cross admits no value, closed or open. +func TestValidate_AnEnumsBoundsAreRead(t *testing.T) { + t.Parallel() + members := []ir.EnumMember{{ID: "enum-member/a", Value: *text("a")}, {ID: "enum-member/bb", Value: *text("bb")}} + enumOf := func(id ir.TypeID, closed bool, constraints *ir.Constraints) *ir.Enum { + return &ir.Enum{ID: id, ValueType: ir.PrimitiveString, Closed: closed, Members: members, Constraints: constraints, Provenance: provAt(string(id))} + } + upToFour := lengths(0, 4) + at := func(value *ir.Value, target ir.TypeID) *ir.Document { + doc := modelOf(property("property/a/c", ir.TypeRef{Target: target}, defaulted(value))) + flags := enumOf("type/flags", false, nil) + flags.Flags = true + for _, typeDef := range []ir.TypeDef{ + enumOf("type/open", false, upToFour), enumOf("type/bare", false, nil), enumOf("type/closed", true, upToFour), + enumOf("type/tight", true, lengths(0, 1)), flags, + } { + doc.Types[typeDef.Common().ID] = typeDef + } + return doc + } + for _, tc := range []struct { + name string + doc *ir.Document + // words are words of the one finding the default draws, or "" for none. + words string + }{ + {"a listed value of an open enum", at(text("bb"), "type/open"), ""}, + {"an unlisted value within an open enum's bounds", at(text("ccc"), "type/open"), ""}, + {"an unlisted value past an open enum's bounds", at(text("ccccc"), "type/open"), "default lies outside the bounds declared for it"}, + {"an unlisted value of an open enum with no bounds", at(text("anything"), "type/bare"), ""}, + {"a value of another kind for an open enum", at(number("1"), "type/open"), "default is a number"}, + {"an unlisted value within a closed enum's bounds", at(text("ccc"), "type/closed"), "default is not a member of enum type/closed"}, + {"a listed value past the enum's bounds", at(text("bb"), "type/tight"), "default lies outside the bounds declared for it"}, + {"an unlisted value of a flags enum, which may combine members", at(text("a|bb"), "type/flags"), ""}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := found(t, tc.doc, defaultCode) + if tc.words == "" { + assert.Empty(t, got) + return + } + if assert.Len(t, got, 1) { + assert.Equal(t, "property/a/c", got[0].node) + assert.Contains(t, got[0].message, tc.words) + } + }) + } + + nullable := modelOf(property("property/a/n", ir.TypeRef{Target: "type/closed", Nullable: true}, defaulted(null()))) + nullable.Types["type/closed"] = enumOf("type/closed", true, upToFour) + assert.Empty(t, found(t, nullable, defaultCode), "a null the reference admits is no value the enum judges") + + crossed := &ir.Constraints{MinLength: new(int64(3)), MaxLength: new(int64(1))} + for _, closed := range []bool{false, true} { + doc := valueDoc() + doc.Types["type/x"] = enumOf("type/x", closed, crossed) + assert.Equal(t, []finding{{"type/x", "bounds admit no string: none has at least 3 characters and at most 1"}}, + found(t, doc, "pass/bounds-admit-no-value"), "closed: %t", closed) + } +} diff --git a/pass/validate_enummembers.go b/pass/validate_enummembers.go index b9a8e42a0..a39ca314f 100644 --- a/pass/validate_enummembers.go +++ b/pass/validate_enummembers.go @@ -5,6 +5,8 @@ package pass import ( "fmt" + "strconv" + "strings" "github.com/dexpace/morphic/ir" "github.com/dexpace/morphic/scratchstate" @@ -41,3 +43,91 @@ func checkDuplicateMemberIDs(doc *ir.Document, live []ir.TypeID) []ir.Diagnostic } return diags } + +// checkMembersOutsideBounds warns at each Enum whose own Constraints refuse +// some of its members, as the run's value admission reader judges them, naming +// each with the bounds refusing it (pass/enum-member-outside-bounds, +// docs/ir/enums.md#bounds); a member the reader cannot judge is not named. An +// enum they refuse every member of is the compiler's to report +// (openapi/unsatisfiable-schema), and one whose bounds admit no value of its +// kind is pass/bounds-admit-no-value's. +func checkMembersOutsideBounds(doc *ir.Document, chains *aliasChains, live []ir.TypeID) []ir.Diagnostic { + var diags []ir.Diagnostic + for _, id := range live { + enum, ok := doc.Types[id].(*ir.Enum) + if !ok || enum.Constraints == nil { + continue + } + refused := 0 + for i := range enum.Members { + if memberRefused(chains, id, &enum.Members[i]) { + refused++ + } + } + if refused == 0 || refused == len(enum.Members) || chains.typeUnsatisfiable(id, enum) != "" { + continue + } + diags = append(diags, diagAt("pass/enum-member-outside-bounds", + "enum lists members its own bounds refuse, so no instance is one of them: "+refusedMembers(chains, id, enum), + string(id), enum.Provenance)) + } + return diags +} + +// memberRefused reports whether the run's value admission reader refuses +// enumMember's value against the enum the type id names, which lists it, so +// only the enum's bounds can. +func memberRefused(chains *aliasChains, id ir.TypeID, enumMember *ir.EnumMember) bool { + return chains.admission.Admits(ir.TypeRef{Target: id}, enumMember.Value) == ir.AdmitsNo +} + +// refusedMembers spells each member of enum, the type id names, that its +// bounds refuse (memberRefused), in member order, with the bounds refusing it. +func refusedMembers(chains *aliasChains, id ir.TypeID, enum *ir.Enum) string { + var spelled []string + for i := range enum.Members { + if memberRefused(chains, id, &enum.Members[i]) { + value := enum.Members[i].Value + spelled = append(spelled, memberText(value)+" by its "+boundsRefusing(enum.Constraints, value)) + } + } + return strings.Join(spelled, "; ") +} + +// memberText spells a member's value for a message: a string quoted, a number +// as written, and any other, bytes being the one other kind a bound refuses, +// by its member key (ir.EnumMemberKey). +func memberText(value ir.Value) string { + if value.Kind == ir.ValueString { + return strconv.Quote(value.String) + } + if value.Kind == ir.ValueNumber { + return string(value.Number) + } + key, _ := ir.EnumMemberKey(value) + return key +} + +// boundsRefusing names, by its IR JSON member, each keyword constraints sets +// that refuses value held alone (ir.ConstraintsAdmit), joined by "and". +func boundsRefusing(constraints *ir.Constraints, value ir.Value) string { + var names []string + for keyword := range ir.ConstraintKeywords() { + if constraints.SetsKeyword(keyword) && ir.ConstraintsAdmit(holdingAlone(constraints, keyword), value) == ir.AdmitsNo { + names = append(names, keyword.String()) + } + } + return strings.Join(names, " and ") +} + +// holdingAlone is a new set holding constraints' value of keyword and of no +// other keyword. +func holdingAlone(constraints *ir.Constraints, keyword ir.ConstraintKeyword) *ir.Constraints { + var others []ir.ConstraintKeyword + for other := range ir.ConstraintKeywords() { + if other != keyword { + others = append(others, other) + } + } + return constraints.WithoutKeywords(others...) +} diff --git a/pass/validate_goldens_test.go b/pass/validate_goldens_test.go index 608f70298..cc9c5b725 100644 --- a/pass/validate_goldens_test.go +++ b/pass/validate_goldens_test.go @@ -65,17 +65,15 @@ func TestValidate_BoundsFireOnTheGoldensWhereTheirSpecsContradictThemselves(t *t } // TestValidate_DefaultsFireOnTheGoldensWhereTheirTypeAdmitsNothingLikeThem holds -// pass/default-outside-type to the two defaults under testdata that their -// types do not admit: bytes on a string, and a string past a maximum length -// written on the allOf branch it is declared in. Every other default of the -// goldens, null on a nullable string and a list among them, is admitted. +// pass/default-outside-type to the one default under testdata that its type +// does not admit: bytes on a string. Every other default of the goldens, null +// on a nullable string and a list among them, is admitted; one past a bound its +// own allOf declaration writes is refused by the fold and reaches no property. func TestValidate_DefaultsFireOnTheGoldensWhereTheirTypeAdmitsNothingLikeThem(t *testing.T) { t.Parallel() got := onTheGoldens(t, validatesOnce(t), withTheCode(defaultCode)) assert.Equal(t, []string{ - schemas + "allof-redeclared-bounds.golden.json @ " + componentsOf + "DefaultPastItsOwnBound/allOf/0/properties/p: " + - "default lies outside the bounds declared for it", schemas + "defaults.golden.json @ " + componentsOf + "S/properties/blob: " + "default is bytes, and type/primitive/string holds a string", }, got) diff --git a/pass/validate_graphql.go b/pass/validate_graphql.go index 1aeb8d7cc..0b93e40c5 100644 --- a/pass/validate_graphql.go +++ b/pass/validate_graphql.go @@ -82,12 +82,12 @@ func graphqlReachableTypes(doc *ir.Document) (map[ir.TypeID]bool, bool) { // EntityRef are passed over, as ir.TypeEdges passes them: neither uses what it // names. func appendTypeIDs(dst []ir.TypeID, root any) []ir.TypeID { - ir.WalkValues(root, "", ir.VisitFunc(func(v reflect.Value, _ ir.WalkPath) bool { - if v.Kind() == reflect.Struct && namingTypes[v.Type()] { + ir.WalkValues(root, "", ir.VisitFunc(func(value reflect.Value, _ ir.WalkPath) bool { + if value.Kind() == reflect.Struct && namingTypes[value.Type()] { return false } - if v.Kind() == reflect.String && v.Type() == typeIDType && v.String() != "" { - dst = append(dst, ir.TypeID(v.String())) + if value.Kind() == reflect.String && value.Type() == typeIDType && value.String() != "" { + dst = append(dst, ir.TypeID(value.String())) } return true })) diff --git a/pass/validate_graphql_test.go b/pass/validate_graphql_test.go index 7decd3f80..7f1b62951 100644 --- a/pass/validate_graphql_test.go +++ b/pass/validate_graphql_test.go @@ -253,13 +253,13 @@ func TestAppendTypeIDs_ReadsWhatTheTypeGraphReads(t *testing.T) { for _, kind := range kinds { t.Run(kind.Value, func(t *testing.T) { t.Parallel() - td, ok := ir.NewTypeDef(ir.TypeKind(kind.Value)) + typeDef, ok := ir.NewTypeDef(ir.TypeKind(kind.Value)) require.True(t, ok, "no concrete type for kind %q", kind.Value) - irtest.Fill(t, td) - edges := slices.Collect(ir.TypeEdges(td)) + irtest.Fill(t, typeDef) + edges := slices.Collect(ir.TypeEdges(typeDef)) require.NotEmpty(t, edges, "a filled %s holds no edge, so this compares nothing", kind.Value) - read := slices.DeleteFunc(pass.AppendTypeIDs(nil, td), func(id ir.TypeID) bool { - return id == td.Common().ID + read := slices.DeleteFunc(pass.AppendTypeIDs(nil, typeDef), func(id ir.TypeID) bool { + return id == typeDef.Common().ID }) assert.Empty(t, cmp.Diff(edges, read), "mismatch (-edges +read)") }) diff --git a/pass/validate_indices.go b/pass/validate_indices.go index cb12550b0..49d9e1c6b 100644 --- a/pass/validate_indices.go +++ b/pass/validate_indices.go @@ -20,8 +20,8 @@ import ( func checkResponseIndices(doc *ir.Document) []ir.Diagnostic { var diags []ir.Diagnostic ir.ForEachOperation(doc, func(operation ir.Operation) { - for i, b := range operation.Bindings.HTTP { - diags = appendSuccessStatusDiags(diags, b.SuccessStatus, len(operation.Responses), operation.ID, i) + for i, binding := range operation.Bindings.HTTP { + diags = appendSuccessStatusDiags(diags, binding.SuccessStatus, len(operation.Responses), operation.ID, i) } }) return diags diff --git a/pass/validate_indices_test.go b/pass/validate_indices_test.go index 1d5bfdaba..6b7585ae0 100644 --- a/pass/validate_indices_test.go +++ b/pass/validate_indices_test.go @@ -53,8 +53,8 @@ func TestValidate_ResponseIndexOutOfRange(t *testing.T) { } } -// TestValidate_ResponseIndexInRangeIsClean is the silent half: a key addressing a -// declared response reports nothing. +// TestValidate_ResponseIndexInRangeIsClean is the report-nothing half: a key +// addressing a declared response reports nothing. func TestValidate_ResponseIndexInRangeIsClean(t *testing.T) { t.Parallel() assert.Empty(t, validated(t, operationWithSuccessStatus(map[int]int{0: 200}))) diff --git a/pass/validate_knots.go b/pass/validate_knots.go index 818c08be0..6d76aa8d9 100644 --- a/pass/validate_knots.go +++ b/pass/validate_knots.go @@ -67,25 +67,6 @@ func (x typeIndex) isUnion(ref *ir.TypeRef) bool { return ok && x.composed[i] } -// leadsToUnion reports whether td is a union, or an alias scalar whose bases -// reach one within maxAliasHops. -func leadsToUnion(doc *ir.Document, td ir.TypeDef) bool { - for range maxAliasHops { - switch t := td.(type) { - case *ir.Union: - return true - case *ir.Scalar: - if t == nil || t.Base == nil { - return false - } - td = doc.Types[t.Base.Target] - default: - return false - } - } - return false -} - // edgeSink takes the edges eachEdge reads: it counts them, then fills a list // of their targets, or remembers the first into a set of vertices, so no // function value is made for a type. @@ -97,15 +78,15 @@ type edgeSink struct { found bool } -func (s *edgeSink) add(edgeValue edge) { +func (s *edgeSink) add(edge edge) { if s.into != nil { - if !s.found && s.into[edgeValue.target] { - s.first, s.found = edgeValue, true + if !s.found && s.into[edge.target] { + s.first, s.found = edge, true } return } if s.targets != nil { - s.targets[s.count] = edgeValue.target + s.targets[s.count] = edge.target } s.count++ } @@ -118,14 +99,14 @@ func (s *edgeSink) emit(ix typeIndex, ref *ir.TypeRef, kind edgeKind, index int) } } -// eachEdge adds to sink the edges of td that set picks, in the order a finding -// names the first of: a model's base, its mixins, then its required properties. -// A scalar needs its base, a list its element once it must hold one, a map its -// value likewise, a tuple each position it must fill, and a union each -// variant, none where one is nullable or names no live type, since that is a -// value needing no other. docs/ir/models.md lists what is not read. -func eachEdge(td ir.TypeDef, ix typeIndex, set edgeSet, sink *edgeSink) { - switch t := td.(type) { +// eachEdge adds to sink the edges of typeDef that set picks, in the order a +// finding names the first of: a model's base, its mixins, then its required +// properties. A scalar needs its base, a list its element once it must hold +// one, a map its value likewise, a tuple each position it must fill, and a +// union each variant, none where one is nullable or names no live type, since +// that is a value needing no other. docs/ir/models.md lists what is not read. +func eachEdge(typeDef ir.TypeDef, ix typeIndex, set edgeSet, sink *edgeSink) { + switch t := typeDef.(type) { case *ir.Model: sink.model(ix, t, set) case *ir.Scalar: @@ -220,8 +201,8 @@ func atLeastOne(constraints *ir.Constraints, pick func(*ir.Constraints) *int64) if constraints == nil { return false } - n := pick(constraints) - return n != nil && *n >= 1 + picked := pick(constraints) + return picked != nil && *picked >= 1 } // everyVariantNeeded reports whether each variant of union is a live type that @@ -243,14 +224,14 @@ func everyVariantNeeded(union *ir.Union, ix typeIndex) bool { // no other unfounded vertex needs are then dropped, one at a time, so what // remains lies on a cycle of needs, or between two, and not merely before one. // Each edge is read a constant number of times and the lists are made once. -func typesWithNoFiniteValue(n int, starts, targets []int32, every []bool) []bool { - reverse, from := reversed(n, starts, targets) - founded := make([]bool, n) - left := make([]int32, n) - work := make([]int32, 0, n) - for i := range n { - left[i] = starts[i+1] - starts[i] - if left[i] == 0 { +func typesWithNoFiniteValue(typeCount int, starts, targets []int32, every []bool) []bool { + reverse, from := reversed(typeCount, starts, targets) + founded := make([]bool, typeCount) + unfoundedNeeds := make([]int32, typeCount) + work := make([]int32, 0, typeCount) + for i := range typeCount { + unfoundedNeeds[i] = starts[i+1] - starts[i] + if unfoundedNeeds[i] == 0 { founded[i] = true work = append(work, int32(i)) } @@ -258,33 +239,33 @@ func typesWithNoFiniteValue(n int, starts, targets []int32, every []bool) []bool for len(work) > 0 { t := work[len(work)-1] work = work[:len(work)-1] - for _, u := range from[reverse[t]:reverse[t+1]] { - if founded[u] { + for _, source := range from[reverse[t]:reverse[t+1]] { + if founded[source] { continue } - if left[u]--; !every[u] || left[u] == 0 { - founded[u] = true - work = append(work, u) + if unfoundedNeeds[source]--; !every[source] || unfoundedNeeds[source] == 0 { + founded[source] = true + work = append(work, source) } } } - return peel(n, starts, targets, founded, work[:0]) + return peel(typeCount, starts, targets, founded, work[:0]) } // reversed returns the edges of the graph turned around: the users of vertex t // are from[reverse[t]:reverse[t+1]]. -func reversed(n int, starts, targets []int32) (reverse, from []int32) { - reverse = make([]int32, n+1) +func reversed(typeCount int, starts, targets []int32) (reverse, from []int32) { + reverse = make([]int32, typeCount+1) for _, t := range targets { reverse[t+1]++ } - for i := range n { + for i := range typeCount { reverse[i+1] += reverse[i] } from = make([]int32, len(targets)) - next := make([]int32, n) + next := make([]int32, typeCount) copy(next, reverse) - for i := range n { + for i := range typeCount { for _, t := range targets[starts[i]:starts[i+1]] { from[next[t]] = int32(i) next[t]++ @@ -295,9 +276,9 @@ func reversed(n int, starts, targets []int32) (reverse, from []int32) { // peel returns the unfounded vertices that remain once each one no remaining // unfounded vertex needs is dropped. work is scratch for it, empty. -func peel(n int, starts, targets []int32, founded []bool, work []int32) []bool { - needed := make([]int32, n) - for i := range n { +func peel(typeCount int, starts, targets []int32, founded []bool, work []int32) []bool { + needed := make([]int32, typeCount) + for i := range typeCount { if founded[i] { continue } @@ -307,8 +288,8 @@ func peel(n int, starts, targets []int32, founded []bool, work []int32) []bool { } } } - remains := make([]bool, n) - for i := range n { + remains := make([]bool, typeCount) + for i := range typeCount { remains[i] = !founded[i] if remains[i] && needed[i] == 0 { work = append(work, int32(i)) @@ -360,19 +341,19 @@ func edgesOf(composition bool, cyclic []bool, i int) edgeSet { // buildGraph reads the edges of each of ix's types that edgesOf picks. func buildGraph(doc *ir.Document, ix typeIndex, composition bool, cyclic []bool) graph { - n := len(ix.ids) - graphValue := graph{starts: make([]int32, n+1)} + idCount := len(ix.ids) + graph := graph{starts: make([]int32, idCount+1)} var count edgeSink for i, id := range ix.ids { eachEdge(doc.Types[id], ix, edgesOf(composition, cyclic, i), &count) - graphValue.starts[i+1] = count.count + graph.starts[i+1] = count.count } - graphValue.targets = make([]int32, count.count) - fill := edgeSink{targets: graphValue.targets} + graph.targets = make([]int32, count.count) + fill := edgeSink{targets: graph.targets} for i, id := range ix.ids { eachEdge(doc.Types[id], ix, edgesOf(composition, cyclic, i), &fill) } - return graphValue + return graph } // checkCompositionCyclesAndInfiniteTypes reports each type that lies on a cycle @@ -382,7 +363,7 @@ func buildGraph(doc *ir.Document, ix typeIndex, composition bool, cyclic []bool) // and a target reads it to its fixpoint, so no target is refused // (docs/ir/models.md). Each is told at every type of the type cycle, naming the // entry that leads on, the composition ones first. -func checkCompositionCyclesAndInfiniteTypes(doc *ir.Document, ids []ir.TypeID) []ir.Diagnostic { +func checkCompositionCyclesAndInfiniteTypes(doc *ir.Document, chains *aliasChains, ids []ir.TypeID) []ir.Diagnostic { if len(ids) == 0 { return nil } @@ -390,7 +371,7 @@ func checkCompositionCyclesAndInfiniteTypes(doc *ir.Document, ids []ir.TypeID) [ every := make([]bool, len(ids)) for i, id := range ids { _, union := doc.Types[id].(*ir.Union) - ix.composed[i] = leadsToUnion(doc, doc.Types[id]) + ix.composed[i] = chains.leadsToUnion(id) every[i] = !union } comp := buildGraph(doc, ix, true, nil) @@ -413,9 +394,9 @@ func appendTypeCycleFindings(diags []ir.Diagnostic, doc *ir.Document, ix typeInd if !infiniteGroupOf[i] { continue } - td := doc.Types[id] + typeDef := doc.Types[id] sink := edgeSink{into: infiniteGroupOf} - eachEdge(td, ix, edgesOf(composition, cyclic, i), &sink) + eachEdge(typeDef, ix, edgesOf(composition, cyclic, i), &sink) var message string if composition { message = "composition never ends: " + entryWords(sink.first) + " " + string(ix.ids[sink.first.target]) + @@ -424,7 +405,7 @@ func appendTypeCycleFindings(diags []ir.Diagnostic, doc *ir.Document, ix typeInd message = "no finite value: each needs its " + entryWords(sink.first) + ", " + string(ix.ids[sink.first.target]) + ", which has none either" } - diags = append(diags, diagAt(code, message, string(id), td.Common().Provenance)) + diags = append(diags, diagAt(code, message, string(id), typeDef.Common().Provenance)) } return diags } diff --git a/pass/validate_knots_test.go b/pass/validate_knots_test.go index 9d200f8a5..019fee0e1 100644 --- a/pass/validate_knots_test.go +++ b/pass/validate_knots_test.go @@ -36,8 +36,8 @@ func needs(id string, typ ir.TypeRef) ir.Property { // noFiniteValueDoc is valueDoc holding defs. func noFiniteValueDoc(defs ...ir.TypeDef) *ir.Document { doc := valueDoc() - for _, td := range defs { - doc.Types[td.Common().ID] = td + for _, typeDef := range defs { + doc.Types[typeDef.Common().ID] = typeDef } return doc } diff --git a/pass/validate_knots_twins_test.go b/pass/validate_knots_twins_test.go index b61d726db..ef97cdd22 100644 --- a/pass/validate_knots_twins_test.go +++ b/pass/validate_knots_twins_test.go @@ -56,8 +56,8 @@ func TestValidate_AModelComposingTheUnionThatListsItHasAFiniteValue(t *testing.T } listing := func(id string, variants ...string) *ir.Union { union := &ir.Union{ID: ir.TypeID(id), Provenance: provAt(id)} - for _, v := range variants { - union.Variants = append(union.Variants, ir.Variant{Type: ref(v)}) + for _, variant := range variants { + union.Variants = append(union.Variants, ir.Variant{Type: ref(variant)}) } return union } diff --git a/pass/validate_member_counts_test.go b/pass/validate_member_counts_test.go new file mode 100644 index 000000000..761ed1db7 --- /dev/null +++ b/pass/validate_member_counts_test.go @@ -0,0 +1,229 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass_test + +import ( + "encoding/json/jsontext" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +// countedModel is a model of the ID id, composing base where it is set, of +// the member counts minimum and maximum, nil leaving one unset. +func countedModel(id ir.TypeID, base ir.TypeID, minimum, maximum *int64) *ir.Model { + model := &ir.Model{ID: id, Provenance: provAt(string(id))} + if base != "" { + model.Base = &ir.TypeRef{Target: base} + } + if minimum != nil || maximum != nil { + model.Constraints = &ir.Constraints{MinProperties: minimum, MaxProperties: maximum} + } + return model +} + +// TestValidate_AModelsCountsAreIntersectedAcrossItsComposition holds +// pass.Validate to the member counts an instance of a model is held to, those +// of every model it composes along Base and Mixins (ir.PropertyCountBounds): a +// model whose intersection crosses admits no object, told by the first model +// whose intersection does, so one composing it, directly or through an alias, +// draws nothing, one composing what names no model tells its own, and a default +// is judged against the intersection, the second default of one model read off +// the intersection already read. +func TestValidate_AModelsCountsAreIntersectedAcrossItsComposition(t *testing.T) { + t.Parallel() + one, two := new(int64(1)), new(int64(2)) + doc := modelOf( + property("property/a/own", ir.TypeRef{Target: "type/obj"}, defaulted(&ir.Value{Kind: ir.ValueObject})), + property("property/a/via", ir.TypeRef{Target: "type/sub"}, defaulted(&ir.Value{Kind: ir.ValueObject})), + property("property/a/again", ir.TypeRef{Target: "type/sub"}, defaulted(&ir.Value{Kind: ir.ValueObject})), + ) + both := countedModel("type/both", "type/obj", nil, nil) + both.Mixins = []ir.TypeRef{{Target: "type/cap"}} + for _, typeDef := range []ir.TypeDef{ + countedModel("type/obj", "", two, nil), + countedModel("type/cap", "", nil, one), + countedModel("type/sub", "type/obj", nil, nil), + both, + countedModel("type/deeper", "type/both", nil, nil), + &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/both"}, Provenance: provAt("type/alias")}, + countedModel("type/aliased", "type/alias", nil, nil), + countedModel("type/over-a-scalar", ir.PrimitiveTypeID(ir.PrimitiveString), two, one), + } { + doc.Types[typeDef.Common().ID] = typeDef + } + + assert.ElementsMatch(t, []finding{ + {"type/both", "bounds admit no object: none has at least 2 members and at most 1"}, + {"type/over-a-scalar", "bounds admit no object: none has at least 2 members and at most 1"}, + }, found(t, doc, boundsCode), "a part naming no model leaves the model to tell its own") + assert.Equal(t, []finding{ + {"property/a/own", "default lies outside the bounds declared for it"}, + {"property/a/via", "default lies outside the bounds declared for it"}, + {"property/a/again", "default lies outside the bounds declared for it"}, + }, found(t, doc, defaultCode)) +} + +// countedChains are the compositions TestValidate_MemberCountsCostLinearWork +// validates at a size: n models, each writing a minimum of its place in the +// chain, composed in a chain of bases and in a chain of mixins each named +// through an alias, the last model's maximum of 0 crossing the minimum its +// composition brings. +func countedChains() map[string]func(n int) *ir.Document { + model := func(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("type/m%05d", i)) } + build := func(count int, compose func(composer *ir.Model, i int, types ir.TypeRegistry)) *ir.Document { + types := ir.TypeRegistry{} + for i := range count { + composer := countedModel(model(i), "", new(int64(i)), nil) + if i == count-1 { + composer.Constraints.MaxProperties = new(int64(0)) + } + if i > 0 { + compose(composer, i, types) + } + types[composer.ID] = composer + } + return &ir.Document{IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: types} + } + return map[string]func(n int) *ir.Document{ + "a chain of bases": func(count int) *ir.Document { + return build(count, func(composer *ir.Model, i int, _ ir.TypeRegistry) { + composer.Base = &ir.TypeRef{Target: model(i - 1)} + }) + }, + "a chain of mixins through aliases": func(count int) *ir.Document { + return build(count, func(composer *ir.Model, i int, types ir.TypeRegistry) { + alias := ir.TypeID(fmt.Sprintf("type/a%05d", i)) + types[alias] = &ir.Scalar{ID: alias, Base: &ir.TypeRef{Target: model(i - 1)}, Provenance: provAt(string(alias))} + composer.Mixins = []ir.TypeRef{{Target: alias}} + }) + }, + } +} + +// TestValidate_MemberCountsCostLinearWork holds validating each countedChains +// composition to one finding, at its last model, whose crossed counts reach +// back to the chain's start, and its allocations and bytes to linear growth +// around 125, 250 and 500 models, as +// TestValidate_DiscriminatorRoutesCostLinearWork does: reading each model's +// composition of its own grows with the square of the chain. It does not run +// in parallel, since both counts are process-wide. +func TestValidate_MemberCountsCostLinearWork(t *testing.T) { + for name, build := range countedChains() { + var allocs, bytes [3]float64 + for k, n := range []int{125, 250, 500} { + allocs[k], bytes[k] = costAround(t, n, build, func(t *testing.T, size int, diags []ir.Diagnostic) { + counts := withCode(diags, boundsCode) + require.Len(t, counts, 1, "%s of %d: one finding", name, size) + require.Equal(t, fmt.Sprintf("bounds admit no object: none has at least %d members and at most 0", size-1), + counts[0].Message, "%s of %d: the last model's counts reach the chain's start", name, size) + }) + } + assert.LessOrEqual(t, allocs[2]-allocs[1], 2.5*(allocs[1]-allocs[0]), + "%s: allocations around 125, 250, 500: %v", name, allocs) + assert.LessOrEqual(t, bytes[2]-bytes[1], 2.5*(bytes[1]-bytes[0]), + "%s: bytes around 125, 250, 500: %v", name, bytes) + } +} + +// cycleModel is a model at pointer in source, composing base where it is set, +// of the member counts minimum and maximum, nil leaving one unset. +func cycleModel(id ir.TypeID, source int, pointer jsontext.Pointer, base ir.TypeID, minimum, maximum *int64) *ir.Model { + model := countedModel(id, base, minimum, maximum) + model.Provenance = ir.Provenance{Source: source, Pointer: pointer} + return model +} + +// crossedCycles is what pass.Validate reports of doc as +// pass/bounds-admit-no-value, by the node each finding names, each held to be +// a warning carrying that node's provenance. +func crossedCycles(t *testing.T, doc *ir.Document) map[string]string { + t.Helper() + got := map[string]string{} + for _, diagnostic := range withCode(validated(t, doc), boundsCode) { + assert.Equal(t, ir.SeverityWarning, diagnostic.Severity, diagnostic.Message) + want := doc.Types[ir.TypeID(diagnostic.Provenance.Node)].Common().Provenance + want.Node = diagnostic.Provenance.Node + assert.Equal(t, want, diagnostic.Provenance, "a finding carries its model's provenance: %s", diagnostic.Message) + got[diagnostic.Provenance.Node] = diagnostic.Message + } + return got +} + +// crossedCycleAt is the finding on a cycle whose intersected member counts +// are at least minimum and at most maximum. +func crossedCycleAt(minimum, maximum int) string { + return fmt.Sprintf("composes itself, alone or through other models, and the intersected member counts of that "+ + "cycle admit no object: none has at least %d members and at most %d", minimum, maximum) +} + +// TestValidate_ACrossedCompositionCycleIsToldOnceAtItsLeastMember pins the +// one report of a cycle of models composing one another whose intersected +// member counts admit no object: at the member whose provenance is least, +// whatever its ID, for a cycle of two, a model composing itself and one doing +// so through an alias; none for a cycle admitting an object, one whose +// minimum equals its maximum among them, one writing no count, or a model +// composing a crossed cycle; and a cycle composing a crossed model outside it +// is left to that model, which tells its own. +func TestValidate_ACrossedCompositionCycleIsToldOnceAtItsLeastMember(t *testing.T) { + t.Parallel() + one, two, three := new(int64(1)), new(int64(2)), new(int64(3)) + doc := &ir.Document{IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: ir.TypeRegistry{}} + composesCrossed := cycleModel("type/x/p", 0, "/components/schemas/P", "type/x/q", nil, nil) + composesCrossed.Mixins = []ir.TypeRef{{Target: "type/x/crossed"}} + for _, typeDef := range []ir.TypeDef{ + cycleModel("type/x/a", 0, "/components/schemas/Z", "type/x/b", three, nil), + cycleModel("type/x/b", 0, "/components/schemas/Y", "type/x/a", nil, one), + cycleModel("type/x/self", 0, "/components/schemas/Self", "type/x/self", three, one), + cycleModel("type/x/via", 0, "/components/schemas/Via", "type/x/alias", three, one), + &ir.Scalar{ID: "type/x/alias", Base: &ir.TypeRef{Target: "type/x/via"}, Provenance: ir.Provenance{Pointer: "/components/schemas/Alias"}}, + cycleModel("type/x/c", 0, "/components/schemas/C", "type/x/d", one, three), + cycleModel("type/x/d", 0, "/components/schemas/D", "type/x/c", nil, nil), + cycleModel("type/x/g", 0, "/components/schemas/G", "type/x/h", two, nil), + cycleModel("type/x/h", 0, "/components/schemas/H", "type/x/g", nil, two), + cycleModel("type/x/e", 0, "/components/schemas/E", "type/x/f", nil, nil), + cycleModel("type/x/f", 0, "/components/schemas/F", "type/x/e", nil, nil), + cycleModel("type/x/outside", 0, "/components/schemas/Outside", "type/x/self", nil, nil), + composesCrossed, + cycleModel("type/x/q", 0, "/components/schemas/Q", "type/x/p", nil, nil), + cycleModel("type/x/crossed", 0, "/components/schemas/Crossed", "", three, one), + } { + doc.Types[typeDef.Common().ID] = typeDef + } + + assert.Equal(t, map[string]string{ + "type/x/b": crossedCycleAt(3, 1), + "type/x/self": crossedCycleAt(3, 1), + "type/x/via": crossedCycleAt(3, 1), + "type/x/crossed": "bounds admit no object: none has at least 3 members and at most 1", + }, crossedCycles(t, doc)) +} + +// TestValidate_ACrossedCycleIsToldAtOneMemberInEitherDirection pins the site +// and the message of a crossed cycle of three models to the cycle and not to +// how it is written: composed one way round or the other, it is told at the +// model of least Source, though its pointer is the greatest, and between two +// of one provenance, at the least ID. +func TestValidate_ACrossedCycleIsToldAtOneMemberInEitherDirection(t *testing.T) { + t.Parallel() + two, four := new(int64(2)), new(int64(4)) + for _, tc := range []struct { + name string + bases map[ir.TypeID]ir.TypeID + }{ + {"k, l, m", map[ir.TypeID]ir.TypeID{"type/x/k": "type/x/l", "type/x/l": "type/x/m", "type/x/m": "type/x/k"}}, + {"k, m, l", map[ir.TypeID]ir.TypeID{"type/x/k": "type/x/m", "type/x/m": "type/x/l", "type/x/l": "type/x/k"}}, + } { + doc := &ir.Document{IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: ir.TypeRegistry{ + "type/x/k": cycleModel("type/x/k", 1, "/components/schemas/A", tc.bases["type/x/k"], four, nil), + "type/x/l": cycleModel("type/x/l", 0, "/components/schemas/Z", tc.bases["type/x/l"], nil, two), + "type/x/m": cycleModel("type/x/m", 0, "/components/schemas/Z", tc.bases["type/x/m"], nil, nil), + }} + assert.Equal(t, map[string]string{"type/x/l": crossedCycleAt(4, 2)}, crossedCycles(t, doc), "%s", tc.name) + } +} diff --git a/pass/validate_memberbounds_test.go b/pass/validate_memberbounds_test.go new file mode 100644 index 000000000..8b3592e93 --- /dev/null +++ b/pass/validate_memberbounds_test.go @@ -0,0 +1,177 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package pass_test + +import ( + "reflect" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/ir" +) + +const memberBoundsCode = "pass/enum-member-outside-bounds" + +// boundedEnum is valueDoc holding the enum type/x of valueType listing values, +// held to constraints. +func boundedEnum(valueType ir.PrimitiveKind, constraints *ir.Constraints, values ...ir.Value) *ir.Document { + doc := valueDoc() + enum := &ir.Enum{ID: "type/x", ValueType: valueType, Closed: true, Constraints: constraints, Provenance: provAt("type/x")} + for i, value := range values { + enum.Members = append(enum.Members, ir.EnumMember{ID: ir.EnumMemberID("enum-member/x/" + strconv.Itoa(i)), Value: value}) + } + doc.Types["type/x"] = enum + return doc +} + +// TestValidate_AMemberItsEnumsBoundsRefuseIsNamed holds +// pass/enum-member-outside-bounds to one warning per enum, at the enum, naming +// each member its own bounds refuse with each bound refusing it, as the value +// admission reader judges a member: a member a pattern alone may refuse, which +// the reader answers unknown for as it evaluates no pattern, is not named, and +// an enum every member of which its bounds refuse, or none, draws nothing, the +// first being its compiler's to report at the position. +func TestValidate_AMemberItsEnumsBoundsRefuseIsNamed(t *testing.T) { + t.Parallel() + maxThree := &ir.Constraints{MaxLength: new(int64(3))} + bytesOf := func(text string) ir.Value { return ir.Value{Kind: ir.ValueBytes, Bytes: []byte(text)} } + for _, tc := range []struct { + name string + doc *ir.Document + // message is the one finding's, "" for none. + message string + }{ + {"one member past a length", boundedEnum(ir.PrimitiveString, maxThree, *text("a"), *text("abcd")), + `"abcd" by its maxLength`}, + {"every member past a length", boundedEnum(ir.PrimitiveString, maxThree, *text("abcd"), *text("abcde")), ""}, + {"no member past a length", boundedEnum(ir.PrimitiveString, maxThree, *text("a"), *text("abc")), ""}, + {"no bounds", boundedEnum(ir.PrimitiveString, nil, *text("a"), *text("abcd")), ""}, + {"a member only a pattern may refuse", boundedEnum(ir.PrimitiveString, &ir.Constraints{Pattern: "^(?!b)"}, *text("a"), *text("b")), ""}, + {"a length beside a pattern", boundedEnum(ir.PrimitiveString, &ir.Constraints{Pattern: "^(?!b)", MaxLength: new(int64(3))}, + *text("a"), *text("abcd")), `"abcd" by its maxLength`}, + {"a member under a minimum length", boundedEnum(ir.PrimitiveString, &ir.Constraints{MinLength: new(int64(2))}, + *text("a"), *text("ab"), *text("b")), `"a" by its minLength; "b" by its minLength`}, + {"numbers past each numeric bound", boundedEnum(ir.PrimitiveInteger, withMultiple(numeric("1", "0", "100", "101"), "2"), + *number("2"), *number("200"), *number("7"), *number("-2")), + "200 by its max and exclusiveMax; 7 by its multipleOf; -2 by its min and exclusiveMin"}, + {"bytes past a length", boundedEnum(ir.PrimitiveBytes, maxThree, bytesOf("ab"), bytesOf("abcd")), + `bytes:YWJjZA by its maxLength`}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got := found(t, tc.doc, memberBoundsCode) + if tc.message == "" { + assert.Empty(t, got) + return + } + assert.Equal(t, []finding{{"type/x", "enum lists members its own bounds refuse, so no instance is one of them: " + tc.message}}, got) + }) + } +} + +// TestValidate_AnEnumEveryMemberOfWhichItsBoundsRefuseDrawsNoMemberFinding +// holds the one-finding rule beside the bounds check: an enum whose bounds +// cross draws pass/bounds-admit-no-value alone, open or closed, the bounds +// being the cause, whether they refuse every member or, a symbol member being +// text no length is read of, some of them. +func TestValidate_AnEnumEveryMemberOfWhichItsBoundsRefuseDrawsNoMemberFinding(t *testing.T) { + t.Parallel() + symbol := ir.Value{Kind: ir.ValueSymbol, String: "a"} + for _, members := range [][]ir.Value{{*text("a"), *text("bb")}, {*text("a"), symbol}} { + for _, closed := range []bool{false, true} { + doc := boundedEnum(ir.PrimitiveString, lengths(3, 1), members...) + enum, ok := doc.Types["type/x"].(*ir.Enum) + require.True(t, ok) + enum.Closed = closed + assert.Empty(t, found(t, doc, memberBoundsCode), "closed: %t, members %v", closed, members) + assert.Len(t, found(t, doc, boundsCode), 1, "closed: %t, members %v", closed, members) + } + } + unbounded := boundedEnum(ir.PrimitiveString, &ir.Constraints{MaxLength: new(int64(1))}, *text("bb"), symbol) + assert.Equal(t, []finding{{"type/x", `enum lists members its own bounds refuse, so no instance is one of them: "bb" by its maxLength`}}, + found(t, unbounded, memberBoundsCode), "uncrossed, the symbol is admitted and the string named") +} + +// TestMemberBounds_NameEveryBoundIrRefusesAMemberBy holds the bounds the +// finding names to what ir refuses a member by, read off ir.Constraints +// rather than listed: each count or number field, set alone to a limit that +// leaves one candidate member admitted and refuses another +// (ir.ConstraintsAdmit), draws the finding naming that field by its JSON +// member. A field ir judges no member by draws none, and at least the bounds +// ir declares today are reached. +func TestMemberBounds_NameEveryBoundIrRefusesAMemberBy(t *testing.T) { + t.Parallel() + numbers := []ir.Value{*number("1"), *number("5"), *number("20")} + texts := []ir.Value{*text("a"), *text("abcde"), *text("abcdefghijklmnopqrst")} + named := map[string]bool{} + constraintsType := reflect.TypeFor[ir.Constraints]() + for field := range constraintsType.Fields() { + name, _, _ := strings.Cut(field.Tag.Get("json"), ",") + for _, limit := range []string{"2", "10"} { + alone, set := settingAlone(t, field, limit) + if !set { + continue + } + for _, candidates := range [][]ir.Value{numbers, texts} { + refused, admitted := splitByBounds(alone, candidates) + if refused == nil || admitted == nil { + continue + } + valueType := ir.PrimitiveNumber + if candidates[0].Kind == ir.ValueString { + valueType = ir.PrimitiveString + } + got := found(t, boundedEnum(valueType, alone, append([]ir.Value{*admitted}, refused...)...), memberBoundsCode) + if assert.Len(t, got, 1, "%s %s", name, limit) { + assert.Contains(t, got[0].message, " by its "+name, "%s %s names the field", name, limit) + } + named[name] = true + } + } + } + for _, name := range []string{"min", "exclusiveMin", "max", "exclusiveMax", "multipleOf", "minLength", "maxLength"} { + assert.True(t, named[name], "%s refuses a candidate member", name) + } +} + +// settingAlone returns the Constraints setting field, a number or a count, to +// limit and nothing else, and false for a field of any other type. +func settingAlone(t *testing.T, field reflect.StructField, limit string) (*ir.Constraints, bool) { + t.Helper() + alone := &ir.Constraints{} + target := reflect.ValueOf(alone).Elem().FieldByIndex(field.Index) + switch field.Type { + case reflect.TypeFor[*ir.BigVal](): + target.Set(reflect.ValueOf(new(ir.BigVal(limit)))) + case reflect.TypeFor[*int64](): + count, err := strconv.ParseInt(limit, 10, 64) + require.NoError(t, err) + target.Set(reflect.ValueOf(new(count))) + default: + return nil, false + } + return alone, true +} + +// splitByBounds returns the candidates bounds refuses, and one it admits, nil +// where there is none of either. +func splitByBounds(bounds *ir.Constraints, candidates []ir.Value) ([]ir.Value, *ir.Value) { + var refused []ir.Value + var admitted *ir.Value + for i := range candidates { + // A bound ir does not read answers unknown, and lands in neither. + admission := ir.ConstraintsAdmit(bounds, candidates[i]) + if admission == ir.AdmitsNo { + refused = append(refused, candidates[i]) + } + if admission == ir.AdmitsYes { + admitted = &candidates[i] + } + } + return refused, admitted +} diff --git a/pass/validate_messages.go b/pass/validate_messages.go index 378fdcc7d..324639784 100644 --- a/pass/validate_messages.go +++ b/pass/validate_messages.go @@ -40,15 +40,15 @@ func checkMessageBindings(doc *ir.Document) []ir.Diagnostic { // there is no declared message set to hold it to (docs/ir/messaging.md). Each // channel's messages are read through carried. func checkBoundMessages(doc *ir.Document, operation ir.Operation, carried *scratchstate.Map[ir.MessageID, bool]) []ir.Diagnostic { - b := operation.Bindings.Message - if b == nil { + message := operation.Bindings.Message + if message == nil { return nil } - diags := appendUncarriedMessageDiags(nil, doc, b.Channel, b.Messages, messagesAt{operation.ID, "messages"}, carried) - if b.Reply == nil || b.Reply.Channel == nil { + diags := appendUncarriedMessageDiags(nil, doc, message.Channel, message.Messages, messagesAt{operation.ID, "messages"}, carried) + if message.Reply == nil || message.Reply.Channel == nil { return diags } - return appendUncarriedMessageDiags(diags, doc, *b.Reply.Channel, b.Reply.Messages, + return appendUncarriedMessageDiags(diags, doc, *message.Reply.Channel, message.Reply.Messages, messagesAt{operation.ID, "reply/messages"}, carried) } diff --git a/pass/validate_messages_test.go b/pass/validate_messages_test.go index ead1bc5c9..5a356125b 100644 --- a/pass/validate_messages_test.go +++ b/pass/validate_messages_test.go @@ -29,8 +29,8 @@ func messageBindingDoc(channel ir.ChannelID, carried, used []ir.MessageID) *ir.D // TestValidate_MessageNotCarriedByChannel is the containment claim // docs/ir/messaging.md makes for MessageBinding.Messages: an operation may use // only the messages its channel carries. Both ids resolve, so the reference -// walk is silent and a publisher for a message the channel contract forbids -// validated clean. +// walk reports nothing and a publisher for a message the channel contract +// forbids validated clean. func TestValidate_MessageNotCarriedByChannel(t *testing.T) { t.Parallel() diags := validated(t, messageBindingDoc("channel/a", @@ -52,10 +52,10 @@ func TestValidate_MessageNotCarriedIsPlacedAtItsPosition(t *testing.T) { pointers(withCode(validated(t, doc), "pass/message-not-in-channel"))) } -// TestValidate_MessagesCarriedByChannelAreClean is the silent half. A binding -// using a subset of the channel's messages, and one naming none at all, both -// report nothing — a check that cannot stay silent is no better than one that -// cannot fire. +// TestValidate_MessagesCarriedByChannelAreClean is the report-nothing half. A +// binding using a subset of the channel's messages, and one naming none at all, +// both report nothing — a check that cannot report nothing is no better than +// one that cannot fire. func TestValidate_MessagesCarriedByChannelAreClean(t *testing.T) { t.Parallel() carried := []ir.MessageID{"message/a", "message/b"} @@ -114,10 +114,10 @@ func TestValidate_ReplyMessageNotCarriedByChannel(t *testing.T) { "the reply's own position, not the request set's") } -// TestValidate_ReplyMessagesCarriedAreClean is the silent half, including the -// reply whose address is dynamic: docs/ir/messaging.md leaves such a reply's -// channel nil, so there is no declared message set to hold it to and a check -// that reported there would refuse legal IR. +// TestValidate_ReplyMessagesCarriedAreClean is the report-nothing half, +// including the reply whose address is dynamic: docs/ir/messaging.md leaves +// such a reply's channel nil, so there is no declared message set to hold it to +// and a check that reported there would refuse legal IR. func TestValidate_ReplyMessagesCarriedAreClean(t *testing.T) { t.Parallel() carried := []ir.MessageID{"message/a", "message/b"} diff --git a/pass/validate_niltypes_test.go b/pass/validate_niltypes_test.go index 084c6a531..9e3723e5e 100644 --- a/pass/validate_niltypes_test.go +++ b/pass/validate_niltypes_test.go @@ -33,11 +33,11 @@ func TestValidate_NilTypeDefIsReportedNotPanicked(t *testing.T) { "any": (*ir.Any)(nil), "untyped": nil, } - for name, td := range kinds { + for name, typeDef := range kinds { t.Run(name, func(t *testing.T) { t.Parallel() doc := validDoc() - doc.Types["type/nil"] = td + doc.Types["type/nil"] = typeDef var diags []ir.Diagnostic require.NotPanics(t, func() { diags = validated(t, doc) }) diff --git a/pass/validate_params.go b/pass/validate_params.go index 0bced1c5e..bebb2b915 100644 --- a/pass/validate_params.go +++ b/pass/validate_params.go @@ -82,10 +82,10 @@ type paramLocation struct { func checkHTTPParamBinding(operation ir.Operation, idx int, names map[ir.ParameterID]string, refs *ir.IDReferences, read *bindingMaps, ) []ir.Diagnostic { - b := operation.Bindings.HTTP[idx] + binding := operation.Bindings.HTTP[idx] var diags []ir.Diagnostic bound, perLocation := read.bound.Emptied(), read.perLocation.Emptied() - for _, pb := range b.ParamBindings { + for _, pb := range binding.ParamBindings { name, own := names[pb.Param] if !own { if reportedHere(pb.Param, refs) { diff --git a/pass/validate_payloads.go b/pass/validate_payloads.go index 0f9c05a15..1a0c58bc3 100644 --- a/pass/validate_payloads.go +++ b/pass/validate_payloads.go @@ -24,11 +24,11 @@ import ( // The code carries the ir/ namespace because it names the defect, not the // finder (see the package doc), so a second checker growing this check adopts // it. Only this pass reports it today. facts indexes doc. -func checkEncodingKeys(doc *ir.Document, facts *irfacts.DocumentFacts) []ir.Diagnostic { +func checkEncodingKeys(doc *ir.Document, facts *irfacts.DocumentFacts, chains *aliasChains) []ir.Diagnostic { var diags []ir.Diagnostic var keys []ir.PropertyID // every content's keys are sorted in this one list forEachPayload(doc, func(site payloadSite) { - diags = appendEncodingKeyDiags(diags, doc.Types, facts, site, &keys) + diags = appendEncodingKeyDiags(diags, chains, facts, site, &keys) }) return diags } @@ -42,14 +42,14 @@ func checkEncodingKeys(doc *ir.Document, facts *irfacts.DocumentFacts) []ir.Diag // a key up finds no catch-all and renders its parts with no encoding. An empty // key is checkEmptyRefs's and one naming no type checkDanglingRefs', so each // defect draws one code. -func checkCatchAllEncodingKeys(doc *ir.Document) []ir.Diagnostic { +func checkCatchAllEncodingKeys(doc *ir.Document, chains *aliasChains) []ir.Diagnostic { var diags []ir.Diagnostic var keys []ir.TypeID // every content's keys are sorted in this one list forEachPayload(doc, func(site payloadSite) { for i, content := range site.contents { if len(content.CatchAllEncoding) > 0 { at := site.where() + "/contents/" + strconv.Itoa(i) + "/catchAllEncoding/" - diags = appendCatchAllDiags(diags, doc.Types, content, at, &keys) + diags = appendCatchAllDiags(diags, chains, content, at, &keys) } } }) @@ -59,10 +59,11 @@ func checkCatchAllEncodingKeys(doc *ir.Document) []ir.Diagnostic { // appendCatchAllDiags appends to dst a diagnostic per statement of content's // CatchAllEncoding, at at and its key, that the holders of content's body // refute, asking the keys in ascending order, sorted in keys. -func appendCatchAllDiags(dst []ir.Diagnostic, types ir.TypeRegistry, content ir.Content, at string, keys *[]ir.TypeID, +func appendCatchAllDiags(dst []ir.Diagnostic, chains *aliasChains, content ir.Content, at string, keys *[]ir.TypeID, ) []ir.Diagnostic { + types := chains.types holders := map[ir.TypeID]bool{} - anyHolder(types, content.Type.Target, func(typeID ir.TypeID) bool { + chains.anyHolder(content.Type.Target, func(typeID ir.TypeID) bool { for _, holder := range ir.CatchAllHolders(types, typeID) { holders[holder] = true } @@ -226,11 +227,11 @@ func siteOf(payload ir.Payload, owner, field string, index int, request bool) pa // A content whose type no entry declares exposes no part, so each of its keys // is reported beside checkDanglingRefs's finding on the type. The claims // differ, as with checkMapping. -func appendEncodingKeyDiags(dst []ir.Diagnostic, types ir.TypeRegistry, facts *irfacts.DocumentFacts, site payloadSite, +func appendEncodingKeyDiags(dst []ir.Diagnostic, chains *aliasChains, facts *irfacts.DocumentFacts, site payloadSite, keys *[]ir.PropertyID, ) []ir.Diagnostic { for i, content := range site.contents { - dst = appendUnknownPartDiags(dst, types, facts, content, site, i, keys) + dst = appendUnknownPartDiags(dst, chains, facts, content, site, i, keys) } return dst } @@ -243,7 +244,7 @@ func appendEncodingKeyDiags(dst []ir.Diagnostic, types ir.TypeRegistry, facts *i // type's flattening overrides passes, though docs/ir/models.md#the-flattening // has it name the one taken: flattening every type asked about grows // quadratically down a deep hierarchy. -func appendUnknownPartDiags(dst []ir.Diagnostic, types ir.TypeRegistry, facts *irfacts.DocumentFacts, content ir.Content, +func appendUnknownPartDiags(dst []ir.Diagnostic, chains *aliasChains, facts *irfacts.DocumentFacts, content ir.Content, site payloadSite, i int, keys *[]ir.PropertyID, ) []ir.Diagnostic { *keys = (*keys)[:0] @@ -252,7 +253,7 @@ func appendUnknownPartDiags(dst []ir.Diagnostic, types ir.TypeRegistry, facts *i } slices.Sort(*keys) for _, key := range *keys { - if key == "" || partNamed(types, facts, content.Type.Target, key) { + if key == "" || chains.partNamed(facts, content.Type.Target, key) { continue // an empty key names no part, which checkEmptyRefs reports } at := site.where() + "/contents/" + strconv.Itoa(i) + "/encoding/" + string(key) @@ -263,22 +264,24 @@ func appendUnknownPartDiags(dst []ir.Diagnostic, types ir.TypeRegistry, facts *i return dst } -// partNamed reports whether key names a part of a body typed target: a -// property the type exposes, or one a variant of the union it stands for -// exposes, through the unions nested in its variants, as a composition -// distributed across a union puts the body's properties on every variant; -// else one a shape of such a type that is a model narrowing a union holds -// (narrowedHolds), which is read only then (docs/ir/payloads.md). -func partNamed(types ir.TypeRegistry, facts *irfacts.DocumentFacts, target ir.TypeID, key ir.PropertyID) bool { - return anyHolder(types, target, func(typeID ir.TypeID) bool { return facts.Exposes(typeID, key) }) || - anyHolder(types, target, func(typeID ir.TypeID) bool { return narrowedHolds(types, typeID, key, maxNarrowedSteps) }) +// partNamed reports whether key names a part of a body typed target: a property +// the type exposes, or one a variant of the union it names exposes, through the +// unions nested in its variants, as a composition distributed across a union +// puts the body's properties on every variant; else one a shape of such a type +// that is a model narrowing a union holds (narrowedHolds), which is read only +// then (docs/ir/payloads.md). +func (chains *aliasChains) partNamed(facts *irfacts.DocumentFacts, target ir.TypeID, key ir.PropertyID) bool { + return chains.anyHolder(target, func(typeID ir.TypeID) bool { return facts.Exposes(typeID, key) }) || + chains.anyHolder(target, func(typeID ir.TypeID) bool { + return narrowedHolds(chains.types, typeID, key, maxNarrowedSteps) + }) } -// anyHolder reports whether holds answers true of target or, where it stands -// for a union, of a variant of that union, through the unions nested in them, -// depth first, stopping at the first. Each union is read once, so a union +// anyHolder reports whether holds answers true of target or, where it sits for +// a union (unionAt), of a variant of that union, through the unions nested in +// them, depth first, stopping at the first. Each union is read once, so a union // nesting itself ends. -func anyHolder(types ir.TypeRegistry, target ir.TypeID, holds func(ir.TypeID) bool) bool { +func (chains *aliasChains) anyHolder(target ir.TypeID, holds func(ir.TypeID) bool) bool { if holds(target) { return true } @@ -287,7 +290,7 @@ func anyHolder(types ir.TypeRegistry, target ir.TypeID, holds func(ir.TypeID) bo for len(pending) > 0 { next := pending[len(pending)-1] pending = pending[:len(pending)-1] - union := unionThrough(types, next) + union := chains.unionAt(next) if union == nil || read[union] { continue } @@ -321,22 +324,3 @@ func narrowedHolds(types ir.TypeRegistry, target ir.TypeID, key ir.PropertyID, l } return false } - -// unionThrough returns the union target stands for, read through a chain of -// alias scalars, and nil where it stands for none. The IR permits a cyclic -// chain, so a visited set ends the walk at the first type it meets twice. -func unionThrough(types ir.TypeRegistry, target ir.TypeID) *ir.Union { - seen := map[ir.TypeID]bool{} - for !seen[target] { - seen[target] = true - if union, ok := types[target].(*ir.Union); ok { - return union - } - base, alias := ir.AliasBase(types, target) - if !alias { - return nil - } - target = base - } - return nil -} diff --git a/pass/validate_payloads_test.go b/pass/validate_payloads_test.go index 29773cee7..190dd962c 100644 --- a/pass/validate_payloads_test.go +++ b/pass/validate_payloads_test.go @@ -120,10 +120,10 @@ func TestValidate_PayloadRequiredOutsideARequest(t *testing.T) { } } -// TestValidate_EncodingKeysNamingRealPropertiesAreClean is the silent half of the -// proof: with every carrier keyed by a property the content's type really -// declares, Validate reports nothing at all. A check that cannot stay silent is -// no better than one that cannot fire. +// TestValidate_EncodingKeysNamingRealPropertiesAreClean is the report-nothing +// half of the proof: with every carrier keyed by a property the content's type +// really declares, Validate reports nothing at all. A check that cannot report +// nothing is no better than one that cannot fire. func TestValidate_EncodingKeysNamingRealPropertiesAreClean(t *testing.T) { t.Parallel() doc := validDoc() @@ -183,8 +183,8 @@ func TestValidate_EncodingKeyThroughServiceCommonErrors(t *testing.T) { // TestValidate_EncodingKeyThroughComposition covers the three ways a body model // composes a part in. An emitter renders the flat property set // (docs/ir/models.md#the-flattening), so a key naming an inherited part is -// legal IR and the check must stay silent on it — resolving against the model's -// own properties alone would fail every one of these. +// legal IR and the check must report nothing on it — resolving against the +// model's own properties alone would fail every one of these. func TestValidate_EncodingKeyThroughComposition(t *testing.T) { t.Parallel() cases := []struct { @@ -237,7 +237,7 @@ func TestValidate_EncodingKeyThroughAlias(t *testing.T) { t.Parallel() cases := []struct { name string - base ir.TypeID // what the content's alias stands for + base ir.TypeID // what the content's alias names }{ {"an alias over the body model", "type/m"}, {"an alias over an alias over it", "type/alias/inner"}, @@ -394,7 +394,7 @@ func narrowingDoc() *ir.Document { } // TestValidate_EncodingKeyOnTypeWithoutParts covers the targets that expose no -// part at all: a type that is no model, an opaque alias standing for nothing, a +// part at all: a type that is no model, an opaque alias naming nothing, a // registry entry holding a typed nil — which must be reported rather than // dereferenced — and no target at all. Every key on such a content addresses // nothing. @@ -465,7 +465,7 @@ components: } // TestValidate_CompiledAliasMultipartBodyIsClean compiles the documents whose -// bodies sit behind an alias and requires validation to stay silent, the way +// bodies sit behind an alias and requires validation to report nothing, the way // `morphic compile` runs the two stages together. // // The unit cases above plant an alias by hand, and the conformance corpus has no diff --git a/pass/validate_positions.go b/pass/validate_positions.go index 4a33f06bd..c950abe0e 100644 --- a/pass/validate_positions.go +++ b/pass/validate_positions.go @@ -37,87 +37,87 @@ type position struct { // which no compiler writes (#1413). A stop of ir.ForEachOperation is the one // Validate reports for each check that visits operations. func eachPosition(doc *ir.Document, live []ir.TypeID, keys *[]ir.PropertyID, visit func(*position)) { - var positionValue position + var position position for _, id := range live { model, ok := doc.Types[id].(*ir.Model) if !ok { continue } for i := range model.Properties { - visit(propertyPosition(&positionValue, &model.Properties[i], string(id))) + visit(propertyPosition(&position, &model.Properties[i], string(id))) } } for i := range doc.Services { for j := range doc.Services[i].CommonErrors { - headerPositions(&positionValue, doc.Services[i].CommonErrors[j].Headers, string(doc.Services[i].ID), visit) + headerPositions(&position, doc.Services[i].CommonErrors[j].Headers, string(doc.Services[i].ID), visit) } } - ir.ForEachOperation(doc, func(operation ir.Operation) { operationPositions(&positionValue, &operation, keys, visit) }) + ir.ForEachOperation(doc, func(operation ir.Operation) { operationPositions(&position, &operation, keys, visit) }) } -// propertyPosition fills positionValue from pr, a property of owner, which -// stands in for the property's own ID where that is empty. -func propertyPosition(positionValue *position, pr *ir.Property, owner string) *position { +// propertyPosition fills parent from pr, a property of owner, which +// takes the place of the property's own ID where that is empty. +func propertyPosition(parent *position, pr *ir.Property, owner string) *position { node := string(pr.ID) if node == "" { node = owner } - *positionValue = position{ + *parent = position{ node: node, from: pr.Provenance, typ: pr.Type, own: pr.Constraints, encoded: pr.Encoding != nil, def: pr.Default, examples: pr.Examples, } - return positionValue + return parent } // headerPositions visits each of headers, which belong to owner. -func headerPositions(positionValue *position, headers []ir.Header, owner string, visit func(*position)) { +func headerPositions(position *position, headers []ir.Header, owner string, visit func(*position)) { for i := range headers { - visit(propertyPosition(positionValue, &headers[i].Property, owner)) + visit(propertyPosition(position, &headers[i].Property, owner)) } } // operationPositions visits the positions of operation. -func operationPositions(positionValue *position, operation *ir.Operation, keys *[]ir.PropertyID, visit func(*position)) { +func operationPositions(parent *position, operation *ir.Operation, keys *[]ir.PropertyID, visit func(*position)) { for i := range operation.Params { pm := &operation.Params[i] - *positionValue = position{ + *parent = position{ node: string(pm.ID), from: pm.Provenance, typ: pm.Type, own: pm.Constraints, def: pm.Default, examples: pm.Examples, } - visit(positionValue) + visit(parent) } owner := string(operation.ID) for i := range operation.Responses { - headerPositions(positionValue, operation.Responses[i].Headers, owner, visit) + headerPositions(parent, operation.Responses[i].Headers, owner, visit) } if operation.Default != nil { - headerPositions(positionValue, operation.Default.Headers, owner, visit) + headerPositions(parent, operation.Default.Headers, owner, visit) } for i := range operation.Errors { - headerPositions(positionValue, operation.Errors[i].Headers, owner, visit) + headerPositions(parent, operation.Errors[i].Headers, owner, visit) } - partPositions(positionValue, operation.Request, owner, keys, visit) + partPositions(parent, operation.Request, owner, keys, visit) for i := range operation.Responses { - partPositions(positionValue, operation.Responses[i].Payload, owner, keys, visit) + partPositions(parent, operation.Responses[i].Payload, owner, keys, visit) } if operation.Default != nil { - partPositions(positionValue, operation.Default.Payload, owner, keys, visit) + partPositions(parent, operation.Default.Payload, owner, keys, visit) } for i := range operation.Errors { - partPositions(positionValue, operation.Errors[i].Payload, owner, keys, visit) + partPositions(parent, operation.Errors[i].Payload, owner, keys, visit) } } // partPositions visits the headers of the parts of each content of payload: the // item's, then each part's, in the order of its sorted keys. -func partPositions(positionValue *position, payload *ir.Payload, owner string, keys *[]ir.PropertyID, visit func(*position)) { +func partPositions(position *position, payload *ir.Payload, owner string, keys *[]ir.PropertyID, visit func(*position)) { if payload == nil { return } for i := range payload.Contents { content := &payload.Contents[i] if content.ItemEncoding != nil { - headerPositions(positionValue, content.ItemEncoding.Headers, owner, visit) + headerPositions(position, content.ItemEncoding.Headers, owner, visit) } *keys = (*keys)[:0] for propertyID := range content.Encoding { @@ -126,7 +126,7 @@ func partPositions(positionValue *position, payload *ir.Payload, owner string, k slices.Sort(*keys) for _, propertyID := range *keys { part := content.Encoding[propertyID] - headerPositions(positionValue, part.Headers, owner, visit) + headerPositions(position, part.Headers, owner, visit) } } } diff --git a/pass/validate_refs.go b/pass/validate_refs.go index 943e08d4c..4288643ae 100644 --- a/pass/validate_refs.go +++ b/pass/validate_refs.go @@ -120,15 +120,15 @@ type propertyIDSites struct { paths ir.PathLog } -// Visit keeps v if it is a PropertyID reference that may not resolve. -func (p *propertyIDSites) Visit(v reflect.Value, at ir.WalkPath) bool { - if v.Kind() != reflect.String || v.Type() != propertyIDType || v.String() == "" || at.IsMapKey() { +// Visit keeps value if it is a PropertyID reference that may not resolve. +func (p *propertyIDSites) Visit(value reflect.Value, at ir.WalkPath) bool { + if value.Kind() != reflect.String || value.Type() != propertyIDType || value.String() == "" || at.IsMapKey() { return true } - if p.refs.Declares(propertyIDType, v.String()) { + if p.refs.Declares(propertyIDType, value.String()) { return true } - p.sites = append(p.sites, ir.IDReference{Class: propertyIDType, ID: v.String()}) + p.sites = append(p.sites, ir.IDReference{Class: propertyIDType, ID: value.String()}) p.paths.Record(at) return true } diff --git a/pass/validate_refs_test.go b/pass/validate_refs_test.go index 86e687b87..3932a27bb 100644 --- a/pass/validate_refs_test.go +++ b/pass/validate_refs_test.go @@ -304,7 +304,7 @@ func TestValidate_DiagnosticOrderIsDeterministic(t *testing.T) { // TestValidate_ResolvedRefsInEveryFieldAreClean is the other half of the // mutation proof: with every one of those fields populated by a target that // does resolve, Validate reports no dangling reference. A check that cannot -// stay silent is no better than one that cannot fire. +// report nothing is no better than one that cannot fire. func TestValidate_ResolvedRefsInEveryFieldAreClean(t *testing.T) { t.Parallel() doc := validDoc() @@ -717,7 +717,7 @@ func TestValidate_DanglingTypedIDRef(t *testing.T) { // TestValidate_ResolvedTypedIDRefsAreClean is the other half of the proof: the // same fields filled with references that resolve must report nothing. A check -// that cannot stay silent is no better than one that cannot fire. +// that cannot report nothing is no better than one that cannot fire. func TestValidate_ResolvedTypedIDRefsAreClean(t *testing.T) { t.Parallel() doc := registryDoc() diff --git a/pass/validate_registrykeys_sweep_test.go b/pass/validate_registrykeys_sweep_test.go index 50e286a50..39804112c 100644 --- a/pass/validate_registrykeys_sweep_test.go +++ b/pass/validate_registrykeys_sweep_test.go @@ -44,12 +44,12 @@ func registryFields(t *testing.T) []reflect.StructField { // registryNode is the ID the registry node v declares, and the group the sweep // moves one node of: a type's kind, or a scheme's kind and its ID's space. -func registryNode(v reflect.Value) (id, group string) { - if td, ok := reflect.TypeAssert[ir.TypeDef](v); ok { - return string(td.Common().ID), string(td.Kind()) +func registryNode(value reflect.Value) (id, group string) { + if typeDef, ok := reflect.TypeAssert[ir.TypeDef](value); ok { + return string(typeDef.Common().ID), string(typeDef.Kind()) } - id = v.FieldByName("ID").String() - if k := v.FieldByName("Kind"); k.IsValid() { + id = value.FieldByName("ID").String() + if k := value.FieldByName("Kind"); k.IsValid() { kind, _, _ := strings.Cut(id, ir.IDSeparator) space, _ := ir.IDSpace(kind, id) return id, k.String() + " in " + space @@ -77,7 +77,7 @@ func unfiled(doc *ir.Document, field reflect.StructField, key string) *ir.Docume func refiledUnder(doc *ir.Document, field reflect.StructField, from, to string) *ir.Document { out := unfiled(doc, field, from) m := reflect.ValueOf(doc).Elem().FieldByIndex(field.Index) - key := func(s string) reflect.Value { return reflect.ValueOf(s).Convert(m.Type().Key()) } + key := func(text string) reflect.Value { return reflect.ValueOf(text).Convert(m.Type().Key()) } reflect.ValueOf(out).Elem().FieldByIndex(field.Index).SetMapIndex(key(to), m.MapIndex(key(from))) return out } @@ -260,18 +260,18 @@ func holdsTheMismatchAlone(t *testing.T, name string, field reflect.StructField, // whatever a registry files under the empty key. func TestValidate_AnEmptyReferenceResolvesToNoNodeUnderTheEmptyKey(t *testing.T) { t.Parallel() - stringValue := ir.Value{Kind: ir.ValueString, String: "v"} + text := ir.Value{Kind: ir.ValueString, String: "v"} empties := func() *ir.Document { return &ir.Document{IRVersion: ir.IRVersion, Types: ir.TypeRegistry{ "type/primitive/int32": &ir.Primitive{ID: "type/primitive/int32", PrimitiveKind: ir.PrimitiveInt32}, "type/x/U": &ir.Model{ID: "type/x/U", Name: named("u"), Base: &ir.TypeRef{}, Properties: []ir.Property{ - {ID: "property/x/U/a", Name: named("a"), WireName: "a", Required: true, Type: ir.TypeRef{}, Default: &stringValue}, + {ID: "property/x/U/a", Name: named("a"), WireName: "a", Required: true, Type: ir.TypeRef{}, Default: &text}, }}, "type/x/V": &ir.Union{ID: "type/x/V", Name: named("v"), Variants: []ir.Variant{{Type: ir.TypeRef{}}}}, "type/x/L": &ir.List{ID: "type/x/L", ElementType: ir.TypeRef{}}, }, Services: []ir.Service{{ID: "service/x/S", Groups: []ir.OperationGroup{{ID: "operation-group/x/G", Operations: []ir.Operation{{ ID: "operation/x/o", Params: []ir.Parameter{{ID: "parameter/x/o/q", Name: named("q")}}, - Examples: []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": stringValue}}}}, + Examples: []ir.Example{{Name: "ex", Input: &ir.ScenarioInput{Params: map[ir.ParameterID]ir.Value{"parameter/x/o/q": text}}}}, }}}}}}} } want := validatedOnce(t, empties()) diff --git a/pass/validate_responses_test.go b/pass/validate_responses_test.go index 2bdd85a5f..f3357bdae 100644 --- a/pass/validate_responses_test.go +++ b/pass/validate_responses_test.go @@ -104,9 +104,9 @@ func TestValidate_ADefaultAnswersTheCatchAllAlone(t *testing.T) { } } -// TestValidate_AnOperationWithoutADefaultHasNoDefaultConditionsToJudge pins that -// the check is silent on an operation declaring no Default, whose absent -// response has no conditions to hold to the catch-all. +// TestValidate_AnOperationWithoutADefaultHasNoDefaultConditionsToJudge pins +// that the check reports nothing on an operation declaring no Default, whose +// absent response has no conditions to hold to the catch-all. func TestValidate_AnOperationWithoutADefaultHasNoDefaultConditionsToJudge(t *testing.T) { t.Parallel() operation := ir.Operation{ID: "op", Responses: []ir.Response{{ diff --git a/pass/validate_scaling_test.go b/pass/validate_scaling_test.go index 886442f05..d5e45e113 100644 --- a/pass/validate_scaling_test.go +++ b/pass/validate_scaling_test.go @@ -20,16 +20,16 @@ import ( // Base, and n bases, each routing a discriminator mapping to the bottom of the // chain. Validate asks, for every base, whether that model is its subtype, and // the answer is no. -func chainedDiscriminators(n int) *ir.Document { +func chainedDiscriminators(count int) *ir.Document { chain := func(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("type/c%05d", i)) } types := ir.TypeRegistry{chain(0): &ir.Model{ID: chain(0)}} - for i := 1; i <= n; i++ { + for i := 1; i <= count; i++ { types[chain(i)] = &ir.Model{ID: chain(i), Base: &ir.TypeRef{Target: chain(i - 1)}} } - for k := range n { + for k := range count { id := ir.TypeID(fmt.Sprintf("type/m%05d", k)) types[id] = &ir.Model{ID: id, Discriminator: &ir.Discriminator{ - Mapping: map[string]ir.TypeID{"x": chain(n)}, + Mapping: map[string]ir.TypeID{"x": chain(count)}, }} } return &ir.Document{IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: types} @@ -46,12 +46,12 @@ const spread = 8 // size allocates step up wherever a table or a backing array happens to grow. // Averaged across a whole doubling the steps cancel, rather than one falling // between two of the sizes a test compares and reading as superlinear growth. -func costAround(t *testing.T, n int, build func(n int) *ir.Document, +func costAround(t *testing.T, count int, build func(n int) *ir.Document, holds func(t *testing.T, size int, diags []ir.Diagnostic), ) (allocs, bytes float64) { t.Helper() for j := range spread { - size := int(math.Round(float64(n) * math.Exp2(float64(j)/spread))) + size := int(math.Round(float64(count) * math.Exp2(float64(j)/spread))) doc := build(size) holds(t, size, validatedOnce(t, doc)) a, b := validateCost(t, doc) @@ -87,39 +87,80 @@ func TestValidate_DiscriminatorRoutesCostLinearWork(t *testing.T) { "bytes around 250, 500, 1000: %v", bytes) } +// chainedHolders is n+1 models chained by Base, each holding a discriminator +// that routes nothing, so each of the n below the top is a subtype no route +// reaches, below as many discriminators as there are models above it. +func chainedHolders(count int) *ir.Document { + chain := func(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("type/c%05d", i)) } + types := ir.TypeRegistry{} + for i := 0; i <= count; i++ { + model := &ir.Model{ID: chain(i), Discriminator: &ir.Discriminator{PropertyName: "kind"}} + if i > 0 { + model.Base = &ir.TypeRef{Target: chain(i - 1)} + } + types[model.ID] = model + } + return &ir.Document{IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: types} +} + +// TestValidate_UnroutedSubtypesCostLinearWork holds validating chainedHolders +// to one finding a subtype, at the discriminator nearest above it, and its +// allocations and bytes to linear growth around three sizes, as +// TestValidate_DiscriminatorRoutesCostLinearWork does: a finding a pair of +// discriminator and subtype below it grows with the square of the chain, and +// so does a walk below each discriminator. It does not run in parallel, since +// both counts are process-wide. +func TestValidate_UnroutedSubtypesCostLinearWork(t *testing.T) { + var allocs, bytes [3]float64 + for k, n := range []int{250, 500, 1000} { + allocs[k], bytes[k] = costAround(t, n, chainedHolders, func(t *testing.T, size int, diags []ir.Diagnostic) { + require.Len(t, withCode(diags, "pass/discriminator-unrouted-variant"), size, "one finding a subtype") + }) + } + assert.LessOrEqual(t, allocs[2]-allocs[1], 2.5*(allocs[1]-allocs[0]), + "allocations around 250, 500, 1000: %v", allocs) + assert.LessOrEqual(t, bytes[2]-bytes[1], 2.5*(bytes[1]-bytes[0]), + "bytes around 250, 500, 1000: %v", bytes) +} + // chainedProperties is n+1 models chained by Base, the top declaring property -// "property/kind", shaped further by mutate. -func chainedProperties(n int, mutate func(model *ir.Model)) (ir.TypeRegistry, ir.TypeID) { +// "property/kind". +func chainedProperties(count int) (ir.TypeRegistry, ir.TypeID) { chain := func(i int) ir.TypeID { return ir.TypeID(fmt.Sprintf("type/c%05d", i)) } types := ir.TypeRegistry{"type/string": &ir.Primitive{ID: "type/string", PrimitiveKind: ir.PrimitiveString}} - for i := 0; i <= n; i++ { + for i := 0; i <= count; i++ { model := &ir.Model{ID: chain(i)} if i == 0 { model.Properties = []ir.Property{{ID: "property/kind", Type: ir.TypeRef{Target: "type/string"}}} } else { model.Base = &ir.TypeRef{Target: chain(i - 1)} } - if mutate != nil { - mutate(model) - } types[model.ID] = model } - return types, chain(n) + return types, chain(count) } // exposureShapes are the documents whose exposed-property questions Validate -// asks once per site: a chain of discriminators, each tagging the property its -// top declares, and n operations each sending the chain's bottom as multipart -// with that property encoded as a part. Every question is answered yes. +// asks once per site: a discriminator below each model of a chain, each +// tagging the property the chain's top declares, and n operations each +// sending the chain's bottom as multipart with that property encoded as a +// part. Every question is answered yes. A discriminator sits on a model with +// no subtype, so none has a subtype it leaves unrouted +// (TestValidate_UnroutedSubtypesCostLinearWork holds those). func exposureShapes() map[string]func(n int) *ir.Document { return map[string]func(n int) *ir.Document{ - "a chain of discriminators tagging the top's property": func(n int) *ir.Document { - types, _ := chainedProperties(n, func(model *ir.Model) { model.Discriminator = &ir.Discriminator{Property: "property/kind"} }) + "discriminators below a chain tagging its top's property": func(count int) *ir.Document { + types, _ := chainedProperties(count) + for i := 0; i <= count; i++ { + id := ir.TypeID(fmt.Sprintf("type/d%05d", i)) + types[id] = &ir.Model{ID: id, Base: &ir.TypeRef{Target: ir.TypeID(fmt.Sprintf("type/c%05d", i))}, + Discriminator: &ir.Discriminator{Property: "property/kind"}} + } return &ir.Document{IRVersion: ir.IRVersion, Name: "t", Version: "1", Types: types} }, - "multipart parts naming the top's property of the bottom": func(n int) *ir.Document { - types, bottom := chainedProperties(n, nil) - operations := make([]ir.Operation, n) + "multipart parts naming the top's property of the bottom": func(count int) *ir.Document { + types, bottom := chainedProperties(count) + operations := make([]ir.Operation, count) for i := range operations { operations[i] = ir.Operation{ID: ir.OperationID(fmt.Sprintf("op%05d", i)), Request: &ir.Payload{Contents: []ir.Content{{ MediaType: "multipart/form-data", Type: ir.TypeRef{Target: bottom}, diff --git a/pass/validate_shapes_test.go b/pass/validate_shapes_test.go index 7b9b8a07f..8faa39adf 100644 --- a/pass/validate_shapes_test.go +++ b/pass/validate_shapes_test.go @@ -21,7 +21,7 @@ func shapesDoc(properties ...ir.Property) *ir.Document { id := ir.PrimitiveTypeID(kind) doc.Types[id] = &ir.Primitive{ID: id, PrimitiveKind: kind} } - for _, td := range []ir.TypeDef{ + for _, typeDef := range []ir.TypeDef{ &ir.List{ID: "type/list", ElementType: stringT}, &ir.Tuple{ID: "type/tuple", ElementTypes: []ir.TypeRef{stringT, stringT}}, &ir.MapT{ID: "type/map", Key: &stringKey, Value: stringT}, @@ -30,14 +30,14 @@ func shapesDoc(properties ...ir.Property) *ir.Document { &ir.Scalar{ID: "type/alias", Base: &ir.TypeRef{Target: "type/list"}}, &ir.Scalar{ID: "type/loop-a", Base: &ir.TypeRef{Target: "type/loop-b"}}, &ir.Scalar{ID: "type/loop-b", Base: &ir.TypeRef{Target: "type/loop-a"}}, - &ir.Enum{ID: "type/mixed", ValueType: ir.PrimitiveString, Members: []ir.EnumMember{ + &ir.Enum{ID: "type/mixed", ValueType: ir.PrimitiveString, Closed: true, Members: []ir.EnumMember{ {ID: "enum-member/null", Value: *null()}, {ID: "enum-member/flag", Value: ir.Value{Kind: ir.ValueBool, Bool: true}}, {ID: "enum-member/symbol", Value: ir.Value{Kind: ir.ValueSymbol, String: "sym"}}, {ID: "enum-member/bytes", Value: ir.Value{Kind: ir.ValueBytes, Bytes: []byte("ab")}}, {ID: "enum-member/list", Value: ir.Value{Kind: ir.ValueList}}, {ID: "enum-member/bad", Value: *number("x")}, }}, } { - doc.Types[td.Common().ID] = td + doc.Types[typeDef.Common().ID] = typeDef } return doc } @@ -129,6 +129,25 @@ func TestValidate_ADefaultIsHeldToTheShapeOfItsType(t *testing.T) { } } +// TestValidate_ANonFiniteElementOfAListOfFloatsIsOneOfItsValues holds a +// default's elements to a list of float64: an infinity and a NaN are values of +// the element type and draw nothing, and a string draws the finding. +func TestValidate_ANonFiniteElementOfAListOfFloatsIsOneOfItsValues(t *testing.T) { + t.Parallel() + floats := &ir.List{ID: "type/floats", ElementType: ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveFloat64)}} + for name, tc := range map[string]struct { + elements []ir.Value + want int + }{ + "an infinity and a NaN": {[]ir.Value{{Kind: ir.ValueInfinity}, {Kind: ir.ValueNegativeInfinity}, {Kind: ir.ValueNaN}}, 0}, + "a string": {[]ir.Value{*text("s")}, 1}, + } { + doc := shapesDoc(property("property/a/x", ir.TypeRef{Target: floats.ID}, defaulted(&ir.Value{Kind: ir.ValueList, List: tc.elements}))) + doc.Types[floats.ID] = floats + assert.Len(t, found(t, doc, defaultCode), tc.want, name) + } +} + // TestValidate_ADefaultIsHeldToTheBoundsOfItsShape holds a default of a count // of bytes, members or items and a number to the bounds its position declares // at either end, and leaves a value the bounds do not apply to alone. @@ -151,8 +170,8 @@ func TestValidate_ADefaultIsHeldToTheBoundsOfItsShape(t *testing.T) { {"a number over its maximum", intT, number("5"), numeric("", "", "4", ""), 1}, {"a number at an exclusive maximum", intT, number("4"), numeric("", "", "", "4"), 1}, {"a number at its maximum", intT, number("4"), numeric("", "", "4", ""), 0}, - {"an infinity under bounds on numbers", ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveFloat64)}, - &ir.Value{Kind: ir.ValueInfinity}, numeric("", "", "4", ""), 0}, + {"an infinity past a maximum", ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveFloat64)}, + &ir.Value{Kind: ir.ValueInfinity}, numeric("", "", "4", ""), 1}, {"a number that does not parse", intT, number("x"), numeric("", "", "4", ""), 0}, {"a bool under bounds", boolT, &ir.Value{Kind: ir.ValueBool}, lengths(0, 1), 0}, } { @@ -164,6 +183,44 @@ func TestValidate_ADefaultIsHeldToTheBoundsOfItsShape(t *testing.T) { } } +// TestValidate_AnInfinityOrNaNIsHeldToTheNumericBounds holds a non-finite +// default to the numeric bounds its position declares, as the value admission +// reader judges it: an infinity lies past every limit on its side, NaN within +// none and neither on a step, and NaN under no numeric bound is a value of a +// float. At a number of no IEEE 754 kind, none is a value. +func TestValidate_AnInfinityOrNaNIsHeldToTheNumericBounds(t *testing.T) { + t.Parallel() + float64T, numberT := ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveFloat64)}, ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveNumber)} + infinity, negativeInfinity, nan := &ir.Value{Kind: ir.ValueInfinity}, &ir.Value{Kind: ir.ValueNegativeInfinity}, &ir.Value{Kind: ir.ValueNaN} + for _, tc := range []struct { + name string + typ ir.TypeRef + def *ir.Value + c *ir.Constraints + want int + }{ + {"an infinity above a minimum", float64T, infinity, numeric("4", "", "", ""), 0}, + {"an infinity past an exclusive maximum", float64T, infinity, numeric("", "", "", "4"), 1}, + {"a negative infinity within a maximum", float64T, negativeInfinity, numeric("", "", "4", ""), 0}, + {"a negative infinity below a minimum", float64T, negativeInfinity, numeric("4", "", "", ""), 1}, + {"a negative infinity below an exclusive minimum", float64T, negativeInfinity, numeric("", "4", "", ""), 1}, + {"an infinity off a step", float64T, infinity, withMultiple(&ir.Constraints{}, "2"), 1}, + {"NaN under a minimum", float64T, nan, numeric("4", "", "", ""), 1}, + {"NaN under a maximum", float64T, nan, numeric("", "", "4", ""), 1}, + {"NaN off a step", float64T, nan, withMultiple(&ir.Constraints{}, "2"), 1}, + {"NaN under a length alone", float64T, nan, lengths(0, 1), 0}, + {"an infinity at a number", numberT, infinity, nil, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + doc := shapesDoc(property("property/a/x", tc.typ, func(property *ir.Property) { property.Default = tc.def; property.Constraints = tc.c })) + doc.Types[numberT.Target] = &ir.Primitive{ID: numberT.Target, PrimitiveKind: ir.PrimitiveNumber} + got := found(t, doc, defaultCode) + assert.Len(t, got, tc.want, "%v", got) + }) + } +} + // TestValidate_ADefaultIsHeldToTheMembersOfAnEnumAsTheyAreWritten holds a // default to an enum whose members are of each kind: a symbol is a string, a // pair of bytes the same by content, a null a member of its own, and what a diff --git a/pass/validate_stop_test.go b/pass/validate_stop_test.go index 155cd73c3..5085a67d3 100644 --- a/pass/validate_stop_test.go +++ b/pass/validate_stop_test.go @@ -20,12 +20,12 @@ import ( // cutWalk returns a walk of the document as Validate takes it that shows each // visitor at most n values, as a walk cut short by the limit does, and says it // stopped once a visitor would have been shown another. -func cutWalk(n int) func(context.Context, any, string, ...ir.Visitor) (bool, error) { +func cutWalk(count int) func(context.Context, any, string, ...ir.Visitor) (bool, error) { return func(ctx context.Context, root any, path string, visitors ...ir.Visitor) (bool, error) { cut := false held := make([]ir.Visitor, len(visitors)) for i, visitor := range visitors { - held[i] = &cutVisitor{inner: visitor, left: n, cut: &cut} + held[i] = &cutVisitor{inner: visitor, valuesLeft: count, cut: &cut} } truncated, err := ir.WalkValuesContext(ctx, root, path, held...) return truncated || cut, err @@ -35,19 +35,19 @@ func cutWalk(n int) func(context.Context, any, string, ...ir.Visitor) (bool, err // cutVisitor shows inner the values a walk reaches until left runs out, and // then none, recording in cut that one went unshown. type cutVisitor struct { - inner ir.Visitor - left int - cut *bool + inner ir.Visitor + valuesLeft int + cut *bool } // Visit shows v to the inner visitor while the limit lasts. -func (c *cutVisitor) Visit(v reflect.Value, at ir.WalkPath) bool { - if c.left == 0 { +func (c *cutVisitor) Visit(value reflect.Value, at ir.WalkPath) bool { + if c.valuesLeft == 0 { *c.cut = true return false } - c.left-- - return c.inner.Visit(v, at) + c.valuesLeft-- + return c.inner.Visit(value, at) } // shownWhole returns how many values a walk of root shows a visitor that prunes @@ -61,8 +61,8 @@ func shownWhole(root any) int { // TestValidate_AStoppedWalkIsReportedOnce holds Validate to saying that part of // the document went unchecked once, however many of its checks read operations // through a walk that stopped: the document walk's stop is reported, and the -// check of nested groups, whose own walk is cut at the same document, is silent -// where that has been said. +// check of nested groups, whose own walk is cut at the same document, reports +// nothing where that has been said. func TestValidate_AStoppedWalkIsReportedOnce(t *testing.T) { t.Parallel() oneway := ir.Operation{ID: "deep", OneWay: true, Responses: []ir.Response{{}}} diff --git a/pass/validate_unions_test.go b/pass/validate_unions_test.go index 38fc1d647..a6da70d66 100644 --- a/pass/validate_unions_test.go +++ b/pass/validate_unions_test.go @@ -51,7 +51,8 @@ func TestValidate_ReportsAVariantNamingAnEarlierVariantsType(t *testing.T) { {"after another type", ir.Union{Exclusive: true, Variants: variants("type/primitive/string", "type/m", "type/m")}, []string{exclusive + "2: variants 1 and 2"}}, {"tagged in the payload", ir.Union{Exclusive: true, WireTagged: true, - Discriminator: &ir.Discriminator{PropertyName: "kind"}, Variants: variants("type/m", "type/m")}, + Discriminator: &ir.Discriminator{PropertyName: "kind", Mapping: map[string]ir.TypeID{"m": "type/m"}}, + Variants: variants("type/m", "type/m")}, []string{exclusive + "1: variants 0 and 1"}}, {"tagged by key", ir.Union{Exclusive: true, WireTagged: true, Variants: variants("type/m", "type/m")}, []string{}}, {"distinct types", ir.Union{Exclusive: true, Variants: variants("type/m", "type/primitive/string")}, []string{}}, diff --git a/pass/validate_unreached_test.go b/pass/validate_unreached_test.go index 8e2b95236..916cbeff3 100644 --- a/pass/validate_unreached_test.go +++ b/pass/validate_unreached_test.go @@ -15,8 +15,8 @@ import ( // TestValidate_TheChecksOfWhatASourceSaysSkipAReferenceWithNoDeclaration holds // each of them to a position whose type is empty or names nothing the document // declares: such a reference is irverify's when empty and the dangling check's -// otherwise, so a check that reads one stays silent and does not panic. It is -// the row that fails if a check forgets and reads an empty ID as a type to +// otherwise, so a check that reads one reports nothing and does not panic. It +// is the row that fails if a check forgets and reads an empty ID as a type to // judge: every position holds a bound, a default, an example, a base or a // requirement that a declared type would make a finding. func TestValidate_TheChecksOfWhatASourceSaysSkipAReferenceWithNoDeclaration(t *testing.T) { diff --git a/pass/validate_values.go b/pass/validate_values.go index 96b6f72fa..96660fd86 100644 --- a/pass/validate_values.go +++ b/pass/validate_values.go @@ -4,9 +4,9 @@ package pass import ( + "fmt" "slices" "strconv" - "unicode/utf8" "github.com/dexpace/morphic/ir" ) @@ -15,7 +15,8 @@ import ( // the place declares, the bounds it declares beside it, and whether its value // is written in an encoding of its own. type valueSite struct { - doc *ir.Document + // chains reads the alias chains the site's type reaches. + chains *aliasChains // node and from place a finding at the entity that holds the value. node string from ir.Provenance @@ -24,39 +25,49 @@ type valueSite struct { // encoded says the value is written in an encoding, so its kind says // nothing of what the type holds. encoded bool - // typeLevel says the value is an example of the type itself, for which - // null stands for an example that is absent and is never judged. + // typeLevel says the value is an example of the type itself, for which null + // names an example that is absent and is never judged. typeLevel bool } // checkValues reports each default and each example whose value its type does // not admit (pass/default-outside-type, pass/example-outside-type, // docs/ir/values.md): two codes, since a default reaches the code an emitter -// writes and an example the docs. The judgement is shallow, of kind, enum -// members, a literal, null, whole numbers and declared bounds. What it leaves -// alone, such as a content's examples (#1949), is listed in docs/ir/values.md. -func checkValues(doc *ir.Document, live []ir.TypeID) []ir.Diagnostic { +// writes and an example the docs. Past enum members, a literal and null, the +// run's value admission reader judges the value against the type and the +// bounds the position declares (valueSite.admitted). What it leaves alone, +// such as a content's examples (#1949), is listed in docs/ir/values.md. +func checkValues(doc *ir.Document, chains *aliasChains, live []ir.TypeID) []ir.Diagnostic { var diags []ir.Diagnostic for _, id := range live { typeCommon := doc.Types[id].Common() - site := valueSite{doc: doc, node: string(id), from: typeCommon.Provenance, ref: ir.TypeRef{Target: id}, typeLevel: true} + site := valueSite{chains: chains, node: string(id), from: typeCommon.Provenance, ref: ir.TypeRef{Target: id}, typeLevel: true} diags = site.appendExamples(diags, typeCommon.Examples) } var keys []ir.PropertyID - eachPosition(doc, live, &keys, func(positionValue *position) { - site := valueSite{doc: doc, node: positionValue.node, from: positionValue.from, ref: positionValue.typ, own: positionValue.own, encoded: positionValue.encoded} - if why := site.fits(positionValue.def); why != "" { + eachPosition(doc, live, &keys, func(position *position) { + site := valueSite{chains: chains, node: position.node, from: position.from, ref: position.typ, own: position.own, encoded: position.encoded} + if why := site.fits(position.def); why != "" { diags = append(diags, site.finding("pass/default-outside-type", "default "+why)) } - diags = site.appendExamples(diags, positionValue.examples) + diags = site.appendExamples(diags, position.examples) }) var params []ir.ParameterID ir.ForEachOperation(doc, func(operation ir.Operation) { - diags = appendScenarioValues(diags, doc, &operation, ¶ms) + diags = appendScenarioValues(diags, chains, &operation, ¶ms) }) + if chains.unjudged != nil { + diags = append(diags, *chains.unjudged) + } return diags } +// maxValueJudgments bounds the judgments, each a type against one node of a +// value (ir.ValueAdmissionReader.AdmitsAtPositionWithin), the run's value +// admission reader takes over every value a Validate run judges: a union of +// many models judged for many values costs their product. +const maxValueJudgments = 1 << 22 + // finding is the warning a value of the site draws. func (s *valueSite) finding(code, message string) ir.Diagnostic { return diagAt(code, message, s.node, s.from) @@ -83,17 +94,17 @@ func exampleLabel(ex *ir.Example, i int) string { } // appendScenarioValues reports the values of operation's scenarios the type of -// what they stand for does not admit: each input parameter, against the -// parameter of its ID, and the content of the error a scenario ends in, against -// the error's type. params holds the sorted IDs of one input. -func appendScenarioValues(diags []ir.Diagnostic, doc *ir.Document, operation *ir.Operation, params *[]ir.ParameterID) []ir.Diagnostic { +// what they name does not admit: each input parameter, against the parameter of +// its ID, and the content of the error a scenario ends in, against the error's +// type. params holds the sorted IDs of one input. +func appendScenarioValues(diags []ir.Diagnostic, chains *aliasChains, operation *ir.Operation, params *[]ir.ParameterID) []ir.Diagnostic { for i := range operation.Examples { ex := &operation.Examples[i] if ex.Input != nil { - diags = appendInputValues(diags, doc, operation, ex, i, params) + diags = appendInputValues(diags, chains, operation, ex, i, params) } if ex.Error != nil { - site := valueSite{doc: doc, node: string(operation.ID), from: operation.Provenance, ref: ex.Error.Type} + site := valueSite{chains: chains, node: string(operation.ID), from: operation.Provenance, ref: ex.Error.Type} if why := site.fits(&ex.Error.Content); why != "" { diags = append(diags, site.finding("pass/example-outside-type", "scenario "+exampleLabel(ex, i)+" error "+why)) @@ -107,7 +118,7 @@ func appendScenarioValues(diags []ir.Diagnostic, doc *ir.Document, operation *ir // operation, whose value the parameter's type does not admit, in the order of // their IDs. An input naming a parameter operation does not declare is skipped: // pass/param-binding-mismatch has it. -func appendInputValues(diags []ir.Diagnostic, doc *ir.Document, operation *ir.Operation, ex *ir.Example, i int, +func appendInputValues(diags []ir.Diagnostic, chains *aliasChains, operation *ir.Operation, ex *ir.Example, i int, params *[]ir.ParameterID, ) []ir.Diagnostic { *params = (*params)[:0] @@ -120,7 +131,7 @@ func appendInputValues(diags []ir.Diagnostic, doc *ir.Document, operation *ir.Op if pm == nil { continue } - site := valueSite{doc: doc, node: string(operation.ID), from: operation.Provenance, ref: pm.Type, own: pm.Constraints} + site := valueSite{chains: chains, node: string(operation.ID), from: operation.Provenance, ref: pm.Type, own: pm.Constraints} value := ex.Input.Params[id] if why := site.fits(&value); why != "" { diags = append(diags, site.finding("pass/example-outside-type", @@ -141,65 +152,163 @@ func parameterOf(operation *ir.Operation, id ir.ParameterID) *ir.Parameter { } // fits returns why value is no value of the site's type, or "" when it is one -// or the check leaves it alone: a value that is a reference or a constructor, a -// type nothing declares, one holding anything, a union or an external type, and -// a value written in an encoding. +// or the check leaves it alone. Past the membership, null and encoding checks, +// in that order (GitHub #2178), the run's value admission reader judges the +// value against the type and the position's own bounds (admitted). func (s *valueSite) fits(value *ir.Value) string { if value == nil || value.Kind == ir.ValueRefKind || value.Kind == ir.ValueConstructor { return "" } - var b bounds - b.and(s.own) - sh, td, enc := settle(s.doc, s.ref.Target, &b) - if td == nil || sh == shapeAnything { + reading := s.chains.settle(s.ref.Target) + sh, typeDef := reading.shape, reading.end + if typeDef == nil || sh == shapeAnything { return "" } - target := s.ref.Target nullOK := s.ref.Nullable || s.typeLevel - switch t := td.(type) { - case *ir.Union, *ir.External: + bounds := boundSetsOf(s.own).then(reading.bounds) + switch t := typeDef.(type) { + case *ir.External: return "" case *ir.Enum: - if slices.ContainsFunc(t.Members, func(enumMember ir.EnumMember) bool { return same(&enumMember.Value, value) }) || - (value.Kind == ir.ValueNull && nullOK) { - return "" - } - return "is not a member of enum " + string(target) + return s.enumRefusal(t, value, reading.encoded, bounds) case *ir.Literal: if same(&t.Value, value) || (value.Kind == ir.ValueNull && nullOK) { return "" } - return "is not the value of literal " + string(target) + return "is not the value of literal " + string(s.ref.Target) default: - // a value of any other type is judged by its kind below + // a value of any other type is judged by the reader below + } + if holdsParts(sh) && !admits(sh, value.Kind) && typeDef.Common().Provenance.Inferred != "" { + return "" // a heuristic gave the node its kind, so the source may admit every kind, null among them } if value.Kind == ir.ValueNull { - if nullOK { - return "" - } - return "is null, and " + string(target) + " is not nullable here" + return s.fitsNull(value, sh, nullOK) } - if s.encoded || enc || sh == shapeNotChecked { + if s.encoded || reading.encoded { return "" } - return fitsShape(value, sh, target, &b) + return s.admitted(value, sh, bounds) } -// fitsShape returns why value, which is not null, is no value of shape sh, the -// shape of target, or lies outside the bounds b holds. -func fitsShape(value *ir.Value, sh shape, target ir.TypeID, b *bounds) string { - if !admits(sh, value.Kind) { - return "is " + kindWords(value.Kind) + ", and " + string(target) + " holds " + shapeWords(sh) +// fitsNull returns why null, value, is no value of the site's type, of shape +// sh, or "" where nullOK says the site admits it. A shape the checks read no +// further, as a union's, whose variant may admit null, is the reader's. +func (s *valueSite) fitsNull(value *ir.Value, sh shape, nullOK bool) string { + switch { + case nullOK: + return "" + case sh == shapeNotChecked: + return s.admitted(value, sh, boundSets{}) + default: + return "is null, and " + string(s.ref.Target) + " is not nullable here" } - if sh == shapeInteger { - if decimal, err := value.Number.Decimal(); err == nil && !decimal.IsInt() { - return "is no integer, and " + string(target) + " holds one" +} + +// holdsParts reports whether a value of shape sh holds values of its own, a +// list's elements or an object's members. +func holdsParts(sh shape) bool { return sh == shapeList || sh == shapeObject } + +// admitted returns why the run's value admission reader refuses value at the +// site, against its type and the bounds the position declares beside it, or +// "" where it admits value, cannot tell or has no judgment left for it +// (maxValueJudgments): a finding rests on a no alone. bounds, the position's +// and its chain's, word the finding (refusal). +func (s *valueSite) admitted(value *ir.Value, sh shape, bounds boundSets) string { + if why, apart := readApart(value, sh, s.ref.Target); apart { + return why + } + judged := *value + if sh == shapeText && value.Kind == ir.ValueSymbol { + judged.Kind = ir.ValueString // a symbol at a text position is judged as the text it holds + } + ref := s.ref + ref.Nullable = ref.Nullable || s.typeLevel + if s.chains.unjudged != nil { + return "" // past the run's judgments, no value is judged + } + admission, spent, ok := s.chains.admission.AdmitsAtPositionWithin(ref, s.own, judged, s.chains.judgments) + s.chains.judgments -= spent + if !ok { + s.chains.unjudged = new(s.unjudgedFinding()) + return "" + } + if admission != ir.AdmitsNo { + return "" + } + return refusal(&judged, sh, s.ref.Target, bounds) +} + +// unjudgedFinding is the error the site's value draws where the run's value +// admission reader has no judgment left for it (maxValueJudgments): it and +// every value after it go unjudged. +func (s *valueSite) unjudgedFinding() ir.Diagnostic { + from := s.from + from.Node = s.node + return ir.NewDiagnostic(ir.SeverityError, "pass/budget-exceeded", fmt.Sprintf( + "the defaults and examples judged against their types took more than %d judgments of a type against "+ + "a value; this value and every one after it go unjudged", maxValueJudgments), from) +} + +// readApart returns pass's own answer for value at a position of shape sh +// typed target, where pass and the value admission reader read the value apart +// and which reading holds is not settled, and false for any other value. At +// bytes a string, which an encoding writes, is not measured; a number no +// Decimal holds is irverify's. +func readApart(value *ir.Value, sh shape, target ir.TypeID) (string, bool) { + switch { + case sh == shapeBytes && value.Kind != ir.ValueBytes: + if admits(sh, value.Kind) { + return "", true } + return "is " + kindWords(value.Kind) + ", and " + string(target) + " holds " + shapeWords(sh), true + case (sh == shapeNumber || sh == shapeInteger) && value.Kind == ir.ValueNumber: + _, err := value.Number.Decimal() + return "", err != nil + default: + return "", false } - if outside(value, sh, b) { +} + +// refusal words why the reader refused value at a position typed target, of +// shape sh. +func refusal(value *ir.Value, sh shape, target ir.TypeID, bounds boundSets) string { + switch { + case sh != shapeNotChecked && value.Kind != ir.ValueNull && !admits(sh, value.Kind): + return "is " + kindWords(value.Kind) + ", and " + string(target) + " holds " + shapeWords(sh) + case sh == shapeInteger && fraction(value): + return "is no integer, and " + string(target) + " holds one" + case bounds.refuse(value): return "lies outside the bounds declared for it" + default: + return "is no value " + string(target) + " admits" + } +} + +// fraction reports whether value, a number, is shown to be no whole one. +func fraction(value *ir.Value) bool { + decimal, err := value.Number.Decimal() + return err == nil && !decimal.IsInt() +} + +// enumRefusal returns why value is no value of enum, the type the site names, +// or "" where it is one (docs/ir/enums.md#bounds): a member it lists or a +// value an open enum takes, as the reader judges it (admitted). A flags enum, +// which may combine members, and a value written in an encoding are not judged +// further. Null is a member only where the site's reference admits it. +func (s *valueSite) enumRefusal(enum *ir.Enum, value *ir.Value, encoded bool, bounds boundSets) string { + nullOK := s.ref.Nullable || s.typeLevel + listed := slices.ContainsFunc(enum.Members, func(enumMember ir.EnumMember) bool { return same(&enumMember.Value, value) }) + switch { + case value.Kind == ir.ValueNull && nullOK: + return "" + case !listed && (enum.Closed || value.Kind == ir.ValueNull): + return "is not a member of enum " + string(s.ref.Target) + case !listed && enum.Flags, s.encoded || encoded: + return "" + default: + return s.admitted(value, primitiveShape(enum.ValueType), bounds) } - return "" } // admits reports whether a value of kind valueKind is one a type of shape sh @@ -244,7 +353,7 @@ func shapeWords(sh shape) string { } // kindWords says what a value of kind valueKind is. Null and the two kinds that -// stand for another value are judged before it is asked, and are named by their +// name another value are judged before it is asked, and are named by their // kind. func kindWords(valueKind ir.ValueKind) string { switch valueKind { @@ -273,38 +382,6 @@ func kindWords(valueKind ir.ValueKind) string { } } -// outside reports whether value, a value its shape admits, lies outside the -// bounds b holds: a number beyond an end, a string, bytes, list or object of a -// count beyond a limit. A string for bytes is not measured. -func outside(value *ir.Value, sh shape, b *bounds) bool { - switch { - case sh == shapeText: - return beyond(int64(utf8.RuneCountInString(value.String)), b.minLen, b.maxLen) - case sh == shapeBytes && value.Kind == ir.ValueBytes: - return beyond(int64(len(value.Bytes)), b.minLen, b.maxLen) - case sh == shapeList: - return beyond(int64(len(value.List)), b.minItems, b.maxItems) - case sh == shapeObject: - return beyond(int64(len(value.Object)), b.minProperties, b.maxProperties) - case (sh == shapeNumber || sh == shapeInteger) && value.Kind == ir.ValueNumber: - decimal, err := value.Number.Decimal() - return err == nil && ((b.loSet && below(decimal.Cmp(b.lo), b.loOpen)) || (b.hiSet && below(-decimal.Cmp(b.hi), b.hiOpen))) - default: - return false - } -} - -// below reports whether a number whose comparison with an end of the range is c, -// negative when it lies on the wrong side, is outside it: equal counts where -// the end is open. -func below(c int, open bool) bool { return c < 0 || (c == 0 && open) } - -// beyond reports whether n is under the minimum or over the maximum, either of -// which may be unset. -func beyond(n int64, minimum, maximum *int64) bool { - return (minimum != nil && n < *minimum) || (maximum != nil && n > *maximum) -} - // same reports whether two values are the same one, as an enum member is a // value of the type: two numbers by value, a string and a symbol by their text, // bytes by content, two of one other kind alike (a container's contents are not diff --git a/pass/validate_values_test.go b/pass/validate_values_test.go index 46b8fb5e0..d4c425373 100644 --- a/pass/validate_values_test.go +++ b/pass/validate_values_test.go @@ -17,10 +17,10 @@ const ( ) // number is the number s, as written. -func number(s string) *ir.Value { return &ir.Value{Kind: ir.ValueNumber, Number: ir.BigVal(s)} } +func number(text string) *ir.Value { return &ir.Value{Kind: ir.ValueNumber, Number: ir.BigVal(text)} } // text is the string s. -func text(s string) *ir.Value { return &ir.Value{Kind: ir.ValueString, String: s} } +func text(text string) *ir.Value { return &ir.Value{Kind: ir.ValueString, String: text} } // null is the value null. func null() *ir.Value { return &ir.Value{Kind: ir.ValueNull} } @@ -43,22 +43,25 @@ func exampled(vs ...*ir.Value) func(*ir.Property) { // type of the position it sits at: its kind, an enum's members, a literal's // value, null where the position admits none, the whole numbers of an integer // and the bounds declared at the position. Each row is followed by the -// nearest default that is admitted, and so are the positions the check leaves -// alone: one encoded by its type or by the property, a union, and a reference -// to a constant. +// nearest default that is admitted, and so are a union one of whose variants +// admits it and the positions the check leaves alone: one encoded by its type +// or by the property, and a reference to a constant. A type whose encoding +// names no scheme encodes nothing, so a default of it is judged. func TestValidate_ADefaultItsTypeDoesNotAdmitIsReported(t *testing.T) { t.Parallel() - enum := &ir.Enum{ID: "type/e", ValueType: ir.PrimitiveString, Members: []ir.EnumMember{ + enum := &ir.Enum{ID: "type/e", ValueType: ir.PrimitiveString, Closed: true, Members: []ir.EnumMember{ {ID: "enum-member/red", Value: *text("red")}, {ID: "enum-member/green", Value: *text("green")}, }} literal := &ir.Literal{ID: "type/four", Value: *number("4")} list := &ir.List{ID: "type/l", ElementType: stringT} decimal := &ir.Scalar{ID: "type/dec", Base: &ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveDecimal)}, Encoding: &ir.Encoding{Name: "string"}} + described := &ir.Scalar{ID: "type/described", Base: &ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveDecimal)}, + Encoding: &ir.Encoding{MediaType: "text/plain"}} union := &ir.Union{ID: "type/u", Variants: []ir.Variant{{Type: intT}, {Type: stringT}}} at := func(set func(*ir.Property), typ ir.TypeRef) *ir.Document { doc := modelOf(property("property/a/c", typ, set)) - for _, td := range []ir.TypeDef{enum, literal, list, decimal, union} { - doc.Types[td.Common().ID] = td + for _, typeDef := range []ir.TypeDef{enum, literal, list, decimal, described, union} { + doc.Types[typeDef.Common().ID] = typeDef } return doc } @@ -111,6 +114,8 @@ func TestValidate_ADefaultItsTypeDoesNotAdmitIsReported(t *testing.T) { }, ir.TypeRef{Target: "type/l"}), nil}, {"a string for an encoded decimal", at(defaulted(text("1.5")), ir.TypeRef{Target: "type/dec"}), nil}, + {"a string for a decimal whose encoding names no scheme", at(defaulted(text("1.5")), ir.TypeRef{Target: "type/described"}), + want("is a string, and type/described holds a number")}, {"a string for an integer the property encodes", at(func(property *ir.Property) { property.Default = text("5") property.Encoding = &ir.Encoding{Name: "string"} @@ -128,6 +133,61 @@ func TestValidate_ADefaultItsTypeDoesNotAdmitIsReported(t *testing.T) { } } +// TestValidate_APositionsValueIsJudgedByItsTypeAndItsOwnBounds holds a +// default to what the value admission reader reads of its position, the type +// and the bounds declared beside it: a fixed-width integer's range, a date's +// grammar, a step, distinct items, a list's elements and a minimum, each +// beside the nearest value admitted. +func TestValidate_APositionsValueIsJudgedByItsTypeAndItsOwnBounds(t *testing.T) { + t.Parallel() + int32T := ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveInt32)} + dateT := ir.TypeRef{Target: ir.PrimitiveTypeID(ir.PrimitiveDate)} + integers := &ir.List{ID: "type/ints", ElementType: intT} + list := func(values ...*ir.Value) *ir.Value { + listed := &ir.Value{Kind: ir.ValueList} + for _, value := range values { + listed.List = append(listed.List, *value) + } + return listed + } + at := func(typ ir.TypeRef, value *ir.Value, own *ir.Constraints) *ir.Document { + doc := modelOf(property("property/a/c", typ, func(property *ir.Property) { property.Default, property.Constraints = value, own })) + for _, typeDef := range []ir.TypeDef{integers, + &ir.Primitive{ID: int32T.Target, PrimitiveKind: ir.PrimitiveInt32}, &ir.Primitive{ID: dateT.Target, PrimitiveKind: ir.PrimitiveDate}} { + doc.Types[typeDef.Common().ID] = typeDef + } + return doc + } + ints := ir.TypeRef{Target: "type/ints"} + want := func(message string) []finding { return []finding{{"property/a/c", "default " + message}} } + for _, tc := range []struct { + name string + doc *ir.Document + want []finding + }{ + {"an int32 past its range", at(int32T, number("3000000000"), nil), want("is no value type/primitive/int32 admits")}, + {"an int32 at its range's end", at(int32T, number("2147483647"), nil), nil}, + {"a value off the position's step", at(intT, number("3"), &ir.Constraints{MultipleOf: big("2")}), + want("lies outside the bounds declared for it")}, + {"a value on it", at(intT, number("4"), &ir.Constraints{MultipleOf: big("2")}), nil}, + {"a date its grammar refuses", at(dateT, text("2020-13-45"), nil), want("is no value type/primitive/date admits")}, + {"a date it admits", at(dateT, text("2020-12-31"), nil), nil}, + {"items the position holds distinct repeated", at(ints, list(number("1"), number("1")), &ir.Constraints{UniqueItems: true}), + want("lies outside the bounds declared for it")}, + {"distinct items", at(ints, list(number("1"), number("2")), &ir.Constraints{UniqueItems: true}), nil}, + {"an element of another kind", at(ints, list(text("a")), nil), want("is no value type/ints admits")}, + {"an element of its kind", at(ints, list(number("1")), nil), nil}, + {"a value below the position's minimum", at(intT, number("-1"), numeric("0", "", "", "")), + want("lies outside the bounds declared for it")}, + {"a value at it", at(intT, number("0"), numeric("0", "", "", "")), nil}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, found(t, tc.doc, defaultCode)) + }) + } +} + // TestValidate_AParametersDefaultIsHeldToItsType holds a parameter's default to // its type at the parameter, as a property's is held at the property. func TestValidate_AParametersDefaultIsHeldToItsType(t *testing.T) { diff --git a/rfc3339/doc.go b/rfc3339/doc.go new file mode 100644 index 000000000..bc028a77c --- /dev/null +++ b/rfc3339/doc.go @@ -0,0 +1,7 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +// Package rfc3339 reads the time and date-time texts of RFC 3339 §5.6 by +// their grammar, which time.Parse alone does not hold to. It knows no morphic +// concept, so ir and the packages above it share one reading. +package rfc3339 diff --git a/rfc3339/rfc3339.go b/rfc3339/rfc3339.go new file mode 100644 index 000000000..03ba1808d --- /dev/null +++ b/rfc3339/rfc3339.go @@ -0,0 +1,117 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package rfc3339 + +import ( + "strings" + "time" +) + +// Form names a text [Parses] reads. +type Form uint8 + +const ( + // PartialTime is a time of day with no offset, the partial-time + // production. + PartialTime Form = iota + // FullTime is a time of day with its offset, the full-time production. + FullTime + // LocalDateTime is a full-date, T and a partial-time: a date-time with no + // offset, which RFC 3339 names no production for. + LocalDateTime + // DateTime is a date-time with its offset, the date-time production. + DateTime +) + +// Parses reports whether text is the text form names: the grammar's shape +// first, since time.Parse accepts a comma fraction and an offset hour above +// 23, then time.Parse for the calendar and range. The T separator and the Z +// offset may be lower case, which time.Parse refuses, so both are upper-cased +// once the shape is known. A second of 60 is a leap second, which time.Parse +// refuses, so it is parsed as 59. With an offset it is admitted where the time +// in UTC is 23:59 (§5.7). Without one, an offset could put 23:59 at any +// minute, so it is admitted at each. +func Parses(text string, form Form) bool { + s := text + layout, clock := "15:04:05", s + if form == LocalDateTime || form == DateTime { + if len(s) < len("2006-01-02T") || s[10] != 'T' && s[10] != 't' { + return false + } + layout, clock = "2006-01-02T15:04:05", s[11:] + s = s[:10] + "T" + clock + } + offset := form == FullTime || form == DateTime + if !clockShape(clock, offset) { + return false + } + if offset { + layout += "Z07:00" + if last := len(s) - 1; s[last] == 'z' { + s = s[:last] + "Z" + } + } + sec := len(s) - len(clock) + len("15:04:") + leap := s[sec:sec+2] == "60" + if leap { + s = s[:sec] + "59" + s[sec+2:] + } + t, err := time.Parse(layout, s) + return err == nil && (!leap || !offset || t.UTC().Hour() == 23 && t.UTC().Minute() == 59) +} + +// clockShape reports whether s is hh:mm:ss and an optional fraction of a dot +// and at least one digit, then an offset where offset is set and nothing where +// it is not. +func clockShape(s string, offset bool) bool { + const clockLength = len("15:04:05") + if len(s) < clockLength || s[2] != ':' || s[5] != ':' { + return false + } + for _, i := range []int{0, 1, 3, 4, 6, 7} { + if !isDigit(s[i]) { + return false + } + } + rest := s[clockLength:] + if strings.HasPrefix(rest, ".") { + end := 1 + for end < len(rest) && isDigit(rest[end]) { + end++ + } + if end == 1 { + return false + } + rest = rest[end:] + } + if offset { + return isOffset(rest) + } + return rest == "" +} + +// isOffset reports whether s is Z, z or ±hh:mm with hh 00-23 and mm 00-59. +func isOffset(s string) bool { + if s == "Z" || s == "z" { + return true + } + if len(s) != len("+05:30") || s[0] != '+' && s[0] != '-' || s[3] != ':' { + return false + } + hour, hourRead := twoDigits(s[1:3]) + minute, minuteRead := twoDigits(s[4:6]) + return hourRead && minuteRead && hour <= 23 && minute <= 59 +} + +// twoDigits reads s, two bytes, as a number, and false when either is not a +// digit. +func twoDigits(s string) (int, bool) { + if !isDigit(s[0]) || !isDigit(s[1]) { + return 0, false + } + return int(s[0]-'0')*10 + int(s[1]-'0'), true +} + +// isDigit reports whether c is an ASCII decimal digit. +func isDigit(c byte) bool { return c >= '0' && c <= '9' } diff --git a/compilers/openapi/internal/merge/formats_internal_test.go b/rfc3339/rfc3339_internal_test.go similarity index 76% rename from compilers/openapi/internal/merge/formats_internal_test.go rename to rfc3339/rfc3339_internal_test.go index b5b50625f..4b2dc71e0 100644 --- a/compilers/openapi/internal/merge/formats_internal_test.go +++ b/rfc3339/rfc3339_internal_test.go @@ -1,7 +1,7 @@ // Copyright (c) 2026 dexpace. // Licensed under the MIT License. See LICENSE in the repository root for details. -package merge +package rfc3339 import ( "testing" @@ -10,9 +10,9 @@ import ( ) // TestIsOffset_ReadsTheGrammar pins the offset grammar on its own terms. A -// time format reaches it only through parsesRFC3339, whose time.Parse also -// refuses a non-digit offset, so no format test fails when isOffset reads a -// byte that is no digit as a number. +// text reaches it only through Parses, whose time.Parse also refuses a +// non-digit offset, so no test of Parses fails when isOffset reads a byte that +// is no digit as a number. func TestIsOffset_ReadsTheGrammar(t *testing.T) { t.Parallel() for offset, want := range map[string]bool{ diff --git a/rfc3339/rfc3339_test.go b/rfc3339/rfc3339_test.go new file mode 100644 index 000000000..4473ecad3 --- /dev/null +++ b/rfc3339/rfc3339_test.go @@ -0,0 +1,60 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package rfc3339_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/rfc3339" +) + +// TestParses_ReadsEachForm pins the four texts of RFC 3339 §5.6 Parses +// reads: a partial-time and a local date-time carry no offset, a full-time and +// a date-time carry one, and each refuses what the other spelling of its clock +// writes. A second of 60 is a leap second, admitted with an offset only where +// the time in UTC is 23:59 (§5.7). +func TestParses_ReadsEachForm(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + text string + form rfc3339.Form + want bool + }{ + {"a partial-time", "23:59:59", rfc3339.PartialTime, true}, + {"a partial-time with a fraction", "23:59:59.5", rfc3339.PartialTime, true}, + {"a partial-time with an offset", "23:59:59Z", rfc3339.PartialTime, false}, + {"a partial-time leap second at any minute", "12:34:60", rfc3339.PartialTime, true}, + {"a partial-time with a comma fraction", "23:59:59,5", rfc3339.PartialTime, false}, + {"a partial-time at hour 24", "24:00:00", rfc3339.PartialTime, false}, + {"a partial-time with a letter for a digit", "23:5a:59", rfc3339.PartialTime, false}, + {"a partial-time with a dot and no fraction", "23:59:59.", rfc3339.PartialTime, false}, + {"a full-time with a Z offset", "23:59:59Z", rfc3339.FullTime, true}, + {"a full-time with a lower case z", "23:59:59z", rfc3339.FullTime, true}, + {"a full-time with the widest offset", "23:59:59-23:59", rfc3339.FullTime, true}, + {"a full-time with no offset", "23:59:59", rfc3339.FullTime, false}, + {"a full-time offset with no colon", "23:59:59+0500", rfc3339.FullTime, false}, + {"a full-time offset hour of 24", "23:59:59+24:00", rfc3339.FullTime, false}, + {"a full-time offset with a letter", "23:59:59+0a:30", rfc3339.FullTime, false}, + {"a full-time leap second behind UTC", "15:59:60-08:00", rfc3339.FullTime, true}, + {"a full-time leap second at the wrong minute", "23:58:60Z", rfc3339.FullTime, false}, + {"a local date-time", "2024-02-29T23:59:59", rfc3339.LocalDateTime, true}, + {"a local date-time with a lower case t", "2024-02-29t23:59:59", rfc3339.LocalDateTime, true}, + {"a local date-time with an offset", "2024-02-29T23:59:59Z", rfc3339.LocalDateTime, false}, + {"a local date-time off the calendar", "2023-02-29T00:00:00", rfc3339.LocalDateTime, false}, + {"a local date-time with a space", "2024-01-01 00:00:00", rfc3339.LocalDateTime, false}, + {"a date-time", "2024-01-01T00:00:00.5Z", rfc3339.DateTime, true}, + {"a date-time in lower case", "2024-01-01t00:00:00z", rfc3339.DateTime, true}, + {"a date-time with no offset", "2024-01-01T00:00:00", rfc3339.DateTime, false}, + {"a date-time leap second", "2016-12-31T23:59:60Z", rfc3339.DateTime, true}, + {"a date-time leap second at the wrong hour", "2016-12-31T22:59:60Z", rfc3339.DateTime, false}, + {"a date-time with a comma fraction", "2024-01-01T00:00:00,5Z", rfc3339.DateTime, false}, + {"a date alone", "2024-01-01", rfc3339.DateTime, false}, + {"an empty text", "", rfc3339.FullTime, false}, + } { + assert.Equal(t, tc.want, rfc3339.Parses(tc.text, tc.form), "%s: %q", tc.name, tc.text) + } +} diff --git a/stronglyconnected/components.go b/stronglyconnected/components.go new file mode 100644 index 000000000..5cbe158b4 --- /dev/null +++ b/stronglyconnected/components.go @@ -0,0 +1,63 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package stronglyconnected + +// Components returns the strongly connected components of the graph whose +// vertex v has an edge to each vertex adjacency[v] names, every one of them +// below len(adjacency). A component comes after every one its edges reach, +// its members in the order the search met them. +func Components(adjacency [][]int) [][]int { + visitor := &adjacencyVisitor{adjacency: adjacency, members: make([]int, 0, len(adjacency)), + ends: make([]int, 0, len(adjacency))} + search := Search[int]{visitor: visitor, numbers: denseNumbers(make([]int, len(adjacency))), + met: make([]metVertex[int], 0, len(adjacency))} + for root := range adjacency { + search.From(root) + } + out := make([][]int, len(visitor.ends)) + start := 0 + for c, end := range visitor.ends { + out[c] = visitor.members[start:end:end] + start = end + } + return out +} + +// adjacencyVisitor keeps the closed components' members back to back, ends +// marking where each stops, so a search allocates per vertex, not per +// component. +type adjacencyVisitor struct { + adjacency [][]int + members []int + ends []int +} + +// Edge returns from's edge at index, every edge being one the search walks. +func (visitor *adjacencyVisitor) Edge(from, index int) (to int, follow, more bool) { + if index == len(visitor.adjacency[from]) { + return 0, false, false + } + return visitor.adjacency[from][index], true, true +} + +// LeaveVertex keeps nothing of a vertex left. +func (*adjacencyVisitor) LeaveVertex(int) {} + +// CloseComponent keeps members after the components closed before them. +func (visitor *adjacencyVisitor) CloseComponent(members []int) { + visitor.members = append(visitor.members, members...) + visitor.ends = append(visitor.ends, len(visitor.members)) +} + +// denseNumbers holds each vertex's number plus one, indexed by vertex, so a +// zero says the vertex is not met. +type denseNumbers []int + +// numberOf returns vertex's number, and false where it has none. +func (numbers denseNumbers) numberOf(vertex int) (int, bool) { + return numbers[vertex] - 1, numbers[vertex] != 0 +} + +// give records number as vertex's. +func (numbers denseNumbers) give(vertex, number int) { numbers[vertex] = number + 1 } diff --git a/stronglyconnected/components_test.go b/stronglyconnected/components_test.go new file mode 100644 index 000000000..e38600f94 --- /dev/null +++ b/stronglyconnected/components_test.go @@ -0,0 +1,151 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package stronglyconnected_test + +import ( + "math/rand/v2" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/dexpace/morphic/stronglyconnected" +) + +// TestComponents_CondensesASmallGraph pins one graph's components and their +// order: a two-vertex cycle is one component, a vertex with an edge to itself +// one of its own, each component closes after every one its edges reach, and +// each holds its members in the order the search met them. +func TestComponents_CondensesASmallGraph(t *testing.T) { + t.Parallel() + adjacency := [][]int{ + 0: {1}, + 1: {2}, + 2: {1, 3}, + 3: {3}, + 4: {0, 3}, + } + + assert.Equal(t, [][]int{{3}, {1, 2}, {0}, {4}}, stronglyconnected.Components(adjacency)) +} + +// TestComponents_CondensesNoGraph pins the empty graph, which has no +// component. +func TestComponents_CondensesNoGraph(t *testing.T) { + t.Parallel() + assert.Empty(t, stronglyconnected.Components(nil)) +} + +// TestComponents_HoldsToMutualReach holds the components to their definition on +// random graphs: two vertices share a component exactly where each reaches the +// other, and a component closes after every other one an edge leads to. +func TestComponents_HoldsToMutualReach(t *testing.T) { + t.Parallel() + var shared int + for seed := range uint64(300) { + rng := rand.New(rand.NewPCG(seed, seed+7)) + adjacency := randomGraph(rng, 1+rng.IntN(20)) + + components := stronglyconnected.Components(adjacency) + + at := componentOf(t, len(adjacency), components) + reach := closure(adjacency) + for a := range adjacency { + for _, b := range adjacency[a] { + assert.LessOrEqual(t, at[b], at[a], "seed %d: %d leads to %d, whose component closes first", seed, a, b) + } + for b := range adjacency { + mutual := a == b || reach[a][b] && reach[b][a] + require.Equal(t, mutual, at[a] == at[b], "seed %d: %d and %d", seed, a, b) + if mutual && a != b { + shared++ + } + } + } + } + require.Positive(t, shared, "no random graph held a cycle of two vertices") +} + +// TestComponents_CondensesADeepGraph pins the explicit stacks: a cycle and a +// chain each a million vertices long are condensed without exhausting the +// goroutine stack. +func TestComponents_CondensesADeepGraph(t *testing.T) { + t.Parallel() + const n = 1_000_000 + cycle, chain := make([][]int, n), make([][]int, n) + for v := range n { + cycle[v] = []int{(v + 1) % n} + if v+1 < n { + chain[v] = []int{v + 1} + } + } + + assert.Len(t, stronglyconnected.Components(cycle), 1, "a cycle is one component") + assert.Len(t, stronglyconnected.Components(chain), n, "a chain is a component a vertex") +} + +// TestComponents_AllocatesPerVertexNotPerComponent holds the components to one +// backing array: a graph of a thousand components costs no more allocations +// than one of the same size holding a single component. It is not run in +// parallel: AllocsPerRun measures the process. +func TestComponents_AllocatesPerVertexNotPerComponent(t *testing.T) { + const n = 1000 + cycle, singles := make([][]int, n), make([][]int, n) + for v := range n { + cycle[v] = []int{(v + 1) % n} + singles[v] = []int{v} + } + one := testing.AllocsPerRun(5, func() { _ = stronglyconnected.Components(cycle) }) + many := testing.AllocsPerRun(5, func() { _ = stronglyconnected.Components(singles) }) + + assert.LessOrEqual(t, many, one+16, "a thousand components against one: %v allocations against %v", many, one) +} + +// randomGraph returns a graph of n vertices, each with up to three edges to +// vertices rng picks, itself among them. +func randomGraph(rng *rand.Rand, n int) [][]int { + adjacency := make([][]int, n) + for v := range adjacency { + for range rng.IntN(4) { + adjacency[v] = append(adjacency[v], rng.IntN(n)) + } + } + return adjacency +} + +// componentOf returns the index of each vertex's component, requiring each of +// the n vertices in exactly one. +func componentOf(t *testing.T, n int, components [][]int) []int { + t.Helper() + at := slices.Repeat([]int{-1}, n) + for c, members := range components { + for _, v := range members { + require.Equal(t, -1, at[v], "vertex %d in two components", v) + at[v] = c + } + } + require.NotContains(t, at, -1, "a vertex in no component") + return at +} + +// closure returns, for each pair of vertices, whether a path of one edge or +// more leads from the first to the second, by Floyd and Warshall's closure. +func closure(adjacency [][]int) [][]bool { + reach := make([][]bool, len(adjacency)) + for v, out := range adjacency { + reach[v] = make([]bool, len(adjacency)) + for _, w := range out { + reach[v][w] = true + } + } + for k := range adjacency { + for i := range adjacency { + for j := range adjacency { + reach[i][j] = reach[i][j] || reach[i][k] && reach[k][j] + } + } + } + return reach +} diff --git a/stronglyconnected/doc.go b/stronglyconnected/doc.go new file mode 100644 index 000000000..e153e2dbc --- /dev/null +++ b/stronglyconnected/doc.go @@ -0,0 +1,11 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +// Package stronglyconnected finds the strongly connected components of a +// directed graph by Tarjan's algorithm, on stacks of its own rather than by +// recursion, so a graph as deep as it is large exhausts no goroutine stack. +// Components condenses a graph given whole as adjacency lists; a Search reads +// one edge at a time and tells its Visitor of each vertex it leaves and each +// component it closes. It knows no morphic concept, so every package that +// condenses a graph shares it. +package stronglyconnected diff --git a/stronglyconnected/search.go b/stronglyconnected/search.go new file mode 100644 index 000000000..9db0d9a28 --- /dev/null +++ b/stronglyconnected/search.go @@ -0,0 +1,151 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package stronglyconnected + +// Visitor is what a Search reads of a directed graph and tells of it. +type Visitor[V comparable] interface { + // Edge returns the vertex from's edge at index leads to, follow false where + // it leads to none the search walks, and more false past from's last edge. + // A search asks for each of from's indices once, in order, up to and + // including the first past its last edge. + Edge(from V, index int) (to V, follow, more bool) + // LeaveVertex is told each vertex once the search has followed all its + // edges. + LeaveVertex(vertex V) + // CloseComponent is told each component as it closes, after every + // component its edges reach and after its last member is left, with its + // members in the order met. The search reuses the slice, so a visitor + // copies what it keeps. + CloseComponent(members []V) +} + +// Search walks the graph its Visitor reads from each root it is handed, +// meeting a vertex once across every walk. It is not safe for concurrent use, +// and its zero value is not ready: NewSearch returns one. +type Search[V comparable] struct { + visitor Visitor[V] + numbers vertexNumbers[V] + // met holds each vertex met, indexed by its number. + met []metVertex[V] + // stack holds the numbers of the vertices met whose component has not + // closed, in the order met. + stack []int + // path is the depth-first path, innermost last. + path []pathStep + // members is the scratch a closing component's vertices are read into. + members []V +} + +// metVertex is a vertex the search has met. Its low link is the least number +// on the stack that it reaches through its edges or those of the vertices it +// opened. +type metVertex[V comparable] struct { + vertex V + low int + onStack bool +} + +// pathStep is one vertex on the depth-first path, by its number, and the index +// of the next of its edges to follow. +type pathStep struct { + number int + next int +} + +// vertexNumbers is how a search finds the number it gave a vertex. +type vertexNumbers[V comparable] interface { + numberOf(vertex V) (int, bool) + give(vertex V, number int) +} + +// NewSearch returns a search over the graph visitor reads. +func NewSearch[V comparable](visitor Visitor[V]) *Search[V] { + return &Search[V]{visitor: visitor, numbers: mapNumbers[V]{}} +} + +// From walks every vertex root reaches that no earlier walk met, following +// each edge once. +func (s *Search[V]) From(root V) { + if _, met := s.numbers.numberOf(root); met { + return + } + s.open(root) + for len(s.path) > 0 { + top := &s.path[len(s.path)-1] + from := top.number + to, follow, more := s.visitor.Edge(s.met[from].vertex, top.next) + if !more { + s.leave() + continue + } + top.next++ + if follow { + s.follow(from, to) + } + } +} + +// follow takes the edge from the vertex numbered from to to. A vertex met but +// off the stack is in a closed component and changes nothing. +func (s *Search[V]) follow(from int, to V) { + number, met := s.numbers.numberOf(to) + switch { + case !met: + s.open(to) + case s.met[number].onStack: + s.met[from].low = min(s.met[from].low, number) + } +} + +// open gives vertex the next number and pushes it on the path and the stack. +func (s *Search[V]) open(vertex V) { + number := len(s.met) + s.numbers.give(vertex, number) + s.met = append(s.met, metVertex[V]{vertex: vertex, low: number, onStack: true}) + s.stack = append(s.stack, number) + s.path = append(s.path, pathStep{number: number}) +} + +// leave takes the innermost vertex off the path once its edges are followed, +// closing its component where it is the component's first vertex met. +func (s *Search[V]) leave() { + number := s.path[len(s.path)-1].number + s.path = s.path[:len(s.path)-1] + s.visitor.LeaveVertex(s.met[number].vertex) + if s.met[number].low == number { + s.closeComponent(number) + } + if len(s.path) > 0 { + parent := s.path[len(s.path)-1].number + s.met[parent].low = min(s.met[parent].low, s.met[number].low) + } +} + +// closeComponent pops root and every vertex above it off the stack as one +// component and tells the visitor of it. +func (s *Search[V]) closeComponent(root int) { + at := len(s.stack) - 1 + for s.stack[at] != root { + at-- + } + s.members = s.members[:0] + for _, number := range s.stack[at:] { + s.met[number].onStack = false + s.members = append(s.members, s.met[number].vertex) + } + s.stack = s.stack[:at] + s.visitor.CloseComponent(s.members) +} + +// mapNumbers finds the number of any comparable vertex by a map. +type mapNumbers[V comparable] map[V]int + +// numberOf returns vertex's number, and false where it has none. +func (numbers mapNumbers[V]) numberOf(vertex V) (int, bool) { + number, met := numbers[vertex] + return number, met +} + +// give records number as vertex's. +func (numbers mapNumbers[V]) give(vertex V, number int) { numbers[vertex] = number } diff --git a/stronglyconnected/search_test.go b/stronglyconnected/search_test.go new file mode 100644 index 000000000..8c6270dd7 --- /dev/null +++ b/stronglyconnected/search_test.go @@ -0,0 +1,103 @@ +// Copyright (c) 2026 dexpace. +// Licensed under the MIT License. See LICENSE in the repository root for details. + +package stronglyconnected_test + +import ( + "fmt" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/dexpace/morphic/stronglyconnected" +) + +// recordingVisitor reads a graph of named vertices whose edges may lead to a +// name it holds no edges for, which the search does not walk, and records +// every call a search makes. +type recordingVisitor struct { + edges map[string][]string + asked []string + left []string + closed [][]string +} + +// Edge returns from's edge at index, followed where it leads to a vertex the +// visitor holds. +func (visitor *recordingVisitor) Edge(from string, index int) (to string, follow, more bool) { + visitor.asked = append(visitor.asked, fmt.Sprintf("%s/%d", from, index)) + if index == len(visitor.edges[from]) { + return "", false, false + } + to = visitor.edges[from][index] + _, follow = visitor.edges[to] + return to, follow, true +} + +// LeaveVertex records vertex as left. +func (visitor *recordingVisitor) LeaveVertex(vertex string) { + visitor.left = append(visitor.left, vertex) +} + +// CloseComponent records a copy of members. +func (visitor *recordingVisitor) CloseComponent(members []string) { + visitor.closed = append(visitor.closed, slices.Clone(members)) +} + +// TestSearch_ReadsEachEdgeOnceInOrder pins what a search asks of its visitor: +// each index of each vertex it meets once, in order, up to the first past the +// last edge, none of a vertex an edge leads to that the visitor says is not +// followed, and none of a vertex met already. +func TestSearch_ReadsEachEdgeOnceInOrder(t *testing.T) { + t.Parallel() + visitor := &recordingVisitor{edges: map[string][]string{ + "a": {"b", "outside", "c"}, + "b": {"a"}, + "c": {"b"}, + }} + + stronglyconnected.NewSearch[string](visitor).From("a") + + assert.Equal(t, []string{"a/0", "b/0", "b/1", "a/1", "a/2", "c/0", "c/1", "a/3"}, visitor.asked) +} + +// TestSearch_TellsEachVertexLeftAndEachComponentClosed pins the order of what a +// search tells: each vertex as it leaves it, in post-order, which a component's +// members are not in, and each component once its first vertex met is left, +// after every component its edges reach, its members in the order met. +func TestSearch_TellsEachVertexLeftAndEachComponentClosed(t *testing.T) { + t.Parallel() + visitor := &recordingVisitor{edges: map[string][]string{ + "a": {"b"}, + "b": {"c", "d"}, + "c": {"a"}, + "d": {"d"}, + }} + + stronglyconnected.NewSearch[string](visitor).From("a") + + assert.Equal(t, []string{"c", "d", "b", "a"}, visitor.left) + assert.Equal(t, [][]string{{"d"}, {"a", "b", "c"}}, visitor.closed) +} + +// TestSearch_WalksFromEachRootOnce pins a search's memory across walks: a root +// met by an earlier walk is skipped, and a later walk meets only what no +// earlier one did, an edge to a vertex an earlier walk closed leading nowhere +// new. +func TestSearch_WalksFromEachRootOnce(t *testing.T) { + t.Parallel() + visitor := &recordingVisitor{edges: map[string][]string{ + "a": {"b"}, + "b": {}, + "c": {"a", "c"}, + }} + search := stronglyconnected.NewSearch[string](visitor) + + search.From("a") + search.From("b") + search.From("c") + + assert.Equal(t, [][]string{{"b"}, {"a"}, {"c"}}, visitor.closed) + assert.Equal(t, []string{"a/0", "b/0", "a/1", "c/0", "c/1", "c/2"}, visitor.asked) +} diff --git a/testdata/conformance/openapi/allof-boolean-branch.golden.json b/testdata/conformance/openapi/allof-boolean-branch.golden.json index f23a981cc..3096d10fb 100644 --- a/testdata/conformance/openapi/allof-boolean-branch.golden.json +++ b/testdata/conformance/openapi/allof-boolean-branch.golden.json @@ -239,6 +239,15 @@ } }, "diagnostics": [ + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies every allOf entry (allOf/0: no value, allOf/1: object); lowered as a node of kind \"model\" — remove or correct one entry", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Never" + } + }, { "severity": "info", "code": "openapi/false-schema", diff --git a/testdata/conformance/openapi/allof-conflicting-type.golden.json b/testdata/conformance/openapi/allof-conflicting-type.golden.json index 791e08954..39845b3c9 100644 --- a/testdata/conformance/openapi/allof-conflicting-type.golden.json +++ b/testdata/conformance/openapi/allof-conflicting-type.golden.json @@ -402,59 +402,144 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "declarations of field \"id\" give its default differently; kept the one the declaration at /components/schemas/Described/allOf/1/properties/id gives over the one at /components/schemas/Described/allOf/0/properties/id, which is kept verbatim under Unmodeled", + "message": "field \"id\" of /components/schemas/Described: /components/schemas/Described/allOf/1/properties/id and /components/schemas/Described/allOf/0/properties/id give its default differently; chose the one the first gives; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Described/allOf/0/properties/id" - } + }, + "related": [ + { + "role": "chosen", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/allOf/1/properties/id" + } + }, + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described", + "node": "property/openapi/components/schemas/Described/allOf/0/properties/id" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "declarations of field \"id\" give its examples differently; kept the one the declaration at /components/schemas/Described/allOf/1/properties/id gives over the one at /components/schemas/Described/allOf/0/properties/id, which is kept verbatim under Unmodeled", + "message": "field \"id\" of /components/schemas/Described: /components/schemas/Described/allOf/1/properties/id and /components/schemas/Described/allOf/0/properties/id give its examples differently; chose the one the first gives; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Described/allOf/0/properties/id" - } + }, + "related": [ + { + "role": "chosen", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/allOf/1/properties/id" + } + }, + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described", + "node": "property/openapi/components/schemas/Described/allOf/0/properties/id" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "declarations of field \"id\" give its title differently; kept the one the declaration at /components/schemas/Described/allOf/1/properties/id gives over the one at /components/schemas/Described/allOf/0/properties/id, which is kept verbatim under Unmodeled", + "message": "field \"id\" of /components/schemas/Described: /components/schemas/Described/allOf/1/properties/id and /components/schemas/Described/allOf/0/properties/id give its title differently; chose the one the first gives; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Described/allOf/0/properties/id" - } + }, + "related": [ + { + "role": "chosen", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/allOf/1/properties/id" + } + }, + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described", + "node": "property/openapi/components/schemas/Described/allOf/0/properties/id" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "declarations of field \"id\" give its description differently; kept the one the declaration at /components/schemas/Described/allOf/1/properties/id gives over the one at /components/schemas/Described/allOf/0/properties/id, which is kept verbatim under Unmodeled", + "message": "field \"id\" of /components/schemas/Described: /components/schemas/Described/allOf/1/properties/id and /components/schemas/Described/allOf/0/properties/id give its description differently; chose the one the first gives; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Described/allOf/0/properties/id" - } + }, + "related": [ + { + "role": "chosen", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/allOf/1/properties/id" + } + }, + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described", + "node": "property/openapi/components/schemas/Described/allOf/0/properties/id" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "declarations of field \"id\" give its external docs differently; kept the one the declaration at /components/schemas/Described/allOf/1/properties/id gives over the one at /components/schemas/Described/allOf/0/properties/id, which is kept verbatim under Unmodeled", + "message": "field \"id\" of /components/schemas/Described: /components/schemas/Described/allOf/1/properties/id and /components/schemas/Described/allOf/0/properties/id give its external docs differently; chose the one the first gives; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Described/allOf/0/properties/id" - } + }, + "related": [ + { + "role": "chosen", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/allOf/1/properties/id" + } + }, + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described", + "node": "property/openapi/components/schemas/Described/allOf/0/properties/id" + } + } + ] }, { "severity": "warning", "code": "openapi/conflicting-redeclaration", - "message": "declarations of field \"id\" disagree: incompatible types type/primitive/string and type/primitive/integer; kept what the declaration at /components/schemas/Identified/allOf/1/properties/id says over the one at /components/schemas/Identified/allOf/0/properties/id, which is kept verbatim under Unmodeled", + "message": "field \"id\" of /components/schemas/Identified: /components/schemas/Identified/allOf/1/properties/id and /components/schemas/Identified/allOf/0/properties/id disagree: incompatible types string and integer; chose what the first says; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Identified/allOf/0/properties/id" }, "related": [ { - "role": "kept", + "role": "chosen", "provenance": { "source": 0, "pointer": "/components/schemas/Identified/allOf/1/properties/id" @@ -463,7 +548,8 @@ { "role": "decided", "provenance": { - "source": -1, + "source": 0, + "pointer": "/components/schemas/Identified", "node": "property/openapi/components/schemas/Identified/allOf/0/properties/id" } } @@ -472,23 +558,40 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "declarations of field \"n\" give types type/primitive/uint32 and type/primitive/int32 whose values overlap but that the merge does not narrow to one; kept the type the declaration at /components/schemas/Overlapping/allOf/1/properties/n gives over the one at /components/schemas/Overlapping/allOf/0/properties/n, which is kept verbatim under Unmodeled", + "message": "field \"n\" of /components/schemas/Overlapping: /components/schemas/Overlapping/allOf/1/properties/n and /components/schemas/Overlapping/allOf/0/properties/n give types uint32 and int32 whose values overlap but that the merge does not narrow to one; chose the type the first gives; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Overlapping/allOf/0/properties/n" - } + }, + "related": [ + { + "role": "chosen", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping/allOf/1/properties/n" + } + }, + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping", + "node": "property/openapi/components/schemas/Overlapping/allOf/0/properties/n" + } + } + ] }, { "severity": "warning", "code": "openapi/conflicting-redeclaration", - "message": "declarations of field \"clone_url\" disagree: incompatible types type/primitive/integer and type/primitive/url; kept what the declaration at /components/schemas/Repository/allOf/1/properties/clone_url says over the one at /components/schemas/Repository/allOf/0/properties/clone_url, which is kept verbatim under Unmodeled", + "message": "field \"clone_url\" of /components/schemas/Repository: /components/schemas/Repository/allOf/1/properties/clone_url and /components/schemas/Repository/allOf/0/properties/clone_url disagree: incompatible types integer and url; chose what the first says; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Repository/allOf/0/properties/clone_url" }, "related": [ { - "role": "kept", + "role": "chosen", "provenance": { "source": 0, "pointer": "/components/schemas/Repository/allOf/1/properties/clone_url" @@ -497,7 +600,8 @@ { "role": "decided", "provenance": { - "source": -1, + "source": 0, + "pointer": "/components/schemas/Repository", "node": "property/openapi/components/schemas/Repository/allOf/0/properties/clone_url" } } diff --git a/testdata/conformance/openapi/allof-disjoint-conjuncts.golden.json b/testdata/conformance/openapi/allof-disjoint-conjuncts.golden.json index f5bc9b1d3..f30bc4728 100644 --- a/testdata/conformance/openapi/allof-disjoint-conjuncts.golden.json +++ b/testdata/conformance/openapi/allof-disjoint-conjuncts.golden.json @@ -70,12 +70,25 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:type": { + "openapi:$ref": { "reason": "degraded_lowering", - "value": "string", + "value": "#/components/schemas/Obj", + "targets": { + "": "type/openapi/components/schemas/Obj" + }, "provenance": { "source": 0, - "pointer": "/components/schemas/Inline/allOf/1/type" + "pointer": "/components/schemas/Inline/allOf/0" + } + }, + "openapi:allOf/1": { + "reason": "degraded_lowering", + "value": { + "type": "string" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Inline/allOf/1" } } }, @@ -83,10 +96,7 @@ "source": 0, "pointer": "/components/schemas/Inline" }, - "base": { - "target": "type/openapi/components/schemas/Obj", - "nullable": false - }, + "additional": "closed", "abstract": false, "positional": false, "inputOnly": false @@ -244,18 +254,27 @@ "source": 0, "pointer": "/components/schemas/OwnType/allOf/0" } + }, + "openapi:type": { + "reason": "degraded_lowering", + "value": "object", + "provenance": { + "source": 0, + "pointer": "/components/schemas/OwnType/type" + } } }, "provenance": { "source": 0, "pointer": "/components/schemas/OwnType" }, + "additional": "closed", "abstract": false, "positional": false, "inputOnly": false }, "type/openapi/components/schemas/SharedNull": { - "kind": "model", + "kind": "enum", "id": "type/openapi/components/schemas/SharedNull", "name": { "source": "SharedNull", @@ -265,7 +284,18 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:$ref": { + "openapi:$ref/0": { + "reason": "degraded_lowering", + "value": "#/components/schemas/NullableObj", + "targets": { + "": "type/openapi/components/schemas/NullableObj" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/SharedNull/allOf/1" + } + }, + "openapi:$ref/1": { "reason": "degraded_lowering", "value": "#/components/schemas/NullableStr", "targets": { @@ -281,13 +311,9 @@ "source": 0, "pointer": "/components/schemas/SharedNull" }, - "base": { - "target": "type/openapi/components/schemas/NullableObj", - "nullable": false - }, - "abstract": false, - "positional": false, - "inputOnly": false + "valueType": "any", + "closed": true, + "flags": false }, "type/openapi/components/schemas/Str": { "kind": "scalar", @@ -319,7 +345,18 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:$ref": { + "openapi:$ref/0": { + "reason": "degraded_lowering", + "value": "#/components/schemas/Obj", + "targets": { + "": "type/openapi/components/schemas/Obj" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/TwoRefs/allOf/1" + } + }, + "openapi:$ref/1": { "reason": "degraded_lowering", "value": "#/components/schemas/Str", "targets": { @@ -335,10 +372,7 @@ "source": 0, "pointer": "/components/schemas/TwoRefs" }, - "base": { - "target": "type/openapi/components/schemas/Obj", - "nullable": false - }, + "additional": "closed", "abstract": false, "positional": false, "inputOnly": false @@ -372,44 +406,26 @@ "diagnostics": [ { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (type: object, allOf/0: array), so no instance satisfies this schema, which a composition cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the type and every allOf entry (type: object, allOf/0: array); lowered as the closed model with no member a false schema lowers to — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/OwnType" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "the schema this $ref names is not an object alone, and a model composes only models, so the $ref is kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/OwnType/allOf/0" - } - }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (allOf/0: string, allOf/1: object), so no instance satisfies this schema, which a composition cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies every allOf entry (allOf/0: string, allOf/1: object); lowered as the closed model with no member a false schema lowers to — remove or correct one entry", "provenance": { "source": 0, "pointer": "/components/schemas/TwoRefs" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "the schema this $ref names is not an object alone, and a model composes only models, so the $ref is kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/TwoRefs/allOf/0" - } - }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (allOf/0: object, allOf/1: string), so no instance satisfies this schema, which a composition cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies every allOf entry (allOf/0: object, allOf/1: string); lowered as the closed model with no member a false schema lowers to — remove or correct one entry", "provenance": { "source": 0, "pointer": "/components/schemas/Inline" @@ -418,19 +434,19 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this allOf lowered to a node of kind \"model\", which has no home for type written on this inline entry; kept verbatim under Unmodeled", + "message": "the conjuncts of this allOf admit null alone together, so the position is the enum with no member a schema of null alone lowers to, a use of no target; the $ref is kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/Inline/allOf/1" + "pointer": "/components/schemas/SharedNull/allOf/0" } }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "the schema this $ref names is not an object alone, and a model composes only models, so the $ref is kept verbatim under Unmodeled", + "message": "the conjuncts of this allOf admit null alone together, so the position is the enum with no member a schema of null alone lowers to, a use of no target; the $ref is kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/SharedNull/allOf/0" + "pointer": "/components/schemas/SharedNull/allOf/1" } } ], @@ -438,7 +454,7 @@ { "format": "openapi@3.0", "path": "allof-disjoint-conjuncts.yaml", - "hash": "3f427829d58c4759ac8938e5eaddf24edf00e8a9d7855e9d5783c30de789978b" + "hash": "381c68bf6a83128ef8e1eceb6fa61d6cfebebc7be24aecac51b88766968463e7" } ] } diff --git a/testdata/conformance/openapi/allof-disjoint-conjuncts.yaml b/testdata/conformance/openapi/allof-disjoint-conjuncts.yaml index e5e7f0d65..ec5dcdad3 100644 --- a/testdata/conformance/openapi/allof-disjoint-conjuncts.yaml +++ b/testdata/conformance/openapi/allof-disjoint-conjuncts.yaml @@ -29,8 +29,9 @@ components: allOf: - {$ref: '#/components/schemas/Obj'} - {type: string} - # The control: both conjuncts admit null, which is a value they share, so - # nothing is reported. + # The control: both conjuncts admit null and nothing else together, so the + # position is the null type, each $ref kept with an info saying so, and no + # report says they share no value. SharedNull: allOf: - {$ref: '#/components/schemas/NullableStr'} diff --git a/testdata/conformance/openapi/allof-inheritance.golden.json b/testdata/conformance/openapi/allof-inheritance.golden.json index 144fa4cf9..ec3b19fb8 100644 --- a/testdata/conformance/openapi/allof-inheritance.golden.json +++ b/testdata/conformance/openapi/allof-inheritance.golden.json @@ -120,6 +120,14 @@ "sensitive": false, "deprecation": {}, "unmodeled": { + "openapi:additionalProperties": { + "reason": "degraded_lowering", + "value": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Derived/additionalProperties" + } + }, "openapi:x-team": { "reason": "vendor_extension", "value": "pets", @@ -317,6 +325,11 @@ "positional": false, "discriminator": { "property": "property/openapi/components/schemas/Root/properties/kind", + "mapping": { + "Leaf": "type/openapi/components/schemas/Leaf", + "Mid": "type/openapi/components/schemas/Mid", + "Root": "type/openapi/components/schemas/Root" + }, "inferred": false }, "inputOnly": false @@ -347,6 +360,17 @@ } } }, + "diagnostics": [ + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "additionalProperties also applies to id, which the composition brings and its own object does not declare; the model takes it as the closed subtype written, and it is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Derived/additionalProperties" + } + } + ], "sources": [ { "format": "openapi@3.1", diff --git a/testdata/conformance/openapi/allof-inline-residue.golden.json b/testdata/conformance/openapi/allof-inline-residue.golden.json index bb17c82bb..7349f9093 100644 --- a/testdata/conformance/openapi/allof-inline-residue.golden.json +++ b/testdata/conformance/openapi/allof-inline-residue.golden.json @@ -274,7 +274,7 @@ "inputOnly": false }, "type/openapi/components/schemas/Contradicted": { - "kind": "model", + "kind": "enum", "id": "type/openapi/components/schemas/Contradicted", "name": { "source": "Contradicted", @@ -284,36 +284,24 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:allOf/0": { + "openapi:maxLength": { "reason": "degraded_lowering", - "value": { - "properties": { - "id": { - "type": "string" - } - }, - "type": [ - "object", - "null" - ] - }, + "value": 3, "provenance": { "source": 0, - "pointer": "/components/schemas/Contradicted/allOf/0" + "pointer": "/components/schemas/Contradicted/allOf/1/maxLength" } }, - "openapi:allOf/1": { + "openapi:properties": { "reason": "degraded_lowering", "value": { - "maxLength": 3, - "type": [ - "string", - "null" - ] + "id": { + "type": "string" + } }, "provenance": { "source": 0, - "pointer": "/components/schemas/Contradicted/allOf/1" + "pointer": "/components/schemas/Contradicted/allOf/0/properties" } } }, @@ -321,38 +309,9 @@ "source": 0, "pointer": "/components/schemas/Contradicted" }, - "properties": [ - { - "id": "property/openapi/components/schemas/Contradicted/allOf/0/properties/id", - "name": { - "source": "id", - "canonical": "id" - }, - "wireName": "id", - "type": { - "target": "type/primitive/string", - "nullable": false - }, - "required": false, - "clientOptional": false, - "defaultAdded": false, - "visibility": { - "invisibleInEveryLifecycle": false - }, - "flatten": false, - "eventHeader": false, - "eventPayload": false, - "secret": false, - "docs": {}, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Contradicted/allOf/0/properties/id" - } - } - ], - "abstract": false, - "positional": false, - "inputOnly": false + "valueType": "any", + "closed": true, + "flags": false }, "type/openapi/components/schemas/Distributed": { "kind": "union", @@ -720,16 +679,16 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "another conjunct of this allOf writes a keyword this inline entry keeps otherwise, and one Unmodeled entry under that keyword holds one value; the entry (type) is kept verbatim under Unmodeled", + "message": "this allOf lowered to a node of kind \"enum\", which has no home for properties written on this inline entry; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Contradicted/allOf/0" } }, { - "severity": "warning", + "severity": "info", "code": "openapi/degraded-construct", - "message": "inline allOf entry declares a type that is not an object, which the composed model asserts it is; the entry (type, maxLength) is kept verbatim under Unmodeled", + "message": "this allOf lowered to a node of kind \"enum\", which has no home for maxLength written on this inline entry; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Contradicted/allOf/1" @@ -803,7 +762,7 @@ { "format": "openapi@3.1", "path": "allof-inline-residue.yaml", - "hash": "428d678354d3c1780b143894d314864474f4fd996dae47408ea9e2e841106e84" + "hash": "d664b59fee7e0a1b2322c701bbfa60d32118e57a40157ae3767a211220787449" } ] } diff --git a/testdata/conformance/openapi/allof-inline-residue.yaml b/testdata/conformance/openapi/allof-inline-residue.yaml index 6c82ea40f..ccf551ee0 100644 --- a/testdata/conformance/openapi/allof-inline-residue.yaml +++ b/testdata/conformance/openapi/allof-inline-residue.yaml @@ -20,12 +20,11 @@ components: unevaluatedProperties: false description: A narrowed base. maxProperties: 3 - # This entry declares a type that cannot be an object, which the composed - # model asserts it is — the same residue, reported one severity higher. The - # two entries share only null, a value, so allof-disjoint-conjuncts reports - # nothing; were they to share none it would report that once at the schema, - # leaving the entry an info. Beside an entry declaring no object the - # declared string decides, and the allOf is no composition (allof-refinement). + # This entry declares a type that cannot be an object, beside an entry the + # two share only null with: no model asserts an object, the position is the + # null type, and each entry keeps what the Enum has no field for, reported + # as an info at it; were they to share none allof-disjoint-conjuncts would + # report that once at the schema (allof-refinement). Contradicted: allOf: - type: [object, 'null'] diff --git a/testdata/conformance/openapi/allof-narrowing-redeclaration.golden.json b/testdata/conformance/openapi/allof-narrowing-redeclaration.golden.json index 4713ef8d8..ced81ff30 100644 --- a/testdata/conformance/openapi/allof-narrowing-redeclaration.golden.json +++ b/testdata/conformance/openapi/allof-narrowing-redeclaration.golden.json @@ -307,9 +307,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/AliasMeetsFirst/allOf/1/properties/p": { + "type/composed/components/schemas/AliasMeetsFirst/allOf/properties/p": { "kind": "enum", - "id": "type/composed/components/schemas/AliasMeetsFirst/allOf/1/properties/p", + "id": "type/composed/components/schemas/AliasMeetsFirst/allOf/properties/p", "name": { "hint": "p" }, @@ -320,12 +320,12 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/AliasMeetsFirst/allOf/1/properties/p" + "pointer": "/components/schemas/AliasMeetsFirst/allOf/properties/p" }, "valueType": "string", "members": [ { - "id": "enum-member/composed/components/schemas/AliasMeetsFirst/allOf/1/properties/p/string:b", + "id": "enum-member/composed/components/schemas/AliasMeetsFirst/allOf/properties/p/string:b", "name": { "source": "b", "canonical": "b" @@ -337,7 +337,7 @@ "docs": {} }, { - "id": "enum-member/composed/components/schemas/AliasMeetsFirst/allOf/1/properties/p/string:c", + "id": "enum-member/composed/components/schemas/AliasMeetsFirst/allOf/properties/p/string:c", "name": { "source": "c", "canonical": "c" @@ -352,9 +352,9 @@ "closed": true, "flags": false }, - "type/composed/components/schemas/AliasMeetsLast/allOf/1/properties/p": { + "type/composed/components/schemas/AliasMeetsLast/allOf/properties/p": { "kind": "enum", - "id": "type/composed/components/schemas/AliasMeetsLast/allOf/1/properties/p", + "id": "type/composed/components/schemas/AliasMeetsLast/allOf/properties/p", "name": { "hint": "p" }, @@ -365,12 +365,12 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/AliasMeetsLast/allOf/1/properties/p" + "pointer": "/components/schemas/AliasMeetsLast/allOf/properties/p" }, "valueType": "string", "members": [ { - "id": "enum-member/composed/components/schemas/AliasMeetsLast/allOf/1/properties/p/string:b", + "id": "enum-member/composed/components/schemas/AliasMeetsLast/allOf/properties/p/string:b", "name": { "source": "b", "canonical": "b" @@ -382,7 +382,7 @@ "docs": {} }, { - "id": "enum-member/composed/components/schemas/AliasMeetsLast/allOf/1/properties/p/string:c", + "id": "enum-member/composed/components/schemas/AliasMeetsLast/allOf/properties/p/string:c", "name": { "source": "c", "canonical": "c" @@ -397,9 +397,9 @@ "closed": true, "flags": false }, - "type/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p": { + "type/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p": { "kind": "list", - "id": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p", + "id": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p", "name": { "hint": "p" }, @@ -408,16 +408,16 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p" + "pointer": "/components/schemas/AliasedListMeetsFirst/allOf/properties/p" }, "elementType": { - "target": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p/items", + "target": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p/items", "nullable": false } }, - "type/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p/items": { + "type/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p/items": { "kind": "enum", - "id": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p/items", + "id": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p/items", "name": { "hint": "p_item" }, @@ -426,12 +426,12 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p/items" + "pointer": "/components/schemas/AliasedListMeetsFirst/allOf/properties/p/items" }, "valueType": "string", "members": [ { - "id": "enum-member/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p/items/string:b", + "id": "enum-member/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p/items/string:b", "name": { "source": "b", "canonical": "b" @@ -443,7 +443,7 @@ "docs": {} }, { - "id": "enum-member/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p/items/string:c", + "id": "enum-member/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p/items/string:c", "name": { "source": "c", "canonical": "c" @@ -458,9 +458,9 @@ "closed": true, "flags": false }, - "type/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p": { + "type/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p": { "kind": "list", - "id": "type/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p", + "id": "type/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p", "name": { "hint": "p" }, @@ -469,16 +469,16 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/AliasedListMeetsLast/allOf/1/properties/p" + "pointer": "/components/schemas/AliasedListMeetsLast/allOf/properties/p" }, "elementType": { - "target": "type/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p/items", + "target": "type/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p/items", "nullable": false } }, - "type/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p/items": { + "type/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p/items": { "kind": "enum", - "id": "type/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p/items", + "id": "type/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p/items", "name": { "hint": "p_item" }, @@ -487,12 +487,12 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/AliasedListMeetsLast/allOf/1/properties/p/items" + "pointer": "/components/schemas/AliasedListMeetsLast/allOf/properties/p/items" }, "valueType": "string", "members": [ { - "id": "enum-member/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p/items/string:b", + "id": "enum-member/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p/items/string:b", "name": { "source": "b", "canonical": "b" @@ -504,7 +504,7 @@ "docs": {} }, { - "id": "enum-member/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p/items/string:c", + "id": "enum-member/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p/items/string:c", "name": { "source": "c", "canonical": "c" @@ -519,9 +519,9 @@ "closed": true, "flags": false }, - "type/composed/components/schemas/EnumValueTypesMeet/allOf/1/properties/p": { + "type/composed/components/schemas/EnumValueTypesMeet/allOf/properties/p": { "kind": "enum", - "id": "type/composed/components/schemas/EnumValueTypesMeet/allOf/1/properties/p", + "id": "type/composed/components/schemas/EnumValueTypesMeet/allOf/properties/p", "name": { "hint": "p" }, @@ -530,12 +530,12 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/EnumValueTypesMeet/allOf/1/properties/p" + "pointer": "/components/schemas/EnumValueTypesMeet/allOf/properties/p" }, "valueType": "integer", "members": [ { - "id": "enum-member/composed/components/schemas/EnumValueTypesMeet/allOf/1/properties/p/number:1e0", + "id": "enum-member/composed/components/schemas/EnumValueTypesMeet/allOf/properties/p/number:1e0", "name": { "source": "1", "canonical": "1" @@ -550,9 +550,9 @@ "closed": true, "flags": false }, - "type/composed/components/schemas/EnumsMeet/allOf/1/properties/p": { + "type/composed/components/schemas/EnumsMeet/allOf/properties/p": { "kind": "enum", - "id": "type/composed/components/schemas/EnumsMeet/allOf/1/properties/p", + "id": "type/composed/components/schemas/EnumsMeet/allOf/properties/p", "name": { "hint": "p" }, @@ -561,12 +561,12 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/EnumsMeet/allOf/1/properties/p" + "pointer": "/components/schemas/EnumsMeet/allOf/properties/p" }, "valueType": "string", "members": [ { - "id": "enum-member/composed/components/schemas/EnumsMeet/allOf/1/properties/p/string:b", + "id": "enum-member/composed/components/schemas/EnumsMeet/allOf/properties/p/string:b", "name": { "source": "b", "canonical": "b" @@ -581,9 +581,9 @@ "closed": true, "flags": false }, - "type/composed/components/schemas/ListNarrowFirst/allOf/1/properties/p": { + "type/composed/components/schemas/ListNarrowFirst/allOf/properties/p": { "kind": "list", - "id": "type/composed/components/schemas/ListNarrowFirst/allOf/1/properties/p", + "id": "type/composed/components/schemas/ListNarrowFirst/allOf/properties/p", "name": { "hint": "p" }, @@ -594,16 +594,16 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/ListNarrowFirst/allOf/1/properties/p" + "pointer": "/components/schemas/ListNarrowFirst/allOf/properties/p" }, "elementType": { "target": "type/primitive/int32", "nullable": false } }, - "type/composed/components/schemas/ListWideFirst/allOf/1/properties/p": { + "type/composed/components/schemas/ListWideFirst/allOf/properties/p": { "kind": "list", - "id": "type/composed/components/schemas/ListWideFirst/allOf/1/properties/p", + "id": "type/composed/components/schemas/ListWideFirst/allOf/properties/p", "name": { "hint": "p" }, @@ -614,7 +614,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/ListWideFirst/allOf/1/properties/p" + "pointer": "/components/schemas/ListWideFirst/allOf/properties/p" }, "elementType": { "target": "type/primitive/int32", @@ -645,7 +645,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/AliasMeetsFirst/allOf/1/properties/p", + "target": "type/composed/components/schemas/AliasMeetsFirst/allOf/properties/p", "nullable": false }, "required": false, @@ -695,7 +695,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/AliasMeetsLast/allOf/1/properties/p", + "target": "type/composed/components/schemas/AliasMeetsLast/allOf/properties/p", "nullable": false }, "required": false, @@ -745,7 +745,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/1/properties/p", + "target": "type/composed/components/schemas/AliasedListMeetsFirst/allOf/properties/p", "nullable": false }, "required": false, @@ -793,7 +793,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/AliasedListMeetsLast/allOf/1/properties/p", + "target": "type/composed/components/schemas/AliasedListMeetsLast/allOf/properties/p", "nullable": false }, "required": false, @@ -1316,7 +1316,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/EnumValueTypesMeet/allOf/1/properties/p", + "target": "type/composed/components/schemas/EnumValueTypesMeet/allOf/properties/p", "nullable": false }, "required": false, @@ -1412,7 +1412,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/EnumsMeet/allOf/1/properties/p", + "target": "type/composed/components/schemas/EnumsMeet/allOf/properties/p", "nullable": false }, "required": false, @@ -1993,7 +1993,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/ListNarrowFirst/allOf/1/properties/p", + "target": "type/composed/components/schemas/ListNarrowFirst/allOf/properties/p", "nullable": false }, "required": false, @@ -2041,7 +2041,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/ListWideFirst/allOf/1/properties/p", + "target": "type/composed/components/schemas/ListWideFirst/allOf/properties/p", "nullable": false }, "required": false, @@ -2128,7 +2128,7 @@ }, "properties": [ { - "id": "property/composed/components/schemas/NarrowedPastARef/allOf/1/properties/p", + "id": "property/composed/components/schemas/NarrowedPastARef/allOf/properties/p", "name": { "source": "p", "canonical": "p" @@ -2151,7 +2151,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/NarrowedPastARef/allOf/1/properties/p" + "pointer": "/components/schemas/NarrowedPastARef/allOf/properties/p" } } ], @@ -3351,47 +3351,97 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"p\" merge to admits the default the declaration at /components/schemas/InadmissibleDefaultBroadFirst/allOf/0/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/InadmissibleDefaultBroadFirst: the merge cannot show that the type its declarations merge to admits the default /components/schemas/InadmissibleDefaultBroadFirst/allOf/0/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/InadmissibleDefaultBroadFirst/allOf/0/properties/p" - } + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/InadmissibleDefaultBroadFirst", + "node": "property/openapi/components/schemas/InadmissibleDefaultBroadFirst/allOf/0/properties/p" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"p\" merge to admits the default the declaration at /components/schemas/InadmissibleDefaultNarrowFirst/allOf/1/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/InadmissibleDefaultNarrowFirst: the merge cannot show that the type its declarations merge to admits the default /components/schemas/InadmissibleDefaultNarrowFirst/allOf/1/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/InadmissibleDefaultNarrowFirst/allOf/1/properties/p" - } + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/InadmissibleDefaultNarrowFirst", + "node": "property/openapi/components/schemas/InadmissibleDefaultNarrowFirst/allOf/0/properties/p" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"p\" merge to admits the default the declaration at /components/schemas/RefusedLateDefaultFirst/allOf/2/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/RefusedLateDefaultFirst: the merge cannot show that the type its declarations merge to admits the default /components/schemas/RefusedLateDefaultFirst/allOf/2/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/RefusedLateDefaultFirst/allOf/2/properties/p" - } + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/RefusedLateDefaultFirst", + "node": "property/openapi/components/schemas/RefusedLateDefaultFirst/allOf/0/properties/p" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"p\" merge to admits the default the declaration at /components/schemas/RefusedLateDefaultLast/allOf/1/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/RefusedLateDefaultLast: the merge cannot show that the type its declarations merge to admits the default /components/schemas/RefusedLateDefaultLast/allOf/1/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/RefusedLateDefaultLast/allOf/1/properties/p" - } + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/RefusedLateDefaultLast", + "node": "property/openapi/components/schemas/RefusedLateDefaultLast/allOf/0/properties/p" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"p\" merge to admits the default the declaration at /components/schemas/RefusedLateDefaultMiddle/allOf/2/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/RefusedLateDefaultMiddle: the merge cannot show that the type its declarations merge to admits the default /components/schemas/RefusedLateDefaultMiddle/allOf/2/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/RefusedLateDefaultMiddle/allOf/2/properties/p" - } + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/RefusedLateDefaultMiddle", + "node": "property/openapi/components/schemas/RefusedLateDefaultMiddle/allOf/0/properties/p" + } + } + ] } ], "sources": [ diff --git a/testdata/conformance/openapi/allof-nested-inline.golden.json b/testdata/conformance/openapi/allof-nested-inline.golden.json index 895f5ed8f..26135b081 100644 --- a/testdata/conformance/openapi/allof-nested-inline.golden.json +++ b/testdata/conformance/openapi/allof-nested-inline.golden.json @@ -328,6 +328,16 @@ "description": "grouped" }, "sensitive": false, + "unmodeled": { + "openapi:additionalProperties": { + "reason": "degraded_lowering", + "value": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/allOf/0/additionalProperties" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/Described" @@ -672,6 +682,15 @@ } }, "diagnostics": [ + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies every allOf entry (allOf/0/allOf/0: no value); lowered as a node of kind \"model\" — remove or correct one entry", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Closed" + } + }, { "severity": "info", "code": "openapi/false-schema", @@ -681,6 +700,15 @@ "pointer": "/components/schemas/Closed/allOf/0/allOf/0" } }, + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies every allOf entry (allOf/0/allOf/0: object, allOf/0/allOf/2/allOf/0: no value); lowered as a union of models conjoining its body with each branch — remove or correct one entry", + "provenance": { + "source": 0, + "pointer": "/components/schemas/U" + } + }, { "severity": "info", "code": "openapi/false-schema", @@ -698,13 +726,22 @@ "source": 0, "pointer": "/components/schemas/U" } + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "additionalProperties also applies to a, b, which the composition brings and its own object does not declare; the model takes it as the closed subtype written, and it is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/allOf/0/additionalProperties" + } } ], "sources": [ { "format": "openapi@3.1", "path": "allof-nested-inline.yaml", - "hash": "0a8e7c35fcf7ebfe717d0b6cf66edbb9eb888f48b6059aad4ce7f26c4d3d9945" + "hash": "db8eb1308c678e2f62fc4c0bbec1cf426306226bc658302fddd12ef101e5a9ec" } ] } diff --git a/testdata/conformance/openapi/allof-nested-inline.yaml b/testdata/conformance/openapi/allof-nested-inline.yaml index 7d9d9a59b..c9f6068d3 100644 --- a/testdata/conformance/openapi/allof-nested-inline.yaml +++ b/testdata/conformance/openapi/allof-nested-inline.yaml @@ -53,8 +53,9 @@ components: a: {type: string} - allOf: [false] # A wrapper that also writes a closure is flattened, so A and B are Mixins. - # No conjunct declares a member the closure would not read, so it closes - # the model, and its description folds: nothing of the wrapper is kept. + # The closure closes the model, and its description folds. It applies to + # a and b, which A and B bring and its own object does not declare, so it + # is also kept verbatim, with one info. Described: allOf: - additionalProperties: false diff --git a/testdata/conformance/openapi/allof-oneof-cooccurrence.golden.json b/testdata/conformance/openapi/allof-oneof-cooccurrence.golden.json index 8cc599a3c..a548c6757 100644 --- a/testdata/conformance/openapi/allof-oneof-cooccurrence.golden.json +++ b/testdata/conformance/openapi/allof-oneof-cooccurrence.golden.json @@ -773,7 +773,7 @@ }, { "severity": "warning", - "code": "openapi/degraded-construct", + "code": "openapi/unsatisfiable-schema", "message": "the body beside this oneOf admits objects alone, and 1 of its branches admits no object (oneOf/2: string), so no instance satisfies it: it is no variant of the union, kept verbatim under Unmodeled", "provenance": { "source": 0, @@ -797,6 +797,15 @@ "source": 0, "pointer": "/components/schemas/BoundedKinds" } + }, + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "1 of the 2 branches of this oneOf shares no value with the rest of the schema (oneOf/0: object), so no instance satisfies it: the oneOf is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/BoundedKinds/oneOf" + } } ], "sources": [ diff --git a/testdata/conformance/openapi/allof-redeclared-bounds.golden.json b/testdata/conformance/openapi/allof-redeclared-bounds.golden.json index 35f2fbfb7..1edbe0426 100644 --- a/testdata/conformance/openapi/allof-redeclared-bounds.golden.json +++ b/testdata/conformance/openapi/allof-redeclared-bounds.golden.json @@ -178,9 +178,9 @@ "uniqueItems": false } }, - "type/composed/components/schemas/BothListBoundsLowerFirst/allOf/1/properties/p": { + "type/composed/components/schemas/BothListBoundsLowerFirst/allOf/properties/p": { "kind": "list", - "id": "type/composed/components/schemas/BothListBoundsLowerFirst/allOf/1/properties/p", + "id": "type/composed/components/schemas/BothListBoundsLowerFirst/allOf/properties/p", "name": { "hint": "p" }, @@ -189,7 +189,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/BothListBoundsLowerFirst/allOf/1/properties/p" + "pointer": "/components/schemas/BothListBoundsLowerFirst/allOf/properties/p" }, "elementType": { "target": "type/primitive/string", @@ -201,9 +201,9 @@ "uniqueItems": false } }, - "type/composed/components/schemas/BothListBoundsUpperFirst/allOf/1/properties/p": { + "type/composed/components/schemas/BothListBoundsUpperFirst/allOf/properties/p": { "kind": "list", - "id": "type/composed/components/schemas/BothListBoundsUpperFirst/allOf/1/properties/p", + "id": "type/composed/components/schemas/BothListBoundsUpperFirst/allOf/properties/p", "name": { "hint": "p" }, @@ -212,7 +212,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/BothListBoundsUpperFirst/allOf/1/properties/p" + "pointer": "/components/schemas/BothListBoundsUpperFirst/allOf/properties/p" }, "elementType": { "target": "type/primitive/string", @@ -224,9 +224,9 @@ "uniqueItems": false } }, - "type/composed/components/schemas/BothMapBounds/allOf/1/properties/p": { + "type/composed/components/schemas/BothMapBounds/allOf/properties/p": { "kind": "map", - "id": "type/composed/components/schemas/BothMapBounds/allOf/1/properties/p", + "id": "type/composed/components/schemas/BothMapBounds/allOf/properties/p", "name": { "hint": "p" }, @@ -235,7 +235,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/BothMapBounds/allOf/1/properties/p" + "pointer": "/components/schemas/BothMapBounds/allOf/properties/p" }, "value": { "target": "type/primitive/string", @@ -247,9 +247,9 @@ "maxProperties": 5 } }, - "type/composed/components/schemas/BothScalarBounds/allOf/1/properties/p": { + "type/composed/components/schemas/BothScalarBounds/allOf/properties/p": { "kind": "scalar", - "id": "type/composed/components/schemas/BothScalarBounds/allOf/1/properties/p", + "id": "type/composed/components/schemas/BothScalarBounds/allOf/properties/p", "name": { "hint": "p" }, @@ -258,7 +258,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/BothScalarBounds/allOf/1/properties/p" + "pointer": "/components/schemas/BothScalarBounds/allOf/properties/p" }, "base": { "target": "type/primitive/string", @@ -273,9 +273,9 @@ "name": "x-custom" } }, - "type/composed/components/schemas/BothTupleBounds/allOf/1/properties/p": { + "type/composed/components/schemas/BothTupleBounds/allOf/properties/p": { "kind": "tuple", - "id": "type/composed/components/schemas/BothTupleBounds/allOf/1/properties/p", + "id": "type/composed/components/schemas/BothTupleBounds/allOf/properties/p", "name": { "hint": "p" }, @@ -284,7 +284,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/BothTupleBounds/allOf/1/properties/p" + "pointer": "/components/schemas/BothTupleBounds/allOf/properties/p" }, "elementTypes": [ { @@ -513,7 +513,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/BothListBoundsLowerFirst/allOf/1/properties/p", + "target": "type/composed/components/schemas/BothListBoundsLowerFirst/allOf/properties/p", "nullable": false }, "required": false, @@ -560,7 +560,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/BothListBoundsUpperFirst/allOf/1/properties/p", + "target": "type/composed/components/schemas/BothListBoundsUpperFirst/allOf/properties/p", "nullable": false }, "required": false, @@ -607,7 +607,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/BothMapBounds/allOf/1/properties/p", + "target": "type/composed/components/schemas/BothMapBounds/allOf/properties/p", "nullable": false }, "required": false, @@ -654,7 +654,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/BothScalarBounds/allOf/1/properties/p", + "target": "type/composed/components/schemas/BothScalarBounds/allOf/properties/p", "nullable": false }, "required": false, @@ -701,7 +701,7 @@ }, "wireName": "p", "type": { - "target": "type/composed/components/schemas/BothTupleBounds/allOf/1/properties/p", + "target": "type/composed/components/schemas/BothTupleBounds/allOf/properties/p", "nullable": false }, "required": false, @@ -900,23 +900,23 @@ "positional": false, "inputOnly": false }, - "type/openapi/components/schemas/DefaultPastItsOwnBound": { + "type/openapi/components/schemas/DefaultPastItsOwnBoundFirst": { "kind": "model", - "id": "type/openapi/components/schemas/DefaultPastItsOwnBound", + "id": "type/openapi/components/schemas/DefaultPastItsOwnBoundFirst", "name": { - "source": "DefaultPastItsOwnBound", - "canonical": "default_past_its_own_bound" + "source": "DefaultPastItsOwnBoundFirst", + "canonical": "default_past_its_own_bound_first" }, "anonymous": false, "docs": {}, "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/DefaultPastItsOwnBound" + "pointer": "/components/schemas/DefaultPastItsOwnBoundFirst" }, "properties": [ { - "id": "property/openapi/components/schemas/DefaultPastItsOwnBound/allOf/0/properties/p", + "id": "property/openapi/components/schemas/DefaultPastItsOwnBoundFirst/allOf/0/properties/p", "name": { "source": "p", "canonical": "p" @@ -932,9 +932,70 @@ "visibility": { "invisibleInEveryLifecycle": false }, - "default": { - "kind": "string", - "string": "hello" + "constraints": { + "maxLength": 3, + "uniqueItems": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "unmodeled": { + "openapi:conflicting-redeclaration/components/schemas/DefaultPastItsOwnBoundFirst/allOf/0/properties/p": { + "reason": "degraded_lowering", + "value": { + "default": "hello", + "maxLength": 3, + "type": "string" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundFirst/allOf/0/properties/p" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundFirst/allOf/0/properties/p" + } + } + ], + "abstract": false, + "positional": false, + "inputOnly": false + }, + "type/openapi/components/schemas/DefaultPastItsOwnBoundLast": { + "kind": "model", + "id": "type/openapi/components/schemas/DefaultPastItsOwnBoundLast", + "name": { + "source": "DefaultPastItsOwnBoundLast", + "canonical": "default_past_its_own_bound_last" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundLast" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/DefaultPastItsOwnBoundLast/allOf/0/properties/p", + "name": { + "source": "p", + "canonical": "p" + }, + "wireName": "p", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false }, "constraints": { "maxLength": 3, @@ -945,9 +1006,23 @@ "eventPayload": false, "secret": false, "docs": {}, + "unmodeled": { + "openapi:conflicting-redeclaration/components/schemas/DefaultPastItsOwnBoundLast/allOf/1/properties/p": { + "reason": "degraded_lowering", + "value": { + "default": "hello", + "maxLength": 3, + "type": "string" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundLast/allOf/1/properties/p" + } + } + }, "provenance": { "source": 0, - "pointer": "/components/schemas/DefaultPastItsOwnBound/allOf/0/properties/p" + "pointer": "/components/schemas/DefaultPastItsOwnBoundLast/allOf/0/properties/p" } } ], @@ -1447,32 +1522,90 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"p\" merge to admits the default the declaration at /components/schemas/DefaultPastAnotherBoundBoundFirst/allOf/1/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/DefaultPastAnotherBoundBoundFirst: the merge cannot show that the type its declarations merge to admits the default /components/schemas/DefaultPastAnotherBoundBoundFirst/allOf/1/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/DefaultPastAnotherBoundBoundFirst/allOf/1/properties/p" - } + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastAnotherBoundBoundFirst", + "node": "property/openapi/components/schemas/DefaultPastAnotherBoundBoundFirst/allOf/0/properties/p" + } + } + ] }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"p\" merge to admits the default the declaration at /components/schemas/DefaultPastAnotherBoundDefaultFirst/allOf/0/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/DefaultPastAnotherBoundDefaultFirst: the merge cannot show that the type its declarations merge to admits the default /components/schemas/DefaultPastAnotherBoundDefaultFirst/allOf/0/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/DefaultPastAnotherBoundDefaultFirst/allOf/0/properties/p" - } + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastAnotherBoundDefaultFirst", + "node": "property/openapi/components/schemas/DefaultPastAnotherBoundDefaultFirst/allOf/0/properties/p" + } + } + ] + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "field \"p\" of /components/schemas/DefaultPastItsOwnBoundFirst: the merge cannot show that the type its declarations merge to admits the default /components/schemas/DefaultPastItsOwnBoundFirst/allOf/0/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundFirst/allOf/0/properties/p" + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundFirst", + "node": "property/openapi/components/schemas/DefaultPastItsOwnBoundFirst/allOf/0/properties/p" + } + } + ] + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "field \"p\" of /components/schemas/DefaultPastItsOwnBoundLast: the merge cannot show that the type its declarations merge to admits the default /components/schemas/DefaultPastItsOwnBoundLast/allOf/1/properties/p gives; not adopted, and that declaration is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundLast/allOf/1/properties/p" + }, + "related": [ + { + "role": "decided", + "provenance": { + "source": 0, + "pointer": "/components/schemas/DefaultPastItsOwnBoundLast", + "node": "property/openapi/components/schemas/DefaultPastItsOwnBoundLast/allOf/0/properties/p" + } + } + ] }, { "severity": "warning", "code": "openapi/conflicting-redeclaration", - "message": "declarations of field \"p\" disagree: conflicting pattern (\"^b\" and \"^a\"); kept what the declaration at /components/schemas/PatternsAThenB/allOf/1/properties/p says over the one at /components/schemas/PatternsAThenB/allOf/0/properties/p, which is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/PatternsAThenB: /components/schemas/PatternsAThenB/allOf/1/properties/p and /components/schemas/PatternsAThenB/allOf/0/properties/p disagree: conflicting pattern (\"^b\" and \"^a\"); chose what the first says; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/PatternsAThenB/allOf/0/properties/p" }, "related": [ { - "role": "kept", + "role": "chosen", "provenance": { "source": 0, "pointer": "/components/schemas/PatternsAThenB/allOf/1/properties/p" @@ -1481,7 +1614,8 @@ { "role": "decided", "provenance": { - "source": -1, + "source": 0, + "pointer": "/components/schemas/PatternsAThenB", "node": "property/openapi/components/schemas/PatternsAThenB/allOf/0/properties/p" } } @@ -1490,14 +1624,14 @@ { "severity": "warning", "code": "openapi/conflicting-redeclaration", - "message": "declarations of field \"p\" disagree: conflicting pattern (\"^a\" and \"^b\"); kept what the declaration at /components/schemas/PatternsBThenA/allOf/1/properties/p says over the one at /components/schemas/PatternsBThenA/allOf/0/properties/p, which is kept verbatim under Unmodeled", + "message": "field \"p\" of /components/schemas/PatternsBThenA: /components/schemas/PatternsBThenA/allOf/1/properties/p and /components/schemas/PatternsBThenA/allOf/0/properties/p disagree: conflicting pattern (\"^a\" and \"^b\"); chose what the first says; the second is kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/PatternsBThenA/allOf/0/properties/p" }, "related": [ { - "role": "kept", + "role": "chosen", "provenance": { "source": 0, "pointer": "/components/schemas/PatternsBThenA/allOf/1/properties/p" @@ -1506,7 +1640,8 @@ { "role": "decided", "provenance": { - "source": -1, + "source": 0, + "pointer": "/components/schemas/PatternsBThenA", "node": "property/openapi/components/schemas/PatternsBThenA/allOf/0/properties/p" } } @@ -1517,7 +1652,7 @@ { "format": "openapi@3.1", "path": "allof-redeclared-bounds.yaml", - "hash": "a9c20ba29465edbef6d5bf7aa107376569456a3764f1ffe388f04e7cf4726a58" + "hash": "a5ce8eb619e41cc873c159f818926a8596f1c73598725399d28871b1c6a72c84" } ] } diff --git a/testdata/conformance/openapi/allof-redeclared-bounds.yaml b/testdata/conformance/openapi/allof-redeclared-bounds.yaml index e6634fd87..ea72d396d 100644 --- a/testdata/conformance/openapi/allof-redeclared-bounds.yaml +++ b/testdata/conformance/openapi/allof-redeclared-bounds.yaml @@ -162,9 +162,9 @@ components: - type: object properties: p: {type: string, pattern: '^a'} - # A default another declaration's bound refuses stays off the field, reported - # and kept at the declaration that wrote it. One its own bound refuses is that - # declaration's to answer for and stands. + # A default a bound at its position refuses stays off the field, reported and + # kept at the declaration that wrote it, whether another declaration wrote the + # bound or the one giving the default did. DefaultPastAnotherBoundDefaultFirst: allOf: - type: object @@ -181,7 +181,7 @@ components: - type: object properties: p: {type: string, default: hello} - DefaultPastItsOwnBound: + DefaultPastItsOwnBoundFirst: allOf: - type: object properties: @@ -189,3 +189,11 @@ components: - type: object properties: p: {type: string} + DefaultPastItsOwnBoundLast: + allOf: + - type: object + properties: + p: {type: string} + - type: object + properties: + p: {type: string, maxLength: 3, default: hello} diff --git a/testdata/conformance/openapi/allof-redeclared-models.golden.json b/testdata/conformance/openapi/allof-redeclared-models.golden.json index 12300aba5..836a2fc29 100644 --- a/testdata/conformance/openapi/allof-redeclared-models.golden.json +++ b/testdata/conformance/openapi/allof-redeclared-models.golden.json @@ -387,7 +387,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/SharedFirst/allOf/0/allOf/1/properties/data", + "target": "type/composed/components/schemas/SharedFirst/allOf/0/allOf/properties/data", "nullable": false }, "required": false, @@ -433,7 +433,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/SharedLast/allOf/1/allOf/1/properties/data", + "target": "type/composed/components/schemas/SharedLast/allOf/1/allOf/properties/data", "nullable": false }, "required": false, @@ -654,9 +654,9 @@ "closed": true, "inputOnly": false }, - "type/composed/components/schemas/ConstrainedAliasAndModel/allOf/1/properties/data": { + "type/composed/components/schemas/ConstrainedAliasAndModel/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/ConstrainedAliasAndModel/allOf/1/properties/data", + "id": "type/composed/components/schemas/ConstrainedAliasAndModel/allOf/properties/data", "name": { "hint": "data" }, @@ -665,7 +665,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/ConstrainedAliasAndModel/allOf/1/properties/data" + "pointer": "/components/schemas/ConstrainedAliasAndModel/allOf/properties/data" }, "mixins": [ { @@ -681,9 +681,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/DiscriminatedBase/allOf/1/properties/pet": { + "type/composed/components/schemas/DiscriminatedBase/allOf/properties/pet": { "kind": "model", - "id": "type/composed/components/schemas/DiscriminatedBase/allOf/1/properties/pet", + "id": "type/composed/components/schemas/DiscriminatedBase/allOf/properties/pet", "name": { "hint": "pet" }, @@ -692,7 +692,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/DiscriminatedBase/allOf/1/properties/pet" + "pointer": "/components/schemas/DiscriminatedBase/allOf/properties/pet" }, "base": { "target": "type/openapi/components/schemas/Pet", @@ -708,9 +708,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/DiscriminatedFirst/allOf/1/properties/pet": { + "type/composed/components/schemas/DiscriminatedFirst/allOf/properties/pet": { "kind": "model", - "id": "type/composed/components/schemas/DiscriminatedFirst/allOf/1/properties/pet", + "id": "type/composed/components/schemas/DiscriminatedFirst/allOf/properties/pet", "name": { "hint": "pet" }, @@ -719,7 +719,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/DiscriminatedFirst/allOf/1/properties/pet" + "pointer": "/components/schemas/DiscriminatedFirst/allOf/properties/pet" }, "base": { "target": "type/openapi/components/schemas/Pet", @@ -735,9 +735,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/InlineFirst/allOf/1/properties/data": { + "type/composed/components/schemas/InlineFirst/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/InlineFirst/allOf/1/properties/data", + "id": "type/composed/components/schemas/InlineFirst/allOf/properties/data", "name": { "hint": "data" }, @@ -746,7 +746,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/InlineFirst/allOf/1/properties/data" + "pointer": "/components/schemas/InlineFirst/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Meeting", @@ -762,9 +762,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/KeptDefault/allOf/1/properties/data": { + "type/composed/components/schemas/KeptDefault/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/KeptDefault/allOf/1/properties/data", + "id": "type/composed/components/schemas/KeptDefault/allOf/properties/data", "name": { "hint": "data" }, @@ -773,7 +773,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/KeptDefault/allOf/1/properties/data" + "pointer": "/components/schemas/KeptDefault/allOf/properties/data" }, "mixins": [ { @@ -789,9 +789,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/ListsOfModels/allOf/1/properties/data": { + "type/composed/components/schemas/ListsOfModels/allOf/properties/data": { "kind": "list", - "id": "type/composed/components/schemas/ListsOfModels/allOf/1/properties/data", + "id": "type/composed/components/schemas/ListsOfModels/allOf/properties/data", "name": { "hint": "data" }, @@ -800,16 +800,16 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/ListsOfModels/allOf/1/properties/data" + "pointer": "/components/schemas/ListsOfModels/allOf/properties/data" }, "elementType": { - "target": "type/composed/components/schemas/ListsOfModels/allOf/1/properties/data/items", + "target": "type/composed/components/schemas/ListsOfModels/allOf/properties/data/items", "nullable": false } }, - "type/composed/components/schemas/ListsOfModels/allOf/1/properties/data/items": { + "type/composed/components/schemas/ListsOfModels/allOf/properties/data/items": { "kind": "model", - "id": "type/composed/components/schemas/ListsOfModels/allOf/1/properties/data/items", + "id": "type/composed/components/schemas/ListsOfModels/allOf/properties/data/items", "name": { "hint": "data_item" }, @@ -818,7 +818,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/ListsOfModels/allOf/1/properties/data/items" + "pointer": "/components/schemas/ListsOfModels/allOf/properties/data/items" }, "mixins": [ { @@ -834,9 +834,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/MapThenModel/allOf/1/properties/data": { + "type/composed/components/schemas/MapThenModel/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/MapThenModel/allOf/1/properties/data", + "id": "type/composed/components/schemas/MapThenModel/allOf/properties/data", "name": { "hint": "data" }, @@ -845,7 +845,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/MapThenModel/allOf/1/properties/data" + "pointer": "/components/schemas/MapThenModel/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Meeting", @@ -861,9 +861,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/MapsOfModels/allOf/1/properties/data": { + "type/composed/components/schemas/MapsOfModels/allOf/properties/data": { "kind": "map", - "id": "type/composed/components/schemas/MapsOfModels/allOf/1/properties/data", + "id": "type/composed/components/schemas/MapsOfModels/allOf/properties/data", "name": { "hint": "data" }, @@ -872,16 +872,16 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/MapsOfModels/allOf/1/properties/data" + "pointer": "/components/schemas/MapsOfModels/allOf/properties/data" }, "value": { - "target": "type/composed/components/schemas/MapsOfModels/allOf/1/properties/data/additionalProperties", + "target": "type/composed/components/schemas/MapsOfModels/allOf/properties/data/additionalProperties", "nullable": false } }, - "type/composed/components/schemas/MapsOfModels/allOf/1/properties/data/additionalProperties": { + "type/composed/components/schemas/MapsOfModels/allOf/properties/data/additionalProperties": { "kind": "model", - "id": "type/composed/components/schemas/MapsOfModels/allOf/1/properties/data/additionalProperties", + "id": "type/composed/components/schemas/MapsOfModels/allOf/properties/data/additionalProperties", "name": { "hint": "data_value" }, @@ -890,7 +890,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/MapsOfModels/allOf/1/properties/data/additionalProperties" + "pointer": "/components/schemas/MapsOfModels/allOf/properties/data/additionalProperties" }, "mixins": [ { @@ -906,9 +906,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/ModelThenMap/allOf/1/properties/data": { + "type/composed/components/schemas/ModelThenMap/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/ModelThenMap/allOf/1/properties/data", + "id": "type/composed/components/schemas/ModelThenMap/allOf/properties/data", "name": { "hint": "data" }, @@ -917,7 +917,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/ModelThenMap/allOf/1/properties/data" + "pointer": "/components/schemas/ModelThenMap/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Meeting", @@ -933,9 +933,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/ModelThenUnion/allOf/1/properties/data": { + "type/composed/components/schemas/ModelThenUnion/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/ModelThenUnion/allOf/1/properties/data", + "id": "type/composed/components/schemas/ModelThenUnion/allOf/properties/data", "name": { "hint": "data" }, @@ -944,7 +944,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/ModelThenUnion/allOf/1/properties/data" + "pointer": "/components/schemas/ModelThenUnion/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Meeting", @@ -960,9 +960,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/RefFirst/allOf/1/properties/data": { + "type/composed/components/schemas/RefFirst/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/RefFirst/allOf/1/properties/data", + "id": "type/composed/components/schemas/RefFirst/allOf/properties/data", "name": { "hint": "data" }, @@ -971,7 +971,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/RefFirst/allOf/1/properties/data" + "pointer": "/components/schemas/RefFirst/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Meeting", @@ -987,9 +987,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/RefIntoBranch/allOf/1/properties/data": { + "type/composed/components/schemas/RefIntoBranch/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/RefIntoBranch/allOf/1/properties/data", + "id": "type/composed/components/schemas/RefIntoBranch/allOf/properties/data", "name": { "hint": "data" }, @@ -998,7 +998,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/RefIntoBranch/allOf/1/properties/data" + "pointer": "/components/schemas/RefIntoBranch/allOf/properties/data" }, "mixins": [ { @@ -1014,9 +1014,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/SharedFirst/allOf/0/allOf/1/properties/data": { + "type/composed/components/schemas/SharedFirst/allOf/0/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/SharedFirst/allOf/0/allOf/1/properties/data", + "id": "type/composed/components/schemas/SharedFirst/allOf/0/allOf/properties/data", "name": { "hint": "data" }, @@ -1025,7 +1025,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/SharedFirst/allOf/0/allOf/1/properties/data" + "pointer": "/components/schemas/SharedFirst/allOf/0/allOf/properties/data" }, "mixins": [ { @@ -1041,9 +1041,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/SharedFirst/allOf/1/properties/data": { + "type/composed/components/schemas/SharedFirst/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/SharedFirst/allOf/1/properties/data", + "id": "type/composed/components/schemas/SharedFirst/allOf/properties/data", "name": { "hint": "data" }, @@ -1052,7 +1052,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/SharedFirst/allOf/1/properties/data" + "pointer": "/components/schemas/SharedFirst/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Pet", @@ -1072,9 +1072,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/SharedLast/allOf/1/allOf/0/properties/data": { + "type/composed/components/schemas/SharedLast/allOf/1/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/SharedLast/allOf/1/allOf/0/properties/data", + "id": "type/composed/components/schemas/SharedLast/allOf/1/allOf/properties/data", "name": { "hint": "data" }, @@ -1083,11 +1083,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/SharedLast/allOf/1/allOf/0/properties/data" - }, - "base": { - "target": "type/openapi/components/schemas/Pet", - "nullable": false + "pointer": "/components/schemas/SharedLast/allOf/1/allOf/properties/data" }, "mixins": [ { @@ -1103,9 +1099,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/SharedLast/allOf/1/allOf/1/properties/data": { + "type/composed/components/schemas/SharedLast/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/SharedLast/allOf/1/allOf/1/properties/data", + "id": "type/composed/components/schemas/SharedLast/allOf/properties/data", "name": { "hint": "data" }, @@ -1114,7 +1110,11 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/SharedLast/allOf/1/allOf/1/properties/data" + "pointer": "/components/schemas/SharedLast/allOf/properties/data" + }, + "base": { + "target": "type/openapi/components/schemas/Pet", + "nullable": false }, "mixins": [ { @@ -1130,9 +1130,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/TitledAndModel/allOf/1/properties/data": { + "type/composed/components/schemas/TitledAndModel/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/TitledAndModel/allOf/1/properties/data", + "id": "type/composed/components/schemas/TitledAndModel/allOf/properties/data", "name": { "hint": "data" }, @@ -1141,7 +1141,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/TitledAndModel/allOf/1/properties/data" + "pointer": "/components/schemas/TitledAndModel/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Meeting", @@ -1157,9 +1157,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/TopAliasFirst/allOf/1/properties/data": { + "type/composed/components/schemas/TopAliasFirst/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/TopAliasFirst/allOf/1/properties/data", + "id": "type/composed/components/schemas/TopAliasFirst/allOf/properties/data", "name": { "hint": "data" }, @@ -1168,7 +1168,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/TopAliasFirst/allOf/1/properties/data" + "pointer": "/components/schemas/TopAliasFirst/allOf/properties/data" }, "mixins": [ { @@ -1184,9 +1184,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/TopAliasLast/allOf/1/properties/data": { + "type/composed/components/schemas/TopAliasLast/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/TopAliasLast/allOf/1/properties/data", + "id": "type/composed/components/schemas/TopAliasLast/allOf/properties/data", "name": { "hint": "data" }, @@ -1195,7 +1195,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/TopAliasLast/allOf/1/properties/data" + "pointer": "/components/schemas/TopAliasLast/allOf/properties/data" }, "mixins": [ { @@ -1211,9 +1211,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/TuplesOfModels/allOf/1/properties/data": { + "type/composed/components/schemas/TuplesOfModels/allOf/properties/data": { "kind": "tuple", - "id": "type/composed/components/schemas/TuplesOfModels/allOf/1/properties/data", + "id": "type/composed/components/schemas/TuplesOfModels/allOf/properties/data", "name": { "hint": "data" }, @@ -1222,11 +1222,11 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/TuplesOfModels/allOf/1/properties/data" + "pointer": "/components/schemas/TuplesOfModels/allOf/properties/data" }, "elementTypes": [ { - "target": "type/composed/components/schemas/TuplesOfModels/allOf/1/properties/data/prefixItems/0", + "target": "type/composed/components/schemas/TuplesOfModels/allOf/properties/data/prefixItems/0", "nullable": false } ], @@ -1235,9 +1235,9 @@ "nullable": false } }, - "type/composed/components/schemas/TuplesOfModels/allOf/1/properties/data/prefixItems/0": { + "type/composed/components/schemas/TuplesOfModels/allOf/properties/data/prefixItems/0": { "kind": "model", - "id": "type/composed/components/schemas/TuplesOfModels/allOf/1/properties/data/prefixItems/0", + "id": "type/composed/components/schemas/TuplesOfModels/allOf/properties/data/prefixItems/0", "name": { "hint": "data_0" }, @@ -1246,7 +1246,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/TuplesOfModels/allOf/1/properties/data/prefixItems/0" + "pointer": "/components/schemas/TuplesOfModels/allOf/properties/data/prefixItems/0" }, "mixins": [ { @@ -1262,9 +1262,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/TwoComponents/allOf/1/properties/data": { + "type/composed/components/schemas/TwoComponents/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/TwoComponents/allOf/1/properties/data", + "id": "type/composed/components/schemas/TwoComponents/allOf/properties/data", "name": { "hint": "data" }, @@ -1273,7 +1273,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/TwoComponents/allOf/1/properties/data" + "pointer": "/components/schemas/TwoComponents/allOf/properties/data" }, "mixins": [ { @@ -1289,9 +1289,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/TwoInline/allOf/1/properties/data": { + "type/composed/components/schemas/TwoInline/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/TwoInline/allOf/1/properties/data", + "id": "type/composed/components/schemas/TwoInline/allOf/properties/data", "name": { "hint": "data" }, @@ -1300,7 +1300,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/TwoInline/allOf/1/properties/data" + "pointer": "/components/schemas/TwoInline/allOf/properties/data" }, "mixins": [ { @@ -1316,9 +1316,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/UnionThenModel/allOf/1/properties/data": { + "type/composed/components/schemas/UnionThenModel/allOf/properties/data": { "kind": "model", - "id": "type/composed/components/schemas/UnionThenModel/allOf/1/properties/data", + "id": "type/composed/components/schemas/UnionThenModel/allOf/properties/data", "name": { "hint": "data" }, @@ -1327,7 +1327,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/UnionThenModel/allOf/1/properties/data" + "pointer": "/components/schemas/UnionThenModel/allOf/properties/data" }, "base": { "target": "type/openapi/components/schemas/Meeting", @@ -1648,7 +1648,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/ConstrainedAliasAndModel/allOf/1/properties/data", + "target": "type/composed/components/schemas/ConstrainedAliasAndModel/allOf/properties/data", "nullable": false }, "required": false, @@ -1742,7 +1742,7 @@ }, "wireName": "pet", "type": { - "target": "type/composed/components/schemas/DiscriminatedBase/allOf/1/properties/pet", + "target": "type/composed/components/schemas/DiscriminatedBase/allOf/properties/pet", "nullable": false }, "required": false, @@ -1789,7 +1789,7 @@ }, "wireName": "pet", "type": { - "target": "type/composed/components/schemas/DiscriminatedFirst/allOf/1/properties/pet", + "target": "type/composed/components/schemas/DiscriminatedFirst/allOf/properties/pet", "nullable": false }, "required": false, @@ -1935,7 +1935,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/InlineFirst/allOf/1/properties/data", + "target": "type/composed/components/schemas/InlineFirst/allOf/properties/data", "nullable": false }, "required": false, @@ -1982,7 +1982,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/KeptDefault/allOf/1/properties/data", + "target": "type/composed/components/schemas/KeptDefault/allOf/properties/data", "nullable": false }, "required": false, @@ -1991,29 +1991,23 @@ "visibility": { "invisibleInEveryLifecycle": false }, + "default": { + "kind": "object", + "object": [ + { + "name": "id", + "value": { + "kind": "string", + "string": "a" + } + } + ] + }, "flatten": false, "eventHeader": false, "eventPayload": false, "secret": false, "docs": {}, - "unmodeled": { - "openapi:conflicting-redeclaration/components/schemas/KeptDefault/allOf/0/properties/data": { - "reason": "degraded_lowering", - "value": { - "$ref": "#/components/schemas/Meeting", - "default": { - "id": "a" - } - }, - "targets": { - "/$ref": "type/openapi/components/schemas/Meeting" - }, - "provenance": { - "source": 0, - "pointer": "/components/schemas/KeptDefault/allOf/0/properties/data" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/KeptDefault/allOf/0/properties/data" @@ -2094,7 +2088,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/ListsOfModels/allOf/1/properties/data", + "target": "type/composed/components/schemas/ListsOfModels/allOf/properties/data", "nullable": false }, "required": false, @@ -2141,7 +2135,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/MapThenModel/allOf/1/properties/data", + "target": "type/composed/components/schemas/MapThenModel/allOf/properties/data", "nullable": false }, "required": false, @@ -2188,7 +2182,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/MapsOfModels/allOf/1/properties/data", + "target": "type/composed/components/schemas/MapsOfModels/allOf/properties/data", "nullable": false }, "required": false, @@ -2306,7 +2300,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/ModelThenMap/allOf/1/properties/data", + "target": "type/composed/components/schemas/ModelThenMap/allOf/properties/data", "nullable": false }, "required": false, @@ -2353,7 +2347,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/ModelThenUnion/allOf/1/properties/data", + "target": "type/composed/components/schemas/ModelThenUnion/allOf/properties/data", "nullable": false }, "required": false, @@ -2545,6 +2539,10 @@ "positional": false, "discriminator": { "property": "property/openapi/components/schemas/Pet/properties/kind", + "mapping": { + "Dog": "type/openapi/components/schemas/Dog", + "Pet": "type/openapi/components/schemas/Pet" + }, "inferred": false }, "inputOnly": false @@ -2619,7 +2617,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/RefFirst/allOf/1/properties/data", + "target": "type/composed/components/schemas/RefFirst/allOf/properties/data", "nullable": false }, "required": false, @@ -2659,14 +2657,14 @@ }, "properties": [ { - "id": "property/composed/components/schemas/RefIntoBranch/allOf/1/properties/data", + "id": "property/composed/components/schemas/RefIntoBranch/allOf/properties/data", "name": { "source": "data", "canonical": "data" }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/RefIntoBranch/allOf/1/properties/data", + "target": "type/composed/components/schemas/RefIntoBranch/allOf/properties/data", "nullable": false }, "required": false, @@ -2682,7 +2680,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/RefIntoBranch/allOf/1/properties/data" + "pointer": "/components/schemas/RefIntoBranch/allOf/properties/data" } } ], @@ -2706,14 +2704,14 @@ }, "properties": [ { - "id": "property/composed/components/schemas/SharedFirst/allOf/1/properties/data", + "id": "property/openapi/components/schemas/SharedFirst/allOf/1/properties/data", "name": { "source": "data", "canonical": "data" }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/SharedFirst/allOf/1/properties/data", + "target": "type/composed/components/schemas/SharedFirst/allOf/properties/data", "nullable": false }, "required": false, @@ -2760,7 +2758,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/SharedLast/allOf/1/allOf/0/properties/data", + "target": "type/composed/components/schemas/SharedLast/allOf/properties/data", "nullable": false }, "required": false, @@ -2854,7 +2852,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/TitledAndModel/allOf/1/properties/data", + "target": "type/composed/components/schemas/TitledAndModel/allOf/properties/data", "nullable": false }, "required": false, @@ -2901,7 +2899,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/TopAliasFirst/allOf/1/properties/data", + "target": "type/composed/components/schemas/TopAliasFirst/allOf/properties/data", "nullable": false }, "required": false, @@ -2950,7 +2948,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/TopAliasLast/allOf/1/properties/data", + "target": "type/composed/components/schemas/TopAliasLast/allOf/properties/data", "nullable": false }, "required": false, @@ -2999,7 +2997,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/TuplesOfModels/allOf/1/properties/data", + "target": "type/composed/components/schemas/TuplesOfModels/allOf/properties/data", "nullable": false }, "required": false, @@ -3046,7 +3044,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/TwoComponents/allOf/1/properties/data", + "target": "type/composed/components/schemas/TwoComponents/allOf/properties/data", "nullable": true }, "required": false, @@ -3140,7 +3138,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/TwoInline/allOf/1/properties/data", + "target": "type/composed/components/schemas/TwoInline/allOf/properties/data", "nullable": false }, "required": false, @@ -3187,7 +3185,7 @@ }, "wireName": "data", "type": { - "target": "type/composed/components/schemas/UnionThenModel/allOf/1/properties/data", + "target": "type/composed/components/schemas/UnionThenModel/allOf/properties/data", "nullable": false }, "required": false, @@ -3261,17 +3259,6 @@ } } }, - "diagnostics": [ - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "the merge cannot show that the type the declarations of field \"data\" merge to admits the default the declaration at /components/schemas/KeptDefault/allOf/0/properties/data gives; not adopted, and that declaration is kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/KeptDefault/allOf/0/properties/data" - } - } - ], "sources": [ { "format": "openapi@3.1", diff --git a/testdata/conformance/openapi/allof-ref-branch-siblings.golden.json b/testdata/conformance/openapi/allof-ref-branch-siblings.golden.json index 38642bf2f..5e45b0179 100644 --- a/testdata/conformance/openapi/allof-ref-branch-siblings.golden.json +++ b/testdata/conformance/openapi/allof-ref-branch-siblings.golden.json @@ -283,54 +283,50 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:allOf/0/allOf/0": { + "openapi:allOf/0": { "reason": "degraded_lowering", "value": { - "type": "string" + "$ref": "#/components/schemas/Base", + "allOf": [ + { + "type": "string" + } + ] + }, + "targets": { + "/$ref": "type/openapi/components/schemas/Base" }, "provenance": { "source": 0, - "pointer": "/components/schemas/NestedAllOfBranch/allOf/0/allOf/0" + "pointer": "/components/schemas/NestedAllOfBranch/allOf/0" } - } - }, - "provenance": { - "source": 0, - "pointer": "/components/schemas/NestedAllOfBranch" - }, - "properties": [ - { - "id": "property/openapi/components/schemas/NestedAllOfBranch/properties/e", - "name": { - "source": "e", - "canonical": "e" - }, - "wireName": "e", - "type": { - "target": "type/primitive/string", - "nullable": false - }, - "required": false, - "clientOptional": false, - "defaultAdded": false, - "visibility": { - "invisibleInEveryLifecycle": false + }, + "openapi:properties": { + "reason": "degraded_lowering", + "value": { + "e": { + "type": "string" + } }, - "flatten": false, - "eventHeader": false, - "eventPayload": false, - "secret": false, - "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/NestedAllOfBranch/properties/e" + "pointer": "/components/schemas/NestedAllOfBranch/properties" + } + }, + "openapi:type": { + "reason": "degraded_lowering", + "value": "object", + "provenance": { + "source": 0, + "pointer": "/components/schemas/NestedAllOfBranch/type" } } - ], - "base": { - "target": "type/openapi/components/schemas/Base", - "nullable": false }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/NestedAllOfBranch" + }, + "additional": "closed", "abstract": false, "positional": false, "inputOnly": false @@ -432,39 +428,21 @@ "diagnostics": [ { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (type: object, allOf/0/$ref: object, allOf/0: string or integer), so no instance satisfies this schema, which a composition cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the type and every allOf entry (type: object, allOf/0: string or integer, allOf/0/$ref: object); lowered as a node of kind \"model\", its allOf/0/oneOf kept verbatim under Unmodeled — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/UnionBranch" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this allOf lowered to a node of kind \"model\", which has no home for oneOf written beside this $ref; kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/UnionBranch/allOf/0" - } - }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (type: object, allOf/0/$ref: object, allOf/0/allOf/0: string), so no instance satisfies this schema, which a composition cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the type and every allOf entry (type: object, allOf/0/$ref: object, allOf/0/allOf/0: string); lowered as the closed model with no member a false schema lowers to — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/NestedAllOfBranch" } - }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "another conjunct of this allOf writes a keyword this inline entry keeps otherwise, and one Unmodeled entry under that keyword holds one value; the entry (type) is kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/NestedAllOfBranch/allOf/0/allOf/0" - } } ], "sources": [ diff --git a/testdata/conformance/openapi/allof-refinement.golden.json b/testdata/conformance/openapi/allof-refinement.golden.json index 19ff902d0..e770ad303 100644 --- a/testdata/conformance/openapi/allof-refinement.golden.json +++ b/testdata/conformance/openapi/allof-refinement.golden.json @@ -524,6 +524,7 @@ "source": 0, "pointer": "/components/schemas/Disjoint" }, + "additional": "closed", "abstract": false, "positional": false, "inputOnly": false @@ -667,6 +668,26 @@ "anonymous": false, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:anyOf": { + "reason": "degraded_lowering", + "value": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + } + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/Needle/allOf/0/anyOf" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/Needle" @@ -690,6 +711,26 @@ "anonymous": false, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:anyOf": { + "reason": "degraded_lowering", + "value": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + } + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/NeedleBeside/anyOf" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/NeedleBeside" @@ -1138,7 +1179,7 @@ }, "wireName": "width", "type": { - "target": "type/openapi/components/schemas/Port", + "target": "type/primitive/int32", "nullable": false }, "required": false, @@ -1153,12 +1194,15 @@ "secret": false, "docs": {}, "unmodeled": { - "openapi:format": { + "openapi:$ref": { "reason": "degraded_lowering", - "value": "int32", + "value": "#/components/schemas/Port", + "targets": { + "": "type/openapi/components/schemas/Port" + }, "provenance": { "source": 0, - "pointer": "/components/schemas/Zone/properties/width/allOf/1/format" + "pointer": "/components/schemas/Zone/properties/width/allOf/0" } } }, @@ -1349,7 +1393,7 @@ "source": 0, "pointer": "/components/schemas/Port80/allOf/1/const", "position": { - "line": 122, + "line": 123, "column": 19 } } @@ -1375,10 +1419,10 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this allOf lowered to a use of one of its allOf conjuncts, which has no home for format written on this inline entry; kept verbatim under Unmodeled", + "message": "format: int32 on allOf/1 makes this allOf an int32, while the $ref target \"#/components/schemas/Port\" is a plain integer; lowered as an int32 with the $ref kept under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/Zone/properties/width/allOf/1" + "pointer": "/components/schemas/Zone/properties/width/allOf/0" } }, { @@ -1392,8 +1436,8 @@ }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (allOf/0: integer, allOf/1: string), so no instance satisfies this schema, which a composition cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies every allOf entry (allOf/0: integer, allOf/1: string); lowered as the closed model with no member a false schema lowers to — remove or correct one entry", "provenance": { "source": 0, "pointer": "/components/schemas/Disjoint" @@ -1402,28 +1446,46 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "another conjunct of this allOf writes a keyword this inline entry keeps otherwise, and one Unmodeled entry under that keyword holds one value; the entry (type) is kept verbatim under Unmodeled", + "message": "readOnly on a type declaration binds a use of the type, not the type; it is kept verbatim under Unmodeled and applied to a referencing property, header or parameter wherever that carrier has a field for it", "provenance": { "source": 0, - "pointer": "/components/schemas/Disjoint/allOf/0" + "pointer": "/components/schemas/Identifier/readOnly" } }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "another conjunct of this allOf writes a keyword this inline entry keeps otherwise, and one Unmodeled entry under that keyword holds one value; the entry (type) is kept verbatim under Unmodeled", + "message": "this allOf lowered to a node of kind \"scalar\", which has no home for anyOf written on this inline entry; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Needle/allOf/0" + } + }, + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "2 of the 3 branches of this anyOf share no value with the rest of the schema (anyOf/1: number, anyOf/2: boolean), so no instance satisfies them: the anyOf is kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/Disjoint/allOf/1" + "pointer": "/components/schemas/Needle/allOf/0/anyOf" } }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "readOnly on a type declaration binds a use of the type, not the type; it is kept verbatim under Unmodeled and applied to a referencing property, header or parameter wherever that carrier has a field for it", + "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and the body is not a model, so it carries no composition to distribute into; union branches kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/Identifier/readOnly" + "pointer": "/components/schemas/NeedleBeside" + } + }, + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "2 of the 3 branches of this anyOf share no value with the rest of the schema (anyOf/1: number, anyOf/2: boolean), so no instance satisfies them: the anyOf is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/NeedleBeside/anyOf" } } ], @@ -1431,7 +1493,7 @@ { "format": "openapi@3.0", "path": "allof-refinement.yaml", - "hash": "713bb2f11b35c7c602f167337351c41ab83ba6614cac5e1ed75796ce8faf059f" + "hash": "cc55c5e69a0ca2daff1782b1dfb872813255e6f507c8a5db55bf735e4e7716e2" } ] } diff --git a/testdata/conformance/openapi/allof-refinement.yaml b/testdata/conformance/openapi/allof-refinement.yaml index 7d265ad3f..7fbd948db 100644 --- a/testdata/conformance/openapi/allof-refinement.yaml +++ b/testdata/conformance/openapi/allof-refinement.yaml @@ -61,7 +61,8 @@ components: allOf: - {$ref: '#/components/schemas/Mode'} - {enum: [set]} - # A value narrower than nothing the reference says stays verbatim. + # A format narrowing the primitive the reference is rooted at elects + # its conjunct, the reference kept. width: allOf: - {$ref: '#/components/schemas/Port'} @@ -143,13 +144,14 @@ components: Mode: {type: string, enum: [get, set], description: What to do} Blob: {type: string, format: binary} # A union on an entry is a conjunct admitting what its branches do, so this - # is the string the second entry says, and the anyOf adds nothing to it. + # is the string the second entry says; its number and boolean branches share + # no value with it, so the anyOf is kept, warned of at the keyword. Needle: allOf: - anyOf: [{type: string}, {type: number}, {type: boolean}] - {type: string, maxLength: 1000} # A union written beside the allOf is one of its conjuncts as one on an - # entry is, so this is the string Needle is. + # entry is, so this is the string Needle is, keeping its anyOf alike. NeedleBeside: allOf: [{type: string, maxLength: 1000}] anyOf: [{type: string}, {type: number}, {type: boolean}] diff --git a/testdata/conformance/openapi/allof-union-branch.golden.json b/testdata/conformance/openapi/allof-union-branch.golden.json index 51f5d2767..971ac6de5 100644 --- a/testdata/conformance/openapi/allof-union-branch.golden.json +++ b/testdata/conformance/openapi/allof-union-branch.golden.json @@ -365,7 +365,7 @@ "hint": "without_data" }, "type": { - "target": "type/composed/components/schemas/Kennel/properties/resident/allOf/1/oneOf/0", + "target": "type/composed/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/0", "nullable": false }, "docs": {} @@ -375,7 +375,7 @@ "hint": "with_data" }, "type": { - "target": "type/composed/components/schemas/Kennel/properties/resident/allOf/1/oneOf/1", + "target": "type/composed/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/1", "nullable": false }, "docs": {} @@ -422,7 +422,7 @@ "hint": "without_data" }, "type": { - "target": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/0", + "target": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/0", "nullable": false }, "docs": {} @@ -432,7 +432,7 @@ "hint": "with_data" }, "type": { - "target": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/1", + "target": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/1", "nullable": false }, "docs": {} @@ -464,9 +464,9 @@ "mediaType": "image/png" } }, - "type/composed/components/schemas/App/allOf/1/oneOf/0": { + "type/composed/components/schemas/App/allOf/-/1/oneOf/0": { "kind": "model", - "id": "type/composed/components/schemas/App/allOf/1/oneOf/0", + "id": "type/composed/components/schemas/App/allOf/-/1/oneOf/0", "name": { "hint": "app_variant_0" }, @@ -475,7 +475,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/App/allOf/1/oneOf/0" + "pointer": "/components/schemas/App/allOf/-/1/oneOf/0" }, "properties": [ { @@ -514,9 +514,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/App/allOf/1/oneOf/1": { + "type/composed/components/schemas/App/allOf/-/1/oneOf/1": { "kind": "model", - "id": "type/composed/components/schemas/App/allOf/1/oneOf/1", + "id": "type/composed/components/schemas/App/allOf/-/1/oneOf/1", "name": { "hint": "app_variant_1" }, @@ -525,7 +525,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/App/allOf/1/oneOf/1" + "pointer": "/components/schemas/App/allOf/-/1/oneOf/1" }, "properties": [ { @@ -564,41 +564,18 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/AppRequest/allOf/0/oneOf/0": { + "type/composed/components/schemas/AppRequest/allOf/-/0/oneOf/0": { "kind": "model", - "id": "type/composed/components/schemas/AppRequest/allOf/0/oneOf/0", + "id": "type/composed/components/schemas/AppRequest/allOf/-/0/oneOf/0", "name": { "hint": "app_request_variant_0" }, "anonymous": true, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:anyOf": { - "reason": "validation_only", - "value": [ - { - "required": [ - "breakout" - ], - "type": "object" - }, - { - "required": [ - "priority" - ], - "type": "object" - } - ], - "provenance": { - "source": 0, - "pointer": "/components/schemas/AppRequest/allOf/1/anyOf" - } - } - }, "provenance": { "source": 0, - "pointer": "/components/schemas/AppRequest/allOf/0/oneOf/0" + "pointer": "/components/schemas/AppRequest/allOf/-/0/oneOf/0" }, "properties": [ { @@ -664,41 +641,18 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/AppRequest/allOf/0/oneOf/1": { + "type/composed/components/schemas/AppRequest/allOf/-/0/oneOf/1": { "kind": "model", - "id": "type/composed/components/schemas/AppRequest/allOf/0/oneOf/1", + "id": "type/composed/components/schemas/AppRequest/allOf/-/0/oneOf/1", "name": { "hint": "app_request_variant_1" }, "anonymous": true, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:anyOf": { - "reason": "validation_only", - "value": [ - { - "required": [ - "breakout" - ], - "type": "object" - }, - { - "required": [ - "priority" - ], - "type": "object" - } - ], - "provenance": { - "source": 0, - "pointer": "/components/schemas/AppRequest/allOf/1/anyOf" - } - } - }, "provenance": { "source": 0, - "pointer": "/components/schemas/AppRequest/allOf/0/oneOf/1" + "pointer": "/components/schemas/AppRequest/allOf/-/0/oneOf/1" }, "properties": [ { @@ -804,9 +758,9 @@ "closed": true, "inputOnly": false }, - "type/composed/components/schemas/Kennel/properties/resident/allOf/1/oneOf/0": { + "type/composed/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/0": { "kind": "model", - "id": "type/composed/components/schemas/Kennel/properties/resident/allOf/1/oneOf/0", + "id": "type/composed/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/0", "name": { "hint": "resident_without_data" }, @@ -815,7 +769,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Kennel/properties/resident/allOf/1/oneOf/0" + "pointer": "/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/0" }, "base": { "target": "type/openapi/components/schemas/Pet", @@ -831,9 +785,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/Kennel/properties/resident/allOf/1/oneOf/1": { + "type/composed/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/1": { "kind": "model", - "id": "type/composed/components/schemas/Kennel/properties/resident/allOf/1/oneOf/1", + "id": "type/composed/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/1", "name": { "hint": "resident_with_data" }, @@ -842,7 +796,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Kennel/properties/resident/allOf/1/oneOf/1" + "pointer": "/components/schemas/Kennel/properties/resident/allOf/-/1/oneOf/1" }, "base": { "target": "type/openapi/components/schemas/Pet", @@ -858,9 +812,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/Payment/allOf/1/oneOf/0": { + "type/composed/components/schemas/Payment/allOf/-/1/oneOf/0": { "kind": "model", - "id": "type/composed/components/schemas/Payment/allOf/1/oneOf/0", + "id": "type/composed/components/schemas/Payment/allOf/-/1/oneOf/0", "name": { "hint": "payment_card" }, @@ -869,7 +823,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Payment/allOf/1/oneOf/0" + "pointer": "/components/schemas/Payment/allOf/-/1/oneOf/0" }, "properties": [ { @@ -908,9 +862,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/Payment/allOf/1/oneOf/1": { + "type/composed/components/schemas/Payment/allOf/-/1/oneOf/1": { "kind": "model", - "id": "type/composed/components/schemas/Payment/allOf/1/oneOf/1", + "id": "type/composed/components/schemas/Payment/allOf/-/1/oneOf/1", "name": { "hint": "payment_bank" }, @@ -919,7 +873,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Payment/allOf/1/oneOf/1" + "pointer": "/components/schemas/Payment/allOf/-/1/oneOf/1" }, "properties": [ { @@ -958,9 +912,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/Record/allOf/0/anyOf/0": { + "type/composed/components/schemas/Record/allOf/-/0/anyOf/0": { "kind": "model", - "id": "type/composed/components/schemas/Record/allOf/0/anyOf/0", + "id": "type/composed/components/schemas/Record/allOf/-/0/anyOf/0", "name": { "hint": "record_without_data" }, @@ -969,7 +923,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Record/allOf/0/anyOf/0" + "pointer": "/components/schemas/Record/allOf/-/0/anyOf/0" }, "properties": [ { @@ -1008,9 +962,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/Record/allOf/0/anyOf/1": { + "type/composed/components/schemas/Record/allOf/-/0/anyOf/1": { "kind": "model", - "id": "type/composed/components/schemas/Record/allOf/0/anyOf/1", + "id": "type/composed/components/schemas/Record/allOf/-/0/anyOf/1", "name": { "hint": "record_with_data" }, @@ -1019,7 +973,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Record/allOf/0/anyOf/1" + "pointer": "/components/schemas/Record/allOf/-/0/anyOf/1" }, "properties": [ { @@ -1058,9 +1012,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/Refund/allOf/1/oneOf/0": { + "type/composed/components/schemas/Refund/allOf/-/1/oneOf/0": { "kind": "model", - "id": "type/composed/components/schemas/Refund/allOf/1/oneOf/0", + "id": "type/composed/components/schemas/Refund/allOf/-/1/oneOf/0", "name": { "hint": "refund_card" }, @@ -1069,7 +1023,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Refund/allOf/1/oneOf/0" + "pointer": "/components/schemas/Refund/allOf/-/1/oneOf/0" }, "properties": [ { @@ -1108,9 +1062,9 @@ "positional": false, "inputOnly": false }, - "type/composed/components/schemas/Refund/allOf/1/oneOf/1": { + "type/composed/components/schemas/Refund/allOf/-/1/oneOf/1": { "kind": "model", - "id": "type/composed/components/schemas/Refund/allOf/1/oneOf/1", + "id": "type/composed/components/schemas/Refund/allOf/-/1/oneOf/1", "name": { "hint": "refund_bank" }, @@ -1119,7 +1073,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Refund/allOf/1/oneOf/1" + "pointer": "/components/schemas/Refund/allOf/-/1/oneOf/1" }, "properties": [ { @@ -1158,9 +1112,9 @@ "positional": false, "inputOnly": false }, - "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/0": { + "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/0": { "kind": "model", - "id": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/0", + "id": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/0", "name": { "hint": "upload_request_without_data" }, @@ -1169,7 +1123,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/0" + "pointer": "/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/0" }, "properties": [ { @@ -1235,9 +1189,9 @@ "positional": false, "inputOnly": false }, - "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/1": { + "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/1": { "kind": "model", - "id": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/1", + "id": "type/composed/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/1", "name": { "hint": "upload_request_with_data" }, @@ -1246,7 +1200,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/1/oneOf/1" + "pointer": "/paths/~1upload/post/requestBody/content/multipart~1form-data/schema/allOf/-/1/oneOf/1" }, "properties": [ { @@ -1332,7 +1286,7 @@ "hint": "variant_0" }, "type": { - "target": "type/composed/components/schemas/App/allOf/1/oneOf/0", + "target": "type/composed/components/schemas/App/allOf/-/1/oneOf/0", "nullable": false }, "docs": {} @@ -1342,7 +1296,7 @@ "hint": "variant_1" }, "type": { - "target": "type/composed/components/schemas/App/allOf/1/oneOf/1", + "target": "type/composed/components/schemas/App/allOf/-/1/oneOf/1", "nullable": false }, "docs": {} @@ -1363,6 +1317,29 @@ "anonymous": false, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:anyOf": { + "reason": "validation_only", + "value": [ + { + "required": [ + "breakout" + ], + "type": "object" + }, + { + "required": [ + "priority" + ], + "type": "object" + } + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/AppRequest/allOf/1/anyOf" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/AppRequest" @@ -1373,7 +1350,7 @@ "hint": "variant_0" }, "type": { - "target": "type/composed/components/schemas/AppRequest/allOf/0/oneOf/0", + "target": "type/composed/components/schemas/AppRequest/allOf/-/0/oneOf/0", "nullable": false }, "docs": {} @@ -1383,7 +1360,7 @@ "hint": "variant_1" }, "type": { - "target": "type/composed/components/schemas/AppRequest/allOf/0/oneOf/1", + "target": "type/composed/components/schemas/AppRequest/allOf/-/0/oneOf/1", "nullable": false }, "docs": {} @@ -1814,7 +1791,7 @@ "hint": "card" }, "type": { - "target": "type/composed/components/schemas/Payment/allOf/1/oneOf/0", + "target": "type/composed/components/schemas/Payment/allOf/-/1/oneOf/0", "nullable": false }, "docs": {} @@ -1824,7 +1801,7 @@ "hint": "bank" }, "type": { - "target": "type/composed/components/schemas/Payment/allOf/1/oneOf/1", + "target": "type/composed/components/schemas/Payment/allOf/-/1/oneOf/1", "nullable": false }, "docs": {} @@ -1835,8 +1812,8 @@ "discriminator": { "propertyName": "method", "mapping": { - "Bank": "type/composed/components/schemas/Payment/allOf/1/oneOf/1", - "Card": "type/composed/components/schemas/Payment/allOf/1/oneOf/0" + "Bank": "type/composed/components/schemas/Payment/allOf/-/1/oneOf/1", + "Card": "type/composed/components/schemas/Payment/allOf/-/1/oneOf/0" }, "inferred": false }, @@ -1891,8 +1868,12 @@ "discriminator": { "property": "property/openapi/components/schemas/Pet/properties/kind", "mapping": { + "Pet": "type/openapi/components/schemas/Pet", "dog": "type/openapi/components/schemas/Dog" }, + "decodeOnlyRoutes": { + "Dog": "type/openapi/components/schemas/Dog" + }, "inferred": false }, "inputOnly": false @@ -1917,7 +1898,7 @@ "hint": "without_data" }, "type": { - "target": "type/composed/components/schemas/Record/allOf/0/anyOf/0", + "target": "type/composed/components/schemas/Record/allOf/-/0/anyOf/0", "nullable": false }, "docs": {} @@ -1927,7 +1908,7 @@ "hint": "with_data" }, "type": { - "target": "type/composed/components/schemas/Record/allOf/0/anyOf/1", + "target": "type/composed/components/schemas/Record/allOf/-/0/anyOf/1", "nullable": false }, "docs": {} @@ -1958,7 +1939,7 @@ "hint": "card" }, "type": { - "target": "type/composed/components/schemas/Refund/allOf/1/oneOf/0", + "target": "type/composed/components/schemas/Refund/allOf/-/1/oneOf/0", "nullable": false }, "docs": {} @@ -1968,7 +1949,7 @@ "hint": "bank" }, "type": { - "target": "type/composed/components/schemas/Refund/allOf/1/oneOf/1", + "target": "type/composed/components/schemas/Refund/allOf/-/1/oneOf/1", "nullable": false }, "docs": {} @@ -1979,8 +1960,8 @@ "discriminator": { "propertyName": "method", "mapping": { - "Bank": "type/composed/components/schemas/Refund/allOf/1/oneOf/1", - "Card": "type/composed/components/schemas/Refund/allOf/1/oneOf/0" + "Bank": "type/composed/components/schemas/Refund/allOf/-/1/oneOf/1", + "Card": "type/composed/components/schemas/Refund/allOf/-/1/oneOf/0" }, "inferred": false }, @@ -2140,20 +2121,20 @@ }, { "severity": "info", - "code": "openapi/validation-only-keyword", - "message": "validation-only keyword \"anyOf\" kept verbatim under Unmodeled", + "code": "openapi/composition-lowering", + "message": "oneOf/anyOf written on an allOf entry conjoins with the rest of the composition; the composition is distributed across the union variants", "provenance": { "source": 0, - "pointer": "/components/schemas/AppRequest/allOf/1" + "pointer": "/components/schemas/AppRequest" } }, { "severity": "info", - "code": "openapi/composition-lowering", - "message": "oneOf/anyOf written on an allOf entry conjoins with the rest of the composition; the composition is distributed across the union variants", + "code": "openapi/validation-only-keyword", + "message": "validation-only keyword \"anyOf\" kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/AppRequest" + "pointer": "/components/schemas/AppRequest/allOf/1" } }, { @@ -2224,7 +2205,7 @@ { "format": "openapi@3.1", "path": "allof-union-branch.yaml", - "hash": "4ba906ba6a6ea4fb91e4b0ad0f754c4e90b0ed4e45d010623031496b1ebab60d" + "hash": "4642ef95065d4419ac4a73e4f808978c9a0939b854ff801b19765d2f8b82d4c8" } ] } diff --git a/testdata/conformance/openapi/allof-union-branch.yaml b/testdata/conformance/openapi/allof-union-branch.yaml index 7522b8a18..5af21b76b 100644 --- a/testdata/conformance/openapi/allof-union-branch.yaml +++ b/testdata/conformance/openapi/allof-union-branch.yaml @@ -52,8 +52,8 @@ components: - type: object required: [managed_app_id] properties: {managed_app_id: {type: string}} - # Of two union entries, one only narrows the body: it stays with its - # entry on each variant, and the other distributes. + # Of two union entries, one only narrows the body: it is kept once, on + # the Union, and the other distributes. AppRequest: type: object allOf: diff --git a/testdata/conformance/openapi/allof-value-set-beside-entry.golden.json b/testdata/conformance/openapi/allof-value-set-beside-entry.golden.json index a6fd219dd..6ab1861b8 100644 --- a/testdata/conformance/openapi/allof-value-set-beside-entry.golden.json +++ b/testdata/conformance/openapi/allof-value-set-beside-entry.golden.json @@ -499,14 +499,6 @@ "source": 0, "pointer": "/components/schemas/BesideTyped/allOf" } - }, - "openapi:type": { - "reason": "degraded_lowering", - "value": "object", - "provenance": { - "source": 0, - "pointer": "/components/schemas/BesideTyped/type" - } } }, "provenance": { @@ -600,15 +592,6 @@ "pointer": "/components/schemas/BesideTyped" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"union\", which has no home for type declared beside it; kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/BesideTyped" - } - }, { "severity": "info", "code": "openapi/degraded-construct", diff --git a/testdata/conformance/openapi/anyof-discriminated.golden.json b/testdata/conformance/openapi/anyof-discriminated.golden.json index 6d1cac408..ff4f03fc0 100644 --- a/testdata/conformance/openapi/anyof-discriminated.golden.json +++ b/testdata/conformance/openapi/anyof-discriminated.golden.json @@ -269,6 +269,10 @@ "labelled": "type/openapi/components/schemas/Labelled", "named": "type/openapi/components/schemas/Named" }, + "decodeOnlyRoutes": { + "Labelled": "type/openapi/components/schemas/Labelled", + "Named": "type/openapi/components/schemas/Named" + }, "inferred": false }, "closed": true, diff --git a/testdata/conformance/openapi/codeclared-keywords.golden.json b/testdata/conformance/openapi/codeclared-keywords.golden.json index 7c916d946..283bcd6b1 100644 --- a/testdata/conformance/openapi/codeclared-keywords.golden.json +++ b/testdata/conformance/openapi/codeclared-keywords.golden.json @@ -131,6 +131,21 @@ "source": 0, "pointer": "/components/schemas/BothCombinators/anyOf" } + }, + "openapi:oneOf": { + "reason": "degraded_lowering", + "value": [ + { + "type": "string" + }, + { + "type": "integer" + } + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/BothCombinators/oneOf" + } } }, "provenance": { @@ -138,16 +153,6 @@ "pointer": "/components/schemas/BothCombinators" }, "variants": [ - { - "name": { - "hint": "variant_0" - }, - "type": { - "target": "type/primitive/string", - "nullable": false - }, - "docs": {} - }, { "name": { "hint": "variant_1" @@ -288,7 +293,7 @@ "flags": false }, "type/openapi/components/schemas/NullableWithCombinators": { - "kind": "union", + "kind": "scalar", "id": "type/openapi/components/schemas/NullableWithCombinators", "name": { "source": "NullableWithCombinators", @@ -312,28 +317,43 @@ "source": 0, "pointer": "/components/schemas/NullableWithCombinators/anyOf" } + }, + "openapi:oneOf": { + "reason": "degraded_lowering", + "value": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/NullableWithCombinators/oneOf" + } } }, "provenance": { "source": 0, "pointer": "/components/schemas/NullableWithCombinators" }, - "variants": [ - { - "name": { - "hint": "variant_0" - }, - "type": { - "target": "type/primitive/string", - "nullable": false - }, - "docs": {} - } - ], - "exclusive": true, - "wireTagged": false, - "closed": true, - "inputOnly": false + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/primitive/any": { + "kind": "primitive", + "id": "type/primitive/any", + "name": {}, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": -1 + }, + "primitiveKind": "any" }, "type/primitive/integer": { "kind": "primitive", @@ -376,8 +396,8 @@ "diagnostics": [ { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (enum: string, allOf/0: object), so no instance satisfies this schema, which the enum it lowered as cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the enum and every allOf entry (enum: [\"a\", \"b\"], allOf/0: object); lowered as its enum — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/NarrowedEnum" @@ -394,8 +414,8 @@ }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (const: string, allOf/0: object), so no instance satisfies this schema, which the const it lowered as cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the const and every allOf entry (const: \"a\", allOf/0: object); lowered as its const — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/NarrowedConst" @@ -429,18 +449,18 @@ } }, { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "oneOf and anyOf are both declared here and conjoin, and one Union carries one branch set; this position lowered as its oneOf, with anyOf kept verbatim under Unmodeled", + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "1 of the 2 branches of this oneOf shares no value with the rest of the schema (oneOf/0: string), so no instance satisfies it: the oneOf is kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/NullableWithCombinators" + "pointer": "/components/schemas/BothCombinators/oneOf" } }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this schema share no value (oneOf: string, anyOf: number or boolean), so no instance satisfies this schema, which the union it lowered as cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the oneOf and the anyOf (oneOf: string, anyOf: number or boolean); lowered as a node of kind \"scalar\", its oneOf and anyOf kept verbatim under Unmodeled — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/NullableWithCombinators" @@ -451,7 +471,7 @@ { "format": "openapi@3.1", "path": "codeclared-keywords.yaml", - "hash": "e1034b898f0d09ce7b3bc80f74e0e9bc50de574faf2aff3ac2dfd0e974e771f0" + "hash": "0554aa3a25a4abf4b435660b74b6be437439fb51a99e811f7df4e6d4113ed0c1" } ] } diff --git a/testdata/conformance/openapi/codeclared-keywords.yaml b/testdata/conformance/openapi/codeclared-keywords.yaml index 300771f30..ac52e1730 100644 --- a/testdata/conformance/openapi/codeclared-keywords.yaml +++ b/testdata/conformance/openapi/codeclared-keywords.yaml @@ -34,7 +34,8 @@ components: enum: [a, b] # Two union combinators at one level conjoin: the value matches exactly one # of the oneOf branches AND at least one of the anyOf branches. One ir.Union - # carries one branch set, so oneOf becomes the union and anyOf is kept. + # carries one branch set, so oneOf becomes the union and anyOf is kept. No + # string is a number or a boolean, so the string branch is no variant. BothCombinators: oneOf: - {type: string} @@ -42,10 +43,9 @@ components: anyOf: - {type: number} - {type: boolean} - # A {X, null} oneOf normally collapses to nullable X, which would resolve - # this position straight to the shared string primitive and leave the - # co-declared anyOf nowhere of its own to sit. With both combinators written - # it stays a Union — of the one non-null branch — and keeps the anyOf on it. + # A {X, null} oneOf normally collapses to nullable X. No string or null is a + # number or a boolean, so no branch of the oneOf shares a value with the + # anyOf: the position is the top type keeping both unions. NullableWithCombinators: oneOf: - {type: string} diff --git a/testdata/conformance/openapi/constraints.golden.json b/testdata/conformance/openapi/constraints.golden.json index 4f887de50..119fe3d7a 100644 --- a/testdata/conformance/openapi/constraints.golden.json +++ b/testdata/conformance/openapi/constraints.golden.json @@ -608,7 +608,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"primitive\", which has no home for maximum, minimum declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"scalar\", which has no home for maximum, minimum declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/S/properties/id" @@ -644,7 +644,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"primitive\", which has no home for maxLength declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"scalar\", which has no home for maxLength declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Port" diff --git a/testdata/conformance/openapi/discriminated-union-beside-model.golden.json b/testdata/conformance/openapi/discriminated-union-beside-model.golden.json index b2ca4cb48..d2f41377c 100644 --- a/testdata/conformance/openapi/discriminated-union-beside-model.golden.json +++ b/testdata/conformance/openapi/discriminated-union-beside-model.golden.json @@ -59,52 +59,6 @@ } ], "types": { - "type/anonymous/components/schemas/Vehicle/type/0": { - "kind": "model", - "id": "type/anonymous/components/schemas/Vehicle/type/0", - "name": { - "hint": "vehicle" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Vehicle/type/0" - }, - "properties": [ - { - "id": "property/openapi/components/schemas/Vehicle/type/0/properties/kind", - "name": { - "source": "kind", - "canonical": "kind" - }, - "wireName": "kind", - "type": { - "target": "type/primitive/string", - "nullable": false - }, - "required": false, - "clientOptional": false, - "defaultAdded": false, - "visibility": { - "invisibleInEveryLifecycle": false - }, - "flatten": false, - "eventHeader": false, - "eventPayload": false, - "secret": false, - "docs": {}, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Vehicle/type/0/properties/kind" - } - } - ], - "abstract": false, - "positional": false, - "inputOnly": false - }, "type/composed/components/schemas/Bird/oneOf": { "kind": "union", "id": "type/composed/components/schemas/Bird/oneOf", @@ -145,6 +99,56 @@ "closed": true, "inputOnly": false }, + "type/composed/components/schemas/Vehicle/oneOf/0": { + "kind": "model", + "id": "type/composed/components/schemas/Vehicle/oneOf/0", + "name": { + "hint": "vehicle_car" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Vehicle/oneOf/0" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Vehicle/properties/kind", + "name": { + "source": "kind", + "canonical": "kind" + }, + "wireName": "kind", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Vehicle/properties/kind" + } + } + ], + "base": { + "target": "type/openapi/components/schemas/Car", + "nullable": false + }, + "abstract": false, + "positional": false, + "inputOnly": false + }, "type/openapi/components/schemas/Animal": { "kind": "model", "id": "type/openapi/components/schemas/Animal", @@ -181,8 +185,12 @@ "discriminator": { "propertyName": "kind", "mapping": { + "Animal": "type/openapi/components/schemas/Animal", "bird": "type/openapi/components/schemas/Bird" }, + "decodeOnlyRoutes": { + "Bird": "type/openapi/components/schemas/Bird" + }, "inferred": false }, "inputOnly": false @@ -620,20 +628,17 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:discriminator": { - "reason": "degraded_lowering", + "openapi:discriminator/mapping": { + "reason": "no_ir_home", "value": { - "mapping": { - "cat": "#/components/schemas/Cat" - }, - "propertyName": "kind" + "cat": "#/components/schemas/Cat" }, "targets": { - "/mapping/cat": "type/openapi/components/schemas/Cat" + "/cat": "type/openapi/components/schemas/Cat" }, "provenance": { "source": 0, - "pointer": "/components/schemas/Mixed/discriminator" + "pointer": "/components/schemas/Mixed/discriminator/mapping" } }, "openapi:oneOf": { @@ -662,6 +667,14 @@ }, "abstract": false, "positional": false, + "discriminator": { + "propertyName": "kind", + "mapping": { + "Kitten": "type/openapi/components/schemas/Kitten", + "Mixed": "type/openapi/components/schemas/Mixed" + }, + "inferred": false + }, "inputOnly": false }, "type/openapi/components/schemas/Pet": { @@ -708,6 +721,9 @@ "Dog": "type/openapi/components/schemas/Dog", "cat": "type/openapi/components/schemas/Cat" }, + "decodeOnlyRoutes": { + "Cat": "type/openapi/components/schemas/Cat" + }, "inferred": false }, "closed": true, @@ -753,8 +769,13 @@ "discriminator": { "propertyName": "kind", "mapping": { + "Shape": "type/openapi/components/schemas/Shape", + "Square": "type/openapi/components/schemas/Square", "circle": "type/openapi/components/schemas/Circle" }, + "decodeOnlyRoutes": { + "Circle": "type/openapi/components/schemas/Circle" + }, "inferred": false }, "inputOnly": false @@ -821,39 +842,6 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:discriminator": { - "reason": "degraded_lowering", - "value": { - "mapping": { - "car": "#/components/schemas/Car" - }, - "propertyName": "kind" - }, - "targets": { - "/mapping/car": "type/openapi/components/schemas/Car" - }, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Vehicle/discriminator" - } - }, - "openapi:oneOf": { - "reason": "degraded_lowering", - "value": [ - { - "$ref": "#/components/schemas/Car" - } - ], - "targets": { - "/0/$ref": "type/openapi/components/schemas/Car" - }, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Vehicle/oneOf" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/Vehicle" @@ -861,27 +849,27 @@ "variants": [ { "name": { - "hint": "object" + "hint": "car" }, "type": { - "target": "type/anonymous/components/schemas/Vehicle/type/0", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "string" - }, - "type": { - "target": "type/primitive/string", + "target": "type/composed/components/schemas/Vehicle/oneOf/0", "nullable": false }, "docs": {} } ], "exclusive": true, - "wireTagged": false, + "wireTagged": true, + "discriminator": { + "propertyName": "kind", + "mapping": { + "car": "type/composed/components/schemas/Vehicle/oneOf/0" + }, + "decodeOnlyRoutes": { + "Car": "type/composed/components/schemas/Vehicle/oneOf/0" + }, + "inferred": false + }, "closed": true, "inputOnly": false }, @@ -986,8 +974,8 @@ }, { "severity": "info", - "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"union\", which has no home for discriminator declared beside it; kept verbatim under Unmodeled", + "code": "openapi/composition-lowering", + "message": "oneOf/anyOf co-declared with structural keywords; the composition is distributed across the union variants", "provenance": { "source": 0, "pointer": "/components/schemas/Vehicle" @@ -995,20 +983,20 @@ }, { "severity": "info", - "code": "openapi/degraded-construct", - "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and the body is not a model, so it carries no composition to distribute into; union branches kept verbatim under Unmodeled", + "code": "openapi/unhomed-construct", + "message": "the mapping routes \"cat\" to \"#/components/schemas/Cat\", which is neither the model holding the discriminator nor a subtype of it; the entry is kept verbatim under Unmodeled, the other routes typed", "provenance": { "source": 0, - "pointer": "/components/schemas/Vehicle" + "pointer": "/components/schemas/Mixed/discriminator/mapping/cat" } }, { "severity": "info", - "code": "openapi/degraded-construct", - "message": "the discriminator routes to a type that is not a subtype of the model holding it, so it cannot stay there; kept verbatim under Unmodeled beside the union it was written for", + "code": "openapi/unhomed-construct", + "message": "the discriminator beside this union routes this branch by its component name, \"Cat\", which names a type that is neither the model holding the discriminator nor a subtype of it; no route is written for it", "provenance": { "source": 0, - "pointer": "/components/schemas/Mixed/discriminator" + "pointer": "/components/schemas/Mixed/oneOf/1" } } ], @@ -1016,7 +1004,7 @@ { "format": "openapi@3.1", "path": "discriminated-union-beside-model.yaml", - "hash": "68c529dcf191e9916ca4b715d6e70cb0f3f35b492899ab31e354dc6a638de6f7" + "hash": "81755c813640ae11b5ca1775933151a9ca5986ccf66b7c9e97c6f6fbb6c5a1d7" } ] } diff --git a/testdata/conformance/openapi/discriminated-union-beside-model.yaml b/testdata/conformance/openapi/discriminated-union-beside-model.yaml index 2f657ea81..a205461d0 100644 --- a/testdata/conformance/openapi/discriminated-union-beside-model.yaml +++ b/testdata/conformance/openapi/discriminated-union-beside-model.yaml @@ -95,9 +95,9 @@ components: type: object properties: caw: {type: string} - # A multi-typed body lowers to a union with one variant per type. No schema - # can name its object variant, so Car is no subtype of it, and the variant - # holds no discriminator: it is kept verbatim on Vehicle, beside the union. + # A multi-typed body beside a oneOf of one object: no string is a Car, so + # the position is the union of the Car the body composes, which the + # discriminator routes. Vehicle: type: [object, string] properties: diff --git a/testdata/conformance/openapi/discriminated-union-distributed.golden.json b/testdata/conformance/openapi/discriminated-union-distributed.golden.json index 0d3ad382a..321e559fe 100644 --- a/testdata/conformance/openapi/discriminated-union-distributed.golden.json +++ b/testdata/conformance/openapi/discriminated-union-distributed.golden.json @@ -461,6 +461,10 @@ "bank": "type/composed/components/schemas/Payment/oneOf/1", "card": "type/composed/components/schemas/Payment/oneOf/0" }, + "decodeOnlyRoutes": { + "Bank": "type/composed/components/schemas/Payment/oneOf/1", + "Card": "type/composed/components/schemas/Payment/oneOf/0" + }, "inferred": false }, "closed": true, diff --git a/testdata/conformance/openapi/discriminator-alias-mapping.golden.json b/testdata/conformance/openapi/discriminator-alias-mapping.golden.json index 8cc28e524..06188b78e 100644 --- a/testdata/conformance/openapi/discriminator-alias-mapping.golden.json +++ b/testdata/conformance/openapi/discriminator-alias-mapping.golden.json @@ -188,6 +188,7 @@ }, "abstract": false, "positional": false, + "discriminatorValue": "CatAlias", "inputOnly": false }, "type/openapi/components/schemas/CatNote": { @@ -315,11 +316,18 @@ "discriminator": { "property": "property/openapi/components/schemas/Pet/properties/petType", "mapping": { + "CatAlias": "type/openapi/components/schemas/CatAlias", + "CatNote": "type/openapi/components/schemas/CatNote", + "Pet": "type/openapi/components/schemas/Pet", "alpha": "type/openapi/components/schemas/Dog", "cat": "type/openapi/components/schemas/Cat", "kitten": "type/openapi/components/schemas/Cat", "zulu": "type/openapi/components/schemas/Dog" }, + "decodeOnlyRoutes": { + "Cat": "type/openapi/components/schemas/Cat", + "Dog": "type/openapi/components/schemas/Dog" + }, "inferred": false }, "inputOnly": false @@ -369,6 +377,10 @@ "cat": "type/openapi/components/schemas/Cat", "kitten": "type/openapi/components/schemas/Cat" }, + "decodeOnlyRoutes": { + "Bird": "type/openapi/components/schemas/Bird", + "Cat": "type/openapi/components/schemas/Cat" + }, "inferred": false }, "closed": true, diff --git a/testdata/conformance/openapi/discriminator-aliased-branch.golden.json b/testdata/conformance/openapi/discriminator-aliased-branch.golden.json index e1b0b99ba..a27afc285 100644 --- a/testdata/conformance/openapi/discriminator-aliased-branch.golden.json +++ b/testdata/conformance/openapi/discriminator-aliased-branch.golden.json @@ -369,6 +369,10 @@ "cat": "type/anonymous/components/schemas/Pet/oneOf/0", "dog": "type/openapi/components/schemas/Dog" }, + "decodeOnlyRoutes": { + "Cat": "type/anonymous/components/schemas/Pet/oneOf/0", + "Dog": "type/openapi/components/schemas/Dog" + }, "inferred": false }, "closed": true, @@ -429,6 +433,9 @@ "dog": "type/openapi/components/schemas/Dog", "tom": "type/anonymous/components/schemas/Twins/oneOf/0" }, + "decodeOnlyRoutes": { + "Dog": "type/openapi/components/schemas/Dog" + }, "inferred": false }, "closed": true, @@ -478,6 +485,9 @@ "Dog": "type/openapi/components/schemas/Dog", "cat": "type/anonymous/components/schemas/Unknown/oneOf/0" }, + "decodeOnlyRoutes": { + "Cat": "type/anonymous/components/schemas/Unknown/oneOf/0" + }, "inferred": false }, "closed": true, diff --git a/testdata/conformance/openapi/discriminator-decode-only.golden.json b/testdata/conformance/openapi/discriminator-decode-only.golden.json new file mode 100644 index 000000000..e18de546b --- /dev/null +++ b/testdata/conformance/openapi/discriminator-decode-only.golden.json @@ -0,0 +1,503 @@ +{ + "idSpaces": { + "auth": [ + "openapi", + "unresolved" + ], + "enum-member": [ + "anonymous", + "composed", + "openapi" + ], + "operation": [ + "openapi" + ], + "operation-group": [ + "default", + "extension", + "path-prefix", + "tags", + "webhooks" + ], + "parameter": [ + "openapi" + ], + "property": [ + "composed", + "openapi" + ], + "server": [ + "default", + "openapi" + ], + "service": [ + "openapi" + ], + "type": [ + "anonymous", + "composed", + "openapi" + ] + }, + "name": "DiscriminatorDecodeOnly", + "version": "1.0.0", + "docs": {}, + "services": [ + { + "id": "service/openapi/0", + "name": { + "source": "DiscriminatorDecodeOnly", + "canonical": "discriminator_decode_only" + }, + "docs": {}, + "servers": [ + "server/default" + ], + "provenance": { + "source": 0 + } + } + ], + "types": { + "type/anonymous/components/schemas/Hound/properties/petType": { + "kind": "literal", + "id": "type/anonymous/components/schemas/Hound/properties/petType", + "name": { + "hint": "pet_type" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Hound/properties/petType" + }, + "value": { + "kind": "string", + "string": "hound" + }, + "valueType": "string" + }, + "type/openapi/components/schemas/Cat": { + "kind": "model", + "id": "type/openapi/components/schemas/Cat", + "name": { + "source": "Cat", + "canonical": "cat" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Cat" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Cat/properties/kind", + "name": { + "source": "kind", + "canonical": "kind" + }, + "wireName": "kind", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": true, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Cat/properties/kind" + } + }, + { + "id": "property/openapi/components/schemas/Cat/properties/meow", + "name": { + "source": "meow", + "canonical": "meow" + }, + "wireName": "meow", + "type": { + "target": "type/primitive/bool", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Cat/properties/meow" + } + } + ], + "abstract": false, + "positional": false, + "inputOnly": false + }, + "type/openapi/components/schemas/Dog": { + "kind": "model", + "id": "type/openapi/components/schemas/Dog", + "name": { + "source": "Dog", + "canonical": "dog" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Dog" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Dog/properties/kind", + "name": { + "source": "kind", + "canonical": "kind" + }, + "wireName": "kind", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": true, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Dog/properties/kind" + } + }, + { + "id": "property/openapi/components/schemas/Dog/properties/bark", + "name": { + "source": "bark", + "canonical": "bark" + }, + "wireName": "bark", + "type": { + "target": "type/primitive/bool", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Dog/properties/bark" + } + } + ], + "abstract": false, + "positional": false, + "inputOnly": false + }, + "type/openapi/components/schemas/Hound": { + "kind": "model", + "id": "type/openapi/components/schemas/Hound", + "name": { + "source": "Hound", + "canonical": "hound" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Hound", + "inferred": "discriminator-inference" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Hound/properties/petType", + "name": { + "source": "petType", + "canonical": "pet_type" + }, + "wireName": "petType", + "type": { + "target": "type/anonymous/components/schemas/Hound/properties/petType", + "nullable": false + }, + "required": true, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Hound/properties/petType" + } + } + ], + "base": { + "target": "type/openapi/components/schemas/Pet", + "nullable": false + }, + "abstract": false, + "positional": false, + "discriminatorValue": "hound", + "inputOnly": false + }, + "type/openapi/components/schemas/Labrador": { + "kind": "model", + "id": "type/openapi/components/schemas/Labrador", + "name": { + "source": "Labrador", + "canonical": "labrador" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Labrador" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Labrador/properties/coat", + "name": { + "source": "coat", + "canonical": "coat" + }, + "wireName": "coat", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Labrador/properties/coat" + } + } + ], + "base": { + "target": "type/openapi/components/schemas/Pet", + "nullable": false + }, + "abstract": false, + "positional": false, + "discriminatorValue": "lab", + "inputOnly": false + }, + "type/openapi/components/schemas/Pet": { + "kind": "model", + "id": "type/openapi/components/schemas/Pet", + "name": { + "source": "Pet", + "canonical": "pet" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Pet", + "inferred": "discriminator-inference" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Pet/properties/petType", + "name": { + "source": "petType", + "canonical": "pet_type" + }, + "wireName": "petType", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": true, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Pet/properties/petType" + } + } + ], + "abstract": false, + "positional": false, + "discriminator": { + "property": "property/openapi/components/schemas/Pet/properties/petType", + "mapping": { + "Pet": "type/openapi/components/schemas/Pet", + "hound": "type/openapi/components/schemas/Hound", + "lab": "type/openapi/components/schemas/Labrador" + }, + "decodeOnlyRoutes": { + "Hound": "type/openapi/components/schemas/Hound", + "Labrador": "type/openapi/components/schemas/Labrador" + }, + "inferred": false + }, + "inputOnly": false + }, + "type/openapi/components/schemas/Pets": { + "kind": "union", + "id": "type/openapi/components/schemas/Pets", + "name": { + "source": "Pets", + "canonical": "pets" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Pets" + }, + "variants": [ + { + "name": { + "hint": "dog" + }, + "type": { + "target": "type/openapi/components/schemas/Dog", + "nullable": false + }, + "docs": {} + }, + { + "name": { + "hint": "cat" + }, + "type": { + "target": "type/openapi/components/schemas/Cat", + "nullable": false + }, + "docs": {} + } + ], + "exclusive": true, + "wireTagged": true, + "discriminator": { + "propertyName": "kind", + "mapping": { + "Cat": "type/openapi/components/schemas/Cat", + "dog": "type/openapi/components/schemas/Dog" + }, + "decodeOnlyRoutes": { + "Dog": "type/openapi/components/schemas/Dog" + }, + "inferred": false + }, + "closed": true, + "inputOnly": false + }, + "type/primitive/bool": { + "kind": "primitive", + "id": "type/primitive/bool", + "name": {}, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": -1 + }, + "primitiveKind": "bool" + }, + "type/primitive/string": { + "kind": "primitive", + "id": "type/primitive/string", + "name": {}, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": -1 + }, + "primitiveKind": "string" + } + }, + "servers": { + "server/default": { + "id": "server/default", + "name": { + "hint": "server" + }, + "urlTemplate": "/", + "description": {}, + "provenance": { + "source": 0 + } + } + }, + "diagnostics": [ + { + "severity": "info", + "code": "openapi/inferred-discriminator", + "message": "the discriminator routes this schema by its name, \"Hound\", a tag its \"petType\" rejects, admitting only \"hound\"; it carries \"hound\" instead, marked inferred", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Hound" + } + } + ], + "sources": [ + { + "format": "openapi@3.1", + "path": "discriminator-decode-only.yaml", + "hash": "7004999f275c8cdef92d2f20447693cf44c4df132d4343fc5792c70d9671cdf5" + } + ] +} diff --git a/testdata/conformance/openapi/discriminator-decode-only.yaml b/testdata/conformance/openapi/discriminator-decode-only.yaml new file mode 100644 index 000000000..bc8fb3487 --- /dev/null +++ b/testdata/conformance/openapi/discriminator-decode-only.yaml @@ -0,0 +1,52 @@ +openapi: 3.1.0 +info: {title: DiscriminatorDecodeOnly, version: "1.0.0"} +paths: {} +components: + schemas: + # OpenAPI routes a payload by the name of the component a branch names + # unless an entry keys that name, so a payload tagged Dog selects Dog + # beside the entry dog: Dog. That second route is one a decoder reads and + # no encoder writes: a decode-only route, beside the Mapping a writer + # takes a variant's tag from. + Pets: + oneOf: + - {$ref: '#/components/schemas/Dog'} + - {$ref: '#/components/schemas/Cat'} + discriminator: + propertyName: kind + mapping: + dog: '#/components/schemas/Dog' + Dog: + type: object + required: [kind] + properties: + kind: {type: string} + bark: {type: boolean} + Cat: + type: object + required: [kind] + properties: + kind: {type: string} + meow: {type: boolean} + # A hierarchy alike: Pet routes itself and each subtype by its name, and + # a subtype an entry routes under another key, or whose tag refuses its + # name, by that name for a decoder alone. + Pet: + type: object + required: [petType] + properties: + petType: {type: string} + discriminator: + propertyName: petType + mapping: + lab: '#/components/schemas/Labrador' + Labrador: + allOf: + - {$ref: '#/components/schemas/Pet'} + properties: + coat: {type: string} + Hound: + allOf: + - {$ref: '#/components/schemas/Pet'} + properties: + petType: {const: hound} diff --git a/testdata/conformance/openapi/discriminator-default-mapping.golden.json b/testdata/conformance/openapi/discriminator-default-mapping.golden.json index cbfe30dba..87dabdea9 100644 --- a/testdata/conformance/openapi/discriminator-default-mapping.golden.json +++ b/testdata/conformance/openapi/discriminator-default-mapping.golden.json @@ -211,8 +211,13 @@ "discriminator": { "property": "property/openapi/components/schemas/Pet/properties/petType", "mapping": { + "Dog": "type/openapi/components/schemas/Dog", + "Pet": "type/openapi/components/schemas/Pet", "cat": "type/openapi/components/schemas/Cat" }, + "decodeOnlyRoutes": { + "Cat": "type/openapi/components/schemas/Cat" + }, "default": "type/openapi/components/schemas/Dog", "inferred": false }, diff --git a/testdata/conformance/openapi/discriminator-inferred.golden.json b/testdata/conformance/openapi/discriminator-inferred.golden.json index 3c71bf019..9a981d4b0 100644 --- a/testdata/conformance/openapi/discriminator-inferred.golden.json +++ b/testdata/conformance/openapi/discriminator-inferred.golden.json @@ -1573,6 +1573,10 @@ "json": "type/openapi/components/schemas/JsonFormat", "text": "type/openapi/components/schemas/TextFormat" }, + "decodeOnlyRoutes": { + "JsonFormat": "type/openapi/components/schemas/JsonFormat", + "TextFormat": "type/openapi/components/schemas/TextFormat" + }, "inferred": false }, "closed": true, @@ -1848,7 +1852,8 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Shape" + "pointer": "/components/schemas/Shape", + "inferred": "discriminator-inference" }, "properties": [ { @@ -1883,6 +1888,18 @@ "positional": false, "discriminator": { "property": "property/openapi/components/schemas/Shape/properties/kind", + "mapping": { + "Shape": "type/openapi/components/schemas/Shape", + "circle": "type/openapi/components/schemas/Circle", + "hexagon": "type/openapi/components/schemas/Polygon", + "square": "type/openapi/components/schemas/Square", + "triangle": "type/openapi/components/schemas/Polygon" + }, + "decodeOnlyRoutes": { + "Circle": "type/openapi/components/schemas/Circle", + "Polygon": "type/openapi/components/schemas/Polygon", + "Square": "type/openapi/components/schemas/Square" + }, "inferred": false }, "inputOnly": false @@ -2026,6 +2043,10 @@ "json": "type/composed/components/schemas/Styled/oneOf/0", "text": "type/composed/components/schemas/Styled/oneOf/1" }, + "decodeOnlyRoutes": { + "JsonFormat": "type/composed/components/schemas/Styled/oneOf/0", + "TextFormat": "type/composed/components/schemas/Styled/oneOf/1" + }, "inferred": false }, "closed": true, diff --git a/testdata/conformance/openapi/discriminator-inheritance.golden.json b/testdata/conformance/openapi/discriminator-inheritance.golden.json index 854da70d8..07643c133 100644 --- a/testdata/conformance/openapi/discriminator-inheritance.golden.json +++ b/testdata/conformance/openapi/discriminator-inheritance.golden.json @@ -211,8 +211,13 @@ "discriminator": { "property": "property/openapi/components/schemas/Pet/properties/petType", "mapping": { + "Dog": "type/openapi/components/schemas/Dog", + "Pet": "type/openapi/components/schemas/Pet", "cat": "type/openapi/components/schemas/Cat" }, + "decodeOnlyRoutes": { + "Cat": "type/openapi/components/schemas/Cat" + }, "inferred": false }, "inputOnly": false diff --git a/testdata/conformance/openapi/discriminator-inline-subtype.golden.json b/testdata/conformance/openapi/discriminator-inline-subtype.golden.json index 75c455819..cf83196dc 100644 --- a/testdata/conformance/openapi/discriminator-inline-subtype.golden.json +++ b/testdata/conformance/openapi/discriminator-inline-subtype.golden.json @@ -423,6 +423,10 @@ "positional": false, "discriminator": { "property": "property/openapi/components/schemas/Pet/properties/petType", + "mapping": { + "Dog": "type/openapi/components/schemas/Dog", + "Pet": "type/openapi/components/schemas/Pet" + }, "inferred": false }, "inputOnly": false diff --git a/testdata/conformance/openapi/discriminator-transitive.golden.json b/testdata/conformance/openapi/discriminator-transitive.golden.json index 9e27c2c16..1cb5cc898 100644 --- a/testdata/conformance/openapi/discriminator-transitive.golden.json +++ b/testdata/conformance/openapi/discriminator-transitive.golden.json @@ -159,9 +159,15 @@ "discriminator": { "property": "property/openapi/components/schemas/Pet/properties/petType", "mapping": { + "Pet": "type/openapi/components/schemas/Pet", + "Whelp": "type/openapi/components/schemas/Whelp", "dog": "type/openapi/components/schemas/Dog", "puppy": "type/openapi/components/schemas/Puppy" }, + "decodeOnlyRoutes": { + "Dog": "type/openapi/components/schemas/Dog", + "Puppy": "type/openapi/components/schemas/Puppy" + }, "inferred": false }, "inputOnly": false diff --git a/testdata/conformance/openapi/dynamic-ref.golden.json b/testdata/conformance/openapi/dynamic-ref.golden.json index f63740ee2..47b72d27b 100644 --- a/testdata/conformance/openapi/dynamic-ref.golden.json +++ b/testdata/conformance/openapi/dynamic-ref.golden.json @@ -119,24 +119,6 @@ "pointer": "/components/schemas/Recursive/properties/children" }, "elementType": { - "target": "type/anonymous/components/schemas/Recursive/properties/children/items", - "nullable": false - } - }, - "type/anonymous/components/schemas/Recursive/properties/children/items": { - "kind": "scalar", - "id": "type/anonymous/components/schemas/Recursive/properties/children/items", - "name": { - "hint": "children_item" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Recursive/properties/children/items" - }, - "base": { "target": "type/openapi/components/schemas/Recursive", "nullable": false } diff --git a/testdata/conformance/openapi/empty-enum.golden.json b/testdata/conformance/openapi/empty-enum.golden.json index 7fe9e2a50..3bd1ccba8 100644 --- a/testdata/conformance/openapi/empty-enum.golden.json +++ b/testdata/conformance/openapi/empty-enum.golden.json @@ -177,19 +177,6 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:$ref": { - "reason": "degraded_lowering", - "value": "#/components/schemas/Base", - "targets": { - "": "type/openapi/components/schemas/Base" - }, - "provenance": { - "source": 0, - "pointer": "/components/schemas/BesideAllOf/allOf/0" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/BesideAllOf" @@ -420,15 +407,6 @@ "source": 0, "pointer": "/components/schemas/BesideAllOf" } - }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this position declares allOf beside its enum, and JSON Schema conjoins them where only one can be the value; it lowered as the enum, with the $ref of its allOf kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/BesideAllOf" - } } ], "sources": [ diff --git a/testdata/conformance/openapi/encoding-byte.golden.json b/testdata/conformance/openapi/encoding-byte.golden.json index 454baf20f..539772303 100644 --- a/testdata/conformance/openapi/encoding-byte.golden.json +++ b/testdata/conformance/openapi/encoding-byte.golden.json @@ -68,6 +68,24 @@ "anonymous": true, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:maxLength": { + "reason": "no_ir_home", + "value": 9, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/blob/maxLength" + } + }, + "openapi:minLength": { + "reason": "no_ir_home", + "value": 5, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/blob/minLength" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/Holder/properties/blob" @@ -76,11 +94,6 @@ "target": "type/primitive/bytes", "nullable": false }, - "constraints": { - "minLength": 5, - "maxLength": 9, - "uniqueItems": false - }, "encoding": { "name": "base64", "wireType": { @@ -174,6 +187,26 @@ } } }, + "diagnostics": [ + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "maxLength bounds the text a value of another kind is written as, not the value its Constraints speak of: a keyword of the text binds only text; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/blob/maxLength" + } + }, + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "minLength bounds the text a value of another kind is written as, not the value its Constraints speak of: a keyword of the text binds only text; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/blob/minLength" + } + } + ], "sources": [ { "format": "openapi@3.1", diff --git a/testdata/conformance/openapi/encoding-union-branches.golden.json b/testdata/conformance/openapi/encoding-union-branches.golden.json index c92fe4506..f1e1d3786 100644 --- a/testdata/conformance/openapi/encoding-union-branches.golden.json +++ b/testdata/conformance/openapi/encoding-union-branches.golden.json @@ -315,7 +315,7 @@ "nullable": false }, "encoding": { - "property/openapi/paths/~1multi-typed/post/requestBody/content/multipart~1form-data/schema/type/1/properties/file": { + "property/openapi/paths/~1multi-typed/post/requestBody/content/multipart~1form-data/schema/properties/file": { "inferred": "binary-inference", "contentTypes": [ "image/png" @@ -734,7 +734,7 @@ "hint": "variant_0" }, "type": { - "target": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/0", + "target": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/0", "nullable": false }, "docs": {} @@ -744,7 +744,7 @@ "hint": "variant_1" }, "type": { - "target": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/1", + "target": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/1", "nullable": false }, "docs": {} @@ -904,7 +904,7 @@ }, "properties": [ { - "id": "property/openapi/paths/~1multi-typed/post/requestBody/content/multipart~1form-data/schema/type/1/properties/file", + "id": "property/openapi/paths/~1multi-typed/post/requestBody/content/multipart~1form-data/schema/properties/file", "name": { "source": "file", "canonical": "file" @@ -927,7 +927,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/paths/~1multi-typed/post/requestBody/content/multipart~1form-data/schema/type/1/properties/file" + "pointer": "/paths/~1multi-typed/post/requestBody/content/multipart~1form-data/schema/properties/file" } } ], @@ -1267,9 +1267,9 @@ "nullable": false } }, - "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/0": { + "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/0": { "kind": "model", - "id": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/0", + "id": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/0", "name": { "hint": "composed_request_variant_0" }, @@ -1278,7 +1278,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/0" + "pointer": "/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/0" }, "base": { "target": "type/openapi/components/schemas/Common", @@ -1294,9 +1294,9 @@ "positional": false, "inputOnly": false }, - "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/1": { + "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/1": { "kind": "model", - "id": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/1", + "id": "type/composed/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/1", "name": { "hint": "composed_request_variant_1" }, @@ -1305,7 +1305,7 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/0/oneOf/1" + "pointer": "/paths/~1composed/post/requestBody/content/multipart~1form-data/schema/allOf/-/0/oneOf/1" }, "base": { "target": "type/openapi/components/schemas/Common", diff --git a/testdata/conformance/openapi/enum-bounds.golden.json b/testdata/conformance/openapi/enum-bounds.golden.json new file mode 100644 index 000000000..90590c279 --- /dev/null +++ b/testdata/conformance/openapi/enum-bounds.golden.json @@ -0,0 +1,400 @@ +{ + "idSpaces": { + "auth": [ + "openapi", + "unresolved" + ], + "enum-member": [ + "anonymous", + "composed", + "openapi" + ], + "operation": [ + "openapi" + ], + "operation-group": [ + "default", + "extension", + "path-prefix", + "tags", + "webhooks" + ], + "parameter": [ + "openapi" + ], + "property": [ + "composed", + "openapi" + ], + "server": [ + "default", + "openapi" + ], + "service": [ + "openapi" + ], + "type": [ + "anonymous", + "composed", + "openapi" + ] + }, + "name": "EnumBounds", + "version": "1.0.0", + "docs": {}, + "services": [ + { + "id": "service/openapi/0", + "name": { + "source": "EnumBounds", + "canonical": "enum_bounds" + }, + "docs": {}, + "servers": [ + "server/default" + ], + "provenance": { + "source": 0 + } + } + ], + "types": { + "type/anonymous/components/schemas/Mixed/enum/0": { + "kind": "literal", + "id": "type/anonymous/components/schemas/Mixed/enum/0", + "name": { + "hint": "mixed_0" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Mixed/enum/0" + }, + "value": { + "kind": "string", + "string": "auto" + }, + "valueType": "string" + }, + "type/anonymous/components/schemas/Mixed/enum/1": { + "kind": "literal", + "id": "type/anonymous/components/schemas/Mixed/enum/1", + "name": { + "hint": "mixed_1" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Mixed/enum/1" + }, + "value": { + "kind": "number", + "number": "0" + }, + "valueType": "number" + }, + "type/openapi/components/schemas/Mixed": { + "kind": "union", + "id": "type/openapi/components/schemas/Mixed", + "name": { + "source": "Mixed", + "canonical": "mixed" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Mixed" + }, + "variants": [ + { + "name": { + "hint": "mixed_0" + }, + "type": { + "target": "type/anonymous/components/schemas/Mixed/enum/0", + "nullable": false + }, + "docs": {} + }, + { + "name": { + "hint": "mixed_1" + }, + "type": { + "target": "type/anonymous/components/schemas/Mixed/enum/1", + "nullable": false + }, + "docs": {} + } + ], + "exclusive": true, + "wireTagged": false, + "constraints": { + "maxLength": 4, + "uniqueItems": false + }, + "closed": true, + "inputOnly": false + }, + "type/openapi/components/schemas/Mode": { + "kind": "enum", + "id": "type/openapi/components/schemas/Mode", + "name": { + "source": "Mode", + "canonical": "mode" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Mode" + }, + "valueType": "string", + "members": [ + { + "id": "enum-member/openapi/components/schemas/Mode/string:block", + "name": { + "source": "block", + "canonical": "block" + }, + "value": { + "kind": "string", + "string": "block" + }, + "docs": {} + }, + { + "id": "enum-member/openapi/components/schemas/Mode/string:js_challenge", + "name": { + "source": "js_challenge", + "canonical": "js_challenge" + }, + "value": { + "kind": "string", + "string": "js_challenge" + }, + "docs": {} + } + ], + "closed": true, + "flags": false, + "constraints": { + "maxLength": 8, + "uniqueItems": false + } + }, + "type/openapi/components/schemas/Port": { + "kind": "enum", + "id": "type/openapi/components/schemas/Port", + "name": { + "source": "Port", + "canonical": "port" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Port" + }, + "valueType": "integer", + "members": [ + { + "id": "enum-member/openapi/components/schemas/Port/number:8e1", + "name": { + "source": "80", + "canonical": "80" + }, + "value": { + "kind": "number", + "number": "80" + }, + "docs": {} + }, + { + "id": "enum-member/openapi/components/schemas/Port/number:4.43e2", + "name": { + "source": "443", + "canonical": "443" + }, + "value": { + "kind": "number", + "number": "443" + }, + "docs": {} + } + ], + "closed": true, + "flags": false, + "constraints": { + "min": "1", + "max": "65535", + "uniqueItems": false + } + }, + "type/openapi/components/schemas/Region": { + "kind": "enum", + "id": "type/openapi/components/schemas/Region", + "name": { + "source": "Region", + "canonical": "region" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:x-extensible-enum": { + "reason": "vendor_extension", + "value": [ + "eu", + "us" + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/Region/x-extensible-enum" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Region", + "inferred": "extension-promotion" + }, + "valueType": "string", + "members": [ + { + "id": "enum-member/openapi/components/schemas/Region/string:eu", + "name": { + "source": "eu", + "canonical": "eu" + }, + "value": { + "kind": "string", + "string": "eu" + }, + "docs": {} + }, + { + "id": "enum-member/openapi/components/schemas/Region/string:us", + "name": { + "source": "us", + "canonical": "us" + }, + "value": { + "kind": "string", + "string": "us" + }, + "docs": {} + } + ], + "closed": false, + "flags": false, + "constraints": { + "minLength": 2, + "pattern": "^[a-z]+$", + "uniqueItems": false + } + }, + "type/openapi/components/schemas/Tags": { + "kind": "enum", + "id": "type/openapi/components/schemas/Tags", + "name": { + "source": "Tags", + "canonical": "tags" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:maxItems": { + "reason": "degraded_lowering", + "value": 1, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Tags/maxItems" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Tags" + }, + "valueType": "string", + "members": [ + { + "id": "enum-member/openapi/components/schemas/Tags/string:a", + "name": { + "source": "a", + "canonical": "a" + }, + "value": { + "kind": "string", + "string": "a" + }, + "docs": {} + }, + { + "id": "enum-member/openapi/components/schemas/Tags/string:b", + "name": { + "source": "b", + "canonical": "b" + }, + "value": { + "kind": "string", + "string": "b" + }, + "docs": {} + } + ], + "closed": true, + "flags": false + } + }, + "servers": { + "server/default": { + "id": "server/default", + "name": { + "hint": "server" + }, + "urlTemplate": "/", + "description": {}, + "provenance": { + "source": 0 + } + } + }, + "diagnostics": [ + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "heterogeneous or non-scalar enum lowered as a union of literals", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Mixed" + } + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "this position lowered to a node of kind \"enum\", which has no home for maxItems declared beside it; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Tags" + } + } + ], + "sources": [ + { + "format": "openapi@3.1", + "path": "enum-bounds.yaml", + "hash": "0e98bc4dac5abf22ef2d73c08451a3e7886f85525bffdfc698a18d84fa0a5fd4" + } + ] +} diff --git a/testdata/conformance/openapi/enum-bounds.yaml b/testdata/conformance/openapi/enum-bounds.yaml new file mode 100644 index 000000000..160d39e0a --- /dev/null +++ b/testdata/conformance/openapi/enum-bounds.yaml @@ -0,0 +1,31 @@ +openapi: 3.1.0 +info: {title: EnumBounds, version: "1.0.0"} +paths: {} +components: + schemas: + # A closed enum's bound can exclude a member it lists, so it is held. + Mode: + type: string + enum: [block, js_challenge] + maxLength: 8 + # An open enum's bound binds the values it does not list. + Region: + type: string + enum: [eu, us] + x-extensible-enum: [eu, us] + minLength: 2 + pattern: '^[a-z]+$' + Port: + type: integer + enum: [80, 443] + minimum: 1 + maximum: 65535 + # A mixed enum is a union of literals, which holds its bounds itself. + Mixed: + enum: [auto, 0] + maxLength: 4 + # A bound of another kind binds no member and stays kept verbatim. + Tags: + type: string + enum: [a, b] + maxItems: 1 diff --git a/testdata/conformance/openapi/enum-null-member.golden.json b/testdata/conformance/openapi/enum-null-member.golden.json index 4774981b0..fb071342e 100644 --- a/testdata/conformance/openapi/enum-null-member.golden.json +++ b/testdata/conformance/openapi/enum-null-member.golden.json @@ -528,7 +528,7 @@ }, { "severity": "warning", - "code": "openapi/degraded-construct", + "code": "openapi/unsatisfiable-schema", "message": "enum member null admits no instance: a keyword beside the enum excludes null, and JSON Schema conjoins the two; the member is dropped, and the reference admits no null", "provenance": { "source": 0, diff --git a/testdata/conformance/openapi/keywords-at-every-outcome.golden.json b/testdata/conformance/openapi/keywords-at-every-outcome.golden.json index a8fad4258..3db16e590 100644 --- a/testdata/conformance/openapi/keywords-at-every-outcome.golden.json +++ b/testdata/conformance/openapi/keywords-at-every-outcome.golden.json @@ -114,7 +114,7 @@ }, "properties": [ { - "id": "property/openapi/components/schemas/Homed/type/1/properties/a", + "id": "property/openapi/components/schemas/Homed/properties/a", "name": { "source": "a", "canonical": "a" @@ -137,7 +137,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/Homed/type/1/properties/a" + "pointer": "/components/schemas/Homed/properties/a" } } ], @@ -551,14 +551,6 @@ "source": 0, "pointer": "/components/schemas/Carrier/properties/dyn/maxItems" } - }, - "openapi:uniqueItems": { - "reason": "degraded_lowering", - "value": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Carrier/properties/dyn/uniqueItems" - } } }, "provenance": { @@ -631,7 +623,7 @@ "inputOnly": false }, "type/openapi/components/schemas/Dyn": { - "kind": "scalar", + "kind": "model", "id": "type/openapi/components/schemas/Dyn", "name": { "source": "Dyn", @@ -641,16 +633,6 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:discriminator": { - "reason": "degraded_lowering", - "value": { - "propertyName": "kind" - }, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Dyn/discriminator" - } - }, "openapi:format": { "reason": "degraded_lowering", "value": "uuid", @@ -667,7 +649,17 @@ "base": { "target": "type/openapi/components/schemas/Node", "nullable": false - } + }, + "abstract": false, + "positional": false, + "discriminator": { + "propertyName": "kind", + "mapping": { + "Dyn": "type/openapi/components/schemas/Dyn" + }, + "inferred": false + }, + "inputOnly": false }, "type/openapi/components/schemas/Homed": { "kind": "union", @@ -781,16 +773,6 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:pattern": { - "reason": "degraded_lowering", - "value": "", - "provenance": { - "source": 0, - "pointer": "/components/schemas/NoBound/pattern" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/NoBound" @@ -1026,7 +1008,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a reference to the type its $dynamicRef expands to, which has no home for discriminator, format declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"model\", which has no home for format declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Dyn" @@ -1044,7 +1026,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a reference to the type its $dynamicRef expands to, which has no home for maxItems, uniqueItems declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a reference to the type its $dynamicRef expands to, which has no home for maxItems declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Carrier/properties/dyn" @@ -1080,28 +1062,28 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"union\", which has no home for pattern declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"union\", which has no home for discriminator declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/NoBound" + "pointer": "/components/schemas/BesideAUnion" } }, { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"union\", which has no home for discriminator declared beside it; kept verbatim under Unmodeled", + "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and the body is not a model, so it carries no composition to distribute into; union branches kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/BesideAUnion" } }, { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and the body is not a model, so it carries no composition to distribute into; union branches kept verbatim under Unmodeled", + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "1 of the 2 branches of this oneOf shares no value with the rest of the schema (oneOf/1: integer), so no instance satisfies it: the oneOf is kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/BesideAUnion" + "pointer": "/components/schemas/BesideAUnion/oneOf" } } ], @@ -1109,7 +1091,7 @@ { "format": "openapi@3.1", "path": "keywords-at-every-outcome.yaml", - "hash": "894ef2858c68818440809dabd9d876121ac4546a88d9dd33ed1657604eb98d59" + "hash": "00e6359d8d29b9782bf432c145d61d9c8629f4e97d33f24af076fa6f319caa5f" } ] } diff --git a/testdata/conformance/openapi/keywords-at-every-outcome.yaml b/testdata/conformance/openapi/keywords-at-every-outcome.yaml index 977c0aaa9..7dfc22523 100644 --- a/testdata/conformance/openapi/keywords-at-every-outcome.yaml +++ b/testdata/conformance/openapi/keywords-at-every-outcome.yaml @@ -40,7 +40,7 @@ components: discriminator: propertyName: kind # The anchor is no array, so the carrier holds no collection bound beside the - # reference and keeps each verbatim. + # reference and keeps it verbatim; a false uniqueItems says nothing. Carrier: type: object properties: @@ -63,7 +63,8 @@ components: items: {type: string} discriminator: propertyName: kind - # An empty pattern fills no Constraints field, so no variant holds it. + # An empty pattern matches every string, so it says nothing: no variant + # holds it, and the union keeps none of it. NoBound: type: [string, integer] pattern: "" diff --git a/testdata/conformance/openapi/later-version-constructs.golden.json b/testdata/conformance/openapi/later-version-constructs.golden.json index 6cfca29fa..266765969 100644 --- a/testdata/conformance/openapi/later-version-constructs.golden.json +++ b/testdata/conformance/openapi/later-version-constructs.golden.json @@ -869,6 +869,10 @@ "positional": false, "discriminator": { "property": "property/openapi/components/schemas/Item/properties/kind", + "mapping": { + "Item": "type/openapi/components/schemas/Item", + "Novel": "type/openapi/components/schemas/Novel" + }, "default": "type/openapi/components/schemas/Novel", "inferred": false }, diff --git a/testdata/conformance/openapi/matrix.md b/testdata/conformance/openapi/matrix.md index c4d4ea566..338309bbd 100644 --- a/testdata/conformance/openapi/matrix.md +++ b/testdata/conformance/openapi/matrix.md @@ -27,7 +27,8 @@ witnessing it. - Witnesses: `oneof-discriminated`, `anyof-discriminated`, `discriminator-inheritance`, `discriminator-inline-subtype`, `discriminator-default-mapping`, `discriminator-transitive`, `discriminator-alias-mapping`, `discriminated-union-beside-model`, `nullable-union-discriminator`, - `discriminator-aliased-branch`, `discriminated-union-distributed`, `discriminator-inferred` + `discriminator-aliased-branch`, `discriminated-union-distributed`, `discriminator-inferred`, + `discriminator-decode-only` ### `untagged-unions` @@ -90,7 +91,7 @@ witnessing it. ### `constraints` - Witnesses: `constraints`, `numeric-precision`, `ref-collection-bounds`, `reference-bounds`, - `type-array-bounds` + `type-array-bounds`, `enum-bounds` ### `visibility` diff --git a/testdata/conformance/openapi/merge-depth-bound.golden.json b/testdata/conformance/openapi/merge-depth-bound.golden.json index 50d2cda01..58e5cfede 100644 --- a/testdata/conformance/openapi/merge-depth-bound.golden.json +++ b/testdata/conformance/openapi/merge-depth-bound.golden.json @@ -306,14 +306,6 @@ "source": 0, "pointer": "/components/schemas/Doc/readOnly" } - }, - "openapi:writeOnly": { - "reason": "no_ir_home", - "value": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Doc/writeOnly" - } } }, "provenance": { @@ -398,7 +390,7 @@ } }, "type/openapi/components/schemas/Log": { - "kind": "union", + "kind": "scalar", "id": "type/openapi/components/schemas/Log", "name": { "source": "Log", @@ -409,7 +401,7 @@ "sensitive": false, "unmodeled": { "openapi:anyOf": { - "reason": "validation_only", + "reason": "degraded_lowering", "value": [ { "type": "string" @@ -459,42 +451,35 @@ "source": 0, "pointer": "/components/schemas/Log/not" } + }, + "openapi:oneOf": { + "reason": "degraded_lowering", + "value": [ + { + "type": "string" + }, + { + "type": "integer" + } + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/Log/oneOf" + } } }, "provenance": { "source": 0, "pointer": "/components/schemas/Log" }, - "variants": [ - { - "name": { - "hint": "variant_0" - }, - "type": { - "target": "type/primitive/string", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_1" - }, - "type": { - "target": "type/primitive/integer", - "nullable": false - }, - "docs": {} - } - ], - "exclusive": true, - "wireTagged": false, + "base": { + "target": "type/primitive/string", + "nullable": false + }, "constraints": { "minLength": 1, "uniqueItems": false - }, - "closed": true, - "inputOnly": false + } }, "type/openapi/components/schemas/Obj": { "kind": "model", @@ -694,6 +679,32 @@ "anonymous": false, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:maxLength": { + "reason": "no_ir_home", + "value": 9, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Str/maxLength" + } + }, + "openapi:minLength": { + "reason": "no_ir_home", + "value": 1, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Str/minLength" + } + }, + "openapi:pattern": { + "reason": "no_ir_home", + "value": "^a", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Str/pattern" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/Str" @@ -702,12 +713,6 @@ "target": "type/primitive/bytes", "nullable": false }, - "constraints": { - "minLength": 1, - "maxLength": 9, - "pattern": "^a", - "uniqueItems": false - }, "encoding": { "name": "base64", "wireType": { @@ -1664,6 +1669,33 @@ "pointer": "/components/schemas/Str" } }, + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "maxLength bounds the text a value of another kind is written as, not the value its Constraints speak of: a keyword of the text binds only text; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Str/maxLength" + } + }, + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "minLength bounds the text a value of another kind is written as, not the value its Constraints speak of: a keyword of the text binds only text; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Str/minLength" + } + }, + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "pattern bounds the text a value of another kind is written as, not the value its Constraints speak of: a keyword of the text binds only text; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Str/pattern" + } + }, { "severity": "warning", "code": "openapi/degraded-construct", @@ -1736,15 +1768,6 @@ "pointer": "/components/schemas/Doc" } }, - { - "severity": "info", - "code": "openapi/inferred-nullable", - "message": "nullable: true is read as admitting null under the nullable-inference policy, though the dialect this schema is read in defines no nullable keyword; a reference whose null rests on it is marked inferred", - "provenance": { - "source": 0, - "pointer": "/components/schemas/Doc/nullable" - } - }, { "severity": "info", "code": "openapi/degraded-construct", @@ -1765,11 +1788,11 @@ }, { "severity": "info", - "code": "openapi/degraded-construct", - "message": "writeOnly on a type declaration binds a use of the type, not the type; it is kept verbatim under Unmodeled and applied to a referencing property, header or parameter wherever that carrier has a field for it", + "code": "openapi/inferred-nullable", + "message": "nullable: true is read as admitting null under the nullable-inference policy, though the dialect this schema is read in defines no nullable keyword; a reference whose null rests on it is marked inferred", "provenance": { "source": 0, - "pointer": "/components/schemas/Doc/writeOnly" + "pointer": "/components/schemas/Doc/nullable" } }, { @@ -1783,13 +1806,22 @@ }, { "severity": "info", - "code": "openapi/validation-only-keyword", - "message": "validation-only keyword \"anyOf\" kept verbatim under Unmodeled", + "code": "openapi/degraded-construct", + "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and the body is not a model, so it carries no composition to distribute into; union branches kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/Log" } }, + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "1 of the 2 branches of this oneOf shares no value with the rest of the schema (oneOf/1: integer), so no instance satisfies it: the oneOf is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Log/oneOf" + } + }, { "severity": "info", "code": "openapi/validation-only-keyword", diff --git a/testdata/conformance/openapi/missing-array-items.golden.json b/testdata/conformance/openapi/missing-array-items.golden.json index 5ac66e1ef..aaf3fe4a3 100644 --- a/testdata/conformance/openapi/missing-array-items.golden.json +++ b/testdata/conformance/openapi/missing-array-items.golden.json @@ -302,16 +302,6 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:type": { - "reason": "degraded_lowering", - "value": "array", - "provenance": { - "source": 0, - "pointer": "/components/schemas/Choice/type" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/Choice" @@ -566,15 +556,6 @@ "pointer": "/components/schemas/Choice" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"union\", which has no home for type declared beside it; kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/Choice" - } - }, { "severity": "warning", "code": "openapi/missing-array-items", diff --git a/testdata/conformance/openapi/multipart-encoding.golden.json b/testdata/conformance/openapi/multipart-encoding.golden.json index 36023c89c..2cfb30f0f 100644 --- a/testdata/conformance/openapi/multipart-encoding.golden.json +++ b/testdata/conformance/openapi/multipart-encoding.golden.json @@ -1017,15 +1017,14 @@ { "severity": "warning", "code": "openapi/conflicting-redeclaration", - "message": "declarations of field \"file\" disagree: incompatible types type/anonymous/components/schemas/FileList/properties/file and type/primitive/bytes; kept what the declaration at /components/schemas/FileList/properties/file says over the one at /components/schemas/UploadForm/properties/file, which stays declared on its model", + "message": "field \"file\" of /paths/~1upload-redeclared/post/requestBody/content/multipart~1form-data/schema: /components/schemas/FileList/properties/file and /components/schemas/UploadForm/properties/file disagree: incompatible types a list and bytes; chose what the first says; the second stays declared on its model", "provenance": { "source": 0, - "pointer": "/components/schemas/UploadForm/properties/file", - "node": "property/composed/paths/~1upload-redeclared/post/requestBody/content/multipart~1form-data/schema/allOf/properties/file" + "pointer": "/components/schemas/UploadForm/properties/file" }, "related": [ { - "role": "kept", + "role": "chosen", "provenance": { "source": 0, "pointer": "/components/schemas/FileList/properties/file" @@ -1034,7 +1033,8 @@ { "role": "decided", "provenance": { - "source": -1, + "source": 0, + "pointer": "/paths/~1upload-redeclared/post/requestBody/content/multipart~1form-data/schema", "node": "property/composed/paths/~1upload-redeclared/post/requestBody/content/multipart~1form-data/schema/allOf/properties/file" } } diff --git a/testdata/conformance/openapi/nullable-keyword-30.golden.json b/testdata/conformance/openapi/nullable-keyword-30.golden.json index 99f149d4a..79ffeb2d2 100644 --- a/testdata/conformance/openapi/nullable-keyword-30.golden.json +++ b/testdata/conformance/openapi/nullable-keyword-30.golden.json @@ -102,27 +102,6 @@ "closed": true, "flags": false }, - "type/anonymous/components/schemas/Holder/properties/typedComposed": { - "kind": "model", - "id": "type/anonymous/components/schemas/Holder/properties/typedComposed", - "name": { - "hint": "typed_composed" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Holder/properties/typedComposed" - }, - "base": { - "target": "type/openapi/components/schemas/Pet", - "nullable": false - }, - "abstract": false, - "positional": false, - "inputOnly": false - }, "type/anonymous/components/schemas/Holder/properties/unlisted": { "kind": "enum", "id": "type/anonymous/components/schemas/Holder/properties/unlisted", @@ -327,7 +306,7 @@ }, "wireName": "typedComposed", "type": { - "target": "type/anonymous/components/schemas/Holder/properties/typedComposed", + "target": "type/openapi/components/schemas/Pet", "nullable": true, "inferred": "nullable-inference" }, diff --git a/testdata/conformance/openapi/oneof-discriminated.golden.json b/testdata/conformance/openapi/oneof-discriminated.golden.json index 7403d9b69..9b5492de4 100644 --- a/testdata/conformance/openapi/oneof-discriminated.golden.json +++ b/testdata/conformance/openapi/oneof-discriminated.golden.json @@ -197,6 +197,10 @@ "cat": "type/openapi/components/schemas/Cat", "dog": "type/openapi/components/schemas/Dog" }, + "decodeOnlyRoutes": { + "Cat": "type/openapi/components/schemas/Cat", + "Dog": "type/openapi/components/schemas/Dog" + }, "inferred": false }, "closed": true, diff --git a/testdata/conformance/openapi/reached-outside-model.golden.json b/testdata/conformance/openapi/reached-outside-model.golden.json index 3f9db324d..7e3f4200c 100644 --- a/testdata/conformance/openapi/reached-outside-model.golden.json +++ b/testdata/conformance/openapi/reached-outside-model.golden.json @@ -320,6 +320,7 @@ "discriminator": { "property": "property/openapi/components/schemas/Kennel/properties/kind", "mapping": { + "Kennel": "type/openapi/components/schemas/Kennel", "cat": "type/anonymous/x-lib/Cat" }, "inferred": false diff --git a/testdata/conformance/openapi/ref-collection-bounds.golden.json b/testdata/conformance/openapi/ref-collection-bounds.golden.json index e008bd647..b9f0979af 100644 --- a/testdata/conformance/openapi/ref-collection-bounds.golden.json +++ b/testdata/conformance/openapi/ref-collection-bounds.golden.json @@ -399,16 +399,6 @@ "eventPayload": false, "secret": false, "docs": {}, - "unmodeled": { - "openapi:uniqueItems": { - "reason": "degraded_lowering", - "value": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Holder/properties/unstated/uniqueItems" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/Holder/properties/unstated" @@ -486,22 +476,11 @@ } } }, - "diagnostics": [ - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this position lowered to a use of one of its conjuncts, which has no home for uniqueItems declared beside it; kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/Holder/properties/unstated" - } - } - ], "sources": [ { "format": "openapi@3.1", "path": "ref-collection-bounds.yaml", - "hash": "9a888e619993f061eaf4f2023bb1527d455a31e3217091770ca9021b3dee8fec" + "hash": "6e82b85e3abb62408d9217ef1aed97760b252c46c9b8f39bcb7b922f783133fc" } ] } diff --git a/testdata/conformance/openapi/ref-collection-bounds.yaml b/testdata/conformance/openapi/ref-collection-bounds.yaml index f64e4c8f3..8c1c6349a 100644 --- a/testdata/conformance/openapi/ref-collection-bounds.yaml +++ b/testdata/conformance/openapi/ref-collection-bounds.yaml @@ -3,8 +3,8 @@ openapi: 3.1.0 # reaches the Constraints of what the position owns: the property, parameter or # header carrying it, or the alias hoisted where nothing carries it. `plain` is # the control, whose List holds its own bound and whose carrier restates nothing, -# and `unstated` writes the one value a plain bool cannot tell from unset, which -# stays verbatim. +# and `unstated` writes `uniqueItems: false`, which equals the keyword left out +# and so says nothing: it lowers as the control does. info: {title: RefCollectionBounds, version: "1.0.0"} paths: /tags/{tags}: diff --git a/testdata/conformance/openapi/required-members.golden.json b/testdata/conformance/openapi/required-members.golden.json index 349cc2aa6..baa4128aa 100644 --- a/testdata/conformance/openapi/required-members.golden.json +++ b/testdata/conformance/openapi/required-members.golden.json @@ -74,7 +74,7 @@ }, "properties": [ { - "id": "property/openapi/components/schemas/Either/type/0/properties/id", + "id": "property/openapi/components/schemas/Either/properties/id", "name": { "source": "id", "canonical": "id" @@ -97,7 +97,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/Either/type/0/properties/id" + "pointer": "/components/schemas/Either/properties/id" } } ], diff --git a/testdata/conformance/openapi/scalar-format.golden.json b/testdata/conformance/openapi/scalar-format.golden.json index f948f48e9..79ad375bc 100644 --- a/testdata/conformance/openapi/scalar-format.golden.json +++ b/testdata/conformance/openapi/scalar-format.golden.json @@ -143,6 +143,16 @@ "anonymous": true, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:minLength": { + "reason": "no_ir_home", + "value": 29, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/modified/minLength" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/Holder/properties/modified" @@ -151,10 +161,6 @@ "target": "type/primitive/datetime_offset", "nullable": false }, - "constraints": { - "minLength": 29, - "uniqueItems": false - }, "encoding": { "name": "http-date" } @@ -214,6 +220,16 @@ "anonymous": true, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:minimum": { + "reason": "no_ir_home", + "value": 0, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/resetAt/minimum" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/Holder/properties/resetAt" @@ -222,10 +238,6 @@ "target": "type/primitive/datetime_offset", "nullable": false }, - "constraints": { - "min": "0", - "uniqueItems": false - }, "encoding": { "name": "unixTimestamp", "wireType": { @@ -1308,6 +1320,26 @@ } } }, + "diagnostics": [ + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "minLength bounds the text a value of another kind is written as, not the value its Constraints speak of: a keyword of the text binds only text; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/modified/minLength" + } + }, + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "minimum bounds the number a value of another kind is written as, not the value its Constraints speak of: a bound binds only the kind its node's value is; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Holder/properties/resetAt/minimum" + } + } + ], "sources": [ { "format": "openapi@3.1", diff --git a/testdata/conformance/openapi/silent-applicator.golden.json b/testdata/conformance/openapi/silent-applicator.golden.json new file mode 100644 index 000000000..4ad42d0e2 --- /dev/null +++ b/testdata/conformance/openapi/silent-applicator.golden.json @@ -0,0 +1,371 @@ +{ + "idSpaces": { + "auth": [ + "openapi", + "unresolved" + ], + "enum-member": [ + "anonymous", + "composed", + "openapi" + ], + "operation": [ + "openapi" + ], + "operation-group": [ + "default", + "extension", + "path-prefix", + "tags", + "webhooks" + ], + "parameter": [ + "openapi" + ], + "property": [ + "composed", + "openapi" + ], + "server": [ + "default", + "openapi" + ], + "service": [ + "openapi" + ], + "type": [ + "anonymous", + "composed", + "openapi" + ] + }, + "name": "SilentApplicator", + "version": "1.0.0", + "docs": {}, + "services": [ + { + "id": "service/openapi/0", + "name": { + "source": "SilentApplicator", + "canonical": "silent_applicator" + }, + "docs": {}, + "servers": [ + "server/default" + ], + "provenance": { + "source": 0 + } + } + ], + "types": { + "type/anonymous/components/schemas/Described/items": { + "kind": "scalar", + "id": "type/anonymous/components/schemas/Described/items", + "name": { + "hint": "described_item" + }, + "anonymous": true, + "docs": { + "description": "d" + }, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described/items" + }, + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/openapi/components/schemas/Comment": { + "kind": "scalar", + "id": "type/openapi/components/schemas/Comment", + "name": { + "source": "Comment", + "canonical": "comment" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:items": { + "reason": "degraded_lowering", + "value": { + "$comment": "c" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Comment/items" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Comment" + }, + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/openapi/components/schemas/Described": { + "kind": "list", + "id": "type/openapi/components/schemas/Described", + "name": { + "source": "Described", + "canonical": "described" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Described", + "inferred": "kind-inference" + }, + "elementType": { + "target": "type/anonymous/components/schemas/Described/items", + "nullable": false + } + }, + "type/openapi/components/schemas/Empty": { + "kind": "scalar", + "id": "type/openapi/components/schemas/Empty", + "name": { + "source": "Empty", + "canonical": "empty" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:items": { + "reason": "degraded_lowering", + "value": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Empty/items" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Empty" + }, + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/openapi/components/schemas/EntryComment": { + "kind": "scalar", + "id": "type/openapi/components/schemas/EntryComment", + "name": { + "source": "EntryComment", + "canonical": "entry_comment" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:items": { + "reason": "degraded_lowering", + "value": { + "$comment": "c" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/EntryComment/allOf/0/items" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/EntryComment" + }, + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/openapi/components/schemas/EntryEmpty": { + "kind": "scalar", + "id": "type/openapi/components/schemas/EntryEmpty", + "name": { + "source": "EntryEmpty", + "canonical": "entry_empty" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:items": { + "reason": "degraded_lowering", + "value": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/EntryEmpty/allOf/0/items" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/EntryEmpty" + }, + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/openapi/components/schemas/MapComment": { + "kind": "scalar", + "id": "type/openapi/components/schemas/MapComment", + "name": { + "source": "MapComment", + "canonical": "map_comment" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:additionalProperties": { + "reason": "degraded_lowering", + "value": { + "$comment": "c" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/MapComment/additionalProperties" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/MapComment" + }, + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/openapi/components/schemas/MapEmpty": { + "kind": "scalar", + "id": "type/openapi/components/schemas/MapEmpty", + "name": { + "source": "MapEmpty", + "canonical": "map_empty" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:additionalProperties": { + "reason": "degraded_lowering", + "value": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/MapEmpty/additionalProperties" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/MapEmpty" + }, + "base": { + "target": "type/primitive/any", + "nullable": false + } + }, + "type/primitive/any": { + "kind": "primitive", + "id": "type/primitive/any", + "name": {}, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": -1 + }, + "primitiveKind": "any" + } + }, + "servers": { + "server/default": { + "id": "server/default", + "name": { + "hint": "server" + }, + "urlTemplate": "/", + "description": {}, + "provenance": { + "source": 0 + } + } + }, + "diagnostics": [ + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "this position lowered to a node of kind \"scalar\", which has no home for items declared beside it; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Comment" + } + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "this position lowered to a node of kind \"scalar\", which has no home for items declared beside it; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Empty" + } + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "this position lowered to a node of kind \"scalar\", which has no home for additionalProperties declared beside it; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/MapComment" + } + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "this position lowered to a node of kind \"scalar\", which has no home for additionalProperties declared beside it; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/MapEmpty" + } + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "this allOf lowered to what the keywords beside it say, as no entry of it is the one it lowers from (where they name no kind, the primitive kinds its entries admit together, else the top type), which has no home for items written on this inline entry; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/EntryComment/allOf/0" + } + }, + { + "severity": "info", + "code": "openapi/degraded-construct", + "message": "this allOf lowered to what the keywords beside it say, as no entry of it is the one it lowers from (where they name no kind, the primitive kinds its entries admit together, else the top type), which has no home for items written on this inline entry; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/EntryEmpty/allOf/0" + } + } + ], + "sources": [ + { + "format": "openapi@3.1", + "path": "silent-applicator.yaml", + "hash": "3d9514dd6608a18388c923f4ce44f1b9f7f910141dc20a731d47ea27f872a054" + } + ] +} diff --git a/testdata/conformance/openapi/silent-applicator.yaml b/testdata/conformance/openapi/silent-applicator.yaml new file mode 100644 index 000000000..5f855d771 --- /dev/null +++ b/testdata/conformance/openapi/silent-applicator.yaml @@ -0,0 +1,17 @@ +# An items or additionalProperties holding a schema that writes only +# identifier and meta keywords states nothing of the instances it applies to, +# as one holding {} does: each Comment spelling below lowers as its Empty twin, +# written flat and as an allOf entry. One holding a note still types its +# instances, so Described stays the list it is. +openapi: 3.1.0 +info: {title: SilentApplicator, version: "1.0.0"} +paths: {} +components: + schemas: + Comment: {items: {$comment: c}} + Empty: {items: {}} + MapComment: {additionalProperties: {$comment: c}} + MapEmpty: {additionalProperties: {}} + EntryComment: {allOf: [{items: {$comment: c}}]} + EntryEmpty: {allOf: [{items: {}}]} + Described: {items: {description: d}} diff --git a/testdata/conformance/openapi/tuples-prefixitems.golden.json b/testdata/conformance/openapi/tuples-prefixitems.golden.json index a6954b772..20ebce3e3 100644 --- a/testdata/conformance/openapi/tuples-prefixitems.golden.json +++ b/testdata/conformance/openapi/tuples-prefixitems.golden.json @@ -316,18 +316,6 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:unevaluated": { - "reason": "validation_only", - "value": { - "unevaluatedItems": false - }, - "provenance": { - "source": 0, - "pointer": "/components/schemas/LivePair" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/LivePair" @@ -337,11 +325,7 @@ "target": "type/primitive/string", "nullable": false } - ], - "rest": { - "target": "type/primitive/any", - "nullable": false - } + ] }, "type/openapi/components/schemas/Pair": { "kind": "tuple", @@ -469,15 +453,6 @@ "pointer": "/components/schemas/InertPair" } }, - { - "severity": "info", - "code": "openapi/validation-only-keyword", - "message": "validation-only keyword \"unevaluated\" kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/LivePair" - } - }, { "severity": "info", "code": "openapi/validation-only-keyword", diff --git a/testdata/conformance/openapi/type-array-bounds.golden.json b/testdata/conformance/openapi/type-array-bounds.golden.json index e563e7ac8..b16efdebd 100644 --- a/testdata/conformance/openapi/type-array-bounds.golden.json +++ b/testdata/conformance/openapi/type-array-bounds.golden.json @@ -68,6 +68,16 @@ "anonymous": true, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:minLength": { + "reason": "no_ir_home", + "value": 10, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Dated/minLength" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/Dated/type/1" @@ -75,10 +85,6 @@ "base": { "target": "type/primitive/date", "nullable": false - }, - "constraints": { - "minLength": 10, - "uniqueItems": false } }, "type/anonymous/components/schemas/Holder/properties/either": { @@ -586,6 +592,15 @@ "source": 0, "pointer": "/components/schemas/Untaken" } + }, + { + "severity": "info", + "code": "openapi/unhomed-construct", + "message": "minLength bounds the text a value of another kind is written as, not the value its Constraints speak of: a keyword of the text binds only text; kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Dated/minLength" + } } ], "sources": [ diff --git a/testdata/conformance/openapi/type-array-discriminator.golden.json b/testdata/conformance/openapi/type-array-discriminator.golden.json index d16fd5d59..d41c5f21c 100644 --- a/testdata/conformance/openapi/type-array-discriminator.golden.json +++ b/testdata/conformance/openapi/type-array-discriminator.golden.json @@ -74,7 +74,7 @@ }, "properties": [ { - "id": "property/openapi/components/schemas/Pet/type/0/properties/kind", + "id": "property/openapi/components/schemas/Pet/properties/kind", "name": { "source": "kind", "canonical": "kind" @@ -97,7 +97,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/Pet/type/0/properties/kind" + "pointer": "/components/schemas/Pet/properties/kind" } } ], diff --git a/testdata/conformance/openapi/unevaluated-at-every-outcome.golden.json b/testdata/conformance/openapi/unevaluated-at-every-outcome.golden.json index cad3abfe7..d05dbcc1a 100644 --- a/testdata/conformance/openapi/unevaluated-at-every-outcome.golden.json +++ b/testdata/conformance/openapi/unevaluated-at-every-outcome.golden.json @@ -153,6 +153,98 @@ } ], "types": { + "type/anonymous/components/schemas/Distributed/oneOf/0": { + "kind": "model", + "id": "type/anonymous/components/schemas/Distributed/oneOf/0", + "name": { + "hint": "variant_0" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Distributed/oneOf/0" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Distributed/oneOf/0/properties/t", + "name": { + "source": "t", + "canonical": "t" + }, + "wireName": "t", + "type": { + "target": "type/anonymous/components/schemas/Distributed/oneOf/0/properties/t", + "nullable": false + }, + "required": true, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Distributed/oneOf/0/properties/t" + } + }, + { + "id": "property/openapi/components/schemas/Distributed/oneOf/0/properties/a", + "name": { + "source": "a", + "canonical": "a" + }, + "wireName": "a", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Distributed/oneOf/0/properties/a" + } + } + ], + "abstract": false, + "positional": false, + "inputOnly": false + }, + "type/anonymous/components/schemas/Distributed/oneOf/0/properties/t": { + "kind": "literal", + "id": "type/anonymous/components/schemas/Distributed/oneOf/0/properties/t", + "name": { + "hint": "t" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Distributed/oneOf/0/properties/t" + }, + "value": { + "kind": "string", + "string": "a" + }, + "valueType": "string" + }, "type/anonymous/components/schemas/Distributed/oneOf/1": { "kind": "model", "id": "type/anonymous/components/schemas/Distributed/oneOf/1", @@ -167,6 +259,33 @@ "pointer": "/components/schemas/Distributed/oneOf/1" }, "properties": [ + { + "id": "property/openapi/components/schemas/Distributed/oneOf/1/properties/t", + "name": { + "source": "t", + "canonical": "t" + }, + "wireName": "t", + "type": { + "target": "type/anonymous/components/schemas/Distributed/oneOf/1/properties/t", + "nullable": false + }, + "required": true, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Distributed/oneOf/1/properties/t" + } + }, { "id": "property/openapi/components/schemas/Distributed/oneOf/1/properties/b", "name": { @@ -199,6 +318,25 @@ "positional": false, "inputOnly": false }, + "type/anonymous/components/schemas/Distributed/oneOf/1/properties/t": { + "kind": "literal", + "id": "type/anonymous/components/schemas/Distributed/oneOf/1/properties/t", + "name": { + "hint": "t" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Distributed/oneOf/1/properties/t" + }, + "value": { + "kind": "string", + "string": "b" + }, + "valueType": "string" + }, "type/anonymous/components/schemas/Holder/properties/list": { "kind": "list", "id": "type/anonymous/components/schemas/Holder/properties/list", @@ -262,7 +400,7 @@ }, "properties": [ { - "id": "property/openapi/components/schemas/ObjectVariant/type/0/properties/a", + "id": "property/openapi/components/schemas/ObjectVariant/properties/a", "name": { "source": "a", "canonical": "a" @@ -285,7 +423,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/ObjectVariant/type/0/properties/a" + "pointer": "/components/schemas/ObjectVariant/properties/a" } } ], @@ -294,11 +432,57 @@ "positional": false, "inputOnly": false }, + "type/anonymous/components/schemas/Overlapping/oneOf/1": { + "kind": "model", + "id": "type/anonymous/components/schemas/Overlapping/oneOf/1", + "name": { + "hint": "variant_1" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping/oneOf/1" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Overlapping/oneOf/1/properties/b", + "name": { + "source": "b", + "canonical": "b" + }, + "wireName": "b", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping/oneOf/1/properties/b" + } + } + ], + "abstract": false, + "positional": false, + "inputOnly": false + }, "type/composed/components/schemas/Distributed/oneOf/0": { "kind": "model", "id": "type/composed/components/schemas/Distributed/oneOf/0", "name": { - "hint": "distributed_closed" + "hint": "distributed_variant_0" }, "anonymous": true, "docs": {}, @@ -337,7 +521,7 @@ } ], "base": { - "target": "type/openapi/components/schemas/Closed", + "target": "type/anonymous/components/schemas/Distributed/oneOf/0", "nullable": false }, "additional": "closed_after_composition", @@ -396,6 +580,106 @@ "positional": false, "inputOnly": false }, + "type/composed/components/schemas/Overlapping/oneOf/0": { + "kind": "model", + "id": "type/composed/components/schemas/Overlapping/oneOf/0", + "name": { + "hint": "overlapping_closed" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping/oneOf/0" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Overlapping/properties/k", + "name": { + "source": "k", + "canonical": "k" + }, + "wireName": "k", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping/properties/k" + } + } + ], + "base": { + "target": "type/openapi/components/schemas/Closed", + "nullable": false + }, + "abstract": false, + "positional": false, + "inputOnly": false + }, + "type/composed/components/schemas/Overlapping/oneOf/1": { + "kind": "model", + "id": "type/composed/components/schemas/Overlapping/oneOf/1", + "name": { + "hint": "overlapping_variant_1" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping/oneOf/1" + }, + "properties": [ + { + "id": "property/openapi/components/schemas/Overlapping/properties/k", + "name": { + "source": "k", + "canonical": "k" + }, + "wireName": "k", + "type": { + "target": "type/primitive/string", + "nullable": false + }, + "required": false, + "clientOptional": false, + "defaultAdded": false, + "visibility": { + "invisibleInEveryLifecycle": false + }, + "flatten": false, + "eventHeader": false, + "eventPayload": false, + "secret": false, + "docs": {}, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping/properties/k" + } + } + ], + "base": { + "target": "type/anonymous/components/schemas/Overlapping/oneOf/1", + "nullable": false + }, + "abstract": false, + "positional": false, + "inputOnly": false + }, "type/openapi/components/schemas/Alias": { "kind": "scalar", "id": "type/openapi/components/schemas/Alias", @@ -618,12 +902,13 @@ "sensitive": false, "provenance": { "source": 0, - "pointer": "/components/schemas/Distributed" + "pointer": "/components/schemas/Distributed", + "inferred": "discriminator-inference" }, "variants": [ { "name": { - "hint": "closed" + "hint": "variant_0" }, "type": { "target": "type/composed/components/schemas/Distributed/oneOf/0", @@ -643,7 +928,15 @@ } ], "exclusive": true, - "wireTagged": false, + "wireTagged": true, + "discriminator": { + "propertyName": "t", + "mapping": { + "a": "type/composed/components/schemas/Distributed/oneOf/0", + "b": "type/composed/components/schemas/Distributed/oneOf/1" + }, + "inferred": true + }, "closed": true, "inputOnly": false }, @@ -960,6 +1253,59 @@ "closed": true, "inputOnly": false }, + "type/openapi/components/schemas/Overlapping": { + "kind": "union", + "id": "type/openapi/components/schemas/Overlapping", + "name": { + "source": "Overlapping", + "canonical": "overlapping" + }, + "anonymous": false, + "docs": {}, + "sensitive": false, + "unmodeled": { + "openapi:unevaluated": { + "reason": "validation_only", + "value": { + "unevaluatedProperties": false + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping" + } + } + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping" + }, + "variants": [ + { + "name": { + "hint": "closed" + }, + "type": { + "target": "type/composed/components/schemas/Overlapping/oneOf/0", + "nullable": false + }, + "docs": {} + }, + { + "name": { + "hint": "variant_1" + }, + "type": { + "target": "type/composed/components/schemas/Overlapping/oneOf/1", + "nullable": false + }, + "docs": {} + } + ], + "exclusive": true, + "wireTagged": false, + "closed": true, + "inputOnly": false + }, "type/openapi/components/schemas/Paired": { "kind": "tuple", "id": "type/openapi/components/schemas/Paired", @@ -1141,6 +1487,24 @@ "pointer": "/components/schemas/Distributed" } }, + { + "severity": "info", + "code": "openapi/composition-lowering", + "message": "oneOf/anyOf co-declared with structural keywords; the composition is distributed across the union variants", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping" + } + }, + { + "severity": "info", + "code": "openapi/validation-only-keyword", + "message": "validation-only keyword \"unevaluated\" kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Overlapping" + } + }, { "severity": "info", "code": "openapi/validation-only-keyword", @@ -1222,6 +1586,15 @@ "pointer": "/components/schemas/Anything" } }, + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the type and every allOf entry (type: object, allOf/0: no value); lowered as a node of kind \"model\" — remove or correct one of them", + "provenance": { + "source": 0, + "pointer": "/components/schemas/ClosedByABranch" + } + }, { "severity": "info", "code": "openapi/false-schema", @@ -1281,7 +1654,7 @@ { "format": "openapi@3.1", "path": "unevaluated-at-every-outcome.yaml", - "hash": "9672532323afaa93ad1d7d11a32f00c382bd45ee1d935384ba247f618ce1038f" + "hash": "184084862d56c716858e44027b929a46c46a0b4187507ae731633e1b9184993c" } ] } diff --git a/testdata/conformance/openapi/unevaluated-at-every-outcome.yaml b/testdata/conformance/openapi/unevaluated-at-every-outcome.yaml index f3d36db57..669089ff8 100644 --- a/testdata/conformance/openapi/unevaluated-at-every-outcome.yaml +++ b/testdata/conformance/openapi/unevaluated-at-every-outcome.yaml @@ -23,7 +23,17 @@ components: type: [object, string] properties: {a: {type: string}} unevaluatedProperties: false + # A distributed oneOf closes only where its branches require disjoint + # tags: one whose branches may both match is kept, as the closure alone + # refuses an instance matching both. Distributed: + type: object + properties: {k: {type: string}} + oneOf: + - {type: object, properties: {t: {const: a}, a: {type: string}}, required: [t]} + - {type: object, properties: {t: {const: b}, b: {type: string}}, required: [t]} + unevaluatedProperties: false + Overlapping: type: object properties: {k: {type: string}} oneOf: diff --git a/testdata/conformance/openapi/unhomed-keywords.golden.json b/testdata/conformance/openapi/unhomed-keywords.golden.json index a02f55086..f430ad8eb 100644 --- a/testdata/conformance/openapi/unhomed-keywords.golden.json +++ b/testdata/conformance/openapi/unhomed-keywords.golden.json @@ -59,6 +59,27 @@ } ], "types": { + "type/anonymous/components/schemas/RefCarrier/properties/p": { + "kind": "scalar", + "id": "type/anonymous/components/schemas/RefCarrier/properties/p", + "name": { + "hint": "p" + }, + "anonymous": true, + "docs": {}, + "sensitive": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/RefCarrier/properties/p" + }, + "base": { + "target": "type/openapi/components/schemas/RefTargetStr", + "nullable": false + }, + "encoding": { + "name": "email" + } + }, "type/openapi/components/schemas/AllOfWithObjectType": { "kind": "model", "id": "type/openapi/components/schemas/AllOfWithObjectType", @@ -92,6 +113,17 @@ "docs": {}, "sensitive": false, "unmodeled": { + "openapi:$ref": { + "reason": "degraded_lowering", + "value": "#/components/schemas/RefTargetObj", + "targets": { + "": "type/openapi/components/schemas/RefTargetObj" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/AllOfWithScalarType/allOf/0" + } + }, "openapi:type": { "reason": "degraded_lowering", "value": "string", @@ -105,10 +137,7 @@ "source": 0, "pointer": "/components/schemas/AllOfWithScalarType" }, - "base": { - "target": "type/openapi/components/schemas/RefTargetObj", - "nullable": false - }, + "additional": "closed", "abstract": false, "positional": false, "inputOnly": false @@ -400,6 +429,16 @@ "anonymous": false, "docs": {}, "sensitive": false, + "unmodeled": { + "openapi:additionalProperties": { + "reason": "degraded_lowering", + "value": false, + "provenance": { + "source": 0, + "pointer": "/components/schemas/RefAdditionalProperties/additionalProperties" + } + } + }, "provenance": { "source": 0, "pointer": "/components/schemas/RefAdditionalProperties" @@ -436,7 +475,7 @@ }, "wireName": "p", "type": { - "target": "type/openapi/components/schemas/RefTargetStr", + "target": "type/anonymous/components/schemas/RefCarrier/properties/p", "nullable": false }, "required": false, @@ -450,16 +489,6 @@ "eventPayload": false, "secret": false, "docs": {}, - "unmodeled": { - "openapi:format": { - "reason": "degraded_lowering", - "value": "email", - "provenance": { - "source": 0, - "pointer": "/components/schemas/RefCarrier/properties/p/format" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/RefCarrier/properties/p" @@ -550,6 +579,9 @@ "positional": false, "discriminator": { "propertyName": "a", + "mapping": { + "RefDiscriminator": "type/openapi/components/schemas/RefDiscriminator" + }, "inferred": false }, "inputOnly": false @@ -621,16 +653,6 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:format": { - "reason": "degraded_lowering", - "value": "email", - "provenance": { - "source": 0, - "pointer": "/components/schemas/RefFormat/format" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/RefFormat" @@ -638,6 +660,9 @@ "base": { "target": "type/openapi/components/schemas/RefTargetStr", "nullable": false + }, + "encoding": { + "name": "email" } }, "type/openapi/components/schemas/RefRequired": { @@ -989,7 +1014,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"primitive\", which has no home for required declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"scalar\", which has no home for required declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/UntypedRequired" @@ -998,7 +1023,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"primitive\", which has no home for format declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"scalar\", which has no home for format declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/UntypedFormat" @@ -1007,7 +1032,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"primitive\", which has no home for discriminator declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"scalar\", which has no home for discriminator declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/UntypedDiscriminator" @@ -1025,7 +1050,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"primitive\", which has no home for properties declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"scalar\", which has no home for properties declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/ScalarWithProperties" @@ -1043,7 +1068,7 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"primitive\", which has no home for items declared beside it; kept verbatim under Unmodeled", + "message": "this position lowered to a node of kind \"scalar\", which has no home for items declared beside it; kept verbatim under Unmodeled", "provenance": { "source": 0, "pointer": "/components/schemas/UnionWithItems" @@ -1058,15 +1083,6 @@ "pointer": "/components/schemas/UnionWithItems" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this position lowered to a use of one of its conjuncts, which has no home for format declared beside it; kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/RefFormat" - } - }, { "severity": "info", "code": "openapi/degraded-construct", @@ -1088,25 +1104,16 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this position lowered to a use of one of its conjuncts, which has no home for format declared beside it; kept verbatim under Unmodeled", + "message": "additionalProperties also applies to a, which the composition brings and its own object does not declare; the model takes it as the closed subtype written, and it is kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/RefCarrier/properties/p" + "pointer": "/components/schemas/RefAdditionalProperties/additionalProperties" } }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this allOf share no value (type: string, allOf/0: object), so no instance satisfies this schema, which a composition cannot state", - "provenance": { - "source": 0, - "pointer": "/components/schemas/AllOfWithScalarType" - } - }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this position lowered to a node of kind \"model\", which has no home for type declared beside it; kept verbatim under Unmodeled", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the type and every allOf entry (type: string, allOf/0: object); lowered as the closed model with no member a false schema lowers to — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/AllOfWithScalarType" @@ -1135,7 +1142,7 @@ { "format": "openapi@3.1", "path": "unhomed-keywords.yaml", - "hash": "157121e1a29447c90d4ee6f9919ab4e55d35fa9d2e75bd8f911011adfa783cdf" + "hash": "b7196d27d932b97e5bce05198a6a307bcba8f06fbe81168ad805401e0310356b" } ] } diff --git a/testdata/conformance/openapi/unhomed-keywords.yaml b/testdata/conformance/openapi/unhomed-keywords.yaml index 6fc6c5b86..08231ac7d 100644 --- a/testdata/conformance/openapi/unhomed-keywords.yaml +++ b/testdata/conformance/openapi/unhomed-keywords.yaml @@ -53,9 +53,11 @@ components: items: {type: string} # In JSON Schema 2020-12 — and so in OpenAPI 3.1 — $ref is an ordinary # keyword and what stands beside it is conjoined with it. The position - # lowers to an alias over the target, which has no member set, no value, no - # property set and no encoding of its own, so each of these reached no IR - # field: the $ref path kept no keyword unread at all until it kept them as the body path does. + # lowers to an alias over the target, which has no member set, no value and + # no property set of its own, so each of these reached no IR field: the + # $ref path kept no keyword unread at all until it kept them as the body + # path does. A format selecting no primitive restricts the alias with its + # Encoding, as the flat spelling's Scalar carries one. # Declared above their targets on purpose: an alias hoisted at a pointer # another declaration can also reach must not depend on which arrives first. RefFormat: {$ref: '#/components/schemas/RefTargetStr', format: email} @@ -67,8 +69,8 @@ components: # The control: a bound and a description at the identical position always # reached the alias's own fields, so neither may acquire an entry now. RefConstrained: {$ref: '#/components/schemas/RefTargetStr', minLength: 3, description: kept} - # The same keeping at a carrier, which keeps them on itself rather than - # hoisting a node: a property's $ref resolves straight to the target. + # The same at a carrier: the restriction stands on a node of the + # property's own, which carries the Encoding. RefCarrier: type: object properties: diff --git a/testdata/conformance/openapi/union-beside-ref.golden.json b/testdata/conformance/openapi/union-beside-ref.golden.json index ff7cae68e..68bec7c6e 100644 --- a/testdata/conformance/openapi/union-beside-ref.golden.json +++ b/testdata/conformance/openapi/union-beside-ref.golden.json @@ -280,12 +280,25 @@ "docs": {}, "sensitive": false, "unmodeled": { - "openapi:type": { + "openapi:$ref": { "reason": "degraded_lowering", - "value": "string", + "value": "#/components/schemas/Base", + "targets": { + "": "type/openapi/components/schemas/Base" + }, "provenance": { "source": 0, - "pointer": "/components/schemas/I/allOf/0/type" + "pointer": "/components/schemas/I" + } + }, + "openapi:allOf/0": { + "reason": "degraded_lowering", + "value": { + "type": "string" + }, + "provenance": { + "source": 0, + "pointer": "/components/schemas/I/allOf/0" } } }, @@ -293,10 +306,7 @@ "source": 0, "pointer": "/components/schemas/I" }, - "base": { - "target": "type/openapi/components/schemas/Base", - "nullable": false - }, + "additional": "closed", "abstract": false, "positional": false, "inputOnly": false @@ -330,17 +340,8 @@ "diagnostics": [ { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this schema share no value (oneOf: string or integer, $ref: object), so no instance satisfies this schema, which a composition cannot state", - "provenance": { - "source": 0, - "pointer": "/components/schemas/G" - } - }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and none of its branches shares a kind with the allOf beside it, so no instance satisfies them together; union branches kept verbatim under Unmodeled", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the $ref and the oneOf ($ref: object, oneOf: string or integer); lowered as a node of kind \"model\", its oneOf kept verbatim under Unmodeled — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/G" @@ -348,17 +349,8 @@ }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this schema share no value (anyOf: string or integer, $ref: object), so no instance satisfies this schema, which a composition cannot state", - "provenance": { - "source": 0, - "pointer": "/components/schemas/H" - } - }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and none of its branches shares a kind with the allOf beside it, so no instance satisfies them together; union branches kept verbatim under Unmodeled", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the $ref and the anyOf ($ref: object, anyOf: string or integer); lowered as a node of kind \"model\", its anyOf kept verbatim under Unmodeled — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/H" @@ -366,35 +358,17 @@ }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this schema share no value ($ref: object, allOf/0: string), so no instance satisfies this schema, which a composition cannot state", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the $ref and every allOf entry ($ref: object, allOf/0: string); lowered as the closed model with no member a false schema lowers to — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/I" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this allOf lowered to a node of kind \"model\", which has no home for type written on this inline entry; kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/I/allOf/0" - } - }, { "severity": "warning", - "code": "openapi/degraded-construct", - "message": "the conjuncts of this schema share no value (oneOf: string or integer, $ref: object), so no instance satisfies this schema, which a composition cannot state", - "provenance": { - "source": 0, - "pointer": "/components/schemas/Carrier/properties/p" - } - }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and none of its branches shares a kind with the allOf beside it, so no instance satisfies them together; union branches kept verbatim under Unmodeled", + "code": "openapi/unsatisfiable-schema", + "message": "no value satisfies both the $ref and the oneOf ($ref: object, oneOf: string or integer); lowered as a node of kind \"model\", its oneOf kept verbatim under Unmodeled — remove or correct one of them", "provenance": { "source": 0, "pointer": "/components/schemas/Carrier/properties/p" diff --git a/testdata/conformance/openapi/union-joined-value-sets.golden.json b/testdata/conformance/openapi/union-joined-value-sets.golden.json index 5fe842c23..86a21e5a9 100644 --- a/testdata/conformance/openapi/union-joined-value-sets.golden.json +++ b/testdata/conformance/openapi/union-joined-value-sets.golden.json @@ -59,404 +59,8 @@ } ], "types": { - "type/anonymous/components/schemas/Many/allOf/0/oneOf/0": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/0", - "name": { - "hint": "variant_0" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/0" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/0/string:v1", - "name": { - "source": "v1", - "canonical": "v_1" - }, - "value": { - "kind": "string", - "string": "v1" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/1": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/1", - "name": { - "hint": "variant_1" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/1" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/1/string:v2", - "name": { - "source": "v2", - "canonical": "v_2" - }, - "value": { - "kind": "string", - "string": "v2" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/2": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/2", - "name": { - "hint": "variant_2" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/2" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/2/string:v3", - "name": { - "source": "v3", - "canonical": "v_3" - }, - "value": { - "kind": "string", - "string": "v3" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/3": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/3", - "name": { - "hint": "variant_3" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/3" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/3/string:v4", - "name": { - "source": "v4", - "canonical": "v_4" - }, - "value": { - "kind": "string", - "string": "v4" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/4": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/4", - "name": { - "hint": "variant_4" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/4" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/4/string:v5", - "name": { - "source": "v5", - "canonical": "v_5" - }, - "value": { - "kind": "string", - "string": "v5" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/5": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/5", - "name": { - "hint": "variant_5" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/5" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/5/string:v6", - "name": { - "source": "v6", - "canonical": "v_6" - }, - "value": { - "kind": "string", - "string": "v6" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/6": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/6", - "name": { - "hint": "variant_6" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/6" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/6/string:v7", - "name": { - "source": "v7", - "canonical": "v_7" - }, - "value": { - "kind": "string", - "string": "v7" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/7": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/7", - "name": { - "hint": "variant_7" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/7" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/7/string:v8", - "name": { - "source": "v8", - "canonical": "v_8" - }, - "value": { - "kind": "string", - "string": "v8" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/8": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/8", - "name": { - "hint": "variant_8" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/8" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/8/string:v9", - "name": { - "source": "v9", - "canonical": "v_9" - }, - "value": { - "kind": "string", - "string": "v9" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Many/allOf/0/oneOf/9": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Many/allOf/0/oneOf/9", - "name": { - "hint": "variant_9" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/0/oneOf/9" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Many/allOf/0/oneOf/9/string:v10", - "name": { - "source": "v10", - "canonical": "v_10" - }, - "value": { - "kind": "string", - "string": "v10" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Shared/allOf/0/anyOf/0": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Shared/allOf/0/anyOf/0", - "name": { - "hint": "variant_0" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Shared/allOf/0/anyOf/0" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Shared/allOf/0/anyOf/0/string:a", - "name": { - "source": "a", - "canonical": "a" - }, - "value": { - "kind": "string", - "string": "a" - }, - "docs": {} - }, - { - "id": "enum-member/anonymous/components/schemas/Shared/allOf/0/anyOf/0/string:b", - "name": { - "source": "b", - "canonical": "b" - }, - "value": { - "kind": "string", - "string": "b" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, - "type/anonymous/components/schemas/Shared/allOf/0/anyOf/1": { - "kind": "enum", - "id": "type/anonymous/components/schemas/Shared/allOf/0/anyOf/1", - "name": { - "hint": "variant_1" - }, - "anonymous": true, - "docs": {}, - "sensitive": false, - "provenance": { - "source": 0, - "pointer": "/components/schemas/Shared/allOf/0/anyOf/1" - }, - "valueType": "string", - "members": [ - { - "id": "enum-member/anonymous/components/schemas/Shared/allOf/0/anyOf/1/string:b", - "name": { - "source": "b", - "canonical": "b" - }, - "value": { - "kind": "string", - "string": "b" - }, - "docs": {} - }, - { - "id": "enum-member/anonymous/components/schemas/Shared/allOf/0/anyOf/1/string:c", - "name": { - "source": "c", - "canonical": "c" - }, - "value": { - "kind": "string", - "string": "c" - }, - "docs": {} - } - ], - "closed": true, - "flags": false - }, "type/openapi/components/schemas/Many": { - "kind": "union", + "kind": "enum", "id": "type/openapi/components/schemas/Many", "name": { "source": "Many", @@ -476,118 +80,88 @@ "source": 0, "pointer": "/components/schemas/Many/allOf/1/enum" } + }, + "openapi:oneOf": { + "reason": "degraded_lowering", + "value": [ + { + "enum": [ + "v1" + ] + }, + { + "enum": [ + "v2" + ] + }, + { + "enum": [ + "v3" + ] + }, + { + "enum": [ + "v4" + ] + }, + { + "enum": [ + "v5" + ] + }, + { + "enum": [ + "v6" + ] + }, + { + "enum": [ + "v7" + ] + }, + { + "enum": [ + "v8" + ] + }, + { + "enum": [ + "v9" + ] + }, + { + "enum": [ + "v10" + ] + } + ], + "provenance": { + "source": 0, + "pointer": "/components/schemas/Many/allOf/0/oneOf" + } } }, "provenance": { "source": 0, "pointer": "/components/schemas/Many" }, - "variants": [ - { - "name": { - "hint": "variant_0" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/0", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_1" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/1", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_2" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/2", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_3" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/3", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_4" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/4", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_5" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/5", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_6" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/6", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_7" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/7", - "nullable": false - }, - "docs": {} - }, - { - "name": { - "hint": "variant_8" - }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/8", - "nullable": false - }, - "docs": {} - }, + "valueType": "string", + "members": [ { + "id": "enum-member/openapi/components/schemas/Many/string:v3", "name": { - "hint": "variant_9" + "source": "v3", + "canonical": "v_3" }, - "type": { - "target": "type/anonymous/components/schemas/Many/allOf/0/oneOf/9", - "nullable": false + "value": { + "kind": "string", + "string": "v3" }, "docs": {} } ], - "exclusive": true, - "wireTagged": false, "closed": true, - "inputOnly": false + "flags": false }, "type/openapi/components/schemas/Nested": { "kind": "enum", @@ -599,41 +173,6 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:anyOf": { - "reason": "degraded_lowering", - "value": [ - { - "enum": [ - "s1", - "s2", - "s3", - "s4", - "s5" - ] - }, - { - "anyOf": [ - { - "enum": [ - "p", - "q" - ] - }, - { - "enum": [ - "s1" - ] - } - ] - } - ], - "provenance": { - "source": 0, - "pointer": "/components/schemas/Nested/allOf/0/anyOf" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/Nested" @@ -669,7 +208,7 @@ "flags": false }, "type/openapi/components/schemas/Shared": { - "kind": "union", + "kind": "enum", "id": "type/openapi/components/schemas/Shared", "name": { "source": "Shared", @@ -695,32 +234,23 @@ "source": 0, "pointer": "/components/schemas/Shared" }, - "variants": [ - { - "name": { - "hint": "variant_0" - }, - "type": { - "target": "type/anonymous/components/schemas/Shared/allOf/0/anyOf/0", - "nullable": false - }, - "docs": {} - }, + "valueType": "string", + "members": [ { + "id": "enum-member/openapi/components/schemas/Shared/string:b", "name": { - "hint": "variant_1" + "source": "b", + "canonical": "b" }, - "type": { - "target": "type/anonymous/components/schemas/Shared/allOf/0/anyOf/1", - "nullable": false + "value": { + "kind": "string", + "string": "b" }, "docs": {} } ], - "exclusive": false, - "wireTagged": false, "closed": true, - "inputOnly": false + "flags": false } }, "servers": { @@ -740,28 +270,19 @@ { "severity": "info", "code": "openapi/degraded-construct", - "message": "this allOf lowered to a node of kind \"union\", which has no home for enum written on this inline entry; kept verbatim under Unmodeled", + "message": "this allOf lowered to a node of kind \"enum\", which has no home for oneOf written on this inline entry; kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/Shared/allOf/1" + "pointer": "/components/schemas/Many/allOf/0" } }, { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this allOf lowered to a node of kind \"union\", which has no home for enum written on this inline entry; kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/Many/allOf/1" - } - }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "this allOf lowered to a node of kind \"enum\", which has no home for anyOf written on this inline entry; kept verbatim under Unmodeled", + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "9 of the 10 branches of this oneOf share no value with the rest of the schema (oneOf/0: enum [\"v1\"], oneOf/1: enum [\"v2\"], oneOf/3: enum [\"v4\"], oneOf/4: enum [\"v5\"], oneOf/5: enum [\"v6\"], oneOf/6: enum [\"v7\"], oneOf/7: enum [\"v8\"], oneOf/8: enum [\"v9\"], oneOf/9: enum [\"v10\"]), so no instance satisfies them: the oneOf is kept verbatim under Unmodeled", "provenance": { "source": 0, - "pointer": "/components/schemas/Nested/allOf/0" + "pointer": "/components/schemas/Many/allOf/0/oneOf" } } ], diff --git a/testdata/conformance/openapi/union-restated-branches.golden.json b/testdata/conformance/openapi/union-restated-branches.golden.json index 9d9245f4f..4d25e7068 100644 --- a/testdata/conformance/openapi/union-restated-branches.golden.json +++ b/testdata/conformance/openapi/union-restated-branches.golden.json @@ -1321,7 +1321,7 @@ "inputOnly": false }, "type/openapi/components/schemas/RenderFormats": { - "kind": "scalar", + "kind": "union", "id": "type/openapi/components/schemas/RenderFormats", "name": { "source": "RenderFormats", @@ -1330,31 +1330,36 @@ "anonymous": false, "docs": {}, "sensitive": false, - "unmodeled": { - "openapi:oneOf": { - "reason": "degraded_lowering", - "value": [ - { - "format": "date" - }, - { - "format": "uri" - } - ], - "provenance": { - "source": 0, - "pointer": "/components/schemas/RenderFormats/oneOf" - } - } - }, "provenance": { "source": 0, "pointer": "/components/schemas/RenderFormats" }, - "base": { - "target": "type/primitive/string", - "nullable": false - } + "variants": [ + { + "name": { + "hint": "variant_0" + }, + "type": { + "target": "type/primitive/date", + "nullable": false + }, + "docs": {} + }, + { + "name": { + "hint": "variant_1" + }, + "type": { + "target": "type/primitive/url", + "nullable": false + }, + "docs": {} + } + ], + "exclusive": true, + "wireTagged": false, + "closed": true, + "inputOnly": false }, "type/openapi/components/schemas/RenderJoint": { "kind": "model", @@ -1412,7 +1417,7 @@ }, "properties": [ { - "id": "property/openapi/components/schemas/RenderJoint/allOf/0/properties/kind", + "id": "property/openapi/components/schemas/RenderJoint/properties/kind", "name": { "source": "kind", "canonical": "kind" @@ -1435,7 +1440,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/RenderJoint/allOf/0/properties/kind" + "pointer": "/components/schemas/RenderJoint/properties/kind" } }, { @@ -1527,7 +1532,8 @@ }, "provenance": { "source": 0, - "pointer": "/components/schemas/RenderSelf" + "pointer": "/components/schemas/RenderSelf", + "inferred": "kind-inference" }, "properties": [ { @@ -1675,6 +1681,18 @@ "closed": true, "inputOnly": false }, + "type/primitive/date": { + "kind": "primitive", + "id": "type/primitive/date", + "name": {}, + "anonymous": false, + "docs": {}, + "sensitive": false, + "provenance": { + "source": -1 + }, + "primitiveKind": "date" + }, "type/primitive/integer": { "kind": "primitive", "id": "type/primitive/integer", @@ -1798,15 +1816,6 @@ "pointer": "/components/schemas/RenderComposed" } }, - { - "severity": "info", - "code": "openapi/degraded-construct", - "message": "oneOf/anyOf co-declared with structural keywords intersects with them, and the body is not a model, so it carries no composition to distribute into; union branches kept verbatim under Unmodeled", - "provenance": { - "source": 0, - "pointer": "/components/schemas/RenderFormats" - } - }, { "severity": "info", "code": "openapi/validation-only-keyword", @@ -1839,7 +1848,7 @@ { "format": "openapi@3.1", "path": "union-restated-branches.yaml", - "hash": "c1f848e936c2280484a121fd6eeca4003bc0d8fb203e49d2ee263227548d42ab" + "hash": "a332dce5817e1ca2da7ebd0c5c6d555d122a14060693f3ae8b8972b0564d76c0" } ] } diff --git a/testdata/conformance/openapi/union-restated-branches.yaml b/testdata/conformance/openapi/union-restated-branches.yaml index a64c2f472..0ca41f079 100644 --- a/testdata/conformance/openapi/union-restated-branches.yaml +++ b/testdata/conformance/openapi/union-restated-branches.yaml @@ -86,7 +86,8 @@ components: type: array oneOf: [{items: {type: string}}, {items: {type: integer}}] # A branch writing a format says more than the body and no kind of its - # own, so the union degrades, here beside a body that is no model. + # own, so beside a body that is no model the branches conjoin with it: a + # Union of the encodings. RenderFormats: type: string oneOf: [{format: date}, {format: uri}] @@ -112,9 +113,10 @@ components: - required: [links] properties: links: {allOf: [{$ref: '#/components/schemas/RenderLinks'}, {type: array, minItems: 1, items: {minLength: 1}}]} - # A body composing itself is a cycle no reading of what it composes - # finishes, but these branches restate only what the body itself writes, - # which its own reading settles, so the union is validation logic still. + # A body composing itself is a loop, which admits every kind, so its own + # keywords decide and the self-reference is kept with one report; these + # branches restate only what the body writes, so the union is validation + # logic still. RenderSelf: allOf: [{$ref: '#/components/schemas/RenderSelf'}] properties: {html: {type: string}, url: {type: string}} diff --git a/testdata/conformance/openapi/union-restated-type.golden.json b/testdata/conformance/openapi/union-restated-type.golden.json index 3b419c387..ad96952c3 100644 --- a/testdata/conformance/openapi/union-restated-type.golden.json +++ b/testdata/conformance/openapi/union-restated-type.golden.json @@ -539,6 +539,15 @@ "source": 0, "pointer": "/components/schemas/Mixed" } + }, + { + "severity": "warning", + "code": "openapi/unsatisfiable-schema", + "message": "1 of the 2 branches of this oneOf shares no value with the rest of the schema (oneOf/1: number), so no instance satisfies it: the oneOf is kept verbatim under Unmodeled", + "provenance": { + "source": 0, + "pointer": "/components/schemas/Mixed/oneOf" + } } ], "sources": [ diff --git a/testdata/golden/openapi/hint_positions.golden.json b/testdata/golden/openapi/hint_positions.golden.json index c728a95b3..e37f0a897 100644 --- a/testdata/golden/openapi/hint_positions.golden.json +++ b/testdata/golden/openapi/hint_positions.golden.json @@ -3379,7 +3379,7 @@ }, "properties": [ { - "id": "property/openapi/components/schemas/Positions/properties/multiTypedObject/type/0/properties/w", + "id": "property/openapi/components/schemas/Positions/properties/multiTypedObject/properties/w", "name": { "source": "w", "canonical": "w" @@ -3402,7 +3402,7 @@ "docs": {}, "provenance": { "source": 0, - "pointer": "/components/schemas/Positions/properties/multiTypedObject/type/0/properties/w" + "pointer": "/components/schemas/Positions/properties/multiTypedObject/properties/w" } } ], @@ -6515,6 +6515,7 @@ "discriminator": { "property": "property/openapi/components/schemas/Kennel/properties/kind", "mapping": { + "Kennel": "type/openapi/components/schemas/Kennel", "routed": "type/anonymous/components/schemas/Positions/properties/routed", "routedBranch": "type/anonymous/components/schemas/Positions/properties/routedBranch" }, diff --git a/testdata/openapi/allof_redeclared_ref_declared_later.yaml b/testdata/openapi/allof_redeclared_ref_declared_later.yaml index 985b11b86..060062d85 100644 --- a/testdata/openapi/allof_redeclared_ref_declared_later.yaml +++ b/testdata/openapi/allof_redeclared_ref_declared_later.yaml @@ -5,8 +5,9 @@ # merged type and the declaration kept beside it must not follow the order the # components are declared in # (docs/compilers/openapi.md#allof-redeclared-property). `same` pairs two -# named enums declared alike, and `overlap` two named scalars, over number and -# over integer, which the merge does not narrow (#1042): it reports each pair +# named enums declared alike, one type, the field naming the least and keeping +# the other's declaration with an info, and `overlap` two named scalars, over +# number and over integer, which the merge does not narrow (#1042) and reports # as an overlap. openapi: 3.0.3 info: diff --git a/testdata/openapi/value_set_refused_across_entries.yaml b/testdata/openapi/value_set_refused_across_entries.yaml new file mode 100644 index 000000000..054316eea --- /dev/null +++ b/testdata/openapi/value_set_refused_across_entries.yaml @@ -0,0 +1,39 @@ +# A value set split over allOf entries beside a oneOf that refuses a member +# both entries write, the same set beside a union a $ref names, and a set two +# $ref'd unions refuse members of. The refused members are reported once, at +# the schema, wherever the set and the unions are written, so reversing the +# allOf entries moves no report +# (docs/compilers/openapi.md#union-beside-structure). +openapi: 3.1.0 +info: + title: Value set refused across entries + version: 1.0.0 +paths: {} +components: + schemas: + Numbers: + oneOf: + - type: integer + - type: number + AtLeastTwo: + anyOf: + - type: number + minimum: 2 + - type: boolean + Split: + oneOf: + - type: integer + - type: number + allOf: + - enum: [1, 1.5] + - enum: [1, 1.5, 2] + Referenced: + allOf: + - $ref: '#/components/schemas/Numbers' + - enum: [1, 1.5] + - enum: [1, 1.5, 2] + TwoUnions: + enum: [1, 1.5, 2.5] + allOf: + - $ref: '#/components/schemas/AtLeastTwo' + - $ref: '#/components/schemas/Numbers'